(function outer(modules, cache, entry) {
  var previousRequire = "function" == typeof require && require;
  function newRequire(name, jumped) {
    var module = cache[name];
    if (!module) {
      var moduleData = modules[name];
      if (!moduleData) {
        var currentRequire = "function" == typeof require && require;
        if (!jumped && currentRequire) return currentRequire(name, true);
        if (previousRequire) return previousRequire(name, true);
        var err = new Error("Cannot find module '" + name + "'");
        err.code = "MODULE_NOT_FOUND";
        throw err;
      }
      var exports = {};
      module = cache[name] = {
        exports: exports
      };
      moduleData[0]((function(x) {
        return newRequire(moduleData[1][x] || x);
      }), module, exports);
    }
    return module.exports;
  }
  for (var i = 0; i < entry.length; i++) newRequire(entry[i]);
  return newRequire;
})({
  1: [ (function(require, module, exports) {
    cc._LogInfos = cc._LogInfos || {};
    var engineVersion;
    engineVersion = "1.8.2-rc.2";
    window["CocosEngine"] = cc.ENGINE_VERSION = engineVersion;
    cc._renderContext = null;
    cc._supportRender = false;
    cc._canvas = null;
    cc.container = null;
    cc._gameDiv = null;
    require("./cocos2d/core/utils");
    require("./cocos2d/core/platform/CCSys");
    var _engineInitCalled = false, _engineLoadedCallback = null;
    cc._engineLoaded = false;
    function _determineRenderType(config) {
      var CONFIG_KEY = cc.game.CONFIG_KEY, userRenderMode = parseInt(config[CONFIG_KEY.renderMode]) || 0;
      (isNaN(userRenderMode) || userRenderMode > 2 || userRenderMode < 0) && (config[CONFIG_KEY.renderMode] = 0);
      cc._renderType = cc.game.RENDER_TYPE_CANVAS;
      cc._supportRender = false;
      if (0 === userRenderMode) {
        if (cc.sys.capabilities["opengl"]) {
          cc._renderType = cc.game.RENDER_TYPE_WEBGL;
          cc._supportRender = true;
        } else if (cc.sys.capabilities["canvas"]) {
          cc._renderType = cc.game.RENDER_TYPE_CANVAS;
          cc._supportRender = true;
        }
      } else if (1 === userRenderMode && cc.sys.capabilities["canvas"]) {
        cc._renderType = cc.game.RENDER_TYPE_CANVAS;
        cc._supportRender = true;
      } else if (2 === userRenderMode && cc.sys.capabilities["opengl"]) {
        cc._renderType = cc.game.RENDER_TYPE_WEBGL;
        cc._supportRender = true;
      }
    }
    function _afterEngineLoaded() {
      cc._engineLoaded = true;
      false;
      console.log(cc.ENGINE_VERSION);
      _engineLoadedCallback && _engineLoadedCallback();
    }
    function _windowLoaded() {
      window.removeEventListener("load", _windowLoaded, false);
      _afterEngineLoaded();
    }
    cc.initEngine = function(config, cb) {
      if (_engineInitCalled) {
        var previousCallback = _engineLoadedCallback;
        _engineLoadedCallback = function() {
          previousCallback && previousCallback();
          cb && cb();
        };
        return;
      }
      _engineLoadedCallback = cb;
      !cc.game.config && config ? cc.game.config = config : cc.game.config || cc.game._loadConfig();
      config = cc.game.config;
      _determineRenderType(config);
      document.body ? _afterEngineLoaded() : window.addEventListener("load", _windowLoaded, false);
      _engineInitCalled = true;
    };
  }), {
    "./cocos2d/core/platform/CCSys": 184,
    "./cocos2d/core/utils": 224
  } ],
  2: [ (function(require, module, exports) {
    var logList;
    var Enum = require("./cocos2d/core/platform/CCEnum");
    cc.DebugMode = Enum({
      NONE: 0,
      INFO: 1,
      WARN: 2,
      ERROR: 3,
      INFO_FOR_WEB_PAGE: 4,
      WARN_FOR_WEB_PAGE: 5,
      ERROR_FOR_WEB_PAGE: 6
    });
    cc._initDebugSetting = function(mode) {
      cc.log = cc.logID = cc.warn = cc.warnID = cc.error = cc.errorID = cc._throw = cc.assert = cc.assertID = function() {};
      if (mode === cc.DebugMode.NONE) return;
      if (true, mode > cc.DebugMode.ERROR) (function() {
        function logToWebPage(msg) {
          if (!cc._canvas) return;
          if (!logList) {
            var logDiv = document.createElement("Div");
            logDiv.setAttribute("id", "logInfoDiv");
            logDiv.setAttribute("width", "200");
            logDiv.setAttribute("height", cc._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 = 0;
            logDiv.appendChild(logList);
            cc._canvas.parentNode.appendChild(logDiv);
          }
          logList.value = logList.value + msg + "\r\n";
          logList.scrollTop = logList.scrollHeight;
        }
        cc.error = function() {
          logToWebPage("ERROR :  " + cc.js.formatStr.apply(null, arguments));
        };
        cc.assert = function(cond, msg) {
          "use strict";
          if (!cond && msg) {
            msg = cc.js.formatStr.apply(null, cc.js.shiftArguments.apply(null, arguments));
            logToWebPage("ASSERT: " + msg);
          }
        };
        mode !== cc.DebugMode.ERROR_FOR_WEB_PAGE && (cc.warn = function() {
          logToWebPage("WARN :  " + cc.js.formatStr.apply(null, arguments));
        });
        mode === cc.DebugMode.INFO_FOR_WEB_PAGE && (cc.log = cc.info = function() {
          logToWebPage(cc.js.formatStr.apply(null, arguments));
        });
      })(); else if (console && console.log.apply) {
        console.error || (console.error = console.log);
        console.warn || (console.warn = console.log);
        false;
        console.error.bind ? cc.error = console.error.bind(console) : cc.error = function() {
          return console.error.apply(console, arguments);
        };
        cc.assert = function(cond, msg) {
          if (!cond) {
            msg && (msg = cc.js.formatStr.apply(null, cc.js.shiftArguments.apply(null, arguments)));
            false;
            false;
            throw new Error(msg);
          }
        };
      }
      if (mode !== cc.DebugMode.ERROR) {
        false;
        console.warn.bind ? cc.warn = console.warn.bind(console) : cc.warn = function() {
          return console.warn.apply(console, arguments);
        };
      }
      false;
      if (mode === cc.DebugMode.INFO) {
        false;
        console.log.bind ? cc.log = console.log.bind(console) : cc.log = function() {
          return console.log.apply(console, arguments);
        };
        false;
        cc.info = function() {
          (console.info || console.log).apply(console, arguments);
        };
      }
      cc.warnID = genLogFunc(cc.warn, "Warning");
      cc.errorID = genLogFunc(cc.error, "Error");
      cc.logID = genLogFunc(cc.log, "Log");
      var assertFailed = genLogFunc((function() {
        var argsArr = [ false ];
        for (var i = 0; i < arguments.length; ++i) argsArr.push(arguments[i]);
        cc.assert.apply(null, argsArr);
      }), "Assert");
      cc.assertID = function(cond) {
        "use strict";
        if (cond) return;
        assertFailed.apply(null, cc.js.shiftArguments.apply(null, arguments));
      };
    };
    cc._throw = function(error) {
      var stack = error.stack;
      stack ? cc.error(stack) : cc.error(error);
    };
    var errorMapUrl = "https://github.com/cocos-creator/engine/blob/master/EngineErrorMap.md";
    function genLogFunc(func, type) {
      return function(id) {
        "use strict";
        if (1 === arguments.length) {
          func(cc._LogInfos[id]);
          return;
        }
        var msg;
        true;
        var argsArr = cc.js.shiftArguments.apply(null, arguments);
        func.apply(cc, [ cc._LogInfos[id] ].concat(argsArr));
      };
    }
  }), {
    "./cocos2d/core/platform/CCEnum": 177
  } ],
  3: [ (function(require, module, exports) {
    true;
    var logs = {
      "1000": "cc.ActionManager.addAction(): action must be non-null",
      "1001": "cocos2d: removeAction: Target not found",
      "1002": "cc.ActionManager.removeActionByTag(): an invalid tag",
      "1003": "cc.ActionManager.removeActionByTag(): target must be non-null",
      "1004": "cc.ActionManager.getActionByTag(): an invalid tag",
      "1005": "cocos2d : getActionByTag(tag = %s): Action not found",
      "1006": "[Action step]. override me",
      "1007": "[Action update]. override me",
      "1008": "cocos2d: FiniteTimeAction#reverse: Implement me",
      "1009": "cc.EaseElastic.reverse(): it should be overridden in subclass.",
      "1010": "cc.IntervalAction: reverse not implemented.",
      "1011": "cc.ActionInterval.setAmplitudeRate(): it should be overridden in subclass.",
      "1012": "cc.ActionInterval.getAmplitudeRate(): it should be overridden in subclass.",
      "1013": "The speed parameter error",
      "1014": "The repeat parameter error",
      "1015": "parameters should not be ending with null in Javascript",
      "1016": "cc.RotateTo.reverse(): it should be overridden in subclass.",
      "1017": "cc.GridAction.getGrid(): it should be overridden in subclass.",
      "1018": "Grid size must be (1,1)",
      "1019": "Failed to construct, Sequence construction needs two or more actions",
      "1020": "Failed to construct, Spawn construction needs two or more actions",
      "1100": "Expected 'data' dict, but not found. Config file: %s",
      "1101": "Please load the resource first : %s",
      "1200": "cocos2d: Director: Error in gettimeofday",
      "1201": "cocos2d: Director: unrecognized projection",
      "1202": "cocos2d: Director: unrecognized projection",
      "1203": "cocos2d: Director: Error in gettimeofday",
      "1204": "running scene should not null",
      "1205": "the scene should not 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 loading",
      "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",
      "1300": "element type is wrong!",
      "1400": "'%s' is deprecated, please use '%s' instead.",
      "1401": "The first argument should be the destination object",
      "1402": "The 'visible' property of %s is deprecated, use 'enabled' instead please.",
      "1403": "Sorry, cc.audioEngine.willPlayMusic is removed.",
      "1404": "cc.spriteFrameCache is removed, please use cc.loader to load and cache sprite frames of atlas format.",
      "1405": "The '%s' will be removed in v2.0, please use '%s' instead. 😰",
      "1500": "cc.Scheduler#schedule: Callback already scheduled. Updating interval from:%s to %s",
      "1501": "cc.Scheduler#scheduleCallbackForTarget(): callback_fn should be non-null.",
      "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": "cc.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 uuid or instanceId",
      "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",
      "1512": "cc.Scheduler: updateFunc parameter is deprecated in scheduleUpdate function, and will be removed in v2.0",
      "1600": "getZOrder is deprecated. Please use getLocalZOrder instead.",
      "1601": "setZOrder is deprecated. Please use setLocalZOrder instead.",
      "1602": "RotationX != RotationY. Don't know which one to return",
      "1603": "ScaleX != ScaleY. Don't know which one to return",
      "1604": "An Node can't be added as a child of itself.",
      "1605": "child already added. It can't be added again",
      "1606": "child must be non-null",
      "1607": "removeFromParentAndCleanup is deprecated. Use removeFromParent instead",
      "1608": "boundingBox is deprecated. Use getBoundingBox instead",
      "1609": "argument tag is an invalid tag",
      "1610": "cocos2d: removeChildByTag(tag = %s): child not found!",
      "1611": "removeAllChildrenWithCleanup is deprecated. Use removeAllChildren instead",
      "1612": "cc.Node.stopActionBy(): argument tag an invalid tag",
      "1613": "cc.Node.getActionByTag(): argument tag is an invalid tag",
      "1614": "resumeSchedulerAndActions is deprecated, please use resume instead.",
      "1615": "pauseSchedulerAndActions is deprecated, please use pause instead.",
      "1616": "Unknown callback function",
      "1617": "child must be non-null",
      "1618": "cc.Node.runAction(): action must be non-null",
      "1619": "callback function must be non-null",
      "1620": "interval must be positive",
      "1621": "cocos2d: Could not initialize cc.AtlasNode. Invalid Texture.",
      "1622": "_ccsg.Node._requestDirtyFlag: failed to satisfy the request, key (%s) for flag have already been taken",
      "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",
      "1628": "Renderer error: Size of the cc._RendererInSG._sgNode must be zero",
      "1629": "The node '%s' has a component inherited from 'cc._RendererInSG'",
      "1630": "JSB environment is not support invoke node.runAction before the 'cc._RendererInSG' component enabled.",
      "1631": "Please use runAction in the method 'start' instead.",
      "1632": "Node name can not include '/'.",
      "1633": "Internal error, should not remove unknown node from parent.",
      "1634": "addChild: The child to add must be instance of cc.Node, not %s.",
      "1635": "reorderChild: this child is not in children list",
      "1700": "cc.AtlasNode.updateAtlasValues(): Shall be overridden in subclasses",
      "1701": "",
      "1702": "cocos2d: Could not initialize cc.AtlasNode. Invalid Texture.",
      "1703": "The new text must be String",
      "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.",
      "2000": "Don't call this method if the event is for touch.",
      "2100": "parameters should not be ending with null in Javascript",
      "2101": "Invalid index in MultiplexLayer switchTo message",
      "2102": "Invalid index in MultiplexLayer switchTo message",
      "2103": "cc.Layer.addLayer(): layer should be non-null",
      "2200": "Resolution not valid",
      "2201": "should set resolutionPolicy",
      "2300": "The touches is more than MAX_TOUCHES, nUnusedIndex = %s",
      "2400": "WebGL error %s",
      "2401": "Too many graphics vertices generated, only 65536 vertices support.",
      "2500": "cocos2d: cc.SpriteFrameAnimationCache: No animations were found in provided dictionary.",
      "2501": "cc.SpriteFrameAnimationCache. Invalid animation format",
      "2502": "cc.SpriteFrameAnimationCache.addAnimations(): File could not be found",
      "2503": "cocos2d: cc.SpriteFrameAnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.",
      "2504": "cocos2d: cc.SpriteFrameAnimationCache: Animation '%s' refers to frame '%s' which is not currently in the cc.SpriteFrameCache. This frame will not be added to the animation.",
      "2505": "cocos2d: cc.SpriteFrameAnimationCache: None of the frames for animation '%s' were found in the cc.SpriteFrameCache. Animation is not being added to the Animation Cache.",
      "2506": "cocos2d: cc.SpriteFrameAnimationCache: An animation in your dictionary refers to a frame which is not in the cc.SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.",
      "2507": "cocos2d: CCAnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.",
      "2508": "cocos2d: cc.SpriteFrameAnimationCache: Animation '%s' refers to frame '%s' which is not currently in the cc.SpriteFrameCache. This frame will not be added to the animation.",
      "2509": "cc.SpriteFrameAnimationCache.addAnimations(): Invalid texture file name",
      "2600": "cc.Sprite.reorderChild(): this child is not in children list",
      "2601": "cc.Sprite.setIgnoreAnchorPointForPosition(): it is invalid in cc.Sprite when using SpriteBatchNode",
      "2602": "cc.Sprite.setDisplayFrameWithAnimationName(): Frame not found",
      "2603": "cc.Sprite.setDisplayFrameWithAnimationName(): Invalid frame index",
      "2604": "setDisplayFrame is deprecated, please use setSpriteFrame instead.",
      "2605": "cc.Sprite._updateBlendFunc(): _updateBlendFunc doesn't work when the sprite is rendered using a cc.CCSpriteBatchNode",
      "2606": "cc.Sprite.initWithSpriteFrame(): spriteFrame should be non-null",
      "2608": "initWithSpriteFrameName is deprecated and can not provide correct functionality",
      "2609": "cc.Sprite.initWithFile(): filename should be non-null",
      "2610": "cc.Sprite.setDisplayFrameWithAnimationName(): animationName must be non-null",
      "2611": "cc.Sprite.reorderChild(): child should be non-null",
      "2612": "cc.Sprite.addChild(): cc.Sprite only supports cc.Sprites as children when using cc.SpriteBatchNode",
      "2613": "cc.Sprite.addChild(): cc.Sprite only supports a sprite using same texture as children when using cc.SpriteBatchNode",
      "2614": "cc.Sprite.addChild(): child should be non-null",
      "2615": "cc.Sprite.texture setter: Batched sprites should use the same texture as the batchnode",
      "2616": "cc.SpriteBatchNode.updateQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children",
      "2617": "cc.SpriteBatchNode.insertQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children",
      "2618": "cc.SpriteBatchNode.addChild(): cc.SpriteBatchNode only supports cc.Sprites as children",
      "2619": "cc.SpriteBatchNode.addChild(): cc.Sprite is not using the same texture",
      "2620": "Sprite.initWithTexture(): Argument must be non-nil ",
      "2621": "Invalid spriteFrameName",
      "2622": "Invalid argument: cc.Sprite.texture setter expects a CCTexture2D.",
      "2623": "cc.SpriteBatchNode.updateQuadFromSprite(): sprite should be non-null",
      "2624": "cc.SpriteBatchNode.insertQuadFromSprite(): sprite should be non-null",
      "2625": "too many tiles, only 16384 tiles will be show",
      "2626": "Unrecognized fill type in bar fill",
      "2627": "Can not generate quad",
      "2728": "%s does not exist",
      "2700": "cc.SpriteBatchNode.addQuadFromSprite(): SpriteBatchNode only supports cc.Sprites as children",
      "2701": "cocos2d: CCSpriteBatchNode: resizing TextureAtlas capacity from %s to %s.",
      "2702": "cocos2d: WARNING: Not enough memory to resize the atlas",
      "2703": "cc.SpriteBatchNode.addChild(): Child doesn't belong to Sprite",
      "2704": "cc.SpriteBatchNode.addChild(): sprite batch node should contain the child",
      "2705": "cc.SpriteBatchNode.addQuadFromSprite(): child should be non-null",
      "2706": "cc.SpriteBatchNode.addChild(): child should be non-null",
      "2707": "cc.SpriteBatchNode.updateQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children",
      "2708": "cc.SpriteBatchNode.insertQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children",
      "2709": "cc.SpriteBatchNode.addChild(): cc.SpriteBatchNode only supports cc.Sprites as children",
      "2710": "Sprite.initWithTexture(): Argument must be non-nil ",
      "2711": "cc.Sprite.addChild(): child should be non-null",
      "2712": "Invalid spriteFrameName",
      "2713": "Invalid argument: cc.Sprite texture setter expects a CCTexture2D.",
      "2714": "cc.SpriteBatchNode.updateQuadFromSprite(): sprite should be non-null",
      "2715": "cc.SpriteBatchNode.insertQuadFromSprite(): sprite should be non-null",
      "2716": "cc.SpriteBatchNode.addChild(): child should be non-null",
      "2800": "cocos2d: WARNING: originalWidth/Height not found on the cc.SpriteFrame. AnchorPoint won't work as expected. Regenrate the .plist",
      "2801": "cocos2d: WARNING: an alias with name %s already exists",
      "2802": "cocos2d: WARNING: Sprite frame: %s has already been added by another source, please fix name conflit",
      "2803": "cocos2d: cc.SpriteFrameCahce: Frame %s not found",
      "2804": "Please load the resource first : %s",
      "2805": "cc.SpriteFrameCache.addSpriteFrames(): plist should be non-null",
      "2806": "Argument must be non-nil",
      "2900": "cocos2d: Could not open file: %s",
      "2901": "cc.TextureAtlas.insertQuad(): invalid totalQuads",
      "2902": "cc.TextureAtlas.initWithTexture():texture should be non-null",
      "2903": "cc.TextureAtlas.updateQuad(): quad should be non-null",
      "2904": "cc.TextureAtlas.updateQuad(): Invalid index",
      "2905": "cc.TextureAtlas.insertQuad(): Invalid index",
      "2906": "cc.TextureAtlas.insertQuad(): Invalid index + amount",
      "2907": "cc.TextureAtlas.insertQuadFromIndex(): Invalid newIndex",
      "2908": "cc.TextureAtlas.insertQuadFromIndex(): Invalid fromIndex",
      "2909": "cc.TextureAtlas.removeQuadAtIndex(): Invalid index",
      "2910": "cc.TextureAtlas.removeQuadsAtIndex(): index + amount out of bounds",
      "2911": "cc.TextureAtlas.moveQuadsFromIndex(): move is out of bounds",
      "2912": "cc.TextureAtlas.moveQuadsFromIndex(): Invalid newIndex",
      "2913": "cc.TextureAtlas.moveQuadsFromIndex(): Invalid oldIndex",
      "3000": "TextureCache:addPVRTCImage does not support on HTML5",
      "3001": "TextureCache:addPVRTCImage does not support on HTML5",
      "3002": "textureForKey is deprecated. Please use getTextureForKey instead.",
      "3003": "addPVRImage does not support on HTML5",
      "3004": "cocos2d: Couldn't add UIImage in TextureCache",
      "3005": "cocos2d: '%s' id=%s %s x %s",
      "3006": "cocos2d: '%s' id= HTMLCanvasElement %s x %s",
      "3007": "cocos2d: TextureCache dumpDebugInfo: %s textures, HTMLCanvasElement for %s KB (%s MB)",
      "3008": "cc.Texture.addUIImage(): image should be non-null",
      "3009": "TextureCache: url should be non-null",
      "3100": "initWithETCFile does not support on HTML5",
      "3101": "initWithPVRFile does not support on HTML5",
      "3102": "initWithPVRTCData does not support on HTML5",
      "3103": "cc.Texture.addImage(): path should be non-null",
      "3104": "cocos2d: cc.Texture2D. Can't create Texture. UIImage is nil",
      "3105": "cocos2d: WARNING: Image (%s x %s) is bigger than the supported %s x %s",
      "3106": "initWithString isn't supported on cocos2d-html5",
      "3107": "initWithETCFile does not support on HTML5",
      "3108": "initWithPVRFile does not support on HTML5",
      "3109": "initWithPVRTCData does not support on HTML5",
      "3110": "bitsPerPixelForFormat: %s, cannot give useful result, it's a illegal pixel format",
      "3111": "cocos2d: cc.Texture2D: Using RGB565 texture since image has no alpha",
      "3112": "cc.Texture.addImage(): path should be non-null",
      "3113": "NSInternalInconsistencyException",
      "3114": "SpriteFrame: Failed to load sprite texture '%s'",
      "3115": "Frame Grabber: could not attach texture to framebuffer",
      "3116": "WebGLRenderingContext.CLAMP_TO_EDGE should be used in NPOT textures",
      "3117": "Mimpap texture only works in POT textures",
      "3118": "contentSize parameter is deprecated and ignored for cc.Texture2D initWithData function",
      "3300": "Rect width exceeds maximum margin: %s",
      "3400": "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",
      "3600": "cc.Class will automatically call super constructor of %s, you should not call it manually.",
      "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 cc.String, not String.",
      "3609": "The type of %s must be cc.Boolean, not Boolean.",
      "3610": "The type of %s must be cc.Float or cc.Integer, 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 specify the '%s' attribute for the getter of '%s.%s', every getter is actually non-serialized.",
      "3615": "Each script can have at most one Component.",
      "3616": "Should not specify class name %s for Component which defines in project.",
      "3617": "ctor of CCClass '%s' should not accept any arguments.",
      "3618": "ctor of '%s' can not be another CCClass",
      "3619": "ctor of '%s' must be function type",
      "3620": "this._super declared in '%s.%s' but no super method defined",
      "3621": "Unknown type of %s.%s, maybe you want is '%s'.",
      "3622": "Unknown type of %s.%s, property should be defined in 'properties' or 'ctor'",
      "3623": "Can not use 'editor' attribute, '%s' not inherits from Components.",
      "3624": "'%s' overwrote '%s' but '%s' is defined as 'false' so the super method will not be called. You can set '%s' to null to disable this warning.",
      "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.",
      "3629": "attribute must be type object",
      "3630": "RawType is only available for Assets",
      "3631": "RawType name cannot contain uppercase",
      "3632": "Each asset cannot have more than one RawType",
      "3633": "Properties function of '%s' should return an object!",
      "3634": "Disallow to use '.' in property name",
      "3635": "Default array must be empty, set default value of %s.%s to [], and initialize in 'onLoad' or 'ctor' please. (just like 'this.%s = [...];')",
      "3636": "Can not set default value to non-empty object, unless the object derived from cc.ValueType and overwrite the 'clone' function. Set default value of %s.%s to null or {}, and initialize in 'onLoad' or 'ctor' please. (just like 'this.%s = {foo: bar};')",
      "3637": "Can not declare %s.%s, it is already defined in the prototype of %s",
      "3638": "'%s': the getter of '%s' is already defined!",
      "3640": "'%s': the setter of '%s' is already defined!",
      "3641": "Can not construct %s because it contains object property.",
      "3642": "Cannot define %s.%s because static member name can not be '%s'.",
      "3643": "Can not define a member called 'constructor' in the class '%s', please use 'ctor' instead.",
      "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.",
      "3649": "CCClass %s have conflict between its ctor and __ctor__.",
      "3650": 'No need to specifiy "%s" attribute for "%s" property in "%s" class.',
      "3651": 'Can not call `_super` or `prototype.ctor` in ES6 Classes "%s", use `super` instead please.',
      "3652": 'Failed to construct a dummy instance of the "%s" class using `new` behind the scenes. This is for getting default values declared in TypeScript. Please ensure the class will be able to construct during script\'s initialization. %s',
      "3653": 'Please do not specifiy "default" attribute in decorator of "%s" property in "%s" class.\n  Default value must be initialized at their declaration: 😂\n    // Before:\n    @property({\n      type: cc.Integer\n      default: 0  // <--\n    })\n    value;\n\n    // After:\n    @property({\n      type: cc.Integer\n    })\n    value = 0;    // <--',
      "3654": 'Please specifiy a default value for "%s" property at its declaration: 😂\n    // Before:\n    @property(...)\n    value;\n\n    // After:\n    @property(...)\n    value = 0;',
      "3655": 'Can not specifiy "get" or "set"  attribute in decorator for "%s" property in "%s" class.\n  Please use:\n    @property(...)\n    get %s () {\n      ...\n    }\n    @property\n    set %s (value) {\n      ...\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 invalid 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 or deactivating.",
      "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",
      "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",
      "3908": "animation not added or already removed",
      "3909": "[animate] keyFrames must be non-nil",
      "3910": "[animate] ratio should >= 0!",
      "3911": "[animate] ratio should in the order of smallest to largest!",
      "4000": "Sorry, the cc.Font has been modified from Raw Asset to Asset. Please load the font asset before using.",
      "4001": "_ccsg.Label._initBMFontWithString(): Impossible to create font. Please check file",
      "4002": "_ccsg.Label._initBMFontWithString(): re-init is no longer supported",
      "4003": "Label font size can't be shirnked less than 0!",
      "4004": "force notify all fonts loaded!",
      "4005": "cc.LabelAtlas.initWithString(): Unsupported version. Upgrade cocos2d version",
      "4006": "cc.LabelAtlas._updateAtlasValues(): Invalid String length",
      "4007": "cc.LabelBMFont.initWithString(): re-init is no longer supported",
      "4008": "cc.LabelBMFont.initWithString(): Impossible to create font. Please check file",
      "4009": "cocos2d: LabelBMFont: character not found %s",
      "4010": "cc.LabelBMFont.setFntFile() : Impossible to create font. Please check file",
      "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.",
      "4100": "Property padding is deprecated, please use paddingLeft, paddingRight, paddingTop and paddingBottom instead",
      "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.",
      "4400": "Invalid RichText img tag! The sprite frame name can't be found in the ImageAtlas!",
      "4600": "Script attached to '%s' is missing or invalid.",
      "4700": "The dom control is not created!",
      "4800": "unknown asset type %s",
      "4901": "loadRes: should not specify the extname in %s %s",
      "4902": "No need to release non-cached asset.",
      "4903": "Can not get class '%s'",
      "4904": "%s does not exist",
      "4905": "%s load error, must be json file",
      "4906": "Can't find the parser : %s",
      "4907": "%s is armature. please use:",
      "4908": "    ccs.armatureDataManager.addArmatureFileInfoAsync(%s);",
      "4909": "    var armature = new ccs.Armature('name');",
      "4910": "Can't find the parser : %s",
      "4911": "register parser error",
      "4912": "Can't find the parser : %s",
      "4913": "Group versions haven't been loaded, you can also set group data with 'cc.LoaderLayer.groups'",
      "4914": "Resources url '%s' does not exist.",
      "4915": "Pack indices and data do not match in size",
      "4916": "Failed to download package for %s",
      "4917": "cc.LabelBMFont._parseCommonArguments(): page can't be larger than supported",
      "4918": "cc.LabelBMFont._parseCommonArguments(): only supports 1 page",
      "4919": "cc.LabelBMFont._parseImageFileName() : file could not be found",
      "4920": "Sorry, you shouldn't use id as item identity any more, please use url or uuid instead, the current id is being set as url: (%s)",
      "4921": "Invalid pipe or invalid index provided!",
      "4922": "The pipe to be inserted is already in the pipeline!",
      "5000": "object already destroyed",
      "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",
      "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'",
      "5400": "'%s' is deprecated, use '%s' instead please.",
      "5401": "'%s' is deprecated, use '%s' instead please.",
      "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't work with 'get/set' !",
      "5501": "'notify' must work with 'default' !",
      "5502": "Invalid url of %s.%s",
      "5503": "The 'url' attribute of '%s.%s' is undefined when loading script.",
      "5504": "The 'url' type of '%s.%s' must be child class of cc.RawAsset.",
      "5505": "The 'url' type of '%s.%s' must not be child class of cc.Asset, otherwise you should use 'type: %s' instead.",
      "5506": "Can not specify 'type' attribute for '%s.%s', because its 'url' is already defined.",
      "5507": "The 'default' attribute of '%s.%s' must be an array",
      "5508": "Invalid type of %s.%s",
      "5509": "The 'type' attribute of '%s.%s' must be child class of cc.Asset, otherwise you should use 'url: %s' instead",
      "5510": "The 'type' attribute of '%s.%s' can not be 'Number', use 'Float' or '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.",
      "5516": "Property '%s.%s' must define at least one of 'default', 'get' or 'set'.",
      "5517": "'%s.%s' hides inherited property '%s.%s'. To make the current property overwrite that implementation, add the `override: true` attribute please.",
      "5600": "Argument must be non-nil",
      "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",
      "6002": "_ccsg.ParticleSystem.addChild() : Can't add a ParticleSystem that uses a different blending function",
      "6003": "cc.ParticleBatchNode.removeChild(): doesn't contain the sprite. Can't remove it",
      "6004": "cc.ParticleBatchNode.reorderChild(): Child doesn't belong to batch",
      "6005": "cc.ParticleBatchNode._increaseAtlasCapacityTo() : WARNING: Not enough memory to resize the atlas",
      "6006": "cocos2d: cc.ParticleBatchNode: resizing TextureAtlas capacity from [%d] to [%d]",
      "6007": "cc.ParticleBatchNode._addChildHelper(): child already added. It can't be added again",
      "6008": "_ccsg.ParticleSystem.initWithFile(): Particles: file not found",
      "6009": "_ccsg.ParticleSystem.initWithDictionary(): Invalid emitterType in config file",
      "6010": "_ccsg.ParticleSystem: error decoding or ungzipping textureImageData",
      "6011": "_ccsg.ParticleSystem: unknown image format with Data",
      "6012": "_ccsg.ParticleSystem.initWithDictionary() : error loading the texture",
      "6013": "Particle system: not enough memory",
      "6014": "Can't change blending functions when the particle is being batched",
      "6015": "_ccsg.ParticleSystem.setDisplayFrame(): QuadParticle only supports SpriteFrames with no offsets",
      "6016": "_ccsg.ParticleSystem._allocMemory(): Memory should not be allocated when not using batchNode",
      "6100": "Not supported file types, Please try use the ccs.load",
      "6200": "Canvas doesn't support mesh slot!",
      "6300": "only cc.DrawNode is accepted as stencil",
      "6301": "Stencil buffer is not enabled.",
      "6302": "Nesting more than %d stencils is not supported. Everything will be drawn without stencil for this node and its children.",
      "6400": "asset.url is not usable in core process",
      "6401": "asset.urls 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",
      "6701": "Should not add Canvas to a node which already contains a renderer component (%s).",
      "6702": "Should not add Canvas to a node which size is already used by its other component.",
      "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",
      "7000": "Failed to init asset's raw path.",
      "7001": "Should not load '%s' from script dynamically, unless it is placed in the 'resources' folder.",
      "7002": "Sorry can not load '%s' because it is not placed in the 'resources' folder.",
      "7003": "Failed to init builtin asset's raw path.",
      "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'.",
      "7204": "_ccsg.TMXLayer.getTileAt(): TMXLayer: the tiles map has been released",
      "7205": "_ccsg.TMXLayer.getTileGIDAt(): TMXLayer: the tiles map has been released",
      "7206": "_ccsg.TMXLayer.setTileGID(): TMXLayer: the tiles map has been released",
      "7207": "_ccsg.TMXLayer.setTileGID(): invalid gid: %s",
      "7208": "_ccsg.TMXLayer.getTileFlagsAt(): TMXLayer: the tiles map has been released",
      "7209": "_ccsg.TMXLayer.removeTileAt(): TMXLayer: the tiles map has been released",
      "7210": "TMX Hexa zOrder not supported",
      "7211": "TMX invalid value",
      "7212": "_ccsg.TMXTiledMap.initWithTMXFile(): Map not found. Please check the filename.",
      "7213": "_ccsg.TMXTiledMap.initWithXML(): Map not found. Please check the filename.",
      "7214": "propertiesForGID is deprecated. Please use getPropertiesForGID instead.",
      "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",
      "7220": "TMX Parser: please load the xml resource first: %s",
      "7300": "The new selected must be number",
      "7301": "The new bake must be boolean",
      "7400": "Failed to set _defaultArmatureIndex for '%s' because its dragonAsset is invalid.",
      "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.",
      "7500": "Failed to set _defaultSkinIndex for '%s' because its skeletonData is invalid.",
      "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",
      "7505": "Invalid type of atlasFile, atlas should be registered as raw asset.",
      "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.",
      "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!",
      "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.",
      "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",
      "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."
    };
    cc._LogInfos = logs;
  }), {} ],
  4: [ (function(require, module, exports) {
    cc.Action = cc._Class.extend({
      ctor: function() {
        this.originalTarget = null;
        this.target = null;
        this.tag = cc.Action.TAG_INVALID;
      },
      clone: function() {
        var action = new cc.Action();
        action.originalTarget = null;
        action.target = null;
        action.tag = this.tag;
        return action;
      },
      isDone: function() {
        return true;
      },
      startWithTarget: function(target) {
        this.originalTarget = target;
        this.target = target;
      },
      stop: function() {
        this.target = null;
      },
      step: function(dt) {
        cc.logID(1006);
      },
      update: function(dt) {
        cc.logID(1007);
      },
      getTarget: function() {
        return this.target;
      },
      setTarget: function(target) {
        this.target = target;
      },
      getOriginalTarget: function() {
        return this.originalTarget;
      },
      setOriginalTarget: function(originalTarget) {
        this.originalTarget = originalTarget;
      },
      getTag: function() {
        return this.tag;
      },
      setTag: function(tag) {
        this.tag = tag;
      },
      retain: function() {},
      release: function() {}
    });
    cc.Action.TAG_INVALID = -1;
    cc.FiniteTimeAction = cc.Action.extend({
      _duration: 0,
      ctor: function() {
        cc.Action.prototype.ctor.call(this);
        this._duration = 0;
      },
      getDuration: function() {
        return this._duration * (this._timesForRepeat || 1);
      },
      setDuration: function(duration) {
        this._duration = duration;
      },
      reverse: function() {
        cc.logID(1008);
        return null;
      },
      clone: function() {
        return new cc.FiniteTimeAction();
      }
    });
    cc.Speed = cc.Action.extend({
      _speed: 0,
      _innerAction: null,
      ctor: function(action, speed) {
        cc.Action.prototype.ctor.call(this);
        this._speed = 0;
        this._innerAction = null;
        action && this.initWithAction(action, speed);
      },
      getSpeed: function() {
        return this._speed;
      },
      setSpeed: function(speed) {
        this._speed = speed;
      },
      initWithAction: function(action, speed) {
        if (!action) throw new Error("cc.Speed.initWithAction(): action must be non nil");
        this._innerAction = action;
        this._speed = speed;
        return true;
      },
      clone: function() {
        var action = new cc.Speed();
        action.initWithAction(this._innerAction.clone(), this._speed);
        return action;
      },
      startWithTarget: function(target) {
        cc.Action.prototype.startWithTarget.call(this, target);
        this._innerAction.startWithTarget(target);
      },
      stop: function() {
        this._innerAction.stop();
        cc.Action.prototype.stop.call(this);
      },
      step: function(dt) {
        this._innerAction.step(dt * this._speed);
      },
      isDone: function() {
        return this._innerAction.isDone();
      },
      reverse: function() {
        return new cc.Speed(this._innerAction.reverse(), this._speed);
      },
      setInnerAction: function(action) {
        this._innerAction !== action && (this._innerAction = action);
      },
      getInnerAction: function() {
        return this._innerAction;
      }
    });
    cc.speed = function(action, speed) {
      return new cc.Speed(action, speed);
    };
    cc.Follow = cc.Action.extend({
      _followedNode: null,
      _boundarySet: false,
      _boundaryFullyCovered: false,
      _halfScreenSize: null,
      _fullScreenSize: null,
      _worldRect: null,
      leftBoundary: 0,
      rightBoundary: 0,
      topBoundary: 0,
      bottomBoundary: 0,
      ctor: function(followedNode, rect) {
        cc.Action.prototype.ctor.call(this);
        this._followedNode = null;
        this._boundarySet = false;
        this._boundaryFullyCovered = false;
        this._halfScreenSize = null;
        this._fullScreenSize = null;
        this.leftBoundary = 0;
        this.rightBoundary = 0;
        this.topBoundary = 0;
        this.bottomBoundary = 0;
        this._worldRect = cc.rect(0, 0, 0, 0);
        followedNode && (rect ? this.initWithTarget(followedNode, rect) : this.initWithTarget(followedNode));
      },
      clone: function() {
        var action = new cc.Follow();
        var locRect = this._worldRect;
        var rect = new cc.Rect(locRect.x, locRect.y, locRect.width, locRect.height);
        action.initWithTarget(this._followedNode, rect);
        return action;
      },
      isBoundarySet: function() {
        return this._boundarySet;
      },
      setBoudarySet: function(value) {
        this._boundarySet = value;
      },
      initWithTarget: function(followedNode, rect) {
        if (!followedNode) throw new Error("cc.Follow.initWithAction(): followedNode must be non nil");
        var _this = this;
        rect = rect || cc.rect(0, 0, 0, 0);
        _this._followedNode = followedNode;
        _this._worldRect = rect;
        _this._boundarySet = !cc._rectEqualToZero(rect);
        _this._boundaryFullyCovered = false;
        var winSize = cc.director.getWinSize();
        _this._fullScreenSize = cc.p(winSize.width, winSize.height);
        _this._halfScreenSize = cc.pMult(_this._fullScreenSize, .5);
        if (_this._boundarySet) {
          _this.leftBoundary = -(rect.x + rect.width - _this._fullScreenSize.x);
          _this.rightBoundary = -rect.x;
          _this.topBoundary = -rect.y;
          _this.bottomBoundary = -(rect.y + rect.height - _this._fullScreenSize.y);
          _this.rightBoundary < _this.leftBoundary && (_this.rightBoundary = _this.leftBoundary = (_this.leftBoundary + _this.rightBoundary) / 2);
          _this.topBoundary < _this.bottomBoundary && (_this.topBoundary = _this.bottomBoundary = (_this.topBoundary + _this.bottomBoundary) / 2);
          _this.topBoundary === _this.bottomBoundary && _this.leftBoundary === _this.rightBoundary && (_this._boundaryFullyCovered = true);
        }
        return true;
      },
      step: function(dt) {
        var targetWorldPos = this.target.convertToWorldSpaceAR(cc.Vec2.ZERO);
        var followedWorldPos = this._followedNode.convertToWorldSpaceAR(cc.Vec2.ZERO);
        var delta = cc.pSub(targetWorldPos, followedWorldPos);
        var tempPos = this.target.parent.convertToNodeSpaceAR(cc.pAdd(delta, this._halfScreenSize));
        if (this._boundarySet) {
          if (this._boundaryFullyCovered) return;
          this.target.setPosition(cc.clampf(tempPos.x, this.leftBoundary, this.rightBoundary), cc.clampf(tempPos.y, this.bottomBoundary, this.topBoundary));
        } else this.target.setPosition(tempPos.x, tempPos.y);
      },
      isDone: function() {
        return !this._followedNode.isRunning();
      },
      stop: function() {
        this.target = null;
        cc.Action.prototype.stop.call(this);
      }
    });
    cc.follow = function(followedNode, rect) {
      return new cc.Follow(followedNode, rect);
    };
  }), {} ],
  5: [ (function(require, module, exports) {
    cc.cardinalSplineAt = function(p0, p1, p2, p3, tension, t) {
      var t2 = t * t;
      var t3 = t2 * t;
      var s = (1 - tension) / 2;
      var b1 = s * (2 * t2 - t3 - t);
      var b2 = s * (-t3 + t2) + (2 * t3 - 3 * t2 + 1);
      var b3 = s * (t3 - 2 * t2 + t) + (-2 * t3 + 3 * t2);
      var b4 = s * (t3 - t2);
      var x = p0.x * b1 + p1.x * b2 + p2.x * b3 + p3.x * b4;
      var y = p0.y * b1 + p1.y * b2 + p2.y * b3 + p3.y * b4;
      return cc.p(x, y);
    };
    cc.getControlPointAt = function(controlPoints, pos) {
      var p = Math.min(controlPoints.length - 1, Math.max(pos, 0));
      return controlPoints[p];
    };
    function reverseControlPoints(controlPoints) {
      var newArray = [];
      for (var i = controlPoints.length - 1; i >= 0; i--) newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y));
      return newArray;
    }
    function cloneControlPoints(controlPoints) {
      var newArray = [];
      for (var i = 0; i < controlPoints.length; i++) newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y));
      return newArray;
    }
    cc.CardinalSplineTo = cc.ActionInterval.extend({
      _points: null,
      _deltaT: 0,
      _tension: 0,
      _previousPosition: null,
      _accumulatedDiff: null,
      ctor: function(duration, points, tension) {
        cc.ActionInterval.prototype.ctor.call(this);
        this._points = [];
        void 0 !== tension && this.initWithDuration(duration, points, tension);
      },
      initWithDuration: function(duration, points, tension) {
        if (!points || 0 === points.length) throw new Error("Invalid configuration. It must at least have one control point");
        if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
          this.setPoints(points);
          this._tension = tension;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.CardinalSplineTo();
        action.initWithDuration(this._duration, cloneControlPoints(this._points), this._tension);
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        this._deltaT = 1 / (this._points.length - 1);
        this._previousPosition = cc.p(this.target.getPositionX(), this.target.getPositionY());
        this._accumulatedDiff = cc.p(0, 0);
      },
      update: function(dt) {
        dt = this._computeEaseTime(dt);
        var p, lt;
        var ps = this._points;
        if (1 === dt) {
          p = ps.length - 1;
          lt = 1;
        } else {
          var locDT = this._deltaT;
          p = 0 | dt / locDT;
          lt = (dt - locDT * p) / locDT;
        }
        var newPos = cc.cardinalSplineAt(cc.getControlPointAt(ps, p - 1), cc.getControlPointAt(ps, p - 0), cc.getControlPointAt(ps, p + 1), cc.getControlPointAt(ps, p + 2), this._tension, lt);
        if (cc.macro.ENABLE_STACKABLE_ACTIONS) {
          var tempX, tempY;
          tempX = this.target.getPositionX() - this._previousPosition.x;
          tempY = this.target.getPositionY() - this._previousPosition.y;
          if (0 !== tempX || 0 !== tempY) {
            var locAccDiff = this._accumulatedDiff;
            tempX = locAccDiff.x + tempX;
            tempY = locAccDiff.y + tempY;
            locAccDiff.x = tempX;
            locAccDiff.y = tempY;
            newPos.x += tempX;
            newPos.y += tempY;
          }
        }
        this.updatePosition(newPos);
      },
      reverse: function() {
        var reversePoints = reverseControlPoints(this._points);
        return cc.cardinalSplineTo(this._duration, reversePoints, this._tension);
      },
      updatePosition: function(newPos) {
        this.target.setPosition(newPos);
        this._previousPosition = newPos;
      },
      getPoints: function() {
        return this._points;
      },
      setPoints: function(points) {
        this._points = points;
      }
    });
    cc.cardinalSplineTo = function(duration, points, tension) {
      return new cc.CardinalSplineTo(duration, points, tension);
    };
    cc.CardinalSplineBy = cc.CardinalSplineTo.extend({
      _startPosition: null,
      ctor: function(duration, points, tension) {
        cc.CardinalSplineTo.prototype.ctor.call(this);
        this._startPosition = cc.p(0, 0);
        void 0 !== tension && this.initWithDuration(duration, points, tension);
      },
      startWithTarget: function(target) {
        cc.CardinalSplineTo.prototype.startWithTarget.call(this, target);
        this._startPosition.x = target.getPositionX();
        this._startPosition.y = target.getPositionY();
      },
      reverse: function() {
        var copyConfig = this._points.slice();
        var current;
        var p = copyConfig[0];
        for (var i = 1; i < copyConfig.length; ++i) {
          current = copyConfig[i];
          copyConfig[i] = cc.pSub(current, p);
          p = current;
        }
        var reverseArray = reverseControlPoints(copyConfig);
        p = reverseArray[reverseArray.length - 1];
        reverseArray.pop();
        p.x = -p.x;
        p.y = -p.y;
        reverseArray.unshift(p);
        for (var i = 1; i < reverseArray.length; ++i) {
          current = reverseArray[i];
          current.x = -current.x;
          current.y = -current.y;
          current.x += p.x;
          current.y += p.y;
          reverseArray[i] = current;
          p = current;
        }
        return cc.cardinalSplineBy(this._duration, reverseArray, this._tension);
      },
      updatePosition: function(newPos) {
        var pos = this._startPosition;
        var posX = newPos.x + pos.x;
        var posY = newPos.y + pos.y;
        this._previousPosition.x = posX;
        this._previousPosition.y = posY;
        this.target.setPosition(posX, posY);
      },
      clone: function() {
        var a = new cc.CardinalSplineBy();
        a.initWithDuration(this._duration, cloneControlPoints(this._points), this._tension);
        return a;
      }
    });
    cc.cardinalSplineBy = function(duration, points, tension) {
      return new cc.CardinalSplineBy(duration, points, tension);
    };
    cc.CatmullRomTo = cc.CardinalSplineTo.extend({
      ctor: function(dt, points) {
        points && this.initWithDuration(dt, points);
      },
      initWithDuration: function(dt, points) {
        return cc.CardinalSplineTo.prototype.initWithDuration.call(this, dt, points, .5);
      },
      clone: function() {
        var action = new cc.CatmullRomTo();
        action.initWithDuration(this._duration, cloneControlPoints(this._points));
        return action;
      }
    });
    cc.catmullRomTo = function(dt, points) {
      return new cc.CatmullRomTo(dt, points);
    };
    cc.CatmullRomBy = cc.CardinalSplineBy.extend({
      ctor: function(dt, points) {
        cc.CardinalSplineBy.prototype.ctor.call(this);
        points && this.initWithDuration(dt, points);
      },
      initWithDuration: function(dt, points) {
        return cc.CardinalSplineTo.prototype.initWithDuration.call(this, dt, points, .5);
      },
      clone: function() {
        var action = new cc.CatmullRomBy();
        action.initWithDuration(this._duration, cloneControlPoints(this._points));
        return action;
      }
    });
    cc.catmullRomBy = function(dt, points) {
      return new cc.CatmullRomBy(dt, points);
    };
  }), {} ],
  6: [ (function(require, module, exports) {
    cc.ActionEase = cc.ActionInterval.extend({
      _inner: null,
      ctor: function(action) {
        cc.ActionInterval.prototype.ctor.call(this);
        action && this.initWithAction(action);
      },
      initWithAction: function(action) {
        if (!action) throw new Error("cc.ActionEase.initWithAction(): action must be non nil");
        if (this.initWithDuration(action.getDuration())) {
          this._inner = action;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.ActionEase();
        action.initWithAction(this._inner.clone());
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        this._inner.startWithTarget(this.target);
      },
      stop: function() {
        this._inner.stop();
        cc.ActionInterval.prototype.stop.call(this);
      },
      update: function(dt) {
        this._inner.update(dt);
      },
      reverse: function() {
        return new cc.ActionEase(this._inner.reverse());
      },
      getInnerAction: function() {
        return this._inner;
      }
    });
    cc.actionEase = function(action) {
      return new cc.ActionEase(action);
    };
    cc.EaseRateAction = cc.ActionEase.extend({
      _rate: 0,
      ctor: function(action, rate) {
        cc.ActionEase.prototype.ctor.call(this);
        void 0 !== rate && this.initWithAction(action, rate);
      },
      setRate: function(rate) {
        this._rate = rate;
      },
      getRate: function() {
        return this._rate;
      },
      initWithAction: function(action, rate) {
        if (cc.ActionEase.prototype.initWithAction.call(this, action)) {
          this._rate = rate;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.EaseRateAction();
        action.initWithAction(this._inner.clone(), this._rate);
        return action;
      },
      reverse: function() {
        return new cc.EaseRateAction(this._inner.reverse(), 1 / this._rate);
      }
    });
    cc.easeRateAction = function(action, rate) {
      return new cc.EaseRateAction(action, rate);
    };
    cc.EaseIn = cc.EaseRateAction.extend({
      update: function(dt) {
        this._inner.update(Math.pow(dt, this._rate));
      },
      reverse: function() {
        return new cc.EaseIn(this._inner.reverse(), 1 / this._rate);
      },
      clone: function() {
        var action = new cc.EaseIn();
        action.initWithAction(this._inner.clone(), this._rate);
        return action;
      }
    });
    cc.easeIn = function(rate) {
      return {
        _rate: rate,
        easing: function(dt) {
          return Math.pow(dt, this._rate);
        },
        reverse: function() {
          return cc.easeIn(1 / this._rate);
        }
      };
    };
    cc.EaseOut = cc.EaseRateAction.extend({
      update: function(dt) {
        this._inner.update(Math.pow(dt, 1 / this._rate));
      },
      reverse: function() {
        return new cc.EaseOut(this._inner.reverse(), 1 / this._rate);
      },
      clone: function() {
        var action = new cc.EaseOut();
        action.initWithAction(this._inner.clone(), this._rate);
        return action;
      }
    });
    cc.easeOut = function(rate) {
      return {
        _rate: rate,
        easing: function(dt) {
          return Math.pow(dt, 1 / this._rate);
        },
        reverse: function() {
          return cc.easeOut(1 / this._rate);
        }
      };
    };
    cc.EaseInOut = cc.EaseRateAction.extend({
      update: function(dt) {
        dt *= 2;
        dt < 1 ? this._inner.update(.5 * Math.pow(dt, this._rate)) : this._inner.update(1 - .5 * Math.pow(2 - dt, this._rate));
      },
      clone: function() {
        var action = new cc.EaseInOut();
        action.initWithAction(this._inner.clone(), this._rate);
        return action;
      },
      reverse: function() {
        return new cc.EaseInOut(this._inner.reverse(), this._rate);
      }
    });
    cc.easeInOut = function(rate) {
      return {
        _rate: rate,
        easing: function(dt) {
          dt *= 2;
          return dt < 1 ? .5 * Math.pow(dt, this._rate) : 1 - .5 * Math.pow(2 - dt, this._rate);
        },
        reverse: function() {
          return cc.easeInOut(this._rate);
        }
      };
    };
    cc.EaseExponentialIn = cc.ActionEase.extend({
      update: function(dt) {
        this._inner.update(0 === dt ? 0 : Math.pow(2, 10 * (dt - 1)));
      },
      reverse: function() {
        return new cc.EaseExponentialOut(this._inner.reverse());
      },
      clone: function() {
        var action = new cc.EaseExponentialIn();
        action.initWithAction(this._inner.clone());
        return action;
      }
    });
    cc._easeExponentialInObj = {
      easing: function(dt) {
        return 0 === dt ? 0 : Math.pow(2, 10 * (dt - 1));
      },
      reverse: function() {
        return cc._easeExponentialOutObj;
      }
    };
    cc.easeExponentialIn = function() {
      return cc._easeExponentialInObj;
    };
    cc.EaseExponentialOut = cc.ActionEase.extend({
      update: function(dt) {
        this._inner.update(1 === dt ? 1 : 1 - Math.pow(2, -10 * dt));
      },
      reverse: function() {
        return new cc.EaseExponentialIn(this._inner.reverse());
      },
      clone: function() {
        var action = new cc.EaseExponentialOut();
        action.initWithAction(this._inner.clone());
        return action;
      }
    });
    cc._easeExponentialOutObj = {
      easing: function(dt) {
        return 1 === dt ? 1 : 1 - Math.pow(2, -10 * dt);
      },
      reverse: function() {
        return cc._easeExponentialInObj;
      }
    };
    cc.easeExponentialOut = function() {
      return cc._easeExponentialOutObj;
    };
    cc.EaseExponentialInOut = cc.ActionEase.extend({
      update: function(dt) {
        if (1 !== dt && 0 !== dt) {
          dt *= 2;
          dt = dt < 1 ? .5 * Math.pow(2, 10 * (dt - 1)) : .5 * (2 - Math.pow(2, -10 * (dt - 1)));
        }
        this._inner.update(dt);
      },
      reverse: function() {
        return new cc.EaseExponentialInOut(this._inner.reverse());
      },
      clone: function() {
        var action = new cc.EaseExponentialInOut();
        action.initWithAction(this._inner.clone());
        return action;
      }
    });
    cc._easeExponentialInOutObj = {
      easing: function(dt) {
        if (1 !== dt && 0 !== dt) {
          dt *= 2;
          return dt < 1 ? .5 * Math.pow(2, 10 * (dt - 1)) : .5 * (2 - Math.pow(2, -10 * (dt - 1)));
        }
        return dt;
      },
      reverse: function() {
        return cc._easeExponentialInOutObj;
      }
    };
    cc.easeExponentialInOut = function() {
      return cc._easeExponentialInOutObj;
    };
    cc.EaseSineIn = cc.ActionEase.extend({
      update: function(dt) {
        dt = 0 === dt || 1 === dt ? dt : -1 * Math.cos(dt * Math.PI / 2) + 1;
        this._inner.update(dt);
      },
      reverse: function() {
        return new cc.EaseSineOut(this._inner.reverse());
      },
      clone: function() {
        var action = new cc.EaseSineIn();
        action.initWithAction(this._inner.clone());
        return action;
      }
    });
    cc._easeSineInObj = {
      easing: function(dt) {
        return 0 === dt || 1 === dt ? dt : -1 * Math.cos(dt * Math.PI / 2) + 1;
      },
      reverse: function() {
        return cc._easeSineOutObj;
      }
    };
    cc.easeSineIn = function() {
      return cc._easeSineInObj;
    };
    cc.EaseSineOut = cc.ActionEase.extend({
      update: function(dt) {
        dt = 0 === dt || 1 === dt ? dt : Math.sin(dt * Math.PI / 2);
        this._inner.update(dt);
      },
      reverse: function() {
        return new cc.EaseSineIn(this._inner.reverse());
      },
      clone: function() {
        var action = new cc.EaseSineOut();
        action.initWithAction(this._inner.clone());
        return action;
      }
    });
    cc._easeSineOutObj = {
      easing: function(dt) {
        return 0 === dt || 1 === dt ? dt : Math.sin(dt * Math.PI / 2);
      },
      reverse: function() {
        return cc._easeSineInObj;
      }
    };
    cc.easeSineOut = function() {
      return cc._easeSineOutObj;
    };
    cc.EaseSineInOut = cc.ActionEase.extend({
      update: function(dt) {
        dt = 0 === dt || 1 === dt ? dt : -.5 * (Math.cos(Math.PI * dt) - 1);
        this._inner.update(dt);
      },
      clone: function() {
        var action = new cc.EaseSineInOut();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseSineInOut(this._inner.reverse());
      }
    });
    cc._easeSineInOutObj = {
      easing: function(dt) {
        return 0 === dt || 1 === dt ? dt : -.5 * (Math.cos(Math.PI * dt) - 1);
      },
      reverse: function() {
        return cc._easeSineInOutObj;
      }
    };
    cc.easeSineInOut = function() {
      return cc._easeSineInOutObj;
    };
    cc.EaseElastic = cc.ActionEase.extend({
      _period: .3,
      ctor: function(action, period) {
        cc.ActionEase.prototype.ctor.call(this);
        action && this.initWithAction(action, period);
      },
      getPeriod: function() {
        return this._period;
      },
      setPeriod: function(period) {
        this._period = period;
      },
      initWithAction: function(action, period) {
        cc.ActionEase.prototype.initWithAction.call(this, action);
        this._period = null == period ? .3 : period;
        return true;
      },
      reverse: function() {
        cc.logID(1009);
        return null;
      },
      clone: function() {
        var action = new cc.EaseElastic();
        action.initWithAction(this._inner.clone(), this._period);
        return action;
      }
    });
    cc.EaseElasticIn = cc.EaseElastic.extend({
      update: function(dt) {
        var newT = 0;
        if (0 === dt || 1 === dt) newT = dt; else {
          var s = this._period / 4;
          dt -= 1;
          newT = -Math.pow(2, 10 * dt) * Math.sin((dt - s) * Math.PI * 2 / this._period);
        }
        this._inner.update(newT);
      },
      reverse: function() {
        return new cc.EaseElasticOut(this._inner.reverse(), this._period);
      },
      clone: function() {
        var action = new cc.EaseElasticIn();
        action.initWithAction(this._inner.clone(), this._period);
        return action;
      }
    });
    cc._easeElasticInObj = {
      easing: function(dt) {
        if (0 === dt || 1 === dt) return dt;
        dt -= 1;
        return -Math.pow(2, 10 * dt) * Math.sin((dt - .075) * Math.PI * 2 / .3);
      },
      reverse: function() {
        return cc._easeElasticOutObj;
      }
    };
    cc.easeElasticIn = function(period) {
      if (period && .3 !== period) return {
        _period: period,
        easing: function(dt) {
          if (0 === dt || 1 === dt) return dt;
          dt -= 1;
          return -Math.pow(2, 10 * dt) * Math.sin((dt - this._period / 4) * Math.PI * 2 / this._period);
        },
        reverse: function() {
          return cc.easeElasticOut(this._period);
        }
      };
      return cc._easeElasticInObj;
    };
    cc.EaseElasticOut = cc.EaseElastic.extend({
      update: function(dt) {
        var newT = 0;
        if (0 === dt || 1 === dt) newT = dt; else {
          var s = this._period / 4;
          newT = Math.pow(2, -10 * dt) * Math.sin((dt - s) * Math.PI * 2 / this._period) + 1;
        }
        this._inner.update(newT);
      },
      reverse: function() {
        return new cc.EaseElasticIn(this._inner.reverse(), this._period);
      },
      clone: function() {
        var action = new cc.EaseElasticOut();
        action.initWithAction(this._inner.clone(), this._period);
        return action;
      }
    });
    cc._easeElasticOutObj = {
      easing: function(dt) {
        return 0 === dt || 1 === dt ? dt : Math.pow(2, -10 * dt) * Math.sin((dt - .075) * Math.PI * 2 / .3) + 1;
      },
      reverse: function() {
        return cc._easeElasticInObj;
      }
    };
    cc.easeElasticOut = function(period) {
      if (period && .3 !== period) return {
        _period: period,
        easing: function(dt) {
          return 0 === dt || 1 === dt ? dt : Math.pow(2, -10 * dt) * Math.sin((dt - this._period / 4) * Math.PI * 2 / this._period) + 1;
        },
        reverse: function() {
          return cc.easeElasticIn(this._period);
        }
      };
      return cc._easeElasticOutObj;
    };
    cc.EaseElasticInOut = cc.EaseElastic.extend({
      update: function(dt) {
        var newT = 0;
        var locPeriod = this._period;
        if (0 === dt || 1 === dt) newT = dt; else {
          dt *= 2;
          locPeriod || (locPeriod = this._period = .3 * 1.5);
          var s = locPeriod / 4;
          dt -= 1;
          newT = dt < 0 ? -.5 * Math.pow(2, 10 * dt) * Math.sin((dt - s) * Math.PI * 2 / locPeriod) : Math.pow(2, -10 * dt) * Math.sin((dt - s) * Math.PI * 2 / locPeriod) * .5 + 1;
        }
        this._inner.update(newT);
      },
      reverse: function() {
        return new cc.EaseElasticInOut(this._inner.reverse(), this._period);
      },
      clone: function() {
        var action = new cc.EaseElasticInOut();
        action.initWithAction(this._inner.clone(), this._period);
        return action;
      }
    });
    cc.easeElasticInOut = function(period) {
      period = period || .3;
      return {
        _period: period,
        easing: function(dt) {
          var newT = 0;
          var locPeriod = this._period;
          if (0 === dt || 1 === dt) newT = dt; else {
            dt *= 2;
            locPeriod || (locPeriod = this._period = .3 * 1.5);
            var s = locPeriod / 4;
            dt -= 1;
            newT = dt < 0 ? -.5 * Math.pow(2, 10 * dt) * Math.sin((dt - s) * Math.PI * 2 / locPeriod) : Math.pow(2, -10 * dt) * Math.sin((dt - s) * Math.PI * 2 / locPeriod) * .5 + 1;
          }
          return newT;
        },
        reverse: function() {
          return cc.easeElasticInOut(this._period);
        }
      };
    };
    cc.EaseBounce = cc.ActionEase.extend({
      bounceTime: function(time1) {
        if (time1 < 1 / 2.75) return 7.5625 * time1 * time1;
        if (time1 < 2 / 2.75) {
          time1 -= 1.5 / 2.75;
          return 7.5625 * time1 * time1 + .75;
        }
        if (time1 < 2.5 / 2.75) {
          time1 -= 2.25 / 2.75;
          return 7.5625 * time1 * time1 + .9375;
        }
        time1 -= 2.625 / 2.75;
        return 7.5625 * time1 * time1 + .984375;
      },
      clone: function() {
        var action = new cc.EaseBounce();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseBounce(this._inner.reverse());
      }
    });
    cc.EaseBounceIn = cc.EaseBounce.extend({
      update: function(dt) {
        var newT = 1 - this.bounceTime(1 - dt);
        this._inner.update(newT);
      },
      reverse: function() {
        return new cc.EaseBounceOut(this._inner.reverse());
      },
      clone: function() {
        var action = new cc.EaseBounceIn();
        action.initWithAction(this._inner.clone());
        return action;
      }
    });
    cc._bounceTime = function(time1) {
      if (time1 < 1 / 2.75) return 7.5625 * time1 * time1;
      if (time1 < 2 / 2.75) {
        time1 -= 1.5 / 2.75;
        return 7.5625 * time1 * time1 + .75;
      }
      if (time1 < 2.5 / 2.75) {
        time1 -= 2.25 / 2.75;
        return 7.5625 * time1 * time1 + .9375;
      }
      time1 -= 2.625 / 2.75;
      return 7.5625 * time1 * time1 + .984375;
    };
    cc._easeBounceInObj = {
      easing: function(dt) {
        return 1 - cc._bounceTime(1 - dt);
      },
      reverse: function() {
        return cc._easeBounceOutObj;
      }
    };
    cc.easeBounceIn = function() {
      return cc._easeBounceInObj;
    };
    cc.EaseBounceOut = cc.EaseBounce.extend({
      update: function(dt) {
        var newT = this.bounceTime(dt);
        this._inner.update(newT);
      },
      reverse: function() {
        return new cc.EaseBounceIn(this._inner.reverse());
      },
      clone: function() {
        var action = new cc.EaseBounceOut();
        action.initWithAction(this._inner.clone());
        return action;
      }
    });
    cc._easeBounceOutObj = {
      easing: function(dt) {
        return cc._bounceTime(dt);
      },
      reverse: function() {
        return cc._easeBounceInObj;
      }
    };
    cc.easeBounceOut = function() {
      return cc._easeBounceOutObj;
    };
    cc.EaseBounceInOut = cc.EaseBounce.extend({
      update: function(dt) {
        var newT = 0;
        if (dt < .5) {
          dt *= 2;
          newT = .5 * (1 - this.bounceTime(1 - dt));
        } else newT = .5 * this.bounceTime(2 * dt - 1) + .5;
        this._inner.update(newT);
      },
      clone: function() {
        var action = new cc.EaseBounceInOut();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseBounceInOut(this._inner.reverse());
      }
    });
    cc._easeBounceInOutObj = {
      easing: function(time1) {
        var newT;
        if (time1 < .5) {
          time1 *= 2;
          newT = .5 * (1 - cc._bounceTime(1 - time1));
        } else newT = .5 * cc._bounceTime(2 * time1 - 1) + .5;
        return newT;
      },
      reverse: function() {
        return cc._easeBounceInOutObj;
      }
    };
    cc.easeBounceInOut = function() {
      return cc._easeBounceInOutObj;
    };
    cc.EaseBackIn = cc.ActionEase.extend({
      update: function(dt) {
        var overshoot = 1.70158;
        dt = 0 === dt || 1 === dt ? dt : dt * dt * ((overshoot + 1) * dt - overshoot);
        this._inner.update(dt);
      },
      reverse: function() {
        return new cc.EaseBackOut(this._inner.reverse());
      },
      clone: function() {
        var action = new cc.EaseBackIn();
        action.initWithAction(this._inner.clone());
        return action;
      }
    });
    cc._easeBackInObj = {
      easing: function(time1) {
        var overshoot = 1.70158;
        return 0 === time1 || 1 === time1 ? time1 : time1 * time1 * ((overshoot + 1) * time1 - overshoot);
      },
      reverse: function() {
        return cc._easeBackOutObj;
      }
    };
    cc.easeBackIn = function() {
      return cc._easeBackInObj;
    };
    cc.EaseBackOut = cc.ActionEase.extend({
      update: function(dt) {
        var overshoot = 1.70158;
        dt -= 1;
        this._inner.update(dt * dt * ((overshoot + 1) * dt + overshoot) + 1);
      },
      reverse: function() {
        return new cc.EaseBackIn(this._inner.reverse());
      },
      clone: function() {
        var action = new cc.EaseBackOut();
        action.initWithAction(this._inner.clone());
        return action;
      }
    });
    cc._easeBackOutObj = {
      easing: function(time1) {
        var overshoot = 1.70158;
        time1 -= 1;
        return time1 * time1 * ((overshoot + 1) * time1 + overshoot) + 1;
      },
      reverse: function() {
        return cc._easeBackInObj;
      }
    };
    cc.easeBackOut = function() {
      return cc._easeBackOutObj;
    };
    cc.EaseBackInOut = cc.ActionEase.extend({
      update: function(dt) {
        var overshoot = 2.5949095;
        dt *= 2;
        if (dt < 1) this._inner.update(dt * dt * ((overshoot + 1) * dt - overshoot) / 2); else {
          dt -= 2;
          this._inner.update(dt * dt * ((overshoot + 1) * dt + overshoot) / 2 + 1);
        }
      },
      clone: function() {
        var action = new cc.EaseBackInOut();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseBackInOut(this._inner.reverse());
      }
    });
    cc._easeBackInOutObj = {
      easing: function(time1) {
        var overshoot = 2.5949095;
        time1 *= 2;
        if (time1 < 1) return time1 * time1 * ((overshoot + 1) * time1 - overshoot) / 2;
        time1 -= 2;
        return time1 * time1 * ((overshoot + 1) * time1 + overshoot) / 2 + 1;
      },
      reverse: function() {
        return cc._easeBackInOutObj;
      }
    };
    cc.easeBackInOut = function() {
      return cc._easeBackInOutObj;
    };
    cc.EaseBezierAction = cc.ActionEase.extend({
      _p0: null,
      _p1: null,
      _p2: null,
      _p3: null,
      ctor: function(action) {
        cc.ActionEase.prototype.ctor.call(this, action);
      },
      _updateTime: function(a, b, c, d, t) {
        return Math.pow(1 - t, 3) * a + 3 * t * Math.pow(1 - t, 2) * b + 3 * Math.pow(t, 2) * (1 - t) * c + Math.pow(t, 3) * d;
      },
      update: function(dt) {
        var t = this._updateTime(this._p0, this._p1, this._p2, this._p3, dt);
        this._inner.update(t);
      },
      clone: function() {
        var action = new cc.EaseBezierAction();
        action.initWithAction(this._inner.clone());
        action.setBezierParamer(this._p0, this._p1, this._p2, this._p3);
        return action;
      },
      reverse: function() {
        var action = new cc.EaseBezierAction(this._inner.reverse());
        action.setBezierParamer(this._p3, this._p2, this._p1, this._p0);
        return action;
      },
      setBezierParamer: function(p0, p1, p2, p3) {
        this._p0 = p0 || 0;
        this._p1 = p1 || 0;
        this._p2 = p2 || 0;
        this._p3 = p3 || 0;
      }
    });
    cc.easeBezierAction = function(p0, p1, p2, p3) {
      return {
        easing: function(time) {
          return cc.EaseBezierAction.prototype._updateTime(p0, p1, p2, p3, time);
        },
        reverse: function() {
          return cc.easeBezierAction(p3, p2, p1, p0);
        }
      };
    };
    cc.EaseQuadraticActionIn = cc.ActionEase.extend({
      _updateTime: function(time) {
        return Math.pow(time, 2);
      },
      update: function(dt) {
        this._inner.update(this._updateTime(dt));
      },
      clone: function() {
        var action = new cc.EaseQuadraticActionIn();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseQuadraticActionIn(this._inner.reverse());
      }
    });
    cc._easeQuadraticActionIn = {
      easing: cc.EaseQuadraticActionIn.prototype._updateTime,
      reverse: function() {
        return cc._easeQuadraticActionIn;
      }
    };
    cc.easeQuadraticActionIn = function() {
      return cc._easeQuadraticActionIn;
    };
    cc.EaseQuadraticActionOut = cc.ActionEase.extend({
      _updateTime: function(time) {
        return -time * (time - 2);
      },
      update: function(dt) {
        this._inner.update(this._updateTime(dt));
      },
      clone: function() {
        var action = new cc.EaseQuadraticActionOut();
        action.initWithAction();
        return action;
      },
      reverse: function() {
        return new cc.EaseQuadraticActionOut(this._inner.reverse());
      }
    });
    cc._easeQuadraticActionOut = {
      easing: cc.EaseQuadraticActionOut.prototype._updateTime,
      reverse: function() {
        return cc._easeQuadraticActionOut;
      }
    };
    cc.easeQuadraticActionOut = function() {
      return cc._easeQuadraticActionOut;
    };
    cc.EaseQuadraticActionInOut = cc.ActionEase.extend({
      _updateTime: function(time) {
        var resultTime = time;
        time *= 2;
        if (time < 1) resultTime = time * time * .5; else {
          --time;
          resultTime = -.5 * (time * (time - 2) - 1);
        }
        return resultTime;
      },
      update: function(dt) {
        this._inner.update(this._updateTime(dt));
      },
      clone: function() {
        var action = new cc.EaseQuadraticActionInOut();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseQuadraticActionInOut(this._inner.reverse());
      }
    });
    cc._easeQuadraticActionInOut = {
      easing: cc.EaseQuadraticActionInOut.prototype._updateTime,
      reverse: function() {
        return cc._easeQuadraticActionInOut;
      }
    };
    cc.easeQuadraticActionInOut = function() {
      return cc._easeQuadraticActionInOut;
    };
    cc.EaseQuarticActionIn = cc.ActionEase.extend({
      _updateTime: function(time) {
        return time * time * time * time;
      },
      update: function(dt) {
        this._inner.update(this._updateTime(dt));
      },
      clone: function() {
        var action = new cc.EaseQuarticActionIn();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseQuarticActionIn(this._inner.reverse());
      }
    });
    cc._easeQuarticActionIn = {
      easing: cc.EaseQuarticActionIn.prototype._updateTime,
      reverse: function() {
        return cc._easeQuarticActionIn;
      }
    };
    cc.easeQuarticActionIn = function() {
      return cc._easeQuarticActionIn;
    };
    cc.EaseQuarticActionOut = cc.ActionEase.extend({
      _updateTime: function(time) {
        time -= 1;
        return -(time * time * time * time - 1);
      },
      update: function(dt) {
        this._inner.update(this._updateTime(dt));
      },
      clone: function() {
        var action = new cc.EaseQuarticActionOut();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseQuarticActionOut(this._inner.reverse());
      }
    });
    cc._easeQuarticActionOut = {
      easing: cc.EaseQuarticActionOut.prototype._updateTime,
      reverse: function() {
        return cc._easeQuarticActionOut;
      }
    };
    cc.easeQuarticActionOut = function() {
      return cc._easeQuarticActionOut;
    };
    cc.EaseQuarticActionInOut = cc.ActionEase.extend({
      _updateTime: function(time) {
        time *= 2;
        if (time < 1) return .5 * time * time * time * time;
        time -= 2;
        return -.5 * (time * time * time * time - 2);
      },
      update: function(dt) {
        this._inner.update(this._updateTime(dt));
      },
      clone: function() {
        var action = new cc.EaseQuarticActionInOut();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseQuarticActionInOut(this._inner.reverse());
      }
    });
    cc._easeQuarticActionInOut = {
      easing: cc.EaseQuarticActionInOut.prototype._updateTime,
      reverse: function() {
        return cc._easeQuarticActionInOut;
      }
    };
    cc.easeQuarticActionInOut = function() {
      return cc._easeQuarticActionInOut;
    };
    cc.EaseQuinticActionIn = cc.ActionEase.extend({
      _updateTime: function(time) {
        return time * time * time * time * time;
      },
      update: function(dt) {
        this._inner.update(this._updateTime(dt));
      },
      clone: function() {
        var action = new cc.EaseQuinticActionIn();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseQuinticActionIn(this._inner.reverse());
      }
    });
    cc._easeQuinticActionIn = {
      easing: cc.EaseQuinticActionIn.prototype._updateTime,
      reverse: function() {
        return cc._easeQuinticActionIn;
      }
    };
    cc.easeQuinticActionIn = function() {
      return cc._easeQuinticActionIn;
    };
    cc.EaseQuinticActionOut = cc.ActionEase.extend({
      _updateTime: function(time) {
        time -= 1;
        return time * time * time * time * time + 1;
      },
      update: function(dt) {
        this._inner.update(this._updateTime(dt));
      },
      clone: function() {
        var action = new cc.EaseQuinticActionOut();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseQuinticActionOut(this._inner.reverse());
      }
    });
    cc._easeQuinticActionOut = {
      easing: cc.EaseQuinticActionOut.prototype._updateTime,
      reverse: function() {
        return cc._easeQuinticActionOut;
      }
    };
    cc.easeQuinticActionOut = function() {
      return cc._easeQuinticActionOut;
    };
    cc.EaseQuinticActionInOut = cc.ActionEase.extend({
      _updateTime: function(time) {
        time *= 2;
        if (time < 1) return .5 * time * time * time * time * time;
        time -= 2;
        return .5 * (time * time * time * time * time + 2);
      },
      update: function(dt) {
        this._inner.update(this._updateTime(dt));
      },
      clone: function() {
        var action = new cc.EaseQuinticActionInOut();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseQuinticActionInOut(this._inner.reverse());
      }
    });
    cc._easeQuinticActionInOut = {
      easing: cc.EaseQuinticActionInOut.prototype._updateTime,
      reverse: function() {
        return cc._easeQuinticActionInOut;
      }
    };
    cc.easeQuinticActionInOut = function() {
      return cc._easeQuinticActionInOut;
    };
    cc.EaseCircleActionIn = cc.ActionEase.extend({
      _updateTime: function(time) {
        return -1 * (Math.sqrt(1 - time * time) - 1);
      },
      update: function(dt) {
        this._inner.update(this._updateTime(dt));
      },
      clone: function() {
        var action = new cc.EaseCircleActionIn();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseCircleActionIn(this._inner.reverse());
      }
    });
    cc._easeCircleActionIn = {
      easing: cc.EaseCircleActionIn.prototype._updateTime,
      reverse: function() {
        return cc._easeCircleActionIn;
      }
    };
    cc.easeCircleActionIn = function() {
      return cc._easeCircleActionIn;
    };
    cc.EaseCircleActionOut = cc.ActionEase.extend({
      _updateTime: function(time) {
        time -= 1;
        return Math.sqrt(1 - time * time);
      },
      update: function(dt) {
        this._inner.update(this._updateTime(dt));
      },
      clone: function() {
        var action = new cc.EaseCircleActionOut();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseCircleActionOut(this._inner.reverse());
      }
    });
    cc._easeCircleActionOut = {
      easing: cc.EaseCircleActionOut.prototype._updateTime,
      reverse: function() {
        return cc._easeCircleActionOut;
      }
    };
    cc.easeCircleActionOut = function() {
      return cc._easeCircleActionOut;
    };
    cc.EaseCircleActionInOut = cc.ActionEase.extend({
      _updateTime: function(time) {
        time *= 2;
        if (time < 1) return -.5 * (Math.sqrt(1 - time * time) - 1);
        time -= 2;
        return .5 * (Math.sqrt(1 - time * time) + 1);
      },
      update: function(dt) {
        this._inner.update(this._updateTime(dt));
      },
      clone: function() {
        var action = new cc.EaseCircleActionInOut();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseCircleActionInOut(this._inner.reverse());
      }
    });
    cc._easeCircleActionInOut = {
      easing: cc.EaseCircleActionInOut.prototype._updateTime,
      reverse: function() {
        return cc._easeCircleActionInOut;
      }
    };
    cc.easeCircleActionInOut = function() {
      return cc._easeCircleActionInOut;
    };
    cc.EaseCubicActionIn = cc.ActionEase.extend({
      _updateTime: function(time) {
        return time * time * time;
      },
      update: function(dt) {
        this._inner.update(this._updateTime(dt));
      },
      clone: function() {
        var action = new cc.EaseCubicActionIn();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseCubicActionIn(this._inner.reverse());
      }
    });
    cc._easeCubicActionIn = {
      easing: cc.EaseCubicActionIn.prototype._updateTime,
      reverse: function() {
        return cc._easeCubicActionIn;
      }
    };
    cc.easeCubicActionIn = function() {
      return cc._easeCubicActionIn;
    };
    cc.EaseCubicActionOut = cc.ActionEase.extend({
      _updateTime: function(time) {
        time -= 1;
        return time * time * time + 1;
      },
      update: function(dt) {
        this._inner.update(this._updateTime(dt));
      },
      clone: function() {
        var action = new cc.EaseCubicActionOut();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseCubicActionOut(this._inner.reverse());
      }
    });
    cc._easeCubicActionOut = {
      easing: cc.EaseCubicActionOut.prototype._updateTime,
      reverse: function() {
        return cc._easeCubicActionOut;
      }
    };
    cc.easeCubicActionOut = function() {
      return cc._easeCubicActionOut;
    };
    cc.EaseCubicActionInOut = cc.ActionEase.extend({
      _updateTime: function(time) {
        time *= 2;
        if (time < 1) return .5 * time * time * time;
        time -= 2;
        return .5 * (time * time * time + 2);
      },
      update: function(dt) {
        this._inner.update(this._updateTime(dt));
      },
      clone: function() {
        var action = new cc.EaseCubicActionInOut();
        action.initWithAction(this._inner.clone());
        return action;
      },
      reverse: function() {
        return new cc.EaseCubicActionInOut(this._inner.reverse());
      }
    });
    cc._easeCubicActionInOut = {
      easing: cc.EaseCubicActionInOut.prototype._updateTime,
      reverse: function() {
        return cc._easeCubicActionInOut;
      }
    };
    cc.easeCubicActionInOut = function() {
      return cc._easeCubicActionInOut;
    };
  }), {} ],
  7: [ (function(require, module, exports) {
    cc.ActionInstant = cc.FiniteTimeAction.extend({
      isDone: function() {
        return true;
      },
      step: function(dt) {
        this.update(1);
      },
      update: function(dt) {},
      reverse: function() {
        return this.clone();
      },
      clone: function() {
        return new cc.ActionInstant();
      }
    });
    cc.Show = cc.ActionInstant.extend({
      update: function(dt) {
        var _renderComps = this.target.getComponentsInChildren(cc._SGComponent);
        for (var i = 0; i < _renderComps.length; ++i) {
          var render = _renderComps[i];
          render.enabled = true;
        }
      },
      reverse: function() {
        return new cc.Hide();
      },
      clone: function() {
        return new cc.Show();
      }
    });
    cc.show = function() {
      return new cc.Show();
    };
    cc.Hide = cc.ActionInstant.extend({
      update: function(dt) {
        var _renderComps = this.target.getComponentsInChildren(cc._SGComponent);
        for (var i = 0; i < _renderComps.length; ++i) {
          var render = _renderComps[i];
          render.enabled = false;
        }
      },
      reverse: function() {
        return new cc.Show();
      },
      clone: function() {
        return new cc.Hide();
      }
    });
    cc.hide = function() {
      return new cc.Hide();
    };
    cc.ToggleVisibility = cc.ActionInstant.extend({
      update: function(dt) {
        var _renderComps = this.target.getComponentsInChildren(cc._SGComponent);
        for (var i = 0; i < _renderComps.length; ++i) {
          var render = _renderComps[i];
          render.enabled = !render.enabled;
        }
      },
      reverse: function() {
        return new cc.ToggleVisibility();
      },
      clone: function() {
        return new cc.ToggleVisibility();
      }
    });
    cc.toggleVisibility = function() {
      return new cc.ToggleVisibility();
    };
    cc.RemoveSelf = cc.ActionInstant.extend({
      _isNeedCleanUp: true,
      ctor: function(isNeedCleanUp) {
        cc.FiniteTimeAction.prototype.ctor.call(this);
        void 0 !== isNeedCleanUp && this.init(isNeedCleanUp);
      },
      update: function(dt) {
        this.target.removeFromParent(this._isNeedCleanUp);
      },
      init: function(isNeedCleanUp) {
        this._isNeedCleanUp = isNeedCleanUp;
        return true;
      },
      reverse: function() {
        return new cc.RemoveSelf(this._isNeedCleanUp);
      },
      clone: function() {
        return new cc.RemoveSelf(this._isNeedCleanUp);
      }
    });
    cc.removeSelf = function(isNeedCleanUp) {
      return new cc.RemoveSelf(isNeedCleanUp);
    };
    cc.FlipX = cc.ActionInstant.extend({
      _flippedX: false,
      ctor: function(flip) {
        cc.FiniteTimeAction.prototype.ctor.call(this);
        this._flippedX = false;
        void 0 !== flip && this.initWithFlipX(flip);
      },
      initWithFlipX: function(flip) {
        this._flippedX = flip;
        return true;
      },
      update: function(dt) {
        this.target.scaleX = Math.abs(this.target.scaleX) * (this._flippedX ? -1 : 1);
      },
      reverse: function() {
        return new cc.FlipX(!this._flippedX);
      },
      clone: function() {
        var action = new cc.FlipX();
        action.initWithFlipX(this._flippedX);
        return action;
      }
    });
    cc.flipX = function(flip) {
      return new cc.FlipX(flip);
    };
    cc.FlipY = cc.ActionInstant.extend({
      _flippedY: false,
      ctor: function(flip) {
        cc.FiniteTimeAction.prototype.ctor.call(this);
        this._flippedY = false;
        void 0 !== flip && this.initWithFlipY(flip);
      },
      initWithFlipY: function(flip) {
        this._flippedY = flip;
        return true;
      },
      update: function(dt) {
        this.target.scaleY = Math.abs(this.target.scaleY) * (this._flippedY ? -1 : 1);
      },
      reverse: function() {
        return new cc.FlipY(!this._flippedY);
      },
      clone: function() {
        var action = new cc.FlipY();
        action.initWithFlipY(this._flippedY);
        return action;
      }
    });
    cc.flipY = function(flip) {
      return new cc.FlipY(flip);
    };
    cc.Place = cc.ActionInstant.extend({
      _x: 0,
      _y: 0,
      ctor: function(pos, y) {
        cc.FiniteTimeAction.prototype.ctor.call(this);
        this._x = 0;
        this._y = 0;
        if (void 0 !== pos) {
          if (void 0 !== pos.x) {
            y = pos.y;
            pos = pos.x;
          }
          this.initWithPosition(pos, y);
        }
      },
      initWithPosition: function(x, y) {
        this._x = x;
        this._y = y;
        return true;
      },
      update: function(dt) {
        this.target.setPosition(this._x, this._y);
      },
      clone: function() {
        var action = new cc.Place();
        action.initWithPosition(this._x, this._y);
        return action;
      }
    });
    cc.place = function(pos, y) {
      return new cc.Place(pos, y);
    };
    cc.CallFunc = cc.ActionInstant.extend({
      _selectorTarget: null,
      _function: null,
      _data: null,
      ctor: function(selector, selectorTarget, data) {
        cc.FiniteTimeAction.prototype.ctor.call(this);
        this.initWithFunction(selector, selectorTarget, data);
      },
      initWithFunction: function(selector, selectorTarget, data) {
        selector && (this._function = selector);
        selectorTarget && (this._selectorTarget = selectorTarget);
        void 0 !== data && (this._data = data);
        return true;
      },
      execute: function() {
        this._function && this._function.call(this._selectorTarget, this.target, this._data);
      },
      update: function(dt) {
        this.execute();
      },
      getTargetCallback: function() {
        return this._selectorTarget;
      },
      setTargetCallback: function(sel) {
        if (sel !== this._selectorTarget) {
          this._selectorTarget && (this._selectorTarget = null);
          this._selectorTarget = sel;
        }
      },
      clone: function() {
        var action = new cc.CallFunc();
        action.initWithFunction(this._function, this._selectorTarget, this._data);
        return action;
      }
    });
    cc.callFunc = function(selector, selectorTarget, data) {
      return new cc.CallFunc(selector, selectorTarget, data);
    };
  }), {} ],
  8: [ (function(require, module, exports) {
    cc.ActionInterval = cc.FiniteTimeAction.extend({
      _elapsed: 0,
      _firstTick: false,
      _easeList: null,
      _timesForRepeat: 1,
      _repeatForever: false,
      _repeatMethod: false,
      _speed: 1,
      _speedMethod: false,
      ctor: function(d) {
        this._speed = 1;
        this._timesForRepeat = 1;
        this._repeatForever = false;
        this.MAX_VALUE = 2;
        this._repeatMethod = false;
        this._speedMethod = false;
        cc.FiniteTimeAction.prototype.ctor.call(this);
        void 0 !== d && this.initWithDuration(d);
      },
      getElapsed: function() {
        return this._elapsed;
      },
      initWithDuration: function(d) {
        this._duration = 0 === d ? cc.macro.FLT_EPSILON : d;
        this._elapsed = 0;
        this._firstTick = true;
        return true;
      },
      isDone: function() {
        return this._elapsed >= this._duration;
      },
      _cloneDecoration: function(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;
      },
      _reverseEaseList: function(action) {
        if (this._easeList) {
          action._easeList = [];
          for (var i = 0; i < this._easeList.length; i++) action._easeList.push(this._easeList[i].reverse());
        }
      },
      clone: function() {
        var action = new cc.ActionInterval(this._duration);
        this._cloneDecoration(action);
        return action;
      },
      easing: function(easeObj) {
        this._easeList ? this._easeList.length = 0 : this._easeList = [];
        for (var i = 0; i < arguments.length; i++) this._easeList.push(arguments[i]);
        return this;
      },
      _computeEaseTime: function(dt) {
        var locList = this._easeList;
        if (!locList || 0 === locList.length) return dt;
        for (var i = 0, n = locList.length; i < n; i++) dt = locList[i].easing(dt);
        return dt;
      },
      step: function(dt) {
        if (this._firstTick) {
          this._firstTick = false;
          this._elapsed = 0;
        } else this._elapsed += dt;
        var t = this._elapsed / (this._duration > 1.192092896e-7 ? this._duration : 1.192092896e-7);
        t = 1 > t ? t : 1;
        this.update(t > 0 ? t : 0);
        if (this._repeatMethod && this._timesForRepeat > 1 && this.isDone()) {
          this._repeatForever || this._timesForRepeat--;
          this.startWithTarget(this.target);
          this.step(this._elapsed - this._duration);
        }
      },
      startWithTarget: function(target) {
        cc.Action.prototype.startWithTarget.call(this, target);
        this._elapsed = 0;
        this._firstTick = true;
      },
      reverse: function() {
        cc.logID(1010);
        return null;
      },
      setAmplitudeRate: function(amp) {
        cc.logID(1011);
      },
      getAmplitudeRate: function() {
        cc.logID(1012);
        return 0;
      },
      speed: function(speed) {
        if (speed <= 0) {
          cc.logID(1013);
          return this;
        }
        this._speedMethod = true;
        this._speed *= speed;
        return this;
      },
      getSpeed: function() {
        return this._speed;
      },
      setSpeed: function(speed) {
        this._speed = speed;
        return this;
      },
      repeat: function(times) {
        times = Math.round(times);
        if (isNaN(times) || times < 1) {
          cc.logID(1014);
          return this;
        }
        this._repeatMethod = true;
        this._timesForRepeat *= times;
        return this;
      },
      repeatForever: function() {
        this._repeatMethod = true;
        this._timesForRepeat = this.MAX_VALUE;
        this._repeatForever = true;
        return this;
      }
    });
    cc.actionInterval = function(d) {
      return new cc.ActionInterval(d);
    };
    cc.Sequence = cc.ActionInterval.extend({
      _actions: null,
      _split: null,
      _last: 0,
      _reversed: false,
      ctor: function(tempArray) {
        cc.ActionInterval.prototype.ctor.call(this);
        this._actions = [];
        var paramArray = tempArray instanceof Array ? tempArray : arguments;
        if (1 === paramArray.length) {
          cc.errorID(1019);
          return;
        }
        var last = paramArray.length - 1;
        last >= 0 && null == paramArray[last] && cc.logID(1015);
        if (last >= 0) {
          var prev = paramArray[0], action1;
          for (var i = 1; i < last; i++) if (paramArray[i]) {
            action1 = prev;
            prev = cc.Sequence._actionOneTwo(action1, paramArray[i]);
          }
          this.initWithTwoActions(prev, paramArray[last]);
        }
      },
      initWithTwoActions: function(actionOne, actionTwo) {
        if (!actionOne || !actionTwo) throw new Error("cc.Sequence.initWithTwoActions(): arguments must all be non nil");
        var d = actionOne._duration + actionTwo._duration;
        this.initWithDuration(d);
        this._actions[0] = actionOne;
        this._actions[1] = actionTwo;
        return true;
      },
      clone: function() {
        var action = new cc.Sequence();
        this._cloneDecoration(action);
        action.initWithTwoActions(this._actions[0].clone(), this._actions[1].clone());
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        this._split = this._actions[0]._duration / this._duration;
        this._last = -1;
      },
      stop: function() {
        -1 !== this._last && this._actions[this._last].stop();
        cc.Action.prototype.stop.call(this);
      },
      update: function(dt) {
        var new_t, found = 0;
        var locSplit = this._split, locActions = this._actions, locLast = this._last, actionFound;
        dt = this._computeEaseTime(dt);
        if (dt < locSplit) {
          new_t = 0 !== locSplit ? dt / locSplit : 1;
          if (0 === found && 1 === locLast && this._reversed) {
            locActions[1].update(0);
            locActions[1].stop();
          }
        } else {
          found = 1;
          new_t = 1 === locSplit ? 1 : (dt - locSplit) / (1 - locSplit);
          if (-1 === locLast) {
            locActions[0].startWithTarget(this.target);
            locActions[0].update(1);
            locActions[0].stop();
          }
          if (0 === locLast) {
            locActions[0].update(1);
            locActions[0].stop();
          }
        }
        actionFound = locActions[found];
        if (locLast === found && actionFound.isDone()) return;
        locLast !== found && actionFound.startWithTarget(this.target);
        new_t *= actionFound._timesForRepeat;
        actionFound.update(new_t > 1 ? new_t % 1 : new_t);
        this._last = found;
      },
      reverse: function() {
        var action = cc.Sequence._actionOneTwo(this._actions[1].reverse(), this._actions[0].reverse());
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        action._reversed = true;
        return action;
      }
    });
    cc.sequence = function(tempArray) {
      var paramArray = tempArray instanceof Array ? tempArray : arguments;
      if (1 === paramArray.length) {
        cc.errorID(1019);
        return null;
      }
      var last = paramArray.length - 1;
      last >= 0 && null == paramArray[last] && cc.logID(1015);
      var result = null;
      if (last >= 0) {
        result = paramArray[0];
        for (var i = 1; i <= last; i++) paramArray[i] && (result = cc.Sequence._actionOneTwo(result, paramArray[i]));
      }
      return result;
    };
    cc.Sequence._actionOneTwo = function(actionOne, actionTwo) {
      var sequence = new cc.Sequence();
      sequence.initWithTwoActions(actionOne, actionTwo);
      return sequence;
    };
    cc.Repeat = cc.ActionInterval.extend({
      _times: 0,
      _total: 0,
      _nextDt: 0,
      _actionInstant: false,
      _innerAction: null,
      ctor: function(action, times) {
        cc.ActionInterval.prototype.ctor.call(this);
        void 0 !== times && this.initWithAction(action, times);
      },
      initWithAction: function(action, times) {
        var duration = action._duration * times;
        if (this.initWithDuration(duration)) {
          this._times = times;
          this._innerAction = action;
          if (action instanceof cc.ActionInstant) {
            this._actionInstant = true;
            this._times -= 1;
          }
          this._total = 0;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.Repeat();
        this._cloneDecoration(action);
        action.initWithAction(this._innerAction.clone(), this._times);
        return action;
      },
      startWithTarget: function(target) {
        this._total = 0;
        this._nextDt = this._innerAction._duration / this._duration;
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        this._innerAction.startWithTarget(target);
      },
      stop: function() {
        this._innerAction.stop();
        cc.Action.prototype.stop.call(this);
      },
      update: function(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;
          }
          if (dt >= 1 && this._total < locTimes) {
            locInnerAction.update(1);
            this._total++;
          }
          this._actionInstant || (this._total === locTimes ? locInnerAction.stop() : locInnerAction.update(dt - (locNextDt - locInnerAction._duration / locDuration)));
        } else locInnerAction.update(dt * locTimes % 1);
      },
      isDone: function() {
        return this._total === this._times;
      },
      reverse: function() {
        var action = new cc.Repeat(this._innerAction.reverse(), this._times);
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        return action;
      },
      setInnerAction: function(action) {
        this._innerAction !== action && (this._innerAction = action);
      },
      getInnerAction: function() {
        return this._innerAction;
      }
    });
    cc.repeat = function(action, times) {
      return new cc.Repeat(action, times);
    };
    cc.RepeatForever = cc.ActionInterval.extend({
      _innerAction: null,
      ctor: function(action) {
        cc.ActionInterval.prototype.ctor.call(this);
        this._innerAction = null;
        action && this.initWithAction(action);
      },
      initWithAction: function(action) {
        if (!action) throw new Error("cc.RepeatForever.initWithAction(): action must be non null");
        this._innerAction = action;
        return true;
      },
      clone: function() {
        var action = new cc.RepeatForever();
        this._cloneDecoration(action);
        action.initWithAction(this._innerAction.clone());
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        this._innerAction.startWithTarget(target);
      },
      step: function(dt) {
        var locInnerAction = this._innerAction;
        locInnerAction.step(dt);
        if (locInnerAction.isDone()) {
          locInnerAction.startWithTarget(this.target);
          locInnerAction.step(locInnerAction.getElapsed() - locInnerAction._duration);
        }
      },
      isDone: function() {
        return false;
      },
      reverse: function() {
        var action = new cc.RepeatForever(this._innerAction.reverse());
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        return action;
      },
      setInnerAction: function(action) {
        this._innerAction !== action && (this._innerAction = action);
      },
      getInnerAction: function() {
        return this._innerAction;
      }
    });
    cc.repeatForever = function(action) {
      return new cc.RepeatForever(action);
    };
    cc.Spawn = cc.ActionInterval.extend({
      _one: null,
      _two: null,
      ctor: function(tempArray) {
        cc.ActionInterval.prototype.ctor.call(this);
        this._one = null;
        this._two = null;
        var paramArray = tempArray instanceof Array ? tempArray : arguments;
        if (1 === paramArray.length) {
          cc.errorID(1020);
          return;
        }
        var last = paramArray.length - 1;
        last >= 0 && null == paramArray[last] && cc.logID(1015);
        if (last >= 0) {
          var prev = paramArray[0], action1;
          for (var i = 1; i < last; i++) if (paramArray[i]) {
            action1 = prev;
            prev = cc.Spawn._actionOneTwo(action1, paramArray[i]);
          }
          this.initWithTwoActions(prev, paramArray[last]);
        }
      },
      initWithTwoActions: function(action1, action2) {
        if (!action1 || !action2) throw new Error("cc.Spawn.initWithTwoActions(): arguments must all be non null");
        var ret = false;
        var d1 = action1._duration;
        var d2 = action2._duration;
        if (this.initWithDuration(Math.max(d1, d2))) {
          this._one = action1;
          this._two = action2;
          d1 > d2 ? this._two = cc.Sequence._actionOneTwo(action2, cc.delayTime(d1 - d2)) : d1 < d2 && (this._one = cc.Sequence._actionOneTwo(action1, cc.delayTime(d2 - d1)));
          ret = true;
        }
        return ret;
      },
      clone: function() {
        var action = new cc.Spawn();
        this._cloneDecoration(action);
        action.initWithTwoActions(this._one.clone(), this._two.clone());
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        this._one.startWithTarget(target);
        this._two.startWithTarget(target);
      },
      stop: function() {
        this._one.stop();
        this._two.stop();
        cc.Action.prototype.stop.call(this);
      },
      update: function(dt) {
        dt = this._computeEaseTime(dt);
        this._one && this._one.update(dt);
        this._two && this._two.update(dt);
      },
      reverse: function() {
        var action = cc.Spawn._actionOneTwo(this._one.reverse(), this._two.reverse());
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        return action;
      }
    });
    cc.spawn = function(tempArray) {
      var paramArray = tempArray instanceof Array ? tempArray : arguments;
      if (1 === paramArray.length) {
        cc.errorID(1020);
        return null;
      }
      paramArray.length > 0 && null == paramArray[paramArray.length - 1] && cc.logID(1015);
      var prev = paramArray[0];
      for (var i = 1; i < paramArray.length; i++) null != paramArray[i] && (prev = cc.Spawn._actionOneTwo(prev, paramArray[i]));
      return prev;
    };
    cc.Spawn._actionOneTwo = function(action1, action2) {
      var pSpawn = new cc.Spawn();
      pSpawn.initWithTwoActions(action1, action2);
      return pSpawn;
    };
    cc.RotateTo = cc.ActionInterval.extend({
      _dstAngleX: 0,
      _startAngleX: 0,
      _diffAngleX: 0,
      _dstAngleY: 0,
      _startAngleY: 0,
      _diffAngleY: 0,
      ctor: function(duration, deltaAngleX, deltaAngleY) {
        cc.ActionInterval.prototype.ctor.call(this);
        void 0 !== deltaAngleX && this.initWithDuration(duration, deltaAngleX, deltaAngleY);
      },
      initWithDuration: function(duration, deltaAngleX, deltaAngleY) {
        if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
          this._dstAngleX = deltaAngleX || 0;
          this._dstAngleY = void 0 !== deltaAngleY ? deltaAngleY : this._dstAngleX;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.RotateTo();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._dstAngleX, this._dstAngleY);
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        var locStartAngleX = target.rotationX % 360;
        var locDiffAngleX = this._dstAngleX - locStartAngleX;
        locDiffAngleX > 180 && (locDiffAngleX -= 360);
        locDiffAngleX < -180 && (locDiffAngleX += 360);
        this._startAngleX = locStartAngleX;
        this._diffAngleX = locDiffAngleX;
        this._startAngleY = target.rotationY % 360;
        var locDiffAngleY = this._dstAngleY - this._startAngleY;
        locDiffAngleY > 180 && (locDiffAngleY -= 360);
        locDiffAngleY < -180 && (locDiffAngleY += 360);
        this._diffAngleY = locDiffAngleY;
      },
      reverse: function() {
        cc.logID(1016);
      },
      update: function(dt) {
        dt = this._computeEaseTime(dt);
        if (this.target) {
          this.target.rotationX = this._startAngleX + this._diffAngleX * dt;
          this.target.rotationY = this._startAngleY + this._diffAngleY * dt;
        }
      }
    });
    cc.rotateTo = function(duration, deltaAngleX, deltaAngleY) {
      return new cc.RotateTo(duration, deltaAngleX, deltaAngleY);
    };
    cc.RotateBy = cc.ActionInterval.extend({
      _angleX: 0,
      _startAngleX: 0,
      _angleY: 0,
      _startAngleY: 0,
      ctor: function(duration, deltaAngleX, deltaAngleY) {
        cc.ActionInterval.prototype.ctor.call(this);
        void 0 !== deltaAngleX && this.initWithDuration(duration, deltaAngleX, deltaAngleY);
      },
      initWithDuration: function(duration, deltaAngleX, deltaAngleY) {
        if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
          this._angleX = deltaAngleX || 0;
          this._angleY = void 0 !== deltaAngleY ? deltaAngleY : this._angleX;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.RotateBy();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._angleX, this._angleY);
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        this._startAngleX = target.rotationX;
        this._startAngleY = target.rotationY;
      },
      update: function(dt) {
        dt = this._computeEaseTime(dt);
        if (this.target) {
          this.target.rotationX = this._startAngleX + this._angleX * dt;
          this.target.rotationY = this._startAngleY + this._angleY * dt;
        }
      },
      reverse: function() {
        var action = new cc.RotateBy(this._duration, -this._angleX, -this._angleY);
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        return action;
      }
    });
    cc.rotateBy = function(duration, deltaAngleX, deltaAngleY) {
      return new cc.RotateBy(duration, deltaAngleX, deltaAngleY);
    };
    cc.MoveBy = cc.ActionInterval.extend({
      _positionDelta: null,
      _startPosition: null,
      _previousPosition: null,
      ctor: function(duration, deltaPos, deltaY) {
        cc.ActionInterval.prototype.ctor.call(this);
        this._positionDelta = cc.p(0, 0);
        this._startPosition = cc.p(0, 0);
        this._previousPosition = cc.p(0, 0);
        void 0 !== deltaPos && this.initWithDuration(duration, deltaPos, deltaY);
      },
      initWithDuration: function(duration, position, y) {
        if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
          if (void 0 !== position.x) {
            y = position.y;
            position = position.x;
          }
          this._positionDelta.x = position;
          this._positionDelta.y = y;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.MoveBy();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._positionDelta);
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        var locPosX = target.getPositionX();
        var locPosY = target.getPositionY();
        this._previousPosition.x = locPosX;
        this._previousPosition.y = locPosY;
        this._startPosition.x = locPosX;
        this._startPosition.y = locPosY;
      },
      update: function(dt) {
        dt = this._computeEaseTime(dt);
        if (this.target) {
          var x = this._positionDelta.x * dt;
          var y = this._positionDelta.y * dt;
          var locStartPosition = this._startPosition;
          if (cc.macro.ENABLE_STACKABLE_ACTIONS) {
            var targetX = this.target.getPositionX();
            var targetY = this.target.getPositionY();
            var locPreviousPosition = this._previousPosition;
            locStartPosition.x = locStartPosition.x + targetX - locPreviousPosition.x;
            locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y;
            x += locStartPosition.x;
            y += locStartPosition.y;
            locPreviousPosition.x = x;
            locPreviousPosition.y = y;
            this.target.setPosition(x, y);
          } else this.target.setPosition(locStartPosition.x + x, locStartPosition.y + y);
        }
      },
      reverse: function() {
        var action = new cc.MoveBy(this._duration, cc.p(-this._positionDelta.x, -this._positionDelta.y));
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        return action;
      }
    });
    cc.moveBy = function(duration, deltaPos, deltaY) {
      return new cc.MoveBy(duration, deltaPos, deltaY);
    };
    cc.MoveTo = cc.MoveBy.extend({
      _endPosition: null,
      ctor: function(duration, position, y) {
        cc.MoveBy.prototype.ctor.call(this);
        this._endPosition = cc.p(0, 0);
        void 0 !== position && this.initWithDuration(duration, position, y);
      },
      initWithDuration: function(duration, position, y) {
        if (cc.MoveBy.prototype.initWithDuration.call(this, duration, position, y)) {
          if (void 0 !== position.x) {
            y = position.y;
            position = position.x;
          }
          this._endPosition.x = position;
          this._endPosition.y = y;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.MoveTo();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._endPosition);
        return action;
      },
      startWithTarget: function(target) {
        cc.MoveBy.prototype.startWithTarget.call(this, target);
        this._positionDelta.x = this._endPosition.x - target.getPositionX();
        this._positionDelta.y = this._endPosition.y - target.getPositionY();
      }
    });
    cc.moveTo = function(duration, position, y) {
      return new cc.MoveTo(duration, position, y);
    };
    cc.SkewTo = cc.ActionInterval.extend({
      _skewX: 0,
      _skewY: 0,
      _startSkewX: 0,
      _startSkewY: 0,
      _endSkewX: 0,
      _endSkewY: 0,
      _deltaX: 0,
      _deltaY: 0,
      ctor: function(t, sx, sy) {
        cc.ActionInterval.prototype.ctor.call(this);
        void 0 !== sy && this.initWithDuration(t, sx, sy);
      },
      initWithDuration: function(t, sx, sy) {
        var ret = false;
        if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) {
          this._endSkewX = sx;
          this._endSkewY = sy;
          ret = true;
        }
        return ret;
      },
      clone: function() {
        var action = new cc.SkewTo();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._endSkewX, this._endSkewY);
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        this._startSkewX = target.skewX % 180;
        this._deltaX = this._endSkewX - this._startSkewX;
        this._deltaX > 180 && (this._deltaX -= 360);
        this._deltaX < -180 && (this._deltaX += 360);
        this._startSkewY = target.skewY % 360;
        this._deltaY = this._endSkewY - this._startSkewY;
        this._deltaY > 180 && (this._deltaY -= 360);
        this._deltaY < -180 && (this._deltaY += 360);
      },
      update: function(dt) {
        dt = this._computeEaseTime(dt);
        this.target.skewX = this._startSkewX + this._deltaX * dt;
        this.target.skewY = this._startSkewY + this._deltaY * dt;
      }
    });
    cc.skewTo = function(t, sx, sy) {
      return new cc.SkewTo(t, sx, sy);
    };
    cc.SkewBy = cc.SkewTo.extend({
      ctor: function(t, sx, sy) {
        cc.SkewTo.prototype.ctor.call(this);
        void 0 !== sy && this.initWithDuration(t, sx, sy);
      },
      initWithDuration: function(t, deltaSkewX, deltaSkewY) {
        var ret = false;
        if (cc.SkewTo.prototype.initWithDuration.call(this, t, deltaSkewX, deltaSkewY)) {
          this._skewX = deltaSkewX;
          this._skewY = deltaSkewY;
          ret = true;
        }
        return ret;
      },
      clone: function() {
        var action = new cc.SkewBy();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._skewX, this._skewY);
        return action;
      },
      startWithTarget: function(target) {
        cc.SkewTo.prototype.startWithTarget.call(this, target);
        this._deltaX = this._skewX;
        this._deltaY = this._skewY;
        this._endSkewX = this._startSkewX + this._deltaX;
        this._endSkewY = this._startSkewY + this._deltaY;
      },
      reverse: function() {
        var action = new cc.SkewBy(this._duration, -this._skewX, -this._skewY);
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        return action;
      }
    });
    cc.skewBy = function(t, sx, sy) {
      return new cc.SkewBy(t, sx, sy);
    };
    cc.JumpBy = cc.ActionInterval.extend({
      _startPosition: null,
      _delta: null,
      _height: 0,
      _jumps: 0,
      _previousPosition: null,
      ctor: function(duration, position, y, height, jumps) {
        cc.ActionInterval.prototype.ctor.call(this);
        this._startPosition = cc.p(0, 0);
        this._previousPosition = cc.p(0, 0);
        this._delta = cc.p(0, 0);
        void 0 !== height && this.initWithDuration(duration, position, y, height, jumps);
      },
      initWithDuration: function(duration, position, y, height, jumps) {
        if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
          if (void 0 === jumps) {
            jumps = height;
            height = y;
            y = position.y;
            position = position.x;
          }
          this._delta.x = position;
          this._delta.y = y;
          this._height = height;
          this._jumps = jumps;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.JumpBy();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._delta, this._height, this._jumps);
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        var locPosX = target.getPositionX();
        var locPosY = target.getPositionY();
        this._previousPosition.x = locPosX;
        this._previousPosition.y = locPosY;
        this._startPosition.x = locPosX;
        this._startPosition.y = locPosY;
      },
      update: function(dt) {
        dt = this._computeEaseTime(dt);
        if (this.target) {
          var frac = dt * this._jumps % 1;
          var y = 4 * this._height * frac * (1 - frac);
          y += this._delta.y * dt;
          var x = this._delta.x * dt;
          var locStartPosition = this._startPosition;
          if (cc.macro.ENABLE_STACKABLE_ACTIONS) {
            var targetX = this.target.getPositionX();
            var targetY = this.target.getPositionY();
            var locPreviousPosition = this._previousPosition;
            locStartPosition.x = locStartPosition.x + targetX - locPreviousPosition.x;
            locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y;
            x += locStartPosition.x;
            y += locStartPosition.y;
            locPreviousPosition.x = x;
            locPreviousPosition.y = y;
            this.target.setPosition(x, y);
          } else this.target.setPosition(locStartPosition.x + x, locStartPosition.y + y);
        }
      },
      reverse: function() {
        var action = new cc.JumpBy(this._duration, cc.p(-this._delta.x, -this._delta.y), this._height, this._jumps);
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        return action;
      }
    });
    cc.jumpBy = function(duration, position, y, height, jumps) {
      return new cc.JumpBy(duration, position, y, height, jumps);
    };
    cc.JumpTo = cc.JumpBy.extend({
      _endPosition: null,
      ctor: function(duration, position, y, height, jumps) {
        cc.JumpBy.prototype.ctor.call(this);
        this._endPosition = cc.p(0, 0);
        void 0 !== height && this.initWithDuration(duration, position, y, height, jumps);
      },
      initWithDuration: function(duration, position, y, height, jumps) {
        if (cc.JumpBy.prototype.initWithDuration.call(this, duration, position, y, height, jumps)) {
          if (void 0 === jumps) {
            y = position.y;
            position = position.x;
          }
          this._endPosition.x = position;
          this._endPosition.y = y;
          return true;
        }
        return false;
      },
      startWithTarget: function(target) {
        cc.JumpBy.prototype.startWithTarget.call(this, target);
        this._delta.x = this._endPosition.x - this._startPosition.x;
        this._delta.y = this._endPosition.y - this._startPosition.y;
      },
      clone: function() {
        var action = new cc.JumpTo();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._endPosition, this._height, this._jumps);
        return action;
      }
    });
    cc.jumpTo = function(duration, position, y, height, jumps) {
      return new cc.JumpTo(duration, position, y, height, jumps);
    };
    cc.bezierAt = function(a, b, c, d, t) {
      return Math.pow(1 - t, 3) * a + 3 * t * Math.pow(1 - t, 2) * b + 3 * Math.pow(t, 2) * (1 - t) * c + Math.pow(t, 3) * d;
    };
    cc.BezierBy = cc.ActionInterval.extend({
      _config: null,
      _startPosition: null,
      _previousPosition: null,
      ctor: function(t, c) {
        cc.ActionInterval.prototype.ctor.call(this);
        this._config = [];
        this._startPosition = cc.p(0, 0);
        this._previousPosition = cc.p(0, 0);
        c && this.initWithDuration(t, c);
      },
      initWithDuration: function(t, c) {
        if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) {
          this._config = c;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.BezierBy();
        this._cloneDecoration(action);
        var newConfigs = [];
        for (var i = 0; i < this._config.length; i++) {
          var selConf = this._config[i];
          newConfigs.push(cc.p(selConf.x, selConf.y));
        }
        action.initWithDuration(this._duration, newConfigs);
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        var locPosX = target.getPositionX();
        var locPosY = target.getPositionY();
        this._previousPosition.x = locPosX;
        this._previousPosition.y = locPosY;
        this._startPosition.x = locPosX;
        this._startPosition.y = locPosY;
      },
      update: function(dt) {
        dt = this._computeEaseTime(dt);
        if (this.target) {
          var locConfig = this._config;
          var xa = 0;
          var xb = locConfig[0].x;
          var xc = locConfig[1].x;
          var xd = locConfig[2].x;
          var ya = 0;
          var yb = locConfig[0].y;
          var yc = locConfig[1].y;
          var yd = locConfig[2].y;
          var x = cc.bezierAt(xa, xb, xc, xd, dt);
          var y = cc.bezierAt(ya, yb, yc, yd, dt);
          var locStartPosition = this._startPosition;
          if (cc.macro.ENABLE_STACKABLE_ACTIONS) {
            var targetX = this.target.getPositionX();
            var targetY = this.target.getPositionY();
            var locPreviousPosition = this._previousPosition;
            locStartPosition.x = locStartPosition.x + targetX - locPreviousPosition.x;
            locStartPosition.y = locStartPosition.y + targetY - locPreviousPosition.y;
            x += locStartPosition.x;
            y += locStartPosition.y;
            locPreviousPosition.x = x;
            locPreviousPosition.y = y;
            this.target.setPosition(x, y);
          } else this.target.setPosition(locStartPosition.x + x, locStartPosition.y + y);
        }
      },
      reverse: function() {
        var locConfig = this._config;
        var r = [ cc.pAdd(locConfig[1], cc.pNeg(locConfig[2])), cc.pAdd(locConfig[0], cc.pNeg(locConfig[2])), cc.pNeg(locConfig[2]) ];
        var action = new cc.BezierBy(this._duration, r);
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        return action;
      }
    });
    cc.bezierBy = function(t, c) {
      return new cc.BezierBy(t, c);
    };
    cc.BezierTo = cc.BezierBy.extend({
      _toConfig: null,
      ctor: function(t, c) {
        cc.BezierBy.prototype.ctor.call(this);
        this._toConfig = [];
        c && this.initWithDuration(t, c);
      },
      initWithDuration: function(t, c) {
        if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) {
          this._toConfig = c;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.BezierTo();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._toConfig);
        return action;
      },
      startWithTarget: function(target) {
        cc.BezierBy.prototype.startWithTarget.call(this, target);
        var locStartPos = this._startPosition;
        var locToConfig = this._toConfig;
        var locConfig = this._config;
        locConfig[0] = cc.pSub(locToConfig[0], locStartPos);
        locConfig[1] = cc.pSub(locToConfig[1], locStartPos);
        locConfig[2] = cc.pSub(locToConfig[2], locStartPos);
      }
    });
    cc.bezierTo = function(t, c) {
      return new cc.BezierTo(t, c);
    };
    cc.ScaleTo = cc.ActionInterval.extend({
      _scaleX: 1,
      _scaleY: 1,
      _startScaleX: 1,
      _startScaleY: 1,
      _endScaleX: 0,
      _endScaleY: 0,
      _deltaX: 0,
      _deltaY: 0,
      ctor: function(duration, sx, sy) {
        cc.ActionInterval.prototype.ctor.call(this);
        void 0 !== sx && this.initWithDuration(duration, sx, sy);
      },
      initWithDuration: function(duration, sx, sy) {
        if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
          this._endScaleX = sx;
          this._endScaleY = null != sy ? sy : sx;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.ScaleTo();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._endScaleX, this._endScaleY);
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        this._startScaleX = target.scaleX;
        this._startScaleY = target.scaleY;
        this._deltaX = this._endScaleX - this._startScaleX;
        this._deltaY = this._endScaleY - this._startScaleY;
      },
      update: function(dt) {
        dt = this._computeEaseTime(dt);
        if (this.target) {
          this.target.scaleX = this._startScaleX + this._deltaX * dt;
          this.target.scaleY = this._startScaleY + this._deltaY * dt;
        }
      }
    });
    cc.scaleTo = function(duration, sx, sy) {
      return new cc.ScaleTo(duration, sx, sy);
    };
    cc.ScaleBy = cc.ScaleTo.extend({
      startWithTarget: function(target) {
        cc.ScaleTo.prototype.startWithTarget.call(this, target);
        this._deltaX = this._startScaleX * this._endScaleX - this._startScaleX;
        this._deltaY = this._startScaleY * this._endScaleY - this._startScaleY;
      },
      reverse: function() {
        var action = new cc.ScaleBy(this._duration, 1 / this._endScaleX, 1 / this._endScaleY);
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        return action;
      },
      clone: function() {
        var action = new cc.ScaleBy();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._endScaleX, this._endScaleY);
        return action;
      }
    });
    cc.scaleBy = function(duration, sx, sy) {
      return new cc.ScaleBy(duration, sx, sy);
    };
    cc.Blink = cc.ActionInterval.extend({
      _times: 0,
      _originalState: false,
      ctor: function(duration, blinks) {
        cc.ActionInterval.prototype.ctor.call(this);
        void 0 !== blinks && this.initWithDuration(duration, blinks);
      },
      initWithDuration: function(duration, blinks) {
        if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
          this._times = blinks;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.Blink();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._times);
        return action;
      },
      update: function(dt) {
        dt = this._computeEaseTime(dt);
        if (this.target && !this.isDone()) {
          var slice = 1 / this._times;
          var m = dt % slice;
          this.target.opacity = m > slice / 2 ? 255 : 0;
        }
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        this._originalState = target.opacity;
      },
      stop: function() {
        this.target.opacity = this._originalState;
        cc.ActionInterval.prototype.stop.call(this);
      },
      reverse: function() {
        var action = new cc.Blink(this._duration, this._times);
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        return action;
      }
    });
    cc.blink = function(duration, blinks) {
      return new cc.Blink(duration, blinks);
    };
    cc.FadeTo = cc.ActionInterval.extend({
      _toOpacity: 0,
      _fromOpacity: 0,
      ctor: function(duration, opacity) {
        cc.ActionInterval.prototype.ctor.call(this);
        void 0 !== opacity && this.initWithDuration(duration, opacity);
      },
      initWithDuration: function(duration, opacity) {
        if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
          this._toOpacity = opacity;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.FadeTo();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._toOpacity);
        return action;
      },
      update: function(time) {
        time = this._computeEaseTime(time);
        var fromOpacity = void 0 !== this._fromOpacity ? this._fromOpacity : 255;
        this.target.opacity = fromOpacity + (this._toOpacity - fromOpacity) * time;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        this._fromOpacity = target.opacity;
      }
    });
    cc.fadeTo = function(duration, opacity) {
      return new cc.FadeTo(duration, opacity);
    };
    cc.FadeIn = cc.FadeTo.extend({
      _reverseAction: null,
      ctor: function(duration) {
        cc.FadeTo.prototype.ctor.call(this);
        null == duration && (duration = 0);
        this.initWithDuration(duration, 255);
      },
      reverse: function() {
        var action = new cc.FadeOut();
        action.initWithDuration(this._duration, 0);
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        return action;
      },
      clone: function() {
        var action = new cc.FadeIn();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._toOpacity);
        return action;
      },
      startWithTarget: function(target) {
        this._reverseAction && (this._toOpacity = this._reverseAction._fromOpacity);
        cc.FadeTo.prototype.startWithTarget.call(this, target);
      }
    });
    cc.fadeIn = function(duration) {
      return new cc.FadeIn(duration);
    };
    cc.FadeOut = cc.FadeTo.extend({
      ctor: function(duration) {
        cc.FadeTo.prototype.ctor.call(this);
        null == duration && (duration = 0);
        this.initWithDuration(duration, 0);
      },
      reverse: function() {
        var action = new cc.FadeIn();
        action._reverseAction = this;
        action.initWithDuration(this._duration, 255);
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        return action;
      },
      clone: function() {
        var action = new cc.FadeOut();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._toOpacity);
        return action;
      }
    });
    cc.fadeOut = function(d) {
      return new cc.FadeOut(d);
    };
    cc.TintTo = cc.ActionInterval.extend({
      _to: null,
      _from: null,
      ctor: function(duration, red, green, blue) {
        cc.ActionInterval.prototype.ctor.call(this);
        this._to = cc.color(0, 0, 0);
        this._from = cc.color(0, 0, 0);
        if (red instanceof cc.Color) {
          blue = red.b;
          green = red.g;
          red = red.r;
        }
        void 0 !== blue && this.initWithDuration(duration, red, green, blue);
      },
      initWithDuration: function(duration, red, green, blue) {
        if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
          this._to = cc.color(red, green, blue);
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.TintTo();
        this._cloneDecoration(action);
        var locTo = this._to;
        action.initWithDuration(this._duration, locTo.r, locTo.g, locTo.b);
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        this._from = this.target.color;
      },
      update: function(dt) {
        dt = this._computeEaseTime(dt);
        var locFrom = this._from, locTo = this._to;
        locFrom && this.target.setColor(cc.color(locFrom.r + (locTo.r - locFrom.r) * dt, locFrom.g + (locTo.g - locFrom.g) * dt, locFrom.b + (locTo.b - locFrom.b) * dt));
      }
    });
    cc.tintTo = function(duration, red, green, blue) {
      return new cc.TintTo(duration, red, green, blue);
    };
    cc.TintBy = cc.ActionInterval.extend({
      _deltaR: 0,
      _deltaG: 0,
      _deltaB: 0,
      _fromR: 0,
      _fromG: 0,
      _fromB: 0,
      ctor: function(duration, deltaRed, deltaGreen, deltaBlue) {
        cc.ActionInterval.prototype.ctor.call(this);
        void 0 !== deltaBlue && this.initWithDuration(duration, deltaRed, deltaGreen, deltaBlue);
      },
      initWithDuration: function(duration, deltaRed, deltaGreen, deltaBlue) {
        if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
          this._deltaR = deltaRed;
          this._deltaG = deltaGreen;
          this._deltaB = deltaBlue;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.TintBy();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration, this._deltaR, this._deltaG, this._deltaB);
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        var color = target.color;
        this._fromR = color.r;
        this._fromG = color.g;
        this._fromB = color.b;
      },
      update: function(dt) {
        dt = this._computeEaseTime(dt);
        this.target.color = cc.color(this._fromR + this._deltaR * dt, this._fromG + this._deltaG * dt, this._fromB + this._deltaB * dt);
      },
      reverse: function() {
        var action = new cc.TintBy(this._duration, -this._deltaR, -this._deltaG, -this._deltaB);
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        return action;
      }
    });
    cc.tintBy = function(duration, deltaRed, deltaGreen, deltaBlue) {
      return new cc.TintBy(duration, deltaRed, deltaGreen, deltaBlue);
    };
    cc.DelayTime = cc.ActionInterval.extend({
      update: function(dt) {},
      reverse: function() {
        var action = new cc.DelayTime(this._duration);
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        return action;
      },
      clone: function() {
        var action = new cc.DelayTime();
        this._cloneDecoration(action);
        action.initWithDuration(this._duration);
        return action;
      }
    });
    cc.delayTime = function(d) {
      return new cc.DelayTime(d);
    };
    cc.ReverseTime = cc.ActionInterval.extend({
      _other: null,
      ctor: function(action) {
        cc.ActionInterval.prototype.ctor.call(this);
        this._other = null;
        action && this.initWithAction(action);
      },
      initWithAction: function(action) {
        if (!action) throw new Error("cc.ReverseTime.initWithAction(): action must be non null");
        if (action === this._other) throw new Error("cc.ReverseTime.initWithAction(): the action was already passed in.");
        if (cc.ActionInterval.prototype.initWithDuration.call(this, action._duration)) {
          this._other = action;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.ReverseTime();
        this._cloneDecoration(action);
        action.initWithAction(this._other.clone());
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        this._other.startWithTarget(target);
      },
      update: function(dt) {
        dt = this._computeEaseTime(dt);
        this._other && this._other.update(1 - dt);
      },
      reverse: function() {
        return this._other.clone();
      },
      stop: function() {
        this._other.stop();
        cc.Action.prototype.stop.call(this);
      }
    });
    cc.reverseTime = function(action) {
      return new cc.ReverseTime(action);
    };
    cc.Animate = cc.ActionInterval.extend({
      _animation: null,
      _nextFrame: 0,
      _origFrame: null,
      _executedLoops: 0,
      _splitTimes: null,
      _currFrameIndex: 0,
      ctor: function(animation) {
        cc.ActionInterval.prototype.ctor.call(this);
        this._splitTimes = [];
        animation && this.initWithAnimation(animation);
      },
      getAnimation: function() {
        return this._animation;
      },
      setAnimation: function(animation) {
        this._animation = animation;
      },
      getCurrentFrameIndex: function() {
        return this._currFrameIndex;
      },
      initWithAnimation: function(animation) {
        if (!animation) throw new Error("cc.Animate.initWithAnimation(): animation must be non-NULL");
        var singleDuration = animation.getDuration();
        if (this.initWithDuration(singleDuration * animation.getLoops())) {
          this._nextFrame = 0;
          this.setAnimation(animation);
          this._origFrame = null;
          this._executedLoops = 0;
          var locTimes = this._splitTimes;
          locTimes.length = 0;
          var accumUnitsOfTime = 0;
          var newUnitOfTimeValue = singleDuration / animation.getTotalDelayUnits();
          var frames = animation.getFrames();
          cc.js.array.verifyType(frames, cc.AnimationFrame);
          for (var i = 0; i < frames.length; i++) {
            var frame = frames[i];
            var value = accumUnitsOfTime * newUnitOfTimeValue / singleDuration;
            accumUnitsOfTime += frame.getDelayUnits();
            locTimes.push(value);
          }
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.Animate();
        this._cloneDecoration(action);
        action.initWithAnimation(this._animation.clone());
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        this._animation.getRestoreOriginalFrame() && (this._origFrame = target.getSpriteFrame());
        this._nextFrame = 0;
        this._executedLoops = 0;
      },
      update: function(dt) {
        dt = this._computeEaseTime(dt);
        if (dt < 1) {
          dt *= this._animation.getLoops();
          var loopNumber = 0 | dt;
          if (loopNumber > this._executedLoops) {
            this._nextFrame = 0;
            this._executedLoops++;
          }
          dt %= 1;
        }
        var frames = this._animation.getFrames();
        var numberOfFrames = frames.length, locSplitTimes = this._splitTimes;
        for (var i = this._nextFrame; i < numberOfFrames; i++) {
          if (!(locSplitTimes[i] <= dt)) break;
          _currFrameIndex = i;
          this.target.setSpriteFrame(frames[_currFrameIndex].getSpriteFrame());
          this._nextFrame = i + 1;
        }
      },
      reverse: function() {
        var locAnimation = this._animation;
        var oldArray = locAnimation.getFrames();
        var newArray = [];
        cc.js.array.verifyType(oldArray, cc.AnimationFrame);
        if (oldArray.length > 0) for (var i = oldArray.length - 1; i >= 0; i--) {
          var element = oldArray[i];
          if (!element) break;
          newArray.push(element.clone());
        }
        var newAnim = new cc.SpriteFrameAnimation(newArray, locAnimation.getDelayPerUnit(), locAnimation.getLoops());
        newAnim.setRestoreOriginalFrame(locAnimation.getRestoreOriginalFrame());
        var action = new cc.Animate(newAnim);
        this._cloneDecoration(action);
        this._reverseEaseList(action);
        return action;
      },
      stop: function() {
        this._animation.getRestoreOriginalFrame() && this.target && this.target.setSpriteFrame(this._origFrame);
        cc.Action.prototype.stop.call(this);
      }
    });
    cc.animate = function(animation) {
      return new cc.Animate(animation);
    };
    cc.TargetedAction = cc.ActionInterval.extend({
      _action: null,
      _forcedTarget: null,
      ctor: function(target, action) {
        cc.ActionInterval.prototype.ctor.call(this);
        action && this.initWithTarget(target, action);
      },
      initWithTarget: function(target, action) {
        if (this.initWithDuration(action._duration)) {
          this._forcedTarget = target;
          this._action = action;
          return true;
        }
        return false;
      },
      clone: function() {
        var action = new cc.TargetedAction();
        this._cloneDecoration(action);
        action.initWithTarget(this._forcedTarget, this._action.clone());
        return action;
      },
      startWithTarget: function(target) {
        cc.ActionInterval.prototype.startWithTarget.call(this, target);
        this._action.startWithTarget(this._forcedTarget);
      },
      stop: function() {
        this._action.stop();
      },
      update: function(dt) {
        dt = this._computeEaseTime(dt);
        this._action.update(dt);
      },
      getForcedTarget: function() {
        return this._forcedTarget;
      },
      setForcedTarget: function(forcedTarget) {
        this._forcedTarget !== forcedTarget && (this._forcedTarget = forcedTarget);
      }
    });
    cc.targetedAction = function(target, action) {
      return new cc.TargetedAction(target, action);
    };
  }), {} ],
  9: [ (function(require, module, exports) {
    var HashElement = function() {
      this.actions = [];
      this.target = null;
      this.actionIndex = 0;
      this.currentAction = null;
      this.paused = false;
      this.lock = false;
    };
    cc.ActionManager = cc._Class.extend({
      _elementPool: [],
      _searchElementByTarget: function(arr, target) {
        for (var k = 0; k < arr.length; k++) if (target === arr[k].target) return arr[k];
        return null;
      },
      ctor: function() {
        this._hashTargets = {};
        this._arrayTargets = [];
        this._currentTarget = null;
      },
      _getElement: function(target, paused) {
        var element = this._elementPool.pop();
        element || (element = new HashElement());
        element.target = target;
        element.paused = !!paused;
        return element;
      },
      _putElement: function(element) {
        element.actions.length = 0;
        element.actionIndex = 0;
        element.currentAction = null;
        element.paused = false;
        element.target = null;
        element.lock = false;
        this._elementPool.push(element);
      },
      addAction: function(action, target, paused) {
        if (!action) throw new Error("cc.ActionManager.addAction(): action must be non-null");
        if (!target) throw new Error("cc.ActionManager.addAction(): action must be non-null");
        var element = this._hashTargets[target.__instanceId];
        if (element) element.actions || (element.actions = []); else {
          element = this._getElement(target, paused);
          this._hashTargets[target.__instanceId] = element;
          this._arrayTargets.push(element);
        }
        element.actions.push(action);
        action.startWithTarget(target);
      },
      removeAllActions: function() {
        var locTargets = this._arrayTargets;
        for (var i = 0; i < locTargets.length; i++) {
          var element = locTargets[i];
          element && this.removeAllActionsFromTarget(element.target, true);
        }
      },
      removeAllActionsFromTarget: function(target, forceDelete) {
        if (null == target) return;
        var element = this._hashTargets[target.__instanceId];
        if (element) {
          element.actions.length = 0;
          this._deleteHashElement(element);
        }
      },
      removeAction: function(action) {
        if (null == action) return;
        var target = action.getOriginalTarget();
        var element = this._hashTargets[target.__instanceId];
        if (element) {
          for (var i = 0; i < element.actions.length; i++) if (element.actions[i] === action) {
            element.actions.splice(i, 1);
            element.actionIndex >= i && element.actionIndex--;
            break;
          }
        } else cc.logID(1001);
      },
      removeActionByTag: function(tag, target) {
        tag === cc.Action.TAG_INVALID && cc.logID(1002);
        cc.assertID(target, 1003);
        var element = this._hashTargets[target.__instanceId];
        if (element) {
          var limit = element.actions.length;
          for (var i = 0; i < limit; ++i) {
            var action = element.actions[i];
            if (action && action.getTag() === tag && action.getOriginalTarget() === target) {
              this._removeActionAtIndex(i, element);
              break;
            }
          }
        }
      },
      getActionByTag: function(tag, target) {
        tag === cc.Action.TAG_INVALID && cc.logID(1004);
        var element = this._hashTargets[target.__instanceId];
        if (element) {
          if (null != element.actions) for (var i = 0; i < element.actions.length; ++i) {
            var action = element.actions[i];
            if (action && action.getTag() === tag) return action;
          }
          cc.logID(1005, tag);
        }
        return null;
      },
      getNumberOfRunningActionsInTarget: function(target) {
        var element = this._hashTargets[target.__instanceId];
        if (element) return element.actions ? element.actions.length : 0;
        return 0;
      },
      pauseTarget: function(target) {
        var element = this._hashTargets[target.__instanceId];
        element && (element.paused = true);
      },
      resumeTarget: function(target) {
        var element = this._hashTargets[target.__instanceId];
        element && (element.paused = false);
      },
      pauseAllRunningActions: function() {
        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;
      },
      resumeTargets: function(targetsToResume) {
        if (!targetsToResume) return;
        for (var i = 0; i < targetsToResume.length; i++) targetsToResume[i] && this.resumeTarget(targetsToResume[i]);
      },
      pauseTargets: function(targetsToPause) {
        if (!targetsToPause) return;
        for (var i = 0; i < targetsToPause.length; i++) targetsToPause[i] && this.pauseTarget(targetsToPause[i]);
      },
      purgeSharedManager: function() {
        cc.director.getScheduler().unscheduleUpdate(this);
      },
      _removeActionAtIndex: function(index, element) {
        var action = element.actions[index];
        element.actions.splice(index, 1);
        element.actionIndex >= index && element.actionIndex--;
        0 === element.actions.length && this._deleteHashElement(element);
      },
      _deleteHashElement: function(element) {
        var ret = false;
        if (element && !element.lock && this._hashTargets[element.target.__instanceId]) {
          delete this._hashTargets[element.target.__instanceId];
          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;
      },
      update: function(dt) {
        var locTargets = this._arrayTargets, locCurrTarget;
        for (var elt = 0; elt < locTargets.length; elt++) {
          this._currentTarget = locTargets[elt];
          locCurrTarget = this._currentTarget;
          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;
          }
          0 === locCurrTarget.actions.length && this._deleteHashElement(locCurrTarget) && elt--;
        }
      }
    });
    false;
  }), {} ],
  10: [ (function(require, module, exports) {
    require("./CCActionManager");
    require("./CCAction");
    require("./CCActionInterval");
    require("./CCActionInstant");
    require("./CCActionEase");
    require("./CCActionCatmullRom");
  }), {
    "./CCAction": 4,
    "./CCActionCatmullRom": 5,
    "./CCActionEase": 6,
    "./CCActionInstant": 7,
    "./CCActionInterval": 8,
    "./CCActionManager": 9
  } ],
  11: [ (function(require, module, exports) {
    var JS = cc.js;
    var Playable = require("./playable");
    var DynamicAnimCurve = require("./animation-curves").DynamicAnimCurve;
    var quickFindIndex = require("./animation-curves").quickFindIndex;
    var sampleMotionPaths = require("./motion-path-helper").sampleMotionPaths;
    var EventAnimCurve = require("./animation-curves").EventAnimCurve;
    var EventInfo = require("./animation-curves").EventInfo;
    var WrapModeMask = require("./types").WrapModeMask;
    var binarySearch = require("../core/utils/binary-search").binarySearchEpsilon;
    function AnimationAnimator(target, animation) {
      Playable.call(this);
      this.target = target;
      this.animation = animation;
      this._anims = new JS.array.MutableForwardIterator([]);
    }
    JS.extend(AnimationAnimator, Playable);
    var p = AnimationAnimator.prototype;
    p.playState = function(state, startTime) {
      if (!state.clip) return;
      state.curveLoaded || initClipData(this.target, state);
      state.animator = this;
      state.play();
      "number" === typeof startTime && state.setTime(startTime);
      this.play();
    };
    p.stopStatesExcept = function(state) {
      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 === state) continue;
        this.stopState(anim);
      }
    };
    p.addAnimation = function(anim) {
      var index = this._anims.array.indexOf(anim);
      -1 === index && this._anims.push(anim);
      anim._setListeners(this.animation);
    };
    p.removeAnimation = function(anim) {
      var index = this._anims.array.indexOf(anim);
      if (index >= 0) {
        this._anims.fastRemoveAt(index);
        0 === this._anims.array.length && this.stop();
      } else cc.errorID(3908);
      anim.animator = null;
    };
    p.sample = function() {
      var iterator = this._anims;
      var array = iterator.array;
      for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
        var anim = array[iterator.i];
        anim.sample();
      }
    };
    p.stopState = function(state) {
      state && state.stop();
    };
    p.pauseState = function(state) {
      state && state.pause();
    };
    p.resumeState = function(state) {
      state && state.resume();
      this.isPaused && this.resume();
    };
    p.setStateTime = function(state, time) {
      if (void 0 !== time) {
        if (state) {
          state.setTime(time);
          state.sample();
        }
      } else {
        time = state;
        var array = this._anims.array;
        for (var i = 0; i < array.length; ++i) {
          var anim = array[i];
          anim.setTime(time);
          anim.sample();
        }
      }
    };
    p.onStop = function() {
      var iterator = this._anims;
      var array = iterator.array;
      for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
        var anim = array[iterator.i];
        anim.stop();
      }
    };
    p.onPause = function() {
      var array = this._anims.array;
      for (var i = 0; i < array.length; ++i) {
        var anim = array[i];
        anim.pause();
        anim.animator = null;
      }
    };
    p.onResume = function() {
      var array = this._anims.array;
      for (var i = 0; i < array.length; ++i) {
        var anim = array[i];
        anim.animator = this;
        anim.resume();
      }
    };
    p._reloadClip = function(state) {
      initClipData(this.target, state);
    };
    function createBatchedProperty(propPath, firstDotIndex, mainValue, animValue) {
      mainValue = mainValue.clone();
      var nextValue = mainValue;
      var leftIndex = firstDotIndex + 1;
      var rightIndex = propPath.indexOf(".", leftIndex);
      while (-1 !== rightIndex) {
        var nextName = propPath.slice(leftIndex, rightIndex);
        nextValue = nextValue[nextName];
        leftIndex = rightIndex + 1;
        rightIndex = propPath.indexOf(".", leftIndex);
      }
      var lastPropName = propPath.slice(leftIndex);
      nextValue[lastPropName] = animValue;
      return mainValue;
    }
    false;
    function splitPropPath(propPath) {
      var array = propPath.split(".");
      array.shift();
      return array.length > 0 ? array : null;
    }
    function initClipData(root, state) {
      var clip = state.clip;
      var curves = state.curves;
      curves.length = 0;
      state.duration = clip.duration;
      state.speed = clip.speed;
      state.wrapMode = clip.wrapMode;
      state.frameRate = clip.sample;
      (state.wrapMode & WrapModeMask.Loop) === WrapModeMask.Loop ? state.repeatCount = Infinity : state.repeatCount = 1;
      function checkMotionPath(motionPath) {
        if (!Array.isArray(motionPath)) return false;
        for (var i = 0, l = motionPath.length; i < l; i++) {
          var controls = motionPath[i];
          if (!Array.isArray(controls) || 6 !== controls.length) return false;
        }
        return true;
      }
      function createPropCurve(target, propPath, keyframes) {
        var isMotionPathProp = target instanceof cc.Node && "position" === propPath;
        var motionPaths = [];
        var curve = new DynamicAnimCurve();
        curve.target = target;
        var propName, propValue;
        var dotIndex = propPath.indexOf(".");
        var hasSubProp = -1 !== dotIndex;
        if (hasSubProp) {
          propName = propPath.slice(0, dotIndex);
          propValue = target[propName];
        } else propName = propPath;
        curve.prop = propName;
        curve.subProps = splitPropPath(propPath);
        for (var i = 0, l = keyframes.length; i < l; i++) {
          var keyframe = keyframes[i];
          var ratio = keyframe.frame / state.duration;
          curve.ratios.push(ratio);
          if (isMotionPathProp) {
            var motionPath = keyframe.motionPath;
            if (motionPath && !checkMotionPath(motionPath)) {
              cc.errorID(3904, target.name, propPath, i);
              motionPath = null;
            }
            motionPaths.push(motionPath);
          }
          var curveValue = keyframe.value;
          curve.values.push(curveValue);
          var curveTypes = keyframe.curve;
          if (curveTypes) {
            if ("string" === typeof curveTypes) {
              curve.types.push(curveTypes);
              continue;
            }
            if (Array.isArray(curveTypes)) {
              curveTypes[0] === curveTypes[1] && curveTypes[2] === curveTypes[3] ? curve.types.push(DynamicAnimCurve.Linear) : curve.types.push(DynamicAnimCurve.Bezier(curveTypes));
              continue;
            }
          }
          curve.types.push(DynamicAnimCurve.Linear);
        }
        isMotionPathProp && sampleMotionPaths(motionPaths, curve, clip.duration, clip.sample);
        var ratios = curve.ratios;
        var currRatioDif, 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 (1 === _i) lastRatioDif = currRatioDif; else if (Math.abs(currRatioDif - lastRatioDif) > EPSILON) {
            canOptimize = false;
            break;
          }
        }
        curve._findFrameIndex = canOptimize ? quickFindIndex : binarySearch;
        return curve;
      }
      function createTargetCurves(target, curveData) {
        var propsData = curveData.props;
        var compsData = curveData.comps;
        if (propsData) for (var propPath in propsData) {
          var data = propsData[propPath];
          var curve = createPropCurve(target, propPath, data);
          curves.push(curve);
        }
        if (compsData) for (var compName in compsData) {
          var comp = target.getComponent(compName);
          if (!comp) continue;
          var compData = compsData[compName];
          for (var propPath in compData) {
            var data = compData[propPath];
            var curve = createPropCurve(comp, propPath, data);
            curves.push(curve);
          }
        }
      }
      var curveData = clip.curveData;
      var childrenCurveDatas = curveData.paths;
      createTargetCurves(root, curveData);
      for (var namePath in childrenCurveDatas) {
        var target = cc.find(namePath, root);
        if (!target) continue;
        var childCurveDatas = childrenCurveDatas[namePath];
        createTargetCurves(target, childCurveDatas);
      }
      var events = clip.events;
      if (true, events) {
        var curve;
        for (var i = 0, l = events.length; i < l; i++) {
          if (!curve) {
            curve = new EventAnimCurve();
            curve.target = root;
            curves.push(curve);
          }
          var eventData = events[i];
          var ratio = eventData.frame / state.duration;
          var eventInfo;
          var index = binarySearch(curve.ratios, ratio);
          if (index >= 0) eventInfo = curve.events[index]; else {
            eventInfo = new EventInfo();
            curve.ratios.push(ratio);
            curve.events.push(eventInfo);
          }
          eventInfo.add(eventData.func, eventData.params);
        }
      }
    }
    false;
    module.exports = AnimationAnimator;
  }), {
    "../core/utils/binary-search": 221,
    "./animation-curves": 13,
    "./motion-path-helper": 19,
    "./playable": 20,
    "./types": 21
  } ],
  12: [ (function(require, module, exports) {
    var AnimationClip = cc.Class({
      name: "cc.AnimationClip",
      extends: cc.Asset,
      properties: {
        _duration: {
          default: 0,
          type: "Float"
        },
        duration: {
          get: function() {
            return this._duration;
          }
        },
        sample: {
          default: 60
        },
        speed: {
          default: 1
        },
        wrapMode: {
          default: cc.WrapMode.Normal
        },
        curveData: {
          default: {},
          visible: false
        },
        events: {
          default: [],
          visible: false
        }
      },
      statics: {
        createWithSpriteFrames: function(spriteFrames, sample) {
          if (!Array.isArray(spriteFrames)) {
            cc.errorID(3905);
            return null;
          }
          var clip = new AnimationClip();
          clip.sample = sample || clip.sample;
          clip._duration = spriteFrames.length / clip.sample;
          var frames = [];
          var step = 1 / clip.sample;
          for (var i = 0, l = spriteFrames.length; i < l; i++) frames[i] = {
            frame: i * step,
            value: spriteFrames[i]
          };
          clip.curveData = {
            comps: {
              "cc.Sprite": {
                spriteFrame: frames
              }
            }
          };
          return clip;
        }
      }
    });
    cc.AnimationClip = module.exports = AnimationClip;
  }), {} ],
  13: [ (function(require, module, exports) {
    var bezierByTime = require("./bezier").bezierByTime;
    var binarySearch = require("../core/utils/binary-search").binarySearchEpsilon;
    var WrapModeMask = require("./types").WrapModeMask;
    var WrappedInfo = require("./types").WrappedInfo;
    function computeRatioByType(ratio, type) {
      if ("string" === typeof type) {
        var func = cc.Easing[type];
        func ? ratio = func(ratio) : cc.errorID(3906, type);
      } else Array.isArray(type) && (ratio = bezierByTime(type, ratio));
      return ratio;
    }
    var AnimCurve = cc.Class({
      name: "cc.AnimCurve",
      sample: function(time, ratio, state) {},
      onTimeChangedManually: void 0
    });
    function quickFindIndex(ratios, ratio) {
      var length = ratios.length - 1;
      if (0 === length) 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 = 0 | index;
      var EPSILON = 1e-6;
      if (index - floorIndex < EPSILON) return floorIndex;
      return ~(floorIndex + 1);
    }
    var DynamicAnimCurve = cc.Class({
      name: "cc.DynamicAnimCurve",
      extends: AnimCurve,
      properties: {
        target: null,
        prop: "",
        values: [],
        ratios: [],
        types: [],
        subProps: null
      },
      _findFrameIndex: binarySearch,
      sample: function(time, ratio, state) {
        var values = this.values;
        var ratios = this.ratios;
        var frameCount = ratios.length;
        if (0 === frameCount) return;
        var value;
        var index = this._findFrameIndex(ratios, ratio);
        if (index < 0) {
          index = ~index;
          if (index <= 0) value = values[0]; else if (index >= frameCount) value = values[frameCount - 1]; else {
            var fromVal = values[index - 1];
            var isNumber = "number" === typeof fromVal;
            var canLerp = fromVal && fromVal.lerp;
            if (isNumber || canLerp) {
              var fromRatio = ratios[index - 1];
              var toRatio = ratios[index];
              var type = this.types[index - 1];
              var ratioBetweenFrames = (ratio - fromRatio) / (toRatio - fromRatio);
              type && (ratioBetweenFrames = computeRatioByType(ratioBetweenFrames, type));
              var toVal = values[index];
              isNumber ? value = fromVal + (toVal - fromVal) * ratioBetweenFrames : canLerp && (value = fromVal.lerp(toVal, ratioBetweenFrames));
            } else value = fromVal;
          }
        } else value = values[index];
        var subProps = this.subProps;
        if (subProps) {
          var mainProp = this.target[this.prop];
          var subProp = mainProp;
          for (var i = 0; i < subProps.length - 1; i++) {
            var subPropName = subProps[i];
            if (!subProp) return;
            subProp = subProp[subPropName];
          }
          var propName = subProps[subProps.length - 1];
          if (!subProp) return;
          subProp[propName] = value;
          value = mainProp;
        }
        this.target[this.prop] = value;
      }
    });
    DynamicAnimCurve.Linear = null;
    DynamicAnimCurve.Bezier = function(controlPoints) {
      return controlPoints;
    };
    var EventInfo = function() {
      this.events = [];
    };
    EventInfo.prototype.add = function(func, params) {
      this.events.push({
        func: func || "",
        params: params || []
      });
    };
    var EventAnimCurve = cc.Class({
      name: "cc.EventAnimCurve",
      extends: AnimCurve,
      properties: {
        target: null,
        ratios: [],
        events: [],
        _wrappedInfo: {
          default: function() {
            return new WrappedInfo();
          }
        },
        _lastWrappedInfo: null,
        _ignoreIndex: NaN
      },
      _wrapIterations: function(iterations) {
        iterations - (0 | iterations) === 0 && (iterations -= 1);
        return 0 | iterations;
      },
      sample: function(time, ratio, state) {
        var length = this.ratios.length;
        var currentWrappedInfo = state.getWrappedInfo(state.time, this._wrappedInfo);
        var direction = currentWrappedInfo.direction;
        var currentIndex = binarySearch(this.ratios, currentWrappedInfo.ratio);
        if (currentIndex < 0) {
          currentIndex = ~currentIndex - 1;
          direction < 0 && (currentIndex += 1);
        }
        this._ignoreIndex !== currentIndex && (this._ignoreIndex = NaN);
        currentWrappedInfo.frameIndex = currentIndex;
        if (!this._lastWrappedInfo) {
          this._fireEvent(currentIndex);
          this._lastWrappedInfo = new WrappedInfo(currentWrappedInfo);
          return;
        }
        var wrapMode = state.wrapMode;
        var currentIterations = this._wrapIterations(currentWrappedInfo.iterations);
        var lastWrappedInfo = this._lastWrappedInfo;
        var lastIterations = this._wrapIterations(lastWrappedInfo.iterations);
        var lastIndex = lastWrappedInfo.frameIndex;
        var lastDirection = lastWrappedInfo.direction;
        var interationsChanged = -1 !== lastIterations && currentIterations !== lastIterations;
        if (lastIndex === currentIndex && interationsChanged && 1 === length) this._fireEvent(0); else if (lastIndex !== currentIndex || interationsChanged) {
          direction = lastDirection;
          do {
            if (lastIndex !== currentIndex) {
              if (-1 === direction && 0 === lastIndex && currentIndex > 0) {
                (wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong ? direction *= -1 : lastIndex = length;
                lastIterations++;
              } else if (1 === direction && lastIndex === length - 1 && currentIndex < length - 1) {
                (wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong ? direction *= -1 : lastIndex = -1;
                lastIterations++;
              }
              if (lastIndex === currentIndex) break;
              if (lastIterations > currentIterations) break;
            }
            lastIndex += direction;
            cc.director.getAnimationManager().pushDelayEvent(this, "_fireEvent", [ lastIndex ]);
          } while (lastIndex !== currentIndex && lastIndex > -1 && lastIndex < length);
        }
        this._lastWrappedInfo.set(currentWrappedInfo);
      },
      _fireEvent: function(index) {
        if (index < 0 || index >= this.events.length || this._ignoreIndex === index) return;
        var eventInfo = this.events[index];
        var events = eventInfo.events;
        if (!this.target.isValid) return;
        var components = this.target._components;
        for (var i = 0; i < events.length; i++) {
          var event = events[i];
          var funcName = event.func;
          for (var j = 0; j < components.length; j++) {
            var component = components[j];
            var func = component[funcName];
            func && func.apply(component, event.params);
          }
        }
      },
      onTimeChangedManually: function(time, state) {
        this._lastWrappedInfo = null;
        this._ignoreIndex = NaN;
        var info = state.getWrappedInfo(time, this._wrappedInfo);
        var direction = info.direction;
        var frameIndex = binarySearch(this.ratios, info.ratio);
        if (frameIndex < 0) {
          frameIndex = ~frameIndex - 1;
          direction < 0 && (frameIndex += 1);
          this._ignoreIndex = frameIndex;
        }
      }
    });
    false;
    module.exports = {
      AnimCurve: AnimCurve,
      DynamicAnimCurve: DynamicAnimCurve,
      EventAnimCurve: EventAnimCurve,
      EventInfo: EventInfo,
      computeRatioByType: computeRatioByType,
      quickFindIndex: quickFindIndex
    };
  }), {
    "../core/utils/binary-search": 221,
    "./bezier": 16,
    "./types": 21
  } ],
  14: [ (function(require, module, exports) {
    var JS = cc.js;
    var AnimationManager = cc.Class({
      ctor: function() {
        this.__instanceId = cc.ClassManager.getNewInstanceId();
        this._anims = new JS.array.MutableForwardIterator([]);
        this._delayEvents = [];
      },
      update: function(dt) {
        var iterator = this._anims;
        var array = iterator.array;
        for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
          var anim = array[iterator.i];
          anim._isPlaying && !anim._isPaused && anim.update(dt);
        }
        var events = this._delayEvents;
        for (i = 0, l = events.length; i < l; i++) {
          var event = events[i];
          event.target[event.func].apply(event.target, event.args);
        }
        events.length = 0;
      },
      destruct: function() {},
      addAnimation: function(anim) {
        var index = this._anims.array.indexOf(anim);
        -1 === index && this._anims.push(anim);
      },
      removeAnimation: function(anim) {
        var index = this._anims.array.indexOf(anim);
        index >= 0 ? this._anims.fastRemoveAt(index) : cc.errorID(3907);
      },
      pushDelayEvent: function(target, func, args) {
        this._delayEvents.push({
          target: target,
          func: func,
          args: args
        });
      }
    });
    cc.AnimationManager = module.exports = AnimationManager;
  }), {} ],
  15: [ (function(require, module, exports) {
    var JS = cc.js;
    var Playable = require("./playable");
    var Types = require("./types");
    var WrappedInfo = Types.WrappedInfo;
    var WrapMode = Types.WrapMode;
    var WrapModeMask = Types.WrapModeMask;
    function AnimationState(clip, name) {
      Playable.call(this);
      cc.EventTarget.call(this);
      this._firstFramePlayed = false;
      this._delay = 0;
      this._delayTime = 0;
      this._wrappedInfo = new WrappedInfo();
      this._lastWrappedInfo = null;
      this._process = process;
      this._clip = clip;
      this._name = name || clip && clip.name;
      this.animator = null;
      this.curves = [];
      this.delay = 0;
      this.repeatCount = 1;
      this.duration = 1;
      this.speed = 1;
      this.wrapMode = WrapMode.Normal;
      this.time = 0;
      this._emit = this.emit;
      this.emit = function() {
        var args = new Array(arguments.length);
        for (var i = 0, l = args.length; i < l; i++) args[i] = arguments[i];
        cc.director.getAnimationManager().pushDelayEvent(this, "_emit", args);
      };
    }
    JS.extend(AnimationState, Playable);
    var proto = AnimationState.prototype;
    cc.js.mixin(proto, cc.EventTarget.prototype);
    proto._setListeners = function(target) {
      this._capturingListeners = target ? target._capturingListeners : null;
      this._bubblingListeners = target ? target._bubblingListeners : null;
      this._hasListenerCache = target ? target._hasListenerCache : null;
    };
    proto.onPlay = function() {
      this.setTime(0);
      this._delayTime = this._delay;
      cc.director.getAnimationManager().addAnimation(this);
      this.animator && this.animator.addAnimation(this);
      this.emit("play", this);
    };
    proto.onStop = function() {
      this.isPaused || cc.director.getAnimationManager().removeAnimation(this);
      this.animator && this.animator.removeAnimation(this);
      this.emit("stop", this);
    };
    proto.onResume = function() {
      cc.director.getAnimationManager().addAnimation(this);
      this.emit("resume", this);
    };
    proto.onPause = function() {
      cc.director.getAnimationManager().removeAnimation(this);
      this.emit("pause", this);
    };
    proto.setTime = function(time) {
      this.time = time || 0;
      var curves = this.curves;
      for (var i = 0, l = curves.length; i < l; i++) {
        var curve = curves[i];
        curve.onTimeChangedManually && curve.onTimeChangedManually(time, this);
      }
    };
    function process() {
      var info = this.sample();
      var cache = this._hasListenerCache;
      if (cache && cache["lastframe"]) {
        var lastInfo;
        lastInfo || (lastInfo = this._lastWrappedInfo = new WrappedInfo(info));
        this.repeatCount > 1 && (0 | info.iterations) > (0 | lastInfo.iterations) && ((this.wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse ? lastInfo.direction < 0 && this.emit("lastframe", this) : lastInfo.direction > 0 && this.emit("lastframe", this));
        lastInfo.set(info);
      }
      if (info.stopped) {
        this.stop();
        this.emit("finished", this);
      }
    }
    function simpleProcess() {
      var time = this.time;
      var duration = this.duration;
      if (time > duration) {
        time %= duration;
        0 === time && (time = duration);
      } else if (time < 0) {
        time %= duration;
        0 !== time && (time += duration);
      }
      var ratio = time / duration;
      var curves = this.curves;
      for (var i = 0, len = curves.length; i < len; i++) {
        var curve = curves[i];
        curve.sample(time, ratio, this);
      }
      var cache = this._hasListenerCache;
      if (cache && cache["lastframe"]) {
        var currentIterations = time > 0 ? time / duration : -time / duration;
        var lastIterations = this._lastIterations;
        void 0 === lastIterations && (lastIterations = this._lastIterations = currentIterations);
        (0 | currentIterations) > (0 | lastIterations) && this.emit("lastframe", this);
        this._lastIterations = currentIterations;
      }
    }
    proto.update = function(delta) {
      if (this._delayTime > 0) {
        this._delayTime -= delta;
        if (this._delayTime > 0) return;
      }
      this._firstFramePlayed ? this.time += delta * this.speed : this._firstFramePlayed = true;
      this._process();
    };
    proto._needRevers = function(currentIterations) {
      var wrapMode = this.wrapMode;
      var needRevers = false;
      if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
        var isEnd = currentIterations - (0 | currentIterations) === 0;
        isEnd && currentIterations > 0 && (currentIterations -= 1);
        var isOddIteration = 1 & currentIterations;
        isOddIteration && (needRevers = !needRevers);
      }
      (wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse && (needRevers = !needRevers);
      return needRevers;
    };
    proto.getWrappedInfo = function(time, info) {
      info = info || new WrappedInfo();
      var stopped = false;
      var duration = this.duration;
      var repeatCount = this.repeatCount;
      var currentIterations = time > 0 ? time / duration : -time / duration;
      if (currentIterations >= repeatCount) {
        currentIterations = repeatCount;
        stopped = true;
        var tempRatio = repeatCount - (0 | repeatCount);
        0 === tempRatio && (tempRatio = 1);
        time = tempRatio * duration * (time > 0 ? 1 : -1);
      }
      if (time > duration) {
        var tempTime = time % duration;
        time = 0 === tempTime ? duration : tempTime;
      } else if (time < 0) {
        time %= duration;
        0 !== time && (time += duration);
      }
      var needRevers = false;
      var shouldWrap = this._wrapMode & WrapModeMask.ShouldWrap;
      shouldWrap && (needRevers = this._needRevers(currentIterations));
      var direction = needRevers ? -1 : 1;
      this.speed < 0 && (direction *= -1);
      shouldWrap && needRevers && (time = duration - time);
      info.ratio = time / duration;
      info.time = time;
      info.direction = direction;
      info.stopped = stopped;
      info.iterations = currentIterations;
      return info;
    };
    proto.sample = function() {
      var info = this.getWrappedInfo(this.time, this._wrappedInfo);
      var curves = this.curves;
      for (var i = 0, len = curves.length; i < len; i++) {
        var curve = curves[i];
        curve.sample(info.time, info.ratio, this);
      }
      return info;
    };
    JS.get(proto, "clip", (function() {
      return this._clip;
    }));
    JS.get(proto, "name", (function() {
      return this._name;
    }));
    JS.obsolete(proto, "AnimationState.length", "duration");
    JS.getset(proto, "curveLoaded", (function() {
      return this.curves.length > 0;
    }), (function() {
      this.curves.length = 0;
    }));
    JS.getset(proto, "wrapMode", (function() {
      return this._wrapMode;
    }), (function(value) {
      this._wrapMode = value;
      false;
      this.time = 0;
      value & WrapModeMask.Loop ? this.repeatCount = Infinity : this.repeatCount = 1;
    }));
    JS.getset(proto, "repeatCount", (function() {
      return this._repeatCount;
    }), (function(value) {
      this._repeatCount = value;
      var shouldWrap = this._wrapMode & WrapModeMask.ShouldWrap;
      var reverse = (this.wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse;
      this._process = Infinity !== value || shouldWrap || reverse ? process : simpleProcess;
    }));
    JS.getset(proto, "delay", (function() {
      return this._delay;
    }), (function(value) {
      this._delayTime = this._delay = value;
    }));
    cc.AnimationState = module.exports = AnimationState;
  }), {
    "./playable": 20,
    "./types": 21
  } ],
  16: [ (function(require, module, exports) {
    function bezier(C1, C2, C3, C4, t) {
      var t1 = 1 - t;
      return C1 * t1 * t1 * t1 + 3 * C2 * t1 * t1 * t + 3 * C3 * t1 * t * t + C4 * t * t * t;
    }
    var cos = Math.cos, acos = Math.acos, max = Math.max, pi = Math.PI, tau = 2 * pi, sqrt = Math.sqrt;
    function crt(v) {
      return v < 0 ? -Math.pow(-v, 1 / 3) : 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 = 3 * pa;
      var pb3 = 3 * pb;
      var pc3 = 3 * pc;
      var d = -pa + pb3 - pc3 + pd, rd = 1 / d, r3 = 1 / 3, a = (pa3 - 6 * pb + pc3) * rd, a3 = a * r3, b = (-pa3 + pb3) * rd, c = pa * rd, p = (3 * b - a * a) * r3, p3 = p * r3, q = (2 * a * a * a - 9 * a * b + 27 * c) / 27, q2 = q / 2, discriminant = q2 * q2 + p3 * p3 * p3, u1, v1, x1, x2, x3;
      if (discriminant < 0) {
        var mp3 = -p * r3, mp33 = mp3 * mp3 * mp3, r = sqrt(mp33), t = -q / (2 * r), cosphi = t < -1 ? -1 : t > 1 ? 1 : t, phi = acos(cosphi), crtr = crt(r), t1 = 2 * crtr;
        x1 = t1 * cos(phi * r3) - a3;
        x2 = t1 * cos((phi + tau) * r3) - a3;
        x3 = t1 * cos((phi + 2 * tau) * r3) - a3;
        return 0 <= x1 && x1 <= 1 ? 0 <= x2 && x2 <= 1 ? 0 <= x3 && x3 <= 1 ? max(x1, x2, x3) : max(x1, x2) : 0 <= x3 && x3 <= 1 ? max(x1, x3) : x1 : 0 <= x2 && x2 <= 1 ? 0 <= x3 && x3 <= 1 ? max(x2, x3) : x2 : x3;
      }
      if (0 === discriminant) {
        u1 = q2 < 0 ? crt(-q2) : -crt(q2);
        x1 = 2 * u1 - a3;
        x2 = -u1 - a3;
        return 0 <= x1 && x1 <= 1 ? 0 <= x2 && x2 <= 1 ? max(x1, x2) : x1 : x2;
      }
      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 p0y = 0;
      var p1y = controlPoints[1];
      var p2y = controlPoints[3];
      var p3y = 1;
      var t1 = 1 - percent;
      return p0y * t1 * t1 * t1 + 3 * p1y * percent * t1 * t1 + 3 * p2y * percent * percent * t1 + p3y * percent * percent * percent;
    }
    false;
    module.exports = {
      bezier: bezier,
      bezierByTime: bezierByTime
    };
  }), {} ],
  17: [ (function(require, module, exports) {
    var Easing = {
      constant: function() {
        return 0;
      },
      linear: function(k) {
        return k;
      },
      quadIn: function(k) {
        return k * k;
      },
      quadOut: function(k) {
        return k * (2 - k);
      },
      quadInOut: function(k) {
        if ((k *= 2) < 1) return .5 * k * k;
        return -.5 * (--k * (k - 2) - 1);
      },
      cubicIn: function(k) {
        return k * k * k;
      },
      cubicOut: function(k) {
        return --k * k * k + 1;
      },
      cubicInOut: function(k) {
        if ((k *= 2) < 1) return .5 * k * k * k;
        return .5 * ((k -= 2) * k * k + 2);
      },
      quartIn: function(k) {
        return k * k * k * k;
      },
      quartOut: function(k) {
        return 1 - --k * k * k * k;
      },
      quartInOut: function(k) {
        if ((k *= 2) < 1) return .5 * k * k * k * k;
        return -.5 * ((k -= 2) * k * k * k - 2);
      },
      quintIn: function(k) {
        return k * k * k * k * k;
      },
      quintOut: function(k) {
        return --k * k * k * k * k + 1;
      },
      quintInOut: function(k) {
        if ((k *= 2) < 1) return .5 * k * k * k * k * k;
        return .5 * ((k -= 2) * k * k * k * k + 2);
      },
      sineIn: function(k) {
        return 1 - Math.cos(k * Math.PI / 2);
      },
      sineOut: function(k) {
        return Math.sin(k * Math.PI / 2);
      },
      sineInOut: function(k) {
        return .5 * (1 - Math.cos(Math.PI * k));
      },
      expoIn: function(k) {
        return 0 === k ? 0 : Math.pow(1024, k - 1);
      },
      expoOut: function(k) {
        return 1 === k ? 1 : 1 - Math.pow(2, -10 * k);
      },
      expoInOut: function(k) {
        if (0 === k) return 0;
        if (1 === k) return 1;
        if ((k *= 2) < 1) return .5 * Math.pow(1024, k - 1);
        return .5 * (2 - Math.pow(2, -10 * (k - 1)));
      },
      circIn: function(k) {
        return 1 - Math.sqrt(1 - k * k);
      },
      circOut: function(k) {
        return Math.sqrt(1 - --k * k);
      },
      circInOut: function(k) {
        if ((k *= 2) < 1) return -.5 * (Math.sqrt(1 - k * k) - 1);
        return .5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
      },
      elasticIn: function(k) {
        var s, a = .1, p = .4;
        if (0 === k) return 0;
        if (1 === k) 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);
      },
      elasticOut: function(k) {
        var s, a = .1, p = .4;
        if (0 === k) return 0;
        if (1 === k) 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;
      },
      elasticInOut: function(k) {
        var s, a = .1, p = .4;
        if (0 === k) return 0;
        if (1 === k) return 1;
        if (!a || a < 1) {
          a = 1;
          s = p / 4;
        } else s = p * Math.asin(1 / a) / (2 * Math.PI);
        if ((k *= 2) < 1) return a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * -.5;
        return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * .5 + 1;
      },
      backIn: function(k) {
        var s = 1.70158;
        return k * k * ((s + 1) * k - s);
      },
      backOut: function(k) {
        var s = 1.70158;
        return --k * k * ((s + 1) * k + s) + 1;
      },
      backInOut: function(k) {
        var s = 2.5949095;
        if ((k *= 2) < 1) return k * k * ((s + 1) * k - s) * .5;
        return .5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
      },
      bounceOut: function(k) {
        return k < 1 / 2.75 ? 7.5625 * k * k : k < 2 / 2.75 ? 7.5625 * (k -= 1.5 / 2.75) * k + .75 : k < 2.5 / 2.75 ? 7.5625 * (k -= 2.25 / 2.75) * k + .9375 : 7.5625 * (k -= 2.625 / 2.75) * k + .984375;
      },
      smooth: function(t) {
        if (t <= 0) return 0;
        if (t >= 1) return 1;
        return t * t * (3 - 2 * t);
      },
      fade: function(t) {
        if (t <= 0) return 0;
        if (t >= 1) return 1;
        return t * t * t * (t * (6 * t - 15) + 10);
      }
    };
    function _makeOutIn(fnIn, fnOut) {
      return function(k) {
        if (k < .5) return fnOut(2 * k) / 2;
        return fnIn(2 * k - 1) / 2 + .5;
      };
    }
    Easing.quadOutIn = _makeOutIn(Easing.quadIn, Easing.quadOut);
    Easing.cubicOutIn = _makeOutIn(Easing.cubicIn, Easing.cubicOut);
    Easing.quartOutIn = _makeOutIn(Easing.quartIn, Easing.quartOut);
    Easing.quintOutIn = _makeOutIn(Easing.quintIn, Easing.quintOut);
    Easing.sineOutIn = _makeOutIn(Easing.sineIn, Easing.sineOut);
    Easing.expoOutIn = _makeOutIn(Easing.expoIn, Easing.expoOut);
    Easing.circOutIn = _makeOutIn(Easing.circIn, Easing.circOut);
    Easing.backOutIn = _makeOutIn(Easing.backIn, Easing.backOut);
    Easing.backOutIn = _makeOutIn(Easing.backIn, Easing.backOut);
    Easing.bounceIn = function(k) {
      return 1 - Easing.bounceOut(1 - k);
    };
    Easing.bounceInOut = function(k) {
      if (k < .5) return .5 * Easing.bounceIn(2 * k);
      return .5 * Easing.bounceOut(2 * k - 1) + .5;
    };
    Easing.bounceOutIn = _makeOutIn(Easing.bounceIn, Easing.bounceOut);
    cc.Easing = module.exports = Easing;
  }), {} ],
  18: [ (function(require, module, exports) {
    require("./bezier");
    require("./easing");
    require("./types");
    require("./motion-path-helper");
    require("./animation-curves");
    require("./animation-clip");
    require("./animation-manager");
    require("./animation-state");
    require("./animation-animator");
  }), {
    "./animation-animator": 11,
    "./animation-clip": 12,
    "./animation-curves": 13,
    "./animation-manager": 14,
    "./animation-state": 15,
    "./bezier": 16,
    "./easing": 17,
    "./motion-path-helper": 19,
    "./types": 21
  } ],
  19: [ (function(require, module, exports) {
    var DynamicAnimCurve = require("./animation-curves").DynamicAnimCurve;
    var computeRatioByType = require("./animation-curves").computeRatioByType;
    var bezier = require("./bezier").bezier;
    var binarySearch = require("../core/utils/binary-search").binarySearchEpsilon;
    var v2 = cc.v2;
    function Curve(points) {
      this.points = points || [];
      this.beziers = [];
      this.ratios = [];
      this.progresses = [];
      this.length = 0;
      this.computeBeziers();
    }
    Curve.prototype.computeBeziers = function() {
      this.beziers.length = 0;
      this.ratios.length = 0;
      this.progresses.length = 0;
      this.length = 0;
      var bezier;
      for (var i = 1; i < this.points.length; i++) {
        var startPoint = this.points[i - 1];
        var endPoint = this.points[i];
        bezier = new Bezier();
        bezier.start = startPoint.pos;
        bezier.startCtrlPoint = startPoint.out;
        bezier.end = endPoint.pos;
        bezier.endCtrlPoint = endPoint.in;
        this.beziers.push(bezier);
        this.length += bezier.getLength();
      }
      var current = 0;
      for (var i = 0; i < this.beziers.length; i++) {
        bezier = this.beziers[i];
        this.ratios[i] = bezier.getLength() / this.length;
        this.progresses[i] = current += this.ratios[i];
      }
      return this.beziers;
    };
    function Bezier() {
      this.start = v2();
      this.end = v2();
      this.startCtrlPoint = v2();
      this.endCtrlPoint = v2();
    }
    Bezier.prototype.getPointAt = function(u) {
      var t = this.getUtoTmapping(u);
      return this.getPoint(t);
    };
    Bezier.prototype.getPoint = function(t) {
      var x = bezier(this.start.x, this.startCtrlPoint.x, this.endCtrlPoint.x, this.end.x, t);
      var y = bezier(this.start.y, this.startCtrlPoint.y, this.endCtrlPoint.y, this.end.y, t);
      return new v2(x, y);
    };
    Bezier.prototype.getLength = function() {
      var lengths = this.getLengths();
      return lengths[lengths.length - 1];
    };
    Bezier.prototype.getLengths = function(divisions) {
      divisions || (divisions = this.__arcLengthDivisions ? this.__arcLengthDivisions : 200);
      if (this.cacheArcLengths && this.cacheArcLengths.length === divisions + 1) return this.cacheArcLengths;
      var cache = [];
      var current, last = this.getPoint(0);
      var p, sum = 0;
      cache.push(0);
      for (p = 1; p <= divisions; p++) {
        current = this.getPoint(p / divisions);
        sum += cc.pDistance(current, last);
        cache.push(sum);
        last = current;
      }
      this.cacheArcLengths = cache;
      return cache;
    };
    Bezier.prototype.getUtoTmapping = function(u, distance) {
      var arcLengths = this.getLengths();
      var i = 0, il = arcLengths.length;
      var targetArcLength;
      targetArcLength = distance || u * arcLengths[il - 1];
      var low = 0, high = il - 1, comparison;
      while (low <= high) {
        i = Math.floor(low + (high - low) / 2);
        comparison = arcLengths[i] - targetArcLength;
        if (comparison < 0) {
          low = i + 1;
          continue;
        }
        if (comparison > 0) {
          high = i - 1;
          continue;
        }
        high = i;
        break;
      }
      i = high;
      if (arcLengths[i] === targetArcLength) {
        var t = i / (il - 1);
        return t;
      }
      var lengthBefore = arcLengths[i];
      var lengthAfter = arcLengths[i + 1];
      var segmentLength = lengthAfter - lengthBefore;
      var segmentFraction = (targetArcLength - lengthBefore) / segmentLength;
      var t = (i + segmentFraction) / (il - 1);
      return t;
    };
    function sampleMotionPaths(motionPaths, data, duration, fps) {
      function createControlPoints(array) {
        if (array instanceof cc.Vec2) return {
          in: array,
          pos: array,
          out: array
        };
        if (Array.isArray(array) && 6 === array.length) return {
          in: v2(array[2], array[3]),
          pos: v2(array[0], array[1]),
          out: v2(array[4], array[5])
        };
        return {
          in: cc.Vec2.ZERO,
          pos: cc.Vec2.ZERO,
          out: cc.Vec2.ZERO
        };
      }
      var values = data.values;
      if (0 === motionPaths.length || 0 === values.length) return;
      values = values.map((function(value) {
        return v2(value[0], value[1]);
      }));
      if (1 === values.length) {
        data.values = values;
        return;
      }
      var types = data.types;
      var ratios = data.ratios;
      var newValues = data.values = [];
      var newTypes = data.types = [];
      var newRatios = data.ratios = [];
      function addNewDatas(value, type, ratio) {
        newValues.push(value);
        newTypes.push(type);
        newRatios.push(ratio);
      }
      var startRatioOffset = 0;
      var EPSILON = 1e-6;
      var newType = DynamicAnimCurve.Linear;
      for (var i = 0, l = motionPaths.length; i < l - 1; i++) {
        var motionPath = motionPaths[i];
        var ratio = ratios[i];
        var nextRatio = ratios[i + 1];
        var betweenRatio = nextRatio - ratio;
        var value = values[i];
        var nextValue = values[i + 1];
        var type = types[i];
        var results = [];
        var progress = startRatioOffset / betweenRatio;
        var speed = 1 / (betweenRatio * duration * fps);
        var finalProgress;
        if (motionPath && motionPath.length > 0) {
          var points = [];
          points.push(createControlPoints(value));
          for (var j = 0, l2 = motionPath.length; j < l2; j++) {
            var controlPoints = createControlPoints(motionPath[j]);
            points.push(controlPoints);
          }
          points.push(createControlPoints(nextValue));
          var curve = new Curve(points);
          curve.computeBeziers();
          var progresses = curve.progresses;
          while (1 - progress > EPSILON) {
            finalProgress = progress;
            finalProgress = computeRatioByType(finalProgress, type);
            var pos, bezier, normal, length;
            if (finalProgress < 0) {
              bezier = curve.beziers[0];
              length = (0 - finalProgress) * bezier.getLength();
              normal = bezier.start.sub(bezier.endCtrlPoint).normalize();
              pos = bezier.start.add(normal.mul(length));
            } else if (finalProgress > 1) {
              bezier = curve.beziers[curve.beziers.length - 1];
              length = (finalProgress - 1) * bezier.getLength();
              normal = bezier.end.sub(bezier.startCtrlPoint).normalize();
              pos = bezier.end.add(normal.mul(length));
            } else {
              var bezierIndex = binarySearch(progresses, finalProgress);
              bezierIndex < 0 && (bezierIndex = ~bezierIndex);
              finalProgress -= bezierIndex > 0 ? progresses[bezierIndex - 1] : 0;
              finalProgress /= curve.ratios[bezierIndex];
              pos = curve.beziers[bezierIndex].getPointAt(finalProgress);
            }
            results.push(pos);
            progress += speed;
          }
        } else while (1 - progress > EPSILON) {
          finalProgress = progress;
          finalProgress = computeRatioByType(finalProgress, type);
          results.push(value.lerp(nextValue, finalProgress));
          progress += speed;
        }
        newType = "constant" === type ? type : DynamicAnimCurve.Linear;
        for (var j = 0, l2 = results.length; j < l2; j++) {
          var newRatio = ratio + startRatioOffset + speed * j * betweenRatio;
          addNewDatas(results[j], newType, newRatio);
        }
        startRatioOffset = Math.abs(progress - 1) > EPSILON ? (progress - 1) * betweenRatio : 0;
      }
      ratios[ratios.length - 1] !== newRatios[newRatios.length - 1] && addNewDatas(values[values.length - 1], newType, ratios[ratios.length - 1]);
    }
    false;
    module.exports = {
      sampleMotionPaths: sampleMotionPaths,
      Curve: Curve,
      Bezier: Bezier
    };
  }), {
    "../core/utils/binary-search": 221,
    "./animation-curves": 13,
    "./bezier": 16
  } ],
  20: [ (function(require, module, exports) {
    var JS = cc.js;
    function Playable() {
      this._isPlaying = false;
      this._isPaused = false;
      this._stepOnce = false;
    }
    var prototype = Playable.prototype;
    JS.get(prototype, "isPlaying", (function() {
      return this._isPlaying;
    }), true);
    JS.get(prototype, "isPaused", (function() {
      return this._isPaused;
    }), true);
    var virtual = function() {};
    prototype.onPlay = virtual;
    prototype.onPause = virtual;
    prototype.onResume = virtual;
    prototype.onStop = virtual;
    prototype.onError = virtual;
    prototype.play = function() {
      if (this._isPlaying) if (this._isPaused) {
        this._isPaused = false;
        this.onResume();
      } else this.onError("already-playing"); else {
        this._isPlaying = true;
        this.onPlay();
      }
    };
    prototype.stop = function() {
      if (this._isPlaying) {
        this._isPlaying = false;
        this.onStop();
        this._isPaused = false;
      }
    };
    prototype.pause = function() {
      if (this._isPlaying && !this._isPaused) {
        this._isPaused = true;
        this.onPause();
      }
    };
    prototype.resume = function() {
      if (this._isPlaying && this._isPaused) {
        this._isPaused = false;
        this.onResume();
      }
    };
    prototype.step = function() {
      this.pause();
      this._stepOnce = true;
      this._isPlaying || this.play();
    };
    module.exports = Playable;
  }), {} ],
  21: [ (function(require, module, exports) {
    var JS = cc.js;
    var WrapModeMask = {
      Loop: 2,
      ShouldWrap: 4,
      PingPong: 22,
      Reverse: 36
    };
    var WrapMode = cc.Enum({
      Default: 0,
      Normal: 1,
      Reverse: WrapModeMask.Reverse,
      Loop: WrapModeMask.Loop,
      LoopReverse: WrapModeMask.Loop | WrapModeMask.Reverse,
      PingPong: WrapModeMask.PingPong,
      PingPongReverse: WrapModeMask.PingPong | WrapModeMask.Reverse
    });
    cc.WrapMode = WrapMode;
    function WrappedInfo(info) {
      if (info) {
        this.set(info);
        return;
      }
      this.ratio = 0;
      this.time = 0;
      this.direction = 1;
      this.stopped = true;
      this.iterations = 0;
      this.frameIndex = void 0;
    }
    WrappedInfo.prototype.set = function(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;
    };
    module.exports = {
      WrapModeMask: WrapModeMask,
      WrapMode: WrapMode,
      WrappedInfo: WrappedInfo
    };
  }), {} ],
  22: [ (function(require, module, exports) {
    var EventTarget = require("../core/event/event-target");
    var sys = require("../core/platform/CCSys");
    var touchBinded = false;
    var touchPlayList = [];
    var Audio = function(src) {
      EventTarget.call(this);
      this._src = src;
      this._audioType = Audio.Type.UNKNOWN;
      this._element = null;
      this._eventList = {};
      this._state = Audio.State.INITIALZING;
      this._loaded = false;
      this._onended = function() {
        this.emit("ended");
      }.bind(this);
    };
    cc.js.extend(Audio, EventTarget);
    Audio.Type = {
      DOM: "AUDIO",
      WEBAUDIO: "WEBAUDIO",
      NATIVE: "NATIVE",
      UNKNOWN: "UNKNOWN"
    };
    Audio.State = {
      ERROR: -1,
      INITIALZING: 0,
      PLAYING: 1,
      PAUSED: 2
    };
    (function(proto) {
      proto.preload = function() {
        var src = this._src, audio = this;
        if (!src) {
          this._src = "";
          this._audioType = Audio.Type.UNKNOWN;
          this._element = null;
          this._state = Audio.State.INITIALZING;
          this._loaded = false;
          return;
        }
        var item = cc.loader.getItem(src);
        item || (item = cc.loader.getItem(src + "?useDom=1"));
        if (!item || !item.complete) return cc.loader.load(src, (function(error) {
          if (!error) {
            var item = cc.loader.getItem(src);
            audio.mount(item.element || item.buffer);
            audio.emit("load");
          }
        }));
        audio.mount(item.element || item.buffer);
        audio.emit("load");
      };
      proto._bindEnded = function(callback) {
        callback = callback || this._onended;
        this._audioType === Audio.Type.DOM ? this._element.addEventListener("ended", callback) : this._element.onended = callback;
      };
      proto._unbindEnded = function() {
        this._audioType === Audio.Type.DOM ? this._element.removeEventListener("ended", this._onended) : this._element.onended = null;
      };
      proto.mount = function(elem) {
        if (sys.platform === sys.WECHAT_GAME || elem instanceof HTMLElement) {
          this._element = document.createElement("audio");
          this._element.src = elem.src;
          this._audioType = Audio.Type.DOM;
        } else {
          this._element = new WebAudioElement(elem, this);
          this._audioType = Audio.Type.WEBAUDIO;
        }
        this._state = Audio.State.INITIALZING;
        this._loaded = true;
      };
      proto.play = function() {
        if (!this._element) return;
        this._bindEnded();
        this._element.play();
        this.emit("play");
        this._state = Audio.State.PLAYING;
        sys.platform !== sys.WECHAT_GAME && this._audioType === Audio.Type.DOM && this._element.paused && touchPlayList.push({
          instance: this,
          offset: 0,
          audio: this._element
        });
        if (touchBinded) return;
        touchBinded = true;
        cc.game.canvas.addEventListener("touchstart", (function() {
          var item;
          while (item = touchPlayList.pop()) item.audio.play(item.offset);
        }));
      };
      proto.pause = function() {
        if (!this._element) return;
        this._unbindEnded();
        this._element.pause();
        this.emit("pause");
        this._state = Audio.State.PAUSED;
      };
      proto.resume = function() {
        if (!this._element || 0 === this._element.currentTime) return;
        this._bindEnded();
        this._element.play();
        this.emit("resume");
        this._state = Audio.State.PLAYING;
      };
      proto.stop = function() {
        if (!this._element) return;
        try {
          this._element.currentTime = 0;
        } catch (error) {}
        this._element.pause();
        for (var i = 0; i < touchPlayList.length; i++) if (touchPlayList[i].instance === this) {
          touchPlayList.splice(i, 1);
          break;
        }
        this._unbindEnded();
        this.emit("stop");
        this._state = Audio.State.PAUSED;
      };
      proto.setLoop = function(loop) {
        if (!this._element) return;
        this._element.loop = loop;
      };
      proto.getLoop = function() {
        return this._element && this._element.loop;
      };
      proto.setVolume = function(num) {
        if (!this._element) return;
        this._element.volume = num;
      };
      proto.getVolume = function() {
        return this._element ? this._element.volume : 1;
      };
      proto.setCurrentTime = function(num) {
        if (!this._element) return;
        this._unbindEnded();
        sys.platform !== sys.WECHAT_GAME && this._bindEnded(function() {
          this._bindEnded();
        }.bind(this));
        try {
          this._element.currentTime = num;
        } catch (err) {
          var _element = this._element;
          if (_element.addEventListener) {
            var func = function() {
              _element.removeEventListener("loadedmetadata", func);
              _element.currentTime = num;
            };
            _element.addEventListener("loadedmetadata", func);
          }
        }
      };
      proto.getCurrentTime = function() {
        return this._element ? this._element.currentTime : 0;
      };
      proto.getDuration = function() {
        return this._element ? this._element.duration : 0;
      };
      proto.getState = function() {
        var elem = this._element;
        Audio.State.PLAYING === this._state && elem.paused && (this._state = Audio.State.PAUSED);
        return this._state;
      };
      proto.__defineGetter__("src", (function() {
        return this._src;
      }));
      proto.__defineSetter__("src", (function(string) {
        return this._src = string;
      }));
      proto.__defineGetter__("paused", (function() {
        return !this._element || this._element.paused;
      }));
    })(Audio.prototype);
    var WebAudioElement = function(buffer, audio) {
      this._audio = audio;
      this._context = sys.__audioSupport.context;
      this._buffer = buffer;
      this._gainObj = this._context["createGain"]();
      this._volume = 1;
      this._gainObj["gain"].setTargetAtTime ? this._gainObj["gain"].setTargetAtTime(this._volume, this._context.currentTime, .01) : this._gainObj["gain"].value = 1;
      this._gainObj["connect"](this._context["destination"]);
      this._loop = false;
      this._startTime = -1;
      this._currentSource = null;
      this.playedLength = 0;
      this._currextTimer = null;
      this._endCallback = function() {
        this.onended && this.onended(this);
      }.bind(this);
    };
    (function(proto) {
      proto.play = function(offset) {
        if (this._currentSource && !this.paused) {
          this._currentSource.onended = null;
          this._currentSource.stop(0);
          this.playedLength = 0;
        }
        var audio = this._context["createBufferSource"]();
        audio.buffer = this._buffer;
        audio["connect"](this._gainObj);
        audio.loop = this._loop;
        this._startTime = this._context.currentTime;
        offset = offset || this.playedLength;
        offset && (this._startTime -= offset);
        var duration = this._buffer.duration;
        var startTime = offset;
        var endTime;
        if (this._loop) audio.start ? audio.start(0, startTime) : audio["notoGrainOn"] ? audio["noteGrainOn"](0, startTime) : audio["noteOn"](0, startTime); else {
          endTime = duration - offset;
          audio.start ? audio.start(0, startTime, endTime) : audio["notoGrainOn"] ? audio["noteGrainOn"](0, startTime, endTime) : audio["noteOn"](0, startTime, endTime);
        }
        this._currentSource = audio;
        audio.onended = this._endCallback;
        if ((!audio.context.state || "suspended" === audio.context.state) && 0 === this._context.currentTime) {
          var self = this;
          clearTimeout(this._currextTimer);
          this._currextTimer = setTimeout((function() {
            sys.platform !== sys.WECHAT_GAME && 0 === self._context.currentTime && touchPlayList.push({
              instance: self._audio,
              offset: offset,
              audio: self
            });
          }), 10);
        }
      };
      proto.pause = function() {
        clearTimeout(this._currextTimer);
        if (this.paused) return;
        this.playedLength = this._context.currentTime - this._startTime;
        this.playedLength %= this._buffer.duration;
        var audio = this._currentSource;
        this._currentSource = null;
        this._startTime = -1;
        audio && audio.stop(0);
      };
      proto.__defineGetter__("paused", (function() {
        if (this._currentSource && this._currentSource.loop) return false;
        if (-1 === this._startTime) return true;
        return this._context.currentTime - this._startTime > this._buffer.duration;
      }));
      proto.__defineGetter__("loop", (function() {
        return this._loop;
      }));
      proto.__defineSetter__("loop", (function(bool) {
        this._currentSource && (this._currentSource.loop = bool);
        return this._loop = bool;
      }));
      proto.__defineGetter__("volume", (function() {
        return this._volume;
      }));
      proto.__defineSetter__("volume", (function(num) {
        this._volume = num;
        this._gainObj["gain"].setTargetAtTime ? this._gainObj["gain"].setTargetAtTime(this._volume, this._context.currentTime, .01) : this._volume["gain"].value = num;
        if (sys.os === sys.OS_IOS && !this.paused && this._currentSource) {
          this._currentSource.onended = null;
          this.pause();
          this.play();
        }
        return num;
      }));
      proto.__defineGetter__("currentTime", (function() {
        if (this.paused) return this.playedLength;
        this.playedLength = this._context.currentTime - this._startTime;
        this.playedLength %= this._buffer.duration;
        return this.playedLength;
      }));
      proto.__defineSetter__("currentTime", (function(num) {
        if (this.paused) this.playedLength = num; else {
          this.pause();
          this.playedLength = num;
          this.play();
        }
        return num;
      }));
      proto.__defineGetter__("duration", (function() {
        return this._buffer.duration;
      }));
    })(WebAudioElement.prototype);
    module.exports = cc.Audio = Audio;
  }), {
    "../core/event/event-target": 112,
    "../core/platform/CCSys": 184
  } ],
  23: [ (function(require, module, exports) {
    var Audio = require("./CCAudio");
    var instanceId = 0;
    var id2audio = {};
    var url2id = {};
    var getAudioFromPath = function(path) {
      var id = instanceId++;
      var list = url2id[path];
      list || (list = url2id[path] = []);
      var audio;
      if (audioEngine._maxAudioInstance <= list.length) {
        var oldId = list.shift();
        var oldAudio = id2audio[oldId];
        oldAudio.stop();
      }
      audio = new Audio(path);
      var callback = function() {
        var id = this.instanceId;
        delete id2audio[id];
        var index = list.indexOf(id);
        cc.js.array.fastRemoveAt(list, index);
      };
      audio.on("ended", callback);
      audio.on("stop", callback);
      id2audio[id] = audio;
      audio.instanceId = id;
      list.push(id);
      return audio;
    };
    var getAudioFromId = function(id) {
      return id2audio[id];
    };
    var audioEngine = {
      AudioState: Audio.State,
      _maxWebAudioSize: 2097152,
      _maxAudioInstance: 24,
      _id2audio: id2audio,
      play: function(filePath, loop, volume) {
        if (true, "string" !== typeof filePath) {
          cc.errorID(8400);
          return;
        }
        var audio = getAudioFromPath(filePath);
        var callback = function() {
          audio.setLoop(loop || false);
          ("number" != typeof volume || isNaN(volume)) && (volume = 1);
          audio.setVolume(volume);
          audio.play();
        };
        audio.__callback = callback;
        audio.on("load", callback);
        audio.preload();
        return audio.instanceId;
      },
      setLoop: function(audioID, loop) {
        var audio = getAudioFromId(audioID);
        if (!audio || !audio.setLoop) return;
        audio.setLoop(loop);
      },
      isLoop: function(audioID) {
        var audio = getAudioFromId(audioID);
        if (!audio || !audio.isLoop) return false;
        return audio.isLoop();
      },
      setVolume: function(audioID, volume) {
        var audio = getAudioFromId(audioID);
        if (!audio) return;
        audio._loaded || audio.once("load", (function() {
          audio.setVolume && audio.setVolume(volume);
        }));
        audio.setVolume && audio.setVolume(volume);
      },
      getVolume: function(audioID) {
        var audio = getAudioFromId(audioID);
        if (!audio || !audio.getVolume) return 1;
        return audio.getVolume();
      },
      setCurrentTime: function(audioID, sec) {
        var audio = getAudioFromId(audioID);
        if (!audio) return false;
        if (!audio._loaded) {
          audio.once("load", (function() {
            audio.setCurrentTime && audio.setCurrentTime(sec);
          }));
          return true;
        }
        audio.setCurrentTime && audio.setCurrentTime(sec);
        return true;
      },
      getCurrentTime: function(audioID) {
        var audio = getAudioFromId(audioID);
        if (!audio || !audio.getCurrentTime) return 0;
        return audio.getCurrentTime();
      },
      getDuration: function(audioID) {
        var audio = getAudioFromId(audioID);
        if (!audio || !audio.getDuration) return 0;
        return audio.getDuration();
      },
      getState: function(audioID) {
        var audio = getAudioFromId(audioID);
        if (!audio || !audio.getState) return this.AudioState.ERROR;
        return audio.getState();
      },
      setFinishCallback: function(audioID, callback) {
        var audio = getAudioFromId(audioID);
        if (!audio) return;
        audio.off("ended", audio._finishCallback);
        audio._finishCallback = callback;
        audio.on("ended", audio._finishCallback);
      },
      pause: function(audioID) {
        var audio = getAudioFromId(audioID);
        if (!audio || !audio.pause) return false;
        audio.pause();
        return true;
      },
      _pauseIDCache: [],
      pauseAll: function() {
        for (var id in id2audio) {
          var audio = id2audio[id];
          var state = audio.getState();
          if (state === Audio.State.PLAYING) {
            this._pauseIDCache.push(id);
            audio.pause();
          }
        }
      },
      resume: function(audioID) {
        var audio = getAudioFromId(audioID);
        if (!audio || !audio.resume) return false;
        0 === audio.getCurrentTime() ? audio.play() : audio.resume();
      },
      resumeAll: function() {
        while (this._pauseIDCache.length > 0) {
          var id = this._pauseIDCache.pop();
          var audio = getAudioFromId(id);
          audio && audio.resume && audio.resume();
        }
      },
      stop: function(audioID) {
        var audio = getAudioFromId(audioID);
        if (!audio || !audio.stop) return false;
        audio.off("load", audio.__callback);
        audio.stop();
        return true;
      },
      stopAll: function() {
        for (var id in id2audio) {
          var audio = id2audio[id];
          if (audio && audio.stop) {
            audio.stop();
            audio.off("load", audio.__callback);
          }
        }
      },
      setMaxAudioInstance: function(num) {
        return this._maxAudioInstance = num;
      },
      getMaxAudioInstance: function() {
        return this._maxAudioInstance;
      },
      uncache: function(filePath) {
        var list = url2id[filePath];
        if (!list) return;
        while (list.length > 0) {
          var id = list.pop();
          var audio = id2audio[id];
          if (audio) {
            audio.stop();
            delete id2audio[id];
          }
        }
      },
      uncacheAll: function() {
        this.stopAll();
        id2audio = {};
        url2id = {};
      },
      getProfile: function(profileName) {},
      preload: function(filePath, callback) {
        cc.loader.load(filePath, callback && function(error) {
          error || callback();
        });
      },
      setMaxWebAudioSize: function(kb) {
        this._maxWebAudioSize = 1024 * kb;
      },
      _breakCache: null,
      _break: function() {
        this._breakCache = [];
        for (var id in id2audio) {
          var audio = id2audio[id];
          var state = audio.getState();
          if (state === Audio.State.PLAYING) {
            this._breakCache.push(id);
            audio.pause();
          }
        }
      },
      _restore: function() {
        if (!this._breakCache) return;
        while (this._breakCache.length > 0) {
          var id = this._breakCache.pop();
          var audio = getAudioFromId(id);
          audio && audio.resume && audio.resume();
        }
        this._breakCache = null;
      }
    };
    module.exports = cc.audioEngine = audioEngine;
    var Module = require("./deprecated");
    Module.removed(audioEngine);
    Module.deprecated(audioEngine);
  }), {
    "./CCAudio": 22,
    "./deprecated": 24
  } ],
  24: [ (function(require, module, exports) {
    var js = cc.js;
    exports.removed = function(audioEngine) {
      function willPlayMusicError() {
        cc.errorID(1403);
      }
      js.getset(audioEngine, "willPlayMusic", willPlayMusicError, willPlayMusicError);
    };
    exports.deprecated = function(audioEngine) {
      var musicId = -1;
      var musicPath = 1;
      var musicLoop = 1;
      var musicVolume = 1;
      var effectsVolume = 1;
      var pauseIDCache = [];
      js.get(audioEngine, "playMusic", (function() {
        return function(url, loop) {
          audioEngine.stop(musicId);
          musicId = audioEngine.play(url, loop, musicVolume);
          musicPath = url;
          musicLoop = loop;
          return musicId;
        };
      }));
      js.get(audioEngine, "stopMusic", (function() {
        return function() {
          audioEngine.stop(musicId);
          return musicId;
        };
      }));
      js.get(audioEngine, "pauseMusic", (function() {
        return function() {
          audioEngine.pause(musicId);
          return musicId;
        };
      }));
      js.get(audioEngine, "resumeMusic", (function() {
        return function() {
          audioEngine.resume(musicId);
          return musicId;
        };
      }));
      js.get(audioEngine, "rewindMusic", (function() {
        return function() {
          audioEngine.setCurrentTime(musicId, 0);
          return musicId;
        };
      }));
      js.get(audioEngine, "getMusicVolume", (function() {
        return function() {
          return musicVolume;
        };
      }));
      js.get(audioEngine, "setMusicVolume", (function() {
        return function(volume) {
          musicVolume = volume;
          audioEngine.setVolume(musicId, musicVolume);
          return musicVolume;
        };
      }));
      js.get(audioEngine, "isMusicPlaying", (function() {
        return function() {
          return audioEngine.getState(musicId) === audioEngine.AudioState.PLAYING;
        };
      }));
      js.get(audioEngine, "playEffect", (function() {
        return function(url, loop, volume) {
          return audioEngine.play(url, loop || false, void 0 === volume ? effectsVolume : volume);
        };
      }));
      js.get(audioEngine, "setEffectsVolume", (function(volume) {
        return function(volume) {
          effectsVolume = volume;
          var id2audio = audioEngine._id2audio;
          for (var id in id2audio) {
            if (id === musicId) continue;
            audioEngine.setVolume(id, volume);
          }
        };
      }));
      js.get(audioEngine, "getEffectsVolume", (function() {
        return function() {
          return effectsVolume;
        };
      }));
      js.get(audioEngine, "pauseEffect", (function() {
        return function(id) {
          return audioEngine.pause(id);
        };
      }));
      js.get(audioEngine, "pauseAllEffects", (function() {
        false;
        return function() {
          pauseIDCache.length = 0;
          var id2audio = audioEngine._id2audio;
          for (var id in id2audio) {
            if (id === musicId) continue;
            var audio = id2audio[id];
            var state = audio.getState();
            if (state === audioEngine.AudioState.PLAYING) {
              pauseIDCache.push(id);
              audio.pause();
            }
          }
        };
      }));
      js.get(audioEngine, "resumeEffect", (function() {
        return function(id) {
          audioEngine.resume(id);
        };
      }));
      js.get(audioEngine, "resumeAllEffects", (function() {
        false;
        return function() {
          var id2audio = audioEngine._id2audio;
          while (pauseIDCache.length > 0) {
            var id = pauseIDCache.pop();
            var audio = id2audio[id];
            audio && audio.resume && audio.resume();
          }
        };
      }));
      js.get(audioEngine, "stopEffect", (function() {
        return function(id) {
          return audioEngine.stop(id);
        };
      }));
      js.get(audioEngine, "stopAllEffects", (function() {
        false;
        return function() {
          var id2audio = audioEngine._id2audio;
          for (var id in id2audio) {
            if (id === musicId) continue;
            var audio = id2audio[id];
            var state = audio.getState();
            state === audioEngine.AudioState.PLAYING && audio.stop();
          }
        };
      }));
      js.get(audioEngine, "unloadEffect", (function() {
        return function(id) {
          return audioEngine.stop(id);
        };
      }));
      true;
      js.get(audioEngine, "end", (function() {
        return function() {
          return audioEngine.stopAll();
        };
      }));
    };
  }), {} ],
  25: [ (function(require, module, exports) {
    cc.ClippingNode = _ccsg.Node.extend({
      inverted: false,
      _alphaThreshold: 0,
      _stencil: null,
      _className: "ClippingNode",
      _originStencilProgram: null,
      ctor: function(stencil) {
        stencil = stencil || null;
        _ccsg.Node.prototype.ctor.call(this);
        this._stencil = stencil;
        stencil && (this._originStencilProgram = stencil.getShaderProgram());
        this.alphaThreshold = 1;
        this.inverted = false;
        this._renderCmd.initStencilBits();
      },
      onEnter: function() {
        _ccsg.Node.prototype.onEnter.call(this);
        this._stencil && this._stencil.performRecursive(_ccsg.Node.performType.onEnter);
      },
      onEnterTransitionDidFinish: function() {
        _ccsg.Node.prototype.onEnterTransitionDidFinish.call(this);
        this._stencil && this._stencil.performRecursive(_ccsg.Node.performType.onEnterTransitionDidFinish);
      },
      onExitTransitionDidStart: function() {
        this._stencil && this._stencil.performRecursive(_ccsg.Node.performType.onExitTransitionDidStart);
        _ccsg.Node.prototype.onExitTransitionDidStart.call(this);
      },
      onExit: function() {
        this._stencil && this._stencil.performRecursive(_ccsg.Node.performType.onExit);
        _ccsg.Node.prototype.onExit.call(this);
      },
      visit: function(parent) {
        this._renderCmd.clippingVisit(parent && parent._renderCmd);
      },
      _visitChildren: function() {
        this._reorderChildDirty && this.sortAllChildren();
        var children = this._children, child;
        for (var i = 0, len = children.length; i < len; i++) {
          child = children[i];
          child && child._visible && child.visit(this);
        }
        this._renderCmd._dirtyFlag = 0;
      },
      getAlphaThreshold: function() {
        return this._alphaThreshold;
      },
      setAlphaThreshold: function(alphaThreshold) {
        1 === alphaThreshold && alphaThreshold !== this._alphaThreshold && this._renderCmd.resetProgramByStencil();
        this._alphaThreshold = alphaThreshold;
      },
      isInverted: function() {
        return this.inverted;
      },
      setInverted: function(inverted) {
        this.inverted = inverted;
      },
      getStencil: function() {
        return this._stencil;
      },
      setStencil: function(stencil) {
        if (this._stencil === stencil) return;
        stencil && (this._originStencilProgram = stencil.getShaderProgram());
        this._renderCmd.setStencil(stencil);
      },
      _createRenderCmd: function() {
        return cc._renderType === cc.game.RENDER_TYPE_CANVAS ? new cc.ClippingNode.CanvasRenderCmd(this) : new cc.ClippingNode.WebGLRenderCmd(this);
      }
    });
    cc.ClippingNode.stencilBits = -1;
    var _p = cc.ClippingNode.prototype;
    cc.defineGetterSetter(_p, "stencil", _p.getStencil, _p.setStencil);
    cc.defineGetterSetter(_p, "alphaThreshold", _p.getAlphaThreshold, _p.setAlphaThreshold);
  }), {} ],
  26: [ (function(require, module, exports) {
    require("../shape-nodes/CCDrawNode");
    cc.ClippingNode.CanvasRenderCmd = function(renderable) {
      this._rootCtor(renderable);
      this._needDraw = false;
      this._rendererClipCmd = new cc.CustomRenderCmd(this, this._drawStencilCommand);
      this._rendererRestoreCmd = new cc.CustomRenderCmd(this, this._restoreCmdCallback);
    };
    var proto = cc.ClippingNode.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
    proto.constructor = cc.ClippingNode.CanvasRenderCmd;
    proto.resetProgramByStencil = function() {};
    proto.initStencilBits = function() {};
    proto.setStencil = function(stencil) {
      if (null == stencil) return;
      this._node._stencil = stencil;
      stencil instanceof cc.DrawNode || cc.errorID(6300);
    };
    proto._restoreCmdCallback = function(ctx) {
      var wrapper = ctx || cc._renderContext;
      wrapper.restore();
    };
    proto._drawStencilCommand = function(ctx, scaleX, scaleY) {
      var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
      wrapper.save();
      context.beginPath();
      wrapper.setTransform(this._worldTransform, scaleX, scaleY);
      var stencilBuffer = this._node._stencil._buffer;
      for (var index = 0; index < stencilBuffer.length; ++index) {
        var vertices = stencilBuffer[index].verts;
        if (vertices.length < 3) continue;
        context.moveTo(vertices[0].x, -vertices[0].y);
        for (var vIndex = 1; vIndex < vertices.length; ++vIndex) context.lineTo(vertices[vIndex].x, -vertices[vIndex].y);
      }
      context.clip();
    };
    proto.clippingVisit = function(parentCmd) {
      var node = this._node;
      parentCmd = parentCmd || this.getParentRenderCmd();
      this._propagateFlagsDown(parentCmd);
      if (!node._visible) return;
      parentCmd && (this._curLevel = parentCmd._curLevel + 1);
      this._syncStatus(parentCmd);
      node._stencil && cc.renderer.pushRenderCommand(this._rendererClipCmd);
      var children = node._children;
      var i, len = children.length;
      if (len > 0) {
        node.sortAllChildren();
        for (i = 0; i < len; i++) children[i].visit(node);
      }
      node._stencil && cc.renderer.pushRenderCommand(this._rendererRestoreCmd);
      this._dirtyFlag = 0;
    };
  }), {
    "../shape-nodes/CCDrawNode": 274
  } ],
  27: [ (function(require, module, exports) {
    require("../core/CCDrawingPrimitives");
    function setProgram(node, program) {
      node.shaderProgram = program;
      var children = node.children;
      if (!children) return;
      for (var i = 0; i < children.length; i++) setProgram(children[i], program);
    }
    var _currentState = {
      stencilEnabled: false,
      depthWriteMask: true
    };
    cc.ClippingNode.WebGLRenderCmd = function(renderable) {
      this._rootCtor(renderable);
      this._needDraw = false;
      this._beforeVisitCmd = new cc.CustomRenderCmd(this, this._onBeforeVisit);
      this._afterDrawStencilCmd = new cc.CustomRenderCmd(this, this._onAfterDrawStencil);
      this._afterVisitCmd = new cc.CustomRenderCmd(this, this._onAfterVisit);
      this._previousState = null;
      this._state = {
        stencilEnabled: true,
        stencilWriteMask: 0,
        depthWriteMask: false,
        stencilFunc: 0,
        stencilRef: 0,
        stencilValueMask: 0
      };
    };
    var proto = cc.ClippingNode.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype);
    proto.constructor = cc.ClippingNode.WebGLRenderCmd;
    cc.ClippingNode.WebGLRenderCmd._init_once = null;
    cc.ClippingNode.WebGLRenderCmd._visit_once = null;
    cc.ClippingNode.WebGLRenderCmd._layer = -1;
    proto.initStencilBits = function() {
      cc.ClippingNode.WebGLRenderCmd._init_once = true;
      if (cc.ClippingNode.WebGLRenderCmd._init_once) {
        cc.ClippingNode.stencilBits = cc._renderContext.getParameter(cc._renderContext.STENCIL_BITS);
        cc.ClippingNode.stencilBits <= 0 && cc.logID(6301);
        cc.ClippingNode.WebGLRenderCmd._init_once = false;
      }
    };
    proto.transform = function(parentCmd, recursive) {
      var node = this._node;
      this.originTransform(parentCmd, recursive);
      if (node._stencil) {
        node._stencil._renderCmd.transform(this, true);
        node._stencil._dirtyFlag &= ~_ccsg.Node._dirtyFlags.transformDirty;
      }
    };
    proto.clippingVisit = function(parentCmd) {
      var node = this._node;
      parentCmd = parentCmd || this.getParentRenderCmd();
      this.visit(parentCmd);
      if (cc.ClippingNode.stencilBits < 1) {
        node._visitChildren();
        return;
      }
      if (!node._stencil || !node._stencil.visible) {
        node.inverted && node._visitChildren();
        return;
      }
      if (cc.ClippingNode.WebGLRenderCmd._layer + 1 === cc.ClippingNode.stencilBits) {
        cc.ClippingNode.WebGLRenderCmd._visit_once = true;
        if (cc.ClippingNode.WebGLRenderCmd._visit_once) {
          cc.logID(6302, cc.ClippingNode.stencilBits);
          cc.ClippingNode.WebGLRenderCmd._visit_once = false;
        }
        node._visitChildren();
        return;
      }
      cc.renderer.pushRenderCommand(this._beforeVisitCmd);
      node._stencil.visit(node);
      cc.renderer.pushRenderCommand(this._afterDrawStencilCmd);
      var locChildren = node._children;
      if (locChildren && locChildren.length > 0) {
        var childLen = locChildren.length;
        node.sortAllChildren();
        for (var i = 0; i < childLen; i++) locChildren[i].visit(node);
      }
      cc.renderer.pushRenderCommand(this._afterVisitCmd);
      this._dirtyFlag = 0;
    };
    proto.setStencil = function(stencil) {
      var node = this._node;
      node._stencil && (node._stencil._parent = null);
      node._stencil = stencil;
      node._stencil && (node._stencil._parent = node);
    };
    proto._drawFullScreenQuadClearStencil = function() {
      var projStack = cc.math.projection_matrix_stack;
      projStack.push();
      projStack.top.identity();
      var modelViewStack = cc.math.modelview_matrix_stack;
      modelViewStack.push();
      modelViewStack.top.identity();
      cc._drawingUtil.drawSolidRect(cc.p(-1, -1), cc.p(1, 1), cc.color(255, 255, 255, 255));
      projStack.pop();
      modelViewStack.pop();
    };
    proto.resetProgramByStencil = function() {
      var node = this._node;
      if (node._stencil) {
        var program = node._originStencilProgram;
        setProgram(node._stencil, program);
      }
    };
    proto._onBeforeVisit = function(ctx) {
      var gl = ctx || cc._renderContext, node = this._node;
      cc.ClippingNode.WebGLRenderCmd._layer++;
      var mask_layer = 1 << cc.ClippingNode.WebGLRenderCmd._layer;
      var mask_layer_l = mask_layer - 1;
      var mask_layer_le = mask_layer | mask_layer_l;
      this._previousState = _currentState;
      gl.enable(gl.STENCIL_TEST);
      gl.stencilMask(mask_layer);
      gl.depthMask(false);
      gl.stencilFunc(gl.NEVER, mask_layer, mask_layer);
      gl.stencilOp(this._node.inverted ? gl.REPLACE : gl.ZERO, gl.KEEP, gl.KEEP);
      this._drawFullScreenQuadClearStencil();
      gl.stencilFunc(gl.NEVER, mask_layer, mask_layer);
      gl.stencilOp(this._node.inverted ? gl.ZERO : gl.REPLACE, gl.KEEP, gl.KEEP);
      if (node.alphaThreshold < 1) {
        var program = cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURECOLORALPHATEST);
        cc.gl.useProgram(program.getProgram());
        program.setUniformLocationWith1f(cc.macro.UNIFORM_ALPHA_TEST_VALUE_S, node.alphaThreshold);
        program.setUniformLocationWithMatrix4fv(cc.macro.UNIFORM_MVMATRIX_S, cc.renderer.mat4Identity.mat);
        setProgram(node._stencil, program);
      }
      this._state.stencilWriteMask = mask_layer;
      this._state.stencilRef = this._state.stencilValueMask = mask_layer_le;
      this._state.stencilFunc = gl.NEVER;
      _currentState = this._state;
    };
    proto._onAfterDrawStencil = function(ctx) {
      var gl = ctx || cc._renderContext;
      gl.depthMask(this._previousState.depthWriteMask);
      gl.stencilFunc(gl.EQUAL, this._state.stencilRef, this._state.stencilValueMask);
      gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
      this._state.stencilFunc = gl.EQUAL;
    };
    proto._onAfterVisit = function(ctx) {
      var gl = ctx || cc._renderContext;
      var state = this._previousState;
      if (state.stencilEnabled) {
        gl.stencilFunc(state.stencilFunc, state.stencilRef, state.stencilValueMask);
        gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
        gl.stencilMask(state.stencilWriteMask);
      } else gl.disable(gl.STENCIL_TEST);
      _currentState = this._previousState;
      this._previousState = null;
      cc.ClippingNode.WebGLRenderCmd._layer--;
    };
  }), {
    "../core/CCDrawingPrimitives": 36
  } ],
  28: [ (function(require, module, exports) {
    cc.Codec = {
      name: "Jacob__Codec"
    };
    cc.Codec.Base64 = require("./base64");
    cc.Codec.GZip = require("./gzip");
    cc.Codec.unzip = function() {
      return cc.Codec.GZip.gunzip.apply(cc.Codec.GZip, arguments);
    };
    cc.Codec.unzipBase64 = function() {
      var buffer = cc.Codec.Base64.decode.apply(cc.Codec.Base64, arguments);
      try {
        return cc.Codec.GZip.gunzip.call(cc.Codec.GZip, buffer);
      } catch (e) {
        return buffer.slice(7);
      }
    };
    cc.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) << 8 * j;
      }
      return ar;
    };
    cc.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) << 8 * j;
      }
      return ar;
    };
  }), {
    "./base64": 29,
    "./gzip": 30
  } ],
  29: [ (function(require, module, exports) {
    var Misc = require("../core/utils/misc");
    var strValue = Misc.BASE64_VALUES;
    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 = strValue[input.charCodeAt(i++)];
        enc2 = strValue[input.charCodeAt(i++)];
        enc3 = strValue[input.charCodeAt(i++)];
        enc4 = strValue[input.charCodeAt(i++)];
        chr1 = enc1 << 2 | enc2 >> 4;
        chr2 = (15 & enc2) << 4 | enc3 >> 2;
        chr3 = (3 & enc3) << 6 | enc4;
        output.push(String.fromCharCode(chr1));
        64 !== enc3 && output.push(String.fromCharCode(chr2));
        64 !== enc4 && 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) << 8 * j;
      }
      return ar;
    };
    module.exports = Base64;
  }), {
    "../core/utils/misc": 225
  } ],
  30: [ (function(require, module, exports) {
    var GZip = function Jacob__GZip(data) {
      this.data = data;
      this.debug = false;
      this.gpflags = void 0;
      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 = void 0;
      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 = void 0;
      this.fmax = void 0;
    };
    GZip.gunzip = function(string) {
      string.constructor === Array || 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 = [ 0, 128, 64, 192, 32, 160, 96, 224, 16, 144, 80, 208, 48, 176, 112, 240, 8, 136, 72, 200, 40, 168, 104, 232, 24, 152, 88, 216, 56, 184, 120, 248, 4, 132, 68, 196, 36, 164, 100, 228, 20, 148, 84, 212, 52, 180, 116, 244, 12, 140, 76, 204, 44, 172, 108, 236, 28, 156, 92, 220, 60, 188, 124, 252, 2, 130, 66, 194, 34, 162, 98, 226, 18, 146, 82, 210, 50, 178, 114, 242, 10, 138, 74, 202, 42, 170, 106, 234, 26, 154, 90, 218, 58, 186, 122, 250, 6, 134, 70, 198, 38, 166, 102, 230, 22, 150, 86, 214, 54, 182, 118, 246, 14, 142, 78, 206, 46, 174, 110, 238, 30, 158, 94, 222, 62, 190, 126, 254, 1, 129, 65, 193, 33, 161, 97, 225, 17, 145, 81, 209, 49, 177, 113, 241, 9, 137, 73, 201, 41, 169, 105, 233, 25, 153, 89, 217, 57, 185, 121, 249, 5, 133, 69, 197, 37, 165, 101, 229, 21, 149, 85, 213, 53, 181, 117, 245, 13, 141, 77, 205, 45, 173, 109, 237, 29, 157, 93, 221, 61, 189, 125, 253, 3, 131, 67, 195, 35, 163, 99, 227, 19, 147, 83, 211, 51, 179, 115, 243, 11, 139, 75, 203, 43, 171, 107, 235, 27, 155, 91, 219, 59, 187, 123, 251, 7, 135, 71, 199, 39, 167, 103, 231, 23, 151, 87, 215, 55, 183, 119, 247, 15, 143, 79, 207, 47, 175, 111, 239, 31, 159, 95, 223, 63, 191, 127, 255 ];
    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 = [ 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 ];
    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;
      return this.bytepos < this.data.length ? this.data.charCodeAt(this.bytepos++) : -1;
    };
    GZip.prototype.byteAlign = function() {
      this.bb = 1;
    };
    GZip.prototype.readBit = function() {
      var carry;
      this.bits++;
      carry = 1 & this.bb;
      this.bb >>= 1;
      if (0 === this.bb) {
        this.bb = this.readByte();
        carry = 1 & this.bb;
        this.bb = this.bb >> 1 | 128;
      }
      return carry;
    };
    GZip.prototype.readBits = function(a) {
      var res = 0, i = a;
      while (i--) res = res << 1 | this.readBit();
      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));
      32768 === this.bIdx && (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 (17 === this.len) return -1;
      this.treepos++;
      this.len++;
      tmp = this.IsPat();
      if (tmp >= 0) curplace.b0 = tmp; else {
        curplace.b0 = 32768;
        if (this.Rec()) return -1;
      }
      tmp = this.IsPat();
      if (tmp >= 0) {
        curplace.b1 = tmp;
        curplace.jump = null;
      } else {
        curplace.b1 = 32768;
        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 (!(32768 & X.b1)) return X.b1;
          X = X.jump;
          len = currentTree.length;
          for (i = 0; i < len; i++) if (currentTree[i] === X) {
            xtreepos = i;
            break;
          }
        } else {
          if (!(32768 & X.b0)) 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 (0 === type) {
          var blockLen, cSum;
          this.byteAlign();
          blockLen = this.readByte();
          blockLen |= this.readByte() << 8;
          cSum = this.readByte();
          cSum |= this.readByte() << 8;
          65535 & (blockLen ^ ~cSum) && document.write("BlockLen checksum mismatch\n");
          while (blockLen--) {
            c = this.readByte();
            this.addBuffer(c);
          }
        } else if (1 === type) {
          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;
                j > 143 && (j += 136);
              }
            } else j += 256;
            if (j < 256) this.addBuffer(j); else {
              if (256 === j) break;
              var len, dist;
              j -= 257;
              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 & 32767];
                this.addBuffer(c);
              }
            }
          }
        } else if (2 === type) {
          var j, n, literalCodes, distCodes, lenCodes;
          var ll = new Array(320);
          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;
          var z = -1;
          while (i < n) {
            z++;
            j = this.DecodeValue(this.distanceTree);
            if (j < 16) ll[i++] = j; else if (16 === j) {
              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 {
              j = 17 === j ? 3 + this.readBits(3) : 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 (0 === j) 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 & 32767];
                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 (120 === tmp[0] && 218 === tmp[1]) {
        this.DeflateLoop();
        this.unzipped[this.files] = [ this.outputArr.join(""), "geonext.gxt" ];
        this.files++;
      }
      if (31 === tmp[0] && 139 === tmp[1]) {
        this.skipdir();
        this.unzipped[this.files] = [ this.outputArr.join(""), "file" ];
        this.files++;
      }
      if (80 === tmp[0] && 75 === tmp[1]) {
        this.modeZIP = true;
        tmp[2] = this.readByte();
        tmp[3] = this.readByte();
        if (3 === tmp[2] && 4 === tmp[3]) {
          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();
            "/" === c | ":" === c ? i = 0 : i < GZip.NAMEMAX - 1 && (this.nameBuf[i++] = String.fromCharCode(c));
          }
          this.fileout || (this.fileout = this.nameBuf);
          var i = 0;
          while (i < extralen) {
            c = this.readByte();
            i++;
          }
          if (8 === method) {
            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 (8 & this.gpflags) {
        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;
      }
      this.modeZIP && this.nextFile();
      tmp[0] = this.readByte();
      if (8 !== tmp[0]) return 0;
      this.gpflags = this.readByte();
      this.readByte();
      this.readByte();
      this.readByte();
      this.readByte();
      this.readByte();
      os = this.readByte();
      if (4 & this.gpflags) {
        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 (8 & this.gpflags) {
        i = 0;
        this.nameBuf = [];
        while (c = this.readByte()) {
          "7" !== c && ":" !== c || (i = 0);
          i < GZip.NAMEMAX - 1 && (this.nameBuf[i++] = c);
        }
      }
      if (16 & this.gpflags) while (c = this.readByte()) ;
      if (2 & this.gpflags) {
        this.readByte();
        this.readByte();
      }
      this.DeflateLoop();
      size = this.readByte();
      size |= this.readByte() << 8;
      size |= this.readByte() << 16;
      size |= this.readByte() << 24;
      this.modeZIP && this.nextFile();
    };
    module.exports = GZip;
  }), {} ],
  31: [ (function(require, module, exports) {
    (function() {
      "use strict";
      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 = e[f] ? e[f] : e[f] = {} : e[f] = c;
      }
      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] = (255 & c[b].charCodeAt(0)) >>> 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[255 & a] << 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 |= 1 & R, 
        --ja;
        ca[ha] = (ia << ja & 255) >>> 0;
      }
      var N = ca;
      var ka = [ 0, 1996959894, 3993919788, 2567524794, 124634137, 1886057615, 3915621685, 2657392035, 249268274, 2044508324, 3772115230, 2547177864, 162941995, 2125561021, 3887607047, 2428444049, 498536548, 1789927666, 4089016648, 2227061214, 450548861, 1843258603, 4107580753, 2211677639, 325883990, 1684777152, 4251122042, 2321926636, 335633487, 1661365465, 4195302755, 2366115317, 997073096, 1281953886, 3579855332, 2724688242, 1006888145, 1258607687, 3524101629, 2768942443, 901097722, 1119000684, 3686517206, 2898065728, 853044451, 1172266101, 3705015759, 2882616665, 651767980, 1373503546, 3369554304, 3218104598, 565507253, 1454621731, 3485111705, 3099436303, 671266974, 1594198024, 3322730930, 2970347812, 795835527, 1483230225, 3244367275, 3060149565, 1994146192, 31158534, 2563907772, 4023717930, 1907459465, 112637215, 2680153253, 3904427059, 2013776290, 251722036, 2517215374, 3775830040, 2137656763, 141376813, 2439277719, 3865271297, 1802195444, 476864866, 2238001368, 4066508878, 1812370925, 453092731, 2181625025, 4111451223, 1706088902, 314042704, 2344532202, 4240017532, 1658658271, 366619977, 2362670323, 4224994405, 1303535960, 984961486, 2747007092, 3569037538, 1256170817, 1037604311, 2765210733, 3554079995, 1131014506, 879679996, 2909243462, 3663771856, 1141124467, 855842277, 2852801631, 3708648649, 1342533948, 654459306, 3188396048, 3373015174, 1466479909, 544179635, 3110523913, 3462522015, 1591671054, 702138776, 2966460450, 3352799412, 1504918807, 783551873, 3082640443, 3233442989, 3988292384, 2596254646, 62317068, 1957810842, 3939845945, 2647816111, 81470997, 1943803523, 3814918930, 2489596804, 225274430, 2053790376, 3826175755, 2466906013, 167816743, 2097651377, 4027552580, 2265490386, 503444072, 1762050814, 4150417245, 2154129355, 426522225, 1852507879, 4275313526, 2312317920, 282753626, 1742555852, 4189708143, 2394877945, 397917763, 1622183637, 3604390888, 2714866558, 953729732, 1340076626, 3518719985, 2797360999, 1068828381, 1219638859, 3624741850, 2936675148, 906185462, 1090812512, 3747672003, 2825379669, 829329135, 1181335161, 3412177804, 3160834842, 628085408, 1382605366, 3423369109, 3138078467, 570562233, 1426400815, 3317316542, 2998733608, 733239954, 1555261956, 3268935591, 3050360625, 752459403, 1541320221, 2607071920, 3965973030, 1969922972, 40735498, 2617837225, 3943577151, 1913087877, 83908371, 2512341634, 3803740692, 2075208622, 213261112, 2463272603, 3855990285, 2094854071, 198958881, 2262029012, 4057260610, 1759359992, 534414190, 2176718541, 4139329115, 1873836001, 414664567, 2282248934, 4279200368, 1711684554, 285281116, 2405801727, 4167216745, 1634467795, 376229701, 2685067896, 3608007406, 1308918612, 956543938, 2808555105, 3495958263, 1231636301, 1047427035, 2932959818, 3654703836, 1088359270, 936918e3, 2847714899, 3736837829, 1202900863, 817233897, 3183342108, 3401237130, 1404277552, 615818150, 3134207493, 3453421203, 1423857449, 601450431, 3009837614, 3294710456, 1567103746, 711928724, 3020668471, 3272380065, 1510334235, 755167117 ];
      H && new Uint32Array(ka);
      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])) break;
          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;
        }
        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])) break;
          e = b[d], b[d] = b[f], b[f] = e, e = b[d + 1], b[d + 1] = b[f + 1], b[f + 1] = e;
          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 | 1 & s, 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++] = 0 | h;
            m = d.length;
            j = 65536 + ~m & 65535;
            l[q++] = 255 & m;
            l[q++] = m >>> 8 & 255;
            l[q++] = 255 & j;
            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++] = 65535 & f;
          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]] = 1 + (0 | b[a[d]]);
        d = 1;
        for (g = 16; d <= g; d++) e[d] = f, f += 0 | b[d], 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 | 1 & f, 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;
        !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++] = 255 & d;
        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;
        !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);
          1 & a && (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 65535 & j;
      }
      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 = e / 2 * 258 | 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;
        !c && (c = {}) || (c.index && (this.c = c.index), c.verify && (this.M = c.verify));
        b = a[this.c++];
        e = a[this.c++];
        switch (15 & b) {
         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));
        32 & e && 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 ob = [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
      H && new Uint16Array(ob);
      var pb = [ 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 ];
      H && new Uint16Array(pb);
      var qb = [ 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 ];
      H && new Uint8Array(qb);
      var rb = [ 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 ];
      H && new Uint16Array(rb);
      var sb = [ 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 ];
      H && new Uint8Array(sb);
      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);
    var _p = window.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"];
    module.exports = _p;
  }), {} ],
  32: [ (function(require, module, exports) {
    cc.configuration = {
      ERROR: 0,
      STRING: 1,
      INT: 2,
      DOUBLE: 3,
      BOOLEAN: 4,
      _maxTextureSize: 0,
      _maxModelviewStackDepth: 0,
      _supportsPVRTC: false,
      _supportsNPOT: false,
      _supportsBGRA8888: false,
      _supportsDiscardFramebuffer: false,
      _supportsShareableVAO: false,
      _maxSamplesAllowed: 0,
      _maxTextureUnits: 0,
      _GlExtensions: "",
      _valueDict: {},
      _inited: false,
      _init: function() {
        var locValueDict = this._valueDict;
        locValueDict["cocos2d.x.version"] = cc.ENGINE_VERSION;
        locValueDict["cocos2d.x.compiled_with_profiler"] = false;
        locValueDict["cocos2d.x.compiled_with_gl_state_cache"] = cc.macro.ENABLE_GL_STATE_CACHE;
        this._inited = true;
      },
      getMaxTextureSize: function() {
        return this._maxTextureSize;
      },
      getMaxModelviewStackDepth: function() {
        return this._maxModelviewStackDepth;
      },
      getMaxTextureUnits: function() {
        return this._maxTextureUnits;
      },
      supportsNPOT: function() {
        return this._supportsNPOT;
      },
      supportsPVRTC: function() {
        return this._supportsPVRTC;
      },
      supportsETC: function() {
        return false;
      },
      supportsS3TC: function() {
        return false;
      },
      supportsATITC: function() {
        return false;
      },
      supportsBGRA8888: function() {
        return this._supportsBGRA8888;
      },
      supportsDiscardFramebuffer: function() {
        return this._supportsDiscardFramebuffer;
      },
      supportsShareableVAO: function() {
        return this._supportsShareableVAO;
      },
      checkForGLExtension: function(searchName) {
        return this._GlExtensions.indexOf(searchName) > -1;
      },
      getValue: function(key, default_value) {
        this._inited || this._init();
        var locValueDict = this._valueDict;
        if (locValueDict[key]) return locValueDict[key];
        return default_value;
      },
      setValue: function(key, value) {
        this._valueDict[key] = value;
      },
      gatherGPUInfo: function() {
        if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return;
        this._inited || this._init();
        var gl = cc._renderContext;
        var locValueDict = this._valueDict;
        locValueDict["gl.vendor"] = gl.getParameter(gl.VENDOR);
        locValueDict["gl.renderer"] = gl.getParameter(gl.RENDERER);
        locValueDict["gl.version"] = gl.getParameter(gl.VERSION);
        this._GlExtensions = "";
        var extArr = gl.getSupportedExtensions();
        for (var i = 0; i < extArr.length; i++) this._GlExtensions += extArr[i] + " ";
        this._maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
        locValueDict["gl.max_texture_size"] = this._maxTextureSize;
        this._maxTextureUnits = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
        locValueDict["gl.max_texture_units"] = this._maxTextureUnits;
        this._supportsPVRTC = this.checkForGLExtension("GL_IMG_texture_compression_pvrtc");
        locValueDict["gl.supports_PVRTC"] = this._supportsPVRTC;
        this._supportsNPOT = true;
        locValueDict["gl.supports_NPOT"] = this._supportsNPOT;
        this._supportsBGRA8888 = this.checkForGLExtension("GL_IMG_texture_format_BGRA888");
        locValueDict["gl.supports_BGRA8888"] = this._supportsBGRA8888;
        this._supportsDiscardFramebuffer = this.checkForGLExtension("GL_EXT_discard_framebuffer");
        locValueDict["gl.supports_discard_framebuffer"] = this._supportsDiscardFramebuffer;
        this._supportsShareableVAO = this.checkForGLExtension("vertex_array_object");
        locValueDict["gl.supports_vertex_array_object"] = this._supportsShareableVAO;
        cc.checkGLErrorDebug();
      },
      loadConfigFile: function(url) {
        this._inited || this._init();
        var dict = cc.loader.getRes(url);
        if (!dict) throw new Error("Please load the resource first : " + url);
        cc.assertID(dict, 1101, url);
        var getDatas = dict["data"];
        if (!getDatas) {
          cc.logID(1100, url);
          return;
        }
        for (var selKey in getDatas) this._valueDict[selKey] = getDatas[selKey];
      }
    };
  }), {} ],
  33: [ (function(require, module, exports) {
    var EventTarget = require("./event/event-target");
    var Class = require("./platform/_CCClass");
    var AutoReleaseUtils = require("./load-pipeline/auto-release-utils");
    var ComponentScheduler = require("./component-scheduler");
    var NodeActivator = require("./node-activator");
    var EventListeners = require("./event/event-listeners");
    var eventManager = require("./event-manager");
    cc.g_NumberOfDraws = 0;
    cc.Director = Class.extend({
      ctor: function() {
        var self = this;
        EventTarget.call(self);
        self._landscape = false;
        self._nextDeltaTimeZero = false;
        self._paused = false;
        self._purgeDirectorInNextLoop = false;
        self._sendCleanupToScene = false;
        self._animationInterval = 0;
        self._oldAnimationInterval = 0;
        self._projection = 0;
        self._projectionDelegate = null;
        self._contentScaleFactor = 1;
        self._winSizeInPoints = null;
        self._openGLView = null;
        self._scenesStack = null;
        self._nextScene = null;
        self._loadingScene = "";
        self._runningScene = null;
        self._scene = null;
        self._totalFrames = 0;
        self._lastUpdate = Date.now();
        self._deltaTime = 0;
        self._dirtyRegion = null;
        self._scheduler = null;
        self._compScheduler = null;
        self._nodeActivator = null;
        self._actionManager = null;
        cc.game.on(cc.game.EVENT_SHOW, (function() {
          self._lastUpdate = Date.now();
        }));
      },
      init: function() {
        this._oldAnimationInterval = this._animationInterval = 1 / cc.defaultFPS;
        this._scenesStack = [];
        this._projection = cc.Director.PROJECTION_DEFAULT;
        this._projectionDelegate = null;
        this._totalFrames = 0;
        this._lastUpdate = Date.now();
        this._paused = false;
        this._purgeDirectorInNextLoop = false;
        this._winSizeInPoints = cc.size(0, 0);
        this._openGLView = null;
        this._contentScaleFactor = 1;
        this._scheduler = new cc.Scheduler();
        if (cc.ActionManager) {
          this._actionManager = new cc.ActionManager();
          this._scheduler.scheduleUpdate(this._actionManager, cc.Scheduler.PRIORITY_SYSTEM, false);
        } else this._actionManager = null;
        this.sharedInit();
        return true;
      },
      sharedInit: function() {
        this._compScheduler = new ComponentScheduler();
        this._nodeActivator = new NodeActivator();
        if (cc.AnimationManager) {
          this._animationManager = new cc.AnimationManager();
          this._scheduler.scheduleUpdate(this._animationManager, cc.Scheduler.PRIORITY_SYSTEM, false);
        } else this._animationManager = null;
        if (cc.CollisionManager) {
          this._collisionManager = new cc.CollisionManager();
          this._scheduler.scheduleUpdate(this._collisionManager, cc.Scheduler.PRIORITY_SYSTEM, false);
        } else this._collisionManager = null;
        if (cc.PhysicsManager) {
          this._physicsManager = new cc.PhysicsManager();
          this._scheduler.scheduleUpdate(this._physicsManager, cc.Scheduler.PRIORITY_SYSTEM, false);
        } else this._physicsManager = null;
        cc._widgetManager && cc._widgetManager.init(this);
        cc.loader.init(this);
      },
      calculateDeltaTime: function() {
        var now = Date.now();
        if (this._nextDeltaTimeZero) {
          this._deltaTime = 0;
          this._nextDeltaTimeZero = false;
        } else {
          this._deltaTime = (now - this._lastUpdate) / 1e3;
          cc.game.config[cc.game.CONFIG_KEY.debugMode] > 0 && this._deltaTime > 1 && (this._deltaTime = 1 / 60);
        }
        this._lastUpdate = now;
      },
      convertToGL: function(uiPoint) {
        var container = cc.game.container;
        var view = cc.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 ? {
          x: view._viewPortRect.width - y,
          y: x
        } : {
          x: x,
          y: y
        };
      },
      convertToUI: function(glPoint) {
        var container = cc.game.container;
        var view = cc.view;
        var box = container.getBoundingClientRect();
        var left = box.left + window.pageXOffset - container.clientLeft;
        var top = box.top + window.pageYOffset - container.clientTop;
        var uiPoint = {
          x: 0,
          y: 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;
      },
      _visitScene: function() {
        if (this._runningScene) {
          var renderer = cc.renderer;
          if (renderer.childrenOrderDirty) {
            renderer.clearRenderCommands();
            cc.renderer.assignedZ = 0;
            this._runningScene._renderCmd._curLevel = 0;
            this._runningScene.visit();
            renderer.resetFlag();
          } else renderer.transformDirty() && renderer.transform();
        }
      },
      end: function() {
        this._purgeDirectorInNextLoop = true;
      },
      getContentScaleFactor: function() {
        return this._contentScaleFactor;
      },
      getWinSize: function() {
        return cc.size(this._winSizeInPoints);
      },
      getWinSizeInPixels: function() {
        return cc.size(this._winSizeInPoints.width * this._contentScaleFactor, this._winSizeInPoints.height * this._contentScaleFactor);
      },
      getVisibleSize: null,
      getVisibleOrigin: null,
      getZEye: null,
      pause: function() {
        if (this._paused) return;
        this._oldAnimationInterval = this._animationInterval;
        this.setAnimationInterval(.25);
        this._paused = true;
      },
      popScene: function() {
        cc.assertID(this._runningScene, 1204);
        this._scenesStack.pop();
        var c = this._scenesStack.length;
        if (0 === c) this.end(); else {
          this._sendCleanupToScene = true;
          this._nextScene = this._scenesStack[c - 1];
        }
      },
      purgeCachedData: function() {
        cc.textureCache._clear();
        cc.loader.releaseAll();
      },
      purgeDirector: function() {
        this.getScheduler().unscheduleAll();
        this._compScheduler.unscheduleAll();
        this._nodeActivator.reset();
        eventManager && eventManager.setEnabled(false);
        if (this._runningScene) {
          this._runningScene.performRecursive(_ccsg.Node.performType.onExitTransitionDidStart);
          this._runningScene.performRecursive(_ccsg.Node.performType.onExit);
          this._runningScene.performRecursive(_ccsg.Node.performType.cleanup);
          cc.renderer.clearRenderCommands();
        }
        this._runningScene = null;
        this._nextScene = null;
        this._scenesStack.length = 0;
        this.stopAnimation();
        this.purgeCachedData();
        false;
      },
      reset: function() {
        this.purgeDirector();
        eventManager && eventManager.setEnabled(true);
        this._actionManager && this._scheduler.scheduleUpdate(this._actionManager, cc.Scheduler.PRIORITY_SYSTEM, false);
        this._animationManager && this._scheduler.scheduleUpdate(this._animationManager, cc.Scheduler.PRIORITY_SYSTEM, false);
        this._collisionManager && this._scheduler.scheduleUpdate(this._collisionManager, cc.Scheduler.PRIORITY_SYSTEM, false);
        this._physicsManager && this._scheduler.scheduleUpdate(this._physicsManager, cc.Scheduler.PRIORITY_SYSTEM, false);
        this.startAnimation();
      },
      pushScene: function(scene) {
        cc.assertID(scene, 1205);
        this._sendCleanupToScene = false;
        this._scenesStack.push(scene);
        this._nextScene = scene;
      },
      runSceneImmediate: function(scene, onBeforeLoadScene, onLaunched) {
        if (scene instanceof cc.Scene) {
          (true, true) && console.time("InitScene");
          scene._load();
          (true, true) && console.timeEnd("InitScene");
        }
        var game = cc.game;
        var persistNodeList = Object.keys(game._persistRootNodes).map((function(x) {
          return game._persistRootNodes[x];
        }));
        for (var _i = 0; _i < persistNodeList.length; _i++) {
          var node = persistNodeList[_i];
          game._ignoreRemovePersistNode = node;
          node.parent = null;
          game._ignoreRemovePersistNode = null;
        }
        var oldScene = this._scene;
        true;
        (true, true) && console.time("AutoRelease");
        var autoReleaseAssets = oldScene && oldScene.autoReleaseAssets && oldScene.dependAssets;
        AutoReleaseUtils.autoRelease(autoReleaseAssets, scene.dependAssets, persistNodeList);
        (true, true) && console.timeEnd("AutoRelease");
        (true, true) && console.time("Destroy");
        cc.isValid(oldScene) && oldScene.destroy();
        this._scene = null;
        cc.Object._deferredDestroy();
        (true, true) && console.timeEnd("Destroy");
        onBeforeLoadScene && onBeforeLoadScene();
        this.emit(cc.Director.EVENT_BEFORE_SCENE_LAUNCH, scene);
        var sgScene = scene;
        if (scene instanceof cc.Scene) {
          this._scene = scene;
          sgScene = scene._sgNode;
          (true, true) && console.time("AttachPersist");
          for (var _i2 = 0; _i2 < persistNodeList.length; _i2++) {
            var _node = persistNodeList[_i2];
            var existNode = scene.getChildByUuid(_node.uuid);
            if (existNode) {
              var index = existNode.getSiblingIndex();
              existNode._destroyImmediate();
              scene.insertChild(_node, index);
            } else _node.parent = scene;
          }
          (true, true) && console.timeEnd("AttachPersist");
          (true, true) && console.time("Activate");
          scene._activate();
          (true, true) && console.timeEnd("Activate");
        }
        if (this._runningScene) {
          var i = this._scenesStack.length;
          this._scenesStack[Math.max(i - 1, 0)] = sgScene;
          this._sendCleanupToScene = true;
          this._nextScene = sgScene;
        } else {
          this.pushScene(sgScene);
          this.startAnimation();
        }
        this._nextScene && this.setNextScene();
        onLaunched && onLaunched(null, scene);
        this.emit(cc.Director.EVENT_AFTER_SCENE_LAUNCH, scene);
      },
      runScene: function(scene, onBeforeLoadScene, onLaunched) {
        cc.assertID(scene, 1205);
        scene instanceof cc.Scene && scene._load();
        this.once(cc.Director.EVENT_AFTER_UPDATE, (function() {
          this.runSceneImmediate(scene, onBeforeLoadScene, onLaunched);
        }));
      },
      _getSceneUuid: function(key) {
        var scenes = cc.game._sceneInfos;
        if ("string" === typeof key) {
          key.endsWith(".fire") || (key += ".fire");
          "/" === key[0] || key.startsWith("db://assets/") || (key = "/" + key);
          for (var i = 0; i < scenes.length; i++) {
            var info = scenes[i];
            if (info.url.endsWith(key)) return info;
          }
        } else if ("number" === typeof key) {
          if (0 <= key && key < scenes.length) return scenes[key];
          cc.errorID(1206, key);
        } else cc.errorID(1207, key);
        return null;
      },
      loadScene: function(sceneName, onLaunched, _onUnloaded) {
        if (this._loadingScene) {
          cc.errorID(1208, sceneName, this._loadingScene);
          return false;
        }
        var info = this._getSceneUuid(sceneName);
        if (info) {
          var uuid = info.uuid;
          this.emit(cc.Director.EVENT_BEFORE_SCENE_LOADING, sceneName);
          this._loadingScene = sceneName;
          var self;
          var groupName;
          var ensureAsync;
          false;
          this._loadSceneByUuid(uuid, onLaunched, _onUnloaded);
          return true;
        }
        cc.errorID(1209, sceneName);
        return false;
      },
      preloadScene: function(sceneName, onLoaded) {
        var info = this._getSceneUuid(sceneName);
        if (info) {
          this.emit(cc.Director.EVENT_BEFORE_SCENE_LOADING, sceneName);
          cc.loader.load({
            uuid: info.uuid,
            type: "uuid"
          }, (function(error, asset) {
            error && cc.errorID(1210, sceneName, error.message);
            onLoaded && onLoaded(error, asset);
          }));
        } else {
          var error = 'Can not preload the scene "' + sceneName + '" because it is not in the build settings.';
          onLoaded(new Error(error));
          cc.error("preloadScene: " + error);
        }
      },
      _loadSceneByUuid: function(uuid, onLaunched, onUnloaded, dontRunScene) {
        false;
        console.time("LoadScene " + uuid);
        cc.AssetLibrary.loadAsset(uuid, (function(error, sceneAsset) {
          console.timeEnd("LoadScene " + uuid);
          var self = cc.director;
          self._loadingScene = "";
          if (error) {
            error = "Failed to load scene: " + error;
            cc.error(error);
          } else {
            if (sceneAsset instanceof cc.SceneAsset) {
              var scene = sceneAsset.scene;
              scene._id = sceneAsset._uuid;
              scene._name = sceneAsset._name;
              false;
              self.runSceneImmediate(scene, onUnloaded, onLaunched);
              return;
            }
            error = "The asset " + uuid + " is not a scene";
            cc.error(error);
          }
          onLaunched && onLaunched(error);
        }));
      },
      resume: function() {
        if (!this._paused) return;
        this.setAnimationInterval(this._oldAnimationInterval);
        this._lastUpdate = Date.now();
        this._lastUpdate || cc.logID(1200);
        this._paused = false;
        this._deltaTime = 0;
      },
      setContentScaleFactor: function(scaleFactor) {
        scaleFactor !== this._contentScaleFactor && (this._contentScaleFactor = scaleFactor);
      },
      setDepthTest: null,
      setClearColor: null,
      setDefaultValues: function() {},
      setNextDeltaTimeZero: function(nextDeltaTimeZero) {
        this._nextDeltaTimeZero = nextDeltaTimeZero;
      },
      setNextScene: function() {
        var runningIsTransition = false, newIsTransition = false;
        if (cc.TransitionScene) {
          runningIsTransition = !!this._runningScene && this._runningScene instanceof cc.TransitionScene;
          newIsTransition = !!this._nextScene && this._nextScene instanceof cc.TransitionScene;
        }
        if (!newIsTransition) {
          var locRunningScene = this._runningScene;
          if (locRunningScene) {
            locRunningScene.performRecursive(_ccsg.Node.performType.onExitTransitionDidStart);
            locRunningScene.performRecursive(_ccsg.Node.performType.onExit);
          }
          this._sendCleanupToScene && locRunningScene && locRunningScene.performRecursive(_ccsg.Node.performType.cleanup);
        }
        this._runningScene = this._nextScene;
        cc.renderer.childrenOrderDirty = true;
        this._nextScene = null;
        if (!runningIsTransition && null !== this._runningScene) {
          this._runningScene.performRecursive(_ccsg.Node.performType.onEnter);
          this._runningScene.performRecursive(_ccsg.Node.performType.onEnterTransitionDidFinish);
        }
      },
      getDelegate: function() {
        return this._projectionDelegate;
      },
      setDelegate: function(delegate) {
        this._projectionDelegate = delegate;
      },
      setOpenGLView: null,
      setProjection: null,
      setViewport: null,
      getOpenGLView: null,
      getProjection: null,
      setAlphaBlending: null,
      isSendCleanupToScene: function() {
        return this._sendCleanupToScene;
      },
      getRunningScene: function() {
        return this._runningScene;
      },
      getScene: function() {
        return this._scene;
      },
      getAnimationInterval: function() {
        return this._animationInterval;
      },
      isDisplayStats: function() {
        return !!cc.profiler && cc.profiler.isShowingStats();
      },
      setDisplayStats: function(displayStats) {
        if (cc.profiler) {
          displayStats ? cc.profiler.showStats() : cc.profiler.hideStats();
          cc.game.config[cc.game.CONFIG_KEY.showFPS] = !!displayStats;
        }
      },
      isNextDeltaTimeZero: function() {
        return this._nextDeltaTimeZero;
      },
      isPaused: function() {
        return this._paused;
      },
      getTotalFrames: function() {
        return this._totalFrames;
      },
      popToRootScene: function() {
        this.popToSceneStackLevel(1);
      },
      popToSceneStackLevel: function(level) {
        cc.assertID(this._runningScene, 1203);
        var locScenesStack = this._scenesStack;
        var c = locScenesStack.length;
        if (0 === c) {
          this.end();
          return;
        }
        if (level > c) return;
        while (c > level) {
          var current = locScenesStack.pop();
          if (current.running) {
            current.performRecursive(_ccsg.Node.performType.onExitTransitionDidStart);
            current.performRecursive(_ccsg.Node.performType.onExit);
          }
          current.performRecursive(_ccsg.Node.performType.cleanup);
          c--;
        }
        this._nextScene = locScenesStack[locScenesStack.length - 1];
        this._sendCleanupToScene = true;
      },
      getScheduler: function() {
        return this._scheduler;
      },
      setScheduler: function(scheduler) {
        this._scheduler !== scheduler && (this._scheduler = scheduler);
      },
      getActionManager: function() {
        return this._actionManager;
      },
      setActionManager: function(actionManager) {
        if (this._actionManager !== actionManager) {
          this._actionManager && this._scheduler.unscheduleUpdate(this._actionManager);
          this._actionManager = actionManager;
          this._scheduler.scheduleUpdate(this._actionManager, cc.Scheduler.PRIORITY_SYSTEM, false);
        }
      },
      getAnimationManager: function() {
        return this._animationManager;
      },
      getCollisionManager: function() {
        return this._collisionManager;
      },
      getPhysicsManager: function() {
        return this._physicsManager;
      },
      getDeltaTime: function() {
        return this._deltaTime;
      }
    });
    cc.js.addon(cc.Director.prototype, EventTarget.prototype);
    cc.Director.EVENT_PROJECTION_CHANGED = "director_projection_changed";
    cc.Director.EVENT_BEFORE_SCENE_LOADING = "director_before_scene_loading";
    cc.Director.EVENT_BEFORE_SCENE_LAUNCH = "director_before_scene_launch";
    cc.Director.EVENT_AFTER_SCENE_LAUNCH = "director_after_scene_launch";
    cc.Director.EVENT_BEFORE_UPDATE = "director_before_update";
    cc.Director.EVENT_AFTER_UPDATE = "director_after_update";
    cc.Director.EVENT_BEFORE_VISIT = "director_before_visit";
    cc.Director.EVENT_AFTER_VISIT = "director_after_visit";
    cc.Director.EVENT_AFTER_DRAW = "director_after_draw";
    cc.DisplayLinkDirector = cc.Director.extend({
      invalid: false,
      startAnimation: function() {
        this._nextDeltaTimeZero = true;
        this.invalid = false;
      },
      mainLoop: function() {
        if (this._purgeDirectorInNextLoop) {
          this._purgeDirectorInNextLoop = false;
          this.purgeDirector();
        } else if (!this.invalid) {
          this.calculateDeltaTime();
          if (!this._paused) {
            this.emit(cc.Director.EVENT_BEFORE_UPDATE);
            this._compScheduler.startPhase();
            this._compScheduler.updatePhase(this._deltaTime);
            this._scheduler.update(this._deltaTime);
            this._compScheduler.lateUpdatePhase(this._deltaTime);
            this.emit(cc.Director.EVENT_AFTER_UPDATE);
            cc.Object._deferredDestroy();
          }
          this._nextScene && this.setNextScene();
          this.emit(cc.Director.EVENT_BEFORE_VISIT);
          this._visitScene();
          this.emit(cc.Director.EVENT_AFTER_VISIT);
          cc.g_NumberOfDraws = 0;
          cc.renderer.clear();
          cc.renderer.rendering(cc._renderContext);
          this._totalFrames++;
          this.emit(cc.Director.EVENT_AFTER_DRAW);
          eventManager.frameUpdateListeners();
        }
      },
      stopAnimation: function() {
        this.invalid = true;
      },
      setAnimationInterval: function(value) {
        this._animationInterval = value;
        if (!this.invalid) {
          this.stopAnimation();
          this.startAnimation();
        }
      },
      __fastOn: function(type, callback, target) {
        var listeners = this._bubblingListeners;
        listeners || (listeners = this._bubblingListeners = new EventListeners());
        listeners.add(type, callback, target);
        this._addEventFlag(type, listeners, false);
      },
      __fastOff: function(type, callback, target) {
        var listeners = this._bubblingListeners;
        if (listeners) {
          listeners.remove(type, callback, target);
          this._purgeEventFlag(type, listeners, false);
        }
      }
    });
    cc.Director.sharedDirector = null;
    cc.Director.firstUseDirector = true;
    cc.Director._getInstance = function() {
      if (cc.Director.firstUseDirector) {
        cc.Director.firstUseDirector = false;
        cc.Director.sharedDirector = new cc.DisplayLinkDirector();
        cc.Director.sharedDirector.init();
      }
      return cc.Director.sharedDirector;
    };
    cc.defaultFPS = 60;
    cc.Director.PROJECTION_2D = 0;
    cc.Director.PROJECTION_3D = 1;
    cc.Director.PROJECTION_CUSTOM = 3;
    cc.Director.PROJECTION_DEFAULT = cc.Director.PROJECTION_2D;
  }), {
    "./component-scheduler": 70,
    "./event-manager": 110,
    "./event/event-listeners": 111,
    "./event/event-target": 112,
    "./load-pipeline/auto-release-utils": 134,
    "./node-activator": 147,
    "./platform/_CCClass": 187
  } ],
  34: [ (function(require, module, exports) {
    require("./CCDirector");
    require("./CCGame");
    var eventManager = require("./event-manager");
    cc.game.once(cc.game.EVENT_RENDERER_INITED, (function() {
      if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
        var _p = cc.Director.prototype;
        _p.getProjection = function(projection) {
          return this._projection;
        };
        _p.setProjection = function(projection) {
          this._projection = projection;
          this.emit(cc.Director.EVENT_PROJECTION_CHANGED, this);
        };
        _p.setDepthTest = function() {};
        _p.setClearColor = function(clearColor) {
          cc.renderer._clearColor = clearColor;
          cc.renderer._clearFillStyle = "rgb(" + clearColor.r + "," + clearColor.g + "," + clearColor.b + ")";
        };
        _p.setOpenGLView = function(openGLView) {
          this._winSizeInPoints.width = cc._canvas.width;
          this._winSizeInPoints.height = cc._canvas.height;
          this._openGLView = openGLView || cc.view;
          eventManager && eventManager.setEnabled(true);
        };
        _p.getVisibleSize = function() {
          return this.getWinSize();
        };
        _p.getVisibleOrigin = function() {
          return cc.p(0, 0);
        };
      }
    }));
  }), {
    "./CCDirector": 33,
    "./CCGame": 39,
    "./event-manager": 110
  } ],
  35: [ (function(require, module, exports) {
    require("./CCDirector");
    require("./CCGame");
    require("../kazmath");
    var eventManager = require("./event-manager");
    var math = cc.math;
    cc.game.once(cc.game.EVENT_RENDERER_INITED, (function() {
      if (cc._renderType !== cc.game.RENDER_TYPE_WEBGL) return;
      cc.DirectorDelegate = cc._Class.extend({
        updateProjection: function() {}
      });
      var _p = cc.Director.prototype;
      var recursiveChild = function(node) {
        if (node && node._renderCmd) {
          node._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
          var i, children = node._children;
          for (i = 0; i < children.length; i++) recursiveChild(children[i]);
        }
      };
      cc.Director._getInstance().on(cc.Director.EVENT_PROJECTION_CHANGED, (function() {
        var stack = cc.director._scenesStack;
        for (var i = 0; i < stack.length; i++) recursiveChild(stack[i]);
      }));
      _p.setProjection = function(projection) {
        var _t = this;
        var size = _t._winSizeInPoints;
        _t.setViewport();
        var view = _t._openGLView, ox = view._viewPortRect.x / view._scaleX, oy = view._viewPortRect.y / view._scaleY;
        switch (projection) {
         case cc.Director.PROJECTION_2D:
          math.glMatrixMode(math.KM_GL_PROJECTION);
          math.glLoadIdentity();
          var orthoMatrix = math.Matrix4.createOrthographicProjection(0, size.width, 0, size.height, -1024, 1024);
          math.glMultMatrix(orthoMatrix);
          math.glMatrixMode(math.KM_GL_MODELVIEW);
          math.glLoadIdentity();
          break;

         case cc.Director.PROJECTION_3D:
          var zeye = _t.getZEye();
          var matrixPerspective = new math.Matrix4(), matrixLookup = new math.Matrix4();
          math.glMatrixMode(math.KM_GL_PROJECTION);
          math.glLoadIdentity();
          matrixPerspective = math.Matrix4.createPerspectiveProjection(60, size.width / size.height, .1, 2 * zeye);
          math.glMultMatrix(matrixPerspective);
          var eye = new math.Vec3(-ox + size.width / 2, -oy + size.height / 2, zeye);
          var center = new math.Vec3(-ox + size.width / 2, -oy + size.height / 2, 0);
          var up = new math.Vec3(0, 1, 0);
          matrixLookup.lookAt(eye, center, up);
          math.glMultMatrix(matrixLookup);
          math.glMatrixMode(math.KM_GL_MODELVIEW);
          math.glLoadIdentity();
          break;

         case cc.Director.PROJECTION_CUSTOM:
          _t._projectionDelegate && _t._projectionDelegate.updateProjection();
          break;

         default:
          cc.logID(1201);
        }
        _t._projection = projection;
        _t.emit(cc.Director.EVENT_PROJECTION_CHANGED, _t);
        cc.gl.setProjectionMatrixDirty();
        cc.renderer.childrenOrderDirty = true;
      };
      _p.setDepthTest = function(on) {
        cc.renderer.setDepthTest(on);
      };
      _p.setClearColor = function(clearColor) {
        var locClearColor = cc.renderer._clearColor;
        locClearColor.r = clearColor.r / 255;
        locClearColor.g = clearColor.g / 255;
        locClearColor.b = clearColor.b / 255;
        locClearColor.a = clearColor.a / 255;
      };
      _p.setOpenGLView = function(openGLView) {
        var _t = this;
        _t._winSizeInPoints.width = cc._canvas.width;
        _t._winSizeInPoints.height = cc._canvas.height;
        _t._openGLView = openGLView || cc.view;
        var conf = cc.configuration;
        conf.gatherGPUInfo();
        _t.setGLDefaultValues();
        eventManager && eventManager.setEnabled(true);
      };
      _p.getVisibleSize = function() {
        return this._openGLView.getVisibleSize();
      };
      _p.getVisibleOrigin = function() {
        return this._openGLView.getVisibleOrigin();
      };
      _p.getZEye = function() {
        return this._winSizeInPoints.height / 1.1566;
      };
      _p.setViewport = function() {
        var view = this._openGLView;
        if (view) {
          var locWinSizeInPoints = this._winSizeInPoints;
          view.setViewPortInPoints(-view._viewPortRect.x / view._scaleX, -view._viewPortRect.y / view._scaleY, locWinSizeInPoints.width, locWinSizeInPoints.height);
        }
      };
      _p.getOpenGLView = function() {
        return this._openGLView;
      };
      _p.getProjection = function() {
        return this._projection;
      };
      _p.setAlphaBlending = function(on) {
        on ? cc.gl.blendFunc(cc.macro.BLEND_SRC, cc.macro.BLEND_DST) : cc.gl.blendFunc(cc.macro.ONE, cc.macro.ZERO);
      };
      _p.setGLDefaultValues = function() {
        var _t = this;
        _t.setAlphaBlending(true);
        _t.setProjection(_t._projection);
        cc._renderContext.clearColor(0, 0, 0, 0);
      };
    }));
  }), {
    "../kazmath": 246,
    "./CCDirector": 33,
    "./CCGame": 39,
    "./event-manager": 110
  } ],
  36: [ (function(require, module, exports) {
    var game = require("./CCGame");
    cc._drawingUtil = null;
    game.once(game.EVENT_RENDERER_INITED, (function() {
      cc._renderType === game.RENDER_TYPE_WEBGL ? cc._drawingUtil = new (require("./CCDrawingPrimitivesWebGL"))(cc._renderContext) : cc._drawingUtil = new (require("./CCDrawingPrimitivesCanvas"))(cc._renderContext);
    }));
  }), {
    "./CCDrawingPrimitivesCanvas": 37,
    "./CCDrawingPrimitivesWebGL": 38,
    "./CCGame": 39
  } ],
  37: [ (function(require, module, exports) {
    var DrawingPrimitiveCanvas = cc._Class.extend({
      _cacheArray: [],
      ctor: function(renderContext) {
        this._renderContext = renderContext;
      },
      drawPoint: function(point, size) {
        size || (size = 1);
        var locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY();
        var newPoint = cc.p(point.x * locScaleX, point.y * locScaleY);
        var ctx = this._renderContext.getContext();
        ctx.beginPath();
        ctx.arc(newPoint.x, -newPoint.y, size * locScaleX, 0, 2 * Math.PI, false);
        ctx.closePath();
        ctx.fill();
      },
      drawPoints: function(points, numberOfPoints, size) {
        if (null == points) return;
        size || (size = 1);
        var locContext = this._renderContext.getContext(), locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY();
        locContext.beginPath();
        for (var i = 0, len = points.length; i < len; i++) locContext.arc(points[i].x * locScaleX, -points[i].y * locScaleY, size * locScaleX, 0, 2 * Math.PI, false);
        locContext.closePath();
        locContext.fill();
      },
      drawLine: function(origin, destination) {
        var locContext = this._renderContext.getContext(), locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY();
        locContext.beginPath();
        locContext.moveTo(origin.x * locScaleX, -origin.y * locScaleY);
        locContext.lineTo(destination.x * locScaleX, -destination.y * locScaleY);
        locContext.closePath();
        locContext.stroke();
      },
      drawRect: function(origin, destination) {
        this.drawLine(cc.p(origin.x, origin.y), cc.p(destination.x, origin.y));
        this.drawLine(cc.p(destination.x, origin.y), cc.p(destination.x, destination.y));
        this.drawLine(cc.p(destination.x, destination.y), cc.p(origin.x, destination.y));
        this.drawLine(cc.p(origin.x, destination.y), cc.p(origin.x, origin.y));
      },
      drawSolidRect: function(origin, destination, color) {
        var vertices = [ origin, cc.p(destination.x, origin.y), destination, cc.p(origin.x, destination.y) ];
        this.drawSolidPoly(vertices, 4, color);
      },
      drawPoly: function(vertices, numOfVertices, closePolygon, fill) {
        fill = fill || false;
        if (null == vertices) return;
        if (vertices.length < 3) throw new Error("Polygon's point must greater than 2");
        var firstPoint = vertices[0], locContext = this._renderContext.getContext();
        var locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY();
        locContext.beginPath();
        locContext.moveTo(firstPoint.x * locScaleX, -firstPoint.y * locScaleY);
        for (var i = 1, len = vertices.length; i < len; i++) locContext.lineTo(vertices[i].x * locScaleX, -vertices[i].y * locScaleY);
        closePolygon && locContext.closePath();
        fill ? locContext.fill() : locContext.stroke();
      },
      drawSolidPoly: function(polygons, numberOfPoints, color) {
        this.setDrawColor(color.r, color.g, color.b, color.a);
        this.drawPoly(polygons, numberOfPoints, true, true);
      },
      drawCircle: function(center, radius, angle, segments, drawLineToCenter) {
        drawLineToCenter = drawLineToCenter || false;
        var locContext = this._renderContext.getContext();
        var locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY();
        locContext.beginPath();
        var endAngle = angle - 2 * Math.PI;
        locContext.arc(0 | center.x * locScaleX, 0 | -center.y * locScaleY, radius * locScaleX, -angle, -endAngle, false);
        drawLineToCenter && locContext.lineTo(0 | center.x * locScaleX, 0 | -center.y * locScaleY);
        locContext.stroke();
      },
      drawQuadBezier: function(origin, control, destination, segments) {
        var vertices = this._cacheArray;
        vertices.length = 0;
        var t = 0;
        for (var i = 0; i < segments; i++) {
          var x = Math.pow(1 - t, 2) * origin.x + 2 * (1 - t) * t * control.x + t * t * destination.x;
          var y = Math.pow(1 - t, 2) * origin.y + 2 * (1 - t) * t * control.y + t * t * destination.y;
          vertices.push(cc.p(x, y));
          t += 1 / segments;
        }
        vertices.push(cc.p(destination.x, destination.y));
        this.drawPoly(vertices, segments + 1, false, false);
      },
      drawCubicBezier: function(origin, control1, control2, destination, segments) {
        var vertices = this._cacheArray;
        vertices.length = 0;
        var t = 0;
        for (var i = 0; i < segments; i++) {
          var x = Math.pow(1 - t, 3) * origin.x + 3 * Math.pow(1 - t, 2) * t * control1.x + 3 * (1 - t) * t * t * control2.x + t * t * t * destination.x;
          var y = Math.pow(1 - t, 3) * origin.y + 3 * Math.pow(1 - t, 2) * t * control1.y + 3 * (1 - t) * t * t * control2.y + t * t * t * destination.y;
          vertices.push(cc.p(x, y));
          t += 1 / segments;
        }
        vertices.push(cc.p(destination.x, destination.y));
        this.drawPoly(vertices, segments + 1, false, false);
      },
      drawCatmullRom: function(points, segments) {
        this.drawCardinalSpline(points, .5, segments);
      },
      drawCardinalSpline: function(config, tension, segments) {
        cc._renderContext.setStrokeStyle("rgba(255,255,255,1)");
        var points = this._cacheArray;
        points.length = 0;
        var p, lt;
        var deltaT = 1 / config.length;
        for (var i = 0; i < segments + 1; i++) {
          var dt = i / segments;
          if (1 === dt) {
            p = config.length - 1;
            lt = 1;
          } else {
            p = 0 | dt / deltaT;
            lt = (dt - deltaT * p) / deltaT;
          }
          var newPos = cc.cardinalSplineAt(cc.getControlPointAt(config, p - 1), cc.getControlPointAt(config, p - 0), cc.getControlPointAt(config, p + 1), cc.getControlPointAt(config, p + 2), tension, lt);
          points.push(newPos);
        }
        this.drawPoly(points, segments + 1, false, false);
      },
      drawImage: function(image, sourcePoint, sourceSize, destPoint, destSize) {
        var len = arguments.length;
        var ctx = this._renderContext.getContext();
        switch (len) {
         case 2:
          var height = image.height;
          ctx.drawImage(image, sourcePoint.x, -(sourcePoint.y + height));
          break;

         case 3:
          ctx.drawImage(image, sourcePoint.x, -(sourcePoint.y + sourceSize.height), sourceSize.width, sourceSize.height);
          break;

         case 5:
          ctx.drawImage(image, sourcePoint.x, sourcePoint.y, sourceSize.width, sourceSize.height, destPoint.x, -(destPoint.y + destSize.height), destSize.width, destSize.height);
          break;

         default:
          throw new Error("Argument must be non-nil");
        }
      },
      drawStar: function(ctx, radius, color) {
        var wrapper = ctx || this._renderContext;
        var context = wrapper.getContext();
        radius *= cc.view.getScaleX();
        var colorStr = "rgba(" + (0 | color.r) + "," + (0 | color.g) + "," + (0 | color.b);
        wrapper.setFillStyle(colorStr + ",1)");
        var subRadius = radius / 10;
        context.beginPath();
        context.moveTo(-radius, radius);
        context.lineTo(0, subRadius);
        context.lineTo(radius, radius);
        context.lineTo(subRadius, 0);
        context.lineTo(radius, -radius);
        context.lineTo(0, -subRadius);
        context.lineTo(-radius, -radius);
        context.lineTo(-subRadius, 0);
        context.lineTo(-radius, radius);
        context.closePath();
        context.fill();
        var rg = context.createRadialGradient(0, 0, subRadius, 0, 0, radius);
        rg.addColorStop(0, colorStr + ", 1)");
        rg.addColorStop(.3, colorStr + ", 0.8)");
        rg.addColorStop(1, colorStr + ", 0.0)");
        wrapper.setFillStyle(rg);
        context.beginPath();
        var startAngle_1 = 0;
        var endAngle_1 = cc.macro.PI2;
        context.arc(0, 0, radius - subRadius, startAngle_1, endAngle_1, false);
        context.closePath();
        context.fill();
      },
      drawColorBall: function(ctx, radius, color) {
        var wrapper = ctx || this._renderContext;
        var context = wrapper.getContext();
        radius *= cc.view.getScaleX();
        var colorStr = "rgba(" + (0 | color.r) + "," + (0 | color.g) + "," + (0 | color.b);
        var subRadius = radius / 10;
        var g1 = context.createRadialGradient(0, 0, subRadius, 0, 0, radius);
        g1.addColorStop(0, colorStr + ", 1)");
        g1.addColorStop(.3, colorStr + ", 0.8)");
        g1.addColorStop(.6, colorStr + ", 0.4)");
        g1.addColorStop(1, colorStr + ", 0.0)");
        wrapper.setFillStyle(g1);
        context.beginPath();
        var startAngle_1 = 0;
        var endAngle_1 = cc.macro.PI2;
        context.arc(0, 0, radius, startAngle_1, endAngle_1, false);
        context.closePath();
        context.fill();
      },
      fillText: function(strText, x, y) {
        this._renderContext.getContext().fillText(strText, x, -y);
      },
      setDrawColor: function(r, g, b, a) {
        this._renderContext.setFillStyle("rgba(" + r + "," + g + "," + b + "," + a / 255 + ")");
        this._renderContext.setStrokeStyle("rgba(" + r + "," + g + "," + b + "," + a / 255 + ")");
      },
      setPointSize: function(pointSize) {},
      setLineWidth: function(width) {
        this._renderContext.getContext().lineWidth = width * cc.view.getScaleX();
      }
    });
    module.exports = DrawingPrimitiveCanvas;
  }), {} ],
  38: [ (function(require, module, exports) {
    var macro = cc.macro;
    var DrawingPrimitiveWebGL = cc._Class.extend({
      _initialized: false,
      _shader: null,
      _colorLocation: "u_color",
      _pointSizeLocation: "u_pointSize",
      _pointSize: -1,
      ctor: function(ctx) {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME && !ctx instanceof WebGLRenderingContext) throw new Error("Can't initialise DrawingPrimitiveWebGL. context need is WebGLRenderingContext");
        this._renderContext = ctx;
        this._colorArray = new Float32Array([ 1, 1, 1, 1 ]);
      },
      lazy_init: function() {
        var _t = this;
        if (!_t._initialized) {
          _t._shader = cc.shaderCache.programForKey(macro.SHADER_POSITION_UCOLOR);
          _t._shader._addUniformLocation(_t._colorLocation);
          _t._shader._addUniformLocation(_t._pointSizeLocation);
          _t._initialized = true;
        }
      },
      drawInit: function() {
        this._initialized = false;
      },
      drawPoint: function(point) {
        this.lazy_init();
        var glContext = this._renderContext;
        this._shader.use();
        this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
        glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_POSITION);
        this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
        this._shader.setUniformLocationWith1f(this._pointSizeLocation, this._pointSize);
        var pointBuffer = glContext.createBuffer();
        glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
        glContext.bufferData(glContext.ARRAY_BUFFER, new Float32Array([ point.x, point.y ]), glContext.STATIC_DRAW);
        glContext.vertexAttribPointer(macro.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0);
        glContext.drawArrays(glContext.POINTS, 0, 1);
        glContext.deleteBuffer(pointBuffer);
        cc.incrementGLDraws(1);
      },
      drawPoints: function(points, numberOfPoints) {
        if (!points || 0 === points.length) return;
        this.lazy_init();
        var glContext = this._renderContext;
        this._shader.use();
        this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
        glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_POSITION);
        this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
        this._shader.setUniformLocationWith1f(this._pointSizeLocation, this._pointSize);
        var pointBuffer = glContext.createBuffer();
        glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
        glContext.bufferData(glContext.ARRAY_BUFFER, this._pointsToTypeArray(points), glContext.STATIC_DRAW);
        glContext.vertexAttribPointer(macro.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0);
        glContext.drawArrays(glContext.POINTS, 0, points.length);
        glContext.deleteBuffer(pointBuffer);
        cc.incrementGLDraws(1);
      },
      _pointsToTypeArray: function(points) {
        var typeArr = new Float32Array(2 * points.length);
        for (var i = 0; i < points.length; i++) {
          typeArr[2 * i] = points[i].x;
          typeArr[2 * i + 1] = points[i].y;
        }
        return typeArr;
      },
      drawLine: function(origin, destination) {
        this.lazy_init();
        var glContext = this._renderContext;
        this._shader.use();
        this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
        glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_POSITION);
        this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
        var pointBuffer = glContext.createBuffer();
        glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
        glContext.bufferData(glContext.ARRAY_BUFFER, this._pointsToTypeArray([ origin, destination ]), glContext.STATIC_DRAW);
        glContext.vertexAttribPointer(macro.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0);
        glContext.drawArrays(glContext.LINES, 0, 2);
        glContext.deleteBuffer(pointBuffer);
        cc.incrementGLDraws(1);
      },
      drawRect: function(origin, destination) {
        this.drawLine(cc.p(origin.x, origin.y), cc.p(destination.x, origin.y));
        this.drawLine(cc.p(destination.x, origin.y), cc.p(destination.x, destination.y));
        this.drawLine(cc.p(destination.x, destination.y), cc.p(origin.x, destination.y));
        this.drawLine(cc.p(origin.x, destination.y), cc.p(origin.x, origin.y));
      },
      drawSolidRect: function(origin, destination, color) {
        var vertices = [ origin, cc.p(destination.x, origin.y), destination, cc.p(origin.x, destination.y) ];
        this.drawSolidPoly(vertices, 4, color);
      },
      drawPoly: function(vertices, numOfVertices, closePolygon) {
        this.lazy_init();
        var glContext = this._renderContext;
        this._shader.use();
        this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
        glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_POSITION);
        this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
        var pointBuffer = glContext.createBuffer();
        glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
        glContext.bufferData(glContext.ARRAY_BUFFER, this._pointsToTypeArray(vertices), glContext.STATIC_DRAW);
        glContext.vertexAttribPointer(macro.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0);
        closePolygon ? glContext.drawArrays(glContext.LINE_LOOP, 0, vertices.length) : glContext.drawArrays(glContext.LINE_STRIP, 0, vertices.length);
        glContext.deleteBuffer(pointBuffer);
        cc.incrementGLDraws(1);
      },
      drawSolidPoly: function(poli, numberOfPoints, color) {
        this.lazy_init();
        color && this.setDrawColor(color.r, color.g, color.b, color.a);
        var glContext = this._renderContext;
        this._shader.use();
        this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
        glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_POSITION);
        this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
        var pointBuffer = glContext.createBuffer();
        glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
        glContext.bufferData(glContext.ARRAY_BUFFER, this._pointsToTypeArray(poli), glContext.STATIC_DRAW);
        glContext.vertexAttribPointer(macro.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0);
        glContext.drawArrays(glContext.TRIANGLE_FAN, 0, poli.length);
        glContext.deleteBuffer(pointBuffer);
        cc.incrementGLDraws(1);
      },
      drawCircle: function(center, radius, angle, segments, drawLineToCenter) {
        this.lazy_init();
        var additionalSegment = 1;
        drawLineToCenter && additionalSegment++;
        var coef = 2 * Math.PI / segments;
        var vertices = new Float32Array(2 * (segments + 2));
        if (!vertices) return;
        for (var i = 0; i <= segments; i++) {
          var rads = i * coef;
          var j = radius * Math.cos(rads + angle) + center.x;
          var k = radius * Math.sin(rads + angle) + center.y;
          vertices[2 * i] = j;
          vertices[2 * i + 1] = k;
        }
        vertices[2 * (segments + 1)] = center.x;
        vertices[2 * (segments + 1) + 1] = center.y;
        var glContext = this._renderContext;
        this._shader.use();
        this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
        glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_POSITION);
        this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
        var pointBuffer = glContext.createBuffer();
        glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
        glContext.bufferData(glContext.ARRAY_BUFFER, vertices, glContext.STATIC_DRAW);
        glContext.vertexAttribPointer(macro.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0);
        glContext.drawArrays(glContext.LINE_STRIP, 0, segments + additionalSegment);
        glContext.deleteBuffer(pointBuffer);
        cc.incrementGLDraws(1);
      },
      drawQuadBezier: function(origin, control, destination, segments) {
        this.lazy_init();
        var vertices = new Float32Array(2 * (segments + 1));
        var t = 0;
        for (var i = 0; i < segments; i++) {
          vertices[2 * i] = Math.pow(1 - t, 2) * origin.x + 2 * (1 - t) * t * control.x + t * t * destination.x;
          vertices[2 * i + 1] = Math.pow(1 - t, 2) * origin.y + 2 * (1 - t) * t * control.y + t * t * destination.y;
          t += 1 / segments;
        }
        vertices[2 * segments] = destination.x;
        vertices[2 * segments + 1] = destination.y;
        var glContext = this._renderContext;
        this._shader.use();
        this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
        glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_POSITION);
        this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
        var pointBuffer = glContext.createBuffer();
        glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
        glContext.bufferData(glContext.ARRAY_BUFFER, vertices, glContext.STATIC_DRAW);
        glContext.vertexAttribPointer(macro.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0);
        glContext.drawArrays(glContext.LINE_STRIP, 0, segments + 1);
        glContext.deleteBuffer(pointBuffer);
        cc.incrementGLDraws(1);
      },
      drawCubicBezier: function(origin, control1, control2, destination, segments) {
        this.lazy_init();
        var vertices = new Float32Array(2 * (segments + 1));
        var t = 0;
        for (var i = 0; i < segments; i++) {
          vertices[2 * i] = Math.pow(1 - t, 3) * origin.x + 3 * Math.pow(1 - t, 2) * t * control1.x + 3 * (1 - t) * t * t * control2.x + t * t * t * destination.x;
          vertices[2 * i + 1] = Math.pow(1 - t, 3) * origin.y + 3 * Math.pow(1 - t, 2) * t * control1.y + 3 * (1 - t) * t * t * control2.y + t * t * t * destination.y;
          t += 1 / segments;
        }
        vertices[2 * segments] = destination.x;
        vertices[2 * segments + 1] = destination.y;
        var glContext = this._renderContext;
        this._shader.use();
        this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
        glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_POSITION);
        this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
        var pointBuffer = glContext.createBuffer();
        glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
        glContext.bufferData(glContext.ARRAY_BUFFER, vertices, glContext.STATIC_DRAW);
        glContext.vertexAttribPointer(macro.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0);
        glContext.drawArrays(glContext.LINE_STRIP, 0, segments + 1);
        glContext.deleteBuffer(pointBuffer);
        cc.incrementGLDraws(1);
      },
      drawCatmullRom: function(points, segments) {
        this.drawCardinalSpline(points, .5, segments);
      },
      drawCardinalSpline: function(config, tension, segments) {
        this.lazy_init();
        var vertices = new Float32Array(2 * (segments + 1));
        var p, lt, deltaT = 1 / config.length;
        for (var i = 0; i < segments + 1; i++) {
          var dt = i / segments;
          if (1 === dt) {
            p = config.length - 1;
            lt = 1;
          } else {
            p = 0 | dt / deltaT;
            lt = (dt - deltaT * p) / deltaT;
          }
          var newPos = cc.cardinalSplineAt(cc.getControlPointAt(config, p - 1), cc.getControlPointAt(config, p), cc.getControlPointAt(config, p + 1), cc.getControlPointAt(config, p + 2), tension, lt);
          vertices[2 * i] = newPos.x;
          vertices[2 * i + 1] = newPos.y;
        }
        var glContext = this._renderContext;
        this._shader.use();
        this._shader.setUniformForModelViewAndProjectionMatrixWithMat4();
        glContext.enableVertexAttribArray(macro.VERTEX_ATTRIB_POSITION);
        this._shader.setUniformLocationWith4fv(this._colorLocation, this._colorArray);
        var pointBuffer = glContext.createBuffer();
        glContext.bindBuffer(glContext.ARRAY_BUFFER, pointBuffer);
        glContext.bufferData(glContext.ARRAY_BUFFER, vertices, glContext.STATIC_DRAW);
        glContext.vertexAttribPointer(macro.VERTEX_ATTRIB_POSITION, 2, glContext.FLOAT, false, 0, 0);
        glContext.drawArrays(glContext.LINE_STRIP, 0, segments + 1);
        glContext.deleteBuffer(pointBuffer);
        cc.incrementGLDraws(1);
      },
      setDrawColor: function(r, g, b, a) {
        this._colorArray[0] = r / 255;
        this._colorArray[1] = g / 255;
        this._colorArray[2] = b / 255;
        this._colorArray[3] = a / 255;
      },
      setPointSize: function(pointSize) {
        this._pointSize = pointSize;
      },
      setLineWidth: function(width) {
        this._renderContext.lineWidth && this._renderContext.lineWidth(width);
      }
    });
    module.exports = DrawingPrimitiveWebGL;
  }), {} ],
  39: [ (function(require, module, exports) {
    var EventTarget = require("./event/event-target");
    var View;
    true;
    View = require("./platform/CCView");
    require("../audio/CCAudioEngine");
    var inputManager = require("./platform/CCInputManager");
    var game = {
      EVENT_HIDE: "game_on_hide",
      EVENT_SHOW: "game_on_show",
      EVENT_GAME_INITED: "game_inited",
      EVENT_RENDERER_INITED: "renderer_inited",
      RENDER_TYPE_CANVAS: 0,
      RENDER_TYPE_WEBGL: 1,
      RENDER_TYPE_OPENGL: 2,
      _persistRootNodes: {},
      _ignoreRemovePersistNode: null,
      CONFIG_KEY: {
        width: "width",
        height: "height",
        debugMode: "debugMode",
        exposeClassName: "exposeClassName",
        showFPS: "showFPS",
        frameRate: "frameRate",
        id: "id",
        renderMode: "renderMode",
        registerSystemEvent: "registerSystemEvent",
        jsList: "jsList",
        scenes: "scenes"
      },
      _paused: true,
      _configLoaded: false,
      _isCloning: false,
      _prepareCalled: false,
      _prepared: false,
      _rendererInitialized: false,
      _renderContext: null,
      _intervalId: null,
      _lastTime: null,
      _frameTime: null,
      _sceneInfos: [],
      frame: null,
      container: null,
      canvas: null,
      config: null,
      onStart: null,
      setFrameRate: function(frameRate) {
        var self = this, config = self.config, CONFIG_KEY = self.CONFIG_KEY;
        config[CONFIG_KEY.frameRate] = frameRate;
        self._intervalId && window.cancelAnimFrame(self._intervalId);
        self._intervalId = 0;
        self._paused = true;
        self._setAnimFrame();
        self._runMainLoop();
      },
      step: function() {
        cc.director.mainLoop();
      },
      pause: function() {
        if (this._paused) return;
        this._paused = true;
        cc.audioEngine && cc.audioEngine._break();
        this._intervalId && window.cancelAnimFrame(this._intervalId);
        this._intervalId = 0;
      },
      resume: function() {
        if (!this._paused) return;
        this._paused = false;
        cc.audioEngine && cc.audioEngine._restore();
        this._runMainLoop();
      },
      isPaused: function() {
        return this._paused;
      },
      restart: function() {
        cc.director.once(cc.Director.EVENT_AFTER_DRAW, (function() {
          for (var id in game._persistRootNodes) game.removePersistRootNode(game._persistRootNodes[id]);
          cc.director.getScene().destroy();
          cc.Object._deferredDestroy();
          cc.director.purgeDirector();
          cc.audioEngine && cc.audioEngine.uncacheAll();
          cc.director.reset();
          game.onStart();
        }));
      },
      end: function() {
        close();
      },
      prepare: function(cb) {
        var self = this, config = self.config, CONFIG_KEY = self.CONFIG_KEY;
        if (!this._configLoaded) {
          this._loadConfig((function() {
            self.prepare(cb);
          }));
          return;
        }
        if (this._prepared) {
          cb && cb();
          return;
        }
        if (this._prepareCalled) return;
        if (cc._engineLoaded) {
          this._prepareCalled = true;
          this._initRenderer(config[CONFIG_KEY.width], config[CONFIG_KEY.height]);
          cc.view = View ? View._getInstance() : null;
          cc.director = cc.Director._getInstance();
          cc.director.setOpenGLView && cc.director.setOpenGLView(cc.view);
          cc.winSize = cc.director.getWinSize();
          true;
          this._initEvents();
          this._setAnimFrame();
          this._runMainLoop();
          var jsList = config[CONFIG_KEY.jsList];
          if (jsList && jsList.length > 0) cc.loader.load(jsList, (function(err) {
            if (err) throw new Error(JSON.stringify(err));
            self._prepared = true;
            cb && cb();
            self.emit(self.EVENT_GAME_INITED);
          })); else {
            cb && cb();
            self.emit(self.EVENT_GAME_INITED);
          }
          return;
        }
        cc.initEngine(this.config, (function() {
          self.prepare(cb);
        }));
      },
      run: function(config, onStart) {
        if ("function" === typeof config) game.onStart = config; else {
          config && (game.config = config);
          "function" === typeof onStart && (game.onStart = onStart);
        }
        this.prepare(game.onStart && game.onStart.bind(game));
      },
      addPersistRootNode: function(node) {
        if (!cc.Node.isNode(node) || !node.uuid) {
          cc.warnID(3800);
          return;
        }
        var id = node.uuid;
        if (!this._persistRootNodes[id]) {
          var scene = cc.director._scene;
          if (cc.isValid(scene)) {
            if (node.parent) {
              if (!(node.parent instanceof cc.Scene)) {
                cc.warnID(3801);
                return;
              }
              if (node.parent !== scene) {
                cc.warnID(3802);
                return;
              }
            } else node.parent = scene;
            this._persistRootNodes[id] = node;
            node._persistNode = true;
          }
        }
      },
      removePersistRootNode: function(node) {
        if (node !== this._ignoreRemovePersistNode) {
          var id = node.uuid || "";
          if (node === this._persistRootNodes[id]) {
            delete this._persistRootNodes[id];
            node._persistNode = false;
          }
        }
      },
      isPersistRootNode: function(node) {
        return node._persistNode;
      },
      _setAnimFrame: function() {
        this._lastTime = new Date();
        var frameRate = game.config[game.CONFIG_KEY.frameRate];
        this._frameTime = 1e3 / frameRate;
        if (60 !== frameRate && 30 !== frameRate) {
          window.requestAnimFrame = this._stTime;
          window.cancelAnimFrame = this._ctTime;
        } else {
          window.requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || this._stTime;
          window.cancelAnimFrame = window.cancelAnimationFrame || window.cancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || window.oCancelRequestAnimationFrame || window.webkitCancelRequestAnimationFrame || window.msCancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.oCancelAnimationFrame || this._ctTime;
        }
      },
      _stTime: function(callback) {
        var currTime = new Date().getTime();
        var timeToCall = Math.max(0, game._frameTime - (currTime - game._lastTime));
        var id = window.setTimeout((function() {
          callback();
        }), timeToCall);
        game._lastTime = currTime + timeToCall;
        return id;
      },
      _ctTime: function(id) {
        window.clearTimeout(id);
      },
      _runMainLoop: function() {
        var self = this, callback, config = self.config, CONFIG_KEY = self.CONFIG_KEY, director = cc.director, skip = true, frameRate = config[CONFIG_KEY.frameRate];
        director.setDisplayStats(config[CONFIG_KEY.showFPS]);
        callback = function() {
          if (!self._paused) {
            self._intervalId = window.requestAnimFrame(callback);
            if (30 === frameRate && (skip = !skip)) return;
            director.mainLoop();
          }
        };
        self._intervalId = window.requestAnimFrame(callback);
        self._paused = false;
      },
      _loadConfig: function(cb) {
        if (this.config) {
          this._initConfig(this.config);
          cb && cb();
          return;
        }
        if (document["ccConfig"]) {
          this._initConfig(document["ccConfig"]);
          cb && cb();
          return;
        }
        var self = this;
        cc.loader.load("project.json", (function(err, data) {
          err && cc.logID(3818);
          self._initConfig(data || {});
          cb && cb();
        }));
      },
      _initConfig: function(config) {
        var CONFIG_KEY = this.CONFIG_KEY;
        "number" !== typeof config[CONFIG_KEY.debugMode] && (config[CONFIG_KEY.debugMode] = 0);
        config[CONFIG_KEY.exposeClassName] = !!config[CONFIG_KEY.exposeClassName];
        "number" !== typeof config[CONFIG_KEY.frameRate] && (config[CONFIG_KEY.frameRate] = 60);
        "number" !== typeof config[CONFIG_KEY.renderMode] && (config[CONFIG_KEY.renderMode] = 0);
        "boolean" !== typeof config[CONFIG_KEY.registerSystemEvent] && (config[CONFIG_KEY.registerSystemEvent] = true);
        config[CONFIG_KEY.showFPS] = !(CONFIG_KEY.showFPS in config) || !!config[CONFIG_KEY.showFPS];
        this._sceneInfos = config[CONFIG_KEY.scenes] || [];
        this.collisionMatrix = config.collisionMatrix || [];
        this.groupList = config.groupList || [];
        cc._initDebugSetting(config[CONFIG_KEY.debugMode]);
        this.config = config;
        this._configLoaded = true;
      },
      _initRenderer: function(width, height) {
        if (this._rendererInitialized) return;
        if (!cc._supportRender) throw new Error("The renderer doesn't support the renderMode " + this.config[this.CONFIG_KEY.renderMode]);
        var el = this.config[game.CONFIG_KEY.id], win = window, localCanvas, localContainer, isWeChatGame = cc.sys.platform === cc.sys.WECHAT_GAME;
        if (isWeChatGame) {
          this.container = cc.container = localContainer = document.createElement("DIV");
          this.frame = localContainer.parentNode === document.body ? document.documentElement : localContainer.parentNode;
          this.canvas = cc._canvas = localCanvas = canvas;
        } else {
          var element = el instanceof HTMLElement ? el : document.querySelector(el) || document.querySelector("#" + el);
          if ("CANVAS" === element.tagName) {
            width = width || element.width;
            height = height || element.height;
            this.canvas = cc._canvas = localCanvas = element;
            this.container = cc.container = localContainer = document.createElement("DIV");
            localCanvas.parentNode && localCanvas.parentNode.insertBefore(localContainer, localCanvas);
          } else {
            "DIV" !== element.tagName && cc.warnID(3819);
            width = width || element.clientWidth;
            height = height || element.clientHeight;
            this.canvas = cc._canvas = localCanvas = document.createElement("CANVAS");
            this.container = cc.container = localContainer = document.createElement("DIV");
            element.appendChild(localContainer);
          }
          localContainer.setAttribute("id", "Cocos2dGameContainer");
          localContainer.appendChild(localCanvas);
          this.frame = localContainer.parentNode === document.body ? document.documentElement : localContainer.parentNode;
          function addClass(element, name) {
            var hasClass = (" " + element.className + " ").indexOf(" " + name + " ") > -1;
            if (!hasClass) {
              element.className && (element.className += " ");
              element.className += name;
            }
          }
          addClass(localCanvas, "gameCanvas");
          localCanvas.setAttribute("width", width || 480);
          localCanvas.setAttribute("height", height || 320);
          localCanvas.setAttribute("tabindex", 99);
        }
        if (cc._renderType === game.RENDER_TYPE_WEBGL) {
          var opts = {
            stencil: true,
            alpha: cc.macro.ENABLE_TRANSPARENT_CANVAS
          };
          isWeChatGame && (opts["preserveDrawingBuffer"] = true);
          this._renderContext = cc._renderContext = cc.webglContext = cc.create3DContext(localCanvas, opts);
        }
        if (this._renderContext) {
          cc.renderer = cc.rendererWebGL;
          win.gl = this._renderContext;
          cc.renderer.init();
        } else {
          cc._renderType = game.RENDER_TYPE_CANVAS;
          cc.renderer = cc.rendererCanvas;
          cc.renderer.init();
          this._renderContext = cc._renderContext = new cc.CanvasContextWrapper(localCanvas.getContext("2d"));
        }
        cc._gameDiv = localContainer;
        game.canvas.oncontextmenu = function() {
          if (!cc._isContextMenuEnable) return false;
        };
        this.emit(this.EVENT_RENDERER_INITED, true);
        this._rendererInitialized = true;
      },
      _initEvents: function() {
        var win = window, hidden, visibilityChange, _undef = "undefined";
        this.config[this.CONFIG_KEY.registerSystemEvent] && inputManager.registerSystemEvent(this.canvas);
        "undefined" !== typeof document.hidden ? hidden = "hidden" : "undefined" !== typeof document.mozHidden ? hidden = "mozHidden" : "undefined" !== typeof document.msHidden ? hidden = "msHidden" : "undefined" !== typeof document.webkitHidden && (hidden = "webkitHidden");
        var changeList = [ "visibilitychange", "mozvisibilitychange", "msvisibilitychange", "webkitvisibilitychange", "qbrowserVisibilityChange" ];
        var onHidden = function() {
          game.emit(game.EVENT_HIDE, game);
        };
        var onShow = function() {
          game.emit(game.EVENT_SHOW, game);
        };
        if (hidden) for (var i = 0; i < changeList.length; i++) document.addEventListener(changeList[i], (function(event) {
          var visible = document[hidden];
          visible = visible || event["hidden"];
          visible ? onHidden() : onShow();
        }), false); else {
          win.addEventListener("blur", onHidden, false);
          win.addEventListener("focus", onShow, false);
        }
        navigator.userAgent.indexOf("MicroMessenger") > -1 && (win.onfocus = onShow);
        false;
        if ("onpageshow" in window && "onpagehide" in window) {
          win.addEventListener("pagehide", onHidden, false);
          win.addEventListener("pageshow", onShow, false);
        }
        this.on(game.EVENT_HIDE, (function() {
          game.pause();
        }));
        this.on(game.EVENT_SHOW, (function() {
          game.resume();
        }));
      }
    };
    EventTarget.call(game);
    cc.js.addon(game, EventTarget.prototype);
    cc.game = module.exports = game;
  }), {
    "../audio/CCAudioEngine": 23,
    "./event/event-target": 112,
    "./platform/CCInputManager": 179,
    "./platform/CCView": 185
  } ],
  40: [ (function(require, module, exports) {
    "use strict";
    var PrefabHelper = require("./utils/prefab-helper");
    var SgHelper = require("./utils/scene-graph-helper");
    var eventManager = require("./event-manager");
    var Flags = cc.Object.Flags;
    var Destroying = Flags.Destroying;
    var POSITION_CHANGED = "position-changed";
    var SIZE_CHANGED = "size-changed";
    var ANCHOR_CHANGED = "anchor-changed";
    var ROTATION_CHANGED = "rotation-changed";
    var SCALE_CHANGED = "scale-changed";
    var CHILD_REORDER = "child-reorder";
    var ERR_INVALID_NUMBER = false;
    var Misc = require("./utils/misc");
    var Event = require("./event/event");
    var ActionManagerExist = !!cc.ActionManager;
    var emptyFunc = function() {};
    var EventType = cc.Enum({
      TOUCH_START: "touchstart",
      TOUCH_MOVE: "touchmove",
      TOUCH_END: "touchend",
      TOUCH_CANCEL: "touchcancel",
      MOUSE_DOWN: "mousedown",
      MOUSE_MOVE: "mousemove",
      MOUSE_ENTER: "mouseenter",
      MOUSE_LEAVE: "mouseleave",
      MOUSE_UP: "mouseup",
      MOUSE_WHEEL: "mousewheel"
    });
    var _touchEvents = [ EventType.TOUCH_START, EventType.TOUCH_MOVE, EventType.TOUCH_END, EventType.TOUCH_CANCEL ];
    var _mouseEvents = [ EventType.MOUSE_DOWN, EventType.MOUSE_ENTER, EventType.MOUSE_MOVE, EventType.MOUSE_LEAVE, EventType.MOUSE_UP, EventType.MOUSE_WHEEL ];
    var _currentHovered = null;
    var _touchStartHandler = function(touch, event) {
      var pos = touch.getLocation();
      var node = this.owner;
      if (node._hitTest(pos, this)) {
        false;
        event.type = EventType.TOUCH_START;
        event.touch = touch;
        event.bubbles = true;
        node.dispatchEvent(event);
        false;
        return true;
      }
      return false;
    };
    var _touchMoveHandler = function(touch, event) {
      false;
      var node = this.owner;
      event.type = EventType.TOUCH_MOVE;
      event.touch = touch;
      event.bubbles = true;
      node.dispatchEvent(event);
      false;
    };
    var _touchEndHandler = function(touch, event) {
      false;
      var pos = touch.getLocation();
      var node = this.owner;
      node._hitTest(pos, this) ? event.type = EventType.TOUCH_END : event.type = EventType.TOUCH_CANCEL;
      event.touch = touch;
      event.bubbles = true;
      node.dispatchEvent(event);
      false;
    };
    var _mouseDownHandler = function(event) {
      var pos = event.getLocation();
      var node = this.owner;
      if (node._hitTest(pos, this)) {
        false;
        event.type = EventType.MOUSE_DOWN;
        event.bubbles = true;
        node.dispatchEvent(event);
        false;
        event.stopPropagation();
      }
    };
    var _mouseMoveHandler = function(event) {
      var pos = event.getLocation();
      var node = this.owner;
      var hit = node._hitTest(pos, this);
      false;
      if (hit) {
        if (!this._previousIn) {
          if (_currentHovered) {
            event.type = EventType.MOUSE_LEAVE;
            _currentHovered.dispatchEvent(event);
            _currentHovered._mouseListener._previousIn = false;
          }
          _currentHovered = this.owner;
          event.type = EventType.MOUSE_ENTER;
          node.dispatchEvent(event);
          this._previousIn = true;
        }
        event.type = EventType.MOUSE_MOVE;
        event.bubbles = true;
        node.dispatchEvent(event);
      } else {
        if (!this._previousIn) return;
        event.type = EventType.MOUSE_LEAVE;
        node.dispatchEvent(event);
        this._previousIn = false;
        _currentHovered = null;
      }
      false;
      event.stopPropagation();
    };
    var _mouseUpHandler = function(event) {
      var pos = event.getLocation();
      var node = this.owner;
      if (node._hitTest(pos, this)) {
        false;
        event.type = EventType.MOUSE_UP;
        event.bubbles = true;
        node.dispatchEvent(event);
        false;
        event.stopPropagation();
      }
    };
    var _mouseWheelHandler = function(event) {
      var pos = event.getLocation();
      var node = this.owner;
      if (node._hitTest(pos, this)) {
        false;
        event.type = EventType.MOUSE_WHEEL;
        event.bubbles = true;
        node.dispatchEvent(event);
        false;
        event.stopPropagation();
      }
    };
    function _searchMaskInParent(node) {
      var Mask = cc.Mask;
      if (Mask) {
        var index = 0;
        for (var curr = node; curr && cc.Node.isNode(curr); curr = curr._parent, ++index) if (curr.getComponent(Mask)) return {
          index: index,
          node: curr
        };
      }
      return null;
    }
    function updateOrder(node) {
      node._parent._delaySort();
      true;
      eventManager._setDirtyForNode(node);
    }
    var Node = cc.Class({
      name: "cc.Node",
      extends: require("./utils/base-node"),
      properties: {
        _opacity: 255,
        _color: cc.Color.WHITE,
        _cascadeOpacityEnabled: true,
        _anchorPoint: cc.p(.5, .5),
        _contentSize: cc.size(0, 0),
        _rotationX: 0,
        _rotationY: 0,
        _scaleX: 1,
        _scaleY: 1,
        _position: cc.p(0, 0),
        _skewX: 0,
        _skewY: 0,
        _localZOrder: 0,
        _globalZOrder: 0,
        _opacityModifyRGB: false,
        groupIndex: {
          default: 0,
          type: cc.Integer
        },
        group: {
          get: function() {
            return cc.game.groupList[this.groupIndex] || "";
          },
          set: function(value) {
            this.groupIndex = cc.game.groupList.indexOf(value);
            this.emit("group-changed");
          }
        },
        x: {
          get: function() {
            return this._position.x;
          },
          set: function(value) {
            var localPosition = this._position;
            if (value !== localPosition.x) {
              true;
              var oldValue;
              false;
              localPosition.x = value;
              this._sgNode.setPositionX(value);
              var cache = this._hasListenerCache;
              if (cache && cache[POSITION_CHANGED]) {
                false;
                this.emit(POSITION_CHANGED);
              }
            }
          }
        },
        y: {
          get: function() {
            return this._position.y;
          },
          set: function(value) {
            var localPosition = this._position;
            if (value !== localPosition.y) {
              true;
              var oldValue;
              false;
              localPosition.y = value;
              this._sgNode.setPositionY(value);
              var cache = this._hasListenerCache;
              if (cache && cache[POSITION_CHANGED]) {
                false;
                this.emit(POSITION_CHANGED);
              }
            }
          }
        },
        rotation: {
          get: function() {
            this._rotationX !== this._rotationY && cc.logID(1602);
            return this._rotationX;
          },
          set: function(value) {
            if (this._rotationX !== value || this._rotationY !== value) {
              this._rotationX = this._rotationY = value;
              this._sgNode.rotation = value;
              var cache = this._hasListenerCache;
              cache && cache[ROTATION_CHANGED] && this.emit(ROTATION_CHANGED);
            }
          }
        },
        rotationX: {
          get: function() {
            return this._rotationX;
          },
          set: function(value) {
            if (this._rotationX !== value) {
              this._rotationX = value;
              this._sgNode.rotationX = value;
              var cache = this._hasListenerCache;
              cache && cache[ROTATION_CHANGED] && this.emit(ROTATION_CHANGED);
            }
          }
        },
        rotationY: {
          get: function() {
            return this._rotationY;
          },
          set: function(value) {
            if (this._rotationY !== value) {
              this._rotationY = value;
              this._sgNode.rotationY = value;
              var cache = this._hasListenerCache;
              cache && cache[ROTATION_CHANGED] && this.emit(ROTATION_CHANGED);
            }
          }
        },
        scaleX: {
          get: function() {
            return this._scaleX;
          },
          set: function(value) {
            if (this._scaleX !== value) {
              this._scaleX = value;
              this._sgNode.scaleX = value;
              var cache = this._hasListenerCache;
              cache && cache[SCALE_CHANGED] && this.emit(SCALE_CHANGED);
            }
          }
        },
        scaleY: {
          get: function() {
            return this._scaleY;
          },
          set: function(value) {
            if (this._scaleY !== value) {
              this._scaleY = value;
              this._sgNode.scaleY = value;
              var cache = this._hasListenerCache;
              cache && cache[SCALE_CHANGED] && this.emit(SCALE_CHANGED);
            }
          }
        },
        skewX: {
          get: function() {
            return this._skewX;
          },
          set: function(value) {
            this._skewX = value;
            this._sgNode.skewX = value;
          }
        },
        skewY: {
          get: function() {
            return this._skewY;
          },
          set: function(value) {
            this._skewY = value;
            this._sgNode.skewY = value;
          }
        },
        opacity: {
          get: function() {
            return this._opacity;
          },
          set: function(value) {
            if (this._opacity !== value) {
              this._opacity = value;
              this._sgNode.setOpacity(value);
              if (!this._cascadeOpacityEnabled) {
                var sizeProvider = this._sizeProvider;
                sizeProvider instanceof _ccsg.Node && sizeProvider !== this._sgNode && sizeProvider.setOpacity(value);
              }
            }
          },
          range: [ 0, 255 ]
        },
        cascadeOpacity: {
          get: function() {
            return this._cascadeOpacityEnabled;
          },
          set: function(value) {
            if (this._cascadeOpacityEnabled !== value) {
              this._cascadeOpacityEnabled = value;
              this._sgNode.cascadeOpacity = value;
              var opacity = value ? 255 : this._opacity;
              var sizeProvider = this._sizeProvider;
              sizeProvider instanceof _ccsg.Node && sizeProvider.setOpacity(opacity);
            }
          }
        },
        color: {
          get: function() {
            return this._color.clone();
          },
          set: function(value) {
            if (!this._color.equals(value)) {
              this._color.fromColor(value);
              false;
              this._sizeProvider instanceof _ccsg.Node && this._sizeProvider.setColor(value);
            }
          }
        },
        anchorX: {
          get: function() {
            return this._anchorPoint.x;
          },
          set: function(value) {
            var anchorPoint = this._anchorPoint;
            if (anchorPoint.x !== value) {
              anchorPoint.x = value;
              var sizeProvider = this._sizeProvider;
              sizeProvider instanceof _ccsg.Node && sizeProvider.setAnchorPoint(anchorPoint);
              this.emit(ANCHOR_CHANGED);
            }
          }
        },
        anchorY: {
          get: function() {
            return this._anchorPoint.y;
          },
          set: function(value) {
            var anchorPoint = this._anchorPoint;
            if (anchorPoint.y !== value) {
              anchorPoint.y = value;
              var sizeProvider = this._sizeProvider;
              sizeProvider instanceof _ccsg.Node && sizeProvider.setAnchorPoint(anchorPoint);
              this.emit(ANCHOR_CHANGED);
            }
          }
        },
        width: {
          get: function() {
            if (this._sizeProvider) {
              var w = this._sizeProvider._getWidth();
              this._contentSize.width = w;
              return w;
            }
            return this._contentSize.width;
          },
          set: function(value) {
            if (value !== this._contentSize.width) {
              var sizeProvider = this._sizeProvider;
              sizeProvider && sizeProvider.setContentSize(value, sizeProvider._getHeight());
              var clone;
              false;
              this._contentSize.width = value;
              false;
              this.emit(SIZE_CHANGED);
            }
          }
        },
        height: {
          get: function() {
            if (this._sizeProvider) {
              var h = this._sizeProvider._getHeight();
              this._contentSize.height = h;
              return h;
            }
            return this._contentSize.height;
          },
          set: function(value) {
            if (value !== this._contentSize.height) {
              var sizeProvider = this._sizeProvider;
              sizeProvider && sizeProvider.setContentSize(sizeProvider._getWidth(), value);
              var clone;
              false;
              this._contentSize.height = value;
              false;
              this.emit(SIZE_CHANGED);
            }
          }
        },
        zIndex: {
          get: function() {
            return this._localZOrder;
          },
          set: function(value) {
            if (this._localZOrder !== value) {
              this._localZOrder = value;
              this._sgNode.zIndex = value;
              this._parent && updateOrder(this);
            }
          }
        }
      },
      ctor: function(name) {
        var sgNode = this._sgNode = new _ccsg.Node();
        false;
        cc.game._isCloning || (sgNode.cascadeOpacity = true);
        this._sizeProvider = null;
        this._reorderChildDirty = false;
        this._widget = null;
        this._touchListener = null;
        this._mouseListener = null;
        false;
      },
      statics: {
        isNode: function(obj) {
          return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene));
        }
      },
      _onSetParent: function(value) {
        var sgNode = this._sgNode;
        sgNode.parent && sgNode.parent.removeChild(sgNode, false);
        if (value) {
          value._sgNode.addChild(sgNode);
          value._delaySort();
        }
      },
      _onSiblingIndexChanged: function(index) {
        var parent = this._parent;
        var siblings = parent._children;
        var i = 0, len = siblings.length, sibling;
        var zOrder;
        var nextSibling;
        var oldZOrder;
        false;
        for (;i < len; i++) {
          sibling = siblings[i]._sgNode;
          sibling._arrivalOrder = i;
          eventManager._setDirtyForNode(sibling);
        }
        cc.renderer.childrenOrderDirty = true;
        parent._sgNode._reorderChildDirty = true;
        parent._delaySort();
      },
      _onPreDestroy: function() {
        var destroyByParent = this._onPreDestroyBase();
        ActionManagerExist && cc.director.getActionManager().removeAllActionsFromTarget(this);
        _currentHovered === this && (_currentHovered = null);
        false;
        this._reorderChildDirty && cc.director.__fastOff(cc.Director.EVENT_AFTER_UPDATE, this.sortAllChildren, this);
        eventManager.removeListeners(this);
        if (destroyByParent) false; else {
          this._removeSgNode();
          false;
        }
      },
      _onPostActivated: function(active) {
        var actionManager = ActionManagerExist ? cc.director.getActionManager() : null;
        if (active) {
          actionManager && actionManager.resumeTarget(this);
          eventManager.resumeTarget(this);
          if (this._touchListener) {
            var mask = this._touchListener.mask = _searchMaskInParent(this);
            this._mouseListener && (this._mouseListener.mask = mask);
          } else this._mouseListener && (this._mouseListener.mask = _searchMaskInParent(this));
        } else {
          actionManager && actionManager.pauseTarget(this);
          eventManager.pauseTarget(this);
        }
      },
      _onHierarchyChanged: function(oldParent) {
        this._onHierarchyChangedBase(oldParent);
        cc._widgetManager._nodesOrderDirty = true;
      },
      _onBatchCreated: function() {
        var prefabInfo = this._prefab;
        prefabInfo && prefabInfo.sync && !prefabInfo._synced && prefabInfo.root === this && PrefabHelper.syncWithPrefab(this);
        this._updateDummySgNode();
        this._parent && this._parent._sgNode.addChild(this._sgNode);
        if (!this._activeInHierarchy) {
          ActionManagerExist && cc.director.getActionManager().pauseTarget(this);
          eventManager.pauseTarget(this);
        }
        var children = this._children;
        for (var i = 0, len = children.length; i < len; i++) children[i]._onBatchCreated();
      },
      on: function(type, callback, target, useCapture) {
        var newAdded = false;
        if (-1 !== _touchEvents.indexOf(type)) {
          if (!this._touchListener) {
            this._touchListener = cc.EventListener.create({
              event: cc.EventListener.TOUCH_ONE_BY_ONE,
              swallowTouches: true,
              owner: this,
              mask: _searchMaskInParent(this),
              onTouchBegan: _touchStartHandler,
              onTouchMoved: _touchMoveHandler,
              onTouchEnded: _touchEndHandler
            });
            false;
            eventManager.addListener(this._touchListener, this);
            newAdded = true;
          }
        } else if (-1 !== _mouseEvents.indexOf(type) && !this._mouseListener) {
          this._mouseListener = cc.EventListener.create({
            event: cc.EventListener.MOUSE,
            _previousIn: false,
            owner: this,
            mask: _searchMaskInParent(this),
            onMouseDown: _mouseDownHandler,
            onMouseMove: _mouseMoveHandler,
            onMouseUp: _mouseUpHandler,
            onMouseScroll: _mouseWheelHandler
          });
          false;
          eventManager.addListener(this._mouseListener, this);
          newAdded = true;
        }
        newAdded && !this._activeInHierarchy && cc.director.getScheduler().schedule((function() {
          this._activeInHierarchy || eventManager.pauseTarget(this);
        }), this, 0, 0, 0, false);
        return this._EventTargetOn(type, callback, target, useCapture);
      },
      off: function(type, callback, target, useCapture) {
        this._EventTargetOff(type, callback, target, useCapture);
        -1 !== _touchEvents.indexOf(type) ? this._checkTouchListeners() : -1 !== _mouseEvents.indexOf(type) && this._checkMouseListeners();
      },
      targetOff: function(target) {
        this._EventTargetTargetOff(target);
        this._checkTouchListeners();
        this._checkMouseListeners();
      },
      pauseSystemEvents: function(recursive) {
        eventManager.pauseTarget(this, recursive);
      },
      resumeSystemEvents: function(recursive) {
        eventManager.resumeTarget(this, recursive);
      },
      _checkTouchListeners: function() {
        if (!(this._objFlags & Destroying) && this._touchListener) {
          var i = 0;
          if (this._bubblingListeners) for (;i < _touchEvents.length; ++i) if (this._bubblingListeners.has(_touchEvents[i])) return;
          if (this._capturingListeners) for (;i < _touchEvents.length; ++i) if (this._capturingListeners.has(_touchEvents[i])) return;
          eventManager.removeListener(this._touchListener);
          this._touchListener = null;
        }
      },
      _checkMouseListeners: function() {
        if (!(this._objFlags & Destroying) && this._mouseListener) {
          var i = 0;
          if (this._bubblingListeners) for (;i < _mouseEvents.length; ++i) if (this._bubblingListeners.has(_mouseEvents[i])) return;
          if (this._capturingListeners) for (;i < _mouseEvents.length; ++i) if (this._capturingListeners.has(_mouseEvents[i])) return;
          _currentHovered === this && (_currentHovered = null);
          eventManager.removeListener(this._mouseListener);
          this._mouseListener = null;
        }
      },
      _hitTest: function(point, listener) {
        var w = this.width, h = this.height, pt = point;
        var Camera = cc.Camera;
        Camera && Camera.main && Camera.main.containsNode(this) && (pt = Camera.main.getCameraToWorldPoint(pt));
        var trans = cc.affineTransformInvertIn(this._sgNode.getNodeToWorldTransform());
        pt = cc.pointApplyAffineTransform(pt, trans);
        pt.x += this._anchorPoint.x * w;
        pt.y += this._anchorPoint.y * h;
        var left = pt.x, right = w - pt.x, bottom = pt.y, top = h - pt.y;
        if (left >= 0 && right >= 0 && top >= 0 && bottom >= 0) {
          if (listener && listener.mask) {
            var mask = listener.mask;
            var parent = this;
            for (var i = 0; parent && i < mask.index; ++i, parent = parent.parent) ;
            if (parent === mask.node) {
              var comp = parent.getComponent(cc.Mask);
              return !comp || !comp.enabledInHierarchy || comp._hitTest(point);
            }
            listener.mask = null;
            return true;
          }
          return true;
        }
        return false;
      },
      _getCapturingTargets: function(type, array) {
        var parent = this.parent;
        while (parent) {
          parent.hasEventListener(type, true) && array.push(parent);
          parent = parent.parent;
        }
      },
      _getBubblingTargets: function(type, array) {
        var parent = this.parent;
        while (parent) {
          parent.hasEventListener(type) && array.push(parent);
          parent = parent.parent;
        }
      },
      isRunning: function() {
        return this._activeInHierarchy;
      },
      runAction: ActionManagerExist ? function(action) {
        if (!this.active) return;
        cc.assertID(action, 1618);
        cc.macro.ENABLE_GC_FOR_NATIVE_OBJECTS || this._retainAction(action);
        false;
        cc.director.getActionManager().addAction(action, this, false);
        return action;
      } : emptyFunc,
      pauseAllActions: ActionManagerExist ? function() {
        cc.director.getActionManager().pauseTarget(this);
      } : emptyFunc,
      resumeAllActions: ActionManagerExist ? function() {
        cc.director.getActionManager().resumeTarget(this);
      } : emptyFunc,
      stopAllActions: ActionManagerExist ? function() {
        cc.director.getActionManager().removeAllActionsFromTarget(this);
      } : emptyFunc,
      stopAction: ActionManagerExist ? function(action) {
        cc.director.getActionManager().removeAction(action);
      } : emptyFunc,
      stopActionByTag: ActionManagerExist ? function(tag) {
        if (tag === cc.Action.TAG_INVALID) {
          cc.logID(1612);
          return;
        }
        cc.director.getActionManager().removeActionByTag(tag, this);
      } : emptyFunc,
      getActionByTag: ActionManagerExist ? function(tag) {
        if (tag === cc.Action.TAG_INVALID) {
          cc.logID(1613);
          return null;
        }
        return cc.director.getActionManager().getActionByTag(tag, this);
      } : function() {
        return null;
      },
      getNumberOfRunningActions: ActionManagerExist ? function() {
        return cc.director.getActionManager().getNumberOfRunningActionsInTarget(this);
      } : function() {
        return 0;
      },
      _retainAction: function(action) {
        false;
      },
      _releaseAllActions: function() {
        var i;
        false;
      },
      setTag: function(value) {
        this._tag = value;
        this._sgNode.tag = value;
      },
      getPosition: function() {
        return new cc.Vec2(this._position);
      },
      setPosition: function(newPosOrX, y) {
        var x;
        if ("undefined" === typeof y) {
          x = newPosOrX.x;
          y = newPosOrX.y;
        } else x = newPosOrX;
        var locPosition = this._position;
        if (locPosition.x === x && locPosition.y === y) return;
        var oldPosition;
        false;
        true;
        locPosition.x = x;
        true;
        locPosition.y = y;
        this._sgNode.setPosition(x, y);
        var cache = this._hasListenerCache;
        if (cache && cache[POSITION_CHANGED]) {
          false;
          this.emit(POSITION_CHANGED);
        }
      },
      getScale: function() {
        this._scaleX !== this._scaleY && cc.logID(1603);
        return this._scaleX;
      },
      setScale: function(scaleX, scaleY) {
        if ("object" === typeof scaleX) {
          scaleY = scaleX.y;
          scaleX = scaleX.x;
        } else scaleY = scaleY || 0 === scaleY ? scaleY : scaleX;
        if (this._scaleX !== scaleX || this._scaleY !== scaleY) {
          this._scaleX = scaleX;
          this._scaleY = scaleY;
          this._sgNode.setScale(scaleX, scaleY);
          var cache = this._hasListenerCache;
          cache && cache[SCALE_CHANGED] && this.emit(SCALE_CHANGED);
        }
      },
      getContentSize: function(ignoreSizeProvider) {
        if (this._sizeProvider && !ignoreSizeProvider) {
          var size = this._sizeProvider.getContentSize();
          this._contentSize = size;
          return cc.size(size);
        }
        return cc.size(this._contentSize);
      },
      setContentSize: function(size, height) {
        var locContentSize = this._contentSize;
        var clone;
        if (void 0 === height) {
          if (size.width === locContentSize.width && size.height === locContentSize.height) return;
          false;
          locContentSize.width = size.width;
          locContentSize.height = size.height;
        } else {
          if (size === locContentSize.width && height === locContentSize.height) return;
          false;
          locContentSize.width = size;
          locContentSize.height = height;
        }
        this._sizeProvider && this._sizeProvider.setContentSize(locContentSize);
        false;
        this.emit(SIZE_CHANGED);
      },
      setOpacityModifyRGB: function(opacityValue) {
        if (this._opacityModifyRGB !== opacityValue) {
          this._opacityModifyRGB = opacityValue;
          this._sgNode.setOpacityModifyRGB(opacityValue);
          var sizeProvider = this._sizeProvider;
          sizeProvider instanceof _ccsg.Node && sizeProvider !== this._sgNode && sizeProvider.setOpacityModifyRGB(opacityValue);
        }
      },
      isOpacityModifyRGB: function() {
        return this._opacityModifyRGB;
      },
      setGlobalZOrder: function(globalZOrder) {
        this._globalZOrder = globalZOrder;
        this._sgNode.setGlobalZOrder(globalZOrder);
      },
      getGlobalZOrder: function() {
        this._globalZOrder = this._sgNode.getGlobalZOrder();
        return this._globalZOrder;
      },
      getAnchorPoint: function() {
        return cc.p(this._anchorPoint);
      },
      setAnchorPoint: function(point, y) {
        var locAnchorPoint = this._anchorPoint;
        if (void 0 === y) {
          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;
        }
        var sizeProvider = this._sizeProvider;
        sizeProvider instanceof _ccsg.Node && sizeProvider.setAnchorPoint(locAnchorPoint);
        this.emit(ANCHOR_CHANGED);
      },
      getAnchorPointInPoints: function() {
        return this._sgNode.getAnchorPointInPoints();
      },
      getDisplayedOpacity: function() {
        return this._sgNode.getDisplayedOpacity();
      },
      _updateDisplayedOpacity: function(parentOpacity) {
        this._sgNode.updateDisplayedOpacity(parentOpacity);
      },
      getDisplayedColor: function() {
        return this._sgNode.getDisplayedColor();
      },
      getNodeToParentTransformAR: function() {
        var contentSize = this.getContentSize();
        var mat = this._sgNode.getNodeToParentTransform();
        if (!this._isSgTransformArToMe(contentSize)) {
          var tx = this._anchorPoint.x * contentSize.width;
          var ty = this._anchorPoint.y * contentSize.height;
          var offset = cc.affineTransformMake(1, 0, 0, 1, tx, ty);
          mat = cc.affineTransformConcatIn(offset, mat);
        }
        return mat;
      },
      getBoundingBox: function() {
        var size = this.getContentSize();
        var rect = cc.rect(0, 0, size.width, size.height);
        return cc._rectApplyAffineTransformIn(rect, this.getNodeToParentTransform());
      },
      getBoundingBoxToWorld: function() {
        var trans;
        this.parent && (trans = this.parent.getNodeToWorldTransformAR());
        return this._getBoundingBoxTo(trans);
      },
      _getBoundingBoxTo: function(parentTransformAR) {
        var size = this.getContentSize();
        var width = size.width;
        var height = size.height;
        var rect = cc.rect(-this._anchorPoint.x * width, -this._anchorPoint.y * height, width, height);
        var transAR = cc.affineTransformConcat(this.getNodeToParentTransformAR(), parentTransformAR);
        cc._rectApplyAffineTransformIn(rect, transAR);
        if (!this._children) return rect;
        var locChildren = this._children;
        for (var i = 0; i < locChildren.length; i++) {
          var child = locChildren[i];
          if (child && child.active) {
            var childRect = child._getBoundingBoxTo(transAR);
            childRect && (rect = cc.rectUnion(rect, childRect));
          }
        }
        return rect;
      },
      getNodeToParentTransform: function() {
        var contentSize = this.getContentSize();
        var mat = this._sgNode.getNodeToParentTransform();
        if (this._isSgTransformArToMe(contentSize)) {
          var tx = -this._anchorPoint.x * contentSize.width;
          var ty = -this._anchorPoint.y * contentSize.height;
          var offset = cc.affineTransformMake(1, 0, 0, 1, tx, ty);
          mat = cc.affineTransformConcatIn(offset, mat);
        }
        return mat;
      },
      getNodeToWorldTransform: function() {
        var contentSize = this.getContentSize();
        cc._renderType === cc.game.RENDER_TYPE_CANVAS && cc.director._visitScene();
        var mat = this._sgNode.getNodeToWorldTransform();
        if (this._isSgTransformArToMe(contentSize)) {
          var tx = -this._anchorPoint.x * contentSize.width;
          var ty = -this._anchorPoint.y * contentSize.height;
          var offset = cc.affineTransformMake(1, 0, 0, 1, tx, ty);
          mat = cc.affineTransformConcatIn(offset, mat);
        }
        return mat;
      },
      getNodeToWorldTransformAR: function() {
        var contentSize = this.getContentSize();
        cc._renderType === cc.game.RENDER_TYPE_CANVAS && cc.director._visitScene();
        var mat = this._sgNode.getNodeToWorldTransform();
        if (!this._isSgTransformArToMe(contentSize)) {
          var tx = this._anchorPoint.x * contentSize.width;
          var ty = this._anchorPoint.y * contentSize.height;
          var offset = cc.affineTransformMake(1, 0, 0, 1, tx, ty);
          mat = cc.affineTransformConcatIn(offset, mat);
        }
        return mat;
      },
      getParentToNodeTransform: function() {
        return this._sgNode.getParentToNodeTransform();
      },
      getWorldToNodeTransform: function() {
        cc._renderType === cc.game.RENDER_TYPE_CANVAS && cc.director._visitScene();
        return this._sgNode.getWorldToNodeTransform();
      },
      _isSgTransformArToMe: function(myContentSize) {
        var renderSize = this._sgNode.getContentSize();
        if (0 === renderSize.width && 0 === renderSize.height && (0 !== myContentSize.width || 0 !== myContentSize.height)) return true;
        if (this._sgNode.isIgnoreAnchorPointForPosition()) return true;
        return false;
      },
      convertToNodeSpace: function(worldPoint) {
        cc._renderType === cc.game.RENDER_TYPE_CANVAS && cc.director._visitScene();
        var nodePositionIgnoreAnchorPoint = this._sgNode.convertToNodeSpace(worldPoint);
        return cc.pAdd(nodePositionIgnoreAnchorPoint, cc.p(this._anchorPoint.x * this._contentSize.width, this._anchorPoint.y * this._contentSize.height));
      },
      convertToWorldSpace: function(nodePoint) {
        cc._renderType === cc.game.RENDER_TYPE_CANVAS && cc.director._visitScene();
        var x = nodePoint.x - this._anchorPoint.x * this._contentSize.width;
        var y = nodePoint.y - this._anchorPoint.y * this._contentSize.height;
        return cc.v2(this._sgNode.convertToWorldSpace(cc.v2(x, y)));
      },
      convertToNodeSpaceAR: function(worldPoint) {
        cc._renderType === cc.game.RENDER_TYPE_CANVAS && cc.director._visitScene();
        return this._sgNode.isIgnoreAnchorPointForPosition() ? cc.v2(this._sgNode.convertToNodeSpace(worldPoint)) : this._sgNode.convertToNodeSpaceAR(worldPoint);
      },
      convertToWorldSpaceAR: function(nodePoint) {
        cc._renderType === cc.game.RENDER_TYPE_CANVAS && cc.director._visitScene();
        return this._sgNode.isIgnoreAnchorPointForPosition() ? cc.v2(this._sgNode.convertToWorldSpace(nodePoint)) : cc.v2(this._sgNode.convertToWorldSpaceAR(nodePoint));
      },
      convertTouchToNodeSpace: function(touch) {
        return this.convertToNodeSpace(touch.getLocation());
      },
      convertTouchToNodeSpaceAR: function(touch) {
        return this.convertToNodeSpaceAR(touch.getLocation());
      },
      setNodeDirty: function() {
        this._sgNode.setNodeDirty();
      },
      addChild: function(child, localZOrder, tag) {
        localZOrder = void 0 === localZOrder ? child._localZOrder : localZOrder;
        var name, setTag = false;
        if ("undefined" === typeof tag) {
          tag = void 0;
          name = child._name;
        } else if (cc.js.isString(tag)) {
          name = tag;
          tag = void 0;
        } else if (cc.js.isNumber(tag)) {
          setTag = true;
          name = "";
        }
        false;
        cc.assertID(child, 1606);
        cc.assertID(null === child._parent, 1605);
        child.parent = this;
        child.zIndex = localZOrder;
        setTag ? child.setTag(tag) : child.setName(name);
      },
      cleanup: function() {
        ActionManagerExist && cc.director.getActionManager().removeAllActionsFromTarget(this);
        eventManager.removeListeners(this);
        var i, len = this._children.length, node;
        for (i = 0; i < len; ++i) {
          node = this._children[i];
          node && node.cleanup();
        }
      },
      sortAllChildren: function() {
        if (this._reorderChildDirty) {
          this._reorderChildDirty = false;
          var _children = this._children;
          if (_children.length > 1) {
            var len = _children.length, i, j, child;
            for (i = 1; i < len; i++) {
              child = _children[i];
              j = i - 1;
              while (j >= 0) {
                if (child._localZOrder < _children[j]._localZOrder) _children[j + 1] = _children[j]; else {
                  if (!(child._localZOrder === _children[j]._localZOrder && child._sgNode._arrivalOrder < _children[j]._sgNode._arrivalOrder)) break;
                  _children[j + 1] = _children[j];
                }
                j--;
              }
              _children[j + 1] = child;
            }
            this.emit(CHILD_REORDER);
          }
          cc.director.__fastOff(cc.Director.EVENT_AFTER_UPDATE, this.sortAllChildren, this);
        }
      },
      _delaySort: function() {
        if (!this._reorderChildDirty) {
          this._reorderChildDirty = true;
          cc.director.__fastOn(cc.Director.EVENT_AFTER_UPDATE, this.sortAllChildren, this);
        }
      },
      _updateDummySgNode: function() {
        var self = this;
        var sgNode = self._sgNode;
        sgNode.setPosition(self._position);
        sgNode.setRotationX(self._rotationX);
        sgNode.setRotationY(self._rotationY);
        sgNode.setScale(self._scaleX, self._scaleY);
        sgNode.setSkewX(self._skewX);
        sgNode.setSkewY(self._skewY);
        var arrivalOrder = sgNode._arrivalOrder;
        sgNode.setLocalZOrder(self._localZOrder);
        sgNode._arrivalOrder = arrivalOrder;
        sgNode.setGlobalZOrder(self._globalZOrder);
        false;
        sgNode.setOpacity(self._opacity);
        sgNode.setOpacityModifyRGB(self._opacityModifyRGB);
        sgNode.setCascadeOpacityEnabled(self._cascadeOpacityEnabled);
        sgNode.setTag(self._tag);
      },
      _updateSgNode: function() {
        this._updateDummySgNode();
        var sgNode = this._sgNode;
        sgNode.setAnchorPoint(this._anchorPoint);
        sgNode.setVisible(this._active);
        sgNode.setColor(this._color);
        var actionManager = ActionManagerExist ? cc.director.getActionManager() : null;
        if (this._activeInHierarchy) {
          actionManager && actionManager.resumeTarget(this);
          eventManager.resumeTarget(this);
        } else {
          actionManager && actionManager.pauseTarget(this);
          eventManager.pauseTarget(this);
        }
      },
      _removeSgNode: SgHelper.removeSgNode,
      onRestore: false
    });
    var updateListeners;
    false;
    var SameNameGetSets = [ "parent", "tag", "skewX", "skewY", "position", "rotation", "rotationX", "rotationY", "scale", "scaleX", "scaleY", "opacity", "color" ];
    var DiffNameGetSets = {
      x: [ "getPositionX", "setPositionX" ],
      y: [ "getPositionY", "setPositionY" ],
      zIndex: [ "getLocalZOrder", "setLocalZOrder" ],
      opacityModifyRGB: [ "isOpacityModifyRGB", "setOpacityModifyRGB" ],
      cascadeOpacity: [ "isCascadeOpacityEnabled", "setCascadeOpacityEnabled" ]
    };
    Misc.propertyDefine(Node, SameNameGetSets, DiffNameGetSets);
    Node.EventType = EventType;
    cc.Node = module.exports = Node;
  }), {
    "./event-manager": 110,
    "./event/event": 113,
    "./utils/base-node": 220,
    "./utils/misc": 225,
    "./utils/prefab-helper": 227,
    "./utils/scene-graph-helper": 228
  } ],
  41: [ (function(require, module, exports) {
    var NIL = function() {};
    cc.Scene = cc.Class({
      name: "cc.Scene",
      extends: require("./CCNode"),
      properties: {
        autoReleaseAssets: {
          default: void 0,
          type: cc.Boolean
        }
      },
      ctor: function() {
        var sgNode = this._sgNode = new _ccsg.Scene();
        false;
        sgNode.setAnchorPoint(0, 0);
        this._anchorPoint.x = 0;
        this._anchorPoint.y = 0;
        this._activeInHierarchy = false;
        this._inited = !cc.game._isCloning;
        this.dependAssets = null;
      },
      destroy: function() {
        this._super();
        this._activeInHierarchy = false;
      },
      _onHierarchyChanged: NIL,
      _instantiate: null,
      _load: function() {
        if (!this._inited) {
          false;
          this._onBatchCreated();
          this._inited = true;
        }
      },
      _activate: function(active) {
        active = false !== active;
        false, false;
        cc.director._nodeActivator.activateNode(this, active);
      }
    });
    module.exports = cc.Scene;
  }), {
    "./CCNode": 40
  } ],
  42: [ (function(require, module, exports) {
    var MAX_POOL_SIZE = 20;
    var ListEntry = function(prev, next, callback, target, priority, paused, markedForDeletion) {
      this.prev = prev;
      this.next = next;
      this.callback = callback;
      this.target = target;
      this.priority = priority;
      this.paused = paused;
      this.markedForDeletion = markedForDeletion;
      this.isUpdate = !callback;
    };
    var _listEntries = [];
    ListEntry.get = function(prev, next, callback, target, priority, paused, markedForDeletion) {
      var result = _listEntries.pop();
      if (result) {
        result.prev = prev;
        result.next = next;
        result.callback = callback;
        result.target = target;
        result.priority = priority;
        result.paused = paused;
        result.markedForDeletion = markedForDeletion;
        result.isUpdate = !callback;
      } else result = new ListEntry(prev, next, callback, target, priority, paused, markedForDeletion);
      return result;
    };
    ListEntry.put = function(entry) {
      if (_listEntries.length < MAX_POOL_SIZE) {
        entry.prev = entry.next = entry.callback = entry.target = null;
        _listEntries.push(entry);
      }
    };
    var HashUpdateEntry = function(list, entry, target, callback) {
      this.list = list;
      this.entry = entry;
      this.target = target;
      this.callback = callback;
    };
    var _hashUpdateEntries = [];
    HashUpdateEntry.get = function(list, entry, target, callback) {
      var result = _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 (_hashUpdateEntries.length < MAX_POOL_SIZE) {
        entry.list = entry.entry = entry.target = entry.callback = null;
        _hashUpdateEntries.push(entry);
      }
    };
    var HashTimerEntry = function(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused) {
      var _t = this;
      _t.timers = timers;
      _t.target = target;
      _t.timerIndex = timerIndex;
      _t.currentTimer = currentTimer;
      _t.currentTimerSalvaged = currentTimerSalvaged;
      _t.paused = paused;
    };
    var _hashTimerEntries = [];
    HashTimerEntry.get = function(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused) {
      var result = _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 (_hashTimerEntries.length < MAX_POOL_SIZE) {
        entry.timers = entry.target = entry.currentTimer = null;
        _hashTimerEntries.push(entry);
      }
    };
    function CallbackTimer() {
      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(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 === cc.macro.REPEAT_FOREVER;
      return true;
    };
    proto.getInterval = function() {
      return this._interval;
    };
    proto.setInterval = function(interval) {
      this._interval = interval;
    };
    proto.update = function(dt) {
      if (-1 === this._elapsed) {
        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;
          }
          this._callback && !this._runForever && this._timesExecuted > this._repeat && this.cancel();
        }
      }
    };
    proto.getCallback = function() {
      return this._callback;
    };
    proto.trigger = function() {
      if (this._target && this._callback) {
        this._lock = true;
        this._callback.call(this._target, this._elapsed);
        this._lock = false;
      }
    };
    proto.cancel = function() {
      this._scheduler.unschedule(this._callback, this._target);
    };
    var _timers = [];
    CallbackTimer.get = function() {
      return _timers.pop() || new CallbackTimer();
    };
    CallbackTimer.put = function(timer) {
      if (_timers.length < MAX_POOL_SIZE && !timer._lock) {
        timer._scheduler = timer._target = timer._callback = null;
        _timers.push(timer);
      }
    };
    var getTargetId = function(target) {
      return target.__instanceId || target.uuid;
    };
    cc.Scheduler = cc._Class.extend({
      ctor: function() {
        this._timeScale = 1;
        this._updatesNegList = [];
        this._updates0List = [];
        this._updatesPosList = [];
        this._hashForUpdates = {};
        this._hashForTimers = {};
        this._currentTarget = null;
        this._currentTargetSalvaged = false;
        this._updateHashLocked = false;
        this._arrayForTimers = [];
      },
      _removeHashElement: function(element) {
        delete this._hashForTimers[getTargetId(element.target)];
        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);
      },
      _removeUpdateFromHash: function(entry) {
        var targetId = getTargetId(entry.target);
        var self = this, element = self._hashForUpdates[targetId];
        if (element) {
          var list = element.list, 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);
        }
      },
      _priorityIn: function(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);
      },
      _appendIn: function(ppList, listElement) {
        ppList.push(listElement);
      },
      setTimeScale: function(timeScale) {
        this._timeScale = timeScale;
      },
      getTimeScale: function() {
        return this._timeScale;
      },
      update: function(dt) {
        this._updateHashLocked = true;
        1 !== this._timeScale && (dt *= this._timeScale);
        var i, list, len, entry;
        for (i = 0, list = this._updatesNegList, len = list.length; i < len; i++) {
          entry = list[i];
          entry.paused || entry.markedForDeletion || (entry.isUpdate ? entry.target.update(dt) : entry.callback.call(entry.target, dt));
        }
        for (i = 0, list = this._updates0List, len = list.length; i < len; i++) {
          entry = list[i];
          entry.paused || entry.markedForDeletion || (entry.isUpdate ? entry.target.update(dt) : entry.callback.call(entry.target, dt));
        }
        for (i = 0, list = this._updatesPosList, len = list.length; i < len; i++) {
          entry = list[i];
          entry.paused || entry.markedForDeletion || (entry.isUpdate ? entry.target.update(dt) : entry.callback.call(entry.target, dt));
        }
        var elt, 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 && 0 === this._currentTarget.timers.length) {
            this._removeHashElement(this._currentTarget);
            --i;
          }
        }
        for (i = 0, list = this._updatesNegList; i < list.length; ) {
          entry = list[i];
          entry.markedForDeletion ? this._removeUpdateFromHash(entry) : i++;
        }
        for (i = 0, list = this._updates0List; i < list.length; ) {
          entry = list[i];
          entry.markedForDeletion ? this._removeUpdateFromHash(entry) : i++;
        }
        for (i = 0, list = this._updatesPosList; i < list.length; ) {
          entry = list[i];
          entry.markedForDeletion ? this._removeUpdateFromHash(entry) : i++;
        }
        this._updateHashLocked = false;
        this._currentTarget = null;
      },
      scheduleCallbackForTarget: function(target, callback_fn, interval, repeat, delay, paused) {
        this.schedule(callback_fn, target, interval, repeat, delay, paused);
      },
      schedule: function(callback, target, interval, repeat, delay, paused) {
        "use strict";
        if ("function" !== typeof callback) {
          var tmp = callback;
          callback = target;
          target = tmp;
        }
        if (4 === arguments.length || 5 === arguments.length) {
          paused = !!repeat;
          repeat = cc.macro.REPEAT_FOREVER;
          delay = 0;
        }
        cc.assertID(target, 1502);
        var instanceId = getTargetId(target);
        cc.assertID(instanceId, 1510);
        var element = this._hashForTimers[instanceId];
        if (element) element.paused !== paused && cc.warnID(1511); else {
          element = HashTimerEntry.get(null, target, 0, null, null, paused);
          this._arrayForTimers.push(element);
          this._hashForTimers[instanceId] = element;
        }
        var timer, i;
        if (null == element.timers) element.timers = []; else for (i = 0; i < element.timers.length; ++i) {
          timer = element.timers[i];
          if (timer && callback === timer._callback) {
            cc.logID(1507, timer.getInterval(), interval);
            timer._interval = interval;
            return;
          }
        }
        timer = CallbackTimer.get();
        timer.initWithCallback(this, callback, target, interval, repeat, delay);
        element.timers.push(timer);
        this._currentTarget === element && this._currentTargetSalvaged && (this._currentTargetSalvaged = false);
      },
      scheduleUpdate: function(target, priority, paused, updateFunc) {
        var targetId = getTargetId(target);
        cc.assertID(targetId, 1510);
        var hashElement = this._hashForUpdates[targetId];
        if (hashElement && hashElement.entry) {
          if (hashElement.entry.priority === priority) {
            hashElement.entry.markedForDeletion = false;
            hashElement.entry.paused = paused;
            return;
          }
          if (this._updateHashLocked) {
            cc.logID(1506);
            hashElement.entry.markedForDeletion = false;
            hashElement.entry.paused = paused;
            return;
          }
          this.unscheduleUpdate(target);
        }
        updateFunc && cc.warnID(1512);
        var listElement = ListEntry.get(null, null, updateFunc, target, priority, paused, false);
        var ppList;
        if (0 === priority) {
          ppList = this._updates0List;
          this._appendIn(ppList, listElement);
        } else {
          ppList = priority < 0 ? this._updatesNegList : this._updatesPosList;
          this._priorityIn(ppList, listElement, priority);
        }
        this._hashForUpdates[targetId] = HashUpdateEntry.get(ppList, listElement, target, null);
      },
      unschedule: function(callback, target) {
        if (!target || !callback) return;
        var targetId = getTargetId(target);
        cc.assertID(targetId, 1510);
        var self = this, 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) {
              timer !== element.currentTimer || element.currentTimerSalvaged || (element.currentTimerSalvaged = true);
              timers.splice(i, 1);
              CallbackTimer.put(timer);
              element.timerIndex >= i && element.timerIndex--;
              0 === timers.length && (self._currentTarget === element ? self._currentTargetSalvaged = true : self._removeHashElement(element));
              return;
            }
          }
        }
      },
      unscheduleUpdate: function(target) {
        if (!target) return;
        var targetId = getTargetId(target);
        cc.assertID(targetId, 1510);
        var element = this._hashForUpdates[targetId];
        element && (this._updateHashLocked ? element.entry.markedForDeletion = true : this._removeUpdateFromHash(element.entry));
      },
      unscheduleAllForTarget: function(target) {
        if (!target) return;
        var targetId = getTargetId(target);
        cc.assertID(targetId, 1510);
        var element = this._hashForTimers[targetId];
        if (element) {
          var timers = element.timers;
          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;
          this._currentTarget === element ? this._currentTargetSalvaged = true : this._removeHashElement(element);
        }
        this.unscheduleUpdate(target);
      },
      unscheduleAll: function() {
        this.unscheduleAllWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM);
      },
      unscheduleAllWithMinPriority: function(minPriority) {
        var i, element, 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];
          entry && entry.priority >= minPriority && this.unscheduleUpdate(entry.target);
          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];
          entry && this.unscheduleUpdate(entry.target);
          temp_length == this._updates0List.length && i++;
        }
        for (i = 0; i < this._updatesPosList.length; ) {
          temp_length = this._updatesPosList.length;
          entry = this._updatesPosList[i];
          entry && entry.priority >= minPriority && this.unscheduleUpdate(entry.target);
          temp_length == this._updatesPosList.length && i++;
        }
      },
      isScheduled: function(callback, target) {
        cc.assertID(callback, 1508);
        cc.assertID(target, 1509);
        var targetId = getTargetId(target);
        cc.assertID(targetId, 1510);
        var element = this._hashForTimers[targetId];
        if (!element) return false;
        if (null == element.timers) return false;
        var timers = element.timers;
        for (var i = 0; i < timers.length; ++i) {
          var timer = timers[i];
          if (callback === timer._callback) return true;
        }
        return false;
      },
      pauseAllTargets: function() {
        return this.pauseAllTargetsWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM);
      },
      pauseAllTargetsWithMinPriority: function(minPriority) {
        var idsWithSelectors = [];
        var self = this, element, locArrayForTimers = self._arrayForTimers;
        var i, 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 && 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 && entry.priority >= minPriority) {
            entry.paused = true;
            idsWithSelectors.push(entry.target);
          }
        }
        return idsWithSelectors;
      },
      resumeTargets: function(targetsToResume) {
        if (!targetsToResume) return;
        for (var i = 0; i < targetsToResume.length; i++) this.resumeTarget(targetsToResume[i]);
      },
      pauseTarget: function(target) {
        cc.assertID(target, 1503);
        var targetId = getTargetId(target);
        cc.assertID(targetId, 1510);
        var self = this, element = self._hashForTimers[targetId];
        element && (element.paused = true);
        var elementUpdate = self._hashForUpdates[targetId];
        elementUpdate && (elementUpdate.entry.paused = true);
      },
      resumeTarget: function(target) {
        cc.assertID(target, 1504);
        var targetId = getTargetId(target);
        cc.assertID(targetId, 1510);
        var self = this, element = self._hashForTimers[targetId];
        element && (element.paused = false);
        var elementUpdate = self._hashForUpdates[targetId];
        elementUpdate && (elementUpdate.entry.paused = false);
      },
      isTargetPaused: function(target) {
        cc.assertID(target, 1505);
        var targetId = getTargetId(target);
        cc.assertID(targetId, 1510);
        var element = this._hashForTimers[targetId];
        if (element) return element.paused;
        var elementUpdate = this._hashForUpdates[targetId];
        if (elementUpdate) return elementUpdate.entry.paused;
        return false;
      },
      scheduleUpdateForTarget: function(target, priority, paused) {
        this.scheduleUpdate(target, priority, paused);
      },
      unscheduleCallbackForTarget: function(target, callback) {
        this.unschedule(callback, target);
      },
      unscheduleUpdateForTarget: function(target) {
        this.unscheduleUpdate(target);
      },
      unscheduleAllCallbacksForTarget: function(target) {
        this.unscheduleAllForTarget(target);
      },
      unscheduleAllCallbacks: function() {
        this.unscheduleAllWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM);
      },
      unscheduleAllCallbacksWithMinPriority: function(minPriority) {
        this.unscheduleAllWithMinPriority(minPriority);
      }
    });
    cc.Scheduler.PRIORITY_SYSTEM = 1 << 31;
    cc.Scheduler.PRIORITY_NON_SYSTEM = cc.Scheduler.PRIORITY_SYSTEM + 1;
  }), {} ],
  43: [ (function(require, module, exports) {
    var RawAsset = require("./CCRawAsset");
    cc.Asset = cc.Class({
      name: "cc.Asset",
      extends: RawAsset,
      properties: {
        rawUrl: {
          get: function() {
            if (this._rawFiles) {
              if (cc.AssetLibrary) return cc.AssetLibrary.getLibUrlNoExt(this._uuid) + "/" + this._rawFiles[0];
              cc.errorID(6400);
            }
            return "";
          },
          visible: false
        },
        rawUrls: {
          get: function() {
            if (this._rawFiles) {
              if (cc.AssetLibrary) {
                var dir = cc.AssetLibrary.getLibUrlNoExt(this._uuid) + "/";
                return this._rawFiles.map((function(filename) {
                  return dir + filename;
                }));
              }
              cc.errorID(6401);
            }
            return [];
          },
          visible: false
        },
        _rawFiles: null
      },
      statics: {
        deserialize: function(data) {
          return cc.deserialize(data);
        },
        preventDeferredLoadDependents: false
      },
      serialize: function() {
        return Editor.serialize(this);
      },
      createNode: null,
      _setRawFiles: function(rawFiles) {
        this._rawFiles = rawFiles.length > 0 ? rawFiles : null;
      },
      _preloadRawFiles: null
    });
    module.exports = cc.Asset;
  }), {
    "./CCRawAsset": 49
  } ],
  44: [ (function(require, module, exports) {
    var AudioClip = cc.Class({
      name: "cc.AudioClip",
      extends: cc.RawAsset
    });
    cc.AudioClip = AudioClip;
    module.exports = AudioClip;
  }), {} ],
  45: [ (function(require, module, exports) {
    var BitmapFont = cc.Class({
      name: "cc.BitmapFont",
      extends: cc.Font,
      properties: {
        fntDataStr: {
          default: ""
        },
        spriteFrame: {
          default: null,
          type: cc.SpriteFrame
        },
        fontSize: {
          default: -1
        },
        _fntConfig: null
      }
    });
    cc.BitmapFont = BitmapFont;
    module.exports = BitmapFont;
  }), {} ],
  46: [ (function(require, module, exports) {
    var Font = cc.Class({
      name: "cc.Font",
      extends: cc.Asset
    });
    cc.Font = Font;
    module.exports = Font;
  }), {} ],
  47: [ (function(require, module, exports) {
    var LabelAtlas = cc.Class({
      name: "cc.LabelAtlas",
      extends: cc.BitmapFont
    });
    cc.LabelAtlas = LabelAtlas;
    module.exports = LabelAtlas;
  }), {} ],
  48: [ (function(require, module, exports) {
    var Prefab = cc.Class({
      name: "cc.Prefab",
      extends: cc.Asset,
      properties: {
        data: null,
        asyncLoadAssets: void 0,
        _createFunction: {
          default: null,
          serializable: false
        }
      },
      createNode: false,
      compileCreateFunction: function() {
        var jit = require("../platform/instantiate-jit");
        this._createFunction = jit.compile(this.data);
      },
      _doInstantiate: function(rootToRedirect) {
        this.data._prefab ? this.data._prefab._synced = true : cc.warnID(3700);
        this._createFunction || this.compileCreateFunction();
        return this._createFunction(rootToRedirect);
      },
      _instantiate: function() {
        var node;
        true;
        node = this._doInstantiate();
        this.data._instantiate(node);
        false, false;
        return node;
      }
    });
    cc.Prefab = module.exports = Prefab;
    cc.js.obsolete(cc, "cc._Prefab", "Prefab");
  }), {
    "../platform/instantiate-jit": 194
  } ],
  49: [ (function(require, module, exports) {
    var CCObject = require("../platform/CCObject");
    cc.RawAsset = cc.Class({
      name: "cc.RawAsset",
      extends: CCObject,
      ctor: function() {
        Object.defineProperty(this, "_uuid", {
          value: "",
          writable: true
        });
      },
      statics: {
        createNodeByInfo: null
      }
    });
    Object.defineProperty(cc.RawAsset, "isRawAssetType", {
      value: function(ctor) {
        return cc.isChildClassOf(ctor, cc.RawAsset) && !cc.isChildClassOf(ctor, cc.Asset);
      }
    });
    module.exports = cc.RawAsset;
  }), {
    "../platform/CCObject": 181
  } ],
  50: [ (function(require, module, exports) {
    var Scene = cc.Class({
      name: "cc.SceneAsset",
      extends: cc.Asset,
      properties: {
        scene: null,
        asyncLoadAssets: void 0
      }
    });
    cc.SceneAsset = Scene;
    module.exports = Scene;
  }), {} ],
  51: [ (function(require, module, exports) {
    var Script = cc.Class({
      name: "cc.Script",
      extends: cc.Asset
    });
    cc._Script = Script;
    var JavaScript = cc.Class({
      name: "cc.JavaScript",
      extends: Script
    });
    cc._JavaScript = JavaScript;
    var CoffeeScript = cc.Class({
      name: "cc.CoffeeScript",
      extends: Script
    });
    cc._CoffeeScript = CoffeeScript;
    var TypeScript = cc.Class({
      name: "cc.TypeScript",
      extends: Script
    });
    cc._TypeScript = TypeScript;
  }), {} ],
  52: [ (function(require, module, exports) {
    var SpriteAtlas = cc.Class({
      name: "cc.SpriteAtlas",
      extends: cc.Asset,
      properties: {
        _spriteFrames: {
          default: {}
        }
      },
      getTexture: function() {
        var keys = Object.keys(this._spriteFrames);
        if (keys.length > 0) {
          var spriteFrame = this._spriteFrames[keys[0]];
          return spriteFrame ? spriteFrame.getTexture() : null;
        }
        return null;
      },
      getSpriteFrame: function(key) {
        return this._spriteFrames[key];
      },
      getSpriteFrames: function() {
        var frames = [];
        var spriteFrames = this._spriteFrames;
        for (var key in spriteFrames) frames.push(spriteFrames[key]);
        return frames;
      }
    });
    cc.SpriteAtlas = SpriteAtlas;
    module.exports = SpriteAtlas;
  }), {} ],
  53: [ (function(require, module, exports) {
    var TTFFont = cc.Class({
      name: "cc.TTFFont",
      extends: cc.Font
    });
    cc.TTFFont = TTFFont;
    module.exports = TTFFont;
  }), {} ],
  54: [ (function(require, module, exports) {
    require("./CCRawAsset");
    require("./CCAsset");
    require("./CCFont");
    require("./CCPrefab");
    require("./CCAudioClip");
    require("./CCScripts");
    require("./CCSceneAsset");
    require("../sprites/CCSpriteFrame");
    require("../textures/CCTexture2D");
    require("./CCTTFFont");
    require("./CCSpriteAtlas");
    require("./CCBitmapFont");
    require("./CCLabelAtlas");
  }), {
    "../sprites/CCSpriteFrame": 214,
    "../textures/CCTexture2D": 215,
    "./CCAsset": 43,
    "./CCAudioClip": 44,
    "./CCBitmapFont": 45,
    "./CCFont": 46,
    "./CCLabelAtlas": 47,
    "./CCPrefab": 48,
    "./CCRawAsset": 49,
    "./CCSceneAsset": 50,
    "./CCScripts": 51,
    "./CCSpriteAtlas": 52,
    "./CCTTFFont": 53
  } ],
  55: [ (function(require, module, exports) {
    var Misc = require("../utils/misc");
    var eventManager = require("../event-manager");
    var ActionManagerExist = !!cc.ActionManager;
    var emptyFunc = function() {};
    cc.s_globalOrderOfArrival = 1;
    _ccsg.Node = cc.Class({
      name: "ccsg.Node",
      properties: {
        _running: false,
        _localZOrder: 0,
        _globalZOrder: 0,
        _arrivalOrder: 0,
        _reorderChildDirty: false,
        _vertexZ: 0,
        _customZ: void 0,
        _rotationX: 0,
        _rotationY: 0,
        _scaleX: 1,
        _scaleY: 1,
        _position: cc.p(0, 0),
        _skewX: 0,
        _skewY: 0,
        _children: [],
        _visible: true,
        _anchorPoint: cc.p(0, 0),
        _contentSize: cc.size(0, 0),
        _parent: null,
        _ignoreAnchorPointForPosition: false,
        tag: cc.macro.NODE_TAG_INVALID,
        _name: "",
        _realOpacity: 255,
        _realColor: cc.Color.WHITE,
        _cascadeColorEnabled: false,
        _cascadeOpacityEnabled: false,
        _isTransitionFinished: false,
        _actionManager: null,
        _scheduler: null,
        _renderCmd: null
      },
      ctor: function() {
        this.__instanceId = cc.ClassManager.getNewInstanceId();
        this._renderCmd = this._createRenderCmd();
      },
      init: function() {
        return true;
      },
      attr: function(attrs) {
        for (var key in attrs) this[key] = attrs[key];
      },
      getSkewX: function() {
        return this._skewX;
      },
      setSkewX: function(newSkewX) {
        this._skewX = newSkewX;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
      },
      getSkewY: function() {
        return this._skewY;
      },
      setSkewY: function(newSkewY) {
        this._skewY = newSkewY;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
      },
      setLocalZOrder: function(localZOrder) {
        this._parent ? this._parent.reorderChild(this, localZOrder) : this._localZOrder = localZOrder;
        eventManager._setDirtyForNode(this);
      },
      _setLocalZOrder: function(localZOrder) {
        this._localZOrder = localZOrder;
      },
      getLocalZOrder: function() {
        return this._localZOrder;
      },
      getZOrder: function() {
        cc.logID(1600);
        return this.getLocalZOrder();
      },
      setZOrder: function(z) {
        cc.logID(1601);
        this.setLocalZOrder(z);
      },
      setGlobalZOrder: function(globalZOrder) {
        if (this._globalZOrder !== globalZOrder) {
          this._globalZOrder = globalZOrder;
          eventManager._setDirtyForNode(this);
        }
      },
      getGlobalZOrder: function() {
        return this._globalZOrder;
      },
      getVertexZ: function() {
        return this._vertexZ;
      },
      setVertexZ: function(Var) {
        this._customZ = this._vertexZ = Var;
      },
      getRotation: function() {
        this._rotationX !== this._rotationY && cc.logID(1602);
        return this._rotationX;
      },
      setRotation: function(newRotation) {
        this._rotationX = this._rotationY = newRotation;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
      },
      getRotationX: function() {
        return this._rotationX;
      },
      setRotationX: function(rotationX) {
        this._rotationX = rotationX;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
      },
      getRotationY: function() {
        return this._rotationY;
      },
      setRotationY: function(rotationY) {
        this._rotationY = rotationY;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
      },
      getScale: function() {
        this._scaleX !== this._scaleY && cc.logID(1603);
        return this._scaleX;
      },
      setScale: function(scale, scaleY) {
        this._scaleX = scale;
        this._scaleY = scaleY || 0 === scaleY ? scaleY : scale;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
      },
      getScaleX: function() {
        return this._scaleX;
      },
      setScaleX: function(newScaleX) {
        this._scaleX = newScaleX;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
      },
      getScaleY: function() {
        return this._scaleY;
      },
      setScaleY: function(newScaleY) {
        this._scaleY = newScaleY;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
      },
      setPosition: function(newPosOrxValue, yValue) {
        var locPosition = this._position;
        if (void 0 === yValue) {
          if (locPosition.x === newPosOrxValue.x && locPosition.y === newPosOrxValue.y) return;
          locPosition.x = newPosOrxValue.x;
          locPosition.y = newPosOrxValue.y;
        } else {
          if (locPosition.x === newPosOrxValue && locPosition.y === yValue) return;
          locPosition.x = newPosOrxValue;
          locPosition.y = yValue;
        }
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
      },
      getPosition: function() {
        return cc.p(this._position);
      },
      getPositionX: function() {
        return this._position.x;
      },
      setPositionX: function(x) {
        this._position.x = x;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
      },
      getPositionY: function() {
        return this._position.y;
      },
      setPositionY: function(y) {
        this._position.y = y;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
      },
      getChildrenCount: function() {
        return this._children.length;
      },
      getChildren: function() {
        return this._children;
      },
      isVisible: function() {
        return this._visible;
      },
      setVisible: function(visible) {
        if (this._visible !== visible) {
          this._visible = visible;
          this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
          cc.renderer.childrenOrderDirty = true;
        }
      },
      getAnchorPoint: function() {
        return cc.p(this._anchorPoint);
      },
      setAnchorPoint: function(point, y) {
        var locAnchorPoint = this._anchorPoint;
        if (void 0 === y) {
          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._renderCmd._updateAnchorPointInPoint();
      },
      _getAnchorX: function() {
        return this._anchorPoint.x;
      },
      _setAnchorX: function(x) {
        if (this._anchorPoint.x === x) return;
        this._anchorPoint.x = x;
        this._renderCmd._updateAnchorPointInPoint();
      },
      _getAnchorY: function() {
        return this._anchorPoint.y;
      },
      _setAnchorY: function(y) {
        if (this._anchorPoint.y === y) return;
        this._anchorPoint.y = y;
        this._renderCmd._updateAnchorPointInPoint();
      },
      getAnchorPointInPoints: function() {
        return this._renderCmd.getAnchorPointInPoints();
      },
      _getWidth: function() {
        return this._contentSize.width;
      },
      _setWidth: function(width) {
        this._contentSize.width = width;
        this._renderCmd._updateAnchorPointInPoint();
      },
      _getHeight: function() {
        return this._contentSize.height;
      },
      _setHeight: function(height) {
        this._contentSize.height = height;
        this._renderCmd._updateAnchorPointInPoint();
      },
      getContentSize: function() {
        return cc.size(this._contentSize);
      },
      setContentSize: function(size, height) {
        var locContentSize = this._contentSize;
        if (void 0 === height) {
          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._renderCmd._updateAnchorPointInPoint();
      },
      isRunning: function() {
        return this._running;
      },
      getParent: function() {
        return this._parent;
      },
      setParent: function(parent) {
        this._parent = parent;
        var dirtyFlags = _ccsg.Node._dirtyFlags;
        this._renderCmd.setDirtyFlag(dirtyFlags.transformDirty | dirtyFlags.opacityDirty);
      },
      isIgnoreAnchorPointForPosition: function() {
        return this._ignoreAnchorPointForPosition;
      },
      setIgnoreAnchorPointForPosition: function(newValue) {
        if (newValue !== this._ignoreAnchorPointForPosition) {
          this._ignoreAnchorPointForPosition = newValue;
          this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
        }
      },
      getTag: function() {
        return this.tag;
      },
      setTag: function(tag) {
        this.tag = tag;
      },
      setName: function(name) {
        this._name = name;
      },
      getName: function() {
        return this._name;
      },
      updateOrderOfArrival: function() {
        this._arrivalOrder = ++cc.s_globalOrderOfArrival;
      },
      getScheduler: function() {
        return this._scheduler || cc.director.getScheduler();
      },
      setScheduler: function(scheduler) {
        if (this._scheduler !== scheduler) {
          this.unscheduleAllCallbacks();
          this._scheduler = scheduler;
        }
      },
      boundingBox: function() {
        cc.logID(1608);
        return this.getBoundingBox();
      },
      getBoundingBox: function() {
        var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height);
        return cc._rectApplyAffineTransformIn(rect, this.getNodeToParentTransform());
      },
      cleanup: function() {
        this.stopAllActions();
        this.unscheduleAllCallbacks();
        eventManager.removeListeners(this);
      },
      getChildByTag: function(aTag) {
        var __children = this._children;
        if (null !== __children) for (var i = 0; i < __children.length; i++) {
          var node = __children[i];
          if (node && node.tag === aTag) return node;
        }
        return null;
      },
      getChildByName: function(name) {
        if (!name) {
          cc.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;
      },
      addChild: function(child, localZOrder, tag) {
        localZOrder = void 0 === localZOrder ? child._localZOrder : localZOrder;
        var name, setTag = false;
        if (void 0 === tag) name = child._name; else if ("string" === typeof tag) {
          name = tag;
          tag = void 0;
        } else if ("number" === typeof tag) {
          setTag = true;
          name = "";
        }
        cc.assertID(child, 1606);
        cc.assertID(null === child._parent, 1605);
        this._addChildHelper(child, localZOrder, tag, name, setTag);
      },
      _addChildHelper: function(child, localZOrder, tag, name, setTag) {
        this._children || (this._children = []);
        this._insertChild(child, localZOrder);
        setTag ? child.setTag(tag) : child.setName(name);
        child.setParent(this);
        child.updateOrderOfArrival();
        if (this._running) {
          child.performRecursive(_ccsg.Node.performType.onEnter);
          this._isTransitionFinished && child.performRecursive(_ccsg.Node.performType.onEnterTransitionDidFinish);
        }
        child._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
        this._cascadeColorEnabled && child._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.colorDirty);
        this._cascadeOpacityEnabled && child._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.opacityDirty);
      },
      removeFromParent: function(cleanup) {
        if (this._parent) {
          void 0 === cleanup && (cleanup = true);
          this._parent.removeChild(this, cleanup);
        }
      },
      removeFromParentAndCleanup: function(cleanup) {
        cc.logID(1607);
        this.removeFromParent(cleanup);
      },
      removeChild: function(child, cleanup) {
        if (0 === this._children.length) return;
        void 0 === cleanup && (cleanup = true);
        this._children.indexOf(child) > -1 && this._detachChild(child, cleanup);
        cc.renderer.childrenOrderDirty = true;
      },
      removeChildByTag: function(tag, cleanup) {
        tag === cc.macro.NODE_TAG_INVALID && cc.logID(1609);
        var child = this.getChildByTag(tag);
        child ? this.removeChild(child, cleanup) : cc.logID(1610, tag);
      },
      removeAllChildrenWithCleanup: function(cleanup) {
        this.removeAllChildren(cleanup);
      },
      removeAllChildren: function(cleanup) {
        var __children = this._children;
        if (null !== __children) {
          void 0 === cleanup && (cleanup = true);
          for (var i = 0; i < __children.length; i++) {
            var node = __children[i];
            if (node) {
              if (this._running) {
                node.performRecursive(_ccsg.Node.performType.onExitTransitionDidStart);
                node.performRecursive(_ccsg.Node.performType.onExit);
              }
              cleanup && node.performRecursive(_ccsg.Node.performType.cleanup);
              node.parent = null;
              node._renderCmd.detachFromParent();
            }
          }
          this._children.length = 0;
          cc.renderer.childrenOrderDirty = true;
        }
      },
      _detachChild: function(child, doCleanup) {
        if (this._running) {
          child.performRecursive(_ccsg.Node.performType.onExitTransitionDidStart);
          child.performRecursive(_ccsg.Node.performType.onExit);
        }
        doCleanup && child.performRecursive(_ccsg.Node.performType.cleanup);
        child.parent = null;
        child._renderCmd.detachFromParent();
        cc.js.array.remove(this._children, child);
      },
      _insertChild: function(child, z) {
        cc.renderer.childrenOrderDirty = this._reorderChildDirty = true;
        this._children.push(child);
        child._setLocalZOrder(z);
      },
      setNodeDirty: function() {
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
      },
      reorderChild: function(child, zOrder) {
        cc.assertID(child, 1617);
        if (-1 === this._children.indexOf(child)) {
          cc.logID(1635);
          return;
        }
        if (zOrder === child.zIndex) return;
        cc.renderer.childrenOrderDirty = this._reorderChildDirty = true;
        child.updateOrderOfArrival();
        child._setLocalZOrder(zOrder);
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.orderDirty);
      },
      sortAllChildren: function() {
        if (this._reorderChildDirty) {
          var _children = this._children;
          var len = _children.length, i, j, tmp;
          for (i = 1; i < len; i++) {
            tmp = _children[i];
            j = i - 1;
            while (j >= 0) {
              if (tmp._localZOrder < _children[j]._localZOrder) _children[j + 1] = _children[j]; else {
                if (!(tmp._localZOrder === _children[j]._localZOrder && tmp._arrivalOrder < _children[j]._arrivalOrder)) break;
                _children[j + 1] = _children[j];
              }
              j--;
            }
            _children[j + 1] = tmp;
          }
          this._reorderChildDirty = false;
        }
      },
      draw: function(ctx) {},
      transformAncestors: function() {
        if (null !== this._parent) {
          this._parent.transformAncestors();
          this._parent.transform();
        }
      },
      onEnter: function() {
        this._isTransitionFinished = false;
        this._running = true;
        this.resume();
      },
      performRecursive: function(callbackType) {
        var nodeCallbackType = _ccsg.Node.performType;
        if (callbackType >= nodeCallbackType.max) return;
        var index = 0;
        var children, child, curr, i, len;
        var stack = _ccsg.Node._performStacks[_ccsg.Node._performing];
        if (!stack) {
          stack = [];
          _ccsg.Node._performStacks.push(stack);
        }
        stack.length = 0;
        _ccsg.Node._performing++;
        curr = stack[0] = this;
        while (curr) {
          children = curr._children;
          if (children && children.length > 0) for (i = 0, len = children.length; i < len; ++i) {
            child = children[i];
            stack.push(child);
          }
          index++;
          curr = stack[index];
        }
        switch (callbackType) {
         case nodeCallbackType.onEnter:
          for (i = stack.length - 1; i >= 0; --i) {
            curr = stack[i];
            stack[i] = null;
            if (!curr) continue;
            curr.onEnter();
          }
          break;

         case nodeCallbackType.onExit:
          for (i = stack.length - 1; i >= 0; --i) {
            curr = stack[i];
            stack[i] = null;
            if (!curr) continue;
            curr.onExit();
          }
          break;

         case nodeCallbackType.onEnterTransitionDidFinish:
          for (i = stack.length - 1; i >= 0; --i) {
            curr = stack[i];
            stack[i] = null;
            if (!curr) continue;
            curr.onEnterTransitionDidFinish();
          }
          break;

         case nodeCallbackType.cleanup:
          for (i = stack.length - 1; i >= 0; --i) {
            curr = stack[i];
            stack[i] = null;
            if (!curr) continue;
            curr.cleanup();
          }
          break;

         case nodeCallbackType.onExitTransitionDidStart:
          for (i = stack.length - 1; i >= 0; --i) {
            curr = stack[i];
            stack[i] = null;
            if (!curr) continue;
            curr.onExitTransitionDidStart();
          }
        }
        _ccsg.Node._performing--;
      },
      onEnterTransitionDidFinish: function() {
        this._isTransitionFinished = true;
      },
      onExitTransitionDidStart: function() {},
      onExit: function() {
        this._running = false;
        this.pause();
      },
      runAction: ActionManagerExist ? function(action) {
        cc.assertID(action, 1618);
        cc.director.getActionManager().addAction(action, this, !this._running);
        return action;
      } : emptyFunc,
      stopAllActions: ActionManagerExist ? function() {
        cc.director.getActionManager().removeAllActionsFromTarget(this);
      } : emptyFunc,
      stopAction: ActionManagerExist ? function(action) {
        cc.director.getActionManager().removeAction(action);
      } : emptyFunc,
      stopActionByTag: ActionManagerExist ? function(tag) {
        if (tag === cc.Action.TAG_INVALID) {
          cc.logID(1612);
          return;
        }
        cc.director.getActionManager().removeActionByTag(tag, this);
      } : emptyFunc,
      getActionByTag: ActionManagerExist ? function(tag) {
        if (tag === cc.Action.TAG_INVALID) {
          cc.logID(1613);
          return null;
        }
        return cc.director.getActionManager().getActionByTag(tag, this);
      } : function() {
        return null;
      },
      getNumberOfRunningActions: ActionManagerExist ? function() {
        return cc.director.getActionManager().getNumberOfRunningActionsInTarget(this);
      } : function() {
        return 0;
      },
      scheduleUpdate: function() {
        this.scheduleUpdateWithPriority(0);
      },
      scheduleUpdateWithPriority: function(priority) {
        this.scheduler.scheduleUpdate(this, priority, !this._running);
      },
      unscheduleUpdate: function() {
        this.scheduler.unscheduleUpdate(this);
      },
      schedule: function(callback, interval, repeat, delay, key) {
        var len = arguments.length;
        if ("function" === typeof callback) if (1 === len) {
          interval = 0;
          repeat = cc.macro.REPEAT_FOREVER;
          delay = 0;
          key = this.__instanceId;
        } else if (2 === len) if ("number" === typeof interval) {
          repeat = cc.macro.REPEAT_FOREVER;
          delay = 0;
          key = this.__instanceId;
        } else {
          key = interval;
          interval = 0;
          repeat = cc.macro.REPEAT_FOREVER;
          delay = 0;
        } else if (3 === len) {
          if ("string" === typeof repeat) {
            key = repeat;
            repeat = cc.macro.REPEAT_FOREVER;
          } else key = this.__instanceId;
          delay = 0;
        } else 4 === len && (key = this.__instanceId); else if (1 === len) {
          interval = 0;
          repeat = cc.macro.REPEAT_FOREVER;
          delay = 0;
        } else if (2 === len) {
          repeat = cc.macro.REPEAT_FOREVER;
          delay = 0;
        }
        cc.assertID(callback, 1619);
        cc.assertID(interval >= 0, 1620);
        interval = interval || 0;
        repeat = isNaN(repeat) ? cc.macro.REPEAT_FOREVER : repeat;
        delay = delay || 0;
        this.scheduler.schedule(callback, this, interval, repeat, delay, !this._running, key);
      },
      scheduleOnce: function(callback, delay, key) {
        void 0 === key && (key = this.__instanceId);
        this.schedule(callback, 0, 0, delay, key);
      },
      unschedule: function(callback_fn) {
        if (!callback_fn) return;
        this.scheduler.unschedule(callback_fn, this);
      },
      unscheduleAllCallbacks: function() {
        this.scheduler.unscheduleAllForTarget(this);
      },
      resumeSchedulerAndActions: function() {
        cc.logID(1614);
        this.resume();
      },
      resume: function() {
        this.scheduler.resumeTarget(this);
        ActionManagerExist && cc.director.getActionManager().resumeTarget(this);
        eventManager.resumeTarget(this);
      },
      pauseSchedulerAndActions: function() {
        cc.logID(1615);
        this.pause();
      },
      pause: function() {
        this.scheduler.pauseTarget(this);
        ActionManagerExist && cc.director.getActionManager().pauseTarget(this);
        eventManager.pauseTarget(this);
      },
      getParentToNodeTransform: function() {
        return this._renderCmd.getParentToNodeTransform();
      },
      parentToNodeTransform: function() {
        return this.getParentToNodeTransform();
      },
      getNodeToWorldTransform: function() {
        var t = this.getNodeToParentTransform();
        for (var p = this._parent; null !== p; p = p.parent) t = cc.affineTransformConcat(t, p.getNodeToParentTransform());
        return t;
      },
      nodeToWorldTransform: function() {
        return this.getNodeToWorldTransform();
      },
      getWorldToNodeTransform: function() {
        return cc.affineTransformInvert(this.getNodeToWorldTransform());
      },
      worldToNodeTransform: function() {
        return this.getWorldToNodeTransform();
      },
      convertToNodeSpace: function(worldPoint) {
        return cc.pointApplyAffineTransform(worldPoint, this.getWorldToNodeTransform());
      },
      convertToWorldSpace: function(nodePoint) {
        nodePoint = nodePoint || cc.v2(0, 0);
        return cc.pointApplyAffineTransform(nodePoint, this.getNodeToWorldTransform());
      },
      convertToNodeSpaceAR: function(worldPoint) {
        return cc.pSub(this.convertToNodeSpace(worldPoint), this._renderCmd.getAnchorPointInPoints());
      },
      convertToWorldSpaceAR: function(nodePoint) {
        nodePoint = nodePoint || cc.v2(0, 0);
        var pt = cc.pAdd(nodePoint, this._renderCmd.getAnchorPointInPoints());
        return this.convertToWorldSpace(pt);
      },
      _convertToWindowSpace: function(nodePoint) {
        var worldPoint = this.convertToWorldSpace(nodePoint);
        return cc.director.convertToUI(worldPoint);
      },
      convertTouchToNodeSpace: function(touch) {
        var point = touch.getLocation();
        return this.convertToNodeSpace(point);
      },
      convertTouchToNodeSpaceAR: function(touch) {
        var point = cc.director.convertToGL(touch.getLocation());
        return this.convertToNodeSpaceAR(point);
      },
      updateTransform: function() {
        var children = this._children, node;
        for (var i = 0; i < children.length; i++) {
          var node = children[i];
          node && node.updateTransform();
        }
      },
      retain: function() {},
      release: function() {},
      visit: function(parent) {
        var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null;
        if (!this._visible) {
          cmd._propagateFlagsDown(parentCmd);
          return;
        }
        var renderer = cc.renderer;
        cmd.visit(parentCmd);
        var i, children = this._children, len = children.length, child;
        if (len > 0) {
          this._reorderChildDirty && this.sortAllChildren();
          for (i = 0; i < len; i++) {
            child = children[i];
            if (!(child._localZOrder < 0)) break;
            child.visit(this);
          }
          renderer.pushRenderCommand(cmd);
          for (;i < len; i++) children[i].visit(this);
        } else renderer.pushRenderCommand(cmd);
        cmd._dirtyFlag = 0;
      },
      transform: function(parentCmd, recursive) {
        this._renderCmd.transform(parentCmd, recursive);
      },
      nodeToParentTransform: function() {
        return this.getNodeToParentTransform();
      },
      getNodeToParentTransform: function(ancestor) {
        var t = this._renderCmd.getNodeToParentTransform();
        if (ancestor) {
          var T = {
            a: t.a,
            b: t.b,
            c: t.c,
            d: t.d,
            tx: t.tx,
            ty: t.ty
          };
          for (var p = this._parent; null != p && p != ancestor; p = p.getParent()) cc.affineTransformConcatIn(T, p.getNodeToParentTransform());
          return T;
        }
        return t;
      },
      getNodeToParentAffineTransform: function(ancestor) {
        return this.getNodeToParentTransform(ancestor);
      },
      getShaderProgram: function() {
        return this._renderCmd.getShaderProgram();
      },
      setShaderProgram: function(newShaderProgram) {
        this._renderCmd.setShaderProgram(newShaderProgram);
      },
      getGLServerState: function() {
        return 0;
      },
      setGLServerState: function(state) {},
      getBoundingBoxToWorld: function() {
        var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height);
        var trans = this.getNodeToWorldTransform();
        cc._rectApplyAffineTransformIn(rect, trans);
        if (!this._children) return rect;
        var locChildren = this._children;
        for (var i = 0; i < locChildren.length; i++) {
          var child = locChildren[i];
          if (child && child._visible) {
            var childRect = child._getBoundingBoxToCurrentNode(trans);
            childRect && (rect = cc.rectUnion(rect, childRect));
          }
        }
        return rect;
      },
      _getBoundingBoxToCurrentNode: function(parentTransform) {
        var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height);
        var trans = void 0 === parentTransform ? this.getNodeToParentTransform() : cc.affineTransformConcat(this.getNodeToParentTransform(), parentTransform);
        cc._rectApplyAffineTransformIn(rect, trans);
        if (!this._children) return rect;
        var locChildren = this._children;
        for (var i = 0; i < locChildren.length; i++) {
          var child = locChildren[i];
          if (child && child._visible) {
            var childRect = child._getBoundingBoxToCurrentNode(trans);
            childRect && (rect = cc.rectUnion(rect, childRect));
          }
        }
        return rect;
      },
      getOpacity: function() {
        return this._realOpacity;
      },
      getDisplayedOpacity: function() {
        return this._renderCmd.getDisplayedOpacity();
      },
      setOpacity: function(opacity) {
        this._realOpacity = opacity;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.opacityDirty);
      },
      updateDisplayedOpacity: function(parentOpacity) {
        this._renderCmd._updateDisplayOpacity(parentOpacity);
      },
      isCascadeOpacityEnabled: function() {
        return this._cascadeOpacityEnabled;
      },
      setCascadeOpacityEnabled: function(cascadeOpacityEnabled) {
        if (this._cascadeOpacityEnabled === cascadeOpacityEnabled) return;
        this._cascadeOpacityEnabled = cascadeOpacityEnabled;
        this._renderCmd.setCascadeOpacityEnabledDirty();
      },
      getColor: function() {
        var locRealColor = this._realColor;
        return cc.color(locRealColor.r, locRealColor.g, locRealColor.b, locRealColor.a);
      },
      getDisplayedColor: function() {
        return this._renderCmd.getDisplayedColor();
      },
      setColor: function(color) {
        var locRealColor = this._realColor;
        locRealColor.r = color.r;
        locRealColor.g = color.g;
        locRealColor.b = color.b;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.colorDirty);
      },
      updateDisplayedColor: function(parentColor) {
        this._renderCmd._updateDisplayColor(parentColor);
      },
      isCascadeColorEnabled: function() {
        return this._cascadeColorEnabled;
      },
      setCascadeColorEnabled: function(cascadeColorEnabled) {
        if (this._cascadeColorEnabled === cascadeColorEnabled) return;
        this._cascadeColorEnabled = cascadeColorEnabled;
        this._renderCmd.setCascadeColorEnabledDirty();
      },
      setOpacityModifyRGB: function(opacityValue) {},
      isOpacityModifyRGB: function() {
        return false;
      },
      _createRenderCmd: function() {
        return cc._renderType === cc.game.RENDER_TYPE_CANVAS ? new _ccsg.Node.CanvasRenderCmd(this) : new _ccsg.Node.WebGLRenderCmd(this);
      }
    });
    _ccsg.Node.extend = cc._Class.extend;
    _ccsg.Node.prototype.ctor = _ccsg.Node;
    _ccsg.Node.performType = {
      onEnter: 1,
      onExit: 2,
      cleanup: 3,
      onEnterTransitionDidFinish: 4,
      onExitTransitionDidStart: 5,
      max: 6
    };
    _ccsg.Node._performStacks = [ [] ];
    _ccsg.Node._performing = 0;
    var SameNameGetSets = [ "skewX", "skewY", "vertexZ", "rotation", "rotationX", "rotationY", "scale", "scaleX", "scaleY", "children", "childrenCount", "parent", "scheduler", "shaderProgram", "opacity", "color" ];
    var DiffNameGetSets = {
      x: [ "getPositionX", "setPositionX" ],
      y: [ "getPositionY", "setPositionY" ],
      width: [ "_getWidth", "_setWidth" ],
      height: [ "_getHeight", "_setHeight" ],
      anchorX: [ "_getAnchorX", "_setAnchorX" ],
      anchorY: [ "_getAnchorY", "_setAnchorY" ],
      zIndex: [ "getLocalZOrder", "setLocalZOrder" ],
      visible: [ "isVisible", "setVisible" ],
      running: [ "isRunning" ],
      ignoreAnchor: [ "isIgnoreAnchorPointForPosition", "setIgnoreAnchorPointForPosition" ],
      opacityModifyRGB: [ "isOpacityModifyRGB", "setOpacityModifyRGB" ],
      cascadeOpacity: [ "isCascadeOpacityEnabled", "setCascadeOpacityEnabled" ],
      cascadeColor: [ "isCascadeColorEnabled", "setCascadeColorEnabled" ]
    };
    Misc.propertyDefine(_ccsg.Node, SameNameGetSets, DiffNameGetSets);
  }), {
    "../event-manager": 110,
    "../utils/misc": 225
  } ],
  56: [ (function(require, module, exports) {
    cc.CustomRenderCmd = function(target, func) {
      this._needDraw = true;
      this._target = target;
      this._callback = func;
    };
    cc.CustomRenderCmd.prototype.rendering = function(ctx, scaleX, scaleY) {
      if (!this._callback) return;
      this._callback.call(this._target, ctx, scaleX, scaleY);
    };
    var dirtyFlags = _ccsg.Node._dirtyFlags = {
      transformDirty: 1,
      visibleDirty: 2,
      colorDirty: 4,
      opacityDirty: 8,
      cacheDirty: 16,
      orderDirty: 32,
      textDirty: 64,
      gradientDirty: 128,
      textureDirty: 256,
      contentDirty: 512,
      cullingDirty: 1024,
      COUNT: 9
    };
    cc.js.get(dirtyFlags, "all", (function() {
      var count = dirtyFlags.COUNT;
      return (1 << count) - 1;
    }), false);
    _ccsg.Node._requestDirtyFlag = function(key) {
      cc.assertID(!dirtyFlags[key], 1622, key);
      var count = dirtyFlags.COUNT;
      var value = 1 << count;
      dirtyFlags[key] = value;
      dirtyFlags.COUNT++;
      return value;
    };
    var ONE_DEGREE = Math.PI / 180;
    function walkChildTree(root, funcName) {
      var index = 1;
      var children, child, curr, parentCmd, i, len;
      var stack = _ccsg.Node._performStacks[_ccsg.Node._performing];
      if (!stack) {
        stack = [];
        _ccsg.Node._performStacks.push(stack);
      }
      stack.length = 0;
      _ccsg.Node._performing++;
      stack[0] = root;
      var childChildren;
      while (index) {
        index--;
        curr = stack[index];
        stack[index] = null;
        if (!curr) continue;
        children = curr._children;
        if (children && children.length > 0) {
          parentCmd = curr._renderCmd;
          for (i = 0, len = children.length; i < len; ++i) {
            child = children[i];
            stack[index] = child;
            index++;
            child._renderCmd[funcName](parentCmd);
          }
        }
      }
      _ccsg.Node._performing--;
    }
    _ccsg.Node.RenderCmd = function(renderable) {
      this._node = renderable;
      this._anchorPointInPoints = new cc.Vec2(0, 0);
      this._needDraw = false;
      this._dirtyFlag = 1;
      this._curLevel = -1;
      this._cameraFlag = 0;
      this._displayedColor = new cc.Color(255, 255, 255, 255);
      this._displayedOpacity = 255;
      this._cascadeColorEnabledDirty = false;
      this._cascadeOpacityEnabledDirty = false;
      this._transform = {
        a: 1,
        b: 0,
        c: 0,
        d: 1,
        tx: 0,
        ty: 0
      };
      this._worldTransform = {
        a: 1,
        b: 0,
        c: 0,
        d: 1,
        tx: 0,
        ty: 0
      };
      this._inverse = {
        a: 1,
        b: 0,
        c: 0,
        d: 1,
        tx: 0,
        ty: 0
      };
      this._transformUpdated = false;
      cc.renderer.pushDirtyNode(this);
    };
    _ccsg.Node.RenderCmd.prototype = {
      constructor: _ccsg.Node.RenderCmd,
      _ctor: _ccsg.Node.RenderCmd,
      getAnchorPointInPoints: function() {
        return cc.p(this._anchorPointInPoints);
      },
      getDisplayedColor: function() {
        var tmpColor = this._displayedColor;
        return cc.color(tmpColor.r, tmpColor.g, tmpColor.b, tmpColor.a);
      },
      getDisplayedOpacity: function() {
        return this._displayedOpacity;
      },
      setCascadeColorEnabledDirty: function() {
        this._cascadeColorEnabledDirty = true;
        this.setDirtyFlag(dirtyFlags.colorDirty);
      },
      setCascadeOpacityEnabledDirty: function() {
        this._cascadeOpacityEnabledDirty = true;
        this.setDirtyFlag(dirtyFlags.opacityDirty);
      },
      getParentToNodeTransform: function() {
        this._dirtyFlag & dirtyFlags.transformDirty && cc.affineTransformInvertOut(this.getNodeToParentTransform(), this._inverse);
        return this._inverse;
      },
      detachFromParent: function() {},
      _updateAnchorPointInPoint: function() {
        var locAPP = this._anchorPointInPoints, locSize = this._node._contentSize, locAnchorPoint = this._node._anchorPoint;
        locAPP.x = locSize.width * locAnchorPoint.x;
        locAPP.y = locSize.height * locAnchorPoint.y;
        this.setDirtyFlag(dirtyFlags.transformDirty);
      },
      setDirtyFlag: function(dirtyFlag) {
        0 === this._dirtyFlag && 0 !== dirtyFlag && cc.renderer.pushDirtyNode(this);
        this._dirtyFlag |= dirtyFlag;
      },
      getParentRenderCmd: function() {
        if (this._node && this._node._parent && this._node._parent._renderCmd) return this._node._parent._renderCmd;
        return null;
      },
      updateTransform: function(parentCmd, recursive) {
        var node = this._node, pt = parentCmd ? parentCmd._worldTransform : null, t = this._transform, wt = this._worldTransform;
        if (!this._transformUpdated) {
          var hasRotation = node._rotationX || node._rotationY;
          var hasSkew = node._skewX || node._skewY;
          var sx = node._scaleX, sy = node._scaleY;
          var appX = this._anchorPointInPoints.x, appY = this._anchorPointInPoints.y;
          var a = 1, b = 0, c = 0, d = 1;
          if (hasRotation || hasSkew) {
            t.tx = node._position.x;
            t.ty = node._position.y;
            if (hasRotation) {
              var rotationRadiansX = node._rotationX * ONE_DEGREE;
              c = Math.sin(rotationRadiansX);
              d = Math.cos(rotationRadiansX);
              if (node._rotationY === node._rotationX) {
                a = d;
                b = -c;
              } else {
                var rotationRadiansY = node._rotationY * ONE_DEGREE;
                a = Math.cos(rotationRadiansY);
                b = -Math.sin(rotationRadiansY);
              }
            }
            t.a = a *= sx;
            t.b = b *= sx;
            t.c = c *= sy;
            t.d = d *= sy;
            if (hasSkew) {
              var skx = Math.tan(node._skewX * ONE_DEGREE);
              var sky = Math.tan(node._skewY * ONE_DEGREE);
              Infinity === skx && (skx = 99999999);
              Infinity === sky && (sky = 99999999);
              t.a = a + c * sky;
              t.b = b + d * sky;
              t.c = c + a * skx;
              t.d = d + b * skx;
            }
            if (appX || appY) {
              t.tx -= t.a * appX + t.c * appY;
              t.ty -= t.b * appX + t.d * appY;
              if (node._ignoreAnchorPointForPosition) {
                t.tx += appX;
                t.ty += appY;
              }
            }
          } else {
            t.a = sx;
            t.b = 0;
            t.c = 0;
            t.d = sy;
            t.tx = node._position.x;
            t.ty = node._position.y;
            if (appX || appY) {
              t.tx -= t.a * appX;
              t.ty -= t.d * appY;
              if (node._ignoreAnchorPointForPosition) {
                t.tx += appX;
                t.ty += appY;
              }
            }
          }
        }
        if (pt) {
          wt.a = t.a * pt.a + t.b * pt.c;
          wt.b = t.a * pt.b + t.b * pt.d;
          wt.c = t.c * pt.a + t.d * pt.c;
          wt.d = t.c * pt.b + t.d * pt.d;
          wt.tx = t.tx * pt.a + t.ty * pt.c + pt.tx;
          wt.ty = t.tx * pt.b + t.ty * pt.d + pt.ty;
        } else {
          wt.a = t.a;
          wt.b = t.b;
          wt.c = t.c;
          wt.d = t.d;
          wt.tx = t.tx;
          wt.ty = t.ty;
        }
      },
      transform: function(parentCmd, recursive) {
        this.updateTransform(parentCmd);
        if (this._currentRegion) {
          this._updateCurrentRegions();
          this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.DirtyDouble);
        }
        if (cc.macro.ENABLE_CULLING) {
          this._updateCameraFlag(parentCmd);
          this._doCulling && this._doCulling();
        } else this._doCulling && (this._needDraw = true);
        recursive && walkChildTree(this._node, "transform");
      },
      _updateCameraFlag: function(parentCmd) {
        var Camera = cc.Camera;
        cc._renderType === cc.game.RENDER_TYPE_WEBGL && Camera && parentCmd && this._cameraFlag != Camera.flags.InCamera && (this._cameraFlag = parentCmd._cameraFlag > 0 ? Camera.flags.ParentInCamera : 0);
      },
      culling: function(parentCmd, recursive) {
        if (!cc.macro.ENABLE_CULLING) {
          this._doCulling && (this._needDraw = true);
          return;
        }
        this._updateCameraFlag(parentCmd);
        this._doCulling && this._doCulling();
        recursive && walkChildTree(this._node, "culling");
      },
      getNodeToParentTransform: function() {
        this._dirtyFlag & dirtyFlags.transformDirty && this.transform();
        return this._transform;
      },
      setNodeToParentTransform: function(transform) {
        if (transform) {
          this._transform = transform;
          this._transformUpdated = true;
        } else this._transformUpdated = false;
        this.setDirtyFlag(dirtyFlags.transformDirty);
      },
      _propagateFlagsDown: function(parentCmd) {
        if (!parentCmd) return;
        var locFlag = this._dirtyFlag;
        var parentNode = parentCmd._node;
        var parentFlag = parentCmd._dirtyFlag;
        parentNode._cascadeColorEnabled && parentFlag & dirtyFlags.colorDirty && (locFlag |= dirtyFlags.colorDirty);
        parentNode._cascadeOpacityEnabled && parentFlag & dirtyFlags.opacityDirty && (locFlag |= dirtyFlags.opacityDirty);
        parentFlag & dirtyFlags.transformDirty && (locFlag |= dirtyFlags.transformDirty);
        parentFlag & dirtyFlags.cullingDirty && (locFlag |= dirtyFlags.cullingDirty);
        this._dirtyFlag = locFlag;
      },
      visit: function(parentCmd) {
        var node = this._node, renderer = cc.renderer;
        parentCmd && (this._curLevel = parentCmd._curLevel + 1);
        this._propagateFlagsDown(parentCmd);
        if (isNaN(node._customZ)) {
          node._vertexZ = renderer.assignedZ;
          renderer.assignedZ += renderer.assignedZStep;
        }
        this._syncStatus(parentCmd);
      },
      _updateDisplayColor: function(parentColor) {
        var node = this._node;
        var locDispColor = this._displayedColor, locRealColor = node._realColor;
        var i, len, selChildren, item;
        this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty);
        if (this._cascadeColorEnabledDirty && !node._cascadeColorEnabled) {
          locDispColor.r = locRealColor.r;
          locDispColor.g = locRealColor.g;
          locDispColor.b = locRealColor.b;
          var whiteColor = new cc.Color(255, 255, 255, 255);
          selChildren = node._children;
          for (i = 0, len = selChildren.length; i < len; i++) {
            item = selChildren[i];
            item && item._renderCmd && item._renderCmd._updateDisplayColor(whiteColor);
          }
          this._cascadeColorEnabledDirty = false;
        } else {
          if (void 0 === parentColor) {
            var locParent = node._parent;
            parentColor = locParent && locParent._cascadeColorEnabled ? locParent.getDisplayedColor() : cc.Color.WHITE;
          }
          locDispColor.r = 0 | locRealColor.r * parentColor.r / 255;
          locDispColor.g = 0 | locRealColor.g * parentColor.g / 255;
          locDispColor.b = 0 | locRealColor.b * parentColor.b / 255;
          if (node._cascadeColorEnabled) {
            selChildren = node._children;
            for (i = 0, len = selChildren.length; i < len; i++) {
              item = selChildren[i];
              if (item && item._renderCmd) {
                item._renderCmd._updateDisplayColor(locDispColor);
                item._renderCmd._updateColor();
              }
            }
          }
        }
        this._dirtyFlag &= ~dirtyFlags.colorDirty;
      },
      _updateDisplayOpacity: function(parentOpacity) {
        var node = this._node;
        var i, len, selChildren, item;
        this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty);
        if (this._cascadeOpacityEnabledDirty && !node._cascadeOpacityEnabled) {
          this._displayedOpacity = node._realOpacity;
          selChildren = node._children;
          for (i = 0, len = selChildren.length; i < len; i++) {
            item = selChildren[i];
            item && item._renderCmd && item._renderCmd._updateDisplayOpacity(255);
          }
          this._cascadeOpacityEnabledDirty = false;
        } else {
          if (void 0 === parentOpacity) {
            var locParent = node._parent;
            parentOpacity = 255;
            locParent && locParent._cascadeOpacityEnabled && (parentOpacity = locParent.getDisplayedOpacity());
          }
          this._displayedOpacity = node._realOpacity * parentOpacity / 255;
          if (node._cascadeOpacityEnabled) {
            selChildren = node._children;
            for (i = 0, len = selChildren.length; i < len; i++) {
              item = selChildren[i];
              if (item && item._renderCmd) {
                item._renderCmd._updateDisplayOpacity(this._displayedOpacity);
                item._renderCmd._updateColor();
              }
            }
          }
        }
        this._dirtyFlag &= ~dirtyFlags.opacityDirty;
      },
      _syncDisplayColor: function(parentColor) {
        var node = this._node, locDispColor = this._displayedColor, locRealColor = node._realColor;
        if (void 0 === parentColor) {
          var locParent = node._parent;
          parentColor = locParent && locParent._cascadeColorEnabled ? locParent.getDisplayedColor() : cc.Color.WHITE;
        }
        locDispColor.r = 0 | locRealColor.r * parentColor.r / 255;
        locDispColor.g = 0 | locRealColor.g * parentColor.g / 255;
        locDispColor.b = 0 | locRealColor.b * parentColor.b / 255;
      },
      _syncDisplayOpacity: function(parentOpacity) {
        var node = this._node;
        if (void 0 === parentOpacity) {
          var locParent = node._parent;
          parentOpacity = 255;
          locParent && locParent._cascadeOpacityEnabled && (parentOpacity = locParent.getDisplayedOpacity());
        }
        this._displayedOpacity = node._realOpacity * parentOpacity / 255;
      },
      _updateColor: function() {},
      updateStatus: function() {
        var locFlag = this._dirtyFlag;
        var colorDirty = locFlag & dirtyFlags.colorDirty, opacityDirty = locFlag & dirtyFlags.opacityDirty;
        if (locFlag & dirtyFlags.contentDirty) {
          this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty);
          this._dirtyFlag &= ~dirtyFlags.contentDirty;
        }
        colorDirty && this._updateDisplayColor();
        opacityDirty && this._updateDisplayOpacity();
        (colorDirty || opacityDirty) && this._updateColor();
        if (locFlag & dirtyFlags.transformDirty) {
          var parentCmd = this.getParentRenderCmd();
          this.transform(parentCmd, true);
          this._dirtyFlag &= ~dirtyFlags.transformDirty;
          this._dirtyFlag &= ~dirtyFlags.cullingDirty;
        } else if (locFlag & dirtyFlags.cullingDirty) {
          this.culling(parentCmd, true);
          this._dirtyFlag &= ~dirtyFlags.cullingDirty;
        }
      },
      _syncStatus: function(parentCmd) {
        var locFlag = this._dirtyFlag;
        var colorDirty = locFlag & dirtyFlags.colorDirty, opacityDirty = locFlag & dirtyFlags.opacityDirty;
        colorDirty && this._syncDisplayColor();
        opacityDirty && this._syncDisplayOpacity();
        (colorDirty || opacityDirty) && this._updateColor();
        locFlag & dirtyFlags.transformDirty ? this.transform(parentCmd) : locFlag & dirtyFlags.cullingDirty && this.culling(parentCmd);
      }
    };
    _ccsg.Node.RenderCmd.prototype.originUpdateTransform = _ccsg.Node.RenderCmd.prototype.updateTransform;
    _ccsg.Node.RenderCmd.prototype.originTransform = _ccsg.Node.RenderCmd.prototype.transform;
    _ccsg.Node.RenderCmd.prototype.originCulling = _ccsg.Node.RenderCmd.prototype.culling;
    _ccsg.Node.RenderCmd.prototype.originUpdateStatus = _ccsg.Node.RenderCmd.prototype.updateStatus;
    _ccsg.Node.RenderCmd.prototype._originSyncStatus = _ccsg.Node.RenderCmd.prototype._syncStatus;
  }), {} ],
  57: [ (function(require, module, exports) {
    _ccsg.Node.CanvasRenderCmd = function(renderable) {
      this._ctor(renderable);
      this._currentRegion = new cc.Region();
      this._oldRegion = new cc.Region();
      this._regionFlag = 0;
    };
    _ccsg.Node.CanvasRenderCmd.RegionStatus = {
      NotDirty: 0,
      Dirty: 1,
      DirtyDouble: 2
    };
    var proto = _ccsg.Node.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.RenderCmd.prototype);
    proto.constructor = _ccsg.Node.CanvasRenderCmd;
    proto._rootCtor = _ccsg.Node.CanvasRenderCmd;
    proto._notifyRegionStatus = function(status) {
      this._needDraw && this._regionFlag < status && (this._regionFlag = status);
    };
    var localBB = new cc.Rect();
    proto.getLocalBB = function() {
      var node = this._node;
      localBB.x = localBB.y = 0;
      localBB.width = node._contentSize.width;
      localBB.height = node._contentSize.height;
      return localBB;
    };
    proto._updateCurrentRegions = function() {
      var temp = this._currentRegion;
      this._currentRegion = this._oldRegion;
      this._oldRegion = temp;
      _ccsg.Node.CanvasRenderCmd.RegionStatus.DirtyDouble !== this._regionFlag || this._currentRegion.isEmpty() || this._oldRegion.union(this._currentRegion);
      this._currentRegion.updateRegion(this.getLocalBB(), this._worldTransform);
    };
    proto.detachFromParent = function() {
      var selChildren = this._node._children, item;
      for (var i = 0, len = selChildren.length; i < len; i++) {
        item = selChildren[i];
        item && item._renderCmd && item._renderCmd.detachFromParent();
      }
    };
    proto.setShaderProgram = function(shaderProgram) {};
    proto.getShaderProgram = function() {
      return null;
    };
    _ccsg.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc = function(blendFunc) {
      return blendFunc ? blendFunc.src === cc.macro.SRC_ALPHA && blendFunc.dst === cc.macro.ONE || blendFunc.src === cc.macro.ONE && blendFunc.dst === cc.macro.ONE ? "lighter" : blendFunc.src === cc.macro.ZERO && blendFunc.dst === cc.macro.SRC_ALPHA ? "destination-in" : blendFunc.src === cc.macro.ZERO && blendFunc.dst === cc.macro.ONE_MINUS_SRC_ALPHA ? "destination-out" : "source-over" : "source-over";
    };
  }), {} ],
  58: [ (function(require, module, exports) {
    _ccsg.Node.WebGLRenderCmd = function(renderable) {
      this._ctor(renderable);
      this._shaderProgram = null;
    };
    var proto = _ccsg.Node.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.RenderCmd.prototype);
    proto.constructor = _ccsg.Node.WebGLRenderCmd;
    proto._rootCtor = _ccsg.Node.WebGLRenderCmd;
    proto._updateColor = function() {};
    proto.setShaderProgram = function(shaderProgram) {
      this._shaderProgram = shaderProgram;
    };
    proto.getShaderProgram = function() {
      return this._shaderProgram;
    };
  }), {} ],
  59: [ (function(require, module, exports) {
    var TOP = 1;
    var MID = 2;
    var BOT = 4;
    var LEFT = 8;
    var CENTER = 16;
    var RIGHT = 32;
    var HORIZONTAL = LEFT | CENTER | RIGHT;
    var VERTICAL = TOP | MID | BOT;
    function getReadonlyNodeSize(parent) {
      return parent instanceof cc.Scene ? cc.visibleRect : !parent._sizeProvider || parent._sizeProvider instanceof _ccsg.Node ? parent._contentSize : parent.getContentSize();
    }
    function computeInverseTransForTarget(widgetNode, target, out_inverseTranslate, out_inverseScale) {
      var scaleX = widgetNode._parent._scaleX;
      var scaleY = widgetNode._parent._scaleY;
      var translateX = 0;
      var translateY = 0;
      for (var node = widgetNode._parent; ;) {
        var pos = node._position;
        translateX += pos.x;
        translateY += pos.y;
        node = node._parent;
        if (!node) {
          out_inverseTranslate.x = out_inverseTranslate.y = 0;
          out_inverseScale.x = out_inverseScale.y = 1;
          return;
        }
        if (node === target) break;
        var sx = node._scaleX;
        var sy = node._scaleY;
        translateX *= sx;
        translateY *= sy;
        scaleX *= sx;
        scaleY *= sy;
      }
      out_inverseScale.x = 0 !== scaleX ? 1 / scaleX : 1;
      out_inverseScale.y = 0 !== scaleY ? 1 / scaleY : 1;
      out_inverseTranslate.x = -translateX;
      out_inverseTranslate.y = -translateY;
    }
    var tInverseTranslate = cc.Vec2.ZERO;
    var tInverseScale = cc.Vec2.ONE;
    function align(node, widget) {
      var hasTarget = widget._target;
      var target;
      var inverseTranslate, inverseScale;
      if (hasTarget) {
        target = hasTarget;
        inverseTranslate = tInverseTranslate;
        inverseScale = tInverseScale;
        computeInverseTransForTarget(node, target, inverseTranslate, inverseScale);
      } else target = node._parent;
      var targetSize = getReadonlyNodeSize(target);
      var targetAnchor = target._anchorPoint;
      var isRoot = (true, target instanceof cc.Scene);
      var x = node._position.x, y = node._position.y;
      var anchor = node._anchorPoint;
      if (widget._alignFlags & HORIZONTAL) {
        var localLeft, localRight, targetWidth = targetSize.width;
        if (isRoot) {
          localLeft = cc.visibleRect.left.x;
          localRight = cc.visibleRect.right.x;
        } else {
          localLeft = -targetAnchor.x * targetWidth;
          localRight = localLeft + targetWidth;
        }
        localLeft += widget._isAbsLeft ? widget._left : widget._left * targetWidth;
        localRight -= widget._isAbsRight ? widget._right : widget._right * targetWidth;
        if (hasTarget) {
          localLeft += inverseTranslate.x;
          localLeft *= inverseScale.x;
          localRight += inverseTranslate.x;
          localRight *= inverseScale.x;
        }
        var width, anchorX = anchor.x, scaleX = node._scaleX;
        if (scaleX < 0) {
          anchorX = 1 - anchorX;
          scaleX = -scaleX;
        }
        if (widget.isStretchWidth) {
          width = localRight - localLeft;
          0 !== scaleX && (node.width = width / scaleX);
          x = localLeft + anchorX * width;
        } else {
          width = node.width * scaleX;
          if (widget.isAlignHorizontalCenter) {
            var localHorizontalCenter = widget._isAbsHorizontalCenter ? widget._horizontalCenter : widget._horizontalCenter * targetWidth;
            var targetCenter = (.5 - targetAnchor.x) * targetSize.width;
            if (hasTarget) {
              localHorizontalCenter *= inverseScale.x;
              targetCenter += inverseTranslate.x;
              targetCenter *= inverseScale.x;
            }
            x = targetCenter + (anchorX - .5) * width + localHorizontalCenter;
          } else x = widget.isAlignLeft ? localLeft + anchorX * width : localRight + (anchorX - 1) * width;
        }
      }
      if (widget._alignFlags & VERTICAL) {
        var localTop, localBottom, targetHeight = targetSize.height;
        if (isRoot) {
          localBottom = cc.visibleRect.bottom.y;
          localTop = cc.visibleRect.top.y;
        } else {
          localBottom = -targetAnchor.y * targetHeight;
          localTop = localBottom + targetHeight;
        }
        localBottom += widget._isAbsBottom ? widget._bottom : widget._bottom * targetHeight;
        localTop -= widget._isAbsTop ? widget._top : widget._top * targetHeight;
        if (hasTarget) {
          localBottom += inverseTranslate.y;
          localBottom *= inverseScale.y;
          localTop += inverseTranslate.y;
          localTop *= inverseScale.y;
        }
        var height, anchorY = anchor.y, scaleY = node._scaleY;
        if (scaleY < 0) {
          anchorY = 1 - anchorY;
          scaleY = -scaleY;
        }
        if (widget.isStretchHeight) {
          height = localTop - localBottom;
          0 !== scaleY && (node.height = height / scaleY);
          y = localBottom + anchorY * height;
        } else {
          height = node.height * scaleY;
          if (widget.isAlignVerticalCenter) {
            var localVerticalCenter = widget._isAbsVerticalCenter ? widget._verticalCenter : widget._verticalCenter * targetHeight;
            var targetMiddle = (.5 - targetAnchor.y) * targetSize.height;
            if (hasTarget) {
              localVerticalCenter *= inverseScale.y;
              targetMiddle += inverseTranslate.y;
              targetMiddle *= inverseScale.y;
            }
            y = targetMiddle + (anchorY - .5) * height + localVerticalCenter;
          } else y = widget.isAlignBottom ? localBottom + anchorY * height : localTop + (anchorY - 1) * height;
        }
      }
      node.setPosition(x, y);
    }
    function visitNode(node) {
      var widget = node._widget;
      if (widget) {
        var target;
        var isParent;
        false;
        align(node, widget);
        true, widget.isAlignOnce ? widget.enabled = false : activeWidgets.push(widget);
      }
      var children = node._children;
      for (var i = 0; i < children.length; i++) {
        var child = children[i];
        child._active && visitNode(child);
      }
    }
    var animationState;
    false;
    function refreshScene() {
      var nowPreviewing;
      false;
      var scene = cc.director.getScene();
      if (scene) {
        widgetManager.isAligning = true;
        if (widgetManager._nodesOrderDirty) {
          activeWidgets.length = 0;
          visitNode(scene);
          widgetManager._nodesOrderDirty = false;
        } else {
          var i, widget, iterator = widgetManager._activeWidgetsIterator;
          var editingNode;
          var node;
          false;
          for (iterator.i = 0; iterator.i < activeWidgets.length; ++iterator.i) {
            widget = activeWidgets[iterator.i];
            align(widget.node, widget);
          }
        }
        widgetManager.isAligning = false;
      }
      false;
    }
    var adjustWidgetToAllowMovingInEditor = false;
    var adjustWidgetToAllowResizingInEditor = false;
    var activeWidgets = [];
    function updateAlignment(node) {
      var parent = node._parent;
      cc.Node.isNode(parent) && updateAlignment(parent);
      var widget = node._widget || node.getComponent(cc.Widget);
      widget && align(node, widget);
    }
    var widgetManager = cc._widgetManager = module.exports = {
      _AlignFlags: {
        TOP: TOP,
        MID: MID,
        BOT: BOT,
        LEFT: LEFT,
        CENTER: CENTER,
        RIGHT: RIGHT
      },
      isAligning: false,
      _nodesOrderDirty: false,
      _activeWidgetsIterator: new cc.js.array.MutableForwardIterator(activeWidgets),
      init: function(director) {
        director.on(cc.Director.EVENT_BEFORE_VISIT, refreshScene);
      },
      add: function(widget) {
        widget.node._widget = widget;
        this._nodesOrderDirty = true;
        false;
      },
      remove: function(widget) {
        widget.node._widget = null;
        this._activeWidgetsIterator.remove(widget);
        false;
      },
      updateAlignment: updateAlignment
    };
    false;
  }), {} ],
  60: [ (function(require, module, exports) {
    var cullingDirtyFlag;
    true;
    cullingDirtyFlag = _ccsg.Node._dirtyFlags.cullingDirty;
    require("./CCSGCameraNode");
    var Camera = cc.Class({
      name: "cc.Camera",
      extends: cc._RendererUnderSG,
      ctor: function() {
        this.viewMatrix = cc.affineTransformMake();
        this.invertViewMatrix = cc.affineTransformMake();
        this._lastViewMatrix = cc.affineTransformMake();
        this._sgTarges = [];
        this._checkedTimes = 0;
        this.visibleRect = {
          left: cc.v2(),
          right: cc.v2(),
          top: cc.v2(),
          bottom: cc.v2()
        };
        this.viewPort = cc.rect();
      },
      editor: false,
      properties: {
        _targets: {
          default: [],
          type: cc.Node,
          visible: true
        },
        zoomRatio: 1
      },
      statics: {
        main: null
      },
      _createSgNode: function() {
        if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
          cc.errorID(8301);
          var sgNode = new _ccsg.Node();
          sgNode.setTransform = sgNode.addTarget = sgNode.removeTarget = function() {};
          return sgNode;
        }
        return new _ccsg.CameraNode();
      },
      _initSgNode: function() {
        this._sgNode.setContentSize(this.node.getContentSize(true));
      },
      _addSgTargetInSg: function(target) {
        var sgNode;
        target instanceof cc.Node ? sgNode = target._sgNode : target instanceof _ccsg.Node && (sgNode = target);
        if (!sgNode || sgNode._cameraInfo) return;
        sgNode._cameraInfo = {
          touched: this._checkedTimes
        };
        this._sgNode.addTarget(sgNode);
        this._sgTarges.push(sgNode);
        true;
        var cmd = sgNode._renderCmd;
        cmd.setDirtyFlag(cullingDirtyFlag);
        cmd._cameraFlag = Camera.flags.InCamera;
        cc.renderer.childrenOrderDirty = true;
      },
      _removeTargetInSg: function(target) {
        var sgNode;
        target instanceof cc.Node ? sgNode = target._sgNode : target instanceof _ccsg.Node && (sgNode = target);
        if (!sgNode || !sgNode._cameraInfo) return;
        this._sgNode.removeTarget(sgNode);
        delete sgNode._cameraInfo;
        cc.js.array.remove(this._sgTarges, sgNode);
        true;
        var cmd = sgNode._renderCmd;
        cmd.setDirtyFlag(cullingDirtyFlag);
        cmd._cameraFlag = 0;
        cc.renderer.childrenOrderDirty = true;
      },
      onEnable: function() {
        if (Camera.main) {
          cc.errorID(8300);
          return;
        }
        Camera.main = this;
        false;
        var targets = this._targets;
        for (var i = 0, l = targets.length; i < l; i++) this._addSgTargetInSg(targets[i]);
      },
      onDisable: function() {
        if (Camera.main !== this) return;
        Camera.main = null;
        false;
        var sgTargets = this._sgTarges;
        for (var i = sgTargets.length - 1; i >= 0; i--) this._removeTargetInSg(sgTargets[i]);
      },
      addTarget: function(target) {
        if (-1 !== this._targets.indexOf(target)) return;
        this._addSgTargetInSg(target);
        this._targets.push(target);
      },
      removeTarget: function(target) {
        if (-1 === this._targets.indexOf(target)) return;
        this._removeTargetInSg(target);
        cc.js.array.remove(this._targets, target);
      },
      getTargets: function() {
        return this._targets;
      },
      getNodeToCameraTransform: function(node) {
        var t = node.getNodeToWorldTransform();
        this.containsNode(node) && (t = cc.affineTransformConcatIn(t, cc.Camera.main.viewMatrix));
        return t;
      },
      getCameraToWorldPoint: function(point) {
        cc.Camera.main && (point = cc.pointApplyAffineTransform(point, cc.Camera.main.invertViewMatrix));
        return point;
      },
      containsNode: function(node) {
        node instanceof cc.Node && (node = node._sgNode);
        var targets = this._sgTarges;
        while (node) {
          if (-1 !== targets.indexOf(node)) return true;
          node = node.parent;
        }
        return false;
      },
      _setSgNodesCullingDirty: function() {
        var sgTarges = this._sgTarges;
        for (var i = 0; i < sgTarges.length; i++) {
          false;
          sgTarges[i]._renderCmd.setDirtyFlag(cullingDirtyFlag);
        }
      },
      _checkSgTargets: function() {
        var targets = this._targets;
        var sgTarges = this._sgTarges;
        var checkedTimes = ++this._checkedTimes;
        for (var i = 0, l = targets.length; i < l; i++) {
          var target = targets[i];
          var sgNode = target;
          if (target instanceof cc.Node) {
            sgNode = target._sgNode;
            sgNode && !sgNode._cameraInfo && this._addSgTargetInSg(sgNode);
          }
          sgNode && (sgNode._cameraInfo.touched = checkedTimes);
        }
        for (var _i = sgTarges.length - 1; _i >= 0; _i--) {
          var sgTarget = sgTarges[_i];
          sgTarget._cameraInfo.touched !== checkedTimes && this._removeTargetInSg(sgTarget);
        }
      },
      lateUpdate: (true, function() {
        this._checkSgTargets();
        var m = this.viewMatrix;
        var im = this.invertViewMatrix;
        var viewPort = this.viewPort;
        var visibleRect = cc.visibleRect;
        var selfVisibleRect = this.visibleRect;
        var node = this.node;
        var wt = node.getNodeToWorldTransformAR();
        var rotation = .5 * -(Math.atan2(wt.b, wt.a) + Math.atan2(-wt.c, wt.d));
        var a = 1, b = 0, c = 0, d = 1, tx = 0, ty = 0;
        if (rotation) {
          c = Math.sin(rotation);
          d = Math.cos(rotation);
          a = d;
          b = -c;
        }
        var zoomRatio = this.zoomRatio;
        a *= zoomRatio;
        b *= zoomRatio;
        c *= zoomRatio;
        d *= zoomRatio;
        m.a = a;
        m.b = b;
        m.c = c;
        m.d = d;
        var center = visibleRect.center;
        m.tx = center.x - (a * wt.tx + c * wt.ty);
        m.ty = center.y - (b * wt.tx + d * wt.ty);
        cc.affineTransformInvertOut(m, im);
        viewPort.x = visibleRect.bottomLeft.x;
        viewPort.y = visibleRect.bottomLeft.y;
        viewPort.width = visibleRect.width;
        viewPort.height = visibleRect.height;
        cc._rectApplyAffineTransformIn(viewPort, im);
        selfVisibleRect.left.x = viewPort.xMin;
        selfVisibleRect.right.x = viewPort.xMax;
        selfVisibleRect.bottom.y = viewPort.yMin;
        selfVisibleRect.top.y = viewPort.yMax;
        this._sgNode.setTransform(a, b, c, d, m.tx, m.ty);
        var lvm = this._lastViewMatrix;
        if (lvm.a !== m.a || lvm.b !== m.b || lvm.c !== m.c || lvm.d !== m.d || lvm.tx !== m.tx || lvm.ty !== m.ty) {
          this._setSgNodesCullingDirty();
          lvm.a = m.a;
          lvm.b = m.b;
          lvm.c = m.c;
          lvm.d = m.d;
          lvm.tx = m.tx;
          lvm.ty = m.ty;
        }
      })
    });
    Camera.flags = cc.Enum({
      InCamera: 1,
      ParentInCamera: 2
    });
    module.exports = cc.Camera = Camera;
  }), {
    "./CCSGCameraNode": 61
  } ],
  61: [ (function(require, module, exports) {
    var tempMat = new cc.math.Matrix4();
    var CameraNode = _ccsg.Node.extend({
      ctor: function() {
        this._super();
        this._mat = new cc.math.Matrix4();
        this._mat.identity();
        this._beforeVisitCmd = new cc.CustomRenderCmd(this, this._onBeforeVisit);
        this._afterVisitCmd = new cc.CustomRenderCmd(this, this._onAfterVisit);
      },
      setTransform: function(a, b, c, d, tx, ty) {
        var mat = this._mat.mat;
        mat[0] = a;
        mat[1] = b;
        mat[4] = c;
        mat[5] = d;
        mat[12] = tx;
        mat[13] = ty;
      },
      addTarget: function(target) {
        var info = target._cameraInfo;
        info.sgCameraNode = this;
        info.originVisit = target.visit;
        target.visit = this._visit;
      },
      removeTarget: function(target) {
        target.visit = target._cameraInfo.originVisit;
      },
      _visit: function(parent) {
        var info = this._cameraInfo;
        var sgCameraNode = info.sgCameraNode;
        cc.renderer.pushRenderCommand(sgCameraNode._beforeVisitCmd);
        info.originVisit.call(this, parent);
        cc.renderer.pushRenderCommand(sgCameraNode._afterVisitCmd);
      },
      _onBeforeVisit: function() {
        cc.renderer._breakBatch();
        cc.math.glMatrixMode(cc.math.KM_GL_PROJECTION);
        tempMat.assignFrom(cc.current_stack.top);
        tempMat.multiply(this._mat);
        cc.current_stack.push(tempMat);
      },
      _onAfterVisit: function() {
        cc.renderer._breakBatch();
        cc.math.glMatrixMode(cc.math.KM_GL_PROJECTION);
        cc.current_stack.pop();
      }
    });
    module.exports = _ccsg.CameraNode = CameraNode;
  }), {} ],
  62: [ (function(require, module, exports) {
    cc.Collider.Box = cc.Class({
      properties: {
        _offset: cc.v2(0, 0),
        _size: cc.size(100, 100),
        offset: {
          tooltip: false,
          get: function() {
            return this._offset;
          },
          set: function(value) {
            this._offset = value;
          },
          type: cc.Vec2
        },
        size: {
          tooltip: false,
          get: function() {
            return this._size;
          },
          set: function(value) {
            this._size.width = value.width < 0 ? 0 : value.width;
            this._size.height = value.height < 0 ? 0 : value.height;
          },
          type: cc.Size
        }
      },
      resetInEditor: false
    });
    var BoxCollider = cc.Class({
      name: "cc.BoxCollider",
      extends: cc.Collider,
      mixins: [ cc.Collider.Box ],
      editor: false
    });
    cc.BoxCollider = module.exports = BoxCollider;
  }), {} ],
  63: [ (function(require, module, exports) {
    cc.Collider.Circle = cc.Class({
      properties: {
        _offset: cc.v2(0, 0),
        _radius: 50,
        offset: {
          get: function() {
            return this._offset;
          },
          set: function(value) {
            this._offset = value;
          },
          type: cc.Vec2
        },
        radius: {
          tooltip: false,
          get: function() {
            return this._radius;
          },
          set: function(value) {
            this._radius = value < 0 ? 0 : value;
          }
        }
      },
      resetInEditor: false
    });
    var CircleCollider = cc.Class({
      name: "cc.CircleCollider",
      extends: cc.Collider,
      mixins: [ cc.Collider.Circle ],
      editor: false
    });
    cc.CircleCollider = module.exports = CircleCollider;
  }), {} ],
  64: [ (function(require, module, exports) {
    var Collider = cc.Class({
      name: "cc.Collider",
      extends: cc.Component,
      properties: {
        editing: {
          default: false,
          serializable: false,
          tooltip: false
        },
        tag: {
          tooltip: false,
          default: 0,
          range: [ 0, 1e7 ],
          type: cc.Integer
        }
      },
      onDisable: function() {
        cc.director.getCollisionManager().removeCollider(this);
      },
      onEnable: function() {
        cc.director.getCollisionManager().addCollider(this);
      }
    });
    cc.Collider = module.exports = Collider;
  }), {} ],
  65: [ (function(require, module, exports) {
    var Contact = require("./CCContact");
    var CollisionType = Contact.CollisionType;
    var tempRect = cc.rect();
    var tempVec2 = cc.v2();
    var CollisionManager = cc.Class({
      mixins: [ cc.EventTarget ],
      properties: {
        enabled: false,
        enabledDrawBoundingBox: false
      },
      ctor: function() {
        this.__instanceId = cc.ClassManager.getNewInstanceId();
        this._contacts = [];
        this._colliders = [];
        this._debugDrawer = null;
        this._enabledDebugDraw = false;
      },
      update: function(dt) {
        if (!this.enabled) return;
        var i, l;
        var colliders = this._colliders;
        for (i = 0, l = colliders.length; i < l; i++) this.updateCollider(colliders[i]);
        var contacts = this._contacts;
        var results = [];
        for (i = 0, l = contacts.length; i < l; i++) {
          var collisionType = contacts[i].updateState();
          if (collisionType === CollisionType.None) continue;
          results.push([ collisionType, contacts[i] ]);
        }
        for (i = 0, l = results.length; i < l; i++) {
          var result = results[i];
          this._doCollide(result[0], result[1]);
        }
        this.drawColliders();
      },
      _doCollide: function(collisionType, contact) {
        var contactFunc;
        switch (collisionType) {
         case CollisionType.CollisionEnter:
          contactFunc = "onCollisionEnter";
          break;

         case CollisionType.CollisionStay:
          contactFunc = "onCollisionStay";
          break;

         case CollisionType.CollisionExit:
          contactFunc = "onCollisionExit";
        }
        var collider1 = contact.collider1;
        var collider2 = contact.collider2;
        var comps1 = collider1.node._components;
        var comps2 = collider2.node._components;
        var i, l, comp;
        for (i = 0, l = comps1.length; i < l; i++) {
          comp = comps1[i];
          comp[contactFunc] && comp[contactFunc](collider2, collider1);
        }
        for (i = 0, l = comps2.length; i < l; i++) {
          comp = comps2[i];
          comp[contactFunc] && comp[contactFunc](collider1, collider2);
        }
      },
      shouldCollide: function(c1, c2) {
        var node1 = c1.node, node2 = c2.node;
        var collisionMatrix = cc.game.collisionMatrix;
        return node1 !== node2 && collisionMatrix[node1.groupIndex][node2.groupIndex];
      },
      initCollider: function(collider) {
        if (!collider.world) {
          var world = collider.world = {};
          world.aabb = cc.rect();
          world.preAabb = cc.rect();
          world.radius = 0;
          if (collider instanceof cc.BoxCollider) {
            world.position = null;
            world.points = [ cc.v2(), cc.v2(), cc.v2(), cc.v2() ];
          } else if (collider instanceof cc.PolygonCollider) {
            world.position = null;
            world.points = collider.points.map((function(p) {
              return cc.v2(p.x, p.y);
            }));
          } else if (collider instanceof cc.CircleCollider) {
            world.position = cc.v2();
            world.points = null;
          }
        }
      },
      updateCollider: function(collider) {
        var offset = collider.offset;
        var world = collider.world;
        var aabb = world.aabb;
        var t = world.transform = collider.node.getNodeToWorldTransformAR();
        var preAabb = world.preAabb;
        preAabb.x = aabb.x;
        preAabb.y = aabb.y;
        preAabb.width = aabb.width;
        preAabb.height = aabb.height;
        if (collider instanceof cc.BoxCollider) {
          var size = collider.size;
          tempRect.x = offset.x - size.width / 2;
          tempRect.y = offset.y - size.height / 2;
          tempRect.width = size.width;
          tempRect.height = size.height;
          var wps = world.points;
          var wp0 = wps[0];
          var wp1 = wps[1];
          var wp2 = wps[2];
          var wp3 = wps[3];
          cc.obbApplyAffineTransform(tempRect, t, wp0, wp1, wp2, wp3);
          var minx = Math.min(wp0.x, wp1.x, wp2.x, wp3.x);
          var miny = Math.min(wp0.y, wp1.y, wp2.y, wp3.y);
          var maxx = Math.max(wp0.x, wp1.x, wp2.x, wp3.x);
          var maxy = Math.max(wp0.y, wp1.y, wp2.y, wp3.y);
          aabb.x = minx;
          aabb.y = miny;
          aabb.width = maxx - minx;
          aabb.height = maxy - miny;
        } else if (collider instanceof cc.CircleCollider) {
          var p = cc.pointApplyAffineTransform(collider.offset, t);
          world.position.x = p.x;
          world.position.y = p.y;
          t.tx = t.ty = 0;
          tempVec2.x = collider.radius;
          tempVec2.y = 0;
          var tempP = cc.pointApplyAffineTransform(tempVec2, t);
          var d = Math.sqrt(tempP.x * tempP.x + tempP.y * tempP.y);
          world.radius = d;
          aabb.x = p.x - d;
          aabb.y = p.y - d;
          aabb.width = 2 * d;
          aabb.height = 2 * d;
        } else if (collider instanceof cc.PolygonCollider) {
          var points = collider.points;
          var worldPoints = world.points;
          worldPoints.length = points.length;
          var minx = 1e6, miny = 1e6, maxx = -1e6, maxy = -1e6;
          for (var i = 0, l = points.length; i < l; i++) {
            worldPoints[i] || (worldPoints[i] = cc.v2());
            tempVec2.x = points[i].x + offset.x;
            tempVec2.y = points[i].y + offset.y;
            var p = cc.pointApplyAffineTransform(tempVec2, t);
            worldPoints[i].x = p.x;
            worldPoints[i].y = p.y;
            p.x > maxx && (maxx = p.x);
            p.x < minx && (minx = p.x);
            p.y > maxy && (maxy = p.y);
            p.y < miny && (miny = p.y);
          }
          aabb.x = minx;
          aabb.y = miny;
          aabb.width = maxx - minx;
          aabb.height = maxy - miny;
        }
      },
      addCollider: function(collider) {
        var colliders = this._colliders;
        var index = colliders.indexOf(collider);
        if (-1 === index) {
          for (var i = 0, l = colliders.length; i < l; i++) {
            var other = colliders[i];
            if (this.shouldCollide(collider, other)) {
              var contact = new Contact(collider, other);
              this._contacts.push(contact);
            }
          }
          colliders.push(collider);
          this.initCollider(collider);
        }
        collider.node.on("group-changed", this.onNodeGroupChanged, this);
      },
      removeCollider: function(collider) {
        var colliders = this._colliders;
        var index = colliders.indexOf(collider);
        if (index >= 0) {
          colliders.splice(index, 1);
          var contacts = this._contacts;
          for (var i = contacts.length - 1; i >= 0; i--) {
            var contact = contacts[i];
            if (contact.collider1 === collider || contact.collider2 === collider) {
              contact.touching && this._doCollide(CollisionType.CollisionExit, contact);
              contacts.splice(i, 1);
            }
          }
          collider.node.off("group-changed", this.onNodeGroupChanged, this);
        } else cc.errorID(6600);
      },
      attachDebugDrawToCamera: function(camera) {
        if (!this._debugDrawer) return;
        camera.addTarget(this._debugDrawer);
      },
      detachDebugDrawFromCamera: function(camera) {
        if (!this._debugDrawer) return;
        camera.removeTarget(this._debugDrawer);
      },
      onNodeGroupChanged: function(event) {
        var node = event.currentTarget;
        var colliders = node.getComponents(cc.Collider);
        for (var i = 0, l = colliders.length; i < l; i++) {
          this.removeCollider(colliders[i]);
          this.addCollider(colliders[i]);
        }
      },
      drawColliders: function() {
        var debugDrawer = this._debugDrawer;
        if (!this._enabledDebugDraw || !debugDrawer) return;
        debugDrawer.clear();
        var colliders = this._colliders;
        for (var i = 0, l = colliders.length; i < l; i++) {
          var collider = colliders[i];
          if (collider instanceof cc.BoxCollider || collider instanceof cc.PolygonCollider) {
            var ps = collider.world.points;
            if (ps.length > 0) {
              debugDrawer.strokeColor = cc.Color.WHITE;
              debugDrawer.moveTo(ps[0].x, ps[0].y);
              for (var j = 1; j < ps.length; j++) debugDrawer.lineTo(ps[j].x, ps[j].y);
              debugDrawer.close();
              debugDrawer.stroke();
            }
          } else if (collider instanceof cc.CircleCollider) {
            debugDrawer.circle(collider.world.position.x, collider.world.position.y, collider.world.radius);
            debugDrawer.stroke();
          }
          if (this.enabledDrawBoundingBox) {
            var aabb = collider.world.aabb;
            debugDrawer.strokeColor = cc.Color.BLUE;
            debugDrawer.moveTo(aabb.xMin, aabb.yMin);
            debugDrawer.lineTo(aabb.xMin, aabb.yMax);
            debugDrawer.lineTo(aabb.xMax, aabb.yMax);
            debugDrawer.lineTo(aabb.xMax, aabb.yMin);
            debugDrawer.close();
            debugDrawer.stroke();
          }
        }
      },
      onSceneLaunched: function() {
        if (this._enabledDebugDraw && this._debugDrawer) {
          this._debugDrawer.removeFromParent();
          cc.director.getScene()._sgNode.addChild(this._debugDrawer);
        }
      }
    });
    cc.js.getset(CollisionManager.prototype, "enabledDebugDraw", (function() {
      return this._enabledDebugDraw;
    }), (function(value) {
      if (value && !this._enabledDebugDraw) {
        if (!this._debugDrawer) {
          this._debugDrawer = new _ccsg.GraphicsNode();
          this._debugDrawer.retain();
        }
        cc.director.getScene()._sgNode.addChild(this._debugDrawer);
        cc.director.on(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneLaunched, this);
      } else if (!value && this._enabledDebugDraw) {
        this._debugDrawer.clear();
        this._debugDrawer.removeFromParent(false);
        cc.director.off(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneLaunched, this);
      }
      this._enabledDebugDraw = value;
    }));
    cc.CollisionManager = module.exports = CollisionManager;
  }), {
    "./CCContact": 66
  } ],
  66: [ (function(require, module, exports) {
    var Intersection = require("./CCIntersection");
    var CollisionType = cc.Enum({
      None: 0,
      CollisionEnter: 1,
      CollisionStay: 2,
      CollisionExit: 3
    });
    function Contact(collider1, collider2) {
      this.collider1 = collider1;
      this.collider2 = collider2;
      this.touching = false;
      var isCollider1Polygon = collider1 instanceof cc.BoxCollider || collider1 instanceof cc.PolygonCollider;
      var isCollider2Polygon = collider2 instanceof cc.BoxCollider || collider2 instanceof cc.PolygonCollider;
      var isCollider1Circle = collider1 instanceof cc.CircleCollider;
      var isCollider2Circle = collider2 instanceof cc.CircleCollider;
      if (isCollider1Polygon && isCollider2Polygon) this.testFunc = Intersection.polygonPolygon; else if (isCollider1Circle && isCollider2Circle) this.testFunc = Intersection.circleCircle; else if (isCollider1Polygon && isCollider2Circle) this.testFunc = Intersection.polygonCircle; else if (isCollider1Circle && isCollider2Polygon) {
        this.testFunc = Intersection.polygonCircle;
        this.collider1 = collider2;
        this.collider2 = collider1;
      } else cc.errorID(6601, cc.js.getClassName(collider1), cc.js.getClassName(collider2));
    }
    Contact.prototype.test = function() {
      var world1 = this.collider1.world;
      var world2 = this.collider2.world;
      if (!world1.aabb.intersects(world2.aabb)) return false;
      if (this.testFunc === Intersection.polygonPolygon) return this.testFunc(world1.points, world2.points);
      if (this.testFunc === Intersection.circleCircle) return this.testFunc(world1, world2);
      if (this.testFunc === Intersection.polygonCircle) return this.testFunc(world1.points, world2);
      return false;
    };
    Contact.prototype.updateState = function() {
      var result = this.test();
      var type = CollisionType.None;
      if (result && !this.touching) {
        this.touching = true;
        type = CollisionType.CollisionEnter;
      } else if (result && this.touching) type = CollisionType.CollisionStay; else if (!result && this.touching) {
        this.touching = false;
        type = CollisionType.CollisionExit;
      }
      return type;
    };
    Contact.CollisionType = CollisionType;
    module.exports = Contact;
  }), {
    "./CCIntersection": 67
  } ],
  67: [ (function(require, module, exports) {
    var Intersection = {};
    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 (0 !== u_b) {
        var ua = ua_t / u_b;
        var ub = ub_t / u_b;
        if (0 <= ua && ua <= 1 && 0 <= ub && ub <= 1) return true;
      }
      return false;
    }
    Intersection.lineLine = lineLine;
    function lineRect(a1, a2, b) {
      var r0 = new cc.Vec2(b.x, b.y);
      var r1 = new cc.Vec2(b.x, b.yMax);
      var r2 = new cc.Vec2(b.xMax, b.yMax);
      var r3 = new cc.Vec2(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;
    }
    Intersection.lineRect = lineRect;
    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;
    }
    Intersection.linePolygon = linePolygon;
    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;
    }
    Intersection.rectRect = rectRect;
    function rectPolygon(a, b) {
      var i, l;
      var r0 = new cc.Vec2(a.x, a.y);
      var r1 = new cc.Vec2(a.x, a.yMax);
      var r2 = new cc.Vec2(a.xMax, a.yMax);
      var r3 = new cc.Vec2(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 (i = 0, l = b.length; i < l; ++i) if (pointInPolygon(b[i], a)) 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;
    }
    Intersection.rectPolygon = rectPolygon;
    function polygonPolygon(a, b) {
      var i, 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;
    }
    Intersection.polygonPolygon = polygonPolygon;
    function circleCircle(a, b) {
      var distance = a.position.sub(b.position).mag();
      return distance < a.radius + b.radius;
    }
    Intersection.circleCircle = circleCircle;
    function polygonCircle(polygon, circle) {
      var position = circle.position;
      if (pointInPolygon(position, polygon)) return true;
      for (var i = 0, l = polygon.length; i < l; i++) {
        var start = 0 === i ? polygon[polygon.length - 1] : polygon[i - 1];
        var end = polygon[i];
        if (pointLineDistance(position, start, end, true) < circle.radius) return true;
      }
      return false;
    }
    Intersection.polygonCircle = polygonCircle;
    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, yi = polygon[i].y, xj = polygon[j].x, yj = polygon[j].y, intersect = yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi;
        intersect && (inside = !inside);
      }
      return inside;
    }
    Intersection.pointInPolygon = pointInPolygon;
    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;
      p = isSegment ? d ? t < 0 ? start : t > 1 ? end : cc.v2(start.x + t * dx, start.y + t * dy) : start : cc.v2(start.x + t * dx, start.y + t * dy);
      dx = point.x - p.x;
      dy = point.y - p.y;
      return Math.sqrt(dx * dx + dy * dy);
    }
    Intersection.pointLineDistance = pointLineDistance;
    cc.Intersection = module.exports = Intersection;
  }), {} ],
  68: [ (function(require, module, exports) {
    cc.Collider.Polygon = cc.Class({
      properties: {
        threshold: {
          default: 1,
          serializable: false,
          visible: false
        },
        _offset: cc.v2(0, 0),
        offset: {
          get: function() {
            return this._offset;
          },
          set: function(value) {
            this._offset = value;
          },
          type: cc.Vec2
        },
        points: {
          tooltip: false,
          default: function() {
            return [ cc.v2(-50, -50), cc.v2(50, -50), cc.v2(50, 50), cc.v2(-50, 50) ];
          },
          type: [ cc.Vec2 ]
        }
      },
      resetPointsByContour: false
    });
    var PolygonCollider = cc.Class({
      name: "cc.PolygonCollider",
      extends: cc.Collider,
      mixins: [ cc.Collider.Polygon ],
      editor: false
    });
    cc.PolygonCollider = module.exports = PolygonCollider;
  }), {} ],
  69: [ (function(require, module, exports) {
    require("./CCCollisionManager");
    require("./CCCollider");
    require("./CCBoxCollider");
    require("./CCCircleCollider");
    require("./CCPolygonCollider");
  }), {
    "./CCBoxCollider": 62,
    "./CCCircleCollider": 63,
    "./CCCollider": 64,
    "./CCCollisionManager": 65,
    "./CCPolygonCollider": 68
  } ],
  70: [ (function(require, module, exports) {
    require("./platform/CCClass");
    var Flags = require("./platform/CCObject").Flags;
    var JsArray = require("./platform/js").array;
    var IsStartCalled = Flags.IsStartCalled;
    var IsOnEnableCalled = Flags.IsOnEnableCalled;
    var IsEditorOnEnableCalled = Flags.IsEditorOnEnableCalled;
    var callerFunctor = false;
    var callOnEnableInTryCatch = false;
    var callStartInTryCatch = false;
    var callUpdateInTryCatch = false;
    var callLateUpdateInTryCatch = false;
    var callOnDisableInTryCatch = false;
    var callStart = "c.start();c._objFlags|=" + IsStartCalled;
    var callUpdate = "c.update(dt)";
    var callLateUpdate = "c.lateUpdate(dt)";
    function sortedIndex(array, comp) {
      var order = comp.constructor._executionOrder;
      var id = comp.__instanceId;
      for (var l = 0, 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.__instanceId;
          if (testId > id) h = m - 1; else {
            if (!(testId < id)) return m;
            l = m + 1;
          }
        }
      }
      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._enabled && comp.node._activeInHierarchy) ++next; else {
          iterator.removeAt(next);
          flagToClear && (comp._objFlags &= ~flagToClear);
        }
      }
    }
    var LifeCycleInvoker = cc.Class({
      __ctor__: function(invokeFunc) {
        var Iterator = JsArray.MutableForwardIterator;
        this._zero = new Iterator([]);
        this._neg = new Iterator([]);
        this._pos = new Iterator([]);
        false;
        this._invoke = invokeFunc;
      },
      statics: {
        stableRemoveInactive: stableRemoveInactive
      },
      add: null,
      remove: null,
      invoke: null
    });
    function compareOrder(a, b) {
      return a.constructor._executionOrder - b.constructor._executionOrder;
    }
    var OneOffInvoker = cc.Class({
      extends: LifeCycleInvoker,
      add: function(comp) {
        var order = comp.constructor._executionOrder;
        (0 === order ? this._zero : order < 0 ? this._neg : this._pos).array.push(comp);
      },
      remove: function(comp) {
        var order = comp.constructor._executionOrder;
        (0 === order ? this._zero : order < 0 ? this._neg : this._pos).fastRemove(comp);
      },
      cancelInactive: function(flagToClear) {
        stableRemoveInactive(this._zero, flagToClear);
        stableRemoveInactive(this._neg, flagToClear);
        stableRemoveInactive(this._pos, flagToClear);
      },
      invoke: function() {
        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;
        }
      }
    });
    var ReusableInvoker = cc.Class({
      extends: LifeCycleInvoker,
      add: function(comp) {
        var order = comp.constructor._executionOrder;
        if (0 === order) this._zero.array.push(comp); else {
          var array = order < 0 ? this._neg.array : this._pos.array;
          var i = sortedIndex(array, comp);
          i < 0 && array.splice(~i, 0, comp);
        }
      },
      remove: function(comp) {
        var order = comp.constructor._executionOrder;
        if (0 === order) this._zero.fastRemove(comp); else {
          var iterator = order < 0 ? this._neg : this._pos;
          var i = sortedIndex(iterator.array, comp);
          i >= 0 && iterator.removeAt(i);
        }
      },
      invoke: function(dt) {
        this._neg.array.length > 0 && this._invoke(this._neg, dt);
        this._invoke(this._zero, dt);
        this._pos.array.length > 0 && this._invoke(this._pos, dt);
      }
    });
    function enableInEditor(comp) {
      if (!(comp._objFlags & IsEditorOnEnableCalled)) {
        cc.engine.emit("component-enabled", comp.uuid);
        comp._objFlags |= IsEditorOnEnableCalled;
      }
    }
    function createInvokeImpl(funcOrCode, useDt) {
      if ("function" === typeof funcOrCode) return useDt ? function(iterator, dt) {
        var array = iterator.array;
        for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
          var comp = array[iterator.i];
          funcOrCode(comp, dt);
        }
      } : function(iterator) {
        var array = iterator.array;
        for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
          var comp = array[iterator.i];
          funcOrCode(comp);
        }
      };
      var body = "var a=it.array;for(it.i=0;it.i<a.length;++it.i){var c=a[it.i];" + funcOrCode + "}";
      return useDt ? Function("it", "dt", body) : Function("it", body);
    }
    function ctor() {
      this.startInvoker = new OneOffInvoker(createInvokeImpl(callStart));
      this.updateInvoker = new ReusableInvoker(createInvokeImpl(callUpdate, true));
      this.lateUpdateInvoker = new ReusableInvoker(createInvokeImpl(callLateUpdate, true));
      this.scheduleInNextFrame = [];
      this._updating = false;
    }
    var ComponentScheduler = cc.Class({
      ctor: ctor,
      unscheduleAll: ctor,
      statics: {
        LifeCycleInvoker: LifeCycleInvoker,
        OneOffInvoker: OneOffInvoker,
        createInvokeImpl: createInvokeImpl,
        invokeOnEnable: function(iterator) {
          var compScheduler = cc.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;
              deactivatedDuringOnEnable || compScheduler._onEnabled(comp);
            }
          }
        }
      },
      _onEnabled: function(comp) {
        cc.director.getScheduler().resumeTarget(comp);
        comp._objFlags |= IsOnEnableCalled;
        this._updating ? this.scheduleInNextFrame.push(comp) : this._scheduleImmediate(comp);
      },
      _onDisabled: function(comp) {
        cc.director.getScheduler().pauseTarget(comp);
        comp._objFlags &= ~IsOnEnableCalled;
        var index = this.scheduleInNextFrame.indexOf(comp);
        if (index >= 0) {
          JsArray.fastRemoveAt(this.scheduleInNextFrame, index);
          return;
        }
        !comp.start || comp._objFlags & IsStartCalled || this.startInvoker.remove(comp);
        comp.update && this.updateInvoker.remove(comp);
        comp.lateUpdate && this.lateUpdateInvoker.remove(comp);
      },
      enableComp: function(comp, invoker) {
        if (!(comp._objFlags & IsOnEnableCalled)) {
          if (comp.onEnable) {
            if (invoker) {
              invoker.add(comp);
              return;
            }
            comp.onEnable();
            var deactivatedDuringOnEnable = !comp.node._activeInHierarchy;
            if (deactivatedDuringOnEnable) return;
          }
          this._onEnabled(comp);
        }
      },
      disableComp: function(comp) {
        if (comp._objFlags & IsOnEnableCalled) {
          comp.onDisable && comp.onDisable();
          this._onDisabled(comp);
        }
      },
      _scheduleImmediate: function(comp) {
        !comp.start || comp._objFlags & IsStartCalled || this.startInvoker.add(comp);
        comp.update && this.updateInvoker.add(comp);
        comp.lateUpdate && this.lateUpdateInvoker.add(comp);
      },
      _deferredSchedule: function() {
        var comps = this.scheduleInNextFrame;
        for (var i = 0, len = comps.length; i < len; i++) {
          var comp = comps[i];
          this._scheduleImmediate(comp);
        }
        comps.length = 0;
      },
      startPhase: function() {
        this._updating = true;
        this.scheduleInNextFrame.length > 0 && this._deferredSchedule();
        this.startInvoker.invoke();
      },
      updatePhase: function(dt) {
        this.updateInvoker.invoke(dt);
      },
      lateUpdatePhase: function(dt) {
        this.lateUpdateInvoker.invoke(dt);
        this._updating = false;
      }
    });
    module.exports = ComponentScheduler;
  }), {
    "./platform/CCClass": 175,
    "./platform/CCObject": 181,
    "./platform/js": 196,
    "./utils/misc": 225
  } ],
  71: [ (function(require, module, exports) {
    var AnimationAnimator = require("../../animation/animation-animator");
    var AnimationClip = require("../../animation/animation-clip");
    function equalClips(clip1, clip2) {
      if (clip1 === clip2) return true;
      return clip1 && clip2 && (clip1.name === clip2.name || clip1._uuid === clip2._uuid);
    }
    var Animation = cc.Class({
      name: "cc.Animation",
      extends: require("./CCComponent"),
      mixins: [ cc.EventTarget ],
      editor: false,
      ctor: function() {
        cc.EventTarget.call(this);
        this._animator = null;
        this._nameToState = {};
        this._didInit = false;
        this._currentClip = null;
      },
      properties: {
        _defaultClip: {
          default: null,
          type: AnimationClip
        },
        defaultClip: {
          type: AnimationClip,
          get: function() {
            return this._defaultClip;
          },
          set: function(value) {
            true;
            return;
            var clips;
            var i, l;
          },
          tooltip: false
        },
        currentClip: {
          get: function() {
            return this._currentClip;
          },
          set: function(value) {
            this._currentClip = value;
          },
          type: AnimationClip,
          visible: false
        },
        _clips: {
          default: [],
          type: [ AnimationClip ],
          tooltip: false,
          visible: true
        },
        playOnLoad: {
          default: false,
          tooltip: false
        }
      },
      start: function() {
        if ((true, this.playOnLoad) && this._defaultClip) {
          var isPlaying = this._animator && this._animator.isPlaying;
          if (!isPlaying) {
            var state = this.getAnimationState(this._defaultClip.name);
            this._animator.playState(state);
          }
        }
      },
      onEnable: function() {
        this._animator && this._animator.resume();
      },
      onDisable: function() {
        this._animator && this._animator.pause();
      },
      onDestroy: function() {
        this.stop();
      },
      getClips: function() {
        return this._clips;
      },
      play: function(name, startTime) {
        var state = this.playAdditive(name, startTime);
        this._animator.stopStatesExcept(state);
        return state;
      },
      playAdditive: function(name, startTime) {
        this._init();
        var state = this.getAnimationState(name || this._defaultClip && this._defaultClip.name);
        if (state) {
          this.enabled = true;
          var animator = this._animator;
          if (animator.isPlaying && state.isPlaying) if (state.isPaused) animator.resumeState(state); else {
            animator.stopState(state);
            animator.playState(state, startTime);
          } else animator.playState(state, startTime);
          this.currentClip = state.clip;
        }
        return state;
      },
      stop: function(name) {
        if (!this._didInit) return;
        if (name) {
          var state = this._nameToState[name];
          state && this._animator.stopState(state);
        } else this._animator.stop();
      },
      pause: function(name) {
        if (!this._didInit) return;
        if (name) {
          var state = this._nameToState[name];
          state && this._animator.pauseState(state);
        } else this.enabled = false;
      },
      resume: function(name) {
        if (!this._didInit) return;
        if (name) {
          var state = this._nameToState[name];
          state && this._animator.resumeState(state);
        } else this.enabled = true;
      },
      setCurrentTime: function(time, name) {
        this._init();
        if (name) {
          var state = this._nameToState[name];
          state && this._animator.setStateTime(state, time);
        } else this._animator.setStateTime(time);
      },
      getAnimationState: function(name) {
        this._init();
        var state = this._nameToState[name];
        false;
        state && !state.curveLoaded && this._animator._reloadClip(state);
        return state || null;
      },
      addClip: function(clip, newName) {
        if (!clip) {
          cc.warnID(3900);
          return;
        }
        this._init();
        cc.js.array.contains(this._clips, clip) || this._clips.push(clip);
        newName = newName || clip.name;
        var oldState = this._nameToState[newName];
        if (oldState) {
          if (oldState.clip === clip) return oldState;
          var index = this._clips.indexOf(oldState.clip);
          -1 !== index && this._clips.splice(index, 1);
        }
        var newState = new cc.AnimationState(clip, newName);
        this._nameToState[newName] = newState;
        return newState;
      },
      removeClip: function(clip, force) {
        if (!clip) {
          cc.warnID(3901);
          return;
        }
        this._init();
        var state;
        for (var name in this._nameToState) {
          state = this._nameToState[name];
          var stateClip = state.clip;
          if (stateClip === clip) break;
        }
        if (clip === this._defaultClip) {
          if (!force) {
            true;
            cc.warnID(3902);
            return;
          }
          this._defaultClip = null;
        }
        if (state && state.isPlaying) {
          if (!force) {
            true;
            cc.warnID(3903);
            return;
          }
          this.stop(state.name);
        }
        this._clips = this._clips.filter((function(item) {
          return item !== clip;
        }));
        state && delete this._nameToState[state.name];
      },
      sample: function(name) {
        this._init();
        if (name) {
          var state = this._nameToState[name];
          state && state.sample();
        } else this._animator.sample();
      },
      on: function(type, callback, target, useCapture) {
        this._init();
        var ret = cc.EventTarget.prototype.on.call(this, type, callback, target, useCapture);
        var array = this._animator._anims.array;
        for (var i = 0; i < array.length; ++i) array[i]._setListeners(this);
        return ret;
      },
      off: function(type, callback, target, useCapture) {
        this._init();
        cc.EventTarget.prototype.off.call(this, type, callback, target, useCapture);
        var nameToState = this._nameToState;
        for (var name in nameToState) {
          var state = nameToState[name];
          state._setListeners(null);
        }
      },
      _init: function() {
        if (this._didInit) return;
        this._didInit = true;
        this._animator = new AnimationAnimator(this.node, this);
        this._createStates();
      },
      _createStates: function() {
        this._nameToState = {};
        var state = null;
        var defaultClipState = false;
        for (var i = 0; i < this._clips.length; ++i) {
          var clip = this._clips[i];
          if (clip) {
            state = new cc.AnimationState(clip);
            false;
            this._nameToState[state.name] = state;
            equalClips(this._defaultClip, clip) && (defaultClipState = state);
          }
        }
        if (this._defaultClip && !defaultClipState) {
          state = new cc.AnimationState(this._defaultClip);
          false;
          this._nameToState[state.name] = state;
        }
      }
    });
    cc.Animation = module.exports = Animation;
  }), {
    "../../animation/animation-animator": 11,
    "../../animation/animation-clip": 12,
    "./CCComponent": 76
  } ],
  72: [ (function(require, module, exports) {
    var AudioSource = cc.Class({
      name: "cc.AudioSource",
      extends: require("./CCComponent"),
      editor: false,
      ctor: function() {
        this.audio = new cc.Audio();
      },
      properties: {
        _clip: {
          default: "",
          url: cc.AudioClip
        },
        _volume: 1,
        _mute: false,
        _loop: false,
        _pausedFlag: {
          default: false,
          serializable: false
        },
        isPlaying: {
          get: function() {
            if (!this.audio) return false;
            var state = this.audio.getState();
            return state === cc.Audio.State.PLAYING;
          },
          visible: false
        },
        clip: {
          get: function() {
            return this._clip;
          },
          set: function(value) {
            if (value === this._clip) return;
            this._clip = value;
            this.audio.stop();
            this.audio.src = this._clip;
            this.audio.preload && this.audio.preload();
          },
          url: cc.AudioClip,
          tooltip: false,
          animatable: false
        },
        volume: {
          get: function() {
            return this._volume;
          },
          set: function(value) {
            value = cc.clamp01(value);
            this._volume = value;
            var audio = this.audio;
            if (audio && !this._mute) {
              audio.setVolume(value);
              audio._loaded || audio.on("load", (function() {
                audio.setVolume(value);
              }));
            }
            return value;
          },
          tooltip: false
        },
        mute: {
          get: function() {
            return this._mute;
          },
          set: function(value) {
            this._mute = value;
            this.audio && this.audio.setVolume(value ? 0 : this._volume);
            return value;
          },
          animatable: false,
          tooltip: false
        },
        loop: {
          get: function() {
            return this._loop;
          },
          set: function(value) {
            this._loop = value;
            this.audio && this.audio.setLoop(value);
            return value;
          },
          animatable: false,
          tooltip: false
        },
        playOnLoad: {
          default: false,
          tooltip: false,
          animatable: false
        },
        preload: {
          default: false,
          animatable: false
        }
      },
      _pausedCallback: function() {
        var audio = this.audio;
        if (!audio || audio.paused) return;
        this.audio.pause();
        this._pausedFlag = true;
      },
      _restoreCallback: function() {
        if (!this.audio) return;
        this._pausedFlag && this.audio.resume();
        this._pausedFlag = false;
      },
      onEnable: function() {
        this.playOnLoad && this.play();
        if (this.preload) {
          this.audio.src = this._clip;
          this.audio.preload();
        }
        cc.game.on(cc.game.EVENT_HIDE, this._pausedCallback, this);
        cc.game.on(cc.game.EVENT_SHOW, this._restoreCallback, this);
      },
      onDisable: function() {
        this.stop();
        cc.game.off(cc.game.EVENT_HIDE, this._pausedCallback, this);
        cc.game.off(cc.game.EVENT_SHOW, this._restoreCallback, this);
      },
      onDestroy: function() {
        this.stop();
        cc.audioEngine.uncache(this._clip);
      },
      play: function() {
        if (!this._clip) return;
        var volume = this._mute ? 0 : this._volume;
        var audio = this.audio;
        var loop = this._loop;
        if (audio._loaded) {
          audio.stop();
          audio.setCurrentTime(0);
          audio.play();
          return;
        }
        audio.src = this._clip;
        audio.once("load", (function() {
          audio.setLoop(loop);
          audio.setVolume(volume);
          audio.play();
        }));
        audio.preload();
      },
      stop: function() {
        this.audio && this.audio.stop();
      },
      pause: function() {
        this.audio && this.audio.pause();
      },
      resume: function() {
        this.audio && this.audio.resume();
      },
      rewind: function() {
        this.audio && this.audio.setCurrentTime(0);
      },
      getCurrentTime: function() {
        var time = 0;
        this.audio && (time = this.audio.getCurrentTime());
        return time;
      },
      setCurrentTime: function(time) {
        var audio = this.audio;
        if (!audio) return time;
        if (!audio._loaded) {
          audio.once("load", (function() {
            audio.setCurrentTime(time);
          }));
          return time;
        }
        audio.setCurrentTime(time);
        return time;
      },
      getDuration: function() {
        var time = 0;
        this.audio && (time = this.audio.getDuration());
        return time;
      }
    });
    cc.AudioSource = module.exports = AudioSource;
  }), {
    "./CCComponent": 76
  } ],
  73: [ (function(require, module, exports) {
    var BlockEvents = [ "touchstart", "touchmove", "touchend", "mousedown", "mousemove", "mouseup", "mouseenter", "mouseleave", "mousewheel" ];
    function stopPropagation(event) {
      event.stopPropagation();
    }
    var BlockInputEvents = cc.Class({
      name: "cc.BlockInputEvents",
      extends: require("./CCComponent"),
      editor: {
        menu: "i18n:MAIN_MENU.component.ui/Block Input Events",
        inspector: "packages://inspector/inspectors/comps/block-input-events.js",
        help: "i18n:COMPONENT.help_url.block-input-events"
      },
      onEnable: function() {
        for (var i = 0; i < BlockEvents.length; i++) this.node.on(BlockEvents[i], stopPropagation, this);
      },
      onDisable: function() {
        for (var i = 0; i < BlockEvents.length; i++) this.node.off(BlockEvents[i], stopPropagation, this);
      }
    });
    cc.BlockInputEvents = module.exports = BlockInputEvents;
  }), {
    "./CCComponent": 76
  } ],
  74: [ (function(require, module, exports) {
    var Transition = cc.Enum({
      NONE: 0,
      COLOR: 1,
      SPRITE: 2,
      SCALE: 3
    });
    var Button = cc.Class({
      name: "cc.Button",
      extends: require("./CCComponent"),
      ctor: function() {
        this._resetState();
        this._fromColor = null;
        this._toColor = null;
        this._time = 0;
        this._transitionFinished = true;
        this._fromScale = 1;
        this._toScale = 1;
        this._originalScale = 1;
        this._sprite = null;
        false;
      },
      _resetState: function() {
        this._pressed = false;
        this._hovered = false;
      },
      editor: false,
      properties: {
        interactable: {
          default: true,
          tooltip: false,
          notify: function(oldValue) {
            false;
            this._updateState();
            this.interactable || this._resetState();
          },
          animatable: false
        },
        _resizeToTarget: {
          animatable: false,
          set: function(value) {
            value && this._resizeNodeToTargetNode();
          }
        },
        enableAutoGrayEffect: {
          default: false,
          tooltip: false,
          notify: function() {
            this._updateDisabledState();
          }
        },
        transition: {
          default: Transition.NONE,
          tooltip: false,
          type: Transition,
          animatable: false
        },
        normalColor: {
          default: cc.color(214, 214, 214),
          displayName: "Normal",
          tooltip: false,
          notify: function() {
            this._updateState();
          }
        },
        pressedColor: {
          default: cc.color(211, 211, 211),
          displayName: "Pressed",
          tooltip: false
        },
        hoverColor: {
          default: cc.Color.WHITE,
          displayName: "Hover",
          tooltip: false
        },
        disabledColor: {
          default: cc.color(124, 124, 124),
          displayName: "Disabled",
          tooltip: false,
          notify: function() {
            this._updateState();
          }
        },
        duration: {
          default: .1,
          range: [ 0, 10 ],
          tooltip: false
        },
        zoomScale: {
          default: 1.2,
          tooltip: false
        },
        normalSprite: {
          default: null,
          type: cc.SpriteFrame,
          displayName: "Normal",
          tooltip: false,
          notify: function() {
            this._updateState();
          }
        },
        pressedSprite: {
          default: null,
          type: cc.SpriteFrame,
          displayName: "Pressed",
          tooltip: false,
          formerlySerializedAs: "pressedSprite",
          notify: function() {
            this._updateState();
          }
        },
        hoverSprite: {
          default: null,
          type: cc.SpriteFrame,
          displayName: "Hover",
          tooltip: false,
          formerlySerializedAs: "hoverSprite",
          notify: function() {
            this._updateState();
          }
        },
        disabledSprite: {
          default: null,
          type: cc.SpriteFrame,
          displayName: "Disabled",
          tooltip: false,
          notify: function() {
            this._updateState();
          }
        },
        target: {
          default: null,
          type: cc.Node,
          tooltip: false,
          notify: function() {
            this._applyTarget();
          }
        },
        clickEvents: {
          default: [],
          type: cc.Component.EventHandler,
          tooltip: false
        }
      },
      statics: {
        Transition: Transition
      },
      __preload: function() {
        this.target || (this.target = this.node);
        this._applyTarget();
        this._updateState();
      },
      onEnable: function() {
        this.normalSprite && this.normalSprite.ensureLoadTexture();
        this.hoverSprite && this.hoverSprite.ensureLoadTexture();
        this.pressedSprite && this.pressedSprite.ensureLoadTexture();
        this.disabledSprite && this.disabledSprite.ensureLoadTexture();
        true;
        this._registerEvent();
      },
      update: function(dt) {
        var target = this.target;
        if (this._transitionFinished) return;
        if (this.transition !== Transition.COLOR && this.transition !== Transition.SCALE) return;
        this.time += dt;
        var ratio = 1;
        this.duration > 0 && (ratio = this.time / this.duration);
        if (ratio >= 1) {
          ratio = 1;
          this._transitionFinished = true;
        }
        this.transition === Transition.COLOR ? target.color = this._fromColor.lerp(this._toColor, ratio) : this.transition === Transition.SCALE && (target.scale = cc.lerp(this._fromScale, this._toScale, ratio));
      },
      _registerEvent: function() {
        this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this);
        this.node.on(cc.Node.EventType.MOUSE_ENTER, this._onMouseMoveIn, this);
        this.node.on(cc.Node.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this);
      },
      _getTargetSprite: function(target) {
        var sprite = null;
        target && (sprite = target.getComponent(cc.Sprite));
        return sprite;
      },
      _applyTarget: function() {
        this._sprite = this._getTargetSprite(this.target);
        this.target && (this._originalScale = this.target.scale);
      },
      _onTouchBegan: function(event) {
        if (!this.interactable || !this.enabledInHierarchy) return;
        this._pressed = true;
        this._updateState();
        event.stopPropagation();
      },
      _onTouchMove: function(event) {
        if (!this.interactable || !this.enabledInHierarchy || !this._pressed) return;
        var touch = event.touch;
        var hit = this.node._hitTest(touch.getLocation());
        if (this.transition === Transition.SCALE && this.target) if (hit) {
          this._fromScale = this._originalScale;
          this._toScale = this._originalScale * this.zoomScale;
          this._transitionFinished = false;
        } else {
          this.time = 0;
          this._transitionFinished = true;
          this.target.scale = this._originalScale;
        } else {
          var state;
          state = hit ? "pressed" : "normal";
          this._applyTransition(state);
        }
        event.stopPropagation();
      },
      _onTouchEnded: function(event) {
        if (!this.interactable || !this.enabledInHierarchy) return;
        if (this._pressed) {
          cc.Component.EventHandler.emitEvents(this.clickEvents, event);
          this.node.emit("click", this);
        }
        this._pressed = false;
        this._updateState();
        event.stopPropagation();
      },
      _zoomUp: function() {
        this._fromScale = this._originalScale;
        this._toScale = this._originalScale * this.zoomScale;
        this.time = 0;
        this._transitionFinished = false;
      },
      _zoomBack: function() {
        this._fromScale = this.target.scale;
        this._toScale = this._originalScale;
        this.time = 0;
        this._transitionFinished = false;
      },
      _onTouchCancel: function() {
        if (!this.interactable || !this.enabledInHierarchy) return;
        this._pressed = false;
        this._updateState();
      },
      _onMouseMoveIn: function() {
        if (this._pressed || !this.interactable || !this.enabledInHierarchy) return;
        if (this.transition === Transition.SPRITE && !this.hoverSprite) return;
        if (!this._hovered) {
          this._hovered = true;
          this._updateState();
        }
      },
      _onMouseMoveOut: function() {
        if (this._hovered) {
          this._hovered = false;
          this._updateState();
        }
      },
      _updateState: function() {
        var state = this._getButtonState();
        this._applyTransition(state);
        this._updateDisabledState();
      },
      onDisable: function() {
        this._hovered = false;
        this._pressed = false;
        true;
        this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this);
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
        this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
        this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this);
        this.node.off(cc.Node.EventType.MOUSE_ENTER, this._onMouseMoveIn, this);
        this.node.off(cc.Node.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this);
      },
      _getButtonState: function() {
        var state;
        state = this.interactable ? this._pressed ? "pressed" : this._hovered ? "hover" : "normal" : "disabled";
        return state;
      },
      _updateColorTransition: function(state) {
        var color = this[state + "Color"];
        var target = this.target;
        false;
        this._fromColor = target.color.clone();
        this._toColor = color;
        this.time = 0;
        this._transitionFinished = false;
      },
      _updateSpriteTransition: function(state) {
        var sprite = this[state + "Sprite"];
        this._sprite && sprite && (this._sprite.spriteFrame = sprite);
      },
      _updateScaleTransition: function(state) {
        "pressed" === state ? this._zoomUp() : this._zoomBack();
      },
      _applyTransition: function(state) {
        var transition = this.transition;
        transition === Transition.COLOR ? this._updateColorTransition(state) : transition === Transition.SPRITE ? this._updateSpriteTransition(state) : transition === Transition.SCALE && this._updateScaleTransition(state);
      },
      _resizeNodeToTargetNode: false,
      _updateDisabledState: function() {
        this._sprite && this._sprite._sgNode.setState(0);
        this.enableAutoGrayEffect && this.transition !== Transition.COLOR && (this.transition === Transition.SPRITE && this.disabledSprite || this._sprite && !this.interactable && this._sprite._sgNode.setState(1));
      }
    });
    cc.Button = module.exports = Button;
  }), {
    "./CCComponent": 76
  } ],
  75: [ (function(require, module, exports) {
    var eventManager = require("../event-manager");
    var designResolutionWrapper = {
      getContentSize: function() {
        return cc.visibleRect;
      },
      setContentSize: function(size) {},
      _getWidth: function() {
        return this.getContentSize().width;
      },
      _getHeight: function() {
        return this.getContentSize().height;
      }
    };
    var Canvas = cc.Class({
      name: "cc.Canvas",
      extends: require("./CCComponent"),
      editor: false,
      resetInEditor: false,
      statics: {
        instance: null
      },
      properties: {
        _designResolution: cc.size(960, 640),
        designResolution: {
          get: function() {
            return cc.size(this._designResolution);
          },
          set: function(value) {
            this._designResolution.width = value.width;
            this._designResolution.height = value.height;
            this.applySettings();
          },
          tooltip: false
        },
        _fitWidth: false,
        _fitHeight: true,
        fitHeight: {
          get: function() {
            return this._fitHeight;
          },
          set: function(value) {
            if (this._fitHeight !== value) {
              this._fitHeight = value;
              this.applySettings();
            }
          },
          tooltip: false
        },
        fitWidth: {
          get: function() {
            return this._fitWidth;
          },
          set: function(value) {
            if (this._fitWidth !== value) {
              this._fitWidth = value;
              this.applySettings();
            }
          },
          tooltip: false
        }
      },
      ctor: function() {
        false;
        this._thisOnResized = this.onResized.bind(this);
      },
      __preload: function() {
        var Flags;
        false;
        if (Canvas.instance) return cc.errorID(6700, this.node.name, Canvas.instance.node.name);
        Canvas.instance = this;
        if (this.node._sizeProvider) {
          var renderer;
          false;
        } else this.node._sizeProvider = designResolutionWrapper;
        cc.director.on(cc.Director.EVENT_BEFORE_VISIT, this.alignWithScreen, this);
        false;
        true;
        cc.sys.isMobile ? window.addEventListener("resize", this._thisOnResized) : eventManager.addCustomListener("canvas-resize", this._thisOnResized);
        this.applySettings();
        this.onResized();
      },
      onDestroy: function() {
        this.node._sizeProvider === designResolutionWrapper && (this.node._sizeProvider = null);
        cc.director.off(cc.Director.EVENT_BEFORE_VISIT, this.alignWithScreen, this);
        false;
        true;
        cc.sys.isMobile ? window.removeEventListener("resize", this._thisOnResized) : eventManager.removeCustomListeners("canvas-resize", this._thisOnResized);
        Canvas.instance === this && (Canvas.instance = null);
      },
      alignWithScreen: function() {
        var designSize;
        false;
        var canvasSize = cc.visibleRect;
        var clipTopRight = !this.fitHeight && !this.fitWidth;
        var offsetX = 0;
        var offsetY = 0;
        if (clipTopRight) {
          designSize = cc.view.getDesignResolutionSize();
          offsetX = .5 * (designSize.width - canvasSize.width);
          offsetY = .5 * (designSize.height - canvasSize.height);
        }
        this.node.setPosition(.5 * canvasSize.width + offsetX, .5 * canvasSize.height + offsetY);
      },
      onResized: function() {
        this.alignWithScreen();
      },
      applySettings: function() {
        var ResolutionPolicy = cc.ResolutionPolicy;
        var policy;
        policy = this.fitHeight && this.fitWidth ? ResolutionPolicy.SHOW_ALL : this.fitHeight || this.fitWidth ? this.fitWidth ? ResolutionPolicy.FIXED_WIDTH : ResolutionPolicy.FIXED_HEIGHT : ResolutionPolicy.NO_BORDER;
        var designRes = this._designResolution;
        false;
        cc.view.setDesignResolutionSize(designRes.width, designRes.height, policy);
      }
    });
    cc.Canvas = module.exports = Canvas;
  }), {
    "../event-manager": 110,
    "./CCComponent": 76
  } ],
  76: [ (function(require, module, exports) {
    var CCObject = require("../platform/CCObject");
    var JS = require("../platform/js");
    var idGenerater = new (require("../platform/id-generater"))("Comp");
    var IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled;
    var IsOnLoadCalled = CCObject.Flags.IsOnLoadCalled;
    var Component = cc.Class({
      name: "cc.Component",
      extends: CCObject,
      ctor: function() {
        this.__instanceId = cc.ClassManager.getNewInstanceId();
        this.__eventTargets = [];
      },
      properties: {
        node: {
          default: null,
          visible: false
        },
        name: {
          get: function() {
            if (this._name) return this._name;
            var className = cc.js.getClassName(this);
            var trimLeft = className.lastIndexOf(".");
            trimLeft >= 0 && (className = className.slice(trimLeft + 1));
            return this.node.name + "<" + className + ">";
          },
          set: function(value) {
            this._name = value;
          },
          visible: false
        },
        _id: {
          default: "",
          serializable: false
        },
        uuid: {
          get: function() {
            var id = this._id;
            if (!id) {
              id = this._id = idGenerater.getNewId();
              false, false;
            }
            return id;
          },
          visible: false
        },
        __scriptAsset: false,
        _enabled: true,
        enabled: {
          get: function() {
            return this._enabled;
          },
          set: function(value) {
            if (this._enabled !== value) {
              this._enabled = value;
              if (this.node._activeInHierarchy) {
                var compScheduler = cc.director._compScheduler;
                value ? compScheduler.enableComp(this) : compScheduler.disableComp(this);
              }
            }
          },
          visible: false
        },
        enabledInHierarchy: {
          get: function() {
            return (this._objFlags & IsOnEnableCalled) > 0;
          },
          visible: false
        },
        _isOnLoadCalled: {
          get: function() {
            return this._objFlags & IsOnLoadCalled;
          }
        }
      },
      update: null,
      lateUpdate: null,
      __preload: null,
      onLoad: null,
      start: null,
      onEnable: null,
      onDisable: null,
      onDestroy: null,
      onFocusInEditor: null,
      onLostFocusInEditor: null,
      resetInEditor: null,
      addComponent: function(typeOrClassName) {
        return this.node.addComponent(typeOrClassName);
      },
      getComponent: function(typeOrClassName) {
        return this.node.getComponent(typeOrClassName);
      },
      getComponents: function(typeOrClassName) {
        return this.node.getComponents(typeOrClassName);
      },
      getComponentInChildren: function(typeOrClassName) {
        return this.node.getComponentInChildren(typeOrClassName);
      },
      getComponentsInChildren: function(typeOrClassName) {
        return this.node.getComponentsInChildren(typeOrClassName);
      },
      _getLocalBounds: null,
      onRestore: null,
      destroy: function() {
        var depend;
        false;
        this._super() && this._enabled && this.node._activeInHierarchy && cc.director._compScheduler.disableComp(this);
      },
      _onPreDestroy: function() {
        this.unscheduleAllCallbacks();
        var eventTargets = this.__eventTargets;
        for (var i = 0, l = eventTargets.length; i < l; ++i) {
          var target = eventTargets[i];
          target && target.targetOff(this);
        }
        eventTargets.length = 0;
        false;
        cc.director._nodeActivator.destroyComp(this);
        this.node._removeComponent(this);
        false, false;
      },
      _instantiate: function(cloned) {
        cloned || (cloned = cc.instantiate._clone(this, this));
        cloned.node = null;
        return cloned;
      },
      isRunning: function() {
        return this.enabledInHierarchy;
      },
      schedule: function(callback, interval, repeat, delay) {
        cc.assertID(callback, 1619);
        cc.assertID(interval >= 0, 1620);
        interval = interval || 0;
        repeat = isNaN(repeat) ? cc.macro.REPEAT_FOREVER : repeat;
        delay = delay || 0;
        var scheduler = cc.director.getScheduler();
        var paused = scheduler.isTargetPaused(this);
        scheduler.schedule(callback, this, interval, repeat, delay, paused);
      },
      scheduleOnce: function(callback, delay) {
        this.schedule(callback, 0, 0, delay);
      },
      unschedule: function(callback_fn) {
        if (!callback_fn) return;
        cc.director.getScheduler().unschedule(callback_fn, this);
      },
      unscheduleAllCallbacks: function() {
        cc.director.getScheduler().unscheduleAllForTarget(this);
      }
    });
    Component._requireComponent = null;
    Component._executionOrder = 0;
    false, false;
    JS.value(Component, "_registerEditorProps", (function(cls, props) {
      var reqComp = props.requireComponent;
      reqComp && (cls._requireComponent = reqComp);
      var order = props.executionOrder;
      order && "number" === typeof order && (cls._executionOrder = order);
      var name;
      var key;
      var val;
      var willExecuteInEditMode;
      false, false;
    }));
    Component.prototype.__scriptUuid = "";
    cc.Component = module.exports = Component;
  }), {
    "../platform/CCObject": 181,
    "../platform/id-generater": 192,
    "../platform/js": 196
  } ],
  77: [ (function(require, module, exports) {
    cc.Component.EventHandler = cc.Class({
      name: "cc.ClickEvent",
      properties: {
        target: {
          default: null,
          type: cc.Node
        },
        component: {
          default: ""
        },
        handler: {
          default: ""
        },
        customEventData: {
          default: ""
        }
      },
      statics: {
        emitEvents: function(events) {
          "use strict";
          var args, i, l;
          if (arguments.length > 0) {
            args = new Array(arguments.length - 1);
            for (i = 0, l = args.length; i < l; i++) args[i] = arguments[i + 1];
          }
          for (i = 0, l = events.length; i < l; i++) {
            var event = events[i];
            if (!(event instanceof cc.Component.EventHandler)) continue;
            event.emit(args);
          }
        }
      },
      emit: function(params) {
        var target = this.target;
        if (!cc.isValid(target)) return;
        var comp = target.getComponent(this.component);
        if (!cc.isValid(comp)) return;
        var handler = comp[this.handler];
        if ("function" !== typeof handler) return;
        if (null != this.customEventData && "" !== this.customEventData) {
          params = params.slice();
          params.push(this.customEventData);
        }
        handler.apply(comp, params);
      }
    });
  }), {} ],
  78: [ (function(require, module, exports) {
    require("../editbox/CCSGEditBox");
    var KeyboardReturnType = _ccsg.EditBox.KeyboardReturnType;
    var InputMode = _ccsg.EditBox.InputMode;
    var InputFlag = _ccsg.EditBox.InputFlag;
    var EditBox = cc.Class({
      name: "cc.EditBox",
      extends: cc._RendererUnderSG,
      editor: false,
      properties: {
        _useOriginalSize: true,
        _string: "",
        string: {
          tooltip: false,
          get: function() {
            return this._sgNode.string;
          },
          set: function(value) {
            this._sgNode.string = this._string = value;
          }
        },
        backgroundImage: {
          tooltip: false,
          default: null,
          type: cc.SpriteFrame,
          notify: function() {
            var sgNode = this._sgNode;
            var backgroundSprite = sgNode.getBackgroundSprite();
            if (this.backgroundImage) {
              var sprite = this._createBackgroundSprite();
              sprite.setContentSize(sgNode.getContentSize());
            } else backgroundSprite.removeFromParent();
          }
        },
        returnType: {
          default: KeyboardReturnType.DEFAULT,
          tooltip: false,
          displayName: "KeyboardReturnType",
          type: KeyboardReturnType,
          notify: function() {
            this._sgNode.returnType = this.returnType;
          }
        },
        inputFlag: {
          tooltip: false,
          default: InputFlag.DEFAULT,
          type: InputFlag,
          notify: function() {
            this._sgNode.inputFlag = this.inputFlag;
          }
        },
        inputMode: {
          tooltip: false,
          default: InputMode.ANY,
          type: InputMode,
          notify: function() {
            this._sgNode.inputMode = this.inputMode;
          }
        },
        fontSize: {
          tooltip: false,
          default: 20,
          notify: function() {
            this._sgNode.fontSize = this.fontSize;
          }
        },
        lineHeight: {
          tooltip: false,
          default: 40,
          notify: function() {
            this._sgNode.setLineHeight(this.lineHeight);
          }
        },
        fontColor: {
          tooltip: false,
          default: cc.Color.WHITE,
          notify: function() {
            this._sgNode.fontColor = this.fontColor;
          }
        },
        placeholder: {
          tooltip: false,
          default: "Enter text here...",
          notify: function() {
            this._sgNode.placeholder = this.placeholder;
          }
        },
        placeholderFontSize: {
          tooltip: false,
          default: 20,
          notify: function() {
            this._sgNode.placeholderFontSize = this.placeholderFontSize;
          }
        },
        placeholderFontColor: {
          tooltip: false,
          default: cc.Color.GRAY,
          notify: function() {
            this._sgNode.placeholderFontColor = this.placeholderFontColor;
          }
        },
        maxLength: {
          tooltip: false,
          default: 20,
          notify: function() {
            this._sgNode.maxLength = this.maxLength;
          }
        },
        stayOnTop: {
          tooltip: false,
          default: false,
          notify: function() {
            true;
            this._sgNode.stayOnTop(this.stayOnTop);
            this._sgNode.fontSize = this.fontSize;
            this._sgNode.fontColor = this.fontColor;
          }
        },
        _tabIndex: 0,
        tabIndex: {
          tooltip: false,
          get: function() {
            return this._tabIndex;
          },
          set: function(value) {
            this._tabIndex = value;
            this._sgNode.setTabIndex(value);
          }
        },
        editingDidBegan: {
          default: [],
          type: cc.Component.EventHandler
        },
        textChanged: {
          default: [],
          type: cc.Component.EventHandler
        },
        editingDidEnded: {
          default: [],
          type: cc.Component.EventHandler
        },
        editingReturn: {
          default: [],
          type: cc.Component.EventHandler
        }
      },
      statics: {
        KeyboardReturnType: KeyboardReturnType,
        InputFlag: InputFlag,
        InputMode: InputMode
      },
      _applyCapInset: function(sprite) {
        var backgroundImage = this.backgroundImage;
        sprite.setInsetTop(backgroundImage.insetTop);
        sprite.setInsetBottom(backgroundImage.insetBottom);
        sprite.setInsetRight(backgroundImage.insetRight);
        sprite.setInsetLeft(backgroundImage.insetLeft);
      },
      _createSgNode: function() {
        return new _ccsg.EditBox(cc.size(160, 40));
      },
      _createBackgroundSprite: function() {
        var sgNode = this._sgNode;
        var bgSprite = new cc.Scale9Sprite();
        bgSprite.setRenderingType(cc.Scale9Sprite.RenderingType.SLICED);
        if (this.backgroundImage) {
          this.backgroundImage.ensureLoadTexture();
          bgSprite.setSpriteFrame(this.backgroundImage);
          this._applyCapInset(bgSprite);
        }
        sgNode.initWithSizeAndBackgroundSprite(cc.size(160, 40), bgSprite);
        return bgSprite;
      },
      _initSgNode: function() {
        var sgNode = this._sgNode;
        true;
        sgNode.createDomElementIfNeeded();
        this._createBackgroundSprite();
        false;
        sgNode.setContentSize(this.node.getContentSize());
        sgNode.inputMode = this.inputMode;
        sgNode.maxLength = this.maxLength;
        sgNode.string = this._string;
        sgNode.fontSize = this.fontSize;
        sgNode.fontColor = this.fontColor;
        sgNode.placeholder = this.placeholder;
        sgNode.placeholderFontSize = this.placeholderFontSize;
        sgNode.placeholderFontColor = this.placeholderFontColor;
        sgNode.inputFlag = this.inputFlag;
        sgNode.returnType = this.returnType;
        sgNode.setLineHeight(this.lineHeight);
        sgNode.stayOnTop(this.stayOnTop);
        sgNode.setTabIndex(this.tabIndex);
        sgNode.setDelegate(this);
      },
      editBoxEditingDidBegan: function() {
        cc.Component.EventHandler.emitEvents(this.editingDidBegan, this);
        this.node.emit("editing-did-began", this);
      },
      editBoxEditingDidEnded: function() {
        cc.Component.EventHandler.emitEvents(this.editingDidEnded, this);
        this.node.emit("editing-did-ended", this);
      },
      editBoxTextChanged: function(editBox, text) {
        cc.Component.EventHandler.emitEvents(this.textChanged, text, this);
        this.node.emit("text-changed", this);
      },
      editBoxEditingReturn: function() {
        cc.Component.EventHandler.emitEvents(this.editingReturn, this);
        this.node.emit("editing-return", this);
      },
      onDestroy: function() {
        this._sgNode.setDelegate(null);
        this._super();
      },
      __preload: function() {
        this._super();
        true;
        this._registerEvent();
      },
      _registerEvent: function() {
        true;
        this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
      },
      _onTouchBegan: function(event) {
        this._sgNode && this._sgNode._onTouchBegan(event.touch);
        event.stopPropagation();
      },
      _onTouchEnded: function(event) {
        this._sgNode && this._sgNode._onTouchEnded();
        event.stopPropagation();
      },
      setFocus: function() {
        this._sgNode && this._sgNode.setFocus();
      },
      isFocused: function() {
        var isFocused = false;
        this._sgNode && (isFocused = this._sgNode.isFocused());
        return isFocused;
      }
    });
    false;
    cc.EditBox = module.exports = EditBox;
  }), {
    "../editbox/CCSGEditBox": 105
  } ],
  79: [ (function(require, module, exports) {
    require("../label/CCSGLabel");
    require("../label/CCSGLabelCanvasRenderCmd");
    require("../label/CCSGLabelWebGLRenderCmd");
    var HorizontalAlign = cc.TextAlignment;
    var VerticalAlign = cc.VerticalTextAlignment;
    var Overflow = _ccsg.Label.Overflow;
    function debounce(func, wait, immediate) {
      var timeout;
      return function() {
        var context = this;
        var later = function() {
          timeout = null;
          immediate || func.apply(context, arguments);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        callNow && func.apply(context, arguments);
      };
    }
    var Label = cc.Class({
      name: "cc.Label",
      extends: cc._RendererUnderSG,
      ctor: function() {
        false;
      },
      editor: false,
      _updateSgNodeString: function() {
        this._sgNode.setString(this.string);
        this._updateNodeSize();
      },
      _updateSgNodeFontSize: function() {
        if (this._sgNode) {
          this._sgNode.setFontSize(this._fontSize);
          this._updateNodeSize();
        }
      },
      properties: {
        _useOriginalSize: true,
        string: {
          default: "Label",
          multiline: true,
          tooltip: false,
          notify: function() {
            if (this._sgNode) {
              false;
              this._updateSgNodeString();
            }
          }
        },
        horizontalAlign: {
          default: HorizontalAlign.LEFT,
          type: HorizontalAlign,
          tooltip: false,
          notify: function() {
            this._sgNode && this._sgNode.setHorizontalAlign(this.horizontalAlign);
          },
          animatable: false
        },
        verticalAlign: {
          default: VerticalAlign.TOP,
          type: VerticalAlign,
          tooltip: false,
          notify: function() {
            this._sgNode && this._sgNode.setVerticalAlign(this.verticalAlign);
          },
          animatable: false
        },
        _actualFontSize: {
          default: 40
        },
        actualFontSize: {
          displayName: "Actual Font Size",
          animatable: false,
          readonly: true,
          get: function() {
            this._sgNode && (this._actualFontSize = this._sgNode.getFontSize());
            return this._actualFontSize;
          }
        },
        _fontSize: 40,
        fontSize: {
          get: function() {
            return this._fontSize;
          },
          set: function(value) {
            this._fontSize = value;
            false;
            this._updateSgNodeFontSize();
          },
          tooltip: false
        },
        fontFamily: {
          default: "Arial",
          tooltip: false,
          notify: function() {
            this._sgNode && this._sgNode.setFontFamily(this.fontFamily);
          },
          animatable: false
        },
        _lineHeight: 40,
        lineHeight: {
          get: function() {
            this._sgNode && (this._lineHeight = this._sgNode.getLineHeight());
            return this._lineHeight;
          },
          set: function(value) {
            this._lineHeight = value;
            if (this._sgNode) {
              this._sgNode.setLineHeight(value);
              this._updateNodeSize();
            }
          },
          tooltip: false
        },
        overflow: {
          default: Overflow.NONE,
          type: Overflow,
          tooltip: false,
          notify: function() {
            if (this._sgNode) {
              this._sgNode.setOverflow(this.overflow);
              this._updateNodeSize();
            }
          },
          animatable: false
        },
        _enableWrapText: true,
        enableWrapText: {
          get: function() {
            this._sgNode && (this._enableWrapText = this._sgNode.isWrapTextEnabled());
            return this._enableWrapText;
          },
          set: function(value) {
            this._enableWrapText = value;
            this._sgNode && this._sgNode.enableWrapText(value);
          },
          animatable: false,
          tooltip: false
        },
        _N$file: null,
        font: {
          get: function() {
            return this._N$file;
          },
          set: function(value) {
            value || (this._isSystemFontUsed = true);
            false;
            this._N$file = value;
            this._bmFontOriginalSize = -1;
            value && this._isSystemFontUsed && (this._isSystemFontUsed = false);
            if (this._sgNode) {
              "string" === typeof value && cc.warnID(4e3);
              var font = this.font;
              if (font instanceof cc.BitmapFont) if (font.spriteFrame) {
                true;
                this._sgNode.setFontAsset(font);
              } else {
                cc.warnID(4011, font.name);
                this._sgNode.setFontFamily("");
              } else this._sgNode.setFontAsset(font);
            }
            value instanceof cc.BitmapFont && (this._bmFontOriginalSize = value.fontSize);
          },
          type: cc.Font,
          tooltip: false,
          animatable: false
        },
        _isSystemFontUsed: true,
        useSystemFont: {
          get: function() {
            return this._isSystemFontUsed;
          },
          set: function(value) {
            false;
            this._isSystemFontUsed = !!value;
            if (value) {
              this.font = null;
              this._sgNode && this._sgNode.setFontFamily(this.fontFamily);
            }
          },
          animatable: false,
          tooltip: false
        },
        _bmFontOriginalSize: {
          displayName: "BMFont Original Size",
          default: -1,
          serializable: false,
          readonly: true,
          visible: true,
          animatable: false
        },
        _spacingX: 0,
        spacingX: {
          get: function() {
            return this._spacingX;
          },
          set: function(value) {
            this._spacingX = value;
            if (this._sgNode) {
              this._sgNode.setSpacingX(this.spacingX);
              this._updateNodeSize();
            }
          }
        }
      },
      statics: {
        HorizontalAlign: HorizontalAlign,
        VerticalAlign: VerticalAlign,
        Overflow: Overflow
      },
      __preload: function() {
        this._super();
        true;
        this._sgNode.on("load", this._updateNodeSize, this);
        this._updateNodeSize();
      },
      _createSgNode: function() {
        return null;
      },
      _initSgNode: function() {
        var font = this.font;
        "string" === typeof font && cc.warnID(4e3);
        var sgNode;
        if (font instanceof cc.BitmapFont) if (font.spriteFrame) {
          false;
          sgNode = this._sgNode = _ccsg.Label.pool.get(this.string, font);
        } else {
          cc.warnID(4011, font.name);
          sgNode = this._sgNode = _ccsg.Label.pool.get(this.string);
        } else sgNode = this._sgNode = _ccsg.Label.pool.get(this.string, font, null, this._fontSize);
        false;
        font instanceof cc.BitmapFont && (this._bmFontOriginalSize = font.fontSize);
        sgNode.setVisible(false);
        sgNode.setHorizontalAlign(this.horizontalAlign);
        sgNode.setVerticalAlign(this.verticalAlign);
        sgNode.setFontSize(this._fontSize);
        this.useSystemFont && sgNode.setFontFamily(this.fontFamily);
        sgNode.setOverflow(this.overflow);
        sgNode.enableWrapText(this._enableWrapText);
        sgNode.setLineHeight(this._lineHeight);
        sgNode.setString(this.string);
        font instanceof cc.BitmapFont && sgNode.setSpacingX(this.spacingX);
        false;
        false;
        sgNode.setContentSize(this.node.getContentSize());
        sgNode.setColor(this.node.color);
      },
      _updateNodeSize: function() {
        var initialized = this._sgNode && this._sgNode.parent;
        initialized && (this.overflow !== Overflow.NONE && this.overflow !== Overflow.RESIZE_HEIGHT || this.node.setContentSize(this._sgNode.getContentSize()));
      },
      onDestroy: function() {
        var sgNodeBeforeDestroy = this._sgNode;
        this._super();
        if (sgNodeBeforeDestroy) {
          sgNodeBeforeDestroy.removeFromParent(true);
          _ccsg.Label.pool.put(sgNodeBeforeDestroy);
        }
      }
    });
    cc.Label = module.exports = Label;
  }), {
    "../label/CCSGLabel": 126,
    "../label/CCSGLabelCanvasRenderCmd": 127,
    "../label/CCSGLabelWebGLRenderCmd": 128
  } ],
  80: [ (function(require, module, exports) {
    var LabelOutline = cc.Class({
      name: "cc.LabelOutline",
      extends: require("./CCComponent"),
      editor: false,
      ctor: function() {
        this._labelSGNode = null;
      },
      properties: {
        _color: cc.color(255, 255, 255, 255),
        _width: 1,
        color: {
          get: function() {
            return this._color;
          },
          set: function(value) {
            this._color = cc.color(value);
            this._labelSGNode && this._labelSGNode.setOutlineColor(cc.color(this._color));
          }
        },
        width: {
          get: function() {
            return this._width;
          },
          set: function(value) {
            this._width = value;
            if (this._labelSGNode) {
              this._labelSGNode.setOutlineWidth(value);
              this._labelSGNode.setMargin(value);
            }
          }
        }
      },
      onEnable: function() {
        var label = this.node.getComponent("cc.Label");
        var sgNode = this._labelSGNode = label && label._sgNode;
        if (this._labelSGNode) {
          sgNode.setOutlined(true);
          sgNode.setOutlineColor(cc.color(this._color));
          sgNode.setOutlineWidth(this._width);
          sgNode.setMargin(this._width);
        }
      },
      onDisable: function() {
        if (this._labelSGNode) {
          this._labelSGNode.setOutlined(false);
          this._labelSGNode.setMargin(0);
        }
        this._labelSGNode = null;
      }
    });
    cc.LabelOutline = module.exports = LabelOutline;
  }), {
    "./CCComponent": 76
  } ],
  81: [ (function(require, module, exports) {
    var Type = cc.Enum({
      NONE: 0,
      HORIZONTAL: 1,
      VERTICAL: 2,
      GRID: 3
    });
    var ResizeMode = cc.Enum({
      NONE: 0,
      CONTAINER: 1,
      CHILDREN: 2
    });
    var AxisDirection = cc.Enum({
      HORIZONTAL: 0,
      VERTICAL: 1
    });
    var VerticalDirection = cc.Enum({
      BOTTOM_TO_TOP: 0,
      TOP_TO_BOTTOM: 1
    });
    var HorizontalDirection = cc.Enum({
      LEFT_TO_RIGHT: 0,
      RIGHT_TO_LEFT: 1
    });
    var Layout = cc.Class({
      name: "cc.Layout",
      extends: require("./CCComponent"),
      editor: false,
      properties: {
        _layoutSize: cc.size(300, 200),
        _layoutDirty: {
          default: true,
          serializable: false
        },
        _resize: ResizeMode.NONE,
        _N$layoutType: Type.NONE,
        type: {
          type: Type,
          get: function() {
            return this._N$layoutType;
          },
          set: function(value) {
            this._N$layoutType = value;
            var reLayouted;
            false;
            this._doLayoutDirty();
          },
          tooltip: false,
          animatable: false
        },
        resizeMode: {
          type: ResizeMode,
          tooltip: false,
          animatable: false,
          get: function() {
            return this._resize;
          },
          set: function(value) {
            if (this.type === Type.NONE && value === ResizeMode.CHILDREN) return;
            this._resize = value;
            var reLayouted;
            false;
            this._doLayoutDirty();
          }
        },
        cellSize: {
          default: cc.size(40, 40),
          tooltip: false,
          type: cc.Size,
          notify: function() {
            this._doLayoutDirty();
          }
        },
        startAxis: {
          default: AxisDirection.HORIZONTAL,
          tooltip: false,
          type: AxisDirection,
          notify: function() {
            var reLayouted;
            false;
            this._doLayoutDirty();
          },
          animatable: false
        },
        _N$padding: {
          default: 0
        },
        paddingLeft: {
          default: 0,
          tooltip: false,
          notify: function() {
            this._doLayoutDirty();
          }
        },
        paddingRight: {
          default: 0,
          tooltip: false,
          notify: function() {
            this._doLayoutDirty();
          }
        },
        paddingTop: {
          default: 0,
          tooltip: false,
          notify: function() {
            this._doLayoutDirty();
          }
        },
        paddingBottom: {
          default: 0,
          tooltip: false,
          notify: function() {
            this._doLayoutDirty();
          }
        },
        spacingX: {
          default: 0,
          notify: function() {
            this._doLayoutDirty();
          },
          tooltip: false
        },
        spacingY: {
          default: 0,
          notify: function() {
            this._doLayoutDirty();
          },
          tooltip: false
        },
        verticalDirection: {
          default: VerticalDirection.TOP_TO_BOTTOM,
          type: VerticalDirection,
          notify: function() {
            this._doLayoutDirty();
          },
          tooltip: false,
          animatable: false
        },
        horizontalDirection: {
          default: HorizontalDirection.LEFT_TO_RIGHT,
          type: HorizontalDirection,
          notify: function() {
            this._doLayoutDirty();
          },
          tooltip: false,
          animatable: false
        }
      },
      statics: {
        Type: Type,
        VerticalDirection: VerticalDirection,
        HorizontalDirection: HorizontalDirection,
        ResizeMode: ResizeMode,
        AxisDirection: AxisDirection
      },
      _migratePaddingData: function() {
        this.paddingLeft = this._N$padding;
        this.paddingRight = this._N$padding;
        this.paddingTop = this._N$padding;
        this.paddingBottom = this._N$padding;
        this._N$padding = 0;
      },
      onEnable: function() {
        this._addEventListeners();
        cc.sizeEqualToSize(this.node.getContentSize(), cc.size(0, 0)) && this.node.setContentSize(this._layoutSize);
        0 !== this._N$padding && this._migratePaddingData();
        this._doLayoutDirty();
      },
      onDisable: function() {
        this._removeEventListeners();
      },
      _doLayoutDirty: function() {
        this._layoutDirty = true;
      },
      _addEventListeners: function() {
        cc.director.on(cc.Director.EVENT_BEFORE_VISIT, this.updateLayout, this);
        this.node.on("size-changed", this._resized, this);
        this.node.on("anchor-changed", this._doLayoutDirty, this);
        this.node.on("child-added", this._childAdded, this);
        this.node.on("child-removed", this._childRemoved, this);
        this.node.on("child-reorder", this._doLayoutDirty, this);
        this._addChildrenEventListeners();
      },
      _removeEventListeners: function() {
        cc.director.off(cc.Director.EVENT_BEFORE_VISIT, this.updateLayout, this);
        this.node.off("size-changed", this._resized, this);
        this.node.off("anchor-changed", this._doLayoutDirty, this);
        this.node.off("child-added", this._childAdded, this);
        this.node.off("child-removed", this._childRemoved, this);
        this.node.off("child-reorder", this._doLayoutDirty, this);
        this._removeChildrenEventListeners();
      },
      _addChildrenEventListeners: function() {
        var children = this.node.children;
        children.forEach(function(child) {
          child.on("size-changed", this._doLayoutDirty, this);
          child.on("position-changed", this._doLayoutDirty, this);
          child.on("anchor-changed", this._doLayoutDirty, this);
          child.on("active-in-hierarchy-changed", this._doLayoutDirty, this);
        }.bind(this));
      },
      _removeChildrenEventListeners: function() {
        var children = this.node.children;
        children.forEach(function(child) {
          child.off("size-changed", this._doLayoutDirty, this);
          child.off("position-changed", this._doLayoutDirty, this);
          child.off("anchor-changed", this._doLayoutDirty, this);
          child.off("active-in-hierarchy-changed", this._doLayoutDirty, this);
        }.bind(this));
      },
      _childAdded: function(event) {
        var child = event.detail;
        child.on("size-changed", this._doLayoutDirty, this);
        child.on("position-changed", this._doLayoutDirty, this);
        child.on("anchor-changed", this._doLayoutDirty, this);
        child.on("active-in-hierarchy-changed", this._doLayoutDirty, this);
        this._doLayoutDirty();
      },
      _childRemoved: function(event) {
        var child = event.detail;
        child.off("size-changed", this._doLayoutDirty, this);
        child.off("position-changed", this._doLayoutDirty, this);
        child.off("anchor-changed", this._doLayoutDirty, this);
        child.off("active-in-hierarchy-changed", this._doLayoutDirty, this);
        this._doLayoutDirty();
      },
      _resized: function() {
        this._layoutSize = this.node.getContentSize();
        this._doLayoutDirty();
      },
      _doLayoutHorizontally: function(baseWidth, rowBreak, fnPositionY, applyChildren) {
        var layoutAnchor = this.node.getAnchorPoint();
        var children = this.node.children;
        var sign = 1;
        var paddingX = this.paddingLeft;
        var leftBoundaryOfLayout = -layoutAnchor.x * baseWidth;
        if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) {
          sign = -1;
          leftBoundaryOfLayout = (1 - layoutAnchor.x) * baseWidth;
          paddingX = this.paddingRight;
        }
        var nextX = leftBoundaryOfLayout + sign * paddingX - sign * this.spacingX;
        var rowMaxHeight = 0;
        var tempMaxHeight = 0;
        var secondMaxHeight = 0;
        var row = 0;
        var containerResizeBoundary = 0;
        var maxHeightChildAnchorY = 0;
        var newChildWidth = this.cellSize.width;
        this.type !== Type.GRID && this.resizeMode === ResizeMode.CHILDREN && (newChildWidth = (baseWidth - (this.paddingLeft + this.paddingRight) - (children.length - 1) * this.spacingX) / children.length);
        children.forEach(function(child) {
          if (!child.activeInHierarchy) return;
          if (this._resize === ResizeMode.CHILDREN) {
            child.width = newChildWidth;
            this.type === Type.GRID && (child.height = this.cellSize.height);
          }
          var anchorX = child.anchorX;
          secondMaxHeight > tempMaxHeight && (tempMaxHeight = secondMaxHeight);
          if (child.height >= tempMaxHeight) {
            secondMaxHeight = tempMaxHeight;
            tempMaxHeight = child.height;
            maxHeightChildAnchorY = child.getAnchorPoint().y;
          }
          this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT && (anchorX = 1 - child.anchorX);
          nextX = nextX + sign * anchorX * child.width + sign * this.spacingX;
          var rightBoundaryOfChild = sign * (1 - anchorX) * child.width;
          if (rowBreak) {
            var rowBreakBoundary = nextX + rightBoundaryOfChild + sign * (sign > 0 ? this.paddingRight : this.paddingLeft);
            var leftToRightRowBreak = this.horizontalDirection === HorizontalDirection.LEFT_TO_RIGHT && rowBreakBoundary > (1 - layoutAnchor.x) * baseWidth;
            var rightToLeftRowBreak = this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT && rowBreakBoundary < -layoutAnchor.x * baseWidth;
            if (leftToRightRowBreak || rightToLeftRowBreak) {
              if (child.height >= tempMaxHeight) {
                0 === secondMaxHeight && (secondMaxHeight = tempMaxHeight);
                rowMaxHeight += secondMaxHeight;
                secondMaxHeight = tempMaxHeight;
              } else {
                rowMaxHeight += tempMaxHeight;
                secondMaxHeight = child.height;
                tempMaxHeight = 0;
              }
              nextX = leftBoundaryOfLayout + sign * (paddingX + anchorX * child.width);
              row++;
            }
          }
          var finalPositionY = fnPositionY(child, rowMaxHeight, row);
          baseWidth >= child.width + this.paddingLeft + this.paddingRight && applyChildren && child.setPosition(cc.p(nextX, finalPositionY));
          var signX = 1;
          var tempFinalPositionY;
          var topMarign = 0 === tempMaxHeight ? child.height : tempMaxHeight;
          if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) {
            containerResizeBoundary = containerResizeBoundary || this.node._contentSize.height;
            signX = -1;
            tempFinalPositionY = finalPositionY + signX * (topMarign * maxHeightChildAnchorY + this.paddingBottom);
            tempFinalPositionY < containerResizeBoundary && (containerResizeBoundary = tempFinalPositionY);
          } else {
            containerResizeBoundary = containerResizeBoundary || -this.node._contentSize.height;
            tempFinalPositionY = finalPositionY + signX * (topMarign * maxHeightChildAnchorY + this.paddingTop);
            tempFinalPositionY > containerResizeBoundary && (containerResizeBoundary = tempFinalPositionY);
          }
          nextX += rightBoundaryOfChild;
        }.bind(this));
        return containerResizeBoundary;
      },
      _getVerticalBaseHeight: function(children) {
        var newHeight = 0;
        var activeChildCount = 0;
        if (this.resizeMode === ResizeMode.CONTAINER) {
          children.forEach((function(child) {
            if (!child.activeInHierarchy) return;
            activeChildCount++;
            newHeight += child.height;
          }));
          newHeight += (activeChildCount - 1) * this.spacingY + this.paddingBottom + this.paddingTop;
        } else newHeight = this.node.getContentSize().height;
        return newHeight;
      },
      _doLayoutVertically: function(baseHeight, columnBreak, fnPositionX, applyChildren) {
        var layoutAnchor = this.node.getAnchorPoint();
        var children = this.node.children;
        var sign = 1;
        var paddingY = this.paddingBottom;
        var bottomBoundaryOfLayout = -layoutAnchor.y * baseHeight;
        if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) {
          sign = -1;
          bottomBoundaryOfLayout = (1 - layoutAnchor.y) * baseHeight;
          paddingY = this.paddingTop;
        }
        var nextY = bottomBoundaryOfLayout + sign * paddingY - sign * this.spacingY;
        var columnMaxWidth = 0;
        var tempMaxWidth = 0;
        var secondMaxWidth = 0;
        var column = 0;
        var containerResizeBoundary = 0;
        var maxWidthChildAnchorX = 0;
        var newChildHeight = this.cellSize.height;
        this.type !== Type.GRID && this.resizeMode === ResizeMode.CHILDREN && (newChildHeight = (baseHeight - (this.paddingTop + this.paddingBottom) - (children.length - 1) * this.spacingY) / children.length);
        children.forEach(function(child) {
          if (!child.activeInHierarchy) return;
          if (this.resizeMode === ResizeMode.CHILDREN) {
            child.height = newChildHeight;
            this.type === Type.GRID && (child.width = this.cellSize.width);
          }
          var anchorY = child.anchorY;
          secondMaxWidth > tempMaxWidth && (tempMaxWidth = secondMaxWidth);
          if (child.width >= tempMaxWidth) {
            secondMaxWidth = tempMaxWidth;
            tempMaxWidth = child.width;
            maxWidthChildAnchorX = child.getAnchorPoint().x;
          }
          this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM && (anchorY = 1 - child.anchorY);
          nextY = nextY + sign * anchorY * child.height + sign * this.spacingY;
          var topBoundaryOfChild = sign * (1 - anchorY) * child.height;
          if (columnBreak) {
            var columnBreakBoundary = nextY + topBoundaryOfChild + sign * (sign > 0 ? this.paddingTop : this.paddingBottom);
            var bottomToTopColumnBreak = this.verticalDirection === VerticalDirection.BOTTOM_TO_TOP && columnBreakBoundary > (1 - layoutAnchor.y) * baseHeight;
            var topToBottomColumnBreak = this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM && columnBreakBoundary < -layoutAnchor.y * baseHeight;
            if (bottomToTopColumnBreak || topToBottomColumnBreak) {
              if (child.width >= tempMaxWidth) {
                0 === secondMaxWidth && (secondMaxWidth = tempMaxWidth);
                columnMaxWidth += secondMaxWidth;
                secondMaxWidth = tempMaxWidth;
              } else {
                columnMaxWidth += tempMaxWidth;
                secondMaxWidth = child.width;
                tempMaxWidth = 0;
              }
              nextY = bottomBoundaryOfLayout + sign * (paddingY + anchorY * child.height);
              column++;
            }
          }
          var finalPositionX = fnPositionX(child, columnMaxWidth, column);
          baseHeight >= child.height + (this.paddingTop + this.paddingBottom) && applyChildren && child.setPosition(cc.p(finalPositionX, nextY));
          var signX = 1;
          var tempFinalPositionX;
          var rightMarign = 0 === tempMaxWidth ? child.width : tempMaxWidth;
          if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) {
            signX = -1;
            containerResizeBoundary = containerResizeBoundary || this.node._contentSize.width;
            tempFinalPositionX = finalPositionX + signX * (rightMarign * maxWidthChildAnchorX + this.paddingLeft);
            tempFinalPositionX < containerResizeBoundary && (containerResizeBoundary = tempFinalPositionX);
          } else {
            containerResizeBoundary = containerResizeBoundary || -this.node._contentSize.width;
            tempFinalPositionX = finalPositionX + signX * (rightMarign * maxWidthChildAnchorX + this.paddingRight);
            tempFinalPositionX > containerResizeBoundary && (containerResizeBoundary = tempFinalPositionX);
          }
          nextY += topBoundaryOfChild;
        }.bind(this));
        return containerResizeBoundary;
      },
      _doLayoutBasic: function() {
        var children = this.node.children;
        var allChildrenBoundingBox = null;
        children.forEach((function(child) {
          if (!child.activeInHierarchy) return;
          allChildrenBoundingBox = allChildrenBoundingBox ? cc.rectUnion(allChildrenBoundingBox, child.getBoundingBoxToWorld()) : child.getBoundingBoxToWorld();
        }));
        if (allChildrenBoundingBox) {
          var leftBottomInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.p(allChildrenBoundingBox.x, allChildrenBoundingBox.y));
          leftBottomInParentSpace = cc.pAdd(leftBottomInParentSpace, cc.p(-this.paddingLeft, -this.paddingBottom));
          var rightTopInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.p(allChildrenBoundingBox.x + allChildrenBoundingBox.width, allChildrenBoundingBox.y + allChildrenBoundingBox.height));
          rightTopInParentSpace = cc.pAdd(rightTopInParentSpace, cc.p(this.paddingRight, this.paddingTop));
          var newSize = cc.size(parseFloat((rightTopInParentSpace.x - leftBottomInParentSpace.x).toFixed(2)), parseFloat((rightTopInParentSpace.y - leftBottomInParentSpace.y).toFixed(2)));
          var layoutPosition = this.node.getPosition();
          var newAnchorX = (layoutPosition.x - leftBottomInParentSpace.x) / newSize.width;
          var newAnchorY = (layoutPosition.y - leftBottomInParentSpace.y) / newSize.height;
          var newAnchor = cc.p(parseFloat(newAnchorX.toFixed(2)), parseFloat(newAnchorY.toFixed(2)));
          this.node.setAnchorPoint(newAnchor);
          this.node.setContentSize(newSize);
        }
      },
      _doLayoutGridAxisHorizontal: function(layoutAnchor, layoutSize) {
        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(child, topOffset, row) {
          return bottomBoundaryOfLayout + sign * (topOffset + child.anchorY * child.height + paddingY + row * this.spacingY);
        }.bind(this);
        var newHeight = 0;
        if (this.resizeMode === ResizeMode.CONTAINER) {
          var boundary = this._doLayoutHorizontally(baseWidth, true, fnPositionY, false);
          newHeight = bottomBoundaryOfLayout - boundary;
          newHeight < 0 && (newHeight *= -1);
          bottomBoundaryOfLayout = -layoutAnchor.y * newHeight;
          if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) {
            sign = -1;
            bottomBoundaryOfLayout = (1 - layoutAnchor.y) * newHeight;
          }
        }
        this._doLayoutHorizontally(baseWidth, true, fnPositionY, true);
        this.resizeMode === ResizeMode.CONTAINER && this.node.setContentSize(baseWidth, newHeight);
      },
      _doLayoutGridAxisVertical: function(layoutAnchor, layoutSize) {
        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(child, leftOffset, column) {
          return leftBoundaryOfLayout + sign * (leftOffset + child.anchorX * child.width + paddingX + column * this.spacingX);
        }.bind(this);
        var newWidth = 0;
        if (this.resizeMode === ResizeMode.CONTAINER) {
          var boundary = this._doLayoutVertically(baseHeight, true, fnPositionX, false);
          newWidth = leftBoundaryOfLayout - boundary;
          newWidth < 0 && (newWidth *= -1);
          leftBoundaryOfLayout = -layoutAnchor.x * newWidth;
          if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) {
            sign = -1;
            leftBoundaryOfLayout = (1 - layoutAnchor.x) * newWidth;
          }
        }
        this._doLayoutVertically(baseHeight, true, fnPositionX, true);
        this.resizeMode === ResizeMode.CONTAINER && this.node.setContentSize(newWidth, baseHeight);
      },
      _doLayoutGrid: function() {
        var layoutAnchor = this.node.getAnchorPoint();
        var layoutSize = this.node.getContentSize();
        this.startAxis === AxisDirection.HORIZONTAL ? this._doLayoutGridAxisHorizontal(layoutAnchor, layoutSize) : this.startAxis === AxisDirection.VERTICAL && this._doLayoutGridAxisVertical(layoutAnchor, layoutSize);
      },
      _getHorizontalBaseWidth: function(children) {
        var newWidth = 0;
        var activeChildCount = 0;
        if (this.resizeMode === ResizeMode.CONTAINER) {
          children.forEach((function(child) {
            if (!child.activeInHierarchy) return;
            activeChildCount++;
            newWidth += child.width;
          }));
          newWidth += (activeChildCount - 1) * this.spacingX + this.paddingLeft + this.paddingRight;
        } else newWidth = this.node.getContentSize().width;
        return newWidth;
      },
      _doLayout: function() {
        if (this.type === Type.HORIZONTAL) {
          var newWidth = this._getHorizontalBaseWidth(this.node.children);
          var fnPositionY = function(child) {
            return child.y;
          };
          this._doLayoutHorizontally(newWidth, false, fnPositionY, true);
          this.node.width = newWidth;
        } else if (this.type === Type.VERTICAL) {
          var newHeight = this._getVerticalBaseHeight(this.node.children);
          var fnPositionX = function(child) {
            return child.x;
          };
          this._doLayoutVertically(newHeight, false, fnPositionX, true);
          this.node.height = newHeight;
        } else this.type === Type.NONE ? this.resizeMode === ResizeMode.CONTAINER && this._doLayoutBasic() : this.type === Type.GRID && this._doLayoutGrid();
      },
      updateLayout: function() {
        if (this._layoutDirty && this.node.children.length > 0) {
          this._doLayout();
          this._layoutDirty = false;
        }
      }
    });
    Object.defineProperty(Layout.prototype, "padding", {
      get: function() {
        cc.warnID(4100);
        return this.paddingLeft;
      },
      set: function(value) {
        this._N$padding = value;
        this._migratePaddingData();
        this._doLayoutDirty();
      }
    });
    cc.Layout = module.exports = Layout;
  }), {
    "./CCComponent": 76
  } ],
  82: [ (function(require, module, exports) {
    require("../../clipping-nodes/CCClippingNode");
    require("../../clipping-nodes/CCClippingNodeCanvasRenderCmd");
    require("../../clipping-nodes/CCClippingNodeWebGLRenderCmd");
    require("../../shape-nodes/CCDrawNode");
    var Base = cc._RendererInSG;
    var MaskType = cc.Enum({
      RECT: 0,
      ELLIPSE: 1,
      IMAGE_STENCIL: 2
    });
    var SEGEMENTS_MIN = 3;
    var SEGEMENTS_MAX = 1e4;
    var Mask = cc.Class({
      name: "cc.Mask",
      extends: Base,
      editor: false,
      properties: {
        _clippingStencil: {
          default: null,
          serializable: false
        },
        _type: MaskType.RECT,
        type: {
          get: function() {
            return this._type;
          },
          set: function(value) {
            this._type = value;
            this._refreshStencil();
          },
          type: MaskType,
          tooltip: false
        },
        spriteFrame: {
          default: null,
          type: cc.SpriteFrame,
          tooltip: false,
          notify: function() {
            this._refreshStencil();
          }
        },
        alphaThreshold: {
          default: 1,
          type: cc.Float,
          range: [ 0, 1, .1 ],
          slide: true,
          tooltip: false,
          notify: function() {
            if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
              cc.warnID(4201);
              return;
            }
            this._sgNode.setAlphaThreshold(this.alphaThreshold);
          }
        },
        inverted: {
          default: false,
          type: cc.Boolean,
          tooltip: false,
          notify: function() {
            if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
              cc.warnID(4202);
              return;
            }
            this._sgNode.setInverted(this.inverted);
          }
        },
        _segements: 64,
        segements: {
          get: function() {
            return this._segements;
          },
          set: function(value) {
            this._segements = cc.clampf(value, SEGEMENTS_MIN, SEGEMENTS_MAX);
            this._refreshStencil();
          },
          tooltip: false
        },
        _resizeToTarget: {
          animatable: false,
          set: function(value) {
            value && this._resizeNodeToTargetNode();
          }
        }
      },
      statics: {
        Type: MaskType
      },
      _resizeNodeToTargetNode: false,
      _initSgNode: function() {},
      _createSgNode: function() {
        return new cc.ClippingNode();
      },
      _hitTest: function(point) {
        var size = this.node.getContentSize(), w = size.width, h = size.height, trans = this.node.getNodeToWorldTransform();
        if (this.type === MaskType.RECT || this.type === MaskType.IMAGE_STENCIL) {
          var rect = cc.rect(0, 0, w, h);
          cc._rectApplyAffineTransformIn(rect, trans);
          var left = point.x - rect.x, right = rect.x + rect.width - point.x, bottom = point.y - rect.y, top = rect.y + rect.height - point.y;
          return left >= 0 && right >= 0 && top >= 0 && bottom >= 0;
        }
        if (this.type === MaskType.ELLIPSE) {
          var a = w / 2, b = h / 2;
          var cx = trans.a * a + trans.c * b + trans.tx;
          var cy = trans.b * a + trans.d * b + trans.ty;
          var px = point.x - cx, py = point.y - cy;
          return px * px / (a * a) + py * py / (b * b) < 1;
        }
      },
      onEnable: function() {
        this._super();
        this.spriteFrame && this.spriteFrame.ensureLoadTexture();
        this._refreshStencil();
        this.node.on("size-changed", this._refreshStencil, this);
        this.node.on("anchor-changed", this._refreshStencil, this);
      },
      onDisable: function() {
        this._super();
        this.node.off("size-changed", this._refreshStencil, this);
        this.node.off("anchor-changed", this._refreshStencil, this);
      },
      _calculateCircle: function(center, radius, segements) {
        var polies = [];
        var anglePerStep = 2 * Math.PI / segements;
        for (var step = 0; step < segements; ++step) polies.push(cc.v2(radius.x * Math.cos(anglePerStep * step) + center.x, radius.y * Math.sin(anglePerStep * step) + center.y));
        return polies;
      },
      _refreshStencil: function() {
        if (this.type === MaskType.IMAGE_STENCIL && cc._renderType !== cc.game.RENDER_TYPE_WEBGL && true) {
          cc.warnID(4200);
          return;
        }
        var contentSize = this.node.getContentSize();
        var anchorPoint = this.node.getAnchorPoint();
        var stencil = this._clippingStencil;
        if (this._type === MaskType.IMAGE_STENCIL) {
          var isSgSprite = stencil instanceof cc.Scale9Sprite;
          if (!isSgSprite || stencil._spriteFrame !== this.spriteFrame) {
            stencil = new cc.Scale9Sprite();
            stencil.setSpriteFrame(this.spriteFrame);
            this._sgNode.setStencil(stencil);
          }
          stencil.setContentSize(contentSize);
          stencil.setAnchorPoint(anchorPoint);
          this._sgNode.setAlphaThreshold(this.alphaThreshold);
        } else {
          var isDrawNode = stencil instanceof cc.DrawNode;
          if (!isDrawNode) {
            stencil = new cc.DrawNode();
            false;
            this._sgNode.setStencil(stencil);
          }
          var width = contentSize.width;
          var height = contentSize.height;
          var x = -width * anchorPoint.x;
          var y = -height * anchorPoint.y;
          var color = cc.color(255, 255, 255, 0);
          stencil.clear();
          if (this._type === MaskType.RECT) {
            var rectangle = [ cc.v2(x, y), cc.v2(x + width, y), cc.v2(x + width, y + height), cc.v2(x, y + height) ];
            stencil.drawPoly(rectangle, color, 0, color);
          } else if (this._type === MaskType.ELLIPSE) {
            var center = cc.v2(x + width / 2, y + height / 2);
            var radius = {
              x: width / 2,
              y: height / 2
            };
            stencil.drawPoly(this._calculateCircle(center, radius, this._segements), color, 0, color);
          }
        }
        this._sgNode.setInverted(this.inverted);
        this._clippingStencil = stencil;
        true;
        cc.renderer.childrenOrderDirty = true;
      }
    });
    false;
    cc.Mask = module.exports = Mask;
  }), {
    "../../clipping-nodes/CCClippingNode": 25,
    "../../clipping-nodes/CCClippingNodeCanvasRenderCmd": 26,
    "../../clipping-nodes/CCClippingNodeWebGLRenderCmd": 27,
    "../../shape-nodes/CCDrawNode": 274
  } ],
  83: [ (function(require, module, exports) {
    var SizeMode = cc.Enum({
      Unified: 0,
      Free: 1
    });
    var Direction = cc.Enum({
      Horizontal: 0,
      Vertical: 1
    });
    var EventType = cc.Enum({
      PAGE_TURNING: 0
    });
    var PageView = cc.Class({
      name: "cc.PageView",
      extends: cc.ScrollView,
      editor: false,
      ctor: function() {
        this._curPageIdx = 0;
        this._lastPageIdx = 0;
        this._pages = [];
        this._scrollCenterOffsetX = [];
        this._scrollCenterOffsetY = [];
      },
      properties: {
        sizeMode: {
          default: SizeMode.Unified,
          type: SizeMode,
          tooltip: false,
          notify: function() {
            this._syncSizeMode();
          }
        },
        direction: {
          default: Direction.Horizontal,
          type: Direction,
          tooltip: false,
          notify: function() {
            this._syncScrollDirection();
          }
        },
        scrollThreshold: {
          default: .5,
          type: cc.Float,
          slide: true,
          range: [ 0, 1, .01 ],
          tooltip: false
        },
        autoPageTurningThreshold: {
          default: 100,
          type: cc.Float,
          tooltip: false
        },
        pageTurningEventTiming: {
          default: .1,
          type: cc.Float,
          range: [ 0, 1, .01 ],
          tooltip: false
        },
        indicator: {
          default: null,
          type: cc.PageViewIndicator,
          tooltip: false,
          notify: function() {
            this.indicator && this.indicator.setPageView(this);
          }
        },
        pageTurningSpeed: {
          default: .3,
          type: cc.Float,
          tooltip: false
        },
        pageEvents: {
          default: [],
          type: cc.Component.EventHandler,
          tooltip: false
        }
      },
      statics: {
        SizeMode: SizeMode,
        Direction: Direction,
        EventType: EventType
      },
      __preload: function() {
        this.node.on("size-changed", this._updateAllPagesSize, this);
      },
      onEnable: function() {
        this._super();
        true;
        this.node.on("scroll-ended-with-threshold", this._dispatchPageTurningEvent, this);
      },
      onDisable: function() {
        this._super();
        true;
        this.node.off("scroll-ended-with-threshold", this._dispatchPageTurningEvent, this);
      },
      onLoad: function() {
        this._initPages();
        this.indicator && this.indicator.setPageView(this);
      },
      onDestroy: function() {
        this.node.off("size-changed", this._updateAllPagesSize, this);
      },
      getCurrentPageIndex: function() {
        return this._curPageIdx;
      },
      setCurrentPageIndex: function(index) {
        this.scrollToPage(index, true);
      },
      getPages: function() {
        return this._pages;
      },
      addPage: function(page) {
        if (!page || -1 !== this._pages.indexOf(page) || !this.content) return;
        this.content.addChild(page);
        this._pages.push(page);
        this._updatePageView();
      },
      insertPage: function(page, index) {
        if (index < 0 || !page || -1 !== this._pages.indexOf(page) || !this.content) return;
        var pageCount = this._pages.length;
        if (index >= pageCount) this.addPage(page); else {
          this._pages.splice(index, 0, page);
          this.content.addChild(page);
          this._updatePageView();
        }
      },
      removePage: function(page) {
        if (!page || !this.content) return;
        var index = this._pages.indexOf(page);
        if (-1 === index) {
          cc.warnID(4300, page.name);
          return;
        }
        this.removePageAtIndex(index);
      },
      removePageAtIndex: function(index) {
        var pageList = this._pages;
        if (index < 0 || index >= pageList.length) return;
        var page = pageList[index];
        if (!page) return;
        this.content.removeChild(page);
        pageList.splice(index, 1);
        this._updatePageView();
      },
      removeAllPages: function() {
        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();
      },
      scrollToPage: function(idx, timeInSecond) {
        if (idx < 0 || idx >= this._pages.length) return;
        timeInSecond = void 0 !== timeInSecond ? timeInSecond : .3;
        this._curPageIdx = idx;
        this.scrollToOffset(this._moveOffsetValue(idx), timeInSecond, true);
        this.indicator && this.indicator._changedState();
      },
      getScrollEndedEventTiming: function() {
        return this.pageTurningEventTiming;
      },
      _syncScrollDirection: function() {
        this.horizontal = this.direction === Direction.Horizontal;
        this.vertical = this.direction === Direction.Vertical;
      },
      _syncSizeMode: function() {
        if (!this.content) return;
        var layout = this.content.getComponent(cc.Layout);
        if (layout) {
          if (0 === this._pages.length) layout.padding = 0; else {
            var lastPage = this._pages[this._pages.length - 1];
            if (this.sizeMode === SizeMode.Free) if (this.direction === Direction.Horizontal) {
              layout.paddingLeft = (this.node.width - this._pages[0].width) / 2;
              layout.paddingRight = (this.node.width - lastPage.width) / 2;
            } else if (this.direction === Direction.Vertical) {
              layout.paddingTop = (this.node.height - this._pages[0].height) / 2;
              layout.paddingBottom = (this.node.height - lastPage.height) / 2;
            }
          }
          layout.updateLayout();
        }
      },
      _updatePageView: function() {
        var pageCount = this._pages.length;
        if (this._curPageIdx >= pageCount) {
          this._curPageIdx = 0 === pageCount ? 0 : pageCount - 1;
          this._lastPageIdx = this._curPageIdx;
        }
        for (var i = 0; i < pageCount; ++i) {
          this._pages[i].setSiblingIndex(i);
          this.direction === Direction.Horizontal ? this._scrollCenterOffsetX[i] = Math.abs(this.content.x + this._pages[i].x) : this._scrollCenterOffsetY[i] = Math.abs(this.content.y + this._pages[i].y);
        }
        var layout = this.content.getComponent(cc.Layout);
        layout && layout.enabled && layout.updateLayout();
        this.indicator && this.indicator._refresh();
      },
      _updateAllPagesSize: function() {
        if (this.sizeMode !== SizeMode.Unified) return;
        var locPages = this._pages;
        var selfSize = this.node.getContentSize();
        for (var i = 0, len = locPages.length; i < len; i++) locPages[i].setContentSize(selfSize);
      },
      _initPages: function() {
        if (!this.content) return;
        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();
      },
      _dispatchPageTurningEvent: function() {
        if (this._lastPageIdx === this._curPageIdx) return;
        this._lastPageIdx = this._curPageIdx;
        cc.Component.EventHandler.emitEvents(this.pageEvents, this, EventType.PAGE_TURNING);
        this.node.emit("page-turning", this);
      },
      _isScrollable: function(offset, index, nextIndex) {
        if (this.sizeMode === SizeMode.Free) {
          var curPageCenter, nextPageCenter;
          if (this.direction === Direction.Horizontal) {
            curPageCenter = this._scrollCenterOffsetX[index];
            nextPageCenter = this._scrollCenterOffsetX[nextIndex];
            return Math.abs(offset.x) >= Math.abs(curPageCenter - nextPageCenter) * this.scrollThreshold;
          }
          if (this.direction === Direction.Vertical) {
            curPageCenter = this._scrollCenterOffsetY[index];
            nextPageCenter = this._scrollCenterOffsetY[nextIndex];
            return Math.abs(offset.y) >= Math.abs(curPageCenter - nextPageCenter) * this.scrollThreshold;
          }
        } else {
          if (this.direction === Direction.Horizontal) return Math.abs(offset.x) >= this.node.width * this.scrollThreshold;
          if (this.direction === Direction.Vertical) return Math.abs(offset.y) >= this.node.height * this.scrollThreshold;
        }
      },
      _isQuicklyScrollable: function(touchMoveVelocity) {
        if (this.direction === Direction.Horizontal) {
          if (Math.abs(touchMoveVelocity.x) > this.autoPageTurningThreshold) return true;
        } else if (this.direction === Direction.Vertical && Math.abs(touchMoveVelocity.y) > this.autoPageTurningThreshold) return true;
        return false;
      },
      _moveOffsetValue: function(idx) {
        var offset = cc.p(0, 0);
        this.sizeMode === SizeMode.Free ? this.direction === Direction.Horizontal ? offset.x = this._scrollCenterOffsetX[idx] : this.direction === Direction.Vertical && (offset.y = this._scrollCenterOffsetY[idx]) : this.direction === Direction.Horizontal ? offset.x = idx * this.node.width : this.direction === Direction.Vertical && (offset.y = idx * this.node.height);
        return offset;
      },
      _getDragDirection: function(moveOffset) {
        if (this.direction === Direction.Horizontal) {
          if (0 === moveOffset.x) return 0;
          return moveOffset.x > 0 ? 1 : -1;
        }
        if (this.direction === Direction.Vertical) {
          if (0 === moveOffset.y) return 0;
          return moveOffset.y < 0 ? 1 : -1;
        }
      },
      _handleReleaseLogic: function(touch) {
        var bounceBackStarted = this._startBounceBackIfNeeded();
        var moveOffset = cc.pSub(this._touchBeganPosition, this._touchEndPosition);
        if (bounceBackStarted) {
          var dragDirection = this._getDragDirection(moveOffset);
          if (0 === dragDirection) return;
          this._curPageIdx = dragDirection > 0 ? this._pages.length - 1 : 0;
          this.indicator && this.indicator._changedState();
        } else {
          var index = this._curPageIdx, 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;
            }
            var touchMoveVelocity = this._calculateTouchMoveVelocity();
            if (this._isQuicklyScrollable(touchMoveVelocity)) {
              this.scrollToPage(nextIndex, timeInSecond);
              return;
            }
          }
          this.scrollToPage(index, timeInSecond);
        }
      },
      _onTouchBegan: function(event, captureListeners) {
        this._touchBeganPosition = event.touch.getLocation();
        this._super(event, captureListeners);
      },
      _onTouchMoved: function(event, captureListeners) {
        this._super(event, captureListeners);
      },
      _onTouchEnded: function(event, captureListeners) {
        this._touchEndPosition = event.touch.getLocation();
        this._super(event, captureListeners);
      },
      _onTouchCancelled: function(event, captureListeners) {
        this._touchEndPosition = event.touch.getLocation();
        this._super(event, captureListeners);
      },
      _onMouseWheel: function() {}
    });
    cc.PageView = module.exports = PageView;
  }), {} ],
  84: [ (function(require, module, exports) {
    var Direction = cc.Enum({
      HORIZONTAL: 0,
      VERTICAL: 1
    });
    var PageViewIndicator = cc.Class({
      name: "cc.PageViewIndicator",
      extends: require("./CCComponent"),
      editor: false,
      properties: {
        _layout: null,
        _pageView: null,
        _indicators: [],
        spriteFrame: {
          default: null,
          type: cc.SpriteFrame,
          tooltip: false
        },
        direction: {
          default: Direction.HORIZONTAL,
          type: Direction,
          tooltip: false
        },
        cellSize: {
          default: cc.size(20, 20),
          tooltip: false
        },
        spacing: {
          default: 0,
          tooltip: false
        }
      },
      statics: {
        Direction: Direction
      },
      onLoad: function() {
        this._updateLayout();
      },
      setPageView: function(target) {
        this._pageView = target;
        this._refresh();
      },
      _updateLayout: function() {
        this._layout = this.getComponent(cc.Layout);
        this._layout || (this._layout = this.addComponent(cc.Layout));
        if (this.direction === Direction.HORIZONTAL) {
          this._layout.type = cc.Layout.Type.HORIZONTAL;
          this._layout.spacingX = this.spacing;
        } else if (this.direction === Direction.VERTICAL) {
          this._layout.type = cc.Layout.Type.VERTICAL;
          this._layout.spacingY = this.spacing;
        }
        this._layout.resizeMode = cc.Layout.ResizeMode.CONTAINER;
      },
      _createIndicator: function() {
        var node = new cc.Node();
        var sprite = node.addComponent(cc.Sprite);
        sprite.spriteFrame = this.spriteFrame;
        node.parent = this.node;
        node.width = this.cellSize.width;
        node.height = this.cellSize.height;
        return node;
      },
      _changedState: function() {
        var indicators = this._indicators;
        if (0 === indicators.length) return;
        var idx = this._pageView._curPageIdx;
        if (idx >= indicators.length) return;
        for (var i = 0; i < indicators.length; ++i) {
          var node = indicators[i];
          node.opacity = 127.5;
        }
        indicators[idx].opacity = 255;
      },
      _refresh: function() {
        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) 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);
          }
        }
        this._layout && this._layout.enabledInHierarchy && this._layout.updateLayout();
        this._changedState();
      }
    });
    cc.PageViewIndicator = module.exports = PageViewIndicator;
  }), {
    "./CCComponent": 76
  } ],
  85: [ (function(require, module, exports) {
    var Mode = cc.Enum({
      HORIZONTAL: 0,
      VERTICAL: 1,
      FILLED: 2
    });
    var ProgressBar = cc.Class({
      name: "cc.ProgressBar",
      extends: require("./CCComponent"),
      editor: false,
      _initBarSprite: function() {
        if (this.barSprite) {
          var entity = this.barSprite.node;
          if (!entity) return;
          var nodeSize = this.node.getContentSize();
          var nodeAnchor = this.node.getAnchorPoint();
          var entitySize = entity.getContentSize();
          entity.parent === this.node && this.node.setContentSize(entitySize);
          this.barSprite.fillType === cc.Sprite.FillType.RADIAL && (this.mode = Mode.FILLED);
          var barSpriteSize = entity.getContentSize();
          this.mode === Mode.HORIZONTAL ? this.totalLength = barSpriteSize.width : this.mode === Mode.VERTICAL ? this.totalLength = barSpriteSize.height : this.totalLength = this.barSprite.fillRange;
          if (entity.parent === this.node) {
            var x = -nodeSize.width * nodeAnchor.x;
            var y = 0;
            entity.setPosition(cc.p(x, y));
          }
        }
      },
      _updateBarStatus: function() {
        if (this.barSprite) {
          var entity = this.barSprite.node;
          if (!entity) return;
          var entityAnchorPoint = entity.getAnchorPoint();
          var entitySize = entity.getContentSize();
          var entityPosition = entity.getPosition();
          var anchorPoint = cc.p(0, .5);
          var progress = cc.clamp01(this.progress);
          var actualLenth = this.totalLength * progress;
          var finalContentSize;
          var totalWidth;
          var totalHeight;
          switch (this.mode) {
           case Mode.HORIZONTAL:
            this.reverse && (anchorPoint = cc.p(1, .5));
            finalContentSize = cc.size(actualLenth, entitySize.height);
            totalWidth = this.totalLength;
            totalHeight = entitySize.height;
            break;

           case Mode.VERTICAL:
            anchorPoint = this.reverse ? cc.p(.5, 1) : cc.p(.5, 0);
            finalContentSize = cc.size(entitySize.width, actualLenth);
            totalWidth = entitySize.width;
            totalHeight = this.totalLength;
          }
          if (this.mode === Mode.FILLED) if (this.barSprite.type !== cc.Sprite.Type.FILLED) cc.warn("ProgressBar FILLED mode only works when barSprite's Type is FILLED!"); else {
            this.reverse && (actualLenth *= -1);
            this.barSprite.fillRange = actualLenth;
          } else if (this.barSprite.type !== cc.Sprite.Type.FILLED) {
            var anchorOffsetX = anchorPoint.x - entityAnchorPoint.x;
            var anchorOffsetY = anchorPoint.y - entityAnchorPoint.y;
            var finalPosition = cc.p(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY);
            entity.setPosition(cc.pAdd(entityPosition, finalPosition));
            entity.setAnchorPoint(anchorPoint);
            entity.setContentSize(finalContentSize);
          } else cc.warn("ProgressBar non-FILLED mode only works when barSprite's Type is non-FILLED!");
        }
      },
      properties: {
        barSprite: {
          default: null,
          type: cc.Sprite,
          tooltip: false,
          notify: function() {
            this._initBarSprite();
          },
          animatable: false
        },
        mode: {
          default: Mode.HORIZONTAL,
          type: Mode,
          tooltip: false,
          notify: function() {
            if (this.barSprite) {
              var entity = this.barSprite.node;
              if (!entity) return;
              var entitySize = entity.getContentSize();
              this.mode === Mode.HORIZONTAL ? this.totalLength = entitySize.width : this.mode === Mode.VERTICAL ? this.totalLength = entitySize.height : this.mode === Mode.FILLED && (this.totalLength = this.barSprite.fillRange);
            }
          },
          animatable: false
        },
        _N$totalLength: 1,
        totalLength: {
          range: [ 0, Number.MAX_VALUE ],
          tooltip: false,
          get: function() {
            return this._N$totalLength;
          },
          set: function(value) {
            this.mode === Mode.FILLED && (value = cc.clamp01(value));
            this._N$totalLength = value;
            this._updateBarStatus();
          }
        },
        progress: {
          default: 1,
          type: "Float",
          range: [ 0, 1, .1 ],
          slide: true,
          tooltip: false,
          notify: function() {
            this._updateBarStatus();
          }
        },
        reverse: {
          default: false,
          tooltip: false,
          notify: function() {
            this.barSprite && (this.barSprite.fillStart = 1 - this.barSprite.fillStart);
            this._updateBarStatus();
          },
          animatable: false
        }
      },
      statics: {
        Mode: Mode
      }
    });
    cc.ProgressBar = module.exports = ProgressBar;
  }), {
    "./CCComponent": 76
  } ],
  86: [ (function(require, module, exports) {
    var RendererInSG = cc.Class({
      extends: require("./CCSGComponent"),
      name: "cc._RendererInSG",
      ctor: function() {
        var sgNode = this._sgNode = this._createSgNode();
        sgNode.setVisible(false);
        false;
        false;
        this._plainNode = new _ccsg.Node();
        false;
      },
      __preload: function() {
        this._initSgNode();
        var sgSize;
        false;
      },
      onEnable: function() {
        false;
        this._replaceSgNode(this._sgNode);
      },
      onDisable: function() {
        this._replaceSgNode(this._plainNode);
      },
      onDestroy: function() {
        this._removeSgNode();
        var releasedByNode;
        false;
      },
      _replaceSgNode: function(sgNode) {
        false;
        var node = this.node;
        var replaced = node._sgNode;
        replaced._entity = null;
        false;
        var children = replaced.getChildren().slice();
        replaced.removeAllChildren(false);
        if (sgNode.getChildrenCount() > 0) {
          false;
          sgNode.removeAllChildren(false);
        }
        for (var i = 0, len = children.length; i < len; ++i) sgNode.addChild(children[i]);
        var parentNode = replaced.getParent();
        if (parentNode) {
          true;
          parentNode.removeChild(replaced, false);
          parentNode.addChild(sgNode);
          sgNode._arrivalOrder = replaced._arrivalOrder;
          cc.renderer.childrenOrderDirty = parentNode._reorderChildDirty = true;
        }
        node._sgNode = sgNode;
        node._sgNode._entity = node;
        node._updateSgNode();
      }
    });
    cc._RendererInSG = module.exports = RendererInSG;
  }), {
    "./CCSGComponent": 89
  } ],
  87: [ (function(require, module, exports) {
    var RendererUnderSG = cc.Class({
      extends: require("./CCSGComponent"),
      name: "cc._RendererUnderSG",
      ctor: function() {
        var sgNode = this._sgNode = this._createSgNode();
        if (sgNode) {
          false;
          sgNode.setVisible(false);
        }
      },
      __preload: function() {
        this._initSgNode();
        this._registSizeProvider();
        this._appendSgNode(this._sgNode);
      },
      onEnable: function() {
        this._sgNode && this._sgNode.setVisible(true);
      },
      onDisable: function() {
        this._sgNode && this._sgNode.setVisible(false);
      },
      onDestroy: function() {
        this.node._sizeProvider === this._sgNode && (this.node._sizeProvider = null);
        this._removeSgNode();
      },
      _appendSgNode: function(sgNode) {
        if (!sgNode) return;
        var node = this.node;
        sgNode.setColor(node._color);
        node._cascadeOpacityEnabled || sgNode.setOpacity(node._opacity);
        sgNode.setAnchorPoint(node._anchorPoint);
        sgNode.setOpacityModifyRGB(node._opacityModifyRGB);
        sgNode.setLocalZOrder(-1);
        var sgParent = node._sgNode;
        sgParent.addChild(sgNode);
      }
    });
    cc._RendererUnderSG = module.exports = RendererUnderSG;
  }), {
    "./CCSGComponent": 89
  } ],
  88: [ (function(require, module, exports) {
    require("../label/CCHtmlTextParser");
    require("../label/CCTextUtils");
    var HorizontalAlign = cc.TextAlignment;
    var VerticalAlign = cc.VerticalTextAlignment;
    function debounce(func, wait, immediate) {
      var timeout;
      return function() {
        var context = this;
        var later = function() {
          timeout = null;
          immediate || func.apply(context, arguments);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        callNow && func.apply(context, arguments);
      };
    }
    var RichText = cc.Class({
      name: "cc.RichText",
      extends: cc._RendererUnderSG,
      ctor: function() {
        this._textArray = null;
        this._labelSegments = [];
        this._labelSegmentsCache = [];
        this._linesWidth = [];
        this._resetState();
        false;
        this._updateRichTextStatus = this._updateRichText;
      },
      editor: false,
      properties: {
        string: {
          default: "<color=#00ff00>Rich</c><color=#0fffff>Text</color>",
          multiline: true,
          tooltip: false,
          notify: function() {
            this._updateRichTextStatus();
          }
        },
        horizontalAlign: {
          default: HorizontalAlign.LEFT,
          type: HorizontalAlign,
          tooltip: false,
          animatable: false,
          notify: function(oldValue) {
            if (this.horizontalAlign === oldValue) return;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        },
        fontSize: {
          default: 40,
          tooltip: false,
          notify: function(oldValue) {
            if (this.fontSize === oldValue) return;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        },
        font: {
          default: null,
          type: cc.TTFFont,
          tooltip: false,
          notify: function(oldValue) {
            if (this.font === oldValue) return;
            this._layoutDirty = true;
            (true, this.font) && this._onTTFLoaded();
            this._updateRichTextStatus();
          }
        },
        maxWidth: {
          default: 0,
          tooltip: false,
          notify: function(oldValue) {
            if (this.maxWidth === oldValue) return;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        },
        lineHeight: {
          default: 40,
          tooltip: false,
          notify: function(oldValue) {
            if (this.lineHeight === oldValue) return;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        },
        imageAtlas: {
          default: null,
          type: cc.SpriteAtlas,
          tooltip: false,
          notify: function(oldValue) {
            if (this.imageAtlas === oldValue) return;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        },
        handleTouchEvent: {
          default: true,
          tooltip: false,
          notify: function(oldValue) {
            if (this.handleTouchEvent === oldValue) return;
            this.enabledInHierarchy && (this.handleTouchEvent ? this._addEventListeners() : this._removeEventListeners());
          }
        }
      },
      statics: {
        HorizontalAlign: HorizontalAlign,
        VerticalAlign: VerticalAlign
      },
      onEnable: function() {
        this._super();
        this.handleTouchEvent && this._addEventListeners();
      },
      onDisable: function() {
        this._super();
        this.handleTouchEvent && this._removeEventListeners();
      },
      _addEventListeners: function() {
        this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
      },
      _removeEventListeners: function() {
        this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
      },
      _createSgNode: function() {
        var sgNode = new _ccsg.Node();
        sgNode.setCascadeOpacityEnabled(true);
        var self = this;
        sgNode.setColor = function() {
          self._updateLabelSegmentTextAttributes();
        };
        sgNode._setContentSize = sgNode.setContentSize;
        sgNode.setContentSize = function() {};
        return sgNode;
      },
      _updateLabelSegmentTextAttributes: function() {
        this._labelSegments.forEach(function(item) {
          this._applyTextAttribute(item);
        }.bind(this));
      },
      _initSgNode: function() {
        this._updateRichText();
        true;
        this._onTTFLoaded();
      },
      _createFontLabel: function(string) {
        return _ccsg.Label.pool.get(string, this.font, null, this.fontSize);
      },
      _getFontRawUrl: function() {
        var isAsset = this.font instanceof cc.TTFFont;
        var fntRawUrl = isAsset ? this.font.rawUrl : "";
        return fntRawUrl;
      },
      _onTTFLoaded: function() {
        var rawUrl = this._getFontRawUrl();
        if (!rawUrl) return;
        var self = this;
        var callback = function() {
          self._layoutDirty = true;
          self._updateRichText();
        };
        cc.CustomFontLoader.loadTTF(rawUrl, callback);
      },
      _measureText: function(styleIndex, string) {
        var self = this;
        var func = function(string) {
          var label;
          if (0 === self._labelSegmentsCache.length) {
            label = self._createFontLabel(string);
            self._labelSegmentsCache.push(label);
          } else {
            label = self._labelSegmentsCache[0];
            label.setString(string);
          }
          label._styleIndex = styleIndex;
          self._applyTextAttribute(label);
          var labelSize = label.getContentSize();
          return labelSize.width;
        };
        return string ? func(string) : func;
      },
      _onTouchEnded: function(event) {
        var components = this.node.getComponents(cc.Component);
        for (var i = 0; i < this._labelSegments.length; ++i) {
          var labelSegment = this._labelSegments[i];
          var clickHandler = labelSegment._clickHandler;
          if (clickHandler && this._containsTouchLocation(labelSegment, event.touch.getLocation())) {
            components.forEach((function(component) {
              component.enabledInHierarchy && component[clickHandler] && component[clickHandler](event);
            }));
            event.stopPropagation();
          }
        }
      },
      _containsTouchLocation: function(label, point) {
        var myRect = label.getBoundingBoxToWorld();
        return cc.rectContainsPoint(myRect, point);
      },
      _resetState: function() {
        var sgNode = this._sgNode;
        sgNode && sgNode.removeAllChildren();
        this._labelSegments.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;
      },
      _addLabelSegment: function(stringToken, styleIndex) {
        var labelSegment;
        if (0 === this._labelSegmentsCache.length) labelSegment = this._createFontLabel(stringToken); else {
          labelSegment = this._labelSegmentsCache.pop();
          labelSegment.setString(stringToken);
        }
        labelSegment._styleIndex = styleIndex;
        labelSegment._lineCount = this._lineCount;
        this._applyTextAttribute(labelSegment);
        labelSegment.setAnchorPoint(0, 0);
        this._sgNode.addChild(labelSegment);
        this._labelSegments.push(labelSegment);
        var size;
        false;
        return labelSegment;
      },
      _updateRichTextWithMaxWidth: function(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)) {
              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;
            }
            this._lineOffsetX += checkStringWidth;
            checkStartIndex += checkEndIndex;
          }
        }
        if (fragmentWidth > this.maxWidth) {
          var fragments = cc.TextUtils.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.getContentSize();
            this._lineOffsetX += labelSize.width;
            fragments.length > 1 && k < fragments.length - 1 && this._updateLineInfo();
          }
        } else {
          this._lineOffsetX += fragmentWidth;
          this._addLabelSegment(labelString, styleIndex);
        }
      },
      _isLastComponentCR: function(stringToken) {
        return stringToken.length - 1 === stringToken.lastIndexOf("\n");
      },
      _updateLineInfo: function() {
        this._linesWidth.push(this._lineOffsetX);
        this._lineOffsetX = 0;
        this._lineCount++;
      },
      _needsUpdateTextLayout: function(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;
          if (oldItem.style) {
            if (newItem.style) {
              if (oldItem.style.size !== newItem.style.size || oldItem.style.italic !== newItem.style.italic || oldItem.style.isImage !== newItem.style.isImage) return true;
              if (oldItem.style.isImage === newItem.style.isImage && oldItem.style.src !== newItem.style.src) return true;
            } else if (oldItem.style.size || oldItem.style.italic || oldItem.style.isImage) return true;
          } else if (newItem.style && (newItem.style.size || newItem.style.italic || newItem.style.isImage)) return true;
        }
        return false;
      },
      _onSpriteFrameLoaded: function(event, spriteFrame) {
        var newSpriteFrame;
        newSpriteFrame = spriteFrame || event.target;
        var sprite = newSpriteFrame.__sprite;
        sprite.setSpriteFrame(newSpriteFrame);
      },
      _applySpriteFrame: function(spriteFrame) {
        if (spriteFrame) if (spriteFrame.textureLoaded()) this._onSpriteFrameLoaded(null, spriteFrame); else {
          spriteFrame.once("load", this._onSpriteFrameLoaded, this);
          spriteFrame.ensureLoadTexture();
        }
      },
      _addRichTextImageElement: function(richTextElement) {
        var spriteFrameName = richTextElement.style.src;
        var spriteFrame = this.imageAtlas.getSpriteFrame(spriteFrameName);
        if (spriteFrame) {
          var sprite = new cc.Scale9Sprite();
          sprite.setAnchorPoint(0, 0);
          spriteFrame.__sprite = sprite;
          this._sgNode.addChild(sprite);
          this._labelSegments.push(sprite);
          var spriteRect = spriteFrame.getRect();
          var scaleFactor = 1;
          var spriteWidth = spriteRect.width;
          var spriteHeight = spriteRect.height;
          var expectWidth = richTextElement.style.imageWidth;
          var expectHeight = richTextElement.style.imageHeight;
          if (expectHeight > 0 && expectHeight < this.lineHeight) {
            scaleFactor = expectHeight / spriteHeight;
            spriteWidth *= scaleFactor;
            spriteHeight *= scaleFactor;
          } else {
            scaleFactor = this.lineHeight / spriteHeight;
            spriteWidth *= scaleFactor;
            spriteHeight *= scaleFactor;
          }
          expectWidth > 0 && (spriteWidth = expectWidth);
          if (this.maxWidth > 0) {
            this._lineOffsetX + spriteWidth > this.maxWidth && this._updateLineInfo();
            this._lineOffsetX += spriteWidth;
          } else {
            this._lineOffsetX += spriteWidth;
            this._lineOffsetX > this._labelWidth && (this._labelWidth = this._lineOffsetX);
          }
          this._applySpriteFrame(spriteFrame);
          sprite.setContentSize(spriteWidth, spriteHeight);
          sprite._lineCount = this._lineCount;
          richTextElement.style.event && richTextElement.style.event.click && (sprite._clickHandler = richTextElement.style.event.click);
        } else cc.warnID(4400);
      },
      _updateRichText: function() {
        if (!this.enabled) return;
        var newTextArray = cc.htmlTextParser.parse(this.string);
        if (!this._needsUpdateTextLayout(newTextArray)) {
          this._textArray = newTextArray;
          this._updateLabelSegmentTextAttributes();
          return;
        }
        this._textArray = newTextArray;
        this._resetState();
        var lastEmptyLine = false;
        var label;
        var labelSize;
        for (var i = 0; i < this._textArray.length; ++i) {
          var richTextElement = this._textArray[i];
          var text = richTextElement.text;
          if ("" === text) {
            if (richTextElement.style && richTextElement.style.newline) {
              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);
              multilineTexts.length > 1 && j < multilineTexts.length - 1 && this._updateLineInfo();
            } else {
              label = this._addLabelSegment(labelString, i);
              labelSize = label.getContentSize();
              this._lineOffsetX += labelSize.width;
              this._lineOffsetX > this._labelWidth && (this._labelWidth = this._lineOffsetX);
              multilineTexts.length > 1 && j < multilineTexts.length - 1 && this._updateLineInfo();
            }
          }
        }
        lastEmptyLine || this._linesWidth.push(this._lineOffsetX);
        this.maxWidth > 0 && (this._labelWidth = this.maxWidth);
        this._labelHeight = this._lineCount * this.lineHeight;
        this.node.setContentSize(this._labelWidth, this._labelHeight);
        this._sgNode._setContentSize(this._labelWidth, this._labelHeight);
        this._updateRichTextPosition();
        this._layoutDirty = false;
      },
      _getFirstWordLen: function(text, startIndex, textLen) {
        var character = text.charAt(startIndex);
        if (cc.TextUtils.isUnicodeCJK(character) || cc.TextUtils.isUnicodeSpace(character)) return 1;
        var len = 1;
        for (var index = startIndex + 1; index < textLen; ++index) {
          character = text.charAt(index);
          if (cc.TextUtils.isUnicodeSpace(character) || cc.TextUtils.isUnicodeCJK(character)) break;
          len++;
        }
        return len;
      },
      _updateRichTextPosition: function() {
        var nextTokenX = 0;
        var nextLineIndex = 1;
        var totalLineCount = this._lineCount;
        for (var i = 0; i < this._labelSegments.length; ++i) {
          var label = this._labelSegments[i];
          var lineCount = label._lineCount;
          if (lineCount > nextLineIndex) {
            nextTokenX = 0;
            nextLineIndex = lineCount;
          }
          var lineOffsetX = 0;
          switch (this.horizontalAlign) {
           case cc.TextAlignment.LEFT:
            lineOffsetX = 0;
            break;

           case cc.TextAlignment.CENTER:
            lineOffsetX = (this._labelWidth - this._linesWidth[lineCount - 1]) / 2;
            break;

           case cc.TextAlignment.RIGHT:
            lineOffsetX = this._labelWidth - this._linesWidth[lineCount - 1];
          }
          label.setPositionX(nextTokenX + lineOffsetX);
          var labelSize = label.getContentSize();
          var positionY = (totalLineCount - lineCount) * this.lineHeight;
          label instanceof cc.Scale9Sprite && (positionY += (this.lineHeight - label.getContentSize().height) / 2);
          label.setPositionY(positionY);
          lineCount === nextLineIndex && (nextTokenX += labelSize.width);
        }
      },
      _convertLiteralColorValue: function(color) {
        var colorValue = color.toUpperCase();
        return cc.Color[colorValue] ? cc.Color[colorValue] : cc.hexToColor(color);
      },
      _applyTextAttribute: function(label) {
        if (label instanceof cc.Scale9Sprite) return;
        var index = label._styleIndex;
        label.setLineHeight(this.lineHeight);
        label.setVerticalAlign(VerticalAlign.CENTER);
        var textStyle = null;
        this._textArray[index] && (textStyle = this._textArray[index].style);
        textStyle && textStyle.color ? label.setColor(this._convertLiteralColorValue(textStyle.color)) : label.setColor(this.node.color);
        textStyle && textStyle.bold ? label.enableBold(true) : label.enableBold(false);
        textStyle && textStyle.italic ? label.enableItalics(true) : label.enableItalics(false);
        textStyle && textStyle.underline ? label.enableUnderline(true) : label.enableUnderline(false);
        if (textStyle && textStyle.outline) {
          label.setOutlined(true);
          label.setOutlineColor(this._convertLiteralColorValue(textStyle.outline.color));
          label.setOutlineWidth(textStyle.outline.width);
          label.setMargin(textStyle.outline.width);
        } else {
          label.setOutlined(false);
          label.setMargin(0);
        }
        textStyle && textStyle.size ? label.setFontSize(textStyle.size) : label.setFontSize(this.fontSize);
        textStyle && textStyle.event && textStyle.event.click && (label._clickHandler = textStyle.event.click);
      },
      onDestroy: function() {
        this._super();
        for (var i = 0; i < this._labelSegments.length; ++i) {
          this._labelSegments[i].removeFromParent(true);
          _ccsg.Label.pool.put(this._labelSegments[i]);
        }
        this._resetState();
      }
    });
    cc.RichText = module.exports = RichText;
  }), {
    "../label/CCHtmlTextParser": 125,
    "../label/CCTextUtils": 129
  } ],
  89: [ (function(require, module, exports) {
    var SceneGraphHelper = require("../utils/scene-graph-helper");
    var SGComponent = cc.Class({
      extends: require("./CCComponent"),
      name: "cc._SGComponent",
      editor: false,
      properties: {
        _sgNode: {
          default: null,
          serializable: false
        }
      },
      _createSgNode: null,
      _initSgNode: null,
      _removeSgNode: SceneGraphHelper.removeSgNode,
      _registSizeProvider: function() {
        if (this.node._sizeProvider) {
          var name;
          false;
        } else this.node._sizeProvider = this._sgNode;
      }
    });
    cc._SGComponent = module.exports = SGComponent;
  }), {
    "../utils/scene-graph-helper": 228,
    "./CCComponent": 76
  } ],
  90: [ (function(require, module, exports) {
    var GETTINGSHORTERFACTOR = 20;
    var Direction = cc.Enum({
      HORIZONTAL: 0,
      VERTICAL: 1
    });
    var Scrollbar = cc.Class({
      name: "cc.Scrollbar",
      extends: require("./CCComponent"),
      editor: false,
      properties: {
        _scrollView: null,
        _touching: false,
        _autoHideRemainingTime: {
          default: 0,
          serializable: false
        },
        _opacity: 255,
        handle: {
          default: null,
          type: cc.Sprite,
          tooltip: false,
          notify: function() {
            this._onScroll(cc.p(0, 0));
          },
          animatable: false
        },
        direction: {
          default: Direction.HORIZONTAL,
          type: Direction,
          tooltip: false,
          notify: function() {
            this._onScroll(cc.p(0, 0));
          },
          animatable: false
        },
        enableAutoHide: {
          default: true,
          animatable: false,
          tooltip: false
        },
        autoHideTime: {
          default: 1,
          animatable: false,
          tooltip: false
        }
      },
      statics: {
        Direction: Direction
      },
      setTargetScrollView: function(scrollView) {
        this._scrollView = scrollView;
      },
      _convertToScrollViewSpace: function(content) {
        var worldSpacePos = content.convertToWorldSpace(cc.p(0, 0));
        var scrollViewSpacePos = this._scrollView.node.convertToNodeSpace(worldSpacePos);
        return scrollViewSpacePos;
      },
      _setOpacity: function(opacity) {
        this.handle && this.node.setOpacity(opacity);
      },
      _onScroll: function(outOfBoundary) {
        if (this._scrollView) {
          var content = this._scrollView.content;
          if (content) {
            var contentSize = content.getContentSize();
            var scrollViewSize = this._scrollView.node.getContentSize();
            var handleNodeSize = this.node.getContentSize();
            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;
            if (this.direction === Direction.HORIZONTAL) {
              contentMeasure = contentSize.width;
              scrollViewMeasure = scrollViewSize.width;
              handleNodeMeasure = handleNodeSize.width;
              outOfBoundaryValue = outOfBoundary.x;
              contentPosition = -this._convertToScrollViewSpace(content).x;
            } else if (this.direction === Direction.VERTICAL) {
              contentMeasure = contentSize.height;
              scrollViewMeasure = scrollViewSize.height;
              handleNodeMeasure = handleNodeSize.height;
              outOfBoundaryValue = outOfBoundary.y;
              contentPosition = -this._convertToScrollViewSpace(content).y;
            }
            var length = this._calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundaryValue);
            var position = this._calculatePosition(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundaryValue, length);
            this._updateLength(length);
            this._updateHanlderPosition(position);
          }
        }
      },
      _updateHanlderPosition: function(position) {
        if (this.handle) {
          var oldPosition = this._fixupHandlerPosition();
          this.handle.node.setPosition(cc.pAdd(position, oldPosition));
        }
      },
      _fixupHandlerPosition: function() {
        var barSize = this.node.getContentSize();
        var barAnchor = this.node.getAnchorPoint();
        var handleSize = this.handle.node.getContentSize();
        var handleParent = this.handle.node.parent;
        var leftBottomWorldPosition = this.node.convertToWorldSpaceAR(cc.p(-barSize.width * barAnchor.x, -barSize.height * barAnchor.y));
        var fixupPosition = handleParent.convertToNodeSpaceAR(leftBottomWorldPosition);
        this.direction === Direction.HORIZONTAL ? fixupPosition = cc.pAdd(fixupPosition, cc.p(0, (barSize.height - handleSize.height) / 2)) : this.direction === Direction.VERTICAL && (fixupPosition = cc.pAdd(fixupPosition, cc.p((barSize.width - handleSize.width) / 2, 0)));
        this.handle.node.setPosition(fixupPosition);
        return fixupPosition;
      },
      _onTouchBegan: function() {
        if (!this.enableAutoHide) return;
        this._touching = true;
      },
      _conditionalDisableScrollBar: function(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;
      },
      _onTouchEnded: function() {
        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.getContentSize();
            var scrollViewSize = this._scrollView.node.getContentSize();
            if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) return;
          }
        }
        this._autoHideRemainingTime = this.autoHideTime;
      },
      _calculateLength: function(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) {
        var denominatorValue = contentMeasure;
        outOfBoundary && (denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTINGSHORTERFACTOR);
        var lengthRation = scrollViewMeasure / denominatorValue;
        return handleNodeMeasure * lengthRation;
      },
      _calculatePosition: function(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) {
        var denominatorValue = contentMeasure - scrollViewMeasure;
        outOfBoundary && (denominatorValue += Math.abs(outOfBoundary));
        var positionRatio = 0;
        if (denominatorValue) {
          positionRatio = contentPosition / denominatorValue;
          positionRatio = cc.clamp01(positionRatio);
        }
        var position = (handleNodeMeasure - actualLenth) * positionRatio;
        return this.direction === Direction.VERTICAL ? cc.p(0, position) : cc.p(position, 0);
      },
      _updateLength: function(length) {
        if (this.handle) {
          var handleNode = this.handle.node;
          var handleNodeSize = handleNode.getContentSize();
          handleNode.setAnchorPoint(cc.p(0, 0));
          this.direction === Direction.HORIZONTAL ? handleNode.setContentSize(length, handleNodeSize.height) : handleNode.setContentSize(handleNodeSize.width, length);
        }
      },
      _processAutoHide: function(deltaTime) {
        if (!this.enableAutoHide || this._autoHideRemainingTime <= 0) return;
        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);
        }
      },
      start: function() {
        this.enableAutoHide && this._setOpacity(0);
      },
      hide: function() {
        this._autoHideRemainingTime = 0;
        this._setOpacity(0);
      },
      show: function() {
        this._autoHideRemainingTime = this.autoHideTime;
        this._setOpacity(this._opacity);
      },
      update: function(dt) {
        this._processAutoHide(dt);
      }
    });
    cc.Scrollbar = module.exports = Scrollbar;
  }), {
    "./CCComponent": 76
  } ],
  91: [ (function(require, module, exports) {
    var NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5;
    var OUT_OF_BOUNDARY_BREAKING_FACTOR = .05;
    var EPSILON = 1e-4;
    var MOVEMENT_FACTOR = .7;
    var quintEaseOut = function(time) {
      time -= 1;
      return time * time * time * time * time + 1;
    };
    var getTimeInMilliseconds = function() {
      var currentTime = new Date();
      return currentTime.getMilliseconds();
    };
    var EventType = cc.Enum({
      SCROLL_TO_TOP: 0,
      SCROLL_TO_BOTTOM: 1,
      SCROLL_TO_LEFT: 2,
      SCROLL_TO_RIGHT: 3,
      SCROLLING: 4,
      BOUNCE_TOP: 5,
      BOUNCE_BOTTOM: 6,
      BOUNCE_LEFT: 7,
      BOUNCE_RIGHT: 8,
      SCROLL_ENDED: 9,
      TOUCH_UP: 10,
      AUTOSCROLL_ENDED_WITH_THRESHOLD: 11,
      SCROLL_BEGAN: 12
    });
    var eventMap = {
      "scroll-to-top": EventType.SCROLL_TO_TOP,
      "scroll-to-bottom": EventType.SCROLL_TO_BOTTOM,
      "scroll-to-left": EventType.SCROLL_TO_LEFT,
      "scroll-to-right": EventType.SCROLL_TO_RIGHT,
      scrolling: EventType.SCROLLING,
      "bounce-bottom": EventType.BOUNCE_BOTTOM,
      "bounce-left": EventType.BOUNCE_LEFT,
      "bounce-right": EventType.BOUNCE_RIGHT,
      "bounce-top": EventType.BOUNCE_TOP,
      "scroll-ended": EventType.SCROLL_ENDED,
      "touch-up": EventType.TOUCH_UP,
      "scroll-ended-with-threshold": EventType.AUTOSCROLL_ENDED_WITH_THRESHOLD,
      "scroll-began": EventType.SCROLL_BEGAN
    };
    var ScrollView = cc.Class({
      name: "cc.ScrollView",
      extends: require("./CCViewGroup"),
      editor: false,
      ctor: function() {
        this._topBoundary = 0;
        this._bottomBoundary = 0;
        this._leftBoundary = 0;
        this._rightBoundary = 0;
        this._touchMoveDisplacements = [];
        this._touchMoveTimeDeltas = [];
        this._touchMovePreviousTimestamp = 0;
        this._touchMoved = false;
        this._autoScrolling = false;
        this._autoScrollAttenuate = false;
        this._autoScrollStartPosition = cc.p(0, 0);
        this._autoScrollTargetDelta = cc.p(0, 0);
        this._autoScrollTotalTime = 0;
        this._autoScrollAccumulatedTime = 0;
        this._autoScrollCurrentlyOutOfBoundary = false;
        this._autoScrollBraking = false;
        this._autoScrollBrakingStartPosition = cc.p(0, 0);
        this._outOfBoundaryAmount = cc.p(0, 0);
        this._outOfBoundaryAmountDirty = true;
        this._stopMouseWheel = false;
        this._mouseWheelEventElapsedTime = 0;
        this._isScrollEndedWithThresholdEventFired = false;
        this._scrollEventEmitMask = 0;
        this._isBouncing = false;
        this._scrolling = false;
      },
      properties: {
        content: {
          default: void 0,
          type: cc.Node,
          tooltip: false
        },
        horizontal: {
          default: true,
          animatable: false,
          tooltip: false
        },
        vertical: {
          default: true,
          animatable: false,
          tooltip: false
        },
        inertia: {
          default: true,
          tooltip: false
        },
        brake: {
          default: .5,
          type: "Float",
          range: [ 0, 1, .1 ],
          tooltip: false
        },
        elastic: {
          default: true,
          animatable: false,
          tooltip: false
        },
        bounceDuration: {
          default: 1,
          range: [ 0, 10 ],
          tooltip: false
        },
        horizontalScrollBar: {
          default: void 0,
          type: cc.Scrollbar,
          tooltip: false,
          notify: function() {
            if (this.horizontalScrollBar) {
              this.horizontalScrollBar.setTargetScrollView(this);
              this._updateScrollBar(0);
            }
          },
          animatable: false
        },
        verticalScrollBar: {
          default: void 0,
          type: cc.Scrollbar,
          tooltip: false,
          notify: function() {
            if (this.verticalScrollBar) {
              this.verticalScrollBar.setTargetScrollView(this);
              this._updateScrollBar(0);
            }
          },
          animatable: false
        },
        scrollEvents: {
          default: [],
          type: cc.Component.EventHandler,
          tooltip: false
        },
        cancelInnerEvents: {
          default: true,
          animatable: false,
          tooltip: false
        }
      },
      statics: {
        EventType: EventType
      },
      scrollToBottom: function(timeInSecond, attenuated) {
        var moveDelta = this._calculateMovePercentDelta({
          anchor: cc.p(0, 0),
          applyToHorizontal: false,
          applyToVertical: true
        });
        timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta, true);
      },
      scrollToTop: function(timeInSecond, attenuated) {
        var moveDelta = this._calculateMovePercentDelta({
          anchor: cc.p(0, 1),
          applyToHorizontal: false,
          applyToVertical: true
        });
        timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta);
      },
      scrollToLeft: function(timeInSecond, attenuated) {
        var moveDelta = this._calculateMovePercentDelta({
          anchor: cc.p(0, 0),
          applyToHorizontal: true,
          applyToVertical: false
        });
        timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta);
      },
      scrollToRight: function(timeInSecond, attenuated) {
        var moveDelta = this._calculateMovePercentDelta({
          anchor: cc.p(1, 0),
          applyToHorizontal: true,
          applyToVertical: false
        });
        timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta);
      },
      scrollToTopLeft: function(timeInSecond, attenuated) {
        var moveDelta = this._calculateMovePercentDelta({
          anchor: cc.p(0, 1),
          applyToHorizontal: true,
          applyToVertical: true
        });
        timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta);
      },
      scrollToTopRight: function(timeInSecond, attenuated) {
        var moveDelta = this._calculateMovePercentDelta({
          anchor: cc.p(1, 1),
          applyToHorizontal: true,
          applyToVertical: true
        });
        timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta);
      },
      scrollToBottomLeft: function(timeInSecond, attenuated) {
        var moveDelta = this._calculateMovePercentDelta({
          anchor: cc.p(0, 0),
          applyToHorizontal: true,
          applyToVertical: true
        });
        timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta);
      },
      scrollToBottomRight: function(timeInSecond, attenuated) {
        var moveDelta = this._calculateMovePercentDelta({
          anchor: cc.p(1, 0),
          applyToHorizontal: true,
          applyToVertical: true
        });
        timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta);
      },
      scrollToOffset: function(offset, timeInSecond, attenuated) {
        var maxScrollOffset = this.getMaxScrollOffset();
        var anchor = cc.p(0, 0);
        0 === maxScrollOffset.x ? anchor.x = 0 : anchor.x = offset.x / maxScrollOffset.x;
        0 === maxScrollOffset.y ? anchor.y = 1 : anchor.y = (maxScrollOffset.y - offset.y) / maxScrollOffset.y;
        this.scrollTo(anchor, timeInSecond, attenuated);
      },
      getScrollOffset: function() {
        var topDelta = this._getContentTopBoundary() - this._topBoundary;
        var leftDeta = this._getContentLeftBoundary() - this._leftBoundary;
        return cc.p(leftDeta, topDelta);
      },
      getMaxScrollOffset: function() {
        var scrollSize = this.node.getContentSize();
        var contentSize = this.content.getContentSize();
        var horizontalMaximizeOffset = contentSize.width - scrollSize.width;
        var verticalMaximizeOffset = contentSize.height - scrollSize.height;
        horizontalMaximizeOffset = horizontalMaximizeOffset >= 0 ? horizontalMaximizeOffset : 0;
        verticalMaximizeOffset = verticalMaximizeOffset >= 0 ? verticalMaximizeOffset : 0;
        return cc.p(horizontalMaximizeOffset, verticalMaximizeOffset);
      },
      scrollToPercentHorizontal: function(percent, timeInSecond, attenuated) {
        var moveDelta = this._calculateMovePercentDelta({
          anchor: cc.p(percent, 0),
          applyToHorizontal: true,
          applyToVertical: false
        });
        timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta);
      },
      scrollTo: function(anchor, timeInSecond, attenuated) {
        var moveDelta = this._calculateMovePercentDelta({
          anchor: anchor,
          applyToHorizontal: true,
          applyToVertical: true
        });
        timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta);
      },
      scrollToPercentVertical: function(percent, timeInSecond, attenuated) {
        var moveDelta = this._calculateMovePercentDelta({
          anchor: cc.p(0, percent),
          applyToHorizontal: false,
          applyToVertical: true
        });
        timeInSecond ? this._startAutoScroll(moveDelta, timeInSecond, false !== attenuated) : this._moveContent(moveDelta);
      },
      stopAutoScroll: function() {
        this._autoScrolling = false;
        this._autoScrollAccumulatedTime = this._autoScrollTotalTime;
      },
      setContentPosition: function(position) {
        if (cc.pFuzzyEqual(position, this.getContentPosition(), EPSILON)) return;
        this.content.setPosition(position);
        this._outOfBoundaryAmountDirty = true;
      },
      getContentPosition: function() {
        return this.content.getPosition();
      },
      isScrolling: function() {
        return this._scrolling;
      },
      isAutoScrolling: function() {
        return this._autoScrolling;
      },
      _registerEvent: function() {
        this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this, true);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this, true);
        this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this, true);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true);
        this.node.on(cc.Node.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true);
      },
      _unregisterEvent: function() {
        this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this, true);
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this, true);
        this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this, true);
        this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true);
        this.node.off(cc.Node.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true);
      },
      _onMouseWheel: function(event, captureListeners) {
        if (!this.enabledInHierarchy) return;
        if (this._hasNestedViewGroup(event, captureListeners)) return;
        var deltaMove = cc.p(0, 0);
        var wheelPrecision = -.1;
        false;
        this.vertical ? deltaMove = cc.p(0, event.getScrollY() * wheelPrecision) : this.horizontal && (deltaMove = cc.p(event.getScrollY() * wheelPrecision, 0));
        this._mouseWheelEventElapsedTime = 0;
        this._processDeltaMove(deltaMove);
        if (!this._stopMouseWheel) {
          this._handlePressLogic();
          this.schedule(this._checkMouseWheel, 1 / 60);
          this._stopMouseWheel = true;
        }
        this._stopPropagationIfTargetIsMe(event);
      },
      _checkMouseWheel: function(dt) {
        var currentOutOfBoundary = this._getHowMuchOutOfBoundary();
        var maxElapsedTime = .1;
        if (!cc.pFuzzyEqual(currentOutOfBoundary, cc.p(0, 0), EPSILON)) {
          this._processInertiaScroll();
          this.unschedule(this._checkMouseWheel);
          this._stopMouseWheel = false;
          return;
        }
        this._mouseWheelEventElapsedTime += dt;
        if (this._mouseWheelEventElapsedTime > maxElapsedTime) {
          this._onScrollBarTouchEnded();
          this.unschedule(this._checkMouseWheel);
          this._stopMouseWheel = false;
        }
      },
      _calculateMovePercentDelta: function(options) {
        var anchor = options.anchor;
        var applyToHorizontal = options.applyToHorizontal;
        var applyToVertical = options.applyToVertical;
        this._calculateBoundary();
        anchor = cc.pClamp(anchor, cc.p(0, 0), cc.p(1, 1));
        var scrollSize = this.node.getContentSize();
        var contentSize = this.content.getContentSize();
        var bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary;
        bottomDeta = -bottomDeta;
        var leftDeta = this._getContentLeftBoundary() - this._leftBoundary;
        leftDeta = -leftDeta;
        var moveDelta = cc.p(0, 0);
        var totalScrollDelta = 0;
        if (applyToHorizontal) {
          totalScrollDelta = contentSize.width - scrollSize.width;
          moveDelta.x = leftDeta - totalScrollDelta * anchor.x;
        }
        if (applyToVertical) {
          totalScrollDelta = contentSize.height - scrollSize.height;
          moveDelta.y = bottomDeta - totalScrollDelta * anchor.y;
        }
        return moveDelta;
      },
      _moveContentToTopLeft: function(scrollViewSize) {
        var contentSize = this.content.getContentSize();
        var bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary;
        bottomDeta = -bottomDeta;
        var moveDelta = cc.p(0, 0);
        var totalScrollDelta = 0;
        var leftDeta = this._getContentLeftBoundary() - this._leftBoundary;
        leftDeta = -leftDeta;
        if (contentSize.height < scrollViewSize.height) {
          totalScrollDelta = contentSize.height - scrollViewSize.height;
          moveDelta.y = bottomDeta - totalScrollDelta;
          this.verticalScrollBar && this.verticalScrollBar.hide();
        } else this.verticalScrollBar && this.verticalScrollBar.show();
        if (contentSize.width < scrollViewSize.width) {
          totalScrollDelta = contentSize.width - scrollViewSize.width;
          moveDelta.x = leftDeta;
          this.horizontalScrollBar && this.horizontalScrollBar.hide();
        } else this.horizontalScrollBar && this.horizontalScrollBar.show();
        this._moveContent(moveDelta);
        this._adjustContentOutOfBoundary();
      },
      _calculateBoundary: function() {
        if (this.content) {
          var layout = this.content.getComponent(cc.Layout);
          layout && layout.enabledInHierarchy && layout.updateLayout();
          var scrollViewSize = this.node.getContentSize();
          var leftBottomPosition = this._convertToContentParentSpace(cc.p(0, 0));
          this._leftBoundary = leftBottomPosition.x;
          this._bottomBoundary = leftBottomPosition.y;
          var topRightPosition = this._convertToContentParentSpace(cc.p(scrollViewSize.width, scrollViewSize.height));
          this._rightBoundary = topRightPosition.x;
          this._topBoundary = topRightPosition.y;
          true;
          this._moveContentToTopLeft(scrollViewSize);
        }
      },
      _convertToContentParentSpace: function(position) {
        var scrollViewPositionInWorldSpace = this.node.convertToWorldSpace(position);
        var contentParent = this.content.parent;
        return contentParent.convertToNodeSpaceAR(scrollViewPositionInWorldSpace);
      },
      _hasNestedViewGroup: function(event, captureListeners) {
        if (event.eventPhase !== cc.Event.CAPTURING_PHASE) return;
        if (captureListeners) for (var i = 0; i < captureListeners.length; ++i) {
          var item = captureListeners[i];
          if (this.node === item) {
            if (event.target.getComponent(cc.ViewGroup)) return true;
            return false;
          }
          if (item.getComponent(cc.ViewGroup)) return true;
        }
        return false;
      },
      _stopPropagationIfTargetIsMe: function(event) {
        event.eventPhase === cc.Event.AT_TARGET && event.target === this.node && event.stopPropagation();
      },
      _onTouchBegan: function(event, captureListeners) {
        if (!this.enabledInHierarchy) return;
        if (this._hasNestedViewGroup(event, captureListeners)) return;
        var touch = event.touch;
        this.content && this._handlePressLogic(touch);
        this._touchMoved = false;
        this._stopPropagationIfTargetIsMe(event);
      },
      _onTouchMoved: function(event, captureListeners) {
        if (!this.enabledInHierarchy) return;
        if (this._hasNestedViewGroup(event, captureListeners)) return;
        var touch = event.touch;
        this.content && this._handleMoveLogic(touch);
        if (!this.cancelInnerEvents) return;
        var deltaMove = cc.pSub(touch.getLocation(), touch.getStartLocation());
        if (cc.pLength(deltaMove) > 7 && !this._touchMoved && event.target !== this.node) {
          var cancelEvent = new cc.Event.EventTouch(event.getTouches(), event.bubbles);
          cancelEvent.type = cc.Node.EventType.TOUCH_CANCEL;
          cancelEvent.touch = event.touch;
          cancelEvent.simulate = true;
          event.target.dispatchEvent(cancelEvent);
          this._touchMoved = true;
        }
        this._stopPropagationIfTargetIsMe(event);
      },
      _onTouchEnded: function(event, captureListeners) {
        if (!this.enabledInHierarchy) return;
        if (this._hasNestedViewGroup(event, captureListeners)) return;
        this._dispatchEvent("touch-up");
        var touch = event.touch;
        this.content && this._handleReleaseLogic(touch);
        this._touchMoved ? event.stopPropagation() : this._stopPropagationIfTargetIsMe(event);
      },
      _onTouchCancelled: function(event, captureListeners) {
        if (!this.enabledInHierarchy) return;
        if (this._hasNestedViewGroup(event, captureListeners)) return;
        if (!event.simulate) {
          var touch = event.touch;
          this.content && this._handleReleaseLogic(touch);
        }
        this._stopPropagationIfTargetIsMe(event);
      },
      _processDeltaMove: function(deltaMove) {
        this._scrollChildren(deltaMove);
        this._gatherTouchMove(deltaMove);
      },
      _handleMoveLogic: function(touch) {
        var deltaMove = touch.getDelta();
        this._processDeltaMove(deltaMove);
      },
      _scrollChildren: function(deltaMove) {
        deltaMove = this._clampDelta(deltaMove);
        var realMove = deltaMove;
        var outOfBoundary;
        if (this.elastic) {
          outOfBoundary = this._getHowMuchOutOfBoundary();
          realMove.x *= 0 === outOfBoundary.x ? 1 : .5;
          realMove.y *= 0 === outOfBoundary.y ? 1 : .5;
        }
        if (!this.elastic) {
          outOfBoundary = this._getHowMuchOutOfBoundary(realMove);
          realMove = cc.pAdd(realMove, outOfBoundary);
        }
        var scrollEventType = -1;
        if (realMove.y > 0) {
          var icBottomPos = this.content.y - this.content.anchorY * this.content.height;
          icBottomPos + realMove.y > this._bottomBoundary && (scrollEventType = "scroll-to-bottom");
        } else if (realMove.y < 0) {
          var icTopPos = this.content.y - this.content.anchorY * this.content.height + this.content.height;
          icTopPos + realMove.y <= this._topBoundary && (scrollEventType = "scroll-to-top");
        } else if (realMove.x < 0) {
          var icRightPos = this.content.x - this.content.anchorX * this.content.width + this.content.width;
          icRightPos + realMove.x <= this._rightBoundary && (scrollEventType = "scroll-to-right");
        } else if (realMove.x > 0) {
          var icLeftPos = this.content.x - this.content.anchorX * this.content.width;
          icLeftPos + realMove.x >= this._leftBoundary && (scrollEventType = "scroll-to-left");
        }
        this._moveContent(realMove, false);
        if (0 !== realMove.x || 0 !== realMove.y) {
          if (!this._scrolling) {
            this._scrolling = true;
            this._dispatchEvent("scroll-began");
          }
          this._dispatchEvent("scrolling");
        }
        -1 !== scrollEventType && this._dispatchEvent(scrollEventType);
      },
      _handlePressLogic: function() {
        this._autoScrolling && this._dispatchEvent("scroll-ended");
        this._autoScrolling = false;
        this._isBouncing = false;
        this._touchMovePreviousTimestamp = getTimeInMilliseconds();
        this._touchMoveDisplacements.length = 0;
        this._touchMoveTimeDeltas.length = 0;
        this._onScrollBarTouchBegan();
      },
      _clampDelta: function(delta) {
        var contentSize = this.content.getContentSize();
        var scrollViewSize = this.node.getContentSize();
        contentSize.width < scrollViewSize.width && (delta.x = 0);
        contentSize.height < scrollViewSize.height && (delta.y = 0);
        return delta;
      },
      _gatherTouchMove: function(delta) {
        delta = this._clampDelta(delta);
        while (this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) {
          this._touchMoveDisplacements.shift();
          this._touchMoveTimeDeltas.shift();
        }
        this._touchMoveDisplacements.push(delta);
        var timeStamp = getTimeInMilliseconds();
        this._touchMoveTimeDeltas.push((timeStamp - this._touchMovePreviousTimestamp) / 1e3);
        this._touchMovePreviousTimestamp = timeStamp;
      },
      _startBounceBackIfNeeded: function() {
        if (!this.elastic) return false;
        var bounceBackAmount = this._getHowMuchOutOfBoundary();
        bounceBackAmount = this._clampDelta(bounceBackAmount);
        if (cc.pFuzzyEqual(bounceBackAmount, cc.p(0, 0), EPSILON)) return false;
        var bounceBackTime = Math.max(this.bounceDuration, 0);
        this._startAutoScroll(bounceBackAmount, bounceBackTime, true);
        if (!this._isBouncing) {
          bounceBackAmount.y > 0 && this._dispatchEvent("bounce-top");
          bounceBackAmount.y < 0 && this._dispatchEvent("bounce-bottom");
          bounceBackAmount.x > 0 && this._dispatchEvent("bounce-right");
          bounceBackAmount.x < 0 && this._dispatchEvent("bounce-left");
          this._isBouncing = true;
        }
        return true;
      },
      _processInertiaScroll: function() {
        var bounceBackStarted = this._startBounceBackIfNeeded();
        if (!bounceBackStarted && this.inertia) {
          var touchMoveVelocity = this._calculateTouchMoveVelocity();
          !cc.pFuzzyEqual(touchMoveVelocity, cc.p(0, 0), EPSILON) && this.brake < 1 && this._startInertiaScroll(touchMoveVelocity);
        }
        this._onScrollBarTouchEnded();
      },
      _handleReleaseLogic: function(touch) {
        var delta = touch.getDelta();
        this._gatherTouchMove(delta);
        this._processInertiaScroll();
        if (this._scrolling) {
          this._scrolling = false;
          this._autoScrolling || this._dispatchEvent("scroll-ended");
        }
      },
      _isOutOfBoundary: function() {
        var outOfBoundary = this._getHowMuchOutOfBoundary();
        return !cc.pFuzzyEqual(outOfBoundary, cc.p(0, 0), EPSILON);
      },
      _isNecessaryAutoScrollBrake: function() {
        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;
      },
      getScrollEndedEventTiming: function() {
        return EPSILON;
      },
      _processAutoScrolling: function(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);
        this._autoScrollAttenuate && (percentage = quintEaseOut(percentage));
        var newPosition = cc.pAdd(this._autoScrollStartPosition, cc.pMult(this._autoScrollTargetDelta, percentage));
        var reachedEnd = Math.abs(percentage - 1) <= EPSILON;
        var fireEvent = Math.abs(percentage - 1) <= this.getScrollEndedEventTiming();
        if (fireEvent && !this._isScrollEndedWithThresholdEventFired) {
          this._dispatchEvent("scroll-ended-with-threshold");
          this._isScrollEndedWithThresholdEventFired = true;
        }
        if (this.elastic) {
          var brakeOffsetPosition = cc.pSub(newPosition, this._autoScrollBrakingStartPosition);
          isAutoScrollBrake && (brakeOffsetPosition = cc.pMult(brakeOffsetPosition, brakingFactor));
          newPosition = cc.pAdd(this._autoScrollBrakingStartPosition, brakeOffsetPosition);
        } else {
          var moveDelta = cc.pSub(newPosition, this.getContentPosition());
          var outOfBoundary = this._getHowMuchOutOfBoundary(moveDelta);
          if (!cc.pFuzzyEqual(outOfBoundary, cc.p(0, 0), EPSILON)) {
            newPosition = cc.pAdd(newPosition, outOfBoundary);
            reachedEnd = true;
          }
        }
        reachedEnd && (this._autoScrolling = false);
        var contentPos = cc.pSub(newPosition, this.getContentPosition());
        this._moveContent(contentPos, reachedEnd);
        this._dispatchEvent("scrolling");
        if (!this._autoScrolling) {
          this._isBouncing = false;
          this._dispatchEvent("scroll-ended");
        }
      },
      _startInertiaScroll: function(touchMoveVelocity) {
        var inertiaTotalMovement = cc.pMult(touchMoveVelocity, MOVEMENT_FACTOR);
        this._startAttenuatingAutoScroll(inertiaTotalMovement, touchMoveVelocity);
      },
      _calculateAttenuatedFactor: function(distance) {
        if (this.brake <= 0) return 1 - this.brake;
        var attenuatedFactor = (1 - this.brake) * (1 / (1 + 14e-6 * distance + distance * distance * 8e-9));
        return attenuatedFactor;
      },
      _startAttenuatingAutoScroll: function(deltaMove, initialVelocity) {
        var time = this._calculateAutoScrollTimeByInitalSpeed(cc.pLength(initialVelocity));
        var targetDelta = cc.pNormalize(deltaMove);
        var contentSize = this.content.getContentSize();
        var scrollviewSize = this.node.getContentSize();
        var totalMoveWidth = contentSize.width - scrollviewSize.width;
        var totalMoveHeight = contentSize.height - scrollviewSize.height;
        var attenuatedFactorX = this._calculateAttenuatedFactor(totalMoveWidth);
        var attenuatedFactorY = this._calculateAttenuatedFactor(totalMoveHeight);
        targetDelta = cc.p(targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX, targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake));
        var originalMoveLength = cc.pLength(deltaMove);
        var factor = cc.pLength(targetDelta) / originalMoveLength;
        targetDelta = cc.pAdd(targetDelta, deltaMove);
        if (this.brake > 0 && factor > 7) {
          factor = Math.sqrt(factor);
          targetDelta = cc.pAdd(cc.pMult(deltaMove, factor), deltaMove);
        }
        if (this.brake > 0 && factor > 3) {
          factor = 3;
          time *= factor;
        }
        0 === this.brake && factor > 1 && (time *= factor);
        this._startAutoScroll(targetDelta, time, true);
      },
      _calculateAutoScrollTimeByInitalSpeed: function(initalSpeed) {
        var time = Math.sqrt(Math.sqrt(initalSpeed / 5));
        return time;
      },
      _startAutoScroll: function(deltaMove, timeInSecond, attenuated) {
        var adjustedDeltaMove = this._flattenVectorByDirection(deltaMove);
        this._autoScrolling = true;
        this._autoScrollTargetDelta = adjustedDeltaMove;
        this._autoScrollAttenuate = attenuated;
        this._autoScrollStartPosition = this.getContentPosition();
        this._autoScrollTotalTime = timeInSecond;
        this._autoScrollAccumulatedTime = 0;
        this._autoScrollBraking = false;
        this._isScrollEndedWithThresholdEventFired = false;
        this._autoScrollBrakingStartPosition = cc.p(0, 0);
        var currentOutOfBoundary = this._getHowMuchOutOfBoundary();
        if (!cc.pFuzzyEqual(currentOutOfBoundary, cc.p(0, 0), EPSILON)) {
          this._autoScrollCurrentlyOutOfBoundary = true;
          var afterOutOfBoundary = this._getHowMuchOutOfBoundary(adjustedDeltaMove);
          (currentOutOfBoundary.x * afterOutOfBoundary.x > 0 || currentOutOfBoundary.y * afterOutOfBoundary.y > 0) && (this._autoScrollBraking = true);
        }
      },
      _calculateTouchMoveVelocity: function() {
        var totalTime = 0;
        totalTime = this._touchMoveTimeDeltas.reduce((function(a, b) {
          return a + b;
        }), totalTime);
        if (totalTime <= 0 || totalTime >= .5) return cc.p(0, 0);
        var totalMovement = cc.p(0, 0);
        totalMovement = this._touchMoveDisplacements.reduce((function(a, b) {
          return cc.pAdd(a, b);
        }), totalMovement);
        return cc.p(totalMovement.x * (1 - this.brake) / totalTime, totalMovement.y * (1 - this.brake) / totalTime);
      },
      _flattenVectorByDirection: function(vector) {
        var result = vector;
        result.x = this.horizontal ? result.x : 0;
        result.y = this.vertical ? result.y : 0;
        return result;
      },
      _moveContent: function(deltaMove, canStartBounceBack) {
        var adjustedMove = this._flattenVectorByDirection(deltaMove);
        var newPosition = cc.pAdd(this.getContentPosition(), adjustedMove);
        this.setContentPosition(newPosition);
        var outOfBoundary = this._getHowMuchOutOfBoundary();
        this._updateScrollBar(outOfBoundary);
        this.elastic && canStartBounceBack && this._startBounceBackIfNeeded();
      },
      _getContentLeftBoundary: function() {
        var contentPos = this.getContentPosition();
        var leftBoundary = contentPos.x - this.content.getAnchorPoint().x * this.content.getContentSize().width;
        return leftBoundary;
      },
      _getContentRightBoundary: function() {
        var contentSize = this.content.getContentSize();
        return this._getContentLeftBoundary() + contentSize.width;
      },
      _getContentTopBoundary: function() {
        var contentSize = this.content.getContentSize();
        return this._getContentBottomBoundary() + contentSize.height;
      },
      _getContentBottomBoundary: function() {
        var contentPos = this.getContentPosition();
        var bottomBoundary = contentPos.y - this.content.getAnchorPoint().y * this.content.getContentSize().height;
        return bottomBoundary;
      },
      _getHowMuchOutOfBoundary: function(addition) {
        addition = addition || cc.p(0, 0);
        if (cc.pFuzzyEqual(addition, cc.p(0, 0), EPSILON) && !this._outOfBoundaryAmountDirty) return this._outOfBoundaryAmount;
        var outOfBoundaryAmount = cc.p(0, 0);
        this._getContentLeftBoundary() + addition.x > this._leftBoundary ? outOfBoundaryAmount.x = this._leftBoundary - (this._getContentLeftBoundary() + addition.x) : this._getContentRightBoundary() + addition.x < this._rightBoundary && (outOfBoundaryAmount.x = this._rightBoundary - (this._getContentRightBoundary() + addition.x));
        this._getContentTopBoundary() + addition.y < this._topBoundary ? outOfBoundaryAmount.y = this._topBoundary - (this._getContentTopBoundary() + addition.y) : this._getContentBottomBoundary() + addition.y > this._bottomBoundary && (outOfBoundaryAmount.y = this._bottomBoundary - (this._getContentBottomBoundary() + addition.y));
        if (cc.pFuzzyEqual(addition, cc.p(0, 0), EPSILON)) {
          this._outOfBoundaryAmount = outOfBoundaryAmount;
          this._outOfBoundaryAmountDirty = false;
        }
        outOfBoundaryAmount = this._clampDelta(outOfBoundaryAmount);
        return outOfBoundaryAmount;
      },
      _updateScrollBar: function(outOfBoundary) {
        this.horizontalScrollBar && this.horizontalScrollBar._onScroll(outOfBoundary);
        this.verticalScrollBar && this.verticalScrollBar._onScroll(outOfBoundary);
      },
      _onScrollBarTouchBegan: function() {
        this.horizontalScrollBar && this.horizontalScrollBar._onTouchBegan();
        this.verticalScrollBar && this.verticalScrollBar._onTouchBegan();
      },
      _onScrollBarTouchEnded: function() {
        this.horizontalScrollBar && this.horizontalScrollBar._onTouchEnded();
        this.verticalScrollBar && this.verticalScrollBar._onTouchEnded();
      },
      _dispatchEvent: function(event) {
        if ("scroll-ended" === event) this._scrollEventEmitMask = 0; else if ("scroll-to-top" === event || "scroll-to-bottom" === event || "scroll-to-left" === event || "scroll-to-right" === event) {
          var flag = 1 << eventMap[event];
          if (this._scrollEventEmitMask & flag) return;
          this._scrollEventEmitMask |= flag;
        }
        cc.Component.EventHandler.emitEvents(this.scrollEvents, this, eventMap[event]);
        this.node.emit(event, this);
      },
      _adjustContentOutOfBoundary: function() {
        this._outOfBoundaryAmountDirty = true;
        if (this._isOutOfBoundary()) {
          var outOfBoundary = this._getHowMuchOutOfBoundary(cc.p(0, 0));
          var newPosition = cc.pAdd(this.getContentPosition(), outOfBoundary);
          if (this.content) {
            this.content.setPosition(newPosition);
            this._updateScrollBar(0);
          }
        }
      },
      start: function() {
        this._calculateBoundary();
        this.content && cc.director.once(cc.Director.EVENT_AFTER_VISIT, this._adjustContentOutOfBoundary, this);
      },
      _hideScrollbar: function() {
        this.horizontalScrollBar && this.horizontalScrollBar.hide();
        this.verticalScrollBar && this.verticalScrollBar.hide();
      },
      _showScrollbar: function() {
        this.horizontalScrollBar && this.horizontalScrollBar.show();
        this.verticalScrollBar && this.verticalScrollBar.show();
      },
      onDisable: function() {
        true;
        this._unregisterEvent();
        this.node.off("size-changed", this._calculateBoundary, this);
        this.node.off("scale-changed", this._calculateBoundary, this);
        if (this.content) {
          this.content.off("size-changed", this._calculateBoundary, this);
          this.content.off("scale-changed", this._calculateBoundary, this);
        }
        this._hideScrollbar();
        this.stopAutoScroll();
      },
      onEnable: function() {
        true;
        this._registerEvent();
        this.node.on("size-changed", this._calculateBoundary, this);
        this.node.on("scale-changed", this._calculateBoundary, this);
        if (this.content) {
          this.content.on("size-changed", this._calculateBoundary, this);
          this.content.on("scale-changed", this._calculateBoundary, this);
        }
        this._showScrollbar();
      },
      update: function(dt) {
        this._autoScrolling && this._processAutoScrolling(dt);
      }
    });
    cc.ScrollView = module.exports = ScrollView;
  }), {
    "./CCViewGroup": 100
  } ],
  92: [ (function(require, module, exports) {
    var Direction = cc.Enum({
      Horizontal: 0,
      Vertical: 1
    });
    var Slider = cc.Class({
      name: "cc.Slider",
      extends: require("./CCComponent"),
      editor: false,
      ctor: function() {
        this._dragging = false;
      },
      properties: {
        handle: {
          default: null,
          type: cc.Button,
          tooltip: false,
          notify: function() {
            false;
          }
        },
        direction: {
          default: Direction.Horizontal,
          type: Direction,
          tooltip: false
        },
        progress: {
          default: .5,
          type: cc.Float,
          range: [ 0, 1, .1 ],
          slide: true,
          tooltip: false,
          notify: function() {
            this._updateHandlePosition();
          }
        },
        slideEvents: {
          default: [],
          type: cc.Component.EventHandler,
          tooltip: false
        }
      },
      statics: {
        Direction: Direction
      },
      __preload: function() {
        this._updateHandlePosition();
      },
      onEnable: function() {
        this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this);
        if (this.handle && this.handle.isValid) {
          this.handle.node.on(cc.Node.EventType.TOUCH_START, this._onHandleDragStart, this);
          this.handle.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this);
          this.handle.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
        }
      },
      onDisable: function() {
        this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this);
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this);
        this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
        this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this);
        if (this.handle && this.handle.isValid) {
          this.handle.node.off(cc.Node.EventType.TOUCH_START, this._onHandleDragStart, this);
          this.handle.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this);
          this.handle.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
        }
      },
      _onHandleDragStart: function(event) {
        this._dragging = true;
        event.stopPropagation();
      },
      _onTouchBegan: function(event) {
        if (!this.handle) return;
        this._dragging = true;
        this._handleSliderLogic(event.touch);
        event.stopPropagation();
      },
      _onTouchMoved: function(event) {
        if (!this._dragging) return;
        this._handleSliderLogic(event.touch);
        event.stopPropagation();
      },
      _onTouchEnded: function(event) {
        this._dragging = false;
        event.stopPropagation();
      },
      _onTouchCancelled: function(event) {
        this._dragging = false;
        event.stopPropagation();
      },
      _handleSliderLogic: function(touch) {
        this._updateProgress(touch);
        this._emitSlideEvent();
      },
      _emitSlideEvent: function() {
        cc.Component.EventHandler.emitEvents(this.slideEvents, this);
        this.node.emit("slide", this);
      },
      _updateProgress: function(touch) {
        if (!this.handle) return;
        var maxRange = null, progress = 0, newPos = this.node.convertTouchToNodeSpaceAR(touch);
        if (this.direction === Direction.Horizontal) {
          maxRange = this.node.width / 2 - this.handle.node.width * this.handle.node.anchorX;
          progress = cc.clamp01((newPos.x + maxRange) / (2 * maxRange), 0, 1);
        } else if (this.direction === Direction.Vertical) {
          maxRange = this.node.height / 2 - this.handle.node.height * this.handle.node.anchorY;
          progress = cc.clamp01((newPos.y + maxRange) / (2 * maxRange), 0, 1);
        }
        this.progress = progress;
      },
      _updateHandlePosition: function() {
        if (!this.handle) return;
        var handlelocalPos;
        handlelocalPos = this.direction === Direction.Horizontal ? cc.p(-this.node.width * this.node.anchorX + this.progress * this.node.width, 0) : cc.p(0, -this.node.height * this.node.anchorY + this.progress * this.node.height);
        var worldSpacePos = this.node.convertToWorldSpaceAR(handlelocalPos);
        this.handle.node.position = this.handle.node.parent.convertToNodeSpaceAR(worldSpacePos);
      }
    });
    cc.Slider = module.exports = Slider;
  }), {
    "./CCComponent": 76
  } ],
  93: [ (function(require, module, exports) {
    var Base = require("./CCRendererUnderSG");
    var SpriteType = cc.Scale9Sprite.RenderingType;
    var FillType = cc.Scale9Sprite.FillType;
    var BlendFactor = cc.BlendFunc.BlendFactor;
    var SizeMode = cc.Enum({
      CUSTOM: 0,
      TRIMMED: 1,
      RAW: 2
    });
    var Sprite = cc.Class({
      name: "cc.Sprite",
      extends: Base,
      editor: false,
      ctor: function() {
        this._blendFunc = new cc.BlendFunc(this._srcBlendFactor, this._dstBlendFactor);
      },
      properties: {
        _spriteFrame: {
          default: null,
          type: cc.SpriteFrame
        },
        _type: SpriteType.SIMPLE,
        _sizeMode: SizeMode.TRIMMED,
        _fillType: 0,
        _fillCenter: cc.v2(0, 0),
        _fillStart: 0,
        _fillRange: 0,
        _isTrimmedMode: true,
        _srcBlendFactor: BlendFactor.SRC_ALPHA,
        _dstBlendFactor: BlendFactor.ONE_MINUS_SRC_ALPHA,
        _atlas: {
          default: null,
          type: cc.SpriteAtlas,
          tooltip: false,
          editorOnly: true,
          visible: true,
          animatable: false
        },
        spriteFrame: {
          get: function() {
            return this._spriteFrame;
          },
          set: function(value, force) {
            var lastSprite = this._spriteFrame;
            false;
            if (lastSprite === value) return;
            this._spriteFrame = value;
            this._applySpriteFrame(lastSprite);
            false;
          },
          type: cc.SpriteFrame
        },
        type: {
          get: function() {
            return this._type;
          },
          set: function(value) {
            this._type = value;
            this._sgNode.setRenderingType(value);
          },
          type: SpriteType,
          animatable: false,
          tooltip: false
        },
        fillType: {
          get: function() {
            return this._fillType;
          },
          set: function(value) {
            this._fillType = value;
            this._sgNode && this._sgNode.setFillType(value);
          },
          type: FillType,
          tooltip: false
        },
        fillCenter: {
          get: function() {
            return this._fillCenter;
          },
          set: function(value) {
            this._fillCenter = cc.v2(value);
            this._sgNode && this._sgNode.setFillCenter(this._fillCenter);
          },
          tooltip: false
        },
        fillStart: {
          get: function() {
            return this._fillStart;
          },
          set: function(value) {
            this._fillStart = cc.clampf(value, -1, 1);
            this._sgNode && this._sgNode.setFillStart(value);
          },
          tooltip: false
        },
        fillRange: {
          get: function() {
            return this._fillRange;
          },
          set: function(value) {
            this._fillRange = cc.clampf(value, -1, 1);
            this._sgNode && this._sgNode.setFillRange(value);
          },
          tooltip: false
        },
        trim: {
          get: function() {
            return this._isTrimmedMode;
          },
          set: function(value) {
            if (this._isTrimmedMode !== value) {
              this._isTrimmedMode = value;
              this._sgNode.enableTrimmedContentSize(value);
            }
          },
          animatable: false,
          tooltip: false
        },
        srcBlendFactor: {
          get: function() {
            return this._srcBlendFactor;
          },
          set: function(value) {
            this._srcBlendFactor = value;
            this._blendFunc.src = value;
            this._sgNode.setBlendFunc(this._blendFunc);
          },
          animatable: false,
          type: BlendFactor,
          tooltip: false
        },
        dstBlendFactor: {
          get: function() {
            return this._dstBlendFactor;
          },
          set: function(value) {
            this._dstBlendFactor = value;
            this._blendFunc.dst = value;
            this._sgNode.setBlendFunc(this._blendFunc);
          },
          animatable: false,
          type: BlendFactor,
          tooltip: false
        },
        sizeMode: {
          get: function() {
            return this._sizeMode;
          },
          set: function(value) {
            this._sizeMode = value;
            value !== SizeMode.CUSTOM && this._applySpriteSize();
          },
          animatable: false,
          type: SizeMode,
          tooltip: false
        }
      },
      statics: {
        FillType: FillType,
        Type: SpriteType,
        SizeMode: SizeMode
      },
      setVisible: function(visible) {
        this.enabled = visible;
      },
      setInsetLeft: function(insetLeft) {
        this._sgNode.setInsetLeft(insetLeft);
      },
      getInsetLeft: function() {
        return this._sgNode.getInsetLeft();
      },
      setInsetTop: function(insetTop) {
        this._sgNode.setInsetTop(insetTop);
      },
      getInsetTop: function() {
        return this._sgNode.getInsetTop();
      },
      setInsetRight: function(insetRight) {
        this._sgNode.setInsetRight(insetRight);
      },
      getInsetRight: function() {
        return this._sgNode.getInsetRight();
      },
      setInsetBottom: function(insetBottom) {
        this._sgNode.setInsetBottom(insetBottom);
      },
      getInsetBottom: function() {
        return this._sgNode.getInsetBottom();
      },
      onEnable: function() {
        this._sgNode && this._spriteFrame && this._spriteFrame.textureLoaded() && this._sgNode.setVisible(true);
      },
      _applyAtlas: false,
      _applySpriteFrameInsets: function() {
        var spriteFrame = this._spriteFrame;
        var sgNode = this._sgNode;
        sgNode.setInsetTop(spriteFrame.insetTop);
        sgNode.setInsetBottom(spriteFrame.insetBottom);
        sgNode.setInsetRight(spriteFrame.insetRight);
        sgNode.setInsetLeft(spriteFrame.insetLeft);
      },
      _applySpriteSize: function() {
        if (this._spriteFrame) if (SizeMode.RAW === this._sizeMode) {
          var size = this._spriteFrame.getOriginalSize();
          this.node.setContentSize(size);
        } else if (SizeMode.TRIMMED === this._sizeMode) {
          var rect = this._spriteFrame.getRect();
          this.node.setContentSize(rect.width, rect.height);
        }
      },
      _onTextureLoaded: function(event) {
        var self = this;
        if (!self.isValid) return;
        var sgNode = self._sgNode;
        sgNode.setSpriteFrame(self._spriteFrame);
        self._applySpriteSize();
        self.enabledInHierarchy && !sgNode.isVisible() && sgNode.setVisible(true);
      },
      _applySpriteFrame: function(oldFrame, keepInsets) {
        var sgNode = this._sgNode;
        oldFrame && oldFrame.off && oldFrame.off("load", this._onTextureLoaded, this);
        var spriteFrame = this._spriteFrame;
        if (spriteFrame) {
          keepInsets || this._applySpriteFrameInsets();
          if (spriteFrame.textureLoaded()) this._onTextureLoaded(null); else {
            spriteFrame.once("load", this._onTextureLoaded, this);
            spriteFrame.ensureLoadTexture();
          }
        } else sgNode.setVisible(false);
        false;
      },
      _createSgNode: function() {
        return new cc.Scale9Sprite();
      },
      _initSgNode: function() {
        var sgNode = this._sgNode;
        var insetsChangedViaAPI = 0 !== sgNode.getInsetLeft() || 0 !== sgNode.getInsetRight() || 0 !== sgNode.getInsetTop() || 0 !== sgNode.getInsetBottom();
        this._applySpriteFrame(null, insetsChangedViaAPI);
        sgNode.setContentSize(this.node.getContentSize(true));
        this._applySpriteSize();
        sgNode.setRenderingType(this._type);
        sgNode.setFillType(this._fillType);
        sgNode.setFillCenter(this._fillCenter);
        sgNode.setFillStart(this._fillStart);
        sgNode.setFillRange(this._fillRange);
        sgNode.enableTrimmedContentSize(this._isTrimmedMode);
        this._blendFunc.src = this._srcBlendFactor;
        this._blendFunc.dst = this._dstBlendFactor;
        sgNode.setBlendFunc(this._blendFunc);
      },
      _resized: false
    });
    false;
    var misc = require("../utils/misc");
    var SameNameGetSets = [ "insetLeft", "insetTop", "insetRight", "insetBottom" ];
    var DiffNameGetSets = {
      type: [ null, "setRenderingType" ]
    };
    misc.propertyDefine(Sprite, SameNameGetSets, DiffNameGetSets);
    cc.Sprite = module.exports = Sprite;
  }), {
    "../utils/misc": 225,
    "./CCRendererUnderSG": 87
  } ],
  94: [ (function(require, module, exports) {
    var SpriteDistortion = cc.Class({
      name: "cc.SpriteDistortion",
      extends: require("./CCComponent"),
      editor: false,
      ctor: function() {
        this._spriteSGNode = null;
      },
      properties: {
        _distortionOffset: cc.v2(0, 0),
        offset: {
          get: function() {
            return this._distortionOffset;
          },
          set: function(value) {
            this._distortionOffset.x = value.x;
            this._distortionOffset.y = value.y;
            this._spriteSGNode && this._spriteSGNode.setDistortionOffset(this._distortionOffset);
          }
        },
        _distortionTiling: cc.v2(1, 1),
        tiling: {
          get: function() {
            return this._distortionTiling;
          },
          set: function(value) {
            this._distortionTiling.x = value.x;
            this._distortionTiling.y = value.y;
            this._spriteSGNode && this._spriteSGNode.setDistortionTiling(this._distortionTiling);
          }
        }
      },
      onEnable: function() {
        var sprite = this.node.getComponent("cc.Sprite");
        var sgNode = this._spriteSGNode = sprite && sprite._sgNode;
        if (this._spriteSGNode) {
          sgNode.setState(cc.Scale9Sprite.state.DISTORTION);
          sgNode.setDistortionOffset(this._distortionOffset);
          sgNode.setDistortionTiling(this._distortionTiling);
        }
      },
      onDisable: function() {
        this._spriteSGNode && this._spriteSGNode.setState(cc.Scale9Sprite.state.NORMAL);
        this._spriteSGNode = null;
      }
    });
    cc.SpriteDistortion = module.exports = SpriteDistortion;
  }), {
    "./CCComponent": 76
  } ],
  95: [ (function(require, module, exports) {
    var ComponentType = cc.Enum({
      NONE: 0,
      CHECKBOX: 1,
      TEXT_ATLAS: 2,
      SLIDER_BAR: 3,
      LIST_VIEW: 4,
      PAGE_VIEW: 5
    });
    var ListDirection = cc.Enum({
      VERTICAL: 0,
      HORIZONTAL: 1
    });
    var VerticalAlign = cc.Enum({
      TOP: 0,
      CENTER: 1,
      BOTTOM: 2
    });
    var HorizontalAlign = cc.Enum({
      LEFT: 0,
      CENTER: 1,
      RIGHT: 2
    });
    var StudioComponent = cc.Class({
      name: "cc.StudioComponent",
      extends: cc.Component,
      editor: false,
      properties: false,
      statics: {
        ComponentType: ComponentType,
        ListDirection: ListDirection,
        VerticalAlign: VerticalAlign,
        HorizontalAlign: HorizontalAlign
      }
    });
    var PrefabHelper = require("../utils/prefab-helper");
    StudioComponent.PlaceHolder = cc.Class({
      name: "cc.StudioComponent.PlaceHolder",
      extends: cc.Component,
      properties: {
        _baseUrl: "",
        nestedPrefab: cc.Prefab
      },
      onLoad: function() {
        if (!this.nestedPrefab) {
          false;
          return;
        }
        this._replaceWithNestedPrefab();
      },
      _replaceWithNestedPrefab: function() {
        var node = this.node;
        var _prefab = node._prefab;
        _prefab.root = node;
        _prefab.asset = this.nestedPrefab;
        PrefabHelper.syncWithPrefab(node);
      }
    });
    cc.StudioComponent = module.exports = StudioComponent;
  }), {
    "../utils/prefab-helper": 227
  } ],
  96: [ (function(require, module, exports) {
    var Toggle = cc.Class({
      name: "cc.Toggle",
      extends: require("./CCButton"),
      editor: false,
      properties: {
        isChecked: {
          default: true,
          tooltip: false,
          notify: function() {
            this._updateCheckMark();
          }
        },
        toggleGroup: {
          default: null,
          tooltip: false,
          type: require("./CCToggleGroup")
        },
        checkMark: {
          default: null,
          type: cc.Sprite,
          tooltip: false
        },
        checkEvents: {
          default: [],
          type: cc.Component.EventHandler
        },
        _resizeToTarget: {
          animatable: false,
          set: function(value) {
            value && this._resizeNodeToTargetNode();
          }
        }
      },
      onEnable: function() {
        this._super();
        true;
        this._registerToggleEvent();
        this.toggleGroup && this.toggleGroup.enabled && this.toggleGroup.addToggle(this);
      },
      onDisable: function() {
        this._super();
        true;
        this._unregisterToggleEvent();
        this.toggleGroup && this.toggleGroup.enabled && this.toggleGroup.removeToggle(this);
      },
      _updateCheckMark: function() {
        this.checkMark && (this.checkMark.node.active = !!this.isChecked);
      },
      _updateDisabledState: function() {
        this._super();
        this.checkMark && this.checkMark._sgNode.setState(0);
        this.enableAutoGrayEffect && this.checkMark && !this.interactable && this.checkMark._sgNode.setState(1);
      },
      _registerToggleEvent: function() {
        this.node.on("click", this.toggle, this);
      },
      _unregisterToggleEvent: function() {
        this.node.off("click", this.toggle, this);
      },
      toggle: function(event) {
        var group = this.toggleGroup || this._toggleContainer;
        if (group && group.enabled && this.isChecked && !group.allowSwitchOff) return;
        this.isChecked = !this.isChecked;
        this._updateCheckMark();
        group && group.enabled && group.updateToggles(this);
        this._emitToggleEvents(event);
      },
      _emitToggleEvents: function() {
        this.node.emit("toggle", this);
        this.checkEvents && cc.Component.EventHandler.emitEvents(this.checkEvents, this);
      },
      check: function() {
        var group = this.toggleGroup || this._toggleContainer;
        if (group && group.enabled && this.isChecked && !group.allowSwitchOff) return;
        this.isChecked = true;
        group && group.enabled && group.updateToggles(this);
        this._emitToggleEvents();
      },
      uncheck: function() {
        var group = this.toggleGroup || this._toggleContainer;
        if (group && group.enabled && this.isChecked && !group.allowSwitchOff) return;
        this.isChecked = false;
        this._emitToggleEvents();
      }
    });
    cc.Toggle = module.exports = Toggle;
    var JS = require("../platform/js");
    JS.get(Toggle.prototype, "_toggleContainer", (function() {
      var parent = this.node.parent;
      if (cc.Node.isNode(parent)) return parent.getComponent(cc.ToggleContainer);
      return null;
    }));
  }), {
    "../platform/js": 196,
    "./CCButton": 74,
    "./CCToggleGroup": 98
  } ],
  97: [ (function(require, module, exports) {
    var ToggleContainer = cc.Class({
      name: "cc.ToggleContainer",
      extends: cc.Component,
      editor: false,
      properties: {
        allowSwitchOff: {
          tooltip: false,
          default: false
        }
      },
      updateToggles: function(toggle) {
        this.toggleItems.forEach((function(item) {
          toggle.isChecked && item !== toggle && (item.isChecked = false);
        }));
      },
      _allowOnlyOneToggleChecked: function() {
        var isChecked = false;
        this.toggleItems.forEach((function(item) {
          isChecked ? item.isChecked = false : item.isChecked && (isChecked = true);
        }));
        return isChecked;
      },
      _makeAtLeastOneToggleChecked: function() {
        var isChecked = this._allowOnlyOneToggleChecked();
        if (!isChecked && !this.allowSwitchOff) {
          var toggleItems = this.toggleItems;
          toggleItems.length > 0 && toggleItems[0].check();
        }
      },
      onEnable: function() {
        this.node.on("child-added", this._allowOnlyOneToggleChecked, this);
        this.node.on("child-removed", this._makeAtLeastOneToggleChecked, this);
      },
      onDisable: function() {
        this.node.off("child-added", this._allowOnlyOneToggleChecked, this);
        this.node.off("child-removed", this._makeAtLeastOneToggleChecked, this);
      },
      start: function() {
        this._makeAtLeastOneToggleChecked();
      }
    });
    var JS = require("../platform/js");
    JS.get(ToggleContainer.prototype, "toggleItems", (function() {
      return this.node.getComponentsInChildren(cc.Toggle);
    }));
    cc.ToggleContainer = module.exports = ToggleContainer;
  }), {
    "../platform/js": 196
  } ],
  98: [ (function(require, module, exports) {
    var ToggleGroup = cc.Class({
      name: "cc.ToggleGroup",
      extends: cc.Component,
      ctor: function() {
        this._toggleItems = [];
      },
      editor: false,
      properties: {
        allowSwitchOff: {
          tooltip: false,
          default: false
        },
        toggleItems: {
          get: function() {
            return this._toggleItems;
          }
        }
      },
      updateToggles: function(toggle) {
        if (!this.enabledInHierarchy) return;
        this._toggleItems.forEach((function(item) {
          toggle.isChecked && item !== toggle && item.isChecked && item.enabled && (item.isChecked = false);
        }));
      },
      addToggle: function(toggle) {
        var index = this._toggleItems.indexOf(toggle);
        -1 === index && this._toggleItems.push(toggle);
        this._allowOnlyOneToggleChecked();
      },
      removeToggle: function(toggle) {
        var index = this._toggleItems.indexOf(toggle);
        index > -1 && this._toggleItems.splice(index, 1);
        this._makeAtLeastOneToggleChecked();
      },
      _allowOnlyOneToggleChecked: function() {
        var isChecked = false;
        this._toggleItems.forEach((function(item) {
          isChecked && item.enabled && (item.isChecked = false);
          item.isChecked && item.enabled && (isChecked = true);
        }));
        return isChecked;
      },
      _makeAtLeastOneToggleChecked: function() {
        var isChecked = this._allowOnlyOneToggleChecked();
        isChecked || this.allowSwitchOff || this._toggleItems.length > 0 && (this._toggleItems[0].isChecked = true);
      },
      start: function() {
        this._makeAtLeastOneToggleChecked();
      }
    });
    var JS = require("../platform/js");
    var showed = false;
    cc.js.get(cc, "ToggleGroup", (function() {
      if (!showed) {
        cc.logID(1405, "cc.ToggleGroup", "cc.ToggleContainer");
        showed = true;
      }
      return ToggleGroup;
    }));
    cc.ToggleGroup = module.exports = ToggleGroup;
  }), {
    "../platform/js": 196
  } ],
  99: [ (function(require, module, exports) {
    require("../videoplayer/CCSGVideoPlayer");
    var EventType = _ccsg.VideoPlayer.EventType;
    var ResourceType = cc.Enum({
      REMOTE: 0,
      LOCAL: 1
    });
    var VideoPlayer = cc.Class({
      name: "cc.VideoPlayer",
      extends: cc._RendererUnderSG,
      editor: false,
      properties: {
        _resourceType: ResourceType.REMOTE,
        resourceType: {
          tooltip: false,
          type: ResourceType,
          set: function(value) {
            this._resourceType = value;
            this._updateVideoSource();
          },
          get: function() {
            return this._resourceType;
          }
        },
        _remoteURL: "",
        remoteURL: {
          tooltip: false,
          type: cc.String,
          set: function(url) {
            this._remoteURL = url;
            this._updateVideoSource();
          },
          get: function() {
            return this._remoteURL;
          }
        },
        _clip: {
          default: null,
          url: cc.RawAsset
        },
        clip: {
          tooltip: false,
          get: function() {
            return this._clip;
          },
          set: function(value) {
            "string" !== typeof value && (value = "");
            this._clip = value;
            this._updateVideoSource();
          },
          url: cc.RawAsset
        },
        currentTime: {
          tooltip: false,
          type: cc.Float,
          set: function(time) {
            this._sgNode && this._sgNode.seekTo(time);
          },
          get: function() {
            if (this._sgNode) return this._sgNode.currentTime();
            return -1;
          }
        },
        keepAspectRatio: {
          tooltip: false,
          default: true,
          type: cc.Boolean,
          notify: function() {
            this._sgNode.setKeepAspectRatioEnabled(this.keepAspectRatio);
          }
        },
        isFullscreen: {
          tooltip: false,
          default: false,
          type: cc.Boolean,
          notify: function() {
            this._sgNode.setFullScreenEnabled(this.isFullscreen);
          }
        },
        videoPlayerEvent: {
          default: [],
          type: cc.Component.EventHandler
        }
      },
      statics: {
        EventType: EventType,
        ResourceType: ResourceType
      },
      onLoad: function() {
        false;
      },
      _createSgNode: function() {
        false;
        return new _ccsg.VideoPlayer();
      },
      _updateVideoSource: function() {
        var sgNode = this._sgNode;
        this.resourceType === ResourceType.REMOTE ? sgNode.setURL(this.remoteURL) : sgNode.setURL(this._clip || "");
      },
      _initSgNode: function() {
        var sgNode = this._sgNode;
        if (sgNode) {
          true;
          sgNode.createDomElementIfNeeded();
          this._updateVideoSource();
          sgNode.seekTo(this.currentTime);
          sgNode.setKeepAspectRatioEnabled(this.keepAspectRatio);
          sgNode.setFullScreenEnabled(this.isFullscreen);
          sgNode.setContentSize(this.node.getContentSize());
          this.pause();
          true;
          sgNode.setEventListener(EventType.PLAYING, this.onPlaying.bind(this));
          sgNode.setEventListener(EventType.PAUSED, this.onPasued.bind(this));
          sgNode.setEventListener(EventType.STOPPED, this.onStopped.bind(this));
          sgNode.setEventListener(EventType.COMPLETED, this.onCompleted.bind(this));
          sgNode.setEventListener(EventType.META_LOADED, this.onMetaLoaded.bind(this));
          sgNode.setEventListener(EventType.CLICKED, this.onClicked.bind(this));
          sgNode.setEventListener(EventType.READY_TO_PLAY, this.onReadyToPlay.bind(this));
        }
      },
      onReadyToPlay: function() {
        cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.READY_TO_PLAY);
        this.node.emit("ready-to-play", this);
      },
      onMetaLoaded: function() {
        cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.META_LOADED);
        this.node.emit("meta-loaded", this);
      },
      onClicked: function() {
        cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.CLICKED);
        this.node.emit("clicked", this);
      },
      onPlaying: function() {
        cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.PLAYING);
        this.node.emit("playing", this);
      },
      onPasued: function() {
        cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.PAUSED);
        this.node.emit("paused", this);
      },
      onStopped: function() {
        cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.STOPPED);
        this.node.emit("stopped", this);
      },
      onCompleted: function() {
        cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.COMPLETED);
        this.node.emit("completed", this);
      },
      play: function() {
        this._sgNode && this._sgNode.play();
      },
      resume: function() {
        this._sgNode && this._sgNode.resume();
      },
      pause: function() {
        this._sgNode && this._sgNode.pause();
      },
      stop: function() {
        this._sgNode && this._sgNode.stop();
      },
      getDuration: function() {
        if (this._sgNode) return this._sgNode.duration();
        return -1;
      },
      isPlaying: function() {
        if (this._sgNode) return this._sgNode.isPlaying();
        return false;
      }
    });
    cc.VideoPlayer = module.exports = VideoPlayer;
  }), {
    "../videoplayer/CCSGVideoPlayer": 239
  } ],
  100: [ (function(require, module, exports) {
    var ViewGroup = cc.Class({
      name: "cc.ViewGroup",
      extends: require("./CCComponent")
    });
    cc.ViewGroup = module.exports = ViewGroup;
  }), {
    "./CCComponent": 76
  } ],
  101: [ (function(require, module, exports) {
    require("../webview/CCSGWebView");
    var EventType = _ccsg.WebView.EventType;
    function emptyCallback() {}
    var WebView = cc.Class({
      name: "cc.WebView",
      extends: cc._RendererUnderSG,
      editor: false,
      properties: {
        _useOriginalSize: true,
        _url: "",
        url: {
          type: String,
          tooltip: false,
          get: function() {
            return this._url;
          },
          set: function(url) {
            this._url = url;
            var sgNode = this._sgNode;
            sgNode && sgNode.loadURL(url);
          }
        },
        webviewEvents: {
          default: [],
          type: cc.Component.EventHandler
        }
      },
      statics: {
        EventType: EventType
      },
      onLoad: false,
      _createSgNode: function() {
        false;
        return new _ccsg.WebView();
      },
      _initSgNode: function() {
        var sgNode = this._sgNode;
        if (!sgNode) return;
        true;
        sgNode.createDomElementIfNeeded();
        sgNode.loadURL(this._url);
        false;
        sgNode.setContentSize(this.node.getContentSize());
      },
      onEnable: function() {
        this._super();
        true;
        var sgNode = this._sgNode;
        sgNode.setEventListener(EventType.LOADED, this._onWebViewLoaded.bind(this));
        sgNode.setEventListener(EventType.LOADING, this._onWebViewLoading.bind(this));
        sgNode.setEventListener(EventType.ERROR, this._onWebViewLoadError.bind(this));
      },
      onDisable: function() {
        this._super();
        true;
        var sgNode = this._sgNode;
        sgNode.setEventListener(EventType.LOADED, emptyCallback);
        sgNode.setEventListener(EventType.LOADING, emptyCallback);
        sgNode.setEventListener(EventType.ERROR, emptyCallback);
      },
      _onWebViewLoaded: function() {
        cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADED);
        this.node.emit("loaded", this);
      },
      _onWebViewLoading: function() {
        cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADING);
        this.node.emit("loading", this);
        return true;
      },
      _onWebViewLoadError: function() {
        cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.ERROR);
        this.node.emit("error", this);
      },
      setJavascriptInterfaceScheme: function(scheme) {
        this._sgNode && this._sgNode.setJavascriptInterfaceScheme(scheme);
      },
      setOnJSCallback: function(callback) {
        this._sgNode && this._sgNode.setOnJSCallback(callback);
      },
      evaluateJS: function(str) {
        this._sgNode && this._sgNode.evaluateJS(str);
      }
    });
    cc.WebView = module.exports = WebView;
  }), {
    "../webview/CCSGWebView": 240
  } ],
  102: [ (function(require, module, exports) {
    var WidgetManager = require("../base-ui/CCWidgetManager");
    var AlignFlags = WidgetManager._AlignFlags;
    var TOP = AlignFlags.TOP;
    var MID = AlignFlags.MID;
    var BOT = AlignFlags.BOT;
    var LEFT = AlignFlags.LEFT;
    var CENTER = AlignFlags.CENTER;
    var RIGHT = AlignFlags.RIGHT;
    var TOP_BOT = TOP | BOT;
    var LEFT_RIGHT = LEFT | RIGHT;
    var Widget = cc.Class({
      name: "cc.Widget",
      extends: require("./CCComponent"),
      editor: false,
      properties: {
        target: {
          get: function() {
            return this._target;
          },
          set: function(value) {
            this._target = value;
            false;
          },
          type: cc.Node,
          tooltip: false
        },
        isAlignTop: {
          get: function() {
            return (this._alignFlags & TOP) > 0;
          },
          set: function(value) {
            this._setAlign(TOP, value);
          },
          animatable: false,
          tooltip: false
        },
        isAlignVerticalCenter: {
          get: function() {
            return (this._alignFlags & MID) > 0;
          },
          set: function(value) {
            if (value) {
              this.isAlignTop = false;
              this.isAlignBottom = false;
              this._alignFlags |= MID;
            } else this._alignFlags &= ~MID;
          },
          animatable: false,
          tooltip: false
        },
        isAlignBottom: {
          get: function() {
            return (this._alignFlags & BOT) > 0;
          },
          set: function(value) {
            this._setAlign(BOT, value);
          },
          animatable: false,
          tooltip: false
        },
        isAlignLeft: {
          get: function() {
            return (this._alignFlags & LEFT) > 0;
          },
          set: function(value) {
            this._setAlign(LEFT, value);
          },
          animatable: false,
          tooltip: false
        },
        isAlignHorizontalCenter: {
          get: function() {
            return (this._alignFlags & CENTER) > 0;
          },
          set: function(value) {
            if (value) {
              this.isAlignLeft = false;
              this.isAlignRight = false;
              this._alignFlags |= CENTER;
            } else this._alignFlags &= ~CENTER;
          },
          animatable: false,
          tooltip: false
        },
        isAlignRight: {
          get: function() {
            return (this._alignFlags & RIGHT) > 0;
          },
          set: function(value) {
            this._setAlign(RIGHT, value);
          },
          animatable: false,
          tooltip: false
        },
        isStretchWidth: {
          get: function() {
            return (this._alignFlags & LEFT_RIGHT) === LEFT_RIGHT;
          },
          visible: false
        },
        isStretchHeight: {
          get: function() {
            return (this._alignFlags & TOP_BOT) === TOP_BOT;
          },
          visible: false
        },
        top: {
          get: function() {
            return this._top;
          },
          set: function(value) {
            this._top = value;
          },
          tooltip: false
        },
        bottom: {
          get: function() {
            return this._bottom;
          },
          set: function(value) {
            this._bottom = value;
          },
          tooltip: false
        },
        left: {
          get: function() {
            return this._left;
          },
          set: function(value) {
            this._left = value;
          },
          tooltip: false
        },
        right: {
          get: function() {
            return this._right;
          },
          set: function(value) {
            this._right = value;
          },
          tooltip: false
        },
        horizontalCenter: {
          get: function() {
            return this._horizontalCenter;
          },
          set: function(value) {
            this._horizontalCenter = value;
          },
          tooltip: false
        },
        verticalCenter: {
          get: function() {
            return this._verticalCenter;
          },
          set: function(value) {
            this._verticalCenter = value;
          },
          tooltip: false
        },
        isAbsoluteHorizontalCenter: {
          get: function() {
            return this._isAbsHorizontalCenter;
          },
          set: function(value) {
            this._isAbsHorizontalCenter = value;
          },
          animatable: false
        },
        isAbsoluteVerticalCenter: {
          get: function() {
            return this._isAbsVerticalCenter;
          },
          set: function(value) {
            this._isAbsVerticalCenter = value;
          },
          animatable: false
        },
        isAbsoluteTop: {
          get: function() {
            return this._isAbsTop;
          },
          set: function(value) {
            this._isAbsTop = value;
          },
          animatable: false
        },
        isAbsoluteBottom: {
          get: function() {
            return this._isAbsBottom;
          },
          set: function(value) {
            this._isAbsBottom = value;
          },
          animatable: false
        },
        isAbsoluteLeft: {
          get: function() {
            return this._isAbsLeft;
          },
          set: function(value) {
            this._isAbsLeft = value;
          },
          animatable: false
        },
        isAbsoluteRight: {
          get: function() {
            return this._isAbsRight;
          },
          set: function(value) {
            this._isAbsRight = value;
          },
          animatable: false
        },
        isAlignOnce: {
          default: true,
          tooltip: false,
          displayName: "AlignOnce"
        },
        _target: null,
        _alignFlags: 0,
        _left: 0,
        _right: 0,
        _top: 0,
        _bottom: 0,
        _verticalCenter: 0,
        _horizontalCenter: 0,
        _isAbsLeft: true,
        _isAbsRight: true,
        _isAbsTop: true,
        _isAbsBottom: true,
        _isAbsHorizontalCenter: true,
        _isAbsVerticalCenter: true,
        _originalWidth: 0,
        _originalHeight: 0
      },
      onEnable: function() {
        WidgetManager.add(this);
      },
      onDisable: function() {
        WidgetManager.remove(this);
      },
      _setAlign: function(flag, isAlign) {
        var current = (this._alignFlags & flag) > 0;
        if (isAlign == current) return;
        var isHorizontal = (flag & LEFT_RIGHT) > 0;
        if (isAlign) {
          this._alignFlags |= flag;
          if (isHorizontal) {
            this.isAlignHorizontalCenter = false;
            if (this.isStretchWidth) {
              this._originalWidth = this.node.width;
              false;
            }
          } else {
            this.isAlignVerticalCenter = false;
            if (this.isStretchHeight) {
              this._originalHeight = this.node.height;
              false;
            }
          }
          false;
        } else {
          isHorizontal ? this.isStretchWidth && (this.node.width = this._originalWidth) : this.isStretchHeight && (this.node.height = this._originalHeight);
          this._alignFlags &= ~flag;
        }
      },
      updateAlignment: function() {
        WidgetManager.updateAlignment(this.node);
      }
    });
    cc.Widget = module.exports = Widget;
  }), {
    "../base-ui/CCWidgetManager": 59,
    "./CCComponent": 76
  } ],
  103: [ (function(require, module, exports) {
    require("./CCComponent");
    require("./CCRendererInSG");
    require("./CCRendererUnderSG");
    require("./CCComponentEventHandler");
    require("./missing-script");
    module.exports = [ require("./CCSprite"), require("./CCWidget"), require("./CCCanvas"), require("./CCAudioSource"), require("./CCAnimation"), require("./CCButton"), require("./CCLabel"), require("./CCProgressBar"), require("./CCMask"), require("./CCScrollBar"), require("./CCScrollView"), require("./CCPageViewIndicator"), require("./CCPageView"), require("./CCSlider"), require("./CCLayout"), require("./CCEditBox"), require("./CCVideoPlayer"), require("./CCWebView"), require("./CCSpriteDistortion"), require("./CCLabelOutline"), require("./CCRichText"), require("./CCToggleContainer"), require("./CCToggleGroup"), require("./CCToggle"), require("./CCBlockInputEvents") ];
  }), {
    "./CCAnimation": 71,
    "./CCAudioSource": 72,
    "./CCBlockInputEvents": 73,
    "./CCButton": 74,
    "./CCCanvas": 75,
    "./CCComponent": 76,
    "./CCComponentEventHandler": 77,
    "./CCEditBox": 78,
    "./CCLabel": 79,
    "./CCLabelOutline": 80,
    "./CCLayout": 81,
    "./CCMask": 82,
    "./CCPageView": 83,
    "./CCPageViewIndicator": 84,
    "./CCProgressBar": 85,
    "./CCRendererInSG": 86,
    "./CCRendererUnderSG": 87,
    "./CCRichText": 88,
    "./CCScrollBar": 90,
    "./CCScrollView": 91,
    "./CCSlider": 92,
    "./CCSprite": 93,
    "./CCSpriteDistortion": 94,
    "./CCToggle": 96,
    "./CCToggleContainer": 97,
    "./CCToggleGroup": 98,
    "./CCVideoPlayer": 99,
    "./CCWebView": 101,
    "./CCWidget": 102,
    "./missing-script": 104
  } ],
  104: [ (function(require, module, exports) {
    var JS = cc.js;
    var BUILTIN_CLASSID_RE = require("../utils/misc").BUILTIN_CLASSID_RE;
    var MissingClass = cc.Class({
      name: "cc.MissingClass",
      properties: {
        _$erialized: {
          default: null,
          visible: false,
          editorOnly: true
        }
      }
    });
    var MissingScript = cc.Class({
      name: "cc.MissingScript",
      extends: cc.Component,
      editor: {
        inspector: "packages://inspector/inspectors/comps/missing-script.js"
      },
      properties: {
        compiled: {
          default: false,
          serializable: false
        },
        _$erialized: {
          default: null,
          visible: false,
          editorOnly: true
        }
      },
      ctor: false,
      statics: {
        safeFindClass: function(id, data) {
          var cls = JS._getClassById(id);
          if (cls) return cls;
          if (id) {
            cc.deserialize.reportMissingClass(id);
            return MissingScript.getMissingWrapper(id, data);
          }
          return null;
        },
        getMissingWrapper: function(id, data) {
          return data.node && (/^[0-9a-zA-Z+/]{23}$/.test(id) || BUILTIN_CLASSID_RE.test(id)) ? MissingScript : MissingClass;
        }
      },
      onLoad: function() {
        cc.warnID(4600, this.node.name);
      }
    });
    cc._MissingScript = module.exports = MissingScript;
  }), {
    "../utils/misc": 225
  } ],
  105: [ (function(require, module, exports) {
    var SCROLLY = 40;
    var LEFT_PADDING = 2;
    var DELAY_TIME = 400;
    var FOCUS_DELAY_UC = 400;
    var FOCUS_DELAY_FIREFOX = 0;
    var Utils = require("../platform/utils");
    var sys = require("../platform/CCSys");
    function adjustEditBoxPosition(editBox) {
      var worldPos = editBox.convertToWorldSpace(cc.p(0, 0));
      var windowHeight = cc.visibleRect.height;
      var windowWidth = cc.visibleRect.width;
      var factor = .5;
      windowWidth > windowHeight && (factor = .7);
      setTimeout((function() {
        if (window.scrollY < SCROLLY && worldPos.y < windowHeight * factor) {
          var scrollOffset = windowHeight * factor - worldPos.y - window.scrollY;
          scrollOffset < 35 && (scrollOffset = 35);
          scrollOffset > 320 && (scrollOffset = 320);
          window.scrollTo(scrollOffset, scrollOffset);
        }
      }), DELAY_TIME);
    }
    var capitalize = function(string) {
      return string.replace(/(?:^|\s)\S/g, (function(a) {
        return a.toUpperCase();
      }));
    };
    function capitalizeFirstLetter(string) {
      return string.charAt(0).toUpperCase() + string.slice(1);
    }
    var KeyboardReturnType = cc.Enum({
      DEFAULT: 0,
      DONE: 1,
      SEND: 2,
      SEARCH: 3,
      GO: 4
    });
    var InputMode = cc.Enum({
      ANY: 0,
      EMAIL_ADDR: 1,
      NUMERIC: 2,
      PHONE_NUMBER: 3,
      URL: 4,
      DECIMAL: 5,
      SINGLE_LINE: 6
    });
    var InputFlag = cc.Enum({
      PASSWORD: 0,
      SENSITIVE: 1,
      INITIAL_CAPS_WORD: 2,
      INITIAL_CAPS_SENTENCE: 3,
      INITIAL_CAPS_ALL_CHARACTERS: 4,
      DEFAULT: 5
    });
    cc.EditBoxDelegate = cc._Class.extend({
      editBoxEditingDidBegan: function(sender) {},
      editBoxEditingDidEnded: function(sender) {},
      editBoxTextChanged: function(sender, text) {},
      editBoxEditingReturn: function(sender) {}
    });
    _ccsg.EditBox = _ccsg.Node.extend({
      _backgroundSprite: null,
      _delegate: null,
      _editBoxInputMode: InputMode.ANY,
      _editBoxInputFlag: InputFlag.DEFAULT,
      _keyboardReturnType: KeyboardReturnType.DEFAULT,
      _maxLength: 50,
      _text: "",
      _placeholderText: "",
      _alwaysOnTop: false,
      _placeholderFontName: "",
      _placeholderFontSize: 14,
      __fullscreen: false,
      __autoResize: false,
      _placeholderColor: null,
      _className: "EditBox",
      ctor: function(size, normal9SpriteBg) {
        _ccsg.Node.prototype.ctor.call(this);
        this._textColor = cc.Color.WHITE;
        this._placeholderColor = cc.Color.GRAY;
        this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg);
        this._renderCmd._createLabels();
      },
      _createRenderCmd: function() {
        return cc._renderType === cc.game.RENDER_TYPE_CANVAS ? new _ccsg.EditBox.CanvasRenderCmd(this) : new _ccsg.EditBox.WebGLRenderCmd(this);
      },
      setContentSize: function(width, height) {
        if (void 0 !== width.width && void 0 !== width.height) {
          height = width.height;
          width = width.width;
        }
        _ccsg.Node.prototype.setContentSize.call(this, width, height);
        this._updateEditBoxSize(width, height);
      },
      setVisible: function(visible) {
        _ccsg.Node.prototype.setVisible.call(this, visible);
        this._renderCmd.updateVisibility();
      },
      createDomElementIfNeeded: function() {
        this._renderCmd._edTxt || this._renderCmd.setInputMode(this._editBoxInputMode);
      },
      setTabIndex: function(index) {
        this._renderCmd._edTxt && (this._renderCmd._edTxt.tabIndex = index);
      },
      getTabIndex: function() {
        if (this._renderCmd._edTxt) return this._renderCmd._edTxt.tabIndex;
        cc.warnID(4700);
        return -1;
      },
      setFocus: function() {
        this._renderCmd._edTxt && this._renderCmd._edTxt.focus();
      },
      isFocused: function() {
        if (this._renderCmd._edTxt) return document.activeElement === this._renderCmd._edTxt;
        cc.warnID(4700);
        return false;
      },
      stayOnTop: function(flag) {
        if (this._alwaysOnTop === flag) return;
        this._alwaysOnTop = flag;
        this._renderCmd.stayOnTop(this._alwaysOnTop);
      },
      cleanup: function() {
        this._super();
        this._renderCmd.removeDom();
      },
      _onTouchBegan: function(touch) {
        var touchPoint = touch.getLocation();
        var bb = cc.rect(0, 0, this._contentSize.width, this._contentSize.height);
        var hitted = cc.rectContainsPoint(bb, this.convertToNodeSpace(touchPoint));
        if (hitted) return true;
        this._renderCmd._endEditing();
        return false;
      },
      _onTouchEnded: function() {
        this._renderCmd._beginEditing();
      },
      _updateBackgroundSpriteSize: function(width, height) {
        this._backgroundSprite && this._backgroundSprite.setContentSize(width, height);
      },
      _updateEditBoxSize: function(size, height) {
        var newWidth = "number" === typeof size.width ? size.width : size;
        var newHeight = "number" === typeof size.height ? size.height : height;
        this._updateBackgroundSpriteSize(newWidth, newHeight);
        this._renderCmd.updateSize(newWidth, newHeight);
      },
      setLineHeight: function(lineHeight) {
        this._renderCmd.setLineHeight(lineHeight);
      },
      setFont: function(fontName, fontSize) {
        this._renderCmd.setFont(fontName, fontSize);
      },
      _setFont: function(fontStyle) {
        this._renderCmd._setFont(fontStyle);
      },
      getBackgroundSprite: function() {
        return this._backgroundSprite;
      },
      setFontName: function(fontName) {
        this._renderCmd.setFontName(fontName);
      },
      setFontSize: function(fontSize) {
        this._renderCmd.setFontSize(fontSize);
      },
      setString: function(text) {
        text.length >= this._maxLength && (text = text.slice(0, this._maxLength));
        this._text = text;
        this._renderCmd.setString(text);
      },
      setFontColor: function(color) {
        this._textColor = color;
        this._renderCmd.setFontColor(color);
      },
      setMaxLength: function(maxLength) {
        if (!isNaN(maxLength)) {
          maxLength < 0 && (maxLength = 65535);
          this._maxLength = maxLength;
          this._renderCmd.setMaxLength(maxLength);
        }
      },
      getMaxLength: function() {
        return this._maxLength;
      },
      setPlaceHolder: function(text) {
        if (null !== text) {
          this._renderCmd.setPlaceHolder(text);
          this._placeholderText = text;
        }
      },
      setPlaceholderFont: function(fontName, fontSize) {
        this._placeholderFontName = fontName;
        this._placeholderFontSize = fontSize;
        this._renderCmd._updateDOMPlaceholderFontStyle();
      },
      _setPlaceholderFont: function(fontStyle) {
        var res = cc.LabelTTF._fontStyleRE.exec(fontStyle);
        if (res) {
          this._placeholderFontName = res[2];
          this._placeholderFontSize = parseInt(res[1]);
          this._renderCmd._updateDOMPlaceholderFontStyle();
        }
      },
      setPlaceholderFontName: function(fontName) {
        this._placeholderFontName = fontName;
        this._renderCmd._updateDOMPlaceholderFontStyle();
      },
      setPlaceholderFontSize: function(fontSize) {
        this._placeholderFontSize = fontSize;
        this._renderCmd._updateDOMPlaceholderFontStyle();
      },
      setPlaceholderFontColor: function(color) {
        this._placeholderColor = color;
        this._renderCmd.setPlaceholderFontColor(color);
      },
      setInputFlag: function(inputFlag) {
        this._editBoxInputFlag = inputFlag;
        this._renderCmd.setInputFlag(inputFlag);
      },
      getString: function() {
        return this._text;
      },
      initWithSizeAndBackgroundSprite: function(size, normal9SpriteBg) {
        this._backgroundSprite && this._backgroundSprite.removeFromParent();
        this._backgroundSprite = normal9SpriteBg;
        _ccsg.Node.prototype.setContentSize.call(this, size);
        if (this._backgroundSprite && !this._backgroundSprite.parent) {
          this._backgroundSprite.setAnchorPoint(cc.p(0, 0));
          this.addChild(this._backgroundSprite);
          this._updateBackgroundSpriteSize(size.width, size.height);
        }
        this.x = 0;
        this.y = 0;
        return true;
      },
      setDelegate: function(delegate) {
        this._delegate = delegate;
      },
      getPlaceHolder: function() {
        return this._placeholderText;
      },
      setInputMode: function(inputMode) {
        if (this._editBoxInputMode === inputMode) return;
        var oldText = this.getString();
        this._editBoxInputMode = inputMode;
        this._renderCmd.setInputMode(inputMode);
        this._renderCmd.transform();
        this.setString(oldText);
        this._renderCmd._updateLabelPosition(this.getContentSize());
      },
      setReturnType: function(returnType) {
        this._keyboardReturnType = returnType;
        this._renderCmd._updateDomInputType();
      },
      initWithBackgroundColor: function(size, bgColor) {
        this._edWidth = size.width;
        this.dom.style.width = this._edWidth.toString() + "px";
        this._edHeight = size.height;
        this.dom.style.height = this._edHeight.toString() + "px";
        this.dom.style.backgroundColor = cc.colorToHex(bgColor);
      }
    });
    var _p = _ccsg.EditBox.prototype;
    cc.defineGetterSetter(_p, "font", null, _p._setFont);
    cc.defineGetterSetter(_p, "fontName", null, _p.setFontName);
    cc.defineGetterSetter(_p, "fontSize", null, _p.setFontSize);
    cc.defineGetterSetter(_p, "fontColor", null, _p.setFontColor);
    cc.defineGetterSetter(_p, "string", _p.getString, _p.setString);
    cc.defineGetterSetter(_p, "maxLength", _p.getMaxLength, _p.setMaxLength);
    cc.defineGetterSetter(_p, "placeholder", _p.getPlaceHolder, _p.setPlaceHolder);
    cc.defineGetterSetter(_p, "placeholderFont", null, _p._setPlaceholderFont);
    cc.defineGetterSetter(_p, "placeholderFontName", null, _p.setPlaceholderFontName);
    cc.defineGetterSetter(_p, "placeholderFontSize", null, _p.setPlaceholderFontSize);
    cc.defineGetterSetter(_p, "placeholderFontColor", null, _p.setPlaceholderFontColor);
    cc.defineGetterSetter(_p, "inputFlag", null, _p.setInputFlag);
    cc.defineGetterSetter(_p, "delegate", null, _p.setDelegate);
    cc.defineGetterSetter(_p, "inputMode", null, _p.setInputMode);
    cc.defineGetterSetter(_p, "returnType", null, _p.setReturnType);
    _p = null;
    _ccsg.EditBox.InputMode = InputMode;
    _ccsg.EditBox.InputFlag = InputFlag;
    _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType;
    (function(editbox) {
      editbox._polyfill = {
        zoomInvalid: false
      };
      sys.OS_ANDROID !== sys.os || sys.browserType !== sys.BROWSER_TYPE_SOUGOU && sys.browserType !== sys.BROWSER_TYPE_360 || (editbox._polyfill.zoomInvalid = true);
    })(_ccsg.EditBox);
    (function(polyfill) {
      var EditBoxImpl = function() {};
      var proto = EditBoxImpl.prototype = Object.create(Object.prototype);
      proto.updateMatrix = function() {
        if (!this._edTxt) return;
        var node = this._node, scaleX = cc.view._scaleX, scaleY = cc.view._scaleY;
        var dpr = cc.view._devicePixelRatio;
        var t = this._worldTransform;
        scaleX /= dpr;
        scaleY /= dpr;
        var container = cc.game.container;
        var a = t.a * scaleX, b = t.b, c = t.c, d = t.d * scaleY;
        var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft);
        var offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom);
        var tx = t.tx * scaleX + offsetX, ty = t.ty * scaleY + offsetY;
        if (polyfill.zoomInvalid) {
          this.updateSize(node._contentSize.width * a, node._contentSize.height * d);
          a = 1;
          d = 1;
        }
        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.updateVisibility = function() {
        if (!this._edTxt) return;
        this._node.visible ? this._edTxt.style.visibility = "visible" : this._edTxt.style.visibility = "hidden";
      };
      proto.stayOnTop = function(flag) {
        if (flag) {
          this._removeLabels();
          this._edTxt.style.display = "";
        } else {
          this._createLabels();
          this._edTxt.style.display = "none";
          this._showLabels();
        }
      };
      proto._beginEditingOnMobile = function(editBox) {
        this.__orientationChanged = function() {
          adjustEditBoxPosition(editBox);
        };
        window.addEventListener("orientationchange", this.__orientationChanged);
        if (cc.view.isAutoFullScreenEnabled()) {
          this.__fullscreen = true;
          cc.view.enableAutoFullScreen(false);
          cc.screen.exitFullScreen();
        } else this.__fullscreen = false;
        this.__autoResize = cc.view.__resizeWithBrowserSize;
        cc.view.resizeWithBrowserSize(false);
      };
      proto._endEditingOnMobile = function() {
        if (this.__rotateScreen) {
          cc.container.style["-webkit-transform"] = "rotate(90deg)";
          cc.container.style.transform = "rotate(90deg)";
          var view = cc.view;
          var width = view._originalDesignResolutionSize.width;
          var height = view._originalDesignResolutionSize.height;
          width > 0 && view.setDesignResolutionSize(width, height, view._resolutionPolicy);
          this.__rotateScreen = false;
        }
        window.removeEventListener("orientationchange", this.__orientationChanged);
        window.scrollTo(0, 0);
        this.__fullscreen && cc.view.enableAutoFullScreen(true);
        this.__autoResize && cc.view.resizeWithBrowserSize(true);
      };
      proto._onFocusOnMobile = function(editBox) {
        if (cc.view._isRotated) {
          cc.container.style["-webkit-transform"] = "rotate(0deg)";
          cc.container.style.transform = "rotate(0deg)";
          cc.view._isRotated = false;
          var policy = cc.view.getResolutionPolicy();
          policy.apply(cc.view, cc.view.getDesignResolutionSize());
          cc.view._isRotated = true;
          window.scrollTo(35, 35);
          this.__rotateScreen = true;
        } else this.__rotateScreen = false;
        adjustEditBoxPosition(editBox);
      };
      proto._createDomInput = function() {
        this.removeDom();
        var thisPointer = this;
        var tmpEdTxt = this._edTxt = document.createElement("input");
        tmpEdTxt.type = "text";
        tmpEdTxt.style.fontSize = this._edFontSize + "px";
        tmpEdTxt.style.color = "#000000";
        tmpEdTxt.style.border = 0;
        tmpEdTxt.style.background = "transparent";
        tmpEdTxt.style.width = "100%";
        tmpEdTxt.style.height = "100%";
        tmpEdTxt.style.active = 0;
        tmpEdTxt.style.outline = "medium";
        tmpEdTxt.style.padding = "0";
        tmpEdTxt.style.textTransform = "uppercase";
        tmpEdTxt.style.display = "none";
        tmpEdTxt.style.position = "absolute";
        tmpEdTxt.style.bottom = "0px";
        tmpEdTxt.style.left = LEFT_PADDING + "px";
        tmpEdTxt.style["-moz-appearance"] = "textfield";
        tmpEdTxt.style.className = "cocosEditBox";
        function _inputValueHandle(target) {
          var editBox = thisPointer._editBox;
          target.value.length > target.maxLength && (target.value = target.value.slice(0, target.maxLength));
          if (editBox._delegate && editBox._delegate.editBoxTextChanged && editBox._text !== target.value) {
            editBox._text = target.value;
            thisPointer._updateDomTextCases();
            editBox._delegate.editBoxTextChanged(editBox, editBox._text);
          }
        }
        var inputLock = false;
        tmpEdTxt.addEventListener("compositionstart", (function() {
          inputLock = true;
        }));
        tmpEdTxt.addEventListener("compositionend", (function() {
          inputLock = false;
          _inputValueHandle(this);
        }));
        tmpEdTxt.addEventListener("input", (function() {
          if (inputLock) return;
          _inputValueHandle(this);
        }));
        tmpEdTxt.addEventListener("keypress", (function(e) {
          var editBox = thisPointer._editBox;
          if (e.keyCode === cc.KEY.enter) {
            e.stopPropagation();
            e.preventDefault();
            if ("" === this.value) {
              this.style.fontSize = editBox._placeholderFontSize + "px";
              this.style.color = cc.colorToHex(editBox._placeholderColor);
            }
            editBox._text = this.value;
            thisPointer._updateDomTextCases();
            thisPointer._endEditing();
            editBox._delegate && editBox._delegate.editBoxEditingReturn && editBox._delegate.editBoxEditingReturn(editBox);
            cc._canvas.focus();
          }
        }));
        tmpEdTxt.addEventListener("focus", (function() {
          var editBox = thisPointer._editBox;
          this.style.fontSize = thisPointer._edFontSize + "px";
          this.style.color = cc.colorToHex(editBox._textColor);
          thisPointer._hiddenLabels();
          sys.isMobile && thisPointer._onFocusOnMobile(editBox);
          editBox._delegate && editBox._delegate.editBoxEditingDidBegan && editBox._delegate.editBoxEditingDidBegan(editBox);
        }));
        tmpEdTxt.addEventListener("blur", (function() {
          var editBox = thisPointer._editBox;
          editBox._text = this.value;
          thisPointer._updateDomTextCases();
          editBox._delegate && editBox._delegate.editBoxEditingDidEnded && editBox._delegate.editBoxEditingDidEnded(editBox);
          if ("" === this.value) {
            this.style.fontSize = editBox._placeholderFontSize + "px";
            this.style.color = cc.colorToHex(editBox._placeholderColor);
          }
          thisPointer._endEditing();
        }));
        this._addDomToGameContainer();
        return tmpEdTxt;
      };
      proto._createDomTextArea = function() {
        this.removeDom();
        var thisPointer = this;
        var tmpEdTxt = this._edTxt = document.createElement("textarea");
        tmpEdTxt.type = "text";
        tmpEdTxt.style.fontSize = this._edFontSize + "px";
        tmpEdTxt.style.color = "#000000";
        tmpEdTxt.style.border = 0;
        tmpEdTxt.style.background = "transparent";
        tmpEdTxt.style.width = "100%";
        tmpEdTxt.style.height = "100%";
        tmpEdTxt.style.active = 0;
        tmpEdTxt.style.outline = "medium";
        tmpEdTxt.style.padding = "0";
        tmpEdTxt.style.resize = "none";
        tmpEdTxt.style.textTransform = "uppercase";
        tmpEdTxt.style.overflow_y = "scroll";
        tmpEdTxt.style.display = "none";
        tmpEdTxt.style.position = "absolute";
        tmpEdTxt.style.bottom = "0px";
        tmpEdTxt.style.left = LEFT_PADDING + "px";
        tmpEdTxt.style.className = "cocosEditBox";
        function _inputValueHandle(target) {
          target.value.length > target.maxLength && (target.value = target.value.slice(0, target.maxLength));
          var editBox = thisPointer._editBox;
          if (editBox._delegate && editBox._delegate.editBoxTextChanged && editBox._text.toLowerCase() !== target.value.toLowerCase()) {
            editBox._text = target.value;
            thisPointer._updateDomTextCases();
            editBox._delegate.editBoxTextChanged(editBox, editBox._text);
          }
        }
        var inputLock = false;
        tmpEdTxt.addEventListener("compositionstart", (function() {
          inputLock = true;
        }));
        tmpEdTxt.addEventListener("compositionend", (function() {
          inputLock = false;
          _inputValueHandle(this);
        }));
        tmpEdTxt.addEventListener("input", (function() {
          if (inputLock) return;
          _inputValueHandle(this);
        }));
        tmpEdTxt.addEventListener("focus", (function() {
          var editBox = thisPointer._editBox;
          thisPointer._hiddenLabels();
          this.style.fontSize = thisPointer._edFontSize + "px";
          this.style.color = cc.colorToHex(editBox._textColor);
          sys.isMobile && thisPointer._onFocusOnMobile(editBox);
          editBox._delegate && editBox._delegate.editBoxEditingDidBegan && editBox._delegate.editBoxEditingDidBegan(editBox);
        }));
        tmpEdTxt.addEventListener("keypress", (function(e) {
          var editBox = thisPointer._editBox;
          if (e.keyCode === cc.KEY.enter) {
            e.stopPropagation();
            editBox._delegate && editBox._delegate.editBoxEditingReturn && editBox._delegate.editBoxEditingReturn(editBox);
          }
        }));
        tmpEdTxt.addEventListener("blur", (function() {
          var editBox = thisPointer._editBox;
          editBox._text = this.value;
          thisPointer._updateDomTextCases();
          editBox._delegate && editBox._delegate.editBoxEditingDidEnded && editBox._delegate.editBoxEditingDidEnded(editBox);
          if ("" === this.value) {
            this.style.fontSize = editBox._placeholderFontSize + "px";
            this.style.color = cc.colorToHex(editBox._placeholderColor);
          }
          thisPointer._endEditing();
        }));
        this._addDomToGameContainer();
        return tmpEdTxt;
      };
      proto._createWXInput = function(multiline) {
        this.removeDom();
        var thisPointer = this;
        var tmpEdTxt = this._edTxt = document.createElement("input");
        tmpEdTxt.type = "text";
        tmpEdTxt.focus = function() {
          var editBox = thisPointer._editBox;
          wx.showKeyboard({
            defaultValue: editBox._text,
            maxLength: 140,
            multiple: multiline,
            confirmHold: true,
            confirmType: "done",
            success: function(res) {
              editBox._delegate && editBox._delegate.editBoxEditingDidBegan && editBox._delegate.editBoxEditingDidBegan(editBox);
            },
            fail: function(res) {
              cc.warn(res.errMsg);
              thisPointer._endEditing();
            }
          });
          wx.onKeyboardConfirm((function(res) {
            editBox._text = res.value;
            thisPointer._updateDomTextCases();
            editBox._delegate && editBox._delegate.editBoxEditingReturn && editBox._delegate.editBoxEditingReturn(editBox);
            wx.hideKeyboard({
              success: function(res) {
                editBox._delegate && editBox._delegate.editBoxEditingDidEnded && editBox._delegate.editBoxEditingDidEnded(editBox);
              },
              fail: function(res) {
                cc.warn(res.errMsg);
              }
            });
          }));
          wx.onKeyboardInput((function(res) {
            if (editBox._delegate && editBox._delegate.editBoxTextChanged && editBox._text !== res.value) {
              editBox._text = res.value;
              thisPointer._updateDomTextCases();
              editBox._delegate.editBoxTextChanged(editBox, editBox._text);
            }
          }));
          wx.onKeyboardComplete((function() {
            thisPointer._endEditing();
            wx.offKeyboardConfirm();
            wx.offKeyboardInput();
            wx.offKeyboardComplete();
          }));
        };
      };
      proto._createLabels = function() {
        var editBoxSize = this._editBox.getContentSize();
        if (!this._textLabel) {
          this._textLabel = _ccsg.Label.pool.get();
          this._textLabel.setAnchorPoint(cc.p(0, 1));
          this._textLabel.setOverflow(_ccsg.Label.Overflow.CLAMP);
          this._editBox.addChild(this._textLabel, 100);
        }
        if (!this._placeholderLabel) {
          this._placeholderLabel = _ccsg.Label.pool.get();
          this._placeholderLabel.setAnchorPoint(cc.p(0, 1));
          this._placeholderLabel.setColor(cc.Color.GRAY);
          this._editBox.addChild(this._placeholderLabel, 100);
        }
        this._updateLabelPosition(editBoxSize);
      };
      proto._removeLabels = function() {
        if (!this._textLabel) return;
        this._editBox.removeChild(this._textLabel);
        this._textLabel = null;
      };
      proto._updateLabelPosition = function(editBoxSize) {
        if (!this._textLabel || !this._placeholderLabel) return;
        var labelContentSize = cc.size(editBoxSize.width - LEFT_PADDING, editBoxSize.height);
        this._textLabel.setContentSize(labelContentSize);
        this._placeholderLabel.setLineHeight(editBoxSize.height);
        var placeholderLabelSize = this._placeholderLabel.getContentSize();
        if (this._editBox._editBoxInputMode === InputMode.ANY) {
          this._textLabel.setPosition(LEFT_PADDING, editBoxSize.height);
          this._placeholderLabel.setPosition(LEFT_PADDING, editBoxSize.height);
          this._placeholderLabel.setVerticalAlign(cc.VerticalTextAlignment.TOP);
          this._textLabel.setVerticalAlign(cc.VerticalTextAlignment.TOP);
          this._textLabel.enableWrapText(true);
        } else {
          this._textLabel.enableWrapText(false);
          this._textLabel.setPosition(LEFT_PADDING, editBoxSize.height);
          this._placeholderLabel.setPosition(LEFT_PADDING, (editBoxSize.height + placeholderLabelSize.height) / 2);
          this._placeholderLabel.setVerticalAlign(cc.VerticalTextAlignment.CENTER);
          this._textLabel.setVerticalAlign(cc.VerticalTextAlignment.CENTER);
        }
      };
      proto.setLineHeight = function(lineHeight) {
        this._textLabel && this._textLabel.setLineHeight(lineHeight);
      };
      proto._hiddenLabels = function() {
        this._textLabel && this._textLabel.setVisible(false);
        this._placeholderLabel && this._placeholderLabel.setVisible(false);
      };
      proto._updateDomTextCases = function() {
        var inputFlag = this._editBox._editBoxInputFlag;
        inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS ? this._editBox._text = this._editBox._text.toUpperCase() : inputFlag === InputFlag.INITIAL_CAPS_WORD ? this._editBox._text = capitalize(this._editBox._text) : inputFlag === InputFlag.INITIAL_CAPS_SENTENCE && (this._editBox._text = capitalizeFirstLetter(this._editBox._text));
      };
      proto._updateLabelStringStyle = function() {
        if ("password" === this._edTxt.type) {
          var passwordString = "";
          var len = this._editBox._text.length;
          for (var i = 0; i < len; ++i) passwordString += "●";
          this._textLabel && this._textLabel.setString(passwordString);
        } else {
          this._updateDomTextCases();
          this._textLabel && this._textLabel.setString(this._editBox._text);
        }
      };
      proto._showLabels = function() {
        this._hiddenLabels();
        var text = sys.platform === sys.WECHAT_GAME ? this._editBox._text : this._edTxt.value;
        if ("" === text) {
          if (this._placeholderLabel) {
            this._placeholderLabel.setVisible(true);
            this._placeholderLabel.setString(this._editBox._placeholderText);
          }
        } else if (this._textLabel) {
          this._textLabel.setVisible(true);
          this._textLabel.setString(this._editBox._text);
        }
        this._updateLabelStringStyle();
      };
      proto._beginEditing = function() {
        var self = this;
        if (sys.platform === sys.WECHAT_GAME) this._edTxt.focus(); else if (!self._editBox._alwaysOnTop && "none" === self._edTxt.style.display) {
          self._edTxt.style.display = "";
          function startFocus() {
            self._edTxt.focus();
          }
          sys.browserType === sys.BROWSER_TYPE_UC ? setTimeout(startFocus, FOCUS_DELAY_UC) : sys.browserType === sys.BROWSER_TYPE_FIREFOX ? setTimeout(startFocus, FOCUS_DELAY_FIREFOX) : startFocus();
        }
        sys.isMobile && !self._editingMode && self._beginEditingOnMobile(self._editBox);
        self._editingMode = true;
      };
      proto._endEditing = function() {
        this._editBox._alwaysOnTop || (this._edTxt.style.display = "none");
        this._showLabels();
        if (sys.platform !== sys.WECHAT_GAME && sys.isMobile && this._editingMode) {
          var self = this;
          setTimeout((function() {
            self._endEditingOnMobile();
          }), DELAY_TIME);
        }
        this._editingMode = false;
      };
      proto._setFont = function(fontStyle) {
        var res = cc.LabelTTF._fontStyleRE.exec(fontStyle);
        var textFontName = res[2];
        var textFontSize = parseInt(res[1]);
        res && this.setFont(textFontName, textFontSize);
      };
      proto.setFont = function(fontName, fontSize) {
        this._edFontName = fontName || this._edFontName;
        this._edFontSize = fontSize || this._edFontSize;
        this._updateDOMFontStyle();
      };
      proto.setFontName = function(fontName) {
        this._edFontName = fontName || this._edFontName;
        this._updateDOMFontStyle();
      };
      proto.setFontSize = function(fontSize) {
        this._edFontSize = fontSize || this._edFontSize;
        this._updateDOMFontStyle();
      };
      proto.setFontColor = function(color) {
        if (!this._edTxt) return;
        this._edTxt.value !== this._editBox._placeholderText && (this._edTxt.style.color = cc.colorToHex(color));
        this._textLabel && this._textLabel.setColor(color);
      };
      proto.setPlaceHolder = function(text) {
        this._placeholderLabel.setString(text);
      };
      proto.setMaxLength = function(maxLength) {
        if (!this._edTxt) return;
        this._edTxt.maxLength = maxLength;
      };
      proto._updateDOMPlaceholderFontStyle = function() {
        this._placeholderLabel.setFontFamily(this._editBox._placeholderFontName);
        this._placeholderLabel.setFontSize(this._editBox._placeholderFontSize);
      };
      proto.setPlaceholderFontColor = function(color) {
        this._placeholderLabel.setColor(color);
      };
      proto._updateDomInputType = function() {
        var inputMode = this._editBox._editBoxInputMode;
        if (inputMode === InputMode.EMAIL_ADDR) this._edTxt.type = "email"; else if (inputMode === InputMode.NUMERIC || inputMode === InputMode.DECIMAL) this._edTxt.type = "number"; else if (inputMode === InputMode.PHONE_NUMBER) {
          this._edTxt.type = "number";
          this._edTxt.pattern = "[0-9]*";
        } else if (inputMode === InputMode.URL) this._edTxt.type = "url"; else {
          this._edTxt.type = "text";
          this._editBox._keyboardReturnType === KeyboardReturnType.SEARCH && (this._edTxt.type = "search");
        }
        this._editBox._editBoxInputFlag === InputFlag.PASSWORD && (this._edTxt.type = "password");
      };
      proto.setInputFlag = function(inputFlag) {
        if (!this._edTxt) return;
        this._updateDomInputType();
        this._edTxt.style.textTransform = "none";
        inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS ? this._edTxt.style.textTransform = "uppercase" : inputFlag === InputFlag.INITIAL_CAPS_WORD && (this._edTxt.style.textTransform = "capitalize");
        this._updateLabelStringStyle();
      };
      proto.setInputMode = function(inputMode) {
        sys.platform === sys.WECHAT_GAME ? this._createWXInput(inputMode === InputMode.ANY) : inputMode === InputMode.ANY ? this._createDomTextArea() : this._createDomInput();
        this._updateDomInputType();
        var contentSize = this._node.getContentSize();
        this.updateSize(contentSize.width, contentSize.height);
      };
      proto.setString = function(text) {
        if (!this._edTxt) return;
        if (null !== text) {
          this._edTxt.value = text;
          if ("" === text) {
            if (this._placeholderLabel) {
              this._placeholderLabel.setString(this._editBox._placeholderText);
              this._placeholderLabel.setColor(this._editBox._placeholderColor);
            }
            if (!this._editingMode) {
              this._placeholderLabel && this._placeholderLabel.setVisible(true);
              this._textLabel && this._textLabel.setVisible(false);
            }
          } else {
            this._edTxt.style.color = cc.colorToHex(this._editBox._textColor);
            this._textLabel && this._textLabel.setColor(this._editBox._textColor);
            if (!this._editingMode) {
              this._placeholderLabel && this._placeholderLabel.setVisible(false);
              this._textLabel && this._textLabel.setVisible(true);
            }
            this._updateLabelStringStyle();
          }
        }
      };
      proto._updateDOMFontStyle = function() {
        if (!this._edTxt) return;
        if ("" !== this._edTxt.value) {
          this._edTxt.style.fontFamily = this._edFontName;
          this._edTxt.style.fontSize = this._edFontSize + "px";
        }
        if (this._textLabel) {
          this._textLabel.setFontSize(this._edFontSize);
          this._textLabel.setFontFamily(this._edFontName);
        }
      };
      proto.updateSize = function(newWidth, newHeight) {
        var editboxDomNode = this._edTxt;
        if (!editboxDomNode) return;
        editboxDomNode.style["width"] = newWidth + "px";
        editboxDomNode.style["height"] = newHeight + "px";
        this._updateLabelPosition(cc.size(newWidth, newHeight));
      };
      proto._addDomToGameContainer = function() {
        cc.game.container.appendChild(this._edTxt);
      };
      proto.removeDom = function() {
        var editBox = this._edTxt;
        if (editBox) {
          var hasChild = Utils.contains(cc.game.container, editBox);
          hasChild && cc.game.container.removeChild(editBox);
        }
        this._edTxt = null;
      };
      proto.initializeRenderCmd = function(node) {
        this._editBox = node;
        this._edFontSize = 14;
        this._edFontName = "Arial";
        this._textLabel = null;
        this._placeholderLabel = null;
        this._editingMode = false;
        this.__fullscreen = false;
        this.__autoResize = false;
        this.__rotateScreen = false;
        this.__orientationChanged = null;
      };
      _ccsg.EditBox.CanvasRenderCmd = function(node) {
        this._rootCtor(node);
        this.initializeRenderCmd(node);
      };
      var canvasRenderCmdProto = _ccsg.EditBox.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
      cc.js.mixin(canvasRenderCmdProto, proto);
      canvasRenderCmdProto.constructor = _ccsg.EditBox.CanvasRenderCmd;
      canvasRenderCmdProto.transform = function(parentCmd, recursive) {
        this.originTransform(parentCmd, recursive);
        this.updateMatrix();
      };
      _ccsg.EditBox.WebGLRenderCmd = function(node) {
        this._rootCtor(node);
        this.initializeRenderCmd(node);
      };
      var webGLRenderCmdProto = _ccsg.EditBox.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype);
      cc.js.mixin(webGLRenderCmdProto, proto);
      webGLRenderCmdProto.constructor = _ccsg.EditBox.WebGLRenderCmd;
      webGLRenderCmdProto.transform = function(parentCmd, recursive) {
        this.originTransform(parentCmd, recursive);
        this.updateMatrix();
      };
    })(_ccsg.EditBox._polyfill);
  }), {
    "../platform/CCSys": 184,
    "../platform/utils": 200
  } ],
  106: [ (function(require, module, exports) {
    var JS = cc.js;
    require("../event/event");
    var EventMouse = function(eventType, bubbles) {
      cc.Event.call(this, cc.Event.MOUSE, bubbles);
      this._eventType = eventType;
      this._button = 0;
      this._x = 0;
      this._y = 0;
      this._prevX = 0;
      this._prevY = 0;
      this._scrollX = 0;
      this._scrollY = 0;
    };
    JS.extend(EventMouse, cc.Event);
    var proto = EventMouse.prototype;
    proto.setScrollData = function(scrollX, scrollY) {
      this._scrollX = scrollX;
      this._scrollY = scrollY;
    };
    proto.getScrollX = function() {
      return this._scrollX;
    };
    proto.getScrollY = function() {
      return this._scrollY;
    };
    proto.setLocation = function(x, y) {
      this._x = x;
      this._y = y;
    };
    proto.getLocation = function() {
      return {
        x: this._x,
        y: this._y
      };
    };
    proto.getLocationInView = function() {
      return {
        x: this._x,
        y: cc.view._designResolutionSize.height - this._y
      };
    };
    proto._setPrevCursor = function(x, y) {
      this._prevX = x;
      this._prevY = y;
    };
    proto.getPreviousLocation = function() {
      return {
        x: this._prevX,
        y: this._prevY
      };
    };
    proto.getDelta = function() {
      return {
        x: this._x - this._prevX,
        y: this._y - this._prevY
      };
    };
    proto.getDeltaX = function() {
      return this._x - this._prevX;
    };
    proto.getDeltaY = function() {
      return this._y - this._prevY;
    };
    proto.setButton = function(button) {
      this._button = button;
    };
    proto.getButton = function() {
      return this._button;
    };
    proto.getLocationX = function() {
      return this._x;
    };
    proto.getLocationY = function() {
      return this._y;
    };
    EventMouse.NONE = 0;
    EventMouse.DOWN = 1;
    EventMouse.UP = 2;
    EventMouse.MOVE = 3;
    EventMouse.SCROLL = 4;
    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 = function(touchArr, bubbles) {
      cc.Event.call(this, cc.Event.TOUCH, bubbles);
      this._eventCode = 0;
      this._touches = touchArr || [];
      this.touch = null;
      this.currentTouch = null;
    };
    JS.extend(EventTouch, cc.Event);
    proto = EventTouch.prototype;
    proto.getEventCode = function() {
      return this._eventCode;
    };
    proto.getTouches = function() {
      return this._touches;
    };
    proto._setEventCode = function(eventCode) {
      this._eventCode = eventCode;
    };
    proto._setTouches = function(touches) {
      this._touches = touches;
    };
    proto.setLocation = function(x, y) {
      this.touch && this.touch.setTouchInfo(this.touch.getID(), x, y);
    };
    proto.getLocation = function() {
      return this.touch ? this.touch.getLocation() : cc.v2();
    };
    proto.getLocationInView = function() {
      return this.touch ? this.touch.getLocationInView() : cc.v2();
    };
    proto.getPreviousLocation = function() {
      return this.touch ? this.touch.getPreviousLocation() : cc.v2();
    };
    proto.getStartLocation = function() {
      return this.touch ? this.touch.getStartLocation() : cc.v2();
    };
    proto.getID = function() {
      return this.touch ? this.touch.getID() : null;
    };
    proto.getDelta = function() {
      return this.touch ? this.touch.getDelta() : cc.v2();
    };
    proto.getDeltaX = function() {
      return this.touch ? this.touch.getDelta().x : 0;
    };
    proto.getDeltaY = function() {
      return this.touch ? this.touch.getDelta().y : 0;
    };
    proto.getLocationX = function() {
      return this.touch ? this.touch.getLocationX() : 0;
    };
    proto.getLocationY = function() {
      return this.touch ? this.touch.getLocationY() : 0;
    };
    EventTouch.MAX_TOUCHES = 5;
    EventTouch.BEGAN = 0;
    EventTouch.MOVED = 1;
    EventTouch.ENDED = 2;
    EventTouch.CANCELED = 3;
    var EventAcceleration = function(acc, bubbles) {
      cc.Event.call(this, cc.Event.ACCELERATION, bubbles);
      this.acc = acc;
    };
    JS.extend(EventAcceleration, cc.Event);
    var EventKeyboard = function(keyCode, isPressed, bubbles) {
      cc.Event.call(this, cc.Event.KEYBOARD, bubbles);
      this.keyCode = keyCode;
      this.isPressed = isPressed;
    };
    JS.extend(EventKeyboard, cc.Event);
    cc.Event.EventMouse = EventMouse;
    cc.Event.EventTouch = EventTouch;
    cc.Event.EventAcceleration = EventAcceleration;
    cc.Event.EventKeyboard = EventKeyboard;
    module.exports = cc.Event;
  }), {
    "../event/event": 113
  } ],
  107: [ (function(require, module, exports) {
    cc.EventListener = cc._Class.extend({
      ctor: function(type, listenerID, callback) {
        this._onEvent = callback;
        this._type = type || 0;
        this._listenerID = listenerID || "";
        this._registered = false;
        this._fixedPriority = 0;
        this._node = null;
        this._target = null;
        this._paused = true;
        this._isEnabled = true;
      },
      _setPaused: function(paused) {
        this._paused = paused;
      },
      _isPaused: function() {
        return this._paused;
      },
      _setRegistered: function(registered) {
        this._registered = registered;
      },
      _isRegistered: function() {
        return this._registered;
      },
      _getType: function() {
        return this._type;
      },
      _getListenerID: function() {
        return this._listenerID;
      },
      _setFixedPriority: function(fixedPriority) {
        this._fixedPriority = fixedPriority;
      },
      _getFixedPriority: function() {
        return this._fixedPriority;
      },
      _setSceneGraphPriority: function(node) {
        this._target = node;
        this._node = node;
      },
      _getSceneGraphPriority: function() {
        return this._node;
      },
      checkAvailable: function() {
        return null !== this._onEvent;
      },
      clone: function() {
        return null;
      },
      setEnabled: function(enabled) {
        this._isEnabled = enabled;
      },
      isEnabled: function() {
        return this._isEnabled;
      },
      retain: function() {},
      release: function() {}
    });
    cc.EventListener.UNKNOWN = 0;
    cc.EventListener.TOUCH_ONE_BY_ONE = 1;
    cc.EventListener.TOUCH_ALL_AT_ONCE = 2;
    cc.EventListener.KEYBOARD = 3;
    cc.EventListener.MOUSE = 4;
    cc.EventListener.ACCELERATION = 6;
    cc.EventListener.CUSTOM = 8;
    cc._EventListenerCustom = cc.EventListener.extend({
      _onCustomEvent: null,
      ctor: function(listenerId, callback) {
        this._onCustomEvent = callback;
        cc.EventListener.prototype.ctor.call(this, cc.EventListener.CUSTOM, listenerId, this._callback);
      },
      _callback: function(event) {
        null !== this._onCustomEvent && this._onCustomEvent(event);
      },
      checkAvailable: function() {
        return cc.EventListener.prototype.checkAvailable.call(this) && null !== this._onCustomEvent;
      },
      clone: function() {
        return new cc._EventListenerCustom(this._listenerID, this._onCustomEvent);
      }
    });
    cc._EventListenerMouse = cc.EventListener.extend({
      onMouseDown: null,
      onMouseUp: null,
      onMouseMove: null,
      onMouseScroll: null,
      ctor: function() {
        cc.EventListener.prototype.ctor.call(this, cc.EventListener.MOUSE, cc._EventListenerMouse.LISTENER_ID, this._callback);
      },
      _callback: function(event) {
        var eventType = cc.Event.EventMouse;
        switch (event._eventType) {
         case eventType.DOWN:
          this.onMouseDown && this.onMouseDown(event);
          break;

         case eventType.UP:
          this.onMouseUp && this.onMouseUp(event);
          break;

         case eventType.MOVE:
          this.onMouseMove && this.onMouseMove(event);
          break;

         case eventType.SCROLL:
          this.onMouseScroll && this.onMouseScroll(event);
        }
      },
      clone: function() {
        var eventListener = new cc._EventListenerMouse();
        eventListener.onMouseDown = this.onMouseDown;
        eventListener.onMouseUp = this.onMouseUp;
        eventListener.onMouseMove = this.onMouseMove;
        eventListener.onMouseScroll = this.onMouseScroll;
        return eventListener;
      },
      checkAvailable: function() {
        return true;
      }
    });
    cc._EventListenerMouse.LISTENER_ID = "__cc_mouse";
    cc._EventListenerTouchOneByOne = cc.EventListener.extend({
      _claimedTouches: null,
      swallowTouches: false,
      onTouchBegan: null,
      onTouchMoved: null,
      onTouchEnded: null,
      onTouchCancelled: null,
      ctor: function() {
        cc.EventListener.prototype.ctor.call(this, cc.EventListener.TOUCH_ONE_BY_ONE, cc._EventListenerTouchOneByOne.LISTENER_ID, null);
        this._claimedTouches = [];
      },
      setSwallowTouches: function(needSwallow) {
        this.swallowTouches = needSwallow;
      },
      isSwallowTouches: function() {
        return this.swallowTouches;
      },
      clone: function() {
        var eventListener = new cc._EventListenerTouchOneByOne();
        eventListener.onTouchBegan = this.onTouchBegan;
        eventListener.onTouchMoved = this.onTouchMoved;
        eventListener.onTouchEnded = this.onTouchEnded;
        eventListener.onTouchCancelled = this.onTouchCancelled;
        eventListener.swallowTouches = this.swallowTouches;
        return eventListener;
      },
      checkAvailable: function() {
        if (!this.onTouchBegan) {
          cc.logID(1801);
          return false;
        }
        return true;
      }
    });
    cc._EventListenerTouchOneByOne.LISTENER_ID = "__cc_touch_one_by_one";
    cc._EventListenerTouchAllAtOnce = cc.EventListener.extend({
      onTouchesBegan: null,
      onTouchesMoved: null,
      onTouchesEnded: null,
      onTouchesCancelled: null,
      ctor: function() {
        cc.EventListener.prototype.ctor.call(this, cc.EventListener.TOUCH_ALL_AT_ONCE, cc._EventListenerTouchAllAtOnce.LISTENER_ID, null);
      },
      clone: function() {
        var eventListener = new cc._EventListenerTouchAllAtOnce();
        eventListener.onTouchesBegan = this.onTouchesBegan;
        eventListener.onTouchesMoved = this.onTouchesMoved;
        eventListener.onTouchesEnded = this.onTouchesEnded;
        eventListener.onTouchesCancelled = this.onTouchesCancelled;
        return eventListener;
      },
      checkAvailable: function() {
        if (null === this.onTouchesBegan && null === this.onTouchesMoved && null === this.onTouchesEnded && null === this.onTouchesCancelled) {
          cc.logID(1802);
          return false;
        }
        return true;
      }
    });
    cc._EventListenerTouchAllAtOnce.LISTENER_ID = "__cc_touch_all_at_once";
    cc.EventListener.create = function(argObj) {
      cc.assertID(argObj && argObj.event, 1900);
      var listenerType = argObj.event;
      delete argObj.event;
      var listener = null;
      if (listenerType === cc.EventListener.TOUCH_ONE_BY_ONE) listener = new cc._EventListenerTouchOneByOne(); else if (listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE) listener = new cc._EventListenerTouchAllAtOnce(); else if (listenerType === cc.EventListener.MOUSE) listener = new cc._EventListenerMouse(); else if (listenerType === cc.EventListener.CUSTOM) {
        listener = new cc._EventListenerCustom(argObj.eventName, argObj.callback);
        delete argObj.eventName;
        delete argObj.callback;
      } else if (listenerType === cc.EventListener.KEYBOARD) listener = new cc._EventListenerKeyboard(); else if (listenerType === cc.EventListener.ACCELERATION) {
        listener = new cc._EventListenerAcceleration(argObj.callback);
        delete argObj.callback;
      }
      for (var key in argObj) listener[key] = argObj[key];
      return listener;
    };
    cc._EventListenerAcceleration = cc.EventListener.extend({
      _onAccelerationEvent: null,
      ctor: function(callback) {
        this._onAccelerationEvent = callback;
        cc.EventListener.prototype.ctor.call(this, cc.EventListener.ACCELERATION, cc._EventListenerAcceleration.LISTENER_ID, this._callback);
      },
      _callback: function(event) {
        this._onAccelerationEvent(event.acc, event);
      },
      checkAvailable: function() {
        cc.assertID(this._onAccelerationEvent, 1803);
        return true;
      },
      clone: function() {
        return new cc._EventListenerAcceleration(this._onAccelerationEvent);
      }
    });
    cc._EventListenerAcceleration.LISTENER_ID = "__cc_acceleration";
    cc._EventListenerKeyboard = cc.EventListener.extend({
      onKeyPressed: null,
      onKeyReleased: null,
      ctor: function() {
        cc.EventListener.prototype.ctor.call(this, cc.EventListener.KEYBOARD, cc._EventListenerKeyboard.LISTENER_ID, this._callback);
      },
      _callback: function(event) {
        event.isPressed ? this.onKeyPressed && this.onKeyPressed(event.keyCode, event) : this.onKeyReleased && this.onKeyReleased(event.keyCode, event);
      },
      clone: function() {
        var eventListener = new cc._EventListenerKeyboard();
        eventListener.onKeyPressed = this.onKeyPressed;
        eventListener.onKeyReleased = this.onKeyReleased;
        return eventListener;
      },
      checkAvailable: function() {
        if (null === this.onKeyPressed && null === this.onKeyReleased) {
          cc.logID(1800);
          return false;
        }
        return true;
      }
    });
    cc._EventListenerKeyboard.LISTENER_ID = "__cc_keyboard";
  }), {} ],
  108: [ (function(require, module, exports) {
    var js = require("../platform/js");
    var _EventListenerVector = cc._Class.extend({
      ctor: function() {
        this._fixedListeners = [];
        this._sceneGraphListeners = [];
        this.gt0Index = 0;
      },
      size: function() {
        return this._fixedListeners.length + this._sceneGraphListeners.length;
      },
      empty: function() {
        return 0 === this._fixedListeners.length && 0 === this._sceneGraphListeners.length;
      },
      push: function(listener) {
        0 === listener._getFixedPriority() ? this._sceneGraphListeners.push(listener) : this._fixedListeners.push(listener);
      },
      clearSceneGraphListeners: function() {
        this._sceneGraphListeners.length = 0;
      },
      clearFixedListeners: function() {
        this._fixedListeners.length = 0;
      },
      clear: function() {
        this._sceneGraphListeners.length = 0;
        this._fixedListeners.length = 0;
      },
      getFixedPriorityListeners: function() {
        return this._fixedListeners;
      },
      getSceneGraphPriorityListeners: function() {
        return this._sceneGraphListeners;
      }
    });
    var __getListenerID = function(event) {
      var eventType = cc.Event, type = event.type;
      if (type === eventType.ACCELERATION) return cc._EventListenerAcceleration.LISTENER_ID;
      if (type === eventType.KEYBOARD) return cc._EventListenerKeyboard.LISTENER_ID;
      if (type.startsWith(eventType.MOUSE)) return cc._EventListenerMouse.LISTENER_ID;
      type.startsWith(eventType.TOUCH) && cc.logID(2e3);
      return "";
    };
    var eventManager = {
      DIRTY_NONE: 0,
      DIRTY_FIXED_PRIORITY: 1,
      DIRTY_SCENE_GRAPH_PRIORITY: 2,
      DIRTY_ALL: 3,
      _listenersMap: {},
      _priorityDirtyFlagMap: {},
      _nodeListenersMap: {},
      _nodePriorityMap: {},
      _globalZOrderNodeMap: {},
      _toAddedListeners: [],
      _toRemovedListeners: [],
      _dirtyNodes: [],
      _inDispatch: 0,
      _isEnabled: false,
      _nodePriorityIndex: 0,
      _internalCustomListenerIDs: [],
      _setDirtyForNode: function(node) {
        void 0 !== this._nodeListenersMap[node.__instanceId] && this._dirtyNodes.push(node);
        if (node.getChildren) {
          var _children = node.getChildren();
          for (var i = 0, len = _children ? _children.length : 0; i < len; i++) this._setDirtyForNode(_children[i]);
        }
      },
      pauseTarget: function(node, recursive) {
        if (!(node instanceof cc._BaseNode || node instanceof _ccsg.Node)) {
          cc.warnID(3506);
          return;
        }
        var listeners = this._nodeListenersMap[node.__instanceId], i, len;
        if (listeners) for (i = 0, len = listeners.length; i < len; i++) listeners[i]._setPaused(true);
        if (true === recursive) {
          var locChildren = node.getChildren();
          for (i = 0, len = locChildren ? locChildren.length : 0; i < len; i++) this.pauseTarget(locChildren[i], true);
        }
      },
      resumeTarget: function(node, recursive) {
        if (!(node instanceof cc._BaseNode || node instanceof _ccsg.Node)) {
          cc.warnID(3506);
          return;
        }
        var listeners = this._nodeListenersMap[node.__instanceId], i, len;
        if (listeners) for (i = 0, len = listeners.length; i < len; i++) listeners[i]._setPaused(false);
        this._setDirtyForNode(node);
        if (true === recursive && node.getChildren) {
          var locChildren = node.getChildren();
          for (i = 0, len = locChildren ? locChildren.length : 0; i < len; i++) this.resumeTarget(locChildren[i], true);
        }
      },
      _addListener: function(listener) {
        0 === this._inDispatch ? this._forceAddEventListener(listener) : this._toAddedListeners.push(listener);
      },
      _forceAddEventListener: function(listener) {
        var listenerID = listener._getListenerID();
        var listeners = this._listenersMap[listenerID];
        if (!listeners) {
          listeners = new _EventListenerVector();
          this._listenersMap[listenerID] = listeners;
        }
        listeners.push(listener);
        if (0 === listener._getFixedPriority()) {
          this._setDirty(listenerID, this.DIRTY_SCENE_GRAPH_PRIORITY);
          var node = listener._getSceneGraphPriority();
          null === node && cc.logID(3507);
          this._associateNodeAndEventListener(node, listener);
          node.isRunning() && this.resumeTarget(node);
        } else this._setDirty(listenerID, this.DIRTY_FIXED_PRIORITY);
      },
      _getListeners: function(listenerID) {
        return this._listenersMap[listenerID];
      },
      _updateDirtyFlagForSceneGraph: function() {
        if (0 === this._dirtyNodes.length) return;
        var locDirtyNodes = this._dirtyNodes, selListeners, selListener, locNodeListenersMap = this._nodeListenersMap;
        for (var i = 0, len = locDirtyNodes.length; i < len; i++) {
          selListeners = locNodeListenersMap[locDirtyNodes[i].__instanceId];
          if (selListeners) for (var j = 0, listenersLen = selListeners.length; j < listenersLen; j++) {
            selListener = selListeners[j];
            selListener && this._setDirty(selListener._getListenerID(), this.DIRTY_SCENE_GRAPH_PRIORITY);
          }
        }
        this._dirtyNodes.length = 0;
      },
      _removeAllListenersInVector: function(listenerVector) {
        if (!listenerVector) return;
        var selListener;
        for (var i = 0; i < listenerVector.length; ) {
          selListener = listenerVector[i];
          selListener._setRegistered(false);
          if (null != selListener._getSceneGraphPriority()) {
            this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener);
            selListener._setSceneGraphPriority(null);
          }
          0 === this._inDispatch ? cc.js.array.remove(listenerVector, selListener) : ++i;
        }
      },
      _removeListenersForListenerID: function(listenerID) {
        var listeners = this._listenersMap[listenerID], i;
        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, listener;
        for (i = 0; i < locToAddedListeners.length; ) {
          listener = locToAddedListeners[i];
          listener && listener._getListenerID() === listenerID ? cc.js.array.remove(locToAddedListeners, listener) : ++i;
        }
      },
      _sortEventListeners: function(listenerID) {
        var dirtyFlag = this.DIRTY_NONE, locFlagMap = this._priorityDirtyFlagMap;
        locFlagMap[listenerID] && (dirtyFlag = locFlagMap[listenerID]);
        if (dirtyFlag !== this.DIRTY_NONE) {
          locFlagMap[listenerID] = this.DIRTY_NONE;
          dirtyFlag & this.DIRTY_FIXED_PRIORITY && this._sortListenersOfFixedPriority(listenerID);
          if (dirtyFlag & this.DIRTY_SCENE_GRAPH_PRIORITY) {
            var rootEntity = cc.director.getScene();
            rootEntity && this._sortListenersOfSceneGraphPriority(listenerID, rootEntity);
          }
        }
      },
      _sortListenersOfSceneGraphPriority: function(listenerID, rootNode) {
        var listeners = this._getListeners(listenerID);
        if (!listeners) return;
        var sceneGraphListener = listeners.getSceneGraphPriorityListeners();
        if (!sceneGraphListener || 0 === sceneGraphListener.length) return;
        this._nodePriorityIndex = 0;
        this._nodePriorityMap = {};
        this._visitTarget(rootNode, true);
        listeners.getSceneGraphPriorityListeners().sort(this._sortEventListenersOfSceneGraphPriorityDes);
      },
      _sortEventListenersOfSceneGraphPriorityDes: function(l1, l2) {
        var locNodePriorityMap = eventManager._nodePriorityMap, node1 = l1._getSceneGraphPriority(), node2 = l2._getSceneGraphPriority();
        if (!(l2 && node2 && locNodePriorityMap[node2.__instanceId])) return -1;
        if (!l1 || !node1 || !locNodePriorityMap[node1.__instanceId]) return 1;
        return locNodePriorityMap[node2.__instanceId] - locNodePriorityMap[node1.__instanceId];
      },
      _sortListenersOfFixedPriority: function(listenerID) {
        var listeners = this._listenersMap[listenerID];
        if (!listeners) return;
        var fixedListeners = listeners.getFixedPriorityListeners();
        if (!fixedListeners || 0 === fixedListeners.length) 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;
      },
      _sortListenersOfFixedPriorityAsc: function(l1, l2) {
        return l1._getFixedPriority() - l2._getFixedPriority();
      },
      _onUpdateListeners: function(listeners) {
        var fixedPriorityListeners = listeners.getFixedPriorityListeners();
        var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
        var i, selListener, idx, toRemovedListeners = this._toRemovedListeners;
        if (sceneGraphPriorityListeners) for (i = 0; i < sceneGraphPriorityListeners.length; ) {
          selListener = sceneGraphPriorityListeners[i];
          if (selListener._isRegistered()) ++i; else {
            cc.js.array.remove(sceneGraphPriorityListeners, selListener);
            idx = toRemovedListeners.indexOf(selListener);
            -1 !== idx && toRemovedListeners.splice(idx, 1);
          }
        }
        if (fixedPriorityListeners) for (i = 0; i < fixedPriorityListeners.length; ) {
          selListener = fixedPriorityListeners[i];
          if (selListener._isRegistered()) ++i; else {
            cc.js.array.remove(fixedPriorityListeners, selListener);
            idx = toRemovedListeners.indexOf(selListener);
            -1 !== idx && toRemovedListeners.splice(idx, 1);
          }
        }
        sceneGraphPriorityListeners && 0 === sceneGraphPriorityListeners.length && listeners.clearSceneGraphListeners();
        fixedPriorityListeners && 0 === fixedPriorityListeners.length && listeners.clearFixedListeners();
      },
      frameUpdateListeners: function() {
        var locListenersMap = this._listenersMap, locPriorityDirtyFlagMap = this._priorityDirtyFlagMap;
        for (var selKey in locListenersMap) if (locListenersMap[selKey].empty()) {
          delete locPriorityDirtyFlagMap[selKey];
          delete locListenersMap[selKey];
        }
        var locToAddedListeners = this._toAddedListeners;
        if (0 !== locToAddedListeners.length) {
          for (var i = 0, len = locToAddedListeners.length; i < len; i++) this._forceAddEventListener(locToAddedListeners[i]);
          locToAddedListeners.length = 0;
        }
        0 !== this._toRemovedListeners.length && this._cleanToRemovedListeners();
      },
      _updateTouchListeners: function(event) {
        var locInDispatch = this._inDispatch;
        cc.assertID(locInDispatch > 0, 3508);
        if (locInDispatch > 1) return;
        var listeners;
        listeners = this._listenersMap[cc._EventListenerTouchOneByOne.LISTENER_ID];
        listeners && this._onUpdateListeners(listeners);
        listeners = this._listenersMap[cc._EventListenerTouchAllAtOnce.LISTENER_ID];
        listeners && this._onUpdateListeners(listeners);
        cc.assertID(1 === locInDispatch, 3509);
        var locToAddedListeners = this._toAddedListeners;
        if (0 !== locToAddedListeners.length) {
          for (var i = 0, len = locToAddedListeners.length; i < len; i++) this._forceAddEventListener(locToAddedListeners[i]);
          this._toAddedListeners.length = 0;
        }
        0 !== this._toRemovedListeners.length && this._cleanToRemovedListeners();
      },
      _cleanToRemovedListeners: function() {
        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 idx, fixedPriorityListeners = listeners.getFixedPriorityListeners(), sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
          if (sceneGraphPriorityListeners) {
            idx = sceneGraphPriorityListeners.indexOf(selListener);
            -1 !== idx && sceneGraphPriorityListeners.splice(idx, 1);
          }
          if (fixedPriorityListeners) {
            idx = fixedPriorityListeners.indexOf(selListener);
            -1 !== idx && fixedPriorityListeners.splice(idx, 1);
          }
        }
        toRemovedListeners.length = 0;
      },
      _onTouchEventCallback: function(listener, argsObj) {
        if (!listener._isRegistered) return false;
        var event = argsObj.event, selTouch = event.currentTouch;
        event.currentTarget = listener._node;
        var isClaimed = false, removedIdx;
        var getCode = event.getEventCode(), EventTouch = cc.Event.EventTouch;
        if (getCode === EventTouch.BEGAN) {
          if (listener.onTouchBegan) {
            isClaimed = listener.onTouchBegan(selTouch, event);
            isClaimed && listener._registered && listener._claimedTouches.push(selTouch);
          }
        } else if (listener._claimedTouches.length > 0 && -1 !== (removedIdx = listener._claimedTouches.indexOf(selTouch))) {
          isClaimed = true;
          if (getCode === EventTouch.MOVED && listener.onTouchMoved) listener.onTouchMoved(selTouch, event); else if (getCode === EventTouch.ENDED) {
            listener.onTouchEnded && listener.onTouchEnded(selTouch, event);
            listener._registered && listener._claimedTouches.splice(removedIdx, 1);
          } else if (getCode === EventTouch.CANCELLED) {
            listener.onTouchCancelled && listener.onTouchCancelled(selTouch, event);
            listener._registered && listener._claimedTouches.splice(removedIdx, 1);
          }
        }
        if (event.isStopped()) {
          eventManager._updateTouchListeners(event);
          return true;
        }
        if (isClaimed && listener._registered && listener.swallowTouches) {
          argsObj.needsMutableSet && argsObj.touches.splice(selTouch, 1);
          return true;
        }
        return false;
      },
      _dispatchTouchEvent: function(event) {
        this._sortEventListeners(cc._EventListenerTouchOneByOne.LISTENER_ID);
        this._sortEventListeners(cc._EventListenerTouchAllAtOnce.LISTENER_ID);
        var oneByOneListeners = this._getListeners(cc._EventListenerTouchOneByOne.LISTENER_ID);
        var allAtOnceListeners = this._getListeners(cc._EventListenerTouchAllAtOnce.LISTENER_ID);
        if (null === oneByOneListeners && null === allAtOnceListeners) return;
        var originalTouches = event.getTouches(), mutableTouches = cc.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++) {
          event.currentTouch = originalTouches[i];
          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);
      },
      _onTouchesEventCallback: function(listener, callbackParams) {
        if (!listener._registered) return false;
        var EventTouch = cc.Event.EventTouch, event = callbackParams.event, touches = callbackParams.touches, getCode = event.getEventCode();
        event.currentTarget = listener._node;
        getCode === EventTouch.BEGAN && listener.onTouchesBegan ? listener.onTouchesBegan(touches, event) : getCode === EventTouch.MOVED && listener.onTouchesMoved ? listener.onTouchesMoved(touches, event) : getCode === EventTouch.ENDED && listener.onTouchesEnded ? listener.onTouchesEnded(touches, event) : getCode === EventTouch.CANCELLED && listener.onTouchesCancelled && listener.onTouchesCancelled(touches, event);
        if (event.isStopped()) {
          eventManager._updateTouchListeners(event);
          return true;
        }
        return false;
      },
      _associateNodeAndEventListener: function(node, listener) {
        var listeners = this._nodeListenersMap[node.__instanceId];
        if (!listeners) {
          listeners = [];
          this._nodeListenersMap[node.__instanceId] = listeners;
        }
        listeners.push(listener);
      },
      _dissociateNodeAndEventListener: function(node, listener) {
        var listeners = this._nodeListenersMap[node.__instanceId];
        if (listeners) {
          cc.js.array.remove(listeners, listener);
          0 === listeners.length && delete this._nodeListenersMap[node.__instanceId];
        }
      },
      _dispatchEventToListeners: function(listeners, onEvent, eventOrArgs) {
        var shouldStopPropagation = false;
        var fixedPriorityListeners = listeners.getFixedPriorityListeners();
        var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
        var i = 0, j, selListener;
        if (fixedPriorityListeners && 0 !== fixedPriorityListeners.length) for (;i < listeners.gt0Index; ++i) {
          selListener = fixedPriorityListeners[i];
          if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) {
            shouldStopPropagation = true;
            break;
          }
        }
        if (sceneGraphPriorityListeners && !shouldStopPropagation) for (j = 0; j < sceneGraphPriorityListeners.length; j++) {
          selListener = sceneGraphPriorityListeners[j];
          if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) {
            shouldStopPropagation = true;
            break;
          }
        }
        if (fixedPriorityListeners && !shouldStopPropagation) for (;i < fixedPriorityListeners.length; ++i) {
          selListener = fixedPriorityListeners[i];
          if (selListener.isEnabled() && !selListener._isPaused() && selListener._isRegistered() && onEvent(selListener, eventOrArgs)) {
            shouldStopPropagation = true;
            break;
          }
        }
      },
      _setDirty: function(listenerID, flag) {
        var locDirtyFlagMap = this._priorityDirtyFlagMap;
        null == locDirtyFlagMap[listenerID] ? locDirtyFlagMap[listenerID] = flag : locDirtyFlagMap[listenerID] = flag | locDirtyFlagMap[listenerID];
      },
      _visitTarget: function(node, isRootNode) {
        node._reorderChildDirty && node.sortAllChildren();
        var children = node.getChildren(), i = 0;
        var childrenCount = children.length, locGlobalZOrderNodeMap = this._globalZOrderNodeMap, locNodeListenersMap = this._nodeListenersMap;
        if (childrenCount > 0) {
          var child;
          for (;i < childrenCount; i++) {
            child = children[i];
            if (!(child && child.getLocalZOrder() < 0)) break;
            this._visitTarget(child, false);
          }
          if (void 0 !== locNodeListenersMap[node.__instanceId]) {
            locGlobalZOrderNodeMap[node.getGlobalZOrder()] || (locGlobalZOrderNodeMap[node.getGlobalZOrder()] = []);
            locGlobalZOrderNodeMap[node.getGlobalZOrder()].push(node.__instanceId);
          }
          for (;i < childrenCount; i++) {
            child = children[i];
            child && this._visitTarget(child, false);
          }
        } else if (void 0 !== locNodeListenersMap[node.__instanceId]) {
          locGlobalZOrderNodeMap[node.getGlobalZOrder()] || (locGlobalZOrderNodeMap[node.getGlobalZOrder()] = []);
          locGlobalZOrderNodeMap[node.getGlobalZOrder()].push(node.__instanceId);
        }
        if (isRootNode) {
          var globalZOrders = [];
          for (var selKey in locGlobalZOrderNodeMap) globalZOrders.push(selKey);
          globalZOrders.sort(this._sortNumberAsc);
          var zOrdersLen = globalZOrders.length, selZOrders, j, locNodePriorityMap = this._nodePriorityMap;
          for (i = 0; i < zOrdersLen; i++) {
            selZOrders = locGlobalZOrderNodeMap[globalZOrders[i]];
            for (j = 0; j < selZOrders.length; j++) locNodePriorityMap[selZOrders[j]] = ++this._nodePriorityIndex;
          }
          this._globalZOrderNodeMap = {};
        }
      },
      _sortNumberAsc: function(a, b) {
        return a - b;
      },
      hasEventListener: function(listenerID) {
        return !!this._getListeners(listenerID);
      },
      addListener: function(listener, nodeOrPriority) {
        cc.assertID(listener && nodeOrPriority, 3503);
        if (!(cc.js.isNumber(nodeOrPriority) || nodeOrPriority instanceof cc._BaseNode || nodeOrPriority instanceof _ccsg.Node)) {
          cc.warnID(3506);
          return;
        }
        if (listener instanceof cc.EventListener) {
          if (listener._isRegistered()) {
            cc.logID(3505);
            return;
          }
        } else {
          cc.assertID(!cc.js.isNumber(nodeOrPriority), 3504);
          listener = cc.EventListener.create(listener);
        }
        if (!listener.checkAvailable()) return;
        if (cc.js.isNumber(nodeOrPriority)) {
          if (0 === nodeOrPriority) {
            cc.logID(3500);
            return;
          }
          listener._setSceneGraphPriority(null);
          listener._setFixedPriority(nodeOrPriority);
          listener._setRegistered(true);
          listener._setPaused(false);
          this._addListener(listener);
        } else {
          listener._setSceneGraphPriority(nodeOrPriority);
          listener._setFixedPriority(0);
          listener._setRegistered(true);
          this._addListener(listener);
        }
        return listener;
      },
      addCustomListener: function(eventName, callback) {
        var listener = new cc._EventListenerCustom(eventName, callback);
        this.addListener(listener, 1);
        return listener;
      },
      removeListener: function(listener) {
        if (null == listener) return;
        var isFound, locListener = this._listenersMap;
        for (var selKey in locListener) {
          var listeners = locListener[selKey];
          var fixedPriorityListeners = listeners.getFixedPriorityListeners(), sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
          isFound = this._removeListenerInVector(sceneGraphPriorityListeners, listener);
          if (isFound) this._setDirty(listener._getListenerID(), this.DIRTY_SCENE_GRAPH_PRIORITY); else {
            isFound = this._removeListenerInVector(fixedPriorityListeners, listener);
            isFound && this._setDirty(listener._getListenerID(), this.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 = 0, len = locToAddedListeners.length; i < len; i++) {
            var selListener = locToAddedListeners[i];
            if (selListener === listener) {
              cc.js.array.remove(locToAddedListeners, selListener);
              selListener._setRegistered(false);
              break;
            }
          }
        }
      },
      _removeListenerInCallback: function(listeners, callback) {
        if (null == listeners) return false;
        for (var i = 0, len = listeners.length; i < len; i++) {
          var selListener = listeners[i];
          if (selListener._onCustomEvent === callback || selListener._onEvent === callback) {
            selListener._setRegistered(false);
            if (null != selListener._getSceneGraphPriority()) {
              this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener);
              selListener._setSceneGraphPriority(null);
            }
            0 === this._inDispatch ? cc.js.array.remove(listeners, selListener) : this._toRemovedListeners.push(selListener);
            return true;
          }
        }
        return false;
      },
      _removeListenerInVector: function(listeners, listener) {
        if (null == listeners) return false;
        for (var i = 0, len = listeners.length; i < len; i++) {
          var selListener = listeners[i];
          if (selListener === listener) {
            selListener._setRegistered(false);
            if (null != selListener._getSceneGraphPriority()) {
              this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener);
              selListener._setSceneGraphPriority(null);
            }
            0 === this._inDispatch ? cc.js.array.remove(listeners, selListener) : this._toRemovedListeners.push(selListener);
            return true;
          }
        }
        return false;
      },
      removeListeners: function(listenerType, recursive) {
        var i, _t = this;
        if (!(cc.js.isNumber(listenerType) || listenerType instanceof cc._BaseNode || listenerType instanceof _ccsg.Node)) {
          cc.warnID(3506);
          return;
        }
        if (void 0 !== listenerType.__instanceId) {
          delete _t._nodePriorityMap[listenerType.__instanceId];
          cc.js.array.remove(_t._dirtyNodes, listenerType);
          var listeners = _t._nodeListenersMap[listenerType.__instanceId], i;
          if (listeners) {
            var listenersCopy = cc.js.array.copy(listeners);
            for (i = 0; i < listenersCopy.length; i++) _t.removeListener(listenersCopy[i]);
            delete _t._nodeListenersMap[listenerType.__instanceId];
          }
          var locToAddedListeners = _t._toAddedListeners;
          for (i = 0; i < locToAddedListeners.length; ) {
            var listener = locToAddedListeners[i];
            if (listener._getSceneGraphPriority() === listenerType) {
              listener._setSceneGraphPriority(null);
              listener._setRegistered(false);
              locToAddedListeners.splice(i, 1);
            } else ++i;
          }
          if (true === recursive) {
            var locChildren = listenerType.getChildren(), len;
            for (i = 0, len = locChildren.length; i < len; i++) _t.removeListeners(locChildren[i], true);
          }
        } else listenerType === cc.EventListener.TOUCH_ONE_BY_ONE ? _t._removeListenersForListenerID(cc._EventListenerTouchOneByOne.LISTENER_ID) : listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE ? _t._removeListenersForListenerID(cc._EventListenerTouchAllAtOnce.LISTENER_ID) : listenerType === cc.EventListener.MOUSE ? _t._removeListenersForListenerID(cc._EventListenerMouse.LISTENER_ID) : listenerType === cc.EventListener.ACCELERATION ? _t._removeListenersForListenerID(cc._EventListenerAcceleration.LISTENER_ID) : listenerType === cc.EventListener.KEYBOARD ? _t._removeListenersForListenerID(cc._EventListenerKeyboard.LISTENER_ID) : cc.logID(3501);
      },
      removeCustomListeners: function(customEventName) {
        this._removeListenersForListenerID(customEventName);
      },
      removeAllListeners: function() {
        var locListeners = this._listenersMap, locInternalCustomEventIDs = this._internalCustomListenerIDs;
        for (var selKey in locListeners) -1 === locInternalCustomEventIDs.indexOf(selKey) && this._removeListenersForListenerID(selKey);
      },
      setPriority: function(listener, fixedPriority) {
        if (null == listener) 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 (-1 !== found) {
              null != listener._getSceneGraphPriority() && cc.logID(3502);
              if (listener._getFixedPriority() !== fixedPriority) {
                listener._setFixedPriority(fixedPriority);
                this._setDirty(listener._getListenerID(), this.DIRTY_FIXED_PRIORITY);
              }
              return;
            }
          }
        }
      },
      setEnabled: function(enabled) {
        this._isEnabled = enabled;
      },
      isEnabled: function() {
        return this._isEnabled;
      },
      dispatchEvent: function(event) {
        if (!this._isEnabled) return;
        this._updateDirtyFlagForSceneGraph();
        this._inDispatch++;
        if (!event || !event.getType) throw new Error("event is undefined");
        if (event.getType().startsWith(cc.Event.TOUCH)) {
          this._dispatchTouchEvent(event);
          this._inDispatch--;
          return;
        }
        var listenerID = __getListenerID(event);
        this._sortEventListeners(listenerID);
        var selListeners = this._listenersMap[listenerID];
        if (null != selListeners) {
          this._dispatchEventToListeners(selListeners, this._onListenerCallback, event);
          this._onUpdateListeners(selListeners);
        }
        this._inDispatch--;
      },
      _onListenerCallback: function(listener, event) {
        event.currentTarget = listener._target;
        listener._onEvent(event);
        return event.isStopped();
      },
      dispatchCustomEvent: function(eventName, optionalUserData) {
        var ev = new cc.Event.EventCustom(eventName);
        ev.setUserData(optionalUserData);
        this.dispatchEvent(ev);
      }
    };
    js.get(cc, "eventManager", (function() {
      cc.warnID(1405, "cc.eventManager", "cc.EventTarget or cc.systemEvent");
      return eventManager;
    }));
    module.exports = eventManager;
  }), {
    "../platform/js": 196
  } ],
  109: [ (function(require, module, exports) {
    cc.Touch = cc._Class.extend({
      ctor: function(x, y, id) {
        this._lastModified = 0;
        this.setTouchInfo(id, x, y);
      },
      getLocation: function() {
        return {
          x: this._point.x,
          y: this._point.y
        };
      },
      getLocationX: function() {
        return this._point.x;
      },
      getLocationY: function() {
        return this._point.y;
      },
      getPreviousLocation: function() {
        return {
          x: this._prevPoint.x,
          y: this._prevPoint.y
        };
      },
      getStartLocation: function() {
        return {
          x: this._startPoint.x,
          y: this._startPoint.y
        };
      },
      getDelta: function() {
        return cc.pSub(this._point, this._prevPoint);
      },
      getLocationInView: function() {
        return {
          x: this._point.x,
          y: cc.view._designResolutionSize.height - this._point.y
        };
      },
      getPreviousLocationInView: function() {
        return {
          x: this._prevPoint.x,
          y: cc.view._designResolutionSize.height - this._prevPoint.y
        };
      },
      getStartLocationInView: function() {
        return {
          x: this._startPoint.x,
          y: cc.view._designResolutionSize.height - this._startPoint.y
        };
      },
      getID: function() {
        return this._id;
      },
      setTouchInfo: function(id, x, y) {
        this._prevPoint = this._point;
        this._point = cc.p(x || 0, y || 0);
        this._id = id;
        if (!this._startPointCaptured) {
          this._startPoint = cc.p(this._point);
          cc.view._convertPointWithScale(this._startPoint);
          this._startPointCaptured = true;
        }
      },
      _setPoint: function(x, y) {
        if (void 0 === y) {
          this._point.x = x.x;
          this._point.y = x.y;
        } else {
          this._point.x = x;
          this._point.y = y;
        }
      },
      _setPrevPoint: function(x, y) {
        this._prevPoint = void 0 === y ? cc.p(x.x, x.y) : cc.p(x || 0, y || 0);
      }
    });
  }), {} ],
  110: [ (function(require, module, exports) {
    require("./CCEvent");
    var eventManager;
    false;
    require("./CCTouch");
    require("./CCEventListener");
    eventManager = require("./CCEventManager");
    module.exports = eventManager;
  }), {
    "./CCEvent": 106,
    "./CCEventListener": 107,
    "./CCEventManager": 108,
    "./CCTouch": 109
  } ],
  111: [ (function(require, module, exports) {
    var JS = cc.js;
    var CallbacksHandler = require("../platform/callbacks-invoker").CallbacksHandler;
    function EventListeners() {
      CallbacksHandler.call(this);
    }
    JS.extend(EventListeners, CallbacksHandler);
    EventListeners.prototype.invoke = function(event, captureListeners) {
      var key = event.type;
      var list = this._callbackTable[key];
      if (list) {
        var rootInvoker = !list.isInvoking;
        list.isInvoking = true;
        var callbacks = list.callbacks;
        var targets = list.targets;
        for (var i = 0, len = callbacks.length; i < len; ++i) {
          var callback = callbacks[i];
          if (callback) {
            var target = targets[i] || event.currentTarget;
            callback.call(target, event, captureListeners);
            if (event._propagationImmediateStopped) break;
          }
        }
        if (rootInvoker) {
          list.isInvoking = false;
          list.containCanceled && list.purgeCanceled();
        }
      }
    };
    module.exports = EventListeners;
    false;
  }), {
    "../platform/callbacks-invoker": 189
  } ],
  112: [ (function(require, module, exports) {
    var EventListeners = require("./event-listeners");
    require("./event");
    var JS = cc.js;
    var fastRemove = JS.array.fastRemove;
    var cachedArray = new Array(16);
    cachedArray.length = 0;
    var CAPTURING_FLAG = 2;
    var BUBBLING_FLAG = 4;
    var _doDispatchEvent = function(owner, event) {
      var target, i;
      event.target = owner;
      cachedArray.length = 0;
      owner._getCapturingTargets(event.type, cachedArray);
      event.eventPhase = 1;
      for (i = cachedArray.length - 1; i >= 0; --i) {
        target = cachedArray[i];
        if (target._isTargetActive(event.type) && target._capturingListeners) {
          event.currentTarget = target;
          target._capturingListeners.invoke(event, cachedArray);
          if (event._propagationStopped) {
            cachedArray.length = 0;
            return;
          }
        }
      }
      cachedArray.length = 0;
      if (owner._isTargetActive(event.type)) {
        event.eventPhase = 2;
        event.currentTarget = owner;
        owner._capturingListeners && owner._capturingListeners.invoke(event);
        !event._propagationImmediateStopped && owner._bubblingListeners && owner._bubblingListeners.invoke(event);
      }
      if (!event._propagationStopped && event.bubbles) {
        owner._getBubblingTargets(event.type, cachedArray);
        event.eventPhase = 3;
        for (i = 0; i < cachedArray.length; ++i) {
          target = cachedArray[i];
          if (target._isTargetActive(event.type) && target._bubblingListeners) {
            event.currentTarget = target;
            target._bubblingListeners.invoke(event);
            if (event._propagationStopped) {
              cachedArray.length = 0;
              return;
            }
          }
        }
      }
      cachedArray.length = 0;
    };
    function EventTarget() {
      this._capturingListeners = null;
      this._bubblingListeners = null;
      this._hasListenerCache = null;
    }
    var proto = EventTarget.prototype;
    proto._addEventFlag = function(type, listeners, useCapture) {
      var cache = this._hasListenerCache;
      cache || (cache = this._hasListenerCache = cc.js.createMap());
      void 0 === cache[type] && (cache[type] = 0);
      var flag = useCapture ? CAPTURING_FLAG : BUBBLING_FLAG;
      cache[type] |= flag;
    };
    proto._purgeEventFlag = function(type, listeners, useCapture) {
      var cache = this._hasListenerCache;
      if (!cache || listeners.has(type)) return;
      var flag = useCapture ? CAPTURING_FLAG : BUBBLING_FLAG;
      cache[type] &= ~flag;
      0 === cache[type] && delete cache[type];
    };
    proto._resetFlagForTarget = function(target, listeners, useCapture) {
      var cache = this._hasListenerCache;
      if (!cache) return;
      var flag = useCapture ? CAPTURING_FLAG : BUBBLING_FLAG;
      for (var key in cache) if (!listeners.has(key)) {
        cache[key] &= ~flag;
        0 === cache[key] && delete cache[key];
      }
    };
    proto.hasEventListener = function(type, checkCapture) {
      var cache = this._hasListenerCache;
      if (!cache) return false;
      var flag = checkCapture ? CAPTURING_FLAG : BUBBLING_FLAG;
      return (cache[type] & flag) > 0;
    };
    proto.on = function(type, callback, target, useCapture) {
      if ("boolean" === typeof target) {
        useCapture = target;
        target = void 0;
      } else useCapture = !!useCapture;
      if (!callback) {
        cc.errorID(6800);
        return;
      }
      var listeners = null;
      listeners = useCapture ? this._capturingListeners = this._capturingListeners || new EventListeners() : this._bubblingListeners = this._bubblingListeners || new EventListeners();
      if (!listeners.has(type, callback, target)) {
        listeners.add(type, callback, target);
        target && target.__eventTargets && target.__eventTargets.push(this);
        this._addEventFlag(type, listeners, useCapture);
      }
      return callback;
    };
    proto.off = function(type, callback, target, useCapture) {
      if ("boolean" === typeof target) {
        useCapture = target;
        target = void 0;
      } else useCapture = !!useCapture;
      if (callback) {
        var listeners = useCapture ? this._capturingListeners : this._bubblingListeners;
        if (listeners) {
          listeners.remove(type, callback, target);
          target && target.__eventTargets && fastRemove(target.__eventTargets, this);
          this._purgeEventFlag(type, listeners, useCapture);
        }
      } else {
        this._capturingListeners && this._capturingListeners.removeAll(type);
        this._bubblingListeners && this._bubblingListeners.removeAll(type);
        this._hasListenerCache && delete this._hasListenerCache[type];
      }
    };
    proto.targetOff = function(target) {
      if (this._capturingListeners) {
        this._capturingListeners.removeAll(target);
        this._resetFlagForTarget(target, this._capturingListeners, true);
      }
      if (this._bubblingListeners) {
        this._bubblingListeners.removeAll(target);
        this._resetFlagForTarget(target, this._bubblingListeners, false);
      }
    };
    proto.once = function(type, callback, target, useCapture) {
      var eventType_hasOnceListener = "__ONCE_FLAG:" + type;
      var listeners = useCapture ? this._capturingListeners : this._bubblingListeners;
      var hasOnceListener = listeners && listeners.has(eventType_hasOnceListener, callback, target);
      if (!hasOnceListener) {
        var self = this;
        var onceWrapper = function(event) {
          self.off(type, onceWrapper, target, useCapture);
          listeners.remove(eventType_hasOnceListener, callback, target);
          callback.call(this, event);
        };
        this.on(type, onceWrapper, target, useCapture);
        listeners || (listeners = useCapture ? this._capturingListeners : this._bubblingListeners);
        listeners.add(eventType_hasOnceListener, callback, target);
      }
    };
    proto.dispatchEvent = function(event) {
      _doDispatchEvent(this, event);
      cachedArray.length = 0;
    };
    proto.emit = function(message, detail) {
      false;
      var cache = this._hasListenerCache;
      if (!cache) return;
      var flag = cache[message];
      if (!flag) return;
      var event = cc.Event.EventCustom.get(message);
      event.detail = detail;
      event.eventPhase = 2;
      event.target = event.currentTarget = this;
      var capturingListeners = this._capturingListeners;
      capturingListeners && flag & CAPTURING_FLAG && capturingListeners.invoke(event);
      var bubblingListeners = this._bubblingListeners;
      bubblingListeners && flag & BUBBLING_FLAG && !event._propagationImmediateStopped && bubblingListeners.invoke(event);
      cc.Event.EventCustom.put(event);
    };
    proto._isTargetActive = function(type) {
      return true;
    };
    proto._getCapturingTargets = function(type, array) {};
    proto._getBubblingTargets = function(type, array) {};
    EventTarget.prototype._EventTargetOn = EventTarget.prototype.on;
    EventTarget.prototype._EventTargetOnce = EventTarget.prototype.once;
    EventTarget.prototype._EventTargetOff = EventTarget.prototype.off;
    EventTarget.prototype._EventTargetTargetOff = EventTarget.prototype.targetOff;
    cc.EventTarget = module.exports = EventTarget;
  }), {
    "./event": 113,
    "./event-listeners": 111
  } ],
  113: [ (function(require, module, exports) {
    var JS = require("../platform/js");
    cc.Event = function(type, bubbles) {
      this.type = type;
      this.bubbles = !!bubbles;
      this.target = null;
      this.currentTarget = null;
      this.eventPhase = 0;
      this._propagationStopped = false;
      this._propagationImmediateStopped = false;
    };
    cc.Event.prototype = {
      constructor: cc.Event,
      unuse: function() {
        this.type = cc.Event.NO_TYPE;
        this.target = null;
        this.currentTarget = null;
        this.eventPhase = cc.Event.NONE;
        this._propagationStopped = false;
        this._propagationImmediateStopped = false;
      },
      reuse: function(type, bubbles) {
        this.type = type;
        this.bubbles = bubbles || false;
      },
      stopPropagation: function() {
        this._propagationStopped = true;
      },
      stopPropagationImmediate: function() {
        this._propagationImmediateStopped = true;
      },
      isStopped: function() {
        return this._propagationStopped || this._propagationImmediateStopped;
      },
      getCurrentTarget: function() {
        return this.currentTarget;
      },
      getType: function() {
        return this.type;
      }
    };
    cc.Event.NO_TYPE = "no_type";
    cc.Event.TOUCH = "touch";
    cc.Event.MOUSE = "mouse";
    cc.Event.KEYBOARD = "keyboard";
    cc.Event.ACCELERATION = "acceleration";
    cc.Event.NONE = 0;
    cc.Event.CAPTURING_PHASE = 1;
    cc.Event.AT_TARGET = 2;
    cc.Event.BUBBLING_PHASE = 3;
    var EventCustom = function(type, bubbles) {
      cc.Event.call(this, type, bubbles);
      this.detail = null;
    };
    JS.extend(EventCustom, cc.Event);
    EventCustom.prototype.reset = EventCustom;
    EventCustom.prototype.setUserData = function(data) {
      this.detail = data;
    };
    EventCustom.prototype.getUserData = function() {
      return this.detail;
    };
    EventCustom.prototype.getEventName = cc.Event.prototype.getType;
    var MAX_POOL_SIZE = 10;
    var _eventPool = new JS.Pool(MAX_POOL_SIZE);
    EventCustom.put = function(event) {
      _eventPool.put(event);
    };
    EventCustom.get = function(type, bubbles) {
      var event = _eventPool._get();
      event ? event.reset(type, bubbles) : event = new EventCustom(type, bubbles);
      return event;
    };
    cc.Event.EventCustom = EventCustom;
    module.exports = cc.Event;
  }), {
    "../platform/js": 196
  } ],
  114: [ (function(require, module, exports) {
    require("./event");
    require("./event-listeners");
    require("./event-target");
    require("./system-event");
  }), {
    "./event": 113,
    "./event-listeners": 111,
    "./event-target": 112,
    "./system-event": 115
  } ],
  115: [ (function(require, module, exports) {
    var EventTarget = require("../event/event-target");
    var eventManager = require("../event-manager");
    var inputManger;
    false;
    inputManger = require("../platform/CCInputManager");
    var EventType = cc.Enum({
      KEY_DOWN: "keydown",
      KEY_UP: "keyup",
      DEVICEMOTION: "devicemotion"
    });
    var keyboardListener = null;
    var accelerationListener = null;
    var keyboardListenerAddFrame = 0;
    var SystemEvent = cc.Class({
      name: "SystemEvent",
      extends: EventTarget,
      statics: {
        EventType: EventType
      },
      setAccelerometerEnabled: function(isEnable) {
        inputManger.setAccelerometerEnabled(isEnable);
      },
      setAccelerometerInterval: function(interval) {
        inputManger.setAccelerometerInterval(interval);
      },
      on: function(type, callback, target, useCapture) {
        this._super(type, callback, target, useCapture);
        if (type === EventType.KEY_DOWN || type === EventType.KEY_UP) {
          keyboardListener || (keyboardListener = cc.EventListener.create({
            event: cc.EventListener.KEYBOARD,
            onKeyPressed: function(keyCode, event) {
              event.type = EventType.KEY_DOWN;
              false;
              cc.systemEvent.dispatchEvent(event);
            },
            onKeyReleased: function(keyCode, event) {
              event.type = EventType.KEY_UP;
              false;
              cc.systemEvent.dispatchEvent(event);
            }
          }));
          if (!eventManager.hasEventListener(cc._EventListenerKeyboard.LISTENER_ID)) {
            var currentFrame = cc.director.getTotalFrames();
            if (currentFrame !== keyboardListenerAddFrame) {
              eventManager.addListener(keyboardListener, 1);
              keyboardListenerAddFrame = currentFrame;
            }
          }
        }
        if (type === EventType.DEVICEMOTION) {
          accelerationListener || (accelerationListener = cc.EventListener.create({
            event: cc.EventListener.ACCELERATION,
            callback: function(acc, event) {
              event.type = EventType.DEVICEMOTION;
              false;
              cc.systemEvent.dispatchEvent(event);
            }
          }));
          eventManager.hasEventListener(cc._EventListenerAcceleration.LISTENER_ID) || eventManager.addListener(accelerationListener, 1);
        }
      },
      off: function(type, callback, target, useCapture) {
        this._super(type, callback, target, useCapture);
        if (keyboardListener && (type === EventType.KEY_DOWN || type === EventType.KEY_UP)) {
          var hasKeyDownEventListener = this.hasEventListener(EventType.KEY_DOWN);
          var hasKeyUpEventListener = this.hasEventListener(EventType.KEY_UP);
          hasKeyDownEventListener || hasKeyUpEventListener || eventManager.removeListener(keyboardListener);
        }
        accelerationListener && type === EventType.DEVICEMOTION && eventManager.removeListener(accelerationListener);
      }
    });
    cc.SystemEvent = module.exports = SystemEvent;
    true;
    cc.systemEvent = new cc.SystemEvent();
  }), {
    "../event-manager": 110,
    "../event/event-target": 112,
    "../platform/CCInputManager": 179
  } ],
  116: [ (function(require, module, exports) {
    "use strict";
    module.exports = earcut;
    function earcut(data, holeIndices, dim) {
      dim = dim || 2;
      var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
      if (!outerNode) return triangles;
      var minX, minY, maxX, maxY, x, y, size;
      hasHoles && (outerNode = eliminateHoles(data, holeIndices, outerNode, dim));
      if (data.length > 80 * dim) {
        minX = maxX = data[0];
        minY = maxY = data[1];
        for (var i = dim; i < outerLen; i += dim) {
          x = data[i];
          y = data[i + 1];
          x < minX && (minX = x);
          y < minY && (minY = y);
          x > maxX && (maxX = x);
          y > maxY && (maxY = y);
        }
        size = Math.max(maxX - minX, maxY - minY);
      }
      earcutLinked(outerNode, triangles, dim, minX, minY, size);
      return triangles;
    }
    function linkedList(data, start, end, dim, clockwise) {
      var i, last;
      if (clockwise === signedArea(data, start, end, dim) > 0) for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); else for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
      if (last && equals(last, last.next)) {
        removeNode(last);
        last = last.next;
      }
      return last;
    }
    function filterPoints(start, end) {
      if (!start) return start;
      end || (end = start);
      var p = start, again;
      do {
        again = false;
        if (p.steiner || !equals(p, p.next) && 0 !== area(p.prev, p, p.next)) p = p.next; else {
          removeNode(p);
          p = end = p.prev;
          if (p === p.next) return null;
          again = true;
        }
      } while (again || p !== end);
      return end;
    }
    function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
      if (!ear) return;
      !pass && size && indexCurve(ear, minX, minY, size);
      var stop = ear, prev, next;
      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) if (1 === pass) {
            ear = cureLocalIntersections(ear, triangles, dim);
            earcutLinked(ear, triangles, dim, minX, minY, size, 2);
          } else 2 === pass && splitEarcut(ear, triangles, dim, minX, minY, size); else earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
          break;
        }
      }
    }
    function isEar(ear) {
      var a = ear.prev, b = ear, 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, b = ear, 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, minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y, maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x, maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y;
      var minZ = zOrder(minTX, minTY, minX, minY, size), 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, b = p.next.next;
        if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
          triangles.push(a.i / dim);
          triangles.push(p.i / dim);
          triangles.push(b.i / dim);
          removeNode(p);
          removeNode(p.next);
          p = start = b;
        }
        p = p.next;
      } while (p !== start);
      return p;
    }
    function splitEarcut(start, triangles, dim, minX, minY, size) {
      var a = start;
      do {
        var b = a.next.next;
        while (b !== a.prev) {
          if (a.i !== b.i && isValidDiagonal(a, b)) {
            var c = splitPolygon(a, b);
            a = filterPoints(a, a.next);
            c = filterPoints(c, c.next);
            earcutLinked(a, triangles, dim, minX, minY, size);
            earcutLinked(c, triangles, dim, minX, minY, size);
            return;
          }
          b = b.next;
        }
        a = a.next;
      } while (a !== start);
    }
    function eliminateHoles(data, holeIndices, outerNode, dim) {
      var queue = [], i, len, start, end, list;
      for (i = 0, len = holeIndices.length; i < len; i++) {
        start = holeIndices[i] * dim;
        end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
        list = linkedList(data, start, end, dim, false);
        list === list.next && (list.steiner = true);
        queue.push(getLeftmost(list));
      }
      queue.sort(compareX);
      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, hx = hole.x, hy = hole.y, qx = -Infinity, m;
      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, mx = m.x, my = m.y, tanMin = Infinity, 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 {
        null === p.z && (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, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
      do {
        p = list;
        list = null;
        tail = null;
        numMerges = 0;
        while (p) {
          numMerges++;
          q = p;
          pSize = 0;
          for (i = 0; i < inSize; i++) {
            pSize++;
            q = q.nextZ;
            if (!q) break;
          }
          qSize = inSize;
          while (pSize > 0 || qSize > 0 && q) {
            if (0 === pSize) {
              e = q;
              q = q.nextZ;
              qSize--;
            } else if (0 !== qSize && q) if (p.z <= q.z) {
              e = p;
              p = p.nextZ;
              pSize--;
            } else {
              e = q;
              q = q.nextZ;
              qSize--;
            } else {
              e = p;
              p = p.nextZ;
              pSize--;
            }
            tail ? tail.nextZ = e : 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 = 16711935 & (x | x << 8);
      x = 252645135 & (x | x << 4);
      x = 858993459 & (x | x << 2);
      x = 1431655765 & (x | x << 1);
      y = 16711935 & (y | y << 8);
      y = 252645135 & (y | y << 4);
      y = 858993459 & (y | y << 2);
      y = 1431655765 & (y | y << 1);
      return x | y << 1;
    }
    function getLeftmost(start) {
      var p = start, leftmost = start;
      do {
        p.x < leftmost.x && (leftmost = p);
        p = p.next;
      } while (p !== start);
      return leftmost;
    }
    function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
      return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
    }
    function isValidDiagonal(a, b) {
      return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
    }
    function area(p, q, r) {
      return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
    }
    function equals(p1, p2) {
      return p1.x === p2.x && p1.y === p2.y;
    }
    function intersects(p1, q1, p2, q2) {
      if (equals(p1, q1) && equals(p2, q2) || equals(p1, q2) && equals(p2, q1)) return true;
      return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 && area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
    }
    function intersectsPolygon(a, b) {
      var p = a;
      do {
        if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects(p, p.next, a, b)) return true;
        p = p.next;
      } while (p !== a);
      return false;
    }
    function locallyInside(a, b) {
      return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
    }
    function middleInside(a, b) {
      var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
      do {
        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 Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
      a.next = b;
      b.prev = a;
      a2.next = an;
      an.prev = a2;
      b2.next = a2;
      a2.prev = b2;
      bp.next = b2;
      b2.prev = bp;
      return b2;
    }
    function insertNode(i, x, y, last) {
      var p = new Node(i, x, y);
      if (last) {
        p.next = last.next;
        p.prev = last;
        last.next.prev = p;
        last.next = p;
      } else {
        p.prev = p;
        p.next = p;
      }
      return p;
    }
    function removeNode(p) {
      p.next.prev = p.prev;
      p.prev.next = p.next;
      p.prevZ && (p.prevZ.nextZ = p.nextZ);
      p.nextZ && (p.nextZ.prevZ = p.prevZ);
    }
    function Node(i, x, y) {
      this.i = i;
      this.x = x;
      this.y = y;
      this.prev = null;
      this.next = null;
      this.z = null;
      this.prevZ = null;
      this.nextZ = null;
      this.steiner = false;
    }
    earcut.deviation = function(data, holeIndices, dim, triangles) {
      var hasHoles = holeIndices && holeIndices.length;
      var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
      var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
      if (hasHoles) for (var i = 0, len = holeIndices.length; i < len; i++) {
        var start = holeIndices[i] * dim;
        var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
        polygonArea -= Math.abs(signedArea(data, start, end, dim));
      }
      var trianglesArea = 0;
      for (i = 0; i < triangles.length; i += 3) {
        var a = triangles[i] * dim;
        var b = triangles[i + 1] * dim;
        var c = triangles[i + 2] * dim;
        trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) - (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
      }
      return 0 === polygonArea && 0 === trianglesArea ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
    };
    function signedArea(data, start, end, dim) {
      var sum = 0;
      for (var i = start, j = end - dim; i < end; i += dim) {
        sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
        j = i;
      }
      return sum;
    }
    earcut.flatten = function(data) {
      var dim = data[0][0].length, result = {
        vertices: [],
        holes: [],
        dimensions: dim
      }, holeIndex = 0;
      for (var i = 0; i < data.length; i++) {
        for (var j = 0; j < data[i].length; j++) for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
        if (i > 0) {
          holeIndex += data[i - 1].length;
          result.holes.push(holeIndex);
        }
      }
      return result;
    };
  }), {} ],
  117: [ (function(require, module, exports) {
    var Js = cc.js;
    var LineCap = require("./types").LineCap;
    var LineJoin = require("./types").LineJoin;
    var Helper = require("./helper");
    var CanvasRenderCmd = function(renderable) {
      this._rootCtor(renderable);
      this._needDraw = true;
      this.cmds = [];
      this.style = {
        strokeStyle: "black",
        fillStyle: "white",
        lineCap: "butt",
        lineJoin: "miter",
        miterLimit: 10
      };
    };
    var _p = CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
    _p.constructor = CanvasRenderCmd;
    _p._updateCurrentRegions = function() {
      var temp = this._currentRegion;
      this._currentRegion = this._oldRegion;
      this._oldRegion = temp;
      this._currentRegion.setTo(0, 0, cc.visibleRect.width, cc.visibleRect.height);
    };
    _p.rendering = function(ctx, scaleX, scaleY) {
      var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
      wrapper.setTransform(this._worldTransform, scaleX, scaleY);
      context.save();
      context.scale(1, -1);
      var style = this.style;
      context.strokeStyle = style.strokeStyle;
      context.fillStyle = style.fillStyle;
      context.lineWidth = style.lineWidth;
      context.lineJoin = style.lineJoin;
      context.miterLimit = style.miterLimit;
      var endPath = true;
      var cmds = this.cmds;
      for (var i = 0, l = cmds.length; i < l; i++) {
        var cmd = cmds[i];
        var ctxCmd = cmd[0], args = cmd[1];
        if ("moveTo" === ctxCmd && endPath) {
          context.beginPath();
          endPath = false;
        } else "fill" !== ctxCmd && "stroke" !== ctxCmd && "fillRect" !== ctxCmd || (endPath = true);
        "function" === typeof context[ctxCmd] ? context[ctxCmd].apply(context, args) : context[ctxCmd] = args;
      }
      context.restore();
    };
    _p.setStrokeColor = function(v) {
      var strokeStyle = "rgba(" + (0 | v.r) + "," + (0 | v.g) + "," + (0 | v.b) + "," + v.a / 255 + ")";
      this.cmds.push([ "strokeStyle", strokeStyle ]);
      this.style.strokeStyle = strokeStyle;
    };
    _p.setFillColor = function(v) {
      var fillStyle = "rgba(" + (0 | v.r) + "," + (0 | v.g) + "," + (0 | v.b) + "," + v.a / 255 + ")";
      this.cmds.push([ "fillStyle", fillStyle ]);
      this.style.fillStyle = fillStyle;
    };
    _p.setLineWidth = function(v) {
      this.cmds.push([ "lineWidth", v ]);
      this.style.lineWidth = v;
    };
    _p.setLineCap = function(v) {
      var lineCap = "butt";
      v === LineCap.BUTT ? lineCap = "butt" : v === LineCap.ROUND ? lineCap = "round" : v === LineCap.SQUARE && (lineCap = "square");
      this.cmds.push([ "lineCap", lineCap ]);
      this.style.lineCap = lineCap;
    };
    _p.setLineJoin = function(v) {
      var lineJoin = "bevel";
      v === LineJoin.BEVEL ? lineJoin = "bevel" : v === LineJoin.ROUND ? lineJoin = "round" : v === LineJoin.MITER && (lineJoin = "miter");
      this.cmds.push([ "lineJoin", lineJoin ]);
      this.style.lineJoin = lineJoin;
    };
    _p.setMiterLimit = function(v) {
      this.cmds.push([ "miterLimit", v ]);
      this.style.miterLimit = v;
    };
    _p.beginPath = function() {};
    _p.moveTo = function(x, y) {
      this.cmds.push([ "moveTo", [ x, y ] ]);
    };
    _p.lineTo = function(x, y) {
      this.cmds.push([ "lineTo", [ x, y ] ]);
    };
    _p.bezierCurveTo = function(c1x, c1y, c2x, c2y, x, y) {
      this.cmds.push([ "bezierCurveTo", [ c1x, c1y, c2x, c2y, x, y ] ]);
    };
    _p.quadraticCurveTo = function(cx, cy, x, y) {
      this.cmds.push([ "quadraticCurveTo", [ cx, cy, x, y ] ]);
    };
    _p.arc = function(cx, cy, r, startAngle, endAngle, counterclockwise) {
      Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise);
    };
    _p.ellipse = function(cx, cy, rx, ry) {
      Helper.ellipse(this, cx, cy, rx, ry);
    };
    _p.circle = function(cx, cy, r) {
      Helper.ellipse(this, cx, cy, r, r);
    };
    _p.rect = function(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();
    };
    _p.roundRect = function(x, y, w, h, r) {
      Helper.roundRect(this, x, y, w, h, r);
    };
    _p.fillRect = function(x, y, w, h) {
      this.cmds.push([ "fillRect", [ x, y, w, h ] ]);
      this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
    };
    _p.close = function() {
      this.cmds.push([ "closePath", [] ]);
    };
    _p.stroke = function() {
      this.cmds.push([ "stroke", [] ]);
      this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
    };
    _p.fill = function() {
      this.cmds.push([ "fill", [] ]);
      this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
    };
    _p.clear = function() {
      this.cmds.length = 0;
      this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
    };
    module.exports = CanvasRenderCmd;
  }), {
    "./helper": 121,
    "./types": 123
  } ],
  118: [ (function(require, module, exports) {
    var CanvasRenderCmd = require("./graphics-canvas-cmd");
    var WebGLRenderCmd = require("./graphics-webgl-cmd");
    var LineCap = require("./types").LineCap;
    var LineJoin = require("./types").LineJoin;
    var Js = cc.js;
    var GraphicsNode = _ccsg.Node.extend({
      ctor: function() {
        this._super();
        this.strokeColor = cc.Color.BLACK;
        this.fillColor = cc.Color.WHITE;
      },
      clear: function(clean) {
        this._renderCmd.clear(clean);
      },
      _createRenderCmd: function() {
        return cc._renderType === cc.game.RENDER_TYPE_CANVAS ? new CanvasRenderCmd(this) : new WebGLRenderCmd(this);
      }
    });
    var _p = GraphicsNode.prototype;
    _p._strokeColor = null;
    _p._fillColor = null;
    _p._lineWidth = 1;
    _p._lineCap = LineCap.BUTT;
    _p._lineJoin = LineJoin.MITER;
    _p._miterLimit = 10;
    _p.setStrokeColor = function(v) {
      this._strokeColor = v;
      this._renderCmd.setStrokeColor(v);
    };
    _p.getStrokeColor = function() {
      return this._strokeColor;
    };
    _p.setFillColor = function(v) {
      this._fillColor = v;
      this._renderCmd.setFillColor(v);
    };
    _p.getFillColor = function() {
      return this._fillColor;
    };
    _p.setLineWidth = function(v) {
      this._lineWidth = v;
      this._renderCmd.setLineWidth(v);
    };
    _p.getLineWidth = function() {
      return this._lineWidth;
    };
    _p.setLineCap = function(v) {
      this._lineCap = v;
      this._renderCmd.setLineCap(v);
    };
    _p.getLineCap = function() {
      return this._lineCap;
    };
    _p.setLineJoin = function(v) {
      this._lineJoin = v;
      this._renderCmd.setLineJoin(v);
    };
    _p.getLineJoin = function() {
      return this._lineJoin;
    };
    _p.setMiterLimit = function(v) {
      this._miterLimit = v;
      this._renderCmd.setMiterLimit(v);
    };
    _p.getMiterLimit = function() {
      return this._miterLimit;
    };
    _p.beginPath = function() {
      this._renderCmd.beginPath();
    };
    _p.moveTo = function(x, y) {
      this._renderCmd.moveTo(x, y);
    };
    _p.lineTo = function(x, y) {
      this._renderCmd.lineTo(x, y);
    };
    _p.bezierCurveTo = function(c1x, c1y, c2x, c2y, x, y) {
      this._renderCmd.bezierCurveTo(c1x, c1y, c2x, c2y, x, y);
    };
    _p.quadraticCurveTo = function(cx, cy, x, y) {
      this._renderCmd.quadraticCurveTo(cx, cy, x, y);
    };
    _p.arc = function(cx, cy, r, a0, a1, counterclockwise) {
      this._renderCmd.arc(cx, cy, r, a0, a1, counterclockwise);
    };
    _p.ellipse = function(cx, cy, rx, ry) {
      this._renderCmd.ellipse(cx, cy, rx, ry);
    };
    _p.circle = function(cx, cy, r) {
      this._renderCmd.circle(cx, cy, r);
    };
    _p.rect = function(x, y, w, h) {
      this._renderCmd.rect(x, y, w, h);
    };
    _p.roundRect = function(x, y, w, h, r) {
      this._renderCmd.roundRect(x, y, w, h, r);
    };
    _p.fillRect = function(x, y, w, h) {
      this._renderCmd.fillRect(x, y, w, h);
    };
    _p.close = function() {
      this._renderCmd.close();
    };
    _p.stroke = function() {
      this._renderCmd.stroke();
    };
    _p.fill = function() {
      this._renderCmd.fill();
    };
    module.exports = GraphicsNode;
  }), {
    "./graphics-canvas-cmd": 117,
    "./graphics-webgl-cmd": 119,
    "./types": 123
  } ],
  119: [ (function(require, module, exports) {
    var LineCap = require("./types").LineCap;
    var LineJoin = require("./types").LineJoin;
    var Earcut = require("./earcut");
    var Helper = require("./helper");
    var Vec2 = cc.Vec2;
    var Js = cc.js;
    var INIT_VERTS_SIZE = 32;
    var VERTS_FLOAT_LENGTH = 3;
    var VERTS_BYTE_LENGTH = 12;
    var MAX_BUFFER_SIZE = 65535;
    var PI = Math.PI;
    var min = Math.min;
    var max = Math.max;
    var ceil = Math.ceil;
    var acos = Math.acos;
    var cos = Math.cos;
    var sin = Math.sin;
    var atan2 = Math.atan2;
    var abs = Math.abs;
    function clamp(v, min, max) {
      if (v < min) return min;
      if (v > max) return max;
      return v;
    }
    var PointFlags = cc.Enum({
      PT_CORNER: 1,
      PT_LEFT: 2,
      PT_BEVEL: 4,
      PT_INNERBEVEL: 8
    });
    function Point(x, y) {
      Vec2.call(this, x, y);
      this.reset();
    }
    Js.extend(Point, Vec2);
    Point.prototype.reset = function() {
      this.dx = 0;
      this.dy = 0;
      this.dmx = 0;
      this.dmy = 0;
      this.flags = 0;
      this.len = 0;
    };
    function Path() {
      this.reset();
    }
    Path.prototype.reset = function() {
      this.closed = false;
      this.nbevel = 0;
      this.complex = true;
      this.points ? this.points.length = 0 : this.points = [];
    };
    function GraphicsBuffer() {
      this.vertsOffset = 0;
      this.vertsVBO = gl.createBuffer();
      this.vertsBuffer = null;
      this.uint32VertsBuffer = null;
      this.vertsDirty = false;
      this.indicesOffset = 0;
      this.indicesVBO = gl.createBuffer();
      this.indicesBuffer = null;
      this.indicesDirty = false;
    }
    GraphicsBuffer.prototype.clear = function() {
      this.vertsOffset = 0;
      this.indicesOffset = 0;
    };
    GraphicsBuffer.prototype.alloc = function(cverts, cindices) {
      var dnverts = this.vertsOffset + cverts;
      if (dnverts > MAX_BUFFER_SIZE) return false;
      var verts = this.vertsBuffer;
      var nverts = verts ? verts.length / VERTS_FLOAT_LENGTH : 0;
      if (dnverts > nverts) {
        0 === nverts && (nverts = INIT_VERTS_SIZE);
        while (dnverts > nverts) nverts *= 2;
        var newBuffer = new Float32Array(nverts * VERTS_FLOAT_LENGTH);
        var newUint32Buffer = new Uint32Array(newBuffer.buffer);
        if (verts) {
          var uint32VertsBuffer = this.uint32VertsBuffer;
          for (var i = 0, l = verts.length; i < l; i += VERTS_FLOAT_LENGTH) {
            newBuffer[i] = verts[i];
            newBuffer[i + 1] = verts[i + 1];
            newUint32Buffer[i + 2] = uint32VertsBuffer[i + 2];
          }
        }
        this.vertsBuffer = newBuffer;
        this.uint32VertsBuffer = newUint32Buffer;
      }
      var indices = this.indicesBuffer;
      var dnindices = this.indicesOffset + cindices;
      var nindices = indices ? indices.length : 0;
      if (dnindices > nindices) {
        0 === nindices && (nindices = 3 * INIT_VERTS_SIZE);
        while (dnindices > nindices) nindices *= 2;
        var newIndices = new Uint16Array(nindices);
        if (indices) for (var i = 0, l = indices.length; i < l; i++) newIndices[i] = indices[i];
        this.indicesBuffer = newIndices;
      }
      return true;
    };
    function WebGLRenderCmd(renderable) {
      this._rootCtor(renderable);
      this._needDraw = true;
      var gl = cc._renderContext;
      this._buffers = [];
      this._buffer = null;
      this._allocBuffer();
      this._matrix = new cc.math.Matrix4();
      this._matrix.identity();
      this._paths = [];
      this._points = [];
      this._curColorValue = 0;
      this._blendFunc = new cc.BlendFunc(cc.macro.BLEND_SRC, cc.macro.BLEND_DST);
      var shader = new cc.GLProgram();
      shader.initWithVertexShaderByteArray(cc.PresetShaders.POSITION_COLOR_VERT, cc.PresetShaders.POSITION_COLOR_FRAG);
      shader.retain();
      shader.addAttribute(cc.macro.ATTRIBUTE_NAME_POSITION, cc.macro.VERTEX_ATTRIB_POSITION);
      shader.addAttribute(cc.macro.ATTRIBUTE_NAME_COLOR, cc.macro.VERTEX_ATTRIB_COLOR);
      shader.link();
      shader.updateUniforms();
      this._shaderProgram = shader;
      this._allocVerts(INIT_VERTS_SIZE);
    }
    WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype);
    WebGLRenderCmd.prototype.constructor = WebGLRenderCmd;
    var _p = WebGLRenderCmd.prototype;
    _p._tessTol = .25;
    _p._distTol = .01;
    _p.lineWidth = 1;
    _p.lineCap = LineCap.BUTT;
    _p.lineJoin = LineJoin.MITER;
    _p.miterLimit = 10;
    _p.beginPath = function() {
      this._pathOffset = this._pathLength;
    };
    _p.moveTo = function(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;
    };
    _p.lineTo = function(x, y) {
      this._addPoint(x, y, PointFlags.PT_CORNER);
      this._commandx = x;
      this._commandy = y;
    };
    _p.bezierCurveTo = function(c1x, c1y, c2x, c2y, x, y) {
      var path = this._curPath;
      var last = path.points[path.points.length - 1];
      if (last.x === c1x && last.y === c1y && c2x === x && c2y === y) {
        this.lineTo(x, y);
        return;
      }
      this._tesselateBezier(last.x, last.y, c1x, c1y, c2x, c2y, x, y, 0, PointFlags.PT_CORNER);
      this._commandx = x;
      this._commandy = y;
    };
    _p.quadraticCurveTo = function(cx, cy, x, y) {
      var x0 = this._commandx;
      var y0 = this._commandy;
      this.bezierCurveTo(x0 + 2 / 3 * (cx - x0), y0 + 2 / 3 * (cy - y0), x + 2 / 3 * (cx - x), y + 2 / 3 * (cy - y), x, y);
    };
    _p.arc = function(cx, cy, r, startAngle, endAngle, counterclockwise) {
      Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise);
    };
    _p.ellipse = function(cx, cy, rx, ry) {
      Helper.ellipse(this, cx, cy, rx, ry);
      this._curPath.complex = false;
    };
    _p.circle = function(cx, cy, r) {
      Helper.ellipse(this, cx, cy, r, r);
      this._curPath.complex = false;
    };
    _p.rect = function(x, y, w, h) {
      this.moveTo(x, y);
      this.lineTo(x, y + h);
      this.lineTo(x + w, y + h);
      this.lineTo(x + w, y);
      this.close();
      this._curPath.complex = false;
    };
    _p.roundRect = function(x, y, w, h, r) {
      Helper.roundRect(this, x, y, w, h, r);
      this._curPath.complex = false;
    };
    _p.fillRect = function(x, y, w, h) {
      this.rect(x, y, w, h);
      this.fill();
    };
    _p.close = function() {
      this._curPath.closed = true;
    };
    _p.stroke = function() {
      this._flattenPaths();
      var color = this._strokeColor;
      this._curColorValue = (color.a << 24 >>> 0) + (color.b << 16) + (color.g << 8) + color.r;
      this._expandStroke();
      this._updatePathOffset = true;
    };
    _p.fill = function() {
      var color = this._fillColor;
      this._curColorValue = (color.a << 24 >>> 0) + (color.b << 16) + (color.g << 8) + color.r;
      this._expandFill();
      this._updatePathOffset = true;
      this._filling = false;
    };
    _p._strokeColor = null;
    _p._fillColor = null;
    _p.setStrokeColor = function(c) {
      this._strokeColor = c;
    };
    _p.getStrokeColor = function() {
      return this._strokeColor;
    };
    _p.setFillColor = function(c) {
      this._fillColor = c;
    };
    _p.getFillColor = function() {
      return this._fillColor;
    };
    _p.setLineWidth = function(v) {
      this.lineWidth = v;
    };
    _p.setLineJoin = function(v) {
      this.lineJoin = v;
    };
    _p.setLineCap = function(v) {
      this.lineCap = v;
    };
    _p.setMiterLimit = function(v) {
      this.miterLimit = v;
    };
    Js.getset(_p, "strokeColor", _p.getStrokeColor, _p.setStrokeColor);
    Js.getset(_p, "fillColor", _p.getFillColor, _p.setFillColor);
    _p._render = function() {
      var buffers = this._buffers;
      if (0 === buffers.length) return;
      var gl = cc._renderContext;
      for (var i = 0, l = buffers.length; i < l; i++) {
        var buffer = buffers[i];
        gl.bindBuffer(gl.ARRAY_BUFFER, buffer.vertsVBO);
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer.indicesVBO);
        if (buffer.vertsDirty) {
          gl.bufferData(gl.ARRAY_BUFFER, buffer.vertsBuffer, gl.STREAM_DRAW);
          buffer.vertsDirty = false;
        }
        if (buffer.indicesDirty && buffer.indicesBuffer) {
          gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, buffer.indicesBuffer, gl.STREAM_DRAW);
          buffer.indicesDirty = false;
        }
        gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION);
        gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR);
        gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, VERTS_BYTE_LENGTH, 0);
        gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, VERTS_BYTE_LENGTH, 8);
        gl.drawElements(gl.TRIANGLES, buffer.indicesOffset, gl.UNSIGNED_SHORT, 0);
        cc.g_NumberOfDraws++;
      }
      false;
    };
    _p.rendering = function() {
      cc.gl.blendFunc(this._blendFunc.src, this._blendFunc.dst);
      var wt = this._worldTransform, mat = this._matrix.mat;
      mat[0] = wt.a;
      mat[4] = wt.c;
      mat[12] = wt.tx;
      mat[1] = wt.b;
      mat[5] = wt.d;
      mat[13] = wt.ty;
      var shader = this._shaderProgram;
      shader.use();
      shader._setUniformForMVPMatrixWithMat4(this._matrix);
      this._render();
    };
    _p.clear = function(clean) {
      this._pathLength = 0;
      this._pathOffset = 0;
      this._pointsOffset = 0;
      this._curPath = null;
      if (clean) {
        this._paths.length = 0;
        this._points.length = 0;
        this._buffer = null;
        this._buffers = [];
      } else {
        var buffers = this._buffers;
        for (var i = 0; i < buffers.length; i++) buffers[i].clear();
        this._buffer = buffers[0];
      }
    };
    _p._updatePathOffset = false;
    _p._paths = null;
    _p._pathLength = 0;
    _p._pathOffset = 0;
    _p._points = null;
    _p._pointsOffset = 0;
    _p._commandx = 0;
    _p._commandy = 0;
    _p._addPath = function() {
      var offset = this._pathLength;
      var path = this._paths[offset];
      if (path) path.reset(); else {
        path = new Path();
        this._paths.push(path);
      }
      this._pathLength++;
      this._curPath = path;
      return path;
    };
    _p._addPoint = function(x, y, flags) {
      var path = this._curPath;
      if (!path) return;
      var pt;
      var points = this._points;
      var pathPoints = path.points;
      var offset = this._pointsOffset++;
      pt = points[offset];
      if (pt) {
        pt.x = x;
        pt.y = y;
      } else {
        pt = new Point(x, y);
        points.push(pt);
      }
      pt.flags = flags;
      pathPoints.push(pt);
    };
    _p._flattenPaths = function() {
      var paths = this._paths;
      for (var i = this._pathOffset, l = this._pathLength; i < l; i++) {
        var path = paths[i];
        var pts = path.points;
        var p0 = pts[pts.length - 1];
        var p1 = pts[0];
        if (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 = p1.sub(p0);
          p0.len = dPos.mag();
          (dPos.x || dPos.y) && dPos.normalizeSelf();
          p0.dx = dPos.x;
          p0.dy = dPos.y;
          p0 = p1;
          p1 = pts[j + 1];
        }
      }
    };
    _p._allocBuffer = function() {
      if (this._buffer) {
        var index = this._buffers.indexOf(this._buffer);
        if (index < this._buffers.length - 1) {
          this._buffer = this._buffers[index + 1];
          return;
        }
      }
      var buffer = new GraphicsBuffer();
      this._buffers.push(buffer);
      this._buffer = buffer;
    };
    _p._allocVerts = function(cverts) {
      this._buffer || this._allocBuffer();
      var nIndices = 3 * (cverts - 2 * (this._pathLength - this._pathOffset));
      if (!this._buffer.alloc(cverts, nIndices)) {
        this._allocBuffer();
        this._buffer.alloc(cverts, nIndices);
      }
      this._buffer.vertsDirty = true;
    };
    _p._expandStroke = function() {
      var w = .5 * this.lineWidth, lineCap = this.lineCap, lineJoin = this.lineJoin, miterLimit = this.miterLimit;
      var ncap = this._curveDivs(w, PI, this._tessTol);
      var paths = this._paths;
      this._calculateJoins(w, lineJoin, miterLimit);
      var cverts = 0;
      for (var i = this._pathOffset, l = this._pathLength; i < l; i++) {
        var path = paths[i];
        var pointsLength = path.points.length;
        lineJoin === LineJoin.ROUND ? cverts += 2 * (pointsLength + path.nbevel * (ncap + 2) + 1) : cverts += 2 * (pointsLength + 5 * path.nbevel + 1);
        path.closed || (lineCap === LineCap.ROUND ? cverts += 2 * (2 * ncap + 2) : cverts += 12);
      }
      this._allocVerts(cverts);
      var buffer = this._buffer;
      for (var i = this._pathOffset, l = this._pathLength; i < l; i++) {
        var path = paths[i];
        var pts = path.points;
        var pointsLength = path.points.length;
        var p0, p1;
        var s, e, loop;
        loop = path.closed;
        var offset = buffer.vertsOffset;
        if (loop) {
          p0 = pts[pointsLength - 1];
          p1 = pts[0];
          s = 0;
          e = pointsLength;
        } else {
          p0 = pts[0];
          p1 = pts[1];
          s = 1;
          e = pointsLength - 1;
        }
        if (!loop) {
          var dPos = p1.sub(p0);
          dPos.normalizeSelf();
          var dx = dPos.x;
          var dy = dPos.y;
          lineCap === LineCap.BUTT ? this._buttCap(p0, dx, dy, w, 0) : lineCap === LineCap.SQUARE ? this._buttCap(p0, dx, dy, w, w) : lineCap === LineCap.ROUND && this._roundCapStart(p0, dx, dy, w, ncap);
        }
        for (var j = s; j < e; ++j) {
          if (lineJoin === LineJoin.ROUND) this._roundJoin(p0, p1, w, w, ncap); else if (0 !== (p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL))) this._bevelJoin(p0, p1, w, w); else {
            this._vset(p1.x + p1.dmx * w, p1.y + p1.dmy * w);
            this._vset(p1.x - p1.dmx * w, p1.y - p1.dmy * w);
          }
          p0 = p1;
          p1 = pts[j + 1];
        }
        if (loop) {
          var vertsBuffer = buffer.vertsBuffer;
          this._vset(vertsBuffer[offset * VERTS_FLOAT_LENGTH], vertsBuffer[offset * VERTS_FLOAT_LENGTH + 1]);
          this._vset(vertsBuffer[(offset + 1) * VERTS_FLOAT_LENGTH], vertsBuffer[(offset + 1) * VERTS_FLOAT_LENGTH + 1]);
        } else {
          var dPos = p1.sub(p0);
          dPos.normalizeSelf();
          var dx = dPos.x;
          var dy = dPos.y;
          lineCap === LineCap.BUTT ? this._buttCap(p1, dx, dy, w, 0) : lineCap === LineCap.BUTT || lineCap === LineCap.SQUARE ? this._buttCap(p1, dx, dy, w, w) : lineCap === LineCap.ROUND && this._roundCapEnd(p1, dx, dy, w, ncap);
        }
        var indicesOffset = buffer.indicesOffset;
        var indicesBuffer = buffer.indicesBuffer;
        for (var start = offset + 2, end = buffer.vertsOffset; start < end; start++) {
          indicesBuffer[indicesOffset++] = start - 2;
          indicesBuffer[indicesOffset++] = start - 1;
          indicesBuffer[indicesOffset++] = start;
        }
        buffer.indicesOffset = indicesOffset;
        buffer.indicesDirty = true;
      }
    };
    _p._expandFill = function() {
      var paths = this._paths;
      var cverts = 0;
      for (var i = this._pathOffset, l = this._pathLength; i < l; i++) {
        var path = paths[i];
        var pointsLength = path.points.length;
        cverts += pointsLength;
      }
      this._allocVerts(cverts);
      var buffer = this._buffer;
      for (var i = this._pathOffset, l = this._pathLength; i < l; i++) {
        var path = paths[i];
        var pts = path.points;
        var pointsLength = pts.length;
        if (0 === pointsLength) continue;
        var offset = buffer.vertsOffset;
        for (var j = 0; j < pointsLength; ++j) this._vset(pts[j].x, pts[j].y, .5, 1);
        var indicesOffset = path.indicesOffset = buffer.indicesOffset;
        var indicesBuffer = buffer.indicesBuffer;
        var nIndices = 0;
        if (path.complex) {
          var data = [];
          var start = offset * VERTS_FLOAT_LENGTH, end = buffer.vertsOffset * VERTS_FLOAT_LENGTH;
          for (var j = start; j < end; j += VERTS_FLOAT_LENGTH) {
            data.push(buffer.vertsBuffer[j]);
            data.push(buffer.vertsBuffer[j + 1]);
          }
          var newIndices = Earcut(data, null, 2);
          if (!newIndices || 0 === newIndices.length) continue;
          nIndices = newIndices.length;
          for (var j = 0, l3 = nIndices; j < l3; j++) indicesBuffer[indicesOffset + j] = newIndices[j] + offset;
        } else {
          var first = offset;
          for (var start = offset + 2, end = buffer.vertsOffset; start < end; start++) {
            indicesBuffer[indicesOffset++] = first;
            indicesBuffer[indicesOffset++] = start - 1;
            indicesBuffer[indicesOffset++] = start;
          }
          nIndices = indicesOffset - buffer.indicesOffset;
        }
        buffer.indicesOffset += nIndices;
        buffer.indicesDirty = true;
      }
    };
    _p._curveDivs = function(r, arc, tol) {
      var da = 2 * acos(r / (r + tol));
      return max(2, ceil(arc / da));
    };
    _p._calculateJoins = function(w, lineJoin, miterLimit) {
      var iw = 0;
      w > 0 && (iw = 1 / w);
      var paths = this._paths;
      for (var i = this._pathOffset, l = this._pathLength; i < l; i++) {
        var path = paths[i];
        var pts = path.points;
        var ptsLength = pts.length;
        var p0 = pts[ptsLength - 1];
        var p1 = pts[0];
        var nleft = 0;
        path.nbevel = 0;
        for (var j = 0; j < ptsLength; j++) {
          var dmr2, cross, limit;
          var dlx0 = p0.dy;
          var dly0 = -p0.dx;
          var dlx1 = p1.dy;
          var dly1 = -p1.dx;
          p1.dmx = .5 * (dlx0 + dlx1);
          p1.dmy = .5 * (dly0 + dly1);
          dmr2 = p1.dmx * p1.dmx + p1.dmy * p1.dmy;
          if (dmr2 > 1e-6) {
            var scale = 1 / dmr2;
            scale > 600 && (scale = 600);
            p1.dmx *= scale;
            p1.dmy *= scale;
          }
          cross = p1.dx * p0.dy - p0.dx * p1.dy;
          if (cross > 0) {
            nleft++;
            p1.flags |= PointFlags.PT_LEFT;
          }
          limit = max(11, min(p0.len, p1.len) * iw);
          dmr2 * limit * limit < 1 && (p1.flags |= PointFlags.PT_INNERBEVEL);
          p1.flags & PointFlags.PT_CORNER && (dmr2 * miterLimit * miterLimit < 1 || lineJoin === LineJoin.BEVEL || lineJoin === LineJoin.ROUND) && (p1.flags |= PointFlags.PT_BEVEL);
          0 !== (p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) && path.nbevel++;
          p0 = p1;
          p1 = pts[j + 1];
        }
      }
    };
    _p._vset = function(x, y) {
      var buffer = this._buffer;
      var offset = buffer.vertsOffset * VERTS_FLOAT_LENGTH;
      var vertsBuffer = buffer.vertsBuffer;
      vertsBuffer[offset] = x;
      vertsBuffer[offset + 1] = y;
      buffer.uint32VertsBuffer[offset + 2] = this._curColorValue;
      buffer.vertsOffset++;
    };
    _p._chooseBevel = function(bevel, p0, p1, w) {
      var x = p1.x;
      var y = p1.y;
      var x0, y0, x1, y1;
      if (0 !== bevel) {
        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 ];
    };
    _p._buttCap = function(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);
      this._vset(px - dlx * w, py - dly * w);
    };
    _p._roundCapStart = function(p, dx, dy, w, ncap) {
      var px = p.x;
      var py = p.y;
      var dlx = dy;
      var dly = -dx;
      for (var i = 0; i < ncap; i++) {
        var a = i / (ncap - 1) * PI;
        var ax = cos(a) * w, ay = sin(a) * w;
        this._vset(px - dlx * ax - dx * ay, py - dly * ax - dy * ay);
        this._vset(px, py);
      }
      this._vset(px + dlx * w, py + dly * w);
      this._vset(px - dlx * w, py - dly * w);
    };
    _p._roundCapEnd = function(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);
      this._vset(px - dlx * w, py - dly * w);
      for (var i = 0; i < ncap; i++) {
        var a = i / (ncap - 1) * PI;
        var ax = cos(a) * w, ay = sin(a) * w;
        this._vset(px, py);
        this._vset(px - dlx * ax + dx * ay, py - dly * ax + dy * ay);
      }
    };
    _p._roundJoin = function(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 (0 !== (p1.flags & PointFlags.PT_LEFT)) {
        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);
        a1 > a0 && (a1 -= 2 * PI);
        this._vset(lx0, ly0);
        this._vset(p1x - dlx0 * rw, p1.y - dly0 * rw);
        var n = clamp(ceil((a0 - a1) / PI) * ncap, 2, ncap);
        for (var i = 0; i < n; i++) {
          var u = i / (n - 1);
          var a = a0 + u * (a1 - a0);
          var rx = p1x + cos(a) * rw;
          var ry = p1y + sin(a) * rw;
          this._vset(p1x, p1y);
          this._vset(rx, ry);
        }
        this._vset(lx1, ly1);
        this._vset(p1x - dlx1 * rw, p1y - dly1 * rw);
      } 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 a0 = atan2(dly0, dlx0);
        var a1 = atan2(dly1, dlx1);
        a1 < a0 && (a1 += 2 * PI);
        this._vset(p1x + dlx0 * rw, p1y + dly0 * rw);
        this._vset(rx0, ry0);
        var n = clamp(ceil((a1 - a0) / PI) * ncap, 2, ncap);
        for (var i = 0; i < n; i++) {
          var u = i / (n - 1);
          var a = a0 + u * (a1 - a0);
          var lx = p1x + cos(a) * lw;
          var ly = p1y + sin(a) * lw;
          this._vset(lx, ly);
          this._vset(p1x, p1y);
        }
        this._vset(p1x + dlx1 * rw, p1y + dly1 * rw);
        this._vset(rx1, ry1);
      }
    };
    _p._bevelJoin = function(p0, p1, lw, rw) {
      var rx0, ry0, rx1, ry1;
      var lx0, ly0, lx1, ly1;
      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);
        this._vset(p1.x - dlx0 * rw, p1.y - dly0 * rw);
        this._vset(lx1, ly1);
        this._vset(p1.x - dlx1 * rw, p1.y - dly1 * rw);
      } else {
        var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw);
        rx0 = out[0];
        ry0 = out[1];
        rx1 = out[2];
        ry1 = out[3];
        this._vset(p1.x + dlx0 * lw, p1.y + dly0 * lw);
        this._vset(rx0, ry0);
        this._vset(p1.x + dlx1 * lw, p1.y + dly1 * lw);
        this._vset(rx1, ry1);
      }
    };
    _p._tesselateBezier = function(x1, y1, x2, y2, x3, y3, x4, y4, level, type) {
      var x12, y12, x23, y23, x34, y34, x123, y123, x234, y234, x1234, y1234;
      var dx, dy, d2, d3;
      if (level > 10) return;
      x12 = .5 * (x1 + x2);
      y12 = .5 * (y1 + y2);
      x23 = .5 * (x2 + x3);
      y23 = .5 * (y2 + y3);
      x34 = .5 * (x3 + x4);
      y34 = .5 * (y3 + y4);
      x123 = .5 * (x12 + x23);
      y123 = .5 * (y12 + y23);
      dx = x4 - x1;
      dy = y4 - y1;
      d2 = abs((x2 - x4) * dy - (y2 - y4) * dx);
      d3 = abs((x3 - x4) * dy - (y3 - y4) * dx);
      if ((d2 + d3) * (d2 + d3) < this._tessTol * (dx * dx + dy * dy)) {
        this._addPoint(x4, y4, 0 === type ? type | PointFlags.PT_BEVEL : type);
        return;
      }
      x234 = .5 * (x23 + x34);
      y234 = .5 * (y23 + y34);
      x1234 = .5 * (x123 + x234);
      y1234 = .5 * (y123 + y234);
      this._tesselateBezier(x1, y1, x12, y12, x123, y123, x1234, y1234, level + 1, 0);
      this._tesselateBezier(x1234, y1234, x234, y234, x34, y34, x4, y4, level + 1, type);
    };
    module.exports = WebGLRenderCmd;
  }), {
    "./earcut": 116,
    "./helper": 121,
    "./types": 123
  } ],
  120: [ (function(require, module, exports) {
    var LineCap = require("./types").LineCap;
    var LineJoin = require("./types").LineJoin;
    var Graphics = cc.Class({
      name: "cc.Graphics",
      extends: cc._RendererUnderSG,
      editor: false,
      properties: {
        _lineWidth: 1,
        _strokeColor: cc.Color.BLACK,
        _lineJoin: LineJoin.MITER,
        _lineCap: LineCap.BUTT,
        _fillColor: cc.Color.WHITE,
        _miterLimit: 10,
        lineWidth: {
          get: function() {
            return this._lineWidth;
          },
          set: function(value) {
            this._sgNode.lineWidth = this._lineWidth = value;
          }
        },
        lineJoin: {
          get: function() {
            return this._lineJoin;
          },
          set: function(value) {
            this._sgNode.lineJoin = this._lineJoin = value;
          },
          type: LineJoin
        },
        lineCap: {
          get: function() {
            return this._lineCap;
          },
          set: function(value) {
            this._sgNode.lineCap = this._lineCap = value;
          },
          type: LineCap
        },
        strokeColor: {
          get: function() {
            return this._strokeColor;
          },
          set: function(value) {
            this._sgNode.strokeColor = this._strokeColor = value;
          }
        },
        fillColor: {
          get: function() {
            return this._fillColor;
          },
          set: function(value) {
            this._sgNode.fillColor = this._fillColor = value;
          }
        },
        miterLimit: {
          get: function() {
            return this._miterLimit;
          },
          set: function(value) {
            this._sgNode.miterLimit = this._miterLimit = value;
          }
        }
      },
      statics: {
        LineJoin: LineJoin,
        LineCap: LineCap
      },
      _createSgNode: function() {
        var sgNode;
        var func;
        false;
        return new _ccsg.GraphicsNode();
      },
      _initSgNode: function() {
        var sgNode = this._sgNode;
        sgNode.lineWidth = this._lineWidth;
        sgNode.lineJoin = this._lineJoin;
        sgNode.lineCap = this._lineCap;
        sgNode.strokeColor = this._strokeColor;
        sgNode.fillColor = this._fillColor;
        sgNode.miterLimit = this._miterLimit;
        sgNode.setContentSize(this.node.getContentSize(true));
      },
      moveTo: function(x, y) {
        this._sgNode.moveTo(x, y);
      },
      lineTo: function(x, y) {
        this._sgNode.lineTo(x, y);
      },
      bezierCurveTo: function(c1x, c1y, c2x, c2y, x, y) {
        this._sgNode.bezierCurveTo(c1x, c1y, c2x, c2y, x, y);
      },
      quadraticCurveTo: function(cx, cy, x, y) {
        this._sgNode.quadraticCurveTo(cx, cy, x, y);
      },
      arc: function(cx, cy, r, startAngle, endAngle, counterclockwise) {
        counterclockwise = counterclockwise || false;
        this._sgNode.arc(cx, cy, r, startAngle, endAngle, counterclockwise);
      },
      ellipse: function(cx, cy, rx, ry) {
        this._sgNode.ellipse(cx, cy, rx, ry);
      },
      circle: function(cx, cy, r) {
        this._sgNode.circle(cx, cy, r);
      },
      rect: function(x, y, w, h) {
        this._sgNode.rect(x, y, w, h);
      },
      roundRect: function(x, y, w, h, r) {
        this._sgNode.roundRect(x, y, w, h, r);
      },
      fillRect: function(x, y, w, h) {
        this._sgNode.fillRect(x, y, w, h);
      },
      clear: function(clean) {
        this._sgNode.clear(!!clean);
      },
      close: function() {
        this._sgNode.close();
      },
      stroke: function() {
        this._sgNode.stroke();
      },
      fill: function() {
        this._sgNode.fill();
      }
    });
    cc.Graphics = module.exports = Graphics;
  }), {
    "./types": 123
  } ],
  121: [ (function(require, module, exports) {
    var PI = Math.PI;
    var min = Math.min;
    var max = Math.max;
    var cos = Math.cos;
    var sin = Math.sin;
    var abs = Math.abs;
    var sign = Math.sign;
    var KAPPA90 = .5522847493;
    function arc(ctx, cx, cy, r, startAngle, endAngle, counterclockwise) {
      counterclockwise = counterclockwise || false;
      var a = 0, da = 0, hda = 0, kappa = 0;
      var dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0;
      var px = 0, py = 0, ptanx = 0, ptany = 0;
      var i, ndivs;
      da = endAngle - startAngle;
      if (counterclockwise) if (abs(da) >= 2 * PI) da = 2 * PI; else while (da < 0) da += 2 * PI; else if (abs(da) >= 2 * PI) da = 2 * -PI; else while (da > 0) da -= 2 * PI;
      ndivs = 0 | max(1, min(abs(da) / (.5 * PI) + .5, 5));
      hda = da / ndivs / 2;
      kappa = abs(4 / 3 * (1 - cos(hda)) / sin(hda));
      counterclockwise || (kappa = -kappa);
      for (i = 0; i <= ndivs; i++) {
        a = startAngle + da * (i / ndivs);
        dx = cos(a);
        dy = sin(a);
        x = cx + dx * r;
        y = cy + dy * r;
        tanx = -dy * r * kappa;
        tany = dx * r * kappa;
        0 === i ? ctx.moveTo(x, y) : 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 < .1) {
        ctx.rect(x, y, w, h);
        return;
      }
      var rx = min(r, .5 * abs(w)) * sign(w), ry = min(r, .5 * abs(h)) * sign(h);
      ctx.moveTo(x, y + ry);
      ctx.lineTo(x, y + h - ry);
      ctx.bezierCurveTo(x, y + h - ry * (1 - KAPPA90), x + rx * (1 - KAPPA90), y + h, x + rx, y + h);
      ctx.lineTo(x + w - rx, y + h);
      ctx.bezierCurveTo(x + w - rx * (1 - KAPPA90), y + h, x + w, y + h - ry * (1 - KAPPA90), x + w, y + h - ry);
      ctx.lineTo(x + w, y + ry);
      ctx.bezierCurveTo(x + w, y + ry * (1 - KAPPA90), x + w - rx * (1 - KAPPA90), y, x + w - rx, y);
      ctx.lineTo(x + rx, y);
      ctx.bezierCurveTo(x + rx * (1 - KAPPA90), y, x, y + ry * (1 - KAPPA90), x, y + ry);
      ctx.close();
    }
    module.exports = {
      arc: arc,
      ellipse: ellipse,
      roundRect: roundRect
    };
  }), {} ],
  122: [ (function(require, module, exports) {
    "use strict";
    var GraphicsNode;
    true;
    GraphicsNode = _ccsg.GraphicsNode = require("./graphics-node");
    if (GraphicsNode) {
      var misc = require("../utils/misc");
      misc.propertyDefine(GraphicsNode, [ "lineWidth", "lineCap", "lineJoin", "miterLimit", "strokeColor", "fillColor" ], {});
    }
    require("./graphics");
  }), {
    "../utils/misc": 225,
    "./graphics": 120,
    "./graphics-node": 118
  } ],
  123: [ (function(require, module, exports) {
    "use strict";
    var LineCap = cc.Enum({
      BUTT: 0,
      ROUND: 1,
      SQUARE: 2
    });
    var LineJoin = cc.Enum({
      BEVEL: 0,
      ROUND: 1,
      MITER: 2
    });
    module.exports = {
      LineCap: LineCap,
      LineJoin: LineJoin
    };
  }), {} ],
  124: [ (function(require, module, exports) {
    require("./platform");
    require("./assets");
    true;
    require("./CCNode");
    require("./CCScene");
    require("./components");
    require("./graphics");
    require("./collider");
    require("./collider/CCIntersection");
    require("./physics");
    require("./camera/CCCamera");
    require("./base-ui/CCWidgetManager");
  }), {
    "./CCNode": 40,
    "./CCScene": 41,
    "./assets": 54,
    "./base-ui/CCWidgetManager": 59,
    "./camera/CCCamera": 60,
    "./collider": 69,
    "./collider/CCIntersection": 67,
    "./components": 103,
    "./graphics": 122,
    "./physics": 158,
    "./platform": 193
  } ],
  125: [ (function(require, module, exports) {
    var eventRegx = /^(click)(\s)*=/;
    var imageAttrReg = /(\s)*src(\s)*=|(\s)*height(\s)*=|(\s)*width(\s)*=|(\s)*click(\s)*=/;
    cc.HtmlTextParser = function() {
      this._parsedObject = {};
      this._specialSymbolArray = [];
      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, "'" ]);
    };
    cc.HtmlTextParser.prototype = {
      constructor: cc.HtmlTextParser,
      parse: function(htmlString) {
        this._resultObjectArray = [];
        this._stack = [];
        var startIndex = 0;
        var length = htmlString.length;
        while (startIndex < length) {
          var tagBeginIndex = htmlString.indexOf("<", startIndex);
          if (tagBeginIndex < 0) {
            this._stack.pop();
            this._processResult(htmlString.substring(startIndex));
            startIndex = length;
          } else {
            this._processResult(htmlString.substring(startIndex, tagBeginIndex));
            var tagEndIndex = htmlString.indexOf(">", startIndex);
            -1 === tagEndIndex ? tagEndIndex = tagBeginIndex : "/" === htmlString.charAt(tagBeginIndex + 1) ? this._stack.pop() : this._addToStack(htmlString.substring(tagBeginIndex + 1, tagEndIndex));
            startIndex = tagEndIndex + 1;
          }
        }
        return this._resultObjectArray;
      },
      _attributeToObject: function(attribute) {
        attribute = attribute.trim();
        var obj = {};
        var header = attribute.match(/^(color|size)(\s)*=/);
        var tagName;
        var nextSpace;
        var eventObj;
        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":
            obj.color = nextSpace > -1 ? attribute.substring(0, nextSpace).trim() : attribute;
            break;

           case "s":
            obj.size = parseInt(attribute);
          }
          if (nextSpace > -1) {
            eventHanlderString = attribute.substring(nextSpace + 1).trim();
            eventObj = this._processEventHandler(eventHanlderString);
            obj.event = eventObj;
          }
          return obj;
        }
        header = attribute.match(/^(br(\s)*\/)/);
        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: {
                newline: true
              }
            });
            return obj;
          }
        }
        header = attribute.match(/^(img(\s)*src(\s)*=[^>]+\/)/);
        if (header && header[0].length > 0) {
          tagName = header[0].trim();
          if (tagName.startsWith("img") && "/" === tagName[tagName.length - 1]) {
            header = attribute.match(imageAttrReg);
            var tagValue;
            var remainingArgument;
            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.toLocaleLowerCase();
              attribute = remainingArgument.substring(nextSpace).trim();
              if ("src" === tagName) {
                obj.isImage = true;
                tagValue.endsWith("/") && (tagValue = tagValue.substring(0, tagValue.length - 1));
                if (0 === tagValue.indexOf("'")) {
                  isValidImageTag = true;
                  tagValue = tagValue.substring(1, tagValue.length - 1);
                } else if (0 === tagValue.indexOf('"')) {
                  isValidImageTag = true;
                  tagValue = tagValue.substring(1, tagValue.length - 1);
                }
                obj.src = tagValue;
              } else "height" === tagName ? obj.imageHeight = parseInt(tagValue) : "width" === tagName ? obj.imageWidth = parseInt(tagValue) : "click" === tagName && (obj.event = this._processEventHandler(tagName + "=" + tagValue));
              header = attribute.match(imageAttrReg);
            }
            isValidImageTag && obj.isImage && this._resultObjectArray.push({
              text: "",
              style: obj
            });
            return {};
          }
        }
        header = attribute.match(/^(outline(\s)*[^>]*)/);
        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)*=/;
            header = attribute.match(outlineAttrReg);
            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(" ");
              tagValue = nextSpace > -1 ? remainingArgument.substr(0, nextSpace) : remainingArgument;
              tagName = tagName.replace(/[^a-zA-Z]/g, "").trim();
              tagName = tagName.toLocaleLowerCase();
              attribute = remainingArgument.substring(nextSpace).trim();
              "click" === tagName ? obj.event = this._processEventHandler(tagName + "=" + tagValue) : "color" === tagName ? defaultOutlineObject.color = tagValue : "width" === tagName && (defaultOutlineObject.width = parseInt(tagValue));
              header = attribute.match(outlineAttrReg);
            }
          }
          obj.outline = defaultOutlineObject;
        }
        header = attribute.match(/^(on|u|b|i)(\s)*/);
        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;
          }
          if ("" === attribute) return obj;
          eventObj = this._processEventHandler(attribute);
          obj.event = eventObj;
        }
        return obj;
      },
      _processEventHandler: function(eventString) {
        var index = 0;
        var obj = {};
        var eventNames = eventString.match(eventRegx);
        var isValidTag = false;
        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 = eventString.match(/(\S)+/);
            eventValue = match ? match[0] : "";
            index = eventValue.length;
          }
          if (isValidTag) {
            eventName = eventName.substring(0, eventName.length - 1).trim();
            obj[eventName] = eventValue;
          }
          eventString = eventString.substring(index).trim();
          eventNames = eventString.match(eventRegx);
        }
        return obj;
      },
      _addToStack: function(attribute) {
        var obj = this._attributeToObject(attribute);
        if (0 === this._stack.length) this._stack.push(obj); else {
          if (obj.isNewLine || obj.isImage) return;
          var previousTagObj = this._stack[this._stack.length - 1];
          for (var key in previousTagObj) obj[key] || (obj[key] = previousTagObj[key]);
          this._stack.push(obj);
        }
      },
      _processResult: function(value) {
        if ("" === value) return;
        value = this._escapeSpecialSymbol(value);
        this._stack.length > 0 ? this._resultObjectArray.push({
          text: value,
          style: this._stack[this._stack.length - 1]
        }) : this._resultObjectArray.push({
          text: value
        });
      },
      _escapeSpecialSymbol: function(str) {
        for (var i = 0; i < this._specialSymbolArray.length; ++i) {
          var key = this._specialSymbolArray[i][0];
          var value = this._specialSymbolArray[i][1];
          str = str.replace(key, value);
        }
        return str;
      }
    };
    cc.htmlTextParser = new cc.HtmlTextParser();
  }), {} ],
  126: [ (function(require, module, exports) {
    require("./CCTextUtils");
    var EventTarget = require("../event/event-target");
    var JS = require("../platform/js");
    var FontLetterDefinition = function() {
      this._u = 0;
      this._v = 0;
      this._width = 0;
      this._height = 0;
      this._offsetX = 0;
      this._offsetY = 0;
      this._textureID = 0;
      this._validDefinition = false;
      this._xAdvance = 0;
    };
    cc.FontAtlas = function(fntConfig) {
      this._lineHeight = fntConfig.commonHeight;
      this._fontSize = fntConfig.fontSize;
      this._letterDefinitions = {};
      this._fntConfig = fntConfig;
    };
    cc.FontAtlas.prototype = {
      constructor: cc.FontAtlas,
      setFontSize: function(fontSize) {
        this._fontSize = fontSize;
      },
      getOriginalFontSize: function() {
        return this._fntConfig.fontSize;
      },
      addLetterDefinitions: function(letter, letterDefinition) {
        this._letterDefinitions[letter] = letterDefinition;
      },
      cloneLetterDefinition: function() {
        var copyLetterDefinitions = {};
        for (var key in this._letterDefinitions) {
          var value = new FontLetterDefinition();
          cc.js.mixin(value, this._letterDefinitions[key]);
          copyLetterDefinitions[key] = value;
        }
        return copyLetterDefinitions;
      },
      assignLetterDefinitions: function(letterDefinition) {
        for (var key in this._letterDefinitions) {
          var newValue = letterDefinition[key];
          var oldValue = this._letterDefinitions[key];
          cc.js.mixin(oldValue, newValue);
        }
      },
      scaleFontLetterDefinition: function(scaleFactor) {
        for (var fontDefinition in this._letterDefinitions) {
          var letterDefinitions = this._letterDefinitions[fontDefinition];
          letterDefinitions._width *= scaleFactor;
          letterDefinitions._height *= scaleFactor;
          letterDefinitions._offsetX *= scaleFactor;
          letterDefinitions._offsetY *= scaleFactor;
          letterDefinitions._xAdvance *= scaleFactor;
        }
      },
      getLetterDefinitionForChar: function(char) {
        var hasKey = this._letterDefinitions.hasOwnProperty(char.charCodeAt(0));
        var letterDefinition;
        letterDefinition = hasKey ? this._letterDefinitions[char.charCodeAt(0)] : null;
        return letterDefinition;
      }
    };
    var LetterInfo = function() {
      this._char = "";
      this._valid = true;
      this._positionX = 0;
      this._positionY = 0;
      this._lineIndex = 0;
    };
    _ccsg.Label = _ccsg.Node.extend({
      _hAlign: cc.TextAlignment.LEFT,
      _vAlign: cc.VerticalTextAlignment.TOP,
      _string: "",
      _fontSize: 40,
      _drawFontsize: 40,
      _overFlow: 0,
      _isWrapText: true,
      _spacingX: 0,
      _blendFunc: null,
      _labelType: 0,
      _fontHandle: "",
      _lineSpacing: 0,
      _maxLineWidth: 0,
      _labelDimensions: cc.size(0, 0),
      _labelWidth: 0,
      _labelHeight: 0,
      _lineHeight: 40,
      _outlined: false,
      _outlineColor: null,
      _outlineWidth: 1,
      _gradientEnabled: false,
      _gradientStartColor: cc.color(255, 255, 255, 255),
      _gradientEndColor: cc.color(255, 255, 255, 255),
      _gradientDirection: 0,
      _className: "Label",
      _margin: 0,
      _isBold: false,
      _isItalic: false,
      _isUnderline: false,
      _fontAsset: null,
      ctor: function(string, fontAsset) {
        EventTarget.call(this);
        var isAsset = fontAsset instanceof cc.Font;
        var fontHandle = isAsset ? fontAsset.rawUrl : "";
        this._fontHandle = fontHandle;
        "string" !== typeof string && (string = "" + string);
        this._string = string;
        _ccsg.Node.prototype.ctor.call(this);
        this.setAnchorPoint(.5, .5);
        _ccsg.Node.prototype.setContentSize.call(this, 128, 128);
        this._blendFunc = cc.BlendFunc._alphaNonPremultiplied();
        this._imageOffset = cc.p(0, 0);
        this._numberOfLines = 0;
        this._lettersInfo = [];
        this._linesWidth = [];
        this._linesOffsetX = [];
        this._horizontalKernings = [];
        this._reusedRect = cc.rect(0, 0, 0, 0);
        isAsset ? this.setFontAsset(fontAsset) : this.setFontFamily(fontHandle);
        this.setString(this._string);
      },
      _resetBMFont: function() {
        this._imageOffset.x = this._imageOffset.y = 0;
        this._cascadeColorEnabled = true;
        this._cascadeOpacityEnabled = true;
        this._fontAtlas = null;
        this._config = null;
        this._numberOfLines = 0;
        this._lettersInfo.length = 0;
        this._linesWidth.length = 0;
        this._linesOffsetX.length = 0;
        this._textDesiredHeight = 0;
        this._letterOffsetY = 0;
        this._tailoredTopY = 0;
        this._tailoredBottomY = 0;
        this._bmfontScale = 1;
        this._horizontalKernings.length = 0;
        this._lineBreakWithoutSpaces = false;
        this._reusedRect.x = this._reusedRect.y = this._reusedRect.width = this._reusedRect.height = 0;
        this._textureLoaded = false;
        if (this._spriteBatchNode) {
          this.removeChild(this._spriteBatchNode);
          this._spriteBatchNode = null;
        }
      },
      setHorizontalAlign: function(align) {
        if (this._hAlign === align) return;
        this._hAlign = align;
        this._notifyLabelSkinDirty();
      },
      getHorizontalAlign: function() {
        return this._hAlign;
      },
      setVerticalAlign: function(align) {
        if (this._vAlign === align) return;
        this._vAlign = align;
        this._notifyLabelSkinDirty();
      },
      getVerticalAlign: function() {
        return this._vAlign;
      },
      setString: function(string) {
        "string" !== typeof string && (string = "" + string);
        if (this._string === string) return;
        this._string = string;
        this._notifyLabelSkinDirty();
      },
      setMargin: function(value) {
        if (this._margin === value) return;
        this._margin = value;
        this._notifyLabelSkinDirty();
      },
      getString: function() {
        return this._string;
      },
      getStringLength: function() {
        return this._string.length;
      },
      enableWrapText: function(enabled) {
        if (this._isWrapText === enabled) return;
        if (this._overFlow === _ccsg.Label.Overflow.RESIZE_HEIGHT || this._overFlow === _ccsg.Label.Overflow.NONE) return;
        this._isWrapText = enabled;
        this._rescaleWithOriginalFontSize();
        this._notifyLabelSkinDirty();
      },
      enableItalics: function(enabled) {
        this._isItalic = enabled;
        enabled ? this.setSkewX(12) : this.setSkewX(0);
      },
      enableBold: function(enabled) {
        if (this._isBold === enabled) return;
        this._isBold = enabled;
        this._notifyLabelSkinDirty();
      },
      enableUnderline: function(enabled) {
        if (this._isUnderline === enabled) return;
        this._isUnderline = enabled;
        this._notifyLabelSkinDirty();
      },
      isWrapTextEnabled: function() {
        return this._isWrapText;
      },
      getFontName: function() {
        return this._fontHandle;
      },
      setFontSize: function(fntSize) {
        if (this._fontSize === fntSize) return;
        this._fontSize = fntSize;
        this._drawFontsize = fntSize;
        this._notifyLabelSkinDirty();
      },
      getFontSize: function() {
        return this._fontSize;
      },
      isOutlined: function() {
        return this._outlined;
      },
      setOutlined: function(value) {
        if (this._outlined === value) return;
        this._outlined = !!value;
        this._notifyLabelSkinDirty();
      },
      setFillColorGradientEnabled: function(value) {
        if (this._gradientEnabled === value) return;
        this._gradientEnabled = !!value;
        this._notifyLabelSkinDirty();
      },
      getFillColorGradientEnabled: function() {
        return this._gradientEnabled;
      },
      setGradientStartColor: function(value) {
        if (this._gradientStartColor === value) return;
        this._gradientStartColor = value;
        this._notifyLabelSkinDirty();
      },
      getGradientStartColor: function() {
        return this._gradientStartColor;
      },
      setGradientEndColor: function(value) {
        if (this._gradientEndColor === value) return;
        this._gradientEndColor = value;
        this._notifyLabelSkinDirty();
      },
      getGradientEndColor: function() {
        return this._gradientEndColor;
      },
      setFillColorGradientDirection: function(direction) {
        this._gradientDirection = direction;
        this._notifyLabelSkinDirty();
      },
      getFillColorGradientDirection: function() {
        return this._gradientDirection;
      },
      getOutlineColor: function() {
        return this._outlineColor;
      },
      setOutlineColor: function(value) {
        if (this._outlineColor === value) return;
        this._outlineColor = cc.color(value);
        this._notifyLabelSkinDirty();
      },
      setOutlineWidth: function(value) {
        if (this._outlineWidth === value) return;
        this._outlineWidth = value;
        this._notifyLabelSkinDirty();
      },
      getOutlineWidth: function() {
        return this._outlineWidth;
      },
      _updateWrapText: function(overflow) {
        overflow === _ccsg.Label.Overflow.RESIZE_HEIGHT && (this._isWrapText = true);
        overflow === _ccsg.Label.Overflow.NONE && (this._isWrapText = false);
      },
      _setOverflowBMFont: function() {
        if (this._labelType === _ccsg.Label.Type.BMFont) {
          this._overFlow === _ccsg.Label.Overflow.RESIZE_HEIGHT && this._setDimensions(this._labelDimensions.width, 0);
          this._overFlow === _ccsg.Label.Overflow.NONE && this._setDimensions(0, 0);
          this._rescaleWithOriginalFontSize();
        }
      },
      setOverflow: function(overflow) {
        if (this._overFlow === overflow) return;
        this._overFlow = overflow;
        this._updateWrapText(this._overFlow);
        this._setOverflowBMFont();
        this._notifyLabelSkinDirty();
      },
      getOverflow: function() {
        return this._overFlow;
      },
      setSpacingX: function(spacing) {
        if (this._spacingX === spacing) return;
        this._spacingX = spacing;
        this._notifyLabelSkinDirty();
      },
      setLineHeight: function(lineHeight) {
        if (this._lineHeight === lineHeight) return;
        this._lineHeight = lineHeight;
        this._notifyLabelSkinDirty();
      },
      setLineBreakWithoutSpace: function(lineBreakFlag) {
        if (this._lineBreakWithoutSpaces === lineBreakFlag) return;
        this._lineBreakWithoutSpaces = lineBreakFlag;
        this._notifyLabelSkinDirty();
      },
      getSpacingX: function() {
        return this._spacingX;
      },
      getLineHeight: function() {
        return this._lineHeight;
      },
      getBMFontLineHeight: function() {
        if (this._fontAtlas) return this._fontAtlas._lineHeight;
      },
      setFontFamily: function(fontFamily) {
        this._resetBMFont();
        this._fontHandle = fontFamily || "Arial";
        this._labelType = _ccsg.Label.Type.SystemFont;
        this._blendFunc = cc.BlendFunc._alphaPremultiplied();
        this._renderCmd._needDraw = true;
        this._notifyLabelSkinDirty();
        this.emit("load");
      },
      setFontAsset: function(fontAsset) {
        this._fontAsset = fontAsset;
        var isAsset = fontAsset instanceof cc.Font;
        if (!isAsset) {
          this.setFontFamily("");
          return;
        }
        var fontHandle = isAsset ? fontAsset.rawUrl : "";
        var extName = cc.path.extname(fontHandle);
        this._resetBMFont();
        if (".ttf" === extName) {
          this._labelType = _ccsg.Label.Type.TTF;
          this._blendFunc = cc.BlendFunc._alphaPremultiplied();
          this._renderCmd._needDraw = true;
          this._fontHandle = this._loadTTFFont(fontHandle);
        } else if (fontAsset.spriteFrame) {
          this._labelType = _ccsg.Label.Type.BMFont;
          this._blendFunc = cc.BlendFunc._alphaNonPremultiplied();
          this._renderCmd._needDraw = false;
          this._initBMFontWithString(this._string, fontAsset);
        }
        this._notifyLabelSkinDirty();
      },
      _loadTTFFont: function(fontHandle) {
        var self = this;
        var fontFamilyName = cc.CustomFontLoader._getFontFamily(fontHandle);
        var callback = function() {
          self._notifyLabelSkinDirty();
          self.emit("load");
        };
        cc.CustomFontLoader.loadTTF(fontHandle, callback);
        return fontFamilyName;
      },
      setContentSize: function(size, height) {
        if (this._overFlow === _ccsg.Label.Overflow.NONE) return;
        this._setDimensions(size, height);
      },
      setBlendFunc: function(src, dst) {
        var locBlendFunc = this._blendFunc;
        if (void 0 === dst) {
          locBlendFunc.src = src.src;
          locBlendFunc.dst = src.dst;
        } else {
          locBlendFunc.src = src;
          locBlendFunc.dst = dst;
        }
      },
      getBlendFunc: function() {
        return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
      },
      _setupBMFontOverflowMetrics: function(newWidth, newHeight) {
        this._overFlow === _ccsg.Label.Overflow.RESIZE_HEIGHT && (newHeight = 0);
        if (this._overFlow === _ccsg.Label.Overflow.NONE) {
          newWidth = 0;
          newHeight = 0;
        }
        this._labelWidth = newWidth;
        this._labelHeight = newHeight;
        this._labelDimensions.width = newWidth;
        this._labelDimensions.height = newHeight;
        this._maxLineWidth = newWidth;
      },
      _updateLabel: function() {
        if (this._labelType === _ccsg.Label.Type.BMFont) {
          var contentSize = this._contentSize;
          var newWidth = contentSize.width;
          var newHeight = contentSize.height;
          this._setupBMFontOverflowMetrics(newWidth, newHeight);
          this._updateContent();
          this.setColor(this.color);
        } else this._labelType !== _ccsg.Label.Type.TTF && this._labelType !== _ccsg.Label.Type.SystemFont || this._renderCmd._bakeLabel();
      },
      _notifyLabelSkinDirty: function() {
        false;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.textDirty | _ccsg.Node._dirtyFlags.contentDirty);
      },
      _createRenderCmd: function() {
        return cc._renderType === cc.game.RENDER_TYPE_WEBGL ? new _ccsg.Label.WebGLRenderCmd(this) : new _ccsg.Label.CanvasRenderCmd(this);
      },
      getContentSize: function() {
        var locFlag = this._renderCmd._dirtyFlag;
        if (locFlag & _ccsg.Node._dirtyFlags.textDirty) {
          this._updateLabel();
          this._renderCmd._dirtyFlag &= ~_ccsg.Node._dirtyFlags.textDirty;
        }
        return _ccsg.Node.prototype.getContentSize.call(this);
      },
      _getWidth: function() {
        var locFlag = this._renderCmd._dirtyFlag;
        if (locFlag & _ccsg.Node._dirtyFlags.textDirty) {
          this._updateLabel();
          this._renderCmd._dirtyFlag &= ~_ccsg.Node._dirtyFlags.textDirty;
        }
        return _ccsg.Node.prototype._getWidth.call(this);
      },
      _getHeight: function() {
        var locFlag = this._renderCmd._dirtyFlag;
        if (locFlag & _ccsg.Node._dirtyFlags.textDirty) {
          this._updateLabel();
          this._renderCmd._dirtyFlag &= ~_ccsg.Node._dirtyFlags.textDirty;
        }
        return _ccsg.Node.prototype._getHeight.call(this);
      },
      _alignText: function() {
        var ret = true;
        do {
          if (!this._spriteBatchNode) return true;
          this._textDesiredHeight = 0;
          this._linesWidth = [];
          this._lineBreakWithoutSpaces ? this._multilineTextWrapByChar() : this._multilineTextWrapByWord();
          this._computeAlignmentOffset();
          if (this._overFlow === _ccsg.Label.Overflow.SHRINK) {
            var fontSize = this.getFontSize();
            fontSize > 0 && this._isVerticalClamp() && this._shrinkLabelToContentSize(this._isVerticalClamp.bind(this));
          }
          if (!this._updateQuads()) {
            ret = false;
            this._overFlow === _ccsg.Label.Overflow.SHRINK && this._shrinkLabelToContentSize(this._isHorizontalClamp.bind(this));
            break;
          }
        } while (0);
        return ret;
      },
      _isHorizontalClamped: function(px, lineIndex) {
        var wordWidth = this._linesWidth[lineIndex];
        var letterOverClamp = px > this._contentSize.width || px < 0;
        return this._isWrapText ? wordWidth > this._contentSize.width && letterOverClamp : letterOverClamp;
      },
      _updateQuads: function() {
        var ret = true;
        this._spriteBatchNode.removeAllChildren();
        for (var ctr = 0; ctr < this._string.length; ++ctr) if (this._lettersInfo[ctr]._valid) {
          var letterDef = this._fontAtlas._letterDefinitions[this._lettersInfo[ctr]._char];
          this._reusedRect.height = letterDef._height;
          this._reusedRect.width = letterDef._width;
          this._reusedRect.x = letterDef._u;
          this._reusedRect.y = letterDef._v;
          var py = this._lettersInfo[ctr]._positionY + this._letterOffsetY;
          if (this._labelHeight > 0) {
            if (py > this._tailoredTopY) {
              var clipTop = py - this._tailoredTopY;
              this._reusedRect.y += clipTop;
              this._reusedRect.height -= clipTop;
              py -= clipTop;
            }
            py - letterDef._height * this._bmfontScale < this._tailoredBottomY && (this._reusedRect.height = py < this._tailoredBottomY ? 0 : py - this._tailoredBottomY);
          }
          var lineIndex = this._lettersInfo[ctr]._lineIndex;
          var px = this._lettersInfo[ctr]._positionX + letterDef._width / 2 * this._bmfontScale + this._linesOffsetX[lineIndex];
          if (this._labelWidth > 0 && this._isHorizontalClamped(px, lineIndex)) if (this._overFlow === _ccsg.Label.Overflow.CLAMP) this._reusedRect.width = 0; else if (this._overFlow === _ccsg.Label.Overflow.SHRINK) {
            if (this._contentSize.width > letterDef._width) {
              ret = false;
              break;
            }
            this._reusedRect.width = 0;
          }
          if (this._reusedRect.height > 0 && this._reusedRect.width > 0) {
            var fontChar = this.getChildByTag(ctr);
            var locTexture = this._spriteBatchNode._texture;
            var spriteFrame = this._spriteFrame;
            var isRotated = this._spriteFrame.isRotated();
            var originalSize = spriteFrame._originalSize;
            var rect = spriteFrame._rect;
            var offset = spriteFrame._offset;
            var trimmedLeft = offset.x + (originalSize.width - rect.width) / 2;
            var trimmedTop = offset.y - (originalSize.height - rect.height) / 2;
            if (isRotated) {
              var originalX = this._reusedRect.x;
              this._reusedRect.x = rect.x + rect.height - this._reusedRect.y - this._reusedRect.height - trimmedTop;
              this._reusedRect.y = originalX + rect.y - trimmedLeft;
              this._reusedRect.y < 0 && (this._reusedRect.height = this._reusedRect.height + trimmedTop);
            } else {
              this._reusedRect.x += rect.x - trimmedLeft;
              this._reusedRect.y += rect.y + trimmedTop;
            }
            if (fontChar) fontChar.setTextureRect(this._reusedRect, isRotated); else {
              fontChar = new _ccsg.Sprite();
              fontChar.initWithTexture(locTexture, this._reusedRect, isRotated);
              fontChar.setAnchorPoint(cc.p(0, 1));
            }
            var letterPositionX = this._lettersInfo[ctr]._positionX + this._linesOffsetX[this._lettersInfo[ctr]._lineIndex];
            fontChar.setPosition(letterPositionX, py);
            this._updateLetterSpriteScale(fontChar);
            this._spriteBatchNode.addChild(fontChar);
          }
        }
        return ret;
      },
      _updateLetterSpriteScale: function(sprite) {
        this._labelType === _ccsg.Label.Type.BMFont && this._fontSize > 0 && sprite.setScale(this._bmfontScale);
      },
      _recordPlaceholderInfo: function(letterIndex, char) {
        if (letterIndex >= this._lettersInfo.length) {
          var tmpInfo = new LetterInfo();
          this._lettersInfo.push(tmpInfo);
        }
        this._lettersInfo[letterIndex]._char = char;
        this._lettersInfo[letterIndex]._valid = false;
      },
      _recordLetterInfo: function(letterPosition, character, letterIndex, lineIndex) {
        if (letterIndex >= this._lettersInfo.length) {
          var tmpInfo = new LetterInfo();
          this._lettersInfo.push(tmpInfo);
        }
        character = character.charCodeAt(0);
        this._lettersInfo[letterIndex]._lineIndex = lineIndex;
        this._lettersInfo[letterIndex]._char = character;
        this._lettersInfo[letterIndex]._valid = this._fontAtlas._letterDefinitions[character]._validDefinition;
        this._lettersInfo[letterIndex]._positionX = letterPosition.x;
        this._lettersInfo[letterIndex]._positionY = letterPosition.y;
      },
      _setDimensions: function(size, height) {
        var newWidth = "number" === typeof size.width ? size.width : size;
        var newHeight = "number" === typeof size.height ? size.height : height;
        var oldSize = this.getContentSize();
        _ccsg.Node.prototype.setContentSize.call(this, size, height);
        if (newHeight !== oldSize.height || newWidth !== oldSize.width) {
          this._setupBMFontOverflowMetrics(newWidth, newHeight);
          this._drawFontsize > 0 && this._restoreFontSize();
          this._notifyLabelSkinDirty();
        }
      },
      _restoreFontSize: function() {
        this._fontSize = this._drawFontsize;
      },
      _multilineTextWrap: function(nextTokenFunc) {
        var textLen = this.getStringLength();
        var lineIndex = 0;
        var nextTokenX = 0;
        var nextTokenY = 0;
        var longestLine = 0;
        var letterRight = 0;
        var lineSpacing = this._lineSpacing;
        var highestY = 0;
        var lowestY = 0;
        var letterDef = null;
        var letterPosition = cc.p(0, 0);
        this._updateBMFontScale();
        for (var index = 0; index < textLen; ) {
          var character = this._string.charAt(index);
          if ("\n" === character) {
            this._linesWidth.push(letterRight);
            letterRight = 0;
            lineIndex++;
            nextTokenX = 0;
            nextTokenY -= this._lineHeight * this._bmfontScale + lineSpacing;
            this._recordPlaceholderInfo(index, character);
            index++;
            continue;
          }
          var tokenLen = nextTokenFunc(this._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 = this._string.charAt(letterIndex);
            if ("\r" === character) {
              this._recordPlaceholderInfo(letterIndex, character);
              continue;
            }
            letterDef = this._fontAtlas.getLetterDefinitionForChar(character);
            if (!letterDef) {
              this._recordPlaceholderInfo(letterIndex, character);
              console.log("Can't find letter definition in texture atlas " + this._config.atlasName + " for letter:" + character);
              continue;
            }
            var letterX = nextLetterX + letterDef._offsetX * this._bmfontScale;
            if (this._isWrapText && this._maxLineWidth > 0 && nextTokenX > 0 && letterX + letterDef._width * this._bmfontScale > this._maxLineWidth && !cc.TextUtils.isUnicodeSpace(character)) {
              this._linesWidth.push(letterRight);
              letterRight = 0;
              lineIndex++;
              nextTokenX = 0;
              nextTokenY -= this._lineHeight * this._bmfontScale + lineSpacing;
              newLine = true;
              break;
            }
            letterPosition.x = letterX;
            letterPosition.y = nextTokenY - letterDef._offsetY * this._bmfontScale;
            this._recordLetterInfo(letterPosition, character, letterIndex, lineIndex);
            letterIndex + 1 < this._horizontalKernings.length && letterIndex < textLen - 1 && (nextLetterX += this._horizontalKernings[letterIndex + 1]);
            nextLetterX += letterDef._xAdvance * this._bmfontScale + this._spacingX;
            tokenRight = letterPosition.x + letterDef._width * this._bmfontScale;
            tokenHighestY < letterPosition.y && (tokenHighestY = letterPosition.y);
            tokenLowestY > letterPosition.y - letterDef._height * this._bmfontScale && (tokenLowestY = letterPosition.y - letterDef._height * this._bmfontScale);
          }
          if (newLine) continue;
          nextTokenX = nextLetterX;
          letterRight = tokenRight;
          highestY < tokenHighestY && (highestY = tokenHighestY);
          lowestY > tokenLowestY && (lowestY = tokenLowestY);
          longestLine < letterRight && (longestLine = letterRight);
          index += tokenLen;
        }
        this._linesWidth.push(letterRight);
        this._numberOfLines = lineIndex + 1;
        this._textDesiredHeight = this._numberOfLines * this._lineHeight * this._bmfontScale;
        this._numberOfLines > 1 && (this._textDesiredHeight += (this._numberOfLines - 1) * this._lineSpacing);
        var contentSize = cc.size(this._labelWidth, this._labelHeight);
        this._labelWidth <= 0 && (contentSize.width = parseFloat(longestLine.toFixed(2)));
        this._labelHeight <= 0 && (contentSize.height = parseFloat(this._textDesiredHeight.toFixed(2)));
        _ccsg.Node.prototype.setContentSize.call(this, contentSize);
        this._tailoredTopY = contentSize.height;
        this._tailoredBottomY = 0;
        highestY > 0 && (this._tailoredTopY = contentSize.height + highestY);
        lowestY < -this._textDesiredHeight && (this._tailoredBottomY = this._textDesiredHeight + lowestY);
        return true;
      },
      _multilineTextWrapByWord: function() {
        return this._multilineTextWrap(this._getFirstWordLen.bind(this));
      },
      _multilineTextWrapByChar: function() {
        return this._multilineTextWrap(this._getFirstCharLen.bind(this));
      },
      _isVerticalClamp: function() {
        return this._textDesiredHeight > this._contentSize.height;
      },
      _isHorizontalClamp: function() {
        var letterClamp = false;
        for (var ctr = 0; ctr < this.getStringLength(); ++ctr) if (this._lettersInfo[ctr]._valid) {
          var letterDef = this._fontAtlas._letterDefinitions[this._lettersInfo[ctr]._char];
          var px = this._lettersInfo[ctr]._positionX + letterDef._width / 2 * this._bmfontScale;
          var lineIndex = this._lettersInfo[ctr]._lineIndex;
          if (this._labelWidth > 0) if (this._isWrapText) {
            var wordWidth = this._linesWidth[lineIndex];
            if (wordWidth > this._contentSize.width && (px > this._contentSize.width || px < 0)) {
              letterClamp = true;
              break;
            }
          } else if (px > this._contentSize.width) {
            letterClamp = true;
            break;
          }
        }
        return letterClamp;
      },
      _shrinkLabelToContentSize: function(lambda) {
        var fontSize = this.getFontSize();
        var i = 0;
        var tempLetterDefinition = this._fontAtlas.cloneLetterDefinition();
        var originalLineHeight = this._lineHeight;
        var flag = true;
        while (lambda()) {
          ++i;
          var newFontSize = fontSize - i;
          flag = false;
          if (newFontSize <= 0) break;
          var scale = newFontSize / fontSize;
          this._fontAtlas.assignLetterDefinitions(tempLetterDefinition);
          this._fontAtlas.scaleFontLetterDefinition(scale);
          this._lineHeight = originalLineHeight * scale;
          this._lineBreakWithoutSpaces ? this._multilineTextWrapByChar() : this._multilineTextWrapByWord();
          this._computeAlignmentOffset();
        }
        this._lineHeight = originalLineHeight;
        this._fontAtlas.assignLetterDefinitions(tempLetterDefinition);
        flag || fontSize - i >= 0 && this._scaleFontSizeDown(fontSize - i);
      },
      _scaleFontSizeDown: function(fontSize) {
        var shouldUpdateContent = true;
        if (this._labelType === _ccsg.Label.Type.BMFont) {
          if (!fontSize) {
            fontSize = .1;
            shouldUpdateContent = false;
          }
          this._fontSize = fontSize;
          shouldUpdateContent && this._updateContent();
        }
      },
      _updateContent: function() {
        if (this._fontAtlas) {
          this._computeHorizontalKerningForText(this._string);
          this._alignText();
        }
      },
      _computeAlignmentOffset: function() {
        this._linesOffsetX = [];
        switch (this._hAlign) {
         case cc.TextAlignment.LEFT:
          for (var i = 0; i < this._numberOfLines; ++i) this._linesOffsetX.push(0);
          break;

         case cc.TextAlignment.CENTER:
          this._linesWidth.forEach(function(lineWidth) {
            this._linesOffsetX.push((this._contentSize.width - lineWidth) / 2);
          }.bind(this));
          break;

         case cc.TextAlignment.RIGHT:
          this._linesWidth.forEach(function(lineWidth) {
            this._linesOffsetX.push(this._contentSize.width - lineWidth);
          }.bind(this));
        }
        switch (this._vAlign) {
         case cc.VerticalTextAlignment.TOP:
          this._letterOffsetY = this._contentSize.height;
          break;

         case cc.VerticalTextAlignment.CENTER:
          this._letterOffsetY = (this._contentSize.height + this._textDesiredHeight) / 2;
          break;

         case cc.VerticalTextAlignment.BOTTOM:
          this._letterOffsetY = this._textDesiredHeight;
        }
      },
      _getFirstCharLen: function() {
        return 1;
      },
      _getFirstWordLen: function(text, startIndex, textLen) {
        var character = text.charAt(startIndex);
        if (cc.TextUtils.isUnicodeCJK(character) || "\n" === character || cc.TextUtils.isUnicodeSpace(character)) return 1;
        var len = 1;
        letterDef = this._fontAtlas.getLetterDefinitionForChar(character);
        if (!letterDef) return len;
        var nextLetterX = letterDef._xAdvance * this._bmfontScale + this._spacingX;
        var letterDef;
        var letterX;
        for (var index = startIndex + 1; index < textLen; ++index) {
          character = text.charAt(index);
          letterDef = this._fontAtlas.getLetterDefinitionForChar(character);
          if (!letterDef) break;
          letterX = nextLetterX + letterDef._offsetX * this._bmfontScale;
          if (letterX + letterDef._width * this._bmfontScale > this._maxLineWidth && !cc.TextUtils.isUnicodeSpace(character) && this._maxLineWidth > 0) return len;
          nextLetterX += letterDef._xAdvance * this._bmfontScale + this._spacingX;
          if ("\n" === character || cc.TextUtils.isUnicodeSpace(character) || cc.TextUtils.isUnicodeCJK(character)) break;
          len++;
        }
        return len;
      },
      _updateBMFontScale: function() {
        if (this._labelType === _ccsg.Label.Type.BMFont) {
          var originalFontSize = this._fontAtlas._fontSize;
          this._bmfontScale = this._fontSize / originalFontSize;
        } else this._bmfontScale = 1;
      },
      _initBMFontWithString: function(str, fontAsset) {
        var self = this;
        if (self._config) {
          cc.logID(4002);
          return false;
        }
        this._string = str;
        this._setBMFontFile(fontAsset);
      },
      _createSpriteBatchNode: function(texture) {
        this._spriteBatchNode = new cc.SpriteBatchNode(texture, this._string.length);
        this._spriteBatchNode.setCascadeColorEnabled(true);
        this._spriteBatchNode.setCascadeOpacityEnabled(true);
        this.addChild(this._spriteBatchNode);
        this._updateContent();
        this.setColor(this.color);
      },
      _createFontChars: function() {
        if (!this._config) return;
        this._fontAtlas = new cc.FontAtlas(this._config);
        this._lineHeight || (this._lineHeight = this._fontAtlas._lineHeight);
        var locCfg = this._config;
        var locFontDict = locCfg.fontDefDictionary;
        for (var fontDef in locFontDict) {
          var letterDefinition = new FontLetterDefinition();
          var tempRect = locFontDict[fontDef].rect;
          letterDefinition._offsetX = locFontDict[fontDef].xOffset;
          letterDefinition._offsetY = locFontDict[fontDef].yOffset;
          letterDefinition._width = tempRect.width;
          letterDefinition._height = tempRect.height;
          letterDefinition._u = tempRect.x + this._imageOffset.x;
          letterDefinition._v = tempRect.y + this._imageOffset.y;
          letterDefinition._textureID = 0;
          letterDefinition._validDefinition = true;
          letterDefinition._xAdvance = locFontDict[fontDef].xAdvance;
          this._fontAtlas.addLetterDefinitions(fontDef, letterDefinition);
        }
      },
      _rescaleWithOriginalFontSize: function() {
        var renderingFontSize = this.getFontSize();
        this._drawFontsize - renderingFontSize >= 1 && this._overFlow === _ccsg.Label.Overflow.SHRINK && (this._labelType === _ccsg.Label.Type.BMFont ? this._scaleFontSizeDown(this._drawFontsize) : this._fontSize = this._drawFontsize);
      },
      _computeHorizontalKerningForText: function() {
        var stringLen = this.getStringLength();
        var locKerningDict = this._config.kerningDict;
        var prev = -1;
        for (var i = 0; i < stringLen; ++i) {
          var key = this._string.charCodeAt(i);
          var kerningAmount = locKerningDict[prev << 16 | 65535 & key] || 0;
          this._horizontalKernings[i] = i < stringLen - 1 ? kerningAmount : 0;
          prev = key;
        }
      },
      _setBMFontFile: function(fontAsset) {
        if (fontAsset && this._labelType === _ccsg.Label.Type.BMFont) {
          var self = this;
          this._resetBMFont();
          var fntConfig = this._fontAsset._fntConfig;
          fntConfig ? self._config = fntConfig : cc.warn("Invalid BMFont Assets!");
          var spriteFrame = fontAsset.spriteFrame;
          self._createFontChars();
          self._spriteFrame = spriteFrame;
          var createLabelSprites = function() {
            var texture = spriteFrame.getTexture();
            self._textureLoaded = texture.loaded;
            self._createSpriteBatchNode(texture);
            self.emit("load");
          };
          if (spriteFrame.textureLoaded()) createLabelSprites(); else {
            spriteFrame.once("load", createLabelSprites);
            spriteFrame.ensureLoadTexture();
          }
        }
      }
    });
    _ccsg.Label.pool = new JS.Pool(function(label) {
      if (false, !(label instanceof _ccsg.Label)) return false;
      label._string = "";
      label._fontAsset = null;
      label._fontHandle = "";
      label._labelType = 0;
      label._resetBMFont();
      label._renderCmd._labelCanvas.width = 1;
      label._renderCmd._labelCanvas.height = 1;
      false;
      label._updateLabel();
      return true;
    }, 20);
    _ccsg.Label.pool.get = function(string, fontAsset) {
      var label = this._get();
      if (label) {
        var isAsset = fontAsset instanceof cc.Font;
        var fontHandle = isAsset ? fontAsset.rawUrl : "";
        label._fontHandle = fontHandle;
        "string" !== typeof string && (string = "" + string);
        label._string = string;
        label._position.x = 0;
        label._position.y = 0;
        label.setAnchorPoint(.5, .5);
        _ccsg.Node.prototype.setContentSize.call(label, 128, 128);
        isAsset ? label.setFontAsset(fontAsset) : label.setFontFamily("Arial");
        label.setString(string);
        label.setHorizontalAlign(cc.TextAlignment.LEFT);
        label.setVerticalAlign(cc.VerticalTextAlignment.TOP);
        label.setFontSize(40);
        label.setOverflow(0);
        label.enableWrapText(true);
        label.setVisible(true);
        label.setLineHeight(40);
        label.setOutlined(false);
        label.enableBold(false);
        label.enableItalics(false);
        label.enableUnderline(false);
        return label;
      }
      return new _ccsg.Label(string || "", fontAsset);
    };
    var _p = _ccsg.Label.prototype;
    cc.js.addon(_p, EventTarget.prototype);
    _ccsg.Label.Type = cc.Enum({
      TTF: 0,
      BMFont: 1,
      SystemFont: 2
    });
    _ccsg.Label.Overflow = cc.Enum({
      NONE: 0,
      CLAMP: 1,
      SHRINK: 2,
      RESIZE_HEIGHT: 3
    });
    var labelPro = _ccsg.Label.prototype;
    Object.defineProperty(labelPro, "width", {
      get: labelPro._getWidth,
      set: _ccsg.Node.prototype._setWidth
    });
    Object.defineProperty(labelPro, "height", {
      get: labelPro._getHeight,
      set: _ccsg.Node.prototype._setHeight
    });
  }), {
    "../event/event-target": 112,
    "../platform/js": 196,
    "./CCTextUtils": 129
  } ],
  127: [ (function(require, module, exports) {
    (function() {
      _ccsg.Label.TTFLabelBaker = function() {};
      var proto = _ccsg.Label.TTFLabelBaker.prototype = Object.create(Object.prototype);
      proto.updateStatus = function() {
        var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag;
        var colorDirty = locFlag & flags.colorDirty, opacityDirty = locFlag & flags.opacityDirty;
        colorDirty && this._updateDisplayColor();
        if (opacityDirty) {
          this._updateDisplayOpacity();
          this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty);
        }
        if (locFlag & flags.contentDirty) {
          this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty);
          this._dirtyFlag &= ~flags.contentDirty;
        }
        if (colorDirty || locFlag & flags.textDirty) {
          this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty);
          this._rebuildLabelSkin();
        }
        if (this._dirtyFlag & flags.transformDirty) {
          this.transform(this.getParentRenderCmd(), true);
          this._dirtyFlag &= ~flags.transformDirty;
        }
      };
      proto._syncStatus = function(parentCmd) {
        var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag;
        var parentNode = parentCmd ? parentCmd._node : null;
        parentNode && parentNode._cascadeColorEnabled && parentCmd._dirtyFlag & flags.colorDirty && (locFlag |= flags.colorDirty);
        parentNode && parentNode._cascadeOpacityEnabled && parentCmd._dirtyFlag & flags.opacityDirty && (locFlag |= flags.opacityDirty);
        parentCmd && parentCmd._dirtyFlag & flags.transformDirty && (locFlag |= flags.transformDirty);
        var colorDirty = locFlag & flags.colorDirty, opacityDirty = locFlag & flags.opacityDirty;
        this._dirtyFlag = locFlag;
        colorDirty && this._syncDisplayColor();
        opacityDirty && this._syncDisplayOpacity();
        (colorDirty || opacityDirty || this._dirtyFlag & flags.textDirty) && this._rebuildLabelSkin();
        this._dirtyFlag & flags.transformDirty && this.transform(parentCmd);
      };
      proto._getLineHeight = function() {
        var nodeSpacingY = this._node.getLineHeight();
        var node = this._node;
        nodeSpacingY = 0 === nodeSpacingY ? node._fontSize : nodeSpacingY * node._fontSize / this._drawFontsize;
        var lineHeight = 0 | nodeSpacingY;
        return lineHeight;
      };
      proto._constructFontDesc = function() {
        var node = this._node;
        var fontDesc = node._fontSize.toString() + "px ";
        var fontFamily = 0 === node._fontHandle.length ? "serif" : node._fontHandle;
        fontDesc += fontFamily;
        node._isBold && (fontDesc = "bold " + fontDesc);
        return fontDesc;
      };
      proto._measureText = function(ctx) {
        return function(string) {
          return ctx.measureText(string).width;
        };
      };
      proto._calculateLabelFont = function() {
        var node = this._node;
        var paragraphedStrings = node._string.split("\n");
        node._fontSize = node._drawFontsize;
        var fontDesc = this._constructFontDesc();
        this._labelContext.font = fontDesc;
        var paragraphLength = this._calculateParagraphLength(paragraphedStrings, this._labelContext);
        if (_ccsg.Label.Overflow.SHRINK === node._overFlow) {
          this._splitedStrings = paragraphedStrings;
          var i = 0;
          var totalHeight = 0;
          var maxLength = 0;
          if (node._isWrapText) {
            var canvasWidthNoMargin = this._canvasSize.width - 2 * this._getMargin();
            var canvasHeightNoMargin = this._canvasSize.height - 2 * this._getMargin();
            if (canvasWidthNoMargin < 0 || canvasHeightNoMargin < 0) {
              fontDesc = this._constructFontDesc();
              this._labelContext.font = fontDesc;
              return fontDesc;
            }
            totalHeight = canvasHeightNoMargin + 1;
            maxLength = canvasWidthNoMargin + 1;
            var actualFontSize = this._drawFontsize + 1;
            var textFragment = "";
            var tryDivideByTwo = true;
            var startShrinkFontSize = 0 | actualFontSize;
            while (totalHeight > canvasHeightNoMargin || maxLength > canvasWidthNoMargin) {
              if (tryDivideByTwo) actualFontSize = startShrinkFontSize / 2 | 0; else {
                actualFontSize = startShrinkFontSize - 1;
                startShrinkFontSize = actualFontSize;
              }
              if (actualFontSize <= 0) {
                cc.logID(4003);
                break;
              }
              node._fontSize = actualFontSize;
              fontDesc = this._constructFontDesc();
              this._labelContext.font = fontDesc;
              this._splitedStrings = [];
              totalHeight = 0;
              for (i = 0; i < paragraphedStrings.length; ++i) {
                var j = 0;
                var allWidth = this._labelContext.measureText(paragraphedStrings[i]).width;
                textFragment = cc.TextUtils.fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, this._measureText(this._labelContext));
                while (j < textFragment.length) {
                  var measureWidth = this._labelContext.measureText(textFragment[j]).width;
                  maxLength = measureWidth;
                  totalHeight += this._getLineHeight();
                  ++j;
                }
                this._splitedStrings = this._splitedStrings.concat(textFragment);
              }
              if (tryDivideByTwo) if (totalHeight > canvasHeightNoMargin) startShrinkFontSize = 0 | actualFontSize; else {
                tryDivideByTwo = false;
                totalHeight = canvasHeightNoMargin + 1;
              }
            }
          } else {
            totalHeight = paragraphedStrings.length * this._getLineHeight();
            for (i = 0; i < paragraphedStrings.length; ++i) maxLength < paragraphLength[i] && (maxLength = paragraphLength[i]);
            var scaleX = (this._canvasSize.width - 2 * this._getMargin()) / maxLength;
            var scaleY = this._canvasSize.height / totalHeight;
            node._fontSize = this._drawFontsize * Math.min(1, scaleX, scaleY) | 0;
            fontDesc = this._constructFontDesc();
            this._labelContext.font = fontDesc;
          }
        }
        return fontDesc;
      };
      proto._getMargin = function() {
        return this._node && this._node._margin || 0;
      };
      proto._calculateParagraphLength = function(paragraphedStrings, ctx) {
        var paragraphLength = [];
        for (var i = 0; i < paragraphedStrings.length; ++i) {
          var textMetric = ctx.measureText(paragraphedStrings[i]);
          paragraphLength.push(textMetric.width);
        }
        return paragraphLength;
      };
      proto._calculateCanvasSize = function() {
        var node = this._node;
        var canvasWidth = node._contentSize.width;
        var canvasHeight = node._contentSize.height;
        canvasWidth <= 0 && (canvasWidth = 1);
        canvasHeight <= 0 && (canvasHeight = 1);
        return cc.size(canvasWidth, canvasHeight);
      };
      proto._calculateSplitedStrings = function() {
        var node = this._node;
        var paragraphedStrings = node._string.split("\n");
        var i;
        if (node._isWrapText) {
          this._splitedStrings = [];
          var canvasWidthNoMargin = this._canvasSize.width - 2 * this._getMargin();
          for (i = 0; i < paragraphedStrings.length; ++i) {
            var allWidth = this._labelContext.measureText(paragraphedStrings[i]).width;
            var textFragment = cc.TextUtils.fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, this._measureText(this._labelContext));
            this._splitedStrings = this._splitedStrings.concat(textFragment);
          }
        } else this._splitedStrings = paragraphedStrings;
      };
      proto._updateLabelDimensions = function() {
        var node = this._node;
        var paragraphedStrings = node._string.split("\n");
        var i;
        var ctx = this._labelContext;
        if (_ccsg.Label.Overflow.RESIZE_HEIGHT === node._overFlow) {
          this._canvasSize.height = this._splitedStrings.length * this._getLineHeight();
          _ccsg.Node.prototype.setContentSize.call(node, this._canvasSize);
        } else if (_ccsg.Label.Overflow.NONE === node._overFlow) {
          this._splitedStrings = paragraphedStrings;
          var canvasSizeX = 0;
          var canvasSizeY = 0;
          for (i = 0; i < paragraphedStrings.length; ++i) {
            var paraLength = ctx.measureText(paragraphedStrings[i]).width;
            canvasSizeX = canvasSizeX > paraLength ? canvasSizeX : paraLength;
          }
          canvasSizeY = this._splitedStrings.length * this._getLineHeight();
          this._canvasSize.width = parseFloat(canvasSizeX.toFixed(2)) + 2 * this._getMargin();
          this._canvasSize.height = parseFloat(canvasSizeY.toFixed(2));
          node._isItalic && (this._canvasSize.width += node._drawFontsize * Math.tan(.20943951));
          _ccsg.Node.prototype.setContentSize.call(node, this._canvasSize);
        }
        this._labelCanvas.width = this._canvasSize.width;
        this._labelCanvas.height = this._canvasSize.height;
      };
      proto._calculateFillTextStartPosition = function() {
        var node = this._node;
        var lineHeight = this._getLineHeight();
        var lineCount = this._splitedStrings.length;
        var labelX;
        var firstLinelabelY;
        labelX = cc.TextAlignment.RIGHT === node._hAlign ? this._canvasSize.width - this._getMargin() : cc.TextAlignment.CENTER === node._hAlign ? this._canvasSize.width / 2 : 0 + this._getMargin();
        firstLinelabelY = cc.VerticalTextAlignment.TOP === node._vAlign ? 0 : cc.VerticalTextAlignment.CENTER === node._vAlign ? this._canvasSize.height / 2 - lineHeight * (lineCount - 1) / 2 : this._canvasSize.height - lineHeight * (lineCount - 1);
        return cc.p(labelX, firstLinelabelY);
      };
      proto._calculateTextBaseline = function() {
        var node = this._node;
        var hAlign;
        var vAlign;
        hAlign = cc.TextAlignment.RIGHT === node._hAlign ? "right" : cc.TextAlignment.CENTER === node._hAlign ? "center" : "left";
        this._labelContext.textAlign = hAlign;
        vAlign = cc.VerticalTextAlignment.TOP === node._vAlign ? "top" : cc.VerticalTextAlignment.CENTER === node._vAlign ? "middle" : "bottom";
        this._labelContext.textBaseline = vAlign;
      };
      proto._bakeLabel = function() {
        var node = this._node;
        this._drawFontsize = node._drawFontsize;
        this._canvasSize = this._calculateCanvasSize();
        this._fontDesc = this._calculateLabelFont();
        this._calculateSplitedStrings();
        this._updateLabelDimensions();
        this._calculateTextBaseline();
        this._updateTexture();
      };
      proto._calculateUnderlineStartPosition = function() {
        var node = this._node;
        var lineHeight = this._getLineHeight();
        var lineCount = this._splitedStrings.length;
        var labelX;
        var firstLinelabelY;
        labelX = 0 + this._getMargin();
        firstLinelabelY = cc.VerticalTextAlignment.TOP === node._vAlign ? node._fontSize : cc.VerticalTextAlignment.CENTER === node._vAlign ? this._canvasSize.height / 2 - lineHeight * (lineCount - 1) / 2 + node._fontSize / 2 : this._canvasSize.height - lineHeight * (lineCount - 1);
        return cc.p(labelX, firstLinelabelY);
      };
      proto._updateTexture = function() {
        this._labelContext.clearRect(0, 0, this._labelCanvas.width, this._labelCanvas.height);
        this._labelContext.font = this._fontDesc;
        var startPosition = this._calculateFillTextStartPosition();
        var lineHeight = this._getLineHeight();
        this._labelContext.lineJoin = "round";
        var color = this._displayedColor;
        this._labelContext.fillStyle = "rgb(" + color.r + "," + color.g + "," + color.b + ")";
        var underlineStartPosition;
        for (var i = 0; i < this._splitedStrings.length; ++i) {
          if (this._node.isOutlined()) {
            var strokeColor = this._node.getOutlineColor() || cc.color(255, 255, 255, 255);
            this._labelContext.globalCompositeOperation = "source-over";
            this._labelContext.strokeStyle = "rgb(" + strokeColor.r + "," + strokeColor.g + "," + strokeColor.b + ")";
            this._labelContext.lineWidth = 2 * this._node.getOutlineWidth();
            this._labelContext.strokeText(this._splitedStrings[i], startPosition.x, startPosition.y + i * lineHeight);
          }
          if (this._node.getFillColorGradientEnabled()) {
            var gradientStartColor = this._node.getGradientStartColor() || cc.color(255, 255, 255, 255);
            var gradientEndColor = this._node.getGradientEndColor() || cc.color(255, 255, 255, 255);
            var gradientArgument = this._getGradientArgs();
            var gradient = this._labelContext.createLinearGradient(gradientArgument.left, gradientArgument.top, gradientArgument.right, gradientArgument.bottom);
            gradient.addColorStop(0, cc.colorToHex(gradientStartColor));
            gradient.addColorStop(1, cc.colorToHex(gradientEndColor));
            this._labelContext.fillStyle = gradient;
          }
          this._labelContext.fillText(this._splitedStrings[i], startPosition.x, startPosition.y + i * lineHeight);
          if (this._node._isUnderline) {
            underlineStartPosition = this._calculateUnderlineStartPosition();
            this._labelContext.save();
            this._labelContext.beginPath();
            this._labelContext.lineWidth = this._node._fontSize / 8;
            this._labelContext.strokeStyle = "rgb(" + color.r + "," + color.g + "," + color.b + ")";
            this._labelContext.moveTo(underlineStartPosition.x, underlineStartPosition.y + i * lineHeight - 1);
            this._labelContext.lineTo(underlineStartPosition.x + this._labelCanvas.width, underlineStartPosition.y + i * lineHeight - 1);
            this._labelContext.stroke();
            this._labelContext.restore();
          }
        }
        this._texture.loaded = false;
        this._texture._image = this._labelCanvas;
        this._texture.handleLoadedTexture(true);
      };
      proto._getGradientArgs = function() {
        this._gradientArgument = {};
        this._gradientArgument.left = 0;
        this._gradientArgument.top = 0;
        var contentSize = this._node._contentSize;
        switch (this._node.getFillColorGradientDirection()) {
         case 0:
          this._gradientArgument.right = contentSize.width;
          this._gradientArgument.bottom = 0;
          break;

         case 1:
          this._gradientArgument.right = 0;
          this._gradientArgument.bottom = contentSize.height;
          break;

         case 2:
          this._gradientArgument.right = contentSize.width;
          this._gradientArgument.bottom = contentSize.height;
        }
        return this._gradientArgument;
      };
      proto._rebuildLabelSkin = function() {
        this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.textDirty;
        var node = this._node;
        node._updateLabel();
      };
    })();
    (function() {
      _ccsg.Label.CanvasRenderCmd = function(renderableObject) {
        this._rootCtor(renderableObject);
        this._needDraw = true;
        this._texture = new cc.Texture2D();
        this._labelCanvas = document.createElement("canvas");
        this._labelCanvas.width = 1;
        this._labelCanvas.height = 1;
        this._labelContext = this._labelCanvas.getContext("2d");
        this._texture.initWithElement(this._labelCanvas);
        this._splitedStrings = null;
      };
      var proto = _ccsg.Label.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
      cc.js.mixin(proto, _ccsg.Label.TTFLabelBaker.prototype);
      proto.constructor = _ccsg.Label.CanvasRenderCmd;
      proto._doCulling = function() {
        var rect = cc.visibleRect, bb = this._currentRegion, l = bb._minX, r = bb._maxX, b = bb._minY, t = bb._maxY, vl = rect.left.x, vr = rect.right.x, vt = rect.top.y, vb = rect.bottom.y;
        this._needDraw = !(r < vl || l > vr || t < vb || b > vt);
      };
      proto.rendering = function(ctx, scaleX, scaleY) {
        var node = this._node;
        if (node._labelType === _ccsg.Label.Type.TTF || node._labelType === _ccsg.Label.Type.SystemFont) {
          var locDisplayOpacity = this._displayedOpacity;
          var alpha = locDisplayOpacity / 255;
          if (0 === locDisplayOpacity) return;
          var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
          wrapper.setTransform(this._worldTransform, scaleX, scaleY);
          wrapper.setCompositeOperation(_ccsg.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc(node._blendFunc));
          wrapper.setGlobalAlpha(alpha);
          if (this._texture) {
            var sx, sy, sw, sh;
            var x, y, w, h;
            x = 0;
            y = -this._node._contentSize.height;
            w = this._node._contentSize.width;
            h = this._node._contentSize.height;
            var textureWidth = this._texture.getPixelWidth();
            var textureHeight = this._texture.getPixelHeight();
            sx = 0;
            sy = 0;
            sw = textureWidth;
            sh = textureHeight;
            var image = this._texture._image;
            if ("" !== this._texture._pattern) {
              wrapper.setFillStyle(context.createPattern(image, this._texture._pattern));
              context.fillRect(x, y, w, h);
            } else 0 !== sw && 0 !== sh && 0 !== w && 0 !== h && context.drawImage(image, sx, sy, sw, sh, x, y, w, h);
          }
          cc.g_NumberOfDraws = cc.g_NumberOfDraws + 1;
        }
      };
    })();
  }), {} ],
  128: [ (function(require, module, exports) {
    _ccsg.Label.WebGLRenderCmd = function(renderableObject) {
      this._rootCtor(renderableObject);
      this._needDraw = true;
      this._texture = new cc.Texture2D();
      this._labelCanvas = document.createElement("canvas");
      this._texture.initWithElement(this._labelCanvas);
      this._labelContext = this._labelCanvas.getContext("2d");
      this._labelCanvas.width = 1;
      this._labelCanvas.height = 1;
      this._splitedStrings = null;
      this._drawFontsize = 0;
      this._vertices = [ {
        x: 0,
        y: 0,
        u: 0,
        v: 0
      }, {
        x: 0,
        y: 0,
        u: 0,
        v: 1
      }, {
        x: 0,
        y: 0,
        u: 1,
        v: 0
      }, {
        x: 0,
        y: 0,
        u: 1,
        v: 1
      } ];
      this._color = new Uint32Array(1);
      this._dirty = false;
      this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLOR);
    };
    var proto = _ccsg.Label.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype);
    cc.js.mixin(proto, _ccsg.Label.TTFLabelBaker.prototype);
    proto.constructor = _ccsg.Label.WebGLRenderCmd;
    proto.updateTransform = function(parentCmd) {
      this.originUpdateTransform(parentCmd);
      var node = this._node, lx = 0, rx = this._labelCanvas.width, by = 0, ty = this._labelCanvas.height, wt = this._worldTransform;
      var vert = this._vertices;
      vert[0].x = lx * wt.a + ty * wt.c + wt.tx;
      vert[0].y = lx * wt.b + ty * wt.d + wt.ty;
      vert[1].x = lx * wt.a + by * wt.c + wt.tx;
      vert[1].y = lx * wt.b + by * wt.d + wt.ty;
      vert[2].x = rx * wt.a + ty * wt.c + wt.tx;
      vert[2].y = rx * wt.b + ty * wt.d + wt.ty;
      vert[3].x = rx * wt.a + by * wt.c + wt.tx;
      vert[3].y = rx * wt.b + by * wt.d + wt.ty;
    };
    proto._doCulling = function() {
      var node = this._node;
      if (!node._string || node._labelType !== _ccsg.Label.Type.TTF && node._labelType !== _ccsg.Label.Type.SystemFont) return;
      var rect = cc.visibleRect;
      this._cameraFlag > 0 && (rect = cc.Camera.main.visibleRect);
      var vl = rect.left.x;
      var vr = rect.right.x;
      var vt = rect.top.y;
      var vb = rect.bottom.y;
      var vert = this._vertices;
      (vert[0].x - vl & vert[1].x - vl & vert[2].x - vl & vert[3].x - vl) >> 31 || (vr - vert[0].x & vr - vert[1].x & vr - vert[2].x & vr - vert[3].x) >> 31 || (vert[0].y - vb & vert[1].y - vb & vert[2].y - vb & vert[3].y - vb) >> 31 || (vt - vert[0].y & vt - vert[1].y & vt - vert[2].y & vt - vert[3].y) >> 31 ? this._needDraw = false : this._needDraw = true;
    };
    proto.uploadData = function(f32buffer, ui32buffer, vertexDataOffset) {
      var node = this._node;
      if (!node._string || node._labelType !== _ccsg.Label.Type.TTF && node._labelType !== _ccsg.Label.Type.SystemFont) return 0;
      var opacity = this._displayedOpacity;
      this._color[0] = opacity << 24 | opacity << 16 | opacity << 8 | opacity;
      var z = node._vertexZ;
      var vertices = this._vertices;
      var i, len = vertices.length, vertex, offset = vertexDataOffset;
      for (i = 0; i < len; ++i) {
        vertex = vertices[i];
        f32buffer[offset] = vertex.x;
        f32buffer[offset + 1] = vertex.y;
        f32buffer[offset + 2] = z;
        ui32buffer[offset + 3] = this._color[0];
        f32buffer[offset + 4] = vertex.u;
        f32buffer[offset + 5] = vertex.v;
        offset += 6;
      }
      return len;
    };
  }), {} ],
  129: [ (function(require, module, exports) {
    var CustomFontDescriptor = function() {
      this._status = "unloaded";
      this._observers = [];
      this._isLoadWithCSS = false;
    };
    CustomFontDescriptor.prototype.onLoaded = function() {
      this._status = "loaded";
      this._observers.forEach((function(item) {
        item();
      }));
    };
    CustomFontDescriptor.prototype.isLoaded = function() {
      return "loaded" === this._status;
    };
    CustomFontDescriptor.prototype.addHandler = function(callback) {
      -1 === this._observers.indexOf(callback) && this._observers.push(callback);
    };
    var CustomFontLoader = {
      _fontCache: {},
      _fontWidthCache: {},
      _canvasContext: null,
      _testString: "BESbswy",
      _allFontsLoaded: false,
      _intervalId: 0,
      loadTTF: function(url, callback) {
        var fontFamilyName = this._getFontFamily(url);
        var md5Pipe = cc.loader.md5Pipe;
        md5Pipe && (url = md5Pipe.transformURL(url));
        var useFontFace = cc.sys.browserType !== cc.sys.BROWSER_TYPE_BAIDU && cc.sys.browserType !== cc.sys.BROWSER_TYPE_BAIDU_APP && cc.sys.browserType !== cc.sys.BROWSER_TYPE_MOBILE_QQ;
        window.FontFace && useFontFace ? this._loadWithFontFace(fontFamilyName, url, callback) : this._loadWithCSS(fontFamilyName, url, callback);
        0 === this._intervalId && (this._intervalId = setInterval(this._checkFontLoaded.bind(this), 100));
      },
      _checkFontLoaded: function() {
        this._allFontsLoaded = true;
        for (var k in this._fontCache) {
          var fontDescriptor = this._fontCache[k];
          if (fontDescriptor.isLoaded() || !fontDescriptor._isLoadWithCSS) continue;
          var oldWidth = this._fontWidthCache[k];
          this._canvasContext.font = "40px " + k;
          var newWidth = this._canvasContext.measureText(this._testString).width;
          oldWidth !== newWidth ? fontDescriptor.onLoaded() : this._allFontsLoaded = false;
        }
        if (this._allFontsLoaded) {
          clearInterval(this._intervalId);
          this._intervalId = 0;
        }
      },
      _loadWithFontFace: function(fontFamilyName, url, callback) {
        var fontDescriptor = this._fontCache[fontFamilyName];
        if (fontDescriptor) fontDescriptor.isLoaded() || fontDescriptor.addHandler(callback); else {
          var fontFace = new FontFace(fontFamilyName, "url('" + url + "')");
          document.fonts.add(fontFace);
          fontDescriptor = new CustomFontDescriptor();
          fontDescriptor.addHandler(callback);
          this._fontCache[fontFamilyName] = fontDescriptor;
          fontFace.loaded.then((function() {
            fontDescriptor.onLoaded();
          }));
        }
      },
      _loadWithCSS: function(fontFamilyName, url, callback) {
        var fontDescriptor = this._fontCache[fontFamilyName];
        if (fontDescriptor) fontDescriptor.isLoaded() || fontDescriptor.addHandler(callback); else {
          var doc = document;
          var fontStyle = document.createElement("style");
          fontStyle.type = "text/css";
          doc.body.appendChild(fontStyle);
          var fontStr = "";
          isNaN(fontFamilyName - 0) ? fontStr += "@font-face { font-family:" + fontFamilyName + "; src:" : fontStr += "@font-face { font-family:'" + fontFamilyName + "'; src:";
          fontStr += "url('" + url + "');";
          fontStyle.textContent = fontStr + "}";
          var preloadDiv = document.createElement("div");
          var _divStyle = preloadDiv.style;
          _divStyle.fontFamily = fontFamilyName;
          preloadDiv.innerHTML = ".";
          _divStyle.position = "absolute";
          _divStyle.left = "-100px";
          _divStyle.top = "-100px";
          doc.body.appendChild(preloadDiv);
          fontDescriptor = new CustomFontDescriptor();
          fontDescriptor.addHandler(callback);
          this._fontCache[fontFamilyName] = fontDescriptor;
          fontDescriptor._isLoadWithCSS = true;
          if (!this._canvasContext) {
            var labelCanvas = document.createElement("canvas");
            labelCanvas.width = 100;
            labelCanvas.height = 100;
            this._canvasContext = labelCanvas.getContext("2d");
          }
          var fontDesc = "40px " + fontFamilyName;
          this._canvasContext.font = fontDesc;
          var width = this._canvasContext.measureText(this._testString).width;
          this._fontWidthCache[fontFamilyName] = width;
          var self = this;
          fontStyle.onload = function() {
            setTimeout((function() {
              if (!self._allFontsLoaded) {
                cc.logID(4004);
                fontDescriptor.onLoaded();
                cc.director.getScheduler().unschedule(this._checkFontLoaded, this);
              }
            }), 2e4);
          };
        }
      },
      _getFontFamily: function(fontHandle) {
        var ttfIndex = fontHandle.lastIndexOf(".ttf");
        if (-1 === ttfIndex) return fontHandle;
        var slashPos = fontHandle.lastIndexOf("/");
        var fontFamilyName;
        fontFamilyName = -1 === slashPos ? fontHandle.substring(0, ttfIndex) + "_LABEL" : fontHandle.substring(slashPos + 1, ttfIndex) + "_LABEL";
        return fontFamilyName;
      }
    };
    var TextUtils = {
      label_wordRex: /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûа-яА-ЯЁё]+|\S)/,
      label_symbolRex: /^[!,.:;'}\]%\?>、‘“》？。，！]/,
      label_lastWordRex: /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]+|\S)$/,
      label_lastEnglish: /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]+$/,
      label_firstEnglish: /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]/,
      label_wrapinspection: true,
      isUnicodeCJK: function(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);
      },
      isUnicodeSpace: function(ch) {
        ch = ch.charCodeAt(0);
        return ch >= 9 && ch <= 13 || 32 === ch || 133 === ch || 160 === ch || 5760 === ch || ch >= 8192 && ch <= 8202 || 8232 === ch || 8233 === ch || 8239 === ch || 8287 === ch || 12288 === ch;
      },
      fragmentText: function(stringToken, allWidth, maxWidth, measureText) {
        var wrappedWords = [];
        if (0 === stringToken.length || maxWidth < 0) {
          wrappedWords.push("");
          return wrappedWords;
        }
        var text = stringToken;
        while (allWidth > maxWidth && text.length > 1) {
          var fuzzyLen = text.length * (maxWidth / allWidth) | 0;
          var tmpText = text.substr(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 = text.substr(fuzzyLen);
            width = allWidth - measureText(tmpText);
          }
          checkWhile = 0;
          while (width < maxWidth && checkWhile++ < checkCount) {
            if (tmpText) {
              var exec = this.label_wordRex.exec(tmpText);
              pushNum = exec ? exec[0].length : 1;
              sLine = tmpText;
            }
            fuzzyLen += pushNum;
            tmpText = text.substr(fuzzyLen);
            width = allWidth - measureText(tmpText);
          }
          fuzzyLen -= pushNum;
          if (0 === fuzzyLen) {
            fuzzyLen = 1;
            sLine = sLine.substr(1);
          }
          var sText = text.substr(0, fuzzyLen), result;
          if (this.label_wrapinspection && this.label_symbolRex.test(sLine || tmpText)) {
            result = this.label_lastWordRex.exec(sText);
            fuzzyLen -= result ? result[0].length : 0;
            0 === fuzzyLen && (fuzzyLen = 1);
            sLine = text.substr(fuzzyLen);
            sText = text.substr(0, fuzzyLen);
          }
          if (this.label_firstEnglish.test(sLine)) {
            result = this.label_lastEnglish.exec(sText);
            if (result && sText !== result[0]) {
              fuzzyLen -= result[0].length;
              sLine = text.substr(fuzzyLen);
              sText = text.substr(0, fuzzyLen);
            }
          }
          if (0 === wrappedWords.length && "" === sLine && "" === tmpText) wrappedWords.push(sText); else {
            sText = sText.trim();
            sText.length > 0 && wrappedWords.push(sText);
          }
          text = sLine || tmpText;
          allWidth = measureText(text);
        }
        if (0 === wrappedWords.length) wrappedWords.push(text); else {
          text = text.trim();
          text.length > 0 && wrappedWords.push(text);
        }
        return wrappedWords;
      }
    };
    cc.TextUtils = module.exports = TextUtils;
    cc.CustomFontLoader = module.exports = CustomFontLoader;
  }), {} ],
  130: [ (function(require, module, exports) {
    var JS = require("../platform/js");
    var Pipeline = require("./pipeline");
    var LoadingItems = require("./loading-items");
    var AssetLoader = require("./asset-loader");
    var Downloader = require("./downloader");
    var Loader = require("./loader");
    var AssetTable = require("./asset-table");
    var callInNextTick = require("../platform/utils").callInNextTick;
    var AutoReleaseUtils = require("./auto-release-utils");
    var ReleasedAssetChecker = (true, require("./released-asset-checker"));
    var resources = new AssetTable();
    function getXMLHttpRequest() {
      return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP");
    }
    var _info = {
      url: null,
      raw: false
    };
    function getResWithUrl(res) {
      var id, result, isUuid;
      if ("object" === typeof res) {
        result = res;
        if (res.url) return result;
        id = res.uuid;
      } else {
        result = {};
        id = res;
      }
      isUuid = result.type ? "uuid" === result.type : cc.AssetLibrary._getAssetUrl(id);
      cc.AssetLibrary._getAssetInfoInRuntime(id, _info);
      result.url = isUuid ? _info.url : id;
      if (_info.url && "uuid" === result.type && _info.raw) {
        result.type = null;
        result.isRawAsset = true;
      } else isUuid || (result.isRawAsset = true);
      return result;
    }
    var _sharedResources = [];
    var _sharedList = [];
    function CCLoader() {
      var assetLoader = new AssetLoader();
      var downloader = new Downloader();
      var loader = new Loader();
      Pipeline.call(this, [ assetLoader, downloader, loader ]);
      this.assetLoader = assetLoader;
      this.downloader = downloader;
      this.loader = loader;
      this.onProgress = null;
      this._autoReleaseSetting = {};
      true;
      this._releasedAssetChecker_DEBUG = new ReleasedAssetChecker();
    }
    JS.extend(CCLoader, Pipeline);
    var proto = CCLoader.prototype;
    proto.init = function(director) {
      true;
      var self = this;
      director.on(cc.Director.EVENT_BEFORE_VISIT, (function() {
        self._releasedAssetChecker_DEBUG.checkCouldRelease(self._cache);
      }));
    };
    proto.getXMLHttpRequest = getXMLHttpRequest;
    proto.addDownloadHandlers = function(extMap) {
      this.downloader.addHandlers(extMap);
    };
    proto.addLoadHandlers = function(extMap) {
      this.loader.addHandlers(extMap);
    };
    proto.load = function(resources, progressCallback, completeCallback) {
      if (void 0 === completeCallback) {
        completeCallback = progressCallback;
        progressCallback = this.onProgress || null;
      }
      var self = this;
      var singleRes = false;
      if (!(resources instanceof Array)) {
        singleRes = true;
        resources = resources ? [ resources ] : [];
      }
      _sharedResources.length = 0;
      for (var i = 0; i < resources.length; ++i) {
        var resource = resources[i];
        if (resource && resource.id) {
          cc.warnID(4920, resource.id);
          resource.uuid || resource.url || (resource.url = resource.id);
        }
        var res = getResWithUrl(resource);
        if (!res.url && !res.uuid) continue;
        var item = this._cache[res.url];
        _sharedResources.push(item || res);
      }
      var queue = LoadingItems.create(this, progressCallback, (function(errors, items) {
        callInNextTick((function() {
          if (completeCallback) {
            if (singleRes) {
              var id = res.url;
              completeCallback.call(self, items.getError(id), items.getContent(id));
            } else completeCallback.call(self, errors, items);
            completeCallback = null;
          }
          var _id;
          false;
          items.destroy();
        }));
      }));
      LoadingItems.initQueueDeps(queue);
      queue.append(_sharedResources);
      _sharedResources.length = 0;
    };
    proto.flowInDeps = function(owner, urlList, callback) {
      _sharedList.length = 0;
      for (var i = 0; i < urlList.length; ++i) {
        var res = getResWithUrl(urlList[i]);
        if (!res.url && !res.uuid) continue;
        var item = this._cache[res.url];
        item ? _sharedList.push(item) : _sharedList.push(res);
      }
      var queue = LoadingItems.create(this, owner ? function(completedCount, totalCount, item) {
        this._ownerQueue && this._ownerQueue.onProgress && this._ownerQueue._childOnProgress(item);
      } : null, (function(errors, items) {
        callback(errors, items);
        owner && owner.deps && (owner.deps.length = 0);
        items.destroy();
      }));
      if (owner) {
        var ownerQueue = LoadingItems.getQueue(owner);
        queue._ownerQueue = ownerQueue._ownerQueue || ownerQueue;
      }
      var accepted = queue.append(_sharedList, owner);
      _sharedList.length = 0;
      return accepted;
    };
    proto._resources = resources;
    proto._getResUuid = function(url, type, quiet) {
      if (!url) return null;
      var index = url.indexOf("?");
      -1 !== index && (url = url.substr(0, index));
      var uuid = resources.getUuid(url, type);
      if (!uuid) {
        var extname = cc.path.extname(url);
        if (extname) {
          url = url.slice(0, -extname.length);
          uuid = resources.getUuid(url, type);
          uuid && !quiet && cc.warnID(4901, url, extname);
        }
      }
      return uuid;
    };
    proto._getReferenceKey = function(assetOrUrlOrUuid) {
      var key;
      "object" === typeof assetOrUrlOrUuid ? key = assetOrUrlOrUuid._uuid || null : "string" === typeof assetOrUrlOrUuid && (key = this._getResUuid(assetOrUrlOrUuid, null, true) || assetOrUrlOrUuid);
      if (!key) {
        cc.warnID(4800, assetOrUrlOrUuid);
        return key;
      }
      cc.AssetLibrary._getAssetInfoInRuntime(key, _info);
      return this._cache[_info.url] ? _info.url : key;
    };
    proto._urlNotFound = function(url, type, completeCallback) {
      callInNextTick((function() {
        url = cc.url.normalize(url);
        var info = (type ? JS.getClassName(type) : "Asset") + ' in "resources/' + url + '" does not exist.';
        completeCallback && completeCallback(new Error(info), []);
      }));
    };
    proto._parseLoadResArgs = function(type, onProgress, onComplete) {
      if (void 0 === onComplete) {
        var isValidType = cc.isChildClassOf(type, cc.RawAsset);
        if (onProgress) {
          onComplete = onProgress;
          isValidType && (onProgress = this.onProgress || null);
        } else if (void 0 === onProgress && !isValidType) {
          onComplete = type;
          onProgress = this.onProgress || null;
          type = null;
        }
        if (void 0 !== onProgress && !isValidType) {
          onProgress = type;
          type = null;
        }
      }
      return {
        type: type,
        onProgress: onProgress,
        onComplete: onComplete
      };
    };
    proto.loadRes = function(url, type, progressCallback, completeCallback) {
      var args = this._parseLoadResArgs(type, progressCallback, completeCallback);
      type = args.type;
      progressCallback = args.onProgress;
      completeCallback = args.onComplete;
      var self = this;
      var uuid = self._getResUuid(url, type);
      uuid ? this.load({
        type: "uuid",
        uuid: uuid
      }, progressCallback, (function(err, asset) {
        asset && self.setAutoReleaseRecursively(uuid, false);
        completeCallback && completeCallback(err, asset);
      })) : self._urlNotFound(url, type, completeCallback);
    };
    proto._loadResUuids = function(uuids, progressCallback, completeCallback, urls) {
      if (uuids.length > 0) {
        var self = this;
        var res = uuids.map((function(uuid) {
          return {
            type: "uuid",
            uuid: uuid
          };
        }));
        this.load(res, progressCallback, (function(errors, items) {
          if (completeCallback) {
            var assetRes = [];
            var urlRes = urls && [];
            for (var i = 0; i < res.length; ++i) {
              var uuid = res[i].uuid;
              var id = this._getReferenceKey(uuid);
              var item = items.getContent(id);
              if (item) {
                self.setAutoReleaseRecursively(uuid, false);
                assetRes.push(item);
                urlRes && urlRes.push(urls[i]);
              }
            }
            urls ? completeCallback(errors, assetRes, urlRes) : completeCallback(errors, assetRes);
          }
        }));
      } else completeCallback && callInNextTick((function() {
        urls ? completeCallback(null, [], []) : completeCallback(null, []);
      }));
    };
    proto.loadResArray = function(urls, type, progressCallback, completeCallback) {
      var args = this._parseLoadResArgs(type, progressCallback, completeCallback);
      type = args.type;
      progressCallback = args.onProgress;
      completeCallback = args.onComplete;
      var uuids = [];
      for (var i = 0; i < urls.length; i++) {
        var url = urls[i];
        var uuid = this._getResUuid(url, type);
        if (!uuid) {
          this._urlNotFound(url, type, completeCallback);
          return;
        }
        uuids.push(uuid);
      }
      this._loadResUuids(uuids, progressCallback, completeCallback);
    };
    proto.loadResDir = function(url, type, progressCallback, completeCallback) {
      var args = this._parseLoadResArgs(type, progressCallback, completeCallback);
      type = args.type;
      progressCallback = args.onProgress;
      completeCallback = args.onComplete;
      var urls = [];
      var uuids = resources.getUuidArray(url, type, urls);
      this._loadResUuids(uuids, progressCallback, completeCallback, urls);
    };
    proto.getRes = function(url, type) {
      var item = this._cache[url];
      if (!item) {
        var uuid = this._getResUuid(url, type, true);
        if (!uuid) return null;
        var ref = this._getReferenceKey(uuid);
        item = this._cache[ref];
      }
      item && item.alias && (item = item.alias);
      return item && item.complete ? item.content : null;
    };
    proto.getResCount = function() {
      return Object.keys(this._cache).length;
    };
    proto.getDependsRecursively = function(owner) {
      if (owner) {
        var key = this._getReferenceKey(owner);
        var assets = AutoReleaseUtils.getDependsRecursively(key);
        assets.push(key);
        return assets;
      }
      return [];
    };
    proto.release = function(asset) {
      if (Array.isArray(asset)) for (var i = 0; i < asset.length; i++) {
        var key = asset[i];
        this.release(key);
      } else if (asset) {
        var id = this._getReferenceKey(asset);
        var item = this.getItem(id);
        if (item) {
          var removed = this.removeItem(id);
          asset = item.content;
          if (asset instanceof cc.Asset) {
            false;
            var urls = asset.rawUrls;
            for (var _i = 0; _i < urls.length; _i++) this.release(urls[_i]);
          } else asset instanceof cc.Texture2D && cc.textureCache.removeTextureForKey(item.rawUrl || item.url);
          (true, removed) && this._releasedAssetChecker_DEBUG.setReleased(item, id);
        }
      }
    };
    proto.releaseAsset = function(asset) {
      var uuid = asset._uuid;
      uuid && this.release(uuid);
    };
    proto.releaseRes = function(url, type) {
      var uuid = this._getResUuid(url, type);
      uuid ? this.release(uuid) : cc.errorID(4914, url);
    };
    proto.releaseResDir = function(url, type) {
      var uuids = resources.getUuidArray(url, type);
      for (var i = 0; i < uuids.length; i++) {
        var uuid = uuids[i];
        this.release(uuid);
      }
    };
    proto.releaseAll = function() {
      for (var id in this._cache) this.release(id);
    };
    proto.removeItem = function(key) {
      var removed = Pipeline.prototype.removeItem.call(this, key);
      delete this._autoReleaseSetting[key];
      return removed;
    };
    proto.setAutoRelease = function(assetOrUrlOrUuid, autoRelease) {
      var key = this._getReferenceKey(assetOrUrlOrUuid);
      !!key && (this._autoReleaseSetting[key] = !!autoRelease);
    };
    proto.setAutoReleaseRecursively = function(assetOrUrlOrUuid, autoRelease) {
      autoRelease = !!autoRelease;
      var key = this._getReferenceKey(assetOrUrlOrUuid);
      if (key) {
        this._autoReleaseSetting[key] = autoRelease;
        var depends = AutoReleaseUtils.getDependsRecursively(key);
        for (var i = 0; i < depends.length; i++) {
          var depend = depends[i];
          this._autoReleaseSetting[depend] = autoRelease;
        }
      } else false;
    };
    proto.isAutoRelease = function(assetOrUrl) {
      var key = this._getReferenceKey(assetOrUrl);
      if (key) return !!this._autoReleaseSetting[key];
      return false;
    };
    cc.loader = new CCLoader();
    false;
    module.exports = cc.loader;
  }), {
    "../platform/js": 196,
    "../platform/utils": 200,
    "./asset-loader": 131,
    "./asset-table": 132,
    "./auto-release-utils": 134,
    "./downloader": 135,
    "./loader": 138,
    "./loading-items": 139,
    "./pipeline": 142,
    "./released-asset-checker": 143
  } ],
  131: [ (function(require, module, exports) {
    var Path = require("../utils/CCPath");
    var Pipeline = require("./pipeline");
    var LoadingItems = require("./loading-items");
    var ID = "AssetLoader";
    var AssetLoader = function(extMap) {
      this.id = ID;
      this.async = true;
      this.pipeline = null;
    };
    AssetLoader.ID = ID;
    var reusedArray = [];
    AssetLoader.prototype.handle = function(item, callback) {
      var uuid = item.uuid;
      if (!uuid) return !item.content ? null : item.content;
      var self = this;
      cc.AssetLibrary.queryAssetInfo(uuid, (function(error, url, isRawAsset) {
        if (error) callback(error); else {
          item.url = item.rawUrl = url;
          item.isRawAsset = isRawAsset;
          if (isRawAsset) {
            var ext = Path.extname(url).toLowerCase();
            if (!ext) {
              callback(new Error("Download Uuid: can not find type of raw asset[" + uuid + "]: " + url));
              return;
            }
            ext = ext.substr(1);
            var queue = LoadingItems.getQueue(item);
            reusedArray[0] = {
              queueId: item.queueId,
              id: url,
              url: url,
              type: ext,
              error: null,
              alias: item,
              complete: true
            };
            false;
            queue.append(reusedArray);
            item.type = ext;
            callback(null, item.content);
          } else {
            item.type = "uuid";
            callback(null, item.content);
          }
        }
      }));
    };
    Pipeline.AssetLoader = module.exports = AssetLoader;
  }), {
    "../utils/CCPath": 218,
    "./loading-items": 139,
    "./pipeline": 142
  } ],
  132: [ (function(require, module, exports) {
    var pushToMap = require("../utils/misc").pushToMap;
    function Entry(uuid, type) {
      this.uuid = uuid;
      this.type = type;
    }
    function AssetTable() {
      this._pathToUuid = {};
    }
    function isMatchByWord(path, test) {
      if (path.length > test.length) {
        var nextAscii = path.charCodeAt(test.length);
        return 46 === nextAscii || 47 === nextAscii;
      }
      return true;
    }
    var proto = AssetTable.prototype;
    proto.getUuid = function(path, type) {
      path = cc.url.normalize(path);
      var item = this._pathToUuid[path];
      if (item) if (Array.isArray(item)) {
        if (!type) return item[0].uuid;
        for (var i = 0; i < item.length; i++) {
          var entry = item[i];
          if (cc.isChildClassOf(entry.type, type)) return entry.uuid;
        }
      } else if (!type || cc.isChildClassOf(item.type, type)) return item.uuid;
      return "";
    };
    proto.getUuidArray = function(path, type, out_urls) {
      path = cc.url.normalize(path);
      "/" === path[path.length - 1] && (path = path.slice(0, -1));
      var path2uuid = this._pathToUuid;
      var uuids = [];
      var isChildClassOf = cc.isChildClassOf;
      for (var p in path2uuid) if (p.startsWith(path) && isMatchByWord(p, path) || !path) {
        var item = path2uuid[p];
        if (Array.isArray(item)) for (var i = 0; i < item.length; i++) {
          var entry = item[i];
          if (!type || isChildClassOf(entry.type, type)) {
            uuids.push(entry.uuid);
            out_urls && out_urls.push(p);
          }
        } else if (!type || isChildClassOf(item.type, type)) {
          uuids.push(item.uuid);
          out_urls && out_urls.push(p);
        }
      }
      return uuids;
    };
    proto.add = function(path, uuid, type, isMainAsset) {
      path = path.substring(0, path.length - cc.path.extname(path).length);
      var newEntry = new Entry(uuid, type);
      pushToMap(this._pathToUuid, path, newEntry, isMainAsset);
    };
    proto._getInfo_DEBUG = (true, function(uuid, out_info) {
      var path2uuid = this._pathToUuid;
      var paths = Object.keys(path2uuid);
      for (var p = 0; p < paths.length; ++p) {
        var path = paths[p];
        var item = path2uuid[path];
        if (Array.isArray(item)) for (var i = 0; i < item.length; i++) {
          var entry = item[i];
          if (entry.uuid === uuid) {
            out_info.path = path;
            out_info.type = entry.type;
            return true;
          }
        } else if (item.uuid === uuid) {
          out_info.path = path;
          out_info.type = item.type;
          return true;
        }
      }
      return false;
    });
    proto.reset = function() {
      this._pathToUuid = {};
    };
    module.exports = AssetTable;
  }), {
    "../utils/misc": 225
  } ],
  133: [ (function(require, module, exports) {
    var Path = require("../utils/CCPath");
    var sys = require("../platform/CCSys");
    var Pipeline = require("./pipeline");
    var audioEngine = require("../../audio/CCAudioEngine");
    var __audioSupport = sys.__audioSupport;
    var formatSupport = __audioSupport.format;
    var context = __audioSupport.context;
    function loadDomAudio(item, callback) {
      var dom = document.createElement("audio");
      dom.src = item.url;
      if (sys.platform === sys.WECHAT_GAME) {
        item.element = dom;
        callback(null, item.url);
        return;
      }
      var clearEvent = function() {
        clearTimeout(timer);
        dom.removeEventListener("canplaythrough", success, false);
        dom.removeEventListener("error", failure, false);
        __audioSupport.USE_LOADER_EVENT && dom.removeEventListener(__audioSupport.USE_LOADER_EVENT, success, false);
      };
      var timer = setTimeout((function() {
        0 === dom.readyState ? failure() : success();
      }), 8e3);
      var success = function() {
        clearEvent();
        item.element = dom;
        callback(null, item.url);
      };
      var failure = function() {
        clearEvent();
        var message = "load audio failure - " + item.url;
        cc.log(message);
        callback(message, item.url);
      };
      dom.addEventListener("canplaythrough", success, false);
      dom.addEventListener("error", failure, false);
      __audioSupport.USE_LOADER_EVENT && dom.addEventListener(__audioSupport.USE_LOADER_EVENT, success, false);
    }
    function loadWebAudio(item, callback) {
      context || callback(new Error("Audio Downloader: no web audio context."));
      var request = cc.loader.getXMLHttpRequest();
      request.open("GET", item.url, true);
      request.responseType = "arraybuffer";
      request.onload = function() {
        context["decodeAudioData"](request.response, (function(buffer) {
          item.buffer = buffer;
          callback(null, item.url);
        }), (function() {
          callback("decode error - " + item.url, null);
        }));
      };
      request.onerror = function() {
        callback("request error - " + item.url, null);
      };
      request.send();
    }
    function downloadAudio(item, callback) {
      if (0 === formatSupport.length) return new Error("Audio Downloader: audio not supported on this browser!");
      item.content = item.url;
      !__audioSupport.WEB_AUDIO || item.urlParam && item.urlParam["useDom"] ? loadDomAudio(item, callback) : loadWebAudio(item, callback);
    }
    module.exports = downloadAudio;
  }), {
    "../../audio/CCAudioEngine": 23,
    "../platform/CCSys": 184,
    "../utils/CCPath": 218,
    "./pipeline": 142
  } ],
  134: [ (function(require, module, exports) {
    var JS = require("../platform/js");
    function parseDepends(key, parsed) {
      var item = cc.loader.getItem(key);
      if (item) {
        var depends = item.dependKeys;
        if (depends) for (var i = 0; i < depends.length; i++) {
          var depend = depends[i];
          if (!parsed[depend]) {
            parsed[depend] = true;
            parseDepends(depend, parsed);
          }
        }
      }
    }
    function visitAsset(asset, excludeMap) {
      var key = cc.loader._getReferenceKey(asset);
      if (!excludeMap[key]) {
        excludeMap[key] = true;
        parseDepends(key, excludeMap);
      }
    }
    function visitComponent(comp, excludeMap) {
      var props = Object.getOwnPropertyNames(comp);
      for (var i = 0; i < props.length; i++) {
        var value = comp[props[i]];
        if ("object" === typeof value && value) if (Array.isArray(value)) for (var j = 0; j < value.length; j++) {
          var val = value[j];
          val instanceof cc.RawAsset && visitAsset(val, excludeMap);
        } else if (value.constructor && value.constructor !== Object) value instanceof cc.RawAsset && visitAsset(value, excludeMap); else {
          var keys = Object.getOwnPropertyNames(value);
          for (var _j = 0; _j < keys.length; _j++) {
            var _val = value[keys[_j]];
            _val instanceof cc.RawAsset && visitAsset(_val, excludeMap);
          }
        }
      }
    }
    function visitNode(node, excludeMap) {
      for (var i = 0; i < node._components.length; i++) visitComponent(node._components[i], excludeMap);
      for (var _i = 0; _i < node._children.length; _i++) visitNode(node._children[_i], excludeMap);
    }
    module.exports = {
      autoRelease: function(oldSceneAssets, nextSceneAssets, persistNodes) {
        var releaseSettings = cc.loader._autoReleaseSetting;
        var excludeMap = JS.createMap();
        if (nextSceneAssets) for (var i = 0; i < nextSceneAssets.length; i++) excludeMap[nextSceneAssets[i]] = true;
        for (var _i2 = 0; _i2 < persistNodes.length; _i2++) visitNode(persistNodes[_i2], excludeMap);
        if (oldSceneAssets) for (var _i3 = 0; _i3 < oldSceneAssets.length; _i3++) {
          var key = oldSceneAssets[_i3];
          false === releaseSettings[key] || excludeMap[key] || cc.loader.release(key);
        }
        var keys = Object.keys(releaseSettings);
        for (var _i4 = 0; _i4 < keys.length; _i4++) {
          var _key = keys[_i4];
          true !== releaseSettings[_key] || excludeMap[_key] || cc.loader.release(_key);
        }
      },
      getDependsRecursively: function(key) {
        var depends = {};
        parseDepends(key, depends);
        return Object.keys(depends);
      }
    };
  }), {
    "../platform/js": 196
  } ],
  135: [ (function(require, module, exports) {
    var JS = require("../platform/js");
    var sys = require("../platform/CCSys");
    var Path = require("../utils/CCPath");
    var misc = require("../utils/misc");
    var Pipeline = require("./pipeline");
    var PackDownloader = require("./pack-downloader");
    var downloadText = require("./text-downloader");
    var urlAppendTimestamp = require("./utils").urlAppendTimestamp;
    var downloadAudio;
    true;
    downloadAudio = require("./audio-downloader");
    function downloadScript(item, callback, isAsync) {
      if (sys.platform === sys.WECHAT_GAME) {
        require(item.url);
        callback(null, item.url);
        return;
      }
      var url = item.url, d = document, s = document.createElement("script");
      s.async = isAsync;
      s.src = urlAppendTimestamp(url);
      function loadHandler() {
        s.parentNode.removeChild(s);
        s.removeEventListener("load", loadHandler, false);
        s.removeEventListener("error", errorHandler, false);
        callback(null, url);
      }
      function errorHandler() {
        s.parentNode.removeChild(s);
        s.removeEventListener("load", loadHandler, false);
        s.removeEventListener("error", errorHandler, false);
        callback(new Error("Load " + url + " failed!"), url);
      }
      s.addEventListener("load", loadHandler, false);
      s.addEventListener("error", errorHandler, false);
      d.body.appendChild(s);
    }
    function downloadWebp(item, callback, isCrossOrigin, img) {
      if (!cc.sys.capabilities.webp) return new Error("Load Webp ( " + item.url + " ) failed");
      return downloadImage(item, callback, isCrossOrigin, img);
    }
    function downloadImage(item, callback, isCrossOrigin, img) {
      void 0 === isCrossOrigin && (isCrossOrigin = true);
      var url = urlAppendTimestamp(item.url);
      img = img || misc.imagePool.get();
      isCrossOrigin && "file:" !== window.location.protocol ? img.crossOrigin = "anonymous" : img.crossOrigin = null;
      if (img.complete && img.naturalWidth > 0 && img.src === url) return img;
      (function() {
        function loadCallback() {
          img.removeEventListener("load", loadCallback);
          img.removeEventListener("error", errorCallback);
          callback(null, img);
        }
        function errorCallback() {
          img.removeEventListener("load", loadCallback);
          img.removeEventListener("error", errorCallback);
          "https:" !== window.location.protocol && img.crossOrigin && "anonymous" === img.crossOrigin.toLowerCase() ? downloadImage(item, callback, false, img) : callback(new Error("Load image (" + url + ") failed"));
        }
        img.addEventListener("load", loadCallback);
        img.addEventListener("error", errorCallback);
        img.src = url;
      })();
    }
    var FONT_TYPE = {
      ".eot": "embedded-opentype",
      ".ttf": "truetype",
      ".ttc": "truetype",
      ".woff": "woff",
      ".svg": "svg"
    };
    function _loadFont(name, srcs, type) {
      var doc = document, fontStyle = document.createElement("style");
      fontStyle.type = "text/css";
      doc.body.appendChild(fontStyle);
      var fontStr = "";
      isNaN(name - 0) ? fontStr += "@font-face { font-family:" + name + "; src:" : fontStr += "@font-face { font-family:'" + name + "'; src:";
      if (srcs instanceof Array) for (var i = 0, li = srcs.length; i < li; i++) {
        var src = srcs[i];
        type = Path.extname(src).toLowerCase();
        fontStr += "url('" + srcs[i] + "') format('" + FONT_TYPE[type] + "')";
        fontStr += i === li - 1 ? ";" : ",";
      } else {
        type = type.toLowerCase();
        fontStr += "url('" + srcs + "') format('" + FONT_TYPE[type] + "');";
      }
      fontStyle.textContent += fontStr + "}";
      var preloadDiv = document.createElement("div");
      var _divStyle = preloadDiv.style;
      _divStyle.fontFamily = name;
      preloadDiv.innerHTML = ".";
      _divStyle.position = "absolute";
      _divStyle.left = "-100px";
      _divStyle.top = "-100px";
      doc.body.appendChild(preloadDiv);
    }
    function downloadFont(item, callback) {
      var url = item.url, type = item.type, name = item.name, srcs = item.srcs;
      if (name && srcs) {
        -1 === srcs.indexOf(url) && srcs.push(url);
        _loadFont(name, srcs);
      } else {
        type = Path.extname(url);
        name = Path.basename(url, type);
        _loadFont(name, url, type);
      }
      if (!document.fonts) return null;
      document.fonts.load("1em " + name).then((function() {
        callback(null, null);
      }), (function(err) {
        callback(err);
      }));
    }
    function downloadUuid(item, callback) {
      var result = PackDownloader.load(item, callback);
      if (void 0 === result) return this.extMap["json"](item, callback);
      if (!!result) return result;
    }
    var defaultMap = {
      js: downloadScript,
      png: downloadImage,
      jpg: downloadImage,
      bmp: downloadImage,
      jpeg: downloadImage,
      gif: downloadImage,
      ico: downloadImage,
      tiff: downloadImage,
      webp: downloadWebp,
      image: downloadImage,
      mp3: downloadAudio,
      ogg: downloadAudio,
      wav: downloadAudio,
      m4a: downloadAudio,
      txt: downloadText,
      xml: downloadText,
      vsh: downloadText,
      fsh: downloadText,
      atlas: downloadText,
      tmx: downloadText,
      tsx: downloadText,
      json: downloadText,
      ExportJson: downloadText,
      plist: downloadText,
      fnt: downloadText,
      font: downloadFont,
      eot: downloadFont,
      ttf: downloadFont,
      woff: downloadFont,
      svg: downloadFont,
      ttc: downloadFont,
      uuid: downloadUuid,
      default: downloadText
    };
    var ID = "Downloader";
    var Downloader = function(extMap) {
      this.id = ID;
      this.async = true;
      this.pipeline = null;
      this._curConcurrent = 0;
      this._loadQueue = [];
      this.extMap = JS.mixin(extMap, defaultMap);
    };
    Downloader.ID = ID;
    Downloader.PackDownloader = PackDownloader;
    Downloader.prototype.addHandlers = function(extMap) {
      JS.mixin(this.extMap, extMap);
    };
    Downloader.prototype._handleLoadQueue = function() {
      while (this._curConcurrent < cc.macro.DOWNLOAD_MAX_CONCURRENT) {
        var nextOne = this._loadQueue.shift();
        if (!nextOne) break;
        var syncRet = this.handle(nextOne.item, nextOne.callback);
        void 0 !== syncRet && (syncRet instanceof Error ? nextOne.callback(syncRet) : nextOne.callback(null, syncRet));
      }
    };
    Downloader.prototype.handle = function(item, callback) {
      var self = this;
      var downloadFunc = this.extMap[item.type] || this.extMap["default"];
      var syncRet = void 0;
      if (this._curConcurrent < cc.macro.DOWNLOAD_MAX_CONCURRENT) {
        this._curConcurrent++;
        syncRet = downloadFunc.call(this, item, (function(err, result) {
          self._curConcurrent = Math.max(0, self._curConcurrent - 1);
          self._handleLoadQueue();
          callback && callback(err, result);
        }));
        if (void 0 !== syncRet) {
          this._curConcurrent = Math.max(0, this._curConcurrent - 1);
          this._handleLoadQueue();
          return syncRet;
        }
      } else if (item.ignoreMaxConcurrency) {
        syncRet = downloadFunc.call(this, item, callback);
        if (void 0 !== syncRet) return syncRet;
      } else this._loadQueue.push({
        item: item,
        callback: callback
      });
    };
    Pipeline.Downloader = module.exports = Downloader;
  }), {
    "../platform/CCSys": 184,
    "../platform/js": 196,
    "../utils/CCPath": 218,
    "../utils/misc": 225,
    "./audio-downloader": 133,
    "./pack-downloader": 141,
    "./pipeline": 142,
    "./text-downloader": 144,
    "./utils": 145
  } ],
  136: [ (function(require, module, exports) {
    require("./downloader");
    require("./loader");
    require("./json-unpacker");
    require("./loading-items");
    require("./pipeline");
    require("./CCLoader");
  }), {
    "./CCLoader": 130,
    "./downloader": 135,
    "./json-unpacker": 137,
    "./loader": 138,
    "./loading-items": 139,
    "./pipeline": 142
  } ],
  137: [ (function(require, module, exports) {
    function JsonUnpacker() {
      this.jsons = {};
      this.state = -1;
    }
    JsonUnpacker.prototype.read = function(indices, data) {
      var jsons = "string" === typeof data ? JSON.parse(data) : data;
      jsons.length !== indices.length && cc.errorID(4915);
      for (var i = 0; i < indices.length; i++) {
        var key = indices[i];
        var json = jsons[i];
        this.jsons[key] = json;
      }
    };
    JsonUnpacker.prototype.retrieve = function(key) {
      return this.jsons[key] || null;
    };
    false;
    module.exports = JsonUnpacker;
  }), {} ],
  138: [ (function(require, module, exports) {
    var JS = require("../platform/js");
    var sys = require("../platform/CCSys");
    var Pipeline = require("./pipeline");
    var Texture2D = require("../textures/CCTexture2D");
    var loadUuid = require("./uuid-loader");
    var misc = require("../utils/misc");
    function loadNothing(item, callback) {
      return null;
    }
    function loadJSON(item, callback) {
      if ("string" !== typeof item.content) return new Error("JSON Loader: Input item doesn't contain string content");
      try {
        var result = JSON.parse(item.content);
        return result;
      } catch (e) {
        return new Error("JSON Loader: Parse json [" + item.id + "] failed : " + e);
      }
    }
    function loadImage(item, callback) {
      if (sys.platform !== sys.WECHAT_GAME && !(item.content instanceof Image)) return new Error("Image Loader: Input item doesn't contain Image content");
      var rawUrl = item.rawUrl;
      var tex = cc.textureCache.getTextureForKey(rawUrl) || new Texture2D();
      tex.url = rawUrl;
      tex.initWithElement(item.content);
      tex.handleLoadedTexture();
      cc.textureCache.cacheImage(rawUrl, tex);
      return tex;
    }
    function loadPlist(item, callback) {
      if ("string" !== typeof item.content) return new Error("Plist Loader: Input item doesn't contain string content");
      var result = cc.plistParser.parse(item.content);
      return result || new Error("Plist Loader: Parse [" + item.id + "] failed");
    }
    var defaultMap = {
      png: loadImage,
      jpg: loadImage,
      bmp: loadImage,
      jpeg: loadImage,
      gif: loadImage,
      ico: loadImage,
      tiff: loadImage,
      webp: loadImage,
      image: loadImage,
      json: loadJSON,
      ExportJson: loadJSON,
      plist: loadPlist,
      uuid: loadUuid,
      prefab: loadUuid,
      fire: loadUuid,
      scene: loadUuid,
      default: loadNothing
    };
    var ID = "Loader";
    var Loader = function(extMap) {
      this.id = ID;
      this.async = true;
      this.pipeline = null;
      this.extMap = JS.mixin(extMap, defaultMap);
    };
    Loader.ID = ID;
    Loader.prototype.addHandlers = function(extMap) {
      this.extMap = JS.mixin(this.extMap, extMap);
    };
    Loader.prototype.handle = function(item, callback) {
      var loadFunc = this.extMap[item.type] || this.extMap["default"];
      return loadFunc.call(this, item, callback);
    };
    Pipeline.Loader = module.exports = Loader;
  }), {
    "../platform/CCSys": 184,
    "../platform/js": 196,
    "../textures/CCTexture2D": 215,
    "../utils/misc": 225,
    "./pipeline": 142,
    "./uuid-loader": 146
  } ],
  139: [ (function(require, module, exports) {
    var CallbacksInvoker = require("../platform/callbacks-invoker");
    var Path = require("../utils/CCPath");
    var JS = require("../platform/js");
    var _qid = 0 | 998 * Math.random();
    var _queues = {};
    var _pool = [];
    var _POOL_MAX_LENGTH = 10;
    var ItemState = {
      WORKING: 1,
      COMPLETE: 2,
      ERROR: 3
    };
    var _queueDeps = {};
    function isIdValid(id) {
      var realId = id.url || id;
      return "string" === typeof realId;
    }
    function _parseUrlParam(url) {
      if (!url) return;
      var split = url.split("?");
      if (!split || !split[0] || !split[1]) return;
      var urlParam = {};
      var queries = split[1].split("&");
      queries.forEach((function(item) {
        var itemSplit = item.split("=");
        urlParam[itemSplit[0]] = itemSplit[1];
      }));
      return urlParam;
    }
    function createItem(id, queueId) {
      var url = "object" === typeof id ? id.url : id;
      var result = {
        queueId: queueId,
        id: url,
        url: url,
        rawUrl: void 0,
        urlParam: _parseUrlParam(url),
        type: "",
        error: null,
        content: null,
        complete: false,
        states: {},
        deps: null
      };
      if ("object" === typeof id) {
        JS.mixin(result, id);
        if (id.skips) for (var i = 0; i < id.skips.length; i++) {
          var skip = id.skips[i];
          result.states[skip] = ItemState.COMPLETE;
        }
      }
      result.rawUrl = result.url;
      url && !result.type && (result.type = Path.extname(url).toLowerCase().substr(1));
      return result;
    }
    var checkedIds = [];
    function checkCircleReference(owner, item, recursiveCall) {
      if (!owner || !item) return false;
      var result = false;
      checkedIds.push(item.id);
      if (item.deps) {
        var i, deps = item.deps, subDep;
        for (i = 0; i < deps.length; i++) {
          subDep = deps[i];
          if (subDep.id === owner.id) {
            result = true;
            break;
          }
          if (checkedIds.indexOf(subDep.id) >= 0) continue;
          if (subDep.deps && checkCircleReference(owner, subDep, true)) {
            result = true;
            break;
          }
        }
      }
      recursiveCall || (checkedIds.length = 0);
      return result;
    }
    var LoadingItems = function(pipeline, urlList, onProgress, onComplete) {
      CallbacksInvoker.call(this);
      this._id = ++_qid;
      _queues[this._id] = this;
      this._pipeline = pipeline;
      this._errorUrls = [];
      this._appending = false;
      this._ownerQueue = null;
      this.onProgress = onProgress;
      this.onComplete = onComplete;
      this.map = {};
      this.completed = {};
      this.totalCount = 0;
      this.completedCount = 0;
      this._pipeline ? this.active = true : this.active = false;
      urlList && (urlList.length > 0 ? this.append(urlList) : this.allComplete());
    };
    LoadingItems.ItemState = new cc.Enum(ItemState);
    LoadingItems.create = function(pipeline, urlList, onProgress, onComplete) {
      if (void 0 === onProgress) {
        if ("function" === typeof urlList) {
          onComplete = urlList;
          urlList = onProgress = null;
        }
      } else if (void 0 === onComplete) if ("function" === typeof urlList) {
        onComplete = onProgress;
        onProgress = urlList;
        urlList = null;
      } else {
        onComplete = onProgress;
        onProgress = null;
      }
      var queue = _pool.pop();
      if (queue) {
        queue._pipeline = pipeline;
        queue.onProgress = onProgress;
        queue.onComplete = onComplete;
        _queues[queue._id] = queue;
        queue._pipeline && (queue.active = true);
        urlList && queue.append(urlList);
      } else queue = new LoadingItems(pipeline, urlList, onProgress, onComplete);
      return queue;
    };
    LoadingItems.getQueue = function(item) {
      return item.queueId ? _queues[item.queueId] : null;
    };
    LoadingItems.itemComplete = function(item) {
      var queue = _queues[item.queueId];
      queue && queue.itemComplete(item.id);
    };
    LoadingItems.initQueueDeps = function(queue) {
      var dep = _queueDeps[queue._id];
      if (dep) {
        dep.completed.length = 0;
        dep.deps.length = 0;
      } else dep = _queueDeps[queue._id] = {
        completed: [],
        deps: []
      };
    };
    LoadingItems.registerQueueDep = function(owner, depId) {
      var queueId = owner.queueId || owner;
      if (!queueId) return false;
      var queueDepList = _queueDeps[queueId];
      if (queueDepList) -1 === queueDepList.deps.indexOf(depId) && queueDepList.deps.push(depId); else if (owner.id) for (var id in _queueDeps) {
        var queue = _queueDeps[id];
        -1 !== queue.deps.indexOf(owner.id) && -1 === queue.deps.indexOf(depId) && queue.deps.push(depId);
      }
    };
    LoadingItems.finishDep = function(depId) {
      for (var id in _queueDeps) {
        var queue = _queueDeps[id];
        -1 !== queue.deps.indexOf(depId) && -1 === queue.completed.indexOf(depId) && queue.completed.push(depId);
      }
    };
    var proto = LoadingItems.prototype;
    JS.mixin(proto, CallbacksInvoker.prototype);
    proto.append = function(urlList, owner) {
      if (!this.active) return [];
      owner && !owner.deps && (owner.deps = []);
      this._appending = true;
      var accepted = [], i, url, item;
      for (i = 0; i < urlList.length; ++i) {
        url = urlList[i];
        if (url.queueId && !this.map[url.id]) {
          this.map[url.id] = url;
          owner && owner.deps.push(url);
          if (url.complete || checkCircleReference(owner, url)) {
            this.totalCount++;
            this.itemComplete(url.id);
            continue;
          }
          var self = this;
          var queue = _queues[url.queueId];
          if (queue) {
            this.totalCount++;
            LoadingItems.registerQueueDep(owner || this._id, url.id);
            queue.addListener(url.id, (function(item) {
              self.itemComplete(item.id);
            }));
          }
          continue;
        }
        if (isIdValid(url)) {
          item = createItem(url, this._id);
          var key = item.id;
          if (!this.map[key]) {
            this.map[key] = item;
            this.totalCount++;
            owner && owner.deps.push(item);
            LoadingItems.registerQueueDep(owner || this._id, key);
            accepted.push(item);
          }
        }
      }
      this._appending = false;
      this.completedCount === this.totalCount ? this.allComplete() : this._pipeline.flowIn(accepted);
      return accepted;
    };
    proto._childOnProgress = function(item) {
      if (this.onProgress) {
        var dep = _queueDeps[this._id];
        this.onProgress(dep ? dep.completed.length : this.completedCount, dep ? dep.deps.length : this.totalCount, item);
      }
    };
    proto.allComplete = function() {
      var errors = 0 === this._errorUrls.length ? null : this._errorUrls;
      this.onComplete && this.onComplete(errors, this);
    };
    proto.isCompleted = function() {
      return this.completedCount >= this.totalCount;
    };
    proto.isItemCompleted = function(id) {
      return !!this.completed[id];
    };
    proto.exists = function(id) {
      return !!this.map[id];
    };
    proto.getContent = function(id) {
      var item = this.map[id];
      var ret = null;
      item && (item.content ? ret = item.content : item.alias && (ret = item.alias.content));
      return ret;
    };
    proto.getError = function(id) {
      var item = this.map[id];
      var ret = null;
      item && (item.error ? ret = item.error : item.alias && (ret = item.alias.error));
      return ret;
    };
    proto.addListener = CallbacksInvoker.prototype.add;
    proto.hasListener = CallbacksInvoker.prototype.has;
    proto.removeListener = CallbacksInvoker.prototype.remove;
    proto.removeAllListeners = CallbacksInvoker.prototype.removeAll;
    proto.removeItem = function(url) {
      var item = this.map[url];
      if (!item) return;
      if (!this.completed[item.alias || url]) return;
      delete this.completed[url];
      delete this.map[url];
      if (item.alias) {
        delete this.completed[item.alias.id];
        delete this.map[item.alias.id];
      }
      this.completedCount--;
      this.totalCount--;
    };
    proto.itemComplete = function(id) {
      var item = this.map[id];
      if (!item) return;
      var errorListId = this._errorUrls.indexOf(id);
      item.error && -1 === errorListId ? this._errorUrls.push(id) : item.error || -1 === errorListId || this._errorUrls.splice(errorListId, 1);
      this.completed[id] = item;
      this.completedCount++;
      LoadingItems.finishDep(item.id);
      if (this.onProgress) {
        var dep = _queueDeps[this._id];
        this.onProgress(dep ? dep.completed.length : this.completedCount, dep ? dep.deps.length : this.totalCount, item);
      }
      this.invoke(id, item);
      this.removeAll(id);
      !this._appending && this.completedCount >= this.totalCount && this.allComplete();
    };
    proto.destroy = function() {
      this.active = false;
      this._appending = false;
      this._pipeline = null;
      this._ownerQueue = null;
      this._errorUrls.length = 0;
      this.onProgress = null;
      this.onComplete = null;
      this.map = {};
      this.completed = {};
      this.totalCount = 0;
      this.completedCount = 0;
      CallbacksInvoker.call(this);
      _queues[this._id] = null;
      if (_queueDeps[this._id]) {
        _queueDeps[this._id].completed.length = 0;
        _queueDeps[this._id].deps.length = 0;
      }
      -1 === _pool.indexOf(this) && _pool.length < _POOL_MAX_LENGTH && _pool.push(this);
    };
    cc.LoadingItems = module.exports = LoadingItems;
  }), {
    "../platform/callbacks-invoker": 189,
    "../platform/js": 196,
    "../utils/CCPath": 218
  } ],
  140: [ (function(require, module, exports) {
    var Pipeline = require("./pipeline");
    var ID = "MD5Pipe";
    var ExtnameRegex = /(\.[^.\n\\/]*)$/;
    var MD5Pipe = function(md5AssetsMap, libraryBase, rawAssetsBase) {
      this.id = ID;
      this.async = false;
      this.pipeline = null;
      this.md5AssetsMap = md5AssetsMap;
      this.libraryBase = libraryBase;
      this.rawAssetsBase = rawAssetsBase;
    };
    MD5Pipe.ID = ID;
    MD5Pipe.prototype.handle = function(item) {
      item.url = this.transformURL(item.url);
      return item;
    };
    MD5Pipe.prototype.transformURL = function(url) {
      var index = url.indexOf("?");
      var key = url;
      -1 !== index && (key = url.substr(0, index));
      if (key.startsWith(this.libraryBase)) key = key.slice(this.libraryBase.length); else {
        if (!key.startsWith(this.rawAssetsBase)) return url;
        key = key.slice(this.rawAssetsBase.length);
      }
      var hashValue = this.md5AssetsMap[key];
      if (hashValue) {
        var matched = false;
        url = url.replace(ExtnameRegex, (function(match, p1) {
          matched = true;
          return "." + hashValue + p1;
        }));
        matched || (url = url + "." + hashValue);
      }
      return url;
    };
    Pipeline.MD5Pipe = module.exports = MD5Pipe;
  }), {
    "./pipeline": 142
  } ],
  141: [ (function(require, module, exports) {
    var JsonUnpacker = require("./json-unpacker");
    var pushToMap = require("../utils/misc").pushToMap;
    var uuidToPack = {};
    var packIndices = {};
    var globalUnpackers = {};
    var PackState = {
      Invalid: 0,
      Removed: 1,
      Downloading: 2,
      Loaded: 3
    };
    function error(uuid, packUuid) {
      return new Error("Can not retrieve " + uuid + " from packer " + packUuid);
    }
    module.exports = {
      initPacks: function(packs) {
        packIndices = packs;
        for (var packUuid in packs) {
          var uuids = packs[packUuid];
          for (var i = 0; i < uuids.length; i++) {
            var uuid = uuids[i];
            var pushFront = 1 === uuids.length;
            pushToMap(uuidToPack, uuid, packUuid, pushFront);
          }
        }
      },
      _loadNewPack: function(uuid, packUuid, callback) {
        var self = this;
        var packUrl = cc.AssetLibrary.getLibUrlNoExt(packUuid) + ".json";
        cc.loader.load({
          url: packUrl,
          ignoreMaxConcurrency: true
        }, (function(err, packJson) {
          if (err) {
            cc.errorID(4916, uuid);
            return callback(err);
          }
          var res = self._doLoadNewPack(uuid, packUuid, packJson);
          res ? callback(null, res) : callback(error(uuid, packUuid));
        }));
      },
      _doLoadNewPack: function(uuid, packUuid, packJson) {
        var unpacker = globalUnpackers[packUuid];
        if (unpacker.state !== PackState.Loaded) {
          unpacker.read(packIndices[packUuid], packJson);
          unpacker.state = PackState.Loaded;
        }
        return unpacker.retrieve(uuid);
      },
      _selectLoadedPack: function(packUuids) {
        var existsPackState = PackState.Invalid;
        var existsPackUuid = "";
        for (var i = 0; i < packUuids.length; i++) {
          var packUuid = packUuids[i];
          var unpacker = globalUnpackers[packUuid];
          if (unpacker) {
            var state = unpacker.state;
            if (state === PackState.Loaded) return packUuid;
            if (state > existsPackState) {
              existsPackState = state;
              existsPackUuid = packUuid;
            }
          }
        }
        return existsPackState !== PackState.Invalid ? existsPackUuid : packUuids[0];
      },
      load: function(item, callback) {
        var uuid = item.uuid;
        var packUuid = uuidToPack[uuid];
        if (!packUuid) return;
        Array.isArray(packUuid) && (packUuid = this._selectLoadedPack(packUuid));
        var unpacker = globalUnpackers[packUuid];
        if (unpacker && unpacker.state === PackState.Loaded) {
          var json = unpacker.retrieve(uuid);
          return json || error(uuid, packUuid);
        }
        if (!unpacker) {
          true;
          console.log("Create unpacker %s for %s", packUuid, uuid);
          unpacker = globalUnpackers[packUuid] = new JsonUnpacker();
          unpacker.state = PackState.Downloading;
        }
        this._loadNewPack(uuid, packUuid, callback);
        return null;
      }
    };
    false;
  }), {
    "../utils/misc": 225,
    "./json-unpacker": 137
  } ],
  142: [ (function(require, module, exports) {
    var JS = require("../platform/js");
    var LoadingItems = require("./loading-items");
    var ItemState = LoadingItems.ItemState;
    function flow(pipe, item) {
      var pipeId = pipe.id;
      var itemState = item.states[pipeId];
      var next = pipe.next;
      var pipeline = pipe.pipeline;
      if (item.error || itemState === ItemState.WORKING || itemState === ItemState.ERROR) return;
      if (itemState === ItemState.COMPLETE) next ? flow(next, item) : pipeline.flowOut(item); else {
        item.states[pipeId] = ItemState.WORKING;
        var result = pipe.handle(item, (function(err, result) {
          if (err) {
            item.error = err;
            item.states[pipeId] = ItemState.ERROR;
            pipeline.flowOut(item);
          } else {
            result && (item.content = result);
            item.states[pipeId] = ItemState.COMPLETE;
            next ? flow(next, item) : pipeline.flowOut(item);
          }
        }));
        if (result instanceof Error) {
          item.error = result;
          item.states[pipeId] = ItemState.ERROR;
          pipeline.flowOut(item);
        } else if (void 0 !== result) {
          null !== result && (item.content = result);
          item.states[pipeId] = ItemState.COMPLETE;
          next ? flow(next, item) : pipeline.flowOut(item);
        }
      }
    }
    var Pipeline = function(pipes) {
      this._pipes = pipes;
      this._cache = {};
      for (var i = 0; i < pipes.length; ++i) {
        var pipe = pipes[i];
        if (!pipe.handle || !pipe.id) continue;
        pipe.pipeline = this;
        pipe.next = i < pipes.length - 1 ? pipes[i + 1] : null;
      }
    };
    Pipeline.ItemState = ItemState;
    var proto = Pipeline.prototype;
    proto.insertPipe = function(pipe, index) {
      if (!pipe.handle || !pipe.id || index > this._pipes.length) {
        cc.warnID(4921);
        return;
      }
      if (this._pipes.indexOf(pipe) > 0) {
        cc.warnID(4922);
        return;
      }
      pipe.pipeline = this;
      var nextPipe = null;
      index < this._pipes.length && (nextPipe = this._pipes[index]);
      var previousPipe = null;
      index > 0 && (previousPipe = this._pipes[index - 1]);
      previousPipe && (previousPipe.next = pipe);
      pipe.next = nextPipe;
      this._pipes.splice(index, 0, pipe);
    };
    proto.insertPipeAfter = function(refPipe, newPipe) {
      var index = this._pipes.indexOf(refPipe);
      if (index < 0) return;
      this.insertPipe(newPipe, index + 1);
    };
    proto.appendPipe = function(pipe) {
      if (!pipe.handle || !pipe.id) return;
      pipe.pipeline = this;
      pipe.next = null;
      this._pipes.length > 0 && (this._pipes[this._pipes.length - 1].next = pipe);
      this._pipes.push(pipe);
    };
    proto.flowIn = function(items) {
      var i, pipe = this._pipes[0], item;
      if (pipe) {
        for (i = 0; i < items.length; i++) {
          item = items[i];
          this._cache[item.id] = item;
        }
        for (i = 0; i < items.length; i++) {
          item = items[i];
          flow(pipe, item);
        }
      } else for (i = 0; i < items.length; i++) this.flowOut(items[i]);
    };
    proto.flowInDeps = function(owner, urlList, callback) {
      var deps = LoadingItems.create(this, (function(errors, items) {
        callback(errors, items);
        items.destroy();
      }));
      return deps.append(urlList, owner);
    };
    proto.flowOut = function(item) {
      item.error ? delete this._cache[item.id] : this._cache[item.id] || (this._cache[item.id] = item);
      item.complete = true;
      LoadingItems.itemComplete(item);
    };
    proto.copyItemStates = function(srcItem, dstItems) {
      if (!(dstItems instanceof Array)) {
        dstItems.states = srcItem.states;
        return;
      }
      for (var i = 0; i < dstItems.length; ++i) dstItems[i].states = srcItem.states;
    };
    proto.isFlowing = function() {
      return true;
    };
    proto.getItems = function() {
      return null;
    };
    proto.getItem = function(id) {
      var item = this._cache[id];
      if (!item) return item;
      item.alias && (item = item.alias);
      return item;
    };
    proto.removeItem = function(id) {
      var removed = this._cache[id];
      removed && removed.complete && delete this._cache[id];
      return removed;
    };
    proto.clear = function() {
      for (var id in this._cache) {
        var item = this._cache[id];
        delete this._cache[id];
        if (!item.complete) {
          item.error = new Error("Canceled manually");
          this.flowOut(item);
        }
      }
    };
    cc.Pipeline = module.exports = Pipeline;
  }), {
    "../platform/js": 196,
    "./loading-items": 139
  } ],
  143: [ (function(require, module, exports) {
    true;
    var JS;
    var tmpInfo;
    (function() {
      JS = require("../platform/js");
      function ReleasedAssetChecker() {
        this._releasedKeys = JS.createMap(true);
        this._dirty = false;
      }
      ReleasedAssetChecker.prototype.setReleased = function(item, releasedKey) {
        this._releasedKeys[releasedKey] = true;
        this._dirty = true;
      };
      tmpInfo = null;
      function getItemDesc(item) {
        if (item.uuid) {
          tmpInfo || (tmpInfo = {
            path: "",
            type: null
          });
          if (cc.loader._resources._getInfo_DEBUG(item.uuid, tmpInfo)) {
            tmpInfo.path = "resources/" + tmpInfo.path;
            return '"' + tmpInfo.path + '" (type: ' + JS.getClassName(tmpInfo.type) + ", uuid: " + item.uuid + ")";
          }
          return '"' + item.rawUrl + '" (' + item.uuid + ")";
        }
        return '"' + item.rawUrl + '"';
      }
      function doCheckCouldRelease(releasedKey, refOwnerItem, caches) {
        var loadedAgain = caches[releasedKey];
        loadedAgain || cc.log('"' + releasedKey + '" was released but maybe still referenced by ' + getItemDesc(refOwnerItem));
      }
      ReleasedAssetChecker.prototype.checkCouldRelease = function(caches) {
        if (!this._dirty) return;
        this._dirty = false;
        var released = this._releasedKeys;
        for (var id in caches) {
          var item = caches[id];
          item.alias && (item = item.alias);
          var depends = item.dependKeys;
          if (depends) for (var i = 0; i < depends.length; ++i) {
            var depend = depends[i];
            if (released[depend]) {
              doCheckCouldRelease(depend, item, caches);
              delete released[depend];
            }
          }
        }
        JS.clear(released);
      };
      module.exports = ReleasedAssetChecker;
    })();
  }), {
    "../platform/js": 196
  } ],
  144: [ (function(require, module, exports) {
    var sys = require("../platform/CCSys");
    false;
    var urlAppendTimestamp = require("./utils").urlAppendTimestamp;
    module.exports = function(item, callback) {
      var url = item.url;
      url = urlAppendTimestamp(url);
      var xhr = cc.loader.getXMLHttpRequest(), errInfo = "Load " + url + " failed!", navigator = window.navigator;
      xhr.open("GET", url, true);
      if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
        xhr.setRequestHeader("Accept-Charset", "utf-8");
        xhr.onreadystatechange = function() {
          4 === xhr.readyState && (200 === xhr.status || 0 === xhr.status ? callback(null, xhr.responseText) : callback({
            status: xhr.status,
            errorMessage: errInfo
          }));
        };
      } else {
        xhr.overrideMimeType && xhr.overrideMimeType("text/plain; charset=utf-8");
        xhr.onload = function() {
          4 === xhr.readyState && (200 === xhr.status || 0 === xhr.status ? callback(null, xhr.responseText) : callback({
            status: xhr.status,
            errorMessage: errInfo
          }));
        };
        xhr.onerror = function() {
          callback({
            status: xhr.status,
            errorMessage: errInfo
          });
        };
      }
      xhr.send(null);
    };
  }), {
    "../platform/CCSys": 184,
    "./utils": 145
  } ],
  145: [ (function(require, module, exports) {
    var _noCacheRex = /\?/;
    module.exports = {
      urlAppendTimestamp: function(url) {
        cc.game.config["noCache"] && "string" === typeof url && (_noCacheRex.test(url) ? url += "&_t=" + (new Date() - 0) : url += "?_t=" + (new Date() - 0));
        return url;
      }
    };
  }), {} ],
  146: [ (function(require, module, exports) {
    var JS = require("../platform/js");
    require("../platform/deserialize");
    var LoadingItems = require("./loading-items");
    function isSceneObj(json) {
      var SCENE_ID = "cc.Scene";
      var PREFAB_ID = "cc.Prefab";
      return json && (json[0] && json[0].__type__ === SCENE_ID || json[1] && json[1].__type__ === SCENE_ID || json[0] && json[0].__type__ === PREFAB_ID);
    }
    function loadDepends(pipeline, item, asset, tdInfo, deferredLoadRawAssetsInRuntime, callback) {
      var uuidList = tdInfo.uuidList;
      var objList, propList, depends;
      var i, dependUuid;
      var dependKeys = item.dependKeys = [];
      if (deferredLoadRawAssetsInRuntime) {
        objList = [];
        propList = [];
        depends = [];
        for (i = 0; i < uuidList.length; i++) {
          dependUuid = uuidList[i];
          var obj = tdInfo.uuidObjList[i];
          var prop = tdInfo.uuidPropList[i];
          var info = cc.AssetLibrary._getAssetInfoInRuntime(dependUuid);
          if (info.raw) {
            var url = info.url;
            obj[prop] = url;
            dependKeys.push(url);
          } else {
            objList.push(obj);
            propList.push(prop);
            depends.push({
              type: "uuid",
              uuid: dependUuid,
              deferredLoadRaw: true
            });
          }
        }
      } else {
        objList = tdInfo.uuidObjList;
        propList = tdInfo.uuidPropList;
        depends = new Array(uuidList.length);
        for (i = 0; i < uuidList.length; i++) {
          dependUuid = uuidList[i];
          depends[i] = {
            type: "uuid",
            uuid: dependUuid
          };
        }
      }
      if (tdInfo.rawProp) {
        objList.push(asset);
        propList.push(tdInfo.rawProp);
        depends.push(item.url);
      }
      if (asset._preloadRawFiles) {
        var finalCallback = callback;
        callback = function() {
          asset._preloadRawFiles((function(err) {
            finalCallback(err || null, asset);
          }));
        };
      }
      if (0 === depends.length) {
        cc.deserialize.Details.pool.put(tdInfo);
        return callback(null, asset);
      }
      item.content = asset;
      pipeline.flowInDeps(item, depends, (function(errors, items) {
        var item, missingAssetReporter;
        for (var src in items.map) {
          item = items.map[src];
          item.uuid && item.content && (item.content._uuid = item.uuid);
        }
        for (var i = 0; i < depends.length; i++) {
          var dependSrc = depends[i].uuid;
          var dependUrl = depends[i].url;
          var dependObj = objList[i];
          var dependProp = propList[i];
          item = items.map[dependUrl];
          if (item) {
            var thisOfLoadCallback = {
              obj: dependObj,
              prop: dependProp
            };
            function loadCallback(item) {
              var value = item.isRawAsset ? item.rawUrl : item.content;
              this.obj[this.prop] = value;
              item.uuid !== asset._uuid && dependKeys.indexOf(item.id) < 0 && dependKeys.push(item.id);
            }
            if (item.complete || item.content) if (item.error) {
              var MissingObjectReporter;
              false;
              cc._throw(item.error);
            } else loadCallback.call(thisOfLoadCallback, item); else {
              var queue = LoadingItems.getQueue(item);
              var list = queue._callbackTable[dependSrc];
              list ? list.unshift(loadCallback, thisOfLoadCallback) : queue.addListener(dependSrc, loadCallback, thisOfLoadCallback);
            }
          }
        }
        false;
        cc.deserialize.Details.pool.put(tdInfo);
        callback(null, asset);
      }));
    }
    function canDeferredLoad(asset, item, isScene) {
      false, false;
      var res = item.deferredLoadRaw;
      res ? asset instanceof cc.Asset && asset.constructor.preventDeferredLoadDependents && (res = false) : isScene && (asset instanceof cc.SceneAsset || asset instanceof cc.Prefab) && (res = asset.asyncLoadAssets);
      return res;
    }
    var MissingClass;
    function loadUuid(item, callback) {
      false;
      var json;
      if ("string" === typeof item.content) try {
        json = JSON.parse(item.content);
      } catch (e) {
        return new Error("Uuid Loader: Parse asset [" + item.id + "] failed : " + e.stack);
      } else {
        if ("object" !== typeof item.content) return new Error("JSON Loader: Input item doesn't contain string content");
        json = item.content;
      }
      var classFinder;
      var isScene = isSceneObj(json);
      if (isScene) {
        false;
        classFinder = cc._MissingScript.safeFindClass;
      } else classFinder = function(id) {
        var cls = JS._getClassById(id);
        if (cls) return cls;
        cc.warnID(4903, id);
        return Object;
      };
      var tdInfo = cc.deserialize.Details.pool.get();
      var asset;
      try {
        asset = cc.deserialize(json, tdInfo, {
          classFinder: classFinder,
          target: item.existingAsset,
          customEnv: item
        });
      } catch (e) {
        cc.deserialize.Details.pool.put(tdInfo);
        var err = e.stack;
        return new Error("Uuid Loader: Deserialize asset [" + item.id + "] failed : " + err);
      }
      asset._uuid = item.uuid;
      false;
      var deferredLoad = canDeferredLoad(asset, item, isScene);
      loadDepends(this.pipeline, item, asset, tdInfo, deferredLoad, callback);
    }
    module.exports = loadUuid;
    loadUuid.isSceneObj = isSceneObj;
  }), {
    "../platform/deserialize": 191,
    "../platform/js": 196,
    "./loading-items": 139
  } ],
  147: [ (function(require, module, exports) {
    var CompScheduler = require("./component-scheduler");
    var Flags = require("./platform/CCObject").Flags;
    var JS = require("./platform/js");
    var callerFunctor = false;
    var MAX_POOL_SIZE = 4;
    var IsPreloadStarted = Flags.IsPreloadStarted;
    var IsOnLoadStarted = Flags.IsOnLoadStarted;
    var IsOnLoadCalled = Flags.IsOnLoadCalled;
    var Deactivating = Flags.Deactivating;
    var callPreloadInTryCatch = false;
    var callOnLoadInTryCatch = false;
    var callOnDestroyInTryCatch = false;
    var callResetInTryCatch = false;
    var callOnFocusInTryCatch = false;
    var callOnLostFocusInTryCatch = false;
    var callPreload = "c.__preload();";
    var callOnLoad = "c.onLoad();c._objFlags|=" + IsOnLoadCalled;
    var UnsortedInvoker = cc.Class({
      extends: CompScheduler.LifeCycleInvoker,
      add: function(comp) {
        this._zero.array.push(comp);
      },
      remove: function(comp) {
        this._zero.fastRemove(comp);
      },
      cancelInactive: function(flagToClear) {
        CompScheduler.LifeCycleInvoker.stableRemoveInactive(this._zero, flagToClear);
      },
      invoke: function() {
        this._invoke(this._zero);
        this._zero.array.length = 0;
      }
    });
    var invokePreload = CompScheduler.createInvokeImpl(callPreload);
    var invokeOnLoad = CompScheduler.createInvokeImpl(callOnLoad);
    var activateTasksPool = new JS.Pool(MAX_POOL_SIZE);
    activateTasksPool.get = function getActivateTask() {
      var task = this._get() || {
        preload: new UnsortedInvoker(invokePreload),
        onLoad: new CompScheduler.OneOffInvoker(invokeOnLoad),
        onEnable: new CompScheduler.OneOffInvoker(CompScheduler.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) {
      false;
      comp ? node._removeComponent(comp) : JS.array.removeAt(node._components, index);
    }
    function _onLoadInEditor(comp) {
      if (comp.onLoad && !cc.engine._isPlaying) {
        var focused = Editor.Selection.curActivate("node") === comp.node.uuid;
        focused && comp.onFocusInEditor ? callOnFocusInTryCatch(comp) : comp.onLostFocusInEditor && callOnLostFocusInTryCatch(comp);
      }
      true;
      _Scene.AssetsWatcher.start(comp);
    }
    function ctor() {
      this._activatingStack = [];
    }
    var NodeActivator = cc.Class({
      ctor: ctor,
      reset: ctor,
      _activateNodeRecursively: function(node, preloadInvoker, onLoadInvoker, onEnableInvoker) {
        if (node._objFlags & Deactivating) {
          cc.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 cc.Component) this.activateComp(component, preloadInvoker, onLoadInvoker, onEnableInvoker); else {
            _componentCorrupted(node, component, i);
            --i;
            --originCount;
          }
        }
        for (var _i = 0, len = node._children.length; _i < len; ++_i) {
          var child = node._children[_i];
          child._active && this._activateNodeRecursively(child, preloadInvoker, onLoadInvoker, onEnableInvoker);
        }
        node._onPostActivated(true);
      },
      _deactivateNodeRecursively: function(node) {
        false;
        node._objFlags |= Deactivating;
        node._activeInHierarchy = false;
        var originCount = node._components.length;
        for (var c = 0; c < originCount; ++c) {
          var component = node._components[c];
          if (component._enabled) {
            cc.director._compScheduler.disableComp(component);
            if (node._activeInHierarchy) {
              node._objFlags &= ~Deactivating;
              return;
            }
          }
        }
        for (var i = 0, len = node._children.length; i < len; ++i) {
          var child = node._children[i];
          if (child._activeInHierarchy) {
            this._deactivateNodeRecursively(child);
            if (node._activeInHierarchy) {
              node._objFlags &= ~Deactivating;
              return;
            }
          }
        }
        node._onPostActivated(false);
        node._objFlags &= ~Deactivating;
      },
      activateNode: function(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 i = 0; i < stack.length; i++) {
            var lastTask = stack[i];
            lastTask.preload.cancelInactive(IsPreloadStarted);
            lastTask.onLoad.cancelInactive(IsOnLoadStarted);
            lastTask.onEnable.cancelInactive();
          }
        }
        node.emit("active-in-hierarchy-changed", node);
      },
      activateComp: function(comp, preloadInvoker, onLoadInvoker, onEnableInvoker) {
        if (!(comp._objFlags & IsPreloadStarted)) {
          comp._objFlags |= IsPreloadStarted;
          "function" === typeof comp.__preload && (preloadInvoker ? preloadInvoker.add(comp) : comp.__preload());
        }
        if (!(comp._objFlags & IsOnLoadStarted)) {
          comp._objFlags |= IsOnLoadStarted;
          if (comp.onLoad) if (onLoadInvoker) onLoadInvoker.add(comp); else {
            comp.onLoad();
            comp._objFlags |= IsOnLoadCalled;
          } else comp._objFlags |= IsOnLoadCalled;
        }
        if (comp._enabled) {
          var deactivatedOnLoading = !comp.node._activeInHierarchy;
          if (deactivatedOnLoading) return;
          cc.director._compScheduler.enableComp(comp, onEnableInvoker);
        }
      },
      destroyComp: function(comp) {
        cc.director._compScheduler.disableComp(comp);
        comp.onDestroy && comp._objFlags & IsOnLoadCalled && comp.onDestroy();
      },
      resetComp: false
    });
    module.exports = NodeActivator;
  }), {
    "./component-scheduler": 70,
    "./platform/CCObject": 181,
    "./platform/js": 196,
    "./utils/misc": 225
  } ],
  148: [ (function(require, module, exports) {
    var PTM_RATIO = require("./CCPhysicsTypes").PTM_RATIO;
    var ContactType = require("./CCPhysicsTypes").ContactType;
    var pools = [];
    var pointCache = [ cc.v2(), cc.v2() ];
    var b2worldmanifold;
    true;
    b2worldmanifold = new b2.WorldManifold();
    var worldmanifold = {
      points: [],
      separations: [],
      normal: cc.v2()
    };
    function ManifoldPoint() {
      this.localPoint = cc.v2();
      this.normalImpulse = 0;
      this.tangentImpulse = 0;
    }
    var manifoldPointCache = [ new ManifoldPoint(), new ManifoldPoint() ];
    var b2manifold;
    true;
    b2manifold = new b2.Manifold();
    var manifold = {
      type: 0,
      localPoint: cc.v2(),
      localNormal: cc.v2(),
      points: []
    };
    var impulse = {
      normalImpulses: [],
      tangentImpulses: []
    };
    function PhysicsContact() {}
    PhysicsContact.prototype.init = function(b2contact) {
      this.colliderA = b2contact.GetFixtureA().collider;
      this.colliderB = b2contact.GetFixtureB().collider;
      this.disabled = false;
      this.disabledOnce = false;
      this._impulse = null;
      this._inverted = false;
      this._b2contact = b2contact;
      b2contact._contact = this;
    };
    PhysicsContact.prototype.reset = function() {
      this.colliderA = null;
      this.colliderB = null;
      this.disabled = false;
      this._impulse = null;
      this._b2contact._contact = null;
      this._b2contact = null;
    };
    PhysicsContact.prototype.getWorldManifold = function() {
      var points = worldmanifold.points;
      var separations = worldmanifold.separations;
      var normal = worldmanifold.normal;
      var wrapper;
      var count;
      var i;
      var _p2;
      false;
      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 * PTM_RATIO;
        p.y = b2points[i].y * PTM_RATIO;
        points[i] = p;
        separations[i] = b2separations[i] * PTM_RATIO;
      }
      normal.x = b2worldmanifold.normal.x;
      normal.y = b2worldmanifold.normal.y;
      if (this._inverted) {
        normal.x *= -1;
        normal.y *= -1;
      }
      return worldmanifold;
    };
    PhysicsContact.prototype.getManifold = function() {
      var points = manifold.points;
      var localNormal = manifold.localNormal;
      var localPoint = manifold.localPoint;
      var wrapper;
      var count;
      var i;
      var p;
      false;
      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 * PTM_RATIO;
        p.localPoint.Y = b2p.localPoint.Y * PTM_RATIO;
        p.normalImpulse = b2p.normalImpulse * PTM_RATIO;
        p.tangentImpulse = b2p.tangentImpulse;
        points[i] = p;
      }
      localPoint.x = b2manifold.localPoint.x * PTM_RATIO;
      localPoint.y = b2manifold.localPoint.y * 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;
    };
    PhysicsContact.prototype.getImpulse = function() {
      var b2impulse = this._impulse;
      if (!b2impulse) return null;
      var normalImpulses = impulse.normalImpulses;
      var tangentImpulses = impulse.tangentImpulses;
      var count;
      var i;
      false;
      count = b2impulse.count;
      for (var i = 0; i < count; i++) {
        normalImpulses[i] = b2impulse.normalImpulses[i] * PTM_RATIO;
        tangentImpulses[i] = b2impulse.tangentImpulses[i];
      }
      tangentImpulses.length = normalImpulses.length = count;
      return impulse;
    };
    PhysicsContact.prototype.emit = function(contactType) {
      var func;
      switch (contactType) {
       case ContactType.BEGIN_CONTACT:
        func = "onBeginContact";
        break;

       case ContactType.END_CONTACT:
        func = "onEndContact";
        break;

       case ContactType.PRE_SOLVE:
        func = "onPreSolve";
        break;

       case ContactType.POST_SOLVE:
        func = "onPostSolve";
      }
      var colliderA = this.colliderA;
      var colliderB = this.colliderB;
      var bodyA = colliderA.body;
      var bodyB = colliderB.body;
      var comps;
      var i, l, comp;
      if (bodyA.enabledContactListener) {
        comps = bodyA.node._components;
        this._inverted = false;
        for (i = 0, l = comps.length; i < l; i++) {
          comp = comps[i];
          comp[func] && comp[func](this, colliderA, colliderB);
        }
      }
      if (bodyB.enabledContactListener) {
        comps = bodyB.node._components;
        this._inverted = true;
        for (i = 0, l = comps.length; i < l; i++) {
          comp = comps[i];
          comp[func] && comp[func](this, colliderB, colliderA);
        }
      }
      if (this.disabled || this.disabledOnce) {
        this.setEnabled(false);
        this.disabledOnce = false;
      }
    };
    PhysicsContact.get = function(b2contact) {
      var c;
      c = 0 === pools.length ? new cc.PhysicsContact() : pools.pop();
      c.init(b2contact);
      return c;
    };
    PhysicsContact.put = function(b2contact) {
      var c = b2contact._contact;
      if (!c) return;
      pools.push(c);
      c.reset();
    };
    var _p = PhysicsContact.prototype;
    _p.setEnabled = function(value) {
      this._b2contact.SetEnabled(value);
    };
    _p.isTouching = function() {
      return this._b2contact.IsTouching();
    };
    _p.setTangentSpeed = function(value) {
      this._b2contact.SetTangentSpeed(value / PTM_RATIO);
    };
    _p.getTangentSpeed = function() {
      return this._b2contact.GetTangentSpeed() * PTM_RATIO;
    };
    _p.setFriction = function(value) {
      this._b2contact.SetFriction(value);
    };
    _p.getFriction = function() {
      return this._b2contact.GetFriction();
    };
    _p.resetFriction = function() {
      return this._b2contact.ResetFriction();
    };
    _p.setRestitution = function(value) {
      this._b2contact.SetRestitution(value);
    };
    _p.getRestitution = function() {
      return this._b2contact.GetRestitution();
    };
    _p.resetRestitution = function() {
      return this._b2contact.ResetRestitution();
    };
    PhysicsContact.ContactType = ContactType;
    cc.PhysicsContact = module.exports = PhysicsContact;
  }), {
    "./CCPhysicsTypes": 150
  } ],
  149: [ (function(require, module, exports) {
    var ContactType = require("./CCPhysicsTypes").ContactType;
    var BodyType = require("./CCPhysicsTypes").BodyType;
    var RayCastType = require("./CCPhysicsTypes").RayCastType;
    var PTM_RATIO = require("./CCPhysicsTypes").PTM_RATIO;
    var ANGLE_TO_PHYSICS_ANGLE = require("./CCPhysicsTypes").ANGLE_TO_PHYSICS_ANGLE;
    var PHYSICS_ANGLE_TO_ANGLE = require("./CCPhysicsTypes").PHYSICS_ANGLE_TO_ANGLE;
    var tempB2AABB = new b2.AABB();
    var tempB2Vec21 = new b2.Vec2();
    var tempB2Vec22 = new b2.Vec2();
    var FIXED_TIME_STEP = 1 / 60;
    var MAX_ACCUMULATOR = .2;
    var PhysicsManager = cc.Class({
      mixins: [ cc.EventTarget ],
      statics: {
        DrawBits: b2.Draw,
        PTM_RATIO: PTM_RATIO,
        VELOCITY_ITERATIONS: 10,
        POSITION_ITERATIONS: 10
      },
      ctor: function() {
        this.__instanceId = cc.ClassManager.getNewInstanceId();
        this._debugDrawFlags = 0;
        this._debugDrawer = null;
        this._world = null;
        this._bodies = [];
        this._contactMap = {};
        this._contactID = 0;
        this._delayEvents = [];
        this._accumulator = 0;
        this.enabledAccumulator = false;
      },
      pushDelayEvent: function(target, func, args) {
        this._steping ? this._delayEvents.push({
          target: target,
          func: func,
          args: args
        }) : target[func].apply(target, args);
      },
      update: function(dt) {
        var world = this._world;
        if (!world || !this.enabled) return;
        this.emit("before-step");
        this._steping = true;
        var velocityIterations = PhysicsManager.VELOCITY_ITERATIONS;
        var positionIterations = PhysicsManager.POSITION_ITERATIONS;
        if (this.enabledAccumulator) {
          this._accumulator += dt;
          this._accumulator > MAX_ACCUMULATOR && (this._accumulator = MAX_ACCUMULATOR);
          while (this._accumulator > FIXED_TIME_STEP) {
            world.Step(FIXED_TIME_STEP, velocityIterations, positionIterations);
            this._accumulator -= FIXED_TIME_STEP;
          }
        } else {
          var timeStep = 1 / cc.game.config["frameRate"];
          world.Step(timeStep, velocityIterations, positionIterations);
        }
        world.DrawDebugData();
        this._steping = false;
        var events = this._delayEvents;
        for (var i = 0, l = events.length; i < l; i++) {
          var event = events[i];
          event.target[event.func].apply(event.target, event.args);
        }
        events.length = 0;
        this._syncNode();
      },
      testPoint: function(point) {
        var x = tempB2Vec21.x = point.x / PTM_RATIO;
        var y = tempB2Vec21.y = point.y / PTM_RATIO;
        var d = .2 / 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(tempB2Vec21);
        this._world.QueryAABB(callback, tempB2AABB);
        var fixture = callback.getFixture();
        if (fixture) return fixture.collider;
        return null;
      },
      testAABB: function(rect) {
        tempB2AABB.lowerBound.x = rect.xMin / PTM_RATIO;
        tempB2AABB.lowerBound.y = rect.yMin / PTM_RATIO;
        tempB2AABB.upperBound.x = rect.xMax / PTM_RATIO;
        tempB2AABB.upperBound.y = rect.yMax / PTM_RATIO;
        var callback = this._aabbQueryCallback;
        callback.init();
        this._world.QueryAABB(callback, tempB2AABB);
        var fixtures = callback.getFixtures();
        var colliders = fixtures.map((function(fixture) {
          return fixture.collider;
        }));
        return colliders;
      },
      rayCast: function(p1, p2, type) {
        if (p1.equals(p2)) return [];
        type = type || RayCastType.Closest;
        tempB2Vec21.x = p1.x / PTM_RATIO;
        tempB2Vec21.y = p1.y / PTM_RATIO;
        tempB2Vec22.x = p2.x / PTM_RATIO;
        tempB2Vec22.y = p2.y / PTM_RATIO;
        var callback = this._raycastQueryCallback;
        callback.init(type);
        this._world.RayCast(callback, tempB2Vec21, tempB2Vec22);
        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 collider = fixture.collider;
            if (type === RayCastType.AllClosest) {
              var result = results.find((function(result) {
                return result.collider === collider;
              }));
              if (result) {
                if (fractions[i] < result.fraction) {
                  result.fixtureIndex = collider._getFixtureIndex(fixture);
                  result.point.x = points[i].x * PTM_RATIO;
                  result.point.y = points[i].y * PTM_RATIO;
                  result.normal.x = normals[i].x;
                  result.normal.y = normals[i].y;
                  result.fraction = fractions[i];
                }
                continue;
              }
            }
            results.push({
              collider: collider,
              fixtureIndex: collider._getFixtureIndex(fixture),
              point: cc.v2(points[i].x * PTM_RATIO, points[i].y * PTM_RATIO),
              normal: cc.v2(normals[i]),
              fraction: fractions[i]
            });
          }
          return results;
        }
        return [];
      },
      syncPosition: function() {
        var bodies = this._bodies;
        for (var i = 0; i < bodies.length; i++) bodies[i].syncPosition();
      },
      syncRotation: function() {
        var bodies = this._bodies;
        for (var i = 0; i < bodies.length; i++) bodies[i].syncRotation();
      },
      attachDebugDrawToCamera: function(camera) {
        if (!this._debugDrawer) return;
        camera.addTarget(this._debugDrawer.getDrawer());
      },
      detachDebugDrawFromCamera: function(camera) {
        if (!this._debugDrawer) return;
        camera.removeTarget(this._debugDrawer.getDrawer());
      },
      _registerContactFixture: function(fixture) {
        this._contactListener.registerContactFixture(fixture);
      },
      _unregisterContactFixture: function(fixture) {
        this._contactListener.unregisterContactFixture(fixture);
      },
      _addBody: function(body, bodyDef) {
        var world = this._world;
        var node = body.node;
        if (!world || !node) return;
        body._b2Body = world.CreateBody(bodyDef);
        false;
        body._b2Body.body = body;
        this._utils.addB2Body(body._b2Body);
        this._bodies.push(body);
      },
      _removeBody: function(body) {
        var world = this._world;
        if (!world) return;
        false;
        body._b2Body.body = null;
        this._utils.removeB2Body(body._b2Body);
        world.DestroyBody(body._b2Body);
        body._b2Body = null;
        var index = this._bodies.indexOf(body);
        -1 !== index && this._bodies.splice(index, 1);
      },
      _initCallback: function() {
        if (!this._world) {
          cc.warn("Please init PhysicsManager first");
          return;
        }
        if (this._contactListener) return;
        var listener = new cc.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 cc.PhysicsAABBQueryCallback();
        this._raycastQueryCallback = new cc.PhysicsRayCastCallback();
      },
      _init: function() {
        this.enabled = true;
        this.debugDrawFlags = b2.Draw.e_shapeBit;
      },
      _getWorld: function() {
        return this._world;
      },
      _syncNode: function() {
        this._utils.syncNode();
        var bodies = this._bodies;
        for (var i = 0, l = bodies.length; i < l; i++) {
          var body = bodies[i];
          var node;
          false;
          body.type === BodyType.Animated && body.resetVelocity();
        }
      },
      _onSceneLaunched: function() {
        this._debugDrawer.AddDrawerToNode(cc.director.getScene()._sgNode);
      },
      _onBeginContact: function(b2contact) {
        var c = cc.PhysicsContact.get(b2contact);
        c.emit(ContactType.BEGIN_CONTACT);
      },
      _onEndContact: function(b2contact) {
        var c = b2contact._contact;
        if (!c) return;
        c.emit(ContactType.END_CONTACT);
        cc.PhysicsContact.put(b2contact);
      },
      _onPreSolve: function(b2contact) {
        var c = b2contact._contact;
        if (!c) return;
        c.emit(ContactType.PRE_SOLVE);
      },
      _onPostSolve: function(b2contact, impulse) {
        var c = b2contact._contact;
        if (!c) return;
        c._impulse = impulse;
        c.emit(ContactType.POST_SOLVE);
        c._impulse = null;
      }
    });
    cc.js.getset(PhysicsManager.prototype, "enabled", (function() {
      return this._enabled;
    }), (function(value) {
      if (value && !this._world) {
        var world = new b2.World(new b2.Vec2(0, -10));
        world.SetAllowSleeping(true);
        this._world = world;
        this._utils = new cc.PhysicsUtils();
        this._initCallback();
      }
      this._enabled = value;
    }));
    cc.js.getset(PhysicsManager.prototype, "debugDrawFlags", (function() {
      return this._debugDrawFlags;
    }), (function(value) {
      if (value && !this._debugDrawFlags) {
        if (!this._debugDrawer) {
          this._debugDrawer = new cc.PhysicsDebugDraw(PTM_RATIO);
          this._world.SetDebugDraw(this._debugDrawer);
        }
        var scene = cc.director.getScene();
        scene && this._debugDrawer.AddDrawerToNode(cc.director.getScene()._sgNode);
        cc.director.on(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this._onSceneLaunched, this);
      } else !value && this._debugDrawFlags && cc.director.off(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this._onSceneLaunched, this);
      this._debugDrawFlags = value;
      this._debugDrawer && this._debugDrawer.SetFlags(value);
    }));
    cc.js.getset(PhysicsManager.prototype, "gravity", (function() {
      if (this._world) {
        var g = this._world.GetGravity();
        return cc.v2(g.x * PTM_RATIO, g.y * PTM_RATIO);
      }
      return cc.v2();
    }), (function(value) {
      this._world && this._world.SetGravity(new b2.Vec2(value.x / PTM_RATIO, value.y / PTM_RATIO));
    }));
    cc.PhysicsManager = module.exports = PhysicsManager;
  }), {
    "./CCPhysicsTypes": 150
  } ],
  150: [ (function(require, module, exports) {
    var ContactType = {
      BEGIN_CONTACT: "begin-contact",
      END_CONTACT: "end-contact",
      PRE_SOLVE: "pre-solve",
      POST_SOLVE: "post-solve"
    };
    var BodyType = cc.Enum({
      Static: 0,
      Kinematic: 1,
      Dynamic: 2,
      Animated: 3
    });
    cc.RigidBodyType = BodyType;
    var RayCastType = cc.Enum({
      Closest: 0,
      Any: 1,
      AllClosest: 2,
      All: 3
    });
    cc.RayCastType = RayCastType;
    module.exports = {
      BodyType: BodyType,
      ContactType: ContactType,
      RayCastType: RayCastType,
      PTM_RATIO: 32,
      ANGLE_TO_PHYSICS_ANGLE: -Math.PI / 180,
      PHYSICS_ANGLE_TO_ANGLE: -180 / Math.PI
    };
  }), {} ],
  151: [ (function(require, module, exports) {
    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, lowerDist, upperDist;
      var p;
      var lowerInt = cc.v2();
      var upperInt = cc.v2();
      var lowerIndex = 0, upperIndex = 0;
      var lowerPoly, upperPoly;
      for (var i = 0; i < vertices.length; ++i) if (Reflex(i, vertices)) {
        lowerDist = upperDist = 1e8;
        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).div(2);
          lowerPoly = Copy(i, upperIndex, vertices);
          lowerPoly.push(sp);
          upperPoly = Copy(lowerIndex, i, vertices);
          upperPoly.push(sp);
        } else {
          var highestScore = 0, 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);
            Reflex(j, vertices) ? RightOn(At(j - 1, vertices), At(j, vertices), At(i, vertices)) && LeftOn(At(j + 1, vertices), At(j, vertices), At(i, vertices)) ? score += 3 : score += 2 : 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--) 0 == list[i].length && 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 = cc.v2();
        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 ("undefined" === typeof c) {
        var i = a, 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) {
      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 = cc.v2();
      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) < 1e-6) return false;
      ua /= denom;
      ub /= denom;
      if (0 < ua && ua < 1 && 0 < ub && 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) <= 1e-6;
    }
    function Area(a, b, c) {
      return a.x * (b.y - c.y) + b.x * (c.y - a.y) + c.x * (a.y - b.y);
    }
    module.exports = {
      ConvexPartition: ConvexPartition,
      ForceCounterClockWise: ForceCounterClockWise,
      IsCounterClockWise: IsCounterClockWise
    };
  }), {} ],
  152: [ (function(require, module, exports) {
    var PTM_RATIO = require("./CCPhysicsTypes").PTM_RATIO;
    var ANGLE_TO_PHYSICS_ANGLE = require("./CCPhysicsTypes").ANGLE_TO_PHYSICS_ANGLE;
    var PHYSICS_ANGLE_TO_ANGLE = require("./CCPhysicsTypes").PHYSICS_ANGLE_TO_ANGLE;
    var getWorldRotation = require("./utils").getWorldRotation;
    var BodyType = require("./CCPhysicsTypes").BodyType;
    var tempb2Vec21 = new b2.Vec2();
    var tempb2Vec22 = new b2.Vec2();
    var VEC2_ZERO = cc.Vec2.ZERO;
    var RigidBody = cc.Class({
      name: "cc.RigidBody",
      extends: cc.Component,
      editor: false,
      properties: {
        _type: BodyType.Dynamic,
        _allowSleep: true,
        _gravityScale: 1,
        _linearDamping: 0,
        _angularDamping: 0,
        _linearVelocity: cc.v2(0, 0),
        _angularVelocity: 0,
        _fixedRotation: false,
        enabled: {
          get: function() {
            return this._enabled;
          },
          set: function() {
            cc.warnID("8200");
          },
          visible: false,
          override: true
        },
        enabledContactListener: {
          default: false,
          tooltip: false
        },
        bullet: {
          default: false,
          tooltip: false
        },
        type: {
          type: BodyType,
          tooltip: false,
          get: function() {
            return this._type;
          },
          set: function(value) {
            this._type = value;
            this._b2Body && (value === BodyType.Animated ? this._b2Body.SetType(BodyType.Kinematic) : this._b2Body.SetType(value));
          }
        },
        allowSleep: {
          tooltip: false,
          get: function() {
            if (this._b2Body) return this._b2Body.IsSleepingAllowed();
            return this._allowSleep;
          },
          set: function(value) {
            this._allowSleep = value;
            this._b2Body && this._b2Body.SetSleepingAllowed(value);
          }
        },
        gravityScale: {
          tooltip: false,
          get: function() {
            return this._gravityScale;
          },
          set: function(value) {
            this._gravityScale = value;
            this._b2Body && this._b2Body.SetGravityScale(value);
          }
        },
        linearDamping: {
          tooltip: false,
          get: function() {
            return this._linearDamping;
          },
          set: function(value) {
            this._linearDamping = value;
            this._b2Body && this._b2Body.SetLinearDamping(this._linearDamping);
          }
        },
        angularDamping: {
          tooltip: false,
          get: function() {
            return this._angularDamping;
          },
          set: function(value) {
            this._angularDamping = value;
            this._b2Body && this._b2Body.SetAngularDamping(value);
          }
        },
        linearVelocity: {
          tooltip: false,
          type: cc.Vec2,
          get: function() {
            var lv = this._linearVelocity;
            if (this._b2Body) {
              var velocity = this._b2Body.GetLinearVelocity();
              lv.x = velocity.x * PTM_RATIO;
              lv.y = velocity.y * PTM_RATIO;
            }
            return lv;
          },
          set: function(value) {
            this._linearVelocity = value;
            var b2body = this._b2Body;
            if (b2body) {
              var temp = b2body.m_linearVelocity;
              temp.Set(value.x / PTM_RATIO, value.y / PTM_RATIO);
              b2body.SetLinearVelocity(temp);
            }
          }
        },
        angularVelocity: {
          tooltip: false,
          get: function() {
            if (this._b2Body) return this._b2Body.GetAngularVelocity() * PHYSICS_ANGLE_TO_ANGLE;
            return this._angularVelocity;
          },
          set: function(value) {
            this._angularVelocity = value;
            this._b2Body && this._b2Body.SetAngularVelocity(value * ANGLE_TO_PHYSICS_ANGLE);
          }
        },
        fixedRotation: {
          tooltip: false,
          get: function() {
            return this._fixedRotation;
          },
          set: function(value) {
            this._fixedRotation = value;
            this._b2Body && this._b2Body.SetFixedRotation(value);
          }
        },
        awake: {
          tooltip: false,
          get: function() {
            return !!this._b2Body && this._b2Body.IsAwake();
          },
          set: function(value) {
            this._b2Body && this._b2Body.SetAwake(value);
          }
        },
        active: {
          visible: false,
          get: function() {
            return !!this._b2Body && this._b2Body.IsActive();
          },
          set: function(value) {
            this._b2Body && this._b2Body.SetActive(value);
          }
        }
      },
      getLocalPoint: function(worldPoint, out) {
        out = out || cc.v2();
        if (this._b2Body) {
          tempb2Vec21.Set(worldPoint.x / PTM_RATIO, worldPoint.y / PTM_RATIO);
          var pos = this._b2Body.GetLocalPoint(tempb2Vec21);
          out.x = pos.x * PTM_RATIO;
          out.y = pos.y * PTM_RATIO;
        }
        return out;
      },
      getWorldPoint: function(localPoint, out) {
        out = out || cc.v2();
        if (this._b2Body) {
          tempb2Vec21.Set(localPoint.x / PTM_RATIO, localPoint.y / PTM_RATIO);
          var pos = this._b2Body.GetWorldPoint(tempb2Vec21);
          out.x = pos.x * PTM_RATIO;
          out.y = pos.y * PTM_RATIO;
        }
        return out;
      },
      getWorldVector: function(localVector, out) {
        out = out || cc.v2();
        if (this._b2Body) {
          tempb2Vec21.Set(localVector.x / PTM_RATIO, localVector.y / PTM_RATIO);
          var vector = this._b2Body.GetWorldVector(tempb2Vec21);
          out.x = vector.x * PTM_RATIO;
          out.y = vector.y * PTM_RATIO;
        }
        return out;
      },
      getLocalVector: function(worldVector, out) {
        out = out || cc.v2();
        if (this._b2Body) {
          tempb2Vec21.Set(worldVector.x / PTM_RATIO, worldVector.y / PTM_RATIO);
          var vector = this._b2Body.GetLocalVector(tempb2Vec21);
          out.x = vector.x * PTM_RATIO;
          out.y = vector.y * PTM_RATIO;
        }
        return out;
      },
      getWorldPosition: function(out) {
        out = out || cc.v2();
        if (this._b2Body) {
          var pos = this._b2Body.GetPosition();
          out.x = pos.x * PTM_RATIO;
          out.y = pos.y * PTM_RATIO;
        }
        return out;
      },
      getWorldRotation: function() {
        if (this._b2Body) return this._b2Body.GetAngle() * PHYSICS_ANGLE_TO_ANGLE;
        return 0;
      },
      getLocalCenter: function(out) {
        out = out || cc.v2();
        if (this._b2Body) {
          var pos = this._b2Body.GetLocalCenter();
          out.x = pos.x * PTM_RATIO;
          out.y = pos.y * PTM_RATIO;
        }
        return out;
      },
      getWorldCenter: function(out) {
        out = out || cc.v2();
        if (this._b2Body) {
          var pos = this._b2Body.GetWorldCenter();
          out.x = pos.x * PTM_RATIO;
          out.y = pos.y * PTM_RATIO;
        }
        return out;
      },
      getLinearVelocityFromWorldPoint: function(worldPoint, out) {
        out = out || cc.v2();
        if (this._b2Body) {
          tempb2Vec21.Set(worldPoint.x / PTM_RATIO, worldPoint.y / PTM_RATIO);
          var velocity = this._b2Body.GetLinearVelocityFromWorldPoint(tempb2Vec21);
          out.x = velocity.x * PTM_RATIO;
          out.y = velocity.y * PTM_RATIO;
        }
        return out;
      },
      getMass: function() {
        return this._b2Body ? this._b2Body.GetMass() : 0;
      },
      getInertia: function() {
        return this._b2Body ? this._b2Body.GetInertia() * PTM_RATIO * PTM_RATIO : 0;
      },
      getJointList: function() {
        if (!this._b2Body) return [];
        var joints;
        var i;
        false;
        var joints = [];
        var list = this._b2Body.GetJointList();
        if (!list) return [];
        joints.push(list.joint._joint);
        var prev = list.prev;
        while (prev) {
          joints.push(prev.joint._joint);
          prev = prev.prev;
        }
        var next = list.next;
        while (next) {
          joints.push(next.joint._joint);
          next = next.next;
        }
        return joints;
      },
      applyForce: function(force, point, wake) {
        if (this._b2Body) {
          tempb2Vec21.Set(force.x / PTM_RATIO, force.y / PTM_RATIO);
          tempb2Vec22.Set(point.x / PTM_RATIO, point.y / PTM_RATIO);
          this._b2Body.ApplyForce(tempb2Vec21, tempb2Vec22, wake);
        }
      },
      applyForceToCenter: function(force, wake) {
        if (this._b2Body) {
          tempb2Vec21.Set(force.x / PTM_RATIO, force.y / PTM_RATIO);
          this._b2Body.ApplyForceToCenter(tempb2Vec21, wake);
        }
      },
      applyTorque: function(torque, wake) {
        this._b2Body && this._b2Body.ApplyTorque(torque / PTM_RATIO, wake);
      },
      applyLinearImpulse: function(impulse, point, wake) {
        if (this._b2Body) {
          tempb2Vec21.Set(impulse.x / PTM_RATIO, impulse.y / PTM_RATIO);
          tempb2Vec22.Set(point.x / PTM_RATIO, point.y / PTM_RATIO);
          this._b2Body.ApplyLinearImpulse(tempb2Vec21, tempb2Vec22, wake);
        }
      },
      applyAngularImpulse: function(impulse, wake) {
        this._b2Body && this._b2Body.ApplyAngularImpulse(impulse / PTM_RATIO / PTM_RATIO, wake);
      },
      syncPosition: function(enableAnimated) {
        var b2body = this._b2Body;
        if (!b2body) return;
        var pos = this.node.convertToWorldSpaceAR(VEC2_ZERO);
        var temp;
        false;
        temp = this.type === BodyType.Animated ? b2body.GetLinearVelocity() : b2body.GetPosition();
        temp.x = pos.x / PTM_RATIO;
        temp.y = pos.y / PTM_RATIO;
        if (this.type === BodyType.Animated && enableAnimated) {
          var b2Pos = b2body.GetPosition();
          var timeStep = cc.game.config["frameRate"];
          temp.x = (temp.x - b2Pos.x) * timeStep;
          temp.y = (temp.y - b2Pos.y) * timeStep;
          b2body.SetAwake(true);
          b2body.SetLinearVelocity(temp);
        } else b2body.SetTransform(temp, b2body.GetAngle());
      },
      syncRotation: function(enableAnimated) {
        var b2body = this._b2Body;
        if (!b2body) return;
        var rotation = ANGLE_TO_PHYSICS_ANGLE * getWorldRotation(this.node);
        if (this.type === BodyType.Animated && enableAnimated) {
          var b2Rotation = b2body.GetAngle();
          var timeStep = cc.game.config["frameRate"];
          b2body.SetAwake(true);
          b2body.SetAngularVelocity((rotation - b2Rotation) * timeStep);
        } else b2body.SetTransform(b2body.GetPosition(), rotation);
      },
      resetVelocity: function() {
        var b2body = this._b2Body;
        if (!b2body) return;
        var temp = b2body.m_linearVelocity;
        temp.Set(0, 0);
        b2body.SetLinearVelocity(temp);
        b2body.SetAngularVelocity(0);
      },
      onEnable: function() {
        this._init();
      },
      onDisable: function() {
        this._destroy();
      },
      _registerNodeEvents: function() {
        var node = this.node;
        node.on("position-changed", this._onNodePositionChanged, this);
        node.on("rotation-changed", this._onNodeRotationChanged, this);
        node.on("scale-changed", this._onNodeScaleChanged, this);
      },
      _unregisterNodeEvents: function() {
        var node = this.node;
        node.off("position-changed", this._onNodePositionChanged, this);
        node.off("rotation-changed", this._onNodeRotationChanged, this);
        node.off("scale-changed", this._onNodeScaleChanged, this);
      },
      _onNodePositionChanged: function() {
        this.syncPosition(true);
      },
      _onNodeRotationChanged: function(event) {
        this.syncRotation(true);
      },
      _onNodeScaleChanged: function(event) {
        if (this._b2Body) {
          var colliders = this.getComponents(cc.PhysicsCollider);
          for (var i = 0; i < colliders.length; i++) colliders[i].apply();
        }
      },
      _init: function() {
        cc.director.getPhysicsManager().pushDelayEvent(this, "__init", []);
      },
      _destroy: function() {
        cc.director.getPhysicsManager().pushDelayEvent(this, "__destroy", []);
      },
      __init: function() {
        if (this._inited) return;
        this._registerNodeEvents();
        var bodyDef = new b2.BodyDef();
        this.type === BodyType.Animated ? bodyDef.type = BodyType.Kinematic : bodyDef.type = this.type;
        bodyDef.allowSleep = this.allowSleep;
        bodyDef.gravityScale = this.gravityScale;
        bodyDef.linearDamping = this.linearDamping;
        bodyDef.angularDamping = this.angularDamping;
        var linearVelocity = this.linearVelocity;
        bodyDef.linearVelocity = new b2.Vec2(linearVelocity.x / PTM_RATIO, linearVelocity.y / PTM_RATIO);
        bodyDef.angularVelocity = this.angularVelocity * ANGLE_TO_PHYSICS_ANGLE;
        bodyDef.fixedRotation = this.fixedRotation;
        bodyDef.bullet = this.bullet;
        var node = this.node;
        var pos = node.convertToWorldSpaceAR(VEC2_ZERO);
        bodyDef.position = new b2.Vec2(pos.x / PTM_RATIO, pos.y / PTM_RATIO);
        bodyDef.angle = -Math.PI / 180 * getWorldRotation(node);
        cc.director.getPhysicsManager()._addBody(this, bodyDef);
        this._inited = true;
      },
      __destroy: function() {
        if (!this._inited) return;
        cc.director.getPhysicsManager()._removeBody(this);
        this._unregisterNodeEvents();
        this._inited = false;
      },
      _getBody: function() {
        return this._b2Body;
      }
    });
    cc.RigidBody = module.exports = RigidBody;
  }), {
    "./CCPhysicsTypes": 150,
    "./utils": 173
  } ],
  153: [ (function(require, module, exports) {
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var PhysicsBoxCollider = cc.Class({
      name: "cc.PhysicsBoxCollider",
      extends: cc.PhysicsCollider,
      mixins: [ cc.Collider.Box ],
      editor: {
        menu: false,
        requireComponent: cc.RigidBody
      },
      _createShape: function(scale) {
        var scaleX = Math.abs(scale.x);
        var scaleY = Math.abs(scale.y);
        var width = this.size.width / 2 / PTM_RATIO * scaleX;
        var height = this.size.height / 2 / PTM_RATIO * scaleY;
        var offsetX = this.offset.x / PTM_RATIO * scaleX;
        var offsetY = this.offset.y / PTM_RATIO * scaleY;
        var shape = new b2.PolygonShape();
        shape.SetAsBox(width, height, new b2.Vec2(offsetX, offsetY), 0);
        return shape;
      }
    });
    cc.PhysicsBoxCollider = module.exports = PhysicsBoxCollider;
  }), {
    "../CCPhysicsTypes": 150
  } ],
  154: [ (function(require, module, exports) {
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var PhysicsChainCollider = cc.Class({
      name: "cc.PhysicsChainCollider",
      extends: cc.PhysicsCollider,
      editor: {
        menu: false,
        inspector: false,
        requireComponent: cc.RigidBody
      },
      properties: {
        loop: false,
        points: {
          default: function() {
            return [ cc.v2(-50, 0), cc.v2(50, 0) ];
          },
          type: [ cc.Vec2 ]
        },
        threshold: {
          default: 1,
          serializable: false,
          visible: false
        }
      },
      _createShape: function(scale) {
        var shape = new b2.ChainShape();
        var points = this.points;
        var vertices = [];
        for (var i = 0; i < points.length; i++) {
          var p = points[i];
          vertices.push(new b2.Vec2(p.x / PTM_RATIO * scale.x, p.y / PTM_RATIO * scale.y));
        }
        this.loop ? shape.CreateLoop(vertices, vertices.length) : shape.CreateChain(vertices, vertices.length);
        return shape;
      },
      resetInEditor: false,
      resetPointsByContour: false
    });
    cc.PhysicsChainCollider = module.exports = PhysicsChainCollider;
  }), {
    "../CCPhysicsTypes": 150
  } ],
  155: [ (function(require, module, exports) {
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var PhysicsCircleCollider = cc.Class({
      name: "cc.PhysicsCircleCollider",
      extends: cc.PhysicsCollider,
      mixins: [ cc.Collider.Circle ],
      editor: {
        menu: false,
        requireComponent: cc.RigidBody
      },
      _createShape: function(scale) {
        var scaleX = Math.abs(scale.x);
        var scaleY = Math.abs(scale.y);
        var offsetX = this.offset.x / PTM_RATIO * scaleX;
        var offsetY = this.offset.y / PTM_RATIO * scaleY;
        var shape = new b2.CircleShape();
        shape.m_radius = this.radius / PTM_RATIO * scaleX;
        shape.m_p = new b2.Vec2(offsetX, offsetY);
        return shape;
      }
    });
    cc.PhysicsCircleCollider = module.exports = PhysicsCircleCollider;
  }), {
    "../CCPhysicsTypes": 150
  } ],
  156: [ (function(require, module, exports) {
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var getWorldScale = require("../utils").getWorldScale;
    var PhysicsCollider = cc.Class({
      name: "cc.PhysicsCollider",
      extends: cc.Collider,
      ctor: function() {
        this._fixtures = [];
        this._shapes = [];
        this._inited = false;
        this._rect = cc.rect();
      },
      properties: {
        _density: 1,
        _sensor: false,
        _friction: .2,
        _restitution: 0,
        density: {
          tooltip: false,
          get: function() {
            return this._density;
          },
          set: function(value) {
            this._density = value;
          }
        },
        sensor: {
          tooltip: false,
          get: function() {
            return this._sensor;
          },
          set: function(value) {
            this._sensor = value;
          }
        },
        friction: {
          tooltip: false,
          get: function() {
            return this._friction;
          },
          set: function(value) {
            this._friction = value;
          }
        },
        restitution: {
          tooltip: false,
          get: function() {
            return this._restitution;
          },
          set: function(value) {
            this._restitution = value;
          }
        },
        body: {
          default: null,
          type: cc.RigidBody,
          visible: false
        }
      },
      onDisable: function() {
        this._destroy();
      },
      onEnable: function() {
        this._init();
      },
      start: function() {
        this._init();
      },
      _getFixtureIndex: function(fixture) {
        return this._fixtures.indexOf(fixture);
      },
      _init: function() {
        cc.director.getPhysicsManager().pushDelayEvent(this, "__init", []);
      },
      _destroy: function() {
        cc.director.getPhysicsManager().pushDelayEvent(this, "__destroy", []);
      },
      __init: function() {
        if (this._inited) return;
        var body = this.body || this.getComponent(cc.RigidBody);
        if (!body) return;
        var innerBody = body._getBody();
        if (!innerBody) return;
        var node = body.node;
        var scale = getWorldScale(node);
        var shapes = 0 === scale.x && 0 === scale.y ? [] : this._createShape(scale);
        shapes instanceof Array || (shapes = [ shapes ]);
        var categoryBits = 1 << node.groupIndex;
        var maskBits = 0;
        var bits = cc.game.collisionMatrix[node.groupIndex];
        for (var i = 0; i < bits.length; i++) {
          if (!bits[i]) continue;
          maskBits |= 1 << i;
        }
        var filter = {
          categoryBits: categoryBits,
          maskBits: maskBits,
          groupIndex: 0
        };
        var manager = cc.director.getPhysicsManager();
        for (var _i = 0; _i < shapes.length; _i++) {
          var shape = shapes[_i];
          var fixDef = new b2.FixtureDef();
          fixDef.density = this.density;
          fixDef.isSensor = this.sensor;
          fixDef.friction = this.friction;
          fixDef.restitution = this.restitution;
          fixDef.shape = shape;
          fixDef.filter = filter;
          var fixture = innerBody.CreateFixture(fixDef);
          fixture.collider = this;
          body.enabledContactListener && manager._registerContactFixture(fixture);
          this._shapes.push(shape);
          this._fixtures.push(fixture);
        }
        this.body = body;
        this._inited = true;
      },
      __destroy: function() {
        if (!this._inited) return;
        var fixtures = this._fixtures;
        var body = this.body._getBody();
        var manager = cc.director.getPhysicsManager();
        for (var i = fixtures.length - 1; i >= 0; i--) {
          var fixture = fixtures[i];
          fixture.collider = null;
          false;
          manager._unregisterContactFixture(fixture);
          body && body.DestroyFixture(fixture);
        }
        this.body = null;
        this._fixtures.length = 0;
        this._shapes.length = 0;
        this._inited = false;
      },
      _createShape: function() {},
      apply: function() {
        this._destroy();
        this._init();
      },
      getAABB: function() {
        var MAX = 1e7;
        var minX = MAX, minY = MAX;
        var maxX = -MAX, 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);
            aabb.lowerBound.x < minX && (minX = aabb.lowerBound.x);
            aabb.lowerBound.y < minY && (minY = aabb.lowerBound.y);
            aabb.upperBound.x > maxX && (maxX = aabb.upperBound.x);
            aabb.upperBound.y > maxY && (maxY = aabb.upperBound.y);
          }
        }
        minX *= PTM_RATIO;
        minY *= PTM_RATIO;
        maxX *= PTM_RATIO;
        maxY *= PTM_RATIO;
        var r = this._rect;
        r.x = minX;
        r.y = minY;
        r.width = maxX - minX;
        r.height = maxY - minY;
        return r;
      }
    });
    cc.PhysicsCollider = module.exports = PhysicsCollider;
  }), {
    "../CCPhysicsTypes": 150,
    "../utils": 173
  } ],
  157: [ (function(require, module, exports) {
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var PolygonSeparator = require("../CCPolygonSeparator");
    var PhysicsPolygonCollider = cc.Class({
      name: "cc.PhysicsPolygonCollider",
      extends: cc.PhysicsCollider,
      mixins: [ cc.Collider.Polygon ],
      editor: {
        menu: false,
        inspector: false,
        requireComponent: cc.RigidBody
      },
      _createShape: function(scale) {
        var shapes = [];
        var points = this.points;
        points.length > 0 && points[0].equals(points[points.length - 1]) && (points.length -= 1);
        var polys = PolygonSeparator.ConvexPartition(points);
        var offset = this.offset;
        for (var i = 0; i < polys.length; i++) {
          var poly = polys[i];
          var shape = null, vertices = [];
          var firstVertice = null;
          for (var j = 0, l = poly.length; j < l; j++) {
            shape || (shape = new b2.PolygonShape());
            var p = poly[j];
            var x = (p.x + offset.x) / PTM_RATIO * scale.x;
            var y = (p.y + offset.y) / PTM_RATIO * scale.y;
            var v = new b2.Vec2(x, y);
            vertices.push(v);
            firstVertice || (firstVertice = v);
            if (vertices.length === b2.maxPolygonVertices) {
              shape.Set(vertices, vertices.length);
              shapes.push(shape);
              shape = null;
              j < l - 1 && (vertices = [ firstVertice, vertices[vertices.length - 1] ]);
            }
          }
          if (shape) {
            shape.Set(vertices, vertices.length);
            shapes.push(shape);
          }
        }
        return shapes;
      }
    });
    cc.PhysicsPolygonCollider = module.exports = PhysicsPolygonCollider;
  }), {
    "../CCPhysicsTypes": 150,
    "../CCPolygonSeparator": 151
  } ],
  158: [ (function(require, module, exports) {
    true;
    window.b2 = require("../../../external/box2d/box2d");
    require("./CCPhysicsManager");
    require("./CCRigidBody");
    require("./CCPhysicsContact");
    require("./collider/CCPhysicsCollider");
    require("./collider/CCPhysicsChainCollider");
    require("./collider/CCPhysicsCircleCollider");
    require("./collider/CCPhysicsBoxCollider");
    require("./collider/CCPhysicsPolygonCollider");
    require("./joint/CCJoint");
    require("./joint/CCDistanceJoint");
    require("./joint/CCRevoluteJoint");
    require("./joint/CCMouseJoint");
    require("./joint/CCMotorJoint");
    require("./joint/CCPrismaticJoint");
    require("./joint/CCWeldJoint");
    require("./joint/CCWheelJoint");
    require("./joint/CCRopeJoint");
    true;
    require("./platform/CCPhysicsDebugDraw");
    require("./platform/CCPhysicsUtils");
    require("./platform/CCPhysicsContactListner");
    require("./platform/CCPhysicsAABBQueryCallback");
    require("./platform/CCPhysicsRayCastCallback");
  }), {
    "../../../external/box2d/box2d": 309,
    "./CCPhysicsContact": 148,
    "./CCPhysicsManager": 149,
    "./CCRigidBody": 152,
    "./collider/CCPhysicsBoxCollider": 153,
    "./collider/CCPhysicsChainCollider": 154,
    "./collider/CCPhysicsCircleCollider": 155,
    "./collider/CCPhysicsCollider": 156,
    "./collider/CCPhysicsPolygonCollider": 157,
    "./joint/CCDistanceJoint": 159,
    "./joint/CCJoint": 160,
    "./joint/CCMotorJoint": 161,
    "./joint/CCMouseJoint": 162,
    "./joint/CCPrismaticJoint": 163,
    "./joint/CCRevoluteJoint": 164,
    "./joint/CCRopeJoint": 165,
    "./joint/CCWeldJoint": 166,
    "./joint/CCWheelJoint": 167,
    "./platform/CCPhysicsAABBQueryCallback": 168,
    "./platform/CCPhysicsContactListner": 169,
    "./platform/CCPhysicsDebugDraw": 170,
    "./platform/CCPhysicsRayCastCallback": 171,
    "./platform/CCPhysicsUtils": 172
  } ],
  159: [ (function(require, module, exports) {
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var DistanceJoint = cc.Class({
      name: "cc.DistanceJoint",
      extends: cc.Joint,
      editor: false,
      properties: {
        _distance: 1,
        _frequency: 0,
        _dampingRatio: 0,
        distance: {
          tooltip: false,
          get: function() {
            return this._distance;
          },
          set: function(value) {
            this._distance = value;
            this._joint && this._joint.SetLength(value);
          }
        },
        frequency: {
          tooltip: false,
          get: function() {
            return this._frequency;
          },
          set: function(value) {
            this._frequency = value;
            this._joint && this._joint.SetFrequency(value);
          }
        },
        dampingRatio: {
          tooltip: false,
          get: function() {
            return this._dampingRatio;
          },
          set: function(value) {
            this._dampingRatio = value;
            this._joint && this._joint.SetDampingRatio(value);
          }
        }
      },
      _createJointDef: function() {
        var def = new b2.DistanceJointDef();
        def.localAnchorA = new b2.Vec2(this.anchor.x / PTM_RATIO, this.anchor.y / PTM_RATIO);
        def.localAnchorB = new b2.Vec2(this.connectedAnchor.x / PTM_RATIO, this.connectedAnchor.y / PTM_RATIO);
        def.length = this.distance / PTM_RATIO;
        def.dampingRatio = this.dampingRatio;
        def.frequencyHz = this.frequency;
        return def;
      }
    });
    cc.DistanceJoint = module.exports = DistanceJoint;
  }), {
    "../CCPhysicsTypes": 150
  } ],
  160: [ (function(require, module, exports) {
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var Joint = cc.Class({
      name: "cc.Joint",
      extends: cc.Component,
      editor: {
        requireComponent: cc.RigidBody
      },
      properties: {
        anchor: {
          default: cc.v2(0, 0),
          tooltip: false
        },
        connectedAnchor: {
          default: cc.v2(0, 0),
          tooltip: false
        },
        connectedBody: {
          default: null,
          type: cc.RigidBody,
          tooltip: false
        },
        collideConnected: {
          default: false,
          tooltip: false
        }
      },
      onDisable: function() {
        this._destroy();
      },
      onEnable: function() {
        this._init();
      },
      start: function() {
        this._init();
      },
      apply: function() {
        this._destroy();
        this._init();
      },
      getWorldAnchor: function() {
        if (this._joint) {
          var anchor = this._joint.GetAnchorA();
          return cc.v2(anchor.x * PTM_RATIO, anchor.y * PTM_RATIO);
        }
        return cc.Vec2.ZERO;
      },
      getWorldConnectedAnchor: function() {
        if (this._joint) {
          var anchor = this._joint.GetAnchorB();
          return cc.v2(anchor.x * PTM_RATIO, anchor.y * PTM_RATIO);
        }
        return cc.Vec2.ZERO;
      },
      getReactionForce: function(timeStep) {
        if (this._joint) return this._joint.GetReactionForce(timeStep);
        return 0;
      },
      getReactionTorque: function(timeStep) {
        if (this._joint) return this._joint.GetReactionTorque(timeStep);
        return 0;
      },
      _init: function() {
        cc.director.getPhysicsManager().pushDelayEvent(this, "__init", []);
      },
      _destroy: function() {
        cc.director.getPhysicsManager().pushDelayEvent(this, "__destroy", []);
      },
      __init: function() {
        if (this._inited) return;
        this.body = this.getComponent(cc.RigidBody);
        if (this._isValid()) {
          var world = cc.director.getPhysicsManager()._getWorld();
          var def = this._createJointDef();
          if (!def) return;
          def.bodyA = this.body._getBody();
          def.bodyB = this.connectedBody._getBody();
          def.collideConnected = this.collideConnected;
          this._joint = world.CreateJoint(def);
          this._joint && (this._joint._joint = this);
          this._inited = true;
        }
      },
      __destroy: function() {
        if (!this._inited) return;
        this._isValid() && cc.director.getPhysicsManager()._getWorld().DestroyJoint(this._joint);
        this._joint && (this._joint._joint = null);
        this._joint = null;
        this._inited = false;
      },
      _createJointDef: function() {
        return null;
      },
      _isValid: function() {
        return this.body && this.body._getBody() && this.connectedBody && this.connectedBody._getBody();
      }
    });
    cc.Joint = module.exports = Joint;
  }), {
    "../CCPhysicsTypes": 150
  } ],
  161: [ (function(require, module, exports) {
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var ANGLE_TO_PHYSICS_ANGLE = require("../CCPhysicsTypes").ANGLE_TO_PHYSICS_ANGLE;
    var MotorJoint = cc.Class({
      name: "cc.MotorJoint",
      extends: cc.Joint,
      editor: false,
      properties: {
        _linearOffset: cc.v2(0, 0),
        _angularOffset: 0,
        _maxForce: 1,
        _maxTorque: 1,
        _correctionFactor: .3,
        anchor: {
          tooltip: false,
          default: cc.v2(0, 0),
          override: true,
          visible: false
        },
        connectedAnchor: {
          tooltip: false,
          default: cc.v2(0, 0),
          override: true,
          visible: false
        },
        linearOffset: {
          tooltip: false,
          get: function() {
            return this._linearOffset;
          },
          set: function(value) {
            this._linearOffset = value;
            this._joint && this._joint.SetLinearOffset(new b2.Vec2(value.x / PTM_RATIO, value.y / PTM_RATIO));
          }
        },
        angularOffset: {
          tooltip: false,
          get: function() {
            return this._angularOffset;
          },
          set: function(value) {
            this._angularOffset = value;
            this._joint && this._joint.SetAngularOffset(value);
          }
        },
        maxForce: {
          tooltip: false,
          get: function() {
            return this._maxForce;
          },
          set: function(value) {
            this._maxForce = value;
            this._joint && this._joint.SetMaxForce(value);
          }
        },
        maxTorque: {
          tooltip: false,
          get: function() {
            return this._maxTorque;
          },
          set: function(value) {
            this._maxTorque = value;
            this._joint && this._joint.SetMaxTorque(value);
          }
        },
        correctionFactor: {
          tooltip: false,
          get: function() {
            return this._correctionFactor;
          },
          set: function(value) {
            this._correctionFactor = value;
            this._joint && this._joint.SetCorrectionFactor(value);
          }
        }
      },
      _createJointDef: function() {
        var def = new b2.MotorJointDef();
        def.linearOffset = new b2.Vec2(this.linearOffset.x / PTM_RATIO, this.linearOffset.y / PTM_RATIO);
        def.angularOffset = this.angularOffset * ANGLE_TO_PHYSICS_ANGLE;
        def.maxForce = this.maxForce;
        def.maxTorque = this.maxTorque;
        def.correctionFactor = this.correctionFactor;
        return def;
      }
    });
    cc.MotorJoint = module.exports = MotorJoint;
  }), {
    "../CCPhysicsTypes": 150
  } ],
  162: [ (function(require, module, exports) {
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var tempB2Vec2 = new b2.Vec2();
    var MouseJoint = cc.Class({
      name: "cc.MouseJoint",
      extends: cc.Joint,
      editor: false,
      properties: {
        _target: 1,
        _frequency: 5,
        _dampingRatio: .7,
        _maxForce: 0,
        connectedBody: {
          default: null,
          type: cc.RigidBody,
          visible: false,
          override: true
        },
        collideConnected: {
          default: true,
          visible: false,
          override: true
        },
        anchor: {
          tooltip: false,
          default: cc.v2(0, 0),
          override: true,
          visible: false
        },
        connectedAnchor: {
          tooltip: false,
          default: cc.v2(0, 0),
          override: true,
          visible: false
        },
        mouseRegion: {
          tooltip: false,
          default: null,
          type: cc.Node
        },
        target: {
          tooltip: false,
          visible: false,
          get: function() {
            return this._target;
          },
          set: function(value) {
            this._target = value;
            if (this._joint) {
              tempB2Vec2.x = value.x / PTM_RATIO;
              tempB2Vec2.y = value.y / PTM_RATIO;
              this._joint.SetTarget(tempB2Vec2);
            }
          }
        },
        frequency: {
          tooltip: false,
          get: function() {
            return this._frequency;
          },
          set: function(value) {
            this._frequency = value;
            this._joint && this._joint.SetFrequency(value);
          }
        },
        dampingRatio: {
          tooltip: false,
          get: function() {
            return this._dampingRatio;
          },
          set: function(value) {
            this._dampingRatio = value;
            this._joint && this._joint.SetDampingRatio(value);
          }
        },
        maxForce: {
          tooltip: false,
          visible: false,
          get: function() {
            return this._maxForce;
          },
          set: function(value) {
            this._maxForce = value;
            this._joint && this._joint.SetMaxForce(value);
          }
        }
      },
      onLoad: function() {
        var mouseRegion = this.mouseRegion || this.node;
        mouseRegion.on(cc.Node.EventType.TOUCH_START, this.onTouchBegan, this);
        mouseRegion.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        mouseRegion.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
      },
      onEnable: function() {},
      start: function() {},
      onTouchBegan: function(event) {
        var manager = cc.director.getPhysicsManager();
        var target = this._pressPoint = event.touch.getLocation();
        cc.Camera && cc.Camera.main && (target = cc.Camera.main.getCameraToWorldPoint(target));
        var collider = manager.testPoint(target);
        if (!collider) return;
        var body = this.connectedBody = collider.body;
        body.awake = true;
        this.maxForce = 1e3 * this.connectedBody.getMass();
        this.target = target;
        this._init();
      },
      onTouchMove: function(event) {
        this._pressPoint = event.touch.getLocation();
      },
      onTouchEnd: function(event) {
        this._destroy();
        this._pressPoint = null;
      },
      _createJointDef: function() {
        var def = new b2.MouseJointDef();
        tempB2Vec2.x = this.target.x / PTM_RATIO;
        tempB2Vec2.y = this.target.y / PTM_RATIO;
        def.target = tempB2Vec2;
        def.maxForce = this.maxForce;
        def.dampingRatio = this.dampingRatio;
        def.frequencyHz = this.frequency;
        return def;
      },
      update: function() {
        if (!this._pressPoint || !this._isValid()) return;
        cc.Camera && cc.Camera.main ? this.target = cc.Camera.main.getCameraToWorldPoint(this._pressPoint) : this.target = this._pressPoint;
      }
    });
    cc.MouseJoint = module.exports = MouseJoint;
  }), {
    "../CCPhysicsTypes": 150
  } ],
  163: [ (function(require, module, exports) {
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var ANGLE_TO_PHYSICS_ANGLE = require("../CCPhysicsTypes").ANGLE_TO_PHYSICS_ANGLE;
    var PrismaticJoint = cc.Class({
      name: "cc.PrismaticJoint",
      extends: cc.Joint,
      editor: false,
      properties: {
        localAxisA: {
          default: cc.v2(1, 0),
          tooltip: false
        },
        referenceAngle: {
          default: 0,
          tooltip: false
        },
        enableLimit: {
          default: false,
          tooltip: false
        },
        enableMotor: {
          default: false,
          tooltip: false
        },
        lowerLimit: {
          default: 0,
          tooltip: false
        },
        upperLimit: {
          default: 0,
          tooltip: false
        },
        _maxMotorForce: 0,
        _motorSpeed: 0,
        maxMotorForce: {
          tooltip: false,
          get: function() {
            return this._maxMotorForce;
          },
          set: function(value) {
            this._maxMotorForce = value;
            this._joint && this._joint.SetMaxMotorForce(value);
          }
        },
        motorSpeed: {
          tooltip: false,
          get: function() {
            return this._motorSpeed;
          },
          set: function(value) {
            this._motorSpeed = value;
            this._joint && this._joint.SetMotorSpeed(value);
          }
        }
      },
      _createJointDef: function() {
        var def = new b2.PrismaticJointDef();
        def.localAnchorA = new b2.Vec2(this.anchor.x / PTM_RATIO, this.anchor.y / PTM_RATIO);
        def.localAnchorB = new b2.Vec2(this.connectedAnchor.x / PTM_RATIO, this.connectedAnchor.y / PTM_RATIO);
        def.localAxisA = new b2.Vec2(this.localAxisA.x, this.localAxisA.y);
        def.referenceAngle = this.referenceAngle * ANGLE_TO_PHYSICS_ANGLE;
        def.enableLimit = this.enableLimit;
        def.lowerTranslation = this.lowerLimit / PTM_RATIO;
        def.upperTranslation = this.upperLimit / PTM_RATIO;
        def.enableMotor = this.enableMotor;
        def.maxMotorForce = this.maxMotorForce;
        def.motorSpeed = this.motorSpeed;
        return def;
      }
    });
    cc.PrismaticJoint = module.exports = PrismaticJoint;
  }), {
    "../CCPhysicsTypes": 150
  } ],
  164: [ (function(require, module, exports) {
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var ANGLE_TO_PHYSICS_ANGLE = require("../CCPhysicsTypes").ANGLE_TO_PHYSICS_ANGLE;
    var PHYSICS_ANGLE_TO_ANGLE = require("../CCPhysicsTypes").PHYSICS_ANGLE_TO_ANGLE;
    var RevoluteJoint = cc.Class({
      name: "cc.RevoluteJoint",
      extends: cc.Joint,
      editor: false,
      properties: {
        _maxMotorTorque: 0,
        _motorSpeed: 0,
        _enableLimit: false,
        _enableMotor: false,
        referenceAngle: {
          default: 0,
          tooltip: false
        },
        lowerAngle: {
          default: 0,
          tooltip: false
        },
        upperAngle: {
          default: 0,
          tooltip: false
        },
        maxMotorTorque: {
          tooltip: false,
          get: function() {
            return this._maxMotorTorque;
          },
          set: function(value) {
            this._maxMotorTorque = value;
            this._joint && this._joint.SetMaxMotorTorque(value);
          }
        },
        motorSpeed: {
          tooltip: false,
          get: function() {
            return this._motorSpeed;
          },
          set: function(value) {
            this._motorSpeed = value;
            this._joint && this._joint.SetMotorSpeed(value * ANGLE_TO_PHYSICS_ANGLE);
          }
        },
        enableLimit: {
          tooltip: false,
          get: function() {
            return this._enableLimit;
          },
          set: function(value) {
            this._enableLimit = value;
            this._joint && this._joint.EnableLimit(value);
          }
        },
        enableMotor: {
          tooltip: false,
          get: function() {
            return this._enableMotor;
          },
          set: function(value) {
            this._enableMotor = value;
            this._joint && this._joint.EnableMotor(value);
          }
        }
      },
      getJointAngle: function() {
        if (this._joint) return this._joint.GetJointAngle() * PHYSICS_ANGLE_TO_ANGLE;
        return 0;
      },
      _createJointDef: function() {
        var def = new b2.RevoluteJointDef();
        def.localAnchorA = new b2.Vec2(this.anchor.x / PTM_RATIO, this.anchor.y / PTM_RATIO);
        def.localAnchorB = new b2.Vec2(this.connectedAnchor.x / PTM_RATIO, this.connectedAnchor.y / PTM_RATIO);
        def.lowerAngle = (this.upperAngle + 90) * ANGLE_TO_PHYSICS_ANGLE;
        def.upperAngle = (this.lowerAngle + 90) * ANGLE_TO_PHYSICS_ANGLE;
        def.maxMotorTorque = this.maxMotorTorque;
        def.motorSpeed = this.motorSpeed * ANGLE_TO_PHYSICS_ANGLE;
        def.enableLimit = this.enableLimit;
        def.enableMotor = this.enableMotor;
        def.referenceAngle = this.referenceAngle * ANGLE_TO_PHYSICS_ANGLE;
        return def;
      }
    });
    cc.RevoluteJoint = module.exports = RevoluteJoint;
  }), {
    "../CCPhysicsTypes": 150
  } ],
  165: [ (function(require, module, exports) {
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var RopeJoint = cc.Class({
      name: "cc.RopeJoint",
      extends: cc.Joint,
      editor: false,
      properties: {
        _maxLength: 1,
        maxLength: {
          tooltip: false,
          get: function() {
            return this._maxLength;
          },
          set: function(value) {
            this._maxLength = value;
            this._joint && this._joint.SetMaxLength(value);
          }
        }
      },
      _createJointDef: function() {
        var def = new b2.RopeJointDef();
        def.localAnchorA = new b2.Vec2(this.anchor.x / PTM_RATIO, this.anchor.y / PTM_RATIO);
        def.localAnchorB = new b2.Vec2(this.connectedAnchor.x / PTM_RATIO, this.connectedAnchor.y / PTM_RATIO);
        def.maxLength = this.maxLength / PTM_RATIO;
        return def;
      }
    });
    cc.RopeJoint = module.exports = RopeJoint;
  }), {
    "../CCPhysicsTypes": 150
  } ],
  166: [ (function(require, module, exports) {
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var ANGLE_TO_PHYSICS_ANGLE = require("../CCPhysicsTypes").ANGLE_TO_PHYSICS_ANGLE;
    var WeldJoint = cc.Class({
      name: "cc.WeldJoint",
      extends: cc.Joint,
      editor: false,
      properties: {
        referenceAngle: {
          default: 0,
          tooltip: false
        },
        _frequency: 0,
        _dampingRatio: 0,
        frequency: {
          tooltip: false,
          get: function() {
            return this._frequency;
          },
          set: function(value) {
            this._frequency = value;
            this._joint && this._joint.SetFrequency(value);
          }
        },
        dampingRatio: {
          tooltip: false,
          get: function() {
            return this._dampingRatio;
          },
          set: function(value) {
            this._dampingRatio = value;
            this._joint && this._joint.SetDampingRatio(value);
          }
        }
      },
      _createJointDef: function() {
        var def = new b2.WeldJointDef();
        def.localAnchorA = new b2.Vec2(this.anchor.x / PTM_RATIO, this.anchor.y / PTM_RATIO);
        def.localAnchorB = new b2.Vec2(this.connectedAnchor.x / PTM_RATIO, this.connectedAnchor.y / PTM_RATIO);
        def.referenceAngle = this.referenceAngle * ANGLE_TO_PHYSICS_ANGLE;
        def.frequencyHz = this.frequency;
        def.dampingRatio = this.dampingRatio;
        return def;
      }
    });
    cc.WeldJoint = module.exports = WeldJoint;
  }), {
    "../CCPhysicsTypes": 150
  } ],
  167: [ (function(require, module, exports) {
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var ANGLE_TO_PHYSICS_ANGLE = require("../CCPhysicsTypes").ANGLE_TO_PHYSICS_ANGLE;
    var WheelJoint = cc.Class({
      name: "cc.WheelJoint",
      extends: cc.Joint,
      editor: false,
      properties: {
        _maxMotorTorque: 0,
        _motorSpeed: 0,
        _enableMotor: false,
        _frequency: 2,
        _dampingRatio: .7,
        localAxisA: {
          default: cc.v2(1, 0),
          tooltip: false
        },
        maxMotorTorque: {
          tooltip: false,
          get: function() {
            return this._maxMotorTorque;
          },
          set: function(value) {
            this._maxMotorTorque = value;
            this._joint && this._joint.SetMaxMotorTorque(value);
          }
        },
        motorSpeed: {
          tooltip: false,
          get: function() {
            return this._motorSpeed;
          },
          set: function(value) {
            this._motorSpeed = value;
            this._joint && this._joint.SetMotorSpeed(value * ANGLE_TO_PHYSICS_ANGLE);
          }
        },
        enableMotor: {
          tooltip: false,
          get: function() {
            return this._enableMotor;
          },
          set: function(value) {
            this._enableMotor = value;
            this._joint && this._joint.EnableMotor(value);
          }
        },
        frequency: {
          tooltip: false,
          get: function() {
            return this._frequency;
          },
          set: function(value) {
            this._frequency = value;
            this._joint && this._joint.SetFrequency(value);
          }
        },
        dampingRatio: {
          tooltip: false,
          get: function() {
            return this._dampingRatio;
          },
          set: function(value) {
            this._dampingRatio = value;
            this._joint && this._joint.SetDampingRatio(value);
          }
        }
      },
      _createJointDef: function() {
        var def = new b2.WheelJointDef();
        def.localAnchorA = new b2.Vec2(this.anchor.x / PTM_RATIO, this.anchor.y / PTM_RATIO);
        def.localAnchorB = new b2.Vec2(this.connectedAnchor.x / PTM_RATIO, this.connectedAnchor.y / PTM_RATIO);
        def.localAxisA = new b2.Vec2(this.localAxisA.x, this.localAxisA.y);
        def.maxMotorTorque = this.maxMotorTorque;
        def.motorSpeed = this.motorSpeed * ANGLE_TO_PHYSICS_ANGLE;
        def.enableMotor = this.enableMotor;
        def.dampingRatio = this.dampingRatio;
        def.frequencyHz = this.frequency;
        return def;
      }
    });
    cc.WheelJoint = module.exports = WheelJoint;
  }), {
    "../CCPhysicsTypes": 150
  } ],
  168: [ (function(require, module, exports) {
    function PhysicsAABBQueryCallback() {
      this._point = new b2.Vec2();
      this._isPoint = false;
      this._fixtures = [];
    }
    PhysicsAABBQueryCallback.prototype.init = function(point) {
      if (point) {
        this._isPoint = true;
        this._point.x = point.x;
        this._point.y = point.y;
      } else this._isPoint = false;
      this._fixtures.length = 0;
    };
    PhysicsAABBQueryCallback.prototype.ReportFixture = function(fixture) {
      var body = fixture.GetBody();
      if (body.GetType() === b2.Body.b2_dynamicBody) if (this._isPoint) {
        if (fixture.TestPoint(this._point)) {
          this._fixtures.push(fixture);
          return false;
        }
      } else this._fixtures.push(fixture);
      return true;
    };
    PhysicsAABBQueryCallback.prototype.getFixture = function() {
      return this._fixtures[0];
    };
    PhysicsAABBQueryCallback.prototype.getFixtures = function() {
      return this._fixtures;
    };
    cc.PhysicsAABBQueryCallback = module.exports = PhysicsAABBQueryCallback;
  }), {} ],
  169: [ (function(require, module, exports) {
    function PhysicsContactListener() {
      this._contactFixtures = [];
    }
    PhysicsContactListener.prototype.setBeginContact = function(cb) {
      this._BeginContact = cb;
    };
    PhysicsContactListener.prototype.setEndContact = function(cb) {
      this._EndContact = cb;
    };
    PhysicsContactListener.prototype.setPreSolve = function(cb) {
      this._PreSolve = cb;
    };
    PhysicsContactListener.prototype.setPostSolve = function(cb) {
      this._PostSolve = cb;
    };
    PhysicsContactListener.prototype.BeginContact = function(contact) {
      if (!this._BeginContact) return;
      var fixtureA = contact.GetFixtureA();
      var fixtureB = contact.GetFixtureB();
      var fixtures = this._contactFixtures;
      contact._shouldReport = false;
      if (-1 !== fixtures.indexOf(fixtureA) || -1 !== fixtures.indexOf(fixtureB)) {
        contact._shouldReport = true;
        this._BeginContact(contact);
      }
    };
    PhysicsContactListener.prototype.EndContact = function(contact) {
      if (this._EndContact && contact._shouldReport) {
        contact._shouldReport = false;
        this._EndContact(contact);
      }
    };
    PhysicsContactListener.prototype.PreSolve = function(contact, oldManifold) {
      this._PreSolve && contact._shouldReport && this._PreSolve(contact, oldManifold);
    };
    PhysicsContactListener.prototype.PostSolve = function(contact, impulse) {
      this._PostSolve && contact._shouldReport && this._PostSolve(contact, impulse);
    };
    PhysicsContactListener.prototype.registerContactFixture = function(fixture) {
      this._contactFixtures.push(fixture);
    };
    PhysicsContactListener.prototype.unregisterContactFixture = function(fixture) {
      cc.js.array.remove(this._contactFixtures, fixture);
    };
    cc.PhysicsContactListener = module.exports = PhysicsContactListener;
  }), {} ],
  170: [ (function(require, module, exports) {
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var PhysicsDebugDraw = cc.Class({
      name: "cc.PhysicsDebugDraw",
      mixins: [ b2.Draw ],
      ctor: function() {
        this._drawer = new _ccsg.GraphicsNode();
        this._drawer.retain();
      },
      getDrawer: function() {
        return this._drawer;
      },
      AddDrawerToNode: function(node) {
        this._drawer.removeFromParent();
        node.addChild(this._drawer);
      },
      ClearDraw: function() {
        this._drawer.clear();
      },
      _DrawPolygon: function(vertices, vertexCount) {
        var drawer = this._drawer;
        for (var i = 0; i < vertexCount; i++) 0 === i ? drawer.moveTo(vertices[i].x * PTM_RATIO, vertices[i].y * PTM_RATIO) : drawer.lineTo(vertices[i].x * PTM_RATIO, vertices[i].y * PTM_RATIO);
        drawer.close();
      },
      DrawPolygon: function(vertices, vertexCount, color) {
        this._applyStrokeColor(color);
        this._DrawPolygon(vertices, vertexCount);
        this._drawer.stroke();
      },
      DrawSolidPolygon: function(vertices, vertexCount, color) {
        this._applyFillColor(color);
        this._DrawPolygon(vertices, vertexCount);
        this._drawer.fill();
        this._drawer.stroke();
      },
      _DrawCircle: function(center, radius) {
        this._drawer.circle(center.x * PTM_RATIO, center.y * PTM_RATIO, radius * PTM_RATIO);
      },
      DrawCircle: function(center, radius, color) {
        this._applyStrokeColor(color);
        this._DrawCircle(center, radius);
        this._drawer.stroke();
      },
      DrawSolidCircle: function(center, radius, axis, color) {
        this._applyFillColor(color);
        this._DrawCircle(center, radius);
        this._drawer.fill();
      },
      DrawSegment: function(p1, p2, color) {
        var drawer = this._drawer;
        if (p1.x === p2.x && p1.y === p2.y) {
          this._applyFillColor(color);
          this._DrawCircle(p1, 2 / PTM_RATIO);
          drawer.fill();
          return;
        }
        this._applyStrokeColor(color);
        drawer.moveTo(p1.x * PTM_RATIO, p1.y * PTM_RATIO);
        drawer.lineTo(p2.x * PTM_RATIO, p2.y * PTM_RATIO);
        drawer.stroke();
      },
      DrawPoint: function(center, radius, color) {},
      _applyStrokeColor: function(color) {
        this._drawer.setStrokeColor(cc.color(255 * color.r, 255 * color.g, 255 * color.b, 150));
      },
      _applyFillColor: function(color) {
        this._drawer.setFillColor(cc.color(255 * color.r, 255 * color.g, 255 * color.b, 150));
      }
    });
    cc.PhysicsDebugDraw = module.exports = PhysicsDebugDraw;
  }), {
    "../CCPhysicsTypes": 150
  } ],
  171: [ (function(require, module, exports) {
    function PhysicsRayCastCallback() {
      this._type = 0;
      this._fixtures = [];
      this._points = [];
      this._normals = [];
      this._fractions = [];
    }
    PhysicsRayCastCallback.prototype.init = function(type) {
      this._type = type;
      this._fixtures.length = 0;
      this._points.length = 0;
      this._normals.length = 0;
      this._fractions.length = 0;
    };
    PhysicsRayCastCallback.prototype.ReportFixture = function(fixture, point, normal, fraction) {
      if (0 === this._type) {
        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(point);
      this._normals.push(normal);
      this._fractions.push(fraction);
      if (1 === this._type) return 0;
      if (this._type >= 2) return 1;
      return fraction;
    };
    PhysicsRayCastCallback.prototype.getFixtures = function() {
      return this._fixtures;
    };
    PhysicsRayCastCallback.prototype.getPoints = function() {
      return this._points;
    };
    PhysicsRayCastCallback.prototype.getNormals = function() {
      return this._normals;
    };
    PhysicsRayCastCallback.prototype.getFractions = function() {
      return this._fractions;
    };
    cc.PhysicsRayCastCallback = module.exports = PhysicsRayCastCallback;
  }), {} ],
  172: [ (function(require, module, exports) {
    var PHYSICS_ANGLE_TO_ANGLE = require("../CCPhysicsTypes").PHYSICS_ANGLE_TO_ANGLE;
    var PTM_RATIO = require("../CCPhysicsTypes").PTM_RATIO;
    var convertToNodeRotation = require("../utils").convertToNodeRotation;
    var tempPosition = cc.v2();
    function PhysicsUtils() {}
    PhysicsUtils.prototype.addB2Body = function(body) {};
    PhysicsUtils.prototype.removeB2Body = function(body) {};
    PhysicsUtils.prototype.syncNode = function() {
      var bodies = cc.director.getPhysicsManager()._bodies;
      for (var i = 0, l = bodies.length; i < l; i++) {
        var body = bodies[i];
        var node = body.node;
        var b2body = body._b2Body;
        var pos = b2body.GetPosition();
        tempPosition.x = pos.x * PTM_RATIO;
        tempPosition.y = pos.y * PTM_RATIO;
        var angle = b2body.GetAngle() * PHYSICS_ANGLE_TO_ANGLE;
        if (null !== node.parent.parent) {
          tempPosition = node.parent.convertToNodeSpaceAR(tempPosition);
          angle = convertToNodeRotation(node.parent, angle);
        }
        var sgNode = node._sgNode;
        var position = node._position;
        position.x = tempPosition.x;
        position.y = tempPosition.y;
        sgNode.setPosition(position);
        node._rotationX = node._rotationY = angle;
        sgNode.rotation = angle;
      }
    };
    cc.PhysicsUtils = module.exports = PhysicsUtils;
  }), {
    "../CCPhysicsTypes": 150,
    "../utils": 173
  } ],
  173: [ (function(require, module, exports) {
    function getWorldRotation(node) {
      var rot = node.rotationX;
      var parent = node.parent;
      while (parent.parent) {
        rot += parent.rotationX;
        parent = parent.parent;
      }
      return rot;
    }
    function getWorldScale(node) {
      var scaleX = node.scaleX;
      var scaleY = node.scaleY;
      var parent = node.parent;
      while (parent.parent) {
        scaleX *= parent.scaleX;
        scaleY *= parent.scaleY;
        parent = parent.parent;
      }
      return cc.v2(scaleX, scaleY);
    }
    function convertToNodeRotation(node, rotation) {
      rotation -= node.rotationX;
      var parent = node.parent;
      while (parent.parent) {
        rotation -= parent.rotationX;
        parent = parent.parent;
      }
      return rotation;
    }
    module.exports = {
      getWorldRotation: getWorldRotation,
      getWorldScale: getWorldScale,
      convertToNodeRotation: convertToNodeRotation
    };
  }), {} ],
  174: [ (function(require, module, exports) {
    var Asset = require("../assets/CCAsset");
    var callInNextTick = require("./utils").callInNextTick;
    var Loader = require("../load-pipeline/CCLoader");
    var PackDownloader = require("../load-pipeline/pack-downloader");
    var AutoReleaseUtils = require("../load-pipeline/auto-release-utils");
    var decodeUuid = require("../utils/decode-uuid");
    var MD5Pipe = require("../load-pipeline/md5-pipe");
    var _libraryBase = "";
    var _rawAssetsBase = "";
    var _uuidToRawAsset = {};
    function isScene(asset) {
      return asset && (asset.constructor === cc.SceneAsset || asset instanceof cc.Scene);
    }
    function RawAssetEntry(url, type) {
      this.url = url;
      this.type = type;
    }
    var AssetLibrary = {
      loadAsset: function(uuid, callback, options) {
        if ("string" !== typeof uuid) return callInNextTick(callback, new Error("[AssetLibrary] uuid must be string"), null);
        var item = {
          uuid: uuid,
          type: "uuid"
        };
        options && options.existingAsset && (item.existingAsset = options.existingAsset);
        Loader.load(item, (function(error, asset) {
          if (error || !asset) error = new Error("[AssetLibrary] loading JSON or dependencies failed: " + (error ? error.message : "Unknown error")); else {
            if (asset.constructor === cc.SceneAsset) {
              false;
              var key = cc.loader._getReferenceKey(uuid);
              asset.scene.dependAssets = AutoReleaseUtils.getDependsRecursively(key);
            }
            if (false, isScene(asset)) {
              var id = cc.loader._getReferenceKey(uuid);
              Loader.removeItem(id);
            }
          }
          callback && callback(error, asset);
        }));
      },
      getLibUrlNoExt: function(uuid) {
        true;
        uuid = decodeUuid(uuid);
        return _libraryBase + uuid.slice(0, 2) + "/" + uuid;
      },
      _queryAssetInfoInEditor: function(uuid, callback) {
        false;
      },
      _getAssetInfoInRuntime: function(uuid, result) {
        result = result || {
          url: null,
          raw: false
        };
        var info = _uuidToRawAsset[uuid];
        if (info && !cc.isChildClassOf(info.type, cc.Asset)) {
          result.url = _rawAssetsBase + info.url;
          result.raw = true;
        } else {
          result.url = this.getLibUrlNoExt(uuid) + ".json";
          result.raw = false;
        }
        return result;
      },
      _getAssetUrl: function(uuid) {
        var info = _uuidToRawAsset[uuid];
        if (info) return _rawAssetsBase + info.url;
        return null;
      },
      queryAssetInfo: function(uuid, callback) {
        false;
        var info = this._getAssetInfoInRuntime(uuid);
        callback(null, info.url, info.raw);
      },
      parseUuidInEditor: function(url) {
        var uuid;
        var isImported;
        var dir;
        var dirBasename;
        var isAssetUrl;
        var index;
        false;
      },
      loadJson: function(json, callback) {
        var randomUuid = "" + (new Date().getTime() + Math.random());
        var item = {
          uuid: randomUuid,
          type: "uuid",
          content: json,
          skips: [ Loader.assetLoader.id, Loader.downloader.id ]
        };
        Loader.load(item, (function(error, asset) {
          if (error) error = new Error("[AssetLibrary] loading JSON or dependencies failed: " + error.message); else {
            if (asset.constructor === cc.SceneAsset) {
              var key = cc.loader._getReferenceKey(randomUuid);
              asset.scene.dependAssets = AutoReleaseUtils.getDependsRecursively(key);
            }
            if (false, isScene(asset)) {
              var id = cc.loader._getReferenceKey(randomUuid);
              Loader.removeItem(id);
            }
          }
          asset._uuid = "";
          callback && callback(error, asset);
        }));
      },
      getAssetByUuid: function(uuid) {
        return AssetLibrary._uuidToAsset[uuid] || null;
      },
      init: function(options) {
        false;
        var libraryPath = options.libraryPath;
        libraryPath = libraryPath.replace(/\\/g, "/");
        _libraryBase = cc.path.stripSep(libraryPath) + "/";
        _rawAssetsBase = options.rawAssetsBase;
        var md5AssetsMap = options.md5AssetsMap;
        if (md5AssetsMap) {
          var md5Pipe = new MD5Pipe(md5AssetsMap, _libraryBase, _rawAssetsBase);
          cc.loader.insertPipeAfter(cc.loader.assetLoader, md5Pipe);
          cc.loader.md5Pipe = md5Pipe;
        }
        var resources = Loader._resources;
        resources.reset();
        var rawAssets = options.rawAssets;
        if (rawAssets) {
          var RES_DIR = "resources/";
          for (var mountPoint in rawAssets) {
            var assets = rawAssets[mountPoint];
            for (var uuid in assets) {
              var info = assets[uuid];
              var url = info[0];
              var typeId = info[1];
              var type = cc.js._getClassById(typeId);
              if (!type) {
                cc.error("Cannot get", typeId);
                continue;
              }
              _uuidToRawAsset[uuid] = new RawAssetEntry(mountPoint + "/" + url, type);
              if ("assets" === mountPoint && url.startsWith(RES_DIR)) {
                if (cc.isChildClassOf(type, Asset)) {
                  var ext = cc.path.extname(url);
                  url = ext ? url.slice(RES_DIR.length, -ext.length) : url.slice(RES_DIR.length);
                } else url = url.slice(RES_DIR.length);
                var isSubAsset = 1 === info[2];
                resources.add(url, uuid, type, !isSubAsset);
              }
            }
          }
        }
        options.packedAssets && PackDownloader.initPacks(options.packedAssets);
        var mountPaths = options.mountPaths;
        mountPaths || (mountPaths = {
          assets: _rawAssetsBase + "assets",
          internal: _rawAssetsBase + "internal"
        });
        cc.url._init(mountPaths);
      }
    };
    AssetLibrary._uuidToAsset = {};
    module.exports = cc.AssetLibrary = AssetLibrary;
  }), {
    "../assets/CCAsset": 43,
    "../load-pipeline/CCLoader": 130,
    "../load-pipeline/auto-release-utils": 134,
    "../load-pipeline/md5-pipe": 140,
    "../load-pipeline/pack-downloader": 141,
    "../utils/decode-uuid": 222,
    "./utils": 200
  } ],
  175: [ (function(require, module, exports) {
    var JS = require("./js");
    var Enum = require("./CCEnum");
    var Utils = require("./utils");
    var _isPlainEmptyObj_DEV = Utils.isPlainEmptyObj_DEV;
    var _cloneable_DEV = Utils.cloneable_DEV;
    var Attr = require("./attribute");
    var DELIMETER = Attr.DELIMETER;
    var getTypeChecker = Attr.getTypeChecker;
    var preprocess = require("./preprocess-class");
    require("./requiring-frame");
    var BUILTIN_ENTRIES = [ "name", "extends", "mixins", "ctor", "__ctor__", "properties", "statics", "editor", "__ES6__" ];
    var INVALID_STATICS_DEV = false;
    function pushUnique(array, item) {
      array.indexOf(item) < 0 && array.push(item);
    }
    var deferredInitializer = {
      datas: null,
      push: function(data) {
        if (this.datas) this.datas.push(data); else {
          this.datas = [ data ];
          var self = this;
          setTimeout((function() {
            self.init();
          }), 0);
        }
      },
      init: function() {
        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;
            "function" === typeof properties && (properties = properties());
            var name = JS.getClassName(cls);
            properties ? declareProperties(cls, name, properties, cls.$super, data.mixins) : cc.errorID(3633, name);
          }
          this.datas = null;
        }
      }
    };
    function appendProp(cls, name) {
      false;
      pushUnique(cls.__props__, name);
    }
    var tmpArray = [];
    function defineProp(cls, className, propName, val, es6) {
      var defaultValue = val.default;
      false;
      Attr.setClassAttr(cls, propName, "default", defaultValue);
      appendProp(cls, propName);
      var attrs = parseAttributes(cls, val, className, propName, false);
      if (attrs) {
        var onAfterProp = tmpArray;
        for (var i = 0; i < attrs.length; i++) {
          var attr = attrs[i];
          Attr.attr(cls, propName, attr);
          attr._onAfterProp && onAfterProp.push(attr._onAfterProp);
        }
        for (var c = 0; c < onAfterProp.length; c++) onAfterProp[c](cls, propName);
        tmpArray.length = 0;
        attrs.length = 0;
      }
    }
    function defineGetSet(cls, name, propName, val, es6) {
      var getter = val.get;
      var setter = val.set;
      var proto = cls.prototype;
      var d = Object.getOwnPropertyDescriptor(proto, propName);
      var setterUndefined = !d;
      if (getter) {
        false;
        var attrs = parseAttributes(cls, val, name, propName, true);
        for (var i = 0; i < attrs.length; i++) Attr.attr(cls, propName, attrs[i]);
        attrs.length = 0;
        var ForceSerializable = false;
        ForceSerializable || Attr.setClassAttr(cls, propName, "serializable", false);
        !!ForceSerializable && appendProp(cls, propName);
        es6 || JS.get(proto, propName, getter, setterUndefined, setterUndefined);
        false, false;
      }
      if (setter) {
        if (!es6) {
          false;
          JS.set(proto, propName, setter, setterUndefined, setterUndefined);
        }
        false, false;
      }
    }
    function getDefault(defaultVal) {
      if ("function" === typeof defaultVal) {
        false;
        return defaultVal();
      }
      return defaultVal;
    }
    function mixinWithInherited(dest, src, filter) {
      for (var prop in src) dest.hasOwnProperty(prop) || filter && !filter(prop) || Object.defineProperty(dest, prop, JS.getPropertyDescriptor(src, prop));
    }
    function doDefine(className, baseClass, mixins, options) {
      var shouldAddProtoCtor;
      var __ctor__ = options.__ctor__;
      var ctor = options.ctor;
      var __es6__ = options.__ES6__;
      var ctorToUse;
      false;
      var ctors;
      var fireClass;
      if (__es6__) {
        ctors = [ ctor ];
        fireClass = ctor;
      } else {
        ctors = __ctor__ ? [ __ctor__ ] : _getAllCtors(baseClass, mixins, options);
        fireClass = _createCtor(ctors, baseClass, className, options);
        JS.value(fireClass, "extend", (function(options) {
          options.extends = this;
          return CCClass(options);
        }), true);
      }
      JS.value(fireClass, "__ctors__", ctors.length > 0 ? ctors : null, true);
      var prototype = fireClass.prototype;
      if (baseClass) {
        if (!__es6__) {
          JS.extend(fireClass, baseClass);
          prototype = fireClass.prototype;
        }
        JS.value(fireClass, "$super", baseClass);
        false;
      }
      if (mixins) {
        for (var m = mixins.length - 1; m >= 0; m--) {
          var mixin = mixins[m];
          mixinWithInherited(prototype, mixin.prototype);
          mixinWithInherited(fireClass, mixin, (function(prop) {
            return mixin.hasOwnProperty(prop) && true;
          }));
          CCClass._isCCClass(mixin) && mixinWithInherited(Attr.getClassAttrs(fireClass).constructor.prototype, Attr.getClassAttrs(mixin).constructor.prototype);
        }
        prototype.constructor = fireClass;
      }
      __es6__ || (prototype.__initProps__ = compileProps);
      JS.setClassName(className, fireClass);
      return fireClass;
    }
    function define(className, baseClass, mixins, options) {
      var Component = cc.Component;
      var frame = cc._RF.peek();
      if (frame && cc.isChildClassOf(baseClass, Component)) {
        if (cc.isChildClassOf(frame.cls, Component)) {
          cc.errorID(3615);
          return null;
        }
        false;
        className = className || frame.script;
      }
      var cls = doDefine(className, baseClass, mixins, options);
      if (frame) if (cc.isChildClassOf(baseClass, Component)) {
        var uuid = frame.uuid;
        if (uuid) {
          JS._setClassId(uuid, cls);
          false;
        }
        frame.cls = cls;
      } else cc.isChildClassOf(frame.cls, Component) || (frame.cls = cls);
      return cls;
    }
    function normalizeClassName_DEV(className) {
      var DefaultName = "CCClass";
      if (className) {
        className = className.replace(/^[^$A-Za-z_]/, "_").replace(/[^0-9A-Za-z_$]/g, "_");
        try {
          Function("function " + className + "(){}")();
          return className;
        } catch (e) {}
      }
      return DefaultName;
    }
    function getNewValueTypeCode(value) {
      var clsName = JS.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];
        if ("object" === typeof propVal) {
          cc.errorID(3641, clsName);
          return "new " + clsName + "()";
        }
        res += propVal;
        i < type.__props__.length - 1 && (res += ",");
      }
      return res + ")";
    }
    function getNewValueType(value) {
      var clsName = JS.getClassName(value);
      var type = value.constructor;
      var res = new type();
      for (var i = 0; i < type.__props__.length; i++) {
        var prop = type.__props__[i];
        var propVal = value[prop];
        if ("object" === typeof propVal) {
          cc.errorID(3641, clsName);
          return res;
        }
        res[prop] = propVal;
      }
      return res;
    }
    function escapeForJS(s) {
      return JSON.stringify(s).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
    }
    function getInitPropsJit(attrs, propList) {
      var F = [];
      var func = "";
      for (var i = 0; i < propList.length; i++) {
        var prop = propList[i];
        var attrKey = prop + DELIMETER + "default";
        if (attrKey in attrs) {
          var statement;
          statement = IDENTIFIER_RE.test(prop) ? "this." + prop + "=" : "this[" + escapeForJS(prop) + "]=";
          var expression;
          var def = attrs[attrKey];
          if ("object" === typeof def && def) expression = def instanceof cc.ValueType ? getNewValueTypeCode(def) : Array.isArray(def) ? "[]" : "{}"; else if ("function" === typeof def) {
            var index = F.length;
            F.push(def);
            expression = "F[" + index + "]()";
            false;
          } else expression = "string" === typeof def ? escapeForJS(def) : def;
          statement = statement + expression + ";\n";
          func += statement;
        }
      }
      var initProps;
      initProps = 0 === F.length ? Function(func) : Function("F", "return (function(){\n" + func + "})")(F);
      return initProps;
    }
    function getInitProps(attrs, propList) {
      function func() {
        var F = [];
        for (var i = 0; i < propList.length; i++) {
          var prop = propList[i];
          var attrKey = prop + DELIMETER + "default";
          if (attrKey in attrs) {
            var expression;
            var def = attrs[attrKey];
            if ("object" === typeof def && def) expression = def instanceof cc.ValueType ? getNewValueType(def) : Array.isArray(def) ? [] : {}; else if ("function" === typeof def) {
              var index = F.length;
              F.push(def);
              expression = F[index]();
              false;
            } else expression = def;
            this[prop] = expression;
          }
        }
      }
      return func;
    }
    var IDENTIFIER_RE = /^[$A-Za-z_][0-9A-Za-z_$]*$/;
    function compileProps(actualClass) {
      var attrs = Attr.getClassAttrs(actualClass);
      var propList = actualClass.__props__;
      if (null === propList) {
        deferredInitializer.init();
        propList = actualClass.__props__;
      }
      var initProps = getInitPropsJit(attrs, propList);
      actualClass.prototype.__initProps__ = initProps;
      initProps.call(this);
    }
    var _createCtor = function(ctors, baseClass, className, options) {
      var superCallBounded = baseClass && boundSuperCalls(baseClass, options, className);
      var ctorName = "CCClass";
      var body = "return function " + ctorName + "(){\n";
      superCallBounded && (body += "this._super=null;\n");
      body += "this.__initProps__(" + ctorName + ");\n";
      var ctorLen = ctors.length;
      if (ctorLen > 0) {
        var useTryCatch = !(className && className.startsWith("cc."));
        useTryCatch && (body += "try{\n");
        var SNIPPET = "].apply(this,arguments);\n";
        if (1 === ctorLen) body += ctorName + ".__ctors__[0" + SNIPPET; else {
          body += "var cs=" + ctorName + ".__ctors__;\n";
          for (var i = 0; i < ctorLen; i++) body += "cs[" + i + SNIPPET;
        }
        useTryCatch && (body += "}catch(e){\ncc._throw(e);\n}\n");
      }
      body += "}";
      return Function(body)();
    };
    function _validateCtor_DEV(ctor, baseClass, className, options) {
      var originCtor;
      false;
      !(ctor.length > 0) || className && className.startsWith("cc.") || cc.warnID(3617, className);
      return ctor;
    }
    function _getAllCtors(baseClass, mixins, options) {
      function getCtors(cls) {
        return CCClass._isCCClass(cls) ? cls.__ctors__ || [] : [ cls ];
      }
      var ctors = [];
      var baseOrMixins = [ baseClass ].concat(mixins);
      for (var b = 0; b < baseOrMixins.length; b++) {
        var baseOrMixin = baseOrMixins[b];
        if (baseOrMixin) {
          var baseCtors = getCtors(baseOrMixin);
          for (var c = 0; c < baseCtors.length; c++) pushUnique(ctors, baseCtors[c]);
        }
      }
      var ctor = options.ctor;
      ctor && ctors.push(ctor);
      return ctors;
    }
    var SuperCallReg = /xyz/.test((function() {
      xyz;
    })) ? /\b\._super\b/ : /.*/;
    var SuperCallRegStrict = /xyz/.test((function() {
      xyz;
    })) ? /this\._super\s*\(/ : /(NONE){99}/;
    function boundSuperCalls(baseClass, options, className) {
      var hasSuperCall = false;
      for (var funcName in options) {
        if (BUILTIN_ENTRIES.indexOf(funcName) >= 0) continue;
        var func = options[funcName];
        if ("function" !== typeof func) continue;
        var pd = JS.getPropertyDescriptor(baseClass.prototype, funcName);
        if (pd) {
          var superFunc = pd.value;
          if ("function" === typeof superFunc) {
            if (SuperCallReg.test(func)) {
              hasSuperCall = true;
              options[funcName] = (function(superFunc, func) {
                return function() {
                  var tmp = this._super;
                  this._super = superFunc;
                  var ret = func.apply(this, arguments);
                  this._super = tmp;
                  return ret;
                };
              })(superFunc, func);
            }
            continue;
          }
        }
        false;
      }
      return hasSuperCall;
    }
    function declareProperties(cls, className, properties, baseClass, mixins, es6) {
      cls.__props__ = [];
      baseClass && baseClass.__props__ && (cls.__props__ = baseClass.__props__.slice());
      if (mixins) for (var m = 0; m < mixins.length; ++m) {
        var mixin = mixins[m];
        mixin.__props__ && (cls.__props__ = cls.__props__.concat(mixin.__props__.filter((function(x) {
          return cls.__props__.indexOf(x) < 0;
        }))));
      }
      if (properties) {
        preprocess.preprocessAttrs(properties, className, cls, es6);
        for (var propName in properties) {
          var val = properties[propName];
          "default" in val ? defineProp(cls, className, propName, val, es6) : defineGetSet(cls, className, propName, val, es6);
        }
      }
    }
    function CCClass(options) {
      options = options || {};
      var name = options.name;
      var base = options.extends;
      var mixins = options.mixins;
      var cls = define(name, base, mixins, options);
      name || (name = cc.js.getClassName(cls));
      var properties = options.properties;
      if ("function" === typeof properties || base && null === base.__props__ || mixins && mixins.some((function(x) {
        return null === x.__props__;
      }))) {
        false;
        deferredInitializer.push({
          cls: cls,
          props: properties,
          mixins: mixins
        });
        cls.__props__ = null;
      } else declareProperties(cls, name, properties, base, options.mixins, options.__ES6__);
      var statics = options.statics;
      if (statics) {
        var staticPropName;
        false;
        for (staticPropName in statics) cls[staticPropName] = statics[staticPropName];
      }
      for (var funcName in options) {
        if (BUILTIN_ENTRIES.indexOf(funcName) >= 0) continue;
        var func = options[funcName];
        if (!preprocess.validateMethodWithProps(func, funcName, name, cls, base)) continue;
        JS.value(cls.prototype, funcName, func, true, true);
      }
      var editor = options.editor;
      editor && !!cc.isChildClassOf(base, cc.Component) && cc.Component._registerEditorProps(cls, editor);
      return cls;
    }
    CCClass._isCCClass = function(constructor) {
      return constructor && constructor.hasOwnProperty("__ctors__");
    };
    CCClass._fastDefine = function(className, constructor, serializableFields) {
      JS.setClassName(className, constructor);
      var props = constructor.__props__ = Object.keys(serializableFields);
      var attrProtos = Attr.getClassAttrsProto(constructor);
      for (var i = 0; i < props.length; i++) {
        var key = props[i];
        attrProtos[key + DELIMETER + "visible"] = false;
        attrProtos[key + DELIMETER + "default"] = serializableFields[key];
      }
    };
    CCClass.Attr = Attr;
    CCClass.attr = Attr.attr;
    cc.isChildClassOf = function(subclass, superclass) {
      if (subclass && superclass) {
        if ("function" !== typeof subclass) return false;
        if ("function" !== typeof superclass) {
          false;
          return false;
        }
        if (subclass === superclass) return true;
        for (;;) {
          subclass = JS.getSuper(subclass);
          if (!subclass) return false;
          if (subclass === superclass) return true;
        }
      }
      return false;
    };
    CCClass.getInheritanceChain = function(klass) {
      var chain = [];
      for (;;) {
        klass = JS.getSuper(klass);
        if (!klass) break;
        klass !== Object && chain.push(klass);
      }
      return chain;
    };
    var PrimitiveTypes = {
      Integer: "Number",
      Float: "Number",
      Boolean: "Boolean",
      String: "String"
    };
    var tmpAttrs = [];
    function parseAttributes(cls, attrs, className, propName, usedInGetter) {
      var ERR_Type = "";
      var attrsProto = null;
      var attrsProtoKey = "";
      function getAttrsProto() {
        attrsProtoKey = propName + DELIMETER;
        return attrsProto = Attr.getClassAttrsProto(cls);
      }
      tmpAttrs.length = 0;
      var result = tmpAttrs;
      var type = attrs.type;
      if (type) {
        var primitiveType = PrimitiveTypes[type];
        if (primitiveType) result.push({
          type: type,
          _onAfterProp: getTypeChecker(primitiveType, "cc." + type)
        }); else if ("Object" === type) false; else if (type === Attr.ScriptUuid) {
          var attr = Attr.ObjectType(cc.ScriptAsset);
          attr.type = "Script";
          result.push(attr);
        } else "object" === typeof type ? !!Enum.isEnum(type) && result.push({
          type: "Enum",
          enumList: Enum.getList(type)
        }) : "function" === typeof type && (attrs.url ? result.push({
          type: "Object",
          ctor: type,
          _onAfterProp: getTypeChecker("String", "cc.String")
        }) : result.push(attrs._short ? {
          type: "Object",
          ctor: type
        } : Attr.ObjectType(type)));
      }
      function parseSimpleAttr(attrName, expectType) {
        if (attrName in attrs) {
          var val = attrs[attrName];
          typeof val === expectType && ((attrsProto || getAttrsProto())[attrsProtoKey + attrName] = val);
        }
      }
      if (attrs.editorOnly) {
        false;
        (attrsProto || getAttrsProto())[attrsProtoKey + "editorOnly"] = true;
      }
      false;
      attrs.url && ((attrsProto || getAttrsProto())[attrsProtoKey + "saveUrlAsAsset"] = true);
      if (false === attrs.serializable) {
        false;
        (attrsProto || getAttrsProto())[attrsProtoKey + "serializable"] = false;
      }
      parseSimpleAttr("formerlySerializedAs", "string");
      false;
      var visible;
      var startsWithUS;
      false;
      var range = attrs.range;
      if (range) if (Array.isArray(range)) if (range.length >= 2) {
        (attrsProto || getAttrsProto())[attrsProtoKey + "min"] = range[0];
        attrsProto[attrsProtoKey + "max"] = range[1];
        range.length > 2 && (attrsProto[attrsProtoKey + "step"] = range[2]);
      } else false; else false;
      parseSimpleAttr("min", "number");
      parseSimpleAttr("max", "number");
      parseSimpleAttr("step", "number");
      return result;
    }
    cc.Class = CCClass;
    module.exports = {
      isArray: function(defaultVal) {
        defaultVal = getDefault(defaultVal);
        return Array.isArray(defaultVal);
      },
      fastDefine: CCClass._fastDefine,
      getNewValueTypeCode: getNewValueTypeCode,
      IDENTIFIER_RE: IDENTIFIER_RE,
      escapeForJS: escapeForJS,
      getDefault: getDefault
    };
    false;
  }), {
    "./CCEnum": 177,
    "./attribute": 188,
    "./js": 196,
    "./preprocess-class": 197,
    "./requiring-frame": 198,
    "./utils": 200
  } ],
  176: [ (function(require, module, exports) {
    require("./CCClass");
    var Preprocess = require("./preprocess-class");
    var JS = require("./js");
    var isPlainEmptyObj_DEV = false;
    var CACHE_KEY = "__ccclassCache__";
    function fNOP(ctor) {
      return ctor;
    }
    function getSubDict(obj, key) {
      return obj[key] || (obj[key] = {});
    }
    function checkCtorArgument(decorate) {
      return function(target) {
        if ("function" === typeof target) return decorate(target);
        return function(ctor) {
          return decorate(ctor, target);
        };
      };
    }
    function _checkNormalArgument(validator_DEV, decorate, decoratorName) {
      return function(target) {
        false;
        return function(ctor) {
          return decorate(ctor, target);
        };
      };
    }
    var checkCompArgument = _checkNormalArgument.bind(null, false);
    function _argumentChecker(type) {
      return _checkNormalArgument.bind(null, false);
    }
    var checkStringArgument = _argumentChecker("string");
    var checkNumberArgument = _argumentChecker("number");
    function getClassCache(ctor, decoratorName) {
      false;
      return getSubDict(ctor, CACHE_KEY);
    }
    function getDefaultFromInitializer(initializer) {
      var value;
      try {
        value = initializer();
      } catch (e) {
        return initializer;
      }
      return "object" !== typeof value || null === value ? value : initializer;
    }
    function extractActualDefaultValues(ctor) {
      var dummyObj;
      try {
        dummyObj = new ctor();
      } catch (e) {
        false;
        return {};
      }
      return dummyObj;
    }
    function genProperty(ctor, properties, propName, options, desc, cache) {
      var fullOptions = options && (Preprocess.getFullFormOfProperty(options) || options);
      var existsProperty = properties[propName];
      var prop = JS.mixin(existsProperty || {}, fullOptions || {});
      var isGetset = desc && (desc.get || desc.set);
      if (isGetset) {
        var errorProps;
        false;
        desc.get && (prop.get = desc.get);
        desc.set && (prop.set = desc.set);
      } else {
        false;
        var defaultValue = void 0;
        var isDefaultValueSpecified = false;
        if (desc) {
          if (desc.initializer) {
            defaultValue = getDefaultFromInitializer(desc.initializer);
            isDefaultValueSpecified = true;
          }
        } else {
          var actualDefaultValues = cache.default || (cache.default = extractActualDefaultValues(ctor));
          if (actualDefaultValues.hasOwnProperty(propName)) {
            defaultValue = actualDefaultValues[propName];
            isDefaultValueSpecified = true;
          }
        }
        false;
        prop.default = defaultValue;
      }
      properties[propName] = prop;
    }
    var ccclass = checkCtorArgument((function(ctor, name) {
      var base = JS.getSuper(ctor);
      base === Object && (base = null);
      var proto = {
        name: name,
        extends: base,
        ctor: ctor,
        __ES6__: true
      };
      var cache = ctor[CACHE_KEY];
      if (cache) {
        var decoratedProto = cache.proto;
        decoratedProto && JS.mixin(proto, decoratedProto);
        ctor[CACHE_KEY] = void 0;
      }
      var res = cc.Class(proto);
      var propNames;
      var i;
      var prop;
      var desc;
      var func;
      false;
      return res;
    }));
    function property(ctorProtoOrOptions, propName, desc) {
      var options = null;
      function normalized(ctorProto, propName, desc) {
        var cache = getClassCache(ctorProto.constructor);
        if (cache) {
          var ccclassProto = getSubDict(cache, "proto");
          var properties = getSubDict(ccclassProto, "properties");
          genProperty(ctorProto.constructor, properties, propName, options, desc, cache);
        }
      }
      if ("undefined" === typeof propName) {
        options = ctorProtoOrOptions;
        return normalized;
      }
      normalized(ctorProtoOrOptions, propName, desc);
    }
    function createEditorDecorator(argCheckFunc, editorPropName, staticValue) {
      return argCheckFunc((function(ctor, decoratedValue) {
        var cache = getClassCache(ctor, editorPropName);
        if (cache) {
          var value = void 0 !== staticValue ? staticValue : decoratedValue;
          var proto = getSubDict(cache, "proto");
          getSubDict(proto, "editor")[editorPropName] = value;
        }
      }), editorPropName);
    }
    function createDummyDecorator(argCheckFunc) {
      return argCheckFunc(fNOP);
    }
    var executeInEditMode = createDummyDecorator(checkCtorArgument, "executeInEditMode", true);
    var requireComponent = createEditorDecorator(checkCompArgument, "requireComponent");
    var menu = createDummyDecorator(checkStringArgument, "menu");
    var executionOrder = createEditorDecorator(checkNumberArgument, "executionOrder");
    var disallowMultiple = createDummyDecorator(checkCtorArgument, "disallowMultiple");
    var playOnFocus = createDummyDecorator(checkCtorArgument, "playOnFocus");
    var inspector = createDummyDecorator(checkStringArgument, "inspector");
    var icon = createDummyDecorator(checkStringArgument, "icon");
    var help = createDummyDecorator(checkStringArgument, "help");
    function mixins() {
      var mixins = [];
      for (var i = 0; i < arguments.length; i++) mixins[i] = arguments[i];
      return function(ctor) {
        var cache = getClassCache(ctor, "mixins");
        cache && (getSubDict(cache, "proto").mixins = mixins);
      };
    }
    cc._decorator = module.exports = {
      ccclass: ccclass,
      property: property,
      executeInEditMode: executeInEditMode,
      requireComponent: requireComponent,
      menu: menu,
      executionOrder: executionOrder,
      disallowMultiple: disallowMultiple,
      playOnFocus: playOnFocus,
      inspector: inspector,
      icon: icon,
      help: help,
      mixins: mixins
    };
  }), {
    "./CCClass": 175,
    "./js": 196,
    "./preprocess-class": 197,
    "./utils": 200
  } ],
  177: [ (function(require, module, exports) {
    var JS = require("./js");
    function Enum(obj) {
      if ("__enums__" in obj) return obj;
      JS.value(obj, "__enums__", 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 (-1 === val) {
          val = ++lastIndex;
          obj[key] = val;
        } else if ("number" === typeof val) lastIndex = val; else if ("string" === typeof val && Number.isInteger(parseFloat(key))) continue;
        var reverseKey = "" + val;
        if (key !== reverseKey) {
          if ((false, false) && reverseKey in obj && obj[reverseKey] !== key) {
            cc.errorID(7100, reverseKey);
            continue;
          }
          JS.value(obj, reverseKey, key);
        }
      }
      return obj;
    }
    Enum.isEnum = function(enumType) {
      return enumType && enumType.hasOwnProperty("__enums__");
    };
    Enum.getList = function(enumDef) {
      if (enumDef.__enums__) return enumDef.__enums__;
      var enums = enumDef.__enums__ = [];
      for (var name in enumDef) {
        var value = enumDef[name];
        Number.isInteger(value) && enums.push({
          name: name,
          value: value
        });
      }
      enums.sort((function(a, b) {
        return a.value - b.value;
      }));
      return enums;
    };
    var _TestEnum;
    false;
    module.exports = cc.Enum = Enum;
  }), {
    "./js": 196
  } ],
  178: [ (function(require, module, exports) {
    cc.ClassManager || require("./_CCClass");
    var eventManager = require("../event-manager");
    var inputManager = require("./CCInputManager");
    inputManager.__instanceId = cc.ClassManager.getNewInstanceId();
    inputManager.setAccelerometerEnabled = function(isEnable) {
      var _t = this;
      if (_t._accelEnabled === isEnable) return;
      _t._accelEnabled = isEnable;
      var scheduler = cc.director.getScheduler();
      if (_t._accelEnabled) {
        _t._accelCurTime = 0;
        scheduler.scheduleUpdate(_t);
      } else {
        _t._accelCurTime = 0;
        scheduler.scheduleUpdate(_t);
      }
    };
    inputManager.setAccelerometerInterval = function(interval) {
      this._accelInterval !== interval && (this._accelInterval = interval);
    };
    inputManager._registerKeyboardEvent = function() {
      cc.game.canvas.addEventListener("keydown", (function(e) {
        eventManager.dispatchEvent(new cc.Event.EventKeyboard(e.keyCode, true));
        e.stopPropagation();
        e.preventDefault();
      }), false);
      cc.game.canvas.addEventListener("keyup", (function(e) {
        eventManager.dispatchEvent(new cc.Event.EventKeyboard(e.keyCode, false));
        e.stopPropagation();
        e.preventDefault();
      }), false);
    };
    inputManager._registerAccelerometerEvent = function() {
      var w = window, _t = this;
      _t._acceleration = new cc.Acceleration();
      _t._accelDeviceEvent = w.DeviceMotionEvent || w.DeviceOrientationEvent;
      cc.sys.browserType === cc.sys.BROWSER_TYPE_MOBILE_QQ && (_t._accelDeviceEvent = window.DeviceOrientationEvent);
      var _deviceEventType = _t._accelDeviceEvent === w.DeviceMotionEvent ? "devicemotion" : "deviceorientation";
      var ua = navigator.userAgent;
      (/Android/.test(ua) || /Adr/.test(ua) && cc.sys.browserType === cc.BROWSER_TYPE_UC) && (_t._minus = -1);
      w.addEventListener(_deviceEventType, _t.didAccelerate.bind(_t), false);
    };
    inputManager.didAccelerate = function(eventData) {
      var _t = this, w = window;
      if (!_t._accelEnabled) return;
      var mAcceleration = _t._acceleration;
      var x, y, z;
      if (_t._accelDeviceEvent === window.DeviceMotionEvent) {
        var eventAcceleration = eventData["accelerationIncludingGravity"];
        x = _t._accelMinus * eventAcceleration.x * .1;
        y = _t._accelMinus * eventAcceleration.y * .1;
        z = .1 * eventAcceleration.z;
      } else {
        x = eventData["gamma"] / 90 * .981;
        y = -eventData["beta"] / 90 * .981;
        z = eventData["alpha"] / 90 * .981;
      }
      mAcceleration.x = x;
      mAcceleration.y = y;
      mAcceleration.z = z;
      mAcceleration.timestamp = eventData.timeStamp || Date.now();
      var tmpX = mAcceleration.x;
      if (w.orientation === cc.macro.WEB_ORIENTATION_LANDSCAPE_RIGHT) {
        mAcceleration.x = -mAcceleration.y;
        mAcceleration.y = tmpX;
      } else if (w.orientation === cc.macro.WEB_ORIENTATION_LANDSCAPE_LEFT) {
        mAcceleration.x = mAcceleration.y;
        mAcceleration.y = -tmpX;
      } else if (w.orientation === cc.macro.WEB_ORIENTATION_PORTRAIT_UPSIDE_DOWN) {
        mAcceleration.x = -mAcceleration.x;
        mAcceleration.y = -mAcceleration.y;
      }
      if ((true, cc.sys.os === cc.sys.OS_ANDROID) && cc.sys.browserType !== cc.sys.BROWSER_TYPE_MOBILE_QQ) {
        mAcceleration.x = -mAcceleration.x;
        mAcceleration.y = -mAcceleration.y;
      }
    };
  }), {
    "../event-manager": 110,
    "./CCInputManager": 179,
    "./_CCClass": 187
  } ],
  179: [ (function(require, module, exports) {
    var js = require("../platform/js");
    var macro = require("./CCMacro");
    var sys = require("./CCSys");
    var eventManager = require("../event-manager");
    var TOUCH_TIMEOUT = macro.TOUCH_TIMEOUT;
    var inputManager = {
      _mousePressed: false,
      _isRegisterEvent: false,
      _preTouchPoint: cc.p(0, 0),
      _prevMousePoint: cc.p(0, 0),
      _preTouchPool: [],
      _preTouchPoolPointer: 0,
      _touches: [],
      _touchesIntegerDict: {},
      _indexBitsUsed: 0,
      _maxTouches: 5,
      _accelEnabled: false,
      _accelInterval: 1 / 30,
      _accelMinus: 1,
      _accelCurTime: 0,
      _acceleration: null,
      _accelDeviceEvent: null,
      _getUnUsedIndex: function() {
        var temp = this._indexBitsUsed;
        var now = cc.sys.now();
        for (var i = 0; i < this._maxTouches; i++) {
          if (!(1 & temp)) {
            this._indexBitsUsed |= 1 << i;
            return i;
          }
          var touch = this._touches[i];
          if (now - touch._lastModified > TOUCH_TIMEOUT) {
            this._removeUsedIndexBit(i);
            delete this._touchesIntegerDict[touch.getID()];
            return i;
          }
          temp >>= 1;
        }
        return -1;
      },
      _removeUsedIndexBit: function(index) {
        if (index < 0 || index >= this._maxTouches) return;
        var temp = 1 << index;
        temp = ~temp;
        this._indexBitsUsed &= temp;
      },
      _glView: null,
      handleTouchesBegin: function(touches) {
        var selTouch, index, curTouch, touchID, handleTouches = [], locTouchIntDict = this._touchesIntegerDict, now = sys.now();
        for (var i = 0, len = touches.length; i < len; i++) {
          selTouch = touches[i];
          touchID = selTouch.getID();
          index = locTouchIntDict[touchID];
          if (null == index) {
            var unusedIndex = this._getUnUsedIndex();
            if (-1 === unusedIndex) {
              cc.logID(2300, unusedIndex);
              continue;
            }
            curTouch = this._touches[unusedIndex] = new cc.Touch(selTouch._point.x, selTouch._point.y, selTouch.getID());
            curTouch._lastModified = now;
            curTouch._setPrevPoint(selTouch._prevPoint);
            locTouchIntDict[touchID] = unusedIndex;
            handleTouches.push(curTouch);
          }
        }
        if (handleTouches.length > 0) {
          this._glView._convertTouchesWithScale(handleTouches);
          var touchEvent = new cc.Event.EventTouch(handleTouches);
          touchEvent._eventCode = cc.Event.EventTouch.BEGAN;
          eventManager.dispatchEvent(touchEvent);
        }
      },
      handleTouchesMove: function(touches) {
        var selTouch, index, touchID, handleTouches = [], locTouches = this._touches, now = sys.now();
        for (var i = 0, len = touches.length; i < len; i++) {
          selTouch = touches[i];
          touchID = selTouch.getID();
          index = this._touchesIntegerDict[touchID];
          if (null == index) continue;
          if (locTouches[index]) {
            locTouches[index]._setPoint(selTouch._point);
            locTouches[index]._setPrevPoint(selTouch._prevPoint);
            locTouches[index]._lastModified = now;
            handleTouches.push(locTouches[index]);
          }
        }
        if (handleTouches.length > 0) {
          this._glView._convertTouchesWithScale(handleTouches);
          var touchEvent = new cc.Event.EventTouch(handleTouches);
          touchEvent._eventCode = cc.Event.EventTouch.MOVED;
          eventManager.dispatchEvent(touchEvent);
        }
      },
      handleTouchesEnd: function(touches) {
        var handleTouches = this.getSetOfTouchesEndOrCancel(touches);
        if (handleTouches.length > 0) {
          this._glView._convertTouchesWithScale(handleTouches);
          var touchEvent = new cc.Event.EventTouch(handleTouches);
          touchEvent._eventCode = cc.Event.EventTouch.ENDED;
          eventManager.dispatchEvent(touchEvent);
        }
      },
      handleTouchesCancel: function(touches) {
        var handleTouches = this.getSetOfTouchesEndOrCancel(touches);
        if (handleTouches.length > 0) {
          this._glView._convertTouchesWithScale(handleTouches);
          var touchEvent = new cc.Event.EventTouch(handleTouches);
          touchEvent._eventCode = cc.Event.EventTouch.CANCELLED;
          eventManager.dispatchEvent(touchEvent);
        }
      },
      getSetOfTouchesEndOrCancel: function(touches) {
        var selTouch, index, touchID, handleTouches = [], locTouches = this._touches, locTouchesIntDict = this._touchesIntegerDict;
        for (var i = 0, len = touches.length; i < len; i++) {
          selTouch = touches[i];
          touchID = selTouch.getID();
          index = locTouchesIntDict[touchID];
          if (null == index) continue;
          if (locTouches[index]) {
            locTouches[index]._setPoint(selTouch._point);
            locTouches[index]._setPrevPoint(selTouch._prevPoint);
            handleTouches.push(locTouches[index]);
            this._removeUsedIndexBit(index);
            delete locTouchesIntDict[touchID];
          }
        }
        return handleTouches;
      },
      getHTMLElementPosition: function(element) {
        if (sys.platform === sys.WECHAT_GAME) return {
          left: 0,
          top: 0,
          width: window.innerWidth,
          height: window.innerHeight
        };
        var docElem = document.documentElement;
        var leftOffset = window.pageXOffset - docElem.clientLeft;
        var topOffset = window.pageYOffset - docElem.clientTop;
        if ("function" === typeof element.getBoundingClientRect) {
          var box = element.getBoundingClientRect();
          return {
            left: box.left + leftOffset,
            top: box.top + topOffset,
            width: box.width,
            height: box.height
          };
        }
        return element instanceof HTMLCanvasElement ? {
          left: leftOffset,
          top: topOffset,
          width: element.width,
          height: element.height
        } : {
          left: leftOffset,
          top: topOffset,
          width: parseInt(element.style.width),
          height: parseInt(element.style.height)
        };
      },
      getPreTouch: function(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;
        }
        preTouch || (preTouch = touch);
        return preTouch;
      },
      setPreTouch: function(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;
        }
      },
      getTouchByXY: function(tx, ty, pos) {
        var locPreTouch = this._preTouchPoint;
        var location = this._glView.convertToLocationInView(tx, ty, pos);
        var touch = new cc.Touch(location.x, location.y);
        touch._setPrevPoint(locPreTouch.x, locPreTouch.y);
        locPreTouch.x = location.x;
        locPreTouch.y = location.y;
        return touch;
      },
      getMouseEvent: function(location, pos, eventType) {
        var locPreMouse = this._prevMousePoint;
        var mouseEvent = new cc.Event.EventMouse(eventType);
        mouseEvent._setPrevCursor(locPreMouse.x, locPreMouse.y);
        locPreMouse.x = location.x;
        locPreMouse.y = location.y;
        this._glView._convertMouseToLocationInView(locPreMouse, pos);
        mouseEvent.setLocation(locPreMouse.x, locPreMouse.y);
        return mouseEvent;
      },
      getPointByEvent: function(event, pos) {
        if (null != event.pageX) return {
          x: event.pageX,
          y: event.pageY
        };
        if (sys.platform === sys.WECHAT_GAME) {
          pos.left = 0;
          pos.top = 0;
        } else {
          pos.left -= document.body.scrollLeft;
          pos.top -= document.body.scrollTop;
        }
        return {
          x: event.clientX,
          y: event.clientY
        };
      },
      getTouchesByEvent: function(event, pos) {
        var touchArr = [], locView = this._glView;
        var touch_event, touch, preLocation;
        var locPreTouch = this._preTouchPoint;
        var length = event.changedTouches.length;
        for (var i = 0; i < length; i++) {
          touch_event = event.changedTouches[i];
          if (touch_event) {
            var location;
            location = sys.BROWSER_TYPE_FIREFOX === sys.browserType ? locView.convertToLocationInView(touch_event.pageX, touch_event.pageY, pos) : locView.convertToLocationInView(touch_event.clientX, touch_event.clientY, pos);
            if (null != touch_event.identifier) {
              touch = new cc.Touch(location.x, location.y, touch_event.identifier);
              preLocation = this.getPreTouch(touch).getLocation();
              touch._setPrevPoint(preLocation.x, preLocation.y);
              this.setPreTouch(touch);
            } else {
              touch = new cc.Touch(location.x, location.y);
              touch._setPrevPoint(locPreTouch.x, locPreTouch.y);
            }
            locPreTouch.x = location.x;
            locPreTouch.y = location.y;
            touchArr.push(touch);
          }
        }
        return touchArr;
      },
      registerSystemEvent: function(element) {
        if (this._isRegisterEvent) return;
        this._glView = cc.view;
        var selfPointer = this;
        var prohibition = sys.isMobile;
        var supportMouse = "mouse" in sys.capabilities;
        var supportTouches = "touches" in sys.capabilities;
        if (sys.platform === sys.WECHAT_GAME) {
          prohibition = false;
          supportTouches = true;
          supportMouse = false;
        }
        if (supportMouse) {
          if (!prohibition) {
            window.addEventListener("mousedown", (function() {
              selfPointer._mousePressed = true;
            }), false);
            window.addEventListener("mouseup", (function(event) {
              if (!selfPointer._mousePressed) return;
              selfPointer._mousePressed = false;
              var pos = selfPointer.getHTMLElementPosition(element);
              var location = selfPointer.getPointByEvent(event, pos);
              if (!cc.rectContainsPoint(new cc.Rect(pos.left, pos.top, pos.width, pos.height), location)) {
                selfPointer.handleTouchesEnd([ selfPointer.getTouchByXY(location.x, location.y, pos) ]);
                var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.Event.EventMouse.UP);
                mouseEvent.setButton(event.button);
                eventManager.dispatchEvent(mouseEvent);
              }
            }), false);
          }
          var EventMouse = cc.Event.EventMouse;
          var _mouseEventsOnElement = [ !prohibition && [ "mousedown", EventMouse.DOWN, function(event, mouseEvent, location, pos) {
            selfPointer._mousePressed = true;
            selfPointer.handleTouchesBegin([ selfPointer.getTouchByXY(location.x, location.y, pos) ]);
            element.focus();
          } ], !prohibition && [ "mouseup", EventMouse.UP, function(event, mouseEvent, location, pos) {
            selfPointer._mousePressed = false;
            selfPointer.handleTouchesEnd([ selfPointer.getTouchByXY(location.x, location.y, pos) ]);
          } ], !prohibition && [ "mousemove", EventMouse.MOVE, function(event, mouseEvent, location, pos) {
            selfPointer.handleTouchesMove([ selfPointer.getTouchByXY(location.x, location.y, pos) ]);
            selfPointer._mousePressed || mouseEvent.setButton(null);
          } ], [ "mousewheel", EventMouse.SCROLL, function(event, mouseEvent) {
            mouseEvent.setScrollData(0, event.wheelDelta);
          } ], [ "DOMMouseScroll", EventMouse.SCROLL, function(event, mouseEvent) {
            mouseEvent.setScrollData(0, -120 * event.detail);
          } ] ];
          for (var i = 0; i < _mouseEventsOnElement.length; ++i) {
            var entry = _mouseEventsOnElement[i];
            entry && (function() {
              var name = entry[0];
              var type = entry[1];
              var handler = entry[2];
              element.addEventListener(name, (function(event) {
                var pos = selfPointer.getHTMLElementPosition(element);
                var location = selfPointer.getPointByEvent(event, pos);
                var mouseEvent = selfPointer.getMouseEvent(location, pos, type);
                mouseEvent.setButton(event.button);
                handler(event, mouseEvent, location, pos);
                eventManager.dispatchEvent(mouseEvent);
                event.stopPropagation();
                event.preventDefault();
              }), false);
            })();
          }
        }
        if (window.navigator.msPointerEnabled) {
          var _pointerEventsMap = {
            MSPointerDown: selfPointer.handleTouchesBegin,
            MSPointerMove: selfPointer.handleTouchesMove,
            MSPointerUp: selfPointer.handleTouchesEnd,
            MSPointerCancel: selfPointer.handleTouchesCancel
          };
          var _loop = function(eventName) {
            var touchEvent = _pointerEventsMap[eventName];
            element.addEventListener(eventName, (function(event) {
              var pos = selfPointer.getHTMLElementPosition(element);
              pos.left -= document.documentElement.scrollLeft;
              pos.top -= document.documentElement.scrollTop;
              touchEvent.call(selfPointer, [ selfPointer.getTouchByXY(event.clientX, event.clientY, pos) ]);
              event.stopPropagation();
            }), false);
          };
          for (var eventName in _pointerEventsMap) _loop(eventName);
        }
        if (supportTouches) {
          var _touchEventsMap = {
            touchstart: function(touchesToHandle) {
              selfPointer.handleTouchesBegin(touchesToHandle);
              sys.platform !== sys.WECHAT_GAME && element.focus();
            },
            touchmove: function(touchesToHandle) {
              selfPointer.handleTouchesMove(touchesToHandle);
            },
            touchend: function(touchesToHandle) {
              selfPointer.handleTouchesEnd(touchesToHandle);
            },
            touchcancel: function(touchesToHandle) {
              selfPointer.handleTouchesCancel(touchesToHandle);
            }
          };
          var _loop2 = function(eventName) {
            var handler = _touchEventsMap[eventName];
            element.addEventListener(eventName, (function(event) {
              if (!event.changedTouches) return;
              var pos = selfPointer.getHTMLElementPosition(element);
              var body = document.body;
              pos.left -= body.scrollLeft || 0;
              pos.top -= body.scrollTop || 0;
              handler(selfPointer.getTouchesByEvent(event, pos));
              event.stopPropagation();
              event.preventDefault();
            }), false);
          };
          for (var eventName in _touchEventsMap) _loop2(eventName);
        }
        this._registerKeyboardEvent();
        this._registerAccelerometerEvent();
        this._isRegisterEvent = true;
      },
      _registerKeyboardEvent: function() {},
      _registerAccelerometerEvent: function() {},
      update: function(dt) {
        if (this._accelCurTime > this._accelInterval) {
          this._accelCurTime -= this._accelInterval;
          eventManager.dispatchEvent(new cc.Event.EventAcceleration(this._acceleration));
        }
        this._accelCurTime += dt;
      }
    };
    js.get(cc, "inputManager", (function() {
      cc.warnID(1405, "cc.inputManager", "cc.systemEvent");
      return inputManager;
    }));
    module.exports = inputManager;
  }), {
    "../event-manager": 110,
    "../platform/js": 196,
    "./CCMacro": 180,
    "./CCSys": 184
  } ],
  180: [ (function(require, module, exports) {
    require("./_CCClass");
    cc.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: 1e3,
      dpadRight: 1001,
      dpadUp: 1003,
      dpadDown: 1004,
      dpadCenter: 1005
    };
    cc.ImageFormat = cc.Enum({
      JPG: 0,
      PNG: 1,
      TIFF: 2,
      WEBP: 3,
      PVR: 4,
      ETC: 5,
      S3TC: 6,
      ATITC: 7,
      TGA: 8,
      RAWDATA: 9,
      UNKNOWN: 10
    });
    cc.getImageFormatByData = function(imgData) {
      if (imgData.length > 8 && 137 === imgData[0] && 80 === imgData[1] && 78 === imgData[2] && 71 === imgData[3] && 13 === imgData[4] && 10 === imgData[5] && 26 === imgData[6] && 10 === imgData[7]) return cc.ImageFormat.PNG;
      if (imgData.length > 2 && (73 === imgData[0] && 73 === imgData[1] || 77 === imgData[0] && 77 === imgData[1] || 255 === imgData[0] && 216 === imgData[1])) return cc.ImageFormat.TIFF;
      return cc.ImageFormat.UNKNOWN;
    };
    cc.macro = {
      INVALID_INDEX: -1,
      NODE_TAG_INVALID: -1,
      PI: Math.PI,
      PI2: 2 * Math.PI,
      FLT_MAX: parseFloat("3.402823466e+38F"),
      FLT_MIN: parseFloat("1.175494351e-38F"),
      RAD: Math.PI / 180,
      DEG: 180 / Math.PI,
      UINT_MAX: 4294967295,
      REPEAT_FOREVER: Number.MAX_VALUE - 1,
      FLT_EPSILON: 1.192092896e-7,
      ONE: 1,
      ZERO: 0,
      SRC_ALPHA: 770,
      SRC_ALPHA_SATURATE: 776,
      SRC_COLOR: 768,
      DST_ALPHA: 772,
      DST_COLOR: 774,
      ONE_MINUS_SRC_ALPHA: 771,
      ONE_MINUS_SRC_COLOR: 769,
      ONE_MINUS_DST_ALPHA: 773,
      ONE_MINUS_DST_COLOR: 775,
      ONE_MINUS_CONSTANT_ALPHA: 32772,
      ONE_MINUS_CONSTANT_COLOR: 32770,
      LINEAR: 9729,
      BLEND_DST: 771,
      WEB_ORIENTATION_PORTRAIT: 0,
      WEB_ORIENTATION_LANDSCAPE_LEFT: -90,
      WEB_ORIENTATION_PORTRAIT_UPSIDE_DOWN: 180,
      WEB_ORIENTATION_LANDSCAPE_RIGHT: 90,
      ORIENTATION_PORTRAIT: 1,
      ORIENTATION_LANDSCAPE: 2,
      ORIENTATION_AUTO: 3,
      DENSITYDPI_DEVICE: "device-dpi",
      DENSITYDPI_HIGH: "high-dpi",
      DENSITYDPI_MEDIUM: "medium-dpi",
      DENSITYDPI_LOW: "low-dpi",
      VERTEX_ATTRIB_FLAG_NONE: 0,
      VERTEX_ATTRIB_FLAG_POSITION: 1,
      VERTEX_ATTRIB_FLAG_COLOR: 2,
      VERTEX_ATTRIB_FLAG_TEX_COORDS: 4,
      VERTEX_ATTRIB_FLAG_POS_COLOR_TEX: 7,
      GL_ALL: 0,
      VERTEX_ATTRIB_POSITION: 0,
      VERTEX_ATTRIB_COLOR: 1,
      VERTEX_ATTRIB_TEX_COORDS: 2,
      VERTEX_ATTRIB_MAX: 3,
      UNIFORM_PMATRIX: 0,
      UNIFORM_MVMATRIX: 1,
      UNIFORM_MVPMATRIX: 2,
      UNIFORM_TIME: 3,
      UNIFORM_SINTIME: 4,
      UNIFORM_COSTIME: 5,
      UNIFORM_RANDOM01: 6,
      UNIFORM_SAMPLER: 7,
      UNIFORM_MAX: 8,
      SHADER_POSITION_TEXTURECOLOR: "ShaderPositionTextureColor",
      SHADER_SPRITE_POSITION_TEXTURECOLOR: "ShaderSpritePositionTextureColor",
      SHADER_POSITION_TEXTURECOLORALPHATEST: "ShaderPositionTextureColorAlphaTest",
      SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST: "ShaderSpritePositionTextureColorAlphaTest",
      SHADER_POSITION_COLOR: "ShaderPositionColor",
      SHADER_SPRITE_POSITION_COLOR: "ShaderSpritePositionColor",
      SHADER_POSITION_TEXTURE: "ShaderPositionTexture",
      SHADER_POSITION_TEXTURE_UCOLOR: "ShaderPositionTexture_uColor",
      SHADER_POSITION_TEXTUREA8COLOR: "ShaderPositionTextureA8Color",
      SHADER_POSITION_UCOLOR: "ShaderPosition_uColor",
      SHADER_POSITION_LENGTHTEXTURECOLOR: "ShaderPositionLengthTextureColor",
      UNIFORM_PMATRIX_S: "CC_PMatrix",
      UNIFORM_MVMATRIX_S: "CC_MVMatrix",
      UNIFORM_MVPMATRIX_S: "CC_MVPMatrix",
      UNIFORM_TIME_S: "CC_Time",
      UNIFORM_SINTIME_S: "CC_SinTime",
      UNIFORM_COSTIME_S: "CC_CosTime",
      UNIFORM_RANDOM01_S: "CC_Random01",
      UNIFORM_SAMPLER_S: "CC_Texture0",
      UNIFORM_ALPHA_TEST_VALUE_S: "CC_alpha_value",
      ATTRIBUTE_NAME_COLOR: "a_color",
      ATTRIBUTE_NAME_POSITION: "a_position",
      ATTRIBUTE_NAME_TEX_COORD: "a_texCoord",
      ITEM_SIZE: 32,
      CURRENT_ITEM: 3233828865,
      ZOOM_ACTION_TAG: 3233828866,
      NORMAL_TAG: 8801,
      SELECTED_TAG: 8802,
      DISABLE_TAG: 8803,
      FIX_ARTIFACTS_BY_STRECHING_TEXEL: 0,
      FIX_ARTIFACTS_BY_STRECHING_TEXEL_TMX: 1,
      DIRECTOR_STATS_POSITION: cc.p(0, 0),
      DIRECTOR_FPS_INTERVAL: .5,
      COCOSNODE_RENDER_SUBPIXEL: 1,
      SPRITEBATCHNODE_RENDER_SUBPIXEL: 1,
      AUTO_PREMULTIPLIED_ALPHA_FOR_PNG: 0,
      OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA: 0,
      TEXTURE_NPOT_SUPPORT: 0,
      USE_LA88_LABELS: 1,
      SPRITE_DEBUG_DRAW: 0,
      LABELBMFONT_DEBUG_DRAW: 0,
      LABELATLAS_DEBUG_DRAW: 0,
      ENABLE_STACKABLE_ACTIONS: 1,
      ENABLE_GL_STATE_CACHE: 1,
      TOUCH_TIMEOUT: 5e3,
      BATCH_VERTEX_COUNT: 2e4,
      ENABLE_GC_FOR_NATIVE_OBJECTS: true,
      ENABLE_TILEDMAP_CULLING: true,
      DOWNLOAD_MAX_CONCURRENT: 64,
      ENABLE_TRANSPARENT_CANVAS: false
    };
    var ENABLE_CULLING = true;
    cc.defineGetterSetter(cc.macro, "ENABLE_CULLING", (function() {
      return ENABLE_CULLING;
    }), (function(val) {
      ENABLE_CULLING = val;
      var scene = cc.director.getScene();
      if (!scene) return;
      false;
      scene._sgNode._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.cullingDirty);
      cc.renderer.childrenOrderDirty = true;
    }));
    cc.defineGetterSetter(cc.macro, "BLEND_SRC", (function() {
      return cc._renderType === cc.game.RENDER_TYPE_WEBGL && cc.macro.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA ? cc.macro.ONE : cc.macro.SRC_ALPHA;
    }));
    cc.lerp = function(a, b, r) {
      return a + (b - a) * r;
    };
    cc.rand = function() {
      return 16777215 * Math.random();
    };
    cc.randomMinus1To1 = function() {
      return 2 * (Math.random() - .5);
    };
    cc.random0To1 = Math.random;
    cc.degreesToRadians = function(angle) {
      return angle * cc.macro.RAD;
    };
    cc.radiansToDegrees = function(angle) {
      return angle * cc.macro.DEG;
    };
    cc.nodeDrawSetup = function(node) {
      if (node._shaderProgram) {
        node._shaderProgram.use();
        node._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4();
      }
    };
    cc.incrementGLDraws = function(addNumber) {
      cc.g_NumberOfDraws += addNumber;
    };
    cc.checkGLErrorDebug = function() {
      if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
        var _error = cc._renderContext.getError();
        _error && cc.logID(2400, _error);
      }
    };
    module.exports = cc.macro;
  }), {
    "./_CCClass": 187
  } ],
  181: [ (function(require, module, exports) {
    var JS = require("./js");
    var CCClass = require("./CCClass");
    var Destroyed = 1;
    var RealDestroyed = 2;
    var ToDestroy = 4;
    var DontSave = 8;
    var EditorOnly = 16;
    var Dirty = 32;
    var DontDestroy = 64;
    var Destroying = 128;
    var Deactivating = 256;
    var IsOnEnableCalled = 2048;
    var IsEditorOnEnableCalled = 4096;
    var IsPreloadStarted = 8192;
    var IsOnLoadCalled = 16384;
    var IsOnLoadStarted = 32768;
    var IsStartCalled = 65536;
    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);
    function CCObject() {
      this._name = "";
      this._objFlags = 0;
    }
    CCClass.fastDefine("cc.Object", CCObject, {
      _name: "",
      _objFlags: 0
    });
    JS.value(CCObject, "Flags", {
      Destroyed: Destroyed,
      DontSave: DontSave,
      EditorOnly: EditorOnly,
      Dirty: Dirty,
      DontDestroy: DontDestroy,
      PersistentMask: PersistentMask,
      Destroying: Destroying,
      Deactivating: Deactivating,
      IsPreloadStarted: IsPreloadStarted,
      IsOnLoadStarted: IsOnLoadStarted,
      IsOnLoadCalled: IsOnLoadCalled,
      IsOnEnableCalled: IsOnEnableCalled,
      IsStartCalled: IsStartCalled,
      IsEditorOnEnableCalled: IsEditorOnEnableCalled,
      IsPositionLocked: IsPositionLocked,
      IsRotationLocked: IsRotationLocked,
      IsScaleLocked: IsScaleLocked,
      IsAnchorLocked: IsAnchorLocked,
      IsSizeLocked: IsSizeLocked
    });
    var objectsToDestroy = [];
    function deferredDestroy() {
      var deleteCount = objectsToDestroy.length;
      for (var i = 0; i < deleteCount; ++i) {
        var obj = objectsToDestroy[i];
        obj._objFlags & Destroyed || obj._destroyImmediate();
      }
      deleteCount === objectsToDestroy.length ? objectsToDestroy.length = 0 : objectsToDestroy.splice(0, deleteCount);
      false;
    }
    JS.value(CCObject, "_deferredDestroy", deferredDestroy);
    false;
    var prototype = CCObject.prototype;
    JS.getset(prototype, "name", (function() {
      return this._name;
    }), (function(value) {
      this._name = value;
    }));
    JS.get(prototype, "isValid", (function() {
      return !(this._objFlags & Destroyed);
    }));
    false, false;
    var deferredDestroyTimer = null;
    prototype.destroy = function() {
      if (this._objFlags & Destroyed) {
        cc.warnID(5e3);
        return false;
      }
      if (this._objFlags & ToDestroy) return false;
      this._objFlags |= ToDestroy;
      objectsToDestroy.push(this);
      false;
      return true;
    };
    false, false;
    function compileDestruct(obj, ctor) {
      var key, propsToReset = {};
      for (key in obj) if (obj.hasOwnProperty(key)) switch (typeof obj[key]) {
       case "string":
        propsToReset[key] = "";
        break;

       case "object":
       case "function":
        propsToReset[key] = null;
      }
      if (cc.Class._isCCClass(ctor)) {
        var attrs = cc.Class.Attr.getClassAttrs(ctor);
        var propList = ctor.__props__;
        for (var i = 0; i < propList.length; i++) {
          key = propList[i];
          var attrKey = key + cc.Class.Attr.DELIMETER + "default";
          if (attrKey in attrs) switch (typeof attrs[attrKey]) {
           case "string":
            propsToReset[key] = "";
            break;

           case "object":
           case "function":
            propsToReset[key] = null;
            break;

           case "undefined":
            propsToReset[key] = void 0;
          }
        }
      }
      var skipId = obj instanceof cc._BaseNode || obj instanceof cc.Component;
      true;
      var func = "";
      for (key in propsToReset) {
        if (skipId && "_id" === key) continue;
        var statement;
        statement = CCClass.IDENTIFIER_RE.test(key) ? "o." + key + "=" : "o[" + CCClass.escapeForJS(key) + "]=";
        var val = propsToReset[key];
        "" === val && (val = '""');
        func += statement + val + ";\n";
      }
      return Function("o", func);
    }
    prototype._destruct = function() {
      var ctor = this.constructor;
      var destruct = ctor.__destruct__;
      if (!destruct) {
        destruct = compileDestruct(this, ctor);
        JS.value(ctor, "__destruct__", destruct, true);
      }
      destruct(this);
    };
    prototype._onPreDestroy = null;
    prototype._destroyImmediate = function() {
      if (this._objFlags & Destroyed) {
        cc.errorID(5e3);
        return;
      }
      this._onPreDestroy && this._onPreDestroy();
      true;
      this._destruct();
      this._objFlags |= Destroyed;
    };
    false;
    prototype._deserialize = null;
    cc.isValid = function(value) {
      return "object" === typeof value ? !!value && !(value._objFlags & Destroyed) : "undefined" !== typeof value;
    };
    false, false;
    cc.Object = module.exports = CCObject;
  }), {
    "./CCClass": 175,
    "./js": 196
  } ],
  182: [ (function(require, module, exports) {
    cc.SAXParser = cc._Class.extend({
      ctor: function() {
        if (window.DOMParser) {
          this._isSupportDOMParser = true;
          this._parser = new DOMParser();
        } else {
          this._isSupportDOMParser = false;
          this._parser = null;
        }
      },
      parse: function(xmlTxt) {
        return this._parseXML(xmlTxt);
      },
      _parseXML: function(textxml) {
        var xmlDoc;
        if (this._isSupportDOMParser) xmlDoc = this._parser.parseFromString(textxml, "text/xml"); else {
          xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
          xmlDoc.async = "false";
          xmlDoc.loadXML(textxml);
        }
        return xmlDoc;
      }
    });
    cc.PlistParser = cc.SAXParser.extend({
      parse: function(xmlTxt) {
        var xmlDoc = this._parseXML(xmlTxt);
        var plist = xmlDoc.documentElement;
        if ("plist" !== plist.tagName) {
          cc.warnID(5100);
          return {};
        }
        var node = null;
        for (var i = 0, len = plist.childNodes.length; i < len; i++) {
          node = plist.childNodes[i];
          if (1 === node.nodeType) break;
        }
        xmlDoc = null;
        return this._parseNode(node);
      },
      _parseNode: function(node) {
        var data = null, tagName = node.tagName;
        if ("dict" === tagName) data = this._parseDict(node); else if ("array" === tagName) data = this._parseArray(node); else if ("string" === tagName) if (1 === node.childNodes.length) data = node.firstChild.nodeValue; else {
          data = "";
          for (var i = 0; i < node.childNodes.length; i++) data += node.childNodes[i].nodeValue;
        } else "false" === tagName ? data = false : "true" === tagName ? data = true : "real" === tagName ? data = parseFloat(node.firstChild.nodeValue) : "integer" === tagName && (data = parseInt(node.firstChild.nodeValue, 10));
        return data;
      },
      _parseArray: function(node) {
        var data = [];
        for (var i = 0, len = node.childNodes.length; i < len; i++) {
          var child = node.childNodes[i];
          if (1 !== child.nodeType) continue;
          data.push(this._parseNode(child));
        }
        return data;
      },
      _parseDict: function(node) {
        var data = {};
        var key = null;
        for (var i = 0, len = node.childNodes.length; i < len; i++) {
          var child = node.childNodes[i];
          if (1 !== child.nodeType) continue;
          "key" === child.tagName ? key = child.firstChild.nodeValue : data[key] = this._parseNode(child);
        }
        return data;
      }
    });
    cc.saxParser = new cc.SAXParser();
    cc.plistParser = new cc.PlistParser();
  }), {} ],
  183: [ (function(require, module, exports) {
    cc.screen = {
      _supportsFullScreen: false,
      _preOnFullScreenChange: 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() {
        this._fn = {};
        var i, l, val, map = this._fnMap, valL;
        for (i = 0, l = map.length; i < l; i++) {
          val = map[i];
          if (val && val[1] in document) {
            for (i = 0, valL = val.length; i < valL; i++) this._fn[map[0][i]] = val[i];
            break;
          }
        }
        this._supportsFullScreen = "undefined" !== typeof this._fn.requestFullscreen;
        this._touchEvent = "ontouchstart" in window ? "touchstart" : "mousedown";
      },
      fullScreen: function() {
        return !!this._supportsFullScreen && (void 0 !== document[this._fn.fullscreenElement] && null !== document[this._fn.fullscreenElement]);
      },
      requestFullScreen: function(element, onFullScreenChange) {
        if (!this._supportsFullScreen) return;
        element = element || document.documentElement;
        if (onFullScreenChange) {
          var eventName = this._fn.fullscreenchange;
          this._preOnFullScreenChange && document.removeEventListener(eventName, this._preOnFullScreenChange);
          this._preOnFullScreenChange = onFullScreenChange;
          document.addEventListener(eventName, onFullScreenChange, false);
        }
        return element[this._fn.requestFullscreen]();
      },
      exitFullScreen: function() {
        return !this._supportsFullScreen || document[this._fn.exitFullscreen]();
      },
      autoFullScreen: function(element, onFullScreenChange) {
        element = element || document.body;
        var touchTarget = cc.game.canvas || element;
        var theScreen = this;
        function callback() {
          touchTarget.removeEventListener(theScreen._touchEvent, callback);
          theScreen.requestFullScreen(element, onFullScreenChange);
        }
        this.requestFullScreen(element, onFullScreenChange);
        touchTarget.addEventListener(this._touchEvent, callback);
      }
    };
    cc.screen.init();
  }), {} ],
  184: [ (function(require, module, exports) {
    if (cc.sys) return;
    cc.sys = {};
    var sys = cc.sys;
    sys.LANGUAGE_ENGLISH = "en";
    sys.LANGUAGE_CHINESE = "zh";
    sys.LANGUAGE_FRENCH = "fr";
    sys.LANGUAGE_ITALIAN = "it";
    sys.LANGUAGE_GERMAN = "de";
    sys.LANGUAGE_SPANISH = "es";
    sys.LANGUAGE_DUTCH = "du";
    sys.LANGUAGE_RUSSIAN = "ru";
    sys.LANGUAGE_KOREAN = "ko";
    sys.LANGUAGE_JAPANESE = "ja";
    sys.LANGUAGE_HUNGARIAN = "hu";
    sys.LANGUAGE_PORTUGUESE = "pt";
    sys.LANGUAGE_ARABIC = "ar";
    sys.LANGUAGE_NORWEGIAN = "no";
    sys.LANGUAGE_POLISH = "pl";
    sys.LANGUAGE_TURKISH = "tr";
    sys.LANGUAGE_UKRAINIAN = "uk";
    sys.LANGUAGE_ROMANIAN = "ro";
    sys.LANGUAGE_BULGARIAN = "bg";
    sys.LANGUAGE_UNKNOWN = "unknown";
    sys.OS_IOS = "iOS";
    sys.OS_ANDROID = "Android";
    sys.OS_WINDOWS = "Windows";
    sys.OS_MARMALADE = "Marmalade";
    sys.OS_LINUX = "Linux";
    sys.OS_BADA = "Bada";
    sys.OS_BLACKBERRY = "Blackberry";
    sys.OS_OSX = "OS X";
    sys.OS_WP8 = "WP8";
    sys.OS_WINRT = "WINRT";
    sys.OS_UNKNOWN = "Unknown";
    sys.UNKNOWN = -1;
    sys.WIN32 = 0;
    sys.LINUX = 1;
    sys.MACOS = 2;
    sys.ANDROID = 3;
    sys.IPHONE = 4;
    sys.IPAD = 5;
    sys.BLACKBERRY = 6;
    sys.NACL = 7;
    sys.EMSCRIPTEN = 8;
    sys.TIZEN = 9;
    sys.WINRT = 10;
    sys.WP8 = 11;
    sys.MOBILE_BROWSER = 100;
    sys.DESKTOP_BROWSER = 101;
    sys.EDITOR_PAGE = 102;
    sys.EDITOR_CORE = 103;
    sys.WECHAT_GAME = 104;
    sys.BROWSER_TYPE_WECHAT = "wechat";
    sys.BROWSER_TYPE_WECHAT_GAME = "wechatgame";
    sys.BROWSER_TYPE_ANDROID = "androidbrowser";
    sys.BROWSER_TYPE_IE = "ie";
    sys.BROWSER_TYPE_QQ = "qqbrowser";
    sys.BROWSER_TYPE_MOBILE_QQ = "mqqbrowser";
    sys.BROWSER_TYPE_UC = "ucbrowser";
    sys.BROWSER_TYPE_360 = "360browser";
    sys.BROWSER_TYPE_BAIDU_APP = "baiduboxapp";
    sys.BROWSER_TYPE_BAIDU = "baidubrowser";
    sys.BROWSER_TYPE_MAXTHON = "maxthon";
    sys.BROWSER_TYPE_OPERA = "opera";
    sys.BROWSER_TYPE_OUPENG = "oupeng";
    sys.BROWSER_TYPE_MIUI = "miuibrowser";
    sys.BROWSER_TYPE_FIREFOX = "firefox";
    sys.BROWSER_TYPE_SAFARI = "safari";
    sys.BROWSER_TYPE_CHROME = "chrome";
    sys.BROWSER_TYPE_LIEBAO = "liebao";
    sys.BROWSER_TYPE_QZONE = "qzone";
    sys.BROWSER_TYPE_SOUGOU = "sogou";
    sys.BROWSER_TYPE_UNKNOWN = "unknown";
    sys.isNative = false;
    sys.isBrowser = "object" === typeof window && "object" === typeof document && true;
    cc.create3DContext = function(canvas, opt_attribs, opt_contextType) {
      if (!opt_contextType) return cc.create3DContext(canvas, opt_attribs, "webgl") || cc.create3DContext(canvas, opt_attribs, "experimental-webgl") || cc.create3DContext(canvas, opt_attribs, "webkit-3d") || cc.create3DContext(canvas, opt_attribs, "moz-webgl") || null;
      try {
        return canvas.getContext(opt_contextType, opt_attribs);
      } catch (e) {
        return null;
      }
    };
    false;
    var env;
    var version;
    var w;
    var h;
    var ratio;
    false;
    {
      var win = window, nav = win.navigator, doc = document, docEle = doc.documentElement;
      var ua = nav.userAgent.toLowerCase();
      false;
      sys.isMobile = /mobile|android|iphone|ipad/.test(ua);
      sys.platform = sys.isMobile ? sys.MOBILE_BROWSER : sys.DESKTOP_BROWSER;
      var currLanguage = nav.language;
      currLanguage = currLanguage || nav.browserLanguage;
      currLanguage = currLanguage ? currLanguage.split("-")[0] : sys.LANGUAGE_ENGLISH;
      sys.language = currLanguage;
      var isAndroid = false, iOS = false, osVersion = "", osMainVersion = 0;
      var uaResult = /android (\d+(?:\.\d+)+)/i.exec(ua) || /android (\d+(?:\.\d+)+)/i.exec(nav.platform);
      if (uaResult) {
        isAndroid = true;
        osVersion = uaResult[1] || "";
        osMainVersion = parseInt(osVersion) || 0;
      }
      uaResult = /(iPad|iPhone|iPod).*OS ((\d+_?){2,3})/i.exec(ua);
      if (uaResult) {
        iOS = true;
        osVersion = uaResult[2] || "";
        osMainVersion = parseInt(osVersion) || 0;
      } else if (/(iPhone|iPad|iPod)/.exec(nav.platform)) {
        iOS = true;
        osVersion = "";
        osMainVersion = 0;
      }
      var osName = sys.OS_UNKNOWN;
      -1 !== nav.appVersion.indexOf("Win") ? osName = sys.OS_WINDOWS : iOS ? osName = sys.OS_IOS : -1 !== nav.appVersion.indexOf("Mac") ? osName = sys.OS_OSX : -1 !== nav.appVersion.indexOf("X11") && -1 === nav.appVersion.indexOf("Linux") ? osName = sys.OS_UNIX : isAndroid ? osName = sys.OS_ANDROID : -1 === nav.appVersion.indexOf("Linux") && -1 === ua.indexOf("ubuntu") || (osName = sys.OS_LINUX);
      sys.os = osName;
      sys.osVersion = osVersion;
      sys.osMainVersion = osMainVersion;
      sys.browserType = sys.BROWSER_TYPE_UNKNOWN;
      (function() {
        var typeReg1 = /mqqbrowser|micromessenger|qq|sogou|qzone|liebao|maxthon|ucbrowser|360 aphone|360browser|baiduboxapp|baidubrowser|maxthon|mxbrowser|miuibrowser/i;
        var typeReg2 = /qqbrowser|chrome|safari|firefox|trident|opera|opr\/|oupeng/i;
        var browserTypes = typeReg1.exec(ua);
        browserTypes || (browserTypes = typeReg2.exec(ua));
        var browserType = browserTypes ? browserTypes[0].toLowerCase() : sys.BROWSER_TYPE_UNKNOWN;
        false;
        "micromessenger" === browserType ? browserType = sys.BROWSER_TYPE_WECHAT : "safari" === browserType && isAndroid ? browserType = sys.BROWSER_TYPE_ANDROID : "qq" === browserType && ua.match(/android.*applewebkit/i) ? browserType = sys.BROWSER_TYPE_ANDROID : "trident" === browserType ? browserType = sys.BROWSER_TYPE_IE : "360 aphone" === browserType ? browserType = sys.BROWSER_TYPE_360 : "mxbrowser" === browserType ? browserType = sys.BROWSER_TYPE_MAXTHON : "opr/" === browserType && (browserType = sys.BROWSER_TYPE_OPERA);
        sys.browserType = browserType;
      })();
      sys.browserVersion = "";
      (function() {
        var versionReg1 = /(mqqbrowser|micromessenger|qq|sogou|qzone|liebao|maxthon|uc|360 aphone|360|baiduboxapp|baidu|maxthon|mxbrowser|miui)(mobile)?(browser)?\/?([\d.]+)/i;
        var versionReg2 = /(qqbrowser|chrome|safari|firefox|trident|opera|opr\/|oupeng)(mobile)?(browser)?\/?([\d.]+)/i;
        var tmp = ua.match(versionReg1);
        tmp || (tmp = ua.match(versionReg2));
        sys.browserVersion = tmp ? tmp[4] : "";
      })();
      var w = window.innerWidth || document.documentElement.clientWidth;
      var h = window.innerHeight || document.documentElement.clientHeight;
      var ratio = window.devicePixelRatio || 1;
      sys.windowPixelResolution = {
        width: ratio * w,
        height: ratio * h
      };
      sys._checkWebGLRenderMode = function() {
        if (cc._renderType !== cc.game.RENDER_TYPE_WEBGL) throw new Error("This feature supports WebGL render mode only.");
      };
      var _tmpCanvas1 = document.createElement("canvas"), _tmpCanvas2 = document.createElement("canvas");
      sys._supportCanvasNewBlendModes = (function() {
        var canvas = _tmpCanvas1;
        canvas.width = 1;
        canvas.height = 1;
        var context = canvas.getContext("2d");
        context.fillStyle = "#000";
        context.fillRect(0, 0, 1, 1);
        context.globalCompositeOperation = "multiply";
        var canvas2 = _tmpCanvas2;
        canvas2.width = 1;
        canvas2.height = 1;
        var context2 = canvas2.getContext("2d");
        context2.fillStyle = "#fff";
        context2.fillRect(0, 0, 1, 1);
        context.drawImage(canvas2, 0, 0, 1, 1);
        return 0 === context.getImageData(0, 0, 1, 1).data[0];
      })();
      if (cc.sys.isMobile) {
        var fontStyle = document.createElement("style");
        fontStyle.type = "text/css";
        document.body.appendChild(fontStyle);
        fontStyle.textContent = "body,canvas,div{ -moz-user-select: none;-webkit-user-select: none;-ms-user-select: none;-khtml-user-select: none;-webkit-tap-highlight-color:rgba(0,0,0,0);}";
      }
      try {
        var localStorage = sys.localStorage = win.localStorage;
        localStorage.setItem("storage", "");
        localStorage.removeItem("storage");
        localStorage = null;
      } catch (e) {
        var warn = function() {
          cc.warnID(5200);
        };
        sys.localStorage = {
          getItem: warn,
          setItem: warn,
          removeItem: warn,
          clear: warn
        };
      }
      var _supportWebp = _tmpCanvas1.toDataURL("image/webp").startsWith("data:image/webp");
      var _supportCanvas = !!_tmpCanvas1.getContext("2d");
      var _supportWebGL = false;
      if (win.WebGLRenderingContext) {
        cc.create3DContext(document.createElement("CANVAS")) && (_supportWebGL = true);
        if (_supportWebGL && sys.os === sys.OS_ANDROID) {
          var browserVer = parseFloat(sys.browserVersion);
          switch (sys.browserType) {
           case sys.BROWSER_TYPE_MOBILE_QQ:
           case sys.BROWSER_TYPE_BAIDU:
           case sys.BROWSER_TYPE_BAIDU_APP:
            _supportWebGL = browserVer >= 6.2;
            break;

           case sys.BROWSER_TYPE_ANDROID:
            sys.osMainVersion && sys.osMainVersion >= 5 && (_supportWebGL = true);
            break;

           case sys.BROWSER_TYPE_CHROME:
            _supportWebGL = browserVer >= 30;
            break;

           case sys.BROWSER_TYPE_UC:
            _supportWebGL = browserVer > 11;

           case sys.BROWSER_TYPE_360:
            _supportWebGL = false;
          }
        }
      }
      var capabilities = sys.capabilities = {
        canvas: _supportCanvas,
        opengl: _supportWebGL,
        webp: _supportWebp
      };
      (void 0 !== docEle["ontouchstart"] || void 0 !== doc["ontouchstart"] || nav.msPointerEnabled) && (capabilities["touches"] = true);
      void 0 !== docEle["onmouseup"] && (capabilities["mouse"] = true);
      void 0 !== docEle["onkeyup"] && (capabilities["keyboard"] = true);
      (win.DeviceMotionEvent || win.DeviceOrientationEvent) && (capabilities["accelerometer"] = true);
      var __audioSupport;
      (function() {
        var DEBUG = false;
        var version = sys.browserVersion;
        var supportWebAudio = !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext);
        __audioSupport = {
          ONLY_ONE: false,
          WEB_AUDIO: supportWebAudio,
          DELAY_CREATE_CTX: false
        };
        sys.os === sys.OS_IOS && (__audioSupport.USE_LOADER_EVENT = "loadedmetadata");
        if (sys.browserType === sys.BROWSER_TYPE_FIREFOX) {
          __audioSupport.DELAY_CREATE_CTX = true;
          __audioSupport.USE_LOADER_EVENT = "canplay";
        }
        sys.os === sys.OS_ANDROID && sys.browserType === sys.BROWSER_TYPE_UC && (__audioSupport.ONE_SOURCE = true);
        DEBUG && setTimeout((function() {
          cc.log("browse type: " + sys.browserType);
          cc.log("browse version: " + version);
          cc.log("MULTI_CHANNEL: " + __audioSupport.MULTI_CHANNEL);
          cc.log("WEB_AUDIO: " + __audioSupport.WEB_AUDIO);
          cc.log("AUTOPLAY: " + __audioSupport.AUTOPLAY);
        }), 0);
      })();
      try {
        if (__audioSupport.WEB_AUDIO) {
          __audioSupport.context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
          __audioSupport.DELAY_CREATE_CTX && setTimeout((function() {
            __audioSupport.context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
          }), 0);
        }
      } catch (error) {
        __audioSupport.WEB_AUDIO = false;
        cc.logID(5201);
      }
      function detectAudioFormat() {
        var formatSupport = [];
        var audio = document.createElement("audio");
        if (audio.canPlayType) {
          var ogg = audio.canPlayType('audio/ogg; codecs="vorbis"');
          ogg && formatSupport.push(".ogg");
          var mp3 = audio.canPlayType("audio/mpeg");
          mp3 && formatSupport.push(".mp3");
          var wav = audio.canPlayType('audio/wav; codecs="1"');
          wav && formatSupport.push(".wav");
          var mp4 = audio.canPlayType("audio/mp4");
          mp4 && formatSupport.push(".mp4");
          var m4a = audio.canPlayType("audio/x-m4a");
          m4a && formatSupport.push(".m4a");
        }
        return formatSupport;
      }
      __audioSupport.format = detectAudioFormat();
      sys.__audioSupport = __audioSupport;
    }
    sys.garbageCollect = function() {};
    sys.dumpRoot = function() {};
    sys.restartVM = function() {};
    sys.cleanScript = function(jsfile) {};
    sys.isObjectValid = function(obj) {
      return !!obj;
    };
    sys.dump = function() {
      var self = this;
      var str = "";
      str += "isMobile : " + self.isMobile + "\r\n";
      str += "language : " + self.language + "\r\n";
      str += "browserType : " + self.browserType + "\r\n";
      str += "browserVersion : " + self.browserVersion + "\r\n";
      str += "capabilities : " + JSON.stringify(self.capabilities) + "\r\n";
      str += "os : " + self.os + "\r\n";
      str += "osVersion : " + self.osVersion + "\r\n";
      str += "platform : " + self.platform + "\r\n";
      str += "Using " + (cc._renderType === cc.game.RENDER_TYPE_WEBGL ? "WEBGL" : "CANVAS") + " renderer.\r\n";
      cc.log(str);
    };
    sys.openURL = function(url) {
      window.open(url);
    };
    sys.now = function() {
      return Date.now ? Date.now() : +new Date();
    };
    module.exports = sys;
  }), {} ],
  185: [ (function(require, module, exports) {
    var eventManager = require("../event-manager");
    var __BrowserGetter = {
      init: function() {
        cc.sys.platform !== cc.sys.WECHAT_GAME && (this.html = document.getElementsByTagName("html")[0]);
      },
      availWidth: function(frame) {
        return frame && frame !== this.html ? frame.clientWidth : window.innerWidth;
      },
      availHeight: function(frame) {
        return frame && frame !== this.html ? frame.clientHeight : window.innerHeight;
      },
      meta: {
        width: "device-width"
      },
      adaptationType: cc.sys.browserType
    };
    window.navigator.userAgent.indexOf("OS 8_1_") > -1 && (__BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_MIUI);
    cc.sys.os === cc.sys.OS_IOS && (__BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_SAFARI);
    false;
    switch (__BrowserGetter.adaptationType) {
     case cc.sys.BROWSER_TYPE_SAFARI:
      __BrowserGetter.meta["minimal-ui"] = "true";
      __BrowserGetter.availWidth = function(frame) {
        return frame.clientWidth;
      };
      __BrowserGetter.availHeight = function(frame) {
        return frame.clientHeight;
      };
      break;

     case cc.sys.BROWSER_TYPE_CHROME:
      __BrowserGetter.__defineGetter__("target-densitydpi", (function() {
        return cc.view._targetDensityDPI;
      }));
      break;

     case cc.sys.BROWSER_TYPE_SOUGOU:
     case cc.sys.BROWSER_TYPE_UC:
      __BrowserGetter.availWidth = function(frame) {
        return frame.clientWidth;
      };
      __BrowserGetter.availHeight = function(frame) {
        return frame.clientHeight;
      };
      break;

     case cc.sys.BROWSER_TYPE_MIUI:
      __BrowserGetter.init = function(view) {
        if (view.__resizeWithBrowserSize) return;
        var resize = function() {
          view.setDesignResolutionSize(view._designResolutionSize.width, view._designResolutionSize.height, view._resolutionPolicy);
          window.removeEventListener("resize", resize, false);
        };
        window.addEventListener("resize", resize, false);
      };
      break;

     case cc.sys.BROWSER_TYPE_WECHAT_GAME:
      __BrowserGetter.availWidth = function() {
        return window.innerWidth;
      };
      __BrowserGetter.availHeight = function() {
        return window.innerHeight;
      };
    }
    var _scissorRect = null;
    var View = cc._Class.extend({
      ctor: function() {
        var _t = this, _strategyer = cc.ContainerStrategy, _strategy = cc.ContentStrategy;
        __BrowserGetter.init(this);
        _t._frameSize = cc.size(0, 0);
        _t._initFrameSize();
        var w = cc.game.canvas.width, h = cc.game.canvas.height;
        _t._designResolutionSize = cc.size(w, h);
        _t._originalDesignResolutionSize = cc.size(w, h);
        _t._viewPortRect = cc.rect(0, 0, w, h);
        _t._visibleRect = cc.rect(0, 0, w, h);
        _t._contentTranslateLeftTop = {
          left: 0,
          top: 0
        };
        _t._autoFullScreen = false;
        _t._devicePixelRatio = 1;
        _t._viewName = "Cocos2dHTML5";
        _t._resizeCallback = null;
        _t._orientationChanging = true;
        _t._resizing = false;
        _t._scaleX = 1;
        _t._originalScaleX = 1;
        _t._scaleY = 1;
        _t._originalScaleY = 1;
        _t._isRotated = false;
        _t._orientation = 3;
        var sys = cc.sys;
        _t.enableRetina(sys.os === sys.OS_IOS || sys.os === sys.OS_OSX);
        cc.visibleRect && cc.visibleRect.init(_t._visibleRect);
        _t._resolutionPolicy = null;
        _t._rpExactFit = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.EXACT_FIT);
        _t._rpShowAll = new cc.ResolutionPolicy(_strategyer.PROPORTION_TO_FRAME, _strategy.SHOW_ALL);
        _t._rpNoBorder = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.NO_BORDER);
        _t._rpFixedHeight = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_HEIGHT);
        _t._rpFixedWidth = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH);
        _t._initialized = false;
        _t._contentTranslateLeftTop = null;
        _t._frameZoomFactor = 1;
        _t.__resizeWithBrowserSize = false;
        _t._isAdjustViewPort = true;
        _t._targetDensityDPI = cc.macro.DENSITYDPI_HIGH;
        _t.enableAntiAlias(true);
      },
      _resizeEvent: function() {
        var view;
        view = this.setDesignResolutionSize ? this : cc.view;
        var prevFrameW = view._frameSize.width, prevFrameH = view._frameSize.height, prevRotated = view._isRotated;
        if (cc.sys.isMobile) {
          var containerStyle = cc.game.container.style, margin = containerStyle.margin;
          containerStyle.margin = "0";
          containerStyle.display = "none";
          view._initFrameSize();
          containerStyle.margin = margin;
          containerStyle.display = "block";
        } else view._initFrameSize();
        if (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;
        width > 0 && view.setDesignResolutionSize(width, height, view._resolutionPolicy);
        view._resizing = false;
        eventManager.dispatchCustomEvent("canvas-resize");
        view._resizeCallback && view._resizeCallback.call();
      },
      _orientationChange: function() {
        cc.view._orientationChanging = true;
        cc.view._resizeEvent();
      },
      setTargetDensityDPI: function(densityDPI) {
        this._targetDensityDPI = densityDPI;
        this._adjustViewportMeta();
      },
      getTargetDensityDPI: function() {
        return this._targetDensityDPI;
      },
      resizeWithBrowserSize: function(enabled) {
        if (enabled) {
          if (!this.__resizeWithBrowserSize) {
            this.__resizeWithBrowserSize = true;
            window.addEventListener("resize", this._resizeEvent);
            window.addEventListener("orientationchange", this._orientationChange);
          }
        } else if (this.__resizeWithBrowserSize) {
          this.__resizeWithBrowserSize = false;
          window.removeEventListener("resize", this._resizeEvent);
          window.removeEventListener("orientationchange", this._orientationChange);
        }
      },
      setResizeCallback: function(callback) {
        "function" !== typeof callback && null != callback || (this._resizeCallback = callback);
      },
      setOrientation: function(orientation) {
        orientation &= cc.macro.ORIENTATION_AUTO;
        if (orientation && this._orientation !== orientation) {
          this._orientation = orientation;
          var designWidth = this._originalDesignResolutionSize.width;
          var designHeight = this._originalDesignResolutionSize.height;
          this.setDesignResolutionSize(designWidth, designHeight, this._resolutionPolicy);
        }
      },
      _initFrameSize: function() {
        var locFrameSize = this._frameSize;
        var w = __BrowserGetter.availWidth(cc.game.frame);
        var h = __BrowserGetter.availHeight(cc.game.frame);
        var isLandscape = w >= h;
        if ((false, !cc.sys.isMobile) || isLandscape && this._orientation & cc.macro.ORIENTATION_LANDSCAPE || !isLandscape && this._orientation & cc.macro.ORIENTATION_PORTRAIT) {
          locFrameSize.width = w;
          locFrameSize.height = h;
          cc.container.style["-webkit-transform"] = "rotate(0deg)";
          cc.container.style.transform = "rotate(0deg)";
          this._isRotated = false;
        } else {
          locFrameSize.width = h;
          locFrameSize.height = w;
          cc.container.style["-webkit-transform"] = "rotate(90deg)";
          cc.container.style.transform = "rotate(90deg)";
          cc.container.style["-webkit-transform-origin"] = "0px 0px 0px";
          cc.container.style.transformOrigin = "0px 0px 0px";
          this._isRotated = true;
        }
        this._orientationChanging && setTimeout((function() {
          cc.view._orientationChanging = false;
        }), 1e3);
      },
      _adjustSizeKeepCanvasSize: function() {
        var designWidth = this._originalDesignResolutionSize.width;
        var designHeight = this._originalDesignResolutionSize.height;
        designWidth > 0 && this.setDesignResolutionSize(designWidth, designHeight, this._resolutionPolicy);
      },
      _setViewportMeta: function(metas, overwrite) {
        var vp = document.getElementById("cocosMetaElement");
        vp && overwrite && document.head.removeChild(vp);
        var elems = document.getElementsByName("viewport"), currentVP = elems ? elems[0] : null, content, key, pattern;
        content = currentVP ? currentVP.content : "";
        vp = vp || document.createElement("meta");
        vp.id = "cocosMetaElement";
        vp.name = "viewport";
        vp.content = "";
        for (key in metas) if (-1 == content.indexOf(key)) content += "," + key + "=" + metas[key]; else if (overwrite) {
          pattern = new RegExp(key + "s*=s*[^,]+");
          content.replace(pattern, key + "=" + metas[key]);
        }
        /^,/.test(content) && (content = content.substr(1));
        vp.content = content;
        currentVP && (currentVP.content = content);
        document.head.appendChild(vp);
      },
      _adjustViewportMeta: function() {
        if (this._isAdjustViewPort && cc.sys.platform !== cc.sys.WECHAT_GAME) {
          this._setViewportMeta(__BrowserGetter.meta, false);
          this._isAdjustViewPort = false;
        }
      },
      _resetScale: function() {
        this._scaleX = this._originalScaleX;
        this._scaleY = this._originalScaleY;
      },
      _adjustSizeToBrowser: function() {},
      initialize: function() {
        this._initialized = true;
      },
      adjustViewPort: function(enabled) {
        this._isAdjustViewPort = enabled;
      },
      enableRetina: function(enabled) {
        this._retinaEnabled = !!enabled;
      },
      isRetinaEnabled: function() {
        return this._retinaEnabled;
      },
      enableAntiAlias: function(enabled) {
        if (this._antiAliasEnabled === enabled) return;
        this._antiAliasEnabled = enabled;
        if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
          var cache = cc.loader._cache;
          for (var key in cache) {
            var item = cache[key];
            var tex = item && item.content instanceof cc.Texture2D ? item.content : null;
            tex && (enabled ? tex.setAntiAliasTexParameters() : tex.setAliasTexParameters());
          }
        } else if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
          var ctx = cc._canvas.getContext("2d");
          ctx.imageSmoothingEnabled = enabled;
          ctx.mozImageSmoothingEnabled = enabled;
          var dirtyRegion = cc.rendererCanvas._dirtyRegion;
          if (dirtyRegion) {
            var oldRegion = new cc.Region();
            oldRegion.setTo(0, 0, cc.visibleRect.width, cc.visibleRect.height);
            dirtyRegion.addRegion(oldRegion);
          }
        }
      },
      isAntiAliasEnabled: function() {
        return this._antiAliasEnabled;
      },
      enableAutoFullScreen: function(enabled) {
        if (enabled && enabled !== this._autoFullScreen && cc.sys.isMobile && cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT) {
          this._autoFullScreen = true;
          cc.screen.autoFullScreen(cc.game.frame);
        } else this._autoFullScreen = false;
      },
      isAutoFullScreenEnabled: function() {
        return this._autoFullScreen;
      },
      isViewReady: function() {
        return cc.game.canvas && cc._renderContext;
      },
      setFrameZoomFactor: function(zoomFactor) {
        this._frameZoomFactor = zoomFactor;
        cc.director.setProjection(cc.director.getProjection());
      },
      setContentTranslateLeftTop: function(offsetLeft, offsetTop) {
        this._contentTranslateLeftTop = {
          left: offsetLeft,
          top: offsetTop
        };
      },
      getContentTranslateLeftTop: function() {
        return this._contentTranslateLeftTop;
      },
      setCanvasSize: function(width, height) {
        var canvas = cc.game.canvas;
        var container = cc.game.container;
        canvas.width = width * this._devicePixelRatio;
        canvas.height = height * this._devicePixelRatio;
        canvas.style.width = width + "px";
        canvas.style.height = height + "px";
        container.style.width = width + "px";
        container.style.height = height + "px";
        this._resizeEvent();
      },
      getCanvasSize: function() {
        return cc.size(cc.game.canvas.width, cc.game.canvas.height);
      },
      getFrameSize: function() {
        return cc.size(this._frameSize.width, this._frameSize.height);
      },
      setFrameSize: function(width, height) {
        this._frameSize.width = width;
        this._frameSize.height = height;
        cc.game.frame.style.width = width + "px";
        cc.game.frame.style.height = height + "px";
        this._resizeEvent();
        cc.director.setProjection(cc.director.getProjection());
      },
      getVisibleSize: function() {
        return cc.size(this._visibleRect.width, this._visibleRect.height);
      },
      getVisibleSizeInPixel: function() {
        return cc.size(this._visibleRect.width * this._scaleX, this._visibleRect.height * this._scaleY);
      },
      getVisibleOrigin: function() {
        return cc.p(this._visibleRect.x, this._visibleRect.y);
      },
      getVisibleOriginInPixel: function() {
        return cc.p(this._visibleRect.x * this._scaleX, this._visibleRect.y * this._scaleY);
      },
      canSetContentScaleFactor: function() {
        return true;
      },
      getResolutionPolicy: function() {
        return this._resolutionPolicy;
      },
      setResolutionPolicy: function(resolutionPolicy) {
        var _t = this;
        if (resolutionPolicy instanceof cc.ResolutionPolicy) _t._resolutionPolicy = resolutionPolicy; else {
          var _locPolicy = cc.ResolutionPolicy;
          resolutionPolicy === _locPolicy.EXACT_FIT && (_t._resolutionPolicy = _t._rpExactFit);
          resolutionPolicy === _locPolicy.SHOW_ALL && (_t._resolutionPolicy = _t._rpShowAll);
          resolutionPolicy === _locPolicy.NO_BORDER && (_t._resolutionPolicy = _t._rpNoBorder);
          resolutionPolicy === _locPolicy.FIXED_HEIGHT && (_t._resolutionPolicy = _t._rpFixedHeight);
          resolutionPolicy === _locPolicy.FIXED_WIDTH && (_t._resolutionPolicy = _t._rpFixedWidth);
        }
      },
      setDesignResolutionSize: function(width, height, resolutionPolicy) {
        if (!(width > 0 || height > 0)) {
          cc.logID(2200);
          return;
        }
        this.setResolutionPolicy(resolutionPolicy);
        var policy = this._resolutionPolicy;
        policy && policy.preApply(this);
        cc.sys.isMobile && this._adjustViewportMeta();
        this._orientationChanging = true;
        this._resizing || this._initFrameSize();
        if (!policy) {
          cc.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 && 2 === result.scale.length) {
          this._scaleX = result.scale[0];
          this._scaleY = result.scale[1];
        }
        if (result.viewport) {
          var vp = this._viewPortRect, vb = this._visibleRect, rv = result.viewport;
          vp.x = rv.x;
          vp.y = rv.y;
          vp.width = rv.width;
          vp.height = rv.height;
          vb.x = -vp.x / this._scaleX;
          vb.y = -vp.y / this._scaleY;
          vb.width = cc.game.canvas.width / this._scaleX;
          vb.height = cc.game.canvas.height / this._scaleY;
          cc._renderContext.setOffset && cc._renderContext.setOffset(vp.x, -vp.y);
        }
        var director = cc.director;
        director._winSizeInPoints.width = this._designResolutionSize.width;
        director._winSizeInPoints.height = this._designResolutionSize.height;
        policy.postApply(this);
        cc.winSize.width = director._winSizeInPoints.width;
        cc.winSize.height = director._winSizeInPoints.height;
        cc._renderType === cc.game.RENDER_TYPE_WEBGL ? director.setGLDefaultValues() : cc._renderType === cc.game.RENDER_TYPE_CANVAS && (cc.renderer._allNeedDraw = true);
        this._originalScaleX = this._scaleX;
        this._originalScaleY = this._scaleY;
        cc.visibleRect && cc.visibleRect.init(this._visibleRect);
      },
      getDesignResolutionSize: function() {
        return cc.size(this._designResolutionSize.width, this._designResolutionSize.height);
      },
      setRealPixelResolution: function(width, height, resolutionPolicy) {
        if (cc.sys.platform !== cc.sys.WECHAT_GAME) {
          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);
      },
      setViewPortInPoints: function(x, y, w, h) {
        var locFrameZoomFactor = this._frameZoomFactor, locScaleX = this._scaleX, locScaleY = this._scaleY;
        cc._renderContext.viewport(x * locScaleX * locFrameZoomFactor + this._viewPortRect.x * locFrameZoomFactor, y * locScaleY * locFrameZoomFactor + this._viewPortRect.y * locFrameZoomFactor, w * locScaleX * locFrameZoomFactor, h * locScaleY * locFrameZoomFactor);
      },
      setScissorInPoints: function(x, y, w, h) {
        var zoomFactor = this._frameZoomFactor, scaleX = this._scaleX, scaleY = this._scaleY;
        var sx = Math.ceil(x * scaleX * zoomFactor + this._viewPortRect.x * zoomFactor);
        var sy = Math.ceil(y * scaleY * zoomFactor + this._viewPortRect.y * zoomFactor);
        var sw = Math.ceil(w * scaleX * zoomFactor);
        var sh = Math.ceil(h * scaleY * zoomFactor);
        if (!_scissorRect) {
          var boxArr = gl.getParameter(gl.SCISSOR_BOX);
          _scissorRect = cc.rect(boxArr[0], boxArr[1], boxArr[2], boxArr[3]);
        }
        if (_scissorRect.x !== sx || _scissorRect.y !== sy || _scissorRect.width !== sw || _scissorRect.height !== sh) {
          _scissorRect.x = sx;
          _scissorRect.y = sy;
          _scissorRect.width = sw;
          _scissorRect.height = sh;
          cc._renderContext.scissor(sx, sy, sw, sh);
        }
      },
      isScissorEnabled: function() {
        return cc._renderContext.isEnabled(gl.SCISSOR_TEST);
      },
      getScissorRect: function() {
        if (!_scissorRect) {
          var boxArr = gl.getParameter(gl.SCISSOR_BOX);
          _scissorRect = cc.rect(boxArr[0], boxArr[1], boxArr[2], boxArr[3]);
        }
        var scaleXFactor = 1 / this._scaleX;
        var scaleYFactor = 1 / this._scaleY;
        return cc.rect((_scissorRect.x - this._viewPortRect.x) * scaleXFactor, (_scissorRect.y - this._viewPortRect.y) * scaleYFactor, _scissorRect.width * scaleXFactor, _scissorRect.height * scaleYFactor);
      },
      setViewName: function(viewName) {
        null != viewName && viewName.length > 0 && (this._viewName = viewName);
      },
      getViewName: function() {
        return this._viewName;
      },
      getViewPortRect: function() {
        return this._viewPortRect;
      },
      getScaleX: function() {
        return this._scaleX;
      },
      getScaleY: function() {
        return this._scaleY;
      },
      getDevicePixelRatio: function() {
        return this._devicePixelRatio;
      },
      convertToLocationInView: function(tx, ty, relatedPos) {
        var x = this._devicePixelRatio * (tx - relatedPos.left);
        var y = this._devicePixelRatio * (relatedPos.top + relatedPos.height - ty);
        return this._isRotated ? {
          x: this._viewPortRect.width - y,
          y: x
        } : {
          x: x,
          y: y
        };
      },
      _convertMouseToLocationInView: function(in_out_point, relatedPos) {
        var viewport = this._viewPortRect, _t = this;
        in_out_point.x = (_t._devicePixelRatio * (in_out_point.x - relatedPos.left) - viewport.x) / _t._scaleX;
        in_out_point.y = (_t._devicePixelRatio * (relatedPos.top + relatedPos.height - in_out_point.y) - viewport.y) / _t._scaleY;
      },
      _convertPointWithScale: function(point) {
        var viewport = this._viewPortRect;
        point.x = (point.x - viewport.x) / this._scaleX;
        point.y = (point.y - viewport.y) / this._scaleY;
      },
      _convertTouchesWithScale: function(touches) {
        var viewport = this._viewPortRect, scaleX = this._scaleX, scaleY = this._scaleY, selTouch, selPoint, selPrePoint;
        for (var i = 0; i < touches.length; i++) {
          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;
        }
      }
    });
    View._getInstance = function() {
      if (!this._instance) {
        this._instance = this._instance || new View();
        this._instance.initialize();
      }
      return this._instance;
    };
    cc.ContainerStrategy = cc._Class.extend({
      preApply: function(view) {},
      apply: function(view, designedResolution) {},
      postApply: function(view) {},
      _setupContainer: function(view, w, h) {
        var locCanvas = cc.game.canvas, locContainer = cc.game.container;
        if (cc.sys.platform !== cc.sys.WECHAT_GAME) {
          if (cc.sys.os === cc.sys.OS_ANDROID) {
            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";
        }
        var devicePixelRatio = view._devicePixelRatio = 1;
        view.isRetinaEnabled() && (devicePixelRatio = view._devicePixelRatio = Math.min(2, window.devicePixelRatio || 1));
        locCanvas.width = w * devicePixelRatio;
        locCanvas.height = h * devicePixelRatio;
        cc._renderContext.resetCache && cc._renderContext.resetCache();
      },
      _fixContainer: function() {
        document.body.insertBefore(cc.container, document.body.firstChild);
        var bs = document.body.style;
        bs.width = window.innerWidth + "px";
        bs.height = window.innerHeight + "px";
        bs.overflow = "hidden";
        var contStyle = cc.container.style;
        contStyle.position = "fixed";
        contStyle.left = contStyle.top = "0px";
        document.body.scrollTop = 0;
      }
    });
    cc.ContentStrategy = cc._Class.extend({
      _result: {
        scale: [ 1, 1 ],
        viewport: null
      },
      _buildResult: function(containerW, containerH, contentW, contentH, scaleX, scaleY) {
        Math.abs(containerW - contentW) < 2 && (contentW = containerW);
        Math.abs(containerH - contentH) < 2 && (contentH = containerH);
        var viewport = cc.rect(Math.round((containerW - contentW) / 2), Math.round((containerH - contentH) / 2), contentW, contentH);
        cc._renderType === cc.game.RENDER_TYPE_CANVAS;
        this._result.scale = [ scaleX, scaleY ];
        this._result.viewport = viewport;
        return this._result;
      },
      preApply: function(view) {},
      apply: function(view, designedResolution) {
        return {
          scale: [ 1, 1 ]
        };
      },
      postApply: function(view) {}
    });
    (function() {
      var EqualToFrame = cc.ContainerStrategy.extend({
        apply: function(view) {
          var frameH = view._frameSize.height, containerStyle = cc.container.style;
          this._setupContainer(view, view._frameSize.width, view._frameSize.height);
          view._isRotated ? containerStyle.margin = "0 0 0 " + frameH + "px" : containerStyle.margin = "0px";
          containerStyle.padding = "0px";
        }
      });
      var ProportionalToFrame = cc.ContainerStrategy.extend({
        apply: function(view, designedResolution) {
          var frameW = view._frameSize.width, frameH = view._frameSize.height, containerStyle = cc.container.style, designW = designedResolution.width, designH = designedResolution.height, scaleX = frameW / designW, scaleY = frameH / designH, containerW, containerH;
          scaleX < scaleY ? (containerW = frameW, containerH = designH * scaleX) : (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);
          true;
          view._isRotated ? containerStyle.margin = "0 0 0 " + frameH + "px" : containerStyle.margin = "0px";
          containerStyle.paddingLeft = offx + "px";
          containerStyle.paddingRight = offx + "px";
          containerStyle.paddingTop = offy + "px";
          containerStyle.paddingBottom = offy + "px";
        }
      });
      var EqualToWindow = EqualToFrame.extend({
        preApply: function(view) {
          this._super(view);
          cc.game.frame = document.documentElement;
        },
        apply: function(view) {
          this._super(view);
          this._fixContainer();
        }
      });
      var ProportionalToWindow = ProportionalToFrame.extend({
        preApply: function(view) {
          this._super(view);
          cc.game.frame = document.documentElement;
        },
        apply: function(view, designedResolution) {
          this._super(view, designedResolution);
          this._fixContainer();
        }
      });
      var OriginalContainer = cc.ContainerStrategy.extend({
        apply: function(view) {
          this._setupContainer(view, cc.game.canvas.width, cc.game.canvas.height);
        }
      });
      cc.ContainerStrategy.EQUAL_TO_FRAME = new EqualToFrame();
      cc.ContainerStrategy.PROPORTION_TO_FRAME = new ProportionalToFrame();
      cc.ContainerStrategy.ORIGINAL_CONTAINER = new OriginalContainer();
      var ExactFit = cc.ContentStrategy.extend({
        apply: function(view, designedResolution) {
          var containerW = cc.game.canvas.width, containerH = cc.game.canvas.height, scaleX = containerW / designedResolution.width, scaleY = containerH / designedResolution.height;
          return this._buildResult(containerW, containerH, containerW, containerH, scaleX, scaleY);
        }
      });
      var ShowAll = cc.ContentStrategy.extend({
        apply: function(view, designedResolution) {
          var containerW = cc.game.canvas.width, containerH = cc.game.canvas.height, designW = designedResolution.width, designH = designedResolution.height, scaleX = containerW / designW, scaleY = containerH / designH, scale = 0, contentW, contentH;
          scaleX < scaleY ? (scale = scaleX, contentW = containerW, contentH = designH * scale) : (scale = scaleY, 
          contentW = designW * scale, contentH = containerH);
          return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
        }
      });
      var NoBorder = cc.ContentStrategy.extend({
        apply: function(view, designedResolution) {
          var containerW = cc.game.canvas.width, containerH = cc.game.canvas.height, designW = designedResolution.width, designH = designedResolution.height, scaleX = containerW / designW, scaleY = containerH / designH, scale, contentW, contentH;
          scaleX < scaleY ? (scale = scaleY, contentW = designW * scale, contentH = containerH) : (scale = scaleX, 
          contentW = containerW, contentH = designH * scale);
          return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
        }
      });
      var FixedHeight = cc.ContentStrategy.extend({
        apply: function(view, designedResolution) {
          var containerW = cc.game.canvas.width, containerH = cc.game.canvas.height, designH = designedResolution.height, scale = containerH / designH, contentW = containerW, contentH = containerH;
          return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
        },
        postApply: function(view) {
          cc.director._winSizeInPoints = view.getVisibleSize();
        }
      });
      var FixedWidth = cc.ContentStrategy.extend({
        apply: function(view, designedResolution) {
          var containerW = cc.game.canvas.width, containerH = cc.game.canvas.height, designW = designedResolution.width, scale = containerW / designW, contentW = containerW, contentH = containerH;
          return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
        },
        postApply: function(view) {
          cc.director._winSizeInPoints = view.getVisibleSize();
        }
      });
      cc.ContentStrategy.EXACT_FIT = new ExactFit();
      cc.ContentStrategy.SHOW_ALL = new ShowAll();
      cc.ContentStrategy.NO_BORDER = new NoBorder();
      cc.ContentStrategy.FIXED_HEIGHT = new FixedHeight();
      cc.ContentStrategy.FIXED_WIDTH = new FixedWidth();
    })();
    cc.ResolutionPolicy = cc._Class.extend({
      _containerStrategy: null,
      _contentStrategy: null,
      ctor: function(containerStg, contentStg) {
        this.setContainerStrategy(containerStg);
        this.setContentStrategy(contentStg);
      },
      preApply: function(view) {
        this._containerStrategy.preApply(view);
        this._contentStrategy.preApply(view);
      },
      apply: function(view, designedResolution) {
        this._containerStrategy.apply(view, designedResolution);
        return this._contentStrategy.apply(view, designedResolution);
      },
      postApply: function(view) {
        this._containerStrategy.postApply(view);
        this._contentStrategy.postApply(view);
      },
      setContainerStrategy: function(containerStg) {
        containerStg instanceof cc.ContainerStrategy && (this._containerStrategy = containerStg);
      },
      setContentStrategy: function(contentStg) {
        contentStg instanceof cc.ContentStrategy && (this._contentStrategy = contentStg);
      }
    });
    cc.js.get(cc.ResolutionPolicy.prototype, "canvasSize", (function() {
      return cc.v2(cc.game.canvas.width, cc.game.canvas.height);
    }));
    cc.ResolutionPolicy.EXACT_FIT = 0;
    cc.ResolutionPolicy.NO_BORDER = 1;
    cc.ResolutionPolicy.SHOW_ALL = 2;
    cc.ResolutionPolicy.FIXED_HEIGHT = 3;
    cc.ResolutionPolicy.FIXED_WIDTH = 4;
    cc.ResolutionPolicy.UNKNOWN = 5;
    module.exports = View;
  }), {
    "../event-manager": 110
  } ],
  186: [ (function(require, module, exports) {
    cc.visibleRect = {
      topLeft: cc.p(0, 0),
      topRight: cc.p(0, 0),
      top: cc.p(0, 0),
      bottomLeft: cc.p(0, 0),
      bottomRight: cc.p(0, 0),
      bottom: cc.p(0, 0),
      center: cc.p(0, 0),
      left: cc.p(0, 0),
      right: cc.p(0, 0),
      width: 0,
      height: 0,
      init: function(visibleRect) {
        var w = this.width = visibleRect.width;
        var h = this.height = visibleRect.height;
        var l = visibleRect.x, b = visibleRect.y, t = b + h, 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;
      }
    };
  }), {} ],
  187: [ (function(require, module, exports) {
    var ClassManager = cc.ClassManager = {
      instanceId: 0 | 998 * Math.random(),
      getNewInstanceId: function() {
        return this.instanceId++;
      }
    };
    var fnTest = /\b_super\b/;
    var Class = function() {};
    Class.extend = function(props) {
      var _super = this.prototype;
      var proto = Object.create(_super);
      var desc = {
        writable: true,
        enumerable: false,
        configurable: true
      };
      var TheClass;
      if ((true, cc.game) && cc.game.config && cc.game.config[cc.game.CONFIG_KEY.exposeClassName]) {
        var ctor = "return (function " + (props._className || "Class") + "(arg0,arg1,arg2,arg3,arg4) {\nthis.__instanceId = cc.ClassManager.getNewInstanceId();\nif (this.ctor) {\nswitch (arguments.length) {\ncase 0: this.ctor(); break;\ncase 1: this.ctor(arg0); break;\ncase 2: this.ctor(arg0,arg1); break;\ncase 3: this.ctor(arg0,arg1,arg2); break;\ncase 4: this.ctor(arg0,arg1,arg2,arg3); break;\ncase 5: this.ctor(arg0,arg1,arg2,arg3,arg4); break;\ndefault: this.ctor.apply(this, arguments);\n}\n}\n});";
        TheClass = Function(ctor)();
      } else TheClass = function(arg0, arg1, arg2, arg3, arg4) {
        this.__instanceId = ClassManager.getNewInstanceId();
        if (this.ctor) switch (arguments.length) {
         case 0:
          this.ctor();
          break;

         case 1:
          this.ctor(arg0);
          break;

         case 2:
          this.ctor(arg0, arg1);
          break;

         case 3:
          this.ctor(arg0, arg1, arg2);
          break;

         case 4:
          this.ctor(arg0, arg1, arg2, arg3);
          break;

         case 5:
          this.ctor(arg0, arg1, arg2, arg3, arg4);
          break;

         default:
          this.ctor.apply(this, arguments);
        }
      };
      TheClass.prototype = proto;
      desc.value = TheClass;
      Object.defineProperty(proto, "constructor", desc);
      for (var name in props) {
        var isFunc = "function" === typeof props[name];
        var override = isFunc && "function" === typeof _super[name];
        var hasSuperCall = override && fnTest.test(props[name]);
        if (hasSuperCall) {
          desc.value = (function(name, fn) {
            return function() {
              var tmp = this._super;
              this._super = _super[name];
              var ret = fn.apply(this, arguments);
              this._super = tmp;
              return ret;
            };
          })(name, props[name]);
          Object.defineProperty(proto, name, desc);
        } else if (isFunc) {
          desc.value = props[name];
          Object.defineProperty(proto, name, desc);
        } else proto[name] = props[name];
      }
      TheClass.extend = Class.extend;
      TheClass.implement = function(prop) {
        for (var name in prop) proto[name] = prop[name];
      };
      return TheClass;
    };
    cc.defineGetterSetter = function(proto, prop, getter, setter, getterName, setterName) {
      if (proto.__defineGetter__) {
        getter && proto.__defineGetter__(prop, getter);
        setter && proto.__defineSetter__(prop, setter);
      } else {
        if (!Object.defineProperty) throw new Error("browser does not support getters");
        var desc = {
          configurable: true
        };
        getter && (desc.get = getter);
        setter && (desc.set = setter);
        Object.defineProperty(proto, prop, desc);
      }
    };
    cc.clone = function(obj) {
      var newObj = obj.constructor ? new obj.constructor() : {};
      for (var key in obj) {
        var copy = obj[key];
        "object" !== typeof copy || !copy || copy instanceof _ccsg.Node || (false, copy instanceof HTMLElement) ? newObj[key] = copy : newObj[key] = cc.clone(copy);
      }
      return newObj;
    };
    cc._Class = module.exports = Class;
  }), {} ],
  188: [ (function(require, module, exports) {
    var JS = require("./js");
    var isPlainEmptyObj = require("./utils").isPlainEmptyObj_DEV;
    var DELIMETER = "$_$";
    function createAttrsSingle(owner, ownerCtor, superAttrs) {
      var AttrsCtor;
      var ctorName;
      false;
      AttrsCtor = function() {};
      superAttrs && JS.extend(AttrsCtor, superAttrs.constructor);
      var attrs = new AttrsCtor();
      JS.value(owner, "__attrs__", attrs);
      return attrs;
    }
    function createAttrs(subclass) {
      var superClass;
      var chains = cc.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, cls, superClass && superClass.__attrs__);
        }
      }
      superClass = chains[0];
      createAttrsSingle(subclass, subclass, superClass && superClass.__attrs__);
      return subclass.__attrs__;
    }
    function attr(ctor, propName, newAttrs) {
      var attrs, setter, key;
      if ("function" === typeof ctor) {
        attrs = getClassAttrs(ctor);
        setter = attrs.constructor.prototype;
      } else {
        var instance = ctor;
        attrs = instance.__attrs__;
        if (!attrs) {
          ctor = instance.constructor;
          var clsAttrs = getClassAttrs(ctor);
          attrs = createAttrsSingle(instance, ctor, clsAttrs);
        }
        setter = attrs;
      }
      if ("undefined" === typeof newAttrs) {
        var prefix = propName + DELIMETER;
        var ret = {};
        for (key in attrs) key.startsWith(prefix) && (ret[key.slice(prefix.length)] = attrs[key]);
        return ret;
      }
      if ("object" === typeof newAttrs) for (key in newAttrs) 95 !== key.charCodeAt(0) && (setter[propName + DELIMETER + key] = newAttrs[key]); else false;
    }
    function getClassAttrs(ctor) {
      return ctor.hasOwnProperty("__attrs__") && ctor.__attrs__ || createAttrs(ctor);
    }
    function getClassAttrsProto(ctor) {
      return getClassAttrs(ctor).constructor.prototype;
    }
    function setClassAttr(ctor, propName, key, value) {
      var proto = getClassAttrsProto(ctor);
      proto[propName + DELIMETER + key] = value;
    }
    cc.Integer = "Integer";
    cc.Float = "Float";
    false;
    cc.Boolean = "Boolean";
    cc.String = "String";
    function getTypeChecker(type, attrName) {
      false;
    }
    function ObjectType(typeCtor) {
      return {
        type: "Object",
        ctor: typeCtor,
        _onAfterProp: false
      };
    }
    module.exports = {
      attr: attr,
      getClassAttrs: getClassAttrs,
      getClassAttrsProto: getClassAttrsProto,
      setClassAttr: setClassAttr,
      DELIMETER: DELIMETER,
      getTypeChecker: getTypeChecker,
      ObjectType: ObjectType,
      ScriptUuid: {}
    };
  }), {
    "./CCClass": 175,
    "./js": 196,
    "./utils": 200
  } ],
  189: [ (function(require, module, exports) {
    var JS = require("./js");
    var fastRemoveAt = JS.array.fastRemoveAt;
    function CallbackList() {
      this.callbacks = [];
      this.targets = [];
      this.isInvoking = false;
      this.containCanceled = false;
    }
    var proto = CallbackList.prototype;
    proto.removeBy = function(array, value) {
      var callbacks = this.callbacks;
      var targets = this.targets;
      for (var i = 0; i < array.length; ++i) if (array[i] === value) {
        fastRemoveAt(callbacks, i);
        fastRemoveAt(targets, i);
        --i;
      }
    };
    proto.cancel = function(index) {
      this.callbacks[index] = this.targets[index] = null;
      this.containCanceled = true;
    };
    proto.cancelAll = function() {
      var callbacks = this.callbacks;
      var targets = this.targets;
      for (var i = 0; i < callbacks.length; i++) callbacks[i] = targets[i] = null;
      this.containCanceled = true;
    };
    proto.purgeCanceled = function() {
      this.removeBy(this.callbacks, null);
      this.containCanceled = false;
    };
    var MAX_SIZE = 16;
    var callbackListPool = new JS.Pool(function(list) {
      list.callbacks.length = 0;
      list.targets.length = 0;
      list.isInvoking = false;
      list.containCanceled = false;
    }, MAX_SIZE);
    callbackListPool.get = function() {
      return this._get() || new CallbackList();
    };
    function CallbacksHandler() {
      this._callbackTable = JS.createMap(true);
    }
    proto = CallbacksHandler.prototype;
    proto.add = function(key, callback, target) {
      var list = this._callbackTable[key];
      list || (list = this._callbackTable[key] = callbackListPool.get());
      list.callbacks.push(callback);
      list.targets.push(target || null);
    };
    proto.has = function(key, callback, target) {
      var list = this._callbackTable[key];
      if (!list) return false;
      var callbacks = list.callbacks;
      if (!callback) {
        for (var i = 0; i < callbacks.length; i++) if (callbacks[i]) return true;
        return false;
      }
      target = target || null;
      var targets = list.targets;
      for (var _i = 0; _i < callbacks.length; ++_i) if (callbacks[_i] === callback && targets[_i] === target) return true;
      return false;
    };
    proto.removeAll = function(keyOrTarget) {
      if ("string" === typeof keyOrTarget) {
        var list = this._callbackTable[keyOrTarget];
        if (list) if (list.isInvoking) list.cancelAll(); else {
          callbackListPool.put(list);
          delete this._callbackTable[keyOrTarget];
        }
      } else if (keyOrTarget) for (var key in this._callbackTable) {
        var _list = this._callbackTable[key];
        if (_list.isInvoking) {
          var targets = _list.targets;
          for (var i = 0; i < targets.length; ++i) targets[i] === keyOrTarget && _list.cancel(i);
        } else _list.removeBy(_list.targets, keyOrTarget);
      }
    };
    proto.remove = function(key, callback, target) {
      var list = this._callbackTable[key];
      if (list) {
        target = target || null;
        var callbacks = list.callbacks;
        var targets = list.targets;
        for (var i = 0; i < callbacks.length; ++i) if (callbacks[i] === callback && targets[i] === target) {
          if (list.isInvoking) list.cancel(i); else {
            fastRemoveAt(callbacks, i);
            fastRemoveAt(targets, i);
          }
          break;
        }
      }
    };
    var CallbacksInvoker = function() {
      CallbacksHandler.call(this);
    };
    JS.extend(CallbacksInvoker, CallbacksHandler);
    false;
    CallbacksInvoker.prototype.invoke = function(key, p1, p2, p3, p4, p5) {
      var list = this._callbackTable[key];
      if (list) {
        var rootInvoker = !list.isInvoking;
        list.isInvoking = true;
        var callbacks = list.callbacks;
        var targets = list.targets;
        for (var i = 0, len = callbacks.length; i < len; ++i) {
          var callback = callbacks[i];
          if (callback) {
            var target = targets[i];
            target ? callback.call(target, p1, p2, p3, p4, p5) : callback(p1, p2, p3, p4, p5);
          }
        }
        if (rootInvoker) {
          list.isInvoking = false;
          list.containCanceled && list.purgeCanceled();
        }
      }
    };
    CallbacksInvoker.CallbacksHandler = CallbacksHandler;
    module.exports = CallbacksInvoker;
  }), {
    "./js": 196
  } ],
  190: [ (function(require, module, exports) {
    function deepFlatten(strList, array) {
      for (var i = 0; i < array.length; i++) {
        var item = array[i];
        Array.isArray(item) ? deepFlatten(strList, item) : strList.push(item);
      }
    }
    function flattenCodeArray(array) {
      var separator = "";
      var strList = [];
      deepFlatten(strList, array);
      return strList.join(separator);
    }
    module.exports = {
      flattenCodeArray: flattenCodeArray
    };
  }), {} ],
  191: [ (function(require, module, exports) {
    var JS = require("./js");
    var CCObject = require("./CCObject");
    var Attr = require("./attribute");
    var CCClass = require("./CCClass");
    var Misc = require("../utils/misc");
    var Details = function() {
      this.uuidList = [];
      this.uuidObjList = [];
      this.uuidPropList = [];
      this.rawProp = "";
    };
    Details.prototype.reset = function() {
      this.uuidList.length = 0;
      this.uuidObjList.length = 0;
      this.uuidPropList.length = 0;
      this.rawProp = "";
    };
    false;
    Details.prototype.getUuidOf = function(obj, propName) {
      for (var i = 0; i < this.uuidObjList.length; i++) if (this.uuidObjList[i] === obj && this.uuidPropList[i] === propName) return this.uuidList[i];
      return "";
    };
    Details.prototype.push = function(obj, propName, uuid) {
      this.uuidList.push(uuid);
      this.uuidObjList.push(obj);
      this.uuidPropList.push(propName);
    };
    Details.pool = new JS.Pool(function(obj) {
      obj.reset();
    }, 10);
    Details.pool.get = function() {
      return this._get() || new Details();
    };
    var _Deserializer = (function() {
      function _Deserializer(result, target, classFinder, customEnv, ignoreEditorOnly) {
        this.result = result;
        this.customEnv = customEnv;
        this.deserializedList = [];
        this.deserializedData = null;
        this._classFinder = classFinder;
        false;
        this._idList = [];
        this._idObjList = [];
        this._idPropList = [];
      }
      function _dereference(self) {
        var deserializedList = self.deserializedList;
        var idPropList = self._idPropList;
        var idList = self._idList;
        var idObjList = self._idObjList;
        var onDereferenced = self._classFinder && self._classFinder.onDereferenced;
        var i, propName, id;
        false;
        for (i = 0; i < idList.length; i++) {
          propName = idPropList[i];
          id = idList[i];
          idObjList[i][propName] = deserializedList[id];
        }
      }
      var prototype = _Deserializer.prototype;
      prototype.deserialize = function(jsonObj) {
        if (Array.isArray(jsonObj)) {
          var jsonArray = jsonObj;
          var refCount = jsonArray.length;
          this.deserializedList.length = refCount;
          for (var i = 0; i < refCount; i++) if (jsonArray[i]) {
            var mainTarget;
            false, false;
            this.deserializedList[i] = this._deserializeObject(jsonArray[i]);
          }
          this.deserializedData = refCount > 0 ? this.deserializedList[0] : [];
        } else {
          this.deserializedList.length = 1;
          false, false;
          this.deserializedData = jsonObj ? this._deserializeObject(jsonObj) : null;
          this.deserializedList[0] = this.deserializedData;
        }
        _dereference(this);
        return this.deserializedData;
      };
      prototype._deserializeObject = function(serialized, target, owner, propName) {
        var prop;
        var obj = null;
        var klass = null;
        var type = serialized.__type__;
        if (type) {
          klass = this._classFinder(type, serialized, owner, propName);
          if (!klass) {
            var notReported = this._classFinder === JS._getClassById;
            notReported && cc.deserialize.reportMissingClass(type);
            return null;
          }
          if ((false, false) && target) {
            target instanceof klass || cc.warnID(5300, JS.getClassName(target), klass);
            obj = target;
          } else obj = new klass();
          if (obj._deserialize) {
            obj._deserialize(serialized.content, this);
            return obj;
          }
          cc.Class._isCCClass(klass) ? _deserializeFireClass(this, obj, serialized, klass, target) : this._deserializeTypedObject(obj, serialized, klass);
        } else if (Array.isArray(serialized)) {
          if ((false, false) && target) {
            target.length = serialized.length;
            obj = target;
          } else obj = new Array(serialized.length);
          for (var i = 0; i < serialized.length; i++) {
            prop = serialized[i];
            if ("object" === typeof prop && prop) {
              false, false;
              this._deserializeObjField(obj, prop, "" + i);
            } else obj[i] = prop;
          }
        } else {
          obj = (false, false) && target || {};
          this._deserializePrimitiveObject(obj, serialized);
        }
        return obj;
      };
      prototype._deserializeObjField = function(obj, jsonObj, propName, target) {
        var id = jsonObj.__id__;
        if ("undefined" === typeof id) {
          var uuid = jsonObj.__uuid__;
          if (uuid) {
            this.result.uuidList.push(uuid);
            this.result.uuidObjList.push(obj);
            this.result.uuidPropList.push(propName);
          } else {
            false, false;
            obj[propName] = this._deserializeObject(jsonObj);
          }
        } else {
          var dObj = this.deserializedList[id];
          if (dObj) obj[propName] = dObj; else {
            this._idList.push(id);
            this._idObjList.push(obj);
            this._idPropList.push(propName);
          }
        }
      };
      prototype._deserializePrimitiveObject = function(instance, serialized) {
        var self = this;
        for (var propName in serialized) if (serialized.hasOwnProperty(propName)) {
          var prop = serialized[propName];
          if ("object" !== typeof prop) "__type__" !== propName && (instance[propName] = prop); else if (prop) {
            false, false;
            self._deserializeObjField(instance, prop, propName);
          } else instance[propName] = null;
        }
      };
      prototype._deserializeTypedObject = function(instance, serialized, klass) {
        if (klass === cc.Vec2) {
          instance.x = serialized.x || 0;
          instance.y = serialized.y || 0;
          return;
        }
        if (klass === cc.Color) {
          instance.r = serialized.r || 0;
          instance.g = serialized.g || 0;
          instance.b = serialized.b || 0;
          var a = serialized.a;
          instance.a = void 0 === a ? 255 : a;
          return;
        }
        if (klass === cc.Size) {
          instance.width = serialized.width || 0;
          instance.height = serialized.height || 0;
          return;
        }
        var fastDefinedProps = klass.__props__;
        fastDefinedProps || (fastDefinedProps = Object.keys(instance));
        for (var i = 0; i < fastDefinedProps.length; i++) {
          var propName = fastDefinedProps[i];
          var prop = serialized[propName];
          if ("undefined" !== typeof prop && serialized.hasOwnProperty(propName)) if ("object" !== typeof prop) instance[propName] = prop; else if (prop) {
            false, false;
            this._deserializeObjField(instance, prop, propName);
          } else instance[propName] = null;
        }
      };
      var compileObjectType = function(sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue) {
        if (defaultValue instanceof cc.ValueType) {
          assumeHavePropIfIsValue || sources.push("if(prop){");
          var ctorCode = JS.getClassName(defaultValue);
          sources.push("s._deserializeTypedObject(o" + accessorToSet + ",prop," + ctorCode + ");");
          assumeHavePropIfIsValue || sources.push("}else o" + accessorToSet + "=null;");
        } else {
          sources.push("if(prop){");
          false, false;
          sources.push("s._deserializeObjField(o,prop," + propNameLiteralToSet + ");");
          sources.push("}else o" + accessorToSet + "=null;");
        }
      };
      var compileDeserialize = function(self, klass) {
        var TYPE = Attr.DELIMETER + "type";
        var RAW_TYPE = Attr.DELIMETER + "rawType";
        var EDITOR_ONLY = Attr.DELIMETER + "editorOnly";
        var SERIALIZABLE = Attr.DELIMETER + "serializable";
        var DEFAULT = Attr.DELIMETER + "default";
        var SAVE_URL_AS_ASSET = Attr.DELIMETER + "saveUrlAsAsset";
        var FORMERLY_SERIALIZED_AS = Attr.DELIMETER + "formerlySerializedAs";
        var attrs = Attr.getClassAttrs(klass);
        var props = klass.__props__;
        var sources = [ "var prop;" ];
        var fastMode = Misc.BUILTIN_CLASSID_RE.test(JS._getClassId(klass));
        for (var p = 0; p < props.length; p++) {
          var propName = props[p];
          var propNameLiteralToSet;
          var rawType = attrs[propName + RAW_TYPE];
          if (rawType) {
            propNameLiteralToSet = CCClass.IDENTIFIER_RE.test(propName) ? '"' + propName + '"' : CCClass.escapeForJS(propName);
            sources.push('if(s.result.rawProp)\ncc.error("not support multi raw object in a file");');
            sources.push("s.result.rawProp=" + propNameLiteralToSet + ";");
          } else {
            if ((false, false) && attrs[propName + EDITOR_ONLY]) {
              var mayUsedInPersistRoot = "_id" === propName && cc.isChildClassOf(klass, cc.Node);
              if (!mayUsedInPersistRoot) continue;
            }
            if (false === attrs[propName + SERIALIZABLE]) continue;
            var accessorToSet;
            if (CCClass.IDENTIFIER_RE.test(propName)) {
              propNameLiteralToSet = '"' + propName + '"';
              accessorToSet = "." + propName;
            } else {
              propNameLiteralToSet = CCClass.escapeForJS(propName);
              accessorToSet = "[" + propNameLiteralToSet + "]";
            }
            var accessorToGet = accessorToSet;
            if (attrs[propName + FORMERLY_SERIALIZED_AS]) {
              var propNameToRead = attrs[propName + FORMERLY_SERIALIZED_AS];
              accessorToGet = CCClass.IDENTIFIER_RE.test(propNameToRead) ? "." + propNameToRead : "[" + CCClass.escapeForJS(propNameToRead) + "]";
            }
            sources.push("prop=d" + accessorToGet + ";");
            sources.push('if(typeof prop!=="undefined"){');
            var defaultValue = CCClass.getDefault(attrs[propName + DEFAULT]);
            if (fastMode) {
              var isPrimitiveType;
              var userType = attrs[propName + TYPE];
              if (void 0 === defaultValue && userType) isPrimitiveType = userType === cc.String || userType === cc.Integer || userType === cc.Float || userType === cc.Boolean; else {
                var defaultType = typeof defaultValue;
                isPrimitiveType = "string" === defaultType && !attrs[propName + SAVE_URL_AS_ASSET] || "number" === defaultType || "boolean" === defaultType;
              }
              isPrimitiveType ? sources.push("o" + accessorToSet + "=prop;") : compileObjectType(sources, defaultValue, accessorToSet, propNameLiteralToSet, true);
            } else {
              sources.push('if(typeof prop!=="object"){o' + accessorToSet + "=prop;}else{");
              compileObjectType(sources, defaultValue, accessorToSet, propNameLiteralToSet, false);
              sources.push("}");
            }
            sources.push("}");
          }
        }
        if ("_$erialized" === props[props.length - 1]) {
          sources.push("o._$erialized=JSON.parse(JSON.stringify(d));");
          sources.push("s._deserializePrimitiveObject(o._$erialized,d);");
        }
        return Function("s", "o", "d", "k", "t", sources.join(""));
      };
      function unlinkUnusedPrefab(self, serialized, obj) {
        var uuid = serialized["asset"] && serialized["asset"].__uuid__;
        if (uuid) {
          var last = self.result.uuidList.length - 1;
          if (self.result.uuidList[last] === uuid && self.result.uuidObjList[last] === obj && "asset" === self.result.uuidPropList[last]) {
            self.result.uuidList.pop();
            self.result.uuidObjList.pop();
            self.result.uuidPropList.pop();
          } else {
            var debugEnvOnlyInfo = "Failed to skip prefab asset while deserializing PrefabInfo";
            cc.warn(debugEnvOnlyInfo);
          }
        }
      }
      function _deserializeFireClass(self, obj, serialized, klass, target) {
        var deserialize;
        if (klass.hasOwnProperty("__deserialize__")) deserialize = klass.__deserialize__; else {
          deserialize = compileDeserialize(self, klass);
          JS.value(klass, "__deserialize__", deserialize, true);
        }
        deserialize(self, obj, serialized, klass, target);
        false, false;
      }
      _Deserializer.pool = new JS.Pool(function(obj) {
        obj.result = null;
        obj.customEnv = null;
        obj.deserializedList.length = 0;
        obj.deserializedData = null;
        obj._classFinder = null;
        false;
        obj._idList.length = 0;
        obj._idObjList.length = 0;
        obj._idPropList.length = 0;
      }, 1);
      _Deserializer.pool.get = function(result, target, classFinder, customEnv, ignoreEditorOnly) {
        var cache = this._get();
        if (cache) {
          cache.result = result;
          cache.customEnv = customEnv;
          cache._classFinder = classFinder;
          false;
          return cache;
        }
        return new _Deserializer(result, target, classFinder, customEnv, ignoreEditorOnly);
      };
      return _Deserializer;
    })();
    cc.deserialize = function(data, details, options) {
      options = options || {};
      var classFinder = options.classFinder || JS._getClassById;
      var createAssetRefs = options.createAssetRefs || cc.sys.platform === cc.sys.EDITOR_CORE;
      var target = (false, false) && options.target;
      var customEnv = options.customEnv;
      var ignoreEditorOnly = options.ignoreEditorOnly;
      false;
      "string" === typeof data && (data = JSON.parse(data));
      var tempDetails = !details;
      details = details || Details.pool.get();
      var deserializer = _Deserializer.pool.get(details, target, classFinder, customEnv, ignoreEditorOnly);
      cc.game._isCloning = true;
      var res = deserializer.deserialize(data);
      cc.game._isCloning = false;
      _Deserializer.pool.put(deserializer);
      createAssetRefs && details.assignAssetsBy(Editor.serialize.asAsset);
      tempDetails && Details.pool.put(details);
      return res;
    };
    cc.deserialize.Details = Details;
    cc.deserialize.reportMissingClass = function(id) {
      false;
      cc.warnID(5302, id);
    };
  }), {
    "../utils/misc": 225,
    "./CCClass": 175,
    "./CCObject": 181,
    "./attribute": 188,
    "./js": 196
  } ],
  192: [ (function(require, module, exports) {
    var NonUuidMark = ".";
    function IdGenerater(category) {
      this.id = 0 | 998 * Math.random();
      this.prefix = category ? category + NonUuidMark : "";
    }
    IdGenerater.prototype.getNewId = function() {
      return this.prefix + ++this.id;
    };
    IdGenerater.global = new IdGenerater("global");
    module.exports = IdGenerater;
  }), {} ],
  193: [ (function(require, module, exports) {
    require("./js");
    require("./CCClass");
    require("./CCClassDecorator");
    require("./CCEnum");
    require("./CCObject");
    require("./callbacks-invoker");
    require("./url");
    require("./deserialize");
    require("./instantiate");
    require("./instantiate-jit");
    require("./requiring-frame");
    require("./CCSys");
    require("./CCMacro");
    true;
    require("./CCAssetLibrary");
    true;
    require("./CCVisibleRect");
  }), {
    "./CCAssetLibrary": 174,
    "./CCClass": 175,
    "./CCClassDecorator": 176,
    "./CCEnum": 177,
    "./CCMacro": 180,
    "./CCObject": 181,
    "./CCSys": 184,
    "./CCVisibleRect": 186,
    "./callbacks-invoker": 189,
    "./deserialize": 191,
    "./instantiate": 195,
    "./instantiate-jit": 194,
    "./js": 196,
    "./requiring-frame": 198,
    "./url": 199
  } ],
  194: [ (function(require, module, exports) {
    var CCObject = require("./CCObject");
    var Destroyed = CCObject.Flags.Destroyed;
    var PersistentMask = CCObject.Flags.PersistentMask;
    var Attr = require("./attribute");
    var JS = require("./js");
    var CCClass = require("./CCClass");
    var Compiler = require("./compiler");
    var SERIALIZABLE = Attr.DELIMETER + "serializable";
    var DEFAULT = Attr.DELIMETER + "default";
    var IDENTIFIER_RE = CCClass.IDENTIFIER_RE;
    var escapeForJS = CCClass.escapeForJS;
    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.Node": "cc.Node",
      "cc.Sprite": "cc.Sprite",
      "cc.Label": "cc.Label",
      "cc.Button": "cc.Button",
      "cc.Widget": "cc.Widget",
      "cc.Animation": "cc.Animation",
      "cc.ClickEvent": false,
      "cc.PrefabInfo": false
    };
    function Declaration(varName, expression) {
      this.varName = varName;
      this.expression = expression;
    }
    Declaration.prototype.toString = function() {
      return VAR + this.varName + "=" + this.expression + ";";
    };
    function mergeDeclaration(statement, expression) {
      return expression instanceof Declaration ? new Declaration(expression.varName, statement + expression.expression) : 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) + ";");
    }
    function Assignments(targetExpression) {
      this._exps = [];
      this._targetExp = targetExpression;
    }
    Assignments.prototype.append = function(key, expression) {
      this._exps.push([ key, expression ]);
    };
    Assignments.prototype.writeCode = function(codeArray) {
      var targetVar;
      if (this._exps.length > 1) {
        codeArray.push(LOCAL_TEMP_OBJ + "=" + this._targetExp + ";");
        targetVar = LOCAL_TEMP_OBJ;
      } else {
        if (1 !== this._exps.length) return;
        targetVar = this._targetExp;
      }
      for (var i = 0; i < this._exps.length; i++) {
        var pair = this._exps[i];
        writeAssignment(codeArray, targetVar + getPropAccessor(pair[0]) + "=", pair[1]);
      }
    };
    Assignments.pool = new JS.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 equalsToDefault(def, value) {
      if ("function" === typeof def) try {
        def = def();
      } catch (e) {
        return false;
      }
      if (def === value) return true;
      if (def && value) {
        if (def instanceof cc.ValueType && def.equals(value)) return true;
        if (Array.isArray(def) && Array.isArray(value) || def.constructor === Object && value.constructor === Object) try {
          return JSON.stringify(def) === JSON.stringify(value);
        } catch (e) {}
      }
      return false;
    }
    function getPropAccessor(key) {
      return IDENTIFIER_RE.test(key) ? "." + key : "[" + escapeForJS(key) + "]";
    }
    function Parser(obj, parent) {
      this.parent = parent;
      this.objsToClear_iN$t = [];
      this.codeArray = [];
      this.objs = [];
      this.funcs = [];
      this.funcModuleCache = JS.createMap();
      JS.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;
      this.globalVariables.length > 0 && (globalVariablesDeclaration = VAR + this.globalVariables.join(",") + ";");
      var code = Compiler.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 proto = Parser.prototype;
    proto.getFuncModule = function(func, usedInNew) {
      var clsName = JS.getClassName(func);
      if (clsName) {
        var cache = this.funcModuleCache[clsName];
        if (cache) return cache;
        if (void 0 === cache) {
          var clsNameIsModule = -1 !== clsName.indexOf(".");
          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 + "]";
      usedInNew && (res = "(" + res + ")");
      this.funcModuleCache[clsName] = res;
      return res;
    };
    proto.getObjRef = function(obj) {
      var index = this.objs.indexOf(obj);
      if (index < 0) {
        index = this.objs.length;
        this.objs.push(obj);
      }
      return "O[" + index + "]";
    };
    proto.setValueType = function(codeArray, defaultValue, srcValue, targetExpression) {
      var assignments = Assignments.pool.get(targetExpression);
      var fastDefinedProps = defaultValue.constructor.__props__;
      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);
    };
    proto.enumerateCCClass = function(codeArray, obj, klass) {
      var props = klass.__props__;
      var attrs = Attr.getClassAttrs(klass);
      for (var p = 0; p < props.length; p++) {
        var key = props[p];
        if ((false, false) && "_id" === key && (obj instanceof cc._BaseNode || obj instanceof cc.Component)) continue;
        if (false !== attrs[key + SERIALIZABLE]) {
          var val = obj[key];
          var defaultValue = attrs[key + DEFAULT];
          if (equalsToDefault(defaultValue, val)) continue;
          if ("object" === typeof val && val instanceof cc.ValueType) {
            var 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);
        }
      }
    };
    proto.instantiateArray = function(value) {
      if (0 === value.length) 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;
    };
    proto.enumerateField = function(obj, key, value) {
      if ("object" === typeof value && 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;
        }
        return Array.isArray(value) ? this.instantiateArray(value) : this.instantiateObj(value);
      }
      if ("function" === typeof value) return this.getFuncModule(value);
      if ("string" === typeof value) return escapeForJS(value);
      "_objFlags" === key && obj instanceof CCObject && (value &= PersistentMask);
      return value;
    };
    proto.setObjProp = function(codeArray, obj, key, value) {
      var statement = LOCAL_OBJ + getPropAccessor(key) + "=";
      var expression = this.enumerateField(obj, key, value);
      writeAssignment(codeArray, statement, expression);
    };
    proto.enumerateObject = function(codeArray, obj) {
      var klass = obj.constructor;
      if (cc.Class._isCCClass(klass)) this.enumerateCCClass(codeArray, obj, klass); else for (var key in obj) {
        if (!obj.hasOwnProperty(key) || 95 === key.charCodeAt(0) && 95 === key.charCodeAt(1) && "__type__" !== key) continue;
        var value = obj[key];
        if ("object" === typeof value && value && value === obj._iN$t) continue;
        this.setObjProp(codeArray, obj, key, value);
      }
    };
    proto.instantiateObj = function(obj) {
      if (obj instanceof cc.ValueType) return CCClass.getNewValueTypeCode(obj);
      if (obj instanceof cc.Asset) return this.getObjRef(obj);
      if (obj._objFlags & Destroyed) return null;
      var createCode;
      var ctor = obj.constructor;
      if (cc.Class._isCCClass(ctor)) {
        if (this.parent) if (this.parent instanceof cc.Component) {
          if (obj instanceof cc._BaseNode || obj instanceof cc.Component) return this.getObjRef(obj);
        } else if (this.parent instanceof cc._BaseNode) if (obj instanceof cc._BaseNode) {
          if (!obj.isChildOf(this.parent)) return this.getObjRef(obj);
        } else if (obj instanceof cc.Component && !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) return this.getObjRef(obj);
        createCode = new Declaration(LOCAL_OBJ, "Object.create(null)");
      }
      var codeArray = [ createCode ];
      obj._iN$t = {
        globalVar: "",
        source: codeArray
      };
      this.objsToClear_iN$t.push(obj);
      this.enumerateObject(codeArray, obj);
      return [ "(function(){", codeArray, "return o;})();" ];
    };
    function compile(node) {
      var root = node instanceof cc._BaseNode && node;
      var parser = new Parser(node, root);
      return parser.result;
    }
    module.exports = {
      compile: compile,
      equalsToDefault: equalsToDefault
    };
    false;
  }), {
    "./CCClass": 175,
    "./CCObject": 181,
    "./attribute": 188,
    "./compiler": 190,
    "./js": 196
  } ],
  195: [ (function(require, module, exports) {
    var CCObject = require("./CCObject");
    var Destroyed = CCObject.Flags.Destroyed;
    var PersistentMask = CCObject.Flags.PersistentMask;
    var Attr = require("./attribute");
    var _isDomNode = require("./utils").isDomNode;
    function instantiate(original, internal_force) {
      if (!internal_force) {
        if ("object" !== typeof original || Array.isArray(original)) {
          false;
          return null;
        }
        if (!original) {
          false;
          return null;
        }
        if (!cc.isValid(original)) {
          false;
          return null;
        }
        false;
      }
      var clone;
      if (original instanceof CCObject) {
        if (original._instantiate) {
          cc.game._isCloning = true;
          clone = original._instantiate();
          cc.game._isCloning = false;
          return clone;
        }
        if (original instanceof cc.Asset) {
          false;
          return null;
        }
      }
      cc.game._isCloning = true;
      clone = doInstantiate(original);
      cc.game._isCloning = false;
      return clone;
    }
    var objsToClearTmpVar = [];
    function doInstantiate(obj, parent) {
      if (Array.isArray(obj)) {
        false;
        return null;
      }
      if ((true, _isDomNode) && _isDomNode(obj)) {
        false;
        return null;
      }
      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;
    }
    var SERIALIZABLE = Attr.DELIMETER + "serializable";
    function enumerateCCClass(klass, obj, clone, parent) {
      var props = klass.__props__;
      var attrs = Attr.getClassAttrs(klass);
      for (var p = 0; p < props.length; p++) {
        var key = props[p];
        if (false !== attrs[key + SERIALIZABLE]) {
          var value = obj[key];
          clone[key] = "object" === typeof value && value ? value._iN$t || instantiateObj(value, parent) : value;
        }
      }
      (false, false) && (obj instanceof cc._BaseNode || obj instanceof cc.Component) && (clone._id = "");
    }
    function enumerateObject(obj, clone, parent) {
      obj._iN$t = clone;
      objsToClearTmpVar.push(obj);
      var klass = obj.constructor;
      if (cc.Class._isCCClass(klass)) enumerateCCClass(klass, obj, clone, parent); else for (var key in obj) {
        if (!obj.hasOwnProperty(key) || 95 === key.charCodeAt(0) && 95 === key.charCodeAt(1) && "__type__" !== key) continue;
        var value = obj[key];
        if ("object" === typeof value && value) {
          if (value === clone) continue;
          clone[key] = value._iN$t || instantiateObj(value, parent);
        } else clone[key] = value;
      }
      obj instanceof CCObject && (clone._objFlags &= PersistentMask);
    }
    function instantiateObj(obj, parent) {
      if (obj instanceof cc.ValueType) return obj.clone();
      if (obj instanceof cc.Asset) return obj;
      var clone;
      if (Array.isArray(obj)) {
        var len = obj.length;
        clone = new Array(len);
        obj._iN$t = clone;
        for (var i = 0; i < len; ++i) {
          var value = obj[i];
          clone[i] = "object" === typeof value && value ? value._iN$t || instantiateObj(value, parent) : value;
        }
        objsToClearTmpVar.push(obj);
        return clone;
      }
      if (obj._objFlags & Destroyed) return null;
      var ctor = obj.constructor;
      if (cc.Class._isCCClass(ctor)) {
        if (parent) if (parent instanceof cc.Component) {
          if (obj instanceof cc._BaseNode || obj instanceof cc.Component) return obj;
        } else if (parent instanceof cc._BaseNode) if (obj instanceof cc._BaseNode) {
          if (!obj.isChildOf(parent)) return obj;
        } else if (obj instanceof cc.Component && !obj.node.isChildOf(parent)) return obj;
        clone = new ctor();
      } else if (ctor === Object) clone = {}; else {
        if (ctor) return obj;
        clone = Object.create(null);
      }
      enumerateObject(obj, clone, parent);
      return clone;
    }
    instantiate._clone = doInstantiate;
    cc.instantiate = instantiate;
    module.exports = instantiate;
  }), {
    "./CCObject": 181,
    "./attribute": 188,
    "./utils": 200
  } ],
  196: [ (function(require, module, exports) {
    var tempCIDGenerater = new (require("./id-generater"))("TmpCId.");
    function _getPropertyDescriptor(obj, name) {
      while (obj) {
        var pd = Object.getOwnPropertyDescriptor(obj, name);
        if (pd) return pd;
        obj = Object.getPrototypeOf(obj);
      }
      return null;
    }
    function _copyprop(name, source, target) {
      var pd = _getPropertyDescriptor(source, name);
      Object.defineProperty(target, name, pd);
    }
    var js = {
      isNumber: function(obj) {
        return "number" === typeof obj || obj instanceof Number;
      },
      isString: function(obj) {
        return "string" === typeof obj || obj instanceof String;
      },
      addon: function(obj) {
        "use strict";
        obj = obj || {};
        for (var i = 1, length = arguments.length; i < length; i++) {
          var source = arguments[i];
          if (source) {
            if ("object" !== typeof source) {
              cc.errorID(5402, source);
              continue;
            }
            for (var name in source) name in obj || _copyprop(name, source, obj);
          }
        }
        return obj;
      },
      mixin: function(obj) {
        "use strict";
        obj = obj || {};
        for (var i = 1, length = arguments.length; i < length; i++) {
          var source = arguments[i];
          if (source) {
            if ("object" !== typeof source) {
              cc.errorID(5403, source);
              continue;
            }
            for (var name in source) _copyprop(name, source, obj);
          }
        }
        return obj;
      },
      extend: function(cls, base) {
        false;
        for (var p in base) base.hasOwnProperty(p) && (cls[p] = base[p]);
        cls.prototype = Object.create(base.prototype, {
          constructor: {
            value: cls,
            writable: true,
            configurable: true
          }
        });
        return cls;
      },
      getSuper: function(ctor) {
        false;
        var proto = ctor.prototype;
        var dunderProto = proto && Object.getPrototypeOf(proto);
        return dunderProto && dunderProto.constructor;
      },
      clear: function(obj) {
        var keys = Object.keys(obj);
        for (var i = 0; i < keys.length; i++) delete obj[keys[i]];
      },
      getPropertyDescriptor: _getPropertyDescriptor
    };
    var tmpValueDesc = {
      value: void 0,
      enumerable: false,
      writable: false,
      configurable: true
    };
    js.value = function(obj, prop, value, writable, enumerable) {
      tmpValueDesc.value = value;
      tmpValueDesc.writable = writable;
      tmpValueDesc.enumerable = enumerable;
      Object.defineProperty(obj, prop, tmpValueDesc);
      tmpValueDesc.value = void 0;
    };
    var tmpGetSetDesc = {
      get: null,
      set: null,
      enumerable: false
    };
    js.getset = function(obj, prop, getter, setter, enumerable) {
      if ("function" !== typeof setter) {
        enumerable = setter;
        setter = void 0;
      }
      tmpGetSetDesc.get = getter;
      tmpGetSetDesc.set = setter;
      tmpGetSetDesc.enumerable = enumerable;
      Object.defineProperty(obj, prop, tmpGetSetDesc);
      tmpGetSetDesc.get = null;
      tmpGetSetDesc.set = null;
    };
    var tmpGetDesc = {
      get: null,
      enumerable: false,
      configurable: false
    };
    js.get = function(obj, prop, getter, enumerable, configurable) {
      tmpGetDesc.get = getter;
      tmpGetDesc.enumerable = enumerable;
      tmpGetDesc.configurable = configurable;
      Object.defineProperty(obj, prop, tmpGetDesc);
      tmpGetDesc.get = null;
    };
    var tmpSetDesc = {
      set: null,
      enumerable: false,
      configurable: false
    };
    js.set = function(obj, prop, setter, enumerable, configurable) {
      tmpSetDesc.set = setter;
      tmpSetDesc.enumerable = enumerable;
      tmpSetDesc.configurable = configurable;
      Object.defineProperty(obj, prop, tmpSetDesc);
      tmpSetDesc.set = null;
    };
    js.getClassName = function(objOrCtor) {
      if ("function" === typeof objOrCtor) {
        var prototype = objOrCtor.prototype;
        if (prototype && prototype.hasOwnProperty("__classname__") && prototype.__classname__) return prototype.__classname__;
        var retval = "";
        objOrCtor.name && (retval = objOrCtor.name);
        if (objOrCtor.toString) {
          var arr, str = objOrCtor.toString();
          arr = "[" === str.charAt(0) ? str.match(/\[\w+\s*(\w+)\]/) : str.match(/function\s*(\w+)/);
          arr && 2 === arr.length && (retval = arr[1]);
        }
        return "Object" !== retval ? retval : "";
      }
      if (objOrCtor && objOrCtor.constructor) return js.getClassName(objOrCtor.constructor);
      return "";
    };
    function isTempClassId(id) {
      return "string" !== typeof id || id.startsWith(tempCIDGenerater.prefix);
    }
    (function() {
      var _idToClass = {};
      var _nameToClass = {};
      function getRegister(key, table) {
        return function(id, constructor) {
          constructor.prototype.hasOwnProperty(key) && delete table[constructor.prototype[key]];
          js.value(constructor.prototype, key, id);
          if (id) {
            var registered = table[id];
            if (registered && registered !== constructor) {
              var error = "A Class already exists with the same " + key + ' : "' + id + '".';
              false;
              cc.error(error);
            } else table[id] = constructor;
          }
        };
      }
      js._setClassId = getRegister("__cid__", _idToClass);
      var doSetClassName = getRegister("__classname__", _nameToClass);
      js.setClassName = function(className, constructor) {
        doSetClassName(className, constructor);
        if (!constructor.prototype.hasOwnProperty("__cid__")) {
          var id = className || tempCIDGenerater.getNewId();
          id && js._setClassId(id, constructor);
        }
      };
      js.unregisterClass = function() {
        for (var i = 0; i < arguments.length; i++) {
          var p = arguments[i].prototype;
          var classId = p.__cid__;
          classId && delete _idToClass[classId];
          var classname = p.__classname__;
          classname && delete _nameToClass[classname];
        }
      };
      js._getClassById = function(classId) {
        return _idToClass[classId];
      };
      js.getClassByName = function(classname) {
        return _nameToClass[classname];
      };
      js._getClassId = function(obj, allowTempId) {
        allowTempId = "undefined" === typeof allowTempId || allowTempId;
        var res;
        if ("function" === typeof obj && obj.prototype.hasOwnProperty("__cid__")) {
          res = obj.prototype.__cid__;
          if (!allowTempId && (false, false) && isTempClassId(res)) return "";
          return res;
        }
        if (obj && obj.constructor) {
          var prototype = obj.constructor.prototype;
          if (prototype && prototype.hasOwnProperty("__cid__")) {
            res = obj.__cid__;
            if (!allowTempId && (false, false) && isTempClassId(res)) return "";
            return res;
          }
        }
        return "";
      };
      false;
    })();
    js.obsolete = function(obj, obsoleted, newPropName, writable) {
      var oldName = /([^.]+)$/.exec(obsoleted)[0];
      function get() {
        false;
        return this[newPropName];
      }
      writable ? js.getset(obj, oldName, get, (function(value) {
        false;
        this[newPropName] = value;
      })) : js.get(obj, oldName, get);
    };
    js.obsoletes = function(obj, objName, props, writable) {
      for (var obsoleted in props) {
        var newName = props[obsoleted];
        js.obsolete(obj, objName + "." + obsoleted, newName, writable);
      }
    };
    var REGEXP_NUM_OR_STR = /(%d)|(%s)/;
    var REGEXP_STR = /%s/;
    js.formatStr = function() {
      var argLen = arguments.length;
      if (0 === argLen) return "";
      var msg = arguments[0];
      if (1 === argLen) return "" + msg;
      var hasSubstitution = "string" === typeof msg && REGEXP_NUM_OR_STR.test(msg);
      if (hasSubstitution) for (var i = 1; i < argLen; ++i) {
        var arg = arguments[i];
        var regExpToTest = "number" === typeof arg ? REGEXP_NUM_OR_STR : REGEXP_STR;
        regExpToTest.test(msg) ? msg = msg.replace(regExpToTest, arg) : msg += " " + arg;
      } else for (var _i = 1; _i < argLen; ++_i) msg += " " + arguments[_i];
      return msg;
    };
    js.shiftArguments = function() {
      var len = arguments.length - 1;
      var args = new Array(len);
      for (var i = 0; i < len; ++i) args[i] = arguments[i + 1];
      return args;
    };
    js.createMap = function(forceDictMode) {
      var map = Object.create(null);
      if (forceDictMode) {
        var INVALID_IDENTIFIER_1 = ".";
        var INVALID_IDENTIFIER_2 = "/";
        map[INVALID_IDENTIFIER_1] = true;
        map[INVALID_IDENTIFIER_2] = true;
        delete map[INVALID_IDENTIFIER_1];
        delete map[INVALID_IDENTIFIER_2];
      }
      return map;
    };
    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;
      }
      return false;
    }
    function fastRemove(array, value) {
      var index = array.indexOf(value);
      if (index >= 0) {
        array[index] = array[array.length - 1];
        --array.length;
      }
    }
    function verifyType(array, type) {
      if (array && array.length > 0) for (var i = 0; i < array.length; i++) if (!(array[i] instanceof type)) {
        cc.logID(1300);
        return false;
      }
      return true;
    }
    function removeArray(array, minusArr) {
      for (var i = 0, l = minusArr.length; i < l; i++) remove(array, minusArr[i]);
    }
    function appendObjectsAt(array, addObjs, index) {
      array.splice.apply(array, [ index, 0 ].concat(addObjs));
      return array;
    }
    var indexOf = Array.prototype.indexOf;
    function contains(array, value) {
      return array.indexOf(value) >= 0;
    }
    function copy(array) {
      var i, len = array.length, arr_clone = new Array(len);
      for (i = 0; i < len; i += 1) arr_clone[i] = array[i];
      return arr_clone;
    }
    js.array = {
      remove: remove,
      fastRemove: fastRemove,
      removeAt: removeAt,
      fastRemoveAt: fastRemoveAt,
      contains: contains,
      verifyType: verifyType,
      removeArray: removeArray,
      appendObjectsAt: appendObjectsAt,
      copy: copy,
      indexOf: indexOf,
      MutableForwardIterator: require("../utils/mutable-forward-iterator")
    };
    function Pool(cleanupFunc, size) {
      if ("number" === typeof cleanupFunc) {
        size = cleanupFunc;
        cleanupFunc = null;
      }
      this.get = null;
      this.count = 0;
      this._pool = new Array(size);
      this._cleanup = cleanupFunc;
    }
    Pool.prototype._get = function() {
      if (this.count > 0) {
        --this.count;
        var cache = this._pool[this.count];
        this._pool[this.count] = null;
        return cache;
      }
      return null;
    };
    Pool.prototype.put = function(obj) {
      var pool = this._pool;
      if (this.count < pool.length) {
        if (this._cleanup && false === this._cleanup(obj)) return;
        pool[this.count] = obj;
        ++this.count;
      }
    };
    Pool.prototype.resize = function(length) {
      if (length >= 0) {
        this._pool.length = length;
        this.count > length && (this.count = length);
      }
    };
    js.Pool = Pool;
    cc.js = js;
    module.exports = js;
  }), {
    "../utils/mutable-forward-iterator": 226,
    "./id-generater": 192
  } ],
  197: [ (function(require, module, exports) {
    var SerializableAttrs = {
      url: {
        canUsedInGet: true
      },
      default: {},
      serializable: {},
      editorOnly: {},
      rawType: {},
      formerlySerializedAs: {}
    };
    var TYPO_TO_CORRECT_DEV = false;
    function parseNotify(val, propName, notify, properties) {
      if (val.get || val.set) {
        false;
        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];
            v.canUsedInGet || delete val[attr];
          }
        }
      } else false;
    }
    function checkUrl(val, className, propName, url) {
      Array.isArray(url) && url.length > 0 && (url = url[0]);
      false;
      val.type = url;
    }
    function parseType(val, type, className, propName) {
      if (Array.isArray(type)) {
        var isArray;
        false;
        if (!(type.length > 0)) return cc.errorID(5508, className, propName);
        if (cc.RawAsset.isRawAssetType(type[0])) {
          val.url = type[0];
          delete val.type;
          return;
        }
        val.type = type = type[0];
      }
      false;
    }
    function postCheckType(val, type, className, propName) {
      false;
    }
    function getBaseClassWherePropertyDefined_DEV(propName, cls) {
      var res;
      false;
    }
    exports.getFullFormOfProperty = function(options) {
      var isLiteral = options && options.constructor === Object;
      if (!isLiteral) {
        if (Array.isArray(options) && options.length > 0) return {
          default: [],
          type: options,
          _short: true
        };
        if ("function" === typeof options) {
          var type = options;
          return cc.RawAsset.isRawAssetType(type) ? {
            default: "",
            url: type,
            _short: true
          } : {
            default: cc.isChildClassOf(type, cc.ValueType) ? new type() : null,
            type: type,
            _short: true
          };
        }
        return {
          default: options,
          _short: true
        };
      }
      return null;
    };
    exports.preprocessAttrs = function(properties, className, cls, es6) {
      for (var propName in properties) {
        var val = properties[propName];
        var fullForm = exports.getFullFormOfProperty(val);
        fullForm && (val = properties[propName] = fullForm);
        if (val) {
          var maybeTypeScript;
          false;
          var baseClass;
          false;
          var notify = val.notify;
          if (notify) {
            false;
            parseNotify(val, propName, notify, properties);
          }
          "type" in val && parseType(val, val.type, className, propName);
          "url" in val && checkUrl(val, className, propName, val.url);
          "type" in val && postCheckType(val, val.type, className, propName);
        }
      }
    };
    false;
    exports.validateMethodWithProps = function(func, funcName, className, cls, base) {
      false;
      if ("function" !== typeof func && null !== func) {
        var overrided;
        var baseFuc;
        var subFuc;
        var correct;
        false;
        return false;
      }
      false;
      return true;
    };
  }), {
    "./CCClass": 175
  } ],
  198: [ (function(require, module, exports) {
    var requiringFrames = [];
    cc._RF = {
      push: function(module, uuid, script) {
        if (void 0 === script) {
          script = uuid;
          uuid = "";
        }
        requiringFrames.push({
          uuid: uuid,
          script: script,
          module: module,
          exports: module.exports,
          beh: null
        });
      },
      pop: function() {
        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;
        }
      },
      peek: function() {
        return requiringFrames[requiringFrames.length - 1];
      }
    };
    false;
  }), {} ],
  199: [ (function(require, module, exports) {
    var _mounts = {};
    cc.url = {
      _rawAssets: "",
      _builtinRawAssets: "",
      normalize: function(url) {
        46 === url.charCodeAt(0) && 47 === url.charCodeAt(1) ? url = url.slice(2) : 47 === url.charCodeAt(0) && (url = url.slice(1));
        return url;
      },
      raw: function(url) {
        false;
        url = this.normalize(url);
        if (!url.startsWith("resources/")) {
          false;
          cc.errorID(7002, url);
        }
        return this._rawAssets + url;
      },
      builtinRaw: false,
      _init: function(mountPaths) {
        for (var dir in mountPaths) {
          var path = mountPaths[dir];
          path = cc.path.stripSep(path) + "/";
          _mounts[dir] = path;
        }
        this._rawAssets = _mounts.assets;
        this._builtinRawAssets = _mounts.internal;
      }
    };
    module.exports = cc.url;
  }), {} ],
  200: [ (function(require, module, exports) {
    module.exports = {
      contains: function(refNode, otherNode) {
        if ("function" == typeof refNode.contains) return refNode.contains(otherNode);
        if ("function" == typeof refNode.compareDocumentPosition) return !!(16 & refNode.compareDocumentPosition(otherNode));
        var node = otherNode.parentNode;
        if (node) do {
          if (node === refNode) return true;
          node = node.parentNode;
        } while (null !== node);
        return false;
      },
      isDomNode: "object" === typeof window && ("function" === typeof Node ? function(obj) {
        return obj instanceof Node;
      } : function(obj) {
        return obj && "object" === typeof obj && "number" === typeof obj.nodeType && "string" === typeof obj.nodeName;
      }),
      callInNextTick: function(callback, p1, p2) {
        callback && setTimeout((function() {
          callback(p1, p2);
        }), 0);
      }
    };
    false;
    false;
  }), {} ],
  201: [ (function(require, module, exports) {
    require("./platform/js");
    require("./value-types");
    require("./utils");
    require("./platform/CCInputManager");
    require("./platform/CCInputExtension");
    require("./event");
    require("./platform/CCSys");
    require("./platform/CCMacro");
    require("./load-pipeline");
    require("./textures");
    require("./CCDirector");
    require("./CCDirectorWebGL");
    require("./CCDirectorCanvas");
    true;
    require("./platform/CCSAXParser");
    require("./platform/CCView");
    require("./platform/CCScreen");
    require("./CCScheduler");
    require("./event-manager");
    require("./renderer");
  }), {
    "./CCDirector": 33,
    "./CCDirectorCanvas": 34,
    "./CCDirectorWebGL": 35,
    "./CCScheduler": 42,
    "./event": 114,
    "./event-manager": 110,
    "./load-pipeline": 136,
    "./platform/CCInputExtension": 178,
    "./platform/CCInputManager": 179,
    "./platform/CCMacro": 180,
    "./platform/CCSAXParser": 182,
    "./platform/CCScreen": 183,
    "./platform/CCSys": 184,
    "./platform/CCView": 185,
    "./platform/js": 196,
    "./renderer": 205,
    "./textures": 217,
    "./utils": 224,
    "./value-types": 238
  } ],
  202: [ (function(require, module, exports) {
    var Region = function() {
      this._minX = 0;
      this._minY = 0;
      this._maxX = 0;
      this._maxY = 0;
      this._width = 0;
      this._height = 0;
      this._area = 0;
    };
    var regionProto = Region.prototype;
    var regionPool = [];
    function regionCreate() {
      var region = regionPool.pop();
      region || (region = new Region());
      return region;
    }
    function regionRelease(region) {
      regionPool.push(region);
    }
    regionProto.setTo = function(minX, minY, maxX, maxY) {
      this._minX = minX;
      this._minY = minY;
      this._maxX = maxX;
      this._maxY = maxY;
      this.updateArea();
      return this;
    };
    regionProto.intValues = function() {
      this._minX = Math.floor(this._minX);
      this._minY = Math.floor(this._minY);
      this._maxX = Math.ceil(this._maxX);
      this._maxY = Math.ceil(this._maxY);
      this.updateArea();
    };
    regionProto.updateArea = function() {
      this._width = this._maxX - this._minX;
      this._height = this._maxY - this._minY;
      this._area = this._width * this._height;
    };
    regionProto.union = function(target) {
      if (this.isEmpty()) {
        this.setTo(target._minX, target._minY, target._maxX, target._maxY);
        return;
      }
      this._minX > target._minX && (this._minX = target._minX);
      this._minY > target._minY && (this._minY = target._minY);
      this._maxX < target._maxX && (this._maxX = target._maxX);
      this._maxY < target._maxY && (this._maxY = target._maxY);
      this.updateArea();
    };
    regionProto.setEmpty = function() {
      this._minX = 0;
      this._minY = 0;
      this._maxX = 0;
      this._maxY = 0;
      this._width = 0;
      this._height = 0;
      this._area = 0;
    };
    regionProto.isEmpty = function() {
      return this._width <= 0 || this._height <= 0;
    };
    regionProto.intersects = function(target) {
      if (this.isEmpty() || target.isEmpty()) return false;
      var max = this._minX > target._minX ? this._minX : target._minX;
      var min = this._maxX < target._maxX ? this._maxX : target._maxX;
      if (max > min) return false;
      max = this._minY > target._minY ? this._minY : target._minY;
      min = this._maxY < target._maxY ? this._maxY : target._maxY;
      return max <= min;
    };
    regionProto.updateRegion = function(bounds, matrix) {
      if (0 === bounds.width || 0 === bounds.height) {
        this.setEmpty();
        return;
      }
      var m = matrix;
      var a = m.a;
      var b = m.b;
      var c = m.c;
      var d = m.d;
      var tx = m.tx;
      var ty = m.ty;
      var x = bounds.x;
      var y = bounds.y;
      var xMax = x + bounds.width;
      var yMax = y + bounds.height;
      var minX, minY, maxX, maxY;
      if (1 === a && 0 === b && 0 === c && 1 === d) {
        minX = x + tx - 1;
        minY = y + ty - 1;
        maxX = xMax + tx + 1;
        maxY = yMax + ty + 1;
      } else {
        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;
        if (x0 > x1) {
          tmp = x0;
          x0 = x1;
          x1 = tmp;
        }
        if (x2 > x3) {
          tmp = x2;
          x2 = x3;
          x3 = tmp;
        }
        minX = (x0 < x2 ? x0 : x2) - 1;
        maxX = (x1 > x3 ? x1 : x3) + 1;
        if (y0 > y1) {
          tmp = y0;
          y0 = y1;
          y1 = tmp;
        }
        if (y2 > y3) {
          tmp = y2;
          y2 = y3;
          y3 = tmp;
        }
        minY = (y0 < y2 ? y0 : y2) - 1;
        maxY = (y1 > y3 ? y1 : y3) + 1;
      }
      this._minX = minX;
      this._minY = minY;
      this._maxX = maxX;
      this._maxY = maxY;
      this._width = maxX - minX;
      this._height = maxY - minY;
      this._area = this._width * this._height;
    };
    function unionArea(r1, r2) {
      var minX = r1._minX < r2._minX ? r1._minX : r2._minX;
      var minY = r1._minY < r2._minY ? r1._minY : r2._minY;
      var maxX = r1._maxX > r2._maxX ? r1._maxX : r2._maxX;
      var maxY = r1._maxY > r2._maxY ? r1._maxY : r2._maxY;
      return (maxX - minX) * (maxY - minY);
    }
    var DirtyRegion = function() {
      this.dirtyList = [];
      this.hasClipRect = false;
      this.clipWidth = 0;
      this.clipHeight = 0;
      this.clipArea = 0;
      this.clipRectChanged = false;
    };
    var dirtyRegionProto = DirtyRegion.prototype;
    dirtyRegionProto.setClipRect = function(width, height) {
      this.hasClipRect = true;
      this.clipRectChanged = true;
      this.clipWidth = Math.ceil(width);
      this.clipHeight = Math.ceil(height);
      this.clipArea = this.clipWidth * this.clipHeight;
    };
    dirtyRegionProto.addRegion = function(target) {
      var minX = target._minX, minY = target._minY, maxX = target._maxX, maxY = target._maxY;
      if (this.hasClipRect) {
        minX < 0 && (minX = 0);
        minY < 0 && (minY = 0);
        maxX > this.clipWidth && (maxX = this.clipWidth);
        maxY > this.clipHeight && (maxY = this.clipHeight);
      }
      if (minX >= maxX || minY >= maxY) return false;
      if (this.clipRectChanged) return true;
      var dirtyList = this.dirtyList;
      var region = regionCreate();
      dirtyList.push(region.setTo(minX, minY, maxX, maxY));
      this.mergeDirtyList(dirtyList);
      return true;
    };
    dirtyRegionProto.clear = function() {
      var dirtyList = this.dirtyList;
      var length = dirtyList.length;
      for (var i = 0; i < length; i++) regionRelease(dirtyList[i]);
      dirtyList.length = 0;
    };
    dirtyRegionProto.getDirtyRegions = function() {
      var dirtyList = this.dirtyList;
      if (this.clipRectChanged) {
        this.clipRectChanged = false;
        this.clear();
        var region = regionCreate();
        dirtyList.push(region.setTo(0, 0, this.clipWidth, this.clipHeight));
      } else while (this.mergeDirtyList(dirtyList)) ;
      var numDirty = this.dirtyList.length;
      if (numDirty > 0) for (var i = 0; i < numDirty; i++) this.dirtyList[i].intValues();
      return this.dirtyList;
    };
    dirtyRegionProto.mergeDirtyList = function(dirtyList) {
      var length = dirtyList.length;
      if (length < 2) return false;
      var hasClipRect = this.hasClipRect;
      var bestDelta = length > 3 ? Number.POSITIVE_INFINITY : 0;
      var mergeA = 0;
      var mergeB = 0;
      var totalArea = 0;
      for (var i = 0; i < length - 1; i++) {
        var regionA = dirtyList[i];
        hasClipRect && (totalArea += regionA.area);
        for (var j = i + 1; j < length; j++) {
          var regionB = dirtyList[j];
          var delta = unionArea(regionA, regionB) - regionA.area - regionB.area;
          if (bestDelta > delta) {
            mergeA = i;
            mergeB = j;
            bestDelta = delta;
          }
        }
      }
      hasClipRect && totalArea / this.clipArea > .95 && (this.clipRectChanged = true);
      if (mergeA !== mergeB) {
        var region = dirtyList[mergeB];
        dirtyList[mergeA].union(region);
        regionRelease(region);
        dirtyList.splice(mergeB, 1);
        return true;
      }
      return false;
    };
    cc.Region = Region;
    cc.DirtyRegion = DirtyRegion;
  }), {} ],
  203: [ (function(require, module, exports) {
    cc.rendererCanvas = {
      childrenOrderDirty: true,
      assignedZ: 0,
      assignedZStep: 1e-4,
      _transformNodePool: [],
      _renderCmds: [],
      _isCacheToCanvasOn: false,
      _cacheToCanvasCmds: {},
      _cacheInstanceIds: [],
      _currentID: 0,
      _clearColor: cc.color(),
      _clearFillStyle: "rgb(0, 0, 0)",
      _dirtyRegion: null,
      _allNeedDraw: true,
      _enableDirtyRegion: false,
      _debugDirtyRegion: false,
      _dirtyRegionCountThreshold: 10,
      init: function() {
        cc.sys.browserType !== cc.sys.BROWSER_TYPE_IE && cc.sys.browserType !== cc.sys.BROWSER_TYPE_UC || this.enableDirtyRegion(false);
      },
      getRenderCmd: function(renderableObject) {
        return renderableObject._createRenderCmd();
      },
      enableDirtyRegion: function(enabled) {
        this._enableDirtyRegion = enabled;
      },
      isDirtyRegionEnabled: function() {
        return this._enableDirtyRegion;
      },
      setDirtyRegionCountThreshold: function(threshold) {
        this._dirtyRegionCountThreshold = threshold;
      },
      _collectDirtyRegion: function() {
        var locCmds = this._renderCmds, i, len;
        var dirtyRegion = this._dirtyRegion;
        var localStatus = _ccsg.Node.CanvasRenderCmd.RegionStatus;
        var dirtryRegionCount = 0;
        var result = true;
        for (i = 0, len = locCmds.length; i < len; i++) {
          var cmd = locCmds[i];
          var regionFlag = cmd._regionFlag;
          var oldRegion = cmd._oldRegion;
          var currentRegion = cmd._currentRegion;
          if (regionFlag > localStatus.NotDirty) {
            ++dirtryRegionCount;
            dirtryRegionCount > this._dirtyRegionCountThreshold && (result = false);
            if (result) {
              !currentRegion.isEmpty() && dirtyRegion.addRegion(currentRegion);
              cmd._regionFlag > localStatus.Dirty && !oldRegion.isEmpty() && dirtyRegion.addRegion(oldRegion);
            }
            cmd._regionFlag = localStatus.NotDirty;
          }
        }
        return result;
      },
      _beginDrawDirtyRegion: function(ctxWrapper) {
        var ctx = ctxWrapper.getContext();
        var dirtyList = this._dirtyRegion.getDirtyRegions();
        ctx.save();
        ctxWrapper.setTransform({
          a: 1,
          b: 0,
          c: 0,
          d: 1,
          tx: 0,
          ty: 0
        }, 1, 1);
        ctx.beginPath();
        var x = 0, y = 0, width = 0, height = 0, scaleX = ctxWrapper._scaleX, scaleY = ctxWrapper._scaleY;
        for (var index = 0, count = dirtyList.length; index < count; ++index) {
          var region = dirtyList[index];
          x = (region._minX * scaleX | 0) - 1;
          y = (-region._maxY * scaleX | 0) - 1;
          width = 2 + (region._width * scaleX | 0);
          height = 2 + (region._height * scaleY | 0);
          ctx.rect(x, y, width, height);
        }
        ctx.clip();
      },
      _endDrawDirtyRegion: function(ctx) {
        ctx.restore();
      },
      _debugDrawDirtyRegion: function(ctxWrapper) {
        if (!this._debugDirtyRegion) return;
        var ctx = ctxWrapper.getContext();
        var dirtyList = this._dirtyRegion.getDirtyRegions();
        ctxWrapper.setTransform({
          a: 1,
          b: 0,
          c: 0,
          d: 1,
          tx: 0,
          ty: 0
        }, 1, 1);
        ctx.beginPath();
        var x = 0, y = 0, width = 0, height = 0, scaleX = ctxWrapper._scaleX, scaleY = ctxWrapper._scaleY;
        for (var index = 0, count = dirtyList.length; index < count; ++index) {
          var region = dirtyList[index];
          x = (region._minX * scaleX | 0) - 1;
          y = (-region._maxY * scaleX | 0) - 1;
          width = 2 + (region._width * scaleX | 0);
          height = 2 + (region._height * scaleY | 0);
          ctx.rect(x, y, width, height);
        }
        var oldstyle = ctx.fillStyle;
        ctx.fillStyle = "green";
        ctx.fill();
        ctx.fillStyle = oldstyle;
      },
      rendering: function(ctxWrapper) {
        var dirtyRegion = this._dirtyRegion = this._dirtyRegion || new cc.DirtyRegion();
        var viewport = cc._canvas;
        var wrapper = ctxWrapper || cc._renderContext;
        var ctx = wrapper.getContext();
        var scaleX = cc.view.getScaleX(), scaleY = cc.view.getScaleY();
        wrapper.setViewScale(scaleX, scaleY);
        wrapper.computeRealOffsetY();
        var dirtyList = this._dirtyRegion.getDirtyRegions();
        var locCmds = this._renderCmds, i, len;
        var allNeedDraw = this._allNeedDraw || !this._enableDirtyRegion;
        allNeedDraw || (allNeedDraw = allNeedDraw || !this._collectDirtyRegion());
        allNeedDraw || this._beginDrawDirtyRegion(wrapper);
        ctx.setTransform(1, 0, 0, 1, 0, 0);
        ctx.clearRect(0, 0, viewport.width, viewport.height);
        if (0 !== this._clearColor.r || 0 !== this._clearColor.g || 0 !== this._clearColor.b) {
          wrapper.setFillStyle(this._clearFillStyle);
          wrapper.setGlobalAlpha(this._clearColor.a);
          ctx.fillRect(0, 0, viewport.width, viewport.height);
        }
        for (i = 0, len = locCmds.length; i < len; i++) {
          var cmd = locCmds[i];
          if (!cmd._needDraw) continue;
          var needRendering = false;
          var cmdRegion = cmd._currentRegion;
          if (!cmdRegion || allNeedDraw) needRendering = true; else for (var index = 0, count = dirtyList.length; index < count; ++index) if (dirtyList[index].intersects(cmdRegion)) {
            needRendering = true;
            break;
          }
          needRendering && cmd.rendering(wrapper, scaleX, scaleY);
        }
        if (!allNeedDraw) {
          this._debugDrawDirtyRegion(wrapper);
          this._endDrawDirtyRegion(ctx);
        }
        dirtyRegion.clear();
        this._allNeedDraw = false;
      },
      _renderingToCacheCanvas: function(ctx, instanceID, scaleX, scaleY) {
        ctx || cc.logID(7600);
        scaleX = void 0 === scaleX ? 1 : scaleX;
        scaleY = void 0 === scaleY ? 1 : scaleY;
        instanceID = instanceID || this._currentID;
        var locCmds = this._cacheToCanvasCmds[instanceID], i, len;
        ctx.computeRealOffsetY();
        for (i = 0, len = locCmds.length; i < len; i++) locCmds[i].rendering(ctx, scaleX, scaleY);
        this._removeCache(instanceID);
        var locIDs = this._cacheInstanceIds;
        0 === locIDs.length ? this._isCacheToCanvasOn = false : this._currentID = locIDs[locIDs.length - 1];
      },
      _turnToCacheMode: function(renderTextureID) {
        this._isCacheToCanvasOn = true;
        renderTextureID = renderTextureID || 0;
        this._cacheToCanvasCmds[renderTextureID] = [];
        -1 === this._cacheInstanceIds.indexOf(renderTextureID) && this._cacheInstanceIds.push(renderTextureID);
        this._currentID = renderTextureID;
      },
      _turnToNormalMode: function() {
        this._isCacheToCanvasOn = false;
      },
      _removeCache: function(instanceID) {
        instanceID = instanceID || this._currentID;
        var cmds = this._cacheToCanvasCmds[instanceID];
        if (cmds) {
          cmds.length = 0;
          delete this._cacheToCanvasCmds[instanceID];
        }
        var locIDs = this._cacheInstanceIds;
        cc.js.array.remove(locIDs, instanceID);
      },
      resetFlag: function() {
        this.childrenOrderDirty = false;
        this._transformNodePool.length = 0;
      },
      transform: function() {
        var locPool = this._transformNodePool;
        locPool.sort(this._sortNodeByLevelAsc);
        for (var i = 0, len = locPool.length; i < len; i++) locPool[i].updateStatus();
        locPool.length = 0;
      },
      transformDirty: function() {
        return this._transformNodePool.length > 0;
      },
      _sortNodeByLevelAsc: function(n1, n2) {
        return n1._curLevel - n2._curLevel;
      },
      pushDirtyNode: function(node) {
        this._transformNodePool.push(node);
      },
      clear: function() {},
      clearRenderCommands: function() {
        this._renderCmds.length = 0;
        this._cacheInstanceIds.length = 0;
        this._isCacheToCanvasOn = false;
        this._allNeedDraw = true;
      },
      pushRenderCommand: function(cmd) {
        if (!cmd.rendering) return;
        if (this._isCacheToCanvasOn) {
          var currentId = this._currentID, locCmdBuffer = this._cacheToCanvasCmds;
          var cmdList = locCmdBuffer[currentId];
          -1 === cmdList.indexOf(cmd) && cmdList.push(cmd);
        } else -1 === this._renderCmds.indexOf(cmd) && this._renderCmds.push(cmd);
      }
    };
    (function() {
      cc.CanvasContextWrapper = function(context) {
        this._context = context;
        this._saveCount = 0;
        this._currentAlpha = context.globalAlpha;
        this._currentCompositeOperation = context.globalCompositeOperation;
        this._currentFillStyle = context.fillStyle;
        this._currentStrokeStyle = context.strokeStyle;
        this._offsetX = 0;
        this._offsetY = 0;
        this._realOffsetY = this.height;
        this._armatureMode = 0;
      };
      var proto = cc.CanvasContextWrapper.prototype;
      proto.resetCache = function() {
        var context = this._context;
        this._currentAlpha = context.globalAlpha;
        this._currentCompositeOperation = context.globalCompositeOperation;
        this._currentFillStyle = context.fillStyle;
        this._currentStrokeStyle = context.strokeStyle;
        this._realOffsetY = this._context.canvas.height + this._offsetY;
      };
      proto.setOffset = function(x, y) {
        this._offsetX = x;
        this._offsetY = y;
        this._realOffsetY = this._context.canvas.height + this._offsetY;
      };
      proto.computeRealOffsetY = function() {
        this._realOffsetY = this._context.canvas.height + this._offsetY;
      };
      proto.setViewScale = function(scaleX, scaleY) {
        this._scaleX = scaleX;
        this._scaleY = scaleY;
      };
      proto.getContext = function() {
        return this._context;
      };
      proto.save = function() {
        this._context.save();
        this._saveCount++;
      };
      proto.restore = function() {
        this._context.restore();
        this._currentAlpha = this._context.globalAlpha;
        this._saveCount--;
      };
      proto.setGlobalAlpha = function(alpha) {
        if (this._saveCount > 0) this._context.globalAlpha = alpha; else if (this._currentAlpha !== alpha) {
          this._currentAlpha = alpha;
          this._context.globalAlpha = alpha;
        }
      };
      proto.setCompositeOperation = function(compositionOperation) {
        if (this._saveCount > 0) this._context.globalCompositeOperation = compositionOperation; else if (this._currentCompositeOperation !== compositionOperation) {
          this._currentCompositeOperation = compositionOperation;
          this._context.globalCompositeOperation = compositionOperation;
        }
      };
      proto.setFillStyle = function(fillStyle) {
        this._context.fillStyle = fillStyle;
      };
      proto.setStrokeStyle = function(strokeStyle) {
        if (this._saveCount > 0) this._context.strokeStyle = strokeStyle; else if (this._currentStrokeStyle !== strokeStyle) {
          this._currentStrokeStyle = strokeStyle;
          this._context.strokeStyle = strokeStyle;
        }
      };
      proto.setTransform = function(t, scaleX, scaleY) {
        if (this._armatureMode > 0) {
          this.restore();
          this.save();
          this._context.transform(t.a, -t.b, -t.c, t.d, t.tx * scaleX, -t.ty * scaleY);
        } else this._context.setTransform(t.a * scaleX, -t.b * scaleY, -t.c * scaleX, t.d * scaleY, this._offsetX + t.tx * scaleX, this._realOffsetY - t.ty * scaleY);
      };
      proto._switchToArmatureMode = function(enable, t, scaleX, scaleY) {
        if (enable) {
          this._armatureMode++;
          this._context.setTransform(t.a, t.c, t.b, t.d, this._offsetX + t.tx * scaleX, this._realOffsetY - t.ty * scaleY);
          this.save();
        } else {
          this._armatureMode--;
          this.restore();
        }
      };
    })();
  }), {} ],
  204: [ (function(require, module, exports) {
    var _batchedInfo = {
      texture: null,
      blendSrc: null,
      blendDst: null,
      shader: null
    }, _batchBroken = false, _indexBuffer = null, _vertexBuffer = null, _maxVertexSize = 0, _batchingSize = 0, _indexSize = 0, _sizePerVertex = 6, _vertexData = null, _vertexDataSize = 0, _vertexDataF32 = null, _vertexDataUI32 = null, _indexData = null, _prevIndexSize = 0, _pureQuad = true, _IS_IOS = false;
    function updateBuffer(numVertex) {
      var gl = cc._renderContext;
      if (_indexBuffer) {
        var indexCount = 6 * Math.ceil(numVertex / 4);
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _indexBuffer);
        _indexData = new Uint16Array(indexCount);
        var currentQuad = 0;
        for (var i = 0, len = indexCount; i < len; i += 6) {
          _indexData[i] = currentQuad + 0;
          _indexData[i + 1] = currentQuad + 1;
          _indexData[i + 2] = currentQuad + 2;
          _indexData[i + 3] = currentQuad + 1;
          _indexData[i + 4] = currentQuad + 2;
          _indexData[i + 5] = currentQuad + 3;
          currentQuad += 4;
        }
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _indexData, gl.DYNAMIC_DRAW);
      }
      if (_vertexBuffer) {
        _vertexDataSize = numVertex * _sizePerVertex;
        var byteLength = 4 * _vertexDataSize;
        _vertexData = new ArrayBuffer(byteLength);
        _vertexDataF32 = new Float32Array(_vertexData);
        _vertexDataUI32 = new Uint32Array(_vertexData);
        gl.bindBuffer(gl.ARRAY_BUFFER, _vertexBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, _vertexDataF32, gl.DYNAMIC_DRAW);
      }
      _maxVertexSize = numVertex - 200;
    }
    function initQuadBuffer(numVertex) {
      var gl = cc._renderContext;
      if (null === _indexBuffer) {
        _vertexBuffer = gl.createBuffer();
        _indexBuffer = gl.createBuffer();
      }
      updateBuffer(numVertex);
    }
    var VertexType = cc.Enum({
      QUAD: 0,
      TRIANGLE: 1,
      CUSTOM: 2
    });
    cc.rendererWebGL = {
      mat4Identity: null,
      childrenOrderDirty: true,
      assignedZ: 0,
      assignedZStep: .01,
      VertexType: VertexType,
      _transformNodePool: [],
      _renderCmds: [],
      _isCacheToBufferOn: false,
      _cacheToBufferCmds: {},
      _cacheInstanceIds: [],
      _currentID: 0,
      _clearColor: {
        r: 0,
        g: 0,
        b: 0,
        a: 1
      },
      init: function() {
        var gl = cc._renderContext;
        gl.disable(gl.CULL_FACE);
        gl.disable(gl.DEPTH_TEST);
        this._initExtensions([ "OES_element_index_uint" ]);
        this.mat4Identity = new cc.math.Matrix4();
        this.mat4Identity.identity();
        initQuadBuffer(cc.macro.BATCH_VERTEX_COUNT);
        cc.sys.os === cc.sys.OS_IOS && (_IS_IOS = true);
      },
      _initExtensions: function(extensions) {
        this._extensions = this._extensions || {};
        for (var i = 0; i < extensions.length; ++i) {
          var name = extensions[i];
          try {
            var ext = gl.getExtension(name);
            ext && (this._extensions[name] = ext);
          } catch (e) {
            cc.error(e);
          }
        }
      },
      getVertexSize: function() {
        return _maxVertexSize;
      },
      getRenderCmd: function(renderableObject) {
        return renderableObject._createRenderCmd();
      },
      _turnToCacheMode: function(renderTextureID) {
        this._isCacheToBufferOn = true;
        renderTextureID = renderTextureID || 0;
        this._cacheToBufferCmds[renderTextureID] ? this._cacheToBufferCmds[renderTextureID].length = 0 : this._cacheToBufferCmds[renderTextureID] = [];
        -1 === this._cacheInstanceIds.indexOf(renderTextureID) && this._cacheInstanceIds.push(renderTextureID);
        this._currentID = renderTextureID;
      },
      _turnToNormalMode: function() {
        this._isCacheToBufferOn = false;
      },
      _removeCache: function(instanceID) {
        instanceID = instanceID || this._currentID;
        var cmds = this._cacheToBufferCmds[instanceID];
        if (cmds) {
          cmds.length = 0;
          delete this._cacheToBufferCmds[instanceID];
        }
        var locIDs = this._cacheInstanceIds;
        cc.js.array.remove(locIDs, instanceID);
      },
      _renderingToBuffer: function(renderTextureId) {
        renderTextureId = renderTextureId || this._currentID;
        var locCmds = this._cacheToBufferCmds[renderTextureId];
        var ctx = cc._renderContext;
        this.rendering(ctx, locCmds);
        this._removeCache(renderTextureId);
        var locIDs = this._cacheInstanceIds;
        0 === locIDs.length ? this._isCacheToBufferOn = false : this._currentID = locIDs[locIDs.length - 1];
      },
      resetFlag: function() {
        this.childrenOrderDirty && (this.childrenOrderDirty = false);
        this._transformNodePool.length = 0;
      },
      transform: function() {
        var locPool = this._transformNodePool;
        locPool.sort(this._sortNodeByLevelAsc);
        var i, len, cmd;
        for (i = 0, len = locPool.length; i < len; i++) {
          cmd = locPool[i];
          cmd.updateStatus();
        }
        locPool.length = 0;
      },
      transformDirty: function() {
        return this._transformNodePool.length > 0;
      },
      _sortNodeByLevelAsc: function(n1, n2) {
        return n1._curLevel - n2._curLevel;
      },
      pushDirtyNode: function(node) {
        this._transformNodePool.push(node);
      },
      clearRenderCommands: function() {
        this._renderCmds.length = 0;
      },
      clear: function() {
        var gl = cc._renderContext;
        gl.clearColor(this._clearColor.r, this._clearColor.g, this._clearColor.b, this._clearColor.a);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
      },
      setDepthTest: function(enable) {
        var gl = cc._renderContext;
        if (enable) {
          gl.clearDepth(1);
          gl.enable(gl.DEPTH_TEST);
          gl.depthFunc(gl.LEQUAL);
        } else gl.disable(gl.DEPTH_TEST);
      },
      pushRenderCommand: function(cmd) {
        if (!cmd.rendering && !cmd.uploadData) return;
        if (this._isCacheToBufferOn) {
          var currentId = this._currentID, locCmdBuffer = this._cacheToBufferCmds;
          var cmdList = locCmdBuffer[currentId];
          -1 === cmdList.indexOf(cmd) && cmdList.push(cmd);
        } else this._renderCmds.push(cmd);
      },
      _increaseBatchingSize: function(increment, vertexType, indices) {
        vertexType = vertexType || VertexType.QUAD;
        var i, curr;
        switch (vertexType) {
         case VertexType.QUAD:
          for (i = 0; i < increment; i += 4) {
            curr = _batchingSize + i;
            _indexData[_indexSize++] = curr + 0;
            _indexData[_indexSize++] = curr + 1;
            _indexData[_indexSize++] = curr + 2;
            _indexData[_indexSize++] = curr + 1;
            _indexData[_indexSize++] = curr + 2;
            _indexData[_indexSize++] = curr + 3;
          }
          break;

         case VertexType.TRIANGLE:
          _pureQuad = false;
          for (i = 0; i < increment; i += 3) {
            curr = _batchingSize + i;
            _indexData[_indexSize++] = curr + 0;
            _indexData[_indexSize++] = curr + 1;
            _indexData[_indexSize++] = curr + 2;
          }
          break;

         case VertexType.CUSTOM:
          _pureQuad = false;
          var len = indices.length;
          for (i = 0; i < len; i++) _indexData[_indexSize++] = _batchingSize + indices[i];
          break;

         default:
          return;
        }
        _batchingSize += increment;
      },
      _updateBatchedInfo: function(texture, blendFunc, shaderProgram) {
        if (texture !== _batchedInfo.texture || blendFunc.src !== _batchedInfo.blendSrc || blendFunc.dst !== _batchedInfo.blendDst || shaderProgram !== _batchedInfo.shader) {
          this._batchRendering();
          _batchedInfo.texture = texture;
          _batchedInfo.blendSrc = blendFunc.src;
          _batchedInfo.blendDst = blendFunc.dst;
          _batchedInfo.shader = shaderProgram;
          return true;
        }
        return false;
      },
      _breakBatch: function() {
        _batchBroken = true;
      },
      _uploadBufferData: function(cmd) {
        _batchingSize >= _maxVertexSize && this._batchRendering();
        var node = cmd._node;
        var texture = cmd._texture || node._texture || node._spriteFrame && node._spriteFrame._texture;
        var blendSrc = node._blendFunc.src;
        var blendDst = node._blendFunc.dst;
        var shader = cmd._shaderProgram;
        if (_batchBroken || _batchedInfo.texture !== texture || _batchedInfo.blendSrc !== blendSrc || _batchedInfo.blendDst !== blendDst || _batchedInfo.shader !== shader) {
          this._batchRendering();
          _batchedInfo.texture = texture;
          _batchedInfo.blendSrc = blendSrc;
          _batchedInfo.blendDst = blendDst;
          _batchedInfo.shader = shader;
          _batchBroken = false;
        }
        var len = cmd.uploadData(_vertexDataF32, _vertexDataUI32, _batchingSize * _sizePerVertex);
        if (len > 0) {
          var i, curr, type = cmd.vertexType || VertexType.QUAD;
          switch (type) {
           case VertexType.QUAD:
            for (i = 0; i < len; i += 4) {
              curr = _batchingSize + i;
              _indexData[_indexSize++] = curr + 0;
              _indexData[_indexSize++] = curr + 1;
              _indexData[_indexSize++] = curr + 2;
              _indexData[_indexSize++] = curr + 1;
              _indexData[_indexSize++] = curr + 2;
              _indexData[_indexSize++] = curr + 3;
            }
            break;

           case VertexType.TRIANGLE:
            _pureQuad = false;
            for (i = 0; i < len; i += 3) {
              curr = _batchingSize + i;
              _indexData[_indexSize++] = curr + 0;
              _indexData[_indexSize++] = curr + 1;
              _indexData[_indexSize++] = curr + 2;
            }
            break;

           case VertexType.CUSTOM:
            _pureQuad = false;
            cmd.uploadIndexData && (_indexSize += cmd.uploadIndexData(_indexData, _indexSize, _batchingSize));
            break;

           default:
            return;
          }
          _batchingSize += len;
        }
      },
      _batchRendering: function() {
        if (0 === _batchingSize || !_batchedInfo.texture) return;
        var gl = cc._renderContext;
        var texture = _batchedInfo.texture;
        var shader = _batchedInfo.shader;
        var uploadAll = _batchingSize > .5 * _maxVertexSize;
        if (shader) {
          shader.use();
          shader._updateProjectionUniform();
        }
        cc.gl.blendFunc(_batchedInfo.blendSrc, _batchedInfo.blendDst);
        cc.gl.bindTexture2DN(0, texture);
        gl.bindBuffer(gl.ARRAY_BUFFER, _vertexBuffer);
        if (uploadAll) gl.bufferData(gl.ARRAY_BUFFER, _vertexDataF32, gl.DYNAMIC_DRAW); else {
          var view = _vertexDataF32.subarray(0, _batchingSize * _sizePerVertex);
          gl.bufferData(gl.ARRAY_BUFFER, view, gl.DYNAMIC_DRAW);
        }
        gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION);
        gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR);
        gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS);
        gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0);
        gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12);
        gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16);
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _indexBuffer);
        (!_prevIndexSize || !_pureQuad || _indexSize > _prevIndexSize) && (uploadAll ? gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _indexData, gl.DYNAMIC_DRAW) : gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _indexData.subarray(0, _indexSize), gl.DYNAMIC_DRAW));
        gl.drawElements(gl.TRIANGLES, _indexSize, gl.UNSIGNED_SHORT, 0);
        cc.g_NumberOfDraws++;
        if (_pureQuad) _prevIndexSize = _indexSize; else {
          _prevIndexSize = 0;
          _pureQuad = true;
        }
        _batchingSize = 0;
        _indexSize = 0;
      },
      rendering: function(ctx, cmds) {
        var locCmds = cmds || this._renderCmds, i, len, cmd, context = ctx || cc._renderContext;
        context.bindBuffer(context.ARRAY_BUFFER, null);
        cc.gl.bindTexture2DN(0, null);
        for (i = 0, len = locCmds.length; i < len; ++i) {
          cmd = locCmds[i];
          if (!cmd._needDraw) continue;
          if (cmd.uploadData) this._uploadBufferData(cmd); else {
            _batchingSize > 0 && this._batchRendering();
            cmd.rendering(context);
          }
        }
        this._batchRendering();
        _batchedInfo.texture = null;
      }
    };
  }), {} ],
  205: [ (function(require, module, exports) {
    require("./RendererCanvas");
    require("./RendererWebGL");
    require("./DirtyRegion");
  }), {
    "./DirtyRegion": 202,
    "./RendererCanvas": 203,
    "./RendererWebGL": 204
  } ],
  206: [ (function(require, module, exports) {
    _ccsg.Scene = _ccsg.Node.extend({
      _className: "Scene",
      ctor: function() {
        _ccsg.Node.prototype.ctor.call(this);
        this._ignoreAnchorPointForPosition = true;
        this.setAnchorPoint(.5, .5);
        this.setContentSize(cc.director.getWinSize());
      }
    });
  }), {} ],
  207: [ (function(require, module, exports) {
    var EventTarget = require("../event/event-target");
    var Misc = require("../utils/misc");
    _ccsg.Sprite = _ccsg.Node.extend({
      dirty: false,
      _recursiveDirty: null,
      _shouldBeHidden: false,
      _transformToBatch: null,
      _blendFunc: null,
      _texture: null,
      _rect: null,
      _rectRotated: false,
      _offsetPosition: null,
      _unflippedOffsetPositionFromCenter: null,
      _opacityModifyRGB: false,
      _flippedX: false,
      _flippedY: false,
      _textureLoaded: false,
      _className: "Sprite",
      ctor: function(fileName, rect, rotated) {
        var self = this;
        _ccsg.Node.prototype.ctor.call(self);
        EventTarget.call(self);
        self._shouldBeHidden = false;
        self._offsetPosition = cc.p(0, 0);
        self._unflippedOffsetPositionFromCenter = cc.p(0, 0);
        self._blendFunc = {
          src: cc.macro.BLEND_SRC,
          dst: cc.macro.BLEND_DST
        };
        self._rect = cc.rect(0, 0, 0, 0);
        self._softInit(fileName, rect, rotated);
      },
      textureLoaded: function() {
        return this._textureLoaded;
      },
      addLoadedEventListener: function(callback, target) {
        this.once("load", callback, target);
      },
      isDirty: function() {
        return this.dirty;
      },
      setDirty: function(bDirty) {
        this.dirty = bDirty;
      },
      isTextureRectRotated: function() {
        return this._rectRotated;
      },
      getTextureRect: function() {
        return cc.rect(this._rect);
      },
      getOffsetPosition: function() {
        return cc.p(this._offsetPosition);
      },
      _getOffsetX: function() {
        return this._offsetPosition.x;
      },
      _getOffsetY: function() {
        return this._offsetPosition.y;
      },
      getBlendFunc: function() {
        return this._blendFunc;
      },
      initWithSpriteFrame: function(spriteFrame) {
        cc.assertID(spriteFrame, 2606);
        if (!spriteFrame.textureLoaded()) {
          this._textureLoaded = false;
          spriteFrame.once("load", this._renderCmd._spriteFrameLoadedCallback, this._renderCmd);
        }
        var rotated = cc._renderType !== cc.game.RENDER_TYPE_CANVAS && spriteFrame._rotated;
        var ret = this.initWithTexture(spriteFrame.getTexture(), spriteFrame.getRect(), rotated);
        this.setSpriteFrame(spriteFrame);
        return ret;
      },
      initWithSpriteFrameName: function() {
        cc.warnID(2608);
        return;
      },
      setVertexRect: function(rect) {
        var locRect = this._rect;
        locRect.x = rect.x;
        locRect.y = rect.y;
        locRect.width = rect.width;
        locRect.height = rect.height;
      },
      setFlippedX: function(flippedX) {
        if (this._flippedX !== flippedX) {
          this._flippedX = flippedX;
          this.setTextureRect(this._rect, this._rectRotated, this._contentSize);
          this.setNodeDirty(true);
        }
      },
      setFlippedY: function(flippedY) {
        if (this._flippedY !== flippedY) {
          this._flippedY = flippedY;
          this.setTextureRect(this._rect, this._rectRotated, this._contentSize);
          this.setNodeDirty(true);
        }
      },
      isFlippedX: function() {
        return this._flippedX;
      },
      isFlippedY: function() {
        return this._flippedY;
      },
      setOpacityModifyRGB: function(modify) {
        if (this._opacityModifyRGB !== modify) {
          this._opacityModifyRGB = modify;
          this._renderCmd._setColorDirty();
        }
      },
      isOpacityModifyRGB: function() {
        return this._opacityModifyRGB;
      },
      setDisplayFrameWithAnimationName: function(animationName, frameIndex) {
        cc.assertID(animationName, 2610);
        var cache = cc.spriteFrameAnimationCache.getAnimation(animationName);
        if (!cache) {
          cc.logID(2602);
          return;
        }
        var animFrame = cache.getFrames()[frameIndex];
        if (!animFrame) {
          cc.logID(2603);
          return;
        }
        this.setSpriteFrame(animFrame.getSpriteFrame());
      },
      getTexture: function() {
        return this._texture;
      },
      _softInit: function(fileName, rect, rotated) {
        if (void 0 === fileName) _ccsg.Sprite.prototype.init.call(this); else if (cc.js.isString(fileName)) "#" === fileName[0] ? cc.logID(2728, fileName) : _ccsg.Sprite.prototype.init.call(this, fileName, rect); else if ("object" === typeof fileName) if (fileName instanceof cc.Texture2D) this.initWithTexture(fileName, rect, rotated); else if (fileName instanceof cc.SpriteFrame) this.initWithSpriteFrame(fileName); else if (fileName instanceof HTMLImageElement || fileName instanceof HTMLCanvasElement) {
          var texture2d = new cc.Texture2D();
          texture2d.initWithElement(fileName);
          texture2d.handleLoadedTexture();
          this.initWithTexture(texture2d);
        }
      },
      getQuad: function() {
        return null;
      },
      setBlendFunc: function(src, dst) {
        var locBlendFunc = this._blendFunc;
        if (void 0 === dst) {
          locBlendFunc.src = src.src;
          locBlendFunc.dst = src.dst;
        } else {
          locBlendFunc.src = src;
          locBlendFunc.dst = dst;
        }
        this._renderCmd.updateBlendFunc(locBlendFunc);
      },
      init: function() {
        var _t = this;
        if (arguments.length > 0) return _t.initWithFile(arguments[0], arguments[1]);
        _t.dirty = _t._recursiveDirty = false;
        _t._blendFunc.src = cc.macro.BLEND_SRC;
        _t._blendFunc.dst = cc.macro.BLEND_DST;
        _t.texture = null;
        _t._flippedX = _t._flippedY = false;
        _t.anchorX = .5;
        _t.anchorY = .5;
        _t._offsetPosition.x = 0;
        _t._offsetPosition.y = 0;
        _t.setTextureRect(cc.rect(0, 0, 0, 0), false, cc.size(0, 0));
        return true;
      },
      initWithFile: function(filename, rect) {
        cc.assertID(filename, 2609);
        var tex = cc.textureCache.getTextureForKey(filename);
        if (tex) {
          if (!rect) {
            var size = tex.getContentSize();
            rect = cc.rect(0, 0, size.width, size.height);
          }
          return this.initWithTexture(tex, rect);
        }
        tex = cc.textureCache.addImage(filename);
        return this.initWithTexture(tex, rect || cc.rect(0, 0, tex.width, tex.height));
      },
      initWithTexture: function(texture, rect, rotated, counterclockwise) {
        var _t = this;
        cc.assertID(0 !== arguments.length, 2710);
        rotated = rotated || false;
        texture = this._renderCmd._handleTextureForRotatedTexture(texture, rect, rotated, counterclockwise);
        _t._recursiveDirty = false;
        _t.dirty = false;
        _t._opacityModifyRGB = true;
        _t._blendFunc.src = cc.macro.BLEND_SRC;
        _t._blendFunc.dst = cc.macro.BLEND_DST;
        _t._flippedX = _t._flippedY = false;
        _t.setAnchorPoint(.5, .5);
        _t._offsetPosition.x = 0;
        _t._offsetPosition.y = 0;
        var locTextureLoaded = texture.loaded;
        _t._textureLoaded = locTextureLoaded;
        if (!locTextureLoaded) {
          _t._rectRotated = rotated;
          if (rect) {
            _t._rect.x = rect.x;
            _t._rect.y = rect.y;
            _t._rect.width = rect.width;
            _t._rect.height = rect.height;
          }
          _t.texture && _t.texture.off("load", _t._renderCmd._textureLoadedCallback, _t._renderCmd);
          texture.once("load", _t._renderCmd._textureLoadedCallback, _t._renderCmd);
          _t.setTexture(texture);
          return true;
        }
        rect || (rect = cc.rect(0, 0, texture.width, texture.height));
        this._renderCmd._checkTextureBoundary(texture, rect, rotated);
        _t.setTexture(texture);
        _t.setTextureRect(rect, rotated);
        this.emit("load");
        return true;
      },
      setTextureRect: function(rect, rotated, untrimmedSize, needConvert) {
        var _t = this;
        _t._rectRotated = rotated || false;
        _t.setContentSize(untrimmedSize || rect);
        _t.setVertexRect(rect);
        _t._renderCmd._setTextureCoords(rect, needConvert);
        var relativeOffsetX = _t._unflippedOffsetPositionFromCenter.x, relativeOffsetY = _t._unflippedOffsetPositionFromCenter.y;
        _t._flippedX && (relativeOffsetX = -relativeOffsetX);
        _t._flippedY && (relativeOffsetY = -relativeOffsetY);
        var locRect = _t._rect;
        _t._offsetPosition.x = relativeOffsetX + (_t._contentSize.width - locRect.width) / 2;
        _t._offsetPosition.y = relativeOffsetY + (_t._contentSize.height - locRect.height) / 2;
      },
      setSpriteFrame: function(newFrame) {
        var _t = this;
        cc.assertID(newFrame, 2712);
        this.setNodeDirty(true);
        var frameOffset = newFrame.getOffset();
        _t._unflippedOffsetPositionFromCenter.x = frameOffset.x;
        _t._unflippedOffsetPositionFromCenter.y = frameOffset.y;
        var pNewTexture = newFrame.getTexture();
        var locTextureLoaded = newFrame.textureLoaded();
        if (locTextureLoaded) {
          _t._textureLoaded = true;
          if (pNewTexture !== _t._texture) {
            _t._setTexture(pNewTexture);
            _t.setColor(_t._realColor);
          }
          _t.setTextureRect(newFrame.getRect(), newFrame.isRotated(), newFrame.getOriginalSize());
        } else {
          _t._textureLoaded = false;
          newFrame.once("load", (function(event) {
            var sender = event.currentTarget;
            _t._textureLoaded = true;
            var locNewTexture = sender.getTexture();
            locNewTexture !== _t._texture && _t._setTexture(locNewTexture);
            _t.setTextureRect(sender.getRect(), sender.isRotated(), sender.getOriginalSize());
            _t.emit("load");
            _t.setColor(_t._realColor);
          }), _t);
        }
        this._renderCmd._updateForSetSpriteFrame(pNewTexture);
      },
      setDisplayFrame: function(newFrame) {
        cc.logID(2604);
        this.setSpriteFrame(newFrame);
      },
      isFrameDisplayed: function(frame) {
        return this._renderCmd.isFrameDisplayed(frame);
      },
      displayFrame: function() {
        return this.getSpriteFrame();
      },
      getSpriteFrame: function() {
        return new cc.SpriteFrame(this._texture, this._rect, this._rectRotated, this._unflippedOffsetPositionFromCenter, this._contentSize);
      },
      setTexture: function(texture) {
        if (!texture) return this._renderCmd._setTexture(null);
        var isFileName = cc.js.isString(texture);
        isFileName && (texture = cc.textureCache.addImage(texture));
        if (texture.loaded) {
          this._setTexture(texture, isFileName);
          this.setColor(this._realColor);
          this._textureLoaded = true;
          this.emit("load");
        } else {
          this._renderCmd._setTexture(texture);
          texture.once("load", (function(event) {
            this._setTexture(texture, isFileName);
            this.setColor(this._realColor);
            this._textureLoaded = true;
            this.emit("load");
          }), this);
        }
      },
      _setTexture: function(texture, change) {
        this._renderCmd._setTexture(texture);
        change && this._changeRectWithTexture(texture);
      },
      _changeRectWithTexture: function(texture) {
        var rect = cc.rect(0, 0, texture.width, texture.height);
        this.setTextureRect(rect);
      },
      _createRenderCmd: function() {
        return cc._renderType === cc.game.RENDER_TYPE_CANVAS ? new _ccsg.Sprite.CanvasRenderCmd(this) : new _ccsg.Sprite.WebGLRenderCmd(this);
      }
    });
    cc.js.addon(_ccsg.Sprite.prototype, EventTarget.prototype);
    var SameNameGetSets = [ "opacity", "color", "texture", "quad" ];
    var DiffNameGetSets = {
      opacityModifyRGB: [ "isOpacityModifyRGB", "setOpacityModifyRGB" ],
      flippedX: [ "isFlippedX", "setFlippedX" ],
      flippedY: [ "isFlippedY", "setFlippedY" ],
      offsetX: [ "_getOffsetX" ],
      offsetY: [ "_getOffsetY" ],
      textureRectRotated: [ "isTextureRectRotated" ]
    };
    Misc.propertyDefine(_ccsg.Sprite, SameNameGetSets, DiffNameGetSets);
  }), {
    "../event/event-target": 112,
    "../utils/misc": 225
  } ],
  208: [ (function(require, module, exports) {
    _ccsg.Sprite.CanvasRenderCmd = function(renderable) {
      this._rootCtor(renderable);
      this._needDraw = true;
      this._textureCoord = {
        renderX: 0,
        renderY: 0,
        x: 0,
        y: 0,
        width: 0,
        height: 0,
        validRect: false
      };
      this._blendFuncStr = "source-over";
      this._colorized = false;
      this._textureToRender = null;
    };
    var proto = _ccsg.Sprite.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
    proto.constructor = _ccsg.Sprite.CanvasRenderCmd;
    proto.setDirtyRecursively = function(value) {};
    proto._setTexture = function(texture) {
      var node = this._node;
      if (node._texture !== texture) {
        node._textureLoaded = !!texture && texture.loaded;
        node._texture = texture;
        var rect = cc.rect(0, 0, texture.width, texture.height);
        node.setTextureRect(rect);
        this._updateColor();
      }
    };
    proto._setColorDirty = function() {
      this.setDirtyFlag(_ccsg.Node._dirtyFlags.colorDirty | _ccsg.Node._dirtyFlags.opacityDirty);
    };
    proto.isFrameDisplayed = function(frame) {
      var node = this._node;
      if (frame.getTexture() !== node._texture) return false;
      return cc.rectEqualToRect(frame.getRect(), node._rect);
    };
    proto.updateBlendFunc = function(blendFunc) {
      this._blendFuncStr = _ccsg.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc(blendFunc);
    };
    proto._handleTextureForRotatedTexture = function(texture, rect, rotated, counterclockwise) {
      if (rotated && texture.isLoaded()) {
        var tempElement = texture.getHtmlElementObj();
        tempElement = _ccsg.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, rect, counterclockwise);
        var tempTexture = new cc.Texture2D();
        tempTexture.initWithElement(tempElement);
        tempTexture.handleLoadedTexture();
        texture = tempTexture;
        rect.x = rect.y = 0;
        this._node._rect = cc.rect(0, 0, rect.width, rect.height);
      }
      return texture;
    };
    proto._checkTextureBoundary = function(texture, rect, rotated) {
      if (texture && texture.url) {
        var _x = rect.x + rect.width, _y = rect.y + rect.height;
        _x > texture.width && cc.errorID(3300, texture.url);
        _y > texture.height && cc.errorID(3400, texture.url);
      }
    };
    proto.rendering = function(ctx, scaleX, scaleY) {
      var node = this._node;
      var locTextureCoord = this._textureCoord, alpha = this._displayedOpacity / 255;
      var texture = this._textureToRender || node._texture;
      if (texture && (0 === locTextureCoord.width || 0 === locTextureCoord.height || !texture.loaded) || 0 === alpha) return;
      var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
      var locX = node._offsetPosition.x, locHeight = node._rect.height, locWidth = node._rect.width, locY = -node._offsetPosition.y - locHeight, image;
      wrapper.setTransform(this._worldTransform, scaleX, scaleY);
      wrapper.setCompositeOperation(this._blendFuncStr);
      wrapper.setGlobalAlpha(alpha);
      (node._flippedX || node._flippedY) && wrapper.save();
      if (node._flippedX) {
        locX = -locX - locWidth;
        context.scale(-1, 1);
      }
      if (node._flippedY) {
        locY = node._offsetPosition.y;
        context.scale(1, -1);
      }
      var sx, sy, sw, sh, x, y, w, h;
      if (this._colorized) {
        sx = 0;
        sy = 0;
      } else {
        sx = locTextureCoord.renderX;
        sy = locTextureCoord.renderY;
      }
      sw = locTextureCoord.width;
      sh = locTextureCoord.height;
      x = locX;
      y = locY;
      w = locWidth;
      h = locHeight;
      if (texture && texture._image) {
        image = texture._image;
        if ("" !== texture._pattern) {
          wrapper.setFillStyle(context.createPattern(image, texture._pattern));
          context.fillRect(x, y, w, h);
        } else context.drawImage(image, sx, sy, sw, sh, x, y, w, h);
      } else {
        var contentSize = node._contentSize;
        if (locTextureCoord.validRect) {
          var curColor = this._displayedColor;
          wrapper.setFillStyle("rgba(" + curColor.r + "," + curColor.g + "," + curColor.b + ",1)");
          context.fillRect(x, y, contentSize.width, contentSize.height);
        }
      }
      (node._flippedX || node._flippedY) && wrapper.restore();
      cc.g_NumberOfDraws++;
    };
    proto._updateColor = function() {
      var node = this._node;
      var texture = node._texture, rect = this._textureCoord;
      var dColor = this._displayedColor;
      if (texture) if (255 !== dColor.r || 255 !== dColor.g || 255 !== dColor.b) {
        this._textureToRender = texture._generateColorTexture(dColor.r, dColor.g, dColor.b, rect);
        this._colorized = true;
      } else if (texture) {
        this._textureToRender = texture;
        this._colorized = false;
      }
    };
    proto._updateForSetSpriteFrame = function(pNewTexture, textureLoaded) {
      this._colorized = false;
      this._textureCoord.renderX = this._textureCoord.x;
      this._textureCoord.renderY = this._textureCoord.y;
      textureLoaded = textureLoaded || pNewTexture.loaded;
      if (textureLoaded) {
        var curColor = this._node.getColor();
        255 === curColor.r && 255 === curColor.g && 255 === curColor.b || this._updateColor();
      }
    };
    proto._spriteFrameLoadedCallback = function(event) {
      var node = this._node, spriteFrame = event.currentTarget;
      node.setTextureRect(spriteFrame.getRect(), spriteFrame.isRotated(), spriteFrame.getOriginalSize());
      this._updateColor();
      node.emit("load");
    };
    proto._textureLoadedCallback = function(event) {
      var node = this._node, sender = event.currentTarget;
      if (node._textureLoaded) return;
      node._textureLoaded = true;
      var locRect = node._rect;
      if (locRect) {
        if (cc._rectEqualToZero(locRect)) {
          locRect.width = sender.width;
          locRect.height = sender.height;
        }
      } else locRect = cc.rect(0, 0, sender.width, sender.height);
      node.texture = sender;
      node.setTextureRect(locRect, node._rectRotated);
      var locColor = this._displayedColor;
      255 === locColor.r && 255 === locColor.g && 255 === locColor.b || this._updateColor();
      node.emit("load");
    };
    proto._setTextureCoords = function(rect) {
      var locTextureRect = this._textureCoord;
      locTextureRect.renderX = locTextureRect.x = 0 | rect.x;
      locTextureRect.renderY = locTextureRect.y = 0 | rect.y;
      locTextureRect.width = 0 | rect.width;
      locTextureRect.height = 0 | rect.height;
      locTextureRect.validRect = !(0 === locTextureRect.width || 0 === locTextureRect.height || locTextureRect.x < 0 || locTextureRect.y < 0);
    };
    _ccsg.Sprite.CanvasRenderCmd._cutRotateImageToCanvas = function(texture, rect, counterclockwise) {
      if (!texture) return null;
      if (!rect) return texture;
      counterclockwise = null == counterclockwise || counterclockwise;
      var nCanvas = document.createElement("canvas");
      nCanvas.width = rect.width;
      nCanvas.height = rect.height;
      var ctx = nCanvas.getContext("2d");
      ctx.translate(nCanvas.width / 2, nCanvas.height / 2);
      counterclockwise ? ctx.rotate(-1.5707963267948966) : ctx.rotate(1.5707963267948966);
      ctx.drawImage(texture, rect.x, rect.y, rect.height, rect.width, -rect.height / 2, -rect.width / 2, rect.height, rect.width);
      return nCanvas;
    };
  }), {} ],
  209: [ (function(require, module, exports) {
    var macro = cc.macro;
    _ccsg.Sprite.WebGLRenderCmd = function(renderable) {
      this._rootCtor(renderable);
      this._needDraw = true;
      this._vertices = [ {
        x: 0,
        y: 0,
        u: 0,
        v: 0
      }, {
        x: 0,
        y: 0,
        u: 0,
        v: 0
      }, {
        x: 0,
        y: 0,
        u: 0,
        v: 0
      }, {
        x: 0,
        y: 0,
        u: 0,
        v: 0
      } ];
      this._dirty = false;
      this._recursiveDirty = false;
      this._shaderProgram = cc.shaderCache.programForKey(macro.SHADER_SPRITE_POSITION_TEXTURECOLOR);
    };
    var proto = _ccsg.Sprite.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype);
    proto.constructor = _ccsg.Sprite.WebGLRenderCmd;
    proto.updateBlendFunc = function(blendFunc) {};
    proto.setDirtyFlag = function(dirtyFlag) {
      _ccsg.Node.WebGLRenderCmd.prototype.setDirtyFlag.call(this, dirtyFlag);
      this._dirty = true;
    };
    proto.setDirtyRecursively = function(value) {
      this._recursiveDirty = value;
      this._dirty = value;
      var locChildren = this._node._children, child, l = locChildren ? locChildren.length : 0;
      for (var i = 0; i < l; i++) {
        child = locChildren[i];
        child instanceof _ccsg.Sprite && child._renderCmd.setDirtyRecursively(value);
      }
    };
    proto._handleTextureForRotatedTexture = function(texture) {
      return texture;
    };
    proto.isFrameDisplayed = function(frame) {
      var node = this._node;
      return cc.rectEqualToRect(frame.getRect(), node._rect) && frame.getTexture().url === node._texture.url && cc.pointEqualToPoint(frame.getOffset(), node._unflippedOffsetPositionFromCenter);
    };
    proto._updateForSetSpriteFrame = function() {};
    proto._spriteFrameLoadedCallback = function(event) {
      var spriteFrame = event.currentTarget;
      this._node.setTextureRect(spriteFrame.getRect(), spriteFrame.isRotated(), spriteFrame.getOriginalSize());
      this._node.emit("load");
    };
    proto._textureLoadedCallback = function(event) {
      var node = this._node, sender = event.currentTarget;
      if (node._textureLoaded) return;
      node._textureLoaded = true;
      var locRect = node._rect;
      if (locRect) {
        if (cc._rectEqualToZero(locRect)) {
          locRect.width = sender.width;
          locRect.height = sender.height;
        }
      } else locRect = cc.rect(0, 0, sender.width, sender.height);
      node.texture = sender;
      node.setTextureRect(locRect, node._rectRotated);
      node.emit("load");
      cc.renderer.childrenOrderDirty = true;
    };
    proto._setTextureCoords = function(rect) {
      var node = this._node;
      var tex = node._texture;
      var uvs = this._vertices;
      if (!tex) return;
      var atlasWidth = tex.pixelWidth;
      var atlasHeight = tex.pixelHeight;
      var left, right, top, bottom, tempSwap;
      if (node._rectRotated) {
        if (macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL) {
          left = (2 * rect.x + 1) / (2 * atlasWidth);
          right = left + (2 * rect.height - 2) / (2 * atlasWidth);
          top = (2 * rect.y + 1) / (2 * atlasHeight);
          bottom = top + (2 * rect.width - 2) / (2 * atlasHeight);
        } else {
          left = rect.x / atlasWidth;
          right = (rect.x + rect.height) / atlasWidth;
          top = rect.y / atlasHeight;
          bottom = (rect.y + rect.width) / atlasHeight;
        }
        if (node._flippedX) {
          tempSwap = top;
          top = bottom;
          bottom = tempSwap;
        }
        if (node._flippedY) {
          tempSwap = left;
          left = right;
          right = tempSwap;
        }
        uvs[0].u = right;
        uvs[0].v = top;
        uvs[1].u = left;
        uvs[1].v = top;
        uvs[2].u = right;
        uvs[2].v = bottom;
        uvs[3].u = left;
        uvs[3].v = bottom;
      } else {
        if (macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL) {
          left = (2 * rect.x + 1) / (2 * atlasWidth);
          right = left + (2 * rect.width - 2) / (2 * atlasWidth);
          top = (2 * rect.y + 1) / (2 * atlasHeight);
          bottom = top + (2 * rect.height - 2) / (2 * atlasHeight);
        } else {
          left = rect.x / atlasWidth;
          right = (rect.x + rect.width) / atlasWidth;
          top = rect.y / atlasHeight;
          bottom = (rect.y + rect.height) / atlasHeight;
        }
        if (node._flippedX) {
          tempSwap = left;
          left = right;
          right = tempSwap;
        }
        if (node._flippedY) {
          tempSwap = top;
          top = bottom;
          bottom = tempSwap;
        }
        uvs[0].u = left;
        uvs[0].v = top;
        uvs[1].u = left;
        uvs[1].v = bottom;
        uvs[2].u = right;
        uvs[2].v = top;
        uvs[3].u = right;
        uvs[3].v = bottom;
      }
    };
    proto._setColorDirty = function() {};
    proto._updateBlendFunc = function() {
      var node = this._node;
      if (node._texture && node._texture.hasPremultipliedAlpha()) {
        node._blendFunc.src = macro.BLEND_SRC;
        node._blendFunc.dst = macro.BLEND_DST;
        node.opacityModifyRGB = true;
      } else {
        node._blendFunc.src = macro.SRC_ALPHA;
        node._blendFunc.dst = macro.ONE_MINUS_SRC_ALPHA;
        node.opacityModifyRGB = false;
      }
    };
    proto._setTexture = function(texture) {
      var node = this._node;
      if (node._texture !== texture) {
        node._textureLoaded = !!texture && texture.loaded;
        node._texture = texture;
        this._updateBlendFunc();
        node._textureLoaded && (cc.renderer.childrenOrderDirty = true);
      }
    };
    proto._checkTextureBoundary = function(texture, rect, rotated) {
      if (texture && texture.url) {
        var _x, _y;
        if (rotated) {
          _x = rect.x + rect.height;
          _y = rect.y + rect.width;
        } else {
          _x = rect.x + rect.width;
          _y = rect.y + rect.height;
        }
        _x > texture.width && cc.errorID(3300, texture.url);
        _y > texture.height && cc.errorID(3400, texture.url);
      }
    };
    proto.transform = function(parentCmd, recursive) {
      this.originTransform(parentCmd, recursive);
      var node = this._node, lx = node._offsetPosition.x, rx = lx + node._rect.width, by = node._offsetPosition.y, ty = by + node._rect.height, wt = this._worldTransform;
      var vertices = this._vertices;
      vertices[0].x = lx * wt.a + ty * wt.c + wt.tx;
      vertices[0].y = lx * wt.b + ty * wt.d + wt.ty;
      vertices[1].x = lx * wt.a + by * wt.c + wt.tx;
      vertices[1].y = lx * wt.b + by * wt.d + wt.ty;
      vertices[2].x = rx * wt.a + ty * wt.c + wt.tx;
      vertices[2].y = rx * wt.b + ty * wt.d + wt.ty;
      vertices[3].x = rx * wt.a + by * wt.c + wt.tx;
      vertices[3].y = rx * wt.b + by * wt.d + wt.ty;
    };
    proto.needDraw = function() {
      var node = this._node, locTexture = node._texture;
      return this._needDraw && locTexture;
    };
    proto.uploadData = function(f32buffer, ui32buffer, vertexDataOffset) {
      var node = this._node, locTexture = node._texture;
      if (!(locTexture && locTexture.loaded && node._rect.width && node._rect.height) || !this._displayedOpacity) return 0;
      var opacity = this._displayedOpacity;
      var color, colorVal = this._displayedColor._val;
      if (node._opacityModifyRGB) {
        var a = opacity / 255, r = this._displayedColor.r * a, g = this._displayedColor.g * a, b = this._displayedColor.b * a;
        color = (opacity << 24 >>> 0) + (b << 16) + (g << 8) + r;
      } else color = (opacity << 24 >>> 0) + ((65280 & colorVal) << 8) + ((16711680 & colorVal) >> 8) + (colorVal >>> 24);
      var z = node._vertexZ;
      var vertices = this._vertices;
      var i, len = vertices.length, vertex, offset = vertexDataOffset;
      for (i = 0; i < len; ++i) {
        vertex = vertices[i];
        f32buffer[offset] = vertex.x;
        f32buffer[offset + 1] = vertex.y;
        f32buffer[offset + 2] = z;
        ui32buffer[offset + 3] = color;
        f32buffer[offset + 4] = vertex.u;
        f32buffer[offset + 5] = vertex.v;
        offset += 6;
      }
      return len;
    };
  }), {} ],
  210: [ (function(require, module, exports) {
    var EventTarget = require("../event/event-target");
    function sortIndex(a, b) {
      return a - b;
    }
    var dataPool = {
      _pool: {},
      _lengths: [],
      put: function(data) {
        var length = data.length;
        if (this._pool[length]) this._pool[length].push(data); else {
          this._pool[length] = [ data ];
          this._lengths.push(length);
          this._lengths.sort(sortIndex);
        }
      },
      get: function(length) {
        var id;
        for (var i = 0; i < this._lengths.length; i++) if (this._lengths[i] >= length) {
          id = this._lengths[i];
          break;
        }
        return id ? this._pool[id].pop() : void 0;
      }
    };
    var macro = cc.macro, webgl, vl, vb, vt, vr;
    var simpleQuadGenerator = {
      _rebuildQuads_base: function(sprite) {
        var spriteFrame = sprite._spriteFrame, contentSize = sprite._contentSize, isTrimmedContentSize = sprite._isTrimmedContentSize;
        var vertices = sprite._vertices, corner = sprite._corner, l, b, r, t;
        if (isTrimmedContentSize) {
          l = 0;
          b = 0;
          r = contentSize.width;
          t = contentSize.height;
        } else {
          var originalSize = spriteFrame._originalSize;
          var rect = spriteFrame._rect;
          var offset = spriteFrame._offset;
          var cw = contentSize.width, ch = contentSize.height;
          var ow = originalSize.width, oh = originalSize.height;
          var rw = rect.width, rh = rect.height;
          var scaleX = cw / ow;
          var scaleY = ch / oh;
          var trimmLeft = offset.x + (ow - rw) / 2;
          var trimmRight = offset.x - (ow - rw) / 2;
          var trimmedBottom = offset.y + (oh - rh) / 2;
          var trimmedTop = offset.y - (oh - rh) / 2;
          l = trimmLeft * scaleX;
          b = trimmedBottom * scaleY;
          r = cw + trimmRight * scaleX;
          t = ch + trimmedTop * scaleY;
        }
        if (vertices.length < 8) {
          dataPool.put(vertices);
          vertices = dataPool.get(8) || new Float32Array(8);
          sprite._vertices = vertices;
        }
        if (webgl) {
          var wt = sprite._renderCmd._worldTransform;
          var wta = wt.a, wtb = wt.b, wtc = wt.c, wtd = wt.d, wtx = wt.tx, wty = wt.ty;
          var la = l * wta, lb = l * wtb, ra = r * wta, rb = r * wtb, tcx = t * wtc + wtx, tdy = t * wtd + wty, bcx = b * wtc + wtx, bdy = b * wtd + wty;
          vertices[0] = la + bcx;
          vertices[1] = lb + bdy;
          vertices[2] = ra + bcx;
          vertices[3] = rb + bdy;
          vertices[4] = la + tcx;
          vertices[5] = lb + tdy;
          vertices[6] = ra + tcx;
          vertices[7] = rb + tdy;
        } else {
          vertices[0] = l;
          vertices[1] = b;
          vertices[2] = r;
          vertices[3] = b;
          vertices[4] = l;
          vertices[5] = t;
          vertices[6] = r;
          vertices[7] = t;
        }
        corner[0] = 0;
        corner[1] = 2;
        corner[2] = 4;
        corner[3] = 6;
        sprite._uvsDirty && this._calculateUVs(sprite, spriteFrame);
        sprite._vertCount = 4;
      },
      _calculateUVs: function(sprite, spriteFrame) {
        var uvs = sprite._uvs;
        var atlasWidth = spriteFrame._texture.width;
        var atlasHeight = spriteFrame._texture.height;
        var textureRect = spriteFrame._rect;
        if (uvs.length < 8) {
          dataPool.put(uvs);
          uvs = dataPool.get(8) || new Float32Array(8);
          sprite._uvs = uvs;
        }
        var l, b, r, t;
        var texelCorrect = macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL ? .5 : 0;
        if (spriteFrame._rotated) {
          l = (textureRect.x + texelCorrect) / atlasWidth;
          b = (textureRect.y + textureRect.width - texelCorrect) / atlasHeight;
          r = (textureRect.x + textureRect.height - texelCorrect) / atlasWidth;
          t = (textureRect.y + texelCorrect) / atlasHeight;
          uvs[0] = l;
          uvs[1] = t;
          uvs[2] = l;
          uvs[3] = b;
          uvs[4] = r;
          uvs[5] = t;
          uvs[6] = r;
          uvs[7] = b;
        } else {
          l = (textureRect.x + texelCorrect) / atlasWidth;
          b = (textureRect.y + textureRect.height - texelCorrect) / atlasHeight;
          r = (textureRect.x + textureRect.width - texelCorrect) / atlasWidth;
          t = (textureRect.y + texelCorrect) / atlasHeight;
          uvs[0] = l;
          uvs[1] = b;
          uvs[2] = r;
          uvs[3] = b;
          uvs[4] = l;
          uvs[5] = t;
          uvs[6] = r;
          uvs[7] = t;
        }
      }
    };
    var scale9QuadGenerator = {
      x: new Array(4),
      y: new Array(4),
      _rebuildQuads_base: function(sprite) {
        var spriteFrame = sprite._spriteFrame, contentSize = sprite._contentSize, insetLeft = sprite._insetLeft, insetRight = sprite._insetRight, insetTop = sprite._insetTop, insetBottom = sprite._insetBottom;
        var vertices = sprite._vertices;
        var wt = sprite._renderCmd._worldTransform;
        var leftWidth, centerWidth, rightWidth;
        var topHeight, centerHeight, bottomHeight;
        var rect = spriteFrame._rect;
        var corner = sprite._corner;
        leftWidth = insetLeft;
        rightWidth = insetRight;
        centerWidth = rect.width - leftWidth - rightWidth;
        topHeight = insetTop;
        bottomHeight = insetBottom;
        centerHeight = rect.height - topHeight - bottomHeight;
        var preferSize = contentSize;
        var sizableWidth = preferSize.width - leftWidth - rightWidth;
        var sizableHeight = preferSize.height - topHeight - bottomHeight;
        var xScale = preferSize.width / (leftWidth + rightWidth);
        var yScale = preferSize.height / (topHeight + bottomHeight);
        xScale = isNaN(xScale) || xScale > 1 ? 1 : xScale;
        yScale = isNaN(yScale) || yScale > 1 ? 1 : yScale;
        sizableWidth = sizableWidth < 0 ? 0 : sizableWidth;
        sizableHeight = sizableHeight < 0 ? 0 : sizableHeight;
        var x = this.x;
        var y = this.y;
        x[0] = 0;
        x[1] = leftWidth * xScale;
        x[2] = x[1] + sizableWidth;
        x[3] = preferSize.width;
        y[0] = 0;
        y[1] = bottomHeight * yScale;
        y[2] = y[1] + sizableHeight;
        y[3] = preferSize.height;
        if (vertices.length < 32) {
          dataPool.put(vertices);
          vertices = dataPool.get(32) || new Float32Array(32);
          sprite._vertices = vertices;
        }
        var offset = 0, row, col;
        if (webgl) for (row = 0; row < 4; row++) for (col = 0; col < 4; col++) {
          vertices[offset] = x[col] * wt.a + y[row] * wt.c + wt.tx;
          vertices[offset + 1] = x[col] * wt.b + y[row] * wt.d + wt.ty;
          offset += 2;
        } else for (row = 0; row < 4; row++) for (col = 0; col < 4; col++) {
          vertices[offset] = x[col];
          vertices[offset + 1] = y[row];
          offset += 2;
        }
        corner[0] = 0;
        corner[1] = 6;
        corner[2] = 24;
        corner[3] = 30;
        sprite._uvsDirty && this._calculateUVs(sprite, spriteFrame, insetLeft, insetRight, insetTop, insetBottom);
      },
      _calculateUVs: function(sprite, spriteFrame, insetLeft, insetRight, insetTop, insetBottom) {
        var uvs = sprite._uvs;
        var rect = spriteFrame._rect;
        var atlasWidth = spriteFrame._texture.width;
        var atlasHeight = spriteFrame._texture.height;
        var leftWidth, centerWidth, rightWidth;
        var topHeight, centerHeight, bottomHeight;
        var textureRect = spriteFrame._rect;
        leftWidth = insetLeft;
        rightWidth = insetRight;
        centerWidth = rect.width - leftWidth - rightWidth;
        topHeight = insetTop;
        bottomHeight = insetBottom;
        centerHeight = rect.height - topHeight - bottomHeight;
        if (uvs.length < 32) {
          dataPool.put(uvs);
          uvs = dataPool.get(32) || new Float32Array(32);
          sprite._uvs = uvs;
        }
        var u = this.x;
        var v = this.y;
        var texelCorrect = macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL ? .5 : 0;
        var offset = 0, row, col;
        if (spriteFrame._rotated) {
          u[0] = (textureRect.x + texelCorrect) / atlasWidth;
          u[1] = (bottomHeight + textureRect.x) / atlasWidth;
          u[2] = (bottomHeight + centerHeight + textureRect.x) / atlasWidth;
          u[3] = (textureRect.x + textureRect.height - texelCorrect) / atlasWidth;
          v[3] = (textureRect.y + texelCorrect) / atlasHeight;
          v[2] = (leftWidth + textureRect.y) / atlasHeight;
          v[1] = (leftWidth + centerWidth + textureRect.y) / atlasHeight;
          v[0] = (textureRect.y + textureRect.width - texelCorrect) / atlasHeight;
          for (row = 0; row < 4; row++) for (col = 0; col < 4; col++) {
            uvs[offset] = u[row];
            uvs[offset + 1] = v[3 - col];
            offset += 2;
          }
        } else {
          u[0] = (textureRect.x + texelCorrect) / atlasWidth;
          u[1] = (leftWidth + textureRect.x) / atlasWidth;
          u[2] = (leftWidth + centerWidth + textureRect.x) / atlasWidth;
          u[3] = (textureRect.x + textureRect.width - texelCorrect) / atlasWidth;
          v[3] = (textureRect.y + texelCorrect) / atlasHeight;
          v[2] = (topHeight + textureRect.y) / atlasHeight;
          v[1] = (topHeight + centerHeight + textureRect.y) / atlasHeight;
          v[0] = (textureRect.y + textureRect.height - texelCorrect) / atlasHeight;
          for (row = 0; row < 4; row++) for (col = 0; col < 4; col++) {
            uvs[offset] = u[col];
            uvs[offset + 1] = v[row];
            offset += 2;
          }
        }
      }
    };
    var tiledQuadGenerator = {
      _rebuildQuads_base: function(sprite, spriteFrame, contentSize) {
        var spriteFrame = sprite._spriteFrame, contentSize = sprite._contentSize, vertices = sprite._vertices, corner = sprite._corner, wt = sprite._renderCmd._worldTransform, uvs = sprite._uvs;
        var atlasWidth = spriteFrame._texture.width;
        var atlasHeight = spriteFrame._texture.height;
        var textureRect = spriteFrame._rect;
        var u0, v0, u1, v1;
        var texelCorrect = macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL ? .5 : 0;
        if (spriteFrame._rotated) {
          u0 = (textureRect.x + texelCorrect) / atlasWidth;
          u1 = (textureRect.x + textureRect.height - texelCorrect) / atlasWidth;
          v0 = (textureRect.y + textureRect.width - texelCorrect) / atlasHeight;
          v1 = (textureRect.y + texelCorrect) / atlasHeight;
        } else {
          u0 = (textureRect.x + texelCorrect) / atlasWidth;
          u1 = (textureRect.x + textureRect.width - texelCorrect) / atlasWidth;
          v0 = (textureRect.y + textureRect.height - texelCorrect) / atlasHeight;
          v1 = (textureRect.y + texelCorrect) / atlasHeight;
        }
        var rectWidth = textureRect.width;
        var rectHeight = textureRect.height;
        var hRepeat = contentSize.width / rectWidth;
        var vRepeat = contentSize.height / rectHeight;
        var row = Math.ceil(vRepeat), col = Math.ceil(hRepeat);
        row * col > 16384 && cc.errorID(2625);
        var dataLength = row * col * 4 * 2;
        if (vertices.length < dataLength) {
          dataPool.put(vertices);
          vertices = dataPool.get(dataLength) || new Float32Array(dataLength);
          sprite._vertices = vertices;
        }
        if (uvs.length < dataLength) {
          dataPool.put(uvs);
          uvs = dataPool.get(dataLength) || new Float32Array(dataLength);
          sprite._uvs = uvs;
        }
        var offset = 0, l, b, r, t;
        sprite._vertCount = 0;
        for (var vindex = 0; vindex < row; ++vindex) for (var hindex = 0; hindex < col; ++hindex) {
          l = rectWidth * hindex;
          b = rectHeight * vindex;
          r = rectWidth * Math.min(hindex + 1, hRepeat);
          t = rectHeight * Math.min(vindex + 1, vRepeat);
          if (webgl) {
            var la = l * wt.a, lb = l * wt.b, ra = r * wt.a, rb = r * wt.b, tcx = t * wt.c + wt.tx, tdy = t * wt.d + wt.ty, bcx = b * wt.c + wt.tx, bdy = b * wt.d + wt.ty;
            vertices[offset] = la + bcx;
            vertices[offset + 1] = lb + bdy;
            vertices[offset + 2] = ra + bcx;
            vertices[offset + 3] = rb + bdy;
            vertices[offset + 4] = la + tcx;
            vertices[offset + 5] = lb + tdy;
            vertices[offset + 6] = ra + tcx;
            vertices[offset + 7] = rb + tdy;
          } else {
            vertices[offset] = l;
            vertices[offset + 1] = b;
            vertices[offset + 2] = r;
            vertices[offset + 3] = b;
            vertices[offset + 4] = l;
            vertices[offset + 5] = t;
            vertices[offset + 6] = r;
            vertices[offset + 7] = t;
          }
          if (spriteFrame._rotated) {
            uvs[offset] = u0;
            uvs[offset + 1] = v1;
            uvs[offset + 2] = u0;
            uvs[offset + 3] = t = v1 + (v0 - v1) * Math.min(1, hRepeat - hindex);
            uvs[offset + 4] = r = u0 + (u1 - u0) * Math.min(1, vRepeat - vindex);
            uvs[offset + 5] = v1;
            uvs[offset + 6] = r;
            uvs[offset + 7] = t;
          } else {
            uvs[offset] = u0;
            uvs[offset + 1] = v0;
            uvs[offset + 2] = r = u0 + (u1 - u0) * Math.min(1, hRepeat - hindex);
            uvs[offset + 3] = v0;
            uvs[offset + 4] = u0;
            uvs[offset + 5] = t = v0 + (v1 - v0) * Math.min(1, vRepeat - vindex);
            uvs[offset + 6] = r;
            uvs[offset + 7] = t;
          }
          offset += 8;
          sprite._vertCount += 4;
          if (offset > dataLength) return;
        }
        corner[0] = 0;
        corner[1] = 8 * (col - 1) + 2;
        corner[2] = (row - 1) * col * 8 + 4;
        corner[3] = dataLength - 2;
      }
    };
    var fillQuadGeneratorBar = {
      _rebuildQuads_base: function(sprite) {
        var spriteFrame = sprite._spriteFrame, contentSize = sprite._contentSize;
        var fillStart = sprite._fillStart;
        var fillRange = sprite._fillRange;
        if (fillRange < 0) {
          fillStart += fillRange;
          fillRange = -fillRange;
        }
        fillRange = fillStart + fillRange;
        fillStart = fillStart > 1 ? 1 : fillStart;
        fillStart = fillStart < 0 ? 0 : fillStart;
        fillRange = fillRange > 1 ? 1 : fillRange;
        fillRange = fillRange < 0 ? 0 : fillRange;
        fillRange -= fillStart;
        var fillType = sprite._fillType;
        var vertices = sprite._vertices, corner = sprite._corner, wt = sprite._renderCmd._worldTransform, uvs = sprite._uvs;
        var fillEnd;
        var l = 0, b = 0, r = contentSize.width, t = contentSize.height;
        var atlasWidth = spriteFrame._texture.width;
        var atlasHeight = spriteFrame._texture.height;
        var textureRect = spriteFrame._rect;
        var ul, vb, ur, vt;
        var texelCorrect = macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL ? .5 : 0;
        if (spriteFrame._rotated) {
          ul = (textureRect.x + texelCorrect) / atlasWidth;
          vb = (textureRect.y + textureRect.width - texelCorrect) / atlasHeight;
          ur = (textureRect.x + textureRect.height - texelCorrect) / atlasWidth;
          vt = (textureRect.y + texelCorrect) / atlasHeight;
        } else {
          ul = (textureRect.x + texelCorrect) / atlasWidth;
          vb = (textureRect.y + textureRect.height - texelCorrect) / atlasHeight;
          ur = (textureRect.x + textureRect.width - texelCorrect) / atlasWidth;
          vt = (textureRect.y + texelCorrect) / atlasHeight;
        }
        if (vertices.length < 8) {
          dataPool.put(vertices);
          vertices = dataPool.get(8) || new Float32Array(8);
          sprite._vertices = vertices;
        }
        if (uvs.length < 8) {
          dataPool.put(uvs);
          uvs = dataPool.get(8) || new Float32Array(8);
          sprite._uvs = uvs;
        }
        var quadUV = new Array(8);
        if (spriteFrame._rotated) {
          quadUV[0] = quadUV[2] = ul;
          quadUV[4] = quadUV[6] = ur;
          quadUV[3] = quadUV[7] = vb;
          quadUV[1] = quadUV[5] = vt;
        } else {
          quadUV[0] = quadUV[4] = ul;
          quadUV[2] = quadUV[6] = ur;
          quadUV[1] = quadUV[3] = vb;
          quadUV[5] = quadUV[7] = vt;
        }
        fillStart = fillStart > 1 ? 1 : fillStart;
        fillStart = fillStart < 0 ? 0 : fillStart;
        fillRange = fillRange < 0 ? 0 : fillRange;
        fillEnd = fillStart + fillRange;
        fillEnd = fillEnd > 1 ? 1 : fillEnd;
        var progressStart, progressEnd;
        switch (fillType) {
         case FillType.HORIZONTAL:
          progressStart = l + (r - l) * fillStart;
          progressEnd = l + (r - l) * fillEnd;
          l = progressStart;
          r = progressEnd;
          uvs[0] = quadUV[0] + (quadUV[2] - quadUV[0]) * fillStart;
          uvs[1] = quadUV[1];
          uvs[2] = quadUV[0] + (quadUV[2] - quadUV[0]) * fillEnd;
          uvs[3] = quadUV[3];
          uvs[4] = quadUV[4] + (quadUV[6] - quadUV[4]) * fillStart;
          uvs[5] = quadUV[5];
          uvs[6] = quadUV[4] + (quadUV[6] - quadUV[4]) * fillEnd;
          uvs[7] = quadUV[7];
          break;

         case FillType.VERTICAL:
          progressStart = b + (t - b) * fillStart;
          progressEnd = b + (t - b) * fillEnd;
          b = progressStart;
          t = progressEnd;
          uvs[0] = quadUV[0];
          uvs[1] = quadUV[1] + (quadUV[5] - quadUV[1]) * fillStart;
          uvs[2] = quadUV[2];
          uvs[3] = quadUV[3] + (quadUV[7] - quadUV[3]) * fillStart;
          uvs[4] = quadUV[4];
          uvs[5] = quadUV[1] + (quadUV[5] - quadUV[1]) * fillEnd;
          uvs[6] = quadUV[6];
          uvs[7] = quadUV[3] + (quadUV[7] - quadUV[3]) * fillEnd;
          break;

         default:
          cc.errorID(2626);
        }
        if (webgl) {
          var la = l * wt.a, lb = l * wt.b, ra = r * wt.a, rb = r * wt.b, tcx = t * wt.c + wt.tx, tdy = t * wt.d + wt.ty, bcx = b * wt.c + wt.tx, bdy = b * wt.d + wt.ty;
          vertices[0] = la + bcx;
          vertices[1] = lb + bdy;
          vertices[2] = ra + bcx;
          vertices[3] = rb + bdy;
          vertices[4] = la + tcx;
          vertices[5] = lb + tdy;
          vertices[6] = ra + tcx;
          vertices[7] = rb + tdy;
        } else {
          vertices[0] = l;
          vertices[1] = b;
          vertices[2] = r;
          vertices[3] = b;
          vertices[4] = l;
          vertices[5] = t;
          vertices[6] = r;
          vertices[7] = t;
        }
        sprite._vertCount = 4;
        corner[0] = 0;
        corner[1] = 2;
        corner[2] = 4;
        corner[3] = 6;
      }
    };
    var fillQuadGeneratorRadial = {
      _vertPos: [ cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0) ],
      _vertices: [ cc.v2(0, 0), cc.v2(0, 0) ],
      _uvs: [ cc.v2(0, 0), cc.v2(0, 0) ],
      _intersectPoint_1: [ cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0) ],
      _intersectPoint_2: [ cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0) ],
      outVerts: null,
      outUvs: null,
      rawVerts: null,
      rawUvs: null,
      _rebuildQuads_base: function(sprite) {
        var spriteFrame = sprite._spriteFrame, contentSize = sprite._contentSize;
        var fillStart = sprite._fillStart;
        var fillRange = sprite._fillRange;
        if (fillRange < 0) {
          fillStart += fillRange;
          fillRange = -fillRange;
        }
        sprite._isTriangle = true;
        if (!sprite._rawVerts) {
          sprite._rawVerts = dataPool.get(8) || new Float32Array(8);
          sprite._rawUvs = dataPool.get(8) || new Float32Array(8);
        }
        var fillCenter = sprite._fillCenter;
        var vertices = sprite._vertices, corner = sprite._corner, uvs = sprite._uvs, rawVerts = sprite._rawVerts, rawUvs = sprite._rawUvs, wt = sprite._renderCmd._worldTransform;
        while (fillStart >= 1) fillStart -= 1;
        while (fillStart < 0) fillStart += 1;
        var cx = fillCenter.x * contentSize.width, cy = fillCenter.y * contentSize.height;
        var center = cc.v2(cx, cy);
        fillStart *= 2 * Math.PI;
        fillRange *= 2 * Math.PI;
        var fillEnd = fillStart + fillRange;
        this.outVerts = vertices;
        this.outUvs = uvs;
        this.rawVerts = rawVerts;
        this.rawUvs = rawUvs;
        this._calculateVertices(wt, spriteFrame, contentSize);
        this._calculateUVs(spriteFrame);
        var _vertPos = this._vertPos, _vertices = this._vertices;
        _vertPos[0].x = _vertPos[3].x = _vertices[0].x;
        _vertPos[1].x = _vertPos[2].x = _vertices[1].x;
        _vertPos[0].y = _vertPos[1].y = _vertices[0].y;
        _vertPos[2].y = _vertPos[3].y = _vertices[1].y;
        center.x > _vertices[1].x && (center.x = _vertices[1].x);
        center.x < _vertices[0].x && (center.x = _vertices[0].x);
        center.y < _vertices[0].y && (center.y = _vertices[0].y);
        center.y > _vertices[1].y && (center.y = _vertices[1].y);
        rawVerts[0] = rawVerts[4] = this._vertices[0].x;
        rawVerts[2] = rawVerts[6] = this._vertices[1].x;
        rawVerts[1] = rawVerts[3] = this._vertices[0].y;
        rawVerts[5] = rawVerts[7] = this._vertices[1].y;
        if (spriteFrame._rotated) {
          rawUvs[0] = rawUvs[2] = this._uvs[0].x;
          rawUvs[4] = rawUvs[6] = this._uvs[1].x;
          rawUvs[3] = rawUvs[7] = this._uvs[0].y;
          rawUvs[1] = rawUvs[5] = this._uvs[1].y;
        } else {
          rawUvs[0] = rawUvs[4] = this._uvs[0].x;
          rawUvs[2] = rawUvs[6] = this._uvs[1].x;
          rawUvs[1] = rawUvs[3] = this._uvs[0].y;
          rawUvs[5] = rawUvs[7] = this._uvs[1].y;
        }
        var triangles = [ null, null, null, null ];
        center.x !== this._vertices[0].x && (triangles[0] = [ 3, 0 ]);
        center.x !== this._vertices[1].x && (triangles[2] = [ 1, 2 ]);
        center.y !== this._vertices[0].y && (triangles[1] = [ 0, 1 ]);
        center.y !== this._vertices[1].y && (triangles[3] = [ 2, 3 ]);
        this._getInsectedPoints(this._vertices[0].x, this._vertices[1].x, this._vertices[0].y, this._vertices[1].y, center, fillStart, this._intersectPoint_1);
        this._getInsectedPoints(this._vertices[0].x, this._vertices[1].x, this._vertices[0].y, this._vertices[1].y, center, fillStart + fillRange, this._intersectPoint_2);
        var dataLength = 30;
        if (vertices.length < dataLength) {
          dataPool.put(vertices);
          vertices = dataPool.get(dataLength) || new Float32Array(dataLength);
          this.outVerts = sprite._vertices = vertices;
        }
        if (uvs.length < dataLength) {
          dataPool.put(uvs);
          uvs = dataPool.get(dataLength) || new Float32Array(dataLength);
          this.outUvs = sprite._uvs = uvs;
        }
        var offset = 0, count = 0;
        for (var triangleIndex = 0; triangleIndex < 4; ++triangleIndex) {
          var triangle = triangles[triangleIndex];
          if (null === triangle) continue;
          if (fillRange >= 2 * Math.PI) {
            this._generateTriangle(wt, offset, center, this._vertPos[triangle[0]], this._vertPos[triangle[1]]);
            offset += 6;
            count += 3;
            continue;
          }
          var startAngle = this._getVertAngle(center, this._vertPos[triangle[0]]);
          var endAngle = this._getVertAngle(center, this._vertPos[triangle[1]]);
          endAngle < startAngle && (endAngle += 2 * Math.PI);
          startAngle -= 2 * Math.PI;
          endAngle -= 2 * Math.PI;
          for (var testIndex = 0; testIndex < 3; ++testIndex) {
            if (startAngle >= fillEnd) ; else if (startAngle >= fillStart) {
              endAngle >= fillEnd ? this._generateTriangle(wt, offset, center, this._vertPos[triangle[0]], this._intersectPoint_2[triangleIndex]) : this._generateTriangle(wt, offset, center, this._vertPos[triangle[0]], this._vertPos[triangle[1]]);
              offset += 6;
              count += 3;
            } else if (endAngle <= fillStart) ; else if (endAngle <= fillEnd) {
              this._generateTriangle(wt, offset, center, this._intersectPoint_1[triangleIndex], this._vertPos[triangle[1]]);
              offset += 6;
              count += 3;
            } else {
              this._generateTriangle(wt, offset, center, this._intersectPoint_1[triangleIndex], this._intersectPoint_2[triangleIndex]);
              offset += 6;
              count += 3;
            }
            startAngle += 2 * Math.PI;
            endAngle += 2 * Math.PI;
          }
        }
        sprite._vertCount = count;
        var minx = Infinity, miny = Infinity, maxx = -Infinity, maxy = -Infinity;
        var x, y;
        for (var i = 0, l = offset; i < l; i += 2) {
          x = vertices[i];
          y = vertices[i + 1];
          if (x <= minx) {
            minx = x;
            corner[0] = i;
          } else if (x >= maxx) {
            maxx = x;
            corner[1] = i;
          }
          if (y <= miny) {
            miny = y;
            corner[2] = i;
          } else if (y >= maxy) {
            maxy = y;
            corner[3] = i;
          }
        }
      },
      _generateTriangle: function(wt, offset, vert0, vert1, vert2) {
        var rawVerts = this.rawVerts;
        var rawUvs = this.rawUvs;
        var vertices = this.outVerts;
        var v0x = rawVerts[0];
        var v0y = rawVerts[1];
        var v1x = rawVerts[6];
        var v1y = rawVerts[7];
        var progressX, progressY;
        if (webgl) {
          vertices[offset] = vert0.x * wt.a + vert0.y * wt.c + wt.tx;
          vertices[offset + 1] = vert0.x * wt.b + vert0.y * wt.d + wt.ty;
          vertices[offset + 2] = vert1.x * wt.a + vert1.y * wt.c + wt.tx;
          vertices[offset + 3] = vert1.x * wt.b + vert1.y * wt.d + wt.ty;
          vertices[offset + 4] = vert2.x * wt.a + vert2.y * wt.c + wt.tx;
          vertices[offset + 5] = vert2.x * wt.b + vert2.y * wt.d + wt.ty;
        } else {
          vertices[offset] = vert0.x;
          vertices[offset + 1] = vert0.y;
          vertices[offset + 2] = vert1.x;
          vertices[offset + 3] = vert1.y;
          vertices[offset + 4] = vert2.x;
          vertices[offset + 5] = vert2.y;
        }
        progressX = (vert0.x - v0x) / (v1x - v0x);
        progressY = (vert0.y - v0y) / (v1y - v0y);
        this._generateUV(progressX, progressY, rawUvs, offset);
        progressX = (vert1.x - v0x) / (v1x - v0x);
        progressY = (vert1.y - v0y) / (v1y - v0y);
        this._generateUV(progressX, progressY, rawUvs, offset + 2);
        progressX = (vert2.x - v0x) / (v1x - v0x);
        progressY = (vert2.y - v0y) / (v1y - v0y);
        this._generateUV(progressX, progressY, rawUvs, offset + 4);
      },
      _generateUV: function(progressX, progressY, uvs, offset) {
        var out = this.outUvs;
        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;
        out[offset] = px1 + (px2 - px1) * progressY;
        out[offset + 1] = py1 + (py2 - py1) * progressY;
      },
      _isAngleIn: function(angle, start, rangeAngle) {
        var pi_2 = 2 * Math.PI;
        while (angle < start || angle >= start + pi_2) {
          angle < start && (angle += pi_2);
          angle >= start + pi_2 && (angle -= pi_2);
        }
        return angle <= start + rangeAngle;
      },
      _getVertAngle: function(start, end) {
        var placementX, placementY;
        placementX = end.x - start.x;
        placementY = end.y - start.y;
        if (0 === placementX && 0 === placementY) return;
        if (0 === placementX) return placementY > 0 ? .5 * Math.PI : 1.5 * Math.PI;
        var angle = Math.atan(placementY / placementX);
        placementX < 0 && (angle += Math.PI);
        return angle;
      },
      _getInsectedPoints: function(left, right, bottom, top, center, angle, intersectPoints) {
        var result = [ null, null, null, null ];
        var sinAngle = Math.sin(angle);
        var cosAngle = Math.cos(angle);
        var tanAngle, cotAngle;
        if (0 !== Math.cos(angle)) {
          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 (0 !== Math.sin(angle)) {
          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;
          }
        }
        return result;
      },
      _calculateVertices: function(wt, spriteFrame, contentSize) {
        var x0, x3, y0, y3;
        x0 = 0;
        y0 = 0;
        x3 = contentSize.width;
        y3 = contentSize.height;
        this._vertices[0].x = x0;
        this._vertices[0].y = y0;
        this._vertices[1].x = x3;
        this._vertices[1].y = y3;
      },
      _calculateUVs: function(spriteFrame) {
        var atlasWidth = spriteFrame._texture.width;
        var atlasHeight = spriteFrame._texture.height;
        var textureRect = spriteFrame._rect;
        var u0, u3, v0, v3;
        var texelCorrect = macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL ? .5 : 0;
        if (spriteFrame._rotated) {
          u0 = (textureRect.x + texelCorrect) / atlasWidth;
          u3 = (textureRect.x + textureRect.height - texelCorrect) / atlasWidth;
          v0 = (textureRect.y + texelCorrect) / atlasHeight;
          v3 = (textureRect.y + textureRect.width - texelCorrect) / atlasHeight;
        } else {
          u0 = (textureRect.x + texelCorrect) / atlasWidth;
          u3 = (textureRect.x + textureRect.width - texelCorrect) / atlasWidth;
          v0 = (textureRect.y + texelCorrect) / atlasHeight;
          v3 = (textureRect.y + textureRect.height - texelCorrect) / atlasHeight;
        }
        this._uvs[0].x = u0;
        this._uvs[0].y = v3;
        this._uvs[1].x = u3;
        this._uvs[1].y = v0;
      }
    };
    var meshQuadGenerator = {
      _rebuildQuads_base: function(sprite, spriteFrame, polygonInfo) {
        if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) return;
        var spriteFrame = sprite._spriteFrame, polygonInfo = sprite._meshPolygonInfo;
        if (!polygonInfo) return;
        var wt = sprite._renderCmd._worldTransform;
        var srcVerts = polygonInfo.triangles.verts;
        var vertices = sprite._vertices;
        var uvs = sprite._uvs;
        var count = srcVerts.length;
        var corner = sprite._corner;
        var dataLength = 2 * count;
        if (vertices.length < dataLength) {
          dataPool.put(vertices);
          vertices = dataPool.get(dataLength) || new Float32Array(dataLength);
          sprite._vertices = vertices;
        }
        if (uvs.length < dataLength) {
          dataPool.put(uvs);
          uvs = dataPool.get(dataLength) || new Float32Array(dataLength);
          sprite._uvs = uvs;
        }
        var l = Infinity, b = Infinity, r = -Infinity, t = -Infinity;
        for (var i = 0; i < count; i++) {
          var x = srcVerts[i].x * wt.a + srcVerts[i].y * wt.c + wt.tx;
          var y = srcVerts[i].x * wt.b + srcVerts[i].y * wt.d + wt.ty;
          vertices[2 * i] = x;
          vertices[2 * i + 1] = y;
          uvs[2 * i] = srcVerts[i].u;
          uvs[2 * i + 1] = srcVerts[i].v;
          if (x < l) {
            l = x;
            corner[0] = 2 * i;
          }
          if (x > r) {
            r = x;
            corner[1] = 2 * i;
          }
          if (y < b) {
            b = y;
            corner[2] = 2 * i;
          }
          if (y > t) {
            t = y;
            corner[3] = 2 * i;
          }
        }
        sprite._vertCount = count;
      }
    };
    cc.Scale9Sprite = _ccsg.Node.extend({
      _spriteFrame: null,
      _insetLeft: 0,
      _insetRight: 0,
      _insetTop: 0,
      _insetBottom: 0,
      _blendFunc: null,
      _renderingType: 1,
      _brightState: 0,
      _rawVerts: null,
      _rawUvs: null,
      _vertices: null,
      _uvs: null,
      _vertCount: 0,
      _quadsDirty: true,
      _uvsDirty: true,
      _isTriangle: false,
      _isTrimmedContentSize: true,
      _fillType: 0,
      _fillCenter: null,
      _fillStart: 0,
      _fillRange: 2 * Math.PI,
      _distortionOffset: null,
      _distortionTiling: null,
      _meshPolygonInfo: null,
      ctor: function(textureOrSpriteFrame) {
        _ccsg.Node.prototype.ctor.call(this);
        this._renderCmd.setState(this._brightState);
        this._blendFunc = cc.BlendFunc._alphaNonPremultiplied();
        this._fillCenter = cc.v2(0, 0);
        this.setAnchorPoint(cc.p(.5, .5));
        this._rawVerts = null;
        this._rawUvs = null;
        this._vertices = dataPool.get(8) || new Float32Array(8);
        this._uvs = dataPool.get(8) || new Float32Array(8);
        "string" === typeof textureOrSpriteFrame || textureOrSpriteFrame instanceof cc.Texture2D ? this.initWithTexture(textureOrSpriteFrame) : textureOrSpriteFrame instanceof cc.SpriteFrame && this.initWithSpriteFrame(textureOrSpriteFrame);
        void 0 === webgl && (webgl = cc._renderType === cc.game.RENDER_TYPE_WEBGL);
        this._corner = [];
      },
      loaded: function() {
        return null !== this._spriteFrame && this._spriteFrame.textureLoaded();
      },
      initWithTexture: function(textureOrTextureFile) {
        this.setTexture(textureOrTextureFile);
      },
      initWithSpriteFrame: function(spriteFrameOrSFName) {
        this.setSpriteFrame(spriteFrameOrSFName);
      },
      setTexture: function(textureOrTextureFile) {
        var spriteFrame = new cc.SpriteFrame(textureOrTextureFile);
        this.setSpriteFrame(spriteFrame);
      },
      setSpriteFrame: function(spriteFrame) {
        if (spriteFrame) {
          this._spriteFrame = spriteFrame;
          this._quadsDirty = true;
          this._uvsDirty = true;
          this._renderCmd._needDraw = false;
          var self = this;
          var onResourceDataLoaded = function() {
            cc.sizeEqualToSize(self._contentSize, cc.size(0, 0)) && self.setContentSize(self._spriteFrame._rect);
            self._renderCmd._needDraw = true;
            self._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
          };
          spriteFrame.textureLoaded() ? onResourceDataLoaded() : spriteFrame.once("load", onResourceDataLoaded, this);
        }
      },
      setBlendFunc: function(blendFunc, dst) {
        if (void 0 === dst) {
          this._blendFunc.src = blendFunc.src || cc.macro.BLEND_SRC;
          this._blendFunc.dst = blendFunc.dst || cc.macro.BLEND_DST;
        } else {
          this._blendFunc.src = blendFunc || cc.macro.BLEND_SRC;
          this._blendFunc.dst = dst || cc.macro.BLEND_DST;
        }
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
      },
      getBlendFunc: function() {
        return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
      },
      setContentSize: function(width, height) {
        if (void 0 === height) {
          height = width.height;
          width = width.width;
        }
        if (width === this._contentSize.width && height === this._contentSize.height) return;
        _ccsg.Node.prototype.setContentSize.call(this, width, height);
        this._quadsDirty = true;
      },
      enableTrimmedContentSize: function(isTrimmed) {
        if (this._isTrimmedContentSize !== isTrimmed) {
          this._isTrimmedContentSize = isTrimmed;
          this._quadsDirty = true;
          this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
        }
      },
      isTrimmedContentSizeEnabled: function() {
        return this._isTrimmedContentSize;
      },
      setState: function(state) {
        this._brightState = state;
        this._renderCmd.setState(state);
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
      },
      getState: function() {
        return this._brightState;
      },
      setRenderingType: function(type) {
        if (this._renderingType === type) return;
        this._renderingType = type;
        this._quadsDirty = true;
        this._uvsDirty = true;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
      },
      getRenderingType: function() {
        return this._renderingType;
      },
      setInsetLeft: function(insetLeft) {
        this._insetLeft = insetLeft;
        this._quadsDirty = true;
        this._uvsDirty = true;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
      },
      getInsetLeft: function() {
        return this._insetLeft;
      },
      setInsetTop: function(insetTop) {
        this._insetTop = insetTop;
        this._quadsDirty = true;
        this._uvsDirty = true;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
      },
      getInsetTop: function() {
        return this._insetTop;
      },
      setInsetRight: function(insetRight) {
        this._insetRight = insetRight;
        this._quadsDirty = true;
        this._uvsDirty = true;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
      },
      getInsetRight: function() {
        return this._insetRight;
      },
      setInsetBottom: function(insetBottom) {
        this._insetBottom = insetBottom;
        this._quadsDirty = true;
        this._uvsDirty = true;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
      },
      getInsetBottom: function() {
        return this._insetBottom;
      },
      setFillType: function(value) {
        if (this._fillType === value) return;
        this._fillType = value;
        if (this._renderingType === RenderingType.FILLED) {
          this._quadsDirty = true;
          this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
        }
      },
      getFillType: function() {
        return this._fillType;
      },
      setFillCenter: function(value, y) {
        this._fillCenter = cc.v2(value, y);
        if (this._renderingType === RenderingType.FILLED && this._fillType === FillType.RADIAL) {
          this._quadsDirty = true;
          this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
        }
      },
      setDistortionTiling: function(valueOrX, y) {
        if (void 0 === y) {
          y = valueOrX.y;
          valueOrX = valueOrX.x;
        }
        this._distortionTiling = this._distortionTiling || cc.v2(0, 0);
        this._distortionTiling.x = valueOrX;
        this._distortionTiling.y = y;
      },
      setDistortionOffset: function(valueOrX, y) {
        if (void 0 === y) {
          y = valueOrX.y;
          valueOrX = valueOrX.x;
        }
        this._distortionOffset = this._distortionOffset || cc.v2(0, 0);
        this._distortionOffset.x = valueOrX;
        this._distortionOffset.y = y;
      },
      getFillCenter: function() {
        return cc.v2(this._fillCenter);
      },
      setFillStart: function(value) {
        if (this._fillStart === value) return;
        this._fillStart = value;
        if (this._renderingType === RenderingType.FILLED) {
          this._quadsDirty = true;
          this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
        }
      },
      getFillStart: function() {
        return this._fillStart;
      },
      setFillRange: function(value) {
        if (this._fillRange === value) return;
        this._fillRange = value;
        if (this._renderingType === RenderingType.FILLED) {
          this._quadsDirty = true;
          this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
        }
      },
      getFillRange: function() {
        return this._fillRange;
      },
      _rebuildQuads: function() {
        if (!this._spriteFrame || !this._spriteFrame._textureLoaded) {
          this._renderCmd._needDraw = false;
          return;
        }
        this._isTriangle = false;
        var quadGenerator;
        switch (this._renderingType) {
         case RenderingType.SIMPLE:
          quadGenerator = simpleQuadGenerator;
          break;

         case RenderingType.SLICED:
          quadGenerator = scale9QuadGenerator;
          break;

         case RenderingType.TILED:
          quadGenerator = tiledQuadGenerator;
          break;

         case RenderingType.FILLED:
          quadGenerator = this._fillType === FillType.RADIAL ? fillQuadGeneratorRadial : fillQuadGeneratorBar;
          break;

         case RenderingType.MESH:
          quadGenerator = meshQuadGenerator;
        }
        if (quadGenerator) quadGenerator._rebuildQuads_base(this); else {
          this._quadsDirty = false;
          this._uvsDirty = false;
          this._renderCmd._needDraw = false;
          cc.errorID(2627);
        }
        this._quadsDirty = false;
        this._uvsDirty = false;
      },
      _createRenderCmd: function() {
        return cc._renderType === cc.game.RENDER_TYPE_CANVAS ? new cc.Scale9Sprite.CanvasRenderCmd(this) : new cc.Scale9Sprite.WebGLRenderCmd(this);
      },
      setMeshPolygonInfo: function(polygonInfo) {
        this.setRenderingType(RenderingType.MESH);
        this._meshPolygonInfo = polygonInfo;
        this._quadsDirty = true;
        this._uvsDirty = true;
      },
      getMeshPolygonInfo: function() {
        return this._meshPolygonInfo;
      }
    });
    var _p = cc.Scale9Sprite.prototype;
    cc.js.addon(_p, EventTarget.prototype);
    cc.defineGetterSetter(_p, "insetLeft", _p.getInsetLeft, _p.setInsetLeft);
    cc.defineGetterSetter(_p, "insetTop", _p.getInsetTop, _p.setInsetTop);
    cc.defineGetterSetter(_p, "insetRight", _p.getInsetRight, _p.setInsetRight);
    cc.defineGetterSetter(_p, "insetBottom", _p.getInsetBottom, _p.setInsetBottom);
    cc.Scale9Sprite.state = {
      NORMAL: 0,
      GRAY: 1,
      DISTORTION: 2
    };
    var RenderingType = cc.Scale9Sprite.RenderingType = cc.Enum({
      SIMPLE: 0,
      SLICED: 1,
      TILED: 2,
      FILLED: 3,
      MESH: 4
    });
    var FillType = cc.Scale9Sprite.FillType = cc.Enum({
      HORIZONTAL: 0,
      VERTICAL: 1,
      RADIAL: 2
    });
  }), {
    "../event/event-target": 112
  } ],
  211: [ (function(require, module, exports) {
    cc.Scale9Sprite.CanvasRenderCmd = function(renderable) {
      this._rootCtor(renderable);
      this._node.loaded() ? this._needDraw = true : this._needDraw = false;
      this._state = cc.Scale9Sprite.state.NORMAL;
      this._originalTexture = this._textureToRender = null;
    };
    var proto = cc.Scale9Sprite.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
    proto.constructor = cc.Scale9Sprite.CanvasRenderCmd;
    proto.updateTransform = function(parentCmd) {
      this.originUpdateTransform(parentCmd);
      this._node._rebuildQuads();
    };
    proto._doCulling = function() {
      var rect = cc.visibleRect, bb = this._currentRegion, l = bb._minX, r = bb._maxX, b = bb._minY, t = bb._maxY, vl = rect.left.x, vr = rect.right.x, vt = rect.top.y, vb = rect.bottom.y;
      this._needDraw = !(r < vl || l > vr || t < vb || b > vt);
    };
    proto._updateDisplayColor = function(parentColor) {
      _ccsg.Node.WebGLRenderCmd.prototype._updateDisplayColor.call(this, parentColor);
      this._originalTexture = this._textureToRender = null;
    };
    proto._syncDisplayColor = function(parentColor) {
      _ccsg.Node.WebGLRenderCmd.prototype._syncDisplayColor.call(this, parentColor);
      this._originalTexture = this._textureToRender = null;
    };
    proto.setState = function(state) {
      if (this._state === state) return;
      this._state = state;
      this._originalTexture = this._textureToRender = null;
    };
    proto.rendering = function(ctx, scaleX, scaleY) {
      var node = this._node;
      var locDisplayOpacity = this._displayedOpacity;
      var alpha = locDisplayOpacity / 255;
      var locTexture = null;
      node._spriteFrame && (locTexture = node._spriteFrame._texture);
      if (!node.loaded() || 0 === locDisplayOpacity) return;
      if (null === this._textureToRender || this._originalTexture !== locTexture) {
        this._textureToRender = this._originalTexture = locTexture;
        cc.Scale9Sprite.state.GRAY === this._state && (this._textureToRender = this._textureToRender._generateGrayTexture());
        var color = node.getDisplayedColor();
        !locTexture || 255 === color.r && 255 === color.g && 255 === color.b || (this._textureToRender = this._textureToRender._generateColorTexture(color.r, color.g, color.b));
      }
      var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
      wrapper.setTransform(this._worldTransform, scaleX, scaleY);
      wrapper.setCompositeOperation(_ccsg.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc(node._blendFunc));
      wrapper.setGlobalAlpha(alpha);
      if (this._textureToRender) {
        node._quadsDirty && node._rebuildQuads();
        var sx, sy, sw, sh;
        var x, y, w, h;
        var textureWidth = this._textureToRender.width;
        var textureHeight = this._textureToRender.height;
        var image = this._textureToRender._image;
        var vertices = node._vertices;
        var uvs = node._uvs;
        var i = 0, off = 0;
        if (node._isTriangle) {
          var rawVerts = node._rawVerts, rawUvs = node._rawUvs;
          x = rawVerts[0];
          y = rawVerts[1];
          w = rawVerts[6] - x;
          h = rawVerts[7] - y;
          y = -y - h;
          sx = rawUvs[4] * textureWidth;
          sy = rawUvs[5] * textureHeight;
          sw = (rawUvs[6] - rawUvs[0]) * textureWidth;
          sh = (rawUvs[1] - rawUvs[7]) * textureHeight;
          wrapper.save();
          context.beginPath();
          var triangleCount = Math.floor(node._vertCount / 3);
          for (i = 0, off = 0; i < triangleCount; i++) {
            context.moveTo(vertices[off++], -vertices[off++]);
            context.lineTo(vertices[off++], -vertices[off++]);
            context.lineTo(vertices[off++], -vertices[off++]);
          }
          context.clip();
          if ("" !== this._textureToRender._pattern) {
            wrapper.setFillStyle(context.createPattern(image, this._textureToRender._pattern));
            context.fillRect(x, y, w, h);
          } else sw > 0 && sh > 0 && w > 0 && h > 0 && context.drawImage(image, sx, sy, sw, sh, x, y, w, h);
          wrapper.restore();
          cc.g_NumberOfDraws += triangleCount;
        } else if (node._renderingType === cc.Scale9Sprite.RenderingType.SLICED) {
          for (var r = 0; r < 3; ++r) for (var c = 0; c < 3; ++c) {
            off = 8 * r + 2 * c;
            x = vertices[off];
            y = vertices[off + 1];
            w = vertices[off + 10] - x;
            h = vertices[off + 11] - y;
            y = -y - h;
            sx = uvs[off] * textureWidth;
            sy = uvs[off + 11] * textureHeight;
            sw = (uvs[off + 10] - uvs[off]) * textureWidth;
            sh = (uvs[off + 1] - uvs[off + 11]) * textureHeight;
            sw > 0 && sh > 0 && w > 0 && h > 0 && context.drawImage(image, sx, sy, sw, sh, x, y, w, h);
          }
          cc.g_NumberOfDraws += 9;
        } else {
          var quadCount = Math.floor(node._vertCount / 4);
          for (i = 0, off = 0; i < quadCount; i++) {
            x = vertices[off];
            y = vertices[off + 1];
            w = vertices[off + 6] - x;
            h = vertices[off + 7] - y;
            y = -y - h;
            sx = uvs[off] * textureWidth;
            sy = uvs[off + 7] * textureHeight;
            sw = (uvs[off + 6] - uvs[off]) * textureWidth;
            sh = (uvs[off + 1] - uvs[off + 7]) * textureHeight;
            if ("" !== this._textureToRender._pattern) {
              wrapper.setFillStyle(context.createPattern(image, this._textureToRender._pattern));
              context.fillRect(x, y, w, h);
            } else sw > 0 && sh > 0 && w > 0 && h > 0 && context.drawImage(image, sx, sy, sw, sh, x, y, w, h);
            off += 8;
          }
          cc.g_NumberOfDraws += quadCount;
        }
      }
    };
  }), {} ],
  212: [ (function(require, module, exports) {
    var ccgl = cc.gl;
    cc.Scale9Sprite.WebGLRenderCmd = function(renderable) {
      this._rootCtor(renderable);
      this._node.loaded() ? this._needDraw = true : this._needDraw = false;
      this.vertexType = cc.renderer.VertexType.QUAD;
      this._dirty = false;
      this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLOR);
    };
    var Scale9Sprite = cc.Scale9Sprite;
    var proto = Scale9Sprite.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype);
    proto.constructor = Scale9Sprite.WebGLRenderCmd;
    proto._uploadSliced = function(vertices, uvs, color, z, f32buffer, ui32buffer, offset) {
      var off;
      for (var r = 0; r < 3; ++r) for (var c = 0; c < 3; ++c) {
        off = 8 * r + 2 * c;
        f32buffer[offset] = vertices[off];
        f32buffer[offset + 1] = vertices[off + 1];
        f32buffer[offset + 2] = z;
        ui32buffer[offset + 3] = color;
        f32buffer[offset + 4] = uvs[off];
        f32buffer[offset + 5] = uvs[off + 1];
        offset += 6;
        f32buffer[offset] = vertices[off + 2];
        f32buffer[offset + 1] = vertices[off + 3];
        f32buffer[offset + 2] = z;
        ui32buffer[offset + 3] = color;
        f32buffer[offset + 4] = uvs[off + 2];
        f32buffer[offset + 5] = uvs[off + 3];
        offset += 6;
        f32buffer[offset] = vertices[off + 8];
        f32buffer[offset + 1] = vertices[off + 9];
        f32buffer[offset + 2] = z;
        ui32buffer[offset + 3] = color;
        f32buffer[offset + 4] = uvs[off + 8];
        f32buffer[offset + 5] = uvs[off + 9];
        offset += 6;
        f32buffer[offset] = vertices[off + 10];
        f32buffer[offset + 1] = vertices[off + 11];
        f32buffer[offset + 2] = z;
        ui32buffer[offset + 3] = color;
        f32buffer[offset + 4] = uvs[off + 10];
        f32buffer[offset + 5] = uvs[off + 11];
        offset += 6;
      }
      return 36;
    };
    proto.updateTransform = function(parentCmd) {
      this.originUpdateTransform(parentCmd);
      this._node._rebuildQuads();
    };
    proto._doCulling = function() {
      var node = this._node;
      var rect = cc.visibleRect;
      this._cameraFlag > 0 && (rect = cc.Camera.main.visibleRect);
      var vl = rect.left.x;
      var vr = rect.right.x;
      var vt = rect.top.y;
      var vb = rect.bottom.y;
      var vert = node._vertices, corner = node._corner, c0 = corner[0], c1 = corner[1], c2 = corner[2], c3 = corner[3], x0 = vert[c0], x1 = vert[c1], x2 = vert[c2], x3 = vert[c3], y0 = vert[c0 + 1], y1 = vert[c1 + 1], y2 = vert[c2 + 1], y3 = vert[c3 + 1];
      this._needDraw = !((x0 - vl & x1 - vl & x2 - vl & x3 - vl) >> 31 || (vr - x0 & vr - x1 & vr - x2 & vr - x3) >> 31 || (y0 - vb & y1 - vb & y2 - vb & y3 - vb) >> 31 || (vt - y0 & vt - y1 & vt - y2 & vt - y3) >> 31);
    };
    proto.uploadData = function(f32buffer, ui32buffer, vertexDataOffset) {
      var node = this._node;
      if (0 === this._displayedOpacity) return 0;
      node._quadsDirty && node._rebuildQuads();
      if (node._distortionOffset && this._shaderProgram === Scale9Sprite.WebGLRenderCmd._distortionProgram) {
        this._shaderProgram.use();
        this._shaderProgram.setUniformLocationWith2f(Scale9Sprite.WebGLRenderCmd._distortionOffset, node._distortionOffset.x, node._distortionOffset.y);
        this._shaderProgram.setUniformLocationWith2f(Scale9Sprite.WebGLRenderCmd._distortionTiling, node._distortionTiling.x, node._distortionTiling.y);
        cc.renderer._breakBatch();
      }
      var opacity = this._displayedOpacity;
      var color, colorVal = this._displayedColor._val;
      if (node._opacityModifyRGB) {
        var a = opacity / 255, r = this._displayedColor.r * a, g = this._displayedColor.g * a, b = this._displayedColor.b * a;
        color = (opacity << 24 >>> 0) + (b << 16) + (g << 8) + r;
      } else color = (opacity << 24 >>> 0) + ((65280 & colorVal) << 8) + ((16711680 & colorVal) >> 8) + (colorVal >>> 24);
      var z = node._vertexZ;
      var vertices = node._vertices;
      var uvs = node._uvs;
      var types = Scale9Sprite.RenderingType;
      var offset = vertexDataOffset;
      var len = 0;
      switch (node._renderingType) {
       case types.SIMPLE:
       case types.TILED:
       case types.FILLED:
       case types.MESH:
        len = this._node._vertCount;
        for (var i = 0, srcOff = 0; i < len; i++, srcOff += 2) {
          f32buffer[offset] = vertices[srcOff];
          f32buffer[offset + 1] = vertices[srcOff + 1];
          f32buffer[offset + 2] = z;
          ui32buffer[offset + 3] = color;
          f32buffer[offset + 4] = uvs[srcOff];
          f32buffer[offset + 5] = uvs[srcOff + 1];
          offset += 6;
        }
        break;

       case types.SLICED:
        len = this._uploadSliced(vertices, uvs, color, z, f32buffer, ui32buffer, offset);
      }
      node._renderingType === types.MESH ? this.vertexType = cc.renderer.VertexType.CUSTOM : node._renderingType === types.FILLED && node._fillType === Scale9Sprite.FillType.RADIAL ? this.vertexType = cc.renderer.VertexType.TRIANGLE : this.vertexType = cc.renderer.VertexType.QUAD;
      return len;
    };
    proto.uploadIndexData = function(indexData, indexSize, batchingSize) {
      var polygonInfo = this._node._meshPolygonInfo;
      if (!polygonInfo) return 0;
      var indices = polygonInfo.triangles.indices;
      var len = indices.length;
      for (var i = 0; i < len; i++) indexData[indexSize + i] = batchingSize + indices[i];
      return len;
    };
    proto.setState = function(state) {
      state === Scale9Sprite.state.NORMAL ? this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLOR) : state === Scale9Sprite.state.GRAY ? this._shaderProgram = cc.Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram() : state === Scale9Sprite.state.DISTORTION && (this._shaderProgram = cc.Scale9Sprite.WebGLRenderCmd._getDistortionProgram());
    };
    Scale9Sprite.WebGLRenderCmd._grayShaderProgram = null;
    Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram = function() {
      var grayShader = Scale9Sprite.WebGLRenderCmd._grayShaderProgram;
      if (grayShader) return grayShader;
      grayShader = new cc.GLProgram();
      grayShader.initWithVertexShaderByteArray(cc.PresetShaders.SPRITE_POSITION_TEXTURE_COLOR_VERT, cc.Scale9Sprite.WebGLRenderCmd._grayShaderFragment);
      grayShader.addAttribute(cc.macro.ATTRIBUTE_NAME_POSITION, cc.macro.VERTEX_ATTRIB_POSITION);
      grayShader.addAttribute(cc.macro.ATTRIBUTE_NAME_COLOR, cc.macro.VERTEX_ATTRIB_COLOR);
      grayShader.addAttribute(cc.macro.ATTRIBUTE_NAME_TEX_COORD, cc.macro.VERTEX_ATTRIB_TEX_COORDS);
      grayShader.link();
      grayShader.updateUniforms();
      Scale9Sprite.WebGLRenderCmd._grayShaderProgram = grayShader;
      return grayShader;
    };
    Scale9Sprite.WebGLRenderCmd._grayShaderFragment = "precision lowp float;\nvarying vec4 v_fragmentColor;\nvarying vec2 v_texCoord;\nvoid main()\n{\nvec4 c = v_fragmentColor * texture2D(CC_Texture0, v_texCoord);\nfloat gray = 0.2126*c.r + 0.7152*c.g + 0.0722*c.b;\ngl_FragColor = vec4(gray, gray, gray, c.a);\n}";
    Scale9Sprite.WebGLRenderCmd._distortionProgram = null;
    Scale9Sprite.WebGLRenderCmd._getDistortionProgram = function() {
      var shader = Scale9Sprite.WebGLRenderCmd._distortionProgram;
      if (shader) return shader;
      shader = new cc.GLProgram();
      shader.initWithVertexShaderByteArray(cc.PresetShaders.SPRITE_POSITION_TEXTURE_COLOR_VERT, distortionSpriteShader.fShader);
      shader.addAttribute(cc.macro.ATTRIBUTE_NAME_POSITION, cc.macro.VERTEX_ATTRIB_POSITION);
      shader.addAttribute(cc.macro.ATTRIBUTE_NAME_COLOR, cc.macro.VERTEX_ATTRIB_COLOR);
      shader.addAttribute(cc.macro.ATTRIBUTE_NAME_TEX_COORD, cc.macro.VERTEX_ATTRIB_TEX_COORDS);
      shader.link();
      shader.updateUniforms();
      Scale9Sprite.WebGLRenderCmd._distortionProgram = shader;
      Scale9Sprite.WebGLRenderCmd._distortionOffset = shader.getUniformLocationForName("u_offset");
      Scale9Sprite.WebGLRenderCmd._distortionTiling = shader.getUniformLocationForName("u_offset_tiling");
      return shader;
    };
    var distortionSpriteShader = {
      shaderKey: "cc.Sprite.Shader.Distortion",
      fShader: "precision lowp float;\nvarying vec4 v_fragmentColor;\nvarying vec2 v_texCoord;\nuniform vec2 u_offset;\nuniform vec2 u_offset_tiling;\nconst float PI = 3.14159265359;\nvoid main()\n{\nfloat halfPI = 0.5 * PI;\nfloat maxFactor = sin(halfPI);\nvec2 uv = v_texCoord;\nvec2 xy = 2.0 * uv.xy - 1.0;\nfloat d = length(xy);\nif (d < (2.0-maxFactor)) {\nd = length(xy * maxFactor);\nfloat z = sqrt(1.0 - d * d);\nfloat r = atan(d, z) / PI;\nfloat phi = atan(xy.y, xy.x);\nuv.x = r * cos(phi) + 0.5;\nuv.y = r * sin(phi) + 0.5;\n} else {\ndiscard;\n}\nuv = uv * u_offset_tiling + u_offset;\nuv = fract(uv);\ngl_FragColor = v_fragmentColor * texture2D(CC_Texture0, uv);\n}"
    };
  }), {} ],
  213: [ (function(require, module, exports) {
    cc.SpriteBatchNode = _ccsg.Node.extend({
      _blendFunc: null,
      _texture: null,
      _className: "SpriteBatchNode",
      ctor: function(fileImage) {
        _ccsg.Node.prototype.ctor.call(this);
        this._blendFunc = new cc.BlendFunc(cc.macro.BLEND_SRC, cc.macro.BLEND_DST);
        var texture2D;
        if (cc.js.isString(fileImage)) {
          texture2D = cc.textureCache.getTextureForKey(fileImage);
          texture2D || (texture2D = cc.textureCache.addImage(fileImage));
        } else fileImage instanceof cc.Texture2D && (texture2D = fileImage);
        texture2D && this.initWithTexture(texture2D);
      },
      initWithFile: function(fileImage) {
        var texture2D = cc.textureCache.getTextureForKey(fileImage) || cc.textureCache.addImage(fileImage);
        return this.initWithTexture(texture2D);
      },
      removeChildAtIndex: function(index, doCleanup) {
        this.removeChild(this._children[index], doCleanup);
      },
      setBlendFunc: function(src, dst) {
        this._blendFunc = void 0 === dst ? src : {
          src: src,
          dst: dst
        };
      },
      getBlendFunc: function() {
        return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
      },
      updateQuadFromSprite: function(sprite, index) {
        cc.assertID(sprite, 2623);
        if (!(sprite instanceof _ccsg.Sprite)) {
          cc.log(2616);
          return;
        }
        sprite.dirty = true;
        sprite._renderCmd.transform(this._renderCmd, true);
      },
      appendChild: function(sprite) {
        this.sortAllChildren();
        var lastLocalZOrder = this._children[this._children.length - 1]._localZOrder;
        this.addChild(sprite.lastLocalZOrder + 1);
      },
      initWithTexture: function(tex) {
        this.setTexture(tex);
        return true;
      },
      getTexture: function() {
        return this._texture;
      },
      setTexture: function(texture) {
        this._texture = texture;
        if (texture.loaded) {
          var children = this._children, i, len = children.length;
          for (i = 0; i < len; ++i) children[i].setTexture(texture);
        } else texture.addEventListener("load", (function() {
          var children = this._children, i, len = children.length;
          for (i = 0; i < len; ++i) children[i].setTexture(texture);
        }), this);
      },
      setShaderProgram: function(newShaderProgram) {
        this._renderCmd.setShaderProgram(newShaderProgram);
        var children = this._children, i, len = children.length;
        for (i = 0; i < len; ++i) children[i].setShaderProgram(newShaderProgram);
      },
      addChild: function(child, zOrder, tag) {
        cc.assertID(void 0 !== child, 2614);
        if (!this._isValidChild(child)) return;
        zOrder = void 0 === zOrder ? child.zIndex : zOrder;
        tag = void 0 === tag ? child.tag : tag;
        _ccsg.Node.prototype.addChild.call(this, child, zOrder, tag);
        this._renderCmd._shaderProgram && (child.shaderProgram = this._renderCmd._shaderProgram);
      },
      _isValidChild: function(child) {
        if (!(child instanceof _ccsg.Sprite)) {
          cc.logID(2618);
          return false;
        }
        if (child.texture !== this._texture) {
          cc.logID(2619);
          return false;
        }
        return true;
      }
    });
    var _p = cc.SpriteBatchNode.prototype;
    cc.defineGetterSetter(_p, "texture", _p.getTexture, _p.setTexture);
    cc.defineGetterSetter(_p, "shaderProgram", _p.getShaderProgram, _p.setShaderProgram);
  }), {} ],
  214: [ (function(require, module, exports) {
    var EventTarget = require("../event/event-target");
    cc.SpriteFrame = cc.Class({
      name: "cc.SpriteFrame",
      extends: require("../assets/CCAsset"),
      mixins: [ EventTarget ],
      properties: {
        _textureFilenameSetter: {
          set: function(url) {
            this._textureFilename = url;
            if (url) {
              false;
              this._loadTexture();
            }
          }
        }
      },
      ctor: function() {
        var filename = arguments[0];
        var rect = arguments[1];
        var rotated = arguments[2];
        var offset = arguments[3];
        var originalSize = arguments[4];
        this._rect = null;
        this._offset = null;
        this._originalSize = null;
        this._rotated = false;
        this.insetTop = 0;
        this.insetBottom = 0;
        this.insetLeft = 0;
        this.insetRight = 0;
        this._texture = null;
        this._textureFilename = "";
        this._textureLoaded = false;
        false;
        void 0 !== filename && this.initWithTexture(filename, rect, rotated, offset, originalSize);
      },
      textureLoaded: function() {
        return this._textureLoaded;
      },
      addLoadedEventListener: function(callback, target) {
        this.once("load", callback, target);
      },
      isRotated: function() {
        return this._rotated;
      },
      setRotated: function(bRotated) {
        this._rotated = bRotated;
      },
      getRect: function() {
        return cc.rect(this._rect);
      },
      setRect: function(rect) {
        this._rect = rect;
      },
      getOriginalSize: function() {
        return cc.size(this._originalSize);
      },
      setOriginalSize: function(size) {
        if (this._originalSize) {
          this._originalSize.width = size.width;
          this._originalSize.height = size.height;
        } else this._originalSize = cc.size(size);
      },
      getTexture: function() {
        return this._texture;
      },
      _refreshTexture: function(texture) {
        var self = this;
        if (self._texture !== texture) {
          var locLoaded = texture.loaded;
          this._textureLoaded = locLoaded;
          this._texture = texture;
          function textureLoadedCallback() {
            if (!self._texture) return;
            self._textureLoaded = true;
            var w = texture.width, h = texture.height;
            if (self._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
              var tempElement = texture.getHtmlElementObj();
              tempElement = _ccsg.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, self.getRect());
              var tempTexture = new cc.Texture2D();
              tempTexture.initWithElement(tempElement);
              tempTexture.handleLoadedTexture();
              self._texture = tempTexture;
              self._rotated = false;
              w = self._texture.width;
              h = self._texture.height;
              self.setRect(cc.rect(0, 0, w, h));
            }
            self._rect ? self._checkRect(self._texture) : self.setRect(cc.rect(0, 0, w, h));
            self._originalSize || self.setOriginalSize(cc.size(w, h));
            self._offset || self.setOffset(cc.v2(0, 0));
            self.emit("load");
          }
          locLoaded ? textureLoadedCallback() : texture.once("load", textureLoadedCallback);
        }
      },
      getOffset: function() {
        return cc.v2(this._offset);
      },
      setOffset: function(offsets) {
        this._offset = cc.v2(offsets);
      },
      clone: function() {
        return new cc.SpriteFrame(this._texture || this._textureFilename, this._rect, this._rotated, this._offset, this._originalSize);
      },
      setTexture: function(textureOrTextureFile, rect, rotated, offset, originalSize) {
        rect ? this.setRect(rect) : this._rect = null;
        offset ? this.setOffset(offset) : this._offset = null;
        originalSize ? this.setOriginalSize(originalSize) : this._originalSize = null;
        this._rotated = rotated || false;
        var texture = textureOrTextureFile;
        if (cc.js.isString(texture)) {
          this._textureFilename = texture;
          this._loadTexture();
        } else texture instanceof cc.Texture2D && this._refreshTexture(texture);
        return true;
      },
      _loadTexture: function() {
        if (this._textureFilename) {
          var texture = cc.textureCache.addImage(this._textureFilename);
          this._refreshTexture(texture);
        }
      },
      ensureLoadTexture: function() {
        this._texture || this._loadTexture();
      },
      clearTexture: function() {
        this._textureLoaded = false;
        this._texture = null;
      },
      _checkRect: function(texture) {
        var rect = this._rect;
        var maxX = rect.x, maxY = rect.y;
        if (this._rotated) {
          maxX += rect.height;
          maxY += rect.width;
        } else {
          maxX += rect.width;
          maxY += rect.height;
        }
        maxX > texture.getPixelWidth() && cc.errorID(3300, texture.url + "/" + this.name);
        maxY > texture.getPixelHeight() && cc.errorID(3400, texture.url + "/" + this.name);
      },
      _serialize: false,
      _deserialize: function(data, handle) {
        var rect = data.rect;
        rect && this.setRect(new cc.Rect(rect[0], rect[1], rect[2], rect[3]));
        data.offset && this.setOffset(new cc.Vec2(data.offset[0], data.offset[1]));
        data.originalSize && this.setOriginalSize(new cc.Size(data.originalSize[0], data.originalSize[1]));
        this._rotated = 1 === data.rotated;
        this._name = data.name;
        var capInsets = data.capInsets;
        if (capInsets) {
          this.insetLeft = capInsets[0];
          this.insetTop = capInsets[1];
          this.insetRight = capInsets[2];
          this.insetBottom = capInsets[3];
        }
        false;
        var textureUuid = data.texture;
        if (textureUuid) {
          var dontLoadTexture = handle.customEnv && handle.customEnv.deferredLoadRaw;
          var receiver = dontLoadTexture ? "_textureFilename" : "_textureFilenameSetter";
          handle.result.push(this, receiver, textureUuid);
        }
      }
    });
    var proto = cc.SpriteFrame.prototype;
    proto.copyWithZone = proto.clone;
    proto.copy = proto.clone;
    proto.initWithTexture = proto.setTexture;
  }), {
    "../assets/CCAsset": 43,
    "../event/event-target": 112
  } ],
  215: [ (function(require, module, exports) {
    var EventTarget = require("../event/event-target");
    var sys = require("../platform/CCSys");
    var JS = require("../platform/js");
    var misc = require("../utils/misc");
    var game = require("../CCGame");
    require("../platform/_CCClass");
    require("../platform/CCClass");
    var GL_ALPHA = 6406;
    var GL_RGB = 6407;
    var GL_RGBA = 6408;
    var GL_LUMINANCE = 6409;
    var GL_LUMINANCE_ALPHA = 6410;
    var GL_UNSIGNED_BYTE = 5121;
    var GL_UNSIGNED_SHORT = 5123;
    var GL_UNSIGNED_INT = 5125;
    var GL_FLOAT = 5126;
    var GL_UNSIGNED_SHORT_5_6_5 = 33635;
    var GL_UNSIGNED_SHORT_4_4_4_4 = 32819;
    var GL_UNSIGNED_SHORT_5_5_5_1 = 32820;
    var GL_NEAREST = 9728;
    var GL_LINEAR = 9729;
    var GL_REPEAT = 10497;
    var GL_CLAMP_TO_EDGE = 33071;
    var GL_MIRRORED_REPEAT = 33648;
    var _textureFmtGL = [ {
      format: GL_RGB,
      internalFormat: GL_RGB,
      pixelType: GL_UNSIGNED_SHORT_5_6_5
    }, {
      format: GL_RGBA,
      internalFormat: GL_RGBA,
      pixelType: GL_UNSIGNED_SHORT_5_5_5_1
    }, {
      format: GL_RGBA,
      internalFormat: GL_RGBA,
      pixelType: GL_UNSIGNED_SHORT_4_4_4_4
    }, {
      format: GL_RGB,
      internalFormat: GL_RGB,
      pixelType: GL_UNSIGNED_BYTE
    }, {
      format: GL_RGBA,
      internalFormat: GL_RGBA,
      pixelType: GL_UNSIGNED_BYTE
    }, {
      format: GL_ALPHA,
      internalFormat: GL_ALPHA,
      pixelType: GL_UNSIGNED_BYTE
    }, {
      format: GL_LUMINANCE,
      internalFormat: GL_LUMINANCE,
      pixelType: GL_UNSIGNED_BYTE
    }, {
      format: GL_LUMINANCE_ALPHA,
      internalFormat: GL_LUMINANCE_ALPHA,
      pixelType: GL_UNSIGNED_BYTE
    } ];
    var PixelFormat = cc.Enum({
      RGB565: 0,
      RGB5A1: 1,
      RGBA4444: 2,
      RGB888: 3,
      RGBA8888: 4,
      A8: 5,
      I8: 6,
      AI8: 7
    });
    var WrapMode = cc.Enum({
      REPEAT: GL_REPEAT,
      CLAMP_TO_EDGE: GL_CLAMP_TO_EDGE,
      MIRRORED_REPEAT: GL_MIRRORED_REPEAT
    });
    var Filter = cc.Enum({
      LINEAR: GL_LINEAR,
      NEAREST: GL_NEAREST
    });
    var Texture2D = cc.Class({
      name: "cc.Texture2D",
      extends: require("../assets/CCRawAsset"),
      mixins: [ EventTarget ],
      properties: {
        _hasMipmap: false,
        _format: PixelFormat.RGBA8888,
        _compressed: false,
        _premultiplyAlpha: false,
        _minFilter: Filter.LINEAR,
        _magFilter: Filter.LINEAR,
        _wrapS: WrapMode.CLAMP_TO_EDGE,
        _wrapT: WrapMode.CLAMP_TO_EDGE
      },
      statics: {
        PixelFormat: PixelFormat,
        WrapMode: WrapMode,
        Filter: Filter
      },
      ctor: function(gl) {
        this.url = null;
        this.loaded = false;
        this.width = 0;
        this.height = 0;
        this._image = null;
        if (cc._renderType === game.RENDER_TYPE_CANVAS) {
          this._pattern = "";
          this._grayElementObj = null;
          this._backupElement = null;
          this._isGray = false;
        } else if (cc._renderType === game.RENDER_TYPE_WEBGL) {
          this._gl = gl || cc._renderContext;
          this._glID = null;
        }
      },
      update: function(options) {},
      getPixelWidth: function() {
        return this.width;
      },
      getPixelHeight: function() {
        return this.height;
      },
      getContentSize: function() {
        return cc.size(this.width, this.height);
      },
      getContentSizeInPixels: function() {
        return this.getContentSize();
      },
      initWithElement: function(element) {
        if (!element) return;
        this._image = element;
        this.width = element.width;
        this.height = element.height;
        this.loaded = true;
      },
      initWithData: function(data, pixelFormat, pixelsWidth, pixelsHeight, contentSize) {
        return false;
      },
      initWithImage: function(uiImage) {
        return false;
      },
      getHtmlElementObj: function() {
        return this._image;
      },
      isLoaded: function() {
        return this.loaded;
      },
      handleLoadedTexture: function() {
        if (!this._image || !this._image.width || !this._image.height) return;
        var locElement = this._image;
        this.width = locElement.width;
        this.height = locElement.height;
        this.loaded = true;
        this.emit("load");
      },
      description: function() {
        return "<cc.Texture2D | Name = " + this.url + " | Dimensions = " + this.width + " x " + this.height + ">";
      },
      releaseTexture: function() {
        this._gl && null !== this._glID && this._gl.deleteTexture(this._glID);
      },
      getPixelFormat: function() {
        return this._format;
      },
      hasPremultipliedAlpha: function() {
        return this._premultiplyAlpha || false;
      },
      hasMipmaps: function() {
        return this._hasMipmap || false;
      },
      setTexParameters: function(texParams, magFilter, wrapS, wrapT) {
        void 0 !== magFilter && (texParams = {
          minFilter: texParams,
          magFilter: magFilter,
          wrapS: wrapS,
          wrapT: wrapT
        });
        if (texParams.wrapS === WrapMode.REPEAT && texParams.wrapT === WrapMode.REPEAT) {
          this._pattern = "repeat";
          return;
        }
        if (texParams.wrapS === WrapMode.REPEAT) {
          this._pattern = "repeat-x";
          return;
        }
        if (texParams.wrapT === WrapMode.REPEAT) {
          this._pattern = "repeat-y";
          return;
        }
        this._pattern = "";
      },
      setAntiAliasTexParameters: function() {},
      setAliasTexParameters: function() {}
    });
    var _p = Texture2D.prototype;
    _p.pixelFormat;
    cc.defineGetterSetter(_p, "pixelFormat", _p.getPixelFormat);
    _p.pixelWidth;
    cc.defineGetterSetter(_p, "pixelWidth", _p.getPixelWidth);
    _p.pixelHeight;
    cc.defineGetterSetter(_p, "pixelHeight", _p.getPixelHeight);
    game.once(game.EVENT_RENDERER_INITED, (function() {
      if (cc._renderType === game.RENDER_TYPE_CANVAS) {
        var renderToCache = function(image, cache) {
          var w = image.width;
          var h = image.height;
          cache[0].width = w;
          cache[0].height = h;
          cache[1].width = w;
          cache[1].height = h;
          cache[2].width = w;
          cache[2].height = h;
          cache[3].width = w;
          cache[3].height = h;
          var cacheCtx = cache[3].getContext("2d");
          cacheCtx.drawImage(image, 0, 0);
          var pixels = cacheCtx.getImageData(0, 0, w, h).data;
          var ctx;
          for (var rgbI = 0; rgbI < 4; rgbI++) {
            ctx = cache[rgbI].getContext("2d");
            var to = ctx.getImageData(0, 0, w, h);
            var data = to.data;
            for (var i = 0; i < pixels.length; i += 4) {
              data[i] = 0 === rgbI ? pixels[i] : 0;
              data[i + 1] = 1 === rgbI ? pixels[i + 1] : 0;
              data[i + 2] = 2 === rgbI ? pixels[i + 2] : 0;
              data[i + 3] = pixels[i + 3];
            }
            ctx.putImageData(to, 0, 0);
          }
          image.onload = null;
        };
        var generateGrayTexture = function(texture, rect, renderCanvas) {
          if (null === texture) return null;
          renderCanvas = renderCanvas || document.createElement("canvas");
          rect = rect || cc.rect(0, 0, texture.width, texture.height);
          renderCanvas.width = rect.width;
          renderCanvas.height = rect.height;
          var context = renderCanvas.getContext("2d");
          context.drawImage(texture, rect.x, rect.y, rect.width, rect.height, 0, 0, rect.width, rect.height);
          var imgData = context.getImageData(0, 0, rect.width, rect.height);
          var data = imgData.data;
          for (var i = 0, len = data.length; i < len; i += 4) data[i] = data[i + 1] = data[i + 2] = .34 * data[i] + .5 * data[i + 1] + .16 * data[i + 2];
          context.putImageData(imgData, 0, 0);
          return renderCanvas;
        };
        _p._generateTextureCacheForColor = function() {
          if (this.channelCache) return this.channelCache;
          var textureCache = [ document.createElement("canvas"), document.createElement("canvas"), document.createElement("canvas"), document.createElement("canvas") ];
          renderToCache(this._image, textureCache);
          return this.channelCache = textureCache;
        };
        _p._switchToGray = function(toGray) {
          if (!this.loaded || this._isGray === toGray) return;
          this._isGray = toGray;
          if (this._isGray) {
            this._backupElement = this._image;
            this._grayElementObj || (this._grayElementObj = generateGrayTexture(this._image));
            this._image = this._grayElementObj;
          } else null !== this._backupElement && (this._image = this._backupElement);
        };
        _p._generateGrayTexture = function() {
          if (!this.loaded) return null;
          var grayElement = generateGrayTexture(this._image);
          var newTexture = new Texture2D();
          newTexture.initWithElement(grayElement);
          newTexture.handleLoadedTexture();
          return newTexture;
        };
        _p._generateColorTexture = sys._supportCanvasNewBlendModes ? function(r, g, b, rect, canvas) {
          var onlyCanvas = false;
          canvas ? onlyCanvas = true : canvas = document.createElement("canvas");
          var textureImage = this._image;
          rect || (rect = cc.rect(0, 0, textureImage.width, textureImage.height));
          canvas.width = rect.width;
          canvas.height = rect.height;
          if (rect.width && rect.height) {
            var context = canvas.getContext("2d");
            context.globalCompositeOperation = "source-over";
            context.fillStyle = "rgb(" + (0 | r) + "," + (0 | g) + "," + (0 | b) + ")";
            context.fillRect(0, 0, rect.width, rect.height);
            context.globalCompositeOperation = "multiply";
            context.drawImage(textureImage, rect.x, rect.y, rect.width, rect.height, 0, 0, rect.width, rect.height);
            context.globalCompositeOperation = "destination-atop";
            context.drawImage(textureImage, rect.x, rect.y, rect.width, rect.height, 0, 0, rect.width, rect.height);
          }
          if (onlyCanvas) return canvas;
          var newTexture = new Texture2D();
          newTexture.initWithElement(canvas);
          newTexture.handleLoadedTexture();
          return newTexture;
        } : function(r, g, b, rect, canvas) {
          var onlyCanvas = false;
          canvas ? onlyCanvas = true : canvas = document.createElement("canvas");
          var textureImage = this._image;
          rect || (rect = cc.rect(0, 0, textureImage.width, textureImage.height));
          canvas.width = rect.width;
          canvas.height = rect.height;
          if (rect.width && rect.height) {
            var context = canvas.getContext("2d");
            context.drawImage(textureImage, rect.x, rect.y, rect.width, rect.height, 0, 0, rect.width, rect.height);
            var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
            var data = imageData.data;
            r /= 255;
            g /= 255;
            b /= 255;
            for (var i = 0; i < data.length; i += 4) {
              data[i] = data[i] * r;
              data[i + 1] = data[i + 1] * g;
              data[i + 2] = data[i + 2] * b;
            }
            context.putImageData(imageData, 0, 0);
          }
          if (onlyCanvas) return canvas;
          var newTexture = new Texture2D();
          newTexture.initWithElement(canvas);
          newTexture.handleLoadedTexture();
          return newTexture;
        };
      } else if (cc._renderType === game.RENDER_TYPE_WEBGL) {
        var _sharedOpts;
        (function() {
          function _glTextureFmt(pixelFormat) {
            var glFmt = _textureFmtGL[pixelFormat];
            cc.assertID(glFmt, 3113);
            return glFmt;
          }
          function _isPow2(v) {
            return !(v & v - 1) && !!v;
          }
          _sharedOpts = {
            width: void 0,
            height: void 0,
            minFilter: void 0,
            magFilter: void 0,
            wrapS: void 0,
            wrapT: void 0,
            format: void 0,
            mipmap: void 0,
            image: void 0,
            premultiplyAlpha: void 0
          };
          function _getSharedOptions() {
            for (var key in _sharedOpts) _sharedOpts[key] = void 0;
            return _sharedOpts;
          }
          _p.update = function(options) {
            var genMipmap = this._hasMipmap;
            var gl = this._gl;
            var updateImage = false;
            if (options) {
              void 0 !== options.width && (this.width = options.width);
              void 0 !== options.height && (this.height = options.height);
              void 0 !== options.minFilter && (this._minFilter = options.minFilter);
              void 0 !== options.magFilter && (this._magFilter = options.magFilter);
              void 0 !== options.wrapS && (this._wrapS = options.wrapS);
              void 0 !== options.wrapT && (this._wrapT = options.wrapT);
              if (void 0 !== options.format) {
                this._format = options.format;
                updateImage = true;
              }
              if (void 0 !== options.premultiplyAlpha) {
                this._premultiplyAlpha = options.premultiplyAlpha;
                updateImage = true;
              }
              if (void 0 !== options.image) {
                this._image = options.image;
                updateImage = true;
              }
              void 0 !== options.mipmap && (genMipmap = this._hasMipmap = options.mipmap);
            }
            if (this._image) {
              if (updateImage) {
                this.releaseTexture();
                this._glID = gl.createTexture();
                gl.activeTexture(gl.TEXTURE0);
                gl.bindTexture(gl.TEXTURE_2D, this._glID);
                this._setImage(this._image, this.width, this.height, _glTextureFmt(this._format), this._premultiplyAlpha);
              } else {
                gl.activeTexture(gl.TEXTURE0);
                gl.bindTexture(gl.TEXTURE_2D, this._glID);
              }
              this._setTexInfo();
              if (genMipmap) {
                cc.assertID(_isPow2(this.width) && _isPow2(this.height), 3117);
                gl.hint(gl.GENERATE_MIPMAP_HINT, gl.NICEST);
                gl.generateMipmap(gl.TEXTURE_2D);
              }
              gl.bindTexture(gl.TEXTURE_2D, null);
            }
          };
          _p._setImage = function(img, width, height, glFmt, premultiplyAlpha) {
            var gl = this._gl;
            gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha);
            sys.platform === sys.WECHAT_GAME || img instanceof HTMLCanvasElement || img instanceof HTMLImageElement || img instanceof HTMLVideoElement ? gl.texImage2D(gl.TEXTURE_2D, 0, glFmt.internalFormat, glFmt.format, glFmt.pixelType, img) : gl.texImage2D(gl.TEXTURE_2D, 0, glFmt.internalFormat, width, height, 0, glFmt.format, glFmt.pixelType, img);
          };
          _p._setTexInfo = function() {
            var gl = this._gl;
            var pot = _isPow2(this.width) && _isPow2(this.height);
            if (!pot && (this._wrapS !== WrapMode.CLAMP_TO_EDGE || this._wrapT !== WrapMode.CLAMP_TO_EDGE)) {
              cc.warnID(3116);
              this._wrapS = WrapMode.CLAMP_TO_EDGE;
              this._wrapT = WrapMode.CLAMP_TO_EDGE;
            }
            this._minFilter === Filter.LINEAR ? gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this._hasMipmap ? gl.LINEAR_MIPMAP_NEAREST : gl.LINEAR) : gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, this._hasMipmap ? gl.NEAREST_MIPMAP_NEAREST : gl.NEAREST);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, this._magFilter);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, this._wrapS);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, this._wrapT);
          };
          _p.initWithData = function(data, pixelFormat, pixelsWidth, pixelsHeight, contentSize) {
            contentSize && cc.warnID(3118);
            var opts = _getSharedOptions();
            opts.image = data;
            opts.format = pixelFormat;
            opts.width = pixelsWidth;
            opts.height = pixelsHeight;
            this.update(opts);
            this.width = pixelsWidth;
            this.height = pixelsHeight;
            this.loaded = true;
            this.emit("load");
            return true;
          };
          _p.initWithElement = function(element) {
            if (!element || 0 === element.width || 0 === element.height) return;
            this._image = element;
            return true;
          };
          _p.handleLoadedTexture = function(premultiplied) {
            if (!this._image || !this._image.width || !this._image.height) return;
            var opts = _getSharedOptions();
            opts.image = this._image;
            opts.format = PixelFormat.RGBA8888;
            opts.width = this._image.width;
            opts.height = this._image.height;
            opts.premultiplyAlpha = !!premultiplied;
            var filter = cc.view._antiAliasEnabled ? Filter.LINEAR : Filter.NEAREST;
            opts.minFilter = opts.magFilter = filter;
            this.update(opts);
            this.loaded = true;
            this.emit("load");
          };
          _p.setTexParameters = function(texParams, magFilter, wrapS, wrapT) {
            void 0 !== magFilter && (texParams = {
              minFilter: texParams,
              magFilter: magFilter,
              wrapS: wrapS,
              wrapT: wrapT
            });
            this.update(texParams);
          };
          _p.setAntiAliasTexParameters = function() {
            var opts = _getSharedOptions();
            opts.minFilter = Filter.LINEAR;
            opts.magFilter = Filter.LINEAR;
            this.update(opts);
          };
          _p.setAliasTexParameters = function() {
            var opts = _getSharedOptions();
            opts.minFilter = Filter.NEAREST;
            opts.magFilter = Filter.NEAREST;
            this.update(opts);
          };
        })();
      }
    }));
    cc.Texture2D = module.exports = Texture2D;
  }), {
    "../CCGame": 39,
    "../assets/CCRawAsset": 49,
    "../event/event-target": 112,
    "../platform/CCClass": 175,
    "../platform/CCSys": 184,
    "../platform/_CCClass": 187,
    "../platform/js": 196,
    "../utils/misc": 225
  } ],
  216: [ (function(require, module, exports) {
    var game = require("../CCGame");
    var Texture2D = require("./CCTexture2D");
    var textureCache = {
      _textures: {},
      _textureColorsCache: {},
      _textureKeySeq: 0 | 1e3 * Math.random(),
      handleLoadedTexture: null,
      description: function() {
        return "<TextureCache | Number of textures = " + this._textures.length + ">";
      },
      textureForKey: function(textureKeyName) {
        cc.logID(3002);
        return this.getTextureForKey(textureKeyName);
      },
      getTextureForKey: function(textureKeyName) {
        return this._textures[textureKeyName];
      },
      getKeyByTexture: function(texture) {
        for (var key in this._textures) if (this._textures[key] === texture) return key;
        return null;
      },
      _generalTextureKey: function(id) {
        return "_textureKey_" + id;
      },
      getTextureColors: function(texture) {
        var image = texture._image;
        var key = this.getKeyByTexture(image);
        key || (key = image instanceof HTMLImageElement ? image.src : this._generalTextureKey(texture.__instanceId));
        this._textureColorsCache[key] || (this._textureColorsCache[key] = texture._generateTextureCacheForColor());
        return this._textureColorsCache[key];
      },
      getAllTextures: function() {
        var texs = [];
        for (var key in this._textures) {
          var item = this._textures[key];
          texs.push(item);
        }
        return texs;
      },
      removeAllTextures: function() {
        var locTextures = this._textures;
        for (var selKey in locTextures) locTextures[selKey] && locTextures[selKey].releaseTexture();
        this._textures = {};
      },
      removeTexture: function(texture) {
        if (!texture) return;
        var locTextures = this._textures;
        for (var selKey in locTextures) if (locTextures[selKey] === texture) {
          locTextures[selKey].releaseTexture();
          delete locTextures[selKey];
        }
      },
      removeTextureForKey: function(textureKeyName) {
        if ("string" !== typeof textureKeyName) return;
        var locTextures = this._textures;
        if (locTextures[textureKeyName]) {
          locTextures[textureKeyName].releaseTexture();
          delete locTextures[textureKeyName];
        }
      },
      addImage: null,
      addImageAsync: null,
      cacheImage: function(path, texture) {
        cc.assertID(path, 3009);
        if (texture instanceof Texture2D) {
          this._textures[path] = texture;
          return;
        }
        var texture2d = new Texture2D();
        texture2d.initWithElement(texture);
        texture2d.handleLoadedTexture();
        this._textures[path] = texture2d;
      },
      dumpCachedTextureInfo: function() {
        var count = 0;
        var totalBytes = 0, locTextures = this._textures;
        for (var key in locTextures) {
          var selTexture = locTextures[key];
          count++;
          selTexture.getHtmlElementObj() instanceof HTMLImageElement ? cc.logID(3005, key, selTexture.getHtmlElementObj().src, selTexture.getPixelWidth(), selTexture.getPixelHeight()) : cc.logID(3006, key, selTexture.getPixelWidth(), selTexture.getPixelHeight());
          totalBytes += selTexture.getPixelWidth() * selTexture.getPixelHeight() * 4;
        }
        var locTextureColorsCache = this._textureColorsCache;
        for (key in locTextureColorsCache) {
          var selCanvasColorsArr = locTextureColorsCache[key];
          for (var selCanvasKey in selCanvasColorsArr) {
            var selCanvas = selCanvasColorsArr[selCanvasKey];
            count++;
            cc.logID(3006, key, selCanvas.width, selCanvas.height);
            totalBytes += selCanvas.width * selCanvas.height * 4;
          }
        }
        cc.logID(3007, count, totalBytes / 1024, (totalBytes / 1048576).toFixed(2));
      },
      _clear: function() {
        this._textures = {};
        this._textureColorsCache = {};
        this._textureKeySeq = 0 | 1e3 * Math.random();
      }
    };
    game.once(game.EVENT_RENDERER_INITED, (function() {
      var _p = textureCache;
      if (cc._renderType === game.RENDER_TYPE_CANVAS) {
        _p.handleLoadedTexture = function(url) {
          var locTexs = this._textures;
          var tex = locTexs[url];
          if (!tex) {
            cc.assertID(url, 3009);
            tex = locTexs[url] = new Texture2D();
            tex.url = url;
          }
          tex.handleLoadedTexture();
        };
        _p.addImage = function(url, cb, target) {
          cc.assertID(url, 3103);
          var locTexs = this._textures;
          var tex = locTexs[url];
          if (tex) {
            if (tex.isLoaded()) {
              cb && cb.call(target, tex);
              return tex;
            }
            tex.once("load", (function() {
              cb && cb.call(target, tex);
            }), target);
            return tex;
          }
          tex = locTexs[url] = new Texture2D();
          tex.url = url;
          cc.loader.load(url, (function(err, texture) {
            if (err) return cb && cb.call(target, err || new Error("Unknown error"));
            textureCache.handleLoadedTexture(url);
            cb && cb.call(target, tex);
          }));
          return tex;
        };
        _p.addImageAsync = _p.addImage;
      } else if (cc._renderType === game.RENDER_TYPE_WEBGL) {
        _p.handleLoadedTexture = function(url) {
          var locTexs = this._textures, tex, premultiplied;
          tex = locTexs[url];
          if (!tex) {
            cc.assertID(url, 3009);
            tex = locTexs[url] = new Texture2D();
            tex.url = url;
          }
          tex.handleLoadedTexture();
        };
        _p.addImage = function(url, cb, target) {
          cc.assertID(url, 3112);
          var locTexs = this._textures;
          var tex = locTexs[url];
          if (tex) {
            if (tex.isLoaded()) {
              cb && cb.call(target, tex);
              return tex;
            }
            tex.once("load", (function() {
              cb && cb.call(target, tex);
            }), target);
            return tex;
          }
          tex = locTexs[url] = new Texture2D();
          tex.url = url;
          cc.loader.load(url, (function(err, texture) {
            if (err) return cb && cb.call(target, err || new Error("Unknown error"));
            textureCache.handleLoadedTexture(url);
            cb && cb.call(target, tex);
          }));
          return tex;
        };
        _p.addImageAsync = _p.addImage;
      }
    }));
    cc.textureCache = module.exports = textureCache;
  }), {
    "../CCGame": 39,
    "./CCTexture2D": 215
  } ],
  217: [ (function(require, module, exports) {
    require("./CCTexture2D");
    require("./CCTextureCache");
  }), {
    "./CCTexture2D": 215,
    "./CCTextureCache": 216
  } ],
  218: [ (function(require, module, exports) {
    require("../platform/CCSys");
    var EXTNAME_RE = /(\.[^\.\/\?\\]*)(\?.*)?$/;
    var DIRNAME_RE = /((.*)(\/|\\|\\\\))?(.*?\..*$)?/;
    var NORMALIZE_RE = /[^\.\/]+\/\.\.\//;
    cc.path = {
      join: function() {
        var l = arguments.length;
        var result = "";
        for (var i = 0; i < l; i++) result = (result + ("" === result ? "" : "/") + arguments[i]).replace(/(\/|\\\\)$/, "");
        return result;
      },
      extname: function(pathStr) {
        var temp = EXTNAME_RE.exec(pathStr);
        return temp ? temp[1] : "";
      },
      mainFileName: function(fileName) {
        if (fileName) {
          var idx = fileName.lastIndexOf(".");
          if (-1 !== idx) return fileName.substring(0, idx);
        }
        return fileName;
      },
      basename: function(pathStr, extname) {
        var index = pathStr.indexOf("?");
        index > 0 && (pathStr = pathStr.substring(0, index));
        var reg = /(\/|\\\\)([^(\/|\\\\)]+)$/g;
        var result = reg.exec(pathStr.replace(/(\/|\\\\)$/, ""));
        if (!result) return null;
        var baseName = result[2];
        if (extname && pathStr.substring(pathStr.length - extname.length).toLowerCase() === extname.toLowerCase()) return baseName.substring(0, baseName.length - extname.length);
        return baseName;
      },
      dirname: function(pathStr) {
        var temp = DIRNAME_RE.exec(pathStr);
        return temp ? temp[2] : "";
      },
      changeExtname: function(pathStr, extname) {
        extname = extname || "";
        var index = pathStr.indexOf("?");
        var tempStr = "";
        if (index > 0) {
          tempStr = pathStr.substring(index);
          pathStr = pathStr.substring(0, index);
        }
        index = pathStr.lastIndexOf(".");
        if (index < 0) return pathStr + extname + tempStr;
        return pathStr.substring(0, index) + extname + tempStr;
      },
      changeBasename: function(pathStr, basename, isSameExt) {
        if (0 === basename.indexOf(".")) return this.changeExtname(pathStr, basename);
        var index = pathStr.indexOf("?");
        var tempStr = "";
        var ext = isSameExt ? this.extname(pathStr) : "";
        if (index > 0) {
          tempStr = pathStr.substring(index);
          pathStr = pathStr.substring(0, index);
        }
        index = pathStr.lastIndexOf("/");
        index = index <= 0 ? 0 : index + 1;
        return pathStr.substring(0, index) + basename + ext + tempStr;
      },
      _normalize: function(url) {
        var oldUrl = url = String(url);
        do {
          oldUrl = url;
          url = url.replace(NORMALIZE_RE, "");
        } while (oldUrl.length !== url.length);
        return url;
      },
      sep: cc.sys.os === cc.sys.OS_WINDOWS ? "\\" : "/",
      stripSep: function(path) {
        return path.replace(/[\/\\]$/, "");
      }
    };
    module.exports = cc.path;
  }), {
    "../platform/CCSys": 184
  } ],
  219: [ (function(require, module, exports) {
    var PStats = require("../../../external/pstats/pstats");
    var macro = require("../platform/CCMacro");
    var _fps = document.createElement("div");
    _fps.id = "fps";
    var stats = null;
    var _showFPS = false;
    function beforeUpdate() {
      stats("frame").start();
      stats("logic").start();
    }
    function afterVisit() {
      cc.director.isPaused() ? stats("frame").start() : stats("logic").end();
      stats("render").start();
    }
    function afterDraw() {
      stats("render").end();
      stats("draws").value = cc.g_NumberOfDraws;
      stats("frame").end();
      stats("fps").frame();
      stats().tick();
    }
    cc.profiler = module.exports = {
      isShowingStats: function() {
        return _showFPS;
      },
      hideStats: function() {
        if (_showFPS) {
          _fps.parentElement === document.body && document.body.removeChild(_fps);
          cc.director.off(cc.Director.EVENT_BEFORE_UPDATE, beforeUpdate);
          cc.director.off(cc.Director.EVENT_AFTER_VISIT, afterVisit);
          cc.director.off(cc.Director.EVENT_AFTER_DRAW, afterDraw);
          _showFPS = false;
        }
      },
      showStats: function() {
        if (!_showFPS) {
          stats || (stats = PStats.new(_fps, {
            showGraph: false,
            values: {
              frame: {
                desc: "Frame time (ms)",
                min: 0,
                max: 50,
                average: 500
              },
              fps: {
                desc: "Framerate (FPS)",
                below: 30,
                average: 500
              },
              draws: {
                desc: "Draw call"
              },
              logic: {
                desc: "Game Logic (ms)",
                min: 0,
                max: 50,
                average: 500,
                color: "#080"
              },
              render: {
                desc: "Renderer (ms)",
                min: 0,
                max: 50,
                average: 500,
                color: "#f90"
              },
              mode: {
                desc: cc._renderType === cc.game.RENDER_TYPE_WEBGL ? "WebGL" : "Canvas",
                min: 1
              }
            },
            css: ".pstats {left: " + macro.DIRECTOR_STATS_POSITION.x + "px; bottom: " + macro.DIRECTOR_STATS_POSITION.y + "px;}"
          }));
          null === _fps.parentElement && document.body.appendChild(_fps);
          cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, beforeUpdate);
          cc.director.on(cc.Director.EVENT_AFTER_VISIT, afterVisit);
          cc.director.on(cc.Director.EVENT_AFTER_DRAW, afterDraw);
          _showFPS = true;
        }
      }
    };
  }), {
    "../../../external/pstats/pstats": 311,
    "../platform/CCMacro": 180
  } ],
  220: [ (function(require, module, exports) {
    var Flags = require("../platform/CCObject").Flags;
    var Misc = require("./misc");
    var IdGenerater = require("../platform/id-generater");
    var eventManager = require("../event-manager");
    var JS = cc.js;
    var Destroying = Flags.Destroying;
    var DontDestroy = Flags.DontDestroy;
    var CHILD_ADDED = "child-added";
    var CHILD_REMOVED = "child-removed";
    var idGenerater = new IdGenerater("Node");
    function getConstructor(typeOrClassName) {
      if (!typeOrClassName) {
        cc.errorID(3804);
        return null;
      }
      if ("string" === typeof typeOrClassName) return JS.getClassByName(typeOrClassName);
      return typeOrClassName;
    }
    function findComponent(node, constructor) {
      for (var i = 0; i < node._components.length; ++i) {
        var comp = node._components[i];
        if (comp instanceof constructor) return comp;
      }
      return null;
    }
    function findComponents(node, constructor, components) {
      for (var i = 0; i < node._components.length; ++i) {
        var comp = node._components[i];
        comp instanceof constructor && components.push(comp);
      }
    }
    function findChildComponent(children, constructor) {
      for (var i = 0; i < children.length; ++i) {
        var node = children[i];
        var comp = findComponent(node, constructor);
        if (comp) return comp;
        if (node._children.length > 0) {
          comp = findChildComponent(node._children, constructor);
          if (comp) return comp;
        }
      }
      return null;
    }
    function findChildComponents(children, constructor, components) {
      for (var i = 0; i < children.length; ++i) {
        var node = children[i];
        findComponents(node, constructor, components);
        node._children.length > 0 && findChildComponents(node._children, constructor, components);
      }
    }
    var BaseNode = cc.Class({
      name: "cc._BaseNode",
      extends: cc.Object,
      mixins: [ cc.EventTarget ],
      properties: {
        _parent: null,
        _children: [],
        _tag: cc.macro.NODE_TAG_INVALID,
        _active: true,
        _components: [],
        _prefab: null,
        _persistNode: {
          get: function() {
            return (this._objFlags & DontDestroy) > 0;
          },
          set: function(value) {
            value ? this._objFlags |= DontDestroy : this._objFlags &= ~DontDestroy;
          }
        },
        name: {
          get: function() {
            return this._name;
          },
          set: function(value) {
            false;
            this._name = value;
          }
        },
        _id: {
          default: "",
          editorOnly: true
        },
        uuid: {
          get: function() {
            var id = this._id;
            id || (id = this._id = idGenerater.getNewId());
            return id;
          }
        },
        children: {
          get: function() {
            return this._children;
          }
        },
        childrenCount: {
          get: function() {
            return this._children.length;
          }
        },
        active: {
          get: function() {
            return this._active;
          },
          set: function(value) {
            value = !!value;
            if (this._active !== value) {
              this._active = value;
              var parent = this._parent;
              if (parent) {
                var couldActiveInScene = parent._activeInHierarchy;
                couldActiveInScene && cc.director._nodeActivator.activateNode(this, value);
              }
            }
          }
        },
        activeInHierarchy: {
          get: function() {
            return this._activeInHierarchy;
          }
        }
      },
      ctor: function(name) {
        this._name = "undefined" !== typeof name ? name : "New Node";
        this._activeInHierarchy = false;
        this.__instanceId = this._id || cc.ClassManager.getNewInstanceId();
        this.__eventTargets = [];
      },
      getTag: function() {
        return this._tag;
      },
      setTag: function(tag) {
        this._tag = tag;
      },
      getParent: function() {
        return this._parent;
      },
      setParent: function(value) {
        if (this._parent === value) return;
        false;
        var oldParent = this._parent;
        this._parent = value || null;
        this._onSetParent(value);
        if (value) {
          true;
          eventManager._setDirtyForNode(this);
          value._children.push(this);
          value.emit(CHILD_ADDED, this);
        }
        if (oldParent) {
          if (!(oldParent._objFlags & Destroying)) {
            var removeAt = oldParent._children.indexOf(this);
            false;
            oldParent._children.splice(removeAt, 1);
            oldParent.emit(CHILD_REMOVED, this);
            this._onHierarchyChanged(oldParent);
          }
        } else value && this._onHierarchyChanged(null);
      },
      init: function() {
        return true;
      },
      attr: function(attrs) {
        JS.mixin(this, attrs);
      },
      getChildByTag: function(aTag) {
        var children = this._children;
        if (null !== children) for (var i = 0; i < children.length; i++) {
          var node = children[i];
          if (node && node._tag === aTag) return node;
        }
        return null;
      },
      getChildByUuid: function(uuid) {
        if (!uuid) {
          cc.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;
      },
      getChildByName: function(name) {
        if (!name) {
          cc.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;
      },
      addChild: function(child) {
        false;
        cc.assertID(child, 1606);
        cc.assertID(null === child._parent, 1605);
        child.setParent(this);
      },
      insertChild: function(child, siblingIndex) {
        child.parent = this;
        child.setSiblingIndex(siblingIndex);
      },
      getSiblingIndex: function() {
        return this._parent ? this._parent._children.indexOf(this) : 0;
      },
      setSiblingIndex: function(index) {
        if (!this._parent) return;
        var siblings = this._parent._children;
        index = -1 !== index ? index : siblings.length - 1;
        var oldIndex = siblings.indexOf(this);
        if (index !== oldIndex) {
          siblings.splice(oldIndex, 1);
          index < siblings.length ? siblings.splice(index, 0, this) : siblings.push(this);
          this._onSiblingIndexChanged && this._onSiblingIndexChanged(index);
        }
      },
      cleanup: function() {},
      removeFromParent: function(cleanup) {
        if (this._parent) {
          void 0 === cleanup && (cleanup = true);
          this._parent.removeChild(this, cleanup);
        }
      },
      removeChild: function(child, cleanup) {
        if (this._children.indexOf(child) > -1) {
          (cleanup || void 0 === cleanup) && child.cleanup();
          child.parent = null;
        }
      },
      removeChildByTag: function(tag, cleanup) {
        tag === cc.macro.NODE_TAG_INVALID && cc.logID(1609);
        var child = this.getChildByTag(tag);
        child ? this.removeChild(child, cleanup) : cc.logID(1610, tag);
      },
      removeAllChildren: function(cleanup) {
        var children = this._children;
        void 0 === cleanup && (cleanup = true);
        for (var i = children.length - 1; i >= 0; i--) {
          var node = children[i];
          if (node) {
            cleanup && node.cleanup();
            node.parent = null;
          }
        }
        this._children.length = 0;
      },
      isChildOf: function(parent) {
        var child = this;
        do {
          if (child === parent) return true;
          child = child._parent;
        } while (child);
        return false;
      },
      getComponent: function(typeOrClassName) {
        var constructor = getConstructor(typeOrClassName);
        if (constructor) return findComponent(this, constructor);
        return null;
      },
      getComponents: function(typeOrClassName) {
        var constructor = getConstructor(typeOrClassName), components = [];
        constructor && findComponents(this, constructor, components);
        return components;
      },
      getComponentInChildren: function(typeOrClassName) {
        var constructor = getConstructor(typeOrClassName);
        if (constructor) return findChildComponent(this._children, constructor);
        return null;
      },
      getComponentsInChildren: function(typeOrClassName) {
        var constructor = getConstructor(typeOrClassName), components = [];
        if (constructor) {
          findComponents(this, constructor, components);
          findChildComponents(this._children, constructor, components);
        }
        return components;
      },
      _checkMultipleComp: false,
      addComponent: function(typeOrClassName) {
        false;
        var constructor;
        if ("string" === typeof typeOrClassName) {
          constructor = JS.getClassByName(typeOrClassName);
          if (!constructor) {
            cc.errorID(3807, typeOrClassName);
            cc._RFpeek() && cc.errorID(3808, typeOrClassName);
            return null;
          }
        } else {
          if (!typeOrClassName) {
            cc.errorID(3804);
            return null;
          }
          constructor = typeOrClassName;
        }
        if ("function" !== typeof constructor) {
          cc.errorID(3809);
          return null;
        }
        if (!cc.isChildClassOf(constructor, cc.Component)) {
          cc.errorID(3810);
          return null;
        }
        false;
        var ReqComp = constructor._requireComponent;
        if (ReqComp && !this.getComponent(ReqComp)) {
          var depended = this.addComponent(ReqComp);
          if (!depended) return null;
        }
        var component = new constructor();
        component.node = this;
        this._components.push(component);
        this._activeInHierarchy && cc.director._nodeActivator.activateComp(component);
        return component;
      },
      _addComponentAt: false,
      removeComponent: function(component) {
        if (!component) {
          cc.errorID(3813);
          return;
        }
        component instanceof cc.Component || (component = this.getComponent(component));
        component && component.destroy();
      },
      _getDependComponent: false,
      _removeComponent: function(component) {
        if (!component) {
          cc.errorID(3814);
          return;
        }
        if (!(this._objFlags & Destroying)) {
          var i = this._components.indexOf(component);
          -1 !== i ? this._components.splice(i, 1) : component.node !== this && cc.errorID(3815);
        }
      },
      _disableChildComps: function() {
        var i, len = this._components.length;
        for (i = 0; i < len; ++i) {
          var component = this._components[i];
          component._enabled && cc.director._compScheduler.disableComp(component);
        }
        for (i = 0, len = this._children.length; i < len; ++i) {
          var node = this._children[i];
          node._active && node._disableChildComps();
        }
      },
      destroy: function() {
        cc.Object.prototype.destroy.call(this) && this._activeInHierarchy && this._disableChildComps();
      },
      destroyAllChildren: function() {
        var children = this._children;
        for (var i = 0; i < children.length; ++i) children[i].destroy();
      },
      _onSetParent: function(value) {},
      _onPostActivated: function() {},
      _onHierarchyChanged: function(oldParent) {
        var newParent = this._parent;
        if (this._persistNode && !(newParent instanceof cc.Scene)) {
          cc.game.removePersistRootNode(this);
          false;
        }
        var shouldActiveNow = this._active && !!(newParent && newParent._activeInHierarchy);
        this._activeInHierarchy !== shouldActiveNow && cc.director._nodeActivator.activateNode(this, shouldActiveNow);
        var scene;
        var inCurrentSceneBefore;
        var inCurrentSceneNow;
        var newPrefabRoot;
        var myPrefabInfo;
        false, false;
      },
      _onBatchCreated: function() {
        var prefabInfo = this._prefab;
        prefabInfo && prefabInfo.sync && !prefabInfo._synced && prefabInfo.root === this && PrefabHelper.syncWithPrefab(this);
        var children = this._children;
        for (var i = 0, len = children.length; i < len; i++) children[i]._onBatchCreated();
      },
      _instantiate: function(cloned) {
        cloned || (cloned = cc.instantiate._clone(this, this));
        var thisPrefabInfo = this._prefab;
        false;
        var syncing = thisPrefabInfo && this === thisPrefabInfo.root && thisPrefabInfo.sync;
        !!syncing && (cloned._prefab._synced = thisPrefabInfo._synced);
        cloned._parent = null;
        cloned._onBatchCreated();
        return cloned;
      },
      _registerIfAttached: (false, false) && function(register) {
        if (register) {
          cc.engine.attachedObjsForEditor[this.uuid] = this;
          cc.engine.emit("node-attach-to-scene", {
            target: this
          });
        } else {
          cc.engine.emit("node-detach-from-scene", {
            target: this
          });
          delete cc.engine.attachedObjsForEditor[this._id];
        }
        var children = this._children;
        for (var i = 0, len = children.length; i < len; ++i) {
          var child = children[i];
          child._registerIfAttached(register);
        }
      },
      _onPreDestroy: function() {
        var i, len;
        this._objFlags |= Destroying;
        var parent = this._parent;
        var destroyByParent = parent && parent._objFlags & Destroying;
        !destroyByParent && (false, false) && this._registerIfAttached(false);
        var children = this._children;
        for (i = 0, len = children.length; i < len; ++i) children[i]._destroyImmediate();
        for (i = 0, len = this._components.length; i < len; ++i) {
          var component = this._components[i];
          component._destroyImmediate();
        }
        var eventTargets = this.__eventTargets;
        for (i = 0, len = eventTargets.length; i < len; ++i) {
          var target = eventTargets[i];
          target && target.targetOff(this);
        }
        eventTargets.length = 0;
        this._persistNode && cc.game.removePersistRootNode(this);
        if (!destroyByParent && parent) {
          var childIndex = parent._children.indexOf(this);
          parent._children.splice(childIndex, 1);
          parent.emit("child-removed", this);
        }
        return destroyByParent;
      },
      onRestore: false
    });
    BaseNode.prototype._onPreDestroyBase = BaseNode.prototype._onPreDestroy;
    false;
    BaseNode.prototype._onHierarchyChangedBase = BaseNode.prototype._onHierarchyChanged;
    false;
    var SameNameGetSets = [ "name", "children", "childrenCount" ];
    Misc.propertyDefine(BaseNode, SameNameGetSets, {});
    false;
    cc._BaseNode = module.exports = BaseNode;
  }), {
    "../event-manager": 110,
    "../platform/CCObject": 181,
    "../platform/id-generater": 192,
    "./misc": 225
  } ],
  221: [ (function(require, module, exports) {
    var EPSILON = 1e-6;
    function binarySearchEpsilon(array, value) {
      for (var l = 0, h = array.length - 1, m = h >>> 1; l <= h; m = l + h >>> 1) {
        var test = array[m];
        if (test > value + EPSILON) h = m - 1; else {
          if (!(test < value - EPSILON)) return m;
          l = m + 1;
        }
      }
      return ~l;
    }
    module.exports = {
      binarySearchEpsilon: binarySearchEpsilon
    };
  }), {} ],
  222: [ (function(require, module, exports) {
    var Base64Values = require("./misc").BASE64_VALUES;
    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);
    module.exports = function(base64) {
      if (22 !== base64.length) return base64;
      UuidTemplate[0] = base64[0];
      UuidTemplate[1] = base64[1];
      for (var i = 2, j = 2; i < 22; i += 2) {
        var lhs = Base64Values[base64.charCodeAt(i)];
        var rhs = Base64Values[base64.charCodeAt(i + 1)];
        UuidTemplate[Indices[j++]] = HexChars[lhs >> 2];
        UuidTemplate[Indices[j++]] = HexChars[(3 & lhs) << 2 | rhs >> 4];
        UuidTemplate[Indices[j++]] = HexChars[15 & rhs];
      }
      return UuidTemplate.join("");
    };
    false;
  }), {
    "./misc": 225
  } ],
  223: [ (function(require, module, exports) {
    cc.find = module.exports = function(path, referenceNode) {
      if (null == path) {
        cc.errorID(5600);
        return null;
      }
      if (referenceNode) false; else {
        var scene = cc.director.getScene();
        if (!scene) {
          false;
          return null;
        }
        false;
        referenceNode = scene;
      }
      var match = referenceNode;
      var startIndex = "/" !== path[0] ? 0 : 1;
      var nameList = path.split("/");
      for (var n = startIndex; n < nameList.length; n++) {
        var name = nameList[n];
        var children = match._children;
        match = null;
        for (var t = 0, len = children.length; t < len; ++t) {
          var subChild = children[t];
          if (subChild.name === name) {
            match = subChild;
            break;
          }
        }
        if (!match) return null;
      }
      return match;
    };
  }), {} ],
  224: [ (function(require, module, exports) {
    require("./CCPath");
    true, true;
    require("./CCProfiler");
    require("./find");
    require("./mutable-forward-iterator");
  }), {
    "./CCPath": 218,
    "./CCProfiler": 219,
    "./find": 223,
    "./mutable-forward-iterator": 226
  } ],
  225: [ (function(require, module, exports) {
    var JS = require("../platform/js");
    var sys = require("../platform/CCSys");
    var misc = exports;
    misc.propertyDefine = function(ctor, sameNameGetSets, diffNameGetSets) {
      function define(np, propName, getter, setter) {
        var pd = Object.getOwnPropertyDescriptor(np, propName);
        if (pd) {
          pd.get && (np[getter] = pd.get);
          pd.set && setter && (np[setter] = pd.set);
        } else {
          var getterFunc = np[getter];
          var clsName;
          false;
          cc.js.getset(np, propName, getterFunc, np[setter]);
        }
      }
      var propName, np = ctor.prototype;
      for (var i = 0; i < sameNameGetSets.length; i++) {
        propName = sameNameGetSets[i];
        var suffix = propName[0].toUpperCase() + propName.slice(1);
        define(np, propName, "get" + suffix, "set" + suffix);
      }
      for (propName in diffNameGetSets) {
        var getset = diffNameGetSets[propName];
        define(np, propName, getset[0], getset[1]);
      }
    };
    misc.NextPOT = function(x) {
      x -= 1;
      x |= x >> 1;
      x |= x >> 2;
      x |= x >> 4;
      x |= x >> 8;
      x |= x >> 16;
      return x + 1;
    };
    false;
    misc.imagePool = new JS.Pool(function(img) {
      if (img instanceof HTMLImageElement) {
        img.src = this._smallImg;
        return true;
      }
      return false;
    }, 10);
    misc.imagePool.get = function() {
      return this._get() || new Image();
    };
    misc.imagePool._smallImg = "data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA=";
    sys.os !== sys.OS_WINDOWS && sys.os !== sys.OS_LINUX || sys.browserType === sys.BROWSER_TYPE_CHROME || misc.imagePool.resize(0);
    misc.BUILTIN_CLASSID_RE = /^(?:cc|dragonBones|sp|ccsg)\..+/;
    var BASE64_KEYS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var BASE64_VALUES = new Array(123);
    for (var i = 0; i < 123; ++i) BASE64_VALUES[i] = 64;
    for (var _i = 0; _i < 64; ++_i) BASE64_VALUES[BASE64_KEYS.charCodeAt(_i)] = _i;
    misc.BASE64_VALUES = BASE64_VALUES;
    misc.pushToMap = function(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;
    };
  }), {
    "../platform/CCSys": 184,
    "../platform/js": 196
  } ],
  226: [ (function(require, module, exports) {
    function MutableForwardIterator(array) {
      this.i = 0;
      this.array = array;
    }
    var proto = MutableForwardIterator.prototype;
    proto.remove = function(value) {
      var index = this.array.indexOf(value);
      index >= 0 && this.removeAt(index);
    };
    proto.removeAt = function(i) {
      this.array.splice(i, 1);
      i <= this.i && --this.i;
    };
    proto.fastRemove = function(value) {
      var index = this.array.indexOf(value);
      index >= 0 && this.fastRemoveAt(index);
    };
    proto.fastRemoveAt = function(i) {
      var array = this.array;
      array[i] = array[array.length - 1];
      --array.length;
      i <= this.i && --this.i;
    };
    proto.push = function(item) {
      this.array.push(item);
    };
    module.exports = MutableForwardIterator;
  }), {} ],
  227: [ (function(require, module, exports) {
    cc._PrefabInfo = cc.Class({
      name: "cc.PrefabInfo",
      properties: {
        root: null,
        asset: null,
        fileId: "",
        sync: false,
        _synced: {
          default: false,
          serializable: false
        }
      }
    });
    module.exports = {
      syncWithPrefab: function(node) {
        var _prefab = node._prefab;
        _prefab._synced = true;
        if (!_prefab.asset) {
          false;
          cc.errorID(3701, node.name);
          node._prefab = null;
          return;
        }
        var _objFlags = node._objFlags;
        var _parent = node._parent;
        var _id = node._id;
        var _name = node._name;
        var _active = node._active;
        var x = node._position.x;
        var y = node._position.y;
        var _rotationX = node._rotationX;
        var _rotationY = node._rotationY;
        var _localZOrder = node._localZOrder;
        var _globalZOrder = node._globalZOrder;
        cc.game._isCloning = true;
        var prefabRoot;
        true;
        _prefab.asset._doInstantiate(node);
        cc.game._isCloning = false;
        node._objFlags = _objFlags;
        node._parent = _parent;
        node._id = _id;
        node._prefab = _prefab;
        node._name = _name;
        node._active = _active;
        node._position.x = x;
        node._position.y = y;
        node._rotationX = _rotationX;
        node._rotationY = _rotationY;
        node._localZOrder = _localZOrder;
        node._globalZOrder = _globalZOrder;
      }
    };
  }), {} ],
  228: [ (function(require, module, exports) {
    var SceneGraphUtils = {
      removeSgNode: function() {
        var sgNode = this._sgNode;
        if (sgNode) {
          var parent = sgNode._parent;
          if (parent) parent.removeChild(sgNode); else {
            false;
            sgNode.performRecursive(_ccsg.Node.performType.cleanup);
          }
          sgNode._entity && (sgNode._entity = null);
        }
      }
    };
    false;
    module.exports = SceneGraphUtils;
  }), {} ],
  229: [ (function(require, module, exports) {
    cc.AffineTransform = function(a, b, c, d, tx, ty) {
      this.a = a;
      this.b = b;
      this.c = c;
      this.d = d;
      this.tx = tx;
      this.ty = ty;
    };
    cc.affineTransformMake = function(a, b, c, d, tx, ty) {
      return {
        a: a,
        b: b,
        c: c,
        d: d,
        tx: tx,
        ty: ty
      };
    };
    cc.affineTransformClone = function(t) {
      return {
        a: t.a,
        b: t.b,
        c: t.c,
        d: t.d,
        tx: t.tx,
        ty: t.ty
      };
    };
    cc.pointApplyAffineTransform = function(point, transOrY, t) {
      var x, y;
      if (void 0 === t) {
        t = transOrY;
        x = point.x;
        y = point.y;
      } else {
        x = point;
        y = transOrY;
      }
      return {
        x: t.a * x + t.c * y + t.tx,
        y: t.b * x + t.d * y + t.ty
      };
    };
    cc._pointApplyAffineTransformIn = function(point, transOrY, transOrOut, out) {
      var x, y, t;
      if (void 0 === out) {
        t = transOrY;
        x = point.x;
        y = point.y;
        out = transOrOut;
      } else {
        x = point;
        y = transOrY;
        t = transOrOut;
      }
      out.x = t.a * x + t.c * y + t.tx;
      out.y = t.b * x + t.d * y + t.ty;
    };
    cc._pointApplyAffineTransform = function(x, y, t) {
      return cc.pointApplyAffineTransform(x, y, t);
    };
    cc.sizeApplyAffineTransform = function(size, t) {
      return {
        width: t.a * size.width + t.c * size.height,
        height: t.b * size.width + t.d * size.height
      };
    };
    cc.affineTransformMakeIdentity = function() {
      return {
        a: 1,
        b: 0,
        c: 0,
        d: 1,
        tx: 0,
        ty: 0
      };
    };
    cc.affineTransformIdentity = function() {
      return {
        a: 1,
        b: 0,
        c: 0,
        d: 1,
        tx: 0,
        ty: 0
      };
    };
    cc.rectApplyAffineTransform = function(rect, t) {
      var ol = rect.x;
      var ob = rect.y;
      var or = ol + rect.width;
      var ot = ob + rect.height;
      var lbx = t.a * ol + t.c * ob + t.tx;
      var lby = t.b * ol + t.d * ob + t.ty;
      var rbx = t.a * or + t.c * ob + t.tx;
      var rby = t.b * or + t.d * ob + t.ty;
      var ltx = t.a * ol + t.c * ot + t.tx;
      var lty = t.b * ol + 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);
      return cc.rect(minX, minY, maxX - minX, maxY - minY);
    };
    cc._rectApplyAffineTransformIn = function(rect, t) {
      var ol = rect.x;
      var ob = rect.y;
      var or = ol + rect.width;
      var ot = ob + rect.height;
      var lbx = t.a * ol + t.c * ob + t.tx;
      var lby = t.b * ol + t.d * ob + t.ty;
      var rbx = t.a * or + t.c * ob + t.tx;
      var rby = t.b * or + t.d * ob + t.ty;
      var ltx = t.a * ol + t.c * ot + t.tx;
      var lty = t.b * ol + 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);
      rect.x = minX;
      rect.y = minY;
      rect.width = maxX - minX;
      rect.height = maxY - minY;
      return rect;
    };
    cc.obbApplyAffineTransform = function(rect, anAffineTransform, out_bl, out_tl, out_tr, out_br) {
      var x = rect.x;
      var y = rect.y;
      var width = rect.width;
      var height = rect.height;
      var tx = anAffineTransform.a * x + anAffineTransform.c * y + anAffineTransform.tx;
      var ty = anAffineTransform.b * x + anAffineTransform.d * y + anAffineTransform.ty;
      var xa = anAffineTransform.a * width;
      var xb = anAffineTransform.b * width;
      var yc = anAffineTransform.c * height;
      var yd = anAffineTransform.d * 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;
    };
    cc.affineTransformTranslate = function(t, tx, ty) {
      return {
        a: t.a,
        b: t.b,
        c: t.c,
        d: t.d,
        tx: t.tx + t.a * tx + t.c * ty,
        ty: t.ty + t.b * tx + t.d * ty
      };
    };
    cc.affineTransformScale = function(t, sx, sy) {
      return {
        a: t.a * sx,
        b: t.b * sx,
        c: t.c * sy,
        d: t.d * sy,
        tx: t.tx,
        ty: t.ty
      };
    };
    cc.affineTransformRotate = function(aTransform, anAngle) {
      var fSin = Math.sin(anAngle);
      var fCos = Math.cos(anAngle);
      return {
        a: aTransform.a * fCos + aTransform.c * fSin,
        b: aTransform.b * fCos + aTransform.d * fSin,
        c: aTransform.c * fCos - aTransform.a * fSin,
        d: aTransform.d * fCos - aTransform.b * fSin,
        tx: aTransform.tx,
        ty: aTransform.ty
      };
    };
    cc.affineTransformConcat = function(t1, t2) {
      return {
        a: t1.a * t2.a + t1.b * t2.c,
        b: t1.a * t2.b + t1.b * t2.d,
        c: t1.c * t2.a + t1.d * t2.c,
        d: t1.c * t2.b + t1.d * t2.d,
        tx: t1.tx * t2.a + t1.ty * t2.c + t2.tx,
        ty: t1.tx * t2.b + t1.ty * t2.d + t2.ty
      };
    };
    cc.affineTransformConcatIn = function(t1, t2) {
      var a = t1.a, b = t1.b, c = t1.c, d = t1.d, tx = t1.tx, ty = t1.ty;
      t1.a = a * t2.a + b * t2.c;
      t1.b = a * t2.b + b * t2.d;
      t1.c = c * t2.a + d * t2.c;
      t1.d = c * t2.b + d * t2.d;
      t1.tx = tx * t2.a + ty * t2.c + t2.tx;
      t1.ty = tx * t2.b + ty * t2.d + t2.ty;
      return t1;
    };
    cc.affineTransformEqualToTransform = function(t1, t2) {
      return t1.a === t2.a && t1.b === t2.b && t1.c === t2.c && t1.d === t2.d && t1.tx === t2.tx && t1.ty === t2.ty;
    };
    cc.affineTransformInvert = function(t) {
      var determinant = 1 / (t.a * t.d - t.b * t.c);
      return {
        a: determinant * t.d,
        b: -determinant * t.b,
        c: -determinant * t.c,
        d: determinant * t.a,
        tx: determinant * (t.c * t.ty - t.d * t.tx),
        ty: determinant * (t.b * t.tx - t.a * t.ty)
      };
    };
    cc.affineTransformInvertIn = function(t) {
      var a = t.a, b = t.b, c = t.c, d = t.d;
      var determinant = 1 / (a * d - b * c);
      var tx = t.tx, ty = t.ty;
      t.a = determinant * d;
      t.b = -determinant * b;
      t.c = -determinant * c;
      t.d = determinant * a;
      t.tx = determinant * (c * ty - d * tx);
      t.ty = determinant * (b * tx - a * ty);
      return t;
    };
    cc.affineTransformInvertOut = function(t, out) {
      var a = t.a, b = t.b, c = t.c, d = t.d;
      var determinant = 1 / (a * d - b * c);
      out.a = determinant * d;
      out.b = -determinant * b;
      out.c = -determinant * c;
      out.d = determinant * a;
      out.tx = determinant * (c * t.ty - d * t.tx);
      out.ty = determinant * (b * t.tx - a * t.ty);
    };
  }), {} ],
  230: [ (function(require, module, exports) {
    var ValueType = require("./CCValueType");
    var JS = require("../platform/js");
    var Color = (function() {
      function Color(r, g, b, a) {
        if ("object" === typeof r) {
          g = r.g;
          b = r.b;
          a = r.a;
          r = r.r;
        }
        r = r || 0;
        g = g || 0;
        b = b || 0;
        a = "number" === typeof a ? a : 255;
        this._val = (~~r << 24 >>> 0) + (~~g << 16) + (~~b << 8) + ~~a;
      }
      JS.extend(Color, ValueType);
      require("../platform/CCClass").fastDefine("cc.Color", Color, {
        r: 0,
        g: 0,
        b: 0,
        a: 255
      });
      var DefaultColors = {
        WHITE: [ 255, 255, 255, 255 ],
        BLACK: [ 0, 0, 0, 255 ],
        TRANSPARENT: [ 0, 0, 0, 0 ],
        GRAY: [ 127.5, 127.5, 127.5 ],
        RED: [ 255, 0, 0 ],
        GREEN: [ 0, 255, 0 ],
        BLUE: [ 0, 0, 255 ],
        YELLOW: [ 255, 235, 4 ],
        ORANGE: [ 255, 127, 0 ],
        CYAN: [ 0, 255, 255 ],
        MAGENTA: [ 255, 0, 255 ]
      };
      for (var colorName in DefaultColors) JS.get(Color, colorName, (function(rgba) {
        return function() {
          return new Color(rgba[0], rgba[1], rgba[2], rgba[3]);
        };
      })(DefaultColors[colorName]));
      var proto = Color.prototype;
      proto.clone = function() {
        var ret = new Color();
        ret._val = this._val;
        return ret;
      };
      proto.equals = function(other) {
        return other && this._val === other._val;
      };
      proto.lerp = function(to, ratio, out) {
        out = out || new Color();
        var r = this.r;
        var g = this.g;
        var b = this.b;
        var a = this.a;
        out.r = r + (to.r - r) * ratio;
        out.g = g + (to.g - g) * ratio;
        out.b = b + (to.b - b) * ratio;
        out.a = a + (to.a - a) * ratio;
        return out;
      };
      proto.toString = function() {
        return "rgba(" + this.r.toFixed() + ", " + this.g.toFixed() + ", " + this.b.toFixed() + ", " + this.a.toFixed() + ")";
      };
      proto.getR = function() {
        return (4278190080 & this._val) >>> 24;
      };
      proto.setR = function(red) {
        this._val = (16777215 & this._val | ~~red << 24 >>> 0) >>> 0;
        return this;
      };
      proto.getG = function() {
        return (16711680 & this._val) >> 16;
      };
      proto.setG = function(green) {
        this._val = (4278255615 & this._val | ~~green << 16) >>> 0;
        return this;
      };
      proto.getB = function() {
        return (65280 & this._val) >> 8;
      };
      proto.setB = function(blue) {
        this._val = (4294902015 & this._val | ~~blue << 8) >>> 0;
        return this;
      };
      proto.getA = function() {
        return 255 & this._val;
      };
      proto.setA = function(alpha) {
        this._val = (4294967040 & this._val | ~~alpha) >>> 0;
        return this;
      };
      JS.getset(proto, "r", proto.getR, proto.setR, true);
      JS.getset(proto, "g", proto.getG, proto.setG, true);
      JS.getset(proto, "b", proto.getB, proto.setB, true);
      JS.getset(proto, "a", proto.getA, proto.setA, true);
      proto.toCSS = function(opt) {
        return "rgba" === opt ? "rgba(" + (0 | this.r) + "," + (0 | this.g) + "," + (0 | this.b) + "," + (this.a / 255).toFixed(2) + ")" : "rgb" === opt ? "rgb(" + (0 | this.r) + "," + (0 | this.g) + "," + (0 | this.b) + ")" : "#" + this.toHEX(opt);
      };
      proto.clamp = function() {
        return;
      };
      proto.fromHEX = function(hexString) {
        hexString.length < 8 && (hexString += "FF");
        var hex = parseInt(hexString.indexOf("#") > -1 ? hexString.substring(1) : hexString, 16);
        this._val = (0 & this._val | hex) >>> 0;
        return this;
      };
      proto.toHEX = function(fmt) {
        var hex = [ (0 | this.r).toString(16), (0 | this.g).toString(16), (0 | this.b).toString(16) ];
        var i = -1;
        if ("#rgb" === fmt) for (i = 0; i < hex.length; ++i) hex[i].length > 1 && (hex[i] = hex[i][0]); else if ("#rrggbb" === fmt) for (i = 0; i < hex.length; ++i) 1 === hex[i].length && (hex[i] = "0" + hex[i]);
        return hex.join("");
      };
      proto.toRGBValue = function() {
        return 16777215 & this._val;
      };
      proto.fromHSV = function(h, s, v) {
        var rgb = Color.hsv2rgb(h, s, v);
        this._val = (rgb.r << 24 >>> 0) + (rgb.g << 16) + (rgb.b << 8) + this.a;
        return this;
      };
      proto.toHSV = function() {
        return Color.rgb2hsv(this.r, this.g, this.b);
      };
      proto.fromColor = function(color) {
        if (color._val) this._val = color._val; else {
          this.r = color.r;
          this.g = color.g;
          this.b = color.b;
          this.a = color.a;
        }
      };
      return Color;
    })();
    Color.rgb2hsv = function(r, g, b) {
      r /= 255;
      g /= 255;
      b /= 255;
      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) {
        delta = max - min;
        hsv.h = r === max ? (g - b) / delta : g === max ? 2 + (b - r) / delta : 4 + (r - g) / delta;
        hsv.h /= 6;
        hsv.h < 0 && (hsv.h += 1);
      } else hsv.h = 0;
      return hsv;
    };
    Color.hsv2rgb = function(h, s, v) {
      var rgb = {
        r: 0,
        g: 0,
        b: 0
      };
      if (0 === s) rgb.r = rgb.g = rgb.b = v; else if (0 === v) rgb.r = rgb.g = rgb.b = 0; else {
        1 === h && (h = 0);
        h *= 6;
        s = s;
        v = v;
        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:
          rgb.r = v;
          rgb.g = t;
          rgb.b = p;
          break;

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

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

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

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

         case 5:
          rgb.r = v;
          rgb.g = p;
          rgb.b = q;
        }
      }
      rgb.r *= 255;
      rgb.g *= 255;
      rgb.b *= 255;
      return rgb;
    };
    cc.Color = Color;
    cc.color = function color(r, g, b, a) {
      if ("string" === typeof r) {
        var result = new cc.Color();
        return result.fromHEX(r);
      }
      if ("object" === typeof r) return new cc.Color(r.r, r.g, r.b, r.a);
      return new cc.Color(r, g, b, a);
    };
    cc.colorEqual = function(color1, color2) {
      return void 0 !== color1._val && void 0 !== color2._val ? color1._val === color2._val : color1.r === color2.r && color1.g === color2.g && color1.b === color2.b;
    };
    cc.hexToColor = function(hex) {
      hex = hex.replace(/^#?/, "0x");
      var c = parseInt(hex);
      var r = c >> 16;
      var g = (65280 & c) >> 8;
      var b = 255 & c;
      return cc.color(r, g, b);
    };
    cc.colorToHex = function(color) {
      var hR = color.r.toString(16), hG = color.g.toString(16), hB = color.b.toString(16);
      return "#" + (color.r < 16 ? "0" + hR : hR) + (color.g < 16 ? "0" + hG : hG) + (color.b < 16 ? "0" + hB : hB);
    };
    module.exports = cc.Color;
  }), {
    "../platform/CCClass": 175,
    "../platform/js": 196,
    "./CCValueType": 236
  } ],
  231: [ (function(require, module, exports) {
    var POINT_EPSILON = parseFloat("1.192092896e-07F");
    cc.pNeg = function(point) {
      return cc.p(-point.x, -point.y);
    };
    cc.pAdd = function(v1, v2) {
      return cc.p(v1.x + v2.x, v1.y + v2.y);
    };
    cc.pSub = function(v1, v2) {
      return cc.p(v1.x - v2.x, v1.y - v2.y);
    };
    cc.pMult = function(point, floatVar) {
      return cc.p(point.x * floatVar, point.y * floatVar);
    };
    cc.pMidpoint = function(v1, v2) {
      return cc.pMult(cc.pAdd(v1, v2), .5);
    };
    cc.pDot = function(v1, v2) {
      return v1.x * v2.x + v1.y * v2.y;
    };
    cc.pCross = function(v1, v2) {
      return v1.x * v2.y - v1.y * v2.x;
    };
    cc.pPerp = function(point) {
      return cc.p(-point.y, point.x);
    };
    cc.pRPerp = function(point) {
      return cc.p(point.y, -point.x);
    };
    cc.pProject = function(v1, v2) {
      return cc.pMult(v2, cc.pDot(v1, v2) / cc.pDot(v2, v2));
    };
    cc.pLengthSQ = function(v) {
      return cc.pDot(v, v);
    };
    cc.pDistanceSQ = function(point1, point2) {
      return cc.pLengthSQ(cc.pSub(point1, point2));
    };
    cc.pLength = function(v) {
      return Math.sqrt(cc.pLengthSQ(v));
    };
    cc.pDistance = function(v1, v2) {
      return cc.pLength(cc.pSub(v1, v2));
    };
    cc.pNormalize = function(v) {
      var n = cc.pLength(v);
      return 0 === n ? cc.p(v) : cc.pMult(v, 1 / n);
    };
    cc.pForAngle = function(a) {
      return cc.p(Math.cos(a), Math.sin(a));
    };
    cc.pToAngle = function(v) {
      return Math.atan2(v.y, v.x);
    };
    cc.clampf = function(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;
    };
    cc.clamp01 = function(value) {
      return value < 0 ? 0 : value < 1 ? value : 1;
    };
    cc.pClamp = function(p, min_inclusive, max_inclusive) {
      return cc.p(cc.clampf(p.x, min_inclusive.x, max_inclusive.x), cc.clampf(p.y, min_inclusive.y, max_inclusive.y));
    };
    cc.pFromSize = function(s) {
      return cc.p(s.width, s.height);
    };
    cc.pCompOp = function(p, opFunc) {
      return cc.p(opFunc(p.x), opFunc(p.y));
    };
    cc.pLerp = function(a, b, alpha) {
      return cc.pAdd(cc.pMult(a, 1 - alpha), cc.pMult(b, alpha));
    };
    cc.pFuzzyEqual = function(a, b, variance) {
      if (a.x - variance <= b.x && b.x <= a.x + variance && a.y - variance <= b.y && b.y <= a.y + variance) return true;
      return false;
    };
    cc.pCompMult = function(a, b) {
      return cc.p(a.x * b.x, a.y * b.y);
    };
    cc.pAngleSigned = function(a, b) {
      var a2 = cc.pNormalize(a);
      var b2 = cc.pNormalize(b);
      var angle = Math.atan2(a2.x * b2.y - a2.y * b2.x, cc.pDot(a2, b2));
      if (Math.abs(angle) < POINT_EPSILON) return 0;
      return angle;
    };
    cc.pAngle = function(a, b) {
      var angle = Math.acos(cc.pDot(cc.pNormalize(a), cc.pNormalize(b)));
      if (Math.abs(angle) < POINT_EPSILON) return 0;
      return angle;
    };
    cc.pRotateByAngle = function(v, pivot, angle) {
      var r = cc.pSub(v, pivot);
      var cosa = Math.cos(angle), sina = Math.sin(angle);
      var t = r.x;
      r.x = t * cosa - r.y * sina + pivot.x;
      r.y = t * sina + r.y * cosa + pivot.y;
      return r;
    };
    cc.pLineIntersect = function(A, B, C, D, retP) {
      if (A.x === B.x && A.y === B.y || C.x === D.x && C.y === D.y) return false;
      var BAx = B.x - A.x;
      var BAy = B.y - A.y;
      var DCx = D.x - C.x;
      var DCy = D.y - C.y;
      var ACx = A.x - C.x;
      var ACy = A.y - C.y;
      var denom = DCy * BAx - DCx * BAy;
      retP.x = DCx * ACy - DCy * ACx;
      retP.y = BAx * ACy - BAy * ACx;
      if (0 === denom) {
        if (0 === retP.x || 0 === retP.y) return true;
        return false;
      }
      retP.x = retP.x / denom;
      retP.y = retP.y / denom;
      return true;
    };
    cc.pSegmentIntersect = function(A, B, C, D) {
      var retP = cc.p(0, 0);
      if (cc.pLineIntersect(A, B, C, D, retP) && retP.x >= 0 && retP.x <= 1 && retP.y >= 0 && retP.y <= 1) return true;
      return false;
    };
    cc.pIntersectPoint = function(A, B, C, D) {
      var retP = cc.p(0, 0);
      if (cc.pLineIntersect(A, B, C, D, retP)) {
        var P = cc.p(0, 0);
        P.x = A.x + retP.x * (B.x - A.x);
        P.y = A.y + retP.x * (B.y - A.y);
        return P;
      }
      return cc.p(0, 0);
    };
    cc.pSameAs = function(A, B) {
      if (null != A && null != B) return A.x === B.x && A.y === B.y;
      return false;
    };
    cc.pZeroIn = function(v) {
      v.x = 0;
      v.y = 0;
    };
    cc.pIn = function(v1, v2) {
      v1.x = v2.x;
      v1.y = v2.y;
    };
    cc.pMultIn = function(point, floatVar) {
      point.x *= floatVar;
      point.y *= floatVar;
    };
    cc.pSubIn = function(v1, v2) {
      v1.x -= v2.x;
      v1.y -= v2.y;
    };
    cc.pAddIn = function(v1, v2) {
      v1.x += v2.x;
      v1.y += v2.y;
    };
    cc.pNormalizeIn = function(v) {
      cc.pMultIn(v, 1 / Math.sqrt(v.x * v.x + v.y * v.y));
    };
  }), {} ],
  232: [ (function(require, module, exports) {
    var ValueType = require("./CCValueType");
    var JS = require("../platform/js");
    function Rect(x, y, w, h) {
      if (x && "object" === typeof x) {
        y = x.y;
        w = x.width;
        h = x.height;
        x = x.x;
      }
      this.x = x || 0;
      this.y = y || 0;
      this.width = w || 0;
      this.height = h || 0;
    }
    JS.extend(Rect, ValueType);
    require("../platform/CCClass").fastDefine("cc.Rect", Rect, {
      x: 0,
      y: 0,
      width: 0,
      height: 0
    });
    Rect.fromMinMax = function(v1, v2) {
      var min_x = Math.min(v1.x, v2.x);
      var min_y = Math.min(v1.y, v2.y);
      var max_x = Math.max(v1.x, v2.x);
      var max_y = Math.max(v1.y, v2.y);
      return new Rect(min_x, min_y, max_x - min_x, max_y - min_y);
    };
    Rect.contain = function _Contain(a, b) {
      if (a.x < b.x && a.x + a.width > b.x + b.width && a.y < b.y && a.y + a.height > b.y + b.height) return 1;
      if (b.x < a.x && b.x + b.width > a.x + a.width && b.y < a.y && b.y + b.height > a.y + a.height) return -1;
      return 0;
    };
    var proto = Rect.prototype;
    proto.clone = function() {
      return new Rect(this.x, this.y, this.width, this.height);
    };
    proto.equals = function(other) {
      return other && this.x === other.x && this.y === other.y && this.width === other.width && this.height === other.height;
    };
    proto.lerp = function(to, ratio, out) {
      out = out || new Rect();
      var x = this.x;
      var y = this.y;
      var width = this.width;
      var height = this.height;
      out.x = x + (to.x - x) * ratio;
      out.y = y + (to.y - y) * ratio;
      out.width = width + (to.width - width) * ratio;
      out.height = height + (to.height - height) * ratio;
      return out;
    };
    proto.toString = function() {
      return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.width.toFixed(2) + ", " + this.height.toFixed(2) + ")";
    };
    JS.getset(proto, "xMin", (function() {
      return this.x;
    }), (function(value) {
      this.width += this.x - value;
      this.x = value;
    }));
    JS.getset(proto, "yMin", (function() {
      return this.y;
    }), (function(value) {
      this.height += this.y - value;
      this.y = value;
    }));
    JS.getset(proto, "xMax", (function() {
      return this.x + this.width;
    }), (function(value) {
      this.width = value - this.x;
    }));
    JS.getset(proto, "yMax", (function() {
      return this.y + this.height;
    }), (function(value) {
      this.height = value - this.y;
    }));
    JS.getset(proto, "center", (function() {
      return new cc.Vec2(this.x + .5 * this.width, this.y + .5 * this.height);
    }), (function(value) {
      this.x = value.x - .5 * this.width;
      this.y = value.y - .5 * this.height;
    }));
    JS.getset(proto, "origin", (function() {
      return new cc.Vec2(this.x, this.y);
    }), (function(value) {
      this.x = value.x;
      this.y = value.y;
    }));
    JS.getset(proto, "size", (function() {
      return new cc.Size(this.width, this.height);
    }), (function(value) {
      this.width = value.width;
      this.height = value.height;
    }));
    proto.intersects = function(rect) {
      return cc.rectIntersectsRect(this, rect);
    };
    proto.contains = function(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(rect) {
      return this.x <= rect.x && this.x + this.width >= rect.x + rect.width && this.y <= rect.y && this.y + this.height >= rect.y + rect.height;
    };
    cc.Rect = Rect;
    cc.rect = function rect(x, y, w, h) {
      return new Rect(x, y, w, h);
    };
    cc.rectEqualToRect = function(rect1, rect2) {
      return rect1 && rect2 && rect1.x === rect2.x && rect1.y === rect2.y && rect1.width === rect2.width && rect1.height === rect2.height;
    };
    cc._rectEqualToZero = function(rect) {
      return rect && 0 === rect.x && 0 === rect.y && 0 === rect.width && 0 === rect.height;
    };
    cc.rectContainsRect = function(rect1, rect2) {
      if (!rect1 || !rect2) return false;
      return !(rect1.x >= rect2.x || rect1.y >= rect2.y || rect1.x + rect1.width <= rect2.x + rect2.width || rect1.y + rect1.height <= rect2.y + rect2.height);
    };
    cc.rectGetMaxX = function(rect) {
      return rect.x + rect.width;
    };
    cc.rectGetMidX = function(rect) {
      return rect.x + rect.width / 2;
    };
    cc.rectGetMinX = function(rect) {
      return rect.x;
    };
    cc.rectGetMaxY = function(rect) {
      return rect.y + rect.height;
    };
    cc.rectGetMidY = function(rect) {
      return rect.y + rect.height / 2;
    };
    cc.rectGetMinY = function(rect) {
      return rect.y;
    };
    cc.rectContainsPoint = function(rect, point) {
      return point.x >= cc.rectGetMinX(rect) && point.x <= cc.rectGetMaxX(rect) && point.y >= cc.rectGetMinY(rect) && point.y <= cc.rectGetMaxY(rect);
    };
    cc.rectIntersectsRect = function(ra, rb) {
      var maxax = ra.x + ra.width, maxay = ra.y + ra.height, maxbx = rb.x + rb.width, maxby = rb.y + rb.height;
      return !(maxax < rb.x || maxbx < ra.x || maxay < rb.y || maxby < ra.y);
    };
    cc.rectOverlapsRect = function(rectA, rectB) {
      return !(rectA.x + rectA.width < rectB.x || rectB.x + rectB.width < rectA.x || rectA.y + rectA.height < rectB.y || rectB.y + rectB.height < rectA.y);
    };
    cc.rectUnion = function(rectA, rectB) {
      var rect = cc.rect(0, 0, 0, 0);
      rect.x = Math.min(rectA.x, rectB.x);
      rect.y = Math.min(rectA.y, rectB.y);
      rect.width = Math.max(rectA.x + rectA.width, rectB.x + rectB.width) - rect.x;
      rect.height = Math.max(rectA.y + rectA.height, rectB.y + rectB.height) - rect.y;
      return rect;
    };
    cc.rectIntersection = function(rectA, rectB) {
      var intersection = cc.rect(Math.max(cc.rectGetMinX(rectA), cc.rectGetMinX(rectB)), Math.max(cc.rectGetMinY(rectA), cc.rectGetMinY(rectB)), 0, 0);
      intersection.width = Math.min(cc.rectGetMaxX(rectA), cc.rectGetMaxX(rectB)) - cc.rectGetMinX(intersection);
      intersection.height = Math.min(cc.rectGetMaxY(rectA), cc.rectGetMaxY(rectB)) - cc.rectGetMinY(intersection);
      return intersection;
    };
    module.exports = cc.Rect;
  }), {
    "../platform/CCClass": 175,
    "../platform/js": 196,
    "./CCValueType": 236
  } ],
  233: [ (function(require, module, exports) {
    var ValueType = require("./CCValueType");
    var JS = require("../platform/js");
    function Size(width, height) {
      if (width && "object" === typeof width) {
        height = width.height;
        width = width.width;
      }
      this.width = width || 0;
      this.height = height || 0;
    }
    JS.extend(Size, ValueType);
    require("../platform/CCClass").fastDefine("cc.Size", Size, {
      width: 0,
      height: 0
    });
    JS.get(Size, "ZERO", (function() {
      return new Size(0, 0);
    }));
    var proto = Size.prototype;
    proto.clone = function() {
      return new Size(this.width, this.height);
    };
    proto.equals = function(other) {
      return other && this.width === other.width && this.height === other.height;
    };
    proto.lerp = function(to, ratio, out) {
      out = out || new Size();
      var width = this.width;
      var height = this.height;
      out.width = width + (to.width - width) * ratio;
      out.height = height + (to.height - height) * ratio;
      return out;
    };
    proto.toString = function() {
      return "(" + this.width.toFixed(2) + ", " + this.height.toFixed(2) + ")";
    };
    cc.size = function(w, h) {
      return new Size(w, h);
    };
    cc.sizeEqualToSize = function(size1, size2) {
      return size1 && size2 && size1.width === size2.width && size1.height === size2.height;
    };
    cc.Size = module.exports = Size;
  }), {
    "../platform/CCClass": 175,
    "../platform/js": 196,
    "./CCValueType": 236
  } ],
  234: [ (function(require, module, exports) {
    cc.Acceleration = function(x, y, z, timestamp) {
      this.x = x || 0;
      this.y = y || 0;
      this.z = z || 0;
      this.timestamp = timestamp || 0;
    };
    cc.BlendFunc = function(src1, dst1) {
      this.src = src1;
      this.dst = dst1;
    };
    var BlendFactor = cc.Enum({
      ONE: 1,
      ZERO: 0,
      SRC_ALPHA: 770,
      SRC_COLOR: 768,
      DST_ALPHA: 772,
      DST_COLOR: 774,
      ONE_MINUS_SRC_ALPHA: 771,
      ONE_MINUS_SRC_COLOR: 769,
      ONE_MINUS_DST_ALPHA: 773,
      ONE_MINUS_DST_COLOR: 775
    });
    cc.BlendFunc._disable = function() {
      return new cc.BlendFunc(BlendFactor.ONE, BlendFactor.ZERO);
    };
    cc.BlendFunc._alphaPremultiplied = function() {
      return new cc.BlendFunc(BlendFactor.ONE, BlendFactor.ONE_MINUS_SRC_ALPHA);
    };
    cc.BlendFunc._alphaNonPremultiplied = function() {
      return new cc.BlendFunc(BlendFactor.SRC_ALPHA, BlendFactor.ONE_MINUS_SRC_ALPHA);
    };
    cc.BlendFunc._additive = function() {
      return new cc.BlendFunc(BlendFactor.SRC_ALPHA, BlendFactor.ONE);
    };
    cc.BlendFunc.BlendFactor = BlendFactor;
    cc.BlendFunc.DISABLE;
    cc.js.get(cc.BlendFunc, "DISABLE", cc.BlendFunc._disable);
    cc.BlendFunc.ALPHA_PREMULTIPLIED;
    cc.js.get(cc.BlendFunc, "ALPHA_PREMULTIPLIED", cc.BlendFunc._alphaPremultiplied);
    cc.BlendFunc.ALPHA_NON_PREMULTIPLIED;
    cc.js.get(cc.BlendFunc, "ALPHA_NON_PREMULTIPLIED", cc.BlendFunc._alphaNonPremultiplied);
    cc.BlendFunc.ADDITIVE;
    cc.js.get(cc.BlendFunc, "ADDITIVE", cc.BlendFunc._additive);
    cc.blendFuncDisable = cc.BlendFunc._disable;
    cc.TextAlignment = cc.Enum({
      LEFT: 0,
      CENTER: 1,
      RIGHT: 2
    });
    cc.VerticalTextAlignment = cc.Enum({
      TOP: 0,
      CENTER: 1,
      BOTTOM: 2
    });
  }), {} ],
  235: [ (function(require, module, exports) {
    cc.WebGLColor = function(r, g, b, a, arrayBuffer, offset) {
      this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.WebGLColor.BYTES_PER_ELEMENT);
      this._offset = offset || 0;
      var locArrayBuffer = this._arrayBuffer, locOffset = this._offset;
      this._view = new Uint8Array(locArrayBuffer, locOffset, 4);
      this._view[0] = r || 0;
      this._view[1] = g || 0;
      this._view[2] = b || 0;
      if ("number" === typeof a) this._view[3] = a; else {
        this._view[3] = 255;
        this.a_undefined = true;
      }
    };
    cc.WebGLColor.BYTES_PER_ELEMENT = 4;
    var _p = cc.WebGLColor.prototype;
    _p._getR = function() {
      return this._view[0];
    };
    _p._setR = function(value) {
      this._view[0] = value < 0 ? 0 : value;
    };
    _p._getG = function() {
      return this._view[1];
    };
    _p._setG = function(value) {
      this._view[1] = value < 0 ? 0 : value;
    };
    _p._getB = function() {
      return this._view[2];
    };
    _p._setB = function(value) {
      this._view[2] = value < 0 ? 0 : value;
    };
    _p._getA = function() {
      return this._view[3];
    };
    _p._setA = function(value) {
      this._view[3] = value < 0 ? 0 : value;
    };
    _p.r;
    cc.js.getset(_p, "r", _p._getR, _p._setR);
    _p.g;
    cc.js.getset(_p, "g", _p._getG, _p._setG);
    _p.b;
    cc.js.getset(_p, "b", _p._getB, _p._setB);
    _p.a;
    cc.js.getset(_p, "a", _p._getA, _p._setA);
    cc.Vertex2F = function(x, y, arrayBuffer, offset) {
      this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Vertex2F.BYTES_PER_ELEMENT);
      this._offset = offset || 0;
      this._view = new Float32Array(this._arrayBuffer, this._offset, 2);
      this._view[0] = x || 0;
      this._view[1] = y || 0;
    };
    cc.Vertex2F.BYTES_PER_ELEMENT = 8;
    var _p = cc.Vertex2F.prototype;
    _p._getX = function() {
      return this._view[0];
    };
    _p._setX = function(xValue) {
      this._view[0] = xValue;
    };
    _p._getY = function() {
      return this._view[1];
    };
    _p._setY = function(yValue) {
      this._view[1] = yValue;
    };
    cc.js.getset(_p, "x", _p._getX, _p._setX);
    cc.js.getset(_p, "y", _p._getY, _p._setY);
    cc.Vertex3F = function(x, y, z, arrayBuffer, offset) {
      this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Vertex3F.BYTES_PER_ELEMENT);
      this._offset = offset || 0;
      var locArrayBuffer = this._arrayBuffer, locOffset = this._offset;
      this._view = new Float32Array(locArrayBuffer, locOffset, 3);
      this._view[0] = x || 0;
      this._view[1] = y || 0;
      this._view[2] = z || 0;
    };
    cc.Vertex3F.BYTES_PER_ELEMENT = 12;
    _p = cc.Vertex3F.prototype;
    _p._getX = function() {
      return this._view[0];
    };
    _p._setX = function(xValue) {
      this._view[0] = xValue;
    };
    _p._getY = function() {
      return this._view[1];
    };
    _p._setY = function(yValue) {
      this._view[1] = yValue;
    };
    _p._getZ = function() {
      return this._view[2];
    };
    _p._setZ = function(zValue) {
      this._view[2] = zValue;
    };
    cc.js.getset(_p, "x", _p._getX, _p._setX);
    cc.js.getset(_p, "y", _p._getY, _p._setY);
    cc.js.getset(_p, "z", _p._getZ, _p._setZ);
    cc.Tex2F = function(u, v, arrayBuffer, offset) {
      this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Tex2F.BYTES_PER_ELEMENT);
      this._offset = offset || 0;
      this._view = new Float32Array(this._arrayBuffer, this._offset, 2);
      this._view[0] = u || 0;
      this._view[1] = v || 0;
    };
    cc.Tex2F.BYTES_PER_ELEMENT = 8;
    _p = cc.Tex2F.prototype;
    _p._getU = function() {
      return this._view[0];
    };
    _p._setU = function(xValue) {
      this._view[0] = xValue;
    };
    _p._getV = function() {
      return this._view[1];
    };
    _p._setV = function(yValue) {
      this._view[1] = yValue;
    };
    cc.js.getset(_p, "u", _p._getU, _p._setU);
    cc.js.getset(_p, "v", _p._getV, _p._setV);
    cc.Quad2 = function(tl, tr, bl, br, arrayBuffer, offset) {
      this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Quad2.BYTES_PER_ELEMENT);
      this._offset = offset || 0;
      var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.Vertex2F.BYTES_PER_ELEMENT;
      this._tl = tl ? new cc.Vertex2F(tl.x, tl.y, locArrayBuffer, locOffset) : new cc.Vertex2F(0, 0, locArrayBuffer, locOffset);
      locOffset += locElementLen;
      this._tr = tr ? new cc.Vertex2F(tr.x, tr.y, locArrayBuffer, locOffset) : new cc.Vertex2F(0, 0, locArrayBuffer, locOffset);
      locOffset += locElementLen;
      this._bl = bl ? new cc.Vertex2F(bl.x, bl.y, locArrayBuffer, locOffset) : new cc.Vertex2F(0, 0, locArrayBuffer, locOffset);
      locOffset += locElementLen;
      this._br = br ? new cc.Vertex2F(br.x, br.y, locArrayBuffer, locOffset) : new cc.Vertex2F(0, 0, locArrayBuffer, locOffset);
    };
    cc.Quad2.BYTES_PER_ELEMENT = 32;
    _p = cc.Quad2.prototype;
    _p._getTL = function() {
      return this._tl;
    };
    _p._setTL = function(tlValue) {
      this._tl._view[0] = tlValue.x;
      this._tl._view[1] = tlValue.y;
    };
    _p._getTR = function() {
      return this._tr;
    };
    _p._setTR = function(trValue) {
      this._tr._view[0] = trValue.x;
      this._tr._view[1] = trValue.y;
    };
    _p._getBL = function() {
      return this._bl;
    };
    _p._setBL = function(blValue) {
      this._bl._view[0] = blValue.x;
      this._bl._view[1] = blValue.y;
    };
    _p._getBR = function() {
      return this._br;
    };
    _p._setBR = function(brValue) {
      this._br._view[0] = brValue.x;
      this._br._view[1] = brValue.y;
    };
    cc.js.getset(_p, "tl", _p._getTL, _p._setTL);
    cc.js.getset(_p, "tr", _p._getTR, _p._setTR);
    cc.js.getset(_p, "bl", _p._getBL, _p._setBL);
    cc.js.getset(_p, "br", _p._getBR, _p._setBR);
    cc.Quad3 = function(bl1, br1, tl1, tr1, arrayBuffer, offset) {
      this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Quad3.BYTES_PER_ELEMENT);
      this._offset = offset || 0;
      var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.Vertex3F.BYTES_PER_ELEMENT;
      this.bl = bl ? new cc.Vertex3F(bl.x, bl.y, bl.z, locArrayBuffer, locOffset) : new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset);
      locOffset += locElementLen;
      this.br = br ? new cc.Vertex3F(br.x, br.y, br.z, locArrayBuffer, locOffset) : new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset);
      locOffset += locElementLen;
      this.tl = tl ? new cc.Vertex3F(tl.x, tl.y, tl.z, locArrayBuffer, locOffset) : new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset);
      locOffset += locElementLen;
      this.tr = tr ? new cc.Vertex3F(tr.x, tr.y, tr.z, locArrayBuffer, locOffset) : new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset);
    };
    cc.Quad3.BYTES_PER_ELEMENT = 48;
    cc.V3F_C4B_T2F = function(vertices, colors, texCoords, arrayBuffer, offset) {
      this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V3F_C4B_T2F.BYTES_PER_ELEMENT);
      this._offset = offset || 0;
      var locArrayBuffer = this._arrayBuffer, locOffset = this._offset;
      this._vertices = vertices ? new cc.Vertex3F(vertices.x, vertices.y, vertices.z, locArrayBuffer, locOffset) : new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset);
      locOffset += cc.Vertex3F.BYTES_PER_ELEMENT;
      this._colors = colors ? new cc.WebGLColor(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset) : new cc.WebGLColor(0, 0, 0, 0, locArrayBuffer, locOffset);
      locOffset += cc.WebGLColor.BYTES_PER_ELEMENT;
      this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset) : new cc.Tex2F(0, 0, locArrayBuffer, locOffset);
    };
    cc.V3F_C4B_T2F.BYTES_PER_ELEMENT = 24;
    _p = cc.V3F_C4B_T2F.prototype;
    _p._getVertices = function() {
      return this._vertices;
    };
    _p._setVertices = function(verticesValue) {
      var locVertices = this._vertices;
      locVertices._view[0] = verticesValue.x;
      locVertices._view[1] = verticesValue.y;
      locVertices._view[2] = verticesValue.z;
    };
    _p._getColor = function() {
      return this._colors;
    };
    _p._setColor = function(colorValue) {
      var locColors = this._colors;
      locColors._view[0] = colorValue.r;
      locColors._view[1] = colorValue.g;
      locColors._view[2] = colorValue.b;
      locColors._view[3] = colorValue.a;
    };
    _p._getTexCoords = function() {
      return this._texCoords;
    };
    _p._setTexCoords = function(texValue) {
      this._texCoords._view[0] = texValue.u;
      this._texCoords._view[1] = texValue.v;
    };
    cc.js.getset(_p, "vertices", _p._getVertices, _p._setVertices);
    cc.js.getset(_p, "colors", _p._getColor, _p._setColor);
    cc.js.getset(_p, "texCoords", _p._getTexCoords, _p._setTexCoords);
    cc.V3F_C4B_T2F_Quad = function(tl, bl, tr, br, arrayBuffer, offset) {
      this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT);
      this._offset = offset || 0;
      var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.V3F_C4B_T2F.BYTES_PER_ELEMENT;
      this._tl = tl ? new cc.V3F_C4B_T2F(tl.vertices, tl.colors, tl.texCoords, locArrayBuffer, locOffset) : new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
      locOffset += locElementLen;
      this._bl = bl ? new cc.V3F_C4B_T2F(bl.vertices, bl.colors, bl.texCoords, locArrayBuffer, locOffset) : new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
      locOffset += locElementLen;
      this._tr = tr ? new cc.V3F_C4B_T2F(tr.vertices, tr.colors, tr.texCoords, locArrayBuffer, locOffset) : new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
      locOffset += locElementLen;
      this._br = br ? new cc.V3F_C4B_T2F(br.vertices, br.colors, br.texCoords, locArrayBuffer, locOffset) : new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
    };
    cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT = 96;
    _p = cc.V3F_C4B_T2F_Quad.prototype;
    _p._getTL = function() {
      return this._tl;
    };
    _p._setTL = function(tlValue) {
      var locTl = this._tl;
      locTl.vertices = tlValue.vertices;
      locTl.colors = tlValue.colors;
      locTl.texCoords = tlValue.texCoords;
    };
    _p._getBL = function() {
      return this._bl;
    };
    _p._setBL = function(blValue) {
      var locBl = this._bl;
      locBl.vertices = blValue.vertices;
      locBl.colors = blValue.colors;
      locBl.texCoords = blValue.texCoords;
    };
    _p._getTR = function() {
      return this._tr;
    };
    _p._setTR = function(trValue) {
      var locTr = this._tr;
      locTr.vertices = trValue.vertices;
      locTr.colors = trValue.colors;
      locTr.texCoords = trValue.texCoords;
    };
    _p._getBR = function() {
      return this._br;
    };
    _p._setBR = function(brValue) {
      var locBr = this._br;
      locBr.vertices = brValue.vertices;
      locBr.colors = brValue.colors;
      locBr.texCoords = brValue.texCoords;
    };
    _p._getArrayBuffer = function() {
      return this._arrayBuffer;
    };
    cc.js.getset(_p, "tl", _p._getTL, _p._setTL);
    cc.js.getset(_p, "tr", _p._getTR, _p._setTR);
    cc.js.getset(_p, "bl", _p._getBL, _p._setBL);
    cc.js.getset(_p, "br", _p._getBR, _p._setBR);
    cc.js.get(_p, "arrayBuffer", _p._getArrayBuffer);
    cc.V3F_C4B_T2F_QuadZero = function() {
      return new cc.V3F_C4B_T2F_Quad();
    };
    cc.V3F_C4B_T2F_QuadCopy = function(sourceQuad) {
      if (!sourceQuad) return cc.V3F_C4B_T2F_QuadZero();
      var srcTL = sourceQuad.tl, srcBL = sourceQuad.bl, srcTR = sourceQuad.tr, srcBR = sourceQuad.br;
      return {
        tl: {
          vertices: {
            x: srcTL.vertices.x,
            y: srcTL.vertices.y,
            z: srcTL.vertices.z
          },
          colors: {
            r: srcTL.colors.r,
            g: srcTL.colors.g,
            b: srcTL.colors.b,
            a: srcTL.colors.a
          },
          texCoords: {
            u: srcTL.texCoords.u,
            v: srcTL.texCoords.v
          }
        },
        bl: {
          vertices: {
            x: srcBL.vertices.x,
            y: srcBL.vertices.y,
            z: srcBL.vertices.z
          },
          colors: {
            r: srcBL.colors.r,
            g: srcBL.colors.g,
            b: srcBL.colors.b,
            a: srcBL.colors.a
          },
          texCoords: {
            u: srcBL.texCoords.u,
            v: srcBL.texCoords.v
          }
        },
        tr: {
          vertices: {
            x: srcTR.vertices.x,
            y: srcTR.vertices.y,
            z: srcTR.vertices.z
          },
          colors: {
            r: srcTR.colors.r,
            g: srcTR.colors.g,
            b: srcTR.colors.b,
            a: srcTR.colors.a
          },
          texCoords: {
            u: srcTR.texCoords.u,
            v: srcTR.texCoords.v
          }
        },
        br: {
          vertices: {
            x: srcBR.vertices.x,
            y: srcBR.vertices.y,
            z: srcBR.vertices.z
          },
          colors: {
            r: srcBR.colors.r,
            g: srcBR.colors.g,
            b: srcBR.colors.b,
            a: srcBR.colors.a
          },
          texCoords: {
            u: srcBR.texCoords.u,
            v: srcBR.texCoords.v
          }
        }
      };
    };
    cc.V3F_C4B_T2F_QuadsCopy = function(sourceQuads) {
      if (!sourceQuads) return [];
      var retArr = [];
      for (var i = 0; i < sourceQuads.length; i++) retArr.push(cc.V3F_C4B_T2F_QuadCopy(sourceQuads[i]));
      return retArr;
    };
    cc.V2F_C4B_T2F = function(vertices, colors, texCoords, arrayBuffer, offset) {
      this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V2F_C4B_T2F.BYTES_PER_ELEMENT);
      this._offset = offset || 0;
      var locArrayBuffer = this._arrayBuffer, locOffset = this._offset;
      this._vertices = vertices ? new cc.Vertex2F(vertices.x, vertices.y, locArrayBuffer, locOffset) : new cc.Vertex2F(0, 0, locArrayBuffer, locOffset);
      locOffset += cc.Vertex2F.BYTES_PER_ELEMENT;
      this._colors = colors ? new cc.WebGLColor(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset) : new cc.WebGLColor(0, 0, 0, 0, locArrayBuffer, locOffset);
      locOffset += cc.WebGLColor.BYTES_PER_ELEMENT;
      this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset) : new cc.Tex2F(0, 0, locArrayBuffer, locOffset);
    };
    cc.V2F_C4B_T2F.BYTES_PER_ELEMENT = 20;
    _p = cc.V2F_C4B_T2F.prototype;
    _p._getVertices = function() {
      return this._vertices;
    };
    _p._setVertices = function(verticesValue) {
      this._vertices._view[0] = verticesValue.x;
      this._vertices._view[1] = verticesValue.y;
    };
    _p._getColor = function() {
      return this._colors;
    };
    _p._setColor = function(colorValue) {
      var locColors = this._colors;
      locColors._view[0] = colorValue.r;
      locColors._view[1] = colorValue.g;
      locColors._view[2] = colorValue.b;
      locColors._view[3] = colorValue.a;
    };
    _p._getTexCoords = function() {
      return this._texCoords;
    };
    _p._setTexCoords = function(texValue) {
      this._texCoords._view[0] = texValue.u;
      this._texCoords._view[1] = texValue.v;
    };
    cc.js.getset(_p, "vertices", _p._getVertices, _p._setVertices);
    cc.js.getset(_p, "colors", _p._getColor, _p._setColor);
    cc.js.getset(_p, "texCoords", _p._getTexCoords, _p._setTexCoords);
    cc.V2F_C4B_T2F_Triangle = function(a, b, c, arrayBuffer, offset) {
      this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT);
      this._offset = offset || 0;
      var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT;
      this._a = a ? new cc.V2F_C4B_T2F(a.vertices, a.colors, a.texCoords, locArrayBuffer, locOffset) : new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
      locOffset += locElementLen;
      this._b = b ? new cc.V2F_C4B_T2F(b.vertices, b.colors, b.texCoords, locArrayBuffer, locOffset) : new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
      locOffset += locElementLen;
      this._c = c ? new cc.V2F_C4B_T2F(c.vertices, c.colors, c.texCoords, locArrayBuffer, locOffset) : new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
    };
    cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT = 60;
    _p = cc.V2F_C4B_T2F_Triangle.prototype;
    _p._getA = function() {
      return this._a;
    };
    _p._setA = function(aValue) {
      var locA = this._a;
      locA.vertices = aValue.vertices;
      locA.colors = aValue.colors;
      locA.texCoords = aValue.texCoords;
    };
    _p._getB = function() {
      return this._b;
    };
    _p._setB = function(bValue) {
      var locB = this._b;
      locB.vertices = bValue.vertices;
      locB.colors = bValue.colors;
      locB.texCoords = bValue.texCoords;
    };
    _p._getC = function() {
      return this._c;
    };
    _p._setC = function(cValue) {
      var locC = this._c;
      locC.vertices = cValue.vertices;
      locC.colors = cValue.colors;
      locC.texCoords = cValue.texCoords;
    };
    cc.js.getset(_p, "a", _p._getA, _p._setA);
    cc.js.getset(_p, "b", _p._getB, _p._setB);
    cc.js.getset(_p, "c", _p._getC, _p._setC);
  }), {} ],
  236: [ (function(require, module, exports) {
    var JS = require("../platform/js");
    function ValueType() {}
    JS.setClassName("cc.ValueType", ValueType);
    var proto = ValueType.prototype;
    false;
    proto.toString = function() {
      return "" + {};
    };
    cc.ValueType = ValueType;
    module.exports = ValueType;
  }), {
    "../platform/js": 196
  } ],
  237: [ (function(require, module, exports) {
    var ValueType = require("./CCValueType");
    var JS = require("../platform/js");
    var CCClass = require("../platform/CCClass");
    function Vec2(x, y) {
      if (x && "object" === typeof x) {
        y = x.y;
        x = x.x;
      }
      this.x = x || 0;
      this.y = y || 0;
    }
    JS.extend(Vec2, ValueType);
    CCClass.fastDefine("cc.Vec2", Vec2, {
      x: 0,
      y: 0
    });
    var proto = Vec2.prototype;
    proto.clone = function() {
      return new Vec2(this.x, this.y);
    };
    proto.set = function(newValue) {
      this.x = newValue.x;
      this.y = newValue.y;
      return this;
    };
    proto.equals = function(other) {
      return other && this.x === other.x && this.y === other.y;
    };
    proto.toString = function() {
      return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ")";
    };
    proto.lerp = function(to, ratio, out) {
      out = out || new Vec2();
      var x = this.x;
      var y = this.y;
      out.x = x + (to.x - x) * ratio;
      out.y = y + (to.y - y) * ratio;
      return out;
    };
    proto.addSelf = function(vector) {
      this.x += vector.x;
      this.y += vector.y;
      return this;
    };
    proto.add = function(vector, out) {
      out = out || new Vec2();
      out.x = this.x + vector.x;
      out.y = this.y + vector.y;
      return out;
    };
    proto.subSelf = function(vector) {
      this.x -= vector.x;
      this.y -= vector.y;
      return this;
    };
    proto.sub = function(vector, out) {
      out = out || new Vec2();
      out.x = this.x - vector.x;
      out.y = this.y - vector.y;
      return out;
    };
    proto.mulSelf = function(num) {
      this.x *= num;
      this.y *= num;
      return this;
    };
    proto.mul = function(num, out) {
      out = out || new Vec2();
      out.x = this.x * num;
      out.y = this.y * num;
      return out;
    };
    proto.scaleSelf = function(vector) {
      this.x *= vector.x;
      this.y *= vector.y;
      return this;
    };
    proto.scale = function(vector, out) {
      out = out || new Vec2();
      out.x = this.x * vector.x;
      out.y = this.y * vector.y;
      return out;
    };
    proto.divSelf = function(num) {
      this.x /= num;
      this.y /= num;
      return this;
    };
    proto.div = function(num, out) {
      out = out || new Vec2();
      out.x = this.x / num;
      out.y = this.y / num;
      return out;
    };
    proto.negSelf = function() {
      this.x = -this.x;
      this.y = -this.y;
      return this;
    };
    proto.neg = function(out) {
      out = out || new Vec2();
      out.x = -this.x;
      out.y = -this.y;
      return out;
    };
    proto.dot = function(vector) {
      return this.x * vector.x + this.y * vector.y;
    };
    proto.cross = function(vector) {
      return this.y * vector.x - this.x * vector.y;
    };
    proto.mag = function() {
      return Math.sqrt(this.x * this.x + this.y * this.y);
    };
    proto.magSqr = function() {
      return this.x * this.x + this.y * this.y;
    };
    proto.normalizeSelf = function() {
      var magSqr = this.x * this.x + this.y * this.y;
      if (1 === magSqr) return this;
      if (0 === magSqr) {
        console.warn("Can't normalize zero vector");
        return this;
      }
      var invsqrt = 1 / Math.sqrt(magSqr);
      this.x *= invsqrt;
      this.y *= invsqrt;
      return this;
    };
    proto.normalize = function(out) {
      out = out || new Vec2();
      out.x = this.x;
      out.y = this.y;
      out.normalizeSelf();
      return out;
    };
    proto.angle = function(vector) {
      var magSqr1 = this.magSqr();
      var magSqr2 = vector.magSqr();
      if (0 === magSqr1 || 0 === magSqr2) {
        console.warn("Can't get angle between zero vector");
        return 0;
      }
      var dot = this.dot(vector);
      var theta = dot / Math.sqrt(magSqr1 * magSqr2);
      theta = cc.clampf(theta, -1, 1);
      return Math.acos(theta);
    };
    proto.signAngle = function(vector) {
      return Math.atan2(this.y, this.x) - Math.atan2(vector.y, vector.x);
    };
    proto.rotate = function(radians, out) {
      out = out || new Vec2();
      out.x = this.x;
      out.y = this.y;
      return out.rotateSelf(radians);
    };
    proto.rotateSelf = function(radians) {
      var sin = Math.sin(radians);
      var cos = Math.cos(radians);
      var x = this.x;
      this.x = cos * x - sin * this.y;
      this.y = sin * x + cos * this.y;
      return this;
    };
    JS.get(Vec2, "ONE", (function() {
      return new Vec2(1, 1);
    }));
    JS.get(Vec2, "ZERO", (function() {
      return new Vec2(0, 0);
    }));
    JS.get(Vec2, "UP", (function() {
      return new Vec2(0, 1);
    }));
    JS.get(Vec2, "RIGHT", (function() {
      return new Vec2(1, 0);
    }));
    cc.Vec2 = Vec2;
    cc.v2 = function v2(x, y) {
      return new Vec2(x, y);
    };
    cc.p = cc.v2;
    cc.pointEqualToPoint = function(point1, point2) {
      return point1 && point2 && point1.x === point2.x && point1.y === point2.y;
    };
    module.exports = cc.Vec2;
  }), {
    "../platform/CCClass": 175,
    "../platform/js": 196,
    "./CCValueType": 236
  } ],
  238: [ (function(require, module, exports) {
    require("./CCValueType");
    require("./CCVec2");
    require("./CCPointExtension");
    require("./CCSize");
    require("./CCRect");
    require("./CCColor");
    require("./CCTypes");
    require("./CCAffineTransform");
    require("./CCTypesWebGL");
  }), {
    "./CCAffineTransform": 229,
    "./CCColor": 230,
    "./CCPointExtension": 231,
    "./CCRect": 232,
    "./CCSize": 233,
    "./CCTypes": 234,
    "./CCTypesWebGL": 235,
    "./CCValueType": 236,
    "./CCVec2": 237
  } ],
  239: [ (function(require, module, exports) {
    var Utils = require("../platform/utils");
    var sys = require("../platform/CCSys");
    var eventManager = require("../event-manager");
    _ccsg.VideoPlayer = _ccsg.Node.extend({
      ctor: function() {
        _ccsg.Node.prototype.ctor.call(this);
        this._EventList = {};
      },
      _createRenderCmd: function() {
        return new _ccsg.VideoPlayer.RenderCmd(this);
      },
      setURL: function(url) {
        this._renderCmd.updateURL(url);
      },
      getURL: function() {
        return this._renderCmd._url;
      },
      play: function() {
        this._renderCmd.play();
      },
      pause: function() {
        this._renderCmd.pause();
      },
      _resume: function() {
        this._renderCmd.play();
      },
      stop: function() {
        this._renderCmd.stop();
      },
      seekTo: function(time) {
        this._renderCmd.seekTo(time);
      },
      isPlaying: function() {
        return this._renderCmd.isPlaying();
      },
      duration: function() {
        return this._renderCmd.duration();
      },
      currentTime: function() {
        return this._renderCmd.currentTime();
      },
      createDomElementIfNeeded: function() {
        this._renderCmd._video || this._renderCmd.createDom();
      },
      setKeepAspectRatioEnabled: function() {
        cc.logID(7700);
      },
      isKeepAspectRatioEnabled: function() {
        return true;
      },
      setFullScreenEnabled: function(enable) {
        var video = this._renderCmd._video;
        if (!video) return;
        enable ? cc.screen.requestFullScreen(video) : cc.screen.exitFullScreen(video);
      },
      isFullScreenEnabled: function() {
        cc.logID(7701);
      },
      setEventListener: function(event, callback) {
        this._EventList[event] = callback;
      },
      removeEventListener: function(event) {
        this._EventList[event] = null;
      },
      _dispatchEvent: function(event) {
        var callback = this._EventList[event];
        callback && callback.call(this, this, this._renderCmd._video.src);
      },
      onPlayEvent: function() {
        var callback = this._EventList[_ccsg.VideoPlayer.EventType.PLAYING];
        callback.call(this, this, this._renderCmd._video.src);
      },
      setContentSize: function(width, height) {
        if (void 0 !== width.width && void 0 !== width.height) {
          height = width.height;
          width = width.width;
        }
        _ccsg.Node.prototype.setContentSize.call(this, width, height);
        this._renderCmd.updateSize(width, height);
      },
      onEnter: function() {
        _ccsg.Node.prototype.onEnter.call(this);
        var list = _ccsg.VideoPlayer.elements;
        -1 === list.indexOf(this) && list.push(this);
      },
      cleanup: function() {
        this._super();
        this._renderCmd.removeDom();
      },
      onExit: function() {
        _ccsg.Node.prototype.onExit.call(this);
        var list = _ccsg.VideoPlayer.elements;
        var index = list.indexOf(this);
        -1 !== index && list.splice(index, 1);
      },
      setVisible: function(visible) {
        _ccsg.Node.prototype.setVisible.call(this, visible);
        this._renderCmd.updateVisibility();
      }
    });
    _ccsg.VideoPlayer.elements = [];
    _ccsg.VideoPlayer.pauseElements = [];
    eventManager.addCustomListener(cc.game.EVENT_HIDE, (function() {
      var list = _ccsg.VideoPlayer.elements;
      for (var node, i = 0; i < list.length; i++) {
        node = list[i];
        if (list[i]._playing) {
          node.pause();
          _ccsg.VideoPlayer.pauseElements.push(node);
        }
      }
    }));
    cc.game.on(cc.game.EVENT_SHOW, (function() {
      var list = _ccsg.VideoPlayer.pauseElements;
      var node = list.pop();
      while (node) {
        node.play();
        node = list.pop();
      }
    }));
    _ccsg.VideoPlayer.EventType = {
      PLAYING: 0,
      PAUSED: 1,
      STOPPED: 2,
      COMPLETED: 3,
      META_LOADED: 4,
      CLICKED: 5,
      READY_TO_PLAY: 6
    };
    (function(video) {
      video._polyfill = {
        devicePixelRatio: false,
        event: "canplay",
        canPlayType: []
      };
      (function() {
        var dom = document.createElement("video");
        if (sys.platform !== sys.WECHAT_GAME) {
          if (dom.canPlayType("video/ogg")) {
            video._polyfill.canPlayType.push(".ogg");
            video._polyfill.canPlayType.push(".ogv");
          }
          dom.canPlayType("video/mp4") && video._polyfill.canPlayType.push(".mp4");
          dom.canPlayType("video/webm") && video._polyfill.canPlayType.push(".webm");
        }
      })();
      cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX && (video._polyfill.autoplayAfterOperation = true);
      cc.sys.OS_ANDROID !== cc.sys.os || cc.sys.browserType !== cc.sys.BROWSER_TYPE_SOUGOU && cc.sys.browserType !== cc.sys.BROWSER_TYPE_360 || (video._polyfill.zoomInvalid = true);
      var style = document.createElement("style");
      style.innerHTML = ".cocosVideo:-moz-full-screen{transform:matrix(1,0,0,1,0,0) !important;}.cocosVideo:full-screen{transform:matrix(1,0,0,1,0,0) !important;}.cocosVideo:-webkit-full-screen{transform:matrix(1,0,0,1,0,0) !important;}";
      document.head.appendChild(style);
    })(_ccsg.VideoPlayer);
    (function(polyfill) {
      _ccsg.VideoPlayer.RenderCmd = function(node) {
        this._rootCtor(node);
        this._video = null;
        this._url = "";
        this._played = false;
        this._playing = false;
        this._ignorePause = false;
      };
      var proto = _ccsg.VideoPlayer.RenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
      proto.constructor = _ccsg.VideoPlayer.RenderCmd;
      proto.transform = function(parentCmd, recursive) {
        this.originTransform(parentCmd, recursive);
        this.updateMatrix();
      };
      proto.updateMatrix = function() {
        if (!this._video) return;
        var node = this._node, scaleX = cc.view._scaleX, scaleY = cc.view._scaleY;
        var dpr = cc.view._devicePixelRatio;
        var t = this._worldTransform;
        scaleX /= dpr;
        scaleY /= dpr;
        var container = cc.game.container;
        var a = t.a * scaleX, b = t.b, c = t.c, d = t.d * scaleY;
        var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft);
        var offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom);
        var tx = t.tx * scaleX + offsetX, ty = t.ty * scaleY + offsetY;
        if (polyfill.zoomInvalid) {
          this.updateSize(node._contentSize.width * a, node._contentSize.height * d);
          a = 1;
          d = 1;
        }
        var matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")";
        this._video.style["transform"] = matrix;
        this._video.style["-webkit-transform"] = matrix;
        this._video.style["transform-origin"] = "0px 100% 0px";
        this._video.style["-webkit-transform-origin"] = "0px 100% 0px";
      };
      proto.updateURL = function(path) {
        cc.loader.md5Pipe && (path = cc.loader.md5Pipe.transformURL(path));
        var source, video, extname;
        var node = this._node;
        if (this._url == path) return;
        this._url = path;
        cc.loader.resPath && !/^http/.test(path) && (path = cc.path.join(cc.loader.resPath, path));
        this.removeDom();
        this.createDom();
        this.bindEvent();
        video = this._video;
        var cb = function() {
          if (true == this._loaded) return;
          this._loaded = true;
          node.setContentSize(node._contentSize.width, node._contentSize.height);
          video.currentTime = 0;
          node._dispatchEvent(_ccsg.VideoPlayer.EventType.READY_TO_PLAY);
          this.updateVisibility();
          this.updateMatrix();
        }.bind(this);
        video.oncanplay = cb;
        video.style["visibility"] = "hidden";
        this._loaded = false;
        this._played = false;
        this._playing = false;
        source = document.createElement("source");
        source.src = path;
        video.appendChild(source);
        extname = cc.path.extname(path);
        for (var i = 0; i < polyfill.canPlayType.length; i++) if (extname !== polyfill.canPlayType[i]) {
          source = document.createElement("source");
          source.src = path.replace(extname, polyfill.canPlayType[i]);
          video.appendChild(source);
        }
      };
      proto.bindEvent = function() {
        var node = this._node, video = this._video, self = this;
        video.onloadedmetadata = function() {
          node._dispatchEvent(_ccsg.VideoPlayer.EventType.META_LOADED);
        };
        video.addEventListener("ended", function() {
          if (self._video !== video) return;
          this._playing = false;
          node._dispatchEvent(_ccsg.VideoPlayer.EventType.COMPLETED);
        }.bind(this));
        video.addEventListener("play", (function() {
          if (self._video !== video) return;
          node._dispatchEvent(_ccsg.VideoPlayer.EventType.PLAYING);
        }));
        video.addEventListener("pause", (function() {
          if (self._ignorePause || self._video !== video) return;
          node._dispatchEvent(_ccsg.VideoPlayer.EventType.PAUSED);
        }));
        video.addEventListener("click", (function() {
          node._dispatchEvent(_ccsg.VideoPlayer.EventType.CLICKED);
        }));
      };
      proto.updateVisibility = function() {
        var node = this._node;
        if (!this._video) return;
        var video = this._video;
        if (node.visible) video.style.visibility = "visible"; else {
          video.style.visibility = "hidden";
          video.pause();
          this._playing = false;
        }
      };
      proto.createDom = function() {
        var video = document.createElement("video");
        video.style.position = "absolute";
        video.style.bottom = "0px";
        video.style.left = "0px";
        video.className = "cocosVideo";
        video.setAttribute("preload", true);
        video.setAttribute("webkit-playsinline", "");
        video.setAttribute("playsinline", "");
        this._video = video;
        cc.game.container.appendChild(video);
      };
      proto.removeDom = function() {
        var video = this._video;
        if (video) {
          var hasChild = Utils.contains(cc.game.container, video);
          hasChild && cc.game.container.removeChild(video);
        }
        this._video = null;
        this._url = "";
      };
      proto.updateSize = function(width, height) {
        var video = this._video;
        if (!video) return;
        video.style["width"] = width + "px";
        video.style["height"] = height + "px";
      };
      proto.play = function() {
        var video = this._video;
        if (!video || !this._node.isVisible()) return;
        this._played = true;
        if (this._playing) return;
        if (_ccsg.VideoPlayer._polyfill.autoplayAfterOperation) {
          var self = this;
          setTimeout((function() {
            video.play();
            self._playing = true;
          }), 20);
        } else {
          video.play();
          this._playing = true;
        }
      };
      proto.pause = function() {
        var video = this._video;
        if (!this._playing) return;
        this._playing = false;
        if (!video) return;
        video.pause();
      };
      proto.stop = function() {
        var video = this._video;
        if (!video || !this._node.isVisible()) return;
        this._ignorePause = true;
        video.pause();
        var node = this._node;
        setTimeout(function() {
          node._dispatchEvent(_ccsg.VideoPlayer.EventType.STOPPED);
          this._ignorePause = false;
        }.bind(this), 0);
        video.currentTime = 0;
        this._playing = false;
      };
      proto.seekTo = function(sec) {
        var video = this._video;
        if (!video) return;
        if (this._loaded) video.currentTime = sec; else {
          var cb = function() {
            video.currentTime = sec;
            video.removeEventListener(polyfill.event, cb);
          };
          video.addEventListener(polyfill.event, cb);
        }
        _ccsg.VideoPlayer._polyfill.autoplayAfterOperation && this.isPlaying() && setTimeout((function() {
          video.play();
        }), 20);
      };
      proto.isPlaying = function() {
        var video = this._video;
        _ccsg.VideoPlayer._polyfill.autoplayAfterOperation && this._playing && setTimeout((function() {
          video.play();
        }), 20);
        return this._playing;
      };
      proto.duration = function() {
        var video = this._video;
        var duration = -1;
        if (!video) return duration;
        duration = video.duration;
        duration <= 0 && cc.logID(7702);
        return duration;
      };
      proto.currentTime = function() {
        var video = this._video;
        if (!video) return -1;
        return video.currentTime;
      };
    })(_ccsg.VideoPlayer._polyfill);
  }), {
    "../event-manager": 110,
    "../platform/CCSys": 184,
    "../platform/utils": 200
  } ],
  240: [ (function(require, module, exports) {
    var Utils = require("../platform/utils");
    var eventManager = require("../event-manager");
    _ccsg.WebView = _ccsg.Node.extend({
      ctor: function() {
        _ccsg.Node.prototype.ctor.call(this);
        this.setContentSize(cc.size(300, 200));
        this._EventList = {};
      },
      createDomElementIfNeeded: function() {
        this._renderCmd._div || this._renderCmd.createNativeControl();
      },
      setOnJSCallback: function(callback) {},
      setJavascriptInterfaceScheme: function(scheme) {},
      loadData: function(data, MIMEType, encoding, baseURL) {},
      loadHTMLString: function(string, baseURL) {},
      loadURL: function(url) {
        this._renderCmd.updateURL(url);
        this._dispatchEvent(_ccsg.WebView.EventType.LOADING);
      },
      stopLoading: function() {
        cc.logID(7800);
      },
      reload: function() {
        var iframe = this._renderCmd._iframe;
        if (iframe) {
          var win = iframe.contentWindow;
          win && win.location && win.location.reload();
        }
      },
      canGoBack: function() {
        cc.logID(7801);
        return true;
      },
      canGoForward: function() {
        cc.logID(7802);
        return true;
      },
      goBack: function() {
        try {
          if (_ccsg.WebView._polyfill.closeHistory) return cc.logID(7803);
          var iframe = this._renderCmd._iframe;
          if (iframe) {
            var win = iframe.contentWindow;
            win && win.location && win.history.back.call(win);
          }
        } catch (err) {
          cc.log(err);
        }
      },
      goForward: function() {
        try {
          if (_ccsg.WebView._polyfill.closeHistory) return cc.logID(7804);
          var iframe = this._renderCmd._iframe;
          if (iframe) {
            var win = iframe.contentWindow;
            win && win.location && win.history.forward.call(win);
          }
        } catch (err) {
          cc.log(err);
        }
      },
      evaluateJS: function(str) {
        var iframe = this._renderCmd._iframe;
        if (iframe) {
          var win = iframe.contentWindow;
          try {
            win.eval(str);
            this._dispatchEvent(_ccsg.WebView.EventType.JS_EVALUATED);
          } catch (err) {
            console.error(err);
          }
        }
      },
      setScalesPageToFit: function() {
        cc.logID(7805);
      },
      setEventListener: function(event, callback) {
        this._EventList[event] = callback;
      },
      removeEventListener: function(event) {
        this._EventList[event] = null;
      },
      _dispatchEvent: function(event) {
        var callback = this._EventList[event];
        callback && callback.call(this, this, this._renderCmd._iframe.src);
      },
      _createRenderCmd: function() {
        return new _ccsg.WebView.RenderCmd(this);
      },
      setContentSize: function(width, height) {
        if (void 0 !== width.width && void 0 !== width.height) {
          height = width.height;
          width = width.width;
        }
        _ccsg.Node.prototype.setContentSize.call(this, width, height);
        this._renderCmd.updateSize(width, height);
      },
      cleanup: function() {
        this._super();
        this._renderCmd.removeDom();
      },
      setVisible: function(visible) {
        _ccsg.Node.prototype.setVisible.call(this, visible);
        this._renderCmd.updateVisibility();
      }
    });
    _ccsg.WebView.EventType = {
      LOADING: 0,
      LOADED: 1,
      ERROR: 2,
      JS_EVALUATED: 3
    };
    (function() {
      var polyfill = _ccsg.WebView._polyfill = {
        devicePixelRatio: false,
        enableDiv: false
      };
      cc.sys.os === cc.sys.OS_IOS && (polyfill.enableDiv = true);
      cc.sys.isMobile ? cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX && (polyfill.enableBG = true) : cc.sys.browserType === cc.sys.BROWSER_TYPE_IE && (polyfill.closeHistory = true);
    })();
    (function(polyfill) {
      var RenderCmd;
      RenderCmd = cc._renderType === cc.game.RENDER_TYPE_CANVAS ? _ccsg.Node.CanvasRenderCmd : _ccsg.Node.WebGLRenderCmd;
      _ccsg.WebView.RenderCmd = function(node) {
        this._rootCtor(node);
        this._parent = null;
        this._div = null;
        this._iframe = null;
        this._listener = null;
      };
      var proto = _ccsg.WebView.RenderCmd.prototype = Object.create(RenderCmd.prototype);
      proto.constructor = _ccsg.WebView.RenderCmd;
      proto.transform = function(parentCmd, recursive) {
        this.originTransform(parentCmd, recursive);
        this.updateMatrix();
      };
      proto.updateStatus = function() {
        polyfill.devicePixelRatio = cc.view.isRetinaEnabled();
        var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag;
        if (locFlag & flags.transformDirty) {
          this.transform(this.getParentRenderCmd(), true);
          this.updateMatrix();
          this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.transformDirty;
        }
      };
      proto.initEvent = function() {
        var node = this._node;
        this._iframe.addEventListener("load", (function() {
          node._dispatchEvent(_ccsg.WebView.EventType.LOADED);
        }));
        this._iframe.addEventListener("error", (function() {
          node._dispatchEvent(_ccsg.WebView.EventType.ERROR);
        }));
      };
      proto.resize = function(view) {
        view = view || cc.view;
        var node = this._node;
        if (node._parent && node._visible) this.updateMatrix(); else {
          var list = eventManager._listenersMap[cc.game.EVENT_RESIZE].getFixedPriorityListeners();
          eventManager._removeListenerInVector(list, this._listener);
          this._listener = null;
        }
      };
      proto.updateMatrix = function() {
        if (!this._div) return;
        var node = this._node, scaleX = cc.view._scaleX, scaleY = cc.view._scaleY;
        var dpr = cc.view._devicePixelRatio;
        var t = this._worldTransform;
        scaleX /= dpr;
        scaleY /= dpr;
        var container = cc.game.container;
        var a = t.a * scaleX, b = t.b, c = t.c, d = t.d * scaleY;
        var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft);
        var offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom);
        var tx = t.tx * scaleX + offsetX, ty = t.ty * scaleY + offsetY;
        var matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")";
        this._div.style["transform"] = matrix;
        this._div.style["-webkit-transform"] = matrix;
        this._div.style["transform-origin"] = "0px 100% 0px";
        this._div.style["-webkit-transform-origin"] = "0px 100% 0px";
      };
      proto.initStyle = function() {
        if (!this._div) return;
        var div = this._div;
        div.style.position = "absolute";
        div.style.bottom = "0px";
        div.style.left = "0px";
      };
      proto.updateURL = function(url) {
        var iframe = this._iframe;
        iframe.src = url;
        var self = this;
        var cb = function() {
          self._loaded = true;
          self.updateVisibility();
          iframe.removeEventListener("load", cb);
        };
        iframe.addEventListener("load", cb);
      };
      proto.updateSize = function(w, h) {
        var div = this._div;
        if (div) {
          div.style["width"] = w + "px";
          div.style["height"] = h + "px";
        }
      };
      proto.createDom = function() {
        if (polyfill.enableDiv) {
          this._div = document.createElement("div");
          this._div.style["-webkit-overflow"] = "auto";
          this._div.style["-webkit-overflow-scrolling"] = "touch";
          this._iframe = document.createElement("iframe");
          this._div.appendChild(this._iframe);
          this._iframe.style.width = "100%";
          this._iframe.style.height = "100%";
        } else this._div = this._iframe = document.createElement("iframe");
        polyfill.enableBG && (this._div.style["background"] = "#FFF");
        this._div.style["background"] = "#FFF";
        var contentSize = this._node._contentSize;
        this._div.style.height = contentSize.height + "px";
        this._div.style.width = contentSize.width + "px";
        this._div.style.overflow = "scroll";
        this._iframe.style.border = "none";
        cc.game.container.appendChild(this._div);
        this.updateVisibility();
      };
      proto.createNativeControl = function() {
        this.createDom();
        this.initStyle();
        this.initEvent();
      };
      proto.removeDom = function() {
        var div = this._div;
        if (div) {
          var hasChild = Utils.contains(cc.game.container, div);
          hasChild && cc.game.container.removeChild(div);
        }
        this._div = null;
      };
      proto.updateVisibility = function() {
        var node = this._node;
        if (!this._div) return;
        var div = this._div;
        node.visible ? div.style.visibility = "visible" : div.style.visibility = "hidden";
      };
    })(_ccsg.WebView._polyfill);
  }), {
    "../event-manager": 110,
    "../platform/utils": 200
  } ],
  241: [ (function(require, module, exports) {
    var js = cc.js;
    var deprecateEnum;
    var markAsRemoved;
    var provideClearError;
    var shouldNotUseNodeProp;
    var ERR;
    false;
  }), {} ],
  242: [ (function(require, module, exports) {
    require("./core/CCGame");
    require("./actions");
    require("./core/base-nodes/CCSGNode");
    require("./core/base-nodes/CCSGNodeBaseRenderCmd");
    require("./core/base-nodes/CCSGNodeCanvasRenderCmd");
    require("./core/base-nodes/CCSGNodeWebGLRenderCmd");
    require("./core/scenes/CCSGScene");
    require("./core/CCConfiguration");
    require("./core/sprites/CCSGSprite");
    require("./core/sprites/CCSGSpriteCanvasRenderCmd");
    require("./core/sprites/CCSGSpriteWebGLRenderCmd");
    require("./core/sprites/CCScale9Sprite");
    require("./core/sprites/CCScale9SpriteCanvasRenderCmd");
    require("./core/sprites/CCScale9SpriteWebGLRenderCmd");
    require("./core/sprites/CCSpriteBatchNode");
    require("./render-texture/CCRenderTexture");
    require("./render-texture/CCRenderTextureCanvasRenderCmd");
    require("./render-texture/CCRenderTextureWebGLRenderCmd");
  }), {
    "./actions": 10,
    "./core/CCConfiguration": 32,
    "./core/CCGame": 39,
    "./core/base-nodes/CCSGNode": 55,
    "./core/base-nodes/CCSGNodeBaseRenderCmd": 56,
    "./core/base-nodes/CCSGNodeCanvasRenderCmd": 57,
    "./core/base-nodes/CCSGNodeWebGLRenderCmd": 58,
    "./core/scenes/CCSGScene": 206,
    "./core/sprites/CCSGSprite": 207,
    "./core/sprites/CCSGSpriteCanvasRenderCmd": 208,
    "./core/sprites/CCSGSpriteWebGLRenderCmd": 209,
    "./core/sprites/CCScale9Sprite": 210,
    "./core/sprites/CCScale9SpriteCanvasRenderCmd": 211,
    "./core/sprites/CCScale9SpriteWebGLRenderCmd": 212,
    "./core/sprites/CCSpriteBatchNode": 213,
    "./render-texture/CCRenderTexture": 266,
    "./render-texture/CCRenderTextureCanvasRenderCmd": 267,
    "./render-texture/CCRenderTextureWebGLRenderCmd": 268
  } ],
  243: [ (function(require, module, exports) {
    cc.math.AABB = function(min, max) {
      this.min = min || new cc.math.Vec3();
      this.max = max || new cc.math.Vec3();
    };
    cc.math.AABB.prototype.containsPoint = function(point) {
      return point.x >= this.min.x && point.x <= this.max.x && point.y >= this.min.y && point.y <= this.max.y && point.z >= this.min.z && point.z <= this.max.z;
    };
    cc.math.AABB.containsPoint = function(pPoint, pBox) {
      return pPoint.x >= pBox.min.x && pPoint.x <= pBox.max.x && pPoint.y >= pBox.min.y && pPoint.y <= pBox.max.y && pPoint.z >= pBox.min.z && pPoint.z <= pBox.max.z;
    };
    cc.math.AABB.prototype.assignFrom = function(aabb) {
      this.min.assignFrom(aabb.min);
      this.max.assignFrom(aabb.max);
    };
    cc.math.AABB.assign = function(pOut, pIn) {
      pOut.min.assignFrom(pIn.min);
      pOut.max.assignFrom(pIn.max);
      return pOut;
    };
  }), {} ],
  244: [ (function(require, module, exports) {
    cc.math.Matrix4Stack = function(top, stack) {
      this.top = top;
      this.stack = stack || [];
      this.lastUpdated = 0;
    };
    var proto = cc.math.Matrix4Stack.prototype;
    proto.initialize = function() {
      this.stack.length = 0;
      this.top = null;
    };
    proto.push = function(item) {
      item = item || this.top;
      this.stack.push(this.top);
      this.top = new cc.math.Matrix4(item);
      this.update();
    };
    proto.pop = function() {
      this.top = this.stack.pop();
      this.update();
    };
    proto.update = function() {
      this.lastUpdated++;
    };
    proto.release = function() {
      this.stack = null;
      this.top = null;
      this._matrixPool = null;
    };
    proto._getFromPool = function(item) {
      var pool = this._matrixPool;
      if (0 === pool.length) return new cc.math.Matrix4(item);
      var ret = pool.pop();
      ret.assignFrom(item);
      return ret;
    };
    proto._putInPool = function(matrix) {
      this._matrixPool.push(matrix);
    };
  }), {} ],
  245: [ (function(require, module, exports) {
    var math = cc.math;
    math.KM_GL_MODELVIEW = 5888;
    math.KM_GL_PROJECTION = 5889;
    math.KM_GL_TEXTURE = 5890;
    math.modelview_matrix_stack = new math.Matrix4Stack();
    math.projection_matrix_stack = new math.Matrix4Stack();
    math.texture_matrix_stack = new math.Matrix4Stack();
    cc.current_stack = null;
    var initialized = false;
    var lazyInitialize = function() {
      if (!initialized) {
        var identity = new math.Matrix4();
        math.modelview_matrix_stack.initialize();
        math.projection_matrix_stack.initialize();
        math.texture_matrix_stack.initialize();
        cc.current_stack = math.modelview_matrix_stack;
        initialized = true;
        identity.identity();
        math.modelview_matrix_stack.push(identity);
        math.projection_matrix_stack.push(identity);
        math.texture_matrix_stack.push(identity);
      }
    };
    lazyInitialize();
    math.glFreeAll = function() {
      math.modelview_matrix_stack.release();
      math.modelview_matrix_stack = null;
      math.projection_matrix_stack.release();
      math.projection_matrix_stack = null;
      math.texture_matrix_stack.release();
      math.texture_matrix_stack = null;
      initialized = false;
      cc.current_stack = null;
    };
    math.glPushMatrix = function() {
      cc.current_stack.push(cc.current_stack.top);
      cc.current_stack.update();
    };
    math.glPushMatrixWitMat4 = function(saveMat) {
      cc.current_stack.stack.push(cc.current_stack.top);
      saveMat.assignFrom(cc.current_stack.top);
      cc.current_stack.top = saveMat;
      cc.current_stack.update();
    };
    math.glPopMatrix = function() {
      cc.current_stack.top = cc.current_stack.stack.pop();
      cc.current_stack.update();
    };
    math.glMatrixMode = function(mode) {
      switch (mode) {
       case math.KM_GL_MODELVIEW:
        cc.current_stack = math.modelview_matrix_stack;
        break;

       case math.KM_GL_PROJECTION:
        cc.current_stack = math.projection_matrix_stack;
        break;

       case math.KM_GL_TEXTURE:
        cc.current_stack = math.texture_matrix_stack;
        break;

       default:
        throw new Error("Invalid matrix mode specified");
      }
    };
    math.glLoadIdentity = function() {
      cc.current_stack.top.identity();
      cc.current_stack.update();
    };
    math.glLoadMatrix = function(pIn) {
      cc.current_stack.top.assignFrom(pIn);
      cc.current_stack.update();
    };
    math.glMultMatrix = function(pIn) {
      cc.current_stack.top.multiply(pIn);
      cc.current_stack.update();
    };
    var tempMatrix = new math.Matrix4();
    math.glTranslatef = function(x, y, z) {
      var translation = math.Matrix4.createByTranslation(x, y, z, tempMatrix);
      cc.current_stack.top.multiply(translation);
      cc.current_stack.update();
    };
    var tempVector3 = new math.Vec3();
    math.glRotatef = function(angle, x, y, z) {
      tempVector3.fill(x, y, z);
      var rotation = math.Matrix4.createByAxisAndAngle(tempVector3, cc.degreesToRadians(angle), tempMatrix);
      cc.current_stack.top.multiply(rotation);
      cc.current_stack.update();
    };
    math.glScalef = function(x, y, z) {
      var scaling = math.Matrix4.createByScale(x, y, z, tempMatrix);
      cc.current_stack.top.multiply(scaling);
      cc.current_stack.update();
    };
    math.glGetMatrix = function(mode, pOut) {
      switch (mode) {
       case math.KM_GL_MODELVIEW:
        pOut.assignFrom(math.modelview_matrix_stack.top);
        break;

       case math.KM_GL_PROJECTION:
        pOut.assignFrom(math.projection_matrix_stack.top);
        break;

       case math.KM_GL_TEXTURE:
        pOut.assignFrom(math.texture_matrix_stack.top);
        break;

       default:
        throw new Error("Invalid matrix mode specified");
      }
    };
  }), {} ],
  246: [ (function(require, module, exports) {
    require("./utility");
    require("./vec2");
    require("./vec3");
    require("./vec4");
    require("./ray2");
    require("./mat3");
    require("./mat4");
    require("./plane");
    require("./quaternion");
    require("./aabb");
    require("./gl/mat4stack");
    require("./gl/matrix");
  }), {
    "./aabb": 243,
    "./gl/mat4stack": 244,
    "./gl/matrix": 245,
    "./mat3": 247,
    "./mat4": 248,
    "./plane": 249,
    "./quaternion": 250,
    "./ray2": 251,
    "./utility": 252,
    "./vec2": 253,
    "./vec3": 254,
    "./vec4": 255
  } ],
  247: [ (function(require, module, exports) {
    true;
    window.Uint16Array = window.Uint16Array || window.Array;
    window.Float32Array = window.Float32Array || window.Array;
    cc.math.Matrix3 = function(mat3) {
      mat3 && mat3.mat ? this.mat = new Float32Array(mat3.mat) : this.mat = new Float32Array(9);
    };
    var proto = cc.math.Matrix3.prototype;
    proto.fill = function(mat3) {
      var mat = this.mat, matIn = mat3.mat;
      mat[0] = matIn[0];
      mat[1] = matIn[1];
      mat[2] = matIn[2];
      mat[3] = matIn[3];
      mat[4] = matIn[4];
      mat[5] = matIn[5];
      mat[6] = matIn[6];
      mat[7] = matIn[7];
      mat[8] = matIn[8];
      return this;
    };
    proto.adjugate = function() {
      var mat = this.mat;
      var m0 = mat[0], m1 = mat[1], m2 = mat[2], m3 = mat[3], m4 = mat[4], m5 = mat[5], m6 = mat[6], m7 = mat[7], m8 = mat[8];
      mat[0] = m4 * m8 - m5 * m7;
      mat[1] = m2 * m7 - m1 * m8;
      mat[2] = m1 * m5 - m2 * m4;
      mat[3] = m5 * m6 - m3 * m8;
      mat[4] = m0 * m8 - m2 * m6;
      mat[5] = m2 * m3 - m0 * m5;
      mat[6] = m3 * m7 - m4 * m6;
      mat[8] = m0 * m4 - m1 * m3;
      return this;
    };
    proto.identity = function() {
      var mat = this.mat;
      mat[1] = mat[2] = mat[3] = mat[5] = mat[6] = mat[7] = 0;
      mat[0] = mat[4] = mat[8] = 1;
      return this;
    };
    var tmpMatrix = new cc.math.Matrix3();
    proto.inverse = function(determinate) {
      if (0 === determinate) return this;
      tmpMatrix.assignFrom(this);
      var detInv = 1 / determinate;
      this.adjugate();
      this.multiplyScalar(detInv);
      return this;
    };
    proto.isIdentity = function() {
      var mat = this.mat;
      return 1 === mat[0] && 0 === mat[1] && 0 === mat[2] && 0 === mat[3] && 1 === mat[4] && 0 === mat[5] && 0 === mat[6] && 0 === mat[7] && 1 === mat[8];
    };
    proto.transpose = function() {
      var mat = this.mat;
      var m1 = mat[1], m2 = mat[2], m3 = mat[3], m5 = mat[5], m6 = mat[6], m7 = mat[7];
      mat[1] = m3;
      mat[2] = m6;
      mat[3] = m1;
      mat[5] = m7;
      mat[6] = m2;
      mat[7] = m5;
      return this;
    };
    proto.determinant = function() {
      var mat = this.mat;
      var output = mat[0] * mat[4] * mat[8] + mat[1] * mat[5] * mat[6] + mat[2] * mat[3] * mat[7];
      output -= mat[2] * mat[4] * mat[6] + mat[0] * mat[5] * mat[7] + mat[1] * mat[3] * mat[8];
      return output;
    };
    proto.multiply = function(mat3) {
      var m1 = this.mat, m2 = mat3.mat;
      var a0 = m1[0], a1 = m1[1], a2 = m1[2], a3 = m1[3], a4 = m1[4], a5 = m1[5], a6 = m1[6], a7 = m1[7], a8 = m1[8];
      var b0 = m2[0], b1 = m2[1], b2 = m2[2], b3 = m2[3], b4 = m2[4], b5 = m2[5], b6 = m2[6], b7 = m2[7], b8 = m2[8];
      m1[0] = a0 * b0 + a3 * b1 + a6 * b2;
      m1[1] = a1 * b0 + a4 * b1 + a7 * b2;
      m1[2] = a2 * b0 + a5 * b1 + a8 * b2;
      m1[3] = a2 * b0 + a5 * b1 + a8 * b2;
      m1[4] = a1 * b3 + a4 * b4 + a7 * b5;
      m1[5] = a2 * b3 + a5 * b4 + a8 * b5;
      m1[6] = a0 * b6 + a3 * b7 + a6 * b8;
      m1[7] = a1 * b6 + a4 * b7 + a7 * b8;
      m1[8] = a2 * b6 + a5 * b7 + a8 * b8;
      return this;
    };
    proto.multiplyScalar = function(factor) {
      var mat = this.mat;
      mat[0] *= factor;
      mat[1] *= factor;
      mat[2] *= factor;
      mat[3] *= factor;
      mat[4] *= factor;
      mat[5] *= factor;
      mat[6] *= factor;
      mat[7] *= factor;
      mat[8] *= factor;
      return this;
    };
    cc.math.Matrix3.rotationAxisAngle = function(axis, radians) {
      var rcos = Math.cos(radians), rsin = Math.sin(radians);
      var retMat = new cc.math.Matrix3();
      var mat = retMat.mat;
      mat[0] = rcos + axis.x * axis.x * (1 - rcos);
      mat[1] = axis.z * rsin + axis.y * axis.x * (1 - rcos);
      mat[2] = -axis.y * rsin + axis.z * axis.x * (1 - rcos);
      mat[3] = -axis.z * rsin + axis.x * axis.y * (1 - rcos);
      mat[4] = rcos + axis.y * axis.y * (1 - rcos);
      mat[5] = axis.x * rsin + axis.z * axis.y * (1 - rcos);
      mat[6] = axis.y * rsin + axis.x * axis.z * (1 - rcos);
      mat[7] = -axis.x * rsin + axis.y * axis.z * (1 - rcos);
      mat[8] = rcos + axis.z * axis.z * (1 - rcos);
      return retMat;
    };
    proto.assignFrom = function(matIn) {
      if (this === matIn) {
        cc.logID(7900);
        return this;
      }
      var mat = this.mat, m2 = matIn.mat;
      mat[0] = m2[0];
      mat[1] = m2[1];
      mat[2] = m2[2];
      mat[3] = m2[3];
      mat[4] = m2[4];
      mat[5] = m2[5];
      mat[6] = m2[6];
      mat[7] = m2[7];
      mat[8] = m2[8];
      return this;
    };
    proto.equals = function(mat3) {
      if (this === mat3) return true;
      var EPSILON = cc.math.EPSILON, m1 = this.mat, m2 = mat3.mat;
      for (var i = 0; i < 9; ++i) if (!(m1[i] + EPSILON > m2[i] && m1[i] - EPSILON < m2[i])) return false;
      return true;
    };
    cc.math.Matrix3.createByRotationX = function(radians) {
      var retMat = new cc.math.Matrix3(), mat = retMat.mat;
      mat[0] = 1;
      mat[1] = 0;
      mat[2] = 0;
      mat[3] = 0;
      mat[4] = Math.cos(radians);
      mat[5] = Math.sin(radians);
      mat[6] = 0;
      mat[7] = -Math.sin(radians);
      mat[8] = Math.cos(radians);
      return retMat;
    };
    cc.math.Matrix3.createByRotationY = function(radians) {
      var retMat = new cc.math.Matrix3(), mat = retMat.mat;
      mat[0] = Math.cos(radians);
      mat[1] = 0;
      mat[2] = -Math.sin(radians);
      mat[3] = 0;
      mat[4] = 1;
      mat[5] = 0;
      mat[6] = Math.sin(radians);
      mat[7] = 0;
      mat[8] = Math.cos(radians);
      return retMat;
    };
    cc.math.Matrix3.createByRotationZ = function(radians) {
      var retMat = new cc.math.Matrix3(), mat = retMat.mat;
      mat[0] = Math.cos(radians);
      mat[1] = -Math.sin(radians);
      mat[2] = 0;
      mat[3] = Math.sin(radians);
      mat[4] = Math.cos(radians);
      mat[5] = 0;
      mat[6] = 0;
      mat[7] = 0;
      mat[8] = 1;
      return retMat;
    };
    cc.math.Matrix3.createByRotation = function(radians) {
      var retMat = new cc.math.Matrix3(), mat = retMat.mat;
      mat[0] = Math.cos(radians);
      mat[1] = Math.sin(radians);
      mat[2] = 0;
      mat[3] = -Math.sin(radians);
      mat[4] = Math.cos(radians);
      mat[5] = 0;
      mat[6] = 0;
      mat[7] = 0;
      mat[8] = 1;
      return retMat;
    };
    cc.math.Matrix3.createByScale = function(x, y) {
      var ret = new cc.math.Matrix3();
      ret.identity();
      ret.mat[0] = x;
      ret.mat[4] = y;
      return ret;
    };
    cc.math.Matrix3.createByTranslation = function(x, y) {
      var ret = new cc.math.Matrix3();
      ret.identity();
      ret.mat[6] = x;
      ret.mat[7] = y;
      return ret;
    };
    cc.math.Matrix3.createByQuaternion = function(quaternion) {
      if (!quaternion) return null;
      var ret = new cc.math.Matrix3(), mat = ret.mat;
      mat[0] = 1 - 2 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
      mat[1] = 2 * (quaternion.x * quaternion.y - quaternion.w * quaternion.z);
      mat[2] = 2 * (quaternion.x * quaternion.z + quaternion.w * quaternion.y);
      mat[3] = 2 * (quaternion.x * quaternion.y + quaternion.w * quaternion.z);
      mat[4] = 1 - 2 * (quaternion.x * quaternion.x + quaternion.z * quaternion.z);
      mat[5] = 2 * (quaternion.y * quaternion.z - quaternion.w * quaternion.x);
      mat[6] = 2 * (quaternion.x * quaternion.z - quaternion.w * quaternion.y);
      mat[7] = 2 * (quaternion.y * quaternion.z + quaternion.w * quaternion.x);
      mat[8] = 1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
      return ret;
    };
    proto.rotationToAxisAngle = function() {
      return cc.math.Quaternion.rotationMatrix(this).toAxisAndAngle();
    };
  }), {} ],
  248: [ (function(require, module, exports) {
    cc.math.Matrix4 = function(mat4) {
      mat4 && mat4.mat ? this.mat = new Float32Array(mat4.mat) : this.mat = new Float32Array(16);
    };
    var proto = cc.math.Matrix4.prototype;
    proto.fill = function(scalarArr) {
      var mat = this.mat;
      for (var i = 0; i < 16; i++) mat[i] = scalarArr[i];
      return this;
    };
    cc.math.mat4Identity = function(pOut) {
      var mat = pOut.mat;
      mat[1] = mat[2] = mat[3] = mat[4] = mat[6] = mat[7] = mat[8] = mat[9] = mat[11] = mat[12] = mat[13] = mat[14] = 0;
      mat[0] = mat[5] = mat[10] = mat[15] = 1;
      return pOut;
    };
    proto.identity = function() {
      var mat = this.mat;
      mat[1] = mat[2] = mat[3] = mat[4] = mat[6] = mat[7] = mat[8] = mat[9] = mat[11] = mat[12] = mat[13] = mat[14] = 0;
      mat[0] = mat[5] = mat[10] = mat[15] = 1;
      return this;
    };
    proto.get = function(row, col) {
      return this.mat[row + 4 * col];
    };
    proto.set = function(row, col, value) {
      this.mat[row + 4 * col] = value;
    };
    proto.swap = function(r1, c1, r2, c2) {
      var mat = this.mat, tmp = mat[r1 + 4 * c1];
      mat[r1 + 4 * c1] = mat[r2 + 4 * c2];
      mat[r2 + 4 * c2] = tmp;
    };
    cc.math.Matrix4._gaussj = function(a, b) {
      var i, icol = 0, irow = 0, j, k, l, ll, n = 4, m = 4, selElement;
      var big, dum, pivinv;
      var indxc = [ 0, 0, 0, 0 ], indxr = [ 0, 0, 0, 0 ], ipiv = [ 0, 0, 0, 0 ];
      for (i = 0; i < n; i++) {
        big = 0;
        for (j = 0; j < n; j++) if (1 !== ipiv[j]) for (k = 0; k < n; k++) if (0 === ipiv[k]) {
          selElement = Math.abs(a.get(j, k));
          if (selElement >= big) {
            big = selElement;
            irow = j;
            icol = k;
          }
        }
        ++ipiv[icol];
        if (irow !== icol) {
          for (l = 0; l < n; l++) a.swap(irow, l, icol, l);
          for (l = 0; l < m; l++) b.swap(irow, l, icol, l);
        }
        indxr[i] = irow;
        indxc[i] = icol;
        if (0 === a.get(icol, icol)) return false;
        pivinv = 1 / a.get(icol, icol);
        a.set(icol, icol, 1);
        for (l = 0; l < n; l++) a.set(icol, l, a.get(icol, l) * pivinv);
        for (l = 0; l < m; l++) b.set(icol, l, b.get(icol, l) * pivinv);
        for (ll = 0; ll < n; ll++) if (ll !== icol) {
          dum = a.get(ll, icol);
          a.set(ll, icol, 0);
          for (l = 0; l < n; l++) a.set(ll, l, a.get(ll, l) - a.get(icol, l) * dum);
          for (l = 0; l < m; l++) b.set(ll, l, a.get(ll, l) - b.get(icol, l) * dum);
        }
      }
      for (l = n - 1; l >= 0; l--) if (indxr[l] !== indxc[l]) for (k = 0; k < n; k++) a.swap(k, indxr[l], k, indxc[l]);
      return true;
    };
    var identityMatrix = new cc.math.Matrix4().identity();
    cc.math.mat4Inverse = function(pOut, pM) {
      var inv = new cc.math.Matrix4(pM);
      var tmp = new cc.math.Matrix4(identityMatrix);
      if (false === cc.math.Matrix4._gaussj(inv, tmp)) return null;
      pOut.assignFrom(inv);
      return pOut;
    };
    proto.inverse = function() {
      var inv = new cc.math.Matrix4(this);
      var tmp = new cc.math.Matrix4(identityMatrix);
      if (false === cc.math.Matrix4._gaussj(inv, tmp)) return null;
      return inv;
    };
    proto.isIdentity = function() {
      var mat = this.mat;
      return 1 === mat[0] && 0 === mat[1] && 0 === mat[2] && 0 === mat[3] && 0 === mat[4] && 1 === mat[5] && 0 === mat[6] && 0 === mat[7] && 0 === mat[8] && 0 === mat[9] && 1 === mat[10] && 0 === mat[11] && 0 === mat[12] && 0 === mat[13] && 0 === mat[14] && 1 === mat[15];
    };
    proto.transpose = function() {
      var mat = this.mat;
      var m1 = mat[1], m2 = mat[2], m3 = mat[3], m4 = mat[4], m6 = mat[6], m7 = mat[7], m8 = mat[8], m9 = mat[9], m11 = mat[11], m12 = mat[12], m13 = mat[13], m14 = mat[14];
      mat[1] = m4;
      mat[2] = m8;
      mat[3] = m12;
      mat[4] = m1;
      mat[6] = m9;
      mat[7] = m13;
      mat[8] = m2;
      mat[9] = m6;
      mat[11] = m14;
      mat[12] = m3;
      mat[13] = m7;
      mat[14] = m11;
      return this;
    };
    cc.math.mat4Multiply = function(pOut, pM1, pM2) {
      var outArray = pOut.mat, mat1 = pM1.mat, mat2 = pM2.mat;
      var a00 = mat1[0], a01 = mat1[1], a02 = mat1[2], a03 = mat1[3];
      var a10 = mat1[4], a11 = mat1[5], a12 = mat1[6], a13 = mat1[7];
      var a20 = mat1[8], a21 = mat1[9], a22 = mat1[10], a23 = mat1[11];
      var a30 = mat1[12], a31 = mat1[13], a32 = mat1[14], a33 = mat1[15];
      var b00 = mat2[0], b01 = mat2[1], b02 = mat2[2], b03 = mat2[3];
      var b10 = mat2[4], b11 = mat2[5], b12 = mat2[6], b13 = mat2[7];
      var b20 = mat2[8], b21 = mat2[9], b22 = mat2[10], b23 = mat2[11];
      var b30 = mat2[12], b31 = mat2[13], b32 = mat2[14], b33 = mat2[15];
      outArray[0] = b00 * a00 + b01 * a10 + b02 * a20 + b03 * a30;
      outArray[1] = b00 * a01 + b01 * a11 + b02 * a21 + b03 * a31;
      outArray[2] = b00 * a02 + b01 * a12 + b02 * a22 + b03 * a32;
      outArray[3] = b00 * a03 + b01 * a13 + b02 * a23 + b03 * a33;
      outArray[4] = b10 * a00 + b11 * a10 + b12 * a20 + b13 * a30;
      outArray[5] = b10 * a01 + b11 * a11 + b12 * a21 + b13 * a31;
      outArray[6] = b10 * a02 + b11 * a12 + b12 * a22 + b13 * a32;
      outArray[7] = b10 * a03 + b11 * a13 + b12 * a23 + b13 * a33;
      outArray[8] = b20 * a00 + b21 * a10 + b22 * a20 + b23 * a30;
      outArray[9] = b20 * a01 + b21 * a11 + b22 * a21 + b23 * a31;
      outArray[10] = b20 * a02 + b21 * a12 + b22 * a22 + b23 * a32;
      outArray[11] = b20 * a03 + b21 * a13 + b22 * a23 + b23 * a33;
      outArray[12] = b30 * a00 + b31 * a10 + b32 * a20 + b33 * a30;
      outArray[13] = b30 * a01 + b31 * a11 + b32 * a21 + b33 * a31;
      outArray[14] = b30 * a02 + b31 * a12 + b32 * a22 + b33 * a32;
      outArray[15] = b30 * a03 + b31 * a13 + b32 * a23 + b33 * a33;
      return pOut;
    };
    proto.multiply = function(mat4) {
      var mat = this.mat, mat2 = mat4.mat;
      var a00 = mat[0], a01 = mat[1], a02 = mat[2], a03 = mat[3];
      var a10 = mat[4], a11 = mat[5], a12 = mat[6], a13 = mat[7];
      var a20 = mat[8], a21 = mat[9], a22 = mat[10], a23 = mat[11];
      var a30 = mat[12], a31 = mat[13], a32 = mat[14], a33 = mat[15];
      var b00 = mat2[0], b01 = mat2[1], b02 = mat2[2], b03 = mat2[3];
      var b10 = mat2[4], b11 = mat2[5], b12 = mat2[6], b13 = mat2[7];
      var b20 = mat2[8], b21 = mat2[9], b22 = mat2[10], b23 = mat2[11];
      var b30 = mat2[12], b31 = mat2[13], b32 = mat2[14], b33 = mat2[15];
      mat[0] = b00 * a00 + b01 * a10 + b02 * a20 + b03 * a30;
      mat[1] = b00 * a01 + b01 * a11 + b02 * a21 + b03 * a31;
      mat[2] = b00 * a02 + b01 * a12 + b02 * a22 + b03 * a32;
      mat[3] = b00 * a03 + b01 * a13 + b02 * a23 + b03 * a33;
      mat[4] = b10 * a00 + b11 * a10 + b12 * a20 + b13 * a30;
      mat[5] = b10 * a01 + b11 * a11 + b12 * a21 + b13 * a31;
      mat[6] = b10 * a02 + b11 * a12 + b12 * a22 + b13 * a32;
      mat[7] = b10 * a03 + b11 * a13 + b12 * a23 + b13 * a33;
      mat[8] = b20 * a00 + b21 * a10 + b22 * a20 + b23 * a30;
      mat[9] = b20 * a01 + b21 * a11 + b22 * a21 + b23 * a31;
      mat[10] = b20 * a02 + b21 * a12 + b22 * a22 + b23 * a32;
      mat[11] = b20 * a03 + b21 * a13 + b22 * a23 + b23 * a33;
      mat[12] = b30 * a00 + b31 * a10 + b32 * a20 + b33 * a30;
      mat[13] = b30 * a01 + b31 * a11 + b32 * a21 + b33 * a31;
      mat[14] = b30 * a02 + b31 * a12 + b32 * a22 + b33 * a32;
      mat[15] = b30 * a03 + b31 * a13 + b32 * a23 + b33 * a33;
      return this;
    };
    cc.math.getMat4MultiplyValue = function(pM1, pM2) {
      var m1 = pM1.mat, m2 = pM2.mat;
      var mat = new Float32Array(16);
      mat[0] = m1[0] * m2[0] + m1[4] * m2[1] + m1[8] * m2[2] + m1[12] * m2[3];
      mat[1] = m1[1] * m2[0] + m1[5] * m2[1] + m1[9] * m2[2] + m1[13] * m2[3];
      mat[2] = m1[2] * m2[0] + m1[6] * m2[1] + m1[10] * m2[2] + m1[14] * m2[3];
      mat[3] = m1[3] * m2[0] + m1[7] * m2[1] + m1[11] * m2[2] + m1[15] * m2[3];
      mat[4] = m1[0] * m2[4] + m1[4] * m2[5] + m1[8] * m2[6] + m1[12] * m2[7];
      mat[5] = m1[1] * m2[4] + m1[5] * m2[5] + m1[9] * m2[6] + m1[13] * m2[7];
      mat[6] = m1[2] * m2[4] + m1[6] * m2[5] + m1[10] * m2[6] + m1[14] * m2[7];
      mat[7] = m1[3] * m2[4] + m1[7] * m2[5] + m1[11] * m2[6] + m1[15] * m2[7];
      mat[8] = m1[0] * m2[8] + m1[4] * m2[9] + m1[8] * m2[10] + m1[12] * m2[11];
      mat[9] = m1[1] * m2[8] + m1[5] * m2[9] + m1[9] * m2[10] + m1[13] * m2[11];
      mat[10] = m1[2] * m2[8] + m1[6] * m2[9] + m1[10] * m2[10] + m1[14] * m2[11];
      mat[11] = m1[3] * m2[8] + m1[7] * m2[9] + m1[11] * m2[10] + m1[15] * m2[11];
      mat[12] = m1[0] * m2[12] + m1[4] * m2[13] + m1[8] * m2[14] + m1[12] * m2[15];
      mat[13] = m1[1] * m2[12] + m1[5] * m2[13] + m1[9] * m2[14] + m1[13] * m2[15];
      mat[14] = m1[2] * m2[12] + m1[6] * m2[13] + m1[10] * m2[14] + m1[14] * m2[15];
      mat[15] = m1[3] * m2[12] + m1[7] * m2[13] + m1[11] * m2[14] + m1[15] * m2[15];
      return mat;
    };
    cc.math.mat4Assign = function(pOut, pIn) {
      if (pOut === pIn) {
        cc.logID(7901);
        return pOut;
      }
      var outArr = pOut.mat;
      var inArr = pIn.mat;
      outArr[0] = inArr[0];
      outArr[1] = inArr[1];
      outArr[2] = inArr[2];
      outArr[3] = inArr[3];
      outArr[4] = inArr[4];
      outArr[5] = inArr[5];
      outArr[6] = inArr[6];
      outArr[7] = inArr[7];
      outArr[8] = inArr[8];
      outArr[9] = inArr[9];
      outArr[10] = inArr[10];
      outArr[11] = inArr[11];
      outArr[12] = inArr[12];
      outArr[13] = inArr[13];
      outArr[14] = inArr[14];
      outArr[15] = inArr[15];
      return pOut;
    };
    proto.assignFrom = function(mat4) {
      if (this === mat4) {
        cc.logID(7902);
        return this;
      }
      var outArr = this.mat, inArr = mat4.mat;
      outArr[0] = inArr[0];
      outArr[1] = inArr[1];
      outArr[2] = inArr[2];
      outArr[3] = inArr[3];
      outArr[4] = inArr[4];
      outArr[5] = inArr[5];
      outArr[6] = inArr[6];
      outArr[7] = inArr[7];
      outArr[8] = inArr[8];
      outArr[9] = inArr[9];
      outArr[10] = inArr[10];
      outArr[11] = inArr[11];
      outArr[12] = inArr[12];
      outArr[13] = inArr[13];
      outArr[14] = inArr[14];
      outArr[15] = inArr[15];
      return this;
    };
    proto.equals = function(mat4) {
      if (this === mat4) {
        cc.logID(7903);
        return true;
      }
      var matA = this.mat, matB = mat4.mat, EPSILON = cc.math.EPSILON;
      for (var i = 0; i < 16; i++) if (!(matA[i] + EPSILON > matB[i] && matA[i] - EPSILON < matB[i])) return false;
      return true;
    };
    cc.math.Matrix4.createByRotationX = function(radians, matrix) {
      matrix = matrix || new cc.math.Matrix4();
      var mat = matrix.mat;
      mat[0] = 1;
      mat[3] = mat[2] = mat[1] = 0;
      mat[4] = 0;
      mat[5] = Math.cos(radians);
      mat[6] = Math.sin(radians);
      mat[7] = 0;
      mat[8] = 0;
      mat[9] = -Math.sin(radians);
      mat[10] = Math.cos(radians);
      mat[11] = 0;
      mat[14] = mat[13] = mat[12] = 0;
      mat[15] = 1;
      return matrix;
    };
    cc.math.Matrix4.createByRotationY = function(radians, matrix) {
      matrix = matrix || new cc.math.Matrix4();
      var mat = matrix.mat;
      mat[0] = Math.cos(radians);
      mat[1] = 0;
      mat[2] = -Math.sin(radians);
      mat[3] = 0;
      mat[7] = mat[6] = mat[4] = 0;
      mat[5] = 1;
      mat[8] = Math.sin(radians);
      mat[9] = 0;
      mat[10] = Math.cos(radians);
      mat[11] = 0;
      mat[14] = mat[13] = mat[12] = 0;
      mat[15] = 1;
      return matrix;
    };
    cc.math.Matrix4.createByRotationZ = function(radians, matrix) {
      matrix = matrix || new cc.math.Matrix4();
      var mat = matrix.mat;
      mat[0] = Math.cos(radians);
      mat[1] = Math.sin(radians);
      mat[3] = mat[2] = 0;
      mat[4] = -Math.sin(radians);
      mat[5] = Math.cos(radians);
      mat[7] = mat[6] = 0;
      mat[11] = mat[9] = mat[8] = 0;
      mat[10] = 1;
      mat[14] = mat[13] = mat[12] = 0;
      mat[15] = 1;
      return matrix;
    };
    cc.math.Matrix4.createByPitchYawRoll = function(pitch, yaw, roll, matrix) {
      matrix = matrix || new cc.math.Matrix4();
      var cr = Math.cos(pitch), sr = Math.sin(pitch);
      var cp = Math.cos(yaw), sp = Math.sin(yaw);
      var cy = Math.cos(roll), sy = Math.sin(roll);
      var srsp = sr * sp, crsp = cr * sp;
      var mat = matrix.mat;
      mat[0] = cp * cy;
      mat[4] = cp * sy;
      mat[8] = -sp;
      mat[1] = srsp * cy - cr * sy;
      mat[5] = srsp * sy + cr * cy;
      mat[9] = sr * cp;
      mat[2] = crsp * cy + sr * sy;
      mat[6] = crsp * sy - sr * cy;
      mat[10] = cr * cp;
      mat[3] = mat[7] = mat[11] = 0;
      mat[15] = 1;
      return matrix;
    };
    cc.math.Matrix4.createByQuaternion = function(quaternion, matrix) {
      matrix = matrix || new cc.math.Matrix4();
      var mat = matrix.mat;
      mat[0] = 1 - 2 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
      mat[1] = 2 * (quaternion.x * quaternion.y + quaternion.z * quaternion.w);
      mat[2] = 2 * (quaternion.x * quaternion.z - quaternion.y * quaternion.w);
      mat[3] = 0;
      mat[4] = 2 * (quaternion.x * quaternion.y - quaternion.z * quaternion.w);
      mat[5] = 1 - 2 * (quaternion.x * quaternion.x + quaternion.z * quaternion.z);
      mat[6] = 2 * (quaternion.z * quaternion.y + quaternion.x * quaternion.w);
      mat[7] = 0;
      mat[8] = 2 * (quaternion.x * quaternion.z + quaternion.y * quaternion.w);
      mat[9] = 2 * (quaternion.y * quaternion.z - quaternion.x * quaternion.w);
      mat[10] = 1 - 2 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
      mat[11] = 0;
      mat[14] = mat[13] = mat[12] = 0;
      mat[15] = 1;
      return matrix;
    };
    cc.math.Matrix4.createByRotationTranslation = function(rotation, translation, matrix) {
      matrix = matrix || new cc.math.Matrix4();
      var mat = matrix.mat, rMat = rotation.mat;
      mat[0] = rMat[0];
      mat[1] = rMat[1];
      mat[2] = rMat[2];
      mat[3] = 0;
      mat[4] = rMat[3];
      mat[5] = rMat[4];
      mat[6] = rMat[5];
      mat[7] = 0;
      mat[8] = rMat[6];
      mat[9] = rMat[7];
      mat[10] = rMat[8];
      mat[11] = 0;
      mat[12] = translation.x;
      mat[13] = translation.y;
      mat[14] = translation.z;
      mat[15] = 1;
      return matrix;
    };
    cc.math.Matrix4.createByScale = function(x, y, z, matrix) {
      matrix = matrix || new cc.math.Matrix4();
      var mat = matrix.mat;
      mat[0] = x;
      mat[5] = y;
      mat[10] = z;
      mat[15] = 1;
      mat[1] = mat[2] = mat[3] = mat[4] = mat[6] = mat[7] = mat[8] = mat[9] = mat[11] = mat[12] = mat[13] = mat[14] = 0;
      return matrix;
    };
    cc.math.mat4Translation = function(pOut, x, y, z) {
      pOut.mat[0] = pOut.mat[5] = pOut.mat[10] = pOut.mat[15] = 1;
      pOut.mat[1] = pOut.mat[2] = pOut.mat[3] = pOut.mat[4] = pOut.mat[6] = pOut.mat[7] = pOut.mat[8] = pOut.mat[9] = pOut.mat[11] = 0;
      pOut.mat[12] = x;
      pOut.mat[13] = y;
      pOut.mat[14] = z;
      return pOut;
    };
    cc.math.Matrix4.createByTranslation = function(x, y, z, matrix) {
      matrix = matrix || new cc.math.Matrix4();
      matrix.identity();
      matrix.mat[12] = x;
      matrix.mat[13] = y;
      matrix.mat[14] = z;
      return matrix;
    };
    proto.getUpVec3 = function() {
      var mat = this.mat;
      var ret = new cc.math.Vec3(mat[4], mat[5], mat[6]);
      return ret.normalize();
    };
    proto.getRightVec3 = function() {
      var mat = this.mat;
      var ret = new cc.math.Vec3(mat[0], mat[1], mat[2]);
      return ret.normalize();
    };
    proto.getForwardVec3 = function() {
      var mat = this.mat;
      var ret = new cc.math.Vec3(mat[8], mat[9], mat[10]);
      return ret.normalize();
    };
    cc.math.mat4PerspectiveProjection = function(pOut, fovY, aspect, zNear, zFar) {
      var r = cc.degreesToRadians(fovY / 2);
      var deltaZ = zFar - zNear;
      var s = Math.sin(r);
      if (0 === deltaZ || 0 === s || 0 === aspect) return null;
      var cotangent = Math.cos(r) / s;
      pOut.identity();
      pOut.mat[0] = cotangent / aspect;
      pOut.mat[5] = cotangent;
      pOut.mat[10] = -(zFar + zNear) / deltaZ;
      pOut.mat[11] = -1;
      pOut.mat[14] = -2 * zNear * zFar / deltaZ;
      pOut.mat[15] = 0;
      return pOut;
    };
    cc.math.Matrix4.createPerspectiveProjection = function(fovY, aspect, zNear, zFar) {
      var r = cc.degreesToRadians(fovY / 2), deltaZ = zFar - zNear;
      var s = Math.sin(r);
      if (0 === deltaZ || 0 === s || 0 === aspect) return null;
      var cotangent = Math.cos(r) / s;
      var matrix = new cc.math.Matrix4(), mat = matrix.mat;
      matrix.identity();
      mat[0] = cotangent / aspect;
      mat[5] = cotangent;
      mat[10] = -(zFar + zNear) / deltaZ;
      mat[11] = -1;
      mat[14] = -2 * zNear * zFar / deltaZ;
      mat[15] = 0;
      return matrix;
    };
    cc.math.mat4OrthographicProjection = function(pOut, left, right, bottom, top, nearVal, farVal) {
      pOut.identity();
      pOut.mat[0] = 2 / (right - left);
      pOut.mat[5] = 2 / (top - bottom);
      pOut.mat[10] = -2 / (farVal - nearVal);
      pOut.mat[12] = -(right + left) / (right - left);
      pOut.mat[13] = -(top + bottom) / (top - bottom);
      pOut.mat[14] = -(farVal + nearVal) / (farVal - nearVal);
      return pOut;
    };
    cc.math.Matrix4.createOrthographicProjection = function(left, right, bottom, top, nearVal, farVal) {
      var matrix = new cc.math.Matrix4(), mat = matrix.mat;
      matrix.identity();
      mat[0] = 2 / (right - left);
      mat[5] = 2 / (top - bottom);
      mat[10] = -2 / (farVal - nearVal);
      mat[12] = -(right + left) / (right - left);
      mat[13] = -(top + bottom) / (top - bottom);
      mat[14] = -(farVal + nearVal) / (farVal - nearVal);
      return matrix;
    };
    cc.math.mat4LookAt = function(pOut, pEye, pCenter, pUp) {
      var f = new cc.math.Vec3(pCenter), up = new cc.math.Vec3(pUp);
      f.subtract(pEye);
      f.normalize();
      up.normalize();
      var s = new cc.math.Vec3(f);
      s.cross(up);
      s.normalize();
      var u = new cc.math.Vec3(s);
      u.cross(f);
      s.normalize();
      pOut.identity();
      pOut.mat[0] = s.x;
      pOut.mat[4] = s.y;
      pOut.mat[8] = s.z;
      pOut.mat[1] = u.x;
      pOut.mat[5] = u.y;
      pOut.mat[9] = u.z;
      pOut.mat[2] = -f.x;
      pOut.mat[6] = -f.y;
      pOut.mat[10] = -f.z;
      var translate = cc.math.Matrix4.createByTranslation(-pEye.x, -pEye.y, -pEye.z);
      pOut.multiply(translate);
      return pOut;
    };
    var tempMatrix = new cc.math.Matrix4();
    proto.lookAt = function(eyeVec, centerVec, upVec) {
      var f = new cc.math.Vec3(centerVec), up = new cc.math.Vec3(upVec), mat = this.mat;
      f.subtract(eyeVec);
      f.normalize();
      up.normalize();
      var s = new cc.math.Vec3(f);
      s.cross(up);
      s.normalize();
      var u = new cc.math.Vec3(s);
      u.cross(f);
      s.normalize();
      this.identity();
      mat[0] = s.x;
      mat[4] = s.y;
      mat[8] = s.z;
      mat[1] = u.x;
      mat[5] = u.y;
      mat[9] = u.z;
      mat[2] = -f.x;
      mat[6] = -f.y;
      mat[10] = -f.z;
      tempMatrix = cc.math.Matrix4.createByTranslation(-eyeVec.x, -eyeVec.y, -eyeVec.z, tempMatrix);
      this.multiply(tempMatrix);
      return this;
    };
    cc.math.mat4RotationAxisAngle = function(pOut, axis, radians) {
      var rcos = Math.cos(radians), rsin = Math.sin(radians);
      var normalizedAxis = new cc.math.Vec3(axis);
      normalizedAxis.normalize();
      pOut.mat[0] = rcos + normalizedAxis.x * normalizedAxis.x * (1 - rcos);
      pOut.mat[1] = normalizedAxis.z * rsin + normalizedAxis.y * normalizedAxis.x * (1 - rcos);
      pOut.mat[2] = -normalizedAxis.y * rsin + normalizedAxis.z * normalizedAxis.x * (1 - rcos);
      pOut.mat[3] = 0;
      pOut.mat[4] = -normalizedAxis.z * rsin + normalizedAxis.x * normalizedAxis.y * (1 - rcos);
      pOut.mat[5] = rcos + normalizedAxis.y * normalizedAxis.y * (1 - rcos);
      pOut.mat[6] = normalizedAxis.x * rsin + normalizedAxis.z * normalizedAxis.y * (1 - rcos);
      pOut.mat[7] = 0;
      pOut.mat[8] = normalizedAxis.y * rsin + normalizedAxis.x * normalizedAxis.z * (1 - rcos);
      pOut.mat[9] = -normalizedAxis.x * rsin + normalizedAxis.y * normalizedAxis.z * (1 - rcos);
      pOut.mat[10] = rcos + normalizedAxis.z * normalizedAxis.z * (1 - rcos);
      pOut.mat[11] = 0;
      pOut.mat[12] = 0;
      pOut.mat[13] = 0;
      pOut.mat[14] = 0;
      pOut.mat[15] = 1;
      return pOut;
    };
    cc.math.Matrix4.createByAxisAndAngle = function(axis, radians, matrix) {
      matrix = matrix || new cc.math.Matrix4();
      var mat = this.mat, rcos = Math.cos(radians), rsin = Math.sin(radians);
      var normalizedAxis = new cc.math.Vec3(axis);
      normalizedAxis.normalize();
      mat[0] = rcos + normalizedAxis.x * normalizedAxis.x * (1 - rcos);
      mat[1] = normalizedAxis.z * rsin + normalizedAxis.y * normalizedAxis.x * (1 - rcos);
      mat[2] = -normalizedAxis.y * rsin + normalizedAxis.z * normalizedAxis.x * (1 - rcos);
      mat[3] = 0;
      mat[4] = -normalizedAxis.z * rsin + normalizedAxis.x * normalizedAxis.y * (1 - rcos);
      mat[5] = rcos + normalizedAxis.y * normalizedAxis.y * (1 - rcos);
      mat[6] = normalizedAxis.x * rsin + normalizedAxis.z * normalizedAxis.y * (1 - rcos);
      mat[7] = 0;
      mat[8] = normalizedAxis.y * rsin + normalizedAxis.x * normalizedAxis.z * (1 - rcos);
      mat[9] = -normalizedAxis.x * rsin + normalizedAxis.y * normalizedAxis.z * (1 - rcos);
      mat[10] = rcos + normalizedAxis.z * normalizedAxis.z * (1 - rcos);
      mat[11] = 0;
      mat[12] = mat[13] = mat[14] = 0;
      mat[15] = 1;
      return matrix;
    };
    proto.extractRotation = function() {
      var matrix = new cc.math.Matrix3(), mat4 = this.mat, mat3 = matrix.mat;
      mat3[0] = mat4[0];
      mat3[1] = mat4[1];
      mat3[2] = mat4[2];
      mat3[3] = mat4[4];
      mat3[4] = mat4[5];
      mat3[5] = mat4[6];
      mat3[6] = mat4[8];
      mat3[7] = mat4[9];
      mat3[8] = mat4[10];
      return matrix;
    };
    proto.extractPlane = function(planeType) {
      var plane = new cc.math.Plane(), mat = this.mat;
      switch (planeType) {
       case cc.math.Plane.RIGHT:
        plane.a = mat[3] - mat[0];
        plane.b = mat[7] - mat[4];
        plane.c = mat[11] - mat[8];
        plane.d = mat[15] - mat[12];
        break;

       case cc.math.Plane.LEFT:
        plane.a = mat[3] + mat[0];
        plane.b = mat[7] + mat[4];
        plane.c = mat[11] + mat[8];
        plane.d = mat[15] + mat[12];
        break;

       case cc.math.Plane.BOTTOM:
        plane.a = mat[3] + mat[1];
        plane.b = mat[7] + mat[5];
        plane.c = mat[11] + mat[9];
        plane.d = mat[15] + mat[13];
        break;

       case cc.math.Plane.TOP:
        plane.a = mat[3] - mat[1];
        plane.b = mat[7] - mat[5];
        plane.c = mat[11] - mat[9];
        plane.d = mat[15] - mat[13];
        break;

       case cc.math.Plane.FAR:
        plane.a = mat[3] - mat[2];
        plane.b = mat[7] - mat[6];
        plane.c = mat[11] - mat[10];
        plane.d = mat[15] - mat[14];
        break;

       case cc.math.Plane.NEAR:
        plane.a = mat[3] + mat[2];
        plane.b = mat[7] + mat[6];
        plane.c = mat[11] + mat[10];
        plane.d = mat[15] + mat[14];
        break;

       default:
        cc.logID(7904);
      }
      var t = Math.sqrt(plane.a * plane.a + plane.b * plane.b + plane.c * plane.c);
      plane.a /= t;
      plane.b /= t;
      plane.c /= t;
      plane.d /= t;
      return plane;
    };
    proto.toAxisAndAngle = function() {
      var rotation = this.extractRotation();
      var temp = cc.math.Quaternion.rotationMatrix(rotation);
      return temp.toAxisAndAngle();
    };
  }), {} ],
  249: [ (function(require, module, exports) {
    cc.math.Plane = function(a, b, c, d) {
      if (a && void 0 === b) {
        this.a = a.a;
        this.b = a.b;
        this.c = a.c;
        this.d = a.d;
      } else {
        this.a = a || 0;
        this.b = b || 0;
        this.c = c || 0;
        this.d = d || 0;
      }
    };
    var proto = cc.math.Plane.prototype;
    cc.math.Plane.LEFT = 0;
    cc.math.Plane.RIGHT = 1;
    cc.math.Plane.BOTTOM = 2;
    cc.math.Plane.TOP = 3;
    cc.math.Plane.NEAR = 4;
    cc.math.Plane.FAR = 5;
    cc.math.Plane.POINT_INFRONT_OF_PLANE = 0;
    cc.math.Plane.POINT_BEHIND_PLANE = 1;
    cc.math.Plane.POINT_ON_PLANE = 2;
    proto.dot = function(vec4) {
      return this.a * vec4.x + this.b * vec4.y + this.c * vec4.z + this.d * vec4.w;
    };
    proto.dotCoord = function(vec3) {
      return this.a * vec3.x + this.b * vec3.y + this.c * vec3.z + this.d;
    };
    proto.dotNormal = function(vec3) {
      return this.a * vec3.x + this.b * vec3.y + this.c * vec3.z;
    };
    cc.math.Plane.fromPointNormal = function(vec3, normal) {
      return new cc.math.Plane(normal.x, normal.y, normal.z, -normal.dot(vec3));
    };
    cc.math.Plane.fromPoints = function(vec1, vec2, vec3) {
      var v1 = new cc.math.Vec3(vec2), v2 = new cc.math.Vec3(vec3), plane = new cc.math.Plane();
      v1.subtract(vec1);
      v2.subtract(vec1);
      v1.cross(v2);
      v1.normalize();
      plane.a = v1.x;
      plane.b = v1.y;
      plane.c = v1.z;
      plane.d = v1.scale(-1).dot(vec1);
      return plane;
    };
    proto.normalize = function() {
      var n = new cc.math.Vec3(this.a, this.b, this.c), l = 1 / n.length();
      n.normalize();
      this.a = n.x;
      this.b = n.y;
      this.c = n.z;
      this.d = this.d * l;
      return this;
    };
    proto.classifyPoint = function(vec3) {
      var distance = this.a * vec3.x + this.b * vec3.y + this.c * vec3.z + this.d;
      if (distance > .001) return cc.math.Plane.POINT_INFRONT_OF_PLANE;
      if (distance < -.001) return cc.math.Plane.POINT_BEHIND_PLANE;
      return cc.math.Plane.POINT_ON_PLANE;
    };
  }), {} ],
  250: [ (function(require, module, exports) {
    cc.math.Quaternion = function(x, y, z, w) {
      if (x && void 0 === y) {
        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;
      }
    };
    var proto = cc.math.Quaternion.prototype;
    proto.conjugate = function(quaternion) {
      this.x = -quaternion.x;
      this.y = -quaternion.y;
      this.z = -quaternion.z;
      this.w = quaternion.w;
      return this;
    };
    proto.dot = function(quaternion) {
      return this.w * quaternion.w + this.x * quaternion.x + this.y * quaternion.y + this.z * quaternion.z;
    };
    proto.exponential = function() {
      return this;
    };
    proto.identity = function() {
      this.x = 0;
      this.y = 0;
      this.z = 0;
      this.w = 1;
      return this;
    };
    proto.inverse = function() {
      var len = this.length();
      if (Math.abs(len) > cc.math.EPSILON) {
        this.x = 0;
        this.y = 0;
        this.z = 0;
        this.w = 0;
        return this;
      }
      this.conjugate(this).scale(1 / len);
      return this;
    };
    proto.isIdentity = function() {
      return 0 === this.x && 0 === this.y && 0 === this.z && 1 === this.w;
    };
    proto.length = function() {
      return Math.sqrt(this.lengthSq());
    };
    proto.lengthSq = function() {
      return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
    };
    proto.multiply = function(quaternion) {
      var x = this.x, y = this.y, z = this.z, w = this.w;
      this.w = w * quaternion.w - x * quaternion.x - y * quaternion.y - z * quaternion.z;
      this.x = w * quaternion.x + x * quaternion.w + y * quaternion.z - z * quaternion.y;
      this.y = w * quaternion.y + y * quaternion.w + z * quaternion.x - x * quaternion.z;
      this.z = w * quaternion.z + z * quaternion.w + x * quaternion.y - y * quaternion.x;
      return this;
    };
    proto.normalize = function() {
      var length = this.length();
      if (Math.abs(length) <= cc.math.EPSILON) throw new Error("current quaternion is an invalid value");
      this.scale(1 / length);
      return this;
    };
    proto.rotationAxis = function(axis, angle) {
      var rad = .5 * angle, scale = Math.sin(rad);
      this.w = Math.cos(rad);
      this.x = axis.x * scale;
      this.y = axis.y * scale;
      this.z = axis.z * scale;
      return this;
    };
    cc.math.Quaternion.rotationMatrix = function(mat3) {
      if (!mat3) return null;
      var x, y, z, w;
      var m4x4 = [], mat = mat3.mat, scale = 0;
      m4x4[0] = mat[0];
      m4x4[1] = mat[3];
      m4x4[2] = mat[6];
      m4x4[4] = mat[1];
      m4x4[5] = mat[4];
      m4x4[6] = mat[7];
      m4x4[8] = mat[2];
      m4x4[9] = mat[5];
      m4x4[10] = mat[8];
      m4x4[15] = 1;
      var pMatrix = m4x4[0];
      var diagonal = pMatrix[0] + pMatrix[5] + pMatrix[10] + 1;
      if (diagonal > cc.math.EPSILON) {
        scale = 2 * Math.sqrt(diagonal);
        x = (pMatrix[9] - pMatrix[6]) / scale;
        y = (pMatrix[2] - pMatrix[8]) / scale;
        z = (pMatrix[4] - pMatrix[1]) / scale;
        w = .25 * scale;
      } else if (pMatrix[0] > pMatrix[5] && pMatrix[0] > pMatrix[10]) {
        scale = 2 * Math.sqrt(1 + pMatrix[0] - pMatrix[5] - pMatrix[10]);
        x = .25 * scale;
        y = (pMatrix[4] + pMatrix[1]) / scale;
        z = (pMatrix[2] + pMatrix[8]) / scale;
        w = (pMatrix[9] - pMatrix[6]) / scale;
      } else if (pMatrix[5] > pMatrix[10]) {
        scale = 2 * Math.sqrt(1 + pMatrix[5] - pMatrix[0] - pMatrix[10]);
        x = (pMatrix[4] + pMatrix[1]) / scale;
        y = .25 * scale;
        z = (pMatrix[9] + pMatrix[6]) / scale;
        w = (pMatrix[2] - pMatrix[8]) / scale;
      } else {
        scale = 2 * Math.sqrt(1 + pMatrix[10] - pMatrix[0] - pMatrix[5]);
        x = (pMatrix[2] + pMatrix[8]) / scale;
        y = (pMatrix[9] + pMatrix[6]) / scale;
        z = .25 * scale;
        w = (pMatrix[4] - pMatrix[1]) / scale;
      }
      return new cc.math.Quaternion(x, y, z, w);
    };
    cc.math.Quaternion.rotationYawPitchRoll = function(yaw, pitch, roll) {
      var ex, ey, ez;
      var cr, cp, cy, sr, sp, sy, cpcy, spsy;
      ex = cc.degreesToRadians(pitch) / 2;
      ey = cc.degreesToRadians(yaw) / 2;
      ez = cc.degreesToRadians(roll) / 2;
      cr = Math.cos(ex);
      cp = Math.cos(ey);
      cy = Math.cos(ez);
      sr = Math.sin(ex);
      sp = Math.sin(ey);
      sy = Math.sin(ez);
      cpcy = cp * cy;
      spsy = sp * sy;
      var ret = new cc.math.Quaternion();
      ret.w = cr * cpcy + sr * spsy;
      ret.x = sr * cpcy - cr * spsy;
      ret.y = cr * sp * cy + sr * cp * sy;
      ret.z = cr * cp * sy - sr * sp * cy;
      ret.normalize();
      return ret;
    };
    proto.slerp = function(quaternion, t) {
      if (this.x === quaternion.x && this.y === quaternion.y && this.z === quaternion.z && this.w === quaternion.w) return this;
      var ct = this.dot(quaternion), theta = Math.acos(ct), st = Math.sqrt(1 - cc.math.square(ct));
      var stt = Math.sin(t * theta) / st, somt = Math.sin((1 - t) * theta) / st;
      var temp2 = new cc.math.Quaternion(quaternion);
      this.scale(somt);
      temp2.scale(stt);
      this.add(temp2);
      return this;
    };
    proto.toAxisAndAngle = function() {
      var tempAngle;
      var scale;
      var retAngle, retAxis = new cc.math.Vec3();
      tempAngle = Math.acos(this.w);
      scale = Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z));
      if (scale > -cc.math.EPSILON && scale < cc.math.EPSILON || scale < 2 * Math.PI + cc.math.EPSILON && scale > 2 * Math.PI - cc.math.EPSILON) {
        retAngle = 0;
        retAxis.x = 0;
        retAxis.y = 0;
        retAxis.z = 1;
      } else {
        retAngle = 2 * tempAngle;
        retAxis.x = this.x / scale;
        retAxis.y = this.y / scale;
        retAxis.z = this.z / scale;
        retAxis.normalize();
      }
      return {
        axis: retAxis,
        angle: retAngle
      };
    };
    proto.scale = function(scale) {
      this.x *= scale;
      this.y *= scale;
      this.z *= scale;
      this.w *= scale;
      return this;
    };
    proto.assignFrom = function(quaternion) {
      this.x = quaternion.x;
      this.y = quaternion.y;
      this.z = quaternion.z;
      this.w = quaternion.w;
      return this;
    };
    proto.add = function(quaternion) {
      this.x += quaternion.x;
      this.y += quaternion.y;
      this.z += quaternion.z;
      this.w += quaternion.w;
      return this;
    };
    cc.math.Quaternion.rotationBetweenVec3 = function(vec1, vec2, fallback) {
      var v1 = new cc.math.Vec3(vec1), v2 = new cc.math.Vec3(vec2);
      v1.normalize();
      v2.normalize();
      var a = v1.dot(v2), quaternion = new cc.math.Quaternion();
      if (a >= 1) {
        quaternion.identity();
        return quaternion;
      }
      if (a < 1e-6 - 1) if (Math.abs(fallback.lengthSq()) < cc.math.EPSILON) quaternion.rotationAxis(fallback, Math.PI); else {
        var axis = new cc.math.Vec3(1, 0, 0);
        axis.cross(vec1);
        if (Math.abs(axis.lengthSq()) < cc.math.EPSILON) {
          axis.fill(0, 1, 0);
          axis.cross(vec1);
        }
        axis.normalize();
        quaternion.rotationAxis(axis, Math.PI);
      } else {
        var s = Math.sqrt(2 * (1 + a)), invs = 1 / s;
        v1.cross(v2);
        quaternion.x = v1.x * invs;
        quaternion.y = v1.y * invs;
        quaternion.z = v1.z * invs;
        quaternion.w = .5 * s;
        quaternion.normalize();
      }
      return quaternion;
    };
    proto.multiplyVec3 = function(vec) {
      var x = this.x, y = this.y, z = this.z, retVec = new cc.math.Vec3(vec);
      var uv = new cc.math.Vec3(x, y, z), uuv = new cc.math.Vec3(x, y, z);
      uv.cross(vec);
      uuv.cross(uv);
      uv.scale(2 * q.w);
      uuv.scale(2);
      retVec.add(uv);
      retVec.add(uuv);
      return retVec;
    };
  }), {} ],
  251: [ (function(require, module, exports) {
    cc.math.Ray2 = function(start, dir) {
      this.start = start || new cc.math.Vec2();
      this.dir = dir || new cc.math.Vec2();
    };
    cc.math.Ray2.prototype.fill = function(px, py, vx, vy) {
      this.start.x = px;
      this.start.y = py;
      this.dir.x = vx;
      this.dir.y = vy;
    };
    cc.math.Ray2.prototype.intersectLineSegment = function(p1, p2, intersection) {
      var x1 = this.start.x, y1 = this.start.y;
      var x2 = this.start.x + this.dir.x, y2 = this.start.y + this.dir.y;
      var x3 = p1.x, y3 = p1.y;
      var x4 = p2.x, y4 = p2.y;
      var denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
      var ua, x, y;
      if (denom > -cc.math.EPSILON && denom < cc.math.EPSILON) return false;
      ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denom;
      x = x1 + ua * (x2 - x1);
      y = y1 + ua * (y2 - y1);
      if (x < Math.min(p1.x, p2.x) - cc.math.EPSILON || x > Math.max(p1.x, p2.x) + cc.math.EPSILON || y < Math.min(p1.y, p2.y) - cc.math.EPSILON || y > Math.max(p1.y, p2.y) + cc.math.EPSILON) return false;
      if (x < Math.min(x1, x2) - cc.math.EPSILON || x > Math.max(x1, x2) + cc.math.EPSILON || y < Math.min(y1, y2) - cc.math.EPSILON || y > Math.max(y1, y2) + cc.math.EPSILON) return false;
      intersection.x = x;
      intersection.y = y;
      return true;
    };
    function calculate_line_normal(p1, p2, normalOut) {
      var tmp = new cc.math.Vec2(p2);
      tmp.subtract(p1);
      normalOut.x = -tmp.y;
      normalOut.y = tmp.x;
      normalOut.normalize();
    }
    cc.math.Ray2.prototype.intersectTriangle = function(p1, p2, p3, intersection, normal_out) {
      var intersect = new cc.math.Vec2(), final_intersect = new cc.math.Vec2();
      var normal = new cc.math.Vec2(), distance = 1e4, intersected = false;
      var this_distance;
      if (this.intersectLineSegment(p1, p2, intersect)) {
        intersected = true;
        this_distance = intersect.subtract(this.start).length();
        if (this_distance < distance) {
          final_intersect.x = intersect.x;
          final_intersect.y = intersect.y;
          distance = this_distance;
          calculate_line_normal(p1, p2, normal);
        }
      }
      if (this.intersectLineSegment(p2, p3, intersect)) {
        intersected = true;
        this_distance = intersect.subtract(this.start).length();
        if (this_distance < distance) {
          final_intersect.x = intersect.x;
          final_intersect.y = intersect.y;
          distance = this_distance;
          calculate_line_normal(p2, p3, normal);
        }
      }
      if (this.intersectLineSegment(p3, p1, intersect)) {
        intersected = true;
        this_distance = intersect.subtract(this.start).length();
        if (this_distance < distance) {
          final_intersect.x = intersect.x;
          final_intersect.y = intersect.y;
          distance = this_distance;
          calculate_line_normal(p3, p1, normal);
        }
      }
      if (intersected) {
        intersection.x = final_intersect.x;
        intersection.y = final_intersect.y;
        if (normal_out) {
          normal_out.x = normal.x;
          normal_out.y = normal.y;
        }
      }
      return intersected;
    };
  }), {} ],
  252: [ (function(require, module, exports) {
    cc.math = cc.math || {};
    cc.math.EPSILON = 1 / 64;
    cc.math.square = function(s) {
      return s * s;
    };
    cc.math.almostEqual = function(lhs, rhs) {
      return lhs + cc.math.EPSILON > rhs && lhs - cc.math.EPSILON < rhs;
    };
  }), {} ],
  253: [ (function(require, module, exports) {
    cc.math.Vec2 = function(x, y) {
      if (void 0 === y) {
        this.x = x.x;
        this.y = x.y;
      } else {
        this.x = x || 0;
        this.y = y || 0;
      }
    };
    var proto = cc.math.Vec2.prototype;
    proto.fill = function(x, y) {
      this.x = x;
      this.y = y;
    };
    proto.length = function() {
      return Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y));
    };
    proto.lengthSq = function() {
      return cc.math.square(this.x) + cc.math.square(this.y);
    };
    proto.normalize = function() {
      var l = 1 / this.length();
      this.x *= l;
      this.y *= l;
      return this;
    };
    cc.math.Vec2.add = function(pOut, pV1, pV2) {
      pOut.x = pV1.x + pV2.x;
      pOut.y = pV1.y + pV2.y;
      return pOut;
    };
    proto.add = function(vec) {
      this.x += vec.x;
      this.y += vec.y;
      return this;
    };
    proto.dot = function(vec) {
      return this.x * vec.x + this.y * vec.y;
    };
    cc.math.Vec2.subtract = function(pOut, pV1, pV2) {
      pOut.x = pV1.x - pV2.x;
      pOut.y = pV1.y - pV2.y;
      return pOut;
    };
    proto.subtract = function(vec) {
      this.x -= vec.x;
      this.y -= vec.y;
      return this;
    };
    proto.transform = function(mat3) {
      var x = this.x, y = this.y;
      this.x = x * mat3.mat[0] + y * mat3.mat[3] + mat3.mat[6];
      this.y = x * mat3.mat[1] + y * mat3.mat[4] + mat3.mat[7];
      return this;
    };
    cc.math.Vec2.scale = function(pOut, pIn, s) {
      pOut.x = pIn.x * s;
      pOut.y = pIn.y * s;
      return pOut;
    };
    proto.scale = function(s) {
      this.x *= s;
      this.y *= s;
      return this;
    };
    proto.equals = function(vec) {
      return this.x < vec.x + cc.math.EPSILON && this.x > vec.x - cc.math.EPSILON && this.y < vec.y + cc.math.EPSILON && this.y > vec.y - cc.math.EPSILON;
    };
  }), {} ],
  254: [ (function(require, module, exports) {
    cc.math.Vec3 = cc.math.Vec3 = function(x, y, z) {
      if (x && void 0 === y) {
        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;
      }
    };
    cc.math.vec3 = function(x, y, z) {
      return new cc.math.Vec3(x, y, z);
    };
    var proto = cc.math.Vec3.prototype;
    proto.fill = function(x, y, z) {
      if (x && void 0 === y) {
        this.x = x.x;
        this.y = x.y;
        this.z = x.z;
      } else {
        this.x = x;
        this.y = y;
        this.z = z;
      }
      return this;
    };
    proto.length = function() {
      return Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z));
    };
    proto.lengthSq = function() {
      return cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z);
    };
    proto.normalize = function() {
      var l = 1 / this.length();
      this.x *= l;
      this.y *= l;
      this.z *= l;
      return this;
    };
    proto.cross = function(vec3) {
      var x = this.x, y = this.y, z = this.z;
      this.x = y * vec3.z - z * vec3.y;
      this.y = z * vec3.x - x * vec3.z;
      this.z = x * vec3.y - y * vec3.x;
      return this;
    };
    proto.dot = function(vec) {
      return this.x * vec.x + this.y * vec.y + this.z * vec.z;
    };
    proto.add = function(vec) {
      this.x += vec.x;
      this.y += vec.y;
      this.z += vec.z;
      return this;
    };
    proto.subtract = function(vec) {
      this.x -= vec.x;
      this.y -= vec.y;
      this.z -= vec.z;
      return this;
    };
    proto.transform = function(mat4) {
      var x = this.x, y = this.y, z = this.z, mat = mat4.mat;
      this.x = x * mat[0] + y * mat[4] + z * mat[8] + mat[12];
      this.y = x * mat[1] + y * mat[5] + z * mat[9] + mat[13];
      this.z = x * mat[2] + y * mat[6] + z * mat[10] + mat[14];
      return this;
    };
    proto.transformNormal = function(mat4) {
      var x = this.x, y = this.y, z = this.z, mat = mat4.mat;
      this.x = x * mat[0] + y * mat[4] + z * mat[8];
      this.y = x * mat[1] + y * mat[5] + z * mat[9];
      this.z = x * mat[2] + y * mat[6] + z * mat[10];
      return this;
    };
    proto.transformCoord = function(mat4) {
      var v = new cc.math.Vec4(this.x, this.y, this.z, 1);
      v.transform(mat4);
      this.x = v.x / v.w;
      this.y = v.y / v.w;
      this.z = v.z / v.w;
      return this;
    };
    proto.scale = function(scale) {
      this.x *= scale;
      this.y *= scale;
      this.z *= scale;
      return this;
    };
    proto.equals = function(vec) {
      var EPSILON = cc.math.EPSILON;
      return this.x < vec.x + EPSILON && this.x > vec.x - EPSILON && this.y < vec.y + EPSILON && this.y > vec.y - EPSILON && this.z < vec.z + EPSILON && this.z > vec.z - EPSILON;
    };
    proto.inverseTransform = function(mat4) {
      var mat = mat4.mat;
      var v1 = new cc.math.Vec3(this.x - mat[12], this.y - mat[13], this.z - mat[14]);
      this.x = v1.x * mat[0] + v1.y * mat[1] + v1.z * mat[2];
      this.y = v1.x * mat[4] + v1.y * mat[5] + v1.z * mat[6];
      this.z = v1.x * mat[8] + v1.y * mat[9] + v1.z * mat[10];
      return this;
    };
    proto.inverseTransformNormal = function(mat4) {
      var x = this.x, y = this.y, z = this.z, mat = mat4.mat;
      this.x = x * mat[0] + y * mat[1] + z * mat[2];
      this.y = x * mat[4] + y * mat[5] + z * mat[6];
      this.z = x * mat[8] + y * mat[9] + z * mat[10];
      return this;
    };
    proto.assignFrom = function(vec) {
      if (!vec) return this;
      this.x = vec.x;
      this.y = vec.y;
      this.z = vec.z;
      return this;
    };
    cc.math.Vec3.zero = function(vec) {
      vec.x = vec.y = vec.z = 0;
      return vec;
    };
    proto.toTypeArray = function() {
      var tyArr = new Float32Array(3);
      tyArr[0] = this.x;
      tyArr[1] = this.y;
      tyArr[2] = this.z;
      return tyArr;
    };
  }), {} ],
  255: [ (function(require, module, exports) {
    cc.math.Vec4 = function(x, y, z, w) {
      if (x && void 0 === y) {
        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;
      }
    };
    var proto = cc.math.Vec4.prototype;
    proto.fill = function(x, y, z, w) {
      if (x && void 0 === y) {
        this.x = x.x;
        this.y = x.y;
        this.z = x.z;
        this.w = x.w;
      } else {
        this.x = x;
        this.y = y;
        this.z = z;
        this.w = w;
      }
    };
    proto.add = function(vec) {
      if (!vec) return this;
      this.x += vec.x;
      this.y += vec.y;
      this.z += vec.z;
      this.w += vec.w;
      return this;
    };
    proto.dot = function(vec) {
      return this.x * vec.x + this.y * vec.y + this.z * vec.z + this.w * vec.w;
    };
    proto.length = function() {
      return Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z) + cc.math.square(this.w));
    };
    proto.lengthSq = function() {
      return cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z) + cc.math.square(this.w);
    };
    proto.lerp = function(vec, t) {
      return this;
    };
    proto.normalize = function() {
      var l = 1 / this.length();
      this.x *= l;
      this.y *= l;
      this.z *= l;
      this.w *= l;
      return this;
    };
    proto.scale = function(scale) {
      this.normalize();
      this.x *= scale;
      this.y *= scale;
      this.z *= scale;
      this.w *= scale;
      return this;
    };
    proto.subtract = function(vec) {
      this.x -= vec.x;
      this.y -= vec.y;
      this.z -= vec.z;
      this.w -= vec.w;
    };
    proto.transform = function(mat4) {
      var x = this.x, y = this.y, z = this.z, w = this.w, mat = mat4.mat;
      this.x = x * mat[0] + y * mat[4] + z * mat[8] + w * mat[12];
      this.y = x * mat[1] + y * mat[5] + z * mat[9] + w * mat[13];
      this.z = x * mat[2] + y * mat[6] + z * mat[10] + w * mat[14];
      this.w = x * mat[3] + y * mat[7] + z * mat[11] + w * mat[15];
      return this;
    };
    cc.math.Vec4.transformArray = function(vecArray, mat4) {
      var retArray = [];
      for (var i = 0; i < vecArray.length; i++) {
        var selVec = new cc.math.Vec4(vecArray[i]);
        selVec.transform(mat4);
        retArray.push(selVec);
      }
      return retArray;
    };
    proto.equals = function(vec) {
      var EPSILON = cc.math.EPSILON;
      return this.x < vec.x + EPSILON && this.x > vec.x - EPSILON && this.y < vec.y + EPSILON && this.y > vec.y - EPSILON && this.z < vec.z + EPSILON && this.z > vec.z - EPSILON && this.w < vec.w + EPSILON && this.w > vec.w - EPSILON;
    };
    proto.assignFrom = function(vec) {
      this.x = vec.x;
      this.y = vec.y;
      this.z = vec.z;
      this.w = vec.w;
      return this;
    };
    proto.toTypeArray = function() {
      var tyArr = new Float32Array(4);
      tyArr[0] = this.x;
      tyArr[1] = this.y;
      tyArr[2] = this.z;
      tyArr[3] = this.w;
      return tyArr;
    };
  }), {} ],
  256: [ (function(require, module, exports) {
    require("./CCSGMotionStreak");
    require("./CCSGMotionStreakWebGLRenderCmd");
    var MotionStreak = cc.Class({
      name: "cc.MotionStreak",
      extends: cc.Component,
      editor: false,
      ctor: function() {
        this._root = null;
        this._motionStreak = null;
      },
      properties: {
        preview: {
          default: false,
          editorOnly: true,
          notify: false,
          animatable: false
        },
        _fadeTime: 1,
        fadeTime: {
          get: function() {
            return this._fadeTime;
          },
          set: function(value) {
            this._fadeTime = value;
            this._motionStreak && this._motionStreak.setFadeTime(value);
          },
          animatable: false,
          tooltip: false
        },
        _minSeg: 1,
        minSeg: {
          get: function() {
            return this._minSeg;
          },
          set: function(value) {
            this._minSeg = value;
            this._motionStreak && this._motionStreak.setMinSeg(value);
          },
          animatable: false,
          tooltip: false
        },
        _stroke: 64,
        stroke: {
          get: function() {
            return this._stroke;
          },
          set: function(value) {
            this._stroke = value;
            this._motionStreak && this._motionStreak.setStroke(value);
          },
          animatable: false,
          tooltip: false
        },
        _texture: {
          default: "",
          url: cc.Texture2D
        },
        texture: {
          get: function() {
            return this._texture;
          },
          set: function(value) {
            this._texture = value;
            if (this._motionStreak) {
              value && cc.js.isString(value) && (value = cc.textureCache.addImage(value));
              this._motionStreak.setTexture(value);
            }
          },
          url: cc.Texture2D,
          animatable: false,
          tooltip: false
        },
        _color: cc.Color.WHITE,
        color: {
          get: function() {
            return this._color;
          },
          set: function(value) {
            this._color = value;
            this._motionStreak && this._motionStreak.tintWithColor(value);
          },
          tooltip: false
        },
        _fastMode: false,
        fastMode: {
          get: function() {
            return this._fastMode;
          },
          set: function(value) {
            this._fastMode = value;
            this._motionStreak && this._motionStreak.setFastMode(value);
          },
          animatable: false,
          tooltip: false
        }
      },
      onFocusInEditor: false,
      onLostFocusInEditor: false,
      reset: function() {
        this._motionStreak.reset();
      },
      __preload: function() {
        if (cc._renderType !== cc.game.RENDER_TYPE_WEBGL && true) {
          cc.warnID(5900);
          return;
        }
        this._root = new _ccsg.Node();
        var motionStreak = new _ccsg.MotionStreak();
        motionStreak.initWithFade(this._fadeTime, this._minSeg, this._stroke, this.node.color, this._texture || null);
        motionStreak.setFastMode(this._fastMode);
        this._root.addChild(motionStreak);
        var sgNode = this.node._sgNode;
        sgNode && sgNode.addChild(this._root, -10);
        this._motionStreak = motionStreak;
      },
      onEnable: function() {
        this.node.on("position-changed", this._onNodePositionChanged, this);
      },
      onDisable: function() {
        this.node.off("position-changed", this._onNodePositionChanged, this);
      },
      _onNodePositionChanged: function() {
        false;
        if (this._motionStreak) {
          var node = this.node;
          var worldMt = node.getNodeToWorldTransform();
          var tx = worldMt.tx - (node.width / 2 + node.anchorX * node.width);
          var ty = worldMt.ty - (node.height / 2 + node.anchorY * node.height);
          this._root.setPosition(-tx, -ty);
          this._motionStreak.setPosition(tx, ty);
        }
      }
    });
    cc.MotionStreak = module.exports = MotionStreak;
  }), {
    "./CCSGMotionStreak": 257,
    "./CCSGMotionStreakWebGLRenderCmd": 258
  } ],
  257: [ (function(require, module, exports) {
    function vertexLineToPolygon(points, stroke, vertices, offset, nuPoints) {
      nuPoints += offset;
      if (nuPoints <= 1) return;
      stroke *= .5;
      var idx;
      var nuPointsMinus = nuPoints - 1;
      for (var i = offset; i < nuPoints; i++) {
        idx = 2 * i;
        var p1 = cc.p(points[2 * i], points[2 * i + 1]);
        var perpVector;
        if (0 === i) perpVector = cc.pPerp(cc.pNormalize(cc.pSub(p1, cc.p(points[2 * (i + 1)], points[2 * (i + 1) + 1])))); else if (i === nuPointsMinus) perpVector = cc.pPerp(cc.pNormalize(cc.pSub(cc.p(points[2 * (i - 1)], points[2 * (i - 1) + 1]), p1))); else {
          var p0 = cc.p(points[2 * (i - 1)], points[2 * (i - 1) + 1]);
          var p2 = cc.p(points[2 * (i + 1)], points[2 * (i + 1) + 1]);
          var p2p1 = cc.pNormalize(cc.pSub(p2, p1));
          var p0p1 = cc.pNormalize(cc.pSub(p0, p1));
          var angle = Math.acos(cc.pDot(p2p1, p0p1));
          perpVector = angle < cc.degreesToRadians(70) ? cc.pPerp(cc.pNormalize(cc.pMidpoint(p2p1, p0p1))) : angle < cc.degreesToRadians(170) ? cc.pNormalize(cc.pMidpoint(p2p1, p0p1)) : cc.pPerp(cc.pNormalize(cc.pSub(p2, p0)));
        }
        perpVector = cc.pMult(perpVector, stroke);
        vertices[2 * idx] = p1.x + perpVector.x;
        vertices[2 * idx + 1] = p1.y + perpVector.y;
        vertices[2 * (idx + 1)] = p1.x - perpVector.x;
        vertices[2 * (idx + 1) + 1] = p1.y - perpVector.y;
      }
      offset = 0 === offset ? 0 : offset - 1;
      for (i = offset; i < nuPointsMinus; i++) {
        idx = 2 * i;
        var idx1 = idx + 2;
        var v1 = cc.v2(vertices[2 * idx], vertices[2 * idx + 1]);
        var v2 = cc.v2(vertices[2 * (idx + 1)], vertices[2 * (idx + 1) + 1]);
        var v3 = cc.v2(vertices[2 * idx1], vertices[2 * idx1 + 1]);
        var v4 = cc.v2(vertices[2 * (idx1 + 1)], vertices[2 * (idx1 + 1) + 1]);
        var fixVertexResult = vertexLineIntersect(v1.x, v1.y, v4.x, v4.y, v2.x, v2.y, v3.x, v3.y);
        var isSuccess = !fixVertexResult.isSuccess;
        isSuccess || (fixVertexResult.value < 0 || fixVertexResult.value > 1) && (isSuccess = true);
        if (isSuccess) {
          vertices[2 * idx1] = v4.x;
          vertices[2 * idx1 + 1] = v4.y;
          vertices[2 * (idx1 + 1)] = v3.x;
          vertices[2 * (idx1 + 1) + 1] = v3.y;
        }
      }
    }
    function vertexLineIntersect(Ax, Ay, Bx, By, Cx, Cy, Dx, Dy) {
      var distAB, theCos, theSin, newX;
      if (Ax === Bx && Ay === By || Cx === Dx && Cy === Dy) return {
        isSuccess: false,
        value: 0
      };
      Bx -= Ax;
      By -= Ay;
      Cx -= Ax;
      Cy -= Ay;
      Dx -= Ax;
      Dy -= Ay;
      distAB = Math.sqrt(Bx * Bx + By * By);
      theCos = Bx / distAB;
      theSin = By / distAB;
      newX = Cx * theCos + Cy * theSin;
      Cy = Cy * theCos - Cx * theSin;
      Cx = newX;
      newX = Dx * theCos + Dy * theSin;
      Dy = Dy * theCos - Dx * theSin;
      Dx = newX;
      if (Cy === Dy) return {
        isSuccess: false,
        value: 0
      };
      var t = (Dx + (Cx - Dx) * Dy / (Dy - Cy)) / distAB;
      return {
        isSuccess: true,
        value: t
      };
    }
    function vertexListIsClockwise(verts) {
      for (var i = 0, len = verts.length; i < len; i++) {
        var a = verts[i];
        var b = verts[(i + 1) % len];
        var c = verts[(i + 2) % len];
        if (cc.pCross(cc.pSub(b, a), cc.pSub(c, b)) > 0) return false;
      }
      return true;
    }
    _ccsg.MotionStreak = _ccsg.Node.extend({
      texture: null,
      fastMode: false,
      startingPositionInitialized: false,
      _blendFunc: null,
      _stroke: 0,
      _fadeDelta: 0,
      _minSeg: 0,
      _maxPoints: 0,
      _nuPoints: 0,
      _previousNuPoints: 0,
      _pointVertexes: null,
      _pointState: null,
      _vertices: null,
      _colorPointer: null,
      _texCoords: null,
      _verticesBuffer: null,
      _colorPointerBuffer: null,
      _texCoordsBuffer: null,
      _className: "MotionStreak",
      ctor: function(fade, minSeg, stroke, color, texture) {
        _ccsg.Node.prototype.ctor.call(this);
        this._positionR = cc.p(0, 0);
        this._blendFunc = new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA);
        this.fastMode = false;
        this.startingPositionInitialized = false;
        this.texture = null;
        this._stroke = 0;
        this._fadeDelta = 0;
        this._minSeg = 0;
        this._maxPoints = 0;
        this._nuPoints = 0;
        this._previousNuPoints = 0;
        this._pointVertexes = null;
        this._pointState = null;
        this._vertices = null;
        this._colorPointer = null;
        this._texCoords = null;
        this._verticesBuffer = null;
        this._colorPointerBuffer = null;
        this._texCoordsBuffer = null;
        void 0 !== texture && this.initWithFade(fade, minSeg, stroke, color, texture);
      },
      initWithFade: function(fade, minSeg, stroke, color, texture) {
        cc.js.isString(texture) && (texture = cc.textureCache.addImage(texture));
        this.anchorX = 0;
        this.anchorY = 0;
        this.ignoreAnchor = true;
        this.startingPositionInitialized = false;
        this.fastMode = true;
        this._stroke = stroke;
        this.setMinSeg(minSeg);
        this.setFadeTime(fade);
        this._blendFunc.src = gl.SRC_ALPHA;
        this._blendFunc.dst = gl.ONE_MINUS_SRC_ALPHA;
        this.setTexture(texture);
        this.color = color;
        this.scheduleUpdate();
        return true;
      },
      getTexture: function() {
        return this.texture;
      },
      setTexture: function(texture) {
        this.texture !== texture && (this.texture = texture);
      },
      getBlendFunc: function() {
        return this._blendFunc;
      },
      setBlendFunc: function(src, dst) {
        if (void 0 === dst) this._blendFunc = src; else {
          this._blendFunc.src = src;
          this._blendFunc.dst = dst;
        }
      },
      getOpacity: function() {
        cc.logID(5901);
        return 0;
      },
      setOpacity: function(opacity) {
        cc.logID(5902);
      },
      setOpacityModifyRGB: function(value) {},
      isOpacityModifyRGB: function() {
        return false;
      },
      getFadeTime: function() {
        return 1 / this._fadeDelta;
      },
      setFadeTime: function(fade) {
        this._fadeDelta = 1 / fade;
        var locMaxPoints = 2 + (0 | 60 * fade);
        this._maxPoints = locMaxPoints;
        this._nuPoints = 0;
        this._pointState = new Float32Array(locMaxPoints);
        this._pointVertexes = new Float32Array(2 * locMaxPoints);
        this._vertices = new Float32Array(4 * locMaxPoints);
        this._texCoords = new Float32Array(4 * locMaxPoints);
        this._colorPointer = new Uint8Array(8 * locMaxPoints);
        this._verticesBuffer = gl.createBuffer();
        this._texCoordsBuffer = gl.createBuffer();
        this._colorPointerBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, this._verticesBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, this._vertices, gl.DYNAMIC_DRAW);
        gl.bindBuffer(gl.ARRAY_BUFFER, this._texCoordsBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, this._texCoords, gl.DYNAMIC_DRAW);
        gl.bindBuffer(gl.ARRAY_BUFFER, this._colorPointerBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, this._colorPointer, gl.DYNAMIC_DRAW);
      },
      getMinSeg: function() {
        return this._minSeg;
      },
      setMinSeg: function(minSeg) {
        this._minSeg = -1 === minSeg ? this._stroke / 5 : minSeg;
        this._minSeg *= this._minSeg;
      },
      isFastMode: function() {
        return this.fastMode;
      },
      setFastMode: function(fastMode) {
        this.fastMode = fastMode;
      },
      isStartingPositionInitialized: function() {
        return this.startingPositionInitialized;
      },
      setStartingPositionInitialized: function(startingPositionInitialized) {
        this.startingPositionInitialized = startingPositionInitialized;
      },
      getStroke: function() {
        return this._stroke;
      },
      setStroke: function(stroke) {
        this._stroke = stroke;
      },
      tintWithColor: function(color) {
        this.color = color;
        var locColorPointer = this._colorPointer;
        for (var i = 0, len = 2 * this._nuPoints; i < len; i++) {
          locColorPointer[4 * i] = color.r;
          locColorPointer[4 * i + 1] = color.g;
          locColorPointer[4 * i + 2] = color.b;
        }
      },
      reset: function() {
        this._nuPoints = 0;
      },
      setPosition: function(position, yValue) {
        this.startingPositionInitialized = true;
        if (void 0 === yValue) {
          this._positionR.x = position.x;
          this._positionR.y = position.y;
        } else {
          this._positionR.x = position;
          this._positionR.y = yValue;
        }
      },
      getPositionX: function() {
        return this._positionR.x;
      },
      setPositionX: function(x) {
        this._positionR.x = x;
        this.startingPositionInitialized || (this.startingPositionInitialized = true);
      },
      getPositionY: function() {
        return this._positionR.y;
      },
      setPositionY: function(y) {
        this._positionR.y = y;
        this.startingPositionInitialized || (this.startingPositionInitialized = true);
      },
      update: function(delta) {
        if (!this.startingPositionInitialized) return;
        delta *= this._fadeDelta;
        var newIdx, newIdx2, i, i2;
        var mov = 0;
        var locNuPoints = this._nuPoints;
        var locPointState = this._pointState, locPointVertexes = this._pointVertexes, locVertices = this._vertices;
        var locColorPointer = this._colorPointer;
        for (i = 0; i < locNuPoints; i++) {
          locPointState[i] -= delta;
          if (locPointState[i] <= 0) mov++; else {
            newIdx = i - mov;
            if (mov > 0) {
              locPointState[newIdx] = locPointState[i];
              locPointVertexes[2 * newIdx] = locPointVertexes[2 * i];
              locPointVertexes[2 * newIdx + 1] = locPointVertexes[2 * i + 1];
              i2 = 2 * i;
              newIdx2 = 2 * newIdx;
              locVertices[2 * newIdx2] = locVertices[2 * i2];
              locVertices[2 * newIdx2 + 1] = locVertices[2 * i2 + 1];
              locVertices[2 * (newIdx2 + 1)] = locVertices[2 * (i2 + 1)];
              locVertices[2 * (newIdx2 + 1) + 1] = locVertices[2 * (i2 + 1) + 1];
              i2 *= 4;
              newIdx2 *= 4;
              locColorPointer[newIdx2 + 0] = locColorPointer[i2 + 0];
              locColorPointer[newIdx2 + 1] = locColorPointer[i2 + 1];
              locColorPointer[newIdx2 + 2] = locColorPointer[i2 + 2];
              locColorPointer[newIdx2 + 4] = locColorPointer[i2 + 4];
              locColorPointer[newIdx2 + 5] = locColorPointer[i2 + 5];
              locColorPointer[newIdx2 + 6] = locColorPointer[i2 + 6];
            } else newIdx2 = 8 * newIdx;
            var op = 255 * locPointState[newIdx];
            locColorPointer[newIdx2 + 3] = op;
            locColorPointer[newIdx2 + 7] = op;
          }
        }
        locNuPoints -= mov;
        var appendNewPoint = true;
        if (locNuPoints >= this._maxPoints) appendNewPoint = false; else if (locNuPoints > 0) {
          var locPoint1 = cc.p(locPointVertexes[2 * (locNuPoints - 1)], locPointVertexes[2 * (locNuPoints - 1) + 1]);
          var a1 = cc.pDistanceSQ(locPoint1, this._positionR) < this._minSeg;
          var locPoint2 = cc.p(locPointVertexes[2 * (locNuPoints - 2)], locPointVertexes[2 * (locNuPoints - 2) + 1]);
          var a2 = 1 !== locNuPoints && cc.pDistanceSQ(locPoint2, this._positionR) < 2 * this._minSeg;
          (a1 || a2) && (appendNewPoint = false);
        }
        if (appendNewPoint) {
          locPointVertexes[2 * locNuPoints] = this._positionR.x;
          locPointVertexes[2 * locNuPoints + 1] = this._positionR.y;
          locPointState[locNuPoints] = 1;
          var offset = 8 * locNuPoints;
          var locDisplayedColor = this.getDisplayedColor();
          locColorPointer[offset] = locDisplayedColor.r;
          locColorPointer[offset + 1] = locDisplayedColor.g;
          locColorPointer[offset + 2] = locDisplayedColor.b;
          locColorPointer[offset + 4] = locDisplayedColor.r;
          locColorPointer[offset + 5] = locDisplayedColor.g;
          locColorPointer[offset + 6] = locDisplayedColor.b;
          locColorPointer[offset + 3] = 255;
          locColorPointer[offset + 7] = 255;
          locNuPoints > 0 && this.fastMode && (locNuPoints > 1 ? vertexLineToPolygon(locPointVertexes, this._stroke, this._vertices, locNuPoints, 1) : vertexLineToPolygon(locPointVertexes, this._stroke, this._vertices, 0, 2));
          locNuPoints++;
        }
        this.fastMode || vertexLineToPolygon(locPointVertexes, this._stroke, this._vertices, 0, locNuPoints);
        if (locNuPoints && this._previousNuPoints !== locNuPoints) {
          var texDelta = 1 / locNuPoints;
          var locTexCoords = this._texCoords;
          for (i = 0; i < locNuPoints; i++) {
            locTexCoords[4 * i] = 0;
            locTexCoords[4 * i + 1] = texDelta * i;
            locTexCoords[2 * (2 * i + 1)] = 1;
            locTexCoords[2 * (2 * i + 1) + 1] = texDelta * i;
          }
          this._previousNuPoints = locNuPoints;
        }
        this._nuPoints = locNuPoints;
      },
      _createRenderCmd: function() {
        return cc._renderType === cc.game.RENDER_TYPE_WEBGL ? new _ccsg.MotionStreak.WebGLRenderCmd(this) : null;
      }
    });
    var motionStreakPro = _ccsg.MotionStreak.prototype;
    Object.defineProperty(motionStreakPro, "x", {
      get: motionStreakPro.getPositionX,
      set: motionStreakPro.setPositionX
    });
    Object.defineProperty(motionStreakPro, "y", {
      get: motionStreakPro.getPositionY,
      set: motionStreakPro.setPositionY
    });
  }), {} ],
  258: [ (function(require, module, exports) {
    _ccsg.MotionStreak.WebGLRenderCmd = function(renderableObject) {
      this._rootCtor(renderableObject);
      this._needDraw = true;
      this._matrix = new cc.math.Matrix4();
      this._matrix.identity();
      this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURECOLOR);
    };
    _ccsg.MotionStreak.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype);
    _ccsg.MotionStreak.WebGLRenderCmd.prototype.constructor = _ccsg.Sprite.WebGLRenderCmd;
    _ccsg.MotionStreak.WebGLRenderCmd.prototype.rendering = function(ctx) {
      var node = this._node;
      if (node._nuPoints <= 1) return;
      if (node.texture && node.texture.isLoaded()) {
        ctx = ctx || cc._renderContext;
        this._updateDisplayColor();
        var wt = this._worldTransform, mat = this._matrix.mat;
        mat[0] = wt.a;
        mat[4] = wt.c;
        mat[12] = wt.tx;
        mat[1] = wt.b;
        mat[5] = wt.d;
        mat[13] = wt.ty;
        this._shaderProgram.use();
        this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix);
        cc.gl.blendFunc(node._blendFunc.src, node._blendFunc.dst);
        cc.gl.bindTexture2DN(0, node.texture);
        ctx.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION);
        ctx.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR);
        ctx.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS);
        ctx.bindBuffer(ctx.ARRAY_BUFFER, node._verticesBuffer);
        ctx.bufferData(ctx.ARRAY_BUFFER, node._vertices, ctx.DYNAMIC_DRAW);
        ctx.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 2, ctx.FLOAT, false, 0, 0);
        ctx.bindBuffer(ctx.ARRAY_BUFFER, node._texCoordsBuffer);
        ctx.bufferData(ctx.ARRAY_BUFFER, node._texCoords, ctx.DYNAMIC_DRAW);
        ctx.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_TEX_COORDS, 2, ctx.FLOAT, false, 0, 0);
        ctx.bindBuffer(ctx.ARRAY_BUFFER, node._colorPointerBuffer);
        ctx.bufferData(ctx.ARRAY_BUFFER, node._colorPointer, ctx.DYNAMIC_DRAW);
        ctx.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, ctx.UNSIGNED_BYTE, true, 0, 0);
        ctx.drawArrays(ctx.TRIANGLE_STRIP, 0, 2 * node._nuPoints);
        cc.g_NumberOfDraws++;
      }
    };
  }), {} ],
  259: [ (function(require, module, exports) {
    var Zlib = require("../compression/zlib.min");
    var PNGReader = cc._Class.extend({
      ctor: function(data) {
        var chunkSize, colors, delayDen, delayNum, frame, i, index, key, section, ccshort, text, _i, _j, _ref;
        this.data = data;
        this.pos = 8;
        this.palette = [];
        this.imgData = [];
        this.transparency = {};
        this.animation = null;
        this.text = {};
        frame = null;
        while (true) {
          chunkSize = this.readUInt32();
          section = function() {
            var _i, _results;
            _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":
            frame && this.animation.frames.push(frame);
            this.pos += 4;
            frame = {
              width: this.readUInt32(),
              height: this.readUInt32(),
              xOffset: this.readUInt32(),
              yOffset: this.readUInt32()
            };
            delayNum = this.readUInt16();
            delayDen = this.readUInt16() || 100;
            frame.delay = 1e3 * delayNum / delayDen;
            frame.disposeOp = this.data[this.pos++];
            frame.blendOp = this.data[this.pos++];
            frame.data = [];
            break;

           case "IDAT":
           case "fdAT":
            if ("fdAT" === section) {
              this.pos += 4;
              chunkSize -= 4;
            }
            data = (null != frame ? frame.data : void 0) || this.imgData;
            for (i = _i = 0; 0 <= chunkSize ? _i < chunkSize : _i > chunkSize; i = 0 <= chunkSize ? ++_i : --_i) data.push(this.data[this.pos++]);
            break;

           case "tRNS":
            this.transparency = {};
            switch (this.colorType) {
             case 3:
              this.transparency.indexed = this.read(chunkSize);
              ccshort = 255 - this.transparency.indexed.length;
              if (ccshort > 0) for (i = _j = 0; 0 <= ccshort ? _j < ccshort : _j > ccshort; i = 0 <= ccshort ? ++_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":
            text = this.read(chunkSize);
            index = text.indexOf(0);
            key = String.fromCharCode.apply(String, text.slice(0, index));
            this.text[key] = String.fromCharCode.apply(String, text.slice(index + 1));
            break;

           case "IEND":
            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);
            this.hasAlphaChannel = 4 === (_ref = this.colorType) || 6 === _ref;
            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);
            Uint8Array != Array && (this.imgData = new Uint8Array(this.imgData));
            return;

           default:
            this.pos += chunkSize;
          }
          this.pos += 4;
          if (this.pos > this.data.length) throw new Error("Incomplete or corrupt PNG file");
        }
      },
      read: function(bytes) {
        var i, _i, _results;
        _results = [];
        for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) _results.push(this.data[this.pos++]);
        return _results;
      },
      readUInt32: function() {
        var b1, b2, b3, b4;
        b1 = this.data[this.pos++] << 24;
        b2 = this.data[this.pos++] << 16;
        b3 = this.data[this.pos++] << 8;
        b4 = this.data[this.pos++];
        return b1 | b2 | b3 | b4;
      },
      readUInt16: function() {
        var b1, b2;
        b1 = this.data[this.pos++] << 8;
        b2 = this.data[this.pos++];
        return b1 | b2;
      },
      decodePixels: function(data) {
        var ccbyte, c, col, i, left, length, p, pa, paeth, pb, pc, pixelBytes, pixels, pos, row, scanlineLength, upper, upperLeft, _i, _j, _k, _l, _m;
        null == data && (data = this.imgData);
        if (0 === data.length) return new Uint8Array(0);
        var inflate = new Zlib.Inflate(data, {
          index: 0,
          verify: false
        });
        data = inflate.decompress();
        pixelBytes = this.pixelBitlength / 8;
        scanlineLength = pixelBytes * this.width;
        pixels = new Uint8Array(scanlineLength * this.height);
        length = data.length;
        row = 0;
        pos = 0;
        c = 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 (0 === row) 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);
              paeth = pa <= pb && pa <= pc ? left : pb <= pc ? upper : upperLeft;
              pixels[c++] = (ccbyte + paeth) % 256;
            }
            break;

           default:
            throw new Error("Invalid filter algorithm: " + data[pos - 1]);
          }
          row++;
        }
        return pixels;
      },
      copyToImageData: function(imageData, pixels) {
        var alpha, colors, data, i, input, j, k, length, palette, v, _ref;
        colors = this.colors;
        palette = null;
        alpha = this.hasAlphaChannel;
        if (this.palette.length) {
          palette = null != (_ref = this._decodedPalette) ? _ref : this._decodedPalette = this.decodePalette();
          colors = 4;
          alpha = true;
        }
        data = imageData.data || imageData;
        length = data.length;
        input = palette || pixels;
        i = j = 0;
        if (1 === colors) while (i < length) {
          k = palette ? 4 * pixels[i / 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 ? 4 * pixels[i / 4] : j;
          data[i++] = input[k++];
          data[i++] = input[k++];
          data[i++] = input[k++];
          data[i++] = alpha ? input[k++] : 255;
          j = k;
        }
      },
      decodePalette: function() {
        var c, i, palette, pos, ret, transparency, _i, _ref, _ref1;
        palette = this.palette;
        transparency = this.transparency.indexed || [];
        ret = new Uint8Array((transparency.length || 0) + palette.length);
        pos = 0;
        c = 0;
        for (i = _i = 0, _ref = palette.length; _i < _ref; i = _i += 3) {
          ret[pos++] = palette[i];
          ret[pos++] = palette[i + 1];
          ret[pos++] = palette[i + 2];
          ret[pos++] = null != (_ref1 = transparency[c++]) ? _ref1 : 255;
        }
        return ret;
      },
      render: function(canvas) {
        var ctx, data;
        canvas.width = this.width;
        canvas.height = this.height;
        ctx = canvas.getContext("2d");
        data = ctx.createImageData(this.width, this.height);
        this.copyToImageData(data, this.decodePixels());
        return ctx.putImageData(data, 0, 0);
      }
    });
    module.exports = PNGReader;
  }), {
    "../compression/zlib.min": 31
  } ],
  260: [ (function(require, module, exports) {
    var ParticleAsset = cc.Class({
      name: "cc.ParticleAsset",
      extends: cc.RawAsset
    });
    cc.ParticleAsset = module.exports = ParticleAsset;
  }), {} ],
  261: [ (function(require, module, exports) {
    require("./CCParticleAsset");
    require("./CCSGParticleSystem");
    require("./CCSGParticleSystemCanvasRenderCmd");
    require("./CCSGParticleSystemWebGLRenderCmd");
    var BlendFactor = cc.BlendFunc.BlendFactor;
    var EmitterMode = cc.Enum({
      GRAVITY: 0,
      RADIUS: 1
    });
    var PositionType = cc.Enum({
      FREE: 0,
      RELATIVE: 1,
      GROUPED: 2
    });
    var properties = {
      preview: {
        default: true,
        editorOnly: true,
        notify: false,
        animatable: false,
        tooltip: false
      },
      _custom: false,
      custom: {
        get: function() {
          return this._custom;
        },
        set: function(value) {
          false;
          if (this._custom !== value) {
            this._custom = value;
            value ? this._applyCustoms() : this._applyFile();
            false;
          }
        },
        animatable: false,
        tooltip: false
      },
      _file: {
        default: "",
        url: cc.ParticleAsset
      },
      file: {
        get: function() {
          return this._file;
        },
        set: function(value, force) {
          if (this._file !== value || false) {
            this._file = value;
            if (value) {
              this._applyFile();
              false;
            } else this.custom = true;
          }
        },
        animatable: false,
        url: cc.ParticleAsset,
        tooltip: false
      },
      _texture: {
        default: "",
        url: cc.Texture2D
      },
      texture: {
        get: function() {
          return this._texture;
        },
        set: function(value) {
          this._texture = value;
          this._sgNode.texture = value ? cc.textureCache.addImage(value) : null;
          !value && this._file && this._applyFile();
        },
        url: cc.Texture2D,
        tooltip: false
      },
      particleCount: {
        get: function() {
          return this._sgNode.particleCount;
        },
        set: function(value) {
          this._sgNode.particleCount = value;
        },
        visible: false,
        tooltip: false
      },
      _srcBlendFactor: BlendFactor.SRC_ALPHA,
      srcBlendFactor: {
        get: function() {
          return this._srcBlendFactor;
        },
        set: function(value) {
          this._srcBlendFactor = value;
          this._blendFunc.src = value;
          this._sgNode.setBlendFunc(this._blendFunc);
        },
        animatable: false,
        type: BlendFactor,
        tooltip: false
      },
      _dstBlendFactor: BlendFactor.ONE_MINUS_SRC_ALPHA,
      dstBlendFactor: {
        get: function() {
          return this._dstBlendFactor;
        },
        set: function(value) {
          this._dstBlendFactor = value;
          this._blendFunc.dst = value;
          this._sgNode.setBlendFunc(this._blendFunc);
        },
        animatable: false,
        type: BlendFactor,
        tooltip: false
      },
      playOnLoad: true,
      _autoRemoveOnFinish: false,
      autoRemoveOnFinish: {
        get: function() {
          return this._autoRemoveOnFinish;
        },
        set: function(value) {
          if (this._autoRemoveOnFinish !== value) {
            this._autoRemoveOnFinish = value;
            true;
            this._applyAutoRemove();
          }
        },
        animatable: false,
        tooltip: false
      },
      active: {
        get: function() {
          return !!this._sgNode && this._sgNode.isActive();
        },
        visible: false
      }
    };
    var CustomProps = (function() {
      var DefaultValues = {
        totalParticles: 150,
        duration: -1,
        emissionRate: 10,
        life: 1,
        lifeVar: 0,
        startColor: cc.Color.WHITE,
        startColorVar: cc.Color.BLACK,
        endColor: cc.color(255, 255, 255, 0),
        endColorVar: cc.color(0, 0, 0, 0),
        angle: 90,
        angleVar: 20,
        startSize: 50,
        startSizeVar: 0,
        endSize: 0,
        endSizeVar: 0,
        startSpin: 0,
        startSpinVar: 0,
        endSpin: 0,
        endSpinVar: 0,
        sourcePos: cc.p(0, 0),
        posVar: cc.p(0, 0),
        positionType: PositionType.FREE,
        emitterMode: EmitterMode.GRAVITY,
        gravity: cc.p(0, 0),
        speed: 180,
        speedVar: 50,
        tangentialAccel: 80,
        tangentialAccelVar: 0,
        radialAccel: 0,
        radialAccelVar: 0,
        rotationIsDir: false,
        startRadius: 0,
        startRadiusVar: 0,
        endRadius: 0,
        endRadiusVar: 0,
        rotatePerS: 0,
        rotatePerSVar: 0
      };
      var props = Object.keys(DefaultValues);
      for (var i = 0; i < props.length; ++i) {
        var prop = props[i];
        (function(prop, defaultValue) {
          var internalProp = "_" + prop;
          properties[internalProp] = defaultValue;
          var type = defaultValue.constructor;
          var propDef = properties[prop] = {};
          if (cc.isChildClassOf(type, cc.ValueType)) {
            propDef.get = function() {
              return new type(this[internalProp]);
            };
            propDef.type = type;
          } else propDef.get = function() {
            return this[internalProp];
          };
          if (cc.isChildClassOf(type, cc.ValueType)) propDef.set = function(value) {
            this[internalProp] = new type(value);
            this._sgNode[prop] = value;
          }; else {
            false;
            propDef.set = function(value) {
              this[internalProp] = value;
              this._sgNode[prop] = value;
            };
          }
        })(prop, DefaultValues[prop]);
      }
      return props;
    })();
    properties.positionType.type = PositionType;
    properties.emitterMode.type = EmitterMode;
    var ParticleSystem = cc.Class({
      name: "cc.ParticleSystem",
      extends: cc._RendererUnderSG,
      editor: false,
      ctor: function() {
        this._previewTimer = null;
        this._focused = false;
        this._willStart = false;
        this._blendFunc = new cc.BlendFunc(0, 0);
        this._originOnExit = null;
      },
      properties: properties,
      statics: {
        DURATION_INFINITY: -1,
        START_SIZE_EQUAL_TO_END_SIZE: -1,
        START_RADIUS_EQUAL_TO_END_RADIUS: -1,
        EmitterMode: EmitterMode,
        PositionType: PositionType
      },
      __preload: function() {
        this._super();
        true;
        this.playOnLoad && this.resetSystem();
        this._applyAutoRemove();
      },
      onDestroy: function() {
        this._autoRemoveOnFinish && (this.autoRemoveOnFinish = false);
        this._super();
      },
      onFocusInEditor: false,
      onLostFocusInEditor: false,
      _createSgNode: function() {
        return new _ccsg.ParticleSystem();
      },
      _initSgNode: function() {
        var sgNode = this._sgNode;
        if (this._file) if (this._custom) {
          var missCustomTexture = !this._texture;
          missCustomTexture ? this._applyFile() : this._applyCustoms();
        } else this._applyFile(); else this._custom && this._applyCustoms();
        sgNode.stopSystem();
      },
      addParticle: function() {
        return this._sgNode.addParticle();
      },
      stopSystem: function() {
        this._sgNode.stopSystem();
      },
      resetSystem: function() {
        this._sgNode.resetSystem();
      },
      isFull: function() {
        return this.particleCount >= this._totalParticles;
      },
      setDisplayFrame: function(spriteFrame) {
        if (!spriteFrame) return;
        var texture = spriteFrame.getTexture();
        texture && (this._texture = texture.url);
        this._sgNode.setDisplayFrame(spriteFrame);
      },
      setTextureWithRect: function(texture, rect) {
        texture instanceof cc.Texture2D && (this._texture = texture.url);
        this._sgNode.setTextureWithRect(texture, rect);
      },
      _applyFile: function() {
        var file = this._file;
        if (file) {
          var self = this;
          cc.loader.load(file, (function(err, content) {
            if (err || !content) throw err || new Error("Unkown error");
            if (!self.isValid) return;
            var sgNode = self._sgNode;
            sgNode.particleCount = 0;
            var active = sgNode.isActive();
            false;
            sgNode.initWithFile(file);
            content.textureUuid && cc.AssetLibrary.queryAssetInfo(content.textureUuid, (function(err, url, raw) {
              if (err) {
                cc.error(err);
                return;
              }
              self.texture = url;
            }));
            content.emissionRate && (self.emissionRate = content.emissionRate);
            sgNode.setPosition(0, 0);
            active || sgNode.stopSystem();
            true;
            self._applyAutoRemove();
            self._custom && self._applyCustoms();
          }));
        }
      },
      _applyCustoms: function() {
        var sgNode = this._sgNode;
        var active = sgNode.isActive();
        for (var i = 0; i < CustomProps.length; i++) {
          var prop = CustomProps[i];
          sgNode[prop] = this["_" + prop];
        }
        this._blendFunc.src = this._srcBlendFactor;
        this._blendFunc.dst = this._dstBlendFactor;
        sgNode.setBlendFunc(this._blendFunc);
        this._texture && (sgNode.texture = cc.textureCache.addImage(this._texture));
        active || sgNode.stopSystem();
        true;
        this._applyAutoRemove();
      },
      _applyAutoRemove: function() {
        var sgNode = this._sgNode;
        var autoRemove = this._autoRemoveOnFinish;
        sgNode.autoRemoveOnFinish = autoRemove;
        if (autoRemove) {
          if (this._originOnExit) return;
          this._originOnExit = sgNode.onExit;
          var self = this;
          sgNode.onExit = function() {
            self._originOnExit.call(this);
            self.node.destroy();
          };
        } else if (this._originOnExit) {
          sgNode.onExit = this._originOnExit;
          this._originOnExit = null;
        }
      }
    });
    cc.ParticleSystem = module.exports = ParticleSystem;
  }), {
    "./CCParticleAsset": 260,
    "./CCSGParticleSystem": 262,
    "./CCSGParticleSystemCanvasRenderCmd": 263,
    "./CCSGParticleSystemWebGLRenderCmd": 264
  } ],
  262: [ (function(require, module, exports) {
    var PNGReader = require("./CCPNGReader");
    var tiffReader = require("./CCTIFFReader");
    require("../compression/ZipUtils");
    cc.Particle = function(pos, startPos, color, deltaColor, size, deltaSize, rotation, deltaRotation, timeToLive, modeA, modeB) {
      this.pos = pos || cc.v2(0, 0);
      this.startPos = startPos || cc.v2(0, 0);
      this.color = color || cc.color(0, 0, 0, 255);
      this.deltaColor = deltaColor || {
        r: 0,
        g: 0,
        b: 0,
        a: 255
      };
      this.size = size || 0;
      this.deltaSize = deltaSize || 0;
      this.rotation = rotation || 0;
      this.deltaRotation = deltaRotation || 0;
      this.timeToLive = timeToLive || 0;
      this.modeA = modeA || new cc.Particle.ModeA();
      this.modeB = modeB || new cc.Particle.ModeB();
      this.isChangeColor = false;
      this.drawPos = cc.p(0, 0);
    };
    cc.Particle.ModeA = function(dir, radialAccel, tangentialAccel) {
      this.dir = dir || cc.p(0, 0);
      this.radialAccel = radialAccel || 0;
      this.tangentialAccel = tangentialAccel || 0;
    };
    cc.Particle.ModeB = function(angle, degreesPerSecond, radius, deltaRadius) {
      this.angle = angle || 0;
      this.degreesPerSecond = degreesPerSecond || 0;
      this.radius = radius || 0;
      this.deltaRadius = deltaRadius || 0;
    };
    cc.Particle.TemporaryPoints = [ cc.p(), cc.p(), cc.p(), cc.p() ];
    _ccsg.ParticleSystem = _ccsg.Node.extend({
      _className: "ParticleSystem",
      _plistFile: "",
      _elapsed: 0,
      _dontTint: false,
      modeA: null,
      modeB: null,
      _pointZeroForParticle: cc.p(0, 0),
      _particles: null,
      _emitCounter: 0,
      _particleIdx: 0,
      _allocatedParticles: 0,
      _isActive: false,
      particleCount: 0,
      duration: 0,
      _sourcePosition: null,
      _posVar: null,
      life: 0,
      lifeVar: 0,
      angle: 0,
      angleVar: 0,
      startSize: 0,
      startSizeVar: 0,
      endSize: 0,
      endSizeVar: 0,
      _startColor: null,
      _startColorVar: null,
      _endColor: null,
      _endColorVar: null,
      startSpin: 0,
      startSpinVar: 0,
      endSpin: 0,
      endSpinVar: 0,
      emissionRate: 0,
      _totalParticles: 0,
      _texture: null,
      _blendFunc: null,
      _opacityModifyRGB: false,
      positionType: null,
      autoRemoveOnFinish: false,
      emitterMode: 0,
      _textureLoaded: null,
      ctor: function(plistFile) {
        _ccsg.Node.prototype.ctor.call(this);
        this.emitterMode = _ccsg.ParticleSystem.Mode.GRAVITY;
        this.modeA = new _ccsg.ParticleSystem.ModeA();
        this.modeB = new _ccsg.ParticleSystem.ModeB();
        this._blendFunc = {
          src: cc.macro.BLEND_SRC,
          dst: cc.macro.BLEND_DST
        };
        this._particles = [];
        this._sourcePosition = cc.p(0, 0);
        this._posVar = cc.p(0, 0);
        this._startColor = cc.color(255, 255, 255, 255);
        this._startColorVar = cc.color(255, 255, 255, 255);
        this._endColor = cc.color(255, 255, 255, 255);
        this._endColorVar = cc.color(255, 255, 255, 255);
        this._plistFile = "";
        this._elapsed = 0;
        this._dontTint = false;
        this._pointZeroForParticle = cc.p(0, 0);
        this._emitCounter = 0;
        this._particleIdx = 0;
        this._allocatedParticles = 0;
        this._isActive = false;
        this.particleCount = 0;
        this.duration = 0;
        this.life = 0;
        this.lifeVar = 0;
        this.angle = 0;
        this.angleVar = 0;
        this.startSize = 0;
        this.startSizeVar = 0;
        this.endSize = 0;
        this.endSizeVar = 0;
        this.startSpin = 0;
        this.startSpinVar = 0;
        this.endSpin = 0;
        this.endSpinVar = 0;
        this.emissionRate = 0;
        this._totalParticles = 0;
        this._texture = null;
        this._opacityModifyRGB = false;
        this.positionType = _ccsg.ParticleSystem.Type.FREE;
        this.autoRemoveOnFinish = false;
        this._textureLoaded = true;
        if (!plistFile || cc.js.isNumber(plistFile)) {
          var ton = plistFile || 100;
          this.initWithTotalParticles(ton);
        } else "string" === typeof plistFile ? this.initWithFile(plistFile) : "object" === typeof plistFile && this.initWithDictionary(plistFile, "");
      },
      _createRenderCmd: function() {
        return cc._renderType === cc.game.RENDER_TYPE_CANVAS ? new _ccsg.ParticleSystem.CanvasRenderCmd(this) : new _ccsg.ParticleSystem.WebGLRenderCmd(this);
      },
      ignoreColor: function(ignore) {
        this._dontTint = ignore;
      },
      initTexCoordsWithRect: function(pointRect) {
        this._renderCmd.initTexCoordsWithRect(pointRect);
      },
      isActive: function() {
        return this._isActive;
      },
      getParticleCount: function() {
        return this.particleCount;
      },
      setParticleCount: function(particleCount) {
        this.particleCount = particleCount;
      },
      getDuration: function() {
        return this.duration;
      },
      setDuration: function(duration) {
        this.duration = duration;
      },
      getSourcePosition: function() {
        return {
          x: this._sourcePosition.x,
          y: this._sourcePosition.y
        };
      },
      setSourcePosition: function(sourcePosition) {
        this._sourcePosition.x = sourcePosition.x;
        this._sourcePosition.y = sourcePosition.y;
      },
      getPosVar: function() {
        return {
          x: this._posVar.x,
          y: this._posVar.y
        };
      },
      setPosVar: function(posVar) {
        this._posVar.x = posVar.x;
        this._posVar.y = posVar.y;
      },
      getLife: function() {
        return this.life;
      },
      setLife: function(life) {
        this.life = life;
      },
      getLifeVar: function() {
        return this.lifeVar;
      },
      setLifeVar: function(lifeVar) {
        this.lifeVar = lifeVar;
      },
      getAngle: function() {
        return this.angle;
      },
      setAngle: function(angle) {
        this.angle = angle;
      },
      getAngleVar: function() {
        return this.angleVar;
      },
      setAngleVar: function(angleVar) {
        this.angleVar = angleVar;
      },
      getGravity: function() {
        var locGravity = this.modeA.gravity;
        return cc.p(locGravity.x, locGravity.y);
      },
      setGravity: function(gravity) {
        this.modeA.gravity = gravity;
      },
      getSpeed: function() {
        return this.modeA.speed;
      },
      setSpeed: function(speed) {
        this.modeA.speed = speed;
      },
      getSpeedVar: function() {
        return this.modeA.speedVar;
      },
      setSpeedVar: function(speedVar) {
        this.modeA.speedVar = speedVar;
      },
      getTangentialAccel: function() {
        return this.modeA.tangentialAccel;
      },
      setTangentialAccel: function(tangentialAccel) {
        this.modeA.tangentialAccel = tangentialAccel;
      },
      getTangentialAccelVar: function() {
        return this.modeA.tangentialAccelVar;
      },
      setTangentialAccelVar: function(tangentialAccelVar) {
        this.modeA.tangentialAccelVar = tangentialAccelVar;
      },
      getRadialAccel: function() {
        return this.modeA.radialAccel;
      },
      setRadialAccel: function(radialAccel) {
        this.modeA.radialAccel = radialAccel;
      },
      getRadialAccelVar: function() {
        return this.modeA.radialAccelVar;
      },
      setRadialAccelVar: function(radialAccelVar) {
        this.modeA.radialAccelVar = radialAccelVar;
      },
      getRotationIsDir: function() {
        return this.modeA.rotationIsDir;
      },
      setRotationIsDir: function(t) {
        this.modeA.rotationIsDir = t;
      },
      getStartRadius: function() {
        return this.modeB.startRadius;
      },
      setStartRadius: function(startRadius) {
        this.modeB.startRadius = startRadius;
      },
      getStartRadiusVar: function() {
        return this.modeB.startRadiusVar;
      },
      setStartRadiusVar: function(startRadiusVar) {
        this.modeB.startRadiusVar = startRadiusVar;
      },
      getEndRadius: function() {
        return this.modeB.endRadius;
      },
      setEndRadius: function(endRadius) {
        this.modeB.endRadius = endRadius;
      },
      getEndRadiusVar: function() {
        return this.modeB.endRadiusVar;
      },
      setEndRadiusVar: function(endRadiusVar) {
        this.modeB.endRadiusVar = endRadiusVar;
      },
      getRotatePerSecond: function() {
        return this.modeB.rotatePerSecond;
      },
      setRotatePerSecond: function(degrees) {
        this.modeB.rotatePerSecond = degrees;
      },
      getRotatePerSecondVar: function() {
        return this.modeB.rotatePerSecondVar;
      },
      setRotatePerSecondVar: function(degrees) {
        this.modeB.rotatePerSecondVar = degrees;
      },
      getStartSize: function() {
        return this.startSize;
      },
      setStartSize: function(startSize) {
        this.startSize = startSize;
      },
      getStartSizeVar: function() {
        return this.startSizeVar;
      },
      setStartSizeVar: function(startSizeVar) {
        this.startSizeVar = startSizeVar;
      },
      getEndSize: function() {
        return this.endSize;
      },
      setEndSize: function(endSize) {
        this.endSize = endSize;
      },
      getEndSizeVar: function() {
        return this.endSizeVar;
      },
      setEndSizeVar: function(endSizeVar) {
        this.endSizeVar = endSizeVar;
      },
      getStartColor: function() {
        return cc.color(this._startColor.r, this._startColor.g, this._startColor.b, this._startColor.a);
      },
      setStartColor: function(startColor) {
        this._startColor.fromColor(startColor);
      },
      getStartColorVar: function() {
        return cc.color(this._startColorVar.r, this._startColorVar.g, this._startColorVar.b, this._startColorVar.a);
      },
      setStartColorVar: function(startColorVar) {
        this._startColorVar.fromColor(startColorVar);
      },
      getEndColor: function() {
        return cc.color(this._endColor.r, this._endColor.g, this._endColor.b, this._endColor.a);
      },
      setEndColor: function(endColor) {
        this._endColor.fromColor(endColor);
      },
      getEndColorVar: function() {
        return cc.color(this._endColorVar.r, this._endColorVar.g, this._endColorVar.b, this._endColorVar.a);
      },
      setEndColorVar: function(endColorVar) {
        this._endColorVar.fromColor(endColorVar);
      },
      getStartSpin: function() {
        return this.startSpin;
      },
      setStartSpin: function(startSpin) {
        this.startSpin = startSpin;
      },
      getStartSpinVar: function() {
        return this.startSpinVar;
      },
      setStartSpinVar: function(startSpinVar) {
        this.startSpinVar = startSpinVar;
      },
      getEndSpin: function() {
        return this.endSpin;
      },
      setEndSpin: function(endSpin) {
        this.endSpin = endSpin;
      },
      getEndSpinVar: function() {
        return this.endSpinVar;
      },
      setEndSpinVar: function(endSpinVar) {
        this.endSpinVar = endSpinVar;
      },
      getEmissionRate: function() {
        return this.emissionRate;
      },
      setEmissionRate: function(emissionRate) {
        this.emissionRate = emissionRate;
      },
      getTotalParticles: function() {
        return this._totalParticles;
      },
      setTotalParticles: function(tp) {
        this._renderCmd.setTotalParticles(tp);
      },
      getTexture: function() {
        return this._texture;
      },
      setTexture: function(texture) {
        if (!texture) return;
        if (texture.loaded) this.setTextureWithRect(texture, cc.rect(0, 0, texture.width, texture.height)); else {
          this._textureLoaded = false;
          texture.once("load", (function(event) {
            this._textureLoaded = true;
            this.setTextureWithRect(texture, cc.rect(0, 0, texture.width, texture.height));
          }), this);
        }
      },
      getBlendFunc: function() {
        return this._blendFunc;
      },
      setBlendFunc: function(src, dst) {
        if (void 0 === dst) {
          if (this._blendFunc !== src) {
            this._blendFunc = src;
            this._updateBlendFunc();
          }
        } else if (this._blendFunc.src !== src || this._blendFunc.dst !== dst) {
          this._blendFunc = {
            src: src,
            dst: dst
          };
          this._updateBlendFunc();
        }
      },
      isOpacityModifyRGB: function() {
        return this._opacityModifyRGB;
      },
      setOpacityModifyRGB: function(newValue) {
        this._opacityModifyRGB = newValue;
      },
      isBlendAdditive: function() {
        return this._blendFunc.src === cc.macro.SRC_ALPHA && this._blendFunc.dst === cc.macro.ONE || this._blendFunc.src === cc.macro.ONE && this._blendFunc.dst === cc.macro.ONE;
      },
      setBlendAdditive: function(isBlendAdditive) {
        var locBlendFunc = this._blendFunc;
        if (isBlendAdditive) {
          locBlendFunc.src = cc.macro.SRC_ALPHA;
          locBlendFunc.dst = cc.macro.ONE;
        } else this._renderCmd._setBlendAdditive();
      },
      getPositionType: function() {
        return this.positionType;
      },
      setPositionType: function(positionType) {
        this.positionType = positionType;
      },
      isAutoRemoveOnFinish: function() {
        return this.autoRemoveOnFinish;
      },
      setAutoRemoveOnFinish: function(isAutoRemoveOnFinish) {
        this.autoRemoveOnFinish = isAutoRemoveOnFinish;
      },
      getEmitterMode: function() {
        return this.emitterMode;
      },
      setEmitterMode: function(emitterMode) {
        this.emitterMode = emitterMode;
      },
      init: function() {
        return this.initWithTotalParticles(150);
      },
      initWithFile: function(plistFile) {
        this._plistFile = plistFile;
        var dict = cc.loader.getRes(plistFile);
        if (!dict) {
          cc.logID(6008);
          return false;
        }
        return this.initWithDictionary(dict, "");
      },
      getBoundingBoxToWorld: function() {
        return cc.rect(0, 0, cc._canvas.width, cc._canvas.height);
      },
      initWithDictionary: function(dictionary, dirname) {
        var ret = false;
        var buffer = null;
        var image = null;
        var locValueForKey = this._valueForKey;
        var maxParticles = parseInt(locValueForKey("maxParticles", dictionary));
        if (this.initWithTotalParticles(maxParticles)) {
          this.angle = parseFloat(locValueForKey("angle", dictionary));
          this.angleVar = parseFloat(locValueForKey("angleVariance", dictionary));
          this.duration = parseFloat(locValueForKey("duration", dictionary));
          this._blendFunc.src = parseInt(locValueForKey("blendFuncSource", dictionary));
          this._blendFunc.dst = parseInt(locValueForKey("blendFuncDestination", dictionary));
          var locStartColor = this._startColor;
          locStartColor.r = 255 * parseFloat(locValueForKey("startColorRed", dictionary));
          locStartColor.g = 255 * parseFloat(locValueForKey("startColorGreen", dictionary));
          locStartColor.b = 255 * parseFloat(locValueForKey("startColorBlue", dictionary));
          locStartColor.a = 255 * parseFloat(locValueForKey("startColorAlpha", dictionary));
          var locStartColorVar = this._startColorVar;
          locStartColorVar.r = 255 * parseFloat(locValueForKey("startColorVarianceRed", dictionary));
          locStartColorVar.g = 255 * parseFloat(locValueForKey("startColorVarianceGreen", dictionary));
          locStartColorVar.b = 255 * parseFloat(locValueForKey("startColorVarianceBlue", dictionary));
          locStartColorVar.a = 255 * parseFloat(locValueForKey("startColorVarianceAlpha", dictionary));
          var locEndColor = this._endColor;
          locEndColor.r = 255 * parseFloat(locValueForKey("finishColorRed", dictionary));
          locEndColor.g = 255 * parseFloat(locValueForKey("finishColorGreen", dictionary));
          locEndColor.b = 255 * parseFloat(locValueForKey("finishColorBlue", dictionary));
          locEndColor.a = 255 * parseFloat(locValueForKey("finishColorAlpha", dictionary));
          var locEndColorVar = this._endColorVar;
          locEndColorVar.r = 255 * parseFloat(locValueForKey("finishColorVarianceRed", dictionary));
          locEndColorVar.g = 255 * parseFloat(locValueForKey("finishColorVarianceGreen", dictionary));
          locEndColorVar.b = 255 * parseFloat(locValueForKey("finishColorVarianceBlue", dictionary));
          locEndColorVar.a = 255 * parseFloat(locValueForKey("finishColorVarianceAlpha", dictionary));
          this.startSize = parseFloat(locValueForKey("startParticleSize", dictionary));
          this.startSizeVar = parseFloat(locValueForKey("startParticleSizeVariance", dictionary));
          this.endSize = parseFloat(locValueForKey("finishParticleSize", dictionary));
          this.endSizeVar = parseFloat(locValueForKey("finishParticleSizeVariance", dictionary));
          this.setPosition(parseFloat(locValueForKey("sourcePositionx", dictionary)), parseFloat(locValueForKey("sourcePositiony", dictionary)));
          this._posVar.x = parseFloat(locValueForKey("sourcePositionVariancex", dictionary));
          this._posVar.y = parseFloat(locValueForKey("sourcePositionVariancey", dictionary));
          this.startSpin = parseFloat(locValueForKey("rotationStart", dictionary));
          this.startSpinVar = parseFloat(locValueForKey("rotationStartVariance", dictionary));
          this.endSpin = parseFloat(locValueForKey("rotationEnd", dictionary));
          this.endSpinVar = parseFloat(locValueForKey("rotationEndVariance", dictionary));
          this.emitterMode = parseInt(locValueForKey("emitterType", dictionary));
          if (this.emitterMode === _ccsg.ParticleSystem.Mode.GRAVITY) {
            var locModeA = this.modeA;
            locModeA.gravity.x = parseFloat(locValueForKey("gravityx", dictionary));
            locModeA.gravity.y = parseFloat(locValueForKey("gravityy", dictionary));
            locModeA.speed = parseFloat(locValueForKey("speed", dictionary));
            locModeA.speedVar = parseFloat(locValueForKey("speedVariance", dictionary));
            var pszTmp = locValueForKey("radialAcceleration", dictionary);
            locModeA.radialAccel = pszTmp ? parseFloat(pszTmp) : 0;
            pszTmp = locValueForKey("radialAccelVariance", dictionary);
            locModeA.radialAccelVar = pszTmp ? parseFloat(pszTmp) : 0;
            pszTmp = locValueForKey("tangentialAcceleration", dictionary);
            locModeA.tangentialAccel = pszTmp ? parseFloat(pszTmp) : 0;
            pszTmp = locValueForKey("tangentialAccelVariance", dictionary);
            locModeA.tangentialAccelVar = pszTmp ? parseFloat(pszTmp) : 0;
            var locRotationIsDir = locValueForKey("rotationIsDir", dictionary);
            if (null !== locRotationIsDir) {
              locRotationIsDir = locRotationIsDir.toString().toLowerCase();
              locModeA.rotationIsDir = "true" === locRotationIsDir || "1" === locRotationIsDir;
            } else locModeA.rotationIsDir = false;
          } else {
            if (this.emitterMode !== _ccsg.ParticleSystem.Mode.RADIUS) {
              cc.logID(6009);
              return false;
            }
            var locModeB = this.modeB;
            locModeB.startRadius = parseFloat(locValueForKey("maxRadius", dictionary));
            locModeB.startRadiusVar = parseFloat(locValueForKey("maxRadiusVariance", dictionary));
            locModeB.endRadius = parseFloat(locValueForKey("minRadius", dictionary));
            locModeB.endRadiusVar = 0;
            locModeB.rotatePerSecond = parseFloat(locValueForKey("rotatePerSecond", dictionary));
            locModeB.rotatePerSecondVar = parseFloat(locValueForKey("rotatePerSecondVariance", dictionary));
          }
          this.life = parseFloat(locValueForKey("particleLifespan", dictionary));
          this.lifeVar = parseFloat(locValueForKey("particleLifespanVariance", dictionary));
          this.emissionRate = this._totalParticles / this.life;
          this._opacityModifyRGB = false;
          var textureName = locValueForKey("textureFileName", dictionary);
          var imgPath = cc.path.changeBasename(this._plistFile, textureName);
          var tex = cc.textureCache.getTextureForKey(imgPath);
          if (tex) this.setTexture(tex); else {
            var textureData = locValueForKey("textureImageData", dictionary);
            if (textureData && 0 !== textureData.length) {
              buffer = cc.Codec.unzipBase64AsArray(textureData, 1);
              if (!buffer) {
                cc.logID(6010);
                return false;
              }
              var imageFormat = cc.getImageFormatByData(buffer);
              if (imageFormat !== cc.ImageFormat.TIFF && imageFormat !== cc.ImageFormat.PNG) {
                cc.logID(6011);
                return false;
              }
              var canvasObj = document.createElement("canvas");
              if (imageFormat === cc.ImageFormat.PNG) {
                var myPngObj = new PNGReader(buffer);
                myPngObj.render(canvasObj);
              } else tiffReader.parseTIFF(buffer, canvasObj);
              cc.textureCache.cacheImage(imgPath, canvasObj);
              var addTexture = cc.textureCache.getTextureForKey(imgPath);
              addTexture || cc.logID(6012);
              this.setTexture(addTexture);
            } else {
              tex = cc.textureCache.addImage(imgPath);
              if (!tex) return false;
              this.setTexture(tex);
            }
          }
          ret = true;
        }
        return ret;
      },
      initWithTotalParticles: function(numberOfParticles) {
        this._totalParticles = numberOfParticles;
        var locParticles = this._particles;
        if (!locParticles) {
          cc.logID(6013);
          return false;
        }
        locParticles.length = numberOfParticles;
        for (var i = 0; i < numberOfParticles; i++) locParticles[i] = new cc.Particle();
        this._allocatedParticles = numberOfParticles;
        this._isActive = true;
        this._blendFunc.src = cc.macro.BLEND_SRC;
        this._blendFunc.dst = cc.macro.BLEND_DST;
        this.positionType = _ccsg.ParticleSystem.Type.FREE;
        this.emitterMode = _ccsg.ParticleSystem.Mode.GRAVITY;
        this.autoRemoveOnFinish = false;
        this.scheduleUpdateWithPriority(1);
        this._renderCmd._initWithTotalParticles(numberOfParticles);
        return true;
      },
      addParticle: function() {
        if (this.isFull()) return false;
        var particle = this._renderCmd.addParticle();
        this.initParticle(particle);
        ++this.particleCount;
        return true;
      },
      initParticle: function(particle) {
        var locRandomMinus11 = cc.randomMinus1To1;
        particle.timeToLive = this.life + this.lifeVar * locRandomMinus11();
        particle.timeToLive = Math.max(0, particle.timeToLive);
        particle.pos.x = this._sourcePosition.x + this._posVar.x * locRandomMinus11();
        particle.pos.y = this._sourcePosition.y + this._posVar.y * locRandomMinus11();
        var start, end;
        var locStartColor = this._startColor, locStartColorVar = this._startColorVar;
        var locEndColor = this._endColor, locEndColorVar = this._endColorVar;
        start = {
          r: cc.clampf(locStartColor.r + locStartColorVar.r * locRandomMinus11(), 0, 255),
          g: cc.clampf(locStartColor.g + locStartColorVar.g * locRandomMinus11(), 0, 255),
          b: cc.clampf(locStartColor.b + locStartColorVar.b * locRandomMinus11(), 0, 255),
          a: cc.clampf(locStartColor.a + locStartColorVar.a * locRandomMinus11(), 0, 255)
        };
        end = {
          r: cc.clampf(locEndColor.r + locEndColorVar.r * locRandomMinus11(), 0, 255),
          g: cc.clampf(locEndColor.g + locEndColorVar.g * locRandomMinus11(), 0, 255),
          b: cc.clampf(locEndColor.b + locEndColorVar.b * locRandomMinus11(), 0, 255),
          a: cc.clampf(locEndColor.a + locEndColorVar.a * locRandomMinus11(), 0, 255)
        };
        particle.color = start;
        var locParticleDeltaColor = particle.deltaColor, locParticleTimeToLive = particle.timeToLive;
        locParticleDeltaColor.r = (end.r - start.r) / locParticleTimeToLive;
        locParticleDeltaColor.g = (end.g - start.g) / locParticleTimeToLive;
        locParticleDeltaColor.b = (end.b - start.b) / locParticleTimeToLive;
        locParticleDeltaColor.a = (end.a - start.a) / locParticleTimeToLive;
        var startS = this.startSize + this.startSizeVar * locRandomMinus11();
        startS = Math.max(0, startS);
        particle.size = startS;
        if (this.endSize === _ccsg.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE) particle.deltaSize = 0; else {
          var endS = this.endSize + this.endSizeVar * locRandomMinus11();
          endS = Math.max(0, endS);
          particle.deltaSize = (endS - startS) / locParticleTimeToLive;
        }
        var startA = this.startSpin + this.startSpinVar * locRandomMinus11();
        var endA = this.endSpin + this.endSpinVar * locRandomMinus11();
        particle.rotation = startA;
        particle.deltaRotation = (endA - startA) / locParticleTimeToLive;
        if (this.positionType === _ccsg.ParticleSystem.Type.FREE) particle.startPos = this.convertToWorldSpace(this._pointZeroForParticle); else if (this.positionType === _ccsg.ParticleSystem.Type.RELATIVE) {
          particle.startPos.x = this._position.x;
          particle.startPos.y = this._position.y;
        }
        var a = cc.degreesToRadians(this.angle + this.angleVar * locRandomMinus11());
        if (this.emitterMode === _ccsg.ParticleSystem.Mode.GRAVITY) {
          var locModeA = this.modeA, locParticleModeA = particle.modeA;
          var s = locModeA.speed + locModeA.speedVar * locRandomMinus11();
          locParticleModeA.dir.x = Math.cos(a);
          locParticleModeA.dir.y = Math.sin(a);
          cc.pMultIn(locParticleModeA.dir, s);
          locParticleModeA.radialAccel = locModeA.radialAccel + locModeA.radialAccelVar * locRandomMinus11();
          locParticleModeA.tangentialAccel = locModeA.tangentialAccel + locModeA.tangentialAccelVar * locRandomMinus11();
          locModeA.rotationIsDir && (particle.rotation = -cc.radiansToDegrees(cc.pToAngle(locParticleModeA.dir)));
        } else {
          var locModeB = this.modeB, locParitlceModeB = particle.modeB;
          var startRadius = locModeB.startRadius + locModeB.startRadiusVar * locRandomMinus11();
          var endRadius = locModeB.endRadius + locModeB.endRadiusVar * locRandomMinus11();
          locParitlceModeB.radius = startRadius;
          locParitlceModeB.deltaRadius = locModeB.endRadius === _ccsg.ParticleSystem.START_RADIUS_EQUAL_TO_END_RADIUS ? 0 : (endRadius - startRadius) / locParticleTimeToLive;
          locParitlceModeB.angle = a;
          locParitlceModeB.degreesPerSecond = cc.degreesToRadians(locModeB.rotatePerSecond + locModeB.rotatePerSecondVar * locRandomMinus11());
        }
      },
      stopSystem: function() {
        this._isActive = false;
        this._elapsed = this.duration;
        this._emitCounter = 0;
      },
      resetSystem: function() {
        this._isActive = true;
        this._elapsed = 0;
        var locParticles = this._particles;
        for (this._particleIdx = 0; this._particleIdx < this.particleCount; ++this._particleIdx) locParticles[this._particleIdx].timeToLive = 0;
      },
      isFull: function() {
        return this.particleCount >= this._totalParticles;
      },
      updateQuadWithParticle: function(particle, newPosition) {
        this._renderCmd.updateQuadWithParticle(particle, newPosition);
      },
      postStep: function() {
        this._renderCmd.postStep();
      },
      update: function(dt) {
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
        if (this._isActive && this.emissionRate) {
          var rate = 1 / this.emissionRate;
          this.particleCount < this._totalParticles && (this._emitCounter += dt);
          while (this.particleCount < this._totalParticles && this._emitCounter > rate) {
            this.addParticle();
            this._emitCounter -= rate;
          }
          this._elapsed += dt;
          -1 !== this.duration && this.duration < this._elapsed && this.stopSystem();
        }
        this._particleIdx = 0;
        var worldToNodeTransform = this.getWorldToNodeTransform();
        var currentPosition = cc.Particle.TemporaryPoints[0];
        if (this.positionType === _ccsg.ParticleSystem.Type.FREE) cc.pIn(currentPosition, this.convertToWorldSpace(this._pointZeroForParticle)); else if (this.positionType === _ccsg.ParticleSystem.Type.RELATIVE) {
          currentPosition.x = this._position.x;
          currentPosition.y = this._position.y;
        }
        if (this._visible) {
          var tpa = cc.Particle.TemporaryPoints[1], tpb = cc.Particle.TemporaryPoints[2], tpc = cc.Particle.TemporaryPoints[3];
          var locParticles = this._particles;
          while (this._particleIdx < this.particleCount) {
            cc.pZeroIn(tpa);
            cc.pZeroIn(tpb);
            cc.pZeroIn(tpc);
            var selParticle = locParticles[this._particleIdx];
            selParticle.timeToLive -= dt;
            if (selParticle.timeToLive > 0) {
              if (this.emitterMode === _ccsg.ParticleSystem.Mode.GRAVITY) {
                var tmp = tpc, radial = tpa, tangential = tpb;
                if (selParticle.pos.x || selParticle.pos.y) {
                  cc.pIn(radial, selParticle.pos);
                  cc.pNormalizeIn(radial);
                } else cc.pZeroIn(radial);
                cc.pIn(tangential, radial);
                cc.pMultIn(radial, selParticle.modeA.radialAccel);
                var newy = tangential.x;
                tangential.x = -tangential.y;
                tangential.y = newy;
                cc.pMultIn(tangential, selParticle.modeA.tangentialAccel);
                cc.pIn(tmp, radial);
                cc.pAddIn(tmp, tangential);
                cc.pAddIn(tmp, this.modeA.gravity);
                cc.pMultIn(tmp, dt);
                cc.pAddIn(selParticle.modeA.dir, tmp);
                cc.pIn(tmp, selParticle.modeA.dir);
                cc.pMultIn(tmp, dt);
                cc.pAddIn(selParticle.pos, tmp);
              } else {
                var selModeB = selParticle.modeB;
                selModeB.angle += selModeB.degreesPerSecond * dt;
                selModeB.radius += selModeB.deltaRadius * dt;
                selParticle.pos.x = -Math.cos(selModeB.angle) * selModeB.radius;
                selParticle.pos.y = -Math.sin(selModeB.angle) * selModeB.radius;
              }
              this._renderCmd._updateDeltaColor(selParticle, dt);
              selParticle.size += selParticle.deltaSize * dt;
              selParticle.size = Math.max(0, selParticle.size);
              selParticle.rotation += selParticle.deltaRotation * dt;
              var newPos = tpa;
              if (this.positionType === _ccsg.ParticleSystem.Type.FREE || this.positionType === _ccsg.ParticleSystem.Type.RELATIVE) {
                var diff = tpb, localStartPos = tpc;
                cc._pointApplyAffineTransformIn(currentPosition, worldToNodeTransform, diff);
                cc._pointApplyAffineTransformIn(selParticle.startPos, worldToNodeTransform, localStartPos);
                cc.pSubIn(diff, localStartPos);
                cc.pIn(newPos, selParticle.pos);
                cc.pSubIn(newPos, diff);
              } else cc.pIn(newPos, selParticle.pos);
              this._renderCmd.updateParticlePosition(selParticle, newPos);
              ++this._particleIdx;
            } else {
              if (this._particleIdx !== this.particleCount - 1) {
                var deadParticle = locParticles[this._particleIdx];
                locParticles[this._particleIdx] = locParticles[this.particleCount - 1];
                locParticles[this.particleCount - 1] = deadParticle;
              }
              --this.particleCount;
              if (0 === this.particleCount && this.autoRemoveOnFinish) {
                this.unscheduleUpdate();
                this._parent.removeChild(this, true);
                this._renderCmd.updateLocalBB && this._renderCmd.updateLocalBB();
                return;
              }
            }
          }
          this._renderCmd.updateLocalBB && this._renderCmd.updateLocalBB();
        }
        this.postStep();
      },
      updateWithNoTime: function() {
        this.update(0);
      },
      _valueForKey: function(key, dict) {
        if (dict) {
          var pString = dict[key];
          return null != pString ? pString : "";
        }
        return "";
      },
      _updateBlendFunc: function() {
        var locTexture = this._texture;
        if (locTexture && locTexture instanceof cc.Texture2D) {
          this._opacityModifyRGB = false;
          var locBlendFunc = this._blendFunc;
          if (locBlendFunc.src === cc.macro.BLEND_SRC && locBlendFunc.dst === cc.macro.BLEND_DST) if (locTexture.hasPremultipliedAlpha()) this._opacityModifyRGB = true; else {
            locBlendFunc.src = cc.macro.SRC_ALPHA;
            locBlendFunc.dst = cc.macro.ONE_MINUS_SRC_ALPHA;
          }
        }
      },
      clone: function() {
        var retParticle = new _ccsg.ParticleSystem();
        if (retParticle.initWithTotalParticles(this.getTotalParticles())) {
          retParticle.setAngle(this.getAngle());
          retParticle.setAngleVar(this.getAngleVar());
          retParticle.setDuration(this.getDuration());
          var blend = this.getBlendFunc();
          retParticle.setBlendFunc(blend.src, blend.dst);
          retParticle.setStartColor(this.getStartColor());
          retParticle.setStartColorVar(this.getStartColorVar());
          retParticle.setEndColor(this.getEndColor());
          retParticle.setEndColorVar(this.getEndColorVar());
          retParticle.setStartSize(this.getStartSize());
          retParticle.setStartSizeVar(this.getStartSizeVar());
          retParticle.setEndSize(this.getEndSize());
          retParticle.setEndSizeVar(this.getEndSizeVar());
          retParticle.setPosition(cc.p(this.x, this.y));
          retParticle.setPosVar(cc.p(this.getPosVar().x, this.getPosVar().y));
          retParticle.setPositionType(this.getPositionType());
          retParticle.setStartSpin(this.getStartSpin() || 0);
          retParticle.setStartSpinVar(this.getStartSpinVar() || 0);
          retParticle.setEndSpin(this.getEndSpin() || 0);
          retParticle.setEndSpinVar(this.getEndSpinVar() || 0);
          retParticle.setEmitterMode(this.getEmitterMode());
          if (this.getEmitterMode() === _ccsg.ParticleSystem.Mode.GRAVITY) {
            var gra = this.getGravity();
            retParticle.setGravity(cc.p(gra.x, gra.y));
            retParticle.setSpeed(this.getSpeed());
            retParticle.setSpeedVar(this.getSpeedVar());
            retParticle.setRadialAccel(this.getRadialAccel());
            retParticle.setRadialAccelVar(this.getRadialAccelVar());
            retParticle.setTangentialAccel(this.getTangentialAccel());
            retParticle.setTangentialAccelVar(this.getTangentialAccelVar());
          } else if (this.getEmitterMode() === _ccsg.ParticleSystem.Mode.RADIUS) {
            retParticle.setStartRadius(this.getStartRadius());
            retParticle.setStartRadiusVar(this.getStartRadiusVar());
            retParticle.setEndRadius(this.getEndRadius());
            retParticle.setEndRadiusVar(this.getEndRadiusVar());
            retParticle.setRotatePerSecond(this.getRotatePerSecond());
            retParticle.setRotatePerSecondVar(this.getRotatePerSecondVar());
          }
          retParticle.setLife(this.getLife());
          retParticle.setLifeVar(this.getLifeVar());
          retParticle.setEmissionRate(this.getEmissionRate());
          retParticle.setOpacityModifyRGB(this.isOpacityModifyRGB());
          var texture = this.getTexture();
          if (texture) {
            var size = texture.getContentSize();
            retParticle.setTextureWithRect(texture, cc.rect(0, 0, size.width, size.height));
          }
        }
        return retParticle;
      },
      setDisplayFrame: function(spriteFrame) {
        if (!spriteFrame) return;
        var locOffset = spriteFrame.getOffset();
        0 === locOffset.x && 0 === locOffset.y || cc.logID(6015);
        var texture = spriteFrame.getTexture(), locTexture = this._texture;
        locTexture !== texture && this.setTexture(texture);
      },
      setTextureWithRect: function(texture, rect) {
        var locTexture = this._texture;
        if (locTexture !== texture) {
          this._texture = texture;
          this._updateBlendFunc();
        }
        this.initTexCoordsWithRect(rect);
      },
      listenBackToForeground: function(obj) {}
    });
    var _p = _ccsg.ParticleSystem.prototype;
    _p.opacityModifyRGB;
    cc.defineGetterSetter(_p, "opacityModifyRGB", _p.isOpacityModifyRGB, _p.setOpacityModifyRGB);
    _p.active;
    cc.defineGetterSetter(_p, "active", _p.isActive);
    _p.sourcePos;
    cc.defineGetterSetter(_p, "sourcePos", _p.getSourcePosition, _p.setSourcePosition);
    _p.posVar;
    cc.defineGetterSetter(_p, "posVar", _p.getPosVar, _p.setPosVar);
    _p.gravity;
    cc.defineGetterSetter(_p, "gravity", _p.getGravity, _p.setGravity);
    _p.speed;
    cc.defineGetterSetter(_p, "speed", _p.getSpeed, _p.setSpeed);
    _p.speedVar;
    cc.defineGetterSetter(_p, "speedVar", _p.getSpeedVar, _p.setSpeedVar);
    _p.tangentialAccel;
    cc.defineGetterSetter(_p, "tangentialAccel", _p.getTangentialAccel, _p.setTangentialAccel);
    _p.tangentialAccelVar;
    cc.defineGetterSetter(_p, "tangentialAccelVar", _p.getTangentialAccelVar, _p.setTangentialAccelVar);
    _p.radialAccel;
    cc.defineGetterSetter(_p, "radialAccel", _p.getRadialAccel, _p.setRadialAccel);
    _p.radialAccelVar;
    cc.defineGetterSetter(_p, "radialAccelVar", _p.getRadialAccelVar, _p.setRadialAccelVar);
    _p.rotationIsDir;
    cc.defineGetterSetter(_p, "rotationIsDir", _p.getRotationIsDir, _p.setRotationIsDir);
    _p.startRadius;
    cc.defineGetterSetter(_p, "startRadius", _p.getStartRadius, _p.setStartRadius);
    _p.startRadiusVar;
    cc.defineGetterSetter(_p, "startRadiusVar", _p.getStartRadiusVar, _p.setStartRadiusVar);
    _p.endRadius;
    cc.defineGetterSetter(_p, "endRadius", _p.getEndRadius, _p.setEndRadius);
    _p.endRadiusVar;
    cc.defineGetterSetter(_p, "endRadiusVar", _p.getEndRadiusVar, _p.setEndRadiusVar);
    _p.rotatePerS;
    cc.defineGetterSetter(_p, "rotatePerS", _p.getRotatePerSecond, _p.setRotatePerSecond);
    _p.rotatePerSVar;
    cc.defineGetterSetter(_p, "rotatePerSVar", _p.getRotatePerSecondVar, _p.setRotatePerSecondVar);
    _p.startColor;
    cc.defineGetterSetter(_p, "startColor", _p.getStartColor, _p.setStartColor);
    _p.startColorVar;
    cc.defineGetterSetter(_p, "startColorVar", _p.getStartColorVar, _p.setStartColorVar);
    _p.endColor;
    cc.defineGetterSetter(_p, "endColor", _p.getEndColor, _p.setEndColor);
    _p.endColorVar;
    cc.defineGetterSetter(_p, "endColorVar", _p.getEndColorVar, _p.setEndColorVar);
    _p.totalParticles;
    cc.defineGetterSetter(_p, "totalParticles", _p.getTotalParticles, _p.setTotalParticles);
    _p.texture;
    cc.defineGetterSetter(_p, "texture", _p.getTexture, _p.setTexture);
    _ccsg.ParticleSystem.ModeA = function(gravity, speed, speedVar, tangentialAccel, tangentialAccelVar, radialAccel, radialAccelVar, rotationIsDir) {
      this.gravity = gravity || cc.p(0, 0);
      this.speed = speed || 0;
      this.speedVar = speedVar || 0;
      this.tangentialAccel = tangentialAccel || 0;
      this.tangentialAccelVar = tangentialAccelVar || 0;
      this.radialAccel = radialAccel || 0;
      this.radialAccelVar = radialAccelVar || 0;
      this.rotationIsDir = rotationIsDir || false;
    };
    _ccsg.ParticleSystem.ModeB = function(startRadius, startRadiusVar, endRadius, endRadiusVar, rotatePerSecond, rotatePerSecondVar) {
      this.startRadius = startRadius || 0;
      this.startRadiusVar = startRadiusVar || 0;
      this.endRadius = endRadius || 0;
      this.endRadiusVar = endRadiusVar || 0;
      this.rotatePerSecond = rotatePerSecond || 0;
      this.rotatePerSecondVar = rotatePerSecondVar || 0;
    };
    _ccsg.ParticleSystem.DURATION_INFINITY = -1;
    _ccsg.ParticleSystem.START_SIZE_EQUAL_TO_END_SIZE = -1;
    _ccsg.ParticleSystem.START_RADIUS_EQUAL_TO_END_RADIUS = -1;
    _ccsg.ParticleSystem.Mode = cc.Enum({
      GRAVITY: 0,
      RADIUS: 1
    });
    _ccsg.ParticleSystem.Type = cc.Enum({
      FREE: 0,
      RELATIVE: 1,
      GROUPED: 2
    });
  }), {
    "../compression/ZipUtils": 28,
    "./CCPNGReader": 259,
    "./CCTIFFReader": 265
  } ],
  263: [ (function(require, module, exports) {
    _ccsg.ParticleSystem.CanvasRenderCmd = function(renderable) {
      this._rootCtor(renderable);
      this._needDraw = true;
      this._pointRect = cc.rect(0, 0, 0, 0);
      this._localRegion = new cc.Region();
      this._tintCache = null;
    };
    var proto = _ccsg.ParticleSystem.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
    proto.constructor = _ccsg.ParticleSystem.CanvasRenderCmd;
    proto.updateQuadWithParticle = function(particle, newPosition) {};
    proto.updateParticlePosition = function(particle, position) {
      cc.pIn(particle.drawPos, position);
    };
    var particleRegion = new cc.Region();
    var localBB = new cc.Rect();
    proto.updateLocalBB = function() {
      var region = this._localRegion;
      var particles = this._node._particles;
      region.setEmpty();
      for (var index = particles.length - 1; index >= 0; --index) {
        var particle = particles[index];
        var pos = particle.drawPos;
        var size = 1.415 * particle.size;
        particleRegion.setTo(pos.x - size, pos.y - size, pos.x + size, pos.y + size);
        region.union(particleRegion);
      }
      localBB.x = region._minX;
      localBB.y = region._minY;
      localBB.width = region._maxX - region._minX;
      localBB.height = region._maxY - region._minY;
    };
    proto.getLocalBB = function() {
      return localBB;
    };
    proto.updateStatus = function() {
      this.originUpdateStatus();
      this._updateCurrentRegions();
      this._regionFlag = _ccsg.Node.CanvasRenderCmd.RegionStatus.DirtyDouble;
      this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.contentDirty;
    };
    proto.rendering = function(ctx, scaleX, scaleY) {
      var wrapper = ctx || cc._renderContext, context = wrapper.getContext(), node = this._node, pointRect = this._pointRect;
      wrapper.setTransform(this._worldTransform, scaleX, scaleY);
      wrapper.save();
      node.isBlendAdditive() ? context.globalCompositeOperation = "lighter" : context.globalCompositeOperation = "source-over";
      var i, particle, lpx, alpha;
      var particleCount = this._node.particleCount, particles = this._node._particles;
      if (node._texture) {
        if (!node._texture.loaded) {
          wrapper.restore();
          return;
        }
        var element = node._texture.getHtmlElementObj();
        if (!element.width || !element.height) {
          wrapper.restore();
          return;
        }
        var drawElement = element;
        for (i = 0; i < particleCount; i++) {
          particle = particles[i];
          lpx = 0 | .5 * particle.size;
          alpha = particle.color.a / 255;
          if (0 === alpha) continue;
          context.globalAlpha = alpha;
          context.save();
          context.translate(0 | particle.drawPos.x, -(0 | particle.drawPos.y));
          var size = 4 * Math.floor(particle.size / 4);
          var w = pointRect.width;
          var h = pointRect.height;
          context.scale(Math.max(1 / w * size, 1e-6), Math.max(1 / h * size, 1e-6));
          particle.rotation && context.rotate(cc.degreesToRadians(particle.rotation));
          drawElement = particle.isChangeColor ? this._changeTextureColor(node._texture, particle.color, this._pointRect) : element;
          context.drawImage(drawElement, -(0 | w / 2), -(0 | h / 2));
          context.restore();
        }
        cc.g_NumberOfDraws++;
      }
      wrapper.restore();
    };
    proto._changeTextureColor = function(texture, color, rect) {
      this._tintCache || (this._tintCache = document.createElement("canvas"));
      var tintCache = this._tintCache;
      var textureContentSize = texture.getContentSize();
      tintCache.width = textureContentSize.width;
      tintCache.height = textureContentSize.height;
      return texture._generateColorTexture(color.r, color.g, color.b, rect, tintCache);
    };
    proto.initTexCoordsWithRect = function(pointRect) {
      this._pointRect = pointRect;
    };
    proto.setTotalParticles = function(tp) {
      this._node._totalParticles = tp < 200 ? tp : 200;
    };
    proto.addParticle = function() {
      var node = this._node, particles = node._particles, particle;
      if (node.particleCount < particles.length) particle = particles[node.particleCount]; else {
        particle = new cc.Particle();
        particles.push(particle);
      }
      return particle;
    };
    proto._setupVBO = function() {};
    proto._allocMemory = function() {
      return true;
    };
    proto.postStep = function() {};
    proto._setBlendAdditive = function() {
      var locBlendFunc = this._node._blendFunc;
      locBlendFunc.src = cc.macro.BLEND_SRC;
      locBlendFunc.dst = cc.macro.BLEND_DST;
    };
    proto._initWithTotalParticles = function(totalParticles) {};
    proto._updateDeltaColor = function(selParticle, dt) {
      if (!this._node._dontTint) {
        selParticle.color.r += selParticle.deltaColor.r * dt;
        selParticle.color.g += selParticle.deltaColor.g * dt;
        selParticle.color.b += selParticle.deltaColor.b * dt;
        selParticle.color.a += selParticle.deltaColor.a * dt;
        selParticle.isChangeColor = true;
      }
    };
  }), {} ],
  264: [ (function(require, module, exports) {
    _ccsg.ParticleSystem.WebGLRenderCmd = function(renderable) {
      this._rootCtor(renderable);
      this._needDraw = true;
      this._matrix = new cc.math.Matrix4();
      this._matrix.identity();
      this._buffersVBO = [ 0, 0 ];
      this._quads = [];
      this._indices = [];
      this._quadsArrayBuffer = null;
    };
    var proto = _ccsg.ParticleSystem.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype);
    proto.constructor = _ccsg.ParticleSystem.WebGLRenderCmd;
    proto.initIndices = function(totalParticles) {
      var locIndices = this._indices;
      for (var i = 0, len = totalParticles; i < len; ++i) {
        var i6 = 6 * i;
        var i4 = 4 * i;
        locIndices[i6 + 0] = i4 + 0;
        locIndices[i6 + 1] = i4 + 1;
        locIndices[i6 + 2] = i4 + 2;
        locIndices[i6 + 5] = i4 + 1;
        locIndices[i6 + 4] = i4 + 2;
        locIndices[i6 + 3] = i4 + 3;
      }
    };
    proto.isDifferentTexture = function(texture1, texture2) {
      return texture1 === texture2;
    };
    proto.updateParticlePosition = function(particle, position) {
      this.updateQuadWithParticle(particle, position);
    };
    proto.updateQuadWithParticle = function(particle, newPosition) {
      var quad = null, node = this._node;
      quad = this._quads[node._particleIdx];
      var r, g, b, a;
      if (node._opacityModifyRGB) {
        r = 0 | particle.color.r * particle.color.a / 255;
        g = 0 | particle.color.g * particle.color.a / 255;
        b = 0 | particle.color.b * particle.color.a / 255;
      } else {
        r = 0 | particle.color.r;
        g = 0 | particle.color.g;
        b = 0 | particle.color.b;
      }
      a = 0 | particle.color.a;
      var blColors = quad.bl.colors, brColors = quad.br.colors, tlColors = quad.tl.colors, trColors = quad.tr.colors;
      blColors.r = brColors.r = tlColors.r = trColors.r = r;
      blColors.g = brColors.g = tlColors.g = trColors.g = g;
      blColors.b = brColors.b = tlColors.b = trColors.b = b;
      blColors.a = brColors.a = tlColors.a = trColors.a = a;
      var size_2 = particle.size / 2;
      if (particle.rotation) {
        var x1 = -size_2, y1 = -size_2;
        var x2 = size_2, y2 = size_2;
        var x = newPosition.x, y = newPosition.y;
        var rad = -cc.degreesToRadians(particle.rotation);
        var cr = Math.cos(rad), sr = Math.sin(rad);
        var ax = x1 * cr - y1 * sr + x;
        var ay = x1 * sr + y1 * cr + y;
        var bx = x2 * cr - y1 * sr + x;
        var by = x2 * sr + y1 * cr + y;
        var cx = x2 * cr - y2 * sr + x;
        var cy = x2 * sr + y2 * cr + y;
        var dx = x1 * cr - y2 * sr + x;
        var dy = x1 * sr + y2 * cr + y;
        quad.bl.vertices.x = ax;
        quad.bl.vertices.y = ay;
        quad.br.vertices.x = bx;
        quad.br.vertices.y = by;
        quad.tl.vertices.x = dx;
        quad.tl.vertices.y = dy;
        quad.tr.vertices.x = cx;
        quad.tr.vertices.y = cy;
      } else {
        quad.bl.vertices.x = newPosition.x - size_2;
        quad.bl.vertices.y = newPosition.y - size_2;
        quad.br.vertices.x = newPosition.x + size_2;
        quad.br.vertices.y = newPosition.y - size_2;
        quad.tl.vertices.x = newPosition.x - size_2;
        quad.tl.vertices.y = newPosition.y + size_2;
        quad.tr.vertices.x = newPosition.x + size_2;
        quad.tr.vertices.y = newPosition.y + size_2;
      }
    };
    proto.rendering = function(ctx) {
      var node = this._node;
      if (!node._texture) return;
      var gl = ctx || cc._renderContext;
      var wt = this._worldTransform, mat = this._matrix.mat;
      mat[0] = wt.a;
      mat[4] = wt.c;
      mat[12] = wt.tx;
      mat[1] = wt.b;
      mat[5] = wt.d;
      mat[13] = wt.ty;
      this._shaderProgram.use();
      this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix);
      cc.gl.bindTexture2DN(0, node._texture);
      cc.gl.blendFuncForParticle(node._blendFunc.src, node._blendFunc.dst);
      gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION);
      gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR);
      gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS);
      gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]);
      gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0);
      gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12);
      gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16);
      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]);
      gl.drawElements(gl.TRIANGLES, 6 * node._particleIdx, gl.UNSIGNED_SHORT, 0);
    };
    proto.initTexCoordsWithRect = function(pointRect) {
      var node = this._node;
      var texture = node.texture;
      var wide = pointRect.width;
      var high = pointRect.height;
      if (texture) {
        wide = texture.getPixelWidth();
        high = texture.getPixelHeight();
      }
      var left, bottom, right, top;
      if (cc.macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL) {
        left = (2 * pointRect.x + 1) / (2 * wide);
        bottom = (2 * pointRect.y + 1) / (2 * high);
        right = left + (2 * pointRect.width - 2) / (2 * wide);
        top = bottom + (2 * pointRect.height - 2) / (2 * high);
      } else {
        left = pointRect.x / wide;
        bottom = pointRect.y / high;
        right = left + pointRect.width / wide;
        top = bottom + pointRect.height / high;
      }
      var temp = top;
      top = bottom;
      bottom = temp;
      var quads = this._quads;
      var start = 0;
      var end = node._totalParticles;
      for (var i = start; i < end; i++) {
        quads[i] || (quads[i] = cc.V3F_C4B_T2F_QuadZero());
        var selQuad = quads[i];
        selQuad.bl.texCoords.u = left;
        selQuad.bl.texCoords.v = bottom;
        selQuad.br.texCoords.u = right;
        selQuad.br.texCoords.v = bottom;
        selQuad.tl.texCoords.u = left;
        selQuad.tl.texCoords.v = top;
        selQuad.tr.texCoords.u = right;
        selQuad.tr.texCoords.v = top;
      }
    };
    proto.setTotalParticles = function(tp) {
      var node = this._node;
      if (tp > node._allocatedParticles) {
        var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT;
        this._indices = new Uint16Array(6 * tp);
        var locQuadsArrayBuffer = new ArrayBuffer(tp * quadSize);
        var locParticles = node._particles;
        locParticles.length = 0;
        var locQuads = this._quads;
        locQuads.length = 0;
        for (var j = 0; j < tp; j++) {
          locParticles[j] = new cc.Particle();
          locQuads[j] = new cc.V3F_C4B_T2F_Quad(null, null, null, null, locQuadsArrayBuffer, j * quadSize);
        }
        node._allocatedParticles = tp;
        node._totalParticles = tp;
        this._quadsArrayBuffer = locQuadsArrayBuffer;
        this.initIndices(tp);
        this._setupVBO();
        node._texture && this.initTexCoordsWithRect(cc.rect(0, 0, node._texture.width, node._texture.height));
      } else node._totalParticles = tp;
      node.resetSystem();
    };
    proto.addParticle = function() {
      var node = this._node, particles = node._particles;
      return particles[node.particleCount];
    };
    proto._setupVBO = function() {
      var node = this;
      var gl = cc._renderContext;
      this._buffersVBO[0] = gl.createBuffer();
      gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]);
      gl.bufferData(gl.ARRAY_BUFFER, this._quadsArrayBuffer, gl.DYNAMIC_DRAW);
      this._buffersVBO[1] = gl.createBuffer();
      gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._buffersVBO[1]);
      gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indices, gl.STATIC_DRAW);
    };
    proto._allocMemory = function() {
      var node = this._node;
      var quadSize = cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT;
      var totalParticles = node._totalParticles;
      var locQuads = this._quads;
      locQuads.length = 0;
      this._indices = new Uint16Array(6 * totalParticles);
      var locQuadsArrayBuffer = new ArrayBuffer(quadSize * totalParticles);
      for (var i = 0; i < totalParticles; i++) locQuads[i] = new cc.V3F_C4B_T2F_Quad(null, null, null, null, locQuadsArrayBuffer, i * quadSize);
      if (!locQuads || !this._indices) {
        cc.logID(6013);
        return false;
      }
      this._quadsArrayBuffer = locQuadsArrayBuffer;
      return true;
    };
    proto.postStep = function() {
      var gl = cc._renderContext;
      gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]);
      gl.bufferSubData(gl.ARRAY_BUFFER, 0, this._quadsArrayBuffer);
    };
    proto._setBlendAdditive = function() {
      var locBlendFunc = this._node._blendFunc;
      if (this._texture && !this._texture.hasPremultipliedAlpha()) {
        locBlendFunc.src = cc.macro.SRC_ALPHA;
        locBlendFunc.dst = cc.macro.ONE_MINUS_SRC_ALPHA;
      } else {
        locBlendFunc.src = cc.macro.BLEND_SRC;
        locBlendFunc.dst = cc.macro.BLEND_DST;
      }
    };
    proto._initWithTotalParticles = function(totalParticles) {
      if (!this._allocMemory()) return false;
      this.initIndices(totalParticles);
      this._setupVBO();
      this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURECOLOR);
    };
    proto._updateDeltaColor = function(selParticle, dt) {
      selParticle.color.r += selParticle.deltaColor.r * dt;
      selParticle.color.g += selParticle.deltaColor.g * dt;
      selParticle.color.b += selParticle.deltaColor.b * dt;
      selParticle.color.a += selParticle.deltaColor.a * dt;
      selParticle.isChangeColor = true;
    };
  }), {} ],
  265: [ (function(require, module, exports) {
    var tiffReader = {
      _littleEndian: false,
      _tiffData: null,
      _fileDirectories: [],
      getUint8: function(offset) {
        return this._tiffData[offset];
      },
      getUint16: function(offset) {
        return this._littleEndian ? this._tiffData[offset + 1] << 8 | this._tiffData[offset] : this._tiffData[offset] << 8 | this._tiffData[offset + 1];
      },
      getUint32: function(offset) {
        var a = this._tiffData;
        return this._littleEndian ? a[offset + 3] << 24 | a[offset + 2] << 16 | a[offset + 1] << 8 | a[offset] : a[offset] << 24 | a[offset + 1] << 16 | a[offset + 2] << 8 | a[offset + 3];
      },
      checkLittleEndian: function() {
        var BOM = this.getUint16(0);
        if (18761 === BOM) this.littleEndian = true; else {
          if (19789 !== BOM) {
            console.log(BOM);
            throw TypeError("Invalid byte order value.");
          }
          this.littleEndian = false;
        }
        return this.littleEndian;
      },
      hasTowel: function() {
        if (42 !== this.getUint16(2)) throw RangeError("You forgot your towel!");
        return true;
      },
      getFieldTypeName: function(fieldType) {
        var typeNames = this.fieldTypeNames;
        if (fieldType in typeNames) return typeNames[fieldType];
        return null;
      },
      getFieldTagName: function(fieldTag) {
        var tagNames = this.fieldTagNames;
        if (fieldTag in tagNames) return tagNames[fieldTag];
        console.log("Unknown Field Tag:", fieldTag);
        return "Tag" + fieldTag;
      },
      getFieldTypeLength: function(fieldTypeName) {
        if (-1 !== [ "BYTE", "ASCII", "SBYTE", "UNDEFINED" ].indexOf(fieldTypeName)) return 1;
        if (-1 !== [ "SHORT", "SSHORT" ].indexOf(fieldTypeName)) return 2;
        if (-1 !== [ "LONG", "SLONG", "FLOAT" ].indexOf(fieldTypeName)) return 4;
        if (-1 !== [ "RATIONAL", "SRATIONAL", "DOUBLE" ].indexOf(fieldTypeName)) return 8;
        return null;
      },
      getFieldValues: function(fieldTagName, fieldTypeName, typeCount, valueOffset) {
        var fieldValues = [];
        var fieldTypeLength = this.getFieldTypeLength(fieldTypeName);
        var fieldValueSize = fieldTypeLength * typeCount;
        if (fieldValueSize <= 4) false === this.littleEndian ? fieldValues.push(valueOffset >>> 8 * (4 - fieldTypeLength)) : fieldValues.push(valueOffset); else for (var i = 0; i < typeCount; i++) {
          var indexOffset = fieldTypeLength * i;
          if (fieldTypeLength >= 8) if (-1 !== [ "RATIONAL", "SRATIONAL" ].indexOf(fieldTypeName)) {
            fieldValues.push(this.getUint32(valueOffset + indexOffset));
            fieldValues.push(this.getUint32(valueOffset + indexOffset + 4));
          } else cc.logID(8e3); else fieldValues.push(this.getBytes(fieldTypeLength, valueOffset + indexOffset));
        }
        "ASCII" === fieldTypeName && fieldValues.forEach((function(e, i, a) {
          a[i] = String.fromCharCode(e);
        }));
        return fieldValues;
      },
      getBytes: function(numBytes, offset) {
        if (numBytes <= 0) cc.logID(8001); else {
          if (numBytes <= 1) return this.getUint8(offset);
          if (numBytes <= 2) return this.getUint16(offset);
          if (numBytes <= 3) return this.getUint32(offset) >>> 8;
          if (numBytes <= 4) return this.getUint32(offset);
          cc.logID(8002);
        }
      },
      getBits: function(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, rawBits;
        if (totalBits <= 0) console.log("No bits requested"); 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 console.log("Too many bits requested");
        return {
          bits: rawBits << shiftLeft >>> shiftRight,
          byteOffset: newByteOffset + Math.floor(totalBits / 8),
          bitOffset: totalBits % 8
        };
      },
      parseFileDirectory: function(byteOffset) {
        var numDirEntries = this.getUint16(byteOffset);
        var tiffFields = [];
        for (var i = byteOffset + 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);
        0 !== nextIFDByteOffset && this.parseFileDirectory(nextIFDByteOffset);
      },
      clampColorSample: function(colorSample, bitsPerSample) {
        var multiplier = Math.pow(2, 8 - bitsPerSample);
        return Math.floor(colorSample * multiplier + (multiplier - 1));
      },
      parseTIFF: function(tiffData, canvas) {
        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: void 0
          };
          if (bitsPerSample % 8 === 0) {
            sampleProperties[i].hasBytesPerSample = true;
            sampleProperties[i].bytesPerSample = bitsPerSample / 8;
          }
          bitsPerPixel += bitsPerSample;
        }), this);
        if (bitsPerPixel % 8 === 0) {
          hasBytesPerPixel = true;
          var bytesPerPixel = bitsPerPixel / 8;
        }
        var stripOffsetValues = fileDirectory["StripOffsets"].values;
        var numStripOffsetValues = stripOffsetValues.length;
        if (fileDirectory["StripByteCounts"]) var stripByteCountValues = fileDirectory["StripByteCounts"].values; else {
          cc.logID(8003);
          if (1 !== numStripOffsetValues) throw Error("Cannot recover from missing StripByteCounts");
          var stripByteCountValues = [ Math.ceil(imageWidth * imageLength * bitsPerPixel / 8) ];
        }
        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:
            for (var m = 0, pixel = []; m < samplesPerPixel; m++) {
              if (!sampleProperties[m].hasBytesPerSample) {
                var sampleInfo = this.getBits(sampleProperties[m].bitsPerSample, stripOffset + byteOffset, bitOffset);
                pixel.push(sampleInfo.bits);
                byteOffset = sampleInfo.byteOffset - stripOffset;
                bitOffset = sampleInfo.bitOffset;
                throw RangeError("Cannot handle sub-byte bits per sample");
              }
              var sampleOffset = sampleProperties[m].bytesPerSample * m;
              pixel.push(this.getBytes(sampleProperties[m].bytesPerSample, stripOffset + byteOffset + sampleOffset));
            }
            strips[i].push(pixel);
            if (!hasBytesPerPixel) {
              jIncrement = 0;
              throw RangeError("Cannot handle sub-byte bits per pixel");
            }
            jIncrement = bytesPerPixel;
            break;

           case 2:
           case 3:
           case 4:
           case 5:
           case 6:
           case 7:
            break;

           case 32773:
            if (getHeader) {
              getHeader = false;
              var blockLength = 1;
              var iterations = 1;
              var header = this.getInt8(stripOffset + byteOffset);
              header >= 0 && header <= 127 ? blockLength = header + 1 : header >= -127 && header <= -1 ? iterations = 1 - header : getHeader = true;
            } else {
              var currentByte = this.getUint8(stripOffset + byteOffset);
              for (var m = 0; m < iterations; m++) {
                if (!sampleProperties[sample].hasBytesPerSample) throw RangeError("Cannot handle sub-byte bits per sample");
                currentSample = currentSample << 8 * numBytes | currentByte;
                numBytes++;
                if (numBytes === sampleProperties[sample].bytesPerSample) {
                  pixel.push(currentSample);
                  currentSample = numBytes = 0;
                  sample++;
                }
                if (sample === samplesPerPixel) {
                  strips[i].push(pixel);
                  pixel = [];
                  sample = 0;
                }
              }
              blockLength--;
              0 === blockLength && (getHeader = true);
            }
            jIncrement = 1;
          }
        }
        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 = 0 === imageLengthModRowsPerStrip ? 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;
          }
          if (fileDirectory["ColorMap"]) {
            var colorMapValues = fileDirectory["ColorMap"].values;
            var colorMapSampleSize = Math.pow(2, sampleProperties[0].bitsPerSample);
          }
          for (var i = 0; i < numStrips; i++) {
            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;
              if (numExtraSamples > 0) for (var k = 0; k < numExtraSamples; k++) if (1 === extraSamplesValues[k] || 2 === extraSamplesValues[k]) {
                opacity = pixelSamples[3 + k] / 256;
                break;
              }
              switch (photometricInterpretation) {
               case 0:
                if (sampleProperties[0].hasBytesPerSample) var invertValue = Math.pow(16, 2 * sampleProperties[0].bytesPerSample);
                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 (void 0 === colorMapValues) throw Error("Palette image missing color map");
                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("Unknown Photometric Interpretation:", photometricInterpretation);
              }
              ctx.fillStyle = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity + ")";
              ctx.fillRect(x, yPadding + y, 1, 1);
            }
            numRowsInPreviousStrip = numRowsInStrip;
          }
        }
        return this.canvas;
      },
      fieldTagNames: {
        315: "Artist",
        258: "BitsPerSample",
        265: "CellLength",
        264: "CellWidth",
        320: "ColorMap",
        259: "Compression",
        33432: "Copyright",
        306: "DateTime",
        338: "ExtraSamples",
        266: "FillOrder",
        289: "FreeByteCounts",
        288: "FreeOffsets",
        291: "GrayResponseCurve",
        290: "GrayResponseUnit",
        316: "HostComputer",
        270: "ImageDescription",
        257: "ImageLength",
        256: "ImageWidth",
        271: "Make",
        281: "MaxSampleValue",
        280: "MinSampleValue",
        272: "Model",
        254: "NewSubfileType",
        274: "Orientation",
        262: "PhotometricInterpretation",
        284: "PlanarConfiguration",
        296: "ResolutionUnit",
        278: "RowsPerStrip",
        277: "SamplesPerPixel",
        305: "Software",
        279: "StripByteCounts",
        273: "StripOffsets",
        255: "SubfileType",
        263: "Threshholding",
        282: "XResolution",
        283: "YResolution",
        326: "BadFaxLines",
        327: "CleanFaxData",
        343: "ClipPath",
        328: "ConsecutiveBadFaxLines",
        433: "Decode",
        434: "DefaultImageColor",
        269: "DocumentName",
        336: "DotRange",
        321: "HalftoneHints",
        346: "Indexed",
        347: "JPEGTables",
        285: "PageName",
        297: "PageNumber",
        317: "Predictor",
        319: "PrimaryChromaticities",
        532: "ReferenceBlackWhite",
        339: "SampleFormat",
        559: "StripRowCounts",
        330: "SubIFDs",
        292: "T4Options",
        293: "T6Options",
        325: "TileByteCounts",
        323: "TileLength",
        324: "TileOffsets",
        322: "TileWidth",
        301: "TransferFunction",
        318: "WhitePoint",
        344: "XClipPathUnits",
        286: "XPosition",
        529: "YCbCrCoefficients",
        531: "YCbCrPositioning",
        530: "YCbCrSubSampling",
        345: "YClipPathUnits",
        287: "YPosition",
        37378: "ApertureValue",
        40961: "ColorSpace",
        36868: "DateTimeDigitized",
        36867: "DateTimeOriginal",
        34665: "Exif IFD",
        36864: "ExifVersion",
        33434: "ExposureTime",
        41728: "FileSource",
        37385: "Flash",
        40960: "FlashpixVersion",
        33437: "FNumber",
        42016: "ImageUniqueID",
        37384: "LightSource",
        37500: "MakerNote",
        37377: "ShutterSpeedValue",
        37510: "UserComment",
        33723: "IPTC",
        34675: "ICC Profile",
        700: "XMP",
        42112: "GDAL_METADATA",
        42113: "GDAL_NODATA",
        34377: "Photoshop"
      },
      fieldTypeNames: {
        1: "BYTE",
        2: "ASCII",
        3: "SHORT",
        4: "LONG",
        5: "RATIONAL",
        6: "SBYTE",
        7: "UNDEFINED",
        8: "SSHORT",
        9: "SLONG",
        10: "SRATIONAL",
        11: "FLOAT",
        12: "DOUBLE"
      }
    };
    module.exports = tiffReader;
  }), {} ],
  266: [ (function(require, module, exports) {
    cc.RenderTexture = _ccsg.Node.extend({
      sprite: null,
      clearFlags: 0,
      clearDepthVal: 0,
      autoDraw: false,
      _texture: null,
      _pixelFormat: 0,
      clearStencilVal: 0,
      _clearColor: null,
      _className: "RenderTexture",
      ctor: function(width, height, format, depthStencilFormat) {
        _ccsg.Node.prototype.ctor.call(this);
        this._cascadeColorEnabled = true;
        this._cascadeOpacityEnabled = true;
        this._pixelFormat = cc.Texture2D.PixelFormat.RGBA8888;
        this._clearColor = new cc.Color(0, 0, 0, 255);
        if (void 0 !== width && void 0 !== height) {
          format = format || cc.Texture2D.PixelFormat.RGBA8888;
          depthStencilFormat = depthStencilFormat || 0;
          this.initWithWidthAndHeight(width, height, format, depthStencilFormat);
        }
        this.setAnchorPoint(0, 0);
      },
      _createRenderCmd: function() {
        return cc._renderType === cc.game.RENDER_TYPE_CANVAS ? new cc.RenderTexture.CanvasRenderCmd(this) : new cc.RenderTexture.WebGLRenderCmd(this);
      },
      visit: function(parent) {
        var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null;
        if (!this._visible) {
          cmd._propagateFlagsDown(parentCmd);
          return;
        }
        var renderer = cc.renderer;
        cmd.visit(parentCmd);
        renderer.pushRenderCommand(cmd);
        this.sprite.visit(this);
        cmd._dirtyFlag = 0;
      },
      cleanup: function() {
        _ccsg.Node.prototype.onExit.call(this);
        this._renderCmd.cleanup();
      },
      getSprite: function() {
        return this.sprite;
      },
      setSprite: function(sprite) {
        this.sprite = sprite;
      },
      setVirtualViewport: function(rtBegin, fullRect, fullViewport) {
        this._renderCmd.setVirtualViewport(rtBegin, fullRect, fullViewport);
      },
      initWithWidthAndHeight: function(width, height, format, depthStencilFormat) {
        return this._renderCmd.initWithWidthAndHeight(width, height, format, depthStencilFormat);
      },
      begin: function() {
        cc.renderer._turnToCacheMode(this.__instanceId);
        this._renderCmd.begin();
      },
      beginWithClear: function(r, g, b, a, depthValue, stencilValue) {
        var gl = cc._renderContext;
        depthValue = depthValue || gl.COLOR_BUFFER_BIT;
        stencilValue = stencilValue || gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT;
        this._beginWithClear(r, g, b, a, depthValue, stencilValue, gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);
      },
      _beginWithClear: function(r, g, b, a, depthValue, stencilValue, flags) {
        this.begin();
        this._renderCmd._beginWithClear(r, g, b, a, depthValue, stencilValue, flags);
      },
      end: function() {
        this._renderCmd.end();
      },
      clear: function(r, g, b, a) {
        this.beginWithClear(r, g, b, a);
        this.end();
      },
      clearRect: function(x, y, width, height) {
        this._renderCmd.clearRect(x, y, width, height);
      },
      clearDepth: function(depthValue) {
        this._renderCmd.clearDepth(depthValue);
      },
      clearStencil: function(stencilValue) {
        this._renderCmd.clearStencil(stencilValue);
      },
      getClearFlags: function() {
        return this.clearFlags;
      },
      setClearFlags: function(clearFlags) {
        this.clearFlags = clearFlags;
      },
      getClearColor: function() {
        return this._clearColor;
      },
      setClearColor: function(clearColor) {
        var locClearColor = this._clearColor;
        locClearColor.r = clearColor.r;
        locClearColor.g = clearColor.g;
        locClearColor.b = clearColor.b;
        locClearColor.a = clearColor.a;
        this._renderCmd.updateClearColor(clearColor);
      },
      getClearDepth: function() {
        return this.clearDepthVal;
      },
      setClearDepth: function(clearDepth) {
        this.clearDepthVal = clearDepth;
      },
      getClearStencil: function() {
        return this.clearStencilVal;
      },
      setClearStencil: function(clearStencil) {
        this.clearStencilVal = clearStencil;
      },
      isAutoDraw: function() {
        return this.autoDraw;
      },
      setAutoDraw: function(autoDraw) {
        this.autoDraw = autoDraw;
      },
      saveToFile: function(filePath, format) {
        cc.log("saveToFile isn't supported on Cocos2d-Html5");
      },
      newCCImage: function(flipImage) {
        cc.log("saveToFile isn't supported on cocos2d-html5");
        return null;
      },
      listenToBackground: function(obj) {},
      listenToForeground: function(obj) {}
    });
    var _p = cc.RenderTexture.prototype;
    _p.clearColorVal;
    cc.defineGetterSetter(_p, "clearColorVal", _p.getClearColor, _p.setClearColor);
    cc.RenderTexture.create = function(width, height, format, depthStencilFormat) {
      return new cc.RenderTexture(width, height, format, depthStencilFormat);
    };
  }), {} ],
  267: [ (function(require, module, exports) {
    cc.RenderTexture.CanvasRenderCmd = function(renderableObject) {
      this._rootCtor(renderableObject);
      this._needDraw = false;
      this._clearColorStr = "rgba(255,255,255,1)";
      this._cacheCanvas = document.createElement("canvas");
      this._cacheContext = new cc.CanvasContextWrapper(this._cacheCanvas.getContext("2d"));
    };
    var proto = cc.RenderTexture.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
    proto.constructor = cc.RenderTexture.CanvasRenderCmd;
    proto.cleanup = function() {
      this._cacheContext = null;
      this._cacheCanvas = null;
    };
    proto.clearStencil = function(stencilValue) {};
    proto.setVirtualViewport = function(rtBegin, fullRect, fullViewport) {};
    proto.updateClearColor = function(clearColor) {
      this._clearColorStr = "rgba(" + (0 | clearColor.r) + "," + (0 | clearColor.g) + "," + (0 | clearColor.b) + "," + clearColor.a / 255 + ")";
    };
    proto.initWithWidthAndHeight = function(width, height, format, depthStencilFormat) {
      var node = this._node;
      var locCacheCanvas = this._cacheCanvas;
      locCacheCanvas.width = 0 | width;
      locCacheCanvas.height = 0 | height;
      var texture = new cc.Texture2D();
      texture.initWithElement(locCacheCanvas);
      texture.handleLoadedTexture();
      var locSprite = node.sprite = new _ccsg.Sprite(texture);
      locSprite.setBlendFunc(cc.macro.ONE, cc.macro.ONE_MINUS_SRC_ALPHA);
      node.autoDraw = false;
      node.addChild(locSprite);
      return true;
    };
    proto.begin = function() {};
    proto._beginWithClear = function(r, g, b, a, depthValue, stencilValue, flags) {
      r = r || 0;
      g = g || 0;
      b = b || 0;
      a = isNaN(a) ? 255 : a;
      var context = this._cacheContext.getContext();
      var locCanvas = this._cacheCanvas;
      context.setTransform(1, 0, 0, 1, 0, 0);
      this._cacheContext.setFillStyle("rgba(" + (0 | r) + "," + (0 | g) + "," + (0 | b) + "," + a / 255 + ")");
      context.clearRect(0, 0, locCanvas.width, locCanvas.height);
      context.fillRect(0, 0, locCanvas.width, locCanvas.height);
    };
    proto.end = function() {
      var node = this._node;
      cc.renderer._renderingToCacheCanvas(this._cacheContext, node.__instanceId);
      var spriteRenderCmd = node.sprite._renderCmd;
      spriteRenderCmd._notifyRegionStatus && spriteRenderCmd._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty);
    };
    proto.clearRect = function(x, y, width, height) {
      this._cacheContext.clearRect(x, y, width, -height);
    };
    proto.clearDepth = function(depthValue) {
      cc.log("clearDepth isn't supported on Cocos2d-Html5");
    };
  }), {} ],
  268: [ (function(require, module, exports) {
    var misc = require("../core/utils/misc");
    cc.RenderTexture.WebGLRenderCmd = function(renderableObject) {
      this._rootCtor(renderableObject);
      this._needDraw = true;
      this._fBO = null;
      this._oldFBO = null;
      this._textureCopy = null;
      this._depthRenderBuffer = null;
      this._rtTextureRect = new cc.Rect();
      this._fullRect = new cc.Rect();
      this._fullViewport = new cc.Rect();
    };
    var proto = cc.RenderTexture.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype);
    proto.constructor = cc.RenderTexture.WebGLRenderCmd;
    proto.setVirtualViewport = function(rtBegin, fullRect, fullViewport) {
      this._rtTextureRect.x = rtBegin.x;
      this._rtTextureRect.y = rtBegin.y;
      this._fullRect = fullRect;
      this._fullViewport = fullViewport;
    };
    proto.needDraw = function() {
      return this._needDraw && this._node.autoDraw;
    };
    proto.rendering = function(ctx) {
      var gl = ctx || cc._renderContext;
      var node = this._node;
      if (node.autoDraw) {
        node.begin();
        var locClearFlags = node.clearFlags;
        if (locClearFlags) {
          var oldClearColor = [ 0, 0, 0, 0 ];
          var oldDepthClearValue = 0;
          var oldStencilClearValue = 0;
          if (locClearFlags & gl.COLOR_BUFFER_BIT) {
            oldClearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
            gl.clearColor(node._clearColor.r / 255, node._clearColor.g / 255, node._clearColor.b / 255, node._clearColor.a / 255);
          }
          if (locClearFlags & gl.DEPTH_BUFFER_BIT) {
            oldDepthClearValue = gl.getParameter(gl.DEPTH_CLEAR_VALUE);
            gl.clearDepth(node.clearDepthVal);
          }
          if (locClearFlags & gl.STENCIL_BUFFER_BIT) {
            oldStencilClearValue = gl.getParameter(gl.STENCIL_CLEAR_VALUE);
            gl.clearStencil(node.clearStencilVal);
          }
          gl.clear(locClearFlags);
          locClearFlags & gl.COLOR_BUFFER_BIT && gl.clearColor(oldClearColor[0], oldClearColor[1], oldClearColor[2], oldClearColor[3]);
          locClearFlags & gl.DEPTH_BUFFER_BIT && gl.clearDepth(oldDepthClearValue);
          locClearFlags & gl.STENCIL_BUFFER_BIT && gl.clearStencil(oldStencilClearValue);
        }
        node.sortAllChildren();
        var locChildren = node._children;
        for (var i = 0; i < locChildren.length; i++) {
          var getChild = locChildren[i];
          getChild !== node.sprite && getChild.visit(node.sprite);
        }
        node.end();
      }
    };
    proto.clearStencil = function(stencilValue) {
      var gl = cc._renderContext;
      var stencilClearValue = gl.getParameter(gl.STENCIL_CLEAR_VALUE);
      gl.clearStencil(stencilValue);
      gl.clear(gl.STENCIL_BUFFER_BIT);
      gl.clearStencil(stencilClearValue);
    };
    proto.cleanup = function() {
      var node = this._node;
      this._textureCopy = null;
      var gl = cc._renderContext;
      gl.deleteFramebuffer(this._fBO);
      this._depthRenderBuffer && gl.deleteRenderbuffer(this._depthRenderBuffer);
    };
    proto.updateClearColor = function(clearColor) {};
    proto.initWithWidthAndHeight = function(width, height, format, depthStencilFormat) {
      var node = this._node;
      format === cc.Texture2D.PixelFormat.A8 && cc.log("cc.RenderTexture._initWithWidthAndHeightForWebGL() : only RGB and RGBA formats are valid for a render texture;");
      var gl = cc._renderContext;
      this._fullRect = new cc.Rect(0, 0, width, height);
      width |= 0;
      height |= 0;
      this._oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING);
      var powW, powH;
      if (cc.configuration.supportsNPOT()) {
        powW = width;
        powH = height;
      } else {
        powW = misc.NextPOT(width);
        powH = misc.NextPOT(height);
      }
      this._fullViewport = new cc.Rect(0, 0, powW, powH);
      var dataLen = powW * powH * 4;
      var data = new Uint8Array(dataLen);
      for (var i = 0; i < powW * powH * 4; i++) data[i] = 0;
      this._pixelFormat = format;
      var locTexture = node._texture = new cc.Texture2D();
      if (!node._texture) return false;
      locTexture.initWithData(data, node._pixelFormat, powW, powH);
      var oldRBO = gl.getParameter(gl.RENDERBUFFER_BINDING);
      if (cc.configuration.checkForGLExtension("GL_QCOM")) {
        this._textureCopy = new cc.Texture2D();
        if (!this._textureCopy) return false;
        this._textureCopy.initWithData(data, node._pixelFormat, powW, powH);
      }
      this._fBO = gl.createFramebuffer();
      gl.bindFramebuffer(gl.FRAMEBUFFER, this._fBO);
      gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, locTexture._glID, 0);
      if (0 !== depthStencilFormat) {
        this._depthRenderBuffer = gl.createRenderbuffer();
        gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthRenderBuffer);
        gl.renderbufferStorage(gl.RENDERBUFFER, depthStencilFormat, powW, powH);
        depthStencilFormat === gl.DEPTH_STENCIL ? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer) : depthStencilFormat === gl.STENCIL_INDEX || depthStencilFormat === gl.STENCIL_INDEX8 ? gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer) : depthStencilFormat === gl.DEPTH_COMPONENT16 && gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer);
      }
      gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE && cc.log("Could not attach texture to the framebuffer");
      locTexture.setAliasTexParameters();
      var locSprite = node.sprite = new _ccsg.Sprite(locTexture);
      locSprite.scaleY = -1;
      locSprite.setBlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
      gl.bindRenderbuffer(gl.RENDERBUFFER, oldRBO);
      gl.bindFramebuffer(gl.FRAMEBUFFER, this._oldFBO);
      node.autoDraw = false;
      node.addChild(locSprite);
      return true;
    };
    proto.begin = function() {
      var node = this._node;
      cc.math.glMatrixMode(cc.math.KM_GL_PROJECTION);
      cc.math.glPushMatrix();
      cc.math.glMatrixMode(cc.math.KM_GL_MODELVIEW);
      cc.math.glPushMatrix();
      var gl = cc._renderContext;
      var director = cc.director;
      director.setProjection(director.getProjection());
      var size = cc.director.getWinSizeInPixels();
      var widthRatio = size.width / node._texture.width;
      var heightRatio = size.height / node._texture.height;
      var orthoMatrix = cc.math.Matrix4.createOrthographicProjection(-1 / widthRatio, 1 / widthRatio, -1 / heightRatio, 1 / heightRatio, -1, 1);
      cc.math.glMatrixMode(cc.math.KM_GL_PROJECTION);
      cc.math.glMultMatrix(orthoMatrix);
      var viewport = new cc.Rect(0, 0, 0, 0);
      viewport.width = this._fullViewport.width;
      viewport.height = this._fullViewport.height;
      var viewPortRectWidthRatio = viewport.width / this._fullRect.width;
      var viewPortRectHeightRatio = viewport.height / this._fullRect.height;
      viewport.x = (this._fullRect.x - this._rtTextureRect.x) * viewPortRectWidthRatio;
      viewport.y = (this._fullRect.y - this._rtTextureRect.y) * viewPortRectHeightRatio;
      gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height);
      this._oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING);
      gl.bindFramebuffer(gl.FRAMEBUFFER, this._fBO);
      if (cc.configuration.checkForGLExtension("GL_QCOM")) {
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this._textureCopy._glID, 0);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, node._texture._glID, 0);
      }
    };
    proto._beginWithClear = function(r, g, b, a, depthValue, stencilValue, flags) {
      r /= 255;
      g /= 255;
      b /= 255;
      a /= 255;
      var gl = cc._renderContext;
      var clearColor = [ 0, 0, 0, 0 ];
      var depthClearValue = 0;
      var stencilClearValue = 0;
      if (flags & gl.COLOR_BUFFER_BIT) {
        clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
        gl.clearColor(r, g, b, a);
      }
      if (flags & gl.DEPTH_BUFFER_BIT) {
        depthClearValue = gl.getParameter(gl.DEPTH_CLEAR_VALUE);
        gl.clearDepth(depthValue);
      }
      if (flags & gl.STENCIL_BUFFER_BIT) {
        stencilClearValue = gl.getParameter(gl.STENCIL_CLEAR_VALUE);
        gl.clearStencil(stencilValue);
      }
      gl.clear(flags);
      flags & gl.COLOR_BUFFER_BIT && gl.clearColor(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
      flags & gl.DEPTH_BUFFER_BIT && gl.clearDepth(depthClearValue);
      flags & gl.STENCIL_BUFFER_BIT && gl.clearStencil(stencilClearValue);
    };
    proto.end = function() {
      var node = this._node;
      cc.renderer._renderingToBuffer(node.__instanceId);
      var gl = cc._renderContext;
      var director = cc.director;
      gl.bindFramebuffer(gl.FRAMEBUFFER, this._oldFBO);
      director.setViewport();
      cc.math.glMatrixMode(cc.math.KM_GL_PROJECTION);
      cc.math.glPopMatrix();
      cc.math.glMatrixMode(cc.math.KM_GL_MODELVIEW);
      cc.math.glPopMatrix();
    };
    proto.clearRect = function(x, y, width, height) {};
    proto.clearDepth = function(depthValue) {
      var node = this._node;
      node.begin();
      var gl = cc._renderContext;
      var depthClearValue = gl.getParameter(gl.DEPTH_CLEAR_VALUE);
      gl.clearDepth(depthValue);
      gl.clear(gl.DEPTH_BUFFER_BIT);
      gl.clearDepth(depthClearValue);
      node.end();
    };
  }), {
    "../core/utils/misc": 225
  } ],
  269: [ (function(require, module, exports) {
    var macro = cc.macro;
    var math = cc.math;
    cc.GLProgram = cc._Class.extend({
      _updateUniformLocation: function(location) {
        if (!location) return false;
        var updated;
        var element = this._hashForUniforms[location];
        if (element) {
          updated = false;
          var count = arguments.length - 1;
          for (var i = 0; i < count; ++i) if (arguments[i + 1] !== element[i]) {
            element[i] = arguments[i + 1];
            updated = true;
          }
        } else {
          element = [ arguments[1], arguments[2], arguments[3], arguments[4] ];
          this._hashForUniforms[location] = element;
          updated = true;
        }
        return updated;
      },
      _description: function() {
        return "<CCGLProgram = " + this.toString() + " | Program = " + this._programObj.toString() + ", VertexShader = " + this._vertShader.toString() + ", FragmentShader = " + this._fragShader.toString() + ">";
      },
      _compileShader: function(shader, type, source) {
        if (!source || !shader) return false;
        var preStr = cc.GLProgram._isHighpSupported() ? "precision highp float;\n" : "precision mediump float;\n";
        source = preStr + "uniform mat4 CC_PMatrix;\nuniform mat4 CC_MVMatrix;\nuniform mat4 CC_MVPMatrix;\nuniform vec4 CC_Time;\nuniform vec4 CC_SinTime;\nuniform vec4 CC_CosTime;\nuniform vec4 CC_Random01;\nuniform sampler2D CC_Texture0;\n//CC INCLUDES END\n" + source;
        this._glContext.shaderSource(shader, source);
        this._glContext.compileShader(shader);
        var status = this._glContext.getShaderParameter(shader, this._glContext.COMPILE_STATUS);
        if (!status) {
          cc.logID(8100, this._glContext.getShaderSource(shader));
          type === this._glContext.VERTEX_SHADER ? cc.log("cocos2d: \n" + this.vertexShaderLog()) : cc.log("cocos2d: \n" + this.fragmentShaderLog());
        }
        return true === status;
      },
      ctor: function(vShaderFileName, fShaderFileName, glContext) {
        this._uniforms = {};
        this._hashForUniforms = {};
        this._glContext = glContext || cc._renderContext;
        this._programObj = null;
        this._vertShader = null;
        this._fragShader = null;
        this._usesTime = false;
        this._projectionUpdated = -1;
        vShaderFileName && fShaderFileName && this.init(vShaderFileName, fShaderFileName);
      },
      destroyProgram: function() {
        this._vertShader = null;
        this._fragShader = null;
        this._uniforms = null;
        this._hashForUniforms = null;
        this._glContext.deleteProgram(this._programObj);
      },
      initWithVertexShaderByteArray: function(vertShaderStr, fragShaderStr) {
        var locGL = this._glContext;
        this._programObj = locGL.createProgram();
        this._projectionUpdated = -1;
        this._vertShader = null;
        this._fragShader = null;
        if (vertShaderStr) {
          this._vertShader = locGL.createShader(locGL.VERTEX_SHADER);
          this._compileShader(this._vertShader, locGL.VERTEX_SHADER, vertShaderStr) || cc.logID(8101);
        }
        if (fragShaderStr) {
          this._fragShader = locGL.createShader(locGL.FRAGMENT_SHADER);
          this._compileShader(this._fragShader, locGL.FRAGMENT_SHADER, fragShaderStr) || cc.logID(8102);
        }
        this._vertShader && locGL.attachShader(this._programObj, this._vertShader);
        this._fragShader && locGL.attachShader(this._programObj, this._fragShader);
        for (var key in this._hashForUniforms) delete this._hashForUniforms[key];
        false;
        return true;
      },
      initWithString: function(vertShaderStr, fragShaderStr) {
        return this.initWithVertexShaderByteArray(vertShaderStr, fragShaderStr);
      },
      initWithVertexShaderFilename: function(vShaderFilename, fShaderFileName) {
        var vertexSource = cc.loader.getRes(vShaderFilename);
        if (!vertexSource) throw new Error("Please load the resource firset : " + vShaderFilename);
        var fragmentSource = cc.loader.getRes(fShaderFileName);
        if (!fragmentSource) throw new Error("Please load the resource firset : " + fShaderFileName);
        return this.initWithVertexShaderByteArray(vertexSource, fragmentSource);
      },
      init: function(vShaderFilename, fShaderFileName) {
        return this.initWithVertexShaderFilename(vShaderFilename, fShaderFileName);
      },
      addAttribute: function(attributeName, index) {
        this._glContext.bindAttribLocation(this._programObj, index, attributeName);
      },
      link: function() {
        if (!this._programObj) {
          cc.logID(8103);
          return false;
        }
        this._glContext.linkProgram(this._programObj);
        this._vertShader && this._glContext.deleteShader(this._vertShader);
        this._fragShader && this._glContext.deleteShader(this._fragShader);
        this._vertShader = null;
        this._fragShader = null;
        if (cc.game.config[cc.game.CONFIG_KEY.debugMode]) {
          var status = this._glContext.getProgramParameter(this._programObj, this._glContext.LINK_STATUS);
          if (!status) {
            cc.logID(8104, this._glContext.getProgramInfoLog(this._programObj));
            cc.gl.deleteProgram(this._programObj);
            this._programObj = null;
            return false;
          }
        }
        return true;
      },
      use: function() {
        cc.gl.useProgram(this._programObj);
      },
      updateUniforms: function() {
        this._uniforms[macro.UNIFORM_PMATRIX] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_PMATRIX_S);
        this._uniforms[macro.UNIFORM_MVMATRIX] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_MVMATRIX_S);
        this._uniforms[macro.UNIFORM_MVPMATRIX] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_MVPMATRIX_S);
        this._uniforms[macro.UNIFORM_TIME] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_TIME_S);
        this._uniforms[macro.UNIFORM_SINTIME] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_SINTIME_S);
        this._uniforms[macro.UNIFORM_COSTIME] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_COSTIME_S);
        this._usesTime = null != this._uniforms[macro.UNIFORM_TIME] || null != this._uniforms[macro.UNIFORM_SINTIME] || null != this._uniforms[macro.UNIFORM_COSTIME];
        this._uniforms[macro.UNIFORM_RANDOM01] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_RANDOM01_S);
        this._uniforms[macro.UNIFORM_SAMPLER] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_SAMPLER_S);
        this.use();
        this.setUniformLocationWith1i(this._uniforms[macro.UNIFORM_SAMPLER], 0);
      },
      _addUniformLocation: function(name) {
        var location = this._glContext.getUniformLocation(this._programObj, name);
        this._uniforms[name] = location;
      },
      getUniformLocationForName: function(name) {
        if (!name) throw new Error("cc.GLProgram.getUniformLocationForName(): uniform name should be non-null");
        if (!this._programObj) throw new Error("cc.GLProgram.getUniformLocationForName(): Invalid operation. Cannot get uniform location when program is not initialized");
        var location = this._uniforms[name] || this._glContext.getUniformLocation(this._programObj, name);
        return location;
      },
      getUniformMVPMatrix: function() {
        return this._uniforms[macro.UNIFORM_MVPMATRIX];
      },
      getUniformSampler: function() {
        return this._uniforms[macro.UNIFORM_SAMPLER];
      },
      setUniformLocationWith1i: function(location, i1) {
        var gl = this._glContext;
        if ("string" === typeof location) {
          var updated = this._updateUniformLocation(location, i1);
          if (updated) {
            var locObj = this.getUniformLocationForName(location);
            gl.uniform1i(locObj, i1);
          }
        } else gl.uniform1i(location, i1);
      },
      setUniformLocationWith2i: function(location, i1, i2) {
        var gl = this._glContext;
        if ("string" === typeof location) {
          var updated = this._updateUniformLocation(location, i1, i2);
          if (updated) {
            var locObj = this.getUniformLocationForName(location);
            gl.uniform2i(locObj, i1, i2);
          }
        } else gl.uniform2i(location, i1, i2);
      },
      setUniformLocationWith3i: function(location, i1, i2, i3) {
        var gl = this._glContext;
        if ("string" === typeof location) {
          var updated = this._updateUniformLocation(location, i1, i2, i3);
          if (updated) {
            var locObj = this.getUniformLocationForName(location);
            gl.uniform3i(locObj, i1, i2, i3);
          }
        } else gl.uniform3i(location, i1, i2, i3);
      },
      setUniformLocationWith4i: function(location, i1, i2, i3, i4) {
        var gl = this._glContext;
        if ("string" === typeof location) {
          var updated = this._updateUniformLocation(location, i1, i2, i3, i4);
          if (updated) {
            var locObj = this.getUniformLocationForName(location);
            gl.uniform4i(locObj, i1, i2, i3, i4);
          }
        } else gl.uniform4i(location, i1, i2, i3, i4);
      },
      setUniformLocationWith2iv: function(location, intArray) {
        var locObj = "string" === typeof location ? this.getUniformLocationForName(location) : location;
        this._glContext.uniform2iv(locObj, intArray);
      },
      setUniformLocationWith3iv: function(location, intArray) {
        var locObj = "string" === typeof location ? this.getUniformLocationForName(location) : location;
        this._glContext.uniform3iv(locObj, intArray);
      },
      setUniformLocationWith4iv: function(location, intArray) {
        var locObj = "string" === typeof location ? this.getUniformLocationForName(location) : location;
        this._glContext.uniform4iv(locObj, intArray);
      },
      setUniformLocationI32: function(location, i1) {
        this.setUniformLocationWith1i(location, i1);
      },
      setUniformLocationWith1f: function(location, f1) {
        var gl = this._glContext;
        if ("string" === typeof location) {
          var updated = this._updateUniformLocation(location, f1);
          if (updated) {
            var locObj = this.getUniformLocationForName(location);
            gl.uniform1f(locObj, f1);
          }
        } else gl.uniform1f(location, f1);
      },
      setUniformLocationWith2f: function(location, f1, f2) {
        var gl = this._glContext;
        if ("string" === typeof location) {
          var updated = this._updateUniformLocation(location, f1, f2);
          if (updated) {
            var locObj = this.getUniformLocationForName(location);
            gl.uniform2f(locObj, f1, f2);
          }
        } else gl.uniform2f(location, f1, f2);
      },
      setUniformLocationWith3f: function(location, f1, f2, f3) {
        var gl = this._glContext;
        if ("string" === typeof location) {
          var updated = this._updateUniformLocation(location, f1, f2, f3);
          if (updated) {
            var locObj = this.getUniformLocationForName(location);
            gl.uniform3f(locObj, f1, f2, f3);
          }
        } else gl.uniform3f(location, f1, f2, f3);
      },
      setUniformLocationWith4f: function(location, f1, f2, f3, f4) {
        var gl = this._glContext;
        if ("string" === typeof location) {
          var updated = this._updateUniformLocation(location, f1, f2, f3, f4);
          if (updated) {
            var locObj = this.getUniformLocationForName(location);
            gl.uniform4f(locObj, f1, f2, f3, f4);
          }
        } else gl.uniform4f(location, f1, f2, f3, f4);
      },
      setUniformLocationWith2fv: function(location, floatArray) {
        var locObj = "string" === typeof location ? this.getUniformLocationForName(location) : location;
        this._glContext.uniform2fv(locObj, floatArray);
      },
      setUniformLocationWith3fv: function(location, floatArray) {
        var locObj = "string" === typeof location ? this.getUniformLocationForName(location) : location;
        this._glContext.uniform3fv(locObj, floatArray);
      },
      setUniformLocationWith4fv: function(location, floatArray) {
        var locObj = "string" === typeof location ? this.getUniformLocationForName(location) : location;
        this._glContext.uniform4fv(locObj, floatArray);
      },
      setUniformLocationWithMatrix3fv: function(location, matrixArray) {
        var locObj = "string" === typeof location ? this.getUniformLocationForName(location) : location;
        this._glContext.uniformMatrix3fv(locObj, false, matrixArray);
      },
      setUniformLocationWithMatrix4fv: function(location, matrixArray) {
        var locObj = "string" === typeof location ? this.getUniformLocationForName(location) : location;
        this._glContext.uniformMatrix4fv(locObj, false, matrixArray);
      },
      setUniformLocationF32: function(p1, p2, p3, p4, p5) {
        "use strict";
        switch (arguments.length) {
         case 0:
         case 1:
          return;

         case 2:
          this.setUniformLocationWith1f(p1, p2);
          break;

         case 3:
          this.setUniformLocationWith2f(p1, p2, p3);
          break;

         case 4:
          this.setUniformLocationWith3f(p1, p2, p3, p4);
          break;

         case 5:
          this.setUniformLocationWith4f(p1, p2, p3, p4, p5);
        }
      },
      setUniformsForBuiltins: function() {
        var matrixP = new math.Matrix4();
        var matrixMV = new math.Matrix4();
        var matrixMVP = new math.Matrix4();
        math.glGetMatrix(math.KM_GL_PROJECTION, matrixP);
        math.glGetMatrix(math.KM_GL_MODELVIEW, matrixMV);
        math.mat4Multiply(matrixMVP, matrixP, matrixMV);
        this.setUniformLocationWithMatrix4fv(this._uniforms[macro.UNIFORM_PMATRIX], matrixP.mat, 1);
        this.setUniformLocationWithMatrix4fv(this._uniforms[macro.UNIFORM_MVMATRIX], matrixMV.mat, 1);
        this.setUniformLocationWithMatrix4fv(this._uniforms[macro.UNIFORM_MVPMATRIX], matrixMVP.mat, 1);
        if (this._usesTime) {
          var director = cc.director;
          var time = director.getTotalFrames() * director.getAnimationInterval();
          this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_TIME], time / 10, time, 2 * time, 4 * time);
          this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_SINTIME], time / 8, time / 4, time / 2, Math.sin(time));
          this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_COSTIME], time / 8, time / 4, time / 2, Math.cos(time));
        }
        -1 !== this._uniforms[macro.UNIFORM_RANDOM01] && this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_RANDOM01], Math.random(), Math.random(), Math.random(), Math.random());
      },
      _setUniformsForBuiltinsForRenderer: function(node) {
        if (!node || !node._renderCmd) return;
        var matrixP = new math.Matrix4();
        var matrixMVP = new math.Matrix4();
        math.glGetMatrix(math.KM_GL_PROJECTION, matrixP);
        math.mat4Multiply(matrixMVP, matrixP, node._renderCmd._stackMatrix);
        this.setUniformLocationWithMatrix4fv(this._uniforms[macro.UNIFORM_PMATRIX], matrixP.mat, 1);
        this.setUniformLocationWithMatrix4fv(this._uniforms[macro.UNIFORM_MVMATRIX], node._renderCmd._stackMatrix.mat, 1);
        this.setUniformLocationWithMatrix4fv(this._uniforms[macro.UNIFORM_MVPMATRIX], matrixMVP.mat, 1);
        if (this._usesTime) {
          var director = cc.director;
          var time = director.getTotalFrames() * director.getAnimationInterval();
          this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_TIME], time / 10, time, 2 * time, 4 * time);
          this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_SINTIME], time / 8, time / 4, time / 2, Math.sin(time));
          this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_COSTIME], time / 8, time / 4, time / 2, Math.cos(time));
        }
        -1 !== this._uniforms[macro.UNIFORM_RANDOM01] && this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_RANDOM01], Math.random(), Math.random(), Math.random(), Math.random());
      },
      setUniformForModelViewProjectionMatrix: function() {
        this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_MVPMATRIX], false, math.getMat4MultiplyValue(math.projection_matrix_stack.top, math.modelview_matrix_stack.top));
      },
      setUniformForModelViewProjectionMatrixWithMat4: function(swapMat4) {
        math.mat4Multiply(swapMat4, math.projection_matrix_stack.top, math.modelview_matrix_stack.top);
        this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_MVPMATRIX], false, swapMat4.mat);
      },
      setUniformForModelViewAndProjectionMatrixWithMat4: function() {
        this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_MVMATRIX], false, math.modelview_matrix_stack.top.mat);
        this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_PMATRIX], false, math.projection_matrix_stack.top.mat);
      },
      _setUniformForMVPMatrixWithMat4: function(modelViewMatrix) {
        if (!modelViewMatrix) throw new Error("modelView matrix is undefined.");
        this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_MVMATRIX], false, modelViewMatrix.mat);
        this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_PMATRIX], false, math.projection_matrix_stack.top.mat);
      },
      _updateProjectionUniform: function() {
        var stack = math.projection_matrix_stack;
        if (stack.lastUpdated !== this._projectionUpdated) {
          this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_PMATRIX], false, stack.top.mat);
          this._projectionUpdated = stack.lastUpdated;
        }
      },
      vertexShaderLog: function() {
        return this._glContext.getShaderInfoLog(this._vertShader);
      },
      getVertexShaderLog: function() {
        return this._glContext.getShaderInfoLog(this._vertShader);
      },
      getFragmentShaderLog: function() {
        return this._glContext.getShaderInfoLog(this._vertShader);
      },
      fragmentShaderLog: function() {
        return this._glContext.getShaderInfoLog(this._fragShader);
      },
      programLog: function() {
        return this._glContext.getProgramInfoLog(this._programObj);
      },
      getProgramLog: function() {
        return this._glContext.getProgramInfoLog(this._programObj);
      },
      reset: function() {
        this._vertShader = null;
        this._fragShader = null;
        this._uniforms.length = 0;
        this._glContext.deleteProgram(this._programObj);
        this._programObj = null;
        for (var key in this._hashForUniforms) {
          this._hashForUniforms[key].length = 0;
          delete this._hashForUniforms[key];
        }
      },
      getProgram: function() {
        return this._programObj;
      },
      retain: function() {},
      release: function() {}
    });
    cc.GLProgram._highpSupported = null;
    cc.GLProgram._isHighpSupported = function() {
      var ctx = cc._renderContext;
      if (ctx.getShaderPrecisionFormat && null == cc.GLProgram._highpSupported) {
        var highp = ctx.getShaderPrecisionFormat(ctx.FRAGMENT_SHADER, ctx.HIGH_FLOAT);
        cc.GLProgram._highpSupported = 0 !== highp.precision;
      }
      return cc.GLProgram._highpSupported;
    };
  }), {} ],
  270: [ (function(require, module, exports) {
    var _currentProjectionMatrix = -1;
    var macro = cc.macro;
    var ENABLE_GL_STATE_CACHE = macro.ENABLE_GL_STATE_CACHE;
    var MAX_ACTIVETEXTURE = 0, _currentShaderProgram = 0, _currentBoundTexture = null, _blendingSource = 0, _blendingDest = 0, _GLServerState = 0;
    if (ENABLE_GL_STATE_CACHE) {
      MAX_ACTIVETEXTURE = 16;
      _currentShaderProgram = -1;
      _currentBoundTexture = new Array(MAX_ACTIVETEXTURE);
      _blendingSource = -1;
      _blendingDest = -1;
      _GLServerState = 0;
    }
    cc.gl = {};
    cc.gl.invalidateStateCache = function() {
      cc.math.glFreeAll();
      _currentProjectionMatrix = -1;
      if (ENABLE_GL_STATE_CACHE) {
        _currentShaderProgram = -1;
        for (var i = 0; i < MAX_ACTIVETEXTURE; i++) _currentBoundTexture[i] = null;
        _blendingSource = -1;
        _blendingDest = -1;
        _GLServerState = 0;
      }
    };
    cc.gl.useProgram = ENABLE_GL_STATE_CACHE ? function(program) {
      if (program !== _currentShaderProgram) {
        _currentShaderProgram = program;
        cc._renderContext.useProgram(program);
      }
    } : function(program) {
      cc._renderContext.useProgram(program);
    };
    cc.gl.deleteProgram = function(program) {
      ENABLE_GL_STATE_CACHE && program === _currentShaderProgram && (_currentShaderProgram = -1);
      gl.deleteProgram(program);
    };
    cc.gl.setBlending = function(sfactor, dfactor) {
      var gl = cc._renderContext;
      if (sfactor === gl.ONE && dfactor === gl.ZERO) gl.disable(gl.BLEND); else {
        gl.enable(gl.BLEND);
        gl.blendFunc(sfactor, dfactor);
      }
    };
    cc.gl.blendFunc = ENABLE_GL_STATE_CACHE ? function(sfactor, dfactor) {
      if (sfactor !== _blendingSource || dfactor !== _blendingDest) {
        _blendingSource = sfactor;
        _blendingDest = dfactor;
        cc.gl.setBlending(sfactor, dfactor);
      }
    } : cc.gl.setBlending;
    cc.gl.blendFuncForParticle = function(sfactor, dfactor) {
      if (sfactor !== _blendingSource || dfactor !== _blendingDest) {
        _blendingSource = sfactor;
        _blendingDest = dfactor;
        var ctx = cc._renderContext;
        if (sfactor === ctx.ONE && dfactor === ctx.ZERO) ctx.disable(ctx.BLEND); else {
          ctx.enable(ctx.BLEND);
          ctx.blendFuncSeparate(ctx.SRC_ALPHA, dfactor, sfactor, dfactor);
        }
      }
    };
    cc.gl.blendResetToCache = function() {
      var ctx = cc._renderContext;
      ctx.blendEquation(ctx.FUNC_ADD);
      ENABLE_GL_STATE_CACHE ? cc.gl.setBlending(_blendingSource, _blendingDest) : cc.gl.setBlending(ctx.BLEND_SRC, ctx.BLEND_DST);
    };
    cc.gl.setProjectionMatrixDirty = function() {
      _currentProjectionMatrix = -1;
    };
    cc.gl.bindTexture2D = function(texture) {
      cc.gl.bindTexture2DN(0, texture);
    };
    cc.gl.bindTexture2DN = ENABLE_GL_STATE_CACHE ? function(textureUnit, texture) {
      if (_currentBoundTexture[textureUnit] === texture) return;
      _currentBoundTexture[textureUnit] = texture;
      var ctx = cc._renderContext;
      ctx.activeTexture(ctx.TEXTURE0 + textureUnit);
      texture ? ctx.bindTexture(ctx.TEXTURE_2D, texture._glID) : ctx.bindTexture(ctx.TEXTURE_2D, null);
    } : function(textureUnit, texture) {
      var ctx = cc._renderContext;
      ctx.activeTexture(ctx.TEXTURE0 + textureUnit);
      texture ? ctx.bindTexture(ctx.TEXTURE_2D, texture._glID) : ctx.bindTexture(ctx.TEXTURE_2D, null);
    };
    cc.gl.deleteTexture2D = function(texture) {
      cc.gl.deleteTexture2DN(0, texture);
    };
    cc.gl.deleteTexture2DN = function(textureUnit, texture) {
      ENABLE_GL_STATE_CACHE && texture === _currentBoundTexture[textureUnit] && (_currentBoundTexture[textureUnit] = null);
      cc._renderContext.deleteTexture(texture._glID);
    };
    cc.gl.enable = function(flags) {
      ENABLE_GL_STATE_CACHE;
    };
  }), {} ],
  271: [ (function(require, module, exports) {
    var shaders = cc.PresetShaders;
    var macro = cc.macro;
    cc.shaderCache = {
      TYPE_POSITION_TEXTURECOLOR: 0,
      TYPE_POSITION_TEXTURECOLOR_ALPHATEST: 1,
      TYPE_POSITION_COLOR: 2,
      TYPE_POSITION_TEXTURE: 3,
      TYPE_POSITION_TEXTURE_UCOLOR: 4,
      TYPE_POSITION_TEXTURE_A8COLOR: 5,
      TYPE_POSITION_UCOLOR: 6,
      TYPE_POSITION_LENGTH_TEXTURECOLOR: 7,
      TYPE_SPRITE_POSITION_TEXTURECOLOR: 8,
      TYPE_SPRITE_POSITION_TEXTURECOLOR_ALPHATEST: 9,
      TYPE_SPRITE_POSITION_COLOR: 10,
      TYPE_MAX: 10,
      _programs: {},
      _init: function() {
        this.loadDefaultShaders();
        return true;
      },
      _loadDefaultShader: function(program, type) {
        switch (type) {
         case macro.SHADER_POSITION_TEXTURECOLOR:
          program.initWithVertexShaderByteArray(shaders.POSITION_TEXTURE_COLOR_VERT, shaders.POSITION_TEXTURE_COLOR_FRAG);
          program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
          program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
          program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
          break;

         case macro.SHADER_SPRITE_POSITION_TEXTURECOLOR:
          program.initWithVertexShaderByteArray(shaders.SPRITE_POSITION_TEXTURE_COLOR_VERT, shaders.POSITION_TEXTURE_COLOR_FRAG);
          program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
          program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
          program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
          break;

         case macro.SHADER_POSITION_TEXTURECOLORALPHATEST:
          program.initWithVertexShaderByteArray(shaders.POSITION_TEXTURE_COLOR_VERT, shaders.POSITION_TEXTURE_COLOR_ALPHATEST_FRAG);
          program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
          program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
          program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
          break;

         case macro.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST:
          program.initWithVertexShaderByteArray(shaders.SPRITE_POSITION_TEXTURE_COLOR_VERT, shaders.POSITION_TEXTURE_COLOR_ALPHATEST_FRAG);
          program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
          program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
          program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
          break;

         case macro.SHADER_POSITION_COLOR:
          program.initWithVertexShaderByteArray(shaders.POSITION_COLOR_VERT, shaders.POSITION_COLOR_FRAG);
          program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
          program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
          break;

         case macro.SHADER_SPRITE_POSITION_COLOR:
          program.initWithVertexShaderByteArray(shaders.SPRITE_POSITION_COLOR_VERT, shaders.POSITION_COLOR_FRAG);
          program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
          program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
          break;

         case macro.SHADER_POSITION_TEXTURE:
          program.initWithVertexShaderByteArray(shaders.POSITION_TEXTURE_VERT, shaders.POSITION_TEXTURE_FRAG);
          program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
          program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
          break;

         case macro.SHADER_POSITION_TEXTURE_UCOLOR:
          program.initWithVertexShaderByteArray(shaders.POSITION_TEXTURE_UCOLOR_VERT, shaders.POSITION_TEXTURE_UCOLOR_FRAG);
          program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
          program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
          break;

         case macro.SHADER_POSITION_TEXTUREA8COLOR:
          program.initWithVertexShaderByteArray(shaders.POSITION_TEXTURE_A8COLOR_VERT, shaders.POSITION_TEXTURE_A8COLOR_FRAG);
          program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
          program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
          program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
          break;

         case macro.SHADER_POSITION_UCOLOR:
          program.initWithVertexShaderByteArray(shaders.POSITION_UCOLOR_VERT, shaders.POSITION_UCOLOR_FRAG);
          program.addAttribute("aVertex", macro.VERTEX_ATTRIB_POSITION);
          break;

         case macro.SHADER_POSITION_LENGTHTEXTURECOLOR:
          program.initWithVertexShaderByteArray(shaders.POSITION_COLOR_LENGTH_TEXTURE_VERT, shaders.POSITION_COLOR_LENGTH_TEXTURE_FRAG);
          program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
          program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
          program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
          break;

         default:
          cc.logID(8105);
          return;
        }
        program.link();
        program.updateUniforms();
      },
      _reloadShader: function(type) {
        var program = this.programForKey(type);
        program.reset();
        this._loadDefaultShader(program, type);
      },
      loadDefaultShaders: function() {},
      reloadDefaultShaders: function() {
        this._reloadShader(macro.SHADER_POSITION_TEXTURECOLOR);
        this._reloadShader(macro.SHADER_SPRITE_POSITION_TEXTURECOLOR);
        this._reloadShader(macro.SHADER_POSITION_TEXTURECOLORALPHATEST);
        this._reloadShader(macro.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST);
        this._reloadShader(macro.SHADER_POSITION_COLOR);
        this._reloadShader(macro.SHADER_POSITION_TEXTURE);
        this._reloadShader(macro.SHADER_POSITION_TEXTURE_UCOLOR);
        this._reloadShader(macro.SHADER_POSITION_TEXTUREA8COLOR);
        this._reloadShader(macro.SHADER_POSITION_UCOLOR);
      },
      programForKey: function(key) {
        if (!this._programs[key]) {
          var program = new cc.GLProgram();
          this._loadDefaultShader(program, key);
          this._programs[key] = program;
        }
        return this._programs[key];
      },
      getProgram: function(shaderName) {
        return this.programForKey(shaderName);
      },
      addProgram: function(program, key) {
        this._programs[key] = program;
      }
    };
  }), {} ],
  272: [ (function(require, module, exports) {
    cc.PresetShaders = {
      POSITION_UCOLOR_FRAG: "precision lowp float;\nvarying vec4 v_fragmentColor;\nvoid main()\n{\ngl_FragColor = v_fragmentColor;\n}",
      POSITION_UCOLOR_VERT: "attribute vec4 a_position;\nuniform vec4 u_color;\nuniform float u_pointSize;\nvarying lowp vec4 v_fragmentColor;\nvoid main(void)\n{\ngl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;\ngl_PointSize = u_pointSize;\nv_fragmentColor = u_color;\n}",
      POSITION_COLOR_FRAG: "precision lowp float;\nvarying vec4 v_fragmentColor;\nvoid main()\n{\ngl_FragColor = v_fragmentColor;\n}",
      POSITION_COLOR_VERT: "attribute vec4 a_position;\nattribute vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\nvoid main()\n{\ngl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;\nv_fragmentColor = a_color;\n}",
      SPRITE_POSITION_COLOR_VERT: "attribute vec4 a_position;\nattribute vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\nvoid main()\n{\ngl_Position = CC_PMatrix * a_position;\nv_fragmentColor = a_color;\n}",
      POSITION_COLOR_LENGTH_TEXTURE_FRAG: "//#extension GL_OES_standard_derivatives : enable\nvarying mediump vec4 v_color;\nvarying mediump vec2 v_texcoord;\nvoid main()\n{\n//#if defined GL_OES_standard_derivatives\n//gl_FragColor=v_color*smoothstep(0.0, length(fwidth(v_texcoord)), 1.0-length(v_texcoord));\n//#else\ngl_FragColor = v_color * step(0.0, 1.0 - length(v_texcoord));\n//#endif\n}",
      POSITION_COLOR_LENGTH_TEXTURE_VERT: "attribute mediump vec4 a_position;\nattribute mediump vec2 a_texcoord;\nattribute mediump vec4 a_color;\nvarying mediump vec4 v_color;\nvarying mediump vec2 v_texcoord;\nvoid main()\n{\nv_color = a_color;\nv_texcoord = a_texcoord;\ngl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;\n}",
      POSITION_TEXTURE_FRAG: "precision lowp float;\nvarying vec2 v_texCoord;\nvoid main()\n{\ngl_FragColor = texture2D(CC_Texture0, v_texCoord);\n}",
      POSITION_TEXTURE_VERT: "attribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying mediump vec2 v_texCoord;\nvoid main()\n{\ngl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;\nv_texCoord = a_texCoord;\n}",
      POSITION_TEXTURE_UCOLOR_FRAG: "precision lowp float;\nuniform vec4 u_color;\nvarying vec2 v_texCoord;\nvoid main()\n{\ngl_FragColor=texture2D(CC_Texture0, v_texCoord) * u_color;\n}",
      POSITION_TEXTURE_UCOLOR_VERT: "attribute vec4 a_position;\nattribute vec2 a_texCoord;\nvarying mediump vec2 v_texCoord;\nvoid main()\n{\ngl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;\nv_texCoord = a_texCoord;\n}",
      POSITION_TEXTURE_A8COLOR_FRAG: "precision lowp float;\nvarying vec4 v_fragmentColor;\nvarying vec2 v_texCoord;\nvoid main()\n{\ngl_FragColor = vec4(v_fragmentColor.rgb,\nv_fragmentColor.a * texture2D(CC_Texture0, v_texCoord).a);\n}",
      POSITION_TEXTURE_A8COLOR_VERT: "attribute vec4 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\nvarying mediump vec2 v_texCoord;\nvoid main()\n{\ngl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;\nv_fragmentColor = a_color;\nv_texCoord = a_texCoord;\n}",
      POSITION_TEXTURE_COLOR_FRAG: "precision lowp float;\nvarying vec4 v_fragmentColor;\nvarying vec2 v_texCoord;\nvoid main()\n{\ngl_FragColor = v_fragmentColor * texture2D(CC_Texture0, v_texCoord);\n}",
      POSITION_TEXTURE_COLOR_VERT: "attribute vec4 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\nvarying mediump vec2 v_texCoord;\nvoid main()\n{\ngl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;\nv_fragmentColor = a_color;\nv_texCoord = a_texCoord;\n}",
      SPRITE_POSITION_TEXTURE_COLOR_VERT: "attribute vec4 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\nvarying mediump vec2 v_texCoord;\nvoid main()\n{\ngl_Position = CC_PMatrix * a_position;\nv_fragmentColor = a_color;\nv_texCoord = a_texCoord;\n}",
      POSITION_TEXTURE_COLOR_ALPHATEST_FRAG: "precision lowp float;\nvarying vec4 v_fragmentColor;\nvarying vec2 v_texCoord;\nuniform float CC_alpha_value;\nvoid main()\n{\nvec4 texColor=texture2D(CC_Texture0, v_texCoord);\nif(texColor.a <= CC_alpha_value)\n discard; \ngl_FragColor=texColor*v_fragmentColor;\n}",
      EX_SWITCHMASK_FRAG: "precision lowp float;\nvarying vec4 v_fragmentColor;\nvarying vec2 v_texCoord;\nuniform sampler2D u_texture;\nuniform sampler2D u_mask;\nvoid main()\n{\nvec4 texColorc=texture2D(u_texture, v_texCoord);\nvec4 maskColor=texture2D(u_mask, v_texCoord);\nvec4 finalColor=vec4(texColor.r, texColor.g, texColor.b, maskColor.a*texColor.a);\ngl_FragColor=v_fragmentColor*finalColor;\n}"
    };
  }), {} ],
  273: [ (function(require, module, exports) {
    require("./CCShaders");
    require("./CCShaderCache");
    require("./CCGLProgram");
    require("./CCGLStateCache");
  }), {
    "./CCGLProgram": 269,
    "./CCGLStateCache": 270,
    "./CCShaderCache": 271,
    "./CCShaders": 272
  } ],
  274: [ (function(require, module, exports) {
    var __t = function(v) {
      return {
        u: v.x,
        v: v.y
      };
    };
    cc.DrawNode = _ccsg.Node.extend({
      _buffer: null,
      _blendFunc: null,
      _lineWidth: 1,
      _drawColor: null,
      getBlendFunc: function() {
        return this._blendFunc;
      },
      setBlendFunc: function(blendFunc, dst) {
        if (void 0 === dst) {
          this._blendFunc.src = blendFunc.src;
          this._blendFunc.dst = blendFunc.dst;
        } else {
          this._blendFunc.src = blendFunc;
          this._blendFunc.dst = dst;
        }
      },
      setLineWidth: function(width) {
        this._lineWidth = width;
      },
      getLineWidth: function() {
        return this._lineWidth;
      },
      setDrawColor: function(color) {
        var locDrawColor = this._drawColor;
        locDrawColor.r = color.r;
        locDrawColor.g = color.g;
        locDrawColor.b = color.b;
        locDrawColor.a = null == color.a ? 255 : color.a;
      },
      getDrawColor: function() {
        return cc.color(this._drawColor.r, this._drawColor.g, this._drawColor.b, this._drawColor.a);
      }
    });
    cc.DrawNode.TYPE_DOT = 0;
    cc.DrawNode.TYPE_SEGMENT = 1;
    cc.DrawNode.TYPE_POLY = 2;
    cc.game.once(cc.game.EVENT_RENDERER_INITED, (function() {
      var proto = cc.DrawNode.prototype;
      if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
        cc._DrawNodeElement = function(type, verts, fillColor, lineWidth, lineColor, lineCap, isClosePolygon, isFill, isStroke) {
          var _t = this;
          _t.type = type;
          _t.verts = verts || null;
          _t.fillColor = fillColor || null;
          _t.lineWidth = lineWidth || 0;
          _t.lineColor = lineColor || null;
          _t.lineCap = lineCap || "butt";
          _t.isClosePolygon = isClosePolygon || false;
          _t.isFill = isFill || false;
          _t.isStroke = isStroke || false;
        };
        proto._className = "DrawNodeCanvas";
        proto.ctor = function() {
          _ccsg.Node.prototype.ctor.call(this);
          var locCmd = this._renderCmd;
          locCmd._buffer = this._buffer = [];
          locCmd._drawColor = this._drawColor = cc.color(255, 255, 255, 255);
          locCmd._blendFunc = this._blendFunc = new cc.BlendFunc(cc.macro.SRC_ALPHA, cc.macro.ONE_MINUS_SRC_ALPHA);
          this.init();
        };
        proto.drawRect = function(origin, destination, fillColor, lineWidth, lineColor) {
          lineWidth = null == lineWidth ? this._lineWidth : lineWidth;
          lineColor = lineColor || this.getDrawColor();
          null == lineColor.a && (lineColor.a = 255);
          var vertices = [ origin, cc.p(destination.x, origin.y), destination, cc.p(origin.x, destination.y) ];
          var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY);
          element.verts = vertices;
          element.lineWidth = lineWidth;
          element.lineColor = lineColor;
          element.isClosePolygon = true;
          element.isStroke = true;
          element.lineCap = "butt";
          element.fillColor = fillColor;
          if (fillColor) {
            null == fillColor.a && (fillColor.a = 255);
            element.isFill = true;
          }
          this._buffer.push(element);
        };
        proto.drawCircle = function(center, radius, angle, segments, drawLineToCenter, lineWidth, color) {
          lineWidth = lineWidth || this._lineWidth;
          color = color || this.getDrawColor();
          null == color.a && (color.a = 255);
          var coef = 2 * Math.PI / segments;
          var vertices = [];
          for (var i = 0; i <= segments; i++) {
            var rads = i * coef;
            var j = radius * Math.cos(rads + angle) + center.x;
            var k = radius * Math.sin(rads + angle) + center.y;
            vertices.push(cc.p(j, k));
          }
          drawLineToCenter && vertices.push(cc.p(center.x, center.y));
          var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY);
          element.verts = vertices;
          element.lineWidth = lineWidth;
          element.lineColor = color;
          element.isClosePolygon = true;
          element.isStroke = true;
          this._buffer.push(element);
        };
        proto.drawQuadBezier = function(origin, control, destination, segments, lineWidth, color) {
          lineWidth = lineWidth || this._lineWidth;
          color = color || this.getDrawColor();
          null == color.a && (color.a = 255);
          var vertices = [], t = 0;
          for (var i = 0; i < segments; i++) {
            var x = Math.pow(1 - t, 2) * origin.x + 2 * (1 - t) * t * control.x + t * t * destination.x;
            var y = Math.pow(1 - t, 2) * origin.y + 2 * (1 - t) * t * control.y + t * t * destination.y;
            vertices.push(cc.p(x, y));
            t += 1 / segments;
          }
          vertices.push(cc.p(destination.x, destination.y));
          var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY);
          element.verts = vertices;
          element.lineWidth = lineWidth;
          element.lineColor = color;
          element.isStroke = true;
          element.lineCap = "round";
          this._buffer.push(element);
        };
        proto.drawCubicBezier = function(origin, control1, control2, destination, segments, lineWidth, color) {
          lineWidth = lineWidth || this._lineWidth;
          color = color || this.getDrawColor();
          null == color.a && (color.a = 255);
          var vertices = [], t = 0;
          for (var i = 0; i < segments; i++) {
            var x = Math.pow(1 - t, 3) * origin.x + 3 * Math.pow(1 - t, 2) * t * control1.x + 3 * (1 - t) * t * t * control2.x + t * t * t * destination.x;
            var y = Math.pow(1 - t, 3) * origin.y + 3 * Math.pow(1 - t, 2) * t * control1.y + 3 * (1 - t) * t * t * control2.y + t * t * t * destination.y;
            vertices.push(cc.p(x, y));
            t += 1 / segments;
          }
          vertices.push(cc.p(destination.x, destination.y));
          var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY);
          element.verts = vertices;
          element.lineWidth = lineWidth;
          element.lineColor = color;
          element.isStroke = true;
          element.lineCap = "round";
          this._buffer.push(element);
        };
        proto.drawCatmullRom = function(points, segments, lineWidth, color) {
          this.drawCardinalSpline(points, .5, segments, lineWidth, color);
        };
        proto.drawCardinalSpline = function(config, tension, segments, lineWidth, color) {
          lineWidth = lineWidth || this._lineWidth;
          color = color || this.getDrawColor();
          null == color.a && (color.a = 255);
          var vertices = [], p, lt, deltaT = 1 / config.length;
          for (var i = 0; i < segments + 1; i++) {
            var dt = i / segments;
            if (1 === dt) {
              p = config.length - 1;
              lt = 1;
            } else {
              p = 0 | dt / deltaT;
              lt = (dt - deltaT * p) / deltaT;
            }
            var newPos = cc.cardinalSplineAt(cc.getControlPointAt(config, p - 1), cc.getControlPointAt(config, p - 0), cc.getControlPointAt(config, p + 1), cc.getControlPointAt(config, p + 2), tension, lt);
            vertices.push(newPos);
          }
          var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY);
          element.verts = vertices;
          element.lineWidth = lineWidth;
          element.lineColor = color;
          element.isStroke = true;
          element.lineCap = "round";
          this._buffer.push(element);
        };
        proto.drawDot = function(pos, radius, color) {
          color = color || this.getDrawColor();
          null == color.a && (color.a = 255);
          var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_DOT);
          element.verts = [ pos ];
          element.lineWidth = radius;
          element.fillColor = color;
          this._buffer.push(element);
        };
        proto.drawDots = function(points, radius, color) {
          if (!points || 0 == points.length) return;
          color = color || this.getDrawColor();
          null == color.a && (color.a = 255);
          for (var i = 0, len = points.length; i < len; i++) this.drawDot(points[i], radius, color);
        };
        proto.drawSegment = function(from, to, lineWidth, color) {
          lineWidth = lineWidth || this._lineWidth;
          color = color || this.getDrawColor();
          null == color.a && (color.a = 255);
          var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY);
          element.verts = [ from, to ];
          element.lineWidth = 2 * lineWidth;
          element.lineColor = color;
          element.isStroke = true;
          element.lineCap = "round";
          this._buffer.push(element);
        };
        proto.drawPoly_ = function(verts, fillColor, lineWidth, color, notClosePoly) {
          lineWidth = null == lineWidth ? this._lineWidth : lineWidth;
          color = color || this.getDrawColor();
          null == color.a && (color.a = 255);
          var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY);
          element.verts = verts;
          element.fillColor = fillColor;
          element.lineWidth = lineWidth;
          element.lineColor = color;
          element.isClosePolygon = !notClosePoly;
          element.isStroke = true;
          element.lineCap = "round";
          fillColor && (element.isFill = true);
          this._buffer.push(element);
        };
        proto.drawPoly = function(verts, fillColor, lineWidth, color, notClosePoly) {
          var vertsCopy = [];
          for (var i = 0; i < verts.length; i++) vertsCopy.push(cc.p(verts[i].x, verts[i].y));
          return this.drawPoly_(vertsCopy, fillColor, lineWidth, color, notClosePoly);
        };
        proto.clear = function() {
          this._buffer.length = 0;
        };
        require("./CCDrawNodeCanvasRenderCmd");
        proto._createRenderCmd = function() {
          return new cc.DrawNode.CanvasRenderCmd(this);
        };
      } else if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
        proto._bufferCapacity = 0;
        proto._trianglesArrayBuffer = null;
        proto._trianglesWebBuffer = null;
        proto._trianglesReader = null;
        proto._dirty = false;
        proto._className = "DrawNodeWebGL";
        proto.ctor = function() {
          _ccsg.Node.prototype.ctor.call(this);
          this._buffer = [];
          this._blendFunc = new cc.BlendFunc(cc.macro.SRC_ALPHA, cc.macro.ONE_MINUS_SRC_ALPHA);
          this._drawColor = cc.color(255, 255, 255, 255);
          this.init();
        };
        proto.init = function() {
          if (_ccsg.Node.prototype.init.call(this)) {
            this.shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_LENGTHTEXTURECOLOR);
            this._ensureCapacity(64);
            this._trianglesWebBuffer = cc._renderContext.createBuffer();
            this._dirty = true;
            return true;
          }
          return false;
        };
        proto.drawRect = function(origin, destination, fillColor, lineWidth, lineColor) {
          lineWidth = null == lineWidth ? this._lineWidth : lineWidth;
          lineColor = lineColor || this.getDrawColor();
          null == lineColor.a && (lineColor.a = 255);
          var vertices = [ origin, cc.p(destination.x, origin.y), destination, cc.p(origin.x, destination.y) ];
          null == fillColor ? this._drawSegments(vertices, lineWidth, lineColor, true) : this.drawPoly(vertices, fillColor, lineWidth, lineColor);
        };
        proto.drawCircle = function(center, radius, angle, segments, drawLineToCenter, lineWidth, color) {
          lineWidth = lineWidth || this._lineWidth;
          color = color || this.getDrawColor();
          null == color.a && (color.a = 255);
          var coef = 2 * Math.PI / segments, vertices = [], i, len;
          for (i = 0; i <= segments; i++) {
            var rads = i * coef;
            var j = radius * Math.cos(rads + angle) + center.x;
            var k = radius * Math.sin(rads + angle) + center.y;
            vertices.push(cc.p(j, k));
          }
          drawLineToCenter && vertices.push(cc.p(center.x, center.y));
          lineWidth *= .5;
          for (i = 0, len = vertices.length; i < len - 1; i++) this.drawSegment(vertices[i], vertices[i + 1], lineWidth, color);
        };
        proto.drawQuadBezier = function(origin, control, destination, segments, lineWidth, color) {
          lineWidth = lineWidth || this._lineWidth;
          color = color || this.getDrawColor();
          null == color.a && (color.a = 255);
          var vertices = [], t = 0;
          for (var i = 0; i < segments; i++) {
            var x = Math.pow(1 - t, 2) * origin.x + 2 * (1 - t) * t * control.x + t * t * destination.x;
            var y = Math.pow(1 - t, 2) * origin.y + 2 * (1 - t) * t * control.y + t * t * destination.y;
            vertices.push(cc.p(x, y));
            t += 1 / segments;
          }
          vertices.push(cc.p(destination.x, destination.y));
          this._drawSegments(vertices, lineWidth, color, false);
        };
        proto.drawCubicBezier = function(origin, control1, control2, destination, segments, lineWidth, color) {
          lineWidth = lineWidth || this._lineWidth;
          color = color || this.getDrawColor();
          null == color.a && (color.a = 255);
          var vertices = [], t = 0;
          for (var i = 0; i < segments; i++) {
            var x = Math.pow(1 - t, 3) * origin.x + 3 * Math.pow(1 - t, 2) * t * control1.x + 3 * (1 - t) * t * t * control2.x + t * t * t * destination.x;
            var y = Math.pow(1 - t, 3) * origin.y + 3 * Math.pow(1 - t, 2) * t * control1.y + 3 * (1 - t) * t * t * control2.y + t * t * t * destination.y;
            vertices.push(cc.p(x, y));
            t += 1 / segments;
          }
          vertices.push(cc.p(destination.x, destination.y));
          this._drawSegments(vertices, lineWidth, color, false);
        };
        proto.drawCatmullRom = function(points, segments, lineWidth, color) {
          this.drawCardinalSpline(points, .5, segments, lineWidth, color);
        };
        proto.drawCardinalSpline = function(config, tension, segments, lineWidth, color) {
          lineWidth = lineWidth || this._lineWidth;
          color = color || this.getDrawColor();
          null == color.a && (color.a = 255);
          var vertices = [], p, lt, deltaT = 1 / config.length;
          for (var i = 0; i < segments + 1; i++) {
            var dt = i / segments;
            if (1 === dt) {
              p = config.length - 1;
              lt = 1;
            } else {
              p = 0 | dt / deltaT;
              lt = (dt - deltaT * p) / deltaT;
            }
            var newPos = cc.cardinalSplineAt(cc.getControlPointAt(config, p - 1), cc.getControlPointAt(config, p - 0), cc.getControlPointAt(config, p + 1), cc.getControlPointAt(config, p + 2), tension, lt);
            vertices.push(newPos);
          }
          lineWidth *= .5;
          for (var j = 0, len = vertices.length; j < len - 1; j++) this.drawSegment(vertices[j], vertices[j + 1], lineWidth, color);
        };
        proto._render = function() {
          var gl = cc._renderContext;
          gl.bindBuffer(gl.ARRAY_BUFFER, this._trianglesWebBuffer);
          if (this._dirty) {
            gl.bufferData(gl.ARRAY_BUFFER, this._trianglesArrayBuffer, gl.STREAM_DRAW);
            this._dirty = false;
          }
          var triangleSize = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT;
          gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION);
          gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR);
          gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS);
          gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, triangleSize, 0);
          gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, triangleSize, 8);
          gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, triangleSize, 12);
          gl.drawArrays(gl.TRIANGLES, 0, 3 * this._buffer.length);
          cc.incrementGLDraws(1);
        };
        proto._ensureCapacity = function(count) {
          var _t = this;
          var locBuffer = _t._buffer;
          if (locBuffer.length + count > _t._bufferCapacity) {
            var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT;
            _t._bufferCapacity += Math.max(_t._bufferCapacity, count);
            if (null == locBuffer || 0 === locBuffer.length) {
              _t._buffer = [];
              _t._trianglesArrayBuffer = new ArrayBuffer(TriangleLength * _t._bufferCapacity);
              _t._trianglesReader = new Uint8Array(_t._trianglesArrayBuffer);
            } else {
              var newTriangles = [];
              var newArrayBuffer = new ArrayBuffer(TriangleLength * _t._bufferCapacity);
              for (var i = 0; i < locBuffer.length; i++) newTriangles[i] = new cc.V2F_C4B_T2F_Triangle(locBuffer[i].a, locBuffer[i].b, locBuffer[i].c, newArrayBuffer, i * TriangleLength);
              _t._trianglesReader = new Uint8Array(newArrayBuffer);
              _t._trianglesArrayBuffer = newArrayBuffer;
              _t._buffer = newTriangles;
            }
          }
        };
        proto.drawDot = function(pos, radius, color) {
          color = color || this.getDrawColor();
          null == color.a && (color.a = 255);
          var c4bColor = {
            r: 0 | color.r,
            g: 0 | color.g,
            b: 0 | color.b,
            a: 0 | color.a
          };
          var a = {
            vertices: {
              x: pos.x - radius,
              y: pos.y - radius
            },
            colors: c4bColor,
            texCoords: {
              u: -1,
              v: -1
            }
          };
          var b = {
            vertices: {
              x: pos.x - radius,
              y: pos.y + radius
            },
            colors: c4bColor,
            texCoords: {
              u: -1,
              v: 1
            }
          };
          var c = {
            vertices: {
              x: pos.x + radius,
              y: pos.y + radius
            },
            colors: c4bColor,
            texCoords: {
              u: 1,
              v: 1
            }
          };
          var d = {
            vertices: {
              x: pos.x + radius,
              y: pos.y - radius
            },
            colors: c4bColor,
            texCoords: {
              u: 1,
              v: -1
            }
          };
          this._ensureCapacity(6);
          this._buffer.push(new cc.V2F_C4B_T2F_Triangle(a, b, c, this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT));
          this._buffer.push(new cc.V2F_C4B_T2F_Triangle(a, c, d, this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT));
          this._dirty = true;
        };
        proto.drawDots = function(points, radius, color) {
          if (!points || 0 === points.length) return;
          color = color || this.getDrawColor();
          null == color.a && (color.a = 255);
          for (var i = 0, len = points.length; i < len; i++) this.drawDot(points[i], radius, color);
        };
        proto.drawSegment = function(from, to, radius, color) {
          color = color || this.getDrawColor();
          null == color.a && (color.a = 255);
          radius = radius || .5 * this._lineWidth;
          var vertexCount = 18;
          this._ensureCapacity(vertexCount);
          var c4bColor = {
            r: 0 | color.r,
            g: 0 | color.g,
            b: 0 | color.b,
            a: 0 | color.a
          };
          var a = cc.v2(from), b = cc.v2(to);
          var n = cc.pNormalize(cc.pPerp(cc.pSub(b, a))), t = cc.pPerp(n);
          var nw = cc.pMult(n, radius), tw = cc.pMult(t, radius);
          var v0 = cc.pSub(b, cc.pAdd(nw, tw));
          var v1 = cc.pAdd(b, cc.pSub(nw, tw));
          var v2 = cc.pSub(b, nw);
          var v3 = cc.pAdd(b, nw);
          var v4 = cc.pSub(a, nw);
          var v5 = cc.pAdd(a, nw);
          var v6 = cc.pSub(a, cc.pSub(nw, tw));
          var v7 = cc.pAdd(a, cc.pAdd(nw, tw));
          var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, triangleBuffer = this._trianglesArrayBuffer, locBuffer = this._buffer;
          locBuffer.push(new cc.V2F_C4B_T2F_Triangle({
            vertices: v0,
            colors: c4bColor,
            texCoords: __t(cc.pNeg(cc.pAdd(n, t)))
          }, {
            vertices: v1,
            colors: c4bColor,
            texCoords: __t(cc.pSub(n, t))
          }, {
            vertices: v2,
            colors: c4bColor,
            texCoords: __t(cc.pNeg(n))
          }, triangleBuffer, locBuffer.length * TriangleLength));
          locBuffer.push(new cc.V2F_C4B_T2F_Triangle({
            vertices: v3,
            colors: c4bColor,
            texCoords: __t(n)
          }, {
            vertices: v1,
            colors: c4bColor,
            texCoords: __t(cc.pSub(n, t))
          }, {
            vertices: v2,
            colors: c4bColor,
            texCoords: __t(cc.pNeg(n))
          }, triangleBuffer, locBuffer.length * TriangleLength));
          locBuffer.push(new cc.V2F_C4B_T2F_Triangle({
            vertices: v3,
            colors: c4bColor,
            texCoords: __t(n)
          }, {
            vertices: v4,
            colors: c4bColor,
            texCoords: __t(cc.pNeg(n))
          }, {
            vertices: v2,
            colors: c4bColor,
            texCoords: __t(cc.pNeg(n))
          }, triangleBuffer, locBuffer.length * TriangleLength));
          locBuffer.push(new cc.V2F_C4B_T2F_Triangle({
            vertices: v3,
            colors: c4bColor,
            texCoords: __t(n)
          }, {
            vertices: v4,
            colors: c4bColor,
            texCoords: __t(cc.pNeg(n))
          }, {
            vertices: v5,
            colors: c4bColor,
            texCoords: __t(n)
          }, triangleBuffer, locBuffer.length * TriangleLength));
          locBuffer.push(new cc.V2F_C4B_T2F_Triangle({
            vertices: v6,
            colors: c4bColor,
            texCoords: __t(cc.pSub(t, n))
          }, {
            vertices: v4,
            colors: c4bColor,
            texCoords: __t(cc.pNeg(n))
          }, {
            vertices: v5,
            colors: c4bColor,
            texCoords: __t(n)
          }, triangleBuffer, locBuffer.length * TriangleLength));
          locBuffer.push(new cc.V2F_C4B_T2F_Triangle({
            vertices: v6,
            colors: c4bColor,
            texCoords: __t(cc.pSub(t, n))
          }, {
            vertices: v7,
            colors: c4bColor,
            texCoords: __t(cc.pAdd(n, t))
          }, {
            vertices: v5,
            colors: c4bColor,
            texCoords: __t(n)
          }, triangleBuffer, locBuffer.length * TriangleLength));
          this._dirty = true;
        };
        proto.drawPoly = function(verts, fillColor, borderWidth, borderColor, notClosePoly) {
          if (null == fillColor) {
            this._drawSegments(verts, borderWidth, borderColor, !notClosePoly);
            return;
          }
          null == fillColor.a && (fillColor.a = 255);
          null == borderColor.a && (borderColor.a = 255);
          borderWidth = null == borderWidth ? this._lineWidth : borderWidth;
          borderWidth *= .5;
          var c4bFillColor = {
            r: 0 | fillColor.r,
            g: 0 | fillColor.g,
            b: 0 | fillColor.b,
            a: 0 | fillColor.a
          };
          var c4bBorderColor = {
            r: 0 | borderColor.r,
            g: 0 | borderColor.g,
            b: 0 | borderColor.b,
            a: 0 | borderColor.a
          };
          var extrude = [], i, v0, v1, v2, count = verts.length;
          for (i = 0; i < count; i++) {
            v0 = cc.v2(verts[(i - 1 + count) % count]);
            v1 = cc.v2(verts[i]);
            v2 = cc.v2(verts[(i + 1) % count]);
            var n1 = cc.pNormalize(cc.pPerp(cc.pSub(v1, v0)));
            var n2 = cc.pNormalize(cc.pPerp(cc.pSub(v2, v1)));
            var offset = cc.pMult(cc.pAdd(n1, n2), 1 / (cc.pDot(n1, n2) + 1));
            extrude[i] = {
              offset: offset,
              n: n2
            };
          }
          var outline = borderWidth > 0, triangleCount = 3 * count - 2, vertexCount = 3 * triangleCount;
          this._ensureCapacity(vertexCount);
          var triangleBytesLen = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, trianglesBuffer = this._trianglesArrayBuffer;
          var locBuffer = this._buffer;
          var va, vb, vc;
          for (i = 0; i < count - 2; i++) {
            va = {
              vertices: verts[0],
              colors: c4bFillColor,
              texCoords: __t(cc.v2())
            };
            vb = {
              vertices: verts[i + 1],
              colors: c4bFillColor,
              texCoords: __t(cc.v2())
            };
            vc = {
              vertices: verts[i + 2],
              colors: c4bFillColor,
              texCoords: __t(cc.v2())
            };
            locBuffer.push(new cc.V2F_C4B_T2F_Triangle(va, vb, vc, trianglesBuffer, locBuffer.length * triangleBytesLen));
          }
          if (outline) for (i = 0; i < count; i++) {
            var j = (i + 1) % count;
            v0 = cc.v2(verts[i]);
            v1 = cc.v2(verts[j]);
            var n0 = extrude[i].n;
            var offset0 = extrude[i].offset;
            var offset1 = extrude[j].offset;
            var inner0 = cc.pSub(v0, cc.pMult(offset0, borderWidth));
            var inner1 = cc.pSub(v1, cc.pMult(offset1, borderWidth));
            var outer0 = cc.pAdd(v0, cc.pMult(offset0, borderWidth));
            var outer1 = cc.pAdd(v1, cc.pMult(offset1, borderWidth));
            va = {
              vertices: inner0,
              colors: c4bBorderColor,
              texCoords: __t(cc.pNeg(n0))
            };
            vb = {
              vertices: inner1,
              colors: c4bBorderColor,
              texCoords: __t(cc.pNeg(n0))
            };
            vc = {
              vertices: outer1,
              colors: c4bBorderColor,
              texCoords: __t(n0)
            };
            locBuffer.push(new cc.V2F_C4B_T2F_Triangle(va, vb, vc, trianglesBuffer, locBuffer.length * triangleBytesLen));
            va = {
              vertices: inner0,
              colors: c4bBorderColor,
              texCoords: __t(cc.pNeg(n0))
            };
            vb = {
              vertices: outer0,
              colors: c4bBorderColor,
              texCoords: __t(n0)
            };
            vc = {
              vertices: outer1,
              colors: c4bBorderColor,
              texCoords: __t(n0)
            };
            locBuffer.push(new cc.V2F_C4B_T2F_Triangle(va, vb, vc, trianglesBuffer, locBuffer.length * triangleBytesLen));
          }
          extrude = null;
          this._dirty = true;
        };
        proto._drawSegments = function(verts, borderWidth, borderColor, closePoly) {
          borderWidth = null == borderWidth ? this._lineWidth : borderWidth;
          borderColor = borderColor || this._drawColor;
          null == borderColor.a && (borderColor.a = 255);
          borderWidth *= .5;
          if (borderWidth <= 0) return;
          var c4bBorderColor = {
            r: 0 | borderColor.r,
            g: 0 | borderColor.g,
            b: 0 | borderColor.b,
            a: 0 | borderColor.a
          };
          var extrude = [], i, v0, v1, v2, count = verts.length;
          for (i = 0; i < count; i++) {
            v0 = cc.v2(verts[(i - 1 + count) % count]);
            v1 = cc.v2(verts[i]);
            v2 = cc.v2(verts[(i + 1) % count]);
            var n1 = cc.pNormalize(cc.pPerp(cc.pSub(v1, v0)));
            var n2 = cc.pNormalize(cc.pPerp(cc.pSub(v2, v1)));
            var offset = cc.pMult(cc.pAdd(n1, n2), 1 / (cc.pDot(n1, n2) + 1));
            extrude[i] = {
              offset: offset,
              n: n2
            };
          }
          var triangleCount = 3 * count - 2, vertexCount = 3 * triangleCount;
          this._ensureCapacity(vertexCount);
          var triangleBytesLen = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, trianglesBuffer = this._trianglesArrayBuffer;
          var locBuffer = this._buffer;
          var len = closePoly ? count : count - 1;
          for (i = 0; i < len; i++) {
            var j = (i + 1) % count;
            v0 = cc.v2(verts[i]);
            v1 = cc.v2(verts[j]);
            var n0 = extrude[i].n;
            var offset0 = extrude[i].offset;
            var offset1 = extrude[j].offset;
            var inner0 = cc.pSub(v0, cc.pMult(offset0, borderWidth));
            var inner1 = cc.pSub(v1, cc.pMult(offset1, borderWidth));
            var outer0 = cc.pAdd(v0, cc.pMult(offset0, borderWidth));
            var outer1 = cc.pAdd(v1, cc.pMult(offset1, borderWidth));
            locBuffer.push(new cc.V2F_C4B_T2F_Triangle({
              vertices: inner0,
              colors: c4bBorderColor,
              texCoords: __t(cc.pNeg(n0))
            }, {
              vertices: inner1,
              colors: c4bBorderColor,
              texCoords: __t(cc.pNeg(n0))
            }, {
              vertices: outer1,
              colors: c4bBorderColor,
              texCoords: __t(n0)
            }, trianglesBuffer, locBuffer.length * triangleBytesLen));
            locBuffer.push(new cc.V2F_C4B_T2F_Triangle({
              vertices: inner0,
              colors: c4bBorderColor,
              texCoords: __t(cc.pNeg(n0))
            }, {
              vertices: outer0,
              colors: c4bBorderColor,
              texCoords: __t(n0)
            }, {
              vertices: outer1,
              colors: c4bBorderColor,
              texCoords: __t(n0)
            }, trianglesBuffer, locBuffer.length * triangleBytesLen));
          }
          extrude = null;
          this._dirty = true;
        };
        proto.clear = function() {
          this._buffer.length = 0;
          this._dirty = true;
        };
        require("./CCDrawNodeWebGLRenderCmd");
        proto._createRenderCmd = function() {
          return new cc.DrawNode.WebGLRenderCmd(this);
        };
      }
    }));
  }), {
    "./CCDrawNodeCanvasRenderCmd": 275,
    "./CCDrawNodeWebGLRenderCmd": 276
  } ],
  275: [ (function(require, module, exports) {
    cc.DrawNode.CanvasRenderCmd = function(renderableObject) {
      this._rootCtor(renderableObject);
      this._needDraw = true;
      this._buffer = null;
      this._drawColor = null;
      this._blendFunc = null;
    };
    var proto = cc.DrawNode.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
    proto.constructor = cc.DrawNode.CanvasRenderCmd;
    proto.rendering = function(ctx, scaleX, scaleY) {
      var wrapper = ctx || cc._renderContext, context = wrapper.getContext(), node = this._node;
      var alpha = node._displayedOpacity / 255;
      if (0 === alpha) return;
      wrapper.setTransform(this._worldTransform, scaleX, scaleY);
      wrapper.setGlobalAlpha(alpha);
      this._blendFunc && this._blendFunc.src === cc.macro.SRC_ALPHA && this._blendFunc.dst === cc.macro.ONE && wrapper.setCompositeOperation("lighter");
      var locBuffer = this._buffer;
      for (var i = 0, len = locBuffer.length; i < len; i++) {
        var element = locBuffer[i];
        switch (element.type) {
         case cc.DrawNode.TYPE_DOT:
          this._drawDot(wrapper, element, scaleX, scaleY);
          break;

         case cc.DrawNode.TYPE_SEGMENT:
          this._drawSegment(wrapper, element, scaleX, scaleY);
          break;

         case cc.DrawNode.TYPE_POLY:
          this._drawPoly(wrapper, element, scaleX, scaleY);
        }
      }
    };
    proto._drawDot = function(wrapper, element, scaleX, scaleY) {
      var locColor = element.fillColor, locPos = element.verts[0], locRadius = element.lineWidth;
      var ctx = wrapper.getContext();
      wrapper.setFillStyle("rgba(" + (0 | locColor.r) + "," + (0 | locColor.g) + "," + (0 | locColor.b) + "," + locColor.a / 255 + ")");
      ctx.beginPath();
      ctx.arc(locPos.x, -locPos.y, locRadius, 0, 2 * Math.PI, false);
      ctx.closePath();
      ctx.fill();
    };
    proto._drawSegment = function(wrapper, element, scaleX, scaleY) {
      var locColor = element.lineColor;
      var locFrom = element.verts[0], locTo = element.verts[1];
      var locLineWidth = element.lineWidth, locLineCap = element.lineCap;
      var ctx = wrapper.getContext();
      wrapper.setStrokeStyle("rgba(" + (0 | locColor.r) + "," + (0 | locColor.g) + "," + (0 | locColor.b) + "," + locColor.a / 255 + ")");
      ctx.lineWidth = locLineWidth * scaleX;
      ctx.beginPath();
      ctx.lineCap = locLineCap;
      ctx.moveTo(locFrom.x, -locFrom.y);
      ctx.lineTo(locTo.x, -locTo.y);
      ctx.stroke();
    };
    proto._drawPoly = function(wrapper, element, scaleX, scaleY) {
      var locVertices = element.verts, locLineCap = element.lineCap;
      if (null == locVertices) return;
      var locFillColor = element.fillColor, locLineWidth = element.lineWidth;
      var locLineColor = element.lineColor, locIsClosePolygon = element.isClosePolygon;
      var locIsFill = element.isFill, locIsStroke = element.isStroke;
      var ctx = wrapper.getContext();
      var firstPoint = locVertices[0];
      ctx.lineCap = locLineCap;
      locFillColor && wrapper.setFillStyle("rgba(" + (0 | locFillColor.r) + "," + (0 | locFillColor.g) + "," + (0 | locFillColor.b) + "," + locFillColor.a / 255 + ")");
      locLineWidth && (ctx.lineWidth = locLineWidth * scaleX);
      locLineColor && wrapper.setStrokeStyle("rgba(" + (0 | locLineColor.r) + "," + (0 | locLineColor.g) + "," + (0 | locLineColor.b) + "," + locLineColor.a / 255 + ")");
      ctx.beginPath();
      ctx.moveTo(firstPoint.x, -firstPoint.y);
      for (var i = 1, len = locVertices.length; i < len; i++) ctx.lineTo(locVertices[i].x, -locVertices[i].y);
      locIsClosePolygon && ctx.closePath();
      locIsFill && ctx.fill();
      locIsStroke && ctx.stroke();
    };
  }), {} ],
  276: [ (function(require, module, exports) {
    cc.DrawNode.WebGLRenderCmd = function(renderableObject) {
      this._rootCtor(renderableObject);
      this._needDraw = true;
      this._matrix = new cc.math.Matrix4();
      this._matrix.identity();
    };
    cc.DrawNode.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype);
    cc.DrawNode.WebGLRenderCmd.prototype.constructor = cc.DrawNode.WebGLRenderCmd;
    cc.DrawNode.WebGLRenderCmd.prototype.rendering = function(ctx) {
      var node = this._node;
      if (node._buffer.length > 0) {
        var wt = this._worldTransform, mat = this._matrix.mat;
        mat[0] = wt.a;
        mat[4] = wt.c;
        mat[12] = wt.tx;
        mat[1] = wt.b;
        mat[5] = wt.d;
        mat[13] = wt.ty;
        cc.gl.blendFunc(node._blendFunc.src, node._blendFunc.dst);
        this._shaderProgram.use();
        this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix);
        node._render();
      }
    };
  }), {} ],
  277: [ (function(require, module, exports) {
    _ccsg.TMXLayer = _ccsg.Node.extend({
      tiles: null,
      tileset: null,
      layerOrientation: null,
      properties: null,
      layerName: "",
      _texture: null,
      _textures: null,
      _texGrids: null,
      _spriteTiles: null,
      _layerSize: null,
      _mapTileSize: null,
      _opacity: 255,
      _minGID: null,
      _maxGID: null,
      _vertexZvalue: null,
      _useAutomaticVertexZ: null,
      _reusedTile: null,
      _contentScaleFactor: null,
      _staggerAxis: null,
      _staggerIndex: null,
      _hexSideLength: 0,
      _className: "TMXLayer",
      ctor: function(tilesetInfo, layerInfo, mapInfo) {
        cc.SpriteBatchNode.prototype.ctor.call(this);
        this._layerSize = cc.size(0, 0);
        this._mapTileSize = cc.size(0, 0);
        this._spriteTiles = {};
        this._staggerAxis = cc.TiledMap.StaggerAxis.STAGGERAXIS_Y;
        this._staggerIndex = cc.TiledMap.StaggerIndex.STAGGERINDEX_EVEN;
        void 0 !== mapInfo && this.initWithTilesetInfo(tilesetInfo, layerInfo, mapInfo);
      },
      _createRenderCmd: function() {
        return cc._renderType === cc.game.RENDER_TYPE_CANVAS ? new _ccsg.TMXLayer.CanvasRenderCmd(this) : new _ccsg.TMXLayer.WebGLRenderCmd(this);
      },
      _fillTextureGrids: function(tileset, texId) {
        var tex = this._textures[texId];
        if (!tex.isLoaded()) {
          tex.once("load", (function() {
            this._fillTextureGrids(tileset, texId);
          }), this);
          return;
        }
        if (!tileset.imageSize.width || !tileset.imageSize.height) {
          tileset.imageSize.width = tex.width;
          tileset.imageSize.height = tex.height;
        }
        var tw = tileset._tileSize.width, th = tileset._tileSize.height, imageW = tex.width, imageH = tex.height, spacing = tileset.spacing, margin = tileset.margin, cols = Math.floor((imageW - 2 * margin + spacing) / (tw + spacing)), rows = Math.floor((imageH - 2 * margin + spacing) / (th + spacing)), count = rows * cols, gid = tileset.firstGid, maxGid = tileset.firstGid + count, grids = this._texGrids, grid = null, override = !!grids[gid], texelCorrect = cc.macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL_TMX ? .5 : 0;
        for (;gid < maxGid; ++gid) {
          override && !grids[gid] && (override = false);
          if (!override && grids[gid]) break;
          grid = {
            texId: texId,
            x: 0,
            y: 0,
            width: tw,
            height: th,
            t: 0,
            l: 0,
            r: 0,
            b: 0
          };
          tileset.rectForGID(gid, grid);
          grid.x += texelCorrect;
          grid.y += texelCorrect;
          grid.width -= 2 * texelCorrect;
          grid.height -= 2 * texelCorrect;
          grid.t = grid.y / imageH;
          grid.l = grid.x / imageW;
          grid.r = (grid.x + grid.width) / imageW;
          grid.b = (grid.y + grid.height) / imageH;
          grids[gid] = grid;
        }
      },
      initWithTilesetInfo: function(tilesetInfo, layerInfo, 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;
        this._staggerAxis = mapInfo.getStaggerAxis();
        this._staggerIndex = mapInfo.getStaggerIndex();
        this._hexSideLength = mapInfo.getHexSideLength();
        this.tileset = tilesetInfo;
        this.layerOrientation = mapInfo.orientation;
        this._mapTileSize = mapInfo.getTileSize();
        var tilesets = mapInfo._tilesets;
        if (tilesets) {
          var i, len = tilesets.length, tileset, tex;
          this._textures = new Array(len);
          this._texGrids = [];
          for (i = 0; i < len; ++i) {
            tileset = tilesets[i];
            tex = cc.textureCache.addImage(tileset.sourceImage, (function(tex) {
              tex.setAliasTexParameters();
            }));
            this._textures[i] = tex;
            this._fillTextureGrids(tileset, i);
            tileset === tilesetInfo && (this._texture = tex);
          }
        }
        var offset = this._calculateLayerOffset(layerInfo.offset);
        this.setPosition(offset);
        this._parseInternalProperties();
        if (this.layerOrientation === cc.TiledMap.Orientation.HEX) {
          var width = 0, height = 0;
          if (this._staggerAxis === cc.TiledMap.StaggerAxis.STAGGERAXIS_X) {
            height = mapInfo._tileSize.height * (this._layerSize.height + .5);
            width = (mapInfo._tileSize.width + this._hexSideLength) * Math.floor(this._layerSize.width / 2) + mapInfo._tileSize.width * (this._layerSize.width % 2);
          } else {
            width = mapInfo._tileSize.width * (this._layerSize.width + .5);
            height = (mapInfo._tileSize.height + this._hexSideLength) * Math.floor(this._layerSize.height / 2) + mapInfo._tileSize.height * (this._layerSize.height % 2);
          }
          this.setContentSize(width, height);
        } else this.setContentSize(this._layerSize.width * this._mapTileSize.width, this._layerSize.height * this._mapTileSize.height);
        this._useAutomaticVertexZ = false;
        this._vertexZvalue = 0;
        return true;
      },
      visit: function(parent) {
        var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null;
        if (!this._visible) {
          cmd._propagateFlagsDown(parentCmd);
          return;
        }
        var renderer = cc.renderer;
        cmd.visit(parentCmd);
        var i, children = this._children, len = children.length, child, isCanvas = cc._renderType === cc.game.RENDER_TYPE_CANVAS, spTiles = this._spriteTiles;
        if (len > 0) {
          this._reorderChildDirty && this.sortAllChildren();
          for (i = 0; i < len; i++) {
            child = children[i];
            if (!(child._localZOrder < 0)) break;
            child.visit(this);
          }
          renderer.pushRenderCommand(cmd);
          for (;i < len; i++) {
            child = children[i];
            if (isCanvas && 0 === child._localZOrder && spTiles[child.tag]) {
              if (isNaN(child._customZ)) {
                child._vertexZ = renderer.assignedZ;
                renderer.assignedZ += renderer.assignedZStep;
              }
              child._renderCmd.updateStatus();
              continue;
            }
            child.visit(this);
          }
        } else renderer.pushRenderCommand(cmd);
        cc._renderType === cc.game.RENDER_TYPE_WEBGL && renderer.pushRenderCommand(this._renderCmd._disableDepthTestCmd);
        cmd._dirtyFlag = 0;
      },
      getLayerSize: function() {
        return cc.size(this._layerSize.width, this._layerSize.height);
      },
      setLayerSize: function(Var) {
        this._layerSize.width = Var.width;
        this._layerSize.height = Var.height;
      },
      _getLayerWidth: function() {
        return this._layerSize.width;
      },
      _setLayerWidth: function(width) {
        this._layerSize.width = width;
      },
      _getLayerHeight: function() {
        return this._layerSize.height;
      },
      _setLayerHeight: function(height) {
        this._layerSize.height = height;
      },
      getMapTileSize: function() {
        return cc.size(this._mapTileSize.width, this._mapTileSize.height);
      },
      setMapTileSize: function(Var) {
        this._mapTileSize.width = Var.width;
        this._mapTileSize.height = Var.height;
      },
      _getTileWidth: function() {
        return this._mapTileSize.width;
      },
      _setTileWidth: function(width) {
        this._mapTileSize.width = width;
      },
      _getTileHeight: function() {
        return this._mapTileSize.height;
      },
      _setTileHeight: function(height) {
        this._mapTileSize.height = height;
      },
      getTiles: function() {
        return this.tiles;
      },
      setTiles: function(Var) {
        this.tiles = Var;
      },
      getTileSet: function() {
        return this.tileset;
      },
      setTileSet: function(Var) {
        this.tileset = Var;
      },
      getLayerOrientation: function() {
        return this.layerOrientation;
      },
      setLayerOrientation: function(Var) {
        this.layerOrientation = Var;
      },
      getProperties: function() {
        return this.properties;
      },
      setProperties: function(Var) {
        this.properties = Var;
      },
      getProperty: function(propertyName) {
        return this.properties[propertyName];
      },
      getLayerName: function() {
        return this.layerName;
      },
      setLayerName: function(layerName) {
        this.layerName = layerName;
      },
      releaseMap: function() {
        this._spriteTiles = {};
      },
      getTileAt: function(pos, y) {
        if (void 0 === pos) throw new Error("_ccsg.TMXLayer.getTileAt(): pos should be non-null");
        var x = pos;
        if (void 0 === y) {
          x = pos.x;
          y = pos.y;
        }
        if (x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0) throw new Error("_ccsg.TMXLayer.getTileAt(): invalid position");
        if (!this.tiles) {
          cc.logID(7204);
          return null;
        }
        var tile = null, gid = this.getTileGIDAt(x, y);
        if (0 === gid) return tile;
        var z = Math.floor(x) + Math.floor(y) * this._layerSize.width;
        tile = this._spriteTiles[z];
        if (!tile) {
          var rect = this._texGrids[gid];
          var tex = this._textures[rect.texId];
          tile = new _ccsg.Sprite(tex, rect);
          tile.setPosition(this.getPositionAt(x, y));
          var vertexZ = this._vertexZForPos(x, y);
          tile.setVertexZ(vertexZ);
          tile.setAnchorPoint(0, 0);
          tile.setOpacity(this._opacity);
          this.addChild(tile, vertexZ, z);
        }
        return tile;
      },
      getTileGIDAt: function(pos, y) {
        if (void 0 === pos) throw new Error("_ccsg.TMXLayer.getTileGIDAt(): pos should be non-null");
        var x = pos;
        if (void 0 === y) {
          x = pos.x;
          y = pos.y;
        }
        if (x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0) throw new Error("_ccsg.TMXLayer.getTileGIDAt(): invalid position");
        if (!this.tiles) {
          cc.logID(7205);
          return null;
        }
        var idx = Math.floor(x) + Math.floor(y) * this._layerSize.width;
        var tile = this.tiles[idx];
        return (tile & cc.TiledMap.TileFlag.FLIPPED_MASK) >>> 0;
      },
      setTileGID: function(gid, posOrX, flagsOrY, flags) {
        if (void 0 === posOrX) throw new Error("_ccsg.TMXLayer.setTileGID(): pos should be non-null");
        var pos;
        if (void 0 === flags && posOrX instanceof cc.Vec2) {
          pos = posOrX;
          flags = flagsOrY;
        } else pos = cc.p(posOrX, flagsOrY);
        pos.x = Math.floor(pos.x);
        pos.y = Math.floor(pos.y);
        if (pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) throw new Error("_ccsg.TMXLayer.setTileGID(): invalid position");
        if (!this.tiles) {
          cc.logID(7206);
          return;
        }
        if (0 !== gid && gid < this.tileset.firstGid) {
          cc.logID(7207, gid);
          return;
        }
        flags = flags || 0;
        var currentFlags = this.getTileFlagsAt(pos);
        var currentGID = this.getTileGIDAt(pos);
        if (currentGID !== gid || currentFlags !== flags) {
          var gidAndFlags = (gid | flags) >>> 0;
          if (0 === gid) this.removeTileAt(pos); else if (0 === currentGID) this._updateTileForGID(gidAndFlags, pos); else {
            var z = pos.x + pos.y * this._layerSize.width;
            var sprite = this.getChildByTag(z);
            if (sprite) {
              var rect = this._texGrids[gid];
              var tex = this._textures[rect.texId];
              sprite.setTexture(tex);
              sprite.setTextureRect(rect, false);
              null != flags && this._setupTileSprite(sprite, pos, gidAndFlags);
              this.tiles[z] = gidAndFlags;
            } else this._updateTileForGID(gidAndFlags, pos);
          }
        }
      },
      addChild: function(child, localZOrder, tag) {
        _ccsg.Node.prototype.addChild.call(this, child, localZOrder, tag);
        if (void 0 !== tag) {
          this._spriteTiles[tag] = child;
          child._vertexZ = this._vertexZ + cc.renderer.assignedZStep * tag / this.tiles.length;
        }
      },
      removeChild: function(child, cleanup) {
        this._spriteTiles[child.tag] && (this._spriteTiles[child.tag] = null);
        _ccsg.Node.prototype.removeChild.call(this, child, cleanup);
      },
      getTileFlagsAt: function(pos, y) {
        if (!pos) throw new Error("_ccsg.TMXLayer.getTileFlagsAt(): pos should be non-null");
        void 0 !== y && (pos = cc.p(pos, y));
        if (pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) throw new Error("_ccsg.TMXLayer.getTileFlagsAt(): invalid position");
        if (!this.tiles) {
          cc.logID(7208);
          return null;
        }
        var idx = Math.floor(pos.x) + Math.floor(pos.y) * this._layerSize.width;
        var tile = this.tiles[idx];
        return (tile & cc.TiledMap.TileFlag.FLIPPED_ALL) >>> 0;
      },
      removeTileAt: function(pos, y) {
        if (!pos) throw new Error("_ccsg.TMXLayer.removeTileAt(): pos should be non-null");
        void 0 !== y && (pos = cc.p(pos, y));
        if (pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) throw new Error("_ccsg.TMXLayer.removeTileAt(): invalid position");
        if (!this.tiles) {
          cc.logID(7209);
          return;
        }
        var gid = this.getTileGIDAt(pos);
        if (0 !== gid) {
          var z = Math.floor(pos.x) + Math.floor(pos.y) * this._layerSize.width;
          this.tiles[z] = 0;
          var sprite = this._spriteTiles[z];
          sprite && this.removeChild(sprite, true);
        }
      },
      getPositionAt: function(pos, y) {
        void 0 !== y && (pos = cc.p(pos, y));
        pos.x = Math.floor(pos.x);
        pos.y = Math.floor(pos.y);
        var ret = cc.p(0, 0);
        switch (this.layerOrientation) {
         case cc.TiledMap.Orientation.ORTHO:
          ret = this._positionForOrthoAt(pos);
          break;

         case cc.TiledMap.Orientation.ISO:
          ret = this._positionForIsoAt(pos);
          break;

         case cc.TiledMap.Orientation.HEX:
          ret = this._positionForHexAt(pos);
        }
        return ret;
      },
      _positionForIsoAt: function(pos) {
        return cc.p(this._mapTileSize.width / 2 * (this._layerSize.width + pos.x - pos.y - 1), this._mapTileSize.height / 2 * (2 * this._layerSize.height - pos.x - pos.y - 2));
      },
      _positionForOrthoAt: function(pos) {
        return cc.p(pos.x * this._mapTileSize.width, (this._layerSize.height - pos.y - 1) * this._mapTileSize.height);
      },
      _positionForHexAt: function(pos) {
        var xy = cc.p(0, 0);
        var offset = this.tileset.tileOffset;
        var odd_even = this._staggerIndex === cc.TiledMap.StaggerIndex.STAGGERINDEX_ODD ? 1 : -1;
        switch (this._staggerAxis) {
         case cc.TiledMap.StaggerAxis.STAGGERAXIS_Y:
          var diffX = 0;
          pos.y % 2 === 1 && (diffX = this._mapTileSize.width / 2 * odd_even);
          xy = cc.p(pos.x * this._mapTileSize.width + diffX + offset.x, (this._layerSize.height - pos.y - 1) * (this._mapTileSize.height - (this._mapTileSize.height - this._hexSideLength) / 2) - offset.y);
          break;

         case cc.TiledMap.StaggerAxis.STAGGERAXIS_X:
          var diffY = 0;
          pos.x % 2 === 1 && (diffY = this._mapTileSize.height / 2 * -odd_even);
          xy = cc.p(pos.x * (this._mapTileSize.width - (this._mapTileSize.width - this._hexSideLength) / 2) + offset.x, (this._layerSize.height - pos.y - 1) * this._mapTileSize.height + diffY - offset.y);
        }
        return xy;
      },
      _calculateLayerOffset: function(pos) {
        var ret = cc.p(0, 0);
        switch (this.layerOrientation) {
         case cc.TiledMap.Orientation.ORTHO:
          ret = cc.p(pos.x * this._mapTileSize.width, -pos.y * this._mapTileSize.height);
          break;

         case cc.TiledMap.Orientation.ISO:
          ret = cc.p(this._mapTileSize.width / 2 * (pos.x - pos.y), this._mapTileSize.height / 2 * (-pos.x - pos.y));
          break;

         case cc.TiledMap.Orientation.HEX:
          if (this._staggerAxis === cc.TiledMap.StaggerAxis.STAGGERAXIS_Y) {
            var diffX = this._staggerIndex === cc.TiledMap.StaggerIndex.STAGGERINDEX_EVEN ? this._mapTileSize.width / 2 : 0;
            ret = cc.p(pos.x * this._mapTileSize.width + diffX, -pos.y * (this._mapTileSize.height - (this._mapTileSize.width - this._hexSideLength) / 2));
          } else if (this._staggerAxis === cc.TiledMap.StaggerAxis.STAGGERAXIS_X) {
            var diffY = this._staggerIndex === cc.TiledMap.StaggerIndex.STAGGERINDEX_ODD ? this._mapTileSize.height / 2 : 0;
            ret = cc.p(pos.x * (this._mapTileSize.width - (this._mapTileSize.width - this._hexSideLength) / 2), -pos.y * this._mapTileSize.height + diffY);
          }
        }
        return ret;
      },
      _updateTileForGID: function(gid, pos) {
        if (!this._texGrids[gid]) return;
        var idx = 0 | pos.x + pos.y * this._layerSize.width;
        idx < this.tiles.length && (this.tiles[idx] = gid);
      },
      _parseInternalProperties: function() {
        var vertexz = this.getProperty("cc_vertexz");
        if (vertexz) if ("automatic" === vertexz) {
          this._useAutomaticVertexZ = true;
          var alphaFuncVal = this.getProperty("cc_alpha_func");
          var alphaFuncValue = 0;
          alphaFuncVal && (alphaFuncValue = parseFloat(alphaFuncVal));
          if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
            this.shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST);
            this.shaderProgram.use();
            this.shaderProgram.setUniformLocationWith1f(cc.UNIFORM_ALPHA_TEST_VALUE_S, alphaFuncValue);
          }
        } else this._vertexZvalue = parseInt(vertexz, 10);
      },
      _setupTileSprite: function(sprite, pos, gid) {
        var posInPixel = this.getPositionAt(pos);
        sprite.setPosition(posInPixel);
        sprite.setVertexZ(this._vertexZForPos(pos));
        sprite.setAnchorPoint(0, 0);
        sprite.setOpacity(this._opacity);
        sprite.setFlippedX(false);
        sprite.setFlippedY(false);
        sprite.setRotation(0);
        if ((gid & cc.TiledMap.TileFlag.DIAGONAL) >>> 0) {
          sprite.setAnchorPoint(.5, .5);
          sprite.setPosition(posInPixel.x + sprite.width / 2, posInPixel.y + sprite.height / 2);
          var flag = (gid & (cc.TiledMap.TileFlag.HORIZONTAL | cc.TiledMap.TileFlag.VERTICAL) >>> 0) >>> 0;
          if (flag === cc.TiledMap.TileFlag.HORIZONTAL) sprite.setRotation(90); else if (flag === cc.TiledMap.TileFlag.VERTICAL) sprite.setRotation(270); else if (flag === (cc.TiledMap.TileFlag.VERTICAL | cc.TiledMap.TileFlag.HORIZONTAL) >>> 0) {
            sprite.setRotation(90);
            sprite.setFlippedX(true);
          } else {
            sprite.setRotation(270);
            sprite.setFlippedX(true);
          }
        } else {
          (gid & cc.TiledMap.TileFlag.HORIZONTAL) >>> 0 && sprite.setFlippedX(true);
          (gid & cc.TiledMap.TileFlag.VERTICAL) >>> 0 && sprite.setFlippedY(true);
        }
      },
      _vertexZForPos: function(x, y) {
        if (void 0 === y) {
          y = x.y;
          x = x.x;
        }
        var ret = 0;
        var maxVal = 0;
        if (this._useAutomaticVertexZ) switch (this.layerOrientation) {
         case cc.TiledMap.Orientation.ISO:
          maxVal = this._layerSize.width + this._layerSize.height;
          ret = -(maxVal - (x + y));
          break;

         case cc.TiledMap.Orientation.ORTHO:
          ret = -(this._layerSize.height - y);
          break;

         case cc.TiledMap.Orientation.HEX:
          cc.logID(7210);
          break;

         default:
          cc.logID(7211);
        } else ret = this._vertexZvalue;
        return ret;
      }
    });
  }), {} ],
  278: [ (function(require, module, exports) {
    require("../shape-nodes/CCDrawNode");
    _ccsg.TMXObject = cc.Class({
      properties: {
        sgNode: null,
        offset: cc.p(0, 0),
        gid: 0,
        name: "",
        type: null,
        id: 0,
        objectVisible: true,
        objectSize: cc.size(0, 0),
        objectRotation: 0,
        _properties: null,
        _groupSize: cc.size(0, 0)
      },
      initWithInfo: function(objInfo, mapInfo, groupSize, color) {
        this.setProperties(objInfo);
        this.setObjectName(objInfo.name);
        this.id = objInfo.id;
        this.gid = objInfo.gid;
        this.type = objInfo.type;
        this.offset = cc.p(objInfo.x, objInfo.y);
        this.objectSize = cc.size(objInfo.width, objInfo.height);
        this.objectVisible = objInfo.visible;
        this.objectRotation = objInfo.rotation;
        this._groupSize = groupSize;
        this.type === cc.TiledMap.TMXObjectType.IMAGE ? this.sgNode = new _ccsg.TMXObjectImage(this, mapInfo) : this.sgNode = new _ccsg.TMXObjectShape(this, mapInfo, color);
      },
      getObjectName: function() {
        return this.name;
      },
      getProperty: function(propName) {
        return this._properties[propName];
      },
      getProperties: function() {
        return this._properties;
      },
      setObjectName: function(name) {
        this.name = name;
      },
      setProperties: function(props) {
        this._properties = props;
      }
    });
    _ccsg.TMXObjectImage = _ccsg.Sprite.extend({
      _container: null,
      ctor: function(container, mapInfo) {
        _ccsg.Sprite.prototype.ctor.call(this);
        this._container = container;
        this.initWithMapInfo(mapInfo);
      },
      initWithMapInfo: function(mapInfo) {
        if (!this._container.gid) return false;
        var useTileset;
        var tilesets = mapInfo.getTilesets();
        for (var i = tilesets.length - 1; i >= 0; i--) {
          var tileset = tilesets[i];
          if ((this._container.gid & cc.TiledMap.TileFlag.FLIPPED_MASK) >>> 0 >= tileset.firstGid) {
            useTileset = tileset;
            break;
          }
        }
        if (!useTileset) return false;
        this.setVisible(this._container.objectVisible);
        var texture = cc.textureCache.addImage(cc.path._normalize(tileset.sourceImage));
        this._initWithTileset(texture, useTileset);
        this._initPosWithMapInfo(mapInfo);
        this.setRotation(this._container.objectRotation);
        (this._container.gid & cc.TiledMap.TileFlag.HORIZONTAL) >>> 0 && this.setFlippedX(true);
        (this._container.gid & cc.TiledMap.TileFlag.VERTICAL) >>> 0 && this.setFlippedY(true);
        return true;
      },
      _initWithTileset: function(texture, tileset) {
        if (!texture.isLoaded()) {
          texture.once("load", (function() {
            this._initWithTileset(texture, tileset);
          }), this);
          return;
        }
        tileset.imageSize.width = texture.width;
        tileset.imageSize.height = texture.height;
        var rect = tileset.rectForGID(this._container.gid);
        this.initWithTexture(texture, rect);
        this.setScaleX(this._container.objectSize.width / rect.size.width);
        this.setScaleY(this._container.objectSize.height / rect.size.height);
      },
      _initPosWithMapInfo: function(mapInfo) {
        var mapOri = mapInfo.getOrientation();
        switch (mapOri) {
         case cc.TiledMap.Orientation.ORTHO:
         case cc.TiledMap.Orientation.HEX:
          this.setAnchorPoint(cc.p(0, 0));
          this.setPosition(this._container.offset.x, this._container._groupSize.height - this._container.offset.y);
          break;

         case cc.TiledMap.Orientation.ISO:
          this.setAnchorPoint(cc.p(.5, 0));
          var posIdx = cc.p(this._container.offset.x / mapInfo._tileSize.height, this._container.offset.y / mapInfo._tileSize.height);
          var pos = cc.p(mapInfo._tileSize.width / 2 * (mapInfo._mapSize.width + posIdx.x - posIdx.y), mapInfo._tileSize.height / 2 * (2 * mapInfo._mapSize.height - posIdx.x - posIdx.y));
          this.setPosition(pos);
        }
      }
    });
    _ccsg.TMXObjectShape = cc.DrawNode.extend({
      _container: null,
      _color: cc.Color.WHITE,
      _mapOrientation: 0,
      _mapInfo: null,
      ctor: function(container, mapInfo, color) {
        cc.DrawNode.prototype.ctor.call(this);
        this.setLineWidth(1);
        this._container = container;
        this._color = color;
        this._mapInfo = mapInfo;
        this._mapOrientation = mapInfo.getOrientation();
        this._initShape();
      },
      _initShape: function() {
        var originPos;
        if (cc.TiledMap.Orientation.ISO !== this._mapOrientation) {
          var startPos = cc.p(0, this._container._groupSize.height);
          originPos = cc.p(startPos.x + this._container.offset.x, startPos.y - this._container.offset.y);
        } else originPos = this._getPosByOffset(cc.p(0, 0));
        this.setPosition(originPos);
        this.setRotation(this._container.objectRotation);
        switch (this._container.type) {
         case cc.TiledMap.TMXObjectType.RECT:
          this._drawRect();
          break;

         case cc.TiledMap.TMXObjectType.ELLIPSE:
          this._drawEllipse();
          break;

         case cc.TiledMap.TMXObjectType.POLYGON:
          this._drawPoly(originPos, true);
          break;

         case cc.TiledMap.TMXObjectType.POLYLINE:
          this._drawPoly(originPos, false);
        }
        this.setVisible(this._container.objectVisible);
      },
      _getPosByOffset: function(offset) {
        var mapSize = this._mapInfo.getMapSize();
        var tileSize = this._mapInfo.getTileSize();
        var posIdx = cc.p((this._container.offset.x + offset.x) / tileSize.width * 2, (this._container.offset.y + offset.y) / tileSize.height);
        return cc.p(tileSize.width / 2 * (mapSize.width + posIdx.x - posIdx.y), tileSize.height / 2 * (2 * mapSize.height - posIdx.x - posIdx.y));
      },
      _drawRect: function() {
        if (cc.TiledMap.Orientation.ISO !== this._mapOrientation) {
          var objSize = this._container.objectSize;
          if (objSize.equals(cc.Size.ZERO)) {
            objSize = cc.size(20, 20);
            this.setAnchorPoint(cc.p(.5, .5));
          } else this.setAnchorPoint(cc.p(0, 1));
          var bl = cc.p(0, 0);
          var tr = cc.p(objSize.width, objSize.height);
          this.drawRect(bl, tr, null, this.getLineWidth(), this._color);
          this.setContentSize(objSize);
        } else {
          if (this._container.objectSize.equals(cc.Size.ZERO)) return;
          var pos1 = this._getPosByOffset(cc.p(0, 0));
          var pos2 = this._getPosByOffset(cc.p(this._container.objectSize.width, 0));
          var pos3 = this._getPosByOffset(cc.p(this._container.objectSize.width, this._container.objectSize.height));
          var pos4 = this._getPosByOffset(cc.p(0, this._container.objectSize.height));
          var width = pos2.x - pos4.x, height = pos1.y - pos3.y;
          this.setContentSize(cc.size(width, height));
          this.setAnchorPoint(cc.p((pos1.x - pos4.x) / width, 1));
          var origin = cc.p(pos4.x, pos3.y);
          pos1.subSelf(origin);
          pos2.subSelf(origin);
          pos3.subSelf(origin);
          pos4.subSelf(origin);
          if (this._container.objectSize.width > 0) {
            this.drawSegment(pos1, pos2, this.getLineWidth(), this._color);
            this.drawSegment(pos3, pos4, this.getLineWidth(), this._color);
          }
          if (this._container.objectSize.height > 0) {
            this.drawSegment(pos1, pos4, this.getLineWidth(), this._color);
            this.drawSegment(pos3, pos2, this.getLineWidth(), this._color);
          }
        }
      },
      _drawEllipse: function() {
        var scaleX = 1, scaleY = 1, radius = 0;
        var center = cc.p(0, 0);
        var ellipseNode = null;
        if (cc.TiledMap.Orientation.ISO !== this._mapOrientation) {
          var objSize = this._container.objectSize;
          if (objSize.equals(cc.Size.ZERO)) {
            objSize = cc.size(20, 20);
            this.setAnchorPoint(cc.p(.5, .5));
          } else this.setAnchorPoint(cc.p(0, 1));
          center = cc.p(objSize.width / 2, objSize.height / 2);
          if (objSize.width > objSize.height) {
            scaleX = objSize.width / objSize.height;
            radius = objSize.height / 2;
          } else {
            scaleY = objSize.height / objSize.width;
            radius = objSize.width / 2;
          }
          ellipseNode = this;
          this.setContentSize(objSize);
        } else {
          if (this._container.objectSize.equals(cc.Size.ZERO)) return;
          var pos1 = this._getPosByOffset(cc.p(0, 0));
          var pos2 = this._getPosByOffset(cc.p(this._container.objectSize.width, 0));
          var pos3 = this._getPosByOffset(cc.p(this._container.objectSize.width, this._container.objectSize.height));
          var pos4 = this._getPosByOffset(cc.p(0, this._container.objectSize.height));
          var width = pos2.x - pos4.x, height = pos1.y - pos3.y;
          this.setContentSize(cc.size(width, height));
          this.setAnchorPoint(cc.p((pos1.x - pos4.x) / width, 1));
          var origin = cc.p(pos4.x, pos3.y);
          pos1.subSelf(origin);
          pos2.subSelf(origin);
          pos3.subSelf(origin);
          pos4.subSelf(origin);
          if (this._container.objectSize.width > 0) {
            this.drawSegment(pos1, pos2, this.getLineWidth(), this._color);
            this.drawSegment(pos3, pos4, this.getLineWidth(), this._color);
          }
          if (this._container.objectSize.height > 0) {
            this.drawSegment(pos1, pos4, this.getLineWidth(), this._color);
            this.drawSegment(pos3, pos2, this.getLineWidth(), this._color);
          }
          center = this._getPosByOffset(cc.p(this._container.objectSize.width / 2, this._container.objectSize.height / 2));
          center.subSelf(origin);
          ellipseNode = new cc.DrawNode();
          ellipseNode.setLineWidth(this.getLineWidth());
          ellipseNode.setContentSize(cc.size(width, height));
          ellipseNode.setAnchorPoint(cc.p(.5, .5));
          ellipseNode.setPosition(center);
          this.addChild(ellipseNode);
          if (this._container.objectSize.width > this._container.objectSize.height) {
            scaleX = this._container.objectSize.width / this._container.objectSize.height;
            radius = this._container.objectSize.height / 2;
          } else {
            scaleY = this._container.objectSize.height / this._container.objectSize.width;
            radius = this._container.objectSize.width / 2;
          }
          var tileSize = this._mapInfo.getTileSize();
          var rotateDegree = Math.atan(tileSize.width / tileSize.height);
          radius /= Math.sin(rotateDegree);
          ellipseNode.setRotationX(cc.radiansToDegrees(rotateDegree));
          ellipseNode.setRotationY(90 - cc.radiansToDegrees(rotateDegree));
        }
        ellipseNode.drawCircle(center, radius, 0, 50, false, this.getLineWidth(), this._color);
        ellipseNode.setScaleX(scaleX);
        ellipseNode.setScaleY(scaleY);
      },
      _drawPoly: function(originPos, isPolygon) {
        var pointsData;
        var objectInfo = this._container.getProperties();
        pointsData = isPolygon ? objectInfo.points : objectInfo.polylinePoints;
        var points = [];
        var minX = 0, minY = 0, maxX = 0, maxY = 0;
        for (var i = 0, n = pointsData.length; i < n; i++) {
          var pointData = pointsData[i];
          points.push(cc.p(pointData.x, pointData.y));
          minX = Math.min(minX, pointData.x);
          minY = Math.min(minY, pointData.y);
          maxX = Math.max(maxX, pointData.x);
          maxY = Math.max(maxY, pointData.y);
        }
        var width = 0, height = 0;
        if (cc.TiledMap.Orientation.ISO !== this._mapOrientation) {
          width = maxX - minX, height = maxY - minY;
          this.setAnchorPoint(cc.p(-minX / width, maxY / height));
          for (var j = 0; j < points.length; j++) points[j] = cc.p(points[j].x - minX, -points[j].y + maxY);
        } else {
          var bl = this._getPosByOffset(cc.p(minX, maxY));
          var tr = this._getPosByOffset(cc.p(maxX, minY));
          var origin = this._getPosByOffset(cc.p(0, 0));
          width = tr.x - bl.x, height = tr.y - bl.y;
          this.setAnchorPoint(cc.p((origin.x - bl.x) / width, (origin.y - bl.y) / height));
          for (var idx = 0; idx < points.length; idx++) {
            var tempPoint = this._getPosByOffset(points[idx]);
            points[idx] = cc.p(tempPoint.x - bl.x, tempPoint.y - bl.y);
          }
        }
        this.setContentSize(cc.size(width, height));
        this.drawPoly(points, null, this.getLineWidth(), this._color, !isPolygon);
      }
    });
  }), {
    "../shape-nodes/CCDrawNode": 274
  } ],
  279: [ (function(require, module, exports) {
    _ccsg.TMXObjectGroup = _ccsg.Node.extend({
      properties: null,
      groupName: "",
      _positionOffset: null,
      _mapInfo: null,
      _objects: [],
      ctor: function(groupInfo, mapInfo) {
        _ccsg.Node.prototype.ctor.call(this);
        this._initGroup(groupInfo, mapInfo);
      },
      _initGroup: function(groupInfo, mapInfo) {
        this.groupName = groupInfo.name;
        this._positionOffset = groupInfo.offset;
        this._mapInfo = mapInfo;
        this.properties = groupInfo.getProperties();
        var mapSize = mapInfo._mapSize;
        var tileSize = mapInfo._tileSize;
        if (mapInfo.orientation === cc.TiledMap.Orientation.HEX) {
          var width = 0, height = 0;
          if (mapInfo.getStaggerAxis() === cc.TiledMap.StaggerAxis.STAGGERAXIS_X) {
            height = tileSize.height * (mapSize.height + .5);
            width = (tileSize.width + mapInfo.getHexSideLength()) * Math.floor(mapSize.width / 2) + tileSize.width * (mapSize.width % 2);
          } else {
            width = tileSize.width * (mapSize.width + .5);
            height = (tileSize.height + mapInfo.getHexSideLength()) * Math.floor(mapSize.height / 2) + tileSize.height * (mapSize.height % 2);
          }
          this.setContentSize(width, height);
        } else this.setContentSize(mapSize.width * tileSize.width, mapSize.height * tileSize.height);
        this.setAnchorPoint(cc.p(0, 0));
        this.setPosition(this._positionOffset.x, -this._positionOffset.y);
        this.setVisible(groupInfo.visible);
        var objects = [];
        groupInfo._objects instanceof Array && (objects = groupInfo._objects);
        this._objects = [];
        for (var i = 0, n = objects.length; i < n; i++) {
          var objInfo = objects[i];
          var object = new _ccsg.TMXObject();
          object.initWithInfo(objInfo, mapInfo, this.getContentSize(), groupInfo._color);
          this._objects.push(object);
          if (object.sgNode) {
            object.sgNode.setOpacity(groupInfo._opacity);
            this.addChild(object.sgNode, i, i);
          }
        }
      },
      getPositionOffset: function() {
        return cc.p(this._positionOffset);
      },
      setPositionOffset: function(offset) {
        this._positionOffset.x = offset.x;
        this._positionOffset.y = offset.y;
      },
      getProperties: function() {
        return this.properties;
      },
      setProperties: function(Var) {
        this.properties = Var;
      },
      getGroupName: function() {
        return this.groupName;
      },
      setGroupName: function(groupName) {
        this.groupName = groupName;
      },
      propertyNamed: function(propertyName) {
        return this.properties[propertyName];
      },
      objectNamed: function(objectName) {
        return this.getObject(objectName);
      },
      getObject: function(objectName) {
        for (var i = 0, len = this._objects.length; i < len; i++) {
          var obj = this._objects[i];
          if (obj && obj.getObjectName() === objectName) return obj;
        }
        return null;
      },
      getObjects: function() {
        return this._objects;
      }
    });
  }), {} ],
  280: [ (function(require, module, exports) {
    require("./CCSGTMXObject");
    require("./CCTMXXMLParser");
    _ccsg.TMXTiledMap = _ccsg.Node.extend({
      properties: null,
      mapOrientation: null,
      _mapSize: null,
      _tileSize: null,
      _tileProperties: null,
      _className: "TMXTiledMap",
      ctor: function(tmxFile, resourcePath) {
        _ccsg.Node.prototype.ctor.call(this);
        this._mapSize = cc.size(0, 0);
        this._tileSize = cc.size(0, 0);
        void 0 !== resourcePath ? this.initWithXML(tmxFile, resourcePath) : void 0 !== tmxFile && this.initWithTMXFile(tmxFile);
      },
      getMapSize: function() {
        return cc.size(this._mapSize.width, this._mapSize.height);
      },
      setMapSize: function(Var) {
        this._mapSize.width = Var.width;
        this._mapSize.height = Var.height;
      },
      _getMapWidth: function() {
        return this._mapSize.width;
      },
      _setMapWidth: function(width) {
        this._mapSize.width = width;
      },
      _getMapHeight: function() {
        return this._mapSize.height;
      },
      _setMapHeight: function(height) {
        this._mapSize.height = height;
      },
      getTileSize: function() {
        return cc.size(this._tileSize.width, this._tileSize.height);
      },
      setTileSize: function(Var) {
        this._tileSize.width = Var.width;
        this._tileSize.height = Var.height;
      },
      _getTileWidth: function() {
        return this._tileSize.width;
      },
      _setTileWidth: function(width) {
        this._tileSize.width = width;
      },
      _getTileHeight: function() {
        return this._tileSize.height;
      },
      _setTileHeight: function(height) {
        this._tileSize.height = height;
      },
      getMapOrientation: function() {
        return this.mapOrientation;
      },
      setMapOrientation: function(Var) {
        this.mapOrientation = Var;
      },
      getObjectGroups: function() {
        var retArr = [], locChildren = this._children;
        for (var i = 0, len = locChildren.length; i < len; i++) {
          var group = locChildren[i];
          group && group instanceof _ccsg.TMXObjectGroup && retArr.push(group);
        }
        return retArr;
      },
      getProperties: function() {
        return this.properties;
      },
      setProperties: function(Var) {
        this.properties = Var;
      },
      initWithTMXFile: function(tmxFile) {
        if (!tmxFile || 0 === tmxFile.length) return false;
        this.width = 0;
        this.height = 0;
        var mapInfo = new cc.TMXMapInfo(tmxFile);
        if (!mapInfo) return false;
        var locTilesets = mapInfo.getTilesets();
        locTilesets && 0 !== locTilesets.length || cc.logID(7212);
        this._buildWithMapInfo(mapInfo);
        return true;
      },
      initWithXML: function(tmxString, resourcePath) {
        this.width = 0;
        this.height = 0;
        var mapInfo = new cc.TMXMapInfo(tmxString, resourcePath);
        var locTilesets = mapInfo.getTilesets();
        locTilesets && 0 !== locTilesets.length || cc.logID(7213);
        this._buildWithMapInfo(mapInfo);
        return true;
      },
      _buildWithMapInfo: function(mapInfo) {
        this._mapSize = mapInfo.getMapSize();
        this._tileSize = mapInfo.getTileSize();
        this.mapOrientation = mapInfo.orientation;
        this.properties = mapInfo.properties;
        this._tileProperties = mapInfo.getTileProperties();
        var oldChildren = this._children;
        var childCount = oldChildren.length;
        for (var j = childCount - 1; j >= 0; j--) {
          var childNode = oldChildren[j];
          childNode && (childNode instanceof _ccsg.TMXLayer || childNode instanceof _ccsg.TMXObjectGroup) && this.removeChild(childNode);
        }
        var idx = 0;
        var children = mapInfo.getAllChildren();
        if (children && children.length > 0) for (var i = 0, len = children.length; i < len; i++) {
          var childInfo = children[i];
          var child;
          if (childInfo instanceof cc.TMXLayerInfo && childInfo.visible) {
            child = this._parseLayer(childInfo, mapInfo);
            this.addChild(child, idx, idx);
            this.width = Math.max(this.width, child.width);
            this.height = Math.max(this.height, child.height);
            idx++;
          }
          if (childInfo instanceof cc.TMXObjectGroupInfo) {
            child = new _ccsg.TMXObjectGroup(childInfo, mapInfo);
            this.addChild(child, idx, idx);
            idx++;
          }
        }
      },
      allLayers: function() {
        var retArr = [], locChildren = this._children;
        for (var i = 0, len = locChildren.length; i < len; i++) {
          var layer = locChildren[i];
          layer && layer instanceof _ccsg.TMXLayer && retArr.push(layer);
        }
        return retArr;
      },
      getLayer: function(layerName) {
        if (!layerName || 0 === layerName.length) throw new Error("_ccsg.TMXTiledMap.getLayer(): layerName should be non-null or non-empty string.");
        var locChildren = this._children;
        for (var i = 0; i < locChildren.length; i++) {
          var layer = locChildren[i];
          if (layer && layer instanceof _ccsg.TMXLayer && layer.layerName === layerName) return layer;
        }
        return null;
      },
      getObjectGroup: function(groupName) {
        if (!groupName || 0 === groupName.length) throw new Error("_ccsg.TMXTiledMap.getObjectGroup(): groupName should be non-null or non-empty string.");
        var locChildren = this._children;
        for (var i = 0; i < locChildren.length; i++) {
          var group = locChildren[i];
          if (group && group instanceof _ccsg.TMXObjectGroup && group.groupName === groupName) return group;
        }
        return null;
      },
      getProperty: function(propertyName) {
        return this.properties[propertyName.toString()];
      },
      propertiesForGID: function(GID) {
        cc.logID(7214);
        return this.getPropertiesForGID[GID];
      },
      getPropertiesForGID: function(GID) {
        return this._tileProperties[GID];
      },
      _parseLayer: function(layerInfo, mapInfo) {
        var tileset = this._tilesetForLayer(layerInfo, mapInfo);
        var layer = new _ccsg.TMXLayer(tileset, layerInfo, mapInfo);
        layerInfo.ownTiles = false;
        return layer;
      },
      _tilesetForLayer: function(layerInfo, mapInfo) {
        var size = layerInfo._layerSize;
        var tilesets = mapInfo.getTilesets();
        if (tilesets) for (var i = tilesets.length - 1; i >= 0; i--) {
          var tileset = tilesets[i];
          if (tileset) for (var y = 0; y < size.height; y++) for (var x = 0; x < size.width; x++) {
            var pos = x + size.width * y;
            var gid = layerInfo._tiles[pos];
            if (0 !== gid && (gid & cc.TiledMap.TileFlag.FLIPPED_MASK) >>> 0 >= tileset.firstGid) return tileset;
          }
        }
        cc.logID(7215, layerInfo.name);
        return null;
      }
    });
    var _p = _ccsg.TMXTiledMap.prototype;
    _p.mapWidth;
    cc.defineGetterSetter(_p, "mapWidth", _p._getMapWidth, _p._setMapWidth);
    _p.mapHeight;
    cc.defineGetterSetter(_p, "mapHeight", _p._getMapHeight, _p._setMapHeight);
    _p.tileWidth;
    cc.defineGetterSetter(_p, "tileWidth", _p._getTileWidth, _p._setTileWidth);
    _p.tileHeight;
    cc.defineGetterSetter(_p, "tileHeight", _p._getTileHeight, _p._setTileHeight);
  }), {
    "./CCSGTMXObject": 278,
    "./CCTMXXMLParser": 283
  } ],
  281: [ (function(require, module, exports) {
    var Orientation = null;
    var TileFlag = null;
    var FLIPPED_MASK = null;
    var StaggerAxis = null;
    var StaggerIndex = null;
    _ccsg.TMXLayer.CanvasRenderCmd = function(renderable) {
      this._rootCtor(renderable);
      this._needDraw = true;
      if (!Orientation) {
        Orientation = cc.TiledMap.Orientation;
        TileFlag = cc.TiledMap.TileFlag;
        FLIPPED_MASK = TileFlag.FLIPPED_MASK;
        StaggerAxis = cc.TiledMap.StaggerAxis;
        StaggerIndex = cc.TiledMap.StaggerIndex;
      }
    };
    var proto = _ccsg.TMXLayer.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
    proto.constructor = _ccsg.TMXLayer.CanvasRenderCmd;
    proto.rendering = function(ctx, scaleX, scaleY) {
      var node = this._node, layerOrientation = node.layerOrientation, tiles = node.tiles, alpha = node._opacity / 255;
      if (!tiles || alpha <= 0 || !node.tileset) return;
      var maptw = node._mapTileSize.width, mapth = node._mapTileSize.height, tilew = node.tileset._tileSize.width / cc.director._contentScaleFactor, tileh = node.tileset._tileSize.height / cc.director._contentScaleFactor, extw = tilew - maptw, exth = tileh - mapth, winw = cc.winSize.width, winh = cc.winSize.height, rows = node._layerSize.height, cols = node._layerSize.width, grids = node._texGrids, spTiles = node._spriteTiles, wt = this._worldTransform, ox = node._position.x, oy = node._position.y, a = wt.a, b = wt.b, c = wt.c, d = wt.d, mapx = ox * a + oy * c + wt.tx, mapy = ox * b + oy * d + wt.ty;
      var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
      var startCol = 0, startRow = 0, maxCol = cols, maxRow = rows;
      if (cc.macro.ENABLE_TILEDMAP_CULLING && layerOrientation === Orientation.ORTHO) {
        startCol = Math.floor(-(mapx - extw * a) / (maptw * a));
        startRow = Math.floor((mapy - exth * d + mapth * rows * d - winh) / (mapth * d));
        maxCol = Math.ceil((winw - mapx + extw * a) / (maptw * a));
        maxRow = rows - Math.floor(-(mapy + exth * d) / (mapth * d));
        startCol < 0 && (startCol = 0);
        startRow < 0 && (startRow = 0);
        maxCol > cols && (maxCol = cols);
        maxRow > rows && (maxRow = rows);
      }
      var i, row, col, colOffset = startRow * cols, z, gid, grid, tex, cmd, top, left, bottom, right, dw = tilew, dh = tileh, w = tilew * a, h = tileh * d, gt, gl, gb, gr, flippedX = false, flippedY = false;
      z = colOffset + startCol;
      for (i in spTiles) if (i < z && spTiles[i]) {
        cmd = spTiles[i]._renderCmd;
        0 === spTiles[i]._localZOrder && !!cmd.rendering && spTiles[i]._visible && cmd.rendering(ctx, scaleX, scaleY);
      } else if (i >= z) break;
      wrapper.setTransform(wt, scaleX, scaleY);
      wrapper.setGlobalAlpha(alpha);
      var axis, tileOffset, odd_even, diffX1, diffY1;
      if (layerOrientation === Orientation.HEX) {
        var index = node._staggerIndex, hexSideLength = node._hexSideLength;
        axis = node._staggerAxis;
        tileOffset = node.tileset.tileOffset;
        odd_even = index === StaggerIndex.STAGGERINDEX_ODD ? 1 : -1;
        diffX1 = axis === StaggerAxis.STAGGERAXIS_X ? (maptw - hexSideLength) / 2 : 0;
        diffY1 = axis === StaggerAxis.STAGGERAXIS_Y ? (mapth - hexSideLength) / 2 : 0;
      }
      for (row = startRow; row < maxRow; ++row) {
        for (col = startCol; col < maxCol; ++col) {
          z = colOffset + col;
          if (spTiles[z]) {
            cmd = spTiles[z]._renderCmd;
            if (0 === spTiles[z]._localZOrder && !!cmd.rendering && spTiles[z]._visible) {
              cmd.rendering(ctx, scaleX, scaleY);
              wrapper.setTransform(wt, scaleX, scaleY);
              wrapper.setGlobalAlpha(alpha);
            }
            continue;
          }
          gid = node.tiles[z];
          grid = grids[(gid & FLIPPED_MASK) >>> 0];
          if (!grid) continue;
          tex = node._textures[grid.texId];
          if (!tex || !tex._image) continue;
          switch (layerOrientation) {
           case Orientation.ORTHO:
            left = col * maptw;
            bottom = -(rows - row - 1) * mapth;
            break;

           case Orientation.ISO:
            left = maptw / 2 * (cols + col - row - 1);
            bottom = -mapth / 2 * (2 * rows - col - row - 2);
            break;

           case Orientation.HEX:
            var diffX2 = axis === StaggerAxis.STAGGERAXIS_Y && row % 2 === 1 ? maptw / 2 * odd_even : 0;
            left = col * (maptw - diffX1) + diffX2 + tileOffset.x;
            var diffY2 = axis === StaggerAxis.STAGGERAXIS_X && col % 2 === 1 ? mapth / 2 * -odd_even : 0;
            bottom = -(rows - row - 1) * (mapth - diffY1) - diffY2 + tileOffset.y;
          }
          right = left + tilew;
          top = bottom - tileh;
          if (layerOrientation === Orientation.ISO) {
            gb = bottom * d - mapy;
            if (gb < -winh - h) {
              col += Math.floor(2 * (-winh - gb) / h) - 1;
              continue;
            }
            gr = mapx + right * a;
            if (gr < -w) {
              col += Math.floor(2 * -gr / w) - 1;
              continue;
            }
            gl = mapx + left * a;
            gt = top * d - mapy;
            if (gl > winw || gt > 0) {
              col = maxCol;
              continue;
            }
          }
          if (gid > TileFlag.DIAGONAL) {
            flippedX = (gid & TileFlag.HORIZONTAL) >>> 0;
            flippedY = (gid & TileFlag.VERTICAL) >>> 0;
          }
          if (flippedX) {
            left = -right;
            context.scale(-1, 1);
          }
          if (flippedY) {
            top = -bottom;
            context.scale(1, -1);
          }
          context.drawImage(tex._image, grid.x, grid.y, grid.width, grid.height, left, top, dw, dh);
          flippedX && context.scale(-1, 1);
          flippedY && context.scale(1, -1);
          cc.g_NumberOfDraws++;
        }
        colOffset += cols;
      }
      for (i in spTiles) if (i > z && spTiles[i]) {
        cmd = spTiles[i]._renderCmd;
        0 === spTiles[i]._localZOrder && !!cmd.rendering && spTiles[i]._visible && cmd.rendering(ctx, scaleX, scaleY);
      }
    };
  }), {} ],
  282: [ (function(require, module, exports) {
    var Orientation = null;
    var TileFlag = null;
    var FLIPPED_MASK = null;
    var StaggerAxis = null;
    var StaggerIndex = null;
    _ccsg.TMXLayer.WebGLRenderCmd = function(renderableObject) {
      this._rootCtor(renderableObject);
      this._needDraw = true;
      this._vertices = [ {
        x: 0,
        y: 0
      }, {
        x: 0,
        y: 0
      }, {
        x: 0,
        y: 0
      }, {
        x: 0,
        y: 0
      } ];
      this._color = new Uint32Array(1);
      this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST);
      var radian = 90 * Math.PI / 180;
      this._sin90 = Math.sin(radian);
      this._cos90 = Math.cos(radian);
      radian *= 3;
      this._sin270 = Math.sin(radian);
      this._cos270 = Math.cos(radian);
      if (!Orientation) {
        Orientation = cc.TiledMap.Orientation;
        TileFlag = cc.TiledMap.TileFlag;
        FLIPPED_MASK = TileFlag.FLIPPED_MASK;
        StaggerAxis = cc.TiledMap.StaggerAxis;
        StaggerIndex = cc.TiledMap.StaggerIndex;
      }
      this._disableDepthTestCmd = new cc.CustomRenderCmd(this, _disableDepthTest);
    };
    function _disableDepthTest() {
      cc.renderer.setDepthTest(false);
    }
    var proto = _ccsg.TMXLayer.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype);
    proto.constructor = _ccsg.TMXLayer.WebGLRenderCmd;
    proto.uploadData = function(f32buffer, ui32buffer, vertexDataOffset) {
      var node = this._node, layerOrientation = node.layerOrientation, tiles = node.tiles, alpha = node._opacity / 255;
      cc.renderer.setDepthTest(node.layerOrientation === Orientation.ORTHO);
      if (!tiles || alpha <= 0 || !node.tileset) return 0;
      var maptw = node._mapTileSize.width, mapth = node._mapTileSize.height, tilew = node.tileset._tileSize.width / cc.director._contentScaleFactor, tileh = node.tileset._tileSize.height / cc.director._contentScaleFactor, extw = tilew - maptw, exth = tileh - mapth, winw = cc.winSize.width, winh = cc.winSize.height, rows = node._layerSize.height, cols = node._layerSize.width, grids = node._texGrids, spTiles = node._spriteTiles, wt = this._worldTransform, a = wt.a, b = wt.b, c = wt.c, d = wt.d, tx = wt.tx, ty = wt.ty, ox = node._position.x, oy = node._position.y, mapx = ox * a + oy * c + tx, mapy = ox * b + oy * d + ty, w = tilew * a, h = tileh * d;
      var opacity = node._opacity, cr = this._displayedColor.r, cg = this._displayedColor.g, cb = this._displayedColor.b;
      if (node._opacityModifyRGB) {
        var ca = opacity / 255;
        cr *= ca;
        cg *= ca;
        cb *= ca;
      }
      this._color[0] = opacity << 24 | cb << 16 | cg << 8 | cr;
      var startCol = 0, startRow = 0, maxCol = cols, maxRow = rows;
      var cullingA = a, cullingD = d, cullingMapx = mapx, cullingMapy = mapy, cullingW = w, cullingH = h;
      var enabledCulling = cc.macro.ENABLE_TILEDMAP_CULLING;
      if (enabledCulling) {
        if (this._cameraFlag > 0) {
          var tmpt = cc.affineTransformConcat(wt, cc.Camera.main.viewMatrix);
          cullingA = tmpt.a;
          cullingD = tmpt.d;
          cullingMapx = ox * cullingA + oy * tmpt.c + tmpt.tx;
          cullingMapy = ox * tmpt.b + oy * cullingD + tmpt.ty;
          cullingW = tilew * cullingA;
          cullingH = tileh * cullingD;
        }
        if (layerOrientation === Orientation.ORTHO) {
          startCol = Math.floor(-(cullingMapx - extw * cullingA) / (maptw * cullingA));
          startRow = Math.floor((cullingMapy - exth * cullingD + mapth * rows * cullingD - winh) / (mapth * cullingD));
          maxCol = Math.ceil((winw - cullingMapx + extw * cullingA) / (maptw * cullingA));
          maxRow = rows - Math.floor(-(cullingMapy + exth * cullingD) / (mapth * cullingD));
          startCol < 0 && (startCol = 0);
          startRow < 0 && (startRow = 0);
          maxCol > cols && (maxCol = cols);
          maxRow > rows && (maxRow = rows);
        }
      }
      var row, col, offset = vertexDataOffset, colOffset = startRow * cols, z, gid, grid, i, top, left, bottom, right, gt, gl, gb, gr, wa = a, wb = b, wc = c, wd = d, wtx = tx, wty = ty, flagged = false, flippedX = false, flippedY = false, vertices = this._vertices, axis, tileOffset, diffX1, diffY1, odd_even;
      if (layerOrientation === Orientation.HEX) {
        var index = node._staggerIndex, hexSideLength = node._hexSideLength;
        axis = node._staggerAxis;
        tileOffset = node.tileset.tileOffset;
        odd_even = index === StaggerIndex.STAGGERINDEX_ODD ? 1 : -1;
        diffX1 = axis === StaggerAxis.STAGGERAXIS_X ? (maptw - hexSideLength) / 2 : 0;
        diffY1 = axis === StaggerAxis.STAGGERAXIS_Y ? (mapth - hexSideLength) / 2 : 0;
      }
      for (row = startRow; row < maxRow; ++row) {
        for (col = startCol; col < maxCol; ++col) {
          if (offset + 24 > f32buffer.length) {
            cc.renderer._increaseBatchingSize((offset - vertexDataOffset) / 6, cc.renderer.VertexType.QUAD);
            cc.renderer._batchRendering();
            vertexDataOffset = 0;
            offset = 0;
          }
          z = colOffset + col;
          if (spTiles[z]) {
            spTiles[z]._vertexZ = node._vertexZ + cc.renderer.assignedZStep * z / tiles.length;
            continue;
          }
          gid = node.tiles[z];
          grid = grids[(gid & FLIPPED_MASK) >>> 0];
          if (!grid) continue;
          switch (layerOrientation) {
           case Orientation.ORTHO:
            left = col * maptw;
            bottom = (rows - row - 1) * mapth;
            z = node._vertexZ + cc.renderer.assignedZStep * z / tiles.length;
            break;

           case Orientation.ISO:
            left = maptw / 2 * (cols + col - row - 1);
            bottom = mapth / 2 * (2 * rows - col - row - 2);
            z = node._vertexZ + cc.renderer.assignedZStep * (node.height - bottom) / node.height;
            break;

           case Orientation.HEX:
            var diffX2 = axis === StaggerAxis.STAGGERAXIS_Y && row % 2 === 1 ? maptw / 2 * odd_even : 0;
            left = col * (maptw - diffX1) + diffX2 + tileOffset.x;
            var diffY2 = axis === StaggerAxis.STAGGERAXIS_X && col % 2 === 1 ? mapth / 2 * -odd_even : 0;
            bottom = (rows - row - 1) * (mapth - diffY1) + diffY2 - tileOffset.y;
            z = node._vertexZ + cc.renderer.assignedZStep * (node.height - bottom) / node.height;
          }
          right = left + tilew;
          top = bottom + tileh;
          if (enabledCulling && layerOrientation === Orientation.ISO) {
            gb = cullingMapy + bottom * cullingD;
            if (gb > winh + cullingH) {
              col += Math.floor(2 * (gb - winh) / cullingH) - 1;
              continue;
            }
            gr = cullingMapx + right * cullingA;
            if (gr < -cullingW) {
              col += Math.floor(2 * -gr / cullingW) - 1;
              continue;
            }
            gl = cullingMapx + left * cullingA;
            gt = cullingMapy + top * cullingD;
            if (gl > winw || gt < 0) {
              col = maxCol;
              continue;
            }
          }
          if (gid > TileFlag.DIAGONAL) {
            flagged = true;
            flippedX = (gid & TileFlag.HORIZONTAL) >>> 0;
            flippedY = (gid & TileFlag.VERTICAL) >>> 0;
          }
          vertices[0].x = left * wa + top * wc + wtx;
          vertices[0].y = left * wb + top * wd + wty;
          vertices[1].x = left * wa + bottom * wc + wtx;
          vertices[1].y = left * wb + bottom * wd + wty;
          vertices[2].x = right * wa + top * wc + wtx;
          vertices[2].y = right * wb + top * wd + wty;
          vertices[3].x = right * wa + bottom * wc + wtx;
          vertices[3].y = right * wb + bottom * wd + wty;
          for (i = 0; i < 4; ++i) {
            f32buffer[offset] = vertices[i].x;
            f32buffer[offset + 1] = vertices[i].y;
            f32buffer[offset + 2] = z;
            ui32buffer[offset + 3] = this._color[0];
            switch (i) {
             case 0:
              f32buffer[offset + 4] = flippedX ? grid.r : grid.l;
              f32buffer[offset + 5] = flippedY ? grid.b : grid.t;
              break;

             case 1:
              f32buffer[offset + 4] = flippedX ? grid.r : grid.l;
              f32buffer[offset + 5] = flippedY ? grid.t : grid.b;
              break;

             case 2:
              f32buffer[offset + 4] = flippedX ? grid.l : grid.r;
              f32buffer[offset + 5] = flippedY ? grid.b : grid.t;
              break;

             case 3:
              f32buffer[offset + 4] = flippedX ? grid.l : grid.r;
              f32buffer[offset + 5] = flippedY ? grid.t : grid.b;
            }
            offset += 6;
          }
          if (flagged) {
            wa = a;
            wb = b;
            wc = c;
            wd = d;
            wtx = tx;
            wty = ty;
            flippedX = false;
            flippedY = false;
            flagged = false;
          }
        }
        colOffset += cols;
      }
      return (offset - vertexDataOffset) / 6;
    };
  }), {} ],
  283: [ (function(require, module, exports) {
    require("../compression/ZipUtils");
    var Zlib = require("../compression/zlib.min");
    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 = 4 * i;
        retArr[i] = uint8Arr[offset] + 256 * uint8Arr[offset + 1] + 65536 * uint8Arr[offset + 2] + uint8Arr[offset + 3] * (1 << 24);
      }
      return retArr;
    }
    cc.TMXLayerInfo = cc._Class.extend({
      ctor: function() {
        this.properties = {};
        this.name = "";
        this._layerSize = null;
        this._tiles = [];
        this.visible = true;
        this._opacity = 0;
        this.ownTiles = true;
        this._minGID = 1e5;
        this._maxGID = 0;
        this.offset = cc.p(0, 0);
      },
      getProperties: function() {
        return this.properties;
      },
      setProperties: function(value) {
        this.properties = value;
      }
    });
    cc.TMXObjectGroupInfo = cc._Class.extend({
      ctor: function() {
        this.properties = {};
        this.name = "";
        this._objects = [];
        this.visible = true;
        this._opacity = 0;
        this._color = new cc.Color(255, 255, 255, 255);
        this.offset = cc.p(0, 0);
        this._draworder = "topdown";
      },
      getProperties: function() {
        return this.properties;
      },
      setProperties: function(value) {
        this.properties = value;
      }
    });
    cc.TMXTilesetInfo = cc._Class.extend({
      ctor: function() {
        this.name = "";
        this.firstGid = 0;
        this.spacing = 0;
        this.margin = 0;
        this.sourceImage = "";
        this.imageSize = cc.size(0, 0);
        this.tileOffset = cc.p(0, 0);
        this._tileSize = cc.size(0, 0);
      },
      rectForGID: function(gid, result) {
        var rect = result || cc.rect(0, 0, 0, 0);
        rect.width = this._tileSize.width;
        rect.height = this._tileSize.height;
        gid &= cc.TiledMap.TileFlag.FLIPPED_MASK;
        gid -= parseInt(this.firstGid, 10);
        var max_x = parseInt((this.imageSize.width - 2 * this.margin + this.spacing) / (this._tileSize.width + this.spacing), 10);
        rect.x = parseInt(gid % max_x * (this._tileSize.width + this.spacing) + this.margin, 10);
        rect.y = parseInt(parseInt(gid / max_x, 10) * (this._tileSize.height + this.spacing) + this.margin, 10);
        return rect;
      }
    });
    function getPropertyList(node) {
      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]);
      }
      return res.length ? res : null;
    }
    cc.TMXMapInfo = cc.SAXParser.extend({
      properties: null,
      orientation: null,
      parentElement: null,
      parentGID: null,
      layerAttrs: 0,
      storingCharacters: false,
      tmxFileName: null,
      currentString: null,
      _objectGroups: null,
      _allChildren: null,
      _mapSize: null,
      _tileSize: null,
      _layers: null,
      _tilesets: null,
      _tileProperties: null,
      _resources: "",
      _staggerAxis: null,
      _staggerIndex: null,
      _hexSideLength: 0,
      ctor: function(tmxFile, resourcePath) {
        cc.SAXParser.prototype.ctor.apply(this);
        this._mapSize = cc.size(0, 0);
        this._tileSize = cc.size(0, 0);
        this._layers = [];
        this._tilesets = [];
        this._objectGroups = [];
        this._allChildren = [];
        this.properties = [];
        this._tileProperties = {};
        void 0 !== resourcePath ? this.initWithXML(tmxFile, resourcePath) : void 0 !== tmxFile && this.initWithTMXFile(tmxFile);
      },
      getOrientation: function() {
        return this.orientation;
      },
      setOrientation: function(value) {
        this.orientation = value;
      },
      getStaggerAxis: function() {
        return this._staggerAxis;
      },
      setStaggerAxis: function(value) {
        this._staggerAxis = value;
      },
      getStaggerIndex: function() {
        return this._staggerIndex;
      },
      setStaggerIndex: function(value) {
        this._staggerIndex = value;
      },
      getHexSideLength: function() {
        return this._hexSideLength;
      },
      setHexSideLength: function(value) {
        this._hexSideLength = value;
      },
      getMapSize: function() {
        return cc.size(this._mapSize.width, this._mapSize.height);
      },
      setMapSize: function(value) {
        this._mapSize.width = value.width;
        this._mapSize.height = value.height;
      },
      _getMapWidth: function() {
        return this._mapSize.width;
      },
      _setMapWidth: function(width) {
        this._mapSize.width = width;
      },
      _getMapHeight: function() {
        return this._mapSize.height;
      },
      _setMapHeight: function(height) {
        this._mapSize.height = height;
      },
      getTileSize: function() {
        return cc.size(this._tileSize.width, this._tileSize.height);
      },
      setTileSize: function(value) {
        this._tileSize.width = value.width;
        this._tileSize.height = value.height;
      },
      _getTileWidth: function() {
        return this._tileSize.width;
      },
      _setTileWidth: function(width) {
        this._tileSize.width = width;
      },
      _getTileHeight: function() {
        return this._tileSize.height;
      },
      _setTileHeight: function(height) {
        this._tileSize.height = height;
      },
      getLayers: function() {
        return this._layers;
      },
      setLayers: function(value) {
        this._allChildren.push(value);
        this._layers.push(value);
      },
      getTilesets: function() {
        return this._tilesets;
      },
      setTilesets: function(value) {
        this._tilesets.push(value);
      },
      getObjectGroups: function() {
        return this._objectGroups;
      },
      setObjectGroups: function(value) {
        this._allChildren.push(value);
        this._objectGroups.push(value);
      },
      getAllChildren: function() {
        return this._allChildren;
      },
      getParentElement: function() {
        return this.parentElement;
      },
      setParentElement: function(value) {
        this.parentElement = value;
      },
      getParentGID: function() {
        return this.parentGID;
      },
      setParentGID: function(value) {
        this.parentGID = value;
      },
      getLayerAttribs: function() {
        return this.layerAttrs;
      },
      setLayerAttribs: function(value) {
        this.layerAttrs = value;
      },
      getStoringCharacters: function() {
        return this.storingCharacters;
      },
      setStoringCharacters: function(value) {
        this.storingCharacters = value;
      },
      getProperties: function() {
        return this.properties;
      },
      setProperties: function(value) {
        this.properties = value;
      },
      initWithTMXFile: function(tmxFile) {
        this._internalInit(tmxFile, null);
        return this.parseXMLFile(tmxFile);
      },
      initWithXML: function(tmxString, resourcePath) {
        this._internalInit(null, resourcePath);
        return this.parseXMLString(tmxString);
      },
      parseXMLFile: function(tmxFile, isXmlString, tilesetFirstGid) {
        isXmlString = isXmlString || false;
        var xmlStr = isXmlString ? tmxFile : cc.loader.getRes(tmxFile);
        xmlStr || cc.errorID(7220, tmxFile);
        var mapXML = this._parseXML(xmlStr);
        var i, j;
        var map = mapXML.documentElement;
        var version = map.getAttribute("version");
        var orientationStr = map.getAttribute("orientation");
        var staggerAxisStr = map.getAttribute("staggeraxis");
        var staggerIndexStr = map.getAttribute("staggerindex");
        var hexSideLengthStr = map.getAttribute("hexsidelength");
        if ("map" === map.nodeName) {
          "1.0" !== version && null !== version && cc.logID(7216, version);
          "orthogonal" === orientationStr ? this.orientation = cc.TiledMap.Orientation.ORTHO : "isometric" === orientationStr ? this.orientation = cc.TiledMap.Orientation.ISO : "hexagonal" === orientationStr ? this.orientation = cc.TiledMap.Orientation.HEX : null !== orientationStr && cc.logID(7217, orientationStr);
          "x" === staggerAxisStr ? this.setStaggerAxis(cc.TiledMap.StaggerAxis.STAGGERAXIS_X) : "y" === staggerAxisStr && this.setStaggerAxis(cc.TiledMap.StaggerAxis.STAGGERAXIS_Y);
          "odd" === staggerIndexStr ? this.setStaggerIndex(cc.TiledMap.StaggerIndex.STAGGERINDEX_ODD) : "even" === staggerIndexStr && this.setStaggerIndex(cc.TiledMap.StaggerIndex.STAGGERINDEX_EVEN);
          hexSideLengthStr && this.setHexSideLength(parseFloat(hexSideLengthStr));
          var mapSize = cc.size(0, 0);
          mapSize.width = parseFloat(map.getAttribute("width"));
          mapSize.height = parseFloat(map.getAttribute("height"));
          this.setMapSize(mapSize);
          mapSize = cc.size(0, 0);
          mapSize.width = parseFloat(map.getAttribute("tilewidth"));
          mapSize.height = parseFloat(map.getAttribute("tileheight"));
          this.setTileSize(mapSize);
          var propertyArr = getPropertyList(map);
          if (propertyArr) {
            var aPropertyDict = {};
            for (i = 0; i < propertyArr.length; i++) aPropertyDict[propertyArr[i].getAttribute("name")] = propertyArr[i].getAttribute("value");
            this.properties = aPropertyDict;
          }
        }
        var tilesets = map.getElementsByTagName("tileset");
        if ("map" !== map.nodeName) {
          tilesets = [];
          tilesets.push(map);
        }
        for (i = 0; i < tilesets.length; i++) {
          var selTileset = tilesets[i];
          var tsxName = selTileset.getAttribute("source");
          if (tsxName) {
            var currentFirstGID = parseInt(selTileset.getAttribute("firstgid"));
            var tsxPath = isXmlString ? cc.path.join(this._resources, tsxName) : cc.path.changeBasename(tmxFile, tsxName);
            this.parseXMLFile(tsxPath, false, currentFirstGID);
          } else {
            var tileset = new cc.TMXTilesetInfo();
            tileset.name = selTileset.getAttribute("name") || "";
            tileset.firstGid = tilesetFirstGid || (parseInt(selTileset.getAttribute("firstgid")) || 0);
            tileset.spacing = parseInt(selTileset.getAttribute("spacing")) || 0;
            tileset.margin = parseInt(selTileset.getAttribute("margin")) || 0;
            var tilesetSize = cc.size(0, 0);
            tilesetSize.width = parseFloat(selTileset.getAttribute("tilewidth"));
            tilesetSize.height = parseFloat(selTileset.getAttribute("tileheight"));
            tileset._tileSize = tilesetSize;
            var image = selTileset.getElementsByTagName("image")[0];
            var imagename = image.getAttribute("source");
            var num = -1;
            this.tmxFileName && (num = this.tmxFileName.lastIndexOf("/"));
            if (-1 !== num) {
              var dir = this.tmxFileName.substr(0, num + 1);
              tileset.sourceImage = dir + imagename;
            } else tileset.sourceImage = this._resources + (this._resources ? "/" : "") + imagename;
            this.setTilesets(tileset);
            var offset = selTileset.getElementsByTagName("tileoffset")[0];
            if (offset) {
              var offsetX = parseFloat(offset.getAttribute("x"));
              var offsetY = parseFloat(offset.getAttribute("y"));
              tileset.tileOffset = cc.p(offsetX, offsetY);
            }
            var tiles = selTileset.getElementsByTagName("tile");
            if (tiles) for (var tIdx = 0; tIdx < tiles.length; tIdx++) {
              var t = tiles[tIdx];
              this.parentGID = parseInt(tileset.firstGid) + parseInt(t.getAttribute("id") || 0);
              var tp = getPropertyList(t);
              if (tp) {
                var dict = {};
                for (j = 0; j < tp.length; j++) {
                  var name = tp[j].getAttribute("name");
                  dict[name] = tp[j].getAttribute("value");
                }
                this._tileProperties[this.parentGID] = dict;
              }
            }
          }
        }
        var childNodes = map.childNodes;
        for (i = 0; i < childNodes.length; i++) {
          var childNode = childNodes[i];
          if (this._shouldIgnoreNode(childNode)) continue;
          if ("layer" === childNode.nodeName) {
            var layer = this._parseLayer(childNode);
            this.setLayers(layer);
          }
          if ("objectgroup" === childNode.nodeName) {
            var objectGroup = this._parseObjectGroup(childNode);
            this.setObjectGroups(objectGroup);
          }
        }
        return map;
      },
      _shouldIgnoreNode: function(node) {
        return 3 === node.nodeType || 8 === node.nodeType || 4 === node.nodeType;
      },
      _parseLayer: function(selLayer) {
        var data = selLayer.getElementsByTagName("data")[0];
        var layer = new cc.TMXLayerInfo();
        layer.name = selLayer.getAttribute("name");
        var layerSize = cc.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 = !("0" == visible);
        var opacity = selLayer.getAttribute("opacity") || 1;
        layer._opacity = opacity ? parseInt(255 * parseFloat(opacity)) : 255;
        layer.offset = cc.p(parseFloat(selLayer.getAttribute("x")) || 0, parseFloat(selLayer.getAttribute("y")) || 0);
        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 && "gzip" !== compression && "zlib" !== compression) {
          cc.logID(7218);
          return null;
        }
        var tiles;
        switch (compression) {
         case "gzip":
          tiles = cc.Codec.unzipBase64AsArray(nodeValue, 4);
          break;

         case "zlib":
          var inflator = new Zlib.Inflate(cc.Codec.Base64.decodeAsArray(nodeValue, 1));
          tiles = uint8ArrayToUint32Array(inflator.decompress());
          break;

         case null:
         case "":
          if ("base64" === encoding) tiles = cc.Codec.Base64.decodeAsArray(nodeValue, 4); else if ("csv" === encoding) {
            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:
          this.layerAttrs === cc.TMXLayerInfo.ATTRIB_NONE && cc.logID(7219);
        }
        tiles && (layer._tiles = new Uint32Array(tiles));
        var layerProps = getPropertyList(selLayer);
        if (layerProps) {
          var layerProp = {};
          for (var _j = 0; _j < layerProps.length; _j++) layerProp[layerProps[_j].getAttribute("name")] = layerProps[_j].getAttribute("value");
          layer.properties = layerProp;
        }
        return layer;
      },
      _parseObjectGroup: function(selGroup) {
        var objectGroup = new cc.TMXObjectGroupInfo();
        objectGroup.name = selGroup.getAttribute("name") || "";
        objectGroup.offset = cc.p(parseFloat(selGroup.getAttribute("offsetx")), parseFloat(selGroup.getAttribute("offsety")));
        var opacity = selGroup.getAttribute("opacity") || 1;
        objectGroup._opacity = opacity ? parseInt(255 * parseFloat(opacity)) : 255;
        var visible = selGroup.getAttribute("visible");
        visible && 0 === parseInt(visible) && (objectGroup.visible = false);
        var color = selGroup.getAttribute("color");
        color && (objectGroup._color = cc.hexToColor(color));
        var draworder = selGroup.getAttribute("draworder");
        draworder && (objectGroup._draworder = draworder);
        var groupProps = getPropertyList(selGroup);
        if (groupProps) {
          var parsedProps = {};
          for (var j = 0; j < groupProps.length; j++) parsedProps[groupProps[j].getAttribute("name")] = groupProps[j].getAttribute("value");
          objectGroup.setProperties(parsedProps);
        }
        var objects = selGroup.getElementsByTagName("object");
        var getContentScaleFactor = cc.director.getContentScaleFactor();
        if (objects) for (var _j2 = 0; _j2 < objects.length; _j2++) {
          var selObj = objects[_j2];
          var objectProp = {};
          objectProp["id"] = selObj.getAttribute("id") || 0;
          objectProp["name"] = selObj.getAttribute("name") || "";
          objectProp["width"] = parseFloat(selObj.getAttribute("width")) || 0;
          objectProp["height"] = parseFloat(selObj.getAttribute("height")) || 0;
          objectProp["x"] = (selObj.getAttribute("x") || 0) / getContentScaleFactor;
          objectProp["y"] = (selObj.getAttribute("y") || 0) / getContentScaleFactor;
          objectProp["rotation"] = parseFloat(selObj.getAttribute("rotation")) || 0;
          var docObjProps = getPropertyList(selObj);
          if (docObjProps) for (var k = 0; k < docObjProps.length; k++) objectProp[docObjProps[k].getAttribute("name")] = docObjProps[k].getAttribute("value");
          var visibleAttr = selObj.getAttribute("visible");
          objectProp["visible"] = !(visibleAttr && 0 === parseInt(visibleAttr));
          var gid = selObj.getAttribute("gid");
          if (gid) {
            objectProp["gid"] = parseInt(gid);
            objectProp["type"] = cc.TiledMap.TMXObjectType.IMAGE;
          }
          var ellipse = selObj.getElementsByTagName("ellipse");
          ellipse && ellipse.length > 0 && (objectProp["type"] = cc.TiledMap.TMXObjectType.ELLIPSE);
          var polygonProps = selObj.getElementsByTagName("polygon");
          if (polygonProps && polygonProps.length > 0) {
            objectProp["type"] = cc.TiledMap.TMXObjectType.POLYGON;
            var selPgPointStr = polygonProps[0].getAttribute("points");
            selPgPointStr && (objectProp["points"] = this._parsePointsString(selPgPointStr));
          }
          var polylineProps = selObj.getElementsByTagName("polyline");
          if (polylineProps && polylineProps.length > 0) {
            objectProp["type"] = cc.TiledMap.TMXObjectType.POLYLINE;
            var selPlPointStr = polylineProps[0].getAttribute("points");
            selPlPointStr && (objectProp["polylinePoints"] = this._parsePointsString(selPlPointStr));
          }
          objectProp["type"] || (objectProp["type"] = cc.TiledMap.TMXObjectType.RECT);
          objectGroup._objects.push(objectProp);
        }
        return objectGroup;
      },
      _parsePointsString: function(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;
      },
      parseXMLString: function(xmlString) {
        return this.parseXMLFile(xmlString, true);
      },
      getTileProperties: function() {
        return this._tileProperties;
      },
      setTileProperties: function(tileProperties) {
        this._tileProperties.push(tileProperties);
      },
      getCurrentString: function() {
        return this.currentString;
      },
      setCurrentString: function(currentString) {
        this.currentString = currentString;
      },
      getTMXFileName: function() {
        return this.tmxFileName;
      },
      setTMXFileName: function(fileName) {
        this.tmxFileName = fileName;
      },
      _internalInit: function(tmxFileName, resourcePath) {
        this._tilesets.length = 0;
        this._layers.length = 0;
        this.tmxFileName = tmxFileName;
        resourcePath && (this._resources = resourcePath);
        this._objectGroups.length = 0;
        this._allChildren.length = 0;
        this.properties.length = 0;
        this._tileProperties.length = 0;
        this.currentString = "";
        this.storingCharacters = false;
        this.layerAttrs = cc.TMXLayerInfo.ATTRIB_NONE;
        this.parentElement = cc.TiledMap.NONE;
      }
    });
    var _p = cc.TMXMapInfo.prototype;
    _p.mapWidth;
    cc.defineGetterSetter(_p, "mapWidth", _p._getMapWidth, _p._setMapWidth);
    _p.mapHeight;
    cc.defineGetterSetter(_p, "mapHeight", _p._getMapHeight, _p._setMapHeight);
    _p.tileWidth;
    cc.defineGetterSetter(_p, "tileWidth", _p._getTileWidth, _p._setTileWidth);
    _p.tileHeight;
    cc.defineGetterSetter(_p, "tileHeight", _p._getTileHeight, _p._setTileHeight);
    cc.TMXMapInfo.create = function(tmxFile, resourcePath) {
      return new cc.TMXMapInfo(tmxFile, resourcePath);
    };
    cc.TMXLayerInfo.ATTRIB_NONE = 1;
    cc.TMXLayerInfo.ATTRIB_BASE64 = 2;
    cc.TMXLayerInfo.ATTRIB_GZIP = 4;
    cc.TMXLayerInfo.ATTRIB_ZLIB = 8;
  }), {
    "../compression/ZipUtils": 28,
    "../compression/zlib.min": 31
  } ],
  284: [ (function(require, module, exports) {
    require("./CCSGTMXLayer");
    require("./CCTMXLayerCanvasRenderCmd");
    require("./CCTMXLayerWebGLRenderCmd");
    var TiledLayer = cc.Class({
      name: "cc.TiledLayer",
      extends: cc._SGComponent,
      onEnable: function() {
        this._sgNode && this._sgNode.setVisible(true);
      },
      onDisable: function() {
        this._sgNode && this._sgNode.setVisible(false);
      },
      onDestroy: function() {
        this.node._sizeProvider === this._sgNode && (this.node._sizeProvider = null);
      },
      _initSgNode: function() {
        var sgNode = this._sgNode;
        if (!sgNode) return;
        this.enabledInHierarchy || sgNode.setVisible(false);
        this._registSizeProvider();
        var node = this.node;
        sgNode.setAnchorPoint(node.getAnchorPoint());
      },
      _replaceSgNode: function(sgNode) {
        if (sgNode === this._sgNode) return;
        this._removeSgNode();
        this.node._sizeProvider === this._sgNode && (this.node._sizeProvider = null);
        if (sgNode && sgNode instanceof _ccsg.TMXLayer) {
          this._sgNode = sgNode;
          false;
          this._initSgNode();
        } else this._sgNode = null;
      },
      getLayerName: function() {
        if (this._sgNode) return this._sgNode.getLayerName();
        return "";
      },
      setLayerName: function(layerName) {
        this._sgNode && this._sgNode.setLayerName(layerName);
      },
      getProperty: function(propertyName) {
        if (this._sgNode) return this._sgNode.getProperty(propertyName);
        return null;
      },
      getPositionAt: function(pos, y) {
        if (this._sgNode) {
          void 0 !== y && (pos = cc.p(pos, y));
          return this._sgNode.getPositionAt(pos);
        }
        return null;
      },
      removeTileAt: function(pos, y) {
        if (this._sgNode) {
          void 0 !== y && (pos = cc.p(pos, y));
          this._sgNode.removeTileAt(pos);
        }
      },
      setTileGID: function(gid, posOrX, flagsOrY, flags) {
        if (this._sgNode) {
          if (void 0 === posOrX) throw new Error("_ccsg.TMXLayer.setTileGID(): pos should be non-null");
          var pos;
          if (void 0 === flags && posOrX instanceof cc.Vec2) {
            pos = posOrX;
            flags = flagsOrY;
          } else pos = cc.p(posOrX, flagsOrY);
          this._sgNode.setTileGID(gid, pos, flags);
        }
      },
      getTileGIDAt: function(pos, y) {
        if (this._sgNode) {
          void 0 !== y && (pos = cc.p(pos, y));
          return this._sgNode.getTileGIDAt(pos);
        }
        return 0;
      },
      getTileAt: function(pos, y) {
        if (this._sgNode) {
          void 0 !== y && (pos = cc.p(pos, y));
          return this._sgNode.getTileAt(pos);
        }
        return null;
      },
      releaseMap: function() {
        this._sgNode && this._sgNode.releaseMap();
      },
      setContentSize: function(size, height) {
        if (this._sgNode) {
          void 0 !== height && (size = cc.size(size, height));
          this._sgNode.setContentSize(size);
        }
      },
      getTexture: function() {
        if (this._sgNode) return this._sgNode.getTexture();
        return null;
      },
      setTexture: function(texture) {
        this._sgNode && this._sgNode.setTexture(texture);
      },
      setTileOpacity: function(opacity) {
        if (this._sgNode) {
          false;
          this._sgNode._opacity = opacity;
        }
      },
      getLayerSize: function() {
        if (this._sgNode) return this._sgNode.getLayerSize();
        return cc.size(0, 0);
      },
      setLayerSize: function(layerSize) {
        this._sgNode && this._sgNode.setLayerSize(layerSize);
      },
      getMapTileSize: function() {
        if (this._sgNode) return this._sgNode.getMapTileSize();
        return cc.size(0, 0);
      },
      setMapTileSize: function(tileSize) {
        this._sgNode && this._sgNode.setMapTileSize(tileSize);
      },
      getTiles: function() {
        if (this._sgNode) return this._sgNode.getTiles();
        return null;
      },
      setTiles: function(tiles) {
        this._sgNode && this._sgNode.setTiles(tiles);
      },
      getTileSet: function() {
        if (this._sgNode) return this._sgNode.getTileSet();
        return null;
      },
      setTileSet: function(tileset) {
        this._sgNode && this._sgNode.setTileSet(tileset);
      },
      getLayerOrientation: function() {
        if (this._sgNode) return this._sgNode.getLayerOrientation();
        return 0;
      },
      setLayerOrientation: function(orientation) {
        this._sgNode && this._sgNode.setLayerOrientation(orientation);
      },
      getProperties: function() {
        if (this._sgNode) return this._sgNode.getProperties();
        return null;
      },
      setProperties: function(properties) {
        this._sgNode && this._sgNode.setProperties(properties);
      },
      _tryRemoveNode: function() {
        this.node.removeComponent(cc.TiledLayer);
        1 === this.node._components.length && 0 === this.node.getChildren().length && this.node.removeFromParent();
      }
    });
    cc.TiledLayer = module.exports = TiledLayer;
  }), {
    "./CCSGTMXLayer": 277,
    "./CCTMXLayerCanvasRenderCmd": 281,
    "./CCTMXLayerWebGLRenderCmd": 282
  } ],
  285: [ (function(require, module, exports) {
    require("./CCTiledMapAsset");
    require("./CCTiledLayer");
    require("./CCTiledObjectGroup");
    require("./CCSGTMXTiledMap");
    var Orientation = cc.Enum({
      ORTHO: 0,
      HEX: 1,
      ISO: 2
    });
    var Property = cc.Enum({
      NONE: 0,
      MAP: 1,
      LAYER: 2,
      OBJECTGROUP: 3,
      OBJECT: 4,
      TILE: 5
    });
    var TileFlag = cc.Enum({
      HORIZONTAL: 2147483648,
      VERTICAL: 1073741824,
      DIAGONAL: 536870912,
      FLIPPED_ALL: 3758096384,
      FLIPPED_MASK: 536870911
    });
    var StaggerAxis = cc.Enum({
      STAGGERAXIS_X: 0,
      STAGGERAXIS_Y: 1
    });
    var StaggerIndex = cc.Enum({
      STAGGERINDEX_ODD: 0,
      STAGGERINDEX_EVEN: 1
    });
    var TMXObjectType = cc.Enum({
      RECT: 0,
      ELLIPSE: 1,
      POLYGON: 2,
      POLYLINE: 3,
      IMAGE: 4
    });
    var TiledMap = cc.Class({
      name: "cc.TiledMap",
      extends: cc._RendererInSG,
      editor: false,
      statics: {
        Orientation: Orientation,
        Property: Property,
        TileFlag: TileFlag,
        StaggerAxis: StaggerAxis,
        StaggerIndex: StaggerIndex,
        TMXObjectType: TMXObjectType
      },
      properties: {
        _detachedChildren: {
          default: [],
          serializable: false
        },
        _tmxFile: {
          default: null,
          type: cc.TiledMapAsset
        },
        tmxAsset: {
          get: function() {
            return this._tmxFile;
          },
          set: function(value, force) {
            if (this._tmxFile !== value || false) {
              this._tmxFile = value;
              this._applyFile();
            }
          },
          type: cc.TiledMapAsset
        }
      },
      getMapSize: function() {
        return this._sgNode.getMapSize();
      },
      setMapSize: function(mapSize) {
        this._sgNode.setMapSize(mapSize);
      },
      getTileSize: function() {
        return this._sgNode.getTileSize();
      },
      setTileSize: function(tileSize) {
        this._sgNode.setTileSize(tileSize);
      },
      getMapOrientation: function() {
        return this._sgNode.getMapOrientation();
      },
      setMapOrientation: function(orientation) {
        this._sgNode.setMapOrientation(orientation);
      },
      getObjectGroups: function() {
        var logicChildren = this.node.children;
        var ret = [];
        for (var i = 0, n = logicChildren.length; i < n; i++) {
          var child = logicChildren[i];
          var tmxGroup = child.getComponent(cc.TiledObjectGroup);
          tmxGroup && ret.push(tmxGroup);
        }
        return ret;
      },
      getProperties: function() {
        return this._sgNode.getProperties();
      },
      setProperties: function(properties) {
        this._sgNode.setProperties(properties);
      },
      initWithTMXFile: function(tmxFile) {
        cc.errorID(7200);
      },
      initWithXML: function(tmxString, resourcePath) {
        cc.errorID(7201);
      },
      allLayers: function() {
        var logicChildren = this.node.children;
        var ret = [];
        for (var i = 0, n = logicChildren.length; i < n; i++) {
          var child = logicChildren[i];
          var tmxLayer = child.getComponent(cc.TiledLayer);
          tmxLayer && ret.push(tmxLayer);
        }
        return ret;
      },
      getLayer: function(layerName) {
        var logicChildren = this.node.children;
        for (var i = 0, n = logicChildren.length; i < n; i++) {
          var child = logicChildren[i];
          var tmxLayer = child.getComponent(cc.TiledLayer);
          if (tmxLayer && tmxLayer.getLayerName() === layerName) return tmxLayer;
        }
        return null;
      },
      getObjectGroup: function(groupName) {
        var logicChildren = this.node.children;
        for (var i = 0, n = logicChildren.length; i < n; i++) {
          var child = logicChildren[i];
          var tmxGroup = child.getComponent(cc.TiledObjectGroup);
          if (tmxGroup && tmxGroup.getGroupName() === groupName) return tmxGroup;
        }
        return null;
      },
      getProperty: function(propertyName) {
        return this._sgNode.getProperty(propertyName);
      },
      getPropertiesForGID: function(GID) {
        return this._sgNode.getPropertiesForGID(GID);
      },
      onEnable: function() {
        0 === this._detachedChildren.length && this._moveLayersInSgNode(this._sgNode);
        this._super();
        this._tmxFile && this._refreshLayerEntities();
        this.node.on("anchor-changed", this._anchorChanged, this);
        this.node.on("child-added", this._childAdded, this);
        this.node.on("child-reorder", this._syncChildrenOrder, this);
      },
      onDisable: function() {
        this._super();
        this._setLayersEnabled(false);
        var restoredSgNode = this._plainNode;
        this._moveLayersInSgNode(restoredSgNode);
        this.node.off("anchor-changed", this._anchorChanged, this);
        this.node.off("child-added", this._childAdded, this);
        this.node.off("child-reorder", this._syncChildrenOrder, this);
      },
      onDestroy: function() {
        this._super();
        this._removeLayerEntities();
      },
      _createSgNode: function() {
        return new _ccsg.TMXTiledMap();
      },
      _initSgNode: function() {
        this._applyFile();
      },
      _resetSgSize: function() {
        this.node.setContentSize(this._sgNode.getContentSize());
        this._sgNode.setContentSize(0, 0);
      },
      _onMapLoaded: function() {
        this._refreshLayerEntities();
        this._enabled ? this._anchorChanged() : this._moveLayersInSgNode(this._sgNode);
        this._setLayersEnabled(this._enabled);
        this._resetSgSize();
      },
      _setLayersEnabled: function(enabled) {
        var logicChildren = this.node.getChildren();
        for (var i = logicChildren.length - 1; i >= 0; i--) {
          var child = logicChildren[i];
          var tmxLayer = child.getComponent(cc.TiledLayer);
          tmxLayer && (tmxLayer.enabled = enabled);
        }
      },
      _moveLayersInSgNode: function(sgNode) {
        this._detachedChildren.length = 0;
        var children = sgNode.getChildren();
        for (var i = children.length - 1; i >= 0; i--) {
          var child = children[i];
          if (child instanceof _ccsg.TMXLayer || child instanceof _ccsg.TMXObjectGroup) {
            sgNode.removeChild(child);
            var order = child.getLocalZOrder();
            this._detachedChildren.push({
              sgNode: child,
              zorder: order
            });
          }
        }
      },
      _removeLayerEntities: function() {
        var logicChildren = this.node.getChildren();
        for (var i = logicChildren.length - 1; i >= 0; i--) {
          var child = logicChildren[i];
          if (!child.isValid) continue;
          var tmxLayer = child.getComponent(cc.TiledLayer);
          tmxLayer && tmxLayer._tryRemoveNode();
          var tmxGroup = child.getComponent(cc.TiledObjectGroup);
          tmxGroup && tmxGroup._tryRemoveNode();
        }
      },
      _refreshLayerEntities: function() {
        var logicChildren = this.node.getChildren();
        var existedLayers = [];
        var existedGroups = [];
        var otherChildrenInfo = [];
        var i, n;
        for (i = 0; i < this._detachedChildren.length; i++) {
          var info = this._detachedChildren[i];
          this._sgNode.addChild(info.sgNode, info.zorder, info.zorder);
        }
        this._detachedChildren.length = 0;
        var layerNames = this._sgNode.allLayers().map((function(layer) {
          return layer.getLayerName();
        }));
        var groupNames = this._sgNode.getObjectGroups().map((function(group) {
          return group.getGroupName();
        }));
        for (i = logicChildren.length - 1; i >= 0; i--) {
          var child = logicChildren[i];
          var tmxLayer = child.getComponent(cc.TiledLayer);
          var tmxGroup = child.getComponent(cc.TiledObjectGroup);
          if (tmxLayer) {
            var layerName = tmxLayer.getLayerName();
            layerName || (layerName = child._name);
            if (layerNames.indexOf(layerName) < 0) tmxLayer._tryRemoveNode(); else {
              existedLayers.push(child);
              var newSGLayer = this._sgNode.getLayer(layerName);
              tmxLayer._replaceSgNode(newSGLayer);
              tmxLayer.enabled = true;
            }
          } else if (tmxGroup) {
            var groupName = tmxGroup.getGroupName();
            groupName || (groupName = child._name);
            if (groupNames.indexOf(groupName) < 0) tmxGroup._tryRemoveNode(); else {
              existedGroups.push(child);
              var newSGGroup = this._sgNode.getObjectGroup(groupName);
              tmxGroup._replaceSgNode(newSGGroup);
              tmxGroup.enabled = newSGGroup.isVisible();
            }
          } else otherChildrenInfo.push({
            child: child,
            index: child.getSiblingIndex()
          });
        }
        var existedNames = existedLayers.map((function(node) {
          var tmxLayer = node.getComponent(cc.TiledLayer);
          return tmxLayer.getLayerName();
        }));
        for (i = 0, n = layerNames.length; i < n; i++) {
          var name = layerNames[i];
          var sgLayer = this._sgNode.getLayer(name);
          var theIndex = existedNames.indexOf(name);
          if (theIndex < 0) {
            var node = this.node.getChildByName(name);
            var addedLayer = null;
            if (node && !node.getComponent(cc._SGComponent)) addedLayer = node.addComponent(cc.TiledLayer); else {
              node = new cc.Node(name);
              this.node.addChild(node);
              addedLayer = node.addComponent(cc.TiledLayer);
            }
            node && addedLayer || cc.errorID(7202);
            addedLayer._replaceSgNode(sgLayer);
            node.setSiblingIndex(sgLayer.getLocalZOrder());
            node.setAnchorPoint(this.node.getAnchorPoint());
          }
        }
        var existedGroupNames = existedGroups.map((function(node) {
          var tmxGroup = node.getComponent(cc.TiledObjectGroup);
          return tmxGroup.getGroupName();
        }));
        for (i = 0, n = groupNames.length; i < n; i++) {
          name = groupNames[i];
          var sgGroup = this._sgNode.getObjectGroup(name);
          theIndex = existedGroupNames.indexOf(name);
          if (theIndex < 0) {
            node = this.node.getChildByName(name);
            var addedGroup = null;
            if (node && !node.getComponent(cc._SGComponent)) addedGroup = node.addComponent(cc.TiledObjectGroup); else {
              node = new cc.Node(name);
              this.node.addChild(node);
              addedGroup = node.addComponent(cc.TiledObjectGroup);
            }
            node && addedGroup || cc.errorID(7202);
            addedGroup._replaceSgNode(sgGroup);
            node.setSiblingIndex(sgGroup.getLocalZOrder());
            node.setAnchorPoint(this.node.getAnchorPoint());
            addedGroup.enabled = sgGroup.isVisible();
          }
        }
        var curChildren = this.node.getChildren();
        var curLayerNames = [];
        for (i = 0, n = curChildren.length; i < n; i++) {
          child = curChildren[i];
          tmxLayer = child.getComponent(cc.TiledLayer);
          tmxGroup = child.getComponent(cc.TiledObjectGroup);
          (tmxLayer || tmxGroup) && curLayerNames.push(child._name);
        }
        var sgLayerNames = [];
        var sgLayers = [];
        var sgChildren = this._sgNode.getChildren();
        for (i = 0, n = sgChildren.length; i < n; i++) {
          child = sgChildren[i];
          if (child instanceof _ccsg.TMXLayer) {
            sgLayerNames.push(child.getLayerName());
            sgLayers.push(child);
          } else if (child instanceof _ccsg.TMXObjectGroup) {
            sgLayerNames.push(child.getGroupName());
            sgLayers.push(child);
          }
        }
        for (i = sgLayerNames.length - 1; i >= 0; i--) {
          var curName = sgLayerNames[i];
          var nodeIdx = curLayerNames.indexOf(curName);
          if (i !== nodeIdx) {
            var curNode = this.node.getChildByName(curName);
            curNode.setSiblingIndex(sgLayers[i].getLocalZOrder());
          }
        }
        for (i = 0, n = otherChildrenInfo.length; i < n; i++) {
          info = otherChildrenInfo[i];
          info.child.setSiblingIndex(info.index);
        }
        this._syncChildrenOrder();
      },
      _anchorChanged: function() {
        var children = this.node.children;
        var anchor = this.node.getAnchorPoint();
        for (var i = 0, n = children.length; i < n; i++) {
          var child = children[i];
          var hasLayer = child.getComponent(cc.TiledLayer);
          hasLayer && child.setAnchorPoint(anchor);
        }
      },
      _childAdded: function(event) {
        var node = event.detail;
        if (node) {
          var tmxLayer = node.getComponent(cc.TiledLayer);
          var tmxGroup = node.getComponent(cc.TiledObjectGroup);
          if (!tmxLayer && !tmxGroup) {
            var childrenCount = this.node.getChildrenCount();
            node.setSiblingIndex(childrenCount);
            node._sgNode && node._sgNode.setLocalZOrder(childrenCount);
          }
        }
      },
      _syncChildrenOrder: function() {
        var logicChildren = this.node.children;
        for (var i = 0, n = logicChildren.length; i < n; i++) {
          var child = logicChildren[i];
          var tmxLayer = child.getComponent(cc.TiledLayer);
          var tmxGroup = child.getComponent(cc.TiledObjectGroup);
          var zOrderValue = child.getSiblingIndex();
          tmxLayer && tmxLayer._sgNode && tmxLayer._sgNode.setLocalZOrder(zOrderValue);
          tmxGroup && tmxGroup._sgNode && tmxGroup._sgNode.setLocalZOrder(zOrderValue);
          child._sgNode && child._sgNode.setLocalZOrder(zOrderValue);
        }
      },
      _applyFile: function() {
        var sgNode = this._sgNode;
        var file = this._tmxFile;
        var self = this;
        if (file) {
          var resPath = cc.url._rawAssets + file.tmxFolderPath;
          resPath = cc.path.stripSep(resPath);
          false;
          var ret = sgNode.initWithXML(file.tmxXmlStr, resPath);
          if (ret) {
            self._detachedChildren.length = 0;
            self._onMapLoaded();
          }
        } else {
          var layers = sgNode.allLayers();
          for (var i = 0, n = layers.length; i < n; i++) sgNode.removeChild(layers[i]);
          var groups = sgNode.getObjectGroups();
          for (i = 0, n = groups.length; i < n; i++) sgNode.removeChild(groups[i]);
          this._detachedChildren.length = 0;
          self._removeLayerEntities();
        }
      }
    });
    cc.TiledMap = module.exports = TiledMap;
    cc.js.obsolete(cc.TiledMap.prototype, "cc.TiledMap.tmxFile", "tmxAsset", true);
    cc.js.get(cc.TiledMap.prototype, "mapLoaded", (function() {
      cc.errorID(7203);
      return [];
    }), false);
  }), {
    "./CCSGTMXTiledMap": 280,
    "./CCTiledLayer": 284,
    "./CCTiledMapAsset": 286,
    "./CCTiledObjectGroup": 287
  } ],
  286: [ (function(require, module, exports) {
    var TiledMapAsset = cc.Class({
      name: "cc.TiledMapAsset",
      extends: cc.Asset,
      properties: {
        tmxXmlStr: {
          default: ""
        },
        tmxFolderPath: {
          default: ""
        },
        textures: {
          default: [],
          url: [ cc.Texture2D ]
        },
        tsxFiles: {
          default: [],
          url: [ cc.RawAsset ]
        }
      },
      statics: {
        preventDeferredLoadDependents: true
      },
      createNode: false
    });
    cc.TiledMapAsset = TiledMapAsset;
    module.exports = TiledMapAsset;
  }), {} ],
  287: [ (function(require, module, exports) {
    require("./CCSGTMXObjectGroup");
    var TiledObjectGroup = cc.Class({
      name: "cc.TiledObjectGroup",
      extends: cc._SGComponent,
      onEnable: function() {
        this._sgNode && this._sgNode.setVisible(true);
      },
      onDisable: function() {
        this._sgNode && this._sgNode.setVisible(false);
      },
      onDestroy: function() {
        this.node._sizeProvider === this._sgNode && (this.node._sizeProvider = null);
      },
      _initSgNode: function() {
        var sgNode = this._sgNode;
        if (!sgNode) return;
        this._registSizeProvider();
        sgNode.setAnchorPoint(this.node.getAnchorPoint());
      },
      _replaceSgNode: function(sgNode) {
        if (sgNode === this._sgNode) return;
        this._removeSgNode();
        this.node._sizeProvider === this._sgNode && (this.node._sizeProvider = null);
        if (sgNode && sgNode instanceof _ccsg.TMXObjectGroup) {
          this._sgNode = sgNode;
          false;
          this._initSgNode();
        } else this._sgNode = null;
      },
      getPositionOffset: function() {
        if (this._sgNode) return this._sgNode.getPositionOffset();
        return cc.p(0, 0);
      },
      setPositionOffset: function(offset) {
        this._sgNode && this._sgNode.setPositionOffset(offset);
      },
      getProperties: function() {
        if (this._sgNode) return this._sgNode.getProperties();
        return null;
      },
      setProperties: function(Var) {
        this._sgNode && this._sgNode.setProperties(Var);
      },
      getGroupName: function() {
        if (this._sgNode) return this._sgNode.getGroupName();
        return "";
      },
      setGroupName: function(groupName) {
        this._sgNode && this._sgNode.setGroupName(groupName);
      },
      getProperty: function(propertyName) {
        if (this._sgNode) return this._sgNode.propertyNamed(propertyName);
        return null;
      },
      getObject: function(objectName) {
        if (this._sgNode) return this._sgNode.getObject(objectName);
        return null;
      },
      getObjects: function() {
        if (this._sgNode) return this._sgNode.getObjects();
        return [];
      },
      _tryRemoveNode: function() {
        this.node.removeComponent(cc.TiledObjectGroup);
        1 === this.node._components.length && 0 === this.node.getChildren().length && this.node.removeFromParent();
      }
    });
    cc.TiledObjectGroup = module.exports = TiledObjectGroup;
  }), {
    "./CCSGTMXObjectGroup": 279
  } ],
  288: [ (function(require, module, exports) {
    require("./cocos2d/core");
    require("./cocos2d/animation");
    false;
    require("./cocos2d/particle/CCParticleSystem");
    require("./cocos2d/tilemap/CCTiledMap");
    require("./cocos2d/motion-streak/CCMotionStreak");
    require("./cocos2d/core/components/CCStudioComponent");
    require("./extensions/ccpool/CCNodePool");
    require("./extensions/ccpool/CCPool");
    true;
    require("./cocos2d/actions");
    require("./external/chipmunk/chipmunk");
    require("./extensions/spine");
    require("./extensions/dragonbones");
    true;
    require("./cocos2d/deprecated");
  }), {
    "./cocos2d/actions": 10,
    "./cocos2d/animation": 18,
    "./cocos2d/core": 124,
    "./cocos2d/core/components/CCStudioComponent": 95,
    "./cocos2d/deprecated": 241,
    "./cocos2d/motion-streak/CCMotionStreak": 256,
    "./cocos2d/particle/CCParticleAsset": 260,
    "./cocos2d/particle/CCParticleSystem": 261,
    "./cocos2d/tilemap/CCTiledMap": 285,
    "./cocos2d/tilemap/CCTiledMapAsset": 286,
    "./extensions/ccpool/CCNodePool": 289,
    "./extensions/ccpool/CCPool": 290,
    "./extensions/dragonbones": 298,
    "./extensions/spine": 307,
    "./external/chipmunk/chipmunk": 310
  } ],
  289: [ (function(require, module, exports) {
    cc.NodePool = function(poolHandlerComp) {
      this.poolHandlerComp = poolHandlerComp;
      this._pool = [];
    };
    cc.NodePool.prototype = {
      constructor: cc.NodePool,
      size: function() {
        return this._pool.length;
      },
      clear: function() {
        var count = this._pool.length;
        for (var i = 0; i < count; ++i) this._pool[i].destroy();
        this._pool.length = 0;
      },
      put: function(obj) {
        if (obj && -1 === this._pool.indexOf(obj)) {
          obj.removeFromParent(false);
          var handler = this.poolHandlerComp ? obj.getComponent(this.poolHandlerComp) : null;
          handler && handler.unuse && handler.unuse();
          this._pool.push(obj);
        }
      },
      get: function() {
        var last = this._pool.length - 1;
        if (last < 0) return null;
        var obj = this._pool[last];
        this._pool.length = last;
        var handler = this.poolHandlerComp ? obj.getComponent(this.poolHandlerComp) : null;
        handler && handler.reuse && handler.reuse.apply(handler, arguments);
        return obj;
      }
    };
    module.exports = cc.NodePool;
  }), {} ],
  290: [ (function(require, module, exports) {
    var _args = [];
    cc.pool = {
      _pool: {},
      _releaseCB: function() {
        this.release();
      },
      _autoRelease: function(obj) {
        var running = void 0 !== obj._running && !obj._running;
        cc.director.getScheduler().schedule(this._releaseCB, obj, 0, 0, 0, running);
      },
      putInPool: function(obj) {
        var cid = cc.js._getClassId(obj.constructor);
        if (!cid) return;
        this._pool[cid] || (this._pool[cid] = []);
        false;
        obj.unuse && obj.unuse();
        this._pool[cid].push(obj);
      },
      hasObject: function(objClass) {
        var cid = cc.js._getClassId(objClass);
        var list = this._pool[cid];
        if (!list || 0 === list.length) return false;
        return true;
      },
      removeObject: function(obj) {
        var cid = cc.js._getClassId(obj.constructor);
        if (cid) {
          var list = this._pool[cid];
          if (list) for (var i = 0; i < list.length; i++) if (obj === list[i]) {
            false;
            list.splice(i, 1);
          }
        }
      },
      getFromPool: function(objClass) {
        if (this.hasObject(objClass)) {
          var cid = cc.js._getClassId(objClass);
          var list = this._pool[cid];
          _args.length = arguments.length - 1;
          for (var i = 0; i < _args.length; i++) _args[i] = arguments[i + 1];
          var obj = list.pop();
          obj.reuse && obj.reuse.apply(obj, _args);
          false;
          _args.length = 0;
          return obj;
        }
      },
      drainAllPools: function() {
        var i;
        var j;
        var obj;
        false;
        this._pool = {};
      }
    };
  }), {} ],
  291: [ (function(require, module, exports) {
    var DefaultArmaturesEnum = cc.Enum({
      default: -1
    });
    var DefaultAnimsEnum = cc.Enum({
      "<None>": 0
    });
    function setEnumAttr(obj, propName, enumDef) {
      cc.Class.attr(obj, propName, {
        type: "Enum",
        enumList: cc.Enum.getList(enumDef)
      });
    }
    dragonBones.ArmatureDisplay = cc.Class({
      name: "dragonBones.ArmatureDisplay",
      extends: cc._RendererUnderSG,
      editor: false,
      properties: {
        _factory: {
          default: null,
          type: dragonBones.CCFactory,
          serializable: false
        },
        _dragonBonesData: {
          default: null,
          type: dragonBones.DragonBonesData,
          serializable: false
        },
        dragonAsset: {
          default: null,
          type: dragonBones.DragonBonesAsset,
          notify: function() {
            this._parseDragonAsset();
            this._refresh();
            false;
          },
          tooltip: false
        },
        dragonAtlasAsset: {
          default: null,
          type: dragonBones.DragonBonesAtlasAsset,
          notify: function() {
            this._parseDragonAtlasAsset();
            this._refreshSgNode();
          },
          tooltip: false
        },
        _armatureName: "",
        armatureName: {
          get: function() {
            return this._armatureName;
          },
          set: function(value) {
            this._armatureName = value;
            var animNames = this.getAnimationNames(this._armatureName);
            if (!this.animationName || animNames.indexOf(this.animationName) < 0) {
              false;
              this.animationName = "";
            }
            this._refresh();
          },
          visible: false
        },
        _animationName: "",
        animationName: {
          get: function() {
            return this._animationName;
          },
          set: function(value) {
            this._animationName = value;
          },
          visible: false
        },
        _defaultArmatureIndex: {
          default: 0,
          notify: function() {
            var armatureName = "";
            if (this.dragonAsset) {
              var armaturesEnum;
              this.dragonAsset && (armaturesEnum = this.dragonAsset.getArmatureEnum());
              if (!armaturesEnum) return cc.errorID(7400, this.name);
              armatureName = armaturesEnum[this._defaultArmatureIndex];
            }
            void 0 !== armatureName ? this.armatureName = armatureName : cc.errorID(7401, this.name);
          },
          type: DefaultArmaturesEnum,
          visible: true,
          editorOnly: true,
          displayName: "Armature",
          tooltip: false
        },
        _animationIndex: {
          default: 0,
          notify: function() {
            if (0 === this._animationIndex) {
              this.animationName = "";
              return;
            }
            var animsEnum;
            this.dragonAsset && (animsEnum = this.dragonAsset.getAnimsEnum(this.armatureName));
            if (!animsEnum) return;
            var animName = animsEnum[this._animationIndex];
            void 0 !== animName ? this.animationName = animName : cc.errorID(7402, this.name);
          },
          type: DefaultAnimsEnum,
          visible: true,
          editorOnly: true,
          displayName: "Animation",
          tooltip: false
        },
        timeScale: {
          default: 1,
          notify: function() {
            this._sgNode && (this._sgNode.animation().timeScale = this.timeScale);
          },
          tooltip: false
        },
        playTimes: {
          default: -1,
          tooltip: false
        },
        debugBones: {
          default: false,
          notify: function() {
            this._sgNode && this._sgNode.setDebugBones(this.debugBones);
          },
          editorOnly: true,
          tooltip: false
        }
      },
      ctor: function() {
        false;
        this._factory = dragonBones.CCFactory.getInstance();
      },
      __preload: function() {
        this._parseDragonAsset();
        this._parseDragonAtlasAsset();
        this._refresh();
      },
      _createSgNode: function() {
        if (this.dragonAsset && this.dragonAtlasAsset && this.armatureName) return this._factory.buildArmatureDisplay(this.armatureName, this._dragonBonesData.name);
        return null;
      },
      _initSgNode: function() {
        var sgNode = this._sgNode;
        sgNode.animation().timeScale = this.timeScale;
        this.animationName && this.playAnimation(this.animationName, this.playTimes);
        false;
      },
      _removeSgNode: function() {
        var sgNode = this._sgNode;
        this._super();
        sgNode && sgNode.armature().dispose();
      },
      _parseDragonAsset: function() {
        if (this.dragonAsset) {
          false;
          var jsonObj = JSON.parse(this.dragonAsset.dragonBonesJson);
          var data = this._factory.getDragonBonesData(jsonObj.name);
          if (data) {
            var armature, dragonBonesData;
            for (var i = 0, len = jsonObj.armature.length; i < len; i++) {
              armature = jsonObj.armature[i];
              if (!data.armatures[armature.name]) {
                dragonBonesData || (dragonBonesData = this._factory._dataParser.parseDragonBonesData(jsonObj));
                data.addArmature(dragonBonesData.armatures[armature.name]);
              }
            }
            this._dragonBonesData = data;
            return;
          }
          this._dragonBonesData = this._factory.parseDragonBonesData(jsonObj);
        }
      },
      _parseDragonAtlasAsset: function() {
        if (this.dragonAtlasAsset) {
          false;
          var atlasJsonObj = JSON.parse(this.dragonAtlasAsset.atlasJson);
          var atlasName = atlasJsonObj.name;
          var existedAtlasData = null;
          var atlasDataList = this._factory.getTextureAtlasData(atlasName);
          var texturePath = this.dragonAtlasAsset.texture;
          if (atlasDataList && atlasDataList.length > 0) for (var idx in atlasDataList) {
            var data = atlasDataList[idx];
            if (data && data.texture && data.texture.url === texturePath) {
              existedAtlasData = data;
              break;
            }
          }
          var texture = cc.textureCache.getTextureForKey(texturePath);
          existedAtlasData ? existedAtlasData.texture = texture : this._factory.parseTextureAtlasData(atlasJsonObj, texture);
        }
      },
      _refreshSgNode: function() {
        var self = this;
        var listenersBefore = null, listenersCacheBefore = null;
        if (self._sgNode) {
          listenersBefore = self._sgNode._bubblingListeners;
          listenersCacheBefore = self._sgNode._hasListenerCache;
          self.node._sizeProvider === self._sgNode && (self.node._sizeProvider = null);
          self._removeSgNode();
          self._sgNode = null;
        }
        var sgNode = self._sgNode = self._createSgNode();
        if (sgNode) {
          false;
          self.enabledInHierarchy || sgNode.setVisible(false);
          if (listenersBefore) {
            sgNode._bubblingListeners = listenersBefore;
            sgNode._hasListenerCache = listenersCacheBefore;
            false;
          }
          self._initSgNode();
          self._appendSgNode(sgNode);
          self._registSizeProvider();
        }
      },
      _refresh: function() {
        this._refreshSgNode();
        false;
      },
      _updateAnimEnum: false,
      _updateArmatureEnum: false,
      playAnimation: function(animName, playTimes) {
        if (this._sgNode) {
          this.playTimes = void 0 === playTimes ? -1 : playTimes;
          this.animationName = animName;
          return this._sgNode.animation().play(animName, this.playTimes);
        }
        return null;
      },
      getArmatureNames: function() {
        if (this._dragonBonesData) return this._dragonBonesData.armatureNames;
        return [];
      },
      getAnimationNames: function(armatureName) {
        var ret = [];
        if (this._dragonBonesData) {
          var armatureData = this._dragonBonesData.getArmature(armatureName);
          if (armatureData) for (var animName in armatureData.animations) armatureData.animations.hasOwnProperty(animName) && ret.push(animName);
        }
        return ret;
      },
      addEventListener: function(eventType, listener, target) {
        this._sgNode && this._sgNode.addEvent(eventType, listener, target);
      },
      removeEventListener: function(eventType, listener, target) {
        this._sgNode && this._sgNode.removeEvent(eventType, listener, target);
      },
      buildArmature: function(armatureName) {
        if (this._factory) return this._factory.buildArmature(armatureName);
        return null;
      },
      armature: function() {
        if (this._sgNode) return this._sgNode.armature();
        return null;
      }
    });
  }), {} ],
  292: [ (function(require, module, exports) {
    var EventTarget = require("../../cocos2d/core/event/event-target");
    require("../../cocos2d/shape-nodes/CCDrawNode");
    dragonBones.CCArmatureDisplay = cc.Class({
      name: "dragonBones.CCArmatureDisplay",
      extends: _ccsg.Node,
      mixins: [ EventTarget ],
      _armature: null,
      _debugDrawer: null,
      _onClear: function() {
        this._armature = null;
      },
      _dispatchEvent: function(eventObject) {
        this.emit(eventObject.type, eventObject);
      },
      _debugDraw: function() {
        if (!this._armature) return;
        if (!this._debugDrawer) {
          this._debugDrawer = new cc.DrawNode();
          this.addChild(this._debugDrawer);
          this._debugDrawer.setDrawColor(cc.color(255, 0, 0, 255));
          this._debugDrawer.setLineWidth(1);
        }
        this._debugDrawer.clear();
        var bones = this._armature.getBones();
        for (var i = 0, l = bones.length; i < l; ++i) {
          var bone = bones[i];
          var boneLength = Math.max(bone.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;
          this._debugDrawer.drawSegment(cc.p(startX, startY), cc.p(endX, endY));
        }
      },
      update: function(passedTime) {
        this._armature && this._armature.advanceTime(passedTime);
      },
      advanceTimeBySelf: function(on) {
        on ? this.scheduleUpdate() : this.unscheduleUpdate();
      },
      hasEvent: function(type) {
        return this.hasEventListener(type, false);
      },
      addEvent: function(type, listener, target) {
        this.on(type, listener, target);
      },
      removeEvent: function(type, listener, target) {
        this.off(type, listener, target);
      },
      dispose: function() {
        if (this._armature) {
          this.advanceTimeBySelf(false);
          this._armature.dispose();
          this._armature = null;
        }
      },
      armature: function() {
        return this._armature;
      },
      animation: function() {
        return this._armature.animation;
      },
      setDebugBones: function(debug) {
        dragonBones.DragonBones.debugDraw = debug;
        debug ? this.armature().advanceTime(0) : this._debugDrawer && this._debugDrawer.clear();
      }
    });
  }), {
    "../../cocos2d/core/event/event-target": 112,
    "../../cocos2d/shape-nodes/CCDrawNode": 274
  } ],
  293: [ (function(require, module, exports) {
    var BaseObject = dragonBones.BaseObject;
    dragonBones.CCFactory = cc.Class({
      name: "dragonBones.CCFactory",
      extends: dragonBones.BaseFactory,
      buildArmatureDisplay: function(armatureName, dragonBonesName, skinName) {
        var armature = this.buildArmature(armatureName, dragonBonesName, skinName);
        var armatureDisplay = armature ? armature._display : null;
        armatureDisplay && armatureDisplay.advanceTimeBySelf(true);
        return armatureDisplay;
      },
      _generateTextureAtlasData: function(textureAtlasData, texture) {
        textureAtlasData || (textureAtlasData = BaseObject.borrowObject(dragonBones.CCTextureAtlasData));
        textureAtlasData.texture = texture;
        return textureAtlasData;
      },
      _generateArmature: function(dataPackage) {
        var armature = BaseObject.borrowObject(dragonBones.Armature);
        var armatureDisplayContainer = new dragonBones.CCArmatureDisplay();
        armature._armatureData = dataPackage.armature;
        armature._skinData = dataPackage.skin;
        armature._animation = BaseObject.borrowObject(dragonBones.Animation);
        armature._display = armatureDisplayContainer;
        armatureDisplayContainer.setCascadeOpacityEnabled(true);
        armatureDisplayContainer.setCascadeColorEnabled(true);
        armatureDisplayContainer._armature = armature;
        armature._animation._armature = armature;
        armature.animation.animations = dataPackage.armature.animations;
        return armature;
      },
      _generateSlot: function(dataPackage, slotDisplayDataSet) {
        var slot = BaseObject.borrowObject(dragonBones.CCSlot);
        var slotData = slotDisplayDataSet.slot;
        var displayList = [];
        slot.name = slotData.name;
        slot._rawDisplay = new cc.Scale9Sprite();
        slot._rawDisplay.setRenderingType(cc.Scale9Sprite.RenderingType.SIMPLE);
        slot._rawDisplay.setAnchorPoint(cc.p(0, 0));
        slot._meshDisplay = slot._rawDisplay;
        for (var i = 0, l = slotDisplayDataSet.displays.length; i < l; ++i) {
          var displayData = slotDisplayDataSet.displays[i];
          switch (displayData.type) {
           case dragonBones.DisplayType.Image:
            displayData.texture || (displayData.texture = this._getTextureData(dataPackage.dataName, displayData.name));
            displayList.push(slot._rawDisplay);
            break;

           case dragonBones.DisplayType.Mesh:
            displayData.texture || (displayData.texture = this._getTextureData(dataPackage.dataName, displayData.name));
            if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
              slot._meshDisplay.setRenderingType(cc.Scale9Sprite.RenderingType.MESH);
              displayList.push(slot._meshDisplay);
            } else cc.warnID(6200);
            break;

           case dragonBones.DisplayType.Armature:
            var childArmature = this.buildArmature(displayData.name, dataPackage.dataName);
            if (childArmature) {
              if (!slot.inheritAnimation) {
                var actions = slotData.actions.length > 0 ? slotData.actions : childArmature.armatureData.actions;
                if (actions.length > 0) for (var j = 0, n = actions.length; j < n; ++j) childArmature._bufferAction(actions[j]); else childArmature.animation.play();
              }
              displayData.armature = childArmature.armatureData;
            }
            displayList.push(childArmature);
            break;

           default:
            displayList.push(null);
          }
        }
        slot._setDisplayList(displayList);
        slot._rawDisplay.setLocalZOrder(slotData.zOrder);
        return slot;
      },
      getTextureDisplay: function(textureName, textureAtlasName) {
        var textureData = this._getTextureData(textureAtlasName, textureName);
        if (textureData) {
          if (!textureData.texture) {
            var textureAtlasTexture = textureData.parent.texture;
            var rect = cc.rect(textureData.region.x, textureData.region.y, textureData.region.width, textureData.region.height);
            var offset = cc.p(0, 0);
            var originSize = cc.size(textureData.region.width, textureData.region.height);
            textureData.texture = new cc.SpriteFrame();
            textureData.texture.setTexture(textureAtlasTexture, rect, textureData.rotated, offset, originSize);
          }
          var ret = new cc.Scale9Sprite();
          ret.initWithSpriteFrame(textureData.texture);
          return ret;
        }
        return null;
      }
    });
    dragonBones.CCFactory._factory = null;
    dragonBones.CCFactory.getInstance = function() {
      dragonBones.CCFactory._factory || (dragonBones.CCFactory._factory = new dragonBones.CCFactory());
      return dragonBones.CCFactory._factory;
    };
  }), {} ],
  294: [ (function(require, module, exports) {
    dragonBones.CCSlot = cc.Class({
      name: "dragonBones.CCSlot",
      extends: dragonBones.Slot,
      _renderDisplay: null,
      statics: {
        toString: function() {
          return "[class dragonBones.CCSlot]";
        }
      },
      _onClear: function() {
        dragonBones.Slot.prototype._onClear.call(this);
        this._renderDisplay = null;
      },
      _onUpdateDisplay: function() {
        this._rawDisplay || (this._rawDisplay = new cc.Scale9Sprite());
        this._renderDisplay = this._display || this._rawDisplay;
      },
      _initDisplay: function(value) {},
      _addDisplay: function() {
        var container = this._armature._display;
        container.addChild(this._renderDisplay);
      },
      _replaceDisplay: function(value) {
        var container = this._armature._display;
        var prevDisplay = value;
        container.addChild(this._renderDisplay, prevDisplay.getLocalZOrder());
        container.removeChild(prevDisplay);
      },
      _removeDisplay: function() {
        this._renderDisplay.removeFromParent();
      },
      _disposeDisplay: function(object) {},
      _updateVisible: function() {
        this._renderDisplay.setVisible(this._parent.visible);
      },
      _updateZOrder: function() {
        if (this._renderDisplay._parent) this._renderDisplay.setLocalZOrder(this._zOrder); else {
          var container = this._armature._display;
          container.addChild(this._renderDisplay, this._zOrder);
        }
      },
      _updateBlendMode: function() {
        if (this._renderDisplay instanceof cc.Scale9Sprite) switch (this._blendMode) {
         case 0:
          break;

         case 1:
          var texture = this._renderDisplay._spriteFrame.getTexture();
          texture && texture.hasPremultipliedAlpha() ? this._renderDisplay.setBlendFunc(cc.BlendFunc.BlendFactor.ONE, cc.BlendFunc.BlendFactor.ONE) : this._renderDisplay.setBlendFunc(cc.BlendFunc.BlendFactor.SRC_ALPHA, cc.BlendFunc.BlendFactor.ONE);
        } else 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();
          }
        }
      },
      _updateColor: function() {
        this._renderDisplay.setOpacity(255 * this._colorTransform.alphaMultiplier);
        var r = 255 * this._colorTransform.redMultiplier;
        var g = 255 * this._colorTransform.greenMultiplier;
        var b = 255 * this._colorTransform.blueMultiplier;
        this._renderDisplay.setColor(cc.color(r, g, b));
      },
      _updateFilters: function() {},
      _updateFrame: function() {
        if (this._display && this._displayIndex >= 0) {
          var rawDisplayData = this._displayIndex < this._displayDataSet.displays.length ? this._displayDataSet.displays[this._displayIndex] : null;
          var replacedDisplayData = this._displayIndex < this._replacedDisplayDataSet.length ? this._replacedDisplayDataSet[this._displayIndex] : null;
          var currentDisplayData = replacedDisplayData || rawDisplayData;
          var currentTextureData = currentDisplayData.texture;
          if (currentTextureData) {
            var textureAtlasTexture = currentTextureData.parent.texture;
            if (textureAtlasTexture && (!currentTextureData.texture || currentTextureData.texture.getTexture() !== textureAtlasTexture)) {
              var rect = cc.rect(currentTextureData.region.x, currentTextureData.region.y, currentTextureData.region.width, currentTextureData.region.height);
              var offset = cc.p(0, 0);
              var size = cc.size(currentTextureData.region.width, currentTextureData.region.height);
              currentTextureData.texture = new cc.SpriteFrame();
              currentTextureData.texture.setTexture(textureAtlasTexture, rect, false, offset, size);
            }
            var texture = this._armature._replacedTexture || (currentTextureData.texture ? currentTextureData.texture.getTexture() : null);
            if (this._meshData && this._display === this._meshDisplay) {
              var region = currentTextureData.region;
              var textureAtlasSize = currentTextureData.texture.getTexture().getContentSize();
              var displayVertices = [], vertexIndices = [];
              var boundsRect = cc.rect(999999, 999999, -999999, -999999);
              if (this._meshData !== rawDisplayData.mesh && rawDisplayData && rawDisplayData !== currentDisplayData) {
                this._pivotX = rawDisplayData.transform.x - currentDisplayData.transform.x;
                this._pivotY = rawDisplayData.transform.y - currentDisplayData.transform.y;
              } else {
                this._pivotX = 0;
                this._pivotY = 0;
              }
              var i, n;
              for (i = 0, n = this._meshData.uvs.length; i < n; i += 2) {
                var x = this._meshData.vertices[i];
                var y = this._meshData.vertices[i + 1];
                var u = (region.x + this._meshData.uvs[i] * region.width) / textureAtlasSize.width;
                var v = (region.y + this._meshData.uvs[i + 1] * region.height) / textureAtlasSize.height;
                displayVertices.push({
                  x: x,
                  y: -y,
                  u: u,
                  v: v
                });
                boundsRect.x > x && (boundsRect.x = x);
                boundsRect.width < x && (boundsRect.width = x);
                boundsRect.y > -y && (boundsRect.y = -y);
                boundsRect.height < -y && (boundsRect.height = -y);
              }
              boundsRect.width -= boundsRect.x;
              boundsRect.height -= boundsRect.y;
              for (i = 0, n = this._meshData.vertexIndices.length; i < n; ++i) vertexIndices.push(this._meshData.vertexIndices[i]);
              var polygonInfo = {
                triangles: {
                  verts: displayVertices,
                  indices: vertexIndices
                },
                rect: boundsRect
              };
              this._meshDisplay.setSpriteFrame(currentTextureData.texture);
              texture != currentTextureData.texture.getTexture() && this._meshDisplay.setTexture(texture);
              this._meshDisplay.setMeshPolygonInfo(polygonInfo);
              this._meshDisplay.setContentSize(cc.size(boundsRect.width, boundsRect.height));
              if (this._meshData.skinned) {
                this._meshDisplay.setScale(1, 1);
                this._meshDisplay.setRotationX(0);
                this._meshDisplay.setRotationY(0);
                this._meshDisplay.setPosition(0, 0);
              }
              this._meshDisplay.setAnchorPoint(cc.p(0, 0));
            } else {
              var scale = this._armature.armatureData.scale;
              this._pivotX = currentDisplayData.pivot.x;
              this._pivotY = currentDisplayData.pivot.y;
              if (currentDisplayData.isRelativePivot) {
                var rectData = currentTextureData.frame || currentTextureData.region;
                var width = rectData.width * scale;
                var height = rectData.height * scale;
                if (!currentTextureData.frame && currentTextureData.rotated) {
                  width = rectData.height;
                  height = rectData.width;
                }
                this._pivotX *= width;
                this._pivotY *= height;
              }
              if (currentTextureData.frame) {
                this._pivotX += currentTextureData.frame.x * scale;
                this._pivotY += currentTextureData.frame.y * scale;
              }
              if (rawDisplayData && rawDisplayData !== currentDisplayData) {
                this._pivotX += rawDisplayData.transform.x - currentDisplayData.transform.x;
                this._pivotY += rawDisplayData.transform.y - currentDisplayData.transform.y;
              }
              this._pivotY -= currentTextureData.region.height * scale;
              this._rawDisplay.setSpriteFrame(currentTextureData.texture);
              this._rawDisplay.setContentSize(currentTextureData.texture.getOriginalSize());
              texture !== currentTextureData.texture.getTexture() && this._rawDisplay.setTexture(texture);
              this._blendModeDirty = true;
            }
            this._updateVisible();
            return;
          }
        }
        this._pivotX = 0;
        this._pivotY = 0;
        this._rawDisplay.setTexture(null);
        this._rawDisplay.setVisible(false);
        this._rawDisplay.setPosition(this.origin.x, this.origin.y);
      },
      _updateMesh: function() {
        var meshDisplay = this._meshDisplay;
        var polygonInfo = meshDisplay.getMeshPolygonInfo();
        if (!meshDisplay || !polygonInfo) return;
        var hasFFD = this._ffdVertices.length > 0;
        var displayVertices = polygonInfo.triangles.verts;
        var boundsRect = cc.rect(999999, 999999, -999999, -999999);
        var iH = 0, xG = 0, yG = 0, i, l;
        if (this._meshData.skinned) {
          var iF = 0;
          for (i = 0, l = this._meshData.vertices.length; i < l; i += 2) {
            iH = Math.floor(i / 2);
            var boneIndices = this._meshData.boneIndices[iH];
            var boneVertices = this._meshData.boneVertices[iH];
            var weights = this._meshData.weights[iH];
            xG = 0;
            yG = 0;
            for (var iB = 0, lB = boneIndices.length; iB < lB; ++iB) {
              var bone = this._meshBones[boneIndices[iB]];
              var matrix = bone.globalTransformMatrix;
              var weight = weights[iB];
              var xL = 0, yL = 0;
              if (hasFFD) {
                xL = boneVertices[2 * iB] + this._ffdVertices[iF];
                yL = boneVertices[2 * iB + 1] + this._ffdVertices[iF + 1];
              } else {
                xL = boneVertices[2 * iB];
                yL = boneVertices[2 * iB + 1];
              }
              xG += (matrix.a * xL + matrix.c * yL + matrix.tx) * weight;
              yG += (matrix.b * xL + matrix.d * yL + matrix.ty) * weight;
              iF += 2;
            }
            displayVertices[iH].x = xG;
            displayVertices[iH].y = -yG;
            boundsRect.x > xG && (boundsRect.x = xG);
            boundsRect.width < xG && (boundsRect.width = xG);
            boundsRect.y > -yG && (boundsRect.y = -yG);
            boundsRect.height < -yG && (boundsRect.height = -yG);
          }
        } else if (hasFFD) {
          var vertices = this._meshData.vertices;
          for (i = 0, l = this._meshData.vertices.length; i < l; i += 2) {
            iH = Math.floor(i / 2);
            xG = vertices[i] + this._ffdVertices[i];
            yG = vertices[i + 1] + this._ffdVertices[i + 1];
            displayVertices[iH].x = xG;
            displayVertices[iH].y = -yG;
            boundsRect.x > xG && (boundsRect.x = xG);
            boundsRect.width < xG && (boundsRect.width = xG);
            boundsRect.y > -yG && (boundsRect.y = -yG);
            boundsRect.height < -yG && (boundsRect.height = -yG);
          }
        }
        boundsRect.width -= boundsRect.x;
        boundsRect.height -= boundsRect.y;
        polygonInfo.rect = boundsRect;
        var transform = meshDisplay.getNodeToParentTransform();
        meshDisplay.setContentSize(cc.size(boundsRect.width, boundsRect.height));
        meshDisplay.setMeshPolygonInfo(polygonInfo);
        this._renderDisplay._renderCmd.setNodeToParentTransform(transform);
      },
      _updateTransform: function() {
        var transform = {
          a: this.globalTransformMatrix.a,
          b: -this.globalTransformMatrix.b,
          c: -this.globalTransformMatrix.c,
          d: this.globalTransformMatrix.d,
          tx: this.globalTransformMatrix.tx - (this.globalTransformMatrix.a * this._pivotX + this.globalTransformMatrix.c * this._pivotY),
          ty: -(this.globalTransformMatrix.ty - (this.globalTransformMatrix.b * this._pivotX + this.globalTransformMatrix.d * this._pivotY))
        };
        this._renderDisplay._renderCmd.setNodeToParentTransform(transform);
      }
    });
  }), {} ],
  295: [ (function(require, module, exports) {
    dragonBones.CCTextureAtlasData = cc.Class({
      name: "dragonBones.CCTextureAtlasData",
      extends: dragonBones.TextureAtlasData,
      texture: null,
      statics: {
        toString: function() {
          return "[class dragonBones.CCTextureAtlasData]";
        }
      },
      _onClear: function() {
        dragonBones.TextureAtlasData.prototype._onClear.call(this);
        this.texture = null;
      },
      generateTextureData: function() {
        return dragonBones.BaseObject.borrowObject(dragonBones.CCTextureData);
      }
    });
    dragonBones.CCTextureData = cc.Class({
      name: "dragonBones.CCTextureData",
      extends: dragonBones.TextureData,
      texture: null,
      statics: {
        toString: function() {
          return "[class dragonBones.CCTextureData]";
        }
      },
      _onClear: function() {
        dragonBones.TextureData.prototype._onClear.call(this);
        if (this.texture) {
          this.texture.dispose();
          this.texture = null;
        }
      }
    });
  }), {} ],
  296: [ (function(require, module, exports) {
    var DragonBonesAsset = cc.Class({
      name: "dragonBones.DragonBonesAsset",
      extends: cc.Asset,
      properties: {
        _dragonBonesJson: "",
        dragonBonesJson: {
          get: function() {
            return this._dragonBonesJson;
          },
          set: function(value) {
            this._dragonBonesJson = value;
            this.reset();
          }
        }
      },
      statics: {
        preventDeferredLoadDependents: true
      },
      createNode: false,
      reset: function() {
        false;
      },
      getRuntimeData: false,
      getArmatureEnum: false,
      getAnimsEnum: false
    });
    dragonBones.DragonBonesAsset = module.exports = DragonBonesAsset;
  }), {} ],
  297: [ (function(require, module, exports) {
    var DragonBonesAtlasAsset = cc.Class({
      name: "dragonBones.DragonBonesAtlasAsset",
      extends: cc.Asset,
      properties: {
        _atlasJson: "",
        atlasJson: {
          get: function() {
            return this._atlasJson;
          },
          set: function(value) {
            this._atlasJson = value;
          }
        },
        texture: {
          default: "",
          url: cc.Texture2D
        }
      },
      statics: {
        preventDeferredLoadDependents: true
      },
      createNode: false
    });
    dragonBones.DragonBonesAtlasAsset = module.exports = DragonBonesAtlasAsset;
  }), {} ],
  298: [ (function(require, module, exports) {
    dragonBones = require("./lib/dragonBones");
    dragonBones.DisplayType = {
      Image: 0,
      Armature: 1,
      Mesh: 2
    };
    dragonBones.ArmatureType = {
      Armature: 0,
      MovieClip: 1,
      Stage: 2
    };
    dragonBones.ExtensionType = {
      FFD: 0,
      AdjustColor: 10,
      BevelFilter: 11,
      BlurFilter: 12,
      DropShadowFilter: 13,
      GlowFilter: 14,
      GradientBevelFilter: 15,
      GradientGlowFilter: 16
    };
    dragonBones.EventType = {
      Frame: 0,
      Sound: 1
    };
    dragonBones.ActionType = {
      Play: 0,
      Stop: 1,
      GotoAndPlay: 2,
      GotoAndStop: 3,
      FadeIn: 4,
      FadeOut: 5
    };
    dragonBones.AnimationFadeOutMode = {
      None: 0,
      SameLayer: 1,
      SameGroup: 2,
      SameLayerAndGroup: 3,
      All: 4
    };
    true;
    true;
    require("./CCFactory");
    require("./CCSlot");
    require("./CCTextureData");
    require("./CCArmatureDisplay");
    require("./DragonBonesAsset");
    require("./DragonBonesAtlasAsset");
    require("./ArmatureDisplay");
  }), {
    "./ArmatureDisplay": 291,
    "./CCArmatureDisplay": 292,
    "./CCFactory": 293,
    "./CCSlot": 294,
    "./CCTextureData": 295,
    "./DragonBonesAsset": 296,
    "./DragonBonesAtlasAsset": 297,
    "./lib/dragonBones": 299
  } ],
  299: [ (function(require, module, exports) {
    var __extends = this && this.__extends || function(d, b) {
      for (var p in b) b.hasOwnProperty(p) && (d[p] = b[p]);
      function __() {
        this.constructor = d;
      }
      d.prototype = null === b ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
    var dragonBones;
    (function(dragonBones) {
      var DragonBones = (function() {
        function DragonBones() {}
        DragonBones.hasArmature = function(value) {
          return DragonBones._armatures.indexOf(value) >= 0;
        };
        DragonBones.addArmature = function(value) {
          value && DragonBones._armatures.indexOf(value) < 0 && DragonBones._armatures.push(value);
        };
        DragonBones.removeArmature = function(value) {
          if (value) {
            var index = DragonBones._armatures.indexOf(value);
            index >= 0 && DragonBones._armatures.splice(index, 1);
          }
        };
        DragonBones.PI_D = 2 * Math.PI;
        DragonBones.PI_H = Math.PI / 2;
        DragonBones.PI_Q = Math.PI / 4;
        DragonBones.ANGLE_TO_RADIAN = Math.PI / 180;
        DragonBones.RADIAN_TO_ANGLE = 180 / Math.PI;
        DragonBones.SECOND_TO_MILLISECOND = 1e3;
        DragonBones.NO_TWEEN = 100;
        DragonBones.VERSION = "4.7.2";
        DragonBones.debug = false;
        DragonBones.debugDraw = false;
        DragonBones._armatures = [];
        return DragonBones;
      })();
      dragonBones.DragonBones = DragonBones;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var BaseObject = (function() {
        function BaseObject() {
          this.hashCode = BaseObject._hashCode++;
        }
        BaseObject._returnObject = function(object) {
          var classType = String(object.constructor);
          var maxCount = null == BaseObject._maxCountMap[classType] ? BaseObject._defaultMaxCount : BaseObject._maxCountMap[classType];
          var pool = BaseObject._poolsMap[classType] = BaseObject._poolsMap[classType] || [];
          if (pool.length < maxCount) {
            if (!(pool.indexOf(object) < 0)) throw new Error();
            pool.push(object);
          }
        };
        BaseObject.setMaxCount = function(objectConstructor, maxCount) {
          (maxCount < 0 || maxCount != maxCount) && (maxCount = 0);
          if (objectConstructor) {
            var classType = String(objectConstructor);
            BaseObject._maxCountMap[classType] = maxCount;
            var pool = BaseObject._poolsMap[classType];
            pool && pool.length > maxCount && (pool.length = maxCount);
          } else {
            BaseObject._defaultMaxCount = maxCount;
            for (var classType in BaseObject._poolsMap) {
              if (null == BaseObject._maxCountMap[classType]) continue;
              BaseObject._maxCountMap[classType] = maxCount;
              var pool = BaseObject._poolsMap[classType];
              pool.length > maxCount && (pool.length = maxCount);
            }
          }
        };
        BaseObject.clearPool = function(objectConstructor) {
          void 0 === objectConstructor && (objectConstructor = null);
          if (objectConstructor) {
            var pool = BaseObject._poolsMap[String(objectConstructor)];
            pool && pool.length && (pool.length = 0);
          } else for (var iP in BaseObject._poolsMap) {
            var pool = BaseObject._poolsMap[iP];
            pool.length = 0;
          }
        };
        BaseObject.borrowObject = function(objectConstructor) {
          var pool = BaseObject._poolsMap[String(objectConstructor)];
          if (pool && pool.length) return pool.pop();
          var object = new objectConstructor();
          object._onClear();
          return object;
        };
        BaseObject.prototype.returnToPool = function() {
          this._onClear();
          BaseObject._returnObject(this);
        };
        BaseObject._hashCode = 0;
        BaseObject._defaultMaxCount = 5e3;
        BaseObject._maxCountMap = {};
        BaseObject._poolsMap = {};
        return BaseObject;
      })();
      dragonBones.BaseObject = BaseObject;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var ColorTransform = (function() {
        function ColorTransform(alphaMultiplier, redMultiplier, greenMultiplier, blueMultiplier, alphaOffset, redOffset, greenOffset, blueOffset) {
          void 0 === alphaMultiplier && (alphaMultiplier = 1);
          void 0 === redMultiplier && (redMultiplier = 1);
          void 0 === greenMultiplier && (greenMultiplier = 1);
          void 0 === blueMultiplier && (blueMultiplier = 1);
          void 0 === alphaOffset && (alphaOffset = 0);
          void 0 === redOffset && (redOffset = 0);
          void 0 === greenOffset && (greenOffset = 0);
          void 0 === blueOffset && (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.redOffset = value.redOffset;
          this.greenOffset = value.blueOffset;
        };
        ColorTransform.prototype.identity = function() {
          this.alphaMultiplier = this.redMultiplier = this.greenMultiplier = this.blueMultiplier = 1;
          this.alphaOffset = this.redOffset = this.greenOffset = this.blueOffset = 0;
        };
        return ColorTransform;
      })();
      dragonBones.ColorTransform = ColorTransform;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var Point = (function() {
        function Point(x, y) {
          void 0 === x && (x = 0);
          void 0 === y && (y = 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;
        };
        return Point;
      })();
      dragonBones.Point = Point;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var Matrix = (function() {
        function Matrix(a, b, c, d, tx, ty) {
          void 0 === a && (a = 1);
          void 0 === b && (b = 0);
          void 0 === c && (c = 0);
          void 0 === d && (d = 1);
          void 0 === tx && (tx = 0);
          void 0 === ty && (ty = 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;
        };
        Matrix.prototype.identity = function() {
          this.a = this.d = 1;
          this.b = this.c = 0;
          this.tx = this.ty = 0;
        };
        Matrix.prototype.concat = function(value) {
          var aA = this.a;
          var bA = this.b;
          var cA = this.c;
          var dA = this.d;
          var txA = this.tx;
          var tyA = this.ty;
          var aB = value.a;
          var bB = value.b;
          var cB = value.c;
          var dB = value.d;
          var txB = value.tx;
          var tyB = value.ty;
          this.a = aA * aB + bA * cB;
          this.b = aA * bB + bA * dB;
          this.c = cA * aB + dA * cB;
          this.d = cA * bB + dA * dB;
          this.tx = aB * txA + cB * tyA + txB;
          this.ty = dB * tyA + bB * txA + tyB;
        };
        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;
          var n = aA * dA - bA * cA;
          this.a = dA / n;
          this.b = -bA / n;
          this.c = -cA / n;
          this.d = aA / n;
          this.tx = (cA * tyA - dA * txA) / n;
          this.ty = -(aA * tyA - bA * txA) / n;
        };
        Matrix.prototype.transformPoint = function(x, y, result, delta) {
          void 0 === delta && (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;
          }
        };
        return Matrix;
      })();
      dragonBones.Matrix = Matrix;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var Rectangle = (function() {
        function Rectangle(x, y, width, height) {
          void 0 === x && (x = 0);
          void 0 === y && (y = 0);
          void 0 === width && (width = 0);
          void 0 === height && (height = 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;
          this.width = this.height = 0;
        };
        return Rectangle;
      })();
      dragonBones.Rectangle = Rectangle;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var Transform = (function() {
        function Transform(x, y, skewX, skewY, scaleX, scaleY) {
          void 0 === x && (x = 0);
          void 0 === y && (y = 0);
          void 0 === skewX && (skewX = 0);
          void 0 === skewY && (skewY = 0);
          void 0 === scaleX && (scaleX = 1);
          void 0 === scaleY && (scaleY = 1);
          this.x = x;
          this.y = y;
          this.skewX = skewX;
          this.skewY = skewY;
          this.scaleX = scaleX;
          this.scaleY = scaleY;
        }
        Transform.normalizeRadian = function(value) {
          value = (value + Math.PI) % (2 * Math.PI);
          value += value > 0 ? -Math.PI : Math.PI;
          return value;
        };
        Transform.prototype.toString = function() {
          return "[object dragonBones.Transform] x:" + this.x + " y:" + this.y + " skewX:" + 180 * this.skewX / Math.PI + " skewY:" + 180 * this.skewY / Math.PI + " scaleX:" + this.scaleX + " scaleY:" + this.scaleY;
        };
        Transform.prototype.copyFrom = function(value) {
          this.x = value.x;
          this.y = value.y;
          this.skewX = value.skewX;
          this.skewY = value.skewY;
          this.scaleX = value.scaleX;
          this.scaleY = value.scaleY;
          return this;
        };
        Transform.prototype.identity = function() {
          this.x = this.y = this.skewX = this.skewY = 0;
          this.scaleX = this.scaleY = 1;
          return this;
        };
        Transform.prototype.add = function(value) {
          this.x += value.x;
          this.y += value.y;
          this.skewX += value.skewX;
          this.skewY += value.skewY;
          this.scaleX *= value.scaleX;
          this.scaleY *= value.scaleY;
          return this;
        };
        Transform.prototype.minus = function(value) {
          this.x -= value.x;
          this.y -= value.y;
          this.skewX = Transform.normalizeRadian(this.skewX - value.skewX);
          this.skewY = Transform.normalizeRadian(this.skewY - value.skewY);
          this.scaleX /= value.scaleX;
          this.scaleY /= value.scaleY;
          return this;
        };
        Transform.prototype.fromMatrix = function(matrix) {
          var PI_Q = .25 * Math.PI;
          var backupScaleX = this.scaleX, backupScaleY = this.scaleY;
          this.x = matrix.tx;
          this.y = matrix.ty;
          this.skewX = Math.atan(-matrix.c / matrix.d);
          this.skewY = Math.atan(matrix.b / matrix.a);
          this.skewX != this.skewX && (this.skewX = 0);
          this.skewY != this.skewY && (this.skewY = 0);
          this.scaleY = this.skewX > -PI_Q && this.skewX < PI_Q ? matrix.d / Math.cos(this.skewX) : -matrix.c / Math.sin(this.skewX);
          this.scaleX = this.skewY > -PI_Q && this.skewY < PI_Q ? matrix.a / Math.cos(this.skewY) : matrix.b / Math.sin(this.skewY);
          if (backupScaleX >= 0 && this.scaleX < 0) {
            this.scaleX = -this.scaleX;
            this.skewY = this.skewY - Math.PI;
          }
          if (backupScaleY >= 0 && this.scaleY < 0) {
            this.scaleY = -this.scaleY;
            this.skewX = this.skewX - Math.PI;
          }
          return this;
        };
        Transform.prototype.toMatrix = function(matrix) {
          matrix.a = this.scaleX * Math.cos(this.skewY);
          matrix.b = this.scaleX * Math.sin(this.skewY);
          matrix.c = -this.scaleY * Math.sin(this.skewX);
          matrix.d = this.scaleY * Math.cos(this.skewX);
          matrix.tx = this.x;
          matrix.ty = this.y;
          return this;
        };
        Object.defineProperty(Transform.prototype, "rotation", {
          get: function() {
            return this.skewY;
          },
          set: function(value) {
            var dValue = value - this.skewY;
            this.skewX += dValue;
            this.skewY += dValue;
          },
          enumerable: true,
          configurable: true
        });
        return Transform;
      })();
      dragonBones.Transform = Transform;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var TimelineState = (function(_super) {
        __extends(TimelineState, _super);
        function TimelineState() {
          _super.call(this);
        }
        TimelineState.prototype._onClear = function() {
          this._isCompleted = false;
          this._currentPlayTimes = 0;
          this._currentTime = -1;
          this._timeline = null;
          this._isReverse = false;
          this._hasAsynchronyTimeline = false;
          this._frameRate = 0;
          this._keyFrameCount = 0;
          this._frameCount = 0;
          this._position = 0;
          this._duration = 0;
          this._animationDutation = 0;
          this._timeScale = 1;
          this._timeOffset = 0;
          this._currentFrame = null;
          this._armature = null;
          this._animationState = null;
        };
        TimelineState.prototype._onUpdateFrame = function(isUpdate) {};
        TimelineState.prototype._onArriveAtFrame = function(isUpdate) {};
        TimelineState.prototype._setCurrentTime = function(value) {
          var self = this;
          var currentPlayTimes = 0;
          if (1 == self._keyFrameCount && this != self._animationState._timeline) {
            self._isCompleted = self._animationState._fadeState >= 0;
            currentPlayTimes = 1;
          } else if (self._hasAsynchronyTimeline) {
            var playTimes = self._animationState.playTimes;
            var totalTime = playTimes * self._duration;
            value *= self._timeScale;
            0 != self._timeOffset && (value += self._timeOffset * self._animationDutation);
            if (playTimes > 0 && (value >= totalTime || value <= -totalTime)) {
              self._isCompleted = true;
              currentPlayTimes = playTimes;
              value = value < 0 ? 0 : self._duration;
            } else {
              self._isCompleted = false;
              if (value < 0) {
                currentPlayTimes = Math.floor(-value / self._duration);
                value = self._duration - -value % self._duration;
              } else {
                currentPlayTimes = Math.floor(value / self._duration);
                value %= self._duration;
              }
              playTimes > 0 && currentPlayTimes > playTimes && (currentPlayTimes = playTimes);
            }
            value += self._position;
          } else {
            self._isCompleted = self._animationState._timeline._isCompleted;
            currentPlayTimes = self._animationState._timeline._currentPlayTimes;
          }
          if (self._currentTime == value) return false;
          self._isReverse = self._currentTime > value && self._currentPlayTimes == currentPlayTimes;
          self._currentTime = value;
          self._currentPlayTimes = currentPlayTimes;
          self._animationState._onFadeInComplete && (self._currentFrame = null);
          return true;
        };
        TimelineState.prototype.fadeIn = function(armature, animationState, timelineData, time) {
          this._armature = armature;
          this._animationState = animationState;
          this._timeline = timelineData;
          var isMainTimeline = this == this._animationState._timeline;
          this._hasAsynchronyTimeline = isMainTimeline || this._animationState.animationData.hasAsynchronyTimeline;
          this._frameRate = this._armature.armatureData.frameRate;
          this._keyFrameCount = this._timeline.frames.length;
          this._frameCount = this._animationState.animationData.frameCount;
          this._position = this._animationState._position;
          this._duration = this._animationState._duration;
          this._animationDutation = this._animationState.animationData.duration;
          this._timeScale = isMainTimeline ? 1 : 1 / this._timeline.scale;
          this._timeOffset = isMainTimeline ? 0 : this._timeline.offset;
        };
        TimelineState.prototype.fadeOut = function() {};
        TimelineState.prototype.update = function(time) {
          var self = this;
          if (!self._isCompleted && self._setCurrentTime(time)) {
            var currentFrameIndex = self._keyFrameCount > 1 ? Math.floor(self._currentTime * self._frameRate) : 0;
            var currentFrame = self._timeline.frames[currentFrameIndex];
            if (self._currentFrame != currentFrame) {
              self._currentFrame = currentFrame;
              self._onArriveAtFrame(true);
            }
            self._onUpdateFrame(true);
          }
        };
        return TimelineState;
      })(dragonBones.BaseObject);
      dragonBones.TimelineState = TimelineState;
      var TweenTimelineState = (function(_super) {
        __extends(TweenTimelineState, _super);
        function TweenTimelineState() {
          _super.call(this);
        }
        TweenTimelineState._getEasingValue = function(progress, easing) {
          if (progress <= 0) return 0;
          if (progress >= 1) return 1;
          var value = 1;
          if (easing > 2) return progress;
          if (easing > 1) {
            value = .5 * (1 - Math.cos(progress * Math.PI));
            easing -= 1;
          } else if (easing > 0) value = 1 - Math.pow(1 - progress, 2); else if (easing >= -1) {
            easing *= -1;
            value = Math.pow(progress, 2);
          } else {
            if (!(easing >= -2)) return progress;
            easing *= -1;
            value = Math.acos(1 - 2 * progress) / Math.PI;
            easing -= 1;
          }
          return (value - progress) * easing + progress;
        };
        TweenTimelineState._getEasingCurveValue = function(progress, samples) {
          if (progress <= 0) return 0;
          if (progress >= 1) return 1;
          var segmentCount = samples.length + 1;
          var valueIndex = Math.floor(progress * segmentCount);
          var fromValue = 0 == valueIndex ? 0 : samples[valueIndex - 1];
          var toValue = valueIndex == segmentCount - 1 ? 1 : samples[valueIndex];
          return fromValue + (toValue - fromValue) * (progress - valueIndex / segmentCount);
        };
        TweenTimelineState.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          this._tweenProgress = 0;
          this._tweenEasing = dragonBones.DragonBones.NO_TWEEN;
          this._curve = null;
        };
        TweenTimelineState.prototype._onArriveAtFrame = function(isUpdate) {
          var self = this;
          self._tweenEasing = self._currentFrame.tweenEasing;
          self._curve = self._currentFrame.curve;
          if (self._keyFrameCount <= 1 || self._currentFrame.next == self._timeline.frames[0] && (self._tweenEasing != dragonBones.DragonBones.NO_TWEEN || self._curve) && self._animationState.playTimes > 0 && self._animationState.currentPlayTimes == self._animationState.playTimes - 1) {
            self._tweenEasing = dragonBones.DragonBones.NO_TWEEN;
            self._curve = null;
          }
        };
        TweenTimelineState.prototype._onUpdateFrame = function(isUpdate) {
          var self = this;
          if (self._tweenEasing != dragonBones.DragonBones.NO_TWEEN) {
            self._tweenProgress = (self._currentTime - self._currentFrame.position + self._position) / self._currentFrame.duration;
            0 != self._tweenEasing && (self._tweenProgress = TweenTimelineState._getEasingValue(self._tweenProgress, self._tweenEasing));
          } else if (self._curve) {
            self._tweenProgress = (self._currentTime - self._currentFrame.position + self._position) / self._currentFrame.duration;
            self._tweenProgress = TweenTimelineState._getEasingCurveValue(self._tweenProgress, self._curve);
          } else self._tweenProgress = 0;
        };
        TweenTimelineState.prototype._updateExtensionKeyFrame = function(current, next, result) {
          var tweenType = 0;
          if (current.type == next.type) for (var i = 0, l = current.tweens.length; i < l; ++i) {
            var tweenDuration = next.tweens[i] - current.tweens[i];
            result.tweens[i] = tweenDuration;
            tweenDuration > 0 && (tweenType = 2);
          }
          if (0 == tweenType) {
            if (result.type != current.type) {
              tweenType = 1;
              result.type = current.type;
            }
            if (result.tweens.length != current.tweens.length) {
              tweenType = 1;
              result.tweens.length = current.tweens.length;
            }
            if (result.keys.length != current.keys.length) {
              tweenType = 1;
              result.keys.length = current.keys.length;
            }
            for (var i = 0, l = current.keys.length; i < l; ++i) {
              var key = current.keys[i];
              if (result.keys[i] != key) {
                tweenType = 1;
                result.keys[i] = key;
              }
            }
          }
          return tweenType;
        };
        return TweenTimelineState;
      })(TimelineState);
      dragonBones.TweenTimelineState = TweenTimelineState;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var Animation = (function(_super) {
        __extends(Animation, _super);
        function Animation() {
          _super.call(this);
          this._animations = {};
          this._animationNames = [];
          this._animationStates = [];
        }
        Animation._sortAnimationState = function(a, b) {
          return a.layer > b.layer ? -1 : 1;
        };
        Animation.toString = function() {
          return "[class dragonBones.Animation]";
        };
        Animation.prototype._onClear = function() {
          for (var i in this._animations) delete this._animations[i];
          for (var i = 0, l = this._animationStates.length; i < l; ++i) this._animationStates[i].returnToPool();
          this.timeScale = 1;
          this._animationStateDirty = false;
          this._armature = null;
          this._isPlaying = false;
          this._time = 0;
          this._duration = 0;
          this._lastAnimationState = null;
          this._animationNames.length = 0;
          this._animationStates.length = 0;
        };
        Animation.prototype._fadeOut = function(fadeOutTime, layer, group, fadeOutMode, pauseFadeOut) {
          var i = 0, l = this._animationStates.length;
          var animationState = null;
          switch (fadeOutMode) {
           case 1:
            for (;i < l; ++i) {
              animationState = this._animationStates[i];
              animationState.layer == layer && animationState.fadeOut(fadeOutTime, pauseFadeOut);
            }
            break;

           case 2:
            for (;i < l; ++i) {
              animationState = this._animationStates[i];
              animationState.group == group && animationState.fadeOut(fadeOutTime, pauseFadeOut);
            }
            break;

           case 4:
            for (;i < l; ++i) {
              animationState = this._animationStates[i];
              0 == fadeOutTime ? animationState.returnToPool() : animationState.fadeOut(fadeOutTime, pauseFadeOut);
            }
            0 == fadeOutTime && (this._animationStates.length = 0);
            break;

           case 3:
            for (;i < l; ++i) {
              animationState = this._animationStates[i];
              animationState.layer == layer && animationState.group == group && animationState.fadeOut(fadeOutTime, pauseFadeOut);
            }
          }
        };
        Animation.prototype._updateFFDTimelineStates = function() {
          for (var i = 0, l = this._animationStates.length; i < l; ++i) this._animationStates[i]._updateFFDTimelineStates();
        };
        Animation.prototype._advanceTime = function(passedTime) {
          var self = this;
          if (!self._isPlaying) return;
          passedTime < 0 && (passedTime = -passedTime);
          var animationStateCount = self._animationStates.length;
          if (1 == animationStateCount) {
            var animationState = self._animationStates[0];
            if (animationState._fadeState > 0 && animationState._fadeProgress <= 0) {
              animationState.returnToPool();
              self._animationStates.length = 0;
              self._animationStateDirty = true;
              self._lastAnimationState = null;
            } else animationState._advanceTime(passedTime, 1, 0);
          } else if (animationStateCount > 1) {
            var prevLayer = self._animationStates[0]._layer;
            var weightLeft = 1;
            var layerTotalWeight = 0;
            var animationIndex = 1;
            for (var i = 0, r = 0; i < animationStateCount; ++i) {
              var animationState = self._animationStates[i];
              if (animationState._fadeState > 0 && animationState._fadeProgress <= 0) {
                r++;
                animationState.returnToPool();
                self._animationStateDirty = true;
                self._lastAnimationState == animationState && (self._lastAnimationState = i - r >= 0 ? self._animationStates[i - r] : null);
              } else {
                r > 0 && (self._animationStates[i - r] = animationState);
                if (prevLayer != animationState._layer) {
                  prevLayer = animationState._layer;
                  layerTotalWeight >= weightLeft ? weightLeft = 0 : weightLeft -= layerTotalWeight;
                  layerTotalWeight = 0;
                }
                animationState._advanceTime(passedTime, weightLeft, animationIndex);
                if (animationState._weightResult > 0) {
                  layerTotalWeight += animationState._weightResult;
                  animationIndex++;
                }
              }
              i == animationStateCount - 1 && r > 0 && (self._animationStates.length -= r);
            }
          }
        };
        Animation.prototype.reset = function() {
          for (var i = 0, l = this._animationStates.length; i < l; ++i) this._animationStates[i].returnToPool();
          this._isPlaying = false;
          this._lastAnimationState = null;
          this._animationStates.length = 0;
        };
        Animation.prototype.stop = function(animationName) {
          void 0 === animationName && (animationName = null);
          if (animationName) {
            var animationState = this.getState(animationName);
            animationState && animationState.stop();
          } else this._isPlaying = false;
        };
        Animation.prototype.play = function(animationName, playTimes) {
          void 0 === animationName && (animationName = null);
          void 0 === playTimes && (playTimes = -1);
          var animationState = null;
          if (animationName) animationState = this.fadeIn(animationName, 0, playTimes, 0, null, 4); else if (this._lastAnimationState) if (this._isPlaying && (this._lastAnimationState.isPlaying || this._lastAnimationState.isCompleted)) animationState = this.fadeIn(this._lastAnimationState.name, 0, playTimes, 0, null, 4); else {
            this._isPlaying = true;
            this._lastAnimationState.play();
          } else {
            var defaultAnimation = this._armature.armatureData.defaultAnimation;
            defaultAnimation && (animationState = this.fadeIn(defaultAnimation.name, 0, playTimes, 0, null, 4));
          }
          return animationState;
        };
        Animation.prototype.fadeIn = function(animationName, fadeInTime, playTimes, layer, group, fadeOutMode, additiveBlending, displayControl, pauseFadeOut, pauseFadeIn) {
          void 0 === fadeInTime && (fadeInTime = -1);
          void 0 === playTimes && (playTimes = -1);
          void 0 === layer && (layer = 0);
          void 0 === group && (group = null);
          void 0 === fadeOutMode && (fadeOutMode = 3);
          void 0 === additiveBlending && (additiveBlending = false);
          void 0 === displayControl && (displayControl = true);
          void 0 === pauseFadeOut && (pauseFadeOut = true);
          void 0 === pauseFadeIn && (pauseFadeIn = true);
          var animationData = this._animations[animationName];
          if (!animationData) {
            this._time = 0;
            this._duration = 0;
            console.warn("Non-existent animation.", "DragonBones: " + this._armature.armatureData.parent.name, "Armature: " + this._armature.name, "Animation: " + animationName);
            return null;
          }
          this._isPlaying = true;
          this._time != this._time && (this._time = 0);
          this._duration != this._duration && (this._duration = 0);
          (fadeInTime != fadeInTime || fadeInTime < 0) && (fadeInTime = this._lastAnimationState ? animationData.fadeInTime : 0);
          playTimes < 0 && (playTimes = animationData.playTimes);
          this._fadeOut(fadeInTime, layer, group, fadeOutMode, pauseFadeOut);
          var time = this._duration > 0 ? 0 : this._time;
          var position = this._duration > 0 ? this._time : animationData.position;
          var duration = this._duration > 0 ? this._duration : animationData.duration;
          this._lastAnimationState = dragonBones.BaseObject.borrowObject(dragonBones.AnimationState);
          this._lastAnimationState._layer = layer;
          this._lastAnimationState._group = group;
          this._lastAnimationState.additiveBlending = additiveBlending;
          this._lastAnimationState.displayControl = displayControl;
          this._lastAnimationState._fadeIn(this._armature, animationData.animation || animationData, animationName, playTimes, position, duration, time, 1 / animationData.scale, fadeInTime, pauseFadeIn);
          this._animationStates.push(this._lastAnimationState);
          this._animationStateDirty = true;
          this._time = 0;
          this._duration = 0;
          this._armature._cacheFrameIndex = -1;
          this._animationStates.length > 1 && this._animationStates.sort(Animation._sortAnimationState);
          var slots = this._armature.getSlots();
          for (var i = 0, l = slots.length; i < l; ++i) {
            var slot = slots[i];
            if (slot.inheritAnimation) {
              var childArmature = slot.childArmature;
              childArmature && childArmature.animation.hasAnimation(animationName) && !childArmature.animation.getState(animationName) && childArmature.animation.fadeIn(animationName);
            }
          }
          fadeInTime <= 0 && this._armature.advanceTime(0);
          return this._lastAnimationState;
        };
        Animation.prototype.gotoAndPlayByTime = function(animationName, time, playTimes, toTime) {
          void 0 === time && (time = 0);
          void 0 === playTimes && (playTimes = -1);
          void 0 === toTime && (toTime = 0);
          var animationData = this._animations[animationName];
          if (animationData) {
            this._time = time;
            this._duration = toTime - time;
            this._duration < 0 ? this._duration = 0 : this._duration > animationData.duration - this._time && (this._duration = animationData.duration - this._time);
          }
          return this.fadeIn(animationName, 0, playTimes, 0, null, 4);
        };
        Animation.prototype.gotoAndPlayByFrame = function(animationName, frame, playTimes, toFrame) {
          void 0 === frame && (frame = 0);
          void 0 === playTimes && (playTimes = -1);
          void 0 === toFrame && (toFrame = 0);
          var animationData = this._animations[animationName];
          if (animationData) {
            this._time = animationData.duration * frame / animationData.frameCount;
            this._duration < 0 ? this._duration = 0 : this._duration > animationData.duration - this._time && (this._duration = animationData.duration - this._time);
          }
          return this.fadeIn(animationName, 0, playTimes, 0, null, 4);
        };
        Animation.prototype.gotoAndPlayByProgress = function(animationName, progress, playTimes, toProgress) {
          void 0 === progress && (progress = 0);
          void 0 === playTimes && (playTimes = -1);
          void 0 === toProgress && (toProgress = 0);
          var animationData = this._animations[animationName];
          if (animationData) {
            this._time = animationData.duration * (progress > 0 ? progress : 0);
            this._duration < 0 ? this._duration = 0 : this._duration > animationData.duration - this._time && (this._duration = animationData.duration - this._time);
          }
          return this.fadeIn(animationName, 0, playTimes, 0, null, 4);
        };
        Animation.prototype.gotoAndStopByTime = function(animationName, time) {
          void 0 === time && (time = 0);
          var animationState = this.gotoAndPlayByTime(animationName, time, 1);
          animationState && animationState.stop();
          return animationState;
        };
        Animation.prototype.gotoAndStopByFrame = function(animationName, frame) {
          void 0 === frame && (frame = 0);
          var animationState = this.gotoAndPlayByFrame(animationName, frame, 1);
          animationState && animationState.stop();
          return animationState;
        };
        Animation.prototype.gotoAndStopByProgress = function(animationName, progress) {
          void 0 === progress && (progress = 0);
          var animationState = this.gotoAndPlayByProgress(animationName, progress, 1);
          animationState && animationState.stop();
          return animationState;
        };
        Animation.prototype.getState = function(animationName) {
          for (var i = 0, l = this._animationStates.length; i < l; ++i) {
            var animationState = this._animationStates[i];
            if (animationState.name == animationName) return animationState;
          }
          return null;
        };
        Animation.prototype.hasAnimation = function(animationName) {
          return null != this._animations[animationName];
        };
        Object.defineProperty(Animation.prototype, "isPlaying", {
          get: function() {
            if (this._animationStates.length > 1) return this._isPlaying && !this.isCompleted;
            if (this._lastAnimationState) return this._isPlaying && this._lastAnimationState.isPlaying;
            return this._isPlaying;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Animation.prototype, "isCompleted", {
          get: function() {
            if (this._lastAnimationState) {
              if (!this._lastAnimationState.isCompleted) return false;
              for (var i = 0, l = this._animationStates.length; i < l; ++i) if (!this._animationStates[i].isCompleted) return false;
              return true;
            }
            return false;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Animation.prototype, "lastAnimationName", {
          get: function() {
            return this._lastAnimationState ? this._lastAnimationState.name : null;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Animation.prototype, "lastAnimationState", {
          get: function() {
            return this._lastAnimationState;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Animation.prototype, "animationNames", {
          get: function() {
            return this._animationNames;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Animation.prototype, "animations", {
          get: function() {
            return this._animations;
          },
          set: function(value) {
            if (this._animations == value) return;
            for (var i in this._animations) delete this._animations[i];
            this._animationNames.length = 0;
            if (value) for (var i in value) {
              this._animations[i] = value[i];
              this._animationNames.push(i);
            }
          },
          enumerable: true,
          configurable: true
        });
        Animation.prototype.gotoAndPlay = function(animationName, fadeInTime, duration, playTimes, layer, group, fadeOutMode, pauseFadeOut, pauseFadeIn) {
          void 0 === fadeInTime && (fadeInTime = -1);
          void 0 === duration && (duration = -1);
          void 0 === playTimes && (playTimes = -1);
          void 0 === layer && (layer = 0);
          void 0 === group && (group = null);
          void 0 === fadeOutMode && (fadeOutMode = 3);
          void 0 === pauseFadeOut && (pauseFadeOut = true);
          void 0 === pauseFadeIn && (pauseFadeIn = true);
          var animationState = this.fadeIn(animationName, fadeInTime, playTimes, layer, group, fadeOutMode, false, true, pauseFadeOut, pauseFadeIn);
          animationState && duration && duration > 0 && (animationState.timeScale = animationState.totalTime / duration);
          return animationState;
        };
        Animation.prototype.gotoAndStop = function(animationName, time) {
          void 0 === time && (time = 0);
          return this.gotoAndStopByTime(animationName, time);
        };
        Object.defineProperty(Animation.prototype, "animationList", {
          get: function() {
            return this._animationNames;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Animation.prototype, "animationDataList", {
          get: function() {
            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 = {}));
    var dragonBones;
    (function(dragonBones) {
      var AnimationState = (function(_super) {
        __extends(AnimationState, _super);
        function AnimationState() {
          _super.call(this);
          this._boneMask = [];
          this._boneTimelines = [];
          this._slotTimelines = [];
          this._ffdTimelines = [];
          this.autoTween = false;
        }
        AnimationState.toString = function() {
          return "[class dragonBones.AnimationState]";
        };
        AnimationState.prototype._onClear = function() {
          for (var i = 0, l = this._boneTimelines.length; i < l; ++i) this._boneTimelines[i].returnToPool();
          for (var i = 0, l = this._slotTimelines.length; i < l; ++i) this._slotTimelines[i].returnToPool();
          for (var i = 0, l = this._ffdTimelines.length; i < l; ++i) this._ffdTimelines[i].returnToPool();
          this._timeline && this._timeline.returnToPool();
          this._zOrderTimeline && this._zOrderTimeline.returnToPool();
          this.displayControl = true;
          this.additiveBlending = false;
          this.actionEnabled = false;
          this.playTimes = 1;
          this.timeScale = 1;
          this.weight = 1;
          this.autoFadeOutTime = -1;
          this.fadeTotalTime = 0;
          this._onFadeInComplete = false;
          this._fadeState = 0;
          this._layer = 0;
          this._position = 0;
          this._duration = 0;
          this._weightResult = 0;
          this._fadeProgress = 0;
          this._group = null;
          this._timeline = null;
          this._isPlaying = true;
          this._isPausePlayhead = false;
          this._fadeTime = 0;
          this._time = 0;
          this._name = null;
          this._armature = null;
          this._animationData = null;
          this._zOrderTimeline = null;
          this._boneMask.length = 0;
          this._boneTimelines.length = 0;
          this._slotTimelines.length = 0;
          this._ffdTimelines.length = 0;
        };
        AnimationState.prototype._updateTimelineStates = function() {
          var time = this._time;
          this._animationData.hasAsynchronyTimeline || (time = this._timeline._currentTime);
          var boneTimelineStates = {};
          var slotTimelineStates = {};
          for (var i = 0, l = this._boneTimelines.length; i < l; ++i) {
            var boneTimelineState = this._boneTimelines[i];
            boneTimelineStates[boneTimelineState.bone.name] = boneTimelineState;
          }
          var bones = this._armature.getBones();
          for (var i = 0, l = bones.length; i < l; ++i) {
            var bone = bones[i];
            var boneTimelineName = bone.name;
            var boneTimelineData = this._animationData.getBoneTimeline(boneTimelineName);
            if (boneTimelineData && this.containsBoneMask(boneTimelineName)) {
              var boneTimelineState = boneTimelineStates[boneTimelineName];
              if (boneTimelineState) delete boneTimelineStates[boneTimelineName]; else {
                boneTimelineState = dragonBones.BaseObject.borrowObject(dragonBones.BoneTimelineState);
                boneTimelineState.bone = bone;
                boneTimelineState.fadeIn(this._armature, this, boneTimelineData, time);
                this._boneTimelines.push(boneTimelineState);
              }
            }
          }
          for (var i in boneTimelineStates) {
            var boneTimelineState = boneTimelineStates[i];
            boneTimelineState.bone.invalidUpdate();
            this._boneTimelines.splice(this._boneTimelines.indexOf(boneTimelineState), 1);
            boneTimelineState.returnToPool();
          }
          for (var i = 0, l = this._slotTimelines.length; i < l; ++i) {
            var slotTimelineState = this._slotTimelines[i];
            slotTimelineStates[slotTimelineState.slot.name] = slotTimelineState;
          }
          var slots = this._armature.getSlots();
          for (var i = 0, l = slots.length; i < l; ++i) {
            var slot = slots[i];
            var slotTimelineName = slot.name;
            var parentTimelineName = slot.parent.name;
            var slotTimelineData = this._animationData.getSlotTimeline(slotTimelineName);
            if (slotTimelineData && this.containsBoneMask(parentTimelineName) && this._fadeState <= 0) {
              var slotTimelineState = slotTimelineStates[slotTimelineName];
              if (slotTimelineState) delete slotTimelineStates[slotTimelineName]; else {
                slotTimelineState = dragonBones.BaseObject.borrowObject(dragonBones.SlotTimelineState);
                slotTimelineState.slot = slot;
                slotTimelineState.fadeIn(this._armature, this, slotTimelineData, time);
                this._slotTimelines.push(slotTimelineState);
              }
            }
          }
          for (var i in slotTimelineStates) {
            var slotTimelineState = slotTimelineStates[i];
            this._slotTimelines.splice(this._slotTimelines.indexOf(slotTimelineState), 1);
            slotTimelineState.returnToPool();
          }
          this._updateFFDTimelineStates();
        };
        AnimationState.prototype._advanceFadeTime = function(passedTime) {
          var self = this;
          passedTime < 0 && (passedTime = -passedTime);
          self._fadeTime += passedTime;
          var fadeProgress = 0;
          fadeProgress = self._fadeTime >= self.fadeTotalTime ? self._fadeState > 0 ? 0 : 1 : self._fadeTime > 0 ? self._fadeState > 0 ? 1 - self._fadeTime / self.fadeTotalTime : self._fadeTime / self.fadeTotalTime : self._fadeState > 0 ? 1 : 0;
          if (self._fadeProgress != fadeProgress) {
            self._fadeProgress = fadeProgress;
            var eventDispatcher = self._armature._display;
            if (self._fadeTime <= passedTime) if (self._fadeState > 0) {
              if (eventDispatcher.hasEvent(dragonBones.EventObject.FADE_OUT)) {
                var event_1 = dragonBones.BaseObject.borrowObject(dragonBones.EventObject);
                event_1.animationState = this;
                self._armature._bufferEvent(event_1, dragonBones.EventObject.FADE_OUT);
              }
            } else if (eventDispatcher.hasEvent(dragonBones.EventObject.FADE_IN)) {
              var event_2 = dragonBones.BaseObject.borrowObject(dragonBones.EventObject);
              event_2.animationState = this;
              self._armature._bufferEvent(event_2, dragonBones.EventObject.FADE_IN);
            }
            if (self._fadeTime >= self.fadeTotalTime) if (self._fadeState > 0) {
              if (eventDispatcher.hasEvent(dragonBones.EventObject.FADE_OUT_COMPLETE)) {
                var event_3 = dragonBones.BaseObject.borrowObject(dragonBones.EventObject);
                event_3.animationState = this;
                self._armature._bufferEvent(event_3, dragonBones.EventObject.FADE_OUT_COMPLETE);
              }
            } else {
              self._onFadeInComplete = true;
              self._isPausePlayhead = false;
              self._fadeState = 0;
              if (eventDispatcher.hasEvent(dragonBones.EventObject.FADE_IN_COMPLETE)) {
                var event_4 = dragonBones.BaseObject.borrowObject(dragonBones.EventObject);
                event_4.animationState = this;
                self._armature._bufferEvent(event_4, dragonBones.EventObject.FADE_IN_COMPLETE);
              }
            }
          }
        };
        AnimationState.prototype._isDisabled = function(slot) {
          if (this.displayControl && (!slot.displayController || slot.displayController == this._name || slot.displayController == this._group)) return false;
          return true;
        };
        AnimationState.prototype._fadeIn = function(armature, clip, animationName, playTimes, position, duration, time, timeScale, fadeInTime, pausePlayhead) {
          this._armature = armature;
          this._animationData = clip;
          this._name = animationName;
          this.actionEnabled = AnimationState.stateActionEnabled;
          this.playTimes = playTimes;
          this.timeScale = timeScale;
          this.fadeTotalTime = fadeInTime;
          this._fadeState = -1;
          this._position = position;
          this._duration = duration;
          this._time = time;
          this._isPausePlayhead = pausePlayhead;
          this.fadeTotalTime <= 0 && (this._fadeProgress = .999999);
          this._timeline = dragonBones.BaseObject.borrowObject(dragonBones.AnimationTimelineState);
          this._timeline.fadeIn(this._armature, this, this._animationData, this._time);
          if (this._animationData.zOrderTimeline) {
            this._zOrderTimeline = dragonBones.BaseObject.borrowObject(dragonBones.ZOrderTimelineState);
            this._zOrderTimeline.fadeIn(this._armature, this, this._animationData.zOrderTimeline, this._time);
          }
          this._updateTimelineStates();
        };
        AnimationState.prototype._updateFFDTimelineStates = function() {
          var time = this._time;
          this._animationData.hasAsynchronyTimeline || (time = this._timeline._currentTime);
          var ffdTimelineStates = {};
          for (var i = 0, l = this._ffdTimelines.length; i < l; ++i) {
            var ffdTimelineState = this._ffdTimelines[i];
            ffdTimelineStates[ffdTimelineState.slot.name] = ffdTimelineState;
          }
          var slots = this._armature.getSlots();
          for (var i = 0, l = slots.length; i < l; ++i) {
            var slot = slots[i];
            var slotTimelineName = slot.name;
            var parentTimelineName = slot.parent.name;
            var displayData = slot.displayData;
            if (!displayData) continue;
            if (slot._meshData && slot._meshData == displayData.mesh) {
              var ffdTimelineData = this._animationData.getFFDTimeline(this._armature._skinData.name, slotTimelineName, displayData.share && displayData.inheritAnimation ? displayData.share.name : displayData.name);
              if (ffdTimelineData && this.containsBoneMask(parentTimelineName)) {
                var ffdTimelineState = ffdTimelineStates[slotTimelineName];
                if (ffdTimelineState && ffdTimelineState._timeline == ffdTimelineData) delete ffdTimelineStates[slotTimelineName]; else {
                  ffdTimelineState = dragonBones.BaseObject.borrowObject(dragonBones.FFDTimelineState);
                  ffdTimelineState.slot = slot;
                  ffdTimelineState.fadeIn(this._armature, this, ffdTimelineData, time);
                  this._ffdTimelines.push(ffdTimelineState);
                }
              } else {
                for (var iF = 0, lF = slot._ffdVertices.length; iF < lF; ++iF) slot._ffdVertices[iF] = 0;
                slot._ffdDirty = true;
              }
            }
          }
          for (var i in ffdTimelineStates) {
            var ffdTimelineState = ffdTimelineStates[i];
            this._ffdTimelines.splice(this._ffdTimelines.indexOf(ffdTimelineState), 1);
            ffdTimelineState.returnToPool();
          }
        };
        AnimationState.prototype._advanceTime = function(passedTime, weightLeft, index) {
          var self = this;
          self._onFadeInComplete = false;
          0 != self._fadeState && self._advanceFadeTime(passedTime);
          passedTime *= self.timeScale;
          0 != passedTime && self._isPlaying && !self._isPausePlayhead && (self._time += passedTime);
          self._weightResult = self.weight * self._fadeProgress * weightLeft;
          if (0 != self._weightResult) {
            var cacheFrameRate = self._animationData.cacheFrameRate;
            var isCacheEnabled = self._fadeProgress >= 1 && 0 == index && cacheFrameRate > 0;
            var isUpdatesTimeline = true;
            var isUpdatesBoneTimeline = true;
            var time = 2 * cacheFrameRate;
            time = isCacheEnabled ? Math.floor(self._time * time) / time : self._time;
            self._timeline.update(time);
            self._animationData.hasAsynchronyTimeline || (time = self._timeline._currentTime);
            self._zOrderTimeline && self._zOrderTimeline.update(time);
            if (isCacheEnabled) {
              var cacheFrameIndex = Math.floor(self._timeline._currentTime * cacheFrameRate);
              if (self._armature._cacheFrameIndex == cacheFrameIndex) {
                isUpdatesTimeline = false;
                isUpdatesBoneTimeline = false;
              } else {
                self._armature._cacheFrameIndex = cacheFrameIndex;
                if (self._armature._animation._animationStateDirty) {
                  self._armature._animation._animationStateDirty = false;
                  for (var i = 0, l = self._boneTimelines.length; i < l; ++i) {
                    var boneTimeline = self._boneTimelines[i];
                    boneTimeline.bone._cacheFrames = boneTimeline._timeline.cachedFrames;
                  }
                  for (var i = 0, l = self._slotTimelines.length; i < l; ++i) {
                    var slotTimeline = self._slotTimelines[i];
                    slotTimeline.slot._cacheFrames = slotTimeline._timeline.cachedFrames;
                  }
                }
                self._animationData.cachedFrames[cacheFrameIndex] ? isUpdatesBoneTimeline = false : self._animationData.cachedFrames[cacheFrameIndex] = true;
              }
            } else self._armature._cacheFrameIndex = -1;
            if (isUpdatesTimeline) {
              if (isUpdatesBoneTimeline) for (var i = 0, l = self._boneTimelines.length; i < l; ++i) self._boneTimelines[i].update(time);
              for (var i = 0, l = self._slotTimelines.length; i < l; ++i) self._slotTimelines[i].update(time);
              for (var i = 0, l = self._ffdTimelines.length; i < l; ++i) self._ffdTimelines[i].update(time);
            }
          }
          self.autoFadeOutTime >= 0 && self._fadeProgress >= 1 && self._timeline._isCompleted && self.fadeOut(self.autoFadeOutTime);
        };
        AnimationState.prototype.play = function() {
          this._isPlaying = true;
        };
        AnimationState.prototype.stop = function() {
          this._isPlaying = false;
        };
        AnimationState.prototype.fadeOut = function(fadeOutTime, pausePlayhead) {
          void 0 === pausePlayhead && (pausePlayhead = true);
          (fadeOutTime < 0 || fadeOutTime != fadeOutTime) && (fadeOutTime = 0);
          this._isPausePlayhead = pausePlayhead;
          if (this._fadeState > 0) {
            if (fadeOutTime > fadeOutTime - this._fadeTime) return;
          } else {
            this._fadeState = 1;
            (fadeOutTime <= 0 || this._fadeProgress <= 0) && (this._fadeProgress = 1e-6);
            for (var i = 0, l = this._boneTimelines.length; i < l; ++i) this._boneTimelines[i].fadeOut();
            for (var i = 0, l = this._slotTimelines.length; i < l; ++i) this._slotTimelines[i].fadeOut();
          }
          this.displayControl = false;
          this.fadeTotalTime = this._fadeProgress > 1e-6 ? fadeOutTime / this._fadeProgress : 0;
          this._fadeTime = this.fadeTotalTime * (1 - this._fadeProgress);
        };
        AnimationState.prototype.containsBoneMask = function(name) {
          return !this._boneMask.length || this._boneMask.indexOf(name) >= 0;
        };
        AnimationState.prototype.addBoneMask = function(name, recursive) {
          void 0 === recursive && (recursive = true);
          var currentBone = this._armature.getBone(name);
          if (!currentBone) return;
          this._boneMask.indexOf(name) < 0 && this._animationData.getBoneTimeline(name) && this._boneMask.push(name);
          if (recursive) {
            var bones = this._armature.getBones();
            for (var i = 0, l = bones.length; i < l; ++i) {
              var bone = bones[i];
              var boneName = bone.name;
              this._boneMask.indexOf(boneName) < 0 && this._animationData.getBoneTimeline(boneName) && currentBone.contains(bone) && this._boneMask.push(boneName);
            }
          }
          this._updateTimelineStates();
        };
        AnimationState.prototype.removeBoneMask = function(name, recursive) {
          void 0 === recursive && (recursive = true);
          var index = this._boneMask.indexOf(name);
          index >= 0 && this._boneMask.splice(index, 1);
          if (recursive) {
            var currentBone = this._armature.getBone(name);
            if (currentBone) {
              var bones = this._armature.getBones();
              for (var i = 0, l = bones.length; i < l; ++i) {
                var bone = bones[i];
                var boneName = bone.name;
                var index_1 = this._boneMask.indexOf(boneName);
                index_1 >= 0 && currentBone.contains(bone) && this._boneMask.splice(index_1, 1);
              }
            }
          }
          this._updateTimelineStates();
        };
        AnimationState.prototype.removeAllBoneMask = function() {
          this._boneMask.length = 0;
          this._updateTimelineStates();
        };
        Object.defineProperty(AnimationState.prototype, "layer", {
          get: function() {
            return this._layer;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(AnimationState.prototype, "group", {
          get: function() {
            return this._group;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(AnimationState.prototype, "name", {
          get: function() {
            return this._name;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(AnimationState.prototype, "animationData", {
          get: function() {
            return this._animationData;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(AnimationState.prototype, "isCompleted", {
          get: function() {
            return this._timeline._isCompleted;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(AnimationState.prototype, "isPlaying", {
          get: function() {
            return this._isPlaying && !this._timeline._isCompleted;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(AnimationState.prototype, "currentPlayTimes", {
          get: function() {
            return this._timeline._currentPlayTimes;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(AnimationState.prototype, "totalTime", {
          get: function() {
            return this._duration;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(AnimationState.prototype, "currentTime", {
          get: function() {
            return this._timeline._currentTime;
          },
          set: function(value) {
            (value < 0 || value != value) && (value = 0);
            var currentPlayTimes = this._timeline._currentPlayTimes - (this._timeline._isCompleted ? 1 : 0);
            value = value % this._duration + currentPlayTimes * this._duration;
            if (this._time == value) return;
            this._time = value;
            this._timeline.setCurrentTime(this._time);
            this._zOrderTimeline && (this._zOrderTimeline._isCompleted = false);
            for (var i = 0, l = this._boneTimelines.length; i < l; ++i) this._boneTimelines[i]._isCompleted = false;
            for (var i = 0, l = this._slotTimelines.length; i < l; ++i) this._slotTimelines[i]._isCompleted = false;
            for (var i = 0, l = this._ffdTimelines.length; i < l; ++i) this._ffdTimelines[i]._isCompleted = false;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(AnimationState.prototype, "clip", {
          get: function() {
            return this._animationData;
          },
          enumerable: true,
          configurable: true
        });
        AnimationState.stateActionEnabled = true;
        return AnimationState;
      })(dragonBones.BaseObject);
      dragonBones.AnimationState = AnimationState;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var AnimationTimelineState = (function(_super) {
        __extends(AnimationTimelineState, _super);
        function AnimationTimelineState() {
          _super.call(this);
        }
        AnimationTimelineState.toString = function() {
          return "[class dragonBones.AnimationTimelineState]";
        };
        AnimationTimelineState.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          this._isStarted = false;
        };
        AnimationTimelineState.prototype._onCrossFrame = function(frame) {
          var self = this;
          if (self._animationState._fadeState < 0) return;
          if (self._animationState.actionEnabled) {
            var actions = frame.actions;
            for (var i = 0, l = actions.length; i < l; ++i) self._armature._bufferAction(actions[i]);
          }
          var eventDispatcher = self._armature._display;
          var events = frame.events;
          for (var i = 0, l = events.length; i < l; ++i) {
            var eventData = events[i];
            var eventType = "";
            switch (eventData.type) {
             case 10:
              eventType = dragonBones.EventObject.FRAME_EVENT;
              break;

             case 11:
              eventType = dragonBones.EventObject.SOUND_EVENT;
            }
            if ((11 == eventData.type ? self._armature._eventManager : eventDispatcher).hasEvent(eventType)) {
              var eventObject = dragonBones.BaseObject.borrowObject(dragonBones.EventObject);
              eventObject.name = eventData.name;
              eventObject.animationState = self._animationState;
              eventObject.frame = frame;
              eventObject.data = eventData;
              eventData.bone && (eventObject.bone = self._armature.getBone(eventData.bone.name));
              eventData.slot && (eventObject.slot = self._armature.getSlot(eventData.slot.name));
              self._armature._bufferEvent(eventObject, eventType);
            }
          }
        };
        AnimationTimelineState.prototype.fadeIn = function(armature, animationState, timelineData, time) {
          _super.prototype.fadeIn.call(this, armature, animationState, timelineData, time);
          this._currentTime = time;
        };
        AnimationTimelineState.prototype.update = function(time) {
          var self = this;
          var prevTime = self._currentTime;
          var prevPlayTimes = self._currentPlayTimes;
          if (!self._isCompleted && self._setCurrentTime(time)) {
            var eventDispatcher = self._armature._display;
            if (!self._isStarted) {
              self._isStarted = true;
              if (eventDispatcher.hasEvent(dragonBones.EventObject.START)) {
                var eventObject = dragonBones.BaseObject.borrowObject(dragonBones.EventObject);
                eventObject.animationState = self._animationState;
                self._armature._bufferEvent(eventObject, dragonBones.EventObject.START);
              }
            }
            if (self._keyFrameCount > 0) {
              var currentFrameIndex = self._keyFrameCount > 1 ? Math.floor(self._currentTime * self._frameRate) : 0;
              var currentFrame = self._timeline.frames[currentFrameIndex];
              if (self._currentFrame != currentFrame) if (self._keyFrameCount > 1) {
                var crossedFrame = self._currentFrame;
                self._currentFrame = currentFrame;
                if (!crossedFrame) {
                  var prevFrameIndex = Math.floor(prevTime * self._frameRate);
                  crossedFrame = self._timeline.frames[prevFrameIndex];
                  self._isReverse || (prevTime <= crossedFrame.position || prevPlayTimes != self._currentPlayTimes) && (crossedFrame = crossedFrame.prev);
                }
                if (self._isReverse) while (crossedFrame != currentFrame) {
                  self._onCrossFrame(crossedFrame);
                  crossedFrame = crossedFrame.prev;
                } else while (crossedFrame != currentFrame) {
                  crossedFrame = crossedFrame.next;
                  self._onCrossFrame(crossedFrame);
                }
              } else {
                self._currentFrame = currentFrame;
                self._onCrossFrame(self._currentFrame);
              }
            }
            if (prevPlayTimes != self._currentPlayTimes) {
              if (eventDispatcher.hasEvent(dragonBones.EventObject.LOOP_COMPLETE)) {
                var eventObject = dragonBones.BaseObject.borrowObject(dragonBones.EventObject);
                eventObject.animationState = self._animationState;
                self._armature._bufferEvent(eventObject, dragonBones.EventObject.LOOP_COMPLETE);
              }
              if (self._isCompleted && eventDispatcher.hasEvent(dragonBones.EventObject.COMPLETE)) {
                var eventObject = dragonBones.BaseObject.borrowObject(dragonBones.EventObject);
                eventObject.animationState = self._animationState;
                self._armature._bufferEvent(eventObject, dragonBones.EventObject.COMPLETE);
              }
              self._currentFrame = null;
            }
          }
        };
        AnimationTimelineState.prototype.setCurrentTime = function(value) {
          this._setCurrentTime(value);
          this._currentFrame = null;
        };
        return AnimationTimelineState;
      })(dragonBones.TimelineState);
      dragonBones.AnimationTimelineState = AnimationTimelineState;
      var ZOrderTimelineState = (function(_super) {
        __extends(ZOrderTimelineState, _super);
        function ZOrderTimelineState() {
          _super.call(this);
        }
        ZOrderTimelineState.toString = function() {
          return "[class dragonBones.ZOrderTimelineState]";
        };
        ZOrderTimelineState.prototype._onArriveAtFrame = function(isUpdate) {
          var self = this;
          _super.prototype._onArriveAtFrame.call(this, isUpdate);
          self._armature._sortZOrder(self._currentFrame.zOrder);
        };
        return ZOrderTimelineState;
      })(dragonBones.TimelineState);
      dragonBones.ZOrderTimelineState = ZOrderTimelineState;
      var BoneTimelineState = (function(_super) {
        __extends(BoneTimelineState, _super);
        function BoneTimelineState() {
          _super.call(this);
          this._transform = new dragonBones.Transform();
          this._currentTransform = new dragonBones.Transform();
          this._durationTransform = new dragonBones.Transform();
        }
        BoneTimelineState.toString = function() {
          return "[class dragonBones.BoneTimelineState]";
        };
        BoneTimelineState.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          this.bone = null;
          this._tweenTransform = 0;
          this._tweenRotate = 0;
          this._tweenScale = 0;
          this._boneTransform = null;
          this._originalTransform = null;
          this._transform.identity();
          this._currentTransform.identity();
          this._durationTransform.identity();
        };
        BoneTimelineState.prototype._onArriveAtFrame = function(isUpdate) {
          var self = this;
          _super.prototype._onArriveAtFrame.call(this, isUpdate);
          self._currentTransform.copyFrom(self._currentFrame.transform);
          self._tweenTransform = 1;
          self._tweenRotate = 1;
          self._tweenScale = 1;
          if (self._keyFrameCount > 1 && (self._tweenEasing != dragonBones.DragonBones.NO_TWEEN || self._curve)) {
            var nextFrame = self._currentFrame.next;
            var nextTransform = nextFrame.transform;
            self._durationTransform.x = nextTransform.x - self._currentTransform.x;
            self._durationTransform.y = nextTransform.y - self._currentTransform.y;
            0 == self._durationTransform.x && 0 == self._durationTransform.y || (self._tweenTransform = 2);
            var tweenRotate = self._currentFrame.tweenRotate;
            if (tweenRotate == tweenRotate) {
              if (tweenRotate) if (tweenRotate > 0 ? nextTransform.skewY >= self._currentTransform.skewY : nextTransform.skewY <= self._currentTransform.skewY) {
                var rotate = tweenRotate > 0 ? tweenRotate - 1 : tweenRotate + 1;
                self._durationTransform.skewX = nextTransform.skewX - self._currentTransform.skewX + dragonBones.DragonBones.PI_D * rotate;
                self._durationTransform.skewY = nextTransform.skewY - self._currentTransform.skewY + dragonBones.DragonBones.PI_D * rotate;
              } else {
                self._durationTransform.skewX = nextTransform.skewX - self._currentTransform.skewX + dragonBones.DragonBones.PI_D * tweenRotate;
                self._durationTransform.skewY = nextTransform.skewY - self._currentTransform.skewY + dragonBones.DragonBones.PI_D * tweenRotate;
              } else {
                self._durationTransform.skewX = dragonBones.Transform.normalizeRadian(nextTransform.skewX - self._currentTransform.skewX);
                self._durationTransform.skewY = dragonBones.Transform.normalizeRadian(nextTransform.skewY - self._currentTransform.skewY);
              }
              0 == self._durationTransform.skewX && 0 == self._durationTransform.skewY || (self._tweenRotate = 2);
            } else {
              self._durationTransform.skewX = 0;
              self._durationTransform.skewY = 0;
            }
            if (self._currentFrame.tweenScale) {
              self._durationTransform.scaleX = nextTransform.scaleX - self._currentTransform.scaleX;
              self._durationTransform.scaleY = nextTransform.scaleY - self._currentTransform.scaleY;
              0 == self._durationTransform.scaleX && 0 == self._durationTransform.scaleY || (self._tweenScale = 2);
            } else {
              self._durationTransform.scaleX = 0;
              self._durationTransform.scaleY = 0;
            }
          } else {
            self._durationTransform.x = 0;
            self._durationTransform.y = 0;
            self._durationTransform.skewX = 0;
            self._durationTransform.skewY = 0;
            self._durationTransform.scaleX = 0;
            self._durationTransform.scaleY = 0;
          }
        };
        BoneTimelineState.prototype._onUpdateFrame = function(isUpdate) {
          var self = this;
          if (self._tweenTransform || self._tweenRotate || self._tweenScale) {
            _super.prototype._onUpdateFrame.call(this, isUpdate);
            var tweenProgress = 0;
            if (self._tweenTransform) {
              if (1 == self._tweenTransform) {
                self._tweenTransform = 0;
                tweenProgress = 0;
              } else tweenProgress = self._tweenProgress;
              if (self._animationState.additiveBlending) {
                self._transform.x = self._currentTransform.x + self._durationTransform.x * tweenProgress;
                self._transform.y = self._currentTransform.y + self._durationTransform.y * tweenProgress;
              } else {
                self._transform.x = self._originalTransform.x + self._currentTransform.x + self._durationTransform.x * tweenProgress;
                self._transform.y = self._originalTransform.y + self._currentTransform.y + self._durationTransform.y * tweenProgress;
              }
            }
            if (self._tweenRotate) {
              if (1 == self._tweenRotate) {
                self._tweenRotate = 0;
                tweenProgress = 0;
              } else tweenProgress = self._tweenProgress;
              if (self._animationState.additiveBlending) {
                self._transform.skewX = self._currentTransform.skewX + self._durationTransform.skewX * tweenProgress;
                self._transform.skewY = self._currentTransform.skewY + self._durationTransform.skewY * tweenProgress;
              } else {
                self._transform.skewX = self._originalTransform.skewX + self._currentTransform.skewX + self._durationTransform.skewX * tweenProgress;
                self._transform.skewY = self._originalTransform.skewY + self._currentTransform.skewY + self._durationTransform.skewY * tweenProgress;
              }
            }
            if (self._tweenScale) {
              if (1 == self._tweenScale) {
                self._tweenScale = 0;
                tweenProgress = 0;
              } else tweenProgress = self._tweenProgress;
              if (self._animationState.additiveBlending) {
                self._transform.scaleX = self._currentTransform.scaleX + self._durationTransform.scaleX * tweenProgress;
                self._transform.scaleY = self._currentTransform.scaleY + self._durationTransform.scaleY * tweenProgress;
              } else {
                self._transform.scaleX = self._originalTransform.scaleX * (self._currentTransform.scaleX + self._durationTransform.scaleX * tweenProgress);
                self._transform.scaleY = self._originalTransform.scaleY * (self._currentTransform.scaleY + self._durationTransform.scaleY * tweenProgress);
              }
            }
            self.bone.invalidUpdate();
          }
        };
        BoneTimelineState.prototype.fadeIn = function(armature, animationState, timelineData, time) {
          _super.prototype.fadeIn.call(this, armature, animationState, timelineData, time);
          this._originalTransform = this._timeline.originalTransform;
          this._boneTransform = this.bone._animationPose;
        };
        BoneTimelineState.prototype.fadeOut = function() {
          this._transform.skewX = dragonBones.Transform.normalizeRadian(this._transform.skewX);
          this._transform.skewY = dragonBones.Transform.normalizeRadian(this._transform.skewY);
        };
        BoneTimelineState.prototype.update = function(time) {
          var self = this;
          _super.prototype.update.call(this, time);
          var weight = self._animationState._weightResult;
          if (weight > 0) {
            if (0 == self.bone._blendIndex) {
              self._boneTransform.x = self._transform.x * weight;
              self._boneTransform.y = self._transform.y * weight;
              self._boneTransform.skewX = self._transform.skewX * weight;
              self._boneTransform.skewY = self._transform.skewY * weight;
              self._boneTransform.scaleX = (self._transform.scaleX - 1) * weight + 1;
              self._boneTransform.scaleY = (self._transform.scaleY - 1) * weight + 1;
            } else {
              self._boneTransform.x += self._transform.x * weight;
              self._boneTransform.y += self._transform.y * weight;
              self._boneTransform.skewX += self._transform.skewX * weight;
              self._boneTransform.skewY += self._transform.skewY * weight;
              self._boneTransform.scaleX += (self._transform.scaleX - 1) * weight;
              self._boneTransform.scaleY += (self._transform.scaleY - 1) * weight;
            }
            self.bone._blendIndex++;
            0 != self._animationState._fadeState && self.bone.invalidUpdate();
          }
        };
        return BoneTimelineState;
      })(dragonBones.TweenTimelineState);
      dragonBones.BoneTimelineState = BoneTimelineState;
      var SlotTimelineState = (function(_super) {
        __extends(SlotTimelineState, _super);
        function SlotTimelineState() {
          _super.call(this);
          this._color = new dragonBones.ColorTransform();
          this._durationColor = new dragonBones.ColorTransform();
        }
        SlotTimelineState.toString = function() {
          return "[class dragonBones.SlotTimelineState]";
        };
        SlotTimelineState.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          this.slot = null;
          this._colorDirty = false;
          this._tweenColor = 0;
          this._slotColor = null;
          this._color.identity();
          this._durationColor.identity();
        };
        SlotTimelineState.prototype._onArriveAtFrame = function(isUpdate) {
          var self = this;
          _super.prototype._onArriveAtFrame.call(this, isUpdate);
          if (self._animationState._isDisabled(self.slot)) {
            self._tweenEasing = dragonBones.DragonBones.NO_TWEEN;
            self._curve = null;
            self._tweenColor = 0;
            return;
          }
          if (self._animationState._fadeState >= 0) {
            self.slot._setDisplayIndex(self._currentFrame.displayIndex);
            self.slot._updateMeshData(true);
          }
          self._tweenColor = 0;
          var currentColor = self._currentFrame.color;
          if (self._keyFrameCount > 1 && (self._tweenEasing != dragonBones.DragonBones.NO_TWEEN || self._curve)) {
            var nextFrame = self._currentFrame.next;
            var nextColor = nextFrame.color;
            if (currentColor != nextColor && nextFrame.displayIndex >= 0) {
              self._durationColor.alphaMultiplier = nextColor.alphaMultiplier - currentColor.alphaMultiplier;
              self._durationColor.redMultiplier = nextColor.redMultiplier - currentColor.redMultiplier;
              self._durationColor.greenMultiplier = nextColor.greenMultiplier - currentColor.greenMultiplier;
              self._durationColor.blueMultiplier = nextColor.blueMultiplier - currentColor.blueMultiplier;
              self._durationColor.alphaOffset = nextColor.alphaOffset - currentColor.alphaOffset;
              self._durationColor.redOffset = nextColor.redOffset - currentColor.redOffset;
              self._durationColor.greenOffset = nextColor.greenOffset - currentColor.greenOffset;
              self._durationColor.blueOffset = nextColor.blueOffset - currentColor.blueOffset;
              0 == self._durationColor.alphaMultiplier && 0 == self._durationColor.redMultiplier && 0 == self._durationColor.greenMultiplier && 0 == self._durationColor.blueMultiplier && 0 == self._durationColor.alphaOffset && 0 == self._durationColor.redOffset && 0 == self._durationColor.greenOffset && 0 == self._durationColor.blueOffset || (self._tweenColor = 2);
            }
          }
          0 == self._tweenColor && (self._slotColor.alphaMultiplier == currentColor.alphaMultiplier && self._slotColor.redMultiplier == currentColor.redMultiplier && self._slotColor.greenMultiplier == currentColor.greenMultiplier && self._slotColor.blueMultiplier == currentColor.blueMultiplier && self._slotColor.alphaOffset == currentColor.alphaOffset && self._slotColor.redOffset == currentColor.redOffset && self._slotColor.greenOffset == currentColor.greenOffset && self._slotColor.blueOffset == currentColor.blueOffset || (self._tweenColor = 1));
        };
        SlotTimelineState.prototype._onUpdateFrame = function(isUpdate) {
          var self = this;
          _super.prototype._onUpdateFrame.call(this, isUpdate);
          var tweenProgress = 0;
          if (self._tweenColor) {
            if (1 == self._tweenColor) {
              self._tweenColor = 0;
              tweenProgress = 0;
            } else tweenProgress = self._tweenProgress;
            var currentColor = self._currentFrame.color;
            self._color.alphaMultiplier = currentColor.alphaMultiplier + self._durationColor.alphaMultiplier * tweenProgress;
            self._color.redMultiplier = currentColor.redMultiplier + self._durationColor.redMultiplier * tweenProgress;
            self._color.greenMultiplier = currentColor.greenMultiplier + self._durationColor.greenMultiplier * tweenProgress;
            self._color.blueMultiplier = currentColor.blueMultiplier + self._durationColor.blueMultiplier * tweenProgress;
            self._color.alphaOffset = currentColor.alphaOffset + self._durationColor.alphaOffset * tweenProgress;
            self._color.redOffset = currentColor.redOffset + self._durationColor.redOffset * tweenProgress;
            self._color.greenOffset = currentColor.greenOffset + self._durationColor.greenOffset * tweenProgress;
            self._color.blueOffset = currentColor.blueOffset + self._durationColor.blueOffset * tweenProgress;
            self._colorDirty = true;
          }
        };
        SlotTimelineState.prototype.fadeIn = function(armature, animationState, timelineData, time) {
          _super.prototype.fadeIn.call(this, armature, animationState, timelineData, time);
          this._slotColor = this.slot._colorTransform;
        };
        SlotTimelineState.prototype.fadeOut = function() {
          this._tweenColor = 0;
        };
        SlotTimelineState.prototype.update = function(time) {
          var self = this;
          _super.prototype.update.call(this, time);
          if (0 != self._tweenColor || self._colorDirty) {
            var weight = self._animationState._weightResult;
            if (weight > 0) if (0 != self._animationState._fadeState) {
              var fadeProgress = Math.pow(self._animationState._fadeProgress, 4);
              self._slotColor.alphaMultiplier += (self._color.alphaMultiplier - self._slotColor.alphaMultiplier) * fadeProgress;
              self._slotColor.redMultiplier += (self._color.redMultiplier - self._slotColor.redMultiplier) * fadeProgress;
              self._slotColor.greenMultiplier += (self._color.greenMultiplier - self._slotColor.greenMultiplier) * fadeProgress;
              self._slotColor.blueMultiplier += (self._color.blueMultiplier - self._slotColor.blueMultiplier) * fadeProgress;
              self._slotColor.alphaOffset += (self._color.alphaOffset - self._slotColor.alphaOffset) * fadeProgress;
              self._slotColor.redOffset += (self._color.redOffset - self._slotColor.redOffset) * fadeProgress;
              self._slotColor.greenOffset += (self._color.greenOffset - self._slotColor.greenOffset) * fadeProgress;
              self._slotColor.blueOffset += (self._color.blueOffset - self._slotColor.blueOffset) * fadeProgress;
              self.slot._colorDirty = true;
            } else if (self._colorDirty) {
              self._colorDirty = false;
              self._slotColor.alphaMultiplier = self._color.alphaMultiplier;
              self._slotColor.redMultiplier = self._color.redMultiplier;
              self._slotColor.greenMultiplier = self._color.greenMultiplier;
              self._slotColor.blueMultiplier = self._color.blueMultiplier;
              self._slotColor.alphaOffset = self._color.alphaOffset;
              self._slotColor.redOffset = self._color.redOffset;
              self._slotColor.greenOffset = self._color.greenOffset;
              self._slotColor.blueOffset = self._color.blueOffset;
              self.slot._colorDirty = true;
            }
          }
        };
        return SlotTimelineState;
      })(dragonBones.TweenTimelineState);
      dragonBones.SlotTimelineState = SlotTimelineState;
      var FFDTimelineState = (function(_super) {
        __extends(FFDTimelineState, _super);
        function FFDTimelineState() {
          _super.call(this);
          this._ffdVertices = [];
        }
        FFDTimelineState.toString = function() {
          return "[class dragonBones.FFDTimelineState]";
        };
        FFDTimelineState.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          this.slot = null;
          this._tweenFFD = 0;
          this._slotFFDVertices = null;
          if (this._durationFFDFrame) {
            this._durationFFDFrame.returnToPool();
            this._durationFFDFrame = null;
          }
          this._ffdVertices.length = 0;
        };
        FFDTimelineState.prototype._onArriveAtFrame = function(isUpdate) {
          var self = this;
          _super.prototype._onArriveAtFrame.call(this, isUpdate);
          self._tweenFFD = 0;
          (self._tweenEasing != dragonBones.DragonBones.NO_TWEEN || self._curve) && (self._tweenFFD = self._updateExtensionKeyFrame(self._currentFrame, self._currentFrame.next, self._durationFFDFrame));
          if (0 == self._tweenFFD) {
            var currentFFDVertices = self._currentFrame.tweens;
            for (var i = 0, l = currentFFDVertices.length; i < l; ++i) if (self._slotFFDVertices[i] != currentFFDVertices[i]) {
              self._tweenFFD = 1;
              break;
            }
          }
        };
        FFDTimelineState.prototype._onUpdateFrame = function(isUpdate) {
          var self = this;
          _super.prototype._onUpdateFrame.call(this, isUpdate);
          var tweenProgress = 0;
          if (0 != self._tweenFFD) {
            if (1 == self._tweenFFD) {
              self._tweenFFD = 0;
              tweenProgress = 0;
            } else tweenProgress = self._tweenProgress;
            var currentFFDVertices = self._currentFrame.tweens;
            var nextFFDVertices = self._durationFFDFrame.tweens;
            for (var i = 0, l = currentFFDVertices.length; i < l; ++i) self._ffdVertices[i] = currentFFDVertices[i] + nextFFDVertices[i] * tweenProgress;
            self.slot._ffdDirty = true;
          }
        };
        FFDTimelineState.prototype.fadeIn = function(armature, animationState, timelineData, time) {
          _super.prototype.fadeIn.call(this, armature, animationState, timelineData, time);
          this._slotFFDVertices = this.slot._ffdVertices;
          this._durationFFDFrame = dragonBones.BaseObject.borrowObject(dragonBones.ExtensionFrameData);
          this._durationFFDFrame.tweens.length = this._slotFFDVertices.length;
          this._ffdVertices.length = this._slotFFDVertices.length;
          for (var i = 0, l = this._durationFFDFrame.tweens.length; i < l; ++i) this._durationFFDFrame.tweens[i] = 0;
          for (var i = 0, l = this._ffdVertices.length; i < l; ++i) this._ffdVertices[i] = 0;
        };
        FFDTimelineState.prototype.update = function(time) {
          var self = this;
          _super.prototype.update.call(this, time);
          var weight = self._animationState._weightResult;
          if (weight > 0) {
            if (0 == self.slot._blendIndex) for (var i = 0, l = self._ffdVertices.length; i < l; ++i) self._slotFFDVertices[i] = self._ffdVertices[i] * weight; else for (var i = 0, l = self._ffdVertices.length; i < l; ++i) self._slotFFDVertices[i] += self._ffdVertices[i] * weight;
            self.slot._blendIndex++;
            0 != self._animationState._fadeState && (self.slot._ffdDirty = true);
          }
        };
        return FFDTimelineState;
      })(dragonBones.TweenTimelineState);
      dragonBones.FFDTimelineState = FFDTimelineState;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var WorldClock = (function() {
        function WorldClock() {
          this.time = new Date().getTime() / dragonBones.DragonBones.SECOND_TO_MILLISECOND;
          this.timeScale = 1;
          this._animatebles = [];
        }
        Object.defineProperty(WorldClock, "clock", {
          get: function() {
            WorldClock._clock || (WorldClock._clock = new WorldClock());
            return WorldClock._clock;
          },
          enumerable: true,
          configurable: true
        });
        WorldClock.prototype.advanceTime = function(passedTime) {
          passedTime != passedTime && (passedTime = 0);
          passedTime < 0 && (passedTime = new Date().getTime() / dragonBones.DragonBones.SECOND_TO_MILLISECOND - this.time);
          passedTime *= this.timeScale;
          passedTime < 0 ? this.time -= passedTime : this.time += passedTime;
          if (passedTime) {
            var i = 0, r = 0, l = this._animatebles.length;
            for (;i < l; ++i) {
              var animateble = this._animatebles[i];
              if (animateble) {
                if (r > 0) {
                  this._animatebles[i - r] = animateble;
                  this._animatebles[i] = null;
                }
                animateble.advanceTime(passedTime);
              } else r++;
            }
            if (r > 0) {
              l = this._animatebles.length;
              for (;i < l; ++i) {
                var animateble = this._animatebles[i];
                animateble ? this._animatebles[i - r] = animateble : r++;
              }
              this._animatebles.length -= r;
            }
          }
        };
        WorldClock.prototype.contains = function(value) {
          return this._animatebles.indexOf(value) >= 0;
        };
        WorldClock.prototype.add = function(value) {
          if (value && this._animatebles.indexOf(value) < 0) {
            this._animatebles.push(value);
            dragonBones.DragonBones.debug && value instanceof dragonBones.Armature && dragonBones.DragonBones.addArmature(value);
          }
        };
        WorldClock.prototype.remove = function(value) {
          var index = this._animatebles.indexOf(value);
          if (index >= 0) {
            this._animatebles[index] = null;
            dragonBones.DragonBones.debug && value instanceof dragonBones.Armature && dragonBones.DragonBones.removeArmature(value);
          }
        };
        WorldClock.prototype.clear = function() {
          for (var i = 0, l = this._animatebles.length; i < l; ++i) this._animatebles[i] = null;
        };
        WorldClock._clock = null;
        return WorldClock;
      })();
      dragonBones.WorldClock = WorldClock;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var TransformObject = (function(_super) {
        __extends(TransformObject, _super);
        function TransformObject() {
          _super.call(this);
          this.global = new dragonBones.Transform();
          this.origin = new dragonBones.Transform();
          this.offset = new dragonBones.Transform();
          this._globalTransformMatrix = new dragonBones.Matrix();
        }
        TransformObject.prototype._onClear = function() {
          this.userData = null;
          this.name = null;
          this.globalTransformMatrix = this._globalTransformMatrix;
          this.global.identity();
          this.origin.identity();
          this.offset.identity();
          this._armature = null;
          this._parent = null;
          this._globalTransformMatrix.identity();
        };
        TransformObject.prototype._setArmature = function(value) {
          this._armature = value;
        };
        TransformObject.prototype._setParent = function(value) {
          this._parent = value;
        };
        Object.defineProperty(TransformObject.prototype, "armature", {
          get: function() {
            return this._armature;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(TransformObject.prototype, "parent", {
          get: function() {
            return this._parent;
          },
          enumerable: true,
          configurable: true
        });
        return TransformObject;
      })(dragonBones.BaseObject);
      dragonBones.TransformObject = TransformObject;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var Armature = (function(_super) {
        __extends(Armature, _super);
        function Armature() {
          _super.call(this);
          this._bones = [];
          this._slots = [];
          this._actions = [];
          this._events = [];
          this.enableCache = false;
        }
        Armature.toString = function() {
          return "[class dragonBones.Armature]";
        };
        Armature._onSortSlots = function(a, b) {
          return a._zOrder > b._zOrder ? 1 : -1;
        };
        Armature.prototype._onClear = function() {
          for (var i = 0, l = this._bones.length; i < l; ++i) this._bones[i].returnToPool();
          for (var i = 0, l = this._slots.length; i < l; ++i) this._slots[i].returnToPool();
          for (var i = 0, l = this._events.length; i < l; ++i) this._events[i].returnToPool();
          this._animation && this._animation.returnToPool();
          this._display && this._display._onClear();
          this.userData = null;
          this._cacheFrameIndex = -1;
          this._armatureData = null;
          this._skinData = null;
          this._animation = null;
          this._display = null;
          this._parent = null;
          this._eventManager = null;
          this._delayDispose = false;
          this._lockDispose = false;
          this._debugDraw = false;
          this._bonesDirty = false;
          this._slotsDirty = false;
          this._replacedTexture = null;
          this._bones.length = 0;
          this._slots.length = 0;
          this._actions.length = 0;
          this._events.length = 0;
        };
        Armature.prototype._sortBones = function() {
          var total = this._bones.length;
          if (total <= 0) return;
          var sortHelper = this._bones.concat();
          var index = 0;
          var count = 0;
          this._bones.length = 0;
          while (count < total) {
            var bone = sortHelper[index++];
            index >= total && (index = 0);
            if (this._bones.indexOf(bone) >= 0) continue;
            if (bone.parent && this._bones.indexOf(bone.parent) < 0) continue;
            if (bone.ik && this._bones.indexOf(bone.ik) < 0) continue;
            bone.ik && bone.ikChain > 0 && bone.ikChainIndex == bone.ikChain ? this._bones.splice(this._bones.indexOf(bone.parent) + 1, 0, bone) : this._bones.push(bone);
            count++;
          }
        };
        Armature.prototype._sortSlots = function() {
          this._slots.sort(Armature._onSortSlots);
        };
        Armature.prototype._doAction = function(value) {
          switch (value.type) {
           case 0:
            this._animation.play(value.data[0], value.data[1]);
            break;

           case 1:
            this._animation.stop(value.data[0]);
            break;

           case 2:
            this._animation.gotoAndPlayByTime(value.data[0], value.data[1], value.data[2]);
            break;

           case 3:
            this._animation.gotoAndStopByTime(value.data[0], value.data[1]);
            break;

           case 4:
            this._animation.fadeIn(value.data[0], value.data[1], value.data[2]);
          }
        };
        Armature.prototype._addBoneToBoneList = function(value) {
          if (this._bones.indexOf(value) < 0) {
            this._bonesDirty = true;
            this._bones.push(value);
          }
        };
        Armature.prototype._removeBoneFromBoneList = function(value) {
          var index = this._bones.indexOf(value);
          index >= 0 && this._bones.splice(index, 1);
        };
        Armature.prototype._addSlotToSlotList = function(value) {
          if (this._slots.indexOf(value) < 0) {
            this._slotsDirty = true;
            this._slots.push(value);
          }
        };
        Armature.prototype._removeSlotFromSlotList = function(value) {
          var index = this._slots.indexOf(value);
          index >= 0 && this._slots.splice(index, 1);
        };
        Armature.prototype._sortZOrder = function(slotIndices) {
          var sortedSlots = this._armatureData.sortedSlots;
          var isOriginal = slotIndices.length < 1;
          for (var i = 0, l = sortedSlots.length; i < l; ++i) {
            var slotIndex = isOriginal ? i : slotIndices[i];
            var slotData = sortedSlots[slotIndex];
            var slot = this.getSlot(slotData.name);
            slot && slot._setZorder(i);
          }
          this._slotsDirty = true;
        };
        Armature.prototype._bufferAction = function(value) {
          this._actions.push(value);
        };
        Armature.prototype._bufferEvent = function(value, type) {
          value.type = type;
          value.armature = this;
          this._events.push(value);
        };
        Armature.prototype.dispose = function() {
          this._delayDispose = true;
          !this._lockDispose && this._animation && this.returnToPool();
        };
        Armature.prototype.advanceTime = function(passedTime) {
          var self = this;
          if (!self._animation) throw new Error("The armature has been disposed.");
          var scaledPassedTime = passedTime * self._animation.timeScale;
          self._animation._advanceTime(scaledPassedTime);
          if (self._bonesDirty) {
            self._bonesDirty = false;
            self._sortBones();
          }
          if (self._slotsDirty) {
            self._slotsDirty = false;
            self._sortSlots();
          }
          for (var i = 0, l = self._bones.length; i < l; ++i) self._bones[i]._update(self._cacheFrameIndex);
          for (var i = 0, l = self._slots.length; i < l; ++i) {
            var slot = self._slots[i];
            slot._update(self._cacheFrameIndex);
            var childArmature = slot._childArmature;
            childArmature && (slot.inheritAnimation ? childArmature.advanceTime(scaledPassedTime) : childArmature.advanceTime(passedTime));
          }
          if (dragonBones.DragonBones.debugDraw || self._debugDraw) {
            self._debugDraw = dragonBones.DragonBones.debugDraw;
            self._display._debugDraw(self._debugDraw);
          }
          if (!self._lockDispose) {
            self._lockDispose = true;
            if (self._events.length > 0) {
              for (var i = 0, l = self._events.length; i < l; ++i) {
                var event_5 = self._events[i];
                event_5.type == dragonBones.EventObject.SOUND_EVENT ? this._eventManager._dispatchEvent(event_5) : self._display._dispatchEvent(event_5);
                event_5.returnToPool();
              }
              self._events.length = 0;
            }
            if (self._actions.length > 0) {
              for (var i = 0, l = self._actions.length; i < l; ++i) {
                var action = self._actions[i];
                if (action.slot) {
                  var slot = self.getSlot(action.slot.name);
                  if (slot) {
                    var childArmature = slot._childArmature;
                    childArmature && childArmature._doAction(action);
                  }
                } else if (action.bone) for (var i_1 = 0, l_1 = self._slots.length; i_1 < l_1; ++i_1) {
                  var childArmature = self._slots[i_1]._childArmature;
                  childArmature && childArmature._doAction(action);
                } else this._doAction(action);
              }
              self._actions.length = 0;
            }
            self._lockDispose = false;
          }
          self._delayDispose && self.returnToPool();
        };
        Armature.prototype.containsPoint = function(x, y, color) {
          void 0 === color && (color = 0);
          for (var i = 0, l = this._slots.length; i < l; ++i) {
            var slot = this._slots[i];
            if (slot.containsPoint(x, y, color)) return slot;
          }
          return null;
        };
        Armature.prototype.intersectsSegment = function(xA, yA, xB, yB, color, intersectionPointA, intersectionPointB, normalRadians) {
          void 0 === color && (color = 0);
          void 0 === intersectionPointA && (intersectionPointA = null);
          void 0 === intersectionPointB && (intersectionPointB = null);
          void 0 === normalRadians && (normalRadians = null);
          var isV = xA == xB;
          var dMin = 0;
          var dMax = 0;
          var intXA = 0;
          var intYA = 0;
          var intXB = 0;
          var intYB = 0;
          var intAN = 0;
          var intBN = 0;
          var intSlotA = null;
          var intSlotB = null;
          for (var i = 0, l = this._slots.length; i < l; ++i) {
            var slot = this._slots[i];
            var intersectionCount = slot.intersectsSegment(xA, yA, xB, yB, color, intersectionPointA, intersectionPointB, normalRadians);
            if (intersectionCount > 0) {
              if (!intersectionPointA && !intersectionPointB) {
                intSlotA = slot;
                break;
              }
              if (intersectionPointA) {
                var d = isV ? intersectionPointA.y - yA : intersectionPointA.x - xA;
                d < 0 && (d = -d);
                if (!intSlotA || d < dMin) {
                  dMin = d;
                  intXA = intersectionPointA.x;
                  intYA = intersectionPointA.y;
                  intSlotA = slot;
                  normalRadians && (intAN = normalRadians.x);
                }
              }
              if (intersectionPointB) {
                var d = intersectionPointB.x - xA;
                d < 0 && (d = -d);
                if (!intSlotB || d > dMax) {
                  dMax = d;
                  intXB = intersectionPointB.x;
                  intYB = intersectionPointB.y;
                  intSlotB = slot;
                  normalRadians && (intBN = normalRadians.y);
                }
              }
            }
          }
          if (intSlotA && intersectionPointA) {
            intersectionPointA.x = intXA;
            intersectionPointA.y = intYA;
            normalRadians && (normalRadians.x = intAN);
          }
          if (intSlotB && intersectionPointB) {
            intersectionPointB.x = intXB;
            intersectionPointB.y = intYB;
            normalRadians && (normalRadians.y = intBN);
          }
          return intSlotA;
        };
        Armature.prototype.invalidUpdate = function(boneName, updateSlotDisplay) {
          void 0 === boneName && (boneName = null);
          void 0 === updateSlotDisplay && (updateSlotDisplay = false);
          if (boneName) {
            var bone = this.getBone(boneName);
            if (bone) {
              bone.invalidUpdate();
              if (updateSlotDisplay) for (var i = 0, l = this._slots.length; i < l; ++i) {
                var slot = this._slots[i];
                slot.parent == bone && slot.invalidUpdate();
              }
            }
          } else {
            for (var i = 0, l = this._bones.length; i < l; ++i) this._bones[i].invalidUpdate();
            if (updateSlotDisplay) for (var i = 0, l = this._slots.length; i < l; ++i) this._slots[i].invalidUpdate();
          }
        };
        Armature.prototype.getBone = function(name) {
          for (var i = 0, l = this._bones.length; i < l; ++i) {
            var bone = this._bones[i];
            if (bone.name == name) return bone;
          }
          return null;
        };
        Armature.prototype.getBoneByDisplay = function(display) {
          var slot = this.getSlotByDisplay(display);
          return slot ? slot.parent : null;
        };
        Armature.prototype.getSlot = function(name) {
          for (var i = 0, l = this._slots.length; i < l; ++i) {
            var slot = this._slots[i];
            if (slot.name == name) return slot;
          }
          return null;
        };
        Armature.prototype.getSlotByDisplay = function(display) {
          if (display) for (var i = 0, l = this._slots.length; i < l; ++i) {
            var slot = this._slots[i];
            if (slot.display == display) return slot;
          }
          return null;
        };
        Armature.prototype.replaceTexture = function(texture) {
          this.replacedTexture = texture;
        };
        Armature.prototype.getBones = function() {
          return this._bones;
        };
        Armature.prototype.getSlots = function() {
          return this._slots;
        };
        Object.defineProperty(Armature.prototype, "name", {
          get: function() {
            return this._armatureData ? this._armatureData.name : null;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Armature.prototype, "armatureData", {
          get: function() {
            return this._armatureData;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Armature.prototype, "animation", {
          get: function() {
            return this._animation;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Armature.prototype, "display", {
          get: function() {
            return this._display;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Armature.prototype, "parent", {
          get: function() {
            return this._parent;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Armature.prototype, "cacheFrameRate", {
          get: function() {
            return this._armatureData.cacheFrameRate;
          },
          set: function(value) {
            if (this._armatureData.cacheFrameRate != value) {
              this._armatureData.cacheFrames(value);
              for (var i = 0, l = this._slots.length; i < l; ++i) {
                var slot = this._slots[i];
                var childArmature = slot.childArmature;
                childArmature && 0 == childArmature.cacheFrameRate && (childArmature.cacheFrameRate = value);
              }
            }
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Armature.prototype, "replacedTexture", {
          get: function() {
            return this._replacedTexture;
          },
          set: function(value) {
            this._display._onReplaceTexture(value);
            this._replacedTexture = value;
            for (var i = 0, l = this._slots.length; i < l; ++i) this._slots[i].invalidUpdate();
          },
          enumerable: true,
          configurable: true
        });
        Armature.prototype.enableAnimationCache = function(frameRate) {
          this.cacheFrameRate = frameRate;
        };
        Armature.prototype.hasEventListener = function(type) {
          return this._display.hasEvent(type);
        };
        Armature.prototype.addEventListener = function(type, listener, target) {
          this._display.addEvent(type, listener, target);
        };
        Armature.prototype.removeEventListener = function(type, listener, target) {
          this._display.removeEvent(type, listener, target);
        };
        Armature.prototype.addBone = function(value, parentName) {
          void 0 === parentName && (parentName = null);
          if (!value) throw new Error();
          value._setArmature(this);
          value._setParent(parentName ? this.getBone(parentName) : null);
        };
        Armature.prototype.addSlot = function(value, parentName) {
          var bone = this.getBone(parentName);
          if (!bone) throw new Error();
          value._setArmature(this);
          value._setParent(bone);
        };
        Armature.prototype.removeBone = function(value) {
          if (!value || value.armature != this) throw new Error();
          value._setParent(null);
          value._setArmature(null);
        };
        Armature.prototype.removeSlot = function(value) {
          if (!value || value.armature != this) throw new Error();
          value._setParent(null);
          value._setArmature(null);
        };
        Armature.prototype.getDisplay = function() {
          return this._display;
        };
        return Armature;
      })(dragonBones.BaseObject);
      dragonBones.Armature = Armature;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var Bone = (function(_super) {
        __extends(Bone, _super);
        function Bone() {
          _super.call(this);
          this._animationPose = new dragonBones.Transform();
          this._bones = [];
          this._slots = [];
        }
        Bone.toString = function() {
          return "[class dragonBones.Bone]";
        };
        Bone.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          this.inheritTranslation = false;
          this.inheritRotation = false;
          this.inheritScale = false;
          this.ikBendPositive = false;
          this.ikWeight = 0;
          this.length = 0;
          this._transformDirty = 2;
          this._blendIndex = 0;
          this._cacheFrames = null;
          this._animationPose.identity();
          this._visible = true;
          this._ikChain = 0;
          this._ikChainIndex = 0;
          this._ik = null;
          this._bones.length = 0;
          this._slots.length = 0;
        };
        Bone.prototype._updateGlobalTransformMatrix = function() {
          if (this._parent) {
            var parentRotation = this._parent.global.skewY;
            var parentMatrix = this._parent.globalTransformMatrix;
            if (this.inheritScale) {
              if (!this.inheritRotation) {
                this.global.skewX -= parentRotation;
                this.global.skewY -= parentRotation;
              }
              this.global.toMatrix(this.globalTransformMatrix);
              this.globalTransformMatrix.concat(parentMatrix);
              if (!this.inheritTranslation) {
                this.globalTransformMatrix.tx = this.global.x;
                this.globalTransformMatrix.ty = this.global.y;
              }
              this.global.fromMatrix(this.globalTransformMatrix);
            } else {
              if (this.inheritTranslation) {
                var x = this.global.x;
                var y = this.global.y;
                this.global.x = parentMatrix.a * x + parentMatrix.c * y + parentMatrix.tx;
                this.global.y = parentMatrix.d * y + parentMatrix.b * x + parentMatrix.ty;
              }
              if (this.inheritRotation) {
                this.global.skewX += parentRotation;
                this.global.skewY += parentRotation;
              }
              this.global.toMatrix(this.globalTransformMatrix);
            }
          } else this.global.toMatrix(this.globalTransformMatrix);
        };
        Bone.prototype._computeIKA = function() {
          var ikGlobal = this._ik.global;
          var x = this.globalTransformMatrix.a * this.length;
          var y = this.globalTransformMatrix.b * this.length;
          var ikRadian = (Math.atan2(ikGlobal.y - this.global.y, ikGlobal.x - this.global.x) + this.offset.skewY - 2 * this.global.skewY + Math.atan2(y, x)) * this.ikWeight;
          this.global.skewX += ikRadian;
          this.global.skewY += ikRadian;
          this.global.toMatrix(this.globalTransformMatrix);
        };
        Bone.prototype._computeIKB = function() {
          var parentGlobal = this._parent.global;
          var ikGlobal = this._ik.global;
          var x = this.globalTransformMatrix.a * this.length;
          var y = this.globalTransformMatrix.b * this.length;
          var lLL = x * x + y * y;
          var lL = Math.sqrt(lLL);
          var dX = this.global.x - parentGlobal.x;
          var dY = this.global.y - parentGlobal.y;
          var lPP = dX * dX + dY * dY;
          var lP = Math.sqrt(lPP);
          dX = ikGlobal.x - parentGlobal.x;
          dY = ikGlobal.y - parentGlobal.y;
          var lTT = dX * dX + dY * dY;
          var lT = Math.sqrt(lTT);
          var ikRadianA = 0;
          if (lL + lP <= lT || lT + lL <= lP || lT + lP <= lL) {
            ikRadianA = Math.atan2(ikGlobal.y - parentGlobal.y, ikGlobal.x - parentGlobal.x) + this._parent.offset.skewY;
            lL + lP <= lT || lP < lL && (ikRadianA += Math.PI);
          } else {
            var h = (lPP - lLL + lTT) / (2 * 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;
            if (this.ikBendPositive) {
              this.global.x = hX - rX;
              this.global.y = hY - rY;
            } else {
              this.global.x = hX + rX;
              this.global.y = hY + rY;
            }
            ikRadianA = Math.atan2(this.global.y - parentGlobal.y, this.global.x - parentGlobal.x) + this._parent.offset.skewY;
          }
          ikRadianA = (ikRadianA - parentGlobal.skewY) * this.ikWeight;
          parentGlobal.skewX += ikRadianA;
          parentGlobal.skewY += ikRadianA;
          parentGlobal.toMatrix(this._parent.globalTransformMatrix);
          this._parent._transformDirty = 1;
          this.global.x = parentGlobal.x + Math.cos(parentGlobal.skewY) * lP;
          this.global.y = parentGlobal.y + Math.sin(parentGlobal.skewY) * lP;
          var ikRadianB = (Math.atan2(ikGlobal.y - this.global.y, ikGlobal.x - this.global.x) + this.offset.skewY - 2 * this.global.skewY + Math.atan2(y, x)) * this.ikWeight;
          this.global.skewX += ikRadianB;
          this.global.skewY += ikRadianB;
          this.global.toMatrix(this.globalTransformMatrix);
        };
        Bone.prototype._setArmature = function(value) {
          if (this._armature == value) return;
          this._ik = null;
          var oldSlots = null;
          var oldBones = null;
          if (this._armature) {
            oldSlots = this.getSlots();
            oldBones = this.getBones();
            this._armature._removeBoneFromBoneList(this);
          }
          this._armature = value;
          this._armature && this._armature._addBoneToBoneList(this);
          if (oldSlots) for (var i = 0, l = oldSlots.length; i < l; ++i) {
            var slot = oldSlots[i];
            slot.parent == this && slot._setArmature(this._armature);
          }
          if (oldBones) for (var i = 0, l = oldBones.length; i < l; ++i) {
            var bone = oldBones[i];
            bone.parent == this && bone._setArmature(this._armature);
          }
        };
        Bone.prototype._setIK = function(value, chain, chainIndex) {
          if (value) {
            if (chain == chainIndex) {
              var chainEnd = this._parent;
              if (chain && chainEnd) chain = 1; else {
                chain = 0;
                chainIndex = 0;
                chainEnd = this;
              }
              if (chainEnd == value || chainEnd.contains(value)) {
                value = null;
                chain = 0;
                chainIndex = 0;
              } else {
                var ancestor = value;
                while (ancestor.ik && ancestor.ikChain) {
                  if (chainEnd.contains(ancestor.ik)) {
                    value = null;
                    chain = 0;
                    chainIndex = 0;
                    break;
                  }
                  ancestor = ancestor.parent;
                }
              }
            }
          } else {
            chain = 0;
            chainIndex = 0;
          }
          this._ik = value;
          this._ikChain = chain;
          this._ikChainIndex = chainIndex;
          this._armature && (this._armature._bonesDirty = true);
        };
        Bone.prototype._update = function(cacheFrameIndex) {
          var self = this;
          self._blendIndex = 0;
          if (cacheFrameIndex >= 0) {
            var cacheFrame = self._cacheFrames[cacheFrameIndex];
            if (self.globalTransformMatrix == cacheFrame) self._transformDirty = 0; else if (cacheFrame) {
              self._transformDirty = 2;
              self.globalTransformMatrix = cacheFrame;
            } else if (2 == self._transformDirty || self._parent && 0 != self._parent._transformDirty || self._ik && self.ikWeight > 0 && 0 != self._ik._transformDirty) {
              self._transformDirty = 2;
              self.globalTransformMatrix = self._globalTransformMatrix;
            } else if (self.globalTransformMatrix != self._globalTransformMatrix) {
              self._transformDirty = 0;
              self._cacheFrames[cacheFrameIndex] = self.globalTransformMatrix;
            } else {
              self._transformDirty = 2;
              self.globalTransformMatrix = self._globalTransformMatrix;
            }
          } else if (2 == self._transformDirty || self._parent && 0 != self._parent._transformDirty || self._ik && self.ikWeight > 0 && 0 != self._ik._transformDirty) {
            self._transformDirty = 2;
            self.globalTransformMatrix = self._globalTransformMatrix;
          }
          if (0 != self._transformDirty) if (2 == self._transformDirty) {
            self._transformDirty = 1;
            if (self.globalTransformMatrix == self._globalTransformMatrix) {
              self.global.x = self.origin.x + self.offset.x + self._animationPose.x;
              self.global.y = self.origin.y + self.offset.y + self._animationPose.y;
              self.global.skewX = self.origin.skewX + self.offset.skewX + self._animationPose.skewX;
              self.global.skewY = self.origin.skewY + self.offset.skewY + self._animationPose.skewY;
              self.global.scaleX = self.origin.scaleX * self.offset.scaleX * self._animationPose.scaleX;
              self.global.scaleY = self.origin.scaleY * self.offset.scaleY * self._animationPose.scaleY;
              self._updateGlobalTransformMatrix();
              self._ik && self._ikChainIndex == self._ikChain && self.ikWeight > 0 && (self.inheritTranslation && self._ikChain > 0 && self._parent ? self._computeIKB() : self._computeIKA());
              cacheFrameIndex >= 0 && !self._cacheFrames[cacheFrameIndex] && (self.globalTransformMatrix = dragonBones.BoneTimelineData.cacheFrame(self._cacheFrames, cacheFrameIndex, self._globalTransformMatrix));
            }
          } else self._transformDirty = 0;
        };
        Bone.prototype.invalidUpdate = function() {
          this._transformDirty = 2;
        };
        Bone.prototype.contains = function(child) {
          if (child) {
            if (child == this) return false;
            var ancestor = child;
            while (ancestor != this && ancestor) ancestor = ancestor.parent;
            return ancestor == this;
          }
          return false;
        };
        Bone.prototype.getBones = function() {
          this._bones.length = 0;
          var bones = this._armature.getBones();
          for (var i = 0, l = bones.length; i < l; ++i) {
            var bone = bones[i];
            bone.parent == this && this._bones.push(bone);
          }
          return this._bones;
        };
        Bone.prototype.getSlots = function() {
          this._slots.length = 0;
          var slots = this._armature.getSlots();
          for (var i = 0, l = slots.length; i < l; ++i) {
            var slot = slots[i];
            slot.parent == this && this._slots.push(slot);
          }
          return this._slots;
        };
        Object.defineProperty(Bone.prototype, "ikChain", {
          get: function() {
            return this._ikChain;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Bone.prototype, "ikChainIndex", {
          get: function() {
            return this._ikChainIndex;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Bone.prototype, "ik", {
          get: function() {
            return this._ik;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Bone.prototype, "visible", {
          get: function() {
            return this._visible;
          },
          set: function(value) {
            if (this._visible == value) return;
            this._visible = value;
            var slots = this._armature.getSlots();
            for (var i = 0, l = slots.length; i < l; ++i) {
              var slot = slots[i];
              slot._parent == this && slot._updateVisible();
            }
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Bone.prototype, "slot", {
          get: function() {
            var slots = this._armature.getSlots();
            for (var i = 0, l = slots.length; i < l; ++i) {
              var slot = slots[i];
              if (slot.parent == this) return slot;
            }
            return null;
          },
          enumerable: true,
          configurable: true
        });
        return Bone;
      })(dragonBones.TransformObject);
      dragonBones.Bone = Bone;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var Slot = (function(_super) {
        __extends(Slot, _super);
        function Slot() {
          _super.call(this);
          this._colorTransform = new dragonBones.ColorTransform();
          this._ffdVertices = [];
          this._replacedDisplayDataSet = [];
          this._localMatrix = new dragonBones.Matrix();
          this._displayList = [];
          this._meshBones = [];
        }
        Slot.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          var disposeDisplayList = [];
          for (var i = 0, l = this._displayList.length; i < l; ++i) {
            var eachDisplay = this._displayList[i];
            eachDisplay != this._rawDisplay && eachDisplay != this._meshDisplay && disposeDisplayList.indexOf(eachDisplay) < 0 && disposeDisplayList.push(eachDisplay);
          }
          for (var i = 0, l = disposeDisplayList.length; i < l; ++i) {
            var eachDisplay = disposeDisplayList[i];
            eachDisplay instanceof dragonBones.Armature ? eachDisplay.dispose() : this._disposeDisplay(eachDisplay);
          }
          this._meshDisplay && this._meshDisplay != this._rawDisplay && this._disposeDisplay(this._meshDisplay);
          this._rawDisplay && this._disposeDisplay(this._rawDisplay);
          this.inheritAnimation = true;
          this.displayController = null;
          this._blendIndex = 0;
          this._displayDataSet = null;
          this._meshData = null;
          this._childArmature = null;
          this._rawDisplay = null;
          this._meshDisplay = null;
          this._cacheFrames = null;
          this._colorTransform.identity();
          this._ffdVertices.length = 0;
          this._replacedDisplayDataSet.length = 0;
          this._zOrderDirty = false;
          this._displayDirty = false;
          this._colorDirty = false;
          this._blendModeDirty = false;
          this._originDirty = false;
          this._transformDirty = false;
          this._ffdDirty = false;
          this._zOrder = 0;
          this._displayIndex = -2;
          this._pivotX = 0;
          this._pivotY = 0;
          this._blendMode = 0;
          this._display = null;
          this._localMatrix.identity();
          this._displayList.length = 0;
          this._meshBones.length = 0;
        };
        Slot.prototype._isMeshBonesUpdate = function() {
          for (var i = 0, l = this._meshBones.length; i < l; ++i) if (0 != this._meshBones[i]._transformDirty) return true;
          return false;
        };
        Slot.prototype._updatePivot = function(rawDisplayData, currentDisplayData, currentTextureData) {
          var isReplaceDisplay = rawDisplayData && rawDisplayData != currentDisplayData && (!this._meshData || this._meshData != rawDisplayData.mesh);
          if (this._meshData && this._display == this._meshDisplay) {
            this._pivotX = 0;
            this._pivotY = 0;
          } else {
            var scale = this._armature.armatureData.scale;
            this._pivotX = currentDisplayData.pivot.x;
            this._pivotY = currentDisplayData.pivot.y;
            if (currentDisplayData.isRelativePivot) {
              var rect = currentTextureData.frame || currentTextureData.region;
              var width = rect.width * scale;
              var height = rect.height * scale;
              if (currentTextureData.rotated) {
                width = rect.height;
                height = rect.width;
              }
              this._pivotX *= width;
              this._pivotY *= height;
            }
            if (currentTextureData.frame) {
              this._pivotX += currentTextureData.frame.x * scale;
              this._pivotY += currentTextureData.frame.y * scale;
            }
          }
          if (isReplaceDisplay) {
            rawDisplayData.transform.toMatrix(Slot._helpMatrix);
            Slot._helpMatrix.invert();
            Slot._helpMatrix.transformPoint(0, 0, Slot._helpPoint);
            this._pivotX -= Slot._helpPoint.x;
            this._pivotY -= Slot._helpPoint.y;
            currentDisplayData.transform.toMatrix(Slot._helpMatrix);
            Slot._helpMatrix.invert();
            Slot._helpMatrix.transformPoint(0, 0, Slot._helpPoint);
            this._pivotX += Slot._helpPoint.x;
            this._pivotY += Slot._helpPoint.y;
          }
        };
        Slot.prototype._updateDisplay = function() {
          var prevDisplay = 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 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 || this._rawDisplay;
          if (currentDisplay != prevDisplay) {
            this._onUpdateDisplay();
            prevDisplay ? this._replaceDisplay(prevDisplay) : this._addDisplay();
            this._blendModeDirty = true;
            this._colorDirty = true;
          }
          if (this._displayDataSet && this._displayIndex >= 0 && this._displayIndex < this._displayDataSet.displays.length) {
            this.origin.copyFrom(this._displayDataSet.displays[this._displayIndex].transform);
            this._originDirty = true;
          }
          this._updateMeshData(false);
          currentDisplay != this._rawDisplay && currentDisplay != this._meshDisplay || this._updateFrame();
          if (this._childArmature != prevChildArmature) {
            if (prevChildArmature) {
              prevChildArmature._parent = null;
              this.inheritAnimation && prevChildArmature.animation.reset();
            }
            if (this._childArmature) {
              this._childArmature._parent = this;
              if (this.inheritAnimation) {
                if (0 == this._childArmature.cacheFrameRate) {
                  var cacheFrameRate = this._armature.cacheFrameRate;
                  0 != cacheFrameRate && (this._childArmature.cacheFrameRate = cacheFrameRate);
                }
                var slotData = this._armature.armatureData.getSlot(this.name);
                var actions = slotData.actions.length > 0 ? slotData.actions : this._childArmature.armatureData.actions;
                if (actions.length > 0) for (var i = 0, l = actions.length; i < l; ++i) this._childArmature._bufferAction(actions[i]); else this._childArmature.animation.play();
              }
            }
          }
        };
        Slot.prototype._updateLocalTransformMatrix = function() {
          this.global.copyFrom(this.origin).add(this.offset).toMatrix(this._localMatrix);
        };
        Slot.prototype._updateGlobalTransformMatrix = function() {
          this.globalTransformMatrix.copyFrom(this._localMatrix);
          this.globalTransformMatrix.concat(this._parent.globalTransformMatrix);
          this.global.fromMatrix(this.globalTransformMatrix);
        };
        Slot.prototype._setArmature = function(value) {
          if (this._armature == value) return;
          this._armature && this._armature._removeSlotFromSlotList(this);
          this._armature = value;
          this._onUpdateDisplay();
          if (this._armature) {
            this._armature._addSlotToSlotList(this);
            this._addDisplay();
          } else this._removeDisplay();
        };
        Slot.prototype._updateMeshData = function(isTimelineUpdate) {
          var prevMeshData = this._meshData;
          var rawMeshData = null;
          if (this._display && this._display == this._meshDisplay && this._displayIndex >= 0) {
            rawMeshData = this._displayDataSet && this._displayIndex < this._displayDataSet.displays.length ? this._displayDataSet.displays[this._displayIndex].mesh : null;
            var replaceDisplayData = this._displayIndex < this._replacedDisplayDataSet.length ? this._replacedDisplayDataSet[this._displayIndex] : null;
            var replaceMeshData = replaceDisplayData ? replaceDisplayData.mesh : null;
            this._meshData = replaceMeshData || rawMeshData;
          } else this._meshData = null;
          if (this._meshData != prevMeshData) {
            if (this._meshData && this._meshData == rawMeshData) {
              if (this._meshData.skinned) {
                this._meshBones.length = this._meshData.bones.length;
                for (var i = 0, l = this._meshBones.length; i < l; ++i) this._meshBones[i] = this._armature.getBone(this._meshData.bones[i].name);
                var ffdVerticesCount = 0;
                for (var i = 0, l = this._meshData.boneIndices.length; i < l; ++i) ffdVerticesCount += this._meshData.boneIndices[i].length;
                this._ffdVertices.length = 2 * ffdVerticesCount;
              } else {
                this._meshBones.length = 0;
                this._ffdVertices.length = this._meshData.vertices.length;
              }
              for (var i = 0, l = this._ffdVertices.length; i < l; ++i) this._ffdVertices[i] = 0;
              this._ffdDirty = true;
            } else {
              this._meshBones.length = 0;
              this._ffdVertices.length = 0;
            }
            isTimelineUpdate && this._armature.animation._updateFFDTimelineStates();
          }
        };
        Slot.prototype._update = function(cacheFrameIndex) {
          var self = this;
          self._blendIndex = 0;
          if (self._zOrderDirty) {
            self._zOrderDirty = false;
            self._updateZOrder();
          }
          if (self._displayDirty) {
            self._displayDirty = false;
            self._updateDisplay();
          }
          if (!self._display) return;
          if (self._blendModeDirty) {
            self._blendModeDirty = false;
            self._updateBlendMode();
          }
          if (self._colorDirty) {
            self._colorDirty = false;
            self._updateColor();
          }
          if (self._meshData) {
            if (self._ffdDirty || self._meshData.skinned && self._isMeshBonesUpdate()) {
              self._ffdDirty = false;
              self._updateMesh();
            }
            if (self._meshData.skinned) return;
          }
          if (self._originDirty) {
            self._originDirty = false;
            self._transformDirty = true;
            self._updateLocalTransformMatrix();
          }
          if (cacheFrameIndex >= 0 && self._cacheFrames) {
            var cacheFrame = self._cacheFrames[cacheFrameIndex];
            if (self.globalTransformMatrix == cacheFrame) self._transformDirty = false; else if (cacheFrame) {
              self._transformDirty = true;
              self.globalTransformMatrix = cacheFrame;
            } else if (self._transformDirty || 0 != self._parent._transformDirty) {
              self._transformDirty = true;
              self.globalTransformMatrix = self._globalTransformMatrix;
            } else if (self.globalTransformMatrix != self._globalTransformMatrix) {
              self._transformDirty = false;
              self._cacheFrames[cacheFrameIndex] = self.globalTransformMatrix;
            } else {
              self._transformDirty = true;
              self.globalTransformMatrix = self._globalTransformMatrix;
            }
          } else if (self._transformDirty || 0 != self._parent._transformDirty) {
            self._transformDirty = true;
            self.globalTransformMatrix = self._globalTransformMatrix;
          }
          if (self._transformDirty) {
            self._transformDirty = false;
            if (self.globalTransformMatrix == self._globalTransformMatrix) {
              self._updateGlobalTransformMatrix();
              cacheFrameIndex >= 0 && self._cacheFrames && !self._cacheFrames[cacheFrameIndex] && (self.globalTransformMatrix = dragonBones.SlotTimelineData.cacheFrame(self._cacheFrames, cacheFrameIndex, self._globalTransformMatrix));
            }
            self._updateTransform();
          }
        };
        Slot.prototype._setDisplayList = function(value) {
          if (value && value.length > 0) {
            this._displayList.length != value.length && (this._displayList.length = value.length);
            for (var i = 0, l = value.length; i < l; ++i) {
              var eachDisplay = value[i];
              eachDisplay && eachDisplay != this._rawDisplay && eachDisplay != this._meshDisplay && !(eachDisplay instanceof dragonBones.Armature) && this._displayList.indexOf(eachDisplay) < 0 && this._initDisplay(eachDisplay);
              this._displayList[i] = eachDisplay;
            }
          } else this._displayList.length > 0 && (this._displayList.length = 0);
          this._displayIndex >= 0 && this._displayIndex < this._displayList.length ? this._displayDirty = this._display != this._displayList[this._displayIndex] : this._displayDirty = null != this._display;
          return this._displayDirty;
        };
        Slot.prototype._setZorder = function(value) {
          this._zOrder == value;
          this._zOrder = value;
          this._zOrderDirty = true;
          return this._zOrderDirty;
        };
        Slot.prototype._setDisplayIndex = function(value) {
          if (this._displayIndex == value) return false;
          this._displayIndex = value;
          this._displayDirty = true;
          return this._displayDirty;
        };
        Slot.prototype._setBlendMode = function(value) {
          if (this._blendMode == value) return false;
          this._blendMode = value;
          this._blendModeDirty = true;
          return true;
        };
        Slot.prototype._setColor = function(value) {
          this._colorTransform.copyFrom(value);
          this._colorDirty = true;
          return true;
        };
        Slot.prototype.containsPoint = function(x, y, color) {
          void 0 === color && (color = 0);
          var displayData = this.displayData;
          if (!displayData || !displayData.boundingBox || color && displayData.color != color) return false;
          if (0 == this._blendIndex) {
            this._blendIndex = 1;
            this._updateLocalTransformMatrix();
            this._updateGlobalTransformMatrix();
          }
          Slot._helpMatrix.copyFrom(this.globalTransformMatrix);
          Slot._helpMatrix.invert();
          Slot._helpMatrix.transformPoint(x, y, Slot._helpPoint);
          return displayData.boundingBox.containsPoint(Slot._helpPoint.x, Slot._helpPoint.y);
        };
        Slot.prototype.intersectsSegment = function(xA, yA, xB, yB, color, intersectionPointA, intersectionPointB, normalRadians) {
          void 0 === color && (color = 0);
          void 0 === intersectionPointA && (intersectionPointA = null);
          void 0 === intersectionPointB && (intersectionPointB = null);
          void 0 === normalRadians && (normalRadians = null);
          var displayData = this.displayData;
          if (!displayData || !displayData.boundingBox || color && displayData.color != color) return 0;
          if (0 == this._blendIndex) {
            this._blendIndex = 1;
            this._updateLocalTransformMatrix();
            this._updateGlobalTransformMatrix();
          }
          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 = displayData.boundingBox.intersectsSegment(xA, yA, xB, yB, intersectionPointA, intersectionPointB, normalRadians);
          if (intersectionCount > 0) {
            if (1 == intersectionCount || 2 == intersectionCount) if (intersectionPointA) {
              this.globalTransformMatrix.transformPoint(intersectionPointA.x, intersectionPointA.y, intersectionPointA);
              if (intersectionPointB) {
                intersectionPointB.x = intersectionPointA.x;
                intersectionPointB.y = intersectionPointA.y;
              }
            } else intersectionPointB && this.globalTransformMatrix.transformPoint(intersectionPointB.x, intersectionPointB.y, intersectionPointB); else {
              intersectionPointA && this.globalTransformMatrix.transformPoint(intersectionPointA.x, intersectionPointA.y, intersectionPointA);
              intersectionPointB && this.globalTransformMatrix.transformPoint(intersectionPointB.x, intersectionPointB.y, intersectionPointB);
            }
            if (normalRadians) {
              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;
        };
        Object.defineProperty(Slot.prototype, "displayData", {
          get: function() {
            if (this._displayIndex < 0 || this._displayIndex >= this._displayDataSet.displays.length) return null;
            return this._displayDataSet.displays[this._displayIndex];
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Slot.prototype, "rawDisplay", {
          get: function() {
            return this._rawDisplay;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Slot.prototype, "meshDisplay", {
          get: function() {
            return this._meshDisplay;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Slot.prototype, "displayIndex", {
          get: function() {
            return this._displayIndex;
          },
          set: function(value) {
            this._setDisplayIndex(value) && this._update(-1);
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Slot.prototype, "displayList", {
          get: function() {
            return this._displayList.concat();
          },
          set: function(value) {
            var backupDisplayList = this._displayList.concat();
            var disposeDisplayList = [];
            this._setDisplayList(value) && this._update(-1);
            for (var i = 0, l = backupDisplayList.length; i < l; ++i) {
              var eachDisplay = backupDisplayList[i];
              eachDisplay && eachDisplay != this._rawDisplay && eachDisplay != this._meshDisplay && this._displayList.indexOf(eachDisplay) < 0 && disposeDisplayList.indexOf(eachDisplay) < 0 && disposeDisplayList.push(eachDisplay);
            }
            for (var i = 0, l = disposeDisplayList.length; i < l; ++i) {
              var eachDisplay = disposeDisplayList[i];
              eachDisplay instanceof dragonBones.Armature ? eachDisplay.dispose() : this._disposeDisplay(eachDisplay);
            }
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Slot.prototype, "display", {
          get: function() {
            return this._display;
          },
          set: function(value) {
            if (this._display == value) return;
            var displayListLength = this._displayList.length;
            this._displayIndex < 0 && 0 == displayListLength && (this._displayIndex = 0);
            if (this._displayIndex < 0) return;
            var replaceDisplayList = this.displayList;
            displayListLength <= this._displayIndex && (replaceDisplayList.length = this._displayIndex + 1);
            replaceDisplayList[this._displayIndex] = value;
            this.displayList = replaceDisplayList;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(Slot.prototype, "childArmature", {
          get: function() {
            return this._childArmature;
          },
          set: function(value) {
            if (this._childArmature == value) return;
            value && value.display.advanceTimeBySelf(false);
            this.display = value;
          },
          enumerable: true,
          configurable: true
        });
        Slot.prototype.getDisplay = function() {
          return this._display;
        };
        Slot.prototype.setDisplay = function(value) {
          this.display = value;
        };
        Slot._helpPoint = new dragonBones.Point();
        Slot._helpMatrix = new dragonBones.Matrix();
        return Slot;
      })(dragonBones.TransformObject);
      dragonBones.Slot = Slot;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var EventObject = (function(_super) {
        __extends(EventObject, _super);
        function EventObject() {
          _super.call(this);
        }
        EventObject.toString = function() {
          return "[class dragonBones.EventObject]";
        };
        EventObject.prototype._onClear = function() {
          this.type = null;
          this.name = null;
          this.armature = null;
          this.bone = null;
          this.slot = null;
          this.animationState = null;
          this.frame = null;
          this.data = null;
          this.userData = null;
        };
        EventObject.prototype.getInt = function(index) {
          return this.data ? this.data.ints[index] : 0;
        };
        EventObject.prototype.getFloat = function(index) {
          return this.data ? this.data.floats[index] : 0;
        };
        EventObject.prototype.getString = function(index) {
          return this.data ? this.data.strings[index] : 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 = {}));
    var dragonBones;
    (function(dragonBones) {
      var TimelineData = (function(_super) {
        __extends(TimelineData, _super);
        function TimelineData() {
          _super.call(this);
          this.frames = [];
        }
        TimelineData.toString = function() {
          return "[class dragonBones.TimelineData]";
        };
        TimelineData.prototype._onClear = function() {
          var prevFrame = null;
          for (var i = 0, l = this.frames.length; i < l; ++i) {
            var frame = this.frames[i];
            prevFrame && frame != prevFrame && prevFrame.returnToPool();
            prevFrame = frame;
          }
          this.scale = 1;
          this.offset = 0;
          this.frames.length = 0;
        };
        return TimelineData;
      })(dragonBones.BaseObject);
      dragonBones.TimelineData = TimelineData;
      var ZOrderTimelineData = (function(_super) {
        __extends(ZOrderTimelineData, _super);
        function ZOrderTimelineData() {
          _super.apply(this, arguments);
        }
        ZOrderTimelineData.toString = function() {
          return "[class dragonBones.ZOrderTimelineData]";
        };
        return ZOrderTimelineData;
      })(TimelineData);
      dragonBones.ZOrderTimelineData = ZOrderTimelineData;
      var BoneTimelineData = (function(_super) {
        __extends(BoneTimelineData, _super);
        function BoneTimelineData() {
          _super.call(this);
          this.originalTransform = new dragonBones.Transform();
          this.cachedFrames = [];
        }
        BoneTimelineData.cacheFrame = function(cacheFrames, cacheFrameIndex, globalTransformMatrix) {
          var cacheMatrix = cacheFrames[cacheFrameIndex] = new dragonBones.Matrix();
          cacheMatrix.copyFrom(globalTransformMatrix);
          return cacheMatrix;
        };
        BoneTimelineData.toString = function() {
          return "[class dragonBones.BoneTimelineData]";
        };
        BoneTimelineData.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          this.bone = null;
          this.originalTransform.identity();
          this.cachedFrames.length = 0;
        };
        BoneTimelineData.prototype.cacheFrames = function(cacheFrameCount) {
          this.cachedFrames.length = 0;
          this.cachedFrames.length = cacheFrameCount;
        };
        return BoneTimelineData;
      })(TimelineData);
      dragonBones.BoneTimelineData = BoneTimelineData;
      var SlotTimelineData = (function(_super) {
        __extends(SlotTimelineData, _super);
        function SlotTimelineData() {
          _super.call(this);
          this.cachedFrames = [];
        }
        SlotTimelineData.cacheFrame = function(cacheFrames, cacheFrameIndex, globalTransformMatrix) {
          var cacheMatrix = cacheFrames[cacheFrameIndex] = new dragonBones.Matrix();
          cacheMatrix.copyFrom(globalTransformMatrix);
          return cacheMatrix;
        };
        SlotTimelineData.toString = function() {
          return "[class dragonBones.SlotTimelineData]";
        };
        SlotTimelineData.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          this.slot = null;
          this.cachedFrames.length = 0;
        };
        SlotTimelineData.prototype.cacheFrames = function(cacheFrameCount) {
          this.cachedFrames.length = 0;
          this.cachedFrames.length = cacheFrameCount;
        };
        return SlotTimelineData;
      })(TimelineData);
      dragonBones.SlotTimelineData = SlotTimelineData;
      var FFDTimelineData = (function(_super) {
        __extends(FFDTimelineData, _super);
        function FFDTimelineData() {
          _super.call(this);
        }
        FFDTimelineData.toString = function() {
          return "[class dragonBones.FFDTimelineData]";
        };
        FFDTimelineData.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          this.skin = null;
          this.slot = null;
          this.display = null;
        };
        return FFDTimelineData;
      })(TimelineData);
      dragonBones.FFDTimelineData = FFDTimelineData;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var AnimationData = (function(_super) {
        __extends(AnimationData, _super);
        function AnimationData() {
          _super.call(this);
          this.boneTimelines = {};
          this.slotTimelines = {};
          this.ffdTimelines = {};
          this.cachedFrames = [];
        }
        AnimationData.toString = function() {
          return "[class dragonBones.AnimationData]";
        };
        AnimationData.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          this.zOrderTimeline && this.zOrderTimeline.returnToPool();
          for (var i in this.boneTimelines) {
            this.boneTimelines[i].returnToPool();
            delete this.boneTimelines[i];
          }
          for (var i in this.slotTimelines) {
            this.slotTimelines[i].returnToPool();
            delete this.slotTimelines[i];
          }
          for (var i in this.ffdTimelines) {
            for (var j in this.ffdTimelines[i]) for (var k in this.ffdTimelines[i][j]) this.ffdTimelines[i][j][k].returnToPool();
            delete this.ffdTimelines[i];
          }
          this.hasAsynchronyTimeline = false;
          this.frameCount = 0;
          this.playTimes = 0;
          this.position = 0;
          this.duration = 0;
          this.fadeInTime = 0;
          this.cacheFrameRate = 0;
          this.name = null;
          this.animation = null;
          this.zOrderTimeline = null;
          this.cachedFrames.length = 0;
        };
        AnimationData.prototype.cacheFrames = function(cacheFrameRate) {
          if (this.animation) return;
          this.cacheFrameRate = Math.max(Math.ceil(cacheFrameRate * this.scale), 1);
          var cacheFrameCount = Math.ceil(this.cacheFrameRate * this.duration) + 1;
          this.cachedFrames.length = 0;
          this.cachedFrames.length = cacheFrameCount;
          for (var i in this.boneTimelines) this.boneTimelines[i].cacheFrames(cacheFrameCount);
          for (var i in this.slotTimelines) this.slotTimelines[i].cacheFrames(cacheFrameCount);
        };
        AnimationData.prototype.addBoneTimeline = function(value) {
          if (!value || !value.bone || this.boneTimelines[value.bone.name]) throw new Error();
          this.boneTimelines[value.bone.name] = value;
        };
        AnimationData.prototype.addSlotTimeline = function(value) {
          if (!value || !value.slot || this.slotTimelines[value.slot.name]) throw new Error();
          this.slotTimelines[value.slot.name] = value;
        };
        AnimationData.prototype.addFFDTimeline = function(value) {
          if (!(value && value.skin && value.slot && value.display)) throw new Error();
          var skin = this.ffdTimelines[value.skin.name] = this.ffdTimelines[value.skin.name] || {};
          var slot = skin[value.slot.slot.name] = skin[value.slot.slot.name] || {};
          if (slot[value.display.name]) throw new Error();
          slot[value.display.name] = value;
        };
        AnimationData.prototype.getBoneTimeline = function(name) {
          return this.boneTimelines[name];
        };
        AnimationData.prototype.getSlotTimeline = function(name) {
          return this.slotTimelines[name];
        };
        AnimationData.prototype.getFFDTimeline = function(skinName, slotName, displayName) {
          var skin = this.ffdTimelines[skinName];
          if (skin) {
            var slot = skin[slotName];
            if (slot) return slot[displayName];
          }
          return null;
        };
        return AnimationData;
      })(dragonBones.TimelineData);
      dragonBones.AnimationData = AnimationData;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var ArmatureData = (function(_super) {
        __extends(ArmatureData, _super);
        function ArmatureData() {
          _super.call(this);
          this.aabb = new dragonBones.Rectangle();
          this.bones = {};
          this.slots = {};
          this.skins = {};
          this.animations = {};
          this.actions = [];
          this._sortedBones = [];
          this._sortedSlots = [];
          this._bonesChildren = {};
        }
        ArmatureData._onSortSlots = function(a, b) {
          return a.zOrder > b.zOrder ? 1 : -1;
        };
        ArmatureData.toString = function() {
          return "[class dragonBones.ArmatureData]";
        };
        ArmatureData.prototype._onClear = function() {
          for (var i in this.bones) {
            this.bones[i].returnToPool();
            delete this.bones[i];
          }
          for (var i in this.slots) {
            this.slots[i].returnToPool();
            delete this.slots[i];
          }
          for (var i in this.skins) {
            this.skins[i].returnToPool();
            delete this.skins[i];
          }
          for (var i in this.animations) {
            this.animations[i].returnToPool();
            delete this.animations[i];
          }
          for (var i = 0, l = this.actions.length; i < l; ++i) this.actions[i].returnToPool();
          this.frameRate = 0;
          this.type = -1;
          this.name = null;
          this.parent = null;
          this.userData = null;
          this.aabb.clear();
          this.actions.length = 0;
          this.cacheFrameRate = 0;
          this.scale = 1;
          for (var i in this._bonesChildren) delete this._bonesChildren[i];
          this._boneDirty = false;
          this._slotDirty = false;
          this._defaultSkin = null;
          this._defaultAnimation = null;
          this._sortedBones.length = 0;
          this._sortedSlots.length = 0;
        };
        ArmatureData.prototype._sortBones = function() {
          var total = this._sortedBones.length;
          if (total < 1) return;
          var sortHelper = this._sortedBones.concat();
          var index = 0;
          var count = 0;
          this._sortedBones.length = 0;
          while (count < total) {
            var bone = sortHelper[index++];
            index >= total && (index = 0);
            if (this._sortedBones.indexOf(bone) >= 0) continue;
            if (bone.parent && this._sortedBones.indexOf(bone.parent) < 0) continue;
            if (bone.ik && this._sortedBones.indexOf(bone.ik) < 0) continue;
            bone.ik && bone.chain > 0 && bone.chainIndex == bone.chain ? this._sortedBones.splice(this._sortedBones.indexOf(bone.parent) + 1, 0, bone) : this._sortedBones.push(bone);
            count++;
          }
        };
        ArmatureData.prototype._sortSlots = function() {
          this._sortedSlots.sort(ArmatureData._onSortSlots);
        };
        ArmatureData.prototype.cacheFrames = function(value) {
          if (this.cacheFrameRate == value) return;
          this.cacheFrameRate = value;
          for (var i in this.animations) this.animations[i].cacheFrames(this.cacheFrameRate);
        };
        ArmatureData.prototype.addBone = function(value, parentName) {
          if (!value || !value.name || this.bones[value.name]) throw new Error();
          if (parentName) {
            var parent_1 = this.getBone(parentName);
            parent_1 ? value.parent = parent_1 : (this._bonesChildren[parentName] = this._bonesChildren[parentName] || []).push(value);
          }
          var children = this._bonesChildren[value.name];
          if (children) {
            for (var i = 0, l = children.length; i < l; ++i) children[i].parent = value;
            delete this._bonesChildren[value.name];
          }
          this.bones[value.name] = value;
          this._sortedBones.push(value);
          this._boneDirty = true;
        };
        ArmatureData.prototype.addSlot = function(value) {
          if (!value || !value.name || this.slots[value.name]) throw new Error();
          this.slots[value.name] = value;
          this._sortedSlots.push(value);
          this._slotDirty = true;
        };
        ArmatureData.prototype.addSkin = function(value) {
          if (!value || !value.name || this.skins[value.name]) throw new Error();
          this.skins[value.name] = value;
          this._defaultSkin || (this._defaultSkin = value);
        };
        ArmatureData.prototype.addAnimation = function(value) {
          if (!value || !value.name || this.animations[value.name]) throw new Error();
          this.animations[value.name] = value;
          this._defaultAnimation || (this._defaultAnimation = value);
        };
        ArmatureData.prototype.getBone = function(name) {
          return this.bones[name];
        };
        ArmatureData.prototype.getSlot = function(name) {
          return this.slots[name];
        };
        ArmatureData.prototype.getSkin = function(name) {
          return name ? this.skins[name] : this._defaultSkin;
        };
        ArmatureData.prototype.getAnimation = function(name) {
          return name ? this.animations[name] : this._defaultAnimation;
        };
        Object.defineProperty(ArmatureData.prototype, "sortedBones", {
          get: function() {
            if (this._boneDirty) {
              this._boneDirty = false;
              this._sortBones();
            }
            return this._sortedBones;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(ArmatureData.prototype, "sortedSlots", {
          get: function() {
            if (this._slotDirty) {
              this._slotDirty = false;
              this._sortSlots();
            }
            return this._sortedSlots;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(ArmatureData.prototype, "defaultSkin", {
          get: function() {
            return this._defaultSkin;
          },
          enumerable: true,
          configurable: true
        });
        Object.defineProperty(ArmatureData.prototype, "defaultAnimation", {
          get: function() {
            return this._defaultAnimation;
          },
          enumerable: true,
          configurable: true
        });
        return ArmatureData;
      })(dragonBones.BaseObject);
      dragonBones.ArmatureData = ArmatureData;
      var BoneData = (function(_super) {
        __extends(BoneData, _super);
        function BoneData() {
          _super.call(this);
          this.transform = new dragonBones.Transform();
        }
        BoneData.toString = function() {
          return "[class dragonBones.BoneData]";
        };
        BoneData.prototype._onClear = function() {
          this.inheritTranslation = false;
          this.inheritRotation = false;
          this.inheritScale = false;
          this.bendPositive = false;
          this.chain = 0;
          this.chainIndex = 0;
          this.weight = 0;
          this.length = 0;
          this.name = null;
          this.parent = null;
          this.ik = null;
          this.transform.identity();
        };
        return BoneData;
      })(dragonBones.BaseObject);
      dragonBones.BoneData = BoneData;
      var SlotData = (function(_super) {
        __extends(SlotData, _super);
        function SlotData() {
          _super.call(this);
          this.actions = [];
        }
        SlotData.generateColor = function() {
          return new dragonBones.ColorTransform();
        };
        SlotData.toString = function() {
          return "[class dragonBones.SlotData]";
        };
        SlotData.prototype._onClear = function() {
          for (var i = 0, l = this.actions.length; i < l; ++i) this.actions[i].returnToPool();
          this.displayIndex = 0;
          this.zOrder = 0;
          this.blendMode = 0;
          this.name = null;
          this.parent = null;
          this.color = null;
          this.actions.length = 0;
        };
        SlotData.DEFAULT_COLOR = new dragonBones.ColorTransform();
        return SlotData;
      })(dragonBones.BaseObject);
      dragonBones.SlotData = SlotData;
      var SkinData = (function(_super) {
        __extends(SkinData, _super);
        function SkinData() {
          _super.call(this);
          this.slots = {};
        }
        SkinData.toString = function() {
          return "[class dragonBones.SkinData]";
        };
        SkinData.prototype._onClear = function() {
          for (var i in this.slots) {
            this.slots[i].returnToPool();
            delete this.slots[i];
          }
          this.name = null;
        };
        SkinData.prototype.addSlot = function(value) {
          if (!value || !value.slot || this.slots[value.slot.name]) throw new Error();
          this.slots[value.slot.name] = value;
        };
        SkinData.prototype.getSlot = function(name) {
          return this.slots[name];
        };
        return SkinData;
      })(dragonBones.BaseObject);
      dragonBones.SkinData = SkinData;
      var SlotDisplayDataSet = (function(_super) {
        __extends(SlotDisplayDataSet, _super);
        function SlotDisplayDataSet() {
          _super.call(this);
          this.displays = [];
        }
        SlotDisplayDataSet.toString = function() {
          return "[class dragonBones.SlotDisplayDataSet]";
        };
        SlotDisplayDataSet.prototype._onClear = function() {
          for (var i = 0, l = this.displays.length; i < l; ++i) this.displays[i].returnToPool();
          this.slot = null;
          this.displays.length = 0;
        };
        return SlotDisplayDataSet;
      })(dragonBones.BaseObject);
      dragonBones.SlotDisplayDataSet = SlotDisplayDataSet;
      var DisplayData = (function(_super) {
        __extends(DisplayData, _super);
        function DisplayData() {
          _super.call(this);
          this.pivot = new dragonBones.Point();
          this.transform = new dragonBones.Transform();
        }
        DisplayData.toString = function() {
          return "[class dragonBones.DisplayData]";
        };
        DisplayData.prototype._onClear = function() {
          this.mesh && !this.share && this.mesh.returnToPool();
          this.boundingBox && this.boundingBox.returnToPool();
          this.isRelativePivot = false;
          this.type = -1;
          this.inheritAnimation = true;
          this.color = 0;
          this.name = null;
          this.path = null;
          this.texture = null;
          this.armature = null;
          this.mesh = null;
          this.share = null;
          this.boundingBox = null;
          this.pivot.clear();
          this.transform.identity();
        };
        return DisplayData;
      })(dragonBones.BaseObject);
      dragonBones.DisplayData = DisplayData;
      var MeshData = (function(_super) {
        __extends(MeshData, _super);
        function MeshData() {
          _super.call(this);
          this.slotPose = new dragonBones.Matrix();
          this.uvs = [];
          this.vertices = [];
          this.vertexIndices = [];
          this.boneIndices = [];
          this.weights = [];
          this.boneVertices = [];
          this.bones = [];
          this.inverseBindPose = [];
        }
        MeshData.toString = function() {
          return "[class dragonBones.MeshData]";
        };
        MeshData.prototype._onClear = function() {
          this.skinned = false;
          this.slotPose.identity();
          this.uvs.length = 0;
          this.vertices.length = 0;
          this.vertexIndices.length = 0;
          this.boneIndices.length = 0;
          this.weights.length = 0;
          this.boneVertices.length = 0;
          this.bones.length = 0;
          this.inverseBindPose.length = 0;
        };
        return MeshData;
      })(dragonBones.BaseObject);
      dragonBones.MeshData = MeshData;
      var BoundingBoxData = (function(_super) {
        __extends(BoundingBoxData, _super);
        function BoundingBoxData() {
          _super.call(this);
          this.x = 0;
          this.y = 0;
          this.width = 0;
          this.height = 0;
          this.vertices = [];
        }
        BoundingBoxData.toString = function() {
          return "[class dragonBones.BoundingBoxData]";
        };
        BoundingBoxData._computeOutCode = function(x, y, xMin, yMin, xMax, yMax) {
          var code = 0;
          x < xMin ? code |= 1 : x > xMax && (code |= 2);
          y < yMin ? code |= 4 : y > yMax && (code |= 8);
          return code;
        };
        BoundingBoxData.segmentIntersectsRectangle = function(xA, yA, xB, yB, xMin, yMin, xMax, yMax, intersectionPointA, intersectionPointB, normalRadians) {
          void 0 === intersectionPointA && (intersectionPointA = null);
          void 0 === intersectionPointB && (intersectionPointB = null);
          void 0 === normalRadians && (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 = BoundingBoxData._computeOutCode(xA, yA, xMin, yMin, xMax, yMax);
          var outcode1 = BoundingBoxData._computeOutCode(xB, yB, xMin, yMin, xMax, yMax);
          while (true) {
            if (!(outcode0 | outcode1)) {
              intersectionCount = 2;
              break;
            }
            if (outcode0 & outcode1) break;
            var x = 0;
            var y = 0;
            var normalRadian = 0;
            var outcodeOut = outcode0 || outcode1;
            if (4 & outcodeOut) {
              x = xA + (xB - xA) * (yMin - yA) / (yB - yA);
              y = yMin;
              normalRadians && (normalRadian = .5 * -Math.PI);
            } else if (8 & outcodeOut) {
              x = xA + (xB - xA) * (yMax - yA) / (yB - yA);
              y = yMax;
              normalRadians && (normalRadian = .5 * Math.PI);
            } else if (2 & outcodeOut) {
              y = yA + (yB - yA) * (xMax - xA) / (xB - xA);
              x = xMax;
              normalRadians && (normalRadian = 0);
            } else if (1 & outcodeOut) {
              y = yA + (yB - yA) * (xMin - xA) / (xB - xA);
              x = xMin;
              normalRadians && (normalRadian = Math.PI);
            }
            if (outcodeOut == outcode0) {
              xA = x;
              yA = y;
              outcode0 = BoundingBoxData._computeOutCode(xA, yA, xMin, yMin, xMax, yMax);
              normalRadians && (normalRadians.x = normalRadian);
            } else {
              xB = x;
              yB = y;
              outcode1 = BoundingBoxData._computeOutCode(xB, yB, xMin, yMin, xMax, yMax);
              normalRadians && (normalRadians.y = normalRadian);
            }
          }
          if (intersectionCount) if (inSideA) {
            intersectionCount = 2;
            if (intersectionPointA) {
              intersectionPointA.x = xB;
              intersectionPointA.y = yB;
            }
            if (intersectionPointB) {
              intersectionPointB.x = xB;
              intersectionPointB.y = xB;
            }
            normalRadians && (normalRadians.x = normalRadians.y + Math.PI);
          } else if (inSideB) {
            intersectionCount = 1;
            if (intersectionPointA) {
              intersectionPointA.x = xA;
              intersectionPointA.y = yA;
            }
            if (intersectionPointB) {
              intersectionPointB.x = xA;
              intersectionPointB.y = yA;
            }
            normalRadians && (normalRadians.y = normalRadians.x + Math.PI);
          } else {
            intersectionCount = 3;
            if (intersectionPointA) {
              intersectionPointA.x = xA;
              intersectionPointA.y = yA;
            }
            if (intersectionPointB) {
              intersectionPointB.x = xB;
              intersectionPointB.y = yB;
            }
          }
          return intersectionCount;
        };
        BoundingBoxData.segmentIntersectsEllipse = function(xA, yA, xB, yB, xC, yC, widthH, heightH, intersectionPointA, intersectionPointB, normalRadians) {
          void 0 === intersectionPointA && (intersectionPointA = null);
          void 0 === intersectionPointB && (intersectionPointB = null);
          void 0 === normalRadians && (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) {
            var dT = Math.sqrt(dR);
            var sA = a - dT;
            var sB = a + dT;
            var inSideA = sA < 0 ? -1 : sA <= lAB ? 0 : 1;
            var inSideB = sB < 0 ? -1 : sB <= lAB ? 0 : 1;
            var sideAB = inSideA * inSideB;
            if (sideAB < 0) return -1;
            if (0 == sideAB) if (-1 == inSideA) {
              intersectionCount = 2;
              xB = xA + sB * xD;
              yB = (yA + sB * yD) / d;
              if (intersectionPointA) {
                intersectionPointA.x = xB;
                intersectionPointA.y = yB;
              }
              if (intersectionPointB) {
                intersectionPointB.x = xB;
                intersectionPointB.y = yB;
              }
              if (normalRadians) {
                normalRadians.x = Math.atan2(yB / rr * dd, xB / rr);
                normalRadians.y = normalRadians.x + Math.PI;
              }
            } else if (1 == inSideB) {
              intersectionCount = 1;
              xA += sA * xD;
              yA = (yA + sA * yD) / d;
              if (intersectionPointA) {
                intersectionPointA.x = xA;
                intersectionPointA.y = yA;
              }
              if (intersectionPointB) {
                intersectionPointB.x = xA;
                intersectionPointB.y = yA;
              }
              if (normalRadians) {
                normalRadians.x = Math.atan2(yA / rr * dd, xA / rr);
                normalRadians.y = normalRadians.x + Math.PI;
              }
            } else {
              intersectionCount = 3;
              if (intersectionPointA) {
                intersectionPointA.x = xA + sA * xD;
                intersectionPointA.y = (yA + sA * yD) / d;
                normalRadians && (normalRadians.x = Math.atan2(intersectionPointA.y / rr * dd, intersectionPointA.x / rr));
              }
              if (intersectionPointB) {
                intersectionPointB.x = xA + sB * xD;
                intersectionPointB.y = (yA + sB * yD) / d;
                normalRadians && (normalRadians.y = Math.atan2(intersectionPointB.y / rr * dd, intersectionPointB.x / rr));
              }
            }
          }
          return intersectionCount;
        };
        BoundingBoxData.segmentIntersectsPolygon = function(xA, yA, xB, yB, vertices, intersectionPointA, intersectionPointB, normalRadians) {
          void 0 === intersectionPointA && (intersectionPointA = null);
          void 0 === intersectionPointB && (intersectionPointB = null);
          void 0 === normalRadians && (normalRadians = null);
          xA == xB && (xA = xB + .01);
          yA == yB && (yA = yB + .01);
          var l = vertices.length;
          var dXAB = xA - xB;
          var dYAB = yA - yB;
          var llAB = xA * yB - yA * xB;
          var intersectionCount = 0;
          var xC = vertices[l - 2];
          var yC = vertices[l - 1];
          var dMin = 0;
          var dMax = 0;
          var xMin = 0;
          var yMin = 0;
          var xMax = 0;
          var yMax = 0;
          for (var i = 0; i < l; i += 2) {
            var xD = vertices[i];
            var yD = vertices[i + 1];
            xC == xD && (xC = xD + .01);
            yC == yD && (yC = yD + .01);
            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) && (0 == dXAB || x >= xA && x <= xB || x >= xB && x <= xA)) {
              var y = (llAB * dYCD - dYAB * llCD) / ll;
              if ((y >= yC && y <= yD || y >= yD && y <= yC) && (0 == dYAB || y >= yA && y <= yB || y >= yB && y <= yA)) {
                if (!intersectionPointB) {
                  xMin = x;
                  yMin = y;
                  xMax = x;
                  yMax = y;
                  intersectionCount++;
                  if (normalRadians) {
                    normalRadians.x = Math.atan2(yD - yC, xD - xC) - .5 * Math.PI;
                    normalRadians.y = normalRadians.x;
                  }
                  break;
                }
                var d = x - xA;
                d < 0 && (d = -d);
                if (0 == intersectionCount) {
                  dMin = d;
                  dMax = d;
                  xMin = x;
                  yMin = y;
                  xMax = x;
                  yMax = y;
                  if (normalRadians) {
                    normalRadians.x = Math.atan2(yD - yC, xD - xC) - .5 * Math.PI;
                    normalRadians.y = normalRadians.x;
                  }
                } else {
                  if (d < dMin) {
                    dMin = d;
                    xMin = x;
                    yMin = y;
                    normalRadians && (normalRadians.x = Math.atan2(yD - yC, xD - xC) - .5 * Math.PI);
                  }
                  if (d > dMax) {
                    dMax = d;
                    xMax = x;
                    yMax = y;
                    normalRadians && (normalRadians.y = Math.atan2(yD - yC, xD - xC) - .5 * Math.PI);
                  }
                }
                intersectionCount++;
              }
            }
            xC = xD;
            yC = yD;
          }
          if (1 == intersectionCount) {
            if (intersectionPointA) {
              intersectionPointA.x = xMin;
              intersectionPointA.y = yMin;
            }
            if (intersectionPointB) {
              intersectionPointB.x = xMin;
              intersectionPointB.y = yMin;
            }
            normalRadians && (normalRadians.y = normalRadians.x + Math.PI);
          } else if (intersectionCount > 1) {
            intersectionCount++;
            if (intersectionPointA) {
              intersectionPointA.x = xMin;
              intersectionPointA.y = yMin;
            }
            if (intersectionPointB) {
              intersectionPointB.x = xMax;
              intersectionPointB.y = yMax;
            }
          }
          return intersectionCount;
        };
        BoundingBoxData.prototype._onClear = function() {
          this.type = -1;
          this.x = 0;
          this.y = 0;
          this.width = 0;
          this.height = 0;
          this.vertices.length = 0;
        };
        BoundingBoxData.prototype.containsPoint = function(x, y) {
          var isInSide = false;
          if (2 == this.type) {
            if (x >= this.x && x <= this.width && y >= this.y && y <= this.height) for (var i = 0, l = this.vertices.length, prevIndex = l - 2; i < l; i += 2) {
              var yA = this.vertices[prevIndex + 1];
              var yB = this.vertices[i + 1];
              if (yB < y && yA >= y || yA < y && yB >= y) {
                var xA = this.vertices[prevIndex];
                var xB = this.vertices[i];
                (y - yB) * (xA - xB) / (yA - yB) + xB < x && (isInSide = !isInSide);
              }
              prevIndex = i;
            }
          } else {
            var widthH = .5 * this.width;
            if (x >= -widthH && x <= widthH) {
              var heightH = .5 * this.height;
              if (y >= -heightH && y <= heightH) if (1 == this.type) {
                y *= widthH / heightH;
                isInSide = Math.sqrt(x * x + y * y) <= widthH;
              } else isInSide = true;
            }
          }
          return isInSide;
        };
        BoundingBoxData.prototype.intersectsSegment = function(xA, yA, xB, yB, intersectionPointA, intersectionPointB, normalRadians) {
          void 0 === intersectionPointA && (intersectionPointA = null);
          void 0 === intersectionPointB && (intersectionPointB = null);
          void 0 === normalRadians && (normalRadians = null);
          var intersectionCount = 0;
          switch (this.type) {
           case 0:
            var widthH = .5 * this.width;
            var heightH = .5 * this.height;
            intersectionCount = BoundingBoxData.segmentIntersectsRectangle(xA, yA, xB, yB, -widthH, -heightH, widthH, heightH, intersectionPointA, intersectionPointB, normalRadians);
            break;

           case 1:
            intersectionCount = BoundingBoxData.segmentIntersectsEllipse(xA, yA, xB, yB, 0, 0, .5 * this.width, .5 * this.height, intersectionPointA, intersectionPointB, normalRadians);
            break;

           case 2:
            0 != BoundingBoxData.segmentIntersectsRectangle(xA, yA, xB, yB, this.x, this.y, this.width, this.height, null, null) && (intersectionCount = BoundingBoxData.segmentIntersectsPolygon(xA, yA, xB, yB, this.vertices, intersectionPointA, intersectionPointB, normalRadians));
          }
          return intersectionCount;
        };
        return BoundingBoxData;
      })(dragonBones.BaseObject);
      dragonBones.BoundingBoxData = BoundingBoxData;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var DragonBonesData = (function(_super) {
        __extends(DragonBonesData, _super);
        function DragonBonesData() {
          _super.call(this);
          this.armatures = {};
          this._armatureNames = [];
        }
        DragonBonesData.toString = function() {
          return "[class dragonBones.DragonBonesData]";
        };
        DragonBonesData.prototype._onClear = function() {
          for (var i in this.armatures) {
            this.armatures[i].returnToPool();
            delete this.armatures[i];
          }
          this.autoSearch = false;
          this.frameRate = 0;
          this.name = null;
          this._armatureNames.length = 0;
        };
        DragonBonesData.prototype.getArmature = function(name) {
          return this.armatures[name];
        };
        DragonBonesData.prototype.addArmature = function(value) {
          if (!value || !value.name || this.armatures[value.name]) throw new Error();
          this.armatures[value.name] = value;
          this._armatureNames.push(value.name);
          value.parent = this;
        };
        Object.defineProperty(DragonBonesData.prototype, "armatureNames", {
          get: function() {
            return this._armatureNames;
          },
          enumerable: true,
          configurable: true
        });
        DragonBonesData.prototype.dispose = function() {
          this.returnToPool();
        };
        return DragonBonesData;
      })(dragonBones.BaseObject);
      dragonBones.DragonBonesData = DragonBonesData;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var ActionData = (function(_super) {
        __extends(ActionData, _super);
        function ActionData() {
          _super.call(this);
          this.data = [];
        }
        ActionData.toString = function() {
          return "[class dragonBones.ActionData]";
        };
        ActionData.prototype._onClear = function() {
          this.type = -1;
          this.bone = null;
          this.slot = null;
          this.data.length = 0;
        };
        return ActionData;
      })(dragonBones.BaseObject);
      dragonBones.ActionData = ActionData;
      var EventData = (function(_super) {
        __extends(EventData, _super);
        function EventData() {
          _super.call(this);
          this.ints = [];
          this.floats = [];
          this.strings = [];
        }
        EventData.toString = function() {
          return "[class dragonBones.EventData]";
        };
        EventData.prototype._onClear = function() {
          this.type = -1;
          this.name = null;
          this.ints.length = 0;
          this.floats.length = 0;
          this.strings.length = 0;
          this.bone = null;
          this.slot = null;
        };
        return EventData;
      })(dragonBones.BaseObject);
      dragonBones.EventData = EventData;
      var FrameData = (function(_super) {
        __extends(FrameData, _super);
        function FrameData() {
          _super.call(this);
        }
        FrameData.prototype._onClear = function() {
          this.position = 0;
          this.duration = 0;
          this.prev = null;
          this.next = null;
        };
        return FrameData;
      })(dragonBones.BaseObject);
      dragonBones.FrameData = FrameData;
      var TweenFrameData = (function(_super) {
        __extends(TweenFrameData, _super);
        function TweenFrameData() {
          _super.call(this);
        }
        TweenFrameData._getCurvePoint = function(x1, y1, x2, y2, x3, y3, x4, y4, t, result) {
          var l_t = 1 - t;
          var powA = l_t * l_t;
          var powB = t * t;
          var kA = l_t * powA;
          var kB = 3 * t * powA;
          var kC = 3 * 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;
        };
        TweenFrameData.samplingEasingCurve = function(curve, samples) {
          var curveCount = curve.length;
          var result = new dragonBones.Point();
          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;
            var y1 = isInCurve ? curve[stepIndex + 1] : 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;
            var y4 = isInCurve ? curve[stepIndex + 7] : 1;
            var lower = 0;
            var higher = 1;
            while (higher - lower > .01) {
              var percentage = (higher + lower) / 2;
              TweenFrameData._getCurvePoint(x1, y1, x2, y2, x3, y3, x4, y4, percentage, result);
              t - result.x > 0 ? lower = percentage : higher = percentage;
            }
            samples[i] = result.y;
          }
        };
        TweenFrameData.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          this.tweenEasing = 0;
          this.curve = null;
        };
        return TweenFrameData;
      })(FrameData);
      dragonBones.TweenFrameData = TweenFrameData;
      var AnimationFrameData = (function(_super) {
        __extends(AnimationFrameData, _super);
        function AnimationFrameData() {
          _super.call(this);
          this.actions = [];
          this.events = [];
        }
        AnimationFrameData.toString = function() {
          return "[class dragonBones.AnimationFrameData]";
        };
        AnimationFrameData.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          for (var i = 0, l = this.actions.length; i < l; ++i) this.actions[i].returnToPool();
          for (var i = 0, l = this.events.length; i < l; ++i) this.events[i].returnToPool();
          this.actions.length = 0;
          this.events.length = 0;
        };
        return AnimationFrameData;
      })(FrameData);
      dragonBones.AnimationFrameData = AnimationFrameData;
      var ZOrderFrameData = (function(_super) {
        __extends(ZOrderFrameData, _super);
        function ZOrderFrameData() {
          _super.call(this);
          this.zOrder = [];
        }
        ZOrderFrameData.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          this.zOrder.length = 0;
        };
        return ZOrderFrameData;
      })(FrameData);
      dragonBones.ZOrderFrameData = ZOrderFrameData;
      var BoneFrameData = (function(_super) {
        __extends(BoneFrameData, _super);
        function BoneFrameData() {
          _super.call(this);
          this.transform = new dragonBones.Transform();
        }
        BoneFrameData.toString = function() {
          return "[class dragonBones.BoneFrameData]";
        };
        BoneFrameData.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          this.tweenScale = false;
          this.tweenRotate = 0;
          this.transform.identity();
        };
        return BoneFrameData;
      })(TweenFrameData);
      dragonBones.BoneFrameData = BoneFrameData;
      var SlotFrameData = (function(_super) {
        __extends(SlotFrameData, _super);
        function SlotFrameData() {
          _super.call(this);
        }
        SlotFrameData.generateColor = function() {
          return new dragonBones.ColorTransform();
        };
        SlotFrameData.toString = function() {
          return "[class dragonBones.SlotFrameData]";
        };
        SlotFrameData.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          this.displayIndex = 0;
          this.color = null;
        };
        SlotFrameData.DEFAULT_COLOR = new dragonBones.ColorTransform();
        return SlotFrameData;
      })(TweenFrameData);
      dragonBones.SlotFrameData = SlotFrameData;
      var ExtensionFrameData = (function(_super) {
        __extends(ExtensionFrameData, _super);
        function ExtensionFrameData() {
          _super.call(this);
          this.tweens = [];
          this.keys = [];
        }
        ExtensionFrameData.toString = function() {
          return "[class dragonBones.ExtensionFrameData]";
        };
        ExtensionFrameData.prototype._onClear = function() {
          _super.prototype._onClear.call(this);
          this.type = -1;
          this.tweens.length = 0;
          this.keys.length = 0;
        };
        return ExtensionFrameData;
      })(TweenFrameData);
      dragonBones.ExtensionFrameData = ExtensionFrameData;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var DataParser = (function() {
        function DataParser() {
          this._data = null;
          this._armature = null;
          this._skin = null;
          this._slotDisplayDataSet = null;
          this._animation = null;
          this._timeline = null;
          this._isOldData = false;
          this._isGlobalTransform = false;
          this._isAutoTween = false;
          this._animationTweenEasing = 0;
          this._timelinePivot = new dragonBones.Point();
          this._helpPoint = new dragonBones.Point();
          this._helpTransformA = new dragonBones.Transform();
          this._helpTransformB = new dragonBones.Transform();
          this._helpMatrix = new dragonBones.Matrix();
          this._rawBones = [];
        }
        DataParser._getArmatureType = function(value) {
          switch (value.toLowerCase()) {
           case "stage":
            return 2;

           case "armature":
            return 0;

           case "movieclip":
            return 1;

           default:
            return -1;
          }
        };
        DataParser._getDisplayType = function(value) {
          switch (value.toLowerCase()) {
           case "image":
            return 0;

           case "mesh":
            return 2;

           case "armature":
            return 1;

           case "boundingbox":
            return 3;

           default:
            return -1;
          }
        };
        DataParser._getBoundingBoxType = function(value) {
          switch (value.toLowerCase()) {
           case "rectangle":
            return 0;

           case "ellipse":
            return 1;

           case "polygon":
            return 2;

           default:
            return -1;
          }
        };
        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 -1;
          }
        };
        DataParser._getActionType = function(value) {
          switch (value.toLowerCase()) {
           case "play":
            return 0;

           case "stop":
            return 1;

           case "gotoandplay":
            return 2;

           case "gotoandstop":
            return 3;

           case "fadein":
            return 4;

           case "fadeout":
            return 5;

           default:
            return -1;
          }
        };
        DataParser.prototype._getTimelineFrameMatrix = function(animation, timeline, position, transform) {
          var frameIndex = Math.floor(position * animation.frameCount / animation.duration);
          if (1 == timeline.frames.length || frameIndex >= timeline.frames.length) transform.copyFrom(timeline.frames[0].transform); else {
            var frame = timeline.frames[frameIndex];
            var tweenProgress = 0;
            if (frame.tweenEasing != dragonBones.DragonBones.NO_TWEEN) {
              tweenProgress = (position - frame.position) / frame.duration;
              0 != frame.tweenEasing && (tweenProgress = dragonBones.TweenTimelineState._getEasingValue(tweenProgress, frame.tweenEasing));
            } else if (frame.curve) {
              tweenProgress = (position - frame.position) / frame.duration;
              tweenProgress = dragonBones.TweenTimelineState._getEasingCurveValue(tweenProgress, frame.curve);
            }
            var nextFrame = frame.next;
            transform.x = nextFrame.transform.x - frame.transform.x;
            transform.y = nextFrame.transform.y - frame.transform.y;
            transform.skewX = dragonBones.Transform.normalizeRadian(nextFrame.transform.skewX - frame.transform.skewX);
            transform.skewY = dragonBones.Transform.normalizeRadian(nextFrame.transform.skewY - frame.transform.skewY);
            transform.scaleX = nextFrame.transform.scaleX - frame.transform.scaleX;
            transform.scaleY = nextFrame.transform.scaleY - frame.transform.scaleY;
            transform.x = frame.transform.x + transform.x * tweenProgress;
            transform.y = frame.transform.y + transform.y * tweenProgress;
            transform.skewX = frame.transform.skewX + transform.skewX * tweenProgress;
            transform.skewY = frame.transform.skewY + transform.skewY * tweenProgress;
            transform.scaleX = frame.transform.scaleX + transform.scaleX * tweenProgress;
            transform.scaleY = frame.transform.scaleY + transform.scaleY * tweenProgress;
          }
          transform.add(timeline.originalTransform);
        };
        DataParser.prototype._globalToLocal = function(armature) {
          var keyFrames = new Array();
          var bones = armature.sortedBones.concat().reverse();
          for (var i = 0, l = bones.length; i < l; ++i) {
            var bone = bones[i];
            if (bone.parent) {
              bone.parent.transform.toMatrix(this._helpMatrix);
              this._helpMatrix.invert();
              this._helpMatrix.transformPoint(bone.transform.x, bone.transform.y, this._helpPoint);
              bone.transform.x = this._helpPoint.x;
              bone.transform.y = this._helpPoint.y;
              bone.transform.rotation -= bone.parent.transform.rotation;
            }
            for (var i_2 in armature.animations) {
              var animation = armature.animations[i_2];
              var timeline = animation.getBoneTimeline(bone.name);
              if (!timeline) continue;
              var parentTimeline = bone.parent ? animation.getBoneTimeline(bone.parent.name) : null;
              this._helpTransformB.copyFrom(timeline.originalTransform);
              keyFrames.length = 0;
              for (var i_3 = 0, l_2 = timeline.frames.length; i_3 < l_2; ++i_3) {
                var frame = timeline.frames[i_3];
                if (keyFrames.indexOf(frame) >= 0) continue;
                keyFrames.push(frame);
                if (parentTimeline) {
                  this._getTimelineFrameMatrix(animation, parentTimeline, frame.position, this._helpTransformA);
                  frame.transform.add(this._helpTransformB);
                  this._helpTransformA.toMatrix(this._helpMatrix);
                  this._helpMatrix.invert();
                  this._helpMatrix.transformPoint(frame.transform.x, frame.transform.y, this._helpPoint);
                  frame.transform.x = this._helpPoint.x;
                  frame.transform.y = this._helpPoint.y;
                  frame.transform.rotation -= this._helpTransformA.rotation;
                } else frame.transform.add(this._helpTransformB);
                frame.transform.minus(bone.transform);
                if (0 == i_3) {
                  timeline.originalTransform.copyFrom(frame.transform);
                  frame.transform.identity();
                } else frame.transform.minus(timeline.originalTransform);
              }
            }
          }
        };
        DataParser.prototype._mergeFrameToAnimationTimeline = function(framePostion, actions, events) {
          var frameStart = Math.floor(framePostion * this._armature.frameRate);
          var frames = this._animation.frames;
          if (0 == frames.length) {
            var startFrame = dragonBones.BaseObject.borrowObject(dragonBones.AnimationFrameData);
            startFrame.position = 0;
            if (this._animation.frameCount > 1) {
              frames.length = this._animation.frameCount + 1;
              var endFrame = dragonBones.BaseObject.borrowObject(dragonBones.AnimationFrameData);
              endFrame.position = this._animation.frameCount / this._armature.frameRate;
              frames[0] = startFrame;
              frames[this._animation.frameCount] = endFrame;
            }
          }
          var insertedFrame = null;
          var replacedFrame = frames[frameStart];
          if (!replacedFrame || 0 != frameStart && frames[frameStart - 1] != replacedFrame.prev) {
            insertedFrame = dragonBones.BaseObject.borrowObject(dragonBones.AnimationFrameData);
            insertedFrame.position = frameStart / this._armature.frameRate;
            frames[frameStart] = insertedFrame;
            for (var i = frameStart + 1, l = frames.length; i < l; ++i) replacedFrame && frames[i] == replacedFrame && (frames[i] = null);
          } else insertedFrame = replacedFrame;
          if (actions) for (var i = 0, l = actions.length; i < l; ++i) insertedFrame.actions.push(actions[i]);
          if (events) for (var i = 0, l = events.length; i < l; ++i) insertedFrame.events.push(events[i]);
          var prevFrame = null;
          var nextFrame = null;
          for (var i = 0, l = frames.length; i < l; ++i) {
            var currentFrame = frames[i];
            if (currentFrame && nextFrame != currentFrame) {
              nextFrame = currentFrame;
              if (prevFrame) {
                nextFrame.prev = prevFrame;
                prevFrame.next = nextFrame;
                prevFrame.duration = nextFrame.position - prevFrame.position;
              }
              prevFrame = nextFrame;
            } else frames[i] = prevFrame;
          }
          nextFrame.duration = this._animation.duration - nextFrame.position;
          nextFrame = frames[0];
          prevFrame.next = nextFrame;
          nextFrame.prev = prevFrame;
        };
        DataParser.parseDragonBonesData = function(rawData) {
          return dragonBones.ObjectDataParser.getInstance().parseDragonBonesData(rawData);
        };
        DataParser.parseTextureAtlasData = function(rawData, scale) {
          void 0 === scale && (scale = 1);
          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";
        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.ARMATURE = "armature";
        DataParser.BONE = "bone";
        DataParser.IK = "ik";
        DataParser.SLOT = "slot";
        DataParser.SKIN = "skin";
        DataParser.DISPLAY = "display";
        DataParser.ANIMATION = "animation";
        DataParser.Z_ORDER = "zOrder";
        DataParser.FFD = "ffd";
        DataParser.FRAME = "frame";
        DataParser.EVENTS = "events";
        DataParser.ACTIONS = "actions";
        DataParser.INTS = "ints";
        DataParser.FLOATS = "floats";
        DataParser.STRINGS = "strings";
        DataParser.PIVOT = "pivot";
        DataParser.TRANSFORM = "transform";
        DataParser.AABB = "aabb";
        DataParser.COLOR = "color";
        DataParser.FILTER = "filter";
        DataParser.VERSION = "version";
        DataParser.IS_GLOBAL = "isGlobal";
        DataParser.FRAME_RATE = "frameRate";
        DataParser.TYPE = "type";
        DataParser.SUB_TYPE = "subType";
        DataParser.NAME = "name";
        DataParser.PARENT = "parent";
        DataParser.SHARE = "share";
        DataParser.LENGTH = "length";
        DataParser.DATA = "data";
        DataParser.DISPLAY_INDEX = "displayIndex";
        DataParser.BLEND_MODE = "blendMode";
        DataParser.INHERIT_TRANSLATION = "inheritTranslation";
        DataParser.INHERIT_ROTATION = "inheritRotation";
        DataParser.INHERIT_SCALE = "inheritScale";
        DataParser.INHERIT_ANIMATION = "inheritAnimation";
        DataParser.TARGET = "target";
        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.CURVE = "curve";
        DataParser.GUIDE_CURVE = "guideCurve";
        DataParser.EVENT = "event";
        DataParser.SOUND = "sound";
        DataParser.ACTION = "action";
        DataParser.DEFAULT_ACTIONS = "defaultActions";
        DataParser.X = "x";
        DataParser.Y = "y";
        DataParser.SKEW_X = "skX";
        DataParser.SKEW_Y = "skY";
        DataParser.SCALE_X = "scX";
        DataParser.SCALE_Y = "scY";
        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.TWEEN = "tween";
        DataParser.KEY = "key";
        DataParser.COLOR_TRANSFORM = "colorTransform";
        DataParser.TIMELINE = "timeline";
        DataParser.PIVOT_X = "pX";
        DataParser.PIVOT_Y = "pY";
        DataParser.Z = "z";
        DataParser.LOOP = "loop";
        DataParser.AUTO_TWEEN = "autoTween";
        DataParser.HIDE = "hide";
        return DataParser;
      })();
      dragonBones.DataParser = DataParser;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var ObjectDataParser = (function(_super) {
        __extends(ObjectDataParser, _super);
        function ObjectDataParser() {
          _super.call(this);
        }
        ObjectDataParser._getBoolean = function(rawData, key, defaultValue) {
          if (key in rawData) {
            var value = rawData[key];
            var valueType = typeof value;
            if ("boolean" == valueType) return value;
            if ("string" != valueType) return !!value;
            switch (value) {
             case "0":
             case "NaN":
             case "":
             case "false":
             case "null":
             case "undefined":
              return false;

             default:
              return true;
            }
          }
          return defaultValue;
        };
        ObjectDataParser._getNumber = function(rawData, key, defaultValue) {
          if (key in rawData) {
            var value = rawData[key];
            if (null == value || "NaN" == value) return defaultValue;
            return +value || 0;
          }
          return defaultValue;
        };
        ObjectDataParser._getString = function(rawData, key, defaultValue) {
          if (key in rawData) return String(rawData[key]);
          return defaultValue;
        };
        ObjectDataParser._getParameter = function(rawData, index, defaultValue) {
          if (rawData.length > index) return rawData[index];
          return defaultValue;
        };
        ObjectDataParser.prototype._parseArmature = function(rawData, scale) {
          var armature = dragonBones.BaseObject.borrowObject(dragonBones.ArmatureData);
          armature.name = ObjectDataParser._getString(rawData, ObjectDataParser.NAME, null);
          armature.frameRate = ObjectDataParser._getNumber(rawData, ObjectDataParser.FRAME_RATE, this._data.frameRate) || this._data.frameRate;
          armature.scale = scale;
          ObjectDataParser.TYPE in rawData && "string" == typeof rawData[ObjectDataParser.TYPE] ? armature.type = ObjectDataParser._getArmatureType(rawData[ObjectDataParser.TYPE]) : armature.type = ObjectDataParser._getNumber(rawData, ObjectDataParser.TYPE, 0);
          this._armature = armature;
          this._rawBones.length = 0;
          if (ObjectDataParser.AABB in rawData) {
            var aabbObject = rawData[ObjectDataParser.AABB];
            armature.aabb.x = ObjectDataParser._getNumber(aabbObject, ObjectDataParser.X, 0);
            armature.aabb.y = ObjectDataParser._getNumber(aabbObject, ObjectDataParser.Y, 0);
            armature.aabb.width = ObjectDataParser._getNumber(aabbObject, ObjectDataParser.WIDTH, 0);
            armature.aabb.height = ObjectDataParser._getNumber(aabbObject, ObjectDataParser.HEIGHT, 0);
          }
          if (ObjectDataParser.BONE in rawData) {
            var bones = rawData[ObjectDataParser.BONE];
            for (var i = 0, l = bones.length; i < l; ++i) {
              var boneObject = bones[i];
              var bone = this._parseBone(boneObject);
              armature.addBone(bone, ObjectDataParser._getString(boneObject, ObjectDataParser.PARENT, null));
              this._rawBones.push(bone);
            }
          }
          if (ObjectDataParser.IK in rawData) {
            var iks = rawData[ObjectDataParser.IK];
            for (var i = 0, l = iks.length; i < l; ++i) this._parseIK(iks[i]);
          }
          if (ObjectDataParser.SLOT in rawData) {
            var slots = rawData[ObjectDataParser.SLOT];
            var zOrder = 0;
            for (var i = 0, l = slots.length; i < l; ++i) armature.addSlot(this._parseSlot(slots[i], zOrder++));
          }
          if (ObjectDataParser.SKIN in rawData) {
            var skins = rawData[ObjectDataParser.SKIN];
            for (var i = 0, l = skins.length; i < l; ++i) armature.addSkin(this._parseSkin(skins[i]));
          }
          if (ObjectDataParser.ANIMATION in rawData) {
            var animations = rawData[ObjectDataParser.ANIMATION];
            for (var i = 0, l = animations.length; i < l; ++i) armature.addAnimation(this._parseAnimation(animations[i]));
          }
          (ObjectDataParser.ACTIONS in rawData || ObjectDataParser.DEFAULT_ACTIONS in rawData) && this._parseActionData(rawData, armature.actions, null, null);
          this._isOldData && this._isGlobalTransform && this._globalToLocal(armature);
          this._armature = null;
          this._rawBones.length = 0;
          return armature;
        };
        ObjectDataParser.prototype._parseBone = function(rawData) {
          var bone = dragonBones.BaseObject.borrowObject(dragonBones.BoneData);
          bone.name = ObjectDataParser._getString(rawData, ObjectDataParser.NAME, null);
          bone.inheritTranslation = ObjectDataParser._getBoolean(rawData, ObjectDataParser.INHERIT_TRANSLATION, true);
          bone.inheritRotation = ObjectDataParser._getBoolean(rawData, ObjectDataParser.INHERIT_ROTATION, true);
          bone.inheritScale = ObjectDataParser._getBoolean(rawData, ObjectDataParser.INHERIT_SCALE, true);
          bone.length = ObjectDataParser._getNumber(rawData, ObjectDataParser.LENGTH, 0) * this._armature.scale;
          ObjectDataParser.TRANSFORM in rawData && this._parseTransform(rawData[ObjectDataParser.TRANSFORM], bone.transform);
          this._isOldData && (bone.inheritScale = false);
          return bone;
        };
        ObjectDataParser.prototype._parseIK = function(rawData) {
          var bone = this._armature.getBone(ObjectDataParser._getString(rawData, ObjectDataParser.BONE in rawData ? ObjectDataParser.BONE : ObjectDataParser.NAME, null));
          if (bone) {
            bone.ik = this._armature.getBone(ObjectDataParser._getString(rawData, ObjectDataParser.TARGET, null));
            bone.bendPositive = ObjectDataParser._getBoolean(rawData, ObjectDataParser.BEND_POSITIVE, true);
            bone.chain = ObjectDataParser._getNumber(rawData, ObjectDataParser.CHAIN, 0);
            bone.weight = ObjectDataParser._getNumber(rawData, ObjectDataParser.WEIGHT, 1);
            if (bone.chain > 0 && bone.parent && !bone.parent.ik) {
              bone.parent.ik = bone.ik;
              bone.parent.chainIndex = 0;
              bone.parent.chain = 0;
              bone.chainIndex = 1;
            } else {
              bone.chain = 0;
              bone.chainIndex = 0;
            }
          }
        };
        ObjectDataParser.prototype._parseSlot = function(rawData, zOrder) {
          var slot = dragonBones.BaseObject.borrowObject(dragonBones.SlotData);
          slot.name = ObjectDataParser._getString(rawData, ObjectDataParser.NAME, null);
          slot.parent = this._armature.getBone(ObjectDataParser._getString(rawData, ObjectDataParser.PARENT, null));
          slot.displayIndex = ObjectDataParser._getNumber(rawData, ObjectDataParser.DISPLAY_INDEX, 0);
          slot.zOrder = ObjectDataParser._getNumber(rawData, ObjectDataParser.Z, zOrder);
          if (ObjectDataParser.COLOR in rawData || ObjectDataParser.COLOR_TRANSFORM in rawData) {
            slot.color = dragonBones.SlotData.generateColor();
            this._parseColorTransform(rawData[ObjectDataParser.COLOR] || rawData[ObjectDataParser.COLOR_TRANSFORM], slot.color);
          } else slot.color = dragonBones.SlotData.DEFAULT_COLOR;
          ObjectDataParser.BLEND_MODE in rawData && "string" == typeof rawData[ObjectDataParser.BLEND_MODE] ? slot.blendMode = ObjectDataParser._getBlendMode(rawData[ObjectDataParser.BLEND_MODE]) : slot.blendMode = ObjectDataParser._getNumber(rawData, ObjectDataParser.BLEND_MODE, 0);
          (ObjectDataParser.ACTIONS in rawData || ObjectDataParser.DEFAULT_ACTIONS in rawData) && this._parseActionData(rawData, slot.actions, null, null);
          if (this._isOldData) if (ObjectDataParser.COLOR_TRANSFORM in rawData) {
            slot.color = dragonBones.SlotData.generateColor();
            this._parseColorTransform(rawData[ObjectDataParser.COLOR_TRANSFORM], slot.color);
          } else slot.color = dragonBones.SlotData.DEFAULT_COLOR;
          return slot;
        };
        ObjectDataParser.prototype._parseSkin = function(rawData) {
          var skin = dragonBones.BaseObject.borrowObject(dragonBones.SkinData);
          skin.name = ObjectDataParser._getString(rawData, ObjectDataParser.NAME, "__default") || "__default";
          if (ObjectDataParser.SLOT in rawData) {
            this._skin = skin;
            var slots = rawData[ObjectDataParser.SLOT];
            var zOrder = 0;
            for (var i = 0, l = slots.length; i < l; ++i) {
              this._isOldData && this._armature.addSlot(this._parseSlot(slots[i], zOrder++));
              skin.addSlot(this._parseSlotDisplaySet(slots[i]));
            }
            this._skin = null;
          }
          return skin;
        };
        ObjectDataParser.prototype._parseSlotDisplaySet = function(rawData) {
          var slotDisplayDataSet = dragonBones.BaseObject.borrowObject(dragonBones.SlotDisplayDataSet);
          slotDisplayDataSet.slot = this._armature.getSlot(ObjectDataParser._getString(rawData, ObjectDataParser.NAME, null));
          if (ObjectDataParser.DISPLAY in rawData) {
            var displayObjectSet = rawData[ObjectDataParser.DISPLAY];
            var displayDataSet = slotDisplayDataSet.displays;
            this._slotDisplayDataSet = slotDisplayDataSet;
            for (var i = 0, l = displayObjectSet.length; i < l; ++i) displayDataSet.push(this._parseDisplay(displayObjectSet[i]));
            this._slotDisplayDataSet = null;
          }
          return slotDisplayDataSet;
        };
        ObjectDataParser.prototype._parseDisplay = function(rawData) {
          var display = dragonBones.BaseObject.borrowObject(dragonBones.DisplayData);
          display.name = ObjectDataParser._getString(rawData, ObjectDataParser.NAME, null);
          display.path = ObjectDataParser._getString(rawData, ObjectDataParser.SHARE, display.name);
          display.inheritAnimation = ObjectDataParser._getBoolean(rawData, ObjectDataParser.INHERIT_ANIMATION, true);
          ObjectDataParser.TYPE in rawData && "string" == typeof rawData[ObjectDataParser.TYPE] ? display.type = ObjectDataParser._getDisplayType(rawData[ObjectDataParser.TYPE]) : display.type = ObjectDataParser._getNumber(rawData, ObjectDataParser.TYPE, 0);
          display.isRelativePivot = true;
          if (ObjectDataParser.PIVOT in rawData) {
            var pivotObject = rawData[ObjectDataParser.PIVOT];
            display.pivot.x = ObjectDataParser._getNumber(pivotObject, ObjectDataParser.X, 0);
            display.pivot.y = ObjectDataParser._getNumber(pivotObject, ObjectDataParser.Y, 0);
          } else if (this._isOldData) {
            var transformObject = rawData[ObjectDataParser.TRANSFORM];
            display.isRelativePivot = false;
            display.pivot.x = ObjectDataParser._getNumber(transformObject, ObjectDataParser.PIVOT_X, 0) * this._armature.scale;
            display.pivot.y = ObjectDataParser._getNumber(transformObject, ObjectDataParser.PIVOT_Y, 0) * this._armature.scale;
          } else {
            display.pivot.x = .5;
            display.pivot.y = .5;
          }
          ObjectDataParser.TRANSFORM in rawData && this._parseTransform(rawData[ObjectDataParser.TRANSFORM], display.transform);
          switch (display.type) {
           case 0:
           case 1:
            break;

           case 2:
            var shareMeshName = ObjectDataParser._getString(rawData, ObjectDataParser.SHARE, null);
            if (shareMeshName) for (var i = 0, l = this._slotDisplayDataSet.displays.length; i < l; ++i) {
              var eachDisplay = this._slotDisplayDataSet.displays[i];
              if (eachDisplay.name == shareMeshName) {
                display.share = eachDisplay;
                display.mesh = eachDisplay.mesh;
                break;
              }
            } else display.mesh = this._parseMesh(rawData);
            break;

           case 3:
            display.boundingBox = this._BoundingBox(rawData);
          }
          return display;
        };
        ObjectDataParser.prototype._BoundingBox = function(rawData) {
          var boundingBox = dragonBones.BaseObject.borrowObject(dragonBones.BoundingBoxData);
          ObjectDataParser.SUB_TYPE in rawData && "string" == typeof rawData[ObjectDataParser.SUB_TYPE] ? boundingBox.type = ObjectDataParser._getBoundingBoxType(rawData[ObjectDataParser.SUB_TYPE]) : boundingBox.type = ObjectDataParser._getNumber(rawData, ObjectDataParser.SUB_TYPE, 0);
          switch (boundingBox.type) {
           case 0:
           case 1:
            boundingBox.width = ObjectDataParser._getNumber(rawData, ObjectDataParser.WIDTH, 0);
            boundingBox.height = ObjectDataParser._getNumber(rawData, ObjectDataParser.HEIGHT, 0);
            break;

           case 2:
            if (ObjectDataParser.VERTICES in rawData) {
              var rawVertices = rawData[ObjectDataParser.VERTICES];
              boundingBox.vertices.length = rawVertices.length;
              for (var i = 0, l = rawVertices.length; i < l; i += 2) {
                var iN = i + 1;
                var x = rawVertices[i];
                var y = rawVertices[iN];
                boundingBox.vertices[i] = x;
                boundingBox.vertices[iN] = y;
                if (0 == i) {
                  boundingBox.x = x;
                  boundingBox.y = y;
                  boundingBox.width = x;
                  boundingBox.height = y;
                } else {
                  x < boundingBox.x ? boundingBox.x = x : x > boundingBox.width && (boundingBox.width = x);
                  y < boundingBox.y ? boundingBox.y = y : y > boundingBox.height && (boundingBox.height = y);
                }
              }
            }
          }
          return boundingBox;
        };
        ObjectDataParser.prototype._parseMesh = function(rawData) {
          var mesh = dragonBones.BaseObject.borrowObject(dragonBones.MeshData);
          var rawVertices = rawData[ObjectDataParser.VERTICES];
          var rawUVs = rawData[ObjectDataParser.UVS];
          var rawTriangles = rawData[ObjectDataParser.TRIANGLES];
          var numVertices = Math.floor(rawVertices.length / 2);
          var numTriangles = Math.floor(rawTriangles.length / 3);
          var inverseBindPose = new Array(this._armature.sortedBones.length);
          mesh.skinned = ObjectDataParser.WEIGHTS in rawData && rawData[ObjectDataParser.WEIGHTS].length > 0;
          mesh.uvs.length = 2 * numVertices;
          mesh.vertices.length = 2 * numVertices;
          mesh.vertexIndices.length = 3 * numTriangles;
          if (mesh.skinned) {
            mesh.boneIndices.length = numVertices;
            mesh.weights.length = numVertices;
            mesh.boneVertices.length = numVertices;
            if (ObjectDataParser.SLOT_POSE in rawData) {
              var rawSlotPose = rawData[ObjectDataParser.SLOT_POSE];
              mesh.slotPose.a = rawSlotPose[0];
              mesh.slotPose.b = rawSlotPose[1];
              mesh.slotPose.c = rawSlotPose[2];
              mesh.slotPose.d = rawSlotPose[3];
              mesh.slotPose.tx = rawSlotPose[4] * this._armature.scale;
              mesh.slotPose.ty = rawSlotPose[5] * this._armature.scale;
            }
            if (ObjectDataParser.BONE_POSE in rawData) {
              var rawBonePose = rawData[ObjectDataParser.BONE_POSE];
              for (var i = 0, l = rawBonePose.length; i < l; i += 7) {
                var rawBoneIndex = rawBonePose[i];
                var boneMatrix = inverseBindPose[rawBoneIndex] = new dragonBones.Matrix();
                boneMatrix.a = rawBonePose[i + 1];
                boneMatrix.b = rawBonePose[i + 2];
                boneMatrix.c = rawBonePose[i + 3];
                boneMatrix.d = rawBonePose[i + 4];
                boneMatrix.tx = rawBonePose[i + 5] * this._armature.scale;
                boneMatrix.ty = rawBonePose[i + 6] * this._armature.scale;
                boneMatrix.invert();
              }
            }
          }
          for (var i = 0, iW = 0, l = rawVertices.length; i < l; i += 2) {
            var iN = i + 1;
            var vertexIndex = i / 2;
            var x = mesh.vertices[i] = rawVertices[i] * this._armature.scale;
            var y = mesh.vertices[iN] = rawVertices[iN] * this._armature.scale;
            mesh.uvs[i] = rawUVs[i];
            mesh.uvs[iN] = rawUVs[iN];
            if (mesh.skinned) {
              var rawWeights = rawData[ObjectDataParser.WEIGHTS];
              var numBones = rawWeights[iW];
              var indices = mesh.boneIndices[vertexIndex] = new Array(numBones);
              var weights = mesh.weights[vertexIndex] = new Array(numBones);
              var boneVertices = mesh.boneVertices[vertexIndex] = new Array(2 * numBones);
              mesh.slotPose.transformPoint(x, y, this._helpPoint);
              x = mesh.vertices[i] = this._helpPoint.x;
              y = mesh.vertices[iN] = this._helpPoint.y;
              for (var iB = 0; iB < numBones; ++iB) {
                var iI = iW + 1 + 2 * iB;
                var rawBoneIndex = rawWeights[iI];
                var boneData = this._rawBones[rawBoneIndex];
                var boneIndex = mesh.bones.indexOf(boneData);
                if (boneIndex < 0) {
                  boneIndex = mesh.bones.length;
                  mesh.bones[boneIndex] = boneData;
                  mesh.inverseBindPose[boneIndex] = inverseBindPose[rawBoneIndex];
                }
                mesh.inverseBindPose[boneIndex].transformPoint(x, y, this._helpPoint);
                indices[iB] = boneIndex;
                weights[iB] = rawWeights[iI + 1];
                boneVertices[2 * iB] = this._helpPoint.x;
                boneVertices[2 * iB + 1] = this._helpPoint.y;
              }
              iW += 2 * numBones + 1;
            }
          }
          for (var i = 0, l = rawTriangles.length; i < l; ++i) mesh.vertexIndices[i] = rawTriangles[i];
          return mesh;
        };
        ObjectDataParser.prototype._parseAnimation = function(rawData) {
          var animation = dragonBones.BaseObject.borrowObject(dragonBones.AnimationData);
          animation.name = ObjectDataParser._getString(rawData, ObjectDataParser.NAME, "__default") || "__default";
          animation.frameCount = Math.max(ObjectDataParser._getNumber(rawData, ObjectDataParser.DURATION, 1), 1);
          animation.position = ObjectDataParser._getNumber(rawData, ObjectDataParser.POSITION, 0) / this._armature.frameRate;
          animation.duration = animation.frameCount / this._armature.frameRate;
          animation.playTimes = ObjectDataParser._getNumber(rawData, ObjectDataParser.PLAY_TIMES, 1);
          animation.fadeInTime = ObjectDataParser._getNumber(rawData, ObjectDataParser.FADE_IN_TIME, 0);
          this._animation = animation;
          var animationName = ObjectDataParser._getString(rawData, ObjectDataParser.ANIMATION, null);
          if (animationName) {
            animation.animation = this._armature.getAnimation(animationName);
            !animation.animation;
            return animation;
          }
          this._parseTimeline(rawData, animation, this._parseAnimationFrame);
          if (ObjectDataParser.Z_ORDER in rawData) {
            animation.zOrderTimeline = dragonBones.BaseObject.borrowObject(dragonBones.ZOrderTimelineData);
            this._parseTimeline(rawData[ObjectDataParser.Z_ORDER], animation.zOrderTimeline, this._parseZOrderFrame);
          }
          if (ObjectDataParser.BONE in rawData) {
            var boneTimelines = rawData[ObjectDataParser.BONE];
            for (var i = 0, l = boneTimelines.length; i < l; ++i) animation.addBoneTimeline(this._parseBoneTimeline(boneTimelines[i]));
          }
          if (ObjectDataParser.SLOT in rawData) {
            var slotTimelines = rawData[ObjectDataParser.SLOT];
            for (var i = 0, l = slotTimelines.length; i < l; ++i) animation.addSlotTimeline(this._parseSlotTimeline(slotTimelines[i]));
          }
          if (ObjectDataParser.FFD in rawData) {
            var ffdTimelines = rawData[ObjectDataParser.FFD];
            for (var i = 0, l = ffdTimelines.length; i < l; ++i) animation.addFFDTimeline(this._parseFFDTimeline(ffdTimelines[i]));
          }
          if (this._isOldData) {
            this._isAutoTween = ObjectDataParser._getBoolean(rawData, ObjectDataParser.AUTO_TWEEN, true);
            this._animationTweenEasing = ObjectDataParser._getNumber(rawData, ObjectDataParser.TWEEN_EASING, 0) || 0;
            animation.playTimes = ObjectDataParser._getNumber(rawData, ObjectDataParser.LOOP, 1);
            if (ObjectDataParser.TIMELINE in rawData) {
              var timelineObjects = rawData[ObjectDataParser.TIMELINE];
              for (var i = 0, l = timelineObjects.length; i < l; ++i) {
                var timelineObject = timelineObjects[i];
                animation.addBoneTimeline(this._parseBoneTimeline(timelineObject));
                animation.addSlotTimeline(this._parseSlotTimeline(timelineObject));
              }
            }
          } else {
            this._isAutoTween = false;
            this._animationTweenEasing = 0;
          }
          for (var i in this._armature.bones) {
            var bone = this._armature.bones[i];
            if (!animation.getBoneTimeline(bone.name)) {
              var boneTimeline = dragonBones.BaseObject.borrowObject(dragonBones.BoneTimelineData);
              var boneFrame = dragonBones.BaseObject.borrowObject(dragonBones.BoneFrameData);
              boneTimeline.bone = bone;
              boneTimeline.frames[0] = boneFrame;
              animation.addBoneTimeline(boneTimeline);
            }
          }
          for (var i in this._armature.slots) {
            var slot = this._armature.slots[i];
            if (!animation.getSlotTimeline(slot.name)) {
              var slotTimeline = dragonBones.BaseObject.borrowObject(dragonBones.SlotTimelineData);
              var slotFrame = dragonBones.BaseObject.borrowObject(dragonBones.SlotFrameData);
              slotTimeline.slot = slot;
              slotFrame.displayIndex = slot.displayIndex;
              if (slot.color == dragonBones.SlotData.DEFAULT_COLOR) slotFrame.color = dragonBones.SlotFrameData.DEFAULT_COLOR; else {
                slotFrame.color = dragonBones.SlotFrameData.generateColor();
                slotFrame.color.copyFrom(slot.color);
              }
              slotTimeline.frames[0] = slotFrame;
              animation.addSlotTimeline(slotTimeline);
              this._isOldData && (slotFrame.displayIndex = -1);
            }
          }
          this._animation = null;
          return animation;
        };
        ObjectDataParser.prototype._parseBoneTimeline = function(rawData) {
          var timeline = dragonBones.BaseObject.borrowObject(dragonBones.BoneTimelineData);
          timeline.bone = this._armature.getBone(ObjectDataParser._getString(rawData, ObjectDataParser.NAME, null));
          this._parseTimeline(rawData, timeline, this._parseBoneFrame);
          var originalTransform = timeline.originalTransform;
          var prevFrame = null;
          for (var i = 0, l = timeline.frames.length; i < l; ++i) {
            var frame = timeline.frames[i];
            if (prevFrame) prevFrame != frame && frame.transform.minus(originalTransform); else {
              originalTransform.copyFrom(frame.transform);
              frame.transform.identity();
              0 == originalTransform.scaleX && (originalTransform.scaleX = .001);
              0 == originalTransform.scaleY && (originalTransform.scaleY = .001);
            }
            prevFrame = frame;
          }
          1 == timeline.scale && 0 == timeline.offset || (this._animation.hasAsynchronyTimeline = true);
          if (this._isOldData && (ObjectDataParser.PIVOT_X in rawData || ObjectDataParser.PIVOT_Y in rawData)) {
            this._timelinePivot.x = ObjectDataParser._getNumber(rawData, ObjectDataParser.PIVOT_X, 0);
            this._timelinePivot.y = ObjectDataParser._getNumber(rawData, ObjectDataParser.PIVOT_Y, 0);
          } else this._timelinePivot.clear();
          return timeline;
        };
        ObjectDataParser.prototype._parseSlotTimeline = function(rawData) {
          var timeline = dragonBones.BaseObject.borrowObject(dragonBones.SlotTimelineData);
          timeline.slot = this._armature.getSlot(ObjectDataParser._getString(rawData, ObjectDataParser.NAME, null));
          this._parseTimeline(rawData, timeline, this._parseSlotFrame);
          1 == timeline.scale && 0 == timeline.offset || (this._animation.hasAsynchronyTimeline = true);
          return timeline;
        };
        ObjectDataParser.prototype._parseFFDTimeline = function(rawData) {
          var timeline = dragonBones.BaseObject.borrowObject(dragonBones.FFDTimelineData);
          timeline.skin = this._armature.getSkin(ObjectDataParser._getString(rawData, ObjectDataParser.SKIN, null));
          timeline.slot = timeline.skin.getSlot(ObjectDataParser._getString(rawData, ObjectDataParser.SLOT, null));
          var meshName = ObjectDataParser._getString(rawData, ObjectDataParser.NAME, null);
          for (var i = 0, l = timeline.slot.displays.length; i < l; ++i) {
            var display = timeline.slot.displays[i];
            if (display.mesh && display.name == meshName) {
              timeline.display = display;
              break;
            }
          }
          this._parseTimeline(rawData, timeline, this._parseFFDFrame);
          return timeline;
        };
        ObjectDataParser.prototype._parseAnimationFrame = function(rawData, frameStart, frameCount) {
          var frame = dragonBones.BaseObject.borrowObject(dragonBones.AnimationFrameData);
          this._parseFrame(rawData, frame, frameStart, frameCount);
          (ObjectDataParser.ACTION in rawData || ObjectDataParser.ACTIONS in rawData) && this._parseActionData(rawData, frame.actions, null, null);
          (ObjectDataParser.EVENT in rawData || ObjectDataParser.SOUND in rawData) && this._parseEventData(rawData, frame.events, null, null);
          return frame;
        };
        ObjectDataParser.prototype._parseZOrderFrame = function(rawData, frameStart, frameCount) {
          var frame = dragonBones.BaseObject.borrowObject(dragonBones.ZOrderFrameData);
          this._parseFrame(rawData, frame, frameStart, frameCount);
          var rawZOrder = rawData[ObjectDataParser.Z_ORDER];
          if (rawZOrder && rawZOrder.length > 0) {
            var slotCount = this._armature.sortedSlots.length;
            var unchanged = new Array(slotCount - rawZOrder.length / 2);
            frame.zOrder.length = slotCount;
            for (var i_4 = 0; i_4 < slotCount; ++i_4) frame.zOrder[i_4] = -1;
            var originalIndex = 0;
            var unchangedIndex = 0;
            for (var i_5 = 0, l = rawZOrder.length; i_5 < l; i_5 += 2) {
              var slotIndex = rawZOrder[i_5];
              var offset = rawZOrder[i_5 + 1];
              while (originalIndex != slotIndex) unchanged[unchangedIndex++] = originalIndex++;
              frame.zOrder[originalIndex + offset] = originalIndex++;
            }
            while (originalIndex < slotCount) unchanged[unchangedIndex++] = originalIndex++;
            var i = slotCount;
            while (i--) -1 == frame.zOrder[i] && (frame.zOrder[i] = unchanged[--unchangedIndex]);
          }
          return frame;
        };
        ObjectDataParser.prototype._parseBoneFrame = function(rawData, frameStart, frameCount) {
          var frame = dragonBones.BaseObject.borrowObject(dragonBones.BoneFrameData);
          frame.tweenRotate = ObjectDataParser._getNumber(rawData, ObjectDataParser.TWEEN_ROTATE, 0);
          frame.tweenScale = ObjectDataParser._getBoolean(rawData, ObjectDataParser.TWEEN_SCALE, true);
          this._parseTweenFrame(rawData, frame, frameStart, frameCount);
          if (ObjectDataParser.TRANSFORM in rawData) {
            var transformObject = rawData[ObjectDataParser.TRANSFORM];
            this._parseTransform(transformObject, frame.transform);
            if (this._isOldData) {
              this._helpPoint.x = this._timelinePivot.x + ObjectDataParser._getNumber(transformObject, ObjectDataParser.PIVOT_X, 0);
              this._helpPoint.y = this._timelinePivot.y + ObjectDataParser._getNumber(transformObject, ObjectDataParser.PIVOT_Y, 0);
              frame.transform.toMatrix(this._helpMatrix);
              this._helpMatrix.transformPoint(this._helpPoint.x, this._helpPoint.y, this._helpPoint, true);
              frame.transform.x += this._helpPoint.x;
              frame.transform.y += this._helpPoint.y;
            }
          }
          var bone = this._timeline.bone;
          var actions = new Array();
          var events = new Array();
          if (ObjectDataParser.ACTION in rawData || ObjectDataParser.ACTIONS in rawData) {
            var slot = this._armature.getSlot(bone.name);
            this._parseActionData(rawData, actions, bone, slot);
          }
          (ObjectDataParser.EVENT in rawData || ObjectDataParser.SOUND in rawData) && this._parseEventData(rawData, events, bone, null);
          (actions.length > 0 || events.length > 0) && this._mergeFrameToAnimationTimeline(frame.position, actions, events);
          return frame;
        };
        ObjectDataParser.prototype._parseSlotFrame = function(rawData, frameStart, frameCount) {
          var frame = dragonBones.BaseObject.borrowObject(dragonBones.SlotFrameData);
          frame.displayIndex = ObjectDataParser._getNumber(rawData, ObjectDataParser.DISPLAY_INDEX, 0);
          this._parseTweenFrame(rawData, frame, frameStart, frameCount);
          if (ObjectDataParser.COLOR in rawData || ObjectDataParser.COLOR_TRANSFORM in rawData) {
            frame.color = dragonBones.SlotFrameData.generateColor();
            this._parseColorTransform(rawData[ObjectDataParser.COLOR] || rawData[ObjectDataParser.COLOR_TRANSFORM], frame.color);
          } else frame.color = dragonBones.SlotFrameData.DEFAULT_COLOR;
          if (this._isOldData) ObjectDataParser._getBoolean(rawData, ObjectDataParser.HIDE, false) && (frame.displayIndex = -1); else if (ObjectDataParser.ACTION in rawData || ObjectDataParser.ACTIONS in rawData) {
            var slot = this._timeline.slot;
            var actions = new Array();
            this._parseActionData(rawData, actions, slot.parent, slot);
            this._mergeFrameToAnimationTimeline(frame.position, actions, null);
          }
          return frame;
        };
        ObjectDataParser.prototype._parseFFDFrame = function(rawData, frameStart, frameCount) {
          var ffdTimeline = this._timeline;
          var mesh = ffdTimeline.display.mesh;
          var frame = dragonBones.BaseObject.borrowObject(dragonBones.ExtensionFrameData);
          frame.type = ObjectDataParser._getNumber(rawData, ObjectDataParser.TYPE, 0);
          this._parseTweenFrame(rawData, frame, frameStart, frameCount);
          var rawVertices = rawData[ObjectDataParser.VERTICES];
          var offset = ObjectDataParser._getNumber(rawData, ObjectDataParser.OFFSET, 0);
          var x = 0;
          var y = 0;
          for (var i = 0, l = mesh.vertices.length; i < l; i += 2) {
            if (!rawVertices || i < offset || i - offset >= rawVertices.length) {
              x = 0;
              y = 0;
            } else {
              x = rawVertices[i - offset] * this._armature.scale;
              y = rawVertices[i + 1 - offset] * this._armature.scale;
            }
            if (mesh.skinned) {
              mesh.slotPose.transformPoint(x, y, this._helpPoint, true);
              x = this._helpPoint.x;
              y = this._helpPoint.y;
              var boneIndices = mesh.boneIndices[i / 2];
              for (var iB = 0, lB = boneIndices.length; iB < lB; ++iB) {
                var boneIndex = boneIndices[iB];
                mesh.inverseBindPose[boneIndex].transformPoint(x, y, this._helpPoint, true);
                frame.tweens.push(this._helpPoint.x, this._helpPoint.y);
              }
            } else frame.tweens.push(x, y);
          }
          return frame;
        };
        ObjectDataParser.prototype._parseTweenFrame = function(rawData, frame, frameStart, frameCount) {
          this._parseFrame(rawData, frame, frameStart, frameCount);
          if (frame.duration > 0) {
            ObjectDataParser.TWEEN_EASING in rawData ? frame.tweenEasing = ObjectDataParser._getNumber(rawData, ObjectDataParser.TWEEN_EASING, dragonBones.DragonBones.NO_TWEEN) : this._isOldData ? frame.tweenEasing = this._isAutoTween ? this._animationTweenEasing : dragonBones.DragonBones.NO_TWEEN : frame.tweenEasing = dragonBones.DragonBones.NO_TWEEN;
            this._isOldData && 1 == this._animation.scale && 1 == this._timeline.scale && frame.duration * this._armature.frameRate < 2 && (frame.tweenEasing = dragonBones.DragonBones.NO_TWEEN);
            if (frameCount > 0 && ObjectDataParser.CURVE in rawData) {
              frame.curve = new Array(2 * frameCount - 1);
              dragonBones.TweenFrameData.samplingEasingCurve(rawData[ObjectDataParser.CURVE], frame.curve);
            }
          } else {
            frame.tweenEasing = dragonBones.DragonBones.NO_TWEEN;
            frame.curve = null;
          }
        };
        ObjectDataParser.prototype._parseFrame = function(rawData, frame, frameStart, frameCount) {
          frame.position = frameStart / this._armature.frameRate;
          frame.duration = frameCount / this._armature.frameRate;
        };
        ObjectDataParser.prototype._parseTimeline = function(rawData, timeline, frameParser) {
          timeline.scale = ObjectDataParser._getNumber(rawData, ObjectDataParser.SCALE, 1);
          timeline.offset = ObjectDataParser._getNumber(rawData, ObjectDataParser.OFFSET, 0);
          if (ObjectDataParser.FRAME in rawData) {
            this._timeline = timeline;
            var rawFrames = rawData[ObjectDataParser.FRAME];
            if (1 == rawFrames.length) {
              timeline.frames.length = 1;
              timeline.frames[0] = frameParser.call(this, rawFrames[0], 0, ObjectDataParser._getNumber(rawFrames[0], ObjectDataParser.DURATION, 1));
            } else if (rawFrames.length > 1) {
              timeline.frames.length = this._animation.frameCount + 1;
              var frameStart = 0;
              var frameCount = 0;
              var frame = null;
              var prevFrame = null;
              for (var i = 0, iW = 0, l = timeline.frames.length; i < l; ++i) {
                if (frameStart + frameCount <= i && iW < rawFrames.length) {
                  var frameObject = rawFrames[iW++];
                  frameStart = i;
                  frameCount = ObjectDataParser._getNumber(frameObject, ObjectDataParser.DURATION, 1);
                  frame = frameParser.call(this, frameObject, frameStart, frameCount);
                  if (prevFrame) {
                    prevFrame.next = frame;
                    frame.prev = prevFrame;
                    this._isOldData && prevFrame instanceof dragonBones.TweenFrameData && -1 == ObjectDataParser._getNumber(frameObject, ObjectDataParser.DISPLAY_INDEX, 0) && (prevFrame.tweenEasing = dragonBones.DragonBones.NO_TWEEN);
                  }
                  prevFrame = frame;
                }
                timeline.frames[i] = frame;
              }
              frame.duration = this._animation.duration - frame.position;
              frame = timeline.frames[0];
              prevFrame.next = frame;
              frame.prev = prevFrame;
              this._isOldData && prevFrame instanceof dragonBones.TweenFrameData && -1 == ObjectDataParser._getNumber(rawFrames[0], ObjectDataParser.DISPLAY_INDEX, 0) && (prevFrame.tweenEasing = dragonBones.DragonBones.NO_TWEEN);
            }
            this._timeline = null;
          }
        };
        ObjectDataParser.prototype._parseActionData = function(rawData, actions, bone, slot) {
          var actionsObject = rawData[ObjectDataParser.ACTION] || rawData[ObjectDataParser.ACTIONS] || rawData[ObjectDataParser.DEFAULT_ACTIONS];
          if ("string" == typeof actionsObject) {
            var actionData = dragonBones.BaseObject.borrowObject(dragonBones.ActionData);
            actionData.type = 4;
            actionData.bone = bone;
            actionData.slot = slot;
            actionData.data[0] = actionsObject;
            actionData.data[1] = -1;
            actionData.data[2] = -1;
            actions.push(actionData);
          } else if (actionsObject instanceof Array) for (var i = 0, l = actionsObject.length; i < l; ++i) {
            var actionObject = actionsObject[i];
            var isArray = actionObject instanceof Array;
            var actionData = dragonBones.BaseObject.borrowObject(dragonBones.ActionData);
            var animationName = isArray ? ObjectDataParser._getParameter(actionObject, 1, null) : ObjectDataParser._getString(actionObject, "gotoAndPlay", null);
            if (isArray) {
              var actionType = actionObject[0];
              actionData.type = "string" == typeof actionType ? ObjectDataParser._getActionType(actionType) : ObjectDataParser._getParameter(actionObject, 0, 4);
            } else actionData.type = 2;
            switch (actionData.type) {
             case 0:
              actionData.data[0] = animationName;
              actionData.data[1] = isArray ? ObjectDataParser._getParameter(actionObject, 2, -1) : -1;
              break;

             case 1:
              actionData.data[0] = animationName;
              break;

             case 2:
              actionData.data[0] = animationName;
              actionData.data[1] = isArray ? ObjectDataParser._getParameter(actionObject, 2, 0) : 0;
              actionData.data[2] = isArray ? ObjectDataParser._getParameter(actionObject, 3, -1) : -1;
              break;

             case 3:
              actionData.data[0] = animationName;
              actionData.data[1] = isArray ? ObjectDataParser._getParameter(actionObject, 2, 0) : 0;
              break;

             case 4:
              actionData.data[0] = animationName;
              actionData.data[1] = isArray ? ObjectDataParser._getParameter(actionObject, 2, -1) : -1;
              actionData.data[2] = isArray ? ObjectDataParser._getParameter(actionObject, 3, -1) : -1;
              break;

             case 5:
              actionData.data[0] = animationName;
              actionData.data[1] = isArray ? ObjectDataParser._getParameter(actionObject, 2, 0) : 0;
            }
            actionData.bone = bone;
            actionData.slot = slot;
            actions.push(actionData);
          }
        };
        ObjectDataParser.prototype._parseEventData = function(rawData, events, bone, slot) {
          if (ObjectDataParser.SOUND in rawData) {
            var soundEventData = dragonBones.BaseObject.borrowObject(dragonBones.EventData);
            soundEventData.type = 11;
            soundEventData.name = ObjectDataParser._getString(rawData, ObjectDataParser.SOUND, null);
            soundEventData.bone = bone;
            soundEventData.slot = slot;
            events.push(soundEventData);
          }
          if (ObjectDataParser.EVENT in rawData) {
            var eventData = dragonBones.BaseObject.borrowObject(dragonBones.EventData);
            eventData.type = 10;
            eventData.name = ObjectDataParser._getString(rawData, ObjectDataParser.EVENT, null);
            eventData.bone = bone;
            eventData.slot = slot;
            events.push(eventData);
          }
          if (ObjectDataParser.EVENTS in rawData) {
            var rawEvents = rawData[ObjectDataParser.EVENTS];
            for (var i = 0, l = rawEvents.length; i < l; ++i) {
              var rawEvent = rawEvents[i];
              var boneName = ObjectDataParser._getString(rawEvent, ObjectDataParser.BONE, null);
              var eventData = dragonBones.BaseObject.borrowObject(dragonBones.EventData);
              eventData.type = 10;
              eventData.name = ObjectDataParser._getString(rawEvent, ObjectDataParser.NAME, null);
              eventData.bone = this._armature.getBone(boneName);
              if (ObjectDataParser.INTS in rawEvent) {
                var rawInts = rawEvent[ObjectDataParser.INTS];
                for (var i_6 = 0, l_3 = rawInts.length; i_6 < l_3; ++i_6) eventData.ints.push(ObjectDataParser._getParameter(rawInts, i_6, 0));
              }
              if (ObjectDataParser.FLOATS in rawEvent) {
                var rawFloats = rawEvent[ObjectDataParser.FLOATS];
                for (var i_7 = 0, l_4 = rawFloats.length; i_7 < l_4; ++i_7) eventData.floats.push(ObjectDataParser._getParameter(rawFloats, i_7, 0));
              }
              if (ObjectDataParser.STRINGS in rawEvent) {
                var rawStrings = rawEvent[ObjectDataParser.STRINGS];
                for (var i_8 = 0, l_5 = rawStrings.length; i_8 < l_5; ++i_8) eventData.strings.push(ObjectDataParser._getParameter(rawStrings, i_8, null));
              }
              events.push(eventData);
            }
          }
        };
        ObjectDataParser.prototype._parseTransform = function(rawData, transform) {
          transform.x = ObjectDataParser._getNumber(rawData, ObjectDataParser.X, 0) * this._armature.scale;
          transform.y = ObjectDataParser._getNumber(rawData, ObjectDataParser.Y, 0) * this._armature.scale;
          transform.skewX = ObjectDataParser._getNumber(rawData, ObjectDataParser.SKEW_X, 0) * dragonBones.DragonBones.ANGLE_TO_RADIAN;
          transform.skewY = ObjectDataParser._getNumber(rawData, ObjectDataParser.SKEW_Y, 0) * dragonBones.DragonBones.ANGLE_TO_RADIAN;
          transform.scaleX = ObjectDataParser._getNumber(rawData, ObjectDataParser.SCALE_X, 1);
          transform.scaleY = ObjectDataParser._getNumber(rawData, ObjectDataParser.SCALE_Y, 1);
        };
        ObjectDataParser.prototype._parseColorTransform = function(rawData, color) {
          color.alphaMultiplier = .01 * ObjectDataParser._getNumber(rawData, ObjectDataParser.ALPHA_MULTIPLIER, 100);
          color.redMultiplier = .01 * ObjectDataParser._getNumber(rawData, ObjectDataParser.RED_MULTIPLIER, 100);
          color.greenMultiplier = .01 * ObjectDataParser._getNumber(rawData, ObjectDataParser.GREEN_MULTIPLIER, 100);
          color.blueMultiplier = .01 * ObjectDataParser._getNumber(rawData, ObjectDataParser.BLUE_MULTIPLIER, 100);
          color.alphaOffset = ObjectDataParser._getNumber(rawData, ObjectDataParser.ALPHA_OFFSET, 0);
          color.redOffset = ObjectDataParser._getNumber(rawData, ObjectDataParser.RED_OFFSET, 0);
          color.greenOffset = ObjectDataParser._getNumber(rawData, ObjectDataParser.GREEN_OFFSET, 0);
          color.blueOffset = ObjectDataParser._getNumber(rawData, ObjectDataParser.BLUE_OFFSET, 0);
        };
        ObjectDataParser.prototype.parseDragonBonesData = function(rawData, scale) {
          void 0 === scale && (scale = 1);
          if (rawData) {
            var version = ObjectDataParser._getString(rawData, ObjectDataParser.VERSION, null);
            this._isOldData = version == ObjectDataParser.DATA_VERSION_2_3 || version == ObjectDataParser.DATA_VERSION_3_0;
            this._isOldData ? this._isGlobalTransform = ObjectDataParser._getBoolean(rawData, ObjectDataParser.IS_GLOBAL, true) : this._isGlobalTransform = false;
            if (version == ObjectDataParser.DATA_VERSION || version == ObjectDataParser.DATA_VERSION_4_0 || this._isOldData) {
              var data = dragonBones.BaseObject.borrowObject(dragonBones.DragonBonesData);
              data.name = ObjectDataParser._getString(rawData, ObjectDataParser.NAME, null);
              data.frameRate = ObjectDataParser._getNumber(rawData, ObjectDataParser.FRAME_RATE, 24) || 24;
              if (ObjectDataParser.ARMATURE in rawData) {
                this._data = data;
                var armatures = rawData[ObjectDataParser.ARMATURE];
                for (var i = 0, l = armatures.length; i < l; ++i) data.addArmature(this._parseArmature(armatures[i], scale));
                this._data = null;
              }
              return data;
            }
            throw new Error("Nonsupport data version.");
          }
          throw new Error("No data.");
        };
        ObjectDataParser.prototype.parseTextureAtlasData = function(rawData, textureAtlasData, scale) {
          void 0 === scale && (scale = 0);
          if (!rawData) throw new Error("No data.");
          textureAtlasData.name = ObjectDataParser._getString(rawData, ObjectDataParser.NAME, null);
          textureAtlasData.imagePath = ObjectDataParser._getString(rawData, ObjectDataParser.IMAGE_PATH, null);
          scale > 0 ? textureAtlasData.scale = scale : scale = textureAtlasData.scale = ObjectDataParser._getNumber(rawData, ObjectDataParser.SCALE, textureAtlasData.scale);
          scale = 1 / scale;
          if (ObjectDataParser.SUB_TEXTURE in rawData) {
            var textures = rawData[ObjectDataParser.SUB_TEXTURE];
            for (var i = 0, l = textures.length; i < l; ++i) {
              var textureObject = textures[i];
              var textureData = textureAtlasData.generateTextureData();
              textureData.name = ObjectDataParser._getString(textureObject, ObjectDataParser.NAME, null);
              textureData.rotated = ObjectDataParser._getBoolean(textureObject, ObjectDataParser.ROTATED, false);
              textureData.region.x = ObjectDataParser._getNumber(textureObject, ObjectDataParser.X, 0) * scale;
              textureData.region.y = ObjectDataParser._getNumber(textureObject, ObjectDataParser.Y, 0) * scale;
              textureData.region.width = ObjectDataParser._getNumber(textureObject, ObjectDataParser.WIDTH, 0) * scale;
              textureData.region.height = ObjectDataParser._getNumber(textureObject, ObjectDataParser.HEIGHT, 0) * scale;
              var frameWidth = ObjectDataParser._getNumber(textureObject, ObjectDataParser.FRAME_WIDTH, -1);
              var frameHeight = ObjectDataParser._getNumber(textureObject, ObjectDataParser.FRAME_HEIGHT, -1);
              if (frameWidth > 0 && frameHeight > 0) {
                textureData.frame = dragonBones.TextureData.generateRectangle();
                textureData.frame.x = ObjectDataParser._getNumber(textureObject, ObjectDataParser.FRAME_X, 0) * scale;
                textureData.frame.y = ObjectDataParser._getNumber(textureObject, ObjectDataParser.FRAME_Y, 0) * scale;
                textureData.frame.width = frameWidth * scale;
                textureData.frame.height = frameHeight * scale;
              }
              textureAtlasData.addTexture(textureData);
            }
          }
        };
        ObjectDataParser.getInstance = function() {
          ObjectDataParser._instance || (ObjectDataParser._instance = new ObjectDataParser());
          return ObjectDataParser._instance;
        };
        ObjectDataParser._instance = null;
        return ObjectDataParser;
      })(dragonBones.DataParser);
      dragonBones.ObjectDataParser = ObjectDataParser;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var TextureAtlasData = (function(_super) {
        __extends(TextureAtlasData, _super);
        function TextureAtlasData() {
          _super.call(this);
          this.textures = {};
        }
        TextureAtlasData.prototype._onClear = function() {
          for (var i in this.textures) {
            this.textures[i].returnToPool();
            delete this.textures[i];
          }
          this.autoSearch = false;
          this.scale = 1;
          this.name = null;
          this.imagePath = null;
        };
        TextureAtlasData.prototype.addTexture = function(value) {
          if (!value || !value.name || this.textures[value.name]) throw new Error();
          this.textures[value.name] = value;
          value.parent = this;
        };
        TextureAtlasData.prototype.getTexture = function(name) {
          return this.textures[name];
        };
        return TextureAtlasData;
      })(dragonBones.BaseObject);
      dragonBones.TextureAtlasData = TextureAtlasData;
      var TextureData = (function(_super) {
        __extends(TextureData, _super);
        function TextureData() {
          _super.call(this);
          this.region = new dragonBones.Rectangle();
        }
        TextureData.generateRectangle = function() {
          return new dragonBones.Rectangle();
        };
        TextureData.prototype._onClear = function() {
          this.rotated = false;
          this.name = null;
          this.frame = null;
          this.parent = null;
          this.region.clear();
        };
        return TextureData;
      })(dragonBones.BaseObject);
      dragonBones.TextureData = TextureData;
    })(dragonBones || (dragonBones = {}));
    var dragonBones;
    (function(dragonBones) {
      var BaseFactory = (function() {
        function BaseFactory(dataParser) {
          void 0 === dataParser && (dataParser = null);
          this.autoSearch = false;
          this._dataParser = null;
          this._dragonBonesDataMap = {};
          this._textureAtlasDataMap = {};
          this._dataParser = dataParser;
          if (!this._dataParser) {
            BaseFactory._defaultParser || (BaseFactory._defaultParser = new dragonBones.ObjectDataParser());
            this._dataParser = BaseFactory._defaultParser;
          }
        }
        BaseFactory.prototype._getTextureData = function(textureAtlasName, textureName) {
          var textureAtlasDataList = this._textureAtlasDataMap[textureAtlasName];
          if (textureAtlasDataList) for (var i = 0, l = textureAtlasDataList.length; i < l; ++i) {
            var textureData = textureAtlasDataList[i].getTexture(textureName);
            if (textureData) return textureData;
          }
          if (this.autoSearch) for (var i in this._textureAtlasDataMap) {
            textureAtlasDataList = this._textureAtlasDataMap[i];
            for (var j = 0, lJ = textureAtlasDataList.length; j < lJ; ++j) {
              var textureAtlasData = textureAtlasDataList[j];
              if (textureAtlasData.autoSearch) {
                var textureData = textureAtlasData.getTexture(textureName);
                if (textureData) return textureData;
              }
            }
          }
          return null;
        };
        BaseFactory.prototype._fillBuildArmaturePackage = function(dataPackage, dragonBonesName, armatureName, skinName, textureAtlasName) {
          var dragonBonesData = null;
          var armatureData = null;
          if (dragonBonesName) {
            dragonBonesData = this._dragonBonesDataMap[dragonBonesName];
            dragonBonesData && (armatureData = dragonBonesData.getArmature(armatureName));
          }
          if (!armatureData && (!dragonBonesName || this.autoSearch)) for (var eachDragonBonesName in this._dragonBonesDataMap) {
            dragonBonesData = this._dragonBonesDataMap[eachDragonBonesName];
            if (!dragonBonesName || dragonBonesData.autoSearch) {
              armatureData = dragonBonesData.getArmature(armatureName);
              if (armatureData) {
                dragonBonesName = eachDragonBonesName;
                break;
              }
            }
          }
          if (armatureData) {
            dataPackage.dataName = dragonBonesName;
            dataPackage.textureAtlasName = textureAtlasName;
            dataPackage.data = dragonBonesData;
            dataPackage.armature = armatureData;
            dataPackage.skin = armatureData.getSkin(skinName);
            dataPackage.skin || (dataPackage.skin = armatureData.defaultSkin);
            return true;
          }
          return false;
        };
        BaseFactory.prototype._buildBones = function(dataPackage, armature) {
          var bones = dataPackage.armature.sortedBones;
          for (var i = 0, l = bones.length; i < l; ++i) {
            var boneData = bones[i];
            var bone = dragonBones.BaseObject.borrowObject(dragonBones.Bone);
            bone.name = boneData.name;
            bone.inheritTranslation = boneData.inheritTranslation;
            bone.inheritRotation = boneData.inheritRotation;
            bone.inheritScale = boneData.inheritScale;
            bone.length = boneData.length;
            bone.origin.copyFrom(boneData.transform);
            boneData.parent ? armature.addBone(bone, boneData.parent.name) : armature.addBone(bone);
            if (boneData.ik) {
              bone.ikBendPositive = boneData.bendPositive;
              bone.ikWeight = boneData.weight;
              bone._setIK(armature.getBone(boneData.ik.name), boneData.chain, boneData.chainIndex);
            }
          }
        };
        BaseFactory.prototype._buildSlots = function(dataPackage, armature) {
          var currentSkin = dataPackage.skin;
          var defaultSkin = dataPackage.armature.defaultSkin;
          var slotDisplayDataSetMap = {};
          for (var i in defaultSkin.slots) {
            var slotDisplayDataSet = defaultSkin.slots[i];
            slotDisplayDataSetMap[slotDisplayDataSet.slot.name] = slotDisplayDataSet;
          }
          if (currentSkin != defaultSkin) for (var i in currentSkin.slots) {
            var slotDisplayDataSet = currentSkin.slots[i];
            slotDisplayDataSetMap[slotDisplayDataSet.slot.name] = slotDisplayDataSet;
          }
          var slots = dataPackage.armature.sortedSlots;
          for (var i = 0, l = slots.length; i < l; ++i) {
            var slotData = slots[i];
            var slotDisplayDataSet = slotDisplayDataSetMap[slotData.name];
            if (!slotDisplayDataSet) continue;
            var slot = this._generateSlot(dataPackage, slotDisplayDataSet, armature);
            if (slot) {
              slot._displayDataSet = slotDisplayDataSet;
              slot._setDisplayIndex(slotData.displayIndex);
              slot._setBlendMode(slotData.blendMode);
              slot._setColor(slotData.color);
              armature.addSlot(slot, slotData.parent.name);
            }
          }
        };
        BaseFactory.prototype._replaceSlotDisplay = function(dataPackage, displayData, slot, displayIndex) {
          displayIndex < 0 && (displayIndex = slot.displayIndex);
          if (displayIndex >= 0) {
            var displayList = slot.displayList;
            displayList.length <= displayIndex && (displayList.length = displayIndex + 1);
            slot._replacedDisplayDataSet.length <= displayIndex && (slot._replacedDisplayDataSet.length = displayIndex + 1);
            slot._replacedDisplayDataSet[displayIndex] = displayData;
            if (1 == displayData.type) {
              var childArmature = this.buildArmature(displayData.path, dataPackage.dataName, null, dataPackage.textureAtlasName);
              displayList[displayIndex] = childArmature;
            } else {
              displayData.texture && !dataPackage.textureAtlasName || (displayData.texture = this._getTextureData(dataPackage.textureAtlasName || dataPackage.dataName, displayData.path));
              displayData.mesh || displayIndex < slot._displayDataSet.displays.length && slot._displayDataSet.displays[displayIndex].mesh ? displayList[displayIndex] = slot.meshDisplay : displayList[displayIndex] = slot.rawDisplay;
            }
            slot.displayList = displayList;
            slot.invalidUpdate();
          }
        };
        BaseFactory.prototype.parseDragonBonesData = function(rawData, name, scale) {
          void 0 === name && (name = null);
          void 0 === scale && (scale = 1);
          var dragonBonesData = this._dataParser.parseDragonBonesData(rawData, scale);
          this.addDragonBonesData(dragonBonesData, name);
          return dragonBonesData;
        };
        BaseFactory.prototype.parseTextureAtlasData = function(rawData, textureAtlas, name, scale) {
          void 0 === name && (name = null);
          void 0 === scale && (scale = 0);
          var textureAtlasData = this._generateTextureAtlasData(null, null);
          this._dataParser.parseTextureAtlasData(rawData, textureAtlasData, scale);
          this._generateTextureAtlasData(textureAtlasData, textureAtlas);
          this.addTextureAtlasData(textureAtlasData, name);
          return textureAtlasData;
        };
        BaseFactory.prototype.getDragonBonesData = function(name) {
          return this._dragonBonesDataMap[name];
        };
        BaseFactory.prototype.addDragonBonesData = function(data, name) {
          void 0 === name && (name = null);
          if (!data) throw new Error();
          name = name || data.name;
          name ? this._dragonBonesDataMap[name] ? console.warn("Same name data.", name) : this._dragonBonesDataMap[name] = data : console.warn("Unnamed data.");
        };
        BaseFactory.prototype.removeDragonBonesData = function(name, disposeData) {
          void 0 === disposeData && (disposeData = true);
          var dragonBonesData = this._dragonBonesDataMap[name];
          if (dragonBonesData) {
            if (disposeData) {
              if (dragonBones.DragonBones.debug) for (var i = 0, l = dragonBones.DragonBones._armatures.length; i < l; ++i) {
                var armature = dragonBones.DragonBones._armatures[i];
                if (armature.armatureData.parent == dragonBonesData) throw new Error("ArmatureData: " + armature.armatureData.name + " DragonBonesData: " + name);
              }
              dragonBonesData.returnToPool();
            }
            delete this._dragonBonesDataMap[name];
          }
        };
        BaseFactory.prototype.getTextureAtlasData = function(name) {
          return this._textureAtlasDataMap[name];
        };
        BaseFactory.prototype.addTextureAtlasData = function(data, name) {
          void 0 === name && (name = null);
          if (!data) throw new Error();
          name = name || data.name;
          if (name) {
            var textureAtlasList = this._textureAtlasDataMap[name] = this._textureAtlasDataMap[name] || [];
            textureAtlasList.indexOf(data) < 0 && textureAtlasList.push(data);
          } else console.warn("Unnamed data.");
        };
        BaseFactory.prototype.removeTextureAtlasData = function(name, disposeData) {
          void 0 === disposeData && (disposeData = true);
          var textureAtlasDataList = this._textureAtlasDataMap[name];
          if (textureAtlasDataList) {
            if (disposeData) for (var i = 0, l = textureAtlasDataList.length; i < l; ++i) textureAtlasDataList[i].returnToPool();
            delete this._textureAtlasDataMap[name];
          }
        };
        BaseFactory.prototype.clear = function(disposeData) {
          void 0 === disposeData && (disposeData = true);
          for (var i in this._dragonBonesDataMap) {
            disposeData && this._dragonBonesDataMap[i].returnToPool();
            delete this._dragonBonesDataMap[i];
          }
          for (var i in this._textureAtlasDataMap) {
            if (disposeData) {
              var textureAtlasDataList = this._textureAtlasDataMap[i];
              for (var i_9 = 0, l = textureAtlasDataList.length; i_9 < l; ++i_9) textureAtlasDataList[i_9].returnToPool();
            }
            delete this._textureAtlasDataMap[i];
          }
        };
        BaseFactory.prototype.buildArmature = function(armatureName, dragonBonesName, skinName, textureAtlasName) {
          void 0 === dragonBonesName && (dragonBonesName = null);
          void 0 === skinName && (skinName = null);
          void 0 === textureAtlasName && (textureAtlasName = null);
          var dataPackage = {};
          if (this._fillBuildArmaturePackage(dataPackage, dragonBonesName, armatureName, skinName, textureAtlasName)) {
            var armature = this._generateArmature(dataPackage);
            this._buildBones(dataPackage, armature);
            this._buildSlots(dataPackage, armature);
            armature.advanceTime(0);
            return armature;
          }
          console.warn("No armature data.", armatureName, dragonBonesName || "");
          return null;
        };
        BaseFactory.prototype.copyAnimationsToArmature = function(toArmature, fromArmatreName, fromSkinName, fromDragonBonesDataName, ifRemoveOriginalAnimationList) {
          void 0 === fromSkinName && (fromSkinName = null);
          void 0 === fromDragonBonesDataName && (fromDragonBonesDataName = null);
          void 0 === ifRemoveOriginalAnimationList && (ifRemoveOriginalAnimationList = true);
          var dataPackage = {};
          if (this._fillBuildArmaturePackage(dataPackage, fromDragonBonesDataName, fromArmatreName, fromSkinName, null)) {
            var fromArmatureData = dataPackage.armature;
            if (ifRemoveOriginalAnimationList) toArmature.animation.animations = fromArmatureData.animations; else {
              var animations = {};
              for (var animationName in toArmature.animation.animations) animations[animationName] = toArmature.animation.animations[animationName];
              for (var animationName in fromArmatureData.animations) animations[animationName] = fromArmatureData.animations[animationName];
              toArmature.animation.animations = animations;
            }
            if (dataPackage.skin) {
              var slots = toArmature.getSlots();
              for (var i = 0, l = slots.length; i < l; ++i) {
                var toSlot = slots[i];
                var toSlotDisplayList = toSlot.displayList;
                for (var i_10 = 0, l_6 = toSlotDisplayList.length; i_10 < l_6; ++i_10) {
                  var toDisplayObject = toSlotDisplayList[i_10];
                  if (toDisplayObject instanceof dragonBones.Armature) {
                    var displays = dataPackage.skin.getSlot(toSlot.name).displays;
                    if (i_10 < displays.length) {
                      var fromDisplayData = displays[i_10];
                      1 == fromDisplayData.type && this.copyAnimationsToArmature(toDisplayObject, fromDisplayData.path, fromSkinName, fromDragonBonesDataName, ifRemoveOriginalAnimationList);
                    }
                  }
                }
              }
              return true;
            }
          }
          return false;
        };
        BaseFactory.prototype.replaceSlotDisplay = function(dragonBonesName, armatureName, slotName, displayName, slot, displayIndex) {
          void 0 === displayIndex && (displayIndex = -1);
          var dataPackage = {};
          if (this._fillBuildArmaturePackage(dataPackage, dragonBonesName, armatureName, null, null)) {
            var slotDisplayDataSet = dataPackage.skin.getSlot(slotName);
            if (slotDisplayDataSet) for (var i = 0, l = slotDisplayDataSet.displays.length; i < l; ++i) {
              var displayData = slotDisplayDataSet.displays[i];
              if (displayData.path == displayName) {
                this._replaceSlotDisplay(dataPackage, displayData, slot, displayIndex);
                break;
              }
            }
          }
        };
        BaseFactory.prototype.replaceSlotDisplayList = function(dragonBonesName, armatureName, slotName, slot) {
          var dataPackage = {};
          if (this._fillBuildArmaturePackage(dataPackage, dragonBonesName, armatureName, null, null)) {
            var slotDisplayDataSet = dataPackage.skin.getSlot(slotName);
            if (slotDisplayDataSet) {
              var displayIndex = 0;
              for (var i = 0, l = slotDisplayDataSet.displays.length; i < l; ++i) {
                var displayData = slotDisplayDataSet.displays[i];
                this._replaceSlotDisplay(dataPackage, displayData, slot, displayIndex++);
              }
            }
          }
        };
        BaseFactory.prototype.getAllDragonBonesData = function() {
          return this._dragonBonesDataMap;
        };
        BaseFactory.prototype.getAllTextureAtlasData = function() {
          return this._textureAtlasDataMap;
        };
        BaseFactory._defaultParser = null;
        return BaseFactory;
      })();
      dragonBones.BaseFactory = BaseFactory;
    })(dragonBones || (dragonBones = {}));
    module.exports = dragonBones;
  }), {} ],
  300: [ (function(require, module, exports) {
    var spine = sp.spine;
    sp._SGSkeleton = _ccsg.Node.extend({
      _skeleton: null,
      _rootBone: null,
      _timeScale: 1,
      _debugSlots: false,
      _debugBones: false,
      _premultipliedAlpha: false,
      _ownsSkeletonData: null,
      _atlas: null,
      ctor: function(skeletonDataFile, atlasFile, scale) {
        _ccsg.Node.prototype.ctor.call(this);
        0 === arguments.length ? this.init() : this.initWithArgs(skeletonDataFile, atlasFile, scale);
      },
      _createRenderCmd: function() {
        return cc._renderType === cc.game.RENDER_TYPE_CANVAS ? new sp._SGSkeleton.CanvasRenderCmd(this) : new sp._SGSkeleton.WebGLRenderCmd(this);
      },
      init: function() {
        _ccsg.Node.prototype.init.call(this);
        this._premultipliedAlpha = cc._renderType === cc.game.RENDER_TYPE_WEBGL && cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA;
        this.scheduleUpdate();
      },
      setDebugSlotsEnabled: function(enabled) {
        this._debugSlots = enabled;
      },
      getDebugSlotsEnabled: function() {
        return this._debugSlots;
      },
      setDebugBonesEnabled: function(enabled) {
        this._debugBones = enabled;
      },
      getDebugBonesEnabled: function() {
        return this._debugBones;
      },
      setTimeScale: function(scale) {
        this._timeScale = scale;
      },
      getTimeScale: function() {
        return this._timeScale;
      },
      initWithArgs: function(skeletonDataFile, atlasFile, scale) {
        var argSkeletonFile = skeletonDataFile, argAtlasFile = atlasFile, skeletonData, atlas, ownsSkeletonData;
        if (cc.js.isString(argSkeletonFile)) {
          if (cc.js.isString(argAtlasFile)) {
            var data = cc.loader.getRes(argAtlasFile);
            sp._atlasLoader.setAtlasFile(argAtlasFile);
            atlas = new spine.TextureAtlas(data, sp._atlasLoader.load.bind(sp._atlasLoader));
          } else atlas = atlasFile;
          scale = scale || 1 / cc.director.getContentScaleFactor();
          var attachmentLoader = new spine.AtlasAttachmentLoader(atlas);
          var skeletonJsonReader = new spine.SkeletonJson(attachmentLoader);
          skeletonJsonReader.scale = scale;
          var skeletonJson = cc.loader.getRes(argSkeletonFile);
          skeletonData = skeletonJsonReader.readSkeletonData(skeletonJson);
          atlas.dispose(skeletonJsonReader);
          ownsSkeletonData = true;
        } else {
          skeletonData = skeletonDataFile;
          ownsSkeletonData = atlasFile;
        }
        this.setSkeletonData(skeletonData, ownsSkeletonData);
        this.init();
      },
      getBoundingBox: function() {
        var minX = cc.macro.FLT_MAX, minY = cc.macro.FLT_MAX, maxX = cc.macro.FLT_MIN, maxY = cc.macro.FLT_MIN;
        var scaleX = this.getScaleX(), scaleY = this.getScaleY(), vertices, slots = this._skeleton.slots, VERTEX = spine.RegionAttachment;
        for (var i = 0, slotCount = slots.length; i < slotCount; ++i) {
          var slot = slots[i];
          var attachment = slot.attachment;
          if (!attachment || !(attachment instanceof spine.RegionAttachment)) continue;
          vertices = attachment.updateWorldVertices(slot, false);
          minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX);
          minY = Math.min(minY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY);
          maxX = Math.max(maxX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX);
          maxY = Math.max(maxY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY);
        }
        var position = this.getPosition();
        return cc.rect(position.x + minX, position.y + minY, maxX - minX, maxY - minY);
      },
      updateWorldTransform: function() {
        this._skeleton.updateWorldTransform();
      },
      setToSetupPose: function() {
        this._skeleton.setToSetupPose();
      },
      setBonesToSetupPose: function() {
        this._skeleton.setBonesToSetupPose();
      },
      setSlotsToSetupPose: function() {
        this._skeleton.setSlotsToSetupPose();
      },
      findBone: function(boneName) {
        return this._skeleton.findBone(boneName);
      },
      findSlot: function(slotName) {
        return this._skeleton.findSlot(slotName);
      },
      setSkin: function(skinName) {
        return this._skeleton.setSkinByName(skinName);
      },
      getAttachment: function(slotName, attachmentName) {
        return this._skeleton.getAttachmentByName(slotName, attachmentName);
      },
      setAttachment: function(slotName, attachmentName) {
        this._skeleton.setAttachment(slotName, attachmentName);
      },
      setPremultipliedAlpha: function(premultiplied) {
        this._premultipliedAlpha = premultiplied;
      },
      isPremultipliedAlpha: function() {
        return this._premultipliedAlpha;
      },
      setSkeletonData: function(skeletonData, ownsSkeletonData) {
        null != skeletonData.width && null != skeletonData.height && this.setContentSize(skeletonData.width / cc.director.getContentScaleFactor(), skeletonData.height / cc.director.getContentScaleFactor());
        this._skeleton = new spine.Skeleton(skeletonData);
        this._skeleton.updateWorldTransform();
        this._rootBone = this._skeleton.getRootBone();
        this._ownsSkeletonData = ownsSkeletonData;
        this._renderCmd._createChildFormSkeletonData();
      },
      getTextureAtlas: function(regionAttachment) {
        return regionAttachment.region;
      },
      getBlendFunc: function() {
        var slot = this._skeleton.drawOrder[0];
        if (slot) {
          var blend = this._renderCmd._getBlendFunc(slot.data.blendMode, this._premultipliedAlpha);
          return blend;
        }
        return {};
      },
      setBlendFunc: function(src, dst) {
        return;
      },
      update: function(dt) {
        this._skeleton.update(dt);
      }
    });
    var proto = sp._SGSkeleton.prototype;
    Object.defineProperty(proto, "opacityModifyRGB", {
      get: proto.isOpacityModifyRGB
    });
    Object.defineProperty(proto, "_blendFunc", {
      get: proto.getBlendFunc
    });
    Object.defineProperty(proto, "_texture", {
      get: function() {
        return this._renderCmd._currTexture;
      }
    });
  }), {} ],
  301: [ (function(require, module, exports) {
    var spine = sp.spine;
    var animEventType = sp.AnimationEventType;
    sp._atlasLoader = {
      spAtlasFile: null,
      setAtlasFile: function(spAtlasFile) {
        this.spAtlasFile = spAtlasFile;
      },
      load: function(line) {
        var texturePath = cc.path.join(cc.path.dirname(this.spAtlasFile), line);
        var texture = cc.textureCache.addImage(texturePath);
        var tex = new sp.SkeletonTexture({
          width: texture.getPixelWidth(),
          height: texture.getPixelHeight()
        });
        tex.setRealTexture(texture);
        return tex;
      },
      unload: function(obj) {}
    };
    sp.TrackEntryListeners = function(startListener, endListener, completeListener, eventListener, interruptListener, disposeListener) {
      this.startListener = startListener || null;
      this.endListener = endListener || null;
      this.completeListener = completeListener || null;
      this.eventListener = eventListener || null;
      this.interruptListener = interruptListener || null;
      this.disposeListener = disposeListener || null;
      this.callback = null;
      this.callbackTarget = null;
      this.skeletonNode = null;
    };
    var proto = sp.TrackEntryListeners.prototype;
    proto.start = function(trackEntry) {
      this.startListener && this.startListener(trackEntry);
      this.callback && this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.START, null, 0);
    };
    proto.interrupt = function(trackEntry) {
      this.interruptListener && this.interruptListener(trackEntry);
      this.callback && this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.INTERRUPT, null, 0);
    };
    proto.end = function(trackEntry) {
      this.endListener && this.endListener(trackEntry);
      this.callback && this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.END, null, 0);
    };
    proto.dispose = function(trackEntry) {
      this.disposeListener && this.disposeListener(trackEntry);
      this.callback && this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.DISPOSE, null, 0);
    };
    proto.complete = function(trackEntry) {
      var loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd);
      this.completeListener && this.completeListener(trackEntry, loopCount);
      this.callback && this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.COMPLETE, null, loopCount);
    };
    proto.event = function(trackEntry, event) {
      this.eventListener && this.eventListener(trackEntry, event);
      this.callback && this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, animEventType.EVENT, event, 0);
    };
    sp.TrackEntryListeners.getListeners = function(entry) {
      entry.listener || (entry.listener = new sp.TrackEntryListeners());
      return entry.listener;
    };
    sp._SGSkeletonAnimation = sp._SGSkeleton.extend({
      _state: null,
      _ownsAnimationStateData: false,
      _listener: null,
      init: function() {
        sp._SGSkeleton.prototype.init.call(this);
        this._ownsAnimationStateData = true;
        this.setAnimationStateData(new spine.AnimationStateData(this._skeleton.data));
      },
      setAnimationStateData: function(stateData) {
        var state = new spine.AnimationState(stateData);
        this._listener = new sp.TrackEntryListeners();
        state.rendererObject = this;
        state.addListener(this._listener);
        this._state = state;
      },
      setMix: function(fromAnimation, toAnimation, duration) {
        this._state.data.setMixWith(fromAnimation, toAnimation, duration);
      },
      setAnimationListener: function(target, callback) {
        this._listener.callbackTarget = target;
        this._listener.callback = callback;
        this._listener.skeletonNode = this;
      },
      setAnimation: function(trackIndex, name, loop) {
        var animation = this._skeleton.data.findAnimation(name);
        if (!animation) {
          cc.logID(7509, name);
          return null;
        }
        return this._state.setAnimationWith(trackIndex, animation, loop);
      },
      addAnimation: function(trackIndex, name, loop, delay) {
        delay = null == delay ? 0 : delay;
        var animation = this._skeleton.data.findAnimation(name);
        if (!animation) {
          cc.logID(7510, name);
          return null;
        }
        return this._state.addAnimationWith(trackIndex, animation, loop, delay);
      },
      findAnimation: function(name) {
        return this._skeleton.data.findAnimation(name);
      },
      getCurrent: function(trackIndex) {
        return this._state.getCurrent(trackIndex);
      },
      clearTracks: function() {
        this._state.clearTracks();
      },
      clearTrack: function(trackIndex) {
        this._state.clearTrack(trackIndex);
      },
      update: function(dt) {
        this._super(dt);
        dt *= this._timeScale;
        this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
        this._state.update(dt);
        this._state.apply(this._skeleton);
        this._skeleton.updateWorldTransform();
        this._renderCmd._updateChild();
      },
      setStartListener: function(listener) {
        this._listener.startListener = listener;
      },
      setInterruptListener: function(listener) {
        this._listener.interruptListener = listener;
      },
      setEndListener: function(listener) {
        this._listener.endListener = listener;
      },
      setDisposeListener: function(listener) {
        this._listener.disposeListener = listener;
      },
      setCompleteListener: function(listener) {
        this._listener.completeListener = listener;
      },
      setEventListener: function(listener) {
        this._listener.eventListener = listener;
      },
      setTrackStartListener: function(entry, listener) {
        sp.TrackEntryListeners.getListeners(entry).startListener = listener;
      },
      setTrackInterruptListener: function(entry, listener) {
        sp.TrackEntryListeners.getListeners(entry).interruptListener = listener;
      },
      setTrackEndListener: function(entry, listener) {
        sp.TrackEntryListeners.getListeners(entry).endListener = listener;
      },
      setTrackDisposeListener: function(entry, listener) {
        sp.TrackEntryListeners.getListeners(entry).disposeListener = listener;
      },
      setTrackCompleteListener: function(entry, listener) {
        sp.TrackEntryListeners.getListeners(entry).completeListener = listener;
      },
      setTrackEventListener: function(entry, listener) {
        sp.TrackEntryListeners.getListeners(entry).eventListener = listener;
      },
      getState: function() {
        return this._state;
      }
    });
  }), {} ],
  302: [ (function(require, module, exports) {
    require("../../cocos2d/core/CCDrawingPrimitives");
    var spine = sp.spine;
    sp._SGSkeleton.CanvasRenderCmd = function(renderableObject) {
      this._rootCtor(renderableObject);
      this._needDraw = true;
    };
    var proto = sp._SGSkeleton.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
    proto.constructor = sp._SGSkeleton.CanvasRenderCmd;
    proto.rendering = function(wrapper, scaleX, scaleY) {
      var node = this._node, i, n, slot, slotNode;
      wrapper = wrapper || cc._renderContext;
      var locSkeleton = node._skeleton, drawOrder = locSkeleton.drawOrder;
      for (i = 0, n = drawOrder.length; i < n; i++) {
        slot = drawOrder[i];
        slotNode = slot._slotNode;
        if (slotNode._visible && slotNode._renderCmd && slot.currentSprite) {
          slotNode._renderCmd.transform(this, true);
          slot.currentSprite._renderCmd.rendering(wrapper, scaleX, scaleY);
          slotNode._renderCmd._dirtyFlag = slot.currentSprite._renderCmd._dirtyFlag = 0;
        }
      }
      if (!node._debugSlots && !node._debugBones) return;
      wrapper.setTransform(this._worldTransform, scaleX, scaleY);
      wrapper.setGlobalAlpha(1);
      var attachment, drawingUtil = cc._drawingUtil;
      if (node._debugSlots) {
        drawingUtil.setDrawColor(0, 0, 255, 255);
        drawingUtil.setLineWidth(1);
        var points = [];
        for (i = 0, n = locSkeleton.slots.length; i < n; i++) {
          slot = locSkeleton.drawOrder[i];
          if (!slot.attachment || !(slot.attachment instanceof spine.RegionAttachment)) continue;
          attachment = slot.attachment;
          this._updateRegionAttachmentSlot(attachment, slot, points);
          drawingUtil.drawPoly(points, 4, true);
        }
      }
      if (node._debugBones) {
        var bone;
        drawingUtil.setLineWidth(2);
        drawingUtil.setDrawColor(255, 0, 0, 255);
        for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
          bone = locSkeleton.bones[i];
          var x = bone.data.length * bone.a + bone.worldX;
          var y = bone.data.length * bone.c + bone.worldY;
          drawingUtil.drawLine({
            x: bone.worldX,
            y: bone.worldY
          }, {
            x: x,
            y: y
          });
        }
        drawingUtil.setPointSize(4);
        drawingUtil.setDrawColor(0, 0, 255, 255);
        for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
          bone = locSkeleton.bones[i];
          drawingUtil.drawPoint({
            x: bone.worldX,
            y: bone.worldY
          });
          0 === i && drawingUtil.setDrawColor(0, 255, 0, 255);
        }
      }
    };
    proto.updateStatus = function() {
      this.originUpdateStatus();
      this._updateCurrentRegions();
      this._regionFlag = _ccsg.Node.CanvasRenderCmd.RegionStatus.DirtyDouble;
      this._dirtyFlag &= ~_ccsg.Node._dirtyFlags.contentDirty;
    };
    proto.getLocalBB = function() {
      return this._node.getBoundingBox();
    };
    proto._updateRegionAttachmentSlot = function(attachment, slot, points) {
      if (!points) return;
      var vertices = attachment.updateWorldVertices(slot, false);
      var VERTEX = spine.RegionAttachment;
      points.length = 0;
      points.push(cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1]));
      points.push(cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4]));
      points.push(cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3]));
      points.push(cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2]));
    };
    proto._createChildFormSkeletonData = function() {
      var node = this._node;
      var locSkeleton = node._skeleton, spriteName, sprite;
      for (var i = 0, n = locSkeleton.slots.length; i < n; i++) {
        var slot = locSkeleton.slots[i], attachment = slot.attachment;
        var slotNode = new _ccsg.Node();
        slot._slotNode = slotNode;
        if (attachment instanceof spine.RegionAttachment) {
          spriteName = attachment.region.name;
          sprite = this._createSprite(slot, attachment);
          slot.currentSprite = sprite;
          slot.currentSpriteName = spriteName;
          slotNode.addChild(sprite);
        } else attachment instanceof spine.MeshAttachment;
      }
    };
    proto._createSprite = function(slot, attachment) {
      var rendererObject = attachment.region;
      var texture = rendererObject.texture.getRealTexture();
      var rect = new cc.Rect(rendererObject.x, rendererObject.y, rendererObject.width, rendererObject.height);
      var sprite = new _ccsg.Sprite();
      sprite.initWithTexture(texture, rect, rendererObject.rotate, false);
      sprite._rect.width = attachment.width;
      sprite._rect.height = attachment.height;
      sprite.setContentSize(attachment.width, attachment.height);
      sprite.setRotation(-attachment.rotation);
      sprite.setScale(rendererObject.width / rendererObject.originalWidth * attachment.scaleX, rendererObject.height / rendererObject.originalHeight * attachment.scaleY);
      slot.sprites = slot.sprites || {};
      slot.sprites[rendererObject.name] = sprite;
      return sprite;
    };
    proto._updateChild = function() {
      var locSkeleton = this._node._skeleton, slots = locSkeleton.slots;
      var color = this._displayedColor, opacity = this._displayedOpacity;
      var i, n, selSprite, ax, ay;
      var slot, attachment, slotNode;
      for (i = 0, n = slots.length; i < n; i++) {
        slot = slots[i];
        attachment = slot.attachment;
        slotNode = slot._slotNode;
        if (!attachment) {
          slotNode.setVisible(false);
          continue;
        }
        if (attachment instanceof spine.RegionAttachment) {
          if (attachment.region && (!slot.currentSpriteName || slot.currentSpriteName !== attachment.name)) {
            var spriteName = attachment.region.name;
            void 0 !== slot.currentSprite && slot.currentSprite.setVisible(false);
            slot.sprites = slot.sprites || {};
            if (void 0 !== slot.sprites[spriteName]) slot.sprites[spriteName].setVisible(true); else {
              var sprite = this._createSprite(slot, attachment);
              slotNode.addChild(sprite);
            }
            slot.currentSprite = slot.sprites[spriteName];
            slot.currentSpriteName = spriteName;
          }
          var bone = slot.bone;
          if (0 === attachment.region.offsetX && 0 === attachment.region.offsetY) {
            ax = attachment.x;
            ay = attachment.y;
          } else {
            ax = .5 * (attachment.offset[0] + attachment.offset[4]);
            ay = .5 * (attachment.offset[1] + attachment.offset[5]);
          }
          slotNode.setPosition(bone.worldX + ax * bone.a + ay * bone.b, bone.worldY + ax * bone.c + ay * bone.d);
          slotNode.setScale(bone.getWorldScaleX(), bone.getWorldScaleY());
          selSprite = slot.currentSprite;
          selSprite._flippedX = bone.skeleton.flipX;
          selSprite._flippedY = bone.skeleton.flipY;
          if (selSprite._flippedY || selSprite._flippedX) {
            slotNode.setRotation(bone.getWorldRotationX());
            selSprite.setRotation(attachment.rotation);
          } else {
            slotNode.setRotation(-bone.getWorldRotationX());
            selSprite.setRotation(-attachment.rotation);
          }
          selSprite._renderCmd._displayedOpacity = 0 | opacity * slot.color.a;
          var r = 0 | color.r * slot.color.r, g = 0 | color.g * slot.color.g, b = 0 | color.b * slot.color.b;
          selSprite.setColor(cc.color(r, g, b));
          selSprite._renderCmd._updateColor();
        } else if (!(attachment instanceof spine.MeshAttachment)) {
          slotNode.setVisible(false);
          continue;
        }
        slotNode.setVisible(true);
      }
    };
  }), {
    "../../cocos2d/core/CCDrawingPrimitives": 36
  } ],
  303: [ (function(require, module, exports) {
    sp.SkeletonTexture = cc.Class({
      name: "sp.SkeletonTexture",
      extends: sp.spine.Texture,
      _texture: null,
      setRealTexture: function(tex) {
        this._texture = tex;
      },
      getRealTexture: function() {
        return this._texture;
      },
      setFilters: function(minFilter, magFilter) {
        if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
          var gl = cc._renderContext;
          this.bind();
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
        }
      },
      setWraps: function(uWrap, vWrap) {
        if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
          var gl = cc._renderContext;
          this.bind();
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, uWrap);
          gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, vWrap);
        }
      },
      dispose: function() {},
      bind: function() {
        cc._renderType === cc.game.RENDER_TYPE_WEBGL && cc.gl.bindTexture2DN(0, this._texture);
      }
    });
  }), {} ],
  304: [ (function(require, module, exports) {
    require("../../cocos2d/core/CCDrawingPrimitives");
    var spine = sp.spine;
    sp._SGSkeleton.WebGLRenderCmd = function(renderableObject) {
      this._rootCtor(renderableObject);
      this._needDraw = true;
      this._matrix = new cc.math.Matrix4();
      this._matrix.identity();
      this._currTexture = null;
      this._currBlendFunc = {};
      this.vertexType = cc.renderer.VertexType.CUSTOM;
      this.setShaderProgram(cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLOR));
    };
    var proto = sp._SGSkeleton.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype);
    proto.constructor = sp._SGSkeleton.WebGLRenderCmd;
    proto.uploadData = function(f32buffer, ui32buffer, vertexDataOffset) {
      var node = this._node;
      var color = this._displayedColor, locSkeleton = node._skeleton;
      var attachment, slot, i, n;
      var premultiAlpha = node._premultipliedAlpha;
      locSkeleton.r = color.r / 255;
      locSkeleton.g = color.g / 255;
      locSkeleton.b = color.b / 255;
      locSkeleton.a = this._displayedOpacity / 255;
      if (premultiAlpha) {
        locSkeleton.r *= locSkeleton.a;
        locSkeleton.g *= locSkeleton.a;
        locSkeleton.b *= locSkeleton.a;
      }
      var debugSlotsInfo = null;
      this._node._debugSlots && (debugSlotsInfo = []);
      for (i = 0, n = locSkeleton.drawOrder.length; i < n; i++) {
        slot = locSkeleton.drawOrder[i];
        if (!slot.attachment) continue;
        attachment = slot.attachment;
        var vertCount = 0;
        if (attachment instanceof spine.RegionAttachment) vertCount = 6; else {
          if (!(attachment instanceof spine.MeshAttachment)) continue;
          vertCount = attachment.regionUVs.length / 2;
        }
        if (0 === vertCount) continue;
        var regionTextureAtlas = node.getTextureAtlas(attachment);
        this._currTexture = regionTextureAtlas.texture.getRealTexture();
        var batchBroken = cc.renderer._updateBatchedInfo(this._currTexture, this._getBlendFunc(slot.data.blendMode, premultiAlpha), this._shaderProgram);
        if (!batchBroken && vertexDataOffset + 6 * vertCount > f32buffer.length) {
          cc.renderer._batchRendering();
          batchBroken = true;
        }
        batchBroken && (vertexDataOffset = 0);
        var slotDebugPoints = null;
        if (attachment instanceof spine.RegionAttachment) slotDebugPoints = this._uploadRegionAttachmentData(attachment, slot, premultiAlpha, f32buffer, ui32buffer, vertexDataOffset); else {
          if (!(attachment instanceof spine.MeshAttachment)) continue;
          this._uploadMeshAttachmentData(attachment, slot, premultiAlpha, f32buffer, ui32buffer, vertexDataOffset);
        }
        this._node._debugSlots && (debugSlotsInfo[i] = slotDebugPoints);
        attachment instanceof spine.RegionAttachment ? cc.renderer._increaseBatchingSize(vertCount, cc.renderer.VertexType.TRIANGLE) : cc.renderer._increaseBatchingSize(vertCount, cc.renderer.VertexType.CUSTOM, attachment.triangles);
        vertexDataOffset += 6 * vertCount;
      }
      if (node._debugBones || node._debugSlots) {
        cc.renderer._batchRendering();
        var wt = this._worldTransform, mat = this._matrix.mat;
        mat[0] = wt.a;
        mat[4] = wt.c;
        mat[12] = wt.tx;
        mat[1] = wt.b;
        mat[5] = wt.d;
        mat[13] = wt.ty;
        cc.math.glMatrixMode(cc.math.KM_GL_MODELVIEW);
        cc.current_stack.stack.push(cc.current_stack.top);
        cc.current_stack.top = this._matrix;
        var drawingUtil = cc._drawingUtil;
        if (node._debugSlots && debugSlotsInfo && debugSlotsInfo.length > 0) {
          drawingUtil.setDrawColor(0, 0, 255, 255);
          drawingUtil.setLineWidth(1);
          for (i = 0, n = locSkeleton.slots.length; i < n; i++) {
            var points = debugSlotsInfo[i];
            points && drawingUtil.drawPoly(points, 4, true);
          }
        }
        if (node._debugBones) {
          var bone;
          drawingUtil.setLineWidth(2);
          drawingUtil.setDrawColor(255, 0, 0, 255);
          for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
            bone = locSkeleton.bones[i];
            var x = bone.data.length * bone.a + bone.worldX;
            var y = bone.data.length * bone.c + bone.worldY;
            drawingUtil.drawLine(cc.p(bone.worldX, bone.worldY), cc.p(x, y));
          }
          drawingUtil.setPointSize(4);
          drawingUtil.setDrawColor(0, 0, 255, 255);
          for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
            bone = locSkeleton.bones[i];
            drawingUtil.drawPoint(cc.p(bone.worldX, bone.worldY));
            0 == i && drawingUtil.setDrawColor(0, 255, 0, 255);
          }
        }
        cc.math.glPopMatrix();
      }
      return 0;
    };
    proto._getBlendFunc = function(blendMode, premultiAlpha) {
      var ret = this._currBlendFunc;
      switch (blendMode) {
       case spine.BlendMode.Normal:
        ret.src = premultiAlpha ? cc.macro.ONE : cc.macro.SRC_ALPHA;
        ret.dst = cc.macro.ONE_MINUS_SRC_ALPHA;
        break;

       case spine.BlendMode.Additive:
        ret.src = premultiAlpha ? cc.macro.ONE : cc.macro.SRC_ALPHA;
        ret.dst = cc.macro.ONE;
        break;

       case spine.BlendMode.Multiply:
        ret.src = cc.macro.DST_COLOR;
        ret.dst = cc.macro.ONE_MINUS_SRC_ALPHA;
        break;

       case spine.BlendMode.Screen:
        ret.src = cc.macro.ONE;
        ret.dst = cc.macro.ONE_MINUS_SRC_COLOR;
        break;

       default:
        ret = this._node._blendFunc;
      }
      return ret;
    };
    proto._createChildFormSkeletonData = function() {};
    proto._updateChild = function() {};
    proto._uploadRegionAttachmentData = function(attachment, slot, premultipliedAlpha, f32buffer, ui32buffer, vertexDataOffset) {
      var nodeColor = this._displayedColor;
      var nodeR = nodeColor.r, nodeG = nodeColor.g, nodeB = nodeColor.b, nodeA = this._displayedOpacity;
      var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha);
      var wt = this._worldTransform, wa = wt.a, wb = wt.b, wc = wt.c, wd = wt.d, wx = wt.tx, wy = wt.ty, z = this._node.vertexZ;
      var offset = vertexDataOffset;
      for (var i = 0; i < 6; i++) {
        var srcIdx = i < 4 ? i % 3 : i - 2;
        var vx = vertices[8 * srcIdx], vy = vertices[8 * srcIdx + 1];
        var x = vx * wa + vy * wc + wx, y = vx * wb + vy * wd + wy;
        var r = vertices[8 * srcIdx + 2] * nodeR, g = vertices[8 * srcIdx + 3] * nodeG, b = vertices[8 * srcIdx + 4] * nodeB, a = vertices[8 * srcIdx + 5] * nodeA;
        var color = a << 24 | b << 16 | g << 8 | r;
        f32buffer[offset] = x;
        f32buffer[offset + 1] = y;
        f32buffer[offset + 2] = z;
        ui32buffer[offset + 3] = color;
        f32buffer[offset + 4] = vertices[8 * srcIdx + 6];
        f32buffer[offset + 5] = vertices[8 * srcIdx + 7];
        offset += 6;
      }
      if (this._node._debugSlots) {
        var VERTEX = spine.RegionAttachment;
        return [ cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1]), cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2]), cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3]), cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4]) ];
      }
    };
    proto._uploadMeshAttachmentData = function(attachment, slot, premultipliedAlpha, f32buffer, ui32buffer, vertexDataOffset) {
      var wt = this._worldTransform, wa = wt.a, wb = wt.b, wc = wt.c, wd = wt.d, wx = wt.tx, wy = wt.ty, z = this._node.vertexZ;
      var vertices = attachment.updateWorldVertices(slot, premultipliedAlpha);
      var offset = vertexDataOffset;
      var nodeColor = this._displayedColor;
      var nodeR = nodeColor.r, nodeG = nodeColor.g, nodeB = nodeColor.b, nodeA = this._displayedOpacity;
      for (var i = 0, n = vertices.length; i < n; i += 8) {
        var vx = vertices[i], vy = vertices[i + 1];
        var x = vx * wa + vy * wc + wx, y = vx * wb + vy * wd + wy;
        var r = vertices[i + 2] * nodeR, g = vertices[i + 3] * nodeG, b = vertices[i + 4] * nodeB, a = vertices[i + 5] * nodeA;
        var color = a << 24 | b << 16 | g << 8 | r;
        f32buffer[offset] = x;
        f32buffer[offset + 1] = y;
        f32buffer[offset + 2] = z;
        ui32buffer[offset + 3] = color;
        f32buffer[offset + 4] = vertices[i + 6];
        f32buffer[offset + 5] = vertices[i + 7];
        offset += 6;
      }
    };
  }), {
    "../../cocos2d/core/CCDrawingPrimitives": 36
  } ],
  305: [ (function(require, module, exports) {
    var DefaultSkinsEnum = cc.Enum({
      default: -1
    });
    var DefaultAnimsEnum = cc.Enum({
      "<None>": 0
    });
    function setEnumAttr(obj, propName, enumDef) {
      cc.Class.attr(obj, propName, {
        type: "Enum",
        enumList: cc.Enum.getList(enumDef)
      });
    }
    sp.Skeleton = cc.Class({
      name: "sp.Skeleton",
      extends: cc._RendererUnderSG,
      editor: false,
      properties: {
        _startListener: {
          default: null,
          serializable: false
        },
        _endListener: {
          default: null,
          serializable: false
        },
        _completeListener: {
          default: null,
          serializable: false
        },
        _eventListener: {
          default: null,
          serializable: false
        },
        _disposeListener: {
          default: null,
          serializable: false
        },
        _interruptListener: {
          default: null,
          serializable: false
        },
        _paused: false,
        paused: {
          get: function() {
            return this._paused;
          },
          set: function(value) {
            this._paused = value;
            if (!this._sgNode) return;
            value ? this._sgNode.pause() : this._sgNode.resume();
          },
          visible: false
        },
        skeletonData: {
          default: null,
          type: sp.SkeletonData,
          notify: function() {
            this.defaultSkin = "";
            this.defaultAnimation = "";
            this._refresh();
          },
          tooltip: false
        },
        defaultSkin: {
          default: "",
          visible: false
        },
        defaultAnimation: {
          default: "",
          visible: false
        },
        animation: {
          get: function() {
            var entry = this.getCurrent(0);
            return entry && entry.animation.name || "";
          },
          set: function(value) {
            this.defaultAnimation = value;
            if (value) this.setAnimation(0, value, this.loop); else {
              this.clearTrack(0);
              this.setToSetupPose();
            }
          },
          visible: false
        },
        _defaultSkinIndex: {
          get: function() {
            if (this.skeletonData && this.defaultSkin) {
              var skinsEnum = this.skeletonData.getSkinsEnum();
              if (skinsEnum) {
                var skinIndex = skinsEnum[this.defaultSkin];
                if (void 0 !== skinIndex) return skinIndex;
              }
            }
            return 0;
          },
          set: function(value) {
            var skinsEnum;
            this.skeletonData && (skinsEnum = this.skeletonData.getSkinsEnum());
            if (!skinsEnum) return cc.errorID("", this.name);
            var skinName = skinsEnum[value];
            if (void 0 !== skinName) {
              this.defaultSkin = skinName;
              false;
            } else cc.errorID(7501, this.name);
          },
          type: DefaultSkinsEnum,
          visible: true,
          displayName: "Default Skin",
          tooltip: false
        },
        _animationIndex: {
          get: function() {
            var animationName = this.animation;
            if (this.skeletonData && animationName) {
              var animsEnum = this.skeletonData.getAnimsEnum();
              if (animsEnum) {
                var animIndex = animsEnum[animationName];
                if (void 0 !== animIndex) return animIndex;
              }
            }
            return 0;
          },
          set: function(value) {
            if (0 === value) {
              this.animation = "";
              return;
            }
            var animsEnum;
            this.skeletonData && (animsEnum = this.skeletonData.getAnimsEnum());
            if (!animsEnum) return cc.errorID(7502, this.name);
            var animName = animsEnum[value];
            void 0 !== animName ? this.animation = animName : cc.errorID(7503, this.name);
          },
          type: DefaultAnimsEnum,
          visible: true,
          displayName: "Animation",
          tooltip: false
        },
        loop: {
          default: true,
          tooltip: false
        },
        _premultipliedAlpha: true,
        premultipliedAlpha: {
          get: function() {
            return this._premultipliedAlpha;
          },
          set: function(value) {
            this._premultipliedAlpha = value;
            this._sgNode && this._sgNode.setPremultipliedAlpha(value);
          },
          tooltip: false
        },
        timeScale: {
          default: 1,
          notify: function() {
            this._sgNode && this._sgNode.setTimeScale(this.timeScale);
          },
          tooltip: false
        },
        debugSlots: {
          default: false,
          notify: function() {
            this._sgNode && this._sgNode.setDebugSlotsEnabled(this.debugSlots);
          },
          editorOnly: true,
          tooltip: false
        },
        debugBones: {
          default: false,
          notify: function() {
            this._sgNode && this._sgNode.setDebugBonesEnabled(this.debugBones);
          },
          editorOnly: true,
          tooltip: false
        }
      },
      __preload: function() {
        var Flags;
        false;
        this.node.setContentSize(0, 0);
        this._refresh();
      },
      _createSgNode: function() {
        if (this.skeletonData) {
          var uuid;
          var jsonFile;
          var atlasFile;
          false;
          var data = this.skeletonData.getRuntimeData();
          if (data) try {
            return new sp._SGSkeletonAnimation(data, null, this.skeletonData.scale);
          } catch (e) {
            cc._throw(e);
          }
        }
        return null;
      },
      _initSgNode: function() {
        var sgNode = this._sgNode;
        sgNode.setTimeScale(this.timeScale);
        var self = this;
        sgNode.onEnter = function() {
          _ccsg.Node.prototype.onEnter.call(this);
          self._paused && this.pause();
        };
        this._startListener && this.setStartListener(this._startListener);
        this._endListener && this.setEndListener(this._endListener);
        this._completeListener && this.setCompleteListener(this._completeListener);
        this._eventListener && this.setEventListener(this._eventListener);
        this._interruptListener && this.setInterruptListener(this._interruptListener);
        this._disposeListener && this.setDisposeListener(this._disposeListener);
        if (this.defaultSkin) try {
          sgNode.setSkin(this.defaultSkin);
        } catch (e) {
          cc._throw(e);
        }
        sgNode.setPremultipliedAlpha(this._premultipliedAlpha);
        this.animation = this.defaultAnimation;
        false;
      },
      _getLocalBounds: false,
      updateWorldTransform: function() {
        this._sgNode && this._sgNode.updateWorldTransform();
      },
      setToSetupPose: function() {
        this._sgNode && this._sgNode.setToSetupPose();
      },
      setBonesToSetupPose: function() {
        this._sgNode && this._sgNode.setBonesToSetupPose();
      },
      setSlotsToSetupPose: function() {
        this._sgNode && this._sgNode.setSlotsToSetupPose();
      },
      findBone: function(boneName) {
        if (this._sgNode) return this._sgNode.findBone(boneName);
        return null;
      },
      findSlot: function(slotName) {
        if (this._sgNode) return this._sgNode.findSlot(slotName);
        return null;
      },
      setSkin: function(skinName) {
        if (this._sgNode) return this._sgNode.setSkin(skinName);
        return null;
      },
      getAttachment: function(slotName, attachmentName) {
        if (this._sgNode) return this._sgNode.getAttachment(slotName, attachmentName);
        return null;
      },
      setAttachment: function(slotName, attachmentName) {
        this._sgNode && this._sgNode.setAttachment(slotName, attachmentName);
      },
      setSkeletonData: function(skeletonData, ownsSkeletonData) {
        this._sgNode && this._sgNode.setSkeletonData(skeletonData, ownsSkeletonData);
      },
      setAnimationStateData: function(stateData) {
        if (this._sgNode) return this._sgNode.setAnimationStateData(stateData);
      },
      setMix: function(fromAnimation, toAnimation, duration) {
        this._sgNode && this._sgNode.setMix(fromAnimation, toAnimation, duration);
      },
      setAnimationListener: function(target, callback) {
        this._sgNode && this._sgNode.setAnimationListener(target, callback);
      },
      setAnimation: function(trackIndex, name, loop) {
        if (this._sgNode) {
          var res = this._sgNode.setAnimation(trackIndex, name, loop);
          false;
          return res;
        }
        return null;
      },
      _sample: function() {
        this._sgNode && this._sgNode.update(0);
      },
      addAnimation: function(trackIndex, name, loop, delay) {
        if (this._sgNode) return this._sgNode.addAnimation(trackIndex, name, loop, delay || 0);
        return null;
      },
      findAnimation: function(name) {
        if (this._sgNode) return this._sgNode.findAnimation(name);
        return null;
      },
      getCurrent: function(trackIndex) {
        if (this._sgNode) return this._sgNode.getCurrent(trackIndex);
        return null;
      },
      clearTracks: function() {
        this._sgNode && this._sgNode.clearTracks();
      },
      clearTrack: function(trackIndex) {
        if (this._sgNode) {
          this._sgNode.clearTrack(trackIndex);
          false;
        }
      },
      _updateAnimEnum: false,
      _updateSkinEnum: false,
      setStartListener: function(listener) {
        this._startListener = listener;
        this._sgNode && this._sgNode.setStartListener(listener);
      },
      setInterruptListener: function(listener) {
        this._interruptListener = listener;
        this._sgNode && this._sgNode.setInterruptListener(listener);
      },
      setEndListener: function(listener) {
        this._endListener = listener;
        this._sgNode && this._sgNode.setEndListener(listener);
      },
      setDisposeListener: function(listener) {
        this._disposeListener = listener;
        this._sgNode && this._sgNode.setDisposeListener(listener);
      },
      setCompleteListener: function(listener) {
        this._completeListener = listener;
        this._sgNode && this._sgNode.setCompleteListener(listener);
      },
      setEventListener: function(listener) {
        this._eventListener = listener;
        this._sgNode && this._sgNode.setEventListener(listener);
      },
      setTrackStartListener: function(entry, listener) {
        this._sgNode && this._sgNode.setTrackStartListener(entry, listener);
      },
      setTrackInterruptListener: function(entry, listener) {
        this._sgNode && this._sgNode.setTrackInterruptListener(entry, listener);
      },
      setTrackEndListener: function(entry, listener) {
        this._sgNode && this._sgNode.setTrackEndListener(entry, listener);
      },
      setTrackDisposeListener: function(entry, listener) {
        this._sgNode && this._sgNode.setTrackDisposeListener(entry, listener);
      },
      setTrackCompleteListener: function(entry, listener) {
        this._sgNode && this._sgNode.setTrackCompleteListener(entry, listener);
      },
      setTrackEventListener: function(entry, listener) {
        this._sgNode && this._sgNode.setTrackEventListener(entry, listener);
      },
      getState: function() {
        if (this._sgNode) return this._sgNode.getState();
      },
      _refresh: function() {
        var self = this;
        if (self._sgNode) {
          self.node._sizeProvider === self._sgNode && (self.node._sizeProvider = null);
          self._removeSgNode();
          self._sgNode = null;
        }
        var sgNode = self._sgNode = self._createSgNode();
        if (sgNode) {
          false;
          self.enabledInHierarchy || sgNode.setVisible(false);
          sgNode.setContentSize(0, 0);
          self._initSgNode();
          self._appendSgNode(sgNode);
          self._registSizeProvider();
        }
        false;
      }
    });
  }), {} ],
  306: [ (function(require, module, exports) {
    var TextureLoader = (true, cc.Class({
      ctor: function() {
        this.asset = arguments[0];
      },
      getTexture: function(line) {
        var urls = this.asset.textures;
        for (var i = 0; i < urls.length; i++) {
          var url = urls[i];
          if (url.endsWith(line)) {
            var texture = cc.textureCache.addImage(url);
            var tex = new sp.SkeletonTexture({
              width: texture.getPixelWidth(),
              height: texture.getPixelHeight()
            });
            tex.setRealTexture(texture);
            return tex;
          }
        }
        return null;
      },
      load: function(line) {
        var texture = this.getTexture(line);
        if (texture) return texture;
        cc.errorID(7506, line);
        return null;
      },
      unload: function(obj) {}
    }));
    var SkeletonData = cc.Class({
      name: "sp.SkeletonData",
      extends: cc.Asset,
      ctor: function() {
        this.reset();
      },
      properties: {
        _skeletonJson: null,
        skeletonJson: {
          get: function() {
            return this._skeletonJson;
          },
          set: function(value) {
            this._skeletonJson = value;
            this.reset();
          }
        },
        _atlasText: "",
        atlasText: {
          get: function() {
            return this._atlasText;
          },
          set: function(value) {
            this._atlasText = value;
            this.reset();
          }
        },
        atlasUrl: {
          default: "",
          url: cc.RawAsset
        },
        textures: {
          default: [],
          url: [ cc.Texture2D ]
        },
        scale: 1
      },
      statics: {
        preventDeferredLoadDependents: true
      },
      createNode: false,
      reset: function() {
        this._skeletonCache = null;
        this._atlasCache = null;
        false;
      },
      getRuntimeData: (true, function(quiet) {
        if (this._skeletonCache) return this._skeletonCache;
        if (!(this.textures && this.textures.length > 0)) {
          quiet || cc.errorID(7507, this.name);
          return null;
        }
        var atlas = this._getAtlas(quiet);
        if (!atlas) return null;
        var attachmentLoader = new sp.spine.AtlasAttachmentLoader(atlas);
        var jsonReader = new sp.spine.SkeletonJson(attachmentLoader);
        jsonReader.scale = this.scale;
        var json = this.skeletonJson;
        this._skeletonCache = jsonReader.readSkeletonData(json);
        atlas.dispose(jsonReader);
        return this._skeletonCache;
      }),
      getSkinsEnum: false,
      getAnimsEnum: false,
      _getAtlas: (true, function(quiet) {
        if (this._atlasCache) return this._atlasCache;
        if (!this.atlasText) {
          quiet || cc.errorID(7508, this.name);
          return null;
        }
        var loader = new TextureLoader(this);
        return this._atlasCache = new sp.spine.TextureAtlas(this.atlasText, loader.load.bind(loader));
      })
    });
    sp.SkeletonData = module.exports = SkeletonData;
  }), {} ],
  307: [ (function(require, module, exports) {
    sp = {};
    sp.VERTEX_INDEX = {
      X1: 0,
      Y1: 1,
      X2: 2,
      Y2: 3,
      X3: 4,
      Y3: 5,
      X4: 6,
      Y4: 7
    };
    sp.ATTACHMENT_TYPE = {
      REGION: 0,
      BOUNDING_BOX: 1,
      MESH: 2,
      SKINNED_MESH: 3
    };
    sp.AnimationEventType = cc.Enum({
      START: 0,
      INTERRUPT: 1,
      END: 2,
      DISPOSE: 3,
      COMPLETE: 4,
      EVENT: 5
    });
    true;
    true;
    sp.spine = require("./lib/spine");
    require("./SGSkeletonTexture");
    require("./SGSkeleton");
    require("./SGSkeletonCanvasRenderCmd");
    require("./SGSkeletonWebGLRenderCmd");
    require("./SGSkeletonAnimation");
    require("./SkeletonData");
    require("./Skeleton");
  }), {
    "./SGSkeleton": 300,
    "./SGSkeletonAnimation": 301,
    "./SGSkeletonCanvasRenderCmd": 302,
    "./SGSkeletonTexture": 303,
    "./SGSkeletonWebGLRenderCmd": 304,
    "./Skeleton": 305,
    "./SkeletonData": 306,
    "./lib/spine": 308
  } ],
  308: [ (function(require, module, exports) {
    var __extends = this && this.__extends || function(d, b) {
      for (var p in b) b.hasOwnProperty(p) && (d[p] = b[p]);
      function __() {
        this.constructor = d;
      }
      d.prototype = null === b ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
    var spine;
    (function(spine) {
      var Animation = (function() {
        function Animation(name, timelines, duration) {
          if (null == name) throw new Error("name cannot be null.");
          if (null == timelines) throw new Error("timelines cannot be null.");
          this.name = name;
          this.timelines = timelines;
          this.duration = duration;
        }
        Animation.prototype.apply = function(skeleton, lastTime, time, loop, events, alpha, setupPose, mixingOut) {
          if (null == skeleton) throw new Error("skeleton cannot be null.");
          if (loop && 0 != this.duration) {
            time %= this.duration;
            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, setupPose, mixingOut);
        };
        Animation.binarySearch = function(values, target, step) {
          void 0 === step && (step = 1);
          var low = 0;
          var high = values.length / step - 2;
          if (0 == high) return step;
          var current = high >>> 1;
          while (true) {
            values[(current + 1) * step] <= target ? low = current + 1 : 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;
      (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";
      })(spine.TimelineType || (spine.TimelineType = {}));
      var 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 = .03 * (2 * -cx1 + cx2), tmpy = .03 * (2 * -cy1 + cy2);
          var dddfx = .006 * (3 * (cx1 - cx2) + 1), dddfy = .006 * (3 * (cy1 - cy2) + 1);
          var ddfx = 2 * tmpx + dddfx, ddfy = 2 * tmpy + dddfy;
          var dfx = .3 * cx1 + tmpx + .16666667 * dddfx, dfy = .3 * cy1 + tmpy + .16666667 * dddfy;
          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 = 19;
        return CurveTimeline;
      })();
      spine.CurveTimeline = CurveTimeline;
      var RotateTimeline = (function(_super) {
        __extends(RotateTimeline, _super);
        function RotateTimeline(frameCount) {
          _super.call(this, frameCount);
          this.frames = spine.Utils.newFloatArray(frameCount << 1);
        }
        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, setupPose, mixingOut) {
          var frames = this.frames;
          var bone = skeleton.bones[this.boneIndex];
          if (time < frames[0]) {
            setupPose && (bone.rotation = bone.data.rotation);
            return;
          }
          if (time >= frames[frames.length - RotateTimeline.ENTRIES]) {
            if (setupPose) bone.rotation = bone.data.rotation + frames[frames.length + RotateTimeline.PREV_ROTATION] * alpha; else {
              var r_1 = bone.data.rotation + frames[frames.length + RotateTimeline.PREV_ROTATION] - bone.rotation;
              r_1 -= 360 * (16384 - (16384.499999999996 - r_1 / 360 | 0));
              bone.rotation += r_1 * 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 -= 360 * (16384 - (16384.499999999996 - r / 360 | 0));
          r = prevRotation + r * percent;
          if (setupPose) {
            r -= 360 * (16384 - (16384.499999999996 - r / 360 | 0));
            bone.rotation = bone.data.rotation + r * alpha;
          } else {
            r = bone.data.rotation + r - bone.rotation;
            r -= 360 * (16384 - (16384.499999999996 - r / 360 | 0));
            bone.rotation += r * 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) {
          _super.call(this, frameCount);
          this.frames = spine.Utils.newFloatArray(frameCount * TranslateTimeline.ENTRIES);
        }
        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, setupPose, mixingOut) {
          var frames = this.frames;
          var bone = skeleton.bones[this.boneIndex];
          if (time < frames[0]) {
            if (setupPose) {
              bone.x = bone.data.x;
              bone.y = bone.data.y;
            }
            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;
          }
          if (setupPose) {
            bone.x = bone.data.x + x * alpha;
            bone.y = bone.data.y + y * alpha;
          } else {
            bone.x += (bone.data.x + x - bone.x) * alpha;
            bone.y += (bone.data.y + y - bone.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) {
          _super.call(this, frameCount);
        }
        ScaleTimeline.prototype.getPropertyId = function() {
          return (TimelineType.scale << 24) + this.boneIndex;
        };
        ScaleTimeline.prototype.apply = function(skeleton, lastTime, time, events, alpha, setupPose, mixingOut) {
          var frames = this.frames;
          var bone = skeleton.bones[this.boneIndex];
          if (time < frames[0]) {
            if (setupPose) {
              bone.scaleX = bone.data.scaleX;
              bone.scaleY = bone.data.scaleY;
            }
            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 (1 == alpha) {
            bone.scaleX = x;
            bone.scaleY = y;
          } else {
            var bx = 0, by = 0;
            if (setupPose) {
              bx = bone.data.scaleX;
              by = bone.data.scaleY;
            } else {
              bx = bone.scaleX;
              by = bone.scaleY;
            }
            if (mixingOut) {
              x = Math.abs(x) * spine.MathUtils.signum(bx);
              y = Math.abs(y) * spine.MathUtils.signum(by);
            } else {
              bx = Math.abs(bx) * spine.MathUtils.signum(x);
              by = Math.abs(by) * spine.MathUtils.signum(y);
            }
            bone.scaleX = bx + (x - bx) * alpha;
            bone.scaleY = by + (y - by) * alpha;
          }
        };
        return ScaleTimeline;
      })(TranslateTimeline);
      spine.ScaleTimeline = ScaleTimeline;
      var ShearTimeline = (function(_super) {
        __extends(ShearTimeline, _super);
        function ShearTimeline(frameCount) {
          _super.call(this, frameCount);
        }
        ShearTimeline.prototype.getPropertyId = function() {
          return (TimelineType.shear << 24) + this.boneIndex;
        };
        ShearTimeline.prototype.apply = function(skeleton, lastTime, time, events, alpha, setupPose, mixingOut) {
          var frames = this.frames;
          var bone = skeleton.bones[this.boneIndex];
          if (time < frames[0]) {
            if (setupPose) {
              bone.shearX = bone.data.shearX;
              bone.shearY = bone.data.shearY;
            }
            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 += (frames[frame + ShearTimeline.X] - x) * percent;
            y += (frames[frame + ShearTimeline.Y] - y) * percent;
          }
          if (setupPose) {
            bone.shearX = bone.data.shearX + x * alpha;
            bone.shearY = bone.data.shearY + y * alpha;
          } else {
            bone.shearX += (bone.data.shearX + x - bone.shearX) * alpha;
            bone.shearY += (bone.data.shearY + y - bone.shearY) * alpha;
          }
        };
        return ShearTimeline;
      })(TranslateTimeline);
      spine.ShearTimeline = ShearTimeline;
      var ColorTimeline = (function(_super) {
        __extends(ColorTimeline, _super);
        function ColorTimeline(frameCount) {
          _super.call(this, frameCount);
          this.frames = spine.Utils.newFloatArray(frameCount * ColorTimeline.ENTRIES);
        }
        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, setupPose, mixingOut) {
          var slot = skeleton.slots[this.slotIndex];
          var frames = this.frames;
          if (time < frames[0]) {
            setupPose && slot.color.setFromColor(slot.data.color);
            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 (1 == alpha) slot.color.set(r, g, b, a); else {
            var color = slot.color;
            setupPose && 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 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, setupPose, mixingOut) {
          var slot = skeleton.slots[this.slotIndex];
          if (mixingOut && setupPose) {
            var attachmentName_1 = slot.data.attachmentName;
            slot.setAttachment(null == attachmentName_1 ? null : skeleton.getAttachment(this.slotIndex, attachmentName_1));
            return;
          }
          var frames = this.frames;
          if (time < frames[0]) {
            if (setupPose) {
              var attachmentName_2 = slot.data.attachmentName;
              slot.setAttachment(null == attachmentName_2 ? null : skeleton.getAttachment(this.slotIndex, attachmentName_2));
            }
            return;
          }
          var frameIndex = 0;
          frameIndex = time >= frames[frames.length - 1] ? frames.length - 1 : Animation.binarySearch(frames, time, 1) - 1;
          var attachmentName = this.attachmentNames[frameIndex];
          skeleton.slots[this.slotIndex].setAttachment(null == attachmentName ? null : skeleton.getAttachment(this.slotIndex, attachmentName));
        };
        return AttachmentTimeline;
      })();
      spine.AttachmentTimeline = AttachmentTimeline;
      var DeformTimeline = (function(_super) {
        __extends(DeformTimeline, _super);
        function DeformTimeline(frameCount) {
          _super.call(this, frameCount);
          this.frames = spine.Utils.newFloatArray(frameCount);
          this.frameVertices = new Array(frameCount);
        }
        DeformTimeline.prototype.getPropertyId = function() {
          return (TimelineType.deform << 24) + 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, setupPose, mixingOut) {
          var slot = skeleton.slots[this.slotIndex];
          var slotAttachment = slot.getAttachment();
          if (!(slotAttachment instanceof spine.VertexAttachment) || !slotAttachment.applyDeform(this.attachment)) return;
          var frames = this.frames;
          var verticesArray = slot.attachmentVertices;
          if (time < frames[0]) {
            setupPose && spine.Utils.setArraySize(verticesArray, 0);
            return;
          }
          var frameVertices = this.frameVertices;
          var vertexCount = frameVertices[0].length;
          verticesArray.length != vertexCount && (alpha = 1);
          var vertices = spine.Utils.setArraySize(verticesArray, vertexCount);
          if (time >= frames[frames.length - 1]) {
            var lastVertices = frameVertices[frames.length - 1];
            if (1 == alpha) spine.Utils.arrayCopy(lastVertices, 0, vertices, 0, vertexCount); else if (setupPose) {
              var vertexAttachment = slotAttachment;
              if (null == vertexAttachment.bones) {
                var setupVertices = vertexAttachment.vertices;
                for (var i = 0; i < vertexCount; i++) {
                  var setup = setupVertices[i];
                  vertices[i] = setup + (lastVertices[i] - setup) * alpha;
                }
              } else for (var i = 0; i < vertexCount; i++) vertices[i] = lastVertices[i] * alpha;
            } else for (var i = 0; i < vertexCount; i++) vertices[i] += (lastVertices[i] - vertices[i]) * 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 (1 == alpha) for (var i = 0; i < vertexCount; i++) {
            var prev = prevVertices[i];
            vertices[i] = prev + (nextVertices[i] - prev) * percent;
          } else if (setupPose) {
            var vertexAttachment = slotAttachment;
            if (null == vertexAttachment.bones) {
              var setupVertices = vertexAttachment.vertices;
              for (var i = 0; i < vertexCount; i++) {
                var prev = prevVertices[i], setup = setupVertices[i];
                vertices[i] = setup + (prev + (nextVertices[i] - prev) * percent - setup) * alpha;
              }
            } else for (var i = 0; i < vertexCount; i++) {
              var prev = prevVertices[i];
              vertices[i] = (prev + (nextVertices[i] - prev) * percent) * alpha;
            }
          } else for (var i = 0; i < vertexCount; i++) {
            var prev = prevVertices[i];
            vertices[i] += (prev + (nextVertices[i] - prev) * percent - vertices[i]) * 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, setupPose, mixingOut) {
          if (null == firedEvents) return;
          var frames = this.frames;
          var frameCount = this.frames.length;
          if (lastTime > time) {
            this.apply(skeleton, lastTime, Number.MAX_VALUE, firedEvents, alpha, setupPose, mixingOut);
            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, setupPose, mixingOut) {
          var drawOrder = skeleton.drawOrder;
          var slots = skeleton.slots;
          if (mixingOut && setupPose) {
            spine.Utils.arrayCopy(skeleton.slots, 0, skeleton.drawOrder, 0, skeleton.slots.length);
            return;
          }
          var frames = this.frames;
          if (time < frames[0]) {
            setupPose && spine.Utils.arrayCopy(skeleton.slots, 0, skeleton.drawOrder, 0, skeleton.slots.length);
            return;
          }
          var frame = 0;
          frame = time >= frames[frames.length - 1] ? frames.length - 1 : Animation.binarySearch(frames, time) - 1;
          var drawOrderToSetupIndex = this.drawOrders[frame];
          if (null == drawOrderToSetupIndex) 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) {
          _super.call(this, frameCount);
          this.frames = spine.Utils.newFloatArray(frameCount * IkConstraintTimeline.ENTRIES);
        }
        IkConstraintTimeline.prototype.getPropertyId = function() {
          return (TimelineType.ikConstraint << 24) + this.ikConstraintIndex;
        };
        IkConstraintTimeline.prototype.setFrame = function(frameIndex, time, mix, bendDirection) {
          frameIndex *= IkConstraintTimeline.ENTRIES;
          this.frames[frameIndex] = time;
          this.frames[frameIndex + IkConstraintTimeline.MIX] = mix;
          this.frames[frameIndex + IkConstraintTimeline.BEND_DIRECTION] = bendDirection;
        };
        IkConstraintTimeline.prototype.apply = function(skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) {
          var frames = this.frames;
          var constraint = skeleton.ikConstraints[this.ikConstraintIndex];
          if (time < frames[0]) {
            if (setupPose) {
              constraint.mix = constraint.data.mix;
              constraint.bendDirection = constraint.data.bendDirection;
            }
            return;
          }
          if (time >= frames[frames.length - IkConstraintTimeline.ENTRIES]) {
            if (setupPose) {
              constraint.mix = constraint.data.mix + (frames[frames.length + IkConstraintTimeline.PREV_MIX] - constraint.data.mix) * alpha;
              constraint.bendDirection = mixingOut ? constraint.data.bendDirection : frames[frames.length + IkConstraintTimeline.PREV_BEND_DIRECTION];
            } else {
              constraint.mix += (frames[frames.length + IkConstraintTimeline.PREV_MIX] - constraint.mix) * alpha;
              mixingOut || (constraint.bendDirection = frames[frames.length + IkConstraintTimeline.PREV_BEND_DIRECTION]);
            }
            return;
          }
          var frame = Animation.binarySearch(frames, time, IkConstraintTimeline.ENTRIES);
          var mix = frames[frame + IkConstraintTimeline.PREV_MIX];
          var frameTime = frames[frame];
          var percent = this.getCurvePercent(frame / IkConstraintTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + IkConstraintTimeline.PREV_TIME] - frameTime));
          if (setupPose) {
            constraint.mix = constraint.data.mix + (mix + (frames[frame + IkConstraintTimeline.MIX] - mix) * percent - constraint.data.mix) * alpha;
            constraint.bendDirection = mixingOut ? constraint.data.bendDirection : frames[frame + IkConstraintTimeline.PREV_BEND_DIRECTION];
          } else {
            constraint.mix += (mix + (frames[frame + IkConstraintTimeline.MIX] - mix) * percent - constraint.mix) * alpha;
            mixingOut || (constraint.bendDirection = frames[frame + IkConstraintTimeline.PREV_BEND_DIRECTION]);
          }
        };
        IkConstraintTimeline.ENTRIES = 3;
        IkConstraintTimeline.PREV_TIME = -3;
        IkConstraintTimeline.PREV_MIX = -2;
        IkConstraintTimeline.PREV_BEND_DIRECTION = -1;
        IkConstraintTimeline.MIX = 1;
        IkConstraintTimeline.BEND_DIRECTION = 2;
        return IkConstraintTimeline;
      })(CurveTimeline);
      spine.IkConstraintTimeline = IkConstraintTimeline;
      var TransformConstraintTimeline = (function(_super) {
        __extends(TransformConstraintTimeline, _super);
        function TransformConstraintTimeline(frameCount) {
          _super.call(this, frameCount);
          this.frames = spine.Utils.newFloatArray(frameCount * TransformConstraintTimeline.ENTRIES);
        }
        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, setupPose, mixingOut) {
          var frames = this.frames;
          var constraint = skeleton.transformConstraints[this.transformConstraintIndex];
          if (time < frames[0]) {
            if (setupPose) {
              var data = constraint.data;
              constraint.rotateMix = data.rotateMix;
              constraint.translateMix = data.rotateMix;
              constraint.scaleMix = data.scaleMix;
              constraint.shearMix = data.shearMix;
            }
            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 (setupPose) {
            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) {
          _super.call(this, frameCount);
          this.frames = spine.Utils.newFloatArray(frameCount * PathConstraintPositionTimeline.ENTRIES);
        }
        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, setupPose, mixingOut) {
          var frames = this.frames;
          var constraint = skeleton.pathConstraints[this.pathConstraintIndex];
          if (time < frames[0]) {
            setupPose && (constraint.position = constraint.data.position);
            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;
          }
          setupPose ? constraint.position = constraint.data.position + (position - constraint.data.position) * alpha : 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) {
          _super.call(this, frameCount);
        }
        PathConstraintSpacingTimeline.prototype.getPropertyId = function() {
          return (TimelineType.pathConstraintSpacing << 24) + this.pathConstraintIndex;
        };
        PathConstraintSpacingTimeline.prototype.apply = function(skeleton, lastTime, time, firedEvents, alpha, setupPose, mixingOut) {
          var frames = this.frames;
          var constraint = skeleton.pathConstraints[this.pathConstraintIndex];
          if (time < frames[0]) {
            setupPose && (constraint.spacing = constraint.data.spacing);
            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;
          }
          setupPose ? constraint.spacing = constraint.data.spacing + (spacing - constraint.data.spacing) * alpha : constraint.spacing += (spacing - constraint.spacing) * alpha;
        };
        return PathConstraintSpacingTimeline;
      })(PathConstraintPositionTimeline);
      spine.PathConstraintSpacingTimeline = PathConstraintSpacingTimeline;
      var PathConstraintMixTimeline = (function(_super) {
        __extends(PathConstraintMixTimeline, _super);
        function PathConstraintMixTimeline(frameCount) {
          _super.call(this, frameCount);
          this.frames = spine.Utils.newFloatArray(frameCount * PathConstraintMixTimeline.ENTRIES);
        }
        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, setupPose, mixingOut) {
          var frames = this.frames;
          var constraint = skeleton.pathConstraints[this.pathConstraintIndex];
          if (time < frames[0]) {
            if (setupPose) {
              constraint.rotateMix = constraint.data.rotateMix;
              constraint.translateMix = constraint.data.translateMix;
            }
            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 (setupPose) {
            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.events = new Array();
          this.listeners = new Array();
          this.queue = new EventQueue(this);
          this.propertyIDs = new spine.IntSet();
          this.animationsChanged = false;
          this.timeScale = 1;
          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 (null == current) 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 (null != next) {
              var nextTime = current.trackLast - next.delay;
              if (nextTime >= 0) {
                next.delay = 0;
                next.trackTime = nextTime + delta * next.timeScale;
                current.trackTime += currentDelta;
                this.setCurrent(i, next, true);
                while (null != next.mixingFrom) {
                  next.mixTime += currentDelta;
                  next = next.mixingFrom;
                }
                continue;
              }
            } else if (current.trackLast >= current.trackEnd && null == current.mixingFrom) {
              tracks[i] = null;
              this.queue.end(current);
              this.disposeNext(current);
              continue;
            }
            this.updateMixingFrom(current, delta);
            current.trackTime += currentDelta;
          }
          this.queue.drain();
        };
        AnimationState.prototype.updateMixingFrom = function(entry, delta) {
          var from = entry.mixingFrom;
          if (null == from) return;
          this.updateMixingFrom(from, delta);
          if (entry.mixTime >= entry.mixDuration && null != from.mixingFrom && entry.mixTime > 0) {
            entry.mixingFrom = null;
            this.queue.end(from);
            return;
          }
          from.animationLast = from.nextAnimationLast;
          from.trackLast = from.nextTrackLast;
          from.trackTime += delta * from.timeScale;
          entry.mixTime += delta * from.timeScale;
        };
        AnimationState.prototype.apply = function(skeleton) {
          if (null == skeleton) throw new Error("skeleton cannot be null.");
          this.animationsChanged && this._animationsChanged();
          var events = this.events;
          var tracks = this.tracks;
          for (var i = 0, n = tracks.length; i < n; i++) {
            var current = tracks[i];
            if (null == current || current.delay > 0) continue;
            var mix = current.alpha;
            null != current.mixingFrom ? mix *= this.applyMixingFrom(current, skeleton) : current.trackTime >= current.trackEnd && (mix = 0);
            var animationLast = current.animationLast, animationTime = current.getAnimationTime();
            var timelineCount = current.animation.timelines.length;
            var timelines = current.animation.timelines;
            if (1 == mix) for (var ii = 0; ii < timelineCount; ii++) timelines[ii].apply(skeleton, animationLast, animationTime, events, 1, true, false); else {
              var firstFrame = 0 == current.timelinesRotation.length;
              firstFrame && spine.Utils.setArraySize(current.timelinesRotation, timelineCount << 1, null);
              var timelinesRotation = current.timelinesRotation;
              var timelinesFirst = current.timelinesFirst;
              for (var ii = 0; ii < timelineCount; ii++) {
                var timeline = timelines[ii];
                timeline instanceof spine.RotateTimeline ? this.applyRotateTimeline(timeline, skeleton, animationTime, mix, timelinesFirst[ii], timelinesRotation, ii << 1, firstFrame) : timeline.apply(skeleton, animationLast, animationTime, events, mix, timelinesFirst[ii], false);
              }
            }
            this.queueEvents(current, animationTime);
            events.length = 0;
            current.nextAnimationLast = animationTime;
            current.nextTrackLast = current.trackTime;
          }
          this.queue.drain();
        };
        AnimationState.prototype.applyMixingFrom = function(entry, skeleton) {
          var from = entry.mixingFrom;
          null != from.mixingFrom && this.applyMixingFrom(from, skeleton);
          var mix = 0;
          if (0 == entry.mixDuration) mix = 1; else {
            mix = entry.mixTime / entry.mixDuration;
            mix > 1 && (mix = 1);
          }
          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 timelinesFirst = from.timelinesFirst;
          var alpha = from.alpha * entry.mixAlpha * (1 - mix);
          var firstFrame = 0 == from.timelinesRotation.length;
          firstFrame && spine.Utils.setArraySize(from.timelinesRotation, timelineCount << 1, null);
          var timelinesRotation = from.timelinesRotation;
          for (var i = 0; i < timelineCount; i++) {
            var timeline = timelines[i];
            var setupPose = timelinesFirst[i];
            if (timeline instanceof spine.RotateTimeline) this.applyRotateTimeline(timeline, skeleton, animationTime, alpha, setupPose, timelinesRotation, i << 1, firstFrame); else {
              if (!setupPose) {
                if (!attachments && timeline instanceof spine.AttachmentTimeline) continue;
                if (!drawOrder && timeline instanceof spine.DrawOrderTimeline) continue;
              }
              timeline.apply(skeleton, animationLast, animationTime, events, alpha, setupPose, true);
            }
          }
          entry.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, setupPose, timelinesRotation, i, firstFrame) {
          firstFrame && (timelinesRotation[i] = 0);
          if (1 == alpha) {
            timeline.apply(skeleton, 0, time, null, 1, setupPose, false);
            return;
          }
          var rotateTimeline = timeline;
          var frames = rotateTimeline.frames;
          var bone = skeleton.bones[rotateTimeline.boneIndex];
          if (time < frames[0]) {
            setupPose && (bone.rotation = bone.data.rotation);
            return;
          }
          var r2 = 0;
          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 -= 360 * (16384 - (16384.499999999996 - r2 / 360 | 0));
            r2 = prevRotation + r2 * percent + bone.data.rotation;
            r2 -= 360 * (16384 - (16384.499999999996 - r2 / 360 | 0));
          }
          var r1 = setupPose ? bone.data.rotation : bone.rotation;
          var total = 0, diff = r2 - r1;
          if (0 == diff) total = timelinesRotation[i]; else {
            diff -= 360 * (16384 - (16384.499999999996 - diff / 360 | 0));
            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) {
              Math.abs(lastTotal) > 180 && (lastTotal += 360 * spine.MathUtils.signum(lastTotal));
              dir = current;
            }
            total = diff + lastTotal - lastTotal % 360;
            dir != current && (total += 360 * spine.MathUtils.signum(lastTotal));
            timelinesRotation[i] = total;
          }
          timelinesRotation[i + 1] = diff;
          r1 += total * alpha;
          bone.rotation = r1 - 360 * (16384 - (16384.499999999996 - r1 / 360 | 0));
        };
        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);
          }
          (entry.loop ? trackLastWrapped > entry.trackTime % duration : animationTime >= animationEnd && entry.animationLast < animationEnd) && 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() {
          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 = false;
          this.queue.drain();
        };
        AnimationState.prototype.clearTrack = function(trackIndex) {
          if (trackIndex >= this.tracks.length) return;
          var current = this.tracks[trackIndex];
          if (null == current) return;
          this.queue.end(current);
          this.disposeNext(current);
          var entry = current;
          while (true) {
            var from = entry.mixingFrom;
            if (null == from) break;
            this.queue.end(from);
            entry.mixingFrom = 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 (null != from) {
            interrupt && this.queue.interrupt(from);
            current.mixingFrom = from;
            current.mixTime = 0;
            from.timelinesRotation.length = 0;
            null != from.mixingFrom && from.mixDuration > 0 && (current.mixAlpha *= Math.min(from.mixTime / from.mixDuration, 1));
          }
          this.queue.start(current);
        };
        AnimationState.prototype.setAnimation = function(trackIndex, animationName, loop) {
          var animation = this.data.skeletonData.findAnimation(animationName);
          if (null == animation) throw new Error("Animation not found: " + animationName);
          return this.setAnimationWith(trackIndex, animation, loop);
        };
        AnimationState.prototype.setAnimationWith = function(trackIndex, animation, loop) {
          if (null == animation) throw new Error("animation cannot be null.");
          var interrupt = true;
          var current = this.expandToIndex(trackIndex);
          if (null != current) if (-1 == current.nextTrackLast) {
            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 (null == animation) throw new Error("Animation not found: " + animationName);
          return this.addAnimationWith(trackIndex, animation, loop, delay);
        };
        AnimationState.prototype.addAnimationWith = function(trackIndex, animation, loop, delay) {
          if (null == animation) throw new Error("animation cannot be null.");
          var last = this.expandToIndex(trackIndex);
          if (null != last) while (null != last.next) last = last.next;
          var entry = this.trackEntry(trackIndex, animation, loop, last);
          if (null == last) {
            this.setCurrent(trackIndex, entry, true);
            this.queue.drain();
          } else {
            last.next = entry;
            if (delay <= 0) {
              var duration = last.animationEnd - last.animationStart;
              0 != duration ? delay += duration * (1 + (last.trackTime / duration | 0)) - this.data.getMix(last.animation, animation) : delay = 0;
            }
          }
          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) {
          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) {
          this.queue.drainDisabled = true;
          for (var i = 0, n = this.tracks.length; i < n; i++) {
            var current = this.tracks[i];
            null != current && this.setEmptyAnimation(current.trackIndex, mixDuration);
          }
          this.queue.drainDisabled = false;
          this.queue.drain();
        };
        AnimationState.prototype.expandToIndex = function(index) {
          if (index < this.tracks.length) return this.tracks[index];
          spine.Utils.ensureArrayCapacity(this.tracks, index - this.tracks.length + 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.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.mixAlpha = 1;
          entry.mixTime = 0;
          entry.mixDuration = null == last ? 0 : this.data.getMix(last.animation, animation);
          return entry;
        };
        AnimationState.prototype.disposeNext = function(entry) {
          var next = entry.next;
          while (null != next) {
            this.queue.dispose(next);
            next = next.next;
          }
          entry.next = null;
        };
        AnimationState.prototype._animationsChanged = function() {
          this.animationsChanged = false;
          var propertyIDs = this.propertyIDs;
          var i = 0, n = this.tracks.length;
          propertyIDs.clear();
          for (;i < n; i++) {
            var entry = this.tracks[i];
            if (null == entry) continue;
            this.setTimelinesFirst(entry);
            i++;
            break;
          }
          for (;i < n; i++) {
            var entry = this.tracks[i];
            null != entry && this.checkTimelinesFirst(entry);
          }
        };
        AnimationState.prototype.setTimelinesFirst = function(entry) {
          if (null != entry.mixingFrom) {
            this.setTimelinesFirst(entry.mixingFrom);
            this.checkTimelinesUsage(entry, entry.timelinesFirst);
            return;
          }
          var propertyIDs = this.propertyIDs;
          var timelines = entry.animation.timelines;
          var n = timelines.length;
          var usage = spine.Utils.setArraySize(entry.timelinesFirst, n, false);
          for (var i = 0; i < n; i++) {
            propertyIDs.add(timelines[i].getPropertyId());
            usage[i] = true;
          }
        };
        AnimationState.prototype.checkTimelinesFirst = function(entry) {
          null != entry.mixingFrom && this.checkTimelinesFirst(entry.mixingFrom);
          this.checkTimelinesUsage(entry, entry.timelinesFirst);
        };
        AnimationState.prototype.checkTimelinesUsage = function(entry, usageArray) {
          var propertyIDs = this.propertyIDs;
          var timelines = entry.animation.timelines;
          var n = timelines.length;
          var usage = spine.Utils.setArraySize(usageArray, n);
          for (var i = 0; i < n; i++) usage[i] = propertyIDs.add(timelines[i].getPropertyId());
        };
        AnimationState.prototype.getCurrent = function(trackIndex) {
          if (trackIndex >= this.tracks.length) return null;
          return this.tracks[trackIndex];
        };
        AnimationState.prototype.addListener = function(listener) {
          if (null == listener) throw new Error("listener cannot be null.");
          this.listeners.push(listener);
        };
        AnimationState.prototype.removeListener = function(listener) {
          var index = this.listeners.indexOf(listener);
          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);
        return AnimationState;
      })();
      spine.AnimationState = AnimationState;
      var TrackEntry = (function() {
        function TrackEntry() {
          this.timelinesFirst = new Array();
          this.timelinesRotation = new Array();
        }
        TrackEntry.prototype.reset = function() {
          this.next = null;
          this.mixingFrom = null;
          this.animation = null;
          this.listener = null;
          this.timelinesFirst.length = 0;
          this.timelinesRotation.length = 0;
        };
        TrackEntry.prototype.getAnimationTime = function() {
          if (this.loop) {
            var duration = this.animationEnd - this.animationStart;
            if (0 == duration) 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:
              null != entry.listener && entry.listener.start && entry.listener.start(entry);
              for (var ii = 0; ii < listeners.length; ii++) listeners[ii].start && listeners[ii].start(entry);
              break;

             case EventType.interrupt:
              null != entry.listener && entry.listener.interrupt && entry.listener.interrupt(entry);
              for (var ii = 0; ii < listeners.length; ii++) listeners[ii].interrupt && listeners[ii].interrupt(entry);
              break;

             case EventType.end:
              null != entry.listener && entry.listener.end && entry.listener.end(entry);
              for (var ii = 0; ii < listeners.length; ii++) listeners[ii].end && listeners[ii].end(entry);

             case EventType.dispose:
              null != entry.listener && entry.listener.dispose && entry.listener.dispose(entry);
              for (var ii = 0; ii < listeners.length; ii++) listeners[ii].dispose && listeners[ii].dispose(entry);
              this.animState.trackEntryPool.free(entry);
              break;

             case EventType.complete:
              null != entry.listener && entry.listener.complete && entry.listener.complete(entry);
              for (var ii = 0; ii < listeners.length; ii++) listeners[ii].complete && listeners[ii].complete(entry);
              break;

             case EventType.event:
              var event_3 = objects[2 + i++];
              null != entry.listener && entry.listener.event && entry.listener.event(entry, event_3);
              for (var ii = 0; ii < listeners.length; ii++) listeners[ii].event && listeners[ii].event(entry, event_3);
            }
          }
          this.clear();
          this.drainDisabled = false;
        };
        EventQueue.prototype.clear = function() {
          this.objects.length = 0;
        };
        return EventQueue;
      })();
      spine.EventQueue = EventQueue;
      (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";
      })(spine.EventType || (spine.EventType = {}));
      var EventType = spine.EventType;
      var AnimationStateAdapter2 = (function() {
        function AnimationStateAdapter2() {}
        AnimationStateAdapter2.prototype.start = function(entry) {};
        AnimationStateAdapter2.prototype.interrupt = function(entry) {};
        AnimationStateAdapter2.prototype.end = function(entry) {};
        AnimationStateAdapter2.prototype.dispose = function(entry) {};
        AnimationStateAdapter2.prototype.complete = function(entry) {};
        AnimationStateAdapter2.prototype.event = function(entry, event) {};
        return AnimationStateAdapter2;
      })();
      spine.AnimationStateAdapter2 = AnimationStateAdapter2;
    })(spine || (spine = {}));
    var spine;
    (function(spine) {
      var AnimationStateData = (function() {
        function AnimationStateData(skeletonData) {
          this.animationToMixTime = {};
          this.defaultMix = 0;
          if (null == skeletonData) throw new Error("skeletonData cannot be null.");
          this.skeletonData = skeletonData;
        }
        AnimationStateData.prototype.setMix = function(fromName, toName, duration) {
          var from = this.skeletonData.findAnimation(fromName);
          if (null == from) throw new Error("Animation not found: " + fromName);
          var to = this.skeletonData.findAnimation(toName);
          if (null == to) throw new Error("Animation not found: " + toName);
          this.setMixWith(from, to, duration);
        };
        AnimationStateData.prototype.setMixWith = function(from, to, duration) {
          if (null == from) throw new Error("from cannot be null.");
          if (null == to) 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 void 0 === value ? this.defaultMix : value;
        };
        return AnimationStateData;
      })();
      spine.AnimationStateData = AnimationStateData;
    })(spine || (spine = {}));
    var spine;
    (function(spine) {
      var AssetManager = (function() {
        function AssetManager(textureLoader, pathPrefix) {
          void 0 === pathPrefix && (pathPrefix = "");
          this.assets = {};
          this.errors = {};
          this.toLoad = 0;
          this.loaded = 0;
          this.textureLoader = textureLoader;
          this.pathPrefix = pathPrefix;
        }
        AssetManager.prototype.loadText = function(path, success, error) {
          var _this = this;
          void 0 === success && (success = null);
          void 0 === error && (error = null);
          path = this.pathPrefix + path;
          this.toLoad++;
          var request = new XMLHttpRequest();
          request.onreadystatechange = function() {
            if (request.readyState == XMLHttpRequest.DONE) {
              if (request.status >= 200 && request.status < 300) {
                _this.assets[path] = request.responseText;
                success && success(path, request.responseText);
              } else {
                _this.errors[path] = "Couldn't load text " + path + ": status " + request.status + ", " + request.responseText;
                error && error(path, "Couldn't load text " + path + ": status " + request.status + ", " + request.responseText);
              }
              _this.toLoad--;
              _this.loaded++;
            }
          };
          request.open("GET", path, true);
          request.send();
        };
        AssetManager.prototype.loadTexture = function(path, success, error) {
          var _this = this;
          void 0 === success && (success = null);
          void 0 === error && (error = null);
          path = this.pathPrefix + path;
          this.toLoad++;
          var img = new Image();
          img.crossOrigin = "anonymous";
          img.src = path;
          img.onload = function(ev) {
            var texture = _this.textureLoader(img);
            _this.assets[path] = texture;
            _this.toLoad--;
            _this.loaded++;
            success && success(path, img);
          };
          img.onerror = function(ev) {
            _this.errors[path] = "Couldn't load image " + path;
            _this.toLoad--;
            _this.loaded++;
            error && error(path, "Couldn't load image " + path);
          };
        };
        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];
          asset.dispose && asset.dispose();
          this.assets[path] = null;
        };
        AssetManager.prototype.removeAll = function() {
          for (var key in this.assets) {
            var asset = this.assets[key];
            asset.dispose && asset.dispose();
          }
          this.assets = {};
        };
        AssetManager.prototype.isLoadingComplete = function() {
          return 0 == this.toLoad;
        };
        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 (null == region) throw new Error("Region not found in atlas: " + path + " (region attachment: " + name + ")");
          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 (null == region) throw new Error("Region not found in atlas: " + path + " (mesh attachment: " + name + ")");
          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);
        };
        return AtlasAttachmentLoader;
      })();
      spine.AtlasAttachmentLoader = AtlasAttachmentLoader;
    })(spine || (spine = {}));
    var spine;
    (function(spine) {
      var Attachment = (function() {
        function Attachment(name) {
          if (null == name) 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) {
          _super.call(this, name);
          this.worldVerticesLength = 0;
        }
        VertexAttachment.prototype.computeWorldVertices = function(slot, worldVertices) {
          this.computeWorldVerticesWith(slot, 0, this.worldVerticesLength, worldVertices, 0);
        };
        VertexAttachment.prototype.computeWorldVerticesWith = function(slot, start, count, worldVertices, offset) {
          count += offset;
          var skeleton = slot.bone.skeleton;
          var deformArray = slot.attachmentVertices;
          var vertices = this.vertices;
          var bones = this.bones;
          if (null == bones) {
            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 += 2) {
              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 (0 == deformArray.length) for (var w = offset, b = 3 * skip; w < count; w += 2) {
            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 = 3 * skip, f = skip << 1; w < count; w += 2) {
              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.applyDeform = function(sourceAttachment) {
          return this == sourceAttachment;
        };
        return VertexAttachment;
      })(Attachment);
      spine.VertexAttachment = VertexAttachment;
    })(spine || (spine = {}));
    var spine;
    (function(spine) {
      (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";
      })(spine.AttachmentType || (spine.AttachmentType = {}));
      var AttachmentType = spine.AttachmentType;
    })(spine || (spine = {}));
    var spine;
    (function(spine) {
      var BoundingBoxAttachment = (function(_super) {
        __extends(BoundingBoxAttachment, _super);
        function BoundingBoxAttachment(name) {
          _super.call(this, name);
          this.color = new spine.Color(1, 1, 1, 1);
        }
        return BoundingBoxAttachment;
      })(spine.VertexAttachment);
      spine.BoundingBoxAttachment = BoundingBoxAttachment;
    })(spine || (spine = {}));
    var spine;
    (function(spine) {
      var MeshAttachment = (function(_super) {
        __extends(MeshAttachment, _super);
        function MeshAttachment(name) {
          _super.call(this, name);
          this.color = new spine.Color(1, 1, 1, 1);
          this.inheritDeform = false;
          this.tempColor = new spine.Color(0, 0, 0, 0);
        }
        MeshAttachment.prototype.updateUVs = function() {
          var regionUVs = this.regionUVs;
          var verticesLength = regionUVs.length;
          var worldVerticesLength = 8 * (verticesLength >> 1);
          null != this.worldVertices && this.worldVertices.length == worldVerticesLength || (this.worldVertices = spine.Utils.newFloatArray(worldVerticesLength));
          var u = 0, v = 0, width = 0, height = 0;
          if (null == this.region) {
            u = v = 0;
            width = height = 1;
          } else {
            u = this.region.u;
            v = this.region.v;
            width = this.region.u2 - u;
            height = this.region.v2 - v;
          }
          if (this.region.rotate) for (var i = 0, w = 6; i < verticesLength; i += 2, w += 8) {
            this.worldVertices[w] = u + regionUVs[i + 1] * width;
            this.worldVertices[w + 1] = v + height - regionUVs[i] * height;
          } else for (var i = 0, w = 6; i < verticesLength; i += 2, w += 8) {
            this.worldVertices[w] = u + regionUVs[i] * width;
            this.worldVertices[w + 1] = v + regionUVs[i + 1] * height;
          }
        };
        MeshAttachment.prototype.updateWorldVertices = function(slot, premultipliedAlpha) {
          var skeleton = slot.bone.skeleton;
          var skeletonColor = skeleton.color, slotColor = slot.color, meshColor = this.color;
          var alpha = skeletonColor.a * slotColor.a * meshColor.a;
          var multiplier = premultipliedAlpha ? alpha : 1;
          var color = this.tempColor;
          color.set(skeletonColor.r * slotColor.r * meshColor.r * multiplier, skeletonColor.g * slotColor.g * meshColor.g * multiplier, skeletonColor.b * slotColor.b * meshColor.b * multiplier, alpha);
          var deformArray = slot.attachmentVertices;
          var vertices = this.vertices, worldVertices = this.worldVertices;
          var bones = this.bones;
          if (null == bones) {
            var verticesLength = vertices.length;
            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 = 0, w = 0; v < verticesLength; v += 2, w += 8) {
              var vx = vertices[v], vy = vertices[v + 1];
              worldVertices[w] = vx * a + vy * b + x;
              worldVertices[w + 1] = vx * c + vy * d + y;
              worldVertices[w + 2] = color.r;
              worldVertices[w + 3] = color.g;
              worldVertices[w + 4] = color.b;
              worldVertices[w + 5] = color.a;
            }
            return worldVertices;
          }
          var skeletonBones = skeleton.bones;
          if (0 == deformArray.length) for (var w = 0, v = 0, b = 0, n = bones.length; v < n; w += 8) {
            var wx = 0, wy = 0;
            var nn = bones[v++] + v;
            for (;v < nn; 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;
            worldVertices[w + 2] = color.r;
            worldVertices[w + 3] = color.g;
            worldVertices[w + 4] = color.b;
            worldVertices[w + 5] = color.a;
          } else {
            var deform = deformArray;
            for (var w = 0, v = 0, b = 0, f = 0, n = bones.length; v < n; w += 8) {
              var wx = 0, wy = 0;
              var nn = bones[v++] + v;
              for (;v < nn; 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;
              worldVertices[w + 2] = color.r;
              worldVertices[w + 3] = color.g;
              worldVertices[w + 4] = color.b;
              worldVertices[w + 5] = color.a;
            }
          }
          return worldVertices;
        };
        MeshAttachment.prototype.applyDeform = function(sourceAttachment) {
          return this == sourceAttachment || this.inheritDeform && this.parentMesh == sourceAttachment;
        };
        MeshAttachment.prototype.getParentMesh = function() {
          return this.parentMesh;
        };
        MeshAttachment.prototype.setParentMesh = function(parentMesh) {
          this.parentMesh = parentMesh;
          if (null != parentMesh) {
            this.bones = parentMesh.bones;
            this.vertices = parentMesh.vertices;
            this.regionUVs = parentMesh.regionUVs;
            this.triangles = parentMesh.triangles;
            this.hullLength = parentMesh.hullLength;
          }
        };
        return MeshAttachment;
      })(spine.VertexAttachment);
      spine.MeshAttachment = MeshAttachment;
    })(spine || (spine = {}));
    var spine;
    (function(spine) {
      var PathAttachment = (function(_super) {
        __extends(PathAttachment, _super);
        function PathAttachment(name) {
          _super.call(this, name);
          this.closed = false;
          this.constantSpeed = false;
          this.color = new spine.Color(1, 1, 1, 1);
        }
        return PathAttachment;
      })(spine.VertexAttachment);
      spine.PathAttachment = PathAttachment;
    })(spine || (spine = {}));
    var spine;
    (function(spine) {
      var RegionAttachment = (function(_super) {
        __extends(RegionAttachment, _super);
        function RegionAttachment(name) {
          _super.call(this, name);
          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.vertices = spine.Utils.newFloatArray(32);
          this.tempColor = new spine.Color(1, 1, 1, 1);
        }
        RegionAttachment.prototype.setRegion = function(region) {
          var vertices = this.vertices;
          if (region.rotate) {
            vertices[RegionAttachment.U2] = region.u;
            vertices[RegionAttachment.V2] = region.v2;
            vertices[RegionAttachment.U3] = region.u;
            vertices[RegionAttachment.V3] = region.v;
            vertices[RegionAttachment.U4] = region.u2;
            vertices[RegionAttachment.V4] = region.v;
            vertices[RegionAttachment.U1] = region.u2;
            vertices[RegionAttachment.V1] = region.v2;
          } else {
            vertices[RegionAttachment.U1] = region.u;
            vertices[RegionAttachment.V1] = region.v2;
            vertices[RegionAttachment.U2] = region.u;
            vertices[RegionAttachment.V2] = region.v;
            vertices[RegionAttachment.U3] = region.u2;
            vertices[RegionAttachment.V3] = region.v;
            vertices[RegionAttachment.U4] = region.u2;
            vertices[RegionAttachment.V4] = region.v2;
          }
          this.region = region;
        };
        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.updateWorldVertices = function(slot, premultipliedAlpha) {
          var skeleton = slot.bone.skeleton;
          var skeletonColor = skeleton.color;
          var slotColor = slot.color;
          var regionColor = this.color;
          var alpha = skeletonColor.a * slotColor.a * regionColor.a;
          var multiplier = premultipliedAlpha ? alpha : 1;
          var color = this.tempColor;
          color.set(skeletonColor.r * slotColor.r * regionColor.r * multiplier, skeletonColor.g * slotColor.g * regionColor.g * multiplier, skeletonColor.b * slotColor.b * regionColor.b * multiplier, alpha);
          var vertices = this.vertices;
          var offset = this.offset;
          var bone = slot.bone;
          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 = offset[RegionAttachment.OX1];
          offsetY = offset[RegionAttachment.OY1];
          vertices[RegionAttachment.X1] = offsetX * a + offsetY * b + x;
          vertices[RegionAttachment.Y1] = offsetX * c + offsetY * d + y;
          vertices[RegionAttachment.C1R] = color.r;
          vertices[RegionAttachment.C1G] = color.g;
          vertices[RegionAttachment.C1B] = color.b;
          vertices[RegionAttachment.C1A] = color.a;
          offsetX = offset[RegionAttachment.OX2];
          offsetY = offset[RegionAttachment.OY2];
          vertices[RegionAttachment.X2] = offsetX * a + offsetY * b + x;
          vertices[RegionAttachment.Y2] = offsetX * c + offsetY * d + y;
          vertices[RegionAttachment.C2R] = color.r;
          vertices[RegionAttachment.C2G] = color.g;
          vertices[RegionAttachment.C2B] = color.b;
          vertices[RegionAttachment.C2A] = color.a;
          offsetX = offset[RegionAttachment.OX3];
          offsetY = offset[RegionAttachment.OY3];
          vertices[RegionAttachment.X3] = offsetX * a + offsetY * b + x;
          vertices[RegionAttachment.Y3] = offsetX * c + offsetY * d + y;
          vertices[RegionAttachment.C3R] = color.r;
          vertices[RegionAttachment.C3G] = color.g;
          vertices[RegionAttachment.C3B] = color.b;
          vertices[RegionAttachment.C3A] = color.a;
          offsetX = offset[RegionAttachment.OX4];
          offsetY = offset[RegionAttachment.OY4];
          vertices[RegionAttachment.X4] = offsetX * a + offsetY * b + x;
          vertices[RegionAttachment.Y4] = offsetX * c + offsetY * d + y;
          vertices[RegionAttachment.C4R] = color.r;
          vertices[RegionAttachment.C4G] = color.g;
          vertices[RegionAttachment.C4B] = color.b;
          vertices[RegionAttachment.C4A] = color.a;
          return vertices;
        };
        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) {
      (function(BlendMode) {
        BlendMode[BlendMode["Normal"] = 0] = "Normal";
        BlendMode[BlendMode["Additive"] = 1] = "Additive";
        BlendMode[BlendMode["Multiply"] = 2] = "Multiply";
        BlendMode[BlendMode["Screen"] = 3] = "Screen";
      })(spine.BlendMode || (spine.BlendMode = {}));
      var 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.worldX = 0;
          this.c = 0;
          this.d = 0;
          this.worldY = 0;
          this.sorted = false;
          if (null == data) throw new Error("data cannot be null.");
          if (null == skeleton) throw new Error("skeleton cannot be null.");
          this.data = data;
          this.skeleton = skeleton;
          this.parent = parent;
          this.setToSetupPose();
        }
        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 (null == parent) {
            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;
            var skeleton = this.skeleton;
            if (skeleton.flipX) {
              x = -x;
              la = -la;
              lb = -lb;
            }
            if (skeleton.flipY) {
              y = -y;
              lc = -lc;
              ld = -ld;
            }
            this.a = la;
            this.b = lb;
            this.c = lc;
            this.d = ld;
            this.worldX = x + skeleton.x;
            this.worldY = y + 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 > 1e-4) {
              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;
            var zc = pc * cos + pd * sin;
            var s = Math.sqrt(za * za + zc * zc);
            s > 1e-5 && (s = 1 / s);
            za *= s;
            zc *= s;
            s = Math.sqrt(za * za + zc * zc);
            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;
            if (this.data.transformMode != spine.TransformMode.NoScaleOrReflection ? pa * pd - pb * pc < 0 : this.skeleton.flipX != this.skeleton.flipY) {
              this.b = -this.b;
              this.d = -this.d;
            }
            return;
          }
          if (this.skeleton.flipX) {
            this.a = -this.a;
            this.b = -this.b;
          }
          if (this.skeleton.flipY) {
            this.c = -this.c;
            this.d = -this.d;
          }
        };
        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.worldToLocalRotationX = function() {
          var parent = this.parent;
          if (null == parent) return this.arotation;
          var pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d, a = this.a, c = this.c;
          return Math.atan2(pa * c - pc * a, pd * a - pb * c) * spine.MathUtils.radDeg;
        };
        Bone.prototype.worldToLocalRotationY = function() {
          var parent = this.parent;
          if (null == parent) return this.arotation;
          var pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d, b = this.b, d = this.d;
          return Math.atan2(pa * d - pc * b, pd * b - pb * d) * 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;
        };
        Bone.prototype.updateAppliedTransform = function() {
          this.appliedValid = true;
          var parent = this.parent;
          if (null == parent) {
            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 > 1e-4) {
            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;
        };
        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;
          if (index < 0) throw new Error("index must be >= 0.");
          if (null == name) throw new Error("name cannot be null.");
          this.index = index;
          this.name = name;
          this.parent = parent;
        }
        return BoneData;
      })();
      spine.BoneData = BoneData;
      (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";
      })(spine.TransformMode || (spine.TransformMode = {}));
      var TransformMode = spine.TransformMode;
    })(spine || (spine = {}));
    var spine;
    (function(spine) {
      var Event = (function() {
        function Event(time, data) {
          if (null == data) 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.mix = 1;
          this.bendDirection = 0;
          if (null == data) throw new Error("data cannot be null.");
          if (null == skeleton) throw new Error("skeleton cannot be null.");
          this.data = data;
          this.mix = data.mix;
          this.bendDirection = data.bendDirection;
          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.getOrder = function() {
          return this.data.order;
        };
        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.mix);
            break;

           case 2:
            this.apply2(bones[0], bones[1], target.worldX, target.worldY, this.bendDirection, this.mix);
          }
        };
        IkConstraint.prototype.apply1 = function(bone, targetX, targetY, alpha) {
          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;
          bone.ascaleX < 0 && (rotationIK += 180);
          rotationIK > 180 ? rotationIK -= 360 : rotationIK < -180 && (rotationIK += 360);
          bone.updateWorldTransformWith(bone.ax, bone.ay, bone.arotation + rotationIK * alpha, bone.ascaleX, bone.ascaleY, bone.ashearX, bone.ashearY);
        };
        IkConstraint.prototype.apply2 = function(parent, child, targetX, targetY, bendDir, alpha) {
          if (0 == alpha) {
            child.updateWorldTransform();
            return;
          }
          parent.appliedValid || parent.updateAppliedTransform();
          child.appliedValid || child.updateAppliedTransform();
          var px = parent.ax, py = parent.ay, psx = parent.ascaleX, 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) <= 1e-4;
          if (u) {
            cy = child.ay;
            cwx = a * cx + b * cy + parent.worldX;
            cwy = c * cx + d * cy + parent.worldY;
          } else {
            cy = 0;
            cwx = a * cx + parent.worldX;
            cwy = c * cx + 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 = targetX - pp.worldX, y = targetY - pp.worldY;
          var tx = (x * d - y * b) * id - px, ty = (y * a - x * c) * id - py;
          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 = 0, a2 = 0;
          outer: if (u) {
            l2 *= psx;
            var cos = (tx * tx + ty * ty - l1 * l1 - l2 * l2) / (2 * l1 * l2);
            cos < -1 ? cos = -1 : cos > 1 && (cos = 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, dd = tx * tx + ty * ty, 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);
              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 = 0, minDist = Number.MAX_VALUE, minX = 0, minY = 0;
            var maxAngle = 0, maxDist = 0, maxX = 0, maxY = 0;
            x = l1 + a;
            d = x * x;
            if (d > maxDist) {
              maxAngle = 0;
              maxDist = d;
              maxX = x;
            }
            x = l1 - a;
            d = x * x;
            if (d < minDist) {
              minAngle = spine.MathUtils.PI;
              minDist = d;
              minX = x;
            }
            var angle = Math.acos(-a * l1 / (aa - bb));
            x = a * Math.cos(angle) + l1;
            y = b * Math.sin(angle);
            d = x * x + y * y;
            if (d < minDist) {
              minAngle = angle;
              minDist = d;
              minX = x;
              minY = y;
            }
            if (d > maxDist) {
              maxAngle = angle;
              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;
          a1 > 180 ? a1 -= 360 : a1 < -180 && (a1 += 360);
          parent.updateWorldTransformWith(px, py, rotation + a1 * alpha, parent.ascaleX, parent.ascaleY, 0, 0);
          rotation = child.arotation;
          a2 = ((a2 + os) * spine.MathUtils.radDeg - child.ashearX) * s2 + os2 - rotation;
          a2 > 180 ? a2 -= 360 : 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() {
        function IkConstraintData(name) {
          this.order = 0;
          this.bones = new Array();
          this.bendDirection = 1;
          this.mix = 1;
          this.name = name;
        }
        return IkConstraintData;
      })();
      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();
          if (null == data) throw new Error("data cannot be null.");
          if (null == skeleton) 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.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 spacingMode = data.spacingMode;
          var lengthSpacing = spacingMode == spine.SpacingMode.Length;
          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 || lengthSpacing) {
            scale && (lengths = spine.Utils.setArraySize(this.lengths, boneCount));
            for (var i = 0, n = spacesCount - 1; i < n; ) {
              var bone = bones[i];
              var length_1 = bone.data.length, x = length_1 * bone.a, y = length_1 * bone.c;
              length_1 = Math.sqrt(x * x + y * y);
              scale && (lengths[i] = length_1);
              spaces[++i] = lengthSpacing ? Math.max(0, length_1 + spacing) : spacing;
            }
          } else for (var i = 1; i < spacesCount; i++) spaces[i] = spacing;
          var positions = this.computeWorldPositions(attachment, spacesCount, tangents, data.positionMode == spine.PositionMode.Percent, spacingMode == spine.SpacingMode.Percent);
          var boneX = positions[0], boneY = positions[1], offsetRotation = data.offsetRotation;
          var tip = false;
          if (0 == offsetRotation) 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_2 = lengths[i];
              if (0 != length_2) {
                var s = (Math.sqrt(dx * dx + dy * dy) / length_2 - 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;
              r = tangents ? positions[p - 1] : 0 == spaces[i + 1] ? positions[p + 2] : Math.atan2(dy, dx);
              r -= Math.atan2(c, a);
              if (tip) {
                cos = Math.cos(r);
                sin = Math.sin(r);
                var length_3 = bone.data.length;
                boneX += (length_3 * (cos * a - sin * c) - dx) * rotateMix;
                boneY += (length_3 * (sin * a + cos * c) - dy) * rotateMix;
              } else r += offsetRotation;
              r > spine.MathUtils.PI ? r -= spine.MathUtils.PI2 : 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, 3 * spacesCount + 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];
            percentPosition && (position *= pathLength_1);
            if (percentSpacing) for (var i = 0; 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;
                p < 0 && (p += pathLength_1);
                curve = 0;
              } else {
                if (p < 0) {
                  if (prevCurve != PathConstraint.BEFORE) {
                    prevCurve = PathConstraint.BEFORE;
                    path.computeWorldVerticesWith(target, 2, 4, world, 0);
                  }
                  this.addBeforePosition(p, world, 0, out, o);
                  continue;
                }
                if (p > pathLength_1) {
                  if (prevCurve != PathConstraint.AFTER) {
                    prevCurve = PathConstraint.AFTER;
                    path.computeWorldVerticesWith(target, verticesLength - 6, 4, world, 0);
                  }
                  this.addAfterPosition(p - pathLength_1, world, 0, out, o);
                  continue;
                }
              }
              for (;;curve++) {
                var length_4 = lengths[curve];
                if (p > length_4) continue;
                if (0 == curve) p /= length_4; else {
                  var prev = lengths[curve - 1];
                  p = (p - prev) / (length_4 - prev);
                }
                break;
              }
              if (curve != prevCurve) {
                prevCurve = curve;
                if (closed && curve == curveCount) {
                  path.computeWorldVerticesWith(target, verticesLength - 4, 4, world, 0);
                  path.computeWorldVerticesWith(target, 0, 4, world, 4);
                } else path.computeWorldVerticesWith(target, 6 * curve + 2, 8, world, 0);
              }
              this.addCurvePosition(p, world[0], world[1], world[2], world[3], world[4], world[5], world[6], world[7], out, o, tangents || i > 0 && 0 == space);
            }
            return out;
          }
          if (closed) {
            verticesLength += 2;
            world = spine.Utils.setArraySize(this.world, verticesLength);
            path.computeWorldVerticesWith(target, 2, verticesLength - 4, world, 0);
            path.computeWorldVerticesWith(target, 0, 2, world, verticesLength - 4);
            world[verticesLength - 2] = world[0];
            world[verticesLength - 1] = world[1];
          } else {
            curveCount--;
            verticesLength -= 4;
            world = spine.Utils.setArraySize(this.world, verticesLength);
            path.computeWorldVerticesWith(target, 2, verticesLength, world, 0);
          }
          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 = .1875 * (x1 - 2 * cx1 + cx2);
            tmpy = .1875 * (y1 - 2 * cy1 + cy2);
            dddfx = .09375 * (3 * (cx1 - cx2) - x1 + x2);
            dddfy = .09375 * (3 * (cy1 - cy2) - y1 + y2);
            ddfx = 2 * tmpx + dddfx;
            ddfy = 2 * tmpy + dddfy;
            dfx = .75 * (cx1 - x1) + tmpx + .16666667 * dddfx;
            dfy = .75 * (cy1 - y1) + tmpy + .16666667 * dddfy;
            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;
          }
          percentPosition && (position *= pathLength);
          if (percentSpacing) for (var i = 0; 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;
              p < 0 && (p += pathLength);
              curve = 0;
            } else {
              if (p < 0) {
                this.addBeforePosition(p, world, 0, out, o);
                continue;
              }
              if (p > pathLength) {
                this.addAfterPosition(p - pathLength, world, verticesLength - 4, out, o);
                continue;
              }
            }
            for (;;curve++) {
              var length_5 = curves[curve];
              if (p > length_5) continue;
              if (0 == curve) p /= length_5; else {
                var prev = curves[curve - 1];
                p = (p - prev) / (length_5 - prev);
              }
              break;
            }
            if (curve != prevCurve) {
              prevCurve = curve;
              var ii = 6 * curve;
              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 = .03 * (x1 - 2 * cx1 + cx2);
              tmpy = .03 * (y1 - 2 * cy1 + cy2);
              dddfx = .006 * (3 * (cx1 - cx2) - x1 + x2);
              dddfy = .006 * (3 * (cy1 - cy2) - y1 + y2);
              ddfx = 2 * tmpx + dddfx;
              ddfy = 2 * tmpy + dddfy;
              dfx = .3 * (cx1 - x1) + tmpx + .16666667 * dddfx;
              dfy = .3 * (cy1 - y1) + tmpy + .16666667 * dddfy;
              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_6 = segments[segment];
              if (p > length_6) continue;
              if (0 == segment) p /= length_6; else {
                var prev = segments[segment - 1];
                p = segment + (p - prev) / (length_6 - prev);
              }
              break;
            }
            this.addCurvePosition(.1 * p, x1, y1, cx1, cy1, cx2, cy2, x2, y2, out, o, tangents || i > 0 && 0 == space);
          }
          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) {
          (0 == p || isNaN(p)) && (p = 1e-4);
          var tt = p * p, ttt = tt * p, u = 1 - p, uu = u * u, uuu = uu * u;
          var ut = u * p, ut3 = 3 * ut, 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;
          tangents && (out[o + 2] = Math.atan2(y - (y1 * uu + cy1 * ut * 2 + cy2 * tt), x - (x1 * uu + cx1 * ut * 2 + cx2 * tt)));
        };
        PathConstraint.prototype.getOrder = function() {
          return this.data.order;
        };
        PathConstraint.NONE = -1;
        PathConstraint.BEFORE = -2;
        PathConstraint.AFTER = -3;
        return PathConstraint;
      })();
      spine.PathConstraint = PathConstraint;
    })(spine || (spine = {}));
    var spine;
    (function(spine) {
      var PathConstraintData = (function() {
        function PathConstraintData(name) {
          this.order = 0;
          this.bones = new Array();
          this.name = name;
        }
        return PathConstraintData;
      })();
      spine.PathConstraintData = PathConstraintData;
      (function(PositionMode) {
        PositionMode[PositionMode["Fixed"] = 0] = "Fixed";
        PositionMode[PositionMode["Percent"] = 1] = "Percent";
      })(spine.PositionMode || (spine.PositionMode = {}));
      var PositionMode = spine.PositionMode;
      (function(SpacingMode) {
        SpacingMode[SpacingMode["Length"] = 0] = "Length";
        SpacingMode[SpacingMode["Fixed"] = 1] = "Fixed";
        SpacingMode[SpacingMode["Percent"] = 2] = "Percent";
      })(spine.SpacingMode || (spine.SpacingMode = {}));
      var SpacingMode = spine.SpacingMode;
      (function(RotateMode) {
        RotateMode[RotateMode["Tangent"] = 0] = "Tangent";
        RotateMode[RotateMode["Chain"] = 1] = "Chain";
        RotateMode[RotateMode["ChainScale"] = 2] = "ChainScale";
      })(spine.RotateMode || (spine.RotateMode = {}));
      var 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) {
          void 0 === pathPrefix && (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 (null === clientAssets || void 0 === clientAssets) {
            clientAssets = new Assets(clientId);
            this.clientAssets[clientId] = clientAssets;
          }
          null !== textureLoader && (clientAssets.textureLoader = textureLoader);
          clientAssets.toLoad.push(path);
          if (this.queuedAssets[path] === path) return false;
          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() {
            request.readyState == XMLHttpRequest.DONE && (request.status >= 200 && request.status < 300 ? _this.rawAssets[path] = request.responseText : _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() {
            request.readyState == XMLHttpRequest.DONE && (request.status >= 200 && request.status < 300 ? _this.rawAssets[path] = JSON.parse(request.responseText) : _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 (null === clientAssets || void 0 === clientAssets) 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 (null === asset || void 0 === asset) {
              var rawAsset = this.rawAssets[path];
              if (null === rawAsset || void 0 === rawAsset) continue;
              rawAsset instanceof HTMLImageElement ? clientAssets.assets[path] = clientAssets.textureLoader(rawAsset) : clientAssets.assets[path] = rawAsset;
            }
          }
        };
        SharedAssetManager.prototype.isLoadingComplete = function(clientId) {
          var clientAssets = this.clientAssets[clientId];
          if (null === clientAssets || void 0 === clientAssets) 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.flipX = false;
          this.flipY = false;
          this.x = 0;
          this.y = 0;
          if (null == data) 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 (null == boneData.parent) 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;
          var bones = this.bones;
          for (var i = 0, n = bones.length; i < n; i++) bones[i].sorted = false;
          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) {
          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];
            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) {
          var slot = constraint.target;
          var slotIndex = slot.data.index;
          var slotBone = slot.bone;
          null != this.skin && this.sortPathConstraintAttachment(this.skin, slotIndex, slotBone);
          null != this.data.defaultSkin && this.data.defaultSkin != this.skin && this.sortPathConstraintAttachment(this.data.defaultSkin, slotIndex, slotBone);
          for (var ii = 0, nn = this.data.skins.length; ii < nn; ii++) this.sortPathConstraintAttachment(this.data.skins[ii], slotIndex, slotBone);
          var attachment = slot.getAttachment();
          attachment instanceof spine.PathAttachment && this.sortPathConstraintAttachmentWith(attachment, slotBone);
          var constrained = constraint.bones;
          var boneCount = constrained.length;
          for (var ii = 0; ii < boneCount; ii++) this.sortBone(constrained[ii]);
          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.sortTransformConstraint = function(constraint) {
          this.sortBone(constraint.target);
          var constrained = constraint.bones;
          var boneCount = constrained.length;
          for (var ii = 0; ii < boneCount; ii++) this.sortBone(constrained[ii]);
          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 (null == pathBones) 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;
          null != parent && 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];
            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.bendDirection = constraint.data.bendDirection;
            constraint.mix = constraint.data.mix;
          }
          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 (0 == this.bones.length) return null;
          return this.bones[0];
        };
        Skeleton.prototype.findBone = function(boneName) {
          if (null == boneName) 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 (null == boneName) 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 (null == slotName) 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 (null == slotName) 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 (null == skin) throw new Error("Skin not found: " + skinName);
          this.setSkin(skin);
        };
        Skeleton.prototype.setSkin = function(newSkin) {
          if (null != newSkin) if (null != this.skin) 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 (null != name_1) {
                var attachment = newSkin.getAttachment(i, name_1);
                null != attachment && slot.setAttachment(attachment);
              }
            }
          }
          this.skin = newSkin;
        };
        Skeleton.prototype.getAttachmentByName = function(slotName, attachmentName) {
          return this.getAttachment(this.data.findSlotIndex(slotName), attachmentName);
        };
        Skeleton.prototype.getAttachment = function(slotIndex, attachmentName) {
          if (null == attachmentName) throw new Error("attachmentName cannot be null.");
          if (null != this.skin) {
            var attachment = this.skin.getAttachment(slotIndex, attachmentName);
            if (null != attachment) return attachment;
          }
          if (null != this.data.defaultSkin) return this.data.defaultSkin.getAttachment(slotIndex, attachmentName);
          return null;
        };
        Skeleton.prototype.setAttachment = function(slotName, attachmentName) {
          if (null == slotName) 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 (null != attachmentName) {
                attachment = this.getAttachment(i, attachmentName);
                if (null == attachment) 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 (null == constraintName) 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 (null == constraintName) 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 (null == constraintName) 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) {
          if (null == offset) throw new Error("offset cannot be null.");
          if (null == size) 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];
            var vertices = null;
            var attachment = slot.getAttachment();
            attachment instanceof spine.RegionAttachment ? vertices = attachment.updateWorldVertices(slot, false) : attachment instanceof spine.MeshAttachment && (vertices = attachment.updateWorldVertices(slot, true));
            if (null != vertices) for (var ii = 0, nn = vertices.length; ii < nn; ii += 8) {
              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 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 (null == skeleton) 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];
            var attachment = slot.getAttachment();
            if (attachment instanceof spine.BoundingBoxAttachment) {
              var boundingBox = attachment;
              boundingBoxes.push(boundingBox);
              var polygon = polygonPool.obtain();
              polygon.length != boundingBox.worldVerticesLength && (polygon = spine.Utils.newFloatArray(boundingBox.worldVerticesLength));
              polygons.push(polygon);
              boundingBox.computeWorldVertices(slot, polygon);
            }
          }
          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];
              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 (null == boundingBox) throw new Error("boundingBox cannot be null.");
          var index = this.boundingBoxes.indexOf(boundingBox);
          return -1 == index ? 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 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 (null == boneName) 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 (null == boneName) 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 (null == slotName) 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 (null == slotName) 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 (null == skinName) 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 (null == eventDataName) throw new Error("eventDataName cannot be null.");
          var events = this.events;
          for (var i = 0, n = events.length; i < n; i++) {
            var event_4 = events[i];
            if (event_4.name == eventDataName) return event_4;
          }
          return null;
        };
        SkeletonData.prototype.findAnimation = function(animationName) {
          if (null == animationName) 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 (null == constraintName) 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 (null == constraintName) 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 (null == constraintName) 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 (null == pathConstraintName) 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 = "string" === typeof json ? JSON.parse(json) : json;
          var skeletonMap = root.skeleton;
          if (null != skeletonMap) {
            skeletonData.hash = skeletonMap.hash;
            skeletonData.version = skeletonMap.spine;
            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_2 = null;
            var parentName = this.getValue(boneMap, "parent", null);
            if (null != parentName) {
              parent_2 = skeletonData.findBone(parentName);
              if (null == parent_2) throw new Error("Parent bone not found: " + parentName);
            }
            var data = new spine.BoneData(skeletonData.bones.length, boneMap.name, parent_2);
            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"));
            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 (null == boneData) 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);
            null != color && data.color.setFromString(color);
            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);
            for (var j = 0; j < constraintMap.bones.length; j++) {
              var boneName = constraintMap.bones[j];
              var bone = skeletonData.findBone(boneName);
              if (null == bone) throw new Error("IK bone not found: " + boneName);
              data.bones.push(bone);
            }
            var targetName = constraintMap.target;
            data.target = skeletonData.findBone(targetName);
            if (null == data.target) throw new Error("IK target bone not found: " + targetName);
            data.bendDirection = this.getValue(constraintMap, "bendPositive", true) ? 1 : -1;
            data.mix = this.getValue(constraintMap, "mix", 1);
            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);
            for (var j = 0; j < constraintMap.bones.length; j++) {
              var boneName = constraintMap.bones[j];
              var bone = skeletonData.findBone(boneName);
              if (null == bone) throw new Error("Transform constraint bone not found: " + boneName);
              data.bones.push(bone);
            }
            var targetName = constraintMap.target;
            data.target = skeletonData.findBone(targetName);
            if (null == data.target) throw new Error("Transform constraint target bone not found: " + targetName);
            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);
            for (var j = 0; j < constraintMap.bones.length; j++) {
              var boneName = constraintMap.bones[j];
              var bone = skeletonData.findBone(boneName);
              if (null == bone) throw new Error("Transform constraint bone not found: " + boneName);
              data.bones.push(bone);
            }
            var targetName = constraintMap.target;
            data.target = skeletonData.findSlot(targetName);
            if (null == data.target) 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);
            data.positionMode == spine.PositionMode.Fixed && (data.position *= scale);
            data.spacing = this.getValue(constraintMap, "spacing", 0);
            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) for (var skinName in root.skins) {
            var skinMap = root.skins[skinName];
            var skin = new spine.Skin(skinName);
            for (var slotName in skinMap) {
              var slotIndex = skeletonData.findSlotIndex(slotName);
              if (-1 == slotIndex) throw new Error("Slot not found: " + slotName);
              var slotMap = skinMap[slotName];
              for (var entryName in slotMap) {
                var attachment = this.readAttachment(slotMap[entryName], skin, slotIndex, entryName);
                null != attachment && skin.addAttachment(slotIndex, entryName, attachment);
              }
            }
            skeletonData.skins.push(skin);
            "default" == skin.name && (skeletonData.defaultSkin = skin);
          }
          for (var i = 0, n = this.linkedMeshes.length; i < n; i++) {
            var linkedMesh = this.linkedMeshes[i];
            var skin = null == linkedMesh.skin ? skeletonData.defaultSkin : skeletonData.findSkin(linkedMesh.skin);
            if (null == skin) throw new Error("Skin not found: " + linkedMesh.skin);
            var parent_3 = skin.getAttachment(linkedMesh.slotIndex, linkedMesh.parent);
            if (null == parent_3) throw new Error("Parent mesh not found: " + linkedMesh.parent);
            linkedMesh.mesh.setParentMesh(parent_3);
            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", "");
            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) {
          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 (null == region) 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);
            null != color && region.color.setFromString(color);
            region.updateOffset();
            return region;

           case "boundingbox":
            var box = this.attachmentLoader.newBoundingBoxAttachment(skin, name);
            if (null == box) return null;
            this.readVertices(map, box, map.vertexCount << 1);
            var color = this.getValue(map, "color", null);
            null != color && 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 (null == mesh) return null;
            mesh.path = path;
            var color = this.getValue(map, "color", null);
            null != color && mesh.color.setFromString(color);
            var parent_4 = this.getValue(map, "parent", null);
            if (null != parent_4) {
              mesh.inheritDeform = this.getValue(map, "deform", true);
              this.linkedMeshes.push(new LinkedMesh(mesh, this.getValue(map, "skin", null), slotIndex, parent_4));
              return mesh;
            }
            var uvs = map.uvs;
            this.readVertices(map, mesh, uvs.length);
            mesh.triangles = map.triangles;
            mesh.regionUVs = uvs;
            mesh.updateUVs();
            mesh.hullLength = 2 * this.getValue(map, "hull", 0);
            return mesh;

           case "path":
            var path = this.attachmentLoader.newPathAttachment(skin, name);
            if (null == path) 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);
            null != color && path.color.setFromString(color);
            return path;
          }
          return null;
        };
        SkeletonJson.prototype.readVertices = function(map, attachment, verticesLength) {
          var scale = this.scale;
          attachment.worldVerticesLength = verticesLength;
          var vertices = map.vertices;
          if (verticesLength == vertices.length) {
            if (1 != scale) for (var i = 0, n = vertices.length; i < n; i++) vertices[i] *= scale;
            attachment.vertices = spine.Utils.toFloatArray(vertices);
            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 + 4 * boneCount; 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 (-1 == slotIndex) throw new Error("Slot not found: " + slotName);
            for (var timelineName in slotMap) {
              var timelineMap = slotMap[timelineName];
              if ("color" == timelineName) {
                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, valueMap.time, 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 = "attachment")) throw new Error("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")");
                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++, valueMap.time, valueMap.name);
                }
                timelines.push(timeline);
                duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
              }
            }
          }
          if (map.bones) for (var boneName in map.bones) {
            var boneMap = map.bones[boneName];
            var boneIndex = skeletonData.findBoneIndex(boneName);
            if (-1 == boneIndex) throw new Error("Bone not found: " + boneName);
            for (var timelineName in boneMap) {
              var timelineMap = boneMap[timelineName];
              if ("rotate" === timelineName) {
                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, valueMap.time, valueMap.angle);
                  this.readCurve(valueMap, timeline, frameIndex);
                  frameIndex++;
                }
                timelines.push(timeline);
                duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.RotateTimeline.ENTRIES]);
              } else {
                if ("translate" !== timelineName && "scale" !== timelineName && "shear" !== timelineName) throw new Error("Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")");
                var timeline = null;
                var timelineScale = 1;
                if ("scale" === timelineName) timeline = new spine.ScaleTimeline(timelineMap.length); else if ("shear" === timelineName) 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", 0), y = this.getValue(valueMap, "y", 0);
                  timeline.setFrame(frameIndex, valueMap.time, 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]);
              }
            }
          }
          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, valueMap.time, this.getValue(valueMap, "mix", 1), this.getValue(valueMap, "bendPositive", true) ? 1 : -1);
              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, valueMap.time, 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]);
          }
          if (map.paths) for (var constraintName in map.paths) {
            var constraintMap = map.paths[constraintName];
            var index = skeletonData.findPathConstraintIndex(constraintName);
            if (-1 == index) throw new Error("Path constraint not found: " + constraintName);
            var data = skeletonData.pathConstraints[index];
            for (var timelineName in constraintMap) {
              var timelineMap = constraintMap[timelineName];
              if ("position" === timelineName || "spacing" === timelineName) {
                var timeline = null;
                var timelineScale = 1;
                if ("spacing" === timelineName) {
                  timeline = new spine.PathConstraintSpacingTimeline(timelineMap.length);
                  data.spacingMode != spine.SpacingMode.Length && data.spacingMode != spine.SpacingMode.Fixed || (timelineScale = scale);
                } else {
                  timeline = new spine.PathConstraintPositionTimeline(timelineMap.length);
                  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, valueMap.time, 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 ("mix" === timelineName) {
                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, valueMap.time, 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 (null == skin) throw new Error("Skin not found: " + deformName);
            for (var slotName in deformMap) {
              var slotMap = deformMap[slotName];
              var slotIndex = skeletonData.findSlotIndex(slotName);
              if (-1 == slotIndex) throw new Error("Slot not found: " + slotMap.name);
              for (var timelineName in slotMap) {
                var timelineMap = slotMap[timelineName];
                var attachment = skin.getAttachment(slotIndex, timelineName);
                if (null == attachment) throw new Error("Deform attachment not found: " + timelineMap.name);
                var weighted = null != attachment.bones;
                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 (null == verticesValue) 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 (1 != scale) 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, valueMap.time, deform);
                  this.readCurve(valueMap, timeline, frameIndex);
                  frameIndex++;
                }
                timelines.push(timeline);
                duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
              }
            }
          }
          var drawOrderNode = map.drawOrder;
          null == drawOrderNode && (drawOrderNode = map.draworder);
          if (null != drawOrderNode) {
            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 (null != offsets) {
                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 (-1 == slotIndex) 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--) -1 == drawOrder[i] && (drawOrder[i] = unchanged[--unchangedIndex]);
              }
              timeline.setFrame(frameIndex++, drawOrderMap.time, 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 (null == eventData) throw new Error("Event not found: " + eventMap.name);
              var event_5 = new spine.Event(eventMap.time, eventData);
              event_5.intValue = this.getValue(eventMap, "int", eventData.intValue);
              event_5.floatValue = this.getValue(eventMap, "float", eventData.floatValue);
              event_5.stringValue = this.getValue(eventMap, "string", eventData.stringValue);
              timeline.setFrame(frameIndex++, event_5);
            }
            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) {
          if (!map.curve) return;
          if ("stepped" === map.curve) timeline.setStepped(frameIndex); else if ("[object Array]" === Object.prototype.toString.call(map.curve)) {
            var curve = map.curve;
            timeline.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]);
          }
        };
        SkeletonJson.prototype.getValue = function(map, prop, defaultValue) {
          return void 0 !== map[prop] ? map[prop] : defaultValue;
        };
        SkeletonJson.blendModeFromString = function(str) {
          str = str.toLowerCase();
          if ("normal" == str) return spine.BlendMode.Normal;
          if ("additive" == str) return spine.BlendMode.Additive;
          if ("multiply" == str) return spine.BlendMode.Multiply;
          if ("screen" == str) return spine.BlendMode.Screen;
          throw new Error("Unknown blend mode: " + str);
        };
        SkeletonJson.positionModeFromString = function(str) {
          str = str.toLowerCase();
          if ("fixed" == str) return spine.PositionMode.Fixed;
          if ("percent" == str) return spine.PositionMode.Percent;
          throw new Error("Unknown position mode: " + str);
        };
        SkeletonJson.spacingModeFromString = function(str) {
          str = str.toLowerCase();
          if ("length" == str) return spine.SpacingMode.Length;
          if ("fixed" == str) return spine.SpacingMode.Fixed;
          if ("percent" == str) return spine.SpacingMode.Percent;
          throw new Error("Unknown position mode: " + str);
        };
        SkeletonJson.rotateModeFromString = function(str) {
          str = str.toLowerCase();
          if ("tangent" == str) return spine.RotateMode.Tangent;
          if ("chain" == str) return spine.RotateMode.Chain;
          if ("chainscale" == str) return spine.RotateMode.ChainScale;
          throw new Error("Unknown rotate mode: " + str);
        };
        SkeletonJson.transformModeFromString = function(str) {
          str = str.toLowerCase();
          if ("normal" == str) return spine.TransformMode.Normal;
          if ("onlytranslation" == str) return spine.TransformMode.OnlyTranslation;
          if ("norotationorreflection" == str) return spine.TransformMode.NoRotationOrReflection;
          if ("noscale" == str) return spine.TransformMode.NoScale;
          if ("noscaleorreflection" == str) 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) {
          this.mesh = mesh;
          this.skin = skin;
          this.slotIndex = slotIndex;
          this.parent = parent;
        }
        return LinkedMesh;
      })();
    })(spine || (spine = {}));
    var spine;
    (function(spine) {
      var Skin = (function() {
        function Skin(name) {
          this.attachments = new Array();
          if (null == name) throw new Error("name cannot be null.");
          this.name = name;
        }
        Skin.prototype.addAttachment = function(slotIndex, name, attachment) {
          if (null == attachment) throw new Error("attachment cannot be null.");
          var attachments = this.attachments;
          slotIndex >= attachments.length && (attachments.length = slotIndex + 1);
          attachments[slotIndex] || (attachments[slotIndex] = {});
          attachments[slotIndex][name] = attachment;
        };
        Skin.prototype.getAttachment = function(slotIndex, name) {
          var dictionary = this.attachments[slotIndex];
          return dictionary ? dictionary[name] : null;
        };
        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);
                  null != attachment && slot.setAttachment(attachment);
                  break;
                }
              }
            }
            slotIndex++;
          }
        };
        return Skin;
      })();
      spine.Skin = Skin;
    })(spine || (spine = {}));
    var spine;
    (function(spine) {
      var Slot = (function() {
        function Slot(data, bone) {
          this.attachmentVertices = new Array();
          if (null == data) throw new Error("data cannot be null.");
          if (null == bone) throw new Error("bone cannot be null.");
          this.data = data;
          this.bone = bone;
          this.color = new spine.Color();
          this.setToSetupPose();
        }
        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.attachmentVertices.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 (null == this.data.attachmentName) 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 (null == name) throw new Error("name cannot be null.");
          if (null == boneData) 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;
      (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";
      })(spine.TextureFilter || (spine.TextureFilter = {}));
      var TextureFilter = spine.TextureFilter;
      (function(TextureWrap) {
        TextureWrap[TextureWrap["MirroredRepeat"] = 33648] = "MirroredRepeat";
        TextureWrap[TextureWrap["ClampToEdge"] = 33071] = "ClampToEdge";
        TextureWrap[TextureWrap["Repeat"] = 10497] = "Repeat";
      })(spine.TextureWrap || (spine.TextureWrap = {}));
      var 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;
    })(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 (null == textureLoader) 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 (null == line) break;
            line = line.trim();
            if (0 == line.length) page = null; else if (page) {
              var region = new TextureAtlasRegion();
              region.name = line;
              region.page = page;
              region.rotate = "true" == reader.readValue();
              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);
              4 == reader.readTuple(tuple) && 4 == reader.readTuple(tuple) && 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);
            } else {
              page = new TextureAtlasPage();
              page.name = line;
              if (2 == reader.readTuple(tuple)) {
                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;
              "x" == direction ? page.uWrap = spine.TextureWrap.Repeat : "y" == direction ? page.vWrap = spine.TextureWrap.Repeat : "xy" == direction && (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);
            }
          }
        };
        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 (-1 == colon) 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 (-1 == colon) throw new Error("Invalid line: " + line);
          var i = 0, lastMatch = colon + 1;
          for (;i < 3; i++) {
            var comma = line.indexOf(",", lastMatch);
            if (-1 == comma) 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() {
          _super.apply(this, arguments);
        }
        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();
          if (null == data) throw new Error("data cannot be null.");
          if (null == skeleton) 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.apply = function() {
          this.update();
        };
        TransformConstraint.prototype.update = 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 (0 != rotateMix) {
              var a = bone.a, b = bone.b, c = bone.c, d = bone.d;
              var r = Math.atan2(tc, ta) - Math.atan2(c, a) + offsetRotation;
              r > spine.MathUtils.PI ? r -= spine.MathUtils.PI2 : 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 (0 != translateMix) {
              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);
              s > 1e-5 && (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);
              s > 1e-5 && (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));
              r > spine.MathUtils.PI ? r -= spine.MathUtils.PI2 : 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;
            }
            modified && (bone.appliedValid = false);
          }
        };
        TransformConstraint.prototype.getOrder = function() {
          return this.data.order;
        };
        return TransformConstraint;
      })();
      spine.TransformConstraint = TransformConstraint;
    })(spine || (spine = {}));
    var spine;
    (function(spine) {
      var TransformConstraintData = (function() {
        function TransformConstraintData(name) {
          this.order = 0;
          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;
          if (null == name) throw new Error("name cannot be null.");
          this.name = name;
        }
        return TransformConstraintData;
      })();
      spine.TransformConstraintData = TransformConstraintData;
    })(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[0 | value] = 0 | value;
          return !contains;
        };
        IntSet.prototype.contains = function(value) {
          return void 0 != this.array[0 | value];
        };
        IntSet.prototype.remove = function(value) {
          this.array[0 | value] = void 0;
        };
        IntSet.prototype.clear = function() {
          this.array.length = 0;
        };
        return IntSet;
      })();
      spine.IntSet = IntSet;
      var Color = (function() {
        function Color(r, g, b, a) {
          void 0 === r && (r = 0);
          void 0 === g && (g = 0);
          void 0 === b && (b = 0);
          void 0 === a && (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;
          this.g = parseInt(hex.substr(2, 2), 16) / 255;
          this.b = parseInt(hex.substr(4, 2), 16) / 255;
          this.a = (8 != hex.length ? 255 : parseInt(hex.substr(6, 2), 16)) / 255;
          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() {
          this.r < 0 ? this.r = 0 : this.r > 1 && (this.r = 1);
          this.g < 0 ? this.g = 0 : this.g > 1 && (this.g = 1);
          this.b < 0 ? this.b = 0 : this.b > 1 && (this.b = 1);
          this.a < 0 ? this.a = 0 : this.a > 1 && (this.a = 1);
          return this;
        };
        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.PI = 3.1415927;
        MathUtils.PI2 = 2 * MathUtils.PI;
        MathUtils.radiansToDegrees = 180 / MathUtils.PI;
        MathUtils.radDeg = MathUtils.radiansToDegrees;
        MathUtils.degreesToRadians = MathUtils.PI / 180;
        MathUtils.degRad = MathUtils.degreesToRadians;
        return MathUtils;
      })();
      spine.MathUtils = MathUtils;
      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) {
          void 0 === value && (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) {
          void 0 === value && (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);
          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.SUPPORTS_TYPED_ARRAYS = "undefined" !== typeof Float32Array;
        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) {
          item.reset && item.reset();
          this.items.push(item);
        };
        Pool.prototype.freeAll = function(items) {
          for (var i = 0; i < items.length; i++) {
            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) {
          void 0 === x && (x = 0);
          void 0 === y && (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 (0 != len) {
            this.x /= len;
            this.y /= len;
          }
          return this;
        };
        return Vector2;
      })();
      spine.Vector2 = Vector2;
      var TimeKeeper = (function() {
        function TimeKeeper() {
          this.maxDelta = .064;
          this.framesPerSecond = 0;
          this.delta = 0;
          this.totalTime = 0;
          this.lastTime = Date.now() / 1e3;
          this.frameCount = 0;
          this.frameTime = 0;
        }
        TimeKeeper.prototype.update = function() {
          var now = Date.now() / 1e3;
          this.delta = now - this.lastTime;
          this.frameTime += this.delta;
          this.totalTime += this.delta;
          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;
    })(spine || (spine = {}));
    module.exports = spine;
  }), {} ],
  309: [ (function(require, module, exports) {
    (function() {
      "use strict";
      Function.prototype._extend = function(parent) {
        this.prototype.parent = parent;
        for (var x in parent.prototype) this.prototype[x] || (this.prototype[x] = parent.prototype[x]);
      };
      Function.prototype._implement = function(parent) {
        return this._extend(parent);
      };
      var b2Profiler = (function() {
        "undefined" === typeof performance && (window["performance"] = {
          now: function() {
            return +new Date();
          }
        });
        function profileStruct(name, parent) {
          this.name = name;
          this.parent = parent;
          this.children = {};
          this.startTime = 0;
          this.elapsedTime = 0;
          this.totalTime = 0;
          this.running = false;
          this.childrenCount = 0;
        }
        profileStruct.prototype = {
          start: function() {
            this.startTime = performance.now();
            this.running = true;
          },
          stop: function(reset) {
            if (!this.running) return;
            this.running = false;
            this.elapsedTime += performance.now() - this.startTime;
            reset && this.start();
            for (var x in this.children) this.children[x].stop();
          },
          reset: function(dontRun) {
            if (!dontRun) {
              this.running = true;
              this.totalTime += this.elapsedTime;
              this.start();
            }
            this.elapsedTime = 0;
            for (var x in this.children) this.children[x].reset(true);
          }
        };
        var profiles = [];
        var root = new profileStruct("root");
        function create(name, parent) {
          if (!profiles) throw new Error("late profile creation not allowed");
          var s = new profileStruct(name, parent || "root");
          profiles.push(s);
          return s;
        }
        function destroy(profile) {
          profile.childrenCount--;
          delete profile.children[profile.name];
        }
        function recursiveParentCheck(node, profile) {
          if (node.name === profile.parent) return node;
          for (var x in node.children) {
            var n;
            if (n = recursiveParentCheck(node.children[x], profile)) return n;
          }
          return null;
        }
        function init() {
          while (profiles.length) {
            var p = profiles.pop();
            if (p.parentNode = recursiveParentCheck(root, p)) {
              p.parentNode.children[p.name] = p;
              p.parentNode.childrenCount++;
            } else profiles.unshift(p);
          }
          profiles = null;
        }
        function resetAll() {
          root.reset(true);
        }
        return {
          create: create,
          destroy: destroy,
          init: init,
          reset: resetAll,
          profileRoot: root
        };
      })();
      function b2Assert(A) {
        if (!A) {
          console.log("Assertion failed! Pls debug.");
          debugger;
        }
      }
      var b2_maxFloat = Number.MAX_VALUE;
      var b2_epsilon = 2.220446049250313e-16;
      var b2_pi = Math.PI;
      var b2_maxManifoldPoints = 2;
      var b2_maxPolygonVertices = 8;
      var b2_aabbExtension = .1;
      var b2_aabbMultiplier = 2;
      var b2_linearSlop = .005;
      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 = .2;
      var b2_maxAngularCorrection = 8 / 180 * b2_pi;
      var b2_maxTranslation = 2;
      var b2_maxTranslationSquared = b2_maxTranslation * b2_maxTranslation;
      var b2_maxRotation = .5 * b2_pi;
      var b2_maxRotationSquared = b2_maxRotation * b2_maxRotation;
      var b2_baumgarte = .2;
      var b2_toiBaugarte = .75;
      var b2_timeToSleep = .5;
      var b2_linearSleepTolerance = .01;
      var b2_angularSleepTolerance = 2 / 180 * b2_pi;
      function b2Version(ma, mi, re) {
        this.major = ma;
        this.minor = mi;
        this.revision = re;
      }
      b2Version.prototype = {
        toString: function() {
          return this.major + "." + this.minor + "." + this.revision;
        }
      };
      var b2_version = new b2Version(2, 3, 1);
      function b2IsValid(x) {
        return isFinite(x) && !isNaN(x);
      }
      var sqrtf = Math.sqrt;
      var atan2f = Math.atan2;
      var sinf = Math.sin;
      var cosf = Math.cos;
      var floorf = Math.floor;
      var ceilf = Math.ceil;
      var b2Sqrt = sqrtf;
      var b2Atan2 = atan2f;
      function b2InvSqrt(x) {
        return 1 / sqrtf(x);
      }
      function b2Vec2(x, y) {
        if ("undefined" !== typeof x) {
          this.x = x;
          this.y = y;
        } else this.x = this.y = 0;
      }
      b2Vec2.prototype = {
        Clone: function() {
          return new b2Vec2(this.x, this.y);
        },
        SetZero: function() {
          this.x = 0;
          this.y = 0;
          return this;
        },
        Set: function(x_, y_) {
          this.x = x_;
          this.y = y_;
          return this;
        },
        Assign: function(l) {
          this.x = l.x;
          this.y = l.y;
          return this;
        },
        Negate: function() {
          var v = new b2Vec2();
          v.Set(-this.x, -this.y);
          return v;
        },
        get_i: function(i) {
          switch (i) {
           case 0:
            return this.x;

           case 1:
            return this.y;
          }
        },
        set_i: function(i, v) {
          switch (i) {
           case 0:
            return this.x = v;

           case 1:
            return this.y = v;
          }
        },
        Add: function(v) {
          this.x += v.x;
          this.y += v.y;
          return this;
        },
        Subtract: function(v) {
          this.x -= v.x;
          this.y -= v.y;
          return this;
        },
        Multiply: function(a) {
          this.x *= a;
          this.y *= a;
          return this;
        },
        Length: function() {
          return b2Sqrt(this.x * this.x + this.y * this.y);
        },
        LengthSquared: function() {
          return this.x * this.x + this.y * this.y;
        },
        Normalize: function() {
          var length = this.Length();
          if (length < b2_epsilon) return 0;
          var invLength = 1 / length;
          this.x *= invLength;
          this.y *= invLength;
          return length;
        },
        IsValid: function() {
          return b2IsValid(this.x) && b2IsValid(this.y);
        },
        Skew: function() {
          return new b2Vec2(-this.y, this.x);
        },
        _serialize: function(out) {
          var obj = out || [];
          obj[0] = this.x;
          obj[1] = this.y;
          return obj;
        },
        _deserialize: function(data) {
          this.x = data[0];
          this.y = data[1];
        }
      };
      b2Vec2.Add = function(a, b) {
        return new b2Vec2(a.x + b.x, a.y + b.y);
      };
      b2Vec2.Subtract = function(a, b) {
        return new b2Vec2(a.x - b.x, a.y - b.y);
      };
      b2Vec2.Equals = function(a, b) {
        return a.x == b.x && a.y == b.y;
      };
      b2Vec2.Multiply = function(s, a) {
        return new b2Vec2(s * a.x, s * a.y);
      };
      b2Vec2.Negate = function(a) {
        return new b2Vec2(-a.x, -a.y);
      };
      function b2Vec3(x, y, z) {
        if ("undefined" !== typeof x) {
          this.x = x;
          this.y = y;
          this.z = z;
        }
      }
      b2Vec3.prototype = {
        Clone: function() {
          return new b2Vec3(this.x, this.y, this.z);
        },
        SetZero: function() {
          this.x = 0;
          this.y = 0;
          this.z = 0;
        },
        Set: function(x_, y_, z_) {
          this.x = x_;
          this.y = y_;
          this.z = z_;
        },
        Negate: function() {
          var v = new b2Vec3();
          v.Set(-this.x, -this.y, -this.z);
          return v;
        },
        Add: function(v) {
          this.x += v.x;
          this.y += v.y;
          this.z += v.z;
        },
        Subtract: function(v) {
          this.x -= v.x;
          this.y -= v.y;
          this.z -= v.z;
        },
        Multiply: function(s) {
          this.x *= s;
          this.y *= s;
          this.z *= s;
        },
        Invert: function() {
          this.x = -this.x;
          this.y = -this.y;
          this.z = -this.z;
          return this;
        },
        x: 0,
        y: 0,
        z: 0
      };
      b2Vec3.Multiply = function(s, a) {
        return new b2Vec3(s * a.x, s * a.y, s * a.z);
      };
      b2Vec3.Add = function(a, b) {
        return new b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z);
      };
      b2Vec3.Subtract = function(a, b) {
        return new b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z);
      };
      function b2Mat22(c1, c2) {
        this.ex = c1 ? c1.Clone() : new b2Vec2();
        this.ey = c2 ? c2.Clone() : new b2Vec2();
      }
      b2Mat22.prototype = {
        Set: function(c1, c2) {
          this.ex.Assign(c1);
          this.ey.Assign(c2);
        },
        Assign: function(mat) {
          this.ex.Assign(mat.ex);
          this.ey.Assign(mat.ey);
        },
        SetIdentity: function() {
          this.ex.x = 1;
          this.ey.x = 0;
          this.ex.y = 0;
          this.ey.y = 1;
        },
        SetZero: function() {
          this.ex.x = 0;
          this.ey.x = 0;
          this.ex.y = 0;
          this.ey.y = 0;
        },
        GetInverse: function() {
          var a = this.ex.x, b = this.ey.x, c = this.ex.y, d = this.ey.y;
          var B = new b2Mat22();
          var det = a * d - b * c;
          0 != det && (det = 1 / det);
          B.ex.x = det * d;
          B.ey.x = -det * b;
          B.ex.y = -det * c;
          B.ey.y = det * a;
          return B;
        },
        Solve: function(b) {
          var a11 = this.ex.x, a12 = this.ey.x, a21 = this.ex.y, a22 = this.ey.y;
          var det = a11 * a22 - a12 * a21;
          0 != det && (det = 1 / det);
          var x = new b2Vec2();
          x.x = det * (a22 * b.x - a12 * b.y);
          x.y = det * (a11 * b.y - a21 * b.x);
          return x;
        }
      };
      b2Mat22.Add = function(A, B) {
        return new b2Mat22(b2Vec2.Add(A.ex, B.ex), b2Vec2.Add(A.ey, B.ey));
      };
      function b2Mat33(c1, c2, c3) {
        this.ex = c1 ? c1.Clone() : new b2Vec3();
        this.ey = c2 ? c2.Clone() : new b2Vec3();
        this.ez = c3 ? c3.Clone() : new b2Vec3();
      }
      b2Mat33.prototype = {
        SetZero: function() {
          this.ex.SetZero();
          this.ey.SetZero();
          this.ez.SetZero();
        },
        Solve33: function(b) {
          var det = b2Dot_v3_v3(this.ex, b2Cross_v3_v3(this.ey, this.ez));
          0 != det && (det = 1 / det);
          var x = new b2Vec3();
          x.x = det * b2Dot_v3_v3(b, b2Cross_v3_v3(this.ey, this.ez));
          x.y = det * b2Dot_v3_v3(this.ex, b2Cross_v3_v3(b, this.ez));
          x.z = det * b2Dot_v3_v3(this.ex, b2Cross_v3_v3(this.ey, b));
          return x;
        },
        Solve22: function(b) {
          var a11 = this.ex.x, a12 = this.ey.x, a21 = this.ex.y, a22 = this.ey.y;
          var det = a11 * a22 - a12 * a21;
          0 != det && (det = 1 / det);
          var x = new b2Vec2();
          x.x = det * (a22 * b.x - a12 * b.y);
          x.y = det * (a11 * b.y - a21 * b.x);
          return x;
        },
        GetInverse22: function(M) {
          var a = this.ex.x, b = this.ey.x, c = this.ex.y, d = this.ey.y;
          var det = a * d - b * c;
          0 != det && (det = 1 / det);
          M.ex.x = det * d;
          M.ey.x = -det * b;
          M.ex.z = 0;
          M.ex.y = -det * c;
          M.ey.y = det * a;
          M.ey.z = 0;
          M.ez.x = 0;
          M.ez.y = 0;
          M.ez.z = 0;
        },
        GetSymInverse33: function(M) {
          var det = b2Dot_v3_v3(this.ex, b2Cross_v3_v3(this.ey, this.ez));
          0 != det && (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);
        }
      };
      function b2Rot(angle, c) {
        if ("undefined" !== typeof c) {
          this.s = angle;
          this.c = c;
        } else "undefined" !== typeof angle && this.Set(angle);
      }
      b2Rot.prototype = {
        Clone: function() {
          return new b2Rot(this.s, this.c);
        },
        Assign: function(l) {
          this.s = l.s;
          this.c = l.c;
        },
        Set: function(x) {
          this.s = sinf(x);
          this.c = cosf(x);
        },
        SetIdentity: function() {
          this.s = 0;
          this.c = 1;
        },
        GetAngle: function() {
          return b2Atan2(this.s, this.c);
        },
        GetXAxis: function() {
          return new b2Vec2(this.c, this.s);
        },
        GetYAxis: function() {
          return new b2Vec2(-this.s, this.c);
        },
        s: 0,
        c: 1
      };
      function b2Transform(position, rotation) {
        this.p = new b2Vec2();
        this.q = new b2Rot();
        if (position) {
          this.p.Assign(position);
          this.q.Assign(rotation);
        }
      }
      b2Transform.prototype = {
        Clone: function() {
          var xf = new b2Transform(this.p, this.q);
          return xf;
        },
        Assign: function(xf) {
          this.p.Assign(xf.p);
          this.q.Assign(xf.q);
        },
        SetIdentity: function() {
          this.p.SetZero();
          this.q.SetIdentity();
        },
        Set: function(position, angle) {
          this.p.Assign(position);
          this.q.Set(angle);
        }
      };
      function b2Sweep() {
        this.localCenter = new b2Vec2();
        this.c0 = new b2Vec2();
        this.c = new b2Vec2();
      }
      b2Sweep.prototype = {
        Assign: function(sweep) {
          this.localCenter.Assign(sweep.localCenter);
          this.c0.Assign(sweep.c0);
          this.c.Assign(sweep.c);
          this.a = sweep.a;
          this.a0 = sweep.a0;
          this.alpha0 = sweep.alpha0;
        },
        Clone: function() {
          var sweep = new b2Sweep();
          sweep.localCenter.Assign(this.localCenter);
          sweep.c0.Assign(this.c0);
          sweep.c.Assign(this.c);
          sweep.a = this.a;
          sweep.a0 = this.a0;
          sweep.alpha0 = this.alpha0;
          return sweep;
        },
        GetTransform: function(xf, beta) {
          xf.p.x = (1 - beta) * this.c0.x + beta * this.c.x;
          xf.p.y = (1 - beta) * this.c0.y + beta * this.c.y;
          var angle = (1 - beta) * this.a0 + beta * this.a;
          xf.q.Set(angle);
          xf.p.x -= xf.q.c * this.localCenter.x - xf.q.s * this.localCenter.y;
          xf.p.y -= xf.q.s * this.localCenter.x + xf.q.c * this.localCenter.y;
        },
        Advance: function(alpha) {
          b2Assert(this.alpha0 < 1);
          var beta = (alpha - this.alpha0) / (1 - this.alpha0);
          this.c0.Add(b2Vec2.Multiply(beta, b2Vec2.Subtract(this.c, this.c0)));
          this.a0 += beta * (this.a - this.a0);
          this.alpha0 = alpha;
        },
        Normalize: function() {
          var twoPi = 2 * b2_pi;
          var d = twoPi * floorf(this.a0 / twoPi);
          this.a0 -= d;
          this.a -= d;
        },
        a0: 0,
        a: 0,
        alpha0: 0
      };
      function b2Dot_v2_v2(a, b) {
        return a.x * b.x + a.y * b.y;
      }
      function b2Cross_v2_v2(a, b) {
        return a.x * b.y - a.y * b.x;
      }
      function b2Cross_v2_f(a, s) {
        return new b2Vec2(s * a.y, -s * a.x);
      }
      function b2Cross_f_v2(s, a) {
        return new b2Vec2(-s * a.y, s * a.x);
      }
      function b2Mul_m22_v2(A, v) {
        return new b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y);
      }
      function b2MulT_m22_v2(A, v) {
        return new b2Vec2(b2Dot_v2_v2(v, A.ex), b2Dot_v2_v2(v, A.ey));
      }
      function b2Distance(a, b) {
        var c = b2Vec2.Subtract(a, b);
        return c.Length();
      }
      function b2DistanceSquared(a, b) {
        var c = b2Vec2.Subtract(a, b);
        return b2Dot_v2_v2(c, c);
      }
      function b2Dot_v3_v3(a, b) {
        return a.x * b.x + a.y * b.y + a.z * b.z;
      }
      function b2Cross_v3_v3(a, b) {
        return new b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);
      }
      function b2Mul_m22_m22(A, B) {
        return new b2Mat22(b2Mul_m22_v2(A, B.ex), b2Mul_m22_v2(A, B.ey));
      }
      function b2MulT_m22_m22(A, B) {
        var c1 = new b2Vec2(b2Dot_v2_v2(A.ex, B.ex), b2Dot_v2_v2(A.ey, B.ex));
        var c2 = new b2Vec2(b2Dot_v2_v2(A.ex, B.ey), b2Dot_v2_v2(A.ey, B.ey));
        return new b2Mat22(c1, c2);
      }
      function b2Mul_m33_v3(A, v) {
        return b2Vec3.Add(b2Vec3.Add(b2Vec3.Multiply(v.x, A.ex), b2Vec3.Multiply(v.y, A.ey)), b2Vec3.Multiply(v.z, A.ez));
      }
      function b2Mul22_m33_v2(A, v) {
        return new b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y);
      }
      function b2Mul_r_r(q, r) {
        var qr = new b2Rot();
        qr.s = q.s * r.c + q.c * r.s;
        qr.c = q.c * r.c - q.s * r.s;
        return qr;
      }
      function b2MulT_r_r(q, r) {
        var qr = new b2Rot();
        qr.s = q.c * r.s - q.s * r.c;
        qr.c = q.c * r.c + q.s * r.s;
        return qr;
      }
      function b2Mul_r_v2(q, v) {
        return new b2Vec2(q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y);
      }
      function b2MulT_r_v2(q, v) {
        return new b2Vec2(q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y);
      }
      function b2Mul_t_v2(T, v) {
        return new b2Vec2(T.q.c * v.x - T.q.s * v.y + T.p.x, T.q.s * v.x + T.q.c * v.y + T.p.y);
      }
      function b2MulT_t_v2(T, v) {
        var px = v.x - T.p.x;
        var py = v.y - T.p.y;
        var x = T.q.c * px + T.q.s * py;
        var y = -T.q.s * px + T.q.c * py;
        return new b2Vec2(x, y);
      }
      function b2Mul_t_t(A, B) {
        var C = new b2Transform();
        C.q = b2Mul_r_r(A.q, B.q);
        C.p = b2Vec2.Add(b2Mul_r_v2(A.q, B.p), A.p);
        return C;
      }
      function b2MulT_t_t(A, B) {
        var C = new b2Transform();
        C.q = b2MulT_r_r(A.q, B.q);
        var tvx = B.p.x - A.p.x;
        var tvy = B.p.y - A.p.y;
        C.p.x = A.q.c * tvx + A.q.s * tvy;
        C.p.y = -A.q.s * tvx + A.q.c * tvy;
        return C;
      }
      var b2Abs = Math.abs;
      function b2Abs_v2(a) {
        return new b2Vec2(b2Abs(a.x), b2Abs(a.y));
      }
      function b2Abs_m22(A) {
        return new b2Mat22(b2Abs_v2(A.ex), b2Abs_v2(A.ey));
      }
      var b2Min = Math.min;
      function b2Min_v2(a, b) {
        return new b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y));
      }
      var b2Max = Math.max;
      function b2Max_v2(a, b) {
        return new b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y));
      }
      function b2Clamp(a, low, high) {
        return b2Max(low, b2Min(a, high));
      }
      function b2Clamp_v2(a, low, high) {
        return b2Max_v2(low, b2Min_v2(a, high));
      }
      function b2NextPowerOfTwo(x) {
        x |= x >> 1;
        x |= x >> 2;
        x |= x >> 4;
        x |= x >> 8;
        x |= x >> 16;
        return x + 1;
      }
      function b2IsPowerOfTwo(x) {
        var result = x > 0 && 0 == (x & x - 1);
        return result;
      }
      var RAND_LIMIT = 32767;
      function b2RandomFloat(lo, hi) {
        var r = Math.random();
        r = "undefined" !== typeof lo ? (hi - lo) * r + lo : 2 * r - 1;
        return r;
      }
      function b2Color(r, g, b) {
        this.r = r || 0;
        this.g = g || 0;
        this.b = b || 0;
      }
      b2Color.prototype = {
        Set: function(r, g, b) {
          this.r = r;
          this.g = g;
          this.b = b;
        }
      };
      function b2Draw() {}
      b2Draw.prototype = {
        ClearDraw: function() {},
        SetFlags: function(flags) {
          this.m_drawFlags = flags;
        },
        GetFlags: function() {
          return this.m_drawFlags;
        },
        AppendFlags: function(flags) {
          this.m_drawFlags |= flags;
        },
        ClearFlags: function(flags) {
          this.m_drawFlags &= ~flags;
        },
        ToggleFlags: function(flags) {
          this.m_drawFlags ^= flags;
        },
        DrawPolygon: function(vertices, vertexCount, color) {},
        DrawSolidPolygon: function(vertices, vertexCount, color) {},
        DrawCircle: function(center, radius, color) {},
        DrawSolidCircle: function(center, radius, axis, color) {},
        DrawSegment: function(p1, p2, color) {},
        DrawTransform: function(xf) {},
        m_drawFlags: 0
      };
      b2Draw.e_shapeBit = 1;
      b2Draw.e_jointBit = 2;
      b2Draw.e_aabbBit = 4;
      b2Draw.e_centerOfMassBit = 8;
      b2Draw.e_contactPoints = 16;
      b2Draw.e_contactNormals = 32;
      b2Draw.e_contactImpulses = 64;
      b2Draw.e_frictionImpulses = 128;
      b2Draw.e_statistics = 256;
      b2Draw.e_profile = 512;
      b2Draw.e_pairBit = 1024;
      "undefined" === typeof performance && (window.performance = {
        now: function() {
          return +new Date();
        }
      });
      function b2Timer() {
        this.Reset();
      }
      b2Timer.prototype = {
        Reset: function() {
          this.m_start = performance.now();
        },
        GetMilliseconds: function() {
          return performance.now() - this.m_start;
        }
      };
      function b2MassData() {
        this.mass = 0;
        this.center = new b2Vec2();
        this.I = 0;
      }
      function b2Shape() {
        this.m_type = 0;
        this.m_radius = 0;
      }
      b2Shape.prototype = {
        Clone: function() {},
        GetType: function() {
          return this.m_type;
        },
        GetChildCount: function() {},
        TestPoint: function(xf, p) {},
        RayCast: function(output, input, transform, childIndex) {},
        ComputeAABB: function(aabb, xf, childIndex) {},
        ComputeMass: function(massData, density) {},
        _serialize: function(out) {
          var obj = out || {};
          obj["m_type"] = this.m_type;
          obj["m_radius"] = this.m_radius;
          return obj;
        },
        _deserialize: function(data) {
          this.m_radius = data["m_radius"];
        }
      };
      b2Shape.e_circle = 0;
      b2Shape.e_edge = 1;
      b2Shape.e_polygon = 2;
      b2Shape.e_chain = 3;
      b2Shape.e_typeCount = 4;
      function b2CircleShape() {
        this.parent.call(this);
        this.m_type = b2Shape.e_circle;
        this.m_radius = 0;
        this.m_p = new b2Vec2();
        Object.seal(this);
      }
      b2CircleShape.prototype = {
        Clone: function() {
          var shape = new b2CircleShape();
          shape.m_radius = this.m_radius;
          shape.m_p = this.m_p.Clone();
          return shape;
        },
        GetChildCount: function() {
          return 1;
        },
        TestPoint: function(transform, p) {
          var center = b2Vec2.Add(transform.p, b2Mul_r_v2(transform.q, this.m_p));
          var d = b2Vec2.Subtract(p, center);
          return b2Dot_v2_v2(d, d) <= this.m_radius * this.m_radius;
        },
        RayCast: function(output, input, transform, childIndex) {
          var position = b2Vec2.Add(transform.p, b2Mul_r_v2(transform.q, this.m_p));
          var s = b2Vec2.Subtract(input.p1, position);
          var b = b2Dot_v2_v2(s, s) - this.m_radius * this.m_radius;
          var r = b2Vec2.Subtract(input.p2, input.p1);
          var c = b2Dot_v2_v2(s, r);
          var rr = b2Dot_v2_v2(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;
            output.normal = b2Vec2.Add(s, b2Vec2.Multiply(a, r));
            output.normal.Normalize();
            return true;
          }
          return false;
        },
        ComputeAABB: function(aabb, transform, childIndex) {
          var px = transform.p.x + (transform.q.c * this.m_p.x - transform.q.s * this.m_p.y);
          var py = transform.p.y + (transform.q.s * this.m_p.x + transform.q.c * this.m_p.y);
          aabb.lowerBound.x = px - this.m_radius;
          aabb.lowerBound.y = py - this.m_radius;
          aabb.upperBound.x = px + this.m_radius;
          aabb.upperBound.y = py + this.m_radius;
        },
        ComputeMass: function(massData, density) {
          massData.mass = density * b2_pi * this.m_radius * this.m_radius;
          massData.center = this.m_p;
          massData.I = massData.mass * (.5 * this.m_radius * this.m_radius + b2Dot_v2_v2(this.m_p, this.m_p));
        },
        GetSupport: function(d) {
          return 0;
        },
        GetSupportVertex: function(d) {
          return this.m_p;
        },
        GetVertexCount: function() {
          return 1;
        },
        GetVertex: function(index) {
          b2Assert(0 == index);
          return this.m_p;
        },
        _serialize: function(out) {
          var obj = out || {};
          this.parent.prototype._serialize.call(this, obj);
          obj["m_p"] = this.m_p._serialize();
          return obj;
        },
        _deserialize: function(data) {
          this.parent.prototype._deserialize.call(this, data);
          this.m_p._deserialize(data["m_p"]);
        }
      };
      b2CircleShape._extend(b2Shape);
      function b2EdgeShape() {
        this.parent.call(this);
        this.m_type = b2Shape.e_edge;
        this.m_radius = b2_polygonRadius;
        this.m_vertex0 = new b2Vec2();
        this.m_vertex1 = new b2Vec2();
        this.m_vertex2 = new b2Vec2();
        this.m_vertex3 = new b2Vec2();
        this.m_hasVertex0 = false;
        this.m_hasVertex3 = false;
        Object.seal(this);
      }
      b2EdgeShape.prototype = {
        Set: function(v1, v2) {
          this.m_vertex1.Assign(v1);
          this.m_vertex2.Assign(v2);
          this.m_hasVertex0 = false;
          this.m_hasVertex3 = false;
        },
        Clone: function() {
          var shape = new b2EdgeShape();
          shape.m_vertex0 = this.m_vertex0.Clone();
          shape.m_vertex1 = this.m_vertex1.Clone();
          shape.m_vertex2 = this.m_vertex2.Clone();
          shape.m_vertex3 = this.m_vertex3.Clone();
          shape.m_hasVertex0 = this.m_hasVertex0;
          shape.m_hasVertex3 = this.m_hasVertex3;
          return shape;
        },
        GetChildCount: function() {
          return 1;
        },
        TestPoint: function(transform, p) {
          return false;
        },
        RayCast: function(output, input, xf, childIndex) {
          var p1 = b2MulT_r_v2(xf.q, b2Vec2.Subtract(input.p1, xf.p));
          var p2 = b2MulT_r_v2(xf.q, b2Vec2.Subtract(input.p2, xf.p));
          var d = b2Vec2.Subtract(p2, p1);
          var v1 = this.m_vertex1;
          var v2 = this.m_vertex2;
          var e = b2Vec2.Subtract(v2, v1);
          var normal = new b2Vec2(e.y, -e.x);
          normal.Normalize();
          var numerator = b2Dot_v2_v2(normal, b2Vec2.Subtract(v1, p1));
          var denominator = b2Dot_v2_v2(normal, d);
          if (0 == denominator) return false;
          var t = numerator / denominator;
          if (t < 0 || input.maxFraction < t) return false;
          var q = b2Vec2.Add(p1, b2Vec2.Multiply(t, d));
          var r = b2Vec2.Subtract(v2, v1);
          var rr = b2Dot_v2_v2(r, r);
          if (0 == rr) return false;
          var s = b2Dot_v2_v2(b2Vec2.Subtract(q, v1), r) / rr;
          if (s < 0 || 1 < s) return false;
          output.fraction = t;
          output.normal = numerator > 0 ? b2Mul_r_v2(xf.q, normal).Negate() : b2Mul_r_v2(xf.q, normal);
          return true;
        },
        ComputeAABB: function(aabb, xf, childIndex) {
          var v1x = xf.q.c * this.m_vertex1.x - xf.q.s * this.m_vertex1.y + xf.p.x;
          var v1y = xf.q.s * this.m_vertex1.x + xf.q.c * this.m_vertex1.y + xf.p.y;
          var v2x = xf.q.c * this.m_vertex2.x - xf.q.s * this.m_vertex2.y + xf.p.x;
          var v2y = xf.q.s * this.m_vertex2.x + xf.q.c * this.m_vertex2.y + xf.p.y;
          var lowerx = b2Min(v1x, v2x);
          var lowery = b2Min(v1y, v2y);
          var upperx = b2Max(v1x, v2x);
          var uppery = b2Max(v1y, v2y);
          aabb.lowerBound.x = lowerx - this.m_radius;
          aabb.lowerBound.y = lowery - this.m_radius;
          aabb.upperBound.x = upperx + this.m_radius;
          aabb.upperBound.y = uppery + this.m_radius;
        },
        ComputeMass: function(massData, density) {
          massData.mass = 0;
          massData.center = b2Vec2.Multiply(.5, b2Vec2.Add(this.m_vertex1, this.m_vertex2));
          massData.I = 0;
        },
        _serialize: function(out) {
          var obj = out || {};
          this.parent.prototype._serialize.call(this, obj);
          obj["m_vertex1"] = this.m_vertex1._serialize();
          obj["m_vertex2"] = this.m_vertex2._serialize();
          obj["m_hasVertex0"] = this.m_hasVertex0;
          this.m_hasVertex0 && (obj["m_vertex0"] = this.m_vertex0._serialize());
          obj["m_hasVertex3"] = this.m_hasVertex3;
          this.m_hasVertex3 && (obj["m_vertex3"] = this.m_vertex3._serialize());
          return obj;
        },
        _deserialize: function(data) {
          this.parent.prototype._deserialize.call(this, data);
          this.m_vertex1._deserialize(data["m_vertex1"]);
          this.m_vertex2._deserialize(data["m_vertex2"]);
          this.m_hasVertex0 = data["m_hasVertex0"];
          this.m_hasVertex0 && this.m_vertex0._deserialize(data["m_vertex0"]);
          this.m_hasVertex3 = data["m_hasVertex3"];
          this.m_hasVertex3 && this.m_vertex3._deserialize(data["m_vertex3"]);
        }
      };
      b2EdgeShape._extend(b2Shape);
      function b2ChainShape() {
        this.parent.call(this);
        this.m_type = b2Shape.e_chain;
        this.m_radius = b2_polygonRadius;
        this.m_prevVertex = new b2Vec2();
        this.m_nextVertex = new b2Vec2();
        this.m_hasPrevVertex = false;
        this.m_hasNextVertex = false;
        this.Clear();
        Object.seal(this);
      }
      b2ChainShape._tempEdge = new b2EdgeShape();
      b2ChainShape.prototype = {
        Clear: function() {
          this.m_vertices = null;
          this.m_count = 0;
        },
        CreateLoop: function(vertices, count) {
          b2Assert(null == this.m_vertices && 0 == this.m_count);
          b2Assert(count >= 3);
          for (var i = 1; i < count; ++i) b2Assert(b2DistanceSquared(vertices[i - 1], vertices[i]) > b2_linearSlop * b2_linearSlop);
          this.m_count = count + 1;
          this.m_vertices = new Array(this.m_count);
          for (var i = 0; i < count; ++i) this.m_vertices[i] = vertices[i].Clone();
          this.m_vertices[count] = this.m_vertices[0].Clone();
          this.m_prevVertex.Assign(this.m_vertices[this.m_count - 2]);
          this.m_nextVertex.Assign(this.m_vertices[1]);
          this.m_hasPrevVertex = true;
          this.m_hasNextVertex = true;
        },
        CreateChain: function(vertices, count) {
          b2Assert(null == this.m_vertices && 0 == this.m_count);
          b2Assert(count >= 2);
          for (var i = 1; i < count; ++i) {
            var v1 = vertices[i - 1];
            var v2 = vertices[i];
            b2Assert(b2DistanceSquared(v1, v2) > b2_linearSlop * b2_linearSlop);
          }
          this.m_count = count;
          this.m_vertices = new Array(count);
          for (var i = 0; i < count; ++i) this.m_vertices[i] = vertices[i].Clone();
          this.m_hasPrevVertex = false;
          this.m_hasNextVertex = false;
          this.m_prevVertex.SetZero();
          this.m_nextVertex.SetZero();
        },
        SetPrevVertex: function(prevVertex) {
          this.m_prevVertex.Assign(prevVertex);
          this.m_hasPrevVertex = true;
        },
        SetNextVertex: function(nextVertex) {
          this.m_nextVertex.Assign(nextVertex);
          this.m_hasNextVertex = true;
        },
        Clone: function() {
          var shape = new b2ChainShape();
          shape.m_count = this.m_count;
          shape.m_vertices = new Array(this.m_count);
          for (var i = 0; i < this.m_count; ++i) shape.m_vertices[i] = this.m_vertices[i].Clone();
          shape.m_prevVertex = this.m_prevVertex.Clone();
          shape.m_nextVertex = this.m_nextVertex.Clone();
          shape.m_hasPrevVertex = this.m_hasPrevVertex;
          shape.m_hasNextVertex = this.m_hasNextVertex;
          return shape;
        },
        GetChildCount: function() {
          return this.m_count - 1;
        },
        GetChildEdge: function(edge, index) {
          b2Assert(0 <= index && index < this.m_count - 1);
          edge.m_type = b2Shape.e_edge;
          edge.m_radius = this.m_radius;
          edge.m_vertex1 = this.m_vertices[index + 0];
          edge.m_vertex2 = this.m_vertices[index + 1];
          if (index > 0) {
            edge.m_vertex0 = this.m_vertices[index - 1];
            edge.m_hasVertex0 = true;
          } else {
            edge.m_vertex0 = this.m_prevVertex;
            edge.m_hasVertex0 = this.m_hasPrevVertex;
          }
          if (index < this.m_count - 2) {
            edge.m_vertex3 = this.m_vertices[index + 2];
            edge.m_hasVertex3 = true;
          } else {
            edge.m_vertex3 = this.m_nextVertex;
            edge.m_hasVertex3 = this.m_hasNextVertex;
          }
        },
        TestPoint: function(transform, p) {
          return false;
        },
        RayCast: function(output, input, xf, childIndex) {
          b2Assert(childIndex < this.m_count);
          var i1 = childIndex;
          var i2 = childIndex + 1;
          i2 == this.m_count && (i2 = 0);
          b2ChainShape._tempEdge.m_vertex1 = this.m_vertices[i1].Clone();
          b2ChainShape._tempEdge.m_vertex2 = this.m_vertices[i2].Clone();
          return b2ChainShape._tempEdge.RayCast(output, input, xf, 0);
        },
        ComputeAABB: function(aabb, xf, childIndex) {
          b2Assert(childIndex < this.m_count);
          var i1 = childIndex;
          var i2 = childIndex + 1;
          i2 == this.m_count && (i2 = 0);
          var v1x = xf.q.c * this.m_vertices[i1].x - xf.q.s * this.m_vertices[i1].y + xf.p.x;
          var v1y = xf.q.s * this.m_vertices[i1].x + xf.q.c * this.m_vertices[i1].y + xf.p.y;
          var v2x = xf.q.c * this.m_vertices[i2].x - xf.q.s * this.m_vertices[i2].y + xf.p.x;
          var v2y = xf.q.s * this.m_vertices[i2].x + xf.q.c * this.m_vertices[i2].y + xf.p.y;
          aabb.lowerBound.x = b2Min(v1x, v2x);
          aabb.lowerBound.y = b2Min(v1y, v2y);
          aabb.upperBound.x = b2Max(v1x, v2x);
          aabb.upperBound.y = b2Max(v1y, v2y);
        },
        ComputeMass: function(massData, density) {
          massData.mass = 0;
          massData.center.SetZero();
          massData.I = 0;
        },
        _serialize: function(out) {
          var obj = out || {};
          this.parent.prototype._serialize.call(this, obj);
          obj["m_count"] = this.m_count;
          obj["m_vertices"] = [];
          for (var i = 0; i < this.m_count; ++i) obj["m_vertices"].push(this.m_vertices[i]._serialize());
          obj["m_hasPrevVertex"] = this.m_hasPrevVertex;
          this.m_hasPrevVertex && (obj["m_prevVertex"] = this.m_prevVertex._serialize());
          obj["m_hasNextVertex"] = this.m_hasNextVertex;
          this.m_hasNextVertex && (obj["m_nextVertex"] = this.m_nextVertex._serialize());
          return obj;
        },
        _deserialize: function(data) {
          this.parent.prototype._deserialize.call(this, data);
          this.m_count = data["m_count"];
          this.m_vertices = [];
          for (var i = 0; i < this.m_count; ++i) {
            this.m_vertices[i] = new b2Vec2();
            this.m_vertices[i]._deserialize(data["m_vertices"][i]);
          }
          this.m_hasPrevVertex = data["m_hasPrevVertex"];
          this.m_hasPrevVertex && this.m_prevVertex._deserialize(data["m_prevVertex"]);
          this.m_hasNextVertex = data["m_hasNextVertex"];
          this.m_hasNextVertex && this.m_nextVertex._deserialize(data["m_nextVertex"]);
        }
      };
      b2ChainShape._extend(b2Shape);
      function b2PolygonShape() {
        this.parent.call(this);
        this.m_type = b2Shape.e_polygon;
        this.m_radius = b2_polygonRadius;
        this.m_count = 0;
        this.m_centroid = new b2Vec2();
        this.m_vertices = new Array(b2_maxPolygonVertices);
        this.m_normals = new Array(b2_maxPolygonVertices);
        Object.seal(this);
      }
      b2PolygonShape.prototype = {
        Clone: function() {
          var shape = new b2PolygonShape();
          shape.m_count = this.m_count;
          shape.m_centroid = this.m_centroid.Clone();
          for (var i = 0; i < this.m_count; ++i) {
            shape.m_vertices[i] = this.m_vertices[i].Clone();
            shape.m_normals[i] = this.m_normals[i].Clone();
          }
          return shape;
        },
        GetChildCount: function() {
          return 1;
        },
        Set: function(vertices, count) {
          b2Assert(3 <= count && count <= b2_maxPolygonVertices);
          if (count < 3) {
            this.SetAsBox(1, 1);
            return;
          }
          var n = b2Min(count, b2_maxPolygonVertices);
          var ps = new Array(b2_maxPolygonVertices);
          var tempCount = 0;
          for (var i = 0; i < n; ++i) {
            var v = vertices[i];
            var unique = true;
            for (var j = 0; j < tempCount; ++j) if (b2DistanceSquared(v, ps[j]) < .5 * b2_linearSlop) {
              unique = false;
              break;
            }
            unique && (ps[tempCount++] = v.Clone());
          }
          n = tempCount;
          if (n < 3) {
            b2Assert(false);
            this.SetAsBox(1, 1);
            return;
          }
          var i0 = 0;
          var x0 = ps[0].x;
          for (i = 1; i < n; ++i) {
            var x = ps[i].x;
            if (x > x0 || x == x0 && ps[i].y < ps[i0].y) {
              i0 = i;
              x0 = x;
            }
          }
          var hull = new Array(b2_maxPolygonVertices);
          var m = 0;
          var ih = i0;
          for (;;) {
            hull[m] = ih;
            var ie = 0;
            for (j = 1; j < n; ++j) {
              if (ie == ih) {
                ie = j;
                continue;
              }
              var r = b2Vec2.Subtract(ps[ie], ps[hull[m]]);
              var v = b2Vec2.Subtract(ps[j], ps[hull[m]]);
              var c = b2Cross_v2_v2(r, v);
              c < 0 && (ie = j);
              0 == c && v.LengthSquared() > r.LengthSquared() && (ie = j);
            }
            ++m;
            ih = ie;
            if (ie == i0) break;
          }
          if (m < 3) {
            b2Assert(false);
            this.SetAsBox(1, 1);
            return;
          }
          this.m_count = m;
          for (i = 0; i < m; ++i) this.m_vertices[i] = ps[hull[i]].Clone();
          for (i = 0; i < m; ++i) {
            var i1 = i;
            var i2 = i + 1 < m ? i + 1 : 0;
            var edge = b2Vec2.Subtract(this.m_vertices[i2], this.m_vertices[i1]);
            b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon);
            this.m_normals[i] = b2Cross_v2_f(edge, 1).Clone();
            this.m_normals[i].Normalize();
          }
          this.m_centroid = b2PolygonShape.ComputeCentroid(this.m_vertices, m);
        },
        SetAsBox: function(hx, hy, center, angle) {
          this.m_count = 4;
          this.m_vertices[0] = new b2Vec2(-hx, -hy);
          this.m_vertices[1] = new b2Vec2(hx, -hy);
          this.m_vertices[2] = new b2Vec2(hx, hy);
          this.m_vertices[3] = new b2Vec2(-hx, hy);
          this.m_normals[0] = new b2Vec2(0, -1);
          this.m_normals[1] = new b2Vec2(1, 0);
          this.m_normals[2] = new b2Vec2(0, 1);
          this.m_normals[3] = new b2Vec2(-1, 0);
          if (!center) return;
          this.m_centroid.Assign(center);
          var xf = new b2Transform();
          xf.p = center;
          xf.q.Set(angle);
          for (var i = 0; i < this.m_count; ++i) {
            this.m_vertices[i].Assign(b2Mul_t_v2(xf, this.m_vertices[i]));
            this.m_normals[i].Assign(b2Mul_r_v2(xf.q, this.m_normals[i]));
          }
        },
        TestPoint: function(xf, p) {
          var pLocal = b2MulT_r_v2(xf.q, b2Vec2.Subtract(p, xf.p));
          for (var i = 0; i < this.m_count; ++i) {
            var dot = b2Dot_v2_v2(this.m_normals[i], b2Vec2.Subtract(pLocal, this.m_vertices[i]));
            if (dot > 0) return false;
          }
          return true;
        },
        RayCast: function(output, input, xf, childIndex) {
          var p1 = b2MulT_r_v2(xf.q, b2Vec2.Subtract(input.p1, xf.p));
          var p2 = b2MulT_r_v2(xf.q, b2Vec2.Subtract(input.p2, xf.p));
          var d = b2Vec2.Subtract(p2, p1);
          var lower = 0, upper = input.maxFraction;
          var index = -1;
          for (var i = 0; i < this.m_count; ++i) {
            var numerator = b2Dot_v2_v2(this.m_normals[i], b2Vec2.Subtract(this.m_vertices[i], p1));
            var denominator = b2Dot_v2_v2(this.m_normals[i], d);
            if (0 == denominator) {
              if (numerator < 0) return false;
            } else if (denominator < 0 && numerator < lower * denominator) {
              lower = numerator / denominator;
              index = i;
            } else denominator > 0 && numerator < upper * denominator && (upper = numerator / denominator);
            if (upper < lower) return false;
          }
          b2Assert(0 <= lower && lower <= input.maxFraction);
          if (index >= 0) {
            output.fraction = lower;
            output.normal = b2Mul_r_v2(xf.q, this.m_normals[index]);
            return true;
          }
          return false;
        },
        ComputeAABB: function(aabb, xf, childIndex) {
          var lowerx = xf.q.c * this.m_vertices[0].x - xf.q.s * this.m_vertices[0].y + xf.p.x;
          var lowery = xf.q.s * this.m_vertices[0].x + xf.q.c * this.m_vertices[0].y + xf.p.y;
          var upperx = lowerx;
          var uppery = lowery;
          for (var i = 1; i < this.m_count; ++i) {
            var vx = xf.q.c * this.m_vertices[i].x - xf.q.s * this.m_vertices[i].y + xf.p.x;
            var vy = xf.q.s * this.m_vertices[i].x + xf.q.c * this.m_vertices[i].y + xf.p.y;
            lowerx = b2Min(lowerx, vx);
            lowery = b2Min(lowery, vy);
            upperx = b2Max(upperx, vx);
            uppery = b2Max(uppery, vy);
          }
          aabb.lowerBound.x = lowerx - this.m_radius;
          aabb.lowerBound.y = lowery - this.m_radius;
          aabb.upperBound.x = upperx + this.m_radius;
          aabb.upperBound.y = uppery + this.m_radius;
        },
        ComputeMass: function(massData, density) {
          b2Assert(this.m_count >= 3);
          var center = new b2Vec2(0, 0);
          var area = 0;
          var I = 0;
          var s = new b2Vec2(0, 0);
          for (var i = 0; i < this.m_count; ++i) s.Add(this.m_vertices[i]);
          s.Multiply(1 / this.m_count);
          var k_inv3 = 1 / 3;
          for (var i = 0; i < this.m_count; ++i) {
            var e1 = b2Vec2.Subtract(this.m_vertices[i], s);
            var e2 = i + 1 < this.m_count ? b2Vec2.Subtract(this.m_vertices[i + 1], s) : b2Vec2.Subtract(this.m_vertices[0], s);
            var D = b2Cross_v2_v2(e1, e2);
            var triangleArea = .5 * D;
            area += triangleArea;
            center.Add(b2Vec2.Multiply(triangleArea * k_inv3, b2Vec2.Add(e1, e2)));
            var ex1 = e1.x, ey1 = e1.y;
            var ex2 = e2.x, ey2 = e2.y;
            var intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2;
            var inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2;
            I += .25 * k_inv3 * D * (intx2 + inty2);
          }
          massData.mass = density * area;
          b2Assert(area > b2_epsilon);
          center.Multiply(1 / area);
          massData.center = b2Vec2.Add(center, s);
          massData.I = density * I;
          massData.I += massData.mass * (b2Dot_v2_v2(massData.center, massData.center) - b2Dot_v2_v2(center, center));
        },
        GetVertexCount: function() {
          return this.m_count;
        },
        GetVertex: function(index) {
          b2Assert(0 <= index && index < this.m_count);
          return this.m_vertices[index];
        },
        Validate: function() {
          for (var i = 0; i < this.m_count; ++i) {
            var i1 = i;
            var i2 = i < this.m_count - 1 ? i1 + 1 : 0;
            var p = this.m_vertices[i1];
            var e = b2Vec2.Subtract(this.m_vertices[i2], p);
            for (var j = 0; j < this.m_count; ++j) {
              if (j == i1 || j == i2) continue;
              var v = b2Vec2.Subtract(this.m_vertices[j], p);
              var c = b2Cross_v2_v2(e, v);
              if (c < 0) return false;
            }
          }
          return true;
        },
        _serialize: function(out) {
          var obj = out || {};
          this.parent.prototype._serialize.call(this, obj);
          obj["m_count"] = this.m_count;
          obj["m_centroid"] = this.m_centroid._serialize();
          obj["m_vertices"] = [];
          obj["m_normals"] = [];
          for (var i = 0; i < this.m_count; ++i) {
            obj["m_vertices"].push(this.m_vertices[i]._serialize());
            obj["m_normals"].push(this.m_normals[i]._serialize());
          }
          return obj;
        },
        _deserialize: function(data) {
          this.parent.prototype._deserialize.call(this, data);
          this.m_count = data["m_count"];
          this.m_centroid._deserialize(data["m_centroid"]);
          this.m_vertices = [];
          this.m_normals = [];
          for (var i = 0; i < this.m_count; ++i) {
            this.m_vertices[i] = new b2Vec2();
            this.m_vertices[i]._deserialize(data["m_vertices"][i]);
            this.m_normals[i] = new b2Vec2();
            this.m_normals[i]._deserialize(data["m_normals"][i]);
          }
        }
      };
      b2PolygonShape.ComputeCentroid = function(vs, count) {
        b2Assert(count >= 3);
        var c = new b2Vec2();
        var area = 0;
        var pRef = new b2Vec2(0, 0);
        var inv3 = 1 / 3;
        for (var i = 0; i < count; ++i) {
          var p1 = pRef;
          var p2 = vs[i];
          var p3 = i + 1 < count ? vs[i + 1] : vs[0];
          var e1 = b2Vec2.Subtract(p2, p1);
          var e2 = b2Vec2.Subtract(p3, p1);
          var D = b2Cross_v2_v2(e1, e2);
          var triangleArea = .5 * D;
          area += triangleArea;
          c.Add(b2Vec2.Multiply(triangleArea, b2Vec2.Multiply(inv3, b2Vec2.Add(b2Vec2.Add(p1, p2), p3))));
        }
        b2Assert(area > b2_epsilon);
        c.Multiply(1 / area);
        return c;
      };
      b2PolygonShape._extend(b2Shape);
      function b2Pair() {
        this.proxyIdA = 0;
        this.proxyIdB = 0;
      }
      function b2PairLessThan(pair1, pair2) {
        if (pair1.proxyIdA == pair2.proxyIdA) return pair1.proxyIdB - pair2.proxyIdB;
        return pair1.proxyIdA - pair2.proxyIdA;
      }
      function b2BroadPhase() {
        this.m_tree = new b2DynamicTree();
        this.m_queryProxyId = 0;
        this.m_proxyCount = 0;
        this.m_pairCount = 0;
        this.m_pairBuffer = [];
        this.m_moveCount = 0;
        this.m_moveBuffer = [];
      }
      b2BroadPhase.prototype = {
        CreateProxy: function(aabb, userData) {
          var proxyId = this.m_tree.CreateProxy(aabb, userData);
          ++this.m_proxyCount;
          this.BufferMove(proxyId);
          return proxyId;
        },
        DestroyProxy: function(proxyId) {
          this.UnBufferMove(proxyId);
          --this.m_proxyCount;
          this.m_tree.DestroyProxy(proxyId);
        },
        MoveProxy: function(proxyId, aabb, displacement) {
          var buffer = this.m_tree.MoveProxy(proxyId, aabb, displacement);
          buffer && this.BufferMove(proxyId);
        },
        TouchProxy: function(proxyId) {
          this.BufferMove(proxyId);
        },
        GetFatAABB: function(proxyId) {
          return this.m_tree.GetFatAABB(proxyId);
        },
        GetUserData: function(proxyId) {
          return this.m_tree.GetUserData(proxyId);
        },
        TestOverlap: function(proxyIdA, proxyIdB) {
          var aabbA = this.m_tree.GetFatAABB(proxyIdA);
          var aabbB = this.m_tree.GetFatAABB(proxyIdB);
          return b2TestOverlap(aabbA, aabbB);
        },
        GetProxyCount: function() {
          return this.m_proxyCount;
        },
        UpdatePairs: function(callback) {
          this.m_pairCount = 0;
          this.m_pairBuffer.length = 0;
          for (var i = 0; i < this.m_moveCount; ++i) {
            this.m_queryProxyId = this.m_moveBuffer[i];
            if (this.m_queryProxyId == b2BroadPhase.e_nullProxy) continue;
            var fatAABB = this.m_tree.GetFatAABB(this.m_queryProxyId);
            this.m_tree.Query(this, fatAABB);
          }
          this.m_moveCount = 0;
          this.m_pairBuffer.sort(b2PairLessThan);
          var i = 0;
          while (i < this.m_pairCount) {
            var primaryPair = this.m_pairBuffer[i];
            var userDataA = this.m_tree.GetUserData(primaryPair.proxyIdA);
            var userDataB = this.m_tree.GetUserData(primaryPair.proxyIdB);
            callback.AddPair(userDataA, userDataB);
            ++i;
            while (i < this.m_pairCount) {
              var pair = this.m_pairBuffer[i];
              if (pair.proxyIdA != primaryPair.proxyIdA || pair.proxyIdB != primaryPair.proxyIdB) break;
              ++i;
            }
          }
        },
        Query: function(callback, aabb) {
          this.m_tree.Query(callback, aabb);
        },
        RayCast: function(callback, input) {
          this.m_tree.RayCast(callback, input);
        },
        GetTreeHeight: function() {
          return this.m_tree.GetHeight();
        },
        GetTreeBalance: function() {
          return this.m_tree.GetMaxBalance();
        },
        GetTreeQuality: function() {
          return this.m_tree.GetAreaRatio();
        },
        ShiftOrigin: function(newOrigin) {
          this.m_tree.ShiftOrigin(newOrigin);
        },
        BufferMove: function(proxyId) {
          this.m_moveBuffer[this.m_moveCount] = proxyId;
          ++this.m_moveCount;
        },
        UnBufferMove: function(proxyId) {
          for (var i = 0; i < this.m_moveCount; ++i) this.m_moveBuffer[i] == proxyId && (this.m_moveBuffer[i] = b2BroadPhase.e_nullProxy);
        },
        QueryCallback: function(proxyId) {
          if (proxyId == this.m_queryProxyId) return true;
          this.m_pairBuffer[this.m_pairCount] = new b2Pair();
          this.m_pairBuffer[this.m_pairCount].proxyIdA = b2Min(proxyId, this.m_queryProxyId);
          this.m_pairBuffer[this.m_pairCount].proxyIdB = b2Max(proxyId, this.m_queryProxyId);
          ++this.m_pairCount;
          return true;
        }
      };
      b2BroadPhase.e_nullProxy = -1;
      function b2DistanceProxy() {
        this.m_vertices = null;
        this.m_count = 0;
        this.m_radius = 0;
      }
      b2DistanceProxy.prototype = {
        Assign: function(l) {
          this.m_vertices = l.m_vertices;
          this.m_count = l.m_count;
          this.m_radius = l.m_radius;
        },
        Set: function(shape, index) {
          switch (shape.GetType()) {
           case b2Shape.e_circle:
            var circle = shape;
            this.m_vertices = [ circle.m_p ];
            this.m_count = 1;
            this.m_radius = circle.m_radius;
            break;

           case b2Shape.e_polygon:
            var polygon = shape;
            this.m_vertices = polygon.m_vertices;
            this.m_count = polygon.m_count;
            this.m_radius = polygon.m_radius;
            break;

           case b2Shape.e_chain:
            var chain = shape;
            b2Assert(0 <= index && index < chain.m_count);
            this.m_vertices = [ chain.m_vertices[index] ];
            index + 1 < chain.m_count ? this.m_vertices[1] = chain.m_vertices[index + 1] : this.m_vertices[1] = chain.m_vertices[0];
            this.m_count = 2;
            this.m_radius = chain.m_radius;
            break;

           case b2Shape.e_edge:
            var edge = shape;
            this.m_vertices = [ edge.m_vertex1, edge.m_vertex2 ];
            this.m_count = 2;
            this.m_radius = edge.m_radius;
            break;

           default:
            b2Assert(false);
          }
        },
        GetSupport: function(dx, dy) {
          var bestIndex = 0;
          var bestValue = this.m_vertices[0].x * dx + this.m_vertices[0].y * dy;
          for (var i = 1; i < this.m_count; ++i) {
            var value = this.m_vertices[i].x * dx + this.m_vertices[i].y * dy;
            if (value > bestValue) {
              bestIndex = i;
              bestValue = value;
            }
          }
          return bestIndex;
        },
        GetSupportVertex: function(dx, dy) {
          return this.m_vertices[this.GetSupport(dx, dy)];
        },
        GetVertexCount: function() {
          return this.m_count;
        },
        GetVertex: function(index) {
          b2Assert(0 <= index && index < this.m_count);
          return this.m_vertices[index];
        }
      };
      function b2SimplexCache() {
        this.metric = 0;
        this.count = 0;
        this.indexA = [ 0, 0, 0 ];
        this.indexB = [ 0, 0, 0 ];
      }
      function b2DistanceInput() {
        this.proxyA = new b2DistanceProxy();
        this.proxyB = new b2DistanceProxy();
        this.transformA = new b2Transform();
        this.transformB = new b2Transform();
        this.useRadii = false;
      }
      function b2DistanceOutput() {
        this.pointA = new b2Vec2();
        this.pointB = new b2Vec2();
        this.distance = 0;
        this.iterations = 0;
      }
      function b2SimplexVertex() {
        this.wA = new b2Vec2();
        this.wB = new b2Vec2();
        this.w = new b2Vec2();
        this.a = 0;
        this.indexA = 0;
        this.indexB = 0;
      }
      b2SimplexVertex.prototype = {
        Assign: function(l) {
          this.wA.x = l.wA.x;
          this.wA.y = l.wA.y;
          this.wB.x = l.wB.x;
          this.wB.y = l.wB.y;
          this.w.x = l.w.x;
          this.w.y = l.w.y;
          this.a = l.a;
          this.indexA = l.indexA;
          this.indexB = l.indexB;
        }
      };
      function b2Simplex() {
        this.m_v = [ new b2SimplexVertex(), new b2SimplexVertex(), new b2SimplexVertex() ];
        this.m_count = 0;
      }
      b2Simplex.prototype = {
        ReadCache: function(cache, proxyA, transformA, proxyB, transformB) {
          b2Assert(cache.count <= 3);
          this.m_count = cache.count;
          var vertices = this.m_v;
          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);
            v.wA.x = transformA.q.c * wALocal.x - transformA.q.s * wALocal.y + transformA.p.x;
            v.wA.y = transformA.q.s * wALocal.x + transformA.q.c * wALocal.y + transformA.p.y;
            v.wB.x = transformB.q.c * wBLocal.x - transformB.q.s * wBLocal.y + transformB.p.x;
            v.wB.y = transformB.q.s * wBLocal.x + transformB.q.c * wBLocal.y + transformB.p.y;
            v.w.x = v.wB.x - v.wA.x;
            v.w.y = v.wB.y - v.wA.y;
            v.a = 0;
          }
          if (this.m_count > 1) {
            var metric1 = cache.metric;
            var metric2 = this.GetMetric();
            (metric2 < .5 * metric1 || 2 * metric1 < metric2 || metric2 < b2_epsilon) && (this.m_count = 0);
          }
          if (0 == this.m_count) {
            var v = vertices[0];
            v.indexA = 0;
            v.indexB = 0;
            var wALocal = proxyA.GetVertex(0);
            var wBLocal = proxyB.GetVertex(0);
            v.wA.x = transformA.q.c * wALocal.x - transformA.q.s * wALocal.y + transformA.p.x;
            v.wA.y = transformA.q.s * wALocal.x + transformA.q.c * wALocal.y + transformA.p.y;
            v.wB.x = transformB.q.c * wBLocal.x - transformB.q.s * wBLocal.y + transformB.p.x;
            v.wB.y = transformB.q.s * wBLocal.x + transformB.q.c * wBLocal.y + transformB.p.y;
            v.w.x = v.wB.x - v.wA.x;
            v.w.y = v.wB.y - v.wA.y;
            v.a = 1;
            this.m_count = 1;
          }
        },
        WriteCache: function(cache) {
          cache.metric = this.GetMetric();
          cache.count = this.m_count;
          var vertices = this.m_v;
          for (var i = 0; i < this.m_count; ++i) {
            cache.indexA[i] = vertices[i].indexA;
            cache.indexB[i] = vertices[i].indexB;
          }
        },
        GetSearchDirection: function(p) {
          switch (this.m_count) {
           case 1:
            p.x = -this.m_v[0].w.x;
            p.y = -this.m_v[0].w.y;
            break;

           case 2:
            var e12x = this.m_v[1].w.x - this.m_v[0].w.x;
            var e12y = this.m_v[1].w.y - this.m_v[0].w.y;
            var sgn = e12x * -this.m_v[0].w.y - e12y * -this.m_v[0].w.x;
            if (sgn > 0) {
              p.x = -1 * e12y;
              p.y = 1 * e12x;
            } else {
              p.x = 1 * e12y;
              p.y = -1 * e12x;
            }
            break;

           default:
            b2Assert(false);
            p.x = p.y = 0;
          }
        },
        GetClosestPoint: function(p) {
          switch (this.m_count) {
           case 1:
            p.x = this.m_v[0].w.x;
            p.y = this.m_v[0].w.y;
            break;

           case 2:
            p.x = this.m_v[0].a * this.m_v[0].w.x + this.m_v[1].a * this.m_v[1].w.x;
            p.y = this.m_v[0].a * this.m_v[0].w.y + this.m_v[1].a * this.m_v[1].w.y;
            break;

           case 3:
            p.x = p.y = 0;
            break;

           default:
            b2Assert(false);
            p.x = p.y = 0;
          }
        },
        GetWitnessPoints: function(pA, pB) {
          switch (this.m_count) {
           case 1:
            pA.x = this.m_v[0].wA.x;
            pA.y = this.m_v[0].wA.y;
            pB.x = this.m_v[0].wB.x;
            pB.y = this.m_v[0].wB.y;
            break;

           case 2:
            pA.x = this.m_v[0].a * this.m_v[0].wA.x + this.m_v[1].a * this.m_v[1].wA.x;
            pA.y = this.m_v[0].a * this.m_v[0].wA.y + this.m_v[1].a * this.m_v[1].wA.y;
            pB.x = this.m_v[0].a * this.m_v[0].wB.x + this.m_v[1].a * this.m_v[1].wB.x;
            pB.y = this.m_v[0].a * this.m_v[0].wB.y + this.m_v[1].a * this.m_v[1].wB.y;
            break;

           case 3:
            pA.x = this.m_v[0].a * this.m_v[0].wA.x + this.m_v[1].a * this.m_v[1].wA.x + this.m_v[2].a * this.m_v[2].wA.x;
            pA.y = this.m_v[0].a * this.m_v[0].wA.y + this.m_v[1].a * this.m_v[1].wA.y + this.m_v[2].a * this.m_v[2].wA.y;
            pB.x = pA.x;
            pB.y = pA.y;
            break;

           default:
            b2Assert(false);
          }
        },
        GetMetric: function() {
          switch (this.m_count) {
           case 1:
            return 0;

           case 2:
            return b2Distance(this.m_v[0].w, this.m_v[1].w);

           case 3:
            return (this.m_v[1].w.x - this.m_v[0].w.x) * (this.m_v[2].w.y - this.m_v[0].w.y) - (this.m_v[1].w.y - this.m_v[0].w.y) * (this.m_v[2].w.x - this.m_v[0].w.x);

           default:
            b2Assert(false);
            return 0;
          }
        },
        Solve2: function() {
          var w1 = this.m_v[0].w;
          var w2 = this.m_v[1].w;
          var e12x = w2.x - w1.x;
          var e12y = w2.y - w1.y;
          var d12_2 = -(w1.x * e12x + w1.y * e12y);
          if (d12_2 <= 0) {
            this.m_v[0].a = 1;
            this.m_count = 1;
            return;
          }
          var d12_1 = w2.x * e12x + w2.y * e12y;
          if (d12_1 <= 0) {
            this.m_v[1].a = 1;
            this.m_count = 1;
            this.m_v[0].Assign(this.m_v[1]);
            return;
          }
          var inv_d12 = 1 / (d12_1 + d12_2);
          this.m_v[0].a = d12_1 * inv_d12;
          this.m_v[1].a = d12_2 * inv_d12;
          this.m_count = 2;
        },
        Solve3: function() {
          var w1 = this.m_v[0].w;
          var w2 = this.m_v[1].w;
          var w3 = this.m_v[2].w;
          var e12x = w2.x - w1.x;
          var e12y = w2.y - w1.y;
          var w1e12 = w1.x * e12x + w1.y * e12y;
          var w2e12 = w2.x * e12x + w2.y * e12y;
          var d12_1 = w2e12;
          var d12_2 = -w1e12;
          var e13x = w3.x - w1.x;
          var e13y = w3.y - w1.y;
          var w1e13 = w1.x * e13x + w1.y * e13y;
          var w3e13 = w3.x * e13x + w3.y * e13y;
          var d13_1 = w3e13;
          var d13_2 = -w1e13;
          var e23x = w3.x - w2.x;
          var e23y = w3.y - w2.y;
          var w2e23 = w2.x * e23x + w2.y * e23y;
          var w3e23 = w3.x * e23x + w3.y * e23y;
          var d23_1 = w3e23;
          var d23_2 = -w2e23;
          var n123 = e12x * e13y - e12y * e13x;
          var d123_1 = n123 * (w2.x * w3.y - w2.y * w3.x);
          var d123_2 = n123 * (w3.x * w1.y - w3.y * w1.x);
          var d123_3 = n123 * (w1.x * w2.y - w1.y * w2.x);
          if (d12_2 <= 0 && d13_2 <= 0) {
            this.m_v[0].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_v[0].a = d12_1 * inv_d12;
            this.m_v[1].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_v[0].a = d13_1 * inv_d13;
            this.m_v[2].a = d13_2 * inv_d13;
            this.m_count = 2;
            this.m_v[1].Assign(this.m_v[2]);
            return;
          }
          if (d12_1 <= 0 && d23_2 <= 0) {
            this.m_v[1].a = 1;
            this.m_count = 1;
            this.m_v[0].Assign(this.m_v[1]);
            return;
          }
          if (d13_1 <= 0 && d23_1 <= 0) {
            this.m_v[2].a = 1;
            this.m_count = 1;
            this.m_v[0].Assign(this.m_v[2]);
            return;
          }
          if (d23_1 > 0 && d23_2 > 0 && d123_1 <= 0) {
            var inv_d23 = 1 / (d23_1 + d23_2);
            this.m_v[1].a = d23_1 * inv_d23;
            this.m_v[2].a = d23_2 * inv_d23;
            this.m_count = 2;
            this.m_v[0].Assign(this.m_v[2]);
            return;
          }
          var inv_d123 = 1 / (d123_1 + d123_2 + d123_3);
          this.m_v[0].a = d123_1 * inv_d123;
          this.m_v[1].a = d123_2 * inv_d123;
          this.m_v[2].a = d123_3 * inv_d123;
          this.m_count = 3;
        }
      };
      var _b2Distance_simplex = new b2Simplex();
      var _b2Distance_normal = new b2Vec2();
      var _b2Distance_p = new b2Vec2();
      function b2DistanceFunc(output, cache, input) {
        ++b2DistanceFunc.b2_gjkCalls;
        var proxyA = input.proxyA;
        var proxyB = input.proxyB;
        var transformA = input.transformA;
        var transformB = input.transformB;
        _b2Distance_simplex.ReadCache(cache, proxyA, transformA, proxyB, transformB);
        var vertices = _b2Distance_simplex.m_v;
        var k_maxIters = 20;
        var saveA = [ 0, 0, 0 ], saveB = [ 0, 0, 0 ];
        var saveCount = 0;
        var distanceSqr1 = b2_maxFloat;
        var distanceSqr2 = distanceSqr1;
        var iter = 0;
        while (iter < k_maxIters) {
          saveCount = _b2Distance_simplex.m_count;
          for (var i = 0; i < saveCount; ++i) {
            saveA[i] = vertices[i].indexA;
            saveB[i] = vertices[i].indexB;
          }
          switch (_b2Distance_simplex.m_count) {
           case 1:
            break;

           case 2:
            _b2Distance_simplex.Solve2();
            break;

           case 3:
            _b2Distance_simplex.Solve3();
            break;

           default:
            b2Assert(false);
          }
          if (3 == _b2Distance_simplex.m_count) break;
          _b2Distance_simplex.GetClosestPoint(_b2Distance_p);
          distanceSqr2 = _b2Distance_p.LengthSquared();
          distanceSqr2 >= distanceSqr1;
          distanceSqr1 = distanceSqr2;
          _b2Distance_simplex.GetSearchDirection(_b2Distance_p);
          if (_b2Distance_p.LengthSquared() < b2_epsilon * b2_epsilon) break;
          var vertex = vertices[_b2Distance_simplex.m_count];
          vertex.indexA = proxyA.GetSupport(transformA.q.c * -_b2Distance_p.x + transformA.q.s * -_b2Distance_p.y, -transformA.q.s * -_b2Distance_p.x + transformA.q.c * -_b2Distance_p.y);
          var pva = proxyA.GetVertex(vertex.indexA);
          vertex.wA.x = transformA.q.c * pva.x - transformA.q.s * pva.y + transformA.p.x;
          vertex.wA.y = transformA.q.s * pva.x + transformA.q.c * pva.y + transformA.p.y;
          vertex.indexB = proxyB.GetSupport(transformB.q.c * _b2Distance_p.x + transformB.q.s * _b2Distance_p.y, -transformB.q.s * _b2Distance_p.x + transformB.q.c * _b2Distance_p.y);
          var pvb = proxyB.GetVertex(vertex.indexB);
          vertex.wB.x = transformB.q.c * pvb.x - transformB.q.s * pvb.y + transformB.p.x;
          vertex.wB.y = transformB.q.s * pvb.x + transformB.q.c * pvb.y + transformB.p.y;
          vertex.w.x = vertex.wB.x - vertex.wA.x;
          vertex.w.y = vertex.wB.y - vertex.wA.y;
          ++iter;
          ++b2DistanceFunc.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;
          ++_b2Distance_simplex.m_count;
        }
        b2DistanceFunc.b2_gjkMaxIters = b2Max(b2DistanceFunc.b2_gjkMaxIters, iter);
        _b2Distance_simplex.GetWitnessPoints(output.pointA, output.pointB);
        output.distance = b2Distance(output.pointA, output.pointB);
        output.iterations = iter;
        _b2Distance_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;
            _b2Distance_normal.x = output.pointB.x - output.pointA.x;
            _b2Distance_normal.y = output.pointB.y - output.pointA.y;
            _b2Distance_normal.Normalize();
            output.pointA.x += rA * _b2Distance_normal.x;
            output.pointA.y += rA * _b2Distance_normal.y;
            output.pointB.x -= rB * _b2Distance_normal.x;
            output.pointB.y -= rB * _b2Distance_normal.y;
          } else {
            var px = .5 * (output.pointA.x + output.pointB.x);
            var py = .5 * (output.pointA.y + output.pointB.y);
            output.pointA.x = px;
            output.pointA.y = py;
            output.pointB.x = px;
            output.pointB.y = py;
            output.distance = 0;
          }
        }
      }
      b2DistanceFunc.b2_gjkCalls = 0;
      b2DistanceFunc.b2_gjkIters = 0;
      b2DistanceFunc.b2_gjkMaxIters = 0;
      var b2_nullFeature = 255;
      function b2ContactID() {}
      b2ContactID.prototype = {
        indexA: 0,
        indexB: 0,
        typeA: 0,
        typeB: 0,
        Reset: function() {
          this.indexA = this.indexB = this.typeA = this.typeB = 0;
        },
        Get: function() {
          return this.indexA | this.indexB << 8 | this.typeA << 16 | this.typeB << 24;
        },
        Assign: function(k) {
          this.indexA = k.indexA;
          this.indexB = k.indexB;
          this.typeA = k.typeA;
          this.typeB = k.typeB;
        }
      };
      b2ContactID.e_vertex = 0;
      b2ContactID.e_face = 1;
      function b2ManifoldPoint() {
        this.localPoint = new b2Vec2();
        this.normalImpulse = 0;
        this.tangentImpulse = 0;
        this.id = new b2ContactID();
      }
      b2ManifoldPoint.prototype = {
        Clone: function() {
          var point = new b2ManifoldPoint();
          point.localPoint.x = this.localPoint.x;
          point.localPoint.y = this.localPoint.y;
          point.normalImpulse = this.normalImpulse;
          point.tangentImpulse = this.tangentImpulse;
          point.id.Assign(this.id);
          return point;
        }
      };
      function b2Manifold() {
        this.points = new Array(b2_maxManifoldPoints);
        this.localNormal = new b2Vec2();
        this.localPoint = new b2Vec2();
        this.type = 0;
        this.pointCount = 0;
      }
      b2Manifold.prototype = {
        Clone: function() {
          var manifold = new b2Manifold();
          manifold.pointCount = this.pointCount;
          manifold.type = this.type;
          manifold.localPoint.x = this.localPoint.x;
          manifold.localPoint.y = this.localPoint.y;
          manifold.localNormal.x = this.localNormal.x;
          manifold.localNormal.y = this.localNormal.y;
          for (var i = 0; i < this.pointCount; ++i) manifold.points[i] = this.points[i].Clone();
          return manifold;
        },
        Assign: function(manifold) {
          this.pointCount = manifold.pointCount;
          this.type = manifold.type;
          this.localPoint.x = manifold.localPoint.x;
          this.localPoint.y = manifold.localPoint.y;
          this.localNormal.x = manifold.localNormal.x;
          this.localNormal.y = manifold.localNormal.y;
          for (var i = 0; i < this.pointCount; ++i) this.points[i] = manifold.points[i].Clone();
        }
      };
      b2Manifold.e_circles = 0;
      b2Manifold.e_faceA = 1;
      b2Manifold.e_faceB = 2;
      b2Manifold.b2_nullState = 0;
      b2Manifold.b2_addState = 1;
      b2Manifold.b2_persistState = 2;
      b2Manifold.b2_removeState = 3;
      function b2WorldManifold() {
        this.normal = new b2Vec2();
        this.points = new Array(b2_maxManifoldPoints);
        this.separations = new Array(b2_maxManifoldPoints);
      }
      b2WorldManifold.prototype = {
        Initialize: function(manifold, xfA, radiusA, xfB, radiusB) {
          if (0 == manifold.pointCount) return;
          switch (manifold.type) {
           case b2Manifold.e_circles:
            this.normal.x = 1;
            this.normal.y = 0;
            var pointAx = xfA.q.c * manifold.localPoint.x - xfA.q.s * manifold.localPoint.y + xfA.p.x;
            var pointAy = xfA.q.s * manifold.localPoint.x + xfA.q.c * manifold.localPoint.y + xfA.p.y;
            var pointBx = xfB.q.c * manifold.points[0].localPoint.x - xfB.q.s * manifold.points[0].localPoint.y + xfB.p.x;
            var pointBy = xfB.q.s * manifold.points[0].localPoint.x + xfB.q.c * manifold.points[0].localPoint.y + xfB.p.y;
            var cx = pointAx - pointBx;
            var cy = pointAy - pointBy;
            if (cx * cx + cy * cy > b2_epsilon * b2_epsilon) {
              this.normal.x = pointBx - pointAx;
              this.normal.y = pointBy - pointAy;
              this.normal.Normalize();
            }
            var cAx = pointAx + radiusA * this.normal.x;
            var cAy = pointAy + radiusA * this.normal.y;
            var cBx = pointBx - radiusB * this.normal.x;
            var cBy = pointBy - radiusB * this.normal.y;
            this.points[0] = new b2Vec2(.5 * (cAx + cBx), .5 * (cAy + cBy));
            this.separations[0] = (cBx - cAx) * this.normal.x + (cBy - cAy) * this.normal.y;
            break;

           case b2Manifold.e_faceA:
            this.normal.x = xfA.q.c * manifold.localNormal.x - xfA.q.s * manifold.localNormal.y;
            this.normal.y = xfA.q.s * manifold.localNormal.x + xfA.q.c * manifold.localNormal.y;
            var planePointx = xfA.q.c * manifold.localPoint.x - xfA.q.s * manifold.localPoint.y + xfA.p.x;
            var planePointy = xfA.q.s * manifold.localPoint.x + xfA.q.c * manifold.localPoint.y + xfA.p.y;
            for (var i = 0; i < manifold.pointCount; ++i) {
              var clipPointx = xfB.q.c * manifold.points[i].localPoint.x - xfB.q.s * manifold.points[i].localPoint.y + xfB.p.x;
              var clipPointy = xfB.q.s * manifold.points[i].localPoint.x + xfB.q.c * manifold.points[i].localPoint.y + xfB.p.y;
              var d = (clipPointx - planePointx) * this.normal.x + (clipPointy - planePointy) * this.normal.y;
              var cAx = clipPointx + (radiusA - d) * this.normal.x;
              var cAy = clipPointy + (radiusA - d) * this.normal.y;
              var cBx = clipPointx - radiusB * this.normal.x;
              var cBy = clipPointy - radiusB * this.normal.y;
              this.points[i] = new b2Vec2(.5 * (cAx + cBx), .5 * (cAy + cBy));
              this.separations[i] = (cBx - cAx) * this.normal.x + (cBy - cAy) * this.normal.y;
            }
            break;

           case b2Manifold.e_faceB:
            this.normal.x = xfB.q.c * manifold.localNormal.x - xfB.q.s * manifold.localNormal.y;
            this.normal.y = xfB.q.s * manifold.localNormal.x + xfB.q.c * manifold.localNormal.y;
            var planePointx = xfB.q.c * manifold.localPoint.x - xfB.q.s * manifold.localPoint.y + xfB.p.x;
            var planePointy = xfB.q.s * manifold.localPoint.x + xfB.q.c * manifold.localPoint.y + xfB.p.y;
            for (var i = 0; i < manifold.pointCount; ++i) {
              var clipPointx = xfA.q.c * manifold.points[i].localPoint.x - xfA.q.s * manifold.points[i].localPoint.y + xfA.p.x;
              var clipPointy = xfA.q.s * manifold.points[i].localPoint.x + xfA.q.c * manifold.points[i].localPoint.y + xfA.p.y;
              var d = (clipPointx - planePointx) * this.normal.x + (clipPointy - planePointy) * this.normal.y;
              var cBx = clipPointx + (radiusB - d) * this.normal.x;
              var cBy = clipPointy + (radiusB - d) * this.normal.y;
              var cAx = clipPointx - radiusA * this.normal.x;
              var cAy = clipPointy - radiusA * this.normal.y;
              this.points[i] = new b2Vec2(.5 * (cAx + cBx), .5 * (cAy + cBy));
              this.separations[i] = (cAx - cBx) * this.normal.x + (cAy - cBy) * this.normal.y;
            }
            this.normal.x = -this.normal.x;
            this.normal.y = -this.normal.y;
          }
        }
      };
      function b2GetPointStates(state1, state2, manifold1, manifold2) {
        for (var i = 0; i < b2_maxManifoldPoints; ++i) {
          state1[i] = b2Manifold.b2_nullState;
          state2[i] = b2Manifold.b2_nullState;
        }
        for (var i = 0; i < manifold1.pointCount; ++i) {
          var id = manifold1.points[i].id;
          state1[i] = b2Manifold.b2_removeState;
          for (var j = 0; j < manifold2.pointCount; ++j) if (manifold2.points[j].id.Get() == id.Get()) {
            state1[i] = b2Manifold.b2_persistState;
            break;
          }
        }
        for (var i = 0; i < manifold2.pointCount; ++i) {
          var id = manifold2.points[i].id;
          state2[i] = b2Manifold.b2_addState;
          for (var j = 0; j < manifold1.pointCount; ++j) if (manifold1.points[j].id.Get() == id.Get()) {
            state2[i] = b2Manifold.b2_persistState;
            break;
          }
        }
      }
      function b2ClipVertex() {
        this.v = new b2Vec2();
        this.id = new b2ContactID();
      }
      function b2RayCastInput() {
        this.p1 = new b2Vec2(), this.p2 = new b2Vec2();
        this.maxFraction = 0;
      }
      function b2RayCastOutput() {
        this.normal = new b2Vec2();
        this.fraction = 0;
      }
      function b2AABB() {
        this.lowerBound = new b2Vec2();
        this.upperBound = new b2Vec2();
      }
      b2AABB.prototype = {
        Assign: function(other) {
          this.lowerBound.x = other.lowerBound.x;
          this.lowerBound.y = other.lowerBound.y;
          this.upperBound.x = other.upperBound.x;
          this.upperBound.y = other.upperBound.y;
        },
        Clone: function() {
          var clone = new b2AABB();
          clone.lowerBound.x = this.lowerBound.x;
          clone.lowerBound.y = this.lowerBound.y;
          clone.upperBound.x = this.upperBound.x;
          clone.upperBound.y = this.upperBound.y;
          return clone;
        },
        IsValid: function() {
          return this.upperBound.x - this.lowerBound.x >= 0 && this.upperBound.y - this.lowerBound.y >= 0 && this.lowerBound.IsValid() && this.upperBound.IsValid();
        },
        GetCenter: function() {
          return new b2Vec2(.5 * (this.lowerBound.x + this.upperBound.x), .5 * (this.lowerBound.y + this.upperBound.y));
        },
        GetExtents: function() {
          return new b2Vec2(.5 * (this.upperBound.x - this.lowerBound.x), .5 * (this.upperBound.y - this.lowerBound.y));
        },
        GetPerimeter: function() {
          return 2 * (this.upperBound.x - this.lowerBound.x + (this.upperBound.y - this.lowerBound.y));
        },
        Combine: function(aabb1, aabb2) {
          if (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);
          } else {
            this.lowerBound.x = b2Min(this.lowerBound.x, aabb1.lowerBound.x);
            this.lowerBound.y = b2Min(this.lowerBound.y, aabb1.lowerBound.y);
            this.upperBound.x = b2Max(this.upperBound.x, aabb1.upperBound.x);
            this.upperBound.y = b2Max(this.upperBound.y, aabb1.upperBound.y);
          }
        },
        Contains: function(aabb) {
          return this.lowerBound.x <= aabb.lowerBound.x && this.lowerBound.y <= aabb.lowerBound.y && aabb.upperBound.x <= this.upperBound.x && aabb.upperBound.y <= this.upperBound.y;
        },
        RayCast: function(output, input) {
          var tmin = -b2_maxFloat;
          var tmax = b2_maxFloat;
          var p = input.p1;
          var d = b2Vec2.Subtract(input.p2, input.p1);
          var absD = b2Abs_v2(d);
          var normal = new b2Vec2();
          for (var i = 0; i < 2; ++i) if (absD.get_i(i) < b2_epsilon) {
            if (p.get_i(i) < this.lowerBound.get_i(i) || this.upperBound.get_i(i) < p.get_i(i)) return false;
          } else {
            var inv_d = 1 / d.get_i(i);
            var t1 = (this.lowerBound.get_i(i) - p.get_i(i)) * inv_d;
            var t2 = (this.upperBound.get_i(i) - p.get_i(i)) * inv_d;
            var s = -1;
            if (t1 > t2) {
              var temp = t2;
              t2 = t1;
              t1 = temp;
              s = 1;
            }
            if (t1 > tmin) {
              normal.x = normal.y = 0;
              normal.set_i(i, s);
              tmin = t1;
            }
            tmax = b2Min(tmax, t2);
            if (tmin > tmax) return false;
          }
          if (tmin < 0 || input.maxFraction < tmin) return false;
          output.fraction = tmin;
          output.normal.x = normal.x;
          output.normal.y = normal.y;
          return true;
        }
      };
      function b2CollideCircles(manifold, circleA, xfA, circleB, xfB) {
        manifold.pointCount = 0;
        var pA = b2Mul_t_v2(xfA, circleA.m_p);
        var pB = b2Mul_t_v2(xfB, circleB.m_p);
        var dx = pB.x - pA.x;
        var dy = pB.y - pA.y;
        var distSqr = dx * dx + dy * dy;
        var rA = circleA.m_radius, rB = circleB.m_radius;
        var radius = rA + rB;
        if (distSqr > radius * radius) return;
        manifold.type = b2Manifold.e_circles;
        manifold.localPoint.x = circleA.m_p.x;
        manifold.localPoint.y = circleA.m_p.y;
        manifold.localNormal.x = manifold.localNormal.y = 0;
        manifold.pointCount = 1;
        manifold.points[0] = new b2ManifoldPoint();
        manifold.points[0].localPoint.x = circleB.m_p.x;
        manifold.points[0].localPoint.y = circleB.m_p.y;
        manifold.points[0].id.Reset();
      }
      function b2CollidePolygonAndCircle(manifold, polygonA, xfA, circleB, xfB) {
        manifold.pointCount = 0;
        var c = b2Mul_t_v2(xfB, circleB.m_p);
        var cLocal = b2MulT_t_v2(xfA, c);
        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 = normals[i].x * (cLocal.x - vertices[i].x) + normals[i].y * (cLocal.y - vertices[i].y);
          if (s > radius) return;
          if (s > separation) {
            separation = s;
            normalIndex = i;
          }
        }
        var vertIndex1 = normalIndex;
        var vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0;
        var v1 = vertices[vertIndex1];
        var v2 = vertices[vertIndex2];
        if (separation < b2_epsilon) {
          manifold.pointCount = 1;
          manifold.type = b2Manifold.e_faceA;
          manifold.localNormal.x = normals[normalIndex].x;
          manifold.localNormal.y = normals[normalIndex].y;
          manifold.localPoint.x = .5 * (v1.x + v2.x);
          manifold.localPoint.y = .5 * (v1.y + v2.y);
          manifold.points[0] = new b2ManifoldPoint();
          manifold.points[0].localPoint.x = circleB.m_p.x;
          manifold.points[0].localPoint.y = circleB.m_p.y;
          manifold.points[0].id.Reset();
          return;
        }
        var u1 = (cLocal.x - v1.x) * (v2.x - v1.x) + (cLocal.y - v1.y) * (v2.y - v1.y);
        var u2 = (cLocal.x - v2.x) * (v1.x - v2.x) + (cLocal.y - v2.y) * (v1.y - v2.y);
        if (u1 <= 0) {
          if (b2DistanceSquared(cLocal, v1) > radius * radius) return;
          manifold.pointCount = 1;
          manifold.type = b2Manifold.e_faceA;
          manifold.localNormal.x = cLocal.x - v1.x;
          manifold.localNormal.y = cLocal.y - v1.y;
          manifold.localNormal.Normalize();
          manifold.localPoint.x = v1.x;
          manifold.localPoint.y = v1.y;
          manifold.points[0] = new b2ManifoldPoint();
          manifold.points[0].localPoint.x = circleB.m_p.x;
          manifold.points[0].localPoint.y = circleB.m_p.y;
          manifold.points[0].id.Reset();
        } else if (u2 <= 0) {
          if (b2DistanceSquared(cLocal, v2) > radius * radius) return;
          manifold.pointCount = 1;
          manifold.type = b2Manifold.e_faceA;
          manifold.localNormal.x = cLocal.x - v2.x;
          manifold.localNormal.y = cLocal.y - v2.y;
          manifold.localNormal.Normalize();
          manifold.localPoint.x = v2.x;
          manifold.localPoint.y = v2.y;
          manifold.points[0] = new b2ManifoldPoint();
          manifold.points[0].localPoint.x = circleB.m_p.x;
          manifold.points[0].localPoint.y = circleB.m_p.y;
          manifold.points[0].id.Reset();
        } else {
          var faceCenterx = .5 * (v1.x + v2.x);
          var faceCentery = .5 * (v1.y + v2.y);
          var separation = (cLocal.x - faceCenterx) * normals[vertIndex1].x + (cLocal.y - faceCentery) * normals[vertIndex1].y;
          if (separation > radius) return;
          manifold.pointCount = 1;
          manifold.type = b2Manifold.e_faceA;
          manifold.localNormal.x = normals[vertIndex1].x;
          manifold.localNormal.y = normals[vertIndex1].y;
          manifold.localPoint.x = faceCenterx;
          manifold.localPoint.y = faceCentery;
          manifold.points[0] = new b2ManifoldPoint();
          manifold.points[0].localPoint.x = circleB.m_p.x;
          manifold.points[0].localPoint.y = circleB.m_p.y;
          manifold.points[0].id.Reset();
        }
      }
      function b2FindMaxSeparation(edgeIndex, poly1, xf1, poly2, xf2) {
        var count1 = poly1.m_count;
        var count2 = poly2.m_count;
        var n1s = poly1.m_normals;
        var v1s = poly1.m_vertices;
        var v2s = poly2.m_vertices;
        var xf = b2MulT_t_t(xf2, xf1);
        var bestIndex = 0;
        var maxSeparation = -b2_maxFloat;
        for (var i = 0; i < count1; ++i) {
          var nx = xf.q.c * n1s[i].x - xf.q.s * n1s[i].y;
          var ny = xf.q.s * n1s[i].x + xf.q.c * n1s[i].y;
          var v1x = xf.q.c * v1s[i].x - xf.q.s * v1s[i].y + xf.p.x;
          var v1y = xf.q.s * v1s[i].x + xf.q.c * v1s[i].y + xf.p.y;
          var si = b2_maxFloat;
          for (var j = 0; j < count2; ++j) {
            var sij = nx * (v2s[j].x - v1x) + ny * (v2s[j].y - v1y);
            sij < si && (si = sij);
          }
          if (si > maxSeparation) {
            maxSeparation = si;
            bestIndex = i;
          }
        }
        edgeIndex[0] = bestIndex;
        return maxSeparation;
      }
      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;
        b2Assert(0 <= edge1 && edge1 < poly1.m_count);
        var t1x = xf1.q.c * normals1[edge1].x - xf1.q.s * normals1[edge1].y;
        var t1y = xf1.q.s * normals1[edge1].x + xf1.q.c * normals1[edge1].y;
        var normal1x = xf2.q.c * t1x + xf2.q.s * t1y;
        var normal1y = -xf2.q.s * t1x + xf2.q.c * t1y;
        var index = 0;
        var minDot = b2_maxFloat;
        for (var i = 0; i < count2; ++i) {
          var dot = normal1x * normals2[i].x + normal1y * normals2[i].y;
          if (dot < minDot) {
            minDot = dot;
            index = i;
          }
        }
        var i1 = index;
        var i2 = i1 + 1 < count2 ? i1 + 1 : 0;
        c[0].v.x = xf2.q.c * vertices2[i1].x - xf2.q.s * vertices2[i1].y + xf2.p.x;
        c[0].v.y = xf2.q.s * vertices2[i1].x + xf2.q.c * vertices2[i1].y + xf2.p.y;
        c[0].id.indexA = edge1;
        c[0].id.indexB = i1;
        c[0].id.typeA = b2ContactID.e_face;
        c[0].id.typeB = b2ContactID.e_vertex;
        c[1].v.x = xf2.q.c * vertices2[i2].x - xf2.q.s * vertices2[i2].y + xf2.p.x;
        c[1].v.y = xf2.q.s * vertices2[i2].x + xf2.q.c * vertices2[i2].y + xf2.p.y;
        c[1].id.indexA = edge1;
        c[1].id.indexB = i2;
        c[1].id.typeA = b2ContactID.e_face;
        c[1].id.typeB = b2ContactID.e_vertex;
      }
      function b2CollidePolygons(manifold, polyA, xfA, polyB, xfB) {
        manifold.pointCount = 0;
        var totalRadius = polyA.m_radius + polyB.m_radius;
        var edgeA = [ 0 ];
        var separationA = b2FindMaxSeparation(edgeA, polyA, xfA, polyB, xfB);
        if (separationA > totalRadius) return;
        var edgeB = [ 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_tol = .1 * b2_linearSlop;
        if (separationB > separationA + k_tol) {
          poly1 = polyB;
          poly2 = polyA;
          xf1 = xfB;
          xf2 = xfA;
          edge1 = edgeB[0];
          manifold.type = b2Manifold.e_faceB;
          flip = 1;
        } else {
          poly1 = polyA;
          poly2 = polyB;
          xf1 = xfA;
          xf2 = xfB;
          edge1 = edgeA[0];
          manifold.type = b2Manifold.e_faceA;
          flip = 0;
        }
        b2FindIncidentEdge(b2CollidePolygons._local_incidentEdges, poly1, xf1, edge1, poly2, xf2);
        var count1 = poly1.m_count;
        var vertices1 = poly1.m_vertices;
        var iv1 = edge1;
        var iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0;
        var v11 = vertices1[iv1];
        var v12 = vertices1[iv2];
        b2CollidePolygons._localTangent.x = v12.x - v11.x;
        b2CollidePolygons._localTangent.y = v12.y - v11.y;
        b2CollidePolygons._localTangent.Normalize();
        var localNormalx = 1 * b2CollidePolygons._localTangent.y;
        var localNormaly = -1 * b2CollidePolygons._localTangent.x;
        var planePointx = .5 * (v11.x + v12.x);
        var planePointy = .5 * (v11.y + v12.y);
        var tangentx = xf1.q.c * b2CollidePolygons._localTangent.x - xf1.q.s * b2CollidePolygons._localTangent.y;
        var tangenty = xf1.q.s * b2CollidePolygons._localTangent.x + xf1.q.c * b2CollidePolygons._localTangent.y;
        var normalx = 1 * tangenty;
        var normaly = -1 * tangentx;
        v11 = b2Mul_t_v2(xf1, v11);
        v12 = b2Mul_t_v2(xf1, v12);
        var frontOffset = normalx * v11.x + normaly * v11.y;
        var sideOffset1 = -(tangentx * v11.x + tangenty * v11.y) + totalRadius;
        var sideOffset2 = tangentx * v12.x + tangenty * v12.y + totalRadius;
        var clipPoints1 = new Array(2);
        var clipPoints2 = new Array(2);
        var np;
        np = b2ClipSegmentToLine(clipPoints1, b2CollidePolygons._local_incidentEdges, -tangentx, -tangenty, sideOffset1, iv1);
        if (np < 2) return;
        np = b2ClipSegmentToLine(clipPoints2, clipPoints1, tangentx, tangenty, sideOffset2, iv2);
        if (np < 2) return;
        manifold.localNormal.x = localNormalx;
        manifold.localNormal.y = localNormaly;
        manifold.localPoint.x = planePointx;
        manifold.localPoint.y = planePointy;
        var pointCount = 0;
        for (var i = 0; i < b2_maxManifoldPoints; ++i) {
          var separation = normalx * clipPoints2[i].v.x + normaly * clipPoints2[i].v.y - frontOffset;
          if (separation <= totalRadius) {
            var cp = manifold.points[pointCount] = new b2ManifoldPoint();
            cp.localPoint.Assign(b2MulT_t_v2(xf2, clipPoints2[i].v));
            cp.id.Assign(clipPoints2[i].id);
            if (flip) {
              var cf = new b2ContactID();
              cf.Assign(cp.id);
              cp.id.indexA = cf.indexB;
              cp.id.indexB = cf.indexA;
              cp.id.typeA = cf.typeB;
              cp.id.typeB = cf.typeA;
            }
            ++pointCount;
          }
        }
        manifold.pointCount = pointCount;
      }
      b2CollidePolygons._localTangent = new b2Vec2();
      b2CollidePolygons._local_incidentEdges = [ new b2ClipVertex(), new b2ClipVertex() ];
      function b2CollideEdgeAndCircle(manifold, edgeA, xfA, circleB, xfB) {
        manifold.pointCount = 0;
        var Q = b2MulT_t_v2(xfA, b2Mul_t_v2(xfB, circleB.m_p));
        var A = edgeA.m_vertex1, B = edgeA.m_vertex2;
        var ex = B.x - A.x;
        var ey = B.y - A.y;
        var u = ex * (B.x - Q.x) + ey * (B.y - Q.y);
        var v = ex * (Q.x - A.x) + ey * (Q.y - A.y);
        var radius = edgeA.m_radius + circleB.m_radius;
        var cf = new b2ContactID();
        cf.indexB = 0;
        cf.typeB = b2ContactID.e_vertex;
        if (v <= 0) {
          var P = A;
          var dx = Q.x - P.x;
          var dy = Q.y - P.y;
          var dd = dx * dx + dy * dy;
          if (dd > radius * radius) return;
          if (edgeA.m_hasVertex0) {
            var A1 = edgeA.m_vertex0;
            var B1 = A;
            var e1x = B1.x - A1.x;
            var e1y = B1.y - A1.y;
            var u1 = e1x * (B1.x - Q.x) + e1y * (B1.y - Q.y);
            if (u1 > 0) return;
          }
          cf.indexA = 0;
          cf.typeA = b2ContactID.e_vertex;
          manifold.pointCount = 1;
          manifold.type = b2Manifold.e_circles;
          manifold.localNormal.x = manifold.localNormal.y = 0;
          manifold.localPoint.x = P.x;
          manifold.localPoint.y = P.y;
          manifold.points[0] = new b2ManifoldPoint();
          manifold.points[0].id.Assign(cf);
          manifold.points[0].localPoint.x = circleB.m_p.x;
          manifold.points[0].localPoint.y = circleB.m_p.y;
          return;
        }
        if (u <= 0) {
          var P = B;
          var dx = Q.x - P.x;
          var dy = Q.y - P.y;
          var dd = dx * dx + dy * dy;
          if (dd > radius * radius) return;
          if (edgeA.m_hasVertex3) {
            var B2 = edgeA.m_vertex3;
            var A2 = B;
            var e2x = B2.x - A2.x;
            var e2y = B2.y - A2.y;
            var v2 = e2x * (Q.x - A2.x) + e2y * (Q.y - A2.y);
            if (v2 > 0) return;
          }
          cf.indexA = 1;
          cf.typeA = b2ContactID.e_vertex;
          manifold.pointCount = 1;
          manifold.type = b2Manifold.e_circles;
          manifold.localNormal.x = manifold.localNormal.y = 0;
          manifold.localPoint.x = P.x;
          manifold.localPoint.y = P.y;
          manifold.points[0] = new b2ManifoldPoint();
          manifold.points[0].id.Assign(cf);
          manifold.points[0].localPoint.x = circleB.m_p.x;
          manifold.points[0].localPoint.y = circleB.m_p.y;
          return;
        }
        var den = ex * ex + ey * ey;
        b2Assert(den > 0);
        var Px = 1 / den * (u * A.x + v * B.x);
        var Py = 1 / den * (u * A.y + v * B.y);
        var dx = Q.x - Px;
        var dy = Q.y - Py;
        var dd = dx * dx + dy * dy;
        if (dd > radius * radius) return;
        var nx = -ey;
        var ny = ex;
        if (nx * (Q.x - A.x) + ny * (Q.y - A.y) < 0) {
          nx = -nx;
          ny = -ny;
        }
        cf.indexA = 0;
        cf.typeA = b2ContactID.e_face;
        manifold.pointCount = 1;
        manifold.type = b2Manifold.e_faceA;
        manifold.localNormal.x = nx;
        manifold.localNormal.y = ny;
        manifold.localNormal.Normalize();
        manifold.localPoint.x = A.x;
        manifold.localPoint.y = A.y;
        manifold.points[0] = new b2ManifoldPoint();
        manifold.points[0].id.Assign(cf);
        manifold.points[0].localPoint.x = circleB.m_p.x;
        manifold.points[0].localPoint.y = circleB.m_p.y;
      }
      function b2EPAxis() {
        this.type = 0;
        this.index = 0;
        this.separation = 0;
      }
      b2EPAxis.e_unknown = 0;
      b2EPAxis.e_edgeA = 1;
      b2EPAxis.e_edgeB = 2;
      function b2TempPolygon() {
        this.vertices = new Array(b2_maxPolygonVertices);
        this.normals = new Array(b2_maxPolygonVertices);
        this.count = 0;
      }
      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;
      }
      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 = 0, this.m_type2 = 0;
        this.m_lowerLimit = new b2Vec2(), this.m_upperLimit = new b2Vec2();
        this.m_radius = 0;
        this.m_front = false;
      }
      b2EPCollider._temp_edge = new b2Vec2();
      b2EPCollider._temp_edge0 = new b2Vec2();
      b2EPCollider._temp_edge2 = new b2Vec2();
      b2EPCollider.prototype = {
        Collide: function(manifold, edgeA, xfA, polygonB, xfB) {
          this.m_xf.Assign(b2MulT_t_t(xfA, xfB));
          this.m_centroidB.x = this.m_xf.q.c * polygonB.m_centroid.x - this.m_xf.q.s * polygonB.m_centroid.y + this.m_xf.p.x;
          this.m_centroidB.y = this.m_xf.q.s * polygonB.m_centroid.x + this.m_xf.q.c * polygonB.m_centroid.y + this.m_xf.p.y;
          this.m_v0.x = edgeA.m_vertex0.x;
          this.m_v0.y = edgeA.m_vertex0.y;
          this.m_v1.x = edgeA.m_vertex1.x;
          this.m_v1.y = edgeA.m_vertex1.y;
          this.m_v2.x = edgeA.m_vertex2.x;
          this.m_v2.y = edgeA.m_vertex2.y;
          this.m_v3.x = edgeA.m_vertex3.x;
          this.m_v3.y = edgeA.m_vertex3.y;
          var hasVertex0 = edgeA.m_hasVertex0;
          var hasVertex3 = edgeA.m_hasVertex3;
          b2EPCollider._temp_edge.x = this.m_v2.x - this.m_v1.x;
          b2EPCollider._temp_edge.y = this.m_v2.y - this.m_v1.y;
          b2EPCollider._temp_edge.Normalize();
          this.m_normal1.x = b2EPCollider._temp_edge.y;
          this.m_normal1.y = -b2EPCollider._temp_edge.x;
          var offset1 = this.m_normal1.x * (this.m_centroidB.x - this.m_v1.x) + this.m_normal1.y * (this.m_centroidB.y - this.m_v1.y);
          var offset0 = 0, offset2 = 0;
          var convex1 = false, convex2 = false;
          if (hasVertex0) {
            b2EPCollider._temp_edge0.x = this.m_v1.x - this.m_v0.x;
            b2EPCollider._temp_edge0.y = this.m_v1.y - this.m_v0.y;
            b2EPCollider._temp_edge0.Normalize();
            this.m_normal0.x = b2EPCollider._temp_edge0.y;
            this.m_normal0.y = -b2EPCollider._temp_edge0.x;
            convex1 = b2EPCollider._temp_edge0.x * b2EPCollider._temp_edge.y - b2EPCollider._temp_edge0.y * b2EPCollider._temp_edge.x >= 0;
            offset0 = this.m_normal0.x * (this.m_centroidB.x - this.m_v0.x) + this.m_normal0.y * (this.m_centroidB.y - this.m_v0.y);
          }
          if (hasVertex3) {
            b2EPCollider._temp_edge2.x = this.m_v3.x - this.m_v2.x;
            b2EPCollider._temp_edge2.y = this.m_v3.y - this.m_v2.y;
            b2EPCollider._temp_edge2.Normalize();
            this.m_normal2.x = b2EPCollider._temp_edge2.y;
            this.m_normal2.y = -b2EPCollider._temp_edge2.x;
            convex2 = b2EPCollider._temp_edge.x * b2EPCollider._temp_edge2.y - b2EPCollider._temp_edge.y * b2EPCollider._temp_edge2.x > 0;
            offset2 = this.m_normal2.x * (this.m_centroidB.x - this.m_v2.x) + this.m_normal2.y * (this.m_centroidB.y - this.m_v2.y);
          }
          if (hasVertex0 && hasVertex3) if (convex1 && convex2) {
            this.m_front = offset0 >= 0 || offset1 >= 0 || offset2 >= 0;
            if (this.m_front) {
              this.m_normal.x = this.m_normal1.x;
              this.m_normal.y = this.m_normal1.y;
              this.m_lowerLimit.x = this.m_normal0.x;
              this.m_lowerLimit.y = this.m_normal0.y;
              this.m_upperLimit.x = this.m_normal2.x;
              this.m_upperLimit.y = this.m_normal2.y;
            } else {
              this.m_normal.x = -this.m_normal1.x;
              this.m_normal.y = -this.m_normal1.y;
              this.m_lowerLimit.x = -this.m_normal1.x;
              this.m_lowerLimit.y = -this.m_normal1.y;
              this.m_upperLimit.x = -this.m_normal1.x;
              this.m_upperLimit.y = -this.m_normal1.y;
            }
          } else if (convex1) {
            this.m_front = offset0 >= 0 || offset1 >= 0 && offset2 >= 0;
            if (this.m_front) {
              this.m_normal.x = this.m_normal1.x;
              this.m_normal.y = this.m_normal1.y;
              this.m_lowerLimit.x = this.m_normal0.x;
              this.m_lowerLimit.y = this.m_normal0.y;
              this.m_upperLimit.x = this.m_normal1.x;
              this.m_upperLimit.y = this.m_normal1.y;
            } else {
              this.m_normal.x = -this.m_normal1.x;
              this.m_normal.y = -this.m_normal1.y;
              this.m_lowerLimit.x = -this.m_normal2.x;
              this.m_lowerLimit.y = -this.m_normal2.y;
              this.m_upperLimit.x = -this.m_normal1.x;
              this.m_upperLimit.y = -this.m_normal1.y;
            }
          } else if (convex2) {
            this.m_front = offset2 >= 0 || offset0 >= 0 && offset1 >= 0;
            if (this.m_front) {
              this.m_normal.x = this.m_normal1.x;
              this.m_normal.y = this.m_normal1.y;
              this.m_lowerLimit.x = this.m_normal1.x;
              this.m_lowerLimit.y = this.m_normal1.y;
              this.m_upperLimit.x = this.m_normal2.x;
              this.m_upperLimit.y = this.m_normal2.y;
            } else {
              this.m_normal.x = -this.m_normal1.x;
              this.m_normal.y = -this.m_normal1.y;
              this.m_lowerLimit.x = -this.m_normal1.x;
              this.m_lowerLimit.y = -this.m_normal1.y;
              this.m_upperLimit.x = -this.m_normal0.x;
              this.m_upperLimit.y = -this.m_normal0.y;
            }
          } else {
            this.m_front = offset0 >= 0 && offset1 >= 0 && offset2 >= 0;
            if (this.m_front) {
              this.m_normal.x = this.m_normal1.x;
              this.m_normal.y = this.m_normal1.y;
              this.m_lowerLimit.x = this.m_normal1.x;
              this.m_lowerLimit.y = this.m_normal1.y;
              this.m_upperLimit.x = this.m_normal1.x;
              this.m_upperLimit.y = this.m_normal1.y;
            } else {
              this.m_normal.x = -this.m_normal1.x;
              this.m_normal.y = -this.m_normal1.y;
              this.m_lowerLimit.x = -this.m_normal2.x;
              this.m_lowerLimit.y = -this.m_normal2.y;
              this.m_upperLimit.x = -this.m_normal0.x;
              this.m_upperLimit.y = -this.m_normal0.y;
            }
          } else if (hasVertex0) if (convex1) {
            this.m_front = offset0 >= 0 || offset1 >= 0;
            if (this.m_front) {
              this.m_normal.x = this.m_normal1.x;
              this.m_normal.y = this.m_normal1.y;
              this.m_lowerLimit.x = this.m_normal0.x;
              this.m_lowerLimit.y = this.m_normal0.y;
              this.m_upperLimit.x = -this.m_normal1.x;
              this.m_upperLimit.y = -this.m_normal1.y;
            } else {
              this.m_normal.x = -this.m_normal1.x;
              this.m_normal.y = -this.m_normal1.y;
              this.m_lowerLimit.x = this.m_normal1.x;
              this.m_lowerLimit.y = this.m_normal1.y;
              this.m_upperLimit.x = -this.m_normal1.x;
              this.m_upperLimit.y = -this.m_normal1.y;
            }
          } else {
            this.m_front = offset0 >= 0 && offset1 >= 0;
            if (this.m_front) {
              this.m_normal.x = this.m_normal1.x;
              this.m_normal.y = this.m_normal1.y;
              this.m_lowerLimit.x = this.m_normal1.x;
              this.m_lowerLimit.y = this.m_normal1.y;
              this.m_upperLimit.x = -this.m_normal1.x;
              this.m_upperLimit.y = -this.m_normal1.y;
            } else {
              this.m_normal.x = -this.m_normal1.x;
              this.m_normal.y = -this.m_normal1.y;
              this.m_lowerLimit.x = this.m_normal1.x;
              this.m_lowerLimit.y = this.m_normal1.y;
              this.m_upperLimit.x = -this.m_normal0.x;
              this.m_upperLimit.y = -this.m_normal0.y;
            }
          } else if (hasVertex3) if (convex2) {
            this.m_front = offset1 >= 0 || offset2 >= 0;
            if (this.m_front) {
              this.m_normal.x = this.m_normal1.x;
              this.m_normal.y = this.m_normal1.y;
              this.m_lowerLimit.x = -this.m_normal1.x;
              this.m_lowerLimit.y = -this.m_normal1.y;
              this.m_upperLimit.x = this.m_normal2.x;
              this.m_upperLimit.y = this.m_normal2.y;
            } else {
              this.m_normal.x = -this.m_normal1.x;
              this.m_normal.y = -this.m_normal1.y;
              this.m_lowerLimit.x = -this.m_normal1.x;
              this.m_lowerLimit.y = -this.m_normal1.y;
              this.m_upperLimit.x = this.m_normal1.x;
              this.m_upperLimit.y = this.m_normal1.y;
            }
          } else {
            this.m_front = offset1 >= 0 && offset2 >= 0;
            if (this.m_front) {
              this.m_normal.x = this.m_normal1.x;
              this.m_normal.y = this.m_normal1.y;
              this.m_lowerLimit.x = -this.m_normal1.x;
              this.m_lowerLimit.y = -this.m_normal1.y;
              this.m_upperLimit.x = this.m_normal1.x;
              this.m_upperLimit.y = this.m_normal1.y;
            } else {
              this.m_normal.x = -this.m_normal1.x;
              this.m_normal.y = -this.m_normal1.y;
              this.m_lowerLimit.x = -this.m_normal2.x;
              this.m_lowerLimit.y = -this.m_normal2.y;
              this.m_upperLimit.x = this.m_normal1.x;
              this.m_upperLimit.y = this.m_normal1.y;
            }
          } else {
            this.m_front = offset1 >= 0;
            if (this.m_front) {
              this.m_normal.x = this.m_normal1.x;
              this.m_normal.y = this.m_normal1.y;
              this.m_lowerLimit.x = -this.m_normal1.x;
              this.m_lowerLimit.y = -this.m_normal1.y;
              this.m_upperLimit.x = -this.m_normal1.x;
              this.m_upperLimit.y = -this.m_normal1.y;
            } else {
              this.m_normal.x = -this.m_normal1.x;
              this.m_normal.y = -this.m_normal1.y;
              this.m_lowerLimit.x = this.m_normal1.x;
              this.m_lowerLimit.y = this.m_normal1.y;
              this.m_upperLimit.x = this.m_normal1.x;
              this.m_upperLimit.y = this.m_normal1.y;
            }
          }
          this.m_polygonB.count = polygonB.m_count;
          for (var i = 0; i < polygonB.m_count; ++i) {
            this.m_polygonB.vertices[i] = b2Mul_t_v2(this.m_xf, polygonB.m_vertices[i]);
            this.m_polygonB.normals[i] = b2Mul_r_v2(this.m_xf.q, polygonB.m_normals[i]);
          }
          this.m_radius = 2 * b2_polygonRadius;
          manifold.pointCount = 0;
          var edgeAxis = this.ComputeEdgeSeparation();
          if (edgeAxis.type == b2EPAxis.e_unknown) return;
          if (edgeAxis.separation > this.m_radius) return;
          var polygonAxis = this.ComputePolygonSeparation();
          if (polygonAxis.type != b2EPAxis.e_unknown && polygonAxis.separation > this.m_radius) return;
          var k_relativeTol = .98;
          var k_absoluteTol = .001;
          var primaryAxis = new b2EPAxis();
          primaryAxis = polygonAxis.type == b2EPAxis.e_unknown ? edgeAxis : polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol ? polygonAxis : edgeAxis;
          var ie = new Array(2);
          var rf = new b2ReferenceFace();
          if (primaryAxis.type == b2EPAxis.e_edgeA) {
            manifold.type = b2Manifold.e_faceA;
            var bestIndex = 0;
            var bestValue = this.m_normal.x * this.m_polygonB.normals[0].x + this.m_normal.y * this.m_polygonB.normals[0].y;
            for (var i = 1; i < this.m_polygonB.count; ++i) {
              var value = this.m_normal.x * this.m_polygonB.normals[i].x + this.m_normal.y * this.m_polygonB.normals[i].y;
              if (value < bestValue) {
                bestValue = value;
                bestIndex = i;
              }
            }
            var i1 = bestIndex;
            var i2 = i1 + 1 < this.m_polygonB.count ? i1 + 1 : 0;
            ie[0] = new b2ClipVertex();
            ie[0].v.x = this.m_polygonB.vertices[i1].x;
            ie[0].v.y = this.m_polygonB.vertices[i1].y;
            ie[0].id.indexA = 0;
            ie[0].id.indexB = i1;
            ie[0].id.typeA = b2ContactID.e_face;
            ie[0].id.typeB = b2ContactID.e_vertex;
            ie[1] = new b2ClipVertex();
            ie[1].v.x = this.m_polygonB.vertices[i2].x;
            ie[1].v.y = this.m_polygonB.vertices[i2].y;
            ie[1].id.indexA = 0;
            ie[1].id.indexB = i2;
            ie[1].id.typeA = b2ContactID.e_face;
            ie[1].id.typeB = b2ContactID.e_vertex;
            if (this.m_front) {
              rf.i1 = 0;
              rf.i2 = 1;
              rf.v1.x = this.m_v1.x;
              rf.v1.y = this.m_v1.y;
              rf.v2.x = this.m_v2.x;
              rf.v2.y = this.m_v2.y;
              rf.normal.x = this.m_normal1.x;
              rf.normal.y = this.m_normal1.y;
            } else {
              rf.i1 = 1;
              rf.i2 = 0;
              rf.v1.x = this.m_v2.x;
              rf.v1.y = this.m_v2.y;
              rf.v2.x = this.m_v1.x;
              rf.v2.y = this.m_v1.y;
              rf.normal.x = -this.m_normal1.x;
              rf.normal.y = -this.m_normal1.y;
            }
          } else {
            manifold.type = b2Manifold.e_faceB;
            ie[0] = new b2ClipVertex();
            ie[0].v = this.m_v1;
            ie[0].id.indexA = 0;
            ie[0].id.indexB = primaryAxis.index;
            ie[0].id.typeA = b2ContactID.e_vertex;
            ie[0].id.typeB = b2ContactID.e_face;
            ie[1] = new b2ClipVertex();
            ie[1].v = this.m_v2;
            ie[1].id.indexA = 0;
            ie[1].id.indexB = primaryAxis.index;
            ie[1].id.typeA = b2ContactID.e_vertex;
            ie[1].id.typeB = b2ContactID.e_face;
            rf.i1 = primaryAxis.index;
            rf.i2 = rf.i1 + 1 < this.m_polygonB.count ? rf.i1 + 1 : 0;
            rf.v1.x = this.m_polygonB.vertices[rf.i1].x;
            rf.v1.y = this.m_polygonB.vertices[rf.i1].y;
            rf.v2.x = this.m_polygonB.vertices[rf.i2].x;
            rf.v2.y = this.m_polygonB.vertices[rf.i2].y;
            rf.normal.x = this.m_polygonB.normals[rf.i1].x;
            rf.normal.y = this.m_polygonB.normals[rf.i1].y;
          }
          rf.sideNormal1.x = rf.normal.y;
          rf.sideNormal1.y = -rf.normal.x;
          rf.sideNormal2.x = -rf.sideNormal1.x;
          rf.sideNormal2.y = -rf.sideNormal1.y;
          rf.sideOffset1 = rf.sideNormal1.x * rf.v1.x + rf.sideNormal1.y * rf.v1.y;
          rf.sideOffset2 = rf.sideNormal2.x * rf.v2.x + rf.sideNormal2.y * rf.v2.y;
          var clipPoints1 = new Array(2);
          var clipPoints2 = new Array(2);
          var np;
          np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1.x, rf.sideNormal1.y, rf.sideOffset1, rf.i1);
          if (np < b2_maxManifoldPoints) return;
          np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2.x, rf.sideNormal2.y, rf.sideOffset2, rf.i2);
          if (np < b2_maxManifoldPoints) return;
          if (primaryAxis.type == b2EPAxis.e_edgeA) {
            manifold.localNormal.x = rf.normal.x;
            manifold.localNormal.y = rf.normal.y;
            manifold.localPoint.x = rf.v1.x;
            manifold.localPoint.y = rf.v1.y;
          } else {
            manifold.localNormal.x = polygonB.m_normals[rf.i1].x;
            manifold.localNormal.y = polygonB.m_normals[rf.i1].y;
            manifold.localPoint.x = polygonB.m_vertices[rf.i1].x;
            manifold.localPoint.y = polygonB.m_vertices[rf.i1].y;
          }
          var pointCount = 0;
          for (var i = 0; i < b2_maxManifoldPoints; ++i) {
            var separation = rf.normal.x * (clipPoints2[i].v.x - rf.v1.x) + rf.normal.y * (clipPoints2[i].v.y - rf.v1.y);
            if (separation <= this.m_radius) {
              var cp = manifold.points[pointCount] = new b2ManifoldPoint();
              if (primaryAxis.type == b2EPAxis.e_edgeA) {
                cp.localPoint.Assign(b2MulT_t_v2(this.m_xf, clipPoints2[i].v));
                cp.id.Assign(clipPoints2[i].id);
              } else {
                cp.localPoint.x = clipPoints2[i].v.x;
                cp.localPoint.y = clipPoints2[i].v.y;
                cp.id.typeA = clipPoints2[i].id.typeB;
                cp.id.typeB = clipPoints2[i].id.typeA;
                cp.id.indexA = clipPoints2[i].id.indexB;
                cp.id.indexB = clipPoints2[i].id.indexA;
              }
              ++pointCount;
            }
          }
          manifold.pointCount = pointCount;
        },
        ComputeEdgeSeparation: function() {
          var axis = new b2EPAxis();
          axis.type = b2EPAxis.e_edgeA;
          axis.index = this.m_front ? 0 : 1;
          axis.separation = Number.MAX_VALUE;
          for (var i = 0; i < this.m_polygonB.count; ++i) {
            var s = this.m_normal.x * (this.m_polygonB.vertices[i].x - this.m_v1.x) + this.m_normal.y * (this.m_polygonB.vertices[i].y - this.m_v1.y);
            s < axis.separation && (axis.separation = s);
          }
          return axis;
        },
        ComputePolygonSeparation: function() {
          var axis = new b2EPAxis();
          axis.type = b2EPAxis.e_unknown;
          axis.index = -1;
          axis.separation = -Number.MAX_VALUE;
          var perpx = -this.m_normal.y;
          var perpy = this.m_normal.x;
          for (var i = 0; i < this.m_polygonB.count; ++i) {
            var nx = -this.m_polygonB.normals[i].x;
            var ny = -this.m_polygonB.normals[i].y;
            var s1 = nx * (this.m_polygonB.vertices[i].x - this.m_v1.x) + ny * (this.m_polygonB.vertices[i].y - this.m_v1.y);
            var s2 = nx * (this.m_polygonB.vertices[i].x - this.m_v2.x) + ny * (this.m_polygonB.vertices[i].y - this.m_v2.y);
            var s = b2Min(s1, s2);
            if (s > this.m_radius) {
              axis.type = b2EPAxis.e_edgeB;
              axis.index = i;
              axis.separation = s;
              return axis;
            }
            if (nx * perpx + ny * perpy >= 0) {
              if ((nx - this.m_upperLimit.x) * this.m_normal.x + (ny - this.m_upperLimit.y) * this.m_normal.y < -b2_angularSlop) continue;
            } else if ((nx - this.m_lowerLimit.x) * this.m_normal.x + (ny - this.m_lowerLimit.y) * this.m_normal.y < -b2_angularSlop) continue;
            if (s > axis.separation) {
              axis.type = b2EPAxis.e_edgeB;
              axis.index = i;
              axis.separation = s;
            }
          }
          return axis;
        }
      };
      b2EPCollider.e_isolated = 0;
      b2EPCollider.e_concave = 1;
      b2EPCollider.e_convex = 2;
      function b2CollideEdgeAndPolygon(manifold, edgeA, xfA, polygonB, xfB) {
        b2CollideEdgeAndPolygon.collider.Collide(manifold, edgeA, xfA, polygonB, xfB);
      }
      b2CollideEdgeAndPolygon.collider = new b2EPCollider();
      function b2ClipSegmentToLine(vOut, vIn, normalx, normaly, offset, vertexIndexA) {
        var numOut = 0;
        var distance0 = normalx * vIn[0].v.x + normaly * vIn[0].v.y - offset;
        var distance1 = normalx * vIn[1].v.x + normaly * vIn[1].v.y - offset;
        distance0 <= 0 && (vOut[numOut++] = vIn[0]);
        distance1 <= 0 && (vOut[numOut++] = vIn[1]);
        if (distance0 * distance1 < 0) {
          var interp = distance0 / (distance0 - distance1);
          vOut[numOut] = new b2ClipVertex();
          vOut[numOut].v.x = vIn[0].v.x + interp * (vIn[1].v.x - vIn[0].v.x);
          vOut[numOut].v.y = vIn[0].v.y + interp * (vIn[1].v.y - vIn[0].v.y);
          vOut[numOut].id.indexA = vertexIndexA;
          vOut[numOut].id.indexB = vIn[0].id.indexB;
          vOut[numOut].id.typeA = b2ContactID.e_vertex;
          vOut[numOut].id.typeB = b2ContactID.e_face;
          ++numOut;
        }
        return numOut;
      }
      function b2TestShapeOverlap(shapeA, indexA, shapeB, indexB, xfA, xfB) {
        b2TestShapeOverlap.input.proxyA.Set(shapeA, indexA);
        b2TestShapeOverlap.input.proxyB.Set(shapeB, indexB);
        b2TestShapeOverlap.input.transformA = xfA;
        b2TestShapeOverlap.input.transformB = xfB;
        b2TestShapeOverlap.input.useRadii = true;
        b2TestShapeOverlap.cache.count = 0;
        b2DistanceFunc(b2TestShapeOverlap.output, b2TestShapeOverlap.cache, b2TestShapeOverlap.input);
        return b2TestShapeOverlap.output.distance < 10 * b2_epsilon;
      }
      b2TestShapeOverlap.input = new b2DistanceInput();
      b2TestShapeOverlap.cache = new b2SimplexCache();
      b2TestShapeOverlap.output = new b2DistanceOutput();
      function b2TestOverlap(a, b) {
        return !(b.lowerBound.x - a.upperBound.x > 0 || b.lowerBound.y - a.upperBound.y > 0 || a.lowerBound.x - b.upperBound.x > 0 || a.lowerBound.y - b.upperBound.y > 0);
      }
      var b2_nullNode = -1;
      function b2TreeNode() {
        this.aabb = new b2AABB();
        this.userData = null;
        this.parent = 0;
        this.child1 = this.child2 = this.height = 0;
      }
      b2TreeNode.prototype = {
        IsLeaf: function() {
          return this.child1 == b2_nullNode;
        }
      };
      function b2DynamicTree() {
        this.m_root = b2_nullNode;
        this.m_nodeCapacity = 16;
        this.m_nodeCount = 0;
        this.m_nodes = new Array(this.m_nodeCapacity);
        for (var i = 0; i < this.m_nodeCapacity - 1; ++i) {
          this.m_nodes[i] = new b2TreeNode();
          this.m_nodes[i].parent = i + 1;
          this.m_nodes[i].height = -1;
        }
        this.m_nodes[this.m_nodeCapacity - 1] = new b2TreeNode();
        this.m_nodes[this.m_nodeCapacity - 1].parent = b2_nullNode;
        this.m_nodes[this.m_nodeCapacity - 1].height = -1;
        this.m_freeList = 0;
        this.m_path = 0;
        this.m_insertionCount = 0;
      }
      b2DynamicTree.aabbExtensionFattener = new b2Vec2(b2_aabbExtension, b2_aabbExtension);
      b2DynamicTree.prototype = {
        CreateProxy: function(aabb, userData) {
          var proxyId = this.AllocateNode();
          this.m_nodes[proxyId].aabb.lowerBound.Assign(b2Vec2.Subtract(aabb.lowerBound, b2DynamicTree.aabbExtensionFattener));
          this.m_nodes[proxyId].aabb.upperBound.Assign(b2Vec2.Add(aabb.upperBound, b2DynamicTree.aabbExtensionFattener));
          this.m_nodes[proxyId].userData = userData;
          this.m_nodes[proxyId].height = 0;
          this.InsertLeaf(proxyId);
          return proxyId;
        },
        DestroyProxy: function(proxyId) {
          b2Assert(0 <= proxyId && proxyId < this.m_nodeCapacity);
          b2Assert(this.m_nodes[proxyId].IsLeaf());
          this.RemoveLeaf(proxyId);
          this.FreeNode(proxyId);
        },
        MoveProxy: function(proxyId, aabb, displacement) {
          b2Assert(0 <= proxyId && proxyId < this.m_nodeCapacity);
          b2Assert(this.m_nodes[proxyId].IsLeaf());
          if (this.m_nodes[proxyId].aabb.Contains(aabb)) return false;
          this.RemoveLeaf(proxyId);
          this.m_nodes[proxyId].aabb.Assign(aabb);
          this.m_nodes[proxyId].aabb.lowerBound.Subtract(b2DynamicTree.aabbExtensionFattener);
          this.m_nodes[proxyId].aabb.upperBound.Add(b2DynamicTree.aabbExtensionFattener);
          var d = b2Vec2.Multiply(b2_aabbMultiplier, displacement);
          d.x < 0 ? this.m_nodes[proxyId].aabb.lowerBound.x += d.x : this.m_nodes[proxyId].aabb.upperBound.x += d.x;
          d.y < 0 ? this.m_nodes[proxyId].aabb.lowerBound.y += d.y : this.m_nodes[proxyId].aabb.upperBound.y += d.y;
          this.InsertLeaf(proxyId);
          return true;
        },
        GetUserData: function(proxyId) {
          b2Assert(0 <= proxyId && proxyId < this.m_nodeCapacity);
          return this.m_nodes[proxyId].userData;
        },
        GetFatAABB: function(proxyId) {
          b2Assert(0 <= proxyId && proxyId < this.m_nodeCapacity);
          return this.m_nodes[proxyId].aabb;
        },
        Query: function(callback, aabb) {
          var stack = [];
          stack.push(this.m_root);
          while (stack.length > 0) {
            var nodeId = stack.pop();
            if (nodeId == b2_nullNode) continue;
            var node = this.m_nodes[nodeId];
            if (b2TestOverlap(node.aabb, aabb)) if (node.IsLeaf()) {
              var proceed = callback.QueryCallback(nodeId);
              if (false == proceed) return;
            } else {
              stack.push(node.child1);
              stack.push(node.child2);
            }
          }
        },
        RayCast: function(callback, input) {
          var p1 = input.p1;
          var p2 = input.p2;
          var r = b2Vec2.Subtract(p2, p1);
          b2Assert(r.LengthSquared() > 0);
          r.Normalize();
          var v = b2Cross_f_v2(1, r);
          var abs_v = b2Abs_v2(v);
          var maxFraction = input.maxFraction;
          var segmentAABB = new b2AABB();
          var t = b2Vec2.Add(p1, b2Vec2.Multiply(maxFraction, b2Vec2.Subtract(p2, p1)));
          segmentAABB.lowerBound.Assign(b2Min_v2(p1, t));
          segmentAABB.upperBound.Assign(b2Max_v2(p1, t));
          var stack = [];
          stack.push(this.m_root);
          while (stack.length > 0) {
            var nodeId = stack.pop();
            if (nodeId == b2_nullNode) continue;
            var node = this.m_nodes[nodeId];
            if (false == b2TestOverlap(node.aabb, segmentAABB)) continue;
            var c = node.aabb.GetCenter();
            var h = node.aabb.GetExtents();
            var separation = b2Abs(b2Dot_v2_v2(v, b2Vec2.Subtract(p1, c))) - b2Dot_v2_v2(abs_v, h);
            if (separation > 0) continue;
            if (node.IsLeaf()) {
              var subInput = new b2RayCastInput();
              subInput.p1.Assign(input.p1);
              subInput.p2.Assign(input.p2);
              subInput.maxFraction = maxFraction;
              var value = callback.RayCastCallback(subInput, nodeId);
              if (0 == value) return;
              if (value > 0) {
                maxFraction = value;
                var t = b2Vec2.Add(p1, b2Vec2.Multiply(maxFraction, b2Vec2.Subtract(p2, p1)));
                segmentAABB.lowerBound.Assign(b2Min_v2(p1, t));
                segmentAABB.upperBound.Assign(b2Max_v2(p1, t));
              }
            } else {
              stack.push(node.child1);
              stack.push(node.child2);
            }
          }
        },
        Validate: function() {
          this.ValidateStructure(this.m_root);
          this.ValidateMetrics(this.m_root);
          var freeCount = 0;
          var freeIndex = this.m_freeList;
          while (freeIndex != b2_nullNode) {
            b2Assert(0 <= freeIndex && freeIndex < this.m_nodeCapacity);
            freeIndex = this.m_nodes[freeIndex].parent;
            ++freeCount;
          }
          b2Assert(this.GetHeight() == this.ComputeHeight());
          b2Assert(this.m_nodeCount + freeCount == this.m_nodeCapacity);
        },
        GetHeight: function() {
          if (this.m_root == b2_nullNode) return 0;
          return this.m_nodes[this.m_root].height;
        },
        GetMaxBalance: function() {
          var maxBalance = 0;
          for (var i = 0; i < this.m_nodeCapacity; ++i) {
            var node = this.m_nodes[i];
            if (node.height <= 1) continue;
            b2Assert(false == node.IsLeaf());
            var child1 = node.child1;
            var child2 = node.child2;
            var balance = b2Abs(this.m_nodes[child2].height - this.m_nodes[child1].height);
            maxBalance = b2Max(maxBalance, balance);
          }
          return maxBalance;
        },
        GetAreaRatio: function() {
          if (this.m_root == b2_nullNode) return 0;
          var root = this.m_nodes[this.m_root];
          var rootArea = root.aabb.GetPerimeter();
          var totalArea = 0;
          for (var i = 0; i < this.m_nodeCapacity; ++i) {
            var node = this.m_nodes[i];
            if (node.height < 0) continue;
            totalArea += node.aabb.GetPerimeter();
          }
          return totalArea / rootArea;
        },
        RebuildBottomUp: function() {
          var nodes = new Array(this.m_nodeCount);
          var count = 0;
          for (var i = 0; i < this.m_nodeCapacity; ++i) {
            if (this.m_nodes[i].height < 0) continue;
            if (this.m_nodes[i].IsLeaf()) {
              this.m_nodes[i].parent = b2_nullNode;
              nodes[count] = i;
              ++count;
            } else this.FreeNode(i);
          }
          while (count > 1) {
            var minCost = b2_maxFloat;
            var iMin = -1, jMin = -1;
            for (i = 0; i < count; ++i) {
              var aabbi = this.m_nodes[nodes[i]].aabb;
              for (var j = i + 1; j < count; ++j) {
                var aabbj = this.m_nodes[nodes[j]].aabb;
                var b = new b2AABB();
                b.Combine(aabbi, aabbj);
                var cost = b.GetPerimeter();
                if (cost < minCost) {
                  iMin = i;
                  jMin = j;
                  minCost = cost;
                }
              }
            }
            var index1 = nodes[iMin];
            var index2 = nodes[jMin];
            var child1 = this.m_nodes[index1];
            var child2 = this.m_nodes[index2];
            var parentIndex = this.AllocateNode();
            var parent = this.m_nodes[parentIndex];
            parent.child1 = index1;
            parent.child2 = index2;
            parent.height = 1 + b2Max(child1.height, child2.height);
            parent.aabb.Combine(child1.aabb, child2.aabb);
            parent.parent = b2_nullNode;
            child1.parent = parentIndex;
            child2.parent = parentIndex;
            nodes[jMin] = nodes[count - 1];
            nodes[iMin] = parentIndex;
            --count;
          }
          this.m_root = nodes[0];
          this.Validate();
        },
        ShiftOrigin: function(newOrigin) {
          for (var i = 0; i < this.m_nodeCapacity; ++i) {
            this.m_nodes[i].aabb.lowerBound.Subtract(newOrigin);
            this.m_nodes[i].aabb.upperBound.Subtract(newOrigin);
          }
        },
        AllocateNode: function() {
          if (this.m_freeList == b2_nullNode) {
            b2Assert(this.m_nodeCount == this.m_nodeCapacity);
            var oldNodes = this.m_nodes;
            this.m_nodeCapacity *= 2;
            this.m_nodes = oldNodes.concat(new Array(this.m_nodeCapacity - this.m_nodeCount));
            for (var i = this.m_nodeCount; i < this.m_nodeCapacity - 1; ++i) {
              this.m_nodes[i] = new b2TreeNode();
              this.m_nodes[i].parent = i + 1;
              this.m_nodes[i].height = -1;
            }
            this.m_nodes[this.m_nodeCapacity - 1] = new b2TreeNode();
            this.m_nodes[this.m_nodeCapacity - 1].parent = b2_nullNode;
            this.m_nodes[this.m_nodeCapacity - 1].height = -1;
            this.m_freeList = this.m_nodeCount;
          }
          var nodeId = this.m_freeList;
          this.m_freeList = this.m_nodes[nodeId].parent;
          this.m_nodes[nodeId].parent = b2_nullNode;
          this.m_nodes[nodeId].child1 = b2_nullNode;
          this.m_nodes[nodeId].child2 = b2_nullNode;
          this.m_nodes[nodeId].height = 0;
          this.m_nodes[nodeId].userData = null;
          ++this.m_nodeCount;
          return nodeId;
        },
        FreeNode: function(nodeId) {
          b2Assert(0 <= nodeId && nodeId < this.m_nodeCapacity);
          b2Assert(0 < this.m_nodeCount);
          this.m_nodes[nodeId].parent = this.m_freeList;
          this.m_nodes[nodeId].height = -1;
          this.m_freeList = nodeId;
          --this.m_nodeCount;
        },
        InsertLeaf: function(leaf) {
          ++this.m_insertionCount;
          if (this.m_root == b2_nullNode) {
            this.m_root = leaf;
            this.m_nodes[this.m_root].parent = b2_nullNode;
            return;
          }
          var leafAABB = this.m_nodes[leaf].aabb;
          var index = this.m_root;
          while (false == this.m_nodes[index].IsLeaf()) {
            var child1 = this.m_nodes[index].child1;
            var child2 = this.m_nodes[index].child2;
            var area = this.m_nodes[index].aabb.GetPerimeter();
            var combinedAABB = new b2AABB();
            combinedAABB.Combine(this.m_nodes[index].aabb, leafAABB);
            var combinedArea = combinedAABB.GetPerimeter();
            var cost = 2 * combinedArea;
            var inheritanceCost = 2 * (combinedArea - area);
            var cost1;
            var aabb;
            if (this.m_nodes[child1].IsLeaf()) {
              aabb = new b2AABB();
              aabb.Combine(leafAABB, this.m_nodes[child1].aabb);
              cost1 = aabb.GetPerimeter() + inheritanceCost;
            } else {
              aabb = new b2AABB();
              aabb.Combine(leafAABB, this.m_nodes[child1].aabb);
              var oldArea = this.m_nodes[child1].aabb.GetPerimeter();
              var newArea = aabb.GetPerimeter();
              cost1 = newArea - oldArea + inheritanceCost;
            }
            var cost2;
            if (this.m_nodes[child2].IsLeaf()) {
              aabb = new b2AABB();
              aabb.Combine(leafAABB, this.m_nodes[child2].aabb);
              cost2 = aabb.GetPerimeter() + inheritanceCost;
            } else {
              aabb = new b2AABB();
              aabb.Combine(leafAABB, this.m_nodes[child2].aabb);
              var oldArea = this.m_nodes[child2].aabb.GetPerimeter();
              var newArea = aabb.GetPerimeter();
              cost2 = newArea - oldArea + inheritanceCost;
            }
            if (cost < cost1 && cost < cost2) break;
            index = cost1 < cost2 ? child1 : child2;
          }
          var sibling = index;
          var oldParent = this.m_nodes[sibling].parent;
          var newParent = this.AllocateNode();
          this.m_nodes[newParent].parent = oldParent;
          this.m_nodes[newParent].userData = null;
          this.m_nodes[newParent].aabb.Combine(leafAABB, this.m_nodes[sibling].aabb);
          this.m_nodes[newParent].height = this.m_nodes[sibling].height + 1;
          if (oldParent != b2_nullNode) {
            this.m_nodes[oldParent].child1 == sibling ? this.m_nodes[oldParent].child1 = newParent : this.m_nodes[oldParent].child2 = newParent;
            this.m_nodes[newParent].child1 = sibling;
            this.m_nodes[newParent].child2 = leaf;
            this.m_nodes[sibling].parent = newParent;
            this.m_nodes[leaf].parent = newParent;
          } else {
            this.m_nodes[newParent].child1 = sibling;
            this.m_nodes[newParent].child2 = leaf;
            this.m_nodes[sibling].parent = newParent;
            this.m_nodes[leaf].parent = newParent;
            this.m_root = newParent;
          }
          index = this.m_nodes[leaf].parent;
          while (index != b2_nullNode) {
            index = this.Balance(index);
            var child1 = this.m_nodes[index].child1;
            var child2 = this.m_nodes[index].child2;
            b2Assert(child1 != b2_nullNode);
            b2Assert(child2 != b2_nullNode);
            this.m_nodes[index].height = 1 + b2Max(this.m_nodes[child1].height, this.m_nodes[child2].height);
            this.m_nodes[index].aabb.Combine(this.m_nodes[child1].aabb, this.m_nodes[child2].aabb);
            index = this.m_nodes[index].parent;
          }
        },
        RemoveLeaf: function(leaf) {
          if (leaf == this.m_root) {
            this.m_root = b2_nullNode;
            return;
          }
          var parent = this.m_nodes[leaf].parent;
          var grandParent = this.m_nodes[parent].parent;
          var sibling;
          sibling = this.m_nodes[parent].child1 == leaf ? this.m_nodes[parent].child2 : this.m_nodes[parent].child1;
          if (grandParent != b2_nullNode) {
            this.m_nodes[grandParent].child1 == parent ? this.m_nodes[grandParent].child1 = sibling : this.m_nodes[grandParent].child2 = sibling;
            this.m_nodes[sibling].parent = grandParent;
            this.FreeNode(parent);
            var index = grandParent;
            while (index != b2_nullNode) {
              index = this.Balance(index);
              var child1 = this.m_nodes[index].child1;
              var child2 = this.m_nodes[index].child2;
              this.m_nodes[index].aabb.Combine(this.m_nodes[child1].aabb, this.m_nodes[child2].aabb);
              this.m_nodes[index].height = 1 + b2Max(this.m_nodes[child1].height, this.m_nodes[child2].height);
              index = this.m_nodes[index].parent;
            }
          } else {
            this.m_root = sibling;
            this.m_nodes[sibling].parent = b2_nullNode;
            this.FreeNode(parent);
          }
        },
        Balance: function(iA) {
          b2Assert(iA != b2_nullNode);
          var A = this.m_nodes[iA];
          if (A.IsLeaf() || A.height < 2) return iA;
          var iB = A.child1;
          var iC = A.child2;
          b2Assert(0 <= iB && iB < this.m_nodeCapacity);
          b2Assert(0 <= iC && iC < this.m_nodeCapacity);
          var B = this.m_nodes[iB];
          var C = this.m_nodes[iC];
          var balance = C.height - B.height;
          if (balance > 1) {
            var iF = C.child1;
            var iG = C.child2;
            var F = this.m_nodes[iF];
            var G = this.m_nodes[iG];
            b2Assert(0 <= iF && iF < this.m_nodeCapacity);
            b2Assert(0 <= iG && iG < this.m_nodeCapacity);
            C.child1 = iA;
            C.parent = A.parent;
            A.parent = iC;
            if (C.parent != b2_nullNode) if (this.m_nodes[C.parent].child1 == iA) this.m_nodes[C.parent].child1 = iC; else {
              b2Assert(this.m_nodes[C.parent].child2 == iA);
              this.m_nodes[C.parent].child2 = iC;
            } else this.m_root = iC;
            if (F.height > G.height) {
              C.child2 = iF;
              A.child2 = iG;
              G.parent = iA;
              A.aabb.Combine(B.aabb, G.aabb);
              C.aabb.Combine(A.aabb, F.aabb);
              A.height = 1 + b2Max(B.height, G.height);
              C.height = 1 + b2Max(A.height, F.height);
            } else {
              C.child2 = iG;
              A.child2 = iF;
              F.parent = iA;
              A.aabb.Combine(B.aabb, F.aabb);
              C.aabb.Combine(A.aabb, G.aabb);
              A.height = 1 + b2Max(B.height, F.height);
              C.height = 1 + b2Max(A.height, G.height);
            }
            return iC;
          }
          if (balance < -1) {
            var iD = B.child1;
            var iE = B.child2;
            var D = this.m_nodes[iD];
            var E = this.m_nodes[iE];
            b2Assert(0 <= iD && iD < this.m_nodeCapacity);
            b2Assert(0 <= iE && iE < this.m_nodeCapacity);
            B.child1 = iA;
            B.parent = A.parent;
            A.parent = iB;
            if (B.parent != b2_nullNode) if (this.m_nodes[B.parent].child1 == iA) this.m_nodes[B.parent].child1 = iB; else {
              b2Assert(this.m_nodes[B.parent].child2 == iA);
              this.m_nodes[B.parent].child2 = iB;
            } else this.m_root = iB;
            if (D.height > E.height) {
              B.child2 = iD;
              A.child1 = iE;
              E.parent = iA;
              A.aabb.Combine(C.aabb, E.aabb);
              B.aabb.Combine(A.aabb, D.aabb);
              A.height = 1 + b2Max(C.height, E.height);
              B.height = 1 + b2Max(A.height, D.height);
            } else {
              B.child2 = iE;
              A.child1 = iD;
              D.parent = iA;
              A.aabb.Combine(C.aabb, D.aabb);
              B.aabb.Combine(A.aabb, E.aabb);
              A.height = 1 + b2Max(C.height, D.height);
              B.height = 1 + b2Max(A.height, E.height);
            }
            return iB;
          }
          return iA;
        },
        ComputeHeight: function(nodeId) {
          "undefined" === typeof nodeId && (nodeId = this.m_root);
          b2Assert(0 <= nodeId && nodeId < this.m_nodeCapacity);
          var node = this.m_nodes[nodeId];
          if (node.IsLeaf()) return 0;
          var height1 = this.ComputeHeight(node.child1);
          var height2 = this.ComputeHeight(node.child2);
          return 1 + b2Max(height1, height2);
        },
        ValidateStructure: function(index) {
          if (index == b2_nullNode) return;
          index == this.m_root && b2Assert(this.m_nodes[index].parent == b2_nullNode);
          var node = this.m_nodes[index];
          var child1 = node.child1;
          var child2 = node.child2;
          if (node.IsLeaf()) {
            b2Assert(child1 == b2_nullNode);
            b2Assert(child2 == b2_nullNode);
            b2Assert(0 == node.height);
            return;
          }
          b2Assert(0 <= child1 && child1 < this.m_nodeCapacity);
          b2Assert(0 <= child2 && child2 < this.m_nodeCapacity);
          b2Assert(this.m_nodes[child1].parent == index);
          b2Assert(this.m_nodes[child2].parent == index);
          this.ValidateStructure(child1);
          this.ValidateStructure(child2);
        },
        ValidateMetrics: function(index) {
          if (index == b2_nullNode) return;
          var node = this.m_nodes[index];
          var child1 = node.child1;
          var child2 = node.child2;
          if (node.IsLeaf()) {
            b2Assert(child1 == b2_nullNode);
            b2Assert(child2 == b2_nullNode);
            b2Assert(0 == node.height);
            return;
          }
          b2Assert(0 <= child1 && child1 < this.m_nodeCapacity);
          b2Assert(0 <= child2 && child2 < this.m_nodeCapacity);
          var height1 = this.m_nodes[child1].height;
          var height2 = this.m_nodes[child2].height;
          var height;
          height = 1 + b2Max(height1, height2);
          b2Assert(node.height == height);
          var aabb = new b2AABB();
          aabb.Combine(this.m_nodes[child1].aabb, this.m_nodes[child2].aabb);
          b2Assert(b2Vec2.Equals(aabb.lowerBound, node.aabb.lowerBound));
          b2Assert(b2Vec2.Equals(aabb.upperBound, node.aabb.upperBound));
          this.ValidateMetrics(child1);
          this.ValidateMetrics(child2);
        }
      };
      function b2TOIInput() {
        this.proxyA = new b2DistanceProxy();
        this.proxyB = new b2DistanceProxy();
        this.sweepA = new b2Sweep();
        this.sweepB = new b2Sweep();
        this.tMax = 0;
      }
      function b2TOIOutput() {
        this.state = 0;
        this.t = 0;
      }
      b2TOIOutput.e_unknown = 0;
      b2TOIOutput.e_failed = 1;
      b2TOIOutput.e_overlapped = 2;
      b2TOIOutput.e_touching = 3;
      b2TOIOutput.e_separated = 4;
      function b2SeparationFunction() {
        this.m_proxyA = null;
        this.m_proxyB = null;
        this.m_sweepA = null;
        this.m_sweepB = null;
        this.m_type = 0;
        this.m_localPoint = new b2Vec2();
        this.m_axis = new b2Vec2();
      }
      var _local_xfA = new b2Transform();
      var _local_xfB = new b2Transform();
      b2SeparationFunction.prototype = {
        Initialize: function(cache, proxyA, sweepA, proxyB, sweepB, t1) {
          this.m_proxyA = proxyA;
          this.m_proxyB = proxyB;
          var count = cache.count;
          b2Assert(0 < count && count < 3);
          this.m_sweepA = sweepA;
          this.m_sweepB = sweepB;
          this.m_sweepA.GetTransform(_local_xfA, t1);
          this.m_sweepB.GetTransform(_local_xfB, t1);
          if (1 == count) {
            this.m_type = b2SeparationFunction.e_points;
            var localPointA = this.m_proxyA.GetVertex(cache.indexA[0]);
            var localPointB = this.m_proxyB.GetVertex(cache.indexB[0]);
            var pointAx = _local_xfA.q.c * localPointA.x - _local_xfA.q.s * localPointA.y + _local_xfA.p.x;
            var pointAy = _local_xfA.q.s * localPointA.x + _local_xfA.q.c * localPointA.y + _local_xfA.p.y;
            var pointBx = _local_xfB.q.c * localPointB.x - _local_xfB.q.s * localPointB.y + _local_xfB.p.x;
            var pointBy = _local_xfB.q.s * localPointB.x + _local_xfB.q.c * localPointB.y + _local_xfB.p.y;
            this.m_axis.x = pointBx - pointAx;
            this.m_axis.y = pointBy - pointAy;
            var s = this.m_axis.Normalize();
            return s;
          }
          if (cache.indexA[0] == cache.indexA[1]) {
            this.m_type = b2SeparationFunction.e_faceB;
            var localPointB1 = proxyB.GetVertex(cache.indexB[0]);
            var localPointB2 = proxyB.GetVertex(cache.indexB[1]);
            this.m_axis.x = 1 * (localPointB2.y - localPointB1.y);
            this.m_axis.y = -1 * (localPointB2.x - localPointB1.x);
            this.m_axis.Normalize();
            var normalx = _local_xfB.q.c * this.m_axis.x - _local_xfB.q.s * this.m_axis.y;
            var normaly = _local_xfB.q.s * this.m_axis.x + _local_xfB.q.c * this.m_axis.y;
            this.m_localPoint.x = .5 * (localPointB1.x + localPointB2.x);
            this.m_localPoint.y = .5 * (localPointB1.y + localPointB2.y);
            var pointBx = _local_xfB.q.c * this.m_localPoint.x - _local_xfB.q.s * this.m_localPoint.y + _local_xfB.p.x;
            var pointBy = _local_xfB.q.s * this.m_localPoint.x + _local_xfB.q.c * this.m_localPoint.y + _local_xfB.p.y;
            var localPointA = proxyA.GetVertex(cache.indexA[0]);
            var pointAx = _local_xfA.q.c * localPointA.x - _local_xfA.q.s * localPointA.y + _local_xfA.p.x;
            var pointAy = _local_xfA.q.s * localPointA.x + _local_xfA.q.c * localPointA.y + _local_xfA.p.y;
            var s = (pointAx - pointBx) * normalx + (pointAy - pointBy) * normaly;
            if (s < 0) {
              this.m_axis.x = -this.m_axis.x;
              this.m_axis.y = -this.m_axis.y;
              s = -s;
            }
            return s;
          }
          this.m_type = b2SeparationFunction.e_faceA;
          var localPointA1 = this.m_proxyA.GetVertex(cache.indexA[0]);
          var localPointA2 = this.m_proxyA.GetVertex(cache.indexA[1]);
          this.m_axis.x = 1 * (localPointA2.y - localPointA1.y);
          this.m_axis.y = -1 * (localPointA2.x - localPointA1.x);
          this.m_axis.Normalize();
          var normalx = _local_xfA.q.c * this.m_axis.x - _local_xfA.q.s * this.m_axis.y;
          var normaly = _local_xfA.q.s * this.m_axis.x + _local_xfA.q.c * this.m_axis.y;
          this.m_localPoint.x = .5 * (localPointA1.x + localPointA2.x);
          this.m_localPoint.y = .5 * (localPointA1.y + localPointA2.y);
          var pointAx = _local_xfA.q.c * this.m_localPoint.x - _local_xfA.q.s * this.m_localPoint.y + _local_xfA.p.x;
          var pointAy = _local_xfA.q.s * this.m_localPoint.x + _local_xfA.q.c * this.m_localPoint.y + _local_xfA.p.y;
          var localPointB = this.m_proxyB.GetVertex(cache.indexB[0]);
          var pointBx = _local_xfB.q.c * localPointB.x - _local_xfB.q.s * localPointB.y + _local_xfB.p.x;
          var pointBy = _local_xfB.q.s * localPointB.x + _local_xfB.q.c * localPointB.y + _local_xfB.p.y;
          var s = (pointBx - pointAx) * normalx + (pointBy - pointAy) * normaly;
          if (s < 0) {
            this.m_axis.x = -this.m_axis.x;
            this.m_axis.y = -this.m_axis.y;
            s = -s;
          }
          return s;
        },
        FindMinSeparation: function(indices, t) {
          this.m_sweepA.GetTransform(_local_xfA, t);
          this.m_sweepB.GetTransform(_local_xfB, t);
          switch (this.m_type) {
           case b2SeparationFunction.e_points:
            var axisAx = _local_xfA.q.c * this.m_axis.x + _local_xfA.q.s * this.m_axis.y;
            var axisAy = -_local_xfA.q.s * this.m_axis.x + _local_xfA.q.c * this.m_axis.y;
            var axisBx = _local_xfB.q.c * -this.m_axis.x + _local_xfB.q.s * -this.m_axis.y;
            var axisBy = -_local_xfB.q.s * -this.m_axis.x + _local_xfB.q.c * -this.m_axis.y;
            indices[0] = this.m_proxyA.GetSupport(axisAx, axisAy);
            indices[1] = this.m_proxyB.GetSupport(axisBx, axisBy);
            var localPointA = this.m_proxyA.GetVertex(indices[0]);
            var localPointB = this.m_proxyB.GetVertex(indices[1]);
            var pointAx = _local_xfA.q.c * localPointA.x - _local_xfA.q.s * localPointA.y + _local_xfA.p.x;
            var pointAy = _local_xfA.q.s * localPointA.x + _local_xfA.q.c * localPointA.y + _local_xfA.p.y;
            var pointBx = _local_xfB.q.c * localPointB.x - _local_xfB.q.s * localPointB.y + _local_xfB.p.x;
            var pointBy = _local_xfB.q.s * localPointB.x + _local_xfB.q.c * localPointB.y + _local_xfB.p.y;
            return (pointBx - pointAx) * this.m_axis.x + (pointBy - pointAy) * this.m_axis.y;

           case b2SeparationFunction.e_faceA:
            var normalx = _local_xfA.q.c * this.m_axis.x - _local_xfA.q.s * this.m_axis.y;
            var normaly = _local_xfA.q.s * this.m_axis.x + _local_xfA.q.c * this.m_axis.y;
            var pointAx = _local_xfA.q.c * this.m_localPoint.x - _local_xfA.q.s * this.m_localPoint.y + _local_xfA.p.x;
            var pointAy = _local_xfA.q.s * this.m_localPoint.x + _local_xfA.q.c * this.m_localPoint.y + _local_xfA.p.y;
            var axisBx = _local_xfB.q.c * -normalx + _local_xfB.q.s * -normaly;
            var axisBy = -_local_xfB.q.s * -normalx + _local_xfB.q.c * -normaly;
            indices[0] = -1;
            indices[1] = this.m_proxyB.GetSupport(axisBx, axisBy);
            var localPointB = this.m_proxyB.GetVertex(indices[1]);
            var pointBx = _local_xfB.q.c * localPointB.x - _local_xfB.q.s * localPointB.y + _local_xfB.p.x;
            var pointBy = _local_xfB.q.s * localPointB.x + _local_xfB.q.c * localPointB.y + _local_xfB.p.y;
            return (pointBx - pointAx) * normalx + (pointBy - pointAy) * normaly;

           case b2SeparationFunction.e_faceB:
            var normalx = _local_xfB.q.c * this.m_axis.x - _local_xfB.q.s * this.m_axis.y;
            var normaly = _local_xfB.q.s * this.m_axis.x + _local_xfB.q.c * this.m_axis.y;
            var pointBx = _local_xfB.q.c * this.m_localPoint.x - _local_xfB.q.s * this.m_localPoint.y + _local_xfB.p.x;
            var pointBy = _local_xfB.q.s * this.m_localPoint.x + _local_xfB.q.c * this.m_localPoint.y + _local_xfB.p.y;
            var axisAx = _local_xfA.q.c * -normalx + _local_xfA.q.s * -normaly;
            var axisBy = -_local_xfA.q.s * -normalx + _local_xfA.q.c * -normaly;
            indices[1] = -1;
            indices[0] = this.m_proxyA.GetSupport(axisAx, axisBy);
            var localPointA = this.m_proxyA.GetVertex(indices[0]);
            var pointAx = _local_xfA.q.c * localPointA.x - _local_xfA.q.s * localPointA.y + _local_xfA.p.x;
            var pointAy = _local_xfA.q.s * localPointA.x + _local_xfA.q.c * localPointA.y + _local_xfA.p.y;
            return (pointAx - pointBx) * normalx + (pointAy - pointBy) * normaly;

           default:
            b2Assert(false);
            indices[0] = -1;
            indices[1] = -1;
            return 0;
          }
        },
        Evaluate: function(indexA, indexB, t) {
          this.m_sweepA.GetTransform(_local_xfA, t);
          this.m_sweepB.GetTransform(_local_xfB, t);
          switch (this.m_type) {
           case b2SeparationFunction.e_points:
            var localPointA = this.m_proxyA.GetVertex(indexA);
            var localPointB = this.m_proxyB.GetVertex(indexB);
            var pointAx = _local_xfA.q.c * localPointA.x - _local_xfA.q.s * localPointA.y + _local_xfA.p.x;
            var pointAy = _local_xfA.q.s * localPointA.x + _local_xfA.q.c * localPointA.y + _local_xfA.p.y;
            var pointBx = _local_xfB.q.c * localPointB.x - _local_xfB.q.s * localPointB.y + _local_xfB.p.x;
            var pointBy = _local_xfB.q.s * localPointB.x + _local_xfB.q.c * localPointB.y + _local_xfB.p.y;
            var separation = (pointBx - pointAx) * this.m_axis.x + (pointBy - pointAy) * this.m_axis.y;
            return separation;

           case b2SeparationFunction.e_faceA:
            var normalx = _local_xfA.q.c * this.m_axis.x - _local_xfA.q.s * this.m_axis.y;
            var normaly = _local_xfA.q.s * this.m_axis.x + _local_xfA.q.c * this.m_axis.y;
            var pointAx = _local_xfA.q.c * this.m_localPoint.x - _local_xfA.q.s * this.m_localPoint.y + _local_xfA.p.x;
            var pointAy = _local_xfA.q.s * this.m_localPoint.x + _local_xfA.q.c * this.m_localPoint.y + _local_xfA.p.y;
            var localPointB = this.m_proxyB.GetVertex(indexB);
            var pointBx = _local_xfB.q.c * localPointB.x - _local_xfB.q.s * localPointB.y + _local_xfB.p.x;
            var pointBy = _local_xfB.q.s * localPointB.x + _local_xfB.q.c * localPointB.y + _local_xfB.p.y;
            var separation = (pointBx - pointAx) * normalx + (pointBy - pointAy) * normaly;
            return separation;

           case b2SeparationFunction.e_faceB:
            var normalx = _local_xfB.q.c * this.m_axis.x - _local_xfB.q.s * this.m_axis.y;
            var normaly = _local_xfB.q.s * this.m_axis.x + _local_xfB.q.c * this.m_axis.y;
            var pointBx = _local_xfB.q.c * this.m_localPoint.x - _local_xfB.q.s * this.m_localPoint.y + _local_xfB.p.x;
            var pointBy = _local_xfB.q.s * this.m_localPoint.x + _local_xfB.q.c * this.m_localPoint.y + _local_xfB.p.y;
            var localPointA = this.m_proxyA.GetVertex(indexA);
            var pointAx = _local_xfA.q.c * localPointA.x - _local_xfA.q.s * localPointA.y + _local_xfA.p.x;
            var pointAy = _local_xfA.q.s * localPointA.x + _local_xfA.q.c * localPointA.y + _local_xfA.p.y;
            var separation = (pointAx - pointBx) * normalx + (pointAy - pointBy) * normaly;
            return separation;

           default:
            b2Assert(false);
            return 0;
          }
        }
      };
      b2SeparationFunction.e_points = 0;
      b2SeparationFunction.e_faceA = 1;
      b2SeparationFunction.e_faceB = 2;
      var profile_toi = b2Profiler.create("toi", "solveTOI");
      function b2TimeOfImpact(output, input) {
        profile_toi.start();
        ++b2TimeOfImpact.b2_toiCalls;
        output.state = b2TOIOutput.e_unknown;
        output.t = input.tMax;
        var proxyA = input.proxyA;
        var proxyB = input.proxyB;
        b2TimeOfImpact._temp_sweepA.Assign(input.sweepA);
        b2TimeOfImpact._temp_sweepB.Assign(input.sweepB);
        b2TimeOfImpact._temp_sweepA.Normalize();
        b2TimeOfImpact._temp_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 = .25 * b2_linearSlop;
        b2Assert(target > tolerance);
        var t1 = 0;
        var k_maxIterations = 20;
        var iter = 0;
        var cache = new b2SimplexCache();
        cache.count = 0;
        var distanceInput = new b2DistanceInput();
        distanceInput.proxyA.Assign(input.proxyA);
        distanceInput.proxyB.Assign(input.proxyB);
        distanceInput.useRadii = false;
        for (;;) {
          b2TimeOfImpact._temp_sweepA.GetTransform(distanceInput.transformA, t1);
          b2TimeOfImpact._temp_sweepB.GetTransform(distanceInput.transformB, t1);
          var distanceOutput = new b2DistanceOutput();
          b2DistanceFunc(distanceOutput, cache, distanceInput);
          if (distanceOutput.distance <= 0) {
            output.state = b2TOIOutput.e_overlapped;
            output.t = 0;
            break;
          }
          if (distanceOutput.distance < target + tolerance) {
            output.state = b2TOIOutput.e_touching;
            output.t = t1;
            break;
          }
          var fcn = new b2SeparationFunction();
          fcn.Initialize(cache, proxyA, b2TimeOfImpact._temp_sweepA, proxyB, b2TimeOfImpact._temp_sweepB, t1);
          var done = false;
          var t2 = tMax;
          var pushBackIter = 0;
          for (;;) {
            var indices = [];
            var s2 = fcn.FindMinSeparation(indices, t2);
            if (s2 > target + tolerance) {
              output.state = b2TOIOutput.e_separated;
              output.t = tMax;
              done = true;
              break;
            }
            if (s2 > target - tolerance) {
              t1 = t2;
              break;
            }
            var s1 = fcn.Evaluate(indices[0], indices[1], t1);
            if (s1 < target - tolerance) {
              output.state = b2TOIOutput.e_failed;
              output.t = t1;
              done = true;
              break;
            }
            if (s1 <= target + tolerance) {
              output.state = b2TOIOutput.e_touching;
              output.t = t1;
              done = true;
              break;
            }
            var rootIterCount = 0;
            var a1 = t1, a2 = t2;
            for (;;) {
              var t;
              t = 1 & rootIterCount ? a1 + (target - s1) * (a2 - a1) / (s2 - s1) : .5 * (a1 + a2);
              ++rootIterCount;
              ++b2TimeOfImpact.b2_toiRootIters;
              var s = fcn.Evaluate(indices[0], indices[1], t);
              if (b2Abs(s - target) < tolerance) {
                t2 = t;
                break;
              }
              if (s > target) {
                a1 = t;
                s1 = s;
              } else {
                a2 = t;
                s2 = s;
              }
              if (50 == rootIterCount) break;
            }
            b2TimeOfImpact.b2_toiMaxRootIters = b2Max(b2TimeOfImpact.b2_toiMaxRootIters, rootIterCount);
            ++pushBackIter;
            if (pushBackIter == b2_maxPolygonVertices) break;
          }
          ++iter;
          ++b2TimeOfImpact.b2_toiIters;
          if (done) break;
          if (iter == k_maxIterations) {
            output.state = b2TOIOutput.e_failed;
            output.t = t1;
            break;
          }
        }
        b2TimeOfImpact.b2_toiMaxIters = b2Max(b2TimeOfImpact.b2_toiMaxIters, iter);
        profile_toi.stop();
        b2TimeOfImpact.b2_toiMaxTime = b2Max(b2TimeOfImpact.b2_toiMaxTime, profile_toi.elapsedTime);
        b2TimeOfImpact.b2_toiTime += profile_toi.elapsedTime;
      }
      b2TimeOfImpact._temp_sweepA = new b2Sweep();
      b2TimeOfImpact._temp_sweepB = new b2Sweep();
      b2TimeOfImpact.b2_toiTime = 0;
      b2TimeOfImpact.b2_toiMaxTime = 0;
      b2TimeOfImpact.b2_toiCalls = 0;
      b2TimeOfImpact.b2_toiIters = 0;
      b2TimeOfImpact.b2_toiMaxIters = 0;
      b2TimeOfImpact.b2_toiRootIters = 0;
      b2TimeOfImpact.b2_toiMaxRootIters = 0;
      function b2BodyDef() {
        this.type = b2Body.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;
        Object.seal(this);
      }
      b2BodyDef.prototype = {
        _deserialize: function(data) {
          this.type = data["type"];
          this.position._deserialize(data["position"]);
          this.angle = data["angle"];
          this.linearVelocity._deserialize(data["linearVelocity"]);
          this.angularVelocity = data["angularVelocity"];
          this.linearDamping = data["linearDamping"];
          this.angularDamping = data["angularDamping"];
          this.allowSleep = data["allowSleep"];
          this.awake = data["awake"];
          this.fixedRotation = data["fixedRotation"];
          this.bullet = data["bullet"];
          this.active = data["active"];
          this.gravityScale = data["gravityScale"];
        }
      };
      function b2Body(bd, world) {
        b2Assert(bd.position.IsValid());
        b2Assert(bd.linearVelocity.IsValid());
        b2Assert(b2IsValid(bd.angle));
        b2Assert(b2IsValid(bd.angularVelocity));
        b2Assert(b2IsValid(bd.angularDamping) && bd.angularDamping >= 0);
        b2Assert(b2IsValid(bd.linearDamping) && bd.linearDamping >= 0);
        this.m_islandIndex = 0;
        this.m_flags = 0;
        bd.bullet && (this.m_flags |= b2Body.e_bulletFlag);
        bd.fixedRotation && (this.m_flags |= b2Body.e_fixedRotationFlag);
        bd.allowSleep && (this.m_flags |= b2Body.e_autoSleepFlag);
        bd.awake && (this.m_flags |= b2Body.e_awakeFlag);
        bd.active && (this.m_flags |= b2Body.e_activeFlag);
        this.m_world = world;
        this.m_xf = new b2Transform();
        this.m_xf.p.Assign(bd.position);
        this.m_xf.q.Set(bd.angle);
        this.m_sweep = new b2Sweep();
        this.m_sweep.localCenter.SetZero();
        this.m_sweep.c0.Assign(this.m_xf.p);
        this.m_sweep.c.Assign(this.m_xf.p);
        this.m_sweep.a0 = bd.angle;
        this.m_sweep.a = bd.angle;
        this.m_sweep.alpha0 = 0;
        this.m_jointList = null;
        this.m_contactList = null;
        this.m_prev = null;
        this.m_next = null;
        this.m_linearVelocity = bd.linearVelocity.Clone();
        this.m_angularVelocity = bd.angularVelocity;
        this.m_linearDamping = bd.linearDamping;
        this.m_angularDamping = bd.angularDamping;
        this.m_gravityScale = bd.gravityScale;
        this.m_force = new b2Vec2();
        this.m_torque = 0;
        this.m_sleepTime = 0;
        this.m_type = bd.type;
        if (this.m_type == b2Body.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;
      }
      b2Body.b2_staticBody = 0;
      b2Body.b2_kinematicBody = 1;
      b2Body.b2_dynamicBody = 2;
      b2Body.e_islandFlag = 1;
      b2Body.e_awakeFlag = 2;
      b2Body.e_autoSleepFlag = 4;
      b2Body.e_bulletFlag = 8;
      b2Body.e_fixedRotationFlag = 16;
      b2Body.e_activeFlag = 32;
      b2Body.e_toiFlag = 64;
      b2Body.m_local_oldCenter = new b2Vec2();
      b2Body.m_local_xf1 = new b2Transform();
      b2Body.prototype = {
        CreateFixture: function(def, density) {
          if ("undefined" !== typeof density) {
            var ndef = new b2FixtureDef();
            ndef.shape = def;
            ndef.density = density;
            return this.CreateFixture(ndef);
          }
          b2Assert(false == this.m_world.IsLocked());
          if (true == this.m_world.IsLocked()) return null;
          var fixture = new b2Fixture();
          fixture.Create(this, def);
          if (this.m_flags & b2Body.e_activeFlag) {
            var broadPhase = this.m_world.m_contactManager.m_broadPhase;
            fixture.CreateProxies(broadPhase, this.m_xf);
          }
          fixture.m_next = this.m_fixtureList;
          this.m_fixtureList = fixture;
          ++this.m_fixtureCount;
          fixture.m_body = this;
          fixture.m_density > 0 && this.ResetMassData();
          this.m_world.m_flags |= b2World.e_newFixture;
          return fixture;
        },
        DestroyFixture: function(fixture) {
          b2Assert(false == this.m_world.IsLocked());
          if (true == this.m_world.IsLocked()) return;
          b2Assert(fixture.m_body == this);
          b2Assert(this.m_fixtureCount > 0);
          var node = this.m_fixtureList;
          var found = false;
          while (null != node) {
            if (node == fixture) {
              this.m_fixtureList = node = fixture.m_next;
              found = true;
              break;
            }
            node = node.m_next;
          }
          b2Assert(found);
          var edge = this.m_contactList;
          while (edge) {
            var c = edge.contact;
            edge = edge.next;
            var fixtureA = c.GetFixtureA();
            var fixtureB = c.GetFixtureB();
            fixture != fixtureA && fixture != fixtureB || this.m_world.m_contactManager.Destroy(c);
          }
          if (this.m_flags & b2Body.e_activeFlag) {
            var broadPhase = this.m_world.m_contactManager.m_broadPhase;
            fixture.DestroyProxies(broadPhase);
          }
          fixture.Destroy();
          fixture.m_body = null;
          fixture.m_next = null;
          --this.m_fixtureCount;
          this.ResetMassData();
        },
        SetTransform: function(position, angle) {
          b2Assert(false == this.m_world.IsLocked());
          if (true == this.m_world.IsLocked()) return;
          this.m_xf.q.Set(angle);
          this.m_xf.p.Assign(position);
          this.m_sweep.c.Assign(b2Mul_t_v2(this.m_xf, this.m_sweep.localCenter));
          this.m_sweep.a = angle;
          this.m_sweep.c0.Assign(this.m_sweep.c);
          this.m_sweep.a0 = angle;
          var broadPhase = this.m_world.m_contactManager.m_broadPhase;
          for (var f = this.m_fixtureList; f; f = f.m_next) f.Synchronize(broadPhase, this.m_xf, this.m_xf);
        },
        GetTransform: function() {
          return this.m_xf;
        },
        GetPosition: function() {
          return this.m_xf.p;
        },
        GetAngle: function() {
          return this.m_sweep.a;
        },
        GetWorldCenter: function() {
          return this.m_sweep.c;
        },
        GetLocalCenter: function() {
          return this.m_sweep.localCenter;
        },
        SetLinearVelocity: function(v) {
          if (this.m_type == b2Body.b2_staticBody) return;
          b2Dot_v2_v2(v, v) > 0 && this.SetAwake(true);
          this.m_linearVelocity = v;
        },
        GetLinearVelocity: function() {
          return this.m_linearVelocity;
        },
        SetAngularVelocity: function(w) {
          if (this.m_type == b2Body.b2_staticBody) return;
          w * w > 0 && this.SetAwake(true);
          this.m_angularVelocity = w;
        },
        GetAngularVelocity: function() {
          return this.m_angularVelocity;
        },
        ApplyForce: function(force, point, wake) {
          if (this.m_type != b2Body.b2_dynamicBody) return;
          wake && 0 == (this.m_flags & b2Body.e_awakeFlag) && this.SetAwake(true);
          if (this.m_flags & b2Body.e_awakeFlag) {
            this.m_force.Add(force);
            this.m_torque += b2Cross_v2_v2(b2Vec2.Subtract(point, this.m_sweep.c), force);
          }
        },
        ApplyForceToCenter: function(force, wake) {
          if (this.m_type != b2Body.b2_dynamicBody) return;
          wake && 0 == (this.m_flags & b2Body.e_awakeFlag) && this.SetAwake(true);
          this.m_flags & b2Body.e_awakeFlag && this.m_force.Add(force);
        },
        ApplyTorque: function(torque, wake) {
          if (this.m_type != b2Body.b2_dynamicBody) return;
          wake && 0 == (this.m_flags & b2Body.e_awakeFlag) && this.SetAwake(true);
          this.m_flags & b2Body.e_awakeFlag && (this.m_torque += torque);
        },
        ApplyLinearImpulse: function(impulse, point, wake) {
          if (this.m_type != b2Body.b2_dynamicBody) return;
          wake && 0 == (this.m_flags & b2Body.e_awakeFlag) && this.SetAwake(true);
          if (this.m_flags & b2Body.e_awakeFlag) {
            this.m_linearVelocity.Add(b2Vec2.Multiply(this.m_invMass, impulse));
            this.m_angularVelocity += this.m_invI * b2Cross_v2_v2(b2Vec2.Subtract(point, this.m_sweep.c), impulse);
          }
        },
        ApplyAngularImpulse: function(impulse, wake) {
          if (this.m_type != b2Body.b2_dynamicBody) return;
          wake && 0 == (this.m_flags & b2Body.e_awakeFlag) && this.SetAwake(true);
          this.m_flags & b2Body.e_awakeFlag && (this.m_angularVelocity += this.m_invI * impulse);
        },
        GetMass: function() {
          return this.m_mass;
        },
        GetInertia: function() {
          return this.m_I + this.m_mass * b2Dot_v2_v2(this.m_sweep.localCenter, this.m_sweep.localCenter);
        },
        GetMassData: function(data) {
          data.mass = this.m_mass;
          data.I = this.m_I + this.m_mass * b2Dot_v2_v2(this.m_sweep.localCenter, this.m_sweep.localCenter);
          data.center = this.m_sweep.localCenter;
        },
        SetMassData: function(massData) {
          b2Assert(false == this.m_world.IsLocked());
          if (true == this.m_world.IsLocked()) return;
          if (this.m_type != b2Body.b2_dynamicBody) return;
          this.m_invMass = 0;
          this.m_I = 0;
          this.m_invI = 0;
          this.m_mass = massData.mass;
          this.m_mass <= 0 && (this.m_mass = 1);
          this.m_invMass = 1 / this.m_mass;
          if (massData.I > 0 && 0 == (this.m_flags & b2Body.e_fixedRotationFlag)) {
            this.m_I = massData.I - this.m_mass * b2Dot_v2_v2(massData.center, massData.center);
            b2Assert(this.m_I > 0);
            this.m_invI = 1 / this.m_I;
          }
          b2Body.m_local_oldCenter.Assign(this.m_sweep.c);
          this.m_sweep.localCenter.Assign(massData.center);
          this.m_sweep.c0.Assign(b2Mul_t_v2(this.m_xf, this.m_sweep.localCenter));
          this.m_sweep.c.Assign(this.m_sweep.c0);
          this.m_linearVelocity.Add(b2Cross_f_v2(this.m_angularVelocity, b2Vec2.Subtract(this.m_sweep.c, b2Body.m_local_oldCenter)));
        },
        ResetMassData: function() {
          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 == b2Body.b2_staticBody || this.m_type == b2Body.b2_kinematicBody) {
            this.m_sweep.c0.Assign(this.m_xf.p);
            this.m_sweep.c.Assign(this.m_xf.p);
            this.m_sweep.a0 = this.m_sweep.a;
            return;
          }
          b2Assert(this.m_type == b2Body.b2_dynamicBody);
          var localCenter = new b2Vec2(0, 0);
          for (var f = this.m_fixtureList; f; f = f.m_next) {
            if (0 == f.m_density) continue;
            var massData = new b2MassData();
            f.GetMassData(massData);
            this.m_mass += massData.mass;
            localCenter.Add(b2Vec2.Multiply(massData.mass, massData.center));
            this.m_I += massData.I;
          }
          if (this.m_mass > 0) {
            this.m_invMass = 1 / this.m_mass;
            localCenter.Multiply(this.m_invMass);
          } else {
            this.m_mass = 1;
            this.m_invMass = 1;
          }
          if (this.m_I > 0 && 0 == (this.m_flags & b2Body.e_fixedRotationFlag)) {
            this.m_I -= this.m_mass * b2Dot_v2_v2(localCenter, localCenter);
            b2Assert(this.m_I > 0);
            this.m_invI = 1 / this.m_I;
          } else {
            this.m_I = 0;
            this.m_invI = 0;
          }
          b2Body.m_local_oldCenter.Assign(this.m_sweep.c);
          this.m_sweep.localCenter.Assign(localCenter);
          this.m_sweep.c0.Assign(b2Mul_t_v2(this.m_xf, this.m_sweep.localCenter));
          this.m_sweep.c.Assign(this.m_sweep.c0);
          this.m_linearVelocity.Add(b2Cross_f_v2(this.m_angularVelocity, b2Vec2.Subtract(this.m_sweep.c, b2Body.m_local_oldCenter)));
        },
        GetWorldPoint: function(localPoint) {
          return b2Mul_t_v2(this.m_xf, localPoint);
        },
        GetWorldVector: function(localVector) {
          return b2Mul_r_v2(this.m_xf.q, localVector);
        },
        GetLocalPoint: function(worldPoint) {
          return b2MulT_t_v2(this.m_xf, worldPoint);
        },
        GetLocalVector: function(worldVector) {
          return b2MulT_r_v2(this.m_xf.q, worldVector);
        },
        GetLinearVelocityFromWorldPoint: function(worldPoint) {
          return b2Vec2.Add(this.m_linearVelocity, b2Cross_f_v2(this.m_angularVelocity, b2Vec2.Subtract(worldPoint, this.m_sweep.c)));
        },
        GetLinearVelocityFromLocalPoint: function(localPoint) {
          return this.GetLinearVelocityFromWorldPoint(this.GetWorldPoint(localPoint));
        },
        GetLinearDamping: function() {
          return this.m_linearDamping;
        },
        SetLinearDamping: function(linearDamping) {
          this.m_linearDamping = linearDamping;
        },
        GetAngularDamping: function() {
          return this.m_angularDamping;
        },
        SetAngularDamping: function(angularDamping) {
          this.m_angularDamping = angularDamping;
        },
        GetGravityScale: function() {
          return this.m_gravityScale;
        },
        SetGravityScale: function(scale) {
          this.m_gravityScale = scale;
        },
        SetType: function(type) {
          b2Assert(false == this.m_world.IsLocked());
          if (true == this.m_world.IsLocked()) return;
          if (this.m_type == type) return;
          this.m_type = type;
          this.ResetMassData();
          if (this.m_type == b2Body.b2_staticBody) {
            this.m_linearVelocity.SetZero();
            this.m_angularVelocity = 0;
            this.m_sweep.a0 = this.m_sweep.a;
            this.m_sweep.c0.Assign(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;
          var broadPhase = this.m_world.m_contactManager.m_broadPhase;
          for (var f = this.m_fixtureList; f; f = f.m_next) {
            var proxyCount = f.m_proxyCount;
            for (var i = 0; i < proxyCount; ++i) broadPhase.TouchProxy(f.m_proxies[i].proxyId);
          }
        },
        GetType: function() {
          return this.m_type;
        },
        SetBullet: function(flag) {
          flag ? this.m_flags |= b2Body.e_bulletFlag : this.m_flags &= ~b2Body.e_bulletFlag;
        },
        IsBullet: function() {
          return (this.m_flags & b2Body.e_bulletFlag) == b2Body.e_bulletFlag;
        },
        SetSleepingAllowed: function(flag) {
          if (flag) this.m_flags |= b2Body.e_autoSleepFlag; else {
            this.m_flags &= ~b2Body.e_autoSleepFlag;
            this.SetAwake(true);
          }
        },
        IsSleepingAllowed: function() {
          return (this.m_flags & b2Body.e_autoSleepFlag) == b2Body.e_autoSleepFlag;
        },
        SetAwake: function(flag) {
          if (flag) {
            if (0 == (this.m_flags & b2Body.e_awakeFlag)) {
              this.m_flags |= b2Body.e_awakeFlag;
              this.m_sleepTime = 0;
            }
          } else {
            this.m_flags &= ~b2Body.e_awakeFlag;
            this.m_sleepTime = 0;
            this.m_linearVelocity.SetZero();
            this.m_angularVelocity = 0;
            this.m_force.SetZero();
            this.m_torque = 0;
          }
        },
        IsAwake: function() {
          return (this.m_flags & b2Body.e_awakeFlag) == b2Body.e_awakeFlag;
        },
        SetActive: function(flag) {
          b2Assert(false == this.m_world.IsLocked());
          if (flag == this.IsActive()) return;
          if (flag) {
            this.m_flags |= b2Body.e_activeFlag;
            var broadPhase = this.m_world.m_contactManager.m_broadPhase;
            for (var f = this.m_fixtureList; f; f = f.m_next) f.CreateProxies(broadPhase, this.m_xf);
          } else {
            this.m_flags &= ~b2Body.e_activeFlag;
            var broadPhase = this.m_world.m_contactManager.m_broadPhase;
            for (var f = this.m_fixtureList; f; f = f.m_next) f.DestroyProxies(broadPhase);
            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;
          }
        },
        IsActive: function() {
          return (this.m_flags & b2Body.e_activeFlag) == b2Body.e_activeFlag;
        },
        SetFixedRotation: function(flag) {
          var status = (this.m_flags & b2Body.e_fixedRotationFlag) == b2Body.e_fixedRotationFlag;
          if (status == flag) return;
          flag ? this.m_flags |= b2Body.e_fixedRotationFlag : this.m_flags &= ~b2Body.e_fixedRotationFlag;
          this.m_angularVelocity = 0;
          this.ResetMassData();
        },
        IsFixedRotation: function() {
          return (this.m_flags & b2Body.e_fixedRotationFlag) == b2Body.e_fixedRotationFlag;
        },
        GetFixtureList: function() {
          return this.m_fixtureList;
        },
        GetJointList: function() {
          return this.m_jointList;
        },
        GetContactList: function() {
          return this.m_contactList;
        },
        GetNext: function() {
          return this.m_next;
        },
        GetUserData: function() {
          return this.m_userData;
        },
        SetUserData: function(data) {
          this.m_userData = data;
        },
        GetWorld: function() {
          return this.m_world;
        },
        SynchronizeFixtures: function() {
          b2Body.m_local_xf1.q.Set(this.m_sweep.a0);
          b2Body.m_local_xf1.p.Assign(b2Vec2.Subtract(this.m_sweep.c0, b2Mul_r_v2(b2Body.m_local_xf1.q, this.m_sweep.localCenter)));
          var broadPhase = this.m_world.m_contactManager.m_broadPhase;
          for (var f = this.m_fixtureList; f; f = f.m_next) f.Synchronize(broadPhase, b2Body.m_local_xf1, this.m_xf);
        },
        SynchronizeTransform: function() {
          this.m_xf.q.Set(this.m_sweep.a);
          this.m_xf.p.Assign(b2Vec2.Subtract(this.m_sweep.c, b2Mul_r_v2(this.m_xf.q, this.m_sweep.localCenter)));
        },
        ShouldCollide: function(other) {
          if (this.m_type != b2Body.b2_dynamicBody && other.m_type != b2Body.b2_dynamicBody) return false;
          for (var jn = this.m_jointList; jn; jn = jn.next) if (jn.other == other && false == jn.joint.m_collideConnected) return false;
          return true;
        },
        Advance: function(alpha) {
          this.m_sweep.Advance(alpha);
          this.m_sweep.c.Assign(this.m_sweep.c0);
          this.m_sweep.a = this.m_sweep.a0;
          this.m_xf.q.Set(this.m_sweep.a);
          this.m_xf.p.Assign(b2Vec2.Subtract(this.m_sweep.c, b2Mul_r_v2(this.m_xf.q, this.m_sweep.localCenter)));
        },
        _serialize: function(out) {
          var obj = out || {};
          obj["fixtures"] = null;
          obj["type"] = this.m_type;
          obj["position"] = this.GetPosition()._serialize();
          obj["angle"] = this.GetAngle();
          obj["linearVelocity"] = this.GetLinearVelocity()._serialize();
          obj["angularVelocity"] = this.GetAngularVelocity();
          obj["linearDamping"] = this.GetLinearDamping();
          obj["angularDamping"] = this.GetAngularDamping();
          obj["allowSleep"] = this.IsSleepingAllowed();
          obj["awake"] = this.IsAwake();
          obj["fixedRotation"] = this.IsFixedRotation();
          obj["bullet"] = this.IsBullet();
          obj["active"] = this.IsActive();
          obj["gravityScale"] = this.GetGravityScale();
          return obj;
        }
      };
      function b2Filter() {
        this.categoryBits = 1;
        this.maskBits = 65535;
        this.groupIndex = 0;
      }
      b2Filter.prototype = {
        Clone: function() {
          var filter = new b2Filter();
          filter.categoryBits = this.categoryBits;
          filter.maskBits = this.maskBits;
          filter.groupIndex = this.groupIndex;
          return filter;
        },
        Assign: function(filter) {
          this.categoryBits = filter.categoryBits;
          this.maskBits = filter.maskBits;
          this.groupIndex = filter.groupIndex;
        },
        _serialize: function(out) {
          var obj = out || {};
          obj["categoryBits"] = this.categoryBits;
          obj["maskBits"] = this.maskBits;
          obj["groupIndex"] = this.groupIndex;
          return obj;
        },
        _deserialize: function(data) {
          this.categoryBits = data["categoryBits"];
          this.maskBits = data["maskBits"];
          this.groupIndex = data["groupIndex"];
        }
      };
      function b2FixtureDef() {
        this.shape = null;
        this.userData = null;
        this.friction = .2;
        this.restitution = 0;
        this.density = 0;
        this.isSensor = false;
        this.filter = new b2Filter();
        Object.seal(this);
      }
      b2FixtureDef.prototype = {
        _deserialize: function(data) {
          this.friction = data["friction"];
          this.restitution = data["restitution"];
          this.density = data["density"];
          this.isSensor = data["isSensor"];
          this.filter._deserialize(data["filter"]);
        }
      };
      function b2FixtureProxy() {
        this.aabb = new b2AABB();
        this.fixture = null;
        this.childIndex = 0;
        this.proxyId = 0;
      }
      function b2Fixture() {
        this.m_userData = null;
        this.m_body = null;
        this.m_next = null;
        this.m_proxies = null;
        this.m_proxyCount = 0;
        this.m_shape = null;
        this.m_density = 0;
        this.m_filter = new b2Filter();
        this.m_isSensor = false;
        this.m_friction = 0;
        this.m_restitution = 0;
      }
      b2Fixture.prototype = {
        GetType: function() {
          return this.m_shape.GetType();
        },
        GetShape: function() {
          return this.m_shape;
        },
        SetSensor: function(sensor) {
          if (sensor != this.m_isSensor) {
            this.m_body.SetAwake(true);
            this.m_isSensor = sensor;
          }
        },
        IsSensor: function() {
          return this.m_isSensor;
        },
        SetFilterData: function(filter) {
          this.m_filter = filter;
          this.Refilter();
        },
        GetFilterData: function() {
          return this.m_filter;
        },
        Refilter: function() {
          if (null == this.m_body) return;
          var edge = this.m_body.GetContactList();
          while (edge) {
            var contact = edge.contact;
            var fixtureA = contact.GetFixtureA();
            var fixtureB = contact.GetFixtureB();
            fixtureA != this && fixtureB != this || contact.FlagForFiltering();
            edge = edge.next;
          }
          var world = this.m_body.GetWorld();
          if (null == world) return;
          var broadPhase = world.m_contactManager.m_broadPhase;
          for (var i = 0; i < this.m_proxyCount; ++i) broadPhase.TouchProxy(this.m_proxies[i].proxyId);
        },
        GetBody: function() {
          return this.m_body;
        },
        GetNext: function() {
          return this.m_next;
        },
        GetUserData: function() {
          return this.m_userData;
        },
        SetUserData: function(data) {
          this.m_userData = data;
        },
        TestPoint: function(p) {
          return this.m_shape.TestPoint(this.m_body.GetTransform(), p);
        },
        RayCast: function(output, input, childIndex) {
          return this.m_shape.RayCast(output, input, this.m_body.GetTransform(), childIndex);
        },
        GetMassData: function(massData) {
          this.m_shape.ComputeMass(massData, this.m_density);
        },
        SetDensity: function(density) {
          b2Assert(b2IsValid(density) && density >= 0);
          this.m_density = density;
        },
        GetDensity: function() {
          return this.m_density;
        },
        GetFriction: function() {
          return this.m_friction;
        },
        SetFriction: function(friction) {
          this.m_friction = friction;
        },
        GetRestitution: function() {
          return this.m_restitution;
        },
        SetRestitution: function(restitution) {
          this.m_restitution = restitution;
        },
        GetAABB: function(childIndex) {
          b2Assert(0 <= childIndex && childIndex < this.m_proxyCount);
          return this.m_proxies[childIndex].aabb;
        },
        Create: function(body, def) {
          this.m_userData = def.userData;
          this.m_friction = def.friction;
          this.m_restitution = def.restitution;
          this.m_body = body;
          this.m_next = null;
          this.m_filter.Assign(def.filter);
          this.m_isSensor = def.isSensor;
          this.m_shape = def.shape.Clone();
          var childCount = this.m_shape.GetChildCount();
          this.m_proxies = new Array(childCount);
          for (var i = 0; i < childCount; ++i) {
            this.m_proxies[i] = new b2FixtureProxy();
            this.m_proxies[i].fixture = null;
            this.m_proxies[i].proxyId = b2BroadPhase.e_nullProxy;
          }
          this.m_proxyCount = 0;
          this.m_density = def.density;
        },
        Destroy: function() {
          b2Assert(0 == this.m_proxyCount);
          this.m_proxies = null;
          this.m_shape = null;
        },
        CreateProxies: function(broadPhase, xf) {
          b2Assert(0 == this.m_proxyCount);
          this.m_proxyCount = this.m_shape.GetChildCount();
          for (var i = 0; i < this.m_proxyCount; ++i) {
            var proxy = this.m_proxies[i];
            this.m_shape.ComputeAABB(proxy.aabb, xf, i);
            proxy.proxyId = broadPhase.CreateProxy(proxy.aabb, proxy);
            proxy.fixture = this;
            proxy.childIndex = i;
          }
        },
        DestroyProxies: function(broadPhase) {
          for (var i = 0; i < this.m_proxyCount; ++i) {
            var proxy = this.m_proxies[i];
            broadPhase.DestroyProxy(proxy.proxyId);
            proxy.proxyId = b2BroadPhase.e_nullProxy;
          }
          this.m_proxyCount = 0;
        },
        Synchronize: function(broadPhase, transform1, transform2) {
          if (0 == this.m_proxyCount) return;
          for (var i = 0; i < this.m_proxyCount; ++i) {
            var proxy = this.m_proxies[i];
            var aabb1 = new b2AABB(), aabb2 = new b2AABB();
            this.m_shape.ComputeAABB(aabb1, transform1, proxy.childIndex);
            this.m_shape.ComputeAABB(aabb2, transform2, proxy.childIndex);
            proxy.aabb.Combine(aabb1, aabb2);
            var displacement = b2Vec2.Subtract(transform2.p, transform1.p);
            broadPhase.MoveProxy(proxy.proxyId, proxy.aabb, displacement);
          }
        },
        _serialize: function(out) {
          var obj = out || {};
          obj["shape"] = null;
          obj["friction"] = this.m_friction;
          obj["restitution"] = this.m_restitution;
          obj["density"] = this.m_density;
          obj["isSensor"] = this.m_isSensor;
          obj["filter"] = this.m_filter._serialize();
          return obj;
        }
      };
      function b2DestructionListener() {}
      b2DestructionListener.prototype = {
        SayGoodbyeJoint: function(joint) {},
        SayGoodbyeFixture: function(fixture) {}
      };
      function b2ContactFilter() {}
      b2ContactFilter.prototype = {
        ShouldCollide: function(fixtureA, fixtureB) {
          var filterA = fixtureA.GetFilterData();
          var filterB = fixtureB.GetFilterData();
          if (filterA.groupIndex == filterB.groupIndex && 0 != filterA.groupIndex) return filterA.groupIndex > 0;
          var collide = 0 != (filterA.maskBits & filterB.categoryBits) && 0 != (filterA.categoryBits & filterB.maskBits);
          return collide;
        }
      };
      function b2ContactImpulse() {
        this.normalImpulses = new Array(b2_maxManifoldPoints);
        this.tangentImpulses = new Array(b2_maxManifoldPoints);
        this.count = 0;
      }
      function b2ContactListener() {}
      b2ContactListener.prototype = {
        BeginContact: function(contact) {},
        EndContact: function(contact) {},
        PreSolve: function(contact, oldManifold) {},
        PostSolve: function(contact, impulse) {}
      };
      function b2QueryCallback() {}
      b2QueryCallback.prototype = {
        ReportFixture: function(fixture) {
          return false;
        }
      };
      function b2RayCastCallback() {}
      b2RayCastCallback.prototype = {
        ReportFixture: function(fixture, point, normal, fraction) {}
      };
      function b2TimeStep() {
        this.dt = 0;
        this.inv_dt = 0;
        this.dtRatio = 0;
        this.velocityIterations = 0;
        this.positionIterations = 0;
        this.warmStarting = false;
      }
      function b2Position() {
        this.c = new b2Vec2();
        this.a = 0;
      }
      function b2Velocity() {
        this.v = new b2Vec2();
        this.w = 0;
      }
      function b2SolverData() {
        this.step = new b2TimeStep();
        this.positions = null;
        this.velocities = null;
      }
      var profile_world_step = b2Profiler.create("step");
      var profile_world_collide = b2Profiler.create("collide", "step");
      var profile_world_solve = b2Profiler.create("solve", "step");
      var profile_world_solveTOI = b2Profiler.create("solveTOI", "step");
      var profile_world_broadphase = b2Profiler.create("broadphase", "step");
      function b2World(gravity) {
        this.m_contactManager = new b2ContactManager();
        this.m_destructionListener = null;
        this.g_debugDraw = null;
        this.m_bodyList = null;
        this.m_jointList = null;
        this.m_bodyCount = 0;
        this.m_jointCount = 0;
        this.m_warmStarting = true;
        this.m_continuousPhysics = true;
        this.m_subStepping = false;
        this.m_stepComplete = true;
        this.m_allowSleep = true;
        this.m_gravity = gravity;
        this.m_flags = b2World.e_clearForces;
        this.m_inv_dt0 = 0;
        this.p_step = new b2TimeStep();
        this.p_island = new b2Island();
      }
      function b2WorldQueryWrapper() {
        this.broadPhase = null;
        this.callback = null;
      }
      b2WorldQueryWrapper.prototype = {
        QueryCallback: function(proxyId) {
          var proxy = this.broadPhase.GetUserData(proxyId);
          return this.callback.ReportFixture(proxy.fixture);
        }
      };
      function b2WorldRayCastWrapper() {
        this.broadPhase = null;
        this.callback = null;
      }
      b2WorldRayCastWrapper.prototype = {
        RayCastCallback: function(input, proxyId) {
          var userData = this.broadPhase.GetUserData(proxyId);
          var proxy = userData;
          var fixture = proxy.fixture;
          var index = proxy.childIndex;
          var output = new b2RayCastOutput();
          var hit = fixture.RayCast(output, input, index);
          if (hit) {
            var fraction = output.fraction;
            var point = b2Vec2.Add(b2Vec2.Multiply(1 - fraction, input.p1), b2Vec2.Multiply(fraction, input.p2));
            return this.callback.ReportFixture(fixture, point, output.normal, fraction);
          }
          return input.maxFraction;
        }
      };
      b2World.m_local_sweep_backupA = new b2Sweep();
      b2World.m_local_sweep_backupB = new b2Sweep();
      b2World.m_local_sweep_backupC = new b2Sweep();
      b2World.prototype = {
        Destroy: function() {
          var b = this.m_bodyList;
          while (b) {
            var bNext = b.m_next;
            var f = b.m_fixtureList;
            while (f) {
              var fNext = f.m_next;
              f.m_proxyCount = 0;
              f.Destroy();
              f = fNext;
            }
            b = bNext;
          }
        },
        SetDestructionListener: function(listener) {
          this.m_destructionListener = listener;
        },
        SetContactFilter: function(filter) {
          this.m_contactManager.m_contactFilter = filter;
        },
        SetContactListener: function(listener) {
          this.m_contactManager.m_contactListener = listener;
        },
        SetDebugDraw: function(debugDraw) {
          this.g_debugDraw = debugDraw;
        },
        CreateBody: function(def) {
          b2Assert(false == this.IsLocked());
          if (this.IsLocked()) return null;
          var b = new b2Body(def, this);
          b.m_prev = null;
          b.m_next = this.m_bodyList;
          this.m_bodyList && (this.m_bodyList.m_prev = b);
          this.m_bodyList = b;
          ++this.m_bodyCount;
          return b;
        },
        DestroyBody: function(b) {
          b2Assert(this.m_bodyCount > 0);
          b2Assert(false == this.IsLocked());
          if (this.IsLocked()) return;
          var je = b.m_jointList;
          while (je) {
            var je0 = je;
            je = je.next;
            this.m_destructionListener && this.m_destructionListener.SayGoodbyeJoint(je0.joint);
            this.DestroyJoint(je0.joint);
            b.m_jointList = je;
          }
          b.m_jointList = null;
          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;
            this.m_destructionListener && this.m_destructionListener.SayGoodbyeFixture(f0);
            f0.DestroyProxies(this.m_contactManager.m_broadPhase);
            f0.Destroy();
            b.m_fixtureList = f;
            b.m_fixtureCount -= 1;
          }
          b.m_fixtureList = null;
          b.m_fixtureCount = 0;
          b.m_prev && (b.m_prev.m_next = b.m_next);
          b.m_next && (b.m_next.m_prev = b.m_prev);
          b == this.m_bodyList && (this.m_bodyList = b.m_next);
          b.m_destroyed = true;
          --this.m_bodyCount;
        },
        CreateJoint: function(def) {
          b2Assert(false == this.IsLocked());
          if (this.IsLocked()) return null;
          var j = b2Joint.Create(def);
          j.m_prev = null;
          j.m_next = this.m_jointList;
          this.m_jointList && (this.m_jointList.m_prev = j);
          this.m_jointList = j;
          ++this.m_jointCount;
          j.m_edgeA.joint = j;
          j.m_edgeA.other = j.m_bodyB;
          j.m_edgeA.prev = null;
          j.m_edgeA.next = j.m_bodyA.m_jointList;
          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.joint = j;
          j.m_edgeB.other = j.m_bodyA;
          j.m_edgeB.prev = null;
          j.m_edgeB.next = j.m_bodyB.m_jointList;
          j.m_bodyB.m_jointList && (j.m_bodyB.m_jointList.prev = j.m_edgeB);
          j.m_bodyB.m_jointList = j.m_edgeB;
          var bodyA = def.bodyA;
          var bodyB = def.bodyB;
          if (false == def.collideConnected) {
            var edge = bodyB.GetContactList();
            while (edge) {
              edge.other == bodyA && edge.contact.FlagForFiltering();
              edge = edge.next;
            }
          }
          return j;
        },
        DestroyJoint: function(j) {
          b2Assert(false == this.IsLocked());
          if (this.IsLocked()) return;
          var collideConnected = j.m_collideConnected;
          j.m_prev && (j.m_prev.m_next = j.m_next);
          j.m_next && (j.m_next.m_prev = j.m_prev);
          j == this.m_jointList && (this.m_jointList = j.m_next);
          var bodyA = j.m_bodyA;
          var bodyB = j.m_bodyB;
          bodyA.SetAwake(true);
          bodyB.SetAwake(true);
          j.m_edgeA.prev && (j.m_edgeA.prev.next = j.m_edgeA.next);
          j.m_edgeA.next && (j.m_edgeA.next.prev = j.m_edgeA.prev);
          j.m_edgeA == bodyA.m_jointList && (bodyA.m_jointList = j.m_edgeA.next);
          j.m_edgeA.prev = null;
          j.m_edgeA.next = null;
          j.m_edgeB.prev && (j.m_edgeB.prev.next = j.m_edgeB.next);
          j.m_edgeB.next && (j.m_edgeB.next.prev = j.m_edgeB.prev);
          j.m_edgeB == bodyB.m_jointList && (bodyB.m_jointList = j.m_edgeB.next);
          j.m_edgeB.prev = null;
          j.m_edgeB.next = null;
          b2Joint.Destroy(j);
          b2Assert(this.m_jointCount > 0);
          --this.m_jointCount;
          if (false == collideConnected) {
            var edge = bodyB.GetContactList();
            while (edge) {
              edge.other == bodyA && edge.contact.FlagForFiltering();
              edge = edge.next;
            }
          }
        },
        Step: function(dt, velocityIterations, positionIterations) {
          profile_world_step.start();
          if (this.m_flags & b2World.e_newFixture) {
            this.m_contactManager.FindNewContacts();
            this.m_flags &= ~b2World.e_newFixture;
          }
          this.m_flags |= b2World.e_locked;
          this.p_step.dt = dt;
          this.p_step.velocityIterations = velocityIterations;
          this.p_step.positionIterations = positionIterations;
          this.p_step.inv_dt = dt > 0 ? 1 / dt : 0;
          this.p_step.dtRatio = this.m_inv_dt0 * dt;
          this.p_step.warmStarting = this.m_warmStarting;
          profile_world_collide.start();
          this.m_contactManager.Collide();
          profile_world_collide.stop();
          if (this.m_stepComplete && this.p_step.dt > 0) {
            profile_world_solve.start();
            this.Solve(this.p_step);
            profile_world_solve.stop();
          }
          if (this.m_continuousPhysics && this.p_step.dt > 0) {
            profile_world_solveTOI.start();
            this.SolveTOI(this.p_step);
            profile_world_solveTOI.stop();
          }
          this.p_step.dt > 0 && (this.m_inv_dt0 = this.p_step.inv_dt);
          this.m_flags & b2World.e_clearForces && this.ClearForces();
          this.m_flags &= ~b2World.e_locked;
          profile_world_step.stop();
        },
        ClearForces: function() {
          for (var body = this.m_bodyList; body; body = body.GetNext()) {
            body.m_force.x = body.m_force.y = 0;
            body.m_torque = 0;
          }
        },
        DrawDebugData: function() {
          if (null == this.g_debugDraw) return;
          this.g_debugDraw.ClearDraw();
          var flags = this.g_debugDraw.GetFlags();
          if (flags & b2Draw.e_shapeBit) for (var b = this.m_bodyList; b; b = b.GetNext()) {
            var xf = b.GetTransform();
            for (var f = b.GetFixtureList(); f; f = f.GetNext()) false == b.IsActive() ? this.DrawShape(f, xf, new b2Color(.5, .5, .3)) : b.GetType() == b2Body.b2_staticBody ? this.DrawShape(f, xf, new b2Color(.5, .9, .5)) : b.GetType() == b2Body.b2_kinematicBody ? this.DrawShape(f, xf, new b2Color(.5, .5, .9)) : false == b.IsAwake() ? this.DrawShape(f, xf, new b2Color(.6, .6, .6)) : this.DrawShape(f, xf, new b2Color(.9, .7, .7));
          }
          if (flags & b2Draw.e_jointBit) for (var j = this.m_jointList; j; j = j.GetNext()) this.DrawJoint(j);
          if (flags & b2Draw.e_pairBit) {
            var color = new b2Color(.3, .9, .9);
            for (var c = this.m_contactManager.m_contactList; c; c = c.GetNext()) {
              var fixtureA = c.GetFixtureA();
              var fixtureB = c.GetFixtureB();
              var cA = fixtureA.GetAABB(c.GetChildIndexA()).GetCenter();
              var cB = fixtureB.GetAABB(c.GetChildIndexB()).GetCenter();
              this.g_debugDraw.DrawSegment(cA, cB, color);
            }
          }
          if (flags & b2Draw.e_aabbBit) {
            var color = new b2Color(.9, .3, .9);
            var color2 = new b2Color(.3, .3, .9);
            var bp = this.m_contactManager.m_broadPhase;
            for (var b = this.m_bodyList; b; b = b.GetNext()) {
              if (false == b.IsActive()) continue;
              for (var f = b.GetFixtureList(); f; f = f.GetNext()) for (var i = 0; i < f.m_proxyCount; ++i) {
                var proxy = f.m_proxies[i];
                var aabb = bp.GetFatAABB(proxy.proxyId);
                var vs = [];
                vs[0] = new b2Vec2(aabb.lowerBound.x, aabb.lowerBound.y);
                vs[1] = new b2Vec2(aabb.upperBound.x, aabb.lowerBound.y);
                vs[2] = new b2Vec2(aabb.upperBound.x, aabb.upperBound.y);
                vs[3] = new b2Vec2(aabb.lowerBound.x, aabb.upperBound.y);
                this.g_debugDraw.DrawPolygon(vs, 4, color);
                var realAABB = new b2AABB();
                f.GetShape().ComputeAABB(realAABB, b.GetTransform(), 0);
                var vs = [];
                vs[0] = new b2Vec2(realAABB.lowerBound.x, realAABB.lowerBound.y);
                vs[1] = new b2Vec2(realAABB.upperBound.x, realAABB.lowerBound.y);
                vs[2] = new b2Vec2(realAABB.upperBound.x, realAABB.upperBound.y);
                vs[3] = new b2Vec2(realAABB.lowerBound.x, realAABB.upperBound.y);
                this.g_debugDraw.DrawPolygon(vs, 4, color2);
              }
            }
          }
          if (flags & b2Draw.e_centerOfMassBit) for (var b = this.m_bodyList; b; b = b.GetNext()) {
            var xf = b.GetTransform().Clone();
            xf.p = b.GetWorldCenter();
            this.g_debugDraw.DrawTransform(xf);
          }
        },
        QueryAABB: function(callback, aabb) {
          var wrapper = new b2WorldQueryWrapper();
          wrapper.broadPhase = this.m_contactManager.m_broadPhase;
          wrapper.callback = callback;
          this.m_contactManager.m_broadPhase.Query(wrapper, aabb);
        },
        RayCast: function(callback, point1, point2) {
          var wrapper = new b2WorldRayCastWrapper();
          wrapper.broadPhase = this.m_contactManager.m_broadPhase;
          wrapper.callback = callback;
          var input = new b2RayCastInput();
          input.maxFraction = 1;
          input.p1 = point1;
          input.p2 = point2;
          this.m_contactManager.m_broadPhase.RayCast(wrapper, input);
        },
        GetBodyList: function() {
          return this.m_bodyList;
        },
        GetJointList: function() {
          return this.m_jointList;
        },
        GetContactList: function() {
          return this.m_contactManager.m_contactList;
        },
        SetAllowSleeping: function(flag) {
          if (flag == this.m_allowSleep) return;
          this.m_allowSleep = flag;
          if (false == this.m_allowSleep) for (var b = this.m_bodyList; b; b = b.m_next) b.SetAwake(true);
        },
        GetAllowSleeping: function() {
          return this.m_allowSleep;
        },
        SetWarmStarting: function(flag) {
          this.m_warmStarting = flag;
        },
        GetWarmStarting: function() {
          return this.m_warmStarting;
        },
        SetContinuousPhysics: function(flag) {
          this.m_continuousPhysics = flag;
        },
        GetContinuousPhysics: function() {
          return this.m_continuousPhysics;
        },
        SetSubStepping: function(flag) {
          this.m_subStepping = flag;
        },
        GetSubStepping: function() {
          return this.m_subStepping;
        },
        GetProxyCount: function() {
          return this.m_contactManager.m_broadPhase.GetProxyCount();
        },
        GetBodyCount: function() {
          return this.m_bodyCount;
        },
        GetJointCount: function() {
          return this.m_jointCount;
        },
        GetContactCount: function() {
          return this.m_contactManager.m_contactCount;
        },
        GetTreeHeight: function() {
          return this.m_contactManager.m_broadPhase.GetTreeHeight();
        },
        GetTreeBalance: function() {
          return this.m_contactManager.m_broadPhase.GetTreeBalance();
        },
        GetTreeQuality: function() {
          return this.m_contactManager.m_broadPhase.GetTreeQuality();
        },
        SetGravity: function(gravity) {
          this.m_gravity = gravity;
        },
        GetGravity: function() {
          return this.m_gravity;
        },
        IsLocked: function() {
          return (this.m_flags & b2World.e_locked) == b2World.e_locked;
        },
        SetAutoClearForces: function(flag) {
          flag ? this.m_flags |= b2World.e_clearForces : this.m_flags &= ~b2World.e_clearForces;
        },
        GetAutoClearForces: function() {
          return (this.m_flags & b2World.e_clearForces) == b2World.e_clearForces;
        },
        ShiftOrigin: function(newOrigin) {
          b2Assert(0 == (this.m_flags & b2World.e_locked));
          if ((this.m_flags & b2World.e_locked) == b2World.e_locked) return;
          for (var b = this.m_bodyList; b; b = b.m_next) {
            b.m_xf.p.Subtract(newOrigin);
            b.m_sweep.c0.Subtract(newOrigin);
            b.m_sweep.c.Subtract(newOrigin);
          }
          for (var j = this.m_jointList; j; j = j.m_next) j.ShiftOrigin(newOrigin);
          this.m_contactManager.m_broadPhase.ShiftOrigin(newOrigin);
        },
        GetContactManager: function() {
          return this.m_contactManager;
        },
        Solve: function(step) {
          this.p_island.Initialize(this.m_bodyCount, this.m_contactManager.m_contactCount, this.m_jointCount, this.m_contactManager.m_contactListener);
          for (var b = this.m_bodyList; b; b = b.m_next) b.m_flags &= ~b2Body.e_islandFlag;
          for (var c = this.m_contactManager.m_contactList; c; c = c.m_next) c.m_flags &= ~b2Contact.e_islandFlag;
          for (var j = this.m_jointList; j; j = j.m_next) j.m_islandFlag = false;
          var stackSize = this.m_bodyCount;
          var stack = new Array(stackSize);
          for (var seed = this.m_bodyList; seed; seed = seed.m_next) {
            if (seed.m_flags & b2Body.e_islandFlag) continue;
            if (false == seed.IsAwake() || false == seed.IsActive()) continue;
            if (seed.GetType() == b2Body.b2_staticBody) continue;
            this.p_island.Clear();
            var stackCount = 0;
            stack[stackCount++] = seed;
            seed.m_flags |= b2Body.e_islandFlag;
            while (stackCount > 0) {
              var b = stack[--stackCount];
              b2Assert(true == b.IsActive());
              this.p_island.AddBody(b);
              b.SetAwake(true);
              if (b.GetType() == b2Body.b2_staticBody) continue;
              for (var ce = b.m_contactList; ce; ce = ce.next) {
                var contact = ce.contact;
                if (contact.m_flags & b2Contact.e_islandFlag) continue;
                if (false == contact.IsEnabled() || false == contact.IsTouching()) continue;
                var sensorA = contact.m_fixtureA.m_isSensor;
                var sensorB = contact.m_fixtureB.m_isSensor;
                if (sensorA || sensorB) continue;
                this.p_island.AddContact(contact);
                contact.m_flags |= b2Contact.e_islandFlag;
                var other = ce.other;
                if (other.m_flags & b2Body.e_islandFlag) continue;
                b2Assert(stackCount < stackSize);
                stack[stackCount++] = other;
                other.m_flags |= b2Body.e_islandFlag;
              }
              for (var je = b.m_jointList; je; je = je.next) {
                if (true == je.joint.m_islandFlag) continue;
                var other = je.other;
                if (false == other.IsActive()) continue;
                this.p_island.AddJoint(je.joint);
                je.joint.m_islandFlag = true;
                if (other.m_flags & b2Body.e_islandFlag) continue;
                b2Assert(stackCount < stackSize);
                stack[stackCount++] = other;
                other.m_flags |= b2Body.e_islandFlag;
              }
            }
            this.p_island.Solve(step, this.m_gravity, this.m_allowSleep);
            for (var i = 0; i < this.p_island.m_bodyCount; ++i) {
              var b = this.p_island.m_bodies[i];
              b.GetType() == b2Body.b2_staticBody && (b.m_flags &= ~b2Body.e_islandFlag);
            }
          }
          profile_world_broadphase.start();
          for (var b = this.m_bodyList; b; b = b.GetNext()) {
            if (0 == (b.m_flags & b2Body.e_islandFlag)) continue;
            if (b.GetType() == b2Body.b2_staticBody) continue;
            b.SynchronizeFixtures();
          }
          this.m_contactManager.FindNewContacts();
          profile_world_broadphase.stop();
        },
        SolveTOI: function(step) {
          this.p_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_flags &= ~b2Body.e_islandFlag;
              b.m_sweep.alpha0 = 0;
            }
            for (var c = this.m_contactManager.m_contactList; c; c = c.m_next) {
              c.m_flags &= ~(b2Contact.e_toiFlag | b2Contact.e_islandFlag);
              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 (false == c.IsEnabled()) continue;
              if (c.m_toiCount > b2_maxSubSteps) continue;
              var alpha = 1;
              if (c.m_flags & b2Contact.e_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;
                b2Assert(typeA == b2Body.b2_dynamicBody || typeB == b2Body.b2_dynamicBody);
                var activeA = bA.IsAwake() && typeA != b2Body.b2_staticBody;
                var activeB = bB.IsAwake() && typeB != b2Body.b2_staticBody;
                if (false == activeA && false == activeB) continue;
                var collideA = bA.IsBullet() || typeA != b2Body.b2_dynamicBody;
                var collideB = bB.IsBullet() || typeB != b2Body.b2_dynamicBody;
                if (false == collideA && false == 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);
                }
                b2Assert(alpha0 < 1);
                var indexA = c.GetChildIndexA();
                var indexB = c.GetChildIndexB();
                var input = new b2TOIInput();
                input.proxyA.Set(fA.GetShape(), indexA);
                input.proxyB.Set(fB.GetShape(), indexB);
                input.sweepA.Assign(bA.m_sweep);
                input.sweepB.Assign(bB.m_sweep);
                input.tMax = 1;
                var output = new b2TOIOutput();
                b2TimeOfImpact(output, input);
                var beta = output.t;
                alpha = output.state == b2TOIOutput.e_touching ? b2Min(alpha0 + (1 - alpha0) * beta, 1) : 1;
                c.m_toi = alpha;
                c.m_flags |= b2Contact.e_toiFlag;
              }
              if (alpha < minAlpha) {
                minContact = c;
                minAlpha = alpha;
              }
            }
            if (null == minContact || 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();
            b2World.m_local_sweep_backupA.Assign(bA.m_sweep);
            b2World.m_local_sweep_backupB.Assign(bB.m_sweep);
            bA.Advance(minAlpha);
            bB.Advance(minAlpha);
            minContact.Update(this.m_contactManager.m_contactListener);
            minContact.m_flags &= ~b2Contact.e_toiFlag;
            ++minContact.m_toiCount;
            if (false == minContact.IsEnabled() || false == minContact.IsTouching()) {
              minContact.SetEnabled(false);
              bA.m_sweep.Assign(b2World.m_local_sweep_backupA);
              bB.m_sweep.Assign(b2World.m_local_sweep_backupB);
              bA.SynchronizeTransform();
              bB.SynchronizeTransform();
              continue;
            }
            bA.SetAwake(true);
            bB.SetAwake(true);
            this.p_island.Clear();
            this.p_island.AddBody(bA);
            this.p_island.AddBody(bB);
            this.p_island.AddContact(minContact);
            bA.m_flags |= b2Body.e_islandFlag;
            bB.m_flags |= b2Body.e_islandFlag;
            minContact.m_flags |= b2Contact.e_islandFlag;
            var bodies = [ bA, bB ];
            for (var i = 0; i < 2; ++i) {
              var body = bodies[i];
              if (body.m_type == b2Body.b2_dynamicBody) for (var ce = body.m_contactList; ce; ce = ce.next) {
                if (this.p_island.m_bodyCount == this.p_island.m_bodyCapacity) break;
                if (this.p_island.m_contactCount == this.p_island.m_contactCapacity) break;
                var contact = ce.contact;
                if (contact.m_flags & b2Contact.e_islandFlag) continue;
                var other = ce.other;
                if (other.m_type == b2Body.b2_dynamicBody && false == body.IsBullet() && false == other.IsBullet()) continue;
                var sensorA = contact.m_fixtureA.m_isSensor;
                var sensorB = contact.m_fixtureB.m_isSensor;
                if (sensorA || sensorB) continue;
                b2World.m_local_sweep_backupC.Assign(other.m_sweep);
                0 == (other.m_flags & b2Body.e_islandFlag) && other.Advance(minAlpha);
                contact.Update(this.m_contactManager.m_contactListener);
                if (false == contact.IsEnabled()) {
                  other.m_sweep.Assign(b2World.m_local_sweep_backupC);
                  other.SynchronizeTransform();
                  continue;
                }
                if (false == contact.IsTouching()) {
                  other.m_sweep.Assign(b2World.m_local_sweep_backupC);
                  other.SynchronizeTransform();
                  continue;
                }
                contact.m_flags |= b2Contact.e_islandFlag;
                this.p_island.AddContact(contact);
                if (other.m_flags & b2Body.e_islandFlag) continue;
                other.m_flags |= b2Body.e_islandFlag;
                other.m_type != b2Body.b2_staticBody && other.SetAwake(true);
                this.p_island.AddBody(other);
              }
            }
            var subStep = new b2TimeStep();
            subStep.dt = (1 - minAlpha) * step.dt;
            subStep.inv_dt = 1 / subStep.dt;
            subStep.dtRatio = 1;
            subStep.positionIterations = 20;
            subStep.velocityIterations = step.velocityIterations;
            subStep.warmStarting = false;
            this.p_island.SolveTOI(subStep, bA.m_islandIndex, bB.m_islandIndex);
            for (var i = 0; i < this.p_island.m_bodyCount; ++i) {
              var body = this.p_island.m_bodies[i];
              body.m_flags &= ~b2Body.e_islandFlag;
              if (body.m_type != b2Body.b2_dynamicBody) continue;
              body.SynchronizeFixtures();
              for (var ce = body.m_contactList; ce; ce = ce.next) ce.contact.m_flags &= ~(b2Contact.e_toiFlag | b2Contact.e_islandFlag);
            }
            this.m_contactManager.FindNewContacts();
            if (this.m_subStepping) {
              this.m_stepComplete = false;
              break;
            }
          }
        },
        DrawJoint: function(joint) {
          var bodyA = joint.GetBodyA();
          var bodyB = joint.GetBodyB();
          var xf1 = bodyA.GetTransform();
          var xf2 = bodyB.GetTransform();
          var x1 = xf1.p;
          var x2 = xf2.p;
          var p1 = joint.GetAnchorA();
          var p2 = joint.GetAnchorB();
          var color = new b2Color(.5, .8, .8);
          switch (joint.GetType()) {
           case b2Joint.e_distanceJoint:
            this.g_debugDraw.DrawSegment(p1, p2, color);
            break;

           case b2Joint.e_pulleyJoint:
            var pulley = joint;
            var s1 = pulley.GetGroundAnchorA();
            var s2 = pulley.GetGroundAnchorB();
            this.g_debugDraw.DrawSegment(s1, p1, color);
            this.g_debugDraw.DrawSegment(s2, p2, color);
            this.g_debugDraw.DrawSegment(s1, s2, color);
            break;

           case b2Joint.e_mouseJoint:
            break;

           case b2Joint.e_motorJoint:
            this.g_debugDraw.DrawPoint(joint.GetLinearOffset(), 5, color);

           default:
            this.g_debugDraw.DrawSegment(x1, p1, color);
            this.g_debugDraw.DrawSegment(p1, p2, color);
            this.g_debugDraw.DrawSegment(x2, p2, color);
          }
        },
        DrawShape: function(fixture, xf, color) {
          switch (fixture.GetType()) {
           case b2Shape.e_circle:
            var circle = fixture.GetShape();
            var center = b2Mul_t_v2(xf, circle.m_p);
            var radius = circle.m_radius;
            var axis = b2Mul_r_v2(xf.q, new b2Vec2(1, 0));
            this.g_debugDraw.DrawSolidCircle(center, radius, axis, color);
            break;

           case b2Shape.e_edge:
            var edge = fixture.GetShape();
            var v1 = b2Mul_t_v2(xf, edge.m_vertex1);
            var v2 = b2Mul_t_v2(xf, edge.m_vertex2);
            this.g_debugDraw.DrawSegment(v1, v2, color);
            break;

           case b2Shape.e_chain:
            var chain = fixture.GetShape();
            var count = chain.m_count;
            var vertices = chain.m_vertices;
            var v1 = b2Mul_t_v2(xf, vertices[0]);
            for (var i = 1; i < count; ++i) {
              var v2 = b2Mul_t_v2(xf, vertices[i]);
              this.g_debugDraw.DrawSegment(v1, v2, color);
              v1 = v2;
            }
            break;

           case b2Shape.e_polygon:
            var poly = fixture.GetShape();
            var vertexCount = poly.m_count;
            b2Assert(vertexCount <= b2_maxPolygonVertices);
            var vertices = new Array(b2_maxPolygonVertices);
            for (var i = 0; i < vertexCount; ++i) vertices[i] = b2Mul_t_v2(xf, poly.m_vertices[i]);
            this.g_debugDraw.DrawSolidPolygon(vertices, vertexCount, color);
          }
        }
      };
      b2World.e_newFixture = 1;
      b2World.e_locked = 2;
      b2World.e_clearForces = 4;
      function b2MixFriction(friction1, friction2) {
        return b2Sqrt(friction1 * friction2);
      }
      function b2MixRestitution(restitution1, restitution2) {
        return restitution1 > restitution2 ? restitution1 : restitution2;
      }
      function b2ContactRegister() {
        this.fcn = null;
        this.primary = false;
      }
      function b2ContactEdge() {
        this.other = null;
        this.contact = null;
        this.prev = null;
        this.next = null;
      }
      b2ContactEdge.prototype = {
        Clear: function() {
          this.other = this.prev = this.next = null;
        }
      };
      function b2Contact() {
        this.m_nodeA = new b2ContactEdge();
        this.m_nodeB = new b2ContactEdge();
        this.m_manifold = new b2Manifold();
      }
      b2Contact.m_local_tempManifold = new b2Manifold();
      b2Contact.prototype = {
        Create: function(fA, indexA, fB, indexB) {
          this.m_toi = 0;
          this.m_flags = b2Contact.e_enabledFlag;
          this.m_fixtureA = fA || null;
          this.m_fixtureB = fB || null;
          this.m_indexA = indexA || 0;
          this.m_indexB = indexB || 0;
          this.m_manifold.pointCount = 0;
          this.m_prev = null;
          this.m_next = null;
          this.m_nodeA.contact = null;
          this.m_nodeA.prev = null;
          this.m_nodeA.next = null;
          this.m_nodeA.other = null;
          this.m_nodeB.contact = null;
          this.m_nodeB.prev = null;
          this.m_nodeB.next = null;
          this.m_nodeB.other = null;
          this.m_toiCount = 0;
          if (fA) {
            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);
          } else {
            this.m_friction = 0;
            this.m_restitution = 0;
          }
          this.m_tangentSpeed = 0;
        },
        GetManifold: function() {
          return this.m_manifold;
        },
        GetWorldManifold: function(worldManifold) {
          var bodyA = this.m_fixtureA.GetBody();
          var bodyB = this.m_fixtureB.GetBody();
          var shapeA = this.m_fixtureA.GetShape();
          var shapeB = this.m_fixtureB.GetShape();
          worldManifold.Initialize(this.m_manifold, bodyA.GetTransform(), shapeA.m_radius, bodyB.GetTransform(), shapeB.m_radius);
        },
        IsTouching: function() {
          return (this.m_flags & b2Contact.e_touchingFlag) == b2Contact.e_touchingFlag;
        },
        SetEnabled: function(flag) {
          flag ? this.m_flags |= b2Contact.e_enabledFlag : this.m_flags &= ~b2Contact.e_enabledFlag;
        },
        IsEnabled: function() {
          return (this.m_flags & b2Contact.e_enabledFlag) == b2Contact.e_enabledFlag;
        },
        GetNext: function() {
          return this.m_next;
        },
        GetFixtureA: function() {
          return this.m_fixtureA;
        },
        GetChildIndexA: function() {
          return this.m_indexA;
        },
        GetFixtureB: function() {
          return this.m_fixtureB;
        },
        GetChildIndexB: function() {
          return this.m_indexB;
        },
        SetFriction: function(friction) {
          this.m_friction = friction;
        },
        GetFriction: function() {
          return this.m_friction;
        },
        ResetFriction: function() {
          this.m_friction = b2MixFriction(this.m_fixtureA.m_friction, this.m_fixtureB.m_friction);
        },
        SetRestitution: function(restitution) {
          this.m_restitution = restitution;
        },
        GetRestitution: function() {
          return this.m_restitution;
        },
        ResetRestitution: function() {
          this.m_restitution = b2MixRestitution(this.m_fixtureA.m_restitution, this.m_fixtureB.m_restitution);
        },
        SetTangentSpeed: function(speed) {
          this.m_tangentSpeed = speed;
        },
        GetTangentSpeed: function() {
          return this.m_tangentSpeed;
        },
        Evaluate: function(manifold, xfA, xfB) {},
        FlagForFiltering: function() {
          this.m_flags |= b2Contact.e_filterFlag;
        },
        m_oldManifold: null,
        Update: function(listener) {
          b2Contact.m_local_tempManifold.Assign(this.m_manifold);
          this.m_flags |= b2Contact.e_enabledFlag;
          var touching = false;
          var wasTouching = (this.m_flags & b2Contact.e_touchingFlag) == b2Contact.e_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.m_fixtureA.GetShape();
            var shapeB = this.m_fixtureB.GetShape();
            touching = b2TestShapeOverlap(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 < b2Contact.m_local_tempManifold.pointCount; ++j) {
                var mp1 = b2Contact.m_local_tempManifold.points[j];
                if (mp1.id.Get() == id2.Get()) {
                  mp2.normalImpulse = mp1.normalImpulse;
                  mp2.tangentImpulse = mp1.tangentImpulse;
                  break;
                }
              }
            }
            if (touching != wasTouching) {
              bodyA.SetAwake(true);
              bodyB.SetAwake(true);
            }
          }
          touching ? this.m_flags |= b2Contact.e_touchingFlag : this.m_flags &= ~b2Contact.e_touchingFlag;
          false == wasTouching && true == touching && listener && listener.BeginContact(this);
          true == wasTouching && false == touching && listener && listener.EndContact(this);
          false == sensor && touching && listener && listener.PreSolve(this, b2Contact.m_local_tempManifold);
        }
      };
      b2Contact.e_islandFlag = 1;
      b2Contact.e_touchingFlag = 2;
      b2Contact.e_enabledFlag = 4;
      b2Contact.e_filterFlag = 8;
      b2Contact.e_bulletHitFlag = 16;
      b2Contact.e_toiFlag = 32;
      function b2CircleContact() {
        this.parent.call(this);
      }
      b2CircleContact.prototype = {
        Evaluate: function(manifold, xfA, xfB) {
          b2CollideCircles(manifold, this.m_fixtureA.GetShape(), xfA, this.m_fixtureB.GetShape(), xfB);
        },
        Create: function(fixtureA, unused1, fixtureB, unused2) {
          this.parent.prototype.Create.call(this, fixtureA, 0, fixtureB, 0);
          b2Assert(this.m_fixtureA.GetType() == b2Shape.e_circle);
          b2Assert(this.m_fixtureB.GetType() == b2Shape.e_circle);
        }
      };
      b2CircleContact._extend(b2Contact);
      var _local_temp_edgeShape = new b2EdgeShape();
      function b2ChainAndCircleContact() {
        this.parent.call(this);
      }
      b2ChainAndCircleContact.prototype = {
        Evaluate: function(manifold, xfA, xfB) {
          var chain = this.m_fixtureA.GetShape();
          chain.GetChildEdge(_local_temp_edgeShape, this.m_indexA);
          b2CollideEdgeAndCircle(manifold, _local_temp_edgeShape, xfA, this.m_fixtureB.GetShape(), xfB);
        },
        Create: function(fixtureA, indexA, fixtureB, indexB) {
          this.parent.prototype.Create.call(this, fixtureA, indexA, fixtureB, indexB);
          b2Assert(this.m_fixtureA.GetType() == b2Shape.e_chain);
          b2Assert(this.m_fixtureB.GetType() == b2Shape.e_circle);
        }
      };
      b2ChainAndCircleContact._extend(b2Contact);
      function b2ChainAndPolygonContact() {
        this.parent.call(this);
      }
      b2ChainAndPolygonContact.prototype = {
        Evaluate: function(manifold, xfA, xfB) {
          var chain = this.m_fixtureA.GetShape();
          chain.GetChildEdge(_local_temp_edgeShape, this.m_indexA);
          b2CollideEdgeAndPolygon(manifold, _local_temp_edgeShape, xfA, this.m_fixtureB.GetShape(), xfB);
        },
        Create: function(fixtureA, indexA, fixtureB, indexB) {
          this.parent.prototype.Create.call(this, fixtureA, indexA, fixtureB, indexB);
          b2Assert(this.m_fixtureA.GetType() == b2Shape.e_chain);
          b2Assert(this.m_fixtureB.GetType() == b2Shape.e_polygon);
        }
      };
      b2ChainAndPolygonContact.Create = function(fixtureA, indexA, fixtureB, indexB) {
        return new b2ChainAndPolygonContact(fixtureA, indexA, fixtureB, indexB);
      };
      b2ChainAndPolygonContact._extend(b2Contact);
      function b2EdgeAndCircleContact() {
        this.parent.call(this);
      }
      b2EdgeAndCircleContact.prototype = {
        Evaluate: function(manifold, xfA, xfB) {
          b2CollideEdgeAndCircle(manifold, this.m_fixtureA.GetShape(), xfA, this.m_fixtureB.GetShape(), xfB);
        },
        Create: function(fixtureA, indexA, fixtureB, indexB) {
          this.parent.prototype.Create.call(this, fixtureA, 0, fixtureB, 0);
          b2Assert(this.m_fixtureA.GetType() == b2Shape.e_edge);
          b2Assert(this.m_fixtureB.GetType() == b2Shape.e_circle);
        }
      };
      b2EdgeAndCircleContact.Create = function(fixtureA, indexA, fixtureB, indexB) {
        return new b2EdgeAndCircleContact(fixtureA, fixtureB);
      };
      b2EdgeAndCircleContact._extend(b2Contact);
      function b2EdgeAndPolygonContact() {
        this.parent.call(this);
      }
      b2EdgeAndPolygonContact.prototype = {
        Evaluate: function(manifold, xfA, xfB) {
          b2CollideEdgeAndPolygon(manifold, this.m_fixtureA.GetShape(), xfA, this.m_fixtureB.GetShape(), xfB);
        },
        Create: function(fixtureA, indexA, fixtureB, indexB) {
          this.parent.prototype.Create.call(this, fixtureA, 0, fixtureB, 0);
          b2Assert(this.m_fixtureA.GetType() == b2Shape.e_edge);
          b2Assert(this.m_fixtureB.GetType() == b2Shape.e_polygon);
        }
      };
      b2EdgeAndPolygonContact.Create = function(fixtureA, indexA, fixtureB, indexB) {
        return new b2EdgeAndPolygonContact(fixtureA, fixtureB);
      };
      b2EdgeAndPolygonContact._extend(b2Contact);
      function b2PolygonAndCircleContact() {
        this.parent.call(this);
      }
      b2PolygonAndCircleContact.prototype = {
        Evaluate: function(manifold, xfA, xfB) {
          b2CollidePolygonAndCircle(manifold, this.m_fixtureA.GetShape(), xfA, this.m_fixtureB.GetShape(), xfB);
        },
        Create: function(fixtureA, indexA, fixtureB, indexB) {
          this.parent.prototype.Create.call(this, fixtureA, 0, fixtureB, 0);
          b2Assert(this.m_fixtureA.GetType() == b2Shape.e_polygon);
          b2Assert(this.m_fixtureB.GetType() == b2Shape.e_circle);
        }
      };
      b2PolygonAndCircleContact.Create = function(fixtureA, indexA, fixtureB, indexB) {
        return new b2PolygonAndCircleContact(fixtureA, fixtureB);
      };
      b2PolygonAndCircleContact._extend(b2Contact);
      function b2PolygonContact() {
        this.parent.call(this);
      }
      b2PolygonContact.prototype = {
        Evaluate: function(manifold, xfA, xfB) {
          b2CollidePolygons(manifold, this.m_fixtureA.GetShape(), xfA, this.m_fixtureB.GetShape(), xfB);
        },
        Create: function(fixtureA, indexA, fixtureB, indexB) {
          this.parent.prototype.Create.call(this, fixtureA, 0, fixtureB, 0);
          b2Assert(this.m_fixtureA.GetType() == b2Shape.e_polygon);
          b2Assert(this.m_fixtureB.GetType() == b2Shape.e_polygon);
        }
      };
      b2PolygonContact.Create = function(fixtureA, indexA, fixtureB, indexB) {
        return new b2PolygonContact(fixtureA, fixtureB);
      };
      b2PolygonContact._extend(b2Contact);
      b2Contact.AddType = function(fcn, type1, type2) {
        b2Assert(0 <= type1 && type1 < b2Shape.e_typeCount);
        b2Assert(0 <= type2 && type2 < b2Shape.e_typeCount);
        b2Contact.s_registers[type1] || (b2Contact.s_registers[type1] = []);
        b2Contact.s_registers[type1][type2] = new b2ContactRegister();
        b2Contact.s_registers[type1][type2].fcn = fcn;
        b2Contact.s_registers[type1][type2].primary = true;
        if (type1 != type2) {
          b2Contact.s_registers[type2] || (b2Contact.s_registers[type2] = []);
          b2Contact.s_registers[type2][type1] = new b2ContactRegister();
          b2Contact.s_registers[type2][type1].fcn = fcn;
          b2Contact.s_registers[type2][type1].primary = false;
        }
        fcn.garbage = [];
        fcn.alloc = 2;
      };
      b2Contact.InitializeRegisters = function() {
        b2Contact.AddType(b2CircleContact, b2Shape.e_circle, b2Shape.e_circle);
        b2Contact.AddType(b2PolygonAndCircleContact, b2Shape.e_polygon, b2Shape.e_circle);
        b2Contact.AddType(b2PolygonContact, b2Shape.e_polygon, b2Shape.e_polygon);
        b2Contact.AddType(b2EdgeAndCircleContact, b2Shape.e_edge, b2Shape.e_circle);
        b2Contact.AddType(b2EdgeAndPolygonContact, b2Shape.e_edge, b2Shape.e_polygon);
        b2Contact.AddType(b2ChainAndCircleContact, b2Shape.e_chain, b2Shape.e_circle);
        b2Contact.AddType(b2ChainAndPolygonContact, b2Shape.e_chain, b2Shape.e_polygon);
      };
      b2Contact.RetrieveGarbage = function(fcn) {
        var contact;
        if (contact = fcn.garbage.pop()) return contact;
        for (var i = 0; i < fcn.alloc - 1; ++i) fcn.garbage.push(new fcn());
        fcn.alloc += 32;
        return new fcn();
      };
      b2Contact.Create = function(fixtureA, indexA, fixtureB, indexB) {
        if (false == b2Contact.s_initialized) {
          b2Contact.InitializeRegisters();
          b2Contact.s_initialized = true;
        }
        var type1 = fixtureA.GetType();
        var type2 = fixtureB.GetType();
        b2Assert(0 <= type1 && type1 < b2Shape.e_typeCount);
        b2Assert(0 <= type2 && type2 < b2Shape.e_typeCount);
        var fcn = b2Contact.s_registers[type1] && b2Contact.s_registers[type1][type2] ? b2Contact.s_registers[type1][type2].fcn : null;
        if (fcn) {
          var contact = b2Contact.RetrieveGarbage(fcn);
          b2Contact.s_registers[type1][type2].primary ? contact.Create(fixtureA, indexA, fixtureB, indexB) : contact.Create(fixtureB, indexB, fixtureA, indexA);
          return contact;
        }
        return null;
      };
      b2Contact.Destroy = function(contact) {
        b2Assert(true == b2Contact.s_initialized);
        var fixtureA = contact.m_fixtureA;
        var fixtureB = contact.m_fixtureB;
        if (contact.m_manifold.pointCount > 0 && false == fixtureA.IsSensor() && false == fixtureB.IsSensor()) {
          fixtureA.GetBody().SetAwake(true);
          fixtureB.GetBody().SetAwake(true);
        }
        var typeA = fixtureA.GetType();
        var typeB = fixtureB.GetType();
        b2Assert(0 <= typeA && typeB < b2Shape.e_typeCount);
        b2Assert(0 <= typeA && typeB < b2Shape.e_typeCount);
        contact.m_nodeA.Clear();
        contact.m_nodeB.Clear();
        b2Contact.s_registers[typeA][typeB].fcn.garbage.push(contact);
      };
      b2Contact.s_registers = [];
      b2Contact.s_initialized = false;
      var b2_defaultFilter = new b2ContactFilter();
      var b2_defaultListener = new b2ContactListener();
      function b2ContactManager() {
        this.m_broadPhase = new b2BroadPhase();
        this.m_contactList = null;
        this.m_contactCount = 0;
        this.m_contactFilter = b2_defaultFilter;
        this.m_contactListener = b2_defaultListener;
      }
      b2ContactManager.prototype = {
        AddPair: function(proxyUserDataA, proxyUserDataB) {
          var proxyA = proxyUserDataA;
          var proxyB = proxyUserDataB;
          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 (false == bodyB.ShouldCollide(bodyA)) return;
          if (this.m_contactFilter && false == this.m_contactFilter.ShouldCollide(fixtureA, fixtureB)) return;
          var c = b2Contact.Create(fixtureA, indexA, fixtureB, indexB);
          if (null == c) return;
          fixtureA = c.GetFixtureA();
          fixtureB = c.GetFixtureB();
          indexA = c.GetChildIndexA();
          indexB = c.GetChildIndexB();
          bodyA = fixtureA.GetBody();
          bodyB = fixtureB.GetBody();
          c.m_prev = null;
          c.m_next = this.m_contactList;
          null != this.m_contactList && (this.m_contactList.m_prev = c);
          this.m_contactList = c;
          c.m_nodeA.contact = c;
          c.m_nodeA.other = bodyB;
          c.m_nodeA.prev = null;
          c.m_nodeA.next = bodyA.m_contactList;
          null != bodyA.m_contactList && (bodyA.m_contactList.prev = c.m_nodeA);
          bodyA.m_contactList = c.m_nodeA;
          c.m_nodeB.contact = c;
          c.m_nodeB.other = bodyA;
          c.m_nodeB.prev = null;
          c.m_nodeB.next = bodyB.m_contactList;
          null != bodyB.m_contactList && (bodyB.m_contactList.prev = c.m_nodeB);
          bodyB.m_contactList = c.m_nodeB;
          if (false == fixtureA.IsSensor() && false == fixtureB.IsSensor()) {
            bodyA.SetAwake(true);
            bodyB.SetAwake(true);
          }
          ++this.m_contactCount;
        },
        FindNewContacts: function() {
          this.m_broadPhase.UpdatePairs(this);
        },
        Destroy: function(c) {
          var fixtureA = c.GetFixtureA();
          var fixtureB = c.GetFixtureB();
          var bodyA = fixtureA.GetBody();
          var bodyB = fixtureB.GetBody();
          this.m_contactListener && c.IsTouching() && this.m_contactListener.EndContact(c);
          c.m_prev && (c.m_prev.m_next = c.m_next);
          c.m_next && (c.m_next.m_prev = c.m_prev);
          c == this.m_contactList && (this.m_contactList = c.m_next);
          c.m_nodeA.prev && (c.m_nodeA.prev.next = c.m_nodeA.next);
          c.m_nodeA.next && (c.m_nodeA.next.prev = c.m_nodeA.prev);
          c.m_nodeA == bodyA.m_contactList && (bodyA.m_contactList = c.m_nodeA.next);
          c.m_nodeB.prev && (c.m_nodeB.prev.next = c.m_nodeB.next);
          c.m_nodeB.next && (c.m_nodeB.next.prev = c.m_nodeB.prev);
          c.m_nodeB == bodyB.m_contactList && (bodyB.m_contactList = c.m_nodeB.next);
          b2Contact.Destroy(c);
          --this.m_contactCount;
        },
        Collide: function() {
          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_flags & b2Contact.e_filterFlag) {
              if (false == bodyB.ShouldCollide(bodyA)) {
                var cNuke = c;
                c = cNuke.GetNext();
                this.Destroy(cNuke);
                continue;
              }
              if (this.m_contactFilter && false == this.m_contactFilter.ShouldCollide(fixtureA, fixtureB)) {
                var cNuke = c;
                c = cNuke.GetNext();
                this.Destroy(cNuke);
                continue;
              }
              c.m_flags &= ~b2Contact.e_filterFlag;
            }
            var activeA = bodyA.IsAwake() && bodyA.m_type != b2Body.b2_staticBody;
            var activeB = bodyB.IsAwake() && bodyB.m_type != b2Body.b2_staticBody;
            if (false == activeA && false == activeB) {
              c = c.GetNext();
              continue;
            }
            var proxyIdA = fixtureA.m_proxies[indexA].proxyId;
            var proxyIdB = fixtureB.m_proxies[indexB].proxyId;
            var overlap = this.m_broadPhase.TestOverlap(proxyIdA, proxyIdB);
            if (false == overlap) {
              var cNuke = c;
              c = cNuke.GetNext();
              this.Destroy(cNuke);
              continue;
            }
            c.Update(this.m_contactListener);
            c = c.GetNext();
          }
        }
      };
      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;
      }
      function b2ContactPositionConstraint() {
        this.localPoints = new Array(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 = 0;
        this.radiusA = 0, this.radiusB = 0;
        this.pointCount = 0;
      }
      function b2ContactVelocityConstraint() {
        this.points = new Array(b2_maxManifoldPoints);
        for (var i = 0; i < this.points.length; ++i) this.points[i] = new b2VelocityConstraintPoint();
        this.normal = 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;
      }
      function b2PositionSolverManifold() {
        this.normal = new b2Vec2();
        this.point = new b2Vec2();
        this.separation = 0;
      }
      b2PositionSolverManifold.prototype = {
        Initialize: function(pc, xfA, xfB, index) {
          b2Assert(pc.pointCount > 0);
          switch (pc.type) {
           case b2Manifold.e_circles:
            var pointAx = xfA.q.c * pc.localPoint.x - xfA.q.s * pc.localPoint.y + xfA.p.x;
            var pointAy = xfA.q.s * pc.localPoint.x + xfA.q.c * pc.localPoint.y + xfA.p.y;
            var pointBx = xfB.q.c * pc.localPoints[0].x - xfB.q.s * pc.localPoints[0].y + xfB.p.x;
            var pointBy = xfB.q.s * pc.localPoints[0].x + xfB.q.c * pc.localPoints[0].y + xfB.p.y;
            this.point.x = .5 * (pointAx + pointBx);
            this.point.y = .5 * (pointAy + pointBy);
            this.normal.x = pointBx - pointAx;
            this.normal.y = pointBy - pointAy;
            var tempnx = this.normal.x;
            var tempny = this.normal.y;
            this.normal.Normalize();
            this.separation = tempnx * this.normal.x + tempny * this.normal.y - pc.radiusA - pc.radiusB;
            break;

           case b2Manifold.e_faceA:
            this.normal.x = xfA.q.c * pc.localNormal.x - xfA.q.s * pc.localNormal.y;
            this.normal.y = xfA.q.s * pc.localNormal.x + xfA.q.c * pc.localNormal.y;
            var planePointx = xfA.q.c * pc.localPoint.x - xfA.q.s * pc.localPoint.y + xfA.p.x;
            var planePointy = xfA.q.s * pc.localPoint.x + xfA.q.c * pc.localPoint.y + xfA.p.y;
            var clipPointx = xfB.q.c * pc.localPoints[index].x - xfB.q.s * pc.localPoints[index].y + xfB.p.x;
            var clipPointy = xfB.q.s * pc.localPoints[index].x + xfB.q.c * pc.localPoints[index].y + xfB.p.y;
            this.separation = (clipPointx - planePointx) * this.normal.x + (clipPointy - planePointy) * this.normal.y - pc.radiusA - pc.radiusB;
            this.point.x = clipPointx;
            this.point.y = clipPointy;
            break;

           case b2Manifold.e_faceB:
            this.normal.x = xfB.q.c * pc.localNormal.x - xfB.q.s * pc.localNormal.y;
            this.normal.y = xfB.q.s * pc.localNormal.x + xfB.q.c * pc.localNormal.y;
            var planePointx = xfB.q.c * pc.localPoint.x - xfB.q.s * pc.localPoint.y + xfB.p.x;
            var planePointy = xfB.q.s * pc.localPoint.x + xfB.q.c * pc.localPoint.y + xfB.p.y;
            var clipPointx = xfA.q.c * pc.localPoints[index].x - xfA.q.s * pc.localPoints[index].y + xfA.p.x;
            var clipPointy = xfA.q.s * pc.localPoints[index].x + xfA.q.c * pc.localPoints[index].y + xfA.p.y;
            this.separation = (clipPointx - planePointx) * this.normal.x + (clipPointy - planePointy) * this.normal.y - pc.radiusA - pc.radiusB;
            this.point.x = clipPointx;
            this.point.y = clipPointy;
            this.normal.x = -this.normal.x;
            this.normal.y = -this.normal.y;
          }
        }
      };
      function b2ContactSolverDef() {
        this.step = new b2TimeStep();
        this.contacts = null;
        this.count = 0;
        this.positions = null;
        this.velocities = null;
      }
      function b2ContactSolver() {
        this.m_positionConstraints = [];
        this.m_velocityConstraints = [];
      }
      b2ContactSolver.cs_xfA = new b2Transform();
      b2ContactSolver.cs_xfB = new b2Transform();
      b2ContactSolver.temp_solver_manifold = new b2PositionSolverManifold();
      b2ContactSolver.prototype = {
        Init: function(def) {
          this.m_step = def.step;
          this.m_count = def.count;
          this.m_positionConstraints.length = this.m_count;
          this.m_velocityConstraints.length = this.m_count;
          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;
            b2Assert(pointCount > 0);
            var vc = this.m_velocityConstraints[i] || new b2ContactVelocityConstraint();
            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();
            this.m_velocityConstraints[i] = vc;
            var pc = this.m_positionConstraints[i] || new b2ContactPositionConstraint();
            pc.indexA = bodyA.m_islandIndex;
            pc.indexB = bodyB.m_islandIndex;
            pc.invMassA = bodyA.m_invMass;
            pc.invMassB = bodyB.m_invMass;
            pc.localCenterA.x = bodyA.m_sweep.localCenter.x;
            pc.localCenterA.y = bodyA.m_sweep.localCenter.y;
            pc.localCenterB.x = bodyB.m_sweep.localCenter.x;
            pc.localCenterB.y = bodyB.m_sweep.localCenter.y;
            pc.invIA = bodyA.m_invI;
            pc.invIB = bodyB.m_invI;
            pc.localNormal.x = manifold.localNormal.x;
            pc.localNormal.y = manifold.localNormal.y;
            pc.localPoint.x = manifold.localPoint.x;
            pc.localPoint.y = manifold.localPoint.y;
            pc.pointCount = pointCount;
            pc.radiusA = radiusA;
            pc.radiusB = radiusB;
            pc.type = manifold.type;
            this.m_positionConstraints[i] = pc;
            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] = cp.localPoint;
            }
          }
        },
        InitializeVelocityConstraints: function() {
          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;
            b2Assert(manifold.pointCount > 0);
            b2ContactSolver.cs_xfA.q.Set(aA);
            b2ContactSolver.cs_xfB.q.Set(aB);
            b2ContactSolver.cs_xfA.p.x = cA.x - (b2ContactSolver.cs_xfA.q.c * localCenterA.x - b2ContactSolver.cs_xfA.q.s * localCenterA.y);
            b2ContactSolver.cs_xfA.p.y = cA.y - (b2ContactSolver.cs_xfA.q.s * localCenterA.x + b2ContactSolver.cs_xfA.q.c * localCenterA.y);
            b2ContactSolver.cs_xfB.p.x = cB.x - (b2ContactSolver.cs_xfB.q.c * localCenterB.x - b2ContactSolver.cs_xfB.q.s * localCenterB.y);
            b2ContactSolver.cs_xfB.p.y = cB.y - (b2ContactSolver.cs_xfB.q.s * localCenterB.x + b2ContactSolver.cs_xfB.q.c * localCenterB.y);
            var worldManifold = new b2WorldManifold();
            worldManifold.Initialize(manifold, b2ContactSolver.cs_xfA, radiusA, b2ContactSolver.cs_xfB, radiusB);
            vc.normal.x = worldManifold.normal.x;
            vc.normal.y = worldManifold.normal.y;
            var pointCount = vc.pointCount;
            for (var j = 0; j < pointCount; ++j) {
              var vcp = vc.points[j];
              vcp.rA.x = worldManifold.points[j].x - cA.x;
              vcp.rA.y = worldManifold.points[j].y - cA.y;
              vcp.rB.x = worldManifold.points[j].x - cB.x;
              vcp.rB.y = worldManifold.points[j].y - cB.y;
              var rnA = vcp.rA.x * vc.normal.y - vcp.rA.y * vc.normal.x;
              var rnB = vcp.rB.x * vc.normal.y - vcp.rB.y * vc.normal.x;
              var kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
              vcp.normalMass = kNormal > 0 ? 1 / kNormal : 0;
              var tangentx = 1 * vc.normal.y;
              var tangenty = -1 * vc.normal.x;
              var rtA = vcp.rA.x * tangenty - vcp.rA.y * tangentx;
              var rtB = vcp.rB.x * tangenty - vcp.rB.y * tangentx;
              var kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB;
              vcp.tangentMass = kTangent > 0 ? 1 / kTangent : 0;
              vcp.velocityBias = 0;
              var vRel = vc.normal.x * (vB.x + -wB * vcp.rB.y - vA.x - -wA * vcp.rA.y) + vc.normal.y * (vB.y + wB * vcp.rB.x - vA.y - wA * vcp.rA.x);
              vRel < -b2_velocityThreshold && (vcp.velocityBias = -vc.restitution * vRel);
            }
            if (2 == vc.pointCount) {
              var vcp1 = vc.points[0];
              var vcp2 = vc.points[1];
              var rn1A = vcp1.rA.x * vc.normal.y - vcp1.rA.y * vc.normal.x;
              var rn1B = vcp1.rB.x * vc.normal.y - vcp1.rB.y * vc.normal.x;
              var rn2A = vcp2.rA.x * vc.normal.y - vcp2.rA.y * vc.normal.x;
              var rn2B = vcp2.rB.x * vc.normal.y - vcp2.rB.y * vc.normal.x;
              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;
              var k_maxConditionNumber = 1e3;
              if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) {
                vc.K.ex.x = k11;
                vc.K.ex.y = k12;
                vc.K.ey.x = k12;
                vc.K.ey.y = k22;
                vc.normalMass.Assign(vc.K.GetInverse());
              } else vc.pointCount = 1;
            }
          }
        },
        WarmStart: function() {
          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 tangentx = 1 * normal.y;
            var tangenty = -1 * normal.x;
            for (var j = 0; j < pointCount; ++j) {
              var vcp = vc.points[j];
              var Px = vcp.normalImpulse * normal.x + vcp.tangentImpulse * tangentx;
              var Py = vcp.normalImpulse * normal.y + vcp.tangentImpulse * tangenty;
              wA -= iA * (vcp.rA.x * Py - vcp.rA.y * Px);
              vA.x -= mA * Px;
              vA.y -= mA * Py;
              wB += iB * (vcp.rB.x * Py - vcp.rB.y * Px);
              vB.x += mB * Px;
              vB.y += mB * Py;
            }
            this.m_velocities[indexA].w = wA;
            this.m_velocities[indexB].w = wB;
          }
        },
        SolveVelocityConstraints: function() {
          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 tangentx = 1 * normal.y;
            var tangenty = -1 * normal.x;
            var friction = vc.friction;
            b2Assert(1 == pointCount || 2 == pointCount);
            for (var j = 0; j < pointCount; ++j) {
              var vcp = vc.points[j];
              var dvx = vB.x + -wB * vcp.rB.y - vA.x - -wA * vcp.rA.y;
              var dvy = vB.y + wB * vcp.rB.x - vA.y - wA * vcp.rA.x;
              var vt = dvx * tangentx + dvy * tangenty - 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;
              var Px = lambda * tangentx;
              var Py = lambda * tangenty;
              vA.x -= mA * Px;
              vA.y -= mA * Py;
              wA -= iA * (vcp.rA.x * Py - vcp.rA.y * Px);
              vB.x += mB * Px;
              vB.y += mB * Py;
              wB += iB * (vcp.rB.x * Py - vcp.rB.y * Px);
            }
            if (1 == vc.pointCount) {
              vcp = vc.points[0];
              dvx = vB.x + -wB * vcp.rB.y - vA.x - -wA * vcp.rA.y;
              dvy = vB.y + wB * vcp.rB.x - vA.y - wA * vcp.rA.x;
              var vn = dvx * normal.x + dvy * normal.y;
              var lambda = -vcp.normalMass * (vn - vcp.velocityBias);
              var newImpulse = b2Max(vcp.normalImpulse + lambda, 0);
              lambda = newImpulse - vcp.normalImpulse;
              vcp.normalImpulse = newImpulse;
              Px = lambda * normal.x;
              Py = lambda * normal.y;
              vA.x -= mA * Px;
              vA.y -= mA * Py;
              wA -= iA * (vcp.rA.x * Py - vcp.rA.y * Px);
              vB.x += mB * Px;
              vB.y += mB * Py;
              wB += iB * (vcp.rB.x * Py - vcp.rB.y * Px);
            } else {
              var cp1 = vc.points[0];
              var cp2 = vc.points[1];
              var ax = cp1.normalImpulse;
              var ay = cp2.normalImpulse;
              b2Assert(ax >= 0 && ay >= 0);
              var dv1x = vB.x + -wB * cp1.rB.y - vA.x - -wA * cp1.rA.y;
              var dv1y = vB.y + wB * cp1.rB.x - vA.y - wA * cp1.rA.x;
              var dv2x = vB.x + -wB * cp2.rB.y - vA.x - -wA * cp2.rA.y;
              var dv2y = vB.y + wB * cp2.rB.x - vA.y - wA * cp2.rA.x;
              var vn1 = dv1x * normal.x + dv1y * normal.y;
              var vn2 = dv2x * normal.x + dv2y * normal.y;
              var bx = vn1 - cp1.velocityBias;
              var by = vn2 - cp2.velocityBias;
              bx -= vc.K.ex.x * ax + vc.K.ey.x * ay;
              by -= vc.K.ex.y * ax + vc.K.ey.y * ay;
              for (;;) {
                var xx = -(vc.normalMass.ex.x * bx + vc.normalMass.ey.x * by);
                var xy = -(vc.normalMass.ex.y * bx + vc.normalMass.ey.y * by);
                if (xx >= 0 && xy >= 0) {
                  var dx = xx - ax;
                  var dy = xy - ay;
                  var P1x = dx * normal.x;
                  var P1y = dx * normal.y;
                  var P2x = dy * normal.x;
                  var P2y = dy * normal.y;
                  vA.x -= mA * (P1x + P2x);
                  vA.y -= mA * (P1y + P2y);
                  wA -= iA * (cp1.rA.x * P1y - cp1.rA.y * P1x + (cp2.rA.x * P2y - cp2.rA.y * P2x));
                  vB.x += mB * (P1x + P2x);
                  vB.y += mB * (P1y + P2y);
                  wB += iB * (cp1.rB.x * P1y - cp1.rB.y * P1x + (cp2.rB.x * P2y - cp2.rB.y * P2x));
                  cp1.normalImpulse = xx;
                  cp2.normalImpulse = xy;
                  break;
                }
                xx = -cp1.normalMass * bx;
                xy = 0;
                vn1 = 0;
                vn2 = vc.K.ex.y * xx + by;
                if (xx >= 0 && vn2 >= 0) {
                  dx = xx - ax;
                  dy = xy - ay;
                  P1x = dx * normal.x;
                  P1y = dx * normal.y;
                  P2x = dy * normal.x;
                  P2y = dy * normal.y;
                  vA.x -= mA * (P1x + P2x);
                  vA.y -= mA * (P1y + P2y);
                  wA -= iA * (cp1.rA.x * P1y - cp1.rA.y * P1x + (cp2.rA.x * P2y - cp2.rA.y * P2x));
                  vB.x += mB * (P1x + P2x);
                  vB.y += mB * (P1y + P2y);
                  wB += iB * (cp1.rB.x * P1y - cp1.rB.y * P1x + (cp2.rB.x * P2y - cp2.rB.y * P2x));
                  cp1.normalImpulse = xx;
                  cp2.normalImpulse = xy;
                  break;
                }
                xx = 0;
                xy = -cp2.normalMass * by;
                vn1 = vc.K.ey.x * xy + bx;
                vn2 = 0;
                if (xy >= 0 && vn1 >= 0) {
                  dx = xx - ax;
                  dy = xy - ay;
                  P1x = dx * normal.x;
                  P1y = dx * normal.y;
                  P2x = dy * normal.x;
                  P2y = dy * normal.y;
                  vA.x -= mA * (P1x + P2x);
                  vA.y -= mA * (P1y + P2y);
                  wA -= iA * (cp1.rA.x * P1y - cp1.rA.y * P1x + (cp2.rA.x * P2y - cp2.rA.y * P2x));
                  vB.x += mB * (P1x + P2x);
                  vB.y += mB * (P1y + P2y);
                  wB += iB * (cp1.rB.x * P1y - cp1.rB.y * P1x + (cp2.rB.x * P2y - cp2.rB.y * P2x));
                  cp1.normalImpulse = xx;
                  cp2.normalImpulse = xy;
                  break;
                }
                xx = 0;
                xy = 0;
                vn1 = bx;
                vn2 = by;
                if (vn1 >= 0 && vn2 >= 0) {
                  dx = xx - ax;
                  dy = xy - ay;
                  P1x = dx * normal.x;
                  P1y = dx * normal.y;
                  P2x = dy * normal.x;
                  P2y = dy * normal.y;
                  vA.x -= mA * (P1x + P2x);
                  vA.y -= mA * (P1y + P2y);
                  wA -= iA * (cp1.rA.x * P1y - cp1.rA.y * P1x + (cp2.rA.x * P2y - cp2.rA.y * P2x));
                  vB.x += mB * (P1x + P2x);
                  vB.y += mB * (P1y + P2y);
                  wB += iB * (cp1.rB.x * P1y - cp1.rB.y * P1x + (cp2.rB.x * P2y - cp2.rB.y * P2x));
                  cp1.normalImpulse = xx;
                  cp2.normalImpulse = xy;
                  break;
                }
                break;
              }
            }
            this.m_velocities[indexA].w = wA;
            this.m_velocities[indexB].w = wB;
          }
        },
        StoreImpulses: function() {
          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;
            }
          }
        },
        SolvePositionConstraints: function() {
          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) {
              b2ContactSolver.cs_xfA.q.Set(aA);
              b2ContactSolver.cs_xfB.q.Set(aB);
              b2ContactSolver.cs_xfA.p.x = cA.x - (b2ContactSolver.cs_xfA.q.c * localCenterA.x - b2ContactSolver.cs_xfA.q.s * localCenterA.y);
              b2ContactSolver.cs_xfA.p.y = cA.y - (b2ContactSolver.cs_xfA.q.s * localCenterA.x + b2ContactSolver.cs_xfA.q.c * localCenterA.y);
              b2ContactSolver.cs_xfB.p.x = cB.x - (b2ContactSolver.cs_xfB.q.c * localCenterB.x - b2ContactSolver.cs_xfB.q.s * localCenterB.y);
              b2ContactSolver.cs_xfB.p.y = cB.y - (b2ContactSolver.cs_xfB.q.s * localCenterB.x + b2ContactSolver.cs_xfB.q.c * localCenterB.y);
              b2ContactSolver.temp_solver_manifold.Initialize(pc, b2ContactSolver.cs_xfA, b2ContactSolver.cs_xfB, j);
              var normal = b2ContactSolver.temp_solver_manifold.normal;
              var point = b2ContactSolver.temp_solver_manifold.point;
              var separation = b2ContactSolver.temp_solver_manifold.separation;
              var rAx = point.x - cA.x;
              var rAy = point.y - cA.y;
              var rBx = point.x - cB.x;
              var rBy = point.y - cB.y;
              minSeparation = b2Min(minSeparation, separation);
              var C = b2Clamp(b2_baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0);
              var rnA = rAx * normal.y - rAy * normal.x;
              var rnB = rBx * normal.y - rBy * normal.x;
              var K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
              var impulse = K > 0 ? -C / K : 0;
              var Px = impulse * normal.x;
              var Py = impulse * normal.y;
              cA.x -= mA * Px;
              cA.y -= mA * Py;
              aA -= iA * (rAx * Py - rAy * Px);
              cB.x += mB * Px;
              cB.y += mB * Py;
              aB += iB * (rBx * Py - rBy * Px);
            }
            this.m_positions[indexA].a = aA;
            this.m_positions[indexB].a = aB;
          }
          return minSeparation >= -3 * b2_linearSlop;
        },
        SolveTOIPositionConstraints: function(toiIndexA, toiIndexB) {
          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) {
              b2ContactSolver.cs_xfA.q.Set(aA);
              b2ContactSolver.cs_xfB.q.Set(aB);
              b2ContactSolver.cs_xfA.p.Assign(b2Vec2.Subtract(cA, b2Mul_r_v2(b2ContactSolver.cs_xfA.q, localCenterA)));
              b2ContactSolver.cs_xfB.p.Assign(b2Vec2.Subtract(cB, b2Mul_r_v2(b2ContactSolver.cs_xfB.q, localCenterB)));
              b2ContactSolver.temp_solver_manifold.Initialize(pc, b2ContactSolver.cs_xfA, b2ContactSolver.cs_xfB, j);
              var normal = b2ContactSolver.temp_solver_manifold.normal;
              var point = b2ContactSolver.temp_solver_manifold.point;
              var separation = b2ContactSolver.temp_solver_manifold.separation;
              var rA = b2Vec2.Subtract(point, cA);
              var rB = b2Vec2.Subtract(point, cB);
              minSeparation = b2Min(minSeparation, separation);
              var C = b2Clamp(b2_toiBaugarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0);
              var rnA = b2Cross_v2_v2(rA, normal);
              var rnB = b2Cross_v2_v2(rB, normal);
              var K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
              var impulse = K > 0 ? -C / K : 0;
              var P = b2Vec2.Multiply(impulse, normal);
              cA.Subtract(b2Vec2.Multiply(mA, P));
              aA -= iA * b2Cross_v2_v2(rA, P);
              cB.Add(b2Vec2.Multiply(mB, P));
              aB += iB * b2Cross_v2_v2(rB, P);
            }
            this.m_positions[indexA].a = aA;
            this.m_positions[indexB].a = aB;
          }
          return minSeparation >= -1.5 * b2_linearSlop;
        }
      };
      function b2Island() {
        this.m_bodies = [];
        this.m_contacts = [];
        this.m_joints = [];
        this.m_velocities = [];
        this.m_positions = [];
      }
      var profile_solve_init = b2Profiler.create("solve initialization", "solve");
      var profile_solve_init_warmStarting = b2Profiler.create("warm starting", "solve initialization");
      var profile_solve_velocity = b2Profiler.create("solve velocities", "solve");
      var profile_solve_position = b2Profiler.create("solve positions", "solve");
      b2Island._solverData = new b2SolverData();
      b2Island._solverDef = new b2ContactSolverDef();
      b2Island._solver = new b2ContactSolver();
      b2Island.prototype = {
        Clear: function() {
          this.m_bodyCount = 0;
          this.m_contactCount = 0;
          this.m_jointCount = 0;
        },
        Initialize: function(bodyCapacity, contactCapacity, jointCapacity, listener) {
          this.m_listener = 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_bodies.length = bodyCapacity;
          this.m_contacts.length = contactCapacity;
          this.m_joints.length = jointCapacity;
          this.m_velocities.length = bodyCapacity;
          this.m_positions.length = bodyCapacity;
        },
        Solve: function(step, gravity, allowSleep) {
          profile_solve_init.start();
          var h = step.dt;
          for (var i = 0; i < this.m_bodyCount; ++i) {
            var b = this.m_bodies[i];
            this.m_positions[i].c.Assign(b.m_sweep.c);
            var a = b.m_sweep.a;
            this.m_velocities[i].v.Assign(b.m_linearVelocity);
            var w = b.m_angularVelocity;
            b.m_sweep.c0.Assign(b.m_sweep.c);
            b.m_sweep.a0 = b.m_sweep.a;
            if (b.m_type == b2Body.b2_dynamicBody) {
              this.m_velocities[i].v.x += h * (b.m_gravityScale * gravity.x + b.m_invMass * b.m_force.x);
              this.m_velocities[i].v.y += h * (b.m_gravityScale * gravity.y + b.m_invMass * b.m_force.y);
              w += h * b.m_invI * b.m_torque;
              this.m_velocities[i].v.x *= 1 / (1 + h * b.m_linearDamping);
              this.m_velocities[i].v.y *= 1 / (1 + h * b.m_linearDamping);
              w *= 1 / (1 + h * b.m_angularDamping);
            }
            this.m_positions[i].a = a;
            this.m_velocities[i].w = w;
          }
          b2Island._solverData.step = step;
          b2Island._solverData.positions = this.m_positions;
          b2Island._solverData.velocities = this.m_velocities;
          b2Island._solverDef.step = step;
          b2Island._solverDef.contacts = this.m_contacts;
          b2Island._solverDef.count = this.m_contactCount;
          b2Island._solverDef.positions = this.m_positions;
          b2Island._solverDef.velocities = this.m_velocities;
          b2Island._solverDef.allocator = this.m_allocator;
          b2Island._solver.Init(b2Island._solverDef);
          b2Island._solver.InitializeVelocityConstraints();
          if (step.warmStarting) {
            profile_solve_init_warmStarting.start();
            b2Island._solver.WarmStart();
            profile_solve_init_warmStarting.stop();
          }
          for (var i = 0; i < this.m_jointCount; ++i) this.m_joints[i].InitVelocityConstraints(b2Island._solverData);
          profile_solve_init.stop();
          profile_solve_velocity.start();
          for (var i = 0; i < step.velocityIterations; ++i) {
            for (var j = 0; j < this.m_jointCount; ++j) this.m_joints[j].SolveVelocityConstraints(b2Island._solverData);
            b2Island._solver.SolveVelocityConstraints();
          }
          b2Island._solver.StoreImpulses();
          profile_solve_velocity.stop();
          profile_solve_position.start();
          for (var i = 0; i < this.m_bodyCount; ++i) {
            var c = this.m_positions[i].c;
            var a = this.m_positions[i].a;
            var v = this.m_velocities[i].v;
            var w = this.m_velocities[i].w;
            var translationx = h * v.x;
            var translationy = h * v.y;
            var translationl = translationx * translationx + translationy * translationy;
            if (translationl > b2_maxTranslationSquared) {
              var ratio = b2_maxTranslation / b2Sqrt(translationl);
              v.x *= ratio;
              v.y *= ratio;
            }
            var rotation = h * w;
            if (rotation * rotation > b2_maxRotationSquared) {
              var ratio = b2_maxRotation / b2Abs(rotation);
              w *= ratio;
            }
            c.x += h * v.x;
            c.y += h * v.y;
            a += h * w;
            this.m_positions[i].a = a;
            this.m_velocities[i].w = w;
          }
          var positionSolved = false;
          for (var i = 0; i < step.positionIterations; ++i) {
            var contactsOkay = b2Island._solver.SolvePositionConstraints();
            var jointsOkay = true;
            for (var j = 0; j < this.m_jointCount; ++j) {
              var jointOkay = this.m_joints[j].SolvePositionConstraints(b2Island._solverData);
              jointsOkay = jointsOkay && jointOkay;
            }
            if (contactsOkay && jointsOkay) {
              positionSolved = true;
              break;
            }
          }
          for (var i = 0; i < this.m_bodyCount; ++i) {
            var body = this.m_bodies[i];
            body.m_sweep.c.Assign(this.m_positions[i].c);
            body.m_sweep.a = this.m_positions[i].a;
            body.m_linearVelocity.Assign(this.m_velocities[i].v);
            body.m_angularVelocity = this.m_velocities[i].w;
            body.SynchronizeTransform();
          }
          profile_solve_position.stop();
          this.Report(b2Island._solver.m_velocityConstraints);
          if (allowSleep) {
            var minSleepTime = b2_maxFloat;
            var linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance;
            var angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance;
            for (var i = 0; i < this.m_bodyCount; ++i) {
              var b = this.m_bodies[i];
              if (b.GetType() == b2Body.b2_staticBody) continue;
              if (0 == (b.m_flags & b2Body.e_autoSleepFlag) || b.m_angularVelocity * b.m_angularVelocity > angTolSqr || b2Dot_v2_v2(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 i = 0; i < this.m_bodyCount; ++i) {
              var b = this.m_bodies[i];
              b.SetAwake(false);
            }
          }
        },
        SolveTOI: function(subStep, toiIndexA, toiIndexB) {
          b2Assert(toiIndexA < this.m_bodyCount);
          b2Assert(toiIndexB < this.m_bodyCount);
          for (var i = 0; i < this.m_bodyCount; ++i) {
            var b = this.m_bodies[i];
            this.m_positions[i].c.Assign(b.m_sweep.c);
            this.m_positions[i].a = b.m_sweep.a;
            this.m_velocities[i].v.Assign(b.m_linearVelocity);
            this.m_velocities[i].w = b.m_angularVelocity;
          }
          b2Island._solverDef.contacts = this.m_contacts;
          b2Island._solverDef.count = this.m_contactCount;
          b2Island._solverDef.step = subStep;
          b2Island._solverDef.positions = this.m_positions;
          b2Island._solverDef.velocities = this.m_velocities;
          b2Island._solver.Init(b2Island._solverDef);
          for (var i = 0; i < subStep.positionIterations; ++i) {
            var contactsOkay = b2Island._solver.SolveTOIPositionConstraints(toiIndexA, toiIndexB);
            if (contactsOkay) break;
          }
          this.m_bodies[toiIndexA].m_sweep.c0.Assign(this.m_positions[toiIndexA].c);
          this.m_bodies[toiIndexA].m_sweep.a0 = this.m_positions[toiIndexA].a;
          this.m_bodies[toiIndexB].m_sweep.c0.Assign(this.m_positions[toiIndexB].c);
          this.m_bodies[toiIndexB].m_sweep.a0 = this.m_positions[toiIndexB].a;
          b2Island._solver.InitializeVelocityConstraints();
          for (var i = 0; i < subStep.velocityIterations; ++i) b2Island._solver.SolveVelocityConstraints();
          var h = subStep.dt;
          for (var i = 0; i < this.m_bodyCount; ++i) {
            var c = this.m_positions[i].c;
            var a = this.m_positions[i].a;
            var v = this.m_velocities[i].v;
            var w = this.m_velocities[i].w;
            var translation = b2Vec2.Multiply(h, v);
            if (b2Dot_v2_v2(translation, translation) > b2_maxTranslationSquared) {
              var ratio = b2_maxTranslation / translation.Length();
              v.Multiply(ratio);
            }
            var rotation = h * w;
            if (rotation * rotation > b2_maxRotationSquared) {
              var ratio = b2_maxRotation / b2Abs(rotation);
              w *= ratio;
            }
            c.Add(b2Vec2.Multiply(h, v));
            a += h * w;
            this.m_positions[i].a = a;
            this.m_velocities[i].w = w;
            var body = this.m_bodies[i];
            body.m_sweep.c.Assign(c);
            body.m_sweep.a = a;
            body.m_linearVelocity.Assign(v);
            body.m_angularVelocity = w;
            body.SynchronizeTransform();
          }
          this.Report(b2Island._solver.m_velocityConstraints);
        },
        AddBody: function(body) {
          b2Assert(this.m_bodyCount < this.m_bodyCapacity);
          body.m_islandIndex = this.m_bodyCount;
          this.m_bodies[this.m_bodyCount] = body;
          if (!this.m_positions[this.m_bodyCount]) {
            this.m_positions[this.m_bodyCount] = new b2Position();
            this.m_velocities[this.m_bodyCount] = new b2Velocity();
          }
          ++this.m_bodyCount;
        },
        AddContact: function(contact) {
          b2Assert(this.m_contactCount < this.m_contactCapacity);
          this.m_contacts[this.m_contactCount++] = contact;
        },
        AddJoint: function(joint) {
          b2Assert(this.m_jointCount < this.m_jointCapacity);
          this.m_joints[this.m_jointCount++] = joint;
        },
        Report: function(constraints) {
          if (null == this.m_listener) return;
          for (var i = 0; i < this.m_contactCount; ++i) {
            var c = this.m_contacts[i];
            var vc = constraints[i];
            var impulse = new b2ContactImpulse();
            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);
          }
        }
      };
      function b2Jacobian() {
        this.linear = new b2Vec2();
        this.angularA = 0;
        this.angularB = 0;
      }
      function b2JointEdge() {
        this.other = null;
        this.joint = null;
        this.prev = null;
        this.next = null;
      }
      function b2JointDef() {
        this.type = b2Joint.e_unknownJoint;
        this.userData = null;
        this.bodyA = null;
        this.bodyB = null;
        this.collideConnected = false;
      }
      b2JointDef.prototype = {
        _deserialize: function(data, bodies, joints) {
          this.bodyA = bodies[data["bodyA"]];
          this.bodyB = bodies[data["bodyB"]];
          this.collideConnected = data["collideConnected"];
        }
      };
      function b2Joint(def) {
        b2Assert(def.bodyA != def.bodyB);
        this.m_type = def.type;
        this.m_prev = null;
        this.m_next = null;
        this.m_bodyA = def.bodyA;
        this.m_bodyB = def.bodyB;
        this.m_index = 0;
        this.m_collideConnected = def.collideConnected;
        this.m_islandFlag = false;
        this.m_userData = def.userData;
        this.m_edgeA = new b2JointEdge();
        this.m_edgeA.joint = null;
        this.m_edgeA.other = null;
        this.m_edgeA.prev = null;
        this.m_edgeA.next = null;
        this.m_edgeB = new b2JointEdge();
        this.m_edgeB.joint = null;
        this.m_edgeB.other = null;
        this.m_edgeB.prev = null;
        this.m_edgeB.next = null;
      }
      b2Joint.prototype = {
        GetType: function() {
          return this.m_type;
        },
        GetBodyA: function() {
          return this.m_bodyA;
        },
        GetBodyB: function() {
          return this.m_bodyB;
        },
        GetAnchorA: function() {},
        GetAnchorB: function() {},
        GetReactionForce: function(inv_dt) {},
        GetReactionTorque: function(inv_dt) {},
        GetNext: function() {
          return this.m_next;
        },
        GetUserData: function() {
          return this.m_userData;
        },
        SetUserData: function(data) {
          this.m_userData = data;
        },
        IsActive: function() {
          return this.m_bodyA.IsActive() && this.m_bodyB.IsActive();
        },
        GetCollideConnected: function() {
          return this.m_collideConnected;
        },
        ShiftOrigin: function(newOrigin) {},
        InitVelocityConstraints: function(data) {},
        SolveVelocityConstraints: function(data) {},
        SolvePositionConstraints: function(data) {},
        _serialize: function(out) {
          var obj = out || {};
          obj["bodyA"] = null;
          obj["bodyB"] = null;
          obj["type"] = this.m_type;
          obj["collideConnected"] = this.m_collideConnected;
          return obj;
        }
      };
      b2Joint.e_inactiveLimit = 0;
      b2Joint.e_atLowerLimit = 1;
      b2Joint.e_atUpperLimit = 2;
      b2Joint.e_equalLimits = 3;
      b2Joint.e_unknownJoint = 0;
      b2Joint.e_revoluteJoint = 1;
      b2Joint.e_prismaticJoint = 2;
      b2Joint.e_distanceJoint = 3;
      b2Joint.e_pulleyJoint = 4;
      b2Joint.e_mouseJoint = 5;
      b2Joint.e_gearJoint = 6;
      b2Joint.e_wheelJoint = 7;
      b2Joint.e_weldJoint = 8;
      b2Joint.e_frictionJoint = 9;
      b2Joint.e_ropeJoint = 10;
      b2Joint.e_motorJoint = 11;
      b2Joint.Create = function(def) {
        var joint = null;
        switch (def.type) {
         case b2Joint.e_distanceJoint:
          joint = new b2DistanceJoint(def);
          break;

         case b2Joint.e_mouseJoint:
          joint = new b2MouseJoint(def);
          break;

         case b2Joint.e_prismaticJoint:
          joint = new b2PrismaticJoint(def);
          break;

         case b2Joint.e_revoluteJoint:
          joint = new b2RevoluteJoint(def);
          break;

         case b2Joint.e_pulleyJoint:
          joint = new b2PulleyJoint(def);
          break;

         case b2Joint.e_gearJoint:
          joint = new b2GearJoint(def);
          break;

         case b2Joint.e_wheelJoint:
          joint = new b2WheelJoint(def);
          break;

         case b2Joint.e_weldJoint:
          joint = new b2WeldJoint(def);
          break;

         case b2Joint.e_frictionJoint:
          joint = new b2FrictionJoint(def);
          break;

         case b2Joint.e_ropeJoint:
          joint = new b2RopeJoint(def);
          break;

         case b2Joint.e_motorJoint:
          joint = new b2MotorJoint(def);
          break;

         default:
          b2Assert(false);
        }
        return joint;
      };
      b2Joint.Destroy = function(joint) {};
      function b2RevoluteJointDef() {
        this.parent.call(this);
        this.type = b2Joint.e_revoluteJoint;
        this.localAnchorA = new b2Vec2();
        this.localAnchorB = new b2Vec2();
        this.referenceAngle = 0;
        this.lowerAngle = 0;
        this.upperAngle = 0;
        this.maxMotorTorque = 0;
        this.motorSpeed = 0;
        this.enableLimit = false;
        this.enableMotor = false;
        Object.seal(this);
      }
      b2RevoluteJointDef.prototype = {
        Initialize: function(bA, bB, anchor) {
          this.bodyA = bA;
          this.bodyB = bB;
          this.localAnchorA = this.bodyA.GetLocalPoint(anchor);
          this.localAnchorB = this.bodyB.GetLocalPoint(anchor);
          this.referenceAngle = this.bodyB.GetAngle() - this.bodyA.GetAngle();
        },
        _deserialize: function(data, bodies, joints) {
          this.parent.prototype._deserialize.call(this, data, bodies, joints);
          this.localAnchorA._deserialize(data["localAnchorA"]);
          this.localAnchorB._deserialize(data["localAnchorB"]);
          this.referenceAngle = data["referenceAngle"];
          this.lowerAngle = data["lowerAngle"];
          this.upperAngle = data["upperAngle"];
          this.maxMotorTorque = data["maxMotorTorque"];
          this.motorSpeed = data["motorSpeed"];
          this.enableLimit = data["enableLimit"];
          this.enableMotor = data["enableMotor"];
        }
      };
      b2RevoluteJointDef._extend(b2JointDef);
      function b2RevoluteJoint(def) {
        this.parent.call(this, def);
        this.m_localAnchorA = def.localAnchorA.Clone();
        this.m_localAnchorB = def.localAnchorB.Clone();
        this.m_referenceAngle = def.referenceAngle;
        this.m_impulse = new b2Vec3();
        this.m_motorImpulse = 0;
        this.m_lowerAngle = def.lowerAngle;
        this.m_upperAngle = def.upperAngle;
        this.m_maxMotorTorque = def.maxMotorTorque;
        this.m_motorSpeed = def.motorSpeed;
        this.m_enableLimit = def.enableLimit;
        this.m_enableMotor = def.enableMotor;
        this.m_limitState = b2Joint.e_inactiveLimit;
        this.m_indexA = 0;
        this.m_indexB = 0;
        this.m_rA = new b2Vec2();
        this.m_rB = new b2Vec2();
        this.m_localCenterA = new b2Vec2();
        this.m_localCenterB = new b2Vec2();
        this.m_invMassA = 0;
        this.m_invMassB = 0;
        this.m_invIA = 0;
        this.m_invIB = 0;
        this.m_mass = new b2Mat33();
        this.m_motorMass = 0;
      }
      b2RevoluteJoint.prototype = {
        GetAnchorA: function() {
          return this.m_bodyA.GetWorldPoint(this.m_localAnchorA);
        },
        GetAnchorB: function() {
          return this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
        },
        GetLocalAnchorA: function() {
          return this.m_localAnchorA;
        },
        GetLocalAnchorB: function() {
          return this.m_localAnchorB;
        },
        GetReferenceAngle: function() {
          return this.m_referenceAngle;
        },
        GetJointAngle: function() {
          var bA = this.m_bodyA;
          var bB = this.m_bodyB;
          return bB.m_sweep.a - bA.m_sweep.a - this.m_referenceAngle;
        },
        GetJointSpeed: function() {
          var bA = this.m_bodyA;
          var bB = this.m_bodyB;
          return bB.m_angularVelocity - bA.m_angularVelocity;
        },
        IsLimitEnabled: function() {
          return this.m_enableLimit;
        },
        EnableLimit: function(flag) {
          if (flag != this.m_enableLimit) {
            this.m_bodyA.SetAwake(true);
            this.m_bodyB.SetAwake(true);
            this.m_enableLimit = flag;
            this.m_impulse.z = 0;
          }
        },
        GetLowerLimit: function() {
          return this.m_lowerAngle;
        },
        GetUpperLimit: function() {
          return this.m_upperAngle;
        },
        SetLimits: function(lower, upper) {
          b2Assert(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;
          }
        },
        IsMotorEnabled: function() {
          return this.m_enableMotor;
        },
        EnableMotor: function(flag) {
          this.m_bodyA.SetAwake(true);
          this.m_bodyB.SetAwake(true);
          this.m_enableMotor = flag;
        },
        SetMotorSpeed: function(speed) {
          this.m_bodyA.SetAwake(true);
          this.m_bodyB.SetAwake(true);
          this.m_motorSpeed = speed;
        },
        GetMotorSpeed: function() {
          return this.m_motorSpeed;
        },
        SetMaxMotorTorque: function(torque) {
          this.m_bodyA.SetAwake(true);
          this.m_bodyB.SetAwake(true);
          this.m_maxMotorTorque = torque;
        },
        GetMaxMotorTorque: function() {
          return this.m_maxMotorTorque;
        },
        GetReactionForce: function(inv_dt) {
          var P = new b2Vec2(this.m_impulse.x, this.m_impulse.y);
          return b2Vec2.Multiply(inv_dt, P);
        },
        GetReactionTorque: function(inv_dt) {
          return inv_dt * this.m_impulse.z;
        },
        GetMotorTorque: function(inv_dt) {
          return inv_dt * this.m_motorImpulse;
        },
        InitVelocityConstraints: function(data) {
          this.m_indexA = this.m_bodyA.m_islandIndex;
          this.m_indexB = this.m_bodyB.m_islandIndex;
          this.m_localCenterA = this.m_bodyA.m_sweep.localCenter;
          this.m_localCenterB = 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.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var aB = data.positions[this.m_indexB].a;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          this.m_rA = b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_localCenterA));
          this.m_rB = b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB));
          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;
          this.m_motorMass > 0 && (this.m_motorMass = 1 / this.m_motorMass);
          (false == this.m_enableMotor || fixedRotation) && (this.m_motorImpulse = 0);
          if (this.m_enableLimit && false == fixedRotation) {
            var jointAngle = aB - aA - this.m_referenceAngle;
            if (b2Abs(this.m_upperAngle - this.m_lowerAngle) < 2 * b2_angularSlop) this.m_limitState = b2Joint.e_equalLimits; else if (jointAngle <= this.m_lowerAngle) {
              this.m_limitState != b2Joint.e_atLowerLimit && (this.m_impulse.z = 0);
              this.m_limitState = b2Joint.e_atLowerLimit;
            } else if (jointAngle >= this.m_upperAngle) {
              this.m_limitState != b2Joint.e_atUpperLimit && (this.m_impulse.z = 0);
              this.m_limitState = b2Joint.e_atUpperLimit;
            } else {
              this.m_limitState = b2Joint.e_inactiveLimit;
              this.m_impulse.z = 0;
            }
          } else this.m_limitState = b2Joint.e_inactiveLimit;
          if (data.step.warmStarting) {
            this.m_impulse.Multiply(data.step.dtRatio);
            this.m_motorImpulse *= data.step.dtRatio;
            var P = new b2Vec2(this.m_impulse.x, this.m_impulse.y);
            vA.Subtract(b2Vec2.Multiply(mA, P));
            wA -= iA * (b2Cross_v2_v2(this.m_rA, P) + this.m_motorImpulse + this.m_impulse.z);
            vB.Add(b2Vec2.Multiply(mB, P));
            wB += iB * (b2Cross_v2_v2(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].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolveVelocityConstraints: function(data) {
          var vA = data.velocities[this.m_indexA].v.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var vB = data.velocities[this.m_indexB].v.Clone();
          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 != b2Joint.e_equalLimits && false == 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 != b2Joint.e_inactiveLimit && false == fixedRotation) {
            var Cdot1 = b2Vec2.Subtract(b2Vec2.Subtract(b2Vec2.Add(vB, b2Cross_f_v2(wB, this.m_rB)), vA), b2Cross_f_v2(wA, this.m_rA));
            var Cdot2 = wB - wA;
            var Cdot = new b2Vec3(Cdot1.x, Cdot1.y, Cdot2);
            var impulse = this.m_mass.Solve33(Cdot).Negate();
            if (this.m_limitState == b2Joint.e_equalLimits) this.m_impulse.Add(impulse); else if (this.m_limitState == b2Joint.e_atLowerLimit) {
              var newImpulse = this.m_impulse.z + impulse.z;
              if (newImpulse < 0) {
                var rhs = b2Vec2.Add(Cdot1.Negate(), b2Vec2.Multiply(this.m_impulse.z, new b2Vec2(this.m_mass.ez.x, this.m_mass.ez.y)));
                var reduced = this.m_mass.Solve22(rhs);
                impulse.x = reduced.x;
                impulse.y = reduced.y;
                impulse.z = -this.m_impulse.z;
                this.m_impulse.x += reduced.x;
                this.m_impulse.y += reduced.y;
                this.m_impulse.z = 0;
              } else this.m_impulse.Add(impulse);
            } else if (this.m_limitState == b2Joint.e_atUpperLimit) {
              var newImpulse = this.m_impulse.z + impulse.z;
              if (newImpulse > 0) {
                var rhs = b2Vec2.Add(Cdot1.Negate(), b2Vec2.Multiply(this.m_impulse.z, new b2Vec2(this.m_mass.ez.x, this.m_mass.ez.y)));
                var reduced = this.m_mass.Solve22(rhs);
                impulse.x = reduced.x;
                impulse.y = reduced.y;
                impulse.z = -this.m_impulse.z;
                this.m_impulse.x += reduced.x;
                this.m_impulse.y += reduced.y;
                this.m_impulse.z = 0;
              } else this.m_impulse.Add(impulse);
            }
            var P = new b2Vec2(impulse.x, impulse.y);
            vA.Subtract(b2Vec2.Multiply(mA, P));
            wA -= iA * (b2Cross_v2_v2(this.m_rA, P) + impulse.z);
            vB.Add(b2Vec2.Multiply(mB, P));
            wB += iB * (b2Cross_v2_v2(this.m_rB, P) + impulse.z);
          } else {
            var Cdot = b2Vec2.Subtract(b2Vec2.Subtract(b2Vec2.Add(vB, b2Cross_f_v2(wB, this.m_rB)), vA), b2Cross_f_v2(wA, this.m_rA));
            var impulse = this.m_mass.Solve22(Cdot.Negate());
            this.m_impulse.x += impulse.x;
            this.m_impulse.y += impulse.y;
            vA.Subtract(b2Vec2.Multiply(mA, impulse));
            wA -= iA * b2Cross_v2_v2(this.m_rA, impulse);
            vB.Add(b2Vec2.Multiply(mB, impulse));
            wB += iB * b2Cross_v2_v2(this.m_rB, impulse);
          }
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolvePositionConstraints: function(data) {
          var cA = data.positions[this.m_indexA].c.Clone();
          var aA = data.positions[this.m_indexA].a;
          var cB = data.positions[this.m_indexB].c.Clone();
          var aB = data.positions[this.m_indexB].a;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          var angularError = 0;
          var positionError = 0;
          var fixedRotation = this.m_invIA + this.m_invIB == 0;
          if (this.m_enableLimit && this.m_limitState != b2Joint.e_inactiveLimit && false == fixedRotation) {
            var angle = aB - aA - this.m_referenceAngle;
            var limitImpulse = 0;
            if (this.m_limitState == b2Joint.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 == b2Joint.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 == b2Joint.e_atUpperLimit) {
              var C = angle - this.m_upperAngle;
              angularError = C;
              C = b2Clamp(C - b2_angularSlop, 0, b2_maxAngularCorrection);
              limitImpulse = -this.m_motorMass * C;
            }
            aA -= this.m_invIA * limitImpulse;
            aB += this.m_invIB * limitImpulse;
          }
          qA.Set(aA);
          qB.Set(aB);
          var rA = b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_localCenterA));
          var rB = b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB));
          var C = b2Vec2.Subtract(b2Vec2.Subtract(b2Vec2.Add(cB, rB), cA), rA);
          positionError = C.Length();
          var mA = this.m_invMassA, mB = this.m_invMassB;
          var iA = this.m_invIA, iB = this.m_invIB;
          var K = new b2Mat22();
          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).Negate();
          cA.Subtract(b2Vec2.Multiply(mA, impulse));
          aA -= iA * b2Cross_v2_v2(rA, impulse);
          cB.Add(b2Vec2.Multiply(mB, impulse));
          aB += iB * b2Cross_v2_v2(rB, impulse);
          data.positions[this.m_indexA].c.Assign(cA);
          data.positions[this.m_indexA].a = aA;
          data.positions[this.m_indexB].c.Assign(cB);
          data.positions[this.m_indexB].a = aB;
          return positionError <= b2_linearSlop && angularError <= b2_angularSlop;
        },
        _serialize: function(out) {
          var obj = out || {};
          this.parent.prototype._serialize.call(this, obj);
          obj["localAnchorA"] = this.m_localAnchorA._serialize();
          obj["localAnchorB"] = this.m_localAnchorB._serialize();
          obj["referenceAngle"] = this.m_referenceAngle;
          obj["lowerAngle"] = this.m_lowerAngle;
          obj["upperAngle"] = this.m_upperAngle;
          obj["maxMotorTorque"] = this.m_maxMotorTorque;
          obj["motorSpeed"] = this.m_motorSpeed;
          obj["enableLimit"] = this.m_enableLimit;
          obj["enableMotor"] = this.m_enableMotor;
          return obj;
        }
      };
      b2RevoluteJoint._extend(b2Joint);
      function b2MouseJointDef() {
        this.parent.call(this);
        this.type = b2Joint.e_mouseJoint;
        this.target = new b2Vec2(0, 0);
        this.maxForce = 0;
        this.frequencyHz = 5;
        this.dampingRatio = .7;
        Object.seal(this);
      }
      b2MouseJointDef._extend(b2JointDef);
      function b2MouseJoint(def) {
        this.parent.call(this, def);
        b2Assert(def.target.IsValid());
        b2Assert(b2IsValid(def.maxForce) && def.maxForce >= 0);
        b2Assert(b2IsValid(def.frequencyHz) && def.frequencyHz >= 0);
        b2Assert(b2IsValid(def.dampingRatio) && def.dampingRatio >= 0);
        this.m_targetA = def.target.Clone();
        this.m_localAnchorB = b2MulT_t_v2(this.m_bodyB.GetTransform(), this.m_targetA);
        this.m_maxForce = def.maxForce;
        this.m_impulse = new b2Vec2();
        this.m_frequencyHz = def.frequencyHz;
        this.m_dampingRatio = def.dampingRatio;
        this.m_beta = 0;
        this.m_gamma = 0;
        this.m_indexA = 0;
        this.m_indexB = 0;
        this.m_rB = new b2Vec2();
        this.m_localCenterB = new b2Vec2();
        this.m_invMassB = 0;
        this.m_invIB = 0;
        this.m_mass = new b2Mat22();
        this.m_C = new b2Vec2();
      }
      b2MouseJoint.prototype = {
        GetAnchorA: function() {
          return this.m_targetA;
        },
        GetAnchorB: function() {
          return this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
        },
        GetReactionForce: function(inv_dt) {
          return b2Vec2.Multiply(inv_dt, this.m_impulse);
        },
        GetReactionTorque: function(inv_dt) {
          return 0 * inv_dt;
        },
        SetTarget: function(target) {
          false == this.m_bodyB.IsAwake() && this.m_bodyB.SetAwake(true);
          this.m_targetA.Assign(target);
        },
        GetTarget: function() {
          return this.m_targetA;
        },
        SetMaxForce: function(force) {
          this.m_maxForce = force;
        },
        GetMaxForce: function() {
          return this.m_maxForce;
        },
        SetFrequency: function(hz) {
          this.m_frequencyHz = hz;
        },
        GetFrequency: function() {
          return this.m_frequencyHz;
        },
        SetDampingRatio: function(ratio) {
          this.m_dampingRatio = ratio;
        },
        GetDampingRatio: function() {
          return this.m_dampingRatio;
        },
        ShiftOrigin: function(newOrigin) {
          this.m_targetA.Subtract(newOrigin);
        },
        InitVelocityConstraints: function(data) {
          this.m_indexB = this.m_bodyB.m_islandIndex;
          this.m_localCenterB.Assign(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.Clone();
          var aB = data.positions[this.m_indexB].a;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var qB = new b2Rot(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;
          b2Assert(d + h * k > b2_epsilon);
          this.m_gamma = h * (d + h * k);
          0 != this.m_gamma && (this.m_gamma = 1 / this.m_gamma);
          this.m_beta = h * k * this.m_gamma;
          this.m_rB.Assign(b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB)));
          var K = new b2Mat22();
          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;
          this.m_mass.Assign(K.GetInverse());
          this.m_C.Assign(b2Vec2.Subtract(b2Vec2.Add(cB, this.m_rB), this.m_targetA));
          this.m_C.Multiply(this.m_beta);
          wB *= .98;
          if (data.step.warmStarting) {
            this.m_impulse.Multiply(data.step.dtRatio);
            vB.Add(b2Vec2.Multiply(this.m_invMassB, this.m_impulse));
            wB += this.m_invIB * b2Cross_v2_v2(this.m_rB, this.m_impulse);
          } else this.m_impulse.SetZero();
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolveVelocityConstraints: function(data) {
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var Cdot = b2Vec2.Add(vB, b2Cross_f_v2(wB, this.m_rB));
          var impulse = b2Mul_m22_v2(this.m_mass, b2Vec2.Add(b2Vec2.Add(Cdot, this.m_C), b2Vec2.Multiply(this.m_gamma, this.m_impulse)).Negate());
          var oldImpulse = this.m_impulse.Clone();
          this.m_impulse.Add(impulse);
          var maxImpulse = data.step.dt * this.m_maxForce;
          this.m_impulse.LengthSquared() > maxImpulse * maxImpulse && this.m_impulse.Multiply(maxImpulse / this.m_impulse.Length());
          impulse.Assign(b2Vec2.Subtract(this.m_impulse, oldImpulse));
          vB.Add(b2Vec2.Multiply(this.m_invMassB, impulse));
          wB += this.m_invIB * b2Cross_v2_v2(this.m_rB, impulse);
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolvePositionConstraints: function(data) {
          return true;
        }
      };
      b2MouseJoint._extend(b2Joint);
      function b2DistanceJointDef() {
        this.parent.call(this);
        this.type = b2Joint.e_distanceJoint;
        this.localAnchorA = new b2Vec2(0, 0);
        this.localAnchorB = new b2Vec2(0, 0);
        this.length = 1;
        this.frequencyHz = 0;
        this.dampingRatio = 0;
        Object.seal(this);
      }
      b2DistanceJointDef.prototype = {
        Initialize: function(b1, b2, anchor1, anchor2) {
          this.bodyA = b1;
          this.bodyB = b2;
          this.localAnchorA = this.bodyA.GetLocalPoint(anchor1);
          this.localAnchorB = this.bodyB.GetLocalPoint(anchor2);
          var d = b2Vec2.Subtract(anchor2, anchor1);
          this.length = d.Length();
        },
        _deserialize: function(data, bodies, joints) {
          this.parent.prototype._deserialize.call(this, data, bodies, joints);
          this.localAnchorA._deserialize(data["localAnchorA"]);
          this.localAnchorB._deserialize(data["localAnchorB"]);
          this.length = data["length"];
          this.frequencyHz = data["frequencyHz"];
          this.dampingRatio = data["dampingRatio"];
        }
      };
      b2DistanceJointDef._extend(b2JointDef);
      function b2DistanceJoint(def) {
        this.parent.call(this, def);
        this.m_localAnchorA = def.localAnchorA.Clone();
        this.m_localAnchorB = def.localAnchorB.Clone();
        this.m_length = def.length;
        this.m_frequencyHz = def.frequencyHz;
        this.m_dampingRatio = def.dampingRatio;
        this.m_impulse = 0;
        this.m_gamma = 0;
        this.m_bias = 0;
        this.m_indexA = 0;
        this.m_indexB = 0;
        this.m_u = new b2Vec2();
        this.m_rA = new b2Vec2();
        this.m_rB = new b2Vec2();
        this.m_localCenterA = new b2Vec2();
        this.m_localCenterB = new b2Vec2();
        this.m_invMassA = 0;
        this.m_invMassB = 0;
        this.m_invIA = 0;
        this.m_invIB = 0;
        this.m_mass = 0;
      }
      b2DistanceJoint.prototype = {
        GetAnchorA: function() {
          return this.m_bodyA.GetWorldPoint(this.m_localAnchorA);
        },
        GetAnchorB: function() {
          return this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
        },
        GetReactionForce: function(inv_dt) {
          var F = b2Vec2.Multiply(inv_dt * this.m_impulse, this.m_u);
          return F;
        },
        GetReactionTorque: function(inv_dt) {
          return 0;
        },
        GetLocalAnchorA: function() {
          return this.m_localAnchorA;
        },
        GetLocalAnchorB: function() {
          return this.m_localAnchorB;
        },
        SetLength: function(length) {
          this.m_length = length;
        },
        GetLength: function() {
          return this.m_length;
        },
        SetFrequency: function(hz) {
          this.m_frequencyHz = hz;
        },
        GetFrequency: function() {
          return this.m_frequencyHz;
        },
        SetDampingRatio: function(ratio) {
          this.m_dampingRatio = ratio;
        },
        GetDampingRatio: function() {
          return this.m_dampingRatio;
        },
        InitVelocityConstraints: function(data) {
          this.m_indexA = this.m_bodyA.m_islandIndex;
          this.m_indexB = this.m_bodyB.m_islandIndex;
          this.m_localCenterA.Assign(this.m_bodyA.m_sweep.localCenter);
          this.m_localCenterB.Assign(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.Clone();
          var aA = data.positions[this.m_indexA].a;
          var vA = data.velocities[this.m_indexA].v.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var cB = data.positions[this.m_indexB].c.Clone();
          var aB = data.positions[this.m_indexB].a;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          this.m_rA = b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_localCenterA));
          this.m_rB = b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB));
          this.m_u = b2Vec2.Subtract(b2Vec2.Subtract(b2Vec2.Add(cB, this.m_rB), cA), this.m_rA);
          var length = this.m_u.Length();
          length > b2_linearSlop ? this.m_u.Multiply(1 / length) : this.m_u.Set(0, 0);
          var crAu = b2Cross_v2_v2(this.m_rA, this.m_u);
          var crBu = b2Cross_v2_v2(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 = 0 != invMass ? 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 = 0 != this.m_gamma ? 1 / this.m_gamma : 0;
            this.m_bias = C * h * k * this.m_gamma;
            invMass += this.m_gamma;
            this.m_mass = 0 != invMass ? 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.Multiply(this.m_impulse, this.m_u);
            vA.Subtract(b2Vec2.Multiply(this.m_invMassA, P));
            wA -= this.m_invIA * b2Cross_v2_v2(this.m_rA, P);
            vB.Add(b2Vec2.Multiply(this.m_invMassB, P));
            wB += this.m_invIB * b2Cross_v2_v2(this.m_rB, P);
          } else this.m_impulse = 0;
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolveVelocityConstraints: function(data) {
          var vA = data.velocities[this.m_indexA].v.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var vpA = b2Vec2.Add(vA, b2Cross_f_v2(wA, this.m_rA));
          var vpB = b2Vec2.Add(vB, b2Cross_f_v2(wB, this.m_rB));
          var Cdot = b2Dot_v2_v2(this.m_u, b2Vec2.Subtract(vpB, vpA));
          var impulse = -this.m_mass * (Cdot + this.m_bias + this.m_gamma * this.m_impulse);
          this.m_impulse += impulse;
          var P = b2Vec2.Multiply(impulse, this.m_u);
          vA.Subtract(b2Vec2.Multiply(this.m_invMassA, P));
          wA -= this.m_invIA * b2Cross_v2_v2(this.m_rA, P);
          vB.Add(b2Vec2.Multiply(this.m_invMassB, P));
          wB += this.m_invIB * b2Cross_v2_v2(this.m_rB, P);
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolvePositionConstraints: function(data) {
          if (this.m_frequencyHz > 0) return true;
          var cA = data.positions[this.m_indexA].c.Clone();
          var aA = data.positions[this.m_indexA].a;
          var cB = data.positions[this.m_indexB].c.Clone();
          var aB = data.positions[this.m_indexB].a;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          var rA = b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_localCenterA));
          var rB = b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB));
          var u = b2Vec2.Subtract(b2Vec2.Subtract(b2Vec2.Add(cB, rB), cA), rA);
          var length = u.Normalize();
          var C = length - this.m_length;
          C = b2Clamp(C, -b2_maxLinearCorrection, b2_maxLinearCorrection);
          var impulse = -this.m_mass * C;
          var P = b2Vec2.Multiply(impulse, u);
          cA.Subtract(b2Vec2.Multiply(this.m_invMassA, P));
          aA -= this.m_invIA * b2Cross_v2_v2(rA, P);
          cB.Add(b2Vec2.Multiply(this.m_invMassB, P));
          aB += this.m_invIB * b2Cross_v2_v2(rB, P);
          data.positions[this.m_indexA].c.Assign(cA);
          data.positions[this.m_indexA].a = aA;
          data.positions[this.m_indexB].c.Assign(cB);
          data.positions[this.m_indexB].a = aB;
          return b2Abs(C) < b2_linearSlop;
        },
        _serialize: function(out) {
          var obj = out || {};
          this.parent.prototype._serialize.call(this, obj);
          obj["localAnchorA"] = this.m_localAnchorA._serialize();
          obj["localAnchorB"] = this.m_localAnchorB._serialize();
          obj["length"] = this.m_length;
          obj["frequencyHz"] = this.m_frequencyHz;
          obj["dampingRatio"] = this.m_dampingRatio;
          return obj;
        }
      };
      b2DistanceJoint._extend(b2Joint);
      function b2PrismaticJointDef() {
        this.parent.call(this);
        this.type = b2Joint.e_prismaticJoint;
        this.localAnchorA = new b2Vec2();
        this.localAnchorB = new b2Vec2();
        this.localAxisA = new b2Vec2(1, 0);
        this.referenceAngle = 0;
        this.enableLimit = false;
        this.lowerTranslation = 0;
        this.upperTranslation = 0;
        this.enableMotor = false;
        this.maxMotorForce = 0;
        this.motorSpeed = 0;
        Object.seal(this);
      }
      b2PrismaticJointDef.prototype = {
        Initialize: function(bA, bB, anchor, axis) {
          this.bodyA = bA;
          this.bodyB = bB;
          this.localAnchorA = this.bodyA.GetLocalPoint(anchor);
          this.localAnchorB = this.bodyB.GetLocalPoint(anchor);
          this.localAxisA = this.bodyA.GetLocalVector(axis);
          this.referenceAngle = this.bodyB.GetAngle() - this.bodyA.GetAngle();
        },
        _deserialize: function(data, bodies, joints) {
          this.parent.prototype._deserialize.call(this, data, bodies, joints);
          this.localAnchorA._deserialize(data["localAnchorA"]);
          this.localAnchorB._deserialize(data["localAnchorB"]);
          this.localAxisA._deserialize(data["localAxisA"]);
          this.referenceAngle = data["referenceAngle"];
          this.enableLimit = data["enableLimit"];
          this.lowerTranslation = data["lowerTranslation"];
          this.upperTranslation = data["upperTranslation"];
          this.enableMotor = data["enableMotor"];
          this.maxMotorForce = data["maxMotorForce"];
          this.motorSpeed = data["motorSpeed"];
        }
      };
      b2PrismaticJointDef._extend(b2JointDef);
      function b2PrismaticJoint(def) {
        this.parent.call(this, def);
        this.m_localAnchorA = def.localAnchorA.Clone();
        this.m_localAnchorB = def.localAnchorB.Clone();
        this.m_localXAxisA = def.localAxisA.Clone();
        this.m_localXAxisA.Normalize();
        this.m_localYAxisA = b2Cross_f_v2(1, this.m_localXAxisA);
        this.m_referenceAngle = def.referenceAngle;
        this.m_impulse = new b2Vec3();
        this.m_motorMass = 0;
        this.m_motorImpulse = 0;
        this.m_lowerTranslation = def.lowerTranslation;
        this.m_upperTranslation = def.upperTranslation;
        this.m_maxMotorForce = def.maxMotorForce;
        this.m_motorSpeed = def.motorSpeed;
        this.m_enableLimit = def.enableLimit;
        this.m_enableMotor = def.enableMotor;
        this.m_limitState = b2Joint.e_inactiveLimit;
        this.m_axis = new b2Vec2();
        this.m_perp = new b2Vec2();
        this.m_indexA = 0;
        this.m_indexB = 0;
        this.m_localCenterA = new b2Vec2();
        this.m_localCenterB = new b2Vec2();
        this.m_invMassA = 0;
        this.m_invMassB = 0;
        this.m_invIA = 0;
        this.m_invIB = 0;
        this.m_s1 = 0, this.m_s2 = 0;
        this.m_a1 = 0, this.m_a2 = 0;
        this.m_K = new b2Mat33();
        this.m_motorMass = 0;
      }
      b2PrismaticJoint.prototype = {
        GetAnchorA: function() {
          return this.m_bodyA.GetWorldPoint(this.m_localAnchorA);
        },
        GetAnchorB: function() {
          return this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
        },
        GetReactionForce: function(inv_dt) {
          return b2Vec2.Multiply(inv_dt, b2Vec2.Add(b2Vec2.Multiply(this.m_impulse.x, this.m_perp), b2Vec2.Multiply(this.m_motorImpulse + this.m_impulse.z, this.m_axis)));
        },
        GetReactionTorque: function(inv_dt) {
          return inv_dt * this.m_impulse.y;
        },
        GetLocalAnchorA: function() {
          return this.m_localAnchorA;
        },
        GetLocalAnchorB: function() {
          return this.m_localAnchorB;
        },
        GetLocalAxisA: function() {
          return this.m_localXAxisA;
        },
        GetReferenceAngle: function() {
          return this.m_referenceAngle;
        },
        GetJointTranslation: function() {
          var pA = this.m_bodyA.GetWorldPoint(this.m_localAnchorA);
          var pB = this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
          var d = b2Vec2.Subtract(pB, pA);
          var axis = this.m_bodyA.GetWorldVector(this.m_localXAxisA);
          var translation = b2Dot_v2_v2(d, axis);
          return translation;
        },
        GetJointSpeed: function() {
          var bA = this.m_bodyA;
          var bB = this.m_bodyB;
          var rA = b2Mul_r_v2(bA.m_xf.q, b2Vec2.Subtract(this.m_localAnchorA, bA.m_sweep.localCenter));
          var rB = b2Mul_r_v2(bB.m_xf.q, b2Vec2.Subtract(this.m_localAnchorB, bB.m_sweep.localCenter));
          var p1 = b2Vec2.Add(bA.m_sweep.c, rA);
          var p2 = b2Vec2.Add(bB.m_sweep.c, rB);
          var d = b2Vec2.Subtract(p2, p1);
          var axis = b2Mul_r_v2(bA.m_xf.q, this.m_localXAxisA);
          var vA = bA.m_linearVelocity;
          var vB = bB.m_linearVelocity;
          var wA = bA.m_angularVelocity;
          var wB = bB.m_angularVelocity;
          var speed = b2Dot_v2_v2(d, b2Cross_f_v2(wA, axis)) + b2Dot_v2_v2(axis, b2Vec2.Subtract(b2Vec2.Subtract(b2Vec2.Add(vB, b2Cross_f_v2(wB, rB)), vA), b2Cross_f_v2(wA, rA)));
          return speed;
        },
        IsLimitEnabled: function() {
          return this.m_enableLimit;
        },
        EnableLimit: function(flag) {
          if (flag != this.m_enableLimit) {
            this.m_bodyA.SetAwake(true);
            this.m_bodyB.SetAwake(true);
            this.m_enableLimit = flag;
            this.m_impulse.z = 0;
          }
        },
        GetLowerLimit: function() {
          return this.m_lowerTranslation;
        },
        GetUpperLimit: function() {
          return this.m_upperTranslation;
        },
        SetLimits: function(lower, upper) {
          b2Assert(lower <= upper);
          if (lower != this.m_lowerTranslation || upper != this.m_upperTranslation) {
            this.m_bodyA.SetAwake(true);
            this.m_bodyB.SetAwake(true);
            this.m_lowerTranslation = lower;
            this.m_upperTranslation = upper;
            this.m_impulse.z = 0;
          }
        },
        IsMotorEnabled: function() {
          return this.m_enableMotor;
        },
        EnableMotor: function(flag) {
          this.m_bodyA.SetAwake(true);
          this.m_bodyB.SetAwake(true);
          this.m_enableMotor = flag;
        },
        SetMotorSpeed: function(speed) {
          this.m_bodyA.SetAwake(true);
          this.m_bodyB.SetAwake(true);
          this.m_motorSpeed = speed;
        },
        GetMotorSpeed: function() {
          return this.m_motorSpeed;
        },
        SetMaxMotorForce: function(force) {
          this.m_bodyA.SetAwake(true);
          this.m_bodyB.SetAwake(true);
          this.m_maxMotorForce = force;
        },
        GetMaxMotorForce: function() {
          return this.m_maxMotorForce;
        },
        GetMotorForce: function(inv_dt) {
          return inv_dt * this.m_motorImpulse;
        },
        InitVelocityConstraints: function(data) {
          this.m_indexA = this.m_bodyA.m_islandIndex;
          this.m_indexB = this.m_bodyB.m_islandIndex;
          this.m_localCenterA = this.m_bodyA.m_sweep.localCenter;
          this.m_localCenterB = 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.Clone();
          var aA = data.positions[this.m_indexA].a;
          var vA = data.velocities[this.m_indexA].v.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var cB = data.positions[this.m_indexB].c.Clone();
          var aB = data.positions[this.m_indexB].a;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          var rA = b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_localCenterA));
          var rB = b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB));
          var d = b2Vec2.Add(b2Vec2.Subtract(cB, cA), b2Vec2.Subtract(rB, rA));
          var mA = this.m_invMassA, mB = this.m_invMassB;
          var iA = this.m_invIA, iB = this.m_invIB;
          this.m_axis = b2Mul_r_v2(qA, this.m_localXAxisA);
          this.m_a1 = b2Cross_v2_v2(b2Vec2.Add(d, rA), this.m_axis);
          this.m_a2 = b2Cross_v2_v2(rB, this.m_axis);
          this.m_motorMass = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2;
          this.m_motorMass > 0 && (this.m_motorMass = 1 / this.m_motorMass);
          this.m_perp = b2Mul_r_v2(qA, this.m_localYAxisA);
          this.m_s1 = b2Cross_v2_v2(b2Vec2.Add(d, rA), this.m_perp);
          this.m_s2 = b2Cross_v2_v2(rB, this.m_perp);
          var k11 = mA + mB + iA * this.m_s1 * this.m_s1 + iB * this.m_s2 * this.m_s2;
          var k12 = iA * this.m_s1 + iB * this.m_s2;
          var k13 = iA * this.m_s1 * this.m_a1 + iB * this.m_s2 * this.m_a2;
          var k22 = iA + iB;
          0 == k22 && (k22 = 1);
          var k23 = iA * this.m_a1 + iB * this.m_a2;
          var k33 = mA + mB + iA * this.m_a1 * this.m_a1 + iB * this.m_a2 * this.m_a2;
          this.m_K.ex.Set(k11, k12, k13);
          this.m_K.ey.Set(k12, k22, k23);
          this.m_K.ez.Set(k13, k23, k33);
          if (this.m_enableLimit) {
            var jointTranslation = b2Dot_v2_v2(this.m_axis, d);
            if (b2Abs(this.m_upperTranslation - this.m_lowerTranslation) < 2 * b2_linearSlop) this.m_limitState = b2Joint.e_equalLimits; else if (jointTranslation <= this.m_lowerTranslation) {
              if (this.m_limitState != b2Joint.e_atLowerLimit) {
                this.m_limitState = b2Joint.e_atLowerLimit;
                this.m_impulse.z = 0;
              }
            } else if (jointTranslation >= this.m_upperTranslation) {
              if (this.m_limitState != b2Joint.e_atUpperLimit) {
                this.m_limitState = b2Joint.e_atUpperLimit;
                this.m_impulse.z = 0;
              }
            } else {
              this.m_limitState = b2Joint.e_inactiveLimit;
              this.m_impulse.z = 0;
            }
          } else {
            this.m_limitState = b2Joint.e_inactiveLimit;
            this.m_impulse.z = 0;
          }
          false == this.m_enableMotor && (this.m_motorImpulse = 0);
          if (data.step.warmStarting) {
            this.m_impulse.Multiply(data.step.dtRatio);
            this.m_motorImpulse *= data.step.dtRatio;
            var P = b2Vec2.Add(b2Vec2.Multiply(this.m_impulse.x, this.m_perp), b2Vec2.Multiply(this.m_motorImpulse + this.m_impulse.z, this.m_axis));
            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.Subtract(b2Vec2.Multiply(mA, P));
            wA -= iA * LA;
            vB.Add(b2Vec2.Multiply(mB, P));
            wB += iB * LB;
          } else {
            this.m_impulse.SetZero();
            this.m_motorImpulse = 0;
          }
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolveVelocityConstraints: function(data) {
          var vA = data.velocities[this.m_indexA].v.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var vB = data.velocities[this.m_indexB].v.Clone();
          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 != b2Joint.e_equalLimits) {
            var Cdot = b2Dot_v2_v2(this.m_axis, b2Vec2.Subtract(vB, vA)) + 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.Multiply(impulse, this.m_axis);
            var LA = impulse * this.m_a1;
            var LB = impulse * this.m_a2;
            vA.Subtract(b2Vec2.Multiply(mA, P));
            wA -= iA * LA;
            vB.Add(b2Vec2.Multiply(mB, P));
            wB += iB * LB;
          }
          var Cdot1 = new b2Vec2();
          Cdot1.x = b2Dot_v2_v2(this.m_perp, b2Vec2.Subtract(vB, vA)) + this.m_s2 * wB - this.m_s1 * wA;
          Cdot1.y = wB - wA;
          if (this.m_enableLimit && this.m_limitState != b2Joint.e_inactiveLimit) {
            var Cdot2;
            Cdot2 = b2Dot_v2_v2(this.m_axis, b2Vec2.Subtract(vB, vA)) + this.m_a2 * wB - this.m_a1 * wA;
            var Cdot = new b2Vec3(Cdot1.x, Cdot1.y, Cdot2);
            var f1 = this.m_impulse.Clone();
            var df = this.m_K.Solve33(Cdot.Negate());
            this.m_impulse.Add(df);
            this.m_limitState == b2Joint.e_atLowerLimit ? this.m_impulse.z = b2Max(this.m_impulse.z, 0) : this.m_limitState == b2Joint.e_atUpperLimit && (this.m_impulse.z = b2Min(this.m_impulse.z, 0));
            var b = b2Vec2.Subtract(Cdot1.Negate(), b2Vec2.Multiply(this.m_impulse.z - f1.z, new b2Vec2(this.m_K.ez.x, this.m_K.ez.y)));
            var f2r = b2Vec2.Add(this.m_K.Solve22(b), new b2Vec2(f1.x, f1.y));
            this.m_impulse.x = f2r.x;
            this.m_impulse.y = f2r.y;
            df = b2Vec3.Subtract(this.m_impulse, f1);
            var P = b2Vec2.Add(b2Vec2.Multiply(df.x, this.m_perp), b2Vec2.Multiply(df.z, this.m_axis));
            var LA = df.x * this.m_s1 + df.y + df.z * this.m_a1;
            var LB = df.x * this.m_s2 + df.y + df.z * this.m_a2;
            vA.Subtract(b2Vec2.Multiply(mA, P));
            wA -= iA * LA;
            vB.Add(b2Vec2.Multiply(mB, P));
            wB += iB * LB;
          } else {
            var df = this.m_K.Solve22(Cdot1.Negate());
            this.m_impulse.x += df.x;
            this.m_impulse.y += df.y;
            var P = b2Vec2.Multiply(df.x, this.m_perp);
            var LA = df.x * this.m_s1 + df.y;
            var LB = df.x * this.m_s2 + df.y;
            vA.Subtract(b2Vec2.Multiply(mA, P));
            wA -= iA * LA;
            vB.Add(b2Vec2.Multiply(mB, P));
            wB += iB * LB;
          }
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolvePositionConstraints: function(data) {
          var cA = data.positions[this.m_indexA].c.Clone();
          var aA = data.positions[this.m_indexA].a;
          var cB = data.positions[this.m_indexB].c.Clone();
          var aB = data.positions[this.m_indexB].a;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          var mA = this.m_invMassA, mB = this.m_invMassB;
          var iA = this.m_invIA, iB = this.m_invIB;
          var rA = b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_localCenterA));
          var rB = b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB));
          var d = b2Vec2.Subtract(b2Vec2.Subtract(b2Vec2.Add(cB, rB), cA), rA);
          var axis = b2Mul_r_v2(qA, this.m_localXAxisA);
          var a1 = b2Cross_v2_v2(b2Vec2.Add(d, rA), axis);
          var a2 = b2Cross_v2_v2(rB, axis);
          var perp = b2Mul_r_v2(qA, this.m_localYAxisA);
          var s1 = b2Cross_v2_v2(b2Vec2.Add(d, rA), perp);
          var s2 = b2Cross_v2_v2(rB, perp);
          var impulse = new b2Vec3();
          var C1 = new b2Vec2();
          C1.x = b2Dot_v2_v2(perp, d);
          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 = b2Dot_v2_v2(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;
            0 == k22 && (k22 = 1);
            var k23 = iA * a1 + iB * a2;
            var k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2;
            var K = new b2Mat33();
            K.ex.Set(k11, k12, k13);
            K.ey.Set(k12, k22, k23);
            K.ez.Set(k13, k23, k33);
            var C = new b2Vec3();
            C.x = C1.x;
            C.y = C1.y;
            C.z = C2;
            impulse = K.Solve33(C.Negate());
          } else {
            var k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2;
            var k12 = iA * s1 + iB * s2;
            var k22 = iA + iB;
            0 == k22 && (k22 = 1);
            var K = new b2Mat22();
            K.ex.Set(k11, k12);
            K.ey.Set(k12, k22);
            var impulse1 = K.Solve(C1.Negate());
            impulse.x = impulse1.x;
            impulse.y = impulse1.y;
            impulse.z = 0;
          }
          var P = b2Vec2.Add(b2Vec2.Multiply(impulse.x, perp), b2Vec2.Multiply(impulse.z, axis));
          var LA = impulse.x * s1 + impulse.y + impulse.z * a1;
          var LB = impulse.x * s2 + impulse.y + impulse.z * a2;
          cA.Subtract(b2Vec2.Multiply(mA, P));
          aA -= iA * LA;
          cB.Add(b2Vec2.Multiply(mB, P));
          aB += iB * LB;
          data.positions[this.m_indexA].c.Assign(cA);
          data.positions[this.m_indexA].a = aA;
          data.positions[this.m_indexB].c.Assign(cB);
          data.positions[this.m_indexB].a = aB;
          return linearError <= b2_linearSlop && angularError <= b2_angularSlop;
        },
        _serialize: function(out) {
          var obj = out || {};
          this.parent.prototype._serialize.call(this, obj);
          obj["localAnchorA"] = this.m_localAnchorA._serialize();
          obj["localAnchorB"] = this.m_localAnchorB._serialize();
          obj["localAxisA"] = this.m_localXAxisA._serialize();
          obj["referenceAngle"] = this.m_referenceAngle;
          obj["enableLimit"] = this.m_enableLimit;
          obj["lowerTranslation"] = this.m_lowerTranslation;
          obj["upperTranslation"] = this.m_upperTranslation;
          obj["enableMotor"] = this.m_enableMotor;
          obj["maxMotorForce"] = this.m_maxMotorForce;
          obj["motorSpeed"] = this.m_motorSpeed;
          return obj;
        }
      };
      b2PrismaticJoint._extend(b2Joint);
      function b2FrictionJointDef() {
        this.parent.call(this);
        this.type = b2Joint.e_frictionJoint;
        this.localAnchorA = new b2Vec2();
        this.localAnchorB = new b2Vec2();
        this.maxForce = 0;
        this.maxTorque = 0;
        Object.seal(this);
      }
      b2FrictionJointDef.prototype = {
        Initialize: function(bA, bB, anchor) {
          this.bodyA = bA;
          this.bodyB = bB;
          this.localAnchorA.Assign(this.bodyA.GetLocalPoint(anchor));
          this.localAnchorB.Assign(this.bodyB.GetLocalPoint(anchor));
        },
        _deserialize: function(data, bodies, joints) {
          this.parent.prototype._deserialize.call(this, data, bodies, joints);
          this.localAnchorA._deserialize(data["localAnchorA"]);
          this.localAnchorB._deserialize(data["localAnchorB"]);
          this.maxForce = data["maxForce"];
          this.maxTorque = data["maxTorque"];
        }
      };
      b2FrictionJointDef._extend(b2JointDef);
      function b2FrictionJoint(def) {
        this.parent.call(this, def);
        this.m_localAnchorA = def.localAnchorA.Clone();
        this.m_localAnchorB = def.localAnchorB.Clone();
        this.m_linearImpulse = new b2Vec2();
        this.m_angularImpulse = 0;
        this.m_maxForce = def.maxForce;
        this.m_maxTorque = def.maxTorque;
        this.m_indexA = 0;
        this.m_indexB = 0;
        this.m_rA = new b2Vec2();
        this.m_rB = new b2Vec2();
        this.m_localCenterA = new b2Vec2();
        this.m_localCenterB = new b2Vec2();
        this.m_invMassA = 0;
        this.m_invMassB = 0;
        this.m_invIA = 0;
        this.m_invIB = 0;
        this.m_linearMass = new b2Mat22();
        this.m_angularMass = 0;
      }
      b2FrictionJoint.prototype = {
        GetAnchorA: function() {
          return this.m_bodyA.GetWorldPoint(this.m_localAnchorA);
        },
        GetAnchorB: function() {
          return this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
        },
        GetReactionForce: function(inv_dt) {
          return b2Vec2.Multiply(inv_dt, this.m_linearImpulse);
        },
        GetReactionTorque: function(inv_dt) {
          return inv_dt * this.m_angularImpulse;
        },
        GetLocalAnchorA: function() {
          return this.m_localAnchorA;
        },
        GetLocalAnchorB: function() {
          return this.m_localAnchorB;
        },
        SetMaxForce: function(force) {
          b2Assert(b2IsValid(force) && force >= 0);
          this.m_maxForce = force;
        },
        GetMaxForce: function() {
          return this.m_maxForce;
        },
        SetMaxTorque: function(torque) {
          b2Assert(b2IsValid(torque) && torque >= 0);
          this.m_maxTorque = torque;
        },
        GetMaxTorque: function() {
          return this.m_maxTorque;
        },
        InitVelocityConstraints: function(data) {
          this.m_indexA = this.m_bodyA.m_islandIndex;
          this.m_indexB = this.m_bodyB.m_islandIndex;
          this.m_localCenterA.Assign(this.m_bodyA.m_sweep.localCenter);
          this.m_localCenterB.Assign(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.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var aB = data.positions[this.m_indexB].a;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          this.m_rA = b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_localCenterA));
          this.m_rB = b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB));
          var mA = this.m_invMassA, mB = this.m_invMassB;
          var iA = this.m_invIA, iB = this.m_invIB;
          var K = new b2Mat22();
          K.ex.x = mA + mB + iA * this.m_rA.y * this.m_rA.y + iB * this.m_rB.y * this.m_rB.y;
          K.ex.y = -iA * this.m_rA.x * this.m_rA.y - iB * this.m_rB.x * this.m_rB.y;
          K.ey.x = K.ex.y;
          K.ey.y = mA + mB + iA * this.m_rA.x * this.m_rA.x + iB * this.m_rB.x * this.m_rB.x;
          this.m_linearMass = K.GetInverse();
          this.m_angularMass = iA + iB;
          this.m_angularMass > 0 && (this.m_angularMass = 1 / this.m_angularMass);
          if (data.step.warmStarting) {
            this.m_linearImpulse.Multiply(data.step.dtRatio);
            this.m_angularImpulse *= data.step.dtRatio;
            var P = new b2Vec2(this.m_linearImpulse.x, this.m_linearImpulse.y);
            vA.Subtract(b2Vec2.Multiply(mA, P));
            wA -= iA * (b2Cross_v2_v2(this.m_rA, P) + this.m_angularImpulse);
            vB.Add(b2Vec2.Multiply(mB, P));
            wB += iB * (b2Cross_v2_v2(this.m_rB, P) + this.m_angularImpulse);
          } else {
            this.m_linearImpulse.SetZero();
            this.m_angularImpulse = 0;
          }
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolveVelocityConstraints: function(data) {
          var vA = data.velocities[this.m_indexA].v.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var vB = data.velocities[this.m_indexB].v.Clone();
          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 = b2Vec2.Add(vB, b2Vec2.Subtract(b2Cross_f_v2(wB, this.m_rB), b2Vec2.Subtract(vA, b2Cross_f_v2(wA, this.m_rA))));
          var impulse = b2Mul_m22_v2(this.m_linearMass, Cdot).Negate();
          var oldImpulse = this.m_linearImpulse.Clone();
          this.m_linearImpulse.Add(impulse);
          var maxImpulse = h * this.m_maxForce;
          if (this.m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) {
            this.m_linearImpulse.Normalize();
            this.m_linearImpulse.Multiply(maxImpulse);
          }
          impulse = b2Vec2.Subtract(this.m_linearImpulse, oldImpulse);
          vA.Subtract(b2Vec2.Multiply(mA, impulse));
          wA -= iA * b2Cross_v2_v2(this.m_rA, impulse);
          vB.Add(b2Vec2.Multiply(mB, impulse));
          wB += iB * b2Cross_v2_v2(this.m_rB, impulse);
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolvePositionConstraints: function(data) {
          return true;
        },
        _serialize: function(out) {
          var obj = out || {};
          this.parent.prototype._serialize.call(this, obj);
          obj["localAnchorA"] = this.m_localAnchorA._serialize();
          obj["localAnchorB"] = this.m_localAnchorB._serialize();
          obj["maxForce"] = this.m_maxForce;
          obj["maxTorque"] = this.m_maxTorque;
          return obj;
        }
      };
      b2FrictionJoint._extend(b2Joint);
      function b2WeldJointDef() {
        this.parent.call(this);
        this.type = b2Joint.e_weldJoint;
        this.localAnchorA = new b2Vec2(0, 0);
        this.localAnchorB = new b2Vec2(0, 0);
        this.referenceAngle = 0;
        this.frequencyHz = 0;
        this.dampingRatio = 0;
        Object.seal(this);
      }
      b2WeldJointDef.prototype = {
        Initialize: function(bA, bB, anchor) {
          this.bodyA = bA;
          this.bodyB = bB;
          this.localAnchorA.Assign(this.bodyA.GetLocalPoint(anchor));
          this.localAnchorB.Assign(this.bodyB.GetLocalPoint(anchor));
          this.referenceAngle = this.bodyB.GetAngle() - this.bodyA.GetAngle();
        },
        _deserialize: function(data, bodies, joints) {
          this.parent.prototype._deserialize.call(this, data, bodies, joints);
          this.localAnchorA._deserialize(data["localAnchorA"]);
          this.localAnchorB._deserialize(data["localAnchorB"]);
          this.referenceAngle = data["referenceAngle"];
          this.frequencyHz = data["frequencyHz"];
          this.dampingRatio = data["dampingRatio"];
        }
      };
      b2WeldJointDef._extend(b2JointDef);
      function b2WeldJoint(def) {
        this.parent.call(this, def);
        this.m_bias = 0;
        this.m_gamma = 0;
        this.m_indexA = 0;
        this.m_indexB = 0;
        this.m_rA = new b2Vec2();
        this.m_rB = new b2Vec2();
        this.m_localCenterA = new b2Vec2();
        this.m_localCenterB = new b2Vec2();
        this.m_invMassA = 0;
        this.m_invMassB = 0;
        this.m_invIA = 0;
        this.m_invIB = 0;
        this.m_mass = new b2Mat33();
        this.m_localAnchorA = def.localAnchorA.Clone();
        this.m_localAnchorB = def.localAnchorB.Clone();
        this.m_referenceAngle = def.referenceAngle;
        this.m_frequencyHz = def.frequencyHz;
        this.m_dampingRatio = def.dampingRatio;
        this.m_impulse = new b2Vec3();
      }
      b2WeldJoint.prototype = {
        GetAnchorA: function() {
          return this.m_bodyA.GetWorldPoint(this.m_localAnchorA);
        },
        GetAnchorB: function() {
          return this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
        },
        GetReactionForce: function(inv_dt) {
          var P = new b2Vec2(this.m_impulse.x, this.m_impulse.y);
          return b2Vec2.Multiply(inv_dt, P);
        },
        GetReactionTorque: function(inv_dt) {
          return inv_dt * this.m_impulse.z;
        },
        GetLocalAnchorA: function() {
          return this.m_localAnchorA;
        },
        GetLocalAnchorB: function() {
          return this.m_localAnchorB;
        },
        GetReferenceAngle: function() {
          return this.m_referenceAngle;
        },
        SetFrequency: function(hz) {
          this.m_frequencyHz = hz;
        },
        GetFrequency: function() {
          return this.m_frequencyHz;
        },
        SetDampingRatio: function(ratio) {
          this.m_dampingRatio = ratio;
        },
        GetDampingRatio: function() {
          return this.m_dampingRatio;
        },
        InitVelocityConstraints: function(data) {
          this.m_indexA = this.m_bodyA.m_islandIndex;
          this.m_indexB = this.m_bodyB.m_islandIndex;
          this.m_localCenterA.Assign(this.m_bodyA.m_sweep.localCenter);
          this.m_localCenterB.Assign(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.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var aB = data.positions[this.m_indexB].a;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          this.m_rA.Assign(b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_localCenterA)));
          this.m_rB.Assign(b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB)));
          var mA = this.m_invMassA, mB = this.m_invMassB;
          var iA = this.m_invIA, iB = this.m_invIB;
          var K = new b2Mat33();
          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 = 0 != this.m_gamma ? 1 / this.m_gamma : 0;
            this.m_bias = C * h * k * this.m_gamma;
            invM += this.m_gamma;
            this.m_mass.ez.z = 0 != invM ? 1 / invM : 0;
          } else if (0 == K.ez.z) {
            K.GetInverse22(this.m_mass);
            this.m_gamma = 0;
            this.m_bias = 0;
          } else {
            K.GetSymInverse33(this.m_mass);
            this.m_gamma = 0;
            this.m_bias = 0;
          }
          if (data.step.warmStarting) {
            this.m_impulse.Multiply(data.step.dtRatio);
            var P = new b2Vec2(this.m_impulse.x, this.m_impulse.y);
            vA.Subtract(b2Vec2.Multiply(mA, P));
            wA -= iA * (b2Cross_v2_v2(this.m_rA, P) + this.m_impulse.z);
            vB.Add(b2Vec2.Multiply(mB, P));
            wB += iB * (b2Cross_v2_v2(this.m_rB, P) + this.m_impulse.z);
          } else this.m_impulse.SetZero();
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolveVelocityConstraints: function(data) {
          var vA = data.velocities[this.m_indexA].v.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var vB = data.velocities[this.m_indexB].v.Clone();
          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.Subtract(b2Vec2.Subtract(b2Vec2.Add(vB, b2Cross_f_v2(wB, this.m_rB)), vA), b2Cross_f_v2(wA, this.m_rA));
            var impulse1 = b2Mul22_m33_v2(this.m_mass, Cdot1).Negate();
            this.m_impulse.x += impulse1.x;
            this.m_impulse.y += impulse1.y;
            var P = impulse1.Clone();
            vA.Subtract(b2Vec2.Multiply(mA, P));
            wA -= iA * b2Cross_v2_v2(this.m_rA, P);
            vB.Add(b2Vec2.Multiply(mB, P));
            wB += iB * b2Cross_v2_v2(this.m_rB, P);
          } else {
            var Cdot1 = b2Vec2.Subtract(b2Vec2.Subtract(b2Vec2.Add(vB, b2Cross_f_v2(wB, this.m_rB)), vA), b2Cross_f_v2(wA, this.m_rA));
            var Cdot2 = wB - wA;
            var Cdot = new b2Vec3(Cdot1.x, Cdot1.y, Cdot2);
            var impulse = b2Mul_m33_v3(this.m_mass, Cdot).Negate();
            this.m_impulse.Add(impulse);
            var P = new b2Vec2(impulse.x, impulse.y);
            vA.Subtract(b2Vec2.Multiply(mA, P));
            wA -= iA * (b2Cross_v2_v2(this.m_rA, P) + impulse.z);
            vB.Add(b2Vec2.Multiply(mB, P));
            wB += iB * (b2Cross_v2_v2(this.m_rB, P) + impulse.z);
          }
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolvePositionConstraints: function(data) {
          var cA = data.positions[this.m_indexA].c.Clone();
          var aA = data.positions[this.m_indexA].a;
          var cB = data.positions[this.m_indexB].c.Clone();
          var aB = data.positions[this.m_indexB].a;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          var mA = this.m_invMassA, mB = this.m_invMassB;
          var iA = this.m_invIA, iB = this.m_invIB;
          var rA = b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_localCenterA));
          var rB = b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB));
          var positionError, angularError;
          var K = new b2Mat33();
          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.Subtract(b2Vec2.Subtract(b2Vec2.Add(cB, rB), cA), rA);
            positionError = C1.Length();
            angularError = 0;
            var P = K.Solve22(C1).Negate();
            cA.Subtract(b2Vec2.Multiply(mA, P));
            aA -= iA * b2Cross_v2_v2(rA, P);
            cB.Add(b2Vec2.Multiply(mB, P));
            aB += iB * b2Cross_v2_v2(rB, P);
          } else {
            var C1 = b2Vec2.Subtract(b2Vec2.Subtract(b2Vec2.Add(cB, rB), cA), rA);
            var C2 = aB - aA - this.m_referenceAngle;
            positionError = C1.Length();
            angularError = b2Abs(C2);
            var C = new b2Vec3(C1.x, C1.y, C2);
            var impulse;
            if (K.ez.z > 0) impulse = K.Solve33(C).Invert(); else {
              var impulse2 = K.Solve22(C1).Invert();
              impulse = new b2Vec3(impulse2.x, impulse2.y, 0);
            }
            var P = new b2Vec2(impulse.x, impulse.y);
            cA.Subtract(b2Vec2.Multiply(mA, P));
            aA -= iA * (b2Cross_v2_v2(rA, P) + impulse.z);
            cB.Add(b2Vec2.Multiply(mB, P));
            aB += iB * (b2Cross_v2_v2(rB, P) + impulse.z);
          }
          data.positions[this.m_indexA].c.Assign(cA);
          data.positions[this.m_indexA].a = aA;
          data.positions[this.m_indexB].c.Assign(cB);
          data.positions[this.m_indexB].a = aB;
          return positionError <= b2_linearSlop && angularError <= b2_angularSlop;
        },
        _serialize: function(out) {
          var obj = out || {};
          this.parent.prototype._serialize.call(this, obj);
          obj["localAnchorA"] = this.m_localAnchorA._serialize();
          obj["localAnchorB"] = this.m_localAnchorB._serialize();
          obj["referenceAngle"] = this.m_referenceAngle;
          obj["frequencyHz"] = this.m_frequencyHz;
          obj["dampingRatio"] = this.m_dampingRatio;
          return obj;
        }
      };
      b2WeldJoint._extend(b2Joint);
      function b2WheelJointDef() {
        this.parent.call(this);
        this.type = b2Joint.e_wheelJoint;
        this.localAnchorA = new b2Vec2();
        this.localAnchorB = new b2Vec2();
        this.localAxisA = new b2Vec2(1, 0);
        this.enableMotor = false;
        this.maxMotorTorque = 0;
        this.motorSpeed = 0;
        this.frequencyHz = 2;
        this.dampingRatio = .7;
        Object.seal(this);
      }
      b2WheelJointDef.prototype = {
        Initialize: function(bA, bB, anchor, axis) {
          this.bodyA = bA;
          this.bodyB = bB;
          this.localAnchorA.Assign(this.bodyA.GetLocalPoint(anchor));
          this.localAnchorB.Assign(this.bodyB.GetLocalPoint(anchor));
          this.localAxisA.Assign(this.bodyA.GetLocalVector(axis));
        },
        _deserialize: function(data, bodies, joints) {
          this.parent.prototype._deserialize.call(this, data, bodies, joints);
          this.localAnchorA._deserialize(data["localAnchorA"]);
          this.localAnchorB._deserialize(data["localAnchorB"]);
          this.localAxisA._deserialize(data["localAxisA"]);
          this.enableMotor = data["enableMotor"];
          this.maxMotorTorque = data["maxMotorTorque"];
          this.motorSpeed = data["motorSpeed"];
          this.frequencyHz = data["frequencyHz"];
          this.dampingRatio = data["dampingRatio"];
        }
      };
      b2WheelJointDef._extend(b2JointDef);
      function b2WheelJoint(def) {
        this.parent.call(this, def);
        this.m_indexA = 0;
        this.m_indexB = 0;
        this.m_localCenterA = new b2Vec2();
        this.m_localCenterB = new b2Vec2();
        this.m_invMassA = 0;
        this.m_invMassB = 0;
        this.m_invIA = 0;
        this.m_invIB = 0;
        this.m_localAnchorA = def.localAnchorA.Clone();
        this.m_localAnchorB = def.localAnchorB.Clone();
        this.m_localXAxisA = def.localAxisA.Clone();
        this.m_localYAxisA = b2Cross_f_v2(1, this.m_localXAxisA);
        this.m_mass = 0;
        this.m_impulse = 0;
        this.m_motorMass = 0;
        this.m_motorImpulse = 0;
        this.m_springMass = 0;
        this.m_springImpulse = 0;
        this.m_maxMotorTorque = def.maxMotorTorque;
        this.m_motorSpeed = def.motorSpeed;
        this.m_enableMotor = def.enableMotor;
        this.m_frequencyHz = def.frequencyHz;
        this.m_dampingRatio = def.dampingRatio;
        this.m_bias = 0;
        this.m_gamma = 0;
        this.m_ax = new b2Vec2();
        this.m_ay = new b2Vec2();
        this.m_sAx = this.m_sBx = 0;
        this.m_sAy = this.m_sBy = 0;
      }
      b2WheelJoint.prototype = {
        GetAnchorA: function() {
          return this.m_bodyA.GetWorldPoint(this.m_localAnchorA);
        },
        GetAnchorB: function() {
          return this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
        },
        GetReactionForce: function(inv_dt) {
          return b2Vec2.Multiply(inv_dt, b2Vec2.Add(b2Vec2.Multiply(this.m_impulse, this.m_ay), b2Vec2.Multiply(this.m_springImpulse, this.m_ax)));
        },
        GetReactionTorque: function(inv_dt) {
          return inv_dt * this.m_motorImpulse;
        },
        GetLocalAnchorA: function() {
          return this.m_localAnchorA;
        },
        GetLocalAnchorB: function() {
          return this.m_localAnchorB;
        },
        GetLocalAxisA: function() {
          return this.m_localXAxisA;
        },
        GetJointTranslation: function() {
          var bA = this.m_bodyA;
          var bB = this.m_bodyB;
          var pA = bA.GetWorldPoint(this.m_localAnchorA);
          var pB = bB.GetWorldPoint(this.m_localAnchorB);
          var d = b2Vec2.Subtract(pB, pA);
          var axis = bA.GetWorldVector(this.m_localXAxisA);
          var translation = b2Dot_v2_v2(d, axis);
          return translation;
        },
        GetJointSpeed: function() {
          var wA = this.m_bodyA.m_angularVelocity;
          var wB = this.m_bodyB.m_angularVelocity;
          return wB - wA;
        },
        IsMotorEnabled: function() {
          return this.m_enableMotor;
        },
        EnableMotor: function(flag) {
          this.m_bodyA.SetAwake(true);
          this.m_bodyB.SetAwake(true);
          this.m_enableMotor = flag;
        },
        SetMotorSpeed: function(speed) {
          this.m_bodyA.SetAwake(true);
          this.m_bodyB.SetAwake(true);
          this.m_motorSpeed = speed;
        },
        GetMotorSpeed: function() {
          return this.m_motorSpeed;
        },
        SetMaxMotorTorque: function(torque) {
          this.m_bodyA.SetAwake(true);
          this.m_bodyB.SetAwake(true);
          this.m_maxMotorTorque = torque;
        },
        GetMaxMotorTorque: function() {
          return this.m_maxMotorTorque;
        },
        GetMotorTorque: function(inv_dt) {
          return inv_dt * this.m_motorImpulse;
        },
        SetSpringFrequencyHz: function(hz) {
          this.m_frequencyHz = hz;
        },
        GetSpringFrequencyHz: function() {
          return this.m_frequencyHz;
        },
        SetSpringDampingRatio: function(ratio) {
          this.m_dampingRatio = ratio;
        },
        GetSpringDampingRatio: function() {
          return this.m_dampingRatio;
        },
        InitVelocityConstraints: function(data) {
          this.m_indexA = this.m_bodyA.m_islandIndex;
          this.m_indexB = this.m_bodyB.m_islandIndex;
          this.m_localCenterA.Assign(this.m_bodyA.m_sweep.localCenter);
          this.m_localCenterB.Assign(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.Clone();
          var aA = data.positions[this.m_indexA].a;
          var vA = data.velocities[this.m_indexA].v.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var cB = data.positions[this.m_indexB].c.Clone();
          var aB = data.positions[this.m_indexB].a;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          var rA = b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_localCenterA));
          var rB = b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB));
          var d = b2Vec2.Subtract(b2Vec2.Subtract(b2Vec2.Add(cB, rB), cA), rA);
          this.m_ay.Assign(b2Mul_r_v2(qA, this.m_localYAxisA));
          this.m_sAy = b2Cross_v2_v2(b2Vec2.Add(d, rA), this.m_ay);
          this.m_sBy = b2Cross_v2_v2(rB, this.m_ay);
          this.m_mass = mA + mB + iA * this.m_sAy * this.m_sAy + iB * this.m_sBy * this.m_sBy;
          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) {
            this.m_ax.Assign(b2Mul_r_v2(qA, this.m_localXAxisA));
            this.m_sAx = b2Cross_v2_v2(b2Vec2.Add(d, rA), this.m_ax);
            this.m_sBx = b2Cross_v2_v2(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 = b2Dot_v2_v2(d, this.m_ax);
              var omega = 2 * b2_pi * this.m_frequencyHz;
              var d = 2 * this.m_springMass * this.m_dampingRatio * omega;
              var k = this.m_springMass * omega * omega;
              var h = data.step.dt;
              this.m_gamma = h * (d + h * k);
              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;
              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;
            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.Add(b2Vec2.Multiply(this.m_impulse, this.m_ay), b2Vec2.Multiply(this.m_springImpulse, this.m_ax));
            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.Subtract(b2Vec2.Multiply(this.m_invMassA, P));
            wA -= this.m_invIA * LA;
            vB.Add(b2Vec2.Multiply(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].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolveVelocityConstraints: function(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.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var Cdot = b2Dot_v2_v2(this.m_ax, b2Vec2.Subtract(vB, vA)) + 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.Multiply(impulse, this.m_ax);
          var LA = impulse * this.m_sAx;
          var LB = impulse * this.m_sBx;
          vA.Subtract(b2Vec2.Multiply(mA, P));
          wA -= iA * LA;
          vB.Add(b2Vec2.Multiply(mB, P));
          wB += iB * LB;
          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;
          var Cdot = b2Dot_v2_v2(this.m_ay, b2Vec2.Subtract(vB, vA)) + this.m_sBy * wB - this.m_sAy * wA;
          var impulse = -this.m_mass * Cdot;
          this.m_impulse += impulse;
          var P = b2Vec2.Multiply(impulse, this.m_ay);
          var LA = impulse * this.m_sAy;
          var LB = impulse * this.m_sBy;
          vA.Subtract(b2Vec2.Multiply(mA, P));
          wA -= iA * LA;
          vB.Add(b2Vec2.Multiply(mB, P));
          wB += iB * LB;
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolvePositionConstraints: function(data) {
          var cA = data.positions[this.m_indexA].c.Clone();
          var aA = data.positions[this.m_indexA].a;
          var cB = data.positions[this.m_indexB].c.Clone();
          var aB = data.positions[this.m_indexB].a;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          var rA = b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_localCenterA));
          var rB = b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB));
          var d = b2Vec2.Add(b2Vec2.Subtract(cB, cA), b2Vec2.Subtract(rB, rA));
          var ay = b2Mul_r_v2(qA, this.m_localYAxisA);
          var sAy = b2Cross_v2_v2(b2Vec2.Add(d, rA), ay);
          var sBy = b2Cross_v2_v2(rB, ay);
          var C = b2Dot_v2_v2(d, 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;
          impulse = 0 != k ? -C / k : 0;
          var P = b2Vec2.Multiply(impulse, ay);
          var LA = impulse * sAy;
          var LB = impulse * sBy;
          cA.Subtract(b2Vec2.Multiply(this.m_invMassA, P));
          aA -= this.m_invIA * LA;
          cB.Add(b2Vec2.Multiply(this.m_invMassB, P));
          aB += this.m_invIB * LB;
          data.positions[this.m_indexA].c.Assign(cA);
          data.positions[this.m_indexA].a = aA;
          data.positions[this.m_indexB].c.Assign(cB);
          data.positions[this.m_indexB].a = aB;
          return b2Abs(C) <= b2_linearSlop;
        },
        _serialize: function(out) {
          var obj = out || {};
          this.parent.prototype._serialize.call(this, obj);
          obj["localAnchorA"] = this.m_localAnchorA._serialize();
          obj["localAnchorB"] = this.m_localAnchorB._serialize();
          obj["localAxisA"] = this.m_localAxisA._serialize();
          obj["enableMotor"] = this.m_enableMotor;
          obj["maxMotorTorque"] = this.m_maxMotorTorque;
          obj["motorSpeed"] = this.m_motorSpeed;
          obj["frequencyHz"] = this.m_frequencyHz;
          obj["dampingRatio"] = this.m_dampingRatio;
          return obj;
        }
      };
      b2WheelJoint._extend(b2Joint);
      function b2GearJointDef() {
        this.parent.call(this);
        this.type = b2Joint.e_gearJoint;
        this.joint1 = null;
        this.joint2 = null;
        this.ratio = 1;
        Object.seal(this);
      }
      b2GearJointDef.prototype = {
        _deserialize: function(data, bodies, joints) {
          this.parent.prototype._deserialize.call(this, data, bodies, joints);
          this.joint1 = data["joint1"];
          this.joint2 = data["joint2"];
          this.ratio = data["ratio"];
        }
      };
      b2GearJointDef._extend(b2JointDef);
      function b2GearJoint(def) {
        this.parent.call(this, def);
        this.m_joint1 = def.joint1;
        this.m_joint2 = def.joint2;
        this.m_typeA = this.m_joint1.GetType();
        this.m_typeB = this.m_joint2.GetType();
        b2Assert(this.m_typeA == b2Joint.e_revoluteJoint || this.m_typeA == b2Joint.e_prismaticJoint);
        b2Assert(this.m_typeB == b2Joint.e_revoluteJoint || this.m_typeB == b2Joint.e_prismaticJoint);
        var coordinateA, coordinateB;
        this.m_bodyC = this.m_joint1.GetBodyA();
        this.m_bodyA = this.m_joint1.GetBodyB();
        var xfA = this.m_bodyA.m_xf;
        var aA = this.m_bodyA.m_sweep.a;
        var xfC = this.m_bodyC.m_xf;
        var aC = this.m_bodyC.m_sweep.a;
        this.m_localAnchorA = new b2Vec2();
        this.m_localAnchorB = new b2Vec2();
        this.m_localAnchorC = new b2Vec2();
        this.m_localAnchorD = new b2Vec2();
        this.m_localAxisC = new b2Vec2();
        this.m_localAxisD = new b2Vec2();
        if (this.m_typeA == b2Joint.e_revoluteJoint) {
          var revolute = def.joint1;
          this.m_localAnchorC.Assign(revolute.m_localAnchorA);
          this.m_localAnchorA.Assign(revolute.m_localAnchorB);
          this.m_referenceAngleA = revolute.m_referenceAngle;
          this.m_localAxisC.SetZero();
          coordinateA = aA - aC - this.m_referenceAngleA;
        } else {
          var prismatic = def.joint1;
          this.m_localAnchorC.Assign(prismatic.m_localAnchorA);
          this.m_localAnchorA.Assign(prismatic.m_localAnchorB);
          this.m_referenceAngleA = prismatic.m_referenceAngle;
          this.m_localAxisC.Assign(prismatic.m_localXAxisA);
          var pC = this.m_localAnchorC;
          var pA = b2MulT_r_v2(xfC.q, b2Vec2.Add(b2Mul_r_v2(xfA.q, this.m_localAnchorA), b2Vec2.Subtract(xfA.p, xfC.p)));
          coordinateA = b2Dot_v2_v2(b2Vec2.Subtract(pA, pC), this.m_localAxisC);
        }
        this.m_bodyD = this.m_joint2.GetBodyA();
        this.m_bodyB = this.m_joint2.GetBodyB();
        var xfB = this.m_bodyB.m_xf;
        var aB = this.m_bodyB.m_sweep.a;
        var xfD = this.m_bodyD.m_xf;
        var aD = this.m_bodyD.m_sweep.a;
        if (this.m_typeB == b2Joint.e_revoluteJoint) {
          var revolute = def.joint2;
          this.m_localAnchorD.Assign(revolute.m_localAnchorA);
          this.m_localAnchorB.Assign(revolute.m_localAnchorB);
          this.m_referenceAngleB = revolute.m_referenceAngle;
          this.m_localAxisD.SetZero();
          coordinateB = aB - aD - this.m_referenceAngleB;
        } else {
          var prismatic = def.joint2;
          this.m_localAnchorD.Assign(prismatic.m_localAnchorA);
          this.m_localAnchorB.Assign(prismatic.m_localAnchorB);
          this.m_referenceAngleB = prismatic.m_referenceAngle;
          this.m_localAxisD.Assign(prismatic.m_localXAxisA);
          var pD = this.m_localAnchorD;
          var pB = b2MulT_r_v2(xfD.q, b2Vec2.Add(b2Mul_r_v2(xfB.q, this.m_localAnchorB), b2Vec2.Subtract(xfB.p, xfD.p)));
          coordinateB = b2Dot_v2_v2(b2Vec2.Subtract(pB, pD), this.m_localAxisD);
        }
        this.m_ratio = def.ratio;
        this.m_constant = coordinateA + this.m_ratio * coordinateB;
        this.m_impulse = 0;
        this.m_indexA = this.m_indexB = this.m_indexC = this.m_indexD = 0;
        this.m_lcA = new b2Vec2();
        this.m_lcB = new b2Vec2();
        this.m_lcC = new b2Vec2();
        this.m_lcD = new b2Vec2();
        this.m_mA = this.m_mB = this.m_mC = this.m_mD = 0;
        this.m_iA = this.m_iB = this.m_iC = this.m_iD = 0;
        this.m_JvAC = new b2Vec2(), this.m_JvBD = new b2Vec2();
        this.m_JwA = this.m_JwB = this.m_JwC = this.m_JwD = 0;
        this.m_mass = 0;
      }
      b2GearJoint.prototype = {
        GetAnchorA: function() {
          return this.m_bodyA.GetWorldPoint(this.m_localAnchorA);
        },
        GetAnchorB: function() {
          return this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
        },
        GetReactionForce: function(inv_dt) {
          var P = b2Vec2.Multiply(this.m_impulse, this.m_JvAC);
          return b2Vec2.Multiply(inv_dt, P);
        },
        GetReactionTorque: function(inv_dt) {
          var L = this.m_impulse * this.m_JwA;
          return inv_dt * L;
        },
        GetJoint1: function() {
          return this.m_joint1;
        },
        GetJoint2: function() {
          return this.m_joint2;
        },
        SetRatio: function(ratio) {
          b2Assert(b2IsValid(ratio));
          this.m_ratio = ratio;
        },
        GetRatio: function() {
          return this.m_ratio;
        },
        InitVelocityConstraints: function(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.Assign(this.m_bodyA.m_sweep.localCenter);
          this.m_lcB.Assign(this.m_bodyB.m_sweep.localCenter);
          this.m_lcC.Assign(this.m_bodyC.m_sweep.localCenter);
          this.m_lcD.Assign(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.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var aB = data.positions[this.m_indexB].a;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var aC = data.positions[this.m_indexC].a;
          var vC = data.velocities[this.m_indexC].v.Clone();
          var wC = data.velocities[this.m_indexC].w;
          var aD = data.positions[this.m_indexD].a;
          var vD = data.velocities[this.m_indexD].v.Clone();
          var wD = data.velocities[this.m_indexD].w;
          var qA = new b2Rot(aA), qB = new b2Rot(aB), qC = new b2Rot(aC), qD = new b2Rot(aD);
          this.m_mass = 0;
          if (this.m_typeA == b2Joint.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 = b2Mul_r_v2(qC, this.m_localAxisC);
            var rC = b2Mul_r_v2(qC, b2Vec2.Subtract(this.m_localAnchorC, this.m_lcC));
            var rA = b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_lcA));
            this.m_JvAC.Assign(u);
            this.m_JwC = b2Cross_v2_v2(rC, u);
            this.m_JwA = b2Cross_v2_v2(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 == b2Joint.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 = b2Mul_r_v2(qD, this.m_localAxisD);
            var rD = b2Mul_r_v2(qD, b2Vec2.Subtract(this.m_localAnchorD, this.m_lcD));
            var rB = b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_lcB));
            this.m_JvBD.Assign(b2Vec2.Multiply(this.m_ratio, u));
            this.m_JwD = this.m_ratio * b2Cross_v2_v2(rD, u);
            this.m_JwB = this.m_ratio * b2Cross_v2_v2(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.Add(b2Vec2.Multiply(this.m_mA * this.m_impulse, this.m_JvAC));
            wA += this.m_iA * this.m_impulse * this.m_JwA;
            vB.Add(b2Vec2.Multiply(this.m_mB * this.m_impulse, this.m_JvBD));
            wB += this.m_iB * this.m_impulse * this.m_JwB;
            vC.Subtract(b2Vec2.Multiply(this.m_mC * this.m_impulse, this.m_JvAC));
            wC -= this.m_iC * this.m_impulse * this.m_JwC;
            vD.Subtract(b2Vec2.Multiply(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].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
          data.velocities[this.m_indexC].v.Assign(vC);
          data.velocities[this.m_indexC].w = wC;
          data.velocities[this.m_indexD].v.Assign(vD);
          data.velocities[this.m_indexD].w = wD;
        },
        SolveVelocityConstraints: function(data) {
          var vA = data.velocities[this.m_indexA].v.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var vC = data.velocities[this.m_indexC].v.Clone();
          var wC = data.velocities[this.m_indexC].w;
          var vD = data.velocities[this.m_indexD].v.Clone();
          var wD = data.velocities[this.m_indexD].w;
          var Cdot = b2Dot_v2_v2(this.m_JvAC, b2Vec2.Subtract(vA, vC)) + b2Dot_v2_v2(this.m_JvBD, b2Vec2.Subtract(vB, vD));
          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.Add(b2Vec2.Multiply(this.m_mA * impulse, this.m_JvAC));
          wA += this.m_iA * impulse * this.m_JwA;
          vB.Add(b2Vec2.Multiply(this.m_mB * impulse, this.m_JvBD));
          wB += this.m_iB * impulse * this.m_JwB;
          vC.Subtract(b2Vec2.Multiply(this.m_mC * impulse, this.m_JvAC));
          wC -= this.m_iC * impulse * this.m_JwC;
          vD.Subtract(b2Vec2.Multiply(this.m_mD * impulse, this.m_JvBD));
          wD -= this.m_iD * impulse * this.m_JwD;
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
          data.velocities[this.m_indexC].v.Assign(vC);
          data.velocities[this.m_indexC].w = wC;
          data.velocities[this.m_indexD].v.Assign(vD);
          data.velocities[this.m_indexD].w = wD;
        },
        SolvePositionConstraints: function(data) {
          var cA = data.positions[this.m_indexA].c.Clone();
          var aA = data.positions[this.m_indexA].a;
          var cB = data.positions[this.m_indexB].c.Clone();
          var aB = data.positions[this.m_indexB].a;
          var cC = data.positions[this.m_indexC].c.Clone();
          var aC = data.positions[this.m_indexC].a;
          var cD = data.positions[this.m_indexD].c.Clone();
          var aD = data.positions[this.m_indexD].a;
          var qA = new b2Rot(aA), qB = new b2Rot(aB), qC = new b2Rot(aC), qD = new b2Rot(aD);
          var linearError = 0;
          var coordinateA, coordinateB;
          var JvAC = new b2Vec2(), JvBD = new b2Vec2();
          var JwA, JwB, JwC, JwD;
          var mass = 0;
          if (this.m_typeA == b2Joint.e_revoluteJoint) {
            JvAC.SetZero();
            JwA = 1;
            JwC = 1;
            mass += this.m_iA + this.m_iC;
            coordinateA = aA - aC - this.m_referenceAngleA;
          } else {
            var u = b2Mul_r_v2(qC, this.m_localAxisC);
            var rC = b2Mul_r_v2(qC, b2Vec2.Subtract(this.m_localAnchorC, this.m_lcC));
            var rA = b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_lcA));
            JvAC.Assign(u);
            JwC = b2Cross_v2_v2(rC, u);
            JwA = b2Cross_v2_v2(rA, u);
            mass += this.m_mC + this.m_mA + this.m_iC * JwC * JwC + this.m_iA * JwA * JwA;
            var pC = b2Vec2.Subtract(this.m_localAnchorC, this.m_lcC);
            var pA = b2MulT_r_v2(qC, b2Vec2.Add(rA, b2Vec2.Subtract(cA, cC)));
            coordinateA = b2Dot_v2_v2(b2Vec2.Subtract(pA, pC), this.m_localAxisC);
          }
          if (this.m_typeB == b2Joint.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 u = b2Mul_r_v2(qD, this.m_localAxisD);
            var rD = b2Mul_r_v2(qD, b2Vec2.Subtract(this.m_localAnchorD, this.m_lcD));
            var rB = b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_lcB));
            JvBD.Assign(b2Vec2.Multiply(this.m_ratio, u));
            JwD = this.m_ratio * b2Cross_v2_v2(rD, u);
            JwB = this.m_ratio * b2Cross_v2_v2(rB, u);
            mass += this.m_ratio * this.m_ratio * (this.m_mD + this.m_mB) + this.m_iD * JwD * JwD + this.m_iB * JwB * JwB;
            var pD = b2Vec2.Subtract(this.m_localAnchorD, this.m_lcD);
            var pB = b2MulT_r_v2(qD, b2Vec2.Add(rB, b2Vec2.Subtract(cB, cD)));
            coordinateB = b2Dot_v2_v2(b2Vec2.Subtract(pB, pD), this.m_localAxisD);
          }
          var C = coordinateA + this.m_ratio * coordinateB - this.m_constant;
          var impulse = 0;
          mass > 0 && (impulse = -C / mass);
          cA.Add(b2Vec2.Multiply(this.m_mA, b2Vec2.Multiply(impulse, JvAC)));
          aA += this.m_iA * impulse * JwA;
          cB.Add(b2Vec2.Multiply(this.m_mB, b2Vec2.Multiply(impulse, JvBD)));
          aB += this.m_iB * impulse * JwB;
          cC.Subtract(b2Vec2.Multiply(this.m_mC, b2Vec2.Multiply(impulse, JvAC)));
          aC -= this.m_iC * impulse * JwC;
          cD.Subtract(b2Vec2.Multiply(this.m_mD, b2Vec2.Multiply(impulse, JvBD)));
          aD -= this.m_iD * impulse * JwD;
          data.positions[this.m_indexA].c.Assign(cA);
          data.positions[this.m_indexA].a = aA;
          data.positions[this.m_indexB].c.Assign(cB);
          data.positions[this.m_indexB].a = aB;
          data.positions[this.m_indexC].c.Assign(cC);
          data.positions[this.m_indexC].a = aC;
          data.positions[this.m_indexD].c.Assign(cD);
          data.positions[this.m_indexD].a = aD;
          return linearError < b2_linearSlop;
        },
        _serialize: function(out) {
          var obj = out || {};
          this.parent.prototype._serialize.call(this, obj);
          obj["joint1"] = this.m_joint1.__temp_joint_id;
          obj["joint2"] = this.m_joint2.__temp_joint_id;
          obj["ratio"] = this.m_ratio;
          return obj;
        }
      };
      b2GearJoint._extend(b2Joint);
      function b2MotorJointDef() {
        this.parent.call(this);
        this.type = b2Joint.e_motorJoint;
        this.linearOffset = new b2Vec2();
        this.angularOffset = 0;
        this.maxForce = 1;
        this.maxTorque = 1;
        this.correctionFactor = .3;
        Object.seal(this);
      }
      b2MotorJointDef.prototype = {
        Initialize: function(bA, bB) {
          this.bodyA = bA;
          this.bodyB = bB;
          var xB = this.bodyB.GetPosition();
          this.linearOffset.Assign(this.bodyA.GetLocalPoint(xB));
          var angleA = this.bodyA.GetAngle();
          var angleB = this.bodyB.GetAngle();
          this.angularOffset = angleB - angleA;
        },
        _deserialize: function(data, bodies, joints) {
          this.parent.prototype._deserialize.call(this, data, bodies, joints);
          this.linearOffset._deserialize(data["linearOffset"]);
          this.angularOffset = data["angularOffset"];
          this.maxForce = data["maxForce"];
          this.maxTorque = data["maxTorque"];
          this.correctionFactor = data["correctionFactor"];
        }
      };
      b2MotorJointDef._extend(b2JointDef);
      function b2MotorJoint(def) {
        this.parent.call(this, def);
        this.m_linearOffset = def.linearOffset.Clone();
        this.m_angularOffset = def.angularOffset;
        this.m_linearImpulse = new b2Vec2();
        this.m_angularImpulse = 0;
        this.m_maxForce = def.maxForce;
        this.m_maxTorque = def.maxTorque;
        this.m_correctionFactor = def.correctionFactor;
        this.m_indexA = 0;
        this.m_indexB = 0;
        this.m_rA = new b2Vec2();
        this.m_rB = new b2Vec2();
        this.m_localCenterA = new b2Vec2();
        this.m_localCenterB = new b2Vec2();
        this.m_linearError = new b2Vec2();
        this.m_angularError = 0;
        this.m_invMassA = 0;
        this.m_invMassB = 0;
        this.m_invIA = 0;
        this.m_invIB = 0;
        this.m_linearMass = new b2Mat22();
        this.m_angularMass = 0;
      }
      b2MotorJoint.prototype = {
        GetAnchorA: function() {
          return this.m_bodyA.GetPosition();
        },
        GetAnchorB: function() {
          return this.m_bodyB.GetPosition();
        },
        GetReactionForce: function(inv_dt) {
          return b2Vec2.Multiply(inv_dt, this.m_linearImpulse);
        },
        GetReactionTorque: function(inv_dt) {
          return inv_dt * this.m_angularImpulse;
        },
        SetLinearOffset: function(linearOffset) {
          if (linearOffset.x != this.m_linearOffset.x || linearOffset.y != this.m_linearOffset.y) {
            this.m_bodyA.SetAwake(true);
            this.m_bodyB.SetAwake(true);
            this.m_linearOffset.Assign(linearOffset);
          }
        },
        GetLinearOffset: function() {
          return this.m_linearOffset;
        },
        SetAngularOffset: function(angularOffset) {
          if (angularOffset != this.m_angularOffset) {
            this.m_bodyA.SetAwake(true);
            this.m_bodyB.SetAwake(true);
            this.m_angularOffset = angularOffset;
          }
        },
        GetAngularOffset: function() {
          return this.m_angularOffset;
        },
        SetMaxForce: function(force) {
          b2Assert(b2IsValid(force) && force >= 0);
          this.m_maxForce = force;
        },
        GetMaxForce: function() {
          return this.m_maxForce;
        },
        SetMaxTorque: function(torque) {
          b2Assert(b2IsValid(torque) && torque >= 0);
          this.m_maxTorque = torque;
        },
        GetMaxTorque: function() {
          return this.m_maxTorque;
        },
        SetCorrectionFactor: function(factor) {
          b2Assert(b2IsValid(factor) && 0 <= factor && factor <= 1);
          this.m_correctionFactor = factor;
        },
        GetCorrectionFactor: function() {
          return this.m_correctionFactor;
        },
        InitVelocityConstraints: function(data) {
          this.m_indexA = this.m_bodyA.m_islandIndex;
          this.m_indexB = this.m_bodyB.m_islandIndex;
          this.m_localCenterA.Assign(this.m_bodyA.m_sweep.localCenter);
          this.m_localCenterB.Assign(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.Clone();
          var aA = data.positions[this.m_indexA].a;
          var vA = data.velocities[this.m_indexA].v.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var cB = data.positions[this.m_indexB].c.Clone();
          var aB = data.positions[this.m_indexB].a;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          this.m_rA.Assign(b2Mul_r_v2(qA, this.m_localCenterA.Negate()));
          this.m_rB.Assign(b2Mul_r_v2(qB, this.m_localCenterB.Negate()));
          var mA = this.m_invMassA, mB = this.m_invMassB;
          var iA = this.m_invIA, iB = this.m_invIB;
          var K = new b2Mat22();
          K.ex.x = mA + mB + iA * this.m_rA.y * this.m_rA.y + iB * this.m_rB.y * this.m_rB.y;
          K.ex.y = -iA * this.m_rA.x * this.m_rA.y - iB * this.m_rB.x * this.m_rB.y;
          K.ey.x = K.ex.y;
          K.ey.y = mA + mB + iA * this.m_rA.x * this.m_rA.x + iB * this.m_rB.x * this.m_rB.x;
          this.m_linearMass.Assign(K.GetInverse());
          this.m_angularMass = iA + iB;
          this.m_angularMass > 0 && (this.m_angularMass = 1 / this.m_angularMass);
          this.m_linearError.x = cB.x + this.m_rB.x - cA.x - this.m_rA.x - (qA.c * this.m_linearOffset.x - qA.s * this.m_linearOffset.y);
          this.m_linearError.y = cB.y + this.m_rB.y - cA.y - this.m_rA.y - (qA.s * this.m_linearOffset.x + qA.c * this.m_linearOffset.y);
          this.m_angularError = aB - aA - this.m_angularOffset;
          if (data.step.warmStarting) {
            this.m_linearImpulse.Multiply(data.step.dtRatio);
            this.m_angularImpulse *= data.step.dtRatio;
            var P = new b2Vec2(this.m_linearImpulse.x, this.m_linearImpulse.y);
            vA.Subtract(b2Vec2.Multiply(mA, P));
            wA -= iA * (b2Cross_v2_v2(this.m_rA, P) + this.m_angularImpulse);
            vB.Add(b2Vec2.Multiply(mB, P));
            wB += iB * (b2Cross_v2_v2(this.m_rB, P) + this.m_angularImpulse);
          } else {
            this.m_linearImpulse.SetZero();
            this.m_angularImpulse = 0;
          }
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolveVelocityConstraints: function(data) {
          var vA = data.velocities[this.m_indexA].v.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var vB = data.velocities[this.m_indexB].v.Clone();
          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 Cdot = new b2Vec2(vB.x + -wB * this.m_rB.x - vA.x - -wA * this.m_rA.x + inv_h * this.m_correctionFactor * this.m_linearError.x, vB.y + wB * this.m_rB.y - vA.y - wA * this.m_rA.y + inv_h * this.m_correctionFactor * this.m_linearError.y);
          var impulse = b2Mul_m22_v2(this.m_linearMass, Cdot).Negate();
          var oldImpulse = this.m_linearImpulse.Clone();
          this.m_linearImpulse.Add(impulse);
          var maxImpulse = h * this.m_maxForce;
          if (this.m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) {
            this.m_linearImpulse.Normalize();
            this.m_linearImpulse.Multiply(maxImpulse);
          }
          impulse.Assign(b2Vec2.Subtract(this.m_linearImpulse, oldImpulse));
          vA.Subtract(b2Vec2.Multiply(mA, impulse));
          wA -= iA * b2Cross_v2_v2(this.m_rA, impulse);
          vB.Add(b2Vec2.Multiply(mB, impulse));
          wB += iB * b2Cross_v2_v2(this.m_rB, impulse);
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolvePositionConstraints: function(data) {
          return true;
        },
        _serialize: function(out) {
          var obj = out || {};
          this.parent.prototype._serialize.call(this, obj);
          obj["linearOffset"] = this.m_linearOffset._serialize();
          obj["angularOffset"] = this.m_angularOffset;
          obj["maxForce"] = this.m_maxForce;
          obj["maxTorque"] = this.m_maxTorque;
          obj["correctionFactor"] = this.m_correctionFactor;
          return obj;
        }
      };
      b2MotorJoint._extend(b2Joint);
      var b2_minPulleyLength = 2;
      function b2PulleyJointDef() {
        this.parent.call(this);
        this.type = b2Joint.e_pulleyJoint;
        this.groundAnchorA = new b2Vec2(-1, 1);
        this.groundAnchorB = new b2Vec2(1, 1);
        this.localAnchorA = new b2Vec2(-1, 0);
        this.localAnchorB = new b2Vec2(1, 0);
        this.lengthA = 0;
        this.lengthB = 0;
        this.ratio = 1;
        this.collideConnected = true;
        Object.seal(this);
      }
      b2PulleyJointDef.prototype = {
        Initialize: function(bA, bB, groundA, groundB, anchorA, anchorB, r) {
          this.bodyA = bA;
          this.bodyB = bB;
          this.groundAnchorA.Assign(groundA);
          this.groundAnchorB.Assign(groundB);
          this.localAnchorA.Assign(this.bodyA.GetLocalPoint(anchorA));
          this.localAnchorB.Assign(this.bodyB.GetLocalPoint(anchorB));
          var dA = b2Vec2.Subtract(anchorA, groundA);
          this.lengthA = dA.Length();
          var dB = b2Vec2.Subtract(anchorB, groundB);
          this.lengthB = dB.Length();
          this.ratio = r;
          b2Assert(this.ratio > b2_epsilon);
        },
        _deserialize: function(data, bodies, joints) {
          this.parent.prototype._deserialize.call(this, data, bodies, joints);
          this.groundAnchorA._deserialize(data["groundAnchorA"]);
          this.groundAnchorB._deserialize(data["groundAnchorB"]);
          this.localAnchorA._deserialize(data["localAnchorA"]);
          this.localAnchorB._deserialize(data["localAnchorB"]);
          this.lengthA = data["lengthA"];
          this.lengthB = data["lengthB"];
          this.ratio = data["ratio"];
        }
      };
      b2PulleyJointDef._extend(b2JointDef);
      function b2PulleyJoint(def) {
        this.parent.call(this, def);
        this.m_indexA = 0;
        this.m_indexB = 0;
        this.m_uA = new b2Vec2();
        this.m_uB = new b2Vec2();
        this.m_rA = new b2Vec2();
        this.m_rB = new b2Vec2();
        this.m_localCenterA = new b2Vec2();
        this.m_localCenterB = new b2Vec2();
        this.m_invMassA = 0;
        this.m_invMassB = 0;
        this.m_invIA = 0;
        this.m_invIB = 0;
        this.m_mass = 0;
        this.m_groundAnchorA = def.groundAnchorA.Clone();
        this.m_groundAnchorB = def.groundAnchorB.Clone();
        this.m_localAnchorA = def.localAnchorA.Clone();
        this.m_localAnchorB = def.localAnchorB.Clone();
        this.m_lengthA = def.lengthA;
        this.m_lengthB = def.lengthB;
        b2Assert(0 != def.ratio);
        this.m_ratio = def.ratio;
        this.m_constant = def.lengthA + this.m_ratio * def.lengthB;
        this.m_impulse = 0;
      }
      b2PulleyJoint.prototype = {
        GetAnchorA: function() {
          return this.m_bodyA.GetWorldPoint(this.m_localAnchorA);
        },
        GetAnchorB: function() {
          return this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
        },
        GetReactionForce: function(inv_dt) {
          var P = b2Vec2.Multiply(this.m_impulse, this.m_uB);
          return b2Vec2.Multiply(inv_dt, P);
        },
        GetReactionTorque: function(inv_dt) {
          return 0;
        },
        GetGroundAnchorA: function() {
          return this.m_groundAnchorA;
        },
        GetGroundAnchorB: function() {
          return this.m_groundAnchorB;
        },
        GetLengthA: function() {
          return this.m_lengthA;
        },
        GetLengthB: function() {
          return this.m_lengthB;
        },
        GetRatio: function() {
          return this.m_ratio;
        },
        GetCurrentLengthA: function() {
          var p = this.m_bodyA.GetWorldPoint(this.m_localAnchorA);
          var s = this.m_groundAnchorA;
          var d = b2Vec2.Subtract(p, s);
          return d.Length();
        },
        GetCurrentLengthB: function() {
          var p = this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
          var s = this.m_groundAnchorB;
          var d = b2Vec2.Subtract(p, s);
          return d.Length();
        },
        ShiftOrigin: function(newOrigin) {
          this.m_groundAnchorA.Subtract(newOrigin);
          this.m_groundAnchorB.Subtract(newOrigin);
        },
        InitVelocityConstraints: function(data) {
          this.m_indexA = this.m_bodyA.m_islandIndex;
          this.m_indexB = this.m_bodyB.m_islandIndex;
          this.m_localCenterA.Assign(this.m_bodyA.m_sweep.localCenter);
          this.m_localCenterB.Assign(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.Clone();
          var aA = data.positions[this.m_indexA].a;
          var vA = data.velocities[this.m_indexA].v.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var cB = data.positions[this.m_indexB].c.Clone();
          var aB = data.positions[this.m_indexB].a;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          this.m_rA.Assign(b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_localCenterA)));
          this.m_rB.Assign(b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB)));
          this.m_uA.Assign(b2Vec2.Add(cA, b2Vec2.Subtract(this.m_rA, this.m_groundAnchorA)));
          this.m_uB.Assign(b2Vec2.Add(cB, b2Vec2.Subtract(this.m_rB, this.m_groundAnchorB)));
          var lengthA = this.m_uA.Length();
          var lengthB = this.m_uB.Length();
          lengthA > 10 * b2_linearSlop ? this.m_uA.Multiply(1 / lengthA) : this.m_uA.SetZero();
          lengthB > 10 * b2_linearSlop ? this.m_uB.Multiply(1 / lengthB) : this.m_uB.SetZero();
          var ruA = b2Cross_v2_v2(this.m_rA, this.m_uA);
          var ruB = b2Cross_v2_v2(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;
          this.m_mass > 0 && (this.m_mass = 1 / this.m_mass);
          if (data.step.warmStarting) {
            this.m_impulse *= data.step.dtRatio;
            var PA = b2Vec2.Multiply(-this.m_impulse, this.m_uA);
            var PB = b2Vec2.Multiply(-this.m_ratio * this.m_impulse, this.m_uB);
            vA.Add(b2Vec2.Multiply(this.m_invMassA, PA));
            wA += this.m_invIA * b2Cross_v2_v2(this.m_rA, PA);
            vB.Add(b2Vec2.Multiply(this.m_invMassB, PB));
            wB += this.m_invIB * b2Cross_v2_v2(this.m_rB, PB);
          } else this.m_impulse = 0;
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolveVelocityConstraints: function(data) {
          var vA = data.velocities[this.m_indexA].v.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var vpA = b2Vec2.Add(vA, b2Cross_f_v2(wA, this.m_rA));
          var vpB = b2Vec2.Add(vB, b2Cross_f_v2(wB, this.m_rB));
          var Cdot = -b2Dot_v2_v2(this.m_uA, vpA) - this.m_ratio * b2Dot_v2_v2(this.m_uB, vpB);
          var impulse = -this.m_mass * Cdot;
          this.m_impulse += impulse;
          var PA = b2Vec2.Multiply(-impulse, this.m_uA);
          var PB = b2Vec2.Multiply(-this.m_ratio, b2Vec2.Multiply(impulse, this.m_uB));
          vA.Add(b2Vec2.Multiply(this.m_invMassA, PA));
          wA += this.m_invIA * b2Cross_v2_v2(this.m_rA, PA);
          vB.Add(b2Vec2.Multiply(this.m_invMassB, PB));
          wB += this.m_invIB * b2Cross_v2_v2(this.m_rB, PB);
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolvePositionConstraints: function(data) {
          var cA = data.positions[this.m_indexA].c.Clone();
          var aA = data.positions[this.m_indexA].a;
          var cB = data.positions[this.m_indexB].c.Clone();
          var aB = data.positions[this.m_indexB].a;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          var rA = b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_localCenterA));
          var rB = b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB));
          var uA = b2Vec2.Add(cA, b2Vec2.Subtract(rA, this.m_groundAnchorA));
          var uB = b2Vec2.Add(cB, b2Vec2.Subtract(rB, this.m_groundAnchorB));
          var lengthA = uA.Length();
          var lengthB = uB.Length();
          lengthA > 10 * b2_linearSlop ? uA.Multiply(1 / lengthA) : uA.SetZero();
          lengthB > 10 * b2_linearSlop ? uB.Multiply(1 / lengthB) : uB.SetZero();
          var ruA = b2Cross_v2_v2(rA, uA);
          var ruB = b2Cross_v2_v2(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;
          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.Multiply(-impulse, uA);
          var PB = b2Vec2.Multiply(-this.m_ratio, b2Vec2.Multiply(impulse, uB));
          cA.Add(b2Vec2.Multiply(this.m_invMassA, PA));
          aA += this.m_invIA * b2Cross_v2_v2(rA, PA);
          cB.Add(b2Vec2.Multiply(this.m_invMassB, PB));
          aB += this.m_invIB * b2Cross_v2_v2(rB, PB);
          data.positions[this.m_indexA].c.Assign(cA);
          data.positions[this.m_indexA].a = aA;
          data.positions[this.m_indexB].c.Assign(cB);
          data.positions[this.m_indexB].a = aB;
          return linearError < b2_linearSlop;
        },
        _serialize: function(out) {
          var obj = out || {};
          this.parent.prototype._serialize.call(this, obj);
          obj["groundAnchorA"] = this.m_groundAnchorA._serialize();
          obj["groundAnchorB"] = this.m_groundAnchorB._serialize();
          obj["localAnchorA"] = this.m_localAnchorA._serialize();
          obj["localAnchorB"] = this.m_localAnchorB._serialize();
          obj["lengthA"] = this.m_lengthA;
          obj["lengthB"] = this.m_lengthB;
          obj["ratio"] = this.m_ratio;
          return obj;
        }
      };
      b2PulleyJoint._extend(b2Joint);
      function b2RopeJointDef() {
        this.parent.call(this);
        this.type = b2Joint.e_ropeJoint;
        this.localAnchorA = new b2Vec2(-1, 0);
        this.localAnchorB = new b2Vec2(1, 0);
        this.maxLength = 0;
        Object.seal(this);
      }
      b2RopeJointDef.prototype = {
        _deserialize: function(data, bodies, joints) {
          this.parent.prototype._deserialize.call(this, data, bodies, joints);
          this.localAnchorA._deserialize(data["localAnchorA"]);
          this.localAnchorB._deserialize(data["localAnchorB"]);
          this.maxLength = data["maxLength"];
        }
      };
      b2RopeJointDef._extend(b2JointDef);
      function b2RopeJoint(def) {
        this.parent.call(this, def);
        this.m_localAnchorA = def.localAnchorA.Clone();
        this.m_localAnchorB = def.localAnchorB.Clone();
        this.m_maxLength = def.maxLength;
        this.m_mass = 0;
        this.m_impulse = 0;
        this.m_state = b2Joint.e_inactiveLimit;
        this.m_length = 0;
        this.m_indexA = 0;
        this.m_indexB = 0;
        this.m_u = new b2Vec2();
        this.m_rA = new b2Vec2();
        this.m_rB = new b2Vec2();
        this.m_localCenterA = new b2Vec2();
        this.m_localCenterB = new b2Vec2();
        this.m_invMassA = 0;
        this.m_invMassB = 0;
        this.m_invIA = 0;
        this.m_invIB = 0;
      }
      b2RopeJoint.prototype = {
        GetAnchorA: function() {
          return this.m_bodyA.GetWorldPoint(this.m_localAnchorA);
        },
        GetAnchorB: function() {
          return this.m_bodyB.GetWorldPoint(this.m_localAnchorB);
        },
        GetReactionForce: function(inv_dt) {
          var F = b2Vec2.Multiply(inv_dt * this.m_impulse, this.m_u);
          return F;
        },
        GetReactionTorque: function(inv_dt) {
          return 0;
        },
        GetLocalAnchorA: function() {
          return this.m_localAnchorA;
        },
        GetLocalAnchorB: function() {
          return this.m_localAnchorB;
        },
        SetMaxLength: function(length) {
          this.m_maxLength = length;
        },
        GetMaxLength: function() {
          return this.m_maxLength;
        },
        GetLimitState: function() {
          return this.m_state;
        },
        InitVelocityConstraints: function(data) {
          this.m_indexA = this.m_bodyA.m_islandIndex;
          this.m_indexB = this.m_bodyB.m_islandIndex;
          this.m_localCenterA.Assign(this.m_bodyA.m_sweep.localCenter);
          this.m_localCenterB.Assign(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.Clone();
          var aA = data.positions[this.m_indexA].a;
          var vA = data.velocities[this.m_indexA].v.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var cB = data.positions[this.m_indexB].c.Clone();
          var aB = data.positions[this.m_indexB].a;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          this.m_rA.Assign(b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_localCenterA)));
          this.m_rB.Assign(b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB)));
          this.m_u.Assign(b2Vec2.Subtract(b2Vec2.Subtract(b2Vec2.Add(cB, this.m_rB), cA), this.m_rA));
          this.m_length = this.m_u.Length();
          var C = this.m_length - this.m_maxLength;
          this.m_state = C > 0 ? b2Joint.e_atUpperLimit : b2Joint.e_inactiveLimit;
          if (!(this.m_length > b2_linearSlop)) {
            this.m_u.SetZero();
            this.m_mass = 0;
            this.m_impulse = 0;
            return;
          }
          this.m_u.Multiply(1 / this.m_length);
          var crA = b2Cross_v2_v2(this.m_rA, this.m_u);
          var crB = b2Cross_v2_v2(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 = 0 != invMass ? 1 / invMass : 0;
          if (data.step.warmStarting) {
            this.m_impulse *= data.step.dtRatio;
            var P = b2Vec2.Multiply(this.m_impulse, this.m_u);
            vA.Subtract(b2Vec2.Multiply(this.m_invMassA, P));
            wA -= this.m_invIA * b2Cross_v2_v2(this.m_rA, P);
            vB.Add(b2Vec2.Multiply(this.m_invMassB, P));
            wB += this.m_invIB * b2Cross_v2_v2(this.m_rB, P);
          } else this.m_impulse = 0;
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolveVelocityConstraints: function(data) {
          var vA = data.velocities[this.m_indexA].v.Clone();
          var wA = data.velocities[this.m_indexA].w;
          var vB = data.velocities[this.m_indexB].v.Clone();
          var wB = data.velocities[this.m_indexB].w;
          var vpA = b2Vec2.Add(vA, b2Cross_f_v2(wA, this.m_rA));
          var vpB = b2Vec2.Add(vB, b2Cross_f_v2(wB, this.m_rB));
          var C = this.m_length - this.m_maxLength;
          var Cdot = b2Dot_v2_v2(this.m_u, b2Vec2.Subtract(vpB, vpA));
          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.Multiply(impulse, this.m_u);
          vA.Subtract(b2Vec2.Multiply(this.m_invMassA, P));
          wA -= this.m_invIA * b2Cross_v2_v2(this.m_rA, P);
          vB.Add(b2Vec2.Multiply(this.m_invMassB, P));
          wB += this.m_invIB * b2Cross_v2_v2(this.m_rB, P);
          data.velocities[this.m_indexA].v.Assign(vA);
          data.velocities[this.m_indexA].w = wA;
          data.velocities[this.m_indexB].v.Assign(vB);
          data.velocities[this.m_indexB].w = wB;
        },
        SolvePositionConstraints: function(data) {
          var cA = data.positions[this.m_indexA].c.Clone();
          var aA = data.positions[this.m_indexA].a;
          var cB = data.positions[this.m_indexB].c.Clone();
          var aB = data.positions[this.m_indexB].a;
          var qA = new b2Rot(aA), qB = new b2Rot(aB);
          var rA = b2Mul_r_v2(qA, b2Vec2.Subtract(this.m_localAnchorA, this.m_localCenterA));
          var rB = b2Mul_r_v2(qB, b2Vec2.Subtract(this.m_localAnchorB, this.m_localCenterB));
          var u = b2Vec2.Subtract(b2Vec2.Subtract(b2Vec2.Add(cB, rB), cA), 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.Multiply(impulse, u);
          cA.Subtract(b2Vec2.Multiply(this.m_invMassA, P));
          aA -= this.m_invIA * b2Cross_v2_v2(rA, P);
          cB.Add(b2Vec2.Multiply(this.m_invMassB, P));
          aB += this.m_invIB * b2Cross_v2_v2(rB, P);
          data.positions[this.m_indexA].c.Assign(cA);
          data.positions[this.m_indexA].a = aA;
          data.positions[this.m_indexB].c.Assign(cB);
          data.positions[this.m_indexB].a = aB;
          return length - this.m_maxLength < b2_linearSlop;
        },
        _serialize: function(out) {
          var obj = out || {};
          this.parent.prototype._serialize.call(this, obj);
          obj["localAnchorA"] = this.m_localAnchorA._serialize();
          obj["localAnchorB"] = this.m_localAnchorB._serialize();
          obj["maxLength"] = this.m_maxLength;
          return obj;
        }
      };
      b2RopeJoint._extend(b2Joint);
      var expf = Math.exp;
      function b2RopeDef() {
        this.vertices = null;
        this.count = 0;
        this.masses = null;
        this.gravity = new b2Vec2();
        this.damping = .1;
        this.k2 = .9;
        this.k3 = .1;
      }
      function b2Rope() {
        this.m_count = 0;
        this.m_ps = null;
        this.m_p0s = null;
        this.m_vs = null;
        this.m_ims = null;
        this.m_Ls = null;
        this.m_as = null;
        this.m_damping = 0;
        this.m_gravity = new b2Vec2();
        this.m_k2 = 1;
        this.m_k3 = .1;
      }
      b2Rope.prototype = {
        Initialize: function(def) {
          b2Assert(def.count >= 3);
          this.m_count = def.count;
          this.m_ps = new Array(this.m_count);
          this.m_p0s = new Array(this.m_count);
          this.m_vs = new Array(this.m_count);
          this.m_ims = new Array(this.m_count);
          for (var i = 0; i < this.m_count; ++i) {
            this.m_ps[i] = def.vertices[i].Clone();
            this.m_p0s[i] = def.vertices[i].Clone();
            this.m_vs[i] = new b2Vec2();
            var m = def.masses[i];
            this.m_ims[i] = m > 0 ? 1 / m : 0;
          }
          var count2 = this.m_count - 1;
          var count3 = this.m_count - 2;
          this.m_Ls = new Array(count2);
          this.m_as = new Array(count3);
          for (var i = 0; i < count2; ++i) {
            var p1 = this.m_ps[i];
            var p2 = this.m_ps[i + 1];
            this.m_Ls[i] = b2Distance(p1, p2);
          }
          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 d1 = b2Vec2.Subtract(p2, p1);
            var d2 = b2Vec2.Subtract(p3, p2);
            var a = b2Cross_v2_v2(d1, d2);
            var b = b2Dot_v2_v2(d1, d2);
            this.m_as[i] = b2Atan2(a, b);
          }
          this.m_gravity = def.gravity.Clone();
          this.m_damping = def.damping;
          this.m_k2 = def.k2;
          this.m_k3 = def.k3;
        },
        Step: function(h, iterations) {
          if (0 == h) return;
          var d = expf(-h * this.m_damping);
          for (var i = 0; i < this.m_count; ++i) {
            this.m_p0s[i].Assign(this.m_ps[i]);
            this.m_ims[i] > 0 && this.m_vs[i].Add(b2Vec2.Multiply(h, this.m_gravity));
            this.m_vs[i].Multiply(d);
            this.m_ps[i].Add(b2Vec2.Multiply(h, this.m_vs[i]));
          }
          for (var i = 0; i < iterations; ++i) {
            this.SolveC2();
            this.SolveC3();
            this.SolveC2();
          }
          var inv_h = 1 / h;
          for (var i = 0; i < this.m_count; ++i) this.m_vs[i] = b2Vec2.Multiply(inv_h, b2Vec2.Subtract(this.m_ps[i], this.m_p0s[i]));
        },
        GetVertexCount: function() {
          return this.m_count;
        },
        GetVertices: function() {
          return this.m_ps;
        },
        Draw: function(draw) {
          var c = new b2Color(.4, .5, .7);
          for (var i = 0; i < this.m_count - 1; ++i) draw.DrawSegment(this.m_ps[i], this.m_ps[i + 1], c);
        },
        SetAngle: function(angle) {
          var count3 = this.m_count - 2;
          for (var i = 0; i < count3; ++i) this.m_as[i] = angle;
        },
        SolveC2: function() {
          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.Subtract(p2, p1);
            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.Subtract(b2Vec2.Multiply(this.m_k2 * s1 * (this.m_Ls[i] - L), d));
            p2.Add(b2Vec2.Multiply(this.m_k2 * s2 * (this.m_Ls[i] - L), d));
          }
        },
        SolveC3: function() {
          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.Subtract(p2, p1);
            var d2 = b2Vec2.Subtract(p3, p2);
            var L1sqr = d1.LengthSquared();
            var L2sqr = d2.LengthSquared();
            if (L1sqr * L2sqr == 0) continue;
            var a = b2Cross_v2_v2(d1, d2);
            var b = b2Dot_v2_v2(d1, d2);
            var angle = b2Atan2(a, b);
            var Jd1 = b2Vec2.Multiply(-1 / L1sqr, d1.Skew());
            var Jd2 = b2Vec2.Multiply(1 / L2sqr, d2.Skew());
            var J1 = b2Vec2.Negate(Jd1);
            var J2 = b2Vec2.Subtract(Jd1, Jd2);
            var J3 = Jd2;
            var mass = m1 * b2Dot_v2_v2(J1, J1) + m2 * b2Dot_v2_v2(J2, J2) + m3 * b2Dot_v2_v2(J3, J3);
            if (0 == mass) 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.Add(b2Vec2.Multiply(m1 * impulse, J1));
            p2.Add(b2Vec2.Multiply(m2 * impulse, J2));
            p3.Add(b2Vec2.Multiply(m3 * impulse, J3));
          }
        }
      };
      var b2JsonSerializer = {
        serialize: function(world) {
          var shapes = [];
          var i;
          var serialized;
          var b;
          var f;
          var shape;
          for (b = world.GetBodyList(); b; b = b.GetNext()) for (f = b.GetFixtureList(); f; f = f.GetNext()) {
            shape = f.GetShape();
            f.__temp_shape_id = shapes.length;
            shapes.push(shape._serialize());
          }
          var fixtures = [];
          for (b = world.GetBodyList(); b; b = b.GetNext()) {
            b.__temp_fixture_ids = [];
            for (f = b.GetFixtureList(); f; f = f.GetNext()) {
              serialized = f._serialize();
              serialized["shape"] = f.__temp_shape_id;
              delete f.__temp_shape_id;
              b.__temp_fixture_ids.push(fixtures.length);
              fixtures.push(serialized);
            }
          }
          var bodies = [];
          for (b = world.GetBodyList(); b; b = b.GetNext()) {
            serialized = b._serialize();
            serialized.fixtures = [];
            for (i = 0; i < b.__temp_fixture_ids.length; ++i) serialized.fixtures.push(b.__temp_fixture_ids[i]);
            delete b.__temp_fixture_ids;
            b.__temp_body_id = bodies.length;
            bodies.push(serialized);
          }
          var joints = [];
          var j;
          for (j = world.GetJointList(), i = 0; j; j = j.GetNext(), ++i) j.__temp_joint_id = i;
          for (j = world.GetJointList(); j; j = j.GetNext()) {
            if (j.GetType() === b2Joint.e_mouseJoint) continue;
            serialized = j._serialize();
            serialized["bodyA"] = j.GetBodyA().__temp_body_id;
            serialized["bodyB"] = j.GetBodyB().__temp_body_id;
            joints.push(serialized);
          }
          for (j = world.GetJointList(); j; j = j.GetNext()) delete j.__temp_joint_id;
          for (b = world.GetBodyList(); b; b = b.GetNext()) delete b.__temp_body_id;
          return {
            shapes: shapes,
            fixtures: fixtures,
            bodies: bodies,
            joints: joints
          };
        },
        deserialize: function(serialized, world, clear) {
          var deserialized = JSON.parse(serialized);
          if (clear) {
            for (var b = world.GetBodyList(); b; ) {
              var next = b.GetNext();
              world.DestroyBody(b);
              b = next;
            }
            for (var j = world.GetJointList(); j; ) {
              var next = j.GetNext();
              world.DestroyJoint(j);
              j = next;
            }
          }
          var shapes = [];
          for (var i = 0; i < deserialized.shapes.length; ++i) {
            var shapeData = deserialized.shapes[i];
            var shape;
            switch (shapeData.m_type) {
             case b2Shape.e_circle:
              shape = new b2CircleShape();
              break;

             case b2Shape.e_edge:
              shape = new b2EdgeShape();
              break;

             case b2Shape.e_chain:
              shape = new b2ChainShape();
              break;

             case b2Shape.e_polygon:
              shape = new b2PolygonShape();
            }
            shape._deserialize(shapeData);
            shapes.push(shape);
          }
          var fixtures = [];
          for (i = 0; i < deserialized.fixtures.length; ++i) {
            var fixtureData = deserialized.fixtures[i];
            var fixture = new b2FixtureDef();
            fixture._deserialize(fixtureData);
            fixture.shape = shapes[fixtureData["shape"]];
            fixtures.push(fixture);
          }
          var bodies = [];
          for (i = 0; i < deserialized.bodies.length; ++i) {
            var bodyData = deserialized.bodies[i];
            var def = new b2BodyDef();
            def._deserialize(bodyData);
            var body = world.CreateBody(def);
            for (var x = 0; x < bodyData.fixtures.length; ++x) body.CreateFixture(fixtures[bodyData.fixtures[x]]);
            bodies.push(body);
          }
          var joints = [];
          var gears = [];
          for (i = 0; i < deserialized.joints.length; ++i) {
            var jointData = deserialized.joints[i];
            var jointDef;
            switch (jointData.type) {
             case b2Joint.e_revoluteJoint:
              jointDef = new b2RevoluteJointDef();
              break;

             case b2Joint.e_prismaticJoint:
              jointDef = new b2PrismaticJointDef();
              break;

             case b2Joint.e_distanceJoint:
              jointDef = new b2DistanceJointDef();
              break;

             case b2Joint.e_pulleyJoint:
              jointDef = new b2PulleyJointDef();
              break;

             case b2Joint.e_gearJoint:
              jointDef = new b2GearJointDef();
              break;

             case b2Joint.e_wheelJoint:
              jointDef = new b2WheelJointDef();
              break;

             case b2Joint.e_weldJoint:
              jointDef = new b2WeldJointDef();
              break;

             case b2Joint.e_frictionJoint:
              jointDef = new b2FrictionJointDef();
              break;

             case b2Joint.e_ropeJoint:
              jointDef = new b2RopeJointDef();
              break;

             case b2Joint.e_motorJoint:
              jointDef = new b2MotorJointDef();
              break;

             default:
              throw new Error("unknown joint");
            }
            jointDef._deserialize(jointData, bodies);
            if (jointData.type === b2Joint.e_gearJoint) {
              gears.push([ jointDef, joints.length ]);
              joints.push(null);
            } else {
              var joint = world.CreateJoint(jointDef);
              joints.push(joint);
            }
          }
          for (i = 0; i < gears.length; ++i) {
            gears[i][0].joint1 = joints[gears[i][0].joint1];
            gears[i][0].joint2 = joints[gears[i][0].joint2];
            joint = world.CreateJoint(gears[i][0]);
            joints[gears[i][1]] = joint;
          }
        }
      };
      var b2RUBELoader = (function() {
        function parseVector(obj) {
          return new b2Vec2(obj ? obj.x || 0 : 0, obj ? obj.y || 0 : 0);
        }
        function parseVectorArray(obj) {
          var vals = new Array(obj.x.length);
          for (var i = 0; i < vals.length; ++i) vals[i] = new b2Vec2(obj.x[i], obj.y[i]);
          return vals;
        }
        function parseProperty(obj, instance) {
          var name = obj.name;
          var val;
          if ("undefined" !== typeof obj["int"]) val = obj["int"]; else if ("undefined" !== typeof obj["float"]) val = obj["float"]; else if ("undefined" !== typeof obj["string"]) val = obj["string"]; else if ("undefined" !== typeof obj["bool"]) val = obj["bool"]; else {
            if ("undefined" === typeof obj.vec2) throw new Error("unknown property type");
            val = parseVector(obj.vec2);
          }
          if (instance.hasOwnProperty(name)) throw new Error("custom property possibly overwriting an existing one");
          instance[name] = val;
        }
        function parseFixture(obj, body) {
          var def = new b2FixtureDef();
          def.density = obj.density || 0;
          def.filter.categoryBits = "undefined" === typeof obj["filter-categoryBits"] ? 1 : obj["filter-categoryBits"];
          def.filter.maskBits = "undefined" === typeof obj["filter-maskBits"] ? 65535 : obj["filter-maskBits"];
          def.filter.groupIndex = "undefined" === typeof obj["filter-groupIndex"] ? 0 : obj["filter-groupIndex"];
          def.friction = obj.friction || 0;
          def.restitution = obj.restitution || 0;
          def.isSensor = obj.sensor || 0;
          var shape;
          if ("undefined" !== typeof obj.circle) {
            shape = new b2CircleShape();
            shape.m_p = parseVector(obj.circle.center);
            shape.m_radius = obj.circle.radius || 0;
          } else if ("undefined" !== typeof obj.polygon) {
            var vertices = parseVectorArray(obj.polygon.vertices);
            shape = new b2PolygonShape();
            shape.Set(vertices, vertices.length);
          } else {
            if ("undefined" === typeof obj.chain) throw new Error("unknown shape type");
            var vertices = parseVectorArray(obj.chain.vertices);
            shape = new b2ChainShape();
            shape.m_count = vertices.length;
            shape.m_vertices = vertices;
            (shape.m_hasNextVertex = obj.chain.hasNextVertex) && (shape.m_nextVertex = parseVector(obj.chain.nextVertex));
            (shape.m_hasPrevVertex = obj.chain.hasPrevVertex) && (shape.m_prevVertex = parseVector(obj.chain.prevVertex));
          }
          def.shape = shape;
          var fixture = body.CreateFixture(def);
          fixture.name = obj.name;
          if (obj.customProperties) for (var i = 0; i < obj.customProperties.length; ++i) parseProperty(obj, fixture);
        }
        function parseBody(obj, world) {
          var def = new b2BodyDef();
          def.type = obj.type || b2Body.b2_staticBody;
          def.angle = obj.angle || 0;
          def.angularDamping = obj.angularDamping || 0;
          def.angularVelocity = obj.angularVelocity || 0;
          def.awake = obj.awake || false;
          def.bullet = obj.bullet || false;
          def.fixedRotation = obj.fixedRotation || false;
          def.linearDamping = obj.linearDamping || false;
          def.linearVelocity = parseVector(obj.linearVelocity);
          def.gravityScale = "undefined" !== typeof obj.gravityScale ? obj.gravityScale : 1;
          var md = new b2MassData();
          md.mass = obj["massData-mass"] || 0;
          md.center = parseVector(obj["massData-center"]);
          md.I = obj["massData-I"] || 0;
          def.position = parseVector(obj.position);
          var body = world.CreateBody(def);
          body.name = obj.name;
          body.SetMassData(md);
          if (obj.fixture) for (var i = 0; i < obj.fixture.length; ++i) parseFixture(obj.fixture[i], body);
          if (obj.customProperties) for (i = 0; i < obj.customProperties.length; ++i) parseProperty(obj, body);
          return body;
        }
        var jointsList = {
          revolute: b2RevoluteJointDef,
          distance: b2DistanceJointDef,
          prismatic: b2PrismaticJointDef,
          wheel: b2WheelJointDef,
          rope: b2RopeJointDef,
          motor: b2MotorJointDef,
          weld: b2WeldJointDef,
          friction: b2FrictionJointDef
        };
        function parseJoint(obj, world, bodies) {
          if (!jointsList[obj.type]) throw new Error("unknown joint type");
          var jd = new jointsList[obj.type]();
          switch (jd.type) {
           case b2Joint.e_revoluteJoint:
            jd.localAnchorA = parseVector(obj.anchorA);
            jd.localAnchorB = parseVector(obj.anchorB);
            jd.enableLimit = obj.enableLimit || false;
            jd.enableMotor = obj.enableMotor || false;
            jd.lowerAngle = obj.lowerLimit || 0;
            jd.maxMotorTorque = obj.maxMotorTorque || 0;
            jd.motorSpeed = obj.motorSpeed || 0;
            jd.referenceAngle = obj.refAngle || 0;
            jd.upperAngle = obj.upperLimit || 0;
            break;

           case b2Joint.e_distanceJoint:
            jd.localAnchorA = parseVector(obj.anchorA);
            jd.localAnchorB = parseVector(obj.anchorB);
            jd.dampingRatio = obj.dampingRatio || 0;
            jd.frequencyHz = obj.frequency || 0;
            jd.length = obj.length || 0;
            break;

           case b2Joint.e_prismaticJoint:
            jd.localAnchorA = parseVector(obj.anchorA);
            jd.localAnchorB = parseVector(obj.anchorB);
            jd.enableLimit = obj.enableLimit || false;
            jd.enableMotor = obj.enableMotor || false;
            jd.localAxisA = parseVector(obj.localAxisA);
            jd.lowerTranslation = obj.lowerLimit || 0;
            jd.maxMotorForce = obj.maxMotorForce || 0;
            jd.motorSpeed = obj.motorSpeed || 0;
            jd.referenceAngle = obj.refAngle || 0;
            jd.upperTranslation = obj.upperLimit || 0;
            break;

           case b2Joint.e_wheelJoint:
            jd.localAnchorA = parseVector(obj.anchorA);
            jd.localAnchorB = parseVector(obj.anchorB);
            jd.enableMotor = obj.enableMotor || false;
            jd.localAxisA = parseVector(obj.localAxisA);
            jd.maxMotorTorque = obj.maxMotorTorque || 0;
            jd.motorSpeed = obj.motorSpeed || 0;
            jd.dampingRatio = obj.springDampingRatio || 0;
            jd.frequencyHz = obj.springFrequency || 0;
            break;

           case b2Joint.e_ropeJoint:
            jd.localAnchorA = parseVector(obj.anchorA);
            jd.localAnchorB = parseVector(obj.anchorB);
            jd.maxLength = obj.maxLength || 0;
            break;

           case b2Joint.e_motorJoint:
            jd.linearOffset = parseVector(obj.anchorA);
            jd.angularOffset = obj.refAngle || 0;
            jd.maxForce = obj.maxForce || 0;
            jd.maxTorque = obj.maxTorque || 0;
            jd.correctionFactor = obj.correctionFactor || 0;
            break;

           case b2Joint.e_weldJoint:
            jd.localAnchorA = parseVector(obj.anchorA);
            jd.localAnchorB = parseVector(obj.anchorB);
            jd.referenceAngle = obj.refAngle || 0;
            jd.dampingRatio = obj.dampingRatio || 0;
            jd.frequencyHz = obj.frequencyHz || 0;
            break;

           case b2Joint.e_frictionJoint:
            jd.localAnchorA = parseVector(obj.anchorA);
            jd.localAnchorB = parseVector(obj.anchorB);
            jd.maxForce = obj.maxForce || 0;
            jd.maxTorque = obj.maxTorque || 0;
            break;

           default:
            throw new Error("wat?");
          }
          jd.bodyA = bodies[obj.bodyA || 0];
          jd.bodyB = bodies[obj.bodyB || 0];
          jd.collideConnected = obj.collideConnected || false;
          var joint = world.CreateJoint(jd);
          joint.name = obj.name;
          if (obj.customProperties) for (var i = 0; i < obj.customProperties.length; ++i) parseProperty(obj, joint);
          return joint;
        }
        function b2RubeParameters() {
          this.world = null;
          this.positionIterations = 0;
          this.velocityIterations = 0;
          this.stepsPerSecond = 0;
          this.fixtures = {};
          this.bodies = {};
          this.joints = {};
          Object.seal(this);
        }
        function parseWorld(obj, world) {
          var params = new b2RubeParameters();
          params.world = world = world || new b2World(new b2Vec2(0, 0));
          params.positionIterations = obj.positionIterations || 0;
          params.velocityIterations = obj.velocityIterations || 0;
          params.stepsPerSecond = obj.stepsPerSecond || 0;
          obj.gravity && world.SetGravity(parseVector(obj.gravity));
          world.SetAllowSleeping(obj.allowSleep || false);
          world.SetAutoClearForces(obj.autoClearForces || false);
          world.SetWarmStarting(obj.warmStarting || false);
          world.SetContinuousPhysics(obj.continuousPhysics || false);
          world.SetSubStepping(obj.subStepping || false);
          var bodies = [];
          var bl = obj.body;
          if (bl) for (var i = 0; i < bl.length; ++i) {
            var body = parseBody(bl[i], world);
            bodies.push(body);
            for (var f = body.GetFixtureList(); f; f = f.GetNext()) {
              params.fixtures[f.name] || (params.fixtures[f.name] = []);
              params.fixtures[f.name].push(f);
            }
            params.bodies[body.name] || (params.bodies[body.name] = []);
            params.bodies[body.name].push(body);
          }
          var joints = [];
          var jl = obj.joint;
          if (jl) for (i = 0; i < jl.length; ++i) {
            var joint = parseJoint(jl[i], world, bodies);
            joints.push(joint);
            params.joints[joint.name] || (params.joints[joint.name] = []);
            params.joints[joint.name].push(joint);
          }
          return params;
        }
        return {
          parseWorld: parseWorld
        };
      })();
      var mappings = [ {
        trimmed: "version",
        name: "b2_version",
        def: b2_version
      }, {
        trimmed: "Vec2",
        name: "b2Vec2",
        def: b2Vec2
      }, {
        trimmed: "Vec3",
        name: "b2Vec3",
        def: b2Vec3
      }, {
        trimmed: "Mat22",
        name: "b2Mat22",
        def: b2Mat22
      }, {
        trimmed: "Mat33",
        name: "b2Mat33",
        def: b2Mat33
      }, {
        trimmed: "Rot",
        name: "b2Rot",
        def: b2Rot
      }, {
        trimmed: "Transform",
        name: "b2Transform",
        def: b2Transform
      }, {
        trimmed: "Sweep",
        name: "b2Sweep",
        def: b2Sweep
      }, {
        trimmed: "Dot_v2_v2",
        name: "b2Dot_v2_v2",
        def: b2Dot_v2_v2
      }, {
        trimmed: "Cross_v2_v2",
        name: "b2Cross_v2_v2",
        def: b2Cross_v2_v2
      }, {
        trimmed: "Cross_v2_f",
        name: "b2Cross_v2_f",
        def: b2Cross_v2_f
      }, {
        trimmed: "Cross_f_v2",
        name: "b2Cross_f_v2",
        def: b2Cross_f_v2
      }, {
        trimmed: "Mul_m22_v2",
        name: "b2Mul_m22_v2",
        def: b2Mul_m22_v2
      }, {
        trimmed: "MulT_m22_v2",
        name: "b2MulT_m22_v2",
        def: b2MulT_m22_v2
      }, {
        trimmed: "Distance",
        name: "b2Distance",
        def: b2Distance
      }, {
        trimmed: "DistanceSquared",
        name: "b2DistanceSquared",
        def: b2DistanceSquared
      }, {
        trimmed: "Dot_v3_v3",
        name: "b2Dot_v3_v3",
        def: b2Dot_v3_v3
      }, {
        trimmed: "Cross_v3_v3",
        name: "b2Cross_v3_v3",
        def: b2Cross_v3_v3
      }, {
        trimmed: "Mul_m22_m22",
        name: "b2Mul_m22_m22",
        def: b2Mul_m22_m22
      }, {
        trimmed: "MulT_m22_m22",
        name: "b2MulT_m22_m22",
        def: b2MulT_m22_m22
      }, {
        trimmed: "Mul_m33_v3",
        name: "b2Mul_m33_v3",
        def: b2Mul_m33_v3
      }, {
        trimmed: "Mul22_m33_v2",
        name: "b2Mul22_m33_v2",
        def: b2Mul22_m33_v2
      }, {
        trimmed: "Mul_r_r",
        name: "b2Mul_r_r",
        def: b2Mul_r_r
      }, {
        trimmed: "MulT_r_r",
        name: "b2MulT_r_r",
        def: b2MulT_r_r
      }, {
        trimmed: "Mul_r_v2",
        name: "b2Mul_r_v2",
        def: b2Mul_r_v2
      }, {
        trimmed: "MulT_r_v2",
        name: "b2MulT_r_v2",
        def: b2MulT_r_v2
      }, {
        trimmed: "Mul_t_v2",
        name: "b2Mul_t_v2",
        def: b2Mul_t_v2
      }, {
        trimmed: "Min_v2",
        name: "b2Min_v2",
        def: b2Min_v2
      }, {
        trimmed: "Max_v2",
        name: "b2Max_v2",
        def: b2Max_v2
      }, {
        trimmed: "Clamp",
        name: "b2Clamp",
        def: b2Clamp
      }, {
        trimmed: "MulT_t_v2",
        name: "b2MulT_t_v2",
        def: b2MulT_t_v2
      }, {
        trimmed: "Mul_t_t",
        name: "b2Mul_t_t",
        def: b2Mul_t_t
      }, {
        trimmed: "MulT_t_t",
        name: "b2MulT_t_t",
        def: b2MulT_t_t
      }, {
        trimmed: "Clamp_v2",
        name: "b2Clamp_v2",
        def: b2Clamp_v2
      }, {
        trimmed: "NextPowerOfTwo",
        name: "b2NextPowerOfTwo",
        def: b2NextPowerOfTwo
      }, {
        trimmed: "Abs_v2",
        name: "b2Abs_v2",
        def: b2Abs_v2
      }, {
        trimmed: "Abs_m22",
        name: "b2Abs_m22",
        def: b2Abs_m22
      }, {
        trimmed: "IsPowerOfTwo",
        name: "b2IsPowerOfTwo",
        def: b2IsPowerOfTwo
      }, {
        trimmed: "RandomFloat",
        name: "b2RandomFloat",
        def: b2RandomFloat
      }, {
        trimmed: "Timer",
        name: "b2Timer",
        def: b2Timer
      }, {
        trimmed: "Color",
        name: "b2Color",
        def: b2Color
      }, {
        trimmed: "Draw",
        name: "b2Draw",
        def: b2Draw
      }, {
        trimmed: "ContactID",
        name: "b2ContactID",
        def: b2ContactID
      }, {
        trimmed: "ManifoldPoint",
        name: "b2ManifoldPoint",
        def: b2ManifoldPoint
      }, {
        trimmed: "Manifold",
        name: "b2Manifold",
        def: b2Manifold
      }, {
        trimmed: "WorldManifold",
        name: "b2WorldManifold",
        def: b2WorldManifold
      }, {
        trimmed: "GetPointStates",
        name: "b2GetPointStates",
        def: b2GetPointStates
      }, {
        trimmed: "ClipVertex",
        name: "b2ClipVertex",
        def: b2ClipVertex
      }, {
        trimmed: "RayCastInput",
        name: "b2RayCastInput",
        def: b2RayCastInput
      }, {
        trimmed: "RayCastOutput",
        name: "b2RayCastOutput",
        def: b2RayCastOutput
      }, {
        trimmed: "AABB",
        name: "b2AABB",
        def: b2AABB
      }, {
        trimmed: "CollideCircles",
        name: "b2CollideCircles",
        def: b2CollideCircles
      }, {
        trimmed: "CollidePolygonAndCircle",
        name: "b2CollidePolygonAndCircle",
        def: b2CollidePolygonAndCircle
      }, {
        trimmed: "FindMaxSeparation",
        name: "b2FindMaxSeparation",
        def: b2FindMaxSeparation
      }, {
        trimmed: "FindIncidentEdge",
        name: "b2FindIncidentEdge",
        def: b2FindIncidentEdge
      }, {
        trimmed: "CollidePolygons",
        name: "b2CollidePolygons",
        def: b2CollidePolygons
      }, {
        trimmed: "CollideEdgeAndCircle",
        name: "b2CollideEdgeAndCircle",
        def: b2CollideEdgeAndCircle
      }, {
        trimmed: "EPAxis",
        name: "b2EPAxis",
        def: b2EPAxis
      }, {
        trimmed: "TempPolygon",
        name: "b2TempPolygon",
        def: b2TempPolygon
      }, {
        trimmed: "ReferenceFace",
        name: "b2ReferenceFace",
        def: b2ReferenceFace
      }, {
        trimmed: "EPCollider",
        name: "b2EPCollider",
        def: b2EPCollider
      }, {
        trimmed: "CollideEdgeAndPolygon",
        name: "b2CollideEdgeAndPolygon",
        def: b2CollideEdgeAndPolygon
      }, {
        trimmed: "ClipSegmentToLine",
        name: "b2ClipSegmentToLine",
        def: b2ClipSegmentToLine
      }, {
        trimmed: "TestShapeOverlap",
        name: "b2TestShapeOverlap",
        def: b2TestShapeOverlap
      }, {
        trimmed: "TestOverlap",
        name: "b2TestOverlap",
        def: b2TestOverlap
      }, {
        trimmed: "Shape",
        name: "b2Shape",
        def: b2Shape
      }, {
        trimmed: "CircleShape",
        name: "b2CircleShape",
        def: b2CircleShape
      }, {
        trimmed: "EdgeShape",
        name: "b2EdgeShape",
        def: b2EdgeShape
      }, {
        trimmed: "ChainShape",
        name: "b2ChainShape",
        def: b2ChainShape
      }, {
        trimmed: "PolygonShape",
        name: "b2PolygonShape",
        def: b2PolygonShape
      }, {
        trimmed: "Pair",
        name: "b2Pair",
        def: b2Pair
      }, {
        trimmed: "PairLessThan",
        name: "b2PairLessThan",
        def: b2PairLessThan
      }, {
        trimmed: "BroadPhase",
        name: "b2BroadPhase",
        def: b2BroadPhase
      }, {
        trimmed: "DistanceProxy",
        name: "b2DistanceProxy",
        def: b2DistanceProxy
      }, {
        trimmed: "SimplexCache",
        name: "b2SimplexCache",
        def: b2SimplexCache
      }, {
        trimmed: "DistanceInput",
        name: "b2DistanceInput",
        def: b2DistanceInput
      }, {
        trimmed: "DistanceOutput",
        name: "b2DistanceOutput",
        def: b2DistanceOutput
      }, {
        trimmed: "SimplexVertex",
        name: "b2SimplexVertex",
        def: b2SimplexVertex
      }, {
        trimmed: "Simplex",
        name: "b2Simplex",
        def: b2Simplex
      }, {
        trimmed: "DistanceFunc",
        name: "b2DistanceFunc",
        def: b2DistanceFunc
      }, {
        trimmed: "TreeNode",
        name: "b2TreeNode",
        def: b2TreeNode
      }, {
        trimmed: "DynamicTree",
        name: "b2DynamicTree",
        def: b2DynamicTree
      }, {
        trimmed: "TOIInput",
        name: "b2TOIInput",
        def: b2TOIInput
      }, {
        trimmed: "TOIOutput",
        name: "b2TOIOutput",
        def: b2TOIOutput
      }, {
        trimmed: "SeparationFunction",
        name: "b2SeparationFunction",
        def: b2SeparationFunction
      }, {
        trimmed: "TimeOfImpact",
        name: "b2TimeOfImpact",
        def: b2TimeOfImpact
      }, {
        trimmed: "BodyDef",
        name: "b2BodyDef",
        def: b2BodyDef
      }, {
        trimmed: "Body",
        name: "b2Body",
        def: b2Body
      }, {
        trimmed: "Filter",
        name: "b2Filter",
        def: b2Filter
      }, {
        trimmed: "FixtureDef",
        name: "b2FixtureDef",
        def: b2FixtureDef
      }, {
        trimmed: "Fixture",
        name: "b2Fixture",
        def: b2Fixture
      }, {
        trimmed: "DestructionListener",
        name: "b2DestructionListener",
        def: b2DestructionListener
      }, {
        trimmed: "ContactFilter",
        name: "b2ContactFilter",
        def: b2ContactFilter
      }, {
        trimmed: "ContactImpulse",
        name: "b2ContactImpulse",
        def: b2ContactImpulse
      }, {
        trimmed: "ContactListener",
        name: "b2ContactListener",
        def: b2ContactListener
      }, {
        trimmed: "QueryCallback",
        name: "b2QueryCallback",
        def: b2QueryCallback
      }, {
        trimmed: "RayCastCallback",
        name: "b2RayCastCallback",
        def: b2RayCastCallback
      }, {
        trimmed: "TimeStep",
        name: "b2TimeStep",
        def: b2TimeStep
      }, {
        trimmed: "Position",
        name: "b2Position",
        def: b2Position
      }, {
        trimmed: "Velocity",
        name: "b2Velocity",
        def: b2Velocity
      }, {
        trimmed: "SolverData",
        name: "b2SolverData",
        def: b2SolverData
      }, {
        trimmed: "World",
        name: "b2World",
        def: b2World
      }, {
        trimmed: "MixFriction",
        name: "b2MixFriction",
        def: b2MixFriction
      }, {
        trimmed: "MixRestitution",
        name: "b2MixRestitution",
        def: b2MixRestitution
      }, {
        trimmed: "ContactRegister",
        name: "b2ContactRegister",
        def: b2ContactRegister
      }, {
        trimmed: "ContactEdge",
        name: "b2ContactEdge",
        def: b2ContactEdge
      }, {
        trimmed: "Contact",
        name: "b2Contact",
        def: b2Contact
      }, {
        trimmed: "CircleContact",
        name: "b2CircleContact",
        def: b2CircleContact
      }, {
        trimmed: "PolygonContact",
        name: "b2PolygonContact",
        def: b2PolygonContact
      }, {
        trimmed: "ChainAndCircleContact",
        name: "b2ChainAndCircleContact",
        def: b2ChainAndCircleContact
      }, {
        trimmed: "ChainAndPolygonContact",
        name: "b2ChainAndPolygonContact",
        def: b2ChainAndPolygonContact
      }, {
        trimmed: "EdgeAndCircleContact",
        name: "b2EdgeAndCircleContact",
        def: b2EdgeAndCircleContact
      }, {
        trimmed: "EdgeAndPolygonContact",
        name: "b2EdgeAndPolygonContact",
        def: b2EdgeAndPolygonContact
      }, {
        trimmed: "PolygonAndCircleContact",
        name: "b2PolygonAndCircleContact",
        def: b2PolygonAndCircleContact
      }, {
        trimmed: "defaultFilter",
        name: "b2_defaultFilter",
        def: b2_defaultFilter
      }, {
        trimmed: "defaultListener",
        name: "b2_defaultListener",
        def: b2_defaultListener
      }, {
        trimmed: "ContactManager",
        name: "b2ContactManager",
        def: b2ContactManager
      }, {
        trimmed: "VelocityConstraintPoint",
        name: "b2VelocityConstraintPoint",
        def: b2VelocityConstraintPoint
      }, {
        trimmed: "ContactPositionConstraint",
        name: "b2ContactPositionConstraint",
        def: b2ContactPositionConstraint
      }, {
        trimmed: "ContactVelocityConstraint",
        name: "b2ContactVelocityConstraint",
        def: b2ContactVelocityConstraint
      }, {
        trimmed: "PositionSolverManifold",
        name: "b2PositionSolverManifold",
        def: b2PositionSolverManifold
      }, {
        trimmed: "ContactSolverDef",
        name: "b2ContactSolverDef",
        def: b2ContactSolverDef
      }, {
        trimmed: "ContactSolver",
        name: "b2ContactSolver",
        def: b2ContactSolver
      }, {
        trimmed: "Island",
        name: "b2Island",
        def: b2Island
      }, {
        trimmed: "Jacobian",
        name: "b2Jacobian",
        def: b2Jacobian
      }, {
        trimmed: "JointEdge",
        name: "b2JointEdge",
        def: b2JointEdge
      }, {
        trimmed: "JointDef",
        name: "b2JointDef",
        def: b2JointDef
      }, {
        trimmed: "Joint",
        name: "b2Joint",
        def: b2Joint
      }, {
        trimmed: "RevoluteJointDef",
        name: "b2RevoluteJointDef",
        def: b2RevoluteJointDef
      }, {
        trimmed: "RevoluteJoint",
        name: "b2RevoluteJoint",
        def: b2RevoluteJoint
      }, {
        trimmed: "MouseJointDef",
        name: "b2MouseJointDef",
        def: b2MouseJointDef
      }, {
        trimmed: "MouseJoint",
        name: "b2MouseJoint",
        def: b2MouseJoint
      }, {
        trimmed: "DistanceJointDef",
        name: "b2DistanceJointDef",
        def: b2DistanceJointDef
      }, {
        trimmed: "DistanceJoint",
        name: "b2DistanceJoint",
        def: b2DistanceJoint
      }, {
        trimmed: "PrismaticJointDef",
        name: "b2PrismaticJointDef",
        def: b2PrismaticJointDef
      }, {
        trimmed: "PrismaticJoint",
        name: "b2PrismaticJoint",
        def: b2PrismaticJoint
      }, {
        trimmed: "FrictionJointDef",
        name: "b2FrictionJointDef",
        def: b2FrictionJointDef
      }, {
        trimmed: "FrictionJoint",
        name: "b2FrictionJoint",
        def: b2FrictionJoint
      }, {
        trimmed: "WeldJointDef",
        name: "b2WeldJointDef",
        def: b2WeldJointDef
      }, {
        trimmed: "WeldJoint",
        name: "b2WeldJoint",
        def: b2WeldJoint
      }, {
        trimmed: "WheelJointDef",
        name: "b2WheelJointDef",
        def: b2WheelJointDef
      }, {
        trimmed: "WheelJoint",
        name: "b2WheelJoint",
        def: b2WheelJoint
      }, {
        trimmed: "GearJointDef",
        name: "b2GearJointDef",
        def: b2GearJointDef
      }, {
        trimmed: "GearJoint",
        name: "b2GearJoint",
        def: b2GearJoint
      }, {
        trimmed: "MotorJointDef",
        name: "b2MotorJointDef",
        def: b2MotorJointDef
      }, {
        trimmed: "MotorJoint",
        name: "b2MotorJoint",
        def: b2MotorJoint
      }, {
        trimmed: "PulleyJointDef",
        name: "b2PulleyJointDef",
        def: b2PulleyJointDef
      }, {
        trimmed: "PulleyJoint",
        name: "b2PulleyJoint",
        def: b2PulleyJoint
      }, {
        trimmed: "RopeJointDef",
        name: "b2RopeJointDef",
        def: b2RopeJointDef
      }, {
        trimmed: "RopeJoint",
        name: "b2RopeJoint",
        def: b2RopeJoint
      }, {
        trimmed: "RopeDef",
        name: "b2RopeDef",
        def: b2RopeDef
      }, {
        trimmed: "Rope",
        name: "b2Rope",
        def: b2Rope
      }, {
        trimmed: "maxManifoldPoints",
        name: "b2_maxManifoldPoints",
        def: b2_maxManifoldPoints
      }, {
        trimmed: "maxPolygonVertices",
        name: "b2_maxPolygonVertices",
        def: b2_maxPolygonVertices
      }, {
        trimmed: "aabbExtension",
        name: "b2_aabbExtension",
        def: b2_aabbExtension
      }, {
        trimmed: "aabbMultiplier",
        name: "b2_aabbMultiplier",
        def: b2_aabbMultiplier
      }, {
        trimmed: "linearSlop",
        name: "b2_linearSlop",
        def: b2_linearSlop
      }, {
        trimmed: "angularSlop",
        name: "b2_angularSlop",
        def: b2_angularSlop
      }, {
        trimmed: "polygonRadius",
        name: "b2_polygonRadius",
        def: b2_polygonRadius
      }, {
        trimmed: "maxSubSteps",
        name: "b2_maxSubSteps",
        def: b2_maxSubSteps
      }, {
        trimmed: "maxTOIContacts",
        name: "b2_maxTOIContacts",
        def: b2_maxTOIContacts
      }, {
        trimmed: "velocityThreshold",
        name: "b2_velocityThreshold",
        def: b2_velocityThreshold
      }, {
        trimmed: "maxLinearCorrection",
        name: "b2_maxLinearCorrection",
        def: b2_maxLinearCorrection
      }, {
        trimmed: "maxAngularCorrection",
        name: "b2_maxAngularCorrection",
        def: b2_maxAngularCorrection
      }, {
        trimmed: "maxTranslation",
        name: "b2_maxTranslation",
        def: b2_maxTranslation
      }, {
        trimmed: "maxTranslationSquared",
        name: "b2_maxTranslationSquared",
        def: b2_maxTranslationSquared
      }, {
        trimmed: "maxRotation",
        name: "b2_maxRotation",
        def: b2_maxRotation
      }, {
        trimmed: "maxRotationSquared",
        name: "b2_maxRotationSquared",
        def: b2_maxRotationSquared
      }, {
        trimmed: "baumgarte",
        name: "b2_baumgarte",
        def: b2_baumgarte
      }, {
        trimmed: "toiBaugarte",
        name: "b2_toiBaugarte",
        def: b2_toiBaugarte
      }, {
        trimmed: "timeToSleep",
        name: "b2_timeToSleep",
        def: b2_timeToSleep
      }, {
        trimmed: "linearSleepTolerance",
        name: "b2_linearSleepTolerance",
        def: b2_linearSleepTolerance
      }, {
        trimmed: "angularSleepTolerance",
        name: "b2_angularSleepTolerance",
        def: b2_angularSleepTolerance
      }, {
        trimmed: "epsilon",
        name: "b2_epsilon",
        def: b2_epsilon
      }, {
        trimmed: "JsonSerializer",
        name: "b2JsonSerializer",
        def: b2JsonSerializer
      }, {
        trimmed: "RUBELoader",
        name: "b2RUBELoader",
        def: b2RUBELoader
      }, {
        trimmed: "Profiler",
        name: "b2Profiler",
        def: b2Profiler
      } ];
      if ("undefined" !== typeof b2_compatibility && "undefined" !== typeof window) for (var i = 0; i < mappings.length; ++i) window[mappings[i].name] = mappings[i].def; else {
        var b2 = {};
        for (var i = 0; i < mappings.length; ++i) b2[mappings[i].trimmed] = mappings[i].def;
        "undefined" !== typeof module ? module.exports = b2 : window["b2"] = b2;
      }
    })();
  }), {} ],
  310: [ (function(require, module, exports) {
    Object.create = Object.create || function(o) {
      function F() {}
      F.prototype = o;
      return new F();
    };
    var assert = function(value, message) {
      if (!value) throw new Error("Assertion failed: " + message);
    };
    var assertSoft = function(value, message) {
      if (!value && console && console.warn) {
        console.warn("ASSERTION FAILED: " + message);
        console.trace && console.trace();
      }
    };
    var mymin = function(a, b) {
      return a < b ? a : b;
    };
    var mymax = function(a, b) {
      return a > b ? a : b;
    };
    var min, max;
    if ("object" === typeof window && window.navigator.userAgent.indexOf("Firefox") > -1) {
      min = Math.min;
      max = Math.max;
    } else {
      min = mymin;
      max = mymax;
    }
    var hashPair = function(a, b) {
      return a < b ? a + " " + b : b + " " + a;
    };
    var deleteObjFromList = function(arr, obj) {
      for (var i = 0; i < arr.length; i++) if (arr[i] === obj) {
        arr[i] = arr[arr.length - 1];
        arr.length--;
        return;
      }
    };
    var closestPointOnSegment = function(p, a, b) {
      var delta = vsub(a, b);
      var t = clamp01(vdot(delta, vsub(p, b)) / vlengthsq(delta));
      return vadd(b, vmult(delta, t));
    };
    var closestPointOnSegment2 = function(px, py, ax, ay, bx, by) {
      var deltax = ax - bx;
      var deltay = ay - by;
      var t = clamp01(vdot2(deltax, deltay, px - bx, py - by) / vlengthsq2(deltax, deltay));
      return new Vect(bx + deltax * t, by + deltay * t);
    };
    cp.momentForCircle = function(m, r1, r2, offset) {
      return m * (.5 * (r1 * r1 + r2 * r2) + vlengthsq(offset));
    };
    cp.areaForCircle = function(r1, r2) {
      return Math.PI * Math.abs(r1 * r1 - r2 * r2);
    };
    cp.momentForSegment = function(m, a, b) {
      var offset = vmult(vadd(a, b), .5);
      return m * (vdistsq(b, a) / 12 + vlengthsq(offset));
    };
    cp.areaForSegment = function(a, b, r) {
      return r * (Math.PI * r + 2 * vdist(a, b));
    };
    cp.momentForPoly = function(m, verts, offset) {
      var sum1 = 0;
      var sum2 = 0;
      var len = verts.length;
      for (var i = 0; i < len; i += 2) {
        var v1x = verts[i] + offset.x;
        var v1y = verts[i + 1] + offset.y;
        var v2x = verts[(i + 2) % len] + offset.x;
        var v2y = verts[(i + 3) % len] + offset.y;
        var a = vcross2(v2x, v2y, v1x, v1y);
        var b = vdot2(v1x, v1y, v1x, v1y) + vdot2(v1x, v1y, v2x, v2y) + vdot2(v2x, v2y, v2x, v2y);
        sum1 += a * b;
        sum2 += a;
      }
      return m * sum1 / (6 * sum2);
    };
    cp.areaForPoly = function(verts) {
      var area = 0;
      for (var i = 0, len = verts.length; i < len; i += 2) area += vcross(new Vect(verts[i], verts[i + 1]), new Vect(verts[(i + 2) % len], verts[(i + 3) % len]));
      return -area / 2;
    };
    cp.centroidForPoly = function(verts) {
      var sum = 0;
      var vsum = new Vect(0, 0);
      for (var i = 0, len = verts.length; i < len; i += 2) {
        var v1 = new Vect(verts[i], verts[i + 1]);
        var v2 = new Vect(verts[(i + 2) % len], verts[(i + 3) % len]);
        var cross = vcross(v1, v2);
        sum += cross;
        vsum = vadd(vsum, vmult(vadd(v1, v2), cross));
      }
      return vmult(vsum, 1 / (3 * sum));
    };
    cp.recenterPoly = function(verts) {
      var centroid = cp.centroidForPoly(verts);
      for (var i = 0; i < verts.length; i += 2) {
        verts[i] -= centroid.x;
        verts[i + 1] -= centroid.y;
      }
    };
    cp.momentForBox = function(m, width, height) {
      return m * (width * width + height * height) / 12;
    };
    cp.momentForBox2 = function(m, box) {
      var width = box.r - box.l;
      var height = box.t - box.b;
      var offset = vmult([ box.l + box.r, box.b + box.t ], .5);
      return cp.momentForBox(m, width, height) + m * vlengthsq(offset);
    };
    var loopIndexes = cp.loopIndexes = function(verts) {
      var start = 0, end = 0;
      var minx, miny, maxx, maxy;
      minx = maxx = verts[0];
      miny = maxy = verts[1];
      var count = verts.length >> 1;
      for (var i = 1; i < count; i++) {
        var x = verts[2 * i];
        var y = verts[2 * i + 1];
        if (x < minx || x == minx && y < miny) {
          minx = x;
          miny = y;
          start = i;
        } else if (x > maxx || x == maxx && y > maxy) {
          maxx = x;
          maxy = y;
          end = i;
        }
      }
      return [ start, end ];
    };
    var SWAP = function(arr, idx1, idx2) {
      var tmp = arr[2 * idx1];
      arr[2 * idx1] = arr[2 * idx2];
      arr[2 * idx2] = tmp;
      tmp = arr[2 * idx1 + 1];
      arr[2 * idx1 + 1] = arr[2 * idx2 + 1];
      arr[2 * idx2 + 1] = tmp;
    };
    var QHullPartition = function(verts, offs, count, a, b, tol) {
      if (0 === count) return 0;
      var max = 0;
      var pivot = offs;
      var delta = vsub(b, a);
      var valueTol = tol * vlength(delta);
      var head = offs;
      for (var tail = offs + count - 1; head <= tail; ) {
        var v = new Vect(verts[2 * head], verts[2 * head + 1]);
        var value = vcross(delta, vsub(v, a));
        if (value > valueTol) {
          if (value > max) {
            max = value;
            pivot = head;
          }
          head++;
        } else {
          SWAP(verts, head, tail);
          tail--;
        }
      }
      pivot != offs && SWAP(verts, offs, pivot);
      return head - offs;
    };
    var QHullReduce = function(tol, verts, offs, count, a, pivot, b, resultPos) {
      if (count < 0) return 0;
      if (0 == count) {
        verts[2 * resultPos] = pivot.x;
        verts[2 * resultPos + 1] = pivot.y;
        return 1;
      }
      var left_count = QHullPartition(verts, offs, count, a, pivot, tol);
      var left = new Vect(verts[2 * offs], verts[2 * offs + 1]);
      var index = QHullReduce(tol, verts, offs + 1, left_count - 1, a, left, pivot, resultPos);
      var pivotPos = resultPos + index++;
      verts[2 * pivotPos] = pivot.x;
      verts[2 * pivotPos + 1] = pivot.y;
      var right_count = QHullPartition(verts, offs + left_count, count - left_count, pivot, b, tol);
      var right = new Vect(verts[2 * (offs + left_count)], verts[2 * (offs + left_count) + 1]);
      return index + QHullReduce(tol, verts, offs + left_count + 1, right_count - 1, pivot, right, b, resultPos + index);
    };
    cp.convexHull = function(verts, result, tolerance) {
      if (result) for (var i = 0; i < verts.length; i++) result[i] = verts[i]; else result = verts;
      var indexes = loopIndexes(verts);
      var start = indexes[0], end = indexes[1];
      if (start == end) {
        result.length = 2;
        return result;
      }
      SWAP(result, 0, start);
      SWAP(result, 1, 0 == end ? start : end);
      var a = new Vect(result[0], result[1]);
      var b = new Vect(result[2], result[3]);
      var count = verts.length >> 1;
      var resultCount = QHullReduce(tolerance, result, 2, count - 2, a, b, a, 1) + 1;
      result.length = 2 * resultCount;
      assertSoft(polyValidate(result), "Internal error: cpConvexHull() and cpPolyValidate() did not agree.Please report this error with as much info as you can.");
      return result;
    };
    var clamp = function(f, minv, maxv) {
      return min(max(f, minv), maxv);
    };
    var clamp01 = function(f) {
      return max(0, min(f, 1));
    };
    var lerp = function(f1, f2, t) {
      return f1 * (1 - t) + f2 * t;
    };
    var lerpconst = function(f1, f2, d) {
      return f1 + clamp(f2 - f1, -d, d);
    };
    var Vect = cp.Vect = function(x, y) {
      this.x = x;
      this.y = y;
    };
    cp.v = function(x, y) {
      return new Vect(x, y);
    };
    var vzero = cp.vzero = new Vect(0, 0);
    var vdot = cp.v.dot = function(v1, v2) {
      return v1.x * v2.x + v1.y * v2.y;
    };
    var vdot2 = function(x1, y1, x2, y2) {
      return x1 * x2 + y1 * y2;
    };
    var vlength = cp.v.len = function(v) {
      return Math.sqrt(vdot(v, v));
    };
    var vlength2 = cp.v.len2 = function(x, y) {
      return Math.sqrt(x * x + y * y);
    };
    var veql = cp.v.eql = function(v1, v2) {
      return v1.x === v2.x && v1.y === v2.y;
    };
    var vadd = cp.v.add = function(v1, v2) {
      return new Vect(v1.x + v2.x, v1.y + v2.y);
    };
    Vect.prototype.add = function(v2) {
      this.x += v2.x;
      this.y += v2.y;
      return this;
    };
    var vsub = cp.v.sub = function(v1, v2) {
      return new Vect(v1.x - v2.x, v1.y - v2.y);
    };
    Vect.prototype.sub = function(v2) {
      this.x -= v2.x;
      this.y -= v2.y;
      return this;
    };
    var vneg = cp.v.neg = function(v) {
      return new Vect(-v.x, -v.y);
    };
    Vect.prototype.neg = function() {
      this.x = -this.x;
      this.y = -this.y;
      return this;
    };
    var vmult = cp.v.mult = function(v, s) {
      return new Vect(v.x * s, v.y * s);
    };
    Vect.prototype.mult = function(s) {
      this.x *= s;
      this.y *= s;
      return this;
    };
    var vcross = cp.v.cross = function(v1, v2) {
      return v1.x * v2.y - v1.y * v2.x;
    };
    var vcross2 = function(x1, y1, x2, y2) {
      return x1 * y2 - y1 * x2;
    };
    var vperp = cp.v.perp = function(v) {
      return new Vect(-v.y, v.x);
    };
    var vpvrperp = cp.v.pvrperp = function(v) {
      return new Vect(v.y, -v.x);
    };
    var vproject = cp.v.project = function(v1, v2) {
      return vmult(v2, vdot(v1, v2) / vlengthsq(v2));
    };
    Vect.prototype.project = function(v2) {
      this.mult(vdot(this, v2) / vlengthsq(v2));
      return this;
    };
    var vrotate = cp.v.rotate = function(v1, v2) {
      return new Vect(v1.x * v2.x - v1.y * v2.y, v1.x * v2.y + v1.y * v2.x);
    };
    Vect.prototype.rotate = function(v2) {
      this.x = this.x * v2.x - this.y * v2.y;
      this.y = this.x * v2.y + this.y * v2.x;
      return this;
    };
    var vunrotate = cp.v.unrotate = function(v1, v2) {
      return new Vect(v1.x * v2.x + v1.y * v2.y, v1.y * v2.x - v1.x * v2.y);
    };
    var vlengthsq = cp.v.lengthsq = function(v) {
      return vdot(v, v);
    };
    var vlengthsq2 = cp.v.lengthsq2 = function(x, y) {
      return x * x + y * y;
    };
    var vlerp = cp.v.lerp = function(v1, v2, t) {
      return vadd(vmult(v1, 1 - t), vmult(v2, t));
    };
    var vnormalize = cp.v.normalize = function(v) {
      return vmult(v, 1 / vlength(v));
    };
    var vnormalize_safe = cp.v.normalize_safe = function(v) {
      return 0 === v.x && 0 === v.y ? vzero : vnormalize(v);
    };
    var vclamp = cp.v.clamp = function(v, len) {
      return vdot(v, v) > len * len ? vmult(vnormalize(v), len) : v;
    };
    var vlerpconst = cp.v.lerpconst = function(v1, v2, d) {
      return vadd(v1, vclamp(vsub(v2, v1), d));
    };
    var vdist = cp.v.dist = function(v1, v2) {
      return vlength(vsub(v1, v2));
    };
    var vdistsq = cp.v.distsq = function(v1, v2) {
      return vlengthsq(vsub(v1, v2));
    };
    var vnear = cp.v.near = function(v1, v2, dist) {
      return vdistsq(v1, v2) < dist * dist;
    };
    var vslerp = cp.v.slerp = function(v1, v2, t) {
      var omega = Math.acos(vdot(v1, v2));
      if (omega) {
        var denom = 1 / Math.sin(omega);
        return vadd(vmult(v1, Math.sin((1 - t) * omega) * denom), vmult(v2, Math.sin(t * omega) * denom));
      }
      return v1;
    };
    var vslerpconst = cp.v.slerpconst = function(v1, v2, a) {
      var angle = Math.acos(vdot(v1, v2));
      return vslerp(v1, v2, min(a, angle) / angle);
    };
    var vforangle = cp.v.forangle = function(a) {
      return new Vect(Math.cos(a), Math.sin(a));
    };
    var vtoangle = cp.v.toangle = function(v) {
      return Math.atan2(v.y, v.x);
    };
    var vstr = cp.v.str = function(v) {
      return "(" + v.x.toFixed(3) + ", " + v.y.toFixed(3) + ")";
    };
    var numBB = 0;
    var BB = cp.BB = function(l, b, r, t) {
      this.l = l;
      this.b = b;
      this.r = r;
      this.t = t;
      numBB++;
    };
    cp.bb = function(l, b, r, t) {
      return new BB(l, b, r, t);
    };
    var bbNewForCircle = function(p, r) {
      return new BB(p.x - r, p.y - r, p.x + r, p.y + r);
    };
    var bbIntersects = function(a, b) {
      return a.l <= b.r && b.l <= a.r && a.b <= b.t && b.b <= a.t;
    };
    var bbIntersects2 = function(bb, l, b, r, t) {
      return bb.l <= r && l <= bb.r && bb.b <= t && b <= bb.t;
    };
    var bbContainsBB = function(bb, other) {
      return bb.l <= other.l && bb.r >= other.r && bb.b <= other.b && bb.t >= other.t;
    };
    var bbContainsVect = function(bb, v) {
      return bb.l <= v.x && bb.r >= v.x && bb.b <= v.y && bb.t >= v.y;
    };
    var bbContainsVect2 = function(l, b, r, t, v) {
      return l <= v.x && r >= v.x && b <= v.y && t >= v.y;
    };
    var bbMerge = function(a, b) {
      return new BB(min(a.l, b.l), min(a.b, b.b), max(a.r, b.r), max(a.t, b.t));
    };
    var bbExpand = function(bb, v) {
      return new BB(min(bb.l, v.x), min(bb.b, v.y), max(bb.r, v.x), max(bb.t, v.y));
    };
    var bbArea = function(bb) {
      return (bb.r - bb.l) * (bb.t - bb.b);
    };
    var bbMergedArea = function(a, b) {
      return (max(a.r, b.r) - min(a.l, b.l)) * (max(a.t, b.t) - min(a.b, b.b));
    };
    var bbMergedArea2 = function(bb, l, b, r, t) {
      return (max(bb.r, r) - min(bb.l, l)) * (max(bb.t, t) - min(bb.b, b));
    };
    var bbIntersectsSegment = function(bb, a, b) {
      return Infinity != bbSegmentQuery(bb, a, b);
    };
    var bbClampVect = function(bb, v) {
      var x = min(max(bb.l, v.x), bb.r);
      var y = min(max(bb.b, v.y), bb.t);
      return new Vect(x, y);
    };
    var bbWrapVect = function(bb, v) {
      var ix = Math.abs(bb.r - bb.l);
      var modx = (v.x - bb.l) % ix;
      var x = modx > 0 ? modx : modx + ix;
      var iy = Math.abs(bb.t - bb.b);
      var mody = (v.y - bb.b) % iy;
      var y = mody > 0 ? mody : mody + iy;
      return new Vect(x + bb.l, y + bb.b);
    };
    var shapeIDCounter = 0;
    var CP_NO_GROUP = cp.NO_GROUP = 0;
    var CP_ALL_LAYERS = cp.ALL_LAYERS = -1;
    cp.resetShapeIdCounter = function() {
      shapeIDCounter = 0;
    };
    var Shape = cp.Shape = function(body) {
      this.body = body;
      this.bb_l = this.bb_b = this.bb_r = this.bb_t = 0;
      this.hashid = shapeIDCounter++;
      this.sensor = false;
      this.e = 0;
      this.u = 0;
      this.surface_v = vzero;
      this.collision_type = 0;
      this.group = 0;
      this.layers = CP_ALL_LAYERS;
      this.space = null;
      this.collisionCode = this.collisionCode;
    };
    Shape.prototype.setElasticity = function(e) {
      this.e = e;
    };
    Shape.prototype.setFriction = function(u) {
      this.body.activate();
      this.u = u;
    };
    Shape.prototype.setLayers = function(layers) {
      this.body.activate();
      this.layers = layers;
    };
    Shape.prototype.setSensor = function(sensor) {
      this.body.activate();
      this.sensor = sensor;
    };
    Shape.prototype.setCollisionType = function(collision_type) {
      this.body.activate();
      this.collision_type = collision_type;
    };
    Shape.prototype.getBody = function() {
      return this.body;
    };
    Shape.prototype.active = function() {
      return this.body && -1 !== this.body.shapeList.indexOf(this);
    };
    Shape.prototype.setBody = function(body) {
      assert(!this.active(), "You cannot change the body on an active shape. You must remove the shape from the space before changing the body.");
      this.body = body;
    };
    Shape.prototype.cacheBB = function() {
      return this.update(this.body.p, this.body.rot);
    };
    Shape.prototype.update = function(pos, rot) {
      assert(!isNaN(rot.x), "Rotation is NaN");
      assert(!isNaN(pos.x), "Position is NaN");
      this.cacheData(pos, rot);
    };
    Shape.prototype.pointQuery = function(p) {
      var info = this.nearestPointQuery(p);
      if (info.d < 0) return info;
    };
    Shape.prototype.getBB = function() {
      return new BB(this.bb_l, this.bb_b, this.bb_r, this.bb_t);
    };
    var PointQueryExtendedInfo = function(shape) {
      this.shape = shape;
      this.d = Infinity;
      this.n = vzero;
    };
    var NearestPointQueryInfo = function(shape, p, d) {
      this.shape = shape;
      this.p = p;
      this.d = d;
    };
    var SegmentQueryInfo = function(shape, t, n) {
      this.shape = shape;
      this.t = t;
      this.n = n;
    };
    SegmentQueryInfo.prototype.hitPoint = function(start, end) {
      return vlerp(start, end, this.t);
    };
    SegmentQueryInfo.prototype.hitDist = function(start, end) {
      return vdist(start, end) * this.t;
    };
    var CircleShape = cp.CircleShape = function(body, radius, offset) {
      this.c = this.tc = offset;
      this.r = radius;
      this.type = "circle";
      Shape.call(this, body);
    };
    CircleShape.prototype = Object.create(Shape.prototype);
    CircleShape.prototype.cacheData = function(p, rot) {
      var c = this.tc = vrotate(this.c, rot).add(p);
      var r = this.r;
      this.bb_l = c.x - r;
      this.bb_b = c.y - r;
      this.bb_r = c.x + r;
      this.bb_t = c.y + r;
    };
    CircleShape.prototype.nearestPointQuery = function(p) {
      var deltax = p.x - this.tc.x;
      var deltay = p.y - this.tc.y;
      var d = vlength2(deltax, deltay);
      var r = this.r;
      var nearestp = new Vect(this.tc.x + deltax * r / d, this.tc.y + deltay * r / d);
      return new NearestPointQueryInfo(this, nearestp, d - r);
    };
    var circleSegmentQuery = function(shape, center, r, a, b, info) {
      a = vsub(a, center);
      b = vsub(b, center);
      var qa = vdot(a, a) - 2 * vdot(a, b) + vdot(b, b);
      var qb = -2 * vdot(a, a) + 2 * vdot(a, b);
      var qc = vdot(a, a) - r * r;
      var det = qb * qb - 4 * qa * qc;
      if (det >= 0) {
        var t = (-qb - Math.sqrt(det)) / (2 * qa);
        if (0 <= t && t <= 1) return new SegmentQueryInfo(shape, t, vnormalize(vlerp(a, b, t)));
      }
    };
    CircleShape.prototype.segmentQuery = function(a, b) {
      return circleSegmentQuery(this, this.tc, this.r, a, b);
    };
    var SegmentShape = cp.SegmentShape = function(body, a, b, r) {
      this.a = a;
      this.b = b;
      this.n = vperp(vnormalize(vsub(b, a)));
      this.ta = this.tb = this.tn = null;
      this.r = r;
      this.a_tangent = vzero;
      this.b_tangent = vzero;
      this.type = "segment";
      Shape.call(this, body);
    };
    SegmentShape.prototype = Object.create(Shape.prototype);
    SegmentShape.prototype.cacheData = function(p, rot) {
      this.ta = vadd(p, vrotate(this.a, rot));
      this.tb = vadd(p, vrotate(this.b, rot));
      this.tn = vrotate(this.n, rot);
      var l, r, b, t;
      if (this.ta.x < this.tb.x) {
        l = this.ta.x;
        r = this.tb.x;
      } else {
        l = this.tb.x;
        r = this.ta.x;
      }
      if (this.ta.y < this.tb.y) {
        b = this.ta.y;
        t = this.tb.y;
      } else {
        b = this.tb.y;
        t = this.ta.y;
      }
      var rad = this.r;
      this.bb_l = l - rad;
      this.bb_b = b - rad;
      this.bb_r = r + rad;
      this.bb_t = t + rad;
    };
    SegmentShape.prototype.nearestPointQuery = function(p) {
      var closest = closestPointOnSegment(p, this.ta, this.tb);
      var deltax = p.x - closest.x;
      var deltay = p.y - closest.y;
      var d = vlength2(deltax, deltay);
      var r = this.r;
      var nearestp = d ? vadd(closest, vmult(new Vect(deltax, deltay), r / d)) : closest;
      return new NearestPointQueryInfo(this, nearestp, d - r);
    };
    SegmentShape.prototype.segmentQuery = function(a, b) {
      var n = this.tn;
      var d = vdot(vsub(this.ta, a), n);
      var r = this.r;
      var flipped_n = d > 0 ? vneg(n) : n;
      var n_offset = vsub(vmult(flipped_n, r), a);
      var seg_a = vadd(this.ta, n_offset);
      var seg_b = vadd(this.tb, n_offset);
      var delta = vsub(b, a);
      if (vcross(delta, seg_a) * vcross(delta, seg_b) <= 0) {
        var d_offset = d + (d > 0 ? -r : r);
        var ad = -d_offset;
        var bd = vdot(delta, n) - d_offset;
        if (ad * bd < 0) return new SegmentQueryInfo(this, ad / (ad - bd), flipped_n);
      } else if (0 !== r) {
        var info1 = circleSegmentQuery(this, this.ta, this.r, a, b);
        var info2 = circleSegmentQuery(this, this.tb, this.r, a, b);
        return info1 ? info2 && info2.t < info1.t ? info2 : info1 : info2;
      }
    };
    SegmentShape.prototype.setNeighbors = function(prev, next) {
      this.a_tangent = vsub(prev, this.a);
      this.b_tangent = vsub(next, this.b);
    };
    SegmentShape.prototype.setEndpoints = function(a, b) {
      this.a = a;
      this.b = b;
      this.n = vperp(vnormalize(vsub(b, a)));
    };
    var polyValidate = function(verts) {
      var len = verts.length;
      for (var i = 0; i < len; i += 2) {
        var ax = verts[i];
        var ay = verts[i + 1];
        var bx = verts[(i + 2) % len];
        var by = verts[(i + 3) % len];
        var cx = verts[(i + 4) % len];
        var cy = verts[(i + 5) % len];
        if (vcross2(bx - ax, by - ay, cx - bx, cy - by) > 0) return false;
      }
      return true;
    };
    var PolyShape = cp.PolyShape = function(body, verts, offset) {
      this.setVerts(verts, offset);
      this.type = "poly";
      Shape.call(this, body);
    };
    PolyShape.prototype = Object.create(Shape.prototype);
    var SplittingPlane = function(n, d) {
      this.n = n;
      this.d = d;
    };
    SplittingPlane.prototype.compare = function(v) {
      return vdot(this.n, v) - this.d;
    };
    PolyShape.prototype.setVerts = function(verts, offset) {
      assert(verts.length >= 4, "Polygons require some verts");
      assert("number" === typeof verts[0], "Polygon verticies should be specified in a flattened list (eg [x1,y1,x2,y2,x3,y3,...])");
      assert(polyValidate(verts), "Polygon is concave or has a reversed winding. Consider using cpConvexHull()");
      var len = verts.length;
      var numVerts = len >> 1;
      this.verts = new Array(len);
      this.tVerts = new Array(len);
      this.planes = new Array(numVerts);
      this.tPlanes = new Array(numVerts);
      for (var i = 0; i < len; i += 2) {
        var ax = verts[i] + offset.x;
        var ay = verts[i + 1] + offset.y;
        var bx = verts[(i + 2) % len] + offset.x;
        var by = verts[(i + 3) % len] + offset.y;
        var n = vnormalize(vperp(new Vect(bx - ax, by - ay)));
        this.verts[i] = ax;
        this.verts[i + 1] = ay;
        this.planes[i >> 1] = new SplittingPlane(n, vdot2(n.x, n.y, ax, ay));
        this.tPlanes[i >> 1] = new SplittingPlane(new Vect(0, 0), 0);
      }
    };
    var BoxShape = cp.BoxShape = function(body, width, height) {
      var hw = width / 2;
      var hh = height / 2;
      return BoxShape2(body, new BB(-hw, -hh, hw, hh));
    };
    var BoxShape2 = cp.BoxShape2 = function(body, box) {
      var verts = [ box.l, box.b, box.l, box.t, box.r, box.t, box.r, box.b ];
      return new PolyShape(body, verts, vzero);
    };
    PolyShape.prototype.transformVerts = function(p, rot) {
      var src = this.verts;
      var dst = this.tVerts;
      var l = Infinity, r = -Infinity;
      var b = Infinity, t = -Infinity;
      for (var i = 0; i < src.length; i += 2) {
        var x = src[i];
        var y = src[i + 1];
        var vx = p.x + x * rot.x - y * rot.y;
        var vy = p.y + x * rot.y + y * rot.x;
        dst[i] = vx;
        dst[i + 1] = vy;
        l = min(l, vx);
        r = max(r, vx);
        b = min(b, vy);
        t = max(t, vy);
      }
      this.bb_l = l;
      this.bb_b = b;
      this.bb_r = r;
      this.bb_t = t;
    };
    PolyShape.prototype.transformAxes = function(p, rot) {
      var src = this.planes;
      var dst = this.tPlanes;
      for (var i = 0; i < src.length; i++) {
        var n = vrotate(src[i].n, rot);
        dst[i].n = n;
        dst[i].d = vdot(p, n) + src[i].d;
      }
    };
    PolyShape.prototype.cacheData = function(p, rot) {
      this.transformAxes(p, rot);
      this.transformVerts(p, rot);
    };
    PolyShape.prototype.nearestPointQuery = function(p) {
      var planes = this.tPlanes;
      var verts = this.tVerts;
      var v0x = verts[verts.length - 2];
      var v0y = verts[verts.length - 1];
      var minDist = Infinity;
      var closestPoint = vzero;
      var outside = false;
      for (var i = 0; i < planes.length; i++) {
        planes[i].compare(p) > 0 && (outside = true);
        var v1x = verts[2 * i];
        var v1y = verts[2 * i + 1];
        var closest = closestPointOnSegment2(p.x, p.y, v0x, v0y, v1x, v1y);
        var dist = vdist(p, closest);
        if (dist < minDist) {
          minDist = dist;
          closestPoint = closest;
        }
        v0x = v1x;
        v0y = v1y;
      }
      return new NearestPointQueryInfo(this, closestPoint, outside ? minDist : -minDist);
    };
    PolyShape.prototype.segmentQuery = function(a, b) {
      var axes = this.tPlanes;
      var verts = this.tVerts;
      var numVerts = axes.length;
      var len = 2 * numVerts;
      for (var i = 0; i < numVerts; i++) {
        var n = axes[i].n;
        var an = vdot(a, n);
        if (axes[i].d > an) continue;
        var bn = vdot(b, n);
        var t = (axes[i].d - an) / (bn - an);
        if (t < 0 || 1 < t) continue;
        var point = vlerp(a, b, t);
        var dt = -vcross(n, point);
        var dtMin = -vcross2(n.x, n.y, verts[2 * i], verts[2 * i + 1]);
        var dtMax = -vcross2(n.x, n.y, verts[(2 * i + 2) % len], verts[(2 * i + 3) % len]);
        if (dtMin <= dt && dt <= dtMax) return new SegmentQueryInfo(this, t, n);
      }
    };
    PolyShape.prototype.valueOnAxis = function(n, d) {
      var verts = this.tVerts;
      var m = vdot2(n.x, n.y, verts[0], verts[1]);
      for (var i = 2; i < verts.length; i += 2) m = min(m, vdot2(n.x, n.y, verts[i], verts[i + 1]));
      return m - d;
    };
    PolyShape.prototype.containsVert = function(vx, vy) {
      var planes = this.tPlanes;
      for (var i = 0; i < planes.length; i++) {
        var n = planes[i].n;
        var dist = vdot2(n.x, n.y, vx, vy) - planes[i].d;
        if (dist > 0) return false;
      }
      return true;
    };
    PolyShape.prototype.containsVertPartial = function(vx, vy, n) {
      var planes = this.tPlanes;
      for (var i = 0; i < planes.length; i++) {
        var n2 = planes[i].n;
        if (vdot(n2, n) < 0) continue;
        var dist = vdot2(n2.x, n2.y, vx, vy) - planes[i].d;
        if (dist > 0) return false;
      }
      return true;
    };
    PolyShape.prototype.getNumVerts = function() {
      return this.verts.length / 2;
    };
    PolyShape.prototype.getVert = function(i) {
      return new Vect(this.verts[2 * i], this.verts[2 * i + 1]);
    };
    var Body = cp.Body = function(m, i) {
      this.p = new Vect(0, 0);
      this.vx = this.vy = 0;
      this.f = new Vect(0, 0);
      this.w = 0;
      this.t = 0;
      this.v_limit = Infinity;
      this.w_limit = Infinity;
      this.v_biasx = this.v_biasy = 0;
      this.w_bias = 0;
      this.space = null;
      this.shapeList = [];
      this.arbiterList = null;
      this.constraintList = null;
      this.nodeRoot = null;
      this.nodeNext = null;
      this.nodeIdleTime = 0;
      this.setMass(m);
      this.setMoment(i);
      this.rot = new Vect(0, 0);
      this.setAngle(0);
    };
    var createStaticBody = function() {
      var body = new Body(Infinity, Infinity);
      body.nodeIdleTime = Infinity;
      return body;
    };
    cp.StaticBody = createStaticBody;
    if ("undefined" !== typeof DEBUG && DEBUG) {
      var v_assert_nan = function(v, message) {
        assert(v.x == v.x && v.y == v.y, message);
      };
      var v_assert_infinite = function(v, message) {
        assert(Infinity !== Math.abs(v.x) && Infinity !== Math.abs(v.y), message);
      };
      var v_assert_sane = function(v, message) {
        v_assert_nan(v, message);
        v_assert_infinite(v, message);
      };
      Body.prototype.sanityCheck = function() {
        assert(this.m === this.m && this.m_inv === this.m_inv, "Body's mass is invalid.");
        assert(this.i === this.i && this.i_inv === this.i_inv, "Body's moment is invalid.");
        v_assert_sane(this.p, "Body's position is invalid.");
        v_assert_sane(this.f, "Body's force is invalid.");
        assert(this.vx === this.vx && Infinity !== Math.abs(this.vx), "Body's velocity is invalid.");
        assert(this.vy === this.vy && Infinity !== Math.abs(this.vy), "Body's velocity is invalid.");
        assert(this.a === this.a && Infinity !== Math.abs(this.a), "Body's angle is invalid.");
        assert(this.w === this.w && Infinity !== Math.abs(this.w), "Body's angular velocity is invalid.");
        assert(this.t === this.t && Infinity !== Math.abs(this.t), "Body's torque is invalid.");
        v_assert_sane(this.rot, "Body's rotation vector is invalid.");
        assert(this.v_limit === this.v_limit, "Body's velocity limit is invalid.");
        assert(this.w_limit === this.w_limit, "Body's angular velocity limit is invalid.");
      };
    } else Body.prototype.sanityCheck = function() {};
    Body.prototype.getPos = function() {
      return this.p;
    };
    Body.prototype.getVel = function() {
      return new Vect(this.vx, this.vy);
    };
    Body.prototype.getAngVel = function() {
      return this.w;
    };
    Body.prototype.isSleeping = function() {
      return null !== this.nodeRoot;
    };
    Body.prototype.isStatic = function() {
      return Infinity === this.nodeIdleTime;
    };
    Body.prototype.isRogue = function() {
      return null === this.space;
    };
    Body.prototype.setMass = function(mass) {
      assert(mass > 0, "Mass must be positive and non-zero.");
      this.activate();
      this.m = mass;
      this.m_inv = 1 / mass;
    };
    Body.prototype.setMoment = function(moment) {
      assert(moment > 0, "Moment of Inertia must be positive and non-zero.");
      this.activate();
      this.i = moment;
      this.i_inv = 1 / moment;
    };
    Body.prototype.addShape = function(shape) {
      this.shapeList.push(shape);
    };
    Body.prototype.removeShape = function(shape) {
      deleteObjFromList(this.shapeList, shape);
    };
    var filterConstraints = function(node, body, filter) {
      if (node === filter) return node.next(body);
      node.a === body ? node.next_a = filterConstraints(node.next_a, body, filter) : node.next_b = filterConstraints(node.next_b, body, filter);
      return node;
    };
    Body.prototype.removeConstraint = function(constraint) {
      this.constraintList = filterConstraints(this.constraintList, this, constraint);
    };
    Body.prototype.setPos = function(pos) {
      this.activate();
      this.sanityCheck();
      pos === vzero && (pos = cp.v(0, 0));
      this.p = pos;
    };
    Body.prototype.setVel = function(velocity) {
      this.activate();
      this.vx = velocity.x;
      this.vy = velocity.y;
    };
    Body.prototype.setAngVel = function(w) {
      this.activate();
      this.w = w;
    };
    Body.prototype.setAngleInternal = function(angle) {
      assert(!isNaN(angle), "Internal Error: Attempting to set body's angle to NaN");
      this.a = angle;
      this.rot.x = Math.cos(angle);
      this.rot.y = Math.sin(angle);
    };
    Body.prototype.setAngle = function(angle) {
      this.activate();
      this.sanityCheck();
      this.setAngleInternal(angle);
    };
    Body.prototype.velocity_func = function(gravity, damping, dt) {
      var vx = this.vx * damping + (gravity.x + this.f.x * this.m_inv) * dt;
      var vy = this.vy * damping + (gravity.y + this.f.y * this.m_inv) * dt;
      var v_limit = this.v_limit;
      var lensq = vx * vx + vy * vy;
      var scale = lensq > v_limit * v_limit ? v_limit / Math.sqrt(lensq) : 1;
      this.vx = vx * scale;
      this.vy = vy * scale;
      var w_limit = this.w_limit;
      this.w = clamp(this.w * damping + this.t * this.i_inv * dt, -w_limit, w_limit);
      this.sanityCheck();
    };
    Body.prototype.position_func = function(dt) {
      this.p.x += (this.vx + this.v_biasx) * dt;
      this.p.y += (this.vy + this.v_biasy) * dt;
      this.setAngleInternal(this.a + (this.w + this.w_bias) * dt);
      this.v_biasx = this.v_biasy = 0;
      this.w_bias = 0;
      this.sanityCheck();
    };
    Body.prototype.resetForces = function() {
      this.activate();
      this.f = new Vect(0, 0);
      this.t = 0;
    };
    Body.prototype.applyForce = function(force, r) {
      this.activate();
      this.f = vadd(this.f, force);
      this.t += vcross(r, force);
    };
    Body.prototype.applyImpulse = function(j, r) {
      this.activate();
      apply_impulse(this, j.x, j.y, r);
    };
    Body.prototype.getVelAtPoint = function(r) {
      return vadd(new Vect(this.vx, this.vy), vmult(vperp(r), this.w));
    };
    Body.prototype.getVelAtWorldPoint = function(point) {
      return this.getVelAtPoint(vsub(point, this.p));
    };
    Body.prototype.getVelAtLocalPoint = function(point) {
      return this.getVelAtPoint(vrotate(point, this.rot));
    };
    Body.prototype.eachShape = function(func) {
      for (var i = 0, len = this.shapeList.length; i < len; i++) func(this.shapeList[i]);
    };
    Body.prototype.eachConstraint = function(func) {
      var constraint = this.constraintList;
      while (constraint) {
        var next = constraint.next(this);
        func(constraint);
        constraint = next;
      }
    };
    Body.prototype.eachArbiter = function(func) {
      var arb = this.arbiterList;
      while (arb) {
        var next = arb.next(this);
        arb.swappedColl = this === arb.body_b;
        func(arb);
        arb = next;
      }
    };
    Body.prototype.local2World = function(v) {
      return vadd(this.p, vrotate(v, this.rot));
    };
    Body.prototype.world2Local = function(v) {
      return vunrotate(vsub(v, this.p), this.rot);
    };
    Body.prototype.kineticEnergy = function() {
      var vsq = this.vx * this.vx + this.vy * this.vy;
      var wsq = this.w * this.w;
      return (vsq ? vsq * this.m : 0) + (wsq ? wsq * this.i : 0);
    };
    var SpatialIndex = cp.SpatialIndex = function(staticIndex) {
      this.staticIndex = staticIndex;
      if (staticIndex) {
        if (staticIndex.dynamicIndex) throw new Error("This static index is already associated with a dynamic index.");
        staticIndex.dynamicIndex = this;
      }
    };
    SpatialIndex.prototype.collideStatic = function(staticIndex, func) {
      if (staticIndex.count > 0) {
        var query = staticIndex.query;
        this.each((function(obj) {
          query(obj, new BB(obj.bb_l, obj.bb_b, obj.bb_r, obj.bb_t), func);
        }));
      }
    };
    var BBTree = cp.BBTree = function(staticIndex) {
      SpatialIndex.call(this, staticIndex);
      this.velocityFunc = null;
      this.leaves = {};
      this.count = 0;
      this.root = null;
      this.pooledNodes = null;
      this.pooledPairs = null;
      this.stamp = 0;
    };
    BBTree.prototype = Object.create(SpatialIndex.prototype);
    var numNodes = 0;
    var Node = function(tree, a, b) {
      this.obj = null;
      this.bb_l = min(a.bb_l, b.bb_l);
      this.bb_b = min(a.bb_b, b.bb_b);
      this.bb_r = max(a.bb_r, b.bb_r);
      this.bb_t = max(a.bb_t, b.bb_t);
      this.parent = null;
      this.setA(a);
      this.setB(b);
    };
    BBTree.prototype.makeNode = function(a, b) {
      var node = this.pooledNodes;
      if (node) {
        this.pooledNodes = node.parent;
        node.constructor(this, a, b);
        return node;
      }
      numNodes++;
      return new Node(this, a, b);
    };
    var numLeaves = 0;
    var Leaf = function(tree, obj) {
      this.obj = obj;
      tree.getBB(obj, this);
      this.parent = null;
      this.stamp = 1;
      this.pairs = null;
      numLeaves++;
    };
    BBTree.prototype.getBB = function(obj, dest) {
      var velocityFunc = this.velocityFunc;
      if (velocityFunc) {
        var coef = .1;
        var x = (obj.bb_r - obj.bb_l) * coef;
        var y = (obj.bb_t - obj.bb_b) * coef;
        var v = vmult(velocityFunc(obj), .1);
        dest.bb_l = obj.bb_l + min(-x, v.x);
        dest.bb_b = obj.bb_b + min(-y, v.y);
        dest.bb_r = obj.bb_r + max(x, v.x);
        dest.bb_t = obj.bb_t + max(y, v.y);
      } else {
        dest.bb_l = obj.bb_l;
        dest.bb_b = obj.bb_b;
        dest.bb_r = obj.bb_r;
        dest.bb_t = obj.bb_t;
      }
    };
    BBTree.prototype.getStamp = function() {
      var dynamic = this.dynamicIndex;
      return dynamic && dynamic.stamp ? dynamic.stamp : this.stamp;
    };
    BBTree.prototype.incrementStamp = function() {
      this.dynamicIndex && this.dynamicIndex.stamp ? this.dynamicIndex.stamp++ : this.stamp++;
    };
    var numPairs = 0;
    var Pair = function(leafA, nextA, leafB, nextB) {
      this.prevA = null;
      this.leafA = leafA;
      this.nextA = nextA;
      this.prevB = null;
      this.leafB = leafB;
      this.nextB = nextB;
    };
    BBTree.prototype.makePair = function(leafA, nextA, leafB, nextB) {
      var pair = this.pooledPairs;
      if (pair) {
        this.pooledPairs = pair.prevA;
        pair.prevA = null;
        pair.leafA = leafA;
        pair.nextA = nextA;
        pair.prevB = null;
        pair.leafB = leafB;
        pair.nextB = nextB;
        return pair;
      }
      numPairs++;
      return new Pair(leafA, nextA, leafB, nextB);
    };
    Pair.prototype.recycle = function(tree) {
      this.prevA = tree.pooledPairs;
      tree.pooledPairs = this;
    };
    var unlinkThread = function(prev, leaf, next) {
      next && (next.leafA === leaf ? next.prevA = prev : next.prevB = prev);
      prev ? prev.leafA === leaf ? prev.nextA = next : prev.nextB = next : leaf.pairs = next;
    };
    Leaf.prototype.clearPairs = function(tree) {
      var pair = this.pairs, next;
      this.pairs = null;
      while (pair) {
        if (pair.leafA === this) {
          next = pair.nextA;
          unlinkThread(pair.prevB, pair.leafB, pair.nextB);
        } else {
          next = pair.nextB;
          unlinkThread(pair.prevA, pair.leafA, pair.nextA);
        }
        pair.recycle(tree);
        pair = next;
      }
    };
    var pairInsert = function(a, b, tree) {
      var nextA = a.pairs, nextB = b.pairs;
      var pair = tree.makePair(a, nextA, b, nextB);
      a.pairs = b.pairs = pair;
      nextA && (nextA.leafA === a ? nextA.prevA = pair : nextA.prevB = pair);
      nextB && (nextB.leafA === b ? nextB.prevA = pair : nextB.prevB = pair);
    };
    Node.prototype.recycle = function(tree) {
      this.parent = tree.pooledNodes;
      tree.pooledNodes = this;
    };
    Leaf.prototype.recycle = function(tree) {};
    Node.prototype.setA = function(value) {
      this.A = value;
      value.parent = this;
    };
    Node.prototype.setB = function(value) {
      this.B = value;
      value.parent = this;
    };
    Leaf.prototype.isLeaf = true;
    Node.prototype.isLeaf = false;
    Node.prototype.otherChild = function(child) {
      return this.A == child ? this.B : this.A;
    };
    Node.prototype.replaceChild = function(child, value, tree) {
      assertSoft(child == this.A || child == this.B, "Node is not a child of parent.");
      if (this.A == child) {
        this.A.recycle(tree);
        this.setA(value);
      } else {
        this.B.recycle(tree);
        this.setB(value);
      }
      for (var node = this; node; node = node.parent) {
        var a = node.A;
        var b = node.B;
        node.bb_l = min(a.bb_l, b.bb_l);
        node.bb_b = min(a.bb_b, b.bb_b);
        node.bb_r = max(a.bb_r, b.bb_r);
        node.bb_t = max(a.bb_t, b.bb_t);
      }
    };
    Node.prototype.bbArea = Leaf.prototype.bbArea = function() {
      return (this.bb_r - this.bb_l) * (this.bb_t - this.bb_b);
    };
    var bbTreeMergedArea = function(a, b) {
      return (max(a.bb_r, b.bb_r) - min(a.bb_l, b.bb_l)) * (max(a.bb_t, b.bb_t) - min(a.bb_b, b.bb_b));
    };
    var bbProximity = function(a, b) {
      return Math.abs(a.bb_l + a.bb_r - b.bb_l - b.bb_r) + Math.abs(a.bb_b + a.bb_t - b.bb_b - b.bb_t);
    };
    var subtreeInsert = function(subtree, leaf, tree) {
      if (null == subtree) return leaf;
      if (subtree.isLeaf) return tree.makeNode(leaf, subtree);
      var cost_a = subtree.B.bbArea() + bbTreeMergedArea(subtree.A, leaf);
      var cost_b = subtree.A.bbArea() + bbTreeMergedArea(subtree.B, leaf);
      if (cost_a === cost_b) {
        cost_a = bbProximity(subtree.A, leaf);
        cost_b = bbProximity(subtree.B, leaf);
      }
      cost_b < cost_a ? subtree.setB(subtreeInsert(subtree.B, leaf, tree)) : subtree.setA(subtreeInsert(subtree.A, leaf, tree));
      subtree.bb_l = min(subtree.bb_l, leaf.bb_l);
      subtree.bb_b = min(subtree.bb_b, leaf.bb_b);
      subtree.bb_r = max(subtree.bb_r, leaf.bb_r);
      subtree.bb_t = max(subtree.bb_t, leaf.bb_t);
      return subtree;
    };
    Node.prototype.intersectsBB = Leaf.prototype.intersectsBB = function(bb) {
      return this.bb_l <= bb.r && bb.l <= this.bb_r && this.bb_b <= bb.t && bb.b <= this.bb_t;
    };
    var subtreeQuery = function(subtree, bb, func) {
      if (subtree.intersectsBB(bb)) if (subtree.isLeaf) func(subtree.obj); else {
        subtreeQuery(subtree.A, bb, func);
        subtreeQuery(subtree.B, bb, func);
      }
    };
    var nodeSegmentQuery = function(node, a, b) {
      var idx = 1 / (b.x - a.x);
      var tx1 = node.bb_l == a.x ? -Infinity : (node.bb_l - a.x) * idx;
      var tx2 = node.bb_r == a.x ? Infinity : (node.bb_r - a.x) * idx;
      var txmin = min(tx1, tx2);
      var txmax = max(tx1, tx2);
      var idy = 1 / (b.y - a.y);
      var ty1 = node.bb_b == a.y ? -Infinity : (node.bb_b - a.y) * idy;
      var ty2 = node.bb_t == a.y ? Infinity : (node.bb_t - a.y) * idy;
      var tymin = min(ty1, ty2);
      var tymax = max(ty1, ty2);
      if (tymin <= txmax && txmin <= tymax) {
        var min_ = max(txmin, tymin);
        var max_ = min(txmax, tymax);
        if (0 <= max_ && min_ <= 1) return max(min_, 0);
      }
      return Infinity;
    };
    var subtreeSegmentQuery = function(subtree, a, b, t_exit, func) {
      if (subtree.isLeaf) return func(subtree.obj);
      var t_a = nodeSegmentQuery(subtree.A, a, b);
      var t_b = nodeSegmentQuery(subtree.B, a, b);
      if (t_a < t_b) {
        t_a < t_exit && (t_exit = min(t_exit, subtreeSegmentQuery(subtree.A, a, b, t_exit, func)));
        t_b < t_exit && (t_exit = min(t_exit, subtreeSegmentQuery(subtree.B, a, b, t_exit, func)));
      } else {
        t_b < t_exit && (t_exit = min(t_exit, subtreeSegmentQuery(subtree.B, a, b, t_exit, func)));
        t_a < t_exit && (t_exit = min(t_exit, subtreeSegmentQuery(subtree.A, a, b, t_exit, func)));
      }
      return t_exit;
    };
    BBTree.prototype.subtreeRecycle = function(node) {
      if (node.isLeaf) {
        this.subtreeRecycle(node.A);
        this.subtreeRecycle(node.B);
        node.recycle(this);
      }
    };
    var subtreeRemove = function(subtree, leaf, tree) {
      if (leaf == subtree) return null;
      var parent = leaf.parent;
      if (parent == subtree) {
        var other = subtree.otherChild(leaf);
        other.parent = subtree.parent;
        subtree.recycle(tree);
        return other;
      }
      parent.parent.replaceChild(parent, parent.otherChild(leaf), tree);
      return subtree;
    };
    var bbTreeIntersectsNode = function(a, b) {
      return a.bb_l <= b.bb_r && b.bb_l <= a.bb_r && a.bb_b <= b.bb_t && b.bb_b <= a.bb_t;
    };
    Leaf.prototype.markLeafQuery = function(leaf, left, tree, func) {
      if (bbTreeIntersectsNode(leaf, this)) if (left) pairInsert(leaf, this, tree); else {
        this.stamp < leaf.stamp && pairInsert(this, leaf, tree);
        func && func(leaf.obj, this.obj);
      }
    };
    Node.prototype.markLeafQuery = function(leaf, left, tree, func) {
      if (bbTreeIntersectsNode(leaf, this)) {
        this.A.markLeafQuery(leaf, left, tree, func);
        this.B.markLeafQuery(leaf, left, tree, func);
      }
    };
    Leaf.prototype.markSubtree = function(tree, staticRoot, func) {
      if (this.stamp == tree.getStamp()) {
        staticRoot && staticRoot.markLeafQuery(this, false, tree, func);
        for (var node = this; node.parent; node = node.parent) node == node.parent.A ? node.parent.B.markLeafQuery(this, true, tree, func) : node.parent.A.markLeafQuery(this, false, tree, func);
      } else {
        var pair = this.pairs;
        while (pair) if (this === pair.leafB) {
          func && func(pair.leafA.obj, this.obj);
          pair = pair.nextB;
        } else pair = pair.nextA;
      }
    };
    Node.prototype.markSubtree = function(tree, staticRoot, func) {
      this.A.markSubtree(tree, staticRoot, func);
      this.B.markSubtree(tree, staticRoot, func);
    };
    Leaf.prototype.containsObj = function(obj) {
      return this.bb_l <= obj.bb_l && this.bb_r >= obj.bb_r && this.bb_b <= obj.bb_b && this.bb_t >= obj.bb_t;
    };
    Leaf.prototype.update = function(tree) {
      var root = tree.root;
      var obj = this.obj;
      if (!this.containsObj(obj)) {
        tree.getBB(this.obj, this);
        root = subtreeRemove(root, this, tree);
        tree.root = subtreeInsert(root, this, tree);
        this.clearPairs(tree);
        this.stamp = tree.getStamp();
        return true;
      }
      return false;
    };
    Leaf.prototype.addPairs = function(tree) {
      var dynamicIndex = tree.dynamicIndex;
      if (dynamicIndex) {
        var dynamicRoot = dynamicIndex.root;
        dynamicRoot && dynamicRoot.markLeafQuery(this, true, dynamicIndex, null);
      } else {
        var staticRoot = tree.staticIndex.root;
        this.markSubtree(tree, staticRoot, null);
      }
    };
    BBTree.prototype.insert = function(obj, hashid) {
      var leaf = new Leaf(this, obj);
      this.leaves[hashid] = leaf;
      this.root = subtreeInsert(this.root, leaf, this);
      this.count++;
      leaf.stamp = this.getStamp();
      leaf.addPairs(this);
      this.incrementStamp();
    };
    BBTree.prototype.remove = function(obj, hashid) {
      var leaf = this.leaves[hashid];
      delete this.leaves[hashid];
      this.root = subtreeRemove(this.root, leaf, this);
      this.count--;
      leaf.clearPairs(this);
      leaf.recycle(this);
    };
    BBTree.prototype.contains = function(obj, hashid) {
      return null != this.leaves[hashid];
    };
    var voidQueryFunc = function(obj1, obj2) {};
    BBTree.prototype.reindexQuery = function(func) {
      if (!this.root) return;
      var hashid, leaves = this.leaves;
      for (hashid in leaves) leaves[hashid].update(this);
      var staticIndex = this.staticIndex;
      var staticRoot = staticIndex && staticIndex.root;
      this.root.markSubtree(this, staticRoot, func);
      staticIndex && !staticRoot && this.collideStatic(this, staticIndex, func);
      this.incrementStamp();
    };
    BBTree.prototype.reindex = function() {
      this.reindexQuery(voidQueryFunc);
    };
    BBTree.prototype.reindexObject = function(obj, hashid) {
      var leaf = this.leaves[hashid];
      if (leaf) {
        leaf.update(this) && leaf.addPairs(this);
        this.incrementStamp();
      }
    };
    BBTree.prototype.pointQuery = function(point, func) {
      this.query(new BB(point.x, point.y, point.x, point.y), func);
    };
    BBTree.prototype.segmentQuery = function(a, b, t_exit, func) {
      this.root && subtreeSegmentQuery(this.root, a, b, t_exit, func);
    };
    BBTree.prototype.query = function(bb, func) {
      this.root && subtreeQuery(this.root, bb, func);
    };
    BBTree.prototype.count = function() {
      return this.count;
    };
    BBTree.prototype.each = function(func) {
      var hashid;
      for (hashid in this.leaves) func(this.leaves[hashid].obj);
    };
    var bbTreeMergedArea2 = function(node, l, b, r, t) {
      return (max(node.bb_r, r) - min(node.bb_l, l)) * (max(node.bb_t, t) - min(node.bb_b, b));
    };
    var partitionNodes = function(tree, nodes, offset, count) {
      if (1 == count) return nodes[offset];
      if (2 == count) return tree.makeNode(nodes[offset], nodes[offset + 1]);
      var node = nodes[offset];
      var bb_l = node.bb_l, bb_b = node.bb_b, bb_r = node.bb_r, bb_t = node.bb_t;
      var end = offset + count;
      for (var i = offset + 1; i < end; i++) {
        node = nodes[i];
        bb_l = min(bb_l, node.bb_l);
        bb_b = min(bb_b, node.bb_b);
        bb_r = max(bb_r, node.bb_r);
        bb_t = max(bb_t, node.bb_t);
      }
      var splitWidth = bb_r - bb_l > bb_t - bb_b;
      var bounds = new Array(2 * count);
      if (splitWidth) for (var i = offset; i < end; i++) {
        bounds[2 * i + 0] = nodes[i].bb_l;
        bounds[2 * i + 1] = nodes[i].bb_r;
      } else for (var i = offset; i < end; i++) {
        bounds[2 * i + 0] = nodes[i].bb_b;
        bounds[2 * i + 1] = nodes[i].bb_t;
      }
      bounds.sort((function(a, b) {
        return a - b;
      }));
      var split = .5 * (bounds[count - 1] + bounds[count]);
      var a_l = bb_l, a_b = bb_b, a_r = bb_r, a_t = bb_t;
      var b_l = bb_l, b_b = bb_b, b_r = bb_r, b_t = bb_t;
      splitWidth ? a_r = b_l = split : a_t = b_b = split;
      var right = end;
      for (var left = offset; left < right; ) {
        var node = nodes[left];
        if (bbTreeMergedArea2(node, b_l, b_b, b_r, b_t) < bbTreeMergedArea2(node, a_l, a_b, a_r, a_t)) {
          right--;
          nodes[left] = nodes[right];
          nodes[right] = node;
        } else left++;
      }
      if (right == count) {
        var node = null;
        for (var i = offset; i < end; i++) node = subtreeInsert(node, nodes[i], tree);
        return node;
      }
      return NodeNew(tree, partitionNodes(tree, nodes, offset, right - offset), partitionNodes(tree, nodes, right, end - right));
    };
    BBTree.prototype.optimize = function() {
      var nodes = new Array(this.count);
      var i = 0;
      for (var hashid in this.leaves) nodes[i++] = this.nodes[hashid];
      tree.subtreeRecycle(root);
      this.root = partitionNodes(tree, nodes, nodes.length);
    };
    var nodeRender = function(node, depth) {
      if (!node.isLeaf && depth <= 10) {
        nodeRender(node.A, depth + 1);
        nodeRender(node.B, depth + 1);
      }
      var str = "";
      for (var i = 0; i < depth; i++) str += " ";
      console.log(str + node.bb_b + " " + node.bb_t);
    };
    BBTree.prototype.log = function() {
      this.root && nodeRender(this.root, 0);
    };
    var CollisionHandler = cp.CollisionHandler = function() {
      this.a = this.b = 0;
    };
    CollisionHandler.prototype.begin = function(arb, space) {
      return true;
    };
    CollisionHandler.prototype.preSolve = function(arb, space) {
      return true;
    };
    CollisionHandler.prototype.postSolve = function(arb, space) {};
    CollisionHandler.prototype.separate = function(arb, space) {};
    var CP_MAX_CONTACTS_PER_ARBITER = 4;
    var Arbiter = function(a, b) {
      this.e = 0;
      this.u = 0;
      this.surface_vr = vzero;
      this.a = a;
      this.body_a = a.body;
      this.b = b;
      this.body_b = b.body;
      this.thread_a_next = this.thread_a_prev = null;
      this.thread_b_next = this.thread_b_prev = null;
      this.contacts = null;
      this.stamp = 0;
      this.handler = null;
      this.swappedColl = false;
      this.state = "first coll";
    };
    Arbiter.prototype.getShapes = function() {
      return this.swappedColl ? [ this.b, this.a ] : [ this.a, this.b ];
    };
    Arbiter.prototype.totalImpulse = function() {
      var contacts = this.contacts;
      var sum = new Vect(0, 0);
      for (var i = 0, count = contacts.length; i < count; i++) {
        var con = contacts[i];
        sum.add(vmult(con.n, con.jnAcc));
      }
      return this.swappedColl ? sum : sum.neg();
    };
    Arbiter.prototype.totalImpulseWithFriction = function() {
      var contacts = this.contacts;
      var sum = new Vect(0, 0);
      for (var i = 0, count = contacts.length; i < count; i++) {
        var con = contacts[i];
        sum.add(new Vect(con.jnAcc, con.jtAcc).rotate(con.n));
      }
      return this.swappedColl ? sum : sum.neg();
    };
    Arbiter.prototype.totalKE = function() {
      var eCoef = (1 - this.e) / (1 + this.e);
      var sum = 0;
      var contacts = this.contacts;
      for (var i = 0, count = contacts.length; i < count; i++) {
        var con = contacts[i];
        var jnAcc = con.jnAcc;
        var jtAcc = con.jtAcc;
        sum += eCoef * jnAcc * jnAcc / con.nMass + jtAcc * jtAcc / con.tMass;
      }
      return sum;
    };
    Arbiter.prototype.ignore = function() {
      this.state = "ignore";
    };
    Arbiter.prototype.getA = function() {
      return this.swappedColl ? this.b : this.a;
    };
    Arbiter.prototype.getB = function() {
      return this.swappedColl ? this.a : this.b;
    };
    Arbiter.prototype.isFirstContact = function() {
      return "first coll" === this.state;
    };
    var ContactPoint = function(point, normal, dist) {
      this.point = point;
      this.normal = normal;
      this.dist = dist;
    };
    Arbiter.prototype.getContactPointSet = function() {
      var set = new Array(this.contacts.length);
      var i;
      for (i = 0; i < set.length; i++) set[i] = new ContactPoint(this.contacts[i].p, this.contacts[i].n, this.contacts[i].dist);
      return set;
    };
    Arbiter.prototype.getNormal = function(i) {
      var n = this.contacts[i].n;
      return this.swappedColl ? vneg(n) : n;
    };
    Arbiter.prototype.getPoint = function(i) {
      return this.contacts[i].p;
    };
    Arbiter.prototype.getDepth = function(i) {
      return this.contacts[i].dist;
    };
    var unthreadHelper = function(arb, body, prev, next) {
      prev ? prev.body_a === body ? prev.thread_a_next = next : prev.thread_b_next = next : body.arbiterList = next;
      next && (next.body_a === body ? next.thread_a_prev = prev : next.thread_b_prev = prev);
    };
    Arbiter.prototype.unthread = function() {
      unthreadHelper(this, this.body_a, this.thread_a_prev, this.thread_a_next);
      unthreadHelper(this, this.body_b, this.thread_b_prev, this.thread_b_next);
      this.thread_a_prev = this.thread_a_next = null;
      this.thread_b_prev = this.thread_b_next = null;
    };
    Arbiter.prototype.update = function(contacts, handler, a, b) {
      if (this.contacts) for (var i = 0; i < this.contacts.length; i++) {
        var old = this.contacts[i];
        for (var j = 0; j < contacts.length; j++) {
          var new_contact = contacts[j];
          if (new_contact.hash === old.hash) {
            new_contact.jnAcc = old.jnAcc;
            new_contact.jtAcc = old.jtAcc;
          }
        }
      }
      this.contacts = contacts;
      this.handler = handler;
      this.swappedColl = a.collision_type !== handler.a;
      this.e = a.e * b.e;
      this.u = a.u * b.u;
      this.surface_vr = vsub(a.surface_v, b.surface_v);
      this.a = a;
      this.body_a = a.body;
      this.b = b;
      this.body_b = b.body;
      "cached" == this.state && (this.state = "first coll");
    };
    Arbiter.prototype.preStep = function(dt, slop, bias) {
      var a = this.body_a;
      var b = this.body_b;
      for (var i = 0; i < this.contacts.length; i++) {
        var con = this.contacts[i];
        con.r1 = vsub(con.p, a.p);
        con.r2 = vsub(con.p, b.p);
        con.nMass = 1 / k_scalar(a, b, con.r1, con.r2, con.n);
        con.tMass = 1 / k_scalar(a, b, con.r1, con.r2, vperp(con.n));
        con.bias = -bias * min(0, con.dist + slop) / dt;
        con.jBias = 0;
        con.bounce = normal_relative_velocity(a, b, con.r1, con.r2, con.n) * this.e;
      }
    };
    Arbiter.prototype.applyCachedImpulse = function(dt_coef) {
      if (this.isFirstContact()) return;
      var a = this.body_a;
      var b = this.body_b;
      for (var i = 0; i < this.contacts.length; i++) {
        var con = this.contacts[i];
        var nx = con.n.x;
        var ny = con.n.y;
        var jx = nx * con.jnAcc - ny * con.jtAcc;
        var jy = nx * con.jtAcc + ny * con.jnAcc;
        apply_impulses(a, b, con.r1, con.r2, jx * dt_coef, jy * dt_coef);
      }
    };
    var numApplyImpulse = 0;
    var numApplyContact = 0;
    Arbiter.prototype.applyImpulse = function() {
      numApplyImpulse++;
      var a = this.body_a;
      var b = this.body_b;
      var surface_vr = this.surface_vr;
      var friction = this.u;
      for (var i = 0; i < this.contacts.length; i++) {
        numApplyContact++;
        var con = this.contacts[i];
        var nMass = con.nMass;
        var n = con.n;
        var r1 = con.r1;
        var r2 = con.r2;
        var vrx = b.vx - r2.y * b.w - (a.vx - r1.y * a.w);
        var vry = b.vy + r2.x * b.w - (a.vy + r1.x * a.w);
        var vbn = n.x * (b.v_biasx - r2.y * b.w_bias - a.v_biasx + r1.y * a.w_bias) + n.y * (r2.x * b.w_bias + b.v_biasy - r1.x * a.w_bias - a.v_biasy);
        var vrn = vdot2(vrx, vry, n.x, n.y);
        var vrt = vdot2(vrx + surface_vr.x, vry + surface_vr.y, -n.y, n.x);
        var jbn = (con.bias - vbn) * nMass;
        var jbnOld = con.jBias;
        con.jBias = max(jbnOld + jbn, 0);
        var jn = -(con.bounce + vrn) * nMass;
        var jnOld = con.jnAcc;
        con.jnAcc = max(jnOld + jn, 0);
        var jtMax = friction * con.jnAcc;
        var jt = -vrt * con.tMass;
        var jtOld = con.jtAcc;
        con.jtAcc = clamp(jtOld + jt, -jtMax, jtMax);
        var bias_x = n.x * (con.jBias - jbnOld);
        var bias_y = n.y * (con.jBias - jbnOld);
        apply_bias_impulse(a, -bias_x, -bias_y, r1);
        apply_bias_impulse(b, bias_x, bias_y, r2);
        var rot_x = con.jnAcc - jnOld;
        var rot_y = con.jtAcc - jtOld;
        apply_impulses(a, b, r1, r2, n.x * rot_x - n.y * rot_y, n.x * rot_y + n.y * rot_x);
      }
    };
    Arbiter.prototype.callSeparate = function(space) {
      var handler = space.lookupHandler(this.a.collision_type, this.b.collision_type);
      handler.separate(this, space);
    };
    Arbiter.prototype.next = function(body) {
      return this.body_a == body ? this.thread_a_next : this.thread_b_next;
    };
    var numContacts = 0;
    var Contact = function(p, n, dist, hash) {
      this.p = p;
      this.n = n;
      this.dist = dist;
      this.r1 = this.r2 = vzero;
      this.nMass = this.tMass = this.bounce = this.bias = 0;
      this.jnAcc = this.jtAcc = this.jBias = 0;
      this.hash = hash;
      numContacts++;
    };
    var NONE = [];
    var circle2circleQuery = function(p1, p2, r1, r2) {
      var mindist = r1 + r2;
      var delta = vsub(p2, p1);
      var distsq = vlengthsq(delta);
      if (distsq >= mindist * mindist) return;
      var dist = Math.sqrt(distsq);
      return new Contact(vadd(p1, vmult(delta, .5 + (r1 - .5 * mindist) / (dist || Infinity))), dist ? vmult(delta, 1 / dist) : new Vect(1, 0), dist - mindist, 0);
    };
    var circle2circle = function(circ1, circ2) {
      var contact = circle2circleQuery(circ1.tc, circ2.tc, circ1.r, circ2.r);
      return contact ? [ contact ] : NONE;
    };
    var circle2segment = function(circleShape, segmentShape) {
      var seg_a = segmentShape.ta;
      var seg_b = segmentShape.tb;
      var center = circleShape.tc;
      var seg_delta = vsub(seg_b, seg_a);
      var closest_t = clamp01(vdot(seg_delta, vsub(center, seg_a)) / vlengthsq(seg_delta));
      var closest = vadd(seg_a, vmult(seg_delta, closest_t));
      var contact = circle2circleQuery(center, closest, circleShape.r, segmentShape.r);
      if (contact) {
        var n = contact.n;
        return 0 === closest_t && vdot(n, segmentShape.a_tangent) < 0 || 1 === closest_t && vdot(n, segmentShape.b_tangent) < 0 ? NONE : [ contact ];
      }
      return NONE;
    };
    var last_MSA_min = 0;
    var findMSA = function(poly, planes) {
      var min_index = 0;
      var min = poly.valueOnAxis(planes[0].n, planes[0].d);
      if (min > 0) return -1;
      for (var i = 1; i < planes.length; i++) {
        var dist = poly.valueOnAxis(planes[i].n, planes[i].d);
        if (dist > 0) return -1;
        if (dist > min) {
          min = dist;
          min_index = i;
        }
      }
      last_MSA_min = min;
      return min_index;
    };
    var findVertsFallback = function(poly1, poly2, n, dist) {
      var arr = [];
      var verts1 = poly1.tVerts;
      for (var i = 0; i < verts1.length; i += 2) {
        var vx = verts1[i];
        var vy = verts1[i + 1];
        poly2.containsVertPartial(vx, vy, vneg(n)) && arr.push(new Contact(new Vect(vx, vy), n, dist, hashPair(poly1.hashid, i)));
      }
      var verts2 = poly2.tVerts;
      for (var i = 0; i < verts2.length; i += 2) {
        var vx = verts2[i];
        var vy = verts2[i + 1];
        poly1.containsVertPartial(vx, vy, n) && arr.push(new Contact(new Vect(vx, vy), n, dist, hashPair(poly2.hashid, i)));
      }
      return arr;
    };
    var findVerts = function(poly1, poly2, n, dist) {
      var arr = [];
      var verts1 = poly1.tVerts;
      for (var i = 0; i < verts1.length; i += 2) {
        var vx = verts1[i];
        var vy = verts1[i + 1];
        poly2.containsVert(vx, vy) && arr.push(new Contact(new Vect(vx, vy), n, dist, hashPair(poly1.hashid, i >> 1)));
      }
      var verts2 = poly2.tVerts;
      for (var i = 0; i < verts2.length; i += 2) {
        var vx = verts2[i];
        var vy = verts2[i + 1];
        poly1.containsVert(vx, vy) && arr.push(new Contact(new Vect(vx, vy), n, dist, hashPair(poly2.hashid, i >> 1)));
      }
      return arr.length ? arr : findVertsFallback(poly1, poly2, n, dist);
    };
    var poly2poly = function(poly1, poly2) {
      var mini1 = findMSA(poly2, poly1.tPlanes);
      if (-1 == mini1) return NONE;
      var min1 = last_MSA_min;
      var mini2 = findMSA(poly1, poly2.tPlanes);
      if (-1 == mini2) return NONE;
      var min2 = last_MSA_min;
      return min1 > min2 ? findVerts(poly1, poly2, poly1.tPlanes[mini1].n, min1) : findVerts(poly1, poly2, vneg(poly2.tPlanes[mini2].n), min2);
    };
    var segValueOnAxis = function(seg, n, d) {
      var a = vdot(n, seg.ta) - seg.r;
      var b = vdot(n, seg.tb) - seg.r;
      return min(a, b) - d;
    };
    var findPointsBehindSeg = function(arr, seg, poly, pDist, coef) {
      var dta = vcross(seg.tn, seg.ta);
      var dtb = vcross(seg.tn, seg.tb);
      var n = vmult(seg.tn, coef);
      var verts = poly.tVerts;
      for (var i = 0; i < verts.length; i += 2) {
        var vx = verts[i];
        var vy = verts[i + 1];
        if (vdot2(vx, vy, n.x, n.y) < vdot(seg.tn, seg.ta) * coef + seg.r) {
          var dt = vcross2(seg.tn.x, seg.tn.y, vx, vy);
          dta >= dt && dt >= dtb && arr.push(new Contact(new Vect(vx, vy), n, pDist, hashPair(poly.hashid, i)));
        }
      }
    };
    var seg2poly = function(seg, poly) {
      var arr = [];
      var planes = poly.tPlanes;
      var numVerts = planes.length;
      var segD = vdot(seg.tn, seg.ta);
      var minNorm = poly.valueOnAxis(seg.tn, segD) - seg.r;
      var minNeg = poly.valueOnAxis(vneg(seg.tn), -segD) - seg.r;
      if (minNeg > 0 || minNorm > 0) return NONE;
      var mini = 0;
      var poly_min = segValueOnAxis(seg, planes[0].n, planes[0].d);
      if (poly_min > 0) return NONE;
      for (var i = 0; i < numVerts; i++) {
        var dist = segValueOnAxis(seg, planes[i].n, planes[i].d);
        if (dist > 0) return NONE;
        if (dist > poly_min) {
          poly_min = dist;
          mini = i;
        }
      }
      var poly_n = vneg(planes[mini].n);
      var va = vadd(seg.ta, vmult(poly_n, seg.r));
      var vb = vadd(seg.tb, vmult(poly_n, seg.r));
      poly.containsVert(va.x, va.y) && arr.push(new Contact(va, poly_n, poly_min, hashPair(seg.hashid, 0)));
      poly.containsVert(vb.x, vb.y) && arr.push(new Contact(vb, poly_n, poly_min, hashPair(seg.hashid, 1)));
      (minNorm >= poly_min || minNeg >= poly_min) && (minNorm > minNeg ? findPointsBehindSeg(arr, seg, poly, minNorm, 1) : findPointsBehindSeg(arr, seg, poly, minNeg, -1));
      if (0 === arr.length) {
        var mini2 = 2 * mini;
        var verts = poly.tVerts;
        var poly_a = new Vect(verts[mini2], verts[mini2 + 1]);
        var con;
        if (con = circle2circleQuery(seg.ta, poly_a, seg.r, 0, arr)) return [ con ];
        if (con = circle2circleQuery(seg.tb, poly_a, seg.r, 0, arr)) return [ con ];
        var len = 2 * numVerts;
        var poly_b = new Vect(verts[(mini2 + 2) % len], verts[(mini2 + 3) % len]);
        if (con = circle2circleQuery(seg.ta, poly_b, seg.r, 0, arr)) return [ con ];
        if (con = circle2circleQuery(seg.tb, poly_b, seg.r, 0, arr)) return [ con ];
      }
      return arr;
    };
    var circle2poly = function(circ, poly) {
      var planes = poly.tPlanes;
      var mini = 0;
      var min = vdot(planes[0].n, circ.tc) - planes[0].d - circ.r;
      for (var i = 0; i < planes.length; i++) {
        var dist = vdot(planes[i].n, circ.tc) - planes[i].d - circ.r;
        if (dist > 0) return NONE;
        if (dist > min) {
          min = dist;
          mini = i;
        }
      }
      var n = planes[mini].n;
      var verts = poly.tVerts;
      var len = verts.length;
      var mini2 = mini << 1;
      var ax = verts[mini2];
      var ay = verts[mini2 + 1];
      var bx = verts[(mini2 + 2) % len];
      var by = verts[(mini2 + 3) % len];
      var dta = vcross2(n.x, n.y, ax, ay);
      var dtb = vcross2(n.x, n.y, bx, by);
      var dt = vcross(n, circ.tc);
      if (dt < dtb) {
        var con = circle2circleQuery(circ.tc, new Vect(bx, by), circ.r, 0, con);
        return con ? [ con ] : NONE;
      }
      if (dt < dta) return [ new Contact(vsub(circ.tc, vmult(n, circ.r + min / 2)), vneg(n), min, 0) ];
      var con = circle2circleQuery(circ.tc, new Vect(ax, ay), circ.r, 0, con);
      return con ? [ con ] : NONE;
    };
    CircleShape.prototype.collisionCode = 0;
    SegmentShape.prototype.collisionCode = 1;
    PolyShape.prototype.collisionCode = 2;
    CircleShape.prototype.collisionTable = [ circle2circle, circle2segment, circle2poly ];
    SegmentShape.prototype.collisionTable = [ null, function(segA, segB) {
      return NONE;
    }, seg2poly ];
    PolyShape.prototype.collisionTable = [ null, null, poly2poly ];
    var collideShapes = cp.collideShapes = function(a, b) {
      assert(a.collisionCode <= b.collisionCode, "Collided shapes must be sorted by type");
      return a.collisionTable[b.collisionCode](a, b);
    };
    var defaultCollisionHandler = new CollisionHandler();
    var Space = cp.Space = function() {
      this.stamp = 0;
      this.curr_dt = 0;
      this.bodies = [];
      this.rousedBodies = [];
      this.sleepingComponents = [];
      this.staticShapes = new BBTree(null);
      this.activeShapes = new BBTree(this.staticShapes);
      this.arbiters = [];
      this.contactBuffersHead = null;
      this.cachedArbiters = {};
      this.constraints = [];
      this.locked = 0;
      this.collisionHandlers = {};
      this.defaultHandler = defaultCollisionHandler;
      this.postStepCallbacks = [];
      this.iterations = 10;
      this.gravity = vzero;
      this.damping = 1;
      this.idleSpeedThreshold = 0;
      this.sleepTimeThreshold = Infinity;
      this.collisionSlop = .1;
      this.collisionBias = Math.pow(.9, 60);
      this.collisionPersistence = 3;
      this.enableContactGraph = false;
      this.staticBody = new Body(Infinity, Infinity);
      this.staticBody.nodeIdleTime = Infinity;
      this.collideShapes = this.makeCollideShapes();
    };
    Space.prototype.getCurrentTimeStep = function() {
      return this.curr_dt;
    };
    Space.prototype.setIterations = function(iter) {
      this.iterations = iter;
    };
    Space.prototype.isLocked = function() {
      return this.locked;
    };
    var assertSpaceUnlocked = function(space) {
      assert(!space.locked, "This addition/removal cannot be done safely during a call to cpSpaceStep()  or during a query. Put these calls into a post-step callback.");
    };
    Space.prototype.addCollisionHandler = function(a, b, begin, preSolve, postSolve, separate) {
      assertSpaceUnlocked(this);
      this.removeCollisionHandler(a, b);
      var handler = new CollisionHandler();
      handler.a = a;
      handler.b = b;
      begin && (handler.begin = begin);
      preSolve && (handler.preSolve = preSolve);
      postSolve && (handler.postSolve = postSolve);
      separate && (handler.separate = separate);
      this.collisionHandlers[hashPair(a, b)] = handler;
    };
    Space.prototype.removeCollisionHandler = function(a, b) {
      assertSpaceUnlocked(this);
      delete this.collisionHandlers[hashPair(a, b)];
    };
    Space.prototype.setDefaultCollisionHandler = function(begin, preSolve, postSolve, separate) {
      assertSpaceUnlocked(this);
      var handler = new CollisionHandler();
      begin && (handler.begin = begin);
      preSolve && (handler.preSolve = preSolve);
      postSolve && (handler.postSolve = postSolve);
      separate && (handler.separate = separate);
      this.defaultHandler = handler;
    };
    Space.prototype.lookupHandler = function(a, b) {
      return this.collisionHandlers[hashPair(a, b)] || this.defaultHandler;
    };
    Space.prototype.addShape = function(shape) {
      var body = shape.body;
      if (body.isStatic()) return this.addStaticShape(shape);
      assert(!shape.space, "This shape is already added to a space and cannot be added to another.");
      assertSpaceUnlocked(this);
      body.activate();
      body.addShape(shape);
      shape.update(body.p, body.rot);
      this.activeShapes.insert(shape, shape.hashid);
      shape.space = this;
      return shape;
    };
    Space.prototype.addStaticShape = function(shape) {
      assert(!shape.space, "This shape is already added to a space and cannot be added to another.");
      assertSpaceUnlocked(this);
      var body = shape.body;
      body.addShape(shape);
      shape.update(body.p, body.rot);
      this.staticShapes.insert(shape, shape.hashid);
      shape.space = this;
      return shape;
    };
    Space.prototype.addBody = function(body) {
      assert(!body.isStatic(), "Static bodies cannot be added to a space as they are not meant to be simulated.");
      assert(!body.space, "This body is already added to a space and cannot be added to another.");
      assertSpaceUnlocked(this);
      this.bodies.push(body);
      body.space = this;
      return body;
    };
    Space.prototype.addConstraint = function(constraint) {
      assert(!constraint.space, "This shape is already added to a space and cannot be added to another.");
      assertSpaceUnlocked(this);
      var a = constraint.a, b = constraint.b;
      a.activate();
      b.activate();
      this.constraints.push(constraint);
      constraint.next_a = a.constraintList;
      a.constraintList = constraint;
      constraint.next_b = b.constraintList;
      b.constraintList = constraint;
      constraint.space = this;
      return constraint;
    };
    Space.prototype.filterArbiters = function(body, filter) {
      for (var hash in this.cachedArbiters) {
        var arb = this.cachedArbiters[hash];
        if (body === arb.body_a && (filter === arb.a || null === filter) || body === arb.body_b && (filter === arb.b || null === filter)) {
          filter && "cached" !== arb.state && arb.callSeparate(this);
          arb.unthread();
          deleteObjFromList(this.arbiters, arb);
          delete this.cachedArbiters[hash];
        }
      }
    };
    Space.prototype.removeShape = function(shape) {
      var body = shape.body;
      if (body.isStatic()) this.removeStaticShape(shape); else {
        assert(this.containsShape(shape), "Cannot remove a shape that was not added to the space. (Removed twice maybe?)");
        assertSpaceUnlocked(this);
        body.activate();
        body.removeShape(shape);
        this.filterArbiters(body, shape);
        this.activeShapes.remove(shape, shape.hashid);
        shape.space = null;
      }
    };
    Space.prototype.removeStaticShape = function(shape) {
      assert(this.containsShape(shape), "Cannot remove a static or sleeping shape that was not added to the space. (Removed twice maybe?)");
      assertSpaceUnlocked(this);
      var body = shape.body;
      body.isStatic() && body.activateStatic(shape);
      body.removeShape(shape);
      this.filterArbiters(body, shape);
      this.staticShapes.remove(shape, shape.hashid);
      shape.space = null;
    };
    Space.prototype.removeBody = function(body) {
      assert(this.containsBody(body), "Cannot remove a body that was not added to the space. (Removed twice maybe?)");
      assertSpaceUnlocked(this);
      body.activate();
      deleteObjFromList(this.bodies, body);
      body.space = null;
    };
    Space.prototype.removeConstraint = function(constraint) {
      assert(this.containsConstraint(constraint), "Cannot remove a constraint that was not added to the space. (Removed twice maybe?)");
      assertSpaceUnlocked(this);
      constraint.a.activate();
      constraint.b.activate();
      deleteObjFromList(this.constraints, constraint);
      constraint.a.removeConstraint(constraint);
      constraint.b.removeConstraint(constraint);
      constraint.space = null;
    };
    Space.prototype.containsShape = function(shape) {
      return shape.space === this;
    };
    Space.prototype.containsBody = function(body) {
      return body.space == this;
    };
    Space.prototype.containsConstraint = function(constraint) {
      return constraint.space == this;
    };
    Space.prototype.uncacheArbiter = function(arb) {
      delete this.cachedArbiters[hashPair(arb.a.hashid, arb.b.hashid)];
      deleteObjFromList(this.arbiters, arb);
    };
    Space.prototype.eachBody = function(func) {
      this.lock();
      var bodies = this.bodies;
      for (var i = 0; i < bodies.length; i++) func(bodies[i]);
      var components = this.sleepingComponents;
      for (var i = 0; i < components.length; i++) {
        var root = components[i];
        var body = root;
        while (body) {
          var next = body.nodeNext;
          func(body);
          body = next;
        }
      }
      this.unlock(true);
    };
    Space.prototype.eachShape = function(func) {
      this.lock();
      this.activeShapes.each(func);
      this.staticShapes.each(func);
      this.unlock(true);
    };
    Space.prototype.eachConstraint = function(func) {
      this.lock();
      var constraints = this.constraints;
      for (var i = 0; i < constraints.length; i++) func(constraints[i]);
      this.unlock(true);
    };
    Space.prototype.reindexStatic = function() {
      assert(!this.locked, "You cannot manually reindex objects while the space is locked. Wait until the current query or step is complete.");
      this.staticShapes.each((function(shape) {
        var body = shape.body;
        shape.update(body.p, body.rot);
      }));
      this.staticShapes.reindex();
    };
    Space.prototype.reindexShape = function(shape) {
      assert(!this.locked, "You cannot manually reindex objects while the space is locked. Wait until the current query or step is complete.");
      var body = shape.body;
      shape.update(body.p, body.rot);
      this.activeShapes.reindexObject(shape, shape.hashid);
      this.staticShapes.reindexObject(shape, shape.hashid);
    };
    Space.prototype.reindexShapesForBody = function(body) {
      for (var shape = body.shapeList; shape; shape = shape.next) this.reindexShape(shape);
    };
    Space.prototype.useSpatialHash = function(dim, count) {
      throw new Error("Spatial Hash not implemented.");
      var staticShapes;
      var activeShapes;
    };
    Space.prototype.activateBody = function(body) {
      assert(!body.isRogue(), "Internal error: Attempting to activate a rogue body.");
      if (this.locked) -1 === this.rousedBodies.indexOf(body) && this.rousedBodies.push(body); else {
        this.bodies.push(body);
        for (var i = 0; i < body.shapeList.length; i++) {
          var shape = body.shapeList[i];
          this.staticShapes.remove(shape, shape.hashid);
          this.activeShapes.insert(shape, shape.hashid);
        }
        for (var arb = body.arbiterList; arb; arb = arb.next(body)) {
          var bodyA = arb.body_a;
          if (body === bodyA || bodyA.isStatic()) {
            var a = arb.a, b = arb.b;
            this.cachedArbiters[hashPair(a.hashid, b.hashid)] = arb;
            arb.stamp = this.stamp;
            arb.handler = this.lookupHandler(a.collision_type, b.collision_type);
            this.arbiters.push(arb);
          }
        }
        for (var constraint = body.constraintList; constraint; constraint = constraint.nodeNext) {
          var bodyA = constraint.a;
          (body === bodyA || bodyA.isStatic()) && this.constraints.push(constraint);
        }
      }
    };
    Space.prototype.deactivateBody = function(body) {
      assert(!body.isRogue(), "Internal error: Attempting to deactivate a rogue body.");
      deleteObjFromList(this.bodies, body);
      for (var i = 0; i < body.shapeList.length; i++) {
        var shape = body.shapeList[i];
        this.activeShapes.remove(shape, shape.hashid);
        this.staticShapes.insert(shape, shape.hashid);
      }
      for (var arb = body.arbiterList; arb; arb = arb.next(body)) {
        var bodyA = arb.body_a;
        (body === bodyA || bodyA.isStatic()) && this.uncacheArbiter(arb);
      }
      for (var constraint = body.constraintList; constraint; constraint = constraint.nodeNext) {
        var bodyA = constraint.a;
        (body === bodyA || bodyA.isStatic()) && deleteObjFromList(this.constraints, constraint);
      }
    };
    var componentRoot = function(body) {
      return body ? body.nodeRoot : null;
    };
    var componentActivate = function(root) {
      if (!root || !root.isSleeping(root)) return;
      assert(!root.isRogue(), "Internal Error: componentActivate() called on a rogue body.");
      var space = root.space;
      var body = root;
      while (body) {
        var next = body.nodeNext;
        body.nodeIdleTime = 0;
        body.nodeRoot = null;
        body.nodeNext = null;
        space.activateBody(body);
        body = next;
      }
      deleteObjFromList(space.sleepingComponents, root);
    };
    Body.prototype.activate = function() {
      if (!this.isRogue()) {
        this.nodeIdleTime = 0;
        componentActivate(componentRoot(this));
      }
    };
    Body.prototype.activateStatic = function(filter) {
      assert(this.isStatic(), "Body.activateStatic() called on a non-static body.");
      for (var arb = this.arbiterList; arb; arb = arb.next(this)) filter && filter != arb.a && filter != arb.b || (arb.body_a == this ? arb.body_b : arb.body_a).activate();
    };
    Body.prototype.pushArbiter = function(arb) {
      assertSoft(null === (arb.body_a === this ? arb.thread_a_next : arb.thread_b_next), "Internal Error: Dangling contact graph pointers detected. (A)");
      assertSoft(null === (arb.body_a === this ? arb.thread_a_prev : arb.thread_b_prev), "Internal Error: Dangling contact graph pointers detected. (B)");
      var next = this.arbiterList;
      assertSoft(null === next || null === (next.body_a === this ? next.thread_a_prev : next.thread_b_prev), "Internal Error: Dangling contact graph pointers detected. (C)");
      arb.body_a === this ? arb.thread_a_next = next : arb.thread_b_next = next;
      next && (next.body_a === this ? next.thread_a_prev = arb : next.thread_b_prev = arb);
      this.arbiterList = arb;
    };
    var componentAdd = function(root, body) {
      body.nodeRoot = root;
      if (body !== root) {
        body.nodeNext = root.nodeNext;
        root.nodeNext = body;
      }
    };
    var floodFillComponent = function(root, body) {
      if (!body.isRogue()) {
        var other_root = componentRoot(body);
        if (null == other_root) {
          componentAdd(root, body);
          for (var arb = body.arbiterList; arb; arb = arb.next(body)) floodFillComponent(root, body == arb.body_a ? arb.body_b : arb.body_a);
          for (var constraint = body.constraintList; constraint; constraint = constraint.next(body)) floodFillComponent(root, body == constraint.a ? constraint.b : constraint.a);
        } else assertSoft(other_root === root, "Internal Error: Inconsistency detected in the contact graph.");
      }
    };
    var componentActive = function(root, threshold) {
      for (var body = root; body; body = body.nodeNext) if (body.nodeIdleTime < threshold) return true;
      return false;
    };
    Space.prototype.processComponents = function(dt) {
      var sleep = Infinity !== this.sleepTimeThreshold;
      var bodies = this.bodies;
      for (var i = 0; i < bodies.length; i++) {
        var body = bodies[i];
        assertSoft(null === body.nodeNext, "Internal Error: Dangling next pointer detected in contact graph.");
        assertSoft(null === body.nodeRoot, "Internal Error: Dangling root pointer detected in contact graph.");
      }
      if (sleep) {
        var dv = this.idleSpeedThreshold;
        var dvsq = dv ? dv * dv : vlengthsq(this.gravity) * dt * dt;
        for (var i = 0; i < bodies.length; i++) {
          var body = bodies[i];
          var keThreshold = dvsq ? body.m * dvsq : 0;
          body.nodeIdleTime = body.kineticEnergy() > keThreshold ? 0 : body.nodeIdleTime + dt;
        }
      }
      var arbiters = this.arbiters;
      for (var i = 0, count = arbiters.length; i < count; i++) {
        var arb = arbiters[i];
        var a = arb.body_a, b = arb.body_b;
        if (sleep) {
          (b.isRogue() && !b.isStatic() || a.isSleeping()) && a.activate();
          (a.isRogue() && !a.isStatic() || b.isSleeping()) && b.activate();
        }
        a.pushArbiter(arb);
        b.pushArbiter(arb);
      }
      if (sleep) {
        var constraints = this.constraints;
        for (var i = 0; i < constraints.length; i++) {
          var constraint = constraints[i];
          var a = constraint.a, b = constraint.b;
          b.isRogue() && !b.isStatic() && a.activate();
          a.isRogue() && !a.isStatic() && b.activate();
        }
        for (var i = 0; i < bodies.length; ) {
          var body = bodies[i];
          if (null === componentRoot(body)) {
            floodFillComponent(body, body);
            if (!componentActive(body, this.sleepTimeThreshold)) {
              this.sleepingComponents.push(body);
              for (var other = body; other; other = other.nodeNext) this.deactivateBody(other);
              continue;
            }
          }
          i++;
          body.nodeRoot = null;
          body.nodeNext = null;
        }
      }
    };
    Body.prototype.sleep = function() {
      this.sleepWithGroup(null);
    };
    Body.prototype.sleepWithGroup = function(group) {
      assert(!this.isStatic() && !this.isRogue(), "Rogue and static bodies cannot be put to sleep.");
      var space = this.space;
      assert(space, "Cannot put a rogue body to sleep.");
      assert(!space.locked, "Bodies cannot be put to sleep during a query or a call to cpSpaceStep(). Put these calls into a post-step callback.");
      assert(null === group || group.isSleeping(), "Cannot use a non-sleeping body as a group identifier.");
      if (this.isSleeping()) {
        assert(componentRoot(this) === componentRoot(group), "The body is already sleeping and it's group cannot be reassigned.");
        return;
      }
      for (var i = 0; i < this.shapeList.length; i++) this.shapeList[i].update(this.p, this.rot);
      space.deactivateBody(this);
      if (group) {
        var root = componentRoot(group);
        this.nodeRoot = root;
        this.nodeNext = root.nodeNext;
        this.nodeIdleTime = 0;
        root.nodeNext = this;
      } else {
        this.nodeRoot = this;
        this.nodeNext = null;
        this.nodeIdleTime = 0;
        space.sleepingComponents.push(this);
      }
      deleteObjFromList(space.bodies, this);
    };
    Space.prototype.activateShapesTouchingShape = function(shape) {
      Infinity !== this.sleepTimeThreshold && this.shapeQuery(shape, (function(shape, points) {
        shape.body.activate();
      }));
    };
    Space.prototype.pointQuery = function(point, layers, group, func) {
      var helper = function(shape) {
        !(shape.group && group === shape.group) && layers & shape.layers && shape.pointQuery(point) && func(shape);
      };
      var bb = new BB(point.x, point.y, point.x, point.y);
      this.lock();
      this.activeShapes.query(bb, helper);
      this.staticShapes.query(bb, helper);
      this.unlock(true);
    };
    Space.prototype.pointQueryFirst = function(point, layers, group) {
      var outShape = null;
      this.pointQuery(point, layers, group, (function(shape) {
        shape.sensor || (outShape = shape);
      }));
      return outShape;
    };
    Space.prototype.nearestPointQuery = function(point, maxDistance, layers, group, func) {
      var helper = function(shape) {
        if (!(shape.group && group === shape.group) && layers & shape.layers) {
          var info = shape.nearestPointQuery(point);
          info.d < maxDistance && func(shape, info.d, info.p);
        }
      };
      var bb = bbNewForCircle(point, maxDistance);
      this.lock();
      this.activeShapes.query(bb, helper);
      this.staticShapes.query(bb, helper);
      this.unlock(true);
    };
    Space.prototype.nearestPointQueryNearest = function(point, maxDistance, layers, group) {
      var out;
      var helper = function(shape) {
        if (!(shape.group && group === shape.group) && layers & shape.layers && !shape.sensor) {
          var info = shape.nearestPointQuery(point);
          info.d < maxDistance && (!out || info.d < out.d) && (out = info);
        }
      };
      var bb = bbNewForCircle(point, maxDistance);
      this.activeShapes.query(bb, helper);
      this.staticShapes.query(bb, helper);
      return out;
    };
    Space.prototype.segmentQuery = function(start, end, layers, group, func) {
      var helper = function(shape) {
        var info;
        !(shape.group && group === shape.group) && layers & shape.layers && (info = shape.segmentQuery(start, end)) && func(shape, info.t, info.n);
        return 1;
      };
      this.lock();
      this.staticShapes.segmentQuery(start, end, 1, helper);
      this.activeShapes.segmentQuery(start, end, 1, helper);
      this.unlock(true);
    };
    Space.prototype.segmentQueryFirst = function(start, end, layers, group) {
      var out = null;
      var helper = function(shape) {
        var info;
        !(shape.group && group === shape.group) && layers & shape.layers && !shape.sensor && (info = shape.segmentQuery(start, end)) && (null === out || info.t < out.t) && (out = info);
        return out ? out.t : 1;
      };
      this.staticShapes.segmentQuery(start, end, 1, helper);
      this.activeShapes.segmentQuery(start, end, out ? out.t : 1, helper);
      return out;
    };
    Space.prototype.bbQuery = function(bb, layers, group, func) {
      var helper = function(shape) {
        !(shape.group && group === shape.group) && layers & shape.layers && bbIntersects2(bb, shape.bb_l, shape.bb_b, shape.bb_r, shape.bb_t) && func(shape);
      };
      this.lock();
      this.activeShapes.query(bb, helper);
      this.staticShapes.query(bb, helper);
      this.unlock(true);
    };
    Space.prototype.shapeQuery = function(shape, func) {
      var body = shape.body;
      body && shape.update(body.p, body.rot);
      var bb = new BB(shape.bb_l, shape.bb_b, shape.bb_r, shape.bb_t);
      var anyCollision = false;
      var helper = function(b) {
        var a = shape;
        if (a.group && a.group === b.group || !(a.layers & b.layers) || a === b) return;
        var contacts;
        if (a.collisionCode <= b.collisionCode) contacts = collideShapes(a, b); else {
          contacts = collideShapes(b, a);
          for (var i = 0; i < contacts.length; i++) contacts[i].n = vneg(contacts[i].n);
        }
        if (contacts.length) {
          anyCollision = !(a.sensor || b.sensor);
          if (func) {
            var set = new Array(contacts.length);
            for (var i = 0; i < contacts.length; i++) set[i] = new ContactPoint(contacts[i].p, contacts[i].n, contacts[i].dist);
            func(b, set);
          }
        }
      };
      this.lock();
      this.activeShapes.query(bb, helper);
      this.staticShapes.query(bb, helper);
      this.unlock(true);
      return anyCollision;
    };
    Space.prototype.addPostStepCallback = function(func) {
      assertSoft(this.locked, "Adding a post-step callback when the space is not locked is unnecessary. Post-step callbacks will not called until the end of the next call to cpSpaceStep() or the next query.");
      this.postStepCallbacks.push(func);
    };
    Space.prototype.runPostStepCallbacks = function() {
      for (var i = 0; i < this.postStepCallbacks.length; i++) this.postStepCallbacks[i]();
      this.postStepCallbacks = [];
    };
    Space.prototype.lock = function() {
      this.locked++;
    };
    Space.prototype.unlock = function(runPostStep) {
      this.locked--;
      assert(this.locked >= 0, "Internal Error: Space lock underflow.");
      if (0 === this.locked && runPostStep) {
        var waking = this.rousedBodies;
        for (var i = 0; i < waking.length; i++) this.activateBody(waking[i]);
        waking.length = 0;
        this.runPostStepCallbacks();
      }
    };
    Space.prototype.makeCollideShapes = function() {
      var space_ = this;
      return function(a, b) {
        var space = space_;
        if (!(a.bb_l <= b.bb_r && b.bb_l <= a.bb_r && a.bb_b <= b.bb_t && b.bb_b <= a.bb_t) || a.body === b.body || a.group && a.group === b.group || !(a.layers & b.layers)) return;
        var handler = space.lookupHandler(a.collision_type, b.collision_type);
        var sensor = a.sensor || b.sensor;
        if (sensor && handler === defaultCollisionHandler) return;
        if (a.collisionCode > b.collisionCode) {
          var temp = a;
          a = b;
          b = temp;
        }
        var contacts = collideShapes(a, b);
        if (0 === contacts.length) return;
        var arbHash = hashPair(a.hashid, b.hashid);
        var arb = space.cachedArbiters[arbHash];
        arb || (arb = space.cachedArbiters[arbHash] = new Arbiter(a, b));
        arb.update(contacts, handler, a, b);
        "first coll" != arb.state || handler.begin(arb, space) || arb.ignore();
        if ("ignore" !== arb.state && handler.preSolve(arb, space) && !sensor) space.arbiters.push(arb); else {
          arb.contacts = null;
          "ignore" !== arb.state && (arb.state = "normal");
        }
        arb.stamp = space.stamp;
      };
    };
    Space.prototype.arbiterSetFilter = function(arb) {
      var ticks = this.stamp - arb.stamp;
      var a = arb.body_a, b = arb.body_b;
      if ((a.isStatic() || a.isSleeping()) && (b.isStatic() || b.isSleeping())) return true;
      if (ticks >= 1 && "cached" != arb.state) {
        arb.callSeparate(this);
        arb.state = "cached";
      }
      if (ticks >= this.collisionPersistence) {
        arb.contacts = null;
        return false;
      }
      return true;
    };
    var updateFunc = function(shape) {
      var body = shape.body;
      shape.update(body.p, body.rot);
    };
    Space.prototype.step = function(dt) {
      if (0 === dt) return;
      assert(0 === vzero.x && 0 === vzero.y, "vzero is invalid");
      this.stamp++;
      var prev_dt = this.curr_dt;
      this.curr_dt = dt;
      var i;
      var j;
      var hash;
      var bodies = this.bodies;
      var constraints = this.constraints;
      var arbiters = this.arbiters;
      for (i = 0; i < arbiters.length; i++) {
        var arb = arbiters[i];
        arb.state = "normal";
        arb.body_a.isSleeping() || arb.body_b.isSleeping() || arb.unthread();
      }
      arbiters.length = 0;
      this.lock();
      for (i = 0; i < bodies.length; i++) bodies[i].position_func(dt);
      this.activeShapes.each(updateFunc);
      this.activeShapes.reindexQuery(this.collideShapes);
      this.unlock(false);
      this.processComponents(dt);
      this.lock();
      for (hash in this.cachedArbiters) this.arbiterSetFilter(this.cachedArbiters[hash]) || delete this.cachedArbiters[hash];
      var slop = this.collisionSlop;
      var biasCoef = 1 - Math.pow(this.collisionBias, dt);
      for (i = 0; i < arbiters.length; i++) arbiters[i].preStep(dt, slop, biasCoef);
      for (i = 0; i < constraints.length; i++) {
        var constraint = constraints[i];
        constraint.preSolve(this);
        constraint.preStep(dt);
      }
      var damping = Math.pow(this.damping, dt);
      var gravity = this.gravity;
      for (i = 0; i < bodies.length; i++) bodies[i].velocity_func(gravity, damping, dt);
      var dt_coef = 0 === prev_dt ? 0 : dt / prev_dt;
      for (i = 0; i < arbiters.length; i++) arbiters[i].applyCachedImpulse(dt_coef);
      for (i = 0; i < constraints.length; i++) constraints[i].applyCachedImpulse(dt_coef);
      for (i = 0; i < this.iterations; i++) {
        for (j = 0; j < arbiters.length; j++) arbiters[j].applyImpulse();
        for (j = 0; j < constraints.length; j++) constraints[j].applyImpulse();
      }
      for (i = 0; i < constraints.length; i++) constraints[i].postSolve(this);
      for (i = 0; i < arbiters.length; i++) arbiters[i].handler.postSolve(arbiters[i], this);
      this.unlock(true);
    };
    var relative_velocity = function(a, b, r1, r2) {
      var v1_sumx = a.vx + -r1.y * a.w;
      var v1_sumy = a.vy + r1.x * a.w;
      var v2_sumx = b.vx + -r2.y * b.w;
      var v2_sumy = b.vy + r2.x * b.w;
      return new Vect(v2_sumx - v1_sumx, v2_sumy - v1_sumy);
    };
    var normal_relative_velocity = function(a, b, r1, r2, n) {
      var v1_sumx = a.vx + -r1.y * a.w;
      var v1_sumy = a.vy + r1.x * a.w;
      var v2_sumx = b.vx + -r2.y * b.w;
      var v2_sumy = b.vy + r2.x * b.w;
      return vdot2(v2_sumx - v1_sumx, v2_sumy - v1_sumy, n.x, n.y);
    };
    var apply_impulse = function(body, jx, jy, r) {
      body.vx += jx * body.m_inv;
      body.vy += jy * body.m_inv;
      body.w += body.i_inv * (r.x * jy - r.y * jx);
    };
    var apply_impulses = function(a, b, r1, r2, jx, jy) {
      apply_impulse(a, -jx, -jy, r1);
      apply_impulse(b, jx, jy, r2);
    };
    var apply_bias_impulse = function(body, jx, jy, r) {
      body.v_biasx += jx * body.m_inv;
      body.v_biasy += jy * body.m_inv;
      body.w_bias += body.i_inv * vcross2(r.x, r.y, jx, jy);
    };
    var k_scalar_body = function(body, r, n) {
      var rcn = vcross(r, n);
      return body.m_inv + body.i_inv * rcn * rcn;
    };
    var k_scalar = function(a, b, r1, r2, n) {
      var value = k_scalar_body(a, r1, n) + k_scalar_body(b, r2, n);
      assertSoft(0 !== value, "Unsolvable collision or constraint.");
      return value;
    };
    var k_tensor = function(a, b, r1, r2, k1, k2) {
      var k11, k12, k21, k22;
      var m_sum = a.m_inv + b.m_inv;
      k11 = m_sum;
      k12 = 0;
      k21 = 0;
      k22 = m_sum;
      var a_i_inv = a.i_inv;
      var r1xsq = r1.x * r1.x * a_i_inv;
      var r1ysq = r1.y * r1.y * a_i_inv;
      var r1nxy = -r1.x * r1.y * a_i_inv;
      k11 += r1ysq;
      k12 += r1nxy;
      k21 += r1nxy;
      k22 += r1xsq;
      var b_i_inv = b.i_inv;
      var r2xsq = r2.x * r2.x * b_i_inv;
      var r2ysq = r2.y * r2.y * b_i_inv;
      var r2nxy = -r2.x * r2.y * b_i_inv;
      k11 += r2ysq;
      k12 += r2nxy;
      k21 += r2nxy;
      k22 += r2xsq;
      var determinant = k11 * k22 - k12 * k21;
      assertSoft(0 !== determinant, "Unsolvable constraint.");
      var det_inv = 1 / determinant;
      k1.x = k22 * det_inv;
      k1.y = -k12 * det_inv;
      k2.x = -k21 * det_inv;
      k2.y = k11 * det_inv;
    };
    var mult_k = function(vr, k1, k2) {
      return new Vect(vdot(vr, k1), vdot(vr, k2));
    };
    var bias_coef = function(errorBias, dt) {
      return 1 - Math.pow(errorBias, dt);
    };
    var Constraint = cp.Constraint = function(a, b) {
      this.a = a;
      this.b = b;
      this.space = null;
      this.next_a = null;
      this.next_b = null;
      this.maxForce = Infinity;
      this.errorBias = Math.pow(.9, 60);
      this.maxBias = Infinity;
    };
    Constraint.prototype.activateBodies = function() {
      this.a && this.a.activate();
      this.b && this.b.activate();
    };
    Constraint.prototype.preStep = function(dt) {};
    Constraint.prototype.applyCachedImpulse = function(dt_coef) {};
    Constraint.prototype.applyImpulse = function() {};
    Constraint.prototype.getImpulse = function() {
      return 0;
    };
    Constraint.prototype.preSolve = function(space) {};
    Constraint.prototype.postSolve = function(space) {};
    Constraint.prototype.next = function(body) {
      return this.a === body ? this.next_a : this.next_b;
    };
    var PinJoint = cp.PinJoint = function(a, b, anchr1, anchr2) {
      Constraint.call(this, a, b);
      this.anchr1 = anchr1;
      this.anchr2 = anchr2;
      var p1 = a ? vadd(a.p, vrotate(anchr1, a.rot)) : anchr1;
      var p2 = b ? vadd(b.p, vrotate(anchr2, b.rot)) : anchr2;
      this.dist = vlength(vsub(p2, p1));
      assertSoft(this.dist > 0, "You created a 0 length pin joint. A pivot joint will be much more stable.");
      this.r1 = this.r2 = null;
      this.n = null;
      this.nMass = 0;
      this.jnAcc = this.jnMax = 0;
      this.bias = 0;
    };
    PinJoint.prototype = Object.create(Constraint.prototype);
    PinJoint.prototype.preStep = function(dt) {
      var a = this.a;
      var b = this.b;
      this.r1 = vrotate(this.anchr1, a.rot);
      this.r2 = vrotate(this.anchr2, b.rot);
      var delta = vsub(vadd(b.p, this.r2), vadd(a.p, this.r1));
      var dist = vlength(delta);
      this.n = vmult(delta, 1 / (dist || Infinity));
      this.nMass = 1 / k_scalar(a, b, this.r1, this.r2, this.n);
      var maxBias = this.maxBias;
      this.bias = clamp(-bias_coef(this.errorBias, dt) * (dist - this.dist) / dt, -maxBias, maxBias);
      this.jnMax = this.maxForce * dt;
    };
    PinJoint.prototype.applyCachedImpulse = function(dt_coef) {
      var j = vmult(this.n, this.jnAcc * dt_coef);
      apply_impulses(this.a, this.b, this.r1, this.r2, j.x, j.y);
    };
    PinJoint.prototype.applyImpulse = function() {
      var a = this.a;
      var b = this.b;
      var n = this.n;
      var vrn = normal_relative_velocity(a, b, this.r1, this.r2, n);
      var jn = (this.bias - vrn) * this.nMass;
      var jnOld = this.jnAcc;
      this.jnAcc = clamp(jnOld + jn, -this.jnMax, this.jnMax);
      jn = this.jnAcc - jnOld;
      apply_impulses(a, b, this.r1, this.r2, n.x * jn, n.y * jn);
    };
    PinJoint.prototype.getImpulse = function() {
      return Math.abs(this.jnAcc);
    };
    var SlideJoint = cp.SlideJoint = function(a, b, anchr1, anchr2, min, max) {
      Constraint.call(this, a, b);
      this.anchr1 = anchr1;
      this.anchr2 = anchr2;
      this.min = min;
      this.max = max;
      this.r1 = this.r2 = this.n = null;
      this.nMass = 0;
      this.jnAcc = this.jnMax = 0;
      this.bias = 0;
    };
    SlideJoint.prototype = Object.create(Constraint.prototype);
    SlideJoint.prototype.preStep = function(dt) {
      var a = this.a;
      var b = this.b;
      this.r1 = vrotate(this.anchr1, a.rot);
      this.r2 = vrotate(this.anchr2, b.rot);
      var delta = vsub(vadd(b.p, this.r2), vadd(a.p, this.r1));
      var dist = vlength(delta);
      var pdist = 0;
      if (dist > this.max) {
        pdist = dist - this.max;
        this.n = vnormalize_safe(delta);
      } else if (dist < this.min) {
        pdist = this.min - dist;
        this.n = vneg(vnormalize_safe(delta));
      } else {
        this.n = vzero;
        this.jnAcc = 0;
      }
      this.nMass = 1 / k_scalar(a, b, this.r1, this.r2, this.n);
      var maxBias = this.maxBias;
      this.bias = clamp(-bias_coef(this.errorBias, dt) * pdist / dt, -maxBias, maxBias);
      this.jnMax = this.maxForce * dt;
    };
    SlideJoint.prototype.applyCachedImpulse = function(dt_coef) {
      var jn = this.jnAcc * dt_coef;
      apply_impulses(this.a, this.b, this.r1, this.r2, this.n.x * jn, this.n.y * jn);
    };
    SlideJoint.prototype.applyImpulse = function() {
      if (0 === this.n.x && 0 === this.n.y) return;
      var a = this.a;
      var b = this.b;
      var n = this.n;
      var r1 = this.r1;
      var r2 = this.r2;
      var vr = relative_velocity(a, b, r1, r2);
      var vrn = vdot(vr, n);
      var jn = (this.bias - vrn) * this.nMass;
      var jnOld = this.jnAcc;
      this.jnAcc = clamp(jnOld + jn, -this.jnMax, 0);
      jn = this.jnAcc - jnOld;
      apply_impulses(a, b, this.r1, this.r2, n.x * jn, n.y * jn);
    };
    SlideJoint.prototype.getImpulse = function() {
      return Math.abs(this.jnAcc);
    };
    var PivotJoint = cp.PivotJoint = function(a, b, anchr1, anchr2) {
      Constraint.call(this, a, b);
      if ("undefined" === typeof anchr2) {
        var pivot = anchr1;
        anchr1 = a ? a.world2Local(pivot) : pivot;
        anchr2 = b ? b.world2Local(pivot) : pivot;
      }
      this.anchr1 = anchr1;
      this.anchr2 = anchr2;
      this.r1 = this.r2 = vzero;
      this.k1 = new Vect(0, 0);
      this.k2 = new Vect(0, 0);
      this.jAcc = vzero;
      this.jMaxLen = 0;
      this.bias = vzero;
    };
    PivotJoint.prototype = Object.create(Constraint.prototype);
    PivotJoint.prototype.preStep = function(dt) {
      var a = this.a;
      var b = this.b;
      this.r1 = vrotate(this.anchr1, a.rot);
      this.r2 = vrotate(this.anchr2, b.rot);
      k_tensor(a, b, this.r1, this.r2, this.k1, this.k2);
      this.jMaxLen = this.maxForce * dt;
      var delta = vsub(vadd(b.p, this.r2), vadd(a.p, this.r1));
      this.bias = vclamp(vmult(delta, -bias_coef(this.errorBias, dt) / dt), this.maxBias);
    };
    PivotJoint.prototype.applyCachedImpulse = function(dt_coef) {
      apply_impulses(this.a, this.b, this.r1, this.r2, this.jAcc.x * dt_coef, this.jAcc.y * dt_coef);
    };
    PivotJoint.prototype.applyImpulse = function() {
      var a = this.a;
      var b = this.b;
      var r1 = this.r1;
      var r2 = this.r2;
      var vr = relative_velocity(a, b, r1, r2);
      var j = mult_k(vsub(this.bias, vr), this.k1, this.k2);
      var jOld = this.jAcc;
      this.jAcc = vclamp(vadd(this.jAcc, j), this.jMaxLen);
      apply_impulses(a, b, this.r1, this.r2, this.jAcc.x - jOld.x, this.jAcc.y - jOld.y);
    };
    PivotJoint.prototype.getImpulse = function() {
      return vlength(this.jAcc);
    };
    var GrooveJoint = cp.GrooveJoint = function(a, b, groove_a, groove_b, anchr2) {
      Constraint.call(this, a, b);
      this.grv_a = groove_a;
      this.grv_b = groove_b;
      this.grv_n = vperp(vnormalize(vsub(groove_b, groove_a)));
      this.anchr2 = anchr2;
      this.grv_tn = null;
      this.clamp = 0;
      this.r1 = this.r2 = null;
      this.k1 = new Vect(0, 0);
      this.k2 = new Vect(0, 0);
      this.jAcc = vzero;
      this.jMaxLen = 0;
      this.bias = null;
    };
    GrooveJoint.prototype = Object.create(Constraint.prototype);
    GrooveJoint.prototype.preStep = function(dt) {
      var a = this.a;
      var b = this.b;
      var ta = a.local2World(this.grv_a);
      var tb = a.local2World(this.grv_b);
      var n = vrotate(this.grv_n, a.rot);
      var d = vdot(ta, n);
      this.grv_tn = n;
      this.r2 = vrotate(this.anchr2, b.rot);
      var td = vcross(vadd(b.p, this.r2), n);
      if (td <= vcross(ta, n)) {
        this.clamp = 1;
        this.r1 = vsub(ta, a.p);
      } else if (td >= vcross(tb, n)) {
        this.clamp = -1;
        this.r1 = vsub(tb, a.p);
      } else {
        this.clamp = 0;
        this.r1 = vsub(vadd(vmult(vperp(n), -td), vmult(n, d)), a.p);
      }
      k_tensor(a, b, this.r1, this.r2, this.k1, this.k2);
      this.jMaxLen = this.maxForce * dt;
      var delta = vsub(vadd(b.p, this.r2), vadd(a.p, this.r1));
      this.bias = vclamp(vmult(delta, -bias_coef(this.errorBias, dt) / dt), this.maxBias);
    };
    GrooveJoint.prototype.applyCachedImpulse = function(dt_coef) {
      apply_impulses(this.a, this.b, this.r1, this.r2, this.jAcc.x * dt_coef, this.jAcc.y * dt_coef);
    };
    GrooveJoint.prototype.grooveConstrain = function(j) {
      var n = this.grv_tn;
      var jClamp = this.clamp * vcross(j, n) > 0 ? j : vproject(j, n);
      return vclamp(jClamp, this.jMaxLen);
    };
    GrooveJoint.prototype.applyImpulse = function() {
      var a = this.a;
      var b = this.b;
      var r1 = this.r1;
      var r2 = this.r2;
      var vr = relative_velocity(a, b, r1, r2);
      var j = mult_k(vsub(this.bias, vr), this.k1, this.k2);
      var jOld = this.jAcc;
      this.jAcc = this.grooveConstrain(vadd(jOld, j));
      apply_impulses(a, b, this.r1, this.r2, this.jAcc.x - jOld.x, this.jAcc.y - jOld.y);
    };
    GrooveJoint.prototype.getImpulse = function() {
      return vlength(this.jAcc);
    };
    GrooveJoint.prototype.setGrooveA = function(value) {
      this.grv_a = value;
      this.grv_n = vperp(vnormalize(vsub(this.grv_b, value)));
      this.activateBodies();
    };
    GrooveJoint.prototype.setGrooveB = function(value) {
      this.grv_b = value;
      this.grv_n = vperp(vnormalize(vsub(value, this.grv_a)));
      this.activateBodies();
    };
    var defaultSpringForce = function(spring, dist) {
      return (spring.restLength - dist) * spring.stiffness;
    };
    var DampedSpring = cp.DampedSpring = function(a, b, anchr1, anchr2, restLength, stiffness, damping) {
      Constraint.call(this, a, b);
      this.anchr1 = anchr1;
      this.anchr2 = anchr2;
      this.restLength = restLength;
      this.stiffness = stiffness;
      this.damping = damping;
      this.springForceFunc = defaultSpringForce;
      this.target_vrn = this.v_coef = 0;
      this.r1 = this.r2 = null;
      this.nMass = 0;
      this.n = null;
    };
    DampedSpring.prototype = Object.create(Constraint.prototype);
    DampedSpring.prototype.preStep = function(dt) {
      var a = this.a;
      var b = this.b;
      this.r1 = vrotate(this.anchr1, a.rot);
      this.r2 = vrotate(this.anchr2, b.rot);
      var delta = vsub(vadd(b.p, this.r2), vadd(a.p, this.r1));
      var dist = vlength(delta);
      this.n = vmult(delta, 1 / (dist || Infinity));
      var k = k_scalar(a, b, this.r1, this.r2, this.n);
      assertSoft(0 !== k, "Unsolvable this.");
      this.nMass = 1 / k;
      this.target_vrn = 0;
      this.v_coef = 1 - Math.exp(-this.damping * dt * k);
      var f_spring = this.springForceFunc(this, dist);
      apply_impulses(a, b, this.r1, this.r2, this.n.x * f_spring * dt, this.n.y * f_spring * dt);
    };
    DampedSpring.prototype.applyCachedImpulse = function(dt_coef) {};
    DampedSpring.prototype.applyImpulse = function() {
      var a = this.a;
      var b = this.b;
      var n = this.n;
      var r1 = this.r1;
      var r2 = this.r2;
      var vrn = normal_relative_velocity(a, b, r1, r2, n);
      var v_damp = (this.target_vrn - vrn) * this.v_coef;
      this.target_vrn = vrn + v_damp;
      v_damp *= this.nMass;
      apply_impulses(a, b, this.r1, this.r2, this.n.x * v_damp, this.n.y * v_damp);
    };
    DampedSpring.prototype.getImpulse = function() {
      return 0;
    };
    var defaultSpringTorque = function(spring, relativeAngle) {
      return (relativeAngle - spring.restAngle) * spring.stiffness;
    };
    var DampedRotarySpring = cp.DampedRotarySpring = function(a, b, restAngle, stiffness, damping) {
      Constraint.call(this, a, b);
      this.restAngle = restAngle;
      this.stiffness = stiffness;
      this.damping = damping;
      this.springTorqueFunc = defaultSpringTorque;
      this.target_wrn = 0;
      this.w_coef = 0;
      this.iSum = 0;
    };
    DampedRotarySpring.prototype = Object.create(Constraint.prototype);
    DampedRotarySpring.prototype.preStep = function(dt) {
      var a = this.a;
      var b = this.b;
      var moment = a.i_inv + b.i_inv;
      assertSoft(0 !== moment, "Unsolvable spring.");
      this.iSum = 1 / moment;
      this.w_coef = 1 - Math.exp(-this.damping * dt * moment);
      this.target_wrn = 0;
      var j_spring = this.springTorqueFunc(this, a.a - b.a) * dt;
      a.w -= j_spring * a.i_inv;
      b.w += j_spring * b.i_inv;
    };
    DampedRotarySpring.prototype.applyImpulse = function() {
      var a = this.a;
      var b = this.b;
      var wrn = a.w - b.w;
      var w_damp = (this.target_wrn - wrn) * this.w_coef;
      this.target_wrn = wrn + w_damp;
      var j_damp = w_damp * this.iSum;
      a.w += j_damp * a.i_inv;
      b.w -= j_damp * b.i_inv;
    };
    var RotaryLimitJoint = cp.RotaryLimitJoint = function(a, b, min, max) {
      Constraint.call(this, a, b);
      this.min = min;
      this.max = max;
      this.jAcc = 0;
      this.iSum = this.bias = this.jMax = 0;
    };
    RotaryLimitJoint.prototype = Object.create(Constraint.prototype);
    RotaryLimitJoint.prototype.preStep = function(dt) {
      var a = this.a;
      var b = this.b;
      var dist = b.a - a.a;
      var pdist = 0;
      dist > this.max ? pdist = this.max - dist : dist < this.min && (pdist = this.min - dist);
      this.iSum = 1 / (1 / a.i + 1 / b.i);
      var maxBias = this.maxBias;
      this.bias = clamp(-bias_coef(this.errorBias, dt) * pdist / dt, -maxBias, maxBias);
      this.jMax = this.maxForce * dt;
      this.bias || (this.jAcc = 0);
    };
    RotaryLimitJoint.prototype.applyCachedImpulse = function(dt_coef) {
      var a = this.a;
      var b = this.b;
      var j = this.jAcc * dt_coef;
      a.w -= j * a.i_inv;
      b.w += j * b.i_inv;
    };
    RotaryLimitJoint.prototype.applyImpulse = function() {
      if (!this.bias) return;
      var a = this.a;
      var b = this.b;
      var wr = b.w - a.w;
      var j = -(this.bias + wr) * this.iSum;
      var jOld = this.jAcc;
      this.bias < 0 ? this.jAcc = clamp(jOld + j, 0, this.jMax) : this.jAcc = clamp(jOld + j, -this.jMax, 0);
      j = this.jAcc - jOld;
      a.w -= j * a.i_inv;
      b.w += j * b.i_inv;
    };
    RotaryLimitJoint.prototype.getImpulse = function() {
      return Math.abs(joint.jAcc);
    };
    var RatchetJoint = cp.RatchetJoint = function(a, b, phase, ratchet) {
      Constraint.call(this, a, b);
      this.angle = 0;
      this.phase = phase;
      this.ratchet = ratchet;
      this.angle = (b ? b.a : 0) - (a ? a.a : 0);
      this.iSum = this.bias = this.jAcc = this.jMax = 0;
    };
    RatchetJoint.prototype = Object.create(Constraint.prototype);
    RatchetJoint.prototype.preStep = function(dt) {
      var a = this.a;
      var b = this.b;
      var angle = this.angle;
      var phase = this.phase;
      var ratchet = this.ratchet;
      var delta = b.a - a.a;
      var diff = angle - delta;
      var pdist = 0;
      diff * ratchet > 0 ? pdist = diff : this.angle = Math.floor((delta - phase) / ratchet) * ratchet + phase;
      this.iSum = 1 / (a.i_inv + b.i_inv);
      var maxBias = this.maxBias;
      this.bias = clamp(-bias_coef(this.errorBias, dt) * pdist / dt, -maxBias, maxBias);
      this.jMax = this.maxForce * dt;
      this.bias || (this.jAcc = 0);
    };
    RatchetJoint.prototype.applyCachedImpulse = function(dt_coef) {
      var a = this.a;
      var b = this.b;
      var j = this.jAcc * dt_coef;
      a.w -= j * a.i_inv;
      b.w += j * b.i_inv;
    };
    RatchetJoint.prototype.applyImpulse = function() {
      if (!this.bias) return;
      var a = this.a;
      var b = this.b;
      var wr = b.w - a.w;
      var ratchet = this.ratchet;
      var j = -(this.bias + wr) * this.iSum;
      var jOld = this.jAcc;
      this.jAcc = clamp((jOld + j) * ratchet, 0, this.jMax * Math.abs(ratchet)) / ratchet;
      j = this.jAcc - jOld;
      a.w -= j * a.i_inv;
      b.w += j * b.i_inv;
    };
    RatchetJoint.prototype.getImpulse = function(joint) {
      return Math.abs(joint.jAcc);
    };
    var GearJoint = cp.GearJoint = function(a, b, phase, ratio) {
      Constraint.call(this, a, b);
      this.phase = phase;
      this.ratio = ratio;
      this.ratio_inv = 1 / ratio;
      this.jAcc = 0;
      this.iSum = this.bias = this.jMax = 0;
    };
    GearJoint.prototype = Object.create(Constraint.prototype);
    GearJoint.prototype.preStep = function(dt) {
      var a = this.a;
      var b = this.b;
      this.iSum = 1 / (a.i_inv * this.ratio_inv + this.ratio * b.i_inv);
      var maxBias = this.maxBias;
      this.bias = clamp(-bias_coef(this.errorBias, dt) * (b.a * this.ratio - a.a - this.phase) / dt, -maxBias, maxBias);
      this.jMax = this.maxForce * dt;
    };
    GearJoint.prototype.applyCachedImpulse = function(dt_coef) {
      var a = this.a;
      var b = this.b;
      var j = this.jAcc * dt_coef;
      a.w -= j * a.i_inv * this.ratio_inv;
      b.w += j * b.i_inv;
    };
    GearJoint.prototype.applyImpulse = function() {
      var a = this.a;
      var b = this.b;
      var wr = b.w * this.ratio - a.w;
      var j = (this.bias - wr) * this.iSum;
      var jOld = this.jAcc;
      this.jAcc = clamp(jOld + j, -this.jMax, this.jMax);
      j = this.jAcc - jOld;
      a.w -= j * a.i_inv * this.ratio_inv;
      b.w += j * b.i_inv;
    };
    GearJoint.prototype.getImpulse = function() {
      return Math.abs(this.jAcc);
    };
    GearJoint.prototype.setRatio = function(value) {
      this.ratio = value;
      this.ratio_inv = 1 / value;
      this.activateBodies();
    };
    var SimpleMotor = cp.SimpleMotor = function(a, b, rate) {
      Constraint.call(this, a, b);
      this.rate = rate;
      this.jAcc = 0;
      this.iSum = this.jMax = 0;
    };
    SimpleMotor.prototype = Object.create(Constraint.prototype);
    SimpleMotor.prototype.preStep = function(dt) {
      this.iSum = 1 / (this.a.i_inv + this.b.i_inv);
      this.jMax = this.maxForce * dt;
    };
    SimpleMotor.prototype.applyCachedImpulse = function(dt_coef) {
      var a = this.a;
      var b = this.b;
      var j = this.jAcc * dt_coef;
      a.w -= j * a.i_inv;
      b.w += j * b.i_inv;
    };
    SimpleMotor.prototype.applyImpulse = function() {
      var a = this.a;
      var b = this.b;
      var wr = b.w - a.w + this.rate;
      var j = -wr * this.iSum;
      var jOld = this.jAcc;
      this.jAcc = clamp(jOld + j, -this.jMax, this.jMax);
      j = this.jAcc - jOld;
      a.w -= j * a.i_inv;
      b.w += j * b.i_inv;
    };
    SimpleMotor.prototype.getImpulse = function() {
      return Math.abs(this.jAcc);
    };
  }), {} ],
  311: [ (function(require, module, exports) {
    module.exports = (function() {
      "use strict";
      function t() {
        "undefined" === typeof window.performance && (window.performance = {});
        if (!window.performance.now) {
          var t = Date.now();
          performance.timing && performance.timing.navigationStart && (t = performance.timing.navigationStart);
          window.performance.now = function e() {
            return Date.now() - t;
          };
        }
        window.performance.mark || (window.performance.mark = function() {});
        window.performance.measure || (window.performance.measure = function() {});
        window.performance.memory || (window.performance.memory = {
          usedJSHeapSize: 0,
          totalJSHeapSize: 0
        });
      }
      var e = Math.round(window.devicePixelRatio || 1);
      var i = function t(e, i) {
        this._color = i || "#666";
        this._canvas = document.createElement("canvas");
        this._ctx = this._canvas.getContext("2d");
        this._canvas.className = "pstats-canvas";
        e.appendChild(this._canvas);
      };
      i.prototype.init = function t(i, a) {
        var n = i * e;
        var s = a * e;
        this._canvas.width = n;
        this._canvas.height = s;
        this._canvas.style.width = i + "px";
        this._canvas.style.height = a + "px";
        this._ctx.globalAlpha = 1;
        this._ctx.fillStyle = "#444";
        this._ctx.fillRect(0, 0, n, s);
      };
      var a = Math.round(window.devicePixelRatio || 1);
      var n = (function(t) {
        function e(e, i) {
          t.call(this, e, i);
          this._current = 0;
          this._max = 0;
        }
        t && (e.__proto__ = t);
        e.prototype = Object.create(t && t.prototype);
        e.prototype.constructor = e;
        e.prototype.draw = function t(e, i) {
          var n = this._canvas.width;
          var s = this._canvas.height;
          this._current += .1 * (e - this._current);
          this._max *= .99;
          this._current > this._max && (this._max = this._current);
          var o = Math.round((1 - this._current / this._max) * s);
          this._ctx.globalAlpha = 1;
          this._ctx.drawImage(this._canvas, a, 0, n - a, s, 0, 0, n - a, s);
          if (i) {
            this._ctx.fillStyle = "#444";
            this._ctx.fillRect(n - a, 0, a, s);
            this._ctx.fillStyle = "#b70000";
            this._ctx.fillRect(n - a, o, a, s - o);
            this._ctx.globalAlpha = .5;
            this._ctx.fillStyle = "#fff";
            this._ctx.fillRect(n - a, o, a, a);
          } else {
            this._ctx.fillStyle = "#444";
            this._ctx.fillRect(n - a, 0, a, s);
            this._ctx.fillStyle = this._color;
            this._ctx.fillRect(n - a, o, a, s - o);
            this._ctx.globalAlpha = .5;
            this._ctx.fillStyle = "#fff";
            this._ctx.fillRect(n - a, o, a, a);
          }
        };
        return e;
      })(i);
      var s = Math.round(window.devicePixelRatio || 1);
      var o = (function(t) {
        function e(e, i) {
          t.call(this, e, i);
          this._threshold = 0;
          this._canvas2 = document.createElement("canvas");
          this._ctx2 = this._canvas2.getContext("2d");
        }
        t && (e.__proto__ = t);
        e.prototype = Object.create(t && t.prototype);
        e.prototype.constructor = e;
        e.prototype.init = function e(i, a) {
          t.prototype.init.call(this, i, a);
          var n = i * s;
          var o = a * s;
          this._canvas2.width = n;
          this._canvas2.height = o;
          this._canvas2.style.width = i + "px";
          this._canvas2.style.height = a + "px";
          this._ctx2.globalAlpha = 1;
          this._ctx2.fillStyle = "#444";
          this._ctx2.fillRect(0, 0, n, o);
        };
        e.prototype.draw = function t(e, i) {
          var a = this._canvas.width;
          var n = this._canvas.height;
          this._ctx.globalAlpha = 1;
          this._ctx2.globalAlpha = 1;
          if (e > this._threshold) {
            var o = (e - e % n) / n;
            var r = n * (o + 1);
            var l = this._threshold;
            this._threshold = r;
            var c = l / r;
            this._ctx2.drawImage(this._canvas, 0, 0);
            this._ctx.fillStyle = "#444";
            this._ctx.fillRect(0, 0, a, n);
            this._ctx.drawImage(this._canvas2, s, 0, a - s, n, 0, Math.round((1 - c) * n), a - s, n);
          } else this._ctx.drawImage(this._canvas, s, 0, a - s, n, 0, 0, a - s, n);
          var h = Math.round(n * (1 - e / this._threshold));
          if (i) {
            this._ctx.fillStyle = "#444";
            this._ctx.fillRect(a - s, 0, s, n);
            this._ctx.fillStyle = "#b70000";
            this._ctx.fillRect(a - s, h, s, n - h);
            this._ctx.globalAlpha = .5;
            this._ctx.fillStyle = "#fff";
            this._ctx.fillRect(a - s, h, s, s);
          } else {
            this._ctx.fillStyle = "#444";
            this._ctx.fillRect(a - s, 0, s, n);
            this._ctx.fillStyle = this._color;
            this._ctx.fillRect(a - s, h, s, n - h);
            this._ctx.globalAlpha = .5;
            this._ctx.fillStyle = "#fff";
            this._ctx.fillRect(a - s, h, s, s);
          }
        };
        return e;
      })(i);
      var r = Math.round(window.devicePixelRatio || 1);
      var l = (function(t) {
        function e(e, i, a, n) {
          t.call(this, e, i);
          this._min = a;
          this._max = n;
        }
        t && (e.__proto__ = t);
        e.prototype = Object.create(t && t.prototype);
        e.prototype.constructor = e;
        e.prototype.draw = function t(e, i) {
          var a = this._canvas.width;
          var n = this._canvas.height;
          var s = (e - this._min) / (this._max - this._min);
          var o = Math.round((1 - s) * n);
          this._ctx.globalAlpha = 1;
          this._ctx.drawImage(this._canvas, r, 0, a - r, n, 0, 0, a - r, n);
          if (i) {
            this._ctx.fillStyle = "#444";
            this._ctx.fillRect(a - r, 0, r, n);
            this._ctx.fillStyle = "#b70000";
            this._ctx.fillRect(a - r, o, r, n - o);
            this._ctx.globalAlpha = .5;
            this._ctx.fillStyle = "#fff";
            this._ctx.fillRect(a - r, o, r, r);
          } else {
            this._ctx.fillStyle = "#444";
            this._ctx.fillRect(a - r, 0, r, n);
            this._ctx.fillStyle = this._color;
            this._ctx.fillRect(a - r, o, r, n - o);
            this._ctx.globalAlpha = .5;
            this._ctx.fillStyle = "#fff";
            this._ctx.fillRect(a - r, o, r, r);
          }
        };
        return e;
      })(i);
      var c = Math.round(window.devicePixelRatio || 1);
      var h = function t(e, i) {
        this._colors = i;
        this._canvas = document.createElement("canvas");
        this._ctx = this._canvas.getContext("2d");
        this._canvas.className = "pstats-canvas";
        e.appendChild(this._canvas);
      };
      h.prototype.init = function t(e, i, a) {
        var n = e * c;
        var s = i * c;
        this._canvas.width = n;
        this._canvas.height = s * a;
        this._canvas.style.width = e + "px";
        this._canvas.style.height = i * a + "px";
        this._ctx.globalAlpha = 1;
        this._ctx.fillStyle = "#444";
        this._ctx.fillRect(0, 0, n, s * a);
      };
      h.prototype.draw = function t(e) {
        var i = this;
        var a = this._canvas.width;
        var n = this._canvas.height;
        this._ctx.globalAlpha = 1;
        this._ctx.drawImage(this._canvas, c, 0, a - c, n, 0, 0, a - c, n);
        var s = 0;
        for (var o = 0; o < e.length; ++o) {
          var r = e[o] * n;
          i._ctx.fillStyle = i._colors[o];
          i._ctx.fillRect(a - c, s, c, r);
          s += r;
        }
      };
      var p = function t(e, i) {
        this._id = e;
        this._opts = i || {};
        this._value = 0;
        this._total = 0;
        this._averageValue = 0;
        this._accumValue = 0;
        this._accumSamples = 0;
        this._accumStart = window.performance.now();
      };
      var _ = {
        value: {}
      };
      p.prototype._average = function t(e) {
        if (this._opts.average) {
          this._accumValue += e;
          ++this._accumSamples;
          var i = performance.now();
          if (i - this._accumStart >= this._opts.average) {
            this._averageValue = this._accumValue / this._accumSamples;
            this._accumValue = 0;
            this._accumStart = i;
            this._accumSamples = 0;
          }
        }
      };
      _.value.get = function() {
        return this._value;
      };
      _.value.set = function(t) {
        this._value = t;
      };
      p.prototype.sample = function t() {
        this._average(this._value);
      };
      p.prototype.human = function t() {
        var e = this._opts.average ? this._averageValue : this._value;
        return Math.round(100 * e) / 100;
      };
      p.prototype.alarm = function t() {
        return this._opts.below && this._value < this._opts.below || this._opts.over && this._value > this._opts.over;
      };
      Object.defineProperties(p.prototype, _);
      var f = (function(t) {
        function e(e, i) {
          t.call(this, e, i);
          this._time = window.performance.now();
        }
        t && (e.__proto__ = t);
        e.prototype = Object.create(t && t.prototype);
        e.prototype.constructor = e;
        e.prototype.start = function t() {
          this._time = window.performance.now();
        };
        e.prototype.end = function t() {
          this._value = window.performance.now() - this._time;
          this._average(this._value);
        };
        e.prototype.tick = function t() {
          this.end();
          this.start();
        };
        e.prototype.frame = function t() {
          var e = window.performance.now();
          var i = e - this._time;
          this._total++;
          var a = this._opts.average || 1e3;
          if (i > a) {
            this._value = 1e3 * this._total / i;
            this._total = 0;
            this._time = e;
            this._average(this._value);
          }
        };
        return e;
      })(p);
      var u = Math.log(1024);
      var v = [ "Bytes", "KB", "MB", "GB", "TB" ];
      function d(t) {
        var e = 100;
        var i = Math.floor(Math.log(t) / u);
        if (0 === t) return "n/a";
        return Math.round(t * e / Math.pow(1024, i)) / e + " " + v[i];
      }
      var m = (function(t) {
        function e(e, i, a) {
          t.call(this, i, a);
          this._stats = e;
          this._start = 0;
          0 === a.extension.indexOf("memory.") && (this._field = a.extension.substring(7));
        }
        t && (e.__proto__ = t);
        e.prototype = Object.create(t && t.prototype);
        e.prototype.constructor = e;
        e.prototype.snapshot = function t() {
          this._value = this._stats[this._field];
        };
        e.prototype.start = function t() {
          this._start = this._stats[this._field];
        };
        e.prototype.end = function t() {
          this._value = this._stats[this._field] - this._start;
        };
        e.prototype.human = function e() {
          return d(t.prototype.human.call(this));
        };
        return e;
      })(p);
      var x = function t() {
        var e = window.performance.memory;
        0 === e.totalJSHeapSize && console.warn("totalJSHeapSize === 0, performance.memory is only available in Chrome.");
        this._used = 0;
        this._total = 0;
        this._lastUsed = 0;
      };
      var w = {
        alarm: {},
        used: {},
        total: {}
      };
      x.prototype.tick = function t() {
        this._lastUsed = this._used;
        this._used = window.performance.memory.usedJSHeapSize;
        this._total = window.performance.memory.totalJSHeapSize;
      };
      w.alarm.get = function() {
        return this._used - this._lastUsed < 0;
      };
      w.used.get = function() {
        return window.performance.memory.usedJSHeapSize;
      };
      w.total.get = function() {
        return this._total;
      };
      x.prototype.counter = function t(e, i) {
        return new m(this, e, i);
      };
      Object.defineProperties(x.prototype, w);
      var y = {
        memory: x
      };
      var g = 100;
      var b = 10;
      var S = "\n  .pstats {\n    position: fixed;\n    z-index: 9999;\n\n    padding: 5px;\n    width: " + (g + 150) + "px;\n    right: 5px;\n    bottom: 5px;\n\n    font-size: 10px;\n    font-family: 'Roboto Condensed', tahoma, sans-serif;\n    overflow: hidden;\n    user-select: none;\n    cursor: default;\n\n    background: #222;\n    border-radius: 3px;\n  }\n\n  .pstats-container {\n    display: block;\n    position: relative;\n    color: #888;\n    white-space: nowrap;\n  }\n\n  .pstats-item {\n    position: absolute;\n    width: 250px;\n    height: 12px;\n    left: 0px;\n  }\n\n  .pstats-label {\n    position: absolute;\n    width: 150px;\n    height: 12px;\n    text-align: left;\n    transition: background 0.3s;\n  }\n\n  .pstats-label.alarm {\n    color: #ccc;\n    background: #800;\n\n    transition: background 0s;\n  }\n\n  .pstats-counter-id {\n    position: absolute;\n    width: 90px;\n    left: 0px;\n  }\n\n  .pstats-counter-value {\n    position: absolute;\n    width: 60px;\n    left: 90px;\n    text-align: right;\n  }\n\n  .pstats-canvas {\n    display: block;\n    position: absolute;\n    right: 0px;\n    top: 1px;\n  }\n\n  .pstats-fraction {\n    position: absolute;\n    width: 250px;\n    left: 0px;\n  }\n\n  .pstats-legend {\n    position: absolute;\n    width: 150px;\n\n    text-align: right;\n  }\n\n  .pstats-legend > span {\n    position: absolute;\n    right: 0px;\n  }\n";
      var R = document.createElement("style");
      R.type = "text/css";
      R.textContent = S;
      document.head.appendChild(R);
      var C = function t(e, i) {
        var a = this;
        i = i || {};
        this._showGraph = void 0 === i.showGraph || i._showGraph;
        this._values = i.values || {};
        this._fractions = i.fractions || [];
        this._id2counter = {};
        this._id2item = {};
        this._name2extStats = {};
        if (i.css) {
          var s = document.createElement("style");
          s.type = "text/css";
          s.textContent = i.css;
          document.head.appendChild(s);
        }
        if (i.extensions) for (var r = 0; r < i.extensions.length; ++r) {
          var c = i.extensions[r];
          var p = y[c];
          if (!p) {
            console.warn("Can not find extensions " + c + ", please register your extension via pstats.register().");
            continue;
          }
          a._name2extStats[c] = new p();
        }
        this._root = document.createElement("div");
        this._root.className = "pstats";
        var _ = document.createElement("div");
        _.className = "pstats-container";
        this._root.appendChild(_);
        var f = 0;
        for (var u in a._values) {
          var v = a._values[u];
          var d = document.createElement("div");
          d.className = "pstats-item";
          var m = document.createElement("div");
          m.className = "pstats-label";
          var x = document.createElement("span");
          x.className = "pstats-counter-id";
          x.textContent = v.desc || u;
          var w = document.createElement("div");
          w.className = "pstats-counter-value";
          var S = document.createTextNode("");
          S.nodeValue = "0";
          m.appendChild(x);
          m.appendChild(w);
          w.appendChild(S);
          d.appendChild(m);
          var R = void 0;
          if (a._showGraph) {
            R = void 0 !== v.min || void 0 !== v.max ? new l(d, v.color, v.min || 0, v.max || 9999) : v.threshold ? new o(d, v.color) : new n(d, v.color);
            R.init(g - 5, b);
          }
          a._id2item[u] = {
            label: m,
            valueText: S,
            graph: R
          };
          d.style.top = f + "px";
          _.appendChild(d);
          f += 12;
        }
        if (this._showGraph && i.fractions) for (var C = 0; C < i.fractions.length; ++C) {
          var M = i.fractions[C];
          var A = M.steps;
          var E = A.length * b + 2;
          M.colors = M.colors || [ "#850700", "#c74900", "#fcb300", "#284280", "#4c7c0c" ];
          var k = document.createElement("div");
          k.className = "pstats-fraction";
          var N = document.createElement("div");
          N.className = "pstats-legend";
          N.style.height = E + "px";
          for (var z = 0; z < A.length; ++z) {
            var G = document.createElement("span");
            G.textContent = A[z];
            G.style.color = M.colors[z];
            G.style.top = z * b + "px";
            N.appendChild(G);
          }
          k.appendChild(N);
          k.style.height = E + "px";
          k.style.top = f + "px";
          var O = new h(k, M.colors);
          O.init(g - 5, b, A.length);
          M.graph = O;
          M.values = new Array(A.length);
          _.appendChild(k);
          f += A.length * b + 2;
        }
        _.style.height = f + "px";
        this._root.style.height = f + "px";
        this._showGraph || (this._root.style.width = "150px");
        e.appendChild(this._root);
      };
      C.prototype.item = function t(e) {
        if (!e) return null;
        var i = this._id2counter[e];
        if (i) return i;
        var a = this._values[e];
        if (!a) return null;
        if (a.extension) {
          var n = a.extension.indexOf(".");
          var s = a.extension.substring(0, n);
          var o = this._name2extStats[s];
          if (!o) {
            console.error("extension " + s + " not found, make sure you have register and enable it.");
            return null;
          }
          i = o.counter(e, a);
        } else i = new f(e, a);
        this._id2counter[e] = i;
        return i;
      };
      C.prototype.tick = function t() {
        var e = this;
        for (var i in e._name2extStats) {
          var a = e._name2extStats[i];
          a.tick();
        }
        for (var n in e._values) {
          var s = e._id2counter[n];
          if (s) {
            s.sample();
            var o = s.alarm();
            var r = s.human();
            var l = e._id2item[n];
            l.label.classList.toggle("alarm", o > 0);
            l.valueText.nodeValue = r;
            e._showGraph && l.graph.draw(s.value, o);
          }
        }
        if (this._showGraph) for (var c = 0; c < this._fractions.length; ++c) {
          var h = e._fractions[c];
          var p = e._id2counter[h.base];
          if (p) {
            var _ = h.steps;
            for (var f = 0; f < _.length; ++f) {
              var u = _[f];
              var v = e._id2counter[u];
              v && (h.values[f] = v.value / p.value);
            }
            h.graph.draw(h.values);
          }
        }
      };
      t();
      var M = {
        new: function t(e, i) {
          var a = new C(e, i);
          return function(t) {
            if (!t) return a;
            return a.item(t);
          };
        },
        register: function t(e, i) {
          y[e] = i;
        }
      };
      return M;
    })();
  }), {} ],
  312: [ (function(require, module, exports) {
    var _global = "undefined" === typeof window ? global : window;
    function defineMacro(name, defaultValue) {
      "undefined" === typeof _global[name] && (_global[name] = defaultValue);
    }
    function defined(name) {
      return "object" === typeof _global[name];
    }
    defineMacro("CC_TEST", defined("tap") || defined("QUnit"));
    defineMacro("CC_EDITOR", defined("Editor") && defined("process") && "electron" in process.versions);
    defineMacro("CC_PREVIEW", true);
    defineMacro("CC_DEV", true);
    defineMacro("CC_DEBUG", true);
    defineMacro("CC_JSB", defined("jsb"));
    defineMacro("CC_BUILD", false);
    defineMacro("CC_WECHATGAME", false);
    defineMacro("CC_SUPPORT_JIT", true);
    cc = {};
    _ccsg = {};
    false;
    require("./CCDebugger");
    cc._initDebugSetting(cc.DebugMode.INFO);
    true;
    require("./DebugInfos");
    require("./polyfill/string");
    require("./polyfill/misc");
    require("./polyfill/array");
    true;
    require("./polyfill/typescript");
    require("./cocos2d/kazmath");
    require("./cocos2d/core/predefine");
    ccs = {};
    cp = {};
    false;
    require("./cocos2d/shaders");
    require("./CCBoot");
    require("./cocos2d");
    require("./extends");
    false;
    module.exports = cc;
  }), {
    "./CCBoot": 1,
    "./CCDebugger": 2,
    "./DebugInfos": 3,
    "./cocos2d": 242,
    "./cocos2d/core/predefine": 201,
    "./cocos2d/kazmath": 246,
    "./cocos2d/shaders": 273,
    "./extends": 288,
    "./package.json": void 0,
    "./polyfill/array": 313,
    "./polyfill/misc": 314,
    "./polyfill/string": 315,
    "./polyfill/typescript": 316
  } ],
  313: [ (function(require, module, exports) {
    Array.isArray || (Array.isArray = function(arg) {
      return "[object Array]" === Object.prototype.toString.call(arg);
    });
  }), {} ],
  314: [ (function(require, module, exports) {
    Math.sign || (Math.sign = function(x) {
      x = +x;
      if (0 === x || isNaN(x)) return x;
      return x > 0 ? 1 : -1;
    });
    Number.isInteger || (Number.isInteger = function(value) {
      return "number" === typeof value && (0 | value) === value;
    });
    if (false, !console.time) {
      var Timer = window.performance || Date;
      var _timerTable = Object.create(null);
      console.time = function(label) {
        _timerTable[label] = Timer.now();
      };
      console.timeEnd = function(label) {
        var startTime = _timerTable[label];
        var duration = Timer.now() - startTime;
        console.log(label + ": " + duration + "ms");
      };
    }
  }), {} ],
  315: [ (function(require, module, exports) {
    String.prototype.startsWith || (String.prototype.startsWith = function(searchString, position) {
      position = position || 0;
      return this.lastIndexOf(searchString, position) === position;
    });
    String.prototype.endsWith || (String.prototype.endsWith = function(searchString, position) {
      ("undefined" === typeof position || position > this.length) && (position = this.length);
      position -= searchString.length;
      var lastIndex = this.indexOf(searchString, position);
      return -1 !== lastIndex && lastIndex === position;
    });
  }), {} ],
  316: [ (function(require, module, exports) {
    var extendStatics = Object.setPrototypeOf || {
      __proto__: []
    } instanceof Array && function(d, b) {
      d.__proto__ = b;
    } || function(d, b) {
      for (var p in b) b.hasOwnProperty(p) && (d[p] = b[p]);
    };
    window.__extends = function(d, b) {
      extendStatics(d, b);
      function __() {
        this.constructor = d;
      }
      d.prototype = null === b ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
    window.__assign = Object.assign || function(t) {
      for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) Object.prototype.hasOwnProperty.call(s, p) && (t[p] = s[p]);
      }
      return t;
    };
    window.__rest = function(s, e) {
      var t = {};
      for (var p in s) Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0 && (t[p] = s[p]);
      if (null != s && "function" === typeof Object.getOwnPropertySymbols) for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) e.indexOf(p[i]) < 0 && (t[p[i]] = s[p[i]]);
      return t;
    };
    window.__decorate = function(decorators, target, key, desc) {
      var c = arguments.length, r = c < 3 ? target : null === desc ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
      if ("object" === typeof Reflect && "function" === typeof Reflect.decorate) r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) (d = decorators[i]) && (r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r);
      return c > 3 && r && Object.defineProperty(target, key, r), r;
    };
    window.__param = function(paramIndex, decorator) {
      return function(target, key) {
        decorator(target, key, paramIndex);
      };
    };
    window.__metadata = function(metadataKey, metadataValue) {
      if ("object" === typeof Reflect && "function" === typeof Reflect.metadata) return Reflect.metadata(metadataKey, metadataValue);
    };
    window.__awaiter = function(thisArg, _arguments, P, generator) {
      return new (P || (P = Promise))(function(resolve, reject) {
        function fulfilled(value) {
          try {
            step(generator.next(value));
          } catch (e) {
            reject(e);
          }
        }
        function rejected(value) {
          try {
            step(generator["throw"](value));
          } catch (e) {
            reject(e);
          }
        }
        function step(result) {
          result.done ? resolve(result.value) : new P(function(resolve) {
            resolve(result.value);
          }).then(fulfilled, rejected);
        }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
      });
    };
    window.__generator = function(thisArg, body) {
      var _ = {
        label: 0,
        sent: function() {
          if (1 & t[0]) throw t[1];
          return t[1];
        },
        trys: [],
        ops: []
      }, f, y, t, g;
      return g = {
        next: verb(0),
        throw: verb(1),
        return: verb(2)
      }, "function" === typeof Symbol && (g[Symbol.iterator] = function() {
        return this;
      }), g;
      function verb(n) {
        return function(v) {
          return step([ n, v ]);
        };
      }
      function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
          if (f = 1, y && (t = y[2 & op[0] ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
          (y = 0, t) && (op = [ 0, t.value ]);
          switch (op[0]) {
           case 0:
           case 1:
            t = op;
            break;

           case 4:
            _.label++;
            return {
              value: op[1],
              done: false
            };

           case 5:
            _.label++;
            y = op[1];
            op = [ 0 ];
            continue;

           case 7:
            op = _.ops.pop();
            _.trys.pop();
            continue;

           default:
            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (6 === op[0] || 2 === op[0])) {
              _ = 0;
              continue;
            }
            if (3 === op[0] && (!t || op[1] > t[0] && op[1] < t[3])) {
              _.label = op[1];
              break;
            }
            if (6 === op[0] && _.label < t[1]) {
              _.label = t[1];
              t = op;
              break;
            }
            if (t && _.label < t[2]) {
              _.label = t[2];
              _.ops.push(op);
              break;
            }
            t[2] && _.ops.pop();
            _.trys.pop();
            continue;
          }
          op = body.call(thisArg, _);
        } catch (e) {
          op = [ 6, e ];
          y = 0;
        } finally {
          f = t = 0;
        }
        if (5 & op[0]) throw op[1];
        return {
          value: op[0] ? op[1] : void 0,
          done: true
        };
      }
    };
    window.__exportStar = function(m, exports) {
      for (var p in m) exports.hasOwnProperty(p) || (exports[p] = m[p]);
    };
    window.__values = function(o) {
      var m = "function" === typeof Symbol && o[Symbol.iterator], i = 0;
      if (m) return m.call(o);
      return {
        next: function() {
          o && i >= o.length && (o = void 0);
          return {
            value: o && o[i++],
            done: !o
          };
        }
      };
    };
    window.__read = function(o, n) {
      var m = "function" === typeof Symbol && o[Symbol.iterator];
      if (!m) return o;
      var i = m.call(o), r, ar = [], e;
      try {
        while ((void 0 === n || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
      } catch (error) {
        e = {
          error: error
        };
      } finally {
        try {
          r && !r.done && (m = i["return"]) && m.call(i);
        } finally {
          if (e) throw e.error;
        }
      }
      return ar;
    };
    window.__spread = function() {
      for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
      return ar;
    };
    window.__await = function(v) {
      return this instanceof __await ? (this.v = v, this) : new __await(v);
    };
    window.__asyncGenerator = function(thisArg, _arguments, generator) {
      if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
      var g = generator.apply(thisArg, _arguments || []), i, q = [];
      return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
        return this;
      }, i;
      function verb(n) {
        g[n] && (i[n] = function(v) {
          return new Promise(function(a, b) {
            q.push([ n, v, a, b ]) > 1 || resume(n, v);
          });
        });
      }
      function resume(n, v) {
        try {
          step(g[n](v));
        } catch (e) {
          settle(q[0][3], e);
        }
      }
      function step(r) {
        r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
      }
      function fulfill(value) {
        resume("next", value);
      }
      function reject(value) {
        resume("throw", value);
      }
      function settle(f, v) {
        (f(v), q.shift(), q.length) && resume(q[0][0], q[0][1]);
      }
    };
    window.__asyncDelegator = function(o) {
      var i, p;
      return i = {}, verb("next"), verb("throw", (function(e) {
        throw e;
      })), verb("return"), i[Symbol.iterator] = function() {
        return this;
      }, i;
      function verb(n, f) {
        o[n] && (i[n] = function(v) {
          return (p = !p) ? {
            value: __await(o[n](v)),
            done: "return" === n
          } : f ? f(v) : v;
        });
      }
    };
    window.__asyncValues = function(o) {
      if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
      var m = o[Symbol.asyncIterator];
      return m ? m.call(o) : "function" === typeof __values ? __values(o) : o[Symbol.iterator]();
    };
  }), {} ]
}, {}, [ 312 ]);
//# sourceMappingURL=cocos2d-js.js.map