diff --git a/EngineErrorMap.md b/EngineErrorMap.md
index 0759dfffc8..f1314fb05f 100644
--- a/EngineErrorMap.md
+++ b/EngineErrorMap.md
@@ -396,6 +396,7 @@ 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
@@ -420,18 +421,22 @@ 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
@@ -1558,6 +1563,7 @@ _ccsg.Label._initBMFontWithString(): Impossible to create font. Please check fil
### 4002
+
_ccsg.Label._initBMFontWithString(): re-init is no longer supported
### 4003
@@ -2008,26 +2014,32 @@ cc.ParticleBatchNode._addChildHelper(): child already added. It can't be added a
### 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
@@ -2037,6 +2049,7 @@ Can't change blending functions when the particle is being batched
### 6015
+
_ccsg.ParticleSystem.setDisplayFrame(): QuadParticle only supports SpriteFrames with no offsets
### 6016
@@ -2096,6 +2109,18 @@ Unknown Photometric Interpretation: %s
Unkown error
+### 6030
+
+cc.ParticleSystem: error decoding or ungzipping textureImageData
+
+### 6031
+
+cc.ParticleSystem: unknown image format with Data
+
+### 6032
+
+cc.ParticleSystem.initWithDictionary() : error loading the texture
+
### 6100
@@ -2239,26 +2264,32 @@ Property 'mapLoaded' is unused now. Please write the logic to the callback 'star
### 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
@@ -2271,10 +2302,12 @@ 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
@@ -2316,56 +2349,93 @@ Parse %s failed.
### 7223
+
_ccsg.TMXLayer.setTileGID(): pos should be non-null
### 7224
+
_ccsg.TMXTiledMap.getLayer(): layerName should be non-null or non-empty string.
### 7225
+
_ccsg.TMXTiledMap.getObjectGroup(): groupName should be non-null or non-empty string.
### 7226
+
_ccsg.TMXLayer.getTileAt(): pos should be non-null
### 7227
+
_ccsg.TMXLayer.getTileAt(): invalid position
### 7228
+
_ccsg.TMXLayer.getTileGIDAt(): pos should be non-null
### 7229
+
_ccsg.TMXLayer.getTileGIDAt(): invalid position
### 7230
+
_ccsg.TMXLayer.setTileGID(): pos should be non-null
### 7231
+
_ccsg.TMXLayer.setTileGID(): invalid position
### 7232
+
_ccsg.TMXLayer.getTileFlagsAt(): pos should be non-null
### 7233
+
_ccsg.TMXLayer.getTileFlagsAt(): invalid position
### 7234
+
_ccsg.TMXLayer.removeTileAt(): pos should be non-null
### 7235
+
_ccsg.TMXLayer.removeTileAt(): invalid position
+### 7236
+
+cc.TMXLayer.getTileAt(): TMXLayer: the tiles map has been released
+
+### 7237
+
+cc.TMXLayer.getTileGIDAt(): TMXLayer: the tiles map has been released
+
+### 7238
+
+cc.TMXLayer.setTileGID(): TMXLayer: the tiles map has been released
+
+### 7239
+
+cc.TMXLayer.setTileGID(): invalid gid: %s
+
+### 7240
+
+cc.TMXLayer.getTileFlagsAt(): TMXLayer: the tiles map has been released
+
+### 7241
+
+cc.TiledMap.initWithXML(): Map not found. Please check the filename.
+
### 7300
diff --git a/cocos2d/actions/CCAction.js b/cocos2d/actions/CCAction.js
index a856fb067b..4d98beb3a8 100644
--- a/cocos2d/actions/CCAction.js
+++ b/cocos2d/actions/CCAction.js
@@ -400,17 +400,15 @@ cc.speed = function (action, speed) {
* @property {Number} topBoundary - world topBoundary.
* @property {Number} bottomBoundary - world bottomBoundary.
*
- * @param {_ccsg.Node} followedNode
+ * @param {cc.Node} followedNode
* @param {Rect} rect
* @example
* // creates the action with a set boundary
- * var sprite = new _ccsg.Sprite("spriteFileName");
- * var followAction = new cc.Follow(sprite, cc.rect(0, 0, s.width * 2 - 100, s.height));
+ * var followAction = new cc.Follow(node, cc.rect(0, 0, s.width * 2 - 100, s.height));
* this.runAction(followAction);
*
* // creates the action with no boundary set
- * var sprite = new _ccsg.Sprite("spriteFileName");
- * var followAction = new cc.Follow(sprite);
+ * var followAction = new cc.Follow(node);
* this.runAction(followAction);
*
* @class
@@ -424,7 +422,7 @@ cc.Follow = cc.Class({
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
* creates the action with a set boundary.
* creates the action with no boundary set.
- * @param {_ccsg.Node} followedNode
+ * @param {cc.Node} followedNode
* @param {Rect} rect
*/
ctor:function (followedNode, rect) {
@@ -478,7 +476,7 @@ cc.Follow = cc.Class({
/*
* initializes the action with a set boundary.
*
- * @param {_ccsg.Node} followedNode
+ * @param {cc.Node} followedNode
* @param {Rect} [rect=]
* @return {Boolean}
*/
diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js
index a429457b53..866c68b28b 100644
--- a/cocos2d/core/CCDirector.js
+++ b/cocos2d/core/CCDirector.js
@@ -243,7 +243,7 @@ cc.Director.prototype = {
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};
+ return view._isRotated ? cc.v2(view._viewportRect.width - y, x) : cc.v2(x, y);
},
/**
@@ -263,7 +263,7 @@ cc.Director.prototype = {
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};
+ var uiPoint = cc.v2(0, 0);
if (view._isRotated) {
uiPoint.x = left + glPoint.y / view._devicePixelRatio;
uiPoint.y = top + box.height - (view._viewportRect.width - glPoint.x) / view._devicePixelRatio;
diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js
index 8dfabf5569..b7f97f65c2 100644
--- a/cocos2d/core/CCGame.js
+++ b/cocos2d/core/CCGame.js
@@ -610,7 +610,7 @@ var game = {
if (typeof config.registerSystemEvent !== 'boolean') {
config.registerSystemEvent = true;
}
- config.showFPS = (typeof config.showFPS !== 'undefined') ? (!!config.showFPS) : true;
+ config.showFPS = !!config.showFPS;
// Scene parser
this._sceneInfos = config.scenes || [];
@@ -744,7 +744,9 @@ var game = {
this._renderContext = renderer.device._gl;
// Enable dynamic atlas manager by default
- cc.dynamicAtlasManager.enabled = true;
+ if (!cc.macro.CLEANUP_IMAGE_CACHE) {
+ cc.dynamicAtlasManager.enabled = true;
+ }
}
if (!this._renderContext) {
this.renderType = this.RENDER_TYPE_CANVAS;
diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js
index b2a1b82639..fee8abf7e0 100644
--- a/cocos2d/core/CCNode.js
+++ b/cocos2d/core/CCNode.js
@@ -46,6 +46,8 @@ const ONE_DEGREE = Math.PI / 180;
var ActionManagerExist = !!cc.ActionManager;
var emptyFunc = function () {};
+var _vec2a = cc.v2();
+var _vec2b = cc.v2();
var _mat4_temp = math.mat4.create();
var _vec3_temp = math.vec3.create();
var _quat_temp = math.quat.create();
@@ -121,7 +123,7 @@ var LocalDirtyFlag = cc.Enum({
/**
* !#en The event type supported by Node
* !#zh Node 支持的事件类型
- * @enum Node.EventType
+ * @class Node.EventType
* @static
* @namespace Node
*/
@@ -708,9 +710,6 @@ var Node = cc.Class({
*/
rotation: {
get () {
- if (this._rotationX !== this._rotationY) {
- cc.logID(1602);
- }
return this._rotationX;
},
set (value) {
@@ -930,7 +929,7 @@ var Node = cc.Class({
},
set (value) {
if (!this._color.equals(value)) {
- this._color.fromColor(value);
+ this._color.set(value);
if (CC_DEV && value.a !== 255) {
cc.warnID(1626);
}
@@ -1098,7 +1097,7 @@ var Node = cc.Class({
* @method constructor
* @param {String} [name]
*/
- ctor (name) {
+ ctor () {
this._reorderChildDirty = false;
// cache component
@@ -1338,54 +1337,7 @@ var Node = cc.Class({
// EVENT TARGET
- /**
- * !#en
- * Register a callback of a specific event type on Node.
- * Use this method to register touch or mouse event permit propagation based on scene graph,
- * These kinds of event are triggered with dispatchEvent, the dispatch process has three steps:
- * 1. Capturing phase: dispatch in capture targets (`_getCapturingTargets`), e.g. parents in node tree, from root to the real target
- * 2. At target phase: dispatch to the listeners of the real target
- * 3. Bubbling phase: dispatch in bubble targets (`_getBubblingTargets`), e.g. parents in node tree, from the real target to root
- * In any moment of the dispatching process, it can be stopped via `event.stopPropagation()` or `event.stopPropagationImmidiate()`.
- * It's the recommended way to register touch/mouse event for Node,
- * please do not use cc.eventManager directly for Node.
- * You can also register custom event and use `emit` to trigger custom event on Node.
- * For such events, there won't be capturing and bubbling phase, your event will be dispatched directly to its listeners registered on the same node.
- * You can also pass event callback parameters with `emit` by passing parameters after `type`.
- * !#zh
- * 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。
- * 鼠标或触摸事件会被系统调用 dispatchEvent 方法触发,触发的过程包含三个阶段:
- * 1. 捕获阶段:派发事件给捕获目标(通过 `_getCapturingTargets` 获取),比如,节点树中注册了捕获阶段的父节点,从根节点开始派发直到目标节点。
- * 2. 目标阶段:派发给目标节点的监听器。
- * 3. 冒泡阶段:派发事件给冒泡目标(通过 `_getBubblingTargets` 获取),比如,节点树中注册了冒泡阶段的父节点,从目标节点开始派发知道根节点。
- * 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。
- * 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。
- * 你也可以注册自定义事件到节点上,并通过 emit 方法触发此类事件,对于这类事件,不会发生捕获冒泡阶段,只会直接派发给注册在该节点上的监听器
- * 你可以通过在 emit 方法调用时在 type 之后传递额外的参数作为事件回调的参数列表
- * @method on
- * @param {String} type - A string representing the event type to listen for.
- * See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events.
- * @param {Function} callback - The callback that will be invoked when the event is dispatched.
- * The callback is ignored if it is a duplicate (the callbacks are unique).
- * @param {Event} callback.event event
- * @param {Object} [target] - The target (this object) to invoke the callback, can be null
- * @param {Boolean} [useCapture=false] - When set to true, the capture argument prevents callback
- * from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE.
- * When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE.
- * Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET.
- * @return {Function} - Just returns the incoming callback so you can save the anonymous function easier.
- * @typescript
- * on(type: string, callback: (event: Event.EventCustom) => void, target?: any, useCapture?: boolean): (event: Event.EventCustom) => void
- * on(type: string, callback: (event: T) => void, target?: any, useCapture?: boolean): (event: T) => void
- * @example
- * this.node.on(cc.Node.EventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass.
- * node.on(cc.Node.EventType.TOUCH_START, callback, this.node);
- * node.on(cc.Node.EventType.TOUCH_MOVE, callback, this.node);
- * node.on(cc.Node.EventType.TOUCH_END, callback, this.node);
- * node.on(cc.Node.EventType.TOUCH_CANCEL, callback, this.node);
- * node.on(cc.Node.EventType.ANCHOR_CHANGED, callback, this);
- */
- on (type, callback, target, useCapture) {
+ _checknSetupSysEvent (type) {
let newAdded = false;
let forDispatch = false;
if (_touchEvents.indexOf(type) !== -1) {
@@ -1429,7 +1381,61 @@ var Node = cc.Class({
}
}, this, 0, 0, 0, false);
}
+ return forDispatch;
+ },
+ /**
+ * !#en
+ * Register a callback of a specific event type on Node.
+ * Use this method to register touch or mouse event permit propagation based on scene graph,
+ * These kinds of event are triggered with dispatchEvent, the dispatch process has three steps:
+ * 1. Capturing phase: dispatch in capture targets (`_getCapturingTargets`), e.g. parents in node tree, from root to the real target
+ * 2. At target phase: dispatch to the listeners of the real target
+ * 3. Bubbling phase: dispatch in bubble targets (`_getBubblingTargets`), e.g. parents in node tree, from the real target to root
+ * In any moment of the dispatching process, it can be stopped via `event.stopPropagation()` or `event.stopPropagationImmidiate()`.
+ * It's the recommended way to register touch/mouse event for Node,
+ * please do not use cc.eventManager directly for Node.
+ * You can also register custom event and use `emit` to trigger custom event on Node.
+ * For such events, there won't be capturing and bubbling phase, your event will be dispatched directly to its listeners registered on the same node.
+ * You can also pass event callback parameters with `emit` by passing parameters after `type`.
+ * !#zh
+ * 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。
+ * 鼠标或触摸事件会被系统调用 dispatchEvent 方法触发,触发的过程包含三个阶段:
+ * 1. 捕获阶段:派发事件给捕获目标(通过 `_getCapturingTargets` 获取),比如,节点树中注册了捕获阶段的父节点,从根节点开始派发直到目标节点。
+ * 2. 目标阶段:派发给目标节点的监听器。
+ * 3. 冒泡阶段:派发事件给冒泡目标(通过 `_getBubblingTargets` 获取),比如,节点树中注册了冒泡阶段的父节点,从目标节点开始派发知道根节点。
+ * 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。
+ * 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。
+ * 你也可以注册自定义事件到节点上,并通过 emit 方法触发此类事件,对于这类事件,不会发生捕获冒泡阶段,只会直接派发给注册在该节点上的监听器
+ * 你可以通过在 emit 方法调用时在 type 之后传递额外的参数作为事件回调的参数列表
+ * @method on
+ * @param {String|Node.EventType} type - A string representing the event type to listen for.
+ * See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events.
+ * @param {Function} callback - The callback that will be invoked when the event is dispatched.
+ * The callback is ignored if it is a duplicate (the callbacks are unique).
+ * @param {Event|Object} callback.event event or first argument when emit
+ * @param {Event} callback.arg2 arg2
+ * @param {Event} callback.arg3 arg3
+ * @param {Event} callback.arg4 arg4
+ * @param {Event} callback.arg5 arg5
+ * @param {Object} [target] - The target (this object) to invoke the callback, can be null
+ * @param {Boolean} [useCapture=false] - When set to true, the capture argument prevents callback
+ * from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE.
+ * When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE.
+ * Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET.
+ * @return {Function} - Just returns the incoming callback so you can save the anonymous function easier.
+ * @typescript
+ * on(type: string, callback: T, target?: any, useCapture?: boolean): T
+ * @example
+ * this.node.on(cc.Node.EventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass.
+ * node.on(cc.Node.EventType.TOUCH_START, callback, this);
+ * node.on(cc.Node.EventType.TOUCH_MOVE, callback, this);
+ * node.on(cc.Node.EventType.TOUCH_END, callback, this);
+ * node.on(cc.Node.EventType.TOUCH_CANCEL, callback, this);
+ * node.on(cc.Node.EventType.ANCHOR_CHANGED, callback);
+ */
+ on (type, callback, target, useCapture) {
+ let forDispatch = this._checknSetupSysEvent(type);
if (forDispatch) {
return this._onDispatch(type, callback, target, useCapture);
}
@@ -1458,6 +1464,53 @@ var Node = cc.Class({
}
},
+ /**
+ * !#en
+ * Register an callback of a specific event type on the Node,
+ * the callback will remove itself after the first time it is triggered.
+ * !#zh
+ * 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身。
+ *
+ * @method once
+ * @param {String} type - A string representing the event type to listen for.
+ * @param {Function} callback - The callback that will be invoked when the event is dispatched.
+ * The callback is ignored if it is a duplicate (the callbacks are unique).
+ * @param {Event} callback.event event or first argument when emit
+ * @param {Event} callback.arg2 arg2
+ * @param {Event} callback.arg3 arg3
+ * @param {Event} callback.arg4 arg4
+ * @param {Event} callback.arg5 arg5
+ * @param {Object} [target] - The target (this object) to invoke the callback, can be null
+ * @typescript
+ * once(type: string, callback: T, target?: any, useCapture?: boolean): T
+ * @example
+ * node.once(cc.Node.EventType.ANCHOR_CHANGED, callback);
+ */
+ once (type, callback, target, useCapture) {
+ let forDispatch = this._checknSetupSysEvent(type);
+ let eventType_hasOnceListener = '__ONCE_FLAG:' + type;
+
+ let listeners = null;
+ if (forDispatch && useCapture) {
+ listeners = this._capturingListeners = this._capturingListeners || new EventTarget();
+ }
+ else {
+ listeners = this._bubblingListeners = this._bubblingListeners || new EventTarget();
+ }
+
+ let hasOnceListener = listeners.hasEventListener(eventType_hasOnceListener, callback, target);
+ if (!hasOnceListener) {
+ let self = this;
+ let onceWrapper = function (arg1, arg2, arg3, arg4, arg5) {
+ self.off(type, onceWrapper, target);
+ listeners.remove(eventType_hasOnceListener, callback, target);
+ callback.call(this, arg1, arg2, arg3, arg4, arg5);
+ };
+ this.on(type, onceWrapper, target);
+ listeners.add(eventType_hasOnceListener, callback, target);
+ }
+ },
+
_onDispatch (type, callback, target, useCapture) {
// Accept also patameters like: (type, callback, useCapture)
if (typeof target === 'boolean') {
@@ -1488,26 +1541,6 @@ var Node = cc.Class({
return callback;
},
- _onceDispatch (type, callback, target, useCapture) {
- var eventType_hasOnceListener = '__ONCE_FLAG:' + type;
- var listeners = useCapture ? this._capturingListeners : this._bubblingListeners;
- var hasOnceListener = listeners && listeners.hasEventListener(eventType_hasOnceListener, callback, target);
- if (!hasOnceListener) {
- var self = this;
- var onceWrapper = function (event) {
- self._offDispatch(type, onceWrapper, target, useCapture);
- listeners.remove(eventType_hasOnceListener, callback, target);
- callback.call(this, event);
- };
- this._onDispatch(type, onceWrapper, target, useCapture);
- if (!listeners) {
- // obtain new created listeners
- listeners = useCapture ? this._capturingListeners : this._bubblingListeners;
- }
- listeners.add(eventType_hasOnceListener, callback, target);
- }
- },
-
/**
* !#en
* Removes the callback previously registered with the same type, callback, target and or useCapture.
@@ -1729,23 +1762,24 @@ var Node = cc.Class({
},
_hitTest (point, listener) {
- var w = this.width,
- h = this.height;
- var testPt;
+ let w = this._contentSize.width,
+ h = this._contentSize.height,
+ cameraPt = _vec2a,
+ testPt = _vec2b;
let camera = cc.Camera.findCamera(this);
if (camera) {
- testPt = camera.getCameraToWorldPoint(point);
+ camera.getCameraToWorldPoint(point, cameraPt);
}
else {
- testPt = cc.v2(point);
+ cameraPt.set(point);
}
this._updateWorldMatrix();
math.mat4.invert(_mat4_temp, this._worldMatrix);
- math.vec2.transformMat4(testPt, testPt, _mat4_temp);
- testPt.x += this._anchorPoint.x * this._contentSize.width;
- testPt.y += this._anchorPoint.y * this._contentSize.height;
+ math.vec2.transformMat4(testPt, cameraPt, _mat4_temp);
+ testPt.x += this._anchorPoint.x * w;
+ testPt.y += this._anchorPoint.y * h;
if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) {
if (listener && listener.mask) {
@@ -1756,7 +1790,7 @@ var Node = cc.Class({
// find mask parent, should hit test it
if (parent === mask.node) {
var comp = parent.getComponent(cc.Mask);
- return (comp && comp.enabledInHierarchy) ? comp._hitTest(point) : true;
+ return (comp && comp.enabledInHierarchy) ? comp._hitTest(cameraPt) : true;
}
// mask parent no longer exists
else {
@@ -2367,7 +2401,7 @@ var Node = cc.Class({
let t = this._matrix;
//math.mat4.fromRTS(t, this._quat, this._position, this._scale);
- if (dirtyFlag & LocalDirtyFlag.RT) {
+ if (dirtyFlag & (LocalDirtyFlag.RT | LocalDirtyFlag.SKEW)) {
let hasRotation = this._rotationX || this._rotationY;
let hasSkew = this._skewX || this._skewY;
let sx = this._scale.x, sy = this._scale.y;
diff --git a/cocos2d/core/assets/CCSpriteFrame.js b/cocos2d/core/assets/CCSpriteFrame.js
index cb573a6d0d..e68e0ff075 100644
--- a/cocos2d/core/assets/CCSpriteFrame.js
+++ b/cocos2d/core/assets/CCSpriteFrame.js
@@ -33,12 +33,12 @@ let temp_uvs = [{u: 0, v: 0}, {u: 0, v: 0}, {u: 0, v: 0}, {u: 0, v: 0}];
/**
* !#en
* A cc.SpriteFrame has:
- * - texture: A cc.Texture2D that will be used by the _ccsg.Sprite
+ * - texture: A cc.Texture2D that will be used by render components
* - rectangle: A rectangle of the texture
*
* !#zh
* 一个 SpriteFrame 包含:
- * - 纹理:会被 Sprite 使用的 Texture2D 对象。
+ * - 纹理:会被渲染组件使用的 Texture2D 对象。
* - 矩形:在纹理中的矩形区域。
*
* @class SpriteFrame
@@ -102,6 +102,9 @@ let SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{
* @param {Size} [originalSize] - The size of the frame in the texture
*/
ctor: function () {
+ // Init EventTarget data
+ EventTarget.call(this);
+
let filename = arguments[0];
let rect = arguments[1];
let rotated = arguments[2];
diff --git a/cocos2d/core/assets/CCTexture2D.js b/cocos2d/core/assets/CCTexture2D.js
index 23eb5ecd15..d72fd494bc 100644
--- a/cocos2d/core/assets/CCTexture2D.js
+++ b/cocos2d/core/assets/CCTexture2D.js
@@ -536,6 +536,14 @@ var Texture2D = cc.Class({
//dispatch load event to listener.
this.loaded = true;
this.emit("load");
+
+ if (cc.macro.CLEANUP_IMAGE_CACHE && this._image instanceof HTMLImageElement) {
+ // wechat game platform will cache image parsed data,
+ // so image will consume much more memory than web, releasing it
+ this._image.src = "";
+ // Release image in loader cache
+ cc.loader.removeItem(this._image.id);
+ }
},
/**
diff --git a/cocos2d/core/camera/CCCamera.js b/cocos2d/core/camera/CCCamera.js
index fc986cd8a1..3605623808 100644
--- a/cocos2d/core/camera/CCCamera.js
+++ b/cocos2d/core/camera/CCCamera.js
@@ -36,7 +36,6 @@ const vec3 = cc.vmath.vec3;
let _mat4_temp_1 = mat4.create();
let _mat4_temp_2 = mat4.create();
let _vec3_temp_1 = vec3.create();
-let _vec3_temp_2 = vec3.create();
let _cameras = [];
diff --git a/cocos2d/core/components/CCAnimation.js b/cocos2d/core/components/CCAnimation.js
index 55b6741eff..d110f4e85e 100644
--- a/cocos2d/core/components/CCAnimation.js
+++ b/cocos2d/core/components/CCAnimation.js
@@ -37,6 +37,58 @@ function equalClips (clip1, clip2) {
return clip1 && clip2 && (clip1.name === clip2.name || clip1._uuid === clip2._uuid);
}
+/**
+ * !#en The event type supported by Animation
+ * !#zh Animation 支持的事件类型
+ * @class Animation.EventType
+ * @static
+ * @namespace Animationd
+ */
+var EventType = cc.Enum({
+ /**
+ * !#en Emit when begin playing animation
+ * !#zh 开始播放时触发
+ * @property {String} PLAY
+ * @static
+ */
+ PLAY: 'play',
+ /**
+ * !#en Emit when stop playing animation
+ * !#zh 停止播放时触发
+ * @property {String} STOP
+ * @static
+ */
+ STOP: 'stop',
+ /**
+ * !#en Emit when pause animation
+ * !#zh 暂停播放时触发
+ * @property {String} PAUSE
+ * @static
+ */
+ PAUSE: 'pause',
+ /**
+ * !#en Emit when resume animation
+ * !#zh 恢复播放时触发
+ * @property {String} RESUME
+ * @static
+ */
+ RESUME: 'resume',
+ /**
+ * !#en If animation repeat count is larger than 1, emit when animation play to the last frame
+ * !#zh 假如动画循环次数大于 1,当动画播放到最后一帧时触发
+ * @property {String} LASTFRAME
+ * @static
+ */
+ LASTFRAME: 'lastframe',
+ /**
+ * !#en Emit when finish playing animation
+ * !#zh 动画播放完成时触发
+ * @property {String} FINISHED
+ * @static
+ */
+ FINISHED: 'finished'
+})
+
/**
* !#en The animation component is used to play back animations.
*
@@ -73,6 +125,10 @@ var Animation = cc.Class({
executeInEditMode: true,
},
+ statics: {
+ EventType
+ },
+
ctor: function () {
cc.EventTarget.call(this);
diff --git a/cocos2d/core/components/CCLabel.js b/cocos2d/core/components/CCLabel.js
index 48f39b850e..9b6ba277f7 100644
--- a/cocos2d/core/components/CCLabel.js
+++ b/cocos2d/core/components/CCLabel.js
@@ -528,6 +528,7 @@ let Label = cc.Class({
else {
if (!this._ttfTexture) {
this._ttfTexture = new cc.Texture2D();
+ this._ttfTexture.setPremultiplyAlpha(true);
this._assemblerData = this._assembler._getAssemblerData();
this._ttfTexture.initWithElement(this._assemblerData.canvas);
}
@@ -543,6 +544,10 @@ let Label = cc.Class({
if (!material) {
material = new SpriteMaterial();
}
+ // Setup blend function for premultiplied ttf label texture
+ if (this._texture === this._ttfTexture) {
+ this._srcBlendFactor = cc.macro.ONE;
+ }
material.texture = this._texture;
this._updateMaterial(material);
}
diff --git a/cocos2d/core/components/CCMask.js b/cocos2d/core/components/CCMask.js
index a5f450e465..530dabdb8c 100644
--- a/cocos2d/core/components/CCMask.js
+++ b/cocos2d/core/components/CCMask.js
@@ -31,8 +31,8 @@ const StencilMaterial = renderEngine.StencilMaterial;
const RenderComponent = require('./CCRenderComponent');
const RenderFlow = require('../renderer/render-flow');
+let _vec2_temp = cc.v2();
let _mat4_temp = math.mat4.create();
-let _rect_temp = cc.rect();
/**
* !#en the type for mask.
@@ -316,30 +316,25 @@ let Mask = cc.Class({
this.markForRender(true);
},
- _hitTest: function (point) {
+ _hitTest: function (cameraPt) {
let node = this.node;
let size = node.getContentSize(),
w = size.width,
- h = size.height;
- node.getWorldMatrix(_mat4_temp);
+ h = size.height,
+ testPt = _vec2_temp;
+
+ node._updateWorldMatrix();
+ math.mat4.invert(_mat4_temp, node._worldMatrix);
+ math.vec2.transformMat4(testPt, cameraPt, _mat4_temp);
+ testPt.x += node._anchorPoint.x * w;
+ testPt.y += node._anchorPoint.y * h;
if (this.type === MaskType.RECT || this.type === MaskType.IMAGE_STENCIL) {
- _rect_temp.x = -node.anchorX * w,
- _rect_temp.y = -node.anchorX * h;
- _rect_temp.width = w;
- _rect_temp.height = h;
- _rect_temp.transformMat4(_rect_temp, _mat4_temp);
-
- let left = point.x - _rect_temp.x,
- right = _rect_temp.x + _rect_temp.width - point.x,
- bottom = point.y - _rect_temp.y,
- top = _rect_temp.y + _rect_temp.height - point.y;
-
- return left >= 0 && right >= 0 && top >= 0 && bottom >= 0;
+ return testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h;
}
else if (this.type === MaskType.ELLIPSE) {
let rx = w / 2, ry = h / 2;
- let px = point.x - _mat4_temp.m12, py = point.y - _mat4_temp.m13;
+ let px = testPt.x - 0.5 * w, py = testPt.y - 0.5 * h;
return px * px / (rx * rx) + py * py / (ry * ry) < 1;
}
},
diff --git a/cocos2d/core/components/CCSprite.js b/cocos2d/core/components/CCSprite.js
index 1996a4cc9c..18f36f9238 100644
--- a/cocos2d/core/components/CCSprite.js
+++ b/cocos2d/core/components/CCSprite.js
@@ -211,10 +211,6 @@ var Sprite = cc.Class({
}
}
this._spriteFrame = value;
- if ((this._material && this._material._texture) !== (value && value._texture)) {
- // disable render flow util texture is loaded
- this.markForRender(false);
- }
// render & update render data flag will be triggered while applying new sprite frame
this.markForUpdateRenderData(false);
this._applySpriteFrame(lastSprite);
@@ -441,6 +437,10 @@ var Sprite = cc.Class({
if (!this._spriteFrame || !this._spriteFrame.textureLoaded()) {
// Do not render when sprite frame is not ready
this.disableRender();
+ if (this._spriteFrame) {
+ this._spriteFrame.once('load', this._onTextureLoaded, this);
+ this._spriteFrame.ensureLoadTexture();
+ }
}
this._updateAssembler();
@@ -587,6 +587,11 @@ var Sprite = cc.Class({
}
var spriteFrame = this._spriteFrame;
+ if (!spriteFrame || (this._material && this._material._texture) !== (spriteFrame && spriteFrame._texture)) {
+ // disable render flow until texture is loaded
+ this.markForRender(false);
+ }
+
if (spriteFrame) {
if (!oldFrame || spriteFrame._texture !== oldFrame._texture) {
if (spriteFrame.textureLoaded()) {
diff --git a/cocos2d/core/components/editbox/CCEditBox.js b/cocos2d/core/components/editbox/CCEditBox.js
index ed3c43e55b..0238478c51 100644
--- a/cocos2d/core/components/editbox/CCEditBox.js
+++ b/cocos2d/core/components/editbox/CCEditBox.js
@@ -469,8 +469,11 @@ let EditBox = cc.Class({
},
_updateString (text) {
- let placeholderLabel = this._placeholderLabel;
let textLabel = this._textLabel;
+ // Not inited yet
+ if (!textLabel) {
+ return;
+ }
let displayText = text;
if (displayText) {
@@ -479,6 +482,7 @@ let EditBox = cc.Class({
textLabel.string = displayText;
this._impl.setString(text);
+ this._showLabels();
},
_updateLabelStringStyle (text, ignorePassword) {
diff --git a/cocos2d/core/event-manager/CCEvent.js b/cocos2d/core/event-manager/CCEvent.js
index 72b67a75f0..feb282dafa 100644
--- a/cocos2d/core/event-manager/CCEvent.js
+++ b/cocos2d/core/event-manager/CCEvent.js
@@ -103,7 +103,7 @@ proto.setLocation = function (x, y) {
* @return {Vec2} location
*/
proto.getLocation = function () {
- return {x: this._x, y: this._y};
+ return cc.v2(this._x, this._y);
};
/**
@@ -113,7 +113,7 @@ proto.getLocation = function () {
* @return {Vec2}
*/
proto.getLocationInView = function() {
- return {x: this._x, y: cc.view._designResolutionSize.height - this._y};
+ return cc.v2(this._x, cc.view._designResolutionSize.height - this._y);
};
proto._setPrevCursor = function (x, y) {
@@ -128,7 +128,7 @@ proto._setPrevCursor = function (x, y) {
* @return {Vec2}
*/
proto.getPreviousLocation = function () {
- return {x: this._prevX, y: this._prevY};
+ return cc.v2(this._prevX, this._prevY);
};
/**
@@ -138,7 +138,7 @@ proto.getPreviousLocation = function () {
* @return {Vec2}
*/
proto.getDelta = function () {
- return {x: this._x - this._prevX, y: this._y - this._prevY};
+ return cc.v2(this._x - this._prevX, this._y - this._prevY);
};
/**
diff --git a/cocos2d/core/event-manager/CCEventListener.js b/cocos2d/core/event-manager/CCEventListener.js
index 00bd646b35..cd1ba37b1c 100644
--- a/cocos2d/core/event-manager/CCEventListener.js
+++ b/cocos2d/core/event-manager/CCEventListener.js
@@ -149,7 +149,7 @@ cc.EventListener.prototype = {
/*
* Sets scene graph priority for this listener
- * @param {_ccsg.Node|Node} node
+ * @param {cc.Node} node
* @private
*/
_setSceneGraphPriority: function (node) {
@@ -159,7 +159,7 @@ cc.EventListener.prototype = {
/*
* Gets scene graph priority of this listener
- * @returns {_ccsg.Node|cc.Node} if it's a fixed priority listener, non-null for scene graph priority listener
+ * @returns {cc.Node} if it's a fixed priority listener, non-null for scene graph priority listener
* @private
*/
_getSceneGraphPriority: function () {
diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js
index 501e3896df..f7ee2fc2f7 100644
--- a/cocos2d/core/event-manager/CCEventManager.js
+++ b/cocos2d/core/event-manager/CCEventManager.js
@@ -146,7 +146,7 @@ var eventManager = {
* @param {Boolean} [recursive=false]
*/
pauseTarget: function (node, recursive) {
- if (!(node instanceof cc._BaseNode || node instanceof _ccsg.Node)) {
+ if (!(node instanceof cc._BaseNode)) {
cc.warnID(3506);
return;
}
@@ -170,7 +170,7 @@ var eventManager = {
* @param {Boolean} [recursive=false]
*/
resumeTarget: function (node, recursive) {
- if (!(node instanceof cc._BaseNode || node instanceof _ccsg.Node)) {
+ if (!(node instanceof cc._BaseNode)) {
cc.warnID(3506);
return;
}
@@ -732,7 +732,7 @@ var eventManager = {
*/
addListener: function (listener, nodeOrPriority) {
cc.assertID(listener && nodeOrPriority, 3503);
- if (!(cc.js.isNumber(nodeOrPriority) || nodeOrPriority instanceof cc._BaseNode || nodeOrPriority instanceof _ccsg.Node)) {
+ if (!(cc.js.isNumber(nodeOrPriority) || nodeOrPriority instanceof cc._BaseNode)) {
cc.warnID(3506);
return;
}
@@ -902,7 +902,7 @@ var eventManager = {
*/
removeListeners: function (listenerType, recursive) {
var i, _t = this;
- if (!(cc.js.isNumber(listenerType) || listenerType instanceof cc._BaseNode || listenerType instanceof _ccsg.Node)) {
+ if (!(cc.js.isNumber(listenerType) || listenerType instanceof cc._BaseNode)) {
cc.warnID(3506);
return;
}
diff --git a/cocos2d/core/event/event-target.js b/cocos2d/core/event/event-target.js
index cc419f6f72..888594f87e 100644
--- a/cocos2d/core/event/event-target.js
+++ b/cocos2d/core/event/event-target.js
@@ -81,7 +81,11 @@ var proto = EventTarget.prototype;
* @param {String} type - A string representing the event type to listen for.
* @param {Function} callback - The callback that will be invoked when the event is dispatched.
* The callback is ignored if it is a duplicate (the callbacks are unique).
- * @param {Event} callback.event event
+ * @param {Event} callback.arg1 arg1
+ * @param {Event} callback.arg2 arg2
+ * @param {Event} callback.arg3 arg3
+ * @param {Event} callback.arg4 arg4
+ * @param {Event} callback.arg5 arg5
* @param {Object} [target] - The target (this object) to invoke the callback, can be null
* @return {Function} - Just returns the incoming callback so you can save the anonymous function easier.
* @typescript
@@ -165,7 +169,11 @@ proto.targetOff = proto.removeAll;
* @param {String} type - A string representing the event type to listen for.
* @param {Function} callback - The callback that will be invoked when the event is dispatched.
* The callback is ignored if it is a duplicate (the callbacks are unique).
- * @param {Event} callback.event event
+ * @param {Event} callback.arg1 arg1
+ * @param {Event} callback.arg2 arg2
+ * @param {Event} callback.arg3 arg3
+ * @param {Event} callback.arg4 arg4
+ * @param {Event} callback.arg5 arg5
* @param {Object} [target] - The target (this object) to invoke the callback, can be null
* @example
* eventTarget.once('fire', function (event) {
@@ -177,10 +185,10 @@ proto.once = function (type, callback, target) {
var hasOnceListener = this.hasEventListener(eventType_hasOnceListener, callback, target);
if (!hasOnceListener) {
var self = this;
- var onceWrapper = function (event) {
+ var onceWrapper = function (arg1, arg2, arg3, arg4, arg5) {
self.off(type, onceWrapper, target);
self.remove(eventType_hasOnceListener, callback, target);
- callback.call(this, event);
+ callback.call(this, arg1, arg2, arg3, arg4, arg5);
};
this.on(type, onceWrapper, target);
this.add(eventType_hasOnceListener, callback, target);
diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js
index aabe5b776e..d51197fd7c 100644
--- a/cocos2d/core/load-pipeline/CCLoader.js
+++ b/cocos2d/core/load-pipeline/CCLoader.js
@@ -656,7 +656,7 @@ proto.loadResDir = function (url, type, progressCallback, completeCallback) {
}
}
}
- completeCallback(errors, assetRes, urlRes);
+ completeCallback && completeCallback(errors, assetRes, urlRes);
}, urls);
};
diff --git a/cocos2d/core/load-pipeline/downloader.js b/cocos2d/core/load-pipeline/downloader.js
index bd979f0825..6fa1b65c9b 100644
--- a/cocos2d/core/load-pipeline/downloader.js
+++ b/cocos2d/core/load-pipeline/downloader.js
@@ -101,6 +101,7 @@ function downloadImage (item, callback, isCrossOrigin, img) {
img.removeEventListener('load', loadCallback);
img.removeEventListener('error', errorCallback);
+ img.id = item.id;
callback(null, img);
}
function errorCallback () {
diff --git a/cocos2d/core/load-pipeline/loader.js b/cocos2d/core/load-pipeline/loader.js
index 30be4c804c..1b5ef17d95 100644
--- a/cocos2d/core/load-pipeline/loader.js
+++ b/cocos2d/core/load-pipeline/loader.js
@@ -24,17 +24,17 @@
THE SOFTWARE.
****************************************************************************/
-var js = require('../platform/js');
-var sys = require('../platform/CCSys');
-var Pipeline = require('./pipeline');
-var Texture2D = require('../assets/CCTexture2D');
-var loadUuid = require('./uuid-loader');
+const js = require('../platform/js');
+const plistParser = require('../platform/CCSAXParser').plistParser;
+const Pipeline = require('./pipeline');
+const Texture2D = require('../assets/CCTexture2D');
+const loadUuid = require('./uuid-loader');
-function loadNothing (item, callback) {
+function loadNothing () {
return null;
}
-function loadJSON (item, callback) {
+function loadJSON (item) {
if (typeof item.content !== 'string') {
return new Error('JSON Loader: Input item doesn\'t contain string content');
}
@@ -48,7 +48,7 @@ function loadJSON (item, callback) {
}
}
-function loadImage (item, callback) {
+function loadImage (item) {
var loadByDeserializedAsset = (item._owner instanceof cc.Asset);
if (loadByDeserializedAsset) {
// already has cc.Asset
@@ -58,7 +58,7 @@ function loadImage (item, callback) {
var image = item.content;
if (!CC_WECHATGAME && !CC_QQPLAY && !(image instanceof Image)) {
return new Error('Image Loader: Input item doesn\'t contain Image content');
- }
+ }
// load cc.Texture2D
var rawUrl = item.rawUrl;
@@ -85,11 +85,11 @@ function loadAudioAsAsset (item, callback) {
return audioClip;
}
-function loadPlist (item, callback) {
+function loadPlist (item) {
if (typeof item.content !== 'string') {
return new Error('Plist Loader: Input item doesn\'t contain string content');
}
- var result = cc.plistParser.parse(item.content);
+ var result = plistParser.parse(item.content);
if (result) {
return result;
}
@@ -98,7 +98,7 @@ function loadPlist (item, callback) {
}
}
-function loadBinary (item, callback) {
+function loadBinary (item) {
// Invoke custom handle
if (item.load) {
return item.load(item.content);
diff --git a/cocos2d/core/load-pipeline/text-downloader.js b/cocos2d/core/load-pipeline/text-downloader.js
index 79af076cbc..deb9970f35 100644
--- a/cocos2d/core/load-pipeline/text-downloader.js
+++ b/cocos2d/core/load-pipeline/text-downloader.js
@@ -23,10 +23,8 @@
THE SOFTWARE.
****************************************************************************/
-var sys = require('../platform/CCSys');
-
if (CC_JSB) {
- module.exports = function (item, callback) {
+ module.exports = function (item) {
var url = item.url;
var result = jsb.fileUtils.getStringFromFile(url);
@@ -46,8 +44,7 @@ else {
url = urlAppendTimestamp(url);
var xhr = cc.loader.getXMLHttpRequest(),
- errInfo = 'Load text file failed: ' + url,
- navigator = window.navigator;
+ errInfo = 'Load text file failed: ' + url;
xhr.open('GET', url, true);
if (xhr.overrideMimeType) xhr.overrideMimeType('text\/plain; charset=utf-8');
xhr.onload = function () {
diff --git a/cocos2d/core/physics/CCRigidBody.js b/cocos2d/core/physics/CCRigidBody.js
index db023932e0..da71792b99 100644
--- a/cocos2d/core/physics/CCRigidBody.js
+++ b/cocos2d/core/physics/CCRigidBody.js
@@ -65,7 +65,7 @@ var RigidBody = cc.Class({
return this._enabled;
},
set: function () {
- cc.warnID('8200');
+ cc.warnID(8200);
},
visible: false,
override: true
@@ -776,7 +776,7 @@ var RigidBody = cc.Class({
b2body.SetLinearVelocity(temp);
}
else {
- b2body.SetTransform(temp, b2body.GetAngle());
+ b2body.SetTransformVec(temp, b2body.GetAngle());
}
},
/**
@@ -802,7 +802,7 @@ var RigidBody = cc.Class({
b2body.SetAngularVelocity((rotation - b2Rotation)*timeStep);
}
else {
- b2body.SetTransform(b2body.GetPosition(), rotation);
+ b2body.SetTransformVec(b2body.GetPosition(), rotation);
}
},
diff --git a/cocos2d/core/physics/platform/CCPhysicsDebugDraw.js b/cocos2d/core/physics/platform/CCPhysicsDebugDraw.js
index b35bff845b..19bf79397b 100644
--- a/cocos2d/core/physics/platform/CCPhysicsDebugDraw.js
+++ b/cocos2d/core/physics/platform/CCPhysicsDebugDraw.js
@@ -27,6 +27,9 @@ const PTM_RATIO = require('../CCPhysicsTypes').PTM_RATIO;
let _tmp_vec2 = cc.v2();
+let GREEN_COLOR = cc.Color.GREEN;
+let RED_COLOR = cc.Color.RED;
+
function PhysicsDebugDraw (drawer) {
b2.Draw.call(this);
this._drawer = drawer;
@@ -101,6 +104,34 @@ cc.js.mixin(PhysicsDebugDraw.prototype, {
drawer.stroke();
},
+ DrawTransform (xf) {
+ var drawer = this._drawer;
+
+ drawer.strokeColor = RED_COLOR;
+
+ _tmp_vec2.x = _tmp_vec2.y = 0;
+ b2.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
+ drawer.moveTo(_tmp_vec2.x * PTM_RATIO, _tmp_vec2.y * PTM_RATIO);
+
+ _tmp_vec2.x = 1; _tmp_vec2.y = 0;
+ b2.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
+ drawer.lineTo(_tmp_vec2.x * PTM_RATIO, _tmp_vec2.y * PTM_RATIO);
+
+ drawer.stroke();
+
+ drawer.strokeColor = GREEN_COLOR;
+
+ _tmp_vec2.x = _tmp_vec2.y = 0;
+ b2.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
+ drawer.moveTo(_tmp_vec2.x * PTM_RATIO, _tmp_vec2.y * PTM_RATIO);
+
+ _tmp_vec2.x = 0; _tmp_vec2.y = 1;
+ b2.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2);
+ drawer.lineTo(_tmp_vec2.x * PTM_RATIO, _tmp_vec2.y * PTM_RATIO);
+
+ drawer.stroke();
+ },
+
DrawPoint (center, radius, color) {
},
diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js
index 25650c58a3..d3d6486b7a 100644
--- a/cocos2d/core/platform/CCClass.js
+++ b/cocos2d/core/platform/CCClass.js
@@ -151,6 +151,9 @@ function defineProp (cls, className, propName, val, es6) {
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i];
Attr.attr(cls, propName, attr);
+ if (attr['serializable'] === false) {
+ pushUnique(cls.__values__, propName);
+ }
// register callback
if (attr._onAfterProp) {
onAfterProp.push(attr._onAfterProp);
@@ -184,11 +187,9 @@ function defineGetSet (cls, name, propName, val, es6) {
}
attrs.length = 0;
- const ForceSerializable = false;
- if (!ForceSerializable) {
- Attr.setClassAttr(cls, propName, 'serializable', false);
- }
- if (ForceSerializable || CC_DEV) {
+ Attr.setClassAttr(cls, propName, 'serializable', false);
+
+ if (CC_DEV) {
// 不论是否 visible 都要添加到 props,否则 asset watcher 不能正常工作
appendProp(cls, propName);
}
@@ -393,14 +394,14 @@ function normalizeClassName_DEV (className) {
return DefaultName;
}
-function getNewValueTypeCode (value) {
+function getNewValueTypeCodeJit (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 (typeof propVal === 'object') {
+ if (CC_DEV && typeof propVal === 'object') {
cc.errorID(3641, clsName);
return 'new ' + clsName + '()';
}
@@ -412,23 +413,7 @@ function getNewValueTypeCode (value) {
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 (typeof propVal === 'object') {
- cc.errorID(3641, clsName);
- return res;
- }
- res[prop] = propVal;
- }
- return res;
-}
-
-// TODO - move escapeForJS, IDENTIFIER_RE, getNewValueTypeCode to misc.js or a new source file
+// TODO - move escapeForJS, IDENTIFIER_RE, getNewValueTypeCodeJit to misc.js or a new source file
// convert a normal string including newlines, quotes and unicode characters into a string literal
// ready to use in JavaScript source
@@ -459,7 +444,7 @@ function getInitPropsJit (attrs, propList) {
var def = attrs[attrKey];
if (typeof def === 'object' && def) {
if (def instanceof cc.ValueType) {
- expression = getNewValueTypeCode(def);
+ expression = getNewValueTypeCodeJit(def);
}
else if (Array.isArray(def)) {
expression = '[]';
@@ -505,53 +490,65 @@ function getInitPropsJit (attrs, propList) {
}
function getInitProps (attrs, propList) {
- // functions for generated code
+ var advancedProps = [];
+ var advancedValues = [];
+ var simpleProps = [];
+ var simpleValues = [];
- 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) { // getter does not have default
- var expression;
- var def = attrs[attrKey];
- if (typeof def === 'object' && def) {
- if (def instanceof cc.ValueType) {
- expression = getNewValueType(def);
- }
- else if (Array.isArray(def)) {
- expression = [];
- }
- else {
- expression = {};
- }
+ for (var i = 0; i < propList.length; ++i) {
+ var prop = propList[i];
+ var attrKey = prop + DELIMETER + 'default';
+ if (attrKey in attrs) { // getter does not have default
+ var def = attrs[attrKey];
+ if ((typeof def === 'object' && def) || typeof def === 'function') {
+ advancedProps.push(prop);
+ advancedValues.push(def);
+ }
+ else {
+ // number, boolean, null, undefined, string
+ simpleProps.push(prop);
+ simpleValues.push(def);
+ }
+ }
+ }
+
+ return function () {
+ for (let i = 0; i < simpleProps.length; ++i) {
+ this[simpleProps[i]] = simpleValues[i];
+ }
+ for (let i = 0; i < advancedProps.length; i++) {
+ let prop = advancedProps[i];
+ var expression;
+ var def = advancedValues[i];
+ if (typeof def === 'object') {
+ if (def instanceof cc.ValueType) {
+ expression = def.clone();
}
- else if (typeof def === 'function') {
- var index = F.length;
- F.push(def);
- expression = F[index]();
- if (CC_EDITOR) {
- try {
- this[prop] = expression;
- }
- catch(err) {
- cc._throw(e);
- }
+ else if (Array.isArray(def)) {
+ expression = [];
+ }
+ else {
+ expression = {};
+ }
+ }
+ else {
+ // def is function
+ if (CC_EDITOR) {
+ try {
+ expression = def();
+ }
+ catch (err) {
+ cc._throw(e);
continue;
}
}
else {
- // number, boolean, null, undefined, string
- expression = def;
+ expression = def();
}
-
- this[prop] = expression;
}
+ this[prop] = expression;
}
- }
-
- return func;
+ };
}
// simple test variable name
@@ -590,7 +587,7 @@ var _createCtor = CC_SUPPORT_JIT ? function (ctors, baseClass, className, option
// call user constructors
var ctorLen = ctors.length;
if (ctorLen > 0) {
- var useTryCatch = ! (className && className.startsWith('cc.'));
+ var useTryCatch = CC_DEV && ! (className && className.startsWith('cc.'));
if (useTryCatch) {
body += 'try{\n';
}
@@ -615,46 +612,61 @@ var _createCtor = CC_SUPPORT_JIT ? function (ctors, baseClass, className, option
return Function(body)();
} : function (ctors, baseClass, className, options) {
var superCallBounded = baseClass && boundSuperCalls(baseClass, options, className);
+ var ctorLen = ctors.length;
- return function CCClass () {
+ var Class;
+
+ if (ctorLen > 0) {
if (superCallBounded) {
- this._super=null;
- }
-
- this.__initProps__(CCClass);
-
- // call user constructors
- var ctorLen = ctors.length;
- var cs = CCClass.__ctors__;
- if (ctorLen > 0) {
- var useTryCatch = ! (className && className.startsWith('cc.'));
- if (useTryCatch) {
- try {
- if (ctorLen === 1) {
- cs[0].apply(this, arguments);
- }
- else {
- for (let i = 0; i < ctorLen; i++) {
- cs[i].apply(this, arguments);
- }
- }
- }
- catch(e) {
- cc._throw(e);
- }
+ if (ctorLen === 2) {
+ // User Component
+ Class = function () {
+ this._super = null;
+ this.__initProps__(Class);
+ ctors[0].apply(this, arguments);
+ ctors[1].apply(this, arguments);
+ };
}
else {
- if (ctorLen === 1) {
- cs[0].apply(this, arguments);
- }
- else {
- for (let i = 0; i < ctorLen; i++) {
- cs[i].apply(this, arguments);
+ Class = function () {
+ this._super = null;
+ this.__initProps__(Class);
+ for (let i = 0; i < ctors.length; ++i) {
+ ctors[i].apply(this, arguments);
}
- }
+ };
}
}
- };
+ else {
+ if (ctorLen === 3) {
+ // Node
+ Class = function () {
+ this.__initProps__(Class);
+ ctors[0].apply(this, arguments);
+ ctors[1].apply(this, arguments);
+ ctors[2].apply(this, arguments);
+ };
+ }
+ else {
+ Class = function () {
+ this.__initProps__(Class);
+ var ctors = Class.__ctors__;
+ for (let i = 0; i < ctors.length; ++i) {
+ ctors[i].apply(this, arguments);
+ }
+ };
+ }
+ }
+ }
+ else {
+ Class = function () {
+ if (superCallBounded) {
+ this._super = null;
+ }
+ this.__initProps__(Class);
+ };
+ }
+ return Class;
};
function _validateCtor_DEV (ctor, baseClass, className, options) {
@@ -817,6 +829,11 @@ function declareProperties (cls, className, properties, baseClass, mixins, es6)
}
}
}
+
+ var attrs = Attr.getClassAttrs(cls);
+ cls.__values__ = cls.__props__.filter(function (prop) {
+ return attrs[prop + DELIMETER + 'serializable'] !== false;
+ });
}
/**
@@ -943,7 +960,7 @@ function CCClass (options) {
}
else {
deferredInitializer.push({cls: cls, props: properties, mixins: mixins});
- cls.__props__ = null;
+ cls.__props__ = cls.__values__ = null;
}
}
else {
@@ -1019,7 +1036,7 @@ CCClass._isCCClass = function (constructor) {
CCClass._fastDefine = function (className, constructor, serializableFields) {
js.setClassName(className, constructor);
//constructor.__ctors__ = constructor.__ctors__ || null;
- var props = constructor.__props__ = Object.keys(serializableFields);
+ var props = constructor.__props__ = constructor.__values__ = Object.keys(serializableFields);
var attrProtos = Attr.getClassAttrsProto(constructor);
for (var i = 0; i < props.length; i++) {
var key = props[i];
@@ -1229,7 +1246,7 @@ module.exports = {
return Array.isArray(defaultVal);
},
fastDefine: CCClass._fastDefine,
- getNewValueTypeCode,
+ getNewValueTypeCode: CC_SUPPORT_JIT && getNewValueTypeCodeJit,
IDENTIFIER_RE,
escapeForJS,
getDefault: getDefault
diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js
index 90fcbe2623..55121b8fbd 100644
--- a/cocos2d/core/platform/CCMacro.js
+++ b/cocos2d/core/platform/CCMacro.js
@@ -192,8 +192,8 @@ cc.macro = {
* This formula prevents artifacts by using 99% of the texture.
* The "correct" way to prevent artifacts is by expand the texture's border with the same color by 1 pixel
*
- * Affected nodes:
- * - _ccsg.TMXLayer
+ * Affected component:
+ * - cc.TMXLayer
*
* Enabled by default. To disabled set it to 0.
* To modify it, in Web engine please refer to CCMacro.js, in JSB please refer to CCConfig.h
@@ -325,6 +325,24 @@ cc.macro = {
* @default false
*/
ENABLE_CULLING: false,
+
+ /**
+ * !#en
+ * Whether or not clear dom Image object cache after uploading to gl texture.
+ * Concretely, we are setting image.src to empty string to release the cache.
+ * Normally you don't need to enable this option, because on web the Image object doesn't consume too much memory.
+ * But on Wechat Game platform, the current version cache decoded data in Image object, which has high memory usage.
+ * So we enabled this option by default on Wechat, so that we can release Image cache immediately after uploaded to GPU.
+ * !#zh
+ * 是否在将贴图上传至 GPU 之后删除 DOM Image 缓存。
+ * 具体来说,我们通过设置 image.src 为空字符串来释放这部分内存。
+ * 正常情况下,你不需要开启这个选项,因为在 web 平台,Image 对象所占用的内存很小。
+ * 但是在微信小游戏平台的当前版本,Image 对象会缓存解码后的图片数据,它所占用的内存空间很大。
+ * 所以我们在微信平台默认开启了这个选项,这样我们就可以在上传 GL 贴图之后立即释放 Image 对象的内存,避免过高的内存占用。
+ * @property {Boolean} CLEANUP_IMAGE_CACHE
+ * @default false
+ */
+ CLEANUP_IMAGE_CACHE: false,
};
js.getset(cc.macro, 'ENABLE_3D', function () {
diff --git a/cocos2d/core/platform/CCObject.js b/cocos2d/core/platform/CCObject.js
index 285750db15..37eb6dddbc 100644
--- a/cocos2d/core/platform/CCObject.js
+++ b/cocos2d/core/platform/CCObject.js
@@ -349,9 +349,15 @@ if (CC_EDITOR || CC_TEST) {
}
function compileDestruct (obj, ctor) {
+ var shouldSkipId = obj instanceof cc._BaseNode || obj instanceof cc.Component;
+ var idToSkip = shouldSkipId ? '_id' : null;
+
var key, propsToReset = {};
for (key in obj) {
if (obj.hasOwnProperty(key)) {
+ if (key === idToSkip) {
+ continue;
+ }
switch (typeof obj[key]) {
case 'string':
propsToReset[key] = '';
@@ -371,6 +377,9 @@ function compileDestruct (obj, ctor) {
key = propList[i];
var attrKey = key + cc.Class.Attr.DELIMETER + 'default';
if (attrKey in attrs) {
+ if (shouldSkipId && key === '_id') {
+ continue;
+ }
switch (typeof attrs[attrKey]) {
case 'string':
propsToReset[key] = '';
@@ -386,15 +395,11 @@ function compileDestruct (obj, ctor) {
}
}
}
- // compile code
- var skipId = obj instanceof cc._BaseNode || obj instanceof cc.Component;
if (CC_SUPPORT_JIT) {
+ // compile code
var func = '';
for (key in propsToReset) {
- if (skipId && key === '_id') {
- continue;
- }
var statement;
if (CCClass.IDENTIFIER_RE.test(key)) {
statement = 'o.' + key + '=';
@@ -412,10 +417,7 @@ function compileDestruct (obj, ctor) {
}
else {
return function (o) {
- for (key in propsToReset) {
- if (skipId && key === '_id') {
- continue;
- }
+ for (var key in propsToReset) {
o[key] = propsToReset[key];
}
};
diff --git a/cocos2d/core/platform/CCSAXParser.js b/cocos2d/core/platform/CCSAXParser.js
index cdd5d9e1fd..1273193064 100644
--- a/cocos2d/core/platform/CCSAXParser.js
+++ b/cocos2d/core/platform/CCSAXParser.js
@@ -32,7 +32,7 @@ var js = require('../platform/js');
* @class saxParser
*/
cc.SAXParser = function () {
- if (window.DOMParser) {
+ if (!(CC_EDITOR && Editor.isMainProcess) && window.DOMParser) {
this._isSupportDOMParser = true;
this._parser = new DOMParser();
} else {
@@ -164,3 +164,8 @@ cc.saxParser = new cc.SAXParser();
* A Plist Parser
*/
cc.plistParser = new cc.PlistParser();
+
+module.exports = {
+ saxParser: cc.saxParser,
+ plistParser: cc.plistParser
+}
diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js
index 1bf04bbd2e..1baf4b8c4f 100644
--- a/cocos2d/core/platform/CCView.js
+++ b/cocos2d/core/platform/CCView.js
@@ -30,10 +30,6 @@ const js = require('../platform/js');
const renderer = require('../renderer');
require('../platform/CCClass');
-function isWeChatGame () {
- return window['wx'];
-}
-
var __BrowserGetter = {
init: function(){
if (!CC_WECHATGAME && !CC_QQPLAY) {
@@ -77,13 +73,6 @@ if (CC_QQPLAY) {
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_SOUGOU:
case cc.sys.BROWSER_TYPE_UC:
__BrowserGetter.availWidth = function(frame){
diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js
index 00f8f4624d..1223b531cb 100644
--- a/cocos2d/core/platform/deserialize.js
+++ b/cocos2d/core/platform/deserialize.js
@@ -25,7 +25,6 @@
****************************************************************************/
var js = require('./js');
-var CCObject = require('./CCObject');
var Attr = require('./attribute');
var CCClass = require('./CCClass');
var misc = require('../utils/misc');
@@ -432,7 +431,7 @@ var _Deserializer = (function () {
}
};
- var compileObjectType = CC_SUPPORT_JIT ? function (sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue, stillUseUrl) {
+ function compileObjectTypeJit (sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue, stillUseUrl) {
if (defaultValue instanceof cc.ValueType) {
// fast case
if (!assumeHavePropIfIsValue) {
@@ -446,55 +445,24 @@ var _Deserializer = (function () {
}
else {
sources.push('if(prop){');
- if (CC_EDITOR || CC_TEST) {
- sources.push('s._deserializeObjField(o,prop,' + propNameLiteralToSet + ',t&&o,' + !!stillUseUrl + ');');
- }
- else {
- sources.push('s._deserializeObjField(o,prop,' + propNameLiteralToSet + ',null,' + !!stillUseUrl + ');');
- }
+ sources.push('s._deserializeObjField(o,prop,' +
+ propNameLiteralToSet +
+ ((CC_EDITOR || CC_TEST) ? ',t&&o,' : ',null,') +
+ !!stillUseUrl +
+ ');');
sources.push('}else o' + accessorToSet + '=null;');
}
- } : function (s, o, t, prop, defaultValue, propName, assumeHavePropIfIsValue, stillUseUrl) {
- if (defaultValue instanceof cc.ValueType) {
- var ctor = defaultValue.constructor;
-
- if (assumeHavePropIfIsValue) {
- s._deserializeTypedObject(o[propName], prop, ctor);
- }
- else {
- if (prop) {
- s._deserializeTypedObject(o[propName], prop, ctor);
- }
- else {
- o[propName] = null;
- }
- }
- }
- else {
- if (prop) {
- if (CC_EDITOR || CC_TEST) {
- s._deserializeObjField(o, prop, propName, t&&o, stillUseUrl);
- }
- else {
- s._deserializeObjField(o, prop, propName, null, stillUseUrl);
- }
- }
- else {
- o[propName] = null;
- }
- }
- };
+ }
var compileDeserialize = CC_SUPPORT_JIT ? function (self, klass) {
var TYPE = Attr.DELIMETER + 'type';
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 props = klass.__values__;
// self, obj, serializedData, klass, target
var sources = [
'var prop;'
@@ -506,9 +474,6 @@ var _Deserializer = (function () {
if ((CC_PREVIEW || (CC_EDITOR && self._ignoreEditorOnly)) && attrs[propName + EDITOR_ONLY]) {
continue; // skip editor only if in preview
}
- if (attrs[propName + SERIALIZABLE] === false) {
- continue; // skip nonSerialized
- }
var accessorToSet, propNameLiteralToSet;
if (CCClass.IDENTIFIER_RE.test(propName)) {
@@ -557,14 +522,14 @@ var _Deserializer = (function () {
sources.push(`o${accessorToSet}=prop;`);
}
else {
- compileObjectType(sources, defaultValue, accessorToSet, propNameLiteralToSet, true, stillUseUrl);
+ compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, true, stillUseUrl);
}
}
else {
sources.push(`if(typeof ${CC_JSB ? '(prop)' : 'prop'}!=="object"){` +
'o' + accessorToSet + '=prop;' +
'}else{');
- compileObjectType(sources, defaultValue, accessorToSet, propNameLiteralToSet, false, stillUseUrl);
+ compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, false, stillUseUrl);
sources.push('}');
}
sources.push('}');
@@ -588,76 +553,126 @@ var _Deserializer = (function () {
}
return Function('s', 'o', 'd', 'k', 't', sources.join(''));
} : function (self, klass) {
- var TYPE = Attr.DELIMETER + 'type';
- 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 fastMode = misc.BUILTIN_CLASSID_RE.test(js._getClassId(klass));
+ var shouldCopyId = cc.js.isChildClassOf(klass, cc._BaseNode) || cc.js.isChildClassOf(klass, cc.Component);
+ var shouldCopyRawData;
+
+ var simpleProps = [];
+ var simplePropsToRead = simpleProps;
+ var advancedProps = [];
+ var advancedPropsToRead = advancedProps;
+ var advancedPropsUseUrl = [];
+ var advancedPropsValueType = [];
+
+ (function () {
+ var props = klass.__values__;
+ shouldCopyRawData = props[props.length - 1] === '_$erialized';
+
+ var attrs = Attr.getClassAttrs(klass);
+ var TYPE = Attr.DELIMETER + 'type';
+ var DEFAULT = Attr.DELIMETER + 'default';
+ var SAVE_URL_AS_ASSET = Attr.DELIMETER + 'saveUrlAsAsset';
+ var FORMERLY_SERIALIZED_AS = Attr.DELIMETER + 'formerlySerializedAs';
- return function (s, o, d, k, t) {
- var prop;
for (var p = 0; p < props.length; p++) {
var propName = props[p];
- if (attrs[propName + SERIALIZABLE] === false) {
- continue; // skip nonSerialized
- }
-
var propNameToRead = propName;
if (attrs[propName + FORMERLY_SERIALIZED_AS]) {
propNameToRead = attrs[propName + FORMERLY_SERIALIZED_AS];
}
+ var stillUseUrl = attrs[propName + SAVE_URL_AS_ASSET];
+ // function undefined object(null) string boolean number
+ var defaultValue = CCClass.getDefault(attrs[propName + DEFAULT]);
+ var isPrimitiveType = false;
+ if (fastMode) {
+ var userType = attrs[propName + TYPE];
+ if (defaultValue === undefined && userType) {
+ isPrimitiveType = userType === cc.String ||
+ userType === cc.Integer ||
+ userType === cc.Float ||
+ userType === cc.Boolean;
+ }
+ else {
+ var defaultType = typeof defaultValue;
+ isPrimitiveType = (defaultType === 'string' && !stillUseUrl) ||
+ defaultType === 'number' ||
+ defaultType === 'boolean';
+ }
+ }
+ if (fastMode && isPrimitiveType) {
+ if (propNameToRead !== propName && simplePropsToRead === simpleProps) {
+ simplePropsToRead = simpleProps.slice();
+ }
+ simpleProps.push(propName);
+ if (simplePropsToRead !== simpleProps) {
+ simplePropsToRead.push(propNameToRead);
+ }
+ }
+ else {
+ if (propNameToRead !== propName && advancedPropsToRead === advancedProps) {
+ advancedPropsToRead = advancedProps.slice();
+ }
+ advancedProps.push(propName);
+ if (advancedPropsToRead !== advancedProps) {
+ advancedPropsToRead.push(propNameToRead);
+ }
+ advancedPropsUseUrl.push(stillUseUrl);
+ advancedPropsValueType.push((defaultValue instanceof cc.ValueType) && defaultValue.constructor);
+ }
+ }
+ })();
- prop = d[propNameToRead];
-
+ return function (s, o, d, k, t) {
+ for (let i = 0; i < simpleProps.length; ++i) {
+ let prop = d[simplePropsToRead[i]];
if (prop !== undefined) {
- var stillUseUrl = attrs[propName + SAVE_URL_AS_ASSET];
- // function undefined object(null) string boolean number
- var defaultValue = CCClass.getDefault(attrs[propName + DEFAULT]);
- if (fastMode) {
- var isPrimitiveType;
- var userType = attrs[propName + TYPE];
- if (defaultValue === undefined && userType) {
- isPrimitiveType = userType === cc.String ||
- userType === cc.Integer ||
- userType === cc.Float ||
- userType === cc.Boolean;
+ o[simpleProps[i]] = prop;
+ }
+ }
+ for (let i = 0; i < advancedProps.length; ++i) {
+ let propName = advancedProps[i];
+ var prop = d[advancedPropsToRead[i]];
+ if (prop === undefined) {
+ continue;
+ }
+ if (!fastMode && typeof prop !== 'object') {
+ o[propName] = prop;
+ }
+ else {
+ // fastMode (so will not simpleProp) or object
+ var valueTypeCtor = advancedPropsValueType[i];
+ if (valueTypeCtor) {
+ if (fastMode || prop) {
+ s._deserializeTypedObject(o[propName], prop, valueTypeCtor);
}
else {
- var defaultType = typeof defaultValue;
- isPrimitiveType = (defaultType === 'string' && !stillUseUrl) ||
- defaultType === 'number' ||
- defaultType === 'boolean';
- }
-
- if (isPrimitiveType) {
- o[propName] = prop;
- }
- else {
- compileObjectType(s, o, t, prop, defaultValue, propName, true, stillUseUrl);
+ o[propName] = null;
}
}
else {
- if (typeof prop !== 'object') {
- o[propName] = prop;
+ if (prop) {
+ s._deserializeObjField(
+ o,
+ prop,
+ propName,
+ (CC_EDITOR || CC_TEST) ? (t && o) : null,
+ advancedPropsUseUrl[i],
+ );
}
else {
- compileObjectType(s, o, t, prop, defaultValue, propName, false, stillUseUrl);
+ o[propName] = null;
}
}
}
}
- if (((o instanceof cc._BaseNode) || (o instanceof cc.Component)) && d._id) {
+ if (shouldCopyId && d._id) {
o._id = d._id;
}
- if (props[props.length - 1] === '_$erialized') {
+ if (shouldCopyRawData) {
// deep copy original serialized data
- o._$erialized=JSON.parse(JSON.stringify(d));
+ o._$erialized = JSON.parse(JSON.stringify(d));
// parse the serialized data as primitive javascript object, so its __id__ will be dereferenced
- s._deserializePrimitiveObject(o._$erialized,d);
+ s._deserializePrimitiveObject(o._$erialized, d);
}
}
};
diff --git a/cocos2d/core/platform/instantiate-jit.js b/cocos2d/core/platform/instantiate-jit.js
index 02f6991214..e4cf8baa92 100644
--- a/cocos2d/core/platform/instantiate-jit.js
+++ b/cocos2d/core/platform/instantiate-jit.js
@@ -34,7 +34,6 @@ 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;
@@ -317,27 +316,25 @@ proto.setValueType = function (codeArray, defaultValue, srcValue, targetExpressi
};
proto.enumerateCCClass = function (codeArray, obj, klass) {
- var props = klass.__props__;
+ var props = klass.__values__;
var attrs = Attr.getClassAttrs(klass);
for (var p = 0; p < props.length; p++) {
var key = props[p];
- if (attrs[key + SERIALIZABLE] !== false) {
- var val = obj[key];
- var defaultValue = attrs[key + DEFAULT];
- if (equalsToDefault(defaultValue, val)) {
+ var val = obj[key];
+ var defaultValue = attrs[key + DEFAULT];
+ if (equalsToDefault(defaultValue, val)) {
+ continue;
+ }
+ if (typeof val === 'object' && val instanceof cc.ValueType) {
+ defaultValue = CCClass.getDefault(defaultValue);
+ if (defaultValue && defaultValue.constructor === val.constructor) {
+ // fast case
+ var targetExpression = LOCAL_OBJ + getPropAccessor(key);
+ this.setValueType(codeArray, defaultValue, val, targetExpression);
continue;
}
- if (typeof val === 'object' && val instanceof cc.ValueType) {
- var defaultValue = CCClass.getDefault(defaultValue);
- if ((defaultValue && defaultValue.constructor) === val.constructor) {
- // fast case
- var targetExpression = LOCAL_OBJ + getPropAccessor(key);
- this.setValueType(codeArray, defaultValue, val, targetExpression);
- continue;
- }
- }
- this.setObjProp(codeArray, obj, key, val);
}
+ this.setObjProp(codeArray, obj, key, val);
}
};
diff --git a/cocos2d/core/platform/instantiate.js b/cocos2d/core/platform/instantiate.js
index b16d699928..61681c5fb5 100644
--- a/cocos2d/core/platform/instantiate.js
+++ b/cocos2d/core/platform/instantiate.js
@@ -25,9 +25,9 @@
****************************************************************************/
var CCObject = require('./CCObject');
+var CCValueType = require('../value-types/value-type');
var Destroyed = CCObject.Flags.Destroyed;
var PersistentMask = CCObject.Flags.PersistentMask;
-var Attr = require('./attribute');
var _isDomNode = require('./utils').isDomNode;
/**
@@ -157,23 +157,26 @@ function doInstantiate (obj, parent) {
return clone;
}
-var SERIALIZABLE = Attr.DELIMETER + 'serializable';
// @param {Object} obj - The object to instantiate, typeof must be 'object' and should not be an array.
function enumerateCCClass (klass, obj, clone, parent) {
- var props = klass.__props__;
- var attrs = Attr.getClassAttrs(klass);
+ var props = klass.__values__;
for (var p = 0; p < props.length; p++) {
var key = props[p];
- if (attrs[key + SERIALIZABLE] !== false) {
- var value = obj[key];
- if (typeof value === 'object' && value) {
- clone[key] = value._iN$t || instantiateObj(value, parent);
+ var value = obj[key];
+ if (typeof value === 'object' && value) {
+ var initValue = clone[key];
+ if (initValue instanceof CCValueType &&
+ initValue.constructor === value.constructor) {
+ initValue.set(value);
}
else {
- clone[key] = value;
+ clone[key] = value._iN$t || instantiateObj(value, parent);
}
}
+ else {
+ clone[key] = value;
+ }
}
}
@@ -217,7 +220,7 @@ function enumerateObject (obj, clone, parent) {
* @return {Object|Array} - the original non-nil object, typeof must be 'object'
*/
function instantiateObj (obj, parent) {
- if (obj instanceof cc.ValueType) {
+ if (obj instanceof CCValueType) {
return obj.clone();
}
if (obj instanceof cc.Asset) {
diff --git a/cocos2d/core/renderer/render-engine.js b/cocos2d/core/renderer/render-engine.js
index 44a2ea0b3c..2a83954a7a 100644
--- a/cocos2d/core/renderer/render-engine.js
+++ b/cocos2d/core/renderer/render-engine.js
@@ -9431,7 +9431,7 @@ function _commitTextures(gl, cur, next) {
for (var i = 0; i < next.maxTextureSlot + 1; ++i) {
if (cur.textureUnits[i] !== next.textureUnits[i]) {
var texture = next.textureUnits[i];
- if (texture !== undefined && texture._glID !== -1) {
+ if (texture && texture._glID !== -1) {
gl.activeTexture(gl.TEXTURE0 + i);
gl.bindTexture(texture._target, texture._glID);
}
@@ -13389,8 +13389,11 @@ Base.prototype._draw = function _draw (item) {
node.getWorldMatrix(_m4_tmp$2);
device.setUniform('model', mat4.array(_float16_pool.add(), _m4_tmp$2));
- mat3.transpose(_m3_tmp$1, mat3.invert(_m3_tmp$1, mat3.fromMat4(_m3_tmp$1, _m4_tmp$2)));
- device.setUniform('normalMatrix', mat3.array(_float9_pool.add(), _m3_tmp$1));
+ var inverse = mat3.invert(_m3_tmp$1, mat3.fromMat4(_m3_tmp$1, _m4_tmp$2));
+ if (inverse) {
+ mat3.transpose(_m3_tmp$1, inverse);
+ device.setUniform('normalMatrix', mat3.array(_float9_pool.add(), _m3_tmp$1));
+ }
// }
// set technique uniforms
diff --git a/cocos2d/core/renderer/utils/label/ttf.js b/cocos2d/core/renderer/utils/label/ttf.js
index e52ba79304..5cea483c1f 100644
--- a/cocos2d/core/renderer/utils/label/ttf.js
+++ b/cocos2d/core/renderer/utils/label/ttf.js
@@ -26,6 +26,7 @@
const macro = require('../../../platform/CCMacro');
const utils = require('../../../utils/text-utils');
+const Component = require('../../../components/CCComponent');
const Label = require('../../../components/CCLabel');
const LabelOutline = require('../../../components/CCLabelOutline');
const Overflow = Label.Overflow;
@@ -33,6 +34,7 @@ const TextUtils = utils.TextUtils;
const CustomFontLoader = utils.CustomFontLoader;
const WHITE = cc.Color.WHITE;
+const OUTLINE_SUPPORTED = cc.js.isChildClassOf(LabelOutline, Component);
let _context = null;
let _canvas = null;
@@ -204,7 +206,7 @@ module.exports = {
}
// outline
- let outline = (LabelOutline instanceof cc.Component) && comp.getComponent(LabelOutline);
+ let outline = OUTLINE_SUPPORTED && comp.getComponent(LabelOutline);
if (outline && outline.enabled) {
_isOutlined = true;
_margin = _outlineWidth = outline.width;
@@ -262,7 +264,6 @@ module.exports = {
for (let i = 0; i < _splitedStrings.length; ++i) {
if (_isOutlined) {
let strokeColor = _outlineColor || WHITE;
- _context.globalCompositeOperation = 'source-over';
_context.strokeStyle = `rgba(${strokeColor.r}, ${strokeColor.g}, ${strokeColor.b}, ${strokeColor.a / 255})`;
_context.lineWidth = _outlineWidth * 2;
_context.strokeText(_splitedStrings[i], startPosition.x, startPosition.y + i * lineHeight);
diff --git a/cocos2d/core/renderer/webgl/assemblers/graphics/index.js b/cocos2d/core/renderer/webgl/assemblers/graphics/index.js
index f08b1eaf08..96c2b737e4 100644
--- a/cocos2d/core/renderer/webgl/assemblers/graphics/index.js
+++ b/cocos2d/core/renderer/webgl/assemblers/graphics/index.js
@@ -95,12 +95,9 @@ let graphicsAssembler = {
nodeA = nodeColor.a / 255;
let buffer = renderer.getBuffer('mesh', vfmtPosUvColor),
- vertexOffset = buffer.byteOffset >> 2,
- vbuf = buffer._vData,
- uintbuf = buffer._uintVData;
+ vertexOffset = buffer.byteOffset >> 2;
- let ibuf = buffer._iData,
- indiceOffset = buffer.indiceOffset,
+ let indiceOffset = buffer.indiceOffset,
vertexId = buffer.vertexOffset;
let renderDatas = graphics._impl._renderDatas;
@@ -110,6 +107,11 @@ let graphicsAssembler = {
buffer.request(renderData.vertexCount, renderData.indiceCount);
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData,
+ ibuf = buffer._iData,
+ uintbuf = buffer._uintVData;
+
for (let i = 0, l = data.length; i < l; i++) {
vbuf[vertexOffset++] = data[i].x * a + data[i].y * c + tx;
vbuf[vertexOffset++] = data[i].x * b + data[i].y * d + ty;
diff --git a/cocos2d/core/renderer/webgl/assemblers/label/bmfont.js b/cocos2d/core/renderer/webgl/assemblers/label/bmfont.js
index 82354edda5..c4b985ee3c 100644
--- a/cocos2d/core/renderer/webgl/assemblers/label/bmfont.js
+++ b/cocos2d/core/renderer/webgl/assemblers/label/bmfont.js
@@ -42,12 +42,14 @@ module.exports = js.addon({
tx = matrix.m12, ty = matrix.m13;
let buffer = renderer._quadBuffer,
- vertexOffset = buffer.byteOffset >> 2,
- vbuf = buffer._vData;
+ vertexOffset = buffer.byteOffset >> 2;
let vertexCount = renderData.vertexCount;
buffer.request(vertexCount, renderData.indiceCount);
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData;
+
for (let i = 0; i < vertexCount; i++) {
let vert = data[i];
vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx;
diff --git a/cocos2d/core/renderer/webgl/assemblers/label/ttf.js b/cocos2d/core/renderer/webgl/assemblers/label/ttf.js
index 028790dfbb..0d980acdc1 100644
--- a/cocos2d/core/renderer/webgl/assemblers/label/ttf.js
+++ b/cocos2d/core/renderer/webgl/assemblers/label/ttf.js
@@ -54,11 +54,13 @@ module.exports = js.addon({
tx = matrix.m12, ty = matrix.m13;
let buffer = renderer._quadBuffer,
- vertexOffset = buffer.byteOffset >> 2,
- vbuf = buffer._vData;
+ vertexOffset = buffer.byteOffset >> 2;
buffer.request(4, 6);
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData;
+
// vertex
for (let i = 0; i < 4; i++) {
let vert = data[i];
diff --git a/cocos2d/core/renderer/webgl/assemblers/motion-streak.js b/cocos2d/core/renderer/webgl/assemblers/motion-streak.js
index 0388f18a29..f3bade69cd 100644
--- a/cocos2d/core/renderer/webgl/assemblers/motion-streak.js
+++ b/cocos2d/core/renderer/webgl/assemblers/motion-streak.js
@@ -197,15 +197,17 @@ var motionStreakAssembler = {
let buffer = renderer.getBuffer('mesh', vfmtPosUvColor),
vertexOffset = buffer.byteOffset >> 2,
- vbuf = buffer._vData,
- uintbuf = buffer._uintVData,
vertexCount = renderData.vertexCount;
- let ibuf = buffer._iData,
- indiceOffset = buffer.indiceOffset,
+ let indiceOffset = buffer.indiceOffset,
vertexId = buffer.vertexOffset;
buffer.request(vertexCount, renderData.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData,
+ ibuf = buffer._iData,
+ uintbuf = buffer._uintVData;
// vertex buffer
let vert;
diff --git a/cocos2d/core/renderer/webgl/assemblers/sprite/bar-filled.js b/cocos2d/core/renderer/webgl/assemblers/sprite/bar-filled.js
index daf6654324..3e9ac50584 100644
--- a/cocos2d/core/renderer/webgl/assemblers/sprite/bar-filled.js
+++ b/cocos2d/core/renderer/webgl/assemblers/sprite/bar-filled.js
@@ -229,11 +229,13 @@ module.exports = {
tx = matrix.m12, ty = matrix.m13;
let buffer = renderer._quadBuffer,
- vertexOffset = buffer.byteOffset >> 2,
- vbuf = buffer._vData;
+ vertexOffset = buffer.byteOffset >> 2;
buffer.request(4, 6);
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData;
+
// vertex
for (let i = 0; i < 4; i++) {
let vert = data[i];
diff --git a/cocos2d/core/renderer/webgl/assemblers/sprite/index.js b/cocos2d/core/renderer/webgl/assemblers/sprite/index.js
index ab8374ef77..c59947b09c 100644
--- a/cocos2d/core/renderer/webgl/assemblers/sprite/index.js
+++ b/cocos2d/core/renderer/webgl/assemblers/sprite/index.js
@@ -24,7 +24,6 @@
****************************************************************************/
const Sprite = require('../../../../components/CCSprite');
-const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
const SpriteType = Sprite.Type;
const FillType = Sprite.FillType;
diff --git a/cocos2d/core/renderer/webgl/assemblers/sprite/mesh.js b/cocos2d/core/renderer/webgl/assemblers/sprite/mesh.js
index aa92415fe3..5b10883ba2 100644
--- a/cocos2d/core/renderer/webgl/assemblers/sprite/mesh.js
+++ b/cocos2d/core/renderer/webgl/assemblers/sprite/mesh.js
@@ -170,15 +170,17 @@ const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
// buffer
let buffer = renderer._meshBuffer,
- vertexOffset = buffer.byteOffset >> 2,
- vbuf = buffer._vData;
+ vertexOffset = buffer.byteOffset >> 2;
- let ibuf = buffer._iData,
- indiceOffset = buffer.indiceOffset,
+ let indiceOffset = buffer.indiceOffset,
vertexId = buffer.vertexOffset;
buffer.request(renderData.vertexCount, renderData.indiceCount);
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData,
+ ibuf = buffer._iData;
+
for (let i = 0, l = renderData.vertexCount; i < l; i++) {
let vertice = data[i];
vbuf[vertexOffset++] = vertice.x;
diff --git a/cocos2d/core/renderer/webgl/assemblers/sprite/simple.js b/cocos2d/core/renderer/webgl/assemblers/sprite/simple.js
index b9e8a8b809..d583fe2555 100644
--- a/cocos2d/core/renderer/webgl/assemblers/sprite/simple.js
+++ b/cocos2d/core/renderer/webgl/assemblers/sprite/simple.js
@@ -23,7 +23,6 @@
THE SOFTWARE.
****************************************************************************/
-const js = require('../../../../platform/js');
const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
module.exports = {
@@ -59,11 +58,13 @@ module.exports = {
tx = matrix.m12, ty = matrix.m13;
let buffer = renderer._quadBuffer,
- vertexOffset = buffer.byteOffset >> 2,
- vbuf = buffer._vData;
+ vertexOffset = buffer.byteOffset >> 2;
buffer.request(4, 6);
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData;
+
// get uv from sprite frame directly
let uv = sprite._spriteFrame.uv;
vbuf[vertexOffset+2] = uv[0];
diff --git a/cocos2d/core/renderer/webgl/assemblers/sprite/sliced.js b/cocos2d/core/renderer/webgl/assemblers/sprite/sliced.js
index 8c1e2234bd..f8cd07c266 100644
--- a/cocos2d/core/renderer/webgl/assemblers/sprite/sliced.js
+++ b/cocos2d/core/renderer/webgl/assemblers/sprite/sliced.js
@@ -23,9 +23,7 @@
THE SOFTWARE.
****************************************************************************/
-const Sprite = require('../../../../components/CCSprite');
const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
-const FillType = Sprite.FillType;
module.exports = {
useModel: false,
@@ -73,7 +71,6 @@ module.exports = {
appx = node.anchorX * width, appy = node.anchorY * height;
let frame = sprite.spriteFrame;
- let rect = frame._rect;
let leftWidth = frame.insetLeft;
let rightWidth = frame.insetRight;
let topHeight = frame.insetTop;
@@ -106,22 +103,23 @@ module.exports = {
}
let renderData = sprite._renderData,
- data = renderData._data,
- node = sprite.node;
+ data = renderData._data;
let buffer = renderer._meshBuffer,
vertexOffset = buffer.byteOffset >> 2,
- vbuf = buffer._vData,
vertexCount = renderData.vertexCount;
- let ibuf = buffer._iData,
- indiceOffset = buffer.indiceOffset,
+ let indiceOffset = buffer.indiceOffset,
vertexId = buffer.vertexOffset;
let uvSliced = sprite.spriteFrame.uvSliced;
buffer.request(vertexCount, renderData.indiceCount);
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData,
+ ibuf = buffer._iData;
+
for (let i = 4; i < 20; ++i) {
let vert = data[i];
let uvs = uvSliced[i - 4];
diff --git a/cocos2d/core/renderer/webgl/assemblers/sprite/tiled.js b/cocos2d/core/renderer/webgl/assemblers/sprite/tiled.js
index 82d4ca87a6..029272817d 100644
--- a/cocos2d/core/renderer/webgl/assemblers/sprite/tiled.js
+++ b/cocos2d/core/renderer/webgl/assemblers/sprite/tiled.js
@@ -143,15 +143,17 @@ module.exports = {
// buffer
let buffer = renderer._meshBuffer,
- vertexOffset = buffer.byteOffset >> 2,
- vbuf = buffer._vData;
+ vertexOffset = buffer.byteOffset >> 2;
- let ibuf = buffer._iData,
- indiceOffset = buffer.indiceOffset,
+ let indiceOffset = buffer.indiceOffset,
vertexId = buffer.vertexOffset;
buffer.request(renderData.vertexCount, renderData.indiceCount);
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData,
+ ibuf = buffer._iData;
+
//
let rect = sprite.spriteFrame._rect;
let contentWidth = Math.abs(node.width);
diff --git a/cocos2d/core/renderer/webgl/render-component-walker.js b/cocos2d/core/renderer/webgl/render-component-walker.js
index 8e660c054a..1141e3b253 100644
--- a/cocos2d/core/renderer/webgl/render-component-walker.js
+++ b/cocos2d/core/renderer/webgl/render-component-walker.js
@@ -55,10 +55,10 @@ var RenderComponentWalker = function (device, renderScene) {
this._device = device;
this._stencilMgr = StencilManager.sharedManager;
+ this.walking = false;
this.material = empty_material;
this.cullingMask = 1;
- let defaultFormat = new gfx.VertexFormat([]);
this._iaPool = new RecyclePool(function () {
return new InputAssembler();
}, 16);
@@ -129,7 +129,7 @@ RenderComponentWalker.prototype = {
indiceStart = buffer.indiceStart,
indiceOffset = buffer.indiceOffset,
indiceCount = indiceOffset - indiceStart;
- if (!material || indiceCount <= 0) {
+ if (!this.walking || !material || indiceCount <= 0) {
return;
}
@@ -208,6 +208,7 @@ RenderComponentWalker.prototype = {
visit (scene) {
this.reset();
+ this.walking = true;
RenderFlow.render(scene);
@@ -217,6 +218,7 @@ RenderComponentWalker.prototype = {
for (let key in _buffers) {
_buffers[key].uploadData();
}
+ this.walking = false;
},
getBuffer (type, vertextFormat) {
diff --git a/cocos2d/core/renderer/webgl/stencil-manager.js b/cocos2d/core/renderer/webgl/stencil-manager.js
index d5c259305b..5e0c41776c 100644
--- a/cocos2d/core/renderer/webgl/stencil-manager.js
+++ b/cocos2d/core/renderer/webgl/stencil-manager.js
@@ -119,6 +119,7 @@ StencilManager.prototype = {
pass.setStencilFront(func, ref, stencilMask, failOp, zFailOp, zPassOp, writeMask);
pass.setStencilBack(func, ref, stencilMask, failOp, zFailOp, zPassOp, writeMask);
}
+ return effect;
},
pushMask (mask) {
diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js
index 037b60d7b4..c4cea7418f 100644
--- a/cocos2d/core/utils/base-node.js
+++ b/cocos2d/core/utils/base-node.js
@@ -554,7 +554,7 @@ var BaseNode = cc.Class({
* 对子树中的所有节点,包含当前节点,会执行两次回调,prefunc 会在访问它的子节点之前调用,postfunc 会在访问所有子节点之后调用。
* 这个函数的实现不是基于递归的,而是基于栈展开递归的方式。
* 请不要在 walk 过程中对任何其他的节点嵌套执行 walk。
- * @method Walk the child tree
+ * @method walk
* @param {Function} prefunc The callback to process node when reach the node for the first time
* @param {_BaseNode} prefunc.target The current visiting node
* @param {Function} postfunc The callback to process node when re-visit the node after walked all children in its sub tree
diff --git a/cocos2d/core/utils/polyfill-3d.js b/cocos2d/core/utils/polyfill-3d.js
index f18d01b52c..7263669444 100644
--- a/cocos2d/core/utils/polyfill-3d.js
+++ b/cocos2d/core/utils/polyfill-3d.js
@@ -248,6 +248,8 @@ cc._polyfill3D = module.exports = {
proto.setPosition = setPosition;
proto.getScale = getScale;
proto.setScale = setScale;
+ proto.getQuat = getQuat;
+ proto.setQuat = setQuat;
this.enabled = true;
}
},
diff --git a/cocos2d/core/value-types/color.js b/cocos2d/core/value-types/color.js
index 7024aa4066..ead48c05c2 100644
--- a/cocos2d/core/value-types/color.js
+++ b/cocos2d/core/value-types/color.js
@@ -549,7 +549,7 @@ var Color = (function () {
return hsv;
};
- proto.fromColor = function (color) {
+ proto.set = function (color) {
if (color._val) {
this._val = color._val;
}
diff --git a/cocos2d/core/value-types/quat.js b/cocos2d/core/value-types/quat.js
index d5015b1842..d8dc6c9f85 100644
--- a/cocos2d/core/value-types/quat.js
+++ b/cocos2d/core/value-types/quat.js
@@ -119,7 +119,7 @@ proto.getRoll = function () {
var sinr = 2.0 * (this.w * this.x + this.y * this.z);
var cosr = 1.0 - 2.0 * (this.x * this.x + this.y * this.y);
return 180 * Math.atan2(sinr, cosr) / Math.PI;
-}
+};
proto.getPitch = function () {
var sinp = 2.0 * (this.w * this.y - this.z * this.x);
@@ -127,13 +127,13 @@ proto.getPitch = function () {
pitch = sinp < -1 ? -1 : sinp;
pitch = 180 * Math.asin(pitch) / Math.PI;
return pitch;
-}
+};
proto.getYaw = function () {
var siny = 2.0 * (this.w * this.z + this.x * this.y);
var cosy = 1.0 - 2.0 * (this.y * this.y + this.z * this.z);
return 180 * Math.atan2(siny, cosy) / Math.PI;
-}
+};
/**
* !#en The convenience method to create a new {{#crossLink "Quat"}}cc.Quat{{/crossLink}}.
diff --git a/cocos2d/core/value-types/rect.js b/cocos2d/core/value-types/rect.js
index 84431b715a..4c620973c6 100644
--- a/cocos2d/core/value-types/rect.js
+++ b/cocos2d/core/value-types/rect.js
@@ -159,6 +159,13 @@ proto.lerp = function (to, ratio, out) {
return out;
};
+proto.set = function (source) {
+ this.x = source.x;
+ this.y = source.y;
+ this.width = source.width;
+ this.height = source.height;
+};
+
/**
* !#en Check whether the current rectangle intersects with the given one
* !#zh 当前矩形与指定矩形是否相交。
diff --git a/cocos2d/core/value-types/size.js b/cocos2d/core/value-types/size.js
index 789c58aefd..55de763f09 100644
--- a/cocos2d/core/value-types/size.js
+++ b/cocos2d/core/value-types/size.js
@@ -135,6 +135,11 @@ proto.lerp = function (to, ratio, out) {
return out;
};
+proto.set = function (source) {
+ this.width = source.width;
+ this.height = source.height;
+};
+
/**
* !#en TODO
* !#zh 转换为方便阅读的字符串。
diff --git a/cocos2d/core/value-types/value-type.js b/cocos2d/core/value-types/value-type.js
index 3a633003fa..3c24c351bf 100644
--- a/cocos2d/core/value-types/value-type.js
+++ b/cocos2d/core/value-types/value-type.js
@@ -77,6 +77,18 @@ if (CC_EDITOR) {
cc.errorID('0100', js.getClassName(this) + '.lerp');
return this.clone();
};
+
+ /**
+ * !#en
+ * Copys all the properties from another given object to this value.
+ * !#zh
+ * 从其它对象把所有属性复制到当前对象。
+ * @method set
+ * @param {ValueType} source - the source to copy
+ */
+ proto.set = function (source) {
+ cc.errorID('0100', js.getClassName(this) + '.set');
+ };
}
/**
diff --git a/cocos2d/core/value-types/vec2.js b/cocos2d/core/value-types/vec2.js
index 3abe4c2d67..c6ba141759 100644
--- a/cocos2d/core/value-types/vec2.js
+++ b/cocos2d/core/value-types/vec2.js
@@ -465,7 +465,6 @@ proto.normalizeSelf = function () {
return this;
if (magSqr === 0.0) {
- console.warn("Can't normalize zero vector");
return this;
}
diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js
index c31dbe7b67..dded7ff5c8 100644
--- a/cocos2d/deprecated.js
+++ b/cocos2d/deprecated.js
@@ -366,7 +366,7 @@ if (CC_DEV) {
// SCENE
var ERR = '"%s" is not defined in the Scene, it is only defined in normal nodes.';
- Object.defineProperties(cc.Scene.prototype, {
+ CC_EDITOR || Object.defineProperties(cc.Scene.prototype, {
active: {
get: function () {
cc.error(ERR, 'active');
diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js
index 40b9e6f321..0522bb7e38 100644
--- a/cocos2d/particle/CCParticleSystem.js
+++ b/cocos2d/particle/CCParticleSystem.js
@@ -130,6 +130,7 @@ var properties = {
this.resetSystem();
if ( !this.preview ) {
this.stopSystem();
+ this.disableRender();
}
cc.engine.repaintInEditMode();
},
@@ -250,7 +251,7 @@ var properties = {
*/
texture: {
get: function () {
- return this._texture ? this._texture.url : "";
+ return this._texture;
},
set: function (value) {
cc.warnID(6017);
@@ -812,7 +813,9 @@ var ParticleSystem = cc.Class({
},
onLoad () {
- ParticleSystem._assembler.createIA(this);
+ if (!this._ia) {
+ ParticleSystem._assembler.createIA(this);
+ }
},
onEnable () {
@@ -920,15 +923,16 @@ var ParticleSystem = cc.Class({
}
self._plistFile = file.nativeUrl;
- if (self._custom) {
- self._initTextureWithDictionary(content);
- }
- else {
+ if (!self._custom) {
self._initWithDictionary(content);
}
-
- if (file.texture) {
- self.spriteFrame = new cc.SpriteFrame(file.texture);
+ if (!self.spriteFrame) {
+ if (file.texture) {
+ self.spriteFrame = new cc.SpriteFrame(file.texture);
+ }
+ else if (self._custom) {
+ self._initTextureWithDictionary(content);
+ }
}
});
}
@@ -948,13 +952,13 @@ var ParticleSystem = cc.Class({
if (textureData && textureData.length > 0) {
var buffer = codec.unzipBase64AsArray(textureData, 1);
if (!buffer) {
- cc.logID(6010);
+ cc.logID(6030);
return false;
}
var imageFormat = getImageFormatByData(buffer);
if (imageFormat !== macro.ImageFormat.TIFF && imageFormat !== macro.ImageFormat.PNG) {
- cc.logID(6011);
+ cc.logID(6031);
return false;
}
@@ -968,7 +972,7 @@ var ParticleSystem = cc.Class({
var tex = textureUtil.cacheImage(imgPath, canvasObj);
if (!tex)
- cc.logID(6012);
+ cc.logID(6032);
// TODO: Use cc.loader to load asynchronously the SpriteFrame object, avoid using textureUtil
this.spriteFrame = new cc.SpriteFrame(tex);
}
@@ -1091,12 +1095,9 @@ var ParticleSystem = cc.Class({
return true;
},
- _onTextureLoaded: function (event) {
+ _onTextureLoaded: function () {
this._texture = this._spriteFrame.getTexture();
- // Mark render data dirty
- if (this._renderData) {
- this._renderData.uvDirty = true;
- }
+ this._simulator.updateUVs(true);
// Reactivate material
this._activateMaterial();
},
diff --git a/cocos2d/particle/particle-simulator.js b/cocos2d/particle/particle-simulator.js
index fc69d9fc65..d27816e04d 100644
--- a/cocos2d/particle/particle-simulator.js
+++ b/cocos2d/particle/particle-simulator.js
@@ -191,13 +191,15 @@ Simulator.prototype.emitParticle = function (pos) {
}
};
-Simulator.prototype.updateUVs = function (particleCount) {
+Simulator.prototype.updateUVs = function (force) {
+ let particleCount = this.particles.length;
if (this.sys._buffer && this.sys._spriteFrame) {
const FLOAT_PER_PARTICLE = 4 * this.sys._vertexFormat._bytes / 4;
let vbuf = this.sys._buffer._vData;
let uv = this.sys._spriteFrame.uv;
- for (let i = this._uvFilled; i < particleCount; i++) {
+ let start = force ? 0 : this._uvFilled;
+ for (let i = start; i < particleCount; i++) {
let offset = i * FLOAT_PER_PARTICLE;
vbuf[offset+2] = uv[0];
vbuf[offset+3] = uv[1];
@@ -299,11 +301,11 @@ Simulator.prototype.step = function (dt) {
let buffer = psys._buffer;
let particleCount = particles.length;
buffer.reset();
- buffer.request(particleCount * 4, particles.length * 6);
+ buffer.request(particleCount * 4, particleCount * 6);
// Fill up uvs
if (particleCount > this._uvFilled) {
- this.updateUVs(particleCount);
+ this.updateUVs();
}
// Used to reduce memory allocation / creation within the loop
diff --git a/cocos2d/tilemap/CCTMXXMLParser.js b/cocos2d/tilemap/CCTMXXMLParser.js
index da70e531d1..d473e19919 100644
--- a/cocos2d/tilemap/CCTMXXMLParser.js
+++ b/cocos2d/tilemap/CCTMXXMLParser.js
@@ -25,9 +25,9 @@
THE SOFTWARE.
****************************************************************************/
-var codec = require('../compression/ZipUtils');
-var zlib = require('../compression/zlib.min');
-var js = require('../core/platform/js');
+const codec = require('../compression/ZipUtils');
+const zlib = require('../compression/zlib.min');
+const js = require('../core/platform/js');
require('../core/platform/CCSAXParser');
function uint8ArrayToUint32Array (uint8Arr) {
@@ -168,6 +168,7 @@ cc.TMXTilesetInfo = function () {
this._tileSize = cc.size(0, 0);
};
+
cc.TMXTilesetInfo.prototype = {
constructor: cc.TMXTilesetInfo,
/**
@@ -345,7 +346,7 @@ cc.TMXMapInfo.prototype = {
* @return {Size}
*/
getMapSize () {
- return cc.size(this._mapSize.width,this._mapSize.height);
+ return cc.size(this._mapSize.width, this._mapSize.height);
},
/**
@@ -357,18 +358,18 @@ cc.TMXMapInfo.prototype = {
this._mapSize.height = value.height;
},
- _getMapWidth () {
- return this._mapSize.width;
- },
- _setMapWidth (width) {
- this._mapSize.width = width;
- },
- _getMapHeight () {
- return this._mapSize.height;
- },
- _setMapHeight (height) {
- this._mapSize.height = height;
- },
+ _getMapWidth () {
+ return this._mapSize.width;
+ },
+ _setMapWidth (width) {
+ this._mapSize.width = width;
+ },
+ _getMapHeight () {
+ return this._mapSize.height;
+ },
+ _setMapHeight (height) {
+ this._mapSize.height = height;
+ },
/**
* Tiles width & height
@@ -387,18 +388,18 @@ cc.TMXMapInfo.prototype = {
this._tileSize.height = value.height;
},
- _getTileWidth () {
- return this._tileSize.width;
- },
- _setTileWidth (width) {
- this._tileSize.width = width;
- },
- _getTileHeight () {
- return this._tileSize.height;
- },
- _setTileHeight (height) {
- this._tileSize.height = height;
- },
+ _getTileWidth () {
+ return this._tileSize.width;
+ },
+ _setTileWidth (width) {
+ this._tileSize.width = width;
+ },
+ _getTileHeight () {
+ return this._tileSize.height;
+ },
+ _setTileHeight (height) {
+ this._tileSize.height = height;
+ },
/**
* Layers
@@ -450,7 +451,7 @@ cc.TMXMapInfo.prototype = {
this._objectGroups.push(value);
},
- getAllChildren() {
+ getAllChildren () {
return this._allChildren;
},
@@ -541,7 +542,7 @@ cc.TMXMapInfo.prototype = {
* @param {Object} textures
* @return {Boolean}
*/
- initWithXML:function (tmxString, tsxMap, textures) {
+ initWithXML (tmxString, tsxMap, textures) {
this._tilesets.length = 0;
this._layers.length = 0;
@@ -562,15 +563,15 @@ cc.TMXMapInfo.prototype = {
return this.parseXMLString(tmxString);
},
- /**
+ /**
* Initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string
* @param {String} xmlString
* @param {Number} tilesetFirstGid
* @return {Element}
*/
- parseXMLString:function (xmlStr, tilesetFirstGid) {
- var mapXML = this._parser._parseXML(xmlStr);
- var i, j;
+ parseXMLString (xmlStr, tilesetFirstGid) {
+ let mapXML = this._parser._parseXML(xmlStr);
+ let i, j;
// PARSE