From 6cd573fa7f21fa4b42aaa0eaf106d9c62de3c60a Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 6 Dec 2013 18:16:58 +0800 Subject: [PATCH 01/27] issue #2790: Deprecates CCSet. --- cocos/2d/CCActionManager.cpp | 39 ++++++++++++++---------------- cocos/2d/CCActionManager.h | 24 +++++++++---------- cocos/2d/CCDeprecated.h | 8 ++++--- cocos/2d/CCLayer.h | 8 +++---- cocos/2d/CCScheduler.cpp | 27 ++++++++++----------- cocos/2d/CCScheduler.h | 15 ++++++------ cocos/base/CCDataVisitor.cpp | 8 +++---- cocos/base/CCDataVisitor.h | 6 ++--- cocos/base/CCSet.cpp | 46 ++++++++++++++++++------------------ cocos/base/CCSet.h | 20 ++++++++-------- 10 files changed, 97 insertions(+), 104 deletions(-) diff --git a/cocos/2d/CCActionManager.cpp b/cocos/2d/CCActionManager.cpp index d4981053c6..02ea7bb2dc 100644 --- a/cocos/2d/CCActionManager.cpp +++ b/cocos/2d/CCActionManager.cpp @@ -40,7 +40,7 @@ NS_CC_BEGIN typedef struct _hashElement { struct _ccArray *actions; - Object *target; + Node *target; int actionIndex; Action *currentAction; bool currentActionSalvaged; @@ -120,7 +120,7 @@ void ActionManager::removeActionAtIndex(int index, tHashElement *element) // pause / resume -void ActionManager::pauseTarget(Object *target) +void ActionManager::pauseTarget(Node *target) { tHashElement *element = NULL; HASH_FIND_PTR(_targets, &target, element); @@ -130,7 +130,7 @@ void ActionManager::pauseTarget(Object *target) } } -void ActionManager::resumeTarget(Object *target) +void ActionManager::resumeTarget(Node *target) { tHashElement *element = NULL; HASH_FIND_PTR(_targets, &target, element); @@ -140,30 +140,27 @@ void ActionManager::resumeTarget(Object *target) } } -Set* ActionManager::pauseAllRunningActions() +Vector ActionManager::pauseAllRunningActions() { - Set *idsWithActions = new Set(); - idsWithActions->autorelease(); + Vector idsWithActions; for (tHashElement *element=_targets; element != NULL; element = (tHashElement *)element->hh.next) { if (! element->paused) { element->paused = true; - idsWithActions->addObject(element->target); + idsWithActions.pushBack(element->target); } } - return idsWithActions; + return std::move(idsWithActions); } -void ActionManager::resumeTargets(cocos2d::Set *targetsToResume) -{ - SetIterator iter; - for (iter = targetsToResume->begin(); iter != targetsToResume->end(); ++iter) - { - resumeTarget(*iter); - } +void ActionManager::resumeTargets(const Vector& targetsToResume) +{ + targetsToResume.forEach([this](Node* node){ + this->resumeTarget(node); + }); } // run @@ -196,17 +193,17 @@ void ActionManager::addAction(Action *action, Node *target, bool paused) // remove -void ActionManager::removeAllActions(void) +void ActionManager::removeAllActions() { for (tHashElement *element = _targets; element != NULL; ) { - Object *target = element->target; + auto target = element->target; element = (tHashElement*)element->hh.next; removeAllActionsFromTarget(target); } } -void ActionManager::removeAllActionsFromTarget(Object *target) +void ActionManager::removeAllActionsFromTarget(Node *target) { // explicit null handling if (target == NULL) @@ -265,7 +262,7 @@ void ActionManager::removeAction(Action *action) } } -void ActionManager::removeActionByTag(int tag, Object *target) +void ActionManager::removeActionByTag(int tag, Node *target) { CCASSERT(tag != Action::INVALID_TAG, ""); CCASSERT(target != NULL, ""); @@ -293,7 +290,7 @@ void ActionManager::removeActionByTag(int tag, Object *target) // XXX: Passing "const O *" instead of "const O&" because HASH_FIND_IT requries the address of a pointer // and, it is not possible to get the address of a reference -Action* ActionManager::getActionByTag(int tag, const Object *target) const +Action* ActionManager::getActionByTag(int tag, const Node *target) const { CCASSERT(tag != Action::INVALID_TAG, ""); @@ -327,7 +324,7 @@ Action* ActionManager::getActionByTag(int tag, const Object *target) const // XXX: Passing "const O *" instead of "const O&" because HASH_FIND_IT requries the address of a pointer // and, it is not possible to get the address of a reference -int ActionManager::getNumberOfRunningActionsInTarget(const Object *target) const +int ActionManager::getNumberOfRunningActionsInTarget(const Node *target) const { tHashElement *element = NULL; HASH_FIND_PTR(_targets, &target, element); diff --git a/cocos/2d/CCActionManager.h b/cocos/2d/CCActionManager.h index 53d0fe1109..a2fc0dcfb9 100644 --- a/cocos/2d/CCActionManager.h +++ b/cocos/2d/CCActionManager.h @@ -29,13 +29,11 @@ THE SOFTWARE. #define __ACTION_CCACTION_MANAGER_H__ #include "CCAction.h" -#include "CCArray.h" +#include "CCVector.h" #include "CCObject.h" NS_CC_BEGIN -class Set; - struct _hashElement; /** @@ -78,50 +76,50 @@ public: /** Removes all actions from all the targets. */ - void removeAllActions(void); + void removeAllActions(); /** Removes all actions from a certain target. All the actions that belongs to the target will be removed. */ - void removeAllActionsFromTarget(Object *target); + void removeAllActionsFromTarget(Node *target); /** Removes an action given an action reference. */ void removeAction(Action *pAction); /** Removes an action given its tag and the target */ - void removeActionByTag(int tag, Object *target); + void removeActionByTag(int tag, Node *target); /** Gets an action given its tag an a target @return the Action the with the given tag */ - Action* getActionByTag(int tag, const Object *target) const; + Action* getActionByTag(int tag, const Node *target) const; /** Returns the numbers of actions that are running in a certain target. * Composable actions are counted as 1 action. Example: * - If you are running 1 Sequence of 7 actions, it will return 1. * - If you are running 7 Sequences of 2 actions, it will return 7. */ - int getNumberOfRunningActionsInTarget(const Object *target) const; + int getNumberOfRunningActionsInTarget(const Node *target) const; /** @deprecated use getNumberOfRunningActionsInTarget() instead */ - CC_DEPRECATED_ATTRIBUTE inline int numberOfRunningActionsInTarget(Object *target) const { return getNumberOfRunningActionsInTarget(target); } + CC_DEPRECATED_ATTRIBUTE inline int numberOfRunningActionsInTarget(Node *target) const { return getNumberOfRunningActionsInTarget(target); } /** Pauses the target: all running actions and newly added actions will be paused. */ - void pauseTarget(Object *target); + void pauseTarget(Node *target); /** Resumes the target. All queued actions will be resumed. */ - void resumeTarget(Object *target); + void resumeTarget(Node *target); /** Pauses all running actions, returning a list of targets whose actions were paused. */ - Set* pauseAllRunningActions(); + Vector pauseAllRunningActions(); /** Resume a set of targets (convenience function to reverse a pauseAllRunningActions call) */ - void resumeTargets(Set *targetsToResume); + void resumeTargets(const Vector& targetsToResume); protected: // declared in ActionManager.m diff --git a/cocos/2d/CCDeprecated.h b/cocos/2d/CCDeprecated.h index 323be9f642..d7b60f8074 100644 --- a/cocos/2d/CCDeprecated.h +++ b/cocos/2d/CCDeprecated.h @@ -540,7 +540,6 @@ CC_DEPRECATED_ATTRIBUTE typedef Bool CCBool; CC_DEPRECATED_ATTRIBUTE typedef Float CCFloat; CC_DEPRECATED_ATTRIBUTE typedef Double CCDouble; CC_DEPRECATED_ATTRIBUTE typedef Data CCData; -CC_DEPRECATED_ATTRIBUTE typedef Set CCSet; CC_DEPRECATED_ATTRIBUTE typedef Array CCArray; CC_DEPRECATED_ATTRIBUTE typedef Dictionary CCDictionary; CC_DEPRECATED_ATTRIBUTE typedef DataVisitor CCDataVisitor; @@ -549,7 +548,6 @@ CC_DEPRECATED_ATTRIBUTE typedef Acceleration CCAcceleration; CC_DEPRECATED_ATTRIBUTE typedef TextureAtlas CCTextureAtlas; CC_DEPRECATED_ATTRIBUTE typedef Configuration CCConfiguration; CC_DEPRECATED_ATTRIBUTE typedef PointArray CCPointArray; -CC_DEPRECATED_ATTRIBUTE typedef SetIterator CCSetIterator; CC_DEPRECATED_ATTRIBUTE typedef RemoveSelf CCRemoveSelf; CC_DEPRECATED_ATTRIBUTE typedef IMEDelegate CCIMEDelegate; CC_DEPRECATED_ATTRIBUTE typedef IMEKeyboardNotificationInfo CCIMEKeyboardNotificationInfo; @@ -568,7 +566,6 @@ CC_DEPRECATED_ATTRIBUTE typedef Speed CCSpeed; CC_DEPRECATED_ATTRIBUTE typedef Follow CCFollow; CC_DEPRECATED_ATTRIBUTE typedef GLProgram CCGLProgram; CC_DEPRECATED_ATTRIBUTE typedef Touch CCTouch; -CC_DEPRECATED_ATTRIBUTE typedef Set CCSet; CC_DEPRECATED_ATTRIBUTE typedef Texture2D CCTexture2D; CC_DEPRECATED_ATTRIBUTE typedef Node CCNode; CC_DEPRECATED_ATTRIBUTE typedef NodeRGBA CCNodeRGBA; @@ -1028,6 +1025,11 @@ CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLBindVAO(GLuint vaoId) { GL::bindV CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLEnable( int flags ) { /* ignore */ }; CC_DEPRECATED_ATTRIBUTE typedef int ccGLServerState; +CC_DEPRECATED_ATTRIBUTE typedef __Set CCSet; +CC_DEPRECATED_ATTRIBUTE typedef __SetIterator CCSetIterator; +CC_DEPRECATED_ATTRIBUTE typedef __Set Set; +CC_DEPRECATED_ATTRIBUTE typedef __SetIterator SetIterator; + NS_CC_END diff --git a/cocos/2d/CCLayer.h b/cocos/2d/CCLayer.h index 2284e7bf46..bccf5b091d 100644 --- a/cocos/2d/CCLayer.h +++ b/cocos/2d/CCLayer.h @@ -70,10 +70,10 @@ public: CC_DEPRECATED_ATTRIBUTE virtual void ccTouchEnded(Touch *pTouch, Event *pEvent) final {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} CC_DEPRECATED_ATTRIBUTE virtual void ccTouchCancelled(Touch *pTouch, Event *pEvent) final {CC_UNUSED_PARAM(pTouch); CC_UNUSED_PARAM(pEvent);} - CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesBegan(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} - CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesMoved(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} - CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesEnded(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} - CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesCancelled(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesBegan(__Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesMoved(__Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesEnded(__Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} + CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesCancelled(__Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} /* Callback function should not be deprecated, it will generate lots of warnings. Since 'setTouchEnabled' was deprecated, it will make warnings if developer overrides onTouchXXX and invokes setTouchEnabled(true) instead of using EventDispatcher::addEventListenerWithXXX. diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index 88f067f666..f1b1c9e59c 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -764,22 +764,21 @@ bool Scheduler::isTargetPaused(Object *target) return false; // should never get here } -Set* Scheduler::pauseAllTargets() +Vector Scheduler::pauseAllTargets() { return pauseAllTargetsWithMinPriority(PRIORITY_SYSTEM); } -Set* Scheduler::pauseAllTargetsWithMinPriority(int minPriority) +Vector Scheduler::pauseAllTargetsWithMinPriority(int minPriority) { - Set* idsWithSelectors = new Set();// setWithCapacity:50]; - idsWithSelectors->autorelease(); + Vector idsWithSelectors(50); // Custom Selectors for(tHashTimerEntry *element = _hashForTimers; element != nullptr; element = (tHashTimerEntry*)element->hh.next) { element->paused = true; - idsWithSelectors->addObject(element->target); + idsWithSelectors.pushBack(element->target); } // Updates selectors @@ -791,7 +790,7 @@ Set* Scheduler::pauseAllTargetsWithMinPriority(int minPriority) if(entry->priority >= minPriority) { entry->paused = true; - idsWithSelectors->addObject(entry->target); + idsWithSelectors.pushBack(entry->target); } } } @@ -801,7 +800,7 @@ Set* Scheduler::pauseAllTargetsWithMinPriority(int minPriority) DL_FOREACH_SAFE( _updates0List, entry, tmp ) { entry->paused = true; - idsWithSelectors->addObject(entry->target); + idsWithSelectors.pushBack(entry->target); } } @@ -810,20 +809,18 @@ Set* Scheduler::pauseAllTargetsWithMinPriority(int minPriority) if(entry->priority >= minPriority) { entry->paused = true; - idsWithSelectors->addObject(entry->target); + idsWithSelectors.pushBack(entry->target); } } - return idsWithSelectors; + return std::move(idsWithSelectors); } -void Scheduler::resumeTargets(Set* targetsToResume) +void Scheduler::resumeTargets(const Vector& targetsToResume) { - SetIterator iter; - for (iter = targetsToResume->begin(); iter != targetsToResume->end(); ++iter) - { - resumeTarget(*iter); - } + targetsToResume.forEach([this](Object* obj){ + this->resumeTarget(obj); + }); } void Scheduler::performFunctionInCocosThread(const std::function &function) diff --git a/cocos/2d/CCScheduler.h b/cocos/2d/CCScheduler.h index cfda2732d7..64325ae32f 100644 --- a/cocos/2d/CCScheduler.h +++ b/cocos/2d/CCScheduler.h @@ -27,13 +27,13 @@ THE SOFTWARE. #ifndef __CCSCHEDULER_H__ #define __CCSCHEDULER_H__ -#include +#include "CCObject.h" +#include "CCVector.h" +#include "uthash.h" + #include #include -#include "CCObject.h" -#include "uthash.h" - NS_CC_BEGIN /** @@ -41,7 +41,6 @@ NS_CC_BEGIN * @{ */ -class Set; // // Timer // @@ -247,19 +246,19 @@ public: You should NEVER call this method, unless you know what you are doing. @since v2.0.0 */ - Set* pauseAllTargets(); + Vector pauseAllTargets(); /** Pause all selectors from all targets with a minimum priority. You should only call this with kPriorityNonSystemMin or higher. @since v2.0.0 */ - Set* pauseAllTargetsWithMinPriority(int minPriority); + Vector pauseAllTargetsWithMinPriority(int minPriority); /** Resume selectors on a set of targets. This can be useful for undoing a call to pauseAllSelectors. @since v2.0.0 */ - void resumeTargets(Set* targetsToResume); + void resumeTargets(const Vector& targetsToResume); /** calls a function on the cocos2d thread. Useful when you need to call a cocos2d function from another thread. This function is thread safe. diff --git a/cocos/base/CCDataVisitor.cpp b/cocos/base/CCDataVisitor.cpp index 2d2a1f8121..a62b130cfa 100644 --- a/cocos/base/CCDataVisitor.cpp +++ b/cocos/base/CCDataVisitor.cpp @@ -70,7 +70,7 @@ void DataVisitor::visit(const Dictionary *value) visitObject(value); } -void DataVisitor::visit(const Set *value) +void DataVisitor::visit(const __Set *value) { visitObject(value); } @@ -194,7 +194,7 @@ void PrettyPrinter::visit(const Dictionary *p) _result += ""; } -void PrettyPrinter::visit(const Set *p) +void PrettyPrinter::visit(const __Set *p) { _result += "\n"; _result += _indentStr; @@ -203,8 +203,8 @@ void PrettyPrinter::visit(const Set *p) setIndentLevel(_indentLevel+1); int i = 0; - Set* tmp = const_cast(p); - SetIterator it = tmp->begin(); + __Set* tmp = const_cast<__Set*>(p); + __SetIterator it = tmp->begin(); for (; it != tmp->end(); ++it, ++i) { if (i > 0) { diff --git a/cocos/base/CCDataVisitor.h b/cocos/base/CCDataVisitor.h index 93d2463f29..ba8b83726f 100644 --- a/cocos/base/CCDataVisitor.h +++ b/cocos/base/CCDataVisitor.h @@ -38,7 +38,7 @@ class Double; class String; class Array; class Dictionary; -class Set; +class __Set; class Data; /** @@ -79,7 +79,7 @@ public: virtual void visit(const String *p); virtual void visit(const Array *p); virtual void visit(const Dictionary *p); - virtual void visit(const Set *p); + virtual void visit(const __Set *p); virtual void visit(const Data *p); }; @@ -100,7 +100,7 @@ public: virtual void visit(const String *p); virtual void visit(const Array *p); virtual void visit(const Dictionary *p); - virtual void visit(const Set *p); + virtual void visit(const __Set *p); virtual void visit(const Data *p); private: void setIndentLevel(int indentLevel); diff --git a/cocos/base/CCSet.cpp b/cocos/base/CCSet.cpp index c3c24e0e5e..b3e565c6f4 100644 --- a/cocos/base/CCSet.cpp +++ b/cocos/base/CCSet.cpp @@ -28,17 +28,17 @@ using namespace std; NS_CC_BEGIN -Set::Set(void) +__Set::__Set(void) { _set = new set; } -Set::Set(const Set &rSetObject) +__Set::__Set(const __Set &r__SetObject) { - _set = new set(*rSetObject._set); + _set = new set(*r__SetObject._set); // call retain of members - SetIterator iter; + __SetIterator iter; for (iter = _set->begin(); iter != _set->end(); ++iter) { if (! (*iter)) @@ -50,20 +50,20 @@ Set::Set(const Set &rSetObject) } } -Set::~Set(void) +__Set::~__Set(void) { removeAllObjects(); CC_SAFE_DELETE(_set); } -void Set::acceptVisitor(DataVisitor &visitor) +void __Set::acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } -Set * Set::create() +__Set * __Set::create() { - Set * pRet = new Set(); + __Set * pRet = new __Set(); if (pRet != NULL) { @@ -73,24 +73,24 @@ Set * Set::create() return pRet; } -Set* Set::copy(void) +__Set* __Set::copy(void) { - Set *pSet = new Set(*this); + __Set *p__Set = new __Set(*this); - return pSet; + return p__Set; } -Set* Set::mutableCopy(void) +__Set* __Set::mutableCopy(void) { return copy(); } -int Set::count(void) +int __Set::count(void) { return (int)_set->size(); } -void Set::addObject(Object *pObject) +void __Set::addObject(Object *pObject) { if (_set->count(pObject) == 0) { @@ -99,7 +99,7 @@ void Set::addObject(Object *pObject) } } -void Set::removeObject(Object *pObject) +void __Set::removeObject(Object *pObject) { if (_set->erase(pObject) > 0) { @@ -107,10 +107,10 @@ void Set::removeObject(Object *pObject) } } -void Set::removeAllObjects() +void __Set::removeAllObjects() { - SetIterator it = _set->begin(); - SetIterator tmp; + __SetIterator it = _set->begin(); + __SetIterator tmp; while (it != _set->end()) { @@ -128,29 +128,29 @@ void Set::removeAllObjects() } } -bool Set::containsObject(Object *pObject) +bool __Set::containsObject(Object *pObject) { return _set->find(pObject) != _set->end(); } -SetIterator Set::begin(void) +__SetIterator __Set::begin(void) { return _set->begin(); } -SetIterator Set::end(void) +__SetIterator __Set::end(void) { return _set->end(); } -Object* Set::anyObject() +Object* __Set::anyObject() { if (!_set || _set->empty()) { return 0; } - SetIterator it; + __SetIterator it; for( it = _set->begin(); it != _set->end(); ++it) { diff --git a/cocos/base/CCSet.h b/cocos/base/CCSet.h index c748f0ada5..89ef7d0ac4 100644 --- a/cocos/base/CCSet.h +++ b/cocos/base/CCSet.h @@ -35,35 +35,35 @@ NS_CC_BEGIN * @{ */ -typedef std::set::iterator SetIterator; +typedef std::set::iterator __SetIterator; -class CC_DLL Set : public Object +class CC_DLL __Set : public Object { public: /** * @js ctor */ - Set(void); - Set(const Set &rSetObject); + __Set(void); + __Set(const __Set &rSetObject); /** * @js NA * @lua NA */ - virtual ~Set(void); + virtual ~__Set(void); /** * @brief Create and return a new empty set. */ - static Set * create(); + static __Set * create(); /** *@brief Return a copy of the Set, it will copy all the elements. */ - Set* copy(); + __Set* copy(); /** *@brief It is the same as copy(). */ - Set* mutableCopy(); + __Set* mutableCopy(); /** *@brief Return the number of elements the Set contains. */ @@ -89,13 +89,13 @@ public: * @js NA * @lua NA */ - SetIterator begin(); + __SetIterator begin(); /** *@brief Return the iterator that points to the position after the last element. * @js NA * @lua NA */ - SetIterator end(); + __SetIterator end(); /** *@brief Return the first element if it contains elements, or null if it doesn't contain any element. */ From 23ad9f4e1a4489c3315803397bc1adc8049bd946 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 10:46:40 +0800 Subject: [PATCH 02/27] issue #2790: Adds const version of Vector::forEach. --- cocos/base/CCVector.h | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index 2a12c66d76..2314e325ba 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -25,10 +25,12 @@ THE SOFTWARE. #ifndef __CCVECTOR_H__ #define __CCVECTOR_H__ -#include -#include // std::for_each #include "ccMacros.h" +#include +#include +#include // std::for_each + NS_CC_BEGIN template @@ -299,9 +301,19 @@ public: _data.shrink_to_fit(); } - void forEach(std::function callback) + void forEach(const std::function& callback) { - if (size() <= 0) + if (empty()) + return; + + std::for_each(_data.cbegin(), _data.cend(), [&callback](const T& obj){ + callback(obj); + }); + } + + void forEach(const std::function& callback) const + { + if (empty()) return; std::for_each(_data.cbegin(), _data.cend(), [&callback](const T& obj){ @@ -309,9 +321,19 @@ public: }); } - void forEachReverse(std::function callback) + void forEachReverse(const std::function& callback) { - if (size() <= 0) + if (empty()) + return; + + std::for_each(_data.crbegin(), _data.crend(), [&callback](const T& obj){ + callback(obj); + }); + } + + void forEachReverse(const std::function& callback) const + { + if (empty()) return; std::for_each(_data.crbegin(), _data.crend(), [&callback](const T& obj){ From 165cdf7fe62469c8a5305b190fe5f1b7ffda3a58 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 10:48:02 +0800 Subject: [PATCH 03/27] issue #2790: Deprecates CCArray. --- cocos/2d/CCDeprecated.h | 2 +- cocos/2d/CCDirector.h | 4 +- cocos/2d/CCScheduler.h | 2 - cocos/base/CCArray.cpp | 170 +++++++++++++++---------------- cocos/base/CCArray.h | 33 +++--- cocos/base/CCDataVisitor.cpp | 4 +- cocos/base/CCDataVisitor.h | 6 +- cocos/base/CCDictionary.h | 16 +-- cocos/base/CCString.h | 2 +- cocos/physics/CCPhysicsBody.cpp | 22 ++-- cocos/physics/CCPhysicsBody.h | 11 +- cocos/physics/CCPhysicsWorld.cpp | 64 +++++------- cocos/physics/CCPhysicsWorld.h | 17 ++-- 13 files changed, 167 insertions(+), 186 deletions(-) diff --git a/cocos/2d/CCDeprecated.h b/cocos/2d/CCDeprecated.h index d7b60f8074..bae29435be 100644 --- a/cocos/2d/CCDeprecated.h +++ b/cocos/2d/CCDeprecated.h @@ -540,7 +540,6 @@ CC_DEPRECATED_ATTRIBUTE typedef Bool CCBool; CC_DEPRECATED_ATTRIBUTE typedef Float CCFloat; CC_DEPRECATED_ATTRIBUTE typedef Double CCDouble; CC_DEPRECATED_ATTRIBUTE typedef Data CCData; -CC_DEPRECATED_ATTRIBUTE typedef Array CCArray; CC_DEPRECATED_ATTRIBUTE typedef Dictionary CCDictionary; CC_DEPRECATED_ATTRIBUTE typedef DataVisitor CCDataVisitor; CC_DEPRECATED_ATTRIBUTE typedef PrettyPrinter CCPrettyPrinter; @@ -1030,6 +1029,7 @@ CC_DEPRECATED_ATTRIBUTE typedef __SetIterator CCSetIterator; CC_DEPRECATED_ATTRIBUTE typedef __Set Set; CC_DEPRECATED_ATTRIBUTE typedef __SetIterator SetIterator; + NS_CC_END diff --git a/cocos/2d/CCDirector.h b/cocos/2d/CCDirector.h index 9ff23333a1..78c2a96114 100644 --- a/cocos/2d/CCDirector.h +++ b/cocos/2d/CCDirector.h @@ -32,7 +32,7 @@ THE SOFTWARE. #include "CCObject.h" #include "ccTypes.h" #include "CCGeometry.h" -#include "CCArray.h" +#include "CCVector.h" #include "CCGL.h" #include "kazmath/mat4.h" #include "CCLabelAtlas.h" @@ -446,7 +446,7 @@ protected: bool _sendCleanupToScene; /* scheduled scenes */ - Array* _scenesStack; + Vector _scenesStack; /* last time the main loop was updated */ struct timeval *_lastUpdate; diff --git a/cocos/2d/CCScheduler.h b/cocos/2d/CCScheduler.h index 64325ae32f..247b773d00 100644 --- a/cocos/2d/CCScheduler.h +++ b/cocos/2d/CCScheduler.h @@ -108,8 +108,6 @@ struct _listEntry; struct _hashSelectorEntry; struct _hashUpdateEntry; -class Array; - /** @brief Scheduler is responsible for triggering the scheduled callbacks. You should not use NSTimer. Instead use this class. diff --git a/cocos/base/CCArray.cpp b/cocos/base/CCArray.cpp index adb09c237a..333183a822 100644 --- a/cocos/base/CCArray.cpp +++ b/cocos/base/CCArray.cpp @@ -36,15 +36,15 @@ NS_CC_BEGIN // std::vector implementation // ---------------------------------------------------------------------------------- -Array::Array() +__Array::Array() : data(NULL) { init(); } -Array* Array::create() +__Array* __Array::create() { - Array* array = new Array(); + __Array* array = new __Array(); if (array && array->initWithCapacity(7)) { @@ -58,9 +58,9 @@ Array* Array::create() return array; } -Array* Array::createWithObject(Object* object) +__Array* __Array::createWithObject(Object* object) { - Array* array = new Array(); + __Array* array = new __Array(); if (array && array->initWithObject(object)) { @@ -74,12 +74,12 @@ Array* Array::createWithObject(Object* object) return array; } -Array* Array::create(Object* object, ...) +__Array* __Array::create(Object* object, ...) { va_list args; va_start(args,object); - Array* array = create(); + __Array* array = create(); if (array && object) { array->addObject(object); @@ -100,16 +100,16 @@ Array* Array::create(Object* object, ...) return array; } -Array* Array::createWithArray(Array* otherArray) +__Array* __Array::createWithArray(__Array* otherArray) { return otherArray->clone(); } -Array* Array::createWithCapacity(int capacity) +__Array* __Array::createWithCapacity(int capacity) { CCASSERT(capacity>=0, "Invalid capacity"); - Array* array = new Array(); + __Array* array = new __Array(); if (array && array->initWithCapacity(capacity)) { @@ -123,9 +123,9 @@ Array* Array::createWithCapacity(int capacity) return array; } -Array* Array::createWithContentsOfFile(const char* fileName) +__Array* __Array::createWithContentsOfFile(const char* fileName) { - Array* ret = Array::createWithContentsOfFileThreadSafe(fileName); + __Array* ret = __Array::createWithContentsOfFileThreadSafe(fileName); if (ret != nullptr) { ret->autorelease(); @@ -133,17 +133,17 @@ Array* Array::createWithContentsOfFile(const char* fileName) return ret; } -Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) +__Array* __Array::createWithContentsOfFileThreadSafe(const char* fileName) { return FileUtils::getInstance()->createArrayWithContentsOfFile(fileName); } -bool Array::init() +bool __Array::init() { return initWithCapacity(7); } -bool Array::initWithObject(Object* object) +bool __Array::initWithObject(Object* object) { bool ret = initWithCapacity(7); if (ret) @@ -154,7 +154,7 @@ bool Array::initWithObject(Object* object) } /** Initializes an array with some objects */ -bool Array::initWithObjects(Object* object, ...) +bool __Array::initWithObjects(Object* object, ...) { bool ret = false; do @@ -182,7 +182,7 @@ bool Array::initWithObjects(Object* object, ...) return ret; } -bool Array::initWithCapacity(int capacity) +bool __Array::initWithCapacity(int capacity) { CCASSERT(capacity>=0, "Invalid capacity"); @@ -190,13 +190,13 @@ bool Array::initWithCapacity(int capacity) return true; } -bool Array::initWithArray(Array* otherArray) +bool __Array::initWithArray(__Array* otherArray) { data = otherArray->data; return true; } -int Array::getIndexOfObject(Object* object) const +int __Array::getIndexOfObject(Object* object) const { auto it = data.begin(); @@ -211,7 +211,7 @@ int Array::getIndexOfObject(Object* object) const return -1; } -Object* Array::getRandomObject() +Object* __Array::getRandomObject() { if (data.size()==0) { @@ -230,13 +230,13 @@ Object* Array::getRandomObject() return data[r].get(); } -bool Array::containsObject(Object* object) const +bool __Array::containsObject(Object* object) const { auto i = this->getIndexOfObject(object); return (i >= 0); } -bool Array::isEqualToArray(Array* otherArray) +bool __Array::isEqualToArray(__Array* otherArray) { for (int i = 0; i < this->count(); ++i) { @@ -248,64 +248,64 @@ bool Array::isEqualToArray(Array* otherArray) return true; } -void Array::addObject(Object* object) +void __Array::addObject(Object* object) { data.push_back(RCPtr(object)); } -void Array::addObjectsFromArray(Array* otherArray) +void __Array::addObjectsFromArray(__Array* otherArray) { data.insert(data.end(), otherArray->data.begin(), otherArray->data.end()); } -void Array::insertObject(Object* object, int index) +void __Array::insertObject(Object* object, int index) { data.insert(std::begin(data) + index, RCPtr(object)); } -void Array::setObject(Object* object, int index) +void __Array::setObject(Object* object, int index) { data[index] = RCPtr(object); } -void Array::removeLastObject(bool releaseObj) +void __Array::removeLastObject(bool releaseObj) { CCASSERT(data.size(), "no objects added"); data.pop_back(); } -void Array::removeObject(Object* object, bool releaseObj /* ignored */) +void __Array::removeObject(Object* object, bool releaseObj /* ignored */) { data.erase(std::remove(data.begin(), data.end(), object)); } -void Array::removeObjectAtIndex(int index, bool releaseObj /* ignored */) +void __Array::removeObjectAtIndex(int index, bool releaseObj /* ignored */) { auto obj = data[index]; data.erase(data.begin() + index); } -void Array::removeObjectsInArray(Array* otherArray) +void __Array::removeObjectsInArray(__Array* otherArray) { CCASSERT(false, "not implemented"); } -void Array::removeAllObjects() +void __Array::removeAllObjects() { data.erase(std::begin(data), std::end(data)); } -void Array::fastRemoveObjectAtIndex(int index) +void __Array::fastRemoveObjectAtIndex(int index) { removeObjectAtIndex(index); } -void Array::fastRemoveObject(Object* object) +void __Array::fastRemoveObject(Object* object) { removeObject(object); } -void Array::exchangeObject(Object* object1, Object* object2) +void __Array::exchangeObject(Object* object1, Object* object2) { auto idx1 = getIndexOfObject(object1); auto idx2 = getIndexOfObject(object2); @@ -315,34 +315,34 @@ void Array::exchangeObject(Object* object1, Object* object2) std::swap(data[idx1], data[idx2]); } -void Array::exchangeObjectAtIndex(int index1, int index2) +void __Array::exchangeObjectAtIndex(int index1, int index2) { std::swap(data[index1], data[index2]); } -void Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject /* ignored */) +void __Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject /* ignored */) { data[index] = object; } -void Array::reverseObjects() +void __Array::reverseObjects() { std::reverse(std::begin(data), std::end(data)); } -void Array::reduceMemoryFootprint() +void __Array::reduceMemoryFootprint() { // N/A } -Array::~Array() +__Array::~Array() { CCLOGINFO("deallocing Array: %p - len: %d", this, count() ); } -Array* Array::clone() const +__Array* __Array::clone() const { - Array* ret = new Array(); + __Array* ret = new __Array(); ret->autorelease(); ret->initWithCapacity(this->data.size() > 0 ? this->data.size() : 1); @@ -368,7 +368,7 @@ Array* Array::clone() const return ret; } -void Array::acceptVisitor(DataVisitor &visitor) +void __Array::acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } @@ -379,15 +379,15 @@ void Array::acceptVisitor(DataVisitor &visitor) #else -Array::Array() +__Array::__Array() : data(nullptr) { // init(); } -Array* Array::create() +__Array* __Array::create() { - Array* array = new Array(); + __Array* array = new __Array(); if (array && array->initWithCapacity(7)) { @@ -401,9 +401,9 @@ Array* Array::create() return array; } -Array* Array::createWithObject(Object* object) +__Array* __Array::createWithObject(Object* object) { - Array* array = new Array(); + __Array* array = new __Array(); if (array && array->initWithObject(object)) { @@ -417,12 +417,12 @@ Array* Array::createWithObject(Object* object) return array; } -Array* Array::create(Object* object, ...) +__Array* __Array::create(Object* object, ...) { va_list args; va_start(args,object); - Array* array = create(); + __Array* array = create(); if (array && object) { array->addObject(object); @@ -443,16 +443,16 @@ Array* Array::create(Object* object, ...) return array; } -Array* Array::createWithArray(Array* otherArray) +__Array* __Array::createWithArray(__Array* otherArray) { return otherArray->clone(); } -Array* Array::createWithCapacity(int capacity) +__Array* __Array::createWithCapacity(int capacity) { CCASSERT(capacity>=0, "Invalid capacity"); - Array* array = new Array(); + __Array* array = new __Array(); if (array && array->initWithCapacity(capacity)) { @@ -466,9 +466,9 @@ Array* Array::createWithCapacity(int capacity) return array; } -Array* Array::createWithContentsOfFile(const char* fileName) +__Array* __Array::createWithContentsOfFile(const char* fileName) { - Array* ret = Array::createWithContentsOfFileThreadSafe(fileName); + __Array* ret = __Array::createWithContentsOfFileThreadSafe(fileName); if (ret != nullptr) { ret->autorelease(); @@ -476,11 +476,11 @@ Array* Array::createWithContentsOfFile(const char* fileName) return ret; } -Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) +__Array* __Array::createWithContentsOfFileThreadSafe(const char* fileName) { ValueVector arr = FileUtils::getInstance()->getValueVectorFromFile(fileName); - Array* ret = Array::createWithCapacity(static_cast(arr.size())); + __Array* ret = __Array::createWithCapacity(static_cast(arr.size())); std::for_each(arr.cbegin(), arr.cend(), [&ret](const Value& value){ ret->addObject(String::create(value.asString())); @@ -489,14 +489,14 @@ Array* Array::createWithContentsOfFileThreadSafe(const char* fileName) return ret; } -bool Array::init() +bool __Array::init() { CCASSERT(!data, "Array cannot be re-initialized"); return initWithCapacity(7); } -bool Array::initWithObject(Object* object) +bool __Array::initWithObject(Object* object) { CCASSERT(!data, "Array cannot be re-initialized"); @@ -509,7 +509,7 @@ bool Array::initWithObject(Object* object) } /** Initializes an array with some objects */ -bool Array::initWithObjects(Object* object, ...) +bool __Array::initWithObjects(Object* object, ...) { CCASSERT(!data, "Array cannot be re-initialized"); @@ -539,7 +539,7 @@ bool Array::initWithObjects(Object* object, ...) return ret; } -bool Array::initWithCapacity(int capacity) +bool __Array::initWithCapacity(int capacity) { CCASSERT(capacity>=0 && !data, "Array cannot be re-initialized"); @@ -547,7 +547,7 @@ bool Array::initWithCapacity(int capacity) return true; } -bool Array::initWithArray(Array* otherArray) +bool __Array::initWithArray(__Array* otherArray) { CCASSERT(!data, "Array cannot be re-initialized"); @@ -563,12 +563,12 @@ bool Array::initWithArray(Array* otherArray) return ret; } -int Array::getIndexOfObject(Object* object) const +int __Array::getIndexOfObject(Object* object) const { return ccArrayGetIndexOfObject(data, object); } -Object* Array::getRandomObject() +Object* __Array::getRandomObject() { if (data->num == 0) { @@ -585,12 +585,12 @@ Object* Array::getRandomObject() return data->arr[static_cast(data->num * r)]; } -bool Array::containsObject(Object* object) const +bool __Array::containsObject(Object* object) const { return ccArrayContainsObject(data, object); } -bool Array::isEqualToArray(Array* otherArray) +bool __Array::isEqualToArray(__Array* otherArray) { for (int i = 0; i < this->count(); ++i) { @@ -602,25 +602,25 @@ bool Array::isEqualToArray(Array* otherArray) return true; } -void Array::addObject(Object* object) +void __Array::addObject(Object* object) { CCASSERT(data, "Array not initialized"); ccArrayAppendObjectWithResize(data, object); } -void Array::addObjectsFromArray(Array* otherArray) +void __Array::addObjectsFromArray(__Array* otherArray) { CCASSERT(data, "Array not initialized"); ccArrayAppendArrayWithResize(data, otherArray->data); } -void Array::insertObject(Object* object, int index) +void __Array::insertObject(Object* object, int index) { CCASSERT(data, "Array not initialized"); ccArrayInsertObjectAtIndex(data, object, index); } -void Array::setObject(Object* object, int index) +void __Array::setObject(Object* object, int index) { CCASSERT(index >= 0 && index < count(), "Invalid index"); @@ -632,43 +632,43 @@ void Array::setObject(Object* object, int index) } } -void Array::removeLastObject(bool releaseObj) +void __Array::removeLastObject(bool releaseObj) { CCASSERT(data->num, "no objects added"); ccArrayRemoveObjectAtIndex(data, data->num - 1, releaseObj); } -void Array::removeObject(Object* object, bool releaseObj/* = true*/) +void __Array::removeObject(Object* object, bool releaseObj/* = true*/) { ccArrayRemoveObject(data, object, releaseObj); } -void Array::removeObjectAtIndex(int index, bool releaseObj) +void __Array::removeObjectAtIndex(int index, bool releaseObj) { ccArrayRemoveObjectAtIndex(data, index, releaseObj); } -void Array::removeObjectsInArray(Array* otherArray) +void __Array::removeObjectsInArray(__Array* otherArray) { ccArrayRemoveArray(data, otherArray->data); } -void Array::removeAllObjects() +void __Array::removeAllObjects() { ccArrayRemoveAllObjects(data); } -void Array::fastRemoveObjectAtIndex(int index) +void __Array::fastRemoveObjectAtIndex(int index) { ccArrayFastRemoveObjectAtIndex(data, index); } -void Array::fastRemoveObject(Object* object) +void __Array::fastRemoveObject(Object* object) { ccArrayFastRemoveObject(data, object); } -void Array::exchangeObject(Object* object1, Object* object2) +void __Array::exchangeObject(Object* object1, Object* object2) { auto index1 = ccArrayGetIndexOfObject(data, object1); if (index1 == CC_INVALID_INDEX) @@ -685,18 +685,18 @@ void Array::exchangeObject(Object* object1, Object* object2) ccArraySwapObjectsAtIndexes(data, index1, index2); } -void Array::exchangeObjectAtIndex(int index1, int index2) +void __Array::exchangeObjectAtIndex(int index1, int index2) { ccArraySwapObjectsAtIndexes(data, index1, index2); } -void Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject/* = true*/) +void __Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject/* = true*/) { ccArrayInsertObjectAtIndex(data, object, index); ccArrayRemoveObjectAtIndex(data, index + 1); } -void Array::reverseObjects() +void __Array::reverseObjects() { if (data->num > 1) { @@ -712,21 +712,21 @@ void Array::reverseObjects() } } -void Array::reduceMemoryFootprint() +void __Array::reduceMemoryFootprint() { ccArrayShrink(data); } -Array::~Array() +__Array::~__Array() { CCLOGINFO("deallocing Array: %p - len: %d", this, count() ); ccArrayFree(data); } -Array* Array::clone() const +__Array* __Array::clone() const { - Array* ret = new Array(); + __Array* ret = new __Array(); ret->autorelease(); ret->initWithCapacity(this->data->num > 0 ? this->data->num : 1); @@ -752,7 +752,7 @@ Array* Array::clone() const return ret; } -void Array::acceptVisitor(DataVisitor &visitor) +void __Array::acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } diff --git a/cocos/base/CCArray.h b/cocos/base/CCArray.h index 7f67569faa..d5df307745 100644 --- a/cocos/base/CCArray.h +++ b/cocos/base/CCArray.h @@ -230,7 +230,7 @@ while(false) NS_CC_BEGIN -class CC_DLL Array : public Object, public Clonable +class CC_DLL __Array : public Object, public Clonable { public: @@ -238,30 +238,30 @@ public: * @js NA * @lua NA */ - static Array* create(); + static __Array* create(); /** Create an array with objects * @js NA */ - static Array* create(Object* object, ...) CC_REQUIRES_NULL_TERMINATION; + static __Array* create(Object* object, ...) CC_REQUIRES_NULL_TERMINATION; /** Create an array with one object * @js NA */ - static Array* createWithObject(Object* object); + static __Array* createWithObject(Object* object); /** Create an array with a default capacity * @js NA */ - static Array* createWithCapacity(int capacity); + static __Array* createWithCapacity(int capacity); /** Create an array with from an existing array * @js NA */ - static Array* createWithArray(Array* otherArray); + static __Array* createWithArray(__Array* otherArray); /** @brief Generate a Array pointer by file @param pFileName The file name of *.plist file @return The Array pointer generated from the file * @js NA */ - static Array* createWithContentsOfFile(const char* pFileName); + static __Array* createWithContentsOfFile(const char* pFileName); /* @brief The same meaning as arrayWithContentsOfFile(), but it doesn't call autorelease, so the @@ -269,12 +269,12 @@ public: * @js NA * @lua NA */ - static Array* createWithContentsOfFileThreadSafe(const char* pFileName); + static __Array* createWithContentsOfFileThreadSafe(const char* pFileName); /** * @js NA * @lua NA */ - ~Array(); + ~__Array(); /** Initializes an array * @js NA @@ -300,7 +300,7 @@ public: * @js NA * @lua NA */ - bool initWithArray(Array* otherArray); + bool initWithArray(__Array* otherArray); // Querying an Array @@ -384,7 +384,7 @@ public: /** @since 1.1 * @js NA */ - bool isEqualToArray(Array* otherArray); + bool isEqualToArray(__Array* otherArray); // Adding Objects /** Add a certain object @@ -397,7 +397,7 @@ public: /** Add all elements of an existing array * @js NA */ - void addObjectsFromArray(Array* otherArray); + void addObjectsFromArray(__Array* otherArray); /** Insert a certain object at a certain index * @js NA */ @@ -451,7 +451,7 @@ public: /** Remove all elements * @js NA */ - void removeObjectsInArray(Array* otherArray); + void removeObjectsInArray(__Array* otherArray); /** Remove all objects * @js NA */ @@ -498,7 +498,7 @@ public: * @js NA * @lua NA */ - virtual Array* clone() const; + virtual __Array* clone() const; // ------------------------------------------ // Iterators @@ -546,12 +546,15 @@ public: * @js NA * @lua NA */ - Array(); + __Array(); }; // end of data_structure group /// @} +CC_DEPRECATED_ATTRIBUTE typedef __Array CCArray; +CC_DEPRECATED_ATTRIBUTE typedef __Array Array; + NS_CC_END #endif // __CCARRAY_H__ diff --git a/cocos/base/CCDataVisitor.cpp b/cocos/base/CCDataVisitor.cpp index a62b130cfa..5f7d95203c 100644 --- a/cocos/base/CCDataVisitor.cpp +++ b/cocos/base/CCDataVisitor.cpp @@ -60,7 +60,7 @@ void DataVisitor::visit(const String *value) visitObject(value); } -void DataVisitor::visit(const Array *value) +void DataVisitor::visit(const __Array *value) { visitObject(value); } @@ -136,7 +136,7 @@ void PrettyPrinter::visit(const String *p) _result += p->getCString(); } -void PrettyPrinter::visit(const Array *p) +void PrettyPrinter::visit(const __Array *p) { _result += "\n"; _result += _indentStr; diff --git a/cocos/base/CCDataVisitor.h b/cocos/base/CCDataVisitor.h index ba8b83726f..9abb1f1424 100644 --- a/cocos/base/CCDataVisitor.h +++ b/cocos/base/CCDataVisitor.h @@ -36,7 +36,7 @@ class Integer; class Float; class Double; class String; -class Array; +class __Array; class Dictionary; class __Set; class Data; @@ -77,7 +77,7 @@ public: virtual void visit(const Float *p); virtual void visit(const Double *p); virtual void visit(const String *p); - virtual void visit(const Array *p); + virtual void visit(const __Array *p); virtual void visit(const Dictionary *p); virtual void visit(const __Set *p); virtual void visit(const Data *p); @@ -98,7 +98,7 @@ public: virtual void visit(const Float *p); virtual void visit(const Double *p); virtual void visit(const String *p); - virtual void visit(const Array *p); + virtual void visit(const __Array *p); virtual void visit(const Dictionary *p); virtual void visit(const __Set *p); virtual void visit(const Data *p); diff --git a/cocos/base/CCDictionary.h b/cocos/base/CCDictionary.h index 63082109b3..323241a19c 100644 --- a/cocos/base/CCDictionary.h +++ b/cocos/base/CCDictionary.h @@ -207,7 +207,7 @@ public: * @return The array contains all keys of elements. It's an autorelease object yet. * @js NA */ - Array* allKeys(); + __Array* allKeys(); /** * Get all keys according to the specified object. @@ -215,7 +215,7 @@ public: * @return The array contains all keys for the specified object. It's an autorelease object yet. * @js NA */ - Array* allKeysForObject(Object* object); + __Array* allKeysForObject(Object* object); /** * Get the object according to the specified string key. @@ -302,7 +302,7 @@ public: * Remove an object by the specified string key. * * @param key The string key for searching. - * @see removeObjectForKey(intptr_t), removeObjectsForKeys(Array*), + * @see removeObjectForKey(intptr_t), removeObjectsForKeys(__Array*), * removeObjectForElememt(DictElement*), removeAllObjects(). * @js NA */ @@ -312,7 +312,7 @@ public: * Remove an object by the specified integer key. * * @param key The integer key for searching. - * @see removeObjectForKey(const std::string&), removeObjectsForKeys(Array*), + * @see removeObjectForKey(const std::string&), removeObjectsForKeys(__Array*), * removeObjectForElememt(DictElement*), removeAllObjects(). * @js NA */ @@ -321,19 +321,19 @@ public: /** * Remove objects by an array of keys. * - * @param pKeyArray The array contains keys to be removed. + * @param pKey__Array The array contains keys to be removed. * @see removeObjectForKey(const std::string&), removeObjectForKey(intptr_t), * removeObjectForElememt(DictElement*), removeAllObjects(). * @js NA */ - void removeObjectsForKeys(Array* pKeyArray); + void removeObjectsForKeys(__Array* pKey__Array); /** * Remove an object by an element. * * @param pElement The element need to be removed. * @see removeObjectForKey(const std::string&), removeObjectForKey(intptr_t), - * removeObjectsForKeys(Array*), removeAllObjects(). + * removeObjectsForKeys(__Array*), removeAllObjects(). * @js NA * @lua NA */ @@ -343,7 +343,7 @@ public: * Remove all objects in the dictionary. * * @see removeObjectForKey(const std::string&), removeObjectForKey(intptr_t), - * removeObjectsForKeys(Array*), removeObjectForElememt(DictElement*). + * removeObjectsForKeys(__Array*), removeObjectForElememt(DictElement*). * @js NA */ void removeAllObjects(); diff --git a/cocos/base/CCString.h b/cocos/base/CCString.h index 09d558f827..19af0302e2 100644 --- a/cocos/base/CCString.h +++ b/cocos/base/CCString.h @@ -137,7 +137,7 @@ public: * @js NA * @lua NA */ - Array* componentsSeparatedByString(const char *delimiter); + __Array* componentsSeparatedByString(const char *delimiter); /* override functions * @js NA diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index d351444abd..7b78ee4664 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -51,7 +51,6 @@ namespace PhysicsBody::PhysicsBody() : _node(nullptr) -, _shapes(nullptr) , _world(nullptr) , _info(nullptr) , _dynamic(true) @@ -251,9 +250,6 @@ bool PhysicsBody::init() { _info = new PhysicsBodyInfo(); CC_BREAK_IF(_info == nullptr); - _shapes = Array::create(); - CC_BREAK_IF(_shapes == nullptr); - _shapes->retain(); _info->setBody(cpBodyNew(PhysicsHelper::float2cpfloat(_mass), PhysicsHelper::float2cpfloat(_moment))); @@ -368,7 +364,7 @@ PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape, bool addMassAndMoment/* if (shape == nullptr) return nullptr; // add shape to body - if (_shapes->getIndexOfObject(shape) == CC_INVALID_INDEX) + if (_shapes.getIndex(shape) == -1) { shape->setBody(this); @@ -386,7 +382,7 @@ PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape, bool addMassAndMoment/* _world->addShape(shape); } - _shapes->addObject(shape); + _shapes.pushBack(shape); if (_group != CP_NO_GROUP && shape->getGroup() == CP_NO_GROUP) { @@ -631,9 +627,8 @@ void PhysicsBody::setMoment(float moment) PhysicsShape* PhysicsBody::getShape(int tag) const { - for (auto child : *_shapes) + for (auto& shape : _shapes) { - PhysicsShape* shape = dynamic_cast(child); if (shape->getTag() == tag) { return shape; @@ -645,9 +640,8 @@ PhysicsShape* PhysicsBody::getShape(int tag) const void PhysicsBody::removeShape(int tag, bool reduceMassAndMoment/* = true*/) { - for (auto child : *_shapes) + for (auto& shape : _shapes) { - PhysicsShape* shape = dynamic_cast(child); if (shape->getTag() == tag) { removeShape(shape, reduceMassAndMoment); @@ -658,7 +652,7 @@ void PhysicsBody::removeShape(int tag, bool reduceMassAndMoment/* = true*/) void PhysicsBody::removeShape(PhysicsShape* shape, bool reduceMassAndMoment/* = true*/) { - if (_shapes->getIndexOfObject(shape) != CC_INVALID_INDEX) + if (_shapes->getIndexOfObject(shape) != -1) { // deduce the area, mass and moment // area must update before mass, because the density changes depend on it. @@ -678,13 +672,13 @@ void PhysicsBody::removeShape(PhysicsShape* shape, bool reduceMassAndMoment/* = // set shape->_body = nullptr make the shape->setBody will not trigger the _body->removeShape function call. shape->_body = nullptr; shape->setBody(nullptr); - _shapes->removeObject(shape); + _shapes.removeObject(shape); } } void PhysicsBody::removeAllShapes(bool reduceMassAndMoment/* = true*/) { - for (auto child : *_shapes) + for (auto& child : _shapes) { PhysicsShape* shape = dynamic_cast(child); @@ -707,7 +701,7 @@ void PhysicsBody::removeAllShapes(bool reduceMassAndMoment/* = true*/) shape->setBody(nullptr); } - _shapes->removeAllObjects(); + _shapes.clear(); } void PhysicsBody::removeFromWorld() diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index bc72aff57b..58145b75d2 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -30,11 +30,8 @@ #include "CCObject.h" #include "CCGeometry.h" -#include "CCArray.h" - #include "CCPhysicsShape.h" - -#include +#include "CCVector.h" NS_CC_BEGIN class Sprite; @@ -103,9 +100,9 @@ public: /* remove all shapes */ void removeAllShapes(bool reduceMassAndMoment = true); /* get the body shapes. */ - inline Array* getShapes() const { return _shapes; } + inline const Vector getShapes() const { return _shapes; } /* get the first shape of the body shapes. */ - inline PhysicsShape* getFirstShape() const { return _shapes->count() >= 1 ? dynamic_cast(_shapes->getObjectAtIndex(0)) : nullptr; } + inline PhysicsShape* getFirstShape() const { return _shapes.size() >= 1 ? _shapes.at(0) : nullptr; } /* get the shape of the body. */ PhysicsShape* getShape(int tag) const; @@ -305,7 +302,7 @@ protected: protected: Node* _node; std::vector _joints; - Array* _shapes; + Vector _shapes; PhysicsWorld* _world; PhysicsBodyInfo* _info; bool _dynamic; diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 41d6f08f9c..96a42c7797 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -97,7 +97,7 @@ public: static void rayCastCallbackFunc(cpShape *shape, cpFloat t, cpVect n, RayCastCallbackInfo *info); static void queryRectCallbackFunc(cpShape *shape, RectQueryCallbackInfo *info); static void queryPointFunc(cpShape *shape, cpFloat distance, cpVect point, PointQueryCallbackInfo *info); - static void getShapesAtPointFunc(cpShape *shape, cpFloat distance, cpVect point, Array *arr); + static void getShapesAtPointFunc(cpShape *shape, cpFloat distance, cpVect point, Vector* arr); public: static bool continues; @@ -176,13 +176,13 @@ void PhysicsWorldCallback::queryRectCallbackFunc(cpShape *shape, RectQueryCallba PhysicsWorldCallback::continues = info->func(*info->world, *it->second->getShape(), info->data); } -void PhysicsWorldCallback::getShapesAtPointFunc(cpShape *shape, cpFloat distance, cpVect point, Array *arr) +void PhysicsWorldCallback::getShapesAtPointFunc(cpShape *shape, cpFloat distance, cpVect point, Vector* arr) { auto it = PhysicsShapeInfo::getMap().find(shape); CC_ASSERT(it != PhysicsShapeInfo::getMap().end()); - arr->addObject(it->second->getShape()); + arr->pushBack(it->second->getShape()); } void PhysicsWorldCallback::queryPointFunc(cpShape *shape, cpFloat distance, cpVect point, PointQueryCallbackInfo *info) @@ -201,17 +201,17 @@ void PhysicsWorld::debugDraw() _debugDraw = new PhysicsDebugDraw(*this); } - if (_debugDraw && _bodies != nullptr) + if (_debugDraw && !_bodies.empty()) { if (_debugDraw->begin()) { if (_debugDrawMask & DEBUGDRAW_SHAPE) { - for (Object* obj : *_bodies) + for (Object* obj : _bodies) { PhysicsBody* body = dynamic_cast(obj); - for (auto shape : *body->getShapes()) + for (auto& shape : body->getShapes()) { _debugDraw->drawShape(*dynamic_cast(shape)); } @@ -392,16 +392,16 @@ void PhysicsWorld::queryPoint(PhysicsPointQueryCallbackFunc func, const Point& p } } -Array* PhysicsWorld::getShapes(const Point& point) const +Vector PhysicsWorld::getShapes(const Point& point) const { - Array* arr = Array::create(); + Vector arr; cpSpaceNearestPointQuery(this->_info->getSpace(), PhysicsHelper::point2cpv(point), 0, CP_ALL_LAYERS, CP_NO_GROUP, (cpSpaceNearestPointQueryFunc)PhysicsWorldCallback::getShapesAtPointFunc, - arr); + &arr); return arr; } @@ -562,17 +562,8 @@ bool PhysicsWorld::init(Scene& scene) { do { - _delayAddBodies = Array::create(); - _delayRemoveBodies = Array::create(); - CC_BREAK_IF(_delayAddBodies == nullptr || _delayRemoveBodies == nullptr); - _delayAddBodies->retain(); - _delayRemoveBodies->retain(); - _info = new PhysicsWorldInfo(); CC_BREAK_IF(_info == nullptr); - _bodies = Array::create(); - CC_BREAK_IF(_bodies == nullptr); - _bodies->retain(); _scene = &scene; @@ -606,7 +597,7 @@ void PhysicsWorld::addBody(PhysicsBody* body) } addBodyOrDelay(body); - _bodies->addObject(body); + _bodies.pushBack(body); body->_world = this; } @@ -627,7 +618,7 @@ void PhysicsWorld::doAddBody(PhysicsBody* body) } // add shapes to space - for (auto shape : *body->getShapes()) + for (auto& shape : body->getShapes()) { addShape(dynamic_cast(shape)); } @@ -637,17 +628,17 @@ void PhysicsWorld::doAddBody(PhysicsBody* body) void PhysicsWorld::addBodyOrDelay(PhysicsBody* body) { - if (_delayRemoveBodies->getIndexOfObject(body) != CC_INVALID_INDEX) + if (_delayRemoveBodies.getIndex(body) != CC_INVALID_INDEX) { - _delayRemoveBodies->removeObject(body); + _delayRemoveBodies.removeObject(body); return; } if (_info->isLocked()) { - if (_delayAddBodies->getIndexOfObject(body) == CC_INVALID_INDEX) + if (_delayAddBodies.getIndex(body) == CC_INVALID_INDEX) { - _delayAddBodies->addObject(body); + _delayAddBodies.pushBack(body); _delayDirty = true; } }else @@ -663,25 +654,24 @@ void PhysicsWorld::updateBodies() return; } - for (auto body : *_delayAddBodies) + for (auto& body : _delayAddBodies) { - doAddBody(dynamic_cast(body)); + doAddBody(body); } - for (auto body : *_delayRemoveBodies) + for (auto& body : _delayRemoveBodies) { - doRemoveBody(dynamic_cast(body)); + doRemoveBody(body); } - _delayAddBodies->removeAllObjects(); - _delayRemoveBodies->removeAllObjects(); + _delayAddBodies.clear(); + _delayRemoveBodies.clear(); } void PhysicsWorld::removeBody(int tag) { - for (Object* obj : *_bodies) + for (auto& body : _bodies) { - PhysicsBody* body = dynamic_cast(obj); if (body->getTag() == tag) { removeBody(body); @@ -722,24 +712,24 @@ void PhysicsWorld::removeBody(PhysicsBody* body) body->_joints.clear(); removeBodyOrDelay(body); - _bodies->removeObject(body); + _bodies.removeObject(body); body->_world = nullptr; } void PhysicsWorld::removeBodyOrDelay(PhysicsBody* body) { - if (_delayAddBodies->getIndexOfObject(body) != CC_INVALID_INDEX) + if (_delayAddBodies.getIndex(body) != CC_INVALID_INDEX) { - _delayAddBodies->removeObject(body); + _delayAddBodies.removeObject(body); return; } if (_info->isLocked()) { - if (_delayRemoveBodies->getIndexOfObject(body) == CC_INVALID_INDEX) + if (_delayRemoveBodies.getIndex(body) == CC_INVALID_INDEX) { - _delayRemoveBodies->addObject(body); + _delayRemoveBodies.pushBack(body); _delayDirty = true; } }else diff --git a/cocos/physics/CCPhysicsWorld.h b/cocos/physics/CCPhysicsWorld.h index 05999d990d..dfd85e5744 100644 --- a/cocos/physics/CCPhysicsWorld.h +++ b/cocos/physics/CCPhysicsWorld.h @@ -28,12 +28,12 @@ #include "ccConfig.h" #ifdef CC_USE_PHYSICS -#include -#include - +#include "CCVector.h" #include "CCObject.h" #include "CCGeometry.h" +#include + NS_CC_BEGIN class PhysicsBody; @@ -41,7 +41,6 @@ class PhysicsJoint; class PhysicsWorldInfo; class PhysicsShape; class PhysicsContact; -class Array; typedef Point Vect; @@ -104,9 +103,9 @@ public: void rayCast(PhysicsRayCastCallbackFunc func, const Point& point1, const Point& point2, void* data); void queryRect(PhysicsRectQueryCallbackFunc func, const Rect& rect, void* data); void queryPoint(PhysicsPointQueryCallbackFunc func, const Point& point, void* data); - Array* getShapes(const Point& point) const; + Vector getShapes(const Point& point) const; PhysicsShape* getShape(const Point& point) const; - Array* getAllBodies() const; + const Vector& getAllBodies() const; PhysicsBody* getBody(int tag) const; /** Register a listener to receive contact callbacks*/ @@ -156,7 +155,7 @@ protected: float _speed; PhysicsWorldInfo* _info; - Array* _bodies; + Vector _bodies; std::list _joints; Scene* _scene; @@ -165,8 +164,8 @@ protected: int _debugDrawMask; - Array* _delayAddBodies; - Array* _delayRemoveBodies; + Vector _delayAddBodies; + Vector _delayRemoveBodies; std::vector _delayAddJoints; std::vector _delayRemoveJoints; From a12a1015488f02c8f5852bae01adc916260dc379 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:17:47 +0800 Subject: [PATCH 04/27] issue #2790: Removes CCSorting.h/.cpp, uses Vector for storing used and freed cells. --- extensions/GUI/CCScrollView/CCSorting.cpp | 170 ------------------ extensions/GUI/CCScrollView/CCSorting.h | 114 ------------ extensions/GUI/CCScrollView/CCTableView.cpp | 164 +++++++++-------- extensions/GUI/CCScrollView/CCTableView.h | 28 +-- extensions/GUI/CCScrollView/CCTableViewCell.h | 6 +- 5 files changed, 105 insertions(+), 377 deletions(-) delete mode 100644 extensions/GUI/CCScrollView/CCSorting.cpp delete mode 100644 extensions/GUI/CCScrollView/CCSorting.h diff --git a/extensions/GUI/CCScrollView/CCSorting.cpp b/extensions/GUI/CCScrollView/CCSorting.cpp deleted file mode 100644 index 6f42dbd175..0000000000 --- a/extensions/GUI/CCScrollView/CCSorting.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/**************************************************************************** - Copyright (c) 2012 cocos2d-x.org - Copyright (c) 2010 Sangwoo Im - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCSorting.h" -#include "ccCArray.h" - - -NS_CC_EXT_BEGIN - -class SortedObject : public Object, public SortableObject -{ -public: - SortedObject() : objectID(0) {} - virtual void setObjectID(long id) { this->objectID = id; } - virtual long getObjectID() { return objectID; } -private: - long objectID; -}; - -#if 0 -static int _compareObject(const void * val1, const void * val2) -{ - SortableObject* operand1; - SortableObject* operand2; - - operand1 = (SortableObject*)val1; - operand2 = (SortableObject*)val2; - - if (operand1->getObjectID() > operand2->getObjectID()) - { - return 1; - } - else if (operand1->getObjectID() < operand2->getObjectID()) { - return -1; - } - return 0; -} -#endif - - -void ArrayForObjectSorting::insertSortedObject(SortableObject* object) -{ - Object* pObj = dynamic_cast(object); - CCASSERT(pObj, "Invalid parameter."); - long idx = this->indexOfSortedObject(object); - - this->insertObject(pObj, idx); -} - -void ArrayForObjectSorting::removeSortedObject(SortableObject* object) -{ - if (this->count() == 0) { - return; - } - - SortableObject* foundObj = nullptr; - long idx = this->indexOfSortedObject(object); - - if (idx < this->count() && idx != CC_INVALID_INDEX) { - foundObj = dynamic_cast(this->getObjectAtIndex(idx)); - - if(foundObj->getObjectID() == object->getObjectID()) { - this->removeObjectAtIndex(idx); - } - } -} - -void ArrayForObjectSorting::setObjectID_ofSortedObject(unsigned int tag, SortableObject* object) -{ - SortableObject* foundObj = nullptr; - - long idx = this->indexOfSortedObject(object); - - if (idx < this->count() && idx != CC_INVALID_INDEX) - { - foundObj = dynamic_cast(this->getObjectAtIndex(idx)); - Object* pObj = dynamic_cast(foundObj); - pObj->retain(); - - if(foundObj->getObjectID() == object->getObjectID()) { - this->removeObjectAtIndex(idx); - foundObj->setObjectID(tag); - this->insertSortedObject(foundObj); - pObj->release(); - } else { - pObj->release(); - } - } -} - -SortableObject* ArrayForObjectSorting::objectWithObjectID(long tag) -{ - if (this->count() == 0) { - return NULL; - } - - SortableObject* foundObj = new SortedObject(); - foundObj->setObjectID(tag); - - long idx = this->indexOfSortedObject(foundObj); - - ((SortedObject*)foundObj)->release(); - foundObj = NULL; - - if (idx < this->count() && idx != CC_INVALID_INDEX) - { - foundObj = dynamic_cast(this->getObjectAtIndex(idx)); - if (foundObj->getObjectID() != tag) { - foundObj = NULL; - } - } - - return foundObj; -} - -long ArrayForObjectSorting::indexOfSortedObject(SortableObject* object) -{ - long idx = 0; - if (object) - { - // Object* pObj = (Object*)bsearch((Object*)&object, data->arr, data->num, sizeof(Object*), _compareObject); - // FIXME: need to use binary search to improve performance - Object* obj = NULL; - long prevObjectID = 0; - long ofSortObjectID = object->getObjectID(); - - CCARRAY_FOREACH(this, obj) - { - SortableObject* sortableObj = dynamic_cast(obj); - long curObjectID = sortableObj->getObjectID(); - if ( (ofSortObjectID == curObjectID) - || (ofSortObjectID >= prevObjectID && ofSortObjectID < curObjectID)) - { - break; - } - - prevObjectID = curObjectID; - idx++; - } - } - else - { - idx = CC_INVALID_INDEX; - } - return idx; -} - -NS_CC_EXT_END diff --git a/extensions/GUI/CCScrollView/CCSorting.h b/extensions/GUI/CCScrollView/CCSorting.h deleted file mode 100644 index cafcb62ece..0000000000 --- a/extensions/GUI/CCScrollView/CCSorting.h +++ /dev/null @@ -1,114 +0,0 @@ -/**************************************************************************** - Copyright (c) 2012 cocos2d-x.org - Copyright (c) 2010 Sangwoo Im - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef __CCSORTING_H__ -#define __CCSORTING_H__ - -#include "CCArray.h" -#include "extensions/ExtensionMacros.h" - -NS_CC_EXT_BEGIN - -class SortableObject -{ -public: - /** - * @js NA - * @lua NA - */ - virtual ~SortableObject() {} - virtual void setObjectID(long objectID) = 0; - virtual long getObjectID() = 0; -}; - -class ArrayForObjectSorting : public Array -{ -public: - ArrayForObjectSorting() : Array() {} - /*! - * Inserts a given object into array. - * - * Inserts a given object into array with key and value that are used in - * sorting. "value" must respond to message, compare:, which returns - * (NSComparisonResult). If it does not respond to the message, it is appended. - * If the compare message does not result NSComparisonResult, sorting behavior - * is not defined. It ignores duplicate entries and inserts next to it. - * - * @param object The object to be inserted. - */ - void insertSortedObject(SortableObject* object); - - /*! - * Removes an object in array. - * - * Removes an object with given key and value. If no object is found in array - * with the key and value, no action is taken. - * - * @param object The object to be removed. - */ - void removeSortedObject(SortableObject* object); - /*! - * Sets a new value of the key for the given object. - * - * In case where sorting value must be changed, this message must be sent to - * keep consistency of being sorted. If it is changed externally, it must be - * sorted completely again. - * - * @param tag The value to be set to. - * @param object The object which has the value. - */ - void setObjectID_ofSortedObject(unsigned int tag, SortableObject* object); - - SortableObject* objectWithObjectID(long tag); - /*! - * Returns an object with given key and value. - * - * Returns an object with given key and value. If no object is found, - * it returns nil. - * - * @param tag The value to locate object - * @return object found or nil. - */ - SortableObject* getObjectWithObjectID(unsigned int tag); - - /*! - * Returns an index of the object with given key and value. - * - * Returns the index of an object with given key and value. - * If no object is found, it returns an index at which the given object value - * would have been located. If object must be located at the end of array, - * it returns the length of the array, which is out of bound. - * - * @param obj The object - * @return index of the object - */ - long indexOfSortedObject(SortableObject* obj); - -}; - -NS_CC_EXT_END - -#endif /* __CCSORTING_H__ */ - diff --git a/extensions/GUI/CCScrollView/CCTableView.cpp b/extensions/GUI/CCScrollView/CCTableView.cpp index 6bf8bcd67f..16d53aa68a 100644 --- a/extensions/GUI/CCScrollView/CCTableView.cpp +++ b/extensions/GUI/CCScrollView/CCTableView.cpp @@ -26,12 +26,10 @@ #include "cocos2d.h" #include "CCTableView.h" #include "CCTableViewCell.h" -#include "CCMenu.h" -#include "CCSorting.h" -#include "CCLayer.h" NS_CC_EXT_BEGIN + TableView* TableView::create(TableViewDataSource* dataSource, Size size) { return TableView::create(dataSource, size, NULL); @@ -53,10 +51,6 @@ bool TableView::initWithViewSize(Size size, Node* container/* = NULL*/) { if (ScrollView::initWithViewSize(size,container)) { - _cellsUsed = new ArrayForObjectSorting(); - _cellsUsed->init(); - _cellsFreed = new ArrayForObjectSorting(); - _cellsFreed->init(); _indices = new std::set(); _vordering = VerticalFillOrder::BOTTOM_UP; this->setDirection(Direction::VERTICAL); @@ -70,11 +64,10 @@ bool TableView::initWithViewSize(Size size, Node* container/* = NULL*/) TableView::TableView() : _touchedCell(nullptr) , _indices(nullptr) -, _cellsUsed(nullptr) -, _cellsFreed(nullptr) , _dataSource(nullptr) , _tableViewDelegate(nullptr) , _oldDirection(Direction::NONE) +, _isUsedCellsDirty(false) { } @@ -82,15 +75,15 @@ TableView::TableView() TableView::~TableView() { CC_SAFE_DELETE(_indices); - CC_SAFE_RELEASE(_cellsUsed); - CC_SAFE_RELEASE(_cellsFreed); } void TableView::setVerticalFillOrder(VerticalFillOrder fillOrder) { - if (_vordering != fillOrder) { + if (_vordering != fillOrder) + { _vordering = fillOrder; - if (_cellsUsed->count() > 0) { + if (!_cellsUsed.empty()) + { this->reloadData(); } } @@ -104,28 +97,24 @@ TableView::VerticalFillOrder TableView::getVerticalFillOrder() void TableView::reloadData() { _oldDirection = Direction::NONE; - Object* pObj = NULL; - CCARRAY_FOREACH(_cellsUsed, pObj) - { - TableViewCell* cell = static_cast(pObj); + _cellsUsed.forEach([this](TableViewCell* cell){ if(_tableViewDelegate != NULL) { _tableViewDelegate->tableCellWillRecycle(this, cell); } - _cellsFreed->addObject(cell); + _cellsFreed.pushBack(cell); + cell->reset(); if (cell->getParent() == this->getContainer()) { this->getContainer()->removeChild(cell, true); } - } + }); _indices->clear(); - _cellsUsed->release(); - _cellsUsed = new ArrayForObjectSorting(); - _cellsUsed->init(); - + _cellsUsed.clear(); + this->_updateCellPositions(); this->_updateContentSize(); if (_dataSource->numberOfCellsInTableView(this) > 0) @@ -136,14 +125,18 @@ void TableView::reloadData() TableViewCell *TableView::cellAtIndex(long idx) { - TableViewCell *found = NULL; - if (_indices->find(idx) != _indices->end()) { - found = (TableViewCell *)_cellsUsed->objectWithObjectID(idx); + for (const auto& cell : _cellsUsed) + { + if (cell->getIdx() == idx) + { + return cell; + } + } } - return found; + return nullptr; } void TableView::updateCellAtIndex(long idx) @@ -181,22 +174,20 @@ void TableView::insertCellAtIndex(long idx) return; } - TableViewCell* cell = NULL; long newIdx = 0; - cell = static_cast(_cellsUsed->objectWithObjectID(idx)); + auto cell = cellAtIndex(idx); if (cell) { - newIdx = _cellsUsed->indexOfSortedObject(cell); - for (long i = newIdx; i<_cellsUsed->count(); i++) + newIdx = _cellsUsed.getIndex(cell); + // Move all cells behind the inserted position + for (long i = newIdx; i < _cellsUsed.size(); i++) { - cell = static_cast(_cellsUsed->getObjectAtIndex(i)); + cell = _cellsUsed.at(i); this->_setIndexForCell(cell->getIdx()+1, cell); } } - // [_indices shiftIndexesStartingAtIndex:idx by:1]; - //insert a new cell cell = _dataSource->tableCellAtIndex(this, idx); this->_setIndexForCell(idx, cell); @@ -227,17 +218,17 @@ void TableView::removeCellAtIndex(long idx) return; } - newIdx = _cellsUsed->indexOfSortedObject(cell); + newIdx = _cellsUsed.getIndex(cell); //remove first this->_moveCellOutOfSight(cell); _indices->erase(idx); this->_updateCellPositions(); -// [_indices shiftIndexesStartingAtIndex:idx+1 by:-1]; - for (unsigned int i=_cellsUsed->count()-1; i > newIdx; i--) + + for (int i = _cellsUsed.size()-1; i > newIdx; i--) { - cell = (TableViewCell*)_cellsUsed->getObjectAtIndex(i); + cell = _cellsUsed.at(i); this->_setIndexForCell(cell->getIdx()-1, cell); } } @@ -246,12 +237,12 @@ TableViewCell *TableView::dequeueCell() { TableViewCell *cell; - if (_cellsFreed->count() == 0) { + if (_cellsFreed.empty()) { cell = NULL; } else { - cell = (TableViewCell*)_cellsFreed->getObjectAtIndex(0); + cell = _cellsFreed.at(0); cell->retain(); - _cellsFreed->removeObjectAtIndex(0); + _cellsFreed.remove(0); cell->autorelease(); } return cell; @@ -263,9 +254,9 @@ void TableView::_addCellIfNecessary(TableViewCell * cell) { this->getContainer()->addChild(cell); } - _cellsUsed->insertSortedObject(cell); + _cellsUsed.pushBack(cell); _indices->insert(cell->getIdx()); - // [_indices addIndex:cell.idx]; + _isUsedCellsDirty = true; } void TableView::_updateContentSize() @@ -405,12 +396,15 @@ void TableView::_moveCellOutOfSight(TableViewCell *cell) _tableViewDelegate->tableCellWillRecycle(this, cell); } - _cellsFreed->addObject(cell); - _cellsUsed->removeSortedObject(cell); + _cellsFreed.pushBack(cell); + _cellsUsed.removeObject(cell); + _isUsedCellsDirty = true; + _indices->erase(cell->getIdx()); - // [_indices removeIndex:cell.idx]; cell->reset(); - if (cell->getParent() == this->getContainer()) { + + if (cell->getParent() == this->getContainer()) + { this->getContainer()->removeChild(cell, true);; } } @@ -422,8 +416,9 @@ void TableView::_setIndexForCell(long index, TableViewCell *cell) cell->setIdx(index); } -void TableView::_updateCellPositions() { - int cellsCount = _dataSource->numberOfCellsInTableView(this); +void TableView::_updateCellPositions() +{ + long cellsCount = _dataSource->numberOfCellsInTableView(this); _vCellsPositions.resize(cellsCount + 1, 0.0); if (cellsCount > 0) @@ -451,19 +446,27 @@ void TableView::_updateCellPositions() { void TableView::scrollViewDidScroll(ScrollView* view) { - unsigned int uCountOfItems = _dataSource->numberOfCellsInTableView(this); - if (0 == uCountOfItems) + long countOfItems = _dataSource->numberOfCellsInTableView(this); + if (0 == countOfItems) { return; } + if (_isUsedCellsDirty) + { + _isUsedCellsDirty = false; + _cellsUsed.sort([](TableViewCell *a, TableViewCell *b) -> bool{ + return a->getIdx() < b->getIdx(); + }); + } + if(_tableViewDelegate != NULL) { _tableViewDelegate->scrollViewDidScroll(this); } long startIdx = 0, endIdx = 0, idx = 0, maxIdx = 0; Point offset = this->getContentOffset() * -1; - maxIdx = MAX(uCountOfItems-1, 0); + maxIdx = MAX(countOfItems-1, 0); if (_vordering == VerticalFillOrder::TOP_DOWN) { @@ -472,7 +475,7 @@ void TableView::scrollViewDidScroll(ScrollView* view) startIdx = this->_indexFromOffset(offset); if (startIdx == CC_INVALID_INDEX) { - startIdx = uCountOfItems - 1; + startIdx = countOfItems - 1; } if (_vordering == VerticalFillOrder::TOP_DOWN) @@ -488,7 +491,7 @@ void TableView::scrollViewDidScroll(ScrollView* view) endIdx = this->_indexFromOffset(offset); if (endIdx == CC_INVALID_INDEX) { - endIdx = uCountOfItems - 1; + endIdx = countOfItems - 1; } #if 0 // For Testing. @@ -511,17 +514,17 @@ void TableView::scrollViewDidScroll(ScrollView* view) log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); #endif - if (_cellsUsed->count() > 0) + if (!_cellsUsed.empty()) { - TableViewCell* cell = (TableViewCell*)_cellsUsed->getObjectAtIndex(0); - + auto cell = _cellsUsed.at(0); idx = cell->getIdx(); - while(idx _moveCellOutOfSight(cell); - if (_cellsUsed->count() > 0) + if (!_cellsUsed.empty()) { - cell = (TableViewCell*)_cellsUsed->getObjectAtIndex(0); + cell = _cellsUsed.at(0); idx = cell->getIdx(); } else @@ -530,19 +533,18 @@ void TableView::scrollViewDidScroll(ScrollView* view) } } } - if (_cellsUsed->count() > 0) + if (!_cellsUsed.empty()) { - TableViewCell *cell = (TableViewCell*)_cellsUsed->getLastObject(); + auto cell = _cellsUsed.back(); idx = cell->getIdx(); while(idx <= maxIdx && idx > endIdx) { this->_moveCellOutOfSight(cell); - if (_cellsUsed->count() > 0) + if (!_cellsUsed.empty()) { - cell = (TableViewCell*)_cellsUsed->getLastObject(); + cell = _cellsUsed.back(); idx = cell->getIdx(); - } else { @@ -553,7 +555,6 @@ void TableView::scrollViewDidScroll(ScrollView* view) for (long i = startIdx; i <= endIdx; i++) { - //if ([_indices containsIndex:i]) if (_indices->find(i) != _indices->end()) { continue; @@ -586,15 +587,17 @@ void TableView::onTouchEnded(Touch *pTouch, Event *pEvent) bool TableView::onTouchBegan(Touch *pTouch, Event *pEvent) { - if (!this->isVisible()) { + if (!this->isVisible()) + { return false; } bool touchResult = ScrollView::onTouchBegan(pTouch, pEvent); - if(_touches.size() == 1) { - unsigned int index; - Point point; + if(_touches.size() == 1) + { + long index; + Point point; point = this->getContainer()->convertTouchToNodeSpace(pTouch); @@ -608,12 +611,15 @@ bool TableView::onTouchBegan(Touch *pTouch, Event *pEvent) _touchedCell = this->cellAtIndex(index); } - if (_touchedCell && _tableViewDelegate != NULL) { + if (_touchedCell && _tableViewDelegate != NULL) + { _tableViewDelegate->tableCellHighlight(this, _touchedCell); } } - else if(_touchedCell) { - if(_tableViewDelegate != NULL) { + else if (_touchedCell) + { + if(_tableViewDelegate != NULL) + { _tableViewDelegate->tableCellUnhighlight(this, _touchedCell); } @@ -627,8 +633,10 @@ void TableView::onTouchMoved(Touch *pTouch, Event *pEvent) { ScrollView::onTouchMoved(pTouch, pEvent); - if (_touchedCell && isTouchMoved()) { - if(_tableViewDelegate != NULL) { + if (_touchedCell && isTouchMoved()) + { + if(_tableViewDelegate != NULL) + { _tableViewDelegate->tableCellUnhighlight(this, _touchedCell); } @@ -640,8 +648,10 @@ void TableView::onTouchCancelled(Touch *pTouch, Event *pEvent) { ScrollView::onTouchCancelled(pTouch, pEvent); - if (_touchedCell) { - if(_tableViewDelegate != NULL) { + if (_touchedCell) + { + if(_tableViewDelegate != NULL) + { _tableViewDelegate->tableCellUnhighlight(this, _touchedCell); } diff --git a/extensions/GUI/CCScrollView/CCTableView.h b/extensions/GUI/CCScrollView/CCTableView.h index 34c7f05939..4201a2c1a4 100644 --- a/extensions/GUI/CCScrollView/CCTableView.h +++ b/extensions/GUI/CCScrollView/CCTableView.h @@ -35,7 +35,6 @@ NS_CC_EXT_BEGIN class TableView; -class ArrayForObjectSorting; /** * Sole purpose of this delegate is to single touch event in this version. @@ -270,6 +269,17 @@ public: virtual void onTouchCancelled(Touch *pTouch, Event *pEvent) override; protected: + long __indexFromOffset(Point offset); + long _indexFromOffset(Point offset); + Point __offsetFromIndex(long index); + Point _offsetFromIndex(long index); + + void _moveCellOutOfSight(TableViewCell *cell); + void _setIndexForCell(long index, TableViewCell *cell); + void _addCellIfNecessary(TableViewCell * cell); + + void _updateCellPositions(); + TableViewCell *_touchedCell; /** @@ -290,11 +300,11 @@ protected: /** * cells that are currently in the table */ - ArrayForObjectSorting* _cellsUsed; + Vector _cellsUsed; /** * free list of cells */ - ArrayForObjectSorting* _cellsFreed; + Vector _cellsFreed; /** * weak link to the data source object */ @@ -304,18 +314,10 @@ protected: */ TableViewDelegate* _tableViewDelegate; - Direction _oldDirection; + Direction _oldDirection; - long __indexFromOffset(Point offset); - long _indexFromOffset(Point offset); - Point __offsetFromIndex(long index); - Point _offsetFromIndex(long index); + bool _isUsedCellsDirty; - void _moveCellOutOfSight(TableViewCell *cell); - void _setIndexForCell(long index, TableViewCell *cell); - void _addCellIfNecessary(TableViewCell * cell); - - void _updateCellPositions(); public: void _updateContentSize(); diff --git a/extensions/GUI/CCScrollView/CCTableViewCell.h b/extensions/GUI/CCScrollView/CCTableViewCell.h index 95fab98a29..55e1079196 100644 --- a/extensions/GUI/CCScrollView/CCTableViewCell.h +++ b/extensions/GUI/CCScrollView/CCTableViewCell.h @@ -26,15 +26,15 @@ #ifndef __CCTABLEVIEWCELL_H__ #define __CCTABLEVIEWCELL_H__ -#include "CCNode.h" -#include "CCSorting.h" +#include "cocos2d.h" +#include "ExtensionMacros.h" NS_CC_EXT_BEGIN /** * Abstract class for SWTableView cell node */ -class TableViewCell: public Node, public SortableObject +class TableViewCell: public Node { public: TableViewCell() {} From 6f13a111ae6e3d96b4294a6f0f6af97a1c47b0db Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:18:42 +0800 Subject: [PATCH 05/27] issue #2790: Adds Vector::sort method, adds Vector::removeObject(object, toRemoved). --- cocos/base/CCVector.h | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/cocos/base/CCVector.h b/cocos/base/CCVector.h index 2314e325ba..3ea40ccc8a 100644 --- a/cocos/base/CCVector.h +++ b/cocos/base/CCVector.h @@ -230,13 +230,14 @@ public: } /** Remove a certain object */ - void removeObject(T object) + void removeObject(T object, bool toRelease = true) { CCASSERT(object != nullptr, "The object should not be nullptr"); auto iter = std::find(_data.begin(), _data.end(), object); if (iter != _data.end()) _data.erase(iter); - object->release(); + if (toRelease) + object->release(); } /** Removes an element with a certain index */ @@ -341,6 +342,16 @@ public: }); } + void sort(const std::function& callback) + { + if (empty()) + return; + + std::sort(_data.begin(), _data.end(), [&callback](T a, T b) -> bool{ + return callback(a, b); + }); + } + // ------------------------------------------ // Iterators // ------------------------------------------ From d8061477c129ec89db59ba2705eccd241b252806 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:21:01 +0800 Subject: [PATCH 06/27] issue #2790: Removes CCSort.h/.cpp from projects. --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- extensions/Android.mk | 1 - extensions/CMakeLists.txt | 1 - extensions/proj.win32/libExtensions.vcxproj | 2 -- extensions/proj.win32/libExtensions.vcxproj.filters | 6 ------ 5 files changed, 1 insertion(+), 11 deletions(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index 8646685fa1..8f1be0f32e 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -c3b97117ff38c9347b34f01a67fd7206af29194d \ No newline at end of file +42f742346aec806886a8fd399aa42f689cafa71c \ No newline at end of file diff --git a/extensions/Android.mk b/extensions/Android.mk index a5f4fd051f..a06c09bc47 100644 --- a/extensions/Android.mk +++ b/extensions/Android.mk @@ -25,7 +25,6 @@ GUI/CCEditBox/CCEditBoxImplNone.cpp \ GUI/CCEditBox/CCEditBoxImplTizen.cpp \ GUI/CCEditBox/CCEditBoxImplWin.cpp \ GUI/CCScrollView/CCScrollView.cpp \ -GUI/CCScrollView/CCSorting.cpp \ GUI/CCScrollView/CCTableView.cpp \ GUI/CCScrollView/CCTableViewCell.cpp \ physics-nodes/CCPhysicsDebugNode.cpp \ diff --git a/extensions/CMakeLists.txt b/extensions/CMakeLists.txt index 176cd831ce..f8083e1220 100644 --- a/extensions/CMakeLists.txt +++ b/extensions/CMakeLists.txt @@ -18,7 +18,6 @@ set(EXTENSIONS_SRC GUI/CCEditBox/CCEditBoxImplTizen.cpp GUI/CCEditBox/CCEditBoxImplWin.cpp GUI/CCScrollView/CCScrollView.cpp - GUI/CCScrollView/CCSorting.cpp GUI/CCScrollView/CCTableView.cpp GUI/CCScrollView/CCTableViewCell.cpp physics-nodes/CCPhysicsDebugNode.cpp diff --git a/extensions/proj.win32/libExtensions.vcxproj b/extensions/proj.win32/libExtensions.vcxproj index 7a3615643f..1e00952529 100644 --- a/extensions/proj.win32/libExtensions.vcxproj +++ b/extensions/proj.win32/libExtensions.vcxproj @@ -110,7 +110,6 @@ - @@ -138,7 +137,6 @@ - diff --git a/extensions/proj.win32/libExtensions.vcxproj.filters b/extensions/proj.win32/libExtensions.vcxproj.filters index d43ac6197c..fe37d0def2 100644 --- a/extensions/proj.win32/libExtensions.vcxproj.filters +++ b/extensions/proj.win32/libExtensions.vcxproj.filters @@ -24,9 +24,6 @@ GUI\CCScrollView - - GUI\CCScrollView - GUI\CCScrollView @@ -94,9 +91,6 @@ - - GUI\CCScrollView - GUI\CCScrollView From 0091ca2b6f5bc3acbd30305d189c797e4ecf2d4c Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:22:03 +0800 Subject: [PATCH 07/27] issue #2790: Uses non-const ValueMap for simplifying codes in CCAnimationCache.cpp. --- cocos/2d/CCAnimationCache.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/cocos/2d/CCAnimationCache.cpp b/cocos/2d/CCAnimationCache.cpp index a1d0ddd1ec..2c528f0320 100644 --- a/cocos/2d/CCAnimationCache.cpp +++ b/cocos/2d/CCAnimationCache.cpp @@ -141,12 +141,12 @@ void AnimationCache::parseVersion2(const ValueMap& animations) for (auto iter = animations.cbegin(); iter != animations.cend(); ++iter) { std::string name = iter->first; - const ValueMap& animationDict = iter->second.asValueMap(); + ValueMap& animationDict = const_cast(iter->second.asValueMap()); - const Value& loops = animationDict.at("loops"); - bool restoreOriginalFrame = animationDict.at("restoreOriginalFrame").asBool(); + const Value& loops = animationDict["loops"]; + bool restoreOriginalFrame = animationDict["restoreOriginalFrame"].asBool(); - const ValueVector& frameArray = animationDict.at("frames").asValueVector(); + ValueVector& frameArray = animationDict["frames"].asValueVector(); if ( frameArray.empty() ) { @@ -159,8 +159,8 @@ void AnimationCache::parseVersion2(const ValueMap& animations) for (auto& obj : frameArray) { - const ValueMap& entry = obj.asValueMap(); - std::string spriteFrameName = entry.at("spriteframe").asString(); + ValueMap& entry = obj.asValueMap(); + std::string spriteFrameName = entry["spriteframe"].asString(); SpriteFrame *spriteFrame = frameCache->getSpriteFrameByName(spriteFrameName); if( ! spriteFrame ) { @@ -169,15 +169,15 @@ void AnimationCache::parseVersion2(const ValueMap& animations) continue; } - float delayUnits = entry.at("delayUnits").asFloat(); - const Value& userInfo = entry.at("notification"); + float delayUnits = entry["delayUnits"].asFloat(); + Value& userInfo = entry["notification"]; AnimationFrame *animFrame = AnimationFrame::create(spriteFrame, delayUnits, userInfo.asValueMap()); array.pushBack(animFrame); } - float delayPerUnit = animationDict.at("delayPerUnit").asFloat(); + float delayPerUnit = animationDict["delayPerUnit"].asFloat(); Animation *animation = Animation::create(array, delayPerUnit, loops.getType() != Value::Type::NONE ? loops.asInt() : 1); animation->setRestoreOriginalFrame(restoreOriginalFrame); From b0cb7c230a8347ab94e2dc424ff420af6e6fae22 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:22:51 +0800 Subject: [PATCH 08/27] #issue #2790: Uses Vector for scenesStack in CCDirector. --- cocos/2d/CCDirector.cpp | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index bce116b491..cd029d737f 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -110,8 +110,7 @@ bool Director::init(void) _notificationNode = nullptr; - _scenesStack = new Array(); - _scenesStack->initWithCapacity(15); + _scenesStack.reserve(15); // projection delegate if "Custom" projection is used _projectionDelegate = nullptr; @@ -164,7 +163,6 @@ Director::~Director(void) CC_SAFE_RELEASE(_runningScene); CC_SAFE_RELEASE(_notificationNode); - CC_SAFE_RELEASE(_scenesStack); CC_SAFE_RELEASE(_scheduler); CC_SAFE_RELEASE(_actionManager); CC_SAFE_RELEASE(_eventDispatcher); @@ -597,10 +595,10 @@ void Director::replaceScene(Scene *scene) CCASSERT(_runningScene, "Use runWithScene: instead to start the director"); CCASSERT(scene != nullptr, "the scene should not be null"); - unsigned int index = _scenesStack->count(); + int index = _scenesStack.size(); _sendCleanupToScene = true; - _scenesStack->replaceObjectAtIndex(index - 1, scene); + _scenesStack.replace(index - 1, scene); _nextScene = scene; } @@ -611,7 +609,7 @@ void Director::pushScene(Scene *scene) _sendCleanupToScene = false; - _scenesStack->addObject(scene); + _scenesStack.pushBack(scene); _nextScene = scene; } @@ -619,8 +617,8 @@ void Director::popScene(void) { CCASSERT(_runningScene != nullptr, "running scene should not null"); - _scenesStack->removeLastObject(); - unsigned int c = _scenesStack->count(); + _scenesStack.popBack(); + int c = _scenesStack.size(); if (c == 0) { @@ -629,7 +627,7 @@ void Director::popScene(void) else { _sendCleanupToScene = true; - _nextScene = (Scene*)_scenesStack->getObjectAtIndex(c - 1); + _nextScene = _scenesStack.at(c - 1); } } @@ -641,7 +639,7 @@ void Director::popToRootScene(void) void Director::popToSceneStackLevel(int level) { CCASSERT(_runningScene != nullptr, "A running Scene is needed"); - int c = static_cast(_scenesStack->count()); + int c = _scenesStack.size(); // level 0? -> end if (level == 0) @@ -657,7 +655,7 @@ void Director::popToSceneStackLevel(int level) // pop stack until reaching desired level while (c > level) { - Scene *current = (Scene*)_scenesStack->getLastObject(); + auto current = _scenesStack.back(); if (current->isRunning()) { @@ -666,11 +664,11 @@ void Director::popToSceneStackLevel(int level) } current->cleanup(); - _scenesStack->removeLastObject(); + _scenesStack.popBack(); --c; } - _nextScene = (Scene*)_scenesStack->getLastObject(); + _nextScene = _scenesStack.back(); _sendCleanupToScene = false; } @@ -701,7 +699,7 @@ void Director::purgeDirector() // remove all objects, but don't release it. // runWithScene might be executed after 'end'. - _scenesStack->removeAllObjects(); + _scenesStack.clear(); stopAnimation(); From cd7281338945725c9edba968b7c9508b16733d10 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:23:29 +0800 Subject: [PATCH 09/27] issue #2790: Autorelease pool is using Vector now. --- cocos/base/CCAutoreleasePool.cpp | 64 ++++++++++++-------------------- cocos/base/CCAutoreleasePool.h | 6 +-- 2 files changed, 27 insertions(+), 43 deletions(-) diff --git a/cocos/base/CCAutoreleasePool.cpp b/cocos/base/CCAutoreleasePool.cpp index 89a3528f73..e55c8c9b97 100644 --- a/cocos/base/CCAutoreleasePool.cpp +++ b/cocos/base/CCAutoreleasePool.cpp @@ -30,19 +30,17 @@ static PoolManager* s_pPoolManager = NULL; AutoreleasePool::AutoreleasePool() { - _managedObjectArray = new Array(); - _managedObjectArray->initWithCapacity(150); + _managedObjectArray.reserve(150); } AutoreleasePool::~AutoreleasePool() { CCLOGINFO("deallocing AutoreleasePool: %p", this); - CC_SAFE_DELETE(_managedObjectArray); } void AutoreleasePool::addObject(Object* object) { - _managedObjectArray->addObject(object); + _managedObjectArray.pushBack(object); CCASSERT(object->_reference > 1, "reference count should be greater than 1"); ++(object->_autoReleaseCount); @@ -53,34 +51,29 @@ void AutoreleasePool::removeObject(Object* object) { for (unsigned int i = 0; i < object->_autoReleaseCount; ++i) { - _managedObjectArray->removeObject(object, false); + _managedObjectArray.removeObject(object, false); } } void AutoreleasePool::clear() { - if(_managedObjectArray->count() > 0) + if (!_managedObjectArray.empty()) { //CCAutoreleasePool* pReleasePool; #ifdef _DEBUG - int nIndex = _managedObjectArray->count() - 1; + int nIndex = _managedObjectArray.size() - 1; #endif - Object* pObj = NULL; - CCARRAY_FOREACH_REVERSE(_managedObjectArray, pObj) - { - if(!pObj) - break; - - --(pObj->_autoReleaseCount); + _managedObjectArray.forEachReverse([](Object* obj){ + --(obj->_autoReleaseCount); //(*it)->release(); //delete (*it); #ifdef _DEBUG nIndex--; #endif - } + }); - _managedObjectArray->removeAllObjects(); + _managedObjectArray.clear(); } } @@ -107,8 +100,7 @@ void PoolManager::purgePoolManager() PoolManager::PoolManager() { - _releasePoolStack = new Array(); - _releasePoolStack->initWithCapacity(150); + _releasePoolStack.reserve(150); _curReleasePool = 0; } @@ -119,35 +111,27 @@ PoolManager::~PoolManager() // we only release the last autorelease pool here _curReleasePool = 0; - _releasePoolStack->removeObjectAtIndex(0); - - CC_SAFE_DELETE(_releasePoolStack); + _releasePoolStack.remove(0); } void PoolManager::finalize() { - if(_releasePoolStack->count() > 0) + if (!_releasePoolStack.empty()) { - //CCAutoreleasePool* pReleasePool; - Object* pObj = NULL; - CCARRAY_FOREACH(_releasePoolStack, pObj) - { - if(!pObj) - break; - AutoreleasePool* pPool = static_cast(pObj); - pPool->clear(); - } + _releasePoolStack.forEach([](AutoreleasePool* pool){ + pool->clear(); + }); } } void PoolManager::push() { - AutoreleasePool* pPool = new AutoreleasePool(); //ref = 1 - _curReleasePool = pPool; + AutoreleasePool* pool = new AutoreleasePool(); //ref = 1 + _curReleasePool = pool; - _releasePoolStack->addObject(pPool); //ref = 2 + _releasePoolStack.pushBack(pool); //ref = 2 - pPool->release(); //ref = 1 + pool->release(); //ref = 1 } void PoolManager::pop() @@ -157,20 +141,20 @@ void PoolManager::pop() return; } - int nCount = _releasePoolStack->count(); + int count = _releasePoolStack.size(); _curReleasePool->clear(); - if (nCount > 1) + if (count > 1) { - _releasePoolStack->removeObjectAtIndex(nCount-1); + _releasePoolStack.remove(count-1); // if(nCount > 1) // { -// _curReleasePool = _releasePoolStack->getObjectAtIndex(nCount - 2); +// _curReleasePool = _releasePoolStack.at(count - 2); // return; // } - _curReleasePool = (AutoreleasePool*)_releasePoolStack->getObjectAtIndex(nCount - 2); + _curReleasePool = _releasePoolStack.at(count - 2); } /*_curReleasePool = NULL;*/ diff --git a/cocos/base/CCAutoreleasePool.h b/cocos/base/CCAutoreleasePool.h index e446ceb402..67930173e2 100644 --- a/cocos/base/CCAutoreleasePool.h +++ b/cocos/base/CCAutoreleasePool.h @@ -25,7 +25,7 @@ THE SOFTWARE. #define __AUTORELEASEPOOL_H__ #include "CCObject.h" -#include "CCArray.h" +#include "CCVector.h" NS_CC_BEGIN @@ -45,7 +45,7 @@ class CC_DLL AutoreleasePool : public Object * be destructed properly by calling Object::release() even if the object * is in the pool. */ - Array *_managedObjectArray; + Vector _managedObjectArray; public: /** * @js NA @@ -93,7 +93,7 @@ public: class CC_DLL PoolManager { - Array *_releasePoolStack; + Vector _releasePoolStack; AutoreleasePool *_curReleasePool; AutoreleasePool *getCurReleasePool(); From d7997cf0cc450621bc61b92e579edecffa446430 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:24:31 +0800 Subject: [PATCH 10/27] issue #2790: Updates MenuItemToggole --- cocos/2d/CCMenuItem.cpp | 20 ++++---------------- cocos/2d/CCMenuItem.h | 23 ++++++++++++----------- 2 files changed, 16 insertions(+), 27 deletions(-) diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index c97cd7a2fa..f4709c5156 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -806,33 +806,21 @@ void MenuItemImage::setDisabledSpriteFrame(SpriteFrame * frame) // // XXX: deprecated -MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandler selector, Array* menuItems) +MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandler selector, const Vector& menuItems) { MenuItemToggle *ret = new MenuItemToggle(); ret->MenuItem::initWithTarget(target, selector); - - for (int z=0; z < menuItems->count(); z++) - { - MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); - ret->_subItems.pushBack(menuItem); - } - + ret->_subItems = menuItems; ret->_selectedIndex = UINT_MAX; ret->setSelectedIndex(0); return ret; } -MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callback, Array* menuItems) +MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callback, const Vector& menuItems) { MenuItemToggle *ret = new MenuItemToggle(); ret->MenuItem::initWithCallback(callback); - - for (int z=0; z < menuItems->count(); z++) - { - MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z); - ret->_subItems.pushBack(menuItem); - } - + ret->_subItems = menuItems; ret->_selectedIndex = UINT_MAX; ret->setSelectedIndex(0); return ret; diff --git a/cocos/2d/CCMenuItem.h b/cocos/2d/CCMenuItem.h index c9184feba6..57ce4dad9e 100644 --- a/cocos/2d/CCMenuItem.h +++ b/cocos/2d/CCMenuItem.h @@ -453,8 +453,19 @@ private: class CC_DLL MenuItemToggle : public MenuItem { public: + /** creates a menu item from a Array with a target selector + * @js NA + * @lua NA + */ + CC_DEPRECATED_ATTRIBUTE static MenuItemToggle * createWithTarget(Object* target, SEL_MenuHandler selector, const Vector& menuItems); + /** creates a menu item from a list of items with a target/selector + * @js NA + * @lua NA + */ + CC_DEPRECATED_ATTRIBUTE static MenuItemToggle* createWithTarget(Object* target, SEL_MenuHandler selector, MenuItem* item, ...)CC_REQUIRES_NULL_TERMINATION; + /** creates a menu item from a Array with a callable object */ - static MenuItemToggle * createWithCallback(const ccMenuCallback& callback, Array* menuItems); + static MenuItemToggle * createWithCallback(const ccMenuCallback& callback, const Vector& menuItems); /** creates a menu item from a list of items with a callable object */ static MenuItemToggle* createWithCallback(const ccMenuCallback& callback, MenuItem* item, ...) CC_REQUIRES_NULL_TERMINATION; /** creates a menu item with no target/selector and no items */ @@ -496,16 +507,6 @@ public: virtual void setEnabled(bool var) override; protected: - /** creates a menu item from a Array with a target selector - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE static MenuItemToggle * createWithTarget(Object* target, SEL_MenuHandler selector, Array* menuItems); - /** creates a menu item from a list of items with a target/selector - * @js NA - * @lua NA - */ - CC_DEPRECATED_ATTRIBUTE static MenuItemToggle* createWithTarget(Object* target, SEL_MenuHandler selector, MenuItem* item, ...)CC_REQUIRES_NULL_TERMINATION; /** * @js ctor */ From 6b0589679b295549f409c40f84e28ec296086e53 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:25:24 +0800 Subject: [PATCH 11/27] issue #2790: Vector instead of CCArray* in CCScheduler --- cocos/2d/CCScheduler.cpp | 27 +++++++++------------------ cocos/2d/CCScheduler.h | 3 ++- 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index f1b1c9e59c..a617a4b693 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -256,7 +256,7 @@ Scheduler::Scheduler(void) , _currentTarget(nullptr) , _currentTargetSalvaged(false) , _updateHashLocked(false) -, _scriptHandlerEntries(nullptr) +, _scriptHandlerEntries(20) { // I don't expect to have more than 30 functions to all per frame _functionsToPerform.reserve(30); @@ -265,7 +265,6 @@ Scheduler::Scheduler(void) Scheduler::~Scheduler(void) { unscheduleAll(); - CC_SAFE_RELEASE(_scriptHandlerEntries); } void Scheduler::removeHashElement(_hashSelectorEntry *element) @@ -630,10 +629,7 @@ void Scheduler::unscheduleAllWithMinPriority(int minPriority) } } - if (_scriptHandlerEntries) - { - _scriptHandlerEntries->removeAllObjects(); - } + _scriptHandlerEntries.clear(); } void Scheduler::unscheduleAllForTarget(Object *target) @@ -675,20 +671,15 @@ void Scheduler::unscheduleAllForTarget(Object *target) unsigned int Scheduler::scheduleScriptFunc(unsigned int handler, float interval, bool paused) { SchedulerScriptHandlerEntry* entry = SchedulerScriptHandlerEntry::create(handler, interval, paused); - if (!_scriptHandlerEntries) - { - _scriptHandlerEntries = Array::createWithCapacity(20); - _scriptHandlerEntries->retain(); - } - _scriptHandlerEntries->addObject(entry); + _scriptHandlerEntries.pushBack(entry); return entry->getEntryId(); } void Scheduler::unscheduleScriptEntry(unsigned int scheduleScriptEntryID) { - for (int i = _scriptHandlerEntries->count() - 1; i >= 0; i--) + for (int i = _scriptHandlerEntries.size() - 1; i >= 0; i--) { - SchedulerScriptHandlerEntry* entry = static_cast(_scriptHandlerEntries->getObjectAtIndex(i)); + SchedulerScriptHandlerEntry* entry = _scriptHandlerEntries.at(i); if (entry->getEntryId() == (int)scheduleScriptEntryID) { entry->markedForDeletion(); @@ -951,14 +942,14 @@ void Scheduler::update(float dt) // // Iterate over all the script callbacks - if (_scriptHandlerEntries) + if (!_scriptHandlerEntries.empty()) { - for (auto i = _scriptHandlerEntries->count() - 1; i >= 0; i--) + for (auto i = _scriptHandlerEntries.size() - 1; i >= 0; i--) { - SchedulerScriptHandlerEntry* eachEntry = static_cast(_scriptHandlerEntries->getObjectAtIndex(i)); + SchedulerScriptHandlerEntry* eachEntry = _scriptHandlerEntries.at(i); if (eachEntry->isMarkedForDeletion()) { - _scriptHandlerEntries->removeObjectAtIndex(i); + _scriptHandlerEntries.remove(i); } else if (!eachEntry->isPaused()) { diff --git a/cocos/2d/CCScheduler.h b/cocos/2d/CCScheduler.h index 247b773d00..3146729205 100644 --- a/cocos/2d/CCScheduler.h +++ b/cocos/2d/CCScheduler.h @@ -107,6 +107,7 @@ protected: struct _listEntry; struct _hashSelectorEntry; struct _hashUpdateEntry; +class SchedulerScriptHandlerEntry; /** @brief Scheduler is responsible for triggering the scheduled callbacks. You should not use NSTimer. Instead use this class. @@ -290,7 +291,7 @@ protected: bool _currentTargetSalvaged; // If true unschedule will not remove anything from a hash. Elements will only be marked for deletion. bool _updateHashLocked; - Array* _scriptHandlerEntries; + Vector _scriptHandlerEntries; // Used for "perform Function" std::vector> _functionsToPerform; From 06e6d38ab09f534b43ce38d04b9c4cc76163c1e5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:26:17 +0800 Subject: [PATCH 12/27] issue #2790: Initializes Value when empty constructor was invoked. --- cocos/base/CCValue.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/base/CCValue.cpp b/cocos/base/CCValue.cpp index 41f18db6b3..fa6e457425 100644 --- a/cocos/base/CCValue.cpp +++ b/cocos/base/CCValue.cpp @@ -28,9 +28,9 @@ NS_CC_BEGIN Value::Value() -: _vectorData(nullptr) -, _mapData(nullptr) -, _intKeyMapData(nullptr) +: _vectorData(new ValueVector()) +, _mapData(new ValueMap()) +, _intKeyMapData(new IntValueMap()) , _type(Type::NONE) { From 365f6faabbb3b94be7e1d383c79242d0de89e35e Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:26:52 +0800 Subject: [PATCH 13/27] issue #2790: Warning fixes for CCDictionary.cpp and CCString.cpp --- cocos/base/CCDictionary.cpp | 30 +++++++++++++++--------------- cocos/base/CCString.cpp | 4 ++-- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/cocos/base/CCDictionary.cpp b/cocos/base/CCDictionary.cpp index de9abbb31f..ceb0333823 100644 --- a/cocos/base/CCDictionary.cpp +++ b/cocos/base/CCDictionary.cpp @@ -88,12 +88,12 @@ unsigned int Dictionary::count() return HASH_COUNT(_elements); } -Array* Dictionary::allKeys() +__Array* Dictionary::allKeys() { int iKeyCount = this->count(); if (iKeyCount <= 0) return NULL; - Array* pArray = Array::createWithCapacity(iKeyCount); + __Array* array = __Array::createWithCapacity(iKeyCount); DictElement *pElement, *tmp; if (_dictType == kDictStr) @@ -101,7 +101,7 @@ Array* Dictionary::allKeys() HASH_ITER(hh, _elements, pElement, tmp) { String* pOneKey = new String(pElement->_strKey); - pArray->addObject(pOneKey); + array->addObject(pOneKey); CC_SAFE_RELEASE(pOneKey); } } @@ -110,19 +110,19 @@ Array* Dictionary::allKeys() HASH_ITER(hh, _elements, pElement, tmp) { Integer* pOneKey = new Integer(static_cast(pElement->_intKey)); - pArray->addObject(pOneKey); + array->addObject(pOneKey); CC_SAFE_RELEASE(pOneKey); } } - return pArray; + return array; } -Array* Dictionary::allKeysForObject(Object* object) +__Array* Dictionary::allKeysForObject(Object* object) { int iKeyCount = this->count(); if (iKeyCount <= 0) return NULL; - Array* pArray = Array::create(); + __Array* array = __Array::create(); DictElement *pElement, *tmp; @@ -133,7 +133,7 @@ Array* Dictionary::allKeysForObject(Object* object) if (object == pElement->_object) { String* pOneKey = new String(pElement->_strKey); - pArray->addObject(pOneKey); + array->addObject(pOneKey); CC_SAFE_RELEASE(pOneKey); } } @@ -145,12 +145,12 @@ Array* Dictionary::allKeysForObject(Object* object) if (object == pElement->_object) { Integer* pOneKey = new Integer(static_cast(pElement->_intKey)); - pArray->addObject(pOneKey); + array->addObject(pOneKey); CC_SAFE_RELEASE(pOneKey); } } } - return pArray; + return array; } Object* Dictionary::objectForKey(const std::string& key) @@ -303,10 +303,10 @@ void Dictionary::setObjectUnSafe(Object* pObject, const intptr_t key) HASH_ADD_PTR(_elements, _intKey, pElement); } -void Dictionary::removeObjectsForKeys(Array* pKeyArray) +void Dictionary::removeObjectsForKeys(__Array* pKey__Array) { Object* pObj = NULL; - CCARRAY_FOREACH(pKeyArray, pObj) + CCARRAY_FOREACH(pKey__Array, pObj) { String* pStr = static_cast(pObj); removeObjectForKey(pStr->getCString()); @@ -378,7 +378,7 @@ Dictionary* Dictionary::createWithDictionary(Dictionary* srcDict) return srcDict->clone(); } -static Array* visitArray(const ValueVector& array); +static __Array* visitArray(const ValueVector& array); static Dictionary* visitDict(const ValueMap& dict) { @@ -411,9 +411,9 @@ static Dictionary* visitDict(const ValueMap& dict) return ret; } -static Array* visitArray(const ValueVector& array) +static __Array* visitArray(const ValueVector& array) { - Array* ret = new Array(); + __Array* ret = new __Array(); ret->init(); std::for_each(array.begin(), array.end(), [&ret](const Value& value){ diff --git a/cocos/base/CCString.cpp b/cocos/base/CCString.cpp index c2a6ec6bd1..97e1261f48 100644 --- a/cocos/base/CCString.cpp +++ b/cocos/base/CCString.cpp @@ -178,9 +178,9 @@ void String::appendWithFormat(const char* format, ...) } -Array* String::componentsSeparatedByString(const char *delimiter) +__Array* String::componentsSeparatedByString(const char *delimiter) { - Array* result = Array::create(); + __Array* result = __Array::create(); size_t cutAt; while( (cutAt = _string.find_first_of(delimiter)) != _string.npos ) From 16cd61f024176f4c338237bce7cc31b88e9007aa Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:28:14 +0800 Subject: [PATCH 14/27] issue #2790: Vector for physics and remove lots of unneeded dynamic_cast. --- cocos/physics/CCPhysicsBody.cpp | 18 +++++++++--------- cocos/physics/CCPhysicsWorld.cpp | 30 +++++++++++------------------- 2 files changed, 20 insertions(+), 28 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 7b78ee4664..69a197b9b7 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -652,7 +652,7 @@ void PhysicsBody::removeShape(int tag, bool reduceMassAndMoment/* = true*/) void PhysicsBody::removeShape(PhysicsShape* shape, bool reduceMassAndMoment/* = true*/) { - if (_shapes->getIndexOfObject(shape) != -1) + if (_shapes.getIndex(shape) != -1) { // deduce the area, mass and moment // area must update before mass, because the density changes depend on it. @@ -751,9 +751,9 @@ void PhysicsBody::setCategoryBitmask(int bitmask) { _categoryBitmask = bitmask; - for (auto shape : *_shapes) + for (auto& shape : _shapes) { - ((PhysicsShape*)shape)->setCategoryBitmask(bitmask); + shape->setCategoryBitmask(bitmask); } } @@ -761,9 +761,9 @@ void PhysicsBody::setContactTestBitmask(int bitmask) { _contactTestBitmask = bitmask; - for (auto shape : *_shapes) + for (auto& shape : _shapes) { - ((PhysicsShape*)shape)->setContactTestBitmask(bitmask); + shape->setContactTestBitmask(bitmask); } } @@ -771,17 +771,17 @@ void PhysicsBody::setCollisionBitmask(int bitmask) { _collisionBitmask = bitmask; - for (auto shape : *_shapes) + for (auto& shape : _shapes) { - ((PhysicsShape*)shape)->setCollisionBitmask(bitmask); + shape->setCollisionBitmask(bitmask); } } void PhysicsBody::setGroup(int group) { - for (auto shape : *_shapes) + for (auto& shape : _shapes) { - ((PhysicsShape*)shape)->setGroup(group); + shape->setGroup(group); } } diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 96a42c7797..4d3f5066ac 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -933,7 +933,7 @@ void PhysicsWorld::doRemoveBody(PhysicsBody* body) } // remove shaps - for (auto shape : *body->getShapes()) + for (auto& shape : body->getShapes()) { removeShape(dynamic_cast(shape)); } @@ -949,15 +949,14 @@ void PhysicsWorld::doRemoveJoint(PhysicsJoint* joint) void PhysicsWorld::removeAllBodies() { - for (Object* obj : *_bodies) + for (auto& obj : _bodies) { PhysicsBody* child = dynamic_cast(obj); removeBodyOrDelay(child); child->_world = nullptr; } - _bodies->removeAllObjects(); - CC_SAFE_RELEASE(_bodies); + _bodies.clear(); } void PhysicsWorld::setDebugDrawMask(int mask) @@ -970,18 +969,18 @@ void PhysicsWorld::setDebugDrawMask(int mask) _debugDrawMask = mask; } -Array* PhysicsWorld::getAllBodies() const +const Vector& PhysicsWorld::getAllBodies() const { return _bodies; } PhysicsBody* PhysicsWorld::getBody(int tag) const { - for (auto body : *_bodies) + for (auto& body : _bodies) { - if (((PhysicsBody*)body)->getTag() == tag) + if (body->getTag() == tag) { - return (PhysicsBody*)body; + return body; } } @@ -990,12 +989,10 @@ PhysicsBody* PhysicsWorld::getBody(int tag) const void PhysicsWorld::setGravity(const Vect& gravity) { - if (_bodies != nullptr) + if (!_bodies.empty()) { - for (auto child : *_bodies) + for (auto& body : _bodies) { - PhysicsBody* body = dynamic_cast(child); - // reset gravity for body if (!body->isGravityEnabled()) { @@ -1016,10 +1013,10 @@ void PhysicsWorld::update(float delta) // the updateJoints must run before the updateBodies. updateJoints(); updateBodies(); - _delayDirty = !(_delayAddBodies->count() == 0 && _delayRemoveBodies->count() == 0 && _delayAddJoints.size() == 0 && _delayRemoveJoints.size() == 0); + _delayDirty = !(_delayAddBodies.size() == 0 && _delayRemoveBodies.size() == 0 && _delayAddJoints.size() == 0 && _delayRemoveJoints.size() == 0); } - for (auto body : *_bodies) + for (auto& body : _bodies) { body->update(delta); } @@ -1036,13 +1033,10 @@ PhysicsWorld::PhysicsWorld() : _gravity(Point(0.0f, -98.0f)) , _speed(1.0f) , _info(nullptr) -, _bodies(nullptr) , _scene(nullptr) , _delayDirty(false) , _debugDraw(nullptr) , _debugDrawMask(DEBUGDRAW_NONE) -, _delayAddBodies(nullptr) -, _delayRemoveBodies(nullptr) { } @@ -1051,8 +1045,6 @@ PhysicsWorld::~PhysicsWorld() { removeAllJoints(true); removeAllBodies(); - CC_SAFE_RELEASE(_delayRemoveBodies); - CC_SAFE_RELEASE(_delayAddBodies); CC_SAFE_DELETE(_info); CC_SAFE_DELETE(_debugDraw); } From ba56bf6ecdd71881292be5b734e08de5d65249f7 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:28:37 +0800 Subject: [PATCH 15/27] issue #2790: Updates Tests. --- .../Classes/ActionsTest/ActionsTest.cpp | 6 ++---- .../TestCpp/Classes/ActionsTest/ActionsTest.h | 2 +- .../Classes/PhysicsTest/PhysicsTest.cpp | 11 +++++------ .../Classes/SchedulerTest/SchedulerTest.cpp | 18 +++++++----------- .../Classes/SchedulerTest/SchedulerTest.h | 4 ++-- 5 files changed, 17 insertions(+), 24 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp index 66e8e6edb1..cde2c87f2c 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp @@ -2137,14 +2137,13 @@ string ActionCardinalSpline::subtitle() */ PauseResumeActions::PauseResumeActions() -: _pausedTargets(NULL) { } PauseResumeActions::~PauseResumeActions() { - CC_SAFE_RELEASE(_pausedTargets); + } void PauseResumeActions::onEnter() @@ -2176,9 +2175,7 @@ void PauseResumeActions::pause(float dt) log("Pausing"); auto director = Director::getInstance(); - CC_SAFE_RELEASE(_pausedTargets); _pausedTargets = director->getActionManager()->pauseAllRunningActions(); - CC_SAFE_RETAIN(_pausedTargets); } void PauseResumeActions::resume(float dt) @@ -2186,6 +2183,7 @@ void PauseResumeActions::resume(float dt) log("Resuming"); auto director = Director::getInstance(); director->getActionManager()->resumeTargets(_pausedTargets); + _pausedTargets.clear(); } //------------------------------------------------------------------ diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h index 9a601b5212..0cb8ce0f20 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h +++ b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h @@ -553,7 +553,7 @@ public: void pause(float dt); void resume(float dt); private: - Set *_pausedTargets; + Vector _pausedTargets; }; #endif diff --git a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp index ed291dc5ff..4865b81352 100644 --- a/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PhysicsTest/PhysicsTest.cpp @@ -360,14 +360,14 @@ Sprite* PhysicsDemo::makeTriangle(Point point, Size size, PhysicsMaterial materi bool PhysicsDemo::onTouchBegan(Touch* touch, Event* event) { auto location = touch->getLocation(); - Array* arr = _scene->getPhysicsWorld()->getShapes(location); + auto arr = _scene->getPhysicsWorld()->getShapes(location); PhysicsBody* body = nullptr; - for (Object* obj : *arr) + for (auto& obj : arr) { - if ((dynamic_cast(obj)->getBody()->getTag() & DRAG_BODYS_TAG) != 0) + if ((obj->getBody()->getTag() & DRAG_BODYS_TAG) != 0) { - body = dynamic_cast(obj)->getBody(); + body = obj->getBody(); break; } } @@ -1017,9 +1017,8 @@ void PhysicsDemoPump::onEnter() void PhysicsDemoPump::update(float delta) { - for (auto obj : *_scene->getPhysicsWorld()->getAllBodies()) + for (const auto& body : _scene->getPhysicsWorld()->getAllBodies()) { - PhysicsBody* body = dynamic_cast(obj); if (body->getTag() == DRAG_BODYS_TAG && body->getPosition().y < 0.0f) { body->getNode()->setPosition(VisibleRect::leftTop() + Point(75 + CCRANDOM_0_1() * 90, 0)); diff --git a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp index 867f58f98e..e03e7d7943 100644 --- a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.cpp @@ -195,14 +195,13 @@ std::string SchedulerPauseResume::subtitle() //------------------------------------------------------------------ SchedulerPauseResumeAll::SchedulerPauseResumeAll() -: _pausedTargets(NULL) { } SchedulerPauseResumeAll::~SchedulerPauseResumeAll() { - CC_SAFE_RELEASE(_pausedTargets); + } void SchedulerPauseResumeAll::onEnter() @@ -227,7 +226,7 @@ void SchedulerPauseResumeAll::update(float delta) void SchedulerPauseResumeAll::onExit() { - if(_pausedTargets != NULL) + if (!_pausedTargets.empty()) { Director::getInstance()->getScheduler()->resumeTargets(_pausedTargets); } @@ -249,9 +248,8 @@ void SchedulerPauseResumeAll::pause(float dt) log("Pausing"); auto director = Director::getInstance(); _pausedTargets = director->getScheduler()->pauseAllTargets(); - CC_SAFE_RETAIN(_pausedTargets); - unsigned int c = _pausedTargets->count(); + int c = _pausedTargets.size(); if (c > 2) { @@ -265,7 +263,7 @@ void SchedulerPauseResumeAll::resume(float dt) log("Resuming"); auto director = Director::getInstance(); director->getScheduler()->resumeTargets(_pausedTargets); - CC_SAFE_RELEASE_NULL(_pausedTargets); + _pausedTargets.clear(); } std::string SchedulerPauseResumeAll::title() @@ -285,14 +283,13 @@ std::string SchedulerPauseResumeAll::subtitle() //------------------------------------------------------------------ SchedulerPauseResumeAllUser::SchedulerPauseResumeAllUser() -: _pausedTargets(NULL) { } SchedulerPauseResumeAllUser::~SchedulerPauseResumeAllUser() { - CC_SAFE_RELEASE(_pausedTargets); + } void SchedulerPauseResumeAllUser::onEnter() @@ -314,7 +311,7 @@ void SchedulerPauseResumeAllUser::onEnter() void SchedulerPauseResumeAllUser::onExit() { - if(_pausedTargets != NULL) + if (!_pausedTargets.empty()) { Director::getInstance()->getScheduler()->resumeTargets(_pausedTargets); } @@ -336,7 +333,6 @@ void SchedulerPauseResumeAllUser::pause(float dt) log("Pausing"); auto director = Director::getInstance(); _pausedTargets = director->getScheduler()->pauseAllTargetsWithMinPriority(Scheduler::PRIORITY_NON_SYSTEM_MIN); - CC_SAFE_RETAIN(_pausedTargets); } void SchedulerPauseResumeAllUser::resume(float dt) @@ -344,7 +340,7 @@ void SchedulerPauseResumeAllUser::resume(float dt) log("Resuming"); auto director = Director::getInstance(); director->getScheduler()->resumeTargets(_pausedTargets); - CC_SAFE_RELEASE_NULL(_pausedTargets); + _pausedTargets.clear(); } std::string SchedulerPauseResumeAllUser::title() diff --git a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h index 226136cb9c..b77e798a83 100644 --- a/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h +++ b/samples/Cpp/TestCpp/Classes/SchedulerTest/SchedulerTest.h @@ -79,7 +79,7 @@ public: void pause(float dt); void resume(float dt); private: - Set* _pausedTargets; + Vector _pausedTargets; }; class SchedulerPauseResumeAllUser : public SchedulerTestLayer @@ -99,7 +99,7 @@ public: void pause(float dt); void resume(float dt); private: - Set* _pausedTargets; + Vector _pausedTargets; }; class SchedulerUnscheduleAll : public SchedulerTestLayer From 713d89b6d80e420383d9415f65dc44a03513755d Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:36:07 +0800 Subject: [PATCH 16/27] issue #2790: Uses Vector instead of CCArray* for CCControl. Uses std::unordered_map*> instead of CCDictionary*. --- .../GUI/CCControlExtension/CCControl.cpp | 83 ++++++++++--------- extensions/GUI/CCControlExtension/CCControl.h | 5 +- 2 files changed, 44 insertions(+), 44 deletions(-) diff --git a/extensions/GUI/CCControlExtension/CCControl.cpp b/extensions/GUI/CCControlExtension/CCControl.cpp index 4b3edfa1f9..184b8125b5 100644 --- a/extensions/GUI/CCControlExtension/CCControl.cpp +++ b/extensions/GUI/CCControlExtension/CCControl.cpp @@ -74,10 +74,6 @@ bool Control::init() setSelected(false); setHighlighted(false); - // Initialise the tables - _dispatchTable = new Dictionary(); - _dispatchTable->init(); - auto dispatcher = Director::getInstance()->getEventDispatcher(); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->onTouchBegan = CC_CALLBACK_2(Control::onTouchBegan, this); @@ -97,7 +93,12 @@ bool Control::init() Control::~Control() { - CC_SAFE_RELEASE(_dispatchTable); + for (auto iter = _dispatchTable.begin(); iter != _dispatchTable.end(); ++iter) + { + delete iter->second; + } + + _dispatchTable.clear(); } void Control::sendActionsForControlEvents(EventType controlEvents) @@ -109,14 +110,12 @@ void Control::sendActionsForControlEvents(EventType controlEvents) if (((int)controlEvents & (1 << i))) { // Call invocations - // - Array* invocationList = this->dispatchListforControlEvent((Control::EventType)(1<(pObj); + const auto& invocationList = this->dispatchListforControlEvent((Control::EventType)(1<invoke(this); - } + }); + //Call ScriptFunc if (kScriptTypeLua == _scriptType) { @@ -161,8 +160,8 @@ void Control::addTargetWithActionForControlEvent(Object* target, Handler action, Invocation *invocation = Invocation::create(target, action, controlEvent); // Add the invocation into the dispatch list for the given control event - Array* eventInvocationList = this->dispatchListforControlEvent(controlEvent); - eventInvocationList->addObject(invocation); + auto& eventInvocationList = this->dispatchListforControlEvent(controlEvent); + eventInvocationList.pushBack(invocation); } void Control::removeTargetWithActionForControlEvents(Object* target, Handler action, EventType controlEvents) @@ -182,7 +181,7 @@ void Control::removeTargetWithActionForControlEvent(Object* target, Handler acti { // Retrieve all invocations for the given control event // - Array *eventInvocationList = this->dispatchListforControlEvent(controlEvent); + auto& eventInvocationList = this->dispatchListforControlEvent(controlEvent); //remove all invocations if the target and action are null //TODO: should the invocations be deleted, or just removed from the array? Won't that cause issues if you add a single invocation for multiple events? @@ -190,30 +189,27 @@ void Control::removeTargetWithActionForControlEvent(Object* target, Handler acti if (!target && !action) { //remove objects - eventInvocationList->removeAllObjects(); + eventInvocationList.clear(); } else { //normally we would use a predicate, but this won't work here. Have to do it manually - Object* pObj = NULL; - CCARRAY_FOREACH(eventInvocationList, pObj) + eventInvocationList.forEach([&](Invocation* invocation){ + bool shouldBeRemoved=true; + if (target) { - Invocation *invocation = static_cast(pObj); - bool shouldBeRemoved=true; - if (target) - { - shouldBeRemoved=(target==invocation->getTarget()); - } - if (action) - { - shouldBeRemoved=(shouldBeRemoved && (action==invocation->getAction())); - } - // Remove the corresponding invocation object - if (shouldBeRemoved) - { - eventInvocationList->removeObject(invocation, bDeleteObjects); - } + shouldBeRemoved=(target==invocation->getTarget()); } + if (action) + { + shouldBeRemoved=(shouldBeRemoved && (action==invocation->getAction())); + } + // Remove the corresponding invocation object + if (shouldBeRemoved) + { + eventInvocationList.removeObject(invocation, bDeleteObjects); + } + }); } } @@ -254,17 +250,22 @@ bool Control::isTouchInside(Touch* touch) return bBox.containsPoint(touchLocation); } -Array* Control::dispatchListforControlEvent(EventType controlEvent) +Vector& Control::dispatchListforControlEvent(EventType controlEvent) { - Array* invocationList = static_cast(_dispatchTable->objectForKey((int)controlEvent)); - + Vector* invocationList = nullptr; + auto iter = _dispatchTable.find((int)controlEvent); + // If the invocation list does not exist for the dispatch table, we create it - if (invocationList == NULL) + if (iter == _dispatchTable.end()) { - invocationList = Array::createWithCapacity(1); - _dispatchTable->setObject(invocationList, (int)controlEvent); - } - return invocationList; + invocationList = new Vector(); + _dispatchTable[(int)controlEvent] = invocationList; + } + else + { + invocationList = iter->second; + } + return *invocationList; } void Control::needsLayout() diff --git a/extensions/GUI/CCControlExtension/CCControl.h b/extensions/GUI/CCControlExtension/CCControl.h index a86970e1d8..d5adfa5dc7 100644 --- a/extensions/GUI/CCControlExtension/CCControl.h +++ b/extensions/GUI/CCControlExtension/CCControl.h @@ -210,8 +210,7 @@ protected: * * @return the Invocation list for the given control event. */ - // - Array* dispatchListforControlEvent(EventType controlEvent); + Vector& dispatchListforControlEvent(EventType controlEvent); /** * Adds a target and action for a particular event to an internal dispatch @@ -254,7 +253,7 @@ protected: * target-actions pairs. For each ButtonEvents a list of NSInvocation * (which contains the target-action pair) is linked. */ - Dictionary* _dispatchTable; + std::unordered_map*> _dispatchTable; //CCRGBAProtocol bool _isOpacityModifyRGB; From be7c62a2b97c16ae58b7490adfc248fcc010b07c Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 14:44:21 +0800 Subject: [PATCH 17/27] issue #2790: Removes unused CCSet binding glue codes. --- .../javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 46cb2c9d29..29352b90d5 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -cd3a15ee39c63c93b40e323eda6fa43f584742aa \ No newline at end of file +7a245db1098d7ced5947aca62f43e67f06d1492d \ No newline at end of file From f1fac73bb48fe5b166275be143bc500e446a3d36 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 16:14:00 +0800 Subject: [PATCH 18/27] issue #2790: Fix wrong include. --- extensions/GUI/CCScrollView/CCTableViewCell.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/GUI/CCScrollView/CCTableViewCell.h b/extensions/GUI/CCScrollView/CCTableViewCell.h index 55e1079196..96ab28d67d 100644 --- a/extensions/GUI/CCScrollView/CCTableViewCell.h +++ b/extensions/GUI/CCScrollView/CCTableViewCell.h @@ -27,7 +27,7 @@ #define __CCTABLEVIEWCELL_H__ #include "cocos2d.h" -#include "ExtensionMacros.h" +#include "extensions/ExtensionMacros.h" NS_CC_EXT_BEGIN From beb6bb6c8d2df55e846ffd440929213ca80f1ae4 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 16:14:22 +0800 Subject: [PATCH 19/27] issue #2790: Bug fix in CCMap.h --- cocos/base/CCMap.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index 8630dff9f3..d62e72dbea 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -225,12 +225,14 @@ public: clear(); _data = other._data; addRefForAllObjects(); + return *this; } Map& operator= ( Map&& other ) { CCLOG("In the move assignment operator of Map!"); _data = std::move(other._data); + return *this; } protected: @@ -239,7 +241,7 @@ protected: { for (auto iter = _data.begin(); iter != _data.end(); ++iter) { - _data->second->retain(); + iter->second->retain(); } } From 908f5ed51562f801ec14d312a88c4734c28312a5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 16:38:50 +0800 Subject: [PATCH 20/27] issue #2790: Fix for TMXObjectGroup::getObject. --- cocos/2d/CCTMXObjectGroup.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/cocos/2d/CCTMXObjectGroup.cpp b/cocos/2d/CCTMXObjectGroup.cpp index 672dc0509f..3cc08a0473 100644 --- a/cocos/2d/CCTMXObjectGroup.cpp +++ b/cocos/2d/CCTMXObjectGroup.cpp @@ -44,14 +44,15 @@ TMXObjectGroup::~TMXObjectGroup() ValueMap TMXObjectGroup::getObject(const std::string& objectName) const { - if (_objects.size() > 0) + if (!_objects.empty()) { - for (auto& v : _objects) + for (const auto& v : _objects) { - ValueMap dict = v.asValueMap(); - if (dict["name"].asString() == objectName) + const ValueMap& dict = v.asValueMap(); + if (dict.find("name") != dict.end()) { - return dict; + if (dict.at("name").asString() == objectName) + return dict; } } } From abbcd45c589d797ded9224ccb3e4ac3852400423 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 7 Dec 2013 23:32:29 +0800 Subject: [PATCH 21/27] =?UTF-8?q?issue=20#2790:=20CCLOG=20=E2=80=94>=20CCL?= =?UTF-8?q?OGINFO=20in=20CCMap.h?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/base/CCMap.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index d62e72dbea..df39fc80d0 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -221,7 +221,7 @@ public: Map& operator= ( const Map& other ) { - CCLOG("In the copy assignment operator of Map!"); + CCLOGINFO("In the copy assignment operator of Map!"); clear(); _data = other._data; addRefForAllObjects(); @@ -230,7 +230,7 @@ public: Map& operator= ( Map&& other ) { - CCLOG("In the move assignment operator of Map!"); + CCLOGINFO("In the move assignment operator of Map!"); _data = std::move(other._data); return *this; } From 45cb79c5f42f9b7192cc41c5150761b194b743fa Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 8 Dec 2013 22:10:14 +0800 Subject: [PATCH 22/27] issue #2790: Updates bindings-generator. Fixes issue at https://github.com/cocos2d/bindings-generator/pull/53 .Matches typedef name firstly in conversion.yaml. --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index eb2bc8934b..53cfcb95f4 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit eb2bc8934b01f6cdc7661648f883e2e6374a5cf7 +Subproject commit 53cfcb95f4d06af5f484eeda77c9eb5e8b835ec9 From e07f2bdddd32ee57264543535dbdc81cd0d170a8 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 8 Dec 2013 22:17:54 +0800 Subject: [PATCH 23/27] issue #2790: Vector and Map for CCBReader. Not finished yet. --- .../cocosbuilder/CCBAnimationManager.cpp | 32 +-- .../editor-support/cocosbuilder/CCBReader.cpp | 189 ++++++++---------- cocos/editor-support/cocosbuilder/CCBReader.h | 32 +-- .../cocosbuilder/CCBSequenceProperty.cpp | 6 +- .../cocosbuilder/CCBSequenceProperty.h | 4 +- .../cocosbuilder/CCNodeLoader.cpp | 30 ++- 6 files changed, 128 insertions(+), 165 deletions(-) diff --git a/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp b/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp index 3229c12582..0db26201de 100644 --- a/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp +++ b/cocos/editor-support/cocosbuilder/CCBAnimationManager.cpp @@ -529,9 +529,9 @@ void CCBAnimationManager::setAnimatedProperty(const char *propName, Node *pNode, void CCBAnimationManager::setFirstFrame(Node *pNode, CCBSequenceProperty *pSeqProp, float fTweenDuration) { - Array *keyframes = pSeqProp->getKeyframes(); + auto& keyframes = pSeqProp->getKeyframes(); - if (keyframes->count() == 0) + if (keyframes.empty()) { // Use base value (no animation) Object *baseValue = getBaseValue(pNode, pSeqProp->getName()); @@ -541,7 +541,7 @@ void CCBAnimationManager::setFirstFrame(Node *pNode, CCBSequenceProperty *pSeqPr else { // Use first keyframe - CCBKeyframe *keyframe = (CCBKeyframe*)keyframes->getObjectAtIndex(0); + CCBKeyframe *keyframe = keyframes.at(0); setAnimatedProperty(pSeqProp->getName(), pNode, keyframe->getValue(), fTweenDuration); } } @@ -621,13 +621,13 @@ Object* CCBAnimationManager::actionForCallbackChannel(CCBSequenceProperty* chann float lastKeyframeTime = 0; Vector actions; - Array *keyframes = channel->getKeyframes(); - long numKeyframes = keyframes->count(); + auto& keyframes = channel->getKeyframes(); + int numKeyframes = keyframes.size(); for (long i = 0; i < numKeyframes; ++i) { - CCBKeyframe *keyframe = (CCBKeyframe*)keyframes->getObjectAtIndex(i); + CCBKeyframe *keyframe = keyframes.at(i); float timeSinceLastKeyframe = keyframe->getTime() - lastKeyframeTime; lastKeyframeTime = keyframe->getTime(); if(timeSinceLastKeyframe > 0) { @@ -700,12 +700,12 @@ Object* CCBAnimationManager::actionForSoundChannel(CCBSequenceProperty* channel) float lastKeyframeTime = 0; Vector actions; - Array *keyframes = channel->getKeyframes(); - long numKeyframes = keyframes->count(); + auto& keyframes = channel->getKeyframes(); + int numKeyframes = keyframes.size(); - for (int i = 0; i < numKeyframes; ++i) { - - CCBKeyframe *keyframe = (CCBKeyframe*)keyframes->getObjectAtIndex(i); + for (int i = 0; i < numKeyframes; ++i) + { + CCBKeyframe *keyframe = keyframes.at(i); float timeSinceLastKeyframe = keyframe->getTime() - lastKeyframeTime; lastKeyframeTime = keyframe->getTime(); if(timeSinceLastKeyframe > 0) { @@ -741,15 +741,15 @@ Object* CCBAnimationManager::actionForSoundChannel(CCBSequenceProperty* channel) void CCBAnimationManager::runAction(Node *pNode, CCBSequenceProperty *pSeqProp, float fTweenDuration) { - Array *keyframes = pSeqProp->getKeyframes(); - long numKeyframes = keyframes->count(); + auto& keyframes = pSeqProp->getKeyframes(); + int numKeyframes = keyframes.size(); if (numKeyframes > 1) { // Make an animation! Vector actions; - CCBKeyframe *keyframeFirst = (CCBKeyframe*)keyframes->getObjectAtIndex(0); + CCBKeyframe *keyframeFirst = keyframes.at(0); float timeFirst = keyframeFirst->getTime() + fTweenDuration; if (timeFirst > 0) @@ -759,8 +759,8 @@ void CCBAnimationManager::runAction(Node *pNode, CCBSequenceProperty *pSeqProp, for (int i = 0; i < numKeyframes - 1; ++i) { - CCBKeyframe *kf0 = (CCBKeyframe*)keyframes->getObjectAtIndex(i); - CCBKeyframe *kf1 = (CCBKeyframe*)keyframes->getObjectAtIndex(i+1); + CCBKeyframe *kf0 = keyframes.at(i); + CCBKeyframe *kf1 = keyframes.at(i+1); ActionInterval *action = getAction(kf0, kf1, pSeqProp->getName(), pNode); if (action) diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index 1f778248f2..5f0cd809ee 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -24,7 +24,7 @@ namespace cocosbuilder {; Implementation of CCBFile *************************************************************************/ -CCBFile::CCBFile():_CCBFileNode(NULL) {} +CCBFile::CCBFile():_CCBFileNode(nullptr) {} CCBFile* CCBFile::create() { @@ -55,18 +55,13 @@ void CCBFile::setCCBFileNode(Node *pNode) *************************************************************************/ CCBReader::CCBReader(NodeLoaderLibrary * pNodeLoaderLibrary, CCBMemberVariableAssigner * pCCBMemberVariableAssigner, CCBSelectorResolver * pCCBSelectorResolver, NodeLoaderListener * pNodeLoaderListener) -: _data(NULL) -, _bytes(NULL) +: _data(nullptr) +, _bytes(nullptr) , _currentByte(-1) , _currentBit(-1) -, _owner(NULL) -, _actionManager(NULL) -, _actionManagers(NULL) -, _animatedProps(NULL) -, _ownerOutletNodes(NULL) -, _nodesWithAnimationManagers(NULL) -, _animationManagersForNodes(NULL) -, _ownerCallbackNodes(NULL) +, _owner(nullptr) +, _actionManager(nullptr) +, _animatedProps(nullptr) { this->_nodeLoaderLibrary = pNodeLoaderLibrary; this->_nodeLoaderLibrary->retain(); @@ -77,18 +72,13 @@ CCBReader::CCBReader(NodeLoaderLibrary * pNodeLoaderLibrary, CCBMemberVariableAs } CCBReader::CCBReader(CCBReader * ccbReader) -: _data(NULL) -, _bytes(NULL) +: _data(nullptr) +, _bytes(nullptr) , _currentByte(-1) , _currentBit(-1) -, _owner(NULL) -, _actionManager(NULL) -, _actionManagers(NULL) -, _animatedProps(NULL) -, _ownerOutletNodes(NULL) -, _nodesWithAnimationManagers(NULL) -, _animationManagersForNodes(NULL) -, _ownerCallbackNodes(NULL) +, _owner(nullptr) +, _actionManager(nullptr) +, _animatedProps(nullptr) { this->_loadedSpriteSheets = ccbReader->_loadedSpriteSheets; this->_nodeLoaderLibrary = ccbReader->_nodeLoaderLibrary; @@ -104,19 +94,16 @@ CCBReader::CCBReader(CCBReader * ccbReader) } CCBReader::CCBReader() -: _data(NULL) -, _bytes(NULL) +: _data(nullptr) +, _bytes(nullptr) , _currentByte(-1) , _currentBit(-1) -, _owner(NULL) -, _actionManager(NULL) -, _actionManagers(NULL) -, _nodeLoaderLibrary(NULL) -, _nodeLoaderListener(NULL) -, _CCBMemberVariableAssigner(NULL) -, _CCBSelectorResolver(NULL) -, _nodesWithAnimationManagers(NULL) -, _animationManagersForNodes(NULL) +, _owner(nullptr) +, _actionManager(nullptr) +, _nodeLoaderLibrary(nullptr) +, _nodeLoaderListener(nullptr) +, _CCBMemberVariableAssigner(nullptr) +, _CCBSelectorResolver(nullptr) { init(); } @@ -128,23 +115,18 @@ CCBReader::~CCBReader() this->_nodeLoaderLibrary->release(); - CC_SAFE_RELEASE(_ownerOutletNodes); _ownerOutletNames.clear(); - CC_SAFE_RELEASE(_ownerCallbackNodes); _ownerCallbackNames.clear(); - CC_SAFE_RELEASE(_ownerOwnerCallbackControlEvents); // Clear string cache. this->_stringCache.clear(); - CC_SAFE_RELEASE(_nodesWithAnimationManagers); - CC_SAFE_RELEASE(_animationManagersForNodes); - setAnimationManager(NULL); + setAnimationManager(nullptr); } void CCBReader::setCCBRootPath(const char* ccbRootPath) { - CCASSERT(ccbRootPath != NULL, ""); + CCASSERT(ccbRootPath != nullptr, ""); _CCBRootPath = ccbRootPath; } @@ -155,13 +137,6 @@ const std::string& CCBReader::getCCBRootPath() const bool CCBReader::init() { - _ownerOutletNodes = new Array(); - _ownerOutletNodes->init(); - _ownerCallbackNodes = new Array(); - _ownerCallbackNodes->init(); - _ownerOwnerCallbackControlEvents = new Array(); - _ownerOwnerCallbackControlEvents->init(); - // Setup action manager CCBAnimationManager *pActionManager = new CCBAnimationManager(); setAnimationManager(pActionManager); @@ -185,12 +160,12 @@ void CCBReader::setAnimationManager(CCBAnimationManager *pAnimationManager) CC_SAFE_RETAIN(_actionManager); } -Dictionary* CCBReader::getAnimationManagers() +Map& CCBReader::getAnimationManagers() { return _actionManagers; } -void CCBReader::setAnimationManagers(Dictionary* x) +void CCBReader::setAnimationManagers(const Map& x) { _actionManagers = x; } @@ -220,7 +195,7 @@ Object* CCBReader::getOwner() Node* CCBReader::readNodeGraphFromFile(const char *pCCBFileName) { - return this->readNodeGraphFromFile(pCCBFileName, NULL); + return this->readNodeGraphFromFile(pCCBFileName, nullptr); } Node* CCBReader::readNodeGraphFromFile(const char* pCCBFileName, Object* pOwner) @@ -230,9 +205,9 @@ Node* CCBReader::readNodeGraphFromFile(const char* pCCBFileName, Object* pOwner) Node* CCBReader::readNodeGraphFromFile(const char *pCCBFileName, Object *pOwner, const Size &parentSize) { - if (NULL == pCCBFileName || strlen(pCCBFileName) == 0) + if (nullptr == pCCBFileName || strlen(pCCBFileName) == 0) { - return NULL; + return nullptr; } std::string strCCBFileName(pCCBFileName); @@ -270,7 +245,6 @@ Node* CCBReader::readNodeGraphFromData(Data *pData, Object *pOwner, const Size & _actionManager->setRootContainerSize(parentSize); _actionManager->_owner = _owner; - Dictionary* animationManagers = Dictionary::create(); Node *pNodeGraph = readFileWithCleanUp(true, animationManagers); if (pNodeGraph && _actionManager->getAutoPlaySequenceId() != -1) @@ -280,25 +254,17 @@ Node* CCBReader::readNodeGraphFromData(Data *pData, Object *pOwner, const Size & } // Assign actionManagers to userObject - if(_jsControlled) - { - _nodesWithAnimationManagers = new Array(); - _nodesWithAnimationManagers->init(); - _animationManagersForNodes = new Array(); - _animationManagersForNodes->init(); - } - DictElement* pElement = NULL; - CCDICT_FOREACH(animationManagers, pElement) + for (auto iter = _actionManagers.begin(); iter != _actionManagers.end(); ++iter) { - Node* pNode = (Node*)pElement->getIntKey(); - CCBAnimationManager* manager = static_cast(animationManagers->objectForKey((intptr_t)pNode)); + Node* pNode = iter->first; + CCBAnimationManager* manager = iter->second; pNode->setUserObject(manager); if (_jsControlled) { - _nodesWithAnimationManagers->addObject(pNode); - _animationManagersForNodes->addObject(manager); + _nodesWithAnimationManagers.pushBack(pNode); + _animationManagersForNodes.pushBack(manager); } } @@ -307,7 +273,7 @@ Node* CCBReader::readNodeGraphFromData(Data *pData, Object *pOwner, const Size & Scene* CCBReader::createSceneWithNodeGraphFromFile(const char *pCCBFileName) { - return createSceneWithNodeGraphFromFile(pCCBFileName, NULL); + return createSceneWithNodeGraphFromFile(pCCBFileName, nullptr); } Scene* CCBReader::createSceneWithNodeGraphFromFile(const char *pCCBFileName, Object *pOwner) @@ -333,28 +299,28 @@ void CCBReader::cleanUpNodeGraph(Node *node) }); } -Node* CCBReader::readFileWithCleanUp(bool bCleanUp, Dictionary* am) +Node* CCBReader::readFileWithCleanUp(bool bCleanUp, const Map& am) { if (! readHeader()) { - return NULL; + return nullptr; } if (! readStringCache()) { - return NULL; + return nullptr; } if (! readSequences()) { - return NULL; + return nullptr; } setAnimationManagers(am); - Node *pNode = readNodeGraph(NULL); + Node *pNode = readNodeGraph(nullptr); - _actionManagers->setObject(_actionManager, intptr_t(pNode)); + _actionManagers.insert(pNode, _actionManager); if (bCleanUp) { @@ -377,7 +343,7 @@ bool CCBReader::readStringCache() { bool CCBReader::readHeader() { /* If no bytes loaded, don't crash about it. */ - if(this->_bytes == NULL) { + if(this->_bytes == nullptr) { return false; } @@ -567,7 +533,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) if (! ccNodeLoader) { log("no corresponding node loader for %s", className.c_str()); - return NULL; + return nullptr; } Node *node = ccNodeLoader->loadNode(pParent, this); @@ -611,7 +577,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) { CCBKeyframe *keyframe = readKeyframe(static_cast(seqProp->getType())); - seqProp->getKeyframes()->addObject(keyframe); + seqProp->getKeyframes().pushBack(keyframe); } seqNodeProps->setObject(seqProp, seqProp->getName()); @@ -628,7 +594,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) // Read properties ccNodeLoader->parseProperties(node, pParent, this); - bool isCCBFileNode = (NULL == dynamic_cast(node)) ? false : true; + bool isCCBFileNode = (nullptr == dynamic_cast(node)) ? false : true; // Handle sub ccb files (remove middle node) if (isCCBFileNode) { @@ -645,7 +611,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) _actionManager->moveAnimationsFromNode(ccbFileNode, embeddedNode); - ccbFileNode->setCCBFileNode(NULL); + ccbFileNode->setCCBFileNode(nullptr); node = embeddedNode; } @@ -661,7 +627,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) { if(!_jsControlled) { - Object * target = NULL; + Object * target = nullptr; if(memberVarAssignmentType == TargetType::DOCUMENT_ROOT) { target = _actionManager->getRootNode(); @@ -671,19 +637,19 @@ Node * CCBReader::readNodeGraph(Node * pParent) target = this->_owner; } - if(target != NULL) + if(target != nullptr) { CCBMemberVariableAssigner * targetAsCCBMemberVariableAssigner = dynamic_cast(target); bool assigned = false; if (memberVarAssignmentType != TargetType::NONE) { - if(targetAsCCBMemberVariableAssigner != NULL) + if(targetAsCCBMemberVariableAssigner != nullptr) { assigned = targetAsCCBMemberVariableAssigner->onAssignCCBMemberVariable(target, memberVarAssignmentName.c_str(), node); } - if(!assigned && this->_CCBMemberVariableAssigner != NULL) + if(!assigned && this->_CCBMemberVariableAssigner != nullptr) { assigned = this->_CCBMemberVariableAssigner->onAssignCCBMemberVariable(target, memberVarAssignmentName.c_str(), node); } @@ -700,7 +666,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) else { _ownerOutletNames.push_back(memberVarAssignmentName); - _ownerOutletNodes->addObject(node); + _ownerOutletNodes.pushBack(node); } } } @@ -713,10 +679,10 @@ Node * CCBReader::readNodeGraph(Node * pParent) if(!_jsControlled) { Object * target = node; - if(target != NULL) + if(target != nullptr) { CCBMemberVariableAssigner * targetAsCCBMemberVariableAssigner = dynamic_cast(target); - if(targetAsCCBMemberVariableAssigner != NULL) + if(targetAsCCBMemberVariableAssigner != nullptr) { Dictionary* pCustomPropeties = ccNodeLoader->getCustomProperties(); DictElement* pElement; @@ -724,7 +690,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) { customAssigned = targetAsCCBMemberVariableAssigner->onAssignCCBCustomProperty(target, pElement->getStrKey(), static_cast(pElement->getObject())); - if(!customAssigned && this->_CCBMemberVariableAssigner != NULL) + if(!customAssigned && this->_CCBMemberVariableAssigner != nullptr) { customAssigned = this->_CCBMemberVariableAssigner->onAssignCCBCustomProperty(target, pElement->getStrKey(), static_cast(pElement->getObject())); } @@ -737,7 +703,7 @@ Node * CCBReader::readNodeGraph(Node * pParent) #endif // CCB_ENABLE_JAVASCRIPT delete _animatedProps; - _animatedProps = NULL; + _animatedProps = nullptr; /* Read and add children. */ int numChildren = this->readInt(false); @@ -754,11 +720,11 @@ Node * CCBReader::readNodeGraph(Node * pParent) { // Call onNodeLoaded NodeLoaderListener * nodeAsNodeLoaderListener = dynamic_cast(node); - if(nodeAsNodeLoaderListener != NULL) + if(nodeAsNodeLoaderListener != nullptr) { nodeAsNodeLoaderListener->onNodeLoaded(node, ccNodeLoader); } - else if(this->_nodeLoaderListener != NULL) + else if(this->_nodeLoaderListener != nullptr) { this->_nodeLoaderListener->onNodeLoaded(node, ccNodeLoader); } @@ -775,7 +741,7 @@ CCBKeyframe* CCBReader::readKeyframe(PropertyType type) CCBKeyframe::EasingType easingType = static_cast(readInt(false)); float easingOpt = 0; - Object *value = NULL; + Object *value = nullptr; if (easingType == CCBKeyframe::EasingType::CUBIC_IN || easingType == CCBKeyframe::EasingType::CUBIC_OUT @@ -818,7 +784,7 @@ CCBKeyframe* CCBReader::readKeyframe(PropertyType type) value = Array::create(CCBValue::create(a), CCBValue::create(b), - NULL); + nullptr); } else if (type == PropertyType::SPRITEFRAME) { @@ -889,7 +855,7 @@ bool CCBReader::readCallbackKeyframesForSeq(CCBSequence* seq) _actionManager->getKeyframeCallbacks()->addObject(String::createWithFormat("%d:%s",callbackType, callbackName.c_str())); } - channel->getKeyframes()->addObject(keyframe); + channel->getKeyframes().pushBack(keyframe); } seq->setCallbackChannel(channel); @@ -922,7 +888,7 @@ bool CCBReader::readSoundKeyframesForSeq(CCBSequence* seq) { CCBKeyframe* keyframe = new CCBKeyframe(); keyframe->setTime(time); keyframe->setValue(value); - channel->getKeyframes()->addObject(keyframe); + channel->getKeyframes().pushBack(keyframe); keyframe->release(); } @@ -933,7 +899,7 @@ bool CCBReader::readSoundKeyframesForSeq(CCBSequence* seq) { Node * CCBReader::readNodeGraph() { - return this->readNodeGraph(NULL); + return this->readNodeGraph(nullptr); } bool CCBReader::readSequences() @@ -1008,12 +974,12 @@ void CCBReader::addOwnerCallbackName(const std::string& name) void CCBReader::addOwnerCallbackNode(Node *node) { - _ownerCallbackNodes->addObject(node); + _ownerCallbackNodes.pushBack(node); } void CCBReader::addOwnerCallbackControlEvents(Control::EventType type) { - _ownerOwnerCallbackControlEvents->addObject(Integer::create((int)type)); + _ownerOwnerCallbackControlEvents.push_back(Value((int)type)); } void CCBReader::addDocumentCallbackName(const std::string& name) @@ -1031,50 +997,53 @@ void CCBReader::addDocumentCallbackControlEvents(Control::EventType eventType) _actionManager->addDocumentCallbackControlEvents(eventType); } -Array* CCBReader::getOwnerCallbackNames() +ValueVector CCBReader::getOwnerCallbackNames() { - Array* pRet = Array::createWithCapacity(_ownerCallbackNames.size()); + ValueVector ret; + ret.reserve(_ownerCallbackNames.size()); + std::vector::iterator it = _ownerCallbackNames.begin(); for (; it != _ownerCallbackNames.end(); ++it) { - pRet->addObject(String::create(*it)); + ret.push_back(Value(*it)); } - return pRet; + return std::move(ret); } -Array* CCBReader::getOwnerCallbackNodes() +Vector& CCBReader::getOwnerCallbackNodes() { return _ownerCallbackNodes; } -Array* CCBReader::getOwnerCallbackControlEvents() +ValueVector& CCBReader::getOwnerCallbackControlEvents() { return _ownerOwnerCallbackControlEvents; } -Array* CCBReader::getOwnerOutletNames() +ValueVector CCBReader::getOwnerOutletNames() { - Array* pRet = Array::createWithCapacity(_ownerOutletNames.size()); + ValueVector ret; + ret.reserve(_ownerOutletNames.size()); std::vector::iterator it = _ownerOutletNames.begin(); for (; it != _ownerOutletNames.end(); ++it) { - pRet->addObject(String::create(*it)); + ret.push_back(Value(*it)); } - return pRet; + return std::move(ret); } -Array* CCBReader::getOwnerOutletNodes() +Vector& CCBReader::getOwnerOutletNodes() { return _ownerOutletNodes; } -Array* CCBReader::getNodesWithAnimationManagers() +Vector& CCBReader::getNodesWithAnimationManagers() { return _nodesWithAnimationManagers; } -Array* CCBReader::getAnimationManagersForNodes() +Vector& CCBReader::getAnimationManagersForNodes() { return _animationManagersForNodes; } @@ -1086,10 +1055,10 @@ void CCBReader::addOwnerOutletName(std::string name) void CCBReader::addOwnerOutletNode(Node *node) { - if (NULL == node) + if (nullptr == node) return; - _ownerOutletNodes->addObject(node); + _ownerOutletNodes.pushBack(node); } /************************************************************************ diff --git a/cocos/editor-support/cocosbuilder/CCBReader.h b/cocos/editor-support/cocosbuilder/CCBReader.h index 211ea18de4..5e3c2a963a 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.h +++ b/cocos/editor-support/cocosbuilder/CCBReader.h @@ -282,24 +282,24 @@ public: bool readCallbackKeyframesForSeq(CCBSequence* seq); bool readSoundKeyframesForSeq(CCBSequence* seq); - cocos2d::Array* getOwnerCallbackNames(); - cocos2d::Array* getOwnerCallbackNodes(); - cocos2d::Array* getOwnerCallbackControlEvents(); + cocos2d::ValueVector getOwnerCallbackNames(); + cocos2d::Vector& getOwnerCallbackNodes(); + cocos2d::ValueVector& getOwnerCallbackControlEvents(); - cocos2d::Array* getOwnerOutletNames(); - cocos2d::Array* getOwnerOutletNodes(); - cocos2d::Array* getNodesWithAnimationManagers(); - cocos2d::Array* getAnimationManagersForNodes(); + cocos2d::ValueVector getOwnerOutletNames(); + cocos2d::Vector& getOwnerOutletNodes(); + cocos2d::Vector& getNodesWithAnimationManagers(); + cocos2d::Vector& getAnimationManagersForNodes(); /** * @js NA * @lua NA */ - cocos2d::Dictionary* getAnimationManagers(); + cocos2d::Map& getAnimationManagers(); /** * @js NA * @lua NA */ - void setAnimationManagers(cocos2d::Dictionary* x); // weak reference + void setAnimationManagers(const cocos2d::Map& x); // weak reference /** * @js NA * @lua NA @@ -332,7 +332,7 @@ public: * @js NA * @lua NA */ - cocos2d::Node* readFileWithCleanUp(bool bCleanUp, cocos2d::Dictionary* am); + cocos2d::Node* readFileWithCleanUp(bool bCleanUp, const cocos2d::Map& am); void addOwnerOutletName(std::string name); void addOwnerOutletNode(cocos2d::Node *node); @@ -367,7 +367,7 @@ private: cocos2d::Object *_owner; CCBAnimationManager *_actionManager; //retain - cocos2d::Dictionary* _actionManagers; + cocos2d::Map _actionManagers; std::set *_animatedProps; @@ -377,13 +377,13 @@ private: CCBSelectorResolver *_CCBSelectorResolver; std::vector _ownerOutletNames; - cocos2d::Array* _ownerOutletNodes; - cocos2d::Array* _nodesWithAnimationManagers; - cocos2d::Array* _animationManagersForNodes; + cocos2d::Vector _ownerOutletNodes; + cocos2d::Vector _nodesWithAnimationManagers; + cocos2d::Vector _animationManagersForNodes; std::vector _ownerCallbackNames; - cocos2d::Array* _ownerCallbackNodes; - cocos2d::Array* _ownerOwnerCallbackControlEvents; + cocos2d::Vector _ownerCallbackNodes; + cocos2d::ValueVector _ownerOwnerCallbackControlEvents; std::string _CCBRootPath; bool _jsControlled; diff --git a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.cpp b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.cpp index a091adaad1..fa74e33881 100644 --- a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.cpp +++ b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.cpp @@ -14,15 +14,11 @@ CCBSequenceProperty::CCBSequenceProperty() bool CCBSequenceProperty::init() { - _keyframes = new Array(); - _keyframes->init(); - return true; } CCBSequenceProperty::~CCBSequenceProperty() { - CC_SAFE_RELEASE_NULL(_keyframes); } const char* CCBSequenceProperty::getName() @@ -45,7 +41,7 @@ void CCBSequenceProperty::setType(int type) _type = type; } -Array* CCBSequenceProperty::getKeyframes() +cocos2d::Vector& CCBSequenceProperty::getKeyframes() { return _keyframes; } diff --git a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h index cd097c2356..03ca04799f 100644 --- a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h +++ b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h @@ -27,12 +27,12 @@ public: int getType(); void setType(int type); - cocos2d::Array* getKeyframes(); + cocos2d::Vector& getKeyframes(); private: std::string _name; int _type; - cocos2d::Array *_keyframes; + cocos2d::Vector _keyframes; }; } diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp index bf4bd84106..742fa154c6 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp @@ -964,33 +964,31 @@ Node * NodeLoader::parsePropTypeCCBFile(Node * pNode, Node * pParent, CCBReader { //set variables and callback to owner //set callback - Array *ownerCallbackNames = reader->getOwnerCallbackNames(); - Array *ownerCallbackNodes = reader->getOwnerCallbackNodes(); - if (NULL != ownerCallbackNames && ownerCallbackNames->count() > 0 && - NULL != ownerCallbackNodes && ownerCallbackNodes->count() > 0) + auto ownerCallbackNames = reader->getOwnerCallbackNames(); + auto& ownerCallbackNodes = reader->getOwnerCallbackNodes(); + if (!ownerCallbackNames.empty() && !ownerCallbackNodes.empty()) { - CCASSERT(ownerCallbackNames->count() == ownerCallbackNodes->count(), ""); - int nCount = ownerCallbackNames->count(); + CCASSERT(ownerCallbackNames.size() == ownerCallbackNodes.size(), ""); + int nCount = ownerCallbackNames.size(); for (int i = 0 ; i < nCount; i++) { - pCCBReader->addOwnerCallbackName((dynamic_cast(ownerCallbackNames->getObjectAtIndex(i)))->getCString()); - pCCBReader->addOwnerCallbackNode(dynamic_cast(ownerCallbackNodes->getObjectAtIndex(i)) ); + pCCBReader->addOwnerCallbackName(ownerCallbackNames[i].asString()); + pCCBReader->addOwnerCallbackNode(ownerCallbackNodes.at(i)); } } //set variables - Array *ownerOutletNames = reader->getOwnerOutletNames(); - Array *ownerOutletNodes = reader->getOwnerOutletNodes(); - if (NULL != ownerOutletNames && ownerOutletNames->count() > 0 && - NULL != ownerOutletNodes && ownerOutletNodes->count() > 0) + auto ownerOutletNames = reader->getOwnerOutletNames(); + auto ownerOutletNodes = reader->getOwnerOutletNodes(); + if (!ownerOutletNames.empty() && !ownerOutletNodes.empty()) { - CCASSERT(ownerOutletNames->count() == ownerOutletNodes->count(), ""); - int nCount = ownerOutletNames->count(); + CCASSERT(ownerOutletNames.size() == ownerOutletNodes.size(), ""); + int nCount = ownerOutletNames.size(); for (int i = 0 ; i < nCount; i++) { - pCCBReader->addOwnerOutletName((static_cast(ownerOutletNames->getObjectAtIndex(i)))->getCString()); - pCCBReader->addOwnerOutletNode(static_cast(ownerOutletNodes->getObjectAtIndex(i))); + pCCBReader->addOwnerOutletName(ownerOutletNames.at(i).asString()); + pCCBReader->addOwnerOutletNode(ownerOutletNodes.at(i)); } } } From 13111c2cd971a7881686cd3283f7cd1e814d80cd Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 9 Dec 2013 09:54:04 +0800 Subject: [PATCH 24/27] issue #2790: Error fix in CCBReader. --- cocos/editor-support/cocosbuilder/CCBReader.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index 5f0cd809ee..2ab5ca1c79 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -245,6 +245,7 @@ Node* CCBReader::readNodeGraphFromData(Data *pData, Object *pOwner, const Size & _actionManager->setRootContainerSize(parentSize); _actionManager->_owner = _owner; + Map animationManagers; Node *pNodeGraph = readFileWithCleanUp(true, animationManagers); if (pNodeGraph && _actionManager->getAutoPlaySequenceId() != -1) From a2e90f1fca70bda19c791d2b207e9cc4b9cb1f8a Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 9 Dec 2013 10:54:22 +0800 Subject: [PATCH 25/27] issue #2790: Small fixes for physics, uses reference and std::move. --- cocos/physics/CCPhysicsBody.h | 2 +- cocos/physics/CCPhysicsWorld.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 58145b75d2..8d31d82e61 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -100,7 +100,7 @@ public: /* remove all shapes */ void removeAllShapes(bool reduceMassAndMoment = true); /* get the body shapes. */ - inline const Vector getShapes() const { return _shapes; } + inline const Vector& getShapes() const { return _shapes; } /* get the first shape of the body shapes. */ inline PhysicsShape* getFirstShape() const { return _shapes.size() >= 1 ? _shapes.at(0) : nullptr; } /* get the shape of the body. */ diff --git a/cocos/physics/CCPhysicsWorld.cpp b/cocos/physics/CCPhysicsWorld.cpp index 4d3f5066ac..da07a5590b 100644 --- a/cocos/physics/CCPhysicsWorld.cpp +++ b/cocos/physics/CCPhysicsWorld.cpp @@ -403,7 +403,7 @@ Vector PhysicsWorld::getShapes(const Point& point) const (cpSpaceNearestPointQueryFunc)PhysicsWorldCallback::getShapesAtPointFunc, &arr); - return arr; + return std::move(arr); } PhysicsShape* PhysicsWorld::getShape(const Point& point) const From b2e796613773e918718bba7442592e39c22d5196 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Mon, 9 Dec 2013 03:53:01 +0000 Subject: [PATCH 26/27] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index db718e871a..4001693a86 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit db718e871a7b59acdbefb679796c824d7a2b3ebf +Subproject commit 4001693a86e1887ab2a9036aa678ad3b14b2f1b2 From d0da73c365a49be7ccbed2aac85d843816178fa6 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 9 Dec 2013 14:00:10 +0800 Subject: [PATCH 27/27] Add _stencil is nil test, add warning log. --- cocos/2d/CCClippingNode.cpp | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/cocos/2d/CCClippingNode.cpp b/cocos/2d/CCClippingNode.cpp index 710eb3003f..f39131a4ac 100644 --- a/cocos/2d/CCClippingNode.cpp +++ b/cocos/2d/CCClippingNode.cpp @@ -91,10 +91,10 @@ bool ClippingNode::init() return init(NULL); } -bool ClippingNode::init(Node *pStencil) +bool ClippingNode::init(Node *stencil) { CC_SAFE_RELEASE(_stencil); - _stencil = pStencil; + _stencil = stencil; CC_SAFE_RETAIN(_stencil); _alphaThreshold = 1; @@ -117,24 +117,44 @@ bool ClippingNode::init(Node *pStencil) void ClippingNode::onEnter() { Node::onEnter(); - _stencil->onEnter(); + + if (_stencil != nullptr) + { + _stencil->onEnter(); + } + else + { + CCLOG("ClippingNode warning: _stencil is nil."); + } } void ClippingNode::onEnterTransitionDidFinish() { Node::onEnterTransitionDidFinish(); - _stencil->onEnterTransitionDidFinish(); + + if (_stencil != nullptr) + { + _stencil->onEnterTransitionDidFinish(); + } } void ClippingNode::onExitTransitionDidStart() { - _stencil->onExitTransitionDidStart(); + if (_stencil != nullptr) + { + _stencil->onExitTransitionDidStart(); + } + Node::onExitTransitionDidStart(); } void ClippingNode::onExit() { - _stencil->onExit(); + if (_stencil != nullptr) + { + _stencil->onExit(); + } + Node::onExit(); } @@ -321,7 +341,10 @@ void ClippingNode::visit() // (according to the stencil test func/op and alpha (or alpha shader) test) kmGLPushMatrix(); transform(); - _stencil->visit(); + if (_stencil != nullptr) + { + _stencil->visit(); + } kmGLPopMatrix(); // restore alpha test state