From 728e264e98f83c7a0bab3b3bd1fc382efff85002 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Mon, 22 May 2017 18:09:44 +0800 Subject: [PATCH 01/17] minor performance improvement --- cocos2d/core/components/CCRichText.js | 8 +++++--- cocos2d/core/components/CCScrollView.js | 4 ++-- cocos2d/core/label/CCSGLabel.js | 8 ++------ 3 files changed, 9 insertions(+), 11 deletions(-) diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index 93d39385b3..cf2bf9ccf3 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -70,7 +70,9 @@ var RichText = cc.Class({ ctor: function() { this._textArray = null; + this._labelSegments = []; this._labelSegmentsCache = []; + this._linesWidth = []; this._resetState(); @@ -329,9 +331,9 @@ var RichText = cc.Class({ sgNode.removeAllChildren(); } - this._labelSegments = []; - this._labelSegmentsCache = []; - this._linesWidth = []; + this._labelSegments.length = 0; + this._labelSegmentsCache.length = 0; + this._linesWidth.length = 0; this._lineOffsetX = 0; this._lineCount = 1; this._labelWidth = 0; diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 2b058ec992..ad0c0990fa 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -1054,8 +1054,8 @@ var ScrollView = cc.Class({ this._autoScrolling = false; this._touchMovePreviousTimestamp = getTimeInMilliseconds(); - this._touchMoveDisplacements = []; - this._touchMoveTimeDeltas = []; + this._touchMoveDisplacements.length = 0; + this._touchMoveTimeDeltas.length = 0; this._onScrollBarTouchBegan(); }, diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js index 417ababecd..2e515c33bb 100644 --- a/cocos2d/core/label/CCSGLabel.js +++ b/cocos2d/core/label/CCSGLabel.js @@ -669,10 +669,7 @@ _ccsg.Label = _ccsg.Node.extend({ } return _ccsg.Node.prototype._getHeight.call(this); }, -}); - -cc.BMFontHelper = { - _alignText: function() { + _alignText: function() { var ret = true; do { @@ -1328,12 +1325,11 @@ cc.BMFontHelper = { } } } -}; +}); var _p = _ccsg.Label.prototype; cc.js.addon(_p, EventTarget.prototype); -cc.js.mixin(_p, cc.BMFontHelper); _ccsg.Label.Type = cc.Enum({ TTF: 0, From 8eebe674343ce9df8d7693a95109555329dccc4c Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 23 May 2017 13:50:43 +0800 Subject: [PATCH 02/17] Node.getContentSize should return copy --- cocos2d/core/CCNode.js | 2 +- cocos2d/core/event-manager/CCEvent.js | 2 +- cocos2d/core/platform/js.js | 3 +++ 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 852921766f..bd107ed0af 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -1664,7 +1664,7 @@ var Node = cc.Class({ if (this._sizeProvider && !ignoreSizeProvider) { var size = this._sizeProvider.getContentSize(); this._contentSize = size; - return size; + return cc.size(size); } else { return cc.size(this._contentSize); diff --git a/cocos2d/core/event-manager/CCEvent.js b/cocos2d/core/event-manager/CCEvent.js index 25b978d6a1..0c9dc869bf 100644 --- a/cocos2d/core/event-manager/CCEvent.js +++ b/cocos2d/core/event-manager/CCEvent.js @@ -443,7 +443,7 @@ proto.getDelta = function () { */ proto.getDeltaX = function () { return this.touch ? this.touch.getDelta().x : 0; -}, +}; /** * !#en Returns the Y axis delta distance from the previous location to current location. diff --git a/cocos2d/core/platform/js.js b/cocos2d/core/platform/js.js index 4c4c230f5a..b33d112fde 100644 --- a/cocos2d/core/platform/js.js +++ b/cocos2d/core/platform/js.js @@ -919,6 +919,9 @@ js.array = { * @param {Function} [cleanupFunc] - the callback method used to process the cleanup logic when the object is recycled. * @param {Object} cleanupFunc.obj * @param {Number} size - initializes the length of the array + * @typescript + * constructor(cleanupFunc: (obj: any) => void, size: number) + * constructor(size: number) */ function Pool (cleanupFunc, size) { if (typeof cleanupFunc === 'number') { From b09d88e2c871cd26683ed3eab3c4da728ecd8652 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Wed, 24 May 2017 14:12:20 +0800 Subject: [PATCH 03/17] fixed animator not auto stop --- cocos2d/animation/animators.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cocos2d/animation/animators.js b/cocos2d/animation/animators.js index f7edbc1e22..ad0af17a0b 100644 --- a/cocos2d/animation/animators.js +++ b/cocos2d/animation/animators.js @@ -18,7 +18,10 @@ var animProto = Animator.prototype; animProto.update = function (dt) { var iterator = this._anims; var array = iterator.array; + var stoppedCount = 0; + var originLength = array.length; + for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { var anim = array[iterator.i]; if (anim._isPlaying && !anim._isPaused) { @@ -30,7 +33,9 @@ animProto.update = function (dt) { } } - if (array.length === 0 || stoppedCount >= array.length) { + var allRemoved = array.length === 0; + var allStopped = stoppedCount >= originLength; + if (allRemoved || allStopped) { this.stop(); } }; From 4d8408fb48157e97040ab9fdbb5f1e2939b25d6a Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Wed, 24 May 2017 15:34:28 +0800 Subject: [PATCH 04/17] update physics api docs --- cocos2d/core/physics/collider/CCPhysicsCollider.js | 14 ++++++++++++++ cocos2d/core/physics/joint/CCJoint.js | 2 +- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/physics/collider/CCPhysicsCollider.js b/cocos2d/core/physics/collider/CCPhysicsCollider.js index 0178d17faf..c9e6058719 100644 --- a/cocos2d/core/physics/collider/CCPhysicsCollider.js +++ b/cocos2d/core/physics/collider/CCPhysicsCollider.js @@ -279,6 +279,20 @@ PhysicsCollider.properties = { set: function (value) { this._restitution = value; } + }, + + /** + * !#en + * Physics collider will find the rigidbody component on the node and set to this property. + * !#zh + * 碰撞体会在初始化时查找节点上是否存在刚体,如果查找成功则赋值到这个属性上。 + * @property {RigidBody} body + * @default null + */ + body: { + default: null, + type: cc.RigidBody, + visible: false } }; diff --git a/cocos2d/core/physics/joint/CCJoint.js b/cocos2d/core/physics/joint/CCJoint.js index 46fe483aa5..7314208ed1 100644 --- a/cocos2d/core/physics/joint/CCJoint.js +++ b/cocos2d/core/physics/joint/CCJoint.js @@ -125,7 +125,7 @@ var Joint = cc.Class({ * Get the anchor point on rigidbody in world coordinates. * !#zh * 获取刚体世界坐标系下的锚点。 - * @method worldAnchor + * @method getWorldAnchor * @return {Vec2} */ getWorldAnchor: function () { From 9ff7f824e79b4585555b91f186ad920476c29d97 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Thu, 25 May 2017 10:11:52 +0800 Subject: [PATCH 05/17] fixed jsb rigidbody.getJointList --- cocos2d/core/physics/CCRigidBody.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/physics/CCRigidBody.js b/cocos2d/core/physics/CCRigidBody.js index aa0ac1d7a4..7b309b1e43 100644 --- a/cocos2d/core/physics/CCRigidBody.js +++ b/cocos2d/core/physics/CCRigidBody.js @@ -625,7 +625,11 @@ var RigidBody = cc.Class({ if (!this._b2Body) return []; if (CC_JSB) { - return this._b2Body.GetJointList(); + var joints = this._b2Body.GetJointList(); + for (var i = 0; i < joints.length; i++) { + joints[i] = joints[i]._joint; + } + return joints; } else { var joints = []; From bf0d21251dacacc5a063656a9c3f0d5e3b880f58 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 25 May 2017 10:35:30 +0800 Subject: [PATCH 06/17] fix editbox issue --- cocos2d/core/components/CCEditBox.js | 2 +- cocos2d/core/editbox/CCSGEditBox.js | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCEditBox.js b/cocos2d/core/components/CCEditBox.js index a0d1a98c84..be6df3152a 100644 --- a/cocos2d/core/components/CCEditBox.js +++ b/cocos2d/core/components/CCEditBox.js @@ -395,7 +395,7 @@ var EditBox = cc.Class({ /** * !#en The event handler to be called when EditBox began to edit text. * !#zh 开始编辑文本输入框触发的事件回调。 - * @property {Component.EventHandler} editingDidBegin + * @property {Component.EventHandler} editingDidBegan */ editingDidBegan: { default: [], diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index c0bbd6fe9a..45d551a4c0 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -321,6 +321,12 @@ _ccsg.EditBox = _ccsg.Node.extend({ this._renderCmd.stayOnTop(this._alwaysOnTop); }, + onEnter: function () { + _ccsg.Node.prototype.onEnter.call(this); + //in case the EditBox being used after changing parent + this.createDomElementIfNeeded(); + }, + onExit: function () { _ccsg.Node.prototype.onExit.call(this); this._renderCmd._removeDomFromGameContainer(); From df12f42392a182d2ec62a4c1415ed5e2b4b6f0a5 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 26 May 2017 02:24:42 +0800 Subject: [PATCH 07/17] skipped onLoad should be called after node re-activated --- cocos2d/core/component-scheduler.js | 29 ++-- cocos2d/core/node-activator.js | 132 ++++++++++-------- cocos2d/core/platform/CCObject.js | 40 +++--- cocos2d/core/utils/misc.js | 10 +- .../unit-es5/test-component-scheduler.js | 85 +++++++++-- 5 files changed, 193 insertions(+), 103 deletions(-) diff --git a/cocos2d/core/component-scheduler.js b/cocos2d/core/component-scheduler.js index d5b5c18821..0acf38f4dd 100644 --- a/cocos2d/core/component-scheduler.js +++ b/cocos2d/core/component-scheduler.js @@ -33,9 +33,9 @@ var IsEditorOnEnableCalled = Flags.IsEditorOnEnableCalled; var callerFunctor = CC_EDITOR && require('./utils/misc').tryCatchFunctor_EDITOR; var callOnEnableInTryCatch = CC_EDITOR && callerFunctor('onEnable'); -var callStartInTryCatch = CC_EDITOR && callerFunctor('start', null, null, 'target._objFlags |= ' + IsStartCalled); -var callUpdateInTryCatch = CC_EDITOR && callerFunctor('update', 'dt', 'dt'); -var callLateUpdateInTryCatch = CC_EDITOR && callerFunctor('lateUpdate', 'dt', 'dt'); +var callStartInTryCatch = CC_EDITOR && callerFunctor('start', null, 'target._objFlags |= ' + IsStartCalled); +var callUpdateInTryCatch = CC_EDITOR && callerFunctor('update', 'dt'); +var callLateUpdateInTryCatch = CC_EDITOR && callerFunctor('lateUpdate', 'dt'); var callOnDisableInTryCatch = CC_EDITOR && callerFunctor('onDisable'); function sortedIndex (array, comp) { @@ -69,15 +69,20 @@ function sortedIndex (array, comp) { return ~l; } -function stableRemoveInactive (iterator) { +// remove disabled and not invoked component from array +function stableRemoveInactive (iterator, flagToClear) { var array = iterator.array; - for (var i = 0; i < array.length;) { - var comp = array[i]; + var next = iterator.i + 1; + while (next < array.length) { + var comp = array[next]; if (comp._enabled && comp.node._activeInHierarchy) { - ++i; + ++next; } else { - iterator.removeAt(i); + iterator.removeAt(next); + if (flagToClear) { + comp._objFlags &= ~flagToClear; + } } } } @@ -121,10 +126,10 @@ var OneOffInvoker = cc.Class({ var order = comp.constructor._executionOrder; (order === 0 ? this._zero : (order < 0 ? this._neg : this._pos)).fastRemove(comp); }, - cancelInactive () { - stableRemoveInactive(this._zero); - stableRemoveInactive(this._neg); - stableRemoveInactive(this._pos); + cancelInactive (flagToClear) { + stableRemoveInactive(this._zero, flagToClear); + stableRemoveInactive(this._neg, flagToClear); + stableRemoveInactive(this._pos, flagToClear); }, invoke () { var compsNeg = this._neg; diff --git a/cocos2d/core/node-activator.js b/cocos2d/core/node-activator.js index e301e044e4..fa8fff2201 100644 --- a/cocos2d/core/node-activator.js +++ b/cocos2d/core/node-activator.js @@ -30,12 +30,14 @@ var callerFunctor = CC_EDITOR && require('./utils/misc').tryCatchFunctor_EDITOR; var MAX_POOL_SIZE = 4; +var IsPreloadStarted = Flags.IsPreloadStarted; var IsOnLoadStarted = Flags.IsOnLoadStarted; var IsOnLoadCalled = Flags.IsOnLoadCalled; var Deactivating = Flags.Deactivating; var callPreloadInTryCatch = CC_EDITOR && callerFunctor('__preload'); -var callOnLoadInTryCatch = CC_EDITOR && callerFunctor('onLoad'); +var callOnLoadInTryCatch = CC_EDITOR && callerFunctor('onLoad', null, + 'target._objFlags |= ' + IsOnLoadCalled + '; arg(target);', _onLoadInEditor); var callOnDestroyInTryCatch = CC_EDITOR && callerFunctor('onDestroy'); var callResetInTryCatch = CC_EDITOR && callerFunctor('resetInEditor'); var callOnFocusInTryCatch = CC_EDITOR && callerFunctor('onFocusInEditor'); @@ -50,8 +52,8 @@ var UnsortedInvoker = cc.Class({ remove (comp) { this._zero.fastRemove(comp); }, - cancelInactive () { - CompScheduler.LifeCycleInvoker.stableRemoveInactive(this._zero); + cancelInactive (flagToClear) { + CompScheduler.LifeCycleInvoker.stableRemoveInactive(this._zero, flagToClear); }, invoke () { this._invoke(this._zero); @@ -59,25 +61,33 @@ var UnsortedInvoker = cc.Class({ }, }); -function createActivateTask () { - var invokePreload = CompScheduler.createInvokeImpl(CC_EDITOR ? callPreloadInTryCatch : 'c.__preload();'); - var invokeOnLoad = CC_EDITOR ? function (iterator) { - var array = iterator.array; - for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { - let comp = array[iterator.i]; - callOnLoadInTryCatch(comp); - } - } : CompScheduler.createInvokeImpl('c.onLoad();'); - return { +var invokePreload = CompScheduler.createInvokeImpl( + CC_EDITOR ? callPreloadInTryCatch : 'c.__preload();' +); +var invokeOnLoad = CompScheduler.createInvokeImpl( + CC_EDITOR ? callOnLoadInTryCatch : ('c.onLoad();c._objFlags|=' + IsOnLoadCalled) +); + +var activateTasksPool = new JS.Pool(MAX_POOL_SIZE); +activateTasksPool.get = function getActivateTask () { + var task = this._get() || { preload: new UnsortedInvoker(invokePreload), onLoad: new CompScheduler.OneOffInvoker(invokeOnLoad), onEnable: new CompScheduler.OneOffInvoker(CompScheduler.invokeOnEnable) }; -} -var activateTasksPool = new JS.Pool(MAX_POOL_SIZE); -activateTasksPool.get = function getActivateTask () { - return this._get() || createActivateTask(); + // reset index to -1 so we can skip invoked component in cancelInactive + task.preload._zero.i = -1; + var invoker = task.onLoad; + invoker._zero.i = -1; + invoker._neg.i = -1; + invoker._pos.i = -1; + invoker = task.onEnable; + invoker._zero.i = -1; + invoker._neg.i = -1; + invoker._pos.i = -1; + + return task; }; function _componentCorrupted (node, comp, index) { @@ -93,6 +103,20 @@ function _componentCorrupted (node, comp, index) { } } +function _onLoadInEditor (comp) { + if (comp.onLoad && !cc.engine._isPlaying) { + var focused = Editor.Selection.curActivate('node') === comp.node.uuid; + if (focused && comp.onFocusInEditor) { + callOnFocusInTryCatch(comp); + } + else if (comp.onLostFocusInEditor) { + callOnLostFocusInTryCatch(comp); + } + } + if ( !CC_TEST ) { + _Scene.AssetsWatcher.start(comp); + } +} /** * The class used to perform activating and deactivating operations of node and component. @@ -207,50 +231,42 @@ var NodeActivator = cc.Class({ var stack = this._activatingStack; for (var i = 0; i < stack.length; i++) { var lastTask = stack[i]; - lastTask.preload.cancelInactive(node); - lastTask.onLoad.cancelInactive(node); - lastTask.onEnable.cancelInactive(node); + lastTask.preload.cancelInactive(IsPreloadStarted); + lastTask.onLoad.cancelInactive(IsOnLoadStarted); + lastTask.onEnable.cancelInactive(); } } node.emit('active-in-hierarchy-changed', node); }, activateComp: CC_EDITOR ? function (comp, preloadInvoker, onLoadInvoker, onEnableInvoker) { - if (!(comp._objFlags & IsOnLoadStarted) && - (cc.engine._isPlaying || comp.constructor._executeInEditMode)) { - comp._objFlags |= IsOnLoadStarted; - - if (typeof comp.__preload === 'function') { - if (preloadInvoker) { - preloadInvoker.add(comp); + if (cc.engine._isPlaying || comp.constructor._executeInEditMode) { + if (!(comp._objFlags & IsPreloadStarted)) { + comp._objFlags |= IsPreloadStarted; + if (typeof comp.__preload === 'function') { + if (preloadInvoker) { + preloadInvoker.add(comp); + } + else { + callPreloadInTryCatch(comp); + } + } + } + if (!(comp._objFlags & IsOnLoadStarted)) { + comp._objFlags |= IsOnLoadStarted; + if (comp.onLoad) { + if (onLoadInvoker) { + onLoadInvoker.add(comp); + } + else { + callOnLoadInTryCatch(comp); + } } else { - callPreloadInTryCatch(comp); + comp._objFlags |= IsOnLoadCalled; + _onLoadInEditor(comp); } } - if (comp.onLoad) { - if (onLoadInvoker) { - onLoadInvoker.add(comp); - } - else { - callOnLoadInTryCatch(comp); - } - } - - comp._objFlags |= IsOnLoadCalled; - - if (comp.onLoad && !cc.engine._isPlaying) { - var focused = Editor.Selection.curActivate('node') === comp.node.uuid; - if (focused && comp.onFocusInEditor) { - callOnFocusInTryCatch(comp); - } - else if (comp.onLostFocusInEditor) { - callOnLostFocusInTryCatch(comp); - } - } - if ( !CC_TEST ) { - _Scene.AssetsWatcher.start(comp); - } } if (comp._enabled) { var deactivatedOnLoading = !comp.node._activeInHierarchy; @@ -260,9 +276,8 @@ var NodeActivator = cc.Class({ cc.director._compScheduler.enableComp(comp, onEnableInvoker); } } : function (comp, preloadInvoker, onLoadInvoker, onEnableInvoker) { - if (!(comp._objFlags & IsOnLoadStarted)) { - comp._objFlags |= IsOnLoadStarted; - + if (!(comp._objFlags & IsPreloadStarted)) { + comp._objFlags |= IsPreloadStarted; if (typeof comp.__preload === 'function') { if (preloadInvoker) { preloadInvoker.add(comp); @@ -271,16 +286,21 @@ var NodeActivator = cc.Class({ comp.__preload(); } } + } + if (!(comp._objFlags & IsOnLoadStarted)) { + comp._objFlags |= IsOnLoadStarted; if (comp.onLoad) { if (onLoadInvoker) { onLoadInvoker.add(comp); } else { comp.onLoad(); + comp._objFlags |= IsOnLoadCalled; } } - - comp._objFlags |= IsOnLoadCalled; + else { + comp._objFlags |= IsOnLoadCalled; + } } if (comp._enabled) { var deactivatedOnLoading = !comp.node._activeInHierarchy; diff --git a/cocos2d/core/platform/CCObject.js b/cocos2d/core/platform/CCObject.js index 7b76db2fc9..8c7d193d48 100644 --- a/cocos2d/core/platform/CCObject.js +++ b/cocos2d/core/platform/CCObject.js @@ -17,6 +17,7 @@ var Deactivating = 1 << 8; var IsOnEnableCalled = 1 << 11; var IsEditorOnEnableCalled = 1 << 12; +var IsPreloadStarted = 1 << 13; var IsOnLoadCalled = 1 << 14; var IsOnLoadStarted = 1 << 15; var IsStartCalled = 1 << 16; @@ -30,7 +31,7 @@ var IsPositionLocked = 1 << 21; //var Hide = HideInGame | HideInEditor; // should not clone or serialize these flags var PersistentMask = ~(ToDestroy | Dirty | Destroying | DontDestroy | Deactivating | - IsOnLoadStarted | IsOnLoadCalled | IsStartCalled | + IsPreloadStarted | IsOnLoadStarted | IsOnLoadCalled | IsStartCalled | IsOnEnableCalled | IsEditorOnEnableCalled | IsRotationLocked | IsScaleLocked | IsAnchorLocked | IsSizeLocked | IsPositionLocked /*RegisteredInEditor*/); @@ -67,7 +68,7 @@ CCClass.fastDefine('cc.Object', CCObject, { _name: '', _objFlags: 0 }); */ JS.value(CCObject, 'Flags', { - Destroyed: Destroyed, + Destroyed, //ToDestroy: ToDestroy, /** @@ -75,16 +76,16 @@ JS.value(CCObject, 'Flags', { * !#zh 该对象将不会被保存。 * @property {Number} DontSave */ - DontSave: DontSave, + DontSave, /** * !#en The object will not be saved when building a player. * !#zh 构建项目时,该对象将不会被保存。 * @property {Number} EditorOnly */ - EditorOnly: EditorOnly, + EditorOnly, - Dirty: Dirty, + Dirty, /** * !#en Dont destroy automatically when loading a new scene. @@ -92,13 +93,13 @@ JS.value(CCObject, 'Flags', { * @property DontDestroy * @private */ - DontDestroy: DontDestroy, + DontDestroy, - PersistentMask: PersistentMask, + PersistentMask, // FLAGS FOR ENGINE - Destroying: Destroying, + Destroying, /** * !#en The node is deactivating. @@ -106,7 +107,7 @@ JS.value(CCObject, 'Flags', { * @property Deactivating * @private */ - Deactivating: Deactivating, + Deactivating, ///** // * !#en @@ -144,17 +145,18 @@ JS.value(CCObject, 'Flags', { // FLAGS FOR COMPONENT - IsOnLoadCalled: IsOnLoadCalled, - IsOnLoadStarted: IsOnLoadStarted, - IsOnEnableCalled: IsOnEnableCalled, - IsStartCalled: IsStartCalled, - IsEditorOnEnableCalled: IsEditorOnEnableCalled, + IsPreloadStarted, + IsOnLoadStarted, + IsOnLoadCalled, + IsOnEnableCalled, + IsStartCalled, + IsEditorOnEnableCalled, - IsPositionLocked: IsPositionLocked, - IsRotationLocked: IsRotationLocked, - IsScaleLocked: IsScaleLocked, - IsAnchorLocked: IsAnchorLocked, - IsSizeLocked: IsSizeLocked, + IsPositionLocked, + IsRotationLocked, + IsScaleLocked, + IsAnchorLocked, + IsSizeLocked, }); var objectsToDestroy = []; diff --git a/cocos2d/core/utils/misc.js b/cocos2d/core/utils/misc.js index 701441ea51..504aac4705 100644 --- a/cocos2d/core/utils/misc.js +++ b/cocos2d/core/utils/misc.js @@ -106,7 +106,7 @@ m.cleanEval_fireClass = function (code) { if (CC_EDITOR) { // use anonymous function here to ensure it will not being hoisted without CC_EDITOR - m.tryCatchFunctor_EDITOR = function (funcName, receivedArgs, usedArgs, afterCall) { + m.tryCatchFunctor_EDITOR = function (funcName, forwardArgs, afterCall, bindArg) { function call_FUNC_InTryCatch (_R_ARGS_) { try { target._FUNC_(_U_ARGS_); @@ -117,12 +117,12 @@ if (CC_EDITOR) { _AFTER_CALL_ } // use evaled code to generate named function - return Function('return ' + call_FUNC_InTryCatch + return Function('arg', 'return ' + call_FUNC_InTryCatch .toString() .replace(/_FUNC_/g, funcName) - .replace('_R_ARGS_', 'target' + (receivedArgs ? ', ' + receivedArgs : '')) - .replace('_U_ARGS_', usedArgs || '') - .replace('_AFTER_CALL_', afterCall || ''))(); + .replace('_R_ARGS_', 'target' + (forwardArgs ? ', ' + forwardArgs : '')) + .replace('_U_ARGS_', forwardArgs || '') + .replace('_AFTER_CALL_', afterCall || ''))(bindArg); }; } diff --git a/test/qunit/unit-es5/test-component-scheduler.js b/test/qunit/unit-es5/test-component-scheduler.js index 66df02a57a..5426f979e5 100644 --- a/test/qunit/unit-es5/test-component-scheduler.js +++ b/test/qunit/unit-es5/test-component-scheduler.js @@ -1,4 +1,11 @@ -largeModule('Component Scheduler', SetupEngine); +largeModule('Component Scheduler', { + setup: SetupEngine.setup, + teardown: function () { + cc.director._scene = new cc.Scene(); + cc.director._runningScene = cc.director._scene._sgNode; + SetupEngine.teardown(); + } +}); test('life cycle logic for component', function () { // my component @@ -127,7 +134,10 @@ test('disable component during onLoad', function () { nodes.attachToScene(); - expect(0); + // could re-enable + parentComp.onEnable.enable(); + parentComp.enabled = true; + parentComp.onEnable.once('could re-enable component'); }); test('disable component during onEnable', function () { @@ -137,7 +147,6 @@ test('disable component during onEnable', function () { comps: cc.Component, }, }); - var parent = nodes.root; var parentComp = nodes.rootComps[0]; var child = nodes.child; var childComp = nodes.childComps[0]; @@ -150,7 +159,10 @@ test('disable component during onEnable', function () { nodes.attachToScene(); - expect(0); + // could re-enable + childComp.onEnable = new Callback().enable(); + childComp.enabled = true; + childComp.onEnable.once('could re-enable component'); }); (function () { @@ -236,18 +248,33 @@ test('disable component during onEnable', function () { var siblingComp = nodes.siblingComps[0]; siblingComp.onLoad = new Callback().enable(); - cc.director.getScene().addChild(nodes.root); + nodes.attachToScene(); strictEqual(node.active, false, 'node should be deactivated'); strictEqual(cc.director.getActionManager().isTargetPaused_TEST(node), true, 'action should be paused'); previousComp.onLoad.once('onLoad of previous component should be called').disable(); - siblingComp.onLoad.once('onLoad of sibling node should still be called'); + siblingComp.onLoad.once('onLoad of sibling node should still be called').disable(); if (StillInvokeRestCompsOnSameNode) { compShouldBeActivated(restComp, 'rest'); } cc.game.step(); + + // re-active + + previousComp.onEnable.enable(); + testComp.onLoad = new Callback().disable('onLoad of testing component has already called'); + testComp.onEnable.enable(); + restComp.onLoad.enable(); + restComp.onEnable.enable(); + + node.active = true; + + previousComp.onEnable.once('onEnable of previous component should be called when node re-activated'); + testComp.onEnable.once('onEnable of testing component should be called when node re-activated'); + restComp.onLoad.once('onLoad of rest component should be called when node re-activated'); + restComp.onEnable.once('onEnable of rest component should be called when node re-activated'); }); test('could activate next sibling node in onLoad', function () { @@ -259,7 +286,6 @@ test('disable component during onEnable', function () { comps: cc.Component, } }); - var parent = nodes.root; var testComp = nodes.testComps[0]; var next = nodes.next; var nextComp = nodes.nextComps[0]; @@ -356,7 +382,7 @@ test('disable component during onEnable', function () { } // init child - createDisabledComp(child, 'child'); + var compOfChild = createDisabledComp(child, 'child'); // ACTIVATE parentToDeactivate.runAction(cc.delayTime(0)); @@ -379,6 +405,32 @@ test('disable component during onEnable', function () { } cc.game.step(); + + // re-active + var compOfNextNode = nextNode.getComponent(cc.Component); + compOfParent.onEnable.enable(); + compOfPrevNode.onEnable.enable(); + previousComp.onEnable.enable(); + compOfNextNode.onLoad.enable(); + compOfNextNode.onEnable.enable(); + testComp.onEnable.enable(); + restComp.onLoad.enable(); + restComp.onEnable.enable(); + compOfChild.onLoad.enable(); + compOfChild.onEnable.enable(); + + parentToDeactivate.active = true; + + compOfParent.onEnable.once('parent component should be re-enabled'); + compOfPrevNode.onEnable.once('previous node\'s component should be re-enabled'); + previousComp.onEnable.once('previous component should be re-enabled'); + compOfNextNode.onLoad.once('next node\'s component should be loaded'); + compOfNextNode.onEnable.once('next node\'s component should be re-enabled'); + testComp.onEnable.once('testing component should be re-enabled'); + restComp.onLoad.once('rest component should be loaded'); + restComp.onEnable.once('rest component should be re-enabled'); + compOfChild.onLoad.once('child component should be loaded'); + compOfChild.onEnable.once('child component should be re-enabled'); }); // test('could deactivate parent in onLoad', function () { @@ -464,7 +516,7 @@ test('disable component during onEnable', function () { // }); test('could deactivate self node in onEnable', function () { - var node = new cc.Node(); + var node = new cc.Node('P'); var previousComp = createNormalComp(node); @@ -483,8 +535,8 @@ test('disable component during onEnable', function () { restComp = createOnlyOnLoadComp(node, 'rest'); } - var child = new cc.Node(); - createOnlyOnLoadComp(child, 'child'); + var child = new cc.Node('C'); + var compOfChild = createOnlyOnLoadComp(child, 'child'); child.parent = node; cc.director.getScene().addChild(node); @@ -499,6 +551,17 @@ test('disable component during onEnable', function () { } cc.game.step(); + + // re-active + + testComp.onEnable = null; + previousComp.onEnable.enable(); + + restComp.onEnable.enable(); + compOfChild.onEnable.enable(); + node.active = true; + restComp.onEnable.once('rest component should be re-enabled'); + compOfChild.onEnable.once('child component should be re-enabled'); }); function testActivateChildManually (title, childActivedByDefault) { From 7f79e0d8f72a4d58cfb93ad043d2173658605bcd Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 26 May 2017 11:18:24 +0800 Subject: [PATCH 08/17] remove eval --- cocos2d/core/component-scheduler.js | 4 +-- cocos2d/core/platform/CCClass.js | 35 +++++++++++------------- cocos2d/core/platform/instantiate-jit.js | 11 ++++---- cocos2d/core/utils/misc.js | 32 ++++++---------------- 4 files changed, 32 insertions(+), 50 deletions(-) diff --git a/cocos2d/core/component-scheduler.js b/cocos2d/core/component-scheduler.js index 0acf38f4dd..676a3547b9 100644 --- a/cocos2d/core/component-scheduler.js +++ b/cocos2d/core/component-scheduler.js @@ -238,10 +238,10 @@ function createInvokeImpl (code, useDt) { code + '}'; if (useDt) { - return new Function('it', 'dt', body); + return Function('it', 'dt', body); } else { - return new Function('it', body); + return Function('it', body); } } } diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 0f2fef2ffc..78280ec0fa 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -32,7 +32,6 @@ var Attr = require('./attribute'); var DELIMETER = Attr.DELIMETER; var getTypeChecker = Attr.getTypeChecker; var preprocess = require('./preprocess-class'); -var Misc = require('../utils/misc'); require('./requiring-frame'); var BUILTIN_ENTRIES = ['name', 'extends', 'mixins', 'ctor', '__ctor__', 'properties', 'statics', 'editor', '__ES6__']; @@ -465,7 +464,7 @@ function compileProps (actualClass) { // functions for generated code var F = []; - var func = '(function(){\n'; + var func = ''; for (var i = 0; i < propList.length; i++) { var prop = propList[i]; @@ -512,16 +511,19 @@ function compileProps (actualClass) { } } - func += '})'; - // if (CC_TEST && !isPhantomJS) { // console.log(func); // } // Overwite __initProps__ to avoid compile again. - // Use eval to bind scoped variable just in one function, so that we don't have to bind this. - var initProps = actualClass.prototype.__initProps__ = Misc.cleanEval_F(func, F); - + var initProps; + if (F.length === 0) { + initProps = Function(func); + } + else { + initProps = Function('F', 'return (function(){\n' + func + '})')(F); + } + actualClass.prototype.__initProps__ = initProps; // call instantiateProps immediately, no need to pass actualClass into it anymore // (use call to manually bind `this` because `this` may not instanceof actualClass) initProps.call(this); @@ -531,21 +533,16 @@ function _createCtor (ctors, baseClass, className, options) { // bound super calls var superCallBounded = baseClass && boundSuperCalls(baseClass, options, className); - var body; var args = CC_JSB ? '...args' : ''; - if (CC_DEV) { - body = '(function ' + normalizeClassName_DEV(className) + '(' + args + '){\n'; - } - else { - body = '(function(' + args + '){\n'; - } + var ctorName = CC_DEV ? normalizeClassName_DEV(className) : 'CCClass'; + var body = 'return function ' + ctorName + '(' + args + '){\n'; if (superCallBounded) { body += 'this._super=null;\n'; } // instantiate props - body += 'this.__initProps__(fireClass);\n'; + body += 'this.__initProps__(' + ctorName + ');\n'; // call user constructors var ctorLen = ctors.length; @@ -556,10 +553,10 @@ function _createCtor (ctors, baseClass, className, options) { } var SNIPPET = CC_JSB ? '].apply(this,args);\n' : '].apply(this,arguments);\n'; if (ctorLen === 1) { - body += 'fireClass.__ctors__[0' + SNIPPET; + body += ctorName + '.__ctors__[0' + SNIPPET; } else { - body += 'var cs=fireClass.__ctors__;\n'; + body += 'var cs=' + ctorName + '.__ctors__;\n'; for (var i = 0; i < ctorLen; i++) { body += 'cs[' + i + SNIPPET; } @@ -570,9 +567,9 @@ function _createCtor (ctors, baseClass, className, options) { '}\n'; } } - body += '})'; + body += '}'; - return Misc.cleanEval_fireClass(body); + return Function(body)(); } function _validateCtor_DEV (ctor, baseClass, className, options) { diff --git a/cocos2d/core/platform/instantiate-jit.js b/cocos2d/core/platform/instantiate-jit.js index c7421df2d0..a1f0665c0b 100644 --- a/cocos2d/core/platform/instantiate-jit.js +++ b/cocos2d/core/platform/instantiate-jit.js @@ -234,13 +234,14 @@ function Parser (obj, parent) { if (this.globalVariables.length > 0) { globalVariablesDeclaration = VAR + this.globalVariables.join(',') + ';'; } - var code = flattenCodeArray([globalVariablesDeclaration || [], - this.codeArray, - 'return o;'], CC_DEV ? '\n' : ''); + var code = flattenCodeArray(['return (function(R){', + globalVariablesDeclaration || [], + this.codeArray, + 'return o;', + '})'], CC_DEV ? '\n' : ''); // generate method and bind with objs - var createFunction = Function('O', 'F', 'R', code); - this.result = createFunction.bind(null, this.objs, this.funcs); + this.result = Function('O', 'F', code)(this.objs, this.funcs); // if (CC_TEST && !isPhantomJS) { // console.log(code); diff --git a/cocos2d/core/utils/misc.js b/cocos2d/core/utils/misc.js index 504aac4705..7989cfc243 100644 --- a/cocos2d/core/utils/misc.js +++ b/cocos2d/core/utils/misc.js @@ -23,14 +23,11 @@ THE SOFTWARE. ****************************************************************************/ -// jshint evil: true - var JS = require('../platform/js'); -// should not use long variable name because eval breaks uglify's mangle operation in this file -var m = {}; +var misc = {}; -m.propertyDefine = function (ctor, sameNameGetSets, diffNameGetSets) { +misc.propertyDefine = function (ctor, sameNameGetSets, diffNameGetSets) { function define (np, propName, getter, setter) { var pd = Object.getOwnPropertyDescriptor(np, propName); if (pd) { @@ -67,7 +64,7 @@ m.propertyDefine = function (ctor, sameNameGetSets, diffNameGetSets) { * @return {Number} * Constructor */ -m.NextPOT = function (x) { +misc.NextPOT = function (x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); @@ -92,21 +89,10 @@ m.NextPOT = function (x) { // //DirtyFlags.WIDGET = DirtyFlags.TRANSFORM | DirtyFlags.SIZE; -// wrap a new scope to avoid uglify's mangle process broken by eval in caller's scope - -m.cleanEval_F = function (code, F) { - return eval(code); -}; - -m.cleanEval_fireClass = function (code) { - var fireClass = eval(code); - return fireClass; -}; - if (CC_EDITOR) { // use anonymous function here to ensure it will not being hoisted without CC_EDITOR - m.tryCatchFunctor_EDITOR = function (funcName, forwardArgs, afterCall, bindArg) { + misc.tryCatchFunctor_EDITOR = function (funcName, forwardArgs, afterCall, bindArg) { function call_FUNC_InTryCatch (_R_ARGS_) { try { target._FUNC_(_U_ARGS_); @@ -126,18 +112,16 @@ if (CC_EDITOR) { }; } -m.imagePool = new JS.Pool(function (img) { +misc.imagePool = new JS.Pool(function (img) { if (img instanceof HTMLImageElement) { img.src = this._smallImg; return true; } return false; }, 10); -m.imagePool.get = function () { +misc.imagePool.get = function () { return this._get() || new Image(); }; -m.imagePool._smallImg = "data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA="; +misc.imagePool._smallImg = "data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA="; -module.exports = m; - -// jshint evil: false +module.exports = misc; From 5d69039f3a2ed63e03d2f982062d7cd3b61897da Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Fri, 26 May 2017 17:04:58 +0800 Subject: [PATCH 09/17] avoid fire event error --- cocos2d/animation/animation-curves.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/cocos2d/animation/animation-curves.js b/cocos2d/animation/animation-curves.js index aa49c53969..895ba2e55e 100644 --- a/cocos2d/animation/animation-curves.js +++ b/cocos2d/animation/animation-curves.js @@ -390,6 +390,11 @@ var EventAnimCurve = cc.Class({ var eventInfo = this.events[index]; var events = eventInfo.events; + + if ( !this.target.isValid ) { + return; + } + var components = this.target._components; for (var i = 0; i < events.length; i++) { From dabeb3d5e3e2934c468e0e36bad6f95cf68383e2 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Fri, 26 May 2017 18:05:51 +0800 Subject: [PATCH 10/17] fixed camera typo --- cocos2d/core/camera/CCCamera.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/camera/CCCamera.js b/cocos2d/core/camera/CCCamera.js index 3fe21cfe35..c516d9d88d 100644 --- a/cocos2d/core/camera/CCCamera.js +++ b/cocos2d/core/camera/CCCamera.js @@ -182,7 +182,7 @@ let Camera = cc.Class({ return this._targets; }, - calculateCaemraTransformIn: function (transform) { + calculateCameraTransformIn: function (transform) { let node = this.node; let wt = node.getNodeToWorldTransform(); @@ -218,7 +218,7 @@ let Camera = cc.Class({ lateUpdate: !CC_EDITOR && function () { let t = tempTransform; - this.calculateCaemraTransformIn(t); + this.calculateCameraTransformIn(t); this._sgNode.setTransform(t.a, t.b, t.c, t.d, t.tx, t.ty); } }); From 65662e0dd2e5ac5a1717af4f9b2c99ba9a48c586 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 26 May 2017 18:06:46 +0800 Subject: [PATCH 11/17] Fix long call stack in downloader --- cocos2d/core/load-pipeline/downloader.js | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/cocos2d/core/load-pipeline/downloader.js b/cocos2d/core/load-pipeline/downloader.js index 0a4124cee9..ecbc597fc1 100644 --- a/cocos2d/core/load-pipeline/downloader.js +++ b/cocos2d/core/load-pipeline/downloader.js @@ -336,14 +336,16 @@ Downloader.prototype.handle = function (item, callback) { this._curConcurrent++; downloadFunc.call(this, item, function (err, result) { // Concurrent logic - self._curConcurrent = Math.max(0, self._curConcurrent - 1); - while (self._curConcurrent < self.maxConcurrent) { - var nextOne = self._loadQueue.shift(); - if (!nextOne) { - break; + setTimeout(function () { + self._curConcurrent = Math.max(0, self._curConcurrent - 1); + while (self._curConcurrent < self.maxConcurrent) { + var nextOne = self._loadQueue.shift(); + if (!nextOne) { + break; + } + self.handle(nextOne.item, nextOne.callback); } - self.handle(nextOne.item, nextOne.callback); - } + }, 0); callback && callback(err, result); }); From 78428b4943fc0dec8abe9c19669ea5116c2a2aa5 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 26 May 2017 18:28:47 +0800 Subject: [PATCH 12/17] Use customizable max concurrent number --- cocos2d/core/load-pipeline/downloader.js | 5 ++--- cocos2d/core/platform/CCMacro.js | 10 ++++++++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/load-pipeline/downloader.js b/cocos2d/core/load-pipeline/downloader.js index ecbc597fc1..a6f1cab166 100644 --- a/cocos2d/core/load-pipeline/downloader.js +++ b/cocos2d/core/load-pipeline/downloader.js @@ -312,7 +312,6 @@ var Downloader = function (extMap) { this.id = ID; this.async = true; this.pipeline = null; - this.maxConcurrent = cc.sys.isMobile ? 2 : 512; this._curConcurrent = 0; this._loadQueue = []; @@ -332,13 +331,13 @@ Downloader.prototype.addHandlers = function (extMap) { Downloader.prototype.handle = function (item, callback) { var self = this; var downloadFunc = this.extMap[item.type] || this.extMap['default']; - if (this._curConcurrent < this.maxConcurrent) { + if (this._curConcurrent < cc.macro.DOWNLOAD_MAX_CONCURRENT) { this._curConcurrent++; downloadFunc.call(this, item, function (err, result) { // Concurrent logic setTimeout(function () { self._curConcurrent = Math.max(0, self._curConcurrent - 1); - while (self._curConcurrent < self.maxConcurrent) { + while (self._curConcurrent < cc.macro.DOWNLOAD_MAX_CONCURRENT) { var nextOne = self._loadQueue.shift(); if (!nextOne) { break; diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index 04c76a19bc..6f5a603041 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -1898,6 +1898,16 @@ cc.macro = { * @default true */ ENABLE_TILEDMAP_CULLING: true, + + /** + * !#en + * The max concurrent task number for the downloader + * !#zh + * 下载任务的最大并发数限制,在安卓平台部分机型或版本上可能需要限制在较低的水平 + * @property {Number} DOWNLOAD_MAX_CONCURRENT + * @default 64 + */ + DOWNLOAD_MAX_CONCURRENT: 64, }; /** From c9adca15b8292acdffa8112f6a140646083dabd1 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sat, 27 May 2017 11:20:30 +0800 Subject: [PATCH 13/17] More secured Scheduler with target id assert --- DebugInfos.js | 15 ++++++----- cocos2d/core/CCScheduler.js | 53 +++++++++++++++++++++---------------- 2 files changed, 38 insertions(+), 30 deletions(-) diff --git a/DebugInfos.js b/DebugInfos.js index fc0d9ba179..889d3c36ac 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -49,16 +49,17 @@ if (CC_DEV) { "1403": "Sorry, cc.audioEngine.willPlayMusic is removed.", //willPlayMusicError "1404": "cc.spriteFrameCache is removed, please use cc.loader to load and cache sprite frames of atlas format.", //Scheduler: 1500 - "1500": "CCSheduler#scheduleCallback. Callback already scheduled. Updating interval from:%s to %s", //scheduleCallbackForTarget - "1501": "cc.scheduler.scheduleCallbackForTarget(): callback_fn should be non-null.", //scheduleCallbackForTarget_2 - "1502": "cc.scheduler.scheduleCallbackForTarget(): target should be non-null.", //scheduleCallbackForTarget_3 - "1503": "cc.Scheduler.pauseTarget():target should be non-null", //pauseTarget - "1504": "cc.Scheduler.resumeTarget():target should be non-null", //resumeTarget - "1505": "cc.Scheduler.isTargetPaused():target should be non-null", //isTargetPaused + "1500": "cc.Scheduler#schedule: Callback already scheduled. Updating interval from:%s to %s", //scheduleCallbackForTarget + "1501": "cc.Scheduler#scheduleCallbackForTarget(): callback_fn should be non-null.", //scheduleCallbackForTarget_2 + "1502": "cc.Scheduler#scheduleCallbackForTarget(): target should be non-null.", //scheduleCallbackForTarget_3 + "1503": "cc.Scheduler#pauseTarget():target should be non-null", //pauseTarget + "1504": "cc.Scheduler#resumeTarget():target should be non-null", //resumeTarget + "1505": "cc.Scheduler#isTargetPaused():target should be non-null", //isTargetPaused "1506": "warning: you CANNOT change update priority in scheduled function", //_schedulePerFrame - "1507": "CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f", //schedule + "1507": "cc.Scheduler#scheduleSelector: Selector already scheduled. Updating interval from: %.4f to %.4f", //schedule "1508": "Argument callback must not be empty", //isScheduled "1509": "Argument target must be non-nullptr", //isScheduled + "1510": "cc.Scheduler: Illegal target which doesn't have uuid or instanceId", //Node: 1600 "1600": "getZOrder is deprecated. Please use getLocalZOrder instead.", //getZOrder "1601": "setZOrder is deprecated. Please use setLocalZOrder instead.", //setZOrder diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 8efda2ccaa..f817f9d45a 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -543,8 +543,8 @@ cc.Scheduler = cc._Class.extend({ cc.assertID(target, 1502); var instanceId = getTargetId(target); + cc.assertID(target, 1510); var element = this._hashForTimers[instanceId]; - if (!element) { // Is this the 1st element ? Then set the pause level to all the callback_fns of this target element = HashTimerEntry.get(null, target, 0, null, null, paused); @@ -588,7 +588,9 @@ cc.Scheduler = cc._Class.extend({ * @param {Function} updateFunc */ scheduleUpdate: function(target, priority, paused, updateFunc) { - var hashElement = this._hashForUpdates[getTargetId(target)]; + var targetId = getTargetId(target); + cc.assertID(target, 1510); + var hashElement = this._hashForUpdates[targetId]; if (hashElement && hashElement.entry){ // check if priority has changed if (hashElement.entry.priority !== priority){ @@ -623,7 +625,7 @@ cc.Scheduler = cc._Class.extend({ } //update hash entry for quick access - this._hashForUpdates[getTargetId(target)] = HashUpdateEntry.get(ppList, listElement, target, null); + this._hashForUpdates[targetId] = HashUpdateEntry.get(ppList, listElement, target, null); }, /** @@ -643,8 +645,10 @@ cc.Scheduler = cc._Class.extend({ // explicity handle nil arguments when removing an object if (!target || !callback) return; + var targetId = getTargetId(target); + cc.assertID(target, 1510); - var self = this, element = self._hashForTimers[getTargetId(target)]; + var self = this, element = self._hashForTimers[targetId]; if (element) { var timers = element.timers; for(var i = 0, li = timers.length; i < li; i++){ @@ -682,9 +686,10 @@ cc.Scheduler = cc._Class.extend({ unscheduleUpdate: function (target) { if (!target) return; + var targetId = getTargetId(target); + cc.assertID(target, 1510); - var element = this._hashForUpdates[getTargetId(target)]; - + var element = this._hashForUpdates[targetId]; if (element) { if (this._updateHashLocked) { element.entry.markedForDeletion = true; @@ -707,10 +712,11 @@ cc.Scheduler = cc._Class.extend({ if (!target){ return; } + var targetId = getTargetId(target); + cc.assertID(target, 1510); // Custom Selectors - var element = this._hashForTimers[getTargetId(target)]; - + var element = this._hashForTimers[targetId]; if (element) { var timers = element.timers; if (timers.indexOf(element.currentTimer) > -1 && @@ -813,9 +819,10 @@ cc.Scheduler = cc._Class.extend({ //selector, target cc.assertID(callback, 1508); cc.assertID(target, 1509); - - var instanceId = getTargetId(target); - var element = this._hashForTimers[instanceId]; + var targetId = getTargetId(target); + cc.assertID(target, 1510); + + var element = this._hashForTimers[targetId]; if (!element) { return false; @@ -942,19 +949,19 @@ cc.Scheduler = cc._Class.extend({ * @param {Object} target */ pauseTarget: function (target) { - cc.assertID(target, 1503); + var targetId = getTargetId(target); + cc.assertID(target, 1510); //customer selectors var self = this, - instanceId = getTargetId(target), - element = self._hashForTimers[instanceId]; + element = self._hashForTimers[targetId]; if (element) { element.paused = true; } //update callback - var elementUpdate = self._hashForUpdates[instanceId]; + var elementUpdate = self._hashForUpdates[targetId]; if (elementUpdate) { elementUpdate.entry.paused = true; } @@ -973,20 +980,20 @@ cc.Scheduler = cc._Class.extend({ * @param {Object} target */ resumeTarget: function (target) { - cc.assertID(target, 1504); + var targetId = getTargetId(target); + cc.assertID(target, 1510); // custom selectors var self = this, - instanceId = getTargetId(target), - element = self._hashForTimers[instanceId]; + element = self._hashForTimers[targetId]; if (element) { element.paused = false; } //update callback - var elementUpdate = self._hashForUpdates[instanceId]; + var elementUpdate = self._hashForUpdates[targetId]; if (elementUpdate) { elementUpdate.entry.paused = false; @@ -1001,16 +1008,16 @@ cc.Scheduler = cc._Class.extend({ * @return {Boolean} */ isTargetPaused: function (target) { - cc.assertID(target, 1505); + var targetId = getTargetId(target); + cc.assertID(target, 1510); // Custom selectors - var instanceId = getTargetId(target), - element = this._hashForTimers[instanceId]; + var element = this._hashForTimers[targetId]; if (element) { return element.paused; } - var elementUpdate = this._hashForUpdates[instanceId]; + var elementUpdate = this._hashForUpdates[targetId]; if (elementUpdate) { return elementUpdate.entry.paused; } From ce15b4f738b39ec18fd0a2cf3e539ab010486b1a Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sat, 27 May 2017 11:26:14 +0800 Subject: [PATCH 14/17] fix typo --- cocos2d/core/CCScheduler.js | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index f817f9d45a..04aecfeeff 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -543,7 +543,7 @@ cc.Scheduler = cc._Class.extend({ cc.assertID(target, 1502); var instanceId = getTargetId(target); - cc.assertID(target, 1510); + cc.assertID(instanceId, 1510); var element = this._hashForTimers[instanceId]; if (!element) { // Is this the 1st element ? Then set the pause level to all the callback_fns of this target @@ -589,7 +589,7 @@ cc.Scheduler = cc._Class.extend({ */ scheduleUpdate: function(target, priority, paused, updateFunc) { var targetId = getTargetId(target); - cc.assertID(target, 1510); + cc.assertID(targetId, 1510); var hashElement = this._hashForUpdates[targetId]; if (hashElement && hashElement.entry){ // check if priority has changed @@ -646,7 +646,7 @@ cc.Scheduler = cc._Class.extend({ if (!target || !callback) return; var targetId = getTargetId(target); - cc.assertID(target, 1510); + cc.assertID(targetId, 1510); var self = this, element = self._hashForTimers[targetId]; if (element) { @@ -687,7 +687,7 @@ cc.Scheduler = cc._Class.extend({ if (!target) return; var targetId = getTargetId(target); - cc.assertID(target, 1510); + cc.assertID(targetId, 1510); var element = this._hashForUpdates[targetId]; if (element) { @@ -713,7 +713,7 @@ cc.Scheduler = cc._Class.extend({ return; } var targetId = getTargetId(target); - cc.assertID(target, 1510); + cc.assertID(targetId, 1510); // Custom Selectors var element = this._hashForTimers[targetId]; @@ -820,7 +820,7 @@ cc.Scheduler = cc._Class.extend({ cc.assertID(callback, 1508); cc.assertID(target, 1509); var targetId = getTargetId(target); - cc.assertID(target, 1510); + cc.assertID(targetId, 1510); var element = this._hashForTimers[targetId]; @@ -951,7 +951,7 @@ cc.Scheduler = cc._Class.extend({ pauseTarget: function (target) { cc.assertID(target, 1503); var targetId = getTargetId(target); - cc.assertID(target, 1510); + cc.assertID(targetId, 1510); //customer selectors var self = this, @@ -982,7 +982,7 @@ cc.Scheduler = cc._Class.extend({ resumeTarget: function (target) { cc.assertID(target, 1504); var targetId = getTargetId(target); - cc.assertID(target, 1510); + cc.assertID(targetId, 1510); // custom selectors var self = this, @@ -1010,7 +1010,7 @@ cc.Scheduler = cc._Class.extend({ isTargetPaused: function (target) { cc.assertID(target, 1505); var targetId = getTargetId(target); - cc.assertID(target, 1510); + cc.assertID(targetId, 1510); // Custom selectors var element = this._hashForTimers[targetId]; From e280769ec528ea48f08513d08ceb17aa469b4633 Mon Sep 17 00:00:00 2001 From: 2youyouo2 <501251991@qq.com> Date: Sat, 27 May 2017 17:31:24 +0800 Subject: [PATCH 15/17] remove function from Array.prototype in box2d.js --- external/box2d/box2d.js | 122 ---------------------------------------- 1 file changed, 122 deletions(-) diff --git a/external/box2d/box2d.js b/external/box2d/box2d.js index 9a8b1ada59..2e392e65ed 100644 --- a/external/box2d/box2d.js +++ b/external/box2d/box2d.js @@ -17,128 +17,6 @@ Function.prototype._implement = function(parent) { return this._extend(parent); }; -Array.prototype.qsort = function(first, len, cmp) -{ - if (typeof(first) === 'undefined') - first = 0; - if (typeof(len) === 'undefined') - len = this.length - first; - if (typeof(cmp) === 'undefined') - cmp = function(a, b) { return a < b; }; - - var left = first, stack = [], pos = 0; - - for (; ; ) { /* outer loop */ - for (; left + 1 < len; len++) { /* sort left to len-1 */ - var pivot = this[left + Math.floor(Math.random() * (len - left))]; /* pick random pivot */ - stack[pos++] = len; /* sort right part later */ - for (var right = left - 1; ; ) { /* inner loop: partitioning */ - while (cmp(this[++right], pivot)) { } /* look for greater element */ - while (cmp(pivot, this[--len])) { } /* look for smaller element */ - if (right >= len) - break; /* partition point found? */ - var temp = this[right]; - this[right] = this[len]; /* the only swap */ - this[len] = temp; - } /* partitioned, continue left part */ - } - if (pos === 0) - break; /* stack empty? */ - left = len; /* left to right is sorted */ - len = stack[--pos]; /* get next range to sort */ - } - - return this; -}; - -Array.prototype.collapse = function(predicate, length) -{ - if (typeof(length) === 'undefined') - length = this.length; - - var l = 0; - - for (var c = 0; c < length; ++c) - { - // if we can be collapsed, keep l where it is. - if (predicate(this[c])) - continue; - - // this node can't be collapsed; push it back as far as we can. - if (c === l) - { - ++l; - continue; // quick exit if we're already in the right spot - } - - this[l++] = this[c]; - } - - return l; -}; - -Array.prototype.lower_bound = function(first, last, val, cmp) -{ - if (typeof (cmp) === 'undefined') - cmp = function(a, b) { return a < b; }; - - var count = last - first; - while (count > 0) - { - var step = Math.floor(count / 2); - var it = first + step; - - if (cmp(this[it], val)) - { - first = ++it; - count -= step + 1; - } - else - count = step; - } - return first; -}; - -Array.prototype.upper_bound = function(first, last, val, cmp) -{ - if (typeof (cmp) === 'undefined') - cmp = function(a, b) { return a < b; }; - - var count = last - first; - while (count > 0) - { - var step = Math.floor(count / 2); - var it = first + step; - - if (!cmp(val, this[it])) - { - first = ++it; - count -= step + 1; - } - else - count = step; - } - return first; -}; - -Array.prototype.rotate = function(first, n_first, last) -{ - var next = n_first; - while (first != next) - { - //std::iter_swap(first++, next++); - var ofirst = this[first]; - this[first] = this[next]; - this[next] = ofirst; - ++first; - ++next; - - if (next === last) - next = n_first; - else if (first === n_first) - n_first = next; - } -}; var b2Profiler = (function() { if (typeof(performance) === 'undefined') From 5db9af60a82f8a0670d1c00d59cf2bd92ddc4466 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Thu, 1 Jun 2017 09:50:22 +0800 Subject: [PATCH 16/17] fix particleSystem error for fireball/issues/4943 --- cocos2d/core/value-types/CCAffineTransform.js | 16 ++++++++++++++++ cocos2d/particle/CCSGParticleSystem.js | 10 +++++++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/value-types/CCAffineTransform.js b/cocos2d/core/value-types/CCAffineTransform.js index 872527b995..27c2c4fdf5 100644 --- a/cocos2d/core/value-types/CCAffineTransform.js +++ b/cocos2d/core/value-types/CCAffineTransform.js @@ -98,6 +98,22 @@ cc.pointApplyAffineTransform = function (point, transOrY, t) { return {x: t.a * x + t.c * y + t.tx, y: t.b * x + t.d * y + t.ty}; }; +cc._pointApplyAffineTransformIn = function (point, transOrY, transOrOut, out) { + var x, y, t; + if (out === undefined) { + t = transOrY; + x = point.x; + y = point.y; + out = transOrOut; + } else { + x = point; + y = transOrY; + t = transOrOut; + } + out.x = t.a * x + t.c * y + t.tx; + out.y = t.b * x + t.d * y + t.ty; +}; + cc._pointApplyAffineTransform = function (x, y, t) { //it will remove. return cc.pointApplyAffineTransform(x, y, t); }; diff --git a/cocos2d/particle/CCSGParticleSystem.js b/cocos2d/particle/CCSGParticleSystem.js index 6832a39ccf..24e1f00f5e 100644 --- a/cocos2d/particle/CCSGParticleSystem.js +++ b/cocos2d/particle/CCSGParticleSystem.js @@ -1673,6 +1673,7 @@ _ccsg.ParticleSystem = _ccsg.Node.extend({ } this._particleIdx = 0; + var worldToNodeTransform = this.getWorldToNodeTransform(); var currentPosition = cc.Particle.TemporaryPoints[0]; if (this.positionType === _ccsg.ParticleSystem.Type.FREE) { cc.pIn(currentPosition, this.convertToWorldSpace(this._pointZeroForParticle)); @@ -1760,9 +1761,12 @@ _ccsg.ParticleSystem = _ccsg.Node.extend({ // var newPos = tpa; if (this.positionType === _ccsg.ParticleSystem.Type.FREE || this.positionType === _ccsg.ParticleSystem.Type.RELATIVE) { - var diff = tpb; - cc.pIn(diff, currentPosition); - cc.pSubIn(diff, selParticle.startPos); + var diff = tpb, localStartPos = tpc; + // current Position convert To Node Space + cc._pointApplyAffineTransformIn(currentPosition, worldToNodeTransform, diff); + // start Position convert To Node Space + cc._pointApplyAffineTransformIn(selParticle.startPos, worldToNodeTransform, localStartPos); + cc.pSubIn(diff, localStartPos); cc.pIn(newPos, selParticle.pos); cc.pSubIn(newPos, diff); From f07fecffd62db77ce26dfe148c49fac301c227e6 Mon Sep 17 00:00:00 2001 From: zilongshanren Date: Thu, 1 Jun 2017 14:42:44 +0800 Subject: [PATCH 17/17] improve editbox memory management improve videoplayer memory management improve webview memory management add missing API doc annotation. improve API docs improve api docs remove unneeded code fix typo refine API docs remove unintened docs deletion --- cocos2d/core/components/CCEditBox.js | 14 +++++++++++++ cocos2d/core/components/CCVideoPlayer.js | 19 +++++++++++++++++- cocos2d/core/components/CCWebView.js | 15 +++++++++++++- cocos2d/core/editbox/CCSGEditBox.js | 22 ++++++++------------- cocos2d/core/videoplayer/CCSGVideoPlayer.js | 6 +++++- cocos2d/core/webview/CCSGWebView.js | 4 ++-- 6 files changed, 61 insertions(+), 19 deletions(-) diff --git a/cocos2d/core/components/CCEditBox.js b/cocos2d/core/components/CCEditBox.js index be6df3152a..cb36d22ede 100644 --- a/cocos2d/core/components/CCEditBox.js +++ b/cocos2d/core/components/CCEditBox.js @@ -626,3 +626,17 @@ cc.EditBox = module.exports = EditBox; * @param {Event.EventCustom} event * @param {EditBox} event.detail - The EditBox component. */ + +/** + * !#en if you don't need the EditBox and it isn't in any running Scene, you should + * call the destroy method on this component or the associated node explicitly. + * Otherwise, the created DOM element won't be removed from web page. + * !#zh + * 如果你不再使用 EditBox,并且组件未添加到场景中,那么你必须手动对组件或所在节点调用 destroy。 + * 这样才能移除网页上的 DOM 节点,避免 Web 平台内存泄露。 + * @example + * editbox.node.parent = null; // or editbox.node.removeFromParent(false); + * // when you don't need editbox anymore + * editbox.node.destroy(); + * @method destroy + */ diff --git a/cocos2d/core/components/CCVideoPlayer.js b/cocos2d/core/components/CCVideoPlayer.js index 2997f0c8a6..370c2791ab 100644 --- a/cocos2d/core/components/CCVideoPlayer.js +++ b/cocos2d/core/components/CCVideoPlayer.js @@ -347,6 +347,8 @@ var VideoPlayer = cc.Class({ /** * !#en Gets the duration of the video * !#zh 获取视频文件的播放总时长 + * @method getDuration + * @returns {Number} */ getDuration: function() { if(this._sgNode) { @@ -358,6 +360,8 @@ var VideoPlayer = cc.Class({ /** * !#en Determine whether video is playing or not. * !#zh 判断当前视频是否处于播放状态 + * @method isPlaying + * @returns {Boolean} */ isPlaying: function() { if(this._sgNode) { @@ -365,7 +369,6 @@ var VideoPlayer = cc.Class({ } return false; } - }); cc.VideoPlayer = module.exports = VideoPlayer; @@ -440,3 +443,17 @@ cc.VideoPlayer = module.exports = VideoPlayer; * @param {Event.EventCustom} event * @param {VideoPlayer} event.detail - The VideoPlayer component. */ + +/** + * !#en if you don't need the VideoPlayer and it isn't in any running Scene, you should + * call the destroy method on this component or the associated node explicitly. + * Otherwise, the created DOM element won't be removed from web page. + * !#zh + * 如果你不再使用 VideoPlayer,并且组件未添加到场景中,那么你必须手动对组件或所在节点调用 destroy。 + * 这样才能移除网页上的 DOM 节点,避免 Web 平台内存泄露。 + * @example + * videoplayer.node.parent = null; // or videoplayer.node.removeFromParent(false); + * // when you don't need videoplayer anymore + * videoplayer.node.destroy(); + * @method destroy + */ diff --git a/cocos2d/core/components/CCWebView.js b/cocos2d/core/components/CCWebView.js index 369d460399..03aed87c1f 100644 --- a/cocos2d/core/components/CCWebView.js +++ b/cocos2d/core/components/CCWebView.js @@ -152,7 +152,6 @@ var WebView = cc.Class({ cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.ERROR); this.node.emit('error', this); } - }); cc.WebView = module.exports = WebView; @@ -185,3 +184,17 @@ cc.WebView = module.exports = WebView; * @param {Event.EventCustom} event * @param {WebView} event.detail - The WebView component. */ + +/** + * !#en if you don't need the WebView and it isn't in any running Scene, you should + * call the destroy method on this component or the associated node explicitly. + * Otherwise, the created DOM element won't be removed from web page. + * !#zh + * 如果你不再使用 WebView,并且组件未添加到场景中,那么你必须手动对组件或所在节点调用 destroy。 + * 这样才能移除网页上的 DOM 节点,避免 Web 平台内存泄露。 + * @example + * webview.node.parent = null; // or webview.node.removeFromParent(false); + * // when you don't need webview anymore + * webview.node.destroy(); + * @method destroy + */ diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index 45d551a4c0..263ec6da75 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -321,15 +321,9 @@ _ccsg.EditBox = _ccsg.Node.extend({ this._renderCmd.stayOnTop(this._alwaysOnTop); }, - onEnter: function () { - _ccsg.Node.prototype.onEnter.call(this); - //in case the EditBox being used after changing parent - this.createDomElementIfNeeded(); - }, - - onExit: function () { - _ccsg.Node.prototype.onExit.call(this); - this._renderCmd._removeDomFromGameContainer(); + cleanup: function () { + this._super(); + this._renderCmd.removeDom(); }, _onTouchBegan: function (touch) { @@ -675,7 +669,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; proto._createDomInput = function () { - this._removeDomFromGameContainer(); + this.removeDom(); var thisPointer = this; var tmpEdTxt = this._edTxt = document.createElement('input'); @@ -770,7 +764,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; }; proto._createDomTextArea = function () { - this._removeDomFromGameContainer(); + this.removeDom(); var thisPointer = this; var tmpEdTxt = this._edTxt = document.createElement('textarea'); @@ -980,7 +974,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; } if (cc.sys.isMobile && !this._editingMode) { - // Pre adaptation and + // Pre adaptation and this._beginEditingOnMobile(this._editBox); } this._editingMode = true; @@ -1177,7 +1171,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; cc.game.container.appendChild(this._edTxt); }; - proto._removeDomFromGameContainer = function () { + proto.removeDom = function () { var editBox = this._edTxt; if(editBox){ var hasChild = Utils.contains(cc.game.container, editBox); @@ -1197,7 +1191,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; this._textLabel = null; this._placeholderLabel = null; this._editingMode = false; - + this.__fullscreen = false; this.__autoResize = false; this.__rotateScreen = false; diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index 1e07de42f0..45e4b17a4c 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -146,13 +146,17 @@ _ccsg.VideoPlayer = _ccsg.Node.extend(/** @lends _ccsg.VideoPlayer# */{ list.push(this); }, + cleanup: function () { + this._super(); + this._renderCmd.removeDom(); + }, + onExit: function () { _ccsg.Node.prototype.onExit.call(this); var list = _ccsg.VideoPlayer.elements; var index = list.indexOf(this); if(index !== -1) list.splice(index, 1); - this._renderCmd.removeDom(); }, setVisible: function ( visible ) { diff --git a/cocos2d/core/webview/CCSGWebView.js b/cocos2d/core/webview/CCSGWebView.js index 58b142c247..f80f2d3ce6 100644 --- a/cocos2d/core/webview/CCSGWebView.js +++ b/cocos2d/core/webview/CCSGWebView.js @@ -182,8 +182,8 @@ _ccsg.WebView = _ccsg.Node.extend(/** @lends _ccsg.WebView# */{ this._renderCmd.updateSize(width, height); }, - onExit: function () { - _ccsg.Node.prototype.onExit.call(this); + cleanup: function () { + this._super(); this._renderCmd.removeDom(); },