Merge branch 'develop' into Iss2460-glfw-refractor

Conflicts:
	cocos2d_libs.xcodeproj/project.pbxproj
	cocos2dx/platform/mac/CCEGLView.mm
	samples/Cpp/TestCpp/proj.linux/main.cpp
	samples/Cpp/TestCpp/proj.win32/main.cpp
This commit is contained in:
Huabing.Xu 2013-08-28 13:42:22 +08:00
commit e935481361
410 changed files with 19145 additions and 9563 deletions

1
.gitignore vendored
View File

@ -89,6 +89,7 @@ projects/
tools/tojs/user.cfg tools/tojs/user.cfg
# ... userconf.ini generated if running from tools/tojs # ... userconf.ini generated if running from tools/tojs
tools/tojs/userconf.ini tools/tojs/userconf.ini
tools/tolua/userconf.ini
# ... userconf.ini generated if running from tools/jenkins_scripts/mac/android/ # ... userconf.ini generated if running from tools/jenkins_scripts/mac/android/
tools/jenkins_scripts/mac/android/userconf.ini tools/jenkins_scripts/mac/android/userconf.ini

2
.gitmodules vendored
View File

@ -2,7 +2,7 @@
path = tools/bindings-generator path = tools/bindings-generator
url = git://github.com/cocos2d/bindings-generator.git url = git://github.com/cocos2d/bindings-generator.git
[submodule "scripting/javascript/bindings/generated"] [submodule "scripting/javascript/bindings/generated"]
path = scripting/javascript/bindings/generated path = scripting/auto-generated
url = git://github.com/folecr/cocos2dx-autogen-bindings.git url = git://github.com/folecr/cocos2dx-autogen-bindings.git
[submodule "samples/Javascript/Shared"] [submodule "samples/Javascript/Shared"]
path = samples/Javascript/Shared path = samples/Javascript/Shared

View File

@ -567,6 +567,15 @@ Developers:
maciekczwa maciekczwa
Fixing a bug that stroke color with channel color values other than 255 doesn't take effect on android. Fixing a bug that stroke color with channel color values other than 255 doesn't take effect on android.
zcgit
a potential bug fix in Layer::init.
gkosciolek
Fixing a bug that observers with the same target and name but different sender are the same observer in NotificationCenter.
xbruce
Fixing a bug that crash appears when extending cc.ScrollView in JS
Retired Core Developers: Retired Core Developers:
WenSheng Yang WenSheng Yang
Author of windows port, CCTextField, Author of windows port, CCTextField,

View File

@ -42,26 +42,6 @@ THE SOFTWARE.
namespace CocosDenshion { namespace CocosDenshion {
class TypeInfo
{
public:
virtual long getClassTypeInfo() = 0;
};
static inline unsigned int getHashCodeByString(const char *key)
{
unsigned int len = strlen(key);
const char *end=key+len;
unsigned int hash;
for (hash = 0; key < end; key++)
{
hash *= 16777619;
hash ^= (unsigned int) (unsigned char) toupper(*key);
}
return (hash);
}
/** /**
@class SimpleAudioEngine @class SimpleAudioEngine
@brief Offers a VERY simple interface to play background music & sound effects. @brief Offers a VERY simple interface to play background music & sound effects.
@ -69,7 +49,7 @@ static inline unsigned int getHashCodeByString(const char *key)
to release allocated resources. to release allocated resources.
*/ */
class EXPORT_DLL SimpleAudioEngine : public TypeInfo class EXPORT_DLL SimpleAudioEngine
{ {
public: public:
/** /**
@ -90,10 +70,6 @@ protected:
public: public:
virtual long getClassTypeInfo() {
return getHashCodeByString(typeid(CocosDenshion::SimpleAudioEngine).name());
}
/** /**
@brief Preload background music @brief Preload background music
@param pszFilePath The path of the background music file. @param pszFilePath The path of the background music file.

View File

@ -1 +1 @@
bfee153c4c2d4b283d8cd8ea03a83369fdc201b9 dcaf07070ad651b671d721564b6d1aa99ea03d0b

View File

@ -7,12 +7,14 @@ LOCAL_MODULE := cocos2dx_static
LOCAL_MODULE_FILENAME := libcocos2d LOCAL_MODULE_FILENAME := libcocos2d
LOCAL_SRC_FILES := \ LOCAL_SRC_FILES := \
CCCamera.cpp \
CCConfiguration.cpp \ CCConfiguration.cpp \
CCDeprecated.cpp \ CCDeprecated.cpp \
CCScheduler.cpp \ CCDirector.cpp \
CCCamera.cpp \
ccFPSImages.c \ ccFPSImages.c \
CCScheduler.cpp \
ccTypes.cpp \ ccTypes.cpp \
cocos2d.cpp \
actions/CCAction.cpp \ actions/CCAction.cpp \
actions/CCActionCamera.cpp \ actions/CCActionCamera.cpp \
actions/CCActionCatmullRom.cpp \ actions/CCActionCatmullRom.cpp \
@ -29,18 +31,16 @@ actions/CCActionTween.cpp \
base_nodes/CCAtlasNode.cpp \ base_nodes/CCAtlasNode.cpp \
base_nodes/CCNode.cpp \ base_nodes/CCNode.cpp \
cocoa/CCAffineTransform.cpp \ cocoa/CCAffineTransform.cpp \
cocoa/CCGeometry.cpp \ cocoa/CCArray.cpp \
cocoa/CCAutoreleasePool.cpp \ cocoa/CCAutoreleasePool.cpp \
cocoa/CCData.cpp \
cocoa/CCDataVisitor.cpp \
cocoa/CCDictionary.cpp \ cocoa/CCDictionary.cpp \
cocoa/CCGeometry.cpp \
cocoa/CCNS.cpp \ cocoa/CCNS.cpp \
cocoa/CCObject.cpp \ cocoa/CCObject.cpp \
cocoa/CCSet.cpp \ cocoa/CCSet.cpp \
cocoa/CCString.cpp \ cocoa/CCString.cpp \
cocoa/CCArray.cpp \
cocoa/CCDataVisitor.cpp \
cocoa/CCData.cpp \
cocos2d.cpp \
CCDirector.cpp \
draw_nodes/CCDrawingPrimitives.cpp \ draw_nodes/CCDrawingPrimitives.cpp \
draw_nodes/CCDrawNode.cpp \ draw_nodes/CCDrawNode.cpp \
effects/CCGrabber.cpp \ effects/CCGrabber.cpp \
@ -58,9 +58,9 @@ kazmath/src/vec3.c \
kazmath/src/vec4.c \ kazmath/src/vec4.c \
kazmath/src/GL/mat4stack.c \ kazmath/src/GL/mat4stack.c \
kazmath/src/GL/matrix.c \ kazmath/src/GL/matrix.c \
keyboard_dispatcher/CCKeyboardDispatcher.cpp \
keypad_dispatcher/CCKeypadDelegate.cpp \ keypad_dispatcher/CCKeypadDelegate.cpp \
keypad_dispatcher/CCKeypadDispatcher.cpp \ keypad_dispatcher/CCKeypadDispatcher.cpp \
keyboard_dispatcher/CCKeyboardDispatcher.cpp \
label_nodes/CCFont.cpp \ label_nodes/CCFont.cpp \
label_nodes/CCFontAtlas.cpp \ label_nodes/CCFontAtlas.cpp \
label_nodes/CCFontAtlasCache.cpp \ label_nodes/CCFontAtlasCache.cpp \
@ -71,13 +71,13 @@ label_nodes/CCFontFreeType.cpp \
label_nodes/CCLabel.cpp \ label_nodes/CCLabel.cpp \
label_nodes/CCLabelAtlas.cpp \ label_nodes/CCLabelAtlas.cpp \
label_nodes/CCLabelBMFont.cpp \ label_nodes/CCLabelBMFont.cpp \
label_nodes/CCLabelTTF.cpp \
label_nodes/CCLabelTextFormatter.cpp \ label_nodes/CCLabelTextFormatter.cpp \
label_nodes/CCLabelTTF.cpp \
label_nodes/CCTextImage.cpp \ label_nodes/CCTextImage.cpp \
layers_scenes_transitions_nodes/CCLayer.cpp \ layers_scenes_transitions_nodes/CCLayer.cpp \
layers_scenes_transitions_nodes/CCScene.cpp \ layers_scenes_transitions_nodes/CCScene.cpp \
layers_scenes_transitions_nodes/CCTransitionPageTurn.cpp \
layers_scenes_transitions_nodes/CCTransition.cpp \ layers_scenes_transitions_nodes/CCTransition.cpp \
layers_scenes_transitions_nodes/CCTransitionPageTurn.cpp \
layers_scenes_transitions_nodes/CCTransitionProgress.cpp \ layers_scenes_transitions_nodes/CCTransitionProgress.cpp \
menu_nodes/CCMenu.cpp \ menu_nodes/CCMenu.cpp \
menu_nodes/CCMenuItem.cpp \ menu_nodes/CCMenuItem.cpp \
@ -85,71 +85,74 @@ misc_nodes/CCClippingNode.cpp \
misc_nodes/CCMotionStreak.cpp \ misc_nodes/CCMotionStreak.cpp \
misc_nodes/CCProgressTimer.cpp \ misc_nodes/CCProgressTimer.cpp \
misc_nodes/CCRenderTexture.cpp \ misc_nodes/CCRenderTexture.cpp \
particle_nodes/CCParticleBatchNode.cpp \
particle_nodes/CCParticleExamples.cpp \ particle_nodes/CCParticleExamples.cpp \
particle_nodes/CCParticleSystem.cpp \ particle_nodes/CCParticleSystem.cpp \
particle_nodes/CCParticleBatchNode.cpp \
particle_nodes/CCParticleSystemQuad.cpp \ particle_nodes/CCParticleSystemQuad.cpp \
platform/CCEGLViewProtocol.cpp \
platform/CCFileUtils.cpp \
platform/CCSAXParser.cpp \ platform/CCSAXParser.cpp \
platform/CCThread.cpp \ platform/CCThread.cpp \
platform/CCFileUtils.cpp \ platform/third_party/common/atitc/atitc.cpp \
platform/CCEGLViewProtocol.cpp \ platform/third_party/common/etc/etc1.cpp \
platform/third_party/common/s3tc/s3tc.cpp \
script_support/CCScriptSupport.cpp \ script_support/CCScriptSupport.cpp \
shaders/ccShaders.cpp \
shaders/CCGLProgram.cpp \ shaders/CCGLProgram.cpp \
shaders/ccGLStateCache.cpp \ shaders/ccGLStateCache.cpp \
shaders/CCShaderCache.cpp \ shaders/CCShaderCache.cpp \
shaders/ccShaders.cpp \
sprite_nodes/CCAnimation.cpp \ sprite_nodes/CCAnimation.cpp \
sprite_nodes/CCAnimationCache.cpp \ sprite_nodes/CCAnimationCache.cpp \
sprite_nodes/CCSprite.cpp \ sprite_nodes/CCSprite.cpp \
sprite_nodes/CCSpriteBatchNode.cpp \ sprite_nodes/CCSpriteBatchNode.cpp \
sprite_nodes/CCSpriteFrame.cpp \ sprite_nodes/CCSpriteFrame.cpp \
sprite_nodes/CCSpriteFrameCache.cpp \ sprite_nodes/CCSpriteFrameCache.cpp \
support/ccUTF8.cpp \ support/base64.cpp \
support/CCNotificationCenter.cpp \ support/CCNotificationCenter.cpp \
support/CCProfiling.cpp \ support/CCProfiling.cpp \
support/TransformUtils.cpp \ support/ccUTF8.cpp \
support/user_default/CCUserDefaultAndroid.cpp \
support/base64.cpp \
support/ccUtils.cpp \ support/ccUtils.cpp \
support/CCVertex.cpp \ support/CCVertex.cpp \
support/TransformUtils.cpp \
support/component/CCComponent.cpp \
support/component/CCComponentContainer.cpp \
support/data_support/ccCArray.cpp \ support/data_support/ccCArray.cpp \
support/image_support/TGAlib.cpp \ support/image_support/TGAlib.cpp \
support/tinyxml2/tinyxml2.cpp \ support/tinyxml2/tinyxml2.cpp \
support/zip_support/ZipUtils.cpp \ support/user_default/CCUserDefaultAndroid.cpp \
support/zip_support/ioapi.cpp \ support/zip_support/ioapi.cpp \
support/zip_support/unzip.cpp \ support/zip_support/unzip.cpp \
support/component/CCComponent.cpp \ support/zip_support/ZipUtils.cpp \
support/component/CCComponentContainer.cpp \
text_input_node/CCIMEDispatcher.cpp \ text_input_node/CCIMEDispatcher.cpp \
text_input_node/CCTextFieldTTF.cpp \ text_input_node/CCTextFieldTTF.cpp \
textures/CCTexture2D.cpp \ textures/CCTexture2D.cpp \
textures/CCTextureAtlas.cpp \ textures/CCTextureAtlas.cpp \
textures/CCTextureCache.cpp \ textures/CCTextureCache.cpp \
platform/third_party/common/etc/etc1.cpp\
platform/third_party/common/s3tc/s3tc.cpp\
tilemap_parallax_nodes/CCParallaxNode.cpp \ tilemap_parallax_nodes/CCParallaxNode.cpp \
tilemap_parallax_nodes/CCTileMapAtlas.cpp \
tilemap_parallax_nodes/CCTMXLayer.cpp \ tilemap_parallax_nodes/CCTMXLayer.cpp \
tilemap_parallax_nodes/CCTMXObjectGroup.cpp \ tilemap_parallax_nodes/CCTMXObjectGroup.cpp \
tilemap_parallax_nodes/CCTMXTiledMap.cpp \ tilemap_parallax_nodes/CCTMXTiledMap.cpp \
tilemap_parallax_nodes/CCTMXXMLParser.cpp \ tilemap_parallax_nodes/CCTMXXMLParser.cpp \
tilemap_parallax_nodes/CCTileMapAtlas.cpp \ touch_dispatcher/CCTouch.cpp \
touch_dispatcher/CCTouchDispatcher.cpp \ touch_dispatcher/CCTouchDispatcher.cpp \
touch_dispatcher/CCTouchHandler.cpp \ touch_dispatcher/CCTouchHandler.cpp
touch_dispatcher/CCTouch.cpp
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \ LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \
$(LOCAL_PATH)/include \ $(LOCAL_PATH)/include \
$(LOCAL_PATH)/kazmath/include \ $(LOCAL_PATH)/kazmath/include \
$(LOCAL_PATH)/platform/android \ $(LOCAL_PATH)/platform/android \
$(LOCAL_PATH)/platform/third_party/common/etc\ $(LOCAL_PATH)/platform/third_party/common/etc \
$(LOCAL_PATH)/platform/third_party/common/s3tc $(LOCAL_PATH)/platform/third_party/common/s3tc \
$(LOCAL_PATH)/platform/third_party/common/atitc
LOCAL_C_INCLUDES := $(LOCAL_PATH) \ LOCAL_C_INCLUDES := $(LOCAL_PATH) \
$(LOCAL_PATH)/include \ $(LOCAL_PATH)/include \
$(LOCAL_PATH)/kazmath/include \ $(LOCAL_PATH)/kazmath/include \
$(LOCAL_PATH)/platform/android \ $(LOCAL_PATH)/platform/android \
$(LOCAL_PATH)/platform/third_party/common/etc\ $(LOCAL_PATH)/platform/third_party/common/etc \
$(LOCAL_PATH)/platform/third_party/common/s3tc $(LOCAL_PATH)/platform/third_party/common/s3tc \
$(LOCAL_PATH)/platform/third_party/common/atitc
LOCAL_LDLIBS := -lGLESv2 \ LOCAL_LDLIBS := -lGLESv2 \

View File

@ -46,6 +46,7 @@ Configuration::Configuration()
, _supportsPVRTC(false) , _supportsPVRTC(false)
, _supportsETC(false) , _supportsETC(false)
, _supportsS3TC(false) , _supportsS3TC(false)
, _supportsATITC(false)
, _supportsNPOT(false) , _supportsNPOT(false)
, _supportsBGRA8888(false) , _supportsBGRA8888(false)
, _supportsDiscardFramebuffer(false) , _supportsDiscardFramebuffer(false)
@ -131,7 +132,10 @@ void Configuration::gatherGPUInfo()
_valueDict->setObject(Bool::create(_supportsETC), "gl.supports_ETC"); _valueDict->setObject(Bool::create(_supportsETC), "gl.supports_ETC");
_supportsS3TC = checkForGLExtension("GL_EXT_texture_compression_s3tc"); _supportsS3TC = checkForGLExtension("GL_EXT_texture_compression_s3tc");
_valueDict->setObject( Bool::create(_supportsS3TC), "gl.supports_S3TC"); _valueDict->setObject(Bool::create(_supportsS3TC), "gl.supports_S3TC");
_supportsATITC = checkForGLExtension("GL_AMD_compressed_ATC_texture");
_valueDict->setObject(Bool::create(_supportsATITC), "gl.supports_ATITC");
_supportsPVRTC = checkForGLExtension("GL_IMG_texture_compression_pvrtc"); _supportsPVRTC = checkForGLExtension("GL_IMG_texture_compression_pvrtc");
_valueDict->setObject(Bool::create(_supportsPVRTC), "gl.supports_PVRTC"); _valueDict->setObject(Bool::create(_supportsPVRTC), "gl.supports_PVRTC");
@ -238,6 +242,11 @@ bool Configuration::supportsS3TC() const
return _supportsS3TC; return _supportsS3TC;
} }
bool Configuration::supportsATITC() const
{
return _supportsATITC;
}
bool Configuration::supportsBGRA8888() const bool Configuration::supportsBGRA8888() const
{ {
return _supportsBGRA8888; return _supportsBGRA8888;

View File

@ -88,7 +88,10 @@ public:
bool supportsETC() const; bool supportsETC() const;
/** Whether or not S3TC Texture Compressed is supported */ /** Whether or not S3TC Texture Compressed is supported */
bool supportsS3TC(void ) const; bool supportsS3TC() const;
/** Whether or not ATITC Texture Compressed is supported */
bool supportsATITC() const;
/** Whether or not BGRA8888 textures are supported. /** Whether or not BGRA8888 textures are supported.
@since v0.99.2 @since v0.99.2
@ -148,6 +151,7 @@ protected:
bool _supportsPVRTC; bool _supportsPVRTC;
bool _supportsETC; bool _supportsETC;
bool _supportsS3TC; bool _supportsS3TC;
bool _supportsATITC;
bool _supportsNPOT; bool _supportsNPOT;
bool _supportsBGRA8888; bool _supportsBGRA8888;
bool _supportsDiscardFramebuffer; bool _supportsDiscardFramebuffer;

View File

@ -115,7 +115,7 @@ bool Director::init(void)
_notificationNode = nullptr; _notificationNode = nullptr;
_scenesStack = new Array(); _scenesStack = new Array();
_scenesStack->init(); _scenesStack->initWithCapacity(15);
// projection delegate if "Custom" projection is used // projection delegate if "Custom" projection is used
_projectionDelegate = nullptr; _projectionDelegate = nullptr;
@ -168,7 +168,7 @@ bool Director::init(void)
Director::~Director(void) Director::~Director(void)
{ {
CCLOG("cocos2d: deallocing Director %p", this); CCLOGINFO("deallocing Director: %p", this);
CC_SAFE_RELEASE(_FPSLabel); CC_SAFE_RELEASE(_FPSLabel);
CC_SAFE_RELEASE(_SPFLabel); CC_SAFE_RELEASE(_SPFLabel);
@ -622,7 +622,7 @@ void Director::popScene(void)
else else
{ {
_sendCleanupToScene = true; _sendCleanupToScene = true;
_nextScene = (Scene*)_scenesStack->objectAtIndex(c - 1); _nextScene = (Scene*)_scenesStack->getObjectAtIndex(c - 1);
} }
} }
@ -650,7 +650,7 @@ void Director::popToSceneStackLevel(int level)
// pop stack until reaching desired level // pop stack until reaching desired level
while (c > level) while (c > level)
{ {
Scene *current = (Scene*)_scenesStack->lastObject(); Scene *current = (Scene*)_scenesStack->getLastObject();
if (current->isRunning()) if (current->isRunning())
{ {
@ -663,7 +663,7 @@ void Director::popToSceneStackLevel(int level)
--c; --c;
} }
_nextScene = (Scene*)_scenesStack->lastObject(); _nextScene = (Scene*)_scenesStack->getLastObject();
_sendCleanupToScene = false; _sendCleanupToScene = false;
} }

View File

@ -36,7 +36,6 @@ THE SOFTWARE.
#include "CCGL.h" #include "CCGL.h"
#include "kazmath/mat4.h" #include "kazmath/mat4.h"
#include "label_nodes/CCLabelAtlas.h" #include "label_nodes/CCLabelAtlas.h"
#include "ccTypeInfo.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -79,7 +78,7 @@ and when to execute the Scenes.
- GL_COLOR_ARRAY is enabled - GL_COLOR_ARRAY is enabled
- GL_TEXTURE_COORD_ARRAY is enabled - GL_TEXTURE_COORD_ARRAY is enabled
*/ */
class CC_DLL Director : public Object, public TypeInfo class CC_DLL Director : public Object
{ {
public: public:
/** @typedef ccDirectorProjection /** @typedef ccDirectorProjection
@ -109,10 +108,6 @@ public:
Director(void); Director(void);
virtual ~Director(void); virtual ~Director(void);
virtual bool init(void); virtual bool init(void);
virtual long getClassTypeInfo() {
static const long id = cocos2d::getHashCodeByString(typeid(cocos2d::Director).name());
return id;
}
// attribute // attribute

View File

@ -687,7 +687,7 @@ void Scheduler::unscheduleScriptEntry(unsigned int uScheduleScriptEntryID)
{ {
for (int i = _scriptHandlerEntries->count() - 1; i >= 0; i--) for (int i = _scriptHandlerEntries->count() - 1; i >= 0; i--)
{ {
SchedulerScriptHandlerEntry* pEntry = static_cast<SchedulerScriptHandlerEntry*>(_scriptHandlerEntries->objectAtIndex(i)); SchedulerScriptHandlerEntry* pEntry = static_cast<SchedulerScriptHandlerEntry*>(_scriptHandlerEntries->getObjectAtIndex(i));
if (pEntry->getEntryId() == (int)uScheduleScriptEntryID) if (pEntry->getEntryId() == (int)uScheduleScriptEntryID)
{ {
pEntry->markedForDeletion(); pEntry->markedForDeletion();
@ -909,7 +909,7 @@ void Scheduler::update(float dt)
{ {
for (int i = _scriptHandlerEntries->count() - 1; i >= 0; i--) for (int i = _scriptHandlerEntries->count() - 1; i >= 0; i--)
{ {
SchedulerScriptHandlerEntry* pEntry = static_cast<SchedulerScriptHandlerEntry*>(_scriptHandlerEntries->objectAtIndex(i)); SchedulerScriptHandlerEntry* pEntry = static_cast<SchedulerScriptHandlerEntry*>(_scriptHandlerEntries->getObjectAtIndex(i));
if (pEntry->isMarkedForDeletion()) if (pEntry->isMarkedForDeletion())
{ {
_scriptHandlerEntries->removeObjectAtIndex(i); _scriptHandlerEntries->removeObjectAtIndex(i);

View File

@ -43,7 +43,7 @@ Action::Action()
Action::~Action() Action::~Action()
{ {
CCLOGINFO("cocos2d: deallocing"); CCLOGINFO("deallocing Action: %p - tag: %i", this, _tag);
} }
const char* Action::description() const const char* Action::description() const

View File

@ -89,6 +89,8 @@ PointArray* PointArray::clone() const
PointArray::~PointArray() PointArray::~PointArray()
{ {
CCLOGINFO("deallocing PointArray: %p", this);
vector<Point*>::iterator iter; vector<Point*>::iterator iter;
for (iter = _controlPoints->begin(); iter != _controlPoints->end(); ++iter) for (iter = _controlPoints->begin(); iter != _controlPoints->end(); ++iter)
{ {

View File

@ -31,7 +31,6 @@ THE SOFTWARE.
#include <functional> #include <functional>
#include "CCStdC.h" #include "CCStdC.h"
#include "ccTypeInfo.h"
#include "CCAction.h" #include "CCAction.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -297,7 +296,7 @@ protected:
@brief Calls a 'callback' with the node as the first argument @brief Calls a 'callback' with the node as the first argument
N means Node N means Node
*/ */
class CC_DLL CallFuncN : public CallFunc, public TypeInfo class CC_DLL CallFuncN : public CallFunc
{ {
public: public:
/** creates the action with the callback of type std::function<void()>. /** creates the action with the callback of type std::function<void()>.
@ -325,11 +324,6 @@ public:
*/ */
CC_DEPRECATED_ATTRIBUTE bool initWithTarget(Object* pSelectorTarget, SEL_CallFuncN selector); CC_DEPRECATED_ATTRIBUTE bool initWithTarget(Object* pSelectorTarget, SEL_CallFuncN selector);
virtual long getClassTypeInfo() {
static const long id = cocos2d::getHashCodeByString(typeid(cocos2d::CallFunc).name());
return id;
}
// //
// Overrides // Overrides
// //
@ -353,11 +347,6 @@ public:
/** creates the action with the callback and the data to pass as an argument */ /** creates the action with the callback and the data to pass as an argument */
CC_DEPRECATED_ATTRIBUTE static __CCCallFuncND * create(Object* selectorTarget, SEL_CallFuncND selector, void* d); CC_DEPRECATED_ATTRIBUTE static __CCCallFuncND * create(Object* selectorTarget, SEL_CallFuncND selector, void* d);
virtual long getClassTypeInfo() {
static const long id = cocos2d::getHashCodeByString(typeid(cocos2d::CallFunc).name());
return id;
}
protected: protected:
/** initializes the action with the callback and the data to pass as an argument */ /** initializes the action with the callback and the data to pass as an argument */
bool initWithTarget(Object* selectorTarget, SEL_CallFuncND selector, void* d); bool initWithTarget(Object* selectorTarget, SEL_CallFuncND selector, void* d);
@ -382,7 +371,7 @@ protected:
@since v0.99.5 @since v0.99.5
*/ */
class CC_DLL __CCCallFuncO : public CallFunc, public TypeInfo class CC_DLL __CCCallFuncO : public CallFunc
{ {
public: public:
/** creates the action with the callback /** creates the action with the callback
@ -394,11 +383,6 @@ public:
__CCCallFuncO(); __CCCallFuncO();
virtual ~__CCCallFuncO(); virtual ~__CCCallFuncO();
virtual long getClassTypeInfo() {
static const long id = cocos2d::getHashCodeByString(typeid(cocos2d::CallFunc).name());
return id;
}
protected: protected:
/** initializes the action with the callback /** initializes the action with the callback

View File

@ -206,13 +206,13 @@ Sequence* Sequence::create(Array* arrayOfActions)
unsigned int count = arrayOfActions->count(); unsigned int count = arrayOfActions->count();
CC_BREAK_IF(count == 0); CC_BREAK_IF(count == 0);
FiniteTimeAction* prev = static_cast<FiniteTimeAction*>( arrayOfActions->objectAtIndex(0) ); FiniteTimeAction* prev = static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(0));
if (count > 1) if (count > 1)
{ {
for (unsigned int i = 1; i < count; ++i) for (unsigned int i = 1; i < count; ++i)
{ {
prev = createWithTwoActions(prev, static_cast<FiniteTimeAction*>( arrayOfActions->objectAtIndex(i)) ); prev = createWithTwoActions(prev, static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(i)));
} }
} }
else else
@ -578,12 +578,12 @@ Spawn* Spawn::create(Array *arrayOfActions)
{ {
unsigned int count = arrayOfActions->count(); unsigned int count = arrayOfActions->count();
CC_BREAK_IF(count == 0); CC_BREAK_IF(count == 0);
FiniteTimeAction* prev = static_cast<FiniteTimeAction*>( arrayOfActions->objectAtIndex(0) ); FiniteTimeAction* prev = static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(0));
if (count > 1) if (count > 1)
{ {
for (unsigned int i = 1; i < arrayOfActions->count(); ++i) for (unsigned int i = 1; i < arrayOfActions->count(); ++i)
{ {
prev = createWithTwoActions(prev, static_cast<FiniteTimeAction*>( arrayOfActions->objectAtIndex(i)) ); prev = createWithTwoActions(prev, static_cast<FiniteTimeAction*>(arrayOfActions->getObjectAtIndex(i)));
} }
} }
else else
@ -2107,7 +2107,7 @@ void Animate::update(float t)
float splitTime = _splitTimes->at(i); float splitTime = _splitTimes->at(i);
if( splitTime <= t ) { if( splitTime <= t ) {
AnimationFrame* frame = static_cast<AnimationFrame*>(frames->objectAtIndex(i)); AnimationFrame* frame = static_cast<AnimationFrame*>(frames->getObjectAtIndex(i));
frameToDisplay = frame->getSpriteFrame(); frameToDisplay = frame->getSpriteFrame();
static_cast<Sprite*>(_target)->setDisplayFrame(frameToDisplay); static_cast<Sprite*>(_target)->setDisplayFrame(frameToDisplay);

View File

@ -58,7 +58,7 @@ ActionManager::ActionManager(void)
ActionManager::~ActionManager(void) ActionManager::~ActionManager(void)
{ {
CCLOGINFO("cocos2d: deallocing %p", this); CCLOGINFO("deallocing ActionManager: %p", this);
removeAllActions(); removeAllActions();
} }

View File

@ -24,8 +24,13 @@ 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "cocoa/CCString.h"
#include "CCNode.h" #include "CCNode.h"
#include <algorithm>
#include "cocoa/CCString.h"
#include "support/data_support/ccCArray.h"
#include "support/TransformUtils.h" #include "support/TransformUtils.h"
#include "CCCamera.h" #include "CCCamera.h"
#include "effects/CCGrid.h" #include "effects/CCGrid.h"
@ -35,6 +40,7 @@ THE SOFTWARE.
#include "actions/CCActionManager.h" #include "actions/CCActionManager.h"
#include "script_support/CCScriptSupport.h" #include "script_support/CCScriptSupport.h"
#include "shaders/CCGLProgram.h" #include "shaders/CCGLProgram.h"
// externals // externals
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
#include "support/component/CCComponent.h" #include "support/component/CCComponent.h"
@ -63,9 +69,9 @@ Node::Node(void)
, _anchorPointInPoints(Point::ZERO) , _anchorPointInPoints(Point::ZERO)
, _anchorPoint(Point::ZERO) , _anchorPoint(Point::ZERO)
, _contentSize(Size::ZERO) , _contentSize(Size::ZERO)
, _additionalTransform(AffineTransformMakeIdentity()) , _additionalTransform(AffineTransform::IDENTITY)
, _transform(AffineTransformMakeIdentity()) , _transform(AffineTransform::IDENTITY)
, _inverse(AffineTransformMakeIdentity()) , _inverse(AffineTransform::IDENTITY)
, _additionalTransformDirty(false) , _additionalTransformDirty(false)
, _transformDirty(true) , _transformDirty(true)
, _inverseDirty(true) , _inverseDirty(true)
@ -105,7 +111,7 @@ Node::Node(void)
Node::~Node() Node::~Node()
{ {
CCLOGINFO( "cocos2d: deallocing: %p", this ); CCLOGINFO( "deallocing Node: %p - tag: %i", this, _tag );
if (_updateScriptHandler) if (_updateScriptHandler)
{ {
@ -607,10 +613,14 @@ void Node::removeChild(Node* child, bool cleanup /* = true */)
return; return;
} }
if ( _children->containsObject(child) ) // if ( _children->containsObject(child) )
{ // {
this->detachChild(child,cleanup); // this->detachChild(child,cleanup);
} // }
int index = _children->getIndexOfObject(child);
if( index != CC_INVALID_INDEX )
this->detachChild( child, index, cleanup );
} }
void Node::removeChildByTag(int tag, bool cleanup/* = true */) void Node::removeChildByTag(int tag, bool cleanup/* = true */)
@ -668,7 +678,7 @@ void Node::removeAllChildrenWithCleanup(bool cleanup)
} }
void Node::detachChild(Node *child, bool doCleanup) void Node::detachChild(Node *child, int childIndex, bool doCleanup)
{ {
// IMPORTANT: // IMPORTANT:
// -1st do onExit // -1st do onExit
@ -689,7 +699,7 @@ void Node::detachChild(Node *child, bool doCleanup)
// set parent nil at the end // set parent nil at the end
child->setParent(NULL); child->setParent(NULL);
_children->removeObject(child); _children->removeObjectAtIndex(childIndex);
} }
@ -697,7 +707,7 @@ void Node::detachChild(Node *child, bool doCleanup)
void Node::insertChild(Node* child, int z) void Node::insertChild(Node* child, int z)
{ {
_reorderChildDirty = true; _reorderChildDirty = true;
ccArrayAppendObjectWithResize(_children->data, child); _children->addObject(child);
child->_setZOrder(z); child->_setZOrder(z);
} }
@ -709,33 +719,65 @@ void Node::reorderChild(Node *child, int zOrder)
child->_setZOrder(zOrder); child->_setZOrder(zOrder);
} }
#if CC_USE_ARRAY_VECTOR
static bool objectComparisonLess(const RCPtr<Object>& pp1, const RCPtr<Object>& pp2)
{
Object *p1 = static_cast<Object*>(pp1);
Object *p2 = static_cast<Object*>(pp2);
Node *n1 = static_cast<Node*>(p1);
Node *n2 = static_cast<Node*>(p2);
return( n1->getZOrder() < n2->getZOrder() ||
( n1->getZOrder() == n2->getZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() )
);
}
#else
static bool objectComparisonLess(Object* p1, Object* p2)
{
Node *n1 = static_cast<Node*>(p1);
Node *n2 = static_cast<Node*>(p2);
return( n1->getZOrder() < n2->getZOrder() ||
( n1->getZOrder() == n2->getZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() )
);
}
#endif
void Node::sortAllChildren() void Node::sortAllChildren()
{ {
#if 0
if (_reorderChildDirty) if (_reorderChildDirty)
{ {
int i,j,length = _children->data->num; int i,j,length = _children->count();
Node ** x = (Node**)_children->data->arr;
Node *tempItem;
// insertion sort // insertion sort
for(i=1; i<length; i++) for(i=1; i<length; i++)
{ {
tempItem = x[i];
j = i-1; j = i-1;
auto tempI = static_cast<Node*>( _children->getObjectAtIndex(i) );
auto tempJ = static_cast<Node*>( _children->getObjectAtIndex(j) );
//continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while(j>=0 && ( tempItem->_ZOrder < x[j]->_ZOrder || ( tempItem->_ZOrder== x[j]->_ZOrder && tempItem->_orderOfArrival < x[j]->_orderOfArrival ) ) ) while(j>=0 && ( tempI->_ZOrder < tempJ->_ZOrder || ( tempI->_ZOrder == tempJ->_ZOrder && tempI->_orderOfArrival < tempJ->_orderOfArrival ) ) )
{ {
x[j+1] = x[j]; _children->fastSetObject( tempJ, j+1 );
j = j-1; j = j-1;
if(j>=0)
tempJ = static_cast<Node*>( _children->getObjectAtIndex(j) );
} }
x[j+1] = tempItem; _children->fastSetObject(tempI, j+1);
} }
//don't need to check children recursively, that's done in visit of each child //don't need to check children recursively, that's done in visit of each child
_reorderChildDirty = false; _reorderChildDirty = false;
} }
#else
if( _reorderChildDirty ) {
std::sort( std::begin(*_children), std::end(*_children), objectComparisonLess );
_reorderChildDirty = false;
}
#endif
} }
@ -762,38 +804,29 @@ void Node::visit()
} }
this->transform(); this->transform();
Node* pNode = NULL;
unsigned int i = 0; unsigned int i = 0;
if(_children && _children->count() > 0) if(_children && _children->count() > 0)
{ {
sortAllChildren(); sortAllChildren();
// draw children zOrder < 0 // draw children zOrder < 0
ccArray *arrayData = _children->data; for( ; i < _children->count(); i++ )
for( ; i < arrayData->num; i++ )
{ {
pNode = (Node*) arrayData->arr[i]; auto node = static_cast<Node*>( _children->getObjectAtIndex(i) );
if ( pNode && pNode->_ZOrder < 0 ) if ( node && node->_ZOrder < 0 )
{ node->visit();
pNode->visit();
}
else else
{
break; break;
} }
}
// self draw // self draw
this->draw(); this->draw();
for( ; i < arrayData->num; i++ ) for( ; i < _children->count(); i++ )
{ {
pNode = (Node*) arrayData->arr[i]; auto node = static_cast<Node*>( _children->getObjectAtIndex(i) );
if (pNode) if (node)
{ node->visit();
pNode->visit();
}
} }
} }
else else

