From 9203b60fb079f440cb48b06213605c56797002fb Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 19 Mar 2012 14:53:44 +0800 Subject: [PATCH 1/2] add CCDictionary based on UTHASH, improve the performance. --- cocos2dx/cocoa/CCDictionary.cpp | 226 +++++++++++++++++++++++ cocos2dx/include/CCDictionary.h | 90 +++++++++ cocos2dx/include/CCInteger.h | 18 ++ cocos2dx/proj.win32/cocos2d-win32.vcproj | 12 ++ 4 files changed, 346 insertions(+) create mode 100644 cocos2dx/cocoa/CCDictionary.cpp create mode 100644 cocos2dx/include/CCDictionary.h create mode 100644 cocos2dx/include/CCInteger.h diff --git a/cocos2dx/cocoa/CCDictionary.cpp b/cocos2dx/cocoa/CCDictionary.cpp new file mode 100644 index 0000000000..2b01052a5f --- /dev/null +++ b/cocos2dx/cocoa/CCDictionary.cpp @@ -0,0 +1,226 @@ +#include "CCDictionary.h" +#include "CCString.h" +#include "CCInteger.h" + +NS_CC_BEGIN + +CCDictionary2::CCDictionary2() +: m_pElements(NULL) +, m_eDictType(kCCDictUnknown) +, m_eOldDictType(kCCDictUnknown) +{ + +} + +CCDictionary2::~CCDictionary2() +{ + removeAllObjects(); +} + +unsigned int CCDictionary2::count() +{ + return HASH_COUNT(m_pElements); +} + +CCArray* CCDictionary2::allKeys() +{ + int iKeyCount = this->count(); + if (iKeyCount <= 0) return NULL; + CCArray* pArray = CCArray::arrayWithCapacity(iKeyCount); + + tDictElement *pElement, *tmp; + if (m_eDictType == kCCDictStr) + { + HASH_ITER(hh, m_pElements, pElement, tmp) + { + CCString* pOneKey = new CCString(pElement->szKey); + pOneKey->autorelease(); + pArray->addObject(pOneKey); + } + } + else if (m_eDictType == kCCDictInt) + { + HASH_ITER(hh, m_pElements, pElement, tmp) + { + CCInteger* pOneKey = new CCInteger(pElement->iKey); + pOneKey->autorelease(); + pArray->addObject(pOneKey); + } + } + + return pArray; +} + +CCArray* CCDictionary2::allKeysForObject(CCObject* object) +{ + int iKeyCount = this->count(); + if (iKeyCount <= 0) return NULL; + CCArray* pArray = CCArray::array(); + + tDictElement *pElement, *tmp; + + if (m_eDictType == kCCDictStr) + { + HASH_ITER(hh, m_pElements, pElement, tmp) + { + if (object == pElement->object) + { + CCString* pOneKey = new CCString(pElement->szKey); + pOneKey->autorelease(); + pArray->addObject(pOneKey); + } + } + } + else if (m_eDictType == kCCDictInt) + { + HASH_ITER(hh, m_pElements, pElement, tmp) + { + if (object == pElement->object) + { + CCInteger* pOneKey = new CCInteger(pElement->iKey); + pOneKey->autorelease(); + pArray->addObject(pOneKey); + } + } + } + return pArray; +} + +CCObject* CCDictionary2::objectForKey(const char* key) +{ + CCAssert(m_eDictType == kCCDictStr, "this dictionary does not use string as key."); + + CCObject* pRetObject = NULL; + tDictElement *pElement = NULL; + HASH_FIND_STR(m_pElements,key, pElement); + if (pElement != NULL) + { + pRetObject = pElement->object; + } + return pRetObject; +} + +CCObject* CCDictionary2::objectForKey(int key) +{ + CCAssert(m_eDictType == kCCDictInt, "this dictionary does not use integer as key."); + + CCObject* pRetObject = NULL; + tDictElement *pElement = NULL; + HASH_FIND_INT(m_pElements, &key, pElement); + if (pElement != NULL) + { + pRetObject = pElement->object; + } + return pRetObject; +} + +bool CCDictionary2::setObject(CCObject* pObject, const char* key) +{ + CCAssert(key != NULL && strlen(key) > 0 && pObject != NULL, "Invalid Argument!"); + if (m_eOldDictType == kCCDictUnknown) + { + m_eOldDictType = kCCDictStr; + } + m_eDictType = kCCDictStr; + CCAssert(m_eDictType == m_eOldDictType, "this dictionary does not use string as key."); + + bool bRet = false; + tDictElement *pElement = NULL; + HASH_FIND_STR(m_pElements, key, pElement); + if (pElement == NULL) + { + pElement = (tDictElement*)calloc(sizeof(*pElement), 1); + strcpy(pElement->szKey, key); + pObject->retain(); + pElement->object = pObject; + HASH_ADD_STR(m_pElements, szKey, pElement); + bRet = true; + } + else + { + pElement->object->retain(); + removeObjectForKey(key); + setObject(pObject, key); + pElement->object->release(); + bRet = true; + } + return bRet; +} + +bool CCDictionary2::setObject(CCObject* pObject, int key) +{ + CCAssert(pObject != NULL, "Invalid Argument!"); + if (m_eOldDictType == kCCDictUnknown) + { + m_eOldDictType = kCCDictInt; + } + m_eDictType = kCCDictInt; + CCAssert(m_eDictType == m_eOldDictType, "this dictionary does not use integer as key."); + + bool bRet = false; + tDictElement *pElement = NULL; + HASH_FIND_INT(m_pElements, &key, pElement); + if (pElement == NULL) + { + pElement = (tDictElement*)calloc(sizeof(*pElement), 1); + pElement->iKey = key; + pObject->retain(); + pElement->object = pObject; + HASH_ADD_INT(m_pElements, iKey, pElement); + bRet = true; + } + else + { + pElement->object->retain(); + removeObjectForKey(key); + setObject(pObject, key); + pElement->object->release(); + bRet = true; + } + return bRet; +} + +void CCDictionary2::removeObjectForKey(const char* key) +{ + CCAssert(m_eDictType == kCCDictStr, "this dictionary does not use string as its key"); + CCAssert(key != NULL && strlen(key) > 0, "Invalid Argument!"); + tDictElement *pElement = NULL; + HASH_FIND_STR(m_pElements, key, pElement); + if (pElement) + { + HASH_DEL(m_pElements, pElement); + pElement->object->release(); + free(pElement); + } +} + +void CCDictionary2::removeObjectForKey(int key) +{ + CCAssert(m_eDictType == kCCDictInt, "this dictionary does not use integer as its key"); + tDictElement *pElement = NULL; + HASH_FIND_INT(m_pElements, &key, pElement); + if (pElement != NULL) + { + HASH_DEL(m_pElements, pElement); + pElement->object->release(); + free(pElement); + } +} + +void CCDictionary2::removeAllObjects() +{ + tDictElement *pElement, *tmp; + HASH_ITER(hh, m_pElements, pElement, tmp) + { + HASH_DEL(m_pElements, pElement); + pElement->object->release(); + free(pElement); + } +} + +CCDictionary2* CCDictionary2::dictionaryWithDictionary(CCDictionary2* srcDict) +{ + return NULL; +} + +NS_CC_END diff --git a/cocos2dx/include/CCDictionary.h b/cocos2dx/include/CCDictionary.h new file mode 100644 index 0000000000..996011fc70 --- /dev/null +++ b/cocos2dx/include/CCDictionary.h @@ -0,0 +1,90 @@ +/**************************************************************************** +Copyright (c) 2010 cocos2d-x.org + +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 __CCDICTIONARY_H__ +#define __CCDICTIONARY_H__ + +#include "support/data_support/uthash.h" +#include "CCObject.h" +#include "CCArray.h" + +NS_CC_BEGIN + +typedef struct _dictElement +{ + char szKey[20]; /* hash key of string type*/ + int iKey; /* hash key of integer type */ + CCObject* object;/* hash value */ + UT_hash_handle hh; /* makes this class hashable */ +}tDictElement; + +#define CCDICT_FOREACH(__dict__, __object__) \ +for (tDictElement* pElement = __dict__->m_pElements; \ + pElement != NULL && (__object__ = pElement->object) != NULL; \ + pElement = (tDictElement*)pElement->hh.next) + +class CC_DLL CCDictionary2 : public CCObject +{ +public: + CCDictionary2(); + ~CCDictionary2(); + + /// return the number of items + unsigned int count(); + + /// return all the keys + CCArray* allKeys(); + + /** @warning : We use '==' to compare two objects*/ + CCArray* allKeysForObject(CCObject* object); + + CCObject* objectForKey(const char* key); + CCObject* objectForKey(int key); + + bool setObject(CCObject* pObject, const char* key); + bool setObject(CCObject* pObject, int key); + + void removeObjectForKey(const char* key); + void removeObjectForKey(int key); + + void removeAllObjects(); + + static CCDictionary2* dictionaryWithDictionary(CCDictionary2* srcDict); + +public: + tDictElement* m_pElements; +private: + enum CCDictType + { + kCCDictUnknown = 0, + kCCDictStr, + kCCDictInt + }; + CCDictType m_eDictType; + CCDictType m_eOldDictType; +}; + +NS_CC_END + +#endif /* __CCDICTIONARY_H__ */ diff --git a/cocos2dx/include/CCInteger.h b/cocos2dx/include/CCInteger.h new file mode 100644 index 0000000000..4add26bff5 --- /dev/null +++ b/cocos2dx/include/CCInteger.h @@ -0,0 +1,18 @@ +#ifndef __CCINTEGER_H__ +#define __CCINTEGER_H__ + +#include "CCObject.h" + +NS_CC_BEGIN + +class CC_DLL CCInteger : public CCObject +{ +public: + CCInteger(int v) + : value(v) {} + int value; +}; + +NS_CC_END + +#endif /* __CCINTEGER_H__ */ diff --git a/cocos2dx/proj.win32/cocos2d-win32.vcproj b/cocos2dx/proj.win32/cocos2d-win32.vcproj index 7bc0e29028..e8763e13f2 100644 --- a/cocos2dx/proj.win32/cocos2d-win32.vcproj +++ b/cocos2dx/proj.win32/cocos2d-win32.vcproj @@ -211,6 +211,10 @@ RelativePath="..\cocoa\CCData.cpp" > + + @@ -399,6 +403,10 @@ RelativePath="..\include\CCData.h" > + + @@ -435,6 +443,10 @@ RelativePath="..\include\CCIMEDispatcher.h" > + + From 6ce06bd906458f66f4794f5177dbc2808b2d220f Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 20 Mar 2012 15:04:53 +0800 Subject: [PATCH 2/2] issue #1056: Remove CCMutableArray and CCMutableDictionary template, offer CCDictionary to improve the performance of dictionary by 60%, it means that CCDictionary can save about 2/3 time cost. --- cocos2dx/CCDirector.cpp | 10 +- cocos2dx/CCScheduler.cpp | 2 +- cocos2dx/actions/CCActionInterval.cpp | 28 +- cocos2dx/actions/CCActionManager.cpp | 2 +- cocos2dx/cocoa/CCAutoreleasePool.cpp | 38 +- cocos2dx/cocoa/CCDictionary.cpp | 125 +- cocos2dx/extensions/CCNotificationCenter.cpp | 2 + cocos2dx/include/CCActionInterval.h | 7 +- cocos2dx/include/CCActionManager.h | 2 +- cocos2dx/include/CCAnimation.h | 22 +- cocos2dx/include/CCAnimationCache.h | 12 +- cocos2dx/include/CCArray.h | 35 +- cocos2dx/include/CCAutoreleasePool.h | 11 +- cocos2dx/include/CCDictionary.h | 80 +- cocos2dx/include/CCDirector.h | 4 +- cocos2dx/include/CCKeypadDispatcher.h | 6 +- cocos2dx/include/CCLayer.h | 4 +- cocos2dx/include/CCMenuItem.h | 4 +- cocos2dx/include/CCMutableArray.h | 363 ---- cocos2dx/include/CCMutableDictionary.h | 241 --- cocos2dx/include/CCParticleSystem.h | 12 +- cocos2dx/include/CCShaderCache.h | 4 +- cocos2dx/include/CCSprite.h | 2 +- cocos2dx/include/CCSpriteBatchNode.h | 2 +- cocos2dx/include/CCSpriteFrameCache.h | 12 +- cocos2dx/include/CCString.h | 5 + cocos2dx/include/CCTMXLayer.h | 2 +- cocos2dx/include/CCTMXObjectGroup.h | 10 +- cocos2dx/include/CCTMXTiledMap.h | 197 +- cocos2dx/include/CCTMXXMLParser.h | 318 ++-- cocos2dx/include/CCTextureCache.h | 4 +- cocos2dx/include/CCTexturePVR.h | 2 +- cocos2dx/include/CCTouchDispatcher.h | 14 +- cocos2dx/include/cocos2d.h | 4 +- .../keypad_dispatcher/CCKeypadDispatcher.cpp | 24 +- cocos2dx/label_nodes/CCLabelBMFont.cpp | 1649 +++++++++-------- .../CCLayer.cpp | 17 +- cocos2dx/menu_nodes/CCMenuItem.cpp | 1516 +++++++-------- cocos2dx/particle_nodes/CCParticleSystem.cpp | 4 +- cocos2dx/platform/CCFileUtils.cpp | 37 +- cocos2dx/platform/CCFileUtils.h | 6 +- cocos2dx/platform/CCSAXParser.cpp | 2 +- cocos2dx/proj.win32/cocos2d-win32.vcproj | 28 +- cocos2dx/{gles2 => shaders}/CCGLProgram.cpp | 0 cocos2dx/{gles2 => shaders}/CCShaderCache.cpp | 4 +- .../{gles2 => shaders}/ccGLStateCache.cpp | 0 cocos2dx/sprite_nodes/CCAnimation.cpp | 35 +- cocos2dx/sprite_nodes/CCAnimationCache.cpp | 93 +- cocos2dx/sprite_nodes/CCSprite.cpp | 2 +- cocos2dx/sprite_nodes/CCSpriteFrameCache.cpp | 117 +- cocos2dx/support/CCArray.cpp | 31 +- cocos2dx/support/CCProfiling.cpp | 14 +- cocos2dx/support/CCProfiling.h | 4 +- cocos2dx/support/data_support/ccCArray.h | 26 +- cocos2dx/support/data_support/uthash.h | 45 +- cocos2dx/textures/CCTextureCache.cpp | 60 +- .../tileMap_parallax_nodes/CCParallaxNode.cpp | 2 +- .../tileMap_parallax_nodes/CCTMXLayer.cpp | 11 +- .../CCTMXObjectGroup.cpp | 107 +- .../tileMap_parallax_nodes/CCTMXTiledMap.cpp | 47 +- .../tileMap_parallax_nodes/CCTMXXMLParser.cpp | 1143 ++++++------ .../touch_dispatcher/CCTouchDispatcher.cpp | 94 +- tests/tests/ActionsTest/ActionsTest.h | 1 + .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- tests/tests/SpriteTest/SpriteTest.h | 1 + tests/tests/TileMapTest/TileMapTest.cpp | 85 +- tests/tests/TouchesTest/TouchesTest.cpp | 20 +- tests/tests/TouchesTest/TouchesTest.h | 2 +- tests/tests/testBasic.h | 1 + 69 files changed, 3185 insertions(+), 3631 deletions(-) delete mode 100755 cocos2dx/include/CCMutableArray.h delete mode 100755 cocos2dx/include/CCMutableDictionary.h rename cocos2dx/{gles2 => shaders}/CCGLProgram.cpp (100%) rename cocos2dx/{gles2 => shaders}/CCShaderCache.cpp (97%) rename cocos2dx/{gles2 => shaders}/ccGLStateCache.cpp (100%) diff --git a/cocos2dx/CCDirector.cpp b/cocos2dx/CCDirector.cpp index cb187d7308..8ecb526a73 100644 --- a/cocos2dx/CCDirector.cpp +++ b/cocos2dx/CCDirector.cpp @@ -27,7 +27,7 @@ THE SOFTWARE. #include "cocoa/CCNS.h" #include "CCDirector.h" #include "CCScene.h" -#include "CCMutableArray.h" +#include "CCArray.h" #include "CCScheduler.h" #include "ccMacros.h" #include "CCTouchDispatcher.h" @@ -96,7 +96,8 @@ bool CCDirector::init(void) m_pNotificationNode = NULL; m_dOldAnimationInterval = m_dAnimationInterval = 1.0 / kDefaultFPS; - m_pobScenesStack = new CCMutableArray(); + m_pobScenesStack = CCArray::array(); + m_pobScenesStack->retain(); // Set default projection (3D) m_eProjection = kCCDirectorProjectionDefault; @@ -336,8 +337,9 @@ void CCDirector::setProjection(ccDirectorProjection kProjection) { // reset the viewport if 3d proj & retina display if( CC_CONTENT_SCALE_FACTOR() != 1 ) + { glViewport(-size.width/2, -size.height/2, size.width * CC_CONTENT_SCALE_FACTOR(), size.height * CC_CONTENT_SCALE_FACTOR() ); - + } float zeye = this->getZEye(); kmMat4 matrixPerspective, matrixLookup; @@ -563,7 +565,7 @@ void CCDirector::popScene(void) else { m_bSendCleanupToScene = true; - m_pNextScene = m_pobScenesStack->getObjectAtIndex(c - 1); + m_pNextScene = (CCScene*)m_pobScenesStack->objectAtIndex(c - 1); } } diff --git a/cocos2dx/CCScheduler.cpp b/cocos2dx/CCScheduler.cpp index e0f2d53a2c..a1c67e059c 100644 --- a/cocos2dx/CCScheduler.cpp +++ b/cocos2dx/CCScheduler.cpp @@ -326,7 +326,7 @@ void CCScheduler::unscheduleSelector(SEL_SCHEDULE pfnSelector, CCObject *pTarget pElement->currentTimerSalvaged = true; } - ccArrayRemoveObjectAtIndex(pElement->timers, i ); + ccArrayRemoveObjectAtIndex(pElement->timers, i, true); // update timerIndex in case we are in tick:, looping over the actions if (pElement->timerIndex >= i) diff --git a/cocos2dx/actions/CCActionInterval.cpp b/cocos2dx/actions/CCActionInterval.cpp index c614b77d54..866a15dc02 100644 --- a/cocos2dx/actions/CCActionInterval.cpp +++ b/cocos2dx/actions/CCActionInterval.cpp @@ -2055,10 +2055,13 @@ bool CCAnimate::initWithAnimation(CCAnimation *pAnimation) float accumUnitsOfTime = 0; float newUnitOfTimeValue = singleDuration / pAnimation->getTotalDelayUnits(); - CCMutableArray* pFrames = pAnimation->getFrames(); - for (CCMutableArray::CCMutableArrayIterator iterFrame = pFrames->begin(); iterFrame != pFrames->end(); ++iterFrame) + CCArray* pFrames = pAnimation->getFrames(); + CCARRAY_VERIFY_TYPE(pFrames, CCAnimationFrame*); + + CCObject* pObj = NULL; + CCARRAY_FOREACH(pFrames, pObj) { - CCAnimationFrame *frame = *iterFrame; + CCAnimationFrame* frame = (CCAnimationFrame*)pObj; float value = (accumUnitsOfTime * newUnitOfTimeValue) / singleDuration; accumUnitsOfTime += frame->getDelayUnits(); m_pSplitTimes->push_back(value); @@ -2151,7 +2154,7 @@ void CCAnimate::update(ccTime t) t = fmodf(t, 1.0f); } - CCMutableArray* frames = m_pAnimation->getFrames(); + CCArray* frames = m_pAnimation->getFrames(); unsigned int numberOfFrames = frames->count(); CCSpriteFrame *frameToDisplay = NULL; @@ -2159,11 +2162,11 @@ void CCAnimate::update(ccTime t) float splitTime = m_pSplitTimes->at(i); if( splitTime <= t ) { - CCAnimationFrame *frame = frames->getObjectAtIndex(i); + CCAnimationFrame* frame = (CCAnimationFrame*)frames->objectAtIndex(i); frameToDisplay = frame->getSpriteFrame(); ((CCSprite*)m_pTarget)->setDisplayFrame(frameToDisplay); - CCObjectDictionary* dict = frame->getUserInfo(); + CCDictionary* dict = frame->getUserInfo(); if( dict ) { //TODO: [[NSNotificationCenter defaultCenter] postNotificationName:CCAnimationFrameDisplayedNotification object:target_ userInfo:dict]; @@ -2177,16 +2180,17 @@ void CCAnimate::update(ccTime t) CCActionInterval* CCAnimate::reverse(void) { - CCMutableArray* pOldArray = m_pAnimation->getFrames(); - CCMutableArray* pNewArray = new CCMutableArray(pOldArray->count()); + CCArray* pOldArray = m_pAnimation->getFrames(); + CCArray* pNewArray = CCArray::arrayWithCapacity(pOldArray->count()); + CCARRAY_VERIFY_TYPE(pOldArray, CCAnimationFrame*); + if (pOldArray->count() > 0) { - CCAnimationFrame *pElement; - CCMutableArray::CCMutableArrayRevIterator iter; - for (iter = pOldArray->rbegin(); iter != pOldArray->rend(); iter++) + CCObject* pObj = NULL; + CCARRAY_FOREACH_REVERSE(pOldArray, pObj) { - pElement = *iter; + CCAnimationFrame* pElement = (CCAnimationFrame*)pObj; if (! pElement) { break; diff --git a/cocos2dx/actions/CCActionManager.cpp b/cocos2dx/actions/CCActionManager.cpp index f3a497632f..fe649de7ad 100644 --- a/cocos2dx/actions/CCActionManager.cpp +++ b/cocos2dx/actions/CCActionManager.cpp @@ -95,7 +95,7 @@ void CCActionManager::removeActionAtIndex(unsigned int uIndex, tHashElement *pEl pElement->currentActionSalvaged = true; } - ccArrayRemoveObjectAtIndex(pElement->actions, uIndex); + ccArrayRemoveObjectAtIndex(pElement->actions, uIndex, true); // update actionIndex in case we are in tick. looping over the actions if (pElement->actionIndex >= uIndex) diff --git a/cocos2dx/cocoa/CCAutoreleasePool.cpp b/cocos2dx/cocoa/CCAutoreleasePool.cpp index 1b09d47d61..c4a8501fcd 100644 --- a/cocos2dx/cocoa/CCAutoreleasePool.cpp +++ b/cocos2dx/cocoa/CCAutoreleasePool.cpp @@ -24,14 +24,14 @@ THE SOFTWARE. #include "CCAutoreleasePool.h" #include "ccMacros.h" -namespace cocos2d -{ +NS_CC_BEGIN CCPoolManager g_PoolManager; CCAutoreleasePool::CCAutoreleasePool(void) { - m_pManagedObjectArray = new CCMutableArray(); + m_pManagedObjectArray = new CCArray(); + m_pManagedObjectArray->init(); } CCAutoreleasePool::~CCAutoreleasePool(void) @@ -61,13 +61,14 @@ void CCAutoreleasePool::clear() #ifdef _DEBUG int nIndex = m_pManagedObjectArray->count() - 1; #endif - CCMutableArray::CCMutableArrayRevIterator it; - for(it = m_pManagedObjectArray->rbegin(); it != m_pManagedObjectArray->rend(); ++it) + + CCObject* pObj = NULL; + CCARRAY_FOREACH_REVERSE(m_pManagedObjectArray, pObj) { - if(!*it) + if(!pObj) break; - (*it)->m_bManaged = false; + pObj->m_bManaged = false; //(*it)->release(); //delete (*it); #ifdef _DEBUG @@ -93,8 +94,9 @@ CCPoolManager* CCPoolManager::getInstance() CCPoolManager::CCPoolManager() { - m_pReleasePoolStack = new CCMutableArray(); - m_pCurReleasePool = 0; + m_pReleasePoolStack = new CCArray(); + m_pReleasePoolStack->init(); + m_pCurReleasePool = 0; } CCPoolManager::~CCPoolManager() @@ -103,7 +105,7 @@ CCPoolManager::~CCPoolManager() finalize(); // we only release the last autorelease pool here - m_pCurReleasePool = 0; + m_pCurReleasePool = 0; m_pReleasePoolStack->removeObjectAtIndex(0); CC_SAFE_DELETE(m_pReleasePoolStack); @@ -114,13 +116,13 @@ void CCPoolManager::finalize() if(m_pReleasePoolStack->count() > 0) { //CCAutoreleasePool* pReleasePool; - CCMutableArray::CCMutableArrayIterator it; - for(it = m_pReleasePoolStack->begin(); it != m_pReleasePoolStack->end(); ++it) + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_pReleasePoolStack, pObj) { - if(!*it) + if(!pObj) break; - - (*it)->clear(); + CCAutoreleasePool* pPool = (CCAutoreleasePool*)pObj; + pPool->clear(); } } } @@ -152,10 +154,10 @@ void CCPoolManager::pop() // if(nCount > 1) // { -// m_pCurReleasePool = m_pReleasePoolStack->getObjectAtIndex(nCount - 2); +// m_pCurReleasePool = m_pReleasePoolStack->objectAtIndex(nCount - 2); // return; // } - m_pCurReleasePool = m_pReleasePoolStack->getObjectAtIndex(nCount - 2); + m_pCurReleasePool = (CCAutoreleasePool*)m_pReleasePoolStack->objectAtIndex(nCount - 2); } /*m_pCurReleasePool = NULL;*/ @@ -186,4 +188,4 @@ CCAutoreleasePool* CCPoolManager::getCurReleasePool() return m_pCurReleasePool; } -} +NS_CC_END diff --git a/cocos2dx/cocoa/CCDictionary.cpp b/cocos2dx/cocoa/CCDictionary.cpp index 2b01052a5f..12036a27d9 100644 --- a/cocos2dx/cocoa/CCDictionary.cpp +++ b/cocos2dx/cocoa/CCDictionary.cpp @@ -4,7 +4,7 @@ NS_CC_BEGIN -CCDictionary2::CCDictionary2() +CCDictionary::CCDictionary() : m_pElements(NULL) , m_eDictType(kCCDictUnknown) , m_eOldDictType(kCCDictUnknown) @@ -12,28 +12,28 @@ CCDictionary2::CCDictionary2() } -CCDictionary2::~CCDictionary2() +CCDictionary::~CCDictionary() { removeAllObjects(); } -unsigned int CCDictionary2::count() +unsigned int CCDictionary::count() { return HASH_COUNT(m_pElements); } -CCArray* CCDictionary2::allKeys() +CCArray* CCDictionary::allKeys() { int iKeyCount = this->count(); if (iKeyCount <= 0) return NULL; CCArray* pArray = CCArray::arrayWithCapacity(iKeyCount); - tDictElement *pElement, *tmp; + CCDictElement *pElement, *tmp; if (m_eDictType == kCCDictStr) { HASH_ITER(hh, m_pElements, pElement, tmp) { - CCString* pOneKey = new CCString(pElement->szKey); + CCString* pOneKey = new CCString(pElement->m_szKey); pOneKey->autorelease(); pArray->addObject(pOneKey); } @@ -42,7 +42,7 @@ CCArray* CCDictionary2::allKeys() { HASH_ITER(hh, m_pElements, pElement, tmp) { - CCInteger* pOneKey = new CCInteger(pElement->iKey); + CCInteger* pOneKey = new CCInteger(pElement->m_iKey); pOneKey->autorelease(); pArray->addObject(pOneKey); } @@ -51,21 +51,21 @@ CCArray* CCDictionary2::allKeys() return pArray; } -CCArray* CCDictionary2::allKeysForObject(CCObject* object) +CCArray* CCDictionary::allKeysForObject(CCObject* object) { int iKeyCount = this->count(); if (iKeyCount <= 0) return NULL; CCArray* pArray = CCArray::array(); - tDictElement *pElement, *tmp; + CCDictElement *pElement, *tmp; if (m_eDictType == kCCDictStr) { HASH_ITER(hh, m_pElements, pElement, tmp) { - if (object == pElement->object) + if (object == pElement->m_pObject) { - CCString* pOneKey = new CCString(pElement->szKey); + CCString* pOneKey = new CCString(pElement->m_szKey); pOneKey->autorelease(); pArray->addObject(pOneKey); } @@ -75,9 +75,9 @@ CCArray* CCDictionary2::allKeysForObject(CCObject* object) { HASH_ITER(hh, m_pElements, pElement, tmp) { - if (object == pElement->object) + if (object == pElement->m_pObject) { - CCInteger* pOneKey = new CCInteger(pElement->iKey); + CCInteger* pOneKey = new CCInteger(pElement->m_iKey); pOneKey->autorelease(); pArray->addObject(pOneKey); } @@ -86,35 +86,37 @@ CCArray* CCDictionary2::allKeysForObject(CCObject* object) return pArray; } -CCObject* CCDictionary2::objectForKey(const char* key) +CCObject* CCDictionary::objectForKey(const char* key) { + if (m_eDictType == kCCDictUnknown && m_eDictType == kCCDictUnknown) return NULL; CCAssert(m_eDictType == kCCDictStr, "this dictionary does not use string as key."); CCObject* pRetObject = NULL; - tDictElement *pElement = NULL; + CCDictElement *pElement = NULL; HASH_FIND_STR(m_pElements,key, pElement); if (pElement != NULL) { - pRetObject = pElement->object; + pRetObject = pElement->m_pObject; } return pRetObject; } -CCObject* CCDictionary2::objectForKey(int key) +CCObject* CCDictionary::objectForKey(int key) { + if (m_eDictType == kCCDictUnknown && m_eDictType == kCCDictUnknown) return NULL; CCAssert(m_eDictType == kCCDictInt, "this dictionary does not use integer as key."); CCObject* pRetObject = NULL; - tDictElement *pElement = NULL; + CCDictElement *pElement = NULL; HASH_FIND_INT(m_pElements, &key, pElement); if (pElement != NULL) { - pRetObject = pElement->object; + pRetObject = pElement->m_pObject; } return pRetObject; } -bool CCDictionary2::setObject(CCObject* pObject, const char* key) +bool CCDictionary::setObject(CCObject* pObject, const char* key) { CCAssert(key != NULL && strlen(key) > 0 && pObject != NULL, "Invalid Argument!"); if (m_eOldDictType == kCCDictUnknown) @@ -125,29 +127,28 @@ bool CCDictionary2::setObject(CCObject* pObject, const char* key) CCAssert(m_eDictType == m_eOldDictType, "this dictionary does not use string as key."); bool bRet = false; - tDictElement *pElement = NULL; + CCDictElement *pElement = NULL; HASH_FIND_STR(m_pElements, key, pElement); if (pElement == NULL) { - pElement = (tDictElement*)calloc(sizeof(*pElement), 1); - strcpy(pElement->szKey, key); pObject->retain(); - pElement->object = pObject; - HASH_ADD_STR(m_pElements, szKey, pElement); + pElement = new CCDictElement(key, pObject); + HASH_ADD_STR(m_pElements, m_szKey, pElement); bRet = true; } else { - pElement->object->retain(); + CCObject* pTmpObj = pElement->m_pObject; + pTmpObj->retain(); removeObjectForKey(key); setObject(pObject, key); - pElement->object->release(); + pTmpObj->release(); bRet = true; } return bRet; } -bool CCDictionary2::setObject(CCObject* pObject, int key) +bool CCDictionary::setObject(CCObject* pObject, int key) { CCAssert(pObject != NULL, "Invalid Argument!"); if (m_eOldDictType == kCCDictUnknown) @@ -158,69 +159,95 @@ bool CCDictionary2::setObject(CCObject* pObject, int key) CCAssert(m_eDictType == m_eOldDictType, "this dictionary does not use integer as key."); bool bRet = false; - tDictElement *pElement = NULL; + CCDictElement *pElement = NULL; HASH_FIND_INT(m_pElements, &key, pElement); if (pElement == NULL) { - pElement = (tDictElement*)calloc(sizeof(*pElement), 1); - pElement->iKey = key; pObject->retain(); - pElement->object = pObject; - HASH_ADD_INT(m_pElements, iKey, pElement); + pElement = new CCDictElement(key, pObject); + HASH_ADD_INT(m_pElements, m_iKey, pElement); bRet = true; } else { - pElement->object->retain(); + CCObject* pTmpObj = pElement->m_pObject; + pTmpObj->retain(); removeObjectForKey(key); setObject(pObject, key); - pElement->object->release(); + pTmpObj->release(); bRet = true; } return bRet; } -void CCDictionary2::removeObjectForKey(const char* key) +void CCDictionary::removeObjectForKey(const char* key) { CCAssert(m_eDictType == kCCDictStr, "this dictionary does not use string as its key"); CCAssert(key != NULL && strlen(key) > 0, "Invalid Argument!"); - tDictElement *pElement = NULL; + CCDictElement *pElement = NULL; HASH_FIND_STR(m_pElements, key, pElement); if (pElement) { HASH_DEL(m_pElements, pElement); - pElement->object->release(); - free(pElement); + pElement->m_pObject->release(); + CC_SAFE_DELETE(pElement); } } -void CCDictionary2::removeObjectForKey(int key) +void CCDictionary::removeObjectForKey(int key) { CCAssert(m_eDictType == kCCDictInt, "this dictionary does not use integer as its key"); - tDictElement *pElement = NULL; + CCDictElement *pElement = NULL; HASH_FIND_INT(m_pElements, &key, pElement); if (pElement != NULL) { HASH_DEL(m_pElements, pElement); - pElement->object->release(); - free(pElement); + pElement->m_pObject->release(); + CC_SAFE_DELETE(pElement); } } -void CCDictionary2::removeAllObjects() +void CCDictionary::removeAllObjects() { - tDictElement *pElement, *tmp; + CCDictElement *pElement, *tmp; HASH_ITER(hh, m_pElements, pElement, tmp) { HASH_DEL(m_pElements, pElement); - pElement->object->release(); - free(pElement); + pElement->m_pObject->release(); + CC_SAFE_DELETE(pElement); } } -CCDictionary2* CCDictionary2::dictionaryWithDictionary(CCDictionary2* srcDict) +CCObject* CCDictionary::copyWithZone(CCZone* pZone) { - return NULL; + CCDictionary* pNewDict = new CCDictionary(); + + CCDictElement* pElement = NULL; + if (m_eDictType == kCCDictInt) + { + CCDICT_FOREACH(this, pElement) + { + pNewDict->setObject(pElement->getObject(), pElement->getIntKey()); + } + } + else if (m_eDictType == kCCDictStr) + { + CCDICT_FOREACH(this, pElement) + { + pNewDict->setObject(pElement->getObject(), pElement->getStrKey()); + } + } + + return pNewDict; +} + +/* need deep copy ?*/ + +CCDictionary* CCDictionary::dictionaryWithDictionary(CCDictionary* srcDict) +{ + CCDictionary* pNewDict = (CCDictionary*)srcDict->copyWithZone(NULL); + pNewDict->autorelease(); + return pNewDict; } NS_CC_END diff --git a/cocos2dx/extensions/CCNotificationCenter.cpp b/cocos2dx/extensions/CCNotificationCenter.cpp index 861296e0fc..e6d4b47c9a 100644 --- a/cocos2dx/extensions/CCNotificationCenter.cpp +++ b/cocos2dx/extensions/CCNotificationCenter.cpp @@ -23,6 +23,8 @@ THE SOFTWARE. ****************************************************************************/ #include "CCNotificationCenter.h" +#include +using namespace std; NS_CC_BEGIN; diff --git a/cocos2dx/include/CCActionInterval.h b/cocos2dx/include/CCActionInterval.h index 559ae092b7..80d89f6a35 100755 --- a/cocos2dx/include/CCActionInterval.h +++ b/cocos2dx/include/CCActionInterval.h @@ -32,8 +32,9 @@ THE SOFTWARE. #include "CCProtocols.h" #include "CCSpriteFrame.h" #include "CCAnimation.h" +#include -namespace cocos2d { +NS_CC_BEGIN /** @brief An interval action is an action that takes place within a certain period of time. @@ -717,8 +718,6 @@ private: CCFiniteTimeAction* m_pAction; }; - - -} +NS_CC_END #endif //__ACTION_CCINTERVAL_ACTION_H__ diff --git a/cocos2dx/include/CCActionManager.h b/cocos2dx/include/CCActionManager.h index 0cd3d5d1fc..8258c155b9 100755 --- a/cocos2dx/include/CCActionManager.h +++ b/cocos2dx/include/CCActionManager.h @@ -29,7 +29,7 @@ THE SOFTWARE. #define __ACTION_CCACTION_MANAGER_H__ #include "CCAction.h" -#include "CCMutableArray.h" +#include "CCArray.h" #include "CCObject.h" namespace cocos2d { diff --git a/cocos2dx/include/CCAnimation.h b/cocos2dx/include/CCAnimation.h index 08b86dbe49..d7e54cef1d 100755 --- a/cocos2dx/include/CCAnimation.h +++ b/cocos2dx/include/CCAnimation.h @@ -28,8 +28,8 @@ THE SOFTWARE. #include "CCPlatformConfig.h" #include "CCObject.h" -#include "CCMutableArray.h" -#include "CCMutableDictionary.h" +#include "CCArray.h" +#include "CCDictionary.h" #include "CCGeometry.h" #include "CCSpriteFrame.h" #include @@ -54,7 +54,7 @@ public: virtual ~CCAnimationFrame(); virtual CCObject* copyWithZone(CCZone* pZone); /** initializes the animation frame with a spriteframe, number of delay units and a notification user info */ - bool initWithSpriteFrame(CCSpriteFrame* spriteFrame, float delayUnits, CCObjectDictionary* userInfo); + bool initWithSpriteFrame(CCSpriteFrame* spriteFrame, float delayUnits, CCDictionary* userInfo); /** CCSpriteFrameName to be used */ CC_SYNTHESIZE_RETAIN(CCSpriteFrame*, m_pSpriteFrame, SpriteFrame) @@ -63,7 +63,7 @@ public: CC_SYNTHESIZE(float, m_fDelayUnits, DelayUnits) /** A CCAnimationFrameDisplayedNotification notification will be broadcasted when the frame is displayed with this dictionary as UserInfo. If UserInfo is nil, then no notification will be broadcasted. */ - CC_SYNTHESIZE_RETAIN(CCObjectDictionary*, m_pUserInfo, UserInfo) + CC_SYNTHESIZE_RETAIN(CCDictionary*, m_pUserInfo, UserInfo) }; @@ -92,18 +92,18 @@ public: The frames will be created with one "delay unit". @since v0.99.5 */ - static CCAnimation* animationWithSpriteFrames(CCMutableArray *arrayOfSpriteFrameNames); + static CCAnimation* animationWithSpriteFrames(CCArray* arrayOfSpriteFrameNames); /* Creates an animation with an array of CCSpriteFrame and a delay between frames in seconds. The frames will be added with one "delay unit". @since v0.99.5 */ - static CCAnimation* animationWithSpriteFrames(CCMutableArray *arrayOfSpriteFrameNames, float delay); + static CCAnimation* animationWithSpriteFrames(CCArray* arrayOfSpriteFrameNames, float delay); /* Creates an animation with an array of CCAnimationFrame, the delay per units in seconds and and how many times it should be executed. @since v2.0 */ - static CCAnimation* animationWithAnimationFrames(CCMutableArray *arrayOfSpriteFrameNames, float delayPerUnit, unsigned int loops); + static CCAnimation* animationWithAnimationFrames(CCArray *arrayOfSpriteFrameNames, float delayPerUnit, unsigned int loops); /** Adds a CCSpriteFrame to a CCAnimation. The frame will be added with one "delay unit". @@ -126,17 +126,17 @@ public: /** Initializes a CCAnimation with frames. @since v0.99.5 */ - bool initWithSpriteFrames(CCMutableArray *pFrames); + bool initWithSpriteFrames(CCArray *pFrames); /** Initializes a CCAnimation with frames and a delay between frames @since v0.99.5 */ - bool initWithSpriteFrames(CCMutableArray *pFrames, float delay); + bool initWithSpriteFrames(CCArray *pFrames, float delay); /** Initializes a CCAnimation with CCAnimationFrame @since v2.0 */ - bool initWithAnimationFrames(CCMutableArray* arrayOfAnimationFrames, float delayPerUnit, unsigned int loops); + bool initWithAnimationFrames(CCArray* arrayOfAnimationFrames, float delayPerUnit, unsigned int loops); virtual CCObject* copyWithZone(CCZone* pZone); @@ -150,7 +150,7 @@ public: CC_PROPERTY_READONLY(float, m_fDuration, Duration) /** array of CCAnimationFrames */ - CC_SYNTHESIZE_RETAIN(CCMutableArray*, m_pFrames, Frames) + CC_SYNTHESIZE_RETAIN(CCArray*, m_pFrames, Frames) /** whether or not it shall restore the original frame when the animation finishes */ CC_SYNTHESIZE(bool, m_bRestoreOriginalFrame, RestoreOriginalFrame) diff --git a/cocos2dx/include/CCAnimationCache.h b/cocos2dx/include/CCAnimationCache.h index b5ff3de167..5aa0b1891f 100755 --- a/cocos2dx/include/CCAnimationCache.h +++ b/cocos2dx/include/CCAnimationCache.h @@ -27,7 +27,7 @@ THE SOFTWARE. #define __CC_ANIMATION_CACHE_H__ #include "CCObject.h" -#include "CCMutableDictionary.h" +#include "CCDictionary.h" #include @@ -72,7 +72,7 @@ public: Make sure that the frames were previously loaded in the CCSpriteFrameCache. @since v1.1 */ - void addAnimationsWithDictionary(CCObjectDictionary* dictionary); + void addAnimationsWithDictionary(CCDictionary* dictionary); /** Adds an animation from a plist file. Make sure that the frames were previously loaded in the CCSpriteFrameCache. @@ -83,11 +83,11 @@ public: bool init(void); private: - void parseVersion1(CCObjectDictionary* animations); - void parseVersion2(CCObjectDictionary* animations); - const char * valueForKey(const char *key, CCObjectDictionary* dict); + void parseVersion1(CCDictionary* animations); + void parseVersion2(CCDictionary* animations); + const char * valueForKey(const char *key, CCDictionary* dict); private: - CCMutableDictionary* m_pAnimations; + CCDictionary* m_pAnimations; static CCAnimationCache* s_pSharedAnimationCache; }; diff --git a/cocos2dx/include/CCArray.h b/cocos2dx/include/CCArray.h index 0ba25bc256..11cb12b9be 100755 --- a/cocos2dx/include/CCArray.h +++ b/cocos2dx/include/CCArray.h @@ -49,8 +49,25 @@ I found that it's not work in C++. So it keep what it's look like in version 1.0 arr <= end && ((__object__ = *arr) != NULL/* || true*/); \ arr++) -namespace cocos2d -{ +#define CCARRAY_FOREACH_REVERSE(__array__, __object__) \ + if (__array__ && __array__->data->num > 0) \ + for(CCObject** arr = __array__->data->arr + __array__->data->num-1, **end = __array__->data->arr; \ + arr >= end && ((__object__ = *arr) != NULL/* || true*/); \ + arr--) + +#if defined(COCOS2D_DEBUG) && (COCOS2D_DEBUG > 0) +#define CCARRAY_VERIFY_TYPE(__array__, __type__) \ + do { \ + if (__array__ && __array__->data->num > 0) \ + for(CCObject** arr = __array__->data->arr, **end = __array__->data->arr + __array__->data->num-1; arr <= end; arr++) \ + CCAssert(dynamic_cast<__type__>(*arr), "element type is wrong!"); \ + } while(false) +#else +#define CCARRAY_VERIFY_TYPE(__array__, __type__) void(0) +#endif + + +NS_CC_BEGIN class CC_DLL CCArray : public CCObject { @@ -99,11 +116,11 @@ public: // Removing Objects /** Remove last object */ - void removeLastObject(); + void removeLastObject(bool bReleaseObj = true); /** Remove a certain object */ - void removeObject(CCObject* object); + void removeObject(CCObject* object, bool bReleaseObj = true); /** Remove an element with a certain index */ - void removeObjectAtIndex(unsigned int index); + void removeObjectAtIndex(unsigned int index, bool bReleaseObj = true); /** Remove all elements */ void removeObjectsInArray(CCArray* otherArray); /** Remove all objects */ @@ -124,13 +141,15 @@ public: /* Shrinks the array so the memory footprint corresponds with the number of items */ void reduceMemoryFootprint(); + void replaceObjectAtIndex(unsigned int uIndex, CCObject* pObject, bool bReleaseObject = true); + + /** TODO: deep copy array. */ + virtual CCObject* copyWithZone(CCZone* pZone) {CCAssert(false, "");return NULL;} public: ccArray* data; - -private: CCArray() : data(NULL) {}; }; -} +NS_CC_END #endif // __CCARRAY_H__ diff --git a/cocos2dx/include/CCAutoreleasePool.h b/cocos2dx/include/CCAutoreleasePool.h index feee2ee01e..69acb33529 100755 --- a/cocos2dx/include/CCAutoreleasePool.h +++ b/cocos2dx/include/CCAutoreleasePool.h @@ -25,12 +25,13 @@ THE SOFTWARE. #define __AUTORELEASEPOOL_H__ #include "CCObject.h" -#include "CCMutableArray.h" +#include "CCArray.h" + +NS_CC_BEGIN -namespace cocos2d { class CC_DLL CCAutoreleasePool : public CCObject { - CCMutableArray* m_pManagedObjectArray; + CCArray* m_pManagedObjectArray; public: CCAutoreleasePool(void); ~CCAutoreleasePool(void); @@ -43,7 +44,7 @@ public: class CC_DLL CCPoolManager { - CCMutableArray* m_pReleasePoolStack; + CCArray* m_pReleasePoolStack; CCAutoreleasePool* m_pCurReleasePool; CCAutoreleasePool* getCurReleasePool(); @@ -62,6 +63,6 @@ public: friend class CCAutoreleasePool; }; -} +NS_CC_END #endif //__AUTORELEASEPOOL_H__ diff --git a/cocos2dx/include/CCDictionary.h b/cocos2dx/include/CCDictionary.h index 996011fc70..eeb20d76c1 100644 --- a/cocos2dx/include/CCDictionary.h +++ b/cocos2dx/include/CCDictionary.h @@ -31,24 +31,73 @@ THE SOFTWARE. NS_CC_BEGIN -typedef struct _dictElement +class CCDictionary; + +class CC_DLL CCDictElement { - char szKey[20]; /* hash key of string type*/ - int iKey; /* hash key of integer type */ - CCObject* object;/* hash value */ - UT_hash_handle hh; /* makes this class hashable */ -}tDictElement; +public: + CCDictElement(const char* pszKey, CCObject* pObject) + { + init(); + strncpy(m_szKey, pszKey, sizeof(m_szKey)); + m_pObject = pObject; + } + + CCDictElement(int iKey, CCObject* pObject) + { + init(); + m_iKey = iKey; + m_pObject = pObject; + } + + inline const char* getStrKey() const + { + return m_szKey; + } + + inline int getIntKey() const + { + return m_iKey; + } + + inline CCObject* getObject() const + { + return m_pObject; + } + +private: + inline void init() + { + m_iKey = 0; + m_pObject = NULL; + memset(m_szKey, 0, sizeof(m_szKey)); + memset(&hh, 0, sizeof(hh)); + } + +private: + char m_szKey[256]; /* hash key of string type*/ + int m_iKey; /* hash key of integer type */ + CCObject* m_pObject;/* hash value */ +public: + UT_hash_handle hh; /* makes this class hashable */ + friend class CCDictionary; +}; -#define CCDICT_FOREACH(__dict__, __object__) \ -for (tDictElement* pElement = __dict__->m_pElements; \ - pElement != NULL && (__object__ = pElement->object) != NULL; \ - pElement = (tDictElement*)pElement->hh.next) -class CC_DLL CCDictionary2 : public CCObject +// #define CCDICT_FOREACH(__dict__, pElement) \ +// for (pElement = __dict__->m_pElements; pElement != NULL; \ +// pElement = (CCDictElement*)pElement->hh.next) + +#define CCDICT_FOREACH(__dict__, __el__) \ + CCDictElement* ##__dict__##__el__##tmp = NULL; \ + HASH_ITER(hh, (__dict__)->m_pElements, __el__, ##__dict__##__el__##tmp) + + +class CC_DLL CCDictionary : public CCObject { public: - CCDictionary2(); - ~CCDictionary2(); + CCDictionary(); + ~CCDictionary(); /// return the number of items unsigned int count(); @@ -70,10 +119,11 @@ public: void removeAllObjects(); - static CCDictionary2* dictionaryWithDictionary(CCDictionary2* srcDict); + virtual CCObject* copyWithZone(CCZone* pZone); + static CCDictionary* dictionaryWithDictionary(CCDictionary* srcDict); public: - tDictElement* m_pElements; + CCDictElement* m_pElements; private: enum CCDictType { diff --git a/cocos2dx/include/CCDirector.h b/cocos2dx/include/CCDirector.h index 759c91484f..d6205e969b 100755 --- a/cocos2dx/include/CCDirector.h +++ b/cocos2dx/include/CCDirector.h @@ -31,7 +31,7 @@ THE SOFTWARE. #include "CCObject.h" #include "ccTypes.h" #include "CCGeometry.h" -#include "CCMutableArray.h" +#include "CCArray.h" #include "CCGeometry.h" #include "CCEGLView.h" #include "CCGL.h" @@ -448,7 +448,7 @@ protected: bool m_bSendCleanupToScene; /* scheduled scenes */ - CCMutableArray *m_pobScenesStack; + CCArray* m_pobScenesStack; /* last time the main loop was updated */ struct cc_timeval *m_pLastUpdate; diff --git a/cocos2dx/include/CCKeypadDispatcher.h b/cocos2dx/include/CCKeypadDispatcher.h index 04c01bb685..6c79cb753c 100755 --- a/cocos2dx/include/CCKeypadDispatcher.h +++ b/cocos2dx/include/CCKeypadDispatcher.h @@ -26,7 +26,7 @@ THE SOFTWARE. #define __CCKEYPAD_DISPATCHER_H__ #include "CCKeypadDelegate.h" -#include "CCMutableArray.h" +#include "CCArray.h" namespace cocos2d { @@ -84,9 +84,7 @@ public: protected: - typedef CCMutableArray KeypadDelegateArray; - - KeypadDelegateArray* m_pDelegates; + CCArray* m_pDelegates; bool m_bLocked; bool m_bToAdd; bool m_bToRemove; diff --git a/cocos2dx/include/CCLayer.h b/cocos2dx/include/CCLayer.h index 02d326d624..f1312a636f 100755 --- a/cocos2dx/include/CCLayer.h +++ b/cocos2dx/include/CCLayer.h @@ -32,7 +32,7 @@ THE SOFTWARE. #include "CCTouchDelegateProtocol.h" #include "CCAccelerometerDelegate.h" #include "CCKeypadDelegate.h" -#include "CCMutableArray.h" +#include "CCArray.h" namespace cocos2d { @@ -272,7 +272,7 @@ class CC_DLL CCLayerMultiplex : public CCLayer { protected: unsigned int m_nEnabledLayer; - CCMutableArray * m_pLayers; + CCArray* m_pLayers; public: CCLayerMultiplex(); diff --git a/cocos2dx/include/CCMenuItem.h b/cocos2dx/include/CCMenuItem.h index cb8c00c0ba..ee52a5e45f 100755 --- a/cocos2dx/include/CCMenuItem.h +++ b/cocos2dx/include/CCMenuItem.h @@ -29,7 +29,7 @@ THE SOFTWARE. #include "CCNode.h" #include "CCProtocols.h" -#include "CCMutableArray.h" +#include "CCArray.h" namespace cocos2d{ @@ -287,7 +287,7 @@ namespace cocos2d{ /** CCMutableArray that contains the subitems. You can add/remove items in runtime, and you can replace the array with a new one. @since v0.7.2 */ - CC_PROPERTY(CCMutableArray*, m_pSubItems, SubItems); + CC_PROPERTY(CCArray*, m_pSubItems, SubItems); public: CCMenuItemToggle() : m_cOpacity(0) diff --git a/cocos2dx/include/CCMutableArray.h b/cocos2dx/include/CCMutableArray.h deleted file mode 100755 index a5f91b88dc..0000000000 --- a/cocos2dx/include/CCMutableArray.h +++ /dev/null @@ -1,363 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -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 __COCOA_CC_MUTABLE_ARRAY_H__ -#define __COCOA_CC_MUTABLE_ARRAY_H__ - -#include "CCObject.h" -#include "ccMacros.h" -#include -#include - -namespace cocos2d { - -// the element should be pointer of CCObject or it's sub class -template -class CCMutableArray : public CCObject -{ -public: - typedef std::vector CCObjectArray; - typedef typename CCObjectArray::iterator CCMutableArrayIterator; - typedef typename CCObjectArray::reverse_iterator CCMutableArrayRevIterator; - -public: - CCMutableArray(unsigned int uSize = 0) - { - if (uSize != 0) - m_array.reserve(uSize); - } - - virtual ~CCMutableArray(void) - { - removeAllObjects(); - } - - inline unsigned int count(void) - { - return (unsigned int)m_array.size(); - } - - bool containsObject(T pObject) - { - if (m_array.empty() || (! pObject)) - { - return false; - } - - bool bRet = false; - CCMutableArrayIterator iter; - for (iter = m_array.begin(); iter != m_array.end(); ++iter) - { - if (*iter == pObject) - { - bRet = true; - break; - } - } - - return bRet; - } - - T getLastObject(void) - { - CCMutableArrayRevIterator iter = rbegin(); - - if (iter != m_array.rend()) - return *iter; - - return 0; - } - - T getObjectAtIndex(unsigned int uIndex) - { - CCAssert(uIndex < count(), ""); - - if (uIndex >= count()) - { - return 0; - } - - return m_array[uIndex]; - } - - // Adding objects - void addObject(T pObject) - { - // make sure the pointer is not null - if (pObject == 0) - { - return; - } - - // add the refrence - pObject->retain(); - - m_array.push_back(pObject); - } - - void addObjectsFromArray(CCMutableArray *pArray) - { - if (pArray && pArray->count() > 0) - { - m_array.reserve(count() + pArray->count()); - CCMutableArrayIterator iter; - for (iter = pArray->begin(); iter != pArray->end(); ++iter) - { - if (*iter) - (*iter)->retain(); - m_array.push_back(*iter); - } - } - } - - void insertObjectAtIndex(T pObject, unsigned int uIndex) - { - CCAssert(uIndex <= count(), ""); - // make sure the object is not null - if (pObject == 0) - { - return; - } - - // add the reference of the object - pObject->retain(); - - // resize the capacity if the index out of it - if (uIndex >= m_array.capacity()) - { - m_array.reserve(uIndex + 1); - m_array.push_back(pObject); - } - else // insert the object - m_array.insert(m_array.begin() + uIndex, pObject); - } - - // Removing objects - void removeLastObject(bool bDeleteObject = true) - { - CCMutableArrayRevIterator it = m_array.rbegin(); - if (it != m_array.rend()) - { - if (bDeleteObject) - (*it)->release(); - m_array.pop_back(); - } - } - - void removeObject(T pObject, bool bDeleteObject = true) - { - if (m_array.empty() || (! pObject)) - { - return; - } - - CCMutableArrayIterator iter; - int i; - for (iter = m_array.begin(), i = 0; iter != m_array.end(); ++iter, ++i) - { - if (*iter == pObject) - { - m_array.erase(iter); - - if (bDeleteObject) - { - pObject->release(); - } - - break; - } - } - } - - void removeObjectsInArray(CCMutableArray* pDeleteArray) - { - if(pDeleteArray && pDeleteArray->count()) - { - CCMutableArrayIterator it; - for( it = pDeleteArray->m_array.begin(); it != pDeleteArray->m_array.end(); ++it) - { - removeObject(*it); - } - } - } - - void removeObjectAtIndex(unsigned int uIndex, bool bDeleteObject = true) - { - if (m_array.empty()) - { - return; - } - - if (bDeleteObject) - { - T pObject = m_array.at(uIndex); - if (pObject) - { - pObject->release(); - } - } - - m_array.erase(m_array.begin() + uIndex); - } - - void removeAllObjects(bool bDeleteObject = true) - { - if (bDeleteObject) - { - CCMutableArrayIterator iter; - for (iter = m_array.begin(); iter != m_array.end(); ++iter) - (*iter)->release(); - } - - m_array.clear(); - } - - void replaceObjectAtIndex(unsigned int uIndex, T pObject, bool bDeleteObject = true) - { - if (bDeleteObject && m_array[uIndex]) - { - m_array[uIndex]->release(); - } - - m_array[uIndex] = pObject; - - // add the ref - if (pObject) - { - pObject->retain(); - } - } - - inline CCMutableArrayIterator begin(void) - { - return m_array.begin(); - } - - inline CCMutableArrayRevIterator rbegin(void) - { - return m_array.rbegin(); - } - - CCMutableArrayIterator getLastValidIterator(void) - { - CCMutableArrayIterator iter; - CCMutableArrayIterator ret; - for (iter = m_array.begin(); iter != m_array.end(); ++iter) - { - ret = iter; - if (! (*iter)) - { - break; - } - } - - return ret; - } - - /* - * end is a keyword of lua, so should use other name - * to export to lua - */ - inline CCMutableArrayIterator endToLua(void) - { - return m_array.end(); - } - - inline CCMutableArrayIterator end(void) - { - return m_array.end(); - } - - inline CCMutableArrayRevIterator rend(void) - { - return m_array.rend(); - } - - CCMutableArray* copy(void) - { - CCMutableArray* pArray = new CCMutableArray(); - - pArray->m_array.assign(m_array.begin(), m_array.end()); - - if(pArray->count() > 0) - { - CCMutableArrayIterator it; - for(it = pArray->begin(); it != pArray->end(); ++it) - { - if(*it) - { - (*it)->retain(); - } - } - } - - return pArray; - } - -public: - static CCMutableArray* arrayWithObjects(T pObject1, ...) - { - CCMutableArray *pArray = new CCMutableArray(); - pArray->autorelease(); - - va_list params; - va_start(params, pObject1); - - T pFirst = pObject1; - while (pFirst) - { - pArray->addObject(pFirst); - pFirst = va_arg(params, T); - } - - va_end(params); - - return pArray; - } - - static CCMutableArray* arrayWithArray(CCMutableArray *pSrcArray) - { - CCMutableArray *pDestArray = 0; - - if (pSrcArray == 0) - { - pDestArray = new CCMutableArray(); - } - else - { - pDestArray = pSrcArray->copy(); - } - - pDestArray->autorelease(); - - return pDestArray; - } - -private: - std::vector m_array; -}; - -}//namespace cocos2d - -#endif // __COCOA_CC_MUTABLE_ARRAY_H__ diff --git a/cocos2dx/include/CCMutableDictionary.h b/cocos2dx/include/CCMutableDictionary.h deleted file mode 100755 index 748cbb6cb5..0000000000 --- a/cocos2dx/include/CCMutableDictionary.h +++ /dev/null @@ -1,241 +0,0 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -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 __CCMUTABLE_DICTIONARY_H__ -#define __CCMUTABLE_DICTIONARY_H__ - -#include -#include -#include -#include "CCObject.h" -#include "CCMutableArray.h" -#include "ccMacros.h" - -using namespace std; -namespace cocos2d { -class CCString; - -template -class CCMutableDictionary : public CCObject -{ -public: - typedef std::map<_KeyT, _ValueT> CCObjectMap; - typedef typename CCObjectMap::iterator CCObjectMapIter; - -protected: - typedef pair<_KeyT, _ValueT> Int_Pair; - CCObjectMap m_Map; - bool m_bBegin; - CCObjectMapIter m_MapIter; - -public: - CCMutableDictionary(void) - { - m_bBegin = false; - } - - ~CCMutableDictionary(void) - { - removeAllObjects(); - } - - /// return the number of items - unsigned int count() - { - return m_Map.size(); - } - - /// return all the keys - std::vector<_KeyT> allKeys() - { - std::vector<_KeyT> tRet; - if (m_Map.size() > 0) - { - CCObjectMapIter it; - for( it = m_Map.begin(); it != m_Map.end(); ++it) - { - tRet.push_back(it->first); - } - } - return tRet; - } - - /** @warning : We use '==' to compare two objects*/ - std::vector<_KeyT> allKeysForObject(_ValueT object) - { - std::vector<_KeyT> tRet; - if (m_Map.size() > 0) - { - CCObjectMapIter it; - for( it= m_Map.begin(); it != m_Map.end(); ++it) - { - if (it->second == object) - { - tRet.push_back(it->first); - } - } - } - return tRet; - } - - _ValueT objectForKey(const _KeyT& key) ///< - { - CCObjectMapIter it; - - it = m_Map.find(key); - - if(it == m_Map.end()) //no match case - return NULL; - - return it->second; - } - - bool setObject(_ValueT pObject, const _KeyT& key) - { - pair pr; - - pr = m_Map.insert( Int_Pair(key, pObject) ); - - if(pr.second == true) - { - pObject->retain(); - return true; - } - - return false; - } - - void removeObjectForKey(const _KeyT& key) - { - CCObjectMapIter it; - - it = m_Map.find(key); - - if(it == m_Map.end()) //no match case - return; - - if(it->second ) - { - it->second->release() ; - m_Map.erase(it); - } - } - - bool begin() - { - if(m_Map.size() == 0) - return false; - - m_MapIter = m_Map.begin(); - m_bBegin = true; - - return true; - } - - _ValueT next(_KeyT* key = NULL) - { - if(!m_bBegin) - return NULL; - - _ValueT pObject = m_MapIter->second; - - if(m_MapIter == m_Map.end()) - { - m_bBegin = false; - } - else - { - if(key) - { - *key = m_MapIter->first; - } - - ++m_MapIter; - - if(m_MapIter == m_Map.end()) - { - m_bBegin = false; - } - } - - return pObject; - } - - /* - * end is a keyword of lua, so should use other name - * to export to lua - */ - void endToLua() - { - end(); - } - - void end() - { - m_bBegin = false; - } - - void removeAllObjects() - { - if (m_Map.size() > 0) - { - CCObjectMapIter it; - for( it = m_Map.begin(); it != m_Map.end(); ++it) - { - if (it->second) - { - it->second->release(); - } - } - } - m_Map.clear(); - } - - static CCMutableDictionary<_KeyT, _ValueT>* dictionaryWithDictionary(CCMutableDictionary<_KeyT, _ValueT>* srcDict) - { - CCMutableDictionary<_KeyT, _ValueT>* pNewDict = new CCMutableDictionary<_KeyT, _ValueT>(); - - srcDict->begin(); - - _KeyT key; - _ValueT value; - - while( (value = srcDict->next(&key)) ) - { - pNewDict->setObject(value, key); - } - - srcDict->end(); - - return pNewDict; - } -}; - -#define CCDictionary CCMutableDictionary -typedef CCDictionary CCStringToStringDictionary; -typedef CCDictionary CCObjectDictionary; - -}//namespace cocos2d - - -#endif //__CCMUTABLE_DICTIONARY_H__ \ No newline at end of file diff --git a/cocos2dx/include/CCParticleSystem.h b/cocos2dx/include/CCParticleSystem.h index ed73fe7426..3501c90a6b 100755 --- a/cocos2dx/include/CCParticleSystem.h +++ b/cocos2dx/include/CCParticleSystem.h @@ -28,10 +28,10 @@ THE SOFTWARE. #include "CCProtocols.h" #include "CCNode.h" -#include "CCMutableDictionary.h" +#include "CCDictionary.h" #include "CCString.h" -namespace cocos2d { +NS_CC_BEGIN class CCParticleBatchNode; @@ -370,7 +370,7 @@ public: /** initializes a CCQuadParticleSystem from a CCDictionary. @since v0.99.3 */ - bool initWithDictionary(CCDictionary *dictionary); + bool initWithDictionary(CCDictionary *dictionary); //! Initializes a system with a fixed number of particles virtual bool initWithTotalParticles(unsigned int numberOfParticles); @@ -396,17 +396,17 @@ private: /** Private method, return the string found by key in dict. @return "" if not found; return the string if found. */ - inline const char * valueForKey(const char *key, CCDictionary *dict) + inline const char * valueForKey(const char *key, CCDictionary *dict) { if (dict) { - CCString *pString = (CCString*)dict->objectForKey(std::string(key)); + CCString *pString = (CCString*)dict->objectForKey(key); return pString ? pString->m_sString.c_str() : ""; } return ""; } }; -}// namespace cocos2d +NS_CC_END #endif //__CCPARTICLE_SYSTEM_H__ diff --git a/cocos2dx/include/CCShaderCache.h b/cocos2dx/include/CCShaderCache.h index c0f1a80d38..fa24a4743f 100644 --- a/cocos2dx/include/CCShaderCache.h +++ b/cocos2dx/include/CCShaderCache.h @@ -27,7 +27,7 @@ THE SOFTWARE. #ifndef __CCSHADERCACHE_H__ #define __CCSHADERCACHE_H__ -#include "CCMutableDictionary.h" +#include "CCDictionary.h" NS_CC_BEGIN @@ -61,7 +61,7 @@ public: private: bool init(); - CCMutableDictionary* m_pPrograms; + CCDictionary* m_pPrograms; }; diff --git a/cocos2dx/include/CCSprite.h b/cocos2dx/include/CCSprite.h index c0ea305d80..e90bc778f1 100755 --- a/cocos2dx/include/CCSprite.h +++ b/cocos2dx/include/CCSprite.h @@ -31,7 +31,7 @@ THE SOFTWARE. #include "CCProtocols.h" #include "CCTextureAtlas.h" #include "ccTypes.h" -#include "CCMutableDictionary.h" +#include "CCDictionary.h" #include namespace cocos2d { diff --git a/cocos2dx/include/CCSpriteBatchNode.h b/cocos2dx/include/CCSpriteBatchNode.h index fbb9bf6988..938c564c04 100755 --- a/cocos2dx/include/CCSpriteBatchNode.h +++ b/cocos2dx/include/CCSpriteBatchNode.h @@ -32,7 +32,7 @@ THE SOFTWARE. #include "CCProtocols.h" #include "CCTextureAtlas.h" #include "ccMacros.h" -#include "CCMutableArray.h" +#include "CCArray.h" namespace cocos2d { diff --git a/cocos2dx/include/CCSpriteFrameCache.h b/cocos2dx/include/CCSpriteFrameCache.h index 9b29cc32d6..25487374d9 100755 --- a/cocos2dx/include/CCSpriteFrameCache.h +++ b/cocos2dx/include/CCSpriteFrameCache.h @@ -38,7 +38,7 @@ THE SOFTWARE. #include "CCSpriteFrame.h" #include "CCTexture2D.h" #include "CCObject.h" -#include "CCMutableDictionary.h" +#include "CCDictionary.h" namespace cocos2d { class CCSprite; @@ -55,7 +55,7 @@ public: /*Adds multiple Sprite Frames with a dictionary. The texture will be associated with the created sprite frames. */ - void addSpriteFramesWithDictionary(CCDictionary *pobDictionary, CCTexture2D *pobTexture); + void addSpriteFramesWithDictionary(CCDictionary* pobDictionary, CCTexture2D *pobTexture); /** Adds multiple Sprite Frames from a plist file. * A texture will be loaded automatically. The texture name will composed by replacing the .plist suffix with .png @@ -103,7 +103,7 @@ public: /** Removes multiple Sprite Frames from CCDictionary. * @since v0.99.5 */ - void removeSpriteFramesFromDictionary(CCDictionary *dictionary); + void removeSpriteFramesFromDictionary(CCDictionary* dictionary); /** Removes all Sprite Frames associated with the specified textures. * It is convinient to call this method when a specific texture needs to be removed. @@ -126,11 +126,11 @@ public: private: CCSpriteFrameCache(void) : m_pSpriteFrames(NULL), m_pSpriteFramesAliases(NULL){} - const char * valueForKey(const char *key, CCDictionary *dict); + const char * valueForKey(const char* key, CCDictionary* dict); protected: - CCDictionary *m_pSpriteFrames; - CCDictionary *m_pSpriteFramesAliases; + CCDictionary* m_pSpriteFrames; + CCDictionary* m_pSpriteFramesAliases; }; }//namespace cocos2d diff --git a/cocos2dx/include/CCString.h b/cocos2dx/include/CCString.h index 1478df2c4e..ee04d17f8e 100755 --- a/cocos2dx/include/CCString.h +++ b/cocos2dx/include/CCString.h @@ -61,6 +61,11 @@ namespace cocos2d { return m_sString; } + const char* c_str() + { + return m_sString.c_str(); + } + bool isEmpty() { return m_sString.empty(); diff --git a/cocos2dx/include/CCTMXLayer.h b/cocos2dx/include/CCTMXLayer.h index 1b69074c38..8d01aecf9f 100755 --- a/cocos2dx/include/CCTMXLayer.h +++ b/cocos2dx/include/CCTMXLayer.h @@ -79,7 +79,7 @@ class CC_DLL CCTMXLayer : public CCSpriteBatchNode /** Layer orientation, which is the same as the map orientation */ CC_SYNTHESIZE(unsigned int, m_uLayerOrientation, LayerOrientation); /** properties from the layer. They can be added using Tiled */ - CC_PROPERTY(CCStringToStringDictionary*, m_pProperties, Properties); + CC_PROPERTY(CCDictionary*, m_pProperties, Properties); public: CCTMXLayer(); virtual ~CCTMXLayer(); diff --git a/cocos2dx/include/CCTMXObjectGroup.h b/cocos2dx/include/CCTMXObjectGroup.h index 096bf7a9c9..3bac77de02 100755 --- a/cocos2dx/include/CCTMXObjectGroup.h +++ b/cocos2dx/include/CCTMXObjectGroup.h @@ -29,8 +29,8 @@ THE SOFTWARE. #include "CCGeometry.h" #include "CCString.h" -#include "CCMutableArray.h" -#include "CCMutableDictionary.h" +#include "CCArray.h" +#include "CCDictionary.h" namespace cocos2d { @@ -42,9 +42,9 @@ namespace cocos2d { /** offset position of child objects */ CC_SYNTHESIZE_PASS_BY_REF(CCPoint, m_tPositionOffset, PositionOffset); /** list of properties stored in a dictionary */ - CC_PROPERTY(CCStringToStringDictionary*, m_pProperties, Properties); + CC_PROPERTY(CCDictionary*, m_pProperties, Properties); /** array of the objects */ - CC_PROPERTY(CCMutableArray*, m_pObjects, Objects); + CC_PROPERTY(CCArray*, m_pObjects, Objects); public: CCTMXObjectGroup(); virtual ~CCTMXObjectGroup(); @@ -58,7 +58,7 @@ namespace cocos2d { /** return the dictionary for the specific object name. It will return the 1st object found on the array for the given name. */ - CCStringToStringDictionary *objectNamed(const char *objectName); + CCDictionary* objectNamed(const char *objectName); protected: /** name of the group */ std::string m_sGroupName; diff --git a/cocos2dx/include/CCTMXTiledMap.h b/cocos2dx/include/CCTMXTiledMap.h index 091b280baa..5875db5a49 100755 --- a/cocos2dx/include/CCTMXTiledMap.h +++ b/cocos2dx/include/CCTMXTiledMap.h @@ -28,129 +28,130 @@ THE SOFTWARE. #include "CCNode.h" #include "CCTMXObjectGroup.h" -namespace cocos2d { +NS_CC_BEGIN - class CCTMXObjectGroup; - class CCTMXLayer; - class CCTMXLayerInfo; - class CCTMXTilesetInfo; - class CCTMXMapInfo; +class CCTMXObjectGroup; +class CCTMXLayer; +class CCTMXLayerInfo; +class CCTMXTilesetInfo; +class CCTMXMapInfo; - /** Possible oritentations of the TMX map */ - enum - { - /** Orthogonal orientation */ - CCTMXOrientationOrtho, +/** Possible oritentations of the TMX map */ +enum +{ + /** Orthogonal orientation */ + CCTMXOrientationOrtho, - /** Hexagonal orientation */ - CCTMXOrientationHex, + /** Hexagonal orientation */ + CCTMXOrientationHex, - /** Isometric orientation */ - CCTMXOrientationIso, - }; + /** Isometric orientation */ + CCTMXOrientationIso, +}; - /** @brief CCTMXTiledMap knows how to parse and render a TMX map. +/** @brief CCTMXTiledMap knows how to parse and render a TMX map. - It adds support for the TMX tiled map format used by http://www.mapeditor.org - It supports isometric, hexagonal and orthogonal tiles. - It also supports object groups, objects, and properties. +It adds support for the TMX tiled map format used by http://www.mapeditor.org +It supports isometric, hexagonal and orthogonal tiles. +It also supports object groups, objects, and properties. - Features: - - Each tile will be treated as an CCSprite - - The sprites are created on demand. They will be created only when you call "layer->tileAt(position)" - - Each tile can be rotated / moved / scaled / tinted / "opacitied", since each tile is a CCSprite - - Tiles can be added/removed in runtime - - The z-order of the tiles can be modified in runtime - - Each tile has an anchorPoint of (0,0) - - The anchorPoint of the TMXTileMap is (0,0) - - The TMX layers will be added as a child - - The TMX layers will be aliased by default - - The tileset image will be loaded using the CCTextureCache - - Each tile will have a unique tag - - Each tile will have a unique z value. top-left: z=1, bottom-right: z=max z - - Each object group will be treated as an CCMutableArray - - Object class which will contain all the properties in a dictionary - - Properties can be assigned to the Map, Layer, Object Group, and Object +Features: +- Each tile will be treated as an CCSprite +- The sprites are created on demand. They will be created only when you call "layer->tileAt(position)" +- Each tile can be rotated / moved / scaled / tinted / "opacitied", since each tile is a CCSprite +- Tiles can be added/removed in runtime +- The z-order of the tiles can be modified in runtime +- Each tile has an anchorPoint of (0,0) +- The anchorPoint of the TMXTileMap is (0,0) +- The TMX layers will be added as a child +- The TMX layers will be aliased by default +- The tileset image will be loaded using the CCTextureCache +- Each tile will have a unique tag +- Each tile will have a unique z value. top-left: z=1, bottom-right: z=max z +- Each object group will be treated as an CCMutableArray +- Object class which will contain all the properties in a dictionary +- Properties can be assigned to the Map, Layer, Object Group, and Object - Limitations: - - It only supports one tileset per layer. - - Embeded images are not supported - - It only supports the XML format (the JSON format is not supported) +Limitations: +- It only supports one tileset per layer. +- Embeded images are not supported +- It only supports the XML format (the JSON format is not supported) - Technical description: - Each layer is created using an CCTMXLayer (subclass of CCSpriteBatchNode). If you have 5 layers, then 5 CCTMXLayer will be created, - unless the layer visibility is off. In that case, the layer won't be created at all. - You can obtain the layers (CCTMXLayer objects) at runtime by: - - map->getChildByTag(tag_number); // 0=1st layer, 1=2nd layer, 2=3rd layer, etc... - - map->layerNamed(name_of_the_layer); +Technical description: +Each layer is created using an CCTMXLayer (subclass of CCSpriteBatchNode). If you have 5 layers, then 5 CCTMXLayer will be created, +unless the layer visibility is off. In that case, the layer won't be created at all. +You can obtain the layers (CCTMXLayer objects) at runtime by: +- map->getChildByTag(tag_number); // 0=1st layer, 1=2nd layer, 2=3rd layer, etc... +- map->layerNamed(name_of_the_layer); - Each object group is created using a CCTMXObjectGroup which is a subclass of CCMutableArray. - You can obtain the object groups at runtime by: - - map->objectGroupNamed(name_of_the_object_group); +Each object group is created using a CCTMXObjectGroup which is a subclass of CCMutableArray. +You can obtain the object groups at runtime by: +- map->objectGroupNamed(name_of_the_object_group); - Each object is a CCTMXObject. +Each object is a CCTMXObject. - Each property is stored as a key-value pair in an CCMutableDictionary. - You can obtain the properties at runtime by: +Each property is stored as a key-value pair in an CCMutableDictionary. +You can obtain the properties at runtime by: - map->propertyNamed(name_of_the_property); - layer->propertyNamed(name_of_the_property); - objectGroup->propertyNamed(name_of_the_property); - object->propertyNamed(name_of_the_property); +map->propertyNamed(name_of_the_property); +layer->propertyNamed(name_of_the_property); +objectGroup->propertyNamed(name_of_the_property); +object->propertyNamed(name_of_the_property); - @since v0.8.1 - */ - class CC_DLL CCTMXTiledMap : public CCNode - { - /** the map's size property measured in tiles */ - CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tMapSize, MapSize); - /** the tiles's size property measured in pixels */ - CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tTileSize, TileSize); - /** map orientation */ - CC_SYNTHESIZE(int, m_nMapOrientation, MapOrientation); - /** object groups */ - CC_PROPERTY(CCMutableArray*, m_pObjectGroups, ObjectGroups); - /** properties */ - CC_PROPERTY(CCStringToStringDictionary*, m_pProperties, Properties); - public: - CCTMXTiledMap(); - virtual ~CCTMXTiledMap(); +@since v0.8.1 +*/ +class CC_DLL CCTMXTiledMap : public CCNode +{ + /** the map's size property measured in tiles */ + CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tMapSize, MapSize); + /** the tiles's size property measured in pixels */ + CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tTileSize, TileSize); + /** map orientation */ + CC_SYNTHESIZE(int, m_nMapOrientation, MapOrientation); + /** object groups */ + CC_PROPERTY(CCArray*, m_pObjectGroups, ObjectGroups); + /** properties */ + CC_PROPERTY(CCDictionary*, m_pProperties, Properties); +public: + CCTMXTiledMap(); + virtual ~CCTMXTiledMap(); - /** creates a TMX Tiled Map with a TMX file.*/ - static CCTMXTiledMap* tiledMapWithTMXFile(const char *tmxFile); + /** creates a TMX Tiled Map with a TMX file.*/ + static CCTMXTiledMap* tiledMapWithTMXFile(const char *tmxFile); - /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ - static CCTMXTiledMap* tiledMapWithXML(const char* tmxString, const char* resourcePath); + /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ + static CCTMXTiledMap* tiledMapWithXML(const char* tmxString, const char* resourcePath); - /** initializes a TMX Tiled Map with a TMX file */ - bool initWithTMXFile(const char *tmxFile); + /** initializes a TMX Tiled Map with a TMX file */ + bool initWithTMXFile(const char *tmxFile); - /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ - bool initWithXML(const char* tmxString, const char* resourcePath); + /** initializes a TMX Tiled Map with a TMX formatted XML string and a path to TMX resources */ + bool initWithXML(const char* tmxString, const char* resourcePath); - /** return the TMXLayer for the specific layer */ - CCTMXLayer* layerNamed(const char *layerName); + /** return the TMXLayer for the specific layer */ + CCTMXLayer* layerNamed(const char *layerName); - /** return the TMXObjectGroup for the secific group */ - CCTMXObjectGroup* objectGroupNamed(const char *groupName); + /** return the TMXObjectGroup for the secific group */ + CCTMXObjectGroup* objectGroupNamed(const char *groupName); - /** return the value for the specific property name */ - CCString *propertyNamed(const char *propertyName); + /** return the value for the specific property name */ + CCString *propertyNamed(const char *propertyName); - /** return properties dictionary for tile GID */ - CCDictionary *propertiesForGID(int GID); + /** return properties dictionary for tile GID */ + CCDictionary* propertiesForGID(int GID); - private: - CCTMXLayer * parseLayer(CCTMXLayerInfo *layerInfo, CCTMXMapInfo *mapInfo); - CCTMXTilesetInfo * tilesetForLayer(CCTMXLayerInfo *layerInfo, CCTMXMapInfo *mapInfo); - void buildWithMapInfo(CCTMXMapInfo* mapInfo); - protected: - //! tile properties - CCDictionary *m_pTileProperties; +private: + CCTMXLayer * parseLayer(CCTMXLayerInfo *layerInfo, CCTMXMapInfo *mapInfo); + CCTMXTilesetInfo * tilesetForLayer(CCTMXLayerInfo *layerInfo, CCTMXMapInfo *mapInfo); + void buildWithMapInfo(CCTMXMapInfo* mapInfo); +protected: + //! tile properties + CCDictionary* m_pTileProperties; - }; +}; + +NS_CC_END -}// namespace cocos2d #endif //__CCTMX_TILE_MAP_H__ diff --git a/cocos2dx/include/CCTMXXMLParser.h b/cocos2dx/include/CCTMXXMLParser.h index 331cbae957..2b1561d44c 100755 --- a/cocos2dx/include/CCTMXXMLParser.h +++ b/cocos2dx/include/CCTMXXMLParser.h @@ -27,186 +27,186 @@ THE SOFTWARE. #ifndef __CC_TM_XML_PARSER__ #define __CC_TM_XML_PARSER__ -#include "CCMutableArray.h" -#include "CCMutableDictionary.h" +#include "CCArray.h" +#include "CCDictionary.h" #include "CCGeometry.h" #include "../platform/CCSAXParser.h" -namespace cocos2d { +NS_CC_BEGIN - class CCTMXObjectGroup; +class CCTMXObjectGroup; - /** @file - * Internal TMX parser - * - * IMPORTANT: These classed should not be documented using doxygen strings - * since the user should not use them. - * - */ +/** @file +* Internal TMX parser +* +* IMPORTANT: These classed should not be documented using doxygen strings +* since the user should not use them. +* +*/ - enum { - TMXLayerAttribNone = 1 << 0, - TMXLayerAttribBase64 = 1 << 1, - TMXLayerAttribGzip = 1 << 2, - TMXLayerAttribZlib = 1 << 3, - }; +enum { + TMXLayerAttribNone = 1 << 0, + TMXLayerAttribBase64 = 1 << 1, + TMXLayerAttribGzip = 1 << 2, + TMXLayerAttribZlib = 1 << 3, +}; - enum { - TMXPropertyNone, - TMXPropertyMap, - TMXPropertyLayer, - TMXPropertyObjectGroup, - TMXPropertyObject, - TMXPropertyTile - }; +enum { + TMXPropertyNone, + TMXPropertyMap, + TMXPropertyLayer, + TMXPropertyObjectGroup, + TMXPropertyObject, + TMXPropertyTile +}; - typedef enum ccTMXTileFlags_ { - kCCTMXTileHorizontalFlag = 0x80000000, - kCCTMXTileVerticalFlag = 0x40000000, - kCCTMXTileDiagonalFlag = 0x20000000, - kCCFlipedAll = (kCCTMXTileHorizontalFlag|kCCTMXTileVerticalFlag|kCCTMXTileDiagonalFlag), - kCCFlippedMask = ~(kCCFlipedAll) - } ccTMXTileFlags; +typedef enum ccTMXTileFlags_ { + kCCTMXTileHorizontalFlag = 0x80000000, + kCCTMXTileVerticalFlag = 0x40000000, + kCCTMXTileDiagonalFlag = 0x20000000, + kCCFlipedAll = (kCCTMXTileHorizontalFlag|kCCTMXTileVerticalFlag|kCCTMXTileDiagonalFlag), + kCCFlippedMask = ~(kCCFlipedAll) +} ccTMXTileFlags; - // Bits on the far end of the 32-bit global tile ID (GID's) are used for tile flags +// Bits on the far end of the 32-bit global tile ID (GID's) are used for tile flags - /** @brief CCTMXLayerInfo contains the information about the layers like: - - Layer name - - Layer size - - Layer opacity at creation time (it can be modified at runtime) - - Whether the layer is visible (if it's not visible, then the CocosNode won't be created) +/** @brief CCTMXLayerInfo contains the information about the layers like: +- Layer name +- Layer size +- Layer opacity at creation time (it can be modified at runtime) +- Whether the layer is visible (if it's not visible, then the CocosNode won't be created) - This information is obtained from the TMX file. - */ - class CC_DLL CCTMXLayerInfo : public CCObject - { - CC_PROPERTY(CCStringToStringDictionary*, m_pProperties, Properties); - public: - std::string m_sName; - CCSize m_tLayerSize; - unsigned int *m_pTiles; - bool m_bVisible; - unsigned char m_cOpacity; - bool m_bOwnTiles; - unsigned int m_uMinGID; - unsigned int m_uMaxGID; - CCPoint m_tOffset; - public: - CCTMXLayerInfo(); - virtual ~CCTMXLayerInfo(); - }; +This information is obtained from the TMX file. +*/ +class CC_DLL CCTMXLayerInfo : public CCObject +{ + CC_PROPERTY(CCDictionary*, m_pProperties, Properties); +public: + std::string m_sName; + CCSize m_tLayerSize; + unsigned int *m_pTiles; + bool m_bVisible; + unsigned char m_cOpacity; + bool m_bOwnTiles; + unsigned int m_uMinGID; + unsigned int m_uMaxGID; + CCPoint m_tOffset; +public: + CCTMXLayerInfo(); + virtual ~CCTMXLayerInfo(); +}; - /** @brief CCTMXTilesetInfo contains the information about the tilesets like: - - Tileset name - - Tilset spacing - - Tileset margin - - size of the tiles - - Image used for the tiles - - Image size +/** @brief CCTMXTilesetInfo contains the information about the tilesets like: +- Tileset name +- Tilset spacing +- Tileset margin +- size of the tiles +- Image used for the tiles +- Image size - This information is obtained from the TMX file. - */ - class CC_DLL CCTMXTilesetInfo : public CCObject - { - public: - std::string m_sName; - unsigned int m_uFirstGid; - CCSize m_tTileSize; - unsigned int m_uSpacing; - unsigned int m_uMargin; - //! filename containing the tiles (should be spritesheet / texture atlas) - std::string m_sSourceImage; - //! size in pixels of the image - CCSize m_tImageSize; - public: - CCTMXTilesetInfo(); - virtual ~CCTMXTilesetInfo(); - CCRect rectForGID(unsigned int gid); - }; +This information is obtained from the TMX file. +*/ +class CC_DLL CCTMXTilesetInfo : public CCObject +{ +public: + std::string m_sName; + unsigned int m_uFirstGid; + CCSize m_tTileSize; + unsigned int m_uSpacing; + unsigned int m_uMargin; + //! filename containing the tiles (should be spritesheet / texture atlas) + std::string m_sSourceImage; + //! size in pixels of the image + CCSize m_tImageSize; +public: + CCTMXTilesetInfo(); + virtual ~CCTMXTilesetInfo(); + CCRect rectForGID(unsigned int gid); +}; - /** @brief CCTMXMapInfo contains the information about the map like: - - Map orientation (hexagonal, isometric or orthogonal) - - Tile size - - Map size +/** @brief CCTMXMapInfo contains the information about the map like: +- Map orientation (hexagonal, isometric or orthogonal) +- Tile size +- Map size - And it also contains: - - Layers (an array of TMXLayerInfo objects) - - Tilesets (an array of TMXTilesetInfo objects) - - ObjectGroups (an array of TMXObjectGroupInfo objects) +And it also contains: +- Layers (an array of TMXLayerInfo objects) +- Tilesets (an array of TMXTilesetInfo objects) +- ObjectGroups (an array of TMXObjectGroupInfo objects) - This information is obtained from the TMX file. +This information is obtained from the TMX file. - */ - class CC_DLL CCTMXMapInfo : public CCObject, public CCSAXDelegator - { - public: - /// map orientation - CC_SYNTHESIZE(int, m_nOrientation, Orientation); - /// map width & height - CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tMapSize, MapSize); - /// tiles width & height - CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tTileSize, TileSize); - /// Layers - CC_PROPERTY(CCMutableArray*, m_pLayers, Layers); - /// tilesets - CC_PROPERTY(CCMutableArray*, m_pTilesets, Tilesets); - /// ObjectGroups - CC_PROPERTY(CCMutableArray*, m_pObjectGroups, ObjectGroups); - /// parent element - CC_SYNTHESIZE(int, m_nParentElement, ParentElement); - /// parent GID - CC_SYNTHESIZE(unsigned int, m_uParentGID, ParentGID); - /// layer attribs - CC_SYNTHESIZE(int, m_nLayerAttribs, LayerAttribs); - /// is stroing characters? - CC_SYNTHESIZE(bool, m_bStoringCharacters, StoringCharacters); - /// properties - CC_PROPERTY(CCStringToStringDictionary*, m_pProperties, Properties); - public: - CCTMXMapInfo(); - virtual ~CCTMXMapInfo(); - /** creates a TMX Format with a tmx file */ - static CCTMXMapInfo * formatWithTMXFile(const char *tmxFile); - /** creates a TMX Format with an XML string and a TMX resource path */ - static CCTMXMapInfo * formatWithXML(const char* tmxString, const char* resourcePath); - /** initializes a TMX format witha tmx file */ - bool initWithTMXFile(const char *tmxFile); - /** initializes a TMX format with an XML string and a TMX resource path */ - bool initWithXML(const char* tmxString, const char* resourcePath); - /** initalises parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */ - bool parseXMLFile(const char *xmlFilename); - /* initalises parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */ - bool parseXMLString(const char *xmlString); - /* handles the work of parsing for parseXMLFile: and parseXMLString: */ - bool parseXMLData(const char* data); +*/ +class CC_DLL CCTMXMapInfo : public CCObject, public CCSAXDelegator +{ +public: + /// map orientation + CC_SYNTHESIZE(int, m_nOrientation, Orientation); + /// map width & height + CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tMapSize, MapSize); + /// tiles width & height + CC_SYNTHESIZE_PASS_BY_REF(CCSize, m_tTileSize, TileSize); + /// Layers + CC_PROPERTY(CCArray*, m_pLayers, Layers); + /// tilesets + CC_PROPERTY(CCArray*, m_pTilesets, Tilesets); + /// ObjectGroups + CC_PROPERTY(CCArray*, m_pObjectGroups, ObjectGroups); + /// parent element + CC_SYNTHESIZE(int, m_nParentElement, ParentElement); + /// parent GID + CC_SYNTHESIZE(unsigned int, m_uParentGID, ParentGID); + /// layer attribs + CC_SYNTHESIZE(int, m_nLayerAttribs, LayerAttribs); + /// is stroing characters? + CC_SYNTHESIZE(bool, m_bStoringCharacters, StoringCharacters); + /// properties + CC_PROPERTY(CCDictionary*, m_pProperties, Properties); +public: + CCTMXMapInfo(); + virtual ~CCTMXMapInfo(); + /** creates a TMX Format with a tmx file */ + static CCTMXMapInfo * formatWithTMXFile(const char *tmxFile); + /** creates a TMX Format with an XML string and a TMX resource path */ + static CCTMXMapInfo * formatWithXML(const char* tmxString, const char* resourcePath); + /** initializes a TMX format witha tmx file */ + bool initWithTMXFile(const char *tmxFile); + /** initializes a TMX format with an XML string and a TMX resource path */ + bool initWithXML(const char* tmxString, const char* resourcePath); + /** initalises parsing of an XML file, either a tmx (Map) file or tsx (Tileset) file */ + bool parseXMLFile(const char *xmlFilename); + /* initalises parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string */ + bool parseXMLString(const char *xmlString); + /* handles the work of parsing for parseXMLFile: and parseXMLString: */ + bool parseXMLData(const char* data); - CCDictionary * getTileProperties(); - void setTileProperties(CCDictionary * tileProperties); + CCDictionary* getTileProperties(); + void setTileProperties(CCDictionary* tileProperties); - // implement pure virtual methods of CCSAXDelegator - void startElement(void *ctx, const char *name, const char **atts); - void endElement(void *ctx, const char *name); - void textHandler(void *ctx, const char *ch, int len); - - inline const char* getCurrentString(){ return m_sCurrentString.c_str(); } - inline void setCurrentString(const char *currentString){ m_sCurrentString = currentString; } - inline const char* getTMXFileName(){ return m_sTMXFileName.c_str(); } - inline void setTMXFileName(const char *fileName){ m_sTMXFileName = fileName; } - private: - void internalInit(const char* tmxFileName, const char* resourcePath); - protected: - //! tmx filename - std::string m_sTMXFileName; - // tmx resource path - std::string m_sResources; - //! current string - std::string m_sCurrentString; - //! tile properties - CCDictionary* m_pTileProperties; - }; + // implement pure virtual methods of CCSAXDelegator + void startElement(void *ctx, const char *name, const char **atts); + void endElement(void *ctx, const char *name); + void textHandler(void *ctx, const char *ch, int len); + + inline const char* getCurrentString(){ return m_sCurrentString.c_str(); } + inline void setCurrentString(const char *currentString){ m_sCurrentString = currentString; } + inline const char* getTMXFileName(){ return m_sTMXFileName.c_str(); } + inline void setTMXFileName(const char *fileName){ m_sTMXFileName = fileName; } +private: + void internalInit(const char* tmxFileName, const char* resourcePath); +protected: + //! tmx filename + std::string m_sTMXFileName; + // tmx resource path + std::string m_sResources; + //! current string + std::string m_sCurrentString; + //! tile properties + CCDictionary* m_pTileProperties; +}; -}// namespace cocos2d +NS_CC_END #endif diff --git a/cocos2dx/include/CCTextureCache.h b/cocos2dx/include/CCTextureCache.h index a3e07ddfc5..df267c6291 100755 --- a/cocos2dx/include/CCTextureCache.h +++ b/cocos2dx/include/CCTextureCache.h @@ -29,7 +29,7 @@ THE SOFTWARE. #include #include "CCObject.h" -#include "CCMutableDictionary.h" +#include "CCDictionary.h" #include "CCTexture2D.h" @@ -49,7 +49,7 @@ class CCImage; class CC_DLL CCTextureCache : public CCObject { protected: - CCMutableDictionary * m_pTextures; + CCDictionary* m_pTextures; //pthread_mutex_t *m_pDictLock; diff --git a/cocos2dx/include/CCTexturePVR.h b/cocos2dx/include/CCTexturePVR.h index 557f3786f8..870de6bf12 100755 --- a/cocos2dx/include/CCTexturePVR.h +++ b/cocos2dx/include/CCTexturePVR.h @@ -30,7 +30,7 @@ THE SOFTWARE. #include "CCGL.h" #include "CCObject.h" -#include "CCMutableArray.h" +#include "CCArray.h" namespace cocos2d { diff --git a/cocos2dx/include/CCTouchDispatcher.h b/cocos2dx/include/CCTouchDispatcher.h index cdbc9088d7..b0a6ba5bab 100755 --- a/cocos2dx/include/CCTouchDispatcher.h +++ b/cocos2dx/include/CCTouchDispatcher.h @@ -28,7 +28,7 @@ THE SOFTWARE. #include "CCTouchDelegateProtocol.h" #include "CCObject.h" -#include "CCMutableArray.h" +#include "CCArray.h" namespace cocos2d { typedef enum @@ -146,19 +146,19 @@ public: protected: void forceRemoveDelegate(CCTouchDelegate *pDelegate); - void forceAddHandler(CCTouchHandler *pHandler, CCMutableArray *pArray); + void forceAddHandler(CCTouchHandler *pHandler, CCArray* pArray); void forceRemoveAllDelegates(void); - void rearrangeHandlers(CCMutableArray *pArray); - CCTouchHandler* findHandler(CCMutableArray *pArray, CCTouchDelegate *pDelegate); + void rearrangeHandlers(CCArray* pArray); + CCTouchHandler* findHandler(CCArray* pArray, CCTouchDelegate *pDelegate); protected: - CCMutableArray *m_pTargetedHandlers; - CCMutableArray *m_pStandardHandlers; + CCArray* m_pTargetedHandlers; + CCArray* m_pStandardHandlers; bool m_bLocked; bool m_bToAdd; bool m_bToRemove; - CCMutableArray *m_pHandlersToAdd; + CCArray* m_pHandlersToAdd; struct _ccCArray *m_pHandlersToRemove; bool m_bToQuit; bool m_bDispatchEvents; diff --git a/cocos2dx/include/cocos2d.h b/cocos2dx/include/cocos2d.h index 17b9c9b185..4a8d227e37 100755 --- a/cocos2dx/include/cocos2d.h +++ b/cocos2dx/include/cocos2d.h @@ -96,8 +96,8 @@ THE SOFTWARE. // cocoa includes // #include "CCSet.h" -#include "CCMutableArray.h" -#include "CCMutableDictionary.h" +#include "CCArray.h" +#include "CCDictionary.h" #include "CCObject.h" #include "CCZone.h" #include "CCGeometry.h" diff --git a/cocos2dx/keypad_dispatcher/CCKeypadDispatcher.cpp b/cocos2dx/keypad_dispatcher/CCKeypadDispatcher.cpp index b938262230..65b2244cc8 100644 --- a/cocos2dx/keypad_dispatcher/CCKeypadDispatcher.cpp +++ b/cocos2dx/keypad_dispatcher/CCKeypadDispatcher.cpp @@ -38,7 +38,8 @@ CCKeypadDispatcher::CCKeypadDispatcher() , m_bToAdd(false) , m_bToRemove(false) { - m_pDelegates = new KeypadDelegateArray; + m_pDelegates = CCArray::array(); + m_pDelegates->retain(); m_pHandlersToAdd = ccCArrayNew(8); m_pHandlersToRemove = ccCArrayNew(8); @@ -124,12 +125,11 @@ void CCKeypadDispatcher::forceAddDelegate(CCKeypadDelegate* pDelegate) void CCKeypadDispatcher::forceRemoveDelegate(CCKeypadDelegate* pDelegate) { - CCKeypadHandler *pHandler; - CCMutableArray::CCMutableArrayIterator iter; - - for (iter = m_pDelegates->begin(); iter != m_pDelegates->end(); ++iter) + CCKeypadHandler* pHandler = NULL; + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_pDelegates, pObj) { - pHandler = *iter; + pHandler = (CCKeypadHandler*)pObj; if (pHandler && pHandler->getDelegate() == pDelegate) { m_pDelegates->removeObject(pHandler); @@ -140,19 +140,19 @@ void CCKeypadDispatcher::forceRemoveDelegate(CCKeypadDelegate* pDelegate) bool CCKeypadDispatcher::dispatchKeypadMSG(ccKeypadMSGType nMsgType) { - CCKeypadHandler *pHandler; - CCKeypadDelegate *pDelegate; - CCMutableArray::CCMutableArrayIterator iter; + CCKeypadHandler* pHandler = NULL; + CCKeypadDelegate* pDelegate = NULL; m_bLocked = true; if (m_pDelegates->count() > 0) { - for (iter = m_pDelegates->begin(); iter != m_pDelegates->end(); ++iter) + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_pDelegates, pObj) { - CC_BREAK_IF(!(*iter)); + CC_BREAK_IF(!pObj); - pHandler = *iter; + pHandler = (CCKeypadHandler*)pObj; pDelegate = pHandler->getDelegate(); switch (nMsgType) diff --git a/cocos2dx/label_nodes/CCLabelBMFont.cpp b/cocos2dx/label_nodes/CCLabelBMFont.cpp index 1638fc71d6..524c8fbdce 100644 --- a/cocos2dx/label_nodes/CCLabelBMFont.cpp +++ b/cocos2dx/label_nodes/CCLabelBMFont.cpp @@ -33,7 +33,7 @@ http://www.angelcode.com/products/bmfont/ (Free, Windows only) #include "CCLabelBMFont.h" #include "platform/platform.h" -#include "CCMutableDictionary.h" +#include "CCDictionary.h" #include "CCConfiguration.h" #include "CCDrawingPrimitives.h" #include "CCSprite.h" @@ -42,834 +42,835 @@ http://www.angelcode.com/products/bmfont/ (Free, Windows only) #include "CCFileUtils.h" #include "support/data_support/uthash.h" -namespace cocos2d{ +NS_CC_BEGIN - // - //FNTConfig Cache - free functions - // - CCMutableDictionary *configurations = NULL; - CCBMFontConfiguration* FNTConfigLoadFile( const char *fntFile) +// +//FNTConfig Cache - free functions +// +CCDictionary* configurations = NULL; +CCBMFontConfiguration* FNTConfigLoadFile( const char *fntFile) +{ + CCBMFontConfiguration* pRet = NULL; + + if( configurations == NULL ) { - CCBMFontConfiguration *pRet = NULL; + configurations = new CCDictionary(); + } - if( configurations == NULL ) - { - configurations = new CCMutableDictionary(); - } - std::string key(fntFile); - pRet = configurations->objectForKey(key); - if( pRet == NULL ) - { - pRet = CCBMFontConfiguration::configurationWithFNTFile(fntFile); - configurations->setObject(pRet, key); - } + pRet = (CCBMFontConfiguration*)configurations->objectForKey(fntFile); + if( pRet == NULL ) + { + pRet = CCBMFontConfiguration::configurationWithFNTFile(fntFile); + configurations->setObject(pRet, fntFile); + } + return pRet; +} + +void FNTConfigRemoveCache( void ) +{ + if (configurations) + { + configurations->removeAllObjects(); + CC_SAFE_RELEASE_NULL(configurations); + } +} +// +//Hash Element +// +// Equal function for targetSet. +typedef struct _KerningHashElement +{ + int key; // key for the hash. 16-bit for 1st element, 16-bit for 2nd element + int amount; + UT_hash_handle hh; +} tKerningHashElement; +// +//BitmapFontConfiguration +// + +CCBMFontConfiguration * CCBMFontConfiguration::configurationWithFNTFile(const char *FNTfile) +{ + CCBMFontConfiguration * pRet = new CCBMFontConfiguration(); + if (pRet->initWithFNTfile(FNTfile)) + { + pRet->autorelease(); return pRet; } - - void FNTConfigRemoveCache( void ) - { - if (configurations) - { - configurations->removeAllObjects(); - CC_SAFE_RELEASE_NULL(configurations); - } - } - // - //Hash Element - // - // Equal function for targetSet. - typedef struct _KerningHashElement - { - int key; // key for the hash. 16-bit for 1st element, 16-bit for 2nd element - int amount; - UT_hash_handle hh; - } tKerningHashElement; - // - //BitmapFontConfiguration - // - - CCBMFontConfiguration * CCBMFontConfiguration::configurationWithFNTFile(const char *FNTfile) - { - CCBMFontConfiguration * pRet = new CCBMFontConfiguration(); - if (pRet->initWithFNTfile(FNTfile)) - { - pRet->autorelease(); - return pRet; - } - CC_SAFE_DELETE(pRet); - return NULL; - } - bool CCBMFontConfiguration::initWithFNTfile(const char *FNTfile) - { - CCAssert(FNTfile != NULL && strlen(FNTfile)!=0, ""); - m_pKerningDictionary = NULL; - this->parseConfigFile(FNTfile); - return true; - } - - CCBMFontConfiguration::CCBMFontConfiguration() - : m_pBitmapFontArray(new std::map) - , m_uCommonHeight(0) - , m_pKerningDictionary(NULL) - { - - } - - CCBMFontConfiguration::~CCBMFontConfiguration() - { - CCLOGINFO( "cocos2d: deallocing CCBMFontConfiguration" ); - CC_SAFE_DELETE(m_pBitmapFontArray); - this->purgeKerningDictionary(); - m_sAtlasName.clear(); - } - char * CCBMFontConfiguration::description(void) - { - char *ret = new char[100]; - sprintf(ret, "", HASH_COUNT(m_pKerningDictionary), m_sAtlasName.c_str()); - return ret; - } - void CCBMFontConfiguration::purgeKerningDictionary() - { - tKerningHashElement *current; - while(m_pKerningDictionary) - { - current = m_pKerningDictionary; - HASH_DEL(m_pKerningDictionary,current); - free(current); - } - } - void CCBMFontConfiguration::parseConfigFile(const char *controlFile) - { - std::string fullpath = CCFileUtils::fullPathFromRelativePath(controlFile); - - CCFileData data(fullpath.c_str(), "rb"); - unsigned long nBufSize = data.getSize(); - char* pBuffer = (char*) data.getBuffer(); - - CCAssert(pBuffer, "CCBMFontConfiguration::parseConfigFile | Open file error."); - - if (!pBuffer) - { - return; - } - - // parse spacing / padding - std::string line; - std::string strLeft(pBuffer, nBufSize); - while (strLeft.length() > 0) - { - int pos = strLeft.find('\n'); - - if (pos != (int)std::string::npos) - { - // the data is more than a line.get one line - line = strLeft.substr(0, pos); - strLeft = strLeft.substr(pos + 1); - } - else - { - // get the left data - line = strLeft; - strLeft.erase(); - } - - if(line.substr(0,strlen("info face")) == "info face") - { - // XXX: info parsing is incomplete - // Not needed for the Hiero editors, but needed for the AngelCode editor - // [self parseInfoArguments:line]; - this->parseInfoArguments(line); - } - // Check to see if the start of the line is something we are interested in - else if(line.substr(0,strlen("common lineHeight")) == "common lineHeight") - { - this->parseCommonArguments(line); - } - else if(line.substr(0,strlen("page id")) == "page id") - { - this->parseImageFileName(line, controlFile); - } - else if(line.substr(0,strlen("chars c")) == "chars c") - { - // Ignore this line - } - else if(line.substr(0,strlen("char")) == "char") - { - // Parse the current line and create a new CharDef - ccBMFontDef characterDefinition; - this->parseCharacterDefinition(line, &characterDefinition); - - // Add the CharDef returned to the charArray - (*m_pBitmapFontArray)[ characterDefinition.charID ] = characterDefinition; - } - else if(line.substr(0,strlen("kernings count")) == "kernings count") - { - this->parseKerningCapacity(line); - } - else if(line.substr(0,strlen("kerning first")) == "kerning first") - { - this->parseKerningEntry(line); - } - } - } - void CCBMFontConfiguration::parseImageFileName(std::string line, const char *fntFile) - { - ////////////////////////////////////////////////////////////////////////// - // line to parse: - // page id=0 file="bitmapFontTest.png" - ////////////////////////////////////////////////////////////////////////// - - // page ID. Sanity check - int index = line.find('=')+1; - int index2 = line.find(' ', index); - std::string value = line.substr(index, index2-index); - CCAssert(atoi(value.c_str()) == 0, "LabelBMFont file could not be found"); - // file - index = line.find('"')+1; - index2 = line.find('"', index); - value = line.substr(index, index2-index); - - m_sAtlasName = CCFileUtils::fullPathFromRelativeFile(value.c_str(), fntFile); - } - void CCBMFontConfiguration::parseInfoArguments(std::string line) - { - ////////////////////////////////////////////////////////////////////////// - // possible lines to parse: - // info face="Script" size=32 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,4,3,2 spacing=0,0 outline=0 - // info face="Cracked" size=36 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1 - ////////////////////////////////////////////////////////////////////////// - - // padding - int index = line.find("padding="); - int index2 = line.find(' ', index); - std::string value = line.substr(index, index2-index); - sscanf(value.c_str(), "padding=%d,%d,%d,%d", &m_tPadding.top, &m_tPadding.right, &m_tPadding.bottom, &m_tPadding.left); - CCLOG("cocos2d: padding: %d,%d,%d,%d", m_tPadding.left, m_tPadding.top, m_tPadding.right, m_tPadding.bottom); - } - void CCBMFontConfiguration::parseCommonArguments(std::string line) - { - ////////////////////////////////////////////////////////////////////////// - // line to parse: - // common lineHeight=104 base=26 scaleW=1024 scaleH=512 pages=1 packed=0 - ////////////////////////////////////////////////////////////////////////// - - // Height - int index = line.find("lineHeight="); - int index2 = line.find(' ', index); - std::string value = line.substr(index, index2-index); - sscanf(value.c_str(), "lineHeight=%u", &m_uCommonHeight); - // scaleW. sanity check - index = line.find("scaleW=") + strlen("scaleW="); - index2 = line.find(' ', index); - value = line.substr(index, index2-index); - CCAssert(atoi(value.c_str()) <= CCConfiguration::sharedConfiguration()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported"); - // scaleH. sanity check - index = line.find("scaleH=") + strlen("scaleH="); - index2 = line.find(' ', index); - value = line.substr(index, index2-index); - CCAssert(atoi(value.c_str()) <= CCConfiguration::sharedConfiguration()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported"); - // pages. sanity check - index = line.find("pages=") + strlen("pages="); - index2 = line.find(' ', index); - value = line.substr(index, index2-index); - CCAssert(atoi(value.c_str()) == 1, "CCBitfontAtlas: only supports 1 page"); - - // packed (ignore) What does this mean ?? - } - void CCBMFontConfiguration::parseCharacterDefinition(std::string line, ccBMFontDef *characterDefinition) - { - ////////////////////////////////////////////////////////////////////////// - // line to parse: - // char id=32 x=0 y=0 width=0 height=0 xoffset=0 yoffset=44 xadvance=14 page=0 chnl=0 - ////////////////////////////////////////////////////////////////////////// - - // Character ID - int index = line.find("id="); - int index2 = line.find(' ', index); - std::string value = line.substr(index, index2-index); - sscanf(value.c_str(), "id=%u", &characterDefinition->charID); - - // Character x - index = line.find("x="); - index2 = line.find(' ', index); - value = line.substr(index, index2-index); - sscanf(value.c_str(), "x=%f", &characterDefinition->rect.origin.x); - // Character y - index = line.find("y="); - index2 = line.find(' ', index); - value = line.substr(index, index2-index); - sscanf(value.c_str(), "y=%f", &characterDefinition->rect.origin.y); - // Character width - index = line.find("width="); - index2 = line.find(' ', index); - value = line.substr(index, index2-index); - sscanf(value.c_str(), "width=%f", &characterDefinition->rect.size.width); - // Character height - index = line.find("height="); - index2 = line.find(' ', index); - value = line.substr(index, index2-index); - sscanf(value.c_str(), "height=%f", &characterDefinition->rect.size.height); - // Character xoffset - index = line.find("xoffset="); - index2 = line.find(' ', index); - value = line.substr(index, index2-index); - sscanf(value.c_str(), "xoffset=%d", &characterDefinition->xOffset); - // Character yoffset - index = line.find("yoffset="); - index2 = line.find(' ', index); - value = line.substr(index, index2-index); - sscanf(value.c_str(), "yoffset=%d", &characterDefinition->yOffset); - // Character xadvance - index = line.find("xadvance="); - index2 = line.find(' ', index); - value = line.substr(index, index2-index); - sscanf(value.c_str(), "xadvance=%d", &characterDefinition->xAdvance); - } - void CCBMFontConfiguration::parseKerningCapacity(std::string line) - { - // When using uthash there is not need to parse the capacity. - - // CCAssert(!kerningDictionary, @"dictionary already initialized"); - // - // // Break the values for this line up using = - // CCMutableArray *values = [line componentsSeparatedByString:@"="]; - // NSEnumerator *nse = [values objectEnumerator]; - // CCString *propertyValue; - // - // // We need to move past the first entry in the array before we start assigning values - // [nse nextObject]; - // - // // count - // propertyValue = [nse nextObject]; - // int capacity = [propertyValue intValue]; - // - // if( capacity != -1 ) - // kerningDictionary = ccHashSetNew(capacity, targetSetEql); - } - void CCBMFontConfiguration::parseKerningEntry(std::string line) - { - ////////////////////////////////////////////////////////////////////////// - // line to parse: - // kerning first=121 second=44 amount=-7 - ////////////////////////////////////////////////////////////////////////// - - // first - int first; - int index = line.find("first="); - int index2 = line.find(' ', index); - std::string value = line.substr(index, index2-index); - sscanf(value.c_str(), "first=%d", &first); - - // second - int second; - index = line.find("second="); - index2 = line.find(' ', index); - value = line.substr(index, index2-index); - sscanf(value.c_str(), "second=%d", &second); - - // amount - int amount; - index = line.find("amount="); - index2 = line.find(' ', index); - value = line.substr(index, index2-index); - sscanf(value.c_str(), "amount=%d", &amount); - - tKerningHashElement *element = (tKerningHashElement *)calloc( sizeof( *element ), 1 ); - element->amount = amount; - element->key = (first<<16) | (second&0xffff); - HASH_ADD_INT(m_pKerningDictionary,key, element); - } - // - //CCLabelBMFont - // - - //LabelBMFont - Purge Cache - void CCLabelBMFont::purgeCachedData() - { - FNTConfigRemoveCache(); - } - - //LabelBMFont - Creation & Init - CCLabelBMFont *CCLabelBMFont::labelWithString(const char *str, const char *fntFile) - { - CCLabelBMFont *pRet = new CCLabelBMFont(); - if(pRet && pRet->initWithString(str, fntFile)) - { - pRet->autorelease(); - return pRet; - } - CC_SAFE_DELETE(pRet); - return NULL; - } - - bool CCLabelBMFont::initWithString(const char *theString, const char *fntFile) - { - CCAssert(theString != NULL, ""); - CC_SAFE_RELEASE(m_pConfiguration);// allow re-init - m_pConfiguration = FNTConfigLoadFile(fntFile); - m_pConfiguration->retain(); - CCAssert( m_pConfiguration, "Error creating config for LabelBMFont"); - - if (CCSpriteBatchNode::initWithFile(m_pConfiguration->m_sAtlasName.c_str(), strlen(theString))) - { - m_cOpacity = 255; - m_tColor = ccWHITE; - m_tContentSize = CCSizeZero; - m_bIsOpacityModifyRGB = m_pobTextureAtlas->getTexture()->getHasPremultipliedAlpha(); - setAnchorPoint(ccp(0.5f, 0.5f)); - this->setString(theString); - return true; - } - return false; - } - CCLabelBMFont::~CCLabelBMFont() - { - m_sString.clear(); - CC_SAFE_RELEASE(m_pConfiguration); - } - - // LabelBMFont - Atlas generation - int CCLabelBMFont::kerningAmountForFirst(unsigned short first, unsigned short second) - { - int ret = 0; - unsigned int key = (first<<16) | (second & 0xffff); - - if( m_pConfiguration->m_pKerningDictionary ) { - tKerningHashElement *element = NULL; - HASH_FIND_INT(m_pConfiguration->m_pKerningDictionary, &key, element); - if(element) - ret = element->amount; - } - return ret; - } - - static int cc_wcslen(const unsigned short* str) - { - int i=0; - while(*str++) i++; - return i; - } - - /* Code from GLIB gutf8.c starts here. */ - - #define UTF8_COMPUTE(Char, Mask, Len) \ - if (Char < 128) \ - { \ - Len = 1; \ - Mask = 0x7f; \ - } \ - else if ((Char & 0xe0) == 0xc0) \ - { \ - Len = 2; \ - Mask = 0x1f; \ - } \ - else if ((Char & 0xf0) == 0xe0) \ - { \ - Len = 3; \ - Mask = 0x0f; \ - } \ - else if ((Char & 0xf8) == 0xf0) \ - { \ - Len = 4; \ - Mask = 0x07; \ - } \ - else if ((Char & 0xfc) == 0xf8) \ - { \ - Len = 5; \ - Mask = 0x03; \ - } \ - else if ((Char & 0xfe) == 0xfc) \ - { \ - Len = 6; \ - Mask = 0x01; \ - } \ - else \ - Len = -1; - - #define UTF8_LENGTH(Char) \ - ((Char) < 0x80 ? 1 : \ - ((Char) < 0x800 ? 2 : \ - ((Char) < 0x10000 ? 3 : \ - ((Char) < 0x200000 ? 4 : \ - ((Char) < 0x4000000 ? 5 : 6))))) - - - #define UTF8_GET(Result, Chars, Count, Mask, Len) \ - (Result) = (Chars)[0] & (Mask); \ - for ((Count) = 1; (Count) < (Len); ++(Count)) \ - { \ - if (((Chars)[(Count)] & 0xc0) != 0x80) \ - { \ - (Result) = -1; \ - break; \ - } \ - (Result) <<= 6; \ - (Result) |= ((Chars)[(Count)] & 0x3f); \ - } - - #define UNICODE_VALID(Char) \ - ((Char) < 0x110000 && \ - (((Char) & 0xFFFFF800) != 0xD800) && \ - ((Char) < 0xFDD0 || (Char) > 0xFDEF) && \ - ((Char) & 0xFFFE) != 0xFFFE) - - - static const char utf8_skip_data[256] = { - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, - 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, - 5, 5, 5, 6, 6, 1, 1 - }; - - static const char *const g_utf8_skip = utf8_skip_data; - - #define cc_utf8_next_char(p) (char *)((p) + g_utf8_skip[*(unsigned char *)(p)]) - - /* - * g_utf8_strlen: - * @p: pointer to the start of a UTF-8 encoded string. - * @max: the maximum number of bytes to examine. If @max - * is less than 0, then the string is assumed to be - * nul-terminated. If @max is 0, @p will not be examined and - * may be %NULL. - * - * Returns the length of the string in characters. - * - * Return value: the length of the string in characters - **/ - static long - cc_utf8_strlen (const char * p, int max) - { - long len = 0; - const char *start = p; - - if (!(p != NULL || max == 0)) - { - return 0; - } - - if (max < 0) - { - while (*p) - { - p = cc_utf8_next_char (p); - ++len; - } - } - else - { - if (max == 0 || !*p) - return 0; - - p = cc_utf8_next_char (p); - - while (p - start < max && *p) - { - ++len; - p = cc_utf8_next_char (p); - } - - /* only do the last len increment if we got a complete - * char (don't count partial chars) - */ - if (p - start == max) - ++len; - } - - return len; - } - - /* - * g_utf8_get_char: - * @p: a pointer to Unicode character encoded as UTF-8 - * - * Converts a sequence of bytes encoded as UTF-8 to a Unicode character. - * If @p does not point to a valid UTF-8 encoded character, results are - * undefined. If you are not sure that the bytes are complete - * valid Unicode characters, you should use g_utf8_get_char_validated() - * instead. - * - * Return value: the resulting character - **/ - static unsigned int - cc_utf8_get_char (const char * p) - { - int i, mask = 0, len; - unsigned int result; - unsigned char c = (unsigned char) *p; - - UTF8_COMPUTE (c, mask, len); - if (len == -1) - return (unsigned int) - 1; - UTF8_GET (result, p, i, mask, len); - - return result; - } - - - void CCLabelBMFont::createFontChars() - { - int nextFontPositionX = 0; - int nextFontPositionY = 0; - unsigned short prev = -1; - int kerningAmount = 0; - - CCSize tmpSize = CCSizeZero; - - int longestLine = 0; - unsigned int totalHeight = 0; - - unsigned int quantityOfLines = 1; - - if (0 == m_sString.length()) - { - return; - } - - int utf8len = cc_utf8_strlen(m_sString.c_str(), -1); - if (utf8len == 0) - { - return; - } - - unsigned short* pUniStr = new unsigned short[utf8len+1]; - pUniStr[utf8len] = 0; - - const char* p = m_sString.c_str(); - - for (int i = 0; i < utf8len; ++i) - { - pUniStr[i] = cc_utf8_get_char(p); - p = cc_utf8_next_char (p); - } - - unsigned int stringLen = cc_wcslen(pUniStr); - - for (unsigned int i = 0; i < stringLen - 1; ++i) - { - unsigned short c = pUniStr[i]; - if (c == '\n') - { - quantityOfLines++; - } - } - - totalHeight = m_pConfiguration->m_uCommonHeight * quantityOfLines; - nextFontPositionY = -(m_pConfiguration->m_uCommonHeight - m_pConfiguration->m_uCommonHeight * quantityOfLines); - - for (unsigned int i= 0; i < stringLen; i++) - { - unsigned short c = pUniStr[i]; - - if (c == '\n') - { - nextFontPositionX = 0; - nextFontPositionY -= m_pConfiguration->m_uCommonHeight; - continue; - } - - std::map::iterator it = m_pConfiguration->m_pBitmapFontArray->find(c); - CCAssert(it != m_pConfiguration->m_pBitmapFontArray->end(), "LabelBMFont: character is not supported"); - - kerningAmount = this->kerningAmountForFirst(prev, c); - - const ccBMFontDef& fontDef = (*(m_pConfiguration->m_pBitmapFontArray))[c]; - - CCRect rect = fontDef.rect; - - CCSprite *fontChar; - - fontChar = (CCSprite*)(this->getChildByTag(i)); - if( ! fontChar ) - { - fontChar = new CCSprite(); - fontChar->initWithTexture(m_pobTextureAtlas->getTexture(), rect); - this->addChild(fontChar, 0, i); - fontChar->release(); - } - else - { - // reusing fonts - fontChar->setTextureRect(rect, false, rect.size); - - // restore to default in case they were modified - fontChar->setIsVisible(true); - fontChar->setOpacity(255); - } - - float yOffset = (float)(m_pConfiguration->m_uCommonHeight) - fontDef.yOffset; - CCPoint fontPos = ccp( (float)nextFontPositionX + fontDef.xOffset + fontDef.rect.size.width*0.5f + kerningAmount, (float)nextFontPositionY + yOffset - rect.size.height*0.5f ); - fontChar->setPosition(CC_POINT_PIXELS_TO_POINTS(fontPos)); - - // NSLog(@"position.y: %f", fontChar.position.y); - - // update kerning - nextFontPositionX += (*(m_pConfiguration->m_pBitmapFontArray))[c].xAdvance + kerningAmount; - prev = c; - - // Apply label properties - fontChar->setIsOpacityModifyRGB(m_bIsOpacityModifyRGB); - // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on - fontChar->setColor(m_tColor); - - // only apply opaccity if it is different than 255 ) - // to prevent modifying the color too (issue #610) - if( m_cOpacity != 255 ) - { - fontChar->setOpacity(m_cOpacity); - } - - if (longestLine < nextFontPositionX) - { - longestLine = nextFontPositionX; - } - } - - tmpSize.width = (float) longestLine; - tmpSize.height = (float) totalHeight; - - this->setContentSize(tmpSize); - - CC_SAFE_DELETE_ARRAY(pUniStr); - } - - //LabelBMFont - CCLabelProtocol protocol - void CCLabelBMFont::setString(const char *newString) - { - m_sString.clear(); - m_sString = newString; - - if (m_pChildren && m_pChildren->count() != 0) - { - CCObject* child; - CCARRAY_FOREACH(m_pChildren, child) - { - CCNode* pNode = (CCNode*) child; - if (pNode) - { - pNode->setIsVisible(false); - } - } - } - this->createFontChars(); - } - - const char* CCLabelBMFont::getString(void) - { - return m_sString.c_str(); - } - - void CCLabelBMFont::setCString(const char *label) - { - setString(label); - } - - //LabelBMFont - CCRGBAProtocol protocol - void CCLabelBMFont::setColor(const ccColor3B& var) - { - m_tColor = var; - if (m_pChildren && m_pChildren->count() != 0) - { - CCObject* child; - CCARRAY_FOREACH(m_pChildren, child) - { - CCSprite* pNode = (CCSprite*) child; - if (pNode) - { - pNode->setColor(m_tColor); - } - } - } - } - const ccColor3B& CCLabelBMFont::getColor() - { - return m_tColor; - } - void CCLabelBMFont::setOpacity(GLubyte var) - { - m_cOpacity = var; - - if (m_pChildren && m_pChildren->count() != 0) - { - CCObject* child; - CCARRAY_FOREACH(m_pChildren, child) - { - CCNode* pNode = (CCNode*) child; - if (pNode) - { - CCRGBAProtocol *pRGBAProtocol = dynamic_cast(pNode); - if (pRGBAProtocol) - { - pRGBAProtocol->setOpacity(m_cOpacity); - } - } - } - } - } - GLubyte CCLabelBMFont::getOpacity() - { - return m_cOpacity; - } - void CCLabelBMFont::setIsOpacityModifyRGB(bool var) - { - m_bIsOpacityModifyRGB = var; - if (m_pChildren && m_pChildren->count() != 0) - { - CCObject* child; - CCARRAY_FOREACH(m_pChildren, child) - { - CCNode* pNode = (CCNode*) child; - if (pNode) - { - CCRGBAProtocol *pRGBAProtocol = dynamic_cast(pNode); - if (pRGBAProtocol) - { - pRGBAProtocol->setIsOpacityModifyRGB(m_bIsOpacityModifyRGB); - } - } - } - } - } - bool CCLabelBMFont::getIsOpacityModifyRGB() - { - return m_bIsOpacityModifyRGB; - } - - // LabelBMFont - AnchorPoint - void CCLabelBMFont::setAnchorPoint(const CCPoint& point) - { - if( ! CCPoint::CCPointEqualToPoint(point, m_tAnchorPoint) ) - { - CCSpriteBatchNode::setAnchorPoint(point); - this->createFontChars(); - } - } - - //LabelBMFont - Debug draw -#if CC_LABELBMFONT_DEBUG_DRAW - void CCLabelBMFont::draw() - { - CCSpriteBatchNode::draw(); - const CCSize& s = this->getContentSize(); - CCPoint vertices[4]={ - ccp(0,0),ccp(s.width,0), - ccp(s.width,s.height),ccp(0,s.height), - }; - ccDrawPoly(vertices, 4, true); - } -#endif // CC_LABELBMFONT_DEBUG_DRAW + CC_SAFE_DELETE(pRet); + return NULL; +} + +bool CCBMFontConfiguration::initWithFNTfile(const char *FNTfile) +{ + CCAssert(FNTfile != NULL && strlen(FNTfile)!=0, ""); + m_pKerningDictionary = NULL; + this->parseConfigFile(FNTfile); + return true; +} + +CCBMFontConfiguration::CCBMFontConfiguration() + : m_pBitmapFontArray(new std::map) + , m_uCommonHeight(0) + , m_pKerningDictionary(NULL) +{ } + +CCBMFontConfiguration::~CCBMFontConfiguration() +{ + CCLOGINFO( "cocos2d: deallocing CCBMFontConfiguration" ); + CC_SAFE_DELETE(m_pBitmapFontArray); + this->purgeKerningDictionary(); + m_sAtlasName.clear(); +} +char * CCBMFontConfiguration::description(void) +{ + char *ret = new char[100]; + sprintf(ret, "", HASH_COUNT(m_pKerningDictionary), m_sAtlasName.c_str()); + return ret; +} +void CCBMFontConfiguration::purgeKerningDictionary() +{ + tKerningHashElement *current; + while(m_pKerningDictionary) + { + current = m_pKerningDictionary; + HASH_DEL(m_pKerningDictionary,current); + free(current); + } +} +void CCBMFontConfiguration::parseConfigFile(const char *controlFile) +{ + std::string fullpath = CCFileUtils::fullPathFromRelativePath(controlFile); + + CCFileData data(fullpath.c_str(), "rb"); + unsigned long nBufSize = data.getSize(); + char* pBuffer = (char*) data.getBuffer(); + + CCAssert(pBuffer, "CCBMFontConfiguration::parseConfigFile | Open file error."); + + if (!pBuffer) + { + return; + } + + // parse spacing / padding + std::string line; + std::string strLeft(pBuffer, nBufSize); + while (strLeft.length() > 0) + { + int pos = strLeft.find('\n'); + + if (pos != (int)std::string::npos) + { + // the data is more than a line.get one line + line = strLeft.substr(0, pos); + strLeft = strLeft.substr(pos + 1); + } + else + { + // get the left data + line = strLeft; + strLeft.erase(); + } + + if(line.substr(0,strlen("info face")) == "info face") + { + // XXX: info parsing is incomplete + // Not needed for the Hiero editors, but needed for the AngelCode editor + // [self parseInfoArguments:line]; + this->parseInfoArguments(line); + } + // Check to see if the start of the line is something we are interested in + else if(line.substr(0,strlen("common lineHeight")) == "common lineHeight") + { + this->parseCommonArguments(line); + } + else if(line.substr(0,strlen("page id")) == "page id") + { + this->parseImageFileName(line, controlFile); + } + else if(line.substr(0,strlen("chars c")) == "chars c") + { + // Ignore this line + } + else if(line.substr(0,strlen("char")) == "char") + { + // Parse the current line and create a new CharDef + ccBMFontDef characterDefinition; + this->parseCharacterDefinition(line, &characterDefinition); + + // Add the CharDef returned to the charArray + (*m_pBitmapFontArray)[ characterDefinition.charID ] = characterDefinition; + } + else if(line.substr(0,strlen("kernings count")) == "kernings count") + { + this->parseKerningCapacity(line); + } + else if(line.substr(0,strlen("kerning first")) == "kerning first") + { + this->parseKerningEntry(line); + } + } +} +void CCBMFontConfiguration::parseImageFileName(std::string line, const char *fntFile) +{ + ////////////////////////////////////////////////////////////////////////// + // line to parse: + // page id=0 file="bitmapFontTest.png" + ////////////////////////////////////////////////////////////////////////// + + // page ID. Sanity check + int index = line.find('=')+1; + int index2 = line.find(' ', index); + std::string value = line.substr(index, index2-index); + CCAssert(atoi(value.c_str()) == 0, "LabelBMFont file could not be found"); + // file + index = line.find('"')+1; + index2 = line.find('"', index); + value = line.substr(index, index2-index); + + m_sAtlasName = CCFileUtils::fullPathFromRelativeFile(value.c_str(), fntFile); +} +void CCBMFontConfiguration::parseInfoArguments(std::string line) +{ + ////////////////////////////////////////////////////////////////////////// + // possible lines to parse: + // info face="Script" size=32 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,4,3,2 spacing=0,0 outline=0 + // info face="Cracked" size=36 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1 + ////////////////////////////////////////////////////////////////////////// + + // padding + int index = line.find("padding="); + int index2 = line.find(' ', index); + std::string value = line.substr(index, index2-index); + sscanf(value.c_str(), "padding=%d,%d,%d,%d", &m_tPadding.top, &m_tPadding.right, &m_tPadding.bottom, &m_tPadding.left); + CCLOG("cocos2d: padding: %d,%d,%d,%d", m_tPadding.left, m_tPadding.top, m_tPadding.right, m_tPadding.bottom); +} +void CCBMFontConfiguration::parseCommonArguments(std::string line) +{ + ////////////////////////////////////////////////////////////////////////// + // line to parse: + // common lineHeight=104 base=26 scaleW=1024 scaleH=512 pages=1 packed=0 + ////////////////////////////////////////////////////////////////////////// + + // Height + int index = line.find("lineHeight="); + int index2 = line.find(' ', index); + std::string value = line.substr(index, index2-index); + sscanf(value.c_str(), "lineHeight=%u", &m_uCommonHeight); + // scaleW. sanity check + index = line.find("scaleW=") + strlen("scaleW="); + index2 = line.find(' ', index); + value = line.substr(index, index2-index); + CCAssert(atoi(value.c_str()) <= CCConfiguration::sharedConfiguration()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported"); + // scaleH. sanity check + index = line.find("scaleH=") + strlen("scaleH="); + index2 = line.find(' ', index); + value = line.substr(index, index2-index); + CCAssert(atoi(value.c_str()) <= CCConfiguration::sharedConfiguration()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported"); + // pages. sanity check + index = line.find("pages=") + strlen("pages="); + index2 = line.find(' ', index); + value = line.substr(index, index2-index); + CCAssert(atoi(value.c_str()) == 1, "CCBitfontAtlas: only supports 1 page"); + + // packed (ignore) What does this mean ?? +} +void CCBMFontConfiguration::parseCharacterDefinition(std::string line, ccBMFontDef *characterDefinition) +{ + ////////////////////////////////////////////////////////////////////////// + // line to parse: + // char id=32 x=0 y=0 width=0 height=0 xoffset=0 yoffset=44 xadvance=14 page=0 chnl=0 + ////////////////////////////////////////////////////////////////////////// + + // Character ID + int index = line.find("id="); + int index2 = line.find(' ', index); + std::string value = line.substr(index, index2-index); + sscanf(value.c_str(), "id=%u", &characterDefinition->charID); + + // Character x + index = line.find("x="); + index2 = line.find(' ', index); + value = line.substr(index, index2-index); + sscanf(value.c_str(), "x=%f", &characterDefinition->rect.origin.x); + // Character y + index = line.find("y="); + index2 = line.find(' ', index); + value = line.substr(index, index2-index); + sscanf(value.c_str(), "y=%f", &characterDefinition->rect.origin.y); + // Character width + index = line.find("width="); + index2 = line.find(' ', index); + value = line.substr(index, index2-index); + sscanf(value.c_str(), "width=%f", &characterDefinition->rect.size.width); + // Character height + index = line.find("height="); + index2 = line.find(' ', index); + value = line.substr(index, index2-index); + sscanf(value.c_str(), "height=%f", &characterDefinition->rect.size.height); + // Character xoffset + index = line.find("xoffset="); + index2 = line.find(' ', index); + value = line.substr(index, index2-index); + sscanf(value.c_str(), "xoffset=%d", &characterDefinition->xOffset); + // Character yoffset + index = line.find("yoffset="); + index2 = line.find(' ', index); + value = line.substr(index, index2-index); + sscanf(value.c_str(), "yoffset=%d", &characterDefinition->yOffset); + // Character xadvance + index = line.find("xadvance="); + index2 = line.find(' ', index); + value = line.substr(index, index2-index); + sscanf(value.c_str(), "xadvance=%d", &characterDefinition->xAdvance); +} +void CCBMFontConfiguration::parseKerningCapacity(std::string line) +{ + // When using uthash there is not need to parse the capacity. + + // CCAssert(!kerningDictionary, @"dictionary already initialized"); + // + // // Break the values for this line up using = + // CCMutableArray *values = [line componentsSeparatedByString:@"="]; + // NSEnumerator *nse = [values objectEnumerator]; + // CCString *propertyValue; + // + // // We need to move past the first entry in the array before we start assigning values + // [nse nextObject]; + // + // // count + // propertyValue = [nse nextObject]; + // int capacity = [propertyValue intValue]; + // + // if( capacity != -1 ) + // kerningDictionary = ccHashSetNew(capacity, targetSetEql); +} +void CCBMFontConfiguration::parseKerningEntry(std::string line) +{ + ////////////////////////////////////////////////////////////////////////// + // line to parse: + // kerning first=121 second=44 amount=-7 + ////////////////////////////////////////////////////////////////////////// + + // first + int first; + int index = line.find("first="); + int index2 = line.find(' ', index); + std::string value = line.substr(index, index2-index); + sscanf(value.c_str(), "first=%d", &first); + + // second + int second; + index = line.find("second="); + index2 = line.find(' ', index); + value = line.substr(index, index2-index); + sscanf(value.c_str(), "second=%d", &second); + + // amount + int amount; + index = line.find("amount="); + index2 = line.find(' ', index); + value = line.substr(index, index2-index); + sscanf(value.c_str(), "amount=%d", &amount); + + tKerningHashElement *element = (tKerningHashElement *)calloc( sizeof( *element ), 1 ); + element->amount = amount; + element->key = (first<<16) | (second&0xffff); + HASH_ADD_INT(m_pKerningDictionary,key, element); +} +// +//CCLabelBMFont +// + +//LabelBMFont - Purge Cache +void CCLabelBMFont::purgeCachedData() +{ + FNTConfigRemoveCache(); +} + +//LabelBMFont - Creation & Init +CCLabelBMFont *CCLabelBMFont::labelWithString(const char *str, const char *fntFile) +{ + CCLabelBMFont *pRet = new CCLabelBMFont(); + if(pRet && pRet->initWithString(str, fntFile)) + { + pRet->autorelease(); + return pRet; + } + CC_SAFE_DELETE(pRet); + return NULL; +} + +bool CCLabelBMFont::initWithString(const char *theString, const char *fntFile) +{ + CCAssert(theString != NULL, ""); + CC_SAFE_RELEASE(m_pConfiguration);// allow re-init + m_pConfiguration = FNTConfigLoadFile(fntFile); + m_pConfiguration->retain(); + CCAssert( m_pConfiguration, "Error creating config for LabelBMFont"); + + if (CCSpriteBatchNode::initWithFile(m_pConfiguration->m_sAtlasName.c_str(), strlen(theString))) + { + m_cOpacity = 255; + m_tColor = ccWHITE; + m_tContentSize = CCSizeZero; + m_bIsOpacityModifyRGB = m_pobTextureAtlas->getTexture()->getHasPremultipliedAlpha(); + setAnchorPoint(ccp(0.5f, 0.5f)); + this->setString(theString); + return true; + } + return false; +} +CCLabelBMFont::~CCLabelBMFont() +{ + m_sString.clear(); + CC_SAFE_RELEASE(m_pConfiguration); +} + +// LabelBMFont - Atlas generation +int CCLabelBMFont::kerningAmountForFirst(unsigned short first, unsigned short second) +{ + int ret = 0; + unsigned int key = (first<<16) | (second & 0xffff); + + if( m_pConfiguration->m_pKerningDictionary ) { + tKerningHashElement *element = NULL; + HASH_FIND_INT(m_pConfiguration->m_pKerningDictionary, &key, element); + if(element) + ret = element->amount; + } + return ret; +} + +static int cc_wcslen(const unsigned short* str) +{ + int i=0; + while(*str++) i++; + return i; +} + +/* Code from GLIB gutf8.c starts here. */ + +#define UTF8_COMPUTE(Char, Mask, Len) \ + if (Char < 128) \ + { \ + Len = 1; \ + Mask = 0x7f; \ + } \ + else if ((Char & 0xe0) == 0xc0) \ + { \ + Len = 2; \ + Mask = 0x1f; \ + } \ + else if ((Char & 0xf0) == 0xe0) \ + { \ + Len = 3; \ + Mask = 0x0f; \ + } \ + else if ((Char & 0xf8) == 0xf0) \ + { \ + Len = 4; \ + Mask = 0x07; \ + } \ + else if ((Char & 0xfc) == 0xf8) \ + { \ + Len = 5; \ + Mask = 0x03; \ + } \ + else if ((Char & 0xfe) == 0xfc) \ + { \ + Len = 6; \ + Mask = 0x01; \ + } \ + else \ + Len = -1; + +#define UTF8_LENGTH(Char) \ + ((Char) < 0x80 ? 1 : \ + ((Char) < 0x800 ? 2 : \ + ((Char) < 0x10000 ? 3 : \ + ((Char) < 0x200000 ? 4 : \ + ((Char) < 0x4000000 ? 5 : 6))))) + + +#define UTF8_GET(Result, Chars, Count, Mask, Len) \ + (Result) = (Chars)[0] & (Mask); \ + for ((Count) = 1; (Count) < (Len); ++(Count)) \ + { \ + if (((Chars)[(Count)] & 0xc0) != 0x80) \ + { \ + (Result) = -1; \ + break; \ + } \ + (Result) <<= 6; \ + (Result) |= ((Chars)[(Count)] & 0x3f); \ + } + +#define UNICODE_VALID(Char) \ + ((Char) < 0x110000 && \ + (((Char) & 0xFFFFF800) != 0xD800) && \ + ((Char) < 0xFDD0 || (Char) > 0xFDEF) && \ + ((Char) & 0xFFFE) != 0xFFFE) + + +static const char utf8_skip_data[256] = { + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 2, 2, 2, 2, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, + 5, 5, 5, 6, 6, 1, 1 +}; + +static const char *const g_utf8_skip = utf8_skip_data; + +#define cc_utf8_next_char(p) (char *)((p) + g_utf8_skip[*(unsigned char *)(p)]) + +/* + * g_utf8_strlen: + * @p: pointer to the start of a UTF-8 encoded string. + * @max: the maximum number of bytes to examine. If @max + * is less than 0, then the string is assumed to be + * nul-terminated. If @max is 0, @p will not be examined and + * may be %NULL. + * + * Returns the length of the string in characters. + * + * Return value: the length of the string in characters + **/ +static long +cc_utf8_strlen (const char * p, int max) +{ + long len = 0; + const char *start = p; + + if (!(p != NULL || max == 0)) + { + return 0; + } + + if (max < 0) + { + while (*p) + { + p = cc_utf8_next_char (p); + ++len; + } + } + else + { + if (max == 0 || !*p) + return 0; + + p = cc_utf8_next_char (p); + + while (p - start < max && *p) + { + ++len; + p = cc_utf8_next_char (p); + } + + /* only do the last len increment if we got a complete + * char (don't count partial chars) + */ + if (p - start == max) + ++len; + } + + return len; +} + +/* + * g_utf8_get_char: + * @p: a pointer to Unicode character encoded as UTF-8 + * + * Converts a sequence of bytes encoded as UTF-8 to a Unicode character. + * If @p does not point to a valid UTF-8 encoded character, results are + * undefined. If you are not sure that the bytes are complete + * valid Unicode characters, you should use g_utf8_get_char_validated() + * instead. + * + * Return value: the resulting character + **/ +static unsigned int +cc_utf8_get_char (const char * p) +{ + int i, mask = 0, len; + unsigned int result; + unsigned char c = (unsigned char) *p; + + UTF8_COMPUTE (c, mask, len); + if (len == -1) + return (unsigned int) - 1; + UTF8_GET (result, p, i, mask, len); + + return result; +} + + +void CCLabelBMFont::createFontChars() +{ + int nextFontPositionX = 0; + int nextFontPositionY = 0; + unsigned short prev = -1; + int kerningAmount = 0; + + CCSize tmpSize = CCSizeZero; + + int longestLine = 0; + unsigned int totalHeight = 0; + + unsigned int quantityOfLines = 1; + + if (0 == m_sString.length()) + { + return; + } + + int utf8len = cc_utf8_strlen(m_sString.c_str(), -1); + if (utf8len == 0) + { + return; + } + + unsigned short* pUniStr = new unsigned short[utf8len+1]; + pUniStr[utf8len] = 0; + + const char* p = m_sString.c_str(); + + for (int i = 0; i < utf8len; ++i) + { + pUniStr[i] = cc_utf8_get_char(p); + p = cc_utf8_next_char (p); + } + + unsigned int stringLen = cc_wcslen(pUniStr); + + for (unsigned int i = 0; i < stringLen - 1; ++i) + { + unsigned short c = pUniStr[i]; + if (c == '\n') + { + quantityOfLines++; + } + } + + totalHeight = m_pConfiguration->m_uCommonHeight * quantityOfLines; + nextFontPositionY = -(m_pConfiguration->m_uCommonHeight - m_pConfiguration->m_uCommonHeight * quantityOfLines); + + for (unsigned int i= 0; i < stringLen; i++) + { + unsigned short c = pUniStr[i]; + + if (c == '\n') + { + nextFontPositionX = 0; + nextFontPositionY -= m_pConfiguration->m_uCommonHeight; + continue; + } + + std::map::iterator it = m_pConfiguration->m_pBitmapFontArray->find(c); + CCAssert(it != m_pConfiguration->m_pBitmapFontArray->end(), "LabelBMFont: character is not supported"); + + kerningAmount = this->kerningAmountForFirst(prev, c); + + const ccBMFontDef& fontDef = (*(m_pConfiguration->m_pBitmapFontArray))[c]; + + CCRect rect = fontDef.rect; + + CCSprite *fontChar; + + fontChar = (CCSprite*)(this->getChildByTag(i)); + if( ! fontChar ) + { + fontChar = new CCSprite(); + fontChar->initWithTexture(m_pobTextureAtlas->getTexture(), rect); + this->addChild(fontChar, 0, i); + fontChar->release(); + } + else + { + // reusing fonts + fontChar->setTextureRect(rect, false, rect.size); + + // restore to default in case they were modified + fontChar->setIsVisible(true); + fontChar->setOpacity(255); + } + + float yOffset = (float)(m_pConfiguration->m_uCommonHeight) - fontDef.yOffset; + CCPoint fontPos = ccp( (float)nextFontPositionX + fontDef.xOffset + fontDef.rect.size.width*0.5f + kerningAmount, (float)nextFontPositionY + yOffset - rect.size.height*0.5f ); + fontChar->setPosition(CC_POINT_PIXELS_TO_POINTS(fontPos)); + + // NSLog(@"position.y: %f", fontChar.position.y); + + // update kerning + nextFontPositionX += (*(m_pConfiguration->m_pBitmapFontArray))[c].xAdvance + kerningAmount; + prev = c; + + // Apply label properties + fontChar->setIsOpacityModifyRGB(m_bIsOpacityModifyRGB); + // Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on + fontChar->setColor(m_tColor); + + // only apply opaccity if it is different than 255 ) + // to prevent modifying the color too (issue #610) + if( m_cOpacity != 255 ) + { + fontChar->setOpacity(m_cOpacity); + } + + if (longestLine < nextFontPositionX) + { + longestLine = nextFontPositionX; + } + } + + tmpSize.width = (float) longestLine; + tmpSize.height = (float) totalHeight; + + this->setContentSize(tmpSize); + + CC_SAFE_DELETE_ARRAY(pUniStr); +} + +//LabelBMFont - CCLabelProtocol protocol +void CCLabelBMFont::setString(const char *newString) +{ + m_sString.clear(); + m_sString = newString; + + if (m_pChildren && m_pChildren->count() != 0) + { + CCObject* child; + CCARRAY_FOREACH(m_pChildren, child) + { + CCNode* pNode = (CCNode*) child; + if (pNode) + { + pNode->setIsVisible(false); + } + } + } + this->createFontChars(); +} + +const char* CCLabelBMFont::getString(void) +{ + return m_sString.c_str(); +} + +void CCLabelBMFont::setCString(const char *label) +{ + setString(label); +} + +//LabelBMFont - CCRGBAProtocol protocol +void CCLabelBMFont::setColor(const ccColor3B& var) +{ + m_tColor = var; + if (m_pChildren && m_pChildren->count() != 0) + { + CCObject* child; + CCARRAY_FOREACH(m_pChildren, child) + { + CCSprite* pNode = (CCSprite*) child; + if (pNode) + { + pNode->setColor(m_tColor); + } + } + } +} +const ccColor3B& CCLabelBMFont::getColor() +{ + return m_tColor; +} +void CCLabelBMFont::setOpacity(GLubyte var) +{ + m_cOpacity = var; + + if (m_pChildren && m_pChildren->count() != 0) + { + CCObject* child; + CCARRAY_FOREACH(m_pChildren, child) + { + CCNode* pNode = (CCNode*) child; + if (pNode) + { + CCRGBAProtocol *pRGBAProtocol = dynamic_cast(pNode); + if (pRGBAProtocol) + { + pRGBAProtocol->setOpacity(m_cOpacity); + } + } + } + } +} +GLubyte CCLabelBMFont::getOpacity() +{ + return m_cOpacity; +} +void CCLabelBMFont::setIsOpacityModifyRGB(bool var) +{ + m_bIsOpacityModifyRGB = var; + if (m_pChildren && m_pChildren->count() != 0) + { + CCObject* child; + CCARRAY_FOREACH(m_pChildren, child) + { + CCNode* pNode = (CCNode*) child; + if (pNode) + { + CCRGBAProtocol *pRGBAProtocol = dynamic_cast(pNode); + if (pRGBAProtocol) + { + pRGBAProtocol->setIsOpacityModifyRGB(m_bIsOpacityModifyRGB); + } + } + } + } +} +bool CCLabelBMFont::getIsOpacityModifyRGB() +{ + return m_bIsOpacityModifyRGB; +} + +// LabelBMFont - AnchorPoint +void CCLabelBMFont::setAnchorPoint(const CCPoint& point) +{ + if( ! CCPoint::CCPointEqualToPoint(point, m_tAnchorPoint) ) + { + CCSpriteBatchNode::setAnchorPoint(point); + this->createFontChars(); + } +} + +//LabelBMFont - Debug draw +#if CC_LABELBMFONT_DEBUG_DRAW +void CCLabelBMFont::draw() +{ + CCSpriteBatchNode::draw(); + const CCSize& s = this->getContentSize(); + CCPoint vertices[4]={ + ccp(0,0),ccp(s.width,0), + ccp(s.width,s.height),ccp(0,s.height), + }; + ccDrawPoly(vertices, 4, true); +} +#endif // CC_LABELBMFONT_DEBUG_DRAW + +NS_CC_END diff --git a/cocos2dx/layers_scenes_transitions_nodes/CCLayer.cpp b/cocos2dx/layers_scenes_transitions_nodes/CCLayer.cpp index 174a63fb5f..f4c209e64a 100644 --- a/cocos2dx/layers_scenes_transitions_nodes/CCLayer.cpp +++ b/cocos2dx/layers_scenes_transitions_nodes/CCLayer.cpp @@ -745,7 +745,8 @@ void CCLayerMultiplex::addLayer(CCLayer* layer) bool CCLayerMultiplex::initWithLayer(CCLayer* layer) { - m_pLayers = new CCMutableArray(1); + m_pLayers = CCArray::array(); + m_pLayers->retain(); m_pLayers->addObject(layer); m_nEnabledLayer = 0; this->addChild(layer); @@ -754,8 +755,8 @@ bool CCLayerMultiplex::initWithLayer(CCLayer* layer) bool CCLayerMultiplex::initWithLayers(CCLayer *layer, va_list params) { - m_pLayers = new CCMutableArray(5); - //m_pLayers->retain(); + m_pLayers = CCArray::arrayWithCapacity(5); + m_pLayers->retain(); m_pLayers->addObject(layer); @@ -766,7 +767,7 @@ bool CCLayerMultiplex::initWithLayers(CCLayer *layer, va_list params) } m_nEnabledLayer = 0; - this->addChild(m_pLayers->getObjectAtIndex(m_nEnabledLayer)); + this->addChild((CCNode*)m_pLayers->objectAtIndex(m_nEnabledLayer)); return true; } @@ -776,24 +777,24 @@ void CCLayerMultiplex::switchTo(unsigned int n) { CCAssert( n < m_pLayers->count(), "Invalid index in MultiplexLayer switchTo message" ); - this->removeChild(m_pLayers->getObjectAtIndex(m_nEnabledLayer), true); + this->removeChild((CCNode*)m_pLayers->objectAtIndex(m_nEnabledLayer), true); m_nEnabledLayer = n; - this->addChild(m_pLayers->getObjectAtIndex(n)); + this->addChild((CCNode*)m_pLayers->objectAtIndex(n)); } void CCLayerMultiplex::switchToAndReleaseMe(unsigned int n) { CCAssert( n < m_pLayers->count(), "Invalid index in MultiplexLayer switchTo message" ); - this->removeChild(m_pLayers->getObjectAtIndex(m_nEnabledLayer), true); + this->removeChild((CCNode*)m_pLayers->objectAtIndex(m_nEnabledLayer), true); //[layers replaceObjectAtIndex:enabledLayer withObject:[NSNull null]]; m_pLayers->replaceObjectAtIndex(m_nEnabledLayer, NULL); m_nEnabledLayer = n; - this->addChild(m_pLayers->getObjectAtIndex(n)); + this->addChild((CCNode*)m_pLayers->objectAtIndex(n)); } }//namespace cocos2d diff --git a/cocos2dx/menu_nodes/CCMenuItem.cpp b/cocos2dx/menu_nodes/CCMenuItem.cpp index 4c85eedd3b..5f9d5c1b3c 100644 --- a/cocos2dx/menu_nodes/CCMenuItem.cpp +++ b/cocos2dx/menu_nodes/CCMenuItem.cpp @@ -33,788 +33,796 @@ THE SOFTWARE. #include "CCScriptSupport.h" #include -namespace cocos2d{ +NS_CC_BEGIN - static unsigned int _fontSize = kCCItemSize; - static std::string _fontName = "Marker Felt"; - static bool _fontNameRelease = false; - - const unsigned int kCurrentItem = 0xc0c05001; - const unsigned int kZoomActionTag = 0xc0c05002; - - const unsigned int kNormalTag = 0x1; - const unsigned int kSelectedTag = 0x2; - const unsigned int kDisableTag = 0x3; - // - // CCMenuItem - // - CCMenuItem * CCMenuItem::itemWithTarget(CCObject *rec, SEL_MenuHandler selector) +static unsigned int _fontSize = kCCItemSize; +static std::string _fontName = "Marker Felt"; +static bool _fontNameRelease = false; + +const unsigned int kCurrentItem = 0xc0c05001; +const unsigned int kZoomActionTag = 0xc0c05002; + +const unsigned int kNormalTag = 0x1; +const unsigned int kSelectedTag = 0x2; +const unsigned int kDisableTag = 0x3; +// +// CCMenuItem +// +CCMenuItem * CCMenuItem::itemWithTarget(CCObject *rec, SEL_MenuHandler selector) +{ + CCMenuItem *pRet = new CCMenuItem(); + pRet->initWithTarget(rec, selector); + pRet->autorelease(); + return pRet; +} +bool CCMenuItem::initWithTarget(CCObject *rec, SEL_MenuHandler selector) +{ + setAnchorPoint(ccp(0.5f, 0.5f)); + m_pListener = rec; + m_pfnSelector = selector; + m_bIsEnabled = true; + m_bIsSelected = false; + return true; +} + +CCMenuItem::~CCMenuItem() +{ + unregisterScriptHandler(); +} + +void CCMenuItem::selected() +{ + m_bIsSelected = true; +} + +void CCMenuItem::unselected() +{ + m_bIsSelected = false; +} + +void CCMenuItem::registerScriptHandler(int nHandler) +{ + unregisterScriptHandler(); + m_nScriptHandler = nHandler; + LUALOG("[LUA] Add CCMenuItem script handler: %d", m_nScriptHandler); +} + +void CCMenuItem::unregisterScriptHandler(void) +{ + if (m_nScriptHandler) { - CCMenuItem *pRet = new CCMenuItem(); - pRet->initWithTarget(rec, selector); - pRet->autorelease(); - return pRet; + CCScriptEngineManager::sharedManager()->getScriptEngine()->removeLuaHandler(m_nScriptHandler); + LUALOG("[LUA] Remove CCMenuItem script handler: %d", m_nScriptHandler); + m_nScriptHandler = 0; } - bool CCMenuItem::initWithTarget(CCObject *rec, SEL_MenuHandler selector) - { - setAnchorPoint(ccp(0.5f, 0.5f)); - m_pListener = rec; - m_pfnSelector = selector; - m_bIsEnabled = true; - m_bIsSelected = false; - return true; - } - - CCMenuItem::~CCMenuItem() - { - unregisterScriptHandler(); - } - - void CCMenuItem::selected() - { - m_bIsSelected = true; - } - - void CCMenuItem::unselected() - { - m_bIsSelected = false; - } - - void CCMenuItem::registerScriptHandler(int nHandler) - { - unregisterScriptHandler(); - m_nScriptHandler = nHandler; - LUALOG("[LUA] Add CCMenuItem script handler: %d", m_nScriptHandler); - } - - void CCMenuItem::unregisterScriptHandler(void) +} + +void CCMenuItem::activate() +{ + if (m_bIsEnabled) { + if (m_pListener && m_pfnSelector) + { + (m_pListener->*m_pfnSelector)(this); + } + if (m_nScriptHandler) { - CCScriptEngineManager::sharedManager()->getScriptEngine()->removeLuaHandler(m_nScriptHandler); - LUALOG("[LUA] Remove CCMenuItem script handler: %d", m_nScriptHandler); - m_nScriptHandler = 0; + CCScriptEngineManager::sharedManager()->getScriptEngine()->executeFunctionWithIntegerData(m_nScriptHandler, getTag()); } } - - void CCMenuItem::activate() - { - if (m_bIsEnabled) - { - if (m_pListener && m_pfnSelector) - { - (m_pListener->*m_pfnSelector)(this); - } - - if (m_nScriptHandler) - { - CCScriptEngineManager::sharedManager()->getScriptEngine()->executeFunctionWithIntegerData(m_nScriptHandler, getTag()); - } - } - } - - void CCMenuItem::setIsEnabled(bool enabled) - { - m_bIsEnabled = enabled; - } - - bool CCMenuItem::getIsEnabled() - { - return m_bIsEnabled; - } - - CCRect CCMenuItem::rect() - { - return CCRectMake( m_tPosition.x - m_tContentSize.width * m_tAnchorPoint.x, - m_tPosition.y - m_tContentSize.height * m_tAnchorPoint.y, - m_tContentSize.width, m_tContentSize.height); - } - - bool CCMenuItem::getIsSelected() - { - return m_bIsSelected; - } - - void CCMenuItem::setTarget(CCObject *rec, SEL_MenuHandler selector) - { - m_pListener = rec; - m_pfnSelector = selector; - } - - // - //CCMenuItemLabel - // - const ccColor3B& CCMenuItemLabel::getDisabledColor() - { - return m_tDisabledColor; - } - void CCMenuItemLabel::setDisabledColor(const ccColor3B& var) - { - m_tDisabledColor = var; - } - CCNode *CCMenuItemLabel::getLabel() - { - return m_pLabel; - } - void CCMenuItemLabel::setLabel(CCNode* var) - { - if (var) - { - addChild(var); - var->setAnchorPoint(ccp(0, 0)); - setContentSize(var->getContentSize()); - } - - if (m_pLabel) - { - removeChild(m_pLabel, true); - } - - m_pLabel = var; - } - CCMenuItemLabel * CCMenuItemLabel::itemWithLabel(CCNode*label, CCObject* target, SEL_MenuHandler selector) - { - CCMenuItemLabel *pRet = new CCMenuItemLabel(); - pRet->initWithLabel(label, target, selector); - pRet->autorelease(); - return pRet; - } - CCMenuItemLabel* CCMenuItemLabel::itemWithLabel(CCNode *label) - { - CCMenuItemLabel *pRet = new CCMenuItemLabel(); - pRet->initWithLabel(label, NULL, NULL); - pRet->autorelease(); - return pRet; - } - bool CCMenuItemLabel::initWithLabel(CCNode* label, CCObject* target, SEL_MenuHandler selector) - { - CCMenuItem::initWithTarget(target, selector); - m_fOriginalScale = 1.0f; - m_tColorBackup = ccWHITE; - m_tDisabledColor = ccc3(126,126,126); - this->setLabel(label); - return true; - } - CCMenuItemLabel::~CCMenuItemLabel() - { - } - void CCMenuItemLabel::setString(const char * label) - { - dynamic_cast(m_pLabel)->setString(label); - this->setContentSize(m_pLabel->getContentSize()); - } - void CCMenuItemLabel::activate() - { - if(m_bIsEnabled) - { - this->stopAllActions(); - this->setScale( m_fOriginalScale ); - CCMenuItem::activate(); - } - } - void CCMenuItemLabel::selected() - { - // subclass to change the default action - if(m_bIsEnabled) - { - CCMenuItem::selected(); - - CCAction *action = getActionByTag(kZoomActionTag); - if (action) - { - this->stopAction(action); - } - else - { - m_fOriginalScale = this->getScale(); - } - - CCAction *zoomAction = CCScaleTo::actionWithDuration(0.1f, m_fOriginalScale * 1.2f); - zoomAction->setTag(kZoomActionTag); - this->runAction(zoomAction); - } - } - void CCMenuItemLabel::unselected() - { - // subclass to change the default action - if(m_bIsEnabled) - { - CCMenuItem::unselected(); - this->stopActionByTag(kZoomActionTag); - CCAction *zoomAction = CCScaleTo::actionWithDuration(0.1f, m_fOriginalScale); - zoomAction->setTag(kZoomActionTag); - this->runAction(zoomAction); - } - } - void CCMenuItemLabel::setIsEnabled(bool enabled) - { - if( m_bIsEnabled != enabled ) - { - if(enabled == false) - { - m_tColorBackup = dynamic_cast(m_pLabel)->getColor(); - dynamic_cast(m_pLabel)->setColor(m_tDisabledColor); - } - else - { - dynamic_cast(m_pLabel)->setColor(m_tColorBackup); - } - } - CCMenuItem::setIsEnabled(enabled); - } - void CCMenuItemLabel::setOpacity(GLubyte opacity) - { - dynamic_cast(m_pLabel)->setOpacity(opacity); - } - GLubyte CCMenuItemLabel::getOpacity() - { - return dynamic_cast(m_pLabel)->getOpacity(); - } - void CCMenuItemLabel::setColor(const ccColor3B& color) - { - dynamic_cast(m_pLabel)->setColor(color); - } - const ccColor3B& CCMenuItemLabel::getColor() - { - return dynamic_cast(m_pLabel)->getColor(); - } - - // - //CCMenuItemAtlasFont - // - CCMenuItemAtlasFont * CCMenuItemAtlasFont::itemWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap) - { - return CCMenuItemAtlasFont::itemWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, NULL, NULL); - } - - CCMenuItemAtlasFont * CCMenuItemAtlasFont::itemWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, CCObject* target, SEL_MenuHandler selector) - { - CCMenuItemAtlasFont *pRet = new CCMenuItemAtlasFont(); - pRet->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, target, selector); - pRet->autorelease(); - return pRet; - } - bool CCMenuItemAtlasFont::initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, CCObject* target, SEL_MenuHandler selector) - { - CCAssert( value != NULL && strlen(value) != 0, "value length must be greater than 0"); - CCLabelAtlas *label = new CCLabelAtlas(); - label->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap); - label->autorelease(); - if (CCMenuItemLabel::initWithLabel(label, target, selector)) - { - // do something ? - } - return true; - } - // - //CCMenuItemFont - // - void CCMenuItemFont::setFontSize(unsigned int s) - { - _fontSize = s; - } - unsigned int CCMenuItemFont::fontSize() - { - return _fontSize; - } - void CCMenuItemFont::setFontName(const char *name) - { - if( _fontNameRelease ) - { - _fontName.clear(); - } - _fontName = name; - _fontNameRelease = true; - } - const char * CCMenuItemFont::fontName() - { - return _fontName.c_str(); - } - CCMenuItemFont * CCMenuItemFont::itemWithString(const char *value, CCObject* target, SEL_MenuHandler selector) - { - CCMenuItemFont *pRet = new CCMenuItemFont(); - pRet->initWithString(value, target, selector); - pRet->autorelease(); - return pRet; - } - CCMenuItemFont * CCMenuItemFont::itemWithString(const char *value) - { - CCMenuItemFont *pRet = new CCMenuItemFont(); - pRet->initWithString(value, NULL, NULL); - pRet->autorelease(); - return pRet; - } - bool CCMenuItemFont::initWithString(const char *value, CCObject* target, SEL_MenuHandler selector) - { - CCAssert( value != NULL && strlen(value) != 0, "Value length must be greater than 0"); - - m_strFontName = _fontName; - m_uFontSize = _fontSize; - - CCLabelTTF *label = CCLabelTTF::labelWithString(value, m_strFontName.c_str(), (float)m_uFontSize); - if (CCMenuItemLabel::initWithLabel(label, target, selector)) - { - // do something ? - } - return true; - } - - void CCMenuItemFont::recreateLabel() - { - CCLabelTTF *label = CCLabelTTF::labelWithString(dynamic_cast(m_pLabel)->getString(), - m_strFontName.c_str(), (float)m_uFontSize); - this->setLabel(label); - } - - void CCMenuItemFont::setFontSizeObj(unsigned int s) - { - m_uFontSize = s; - recreateLabel(); - } - - unsigned int CCMenuItemFont::fontSizeObj() - { - return m_uFontSize; - } - - void CCMenuItemFont::setFontNameObj(const char* name) - { - m_strFontName = name; - recreateLabel(); - } - - const char* CCMenuItemFont::fontNameObj() - { - return m_strFontName.c_str(); - } - - // - //CCMenuItemSprite - // - CCNode * CCMenuItemSprite::getNormalImage() - { - return m_pNormalImage; - } - void CCMenuItemSprite::setNormalImage(CCNode* var) - { - if (var) - { - addChild(var, 0, kNormalTag); - var->setAnchorPoint(ccp(0, 0)); - var->setIsVisible(true); - } - - if (m_pNormalImage) - { - removeChild(m_pNormalImage, true); - } - - m_pNormalImage = var; - this->setContentSize(m_pNormalImage->getContentSize()); - } - CCNode * CCMenuItemSprite::getSelectedImage() - { - return m_pSelectedImage; - } - void CCMenuItemSprite::setSelectedImage(CCNode* var) - { - if (var) - { - addChild(var, 0, kSelectedTag); - var->setAnchorPoint(ccp(0, 0)); - var->setIsVisible(false); - } - - if (m_pSelectedImage) - { - removeChild(m_pSelectedImage, true); - } - - m_pSelectedImage = var; - } - CCNode * CCMenuItemSprite::getDisabledImage() - { - return m_pDisabledImage; - } - void CCMenuItemSprite::setDisabledImage(CCNode* var) - { - if (var) - { - addChild(var, 0, kDisableTag); - var->setAnchorPoint(ccp(0, 0)); - var->setIsVisible(false); - } - - if (m_pDisabledImage) - { - removeChild(m_pDisabledImage, true); - } - - m_pDisabledImage = var; - } - // - //CCMenuItemSprite - CCRGBAProtocol protocol - // - void CCMenuItemSprite::setOpacity(GLubyte opacity) - { - dynamic_cast(m_pNormalImage)->setOpacity(opacity); - - if (m_pSelectedImage) - { - dynamic_cast(m_pSelectedImage)->setOpacity(opacity); - } - - if (m_pDisabledImage) - { - dynamic_cast(m_pDisabledImage)->setOpacity(opacity); - } - } - void CCMenuItemSprite::setColor(const ccColor3B& color) - { - dynamic_cast(m_pNormalImage)->setColor(color); - - if (m_pSelectedImage) - { - dynamic_cast(m_pSelectedImage)->setColor(color); - } - - if (m_pDisabledImage) - { - dynamic_cast(m_pDisabledImage)->setColor(color); - } - } - GLubyte CCMenuItemSprite::getOpacity() - { - return dynamic_cast(m_pNormalImage)->getOpacity(); - } - const ccColor3B& CCMenuItemSprite::getColor() - { - return dynamic_cast(m_pNormalImage)->getColor(); - } - CCMenuItemSprite * CCMenuItemSprite::itemWithNormalSprite(CCNode* normalSprite, CCNode* selectedSprite, CCNode* disabledSprite) - { - return CCMenuItemSprite::itemWithNormalSprite(normalSprite, selectedSprite, disabledSprite, NULL, NULL); - } - CCMenuItemSprite * CCMenuItemSprite::itemWithNormalSprite(CCNode* normalSprite, CCNode* selectedSprite, CCObject* target, SEL_MenuHandler selector) - { - return CCMenuItemSprite::itemWithNormalSprite(normalSprite, selectedSprite, NULL, target, selector); - } - CCMenuItemSprite * CCMenuItemSprite::itemWithNormalSprite(CCNode *normalSprite, CCNode *selectedSprite, CCNode *disabledSprite, CCObject *target, SEL_MenuHandler selector) - { - CCMenuItemSprite *pRet = new CCMenuItemSprite(); - pRet->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, target, selector); - pRet->autorelease(); - return pRet; - } - bool CCMenuItemSprite::initWithNormalSprite(CCNode* normalSprite, CCNode* selectedSprite, CCNode* disabledSprite, CCObject* target, SEL_MenuHandler selector) - { - CCAssert(normalSprite != NULL, ""); - CCMenuItem::initWithTarget(target, selector); - setNormalImage(normalSprite); - setSelectedImage(selectedSprite); - setDisabledImage(disabledSprite); - - this->setContentSize(m_pNormalImage->getContentSize()); - return true; - } - - /** - @since v0.99.5 - */ - void CCMenuItemSprite::selected() - { - CCMenuItem::selected(); - - if (m_pDisabledImage) - { - m_pDisabledImage->setIsVisible(false); - } - - if (m_pSelectedImage) - { - m_pNormalImage->setIsVisible(false); - m_pSelectedImage->setIsVisible(true); - } - else - { - m_pNormalImage->setIsVisible(true); - } - } - - void CCMenuItemSprite::unselected() - { - CCMenuItem::unselected(); - - m_pNormalImage->setIsVisible(true); - - if (m_pSelectedImage) - { - m_pSelectedImage->setIsVisible(false); - } - - if (m_pDisabledImage) - { - m_pDisabledImage->setIsVisible(false); - } - } - - void CCMenuItemSprite::setIsEnabled(bool bEnabled) - { - CCMenuItem::setIsEnabled(bEnabled); - - if (m_pSelectedImage) - { - m_pSelectedImage->setIsVisible(false); - } - - if (bEnabled) - { - m_pNormalImage->setIsVisible(true); - - if (m_pDisabledImage) - { - m_pDisabledImage->setIsVisible(false); - } - } - else - { - if (m_pDisabledImage) - { - m_pDisabledImage->setIsVisible(true); - m_pNormalImage->setIsVisible(false); - } - else - { - m_pNormalImage->setIsVisible(true); - } - } - } - - CCMenuItemImage * CCMenuItemImage::itemWithNormalImage(const char *normalImage, const char *selectedImage) - { - return CCMenuItemImage::itemWithNormalImage(normalImage, selectedImage, NULL, NULL, NULL); - } - CCMenuItemImage * CCMenuItemImage::itemWithNormalImage(const char *normalImage, const char *selectedImage, CCObject* target, SEL_MenuHandler selector) - { - return CCMenuItemImage::itemWithNormalImage(normalImage, selectedImage, NULL, target, selector); - } - CCMenuItemImage * CCMenuItemImage::itemWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, CCObject* target, SEL_MenuHandler selector) - { - CCMenuItemImage *pRet = new CCMenuItemImage(); - if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, target, selector)) - { - pRet->autorelease(); - return pRet; - } - CC_SAFE_DELETE(pRet); - return NULL; - } - CCMenuItemImage * CCMenuItemImage::itemWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage) - { - CCMenuItemImage *pRet = new CCMenuItemImage(); - if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, NULL, NULL)) - { - pRet->autorelease(); - return pRet; - } - CC_SAFE_DELETE(pRet); - return NULL; - } - bool CCMenuItemImage::initWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, CCObject* target, SEL_MenuHandler selector) - { - CCNode *normalSprite = CCSprite::spriteWithFile(normalImage); - CCNode *selectedSprite = NULL; - CCNode *disabledSprite = NULL; - - if (selectedImage) - { - selectedSprite = CCSprite::spriteWithFile(selectedImage); - } - - if(disabledImage) - { - disabledSprite = CCSprite::spriteWithFile(disabledImage); - } - return initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, target, selector); - } - // - // Setter of sprite frames - // - void CCMenuItemImage::setNormalSpriteFrame(CCSpriteFrame * frame) - { - setNormalImage(CCSprite::spriteWithSpriteFrame(frame)); - } - - void CCMenuItemImage::setSelectedSpriteFrame(CCSpriteFrame * frame) - { - setSelectedImage(CCSprite::spriteWithSpriteFrame(frame)); - } - - void CCMenuItemImage::setDisabledSpriteFrame(CCSpriteFrame * frame) - { - setDisabledImage(CCSprite::spriteWithSpriteFrame(frame)); - } +} - // - // MenuItemToggle - // - void CCMenuItemToggle::setSubItems(CCMutableArray* var) - { - CC_SAFE_RETAIN(var); - CC_SAFE_RELEASE(m_pSubItems); - m_pSubItems = var; - } - CCMutableArray *CCMenuItemToggle::getSubItems() - { - return m_pSubItems; - } - CCMenuItemToggle * CCMenuItemToggle::itemWithTarget(CCObject* target, SEL_MenuHandler selector, CCMenuItem* item, ...) - { - va_list args; - va_start(args, item); - CCMenuItemToggle *pRet = new CCMenuItemToggle(); - pRet->initWithTarget(target, selector, item, args); - pRet->autorelease(); - va_end(args); - return pRet; - } - bool CCMenuItemToggle::initWithTarget(CCObject* target, SEL_MenuHandler selector, CCMenuItem* item, va_list args) - { - CCMenuItem::initWithTarget(target, selector); - this->m_pSubItems = new CCMutableArray(); - int z = 0; - CCMenuItem *i = item; - while(i) - { - z++; - m_pSubItems->addObject(i); - i = va_arg(args, CCMenuItem*); - } - m_uSelectedIndex = UINT_MAX; - this->setSelectedIndex(0); - return true; - } - - CCMenuItemToggle* CCMenuItemToggle::itemWithItem(CCMenuItem *item) - { - CCMenuItemToggle *pRet = new CCMenuItemToggle(); - pRet->initWithItem(item); - pRet->autorelease(); - return pRet; - } - - bool CCMenuItemToggle::initWithItem(CCMenuItem *item) - { - CCMenuItem::initWithTarget(NULL, NULL); - this->m_pSubItems = new CCMutableArray(); - m_pSubItems->addObject(item); - m_uSelectedIndex = UINT_MAX; - this->setSelectedIndex(0); - return true; - } - - void CCMenuItemToggle::addSubItem(CCMenuItem *item) - { - m_pSubItems->addObject(item); - } - - CCMenuItemToggle::~CCMenuItemToggle() - { - CC_SAFE_RELEASE(m_pSubItems); - } - void CCMenuItemToggle::setSelectedIndex(unsigned int index) - { - if( index != m_uSelectedIndex ) - { - m_uSelectedIndex = index; - CCMenuItem *currentItem = (CCMenuItem*)getChildByTag(kCurrentItem); - if( currentItem ) - { - currentItem->removeFromParentAndCleanup(false); - } +void CCMenuItem::setIsEnabled(bool enabled) +{ + m_bIsEnabled = enabled; +} - CCMenuItem *item = m_pSubItems->getObjectAtIndex(m_uSelectedIndex); - this->addChild(item, 0, kCurrentItem); - const CCSize& s = item->getContentSize(); - this->setContentSize(s); - item->setPosition( ccp( s.width/2, s.height/2 ) ); - } - } - unsigned int CCMenuItemToggle::getSelectedIndex() +bool CCMenuItem::getIsEnabled() +{ + return m_bIsEnabled; +} + +CCRect CCMenuItem::rect() +{ + return CCRectMake( m_tPosition.x - m_tContentSize.width * m_tAnchorPoint.x, + m_tPosition.y - m_tContentSize.height * m_tAnchorPoint.y, + m_tContentSize.width, m_tContentSize.height); +} + +bool CCMenuItem::getIsSelected() +{ + return m_bIsSelected; +} + +void CCMenuItem::setTarget(CCObject *rec, SEL_MenuHandler selector) +{ + m_pListener = rec; + m_pfnSelector = selector; +} + +// +//CCMenuItemLabel +// +const ccColor3B& CCMenuItemLabel::getDisabledColor() +{ + return m_tDisabledColor; +} +void CCMenuItemLabel::setDisabledColor(const ccColor3B& var) +{ + m_tDisabledColor = var; +} +CCNode *CCMenuItemLabel::getLabel() +{ + return m_pLabel; +} +void CCMenuItemLabel::setLabel(CCNode* var) +{ + if (var) { - return m_uSelectedIndex; + addChild(var); + var->setAnchorPoint(ccp(0, 0)); + setContentSize(var->getContentSize()); } - void CCMenuItemToggle::selected() + + if (m_pLabel) { - CCMenuItem::selected(); - m_pSubItems->getObjectAtIndex(m_uSelectedIndex)->selected(); + removeChild(m_pLabel, true); } - void CCMenuItemToggle::unselected() + + m_pLabel = var; +} +CCMenuItemLabel * CCMenuItemLabel::itemWithLabel(CCNode*label, CCObject* target, SEL_MenuHandler selector) +{ + CCMenuItemLabel *pRet = new CCMenuItemLabel(); + pRet->initWithLabel(label, target, selector); + pRet->autorelease(); + return pRet; +} +CCMenuItemLabel* CCMenuItemLabel::itemWithLabel(CCNode *label) +{ + CCMenuItemLabel *pRet = new CCMenuItemLabel(); + pRet->initWithLabel(label, NULL, NULL); + pRet->autorelease(); + return pRet; +} +bool CCMenuItemLabel::initWithLabel(CCNode* label, CCObject* target, SEL_MenuHandler selector) +{ + CCMenuItem::initWithTarget(target, selector); + m_fOriginalScale = 1.0f; + m_tColorBackup = ccWHITE; + m_tDisabledColor = ccc3(126,126,126); + this->setLabel(label); + return true; +} +CCMenuItemLabel::~CCMenuItemLabel() +{ +} +void CCMenuItemLabel::setString(const char * label) +{ + dynamic_cast(m_pLabel)->setString(label); + this->setContentSize(m_pLabel->getContentSize()); +} +void CCMenuItemLabel::activate() +{ + if(m_bIsEnabled) { - CCMenuItem::unselected(); - m_pSubItems->getObjectAtIndex(m_uSelectedIndex)->unselected(); - } - void CCMenuItemToggle::activate() - { - // update index - if( m_bIsEnabled ) - { - unsigned int newIndex = (m_uSelectedIndex + 1) % m_pSubItems->count(); - this->setSelectedIndex(newIndex); - } + this->stopAllActions(); + this->setScale( m_fOriginalScale ); CCMenuItem::activate(); } - void CCMenuItemToggle::setIsEnabled(bool enabled) +} +void CCMenuItemLabel::selected() +{ + // subclass to change the default action + if(m_bIsEnabled) { - CCMenuItem::setIsEnabled(enabled); + CCMenuItem::selected(); - if(m_pSubItems && m_pSubItems->count() > 0) + CCAction *action = getActionByTag(kZoomActionTag); + if (action) { - CCMutableArray::CCMutableArrayIterator it; - for( it = m_pSubItems->begin(); it != m_pSubItems->end(); ++it) - { - (*it)->setIsEnabled(enabled); - } + this->stopAction(action); + } + else + { + m_fOriginalScale = this->getScale(); + } + + CCAction *zoomAction = CCScaleTo::actionWithDuration(0.1f, m_fOriginalScale * 1.2f); + zoomAction->setTag(kZoomActionTag); + this->runAction(zoomAction); + } +} +void CCMenuItemLabel::unselected() +{ + // subclass to change the default action + if(m_bIsEnabled) + { + CCMenuItem::unselected(); + this->stopActionByTag(kZoomActionTag); + CCAction *zoomAction = CCScaleTo::actionWithDuration(0.1f, m_fOriginalScale); + zoomAction->setTag(kZoomActionTag); + this->runAction(zoomAction); + } +} +void CCMenuItemLabel::setIsEnabled(bool enabled) +{ + if( m_bIsEnabled != enabled ) + { + if(enabled == false) + { + m_tColorBackup = dynamic_cast(m_pLabel)->getColor(); + dynamic_cast(m_pLabel)->setColor(m_tDisabledColor); + } + else + { + dynamic_cast(m_pLabel)->setColor(m_tColorBackup); } } - CCMenuItem * CCMenuItemToggle::selectedItem() + CCMenuItem::setIsEnabled(enabled); +} +void CCMenuItemLabel::setOpacity(GLubyte opacity) +{ + dynamic_cast(m_pLabel)->setOpacity(opacity); +} +GLubyte CCMenuItemLabel::getOpacity() +{ + return dynamic_cast(m_pLabel)->getOpacity(); +} +void CCMenuItemLabel::setColor(const ccColor3B& color) +{ + dynamic_cast(m_pLabel)->setColor(color); +} +const ccColor3B& CCMenuItemLabel::getColor() +{ + return dynamic_cast(m_pLabel)->getColor(); +} + +// +//CCMenuItemAtlasFont +// +CCMenuItemAtlasFont * CCMenuItemAtlasFont::itemWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap) +{ + return CCMenuItemAtlasFont::itemWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, NULL, NULL); +} + +CCMenuItemAtlasFont * CCMenuItemAtlasFont::itemWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, CCObject* target, SEL_MenuHandler selector) +{ + CCMenuItemAtlasFont *pRet = new CCMenuItemAtlasFont(); + pRet->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, target, selector); + pRet->autorelease(); + return pRet; +} +bool CCMenuItemAtlasFont::initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, CCObject* target, SEL_MenuHandler selector) +{ + CCAssert( value != NULL && strlen(value) != 0, "value length must be greater than 0"); + CCLabelAtlas *label = new CCLabelAtlas(); + label->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap); + label->autorelease(); + if (CCMenuItemLabel::initWithLabel(label, target, selector)) { - return m_pSubItems->getObjectAtIndex(m_uSelectedIndex); + // do something ? } - // - //CCMenuItemToggle - CCRGBAProtocol protocol - // - GLubyte CCMenuItemToggle::getOpacity() + return true; +} +// +//CCMenuItemFont +// +void CCMenuItemFont::setFontSize(unsigned int s) +{ + _fontSize = s; +} +unsigned int CCMenuItemFont::fontSize() +{ + return _fontSize; +} +void CCMenuItemFont::setFontName(const char *name) +{ + if( _fontNameRelease ) { - return m_cOpacity; + _fontName.clear(); } - void CCMenuItemToggle::setOpacity(GLubyte opacity) + _fontName = name; + _fontNameRelease = true; +} +const char * CCMenuItemFont::fontName() +{ + return _fontName.c_str(); +} +CCMenuItemFont * CCMenuItemFont::itemWithString(const char *value, CCObject* target, SEL_MenuHandler selector) +{ + CCMenuItemFont *pRet = new CCMenuItemFont(); + pRet->initWithString(value, target, selector); + pRet->autorelease(); + return pRet; +} +CCMenuItemFont * CCMenuItemFont::itemWithString(const char *value) +{ + CCMenuItemFont *pRet = new CCMenuItemFont(); + pRet->initWithString(value, NULL, NULL); + pRet->autorelease(); + return pRet; +} +bool CCMenuItemFont::initWithString(const char *value, CCObject* target, SEL_MenuHandler selector) +{ + CCAssert( value != NULL && strlen(value) != 0, "Value length must be greater than 0"); + + m_strFontName = _fontName; + m_uFontSize = _fontSize; + + CCLabelTTF *label = CCLabelTTF::labelWithString(value, m_strFontName.c_str(), (float)m_uFontSize); + if (CCMenuItemLabel::initWithLabel(label, target, selector)) { - m_cOpacity = opacity; - if(m_pSubItems && m_pSubItems->count() > 0) - { - CCMutableArray::CCMutableArrayIterator it; - for( it = m_pSubItems->begin(); it != m_pSubItems->end(); ++it) - { - dynamic_cast(*it)->setOpacity(opacity); - } - } + // do something ? } - const ccColor3B& CCMenuItemToggle::getColor() + return true; +} + +void CCMenuItemFont::recreateLabel() +{ + CCLabelTTF *label = CCLabelTTF::labelWithString(dynamic_cast(m_pLabel)->getString(), + m_strFontName.c_str(), (float)m_uFontSize); + this->setLabel(label); +} + +void CCMenuItemFont::setFontSizeObj(unsigned int s) +{ + m_uFontSize = s; + recreateLabel(); +} + +unsigned int CCMenuItemFont::fontSizeObj() +{ + return m_uFontSize; +} + +void CCMenuItemFont::setFontNameObj(const char* name) +{ + m_strFontName = name; + recreateLabel(); +} + +const char* CCMenuItemFont::fontNameObj() +{ + return m_strFontName.c_str(); +} + +// +//CCMenuItemSprite +// +CCNode * CCMenuItemSprite::getNormalImage() +{ + return m_pNormalImage; +} +void CCMenuItemSprite::setNormalImage(CCNode* var) +{ + if (var) { - return m_tColor; - } - void CCMenuItemToggle::setColor(const ccColor3B& color) - { - m_tColor = color; - if(m_pSubItems && m_pSubItems->count() > 0) - { - CCMutableArray::CCMutableArrayIterator it; - for( it = m_pSubItems->begin(); it != m_pSubItems->end(); ++it) - { - dynamic_cast(*it)->setColor(color); - } - } + addChild(var, 0, kNormalTag); + var->setAnchorPoint(ccp(0, 0)); + var->setIsVisible(true); } -} // namespace cocos2d + if (m_pNormalImage) + { + removeChild(m_pNormalImage, true); + } + + m_pNormalImage = var; + this->setContentSize(m_pNormalImage->getContentSize()); +} +CCNode * CCMenuItemSprite::getSelectedImage() +{ + return m_pSelectedImage; +} +void CCMenuItemSprite::setSelectedImage(CCNode* var) +{ + if (var) + { + addChild(var, 0, kSelectedTag); + var->setAnchorPoint(ccp(0, 0)); + var->setIsVisible(false); + } + + if (m_pSelectedImage) + { + removeChild(m_pSelectedImage, true); + } + + m_pSelectedImage = var; +} +CCNode * CCMenuItemSprite::getDisabledImage() +{ + return m_pDisabledImage; +} +void CCMenuItemSprite::setDisabledImage(CCNode* var) +{ + if (var) + { + addChild(var, 0, kDisableTag); + var->setAnchorPoint(ccp(0, 0)); + var->setIsVisible(false); + } + + if (m_pDisabledImage) + { + removeChild(m_pDisabledImage, true); + } + + m_pDisabledImage = var; +} +// +//CCMenuItemSprite - CCRGBAProtocol protocol +// +void CCMenuItemSprite::setOpacity(GLubyte opacity) +{ + dynamic_cast(m_pNormalImage)->setOpacity(opacity); + + if (m_pSelectedImage) + { + dynamic_cast(m_pSelectedImage)->setOpacity(opacity); + } + + if (m_pDisabledImage) + { + dynamic_cast(m_pDisabledImage)->setOpacity(opacity); + } +} +void CCMenuItemSprite::setColor(const ccColor3B& color) +{ + dynamic_cast(m_pNormalImage)->setColor(color); + + if (m_pSelectedImage) + { + dynamic_cast(m_pSelectedImage)->setColor(color); + } + + if (m_pDisabledImage) + { + dynamic_cast(m_pDisabledImage)->setColor(color); + } +} +GLubyte CCMenuItemSprite::getOpacity() +{ + return dynamic_cast(m_pNormalImage)->getOpacity(); +} +const ccColor3B& CCMenuItemSprite::getColor() +{ + return dynamic_cast(m_pNormalImage)->getColor(); +} +CCMenuItemSprite * CCMenuItemSprite::itemWithNormalSprite(CCNode* normalSprite, CCNode* selectedSprite, CCNode* disabledSprite) +{ + return CCMenuItemSprite::itemWithNormalSprite(normalSprite, selectedSprite, disabledSprite, NULL, NULL); +} +CCMenuItemSprite * CCMenuItemSprite::itemWithNormalSprite(CCNode* normalSprite, CCNode* selectedSprite, CCObject* target, SEL_MenuHandler selector) +{ + return CCMenuItemSprite::itemWithNormalSprite(normalSprite, selectedSprite, NULL, target, selector); +} +CCMenuItemSprite * CCMenuItemSprite::itemWithNormalSprite(CCNode *normalSprite, CCNode *selectedSprite, CCNode *disabledSprite, CCObject *target, SEL_MenuHandler selector) +{ + CCMenuItemSprite *pRet = new CCMenuItemSprite(); + pRet->initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, target, selector); + pRet->autorelease(); + return pRet; +} +bool CCMenuItemSprite::initWithNormalSprite(CCNode* normalSprite, CCNode* selectedSprite, CCNode* disabledSprite, CCObject* target, SEL_MenuHandler selector) +{ + CCAssert(normalSprite != NULL, ""); + CCMenuItem::initWithTarget(target, selector); + setNormalImage(normalSprite); + setSelectedImage(selectedSprite); + setDisabledImage(disabledSprite); + + this->setContentSize(m_pNormalImage->getContentSize()); + return true; +} + +/** + @since v0.99.5 + */ +void CCMenuItemSprite::selected() +{ + CCMenuItem::selected(); + + if (m_pDisabledImage) + { + m_pDisabledImage->setIsVisible(false); + } + + if (m_pSelectedImage) + { + m_pNormalImage->setIsVisible(false); + m_pSelectedImage->setIsVisible(true); + } + else + { + m_pNormalImage->setIsVisible(true); + } +} + +void CCMenuItemSprite::unselected() +{ + CCMenuItem::unselected(); + + m_pNormalImage->setIsVisible(true); + + if (m_pSelectedImage) + { + m_pSelectedImage->setIsVisible(false); + } + + if (m_pDisabledImage) + { + m_pDisabledImage->setIsVisible(false); + } +} + +void CCMenuItemSprite::setIsEnabled(bool bEnabled) +{ + CCMenuItem::setIsEnabled(bEnabled); + + if (m_pSelectedImage) + { + m_pSelectedImage->setIsVisible(false); + } + + if (bEnabled) + { + m_pNormalImage->setIsVisible(true); + + if (m_pDisabledImage) + { + m_pDisabledImage->setIsVisible(false); + } + } + else + { + if (m_pDisabledImage) + { + m_pDisabledImage->setIsVisible(true); + m_pNormalImage->setIsVisible(false); + } + else + { + m_pNormalImage->setIsVisible(true); + } + } +} + +CCMenuItemImage * CCMenuItemImage::itemWithNormalImage(const char *normalImage, const char *selectedImage) +{ + return CCMenuItemImage::itemWithNormalImage(normalImage, selectedImage, NULL, NULL, NULL); +} +CCMenuItemImage * CCMenuItemImage::itemWithNormalImage(const char *normalImage, const char *selectedImage, CCObject* target, SEL_MenuHandler selector) +{ + return CCMenuItemImage::itemWithNormalImage(normalImage, selectedImage, NULL, target, selector); +} +CCMenuItemImage * CCMenuItemImage::itemWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, CCObject* target, SEL_MenuHandler selector) +{ + CCMenuItemImage *pRet = new CCMenuItemImage(); + if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, target, selector)) + { + pRet->autorelease(); + return pRet; + } + CC_SAFE_DELETE(pRet); + return NULL; +} +CCMenuItemImage * CCMenuItemImage::itemWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage) +{ + CCMenuItemImage *pRet = new CCMenuItemImage(); + if (pRet && pRet->initWithNormalImage(normalImage, selectedImage, disabledImage, NULL, NULL)) + { + pRet->autorelease(); + return pRet; + } + CC_SAFE_DELETE(pRet); + return NULL; +} +bool CCMenuItemImage::initWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, CCObject* target, SEL_MenuHandler selector) +{ + CCNode *normalSprite = CCSprite::spriteWithFile(normalImage); + CCNode *selectedSprite = NULL; + CCNode *disabledSprite = NULL; + + if (selectedImage) + { + selectedSprite = CCSprite::spriteWithFile(selectedImage); + } + + if(disabledImage) + { + disabledSprite = CCSprite::spriteWithFile(disabledImage); + } + return initWithNormalSprite(normalSprite, selectedSprite, disabledSprite, target, selector); +} +// +// Setter of sprite frames +// +void CCMenuItemImage::setNormalSpriteFrame(CCSpriteFrame * frame) +{ + setNormalImage(CCSprite::spriteWithSpriteFrame(frame)); +} + +void CCMenuItemImage::setSelectedSpriteFrame(CCSpriteFrame * frame) +{ + setSelectedImage(CCSprite::spriteWithSpriteFrame(frame)); +} + +void CCMenuItemImage::setDisabledSpriteFrame(CCSpriteFrame * frame) +{ + setDisabledImage(CCSprite::spriteWithSpriteFrame(frame)); +} + +// +// MenuItemToggle +// +void CCMenuItemToggle::setSubItems(CCArray* var) +{ + CC_SAFE_RETAIN(var); + CC_SAFE_RELEASE(m_pSubItems); + m_pSubItems = var; +} + +CCArray* CCMenuItemToggle::getSubItems() +{ + return m_pSubItems; +} +CCMenuItemToggle * CCMenuItemToggle::itemWithTarget(CCObject* target, SEL_MenuHandler selector, CCMenuItem* item, ...) +{ + va_list args; + va_start(args, item); + CCMenuItemToggle *pRet = new CCMenuItemToggle(); + pRet->initWithTarget(target, selector, item, args); + pRet->autorelease(); + va_end(args); + return pRet; +} + +bool CCMenuItemToggle::initWithTarget(CCObject* target, SEL_MenuHandler selector, CCMenuItem* item, va_list args) +{ + CCMenuItem::initWithTarget(target, selector); + this->m_pSubItems = CCArray::array(); + this->m_pSubItems->retain(); + int z = 0; + CCMenuItem *i = item; + while(i) + { + z++; + m_pSubItems->addObject(i); + i = va_arg(args, CCMenuItem*); + } + m_uSelectedIndex = UINT_MAX; + this->setSelectedIndex(0); + return true; +} + +CCMenuItemToggle* CCMenuItemToggle::itemWithItem(CCMenuItem *item) +{ + CCMenuItemToggle *pRet = new CCMenuItemToggle(); + pRet->initWithItem(item); + pRet->autorelease(); + return pRet; +} + +bool CCMenuItemToggle::initWithItem(CCMenuItem *item) +{ + CCMenuItem::initWithTarget(NULL, NULL); + this->m_pSubItems = CCArray::array(); + this->m_pSubItems->retain(); + m_pSubItems->addObject(item); + m_uSelectedIndex = UINT_MAX; + this->setSelectedIndex(0); + return true; +} + +void CCMenuItemToggle::addSubItem(CCMenuItem *item) +{ + m_pSubItems->addObject(item); +} + +CCMenuItemToggle::~CCMenuItemToggle() +{ + CC_SAFE_RELEASE(m_pSubItems); +} +void CCMenuItemToggle::setSelectedIndex(unsigned int index) +{ + if( index != m_uSelectedIndex ) + { + m_uSelectedIndex = index; + CCMenuItem *currentItem = (CCMenuItem*)getChildByTag(kCurrentItem); + if( currentItem ) + { + currentItem->removeFromParentAndCleanup(false); + } + + CCMenuItem* item = (CCMenuItem*)m_pSubItems->objectAtIndex(m_uSelectedIndex); + this->addChild(item, 0, kCurrentItem); + const CCSize& s = item->getContentSize(); + this->setContentSize(s); + item->setPosition( ccp( s.width/2, s.height/2 ) ); + } +} +unsigned int CCMenuItemToggle::getSelectedIndex() +{ + return m_uSelectedIndex; +} +void CCMenuItemToggle::selected() +{ + CCMenuItem::selected(); + ((CCMenuItem*)(m_pSubItems->objectAtIndex(m_uSelectedIndex)))->selected(); +} +void CCMenuItemToggle::unselected() +{ + CCMenuItem::unselected(); + ((CCMenuItem*)(m_pSubItems->objectAtIndex(m_uSelectedIndex)))->unselected(); +} +void CCMenuItemToggle::activate() +{ + // update index + if( m_bIsEnabled ) + { + unsigned int newIndex = (m_uSelectedIndex + 1) % m_pSubItems->count(); + this->setSelectedIndex(newIndex); + } + CCMenuItem::activate(); +} +void CCMenuItemToggle::setIsEnabled(bool enabled) +{ + CCMenuItem::setIsEnabled(enabled); + + if(m_pSubItems && m_pSubItems->count() > 0) + { + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_pSubItems, pObj) + { + CCMenuItem* pItem = (CCMenuItem*)pObj; + pItem->setIsEnabled(enabled); + } + } +} + +CCMenuItem* CCMenuItemToggle::selectedItem() +{ + return (CCMenuItem*)m_pSubItems->objectAtIndex(m_uSelectedIndex); +} +// +//CCMenuItemToggle - CCRGBAProtocol protocol +// +GLubyte CCMenuItemToggle::getOpacity() +{ + return m_cOpacity; +} +void CCMenuItemToggle::setOpacity(GLubyte opacity) +{ + m_cOpacity = opacity; + if(m_pSubItems && m_pSubItems->count() > 0) + { + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_pSubItems, pObj) + { + CCMenuItem* pItem = (CCMenuItem*)pObj; + dynamic_cast(pItem)->setOpacity(opacity); + } + } +} +const ccColor3B& CCMenuItemToggle::getColor() +{ + return m_tColor; +} +void CCMenuItemToggle::setColor(const ccColor3B& color) +{ + m_tColor = color; + if(m_pSubItems && m_pSubItems->count() > 0) + { + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_pSubItems, pObj) + { + CCMenuItem* pItem = (CCMenuItem*)pObj; + dynamic_cast(pItem)->setColor(color); + } + } +} + +NS_CC_END diff --git a/cocos2dx/particle_nodes/CCParticleSystem.cpp b/cocos2dx/particle_nodes/CCParticleSystem.cpp index 4236da0d46..7950d13d5a 100644 --- a/cocos2dx/particle_nodes/CCParticleSystem.cpp +++ b/cocos2dx/particle_nodes/CCParticleSystem.cpp @@ -150,7 +150,7 @@ bool CCParticleSystem::initWithFile(const char *plistFile) { bool bRet = false; m_sPlistFile = CCFileUtils::fullPathFromRelativePath(plistFile); - CCDictionary *dict = CCFileUtils::dictionaryWithContentsOfFileThreadSafe(m_sPlistFile.c_str()); + CCDictionary *dict = CCFileUtils::dictionaryWithContentsOfFileThreadSafe(m_sPlistFile.c_str()); CCAssert( dict != NULL, "Particles: file not found"); bRet = this->initWithDictionary(dict); @@ -159,7 +159,7 @@ bool CCParticleSystem::initWithFile(const char *plistFile) return bRet; } -bool CCParticleSystem::initWithDictionary(CCDictionary *dictionary) +bool CCParticleSystem::initWithDictionary(CCDictionary *dictionary) { bool bRet = false; unsigned char *buffer = NULL; diff --git a/cocos2dx/platform/CCFileUtils.cpp b/cocos2dx/platform/CCFileUtils.cpp index 246202361a..a4b80817a3 100644 --- a/cocos2dx/platform/CCFileUtils.cpp +++ b/cocos2dx/platform/CCFileUtils.cpp @@ -52,14 +52,14 @@ typedef enum class CCDictMaker : public CCSAXDelegator { public: - CCDictionary *m_pRootDict; - CCDictionary *m_pCurDict; - std::stack*> m_tDictStack; + CCDictionary *m_pRootDict; + CCDictionary *m_pCurDict; + std::stack m_tDictStack; std::string m_sCurKey;///< parsed key CCSAXState m_tState; - CCMutableArray *m_pArray; + CCArray* m_pArray; - std::stack*> m_tArrayStack; + std::stack m_tArrayStack; std::stack m_tStateStack; public: @@ -75,7 +75,7 @@ public: { } - CCDictionary *dictionaryWithContentsOfFile(const char *pFileName) + CCDictionary* dictionaryWithContentsOfFile(const char *pFileName) { CCSAXParser parser; @@ -96,7 +96,7 @@ public: std::string sName((char*)name); if( sName == "dict" ) { - m_pCurDict = new CCDictionary(); + m_pCurDict = new CCDictionary(); if(! m_pRootDict) { // Because it will call m_pCurDict->release() later, so retain here. @@ -120,8 +120,8 @@ public: { // add the dictionary into the pre dictionary CCAssert(! m_tDictStack.empty(), "The state is wrong!"); - CCDictionary* pPreDict = m_tDictStack.top(); - pPreDict->setObject(m_pCurDict, m_sCurKey); + CCDictionary* pPreDict = m_tDictStack.top(); + pPreDict->setObject(m_pCurDict, m_sCurKey.c_str()); } m_pCurDict->release(); @@ -149,17 +149,18 @@ public: else if (sName == "array") { m_tState = SAX_ARRAY; - m_pArray = new CCMutableArray(); + m_pArray = CCArray::array(); + m_pArray->retain(); CCSAXState preState = m_tStateStack.empty() ? SAX_DICT : m_tStateStack.top(); if (preState == SAX_DICT) { - m_pCurDict->setObject(m_pArray, m_sCurKey); + m_pCurDict->setObject(m_pArray, m_sCurKey.c_str()); } else if (preState == SAX_ARRAY) { CCAssert(! m_tArrayStack.empty(), "The state is worng!"); - CCMutableArray* pPreArray = m_tArrayStack.top(); + CCArray* pPreArray = m_tArrayStack.top(); pPreArray->addObject(m_pArray); } m_pArray->release(); @@ -205,7 +206,7 @@ public: } else if (SAX_DICT == curState) { - m_pCurDict->setObject(str, m_sCurKey); + m_pCurDict->setObject(str, m_sCurKey.c_str()); } str->release(); } @@ -218,7 +219,7 @@ public: } else if (SAX_DICT == curState) { - m_pCurDict->setObject(str, m_sCurKey); + m_pCurDict->setObject(str, m_sCurKey.c_str()); } str->release(); } @@ -254,7 +255,7 @@ public: } else if (SAX_DICT == curState) { - m_pCurDict->setObject(pText, m_sCurKey); + m_pCurDict->setObject(pText, m_sCurKey.c_str()); } break; } @@ -287,15 +288,15 @@ std::string& CCFileUtils::ccRemoveHDSuffixFromFile(std::string& path) return path; } -CCDictionary *CCFileUtils::dictionaryWithContentsOfFile(const char *pFileName) +CCDictionary* CCFileUtils::dictionaryWithContentsOfFile(const char *pFileName) { - CCDictionary *ret = dictionaryWithContentsOfFileThreadSafe(pFileName); + CCDictionary* ret = dictionaryWithContentsOfFileThreadSafe(pFileName); ret->autorelease(); return ret; } -CCDictionary *CCFileUtils::dictionaryWithContentsOfFileThreadSafe(const char *pFileName) +CCDictionary* CCFileUtils::dictionaryWithContentsOfFileThreadSafe(const char *pFileName) { CCDictMaker tMaker; return tMaker.dictionaryWithContentsOfFile(pFileName); diff --git a/cocos2dx/platform/CCFileUtils.h b/cocos2dx/platform/CCFileUtils.h index 093dd54eba..265793d559 100644 --- a/cocos2dx/platform/CCFileUtils.h +++ b/cocos2dx/platform/CCFileUtils.h @@ -25,7 +25,7 @@ THE SOFTWARE. #define __CC_FILEUTILS_PLATFORM_H__ #include -#include "CCMutableDictionary.h" +#include "CCDictionary.h" NS_CC_BEGIN; @@ -87,13 +87,13 @@ public: @param pFileName The file name of *.plist file @return The CCDictionary pointer generated from the file */ - static CCDictionary *dictionaryWithContentsOfFile(const char *pFileName); + static CCDictionary* dictionaryWithContentsOfFile(const char *pFileName); /* @brief The same meaning as dictionaryWithContentsOfFile(), but it doesn't call autorelease, so the invoker should call release(). */ - static CCDictionary *dictionaryWithContentsOfFileThreadSafe(const char *pFileName); + static CCDictionary* dictionaryWithContentsOfFileThreadSafe(const char *pFileName); /** @brief Get the writeable path diff --git a/cocos2dx/platform/CCSAXParser.cpp b/cocos2dx/platform/CCSAXParser.cpp index 773a358ee8..d29ec06d76 100644 --- a/cocos2dx/platform/CCSAXParser.cpp +++ b/cocos2dx/platform/CCSAXParser.cpp @@ -22,7 +22,7 @@ ****************************************************************************/ #include "CCSAXParser.h" -#include "CCMutableDictionary.h" +#include "CCDictionary.h" #include #include #include diff --git a/cocos2dx/proj.win32/cocos2d-win32.vcproj b/cocos2dx/proj.win32/cocos2d-win32.vcproj index e8763e13f2..2a19f32f92 100644 --- a/cocos2dx/proj.win32/cocos2d-win32.vcproj +++ b/cocos2dx/proj.win32/cocos2d-win32.vcproj @@ -1112,22 +1112,6 @@ > - - - - - - - - @@ -1263,6 +1247,18 @@ + + + + + + diff --git a/cocos2dx/gles2/CCGLProgram.cpp b/cocos2dx/shaders/CCGLProgram.cpp similarity index 100% rename from cocos2dx/gles2/CCGLProgram.cpp rename to cocos2dx/shaders/CCGLProgram.cpp diff --git a/cocos2dx/gles2/CCShaderCache.cpp b/cocos2dx/shaders/CCShaderCache.cpp similarity index 97% rename from cocos2dx/gles2/CCShaderCache.cpp rename to cocos2dx/shaders/CCShaderCache.cpp index 6233440821..8e1d1a36db 100644 --- a/cocos2dx/gles2/CCShaderCache.cpp +++ b/cocos2dx/shaders/CCShaderCache.cpp @@ -64,7 +64,7 @@ CCShaderCache::~CCShaderCache() bool CCShaderCache::init() { - m_pPrograms = new CCMutableDictionary(); + m_pPrograms = new CCDictionary(); loadDefaultShaders(); return true; } @@ -190,7 +190,7 @@ void CCShaderCache::loadDefaultShaders() CCGLProgram* CCShaderCache::programForKey(const char* key) { - return m_pPrograms->objectForKey(key); + return (CCGLProgram*)m_pPrograms->objectForKey(key); } void CCShaderCache::addProgram(CCGLProgram* program, const char* key) diff --git a/cocos2dx/gles2/ccGLStateCache.cpp b/cocos2dx/shaders/ccGLStateCache.cpp similarity index 100% rename from cocos2dx/gles2/ccGLStateCache.cpp rename to cocos2dx/shaders/ccGLStateCache.cpp diff --git a/cocos2dx/sprite_nodes/CCAnimation.cpp b/cocos2dx/sprite_nodes/CCAnimation.cpp index 22e094117d..1768f5f500 100644 --- a/cocos2dx/sprite_nodes/CCAnimation.cpp +++ b/cocos2dx/sprite_nodes/CCAnimation.cpp @@ -40,7 +40,7 @@ CCAnimationFrame::CCAnimationFrame() } -bool CCAnimationFrame::initWithSpriteFrame(CCSpriteFrame* spriteFrame, float delayUnits, CCObjectDictionary* userInfo) +bool CCAnimationFrame::initWithSpriteFrame(CCSpriteFrame* spriteFrame, float delayUnits, CCDictionary* userInfo) { setSpriteFrame(spriteFrame); setDelayUnits(delayUnits); @@ -73,7 +73,7 @@ CCObject* CCAnimationFrame::copyWithZone(CCZone* pZone) } pCopy->initWithSpriteFrame((CCSpriteFrame*)m_pSpriteFrame->copy()->autorelease(), - m_fDelayUnits, (CCObjectDictionary*)m_pUserInfo->copy()->autorelease()); + m_fDelayUnits, m_pUserInfo != NULL ? (CCDictionary*)m_pUserInfo->copy()->autorelease() : NULL); CC_SAFE_DELETE(pNewZone); return pCopy; @@ -90,7 +90,7 @@ CCAnimation* CCAnimation::animation(void) return pAnimation; } -CCAnimation* CCAnimation::animationWithSpriteFrames(CCMutableArray *frames) +CCAnimation* CCAnimation::animationWithSpriteFrames(CCArray *frames) { CCAnimation *pAnimation = new CCAnimation(); pAnimation->initWithSpriteFrames(frames); @@ -99,7 +99,7 @@ CCAnimation* CCAnimation::animationWithSpriteFrames(CCMutableArray *frames, float delay) +CCAnimation* CCAnimation::animationWithSpriteFrames(CCArray *frames, float delay) { CCAnimation *pAnimation = new CCAnimation(); pAnimation->initWithSpriteFrames(frames, delay); @@ -108,7 +108,7 @@ CCAnimation* CCAnimation::animationWithSpriteFrames(CCMutableArray* arrayOfSpriteFrameNames, float delayPerUnit, unsigned int loops) +CCAnimation* CCAnimation::animationWithAnimationFrames(CCArray* arrayOfSpriteFrameNames, float delayPerUnit, unsigned int loops) { CCAnimation *pAnimation = new CCAnimation(); pAnimation->initWithAnimationFrames(arrayOfSpriteFrameNames, delayPerUnit, loops); @@ -121,24 +121,26 @@ bool CCAnimation::init() return initWithSpriteFrames(NULL, 0.0f); } -bool CCAnimation::initWithSpriteFrames(CCMutableArray* pFrames) +bool CCAnimation::initWithSpriteFrames(CCArray* pFrames) { return initWithSpriteFrames(pFrames, 0.0f); } -bool CCAnimation::initWithSpriteFrames(CCMutableArray *pFrames, float delay) +bool CCAnimation::initWithSpriteFrames(CCArray *pFrames, float delay) { + CCARRAY_VERIFY_TYPE(pFrames, CCSpriteFrame*); + m_uLoops = 1; m_fDelayPerUnit = delay; - CCMutableArray* pTmpFrames = new CCMutableArray(); - pTmpFrames->autorelease(); + CCArray* pTmpFrames = CCArray::array(); setFrames(pTmpFrames); if (pFrames != NULL) { - for(CCMutableArray::CCMutableArrayIterator it = pFrames->begin(); it != pFrames->end(); ++it) + CCObject* pObj = NULL; + CCARRAY_FOREACH(pFrames, pObj) { - CCSpriteFrame* frame = *it; + CCSpriteFrame* frame = (CCSpriteFrame*)pObj; CCAnimationFrame *animFrame = new CCAnimationFrame(); animFrame->initWithSpriteFrame(frame, 1, NULL); m_pFrames->addObject(animFrame); @@ -151,16 +153,19 @@ bool CCAnimation::initWithSpriteFrames(CCMutableArray *pFrames, return true; } -bool CCAnimation::initWithAnimationFrames(CCMutableArray* arrayOfAnimationFrames, float delayPerUnit, unsigned int loops) +bool CCAnimation::initWithAnimationFrames(CCArray* arrayOfAnimationFrames, float delayPerUnit, unsigned int loops) { + CCARRAY_VERIFY_TYPE(arrayOfAnimationFrames, CCAnimationFrame*); + m_fDelayPerUnit = delayPerUnit; m_uLoops = loops; - setFrames(CCMutableArray::arrayWithArray(arrayOfAnimationFrames)); + setFrames(CCArray::arrayWithArray(arrayOfAnimationFrames)); - for( CCMutableArray::CCMutableArrayIterator it = m_pFrames->begin(); it != m_pFrames->end(); ++it ) + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_pFrames, pObj) { - CCAnimationFrame *animFrame = *it; + CCAnimationFrame* animFrame = (CCAnimationFrame*)pObj; m_fTotalDelayUnits += animFrame->getDelayUnits(); } return true; diff --git a/cocos2dx/sprite_nodes/CCAnimationCache.cpp b/cocos2dx/sprite_nodes/CCAnimationCache.cpp index 61ec92b89a..345d98b8ba 100644 --- a/cocos2dx/sprite_nodes/CCAnimationCache.cpp +++ b/cocos2dx/sprite_nodes/CCAnimationCache.cpp @@ -54,7 +54,7 @@ void CCAnimationCache::purgeSharedAnimationCache(void) bool CCAnimationCache::init() { - m_pAnimations = new CCMutableDictionary(); + m_pAnimations = new CCDictionary(); return true; } @@ -71,7 +71,7 @@ CCAnimationCache::~CCAnimationCache() void CCAnimationCache::addAnimation(CCAnimation *animation, const char * name) { - m_pAnimations->setObject(animation, std::string(name)); + m_pAnimations->setObject(animation, name); } void CCAnimationCache::removeAnimationByName(const char* name) @@ -81,41 +81,43 @@ void CCAnimationCache::removeAnimationByName(const char* name) return; } - m_pAnimations->removeObjectForKey(std::string(name)); + m_pAnimations->removeObjectForKey(name); } CCAnimation* CCAnimationCache::animationByName(const char* name) { - return m_pAnimations->objectForKey(std::string(name)); + return (CCAnimation*)m_pAnimations->objectForKey(name); } -void CCAnimationCache::parseVersion1(CCObjectDictionary* animations) +void CCAnimationCache::parseVersion1(CCDictionary* animations) { - vector animationNames = animations->allKeys(); CCSpriteFrameCache *frameCache = CCSpriteFrameCache::sharedSpriteFrameCache(); - - for (vector::iterator iterName = animationNames.begin(); iterName != animationNames.end(); ++iterName) - { - string name = *iterName; - CCObjectDictionary* animationDict = (CCObjectDictionary*)animations->objectForKey(name); - CCMutableArray* frameNames = (CCMutableArray*)animationDict->objectForKey("frames"); + + CCDictElement* pElement = NULL; + CCDICT_FOREACH(animations, pElement) + { + CCDictionary* animationDict = (CCDictionary*)pElement->getObject(); + CCArray* frameNames = (CCArray*)animationDict->objectForKey("frames"); float delay = (float)atof(valueForKey("delay", animationDict)); CCAnimation* animation = NULL; - if ( frameNames == NULL ) { - CCLOG("cocos2d: CCAnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", name.c_str()); + if ( frameNames == NULL ) + { + CCLOG("cocos2d: CCAnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", pElement->getStrKey()); continue; } - CCMutableArray* frames = new CCMutableArray(frameNames->count()); + CCArray* frames = CCArray::arrayWithCapacity(frameNames->count()); + frames->retain(); - for (CCMutableArray::CCMutableArrayIterator iterFrameName = frameNames->begin(); iterFrameName != frameNames->end(); ++iterFrameName) + CCObject* pObj = NULL; + CCARRAY_FOREACH(frameNames, pObj) { - const char* frameName = ((CCString*)(*iterFrameName))->toStdString().c_str(); + const char* frameName = ((CCString*)pObj)->c_str(); CCSpriteFrame* spriteFrame = frameCache->spriteFrameByName(frameName); if ( ! spriteFrame ) { - CCLOG("cocos2d: CCAnimationCache: Animation '%s' refers to frame '%s' which is not currently in the CCSpriteFrameCache. This frame will not be added to the animation.", name.c_str(), frameName); + CCLOG("cocos2d: CCAnimationCache: Animation '%s' refers to frame '%s' which is not currently in the CCSpriteFrameCache. This frame will not be added to the animation.", pElement->getStrKey(), frameName); continue; } @@ -127,57 +129,59 @@ void CCAnimationCache::parseVersion1(CCObjectDictionary* animations) } if ( frames->count() == 0 ) { - CCLOG("cocos2d: CCAnimationCache: None of the frames for animation '%s' were found in the CCSpriteFrameCache. Animation is not being added to the Animation Cache.", name.c_str()); + CCLOG("cocos2d: CCAnimationCache: None of the frames for animation '%s' were found in the CCSpriteFrameCache. Animation is not being added to the Animation Cache.", pElement->getStrKey()); continue; } else if ( frames->count() != frameNames->count() ) { - CCLOG("cocos2d: CCAnimationCache: An animation in your dictionary refers to a frame which is not in the CCSpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.", name.c_str()); + CCLOG("cocos2d: CCAnimationCache: An animation in your dictionary refers to a frame which is not in the CCSpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.", pElement->getStrKey()); } animation = CCAnimation::animationWithAnimationFrames(frames, delay, 1); - CCAnimationCache::sharedAnimationCache()->addAnimation(animation, name.c_str()); + CCAnimationCache::sharedAnimationCache()->addAnimation(animation, pElement->getStrKey()); frames->release(); } } -void CCAnimationCache::parseVersion2(CCObjectDictionary* animations) +void CCAnimationCache::parseVersion2(CCDictionary* animations) { - vector animationNames = animations->allKeys(); CCSpriteFrameCache *frameCache = CCSpriteFrameCache::sharedSpriteFrameCache(); - for (vector::iterator iterName = animationNames.begin(); iterName != animationNames.end(); ++iterName) + CCDictElement* pElement = NULL; + CCDICT_FOREACH(animations, pElement) { - string name = *iterName; - CCObjectDictionary* animationDict = (CCObjectDictionary*)animations->objectForKey(name); + const char* name = pElement->getStrKey(); + CCDictionary* animationDict = (CCDictionary*)pElement->getObject(); int loops = atoi(valueForKey("loops", animationDict)); bool restoreOriginalFrame = atoi(valueForKey("restoreOriginalFrame", animationDict)) == 0 ? false : true; - CCMutableArray* frameArray = (CCMutableArray*)animationDict->objectForKey("frames"); + CCArray* frameArray = (CCArray*)animationDict->objectForKey("frames"); if ( frameArray == NULL ) { - CCLOG("cocos2d: CCAnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", name.c_str()); + CCLOG("cocos2d: CCAnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.", name); continue; } // Array of AnimationFrames - CCMutableArray* array = new CCMutableArray(frameArray->count()); + CCArray* array = CCArray::arrayWithCapacity(frameArray->count()); + array->retain(); - for (CCMutableArray::CCMutableArrayIterator iterFrameName = frameArray->begin(); iterFrameName != frameArray->end(); ++iterFrameName) + CCObject* pObj = NULL; + CCARRAY_FOREACH(frameArray, pObj) { - CCObjectDictionary* entry = (CCObjectDictionary*)(*iterFrameName); + CCDictionary* entry = (CCDictionary*)(pObj); const char* spriteFrameName = valueForKey("spriteframe", entry); CCSpriteFrame *spriteFrame = frameCache->spriteFrameByName(spriteFrameName); if( ! spriteFrame ) { - CCLOG("cocos2d: CCAnimationCache: Animation '%s' refers to frame '%s' which is not currently in the CCSpriteFrameCache. This frame will not be added to the animation.", name.c_str(), spriteFrameName); + CCLOG("cocos2d: CCAnimationCache: Animation '%s' refers to frame '%s' which is not currently in the CCSpriteFrameCache. This frame will not be added to the animation.", name, spriteFrameName); continue; } float delayUnits = (float)atof(valueForKey("delayUnits", entry)); - CCObjectDictionary* userInfo = (CCObjectDictionary*)entry->objectForKey("notification"); + CCDictionary* userInfo = (CCDictionary*)entry->objectForKey("notification"); CCAnimationFrame *animFrame = new CCAnimationFrame(); animFrame->initWithSpriteFrame(spriteFrame, delayUnits, userInfo); @@ -193,14 +197,14 @@ void CCAnimationCache::parseVersion2(CCObjectDictionary* animations) animation->setRestoreOriginalFrame(restoreOriginalFrame); - CCAnimationCache::sharedAnimationCache()->addAnimation(animation, name.c_str()); + CCAnimationCache::sharedAnimationCache()->addAnimation(animation, name); animation->release(); } } -void CCAnimationCache::addAnimationsWithDictionary(CCObjectDictionary* dictionary) +void CCAnimationCache::addAnimationsWithDictionary(CCDictionary* dictionary) { - CCObjectDictionary* animations = (CCObjectDictionary*)dictionary->objectForKey("animations"); + CCDictionary* animations = (CCDictionary*)dictionary->objectForKey("animations"); if ( animations == NULL ) { CCLOG("cocos2d: CCAnimationCache: No animations were found in provided dictionary."); @@ -208,18 +212,19 @@ void CCAnimationCache::addAnimationsWithDictionary(CCObjectDictionary* dictionar } unsigned int version = 1; - CCObjectDictionary* properties = (CCObjectDictionary*)dictionary->objectForKey("properties"); + CCDictionary* properties = (CCDictionary*)dictionary->objectForKey("properties"); if( properties ) { version = atoi(valueForKey("format", properties)); } - CCMutableArray* spritesheets = (CCMutableArray*)properties->objectForKey("spritesheets"); + CCArray* spritesheets = (CCArray*)properties->objectForKey("spritesheets"); - for( CCMutableArray::CCMutableArrayIterator iterName = spritesheets->begin(); iterName != spritesheets->end(); ++iterName) + CCObject* pObj = NULL; + CCARRAY_FOREACH(spritesheets, pObj) { - CCString* name = (CCString*)(*iterName); - CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(name->toStdString().c_str()); + CCString* name = (CCString*)(pObj); + CCSpriteFrameCache::sharedSpriteFrameCache()->addSpriteFramesWithFile(name->c_str()); } switch (version) { @@ -234,11 +239,11 @@ void CCAnimationCache::addAnimationsWithDictionary(CCObjectDictionary* dictionar } } -const char * CCAnimationCache::valueForKey(const char *key, CCDictionary *dict) +const char * CCAnimationCache::valueForKey(const char *key, CCDictionary *dict) { if (dict) { - CCString *pString = (CCString*)dict->objectForKey(std::string(key)); + CCString *pString = (CCString*)dict->objectForKey(key); return pString ? pString->m_sString.c_str() : ""; } return ""; @@ -250,7 +255,7 @@ void CCAnimationCache::addAnimationsWithFile(const char* plist) CCAssert( plist, "Invalid texture file name"); const char* path = CCFileUtils::fullPathFromRelativePath(plist); - CCObjectDictionary* dict = CCFileUtils::dictionaryWithContentsOfFile(path); + CCDictionary* dict = CCFileUtils::dictionaryWithContentsOfFile(path); CCAssert( dict, "CCAnimationCache: File could not be found"); diff --git a/cocos2dx/sprite_nodes/CCSprite.cpp b/cocos2dx/sprite_nodes/CCSprite.cpp index 42ae50be38..1936c4d121 100644 --- a/cocos2dx/sprite_nodes/CCSprite.cpp +++ b/cocos2dx/sprite_nodes/CCSprite.cpp @@ -960,7 +960,7 @@ void CCSprite::setDisplayFrameWithAnimationName(const char *animationName, int f CCAssert(a, "CCSprite#setDisplayFrameWithAnimationName: Frame not found"); - CCAnimationFrame *frame = a->getFrames()->getObjectAtIndex(frameIndex); + CCAnimationFrame* frame = (CCAnimationFrame*)a->getFrames()->objectAtIndex(frameIndex); CCAssert(frame, "CCSprite#setDisplayFrame. Invalid frame"); diff --git a/cocos2dx/sprite_nodes/CCSpriteFrameCache.cpp b/cocos2dx/sprite_nodes/CCSpriteFrameCache.cpp index 9fd870a851..620af012af 100644 --- a/cocos2dx/sprite_nodes/CCSpriteFrameCache.cpp +++ b/cocos2dx/sprite_nodes/CCSpriteFrameCache.cpp @@ -35,8 +35,12 @@ THE SOFTWARE. #include "support/TransformUtils.h" #include "CCFileUtils.h" #include "CCString.h" +#include "CCArray.h" +#include -namespace cocos2d { +using namespace std; + +NS_CC_BEGIN static CCSpriteFrameCache *pSharedSpriteFrameCache = NULL; @@ -58,8 +62,8 @@ void CCSpriteFrameCache::purgeSharedSpriteFrameCache(void) bool CCSpriteFrameCache::init(void) { - m_pSpriteFrames= new CCDictionary(); - m_pSpriteFramesAliases = new CCDictionary(); + m_pSpriteFrames= new CCDictionary(); + m_pSpriteFramesAliases = new CCDictionary(); return true; } @@ -69,7 +73,7 @@ CCSpriteFrameCache::~CCSpriteFrameCache(void) CC_SAFE_RELEASE(m_pSpriteFramesAliases); } -void CCSpriteFrameCache::addSpriteFramesWithDictionary(CCDictionary *dictionary, CCTexture2D *pobTexture) +void CCSpriteFrameCache::addSpriteFramesWithDictionary(CCDictionary* dictionary, CCTexture2D *pobTexture) { /* Supported Zwoptex Formats: @@ -80,8 +84,8 @@ void CCSpriteFrameCache::addSpriteFramesWithDictionary(CCDictionary *metadataDict = (CCDictionary*)dictionary->objectForKey(std::string("metadata")); - CCDictionary *framesDict = (CCDictionary*)dictionary->objectForKey(std::string("frames")); + CCDictionary *metadataDict = (CCDictionary*)dictionary->objectForKey("metadata"); + CCDictionary *framesDict = (CCDictionary*)dictionary->objectForKey("frames"); int format = 0; // get the format @@ -93,12 +97,11 @@ void CCSpriteFrameCache::addSpriteFramesWithDictionary(CCDictionary=0 && format <= 3, ""); - framesDict->begin(); - std::string key = ""; - CCDictionary *frameDict = NULL; - while( (frameDict = (CCDictionary*)framesDict->next(&key)) ) + CCDictElement* pElement = NULL; + CCDICT_FOREACH(framesDict, pElement) { - CCSpriteFrame *spriteFrame = m_pSpriteFrames->objectForKey(key); + CCDictionary* frameDict = (CCDictionary*)pElement->getObject(); + CCSpriteFrame* spriteFrame = (CCSpriteFrame*)m_pSpriteFrames->objectForKey(pElement->getStrKey()); if (spriteFrame) { continue; @@ -164,19 +167,19 @@ void CCSpriteFrameCache::addSpriteFramesWithDictionary(CCDictionary *aliases = (CCMutableArray *) (frameDict->objectForKey(std::string("aliases"))); - CCMutableArray::CCMutableArrayIterator iter; + CCArray* aliases = (CCArray*) (frameDict->objectForKey("aliases")); + CCString * frameKey = new CCString(pElement->getStrKey()); - CCString * frameKey = new CCString(key.c_str()); - for (iter = aliases->begin(); iter != aliases->end(); ++iter) + CCObject* pObj = NULL; + CCARRAY_FOREACH(aliases, pObj) { - std::string oneAlias = ((CCString*) (*iter))->m_sString; - if (m_pSpriteFramesAliases->objectForKey(oneAlias)) + std::string oneAlias = ((CCString*)pObj)->m_sString; + if (m_pSpriteFramesAliases->objectForKey(oneAlias.c_str())) { CCLOG("cocos2d: WARNING: an alias with name %s already exists", oneAlias.c_str()); } - m_pSpriteFramesAliases->setObject(frameKey, oneAlias); + m_pSpriteFramesAliases->setObject(frameKey, oneAlias.c_str()); } frameKey->release(); // create frame @@ -189,7 +192,7 @@ void CCSpriteFrameCache::addSpriteFramesWithDictionary(CCDictionarysetObject(spriteFrame, key); + m_pSpriteFrames->setObject(spriteFrame, pElement->getStrKey()); spriteFrame->release(); } } @@ -197,7 +200,7 @@ void CCSpriteFrameCache::addSpriteFramesWithDictionary(CCDictionary *dict = CCFileUtils::dictionaryWithContentsOfFileThreadSafe(pszPath); + CCDictionary *dict = CCFileUtils::dictionaryWithContentsOfFileThreadSafe(pszPath); addSpriteFramesWithDictionary(dict, pobTexture); @@ -222,11 +225,11 @@ void CCSpriteFrameCache::addSpriteFramesWithFile(const char* plist, const char* void CCSpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist) { const char *pszPath = CCFileUtils::fullPathFromRelativePath(pszPlist); - CCDictionary *dict = CCFileUtils::dictionaryWithContentsOfFileThreadSafe(pszPath); + CCDictionary *dict = CCFileUtils::dictionaryWithContentsOfFileThreadSafe(pszPath); string texturePath(""); - CCDictionary* metadataDict = (CCDictionary*)dict->objectForKey(string("metadata")); + CCDictionary* metadataDict = (CCDictionary*)dict->objectForKey("metadata"); if (metadataDict) { // try to read texture file name from meta data @@ -269,7 +272,7 @@ void CCSpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist) void CCSpriteFrameCache::addSpriteFrame(CCSpriteFrame *pobFrame, const char *pszFrameName) { - m_pSpriteFrames->setObject(pobFrame, std::string(pszFrameName)); + m_pSpriteFrames->setObject(pobFrame, pszFrameName); } void CCSpriteFrameCache::removeSpriteFrames(void) @@ -280,18 +283,16 @@ void CCSpriteFrameCache::removeSpriteFrames(void) void CCSpriteFrameCache::removeUnusedSpriteFrames(void) { - m_pSpriteFrames->begin(); - std::string key = ""; - CCSpriteFrame *spriteFrame = NULL; - while( (spriteFrame = m_pSpriteFrames->next(&key)) ) + CCDictElement* pElement = NULL; + CCDICT_FOREACH(m_pSpriteFrames, pElement) { + CCSpriteFrame* spriteFrame = (CCSpriteFrame*)pElement->getObject(); if( spriteFrame->retainCount() == 1 ) { - CCLOG("cocos2d: CCSpriteFrameCache: removing unused frame: %s", key.c_str()); - m_pSpriteFrames->removeObjectForKey(key); + CCLOG("cocos2d: CCSpriteFrameCache: removing unused frame: %s", pElement->getStrKey()); + m_pSpriteFrames->removeObjectForKey(pElement->getStrKey()); } } - m_pSpriteFrames->end(); } @@ -304,50 +305,47 @@ void CCSpriteFrameCache::removeSpriteFrameByName(const char *pszName) } // Is this an alias ? - CCString *key = (CCString*)m_pSpriteFramesAliases->objectForKey(string(pszName)); + CCString *key = (CCString*)m_pSpriteFramesAliases->objectForKey(pszName); if (key) { - m_pSpriteFrames->removeObjectForKey(key->m_sString); - m_pSpriteFramesAliases->removeObjectForKey(key->m_sString); + m_pSpriteFrames->removeObjectForKey(key->c_str()); + m_pSpriteFramesAliases->removeObjectForKey(key->c_str()); } else { - m_pSpriteFrames->removeObjectForKey(std::string(pszName)); + m_pSpriteFrames->removeObjectForKey(pszName); } } void CCSpriteFrameCache::removeSpriteFramesFromFile(const char* plist) { const char* path = CCFileUtils::fullPathFromRelativePath(plist); - CCDictionary* dict = CCFileUtils::dictionaryWithContentsOfFileThreadSafe(path); + CCDictionary* dict = CCFileUtils::dictionaryWithContentsOfFileThreadSafe(path); - removeSpriteFramesFromDictionary((CCDictionary*)dict); + removeSpriteFramesFromDictionary((CCDictionary*)dict); dict->release(); } -void CCSpriteFrameCache::removeSpriteFramesFromDictionary(CCDictionary *dictionary) +void CCSpriteFrameCache::removeSpriteFramesFromDictionary(CCDictionary* dictionary) { - CCDictionary* framesDict = (CCDictionary*)dictionary->objectForKey(string("frames")); + CCDictionary* framesDict = (CCDictionary*)dictionary->objectForKey("frames"); vector keysToRemove; - framesDict->begin(); - std::string key = ""; - CCDictionary *frameDict = NULL; - while( (frameDict = (CCDictionary*)framesDict->next(&key)) ) + CCDictElement* pElement = NULL; + CCDICT_FOREACH(framesDict, pElement) { - if (m_pSpriteFrames->objectForKey(key)) + if (m_pSpriteFrames->objectForKey(pElement->getStrKey())) { - keysToRemove.push_back(key); + keysToRemove.push_back(pElement->getStrKey()); } } - framesDict->end(); vector::iterator iter; for (iter = keysToRemove.begin(); iter != keysToRemove.end(); ++iter) { - m_pSpriteFrames->removeObjectForKey(*iter); + m_pSpriteFrames->removeObjectForKey((*iter).c_str()); } } @@ -355,36 +353,34 @@ void CCSpriteFrameCache::removeSpriteFramesFromTexture(CCTexture2D* texture) { vector keysToRemove; - m_pSpriteFrames->begin(); - std::string key = ""; - CCDictionary *frameDict = NULL; - while( (frameDict = (CCDictionary*)m_pSpriteFrames->next(&key)) ) + CCDictElement* pElement = NULL; + CCDICT_FOREACH(m_pSpriteFrames, pElement) { - CCSpriteFrame *frame = m_pSpriteFrames->objectForKey(key); + string key = pElement->getStrKey(); + CCSpriteFrame* frame = (CCSpriteFrame*)m_pSpriteFrames->objectForKey(key.c_str()); if (frame && (frame->getTexture() == texture)) { keysToRemove.push_back(key); } } - m_pSpriteFrames->end(); vector::iterator iter; for (iter = keysToRemove.begin(); iter != keysToRemove.end(); ++iter) { - m_pSpriteFrames->removeObjectForKey(*iter); + m_pSpriteFrames->removeObjectForKey((*iter).c_str()); } } CCSpriteFrame* CCSpriteFrameCache::spriteFrameByName(const char *pszName) { - CCSpriteFrame *frame = m_pSpriteFrames->objectForKey(std::string(pszName)); - if (! frame) + CCSpriteFrame* frame = (CCSpriteFrame*)m_pSpriteFrames->objectForKey(pszName); + if (!frame) { // try alias dictionary - CCString *key = (CCString*)m_pSpriteFramesAliases->objectForKey(string(pszName)); + CCString *key = (CCString*)m_pSpriteFramesAliases->objectForKey(pszName); if (key) { - frame = m_pSpriteFrames->objectForKey(key->m_sString); + frame = (CCSpriteFrame*)m_pSpriteFrames->objectForKey(key->c_str()); if (! frame) { CCLOG("cocos2d: CCSpriteFrameCahce: Frame '%s' not found", pszName); @@ -394,13 +390,14 @@ CCSpriteFrame* CCSpriteFrameCache::spriteFrameByName(const char *pszName) return frame; } -const char * CCSpriteFrameCache::valueForKey(const char *key, CCDictionary *dict) +const char * CCSpriteFrameCache::valueForKey(const char *key, CCDictionary *dict) { if (dict) { - CCString *pString = (CCString*)dict->objectForKey(std::string(key)); + CCString *pString = (CCString*)dict->objectForKey(key); return pString ? pString->m_sString.c_str() : ""; } return ""; } -}//namespace cocos2d + +NS_CC_END diff --git a/cocos2dx/support/CCArray.cpp b/cocos2dx/support/CCArray.cpp index ee9c9e5a5d..525037714b 100644 --- a/cocos2dx/support/CCArray.cpp +++ b/cocos2dx/support/CCArray.cpp @@ -25,8 +25,7 @@ THE SOFTWARE. #include "CCArray.h" -namespace cocos2d -{ +NS_CC_BEGIN CCArray* CCArray::array() { @@ -158,20 +157,20 @@ void CCArray::insertObject(CCObject* object, unsigned int index) ccArrayInsertObjectAtIndex(data, object, index); } -void CCArray::removeLastObject() +void CCArray::removeLastObject(bool bReleaseObj) { CCAssert(data->num, "no objects added"); - ccArrayRemoveObjectAtIndex(data, data->num-1); + ccArrayRemoveObjectAtIndex(data, data->num-1, bReleaseObj); } -void CCArray::removeObject(CCObject* object) +void CCArray::removeObject(CCObject* object, bool bReleaseObj/* = true*/) { - ccArrayRemoveObject(data, object); + ccArrayRemoveObject(data, object, bReleaseObj); } -void CCArray::removeObjectAtIndex(unsigned int index) +void CCArray::removeObjectAtIndex(unsigned int index, bool bReleaseObj) { - ccArrayRemoveObjectAtIndex(data, index); + ccArrayRemoveObjectAtIndex(data, index, bReleaseObj); } void CCArray::removeObjectsInArray(CCArray* otherArray) @@ -242,4 +241,20 @@ CCArray::~CCArray() ccArrayFree(data); } +void CCArray::replaceObjectAtIndex(unsigned int uIndex, CCObject* pObject, bool bReleaseObject/* = true*/) +{ + if (bReleaseObject && uIndex < data->num && data->arr[uIndex] != NULL) + { + data->arr[uIndex]->release(); + } + + data->arr[uIndex] = pObject; + + // add the ref + if (pObject) + { + pObject->retain(); + } } + +NS_CC_END diff --git a/cocos2dx/support/CCProfiling.cpp b/cocos2dx/support/CCProfiling.cpp index 7e87947912..eaca68e400 100644 --- a/cocos2dx/support/CCProfiling.cpp +++ b/cocos2dx/support/CCProfiling.cpp @@ -71,7 +71,7 @@ void CCProfiler::releaseAllTimers() bool CCProfiler::init() { - m_pActiveTimers = new CCMutableDictionary(); + m_pActiveTimers = new CCDictionary(); return true; } @@ -82,10 +82,10 @@ CCProfiler::~CCProfiler(void) void CCProfiler::displayTimers() { - vector allKeys = m_pActiveTimers->allKeys(); - for (vector::iterator it = allKeys.begin(); it != allKeys.end(); ++it) + CCDictElement* pElement = NULL; + CCDICT_FOREACH(m_pActiveTimers, pElement) { - CCProfilingTimer* timer = m_pActiveTimers->objectForKey(*it); + CCProfilingTimer* timer = (CCProfilingTimer*)pElement->getObject(); CCLog(timer->description()); } } @@ -130,7 +130,7 @@ void CCProfilingTimer::reset() void CCProfilingBeginTimingBlock(const char *timerName) { CCProfiler* p = CCProfiler::sharedProfiler(); - CCProfilingTimer *timer = p->m_pActiveTimers->objectForKey(timerName); + CCProfilingTimer* timer = (CCProfilingTimer*)p->m_pActiveTimers->objectForKey(timerName); if( ! timer ) { timer = p->createAndAddTimerWithName(timerName); @@ -144,7 +144,7 @@ void CCProfilingBeginTimingBlock(const char *timerName) void CCProfilingEndTimingBlock(const char *timerName) { CCProfiler* p = CCProfiler::sharedProfiler(); - CCProfilingTimer *timer = p->m_pActiveTimers->objectForKey(timerName); + CCProfilingTimer* timer = (CCProfilingTimer*)p->m_pActiveTimers->objectForKey(timerName); CCAssert(timer, "CCProfilingTimer not found"); @@ -164,7 +164,7 @@ void CCProfilingEndTimingBlock(const char *timerName) void CCProfilingResetTimingBlock(const char *timerName) { CCProfiler* p = CCProfiler::sharedProfiler(); - CCProfilingTimer *timer = p->m_pActiveTimers->objectForKey(timerName); + CCProfilingTimer *timer = (CCProfilingTimer*)p->m_pActiveTimers->objectForKey(timerName); CCAssert(timer, "CCProfilingTimer not found"); diff --git a/cocos2dx/support/CCProfiling.h b/cocos2dx/support/CCProfiling.h index 8ca587ce35..cda86207db 100644 --- a/cocos2dx/support/CCProfiling.h +++ b/cocos2dx/support/CCProfiling.h @@ -29,7 +29,7 @@ THE SOFTWARE. #include #include "CCObject.h" #include "platform/platform.h" -#include "CCMutableDictionary.h" +#include "CCDictionary.h" NS_CC_BEGIN @@ -58,7 +58,7 @@ public: /** releases all timers */ void releaseAllTimers(); - CCMutableDictionary* m_pActiveTimers; + CCDictionary* m_pActiveTimers; }; class CCProfilingTimer : public CCObject diff --git a/cocos2dx/support/data_support/ccCArray.h b/cocos2dx/support/data_support/ccCArray.h index 5ebc8956d6..9469f45c48 100644 --- a/cocos2dx/support/data_support/ccCArray.h +++ b/cocos2dx/support/data_support/ccCArray.h @@ -45,7 +45,7 @@ THE SOFTWARE. #include "CCObject.h" #include "ccMacros.h" -namespace cocos2d { +NS_CC_BEGIN // Easy integration #define CCARRAYDATA_FOREACH(__array__, __object__) \ @@ -86,9 +86,7 @@ static inline void ccArrayFree(ccArray *arr) ccArrayRemoveAllObjects(arr); - //delete arr->m_pObjectArray; free(arr->arr); - free(arr); } @@ -225,15 +223,19 @@ static inline void ccArrayRemoveAllObjects(ccArray *arr) /** Removes object at specified index and pushes back all subsequent objects. Behaviour undefined if index outside [0, num-1]. */ -static inline void ccArrayRemoveObjectAtIndex(ccArray *arr, unsigned int index) +static inline void ccArrayRemoveObjectAtIndex(ccArray *arr, unsigned int index, bool bReleaseObj) { - arr->arr[index]->release(); + if (bReleaseObj) + { + arr->arr[index]->release(); + } + arr->num--; unsigned int remaining = arr->num - index; if (remaining > 0) { - memmove(&arr->arr[index], &arr->arr[index+1], remaining * sizeof(void*)); + memmove(&arr->arr[index], &arr->arr[index+1], remaining * sizeof(void*)); } } @@ -252,18 +254,20 @@ static inline void ccArrayFastRemoveObject(ccArray *arr, CCObject* object) { unsigned int index = ccArrayGetIndexOfObject(arr, object); if (index != UINT_MAX) + { ccArrayFastRemoveObjectAtIndex(arr, index); + } } /** Searches for the first occurance of object and removes it. If object is not found the function has no effect. */ -static inline void ccArrayRemoveObject(ccArray *arr, CCObject* object) +static inline void ccArrayRemoveObject(ccArray *arr, CCObject* object, bool bReleaseObj) { unsigned int index = ccArrayGetIndexOfObject(arr, object); if (index != UINT_MAX) { - ccArrayRemoveObjectAtIndex(arr, index); + ccArrayRemoveObjectAtIndex(arr, index, bReleaseObj); } } @@ -273,7 +277,7 @@ static inline void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr) { for( unsigned int i = 0; i < minusArr->num; i++) { - ccArrayRemoveObject(arr, minusArr->arr[i]); + ccArrayRemoveObject(arr, minusArr->arr[i], true); } } @@ -287,7 +291,7 @@ static inline void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) { if( ccArrayContainsObject(minusArr, arr->arr[i]) ) { - delete arr->arr[i]; + arr->arr[i]->release(); back++; } else @@ -496,6 +500,6 @@ static inline void ccCArrayFullRemoveArray(ccCArray *arr, ccCArray *minusArr) arr->num -= back; } -} +NS_CC_END #endif // CC_ARRAY_H diff --git a/cocos2dx/support/data_support/uthash.h b/cocos2dx/support/data_support/uthash.h index 0599baf923..04f672371b 100644 --- a/cocos2dx/support/data_support/uthash.h +++ b/cocos2dx/support/data_support/uthash.h @@ -1,26 +1,25 @@ -/**************************************************************************** -Copyright (c) 2010 cocos2d-x.org - -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. -****************************************************************************/ +/* +Copyright (c) 2003-2010, Troy D. Hanson http://uthash.sourceforge.net +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ #ifndef __SUPPORT_DATA_SUPPORT_UTHASH_H__ #define __SUPPORT_DATA_SUPPORT_UTHASH_H__ diff --git a/cocos2dx/textures/CCTextureCache.cpp b/cocos2dx/textures/CCTextureCache.cpp index fdd60cc50f..0b67183b0a 100644 --- a/cocos2dx/textures/CCTextureCache.cpp +++ b/cocos2dx/textures/CCTextureCache.cpp @@ -41,8 +41,11 @@ THE SOFTWARE. #include "pthread.h" #include "CCThread.h" #include "semaphore.h" +#include "CCString.h" -namespace cocos2d { +using namespace std; + +NS_CC_BEGIN typedef struct _AsyncStruct { @@ -169,7 +172,7 @@ CCTextureCache::CCTextureCache() { CCAssert(g_sharedTextureCache == NULL, "Attempted to allocate a second instance of a singleton."); - m_pTextures = new CCMutableDictionary(); + m_pTextures = new CCDictionary(); } CCTextureCache::~CCTextureCache() @@ -205,7 +208,7 @@ void CCTextureCache::addImageAsync(const char *path, CCObject *target, SEL_CallF CCFileUtils::ccRemoveHDSuffixFromFile(pathKey); pathKey = CCFileUtils::fullPathFromRelativePath(pathKey.c_str()); - texture = m_pTextures->objectForKey(pathKey); + texture = (CCTexture2D*)m_pTextures->objectForKey(pathKey.c_str()); std::string fullpath = pathKey; if (texture != NULL) @@ -326,7 +329,7 @@ CCTexture2D * CCTextureCache::addImage(const char * path) CCFileUtils::ccRemoveHDSuffixFromFile(pathKey); pathKey = CCFileUtils::fullPathFromRelativePath(pathKey.c_str()); - texture = m_pTextures->objectForKey(pathKey); + texture = (CCTexture2D*)m_pTextures->objectForKey(pathKey.c_str()); std::string fullpath = pathKey; // (CCFileUtils::fullPathFromRelativePath(path)); if( ! texture ) @@ -362,7 +365,7 @@ CCTexture2D * CCTextureCache::addImage(const char * path) VolatileTexture::addImageTexture(texture, fullpath.c_str(), CCImage::kFmtJpg); #endif - m_pTextures->setObject(texture, pathKey); + m_pTextures->setObject(texture, pathKey.c_str()); // autorelease prevents possible crash in multithreaded environments texture->autorelease(); } @@ -390,7 +393,7 @@ CCTexture2D * CCTextureCache::addImage(const char * path) VolatileTexture::addImageTexture(texture, fullpath.c_str(), CCImage::kFmtPng); #endif - m_pTextures->setObject(texture, pathKey); + m_pTextures->setObject(texture, pathKey.c_str()); // autorelease prevents possible crash in multithreaded environments texture->autorelease(); } @@ -454,7 +457,7 @@ CCTexture2D * CCTextureCache::addPVRImage(const char* path) // remove possible -HD suffix to prevent caching the same image twice (issue #1040) CCFileUtils::ccRemoveHDSuffixFromFile(key); - if( (tex = m_pTextures->objectForKey(key)) ) + if( (tex = (CCTexture2D*)m_pTextures->objectForKey(key.c_str())) ) { return tex; } @@ -468,7 +471,7 @@ CCTexture2D * CCTextureCache::addPVRImage(const char* path) // cache the texture file name VolatileTexture::addImageTexture(tex, fullpath.c_str(), CCImage::kFmtRawData); #endif - m_pTextures->setObject(tex, key); + m_pTextures->setObject(tex, key.c_str()); tex->autorelease(); } else @@ -497,7 +500,7 @@ CCTexture2D* CCTextureCache::addUIImage(CCImage *image, const char *key) do { // If key is nil, then create a new texture each time - if(key && (texture = m_pTextures->objectForKey(forKey))) + if(key && (texture = (CCTexture2D *)m_pTextures->objectForKey(forKey.c_str()))) { break; } @@ -508,7 +511,7 @@ CCTexture2D* CCTextureCache::addUIImage(CCImage *image, const char *key) if(key && texture) { - m_pTextures->setObject(texture, forKey); + m_pTextures->setObject(texture, forKey.c_str()); texture->autorelease(); } else @@ -530,15 +533,15 @@ void CCTextureCache::removeAllTextures() void CCTextureCache::removeUnusedTextures() { - std::vector keys = m_pTextures->allKeys(); - std::vector::iterator it; - for (it = keys.begin(); it != keys.end(); ++it) + CCDictElement* pElement = NULL; + CCDICT_FOREACH(m_pTextures, pElement) { - CCTexture2D *value = m_pTextures->objectForKey(*it); + CCLOG("cocos2d: CCTextureCache: texture: %s", pElement->getStrKey()); + CCTexture2D *value = (CCTexture2D*)pElement->getObject(); if (value->retainCount() == 1) { - CCLOG("cocos2d: CCTextureCache: removing unused texture: %s", (*it).c_str()); - m_pTextures->removeObjectForKey(*it); + CCLOG("cocos2d: CCTextureCache: removing unused texture: %s", pElement->getStrKey()); + m_pTextures->removeObjectForKey(pElement->getStrKey()); } } } @@ -548,11 +551,12 @@ void CCTextureCache::removeTexture(CCTexture2D* texture) if( ! texture ) return; - std::vector keys = m_pTextures->allKeysForObject(texture); - - for (unsigned int i = 0; i < keys.size(); i++) + CCArray* keys = m_pTextures->allKeysForObject(texture); + CCObject* pObj; + CCARRAY_FOREACH(keys, pObj) { - m_pTextures->removeObjectForKey(keys[i]); + CCString* pKey = (CCString*)pObj; + m_pTextures->removeObjectForKey(pKey->c_str()); } } @@ -564,13 +568,12 @@ void CCTextureCache::removeTextureForKey(const char *textureKeyName) } string fullPath = CCFileUtils::fullPathFromRelativePath(textureKeyName); - m_pTextures->removeObjectForKey(fullPath); + m_pTextures->removeObjectForKey(fullPath.c_str()); } CCTexture2D* CCTextureCache::textureForKey(const char* key) { - std::string strKey = CCFileUtils::fullPathFromRelativePath(key); - return m_pTextures->objectForKey(strKey); + return (CCTexture2D*)m_pTextures->objectForKey(CCFileUtils::fullPathFromRelativePath(key)); } void CCTextureCache::reloadAllTextures() @@ -585,18 +588,17 @@ void CCTextureCache::dumpCachedTextureInfo() unsigned int count = 0; unsigned int totalBytes = 0; - vector keys = m_pTextures->allKeys(); - vector::iterator iter; - for (iter = keys.begin(); iter != keys.end(); iter++) + CCDictElement* pElement = NULL; + CCDICT_FOREACH(m_pTextures, pElement) { - CCTexture2D *tex = m_pTextures->objectForKey(*iter); + CCTexture2D* tex = (CCTexture2D*)pElement->getObject(); unsigned int bpp = tex->bitsPerPixelForFormat(); // Each texture takes up width * height * bytesPerPixel bytes. unsigned int bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8; totalBytes += bytes; count++; CCLOG("cocos2d: \"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB", - (*iter).c_str(), + pElement->getStrKey(), (long)tex->retainCount(), (long)tex->getName(), (long)tex->getPixelsWide(), @@ -797,5 +799,5 @@ void VolatileTexture::reloadAllTextures() #endif // CC_ENABLE_CACHE_TEXTTURE_DATA -}//namespace cocos2d +NS_CC_END diff --git a/cocos2dx/tileMap_parallax_nodes/CCParallaxNode.cpp b/cocos2dx/tileMap_parallax_nodes/CCParallaxNode.cpp index 25c7dc25d6..d8027db723 100644 --- a/cocos2dx/tileMap_parallax_nodes/CCParallaxNode.cpp +++ b/cocos2dx/tileMap_parallax_nodes/CCParallaxNode.cpp @@ -98,7 +98,7 @@ namespace cocos2d { CCPointObject *point = (CCPointObject*)m_pParallaxArray->arr[i]; if( point->getChild()->isEqual(child)) { - ccArrayRemoveObjectAtIndex(m_pParallaxArray, i); + ccArrayRemoveObjectAtIndex(m_pParallaxArray, i, true); break; } } diff --git a/cocos2dx/tileMap_parallax_nodes/CCTMXLayer.cpp b/cocos2dx/tileMap_parallax_nodes/CCTMXLayer.cpp index 1e745326e2..745231772d 100644 --- a/cocos2dx/tileMap_parallax_nodes/CCTMXLayer.cpp +++ b/cocos2dx/tileMap_parallax_nodes/CCTMXLayer.cpp @@ -70,7 +70,7 @@ bool CCTMXLayer::initWithTilesetInfo(CCTMXTilesetInfo *tilesetInfo, CCTMXLayerIn m_uMinGID = layerInfo->m_uMinGID; m_uMaxGID = layerInfo->m_uMaxGID; m_cOpacity = layerInfo->m_cOpacity; - m_pProperties = CCStringToStringDictionary::dictionaryWithDictionary(layerInfo->getProperties()); + setProperties(CCDictionary::dictionaryWithDictionary(layerInfo->getProperties())); m_fContentScaleFactor = CCDirector::sharedDirector()->getContentScaleFactor(); // tilesetInfo @@ -194,10 +194,11 @@ void CCTMXLayer::setupTiles() } // CCTMXLayer - Properties -CCString *CCTMXLayer::propertyNamed(const char *propertyName) +CCString* CCTMXLayer::propertyNamed(const char *propertyName) { - return m_pProperties->objectForKey(std::string(propertyName)); + return (CCString*)m_pProperties->objectForKey(propertyName); } + void CCTMXLayer::parseInternalProperties() { // if cc_vertex=automatic, then tiles will be rendered using vertexz @@ -674,11 +675,11 @@ int CCTMXLayer::vertexZForPos(const CCPoint& pos) return ret; } -CCStringToStringDictionary * CCTMXLayer::getProperties() +CCDictionary * CCTMXLayer::getProperties() { return m_pProperties; } -void CCTMXLayer::setProperties(CCStringToStringDictionary* var) +void CCTMXLayer::setProperties(CCDictionary* var) { CC_SAFE_RETAIN(var); CC_SAFE_RELEASE(m_pProperties); diff --git a/cocos2dx/tileMap_parallax_nodes/CCTMXObjectGroup.cpp b/cocos2dx/tileMap_parallax_nodes/CCTMXObjectGroup.cpp index baa57fafcf..2c5a16c3f0 100644 --- a/cocos2dx/tileMap_parallax_nodes/CCTMXObjectGroup.cpp +++ b/cocos2dx/tileMap_parallax_nodes/CCTMXObjectGroup.cpp @@ -26,64 +26,67 @@ THE SOFTWARE. ****************************************************************************/ #include "CCTMXObjectGroup.h" #include "ccMacros.h" -namespace cocos2d { - //implementation CCTMXObjectGroup +NS_CC_BEGIN + +//implementation CCTMXObjectGroup - CCTMXObjectGroup::CCTMXObjectGroup() - :m_tPositionOffset(CCPointZero) - ,m_sGroupName("") - { - m_pObjects = new CCMutableArray(); - m_pProperties = new CCStringToStringDictionary(); - } - CCTMXObjectGroup::~CCTMXObjectGroup() - { - CCLOGINFO( "cocos2d: deallocing."); - CC_SAFE_RELEASE(m_pObjects); - CC_SAFE_RELEASE(m_pProperties); - } - CCStringToStringDictionary * CCTMXObjectGroup::objectNamed(const char *objectName) - { - if (m_pObjects && m_pObjects->count() > 0) +CCTMXObjectGroup::CCTMXObjectGroup() + :m_tPositionOffset(CCPointZero) + ,m_sGroupName("") +{ + m_pObjects = CCArray::array(); + m_pObjects->retain(); + m_pProperties = new CCDictionary(); +} +CCTMXObjectGroup::~CCTMXObjectGroup() +{ + CCLOGINFO( "cocos2d: deallocing."); + CC_SAFE_RELEASE(m_pObjects); + CC_SAFE_RELEASE(m_pProperties); +} +CCDictionary* CCTMXObjectGroup::objectNamed(const char *objectName) +{ + if (m_pObjects && m_pObjects->count() > 0) + { + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_pObjects, pObj) { - CCMutableArray::CCMutableArrayIterator it; - for (it = m_pObjects->begin(); it != m_pObjects->end(); ++it) + CCDictionary* pDict = (CCDictionary*)pObj; + CCString *name = (CCString*)pDict->objectForKey("name"); + if (name && name->m_sString == objectName) { - CCString *name = (*it)->objectForKey(std::string("name")); - if (name && name->m_sString == objectName) - { - return *it; - } + return pDict; } } - // object not found - return NULL; - } - CCString *CCTMXObjectGroup::propertyNamed(const char* propertyName) - { - return m_pProperties->objectForKey(std::string(propertyName)); } + // object not found + return NULL; +} +CCString* CCTMXObjectGroup::propertyNamed(const char* propertyName) +{ + return (CCString*)m_pProperties->objectForKey(propertyName); +} - CCStringToStringDictionary * CCTMXObjectGroup::getProperties() - { - return m_pProperties; - } - void CCTMXObjectGroup::setProperties(CCStringToStringDictionary * properties) - { - CC_SAFE_RETAIN(properties); - CC_SAFE_RELEASE(m_pProperties); - m_pProperties = properties; - } - CCMutableArray *CCTMXObjectGroup::getObjects() - { - return m_pObjects; - } - void CCTMXObjectGroup::setObjects(CCMutableArray * objects) - { - CC_SAFE_RETAIN(objects); - CC_SAFE_RELEASE(m_pObjects); - m_pObjects = objects; - } +CCDictionary* CCTMXObjectGroup::getProperties() +{ + return m_pProperties; +} +void CCTMXObjectGroup::setProperties(CCDictionary * properties) +{ + CC_SAFE_RETAIN(properties); + CC_SAFE_RELEASE(m_pProperties); + m_pProperties = properties; +} +CCArray* CCTMXObjectGroup::getObjects() +{ + return m_pObjects; +} +void CCTMXObjectGroup::setObjects(CCArray* objects) +{ + CC_SAFE_RETAIN(objects); + CC_SAFE_RELEASE(m_pObjects); + m_pObjects = objects; +} -}// namespace cocos2d \ No newline at end of file +NS_CC_END diff --git a/cocos2dx/tileMap_parallax_nodes/CCTMXTiledMap.cpp b/cocos2dx/tileMap_parallax_nodes/CCTMXTiledMap.cpp index 17b3bdac2e..88ab0a7431 100644 --- a/cocos2dx/tileMap_parallax_nodes/CCTMXTiledMap.cpp +++ b/cocos2dx/tileMap_parallax_nodes/CCTMXTiledMap.cpp @@ -101,24 +101,24 @@ CCTMXTiledMap::~CCTMXTiledMap() CC_SAFE_RELEASE(m_pTileProperties); } -CCMutableArray * CCTMXTiledMap::getObjectGroups() +CCArray* CCTMXTiledMap::getObjectGroups() { return m_pObjectGroups; } -void CCTMXTiledMap::setObjectGroups(CCMutableArray* var) +void CCTMXTiledMap::setObjectGroups(CCArray* var) { CC_SAFE_RETAIN(var); CC_SAFE_RELEASE(m_pObjectGroups); m_pObjectGroups = var; } -CCStringToStringDictionary * CCTMXTiledMap::getProperties() +CCDictionary * CCTMXTiledMap::getProperties() { return m_pProperties; } -void CCTMXTiledMap::setProperties(CCStringToStringDictionary* var) +void CCTMXTiledMap::setProperties(CCDictionary* var) { CC_SAFE_RETAIN(var); CC_SAFE_RELEASE(m_pProperties); @@ -141,14 +141,14 @@ CCTMXLayer * CCTMXTiledMap::parseLayer(CCTMXLayerInfo *layerInfo, CCTMXMapInfo * CCTMXTilesetInfo * CCTMXTiledMap::tilesetForLayer(CCTMXLayerInfo *layerInfo, CCTMXMapInfo *mapInfo) { CCSize size = layerInfo->m_tLayerSize; - CCMutableArray* tilesets = mapInfo->getTilesets(); + CCArray* tilesets = mapInfo->getTilesets(); if (tilesets && tilesets->count()>0) { - CCTMXTilesetInfo *tileset = NULL; - CCMutableArray::CCMutableArrayRevIterator rit; - for (rit = tilesets->rbegin(); rit != tilesets->rend(); ++rit) + CCTMXTilesetInfo* tileset = NULL; + CCObject* pObj = NULL; + CCARRAY_FOREACH_REVERSE(tilesets, pObj); { - tileset = *rit; + tileset = (CCTMXTilesetInfo*)pObj; if (tileset) { for( unsigned int y=0; y < size.height; y++ ) @@ -179,7 +179,7 @@ CCTMXTilesetInfo * CCTMXTiledMap::tilesetForLayer(CCTMXLayerInfo *layerInfo, CCT } // If all the tiles are 0, return empty tileset - CCLOG("cocos2d: Warning: TMX Layer '%@' has no tiles", layerInfo->m_sName.c_str()); + CCLOG("cocos2d: Warning: TMX Layer '%s' has no tiles", layerInfo->m_sName.c_str()); return NULL; } @@ -203,14 +203,14 @@ void CCTMXTiledMap::buildWithMapInfo(CCTMXMapInfo* mapInfo) int idx=0; - CCMutableArray* layers = mapInfo->getLayers(); + CCArray* layers = mapInfo->getLayers(); if (layers && layers->count()>0) { - CCTMXLayerInfo *layerInfo = NULL; - CCMutableArray::CCMutableArrayIterator it; - for (it = layers->begin(); it != layers->end(); ++it) + CCTMXLayerInfo* layerInfo = NULL; + CCObject* pObj = NULL; + CCARRAY_FOREACH(layers, pObj) { - layerInfo = *it; + layerInfo = (CCTMXLayerInfo*)pObj; if (layerInfo && layerInfo->m_bVisible) { CCTMXLayer *child = parseLayer(layerInfo, mapInfo); @@ -257,11 +257,11 @@ CCTMXObjectGroup * CCTMXTiledMap::objectGroupNamed(const char *groupName) std::string sGroupName = groupName; if (m_pObjectGroups && m_pObjectGroups->count()>0) { - CCTMXObjectGroup *objectGroup; - CCMutableArray::CCMutableArrayIterator it; - for (it = m_pObjectGroups->begin(); it != m_pObjectGroups->end(); ++it) + CCTMXObjectGroup* objectGroup = NULL; + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_pObjectGroups, pObj) { - objectGroup = (CCTMXObjectGroup*)(*it); + objectGroup = (CCTMXObjectGroup*)(pObj); if (objectGroup && objectGroup->getGroupName() == sGroupName) { return objectGroup; @@ -273,13 +273,14 @@ CCTMXObjectGroup * CCTMXTiledMap::objectGroupNamed(const char *groupName) return NULL; } -CCString * CCTMXTiledMap::propertyNamed(const char *propertyName) +CCString* CCTMXTiledMap::propertyNamed(const char *propertyName) { - return m_pProperties->objectForKey(std::string(propertyName)); + return (CCString*)m_pProperties->objectForKey(propertyName); } -CCDictionary * CCTMXTiledMap::propertiesForGID(int GID) + +CCDictionary* CCTMXTiledMap::propertiesForGID(int GID) { - return m_pTileProperties->objectForKey(GID); + return (CCDictionary*)m_pTileProperties->objectForKey(GID); } diff --git a/cocos2dx/tileMap_parallax_nodes/CCTMXXMLParser.cpp b/cocos2dx/tileMap_parallax_nodes/CCTMXXMLParser.cpp index 751c2db40e..7314407990 100644 --- a/cocos2dx/tileMap_parallax_nodes/CCTMXXMLParser.cpp +++ b/cocos2dx/tileMap_parallax_nodes/CCTMXXMLParser.cpp @@ -35,6 +35,7 @@ THE SOFTWARE. #include "support/base64.h" #include "platform/platform.h" +using namespace std; /* #if (CC_TARGET_PLATFORM == CC_PLATFORM_MARMALADE) #include "expat.h" @@ -46,609 +47,617 @@ THE SOFTWARE. #endf */ -namespace cocos2d { +NS_CC_BEGIN - /* - void tmx_startElement(void *ctx, const xmlChar *name, const xmlChar **atts); - void tmx_endElement(void *ctx, const xmlChar *name); - void tmx_characters(void *ctx, const xmlChar *ch, int len); - */ +/* +void tmx_startElement(void *ctx, const xmlChar *name, const xmlChar **atts); +void tmx_endElement(void *ctx, const xmlChar *name); +void tmx_characters(void *ctx, const xmlChar *ch, int len); +*/ + +static const char* valueForKey(const char *key, std::map* dict) +{ + if (dict) + { + std::map::iterator it = dict->find(key); + return it!=dict->end() ? it->second.c_str() : ""; + } + return ""; +} +// implementation CCTMXLayerInfo +CCTMXLayerInfo::CCTMXLayerInfo() + : m_sName("") + , m_pTiles(NULL) + , m_bOwnTiles(true) + , m_uMinGID(100000) + , m_uMaxGID(0) + , m_tOffset(CCPointZero) +{ + m_pProperties= new CCDictionary();; +} +CCTMXLayerInfo::~CCTMXLayerInfo() +{ + CCLOGINFO("cocos2d: deallocing."); + CC_SAFE_RELEASE(m_pProperties); + if( m_bOwnTiles && m_pTiles ) + { + delete [] m_pTiles; + m_pTiles = NULL; + } +} +CCDictionary * CCTMXLayerInfo::getProperties() +{ + return m_pProperties; +} +void CCTMXLayerInfo::setProperties(CCDictionary* var) +{ + CC_SAFE_RETAIN(var); + CC_SAFE_RELEASE(m_pProperties); + m_pProperties = var; +} + +// implementation CCTMXTilesetInfo +CCTMXTilesetInfo::CCTMXTilesetInfo() + :m_uFirstGid(0) + ,m_tTileSize(CCSizeZero) + ,m_uSpacing(0) + ,m_uMargin(0) + ,m_tImageSize(CCSizeZero) +{ +} +CCTMXTilesetInfo::~CCTMXTilesetInfo() +{ + CCLOGINFO("cocos2d: deallocing."); +} +CCRect CCTMXTilesetInfo::rectForGID(unsigned int gid) +{ + CCRect rect; + rect.size = m_tTileSize; + gid &= kCCFlippedMask; + gid = gid - m_uFirstGid; + int max_x = (int)((m_tImageSize.width - m_uMargin*2 + m_uSpacing) / (m_tTileSize.width + m_uSpacing)); + // int max_y = (imageSize.height - margin*2 + spacing) / (tileSize.height + spacing); + rect.origin.x = (gid % max_x) * (m_tTileSize.width + m_uSpacing) + m_uMargin; + rect.origin.y = (gid / max_x) * (m_tTileSize.height + m_uSpacing) + m_uMargin; + return rect; +} + +// implementation CCTMXMapInfo + +CCTMXMapInfo * CCTMXMapInfo::formatWithTMXFile(const char *tmxFile) +{ + CCTMXMapInfo *pRet = new CCTMXMapInfo(); + if(pRet->initWithTMXFile(tmxFile)) + { + pRet->autorelease(); + return pRet; + } + CC_SAFE_DELETE(pRet); + return NULL; +} + +CCTMXMapInfo * CCTMXMapInfo::formatWithXML(const char* tmxString, const char* resourcePath) +{ + CCTMXMapInfo *pRet = new CCTMXMapInfo(); + if(pRet->initWithXML(tmxString, resourcePath)) + { + pRet->autorelease(); + return pRet; + } + CC_SAFE_DELETE(pRet); + return NULL; +} + +void CCTMXMapInfo::internalInit(const char* tmxFileName, const char* resourcePath) +{ + m_pTilesets = CCArray::array(); + m_pTilesets->retain(); + + m_pLayers = CCArray::array(); + m_pLayers->retain(); + + m_sTMXFileName = CCFileUtils::fullPathFromRelativePath(tmxFileName); + m_sResources = resourcePath; + m_pObjectGroups = CCArray::array(); + m_pObjectGroups->retain(); + + m_pProperties = new CCDictionary(); + m_pTileProperties = new CCDictionary(); + + // tmp vars + m_sCurrentString = ""; + m_bStoringCharacters = false; + m_nLayerAttribs = TMXLayerAttribNone; + m_nParentElement = TMXPropertyNone; +} +bool CCTMXMapInfo::initWithXML(const char* tmxString, const char* resourcePath) +{ + internalInit("", resourcePath); + return parseXMLString(tmxString); +} + +bool CCTMXMapInfo::initWithTMXFile(const char *tmxFile) +{ + internalInit(tmxFile, ""); + return parseXMLFile(m_sTMXFileName.c_str()); +} + +CCTMXMapInfo::CCTMXMapInfo() + :m_tMapSize(CCSizeZero) + ,m_tTileSize(CCSizeZero) + ,m_pLayers(NULL) + ,m_pTilesets(NULL) + ,m_pObjectGroups(NULL) + ,m_nLayerAttribs(0) + ,m_bStoringCharacters(false) + ,m_pProperties(NULL) + ,m_pTileProperties(NULL) +{ +} +CCTMXMapInfo::~CCTMXMapInfo() +{ + CCLOGINFO("cocos2d: deallocing."); + CC_SAFE_RELEASE(m_pTilesets); + CC_SAFE_RELEASE(m_pLayers); + CC_SAFE_RELEASE(m_pProperties); + CC_SAFE_RELEASE(m_pTileProperties); + CC_SAFE_RELEASE(m_pObjectGroups); +} +CCArray* CCTMXMapInfo::getLayers() +{ + return m_pLayers; +} +void CCTMXMapInfo::setLayers(CCArray* var) +{ + CC_SAFE_RETAIN(var); + CC_SAFE_RELEASE(m_pLayers); + m_pLayers = var; +} +CCArray* CCTMXMapInfo::getTilesets() +{ + return m_pTilesets; +} +void CCTMXMapInfo::setTilesets(CCArray* var) +{ + CC_SAFE_RETAIN(var); + CC_SAFE_RELEASE(m_pTilesets); + m_pTilesets = var; +} +CCArray* CCTMXMapInfo::getObjectGroups() +{ + return m_pObjectGroups; +} +void CCTMXMapInfo::setObjectGroups(CCArray* var) +{ + CC_SAFE_RETAIN(var); + CC_SAFE_RELEASE(m_pObjectGroups); + m_pObjectGroups = var; +} +CCDictionary * CCTMXMapInfo::getProperties() +{ + return m_pProperties; +} +void CCTMXMapInfo::setProperties(CCDictionary* var) +{ + CC_SAFE_RETAIN(var); + CC_SAFE_RELEASE(m_pProperties); + m_pProperties = var; +} + +CCDictionary* CCTMXMapInfo::getTileProperties() +{ + return m_pTileProperties; +} + +void CCTMXMapInfo::setTileProperties(CCDictionary* tileProperties) +{ + CC_SAFE_RETAIN(tileProperties); + CC_SAFE_RELEASE(m_pTileProperties); + m_pTileProperties = tileProperties; +} + +bool CCTMXMapInfo::parseXMLString(const char *xmlString) +{ + // TODO: + return false; +} + +bool CCTMXMapInfo::parseXMLData(const char* data) +{ + // TODO: + return false; +} + +bool CCTMXMapInfo::parseXMLFile(const char *xmlFilename) +{ + CCSAXParser parser; - static const char* valueForKey(const char *key, std::map* dict) + if (false == parser.init("UTF-8") ) { - if (dict) - { - std::map::iterator it = dict->find(key); - return it!=dict->end() ? it->second.c_str() : ""; - } - return ""; - } - // implementation CCTMXLayerInfo - CCTMXLayerInfo::CCTMXLayerInfo() - : m_sName("") - , m_pTiles(NULL) - , m_bOwnTiles(true) - , m_uMinGID(100000) - , m_uMaxGID(0) - , m_tOffset(CCPointZero) - { - m_pProperties= new CCStringToStringDictionary();; - } - CCTMXLayerInfo::~CCTMXLayerInfo() - { - CCLOGINFO("cocos2d: deallocing."); - CC_SAFE_RELEASE(m_pProperties); - if( m_bOwnTiles && m_pTiles ) - { - delete [] m_pTiles; - m_pTiles = NULL; - } - } - CCStringToStringDictionary * CCTMXLayerInfo::getProperties() - { - return m_pProperties; - } - void CCTMXLayerInfo::setProperties(CCStringToStringDictionary* var) - { - CC_SAFE_RETAIN(var); - CC_SAFE_RELEASE(m_pProperties); - m_pProperties = var; - } - - // implementation CCTMXTilesetInfo - CCTMXTilesetInfo::CCTMXTilesetInfo() - :m_uFirstGid(0) - ,m_tTileSize(CCSizeZero) - ,m_uSpacing(0) - ,m_uMargin(0) - ,m_tImageSize(CCSizeZero) - { - } - CCTMXTilesetInfo::~CCTMXTilesetInfo() - { - CCLOGINFO("cocos2d: deallocing."); - } - CCRect CCTMXTilesetInfo::rectForGID(unsigned int gid) - { - CCRect rect; - rect.size = m_tTileSize; - gid &= kCCFlippedMask; - gid = gid - m_uFirstGid; - int max_x = (int)((m_tImageSize.width - m_uMargin*2 + m_uSpacing) / (m_tTileSize.width + m_uSpacing)); - // int max_y = (imageSize.height - margin*2 + spacing) / (tileSize.height + spacing); - rect.origin.x = (gid % max_x) * (m_tTileSize.width + m_uSpacing) + m_uMargin; - rect.origin.y = (gid / max_x) * (m_tTileSize.height + m_uSpacing) + m_uMargin; - return rect; - } - - // implementation CCTMXMapInfo - - CCTMXMapInfo * CCTMXMapInfo::formatWithTMXFile(const char *tmxFile) - { - CCTMXMapInfo *pRet = new CCTMXMapInfo(); - if(pRet->initWithTMXFile(tmxFile)) - { - pRet->autorelease(); - return pRet; - } - CC_SAFE_DELETE(pRet); - return NULL; - } - - CCTMXMapInfo * CCTMXMapInfo::formatWithXML(const char* tmxString, const char* resourcePath) - { - CCTMXMapInfo *pRet = new CCTMXMapInfo(); - if(pRet->initWithXML(tmxString, resourcePath)) - { - pRet->autorelease(); - return pRet; - } - CC_SAFE_DELETE(pRet); - return NULL; - } - - void CCTMXMapInfo::internalInit(const char* tmxFileName, const char* resourcePath) - { - m_pTilesets = new CCMutableArray(); - m_pLayers = new CCMutableArray(); - m_sTMXFileName = CCFileUtils::fullPathFromRelativePath(tmxFileName); - m_sResources = resourcePath; - m_pObjectGroups = new CCMutableArray(); - m_pProperties = new CCStringToStringDictionary(); - m_pTileProperties = new CCDictionary(); - - // tmp vars - m_sCurrentString = ""; - m_bStoringCharacters = false; - m_nLayerAttribs = TMXLayerAttribNone; - m_nParentElement = TMXPropertyNone; - } - bool CCTMXMapInfo::initWithXML(const char* tmxString, const char* resourcePath) - { - internalInit("", resourcePath); - return parseXMLString(tmxString); - } - - bool CCTMXMapInfo::initWithTMXFile(const char *tmxFile) - { - internalInit(tmxFile, ""); - return parseXMLFile(m_sTMXFileName.c_str()); - } - - CCTMXMapInfo::CCTMXMapInfo() - :m_tMapSize(CCSizeZero) - ,m_tTileSize(CCSizeZero) - ,m_pLayers(NULL) - ,m_pTilesets(NULL) - ,m_pObjectGroups(NULL) - ,m_nLayerAttribs(0) - ,m_bStoringCharacters(false) - ,m_pProperties(NULL) - ,m_pTileProperties(NULL) - { - } - CCTMXMapInfo::~CCTMXMapInfo() - { - CCLOGINFO("cocos2d: deallocing."); - CC_SAFE_RELEASE(m_pTilesets); - CC_SAFE_RELEASE(m_pLayers); - CC_SAFE_RELEASE(m_pProperties); - CC_SAFE_RELEASE(m_pTileProperties); - CC_SAFE_RELEASE(m_pObjectGroups); - } - CCMutableArray * CCTMXMapInfo::getLayers() - { - return m_pLayers; - } - void CCTMXMapInfo::setLayers(CCMutableArray* var) - { - CC_SAFE_RETAIN(var); - CC_SAFE_RELEASE(m_pLayers); - m_pLayers = var; - } - CCMutableArray * CCTMXMapInfo::getTilesets() - { - return m_pTilesets; - } - void CCTMXMapInfo::setTilesets(CCMutableArray* var) - { - CC_SAFE_RETAIN(var); - CC_SAFE_RELEASE(m_pTilesets); - m_pTilesets = var; - } - CCMutableArray * CCTMXMapInfo::getObjectGroups() - { - return m_pObjectGroups; - } - void CCTMXMapInfo::setObjectGroups(CCMutableArray* var) - { - CC_SAFE_RETAIN(var); - CC_SAFE_RELEASE(m_pObjectGroups); - m_pObjectGroups = var; - } - CCStringToStringDictionary * CCTMXMapInfo::getProperties() - { - return m_pProperties; - } - void CCTMXMapInfo::setProperties(CCStringToStringDictionary* var) - { - CC_SAFE_RETAIN(var); - CC_SAFE_RELEASE(m_pProperties); - m_pProperties = var; - } - CCDictionary * CCTMXMapInfo::getTileProperties() - { - return m_pTileProperties; - } - void CCTMXMapInfo::setTileProperties(CCDictionary * tileProperties) - { - CC_SAFE_RETAIN(tileProperties); - CC_SAFE_RELEASE(m_pTileProperties); - m_pTileProperties = tileProperties; - } - - bool CCTMXMapInfo::parseXMLString(const char *xmlString) - { - // TODO: return false; } + + parser.setDelegator(this); - bool CCTMXMapInfo::parseXMLData(const char* data) + return parser.parse(xmlFilename);; +} + + +// the XML parser calls here with all the elements +void CCTMXMapInfo::startElement(void *ctx, const char *name, const char **atts) +{ + CC_UNUSED_PARAM(ctx); + CCTMXMapInfo *pTMXMapInfo = this; + std::string elementName = (char*)name; + std::map *attributeDict = new std::map(); + if(atts && atts[0]) { - // TODO: - return false; + for(int i = 0; atts[i]; i += 2) + { + std::string key = (char*)atts[i]; + std::string value = (char*)atts[i+1]; + attributeDict->insert(pair(key, value)); + } } - - bool CCTMXMapInfo::parseXMLFile(const char *xmlFilename) + if(elementName == "map") { - CCSAXParser parser; - - if (false == parser.init("UTF-8") ) + std::string version = valueForKey("version", attributeDict); + if ( version != "1.0") { - return false; + CCLOG("cocos2d: TMXFormat: Unsupported TMX version: %@", version.c_str()); } - - parser.setDelegator(this); + std::string orientationStr = valueForKey("orientation", attributeDict); + if( orientationStr == "orthogonal") + pTMXMapInfo->setOrientation(CCTMXOrientationOrtho); + else if ( orientationStr == "isometric") + pTMXMapInfo->setOrientation(CCTMXOrientationIso); + else if( orientationStr == "hexagonal") + pTMXMapInfo->setOrientation(CCTMXOrientationHex); + else + CCLOG("cocos2d: TMXFomat: Unsupported orientation: %d", pTMXMapInfo->getOrientation()); - return parser.parse(xmlFilename);; - } + CCSize s; + s.width = (float)atof(valueForKey("width", attributeDict)); + s.height = (float)atof(valueForKey("height", attributeDict)); + pTMXMapInfo->setMapSize(s); + s.width = (float)atof(valueForKey("tilewidth", attributeDict)); + s.height = (float)atof(valueForKey("tileheight", attributeDict)); + pTMXMapInfo->setTileSize(s); - // the XML parser calls here with all the elements - void CCTMXMapInfo::startElement(void *ctx, const char *name, const char **atts) - { - CC_UNUSED_PARAM(ctx); - CCTMXMapInfo *pTMXMapInfo = this; - std::string elementName = (char*)name; - std::map *attributeDict = new std::map(); - if(atts && atts[0]) + // The parent element is now "map" + pTMXMapInfo->setParentElement(TMXPropertyMap); + } + else if(elementName == "tileset") + { + // If this is an external tileset then start parsing that + std::string externalTilesetFilename = valueForKey("source", attributeDict); + if (externalTilesetFilename != "") { - for(int i = 0; atts[i]; i += 2) - { - std::string key = (char*)atts[i]; - std::string value = (char*)atts[i+1]; - attributeDict->insert(pair(key, value)); - } + externalTilesetFilename = CCFileUtils::fullPathFromRelativeFile(externalTilesetFilename.c_str(), pTMXMapInfo->getTMXFileName()); + pTMXMapInfo->parseXMLFile(externalTilesetFilename.c_str()); } - if(elementName == "map") + else { - std::string version = valueForKey("version", attributeDict); - if ( version != "1.0") - { - CCLOG("cocos2d: TMXFormat: Unsupported TMX version: %@", version.c_str()); - } - std::string orientationStr = valueForKey("orientation", attributeDict); - if( orientationStr == "orthogonal") - pTMXMapInfo->setOrientation(CCTMXOrientationOrtho); - else if ( orientationStr == "isometric") - pTMXMapInfo->setOrientation(CCTMXOrientationIso); - else if( orientationStr == "hexagonal") - pTMXMapInfo->setOrientation(CCTMXOrientationHex); - else - CCLOG("cocos2d: TMXFomat: Unsupported orientation: %d", pTMXMapInfo->getOrientation()); - + CCTMXTilesetInfo *tileset = new CCTMXTilesetInfo(); + tileset->m_sName = valueForKey("name", attributeDict); + tileset->m_uFirstGid = (unsigned int)atoi(valueForKey("firstgid", attributeDict)); + tileset->m_uSpacing = (unsigned int)atoi(valueForKey("spacing", attributeDict)); + tileset->m_uMargin = (unsigned int)atoi(valueForKey("margin", attributeDict)); CCSize s; - s.width = (float)atof(valueForKey("width", attributeDict)); - s.height = (float)atof(valueForKey("height", attributeDict)); - pTMXMapInfo->setMapSize(s); - s.width = (float)atof(valueForKey("tilewidth", attributeDict)); s.height = (float)atof(valueForKey("tileheight", attributeDict)); - pTMXMapInfo->setTileSize(s); + tileset->m_tTileSize = s; - // The parent element is now "map" - pTMXMapInfo->setParentElement(TMXPropertyMap); - } - else if(elementName == "tileset") - { - // If this is an external tileset then start parsing that - std::string externalTilesetFilename = valueForKey("source", attributeDict); - if (externalTilesetFilename != "") - { - externalTilesetFilename = CCFileUtils::fullPathFromRelativeFile(externalTilesetFilename.c_str(), pTMXMapInfo->getTMXFileName()); - pTMXMapInfo->parseXMLFile(externalTilesetFilename.c_str()); - } - else - { - CCTMXTilesetInfo *tileset = new CCTMXTilesetInfo(); - tileset->m_sName = valueForKey("name", attributeDict); - tileset->m_uFirstGid = (unsigned int)atoi(valueForKey("firstgid", attributeDict)); - tileset->m_uSpacing = (unsigned int)atoi(valueForKey("spacing", attributeDict)); - tileset->m_uMargin = (unsigned int)atoi(valueForKey("margin", attributeDict)); - CCSize s; - s.width = (float)atof(valueForKey("tilewidth", attributeDict)); - s.height = (float)atof(valueForKey("tileheight", attributeDict)); - tileset->m_tTileSize = s; - - pTMXMapInfo->getTilesets()->addObject(tileset); - tileset->release(); - } - } - else if(elementName == "tile") - { - CCTMXTilesetInfo* info = pTMXMapInfo->getTilesets()->getLastObject(); - CCStringToStringDictionary *dict = new CCStringToStringDictionary(); - pTMXMapInfo->setParentGID(info->m_uFirstGid + atoi(valueForKey("id", attributeDict))); - pTMXMapInfo->getTileProperties()->setObject(dict, pTMXMapInfo->getParentGID()); - CC_SAFE_RELEASE(dict); - - pTMXMapInfo->setParentElement(TMXPropertyTile); - - } - else if(elementName == "layer") - { - CCTMXLayerInfo *layer = new CCTMXLayerInfo(); - layer->m_sName = valueForKey("name", attributeDict); - - CCSize s; - s.width = (float)atof(valueForKey("width", attributeDict)); - s.height = (float)atof(valueForKey("height", attributeDict)); - layer->m_tLayerSize = s; - - std::string visible = valueForKey("visible", attributeDict); - layer->m_bVisible = !(visible == "0"); - - std::string opacity = valueForKey("opacity", attributeDict); - if( opacity != "" ) - { - layer->m_cOpacity = (unsigned char)(255 * atof(opacity.c_str())); - } - else - { - layer->m_cOpacity = 255; - } - - float x = (float)atof(valueForKey("x", attributeDict)); - float y = (float)atof(valueForKey("y", attributeDict)); - layer->m_tOffset = ccp(x,y); - - pTMXMapInfo->getLayers()->addObject(layer); - layer->release(); - - // The parent element is now "layer" - pTMXMapInfo->setParentElement(TMXPropertyLayer); - - } - else if(elementName == "objectgroup") - { - CCTMXObjectGroup *objectGroup = new CCTMXObjectGroup(); - objectGroup->setGroupName(valueForKey("name", attributeDict)); - CCPoint positionOffset; - positionOffset.x = (float)atof(valueForKey("x", attributeDict)) * pTMXMapInfo->getTileSize().width; - positionOffset.y = (float)atof(valueForKey("y", attributeDict)) * pTMXMapInfo->getTileSize().height; - objectGroup->setPositionOffset(positionOffset); - - pTMXMapInfo->getObjectGroups()->addObject(objectGroup); - objectGroup->release(); - - // The parent element is now "objectgroup" - pTMXMapInfo->setParentElement(TMXPropertyObjectGroup); - - } - else if(elementName == "image") - { - CCTMXTilesetInfo *tileset = pTMXMapInfo->getTilesets()->getLastObject(); - - // build full path - std::string imagename = valueForKey("source", attributeDict); - tileset->m_sSourceImage = CCFileUtils::fullPathFromRelativeFile(imagename.c_str(), pTMXMapInfo->getTMXFileName()); - - } - else if(elementName == "data") - { - std::string encoding = valueForKey("encoding", attributeDict); - std::string compression = valueForKey("compression", attributeDict); - - if( encoding == "base64" ) - { - int layerAttribs = pTMXMapInfo->getLayerAttribs(); - pTMXMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribBase64); - pTMXMapInfo->setStoringCharacters(true); - - if( compression == "gzip" ) - { - layerAttribs = pTMXMapInfo->getLayerAttribs(); - pTMXMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribGzip); - } else - if (compression == "zlib") - { - layerAttribs = pTMXMapInfo->getLayerAttribs(); - pTMXMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribZlib); - } - CCAssert( compression == "" || compression == "gzip" || compression == "zlib", "TMX: unsupported compression method" ); - } - CCAssert( pTMXMapInfo->getLayerAttribs() != TMXLayerAttribNone, "TMX tile map: Only base64 and/or gzip/zlib maps are supported" ); - - } - else if(elementName == "object") - { - char buffer[32]; - CCTMXObjectGroup *objectGroup = pTMXMapInfo->getObjectGroups()->getLastObject(); - - // The value for "type" was blank or not a valid class name - // Create an instance of TMXObjectInfo to store the object and its properties - CCStringToStringDictionary *dict = new CCStringToStringDictionary(); - - // Set the name of the object to the value for "name" - std::string key = "name"; - CCString *value = new CCString(valueForKey("name", attributeDict)); - dict->setObject(value, key); - value->release(); - - // Assign all the attributes as key/name pairs in the properties dictionary - key = "type"; - value = new CCString(valueForKey("type", attributeDict)); - dict->setObject(value, key); - value->release(); - - int x = atoi(valueForKey("x", attributeDict)) + (int)objectGroup->getPositionOffset().x; - key = "x"; - sprintf(buffer, "%d", x); - value = new CCString(buffer); - dict->setObject(value, key); - value->release(); - - int y = atoi(valueForKey("y", attributeDict)) + (int)objectGroup->getPositionOffset().y; - // Correct y position. (Tiled uses Flipped, cocos2d uses Standard) - y = (int)(pTMXMapInfo->getMapSize().height * pTMXMapInfo->getTileSize().height) - y - atoi(valueForKey("height", attributeDict)); - key = "y"; - sprintf(buffer, "%d", y); - value = new CCString(buffer); - dict->setObject(value, key); - value->release(); - - key = "width"; - value = new CCString(valueForKey("width", attributeDict)); - dict->setObject(value, key); - value->release(); - - key = "height"; - value = new CCString(valueForKey("height", attributeDict)); - dict->setObject(value, key); - value->release(); - - // Add the object to the objectGroup - objectGroup->getObjects()->addObject(dict); - dict->release(); - - // The parent element is now "object" - pTMXMapInfo->setParentElement(TMXPropertyObject); - - } - else if(elementName == "property") - { - if ( pTMXMapInfo->getParentElement() == TMXPropertyNone ) - { - CCLOG( "TMX tile map: Parent element is unsupported. Cannot add property named '%s' with value '%s'", - valueForKey("name", attributeDict), valueForKey("value",attributeDict) ); - } - else if ( pTMXMapInfo->getParentElement() == TMXPropertyMap ) - { - // The parent element is the map - CCString *value = new CCString(valueForKey("value", attributeDict)); - std::string key = valueForKey("name", attributeDict); - pTMXMapInfo->getProperties()->setObject(value, key); - value->release(); - - } - else if ( pTMXMapInfo->getParentElement() == TMXPropertyLayer ) - { - // The parent element is the last layer - CCTMXLayerInfo *layer = pTMXMapInfo->getLayers()->getLastObject(); - CCString *value = new CCString(valueForKey("value", attributeDict)); - std::string key = valueForKey("name", attributeDict); - // Add the property to the layer - layer->getProperties()->setObject(value, key); - value->release(); - - } - else if ( pTMXMapInfo->getParentElement() == TMXPropertyObjectGroup ) - { - // The parent element is the last object group - CCTMXObjectGroup *objectGroup = pTMXMapInfo->getObjectGroups()->getLastObject(); - CCString *value = new CCString(valueForKey("value", attributeDict)); - std::string key = valueForKey("name", attributeDict); - objectGroup->getProperties()->setObject(value, key); - value->release(); - - } - else if ( pTMXMapInfo->getParentElement() == TMXPropertyObject ) - { - // The parent element is the last object - CCTMXObjectGroup *objectGroup = pTMXMapInfo->getObjectGroups()->getLastObject(); - CCStringToStringDictionary *dict = objectGroup->getObjects()->getLastObject(); - - std::string propertyName = valueForKey("name", attributeDict); - CCString *propertyValue = new CCString(valueForKey("value", attributeDict)); - dict->setObject(propertyValue, propertyName); - propertyValue->release(); - } - else if ( pTMXMapInfo->getParentElement() == TMXPropertyTile ) - { - CCStringToStringDictionary *dict; - dict = pTMXMapInfo->getTileProperties()->objectForKey(pTMXMapInfo->getParentGID()); - - std::string propertyName = valueForKey("name", attributeDict); - CCString *propertyValue = new CCString(valueForKey("value", attributeDict)); - dict->setObject(propertyValue, propertyName); - propertyValue->release(); - } - } - if (attributeDict) - { - attributeDict->clear(); - delete attributeDict; + pTMXMapInfo->getTilesets()->addObject(tileset); + tileset->release(); } } - - void CCTMXMapInfo::endElement(void *ctx, const char *name) + else if(elementName == "tile") { - CC_UNUSED_PARAM(ctx); - CCTMXMapInfo *pTMXMapInfo = this; - std::string elementName = (char*)name; + CCTMXTilesetInfo* info = (CCTMXTilesetInfo*)pTMXMapInfo->getTilesets()->lastObject(); + CCDictionary *dict = new CCDictionary(); + pTMXMapInfo->setParentGID(info->m_uFirstGid + atoi(valueForKey("id", attributeDict))); + pTMXMapInfo->getTileProperties()->setObject(dict, pTMXMapInfo->getParentGID()); + CC_SAFE_RELEASE(dict); + + pTMXMapInfo->setParentElement(TMXPropertyTile); - int len = 0; + } + else if(elementName == "layer") + { + CCTMXLayerInfo *layer = new CCTMXLayerInfo(); + layer->m_sName = valueForKey("name", attributeDict); - if(elementName == "data" && pTMXMapInfo->getLayerAttribs()&TMXLayerAttribBase64) + CCSize s; + s.width = (float)atof(valueForKey("width", attributeDict)); + s.height = (float)atof(valueForKey("height", attributeDict)); + layer->m_tLayerSize = s; + + std::string visible = valueForKey("visible", attributeDict); + layer->m_bVisible = !(visible == "0"); + + std::string opacity = valueForKey("opacity", attributeDict); + if( opacity != "" ) { - pTMXMapInfo->setStoringCharacters(false); + layer->m_cOpacity = (unsigned char)(255 * atof(opacity.c_str())); + } + else + { + layer->m_cOpacity = 255; + } - CCTMXLayerInfo *layer = pTMXMapInfo->getLayers()->getLastObject(); + float x = (float)atof(valueForKey("x", attributeDict)); + float y = (float)atof(valueForKey("y", attributeDict)); + layer->m_tOffset = ccp(x,y); - std::string currentString = pTMXMapInfo->getCurrentString(); - unsigned char *buffer; - len = base64Decode((unsigned char*)currentString.c_str(), (unsigned int)currentString.length(), &buffer); - if( ! buffer ) + pTMXMapInfo->getLayers()->addObject(layer); + layer->release(); + + // The parent element is now "layer" + pTMXMapInfo->setParentElement(TMXPropertyLayer); + + } + else if(elementName == "objectgroup") + { + CCTMXObjectGroup *objectGroup = new CCTMXObjectGroup(); + objectGroup->setGroupName(valueForKey("name", attributeDict)); + CCPoint positionOffset; + positionOffset.x = (float)atof(valueForKey("x", attributeDict)) * pTMXMapInfo->getTileSize().width; + positionOffset.y = (float)atof(valueForKey("y", attributeDict)) * pTMXMapInfo->getTileSize().height; + objectGroup->setPositionOffset(positionOffset); + + pTMXMapInfo->getObjectGroups()->addObject(objectGroup); + objectGroup->release(); + + // The parent element is now "objectgroup" + pTMXMapInfo->setParentElement(TMXPropertyObjectGroup); + + } + else if(elementName == "image") + { + CCTMXTilesetInfo* tileset = (CCTMXTilesetInfo*)pTMXMapInfo->getTilesets()->lastObject(); + + // build full path + std::string imagename = valueForKey("source", attributeDict); + tileset->m_sSourceImage = CCFileUtils::fullPathFromRelativeFile(imagename.c_str(), pTMXMapInfo->getTMXFileName()); + + } + else if(elementName == "data") + { + std::string encoding = valueForKey("encoding", attributeDict); + std::string compression = valueForKey("compression", attributeDict); + + if( encoding == "base64" ) + { + int layerAttribs = pTMXMapInfo->getLayerAttribs(); + pTMXMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribBase64); + pTMXMapInfo->setStoringCharacters(true); + + if( compression == "gzip" ) { - CCLOG("cocos2d: TiledMap: decode data error"); + layerAttribs = pTMXMapInfo->getLayerAttribs(); + pTMXMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribGzip); + } else + if (compression == "zlib") + { + layerAttribs = pTMXMapInfo->getLayerAttribs(); + pTMXMapInfo->setLayerAttribs(layerAttribs | TMXLayerAttribZlib); + } + CCAssert( compression == "" || compression == "gzip" || compression == "zlib", "TMX: unsupported compression method" ); + } + CCAssert( pTMXMapInfo->getLayerAttribs() != TMXLayerAttribNone, "TMX tile map: Only base64 and/or gzip/zlib maps are supported" ); + + } + else if(elementName == "object") + { + char buffer[32] = {0}; + CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)pTMXMapInfo->getObjectGroups()->lastObject(); + + // The value for "type" was blank or not a valid class name + // Create an instance of TMXObjectInfo to store the object and its properties + CCDictionary *dict = new CCDictionary(); + + // Set the name of the object to the value for "name" + std::string key = "name"; + CCString *value = new CCString(valueForKey("name", attributeDict)); + dict->setObject(value, key.c_str()); + value->release(); + + // Assign all the attributes as key/name pairs in the properties dictionary + key = "type"; + value = new CCString(valueForKey("type", attributeDict)); + dict->setObject(value, key.c_str()); + value->release(); + + int x = atoi(valueForKey("x", attributeDict)) + (int)objectGroup->getPositionOffset().x; + key = "x"; + sprintf(buffer, "%d", x); + value = new CCString(buffer); + dict->setObject(value, key.c_str()); + value->release(); + + int y = atoi(valueForKey("y", attributeDict)) + (int)objectGroup->getPositionOffset().y; + // Correct y position. (Tiled uses Flipped, cocos2d uses Standard) + y = (int)(pTMXMapInfo->getMapSize().height * pTMXMapInfo->getTileSize().height) - y - atoi(valueForKey("height", attributeDict)); + key = "y"; + sprintf(buffer, "%d", y); + value = new CCString(buffer); + dict->setObject(value, key.c_str()); + value->release(); + + key = "width"; + value = new CCString(valueForKey("width", attributeDict)); + dict->setObject(value, key.c_str()); + value->release(); + + key = "height"; + value = new CCString(valueForKey("height", attributeDict)); + dict->setObject(value, key.c_str()); + value->release(); + + // Add the object to the objectGroup + objectGroup->getObjects()->addObject(dict); + dict->release(); + + // The parent element is now "object" + pTMXMapInfo->setParentElement(TMXPropertyObject); + + } + else if(elementName == "property") + { + if ( pTMXMapInfo->getParentElement() == TMXPropertyNone ) + { + CCLOG( "TMX tile map: Parent element is unsupported. Cannot add property named '%s' with value '%s'", + valueForKey("name", attributeDict), valueForKey("value",attributeDict) ); + } + else if ( pTMXMapInfo->getParentElement() == TMXPropertyMap ) + { + // The parent element is the map + CCString *value = new CCString(valueForKey("value", attributeDict)); + std::string key = valueForKey("name", attributeDict); + pTMXMapInfo->getProperties()->setObject(value, key.c_str()); + value->release(); + + } + else if ( pTMXMapInfo->getParentElement() == TMXPropertyLayer ) + { + // The parent element is the last layer + CCTMXLayerInfo* layer = (CCTMXLayerInfo*)pTMXMapInfo->getLayers()->lastObject(); + CCString *value = new CCString(valueForKey("value", attributeDict)); + std::string key = valueForKey("name", attributeDict); + // Add the property to the layer + layer->getProperties()->setObject(value, key.c_str()); + value->release(); + + } + else if ( pTMXMapInfo->getParentElement() == TMXPropertyObjectGroup ) + { + // The parent element is the last object group + CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)pTMXMapInfo->getObjectGroups()->lastObject(); + CCString *value = new CCString(valueForKey("value", attributeDict)); + const char* key = valueForKey("name", attributeDict); + objectGroup->getProperties()->setObject(value, key); + value->release(); + + } + else if ( pTMXMapInfo->getParentElement() == TMXPropertyObject ) + { + // The parent element is the last object + CCTMXObjectGroup* objectGroup = (CCTMXObjectGroup*)pTMXMapInfo->getObjectGroups()->lastObject(); + CCDictionary* dict = (CCDictionary*)objectGroup->getObjects()->lastObject(); + + const char* propertyName = valueForKey("name", attributeDict); + CCString *propertyValue = new CCString(valueForKey("value", attributeDict)); + dict->setObject(propertyValue, propertyName); + propertyValue->release(); + } + else if ( pTMXMapInfo->getParentElement() == TMXPropertyTile ) + { + CCDictionary* dict = (CCDictionary*)pTMXMapInfo->getTileProperties()->objectForKey(pTMXMapInfo->getParentGID()); + + const char* propertyName = valueForKey("name", attributeDict); + CCString *propertyValue = new CCString(valueForKey("value", attributeDict)); + dict->setObject(propertyValue, propertyName); + propertyValue->release(); + } + } + if (attributeDict) + { + attributeDict->clear(); + delete attributeDict; + } +} + +void CCTMXMapInfo::endElement(void *ctx, const char *name) +{ + CC_UNUSED_PARAM(ctx); + CCTMXMapInfo *pTMXMapInfo = this; + std::string elementName = (char*)name; + + int len = 0; + + if(elementName == "data" && pTMXMapInfo->getLayerAttribs()&TMXLayerAttribBase64) + { + pTMXMapInfo->setStoringCharacters(false); + + CCTMXLayerInfo* layer = (CCTMXLayerInfo*)pTMXMapInfo->getLayers()->lastObject(); + + std::string currentString = pTMXMapInfo->getCurrentString(); + unsigned char *buffer; + len = base64Decode((unsigned char*)currentString.c_str(), (unsigned int)currentString.length(), &buffer); + if( ! buffer ) + { + CCLOG("cocos2d: TiledMap: decode data error"); + return; + } + + if( pTMXMapInfo->getLayerAttribs() & (TMXLayerAttribGzip | TMXLayerAttribZlib) ) + { + unsigned char *deflated; + CCSize s = layer->m_tLayerSize; + // int sizeHint = s.width * s.height * sizeof(uint32_t); + int sizeHint = (int)(s.width * s.height * sizeof(unsigned int)); + + int inflatedLen = ZipUtils::ccInflateMemoryWithHint(buffer, len, &deflated, sizeHint); + CCAssert(inflatedLen == sizeHint, ""); + + inflatedLen = (size_t)&inflatedLen; // XXX: to avoid warings in compiler + + delete [] buffer; + buffer = NULL; + + if( ! deflated ) + { + CCLOG("cocos2d: TiledMap: inflate data error"); return; } - if( pTMXMapInfo->getLayerAttribs() & (TMXLayerAttribGzip | TMXLayerAttribZlib) ) - { - unsigned char *deflated; - CCSize s = layer->m_tLayerSize; - // int sizeHint = s.width * s.height * sizeof(uint32_t); - int sizeHint = (int)(s.width * s.height * sizeof(unsigned int)); - - int inflatedLen = ZipUtils::ccInflateMemoryWithHint(buffer, len, &deflated, sizeHint); - CCAssert(inflatedLen == sizeHint, ""); - - inflatedLen = (size_t)&inflatedLen; // XXX: to avoid warings in compiler - - delete [] buffer; - buffer = NULL; - - if( ! deflated ) - { - CCLOG("cocos2d: TiledMap: inflate data error"); - return; - } - - layer->m_pTiles = (unsigned int*) deflated; - } - else - { - layer->m_pTiles = (unsigned int*) buffer; - } - - pTMXMapInfo->setCurrentString(""); - - } - else if (elementName == "map") - { - // The map element has ended - pTMXMapInfo->setParentElement(TMXPropertyNone); - } - else if (elementName == "layer") - { - // The layer element has ended - pTMXMapInfo->setParentElement(TMXPropertyNone); + layer->m_pTiles = (unsigned int*) deflated; } - else if (elementName == "objectgroup") + else { - // The objectgroup element has ended - pTMXMapInfo->setParentElement(TMXPropertyNone); - } - else if (elementName == "object") - { - // The object element has ended - pTMXMapInfo->setParentElement(TMXPropertyNone); + layer->m_pTiles = (unsigned int*) buffer; } - } - - void CCTMXMapInfo::textHandler(void *ctx, const char *ch, int len) + + pTMXMapInfo->setCurrentString(""); + + } + else if (elementName == "map") { - CC_UNUSED_PARAM(ctx); - CCTMXMapInfo *pTMXMapInfo = this; - std::string pText((char*)ch,0,len); - - if (pTMXMapInfo->getStoringCharacters()) - { - std::string currentString = pTMXMapInfo->getCurrentString(); - currentString += pText; - pTMXMapInfo->setCurrentString(currentString.c_str()); - } + // The map element has ended + pTMXMapInfo->setParentElement(TMXPropertyNone); + } + else if (elementName == "layer") + { + // The layer element has ended + pTMXMapInfo->setParentElement(TMXPropertyNone); } + else if (elementName == "objectgroup") + { + // The objectgroup element has ended + pTMXMapInfo->setParentElement(TMXPropertyNone); + } + else if (elementName == "object") + { + // The object element has ended + pTMXMapInfo->setParentElement(TMXPropertyNone); + } +} + +void CCTMXMapInfo::textHandler(void *ctx, const char *ch, int len) +{ + CC_UNUSED_PARAM(ctx); + CCTMXMapInfo *pTMXMapInfo = this; + std::string pText((char*)ch,0,len); + + if (pTMXMapInfo->getStoringCharacters()) + { + std::string currentString = pTMXMapInfo->getCurrentString(); + currentString += pText; + pTMXMapInfo->setCurrentString(currentString.c_str()); + } +} + +NS_CC_END -}//namespace cocos2d diff --git a/cocos2dx/touch_dispatcher/CCTouchDispatcher.cpp b/cocos2dx/touch_dispatcher/CCTouchDispatcher.cpp index 66bf9f461c..9ad1e0281e 100644 --- a/cocos2dx/touch_dispatcher/CCTouchDispatcher.cpp +++ b/cocos2dx/touch_dispatcher/CCTouchDispatcher.cpp @@ -25,7 +25,7 @@ THE SOFTWARE. #include "CCTouchDispatcher.h" #include "CCTouchHandler.h" -#include "CCMutableArray.h" +#include "CCArray.h" #include "CCSet.h" #include "CCTouch.h" #include "CCTexture2D.h" @@ -36,9 +36,9 @@ THE SOFTWARE. /** * Used for sort */ -static bool less(const cocos2d::CCTouchHandler *p1, const cocos2d::CCTouchHandler *p2) +static int less(const void* p1, const void* p2) { - return ((cocos2d::CCTouchHandler*)p1)->getPriority() < ((cocos2d::CCTouchHandler*)p2)->getPriority(); + return ((cocos2d::CCTouchHandler*)p1)->getPriority() < ((cocos2d::CCTouchHandler*)p2)->getPriority() ? 1 : -1; } namespace cocos2d { @@ -81,10 +81,12 @@ CCTouchDispatcher* CCTouchDispatcher::sharedDispatcher(void) bool CCTouchDispatcher::init(void) { m_bDispatchEvents = true; - m_pTargetedHandlers = new CCMutableArray(8); - m_pStandardHandlers = new CCMutableArray(4); + m_pTargetedHandlers = CCArray::arrayWithCapacity(8); + m_pTargetedHandlers->retain(); + m_pStandardHandlers = CCArray::arrayWithCapacity(4); + m_pStandardHandlers->retain(); - m_pHandlersToAdd = new CCMutableArray(8); + m_pHandlersToAdd = CCArray::arrayWithCapacity(8); m_pHandlersToRemove = ccCArrayNew(8); m_bToRemove = false; @@ -113,14 +115,14 @@ CCTouchDispatcher::~CCTouchDispatcher(void) // // handlers management // -void CCTouchDispatcher::forceAddHandler(CCTouchHandler *pHandler, CCMutableArray *pArray) +void CCTouchDispatcher::forceAddHandler(CCTouchHandler *pHandler, CCArray *pArray) { unsigned int u = 0; - CCMutableArray::CCMutableArrayIterator iter; - for (iter = pArray->begin(); iter != pArray->end(); ++iter) + CCObject* pObj = NULL; + CCARRAY_FOREACH(pArray, pObj) { - CCTouchHandler *h = *iter; + CCTouchHandler *h = (CCTouchHandler *)pObj; if (h) { if (h->getPriority() < pHandler->getPriority()) @@ -136,7 +138,7 @@ void CCTouchDispatcher::forceAddHandler(CCTouchHandler *pHandler, CCMutableArray } } - pArray->insertObjectAtIndex(pHandler, u); + pArray->insertObject(pHandler, u); } void CCTouchDispatcher::addStandardDelegate(CCTouchDelegate *pDelegate, int nPriority) @@ -188,14 +190,14 @@ void CCTouchDispatcher::addTargetedDelegate(CCTouchDelegate *pDelegate, int nPri void CCTouchDispatcher::forceRemoveDelegate(CCTouchDelegate *pDelegate) { CCTouchHandler *pHandler; - CCMutableArray::CCMutableArrayIterator iter; // XXX: remove it from both handlers ??? // remove handler from m_pStandardHandlers - for (iter = m_pStandardHandlers->begin(); iter != m_pStandardHandlers->end(); ++iter) + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_pStandardHandlers, pObj) { - pHandler = *iter; + pHandler = (CCTouchHandler*)pObj; if (pHandler && pHandler->getDelegate() == pDelegate) { m_pStandardHandlers->removeObject(pHandler); @@ -204,9 +206,9 @@ void CCTouchDispatcher::forceRemoveDelegate(CCTouchDelegate *pDelegate) } // remove handler from m_pTargetedHandlers - for (iter = m_pTargetedHandlers->begin(); iter != m_pTargetedHandlers->end(); ++iter) + CCARRAY_FOREACH(m_pTargetedHandlers, pObj) { - pHandler = *iter; + pHandler = (CCTouchHandler*)pObj; if (pHandler && pHandler->getDelegate() == pDelegate) { m_pTargetedHandlers->removeObject(pHandler); @@ -263,47 +265,49 @@ void CCTouchDispatcher::removeAllDelegates(void) CCTouchHandler* CCTouchDispatcher::findHandler(CCTouchDelegate *pDelegate) { - CCMutableArray::CCMutableArrayIterator iter; - - for (iter = m_pTargetedHandlers->begin(); iter != m_pTargetedHandlers->end(); ++iter) + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_pTargetedHandlers, pObj) { - if ((*iter)->getDelegate() == pDelegate) + CCTouchHandler* pHandler = (CCTouchHandler*)pObj; + if (pHandler->getDelegate() == pDelegate) { - return *iter; + return pHandler; } } - for (iter = m_pStandardHandlers->begin(); iter != m_pStandardHandlers->end(); ++iter) + CCARRAY_FOREACH(m_pStandardHandlers, pObj) { - if ((*iter)->getDelegate() == pDelegate) + CCTouchHandler* pHandler = (CCTouchHandler*)pObj; + if (pHandler->getDelegate() == pDelegate) { - return *iter; + return pHandler; } } return NULL; } -CCTouchHandler* CCTouchDispatcher::findHandler(CCMutableArray *pArray, CCTouchDelegate *pDelegate) +CCTouchHandler* CCTouchDispatcher::findHandler(CCArray* pArray, CCTouchDelegate *pDelegate) { CCAssert(pArray != NULL && pDelegate != NULL, ""); - CCMutableArray::CCMutableArrayIterator iter; - - for (iter = pArray->begin(); iter != pArray->end(); ++iter) + CCObject* pObj = NULL; + CCARRAY_FOREACH(pArray, pObj) { - if ((*iter)->getDelegate() == pDelegate) + CCTouchHandler* pHandle = (CCTouchHandler*)pObj; + if (pHandle->getDelegate() == pDelegate) { - return *iter; + return pHandle; } } return NULL; } -void CCTouchDispatcher::rearrangeHandlers(CCMutableArray *pArray) +void CCTouchDispatcher::rearrangeHandlers(CCArray *pArray) { - std::sort(pArray->begin(), pArray->end(), less); + // FIXME: qsort is not supported in bada1.0, so we must implement it ourselves. + qsort(pArray->data->arr, pArray->data->num, sizeof(pArray->data->arr[0]), less); } void CCTouchDispatcher::setPriority(int nPriority, CCTouchDelegate *pDelegate) @@ -350,12 +354,12 @@ void CCTouchDispatcher::touches(CCSet *pTouches, CCEvent *pEvent, unsigned int u for (setIter = pTouches->begin(); setIter != pTouches->end(); ++setIter) { pTouch = (CCTouch *)(*setIter); - CCTargetedTouchHandler *pHandler; - CCMutableArray::CCMutableArrayIterator arrayIter; - for (arrayIter = m_pTargetedHandlers->begin(); arrayIter != m_pTargetedHandlers->end(); ++arrayIter) - /*for (unsigned int i = 0; i < m_pTargetedHandlers->num; ++i)*/ + + CCTargetedTouchHandler *pHandler = NULL; + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_pTargetedHandlers, pObj) { - pHandler = (CCTargetedTouchHandler *)(*arrayIter); + pHandler = (CCTargetedTouchHandler *)(pObj); if (! pHandler) { @@ -411,11 +415,11 @@ void CCTouchDispatcher::touches(CCSet *pTouches, CCEvent *pEvent, unsigned int u // if (uStandardHandlersCount > 0 && pMutableTouches->count() > 0) { - CCMutableArray::CCMutableArrayIterator iter; - CCStandardTouchHandler *pHandler; - for (iter = m_pStandardHandlers->begin(); iter != m_pStandardHandlers->end(); ++iter) + CCStandardTouchHandler *pHandler = NULL; + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_pStandardHandlers, pObj) { - pHandler = (CCStandardTouchHandler*)(*iter); + pHandler = (CCStandardTouchHandler*)(pObj); if (! pHandler) { @@ -463,11 +467,11 @@ void CCTouchDispatcher::touches(CCSet *pTouches, CCEvent *pEvent, unsigned int u if (m_bToAdd) { m_bToAdd = false; - CCMutableArray::CCMutableArrayIterator iter; - CCTouchHandler *pHandler; - for (iter = m_pHandlersToAdd->begin(); iter != m_pHandlersToAdd->end(); ++iter) + CCTouchHandler* pHandler = NULL; + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_pHandlersToAdd, pObj) { - pHandler = *iter; + pHandler = (CCTouchHandler*)pObj; if (! pHandler) { break; diff --git a/tests/tests/ActionsTest/ActionsTest.h b/tests/tests/ActionsTest/ActionsTest.h index 7d39b4c9be..687998d5a6 100644 --- a/tests/tests/ActionsTest/ActionsTest.h +++ b/tests/tests/ActionsTest/ActionsTest.h @@ -6,6 +6,7 @@ using namespace cocos2d; + enum { ACTION_MANUAL_LAYER = 0, diff --git a/tests/tests/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/tests/tests/SpriteTest/SpriteTest.cpp.REMOVED.git-id index ae4b8809a2..bc6f2677e5 100644 --- a/tests/tests/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/tests/tests/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -7593bccdf37e94e6af9b7bfec82d6931c746f428 \ No newline at end of file +6b30e04685cc62b5daa0628f9bb038bc42bae923 \ No newline at end of file diff --git a/tests/tests/SpriteTest/SpriteTest.h b/tests/tests/SpriteTest/SpriteTest.h index 75c9e7476d..3d36798b62 100644 --- a/tests/tests/SpriteTest/SpriteTest.h +++ b/tests/tests/SpriteTest/SpriteTest.h @@ -3,6 +3,7 @@ #include "cocos2d.h" #include "../testBasic.h" +#include class SpriteTestDemo : public CCLayer { diff --git a/tests/tests/TileMapTest/TileMapTest.cpp b/tests/tests/TileMapTest/TileMapTest.cpp index 6f215afa52..803c3b3c35 100644 --- a/tests/tests/TileMapTest/TileMapTest.cpp +++ b/tests/tests/TileMapTest/TileMapTest.cpp @@ -615,13 +615,13 @@ TMXOrthoObjectsTest::TMXOrthoObjectsTest() ////----UXLOG("----> Iterating over all the group objets"); CCTMXObjectGroup* group = map->objectGroupNamed("Object Group 1"); - CCMutableArray * objects = group->getObjects(); + CCArray* objects = group->getObjects(); - CCStringToStringDictionary* dict; - CCMutableArray::CCMutableArrayIterator it; - for( it = objects->begin(); it != objects->end(); it++) + CCDictionary* dict = NULL; + CCObject* pObj = NULL; + CCARRAY_FOREACH(objects, pObj) { - dict = (*it);//dynamic_cast(*it); + dict = (CCDictionary*)pObj;//dynamic_cast(*it); if(!dict) break; @@ -639,24 +639,23 @@ void TMXOrthoObjectsTest::draw() CCTMXTiledMap* map = (CCTMXTiledMap*) getChildByTag(kTagTileMap); CCTMXObjectGroup* group = map->objectGroupNamed("Object Group 1"); - CCMutableArray * objects = group->getObjects(); - CCStringToStringDictionary* dict; - CCMutableArray::CCMutableArrayIterator it; - - for( it = objects->begin(); it != objects->end(); it++) + CCArray* objects = group->getObjects(); + CCDictionary* dict = NULL; + CCObject* pObj = NULL; + CCARRAY_FOREACH(objects, pObj) { - dict = (*it);//dynamic_cast(*it); + dict = (CCDictionary*)pObj;//dynamic_cast(*it); if(!dict) break; - std::string key = "x"; - int x = dict->objectForKey(key)->toInt(); + const char* key = "x"; + int x = ((CCString*)dict->objectForKey(key))->toInt(); key = "y"; - int y = dict->objectForKey(key)->toInt();//dynamic_cast(dict->objectForKey("y"))->getNumber(); + int y = ((CCString*)dict->objectForKey(key))->toInt();//dynamic_cast(dict->objectForKey("y"))->getNumber(); key = "width"; - int width = dict->objectForKey(key)->toInt();//dynamic_cast(dict->objectForKey("width"))->getNumber(); + int width = ((CCString*)dict->objectForKey(key))->toInt();//dynamic_cast(dict->objectForKey("width"))->getNumber(); key = "height"; - int height = dict->objectForKey(key)->toInt();//dynamic_cast(dict->objectForKey("height"))->getNumber(); + int height = ((CCString*)dict->objectForKey(key))->toInt();//dynamic_cast(dict->objectForKey("height"))->getNumber(); glLineWidth(3); @@ -697,15 +696,13 @@ TMXIsoObjectsTest::TMXIsoObjectsTest() CCTMXObjectGroup* group = map->objectGroupNamed("Object Group 1"); //UxMutableArray* objects = group->objects(); - CCMutableArray * objects = group->getObjects(); + CCArray* objects = group->getObjects(); //UxMutableDictionary* dict; - CCStringToStringDictionary* dict; - //CCMutableArray::CCMutableArrayIterator it; - CCMutableArray::CCMutableArrayIterator it; - - for( it = objects->begin(); it != objects->end(); it++) + CCDictionary* dict; + CCObject* pObj = NULL; + CCARRAY_FOREACH(objects, pObj) { - dict = (*it); + dict = (CCDictionary*)pObj; if(!dict) break; @@ -719,24 +716,23 @@ void TMXIsoObjectsTest::draw() CCTMXTiledMap *map = (CCTMXTiledMap*) getChildByTag(kTagTileMap); CCTMXObjectGroup *group = map->objectGroupNamed("Object Group 1"); - CCMutableArray * objects = group->getObjects(); - CCStringToStringDictionary* dict; - CCMutableArray::CCMutableArrayIterator it; - - for( it = objects->begin(); it != objects->end(); it++) + CCArray* objects = group->getObjects(); + CCDictionary* dict; + CCObject* pObj = NULL; + CCARRAY_FOREACH(objects, pObj) { - dict = (*it);//dynamic_cast(*it); + dict = (CCDictionary*)pObj;//dynamic_cast(*it); if(!dict) break; - std::string key = "x"; - int x = dict->objectForKey(key)->toInt();//dynamic_cast(dict->objectForKey("x"))->getNumber(); + const char* key = "x"; + int x = ((CCString*)dict->objectForKey(key))->toInt();//dynamic_cast(dict->objectForKey("x"))->getNumber(); key = "y"; - int y = dict->objectForKey(key)->toInt();//dynamic_cast(dict->objectForKey("y"))->getNumber(); + int y = ((CCString*)dict->objectForKey(key))->toInt();//dynamic_cast(dict->objectForKey("y"))->getNumber(); key = "width"; - int width = dict->objectForKey(key)->toInt();//dynamic_cast(dict->objectForKey("width"))->getNumber(); + int width = ((CCString*)dict->objectForKey(key))->toInt();//dynamic_cast(dict->objectForKey("width"))->getNumber(); key = "height"; - int height = dict->objectForKey(key)->toInt();//dynamic_cast(dict->objectForKey("height"))->getNumber(); + int height = ((CCString*)dict->objectForKey(key))->toInt();//dynamic_cast(dict->objectForKey("height"))->getNumber(); glLineWidth(3); @@ -1412,26 +1408,25 @@ void TMXGIDObjectsTest::draw() CCTMXTiledMap *map = (CCTMXTiledMap*)getChildByTag(kTagTileMap); CCTMXObjectGroup *group = map->objectGroupNamed("Object Layer 1"); - CCMutableArray *array = group->getObjects(); - CCMutableArray::CCMutableArrayIterator iter; - CCStringToStringDictionary *dict; - - for (iter = array->begin(); iter != array->end(); ++iter) + CCArray *array = group->getObjects(); + CCDictionary* dict; + CCObject* pObj = NULL; + CCARRAY_FOREACH(array, pObj) { - dict = *iter; + dict = (CCDictionary*)pObj; if(!dict) { break; } - std::string key = "x"; - int x = dict->objectForKey(key)->toInt(); + const char* key = "x"; + int x = ((CCString*)dict->objectForKey(key))->toInt(); key = "y"; - int y = dict->objectForKey(key)->toInt(); + int y = ((CCString*)dict->objectForKey(key))->toInt(); key = "width"; - int width = dict->objectForKey(key)->toInt(); + int width = ((CCString*)dict->objectForKey(key))->toInt(); key = "height"; - int height = dict->objectForKey(key)->toInt(); + int height = ((CCString*)dict->objectForKey(key))->toInt(); glLineWidth(3); diff --git a/tests/tests/TouchesTest/TouchesTest.cpp b/tests/tests/TouchesTest/TouchesTest.cpp index d62b43f6f9..19c1409a7b 100644 --- a/tests/tests/TouchesTest/TouchesTest.cpp +++ b/tests/tests/TouchesTest/TouchesTest.cpp @@ -54,7 +54,7 @@ PongLayer::PongLayer() CCTexture2D* paddleTexture = CCTextureCache::sharedTextureCache()->addImage(s_Paddle); - CCMutableArray *paddlesM = new CCMutableArray(4); + CCArray *paddlesM = CCArray::arrayWithCapacity(4); Paddle* paddle = Paddle::paddleWithTexture(paddleTexture); paddle->setPosition( CCPointMake(160, 15) ); @@ -72,12 +72,12 @@ PongLayer::PongLayer() paddle->setPosition( CCPointMake(160, 480 - kStatusBarHeight - 100) ); paddlesM->addObject( paddle ); - m_paddles = paddlesM->copy(); + m_paddles = (CCArray*)paddlesM->copy(); - CCMutableArray::CCMutableArrayIterator it; - for(it = m_paddles->begin(); it != m_paddles->end(); it++) + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_paddles, pObj) { - paddle = (Paddle*)(*it); + paddle = (Paddle*)(pObj); if(!paddle) break; @@ -85,8 +85,6 @@ PongLayer::PongLayer() addChild(paddle); } - paddlesM->release(); - schedule( schedule_selector(PongLayer::doStep) ); } @@ -109,11 +107,11 @@ void PongLayer::doStep(ccTime delta) { m_ball->move(delta); - Paddle* paddle; - CCMutableArray::CCMutableArrayIterator it; - for(it = m_paddles->begin(); it != m_paddles->end(); it++) + Paddle* paddle = NULL; + CCObject* pObj = NULL; + CCARRAY_FOREACH(m_paddles, pObj) { - paddle = (Paddle*)(*it); + paddle = (Paddle*)(pObj); if(!paddle) break; diff --git a/tests/tests/TouchesTest/TouchesTest.h b/tests/tests/TouchesTest/TouchesTest.h index 0db8ad3cbf..4b23f6b824 100644 --- a/tests/tests/TouchesTest/TouchesTest.h +++ b/tests/tests/TouchesTest/TouchesTest.h @@ -20,7 +20,7 @@ class Ball; class PongLayer : public CCLayer { Ball* m_ball; - CCMutableArray *m_paddles; + CCArray* m_paddles; CCPoint m_ballStartingVelocity; public: PongLayer(); diff --git a/tests/tests/testBasic.h b/tests/tests/testBasic.h index 5a0b285932..a7cbcc9305 100644 --- a/tests/tests/testBasic.h +++ b/tests/tests/testBasic.h @@ -4,6 +4,7 @@ #include "cocos2d.h" using namespace cocos2d; +using namespace std; class TestScene : public CCScene {