View File

@ -1296,7 +1296,7 @@ public:
virtual void removeAllComponents(); virtual void removeAllComponents();
/// @} end of component functions /// @} end of component functions
private: protected:
/// lazy allocs /// lazy allocs
void childrenAlloc(void); void childrenAlloc(void);
@ -1304,12 +1304,12 @@ private:
void insertChild(Node* child, int z); void insertChild(Node* child, int z);
/// Removes a child, call child->onExit(), do cleanup, remove it from children array. /// Removes a child, call child->onExit(), do cleanup, remove it from children array.
void detachChild(Node *child, bool doCleanup); void detachChild(Node *child, int index, bool doCleanup);
/// Convert cocos2d coordinates to UI windows coordinate. /// Convert cocos2d coordinates to UI windows coordinate.
Point convertToWindowSpace(const Point& nodePoint) const; Point convertToWindowSpace(const Point& nodePoint) const;
protected:
float _rotationX; ///< rotation angle on x-axis float _rotationX; ///< rotation angle on x-axis
float _rotationY; ///< rotation angle on y-axis float _rotationY; ///< rotation angle on y-axis

View File

@ -26,6 +26,13 @@
NS_CC_BEGIN NS_CC_BEGIN
Color4B::Color4B(const Color4F &color4F)
: r((GLubyte)(color4F.r * 255.0f)),
g((GLubyte)(color4F.g * 255.0f)),
b((GLubyte)(color4F.b * 255.0f)),
a((GLubyte)(color4F.a * 255.0f))
{}
const Color3B Color3B::WHITE(255,255,255); const Color3B Color3B::WHITE(255,255,255);
const Color3B Color3B::YELLOW(255,255,0); const Color3B Color3B::YELLOW(255,255,0);
const Color3B Color3B::GREEN(0,255,0); const Color3B Color3B::GREEN(0,255,0);
@ -36,12 +43,25 @@ const Color3B Color3B::BLACK(0,0,0);
const Color3B Color3B::ORANGE(255,127,0); const Color3B Color3B::ORANGE(255,127,0);
const Color3B Color3B::GRAY(166,166,166); const Color3B Color3B::GRAY(166,166,166);
Color4B::Color4B(const Color4F &color4F) const Color4B Color4B::WHITE(255,255,255,255);
: r((GLubyte)(color4F.r * 255.0f)), const Color4B Color4B::YELLOW(255,255,0,255);
g((GLubyte)(color4F.g * 255.0f)), const Color4B Color4B::GREEN(0,255,0,255);
b((GLubyte)(color4F.b * 255.0f)), const Color4B Color4B::BLUE(0,0,255,255);
a((GLubyte)(color4F.a * 255.0f)) const Color4B Color4B::RED(255,0,0,255);
{} const Color4B Color4B::MAGENTA(255,0,255,255);
const Color4B Color4B::BLACK(0,0,0,255);
const Color4B Color4B::ORANGE(255,127,0,255);
const Color4B Color4B::GRAY(166,166,166,255);
const Color4F Color4F::WHITE(1,1,1,1);
const Color4F Color4F::YELLOW(1,1,0,1);
const Color4F Color4F::GREEN(0,1,0,1);
const Color4F Color4F::BLUE(0,0,1,1);
const Color4F Color4F::RED(1,0,0,1);
const Color4F Color4F::MAGENTA(1,0,1,1);
const Color4F Color4F::BLACK(0,0,0,1);
const Color4F Color4F::ORANGE(1,0.5,0,1);
const Color4F Color4F::GRAY(0.65,0.65,0.65,1);
const BlendFunc BlendFunc::DISABLE = {GL_ONE, GL_ZERO}; const BlendFunc BlendFunc::DISABLE = {GL_ONE, GL_ZERO};
const BlendFunc BlendFunc::ALPHA_PREMULTIPLIED = {GL_ONE, GL_ONE_MINUS_SRC_ALPHA}; const BlendFunc BlendFunc::ALPHA_PREMULTIPLIED = {GL_ONE, GL_ONE_MINUS_SRC_ALPHA};

View File

@ -60,7 +60,7 @@ AffineTransform AffineTransformMakeIdentity()
} }
extern const AffineTransform AffineTransformIdentity = AffineTransformMakeIdentity(); extern const AffineTransform AffineTransformIdentity = AffineTransformMakeIdentity();
const AffineTransform AffineTransform::IDENTITY = AffineTransformMakeIdentity();
Rect RectApplyAffineTransform(const Rect& rect, const AffineTransform& anAffineTransform) Rect RectApplyAffineTransform(const Rect& rect, const AffineTransform& anAffineTransform)
{ {

View File

@ -33,6 +33,8 @@ NS_CC_BEGIN
struct AffineTransform { struct AffineTransform {
float a, b, c, d; float a, b, c, d;
float tx, ty; float tx, ty;
static const AffineTransform IDENTITY;
}; };
CC_DLL AffineTransform __CCAffineTransformMake(float a, float b, float c, float d, float tx, float ty); CC_DLL AffineTransform __CCAffineTransformMake(float a, float b, float c, float d, float tx, float ty);

View File

@ -30,74 +30,74 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
#if CC_USE_ARRAY_VECTOR
// ----------------------------------------------------------------------------------
// std::vector implementation
// ----------------------------------------------------------------------------------
Array::Array() Array::Array()
: data(NULL) : data(NULL)
{ {
init(); init();
} }
Array::Array(unsigned int capacity)
: data(NULL)
{
initWithCapacity(capacity);
}
Array* Array::create() Array* Array::create()
{ {
Array* pArray = new Array(); Array* array = new Array();
if (pArray && pArray->init()) if (array && array->initWithCapacity(7))
{ {
pArray->autorelease(); array->autorelease();
} }
else else
{ {
CC_SAFE_DELETE(pArray); CC_SAFE_DELETE(array);
} }
return pArray; return array;
} }
Array* Array::createWithObject(Object* pObject) Array* Array::createWithObject(Object* object)
{ {
Array* pArray = new Array(); Array* array = new Array();
if (pArray && pArray->initWithObject(pObject)) if (array && array->initWithObject(object))
{ {
pArray->autorelease(); array->autorelease();
} }
else else
{ {
CC_SAFE_DELETE(pArray); CC_SAFE_DELETE(array);
} }
return pArray; return array;
} }
Array* Array::create(Object* pObject, ...) Array* Array::create(Object* object, ...)
{ {
va_list args; va_list args;
va_start(args,pObject); va_start(args,object);
Array* pArray = create(); Array* array = create();
if (pArray && pObject) if (array && object)
{ {
pArray->addObject(pObject); array->addObject(object);
Object *i = va_arg(args, Object*); Object *i = va_arg(args, Object*);
while(i) while (i)
{ {
pArray->addObject(i); array->addObject(i);
i = va_arg(args, Object*); i = va_arg(args, Object*);
} }
} }
else else
{ {
CC_SAFE_DELETE(pArray); CC_SAFE_DELETE(array);
} }
va_end(args); va_end(args);
return pArray; return array;
} }
Array* Array::createWithArray(Array* otherArray) Array* Array::createWithArray(Array* otherArray)
@ -105,140 +105,113 @@ Array* Array::createWithArray(Array* otherArray)
return otherArray->clone(); return otherArray->clone();
} }
Array* Array::createWithCapacity(unsigned int capacity) Array* Array::createWithCapacity(int capacity)
{ {
Array* pArray = new Array(); Array* array = new Array();
if (pArray && pArray->initWithCapacity(capacity)) if (array && array->initWithCapacity(capacity))
{ {
pArray->autorelease(); array->autorelease();
} }
else else
{ {
CC_SAFE_DELETE(pArray); CC_SAFE_DELETE(array);
} }
return pArray; return array;
} }
Array* Array::createWithContentsOfFile(const char* pFileName) Array* Array::createWithContentsOfFile(const char* fileName)
{ {
Array* pRet = Array::createWithContentsOfFileThreadSafe(pFileName); Array* ret = Array::createWithContentsOfFileThreadSafe(fileName);
if (pRet != NULL) if (ret != nullptr)
{ {
pRet->autorelease(); ret->autorelease();
} }
return pRet; return ret;
} }
Array* Array::createWithContentsOfFileThreadSafe(const char* pFileName) Array* Array::createWithContentsOfFileThreadSafe(const char* fileName)
{ {
return FileUtils::getInstance()->createArrayWithContentsOfFile(pFileName); return FileUtils::getInstance()->createArrayWithContentsOfFile(fileName);
} }
bool Array::init() bool Array::init()
{ {
return initWithCapacity(1); return initWithCapacity(7);
} }
bool Array::initWithObject(Object* pObject) bool Array::initWithObject(Object* object)
{ {
ccArrayFree(data); bool ret = initWithCapacity(7);
bool bRet = initWithCapacity(1); if (ret)
if (bRet)
{ {
addObject(pObject); addObject(object);
} }
return bRet; return ret;
} }
/** Initializes an array with some objects */ /** Initializes an array with some objects */
bool Array::initWithObjects(Object* pObject, ...) bool Array::initWithObjects(Object* object, ...)
{ {
ccArrayFree(data); bool ret = false;
bool bRet = false;
do do
{ {
CC_BREAK_IF(pObject == NULL); CC_BREAK_IF(object == nullptr);
va_list args; va_list args;
va_start(args, pObject); va_start(args, object);
if (pObject) if (object)
{ {
this->addObject(pObject); this->addObject(object);
Object* i = va_arg(args, Object*); Object* i = va_arg(args, Object*);
while(i) while (i)
{ {
this->addObject(i); this->addObject(i);
i = va_arg(args, Object*); i = va_arg(args, Object*);
} }
bRet = true; ret = true;
} }
va_end(args); va_end(args);
} while (false); } while (false);
return bRet; return ret;
} }
bool Array::initWithCapacity(unsigned int capacity) bool Array::initWithCapacity(int capacity)
{ {
ccArrayFree(data); data.reserve(capacity);
data = ccArrayNew(capacity);
return true; return true;
} }
bool Array::initWithArray(Array* otherArray) bool Array::initWithArray(Array* otherArray)
{ {
ccArrayFree(data); data = otherArray->data;
bool bRet = false; return true;
do }
int Array::getIndexOfObject(Object* object) const
{
auto it = data.begin();
for (int i = 0; it != data.end(); ++it, ++i)
{ {
CC_BREAK_IF(! initWithCapacity(otherArray->data->num)); if (it->get() == object)
addObjectsFromArray(otherArray);
bRet = true;
} while (0);
return bRet;
}
unsigned int Array::count() const
{
return data->num;
}
unsigned int Array::capacity() const
{
return data->max;
}
unsigned int Array::indexOfObject(Object* object) const
{
return ccArrayGetIndexOfObject(data, object);
}
Object* Array::objectAtIndex(unsigned int index)
{
CCASSERT(index < data->num, "index out of range in objectAtIndex()");
return data->arr[index];
}
Object* Array::lastObject()
{
if( data->num > 0 )
return data->arr[data->num-1];
return NULL;
}
Object* Array::randomObject()
{
if (data->num==0)
{ {
return NULL; return i;
}
}
return -1;
}
Object* Array::getRandomObject()
{
if (data.size()==0)
{
return nullptr;
} }
float r = CCRANDOM_0_1(); float r = CCRANDOM_0_1();
@ -248,19 +221,22 @@ Object* Array::randomObject()
r = 0; r = 0;
} }
return data->arr[(int)(data->num * r)]; r *= data.size();
return data[r].get();
} }
bool Array::containsObject(Object* object) const bool Array::containsObject(Object* object) const
{ {
return ccArrayContainsObject(data, object); int i = this->getIndexOfObject(object);
return (i >=0);
} }
bool Array::isEqualToArray(Array* otherArray) bool Array::isEqualToArray(Array* otherArray)
{ {
for (unsigned int i = 0; i< this->count(); i++) for (int i = 0; i< this->count(); i++)
{ {
if (!this->objectAtIndex(i)->isEqual(otherArray->objectAtIndex(i))) if (!this->getObjectAtIndex(i)->isEqual(otherArray->getObjectAtIndex(i)))
{ {
return false; return false;
} }
@ -270,118 +246,105 @@ bool Array::isEqualToArray(Array* otherArray)
void Array::addObject(Object* object) void Array::addObject(Object* object)
{ {
ccArrayAppendObjectWithResize(data, object); data.push_back( RCPtr<Object>(object) );
} }
void Array::addObjectsFromArray(Array* otherArray) void Array::addObjectsFromArray(Array* otherArray)
{ {
ccArrayAppendArrayWithResize(data, otherArray->data); data.insert(data.end(), otherArray->data.begin(), otherArray->data.end());
} }
void Array::insertObject(Object* object, unsigned int index) void Array::insertObject(Object* object, int index)
{ {
ccArrayInsertObjectAtIndex(data, object, index); data.insert( std::begin(data) + index, RCPtr<Object>(object) );
} }
void Array::removeLastObject(bool bReleaseObj) void Array::setObject(Object* object, int index)
{ {
CCASSERT(data->num, "no objects added"); data[index] = RCPtr<Object>(object);
ccArrayRemoveObjectAtIndex(data, data->num-1, bReleaseObj);
} }
void Array::removeObject(Object* object, bool bReleaseObj/* = true*/) void Array::removeLastObject(bool releaseObj)
{ {
ccArrayRemoveObject(data, object, bReleaseObj); CCASSERT(data.size(), "no objects added");
data.pop_back();
} }
void Array::removeObjectAtIndex(unsigned int index, bool bReleaseObj) void Array::removeObject(Object* object, bool releaseObj /* ignored */)
{ {
ccArrayRemoveObjectAtIndex(data, index, bReleaseObj); data.erase( std::remove( data.begin(), data.end(), object ) );
}
void Array::removeObjectAtIndex(int index, bool releaseObj /* ignored */)
{
auto obj = data[index];
data.erase( data.begin() + index );
} }
void Array::removeObjectsInArray(Array* otherArray) void Array::removeObjectsInArray(Array* otherArray)
{ {
ccArrayRemoveArray(data, otherArray->data); CCASSERT(false, "not implemented");
} }
void Array::removeAllObjects() void Array::removeAllObjects()
{ {
ccArrayRemoveAllObjects(data); data.erase(std::begin(data), std::end(data));
} }
void Array::fastRemoveObjectAtIndex(unsigned int index) void Array::fastRemoveObjectAtIndex(int index)
{ {
ccArrayFastRemoveObjectAtIndex(data, index); removeObjectAtIndex(index);
} }
void Array::fastRemoveObject(Object* object) void Array::fastRemoveObject(Object* object)
{ {
ccArrayFastRemoveObject(data, object); removeObject(object);
} }
void Array::exchangeObject(Object* object1, Object* object2) void Array::exchangeObject(Object* object1, Object* object2)
{ {
unsigned int index1 = ccArrayGetIndexOfObject(data, object1); int idx1 = getIndexOfObject(object1);
if(index1 == UINT_MAX) int idx2 = getIndexOfObject(object2);
{
return;
}
unsigned int index2 = ccArrayGetIndexOfObject(data, object2); CCASSERT(idx1>=0 && idx2>=2, "invalid object index");
if(index2 == UINT_MAX)
{
return;
}
ccArraySwapObjectsAtIndexes(data, index1, index2); std::swap( data[idx1], data[idx2] );
} }
void Array::exchangeObjectAtIndex(unsigned int index1, unsigned int index2) void Array::exchangeObjectAtIndex(int index1, int index2)
{ {
ccArraySwapObjectsAtIndexes(data, index1, index2); std::swap( data[index1], data[index2] );
} }
void Array::replaceObjectAtIndex(unsigned int index, Object* pObject, bool bReleaseObject/* = true*/) void Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject /* ignored */)
{ {
ccArrayInsertObjectAtIndex(data, pObject, index); data[index] = object;
ccArrayRemoveObjectAtIndex(data, index+1);
} }
void Array::reverseObjects() void Array::reverseObjects()
{ {
if (data->num > 1) std::reverse( std::begin(data), std::end(data) );
{
// floorf(), since in the case of an even number, the number of swaps stays the same
int count = (int) floorf(data->num/2.f);
unsigned int maxIndex = data->num - 1;
for (int i = 0; i < count ; i++)
{
ccArraySwapObjectsAtIndexes(data, i, maxIndex);
maxIndex--;
}
}
} }
void Array::reduceMemoryFootprint() void Array::reduceMemoryFootprint()
{ {
ccArrayShrink(data); // N/A
} }
Array::~Array() Array::~Array()
{ {
ccArrayFree(data); CCLOGINFO("deallocing Array: %p - len: %d", this, count() );
} }
Array* Array::clone() const Array* Array::clone() const
{ {
Array* ret = new Array(); Array* ret = new Array();
ret->autorelease(); ret->autorelease();
ret->initWithCapacity(this->data->num > 0 ? this->data->num : 1); ret->initWithCapacity(this->data.size() > 0 ? this->data.size() : 1);
Object* obj = NULL; Object* obj = nullptr;
Object* tmpObj = NULL; Object* tmpObj = nullptr;
Clonable* clonable = NULL; Clonable* clonable = nullptr;
CCARRAY_FOREACH(this, obj) CCARRAY_FOREACH(this, obj)
{ {
clonable = dynamic_cast<Clonable*>(obj); clonable = dynamic_cast<Clonable*>(obj);
@ -406,4 +369,380 @@ void Array::acceptVisitor(DataVisitor &visitor)
visitor.visit(this); visitor.visit(this);
} }
// ----------------------------------------------------------------------------------
// ccArray implementation
// ----------------------------------------------------------------------------------
#else
Array::Array()
: data(nullptr)
{
// init();
}
Array* Array::create()
{
Array* array = new Array();
if (array && array->initWithCapacity(7))
{
array->autorelease();
}
else
{
CC_SAFE_DELETE(array);
}
return array;
}
Array* Array::createWithObject(Object* object)
{
Array* array = new Array();
if (array && array->initWithObject(object))
{
array->autorelease();
}
else
{
CC_SAFE_DELETE(array);
}
return array;
}
Array* Array::create(Object* object, ...)
{
va_list args;
va_start(args,object);
Array* array = create();
if (array && object)
{
array->addObject(object);
Object *i = va_arg(args, Object*);
while (i)
{
array->addObject(i);
i = va_arg(args, Object*);
}
}
else
{
CC_SAFE_DELETE(array);
}
va_end(args);
return array;
}
Array* Array::createWithArray(Array* otherArray)
{
return otherArray->clone();
}
Array* Array::createWithCapacity(int capacity)
{
Array* array = new Array();
if (array && array->initWithCapacity(capacity))
{
array->autorelease();
}
else
{
CC_SAFE_DELETE(array);
}
return array;
}
Array* Array::createWithContentsOfFile(const char* fileName)
{
Array* ret = Array::createWithContentsOfFileThreadSafe(fileName);
if (ret != nullptr)
{
ret->autorelease();
}
return ret;
}
Array* Array::createWithContentsOfFileThreadSafe(const char* fileName)
{
return FileUtils::getInstance()->createArrayWithContentsOfFile(fileName);
}
bool Array::init()
{
CCASSERT(!data, "Array cannot be re-initialized");
return initWithCapacity(7);
}
bool Array::initWithObject(Object* object)
{
CCASSERT(!data, "Array cannot be re-initialized");
bool ret = initWithCapacity(7);
if (ret)
{
addObject(object);
}
return ret;
}
/** Initializes an array with some objects */
bool Array::initWithObjects(Object* object, ...)
{
CCASSERT(!data, "Array cannot be re-initialized");
bool ret = false;
do
{
CC_BREAK_IF(object == nullptr);
va_list args;
va_start(args, object);
if (object)
{
this->addObject(object);
Object* i = va_arg(args, Object*);
while (i)
{
this->addObject(i);
i = va_arg(args, Object*);
}
ret = true;
}
va_end(args);
} while (false);
return ret;
}
bool Array::initWithCapacity(int capacity)
{
CCASSERT(!data, "Array cannot be re-initialized");
data = ccArrayNew(capacity);
return true;
}
bool Array::initWithArray(Array* otherArray)
{
CCASSERT(!data, "Array cannot be re-initialized");
bool ret = false;
do
{
CC_BREAK_IF(! initWithCapacity(otherArray->data->num));
addObjectsFromArray(otherArray);
ret = true;
} while (0);
return ret;
}
int Array::getIndexOfObject(Object* object) const
{
return ccArrayGetIndexOfObject(data, object);
}
Object* Array::getRandomObject()
{
if (data->num == 0)
{
return nullptr;
}
float r = CCRANDOM_0_1();
if (r == 1) // to prevent from accessing data-arr[data->num], out of range.
{
r = 0;
}
return data->arr[(int)(data->num * r)];
}
bool Array::containsObject(Object* object) const
{
return ccArrayContainsObject(data, object);
}
bool Array::isEqualToArray(Array* otherArray)
{
for (int i = 0; i< this->count(); i++)
{
if (!this->getObjectAtIndex(i)->isEqual(otherArray->getObjectAtIndex(i)))
{
return false;
}
}
return true;
}
void Array::addObject(Object* object)
{
CCASSERT(data, "Array not initialized");
ccArrayAppendObjectWithResize(data, object);
}
void Array::addObjectsFromArray(Array* otherArray)
{
CCASSERT(data, "Array not initialized");
ccArrayAppendArrayWithResize(data, otherArray->data);
}
void Array::insertObject(Object* object, int index)
{
CCASSERT(data, "Array not initialized");
ccArrayInsertObjectAtIndex(data, object, index);
}
void Array::setObject(Object* object, int index)
{
CCASSERT(index>=0 && index < count(), "Invalid index");
if (object != data->arr[index])
{
data->arr[index]->release();
data->arr[index] = object;
object->retain();
}
}
void Array::removeLastObject(bool releaseObj)
{
CCASSERT(data->num, "no objects added");
ccArrayRemoveObjectAtIndex(data, data->num-1, releaseObj);
}
void Array::removeObject(Object* object, bool releaseObj/* = true*/)
{
ccArrayRemoveObject(data, object, releaseObj);
}
void Array::removeObjectAtIndex(int index, bool releaseObj)
{
ccArrayRemoveObjectAtIndex(data, index, releaseObj);
}
void Array::removeObjectsInArray(Array* otherArray)
{
ccArrayRemoveArray(data, otherArray->data);
}
void Array::removeAllObjects()
{
ccArrayRemoveAllObjects(data);
}
void Array::fastRemoveObjectAtIndex(int index)
{
ccArrayFastRemoveObjectAtIndex(data, index);
}
void Array::fastRemoveObject(Object* object)
{
ccArrayFastRemoveObject(data, object);
}
void Array::exchangeObject(Object* object1, Object* object2)
{
int index1 = ccArrayGetIndexOfObject(data, object1);
if (index1 == UINT_MAX)
{
return;
}
int index2 = ccArrayGetIndexOfObject(data, object2);
if (index2 == UINT_MAX)
{
return;
}
ccArraySwapObjectsAtIndexes(data, index1, index2);
}
void Array::exchangeObjectAtIndex(int index1, int index2)
{
ccArraySwapObjectsAtIndexes(data, index1, index2);
}
void Array::replaceObjectAtIndex(int index, Object* object, bool releaseObject/* = true*/)
{
ccArrayInsertObjectAtIndex(data, object, index);
ccArrayRemoveObjectAtIndex(data, index+1);
}
void Array::reverseObjects()
{
if (data->num > 1)
{
// floorf(), since in the case of an even number, the number of swaps stays the same
int count = (int) floorf(data->num/2.f);
int maxIndex = data->num - 1;
for (int i = 0; i < count ; i++)
{
ccArraySwapObjectsAtIndexes(data, i, maxIndex);
--maxIndex;
}
}
}
void Array::reduceMemoryFootprint()
{
ccArrayShrink(data);
}
Array::~Array()
{
CCLOGINFO("deallocing Array: %p - len: %d", this, count() );
ccArrayFree(data);
}
Array* Array::clone() const
{
Array* ret = new Array();
ret->autorelease();
ret->initWithCapacity(this->data->num > 0 ? this->data->num : 1);
Object* obj = nullptr;
Object* tmpObj = nullptr;
Clonable* clonable = nullptr;
CCARRAY_FOREACH(this, obj)
{
clonable = dynamic_cast<Clonable*>(obj);
if (clonable)
{
tmpObj = dynamic_cast<Object*>(clonable->clone());
if (tmpObj)
{
ret->addObject(tmpObj);
}
}
else
{
CCLOGWARN("%s isn't clonable.", typeid(*obj).name());
}
}
return ret;
}
void Array::acceptVisitor(DataVisitor &visitor)
{
visitor.visit(this);
}
#endif // uses ccArray
NS_CC_END NS_CC_END

View File

@ -25,7 +25,103 @@ THE SOFTWARE.
#ifndef __CCARRAY_H__ #ifndef __CCARRAY_H__
#define __CCARRAY_H__ #define __CCARRAY_H__
#define CC_USE_ARRAY_VECTOR 0
#if CC_USE_ARRAY_VECTOR
#include <vector>
#include <algorithm>
#include "cocoa/CCObject.h"
#include "ccMacros.h"
#else
#include "support/data_support/ccCArray.h" #include "support/data_support/ccCArray.h"
#endif
#if CC_USE_ARRAY_VECTOR
/**
* A reference counting-managed pointer for classes derived from RCBase which can
* be used as C pointer
* Original code: http://www.codeproject.com/Articles/64111/Building-a-Quick-and-Handy-Reference-Counting-Clas
* License: http://www.codeproject.com/info/cpol10.aspx
*/
template < class T >
class RCPtr
{
public:
//Construct using a C pointer
//e.g. RCPtr< T > x = new T();
RCPtr(T* ptr = nullptr)
: _ptr(ptr)
{
if(ptr != nullptr) {ptr->retain();}
}
//Copy constructor
RCPtr(const RCPtr &ptr)
: _ptr(ptr._ptr)
{
// printf("Array: copy constructor: %p\n", this);
if(_ptr != NULL) {_ptr->retain();}
}
//Move constructor
RCPtr(RCPtr &&ptr)
: _ptr(ptr._ptr)
{
// printf("Array: Move Constructor: %p\n", this);
ptr._ptr = nullptr;
}
~RCPtr()
{
// printf("Array: Destructor: %p\n", this);
if(_ptr != nullptr) {_ptr->release();}
}
//Assign a pointer
//e.g. x = new T();
RCPtr &operator=(T* ptr)
{
// printf("Array: operator= T*: %p\n", this);
//The following grab and release operations have to be performed
//in that order to handle the case where ptr == _ptr
//(See comment below by David Garlisch)
if(ptr != nullptr) {ptr->retain();}
if(_ptr != nullptr) {_ptr->release();}
_ptr = ptr;
return (*this);
}
//Assign another RCPtr
RCPtr &operator=(const RCPtr &ptr)
{
// printf("Array: operator= const&: %p\n", this);
return (*this) = ptr._ptr;
}
//Retrieve actual pointer
T* get() const
{
return _ptr;
}
//Some overloaded operators to facilitate dealing with an RCPtr
//as a conventional C pointer.
//Without these operators, one can still use the less transparent
//get() method to access the pointer.
T* operator->() const {return _ptr;} //x->member
T &operator*() const {return *_ptr;} //*x, (*x).member
explicit operator T*() const {return _ptr;} //T* y = x;
explicit operator bool() const {return _ptr != nullptr;} //if(x) {/*x is not NULL*/}
bool operator==(const RCPtr &ptr) {return _ptr == ptr._ptr;}
bool operator==(const T *ptr) {return _ptr == ptr;}
private:
T *_ptr; //Actual pointer
};
#endif // CC_USE_ARRAY_VECTOR
/** /**
* @addtogroup data_structures * @addtogroup data_structures
@ -48,6 +144,26 @@ __arr__++)
I found that it's not work in C++. So it keep what it's look like in version 1.0.0-rc3. ---By Bin I found that it's not work in C++. So it keep what it's look like in version 1.0.0-rc3. ---By Bin
*/ */
#if CC_USE_ARRAY_VECTOR
#define CCARRAY_FOREACH(__array__, __object__) \
if (__array__) \
for( auto __it__ = (__array__)->data.begin(); \
__it__ != (__array__)->data.end() && ((__object__) = __it__->get()) != nullptr; \
++__it__)
#define CCARRAY_FOREACH_REVERSE(__array__, __object__) \
if (__array__) \
for( auto __it__ = (__array__)->data.rbegin(); \
__it__ != (__array__)->data.rend() && ((__object__) = __it__->get()) != nullptr; \
++__it__ )
#define CCARRAY_VERIFY_TYPE(__array__, __type__) void(0)
#else // ! CC_USE_ARRAY_VECTOR --------------------------
#define CCARRAY_FOREACH(__array__, __object__) \ #define CCARRAY_FOREACH(__array__, __object__) \
if ((__array__) && (__array__)->data->num > 0) \ if ((__array__) && (__array__)->data->num > 0) \
for(Object** __arr__ = (__array__)->data->arr, **__end__ = (__array__)->data->arr + (__array__)->data->num-1; \ for(Object** __arr__ = (__array__)->data->arr, **__end__ = (__array__)->data->arr + (__array__)->data->num-1; \
@ -72,6 +188,11 @@ I found that it's not work in C++. So it keep what it's look like in version 1.0
#define CCARRAY_VERIFY_TYPE(__array__, __type__) void(0) #define CCARRAY_VERIFY_TYPE(__array__, __type__) void(0)
#endif #endif
#endif // ! CC_USE_ARRAY_VECTOR
// Common defines -----------------------------------------------------------------------------------------------
#define arrayMakeObjectsPerformSelector(pArray, func, elementType) \ #define arrayMakeObjectsPerformSelector(pArray, func, elementType) \
do { \ do { \
if(pArray && pArray->count() > 0) \ if(pArray && pArray->count() > 0) \
@ -89,7 +210,7 @@ do { \
} \ } \
while(false) while(false)
#define arrayMakeObjectsPerformSelectorWithObject(pArray, func, pObject, elementType) \ #define arrayMakeObjectsPerformSelectorWithObject(pArray, func, object, elementType) \
do { \ do { \
if(pArray && pArray->count() > 0) \ if(pArray && pArray->count() > 0) \
{ \ { \
@ -99,7 +220,7 @@ do { \
elementType pNode = static_cast<elementType>(child); \ elementType pNode = static_cast<elementType>(child); \
if(pNode) \ if(pNode) \
{ \ { \
pNode->func(pObject); \ pNode->func(object); \
} \ } \
} \ } \
} \ } \
@ -112,17 +233,16 @@ NS_CC_BEGIN
class CC_DLL Array : public Object, public Clonable class CC_DLL Array : public Object, public Clonable
{ {
public: public:
~Array();
/** Create an array */ /** Creates an empty array. Default capacity is 10 */
static Array* create(); static Array* create();
/** Create an array with some objects */ /** Create an array with objects */
static Array* create(Object* pObject, ...) CC_REQUIRES_NULL_TERMINATION; static Array* create(Object* object, ...) CC_REQUIRES_NULL_TERMINATION;
/** Create an array with one object */ /** Create an array with one object */
static Array* createWithObject(Object* pObject); static Array* createWithObject(Object* object);
/** Create an array with capacity */ /** Create an array with a default capacity */
static Array* createWithCapacity(unsigned int capacity); static Array* createWithCapacity(int capacity);
/** Create an array with an existing array */ /** Create an array with from an existing array */
static Array* createWithArray(Array* otherArray); static Array* createWithArray(Array* otherArray);
/** /**
@brief Generate a Array pointer by file @brief Generate a Array pointer by file
@ -137,35 +257,74 @@ public:
*/ */
static Array* createWithContentsOfFileThreadSafe(const char* pFileName); static Array* createWithContentsOfFileThreadSafe(const char* pFileName);
~Array();
/** Initializes an array */ /** Initializes an array */
bool init(); bool init();
/** Initializes an array with one object */ /** Initializes an array with one object */
bool initWithObject(Object* pObject); bool initWithObject(Object* object);
/** Initializes an array with some objects */ /** Initializes an array with some objects */
bool initWithObjects(Object* pObject, ...) CC_REQUIRES_NULL_TERMINATION; bool initWithObjects(Object* object, ...) CC_REQUIRES_NULL_TERMINATION;
/** Initializes an array with capacity */ /** Initializes an array with capacity */
bool initWithCapacity(unsigned int capacity); bool initWithCapacity(int capacity);
/** Initializes an array with an existing array */ /** Initializes an array with an existing array */
bool initWithArray(Array* otherArray); bool initWithArray(Array* otherArray);
// Querying an Array // Querying an Array
/** Returns element count of the array */ /** Returns element count of the array */
unsigned int count() const; int count() const
{
#if CC_USE_ARRAY_VECTOR
return data.size();
#else
return data->num;
#endif
}
/** Returns capacity of the array */ /** Returns capacity of the array */
unsigned int capacity() const; int capacity() const
{
#if CC_USE_ARRAY_VECTOR
return data.capacity();
#else
return data->max;
#endif
}
/** Returns index of a certain object, return UINT_MAX if doesn't contain the object */ /** Returns index of a certain object, return UINT_MAX if doesn't contain the object */
unsigned int indexOfObject(Object* object) const; int getIndexOfObject(Object* object) const;
CC_DEPRECATED_ATTRIBUTE int indexOfObject(Object* object) const { return getIndexOfObject(object); }
/** Returns an element with a certain index */ /** Returns an element with a certain index */
Object* objectAtIndex(unsigned int index); Object* getObjectAtIndex(int index)
/** Returns last element */ {
Object* lastObject(); CCASSERT(index>=0 && index < count(), "index out of range in getObjectAtIndex()");
#if CC_USE_ARRAY_VECTOR
return data[index].get();
#else
return data->arr[index];
#endif
}
CC_DEPRECATED_ATTRIBUTE Object* objectAtIndex(int index) { return getObjectAtIndex(index); }
/** Returns the last element of the array */
Object* getLastObject()
{
#if CC_USE_ARRAY_VECTOR
return data.back().get();
#else
if(data->num > 0)
return data->arr[data->num-1];
return nullptr;
#endif
}
CC_DEPRECATED_ATTRIBUTE Object* lastObject() { return getLastObject(); }
/** Returns a random element */ /** Returns a random element */
Object* randomObject(); Object* getRandomObject();
CC_DEPRECATED_ATTRIBUTE Object* randomObject() { return getRandomObject(); }
/** Returns a Boolean value that indicates whether object is present in array. */ /** Returns a Boolean value that indicates whether object is present in array. */
bool containsObject(Object* object) const; bool containsObject(Object* object) const;
/** @since 1.1 */ /** @since 1.1 */
bool isEqualToArray(Array* pOtherArray); bool isEqualToArray(Array* otherArray);
// Adding Objects // Adding Objects
/** Add a certain object */ /** Add a certain object */
@ -173,16 +332,38 @@ public:
/** Add all elements of an existing array */ /** Add all elements of an existing array */
void addObjectsFromArray(Array* otherArray); void addObjectsFromArray(Array* otherArray);
/** Insert a certain object at a certain index */ /** Insert a certain object at a certain index */
void insertObject(Object* object, unsigned int index); void insertObject(Object* object, int index);
/** sets a certain object at a certain index */
void setObject(Object* object, int index);
/** sets a certain object at a certain index without retaining. Use it with caution */
void fastSetObject(Object* object, int index)
{
#if CC_USE_ARRAY_VECTOR
setObject(object, index);
#else
// no retain
data->arr[index] = object;
#endif
}
void swap( int indexOne, int indexTwo )
{
CCASSERT(indexOne >=0 && indexOne < count() && indexTwo >= 0 && indexTwo < count(), "Invalid indices");
#if CC_USE_ARRAY_VECTOR
std::swap(data[indexOne], data[indexTwo]);
#else
std::swap(data->arr[indexOne], data->arr[indexTwo]);
#endif
}
// Removing Objects // Removing Objects
/** Remove last object */ /** Remove last object */
void removeLastObject(bool bReleaseObj = true); void removeLastObject(bool releaseObj = true);
/** Remove a certain object */ /** Remove a certain object */
void removeObject(Object* object, bool bReleaseObj = true); void removeObject(Object* object, bool releaseObj = true);
/** Remove an element with a certain index */ /** Remove an element with a certain index */
void removeObjectAtIndex(unsigned int index, bool bReleaseObj = true); void removeObjectAtIndex(int index, bool releaseObj = true);
/** Remove all elements */ /** Remove all elements */
void removeObjectsInArray(Array* otherArray); void removeObjectsInArray(Array* otherArray);
/** Remove all objects */ /** Remove all objects */
@ -190,17 +371,17 @@ public:
/** Fast way to remove a certain object */ /** Fast way to remove a certain object */
void fastRemoveObject(Object* object); void fastRemoveObject(Object* object);
/** Fast way to remove an element with a certain index */ /** Fast way to remove an element with a certain index */
void fastRemoveObjectAtIndex(unsigned int index); void fastRemoveObjectAtIndex(int index);
// Rearranging Content // Rearranging Content
/** Swap two elements */ /** Swap two elements */
void exchangeObject(Object* object1, Object* object2); void exchangeObject(Object* object1, Object* object2);
/** Swap two elements with certain indexes */ /** Swap two elements with certain indexes */
void exchangeObjectAtIndex(unsigned int index1, unsigned int index2); void exchangeObjectAtIndex(int index1, int index2);
/** Replace object at index with another object. */ /** Replace object at index with another object. */
void replaceObjectAtIndex(unsigned int uIndex, Object* pObject, bool bReleaseObject = true); void replaceObjectAtIndex(int index, Object* object, bool releaseObject = true);
/** Revers the array */ /** Revers the array */
void reverseObjects(); void reverseObjects();
@ -211,10 +392,30 @@ public:
virtual void acceptVisitor(DataVisitor &visitor); virtual void acceptVisitor(DataVisitor &visitor);
virtual Array* clone() const; virtual Array* clone() const;
public: // ------------------------------------------
// Iterators
// ------------------------------------------
#if CC_USE_ARRAY_VECTOR
typedef std::vector<RCPtr<Object>>::iterator iterator;
typedef std::vector<RCPtr<Object>>::const_iterator const_iterator;
iterator begin() { return data.begin(); }
iterator end() { return data.end(); }
const_iterator cbegin() { return data.cbegin(); }
const_iterator cend() { return data.cend(); }
std::vector<RCPtr<Object>> data;
#else
Object** begin() { return &data->arr[0]; }
Object** end() { return &data->arr[data->num]; }
ccArray* data; ccArray* data;
#endif
//protected:
Array(); Array();
Array(unsigned int capacity);
}; };
// end of data_structure group // end of data_structure group

View File

@ -28,31 +28,32 @@ NS_CC_BEGIN
static PoolManager* s_pPoolManager = NULL; static PoolManager* s_pPoolManager = NULL;
AutoreleasePool::AutoreleasePool(void) AutoreleasePool::AutoreleasePool()
{ {
_managedObjectArray = new Array(); _managedObjectArray = new Array();
_managedObjectArray->init(); _managedObjectArray->initWithCapacity(150);
} }
AutoreleasePool::~AutoreleasePool(void) AutoreleasePool::~AutoreleasePool()
{ {
CCLOGINFO("deallocing AutoreleasePool: %p", this);
CC_SAFE_DELETE(_managedObjectArray); CC_SAFE_DELETE(_managedObjectArray);
} }
void AutoreleasePool::addObject(Object* pObject) void AutoreleasePool::addObject(Object* object)
{ {
_managedObjectArray->addObject(pObject); _managedObjectArray->addObject(object);
CCASSERT(pObject->_reference > 1, "reference count should be greater than 1"); CCASSERT(object->_reference > 1, "reference count should be greater than 1");
++(pObject->_autoReleaseCount); ++(object->_autoReleaseCount);
pObject->release(); // no ref count, in this case autorelease pool added. object->release(); // no ref count, in this case autorelease pool added.
} }
void AutoreleasePool::removeObject(Object* pObject) void AutoreleasePool::removeObject(Object* object)
{ {
for (unsigned int i = 0; i < pObject->_autoReleaseCount; ++i) for (unsigned int i = 0; i < object->_autoReleaseCount; ++i)
{ {
_managedObjectArray->removeObject(pObject, false); _managedObjectArray->removeObject(object, false);
} }
} }
@ -107,13 +108,13 @@ void PoolManager::purgePoolManager()
PoolManager::PoolManager() PoolManager::PoolManager()
{ {
_releasePoolStack = new Array(); _releasePoolStack = new Array();
_releasePoolStack->init(); _releasePoolStack->initWithCapacity(150);
_curReleasePool = 0; _curReleasePool = 0;
} }
PoolManager::~PoolManager() PoolManager::~PoolManager()
{ {
CCLOGINFO("deallocing PoolManager: %p", this);
finalize(); finalize();
// we only release the last autorelease pool here // we only release the last autorelease pool here
@ -160,31 +161,31 @@ void PoolManager::pop()
_curReleasePool->clear(); _curReleasePool->clear();
if(nCount > 1) if (nCount > 1)
{ {
_releasePoolStack->removeObjectAtIndex(nCount-1); _releasePoolStack->removeObjectAtIndex(nCount-1);
// if(nCount > 1) // if(nCount > 1)
// { // {
// _curReleasePool = _releasePoolStack->objectAtIndex(nCount - 2); // _curReleasePool = _releasePoolStack->getObjectAtIndex(nCount - 2);
// return; // return;
// } // }
_curReleasePool = (AutoreleasePool*)_releasePoolStack->objectAtIndex(nCount - 2); _curReleasePool = (AutoreleasePool*)_releasePoolStack->getObjectAtIndex(nCount - 2);
} }
/*_curReleasePool = NULL;*/ /*_curReleasePool = NULL;*/
} }
void PoolManager::removeObject(Object* pObject) void PoolManager::removeObject(Object* object)
{ {
CCASSERT(_curReleasePool, "current auto release pool should not be null"); CCASSERT(_curReleasePool, "current auto release pool should not be null");
_curReleasePool->removeObject(pObject); _curReleasePool->removeObject(object);
} }
void PoolManager::addObject(Object* pObject) void PoolManager::addObject(Object* object)
{ {
getCurReleasePool()->addObject(pObject); getCurReleasePool()->addObject(object);
} }

View File

@ -36,36 +36,98 @@ NS_CC_BEGIN
class CC_DLL AutoreleasePool : public Object class CC_DLL AutoreleasePool : public Object
{ {
Array* _managedObjectArray; /**
* The underlying array of object managed by the pool.
*
* Although Array retains the object once when an object is added, proper
* Object::release() is called outside the array to make sure that the pool
* does not affect the managed object's reference count. So an object can
* be destructed properly by calling Object::release() even if the object
* is in the pool.
*/
Array *_managedObjectArray;
public: public:
AutoreleasePool(void); AutoreleasePool();
~AutoreleasePool(void); ~AutoreleasePool();
void addObject(Object *pObject); /**
void removeObject(Object *pObject); * Add a given object to this pool.
*
* The same object may be added several times to the same pool; When the
* pool is destructed, the object's Object::release() method will be called
* for each time it was added.
*
* @param object The object to add to the pool.
*/
void addObject(Object *object);
/**
* Remove a given object from this pool.
*
* @param object The object to be removed from the pool.
*/
void removeObject(Object *object);
/**
* Clear the autorelease pool.
*
* Object::release() will be called for each time the managed object is
* added to the pool.
*/
void clear(); void clear();
}; };
class CC_DLL PoolManager class CC_DLL PoolManager
{ {
Array* _releasePoolStack; Array *_releasePoolStack;
AutoreleasePool* _curReleasePool; AutoreleasePool *_curReleasePool;
AutoreleasePool* getCurReleasePool(); AutoreleasePool *getCurReleasePool();
public: public:
PoolManager();
~PoolManager();
void finalize();
void push();
void pop();
void removeObject(Object* pObject);
void addObject(Object* pObject);
static PoolManager* sharedPoolManager(); static PoolManager* sharedPoolManager();
static void purgePoolManager(); static void purgePoolManager();
PoolManager();
~PoolManager();
/**
* Clear all the AutoreleasePool on the pool stack.
*/
void finalize();
/**
* Push a new AutoreleasePool to the pool stack.
*/
void push();
/**
* Pop one AutoreleasePool from the pool stack.
*
* This method will ensure that there is at least one AutoreleasePool on
* the stack.
*
* The AutoreleasePool being poped is destructed.
*/
void pop();
/**
* Remove a given object from the current autorelease pool.
*
* @param object The object to be removed.
*
* @see AutoreleasePool::removeObject
*/
void removeObject(Object *object);
/**
* Add a given object to the current autorelease pool.
*
* @param object The object to add.
*
* @see AutoreleasePool::addObject
*/
void addObject(Object *object);
friend class AutoreleasePool; friend class AutoreleasePool;
}; };

View File

@ -1,5 +1,30 @@
/****************************************************************************
Copyright (c) 2010-2012 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.
****************************************************************************/
#include <string.h> #include <string.h>
#include "CCData.h" #include "CCData.h"
#include "platform/CCCommon.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -19,6 +44,7 @@ Data::Data(Data *pData)
Data::~Data() Data::~Data()
{ {
CCLOGINFO("deallocing Data: %p", this);
CC_SAFE_DELETE_ARRAY(_bytes); CC_SAFE_DELETE_ARRAY(_bytes);
} }

View File

@ -1,3 +1,26 @@
/****************************************************************************
Copyright (c) 2010-2012 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 __CCDATA_H__ #ifndef __CCDATA_H__
#define __CCDATA_H__ #define __CCDATA_H__

View File

@ -63,7 +63,7 @@ DictElement::DictElement(intptr_t iKey, Object* pObject)
DictElement::~DictElement() DictElement::~DictElement()
{ {
CCLOGINFO("deallocing DictElement: %p", this);
} }
// ----------------------------------------------------------------------- // -----------------------------------------------------------------------
@ -78,6 +78,7 @@ Dictionary::Dictionary()
Dictionary::~Dictionary() Dictionary::~Dictionary()
{ {
CCLOGINFO("deallocing Dictionary: %p", this);
removeAllObjects(); removeAllObjects();
} }
@ -340,7 +341,7 @@ Object* Dictionary::randomObject()
return NULL; return NULL;
} }
Object* key = allKeys()->randomObject(); Object* key = allKeys()->getRandomObject();
if (_dictType == kDictInt) if (_dictType == kDictInt)
{ {
@ -358,12 +359,17 @@ Object* Dictionary::randomObject()
Dictionary* Dictionary::create() Dictionary* Dictionary::create()
{ {
Dictionary* pRet = new Dictionary(); Dictionary* ret = new Dictionary();
if (pRet != NULL) if (ret && ret->init() )
{ {
pRet->autorelease(); ret->autorelease();
} }
return pRet; return ret;
}
bool Dictionary::init()
{
return true;
} }
Dictionary* Dictionary::createWithDictionary(Dictionary* srcDict) Dictionary* Dictionary::createWithDictionary(Dictionary* srcDict)
@ -383,9 +389,7 @@ void Dictionary::acceptVisitor(DataVisitor &visitor)
Dictionary* Dictionary::createWithContentsOfFile(const char *pFileName) Dictionary* Dictionary::createWithContentsOfFile(const char *pFileName)
{ {
Dictionary* pRet = createWithContentsOfFileThreadSafe(pFileName); return createWithContentsOfFileThreadSafe(pFileName);
pRet->autorelease();
return pRet;
} }
bool Dictionary::writeToFile(const char *fullPath) bool Dictionary::writeToFile(const char *fullPath)
@ -395,8 +399,7 @@ bool Dictionary::writeToFile(const char *fullPath)
Dictionary* Dictionary::clone() const Dictionary* Dictionary::clone() const
{ {
Dictionary* newDict = new Dictionary(); Dictionary* newDict = Dictionary::create();
newDict->autorelease();
DictElement* element = NULL; DictElement* element = NULL;
Object* tmpObj = NULL; Object* tmpObj = NULL;

View File

@ -182,6 +182,8 @@ public:
*/ */
~Dictionary(); ~Dictionary();
/** Initializes the dictionary. It returns true if the initializations was successful. */
bool init();
/** /**
* Get the count of elements in Dictionary. * Get the count of elements in Dictionary.
* *

View File

@ -116,6 +116,42 @@ Point Point::rotateByAngle(const Point& pivot, float angle) const
return pivot + (*this - pivot).rotate(Point::forAngle(angle)); return pivot + (*this - pivot).rotate(Point::forAngle(angle));
} }
bool Point::isOneDemensionSegmentOverlap(float A, float B, float C, float D, float *S, float *E)
{
float ABmin = MIN(A, B);
float ABmax = MAX(A, B);
float CDmin = MIN(C, D);
float CDmax = MAX(C, D);
if (ABmax < CDmin || CDmax < ABmin)
{
// ABmin->ABmax->CDmin->CDmax or CDmin->CDmax->ABmin->ABmax
return false;
}
else
{
if (ABmin >= CDmin && ABmin <= CDmax)
{
// CDmin->ABmin->CDmax->ABmax or CDmin->ABmin->ABmax->CDmax
if (S != nullptr) *S = ABmin;
if (E != nullptr) *E = CDmax < ABmax ? CDmax : ABmax;
}
else if (ABmax >= CDmin && ABmax <= CDmax)
{
// ABmin->CDmin->ABmax->CDmax
if (S != nullptr) *S = CDmin;
if (E != nullptr) *E = ABmax;
}
else
{
// ABmin->CDmin->CDmax->ABmax
if (S != nullptr) *S = CDmin;
if (E != nullptr) *E = CDmax;
}
return true;
}
}
bool Point::isLineIntersect(const Point& A, const Point& B, bool Point::isLineIntersect(const Point& A, const Point& B,
const Point& C, const Point& D, const Point& C, const Point& D,
float *S, float *T) float *S, float *T)
@ -125,40 +161,74 @@ bool Point::isLineIntersect(const Point& A, const Point& B,
{ {
return false; return false;
} }
const float BAx = B.x - A.x;
const float BAy = B.y - A.y;
const float DCx = D.x - C.x;
const float DCy = D.y - C.y;
const float ACx = A.x - C.x;
const float ACy = A.y - C.y;
const float denom = DCy*BAx - DCx*BAy; const float denom = crossProduct2Vector(A, B, C, D);
*S = DCx*ACy - DCy*ACx;
*T = BAx*ACy - BAy*ACx;
if (denom == 0) if (denom == 0)
{ {
if (*S == 0 || *T == 0) // Lines parallel or overlap
{
// Lines incident
return true;
}
// Lines parallel and not incident
return false; return false;
} }
*S = *S / denom; if (S != nullptr) *S = crossProduct2Vector(C, D, C, A) / denom;
*T = *T / denom; if (T != nullptr) *T = crossProduct2Vector(A, B, C, A) / denom;
// Point of intersection
// CGPoint P;
// P.x = A.x + *S * (B.x - A.x);
// P.y = A.y + *S * (B.y - A.y);
return true; return true;
} }
bool Point::isLineParallel(const Point& A, const Point& B,
const Point& C, const Point& D)
{
// FAIL: Line undefined
if ( (A.x==B.x && A.y==B.y) || (C.x==D.x && C.y==D.y) )
{
return false;
}
if (crossProduct2Vector(A, B, C, D) == 0)
{
// line overlap
if (crossProduct2Vector(C, D, C, A) == 0 || crossProduct2Vector(A, B, C, A) == 0)
{
return false;
}
return true;
}
return false;
}
bool Point::isLineOverlap(const Point& A, const Point& B,
const Point& C, const Point& D)
{
// FAIL: Line undefined
if ( (A.x==B.x && A.y==B.y) || (C.x==D.x && C.y==D.y) )
{
return false;
}
if (crossProduct2Vector(A, B, C, D) == 0 &&
(crossProduct2Vector(C, D, C, A) == 0 || crossProduct2Vector(A, B, C, A) == 0))
{
return true;
}
return false;
}
bool Point::isSegmentOverlap(const Point& A, const Point& B, const Point& C, const Point& D, Point* S, Point* E)
{
if (isLineOverlap(A, B, C, D))
{
return isOneDemensionSegmentOverlap(A.x, B.x, C.x, D.x, &S->x, &E->x) &&
isOneDemensionSegmentOverlap(A.y, B.y, C.y, D.y, &S->y, &E->y);
}
return false;
}
bool Point::isSegmentIntersect(const Point& A, const Point& B, const Point& C, const Point& D) bool Point::isSegmentIntersect(const Point& A, const Point& B, const Point& C, const Point& D)
{ {
float S, T; float S, T;

View File

@ -262,7 +262,29 @@ public:
*/ */
static bool isLineIntersect(const Point& A, const Point& B, static bool isLineIntersect(const Point& A, const Point& B,
const Point& C, const Point& D, const Point& C, const Point& D,
float *S, float *T); float *S = nullptr, float *T = nullptr);
/*
returns true if Line A-B overlap with segment C-D
@since v3.0
*/
static bool isLineOverlap(const Point& A, const Point& B,
const Point& C, const Point& D);
/*
returns true if Line A-B parallel with segment C-D
@since v3.0
*/
static bool isLineParallel(const Point& A, const Point& B,
const Point& C, const Point& D);
/*
returns true if Segment A-B overlap with segment C-D
@since v3.0
*/
static bool isSegmentOverlap(const Point& A, const Point& B,
const Point& C, const Point& D,
Point* S = nullptr, Point* E = nullptr);
/* /*
returns true if Segment A-B intersects with segment C-D returns true if Segment A-B intersects with segment C-D
@ -277,6 +299,13 @@ public:
static Point getIntersectPoint(const Point& A, const Point& B, const Point& C, const Point& D); static Point getIntersectPoint(const Point& A, const Point& B, const Point& C, const Point& D);
static const Point ZERO; static const Point ZERO;
private:
// returns true if segment A-B intersects with segment C-D. S->E is the ovderlap part
static bool isOneDemensionSegmentOverlap(float A, float B, float C, float D, float *S, float * E);
// cross procuct of 2 vector. A->B X C->D
static float crossProduct2Vector(const Point& A, const Point& B, const Point& C, const Point& D) { return (D.y - C.y) * (B.x - A.x) - (D.x - C.x) * (B.y - A.y); }
}; };
class CC_DLL Size class CC_DLL Size

View File

@ -1,7 +1,32 @@
/****************************************************************************
Copyright (c) 2010-2012 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 __CCINTEGER_H__ #ifndef __CCINTEGER_H__
#define __CCINTEGER_H__ #define __CCINTEGER_H__
#include "CCObject.h" #include "CCObject.h"
#include "platform/CCCommon.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -13,10 +38,6 @@ NS_CC_BEGIN
class CC_DLL Integer : public Object, public Clonable class CC_DLL Integer : public Object, public Clonable
{ {
public: public:
Integer(int v)
: _value(v) {}
int getValue() const {return _value;}
static Integer* create(int v) static Integer* create(int v)
{ {
Integer* pRet = new Integer(v); Integer* pRet = new Integer(v);
@ -24,10 +45,19 @@ public:
return pRet; return pRet;
} }
Integer(int v)
: _value(v) {}
int getValue() const {return _value;}
virtual ~Integer() {
CCLOGINFO("deallocing ~Integer: %p", this);
}
/* override functions */ /* override functions */
virtual void acceptVisitor(DataVisitor &visitor) { visitor.visit(this); } virtual void acceptVisitor(DataVisitor &visitor) { visitor.visit(this); }
Integer* clone() const // overrides
virtual Integer* clone() const override
{ {
return Integer::create(_value); return Integer::create(_value);
} }

View File

@ -30,7 +30,7 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
Object::Object(void) Object::Object()
: _luaID(0) : _luaID(0)
, _reference(1) // when the object is created, the reference count of it is 1 , _reference(1) // when the object is created, the reference count of it is 1
, _autoReleaseCount(0) , _autoReleaseCount(0)
@ -40,7 +40,7 @@ Object::Object(void)
_ID = ++uObjectCount; _ID = ++uObjectCount;
} }
Object::~Object(void) Object::~Object()
{ {
// if the object is managed, we should remove it // if the object is managed, we should remove it
// from pool manager // from pool manager
@ -64,43 +64,25 @@ Object::~Object(void)
} }
} }
void Object::release(void) Object* Object::autorelease()
{
CCASSERT(_reference > 0, "reference count should greater than 0");
--_reference;
if (_reference == 0)
{
delete this;
}
}
void Object::retain(void)
{
CCASSERT(_reference > 0, "reference count should greater than 0");
++_reference;
}
Object* Object::autorelease(void)
{ {
PoolManager::sharedPoolManager()->addObject(this); PoolManager::sharedPoolManager()->addObject(this);
return this; return this;
} }
bool Object::isSingleReference(void) const bool Object::isSingleReference() const
{ {
return _reference == 1; return _reference == 1;
} }
unsigned int Object::retainCount(void) const unsigned int Object::retainCount() const
{ {
return _reference; return _reference;
} }
bool Object::isEqual(const Object *pObject) bool Object::isEqual(const Object *object)
{ {
return this == pObject; return this == object;
} }
void Object::acceptVisitor(DataVisitor &visitor) void Object::acceptVisitor(DataVisitor &visitor)

View File

@ -26,6 +26,7 @@ THE SOFTWARE.
#define __CCOBJECT_H__ #define __CCOBJECT_H__
#include "cocoa/CCDataVisitor.h" #include "cocoa/CCDataVisitor.h"
#include "ccMacros.h"
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
#include <GLES2/gl2.h> #include <GLES2/gl2.h>
@ -64,25 +65,96 @@ public:
class CC_DLL Object class CC_DLL Object
{ {
public: public:
// object id, ScriptSupport need public _ID /// object id, ScriptSupport need public _ID
unsigned int _ID; unsigned int _ID;
// Lua reference id /// Lua reference id
int _luaID; int _luaID;
protected: protected:
// count of references /// count of references
unsigned int _reference; unsigned int _reference;
// count of autorelease /// count of autorelease
unsigned int _autoReleaseCount; unsigned int _autoReleaseCount;
public: public:
Object(void); /**
virtual ~Object(void); * Constructor
*
* The object's reference count is 1 after construction.
*/
Object();
void release(void); virtual ~Object();
void retain(void);
Object* autorelease(void); /**
bool isSingleReference(void) const; * Release the ownership immediately.
unsigned int retainCount(void) const; *
virtual bool isEqual(const Object* pObject); * This decrements the object's reference count.
*
* If the reference count reaches 0 after the descrement, this object is
* destructed.
*
* @see retain, autorelease
*/
inline void release()
{
CCASSERT(_reference > 0, "reference count should greater than 0");
--_reference;
if (_reference == 0)
delete this;
}
/**
* Retains the ownership.
*
* This increases the object's reference count.
*
* @see release, autorelease
*/
inline void retain()
{
CCASSERT(_reference > 0, "reference count should greater than 0");
++_reference;
}
/**
* Release the ownership sometime soon automatically.
*
* This descrements the object's reference count at the end of current
* autorelease pool block.
*
* If the reference count reaches 0 after the descrement, this object is
* destructed.
*
* @returns The object itself.
*
* @see AutoreleasePool, retain, release
*/
Object* autorelease();
/**
* Returns a boolean value that indicates whether there is only one
* reference to the object. That is, whether the reference count is 1.
*
* @returns Whether the object's reference count is 1.
*/
bool isSingleReference() const;
/**
* Returns the object's current reference count.
*
* @returns The object's reference count.
*/
unsigned int retainCount() const;
/**
* Returns a boolean value that indicates whether this object and a given
* object are equal.
*
* @param object The object to be compared to this object.
*
* @returns True if this object and @p object are equal, otherwise false.
*/
virtual bool isEqual(const Object* object);
virtual void acceptVisitor(DataVisitor &visitor); virtual void acceptVisitor(DataVisitor &visitor);

View File

@ -1,3 +1,27 @@
/****************************************************************************
Copyright (c) 2010-2012 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.
****************************************************************************/
#include "CCString.h" #include "CCString.h"
#include "platform/CCFileUtils.h" #include "platform/CCFileUtils.h"
#include "ccMacros.h" #include "ccMacros.h"
@ -27,6 +51,8 @@ String::String(const String& str)
String::~String() String::~String()
{ {
CCLOGINFO("deallocing String: %p", this);
_string.clear(); _string.clear();
} }

View File

@ -93,7 +93,7 @@ void Grabber::afterRender(cocos2d::Texture2D *texture)
Grabber::~Grabber() Grabber::~Grabber()
{ {
CCLOGINFO("cocos2d: deallocing %p", this); CCLOGINFO("deallocing Grabber: %p", this);
glDeleteFramebuffers(1, &_FBO); glDeleteFramebuffers(1, &_FBO);
} }

View File

@ -148,7 +148,7 @@ bool GridBase::initWithSize(const Size& gridSize)
GridBase::~GridBase(void) GridBase::~GridBase(void)
{ {
CCLOGINFO("cocos2d: deallocing %p", this); CCLOGINFO("deallocing GridBase: %p", this);
//TODO: ? why 2.0 comments this line setActive(false); //TODO: ? why 2.0 comments this line setActive(false);
CC_SAFE_RELEASE(_texture); CC_SAFE_RELEASE(_texture);

View File

@ -1,57 +0,0 @@
/****************************************************************************
Copyright (c) 2012 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 cocos2dx_ccTypeInfo_h
#define cocos2dx_ccTypeInfo_h
#include "platform/CCPlatformMacros.h"
#include <typeinfo>
#include <ctype.h>
#include <string.h>
NS_CC_BEGIN
class TypeInfo
{
public:
virtual long getClassTypeInfo() = 0;
};
static inline unsigned int getHashCodeByString(const char *key)
{
size_t len = strlen(key);
const char *end=key+len;
unsigned int hash;
for (hash = 0; key < end; key++)
{
hash *= 16777619;
hash ^= (unsigned int) (unsigned char) toupper(*key);
}
return (hash);
}
NS_CC_END
#endif

View File

@ -92,6 +92,16 @@ struct Color4B
GLubyte g; GLubyte g;
GLubyte b; GLubyte b;
GLubyte a; GLubyte a;
const static Color4B WHITE;
const static Color4B YELLOW;
const static Color4B BLUE;
const static Color4B GREEN;
const static Color4B RED;
const static Color4B MAGENTA;
const static Color4B BLACK;
const static Color4B ORANGE;
const static Color4B GRAY;
}; };
@ -135,6 +145,16 @@ struct Color4F
GLfloat g; GLfloat g;
GLfloat b; GLfloat b;
GLfloat a; GLfloat a;
const static Color4F WHITE;
const static Color4F YELLOW;
const static Color4F BLUE;
const static Color4F GREEN;
const static Color4F RED;
const static Color4F MAGENTA;
const static Color4F BLACK;
const static Color4F ORANGE;
const static Color4F GRAY;
}; };
/** A vertex composed of 2 floats: x, y /** A vertex composed of 2 floats: x, y

View File

@ -31,13 +31,13 @@ NS_CC_BEGIN
Label* Label::createWithTTF( const char* label, const char* fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs ) Label* Label::createWithTTF( const char* label, const char* fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs )
{ {
FontAtlas *tempAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath, fontSize, glyphs, customGlyphs); FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath, fontSize, glyphs, customGlyphs);
if (!tempAtlas) if (!tmpAtlas)
return nullptr; return nullptr;
// create the actual label // create the actual label
Label* templabel = Label::createWithAtlas(tempAtlas, alignment, lineSize); Label* templabel = Label::createWithAtlas(tmpAtlas, alignment, lineSize);
if (templabel) if (templabel)
{ {
@ -53,12 +53,12 @@ Label* Label::createWithTTF( const char* label, const char* fontFilePath, int fo
Label* Label::createWithBMFont( const char* label, const char* bmfontFilePath, TextHAlignment alignment, int lineSize) Label* Label::createWithBMFont( const char* label, const char* bmfontFilePath, TextHAlignment alignment, int lineSize)
{ {
FontAtlas *tempAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath); FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath);
if (!tempAtlas) if (!tmpAtlas)
return 0; return 0;
Label* templabel = Label::createWithAtlas(tempAtlas, alignment, lineSize); Label* templabel = Label::createWithAtlas(tmpAtlas, alignment, lineSize);
if (templabel) if (templabel)
{ {
@ -73,9 +73,9 @@ Label* Label::createWithBMFont( const char* label, const char* bmfontFilePath, T
return 0; return 0;
} }
Label* Label::createWithAtlas(FontAtlas *pAtlas, TextHAlignment alignment, int lineSize) Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int lineSize)
{ {
Label *ret = new Label(pAtlas, alignment); Label *ret = new Label(atlas, alignment);
if (!ret) if (!ret)
return 0; return 0;
@ -94,24 +94,28 @@ Label* Label::createWithAtlas(FontAtlas *pAtlas, TextHAlignment alignment, int l
return ret; return ret;
} }
Label::Label(FontAtlas *pAtlas, TextHAlignment alignment): _currentUTF8String(0), Label::Label(FontAtlas *atlas, TextHAlignment alignment)
_originalUTF8String(0), : _currentUTF8String(0)
_fontAtlas(pAtlas), , _originalUTF8String(0)
_alignment(alignment), , _fontAtlas(atlas)
_lineBreakWithoutSpaces(false), , _alignment(alignment)
_advances(0), , _lineBreakWithoutSpaces(false)
_displayedColor(Color3B::WHITE), , _advances(0)
_realColor(Color3B::WHITE), , _displayedColor(Color3B::WHITE)
_cascadeColorEnabled(true), , _realColor(Color3B::WHITE)
_cascadeOpacityEnabled(true), , _cascadeColorEnabled(true)
_displayedOpacity(255), , _cascadeOpacityEnabled(true)
_realOpacity(255), , _displayedOpacity(255)
_isOpacityModifyRGB(false) , _realOpacity(255)
, _isOpacityModifyRGB(false)
{ {
} }
Label::~Label() Label::~Label()
{ {
CC_SAFE_RELEASE(_spriteArray);
CC_SAFE_RELEASE(_spriteArrayCache);
if (_currentUTF8String) if (_currentUTF8String)
delete [] _currentUTF8String; delete [] _currentUTF8String;
@ -124,6 +128,12 @@ Label::~Label()
bool Label::init() bool Label::init()
{ {
_spriteArray = Array::createWithCapacity(30);
_spriteArrayCache = Array::createWithCapacity(30);
_spriteArray->retain();
_spriteArrayCache->retain();
return true; return true;
} }
@ -253,12 +263,12 @@ void Label::alignText()
void Label::hideAllLetters() void Label::hideAllLetters()
{ {
Object* Obj = NULL; Object* Obj = NULL;
CCARRAY_FOREACH(&_spriteArray, Obj) CCARRAY_FOREACH(_spriteArray, Obj)
{ {
((Sprite *)Obj)->setVisible(false); ((Sprite *)Obj)->setVisible(false);
} }
CCARRAY_FOREACH(&_spriteArrayCache, Obj) CCARRAY_FOREACH(_spriteArrayCache, Obj)
{ {
((Sprite *)Obj)->setVisible(false); ((Sprite *)Obj)->setVisible(false);
} }
@ -431,21 +441,21 @@ Sprite * Label::updateSpriteForLetter(Sprite *spriteToUpdate, unsigned short int
void Label::moveAllSpritesToCache() void Label::moveAllSpritesToCache()
{ {
Object* pObj = NULL; Object* pObj = NULL;
CCARRAY_FOREACH(&_spriteArray, pObj) CCARRAY_FOREACH(_spriteArray, pObj)
{ {
((Sprite *)pObj)->removeFromParent(); ((Sprite *)pObj)->removeFromParent();
_spriteArrayCache.addObject(pObj); _spriteArrayCache->addObject(pObj);
} }
_spriteArray.removeAllObjects(); _spriteArray->removeAllObjects();
} }
Sprite * Label::getSprite() Sprite * Label::getSprite()
{ {
if (_spriteArrayCache.count()) if (_spriteArrayCache->count())
{ {
Sprite *retSprite = (Sprite *) _spriteArrayCache.lastObject(); Sprite *retSprite = static_cast<Sprite *>( _spriteArrayCache->getLastObject() );
_spriteArrayCache.removeLastObject(); _spriteArrayCache->removeLastObject();
return retSprite; return retSprite;
} }
else else
@ -460,7 +470,7 @@ Sprite * Label::getSprite()
Sprite * Label::getSpriteChild(int ID) Sprite * Label::getSpriteChild(int ID)
{ {
Object* pObj = NULL; Object* pObj = NULL;
CCARRAY_FOREACH(&_spriteArray, pObj) CCARRAY_FOREACH(_spriteArray, pObj)
{ {
Sprite *pSprite = (Sprite *)pObj; Sprite *pSprite = (Sprite *)pObj;
if ( pSprite->getTag() == ID) if ( pSprite->getTag() == ID)
@ -471,9 +481,9 @@ Sprite * Label::getSpriteChild(int ID)
return 0; return 0;
} }
Array * Label::getChildrenLetters() Array* Label::getChildrenLetters()
{ {
return &_spriteArray; return _spriteArray;
} }
Sprite * Label::getSpriteForChar(unsigned short int theChar, int spriteIndexHint) Sprite * Label::getSpriteForChar(unsigned short int theChar, int spriteIndexHint)
@ -493,7 +503,7 @@ Sprite * Label::getSpriteForChar(unsigned short int theChar, int spriteIndexHint
if (retSprite) if (retSprite)
retSprite->setTag(spriteIndexHint); retSprite->setTag(spriteIndexHint);
_spriteArray.addObject(retSprite); _spriteArray->addObject(retSprite);
} }
// the sprite is now visible // the sprite is now visible

View File

@ -139,8 +139,8 @@ private:
Sprite * getSpriteForLetter(unsigned short int newLetter); Sprite * getSpriteForLetter(unsigned short int newLetter);
Sprite * updateSpriteForLetter(Sprite *spriteToUpdate, unsigned short int newLetter); Sprite * updateSpriteForLetter(Sprite *spriteToUpdate, unsigned short int newLetter);
Array _spriteArray; Array * _spriteArray;
Array _spriteArrayCache; Array * _spriteArrayCache;
float _commonLineHeight; float _commonLineHeight;
bool _lineBreakWithoutSpaces; bool _lineBreakWithoutSpaces;
float _width; float _width;

View File

@ -69,6 +69,7 @@ CCBMFontConfiguration* FNTConfigLoadFile( const char *fntFile)
if( s_pConfigurations == NULL ) if( s_pConfigurations == NULL )
{ {
s_pConfigurations = new Dictionary(); s_pConfigurations = new Dictionary();
s_pConfigurations->init();
} }
pRet = static_cast<CCBMFontConfiguration*>( s_pConfigurations->objectForKey(fntFile) ); pRet = static_cast<CCBMFontConfiguration*>( s_pConfigurations->objectForKey(fntFile) );
@ -140,7 +141,7 @@ CCBMFontConfiguration::CCBMFontConfiguration()
CCBMFontConfiguration::~CCBMFontConfiguration() CCBMFontConfiguration::~CCBMFontConfiguration()
{ {
CCLOGINFO( "cocos2d: deallocing CCBMFontConfiguration %p", this ); CCLOGINFO( "deallocing CCBMFontConfiguration: %p", this );
this->purgeFontDefDictionary(); this->purgeFontDefDictionary();
this->purgeKerningDictionary(); this->purgeKerningDictionary();
_atlasName.clear(); _atlasName.clear();

View File

@ -68,8 +68,8 @@ bool Layer::init()
Director * pDirector; Director * pDirector;
CC_BREAK_IF(!(pDirector = Director::getInstance())); CC_BREAK_IF(!(pDirector = Director::getInstance()));
this->setContentSize(pDirector->getWinSize()); this->setContentSize(pDirector->getWinSize());
_touchEnabled = false; setTouchEnabled(false);
_accelerometerEnabled = false; setAccelerometerEnabled(false);
// success // success
bRet = true; bRet = true;
} while(0); } while(0);
@ -1073,6 +1073,19 @@ void LayerMultiplex::addLayer(Layer* layer)
_layers->addObject(layer); _layers->addObject(layer);
} }
bool LayerMultiplex::init()
{
if (Layer::init())
{
_layers = Array::create();
_layers->retain();
_enabledLayer = 0;
return true;
}
return false;
}
bool LayerMultiplex::initWithLayers(Layer *layer, va_list params) bool LayerMultiplex::initWithLayers(Layer *layer, va_list params)
{ {
if (Layer::init()) if (Layer::init())
@ -1088,7 +1101,7 @@ bool LayerMultiplex::initWithLayers(Layer *layer, va_list params)
} }
_enabledLayer = 0; _enabledLayer = 0;
this->addChild((Node*)_layers->objectAtIndex(_enabledLayer)); this->addChild((Node*)_layers->getObjectAtIndex(_enabledLayer));
return true; return true;
} }
@ -1104,7 +1117,7 @@ bool LayerMultiplex::initWithArray(Array* arrayOfLayers)
_layers->retain(); _layers->retain();
_enabledLayer = 0; _enabledLayer = 0;
this->addChild((Node*)_layers->objectAtIndex(_enabledLayer)); this->addChild((Node*)_layers->getObjectAtIndex(_enabledLayer));
return true; return true;
} }
return false; return false;
@ -1114,25 +1127,25 @@ void LayerMultiplex::switchTo(unsigned int n)
{ {
CCASSERT( n < _layers->count(), "Invalid index in MultiplexLayer switchTo message" ); CCASSERT( n < _layers->count(), "Invalid index in MultiplexLayer switchTo message" );
this->removeChild((Node*)_layers->objectAtIndex(_enabledLayer), true); this->removeChild((Node*)_layers->getObjectAtIndex(_enabledLayer), true);
_enabledLayer = n; _enabledLayer = n;
this->addChild((Node*)_layers->objectAtIndex(n)); this->addChild((Node*)_layers->getObjectAtIndex(n));
} }
void LayerMultiplex::switchToAndReleaseMe(unsigned int n) void LayerMultiplex::switchToAndReleaseMe(unsigned int n)
{ {
CCASSERT( n < _layers->count(), "Invalid index in MultiplexLayer switchTo message" ); CCASSERT( n < _layers->count(), "Invalid index in MultiplexLayer switchTo message" );
this->removeChild((Node*)_layers->objectAtIndex(_enabledLayer), true); this->removeChild((Node*)_layers->getObjectAtIndex(_enabledLayer), true);
//[layers replaceObjectAtIndex:enabledLayer withObject:[NSNull null]]; //[layers replaceObjectAtIndex:enabledLayer withObject:[NSNull null]];
_layers->replaceObjectAtIndex(_enabledLayer, NULL); _layers->replaceObjectAtIndex(_enabledLayer, NULL);
_enabledLayer = n; _enabledLayer = n;
this->addChild((Node*)_layers->objectAtIndex(n)); this->addChild((Node*)_layers->getObjectAtIndex(n));
} }
NS_CC_END NS_CC_END

View File

@ -374,6 +374,7 @@ public:
LayerMultiplex(); LayerMultiplex();
virtual ~LayerMultiplex(); virtual ~LayerMultiplex();
virtual bool init();
/** initializes a MultiplexLayer with one or more layers using a variable argument list. */ /** initializes a MultiplexLayer with one or more layers using a variable argument list. */
bool initWithLayers(Layer* layer, va_list params); bool initWithLayers(Layer* layer, va_list params);

View File

@ -808,7 +808,7 @@ MenuItemToggle * MenuItemToggle::createWithTarget(Object* target, SEL_MenuHandle
for (unsigned int z=0; z < menuItems->count(); z++) for (unsigned int z=0; z < menuItems->count(); z++)
{ {
MenuItem* menuItem = (MenuItem*)menuItems->objectAtIndex(z); MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z);
pRet->_subItems->addObject(menuItem); pRet->_subItems->addObject(menuItem);
} }
@ -826,7 +826,7 @@ MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callba
for (unsigned int z=0; z < menuItems->count(); z++) for (unsigned int z=0; z < menuItems->count(); z++)
{ {
MenuItem* menuItem = (MenuItem*)menuItems->objectAtIndex(z); MenuItem* menuItem = (MenuItem*)menuItems->getObjectAtIndex(z);
pRet->_subItems->addObject(menuItem); pRet->_subItems->addObject(menuItem);
} }
@ -939,7 +939,7 @@ void MenuItemToggle::setSelectedIndex(unsigned int index)
currentItem->removeFromParentAndCleanup(false); currentItem->removeFromParentAndCleanup(false);
} }
MenuItem* item = (MenuItem*)_subItems->objectAtIndex(_selectedIndex); MenuItem* item = (MenuItem*)_subItems->getObjectAtIndex(_selectedIndex);
this->addChild(item, 0, kCurrentItem); this->addChild(item, 0, kCurrentItem);
Size s = item->getContentSize(); Size s = item->getContentSize();
this->setContentSize(s); this->setContentSize(s);
@ -950,13 +950,13 @@ void MenuItemToggle::setSelectedIndex(unsigned int index)
void MenuItemToggle::selected() void MenuItemToggle::selected()
{ {
MenuItem::selected(); MenuItem::selected();
static_cast<MenuItem*>(_subItems->objectAtIndex(_selectedIndex))->selected(); static_cast<MenuItem*>(_subItems->getObjectAtIndex(_selectedIndex))->selected();
} }
void MenuItemToggle::unselected() void MenuItemToggle::unselected()
{ {
MenuItem::unselected(); MenuItem::unselected();
static_cast<MenuItem*>(_subItems->objectAtIndex(_selectedIndex))->unselected(); static_cast<MenuItem*>(_subItems->getObjectAtIndex(_selectedIndex))->unselected();
} }
void MenuItemToggle::activate() void MenuItemToggle::activate()
@ -989,7 +989,7 @@ void MenuItemToggle::setEnabled(bool enabled)
MenuItem* MenuItemToggle::getSelectedItem() MenuItem* MenuItemToggle::getSelectedItem()
{ {
return static_cast<MenuItem*>(_subItems->objectAtIndex(_selectedIndex)); return static_cast<MenuItem*>(_subItems->getObjectAtIndex(_selectedIndex));
} }
NS_CC_END NS_CC_END

View File

@ -186,7 +186,7 @@ void ParticleBatchNode::addChild(Node * aChild, int zOrder, int tag)
if (pos != 0) if (pos != 0)
{ {
ParticleSystem* p = (ParticleSystem*)_children->objectAtIndex(pos-1); ParticleSystem* p = (ParticleSystem*)_children->getObjectAtIndex(pos-1);
atlasIndex = p->getAtlasIndex() + p->getTotalParticles(); atlasIndex = p->getAtlasIndex() + p->getTotalParticles();
} }
@ -274,7 +274,7 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder)
int newAtlasIndex = 0; int newAtlasIndex = 0;
for( unsigned int i=0;i < _children->count();i++) for( unsigned int i=0;i < _children->count();i++)
{ {
ParticleSystem* pNode = (ParticleSystem*)_children->objectAtIndex(i); ParticleSystem* pNode = (ParticleSystem*)_children->getObjectAtIndex(i);
if( pNode == child ) if( pNode == child )
{ {
newAtlasIndex = child->getAtlasIndex(); newAtlasIndex = child->getAtlasIndex();
@ -302,7 +302,7 @@ void ParticleBatchNode::getCurrentIndex(unsigned int* oldIndex, unsigned int* ne
for( unsigned int i=0; i < count; i++ ) for( unsigned int i=0; i < count; i++ )
{ {
Node* pNode = (Node *)_children->objectAtIndex(i); Node* pNode = (Node *)_children->getObjectAtIndex(i);
// new index // new index
if( pNode->getZOrder() > z && ! foundNewIdx ) if( pNode->getZOrder() > z && ! foundNewIdx )
@ -349,7 +349,7 @@ unsigned int ParticleBatchNode::searchNewPositionInChildrenForZ(int z)
for( unsigned int i=0; i < count; i++ ) for( unsigned int i=0; i < count; i++ )
{ {
Node *child = (Node *)_children->objectAtIndex(i); Node *child = (Node *)_children->getObjectAtIndex(i);
if (child->getZOrder() > z) if (child->getZOrder() > z)
{ {
return i; return i;
@ -385,7 +385,7 @@ void ParticleBatchNode::removeChild(Node* aChild, bool cleanup)
void ParticleBatchNode::removeChildAtIndex(unsigned int index, bool doCleanup) void ParticleBatchNode::removeChildAtIndex(unsigned int index, bool doCleanup)
{ {
removeChild((ParticleSystem *)_children->objectAtIndex(index),doCleanup); removeChild((ParticleSystem *)_children->getObjectAtIndex(index),doCleanup);
} }
void ParticleBatchNode::removeAllChildrenWithCleanup(bool doCleanup) void ParticleBatchNode::removeAllChildrenWithCleanup(bool doCleanup)

View File

@ -25,7 +25,7 @@ THE SOFTWARE.
#ifndef __CCACCELEROMETER_DELEGATE_H__ #ifndef __CCACCELEROMETER_DELEGATE_H__
#define __CCACCELEROMETER_DELEGATE_H__ #define __CCACCELEROMETER_DELEGATE_H__
#include "CCCommon.h" #include "platform/CCCommon.h"
NS_CC_BEGIN NS_CC_BEGIN
/** /**

View File

@ -177,6 +177,7 @@ public:
{ {
_state = SAX_ARRAY; _state = SAX_ARRAY;
_array = new Array(); _array = new Array();
_array->init();
if (_resultType == SAX_RESULT_ARRAY && _rootArray == NULL) if (_resultType == SAX_RESULT_ARRAY && _rootArray == NULL)
{ {
_rootArray = _array; _rootArray = _array;
@ -785,7 +786,14 @@ void FileUtils::loadFilenameLookupDictionaryFromFile(const char* filename)
std::string FileUtils::getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename) std::string FileUtils::getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename)
{ {
std::string ret = strDirectory+strFilename; // get directory+filename, safely adding '/' as necessary
std::string ret = strDirectory;
if (strDirectory.size() && strDirectory[strDirectory.size()-1] != '/'){
ret += '/';
}
ret += strFilename;
// if the file doesn't exist, return an empty string
if (!isFileExist(ret)) { if (!isFileExist(ret)) {
ret = ""; ret = "";
} }

View File

@ -29,7 +29,6 @@ THE SOFTWARE.
#include <map> #include <map>
#include "CCPlatformMacros.h" #include "CCPlatformMacros.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "ccTypeInfo.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -41,20 +40,11 @@ class Array;
*/ */
//! @brief Helper class to handle file operations //! @brief Helper class to handle file operations
class CC_DLL FileUtils : public TypeInfo class CC_DLL FileUtils
{ {
friend class Array; friend class Array;
friend class Dictionary; friend class Dictionary;
public: public:
/**
* Returns an unique ID for this class.
* @note It's only used for JSBindings now.
* @return The unique ID for this class.
*/
virtual long getClassTypeInfo() {
static const long id = cocos2d::getHashCodeByString(typeid(cocos2d::FileUtils).name());
return id;
}
/** /**
* Gets the instance of FileUtils. * Gets the instance of FileUtils.

View File

@ -77,6 +77,8 @@ public:
ETC, ETC,
//! S3TC //! S3TC
S3TC, S3TC,
//! ATITC
ATITC,
//! Raw Data //! Raw Data
RAW_DATA, RAW_DATA,
//! Unknown format //! Unknown format
@ -184,7 +186,6 @@ public:
bool saveToFile(const char *filePath, bool isToRGB = true); bool saveToFile(const char *filePath, bool isToRGB = true);
protected: protected:
bool initWithJpgData(const unsigned char * data, int dataLen); bool initWithJpgData(const unsigned char * data, int dataLen);
bool initWithPngData(const unsigned char * data, int dataLen); bool initWithPngData(const unsigned char * data, int dataLen);
bool initWithTiffData(const unsigned char * data, int dataLen); bool initWithTiffData(const unsigned char * data, int dataLen);
@ -194,6 +195,7 @@ protected:
bool initWithPVRv3Data(const unsigned char * data, int dataLen); bool initWithPVRv3Data(const unsigned char * data, int dataLen);
bool initWithETCData(const unsigned char * data, int dataLen); bool initWithETCData(const unsigned char * data, int dataLen);
bool initWithS3TCData(const unsigned char * data, int dataLen); bool initWithS3TCData(const unsigned char * data, int dataLen);
bool initWithATITCData(const unsigned char *data, int dataLen);
bool saveImageToPNG(const char *filePath, bool isToRGB = true); bool saveImageToPNG(const char *filePath, bool isToRGB = true);
bool saveImageToJPG(const char *filePath); bool saveImageToJPG(const char *filePath);
@ -239,7 +241,7 @@ private:
bool isPvr(const unsigned char * data, int dataLen); bool isPvr(const unsigned char * data, int dataLen);
bool isEtc(const unsigned char * data, int dataLen); bool isEtc(const unsigned char * data, int dataLen);
bool isS3TC(const unsigned char * data,int dataLen); bool isS3TC(const unsigned char * data,int dataLen);
bool isATITC(const unsigned char *data, int dataLen);
}; };
// end of platform group // end of platform group

View File

@ -41,6 +41,7 @@ extern "C"
#include "jpeglib.h" #include "jpeglib.h"
} }
#include "third_party/common/s3tc/s3tc.h" #include "third_party/common/s3tc/s3tc.h"
#include "third_party/common/atitc/atitc.h"
#if defined(__native_client__) || defined(EMSCRIPTEN) #if defined(__native_client__) || defined(EMSCRIPTEN)
// TODO(sbc): I'm pretty sure all platforms should be including // TODO(sbc): I'm pretty sure all platforms should be including
// webph headers in this way. // webph headers in this way.
@ -50,7 +51,7 @@ extern "C"
#endif #endif
#include "ccMacros.h" #include "ccMacros.h"
#include "CCCommon.h" #include "platform/CCCommon.h"
#include "CCStdC.h" #include "CCStdC.h"
#include "CCFileUtils.h" #include "CCFileUtils.h"
#include "CCConfiguration.h" #include "CCConfiguration.h"
@ -60,6 +61,10 @@ extern "C"
#include "platform/android/CCFileUtilsAndroid.h" #include "platform/android/CCFileUtilsAndroid.h"
#endif #endif
#define CC_GL_ATC_RGB_AMD 0x8C92
#define CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD 0x8C93
#define CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD 0x87EE
NS_CC_BEGIN NS_CC_BEGIN
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
@ -315,7 +320,33 @@ namespace
} }
//s3tc struct end //s3tc struct end
///////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
//struct and data for atitc(ktx) struct
namespace
{
struct ATITCTexHeader
{
//HEADER
char identifier[12];
uint32_t endianness;
uint32_t glType;
uint32_t glTypeSize;
uint32_t glFormat;
uint32_t glInternalFormat;
uint32_t glBaseInternalFormat;
uint32_t pixelWidth;
uint32_t pixelHeight;
uint32_t pixelDepth;
uint32_t numberOfArrayElements;
uint32_t numberOfFaces;
uint32_t numberOfMipmapLevels;
uint32_t bytesOfKeyValueData;
};
}
//atittc struct end
//////////////////////////////////////////////////////////////////////////
namespace namespace
{ {
@ -437,10 +468,12 @@ bool Image::initWithImageData(const unsigned char * data, int dataLen)
if (ZipUtils::ccIsCCZBuffer(data, dataLen)) if (ZipUtils::ccIsCCZBuffer(data, dataLen))
{ {
unpackedLen = ZipUtils::ccInflateCCZBuffer(data, dataLen, &unpackedData); unpackedLen = ZipUtils::ccInflateCCZBuffer(data, dataLen, &unpackedData);
}else if (ZipUtils::ccIsGZipBuffer(data, dataLen)) }
else if (ZipUtils::ccIsGZipBuffer(data, dataLen))
{ {
unpackedLen = ZipUtils::ccInflateMemory(const_cast<unsigned char*>(data), dataLen, &unpackedData); unpackedLen = ZipUtils::ccInflateMemory(const_cast<unsigned char*>(data), dataLen, &unpackedData);
}else }
else
{ {
unpackedData = const_cast<unsigned char*>(data); unpackedData = const_cast<unsigned char*>(data);
unpackedLen = dataLen; unpackedLen = dataLen;
@ -471,6 +504,9 @@ bool Image::initWithImageData(const unsigned char * data, int dataLen)
case Format::S3TC: case Format::S3TC:
ret = initWithS3TCData(unpackedData, unpackedLen); ret = initWithS3TCData(unpackedData, unpackedLen);
break; break;
case Format::ATITC:
ret = initWithATITCData(unpackedData, unpackedLen);
break;
default: default:
CCAssert(false, "unsupport image format!"); CCAssert(false, "unsupport image format!");
break; break;
@ -509,7 +545,7 @@ bool Image::isS3TC(const unsigned char * data, int dataLen)
S3TCTexHeader *header = (S3TCTexHeader *)data; S3TCTexHeader *header = (S3TCTexHeader *)data;
if (strncmp(header->fileCode, "DDS", 3)!= 0) if (strncmp(header->fileCode, "DDS", 3) != 0)
{ {
CCLOG("cocos2d: the file is not a dds file!"); CCLOG("cocos2d: the file is not a dds file!");
return false; return false;
@ -517,6 +553,18 @@ bool Image::isS3TC(const unsigned char * data, int dataLen)
return true; return true;
} }
bool Image::isATITC(const unsigned char *data, int dataLen)
{
ATITCTexHeader *header = (ATITCTexHeader *)data;
if (strncmp(&header->identifier[1], "KTX", 3) != 0)
{
CCLOG("cocos3d: the file is not a ktx file!");
return false;
}
return true;
}
bool Image::isJpg(const unsigned char * data, int dataLen) bool Image::isJpg(const unsigned char * data, int dataLen)
{ {
if (dataLen <= 4) if (dataLen <= 4)
@ -576,25 +624,35 @@ Image::Format Image::detectFormat(const unsigned char * data, int dataLen)
if (isPng(data, dataLen)) if (isPng(data, dataLen))
{ {
return Format::PNG; return Format::PNG;
}else if (isJpg(data, dataLen)) }
else if (isJpg(data, dataLen))
{ {
return Format::JPG; return Format::JPG;
}else if (isTiff(data, dataLen)) }
else if (isTiff(data, dataLen))
{ {
return Format::TIFF; return Format::TIFF;
}else if (isWebp(data, dataLen)) }
else if (isWebp(data, dataLen))
{ {
return Format::WEBP; return Format::WEBP;
}else if (isPvr(data, dataLen)) }
else if (isPvr(data, dataLen))
{ {
return Format::PVR; return Format::PVR;
}else if (isEtc(data, dataLen)) }
else if (isEtc(data, dataLen))
{ {
return Format::ETC; return Format::ETC;
}else if (isS3TC(data, dataLen)) }
else if (isS3TC(data, dataLen))
{ {
return Format::S3TC; return Format::S3TC;
} }
else if (isATITC(data, dataLen))
{
return Format::ATITC;
}
else else
{ {
return Format::UNKOWN; return Format::UNKOWN;
@ -1531,6 +1589,134 @@ bool Image::initWithS3TCData(const unsigned char * data, int dataLen)
return true; return true;
} }
bool Image::initWithATITCData(const unsigned char *data, int dataLen)
{
/* load the .ktx file */
ATITCTexHeader *header = (ATITCTexHeader *)data;
_width = header->pixelWidth;
_height = header->pixelHeight;
_numberOfMipmaps = header->numberOfMipmapLevels;
int blockSize = 0;
switch (header->glInternalFormat)
{
case CC_GL_ATC_RGB_AMD:
blockSize = 8;
break;
case CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD:
blockSize = 16;
break;
case CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD:
blockSize = 16;
break;
default:
break;
}
/* pixelData point to the compressed data address */
unsigned char *pixelData = (unsigned char *)data + sizeof(ATITCTexHeader) + header->bytesOfKeyValueData + 4;
/* caculate the dataLen */
int width = _width;
int height = _height;
if (Configuration::getInstance()->supportsATITC()) //compressed data length
{
_dataLen = dataLen - sizeof(ATITCTexHeader) - header->bytesOfKeyValueData - 4;
_data = new unsigned char [_dataLen];
memcpy((void *)_data,(void *)pixelData , _dataLen);
}
else //decompressed data length
{
for (unsigned int i = 0; i < _numberOfMipmaps && (width || height); ++i)
{
if (width == 0) width = 1;
if (height == 0) height = 1;
_dataLen += (height * width *4);
width >>= 1;
height >>= 1;
}
_data = new unsigned char [_dataLen];
}
/* load the mipmaps */
int encodeOffset = 0;
int decodeOffset = 0;
width = _width; height = _height;
for (unsigned int i = 0; i < _numberOfMipmaps && (width || height); ++i)
{
if (width == 0) width = 1;
if (height == 0) height = 1;
int size = ((width+3)/4)*((height+3)/4)*blockSize;
if (Configuration::getInstance()->supportsATITC())
{
/* decode texture throught hardware */
CCLOG("this is atitc H decode");
switch (header->glInternalFormat)
{
case CC_GL_ATC_RGB_AMD:
_renderFormat = Texture2D::PixelFormat::ATC_RGB;
break;
case CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD:
_renderFormat = Texture2D::PixelFormat::ATC_EXPLICIT_ALPHA;
break;
case CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD:
_renderFormat = Texture2D::PixelFormat::ATC_INTERPOLATED_ALPHA;
break;
default:
break;
}
_mipmaps[i].address = (unsigned char *)_data + encodeOffset;
_mipmaps[i].len = size;
}
else
{
/* if it is not gles or device do not support ATITC, decode texture by software */
int bytePerPixel = 4;
unsigned int stride = width * bytePerPixel;
_renderFormat = Texture2D::PixelFormat::RGBA8888;
std::vector<unsigned char> decodeImageData(stride * height);
switch (header->glInternalFormat)
{
case CC_GL_ATC_RGB_AMD:
atitc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, ATITCDecodeFlag::ATC_RGB);
break;
case CC_GL_ATC_RGBA_EXPLICIT_ALPHA_AMD:
atitc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, ATITCDecodeFlag::ATC_EXPLICIT_ALPHA);
break;
case CC_GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD:
atitc_decode(pixelData + encodeOffset, &decodeImageData[0], width, height, ATITCDecodeFlag::ATC_INTERPOLATED_ALPHA);
break;
default:
break;
}
_mipmaps[i].address = (unsigned char *)_data + decodeOffset;
_mipmaps[i].len = (stride * height);
memcpy((void *)_mipmaps[i].address, (void *)&decodeImageData[0], _mipmaps[i].len);
decodeOffset += stride * height;
}
encodeOffset += (size + 4);
width >>= 1;
height >>= 1;
}
/* end load the mipmaps */
return true;
}
bool Image::initWithPVRData(const unsigned char * data, int dataLen) bool Image::initWithPVRData(const unsigned char * data, int dataLen)
{ {
return initWithPVRv2Data(data, dataLen) || initWithPVRv3Data(data, dataLen); return initWithPVRv2Data(data, dataLen) || initWithPVRv3Data(data, dataLen);

View File

@ -25,7 +25,7 @@
#define __CCSAXPARSER_H__ #define __CCSAXPARSER_H__
#include "CCPlatformConfig.h" #include "CCPlatformConfig.h"
#include "CCCommon.h" #include "platform/CCCommon.h"
NS_CC_BEGIN NS_CC_BEGIN

View File

@ -25,7 +25,7 @@ THE SOFTWARE.
#ifndef __CC_PLATFORM_THREAD_H__ #ifndef __CC_PLATFORM_THREAD_H__
#define __CC_PLATFORM_THREAD_H__ #define __CC_PLATFORM_THREAD_H__
#include "CCCommon.h" #include "platform/CCCommon.h"
#include "CCPlatformMacros.h" #include "CCPlatformMacros.h"
NS_CC_BEGIN NS_CC_BEGIN

View File

@ -7,21 +7,19 @@ LOCAL_MODULE := cocos2dxandroid_static
LOCAL_MODULE_FILENAME := libcocos2dandroid LOCAL_MODULE_FILENAME := libcocos2dandroid
LOCAL_SRC_FILES := \ LOCAL_SRC_FILES := \
CCDevice.cpp \
CCEGLView.cpp \
CCAccelerometer.cpp \ CCAccelerometer.cpp \
CCApplication.cpp \ CCApplication.cpp \
CCCommon.cpp \ CCCommon.cpp \
CCDevice.cpp \
CCEGLView.cpp \
CCFileUtilsAndroid.cpp \ CCFileUtilsAndroid.cpp \
CCImage.cpp \ CCImage.cpp \
nativeactivity.cpp \ nativeactivity.cpp \
jni/DPIJni.cpp \
jni/IMEJni.cpp \
jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp \ jni/Java_org_cocos2dx_lib_Cocos2dxBitmap.cpp \
jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp \ jni/Java_org_cocos2dx_lib_Cocos2dxHelper.cpp \
jni/Java_org_cocos2dx_lib_Cocos2dxAccelerometer.cpp \ jni/JniHelper.cpp
jni/JniHelper.cpp \
jni/IMEJni.cpp \
jni/TouchesJni.cpp \
jni/DPIJni.cpp
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)

View File

@ -27,7 +27,6 @@
#include "platform/CCFileUtils.h" #include "platform/CCFileUtils.h"
#include "platform/CCPlatformMacros.h" #include "platform/CCPlatformMacros.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "ccTypeInfo.h"
#include <string> #include <string>
#include <vector> #include <vector>
#include "jni.h" #include "jni.h"

View File

@ -1,109 +0,0 @@
/****************************************************************************
Copyright (c) 2013 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.
****************************************************************************/
package org.cocos2dx.lib;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import android.content.Context;
import android.content.res.AssetManager;
import android.opengl.ETC1Util;
import android.util.Log;
public class Cocos2dxETCLoader {
private static final String ASSETS_PATH = "assets/";
private static Context context;
public static boolean loadTexture(String filePath) {
if (! ETC1Util.isETC1Supported()) {
return false;
}
if (filePath.length() == 0) {
return false;
}
// Create ETC1Texture
InputStream inputStream = null;
ETC1Util.ETC1Texture texture = null;
AssetManager assetManager = null;
try {
if (filePath.charAt(0) == '/') {
// absolute path
inputStream = new FileInputStream(filePath);
} else {
// remove prefix: "assets/"
if (filePath.startsWith(ASSETS_PATH)) {
filePath = filePath.substring(ASSETS_PATH.length());
}
assetManager = context.getAssets();
inputStream = assetManager.open(filePath);
}
texture = ETC1Util.createTexture(inputStream);
inputStream.close();
} catch (Exception e) {
Log.d("Cocos2dx", "Unable to create texture for " + filePath);
texture = null;
}
if (texture != null) {
boolean ret = true;
try {
final int width = texture.getWidth();
final int height = texture.getHeight();
final int length = texture.getData().remaining();
final byte[] data = new byte[length];
final ByteBuffer buf = ByteBuffer.wrap(data);
buf.order(ByteOrder.nativeOrder());
buf.put(texture.getData());
nativeSetTextureInfo(width,
height,
data,
length);
} catch (Exception e)
{
Log.d("invoke native function error", e.toString());
ret = false;
}
return ret;
} else {
return false;
}
}
public static void setContext(Context context) {
Cocos2dxETCLoader.context = context;
}
private static native void nativeSetTextureInfo(final int width, final int height, final byte[] data,
final int dataLength);
}

View File

@ -1,13 +0,0 @@
#include "cocoa/CCGeometry.h"
#include "platform/android/CCAccelerometer.h"
#include "../CCEGLView.h"
#include "JniHelper.h"
#include <jni.h>
#include "CCDirector.h"
using namespace cocos2d;
extern "C" {
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxAccelerometer_onSensorChanged(JNIEnv* env, jobject thiz, jfloat x, jfloat y, jfloat z, jlong timeStamp) {
}
}

View File

@ -1,90 +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.
****************************************************************************/
#include "cocoa/CCSet.h"
#include "CCDirector.h"
#include "keypad_dispatcher/CCKeypadDispatcher.h"
#include "touch_dispatcher/CCTouch.h"
#include "../CCEGLView.h"
#include "touch_dispatcher/CCTouchDispatcher.h"
#include <android/log.h>
#include <jni.h>
using namespace cocos2d;
extern "C" {
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesBegin(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y) {
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &id, &x, &y);
}
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesEnd(JNIEnv * env, jobject thiz, jint id, jfloat x, jfloat y) {
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &id, &x, &y);
}
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesMove(JNIEnv * env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys) {
int size = env->GetArrayLength(ids);
jint id[size];
jfloat x[size];
jfloat y[size];
env->GetIntArrayRegion(ids, 0, size, id);
env->GetFloatArrayRegion(xs, 0, size, x);
env->GetFloatArrayRegion(ys, 0, size, y);
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(size, id, x, y);
}
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeTouchesCancel(JNIEnv * env, jobject thiz, jintArray ids, jfloatArray xs, jfloatArray ys) {
int size = env->GetArrayLength(ids);
jint id[size];
jfloat x[size];
jfloat y[size];
env->GetIntArrayRegion(ids, 0, size, id);
env->GetFloatArrayRegion(xs, 0, size, x);
env->GetFloatArrayRegion(ys, 0, size, y);
cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(size, id, x, y);
}
#define KEYCODE_BACK 0x04
#define KEYCODE_MENU 0x52
JNIEXPORT jboolean JNICALL Java_org_cocos2dx_lib_Cocos2dxRenderer_nativeKeyDown(JNIEnv * env, jobject thiz, jint keyCode) {
Director* pDirector = Director::getInstance();
switch (keyCode) {
case KEYCODE_BACK:
if (pDirector->getKeypadDispatcher()->dispatchKeypadMSG(kTypeBackClicked))
return JNI_TRUE;
break;
case KEYCODE_MENU:
if (pDirector->getKeypadDispatcher()->dispatchKeypadMSG(kTypeMenuClicked))
return JNI_TRUE;
break;
default:
return JNI_FALSE;
}
return JNI_FALSE;
}
}

View File

@ -171,12 +171,6 @@ static cocos_dimensions engine_init_display(struct engine* engine) {
engine->height = h; engine->height = h;
engine->state.angle = 0; engine->state.angle = 0;
// Initialize GL state.
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
glEnable(GL_CULL_FACE);
glShadeModel(GL_SMOOTH);
glDisable(GL_DEPTH_TEST);
r.w = w; r.w = w;
r.h = h; r.h = h;

View File

@ -27,7 +27,6 @@
#include "platform/CCFileUtils.h" #include "platform/CCFileUtils.h"
#include "platform/CCPlatformMacros.h" #include "platform/CCPlatformMacros.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "ccTypeInfo.h"
#include <string> #include <string>
#include <vector> #include <vector>

View File

@ -22,7 +22,7 @@
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "CCCommon.h" #include "platform/CCCommon.h"
#include <stdarg.h> #include <stdarg.h>
#include <stdio.h> #include <stdio.h>
@ -34,7 +34,7 @@ NS_CC_BEGIN
// XXX deprecated // XXX deprecated
void CCLog(const char * pszFormat, ...) void CCLog(const char * pszFormat, ...)
{ {
printf("Cocos2d: "); printf("cocos2d: ");
char szBuf[kMaxLogLen+1] = {0}; char szBuf[kMaxLogLen+1] = {0};
va_list ap; va_list ap;
va_start(ap, pszFormat); va_start(ap, pszFormat);
@ -46,7 +46,7 @@ void CCLog(const char * pszFormat, ...)
void log(const char * pszFormat, ...) void log(const char * pszFormat, ...)
{ {
printf("Cocos2d: "); printf("cocos2d: ");
char szBuf[kMaxLogLen+1] = {0}; char szBuf[kMaxLogLen+1] = {0};
va_list ap; va_list ap;
va_start(ap, pszFormat); va_start(ap, pszFormat);

View File

@ -33,7 +33,6 @@
#import "CCES2Renderer.h" #import "CCES2Renderer.h"
#import "OpenGL_Internal.h" #import "OpenGL_Internal.h"
@implementation CCES2Renderer @implementation CCES2Renderer
@synthesize context=context_; @synthesize context=context_;
@ -207,7 +206,7 @@
- (void)dealloc - (void)dealloc
{ {
NSLog(@"cocos2d: deallocing %@", self); // CCLOGINFO("deallocing CCES2Renderer: %p", self);
// Tear down GL // Tear down GL
if (defaultFramebuffer_) { if (defaultFramebuffer_) {

View File

@ -29,7 +29,6 @@
#include <vector> #include <vector>
#include "CCPlatformMacros.h" #include "CCPlatformMacros.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "ccTypeInfo.h"
NS_CC_BEGIN NS_CC_BEGIN

View File

@ -65,6 +65,7 @@ static void addItemToArray(id item, Array *pArray)
// add dictionary value into array // add dictionary value into array
if ([item isKindOfClass:[NSDictionary class]]) { if ([item isKindOfClass:[NSDictionary class]]) {
Dictionary* pDictItem = new Dictionary(); Dictionary* pDictItem = new Dictionary();
pDictItem->init();
for (id subKey in [item allKeys]) { for (id subKey in [item allKeys]) {
id subValue = [item objectForKey:subKey]; id subValue = [item objectForKey:subKey];
addValueToDict(subKey, subValue, pDictItem); addValueToDict(subKey, subValue, pDictItem);
@ -130,6 +131,7 @@ static void addValueToDict(id key, id value, Dictionary* pDict)
// the value is a new dictionary // the value is a new dictionary
if ([value isKindOfClass:[NSDictionary class]]) { if ([value isKindOfClass:[NSDictionary class]]) {
Dictionary* pSubDict = new Dictionary(); Dictionary* pSubDict = new Dictionary();
pSubDict->init();
for (id subKey in [value allKeys]) { for (id subKey in [value allKeys]) {
id subValue = [value objectForKey:subKey]; id subValue = [value objectForKey:subKey];
addValueToDict(subKey, subValue, pSubDict); addValueToDict(subKey, subValue, pSubDict);
@ -314,7 +316,7 @@ Dictionary* FileUtilsIOS::createDictionaryWithContentsOfFile(const std::string&
if (pDict != nil) if (pDict != nil)
{ {
Dictionary* pRet = new Dictionary(); Dictionary* pRet = Dictionary::create();
for (id key in [pDict allKeys]) { for (id key in [pDict allKeys]) {
id value = [pDict objectForKey:key]; id value = [pDict objectForKey:key];
addValueToDict(key, value, pRet); addValueToDict(key, value, pRet);
@ -354,15 +356,18 @@ Array* FileUtilsIOS::createArrayWithContentsOfFile(const std::string& filename)
// pPath = [[NSBundle mainBundle] pathForResource:pPath ofType:pathExtension]; // pPath = [[NSBundle mainBundle] pathForResource:pPath ofType:pathExtension];
// fixing cannot read data using Array::createWithContentsOfFile // fixing cannot read data using Array::createWithContentsOfFile
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename.c_str()); std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename.c_str());
NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()]; NSString* path = [NSString stringWithUTF8String:fullPath.c_str()];
NSArray* pArray = [NSArray arrayWithContentsOfFile:pPath]; NSArray* array = [NSArray arrayWithContentsOfFile:path];
Array* pRet = new Array(); Array* ret = new Array();
for (id value in pArray) { ret->init();
addItemToArray(value, pRet);
for (id value in array)
{
addItemToArray(value, ret);
} }
return pRet; return ret;
} }
NS_CC_END NS_CC_END

View File

@ -25,7 +25,7 @@ THE SOFTWARE.
#import "CCImage.h" #import "CCImage.h"
#import "CCFileUtils.h" #import "CCFileUtils.h"
#import "CCCommon.h" #import "platform/CCCommon.h"
#import <string> #import <string>
#import <Foundation/Foundation.h> #import <Foundation/Foundation.h>

View File

@ -27,7 +27,6 @@
#include "platform/CCFileUtils.h" #include "platform/CCFileUtils.h"
#include "platform/CCPlatformMacros.h" #include "platform/CCPlatformMacros.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "ccTypeInfo.h"
#include <string> #include <string>
#include <vector> #include <vector>

View File

@ -59,7 +59,7 @@ static id s_sharedDirectorCaller;
-(void) dealloc -(void) dealloc
{ {
s_sharedDirectorCaller = nil; s_sharedDirectorCaller = nil;
CCLOG("cocos2d: deallocing DirectorCaller %p", self); CCLOGINFO("deallocing DirectorCaller: %p", self);
if (displayLink) { if (displayLink) {
CVDisplayLinkRelease(displayLink); CVDisplayLinkRelease(displayLink);
} }

View File

@ -123,6 +123,7 @@ EGLView::EGLView()
EGLView::~EGLView() EGLView::~EGLView()
{ {
CCLOGINFO("deallocing EGLView: %p", this);
glfwTerminate(); glfwTerminate();
s_pEglView = nullptr; s_pEglView = nullptr;
} }

View File

@ -29,7 +29,6 @@
#include <vector> #include <vector>
#include "CCPlatformMacros.h" #include "CCPlatformMacros.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "ccTypeInfo.h"
NS_CC_BEGIN NS_CC_BEGIN
/** /**

View File

@ -38,13 +38,13 @@ NS_CC_BEGIN
static void addValueToDict(id key, id value, Dictionary* pDict); static void addValueToDict(id key, id value, Dictionary* pDict);
static void addObjectToNSDict(const char*key, Object* object, NSMutableDictionary *dict); static void addObjectToNSDict(const char*key, Object* object, NSMutableDictionary *dict);
static void addItemToArray(id item, Array *pArray) static void addItemToArray(id item, Array *array)
{ {
// add string value into array // add string value into array
if ([item isKindOfClass:[NSString class]]) { if ([item isKindOfClass:[NSString class]]) {
String* pValue = new String([item UTF8String]); String* pValue = new String([item UTF8String]);
pArray->addObject(pValue); array->addObject(pValue);
pValue->release(); pValue->release();
return; return;
} }
@ -54,7 +54,7 @@ static void addItemToArray(id item, Array *pArray)
NSString* pStr = [item stringValue]; NSString* pStr = [item stringValue];
String* pValue = new String([pStr UTF8String]); String* pValue = new String([pStr UTF8String]);
pArray->addObject(pValue); array->addObject(pValue);
pValue->release(); pValue->release();
return; return;
} }
@ -62,24 +62,25 @@ static void addItemToArray(id item, Array *pArray)
// add dictionary value into array // add dictionary value into array
if ([item isKindOfClass:[NSDictionary class]]) { if ([item isKindOfClass:[NSDictionary class]]) {
Dictionary* pDictItem = new Dictionary(); Dictionary* pDictItem = new Dictionary();
pDictItem->init();
for (id subKey in [item allKeys]) { for (id subKey in [item allKeys]) {
id subValue = [item objectForKey:subKey]; id subValue = [item objectForKey:subKey];
addValueToDict(subKey, subValue, pDictItem); addValueToDict(subKey, subValue, pDictItem);
} }
pArray->addObject(pDictItem); array->addObject(pDictItem);
pDictItem->release(); pDictItem->release();
return; return;
} }
// add array value into array // add array value into array
if ([item isKindOfClass:[NSArray class]]) { if ([item isKindOfClass:[NSArray class]]) {
Array *pArrayItem = new Array(); Array *arrayItem = new Array();
pArrayItem->init(); arrayItem->initWithCapacity( [item count] );
for (id subItem in item) { for (id subItem in item) {
addItemToArray(subItem, pArrayItem); addItemToArray(subItem, arrayItem);
} }
pArray->addObject(pArrayItem); array->addObject(arrayItem);
pArrayItem->release(); arrayItem->release();
return; return;
} }
} }
@ -157,13 +158,13 @@ static void addValueToDict(id key, id value, Dictionary* pDict)
// the value is a array // the value is a array
if ([value isKindOfClass:[NSArray class]]) { if ([value isKindOfClass:[NSArray class]]) {
Array *pArray = new Array(); Array *array = new Array();
pArray->init(); array->initWithCapacity([value count]);
for (id item in value) { for (id item in value) {
addItemToArray(item, pArray); addItemToArray(item, array);
} }
pDict->setObject(pArray, pKey.c_str()); pDict->setObject(array, pKey.c_str());
pArray->release(); array->release();
return; return;
} }
} }
@ -304,7 +305,7 @@ Dictionary* FileUtilsMac::createDictionaryWithContentsOfFile(const std::string&
NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()]; NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()];
NSDictionary* pDict = [NSDictionary dictionaryWithContentsOfFile:pPath]; NSDictionary* pDict = [NSDictionary dictionaryWithContentsOfFile:pPath];
Dictionary* pRet = new Dictionary(); Dictionary* pRet = Dictionary::create();
for (id key in [pDict allKeys]) { for (id key in [pDict allKeys]) {
id value = [pDict objectForKey:key]; id value = [pDict objectForKey:key];
addValueToDict(key, value, pRet); addValueToDict(key, value, pRet);
@ -338,14 +339,14 @@ Array* FileUtilsMac::createArrayWithContentsOfFile(const std::string& filename)
// fixing cannot read data using Array::createWithContentsOfFile // fixing cannot read data using Array::createWithContentsOfFile
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename.c_str()); std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename.c_str());
NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()]; NSString* pPath = [NSString stringWithUTF8String:fullPath.c_str()];
NSArray* pArray = [NSArray arrayWithContentsOfFile:pPath]; NSArray* array = [NSArray arrayWithContentsOfFile:pPath];
Array* pRet = new Array(); Array* ret = Array::createWithCapacity( [array count] );
for (id value in pArray) { for (id value in array) {
addItemToArray(value, pRet); addItemToArray(value, ret);
} }
return pRet; return ret;
} }

View File

@ -201,7 +201,7 @@ static CCEAGLView *view;
- (void) dealloc - (void) dealloc
{ {
CCLOGINFO(@"cocos2d: deallocing CCEAGLView %@", self); CCLOGINFO("deallocing CCEAGLView: %p", self);
[super dealloc]; [super dealloc];
} }

View File

@ -36,6 +36,7 @@ THE SOFTWARE.
#include <pthread.h> #include <pthread.h>
#include <stdio.h> #include <stdio.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/mount.h>
#include <unistd.h> #include <unistd.h>
USING_NS_CC; USING_NS_CC;

View File

@ -31,7 +31,6 @@
#include "platform/CCPlatformMacros.h" #include "platform/CCPlatformMacros.h"
#include "platform/CCCommon.h" #include "platform/CCCommon.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "ccTypeInfo.h"
#include "ccMacros.h" #include "ccMacros.h"
#include <unistd.h> #include <unistd.h>

View File

@ -0,0 +1,195 @@
/****************************************************************************
Copyright (c) 2013 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.
****************************************************************************/
#include "atitc.h"
//Decode ATITC encode block to 4x4 RGB32 pixels
static void atitc_decode_block(uint8_t **blockData,
uint32_t *decodeBlockData,
unsigned int stride,
bool oneBitAlphaFlag,
uint64_t alpha,
ATITCDecodeFlag decodeFlag)
{
unsigned int colorValue0 = 0 , colorValue1 = 0, initAlpha = (!oneBitAlphaFlag * 255u) << 24;
unsigned int rb0 = 0, rb1 = 0, rb2 = 0, rb3 = 0, g0 = 0, g1 = 0, g2 = 0, g3 = 0;
bool msb = 0;
uint32_t colors[4], pixelsIndex = 0;
/* load the two color values*/
memcpy((void *)&colorValue0, *blockData, 2);
(*blockData) += 2;
memcpy((void *)&colorValue1, *blockData, 2);
(*blockData) += 2;
//extract the msb flag
msb = (colorValue0 & 0x8000);
/* the channel is r5g6b5 , 16 bits */
rb0 = (colorValue0 << 3 | colorValue0 << 9) & 0xf800f8;
rb1 = (colorValue1 << 3 | colorValue1 << 8) & 0xf800f8;
g0 = (colorValue0 << 6) & 0x00fc00;
g1 = (colorValue1 << 5) & 0x00fc00;
g0 += (g0 >> 6) & 0x000300;
g1 += (g1 >> 6) & 0x000300;
/* interpolate the other two color values */
if (!msb)
{
colors[0] = rb0 + g0 + initAlpha;
colors[3] = rb1 + g1 + initAlpha;
rb2 = (((2*rb0 + rb1) * 21) >> 6) & 0xff00ff;
rb3 = (((2*rb1 + rb0) * 21) >> 6) & 0xff00ff;
g2 = (((2*g0 + g1 ) * 21) >> 6) & 0x00ff00;
g3 = (((2*g1 + g0 ) * 21) >> 6) & 0x00ff00;
colors[2] = rb3 + g3 + initAlpha;
colors[1] = rb2 + g2 + initAlpha;
}
else
{
colors[2] = rb0 + g0 + initAlpha;
colors[3] = rb1 + g1 + initAlpha;
rb2 = (rb0 - (rb1 >> 2)) & 0xff00ff;
g2 = (g0 - (g1 >> 2)) & 0x00ff00;
colors[0] = 0 ;
colors[1] = rb2 + g2 + initAlpha;
}
/*read the pixelsIndex , 2bits per pixel, 4 bytes */
memcpy((void*)&pixelsIndex, *blockData, 4);
(*blockData) += 4;
if (ATITCDecodeFlag::ATC_INTERPOLATED_ALPHA == decodeFlag)
{
// atitc_interpolated_alpha use interpolate alpha
// 8-Alpha block: derive the other six alphas.
// Bit code 000 = alpha0, 001 = alpha1, other are interpolated.
unsigned int alphaArray[8];
alphaArray[0] = (alpha ) & 0xff ;
alphaArray[1] = (alpha >> 8) & 0xff ;
if (alphaArray[0] >= alphaArray[1])
{
alphaArray[2] = (alphaArray[0]*6 + alphaArray[1]*1) / 7;
alphaArray[3] = (alphaArray[0]*5 + alphaArray[1]*2) / 7;
alphaArray[4] = (alphaArray[0]*4 + alphaArray[1]*3) / 7;
alphaArray[5] = (alphaArray[0]*3 + alphaArray[1]*4) / 7;
alphaArray[6] = (alphaArray[0]*2 + alphaArray[1]*5) / 7;
alphaArray[7] = (alphaArray[0]*1 + alphaArray[1]*6) / 7;
}
else if (alphaArray[0] < alphaArray[1])
{
alphaArray[2] = (alphaArray[0]*4 + alphaArray[1]*1) / 5;
alphaArray[3] = (alphaArray[0]*3 + alphaArray[1]*2) / 5;
alphaArray[4] = (alphaArray[0]*2 + alphaArray[1]*3) / 5;
alphaArray[5] = (alphaArray[0]*1 + alphaArray[1]*4) / 5;
alphaArray[6] = 0;
alphaArray[7] = 255;
}
// read the flowing 48bit indices (16*3)
alpha >>= 16;
for (int y = 0; y < 4; ++y)
{
for (int x = 0; x < 4; ++x)
{
decodeBlockData[x] = (alphaArray[alpha & 5] << 24) + colors[pixelsIndex & 3];
pixelsIndex >>= 2;
alpha >>= 3;
}
decodeBlockData += stride;
}
} //if (atc_interpolated_alpha == comFlag)
else
{
/* atc_rgb atc_explicit_alpha use explicit alpha */
for (int y = 0; y < 4; ++y)
{
for (int x = 0; x < 4; ++x)
{
initAlpha = (alpha & 0x0f) << 28;
initAlpha += initAlpha >> 4;
decodeBlockData[x] = initAlpha + colors[pixelsIndex & 3];
pixelsIndex >>= 2;
alpha >>= 4;
}
decodeBlockData += stride;
}
}
}
//Decode ATITC encode data to RGB32
void atitc_decode(uint8_t *encodeData, //in_data
uint8_t *decodeData, //out_data
const unsigned int pixelsWidth,
const unsigned int pixelsHeight,
ATITCDecodeFlag decodeFlag)
{
uint32_t *decodeBlockData = (uint32_t *)decodeData;
for (int block_y = 0; block_y < pixelsHeight / 4; ++block_y, decodeBlockData += 3 * pixelsWidth) //stride = 3*width
{
for (int block_x = 0; block_x < pixelsWidth / 4; ++block_x, decodeBlockData += 4) //skip 4 pixels
{
uint64_t blockAlpha = 0;
switch (decodeFlag)
{
case ATITCDecodeFlag::ATC_RGB:
{
atitc_decode_block(&encodeData, decodeBlockData, pixelsWidth, 0, 0LL, ATITCDecodeFlag::ATC_RGB);
}
break;
case ATITCDecodeFlag::ATC_EXPLICIT_ALPHA:
{
memcpy((void *)&blockAlpha, encodeData, 8);
encodeData += 8;
atitc_decode_block(&encodeData, decodeBlockData, pixelsWidth, 1, blockAlpha, ATITCDecodeFlag::ATC_EXPLICIT_ALPHA);
}
break;
case ATITCDecodeFlag::ATC_INTERPOLATED_ALPHA:
{
memcpy((void *)&blockAlpha, encodeData, 8);
encodeData += 8;
atitc_decode_block(&encodeData, decodeBlockData, pixelsWidth, 1, blockAlpha, ATITCDecodeFlag::ATC_INTERPOLATED_ALPHA);
}
break;
default:
break;
}//switch
}//for block_x
}//for block_y
}

View File

@ -0,0 +1,48 @@
/****************************************************************************
Copyright (c) 2013 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 COCOS2DX_PLATFORM_THIRDPARTY_ATITC_
#define COCOS2DX_PLATFORM_THIRDPARTY_ATITC_
#include "CCStdC.h"
enum class ATITCDecodeFlag
{
ATC_RGB = 1,
ATC_EXPLICIT_ALPHA = 3,
ATC_INTERPOLATED_ALPHA = 5,
};
//Decode ATITC encode data to RGB32
void atitc_decode(uint8_t *encode_data,
uint8_t *decode_data,
const unsigned int pixelsWidth,
const unsigned int pixelsHeight,
ATITCDecodeFlag decodeFlag
);
#endif /* defined(COCOS2DX_PLATFORM_THIRDPARTY_ATITC_) */

View File

@ -1,5 +1,5 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2010 cocos2d-x.org Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org http://www.cocos2d-x.org

View File

@ -1,5 +1,5 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2010 cocos2d-x.org Copyright (c) 2013 cocos2d-x.org
http://www.cocos2d-x.org http://www.cocos2d-x.org

View File

@ -29,7 +29,6 @@ THE SOFTWARE.
#include "platform/CCFileUtils.h" #include "platform/CCFileUtils.h"
#include "platform/CCPlatformMacros.h" #include "platform/CCPlatformMacros.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "ccTypeInfo.h"
#include <string> #include <string>
#include <vector> #include <vector>

View File

@ -27,7 +27,6 @@
#include "platform/CCFileUtils.h" #include "platform/CCFileUtils.h"
#include "platform/CCPlatformMacros.h" #include "platform/CCPlatformMacros.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "ccTypeInfo.h"
#include <string> #include <string>
#include <vector> #include <vector>

View File

@ -4,6 +4,7 @@ INCLUDES += \
-I../platform/third_party/linux/libfreetype2 \ -I../platform/third_party/linux/libfreetype2 \
-I../platform/third_party/common/etc \ -I../platform/third_party/common/etc \
-I../platform/third_party/common/s3tc \ -I../platform/third_party/common/s3tc \
-I../platform/third_party/common/atitc \
-I../../extensions \ -I../../extensions \
-I../../extensions/CCBReader \ -I../../extensions/CCBReader \
-I../../extensions/GUI/CCControlExtension \ -I../../extensions/GUI/CCControlExtension \
@ -85,7 +86,8 @@ SOURCES = ../actions/CCAction.cpp \
../platform/linux/CCImage.cpp \ ../platform/linux/CCImage.cpp \
../platform/linux/CCDevice.cpp \ ../platform/linux/CCDevice.cpp \
../platform/third_party/common/etc/etc1.cpp \ ../platform/third_party/common/etc/etc1.cpp \
../platform/third_party/common/s3tc/s3tc.cpp\ ../platform/third_party/common/s3tc/s3tc.cpp \
../platform/third_party/common/atitc/atitc.cpp \
../script_support/CCScriptSupport.cpp \ ../script_support/CCScriptSupport.cpp \
../sprite_nodes/CCAnimation.cpp \ ../sprite_nodes/CCAnimation.cpp \
../sprite_nodes/CCAnimationCache.cpp \ ../sprite_nodes/CCAnimationCache.cpp \

File diff suppressed because it is too large Load Diff

View File

@ -206,6 +206,7 @@ xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir
<ClCompile Include="..\platform\CCFileUtils.cpp" /> <ClCompile Include="..\platform\CCFileUtils.cpp" />
<ClCompile Include="..\platform\CCSAXParser.cpp" /> <ClCompile Include="..\platform\CCSAXParser.cpp" />
<ClCompile Include="..\platform\CCThread.cpp" /> <ClCompile Include="..\platform\CCThread.cpp" />
<ClCompile Include="..\platform\third_party\common\atitc\atitc.cpp" />
<ClCompile Include="..\platform\third_party\common\etc\etc1.cpp" /> <ClCompile Include="..\platform\third_party\common\etc\etc1.cpp" />
<ClCompile Include="..\platform\third_party\common\s3tc\s3tc.cpp" /> <ClCompile Include="..\platform\third_party\common\s3tc\s3tc.cpp" />
<ClCompile Include="..\platform\win32\CCAccelerometer.cpp" /> <ClCompile Include="..\platform\win32\CCAccelerometer.cpp" />
@ -364,6 +365,7 @@ xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir
<ClInclude Include="..\platform\CCSAXParser.h" /> <ClInclude Include="..\platform\CCSAXParser.h" />
<ClInclude Include="..\platform\CCThread.h" /> <ClInclude Include="..\platform\CCThread.h" />
<ClInclude Include="..\platform\platform.h" /> <ClInclude Include="..\platform\platform.h" />
<ClInclude Include="..\platform\third_party\common\atitc\atitc.h" />
<ClInclude Include="..\platform\third_party\common\etc\etc1.h" /> <ClInclude Include="..\platform\third_party\common\etc\etc1.h" />
<ClInclude Include="..\platform\third_party\common\s3tc\s3tc.h" /> <ClInclude Include="..\platform\third_party\common\s3tc\s3tc.h" />
<ClInclude Include="..\platform\win32\CCAccelerometer.h" /> <ClInclude Include="..\platform\win32\CCAccelerometer.h" />

View File

@ -506,6 +506,9 @@
<ClCompile Include="..\platform\third_party\common\s3tc\s3tc.cpp"> <ClCompile Include="..\platform\third_party\common\s3tc\s3tc.cpp">
<Filter>platform</Filter> <Filter>platform</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="..\platform\third_party\common\atitc\atitc.cpp">
<Filter>platform</Filter>
</ClCompile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="..\base_nodes\CCAtlasNode.h"> <ClInclude Include="..\base_nodes\CCAtlasNode.h">
@ -1021,5 +1024,8 @@
<ClInclude Include="..\platform\third_party\common\s3tc\s3tc.h"> <ClInclude Include="..\platform\third_party\common\s3tc\s3tc.h">
<Filter>platform</Filter> <Filter>platform</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="..\platform\third_party\common\atitc\atitc.h">
<Filter>platform</Filter>
</ClInclude>
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -82,7 +82,7 @@ GLProgram::GLProgram()
GLProgram::~GLProgram() GLProgram::~GLProgram()
{ {
CCLOGINFO("cocos2d: %s %d deallocing %p", __FUNCTION__, __LINE__, this); CCLOGINFO("%s %d deallocing GLProgram: %p", __FUNCTION__, __LINE__, this);
// there is no need to delete the shaders. They should have been already deleted. // there is no need to delete the shaders. They should have been already deleted.
CCASSERT(_vertShader == 0, "Vertex Shaders should have been already deleted"); CCASSERT(_vertShader == 0, "Vertex Shaders should have been already deleted");

View File

@ -83,13 +83,15 @@ ShaderCache::ShaderCache()
ShaderCache::~ShaderCache() ShaderCache::~ShaderCache()
{ {
CCLOGINFO("cocos2d deallocing %p", this); CCLOGINFO("deallocing ShaderCache: %p", this);
_programs->release(); _programs->release();
} }
bool ShaderCache::init() bool ShaderCache::init()
{ {
_programs = new Dictionary(); _programs = Dictionary::create();
_programs->retain();
loadDefaultShaders(); loadDefaultShaders();
return true; return true;
} }

View File

@ -50,7 +50,7 @@ bool AnimationFrame::initWithSpriteFrame(SpriteFrame* spriteFrame, float delayUn
AnimationFrame::~AnimationFrame() AnimationFrame::~AnimationFrame()
{ {
CCLOGINFO( "cocos2d: deallocing %p", this); CCLOGINFO( "deallocing AnimationFrame: %p", this);
CC_SAFE_RELEASE(_spriteFrame); CC_SAFE_RELEASE(_spriteFrame);
CC_SAFE_RELEASE(_userInfo); CC_SAFE_RELEASE(_userInfo);
@ -159,7 +159,7 @@ Animation::Animation()
Animation::~Animation(void) Animation::~Animation(void)
{ {
CCLOGINFO("cocos2d, deallocing %p", this); CCLOGINFO("deallocing Animation: %p", this);
CC_SAFE_RELEASE(_frames); CC_SAFE_RELEASE(_frames);
} }

View File

@ -55,7 +55,8 @@ void AnimationCache::destroyInstance()
bool AnimationCache::init() bool AnimationCache::init()
{ {
_animations = new Dictionary(); _animations = new Dictionary;
_animations->init();
return true; return true;
} }
@ -66,7 +67,7 @@ AnimationCache::AnimationCache()
AnimationCache::~AnimationCache() AnimationCache::~AnimationCache()
{ {
CCLOGINFO("cocos2d: deallocing %p", this); CCLOGINFO("deallocing AnimationCache: %p", this);
CC_SAFE_RELEASE(_animations); CC_SAFE_RELEASE(_animations);
} }

View File

@ -104,10 +104,10 @@ Sprite* Sprite::create(const char *filename, const Rect& rect)
return NULL; return NULL;
} }
Sprite* Sprite::createWithSpriteFrame(SpriteFrame *pSpriteFrame) Sprite* Sprite::createWithSpriteFrame(SpriteFrame *spriteFrame)
{ {
Sprite *sprite = new Sprite(); Sprite *sprite = new Sprite();
if (pSpriteFrame && sprite && sprite->initWithSpriteFrame(pSpriteFrame)) if (spriteFrame && sprite && sprite->initWithSpriteFrame(spriteFrame))
{ {
sprite->autorelease(); sprite->autorelease();
return sprite; return sprite;
@ -118,26 +118,26 @@ Sprite* Sprite::createWithSpriteFrame(SpriteFrame *pSpriteFrame)
Sprite* Sprite::createWithSpriteFrameName(const char *spriteFrameName) Sprite* Sprite::createWithSpriteFrameName(const char *spriteFrameName)
{ {
SpriteFrame *pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName);
#if COCOS2D_DEBUG > 0 #if COCOS2D_DEBUG > 0
char msg[256] = {0}; char msg[256] = {0};
sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName); sprintf(msg, "Invalid spriteFrameName: %s", spriteFrameName);
CCASSERT(pFrame != NULL, msg); CCASSERT(frame != NULL, msg);
#endif #endif
return createWithSpriteFrame(pFrame); return createWithSpriteFrame(frame);
} }
Sprite* Sprite::create() Sprite* Sprite::create()
{ {
Sprite *pSprite = new Sprite(); Sprite *sprite = new Sprite();
if (pSprite && pSprite->init()) if (sprite && sprite->init())
{ {
pSprite->autorelease(); sprite->autorelease();
return pSprite; return sprite;
} }
CC_SAFE_DELETE(pSprite); CC_SAFE_DELETE(sprite);
return NULL; return NULL;
} }
@ -174,11 +174,10 @@ bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated)
memset(&_quad, 0, sizeof(_quad)); memset(&_quad, 0, sizeof(_quad));
// Atlas: Color // Atlas: Color
Color4B tmpColor(255, 255, 255, 255); _quad.bl.colors = Color4B::WHITE;
_quad.bl.colors = tmpColor; _quad.br.colors = Color4B::WHITE;
_quad.br.colors = tmpColor; _quad.tl.colors = Color4B::WHITE;
_quad.tl.colors = tmpColor; _quad.tr.colors = Color4B::WHITE;
_quad.tr.colors = tmpColor;
// shader program // shader program
setShaderProgram(ShaderCache::getInstance()->programForKey(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); setShaderProgram(ShaderCache::getInstance()->programForKey(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
@ -248,12 +247,12 @@ bool Sprite::initWithFile(const char *filename, const Rect& rect)
return false; return false;
} }
bool Sprite::initWithSpriteFrame(SpriteFrame *pSpriteFrame) bool Sprite::initWithSpriteFrame(SpriteFrame *spriteFrame)
{ {
CCASSERT(pSpriteFrame != NULL, ""); CCASSERT(spriteFrame != NULL, "");
bool bRet = initWithTexture(pSpriteFrame->getTexture(), pSpriteFrame->getRect()); bool bRet = initWithTexture(spriteFrame->getTexture(), spriteFrame->getRect());
setDisplayFrame(pSpriteFrame); setDisplayFrame(spriteFrame);
return bRet; return bRet;
} }
@ -262,8 +261,8 @@ bool Sprite::initWithSpriteFrameName(const char *spriteFrameName)
{ {
CCASSERT(spriteFrameName != NULL, ""); CCASSERT(spriteFrameName != NULL, "");
SpriteFrame *pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName); SpriteFrame *frame = SpriteFrameCache::getInstance()->getSpriteFrameByName(spriteFrameName);
return initWithSpriteFrame(pFrame); return initWithSpriteFrame(frame);
} }
// XXX: deprecated // XXX: deprecated
@ -293,8 +292,8 @@ Sprite* Sprite::initWithCGImage(CGImageRef pImage, const char *pszKey)
*/ */
Sprite::Sprite(void) Sprite::Sprite(void)
: _shouldBeHidden(false), : _shouldBeHidden(false)
_texture(NULL) , _texture(NULL)
{ {
} }
@ -453,7 +452,7 @@ void Sprite::updateTransform(void)
if( isDirty() ) { if( isDirty() ) {
// If it is not visible, or one of its ancestors is not visible, then do nothing: // If it is not visible, or one of its ancestors is not visible, then do nothing:
if( !_visible || ( _parent && _parent != _batchNode && ((Sprite*)_parent)->_shouldBeHidden) ) if( !_visible || ( _parent && _parent != _batchNode && static_cast<Sprite*>(_parent)->_shouldBeHidden) )
{ {
_quad.br.vertices = _quad.tl.vertices = _quad.tr.vertices = _quad.bl.vertices = Vertex3F(0,0,0); _quad.br.vertices = _quad.tl.vertices = _quad.tr.vertices = _quad.bl.vertices = Vertex3F(0,0,0);
_shouldBeHidden = true; _shouldBeHidden = true;
@ -469,7 +468,7 @@ void Sprite::updateTransform(void)
else else
{ {
CCASSERT( dynamic_cast<Sprite*>(_parent), "Logic error in Sprite. Parent must be a Sprite"); CCASSERT( dynamic_cast<Sprite*>(_parent), "Logic error in Sprite. Parent must be a Sprite");
_transformToBatch = AffineTransformConcat( getNodeToParentTransform() , ((Sprite*)_parent)->_transformToBatch ); _transformToBatch = AffineTransformConcat( getNodeToParentTransform() , static_cast<Sprite*>(_parent)->_transformToBatch );
} }
// //
@ -659,25 +658,25 @@ void Sprite::reorderChild(Node *child, int zOrder)
Node::reorderChild(child, zOrder); Node::reorderChild(child, zOrder);
} }
void Sprite::removeChild(Node *child, bool bCleanup) void Sprite::removeChild(Node *child, bool cleanup)
{ {
if (_batchNode) if (_batchNode)
{ {
_batchNode->removeSpriteFromAtlas((Sprite*)(child)); _batchNode->removeSpriteFromAtlas((Sprite*)(child));
} }
Node::removeChild(child, bCleanup); Node::removeChild(child, cleanup);
} }
void Sprite::removeAllChildrenWithCleanup(bool bCleanup) void Sprite::removeAllChildrenWithCleanup(bool cleanup)
{ {
if (_batchNode) if (_batchNode)
{ {
Object* pObject = NULL; Object* object = NULL;
CCARRAY_FOREACH(_children, pObject) CCARRAY_FOREACH(_children, object)
{ {
Sprite* child = dynamic_cast<Sprite*>(pObject); Sprite* child = dynamic_cast<Sprite*>(object);
if (child) if (child)
{ {
_batchNode->removeSpriteFromAtlas(child); _batchNode->removeSpriteFromAtlas(child);
@ -685,7 +684,7 @@ void Sprite::removeAllChildrenWithCleanup(bool bCleanup)
} }
} }
Node::removeAllChildrenWithCleanup(bCleanup); Node::removeAllChildrenWithCleanup(cleanup);
_hasChildren = false; _hasChildren = false;
} }
@ -694,23 +693,26 @@ void Sprite::sortAllChildren()
{ {
if (_reorderChildDirty) if (_reorderChildDirty)
{ {
int i = 0, j = 0, length = _children->data->num; int i = 0, j = 0, length = _children->count();
Node** x = (Node**)_children->data->arr;
Node *tempItem = NULL;
// insertion sort // insertion sort
for(i=1; i<length; i++) for(i=1; i<length; i++)
{ {
tempItem = x[i];
j = i-1; j = i-1;
auto tempI = static_cast<Node*>( _children->getObjectAtIndex(i) );
auto tempJ = static_cast<Node*>( _children->getObjectAtIndex(j) );
//continue moving element downwards while zOrder is smaller or when zOrder is the same but orderOfArrival is smaller //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while(j>=0 && ( tempItem->getZOrder() < x[j]->getZOrder() || ( tempItem->getZOrder() == x[j]->getZOrder() && tempItem->getOrderOfArrival() < x[j]->getOrderOfArrival() ) ) ) while(j>=0 && ( tempI->getZOrder() < tempJ->getZOrder() ||
( tempI->getZOrder() == tempJ->getZOrder() &&
tempI->getOrderOfArrival() < tempJ->getOrderOfArrival() ) ) )
{ {
x[j+1] = x[j]; _children->fastSetObject( tempJ, j+1 );
j = j-1; j = j-1;
if(j>=0)
tempJ = static_cast<Node*>( _children->getObjectAtIndex(j) );
} }
x[j+1] = tempItem; _children->fastSetObject(tempI, j+1);
} }
if ( _batchNode) if ( _batchNode)
@ -733,11 +735,11 @@ void Sprite::setReorderChildDirtyRecursively(void)
if ( ! _reorderChildDirty ) if ( ! _reorderChildDirty )
{ {
_reorderChildDirty = true; _reorderChildDirty = true;
Node* pNode = (Node*)_parent; Node* node = static_cast<Node*>(_parent);
while (pNode && pNode != _batchNode) while (node && node != _batchNode)
{ {
((Sprite*)pNode)->setReorderChildDirtyRecursively(); static_cast<Sprite*>(node)->setReorderChildDirtyRecursively();
pNode=pNode->getParent(); node=node->getParent();
} }
} }
} }
@ -750,10 +752,10 @@ void Sprite::setDirtyRecursively(bool bValue)
// recursively set dirty // recursively set dirty
if (_hasChildren) if (_hasChildren)
{ {
Object* pObject = NULL; Object* object = NULL;
CCARRAY_FOREACH(_children, pObject) CCARRAY_FOREACH(_children, object)
{ {
Sprite* child = dynamic_cast<Sprite*>(pObject); Sprite* child = dynamic_cast<Sprite*>(object);
if (child) if (child)
{ {
child->setDirtyRecursively(true); child->setDirtyRecursively(true);
@ -986,20 +988,20 @@ void Sprite::setDisplayFrameWithAnimationName(const char *animationName, int fra
CCASSERT(a, "CCSprite#setDisplayFrameWithAnimationName: Frame not found"); CCASSERT(a, "CCSprite#setDisplayFrameWithAnimationName: Frame not found");
AnimationFrame* frame = static_cast<AnimationFrame*>( a->getFrames()->objectAtIndex(frameIndex) ); AnimationFrame* frame = static_cast<AnimationFrame*>( a->getFrames()->getObjectAtIndex(frameIndex) );
CCASSERT(frame, "CCSprite#setDisplayFrame. Invalid frame"); CCASSERT(frame, "CCSprite#setDisplayFrame. Invalid frame");
setDisplayFrame(frame->getSpriteFrame()); setDisplayFrame(frame->getSpriteFrame());
} }
bool Sprite::isFrameDisplayed(SpriteFrame *pFrame) const bool Sprite::isFrameDisplayed(SpriteFrame *frame) const
{ {
Rect r = pFrame->getRect(); Rect r = frame->getRect();
return (r.equals(_rect) && return (r.equals(_rect) &&
pFrame->getTexture()->getName() == _texture->getName() && frame->getTexture()->getName() == _texture->getName() &&
pFrame->getOffset().equals(_unflippedOffsetPositionFromCenter)); frame->getOffset().equals(_unflippedOffsetPositionFromCenter));
} }
SpriteFrame* Sprite::displayFrame(void) SpriteFrame* Sprite::displayFrame(void)

View File

@ -24,7 +24,11 @@ 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 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "CCSpriteBatchNode.h" #include "CCSpriteBatchNode.h"
#include <algorithm>
#include "ccConfig.h" #include "ccConfig.h"
#include "CCSprite.h" #include "CCSprite.h"
#include "effects/CCGrid.h" #include "effects/CCGrid.h"
@ -226,7 +230,7 @@ void SpriteBatchNode::removeChild(Node *child, bool cleanup)
void SpriteBatchNode::removeChildAtIndex(unsigned int uIndex, bool bDoCleanup) void SpriteBatchNode::removeChildAtIndex(unsigned int uIndex, bool bDoCleanup)
{ {
removeChild((Sprite*)(_children->objectAtIndex(uIndex)), bDoCleanup); removeChild((Sprite*)(_children->getObjectAtIndex(uIndex)), bDoCleanup);
} }
void SpriteBatchNode::removeAllChildrenWithCleanup(bool bCleanup) void SpriteBatchNode::removeAllChildrenWithCleanup(bool bCleanup)
@ -241,30 +245,60 @@ void SpriteBatchNode::removeAllChildrenWithCleanup(bool bCleanup)
_textureAtlas->removeAllQuads(); _textureAtlas->removeAllQuads();
} }
#if CC_USE_ARRAY_VECTOR
static bool objectComparisonLess(const RCPtr<Object>& pp1, const RCPtr<Object>& pp2)
{
Object *p1 = static_cast<Object*>(pp1);
Object *p2 = static_cast<Object*>(pp2);
Node *n1 = static_cast<Node*>(p1);
Node *n2 = static_cast<Node*>(p2);
return( n1->getZOrder() < n2->getZOrder() ||
( n1->getZOrder() == n2->getZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() )
);
}
#else
static bool objectComparisonLess(Object* p1, Object* p2)
{
Node *n1 = static_cast<Node*>(p1);
Node *n2 = static_cast<Node*>(p2);
return( n1->getZOrder() < n2->getZOrder() ||
( n1->getZOrder() == n2->getZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() )
);
}
#endif
//override sortAllChildren //override sortAllChildren
void SpriteBatchNode::sortAllChildren() void SpriteBatchNode::sortAllChildren()
{ {
if (_reorderChildDirty) if (_reorderChildDirty)
{ {
int i = 0,j = 0,length = _children->data->num; #if 0
Node ** x = (Node**)_children->data->arr; int i = 0,j = 0,length = _children->count();
Node *tempItem = NULL;
//insertion sort // insertion sort
for(i=1; i<length; i++) for(i=1; i<length; i++)
{ {
tempItem = x[i];
j = i-1; j = i-1;
auto tempI = static_cast<Node*>( _children->getObjectAtIndex(i) );
auto tempJ = static_cast<Node*>( _children->getObjectAtIndex(j) );
//continue moving element downwards while zOrder is smaller or when zOrder is the same but orderOfArrival is smaller //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while(j>=0 && ( tempItem->getZOrder() < x[j]->getZOrder() || ( tempItem->getZOrder() == x[j]->getZOrder() && tempItem->getOrderOfArrival() < x[j]->getOrderOfArrival() ) ) ) while(j>=0 && ( tempI->getZOrder() < tempJ->getZOrder() ||
( tempI->getZOrder() == tempJ->getZOrder() &&
tempI->getOrderOfArrival() < tempJ->getOrderOfArrival() ) ) )
{ {
x[j+1] = x[j]; _children->fastSetObject( tempJ, j+1 );
j--; j = j-1;
if(j>=0)
tempJ = static_cast<Node*>( _children->getObjectAtIndex(j) );
} }
_children->fastSetObject(tempI, j+1);
x[j+1] = tempItem;
} }
#else
std::sort(std::begin(*_children), std::end(*_children), objectComparisonLess);
#endif
//sorted now check all children //sorted now check all children
if (_children->count() > 0) if (_children->count() > 0)
@ -313,7 +347,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex)
{ {
bool needNewIndex=true; bool needNewIndex=true;
if (static_cast<Sprite*>(array->data->arr[0])->getZOrder() >= 0) if (static_cast<Sprite*>(array->getObjectAtIndex(0) )->getZOrder() >= 0)
{ {
//all children are in front of the parent //all children are in front of the parent
oldIndex = sprite->getAtlasIndex(); oldIndex = sprite->getAtlasIndex();
@ -363,19 +397,13 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, int* curIndex)
void SpriteBatchNode::swap(int oldIndex, int newIndex) void SpriteBatchNode::swap(int oldIndex, int newIndex)
{ {
Object** x = _descendants->data->arr;
V3F_C4B_T2F_Quad* quads = _textureAtlas->getQuads(); V3F_C4B_T2F_Quad* quads = _textureAtlas->getQuads();
Object* tempItem = x[oldIndex];
V3F_C4B_T2F_Quad tempItemQuad=quads[oldIndex];
//update the index of other swapped item //update the index of other swapped item
((Sprite*) x[newIndex])->setAtlasIndex(oldIndex); static_cast<Sprite*>( _descendants->getObjectAtIndex(newIndex) )->setAtlasIndex(oldIndex);
x[oldIndex]=x[newIndex]; std::swap( quads[oldIndex], quads[newIndex] );
quads[oldIndex]=quads[newIndex]; _descendants->swap( oldIndex, newIndex );
x[newIndex]=tempItem;
quads[newIndex]=tempItemQuad;
} }
void SpriteBatchNode::reorderBatch(bool reorder) void SpriteBatchNode::reorderBatch(bool reorder)
@ -474,7 +502,7 @@ unsigned int SpriteBatchNode::highestAtlasIndexInChild(Sprite *pSprite)
} }
else else
{ {
return highestAtlasIndexInChild((Sprite*)(children->lastObject())); return highestAtlasIndexInChild((Sprite*)(children->getLastObject()));
} }
} }
@ -488,14 +516,14 @@ unsigned int SpriteBatchNode::lowestAtlasIndexInChild(Sprite *pSprite)
} }
else else
{ {
return lowestAtlasIndexInChild((Sprite*)(children->objectAtIndex(0))); return lowestAtlasIndexInChild((Sprite*)(children->getObjectAtIndex(0)));
} }
} }
unsigned int SpriteBatchNode::atlasIndexForChild(Sprite *sprite, int nZ) unsigned int SpriteBatchNode::atlasIndexForChild(Sprite *sprite, int nZ)
{ {
Array *pBrothers = sprite->getParent()->getChildren(); Array *pBrothers = sprite->getParent()->getChildren();
unsigned int uChildIndex = pBrothers->indexOfObject(sprite); unsigned int uChildIndex = pBrothers->getIndexOfObject(sprite);
// ignore parent Z if parent is spriteSheet // ignore parent Z if parent is spriteSheet
bool bIgnoreParent = (SpriteBatchNode*)(sprite->getParent()) == this; bool bIgnoreParent = (SpriteBatchNode*)(sprite->getParent()) == this;
@ -503,7 +531,7 @@ unsigned int SpriteBatchNode::atlasIndexForChild(Sprite *sprite, int nZ)
if (uChildIndex > 0 && if (uChildIndex > 0 &&
uChildIndex < UINT_MAX) uChildIndex < UINT_MAX)
{ {
pPrevious = (Sprite*)(pBrothers->objectAtIndex(uChildIndex - 1)); pPrevious = (Sprite*)(pBrothers->getObjectAtIndex(uChildIndex - 1));
} }
// first child of the sprite sheet // first child of the sprite sheet
@ -568,16 +596,14 @@ void SpriteBatchNode::insertChild(Sprite *pSprite, unsigned int uIndex)
V3F_C4B_T2F_Quad quad = pSprite->getQuad(); V3F_C4B_T2F_Quad quad = pSprite->getQuad();
_textureAtlas->insertQuad(&quad, uIndex); _textureAtlas->insertQuad(&quad, uIndex);
ccArray *descendantsData = _descendants->data; _descendants->insertObject(pSprite, uIndex);
ccArrayInsertObjectAtIndex(descendantsData, pSprite, uIndex);
// update indices // update indices
unsigned int i = uIndex+1; unsigned int i = uIndex+1;
Sprite* child = nullptr; Sprite* child = nullptr;
for(; i<descendantsData->num; i++){ for(; i<_descendants->count(); i++){
child = static_cast<Sprite*>(descendantsData->arr[i]); child = static_cast<Sprite*>(_descendants->getObjectAtIndex(i));
child->setAtlasIndex(child->getAtlasIndex() + 1); child->setAtlasIndex(child->getAtlasIndex() + 1);
} }
@ -602,11 +628,8 @@ void SpriteBatchNode::appendChild(Sprite* sprite)
increaseAtlasCapacity(); increaseAtlasCapacity();
} }
ccArray *descendantsData = _descendants->data; _descendants->addObject(sprite);
unsigned int index=_descendants->count()-1;
ccArrayAppendObjectWithResize(descendantsData, sprite);
unsigned int index=descendantsData->num-1;
sprite->setAtlasIndex(index); sprite->setAtlasIndex(index);
@ -631,17 +654,17 @@ void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite)
// Cleanup sprite. It might be reused (issue #569) // Cleanup sprite. It might be reused (issue #569)
sprite->setBatchNode(NULL); sprite->setBatchNode(NULL);
unsigned int uIndex = _descendants->indexOfObject(sprite); int index = _descendants->getIndexOfObject(sprite);
if (uIndex != UINT_MAX) if (index != UINT_MAX)
{ {
_descendants->removeObjectAtIndex(uIndex); _descendants->removeObjectAtIndex(index);
// update all sprites beyond this one // update all sprites beyond this one
unsigned int count = _descendants->count(); int count = _descendants->count();
for(; uIndex < count; ++uIndex) for(; index < count; ++index)
{ {
Sprite* s = (Sprite*)(_descendants->objectAtIndex(uIndex)); Sprite* s = static_cast<Sprite*>(_descendants->getObjectAtIndex(index));
s->setAtlasIndex( s->getAtlasIndex() - 1 ); s->setAtlasIndex( s->getAtlasIndex() - 1 );
} }
} }
@ -650,10 +673,10 @@ void SpriteBatchNode::removeSpriteFromAtlas(Sprite *sprite)
Array *children = sprite->getChildren(); Array *children = sprite->getChildren();
if (children && children->count() > 0) if (children && children->count() > 0)
{ {
Object* pObject = NULL; Object* object = NULL;
CCARRAY_FOREACH(children, pObject) CCARRAY_FOREACH(children, object)
{ {
Sprite* child = static_cast<Sprite*>(pObject); Sprite* child = static_cast<Sprite*>(object);
if (child) if (child)
{ {
removeSpriteFromAtlas(child); removeSpriteFromAtlas(child);

View File

@ -116,7 +116,7 @@ bool SpriteFrame::initWithTextureFilename(const char* filename, const Rect& rect
SpriteFrame::~SpriteFrame(void) SpriteFrame::~SpriteFrame(void)
{ {
CCLOGINFO("cocos2d: deallocing %p", this); CCLOGINFO("deallocing SpriteFrame: %p", this);
CC_SAFE_RELEASE(_texture); CC_SAFE_RELEASE(_texture);
} }

View File

@ -64,7 +64,9 @@ void SpriteFrameCache::destroyInstance()
bool SpriteFrameCache::init(void) bool SpriteFrameCache::init(void)
{ {
_spriteFrames= new Dictionary(); _spriteFrames= new Dictionary();
_spriteFrames->init();
_spriteFramesAliases = new Dictionary(); _spriteFramesAliases = new Dictionary();
_spriteFramesAliases->init();
_loadedFileNames = new std::set<std::string>(); _loadedFileNames = new std::set<std::string>();
return true; return true;
} }
@ -207,8 +209,6 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist, Texture2D *
Dictionary *dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str()); Dictionary *dict = Dictionary::createWithContentsOfFileThreadSafe(fullPath.c_str());
addSpriteFramesWithDictionary(dict, pobTexture); addSpriteFramesWithDictionary(dict, pobTexture);
dict->release();
} }
void SpriteFrameCache::addSpriteFramesWithFile(const char* plist, const char* textureFileName) void SpriteFrameCache::addSpriteFramesWithFile(const char* plist, const char* textureFileName)
@ -237,7 +237,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist)
string texturePath(""); string texturePath("");
Dictionary* metadataDict = (Dictionary*)dict->objectForKey("metadata"); Dictionary* metadataDict = static_cast<Dictionary*>( dict->objectForKey("metadata") );
if (metadataDict) if (metadataDict)
{ {
// try to read texture file name from meta data // try to read texture file name from meta data
@ -275,10 +275,7 @@ void SpriteFrameCache::addSpriteFramesWithFile(const char *pszPlist)
{ {
CCLOG("cocos2d: SpriteFrameCache: Couldn't load texture"); CCLOG("cocos2d: SpriteFrameCache: Couldn't load texture");
} }
dict->release();
} }
} }
void SpriteFrameCache::addSpriteFrame(SpriteFrame *pobFrame, const char *pszFrameName) void SpriteFrameCache::addSpriteFrame(SpriteFrame *pobFrame, const char *pszFrameName)
@ -354,8 +351,6 @@ void SpriteFrameCache::removeSpriteFramesFromFile(const char* plist)
{ {
_loadedFileNames->erase(ret); _loadedFileNames->erase(ret);
} }
dict->release();
} }
void SpriteFrameCache::removeSpriteFramesFromDictionary(Dictionary* dictionary) void SpriteFrameCache::removeSpriteFramesFromDictionary(Dictionary* dictionary)

View File

@ -74,7 +74,7 @@ void NotificationCenter::purgeNotificationCenter(void)
// //
// internal functions // internal functions
// //
bool NotificationCenter::observerExisted(Object *target,const char *name) bool NotificationCenter::observerExisted(Object *target,const char *name, Object *sender)
{ {
Object* obj = NULL; Object* obj = NULL;
CCARRAY_FOREACH(_observers, obj) CCARRAY_FOREACH(_observers, obj)
@ -83,7 +83,7 @@ bool NotificationCenter::observerExisted(Object *target,const char *name)
if (!observer) if (!observer)
continue; continue;
if (!strcmp(observer->getName(),name) && observer->getTarget() == target) if (!strcmp(observer->getName(),name) && observer->getTarget() == target && observer->getSender() == sender)
return true; return true;
} }
return false; return false;
@ -95,12 +95,12 @@ bool NotificationCenter::observerExisted(Object *target,const char *name)
void NotificationCenter::addObserver(Object *target, void NotificationCenter::addObserver(Object *target,
SEL_CallFuncO selector, SEL_CallFuncO selector,
const char *name, const char *name,
Object *obj) Object *sender)
{ {
if (this->observerExisted(target, name)) if (this->observerExisted(target, name, sender))
return; return;
NotificationObserver *observer = new NotificationObserver(target, selector, name, obj); NotificationObserver *observer = new NotificationObserver(target, selector, name, sender);
if (!observer) if (!observer)
return; return;
@ -149,7 +149,7 @@ int NotificationCenter::removeAllObservers(Object *target)
void NotificationCenter::registerScriptObserver( Object *target, int handler,const char* name) void NotificationCenter::registerScriptObserver( Object *target, int handler,const char* name)
{ {
if (this->observerExisted(target, name)) if (this->observerExisted(target, name, NULL))
return; return;
NotificationObserver *observer = new NotificationObserver(target, NULL, name, NULL); NotificationObserver *observer = new NotificationObserver(target, NULL, name, NULL);
@ -177,7 +177,7 @@ void NotificationCenter::unregisterScriptObserver(Object *target,const char* nam
} }
} }
void NotificationCenter::postNotification(const char *name, Object *object) void NotificationCenter::postNotification(const char *name, Object *sender)
{ {
Array* ObserversCopy = Array::createWithCapacity(_observers->count()); Array* ObserversCopy = Array::createWithCapacity(_observers->count());
ObserversCopy->addObjectsFromArray(_observers); ObserversCopy->addObjectsFromArray(_observers);
@ -188,7 +188,7 @@ void NotificationCenter::postNotification(const char *name, Object *object)
if (!observer) if (!observer)
continue; continue;
if (!strcmp(name,observer->getName()) && (observer->getObject() == object || observer->getObject() == NULL || object == NULL)) if (!strcmp(name,observer->getName()) && (observer->getSender() == sender || observer->getSender() == NULL || sender == NULL))
{ {
if (0 != observer->getHandler()) if (0 != observer->getHandler())
{ {
@ -198,7 +198,7 @@ void NotificationCenter::postNotification(const char *name, Object *object)
} }
else else
{ {
observer->performSelector(object); observer->performSelector(sender);
} }
} }
} }
@ -241,11 +241,11 @@ int NotificationCenter::getObserverHandlerByName(const char* name)
NotificationObserver::NotificationObserver(Object *target, NotificationObserver::NotificationObserver(Object *target,
SEL_CallFuncO selector, SEL_CallFuncO selector,
const char *name, const char *name,
Object *obj) Object *sender)
{ {
_target = target; _target = target;
_selector = selector; _selector = selector;
_object = obj; _sender = sender;
_name = name; _name = name;
_handler = 0; _handler = 0;
@ -256,14 +256,14 @@ NotificationObserver::~NotificationObserver()
} }
void NotificationObserver::performSelector(Object *obj) void NotificationObserver::performSelector(Object *sender)
{ {
if (_target) if (_target)
{ {
if (obj) { if (sender) {
(_target->*_selector)(obj); (_target->*_selector)(sender);
} else { } else {
(_target->*_selector)(_object); (_target->*_selector)(_sender);
} }
} }
} }
@ -283,9 +283,9 @@ const char* NotificationObserver::getName() const
return _name.c_str(); return _name.c_str();
} }
Object* NotificationObserver::getObject() const Object* NotificationObserver::getSender() const
{ {
return _object; return _sender;
} }
int NotificationObserver::getHandler() const int NotificationObserver::getHandler() const

View File

@ -58,12 +58,12 @@ public:
* @param target The target which wants to observe notification events. * @param target The target which wants to observe notification events.
* @param selector The callback function which will be invoked when the specified notification event was posted. * @param selector The callback function which will be invoked when the specified notification event was posted.
* @param name The name of this notification. * @param name The name of this notification.
* @param obj The extra parameter which will be passed to the callback function. * @param sender The object whose notifications the target wants to receive. Only notifications sent by this sender are delivered to the target. NULL means that the sender is not used to decide whether to deliver the notification to target.
*/ */
void addObserver(Object *target, void addObserver(Object *target,
SEL_CallFuncO selector, SEL_CallFuncO selector,
const char *name, const char *name,
Object *obj); Object *sender);
/** @brief Removes the observer by the specified target and name. /** @brief Removes the observer by the specified target and name.
* @param target The target of this notification. * @param target The target of this notification.
@ -93,9 +93,9 @@ public:
/** @brief Posts one notification event by name. /** @brief Posts one notification event by name.
* @param name The name of this notification. * @param name The name of this notification.
* @param object The extra parameter. * @param sender The object posting the notification. Can be NULL
*/ */
void postNotification(const char *name, Object *object); void postNotification(const char *name, Object *sender);
/** @brief Gets script handler. /** @brief Gets script handler.
* @note Only supports Lua Binding now. * @note Only supports Lua Binding now.
@ -112,7 +112,7 @@ private:
// internal functions // internal functions
// Check whether the observer exists by the specified target and name. // Check whether the observer exists by the specified target and name.
bool observerExisted(Object *target,const char *name); bool observerExisted(Object *target,const char *name, Object *sender);
// variables // variables
// //
@ -127,24 +127,24 @@ public:
* @param target The target which wants to observer notification events. * @param target The target which wants to observer notification events.
* @param selector The callback function which will be invoked when the specified notification event was posted. * @param selector The callback function which will be invoked when the specified notification event was posted.
* @param name The name of this notification. * @param name The name of this notification.
* @param obj The extra parameter which will be passed to the callback function. * @param sender The object whose notifications the target wants to receive. Only notifications sent by this sender are delivered to the target. NULL means that the sender is not used to decide whether to deliver the notification to target.
*/ */
NotificationObserver(Object *target, NotificationObserver(Object *target,
SEL_CallFuncO selector, SEL_CallFuncO selector,
const char *name, const char *name,
Object *obj); Object *sender);
/** NotificationObserver destructor function */ /** NotificationObserver destructor function */
~NotificationObserver(); ~NotificationObserver();
/** Invokes the callback function of this observer */ /** Invokes the callback function of this observer */
void performSelector(Object *obj); void performSelector(Object *sender);
// Getters / Setters // Getters / Setters
Object* getTarget() const; Object* getTarget() const;
SEL_CallFuncO getSelector() const; SEL_CallFuncO getSelector() const;
const char* getName() const; const char* getName() const;
Object* getObject() const; Object* getSender() const;
int getHandler() const; int getHandler() const;
void setHandler(int handler); void setHandler(int handler);
@ -152,7 +152,7 @@ private:
Object* _target; Object* _target;
SEL_CallFuncO _selector; SEL_CallFuncO _selector;
std::string _name; std::string _name;
Object* _object; Object* _sender;
int _handler; int _handler;
}; };

View File

@ -24,6 +24,8 @@ THE SOFTWARE.
****************************************************************************/ ****************************************************************************/
#include "CCProfiling.h" #include "CCProfiling.h"
#include <chrono>
using namespace std; using namespace std;
NS_CC_BEGIN NS_CC_BEGIN
@ -77,6 +79,7 @@ void Profiler::releaseAllTimers()
bool Profiler::init() bool Profiler::init()
{ {
_activeTimers = new Dictionary(); _activeTimers = new Dictionary();
_activeTimers->init();
return true; return true;
} }
@ -97,16 +100,19 @@ void Profiler::displayTimers()
// implementation of ProfilingTimer // implementation of ProfilingTimer
ProfilingTimer::ProfilingTimer()
: numberOfCalls(0)
, _averageTime1(0)
, _averageTime2(0)
, totalTime(0)
, minTime(100000000)
, maxTime(0)
{
}
bool ProfilingTimer::initWithName(const char* timerName) bool ProfilingTimer::initWithName(const char* timerName)
{ {
_nameStr = timerName; _nameStr = timerName;
numberOfCalls = 0;
_averageTime = 0.0;
totalTime = 0.0;
minTime = 10000.0;
maxTime = 0.0;
gettimeofday((struct timeval *)&_startTime, NULL);
return true; return true;
} }
@ -117,33 +123,35 @@ ProfilingTimer::~ProfilingTimer(void)
const char* ProfilingTimer::description() const const char* ProfilingTimer::description() const
{ {
static char s_szDesciption[256] = {0}; static char s_desciption[512] = {0};
sprintf(s_szDesciption, "%s: avg time, %fms", _nameStr.c_str(), _averageTime);
return s_szDesciption; sprintf(s_desciption, "%s ::\tavg1: %dµ,\tavg2: %dµ,\tmin: %dµ,\tmax: %dµ,\ttotal: %.2fs,\tnr calls: %d", _nameStr.c_str(), _averageTime1, _averageTime2, minTime, maxTime, totalTime/1000000., numberOfCalls);
return s_desciption;
} }
void ProfilingTimer::reset() void ProfilingTimer::reset()
{ {
numberOfCalls = 0; numberOfCalls = 0;
_averageTime = 0; _averageTime1 = 0;
_averageTime2 = 0;
totalTime = 0; totalTime = 0;
minTime = 10000; minTime = 100000000;
maxTime = 0; maxTime = 0;
gettimeofday((struct timeval *)&_startTime, NULL); _startTime = chrono::high_resolution_clock::now();
} }
void ProfilingBeginTimingBlock(const char *timerName) void ProfilingBeginTimingBlock(const char *timerName)
{ {
Profiler* p = Profiler::getInstance(); Profiler* p = Profiler::getInstance();
ProfilingTimer* timer = (ProfilingTimer*)p->_activeTimers->objectForKey(timerName); ProfilingTimer* timer = static_cast<ProfilingTimer*>( p->_activeTimers->objectForKey(timerName) );
if( ! timer ) if( ! timer )
{ {
timer = p->createAndAddTimerWithName(timerName); timer = p->createAndAddTimerWithName(timerName);
} }
gettimeofday(&timer->_startTime, NULL);
timer->numberOfCalls++; timer->numberOfCalls++;
timer->_startTime = chrono::high_resolution_clock::now();
} }
void ProfilingEndTimingBlock(const char *timerName) void ProfilingEndTimingBlock(const char *timerName)
@ -153,15 +161,13 @@ void ProfilingEndTimingBlock(const char *timerName)
CCASSERT(timer, "CCProfilingTimer not found"); CCASSERT(timer, "CCProfilingTimer not found");
struct timeval currentTime; auto now = chrono::high_resolution_clock::now();
gettimeofday(&currentTime, NULL);
double duration = (currentTime.tv_sec*1000.0 + currentTime.tv_usec/1000.0) - int duration = chrono::duration_cast<chrono::microseconds>(now - timer->_startTime).count();
(timer->_startTime.tv_sec*1000.0 + timer->_startTime.tv_usec/1000.0);
// milliseconds
timer->_averageTime = (timer->_averageTime + duration) / 2.0f;
timer->totalTime += duration; timer->totalTime += duration;
timer->_averageTime1 = (timer->_averageTime1 + duration) / 2.0f;
timer->_averageTime2 = timer->totalTime / timer->numberOfCalls;
timer->maxTime = MAX( timer->maxTime, duration); timer->maxTime = MAX( timer->maxTime, duration);
timer->minTime = MIN( timer->minTime, duration); timer->minTime = MIN( timer->minTime, duration);

View File

@ -25,10 +25,11 @@ THE SOFTWARE.
#ifndef __SUPPORT_CCPROFILING_H__ #ifndef __SUPPORT_CCPROFILING_H__
#define __SUPPORT_CCPROFILING_H__ #define __SUPPORT_CCPROFILING_H__
#include <string>
#include <chrono>
#include "ccConfig.h" #include "ccConfig.h"
#include "cocoa/CCObject.h" #include "cocoa/CCObject.h"
#include "cocoa/CCDictionary.h" #include "cocoa/CCDictionary.h"
#include <string>
NS_CC_BEGIN NS_CC_BEGIN
@ -72,22 +73,25 @@ public:
class ProfilingTimer : public Object class ProfilingTimer : public Object
{ {
public: public:
bool initWithName(const char* timerName); ProfilingTimer();
~ProfilingTimer(void); ~ProfilingTimer(void);
bool initWithName(const char* timerName);
const char* description(void) const; const char* description(void) const;
inline struct timeval * getStartTime(void) { return &_startTime; }; inline const std::chrono::high_resolution_clock::time_point& getStartTime(void) { return _startTime; };
inline void setAverageTime(double value) { _averageTime = value; }
inline double getAverageTime(void) { return _averageTime; }
/** resets the timer properties */ /** resets the timer properties */
void reset(); void reset();
std::string _nameStr; std::string _nameStr;
struct timeval _startTime; std::chrono::high_resolution_clock::time_point _startTime;
double _averageTime; int _averageTime1;
double minTime; int _averageTime2;
double maxTime; int minTime;
double totalTime; int maxTime;
unsigned int numberOfCalls; long long totalTime;
int numberOfCalls;
}; };
extern void ProfilingBeginTimingBlock(const char *timerName); extern void ProfilingBeginTimingBlock(const char *timerName);

View File

@ -28,11 +28,13 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
const int CC_INVALID_INDEX = -1;
/** Allocates and initializes a new array with specified capacity */ /** Allocates and initializes a new array with specified capacity */
ccArray* ccArrayNew(unsigned int capacity) ccArray* ccArrayNew(int capacity)
{ {
if (capacity == 0) if (capacity == 0)
capacity = 1; capacity = 7;
ccArray *arr = (ccArray*)malloc( sizeof(ccArray) ); ccArray *arr = (ccArray*)malloc( sizeof(ccArray) );
arr->num = 0; arr->num = 0;
@ -66,17 +68,21 @@ void ccArrayDoubleCapacity(ccArray *arr)
arr->arr = newArr; arr->arr = newArr;
} }
void ccArrayEnsureExtraCapacity(ccArray *arr, unsigned int extra) void ccArrayEnsureExtraCapacity(ccArray *arr, int extra)
{ {
while (arr->max < arr->num + extra) while (arr->max < arr->num + extra)
{ {
// CCLOG("cocos2d: ccCArray: resizing ccArray capacity from [%lu] to [%lu].",
// (long) arr->max,
// (long) arr->max*2);
ccArrayDoubleCapacity(arr); ccArrayDoubleCapacity(arr);
} }
} }
void ccArrayShrink(ccArray *arr) void ccArrayShrink(ccArray *arr)
{ {
unsigned int newSize = 0; int newSize = 0;
//only resize when necessary //only resize when necessary
if (arr->max > arr->num && !(arr->num==0 && arr->max==1)) if (arr->max > arr->num && !(arr->num==0 && arr->max==1))
@ -98,13 +104,14 @@ void ccArrayShrink(ccArray *arr)
} }
/** Returns index of first occurrence of object, CC_INVALID_INDEX if object not found. */ /** Returns index of first occurrence of object, CC_INVALID_INDEX if object not found. */
unsigned int ccArrayGetIndexOfObject(ccArray *arr, Object* object) int ccArrayGetIndexOfObject(ccArray *arr, Object* object)
{ {
const unsigned int arrNum = arr->num; const int arrNum = arr->num;
Object** ptr = arr->arr; Object** ptr = arr->arr;
for(unsigned int i = 0; i < arrNum; ++i, ++ptr) for(int i = 0; i < arrNum; ++i, ++ptr)
{ {
if( *ptr == object ) return i; if( *ptr == object )
return i;
} }
return CC_INVALID_INDEX; return CC_INVALID_INDEX;
@ -136,7 +143,7 @@ void ccArrayAppendObjectWithResize(ccArray *arr, Object* object)
enough capacity. */ enough capacity. */
void ccArrayAppendArray(ccArray *arr, ccArray *plusArr) void ccArrayAppendArray(ccArray *arr, ccArray *plusArr)
{ {
for(unsigned int i = 0; i < plusArr->num; i++) for(int i = 0; i < plusArr->num; i++)
{ {
ccArrayAppendObject(arr, plusArr->arr[i]); ccArrayAppendObject(arr, plusArr->arr[i]);
} }
@ -150,14 +157,14 @@ void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr)
} }
/** Inserts an object at index */ /** Inserts an object at index */
void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, unsigned int index) void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, int index)
{ {
CCASSERT(index<=arr->num, "Invalid index. Out of bounds"); CCASSERT(index<=arr->num, "Invalid index. Out of bounds");
CCASSERT(object != NULL, "Invalid parameter!"); CCASSERT(object != NULL, "Invalid parameter!");
ccArrayEnsureExtraCapacity(arr, 1); ccArrayEnsureExtraCapacity(arr, 1);
unsigned int remaining = arr->num - index; int remaining = arr->num - index;
if( remaining > 0) if( remaining > 0)
{ {
memmove((void *)&arr->arr[index+1], (void *)&arr->arr[index], sizeof(Object*) * remaining ); memmove((void *)&arr->arr[index+1], (void *)&arr->arr[index], sizeof(Object*) * remaining );
@ -169,10 +176,10 @@ void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, unsigned int index
} }
/** Swaps two objects */ /** Swaps two objects */
void ccArraySwapObjectsAtIndexes(ccArray *arr, unsigned int index1, unsigned int index2) void ccArraySwapObjectsAtIndexes(ccArray *arr, int index1, int index2)
{ {
CCASSERT(index1 < arr->num, "(1) Invalid index. Out of bounds"); CCASSERT(index1>=0 && index1 < arr->num, "(1) Invalid index. Out of bounds");
CCASSERT(index2 < arr->num, "(2) Invalid index. Out of bounds"); CCASSERT(index2>=0 && index2 < arr->num, "(2) Invalid index. Out of bounds");
Object* object1 = arr->arr[index1]; Object* object1 = arr->arr[index1];
@ -191,9 +198,9 @@ void ccArrayRemoveAllObjects(ccArray *arr)
/** Removes object at specified index and pushes back all subsequent objects. /** Removes object at specified index and pushes back all subsequent objects.
Behavior undefined if index outside [0, num-1]. */ Behavior undefined if index outside [0, num-1]. */
void ccArrayRemoveObjectAtIndex(ccArray *arr, unsigned int index, bool bReleaseObj/* = true*/) void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj/* = true*/)
{ {
CCASSERT(arr && arr->num > 0 && index < arr->num, "Invalid index. Out of bounds"); CCASSERT(arr && arr->num > 0 && index>=0 && index < arr->num, "Invalid index. Out of bounds");
if (bReleaseObj) if (bReleaseObj)
{ {
CC_SAFE_RELEASE(arr->arr[index]); CC_SAFE_RELEASE(arr->arr[index]);
@ -201,7 +208,7 @@ void ccArrayRemoveObjectAtIndex(ccArray *arr, unsigned int index, bool bReleaseO
arr->num--; arr->num--;
unsigned int remaining = arr->num - index; int remaining = arr->num - index;
if(remaining>0) if(remaining>0)
{ {
memmove((void *)&arr->arr[index], (void *)&arr->arr[index+1], remaining * sizeof(Object*)); memmove((void *)&arr->arr[index], (void *)&arr->arr[index+1], remaining * sizeof(Object*));
@ -211,16 +218,16 @@ void ccArrayRemoveObjectAtIndex(ccArray *arr, unsigned int index, bool bReleaseO
/** Removes object at specified index and fills the gap with the last object, /** Removes object at specified index and fills the gap with the last object,
thereby avoiding the need to push back subsequent objects. thereby avoiding the need to push back subsequent objects.
Behavior undefined if index outside [0, num-1]. */ Behavior undefined if index outside [0, num-1]. */
void ccArrayFastRemoveObjectAtIndex(ccArray *arr, unsigned int index) void ccArrayFastRemoveObjectAtIndex(ccArray *arr, int index)
{ {
CC_SAFE_RELEASE(arr->arr[index]); CC_SAFE_RELEASE(arr->arr[index]);
unsigned int last = --arr->num; int last = --arr->num;
arr->arr[index] = arr->arr[last]; arr->arr[index] = arr->arr[last];
} }
void ccArrayFastRemoveObject(ccArray *arr, Object* object) void ccArrayFastRemoveObject(ccArray *arr, Object* object)
{ {
unsigned int index = ccArrayGetIndexOfObject(arr, object); int index = ccArrayGetIndexOfObject(arr, object);
if (index != CC_INVALID_INDEX) if (index != CC_INVALID_INDEX)
{ {
ccArrayFastRemoveObjectAtIndex(arr, index); ccArrayFastRemoveObjectAtIndex(arr, index);
@ -231,7 +238,7 @@ void ccArrayFastRemoveObject(ccArray *arr, Object* object)
found the function has no effect. */ found the function has no effect. */
void ccArrayRemoveObject(ccArray *arr, Object* object, bool bReleaseObj/* = true*/) void ccArrayRemoveObject(ccArray *arr, Object* object, bool bReleaseObj/* = true*/)
{ {
unsigned int index = ccArrayGetIndexOfObject(arr, object); int index = ccArrayGetIndexOfObject(arr, object);
if (index != CC_INVALID_INDEX) if (index != CC_INVALID_INDEX)
{ {
ccArrayRemoveObjectAtIndex(arr, index, bReleaseObj); ccArrayRemoveObjectAtIndex(arr, index, bReleaseObj);
@ -242,7 +249,7 @@ void ccArrayRemoveObject(ccArray *arr, Object* object, bool bReleaseObj/* = true
first matching instance in arr will be removed. */ first matching instance in arr will be removed. */
void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr) void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr)
{ {
for(unsigned int i = 0; i < minusArr->num; i++) for(int i = 0; i < minusArr->num; i++)
{ {
ccArrayRemoveObject(arr, minusArr->arr[i]); ccArrayRemoveObject(arr, minusArr->arr[i]);
} }
@ -252,8 +259,8 @@ void ccArrayRemoveArray(ccArray *arr, ccArray *minusArr)
matching instances in arr will be removed. */ matching instances in arr will be removed. */
void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr) void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr)
{ {
unsigned int back = 0; int back = 0;
unsigned int i = 0; int i = 0;
for( i = 0; i < arr->num; i++) for( i = 0; i < arr->num; i++)
{ {
@ -275,11 +282,11 @@ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr)
// #pragma mark ccCArray for Values (c structures) // #pragma mark ccCArray for Values (c structures)
/** Allocates and initializes a new C array with specified capacity */ /** Allocates and initializes a new C array with specified capacity */
ccCArray* ccCArrayNew(unsigned int capacity) ccCArray* ccCArrayNew(int capacity)
{ {
if (capacity == 0) if (capacity == 0)
{ {
capacity = 1; capacity = 7;
} }
ccCArray *arr = (ccCArray*)malloc( sizeof(ccCArray) ); ccCArray *arr = (ccCArray*)malloc( sizeof(ccCArray) );
@ -310,19 +317,18 @@ void ccCArrayDoubleCapacity(ccCArray *arr)
} }
/** Increases array capacity such that max >= num + extra. */ /** Increases array capacity such that max >= num + extra. */
void ccCArrayEnsureExtraCapacity(ccCArray *arr, unsigned int extra) void ccCArrayEnsureExtraCapacity(ccCArray *arr, int extra)
{ {
ccArrayEnsureExtraCapacity((ccArray*)arr,extra); ccArrayEnsureExtraCapacity((ccArray*)arr,extra);
} }
/** Returns index of first occurrence of value, CC_INVALID_INDEX if value not found. */ /** Returns index of first occurrence of value, CC_INVALID_INDEX if value not found. */
unsigned int ccCArrayGetIndexOfValue(ccCArray *arr, void* value) int ccCArrayGetIndexOfValue(ccCArray *arr, void* value)
{ {
unsigned int i; for( int i = 0; i < arr->num; i++)
for( i = 0; i < arr->num; i++)
{ {
if( arr->arr[i] == value ) return i; if( arr->arr[i] == value )
return i;
} }
return CC_INVALID_INDEX; return CC_INVALID_INDEX;
} }
@ -334,11 +340,11 @@ bool ccCArrayContainsValue(ccCArray *arr, void* value)
} }
/** Inserts a value at a certain position. Behavior undefined if array doesn't have enough capacity */ /** Inserts a value at a certain position. Behavior undefined if array doesn't have enough capacity */
void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, unsigned int index) void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, int index)
{ {
CCASSERT( index < arr->max, "ccCArrayInsertValueAtIndex: invalid index"); CCASSERT( index < arr->max, "ccCArrayInsertValueAtIndex: invalid index");
unsigned int remaining = arr->num - index; int remaining = arr->num - index;
// make sure it has enough capacity // make sure it has enough capacity
if (arr->num + 1 == arr->max) if (arr->num + 1 == arr->max)
{ {
@ -379,9 +385,7 @@ void ccCArrayAppendValueWithResize(ccCArray *arr, void* value)
enough capacity. */ enough capacity. */
void ccCArrayAppendArray(ccCArray *arr, ccCArray *plusArr) void ccCArrayAppendArray(ccCArray *arr, ccCArray *plusArr)
{ {
unsigned int i; for( int i = 0; i < plusArr->num; i++)
for( i = 0; i < plusArr->num; i++)
{ {
ccCArrayAppendValue(arr, plusArr->arr[i]); ccCArrayAppendValue(arr, plusArr->arr[i]);
} }
@ -404,11 +408,9 @@ void ccCArrayRemoveAllValues(ccCArray *arr)
Behavior undefined if index outside [0, num-1]. Behavior undefined if index outside [0, num-1].
@since v0.99.4 @since v0.99.4
*/ */
void ccCArrayRemoveValueAtIndex(ccCArray *arr, unsigned int index) void ccCArrayRemoveValueAtIndex(ccCArray *arr, int index)
{ {
unsigned int last; for( int last = --arr->num; index < last; index++)
for( last = --arr->num; index < last; index++)
{ {
arr->arr[index] = arr->arr[index + 1]; arr->arr[index] = arr->arr[index + 1];
} }
@ -419,9 +421,9 @@ void ccCArrayRemoveValueAtIndex(ccCArray *arr, unsigned int index)
Behavior undefined if index outside [0, num-1]. Behavior undefined if index outside [0, num-1].
@since v0.99.4 @since v0.99.4
*/ */
void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, unsigned int index) void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, int index)
{ {
unsigned int last = --arr->num; int last = --arr->num;
arr->arr[index] = arr->arr[last]; arr->arr[index] = arr->arr[last];
} }
@ -430,7 +432,7 @@ void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, unsigned int index)
*/ */
void ccCArrayRemoveValue(ccCArray *arr, void* value) void ccCArrayRemoveValue(ccCArray *arr, void* value)
{ {
unsigned int index = ccCArrayGetIndexOfValue(arr, value); int index = ccCArrayGetIndexOfValue(arr, value);
if (index != CC_INVALID_INDEX) if (index != CC_INVALID_INDEX)
{ {
ccCArrayRemoveValueAtIndex(arr, index); ccCArrayRemoveValueAtIndex(arr, index);
@ -442,7 +444,7 @@ void ccCArrayRemoveValue(ccCArray *arr, void* value)
*/ */
void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr) void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr)
{ {
for(unsigned int i = 0; i < minusArr->num; i++) for(int i = 0; i < minusArr->num; i++)
{ {
ccCArrayRemoveValue(arr, minusArr->arr[i]); ccCArrayRemoveValue(arr, minusArr->arr[i]);
} }
@ -453,9 +455,9 @@ void ccCArrayRemoveArray(ccCArray *arr, ccCArray *minusArr)
*/ */
void ccCArrayFullRemoveArray(ccCArray *arr, ccCArray *minusArr) void ccCArrayFullRemoveArray(ccCArray *arr, ccCArray *minusArr)
{ {
unsigned int back = 0; int back = 0;
for(unsigned int i = 0; i < arr->num; i++) for(int i = 0; i < arr->num; i++)
{ {
if( ccCArrayContainsValue(minusArr, arr->arr[i]) ) if( ccCArrayContainsValue(minusArr, arr->arr[i]) )
{ {

View File

@ -51,20 +51,20 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
#define CC_INVALID_INDEX 0xffffffff extern const int CC_INVALID_INDEX;
// Easy integration // Easy integration
#define CCARRAYDATA_FOREACH(__array__, __object__) \ #define CCARRAYDATA_FOREACH(__array__, __object__) \
__object__=__array__->arr[0]; for(unsigned int i=0, num=__array__->num; i<num; i++, __object__=__array__->arr[i]) \ __object__=__array__->arr[0]; for(int i=0, num=__array__->num; i<num; i++, __object__=__array__->arr[i]) \
typedef struct _ccArray { typedef struct _ccArray {
unsigned int num, max; int num, max;
Object** arr; Object** arr;
} ccArray; } ccArray;
/** Allocates and initializes a new array with specified capacity */ /** Allocates and initializes a new array with specified capacity */
ccArray* ccArrayNew(unsigned int capacity); ccArray* ccArrayNew(int capacity);
/** Frees array after removing all remaining objects. Silently ignores nil arr. */ /** Frees array after removing all remaining objects. Silently ignores nil arr. */
void ccArrayFree(ccArray*& arr); void ccArrayFree(ccArray*& arr);
@ -73,13 +73,13 @@ void ccArrayFree(ccArray*& arr);
void ccArrayDoubleCapacity(ccArray *arr); void ccArrayDoubleCapacity(ccArray *arr);
/** Increases array capacity such that max >= num + extra. */ /** Increases array capacity such that max >= num + extra. */
void ccArrayEnsureExtraCapacity(ccArray *arr, unsigned int extra); void ccArrayEnsureExtraCapacity(ccArray *arr, int extra);
/** shrinks the array so the memory footprint corresponds with the number of items */ /** shrinks the array so the memory footprint corresponds with the number of items */
void ccArrayShrink(ccArray *arr); void ccArrayShrink(ccArray *arr);
/** Returns index of first occurrence of object, NSNotFound if object not found. */ /** Returns index of first occurrence of object, NSNotFound if object not found. */
unsigned int ccArrayGetIndexOfObject(ccArray *arr, Object* object); int ccArrayGetIndexOfObject(ccArray *arr, Object* object);
/** Returns a Boolean value that indicates whether object is present in array. */ /** Returns a Boolean value that indicates whether object is present in array. */
bool ccArrayContainsObject(ccArray *arr, Object* object); bool ccArrayContainsObject(ccArray *arr, Object* object);
@ -98,22 +98,22 @@ void ccArrayAppendArray(ccArray *arr, ccArray *plusArr);
void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr); void ccArrayAppendArrayWithResize(ccArray *arr, ccArray *plusArr);
/** Inserts an object at index */ /** Inserts an object at index */
void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, unsigned int index); void ccArrayInsertObjectAtIndex(ccArray *arr, Object* object, int index);
/** Swaps two objects */ /** Swaps two objects */
void ccArraySwapObjectsAtIndexes(ccArray *arr, unsigned int index1, unsigned int index2); void ccArraySwapObjectsAtIndexes(ccArray *arr, int index1, int index2);
/** Removes all objects from arr */ /** Removes all objects from arr */
void ccArrayRemoveAllObjects(ccArray *arr); void ccArrayRemoveAllObjects(ccArray *arr);
/** Removes object at specified index and pushes back all subsequent objects. /** Removes object at specified index and pushes back all subsequent objects.
Behavior undefined if index outside [0, num-1]. */ Behavior undefined if index outside [0, num-1]. */
void ccArrayRemoveObjectAtIndex(ccArray *arr, unsigned int index, bool bReleaseObj = true); void ccArrayRemoveObjectAtIndex(ccArray *arr, int index, bool bReleaseObj = true);
/** Removes object at specified index and fills the gap with the last object, /** Removes object at specified index and fills the gap with the last object,
thereby avoiding the need to push back subsequent objects. thereby avoiding the need to push back subsequent objects.
Behavior undefined if index outside [0, num-1]. */ Behavior undefined if index outside [0, num-1]. */
void ccArrayFastRemoveObjectAtIndex(ccArray *arr, unsigned int index); void ccArrayFastRemoveObjectAtIndex(ccArray *arr, int index);
void ccArrayFastRemoveObject(ccArray *arr, Object* object); void ccArrayFastRemoveObject(ccArray *arr, Object* object);
@ -133,12 +133,12 @@ void ccArrayFullRemoveArray(ccArray *arr, ccArray *minusArr);
// #pragma mark ccCArray for Values (c structures) // #pragma mark ccCArray for Values (c structures)
typedef struct _ccCArray { typedef struct _ccCArray {
unsigned int num, max; int num, max;
void** arr; void** arr;
} ccCArray; } ccCArray;
/** Allocates and initializes a new C array with specified capacity */ /** Allocates and initializes a new C array with specified capacity */
ccCArray* ccCArrayNew(unsigned int capacity); ccCArray* ccCArrayNew(int capacity);
/** Frees C array after removing all remaining values. Silently ignores nil arr. */ /** Frees C array after removing all remaining values. Silently ignores nil arr. */
void ccCArrayFree(ccCArray *arr); void ccCArrayFree(ccCArray *arr);
@ -147,16 +147,16 @@ void ccCArrayFree(ccCArray *arr);
void ccCArrayDoubleCapacity(ccCArray *arr); void ccCArrayDoubleCapacity(ccCArray *arr);
/** Increases array capacity such that max >= num + extra. */ /** Increases array capacity such that max >= num + extra. */
void ccCArrayEnsureExtraCapacity(ccCArray *arr, unsigned int extra); void ccCArrayEnsureExtraCapacity(ccCArray *arr, int extra);
/** Returns index of first occurrence of value, NSNotFound if value not found. */ /** Returns index of first occurrence of value, NSNotFound if value not found. */
unsigned int ccCArrayGetIndexOfValue(ccCArray *arr, void* value); int ccCArrayGetIndexOfValue(ccCArray *arr, void* value);
/** Returns a Boolean value that indicates whether value is present in the C array. */ /** Returns a Boolean value that indicates whether value is present in the C array. */
bool ccCArrayContainsValue(ccCArray *arr, void* value); bool ccCArrayContainsValue(ccCArray *arr, void* value);
/** Inserts a value at a certain position. Behavior undefined if array doesn't have enough capacity */ /** Inserts a value at a certain position. Behavior undefined if array doesn't have enough capacity */
void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, unsigned int index); void ccCArrayInsertValueAtIndex( ccCArray *arr, void* value, int index);
/** Appends an value. Behavior undefined if array doesn't have enough capacity. */ /** Appends an value. Behavior undefined if array doesn't have enough capacity. */
void ccCArrayAppendValue(ccCArray *arr, void* value); void ccCArrayAppendValue(ccCArray *arr, void* value);
@ -178,14 +178,14 @@ void ccCArrayRemoveAllValues(ccCArray *arr);
Behavior undefined if index outside [0, num-1]. Behavior undefined if index outside [0, num-1].
@since v0.99.4 @since v0.99.4
*/ */
void ccCArrayRemoveValueAtIndex(ccCArray *arr, unsigned int index); void ccCArrayRemoveValueAtIndex(ccCArray *arr, int index);
/** Removes value at specified index and fills the gap with the last value, /** Removes value at specified index and fills the gap with the last value,
thereby avoiding the need to push back subsequent values. thereby avoiding the need to push back subsequent values.
Behavior undefined if index outside [0, num-1]. Behavior undefined if index outside [0, num-1].
@since v0.99.4 @since v0.99.4
*/ */
void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, unsigned int index); void ccCArrayFastRemoveValueAtIndex(ccCArray *arr, int index);
/** Searches for the first occurrence of value and removes it. If value is not found the function has no effect. /** Searches for the first occurrence of value and removes it. If value is not found the function has no effect.
@since v0.99.4 @since v0.99.4

View File

@ -86,6 +86,20 @@ namespace {
PixelFormatInfoMapValue(Texture2D::PixelFormat::S3TC_DXT5, Texture2D::PixelFormatInfo(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)), PixelFormatInfoMapValue(Texture2D::PixelFormat::S3TC_DXT5, Texture2D::PixelFormatInfo(GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)),
#endif #endif
#ifdef GL_ATC_RGB_AMD
PixelFormatInfoMapValue(Texture2D::PixelFormat::ATC_RGB, Texture2D::PixelFormatInfo(GL_ATC_RGB_AMD,
0xFFFFFFFF, 0xFFFFFFFF, 4, true, false)),
#endif
#ifdef GL_ATC_RGBA_EXPLICIT_ALPHA_AMD
PixelFormatInfoMapValue(Texture2D::PixelFormat::ATC_EXPLICIT_ALPHA, Texture2D::PixelFormatInfo(GL_ATC_RGBA_EXPLICIT_ALPHA_AMD,
0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)),
#endif
#ifdef GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD
PixelFormatInfoMapValue(Texture2D::PixelFormat::ATC_INTERPOLATED_ALPHA, Texture2D::PixelFormatInfo(GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD,
0xFFFFFFFF, 0xFFFFFFFF, 8, true, false)),
#endif
}; };
} }
@ -423,7 +437,7 @@ Texture2D::~Texture2D()
VolatileTexture::removeTexture(this); VolatileTexture::removeTexture(this);
#endif #endif
CCLOGINFO("cocos2d: deallocing Texture2D %u.", _name); CCLOGINFO("deallocing Texture2D: %p - id=%u", this, _name);
CC_SAFE_RELEASE(_shaderProgram); CC_SAFE_RELEASE(_shaderProgram);
if(_name) if(_name)
@ -552,7 +566,8 @@ bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat
if (info.compressed && !Configuration::getInstance()->supportsPVRTC() if (info.compressed && !Configuration::getInstance()->supportsPVRTC()
&& !Configuration::getInstance()->supportsETC() && !Configuration::getInstance()->supportsETC()
&& !Configuration::getInstance()->supportsS3TC()) && !Configuration::getInstance()->supportsS3TC()
&& !Configuration::getInstance()->supportsATITC())
{ {
CCLOG("cocos2d: WARNING: PVRTC/ETC images are not supported"); CCLOG("cocos2d: WARNING: PVRTC/ETC images are not supported");
return false; return false;
@ -606,6 +621,7 @@ bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat
// Specify OpenGL texture image // Specify OpenGL texture image
int width = pixelsWide; int width = pixelsWide;
int height = pixelsHigh; int height = pixelsHigh;
for (int i = 0; i < mipmapsNum; ++i) for (int i = 0; i < mipmapsNum; ++i)
{ {
unsigned char *data = mipmaps[i].address; unsigned char *data = mipmaps[i].address;
@ -634,7 +650,6 @@ bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat
width = MAX(width >> 1, 1); width = MAX(width >> 1, 1);
height = MAX(height >> 1, 1); height = MAX(height >> 1, 1);
} }
_contentSize = Size((float)pixelsWide, (float)pixelsHigh); _contentSize = Size((float)pixelsWide, (float)pixelsHigh);

View File

@ -105,7 +105,12 @@ public:
S3TC_DXT3, S3TC_DXT3,
//! S3TC-compressed texture: S3TC_Dxt5 //! S3TC-compressed texture: S3TC_Dxt5
S3TC_DXT5, S3TC_DXT5,
//! ATITC-compressed texture: ATC_RGB
ATC_RGB,
//! ATITC-compressed texture: ATC_EXPLICIT_ALPHA
ATC_EXPLICIT_ALPHA,
//! ATITC-compresed texture: ATC_INTERPOLATED_ALPHA
ATC_INTERPOLATED_ALPHA,
//! Default texture format: AUTO //! Default texture format: AUTO
DEFAULT = AUTO, DEFAULT = AUTO,

View File

@ -53,7 +53,7 @@ TextureAtlas::TextureAtlas()
TextureAtlas::~TextureAtlas() TextureAtlas::~TextureAtlas()
{ {
CCLOGINFO("cocos2d: TextureAtlas deallocing %p.", this); CCLOGINFO("deallocing TextureAtlas: %p", this);
CC_SAFE_FREE(_quads); CC_SAFE_FREE(_quads);
CC_SAFE_FREE(_indices); CC_SAFE_FREE(_indices);

Some files were not shown because too many files have changed in this diff Show More