Merge remote-tracking branch 'upstream/develop' into develop

Conflicts:
	cocos/scripting/auto-generated
	samples/Javascript/Shared
	tools/bindings-generator
This commit is contained in:
bmanGH 2013-12-30 16:42:03 +08:00
commit 9ac07fcaf3
732 changed files with 39700 additions and 27378 deletions

19
AUTHORS
View File

@ -669,6 +669,25 @@ Developers:
zhiqiangxu zhiqiangxu
Fixed a logic error in ControlUtils::RectUnion. Fixed a logic error in ControlUtils::RectUnion.
yinkaile (2youyouo2)
Maintainer of Armature Bone Animation.
dmurtagh
Fixed a bug that UserDefault::getDoubleForKey() doesn't pass default value to Java.
seobyeongky
Updates spine runtime.
Fixed a potential bug in Data's copy constructor.
luocker
Fix a bug that string itself is also modified in `String::componentsSeparatedByString`.
omersaeed
Fix a bug that game will crash if connection breaks during download using AssetManager.
SBKarr
AngelCode binary file format support for LabelBMFont.
Retired Core Developers: Retired Core Developers:
WenSheng Yang WenSheng Yang
Author of windows port, CCTextField, Author of windows port, CCTextField,

View File

@ -4,13 +4,33 @@ cocos2d-x-3.0beta0 ?? 2013
[NEW] SChedule::performFunctionInCocosThread() [NEW] SChedule::performFunctionInCocosThread()
[NEW] Added tga format support again. [NEW] Added tga format support again.
[FIX] A Logic error in ControlUtils::RectUnion. [FIX] A Logic error in ControlUtils::RectUnion.
[FIX] Bug fixes for Armature, use Vector<T>, Map<K, V> instead of Array, Dictionary.
[FIX] Used c++11 range loop(highest performance) instead of other types of loop.
[FIX] Removed most hungarian notations.
[FIX] Merged NodeRGBA to Node.
[NEW] New renderer support.
[FIX] Potential hash collision fix.
[FIX] Updates spine runtime to the latest version.
[FIX] Uses `const std::string&` instead of `const char*`.
[FIX] LabelBMFont string can't be shown integrally.
[FIX] Deprecates FileUtils::getFileData, adds FileUtils::getStringFromFile/getDataFromFile.
[FIX] GUI refactoring: Removes UI prefix, Widget is inherited from Node, uses new containers(Vector<T>, Map<K,V>).
[FIX] String itself is also modified in `String::componentsSeparatedByString`.
[FIX] Sprites with PhysicsBody move to a wrong position when game resume from background.
[FIX] Crash if connection breaks during download using AssetManager.
[NEW] AngelCode binary file format support for LabelBMFont.
[Android] [Android]
[NEW] build/android-build.sh: add supporting to generate .apk file [NEW] build/android-build.sh: add supporting to generate .apk file
[FIX] XMLHttpRequest receives wrong binary array. [FIX] XMLHttpRequest receives wrong binary array.
[NEW] Bindings-generator supports to bind 'unsigned long'. [NEW] Bindings-generator supports to bind 'unsigned long'.
[FIX] 'Test Frame Event' of TestJavascript/CocoStudioArmatureTest Crashes. [FIX] 'Test Frame Event' of TestJavascript/CocoStudioArmatureTest Crashes.
[FIX] UserDefault::getDoubleForKey() doesn't pass default value to Java.
[Windows] [Windows]
[NEW] CMake support for windows. [NEW] CMake support for windows.
[Bindings]
[FIX] Don't bind override functions for JSB and LuaBining since they aren't needed at all.
[NEW] Adds spine JS binding support.
[FIX] The order of onEnter and onExit is wrong.
cocos2d-x-3.0alpha1 Nov.19 2013 cocos2d-x-3.0alpha1 Nov.19 2013
[all platforms] [all platforms]

View File

@ -143,6 +143,7 @@ include_directories(
${CMAKE_CURRENT_SOURCE_DIR}/cocos ${CMAKE_CURRENT_SOURCE_DIR}/cocos
${CMAKE_CURRENT_SOURCE_DIR}/cocos/audio/include ${CMAKE_CURRENT_SOURCE_DIR}/cocos/audio/include
${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d ${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d
${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d/renderer
${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d/platform ${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d/platform
${CMAKE_CURRENT_SOURCE_DIR}/cocos/base ${CMAKE_CURRENT_SOURCE_DIR}/cocos/base
${CMAKE_CURRENT_SOURCE_DIR}/cocos/physics ${CMAKE_CURRENT_SOURCE_DIR}/cocos/physics
@ -152,6 +153,7 @@ include_directories(
${CMAKE_CURRENT_SOURCE_DIR}/external ${CMAKE_CURRENT_SOURCE_DIR}/external
${CMAKE_CURRENT_SOURCE_DIR}/external/tinyxml2 ${CMAKE_CURRENT_SOURCE_DIR}/external/tinyxml2
${CMAKE_CURRENT_SOURCE_DIR}/external/unzip ${CMAKE_CURRENT_SOURCE_DIR}/external/unzip
${CMAKE_CURRENT_SOURCE_DIR}/external/edtaa3func
${CMAKE_CURRENT_SOURCE_DIR}/external/chipmunk/include/chipmunk ${CMAKE_CURRENT_SOURCE_DIR}/external/chipmunk/include/chipmunk
${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d/platform/${PLATFORM_FOLDER} ${CMAKE_CURRENT_SOURCE_DIR}/cocos/2d/platform/${PLATFORM_FOLDER}
${CMAKE_CURRENT_SOURCE_DIR}/external/jpeg/include/${PLATFORM_FOLDER} ${CMAKE_CURRENT_SOURCE_DIR}/external/jpeg/include/${PLATFORM_FOLDER}
@ -267,8 +269,6 @@ endif(BUILD_EDITOR_COCOSBUILDER)
if(BUILD_EDITOR_COCOSTUDIO) if(BUILD_EDITOR_COCOSTUDIO)
# cocostudio # cocostudio
add_subdirectory(cocos/editor-support/cocostudio) add_subdirectory(cocos/editor-support/cocostudio)
# jsoncpp library, cocostuido depends on jsoncpp
add_subdirectory(external/json)
endif(BUILD_EDITOR_COCOSTUDIO) endif(BUILD_EDITOR_COCOSTUDIO)
if(BUILD_LIBS_LUA) if(BUILD_LIBS_LUA)

View File

@ -12,18 +12,6 @@ LUA_SAMPLES = ['hellolua', 'testlua']
JSB_SAMPLES = ['cocosdragon', 'crystalcraze', 'moonwarriors', 'testjavascript', 'watermelonwithme'] JSB_SAMPLES = ['cocosdragon', 'crystalcraze', 'moonwarriors', 'testjavascript', 'watermelonwithme']
ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JSB_SAMPLES ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JSB_SAMPLES
def usage():
print """%s [-n ndk-build-parameter] [-p android-platform] [-b build-mode] target.
Valid android-platform are:[10|11|12|13|14|15|16|17]
Valid build-mode are:[debug|release]
Valid targets are: [hellocpp|testcpp|simplegame|assetsmanager|hellolua|testlua|cocosdragon
|crystalcraze|moonwarriors|testjavascript|watermelonwithme]
You can use [all|cpp|lua|jsb], to build all, or all the C++, or all the Lua, or all the JavaScript samples respectevely.""" % sys.argv[0]
def check_environment_variables(): def check_environment_variables():
''' Checking the environment NDK_ROOT, which will be used for building ''' Checking the environment NDK_ROOT, which will be used for building
''' '''
@ -253,14 +241,23 @@ def build_samples(target,ndk_build_param,android_platform,build_mode):
if __name__ == '__main__': if __name__ == '__main__':
#parse the params #parse the params
parser = OptionParser() usage = """usage: %prog [options] target
parser.add_option("-n", "--ndk", dest="ndk_build_param", help='parameter for ndk-build')
parser.add_option("-p", "--platform", dest="android_platform", help='parameter for android-update') Valid targets are: [hellocpp|testcpp|simplegame|assetsmanager|hellolua|testlua|cocosdragon|crystalcraze|moonwarriors|testjavascript|watermelonwithme]
parser.add_option("-b", "--build", dest="build_mode", help='the build mode for java project,debug or release.Get more information,please refer to http://developer.android.com/tools/building/building-cmdline.html')
You can use [all|cpp|lua|jsb], to build all, or all the C++, or all the Lua, or all the JavaScript samples respectevely."""
parser = OptionParser(usage=usage)
parser.add_option("-n", "--ndk", dest="ndk_build_param",
help='parameter for ndk-build')
parser.add_option("-p", "--platform", dest="android_platform",
help='parameter for android-update.Without the parameter,the script just build dynamic library for project. Valid android-platform are:[10|11|12|13|14|15|16|17|18|19]')
parser.add_option("-b", "--build", dest="build_mode",
help='the build mode for java project,debug[default] or release.Get more information,please refer to http://developer.android.com/tools/building/building-cmdline.html')
(opts, args) = parser.parse_args() (opts, args) = parser.parse_args()
if len(args) == 0: if len(args) == 0:
usage() parser.print_help()
else: else:
try: try:
build_samples(args, opts.ndk_build_param,opts.android_platform,opts.build_mode) build_samples(args, opts.ndk_build_param,opts.android_platform,opts.build_mode)

View File

@ -1 +1 @@
77ef9ee3921db604edd06a2cc0b9f9a89259a431 812ab716d10a52b752f0d15b2393b2b0a7c8e969

View File

@ -1 +1 @@
133130a8ae8d6597399a7de05ba9b63ee55f5e2d b83c3a0fd60d6b1b1a032495615afd77fccd5050

View File

@ -24,7 +24,6 @@ CCActionTween.cpp \
CCAnimation.cpp \ CCAnimation.cpp \
CCAnimationCache.cpp \ CCAnimationCache.cpp \
CCAtlasNode.cpp \ CCAtlasNode.cpp \
CCCamera.cpp \
ccCArray.cpp \ ccCArray.cpp \
CCClippingNode.cpp \ CCClippingNode.cpp \
CCComponent.cpp \ CCComponent.cpp \
@ -60,6 +59,7 @@ CCGLProgram.cpp \
ccGLStateCache.cpp \ ccGLStateCache.cpp \
CCGrabber.cpp \ CCGrabber.cpp \
CCGrid.cpp \ CCGrid.cpp \
CCNodeGrid.cpp \
CCIMEDispatcher.cpp \ CCIMEDispatcher.cpp \
CCLabel.cpp \ CCLabel.cpp \
CCLabelAtlas.cpp \ CCLabelAtlas.cpp \
@ -117,10 +117,19 @@ platform/CCEGLViewProtocol.cpp \
platform/CCFileUtils.cpp \ platform/CCFileUtils.cpp \
platform/CCSAXParser.cpp \ platform/CCSAXParser.cpp \
platform/CCThread.cpp \ platform/CCThread.cpp \
renderer/CCCustomCommand.cpp \
renderer/CCFrustum.cpp \
renderer/CCGroupCommand.cpp \
renderer/CCMaterialManager.cpp \
renderer/CCQuadCommand.cpp \
renderer/CCRenderCommand.cpp \
renderer/CCRenderer.cpp \
renderer/CCRenderMaterial.cpp \
../base/atitc.cpp \ ../base/atitc.cpp \
../base/CCAffineTransform.cpp \ ../base/CCAffineTransform.cpp \
../base/CCArray.cpp \ ../base/CCArray.cpp \
../base/CCAutoreleasePool.cpp \ ../base/CCAutoreleasePool.cpp \
../base/CCConsole.cpp \
../base/CCData.cpp \ ../base/CCData.cpp \
../base/CCDataVisitor.cpp \ ../base/CCDataVisitor.cpp \
../base/CCDictionary.cpp \ ../base/CCDictionary.cpp \
@ -132,7 +141,6 @@ platform/CCThread.cpp \
../base/CCValue.cpp \ ../base/CCValue.cpp \
../base/etc1.cpp \ ../base/etc1.cpp \
../base/s3tc.cpp \ ../base/s3tc.cpp \
../base/CCConsole.cpp \
../math/kazmath/src/aabb.c \ ../math/kazmath/src/aabb.c \
../math/kazmath/src/mat3.c \ ../math/kazmath/src/mat3.c \
../math/kazmath/src/mat4.c \ ../math/kazmath/src/mat4.c \
@ -158,10 +166,12 @@ platform/CCThread.cpp \
../physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp \ ../physics/chipmunk/CCPhysicsWorldInfo_chipmunk.cpp \
../../external/tinyxml2/tinyxml2.cpp \ ../../external/tinyxml2/tinyxml2.cpp \
../../external/unzip/ioapi.cpp \ ../../external/unzip/ioapi.cpp \
../../external/unzip/unzip.cpp ../../external/unzip/unzip.cpp \
../../external/edtaa3func/edtaa3func.cpp
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \ LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \
$(LOCAL_PATH)/renderer \
$(LOCAL_PATH)/../math/kazmath/include \ $(LOCAL_PATH)/../math/kazmath/include \
platform/android \ platform/android \
$(LOCAL_PATH)/../physics \ $(LOCAL_PATH)/../physics \
@ -171,13 +181,15 @@ LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \
$(LOCAL_PATH)/../../external/chipmunk/include/chipmunk $(LOCAL_PATH)/../../external/chipmunk/include/chipmunk
LOCAL_C_INCLUDES := $(LOCAL_PATH) \ LOCAL_C_INCLUDES := $(LOCAL_PATH) \
$(LOCAL_PATH)/renderer \
$(LOCAL_PATH)/../math/kazmath/include \ $(LOCAL_PATH)/../math/kazmath/include \
$(LOCAL_PATH)/platform/android \ $(LOCAL_PATH)/platform/android \
$(LOCAL_PATH)/../physics \ $(LOCAL_PATH)/../physics \
$(LOCAL_PATH)/../base \ $(LOCAL_PATH)/../base \
$(LOCAL_PATH)/../../external/tinyxml2 \ $(LOCAL_PATH)/../../external/tinyxml2 \
$(LOCAL_PATH)/../../external/unzip \ $(LOCAL_PATH)/../../external/unzip \
$(LOCAL_PATH)/../../external/chipmunk/include/chipmunk $(LOCAL_PATH)/../../external/chipmunk/include/chipmunk \
$(LOCAL_PATH)/../../external/edtaa3func
LOCAL_LDLIBS := -lGLESv2 \ LOCAL_LDLIBS := -lGLESv2 \
@ -193,6 +205,7 @@ LOCAL_EXPORT_LDLIBS := -lGLESv2 \
LOCAL_WHOLE_STATIC_LIBRARIES := cocos_freetype2_static LOCAL_WHOLE_STATIC_LIBRARIES := cocos_freetype2_static
LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static LOCAL_WHOLE_STATIC_LIBRARIES += chipmunk_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dxandroid_static
LOCAL_WHOLE_STATIC_LIBRARIES += spine_static
# define the macro to compile through support/zip_support/ioapi.c # define the macro to compile through support/zip_support/ioapi.c
LOCAL_CFLAGS := -Wno-psabi -DUSE_FILE32API LOCAL_CFLAGS := -Wno-psabi -DUSE_FILE32API
@ -205,3 +218,4 @@ include $(BUILD_STATIC_LIBRARY)
$(call import-module,freetype2/prebuilt/android) $(call import-module,freetype2/prebuilt/android)
$(call import-module,chipmunk) $(call import-module,chipmunk)
$(call import-module,2d/platform/android) $(call import-module,2d/platform/android)
$(call import-module,editor-support/spine)

View File

@ -1,5 +1,5 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc. Copyright (c) 2011 Zynga Inc.
@ -26,7 +26,6 @@ THE SOFTWARE.
#include "CCActionCamera.h" #include "CCActionCamera.h"
#include "CCNode.h" #include "CCNode.h"
#include "CCCamera.h"
#include "CCStdC.h" #include "CCStdC.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -36,11 +35,6 @@ NS_CC_BEGIN
void ActionCamera::startWithTarget(Node *target) void ActionCamera::startWithTarget(Node *target)
{ {
ActionInterval::startWithTarget(target); ActionInterval::startWithTarget(target);
Camera *camera = target->getCamera();
camera->getCenter(&_centerXOrig, &_centerYOrig, &_centerZOrig);
camera->getEye(&_eyeXOrig, &_eyeYOrig, &_eyeZOrig);
camera->getUp(&_upXOrig, &_upYOrig, &_upZOrig);
} }
ActionCamera* ActionCamera::clone() const ActionCamera* ActionCamera::clone() const
@ -56,6 +50,88 @@ ActionCamera * ActionCamera::reverse() const
// FIXME: This conversion isn't safe. // FIXME: This conversion isn't safe.
return (ActionCamera*)ReverseTime::create(const_cast<ActionCamera*>(this)); return (ActionCamera*)ReverseTime::create(const_cast<ActionCamera*>(this));
} }
void ActionCamera::restore()
{
_eyeX = _eyeY = 0.0f;
_eyeZ = FLT_EPSILON;
_centerX = _centerY = _centerZ = 0.0f;
_upX = 0.0f;
_upY = 1.0f;
_upZ = 0.0f;
}
void ActionCamera::setEye(float x, float y, float z)
{
_eyeX = x;
_eyeY = y;
_eyeZ = z;
updateTransform();
}
void ActionCamera::setCenter(float centerX, float centerY, float centerZ)
{
_centerX = centerX;
_centerY = centerY;
_centerZ = centerZ;
updateTransform();
}
void ActionCamera::setUp(float upX, float upY, float upZ)
{
_upX = upX;
_upY = upY;
_upZ = upZ;
updateTransform();
}
void ActionCamera::updateTransform()
{
kmVec3 eye, center, up;
kmVec3Fill(&eye, _eyeX, _eyeY , _eyeZ);
kmVec3Fill(&center, _centerX, _centerY, _centerZ);
kmVec3Fill(&up, _upX, _upY, _upZ);
kmMat4 lookupMatrix;
kmMat4LookAt(&lookupMatrix, &eye, &center, &up);
Point anchorPoint = _target->getAnchorPointInPoints();
bool needsTranslation = !anchorPoint.equals(Point::ZERO);
kmMat4 mv;
kmMat4Identity(&mv);
if(needsTranslation) {
kmMat4 t;
kmMat4Translation(&t, anchorPoint.x, anchorPoint.y, 0);
kmMat4Multiply(&mv, &mv, &t);
}
kmMat4Multiply(&mv, &mv, &lookupMatrix);
if(needsTranslation) {
kmMat4 t;
kmMat4Translation(&t, -anchorPoint.x, -anchorPoint.y, 0);
kmMat4Multiply(&mv, &mv, &t);
}
// XXX FIXME TODO
// Using the AdditionalTransform is a complete hack.
// This should be done by multipliying the lookup-Matrix with the Node's MV matrix
// And then setting the result as the new MV matrix
// But that operation needs to be done after all the 'updates'.
// So the Director should emit an 'director_after_update' event.
// And this object should listen to it
_target->setAdditionalTransform(mv);
}
// //
// OrbitCamera // OrbitCamera
// //
@ -69,7 +145,7 @@ OrbitCamera * OrbitCamera::create(float t, float radius, float deltaRadius, floa
return obitCamera; return obitCamera;
} }
CC_SAFE_DELETE(obitCamera); CC_SAFE_DELETE(obitCamera);
return NULL; return nullptr;
} }
OrbitCamera* OrbitCamera::clone() const OrbitCamera* OrbitCamera::clone() const
@ -101,7 +177,8 @@ bool OrbitCamera::initWithDuration(float t, float radius, float deltaRadius, flo
void OrbitCamera::startWithTarget(Node *target) void OrbitCamera::startWithTarget(Node *target)
{ {
ActionInterval::startWithTarget(target); ActionCamera::startWithTarget(target);
float r, zenith, azimuth; float r, zenith, azimuth;
this->sphericalRadius(&r, &zenith, &azimuth); this->sphericalRadius(&r, &zenith, &azimuth);
if( isnan(_radius) ) if( isnan(_radius) )
@ -117,30 +194,25 @@ void OrbitCamera::startWithTarget(Node *target)
void OrbitCamera::update(float dt) void OrbitCamera::update(float dt)
{ {
float r = (_radius + _deltaRadius * dt) * Camera::getZEye(); float r = (_radius + _deltaRadius * dt) * FLT_EPSILON;
float za = _radZ + _radDeltaZ * dt; float za = _radZ + _radDeltaZ * dt;
float xa = _radX + _radDeltaX * dt; float xa = _radX + _radDeltaX * dt;
float i = sinf(za) * cosf(xa) * r + _centerXOrig; float i = sinf(za) * cosf(xa) * r + _centerX;
float j = sinf(za) * sinf(xa) * r + _centerYOrig; float j = sinf(za) * sinf(xa) * r + _centerY;
float k = cosf(za) * r + _centerZOrig; float k = cosf(za) * r + _centerZ;
_target->getCamera()->setEye(i,j,k); setEye(i,j,k);
} }
void OrbitCamera::sphericalRadius(float *newRadius, float *zenith, float *azimuth) void OrbitCamera::sphericalRadius(float *newRadius, float *zenith, float *azimuth)
{ {
float ex, ey, ez, cx, cy, cz, x, y, z;
float r; // radius float r; // radius
float s; float s;
Camera* camera = _target->getCamera(); float x = _eyeX - _centerX;
camera->getEye(&ex, &ey, &ez); float y = _eyeY - _centerY;
camera->getCenter(&cx, &cy, &cz); float z = _eyeZ - _centerZ;
x = ex-cx;
y = ey-cy;
z = ez-cz;
r = sqrtf( powf(x,2) + powf(y,2) + powf(z,2)); r = sqrtf( powf(x,2) + powf(y,2) + powf(z,2));
s = sqrtf( powf(x,2) + powf(y,2)); s = sqrtf( powf(x,2) + powf(y,2));
@ -155,7 +227,7 @@ void OrbitCamera::sphericalRadius(float *newRadius, float *zenith, float *azimut
else else
*azimuth = asinf(y/s); *azimuth = asinf(y/s);
*newRadius = r / Camera::getZEye(); *newRadius = r / FLT_EPSILON;
} }
NS_CC_END NS_CC_END

View File

@ -27,6 +27,7 @@ THE SOFTWARE.
#define __CCCAMERA_ACTION_H__ #define __CCCAMERA_ACTION_H__
#include "CCActionInterval.h" #include "CCActionInterval.h"
#include "kazmath/kazmath.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -48,15 +49,15 @@ public:
* @js ctor * @js ctor
*/ */
ActionCamera() ActionCamera()
:_centerXOrig(0) :_centerX(0)
,_centerYOrig(0) ,_centerY(0)
,_centerZOrig(0) ,_centerZ(0)
,_eyeXOrig(0) ,_eyeX(0)
,_eyeYOrig(0) ,_eyeY(0)
,_eyeZOrig(0) ,_eyeZ(FLT_EPSILON)
,_upXOrig(0) ,_upX(0)
,_upYOrig(0) ,_upY(1)
,_upZOrig(0) ,_upZ(0)
{} {}
/** /**
* @js NA * @js NA
@ -70,17 +71,22 @@ public:
virtual ActionCamera *clone() const override; virtual ActionCamera *clone() const override;
protected: protected:
float _centerXOrig;
float _centerYOrig;
float _centerZOrig;
float _eyeXOrig; void restore();
float _eyeYOrig; void setEye(float x, float y, float z);
float _eyeZOrig; void setCenter(float x, float y, float z);
void setUp(float x, float y, float z);
void updateTransform();
float _upXOrig; float _centerX;
float _upYOrig; float _centerY;
float _upZOrig; float _centerZ;
float _eyeX;
float _eyeY;
float _eyeZ;
float _upX;
float _upY;
float _upZ;
}; };
/** /**
@ -112,7 +118,7 @@ public:
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
~OrbitCamera(){} virtual ~OrbitCamera(){}
/** initializes a OrbitCamera action with radius, delta-radius, z, deltaZ, x, deltaX */ /** initializes a OrbitCamera action with radius, delta-radius, z, deltaZ, x, deltaX */
bool initWithDuration(float t, float radius, float deltaRadius, float angleZ, float deltaAngleZ, float angleX, float deltaAngleX); bool initWithDuration(float t, float radius, float deltaRadius, float angleZ, float deltaAngleZ, float angleX, float deltaAngleX);

View File

@ -43,7 +43,7 @@ NS_CC_BEGIN;
* Implementation of PointArray * Implementation of PointArray
*/ */
PointArray* PointArray::create(int capacity) PointArray* PointArray::create(ssize_t capacity)
{ {
PointArray* pointArray = new PointArray(); PointArray* pointArray = new PointArray();
if (pointArray) if (pointArray)
@ -63,7 +63,7 @@ PointArray* PointArray::create(int capacity)
} }
bool PointArray::initWithCapacity(int capacity) bool PointArray::initWithCapacity(ssize_t capacity)
{ {
_controlPoints = new vector<Point*>(); _controlPoints = new vector<Point*>();
@ -126,19 +126,19 @@ void PointArray::addControlPoint(Point controlPoint)
_controlPoints->push_back(new Point(controlPoint.x, controlPoint.y)); _controlPoints->push_back(new Point(controlPoint.x, controlPoint.y));
} }
void PointArray::insertControlPoint(Point &controlPoint, int index) void PointArray::insertControlPoint(Point &controlPoint, ssize_t index)
{ {
Point *temp = new Point(controlPoint.x, controlPoint.y); Point *temp = new Point(controlPoint.x, controlPoint.y);
_controlPoints->insert(_controlPoints->begin() + index, temp); _controlPoints->insert(_controlPoints->begin() + index, temp);
} }
Point PointArray::getControlPointAtIndex(int index) Point PointArray::getControlPointAtIndex(ssize_t index)
{ {
index = static_cast<int>(MIN(_controlPoints->size()-1, MAX(index, 0))); index = static_cast<int>(MIN(_controlPoints->size()-1, MAX(index, 0)));
return *(_controlPoints->at(index)); return *(_controlPoints->at(index));
} }
void PointArray::replaceControlPoint(cocos2d::Point &controlPoint, int index) void PointArray::replaceControlPoint(cocos2d::Point &controlPoint, ssize_t index)
{ {
Point *temp = _controlPoints->at(index); Point *temp = _controlPoints->at(index);
@ -146,17 +146,17 @@ void PointArray::replaceControlPoint(cocos2d::Point &controlPoint, int index)
temp->y = controlPoint.y; temp->y = controlPoint.y;
} }
void PointArray::removeControlPointAtIndex(int index) void PointArray::removeControlPointAtIndex(ssize_t index)
{ {
vector<Point*>::iterator iter = _controlPoints->begin() + index; vector<Point*>::iterator iter = _controlPoints->begin() + index;
Point* pRemovedPoint = *iter; Point* removedPoint = *iter;
_controlPoints->erase(iter); _controlPoints->erase(iter);
delete pRemovedPoint; delete removedPoint;
} }
int PointArray::count() const ssize_t PointArray::count() const
{ {
return static_cast<int>(_controlPoints->size()); return _controlPoints->size();
} }
PointArray* PointArray::reverse() const PointArray* PointArray::reverse() const
@ -177,11 +177,11 @@ PointArray* PointArray::reverse() const
void PointArray::reverseInline() void PointArray::reverseInline()
{ {
auto l = _controlPoints->size(); size_t l = _controlPoints->size();
Point *p1 = nullptr; Point *p1 = nullptr;
Point *p2 = nullptr; Point *p2 = nullptr;
int x, y; float x, y;
for (int i = 0; i < l/2; ++i) for (size_t i = 0; i < l/2; ++i)
{ {
p1 = _controlPoints->at(i); p1 = _controlPoints->at(i);
p2 = _controlPoints->at(l-i-1); p2 = _controlPoints->at(l-i-1);
@ -291,7 +291,7 @@ CardinalSplineTo* CardinalSplineTo::clone() const
void CardinalSplineTo::update(float time) void CardinalSplineTo::update(float time)
{ {
int p; ssize_t p;
float lt; float lt;
// eg. // eg.
@ -383,7 +383,7 @@ CardinalSplineBy* CardinalSplineBy::reverse() const
// convert "absolutes" to "diffs" // convert "absolutes" to "diffs"
// //
Point p = copyConfig->getControlPointAtIndex(0); Point p = copyConfig->getControlPointAtIndex(0);
for (unsigned int i = 1; i < copyConfig->count(); ++i) for (ssize_t i = 1; i < copyConfig->count(); ++i)
{ {
Point current = copyConfig->getControlPointAtIndex(i); Point current = copyConfig->getControlPointAtIndex(i);
Point diff = current - p; Point diff = current - p;
@ -405,7 +405,7 @@ CardinalSplineBy* CardinalSplineBy::reverse() const
p = -p; p = -p;
pReverse->insertControlPoint(p, 0); pReverse->insertControlPoint(p, 0);
for (unsigned int i = 1; i < pReverse->count(); ++i) for (ssize_t i = 1; i < pReverse->count(); ++i)
{ {
Point current = pReverse->getControlPointAtIndex(i); Point current = pReverse->getControlPointAtIndex(i);
current = -current; current = -current;
@ -475,8 +475,8 @@ CatmullRomTo* CatmullRomTo::clone() const
CatmullRomTo* CatmullRomTo::reverse() const CatmullRomTo* CatmullRomTo::reverse() const
{ {
PointArray *pReverse = _points->reverse(); PointArray *reverse = _points->reverse();
return CatmullRomTo::create(_duration, pReverse); return CatmullRomTo::create(_duration, reverse);
} }
@ -528,7 +528,7 @@ CatmullRomBy* CatmullRomBy::reverse() const
// convert "absolutes" to "diffs" // convert "absolutes" to "diffs"
// //
Point p = copyConfig->getControlPointAtIndex(0); Point p = copyConfig->getControlPointAtIndex(0);
for (unsigned int i = 1; i < copyConfig->count(); ++i) for (ssize_t i = 1; i < copyConfig->count(); ++i)
{ {
Point current = copyConfig->getControlPointAtIndex(i); Point current = copyConfig->getControlPointAtIndex(i);
Point diff = current - p; Point diff = current - p;
@ -550,7 +550,7 @@ CatmullRomBy* CatmullRomBy::reverse() const
p = -p; p = -p;
reverse->insertControlPoint(p, 0); reverse->insertControlPoint(p, 0);
for (unsigned int i = 1; i < reverse->count(); ++i) for (ssize_t i = 1; i < reverse->count(); ++i)
{ {
Point current = reverse->getControlPointAtIndex(i); Point current = reverse->getControlPointAtIndex(i);
current = -current; current = -current;

View File

@ -61,7 +61,7 @@ public:
/** creates and initializes a Points array with capacity /** creates and initializes a Points array with capacity
* @js NA * @js NA
*/ */
static PointArray* create(int capacity); static PointArray* create(ssize_t capacity);
/** /**
* @js NA * @js NA
@ -77,7 +77,7 @@ public:
/** initializes a Catmull Rom config with a capacity hint /** initializes a Catmull Rom config with a capacity hint
* @js NA * @js NA
*/ */
bool initWithCapacity(int capacity); bool initWithCapacity(ssize_t capacity);
/** appends a control point /** appends a control point
* @js NA * @js NA
@ -87,27 +87,27 @@ public:
/** inserts a controlPoint at index /** inserts a controlPoint at index
* @js NA * @js NA
*/ */
void insertControlPoint(Point &controlPoint, int index); void insertControlPoint(Point &controlPoint, ssize_t index);
/** replaces an existing controlPoint at index /** replaces an existing controlPoint at index
* @js NA * @js NA
*/ */
void replaceControlPoint(Point &controlPoint, int index); void replaceControlPoint(Point &controlPoint, ssize_t index);
/** get the value of a controlPoint at a given index /** get the value of a controlPoint at a given index
* @js NA * @js NA
*/ */
Point getControlPointAtIndex(int index); Point getControlPointAtIndex(ssize_t index);
/** deletes a control point at a given index /** deletes a control point at a given index
* @js NA * @js NA
*/ */
void removeControlPointAtIndex(int index); void removeControlPointAtIndex(ssize_t index);
/** returns the number of objects of the control point array /** returns the number of objects of the control point array
* @js NA * @js NA
*/ */
int count() const; ssize_t count() const;
/** returns a new copy of the array reversed. User is responsible for releasing this copy /** returns a new copy of the array reversed. User is responsible for releasing this copy
* @js NA * @js NA

View File

@ -25,6 +25,7 @@ THE SOFTWARE.
#include "CCActionGrid.h" #include "CCActionGrid.h"
#include "CCDirector.h" #include "CCDirector.h"
#include "CCGrid.h" #include "CCGrid.h"
#include "CCNodeGrid.h"
NS_CC_BEGIN NS_CC_BEGIN
// implementation of GridAction // implementation of GridAction
@ -44,16 +45,16 @@ bool GridAction::initWithDuration(float duration, const Size& gridSize)
void GridAction::startWithTarget(Node *target) void GridAction::startWithTarget(Node *target)
{ {
ActionInterval::startWithTarget(target); ActionInterval::startWithTarget(target);
cacheTargetAsGridNode();
GridBase *newgrid = this->getGrid(); GridBase *newgrid = this->getGrid();
Node *t = _target; GridBase *targetGrid = _gridNodeTarget->getGrid();
GridBase *targetGrid = t->getGrid();
if (targetGrid && targetGrid->getReuseGrid() > 0) if (targetGrid && targetGrid->getReuseGrid() > 0)
{ {
if (targetGrid->isActive() && targetGrid->getGridSize().width == _gridSize.width if (targetGrid->isActive() && targetGrid->getGridSize().width == _gridSize.width
&& targetGrid->getGridSize().height == _gridSize.height /*&& dynamic_cast<GridBase*>(targetGrid) != NULL*/) && targetGrid->getGridSize().height == _gridSize.height /*&& dynamic_cast<GridBase*>(targetGrid) != nullptr*/)
{ {
targetGrid->reuse(); targetGrid->reuse();
} }
@ -69,11 +70,17 @@ void GridAction::startWithTarget(Node *target)
targetGrid->setActive(false); targetGrid->setActive(false);
} }
t->setGrid(newgrid); _gridNodeTarget->setGrid(newgrid);
t->getGrid()->setActive(true); _gridNodeTarget->getGrid()->setActive(true);
} }
} }
void GridAction::cacheTargetAsGridNode()
{
_gridNodeTarget = dynamic_cast<NodeGrid*> (_target);
CCASSERT(_gridNodeTarget, "GridActions can only used on NodeGrid");
}
GridAction* GridAction::reverse() const GridAction* GridAction::reverse() const
{ {
// FIXME: This conversion isn't safe. // FIXME: This conversion isn't safe.
@ -97,19 +104,19 @@ GridBase* Grid3DAction::getGrid()
Vertex3F Grid3DAction::getVertex(const Point& position) const Vertex3F Grid3DAction::getVertex(const Point& position) const
{ {
Grid3D *g = (Grid3D*)_target->getGrid(); Grid3D *g = (Grid3D*)_gridNodeTarget->getGrid();
return g->getVertex(position); return g->getVertex(position);
} }
Vertex3F Grid3DAction::getOriginalVertex(const Point& position) const Vertex3F Grid3DAction::getOriginalVertex(const Point& position) const
{ {
Grid3D *g = (Grid3D*)_target->getGrid(); Grid3D *g = (Grid3D*)_gridNodeTarget->getGrid();
return g->getOriginalVertex(position); return g->getOriginalVertex(position);
} }
void Grid3DAction::setVertex(const Point& position, const Vertex3F& vertex) void Grid3DAction::setVertex(const Point& position, const Vertex3F& vertex)
{ {
Grid3D *g = (Grid3D*)_target->getGrid(); Grid3D *g = (Grid3D*)_gridNodeTarget->getGrid();
g->setVertex(position, vertex); g->setVertex(position, vertex);
} }
@ -122,19 +129,19 @@ GridBase* TiledGrid3DAction::getGrid(void)
Quad3 TiledGrid3DAction::getTile(const Point& pos) const Quad3 TiledGrid3DAction::getTile(const Point& pos) const
{ {
TiledGrid3D *g = (TiledGrid3D*)_target->getGrid(); TiledGrid3D *g = (TiledGrid3D*)_gridNodeTarget->getGrid();
return g->getTile(pos); return g->getTile(pos);
} }
Quad3 TiledGrid3DAction::getOriginalTile(const Point& pos) const Quad3 TiledGrid3DAction::getOriginalTile(const Point& pos) const
{ {
TiledGrid3D *g = (TiledGrid3D*)_target->getGrid(); TiledGrid3D *g = (TiledGrid3D*)_gridNodeTarget->getGrid();
return g->getOriginalTile(pos); return g->getOriginalTile(pos);
} }
void TiledGrid3DAction::setTile(const Point& pos, const Quad3& coords) void TiledGrid3DAction::setTile(const Point& pos, const Quad3& coords)
{ {
TiledGrid3D *g = (TiledGrid3D*)_target->getGrid(); TiledGrid3D *g = (TiledGrid3D*)_gridNodeTarget->getGrid();
return g->setTile(pos, coords); return g->setTile(pos, coords);
} }
@ -345,14 +352,20 @@ DeccelAmplitude* DeccelAmplitude::reverse() const
void StopGrid::startWithTarget(Node *target) void StopGrid::startWithTarget(Node *target)
{ {
ActionInstant::startWithTarget(target); ActionInstant::startWithTarget(target);
cacheTargetAsGridNode();
GridBase *grid = _target->getGrid(); GridBase *grid = _gridNodeTarget->getGrid();
if (grid && grid->isActive()) if (grid && grid->isActive())
{ {
grid->setActive(false); grid->setActive(false);
} }
} }
void StopGrid::cacheTargetAsGridNode()
{
_gridNodeTarget = dynamic_cast<NodeGrid*> (_target);
CCASSERT(_gridNodeTarget, "GridActions can only used on NodeGrid");
}
StopGrid* StopGrid::create() StopGrid* StopGrid::create()
{ {
StopGrid* pAction = new StopGrid(); StopGrid* pAction = new StopGrid();
@ -402,13 +415,20 @@ bool ReuseGrid::initWithTimes(int times)
void ReuseGrid::startWithTarget(Node *target) void ReuseGrid::startWithTarget(Node *target)
{ {
ActionInstant::startWithTarget(target); ActionInstant::startWithTarget(target);
cacheTargetAsGridNode();
if (_target->getGrid() && _target->getGrid()->isActive()) if (_gridNodeTarget->getGrid() && _gridNodeTarget->getGrid()->isActive())
{ {
_target->getGrid()->setReuseGrid(_target->getGrid()->getReuseGrid() + _times); _gridNodeTarget->getGrid()->setReuseGrid(_gridNodeTarget->getGrid()->getReuseGrid() + _times);
} }
} }
void ReuseGrid::cacheTargetAsGridNode()
{
_gridNodeTarget = dynamic_cast<NodeGrid*> (_target);
CCASSERT(_gridNodeTarget, "GridActions can only used on NodeGrid");
}
ReuseGrid* ReuseGrid::clone() const ReuseGrid* ReuseGrid::clone() const
{ {
return ReuseGrid::create(_times); return ReuseGrid::create(_times);

View File

@ -31,6 +31,7 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
class GridBase; class GridBase;
class NodeGrid;
/** /**
* @addtogroup actions * @addtogroup actions
@ -57,6 +58,10 @@ protected:
bool initWithDuration(float duration, const Size& gridSize); bool initWithDuration(float duration, const Size& gridSize);
Size _gridSize; Size _gridSize;
NodeGrid* _gridNodeTarget;
void cacheTargetAsGridNode();
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(GridAction); CC_DISALLOW_COPY_AND_ASSIGN(GridAction);
@ -248,7 +253,7 @@ private:
/** @brief StopGrid action. /** @brief StopGrid action.
@warning Don't call this action if another grid action is active. @warning Don't call this action if another grid action is active.
Call if you want to remove the the grid effect. Example: Call if you want to remove the the grid effect. Example:
Sequence::actions(Lens::action(...), StopGrid::action(...), NULL); Sequence::actions(Lens::action(...), StopGrid::action(...), nullptr);
*/ */
class CC_DLL StopGrid : public ActionInstant class CC_DLL StopGrid : public ActionInstant
{ {
@ -264,6 +269,10 @@ public:
protected: protected:
StopGrid() {} StopGrid() {}
virtual ~StopGrid() {} virtual ~StopGrid() {}
NodeGrid* _gridNodeTarget;
void cacheTargetAsGridNode();
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(StopGrid); CC_DISALLOW_COPY_AND_ASSIGN(StopGrid);
@ -286,7 +295,11 @@ protected:
virtual ~ReuseGrid() {} virtual ~ReuseGrid() {}
/** initializes an action with the number of times that the current grid will be reused */ /** initializes an action with the number of times that the current grid will be reused */
bool initWithTimes(int times); bool initWithTimes(int times);
NodeGrid* _gridNodeTarget;
void cacheTargetAsGridNode();
int _times; int _times;
private: private:

View File

@ -421,7 +421,7 @@ CallFuncN * CallFuncN::create(const std::function<void(Node*)> &func)
} }
CC_SAFE_DELETE(ret); CC_SAFE_DELETE(ret);
return NULL; return nullptr;
} }
// XXX deprecated // XXX deprecated

View File

@ -292,8 +292,8 @@ public:
protected: protected:
CallFunc() CallFunc()
: _selectorTarget(NULL) : _selectorTarget(nullptr)
, _callFunc(NULL) , _callFunc(nullptr)
, _function(nullptr) , _function(nullptr)
{ {
} }

File diff suppressed because it is too large Load Diff

View File

@ -32,7 +32,7 @@ THE SOFTWARE.
#include "CCProtocols.h" #include "CCProtocols.h"
#include "CCSpriteFrame.h" #include "CCSpriteFrame.h"
#include "CCAnimation.h" #include "CCAnimation.h"
#include <CCVector.h> #include "CCVector.h"
#include <vector> #include <vector>
NS_CC_BEGIN NS_CC_BEGIN
@ -57,7 +57,7 @@ then running it again in Reverse mode.
Example: Example:
Action *pingPongAction = Sequence::actions(action, action->reverse(), NULL); Action *pingPongAction = Sequence::actions(action, action->reverse(), nullptr);
*/ */
class CC_DLL ActionInterval : public FiniteTimeAction class CC_DLL ActionInterval : public FiniteTimeAction
{ {
@ -92,7 +92,7 @@ class CC_DLL Sequence : public ActionInterval
{ {
public: public:
/** helper constructor to create an array of sequenceable actions */ /** helper constructor to create an array of sequenceable actions */
static Sequence* create(FiniteTimeAction *pAction1, ...) CC_REQUIRES_NULL_TERMINATION; static Sequence* create(FiniteTimeAction *action1, ...) CC_REQUIRES_NULL_TERMINATION;
/** helper constructor to create an array of sequenceable actions given an array /** helper constructor to create an array of sequenceable actions given an array
* @code * @code
* When this funtion bound to the js or lua,the input params changed * When this funtion bound to the js or lua,the input params changed
@ -102,9 +102,9 @@ public:
*/ */
static Sequence* create(const Vector<FiniteTimeAction*>& arrayOfActions); static Sequence* create(const Vector<FiniteTimeAction*>& arrayOfActions);
/** helper constructor to create an array of sequence-able actions */ /** helper constructor to create an array of sequence-able actions */
static Sequence* createWithVariableList(FiniteTimeAction *pAction1, va_list args); static Sequence* createWithVariableList(FiniteTimeAction *action1, va_list args);
/** creates the action */ /** creates the action */
static Sequence* createWithTwoActions(FiniteTimeAction *pActionOne, FiniteTimeAction *pActionTwo); static Sequence* createWithTwoActions(FiniteTimeAction *actionOne, FiniteTimeAction *actionTwo);
// //
// Overrides // Overrides
@ -136,15 +136,15 @@ class CC_DLL Repeat : public ActionInterval
{ {
public: public:
/** creates a Repeat action. Times is an unsigned integer between 1 and pow(2,30) */ /** creates a Repeat action. Times is an unsigned integer between 1 and pow(2,30) */
static Repeat* create(FiniteTimeAction *pAction, unsigned int times); static Repeat* create(FiniteTimeAction *action, unsigned int times);
inline void setInnerAction(FiniteTimeAction *pAction) inline void setInnerAction(FiniteTimeAction *action)
{ {
if (_innerAction != pAction) if (_innerAction != action)
{ {
CC_SAFE_RETAIN(pAction); CC_SAFE_RETAIN(action);
CC_SAFE_RELEASE(_innerAction); CC_SAFE_RELEASE(_innerAction);
_innerAction = pAction; _innerAction = action;
} }
} }
@ -188,14 +188,14 @@ class CC_DLL RepeatForever : public ActionInterval
{ {
public: public:
/** creates the action */ /** creates the action */
static RepeatForever* create(ActionInterval *pAction); static RepeatForever* create(ActionInterval *action);
inline void setInnerAction(ActionInterval *pAction) inline void setInnerAction(ActionInterval *action)
{ {
if (_innerAction != pAction) if (_innerAction != action)
{ {
CC_SAFE_RELEASE(_innerAction); CC_SAFE_RELEASE(_innerAction);
_innerAction = pAction; _innerAction = action;
CC_SAFE_RETAIN(_innerAction); CC_SAFE_RETAIN(_innerAction);
} }
} }
@ -220,7 +220,7 @@ protected:
{} {}
virtual ~RepeatForever(); virtual ~RepeatForever();
/** initializes the action */ /** initializes the action */
bool initWithAction(ActionInterval *pAction); bool initWithAction(ActionInterval *action);
/** Inner action */ /** Inner action */
ActionInterval *_innerAction; ActionInterval *_innerAction;
@ -241,16 +241,16 @@ public:
* in lua :local create(local object1,local object2, ...) * in lua :local create(local object1,local object2, ...)
* @endcode * @endcode
*/ */
static Spawn* create(FiniteTimeAction *pAction1, ...) CC_REQUIRES_NULL_TERMINATION; static Spawn* create(FiniteTimeAction *action1, ...) CC_REQUIRES_NULL_TERMINATION;
/** helper constructor to create an array of spawned actions */ /** helper constructor to create an array of spawned actions */
static Spawn* createWithVariableList(FiniteTimeAction *pAction1, va_list args); static Spawn* createWithVariableList(FiniteTimeAction *action1, va_list args);
/** helper constructor to create an array of spawned actions given an array */ /** helper constructor to create an array of spawned actions given an array */
static Spawn* create(const Vector<FiniteTimeAction*>& arrayOfActions); static Spawn* create(const Vector<FiniteTimeAction*>& arrayOfActions);
/** creates the Spawn action */ /** creates the Spawn action */
static Spawn* createWithTwoActions(FiniteTimeAction *pAction1, FiniteTimeAction *pAction2); static Spawn* createWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction *action2);
// //
// Overrides // Overrides
@ -265,7 +265,7 @@ protected:
Spawn() {} Spawn() {}
virtual ~Spawn(); virtual ~Spawn();
/** initializes the Spawn action with the 2 actions to spawn */ /** initializes the Spawn action with the 2 actions to spawn */
bool initWithTwoActions(FiniteTimeAction *pAction1, FiniteTimeAction *pAction2); bool initWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction *action2);
FiniteTimeAction *_one; FiniteTimeAction *_one;
FiniteTimeAction *_two; FiniteTimeAction *_two;
@ -282,10 +282,10 @@ class CC_DLL RotateTo : public ActionInterval
{ {
public: public:
/** creates the action with separate rotation angles */ /** creates the action with separate rotation angles */
static RotateTo* create(float fDuration, float fDeltaAngleX, float fDeltaAngleY); static RotateTo* create(float duration, float deltaAngleX, float deltaAngleY);
/** creates the action */ /** creates the action */
static RotateTo* create(float fDuration, float fDeltaAngle); static RotateTo* create(float duration, float deltaAngle);
// //
// Overrides // Overrides
@ -299,8 +299,8 @@ protected:
RotateTo() {} RotateTo() {}
virtual ~RotateTo() {} virtual ~RotateTo() {}
/** initializes the action */ /** initializes the action */
bool initWithDuration(float fDuration, float fDeltaAngle); bool initWithDuration(float duration, float deltaAngle);
bool initWithDuration(float fDuration, float fDeltaAngleX, float fDeltaAngleY); bool initWithDuration(float duration, float deltaAngleX, float deltaAngleY);
float _dstAngleX; float _dstAngleX;
float _startAngleX; float _startAngleX;
@ -320,8 +320,8 @@ class CC_DLL RotateBy : public ActionInterval
{ {
public: public:
/** creates the action */ /** creates the action */
static RotateBy* create(float fDuration, float fDeltaAngle); static RotateBy* create(float duration, float deltaAngle);
static RotateBy* create(float fDuration, float fDeltaAngleX, float fDeltaAngleY); static RotateBy* create(float duration, float deltaAngleX, float deltaAngleY);
// //
// Override // Override
@ -335,8 +335,8 @@ protected:
RotateBy() {} RotateBy() {}
virtual ~RotateBy() {} virtual ~RotateBy() {}
/** initializes the action */ /** initializes the action */
bool initWithDuration(float fDuration, float fDeltaAngle); bool initWithDuration(float duration, float deltaAngle);
bool initWithDuration(float fDuration, float fDeltaAngleX, float fDeltaAngleY); bool initWithDuration(float duration, float deltaAngleX, float deltaAngleY);
float _angleX; float _angleX;
float _startAngleX; float _startAngleX;
@ -878,7 +878,7 @@ class CC_DLL ReverseTime : public ActionInterval
{ {
public: public:
/** creates the action */ /** creates the action */
static ReverseTime* create(FiniteTimeAction *pAction); static ReverseTime* create(FiniteTimeAction *action);
// //
// Overrides // Overrides
@ -893,7 +893,7 @@ protected:
ReverseTime(); ReverseTime();
virtual ~ReverseTime(void); virtual ~ReverseTime(void);
/** initializes the action */ /** initializes the action */
bool initWithAction(FiniteTimeAction *pAction); bool initWithAction(FiniteTimeAction *action);
FiniteTimeAction *_other; FiniteTimeAction *_other;
@ -907,7 +907,7 @@ class CC_DLL Animate : public ActionInterval
{ {
public: public:
/** creates the action with an Animation and will restore the original frame when the animation is over */ /** creates the action with an Animation and will restore the original frame when the animation is over */
static Animate* create(Animation *pAnimation); static Animate* create(Animation *animation);
/** sets the Animation object to be animated */ /** sets the Animation object to be animated */
void setAnimation( Animation* animation ); void setAnimation( Animation* animation );
@ -928,7 +928,7 @@ protected:
Animate(); Animate();
virtual ~Animate(); virtual ~Animate();
/** initializes the action with an Animation and will restore the original frame when the animation is over */ /** initializes the action with an Animation and will restore the original frame when the animation is over */
bool initWithAnimation(Animation *pAnimation); bool initWithAnimation(Animation *animation);
std::vector<float>* _splitTimes; std::vector<float>* _splitTimes;
int _nextFrame; int _nextFrame;
@ -947,7 +947,7 @@ class CC_DLL TargetedAction : public ActionInterval
{ {
public: public:
/** Create an action with the specified action and forced target */ /** Create an action with the specified action and forced target */
static TargetedAction* create(Node* target, FiniteTimeAction* pAction); static TargetedAction* create(Node* target, FiniteTimeAction* action);
/** Sets the target that the action will be forced to run with */ /** Sets the target that the action will be forced to run with */
void setForcedTarget(Node* forcedTarget); void setForcedTarget(Node* forcedTarget);
@ -968,7 +968,7 @@ protected:
TargetedAction(); TargetedAction();
virtual ~TargetedAction(); virtual ~TargetedAction();
/** Init an action with the specified action and forced target */ /** Init an action with the specified action and forced target */
bool initWithTarget(Node* target, FiniteTimeAction* pAction); bool initWithTarget(Node* target, FiniteTimeAction* action);
FiniteTimeAction* _action; FiniteTimeAction* _action;
Node* _forcedTarget; Node* _forcedTarget;

View File

@ -49,8 +49,8 @@ typedef struct _hashElement
} tHashElement; } tHashElement;
ActionManager::ActionManager(void) ActionManager::ActionManager(void)
: _targets(NULL), : _targets(nullptr),
_currentTarget(NULL), _currentTarget(nullptr),
_currentTargetSalvaged(false) _currentTargetSalvaged(false)
{ {
@ -76,7 +76,7 @@ void ActionManager::deleteHashElement(tHashElement *element)
void ActionManager::actionAllocWithHashElement(tHashElement *element) void ActionManager::actionAllocWithHashElement(tHashElement *element)
{ {
// 4 actions per Node by default // 4 actions per Node by default
if (element->actions == NULL) if (element->actions == nullptr)
{ {
element->actions = ccArrayNew(4); element->actions = ccArrayNew(4);
}else }else
@ -122,7 +122,7 @@ void ActionManager::removeActionAtIndex(ssize_t index, tHashElement *element)
void ActionManager::pauseTarget(Node *target) void ActionManager::pauseTarget(Node *target)
{ {
tHashElement *element = NULL; tHashElement *element = nullptr;
HASH_FIND_PTR(_targets, &target, element); HASH_FIND_PTR(_targets, &target, element);
if (element) if (element)
{ {
@ -132,7 +132,7 @@ void ActionManager::pauseTarget(Node *target)
void ActionManager::resumeTarget(Node *target) void ActionManager::resumeTarget(Node *target)
{ {
tHashElement *element = NULL; tHashElement *element = nullptr;
HASH_FIND_PTR(_targets, &target, element); HASH_FIND_PTR(_targets, &target, element);
if (element) if (element)
{ {
@ -144,7 +144,7 @@ Vector<Node*> ActionManager::pauseAllRunningActions()
{ {
Vector<Node*> idsWithActions; Vector<Node*> idsWithActions;
for (tHashElement *element=_targets; element != NULL; element = (tHashElement *)element->hh.next) for (tHashElement *element=_targets; element != nullptr; element = (tHashElement *)element->hh.next)
{ {
if (! element->paused) if (! element->paused)
{ {
@ -158,19 +158,19 @@ Vector<Node*> ActionManager::pauseAllRunningActions()
void ActionManager::resumeTargets(const Vector<Node*>& targetsToResume) void ActionManager::resumeTargets(const Vector<Node*>& targetsToResume)
{ {
targetsToResume.forEach([this](Node* node){ for(const auto &node : targetsToResume) {
this->resumeTarget(node); this->resumeTarget(node);
}); }
} }
// run // run
void ActionManager::addAction(Action *action, Node *target, bool paused) void ActionManager::addAction(Action *action, Node *target, bool paused)
{ {
CCASSERT(action != NULL, ""); CCASSERT(action != nullptr, "");
CCASSERT(target != NULL, ""); CCASSERT(target != nullptr, "");
tHashElement *element = NULL; tHashElement *element = nullptr;
// we should convert it to Object*, because we save it as Object* // we should convert it to Object*, because we save it as Object*
Object *tmp = target; Object *tmp = target;
HASH_FIND_PTR(_targets, &tmp, element); HASH_FIND_PTR(_targets, &tmp, element);
@ -195,7 +195,7 @@ void ActionManager::addAction(Action *action, Node *target, bool paused)
void ActionManager::removeAllActions() void ActionManager::removeAllActions()
{ {
for (tHashElement *element = _targets; element != NULL; ) for (tHashElement *element = _targets; element != nullptr; )
{ {
auto target = element->target; auto target = element->target;
element = (tHashElement*)element->hh.next; element = (tHashElement*)element->hh.next;
@ -206,12 +206,12 @@ void ActionManager::removeAllActions()
void ActionManager::removeAllActionsFromTarget(Node *target) void ActionManager::removeAllActionsFromTarget(Node *target)
{ {
// explicit null handling // explicit null handling
if (target == NULL) if (target == nullptr)
{ {
return; return;
} }
tHashElement *element = NULL; tHashElement *element = nullptr;
HASH_FIND_PTR(_targets, &target, element); HASH_FIND_PTR(_targets, &target, element);
if (element) if (element)
{ {
@ -240,12 +240,12 @@ void ActionManager::removeAllActionsFromTarget(Node *target)
void ActionManager::removeAction(Action *action) void ActionManager::removeAction(Action *action)
{ {
// explicit null handling // explicit null handling
if (action == NULL) if (action == nullptr)
{ {
return; return;
} }
tHashElement *element = NULL; tHashElement *element = nullptr;
Object *target = action->getOriginalTarget(); Object *target = action->getOriginalTarget();
HASH_FIND_PTR(_targets, &target, element); HASH_FIND_PTR(_targets, &target, element);
if (element) if (element)
@ -265,9 +265,9 @@ void ActionManager::removeAction(Action *action)
void ActionManager::removeActionByTag(int tag, Node *target) void ActionManager::removeActionByTag(int tag, Node *target)
{ {
CCASSERT(tag != Action::INVALID_TAG, ""); CCASSERT(tag != Action::INVALID_TAG, "");
CCASSERT(target != NULL, ""); CCASSERT(target != nullptr, "");
tHashElement *element = NULL; tHashElement *element = nullptr;
HASH_FIND_PTR(_targets, &target, element); HASH_FIND_PTR(_targets, &target, element);
if (element) if (element)
@ -294,12 +294,12 @@ Action* ActionManager::getActionByTag(int tag, const Node *target) const
{ {
CCASSERT(tag != Action::INVALID_TAG, ""); CCASSERT(tag != Action::INVALID_TAG, "");
tHashElement *element = NULL; tHashElement *element = nullptr;
HASH_FIND_PTR(_targets, &target, element); HASH_FIND_PTR(_targets, &target, element);
if (element) if (element)
{ {
if (element->actions != NULL) if (element->actions != nullptr)
{ {
auto limit = element->actions->num; auto limit = element->actions->num;
for (int i = 0; i < limit; ++i) for (int i = 0; i < limit; ++i)
@ -319,14 +319,14 @@ Action* ActionManager::getActionByTag(int tag, const Node *target) const
// CCLOG("cocos2d : getActionByTag: Target not found"); // CCLOG("cocos2d : getActionByTag: Target not found");
} }
return NULL; return nullptr;
} }
// XXX: Passing "const O *" instead of "const O&" because HASH_FIND_IT requries the address of a pointer // XXX: Passing "const O *" instead of "const O&" because HASH_FIND_IT requries the address of a pointer
// and, it is not possible to get the address of a reference // and, it is not possible to get the address of a reference
ssize_t ActionManager::getNumberOfRunningActionsInTarget(const Node *target) const ssize_t ActionManager::getNumberOfRunningActionsInTarget(const Node *target) const
{ {
tHashElement *element = NULL; tHashElement *element = nullptr;
HASH_FIND_PTR(_targets, &target, element); HASH_FIND_PTR(_targets, &target, element);
if (element) if (element)
{ {
@ -339,7 +339,7 @@ ssize_t ActionManager::getNumberOfRunningActionsInTarget(const Node *target) con
// main loop // main loop
void ActionManager::update(float dt) void ActionManager::update(float dt)
{ {
for (tHashElement *elt = _targets; elt != NULL; ) for (tHashElement *elt = _targets; elt != nullptr; )
{ {
_currentTarget = elt; _currentTarget = elt;
_currentTargetSalvaged = false; _currentTargetSalvaged = false;
@ -351,7 +351,7 @@ void ActionManager::update(float dt)
_currentTarget->actionIndex++) _currentTarget->actionIndex++)
{ {
_currentTarget->currentAction = (Action*)_currentTarget->actions->arr[_currentTarget->actionIndex]; _currentTarget->currentAction = (Action*)_currentTarget->actions->arr[_currentTarget->actionIndex];
if (_currentTarget->currentAction == NULL) if (_currentTarget->currentAction == nullptr)
{ {
continue; continue;
} }
@ -373,11 +373,11 @@ void ActionManager::update(float dt)
Action *action = _currentTarget->currentAction; Action *action = _currentTarget->currentAction;
// Make currentAction nil to prevent removeAction from salvaging it. // Make currentAction nil to prevent removeAction from salvaging it.
_currentTarget->currentAction = NULL; _currentTarget->currentAction = nullptr;
removeAction(action); removeAction(action);
} }
_currentTarget->currentAction = NULL; _currentTarget->currentAction = nullptr;
} }
} }
@ -393,7 +393,7 @@ void ActionManager::update(float dt)
} }
// issue #635 // issue #635
_currentTarget = NULL; _currentTarget = nullptr;
} }
NS_CC_END NS_CC_END

View File

@ -72,7 +72,7 @@ public:
If the target is not present, a new instance of this target will be created either paused or not, and the action will be added to the newly created target. If the target is not present, a new instance of this target will be created either paused or not, and the action will be added to the newly created target.
When the target is paused, the queued actions won't be 'ticked'. When the target is paused, the queued actions won't be 'ticked'.
*/ */
void addAction(Action *pAction, Node *target, bool paused); void addAction(Action *action, Node *target, bool paused);
/** Removes all actions from all the targets. /** Removes all actions from all the targets.
*/ */
@ -85,7 +85,7 @@ public:
/** Removes an action given an action reference. /** Removes an action given an action reference.
*/ */
void removeAction(Action *pAction); void removeAction(Action *action);
/** Removes an action given its tag and the target */ /** Removes an action given its tag and the target */
void removeActionByTag(int tag, Node *target); void removeActionByTag(int tag, Node *target);
@ -124,9 +124,9 @@ public:
protected: protected:
// declared in ActionManager.m // declared in ActionManager.m
void removeActionAtIndex(ssize_t index, struct _hashElement *pElement); void removeActionAtIndex(ssize_t index, struct _hashElement *element);
void deleteHashElement(struct _hashElement *pElement); void deleteHashElement(struct _hashElement *element);
void actionAllocWithHashElement(struct _hashElement *pElement); void actionAllocWithHashElement(struct _hashElement *element);
void update(float dt); void update(float dt);
protected: protected:

View File

@ -28,21 +28,21 @@ NS_CC_BEGIN
PageTurn3D* PageTurn3D::create(float duration, const Size& gridSize) PageTurn3D* PageTurn3D::create(float duration, const Size& gridSize)
{ {
PageTurn3D *pAction = new PageTurn3D(); PageTurn3D *action = new PageTurn3D();
if (pAction) if (action)
{ {
if (pAction->initWithDuration(duration, gridSize)) if (action->initWithDuration(duration, gridSize))
{ {
pAction->autorelease(); action->autorelease();
} }
else else
{ {
CC_SAFE_RELEASE_NULL(pAction); CC_SAFE_RELEASE_NULL(action);
} }
} }
return pAction; return action;
} }
PageTurn3D *PageTurn3D::clone() const PageTurn3D *PageTurn3D::clone() const

View File

@ -31,20 +31,20 @@ NS_CC_BEGIN
// implementation of ProgressTo // implementation of ProgressTo
ProgressTo* ProgressTo::create(float duration, float fPercent) ProgressTo* ProgressTo::create(float duration, float percent)
{ {
ProgressTo *pProgressTo = new ProgressTo(); ProgressTo *progressTo = new ProgressTo();
pProgressTo->initWithDuration(duration, fPercent); progressTo->initWithDuration(duration, percent);
pProgressTo->autorelease(); progressTo->autorelease();
return pProgressTo; return progressTo;
} }
bool ProgressTo::initWithDuration(float duration, float fPercent) bool ProgressTo::initWithDuration(float duration, float percent)
{ {
if (ActionInterval::initWithDuration(duration)) if (ActionInterval::initWithDuration(duration))
{ {
_to = fPercent; _to = percent;
return true; return true;
} }
@ -87,21 +87,21 @@ void ProgressTo::update(float time)
// implementation of ProgressFromTo // implementation of ProgressFromTo
ProgressFromTo* ProgressFromTo::create(float duration, float fFromPercentage, float fToPercentage) ProgressFromTo* ProgressFromTo::create(float duration, float fromPercentage, float toPercentage)
{ {
ProgressFromTo *pProgressFromTo = new ProgressFromTo(); ProgressFromTo *progressFromTo = new ProgressFromTo();
pProgressFromTo->initWithDuration(duration, fFromPercentage, fToPercentage); progressFromTo->initWithDuration(duration, fromPercentage, toPercentage);
pProgressFromTo->autorelease(); progressFromTo->autorelease();
return pProgressFromTo; return progressFromTo;
} }
bool ProgressFromTo::initWithDuration(float duration, float fFromPercentage, float fToPercentage) bool ProgressFromTo::initWithDuration(float duration, float fromPercentage, float toPercentage)
{ {
if (ActionInterval::initWithDuration(duration)) if (ActionInterval::initWithDuration(duration))
{ {
_to = fToPercentage; _to = toPercentage;
_from = fFromPercentage; _from = fromPercentage;
return true; return true;
} }

View File

@ -42,7 +42,7 @@ class CC_DLL ProgressTo : public ActionInterval
{ {
public: public:
/** Creates and initializes with a duration and a percent */ /** Creates and initializes with a duration and a percent */
static ProgressTo* create(float duration, float fPercent); static ProgressTo* create(float duration, float percent);
// //
// Overrides // Overrides
@ -56,7 +56,7 @@ protected:
ProgressTo() {} ProgressTo() {}
virtual ~ProgressTo() {} virtual ~ProgressTo() {}
/** Initializes with a duration and a percent */ /** Initializes with a duration and a percent */
bool initWithDuration(float duration, float fPercent); bool initWithDuration(float duration, float percent);
float _to; float _to;
float _from; float _from;
@ -73,7 +73,7 @@ class CC_DLL ProgressFromTo : public ActionInterval
{ {
public: public:
/** Creates and initializes the action with a duration, a "from" percentage and a "to" percentage */ /** Creates and initializes the action with a duration, a "from" percentage and a "to" percentage */
static ProgressFromTo* create(float duration, float fFromPercentage, float fToPercentage); static ProgressFromTo* create(float duration, float fromPercentage, float toPercentage);
// //
// Overrides // Overrides
@ -87,7 +87,7 @@ protected:
ProgressFromTo() {} ProgressFromTo() {}
virtual ~ProgressFromTo() {} virtual ~ProgressFromTo() {}
/** Initializes the action with a duration, a "from" percentage and a "to" percentage */ /** Initializes the action with a duration, a "from" percentage and a "to" percentage */
bool initWithDuration(float duration, float fFromPercentage, float fToPercentage); bool initWithDuration(float duration, float fromPercentage, float toPercentage);
float _to; float _to;
float _from; float _from;

View File

@ -26,6 +26,7 @@ THE SOFTWARE.
#include "CCDirector.h" #include "CCDirector.h"
#include "ccMacros.h" #include "ccMacros.h"
#include "CCGrid.h" #include "CCGrid.h"
#include "CCNodeGrid.h"
#include <stdlib.h> #include <stdlib.h>
NS_CC_BEGIN NS_CC_BEGIN
@ -39,31 +40,31 @@ struct Tile
// implementation of ShakyTiles3D // implementation of ShakyTiles3D
ShakyTiles3D* ShakyTiles3D::create(float duration, const Size& gridSize, int nRange, bool bShakeZ) ShakyTiles3D* ShakyTiles3D::create(float duration, const Size& gridSize, int range, bool shakeZ)
{ {
ShakyTiles3D *pAction = new ShakyTiles3D(); ShakyTiles3D *action = new ShakyTiles3D();
if (pAction) if (action)
{ {
if (pAction->initWithDuration(duration, gridSize, nRange, bShakeZ)) if (action->initWithDuration(duration, gridSize, range, shakeZ))
{ {
pAction->autorelease(); action->autorelease();
} }
else else
{ {
CC_SAFE_RELEASE_NULL(pAction); CC_SAFE_RELEASE_NULL(action);
} }
} }
return pAction; return action;
} }
bool ShakyTiles3D::initWithDuration(float duration, const Size& gridSize, int nRange, bool bShakeZ) bool ShakyTiles3D::initWithDuration(float duration, const Size& gridSize, int range, bool shakeZ)
{ {
if (TiledGrid3DAction::initWithDuration(duration, gridSize)) if (TiledGrid3DAction::initWithDuration(duration, gridSize))
{ {
_randrange = nRange; _randrange = range;
_shakeZ = bShakeZ; _shakeZ = shakeZ;
return true; return true;
} }
@ -118,32 +119,32 @@ void ShakyTiles3D::update(float time)
// implementation of ShatteredTiles3D // implementation of ShatteredTiles3D
ShatteredTiles3D* ShatteredTiles3D::create(float duration, const Size& gridSize, int nRange, bool bShatterZ) ShatteredTiles3D* ShatteredTiles3D::create(float duration, const Size& gridSize, int range, bool shatterZ)
{ {
ShatteredTiles3D *pAction = new ShatteredTiles3D(); ShatteredTiles3D *action = new ShatteredTiles3D();
if (pAction) if (action)
{ {
if (pAction->initWithDuration(duration, gridSize, nRange, bShatterZ)) if (action->initWithDuration(duration, gridSize, range, shatterZ))
{ {
pAction->autorelease(); action->autorelease();
} }
else else
{ {
CC_SAFE_RELEASE_NULL(pAction); CC_SAFE_RELEASE_NULL(action);
} }
} }
return pAction; return action;
} }
bool ShatteredTiles3D::initWithDuration(float duration, const Size& gridSize, int nRange, bool bShatterZ) bool ShatteredTiles3D::initWithDuration(float duration, const Size& gridSize, int range, bool shatterZ)
{ {
if (TiledGrid3DAction::initWithDuration(duration, gridSize)) if (TiledGrid3DAction::initWithDuration(duration, gridSize))
{ {
_once = false; _once = false;
_randrange = nRange; _randrange = range;
_shatterZ = bShatterZ; _shatterZ = shatterZ;
return true; return true;
} }
@ -205,21 +206,21 @@ void ShatteredTiles3D::update(float time)
ShuffleTiles* ShuffleTiles::create(float duration, const Size& gridSize, unsigned int seed) ShuffleTiles* ShuffleTiles::create(float duration, const Size& gridSize, unsigned int seed)
{ {
ShuffleTiles *pAction = new ShuffleTiles(); ShuffleTiles *action = new ShuffleTiles();
if (pAction) if (action)
{ {
if (pAction->initWithDuration(duration, gridSize, seed)) if (action->initWithDuration(duration, gridSize, seed))
{ {
pAction->autorelease(); action->autorelease();
} }
else else
{ {
CC_SAFE_RELEASE_NULL(pAction); CC_SAFE_RELEASE_NULL(action);
} }
} }
return pAction; return action;
} }
bool ShuffleTiles::initWithDuration(float duration, const Size& gridSize, unsigned int seed) bool ShuffleTiles::initWithDuration(float duration, const Size& gridSize, unsigned int seed)
@ -227,8 +228,8 @@ bool ShuffleTiles::initWithDuration(float duration, const Size& gridSize, unsign
if (TiledGrid3DAction::initWithDuration(duration, gridSize)) if (TiledGrid3DAction::initWithDuration(duration, gridSize))
{ {
_seed = seed; _seed = seed;
_tilesOrder = NULL; _tilesOrder = nullptr;
_tiles = NULL; _tiles = nullptr;
return true; return true;
} }
@ -251,15 +252,15 @@ ShuffleTiles::~ShuffleTiles(void)
CC_SAFE_DELETE_ARRAY(_tiles); CC_SAFE_DELETE_ARRAY(_tiles);
} }
void ShuffleTiles::shuffle(unsigned int *pArray, unsigned int nLen) void ShuffleTiles::shuffle(unsigned int *array, unsigned int len)
{ {
int i; int i;
for( i = nLen - 1; i >= 0; i-- ) for( i = len - 1; i >= 0; i-- )
{ {
unsigned int j = rand() % (i+1); unsigned int j = rand() % (i+1);
unsigned int v = pArray[i]; unsigned int v = array[i];
pArray[i] = pArray[j]; array[i] = array[j];
pArray[j] = v; array[j] = v;
} }
} }
@ -279,7 +280,7 @@ void ShuffleTiles::placeTile(const Point& pos, Tile *t)
{ {
Quad3 coords = getOriginalTile(pos); Quad3 coords = getOriginalTile(pos);
Point step = _target->getGrid()->getStep(); Point step = _gridNodeTarget->getGrid()->getStep();
coords.bl.x += (int)(t->position.x * step.x); coords.bl.x += (int)(t->position.x * step.x);
coords.bl.y += (int)(t->position.y * step.y); coords.bl.y += (int)(t->position.y * step.y);
@ -356,21 +357,21 @@ void ShuffleTiles::update(float time)
FadeOutTRTiles* FadeOutTRTiles::create(float duration, const Size& gridSize) FadeOutTRTiles* FadeOutTRTiles::create(float duration, const Size& gridSize)
{ {
FadeOutTRTiles *pAction = new FadeOutTRTiles(); FadeOutTRTiles *action = new FadeOutTRTiles();
if (pAction) if (action)
{ {
if (pAction->initWithDuration(duration, gridSize)) if (action->initWithDuration(duration, gridSize))
{ {
pAction->autorelease(); action->autorelease();
} }
else else
{ {
CC_SAFE_RELEASE_NULL(pAction); CC_SAFE_RELEASE_NULL(action);
} }
} }
return pAction; return action;
} }
FadeOutTRTiles* FadeOutTRTiles::clone() const FadeOutTRTiles* FadeOutTRTiles::clone() const
@ -408,7 +409,7 @@ void FadeOutTRTiles::turnOffTile(const Point& pos)
void FadeOutTRTiles::transformTile(const Point& pos, float distance) void FadeOutTRTiles::transformTile(const Point& pos, float distance)
{ {
Quad3 coords = getOriginalTile(pos); Quad3 coords = getOriginalTile(pos);
Point step = _target->getGrid()->getStep(); Point step = _gridNodeTarget->getGrid()->getStep();
coords.bl.x += (step.x / 2) * (1.0f - distance); coords.bl.x += (step.x / 2) * (1.0f - distance);
coords.bl.y += (step.y / 2) * (1.0f - distance); coords.bl.y += (step.y / 2) * (1.0f - distance);
@ -454,21 +455,21 @@ void FadeOutTRTiles::update(float time)
FadeOutBLTiles* FadeOutBLTiles::create(float duration, const Size& gridSize) FadeOutBLTiles* FadeOutBLTiles::create(float duration, const Size& gridSize)
{ {
FadeOutBLTiles *pAction = new FadeOutBLTiles(); FadeOutBLTiles *action = new FadeOutBLTiles();
if (pAction) if (action)
{ {
if (pAction->initWithDuration(duration, gridSize)) if (action->initWithDuration(duration, gridSize))
{ {
pAction->autorelease(); action->autorelease();
} }
else else
{ {
CC_SAFE_RELEASE_NULL(pAction); CC_SAFE_RELEASE_NULL(action);
} }
} }
return pAction; return action;
} }
FadeOutBLTiles* FadeOutBLTiles::clone() const FadeOutBLTiles* FadeOutBLTiles::clone() const
@ -495,21 +496,21 @@ float FadeOutBLTiles::testFunc(const Size& pos, float time)
FadeOutUpTiles* FadeOutUpTiles::create(float duration, const Size& gridSize) FadeOutUpTiles* FadeOutUpTiles::create(float duration, const Size& gridSize)
{ {
FadeOutUpTiles *pAction = new FadeOutUpTiles(); FadeOutUpTiles *action = new FadeOutUpTiles();
if (pAction) if (action)
{ {
if (pAction->initWithDuration(duration, gridSize)) if (action->initWithDuration(duration, gridSize))
{ {
pAction->autorelease(); action->autorelease();
} }
else else
{ {
CC_SAFE_RELEASE_NULL(pAction); CC_SAFE_RELEASE_NULL(action);
} }
} }
return pAction; return action;
} }
FadeOutUpTiles* FadeOutUpTiles::clone() const FadeOutUpTiles* FadeOutUpTiles::clone() const
@ -535,7 +536,7 @@ float FadeOutUpTiles::testFunc(const Size& pos, float time)
void FadeOutUpTiles::transformTile(const Point& pos, float distance) void FadeOutUpTiles::transformTile(const Point& pos, float distance)
{ {
Quad3 coords = getOriginalTile(pos); Quad3 coords = getOriginalTile(pos);
Point step = _target->getGrid()->getStep(); Point step = _gridNodeTarget->getGrid()->getStep();
coords.bl.y += (step.y / 2) * (1.0f - distance); coords.bl.y += (step.y / 2) * (1.0f - distance);
coords.br.y += (step.y / 2) * (1.0f - distance); coords.br.y += (step.y / 2) * (1.0f - distance);
@ -549,21 +550,21 @@ void FadeOutUpTiles::transformTile(const Point& pos, float distance)
FadeOutDownTiles* FadeOutDownTiles::create(float duration, const Size& gridSize) FadeOutDownTiles* FadeOutDownTiles::create(float duration, const Size& gridSize)
{ {
FadeOutDownTiles *pAction = new FadeOutDownTiles(); FadeOutDownTiles *action = new FadeOutDownTiles();
if (pAction) if (action)
{ {
if (pAction->initWithDuration(duration, gridSize)) if (action->initWithDuration(duration, gridSize))
{ {
pAction->autorelease(); action->autorelease();
} }
else else
{ {
CC_SAFE_RELEASE_NULL(pAction); CC_SAFE_RELEASE_NULL(action);
} }
} }
return pAction; return action;
} }
FadeOutDownTiles* FadeOutDownTiles::clone() const FadeOutDownTiles* FadeOutDownTiles::clone() const
@ -604,21 +605,21 @@ TurnOffTiles* TurnOffTiles::create(float duration, const Size& gridSize)
TurnOffTiles* TurnOffTiles::create(float duration, const Size& gridSize, unsigned int seed) TurnOffTiles* TurnOffTiles::create(float duration, const Size& gridSize, unsigned int seed)
{ {
TurnOffTiles *pAction = new TurnOffTiles(); TurnOffTiles *action = new TurnOffTiles();
if (pAction) if (action)
{ {
if (pAction->initWithDuration(duration, gridSize, seed)) if (action->initWithDuration(duration, gridSize, seed))
{ {
pAction->autorelease(); action->autorelease();
} }
else else
{ {
CC_SAFE_RELEASE_NULL(pAction); CC_SAFE_RELEASE_NULL(action);
} }
} }
return pAction; return action;
} }
bool TurnOffTiles::initWithDuration(float duration, const Size& gridSize, unsigned int seed) bool TurnOffTiles::initWithDuration(float duration, const Size& gridSize, unsigned int seed)
@ -626,7 +627,7 @@ bool TurnOffTiles::initWithDuration(float duration, const Size& gridSize, unsign
if (TiledGrid3DAction::initWithDuration(duration, gridSize)) if (TiledGrid3DAction::initWithDuration(duration, gridSize))
{ {
_seed = seed; _seed = seed;
_tilesOrder = NULL; _tilesOrder = nullptr;
return true; return true;
} }
@ -648,15 +649,15 @@ TurnOffTiles::~TurnOffTiles(void)
CC_SAFE_DELETE_ARRAY(_tilesOrder); CC_SAFE_DELETE_ARRAY(_tilesOrder);
} }
void TurnOffTiles::shuffle(unsigned int *pArray, unsigned int nLen) void TurnOffTiles::shuffle(unsigned int *array, unsigned int len)
{ {
int i; int i;
for (i = nLen - 1; i >= 0; i--) for (i = len - 1; i >= 0; i--)
{ {
unsigned int j = rand() % (i+1); unsigned int j = rand() % (i+1);
unsigned int v = pArray[i]; unsigned int v = array[i];
pArray[i] = pArray[j]; array[i] = array[j];
pArray[j] = v; array[j] = v;
} }
} }
@ -721,21 +722,21 @@ void TurnOffTiles::update(float time)
WavesTiles3D* WavesTiles3D::create(float duration, const Size& gridSize, unsigned int waves, float amplitude) WavesTiles3D* WavesTiles3D::create(float duration, const Size& gridSize, unsigned int waves, float amplitude)
{ {
WavesTiles3D *pAction = new WavesTiles3D(); WavesTiles3D *action = new WavesTiles3D();
if (pAction) if (action)
{ {
if (pAction->initWithDuration(duration, gridSize, waves, amplitude)) if (action->initWithDuration(duration, gridSize, waves, amplitude))
{ {
pAction->autorelease(); action->autorelease();
} }
else else
{ {
CC_SAFE_RELEASE_NULL(pAction); CC_SAFE_RELEASE_NULL(action);
} }
} }
return pAction; return action;
} }
bool WavesTiles3D::initWithDuration(float duration, const Size& gridSize, unsigned int waves, float amplitude) bool WavesTiles3D::initWithDuration(float duration, const Size& gridSize, unsigned int waves, float amplitude)
@ -786,21 +787,21 @@ void WavesTiles3D::update(float time)
JumpTiles3D* JumpTiles3D::create(float duration, const Size& gridSize, unsigned int numberOfJumps, float amplitude) JumpTiles3D* JumpTiles3D::create(float duration, const Size& gridSize, unsigned int numberOfJumps, float amplitude)
{ {
JumpTiles3D *pAction = new JumpTiles3D(); JumpTiles3D *action = new JumpTiles3D();
if (pAction) if (action)
{ {
if (pAction->initWithDuration(duration, gridSize, numberOfJumps, amplitude)) if (action->initWithDuration(duration, gridSize, numberOfJumps, amplitude))
{ {
pAction->autorelease(); action->autorelease();
} }
else else
{ {
CC_SAFE_RELEASE_NULL(pAction); CC_SAFE_RELEASE_NULL(action);
} }
} }
return pAction; return action;
} }
bool JumpTiles3D::initWithDuration(float duration, const Size& gridSize, unsigned int numberOfJumps, float amplitude) bool JumpTiles3D::initWithDuration(float duration, const Size& gridSize, unsigned int numberOfJumps, float amplitude)
@ -863,28 +864,28 @@ void JumpTiles3D::update(float time)
SplitRows* SplitRows::create(float duration, unsigned int nRows) SplitRows* SplitRows::create(float duration, unsigned int nRows)
{ {
SplitRows *pAction = new SplitRows(); SplitRows *action = new SplitRows();
if (pAction) if (action)
{ {
if (pAction->initWithDuration(duration, nRows)) if (action->initWithDuration(duration, nRows))
{ {
pAction->autorelease(); action->autorelease();
} }
else else
{ {
CC_SAFE_RELEASE_NULL(pAction); CC_SAFE_RELEASE_NULL(action);
} }
} }
return pAction; return action;
} }
bool SplitRows::initWithDuration(float duration, unsigned int nRows) bool SplitRows::initWithDuration(float duration, unsigned int rows)
{ {
_rows = nRows; _rows = rows;
return TiledGrid3DAction::initWithDuration(duration, Size(1, nRows)); return TiledGrid3DAction::initWithDuration(duration, Size(1, rows));
} }
SplitRows* SplitRows::clone() const SplitRows* SplitRows::clone() const
@ -927,29 +928,29 @@ void SplitRows::update(float time)
// implementation of SplitCols // implementation of SplitCols
SplitCols* SplitCols::create(float duration, unsigned int nCols) SplitCols* SplitCols::create(float duration, unsigned int cols)
{ {
SplitCols *pAction = new SplitCols(); SplitCols *action = new SplitCols();
if (pAction) if (action)
{ {
if (pAction->initWithDuration(duration, nCols)) if (action->initWithDuration(duration, cols))
{ {
pAction->autorelease(); action->autorelease();
} }
else else
{ {
CC_SAFE_RELEASE_NULL(pAction); CC_SAFE_RELEASE_NULL(action);
} }
} }
return pAction; return action;
} }
bool SplitCols::initWithDuration(float duration, unsigned int nCols) bool SplitCols::initWithDuration(float duration, unsigned int cols)
{ {
_cols = nCols; _cols = cols;
return TiledGrid3DAction::initWithDuration(duration, Size(nCols, 1)); return TiledGrid3DAction::initWithDuration(duration, Size(cols, 1));
} }
SplitCols* SplitCols::clone() const SplitCols* SplitCols::clone() const

View File

@ -39,7 +39,7 @@ class CC_DLL ShakyTiles3D : public TiledGrid3DAction
{ {
public: public:
/** creates the action with a range, whether or not to shake Z vertices, a grid size, and duration */ /** creates the action with a range, whether or not to shake Z vertices, a grid size, and duration */
static ShakyTiles3D* create(float duration, const Size& gridSize, int nRange, bool bShakeZ); static ShakyTiles3D* create(float duration, const Size& gridSize, int range, bool shakeZ);
// Override // Override
virtual ShakyTiles3D* clone() const override; virtual ShakyTiles3D* clone() const override;
@ -49,7 +49,7 @@ protected:
ShakyTiles3D() {} ShakyTiles3D() {}
virtual ~ShakyTiles3D() {} virtual ~ShakyTiles3D() {}
/** initializes the action with a range, whether or not to shake Z vertices, a grid size, and duration */ /** initializes the action with a range, whether or not to shake Z vertices, a grid size, and duration */
bool initWithDuration(float duration, const Size& gridSize, int nRange, bool bShakeZ); bool initWithDuration(float duration, const Size& gridSize, int range, bool shakeZ);
int _randrange; int _randrange;
bool _shakeZ; bool _shakeZ;
@ -63,7 +63,7 @@ class CC_DLL ShatteredTiles3D : public TiledGrid3DAction
{ {
public: public:
/** creates the action with a range, whether of not to shatter Z vertices, a grid size and duration */ /** creates the action with a range, whether of not to shatter Z vertices, a grid size and duration */
static ShatteredTiles3D* create(float duration, const Size& gridSize, int nRange, bool bShatterZ); static ShatteredTiles3D* create(float duration, const Size& gridSize, int range, bool shatterZ);
// Override // Override
virtual ShatteredTiles3D* clone() const override; virtual ShatteredTiles3D* clone() const override;
@ -73,7 +73,7 @@ protected:
ShatteredTiles3D() {} ShatteredTiles3D() {}
virtual ~ShatteredTiles3D() {} virtual ~ShatteredTiles3D() {}
/** initializes the action with a range, whether or not to shatter Z vertices, a grid size and duration */ /** initializes the action with a range, whether or not to shatter Z vertices, a grid size and duration */
bool initWithDuration(float duration, const Size& gridSize, int nRange, bool bShatterZ); bool initWithDuration(float duration, const Size& gridSize, int range, bool shatterZ);
int _randrange; int _randrange;
bool _once; bool _once;
@ -93,7 +93,7 @@ public:
/** creates the action with a random seed, the grid size and the duration */ /** creates the action with a random seed, the grid size and the duration */
static ShuffleTiles* create(float duration, const Size& gridSize, unsigned int seed); static ShuffleTiles* create(float duration, const Size& gridSize, unsigned int seed);
void shuffle(unsigned int *array, unsigned int nLen); void shuffle(unsigned int *array, unsigned int len);
Size getDelta(const Size& pos) const; Size getDelta(const Size& pos) const;
void placeTile(const Point& pos, Tile *t); void placeTile(const Point& pos, Tile *t);
@ -219,7 +219,7 @@ public:
/** creates the action with a random seed, the grid size and the duration */ /** creates the action with a random seed, the grid size and the duration */
static TurnOffTiles* create(float duration, const Size& gridSize, unsigned int seed); static TurnOffTiles* create(float duration, const Size& gridSize, unsigned int seed);
void shuffle(unsigned int *pArray, unsigned int nLen); void shuffle(unsigned int *array, unsigned int len);
void turnOnTile(const Point& pos); void turnOnTile(const Point& pos);
void turnOffTile(const Point& pos); void turnOffTile(const Point& pos);
@ -251,11 +251,11 @@ public:
/** waves amplitude */ /** waves amplitude */
inline float getAmplitude(void) const { return _amplitude; } inline float getAmplitude(void) const { return _amplitude; }
inline void setAmplitude(float fAmplitude) { _amplitude = fAmplitude; } inline void setAmplitude(float amplitude) { _amplitude = amplitude; }
/** waves amplitude rate */ /** waves amplitude rate */
inline float getAmplitudeRate(void) const { return _amplitudeRate; } inline float getAmplitudeRate(void) const { return _amplitudeRate; }
inline void setAmplitudeRate(float fAmplitudeRate) { _amplitudeRate = fAmplitudeRate; } inline void setAmplitudeRate(float amplitudeRate) { _amplitudeRate = amplitudeRate; }
// Override // Override
virtual WavesTiles3D* clone() const override; virtual WavesTiles3D* clone() const override;
@ -286,11 +286,11 @@ public:
/** amplitude of the sin*/ /** amplitude of the sin*/
inline float getAmplitude(void) const { return _amplitude; } inline float getAmplitude(void) const { return _amplitude; }
inline void setAmplitude(float fAmplitude) { _amplitude = fAmplitude; } inline void setAmplitude(float amplitude) { _amplitude = amplitude; }
/** amplitude rate */ /** amplitude rate */
inline float getAmplitudeRate(void) const { return _amplitudeRate; } inline float getAmplitudeRate(void) const { return _amplitudeRate; }
inline void setAmplitudeRate(float fAmplitudeRate) { _amplitudeRate = fAmplitudeRate; } inline void setAmplitudeRate(float amplitudeRate) { _amplitudeRate = amplitudeRate; }
// Override // Override
virtual JumpTiles3D* clone() const override; virtual JumpTiles3D* clone() const override;
@ -315,7 +315,7 @@ class CC_DLL SplitRows : public TiledGrid3DAction
{ {
public : public :
/** creates the action with the number of rows to split and the duration */ /** creates the action with the number of rows to split and the duration */
static SplitRows* create(float duration, unsigned int nRows); static SplitRows* create(float duration, unsigned int rows);
// Overrides // Overrides
virtual SplitRows* clone() const override; virtual SplitRows* clone() const override;
@ -326,7 +326,7 @@ protected:
SplitRows() {} SplitRows() {}
virtual ~SplitRows() {} virtual ~SplitRows() {}
/** initializes the action with the number of rows to split and the duration */ /** initializes the action with the number of rows to split and the duration */
bool initWithDuration(float duration, unsigned int nRows); bool initWithDuration(float duration, unsigned int rows);
unsigned int _rows; unsigned int _rows;
Size _winSize; Size _winSize;
@ -340,7 +340,7 @@ class CC_DLL SplitCols : public TiledGrid3DAction
{ {
public: public:
/** creates the action with the number of columns to split and the duration */ /** creates the action with the number of columns to split and the duration */
static SplitCols* create(float duration, unsigned int nCols); static SplitCols* create(float duration, unsigned int cols);
// Overrides // Overrides
virtual SplitCols* clone() const override; virtual SplitCols* clone() const override;
@ -351,7 +351,7 @@ protected:
SplitCols() {} SplitCols() {}
virtual ~SplitCols() {} virtual ~SplitCols() {}
/** initializes the action with the number of columns to split and the duration */ /** initializes the action with the number of columns to split and the duration */
bool initWithDuration(float duration, unsigned int nCols); bool initWithDuration(float duration, unsigned int cols);
unsigned int _cols; unsigned int _cols;
Size _winSize; Size _winSize;

View File

@ -29,21 +29,21 @@ NS_CC_BEGIN
ActionTween* ActionTween::create(float aDuration, const std::string& key, float from, float to) ActionTween* ActionTween::create(float aDuration, const std::string& key, float from, float to)
{ {
ActionTween* pRet = new ActionTween(); ActionTween* ret = new ActionTween();
if (pRet && pRet->initWithDuration(aDuration, key, from, to)) if (ret && ret->initWithDuration(aDuration, key, from, to))
{ {
pRet->autorelease(); ret->autorelease();
} }
else else
{ {
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
} }
return pRet; return ret;
} }
bool ActionTween::initWithDuration(float aDuration, const std::string& key, float from, float to) bool ActionTween::initWithDuration(float duration, const std::string& key, float from, float to)
{ {
if (ActionInterval::initWithDuration(aDuration)) if (ActionInterval::initWithDuration(duration))
{ {
_key = key; _key = key;
_to = to; _to = to;

View File

@ -47,7 +47,7 @@ AnimationFrame* AnimationFrame::create(SpriteFrame* spriteFrame, float delayUnit
} }
AnimationFrame::AnimationFrame() AnimationFrame::AnimationFrame()
: _spriteFrame(NULL) : _spriteFrame(nullptr)
, _delayUnits(0.0f) , _delayUnits(0.0f)
{ {
@ -85,28 +85,28 @@ AnimationFrame* AnimationFrame::clone() const
Animation* Animation::create(void) Animation* Animation::create(void)
{ {
Animation *pAnimation = new Animation(); Animation *animation = new Animation();
pAnimation->init(); animation->init();
pAnimation->autorelease(); animation->autorelease();
return pAnimation; return animation;
} }
Animation* Animation::createWithSpriteFrames(const Vector<SpriteFrame*>& frames, float delay/* = 0.0f*/) Animation* Animation::createWithSpriteFrames(const Vector<SpriteFrame*>& frames, float delay/* = 0.0f*/)
{ {
Animation *pAnimation = new Animation(); Animation *animation = new Animation();
pAnimation->initWithSpriteFrames(frames, delay); animation->initWithSpriteFrames(frames, delay);
pAnimation->autorelease(); animation->autorelease();
return pAnimation; return animation;
} }
Animation* Animation::create(const Vector<AnimationFrame*>& arrayOfAnimationFrameNames, float delayPerUnit, unsigned int loops /* = 1 */) Animation* Animation::create(const Vector<AnimationFrame*>& arrayOfAnimationFrameNames, float delayPerUnit, unsigned int loops /* = 1 */)
{ {
Animation *pAnimation = new Animation(); Animation *animation = new Animation();
pAnimation->initWithAnimationFrames(arrayOfAnimationFrameNames, delayPerUnit, loops); animation->initWithAnimationFrames(arrayOfAnimationFrameNames, delayPerUnit, loops);
pAnimation->autorelease(); animation->autorelease();
return pAnimation; return animation;
} }
bool Animation::init() bool Animation::init()
@ -175,14 +175,14 @@ void Animation::addSpriteFrameWithFile(const std::string& filename)
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename); Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(filename);
Rect rect = Rect::ZERO; Rect rect = Rect::ZERO;
rect.size = texture->getContentSize(); rect.size = texture->getContentSize();
SpriteFrame *pFrame = SpriteFrame::createWithTexture(texture, rect); SpriteFrame *frame = SpriteFrame::createWithTexture(texture, rect);
addSpriteFrame(pFrame); addSpriteFrame(frame);
} }
void Animation::addSpriteFrameWithTexture(Texture2D *pobTexture, const Rect& rect) void Animation::addSpriteFrameWithTexture(Texture2D *pobTexture, const Rect& rect)
{ {
SpriteFrame *pFrame = SpriteFrame::createWithTexture(pobTexture, rect); SpriteFrame *frame = SpriteFrame::createWithTexture(pobTexture, rect);
addSpriteFrame(pFrame); addSpriteFrame(frame);
} }
float Animation::getDuration(void) const float Animation::getDuration(void) const

View File

@ -157,7 +157,7 @@ public:
/** Adds a SpriteFrame to a Animation. /** Adds a SpriteFrame to a Animation.
The frame will be added with one "delay unit". The frame will be added with one "delay unit".
*/ */
void addSpriteFrame(SpriteFrame *pFrame); void addSpriteFrame(SpriteFrame *frame);
/** Adds a frame with an image filename. Internally it will create a SpriteFrame and it will add it. /** Adds a frame with an image filename. Internally it will create a SpriteFrame and it will add it.
The frame will be added with one "delay unit". The frame will be added with one "delay unit".

View File

@ -35,22 +35,22 @@ using namespace std;
NS_CC_BEGIN NS_CC_BEGIN
AnimationCache* AnimationCache::s_pSharedAnimationCache = NULL; AnimationCache* AnimationCache::s_sharedAnimationCache = nullptr;
AnimationCache* AnimationCache::getInstance() AnimationCache* AnimationCache::getInstance()
{ {
if (! s_pSharedAnimationCache) if (! s_sharedAnimationCache)
{ {
s_pSharedAnimationCache = new AnimationCache(); s_sharedAnimationCache = new AnimationCache();
s_pSharedAnimationCache->init(); s_sharedAnimationCache->init();
} }
return s_pSharedAnimationCache; return s_sharedAnimationCache;
} }
void AnimationCache::destroyInstance() void AnimationCache::destroyInstance()
{ {
CC_SAFE_RELEASE_NULL(s_pSharedAnimationCache); CC_SAFE_RELEASE_NULL(s_sharedAnimationCache);
} }
bool AnimationCache::init() bool AnimationCache::init()
@ -102,7 +102,8 @@ void AnimationCache::parseVersion1(const ValueMap& animations)
continue; continue;
} }
Vector<AnimationFrame*> frames(static_cast<int>(frameNames.size())); ssize_t frameNameSize = frameNames.size();
Vector<AnimationFrame*> frames(frameNameSize);
for (auto& frameName : frameNames) for (auto& frameName : frameNames)
{ {
@ -118,12 +119,12 @@ void AnimationCache::parseVersion1(const ValueMap& animations)
frames.pushBack(animFrame); frames.pushBack(animFrame);
} }
if ( frames.size() == 0 ) if ( frames.empty() )
{ {
CCLOG("cocos2d: AnimationCache: None of the frames for animation '%s' were found in the SpriteFrameCache. Animation is not being added to the Animation Cache.", iter->first.c_str()); CCLOG("cocos2d: AnimationCache: None of the frames for animation '%s' were found in the SpriteFrameCache. Animation is not being added to the Animation Cache.", iter->first.c_str());
continue; continue;
} }
else if ( frames.size() != frameNames.size() ) else if ( frames.size() != frameNameSize )
{ {
CCLOG("cocos2d: AnimationCache: An animation in your dictionary refers to a frame which is not in the SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.", iter->first.c_str()); CCLOG("cocos2d: AnimationCache: An animation in your dictionary refers to a frame which is not in the SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.", iter->first.c_str());
} }
@ -203,9 +204,9 @@ void AnimationCache::addAnimationsWithDictionary(const ValueMap& dictionary)
version = properties.at("format").asInt(); version = properties.at("format").asInt();
const ValueVector& spritesheets = properties.at("spritesheets").asValueVector(); const ValueVector& spritesheets = properties.at("spritesheets").asValueVector();
std::for_each(spritesheets.cbegin(), spritesheets.cend(), [](const Value& value){ for(const auto &value : spritesheets) {
SpriteFrameCache::getInstance()->addSpriteFramesWithFile(value.asString()); SpriteFrameCache::getInstance()->addSpriteFramesWithFile(value.asString());
}); }
} }
switch (version) { switch (version) {

View File

@ -120,7 +120,7 @@ private:
private: private:
Map<std::string, Animation*> _animations; Map<std::string, Animation*> _animations;
static AnimationCache* s_pSharedAnimationCache; static AnimationCache* s_sharedAnimationCache;
}; };
// end of sprite_nodes group // end of sprite_nodes group

View File

@ -33,6 +33,8 @@ THE SOFTWARE.
#include "ccGLStateCache.h" #include "ccGLStateCache.h"
#include "CCDirector.h" #include "CCDirector.h"
#include "TransformUtils.h" #include "TransformUtils.h"
#include "CCRenderer.h"
#include "renderer/CCQuadCommand.h"
// external // external
#include "kazmath/GL/matrix.h" #include "kazmath/GL/matrix.h"
@ -48,7 +50,7 @@ AtlasNode::AtlasNode()
, _itemsPerColumn(0) , _itemsPerColumn(0)
, _itemWidth(0) , _itemWidth(0)
, _itemHeight(0) , _itemHeight(0)
, _textureAtlas(NULL) , _textureAtlas(nullptr)
, _isOpacityModifyRGB(false) , _isOpacityModifyRGB(false)
, _quadsToDraw(0) , _quadsToDraw(0)
, _uniformColor(0) , _uniformColor(0)
@ -63,14 +65,14 @@ AtlasNode::~AtlasNode()
AtlasNode * AtlasNode::create(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender) AtlasNode * AtlasNode::create(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender)
{ {
AtlasNode * pRet = new AtlasNode(); AtlasNode * ret = new AtlasNode();
if (pRet->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender)) if (ret->initWithTileFile(tile, tileWidth, tileHeight, itemsToRender))
{ {
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return nullptr;
} }
bool AtlasNode::initWithTileFile(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender) bool AtlasNode::initWithTileFile(const std::string& tile, int tileWidth, int tileHeight, int itemsToRender)
@ -137,14 +139,29 @@ void AtlasNode::updateAtlasValues()
// AtlasNode - draw // AtlasNode - draw
void AtlasNode::draw(void) void AtlasNode::draw(void)
{ {
CC_NODE_DRAW_SETUP(); // CC_NODE_DRAW_SETUP();
//
// GL::blendFunc( _blendFunc.src, _blendFunc.dst );
//
// GLfloat colors[4] = {_displayedColor.r / 255.0f, _displayedColor.g / 255.0f, _displayedColor.b / 255.0f, _displayedOpacity / 255.0f};
// getShaderProgram()->setUniformLocationWith4fv(_uniformColor, colors, 1);
//
// _textureAtlas->drawNumberOfQuads(_quadsToDraw, 0);
GL::blendFunc( _blendFunc.src, _blendFunc.dst );
GLfloat colors[4] = {_displayedColor.r / 255.0f, _displayedColor.g / 255.0f, _displayedColor.b / 255.0f, _displayedOpacity / 255.0f}; auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP);
getShaderProgram()->setUniformLocationWith4fv(_uniformColor, colors, 1);
_quadCommand.init(0,
_vertexZ,
_textureAtlas->getTexture()->getName(),
shader,
_blendFunc,
_textureAtlas->getQuads(),
_textureAtlas->getTotalQuads(),
_modelViewTransform);
Director::getInstance()->getRenderer()->addCommand(&_quadCommand);
_textureAtlas->drawNumberOfQuads(_quadsToDraw, 0);
} }
// AtlasNode - RGBA protocol // AtlasNode - RGBA protocol
@ -155,7 +172,7 @@ const Color3B& AtlasNode::getColor() const
{ {
return _colorUnmodified; return _colorUnmodified;
} }
return NodeRGBA::getColor(); return Node::getColor();
} }
void AtlasNode::setColor(const Color3B& color3) void AtlasNode::setColor(const Color3B& color3)
@ -169,22 +186,22 @@ void AtlasNode::setColor(const Color3B& color3)
tmp.g = tmp.g * _displayedOpacity/255; tmp.g = tmp.g * _displayedOpacity/255;
tmp.b = tmp.b * _displayedOpacity/255; tmp.b = tmp.b * _displayedOpacity/255;
} }
NodeRGBA::setColor(tmp); Node::setColor(tmp);
} }
void AtlasNode::setOpacity(GLubyte opacity) void AtlasNode::setOpacity(GLubyte opacity)
{ {
NodeRGBA::setOpacity(opacity); Node::setOpacity(opacity);
// special opacity for premultiplied textures // special opacity for premultiplied textures
if( _isOpacityModifyRGB ) if( _isOpacityModifyRGB )
this->setColor(_colorUnmodified); this->setColor(_colorUnmodified);
} }
void AtlasNode::setOpacityModifyRGB(bool bValue) void AtlasNode::setOpacityModifyRGB(bool value)
{ {
Color3B oldColor = this->getColor(); Color3B oldColor = this->getColor();
_isOpacityModifyRGB = bValue; _isOpacityModifyRGB = value;
this->setColor(oldColor); this->setColor(oldColor);
} }
@ -198,9 +215,9 @@ void AtlasNode::updateOpacityModifyRGB()
_isOpacityModifyRGB = _textureAtlas->getTexture()->hasPremultipliedAlpha(); _isOpacityModifyRGB = _textureAtlas->getTexture()->hasPremultipliedAlpha();
} }
void AtlasNode::setIgnoreContentScaleFactor(bool bIgnoreContentScaleFactor) void AtlasNode::setIgnoreContentScaleFactor(bool ignoreContentScaleFactor)
{ {
_ignoreContentScaleFactor = bIgnoreContentScaleFactor; _ignoreContentScaleFactor = ignoreContentScaleFactor;
} }
// AtlasNode - CocosNodeTexture protocol // AtlasNode - CocosNodeTexture protocol
@ -245,14 +262,14 @@ TextureAtlas * AtlasNode::getTextureAtlas() const
return _textureAtlas; return _textureAtlas;
} }
int AtlasNode::getQuadsToDraw() const ssize_t AtlasNode::getQuadsToDraw() const
{ {
return _quadsToDraw; return _quadsToDraw;
} }
void AtlasNode::setQuadsToDraw(int uQuadsToDraw) void AtlasNode::setQuadsToDraw(ssize_t quadsToDraw)
{ {
_quadsToDraw = uQuadsToDraw; _quadsToDraw = quadsToDraw;
} }
NS_CC_END NS_CC_END

View File

@ -30,6 +30,7 @@ THE SOFTWARE.
#include "CCNode.h" #include "CCNode.h"
#include "CCProtocols.h" #include "CCProtocols.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "renderer/CCQuadCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -48,7 +49,7 @@ If you are going to render a TextureAtlas consider subclassing AtlasNode (or a s
All features from Node are valid, plus the following features: All features from Node are valid, plus the following features:
- opacity and RGB colors - opacity and RGB colors
*/ */
class CC_DLL AtlasNode : public NodeRGBA, public TextureProtocol class CC_DLL AtlasNode : public Node, public TextureProtocol
{ {
public: public:
/** creates a AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/ /** creates a AtlasNode with an Atlas file the width and height of each item and the quantity of items to render*/
@ -62,8 +63,8 @@ public:
void setTextureAtlas(TextureAtlas* textureAtlas); void setTextureAtlas(TextureAtlas* textureAtlas);
TextureAtlas* getTextureAtlas() const; TextureAtlas* getTextureAtlas() const;
void setQuadsToDraw(int quadsToDraw); void setQuadsToDraw(ssize_t quadsToDraw);
int getQuadsToDraw() const; ssize_t getQuadsToDraw() const;
// Overrides // Overrides
@ -125,11 +126,13 @@ protected:
BlendFunc _blendFunc; BlendFunc _blendFunc;
// quads to draw // quads to draw
int _quadsToDraw; ssize_t _quadsToDraw;
// color uniform // color uniform
GLint _uniformColor; GLint _uniformColor;
// This varible is only used for LabelAtlas FPS display. So plz don't modify its value. // This varible is only used for LabelAtlas FPS display. So plz don't modify its value.
bool _ignoreContentScaleFactor; bool _ignoreContentScaleFactor;
// quad command
QuadCommand _quadCommand;
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(AtlasNode); CC_DISALLOW_COPY_AND_ASSIGN(AtlasNode);

View File

@ -1,144 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
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 "CCCamera.h"
#include "CCString.h"
#include "CCGL.h"
#include "CCDrawingPrimitives.h"
#include "CCDirector.h"
#include "kazmath/GL/matrix.h"
using namespace std;
NS_CC_BEGIN
Camera::Camera(void)
{
init();
}
Camera::~Camera(void)
{
}
std::string Camera::getDescription() const
{
return String::createWithFormat("<Camera | center = (%.2f,%.2f,%.2f)>", _centerX, _centerY, _centerZ)->getCString();
}
void Camera::init(void)
{
restore();
}
void Camera::restore(void)
{
_eyeX = _eyeY = 0.0f;
_eyeZ = getZEye();
_centerX = _centerY = _centerZ = 0.0f;
_upX = 0.0f;
_upY = 1.0f;
_upZ = 0.0f;
kmMat4Identity(&_lookupMatrix);
_dirty = false;
}
void Camera::locate(void)
{
if (_dirty)
{
kmVec3 eye, center, up;
kmVec3Fill(&eye, _eyeX, _eyeY , _eyeZ);
kmVec3Fill(&center, _centerX, _centerY, _centerZ);
kmVec3Fill(&up, _upX, _upY, _upZ);
kmMat4LookAt(&_lookupMatrix, &eye, &center, &up);
_dirty = false;
}
kmGLMultMatrix(&_lookupMatrix);
}
float Camera::getZEye(void)
{
return FLT_EPSILON;
}
void Camera::setEye(float eyeX, float eyeY, float eyeZ)
{
_eyeX = eyeX;
_eyeY = eyeY;
_eyeZ = eyeZ;
_dirty = true;
}
void Camera::setCenter(float centerX, float centerY, float centerZ)
{
_centerX = centerX;
_centerY = centerY;
_centerZ = centerZ;
_dirty = true;
}
void Camera::setUp(float upX, float upY, float upZ)
{
_upX = upX;
_upY = upY;
_upZ = upZ;
_dirty = true;
}
void Camera::getEye(float *eyeX, float *eyeY, float *eyeZ) const
{
*eyeX = _eyeX;
*eyeY = _eyeY;
*eyeZ = _eyeZ;
}
void Camera::getCenter(float *centerX, float *centerY, float *centerZ) const
{
*centerX = _centerX;
*centerY = _centerY;
*centerZ = _centerZ;
}
void Camera::getUp(float *upX, float *upY, float *upZ) const
{
*upX = _upX;
*upY = _upY;
*upZ = _upZ;
}
NS_CC_END

View File

@ -1,186 +0,0 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc.
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_CAMERA_H__
#define __COCOS2DX_CAMERA_H__
#include <string>
#include "CCObject.h"
#include "ccMacros.h"
#include "kazmath/mat4.h"
NS_CC_BEGIN
/**
* @addtogroup base_nodes
* @{
*/
/**
A Camera is used in every Node.
Useful to look at the object from different views.
The OpenGL gluLookAt() function is used to locate the
camera.
If the object is transformed by any of the scale, rotation or
position attributes, then they will override the camera.
IMPORTANT: Either your use the camera or the rotation/scale/position properties. You can't use both.
World coordinates won't work if you use the camera.
Limitations:
- Some nodes, like ParallaxNode, Particle uses world node coordinates, and they won't work properly if you move them (or any of their ancestors)
using the camera.
- It doesn't work on batched nodes like Sprite objects when they are parented to a SpriteBatchNode object.
- It is recommended to use it ONLY if you are going to create 3D effects. For 2D effects, use the action Follow or position/scale/rotate.
*/
class CC_DLL Camera : public Object
{
public:
/** returns the Z eye */
static float getZEye();
/**
* @js ctor
*/
Camera();
/**
* @js NA
* @lua NA
*/
~Camera();
void init();
/**
* @js NA
* @lua NA
*/
virtual std::string getDescription() const;
/** sets the dirty value */
inline void setDirty(bool value) { _dirty = value; }
/** get the dirty value */
inline bool isDirty() const { return _dirty; }
/** sets the camera in the default position */
void restore();
/** Sets the camera using gluLookAt using its eye, center and up_vector */
void locate();
/** sets the eye values in points */
void setEye(float eyeX, float eyeY, float eyeZ);
/**
@deprecated. Use setEye() instead
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE void setEyeXYZ(float eyeX, float eyeY, float eyeZ){ setEye(eyeX, eyeY, eyeZ);}
/** sets the center values in points */
void setCenter(float centerX, float centerY, float centerZ);
/**
@deprecated. Use setCenter() instead
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE void setCenterXYZ(float centerX, float centerY, float centerZ){ setCenter(centerX,centerY,centerZ);}
/** sets the up values */
void setUp(float upX, float upY, float upZ);
/**
@deprecated. Use setUp() instead
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE void setUpXYZ(float upX, float upY, float upZ){ setUp(upX,upY,upZ); }
/** get the eye vector values in points
* @code
* when this function bound to js or lua,the input params are changed
* in js: var getEye()
* in lua:local getEye()
* @endcode
*/
void getEye(float *eyeX, float *eyeY, float *eyeZ) const;
/**
@deprecated. Use getEye() instead
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE void getEyeXYZ(float *eyeX, float *eyeY, float *eyeZ) const { getEye(eyeX, eyeY, eyeZ); }
/** get the center vector values int points
* when this function bound to js or lua,the input params are changed
* in js: var getCenter()
* in lua:local getCenter()
*/
void getCenter(float *centerX, float *centerY, float *centerZ) const;
/**
@deprecated. Use getCenter() instead
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE void getCenterXYZ(float *centerX, float *centerY, float *centerZ) const{ getCenter(centerX,centerY,centerZ); }
/** get the up vector values
* when this function bound to js or lua,the input params are changed
* in js: var getUp()
* in lua:local getUp()
*/
void getUp(float *upX, float *upY, float *upZ) const;
/**
@deprecated. Use getUp() instead
* @js NA
* @lua NA
*/
CC_DEPRECATED_ATTRIBUTE void getUpXYZ(float *upX, float *upY, float *upZ) const{ getUp(upX, upY, upZ); }
protected:
float _eyeX;
float _eyeY;
float _eyeZ;
float _centerX;
float _centerY;
float _centerZ;
float _upX;
float _upY;
float _upZ;
bool _dirty;
kmMat4 _lookupMatrix;
private:
DISALLOW_COPY_AND_ASSIGN(Camera);
};
// end of base_node group
/// @}
NS_CC_END
#endif // __COCOS2DX_CAMERA_H__

View File

@ -31,25 +31,47 @@
#include "CCShaderCache.h" #include "CCShaderCache.h"
#include "CCDirector.h" #include "CCDirector.h"
#include "CCDrawingPrimitives.h" #include "CCDrawingPrimitives.h"
#include "CCRenderer.h"
#include "CCGroupCommand.h"
#include "CCCustomCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
static GLint g_sStencilBits = -1; static GLint g_sStencilBits = -1;
// store the current stencil layer (position in the stencil buffer),
// this will allow nesting up to n ClippingNode,
// where n is the number of bits of the stencil buffer.
static GLint s_layer = -1;
static void setProgram(Node *n, GLProgram *p) static void setProgram(Node *n, GLProgram *p)
{ {
n->setShaderProgram(p); n->setShaderProgram(p);
n->getChildren().forEach([p](Node* child){ auto& children = n->getChildren();
for(const auto &child : children) {
setProgram(child, p); setProgram(child, p);
}); }
} }
ClippingNode::ClippingNode() ClippingNode::ClippingNode()
: _stencil(NULL) : _stencil(nullptr)
, _alphaThreshold(0.0f) , _alphaThreshold(0.0f)
, _inverted(false) , _inverted(false)
{} , _currentStencilEnabled(GL_FALSE)
, _currentStencilWriteMask(~0)
, _currentStencilFunc(GL_ALWAYS)
, _currentStencilRef(0)
, _currentStencilValueMask(~0)
, _currentStencilFail(GL_KEEP)
, _currentStencilPassDepthFail(GL_KEEP)
, _currentStencilPassDepthPass(GL_KEEP)
, _currentDepthWriteMask(GL_TRUE)
, _currentAlphaTestEnabled(GL_FALSE)
, _currentAlphaTestFunc(GL_ALWAYS)
, _currentAlphaTestRef(1)
{
}
ClippingNode::~ClippingNode() ClippingNode::~ClippingNode()
{ {
@ -58,37 +80,37 @@ ClippingNode::~ClippingNode()
ClippingNode* ClippingNode::create() ClippingNode* ClippingNode::create()
{ {
ClippingNode *pRet = new ClippingNode(); ClippingNode *ret = new ClippingNode();
if (pRet && pRet->init()) if (ret && ret->init())
{ {
pRet->autorelease(); ret->autorelease();
} }
else else
{ {
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
} }
return pRet; return ret;
} }
ClippingNode* ClippingNode::create(Node *pStencil) ClippingNode* ClippingNode::create(Node *pStencil)
{ {
ClippingNode *pRet = new ClippingNode(); ClippingNode *ret = new ClippingNode();
if (pRet && pRet->init(pStencil)) if (ret && ret->init(pStencil))
{ {
pRet->autorelease(); ret->autorelease();
} }
else else
{ {
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
} }
return pRet; return ret;
} }
bool ClippingNode::init() bool ClippingNode::init()
{ {
return init(NULL); return init(nullptr);
} }
bool ClippingNode::init(Node *stencil) bool ClippingNode::init(Node *stencil)
@ -178,96 +200,136 @@ void ClippingNode::drawFullScreenQuadClearStencil()
void ClippingNode::visit() void ClippingNode::visit()
{ {
// if stencil buffer disabled if(!_visible)
if (g_sStencilBits < 1)
{
// draw everything, as if there where no stencil
Node::visit();
return; return;
}
// return fast (draw nothing, or draw everything if in inverted mode) if: kmGLPushMatrix();
// - nil stencil node transform();
// - or stencil node invisible: //Add group command
if (!_stencil || !_stencil->isVisible())
Renderer* renderer = Director::getInstance()->getRenderer();
_groupCommand.init(0,_vertexZ);
renderer->addCommand(&_groupCommand);
renderer->pushGroup(_groupCommand.getRenderQueueID());
_beforeVisitCmd.init(0,_vertexZ);
_beforeVisitCmd.func = CC_CALLBACK_0(ClippingNode::onBeforeVisit, this);
renderer->addCommand(&_beforeVisitCmd);
_stencil->visit();
_afterDrawStencilCmd.init(0,_vertexZ);
_afterDrawStencilCmd.func = CC_CALLBACK_0(ClippingNode::onAfterDrawStencil, this);
renderer->addCommand(&_afterDrawStencilCmd);
int i = 0;
if(!_children.empty())
{ {
if (_inverted) sortAllChildren();
// draw children zOrder < 0
for( ; i < _children.size(); i++ )
{ {
// draw everything auto node = _children.at(i);
Node::visit();
}
return;
}
// store the current stencil layer (position in the stencil buffer),
// this will allow nesting up to n ClippingNode,
// where n is the number of bits of the stencil buffer.
static GLint layer = -1;
// all the _stencilBits are in use?
if (layer + 1 == g_sStencilBits)
{
// warn once
static bool once = true;
if (once)
{
char warning[200] = {0};
snprintf(warning, sizeof(warning), "Nesting more than %d stencils is not supported. Everything will be drawn without stencil for this node and its childs.", g_sStencilBits);
CCLOG("%s", warning);
once = false; if ( node && node->getZOrder() < 0 )
node->visit();
else
break;
} }
// draw everything, as if there where no stencil // self draw
Node::visit(); this->draw();
return;
for(auto it=_children.cbegin()+i; it != _children.cend(); ++it)
(*it)->visit();
} }
else
{
this->draw();
}
_afterVisitCmd.init(0,_vertexZ);
_afterVisitCmd.func = CC_CALLBACK_0(ClippingNode::onAfterVisit, this);
renderer->addCommand(&_afterVisitCmd);
renderer->popGroup();
kmGLPopMatrix();
}
Node* ClippingNode::getStencil() const
{
return _stencil;
}
void ClippingNode::setStencil(Node *stencil)
{
CC_SAFE_RELEASE(_stencil);
_stencil = stencil;
CC_SAFE_RETAIN(_stencil);
}
GLfloat ClippingNode::getAlphaThreshold() const
{
return _alphaThreshold;
}
void ClippingNode::setAlphaThreshold(GLfloat alphaThreshold)
{
_alphaThreshold = alphaThreshold;
}
bool ClippingNode::isInverted() const
{
return _inverted;
}
void ClippingNode::setInverted(bool inverted)
{
_inverted = inverted;
}
void ClippingNode::onBeforeVisit()
{
/////////////////////////////////// ///////////////////////////////////
// INIT // INIT
// increment the current layer // increment the current layer
layer++; s_layer++;
// mask of the current layer (ie: for layer 3: 00000100) // mask of the current layer (ie: for layer 3: 00000100)
GLint mask_layer = 0x1 << layer; GLint mask_layer = 0x1 << s_layer;
// mask of all layers less than the current (ie: for layer 3: 00000011) // mask of all layers less than the current (ie: for layer 3: 00000011)
GLint mask_layer_l = mask_layer - 1; GLint mask_layer_l = mask_layer - 1;
// mask of all layers less than or equal to the current (ie: for layer 3: 00000111) // mask of all layers less than or equal to the current (ie: for layer 3: 00000111)
GLint mask_layer_le = mask_layer | mask_layer_l; _mask_layer_le = mask_layer | mask_layer_l;
// manually save the stencil state // manually save the stencil state
GLboolean currentStencilEnabled = GL_FALSE;
GLuint currentStencilWriteMask = ~0; _currentStencilEnabled = glIsEnabled(GL_STENCIL_TEST);
GLenum currentStencilFunc = GL_ALWAYS; glGetIntegerv(GL_STENCIL_WRITEMASK, (GLint *)&_currentStencilWriteMask);
GLint currentStencilRef = 0; glGetIntegerv(GL_STENCIL_FUNC, (GLint *)&_currentStencilFunc);
GLuint currentStencilValueMask = ~0; glGetIntegerv(GL_STENCIL_REF, &_currentStencilRef);
GLenum currentStencilFail = GL_KEEP; glGetIntegerv(GL_STENCIL_VALUE_MASK, (GLint *)&_currentStencilValueMask);
GLenum currentStencilPassDepthFail = GL_KEEP; glGetIntegerv(GL_STENCIL_FAIL, (GLint *)&_currentStencilFail);
GLenum currentStencilPassDepthPass = GL_KEEP; glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, (GLint *)&_currentStencilPassDepthFail);
currentStencilEnabled = glIsEnabled(GL_STENCIL_TEST); glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, (GLint *)&_currentStencilPassDepthPass);
glGetIntegerv(GL_STENCIL_WRITEMASK, (GLint *)&currentStencilWriteMask);
glGetIntegerv(GL_STENCIL_FUNC, (GLint *)&currentStencilFunc);
glGetIntegerv(GL_STENCIL_REF, &currentStencilRef);
glGetIntegerv(GL_STENCIL_VALUE_MASK, (GLint *)&currentStencilValueMask);
glGetIntegerv(GL_STENCIL_FAIL, (GLint *)&currentStencilFail);
glGetIntegerv(GL_STENCIL_PASS_DEPTH_FAIL, (GLint *)&currentStencilPassDepthFail);
glGetIntegerv(GL_STENCIL_PASS_DEPTH_PASS, (GLint *)&currentStencilPassDepthPass);
// enable stencil use // enable stencil use
glEnable(GL_STENCIL_TEST); glEnable(GL_STENCIL_TEST);
// check for OpenGL error while enabling stencil test // check for OpenGL error while enabling stencil test
CHECK_GL_ERROR_DEBUG(); CHECK_GL_ERROR_DEBUG();
// all bits on the stencil buffer are readonly, except the current layer bit, // all bits on the stencil buffer are readonly, except the current layer bit,
// this means that operation like glClear or glStencilOp will be masked with this value // this means that operation like glClear or glStencilOp will be masked with this value
glStencilMask(mask_layer); glStencilMask(mask_layer);
// manually save the depth test state // manually save the depth test state
//GLboolean currentDepthTestEnabled = GL_TRUE;
GLboolean currentDepthWriteMask = GL_TRUE; glGetBooleanv(GL_DEPTH_WRITEMASK, &_currentDepthWriteMask);
//currentDepthTestEnabled = glIsEnabled(GL_DEPTH_TEST);
glGetBooleanv(GL_DEPTH_WRITEMASK, &currentDepthWriteMask);
// disable depth test while drawing the stencil // disable depth test while drawing the stencil
//glDisable(GL_DEPTH_TEST); //glDisable(GL_DEPTH_TEST);
// disable update to the depth buffer while drawing the stencil, // disable update to the depth buffer while drawing the stencil,
@ -275,10 +337,10 @@ void ClippingNode::visit()
// it should never prevent something else to be drawn, // it should never prevent something else to be drawn,
// only disabling depth buffer update should do // only disabling depth buffer update should do
glDepthMask(GL_FALSE); glDepthMask(GL_FALSE);
/////////////////////////////////// ///////////////////////////////////
// CLEAR STENCIL BUFFER // CLEAR STENCIL BUFFER
// manually clear the stencil buffer by drawing a fullscreen rectangle on it // manually clear the stencil buffer by drawing a fullscreen rectangle on it
// setup the stencil test func like this: // setup the stencil test func like this:
// for each pixel in the fullscreen rectangle // for each pixel in the fullscreen rectangle
@ -287,14 +349,14 @@ void ClippingNode::visit()
// if in inverted mode: set the current layer value to 1 in the stencil buffer // if in inverted mode: set the current layer value to 1 in the stencil buffer
glStencilFunc(GL_NEVER, mask_layer, mask_layer); glStencilFunc(GL_NEVER, mask_layer, mask_layer);
glStencilOp(!_inverted ? GL_ZERO : GL_REPLACE, GL_KEEP, GL_KEEP); glStencilOp(!_inverted ? GL_ZERO : GL_REPLACE, GL_KEEP, GL_KEEP);
// draw a fullscreen solid rectangle to clear the stencil buffer // draw a fullscreen solid rectangle to clear the stencil buffer
//ccDrawSolidRect(Point::ZERO, ccpFromSize([[Director sharedDirector] winSize]), Color4F(1, 1, 1, 1)); //ccDrawSolidRect(Point::ZERO, ccpFromSize([[Director sharedDirector] winSize]), Color4F(1, 1, 1, 1));
drawFullScreenQuadClearStencil(); drawFullScreenQuadClearStencil();
/////////////////////////////////// ///////////////////////////////////
// DRAW CLIPPING STENCIL // DRAW CLIPPING STENCIL
// setup the stencil test func like this: // setup the stencil test func like this:
// for each pixel in the stencil node // for each pixel in the stencil node
// never draw it into the frame buffer // never draw it into the frame buffer
@ -302,20 +364,15 @@ void ClippingNode::visit()
// if in inverted mode: set the current layer value to 0 in the stencil buffer // if in inverted mode: set the current layer value to 0 in the stencil buffer
glStencilFunc(GL_NEVER, mask_layer, mask_layer); glStencilFunc(GL_NEVER, mask_layer, mask_layer);
glStencilOp(!_inverted ? GL_REPLACE : GL_ZERO, GL_KEEP, GL_KEEP); glStencilOp(!_inverted ? GL_REPLACE : GL_ZERO, GL_KEEP, GL_KEEP);
// enable alpha test only if the alpha threshold < 1, // enable alpha test only if the alpha threshold < 1,
// indeed if alpha threshold == 1, every pixel will be drawn anyways // indeed if alpha threshold == 1, every pixel will be drawn anyways
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WINDOWS || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
GLboolean currentAlphaTestEnabled = GL_FALSE;
GLenum currentAlphaTestFunc = GL_ALWAYS;
GLclampf currentAlphaTestRef = 1;
#endif
if (_alphaThreshold < 1) { if (_alphaThreshold < 1) {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WINDOWS || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WINDOWS || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
// manually save the alpha test state // manually save the alpha test state
currentAlphaTestEnabled = glIsEnabled(GL_ALPHA_TEST); _currentAlphaTestEnabled = glIsEnabled(GL_ALPHA_TEST);
glGetIntegerv(GL_ALPHA_TEST_FUNC, (GLint *)&currentAlphaTestFunc); glGetIntegerv(GL_ALPHA_TEST_FUNC, (GLint *)&_currentAlphaTestFunc);
glGetFloatv(GL_ALPHA_TEST_REF, &currentAlphaTestRef); glGetFloatv(GL_ALPHA_TEST_REF, &_currentAlphaTestRef);
// enable alpha testing // enable alpha testing
glEnable(GL_ALPHA_TEST); glEnable(GL_ALPHA_TEST);
// check for OpenGL error while enabling alpha test // check for OpenGL error while enabling alpha test
@ -333,27 +390,22 @@ void ClippingNode::visit()
// we need to recursively apply this shader to all the nodes in the stencil node // we need to recursively apply this shader to all the nodes in the stencil node
// XXX: we should have a way to apply shader to all nodes without having to do this // XXX: we should have a way to apply shader to all nodes without having to do this
setProgram(_stencil, program); setProgram(_stencil, program);
#endif #endif
} }
// draw the stencil node as if it was one of our child //Draw _stencil
// (according to the stencil test func/op and alpha (or alpha shader) test) }
kmGLPushMatrix();
transform(); void ClippingNode::onAfterDrawStencil()
if (_stencil != nullptr) {
{
_stencil->visit();
}
kmGLPopMatrix();
// restore alpha test state // restore alpha test state
if (_alphaThreshold < 1) if (_alphaThreshold < 1)
{ {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WINDOWS || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) #if (CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WINDOWS || CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
// manually restore the alpha test state // manually restore the alpha test state
glAlphaFunc(currentAlphaTestFunc, currentAlphaTestRef); glAlphaFunc(_currentAlphaTestFunc, _currentAlphaTestRef);
if (!currentAlphaTestEnabled) if (!_currentAlphaTestEnabled)
{ {
glDisable(GL_ALPHA_TEST); glDisable(GL_ALPHA_TEST);
} }
@ -361,74 +413,45 @@ void ClippingNode::visit()
// XXX: we need to find a way to restore the shaders of the stencil node and its childs // XXX: we need to find a way to restore the shaders of the stencil node and its childs
#endif #endif
} }
// restore the depth test state // restore the depth test state
glDepthMask(currentDepthWriteMask); glDepthMask(_currentDepthWriteMask);
//if (currentDepthTestEnabled) { //if (currentDepthTestEnabled) {
// glEnable(GL_DEPTH_TEST); // glEnable(GL_DEPTH_TEST);
//} //}
/////////////////////////////////// ///////////////////////////////////
// DRAW CONTENT // DRAW CONTENT
// setup the stencil test func like this: // setup the stencil test func like this:
// for each pixel of this node and its childs // for each pixel of this node and its childs
// if all layers less than or equals to the current are set to 1 in the stencil buffer // if all layers less than or equals to the current are set to 1 in the stencil buffer
// draw the pixel and keep the current layer in the stencil buffer // draw the pixel and keep the current layer in the stencil buffer
// else // else
// do not draw the pixel but keep the current layer in the stencil buffer // do not draw the pixel but keep the current layer in the stencil buffer
glStencilFunc(GL_EQUAL, mask_layer_le, mask_layer_le); glStencilFunc(GL_EQUAL, _mask_layer_le, _mask_layer_le);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
// draw (according to the stencil test func) this node and its childs // draw (according to the stencil test func) this node and its childs
Node::visit(); }
void ClippingNode::onAfterVisit()
{
/////////////////////////////////// ///////////////////////////////////
// CLEANUP // CLEANUP
// manually restore the stencil state // manually restore the stencil state
glStencilFunc(currentStencilFunc, currentStencilRef, currentStencilValueMask); glStencilFunc(_currentStencilFunc, _currentStencilRef, _currentStencilValueMask);
glStencilOp(currentStencilFail, currentStencilPassDepthFail, currentStencilPassDepthPass); glStencilOp(_currentStencilFail, _currentStencilPassDepthFail, _currentStencilPassDepthPass);
glStencilMask(currentStencilWriteMask); glStencilMask(_currentStencilWriteMask);
if (!currentStencilEnabled) if (!_currentStencilEnabled)
{ {
glDisable(GL_STENCIL_TEST); glDisable(GL_STENCIL_TEST);
} }
// we are done using this layer, decrement // we are done using this layer, decrement
layer--; s_layer--;
}
Node* ClippingNode::getStencil() const
{
return _stencil;
}
void ClippingNode::setStencil(Node *pStencil)
{
CC_SAFE_RELEASE(_stencil);
_stencil = pStencil;
CC_SAFE_RETAIN(_stencil);
}
GLfloat ClippingNode::getAlphaThreshold() const
{
return _alphaThreshold;
}
void ClippingNode::setAlphaThreshold(GLfloat fAlphaThreshold)
{
_alphaThreshold = fAlphaThreshold;
}
bool ClippingNode::isInverted() const
{
return _inverted;
}
void ClippingNode::setInverted(bool bInverted)
{
_inverted = bInverted;
} }
NS_CC_END NS_CC_END

View File

@ -30,6 +30,8 @@
#include "CCNode.h" #include "CCNode.h"
#include "CCGL.h" #include "CCGL.h"
#include "renderer/CCGroupCommand.h"
#include "renderer/CCCustomCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -48,14 +50,14 @@ public:
/** Creates and initializes a clipping node with an other node as its stencil. /** Creates and initializes a clipping node with an other node as its stencil.
The stencil node will be retained. The stencil node will be retained.
*/ */
static ClippingNode* create(Node *pStencil); static ClippingNode* create(Node *stencil);
/** The Node to use as a stencil to do the clipping. /** The Node to use as a stencil to do the clipping.
The stencil node will be retained. The stencil node will be retained.
This default to nil. This default to nil.
*/ */
Node* getStencil() const; Node* getStencil() const;
void setStencil(Node *pStencil); void setStencil(Node *stencil);
/** The alpha threshold. /** The alpha threshold.
The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold. The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold.
@ -63,14 +65,14 @@ public:
This default to 1 (so alpha test is disabled). This default to 1 (so alpha test is disabled).
*/ */
GLfloat getAlphaThreshold() const; GLfloat getAlphaThreshold() const;
void setAlphaThreshold(GLfloat fAlphaThreshold); void setAlphaThreshold(GLfloat alphaThreshold);
/** Inverted. If this is set to true, /** Inverted. If this is set to true,
the stencil is inverted, so the content is drawn where the stencil is NOT drawn. the stencil is inverted, so the content is drawn where the stencil is NOT drawn.
This default to false. This default to false.
*/ */
bool isInverted() const; bool isInverted() const;
void setInverted(bool bInverted); void setInverted(bool inverted);
// Overrides // Overrides
/** /**
@ -111,7 +113,7 @@ protected:
/** Initializes a clipping node with an other node as its stencil. /** Initializes a clipping node with an other node as its stencil.
The stencil node will be retained, and its parent will be set to this clipping node. The stencil node will be retained, and its parent will be set to this clipping node.
*/ */
virtual bool init(Node *pStencil); virtual bool init(Node *stencil);
/**draw fullscreen quad to clear stencil bits /**draw fullscreen quad to clear stencil bits
*/ */
@ -120,6 +122,32 @@ protected:
Node* _stencil; Node* _stencil;
GLfloat _alphaThreshold; GLfloat _alphaThreshold;
bool _inverted; bool _inverted;
protected:
//renderData and callback
void onBeforeVisit();
void onAfterDrawStencil();
void onAfterVisit();
GLboolean _currentStencilEnabled;
GLuint _currentStencilWriteMask;
GLenum _currentStencilFunc;
GLint _currentStencilRef;
GLuint _currentStencilValueMask;
GLenum _currentStencilFail;
GLenum _currentStencilPassDepthFail;
GLenum _currentStencilPassDepthPass;
GLboolean _currentDepthWriteMask;
GLboolean _currentAlphaTestEnabled;
GLenum _currentAlphaTestFunc;
GLclampf _currentAlphaTestRef;
GLint _mask_layer_le;
GroupCommand _groupCommand;
CustomCommand _beforeVisitCmd;
CustomCommand _afterDrawStencilCmd;
CustomCommand _afterVisitCmd;
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(ClippingNode); CC_DISALLOW_COPY_AND_ASSIGN(ClippingNode);

View File

@ -28,7 +28,7 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
Component::Component(void) Component::Component(void)
: _owner(NULL) : _owner(nullptr)
, _enabled(true) , _enabled(true)
{ {
} }
@ -60,26 +60,26 @@ void Component::serialize(void *ar)
Component* Component::create(void) Component* Component::create(void)
{ {
Component * pRet = new Component(); Component * ret = new Component();
if (pRet != NULL && pRet->init()) if (ret != nullptr && ret->init())
{ {
pRet->autorelease(); ret->autorelease();
} }
else else
{ {
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
} }
return pRet; return ret;
} }
const char* Component::getName() const const std::string& Component::getName() const
{ {
return _name.c_str(); return _name;
} }
void Component::setName(const char *pName) void Component::setName(const std::string& name)
{ {
_name.assign(pName); _name = name;
} }
Node* Component::getOwner() const Node* Component::getOwner() const
@ -87,9 +87,9 @@ Node* Component::getOwner() const
return _owner; return _owner;
} }
void Component::setOwner(Node *pOwner) void Component::setOwner(Node *owner)
{ {
_owner = pOwner; _owner = owner;
} }
bool Component::isEnabled() const bool Component::isEnabled() const

View File

@ -60,8 +60,8 @@ public:
virtual void setEnabled(bool b); virtual void setEnabled(bool b);
static Component* create(void); static Component* create(void);
const char* getName() const; const std::string& getName() const;
void setName(const char *pName); void setName(const std::string& name);
void setOwner(Node *pOwner); void setOwner(Node *pOwner);
Node* getOwner() const; Node* getOwner() const;

View File

@ -29,9 +29,9 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
ComponentContainer::ComponentContainer(Node *pNode) ComponentContainer::ComponentContainer(Node *node)
: _components(nullptr) : _components(nullptr)
, _owner(pNode) , _owner(node)
{ {
} }
@ -40,24 +40,22 @@ ComponentContainer::~ComponentContainer(void)
CC_SAFE_DELETE(_components); CC_SAFE_DELETE(_components);
} }
Component* ComponentContainer::get(const char *pName) const Component* ComponentContainer::get(const std::string& name) const
{ {
Component* pRet = NULL; Component* ret = nullptr;
CCASSERT(pName != NULL, "Argument must be non-nil");
do { do {
CC_BREAK_IF(NULL == pName); CC_BREAK_IF(nullptr == _components);
CC_BREAK_IF(NULL == _components); ret = _components->at(name);
pRet = _components->at(pName);
} while (0); } while (0);
return pRet; return ret;
} }
bool ComponentContainer::add(Component *pCom) bool ComponentContainer::add(Component *com)
{ {
bool bRet = false; bool ret = false;
CCASSERT(pCom != NULL, "Argument must be non-nil"); CCASSERT(com != nullptr, "Argument must be non-nil");
CCASSERT(pCom->getOwner() == NULL, "Component already added. It can't be added again"); CCASSERT(com->getOwner() == nullptr, "Component already added. It can't be added again");
do do
{ {
if (_components == nullptr) if (_components == nullptr)
@ -65,38 +63,37 @@ bool ComponentContainer::add(Component *pCom)
_components = new Map<std::string, Component*>(); _components = new Map<std::string, Component*>();
_owner->scheduleUpdate(); _owner->scheduleUpdate();
} }
Component *pComponent = _components->at(pCom->getName()); Component *component = _components->at(com->getName());
CCASSERT(pComponent == NULL, "Component already added. It can't be added again"); CCASSERT(component == nullptr, "Component already added. It can't be added again");
CC_BREAK_IF(pComponent); CC_BREAK_IF(component);
pCom->setOwner(_owner); com->setOwner(_owner);
_components->insert(pCom->getName(), pCom); _components->insert(com->getName(), com);
pCom->onEnter(); com->onEnter();
bRet = true; ret = true;
} while(0); } while(0);
return bRet; return ret;
} }
bool ComponentContainer::remove(const char *pName) bool ComponentContainer::remove(const std::string& name)
{ {
bool bRet = false; bool ret = false;
CCASSERT(pName != NULL, "Argument must be non-nil");
do do
{ {
CC_BREAK_IF(!_components); CC_BREAK_IF(!_components);
auto iter = _components->find(pName); auto iter = _components->find(name);
CC_BREAK_IF(iter == _components->end()); CC_BREAK_IF(iter == _components->end());
auto com = iter->second; auto com = iter->second;
com->onExit(); com->onExit();
com->setOwner(NULL); com->setOwner(nullptr);
_components->erase(iter); _components->erase(iter);
bRet = true; ret = true;
} while(0); } while(0);
return bRet; return ret;
} }
void ComponentContainer::removeAll() void ComponentContainer::removeAll()
@ -106,7 +103,7 @@ void ComponentContainer::removeAll()
for (auto iter = _components->begin(); iter != _components->end(); ++iter) for (auto iter = _components->begin(); iter != _components->end(); ++iter)
{ {
iter->second->onExit(); iter->second->onExit();
iter->second->setOwner(NULL); iter->second->setOwner(nullptr);
} }
_components->clear(); _components->clear();
@ -121,13 +118,13 @@ void ComponentContainer::alloc(void)
_components = new Map<std::string, Component*>(); _components = new Map<std::string, Component*>();
} }
void ComponentContainer::visit(float fDelta) void ComponentContainer::visit(float delta)
{ {
if (_components != nullptr) if (_components != nullptr)
{ {
for (auto iter = _components->begin(); iter != _components->end(); ++iter) for (auto iter = _components->begin(); iter != _components->end(); ++iter)
{ {
iter->second->update(fDelta); iter->second->update(delta);
} }
} }
} }

View File

@ -26,6 +26,7 @@ THE SOFTWARE.
#define __CC_FRAMEWORK_COMCONTAINER_H__ #define __CC_FRAMEWORK_COMCONTAINER_H__
#include "CCMap.h" #include "CCMap.h"
#include <string>
NS_CC_BEGIN NS_CC_BEGIN
@ -46,11 +47,11 @@ public:
* @lua NA * @lua NA
*/ */
virtual ~ComponentContainer(void); virtual ~ComponentContainer(void);
virtual Component* get(const char *pName) const; virtual Component* get(const std::string& name) const;
virtual bool add(Component *pCom); virtual bool add(Component *com);
virtual bool remove(const char *pName); virtual bool remove(const std::string& name);
virtual void removeAll(); virtual void removeAll();
virtual void visit(float fDelta); virtual void visit(float delta);
public: public:
bool isEmpty() const; bool isEmpty() const;

View File

@ -284,7 +284,7 @@ void Configuration::setValue(const std::string& key, const Value& value)
// //
// load file // load file
// //
void Configuration::loadConfigFile(const char *filename) void Configuration::loadConfigFile(const std::string& filename)
{ {
ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(filename); ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(filename);
CCASSERT(!dict.empty(), "cannot create dictionary"); CCASSERT(!dict.empty(), "cannot create dictionary");
@ -312,14 +312,14 @@ void Configuration::loadConfigFile(const char *filename)
if (! validMetadata) if (! validMetadata)
{ {
CCLOG("Invalid config format for file: %s", filename); CCLOG("Invalid config format for file: %s", filename.c_str());
return; return;
} }
auto dataIter = dict.find("data"); auto dataIter = dict.find("data");
if (dataIter == dict.end() || dataIter->second.getType() != Value::Type::MAP) if (dataIter == dict.end() || dataIter->second.getType() != Value::Type::MAP)
{ {
CCLOG("Expected 'data' dict, but not found. Config file: %s", filename); CCLOG("Expected 'data' dict, but not found. Config file: %s", filename.c_str());
return; return;
} }

View File

@ -128,7 +128,7 @@ public:
void gatherGPUInfo(); void gatherGPUInfo();
/** Loads a config file. If the keys are already present, then they are going to be replaced. Otherwise the new keys are added. */ /** Loads a config file. If the keys are already present, then they are going to be replaced. Otherwise the new keys are added. */
void loadConfigFile(const char *filename); void loadConfigFile(const std::string& filename);
private: private:
Configuration(void); Configuration(void);

View File

@ -560,8 +560,8 @@ CC_DEPRECATED_ATTRIBUTE typedef GLProgram CCGLProgram;
CC_DEPRECATED_ATTRIBUTE typedef Touch CCTouch; CC_DEPRECATED_ATTRIBUTE typedef Touch CCTouch;
CC_DEPRECATED_ATTRIBUTE typedef Texture2D CCTexture2D; CC_DEPRECATED_ATTRIBUTE typedef Texture2D CCTexture2D;
CC_DEPRECATED_ATTRIBUTE typedef Node CCNode; CC_DEPRECATED_ATTRIBUTE typedef Node CCNode;
CC_DEPRECATED_ATTRIBUTE typedef NodeRGBA CCNodeRGBA; CC_DEPRECATED_ATTRIBUTE typedef Node CCNodeRGBA;
CC_DEPRECATED_ATTRIBUTE typedef RGBAProtocol CCRGBAProtocol; CC_DEPRECATED_ATTRIBUTE typedef Node CCRGBAProtocol;
CC_DEPRECATED_ATTRIBUTE typedef SpriteFrame CCSpriteFrame; CC_DEPRECATED_ATTRIBUTE typedef SpriteFrame CCSpriteFrame;
CC_DEPRECATED_ATTRIBUTE typedef AnimationFrame CCAnimationFrame; CC_DEPRECATED_ATTRIBUTE typedef AnimationFrame CCAnimationFrame;
CC_DEPRECATED_ATTRIBUTE typedef Animation CCAnimation; CC_DEPRECATED_ATTRIBUTE typedef Animation CCAnimation;
@ -678,7 +678,7 @@ CC_DEPRECATED_ATTRIBUTE typedef SpriteBatchNode CCSpriteBatchNode;
CC_DEPRECATED_ATTRIBUTE typedef LabelBMFont CCLabelBMFont; CC_DEPRECATED_ATTRIBUTE typedef LabelBMFont CCLabelBMFont;
CC_DEPRECATED_ATTRIBUTE typedef Layer CCLayer; CC_DEPRECATED_ATTRIBUTE typedef Layer CCLayer;
//CC_DEPRECATED_ATTRIBUTE typedef KeypadDelegate CCKeypadDelegate; //CC_DEPRECATED_ATTRIBUTE typedef KeypadDelegate CCKeypadDelegate;
CC_DEPRECATED_ATTRIBUTE typedef LayerRGBA CCLayerRGBA; CC_DEPRECATED_ATTRIBUTE typedef Layer CCLayerRGBA;
CC_DEPRECATED_ATTRIBUTE typedef LayerColor CCLayerColor; CC_DEPRECATED_ATTRIBUTE typedef LayerColor CCLayerColor;
CC_DEPRECATED_ATTRIBUTE typedef LayerGradient CCLayerGradient; CC_DEPRECATED_ATTRIBUTE typedef LayerGradient CCLayerGradient;
CC_DEPRECATED_ATTRIBUTE typedef LayerMultiplex CCLayerMultiplex; CC_DEPRECATED_ATTRIBUTE typedef LayerMultiplex CCLayerMultiplex;
@ -1038,7 +1038,11 @@ CC_DEPRECATED_ATTRIBUTE typedef __Integer CCInteger;
CC_DEPRECATED_ATTRIBUTE typedef __Bool Bool; CC_DEPRECATED_ATTRIBUTE typedef __Bool Bool;
CC_DEPRECATED_ATTRIBUTE typedef __Bool CCBool; CC_DEPRECATED_ATTRIBUTE typedef __Bool CCBool;
CC_DEPRECATED_ATTRIBUTE typedef __String CCString; CC_DEPRECATED_ATTRIBUTE typedef __String CCString;
//CC_DEPRECATED_ATTRIBUTE typedef __String String; CC_DEPRECATED_ATTRIBUTE typedef __String String;
CC_DEPRECATED_ATTRIBUTE typedef __RGBAProtocol RGBAProtocol;
CC_DEPRECATED_ATTRIBUTE typedef __NodeRGBA NodeRGBA;
CC_DEPRECATED_ATTRIBUTE typedef __LayerRGBA LayerRGBA;
NS_CC_END NS_CC_END

View File

@ -1,5 +1,5 @@
/**************************************************************************** /****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) 2008-2010 Ricardo Quesada Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011 Zynga Inc. Copyright (c) 2011 Zynga Inc.
@ -45,11 +45,9 @@ THE SOFTWARE.
#include "platform/CCFileUtils.h" #include "platform/CCFileUtils.h"
#include "CCApplication.h" #include "CCApplication.h"
#include "CCLabelBMFont.h" #include "CCLabelBMFont.h"
#include "CCLabelAtlas.h"
#include "CCActionManager.h" #include "CCActionManager.h"
#include "CCAnimationCache.h" #include "CCAnimationCache.h"
#include "CCTouch.h" #include "CCTouch.h"
#include "CCEventDispatcher.h"
#include "CCUserDefault.h" #include "CCUserDefault.h"
#include "ccGLStateCache.h" #include "ccGLStateCache.h"
#include "CCShaderCache.h" #include "CCShaderCache.h"
@ -60,8 +58,10 @@ THE SOFTWARE.
#include "CCEGLView.h" #include "CCEGLView.h"
#include "CCConfiguration.h" #include "CCConfiguration.h"
#include "CCEventDispatcher.h" #include "CCEventDispatcher.h"
#include "CCEventCustom.h"
#include "CCFontFreeType.h" #include "CCFontFreeType.h"
#include "CCRenderer.h"
#include "renderer/CCFrustum.h"
/** /**
Position of the FPS Position of the FPS
@ -84,6 +84,11 @@ static DisplayLinkDirector *s_SharedDirector = nullptr;
#define kDefaultFPS 60 // 60 frames per second #define kDefaultFPS 60 // 60 frames per second
extern const char* cocos2dVersion(void); extern const char* cocos2dVersion(void);
const char *Director::EVENT_PROJECTION_CHANGED = "director_projection_changed";
const char *Director::EVENT_AFTER_DRAW = "director_after_draw";
const char *Director::EVENT_AFTER_VISIT = "director_after_visit";
const char *Director::EVENT_AFTER_UPDATE = "director_after_udpate";
Director* Director::getInstance() Director* Director::getInstance()
{ {
if (!s_SharedDirector) if (!s_SharedDirector)
@ -95,9 +100,8 @@ Director* Director::getInstance()
return s_SharedDirector; return s_SharedDirector;
} }
Director::Director(void) Director::Director()
{ {
} }
bool Director::init(void) bool Director::init(void)
@ -134,7 +138,9 @@ bool Director::init(void)
_winSizeInPoints = Size::ZERO; _winSizeInPoints = Size::ZERO;
_openGLView = nullptr; _openGLView = nullptr;
_cullingFrustum = new Frustum();
_contentScaleFactor = 1.0f; _contentScaleFactor = 1.0f;
// scheduler // scheduler
@ -144,9 +150,22 @@ bool Director::init(void)
_scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false); _scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false);
_eventDispatcher = new EventDispatcher(); _eventDispatcher = new EventDispatcher();
_eventAfterDraw = new EventCustom(EVENT_AFTER_DRAW);
_eventAfterDraw->setUserData(this);
_eventAfterVisit = new EventCustom(EVENT_AFTER_VISIT);
_eventAfterVisit->setUserData(this);
_eventAfterUpdate = new EventCustom(EVENT_AFTER_UPDATE);
_eventAfterUpdate->setUserData(this);
_eventProjectionChanged = new EventCustom(EVENT_PROJECTION_CHANGED);
_eventProjectionChanged->setUserData(this);
//init TextureCache //init TextureCache
initTextureCache(); initTextureCache();
// Renderer
_renderer = new Renderer;
// create autorelease pool // create autorelease pool
PoolManager::sharedPoolManager()->push(); PoolManager::sharedPoolManager()->push();
@ -166,7 +185,14 @@ Director::~Director(void)
CC_SAFE_RELEASE(_scheduler); CC_SAFE_RELEASE(_scheduler);
CC_SAFE_RELEASE(_actionManager); CC_SAFE_RELEASE(_actionManager);
CC_SAFE_RELEASE(_eventDispatcher); CC_SAFE_RELEASE(_eventDispatcher);
delete _eventAfterUpdate;
delete _eventAfterDraw;
delete _eventAfterVisit;
delete _eventProjectionChanged;
delete _renderer;
// pop the autorelease pool // pop the autorelease pool
PoolManager::sharedPoolManager()->pop(); PoolManager::sharedPoolManager()->pop();
PoolManager::purgePoolManager(); PoolManager::purgePoolManager();
@ -245,6 +271,7 @@ void Director::drawScene()
if (! _paused) if (! _paused)
{ {
_scheduler->update(_deltaTime); _scheduler->update(_deltaTime);
_eventDispatcher->dispatchEvent(_eventAfterUpdate);
} }
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
@ -257,11 +284,22 @@ void Director::drawScene()
} }
kmGLPushMatrix(); kmGLPushMatrix();
//construct the frustum
{
kmMat4 view;
kmMat4 projection;
kmGLGetMatrix(KM_GL_PROJECTION, &projection);
kmGLGetMatrix(KM_GL_MODELVIEW, &view);
_cullingFrustum->setupFromMatrix(view, projection);
}
// draw the scene // draw the scene
if (_runningScene) if (_runningScene)
{ {
_runningScene->visit(); _runningScene->visit();
_eventDispatcher->dispatchEvent(_eventAfterVisit);
} }
// draw the notifications node // draw the notifications node
@ -275,6 +313,9 @@ void Director::drawScene()
showStats(); showStats();
} }
_renderer->render();
_eventDispatcher->dispatchEvent(_eventAfterDraw);
kmGLPopMatrix(); kmGLPopMatrix();
_totalFrames++; _totalFrames++;
@ -353,6 +394,8 @@ void Director::setOpenGLView(EGLView *openGLView)
setGLDefaultValues(); setGLDefaultValues();
} }
_renderer->initGLView();
CHECK_GL_ERROR_DEBUG(); CHECK_GL_ERROR_DEBUG();
// _touchDispatcher->setDispatchEvents(true); // _touchDispatcher->setDispatchEvents(true);
@ -452,6 +495,8 @@ void Director::setProjection(Projection projection)
_projection = projection; _projection = projection;
GL::setProjectionMatrixDirty(); GL::setProjectionMatrixDirty();
_eventDispatcher->dispatchEvent(_eventProjectionChanged);
} }
void Director::purgeCachedData(void) void Director::purgeCachedData(void)
@ -706,6 +751,7 @@ void Director::purgeDirector()
CC_SAFE_RELEASE_NULL(_FPSLabel); CC_SAFE_RELEASE_NULL(_FPSLabel);
CC_SAFE_RELEASE_NULL(_SPFLabel); CC_SAFE_RELEASE_NULL(_SPFLabel);
CC_SAFE_RELEASE_NULL(_drawsLabel); CC_SAFE_RELEASE_NULL(_drawsLabel);
CC_SAFE_DELETE(_cullingFrustum);
// purge bitmap cache // purge bitmap cache
LabelBMFont::purgeCachedData(); LabelBMFont::purgeCachedData();
@ -801,13 +847,10 @@ void Director::resume()
setAnimationInterval(_oldAnimationInterval); setAnimationInterval(_oldAnimationInterval);
if (gettimeofday(_lastUpdate, nullptr) != 0)
{
CCLOG("cocos2d: Director: Error in gettimeofday");
}
_paused = false; _paused = false;
_deltaTime = 0; _deltaTime = 0;
// fix issue #3509, skip one fps to avoid incorrect time calculation.
setNextDeltaTimeZero(true);
} }
// display the FPS using a LabelAtlas // display the FPS using a LabelAtlas
@ -906,17 +949,17 @@ void Director::createStatsLabel()
*/ */
float factor = EGLView::getInstance()->getDesignResolutionSize().height / 320.0f; float factor = EGLView::getInstance()->getDesignResolutionSize().height / 320.0f;
_FPSLabel = new LabelAtlas(); _FPSLabel = new LabelAtlas;
_FPSLabel->setIgnoreContentScaleFactor(true); _FPSLabel->setIgnoreContentScaleFactor(true);
_FPSLabel->initWithString("00.0", texture, 12, 32 , '.'); _FPSLabel->initWithString("00.0", texture, 12, 32 , '.');
_FPSLabel->setScale(factor); _FPSLabel->setScale(factor);
_SPFLabel = new LabelAtlas(); _SPFLabel = new LabelAtlas;
_SPFLabel->setIgnoreContentScaleFactor(true); _SPFLabel->setIgnoreContentScaleFactor(true);
_SPFLabel->initWithString("0.000", texture, 12, 32, '.'); _SPFLabel->initWithString("0.000", texture, 12, 32, '.');
_SPFLabel->setScale(factor); _SPFLabel->setScale(factor);
_drawsLabel = new LabelAtlas(); _drawsLabel = new LabelAtlas;
_drawsLabel->setIgnoreContentScaleFactor(true); _drawsLabel->setIgnoreContentScaleFactor(true);
_drawsLabel->initWithString("000", texture, 12, 32, '.'); _drawsLabel->initWithString("000", texture, 12, 32, '.');
_drawsLabel->setScale(factor); _drawsLabel->setScale(factor);
@ -1009,6 +1052,12 @@ void Director::setEventDispatcher(EventDispatcher* dispatcher)
} }
} }
Renderer* Director::getRenderer() const
{
return _renderer;
}
/*************************************************** /***************************************************
* implementation of DisplayLinkDirector * implementation of DisplayLinkDirector
**************************************************/ **************************************************/
@ -1024,6 +1073,8 @@ void DisplayLinkDirector::startAnimation()
} }
_invalid = false; _invalid = false;
Application::getInstance()->setAnimationInterval(_animationInterval);
} }
void DisplayLinkDirector::mainLoop() void DisplayLinkDirector::mainLoop()

View File

@ -54,7 +54,11 @@ class Node;
class Scheduler; class Scheduler;
class ActionManager; class ActionManager;
class EventDispatcher; class EventDispatcher;
class EventCustom;
class EventListenerCustom;
class TextureCache; class TextureCache;
class Frustum;
class Renderer;
/** /**
@brief Class that creates and handles the main Window and manages how @brief Class that creates and handles the main Window and manages how
@ -79,6 +83,12 @@ and when to execute the Scenes.
class CC_DLL Director : public Object class CC_DLL Director : public Object
{ {
public: public:
static const char *EVENT_PROJECTION_CHANGED;
static const char* EVENT_AFTER_UPDATE;
static const char* EVENT_AFTER_VISIT;
static const char* EVENT_AFTER_DRAW;
/** @typedef ccDirectorProjection /** @typedef ccDirectorProjection
Possible OpenGL projections used by director Possible OpenGL projections used by director
*/ */
@ -330,8 +340,13 @@ public:
*/ */
void setContentScaleFactor(float scaleFactor); void setContentScaleFactor(float scaleFactor);
float getContentScaleFactor() const; float getContentScaleFactor() const;
/**
Get the Culling Frustum
*/
Frustum* getFrustum() const { return _cullingFrustum; }
public:
/** Gets the Scheduler associated with this director /** Gets the Scheduler associated with this director
@since v2.0 @since v2.0
*/ */
@ -361,7 +376,12 @@ public:
@since v3.0 @since v3.0
*/ */
void setEventDispatcher(EventDispatcher* dispatcher); void setEventDispatcher(EventDispatcher* dispatcher);
/** Returns the Renderer
@since v3.0
*/
Renderer* getRenderer() const;
/* Gets delta time since last tick to main loop */ /* Gets delta time since last tick to main loop */
float getDeltaTime() const; float getDeltaTime() const;
@ -388,27 +408,27 @@ protected:
void initTextureCache(); void initTextureCache();
void destroyTextureCache(); void destroyTextureCache();
protected:
/** Scheduler associated with this director /** Scheduler associated with this director
@since v2.0 @since v2.0
*/ */
Scheduler* _scheduler; Scheduler *_scheduler;
/** ActionManager associated with this director /** ActionManager associated with this director
@since v2.0 @since v2.0
*/ */
ActionManager* _actionManager; ActionManager *_actionManager;
/** EventDispatcher associated with this director /** EventDispatcher associated with this director
@since v3.0 @since v3.0
*/ */
EventDispatcher* _eventDispatcher; EventDispatcher* _eventDispatcher;
EventCustom *_eventProjectionChanged, *_eventAfterDraw, *_eventAfterVisit, *_eventAfterUpdate;
/* delta time since last tick to main loop */ /* delta time since last tick to main loop */
float _deltaTime; float _deltaTime;
/* The EGLView, where everything is rendered */ /* The EGLView, where everything is rendered */
EGLView *_openGLView; EGLView *_openGLView;
//texture cache belongs to this director //texture cache belongs to this director
TextureCache *_textureCache; TextureCache *_textureCache;
@ -434,6 +454,8 @@ protected:
unsigned int _totalFrames; unsigned int _totalFrames;
unsigned int _frames; unsigned int _frames;
float _secondsPerFrame; float _secondsPerFrame;
Frustum *_cullingFrustum;
/* The running scene */ /* The running scene */
Scene *_runningScene; Scene *_runningScene;
@ -443,7 +465,7 @@ protected:
Scene *_nextScene; Scene *_nextScene;
/* If true, then "old" scene will receive the cleanup message */ /* If true, then "old" scene will receive the cleanup message */
bool _sendCleanupToScene; bool _sendCleanupToScene;
/* scheduled scenes */ /* scheduled scenes */
Vector<Scene*> _scenesStack; Vector<Scene*> _scenesStack;
@ -458,10 +480,10 @@ protected:
Projection _projection; Projection _projection;
/* window size in points */ /* window size in points */
Size _winSizeInPoints; Size _winSizeInPoints;
/* content scale factor */ /* content scale factor */
float _contentScaleFactor; float _contentScaleFactor;
/* store the fps string */ /* store the fps string */
char *_FPS; char *_FPS;
@ -471,6 +493,8 @@ protected:
/* Projection protocol delegate */ /* Projection protocol delegate */
DirectorDelegate *_projectionDelegate; DirectorDelegate *_projectionDelegate;
Renderer *_renderer;
// EGLViewProtocol will recreate stats labels to fit visible rect // EGLViewProtocol will recreate stats labels to fit visible rect
friend class EGLViewProtocol; friend class EGLViewProtocol;

View File

@ -26,6 +26,9 @@
#include "CCNotificationCenter.h" #include "CCNotificationCenter.h"
#include "CCEventType.h" #include "CCEventType.h"
#include "CCConfiguration.h" #include "CCConfiguration.h"
#include "CCCustomCommand.h"
#include "CCDirector.h"
#include "CCRenderer.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -101,7 +104,7 @@ DrawNode::DrawNode()
, _vbo(0) , _vbo(0)
, _bufferCapacity(0) , _bufferCapacity(0)
, _bufferCount(0) , _bufferCount(0)
, _buffer(NULL) , _buffer(nullptr)
, _dirty(false) , _dirty(false)
{ {
_blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
@ -110,7 +113,7 @@ DrawNode::DrawNode()
DrawNode::~DrawNode() DrawNode::~DrawNode()
{ {
free(_buffer); free(_buffer);
_buffer = NULL; _buffer = nullptr;
glDeleteBuffers(1, &_vbo); glDeleteBuffers(1, &_vbo);
_vbo = 0; _vbo = 0;
@ -129,17 +132,17 @@ DrawNode::~DrawNode()
DrawNode* DrawNode::create() DrawNode* DrawNode::create()
{ {
DrawNode* pRet = new DrawNode(); DrawNode* ret = new DrawNode();
if (pRet && pRet->init()) if (ret && ret->init())
{ {
pRet->autorelease(); ret->autorelease();
} }
else else
{ {
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
} }
return pRet; return ret;
} }
void DrawNode::ensureCapacity(int count) void DrawNode::ensureCapacity(int count)
@ -196,7 +199,7 @@ bool DrawNode::init()
NotificationCenter::getInstance()->addObserver(this, NotificationCenter::getInstance()->addObserver(this,
callfuncO_selector(DrawNode::listenBackToForeground), callfuncO_selector(DrawNode::listenBackToForeground),
EVNET_COME_TO_FOREGROUND, EVNET_COME_TO_FOREGROUND,
NULL); nullptr);
#endif #endif
return true; return true;
@ -237,10 +240,17 @@ void DrawNode::render()
} }
void DrawNode::draw() void DrawNode::draw()
{
_customCommand.init(0, _vertexZ);
_customCommand.func = CC_CALLBACK_0(DrawNode::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(&_customCommand);
}
void DrawNode::onDraw()
{ {
CC_NODE_DRAW_SETUP(); CC_NODE_DRAW_SETUP();
GL::blendFunc(_blendFunc.src, _blendFunc.dst); GL::blendFunc(_blendFunc.src, _blendFunc.dst);
render(); render();
} }

View File

@ -32,6 +32,7 @@
#include "CCNode.h" #include "CCNode.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "renderer/CCCustomCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -84,6 +85,8 @@ public:
*/ */
void listenBackToForeground(Object *obj); void listenBackToForeground(Object *obj);
void onDraw();
// Overrides // Overrides
virtual void draw() override; virtual void draw() override;
@ -103,6 +106,7 @@ protected:
V2F_C4B_T2F *_buffer; V2F_C4B_T2F *_buffer;
BlendFunc _blendFunc; BlendFunc _blendFunc;
CustomCommand _customCommand;
bool _dirty; bool _dirty;

View File

@ -55,7 +55,7 @@ NS_CC_BEGIN
namespace DrawPrimitives { namespace DrawPrimitives {
static bool s_initialized = false; static bool s_initialized = false;
static GLProgram* s_shader = NULL; static GLProgram* s_shader = nullptr;
static int s_colorLocation = -1; static int s_colorLocation = -1;
static Color4F s_color(1.0f,1.0f,1.0f,1.0f); static Color4F s_color(1.0f,1.0f,1.0f,1.0f);
static int s_pointSizeLocation = -1; static int s_pointSizeLocation = -1;
@ -475,7 +475,7 @@ void drawCardinalSpline( PointArray *config, float tension, unsigned int segmen
Vertex2F* vertices = new Vertex2F[segments + 1]; Vertex2F* vertices = new Vertex2F[segments + 1];
unsigned int p; ssize_t p;
float lt; float lt;
float deltaT = 1.0f / config->count(); float deltaT = 1.0f / config->count();

View File

@ -29,6 +29,7 @@
#include <string> #include <string>
#include <stdint.h> #include <stdint.h>
#include "CCObject.h"
#include "CCPlatformMacros.h" #include "CCPlatformMacros.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -38,7 +39,7 @@ class Node;
/** /**
* Base class of all kinds of events. * Base class of all kinds of events.
*/ */
class Event class Event : public Object
{ {
public: public:
enum class Type enum class Type

View File

@ -26,6 +26,11 @@
#include "CCEventTouch.h" #include "CCEventTouch.h"
#include "CCEventCustom.h" #include "CCEventCustom.h"
#include "CCEventListenerTouch.h" #include "CCEventListenerTouch.h"
#include "CCEventListenerAcceleration.h"
#include "CCEventListenerMouse.h"
#include "CCEventListenerKeyboard.h"
#include "CCEventListenerCustom.h"
#include "CCNode.h" #include "CCNode.h"
#include "CCDirector.h" #include "CCDirector.h"
@ -59,31 +64,30 @@ private:
NS_CC_BEGIN NS_CC_BEGIN
static EventListener::ListenerID getListenerID(Event* event) static EventListener::ListenerID __getListenerID(Event* event)
{ {
EventListener::ListenerID ret; EventListener::ListenerID ret;
switch (event->getType()) switch (event->getType())
{ {
case Event::Type::ACCELERATION: case Event::Type::ACCELERATION:
ret = static_cast<EventListener::ListenerID>(EventListener::Type::ACCELERATION); ret = EventListenerAcceleration::LISTENER_ID;
break; break;
case Event::Type::CUSTOM: case Event::Type::CUSTOM:
{ {
auto customEvent = static_cast<EventCustom*>(event); auto customEvent = static_cast<EventCustom*>(event);
auto listenerID = std::hash<std::string>()(customEvent->getEventName()); ret = customEvent->getEventName();
ret = static_cast<EventListener::ListenerID>(listenerID);
} }
break; break;
case Event::Type::KEYBOARD: case Event::Type::KEYBOARD:
ret = static_cast<EventListener::ListenerID>(EventListener::Type::KEYBOARD); ret = EventListenerKeyboard::LISTENER_ID;
break; break;
case Event::Type::MOUSE: case Event::Type::MOUSE:
ret = static_cast<EventListener::ListenerID>(EventListener::Type::MOUSE); ret = EventListenerMouse::LISTENER_ID;
break; break;
case Event::Type::TOUCH: case Event::Type::TOUCH:
// Touch listener is very special, it contains two kinds of listeners, EventListenerTouchOneByOne and EventListenerTouchAllAtOnce. // Touch listener is very special, it contains two kinds of listeners, EventListenerTouchOneByOne and EventListenerTouchAllAtOnce.
// return UNKNOW instead. // return UNKNOWN instead.
ret = static_cast<EventListener::ListenerID>(EventListener::Type::UNKNOWN); CCASSERT(false, "Don't call this method if the event is for touch.");
break; break;
default: default:
CCASSERT(false, "Invalid type!"); CCASSERT(false, "Invalid type!");
@ -93,10 +97,10 @@ static EventListener::ListenerID getListenerID(Event* event)
return ret; return ret;
} }
EventDispatcher::EventListenerVector::EventListenerVector() EventDispatcher::EventListenerVector::EventListenerVector() :
: _sceneGraphListeners(nullptr) _fixedListeners(nullptr),
, _fixedListeners(nullptr) _sceneGraphListeners(nullptr),
, _gt0Index(0) _gt0Index(0)
{ {
} }
@ -335,6 +339,8 @@ void EventDispatcher::addEventListener(EventListener* listener)
{ {
_toAddedListeners.push_back(listener); _toAddedListeners.push_back(listener);
} }
listener->retain();
} }
void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* listener, Node* node) void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* listener, Node* node)
@ -349,7 +355,6 @@ void EventDispatcher::addEventListenerWithSceneGraphPriority(EventListener* list
listener->setFixedPriority(0); listener->setFixedPriority(0);
listener->setRegistered(true); listener->setRegistered(true);
listener->retain();
addEventListener(listener); addEventListener(listener);
associateNodeAndEventListener(node, listener); associateNodeAndEventListener(node, listener);
@ -373,12 +378,17 @@ void EventDispatcher::addEventListenerWithFixedPriority(EventListener* listener,
listener->setFixedPriority(fixedPriority); listener->setFixedPriority(fixedPriority);
listener->setRegistered(true); listener->setRegistered(true);
listener->setPaused(false); listener->setPaused(false);
listener->retain();
addEventListener(listener); addEventListener(listener);
} }
EventListenerCustom* EventDispatcher::addCustomEventListener(const std::string &eventName, std::function<void(EventCustom*)> callback)
{
EventListenerCustom *listener = EventListenerCustom::create(eventName, callback);
addEventListenerWithFixedPriority(listener, 1);
return listener;
}
void EventDispatcher::removeEventListener(EventListener* listener) void EventDispatcher::removeEventListener(EventListener* listener)
{ {
if (listener == nullptr) if (listener == nullptr)
@ -491,11 +501,12 @@ void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, s
auto fixedPriorityListeners = listeners->getFixedPriorityListeners(); auto fixedPriorityListeners = listeners->getFixedPriorityListeners();
auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners(); auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners();
int i = 0; ssize_t i = 0;
// priority < 0 // priority < 0
if (fixedPriorityListeners) if (fixedPriorityListeners)
{ {
for (; !fixedPriorityListeners->empty() && i < listeners->getGt0Index(); ++i) bool isEmpty = fixedPriorityListeners->empty();
for (; !isEmpty && i < listeners->getGt0Index(); ++i)
{ {
auto l = fixedPriorityListeners->at(i); auto l = fixedPriorityListeners->at(i);
if (!l->isPaused() && l->isRegistered() && onEvent(l)) if (!l->isPaused() && l->isRegistered() && onEvent(l))
@ -527,7 +538,8 @@ void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, s
if (!shouldStopPropagation) if (!shouldStopPropagation)
{ {
// priority > 0 // priority > 0
for (; i < fixedPriorityListeners->size(); ++i) ssize_t size = fixedPriorityListeners->size();
for (; i < size; ++i)
{ {
auto l = fixedPriorityListeners->at(i); auto l = fixedPriorityListeners->at(i);
@ -557,7 +569,7 @@ void EventDispatcher::dispatchEvent(Event* event)
return; return;
} }
auto listenerID = getListenerID(event); auto listenerID = __getListenerID(event);
sortEventListeners(listenerID); sortEventListeners(listenerID);
@ -578,16 +590,21 @@ void EventDispatcher::dispatchEvent(Event* event)
updateListeners(event); updateListeners(event);
} }
void EventDispatcher::dispatchCustomEvent(const std::string &eventName, void *optionalUserData)
{
EventCustom ev(eventName);
ev.setUserData(optionalUserData);
dispatchEvent(&ev);
}
void EventDispatcher::dispatchTouchEvent(EventTouch* event) void EventDispatcher::dispatchTouchEvent(EventTouch* event)
{ {
auto touchOneByOneID = static_cast<EventListener::ListenerID>(EventListener::Type::TOUCH_ONE_BY_ONE); sortEventListeners(EventListenerTouchOneByOne::LISTENER_ID);
auto touchAllAtOnceID = static_cast<EventListener::ListenerID>(EventListener::Type::TOUCH_ALL_AT_ONCE); sortEventListeners(EventListenerTouchAllAtOnce::LISTENER_ID);
sortEventListeners(touchOneByOneID); auto oneByOnelisteners = getListeners(EventListenerTouchOneByOne::LISTENER_ID);
sortEventListeners(touchAllAtOnceID); auto allAtOncelisteners = getListeners(EventListenerTouchAllAtOnce::LISTENER_ID);
auto oneByOnelisteners = getListeners(touchOneByOneID);
auto allAtOncelisteners = getListeners(touchAllAtOnceID);
// If there aren't any touch listeners, return directly. // If there aren't any touch listeners, return directly.
if (nullptr == oneByOnelisteners && nullptr == allAtOncelisteners) if (nullptr == oneByOnelisteners && nullptr == allAtOncelisteners)
@ -776,7 +793,7 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event)
void EventDispatcher::updateListeners(Event* event) void EventDispatcher::updateListeners(Event* event)
{ {
auto onUpdateListeners = [this](EventListener::ListenerID listenerID) auto onUpdateListeners = [this](const EventListener::ListenerID& listenerID)
{ {
auto listenersIter = _listeners.find(listenerID); auto listenersIter = _listeners.find(listenerID);
if (listenersIter == _listeners.end()) if (listenersIter == _listeners.end())
@ -844,12 +861,12 @@ void EventDispatcher::updateListeners(Event* event)
if (event->getType() == Event::Type::TOUCH) if (event->getType() == Event::Type::TOUCH)
{ {
onUpdateListeners(static_cast<EventListener::ListenerID>(EventListener::Type::TOUCH_ONE_BY_ONE)); onUpdateListeners(EventListenerTouchOneByOne::LISTENER_ID);
onUpdateListeners(static_cast<EventListener::ListenerID>(EventListener::Type::TOUCH_ALL_AT_ONCE)); onUpdateListeners(EventListenerTouchAllAtOnce::LISTENER_ID);
} }
else else
{ {
onUpdateListeners(getListenerID(event)); onUpdateListeners(__getListenerID(event));
} }
@ -907,7 +924,7 @@ void EventDispatcher::updateDirtyFlagForSceneGraph()
} }
} }
void EventDispatcher::sortEventListeners(EventListener::ListenerID listenerID) void EventDispatcher::sortEventListeners(const EventListener::ListenerID& listenerID)
{ {
DirtyFlag dirtyFlag = DirtyFlag::NONE; DirtyFlag dirtyFlag = DirtyFlag::NONE;
@ -933,7 +950,7 @@ void EventDispatcher::sortEventListeners(EventListener::ListenerID listenerID)
} }
} }
void EventDispatcher::sortEventListenersOfSceneGraphPriority(EventListener::ListenerID listenerID) void EventDispatcher::sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID)
{ {
auto listeners = getListeners(listenerID); auto listeners = getListeners(listenerID);
@ -962,7 +979,7 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(EventListener::List
#endif #endif
} }
void EventDispatcher::sortEventListenersOfFixedPriority(EventListener::ListenerID listenerID) void EventDispatcher::sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID)
{ {
auto listeners = getListeners(listenerID); auto listeners = getListeners(listenerID);
@ -996,7 +1013,7 @@ void EventDispatcher::sortEventListenersOfFixedPriority(EventListener::ListenerI
} }
EventDispatcher::EventListenerVector* EventDispatcher::getListeners(EventListener::ListenerID listenerID) EventDispatcher::EventListenerVector* EventDispatcher::getListeners(const EventListener::ListenerID& listenerID)
{ {
auto iter = _listeners.find(listenerID); auto iter = _listeners.find(listenerID);
if (iter != _listeners.end()) if (iter != _listeners.end())
@ -1007,7 +1024,7 @@ EventDispatcher::EventListenerVector* EventDispatcher::getListeners(EventListene
return nullptr; return nullptr;
} }
void EventDispatcher::removeEventListenersForListenerID(EventListener::ListenerID listenerID) void EventDispatcher::removeEventListenersForListenerID(const EventListener::ListenerID& listenerID)
{ {
auto listenerItemIter = _listeners.find(listenerID); auto listenerItemIter = _listeners.find(listenerID);
if (listenerItemIter != _listeners.end()) if (listenerItemIter != _listeners.end())
@ -1068,26 +1085,47 @@ void EventDispatcher::removeEventListenersForListenerID(EventListener::ListenerI
void EventDispatcher::removeEventListeners(EventListener::Type listenerType) void EventDispatcher::removeEventListeners(EventListener::Type listenerType)
{ {
CCASSERT(listenerType != EventListener::Type::CUSTOM, "Not support custom event listener type, please use EventDispatcher::removeCustomEventListeners instead."); if (listenerType == EventListener::Type::TOUCH_ONE_BY_ONE)
{
removeEventListenersForListenerID(static_cast<EventListener::ListenerID>(listenerType)); removeEventListenersForListenerID(EventListenerTouchOneByOne::LISTENER_ID);
}
else if (listenerType == EventListener::Type::TOUCH_ALL_AT_ONCE)
{
removeEventListenersForListenerID(EventListenerTouchAllAtOnce::LISTENER_ID);
}
else if (listenerType == EventListener::Type::MOUSE)
{
removeEventListenersForListenerID(EventListenerMouse::LISTENER_ID);
}
else if (listenerType == EventListener::Type::ACCELERATION)
{
removeEventListenersForListenerID(EventListenerAcceleration::LISTENER_ID);
}
else if (listenerType == EventListener::Type::KEYBOARD)
{
removeEventListenersForListenerID(EventListenerKeyboard::LISTENER_ID);
}
else
{
CCASSERT(false, "Invalid listener type!");
}
} }
void EventDispatcher::removeCustomEventListeners(const std::string& customEventName) void EventDispatcher::removeCustomEventListeners(const std::string& customEventName)
{ {
removeEventListenersForListenerID(std::hash<std::string>()(customEventName)); removeEventListenersForListenerID(customEventName);
} }
void EventDispatcher::removeAllEventListeners() void EventDispatcher::removeAllEventListeners()
{ {
std::vector<EventListener::ListenerID> types(_listeners.size()); std::vector<EventListener::ListenerID> types(_listeners.size());
for (auto iter = _listeners.begin(); iter != _listeners.end(); ++iter) for (const auto& e : _listeners)
{ {
types.push_back(iter->first); types.push_back(e.first);
} }
for (auto& type : types) for (const auto& type : types)
{ {
removeEventListenersForListenerID(type); removeEventListenersForListenerID(type);
} }
@ -1118,7 +1156,7 @@ void EventDispatcher::setDirtyForNode(Node* node)
} }
} }
void EventDispatcher::setDirty(EventListener::ListenerID listenerID, DirtyFlag flag) void EventDispatcher::setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag)
{ {
auto iter = _priorityDirtyFlagMap.find(listenerID); auto iter = _priorityDirtyFlagMap.find(listenerID);
if (iter == _priorityDirtyFlagMap.end()) if (iter == _priorityDirtyFlagMap.end())

View File

@ -40,6 +40,8 @@ NS_CC_BEGIN
class Event; class Event;
class EventTouch; class EventTouch;
class Node; class Node;
class EventCustom;
class EventListenerCustom;
/** /**
This class manages event listener subscriptions This class manages event listener subscriptions
@ -69,17 +71,23 @@ public:
*/ */
void addEventListenerWithFixedPriority(EventListener* listener, int fixedPriority); void addEventListenerWithFixedPriority(EventListener* listener, int fixedPriority);
/** Remove a listener /** Adds a Custom event listener.
It will use a fixed priority of 1.
@return the generated event. Needed in order to remove the event from the dispather
*/
EventListenerCustom* addCustomEventListener(const std::string &eventName, std::function<void(EventCustom*)> callback);
/** Remove a listener
* @param listener The specified event listener which needs to be removed. * @param listener The specified event listener which needs to be removed.
*/ */
void removeEventListener(EventListener* listener); void removeEventListener(EventListener* listener);
/** Removes all listeners with the same event listener type */ /** Removes all listeners with the same event listener type */
void removeEventListeners(EventListener::Type listenerType); void removeEventListeners(EventListener::Type listenerType);
/** Removes all custom listeners with the same event name */ /** Removes all custom listeners with the same event name */
void removeCustomEventListeners(const std::string& customEventName); void removeCustomEventListeners(const std::string& customEventName);
/** Removes all listeners */ /** Removes all listeners */
void removeAllEventListeners(); void removeAllEventListeners();
@ -97,13 +105,16 @@ public:
* event dispatcher list. * event dispatcher list.
*/ */
void dispatchEvent(Event* event); void dispatchEvent(Event* event);
/** Dispatches a Custom Event with a event name an optional user data */
void dispatchCustomEvent(const std::string &eventName, void *optionalUserData);
/** Constructor of EventDispatcher */ /** Constructor of EventDispatcher */
EventDispatcher(); EventDispatcher();
/** Destructor of EventDispatcher */ /** Destructor of EventDispatcher */
~EventDispatcher(); ~EventDispatcher();
private: protected:
friend class Node; friend class Node;
/** Sets the dirty flag for a node. */ /** Sets the dirty flag for a node. */
@ -148,22 +159,22 @@ private:
void addEventListener(EventListener* listener); void addEventListener(EventListener* listener);
/** Gets event the listener list for the event listener type. */ /** Gets event the listener list for the event listener type. */
EventListenerVector* getListeners(EventListener::ListenerID listenerID); EventListenerVector* getListeners(const EventListener::ListenerID& listenerID);
/** Update dirty flag */ /** Update dirty flag */
void updateDirtyFlagForSceneGraph(); void updateDirtyFlagForSceneGraph();
/** Removes all listeners with the same event listener ID */ /** Removes all listeners with the same event listener ID */
void removeEventListenersForListenerID(EventListener::ListenerID listenerID); void removeEventListenersForListenerID(const EventListener::ListenerID& listenerID);
/** Sort event listener */ /** Sort event listener */
void sortEventListeners(EventListener::ListenerID listenerID); void sortEventListeners(const EventListener::ListenerID& listenerID);
/** Sorts the listeners of specified type by scene graph priority */ /** Sorts the listeners of specified type by scene graph priority */
void sortEventListenersOfSceneGraphPriority(EventListener::ListenerID listenerID); void sortEventListenersOfSceneGraphPriority(const EventListener::ListenerID& listenerID);
/** Sorts the listeners of specified type by fixed priority */ /** Sorts the listeners of specified type by fixed priority */
void sortEventListenersOfFixedPriority(EventListener::ListenerID listenerID); void sortEventListenersOfFixedPriority(const EventListener::ListenerID& listenerID);
/** Updates all listeners /** Updates all listeners
* 1) Removes all listener items that have been marked as 'removed' when dispatching event. * 1) Removes all listener items that have been marked as 'removed' when dispatching event.
@ -193,12 +204,11 @@ private:
}; };
/** Sets the dirty flag for a specified listener ID */ /** Sets the dirty flag for a specified listener ID */
void setDirty(EventListener::ListenerID listenerID, DirtyFlag flag); void setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag);
/** Walks though scene graph to get the draw order for each node, it's called before sorting event listener with scene graph priority */ /** Walks though scene graph to get the draw order for each node, it's called before sorting event listener with scene graph priority */
void visitTarget(Node* node); void visitTarget(Node* node);
private:
/** Listeners map */ /** Listeners map */
std::unordered_map<EventListener::ListenerID, EventListenerVector*> _listeners; std::unordered_map<EventListener::ListenerID, EventListenerVector*> _listeners;

View File

@ -57,7 +57,7 @@ public:
CUSTOM CUSTOM
}; };
typedef std::size_t ListenerID; typedef std::string ListenerID;
protected: protected:
/** Constructor */ /** Constructor */
@ -83,7 +83,7 @@ protected:
inline bool isRegistered() const { return _isRegistered; }; inline bool isRegistered() const { return _isRegistered; };
inline Type getType() const { return _type; }; inline Type getType() const { return _type; };
inline ListenerID getListenerID() const { return _listenerID; }; inline const ListenerID& getListenerID() const { return _listenerID; };
inline void setFixedPriority(int fixedPriority) { _fixedPriority = fixedPriority; }; inline void setFixedPriority(int fixedPriority) { _fixedPriority = fixedPriority; };
inline int getFixedPriority() const { return _fixedPriority; }; inline int getFixedPriority() const { return _fixedPriority; };

View File

@ -27,6 +27,8 @@
NS_CC_BEGIN NS_CC_BEGIN
const std::string EventListenerAcceleration::LISTENER_ID = "__cc_acceleration";
EventListenerAcceleration::EventListenerAcceleration() EventListenerAcceleration::EventListenerAcceleration()
{ {
@ -59,7 +61,7 @@ bool EventListenerAcceleration::init(std::function<void(Acceleration*, Event* ev
this->onAccelerationEvent(&accEvent->_acc, event); this->onAccelerationEvent(&accEvent->_acc, event);
}; };
if (EventListener::init(Type::ACCELERATION, static_cast<ListenerID>(Type::ACCELERATION), listener)) if (EventListener::init(Type::ACCELERATION, LISTENER_ID, listener))
{ {
onAccelerationEvent = callback; onAccelerationEvent = callback;
return true; return true;

View File

@ -33,6 +33,8 @@ NS_CC_BEGIN
class EventListenerAcceleration : public EventListener class EventListenerAcceleration : public EventListener
{ {
public: public:
static const std::string LISTENER_ID;
static EventListenerAcceleration* create(std::function<void(Acceleration*, Event*)> callback); static EventListenerAcceleration* create(std::function<void(Acceleration*, Event*)> callback);
virtual ~EventListenerAcceleration(); virtual ~EventListenerAcceleration();
@ -44,6 +46,8 @@ private:
bool init(std::function<void(Acceleration*, Event* event)> callback); bool init(std::function<void(Acceleration*, Event* event)> callback);
std::function<void(Acceleration*, Event*)> onAccelerationEvent; std::function<void(Acceleration*, Event*)> onAccelerationEvent;
friend class LuaEventListenerAcceleration;
}; };
NS_CC_END NS_CC_END

View File

@ -35,7 +35,7 @@ EventListenerCustom::EventListenerCustom()
EventListenerCustom* EventListenerCustom::create(const std::string& eventName, std::function<void(EventCustom*)> callback) EventListenerCustom* EventListenerCustom::create(const std::string& eventName, std::function<void(EventCustom*)> callback)
{ {
EventListenerCustom* ret = new EventListenerCustom(); EventListenerCustom* ret = new EventListenerCustom();
if (ret && ret->init(std::hash<std::string>()(eventName), callback)) if (ret && ret->init(eventName, callback))
{ {
ret->autorelease(); ret->autorelease();
} }

View File

@ -70,6 +70,8 @@ protected:
bool init(ListenerID listenerId, std::function<void(EventCustom*)> callback); bool init(ListenerID listenerId, std::function<void(EventCustom*)> callback);
std::function<void(EventCustom*)> _onCustomEvent; std::function<void(EventCustom*)> _onCustomEvent;
friend class LuaEventListenerCustom;
}; };
NS_CC_END NS_CC_END

View File

@ -29,6 +29,8 @@
NS_CC_BEGIN NS_CC_BEGIN
const std::string EventListenerKeyboard::LISTENER_ID = "__cc_keyboard";
bool EventListenerKeyboard::checkAvailable() bool EventListenerKeyboard::checkAvailable()
{ {
if (onKeyPressed == nullptr && onKeyReleased == nullptr) if (onKeyPressed == nullptr && onKeyReleased == nullptr)
@ -92,7 +94,7 @@ bool EventListenerKeyboard::init()
} }
}; };
if (EventListener::init(Type::KEYBOARD, static_cast<ListenerID>(Type::KEYBOARD), listener)) if (EventListener::init(Type::KEYBOARD, LISTENER_ID, listener))
{ {
return true; return true;
} }

View File

@ -36,6 +36,8 @@ class Event;
class EventListenerKeyboard : public EventListener class EventListenerKeyboard : public EventListener
{ {
public: public:
static const std::string LISTENER_ID;
static EventListenerKeyboard* create(); static EventListenerKeyboard* create();
/// Overrides /// Overrides

View File

@ -27,6 +27,8 @@
NS_CC_BEGIN NS_CC_BEGIN
const std::string EventListenerMouse::LISTENER_ID = "__cc_mouse";
bool EventListenerMouse::checkAvailable() bool EventListenerMouse::checkAvailable()
{ {
return true; return true;
@ -65,8 +67,8 @@ EventListenerMouse* EventListenerMouse::clone()
} }
EventListenerMouse::EventListenerMouse() EventListenerMouse::EventListenerMouse()
: onMouseUp(nullptr) : onMouseDown(nullptr)
, onMouseDown(nullptr) , onMouseUp(nullptr)
, onMouseMove(nullptr) , onMouseMove(nullptr)
, onMouseScroll(nullptr) , onMouseScroll(nullptr)
{ {
@ -99,7 +101,7 @@ bool EventListenerMouse::init()
} }
}; };
if (EventListener::init(Type::MOUSE, static_cast<ListenerID>(Type::MOUSE), listener)) if (EventListener::init(Type::MOUSE, LISTENER_ID, listener))
{ {
return true; return true;
} }

View File

@ -36,6 +36,8 @@ class Event;
class EventListenerMouse : public EventListener class EventListenerMouse : public EventListener
{ {
public: public:
static const std::string LISTENER_ID;
static EventListenerMouse* create(); static EventListenerMouse* create();
/// Overrides /// Overrides

View File

@ -30,6 +30,8 @@
NS_CC_BEGIN NS_CC_BEGIN
const std::string EventListenerTouchOneByOne::LISTENER_ID = "__cc_touch_one_by_one";
EventListenerTouchOneByOne::EventListenerTouchOneByOne() EventListenerTouchOneByOne::EventListenerTouchOneByOne()
: onTouchBegan(nullptr) : onTouchBegan(nullptr)
, onTouchMoved(nullptr) , onTouchMoved(nullptr)
@ -46,7 +48,7 @@ EventListenerTouchOneByOne::~EventListenerTouchOneByOne()
bool EventListenerTouchOneByOne::init() bool EventListenerTouchOneByOne::init()
{ {
if (EventListener::init(Type::TOUCH_ONE_BY_ONE, static_cast<ListenerID>(Type::TOUCH_ONE_BY_ONE), nullptr)) if (EventListener::init(Type::TOUCH_ONE_BY_ONE, LISTENER_ID, nullptr))
{ {
return true; return true;
} }
@ -107,6 +109,9 @@ EventListenerTouchOneByOne* EventListenerTouchOneByOne::clone()
} }
///////// /////////
const std::string EventListenerTouchAllAtOnce::LISTENER_ID = "__cc_touch_all_at_once";
EventListenerTouchAllAtOnce::EventListenerTouchAllAtOnce() EventListenerTouchAllAtOnce::EventListenerTouchAllAtOnce()
: onTouchesBegan(nullptr) : onTouchesBegan(nullptr)
, onTouchesMoved(nullptr) , onTouchesMoved(nullptr)
@ -122,7 +127,7 @@ EventListenerTouchAllAtOnce::~EventListenerTouchAllAtOnce()
bool EventListenerTouchAllAtOnce::init() bool EventListenerTouchAllAtOnce::init()
{ {
if (EventListener::init(Type::TOUCH_ALL_AT_ONCE, static_cast<ListenerID>(Type::TOUCH_ALL_AT_ONCE), nullptr)) if (EventListener::init(Type::TOUCH_ALL_AT_ONCE, LISTENER_ID, nullptr))
{ {
return true; return true;
} }

View File

@ -36,6 +36,8 @@ NS_CC_BEGIN
class EventListenerTouchOneByOne : public EventListener class EventListenerTouchOneByOne : public EventListener
{ {
public: public:
static const std::string LISTENER_ID;
static EventListenerTouchOneByOne* create(); static EventListenerTouchOneByOne* create();
virtual ~EventListenerTouchOneByOne(); virtual ~EventListenerTouchOneByOne();
@ -67,8 +69,8 @@ private:
class EventListenerTouchAllAtOnce : public EventListener class EventListenerTouchAllAtOnce : public EventListener
{ {
public: public:
static const ListenerID ID = static_cast<ListenerID>(Type::TOUCH_ALL_AT_ONCE); static const std::string LISTENER_ID;
static EventListenerTouchAllAtOnce* create(); static EventListenerTouchAllAtOnce* create();
virtual ~EventListenerTouchAllAtOnce(); virtual ~EventListenerTouchAllAtOnce();

View File

@ -27,15 +27,21 @@
#include "CCFontFNT.h" #include "CCFontFNT.h"
#include "CCFontFreeType.h" #include "CCFontFreeType.h"
#include "edtaa3func.h"
NS_CC_BEGIN NS_CC_BEGIN
const int Font::DistanceMapSpread = 3;
const char * Font::_glyphASCII = "\"!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ "; const char * Font::_glyphASCII = "\"!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ ";
const char * Font::_glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ "; const char * Font::_glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ ";
Font::Font() : _usedGlyphs(GlyphCollection::ASCII), _customGlyphs(nullptr) Font::Font() :
_usedGlyphs(GlyphCollection::ASCII)
, _customGlyphs(nullptr)
,_distanceFieldEnabled(false)
{ {
} }
@ -109,6 +115,164 @@ Font* Font::createWithFNT(const std::string& fntFilePath)
return FontFNT::create(fntFilePath); return FontFNT::create(fntFilePath);
} }
unsigned char * Font::makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height)
{
unsigned int pixelAmount = (width + 2 * DistanceMapSpread) * (height + 2 * DistanceMapSpread);
short * xdist = (short *) malloc( pixelAmount * sizeof(short) );
short * ydist = (short *) malloc( pixelAmount * sizeof(short) );
double * gx = (double *) calloc( pixelAmount, sizeof(double) );
double * gy = (double *) calloc( pixelAmount, sizeof(double) );
double * data = (double *) calloc( pixelAmount, sizeof(double) );
double * outside = (double *) calloc( pixelAmount, sizeof(double) );
double * inside = (double *) calloc( pixelAmount, sizeof(double) );
unsigned int i,j;
// Convert img into double (data) rescale image levels between 0 and 1
unsigned int outWidth = width + 2 * DistanceMapSpread;
for (i = 0; i < width; ++i)
{
for (j = 0; j < height; ++j)
{
data[j * outWidth + DistanceMapSpread + i] = img[j * width + i] / 255.0;
}
}
width += 2 * DistanceMapSpread;
height += 2 * DistanceMapSpread;
// Transform background (outside contour, in areas of 0's)
computegradient( data, width, height, gx, gy);
edtaa3(data, gx, gy, width, height, xdist, ydist, outside);
for( i=0; i< pixelAmount; i++)
if( outside[i] < 0.0 )
outside[i] = 0.0;
// Transform foreground (inside contour, in areas of 1's)
for( i=0; i< pixelAmount; i++)
data[i] = 1 - data[i];
computegradient( data, width, height, gx, gy);
edtaa3(data, gx, gy, width, height, xdist, ydist, inside);
for( i=0; i< pixelAmount; i++)
if( inside[i] < 0.0 )
inside[i] = 0.0;
// The bipolar distance field is now outside-inside
double dist;
/* Single channel 8-bit output (bad precision and range, but simple) */
unsigned char *out = (unsigned char *) malloc( pixelAmount * sizeof(unsigned char) );
for( i=0; i < pixelAmount; i++)
{
dist = outside[i] - inside[i];
dist = 128.0 - dist*16;
if( dist < 0 ) dist = 0;
if( dist > 255 ) dist = 255;
out[i] = (unsigned char) dist;
}
/* Dual channel 16-bit output (more complicated, but good precision and range) */
/*unsigned char *out = (unsigned char *) malloc( pixelAmount * 3 * sizeof(unsigned char) );
for( i=0; i< pixelAmount; i++)
{
dist = outside[i] - inside[i];
dist = 128.0 - dist*16;
if( dist < 0.0 ) dist = 0.0;
if( dist >= 256.0 ) dist = 255.999;
// R channel is a copy of the original grayscale image
out[3*i] = img[i];
// G channel is fraction
out[3*i + 1] = (unsigned char) ( 256 - (dist - floor(dist)* 256.0 ));
// B channel is truncated integer part
out[3*i + 2] = (unsigned char)dist;
}*/
free( xdist );
free( ydist );
free( gx );
free( gy );
free( data );
free( outside );
free( inside );
return out;
}
void Font::setDistanceFieldEnabled(bool distanceFieldEnabled)
{
_distanceFieldEnabled = distanceFieldEnabled;
}
bool Font::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize)
{
unsigned char *sourceBitmap = 0;
int sourceWidth = 0;
int sourceHeight = 0;
sourceBitmap = getGlyphBitmap(charToRender, sourceWidth, sourceHeight);
if (!sourceBitmap)
return false;
if (_distanceFieldEnabled)
{
unsigned char * out = makeDistanceMap(sourceBitmap,sourceWidth,sourceHeight);
int iX = posX;
int iY = posY;
sourceWidth += 2 * DistanceMapSpread;
sourceHeight += 2 * DistanceMapSpread;
for (int y = 0; y < sourceHeight; ++y)
{
int bitmap_y = y * sourceWidth;
for (int x = 0; x < sourceWidth; ++x)
{
/* Dual channel 16-bit output (more complicated, but good precision and range) */
/*int index = (iX + ( iY * destSize )) * 3;
int index2 = (bitmap_y + x)*3;
destMemory[index] = out[index2];
destMemory[index + 1] = out[index2 + 1];
destMemory[index + 2] = out[index2 + 2];*/
//Single channel 8-bit output
destMemory[iX + ( iY * destSize )] = out[bitmap_y + x];
iX += 1;
}
iX = posX;
iY += 1;
}
free(out);
return true;
}
int iX = posX;
int iY = posY;
for (int y = 0; y < sourceHeight; ++y)
{
int bitmap_y = y * sourceWidth;
for (int x = 0; x < sourceWidth; ++x)
{
unsigned char cTemp = sourceBitmap[bitmap_y + x];
// the final pixel
destMemory[(iX + ( iY * destSize ) )] = cTemp;
iX += 1;
}
iX = posX;
iY += 1;
}
//everything good
return true;
}
unsigned short int * Font::getUTF16Text(const char *text, int &outNumLetters) const unsigned short int * Font::getUTF16Text(const char *text, int &outNumLetters) const
{ {
unsigned short* utf16String = cc_utf8_to_utf16(text); unsigned short* utf16String = cc_utf8_to_utf16(text);

View File

@ -40,11 +40,16 @@ class FontAtlas;
class CC_DLL Font : public Object class CC_DLL Font : public Object
{ {
public: public:
static const int DistanceMapSpread;
// create the font // create the font
static Font* createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); static Font* createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs);
static Font* createWithFNT(const std::string& fntFilePath); static Font* createWithFNT(const std::string& fntFilePath);
static unsigned char * makeDistanceMap(unsigned char *img, unsigned int width, unsigned int height);
void setDistanceFieldEnabled(bool distanceFieldEnabled);
bool isDistanceFieldEnabled() const { return _distanceFieldEnabled;}
bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize);
virtual FontAtlas *createFontAtlas() = 0; virtual FontAtlas *createFontAtlas() = 0;
virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0; virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0;
@ -76,7 +81,8 @@ protected:
char * _customGlyphs; char * _customGlyphs;
static const char * _glyphASCII; static const char * _glyphASCII;
static const char * _glyphNEHE; static const char * _glyphNEHE;
bool _distanceFieldEnabled;
}; };
NS_CC_END NS_CC_END

View File

@ -21,12 +21,14 @@
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 "cocos2d.h" #include "cocos2d.h"
#include "CCFontAtlas.h" #include "CCFontAtlas.h"
#include "CCFont.h" #include "CCFont.h"
#include "CCFontFreeType.h" #include "CCFontFreeType.h"
#define PAGE_WIDTH 1024
#define PAGE_HEIGHT 1024
NS_CC_BEGIN NS_CC_BEGIN
FontAtlas::FontAtlas(Font &theFont) : FontAtlas::FontAtlas(Font &theFont) :
@ -34,7 +36,8 @@ _font(&theFont),
_currentPageData(nullptr) _currentPageData(nullptr)
{ {
_font->retain(); _font->retain();
_makeDistanceMap = _font->isDistanceFieldEnabled();
FontFreeType* fontTTf = dynamic_cast<FontFreeType*>(_font); FontFreeType* fontTTf = dynamic_cast<FontFreeType*>(_font);
if (fontTTf && fontTTf->isDynamicGlyphCollection()) if (fontTTf && fontTTf->isDynamicGlyphCollection())
{ {
@ -45,7 +48,17 @@ _currentPageData(nullptr)
_currentPageOrigX = 0; _currentPageOrigX = 0;
_currentPageOrigY = 0; _currentPageOrigY = 0;
_letterPadding = 5; _letterPadding = 5;
_currentPageDataSize = (1024 * 1024 * 4);
if(_makeDistanceMap)
{
_commonLineHeight += 2 * Font::DistanceMapSpread;
_letterPadding += 2 * Font::DistanceMapSpread;
_currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1);
}
else
{
_currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1);
}
_currentPageData = new unsigned char[_currentPageDataSize]; _currentPageData = new unsigned char[_currentPageDataSize];
memset(_currentPageData, 0, _currentPageDataSize); memset(_currentPageData, 0, _currentPageDataSize);
@ -97,16 +110,20 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
FontFreeType* fontTTf = (FontFreeType*)_font; FontFreeType* fontTTf = (FontFreeType*)_font;
std::vector<FontLetterDefinition> fontDefs; std::unordered_map<unsigned short, FontLetterDefinition> fontDefs;
int length = cc_wcslen(utf16String); int length = cc_wcslen(utf16String);
//find out new letter //find out new letter
for (int i = 0; i < length; ++i) for (int i = 0; i < length; ++i)
{ {
auto outIterator = _fontLetterDefinitions.find(utf16String[i]); auto outIterator = _fontLetterDefinitions.find(utf16String[i]);
if (outIterator == _fontLetterDefinitions.end()) if (outIterator == _fontLetterDefinitions.end())
{ {
auto outIterator2 = fontDefs.find(utf16String[i]);
if(outIterator2 != fontDefs.end())
continue;
Rect tempRect; Rect tempRect;
FontLetterDefinition tempDef; FontLetterDefinition tempDef;
@ -135,28 +152,30 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
tempDef.offsetY = tempRect.origin.y; tempDef.offsetY = tempRect.origin.y;
tempDef.commonLineHeight = _currentPageLineHeight; tempDef.commonLineHeight = _currentPageLineHeight;
} }
fontDefs.push_back(tempDef); fontDefs[utf16String[i]] = tempDef;
} }
} }
Size _pageContentSize = Size(PAGE_WIDTH,PAGE_HEIGHT);
float scaleFactor = CC_CONTENT_SCALE_FACTOR(); float scaleFactor = CC_CONTENT_SCALE_FACTOR();
size_t newLetterCount = fontDefs.size();
float glyphWidth; float glyphWidth;
for (int i = 0; i < newLetterCount; ++i) Texture2D::PixelFormat pixelFormat = _makeDistanceMap ? Texture2D::PixelFormat::A8 : Texture2D::PixelFormat::A8;
for(auto it = fontDefs.begin(); it != fontDefs.end(); it++)
{ {
if (fontDefs[i].validDefinition) if(it->second.validDefinition)
{ {
_currentPageOrigX += _letterPadding; _currentPageOrigX += _letterPadding;
glyphWidth = fontDefs[i].width - _letterPadding; glyphWidth = it->second.width - _letterPadding;
if (_currentPageOrigX + glyphWidth > 1024) if (_currentPageOrigX + glyphWidth > PAGE_WIDTH)
{ {
_currentPageOrigY += _currentPageLineHeight; _currentPageOrigY += _currentPageLineHeight;
if(_currentPageOrigY >= 1024) _currentPageOrigX = 0;
if(_currentPageOrigY >= PAGE_HEIGHT)
{ {
_atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, Texture2D::PixelFormat::RGBA8888, 1024, 1024, Size(1024, 1024) ); _atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, pixelFormat, PAGE_WIDTH, PAGE_HEIGHT, _pageContentSize );
_currentPageOrigX = 0;
_currentPageOrigY = 0; _currentPageOrigY = 0;
delete []_currentPageData; delete []_currentPageData;
@ -170,63 +189,25 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String)
tex->release(); tex->release();
} }
} }
renderCharAt(fontDefs[i].letteCharUTF16,_currentPageOrigX,_currentPageOrigY,_currentPageData,1024); _font->renderCharAt(it->second.letteCharUTF16,_currentPageOrigX,_currentPageOrigY,_currentPageData,PAGE_WIDTH);
fontDefs[i].U = _currentPageOrigX - 1; it->second.U = _currentPageOrigX - 1;
fontDefs[i].V = _currentPageOrigY; it->second.V = _currentPageOrigY;
fontDefs[i].textureID = _currentPage; it->second.textureID = _currentPage;
// take from pixels to points // take from pixels to points
fontDefs[i].width = fontDefs[i].width / scaleFactor; it->second.width = it->second.width / scaleFactor;
fontDefs[i].height = fontDefs[i].height / scaleFactor; it->second.height = it->second.height / scaleFactor;
fontDefs[i].U = fontDefs[i].U / scaleFactor; it->second.U = it->second.U / scaleFactor;
fontDefs[i].V = fontDefs[i].V / scaleFactor; it->second.V = it->second.V / scaleFactor;
} }
else else
glyphWidth = 0; glyphWidth = 0;
this->addLetterDefinition(fontDefs[i]); _fontLetterDefinitions[it->second.letteCharUTF16] = it->second;
_currentPageOrigX += glyphWidth; _currentPageOrigX += glyphWidth;
} }
if(newLetterCount > 0) if(fontDefs.size() > 0)
_atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, Texture2D::PixelFormat::RGBA8888, 1024, 1024, Size(1024, 1024) ); _atlasTextures[_currentPage]->initWithData(_currentPageData, _currentPageDataSize, pixelFormat, PAGE_WIDTH, PAGE_HEIGHT, _pageContentSize );
return true;
}
bool FontAtlas::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize)
{
unsigned char *sourceBitmap = 0;
int sourceWidth = 0;
int sourceHeight = 0;
// get the glyph's bitmap
sourceBitmap = _font->getGlyphBitmap(charToRender, sourceWidth, sourceHeight);
if (!sourceBitmap)
return false;
int iX = posX;
int iY = posY;
for (int y = 0; y < sourceHeight; ++y)
{
int bitmap_y = y * sourceWidth;
for (int x = 0; x < sourceWidth; ++x)
{
unsigned char cTemp = sourceBitmap[bitmap_y + x];
// the final pixel
int iTemp = cTemp << 24 | cTemp << 16 | cTemp << 8 | cTemp;
*(int*) &destMemory[(iX + ( iY * destSize ) ) * 4] = iTemp;
iX += 1;
}
iX = posX;
iY += 1;
}
//everything good
return true; return true;
} }
@ -248,6 +229,8 @@ float FontAtlas::getCommonLineHeight() const
void FontAtlas::setCommonLineHeight(float newHeight) void FontAtlas::setCommonLineHeight(float newHeight)
{ {
if(_makeDistanceMap)
newHeight += 2 * Font::DistanceMapSpread;
_commonLineHeight = newHeight; _commonLineHeight = newHeight;
} }

View File

@ -73,7 +73,6 @@ public:
const Font* getFont() const; const Font* getFont() const;
private: private:
bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize);
void relaseTextures(); void relaseTextures();
std::unordered_map<int, Texture2D*> _atlasTextures; std::unordered_map<int, Texture2D*> _atlasTextures;
@ -89,6 +88,7 @@ private:
float _currentPageOrigY; float _currentPageOrigY;
float _currentPageLineHeight; float _currentPageLineHeight;
float _letterPadding; float _letterPadding;
bool _makeDistanceMap;
}; };

View File

@ -30,14 +30,14 @@ NS_CC_BEGIN
std::unordered_map<std::string, FontAtlas *> FontAtlasCache::_atlasMap; std::unordered_map<std::string, FontAtlas *> FontAtlasCache::_atlasMap;
FontAtlas * FontAtlasCache::getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs) FontAtlas * FontAtlasCache::getFontAtlasTTF(const std::string& fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs, bool useDistanceField)
{ {
std::string atlasName = generateFontName(fontFileName, size, glyphs); std::string atlasName = generateFontName(fontFileName, size, glyphs, useDistanceField);
FontAtlas *tempAtlas = _atlasMap[atlasName]; FontAtlas *tempAtlas = _atlasMap[atlasName];
if ( !tempAtlas ) if ( !tempAtlas )
{ {
tempAtlas = FontAtlasFactory::createAtlasFromTTF(fontFileName, size, glyphs, customGlyphs); tempAtlas = FontAtlasFactory::createAtlasFromTTF(fontFileName, size, glyphs, customGlyphs, useDistanceField);
if (tempAtlas) if (tempAtlas)
_atlasMap[atlasName] = tempAtlas; _atlasMap[atlasName] = tempAtlas;
} }
@ -49,9 +49,9 @@ FontAtlas * FontAtlasCache::getFontAtlasTTF(const char *fontFileName, int size,
return tempAtlas; return tempAtlas;
} }
FontAtlas * FontAtlasCache::getFontAtlasFNT(const char *fontFileName) FontAtlas * FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName)
{ {
std::string atlasName = generateFontName(fontFileName, 0, GlyphCollection::CUSTOM); std::string atlasName = generateFontName(fontFileName, 0, GlyphCollection::CUSTOM,false);
FontAtlas *tempAtlas = _atlasMap[atlasName]; FontAtlas *tempAtlas = _atlasMap[atlasName];
if ( !tempAtlas ) if ( !tempAtlas )
@ -68,7 +68,7 @@ FontAtlas * FontAtlasCache::getFontAtlasFNT(const char *fontFileName)
return tempAtlas; return tempAtlas;
} }
std::string FontAtlasCache::generateFontName(const char *fontFileName, int size, GlyphCollection theGlyphs) std::string FontAtlasCache::generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField)
{ {
std::string tempName(fontFileName); std::string tempName(fontFileName);
@ -93,7 +93,8 @@ std::string FontAtlasCache::generateFontName(const char *fontFileName, int size,
default: default:
break; break;
} }
if(useDistanceField)
tempName.append("df");
// std::to_string is not supported on android, using std::stringstream instead. // std::to_string is not supported on android, using std::stringstream instead.
std::stringstream ss; std::stringstream ss;
ss << size; ss << size;

View File

@ -38,14 +38,14 @@ class CC_DLL FontAtlasCache
public: public:
static FontAtlas * getFontAtlasTTF(const char *fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0); static FontAtlas * getFontAtlasTTF(const std::string& fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false);
static FontAtlas * getFontAtlasFNT(const char *fontFileName); static FontAtlas * getFontAtlasFNT(const std::string& fontFileName);
static bool releaseFontAtlas(FontAtlas *atlas); static bool releaseFontAtlas(FontAtlas *atlas);
private: private:
static std::string generateFontName(const char *fontFileName, int size, GlyphCollection theGlyphs); static std::string generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField);
static std::unordered_map<std::string, FontAtlas *> _atlasMap; static std::unordered_map<std::string, FontAtlas *> _atlasMap;
}; };

View File

@ -30,24 +30,28 @@
NS_CC_BEGIN NS_CC_BEGIN
FontAtlas * FontAtlasFactory::createAtlasFromTTF(const char* fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs) FontAtlas * FontAtlasFactory::createAtlasFromTTF(const std::string& fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs, bool useDistanceField)
{ {
Font *font = Font::createWithTTF(fntFilePath, fontSize, glyphs, customGlyphs); Font *font = Font::createWithTTF(fntFilePath, fontSize, glyphs, customGlyphs);
if (font) if (font)
{
font->setDistanceFieldEnabled(useDistanceField);
return font->createFontAtlas(); return font->createFontAtlas();
}
else else
{
return nullptr; return nullptr;
}
} }
FontAtlas * FontAtlasFactory::createAtlasFromFNT(const char* fntFilePath) FontAtlas * FontAtlasFactory::createAtlasFromFNT(const std::string& fntFilePath)
{ {
Font *font = Font::createWithFNT(fntFilePath); Font *font = Font::createWithFNT(fntFilePath);
if(font) if(font)
{ {
FontAtlas * atlas = font->createFontAtlas(); return font->createFontAtlas();
return atlas;
} }
else else
{ {

View File

@ -36,8 +36,8 @@ class CC_DLL FontAtlasFactory
public: public:
static FontAtlas * createAtlasFromTTF(const char* fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs = 0); static FontAtlas * createAtlasFromTTF(const std::string& fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false);
static FontAtlas * createAtlasFromFNT(const char* fntFilePath); static FontAtlas * createAtlasFromFNT(const std::string& fntFilePath);
private: private:
}; };

View File

@ -90,22 +90,23 @@ FT_Library FontFreeType::getFTLibrary()
FontFreeType::FontFreeType(bool dynamicGlyphCollection) FontFreeType::FontFreeType(bool dynamicGlyphCollection)
: _fontRef(nullptr), : _fontRef(nullptr),
_letterPadding(5), _letterPadding(5),
_ttfData(nullptr),
_dynamicGlyphCollection(dynamicGlyphCollection) _dynamicGlyphCollection(dynamicGlyphCollection)
{ {
if(_distanceFieldEnabled)
_letterPadding += 2 * DistanceMapSpread;
} }
bool FontFreeType::createFontObject(const std::string &fontName, int fontSize) bool FontFreeType::createFontObject(const std::string &fontName, int fontSize)
{ {
FT_Face face; FT_Face face;
ssize_t len = 0; _ttfData = FileUtils::getInstance()->getDataFromFile(fontName);
_ttfData = FileUtils::getInstance()->getFileData(fontName.c_str(), "rb", &len);
if (!_ttfData) if (_ttfData.isNull())
return false; return false;
// create the face from the data // create the face from the data
if (FT_New_Memory_Face(getFTLibrary(), _ttfData, len, 0, &face )) if (FT_New_Memory_Face(getFTLibrary(), _ttfData.getBytes(), _ttfData.getSize(), 0, &face ))
return false; return false;
//we want to use unicode //we want to use unicode
@ -134,11 +135,6 @@ FontFreeType::~FontFreeType()
{ {
FT_Done_Face(_fontRef); FT_Done_Face(_fontRef);
} }
if (_ttfData)
{
free(_ttfData);
_ttfData = nullptr;
}
} }
FontAtlas * FontFreeType::createFontAtlas() FontAtlas * FontFreeType::createFontAtlas()
@ -354,23 +350,21 @@ int FontFreeType::getFontMaxHeight() const
return (static_cast<int>(_fontRef->size->metrics.height >> 6)); return (static_cast<int>(_fontRef->size->metrics.height >> 6));
} }
unsigned char * FontFreeType::getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const unsigned char * FontFreeType::getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const
{ {
if (!_fontRef) if (!_fontRef)
return 0; return 0;
// get the ID to the char we need if (_distanceFieldEnabled)
int glyphIndex = FT_Get_Char_Index(_fontRef, theChar); {
if (FT_Load_Char(_fontRef,theChar,FT_LOAD_RENDER | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT))
if (!glyphIndex) return 0;
return 0; }
else
// load glyph infos {
if (FT_Load_Glyph(_fontRef, glyphIndex, FT_LOAD_DEFAULT)) if (FT_Load_Char(_fontRef,theChar,FT_LOAD_RENDER))
return 0; return 0;
}
if (FT_Render_Glyph( _fontRef->glyph, FT_RENDER_MODE_NORMAL ))
return 0;
outWidth = _fontRef->glyph->bitmap.width; outWidth = _fontRef->glyph->bitmap.width;
outHeight = _fontRef->glyph->bitmap.rows; outHeight = _fontRef->glyph->bitmap.rows;

View File

@ -25,11 +25,12 @@
#ifndef _FontFreetype_h_ #ifndef _FontFreetype_h_
#define _FontFreetype_h_ #define _FontFreetype_h_
#include "CCFont.h"
#include "CCData.h"
#include <string> #include <string>
#include <ft2build.h> #include <ft2build.h>
#include "CCFont.h"
#include FT_FREETYPE_H #include FT_FREETYPE_H
NS_CC_BEGIN NS_CC_BEGIN
@ -71,9 +72,9 @@ private:
static FT_Library _FTlibrary; static FT_Library _FTlibrary;
static bool _FTInitialized; static bool _FTInitialized;
FT_Face _fontRef; FT_Face _fontRef;
const int _letterPadding; int _letterPadding;
std::string _fontName; std::string _fontName;
unsigned char* _ttfData; Data _ttfData;
bool _dynamicGlyphCollection; bool _dynamicGlyphCollection;
}; };

View File

@ -46,6 +46,7 @@ typedef struct _hashUniformEntry
} tHashUniformEntry; } tHashUniformEntry;
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR = "ShaderPositionTextureColor"; const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR = "ShaderPositionTextureColor";
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP = "ShaderPositionTextureColor_noMVP";
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST = "ShaderPositionTextureColorAlphaTest"; const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST = "ShaderPositionTextureColorAlphaTest";
const char* GLProgram::SHADER_NAME_POSITION_COLOR = "ShaderPositionColor"; const char* GLProgram::SHADER_NAME_POSITION_COLOR = "ShaderPositionColor";
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE = "ShaderPositionTexture"; const char* GLProgram::SHADER_NAME_POSITION_TEXTURE = "ShaderPositionTexture";
@ -54,6 +55,12 @@ const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR = "ShaderPositionTe
const char* GLProgram::SHADER_NAME_POSITION_U_COLOR = "ShaderPosition_uColor"; const char* GLProgram::SHADER_NAME_POSITION_U_COLOR = "ShaderPosition_uColor";
const char* GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR = "ShaderPositionLengthTextureColor"; const char* GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR = "ShaderPositionLengthTextureColor";
const char* GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_NORMAL = "ShaderLabelNormol";
const char* GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_GLOW = "ShaderLabelGlow";
const char* GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_OUTLINE = "ShaderLabelOutline";
const char* GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_SHADOW = "ShaderLabelShadow";
// uniform names // uniform names
const char* GLProgram::UNIFORM_NAME_P_MATRIX = "CC_PMatrix"; const char* GLProgram::UNIFORM_NAME_P_MATRIX = "CC_PMatrix";
const char* GLProgram::UNIFORM_NAME_MV_MATRIX = "CC_MVMatrix"; const char* GLProgram::UNIFORM_NAME_MV_MATRIX = "CC_MVMatrix";
@ -74,7 +81,7 @@ GLProgram::GLProgram()
: _program(0) : _program(0)
, _vertShader(0) , _vertShader(0)
, _fragShader(0) , _fragShader(0)
, _hashForUniforms(NULL) , _hashForUniforms(nullptr)
, _flags() , _flags()
{ {
memset(_uniforms, 0, sizeof(_uniforms)); memset(_uniforms, 0, sizeof(_uniforms));
@ -138,7 +145,7 @@ bool GLProgram::initWithVertexShaderByteArray(const GLchar* vShaderByteArray, co
{ {
glAttachShader(_program, _fragShader); glAttachShader(_program, _fragShader);
} }
_hashForUniforms = NULL; _hashForUniforms = nullptr;
CHECK_GL_ERROR_DEBUG(); CHECK_GL_ERROR_DEBUG();
@ -147,18 +154,18 @@ bool GLProgram::initWithVertexShaderByteArray(const GLchar* vShaderByteArray, co
bool GLProgram::initWithVertexShaderFilename(const char* vShaderFilename, const char* fShaderFilename) bool GLProgram::initWithVertexShaderFilename(const char* vShaderFilename, const char* fShaderFilename)
{ {
const GLchar * vertexSource = (GLchar*) String::createWithContentsOfFile(FileUtils::getInstance()->fullPathForFilename(vShaderFilename).c_str())->getCString(); std::string vertexSource = FileUtils::getInstance()->getStringFromFile(FileUtils::getInstance()->fullPathForFilename(vShaderFilename).c_str());
const GLchar * fragmentSource = (GLchar*) String::createWithContentsOfFile(FileUtils::getInstance()->fullPathForFilename(fShaderFilename).c_str())->getCString(); std::string fragmentSource = FileUtils::getInstance()->getStringFromFile(FileUtils::getInstance()->fullPathForFilename(fShaderFilename).c_str());
return initWithVertexShaderByteArray(vertexSource, fragmentSource); return initWithVertexShaderByteArray(vertexSource.c_str(), fragmentSource.c_str());
} }
std::string GLProgram::getDescription() const std::string GLProgram::getDescription() const
{ {
return String::createWithFormat("<GLProgram = " return StringUtils::format("<GLProgram = "
CC_FORMAT_PRINTF_SIZE_T CC_FORMAT_PRINTF_SIZE_T
" | Program = %i, VertexShader = %i, FragmentShader = %i>", " | Program = %i, VertexShader = %i, FragmentShader = %i>",
(size_t)this, _program, _vertShader, _fragShader)->getCString(); (size_t)this, _program, _vertShader, _fragShader);
} }
bool GLProgram::compileShader(GLuint * shader, GLenum type, const GLchar* source) bool GLProgram::compileShader(GLuint * shader, GLenum type, const GLchar* source)
@ -186,7 +193,7 @@ bool GLProgram::compileShader(GLuint * shader, GLenum type, const GLchar* source
}; };
*shader = glCreateShader(type); *shader = glCreateShader(type);
glShaderSource(*shader, sizeof(sources)/sizeof(*sources), sources, NULL); glShaderSource(*shader, sizeof(sources)/sizeof(*sources), sources, nullptr);
glCompileShader(*shader); glCompileShader(*shader);
glGetShaderiv(*shader, GL_COMPILE_STATUS, &status); glGetShaderiv(*shader, GL_COMPILE_STATUS, &status);
@ -197,7 +204,7 @@ bool GLProgram::compileShader(GLuint * shader, GLenum type, const GLchar* source
glGetShaderiv(*shader, GL_SHADER_SOURCE_LENGTH, &length); glGetShaderiv(*shader, GL_SHADER_SOURCE_LENGTH, &length);
GLchar* src = (GLchar *)malloc(sizeof(GLchar) * length); GLchar* src = (GLchar *)malloc(sizeof(GLchar) * length);
glGetShaderSource(*shader, length, NULL, src); glGetShaderSource(*shader, length, nullptr, src);
CCLOG("cocos2d: ERROR: Failed to compile shader:\n%s", src); CCLOG("cocos2d: ERROR: Failed to compile shader:\n%s", src);
if (type == GL_VERTEX_SHADER) if (type == GL_VERTEX_SHADER)
@ -234,8 +241,9 @@ void GLProgram::updateUniforms()
_uniforms[UNIFORM_SAMPLER] = glGetUniformLocation(_program, UNIFORM_NAME_SAMPLER); _uniforms[UNIFORM_SAMPLER] = glGetUniformLocation(_program, UNIFORM_NAME_SAMPLER);
_flags.usesP = _uniforms[UNIFORM_P_MATRIX] != -1;
_flags.usesMV = _uniforms[UNIFORM_MV_MATRIX] != -1;
_flags.usesMVP = _uniforms[UNIFORM_MVP_MATRIX] != -1; _flags.usesMVP = _uniforms[UNIFORM_MVP_MATRIX] != -1;
_flags.usesMV = (_uniforms[UNIFORM_MV_MATRIX] != -1 && _uniforms[UNIFORM_P_MATRIX] != -1 );
_flags.usesTime = ( _flags.usesTime = (
_uniforms[UNIFORM_TIME] != -1 || _uniforms[UNIFORM_TIME] != -1 ||
_uniforms[UNIFORM_SIN_TIME] != -1 || _uniforms[UNIFORM_SIN_TIME] != -1 ||
@ -323,7 +331,7 @@ std::string GLProgram::getProgramLog() const
// Uniform cache // Uniform cache
bool GLProgram::updateUniformLocation(GLint location, GLvoid* data, unsigned int bytes) bool GLProgram::updateUniformLocation(GLint location, const GLvoid* data, unsigned int bytes)
{ {
if (location < 0) if (location < 0)
{ {
@ -331,7 +339,7 @@ bool GLProgram::updateUniformLocation(GLint location, GLvoid* data, unsigned int
} }
bool updated = true; bool updated = true;
tHashUniformEntry *element = NULL; tHashUniformEntry *element = nullptr;
HASH_FIND_INT(_hashForUniforms, &location, element); HASH_FIND_INT(_hashForUniforms, &location, element);
if (! element) if (! element)
@ -364,7 +372,7 @@ bool GLProgram::updateUniformLocation(GLint location, GLvoid* data, unsigned int
GLint GLProgram::getUniformLocationForName(const char* name) const GLint GLProgram::getUniformLocationForName(const char* name) const
{ {
CCASSERT(name != NULL, "Invalid uniform name" ); CCASSERT(name != nullptr, "Invalid uniform name" );
CCASSERT(_program != 0, "Invalid operation. Cannot get uniform location when program is not initialized"); CCASSERT(_program != 0, "Invalid operation. Cannot get uniform location when program is not initialized");
return glGetUniformLocation(_program, name); return glGetUniformLocation(_program, name);
@ -486,7 +494,7 @@ void GLProgram::setUniformLocationWith4f(GLint location, GLfloat f1, GLfloat f2,
} }
} }
void GLProgram::setUniformLocationWith2fv(GLint location, GLfloat* floats, unsigned int numberOfArrays) void GLProgram::setUniformLocationWith2fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays)
{ {
bool updated = updateUniformLocation(location, floats, sizeof(float)*2*numberOfArrays); bool updated = updateUniformLocation(location, floats, sizeof(float)*2*numberOfArrays);
@ -496,7 +504,7 @@ void GLProgram::setUniformLocationWith2fv(GLint location, GLfloat* floats, unsig
} }
} }
void GLProgram::setUniformLocationWith3fv(GLint location, GLfloat* floats, unsigned int numberOfArrays) void GLProgram::setUniformLocationWith3fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays)
{ {
bool updated = updateUniformLocation(location, floats, sizeof(float)*3*numberOfArrays); bool updated = updateUniformLocation(location, floats, sizeof(float)*3*numberOfArrays);
@ -506,7 +514,7 @@ void GLProgram::setUniformLocationWith3fv(GLint location, GLfloat* floats, unsig
} }
} }
void GLProgram::setUniformLocationWith4fv(GLint location, GLfloat* floats, unsigned int numberOfArrays) void GLProgram::setUniformLocationWith4fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays)
{ {
bool updated = updateUniformLocation(location, floats, sizeof(float)*4*numberOfArrays); bool updated = updateUniformLocation(location, floats, sizeof(float)*4*numberOfArrays);
@ -516,7 +524,7 @@ void GLProgram::setUniformLocationWith4fv(GLint location, GLfloat* floats, unsig
} }
} }
void GLProgram::setUniformLocationWithMatrix2fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices) { void GLProgram::setUniformLocationWithMatrix2fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices) {
bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*4*numberOfMatrices); bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*4*numberOfMatrices);
if( updated ) if( updated )
@ -525,7 +533,7 @@ void GLProgram::setUniformLocationWithMatrix2fv(GLint location, GLfloat* matrixA
} }
} }
void GLProgram::setUniformLocationWithMatrix3fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices) { void GLProgram::setUniformLocationWithMatrix3fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices) {
bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*9*numberOfMatrices); bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*9*numberOfMatrices);
if( updated ) if( updated )
@ -535,7 +543,7 @@ void GLProgram::setUniformLocationWithMatrix3fv(GLint location, GLfloat* matrixA
} }
void GLProgram::setUniformLocationWithMatrix4fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices) void GLProgram::setUniformLocationWithMatrix4fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices)
{ {
bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*16*numberOfMatrices); bool updated = updateUniformLocation(location, matrixArray, sizeof(float)*16*numberOfMatrices);
@ -547,12 +555,23 @@ void GLProgram::setUniformLocationWithMatrix4fv(GLint location, GLfloat* matrixA
void GLProgram::setUniformsForBuiltins() void GLProgram::setUniformsForBuiltins()
{ {
kmMat4 matrixP;
kmMat4 matrixMV; kmMat4 matrixMV;
kmGLGetMatrix(KM_GL_MODELVIEW, &matrixMV);
setUniformsForBuiltins(matrixMV);
}
void GLProgram::setUniformsForBuiltins(const kmMat4 &matrixMV)
{
kmMat4 matrixP;
kmGLGetMatrix(KM_GL_PROJECTION, &matrixP); kmGLGetMatrix(KM_GL_PROJECTION, &matrixP);
kmGLGetMatrix(KM_GL_MODELVIEW, &matrixMV);
if(_flags.usesP)
setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_P_MATRIX], matrixP.mat, 1);
if(_flags.usesMV)
setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_MV_MATRIX], matrixMV.mat, 1);
if(_flags.usesMVP) { if(_flags.usesMVP) {
kmMat4 matrixMVP; kmMat4 matrixMVP;
@ -560,11 +579,6 @@ void GLProgram::setUniformsForBuiltins()
setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_MVP_MATRIX], matrixMVP.mat, 1); setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_MVP_MATRIX], matrixMVP.mat, 1);
} }
if(_flags.usesMV) {
setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_P_MATRIX], matrixP.mat, 1);
setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_MV_MATRIX], matrixMV.mat, 1);
}
if(_flags.usesTime) { if(_flags.usesTime) {
Director *director = Director::getInstance(); Director *director = Director::getInstance();
// This doesn't give the most accurate global time value. // This doesn't give the most accurate global time value.
@ -601,7 +615,7 @@ void GLProgram::reset()
free(current_element->value); free(current_element->value);
free(current_element); free(current_element);
} }
_hashForUniforms = NULL; _hashForUniforms = nullptr;
} }
NS_CC_END NS_CC_END

View File

@ -32,6 +32,7 @@ THE SOFTWARE.
#include "CCObject.h" #include "CCObject.h"
#include "CCGL.h" #include "CCGL.h"
#include "kazmath/kazmath.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -78,6 +79,7 @@ public:
}; };
static const char* SHADER_NAME_POSITION_TEXTURE_COLOR; static const char* SHADER_NAME_POSITION_TEXTURE_COLOR;
static const char* SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP;
static const char* SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST; static const char* SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST;
static const char* SHADER_NAME_POSITION_COLOR; static const char* SHADER_NAME_POSITION_COLOR;
static const char* SHADER_NAME_POSITION_TEXTURE; static const char* SHADER_NAME_POSITION_TEXTURE;
@ -85,6 +87,11 @@ public:
static const char* SHADER_NAME_POSITION_TEXTURE_A8_COLOR; static const char* SHADER_NAME_POSITION_TEXTURE_A8_COLOR;
static const char* SHADER_NAME_POSITION_U_COLOR; static const char* SHADER_NAME_POSITION_U_COLOR;
static const char* SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR; static const char* SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR;
static const char* SHADER_NAME_LABEL_DISTANCEFIELD_NORMAL;
static const char* SHADER_NAME_LABEL_DISTANCEFIELD_GLOW;
static const char* SHADER_NAME_LABEL_DISTANCEFIELD_OUTLINE;
static const char* SHADER_NAME_LABEL_DISTANCEFIELD_SHADOW;
// uniform names // uniform names
static const char* UNIFORM_NAME_P_MATRIX; static const char* UNIFORM_NAME_P_MATRIX;
@ -190,25 +197,26 @@ public:
void setUniformLocationWith4f(GLint location, GLfloat f1, GLfloat f2, GLfloat f3, GLfloat f4); void setUniformLocationWith4f(GLint location, GLfloat f1, GLfloat f2, GLfloat f3, GLfloat f4);
/** calls glUniform2fv only if the values are different than the previous call for this same shader program. */ /** calls glUniform2fv only if the values are different than the previous call for this same shader program. */
void setUniformLocationWith2fv(GLint location, GLfloat* floats, unsigned int numberOfArrays); void setUniformLocationWith2fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays);
/** calls glUniform3fv only if the values are different than the previous call for this same shader program. */ /** calls glUniform3fv only if the values are different than the previous call for this same shader program. */
void setUniformLocationWith3fv(GLint location, GLfloat* floats, unsigned int numberOfArrays); void setUniformLocationWith3fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays);
/** calls glUniform4fv only if the values are different than the previous call for this same shader program. */ /** calls glUniform4fv only if the values are different than the previous call for this same shader program. */
void setUniformLocationWith4fv(GLint location, GLfloat* floats, unsigned int numberOfArrays); void setUniformLocationWith4fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays);
/** calls glUniformMatrix2fv only if the values are different than the previous call for this same shader program. */ /** calls glUniformMatrix2fv only if the values are different than the previous call for this same shader program. */
void setUniformLocationWithMatrix2fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices); void setUniformLocationWithMatrix2fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices);
/** calls glUniformMatrix3fv only if the values are different than the previous call for this same shader program. */ /** calls glUniformMatrix3fv only if the values are different than the previous call for this same shader program. */
void setUniformLocationWithMatrix3fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices); void setUniformLocationWithMatrix3fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices);
/** calls glUniformMatrix4fv only if the values are different than the previous call for this same shader program. */ /** calls glUniformMatrix4fv only if the values are different than the previous call for this same shader program. */
void setUniformLocationWithMatrix4fv(GLint location, GLfloat* matrixArray, unsigned int numberOfMatrices); void setUniformLocationWithMatrix4fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices);
/** will update the builtin uniforms if they are different than the previous call for this same shader program. */ /** will update the builtin uniforms if they are different than the previous call for this same shader program. */
void setUniformsForBuiltins(); void setUniformsForBuiltins();
void setUniformsForBuiltins(const kmMat4 &modelView);
/** returns the vertexShader error log */ /** returns the vertexShader error log */
std::string getVertexShaderLog() const; std::string getVertexShaderLog() const;
@ -226,8 +234,9 @@ public:
inline const GLuint getProgram() const { return _program; } inline const GLuint getProgram() const { return _program; }
private: private:
bool updateUniformLocation(GLint location, GLvoid* data, unsigned int bytes); bool updateUniformLocation(GLint location, const GLvoid* data, unsigned int bytes);
virtual std::string getDescription() const; virtual std::string getDescription() const;
bool compileShader(GLuint * shader, GLenum type, const GLchar* source); bool compileShader(GLuint * shader, GLenum type, const GLchar* source);
std::string logForOpenGLObject(GLuint object, GLInfoFunction infoFunc, GLLogFunction logFunc) const; std::string logForOpenGLObject(GLuint object, GLInfoFunction infoFunc, GLLogFunction logFunc) const;
@ -242,6 +251,7 @@ private:
unsigned int usesTime:1; unsigned int usesTime:1;
unsigned int usesMVP:1; unsigned int usesMVP:1;
unsigned int usesMV:1; unsigned int usesMV:1;
unsigned int usesP:1;
unsigned int usesRandom:1; unsigned int usesRandom:1;
// handy way to initialize the bitfield // handy way to initialize the bitfield

View File

@ -76,9 +76,9 @@ GridBase* GridBase::create(const Size& gridSize, Texture2D *texture, bool flippe
return pGridBase; return pGridBase;
} }
bool GridBase::initWithSize(const Size& gridSize, Texture2D *texture, bool bFlipped) bool GridBase::initWithSize(const Size& gridSize, Texture2D *texture, bool flipped)
{ {
bool bRet = true; bool ret = true;
_active = false; _active = false;
_reuseGrid = 0; _reuseGrid = 0;
@ -86,7 +86,7 @@ bool GridBase::initWithSize(const Size& gridSize, Texture2D *texture, bool bFlip
_texture = texture; _texture = texture;
CC_SAFE_RETAIN(_texture); CC_SAFE_RETAIN(_texture);
_isTextureFlipped = bFlipped; _isTextureFlipped = flipped;
Size texSize = _texture->getContentSize(); Size texSize = _texture->getContentSize();
_step.x = texSize.width / _gridSize.width; _step.x = texSize.width / _gridSize.width;
@ -99,19 +99,19 @@ bool GridBase::initWithSize(const Size& gridSize, Texture2D *texture, bool bFlip
} }
else else
{ {
bRet = false; ret = false;
} }
_shaderProgram = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE); _shaderProgram = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE);
calculateVertexPoints(); calculateVertexPoints();
return bRet; return ret;
} }
bool GridBase::initWithSize(const Size& gridSize) bool GridBase::initWithSize(const Size& gridSize)
{ {
Director *pDirector = Director::getInstance(); Director *director = Director::getInstance();
Size s = pDirector->getWinSizeInPixels(); Size s = director->getWinSizeInPixels();
auto POTWide = ccNextPOT((unsigned int)s.width); auto POTWide = ccNextPOT((unsigned int)s.width);
auto POTHigh = ccNextPOT((unsigned int)s.height); auto POTHigh = ccNextPOT((unsigned int)s.height);
@ -156,10 +156,10 @@ GridBase::~GridBase(void)
} }
// properties // properties
void GridBase::setActive(bool bActive) void GridBase::setActive(bool active)
{ {
_active = bActive; _active = active;
if (! bActive) if (! active)
{ {
Director *pDirector = Director::getInstance(); Director *pDirector = Director::getInstance();
Director::Projection proj = pDirector->getProjection(); Director::Projection proj = pDirector->getProjection();
@ -167,11 +167,11 @@ void GridBase::setActive(bool bActive)
} }
} }
void GridBase::setTextureFlipped(bool bFlipped) void GridBase::setTextureFlipped(bool flipped)
{ {
if (_isTextureFlipped != bFlipped) if (_isTextureFlipped != flipped)
{ {
_isTextureFlipped = bFlipped; _isTextureFlipped = flipped;
calculateVertexPoints(); calculateVertexPoints();
} }
} }
@ -216,17 +216,17 @@ void GridBase::afterDraw(cocos2d::Node *target)
Director *director = Director::getInstance(); Director *director = Director::getInstance();
director->setProjection(_directorProjection); director->setProjection(_directorProjection);
if (target->getCamera()->isDirty()) // if (target->getCamera()->isDirty())
{ // {
Point offset = target->getAnchorPointInPoints(); // Point offset = target->getAnchorPointInPoints();
//
// // //
// XXX: Camera should be applied in the AnchorPoint // // XXX: Camera should be applied in the AnchorPoint
// // //
kmGLTranslatef(offset.x, offset.y, 0); // kmGLTranslatef(offset.x, offset.y, 0);
target->getCamera()->locate(); // target->getCamera()->locate();
kmGLTranslatef(-offset.x, -offset.y, 0); // kmGLTranslatef(-offset.x, -offset.y, 0);
} // }
GL::bindTexture2D(_texture->getName()); GL::bindTexture2D(_texture->getName());
@ -253,52 +253,52 @@ void GridBase::calculateVertexPoints(void)
// implementation of Grid3D // implementation of Grid3D
Grid3D* Grid3D::create(const Size& gridSize, Texture2D *texture, bool bFlipped) Grid3D* Grid3D::create(const Size& gridSize, Texture2D *texture, bool flipped)
{ {
Grid3D *pRet= new Grid3D(); Grid3D *ret= new Grid3D();
if (pRet) if (ret)
{ {
if (pRet->initWithSize(gridSize, texture, bFlipped)) if (ret->initWithSize(gridSize, texture, flipped))
{ {
pRet->autorelease(); ret->autorelease();
} }
else else
{ {
delete pRet; delete ret;
pRet = NULL; ret = nullptr;
} }
} }
return pRet; return ret;
} }
Grid3D* Grid3D::create(const Size& gridSize) Grid3D* Grid3D::create(const Size& gridSize)
{ {
Grid3D *pRet= new Grid3D(); Grid3D *ret= new Grid3D();
if (pRet) if (ret)
{ {
if (pRet->initWithSize(gridSize)) if (ret->initWithSize(gridSize))
{ {
pRet->autorelease(); ret->autorelease();
} }
else else
{ {
delete pRet; delete ret;
pRet = NULL; ret = nullptr;
} }
} }
return pRet; return ret;
} }
Grid3D::Grid3D() Grid3D::Grid3D()
: _texCoordinates(NULL) : _texCoordinates(nullptr)
, _vertices(NULL) , _vertices(nullptr)
, _originalVertices(NULL) , _originalVertices(nullptr)
, _indices(NULL) , _indices(nullptr)
{ {
} }
@ -470,10 +470,10 @@ void Grid3D::reuse(void)
// implementation of TiledGrid3D // implementation of TiledGrid3D
TiledGrid3D::TiledGrid3D() TiledGrid3D::TiledGrid3D()
: _texCoordinates(NULL) : _texCoordinates(nullptr)
, _vertices(NULL) , _vertices(nullptr)
, _originalVertices(NULL) , _originalVertices(nullptr)
, _indices(NULL) , _indices(nullptr)
{ {
} }
@ -486,44 +486,44 @@ TiledGrid3D::~TiledGrid3D(void)
CC_SAFE_FREE(_indices); CC_SAFE_FREE(_indices);
} }
TiledGrid3D* TiledGrid3D::create(const Size& gridSize, Texture2D *texture, bool bFlipped) TiledGrid3D* TiledGrid3D::create(const Size& gridSize, Texture2D *texture, bool flipped)
{ {
TiledGrid3D *pRet= new TiledGrid3D(); TiledGrid3D *ret= new TiledGrid3D();
if (pRet) if (ret)
{ {
if (pRet->initWithSize(gridSize, texture, bFlipped)) if (ret->initWithSize(gridSize, texture, flipped))
{ {
pRet->autorelease(); ret->autorelease();
} }
else else
{ {
delete pRet; delete ret;
pRet = NULL; ret = nullptr;
} }
} }
return pRet; return ret;
} }
TiledGrid3D* TiledGrid3D::create(const Size& gridSize) TiledGrid3D* TiledGrid3D::create(const Size& gridSize)
{ {
TiledGrid3D *pRet= new TiledGrid3D(); TiledGrid3D *ret= new TiledGrid3D();
if (pRet) if (ret)
{ {
if (pRet->initWithSize(gridSize)) if (ret->initWithSize(gridSize))
{ {
pRet->autorelease(); ret->autorelease();
} }
else else
{ {
delete pRet; delete ret;
pRet = NULL; ret = nullptr;
} }
} }
return pRet; return ret;
} }
void TiledGrid3D::blit(void) void TiledGrid3D::blit(void)

View File

@ -27,7 +27,6 @@ THE SOFTWARE.
#include "CCObject.h" #include "CCObject.h"
#include "CCNode.h" #include "CCNode.h"
#include "CCCamera.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "CCTexture2D.h" #include "CCTexture2D.h"
#include "CCDirector.h" #include "CCDirector.h"
@ -62,16 +61,16 @@ public:
*/ */
virtual ~GridBase(void); virtual ~GridBase(void);
bool initWithSize(const Size& gridSize, Texture2D *texture, bool bFlipped); bool initWithSize(const Size& gridSize, Texture2D *texture, bool flipped);
bool initWithSize(const Size& gridSize); bool initWithSize(const Size& gridSize);
/** whether or not the grid is active */ /** whether or not the grid is active */
inline bool isActive(void) const { return _active; } inline bool isActive(void) const { return _active; }
void setActive(bool bActive); void setActive(bool active);
/** number of times that the grid will be reused */ /** number of times that the grid will be reused */
inline int getReuseGrid(void) const { return _reuseGrid; } inline int getReuseGrid(void) const { return _reuseGrid; }
inline void setReuseGrid(int nReuseGrid) { _reuseGrid = nReuseGrid; } inline void setReuseGrid(int reuseGrid) { _reuseGrid = reuseGrid; }
/** size of the grid */ /** size of the grid */
inline const Size& getGridSize(void) const { return _gridSize; } inline const Size& getGridSize(void) const { return _gridSize; }
@ -83,7 +82,7 @@ public:
/** is texture flipped */ /** is texture flipped */
inline bool isTextureFlipped(void) const { return _isTextureFlipped; } inline bool isTextureFlipped(void) const { return _isTextureFlipped; }
void setTextureFlipped(bool bFlipped); void setTextureFlipped(bool flipped);
void beforeDraw(void); void beforeDraw(void);
void afterDraw(Node *target); void afterDraw(Node *target);
@ -115,7 +114,7 @@ class CC_DLL Grid3D : public GridBase
{ {
public: public:
/** create one Grid */ /** create one Grid */
static Grid3D* create(const Size& gridSize, Texture2D *texture, bool bFlipped); static Grid3D* create(const Size& gridSize, Texture2D *texture, bool flipped);
/** create one Grid */ /** create one Grid */
static Grid3D* create(const Size& gridSize); static Grid3D* create(const Size& gridSize);
/** /**
@ -178,7 +177,7 @@ class CC_DLL TiledGrid3D : public GridBase
{ {
public: public:
/** create one Grid */ /** create one Grid */
static TiledGrid3D* create(const Size& gridSize, Texture2D *texture, bool bFlipped); static TiledGrid3D* create(const Size& gridSize, Texture2D *texture, bool flipped);
/** create one Grid */ /** create one Grid */
static TiledGrid3D* create(const Size& gridSize); static TiledGrid3D* create(const Size& gridSize);
/** /**

View File

@ -25,9 +25,11 @@ THE SOFTWARE.
#ifndef __CC_IME_DELEGATE_H__ #ifndef __CC_IME_DELEGATE_H__
#define __CC_IME_DELEGATE_H__ #define __CC_IME_DELEGATE_H__
#include <string>
#include "CCGeometry.h" #include "CCGeometry.h"
NS_CC_BEGIN NS_CC_BEGIN
extern const std::string STD_STRING_EMPTY;
/** /**
* @addtogroup input * @addtogroup input
@ -114,7 +116,7 @@ protected:
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual const char * getContentText() { return 0; } virtual const std::string& getContentText() { return STD_STRING_EMPTY; }
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
// keyboard show/hide notification // keyboard show/hide notification

View File

@ -78,12 +78,12 @@ public:
_delegateWithIme = 0; _delegateWithIme = 0;
} }
DelegateIter findDelegate(IMEDelegate* pDelegate) DelegateIter findDelegate(IMEDelegate* delegate)
{ {
DelegateIter end = _delegateList.end(); DelegateIter end = _delegateList.end();
for (DelegateIter iter = _delegateList.begin(); iter != end; ++iter) for (DelegateIter iter = _delegateList.begin(); iter != end; ++iter)
{ {
if (pDelegate == *iter) if (delegate == *iter)
{ {
return iter; return iter;
} }
@ -114,29 +114,29 @@ IMEDispatcher::~IMEDispatcher()
// Add/Attach/Remove IMEDelegate // Add/Attach/Remove IMEDelegate
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
void IMEDispatcher::addDelegate(IMEDelegate* pDelegate) void IMEDispatcher::addDelegate(IMEDelegate* delegate)
{ {
if (! pDelegate || ! _impl) if (! delegate || ! _impl)
{ {
return; return;
} }
if (_impl->_delegateList.end() != _impl->findDelegate(pDelegate)) if (_impl->_delegateList.end() != _impl->findDelegate(delegate))
{ {
// pDelegate already in list // pDelegate already in list
return; return;
} }
_impl->_delegateList.push_front(pDelegate); _impl->_delegateList.push_front(delegate);
} }
bool IMEDispatcher::attachDelegateWithIME(IMEDelegate * pDelegate) bool IMEDispatcher::attachDelegateWithIME(IMEDelegate * delegate)
{ {
bool bRet = false; bool ret = false;
do do
{ {
CC_BREAK_IF(! _impl || ! pDelegate); CC_BREAK_IF(! _impl || ! delegate);
DelegateIter end = _impl->_delegateList.end(); DelegateIter end = _impl->_delegateList.end();
DelegateIter iter = _impl->findDelegate(pDelegate); DelegateIter iter = _impl->findDelegate(delegate);
// if pDelegate is not in delegate list, return // if pDelegate is not in delegate list, return
CC_BREAK_IF(end == iter); CC_BREAK_IF(end == iter);
@ -147,55 +147,55 @@ bool IMEDispatcher::attachDelegateWithIME(IMEDelegate * pDelegate)
// or pDelegate canAttachWithIME return false, // or pDelegate canAttachWithIME return false,
// do nothing. // do nothing.
CC_BREAK_IF(! _impl->_delegateWithIme->canDetachWithIME() CC_BREAK_IF(! _impl->_delegateWithIme->canDetachWithIME()
|| ! pDelegate->canAttachWithIME()); || ! delegate->canAttachWithIME());
// detach first // detach first
IMEDelegate * pOldDelegate = _impl->_delegateWithIme; IMEDelegate * oldDelegate = _impl->_delegateWithIme;
_impl->_delegateWithIme = 0; _impl->_delegateWithIme = 0;
pOldDelegate->didDetachWithIME(); oldDelegate->didDetachWithIME();
_impl->_delegateWithIme = *iter; _impl->_delegateWithIme = *iter;
pDelegate->didAttachWithIME(); delegate->didAttachWithIME();
bRet = true; ret = true;
break; break;
} }
// delegate hasn't attached to IME yet // delegate hasn't attached to IME yet
CC_BREAK_IF(! pDelegate->canAttachWithIME()); CC_BREAK_IF(! delegate->canAttachWithIME());
_impl->_delegateWithIme = *iter; _impl->_delegateWithIme = *iter;
pDelegate->didAttachWithIME(); delegate->didAttachWithIME();
bRet = true; ret = true;
} while (0); } while (0);
return bRet; return ret;
} }
bool IMEDispatcher::detachDelegateWithIME(IMEDelegate * pDelegate) bool IMEDispatcher::detachDelegateWithIME(IMEDelegate * delegate)
{ {
bool bRet = false; bool ret = false;
do do
{ {
CC_BREAK_IF(! _impl || ! pDelegate); CC_BREAK_IF(! _impl || ! delegate);
// if pDelegate is not the current delegate attached to IME, return // if pDelegate is not the current delegate attached to IME, return
CC_BREAK_IF(_impl->_delegateWithIme != pDelegate); CC_BREAK_IF(_impl->_delegateWithIme != delegate);
CC_BREAK_IF(! pDelegate->canDetachWithIME()); CC_BREAK_IF(! delegate->canDetachWithIME());
_impl->_delegateWithIme = 0; _impl->_delegateWithIme = 0;
pDelegate->didDetachWithIME(); delegate->didDetachWithIME();
bRet = true; ret = true;
} while (0); } while (0);
return bRet; return ret;
} }
void IMEDispatcher::removeDelegate(IMEDelegate* pDelegate) void IMEDispatcher::removeDelegate(IMEDelegate* delegate)
{ {
do do
{ {
CC_BREAK_IF(! pDelegate || ! _impl); CC_BREAK_IF(! delegate || ! _impl);
DelegateIter iter = _impl->findDelegate(pDelegate); DelegateIter iter = _impl->findDelegate(delegate);
DelegateIter end = _impl->_delegateList.end(); DelegateIter end = _impl->_delegateList.end();
CC_BREAK_IF(end == iter); CC_BREAK_IF(end == iter);
@ -213,16 +213,16 @@ void IMEDispatcher::removeDelegate(IMEDelegate* pDelegate)
// dispatch text message // dispatch text message
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
void IMEDispatcher::dispatchInsertText(const char * pText, int nLen) void IMEDispatcher::dispatchInsertText(const char * text, int len)
{ {
do do
{ {
CC_BREAK_IF(! _impl || ! pText || nLen <= 0); CC_BREAK_IF(! _impl || ! text || len <= 0);
// there is no delegate attached to IME // there is no delegate attached to IME
CC_BREAK_IF(! _impl->_delegateWithIme); CC_BREAK_IF(! _impl->_delegateWithIme);
_impl->_delegateWithIme->insertText(pText, nLen); _impl->_delegateWithIme->insertText(text, len);
} while (0); } while (0);
} }
@ -239,14 +239,13 @@ void IMEDispatcher::dispatchDeleteBackward()
} while (0); } while (0);
} }
const char * IMEDispatcher::getContentText() const std::string& IMEDispatcher::getContentText()
{ {
const char * pszContentText = 0;
if (_impl && _impl->_delegateWithIme) if (_impl && _impl->_delegateWithIme)
{ {
pszContentText = _impl->_delegateWithIme->getContentText(); return _impl->_delegateWithIme->getContentText();
} }
return (pszContentText) ? pszContentText : ""; return STD_STRING_EMPTY;
} }
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
@ -257,14 +256,14 @@ void IMEDispatcher::dispatchKeyboardWillShow(IMEKeyboardNotificationInfo& info)
{ {
if (_impl) if (_impl)
{ {
IMEDelegate * pDelegate = 0; IMEDelegate * delegate = 0;
DelegateIter last = _impl->_delegateList.end(); DelegateIter last = _impl->_delegateList.end();
for (DelegateIter first = _impl->_delegateList.begin(); first != last; ++first) for (DelegateIter first = _impl->_delegateList.begin(); first != last; ++first)
{ {
pDelegate = *(first); delegate = *(first);
if (pDelegate) if (delegate)
{ {
pDelegate->keyboardWillShow(info); delegate->keyboardWillShow(info);
} }
} }
} }
@ -274,14 +273,14 @@ void IMEDispatcher::dispatchKeyboardDidShow(IMEKeyboardNotificationInfo& info)
{ {
if (_impl) if (_impl)
{ {
IMEDelegate * pDelegate = 0; IMEDelegate * delegate = 0;
DelegateIter last = _impl->_delegateList.end(); DelegateIter last = _impl->_delegateList.end();
for (DelegateIter first = _impl->_delegateList.begin(); first != last; ++first) for (DelegateIter first = _impl->_delegateList.begin(); first != last; ++first)
{ {
pDelegate = *(first); delegate = *(first);
if (pDelegate) if (delegate)
{ {
pDelegate->keyboardDidShow(info); delegate->keyboardDidShow(info);
} }
} }
} }
@ -291,14 +290,14 @@ void IMEDispatcher::dispatchKeyboardWillHide(IMEKeyboardNotificationInfo& info)
{ {
if (_impl) if (_impl)
{ {
IMEDelegate * pDelegate = 0; IMEDelegate * delegate = 0;
DelegateIter last = _impl->_delegateList.end(); DelegateIter last = _impl->_delegateList.end();
for (DelegateIter first = _impl->_delegateList.begin(); first != last; ++first) for (DelegateIter first = _impl->_delegateList.begin(); first != last; ++first)
{ {
pDelegate = *(first); delegate = *(first);
if (pDelegate) if (delegate)
{ {
pDelegate->keyboardWillHide(info); delegate->keyboardWillHide(info);
} }
} }
} }
@ -308,14 +307,14 @@ void IMEDispatcher::dispatchKeyboardDidHide(IMEKeyboardNotificationInfo& info)
{ {
if (_impl) if (_impl)
{ {
IMEDelegate * pDelegate = 0; IMEDelegate * delegate = 0;
DelegateIter last = _impl->_delegateList.end(); DelegateIter last = _impl->_delegateList.end();
for (DelegateIter first = _impl->_delegateList.begin(); first != last; ++first) for (DelegateIter first = _impl->_delegateList.begin(); first != last; ++first)
{ {
pDelegate = *(first); delegate = *(first);
if (pDelegate) if (delegate)
{ {
pDelegate->keyboardDidHide(info); delegate->keyboardDidHide(info);
} }
} }
} }

View File

@ -63,7 +63,7 @@ public:
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
void dispatchInsertText(const char * pText, int nLen); void dispatchInsertText(const char * text, int len);
/** /**
@brief Dispatches the delete-backward operation. @brief Dispatches the delete-backward operation.
@ -77,7 +77,7 @@ public:
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
const char * getContentText(); const std::string& getContentText();
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
// dispatch keyboard notification // dispatch keyboard notification
@ -109,20 +109,20 @@ protected:
/** /**
@brief Add delegate to receive IME messages. @brief Add delegate to receive IME messages.
*/ */
void addDelegate(IMEDelegate * pDelegate); void addDelegate(IMEDelegate * delegate);
/** /**
@brief Attach the pDelegate to the IME. @brief Attach the pDelegate to the IME.
@return If the old delegate can detach from the IME, and the new delegate @return If the old delegate can detach from the IME, and the new delegate
can attach to the IME, return true, otherwise false. can attach to the IME, return true, otherwise false.
*/ */
bool attachDelegateWithIME(IMEDelegate * pDelegate); bool attachDelegateWithIME(IMEDelegate * delegate);
bool detachDelegateWithIME(IMEDelegate * pDelegate); bool detachDelegateWithIME(IMEDelegate * delegate);
/** /**
@brief Remove the delegate from the delegates which receive IME messages. @brief Remove the delegate from the delegates which receive IME messages.
*/ */
void removeDelegate(IMEDelegate * pDelegate); void removeDelegate(IMEDelegate * delegate);
private: private:
IMEDispatcher(); IMEDispatcher();

View File

@ -27,20 +27,28 @@
#include "CCFontAtlasCache.h" #include "CCFontAtlasCache.h"
#include "CCLabelTextFormatter.h" #include "CCLabelTextFormatter.h"
#define DISTANCEFIELD_ATLAS_FONTSIZE 50
NS_CC_BEGIN NS_CC_BEGIN
Label* Label::createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs ) Label* Label::createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs, bool useDistanceField)
{ {
FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), fontSize, glyphs, customGlyphs); FontAtlas *tmpAtlas = nullptr;
if(useDistanceField)
tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), DISTANCEFIELD_ATLAS_FONTSIZE, glyphs, customGlyphs,true);
else
tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), fontSize, glyphs, customGlyphs,false);
if (!tmpAtlas) if (!tmpAtlas)
return nullptr; return nullptr;
// create the actual label // create the actual label
Label* templabel = Label::createWithAtlas(tmpAtlas, alignment, lineSize); Label* templabel = Label::createWithAtlas(tmpAtlas, alignment, lineSize, useDistanceField,true);
if (templabel) if (templabel)
{ {
if(useDistanceField)
templabel->setFontSize(fontSize);
templabel->setText(label, lineSize, alignment, false); templabel->setText(label, lineSize, alignment, false);
return templabel; return templabel;
} }
@ -71,9 +79,9 @@ Label* Label::createWithBMFont(const std::string& label, const std::string& bmfo
return 0; return 0;
} }
Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int lineSize) Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int lineSize, bool useDistanceField,bool useA8Shader)
{ {
Label *ret = new Label(atlas, alignment); Label *ret = new Label(atlas, alignment, useDistanceField,useA8Shader);
if (!ret) if (!ret)
return 0; return 0;
@ -92,21 +100,22 @@ Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int li
return ret; return ret;
} }
Label::Label(FontAtlas *atlas, TextHAlignment alignment) Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,bool useA8Shader)
: _reusedLetter(nullptr) : _reusedLetter(nullptr)
, _multilineEnable(true)
, _commonLineHeight(0.0f)
, _lineBreakWithoutSpaces(false) , _lineBreakWithoutSpaces(false)
, _width(0.0f)
, _alignment(alignment) , _alignment(alignment)
, _currentUTF16String(0) , _currentUTF16String(0)
, _originalUTF16String(0) , _originalUTF16String(0)
, _advances(0) , _advances(nullptr)
, _fontAtlas(atlas) , _fontAtlas(atlas)
, _displayedColor(Color3B::WHITE)
, _realColor(Color3B::WHITE)
, _cascadeColorEnabled(true)
, _cascadeOpacityEnabled(true)
, _displayedOpacity(255)
, _realOpacity(255)
, _isOpacityModifyRGB(true) , _isOpacityModifyRGB(true)
, _useDistanceField(useDistanceField)
, _useA8Shader(useA8Shader)
, _fontSize(0)
, _uniformEffectColor(0)
{ {
} }
@ -124,19 +133,31 @@ Label::~Label()
bool Label::init() bool Label::init()
{ {
bool ret = true;
if(_fontAtlas) if(_fontAtlas)
{ {
_reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0)); _reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0));
_reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB); _reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB);
ret = SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30);
_reusedLetter->retain(); _reusedLetter->retain();
return SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30);
} }
if (_useDistanceField)
setLabelEffect(LabelEffect::NORMAL,Color3B::BLACK);
else if(_useA8Shader)
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR));
return true; return ret;
} }
void Label::setString(const std::string &stringToRender) void Label::setString(const std::string &stringToRender)
{ {
_multilineEnable = true;
setText(stringToRender, _width, TextHAlignment::CENTER, false);
}
void Label::setString(const std::string &stringToRender,bool multilineEnable)
{
_multilineEnable = multilineEnable;
setText(stringToRender, _width, TextHAlignment::CENTER, false); setText(stringToRender, _width, TextHAlignment::CENTER, false);
} }
@ -221,20 +242,53 @@ void Label::setLineBreakWithoutSpace(bool breakWithoutSpace)
void Label::setScale(float scale) void Label::setScale(float scale)
{ {
if (_useDistanceField)
{
scale *= 1.0f * _fontSize / DISTANCEFIELD_ATLAS_FONTSIZE;
}
Node::setScale(scale); Node::setScale(scale);
alignText();
} }
void Label::setScaleX(float scaleX) void Label::setScaleX(float scaleX)
{ {
if (_useDistanceField)
{
scaleX *= 1.0f * _fontSize / DISTANCEFIELD_ATLAS_FONTSIZE;
}
Node::setScaleX(scaleX); Node::setScaleX(scaleX);
alignText();
} }
void Label::setScaleY(float scaleY) void Label::setScaleY(float scaleY)
{ {
if (_useDistanceField)
{
scaleY *= 1.0f * _fontSize / DISTANCEFIELD_ATLAS_FONTSIZE;
}
Node::setScaleY(scaleY); Node::setScaleY(scaleY);
alignText(); }
float Label::getScaleY() const
{
if (_useDistanceField)
{
return _scaleY / (1.0f * _fontSize / DISTANCEFIELD_ATLAS_FONTSIZE);
}
else
{
return _scaleY;
}
}
float Label::getScaleX() const
{
if (_useDistanceField)
{
return _scaleX / (1.0f * _fontSize / DISTANCEFIELD_ATLAS_FONTSIZE);
}
else
{
return _scaleX;
}
} }
void Label::alignText() void Label::alignText()
@ -243,22 +297,18 @@ void Label::alignText()
_textureAtlas->removeAllQuads(); _textureAtlas->removeAllQuads();
_fontAtlas->prepareLetterDefinitions(_currentUTF16String); _fontAtlas->prepareLetterDefinitions(_currentUTF16String);
LabelTextFormatter::createStringSprites(this); LabelTextFormatter::createStringSprites(this);
if( LabelTextFormatter::multilineText(this) ) if(_multilineEnable && LabelTextFormatter::multilineText(this) )
LabelTextFormatter::createStringSprites(this); LabelTextFormatter::createStringSprites(this);
LabelTextFormatter::alignText(this); LabelTextFormatter::alignText(this);
int strLen = cc_wcslen(_currentUTF16String); int strLen = cc_wcslen(_currentUTF16String);
for(const auto &child : _children) {
_children.forEach([this, &strLen](Node* child){ int tag = child->getTag();
if (child) if(tag < 0 || tag >= strLen)
{ SpriteBatchNode::removeChild(child, true);
int tag = child->getTag(); }
if(tag < 0 || tag >= strLen)
SpriteBatchNode::removeChild(child, true);
}
});
_reusedLetter->setBatchNode(nullptr); _reusedLetter->setBatchNode(nullptr);
int vaildIndex = 0; int vaildIndex = 0;
@ -415,6 +465,68 @@ void Label::addChild(Node * child, int zOrder/* =0 */, int tag/* =0 */)
CCASSERT(0, "addChild: is not supported on Label."); CCASSERT(0, "addChild: is not supported on Label.");
} }
void Label::setLabelEffect(LabelEffect effect,const Color3B& effectColor)
{
if(_useDistanceField == false)
return;
_currLabelEffect = effect;
_effectColor = effectColor;
switch (_currLabelEffect)
{
case cocos2d::LabelEffect::NORMAL:
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_NORMAL));
break;
case cocos2d::LabelEffect::OUTLINE:
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_OUTLINE));
break;
case cocos2d::LabelEffect::SHADOW:
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_SHADOW));
break;
case cocos2d::LabelEffect::GLOW:
setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_LABEL_DISTANCEFIELD_GLOW));
break;
default:
return;
}
_uniformEffectColor = glGetUniformLocation(_shaderProgram->getProgram(), "v_effectColor");
}
void Label::setFontSize(int fontSize)
{
_fontSize = fontSize;
Node::setScale(1.0f*_fontSize/DISTANCEFIELD_ATLAS_FONTSIZE);
}
void Label::draw()
{
CC_PROFILER_START("CCSpriteBatchNode - draw");
// Optimization: Fast Dispatch
if( _textureAtlas->getTotalQuads() == 0 )
{
return;
}
CC_NODE_DRAW_SETUP();
if (_useDistanceField && _currLabelEffect != LabelEffect::NORMAL)
{
_shaderProgram->setUniformLocationWith3f(_uniformEffectColor, _effectColor.r/255.0f,_effectColor.g/255.0f,_effectColor.b/255.0f);
}
for(const auto &child: _children)
child->updateTransform();
GL::blendFunc( _blendFunc.src, _blendFunc.dst );
_textureAtlas->drawQuads();
CC_PROFILER_STOP("CCSpriteBatchNode - draw");
}
///// PROTOCOL STUFF ///// PROTOCOL STUFF
Sprite * Label::getLetter(int ID) Sprite * Label::getLetter(int ID)
@ -434,7 +546,7 @@ Sprite * Label::getLetter(int ID)
uvRect.origin.x = _lettersInfo[ID].def.U; uvRect.origin.x = _lettersInfo[ID].def.U;
uvRect.origin.y = _lettersInfo[ID].def.V; uvRect.origin.y = _lettersInfo[ID].def.V;
sp = Sprite::createWithTexture(&_fontAtlas->getTexture(_lettersInfo[ID].def.textureID), uvRect); sp = Sprite::createWithTexture(&_fontAtlas->getTexture(_lettersInfo[ID].def.textureID),uvRect);
sp->setBatchNode(this); sp->setBatchNode(this);
sp->setAnchorPoint(Point(_lettersInfo[ID].def.anchorX, _lettersInfo[ID].def.anchorY)); sp->setAnchorPoint(Point(_lettersInfo[ID].def.anchorX, _lettersInfo[ID].def.anchorY));
sp->setPosition(_lettersInfo[ID].position); sp->setPosition(_lettersInfo[ID].position);
@ -592,123 +704,25 @@ void Label::setOpacityModifyRGB(bool isOpacityModifyRGB)
{ {
_isOpacityModifyRGB = isOpacityModifyRGB; _isOpacityModifyRGB = isOpacityModifyRGB;
_children.forEach([this](Node* child){ for(const auto& child: _children) {
if (child) child->setOpacityModifyRGB(_isOpacityModifyRGB);
{ }
RGBAProtocol *pRGBAProtocol = dynamic_cast<RGBAProtocol*>(child);
if (pRGBAProtocol)
{
pRGBAProtocol->setOpacityModifyRGB(_isOpacityModifyRGB);
}
}
});
_reusedLetter->setOpacityModifyRGB(true); _reusedLetter->setOpacityModifyRGB(true);
} }
unsigned char Label::getOpacity() const
{
return _realOpacity;
}
unsigned char Label::getDisplayedOpacity() const
{
return _displayedOpacity;
}
void Label::setOpacity(GLubyte opacity)
{
_displayedOpacity = _realOpacity = opacity;
_reusedLetter->setOpacity(opacity);
if( _cascadeOpacityEnabled ) {
GLubyte parentOpacity = 255;
RGBAProtocol* pParent = dynamic_cast<RGBAProtocol*>(_parent);
if (pParent && pParent->isCascadeOpacityEnabled())
{
parentOpacity = pParent->getDisplayedOpacity();
}
this->updateDisplayedOpacity(parentOpacity);
}
}
void Label::updateDisplayedOpacity(GLubyte parentOpacity)
{
_displayedOpacity = _realOpacity * parentOpacity/255.0;
_children.forEach([this](Node* child){
Sprite *item = static_cast<Sprite*>( child );
item->updateDisplayedOpacity(_displayedOpacity);
});
V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads();
auto count = _textureAtlas->getTotalQuads();
Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity );
if (_isOpacityModifyRGB)
{
color4.r *= _displayedOpacity/255.0f;
color4.g *= _displayedOpacity/255.0f;
color4.b *= _displayedOpacity/255.0f;
}
for (int index = 0; index < count; ++index)
{
quads[index].bl.colors = color4;
quads[index].br.colors = color4;
quads[index].tl.colors = color4;
quads[index].tr.colors = color4;
_textureAtlas->updateQuad(&quads[index], index);
}
}
bool Label::isCascadeOpacityEnabled() const
{
return false;
}
void Label::setCascadeOpacityEnabled(bool cascadeOpacityEnabled)
{
_cascadeOpacityEnabled = cascadeOpacityEnabled;
}
const Color3B& Label::getColor(void) const
{
return _realColor;
}
const Color3B& Label::getDisplayedColor() const
{
return _displayedColor;
}
void Label::setColor(const Color3B& color) void Label::setColor(const Color3B& color)
{ {
_displayedColor = _realColor = color;
_reusedLetter->setColor(color); _reusedLetter->setColor(color);
if( _cascadeColorEnabled ) SpriteBatchNode::setColor(color);
{
Color3B parentColor = Color3B::WHITE;
RGBAProtocol* pParent = dynamic_cast<RGBAProtocol*>(_parent);
if (pParent && pParent->isCascadeColorEnabled())
parentColor = pParent->getDisplayedColor();
updateDisplayedColor(parentColor);
}
} }
void Label::updateDisplayedColor(const Color3B& parentColor) void Label::updateColor()
{ {
_displayedColor.r = _realColor.r * parentColor.r/255.0;
_displayedColor.g = _realColor.g * parentColor.g/255.0;
_displayedColor.b = _realColor.b * parentColor.b/255.0;
_children.forEach([this](Node* child){
Sprite *item = static_cast<Sprite*>( child );
item->updateDisplayedColor(_displayedColor);
});
V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads(); V3F_C4B_T2F_Quad *quads = _textureAtlas->getQuads();
auto count = _textureAtlas->getTotalQuads(); auto count = _textureAtlas->getTotalQuads();
Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity ); Color4B color4( _displayedColor.r, _displayedColor.g, _displayedColor.b, _displayedOpacity );
// special opacity for premultiplied textures // special opacity for premultiplied textures
if (_isOpacityModifyRGB) if (_isOpacityModifyRGB)
{ {
@ -717,29 +731,19 @@ void Label::updateDisplayedColor(const Color3B& parentColor)
color4.b *= _displayedOpacity/255.0f; color4.b *= _displayedOpacity/255.0f;
} }
for (int index=0; index<count; ++index) for (int index=0; index<count; ++index)
{ {
quads[index].bl.colors = color4; quads[index].bl.colors = color4;
quads[index].br.colors = color4; quads[index].br.colors = color4;
quads[index].tl.colors = color4; quads[index].tl.colors = color4;
quads[index].tr.colors = color4; quads[index].tr.colors = color4;
_textureAtlas->updateQuad(&quads[index], index); _textureAtlas->updateQuad(&quads[index], index);
} }
}
bool Label::isCascadeColorEnabled() const
{
return false;
}
void Label::setCascadeColorEnabled(bool cascadeColorEnabled)
{
_cascadeColorEnabled = cascadeColorEnabled;
} }
std::string Label::getDescription() const std::string Label::getDescription() const
{ {
return StringUtils::format("<Label | Tag = %d, Label = '%s'>", _tag, cc_utf16_to_utf8(_currentUTF16String,-1,NULL,NULL)); return StringUtils::format("<Label | Tag = %d, Label = '%s'>", _tag, cc_utf16_to_utf8(_currentUTF16String,-1,nullptr,nullptr));
} }
NS_CC_END NS_CC_END

View File

@ -40,46 +40,47 @@ enum class GlyphCollection {
CUSTOM CUSTOM
}; };
enum class LabelEffect {
NORMAL,
OUTLINE,
SHADOW,
GLOW
};
//fwd //fwd
struct FontLetterDefinition; struct FontLetterDefinition;
class FontAtlas; class FontAtlas;
class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public RGBAProtocol, public LabelTextFormatProtocol class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public LabelTextFormatProtocol
{ {
public: public:
// static create // static create
static Label* createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0); static Label* createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0, bool useDistanceField = false);
static Label* createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment = TextHAlignment::CENTER, int lineSize = 0); static Label* createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment = TextHAlignment::CENTER, int lineSize = 0);
bool setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false); bool setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false);
void setLabelEffect(LabelEffect effect,const Color3B& effectColor);
virtual void setString(const std::string &stringToRender) override; virtual void setString(const std::string &stringToRender) override;
void setString(const std::string &stringToRender,bool multilineEnable);
virtual void setAlignment(TextHAlignment alignment); virtual void setAlignment(TextHAlignment alignment);
virtual void setWidth(float width); virtual void setWidth(float width);
virtual void setLineBreakWithoutSpace(bool breakWithoutSpace); virtual void setLineBreakWithoutSpace(bool breakWithoutSpace);
virtual void setScale(float scale) override; virtual void setScale(float scale) override;
virtual void setScaleX(float scaleX) override; virtual void setScaleX(float scaleX) override;
virtual void setScaleY(float scaleY) override; virtual void setScaleY(float scaleY) override;
virtual float getScaleX() const;
virtual float getScaleY() const;
// RGBAProtocol
virtual bool isOpacityModifyRGB() const override; virtual bool isOpacityModifyRGB() const override;
virtual void setOpacityModifyRGB(bool isOpacityModifyRGB) override; virtual void setOpacityModifyRGB(bool isOpacityModifyRGB) override;
virtual void setOpacity(GLubyte opacity) override;
virtual void updateDisplayedOpacity(GLubyte parentOpacity) override;
virtual bool isCascadeOpacityEnabled() const override;
virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled) override;
virtual void setColor(const Color3B& color) override; virtual void setColor(const Color3B& color) override;
virtual void updateDisplayedColor(const Color3B& parentColor) override;
virtual bool isCascadeColorEnabled() const override;
virtual void setCascadeColorEnabled(bool cascadeColorEnabled) override;
virtual const Color3B& getColor(void) const override;
virtual const Color3B& getDisplayedColor() const override;
virtual unsigned char getOpacity() const override;
virtual unsigned char getDisplayedOpacity() const override;
// CCLabelTextFormat protocol implementation // CCLabelTextFormat protocol implementation
virtual std::vector<LetterInfo> *getLettersInfo() override { return &_lettersInfo; }; virtual std::vector<LetterInfo> *getLettersInfo() override { return &_lettersInfo; };
@ -117,19 +118,22 @@ public:
void addChild(Node * child, int zOrder=0, int tag=0) override; void addChild(Node * child, int zOrder=0, int tag=0) override;
virtual std::string getDescription() const override; virtual std::string getDescription() const override;
virtual void draw(void) override;
private: private:
/** /**
* @js NA * @js NA
*/ */
Label(FontAtlas *atlas, TextHAlignment alignment); Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField = false,bool useA8Shader = false);
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
~Label(); ~Label();
static Label* createWithAtlas(FontAtlas *atlas, TextHAlignment alignment = TextHAlignment::LEFT, int lineSize = 0); static Label* createWithAtlas(FontAtlas *atlas, TextHAlignment alignment = TextHAlignment::LEFT, int lineSize = 0, bool useDistanceField = false,bool useA8Shader = false);
void setFontSize(int fontSize);
bool init(); bool init();
@ -139,14 +143,17 @@ private:
bool setCurrentString(unsigned short *stringToSet); bool setCurrentString(unsigned short *stringToSet);
bool setOriginalString(unsigned short *stringToSet); bool setOriginalString(unsigned short *stringToSet);
void resetCurrentString(); void resetCurrentString();
Sprite * updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, const FontLetterDefinition &theDefinition, Texture2D *theTexture); Sprite * updateSpriteWithLetterDefinition(Sprite *spriteToUpdate, const FontLetterDefinition &theDefinition, Texture2D *theTexture);
virtual void updateColor() override;
//! used for optimization //! used for optimization
Sprite *_reusedLetter; Sprite *_reusedLetter;
std::vector<LetterInfo> _lettersInfo; std::vector<LetterInfo> _lettersInfo;
bool _multilineEnable;
float _commonLineHeight; float _commonLineHeight;
bool _lineBreakWithoutSpaces; bool _lineBreakWithoutSpaces;
float _width; float _width;
@ -155,14 +162,16 @@ private:
unsigned short int * _originalUTF16String; unsigned short int * _originalUTF16String;
Size * _advances; Size * _advances;
FontAtlas * _fontAtlas; FontAtlas * _fontAtlas;
Color3B _displayedColor;
Color3B _realColor;
bool _cascadeColorEnabled;
bool _cascadeOpacityEnabled;
unsigned char _displayedOpacity;
unsigned char _realOpacity;
bool _isOpacityModifyRGB; bool _isOpacityModifyRGB;
bool _useDistanceField;
bool _useA8Shader;
int _fontSize;
LabelEffect _currLabelEffect;
Color3B _effectColor;
GLuint _uniformEffectColor;
}; };

View File

@ -51,7 +51,7 @@ LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& cha
return pRet; return pRet;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(pRet);
return NULL; return nullptr;
} }
bool LabelAtlas::initWithString(const std::string& string, const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) bool LabelAtlas::initWithString(const std::string& string, const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap)
@ -113,7 +113,7 @@ bool LabelAtlas::initWithString(const std::string& theString, const std::string&
//CCLabelAtlas - Atlas generation //CCLabelAtlas - Atlas generation
void LabelAtlas::updateAtlasValues() void LabelAtlas::updateAtlasValues()
{ {
auto n = _string.length(); ssize_t n = _string.length();
const unsigned char *s = (unsigned char*)_string.c_str(); const unsigned char *s = (unsigned char*)_string.c_str();
@ -130,7 +130,7 @@ void LabelAtlas::updateAtlasValues()
CCASSERT(n <= _textureAtlas->getCapacity(), "updateAtlasValues: Invalid String length"); CCASSERT(n <= _textureAtlas->getCapacity(), "updateAtlasValues: Invalid String length");
V3F_C4B_T2F_Quad* quads = _textureAtlas->getQuads(); V3F_C4B_T2F_Quad* quads = _textureAtlas->getQuads();
for(int i = 0; i < n; i++) { for(ssize_t i = 0; i < n; i++) {
unsigned char a = s[i] - _mapStartChar; unsigned char a = s[i] - _mapStartChar;
float row = (float) (a % _itemsPerRow); float row = (float) (a % _itemsPerRow);
@ -178,7 +178,7 @@ void LabelAtlas::updateAtlasValues()
} }
if (n > 0 ){ if (n > 0 ){
_textureAtlas->setDirty(true); _textureAtlas->setDirty(true);
auto totalQuads = _textureAtlas->getTotalQuads(); ssize_t totalQuads = _textureAtlas->getTotalQuads();
if (n > totalQuads) { if (n > totalQuads) {
_textureAtlas->increaseTotalQuadsWith(static_cast<int>(n - totalQuads)); _textureAtlas->increaseTotalQuadsWith(static_cast<int>(n - totalQuads));
} }
@ -188,10 +188,10 @@ void LabelAtlas::updateAtlasValues()
//CCLabelAtlas - LabelProtocol //CCLabelAtlas - LabelProtocol
void LabelAtlas::setString(const std::string &label) void LabelAtlas::setString(const std::string &label)
{ {
auto len = label.size(); ssize_t len = label.size();
if (len > _textureAtlas->getTotalQuads()) if (len > _textureAtlas->getTotalQuads())
{ {
_textureAtlas->resizeCapacity(static_cast<int>(len)); _textureAtlas->resizeCapacity(len);
} }
_string.clear(); _string.clear();
_string = label; _string = label;
@ -201,7 +201,7 @@ void LabelAtlas::setString(const std::string &label)
this->setContentSize(s); this->setContentSize(s);
_quadsToDraw = static_cast<int>(len); _quadsToDraw = len;
} }
const std::string& LabelAtlas::getString(void) const const std::string& LabelAtlas::getString(void) const

View File

@ -65,7 +65,7 @@ static Map<std::string, CCBMFontConfiguration*>* s_configurations = nullptr;
CCBMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile) CCBMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile)
{ {
CCBMFontConfiguration* ret = NULL; CCBMFontConfiguration* ret = nullptr;
if( s_configurations == nullptr ) if( s_configurations == nullptr )
{ {
@ -73,7 +73,7 @@ CCBMFontConfiguration* FNTConfigLoadFile(const std::string& fntFile)
} }
ret = s_configurations->at(fntFile); ret = s_configurations->at(fntFile);
if( ret == NULL ) if( ret == nullptr )
{ {
ret = CCBMFontConfiguration::create(fntFile.c_str()); ret = CCBMFontConfiguration::create(fntFile.c_str());
if (ret) if (ret)
@ -107,13 +107,13 @@ CCBMFontConfiguration * CCBMFontConfiguration::create(const std::string& FNTfile
return ret; return ret;
} }
CC_SAFE_DELETE(ret); CC_SAFE_DELETE(ret);
return NULL; return nullptr;
} }
bool CCBMFontConfiguration::initWithFNTfile(const std::string& FNTfile) bool CCBMFontConfiguration::initWithFNTfile(const std::string& FNTfile)
{ {
_kerningDictionary = NULL; _kerningDictionary = nullptr;
_fontDefDictionary = NULL; _fontDefDictionary = nullptr;
_characterSet = this->parseConfigFile(FNTfile); _characterSet = this->parseConfigFile(FNTfile);
@ -131,10 +131,10 @@ std::set<unsigned int>* CCBMFontConfiguration::getCharacterSet() const
} }
CCBMFontConfiguration::CCBMFontConfiguration() CCBMFontConfiguration::CCBMFontConfiguration()
: _fontDefDictionary(NULL) : _fontDefDictionary(nullptr)
, _commonHeight(0) , _commonHeight(0)
, _kerningDictionary(NULL) , _kerningDictionary(nullptr)
, _characterSet(NULL) , _characterSet(nullptr)
{ {
} }
@ -183,22 +183,28 @@ void CCBMFontConfiguration::purgeFontDefDictionary()
std::set<unsigned int>* CCBMFontConfiguration::parseConfigFile(const std::string& controlFile) std::set<unsigned int>* CCBMFontConfiguration::parseConfigFile(const std::string& controlFile)
{ {
std::string fullpath = FileUtils::getInstance()->fullPathForFilename(controlFile); std::string fullpath = FileUtils::getInstance()->fullPathForFilename(controlFile);
String *contents = String::createWithContentsOfFile(fullpath.c_str());
CCASSERT(contents, "CCBMFontConfiguration::parseConfigFile | Open file error."); Data data = FileUtils::getInstance()->getDataFromFile(fullpath);
CCASSERT((!data.isNull() && data.getSize() > 0), "CCBMFontConfiguration::parseConfigFile | Open file error.");
set<unsigned int> *validCharsString = new set<unsigned int>();
if (!contents) if (memcmp("BMF", data.getBytes(), 3) == 0) {
std::set<unsigned int>* ret = parseBinaryConfigFile(data.getBytes(), data.getSize(), controlFile);
return ret;
}
std::string contents((const char*)data.getBytes(), data.getSize());
std::set<unsigned int> *validCharsString = new std::set<unsigned int>();
if (contents.empty())
{ {
CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str()); CCLOG("cocos2d: Error parsing FNTfile %s", controlFile.c_str());
return NULL; return nullptr;
} }
// parse spacing / padding // parse spacing / padding
std::string line; std::string line;
std::string strLeft = contents->getCString(); std::string strLeft(contents);
while (strLeft.length() > 0) while (strLeft.length() > 0)
{ {
size_t pos = strLeft.find('\n'); size_t pos = strLeft.find('\n');
@ -260,6 +266,167 @@ std::set<unsigned int>* CCBMFontConfiguration::parseConfigFile(const std::string
return validCharsString; return validCharsString;
} }
std::set<unsigned int>* CCBMFontConfiguration::parseBinaryConfigFile(unsigned char* pData, unsigned long size, const std::string& controlFile)
{
/* based on http://www.angelcode.com/products/bmfont/doc/file_format.html file format */
set<unsigned int> *validCharsString = new set<unsigned int>();
unsigned long remains = size;
unsigned char version = pData[3];
CCASSERT(version == 3, "Only version 3 is supported");
pData += 4; remains -= 4;
while (remains > 0)
{
unsigned char blockId = pData[0]; pData += 1; remains -= 1;
uint32_t blockSize = 0; memcpy(&blockSize, pData, 4);
pData += 4; remains -= 4;
if (blockId == 1)
{
/*
fontSize 2 int 0
bitField 1 bits 2 bit 0: smooth, bit 1: unicode, bit 2: italic, bit 3: bold, bit 4: fixedHeigth, bits 5-7: reserved
charSet 1 uint 3
stretchH 2 uint 4
aa 1 uint 6
paddingUp 1 uint 7
paddingRight 1 uint 8
paddingDown 1 uint 9
paddingLeft 1 uint 10
spacingHoriz 1 uint 11
spacingVert 1 uint 12
outline 1 uint 13 added with version 2
fontName n+1 string 14 null terminated string with length n
*/
_padding.top = (unsigned char)pData[7];
_padding.right = (unsigned char)pData[8];
_padding.bottom = (unsigned char)pData[9];
_padding.left = (unsigned char)pData[10];
}
else if (blockId == 2)
{
/*
lineHeight 2 uint 0
base 2 uint 2
scaleW 2 uint 4
scaleH 2 uint 6
pages 2 uint 8
bitField 1 bits 10 bits 0-6: reserved, bit 7: packed
alphaChnl 1 uint 11
redChnl 1 uint 12
greenChnl 1 uint 13
blueChnl 1 uint 14
*/
uint16_t lineHeight = 0; memcpy(&lineHeight, pData, 2);
_commonHeight = lineHeight;
uint16_t scaleW = 0; memcpy(&scaleW, pData + 4, 2);
uint16_t scaleH = 0; memcpy(&scaleH, pData + 6, 2);
CCASSERT(scaleW <= Configuration::getInstance()->getMaxTextureSize() && scaleH <= Configuration::getInstance()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported");
uint16_t pages = 0; memcpy(&pages, pData + 8, 2);
CCASSERT(pages == 1, "CCBitfontAtlas: only supports 1 page");
}
else if (blockId == 3)
{
/*
pageNames p*(n+1) strings 0 p null terminated strings, each with length n
*/
const char *value = (const char *)pData;
size_t len = strlen(value);
CCASSERT(len < blockSize, "Block size should be less then string");
_atlasName = FileUtils::getInstance()->fullPathFromRelativeFile(value, controlFile);
}
else if (blockId == 4)
{
/*
id 4 uint 0+c*20 These fields are repeated until all characters have been described
x 2 uint 4+c*20
y 2 uint 6+c*20
width 2 uint 8+c*20
height 2 uint 10+c*20
xoffset 2 int 12+c*20
yoffset 2 int 14+c*20
xadvance 2 int 16+c*20
page 1 uint 18+c*20
chnl 1 uint 19+c*20
*/
unsigned long count = blockSize / 20;
for (unsigned long i = 0; i < count; i++)
{
tFontDefHashElement* element = (tFontDefHashElement*)malloc( sizeof(*element) );
uint32_t charId = 0; memcpy(&charId, pData + (i * 20), 4);
element->fontDef.charID = charId;
uint16_t charX = 0; memcpy(&charX, pData + (i * 20) + 4, 2);
element->fontDef.rect.origin.x = charX;
uint16_t charY = 0; memcpy(&charY, pData + (i * 20) + 6, 2);
element->fontDef.rect.origin.y = charY;
uint16_t charWidth = 0; memcpy(&charWidth, pData + (i * 20) + 8, 2);
element->fontDef.rect.size.width = charWidth;
uint16_t charHeight = 0; memcpy(&charHeight, pData + (i * 20) + 10, 2);
element->fontDef.rect.size.height = charHeight;
int16_t xoffset = 0; memcpy(&xoffset, pData + (i * 20) + 12, 2);
element->fontDef.xOffset = xoffset;
int16_t yoffset = 0; memcpy(&yoffset, pData + (i * 20) + 14, 2);
element->fontDef.yOffset = yoffset;
int16_t xadvance = 0; memcpy(&xadvance, pData + (i * 20) + 16, 2);
element->fontDef.xAdvance = xadvance;
element->key = element->fontDef.charID;
HASH_ADD_INT(_fontDefDictionary, key, element);
validCharsString->insert(element->fontDef.charID);
}
}
else if (blockId == 5) {
/*
first 4 uint 0+c*10 These fields are repeated until all kerning pairs have been described
second 4 uint 4+c*10
amount 2 int 8+c*10
*/
unsigned long count = blockSize / 20;
for (unsigned long i = 0; i < count; i++)
{
uint32_t first = 0; memcpy(&first, pData + (i * 10), 4);
uint32_t second = 0; memcpy(&second, pData + (i * 10) + 4, 4);
int16_t amount = 0; memcpy(&amount, pData + (i * 10) + 8, 2);
tKerningHashElement *element = (tKerningHashElement *)calloc( sizeof( *element ), 1 );
element->amount = amount;
element->key = (first<<16) | (second&0xffff);
HASH_ADD_INT(_kerningDictionary,key, element);
}
}
pData += blockSize; remains -= blockSize;
}
return validCharsString;
}
void CCBMFontConfiguration::parseImageFileName(std::string line, const std::string& fntFile) void CCBMFontConfiguration::parseImageFileName(std::string line, const std::string& fntFile)
{ {
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
@ -429,7 +596,7 @@ LabelBMFont * LabelBMFont::create()
return pRet; return pRet;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(pRet);
return NULL; return nullptr;
} }
LabelBMFont * LabelBMFont::create(const std::string& str, const std::string& fntFile, float width, TextHAlignment alignment) LabelBMFont * LabelBMFont::create(const std::string& str, const std::string& fntFile, float width, TextHAlignment alignment)
@ -450,14 +617,14 @@ LabelBMFont * LabelBMFont::create(const std::string& str, const std::string& fnt
//LabelBMFont - Creation & Init //LabelBMFont - Creation & Init
LabelBMFont *LabelBMFont::create(const std::string& str, const std::string& fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/) LabelBMFont *LabelBMFont::create(const std::string& str, const std::string& fntFile, float width/* = kLabelAutomaticWidth*/, TextHAlignment alignment/* = TextHAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/)
{ {
LabelBMFont *pRet = new LabelBMFont(); LabelBMFont *ret = new LabelBMFont();
if(pRet && pRet->initWithString(str, fntFile, width, alignment, imageOffset)) if(ret && ret->initWithString(str, fntFile, width, alignment, imageOffset))
{ {
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return nullptr;
} }
bool LabelBMFont::init() bool LabelBMFont::init()
@ -469,7 +636,7 @@ bool LabelBMFont::initWithString(const std::string& theString, const std::string
{ {
CCASSERT(!_configuration, "re-init is no longer supported"); CCASSERT(!_configuration, "re-init is no longer supported");
Texture2D *texture = NULL; Texture2D *texture = nullptr;
if (fntFile.size() > 0 ) if (fntFile.size() > 0 )
{ {
@ -524,20 +691,14 @@ bool LabelBMFont::initWithString(const std::string& theString, const std::string
} }
LabelBMFont::LabelBMFont() LabelBMFont::LabelBMFont()
: _string(NULL) : _string(nullptr)
, _initialString(NULL) , _initialString(nullptr)
, _alignment(TextHAlignment::CENTER) , _alignment(TextHAlignment::CENTER)
, _width(-1.0f) , _width(-1.0f)
, _configuration(NULL) , _configuration(nullptr)
, _lineBreakWithoutSpaces(false) , _lineBreakWithoutSpaces(false)
, _imageOffset(Point::ZERO) , _imageOffset(Point::ZERO)
, _reusedChar(NULL) , _reusedChar(nullptr)
, _displayedOpacity(255)
, _realOpacity(255)
, _displayedColor(Color3B::WHITE)
, _realColor(Color3B::WHITE)
, _cascadeColorEnabled(true)
, _cascadeOpacityEnabled(true)
, _isOpacityModifyRGB(false) , _isOpacityModifyRGB(false)
{ {
@ -558,7 +719,7 @@ int LabelBMFont::kerningAmountForFirst(unsigned short first, unsigned short seco
unsigned int key = (first<<16) | (second & 0xffff); unsigned int key = (first<<16) | (second & 0xffff);
if( _configuration->_kerningDictionary ) { if( _configuration->_kerningDictionary ) {
tKerningHashElement *element = NULL; tKerningHashElement *element = nullptr;
HASH_FIND_INT(_configuration->_kerningDictionary, &key, element); HASH_FIND_INT(_configuration->_kerningDictionary, &key, element);
if(element) if(element)
ret = element->amount; ret = element->amount;
@ -621,7 +782,7 @@ void LabelBMFont::createFontChars()
kerningAmount = this->kerningAmountForFirst(prev, c); kerningAmount = this->kerningAmountForFirst(prev, c);
tFontDefHashElement *element = NULL; tFontDefHashElement *element = nullptr;
// unichar is a short, and an int is needed on HASH_FIND_INT // unichar is a short, and an int is needed on HASH_FIND_INT
unsigned int key = c; unsigned int key = c;
@ -659,7 +820,7 @@ void LabelBMFont::createFontChars()
Ideal for big labels. Ideal for big labels.
*/ */
fontChar = _reusedChar; fontChar = _reusedChar;
fontChar->setBatchNode(NULL); fontChar->setBatchNode(nullptr);
hasSprite = false; hasSprite = false;
} }
else else
@ -747,9 +908,8 @@ void LabelBMFont::setString(unsigned short *newString, bool needUpdateLabel)
CC_SAFE_DELETE_ARRAY(tmp); CC_SAFE_DELETE_ARRAY(tmp);
} }
_children.forEach([](Node* child){ for(const auto &child : _children)
child->setVisible(false); child->setVisible(false);
});
this->createFontChars(); this->createFontChars();
@ -768,119 +928,20 @@ void LabelBMFont::setCString(const char *label)
setString(label); setString(label);
} }
//LabelBMFont - RGBAProtocol protocol
const Color3B& LabelBMFont::getColor() const
{
return _realColor;
}
const Color3B& LabelBMFont::getDisplayedColor() const
{
return _displayedColor;
}
void LabelBMFont::setColor(const Color3B& color)
{
_displayedColor = _realColor = color;
if( _cascadeColorEnabled ) {
Color3B parentColor = Color3B::WHITE;
RGBAProtocol* pParent = dynamic_cast<RGBAProtocol*>(_parent);
if (pParent && pParent->isCascadeColorEnabled())
{
parentColor = pParent->getDisplayedColor();
}
this->updateDisplayedColor(parentColor);
}
}
GLubyte LabelBMFont::getOpacity(void) const
{
return _realOpacity;
}
GLubyte LabelBMFont::getDisplayedOpacity(void) const
{
return _displayedOpacity;
}
/** Override synthesized setOpacity to recurse items */ /** Override synthesized setOpacity to recurse items */
void LabelBMFont::setOpacity(GLubyte opacity)
{
_displayedOpacity = _realOpacity = opacity;
if( _cascadeOpacityEnabled ) {
GLubyte parentOpacity = 255;
RGBAProtocol* pParent = dynamic_cast<RGBAProtocol*>(_parent);
if (pParent && pParent->isCascadeOpacityEnabled())
{
parentOpacity = pParent->getDisplayedOpacity();
}
this->updateDisplayedOpacity(parentOpacity);
}
}
void LabelBMFont::setOpacityModifyRGB(bool var) void LabelBMFont::setOpacityModifyRGB(bool var)
{ {
_isOpacityModifyRGB = var; _isOpacityModifyRGB = var;
_children.forEach([this](Node* child){ for(const auto &child : _children) {
if (child) child->setOpacityModifyRGB(_isOpacityModifyRGB);
{ }
RGBAProtocol *pRGBAProtocol = dynamic_cast<RGBAProtocol*>(child);
if (pRGBAProtocol)
{
pRGBAProtocol->setOpacityModifyRGB(_isOpacityModifyRGB);
}
}
});
} }
bool LabelBMFont::isOpacityModifyRGB() const bool LabelBMFont::isOpacityModifyRGB() const
{ {
return _isOpacityModifyRGB; return _isOpacityModifyRGB;
} }
void LabelBMFont::updateDisplayedOpacity(GLubyte parentOpacity)
{
_displayedOpacity = _realOpacity * parentOpacity/255.0f;
_children.forEach([this](Node* child){
Sprite *item = static_cast<Sprite*>( child );
item->updateDisplayedOpacity(_displayedOpacity);
});
}
void LabelBMFont::updateDisplayedColor(const Color3B& parentColor)
{
_displayedColor.r = _realColor.r * parentColor.r/255.0f;
_displayedColor.g = _realColor.g * parentColor.g/255.0f;
_displayedColor.b = _realColor.b * parentColor.b/255.0f;
_children.forEach([this](Node* child){
Sprite *item = static_cast<Sprite*>( child );
item->updateDisplayedColor(_displayedColor);
});
}
bool LabelBMFont::isCascadeColorEnabled() const
{
return false;
}
void LabelBMFont::setCascadeColorEnabled(bool cascadeColorEnabled)
{
_cascadeColorEnabled = cascadeColorEnabled;
}
bool LabelBMFont::isCascadeOpacityEnabled() const
{
return false;
}
void LabelBMFont::setCascadeOpacityEnabled(bool cascadeOpacityEnabled)
{
_cascadeOpacityEnabled = cascadeOpacityEnabled;
}
// LabelBMFont - AnchorPoint // LabelBMFont - AnchorPoint
void LabelBMFont::setAnchorPoint(const Point& point) void LabelBMFont::setAnchorPoint(const Point& point)
{ {
@ -923,9 +984,6 @@ void LabelBMFont::updateLabel()
} }
skip += justSkipped; skip += justSkipped;
if (!characterSprite->isVisible())
continue;
if (i >= stringLength) if (i >= stringLength)
break; break;
@ -973,6 +1031,8 @@ void LabelBMFont::updateLabel()
startOfLine = startOfWord; startOfLine = startOfWord;
start_line = true; start_line = true;
} }
++i;
continue;
} }
// Whitespace. // Whitespace.
@ -1054,7 +1114,7 @@ void LabelBMFont::updateLabel()
size_t size = multiline_string.size(); size_t size = multiline_string.size();
unsigned short* str_new = new unsigned short[size + 1]; unsigned short* str_new = new unsigned short[size + 1];
for (int j = 0; j < size; ++j) for (size_t j = 0; j < size; ++j)
{ {
str_new[j] = multiline_string[j]; str_new[j] = multiline_string[j];
} }
@ -1090,7 +1150,7 @@ void LabelBMFont::updateLabel()
if (index < 0) continue; if (index < 0) continue;
Sprite* lastChar = static_cast<Sprite*>( getChildByTag(index) ); Sprite* lastChar = static_cast<Sprite*>( getChildByTag(index) );
if ( lastChar == NULL ) if ( lastChar == nullptr )
continue; continue;
lineWidth = lastChar->getPosition().x + lastChar->getContentSize().width/2.0f; lineWidth = lastChar->getPosition().x + lastChar->getContentSize().width/2.0f;

View File

@ -151,6 +151,7 @@ public:
std::set<unsigned int>* getCharacterSet() const; std::set<unsigned int>* getCharacterSet() const;
private: private:
std::set<unsigned int>* parseConfigFile(const std::string& controlFile); std::set<unsigned int>* parseConfigFile(const std::string& controlFile);
std::set<unsigned int>* parseBinaryConfigFile(unsigned char* pData, unsigned long size, const std::string& controlFile);
void parseCharacterDefinition(std::string line, ccBMFontDef *characterDefinition); void parseCharacterDefinition(std::string line, ccBMFontDef *characterDefinition);
void parseInfoArguments(std::string line); void parseInfoArguments(std::string line);
void parseCommonArguments(std::string line); void parseCommonArguments(std::string line);
@ -190,7 +191,7 @@ http://www.angelcode.com/products/bmfont/ (Free, Windows only)
@since v0.8 @since v0.8
*/ */
class CC_DLL LabelBMFont : public SpriteBatchNode, public LabelProtocol, public RGBAProtocol class CC_DLL LabelBMFont : public SpriteBatchNode, public LabelProtocol
{ {
public: public:
/** /**
@ -245,18 +246,6 @@ public:
// RGBAProtocol // RGBAProtocol
virtual bool isOpacityModifyRGB() const; virtual bool isOpacityModifyRGB() const;
virtual void setOpacityModifyRGB(bool isOpacityModifyRGB); virtual void setOpacityModifyRGB(bool isOpacityModifyRGB);
virtual GLubyte getOpacity() const;
virtual GLubyte getDisplayedOpacity() const;
virtual void setOpacity(GLubyte opacity);
virtual void updateDisplayedOpacity(GLubyte parentOpacity);
virtual bool isCascadeOpacityEnabled() const;
virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled);
virtual const Color3B& getColor(void) const;
virtual const Color3B& getDisplayedColor() const;
virtual void setColor(const Color3B& color);
virtual void updateDisplayedColor(const Color3B& parentColor);
virtual bool isCascadeColorEnabled() const;
virtual void setCascadeColorEnabled(bool cascadeColorEnabled);
void setFntFile(const std::string& fntFile); void setFntFile(const std::string& fntFile);
const std::string& getFntFile() const; const std::string& getFntFile() const;
@ -298,13 +287,6 @@ protected:
Sprite *_reusedChar; Sprite *_reusedChar;
// texture RGBA // texture RGBA
GLubyte _displayedOpacity;
GLubyte _realOpacity;
Color3B _displayedColor;
Color3B _realColor;
bool _cascadeColorEnabled;
bool _cascadeOpacityEnabled;
/** conforms to RGBAProtocol protocol */
bool _isOpacityModifyRGB; bool _isOpacityModifyRGB;
}; };

View File

@ -92,7 +92,7 @@ LabelTTF* LabelTTF::create(const std::string& string, const std::string& fontNam
return ret; return ret;
} }
CC_SAFE_DELETE(ret); CC_SAFE_DELETE(ret);
return NULL; return nullptr;
} }
LabelTTF * LabelTTF::createWithFontDefinition(const std::string& string, FontDefinition &textDefinition) LabelTTF * LabelTTF::createWithFontDefinition(const std::string& string, FontDefinition &textDefinition)
@ -104,7 +104,7 @@ LabelTTF * LabelTTF::createWithFontDefinition(const std::string& string, FontDef
return ret; return ret;
} }
CC_SAFE_DELETE(ret); CC_SAFE_DELETE(ret);
return NULL; return nullptr;
} }
bool LabelTTF::init() bool LabelTTF::init()
@ -131,8 +131,8 @@ bool LabelTTF::initWithString(const std::string& string, const std::string& font
if (Sprite::init()) if (Sprite::init())
{ {
// shader program // shader program
this->setShaderProgram(ShaderCache::getInstance()->getProgram(SHADER_PROGRAM)); // this->setShaderProgram(ShaderCache::getInstance()->getProgram(SHADER_PROGRAM));
_dimensions = Size(dimensions.width, dimensions.height); _dimensions = Size(dimensions.width, dimensions.height);
_alignment = hAlignment; _alignment = hAlignment;
_vAlignment = vAlignment; _vAlignment = vAlignment;

View File

@ -25,8 +25,8 @@ THE SOFTWARE.
#ifndef __CCLABELTTF_H__ #ifndef __CCLABELTTF_H__
#define __CCLABELTTF_H__ #define __CCLABELTTF_H__
#include "CCSprite.h"
#include "CCTexture2D.h" #include "CCTexture2D.h"
#include "CCSprite.h"
NS_CC_BEGIN NS_CC_BEGIN

View File

@ -58,7 +58,7 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
std::vector<LetterInfo> *leterInfo = theLabel->getLettersInfo(); std::vector<LetterInfo> *leterInfo = theLabel->getLettersInfo();
int tIndex = 0; int tIndex = 0;
for (int j = 0; j < strLen; j++) for (int j = 0; j+skip < strLen; j++)
{ {
LetterInfo* info = &leterInfo->at(j+skip); LetterInfo* info = &leterInfo->at(j+skip);
@ -200,7 +200,7 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel)
size_t size = multiline_string.size(); size_t size = multiline_string.size();
unsigned short* strNew = new unsigned short[size + 1]; unsigned short* strNew = new unsigned short[size + 1];
for (int j = 0; j < size; ++j) for (size_t j = 0; j < size; ++j)
{ {
strNew[j] = multiline_string[j]; strNew[j] = multiline_string[j];
} }

View File

@ -43,6 +43,8 @@ THE SOFTWARE.
#include "CCEventListenerAcceleration.h" #include "CCEventListenerAcceleration.h"
#include "platform/CCDevice.h" #include "platform/CCDevice.h"
#include "CCScene.h" #include "CCScene.h"
#include "CCCustomCommand.h"
#include "CCRenderer.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -51,11 +53,11 @@ Layer::Layer()
: _touchEnabled(false) : _touchEnabled(false)
, _accelerometerEnabled(false) , _accelerometerEnabled(false)
, _keyboardEnabled(false) , _keyboardEnabled(false)
, _touchMode(Touch::DispatchMode::ALL_AT_ONCE)
, _swallowsTouches(true)
, _touchListener(nullptr) , _touchListener(nullptr)
, _keyboardListener(nullptr) , _keyboardListener(nullptr)
, _accelerationListener(nullptr) , _accelerationListener(nullptr)
, _touchMode(Touch::DispatchMode::ALL_AT_ONCE)
, _swallowsTouches(true)
{ {
_ignoreAnchorPointForPosition = true; _ignoreAnchorPointForPosition = true;
setAnchorPoint(Point(0.5f, 0.5f)); setAnchorPoint(Point(0.5f, 0.5f));
@ -68,30 +70,30 @@ Layer::~Layer()
bool Layer::init() bool Layer::init()
{ {
bool bRet = false; bool ret = false;
do do
{ {
Director * pDirector; Director * director;
CC_BREAK_IF(!(pDirector = Director::getInstance())); CC_BREAK_IF(!(director = Director::getInstance()));
this->setContentSize(pDirector->getWinSize()); this->setContentSize(director->getWinSize());
// success // success
bRet = true; ret = true;
} while(0); } while(0);
return bRet; return ret;
} }
Layer *Layer::create() Layer *Layer::create()
{ {
Layer *pRet = new Layer(); Layer *ret = new Layer();
if (pRet && pRet->init()) if (ret && ret->init())
{ {
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
else else
{ {
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return nullptr;
} }
} }
@ -410,154 +412,17 @@ std::string Layer::getDescription() const
return StringUtils::format("<Layer | Tag = %d>", _tag); return StringUtils::format("<Layer | Tag = %d>", _tag);
} }
__LayerRGBA::__LayerRGBA()
{
CCLOG("LayerRGBA deprecated.");
}
#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1))) #if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
#pragma GCC diagnostic warning "-Wdeprecated-declarations" #pragma GCC diagnostic warning "-Wdeprecated-declarations"
#elif _MSC_VER >= 1400 //vs 2005 or higher #elif _MSC_VER >= 1400 //vs 2005 or higher
#pragma warning (pop) #pragma warning (pop)
#endif #endif
// LayerRGBA
LayerRGBA::LayerRGBA()
: _displayedOpacity(255)
, _realOpacity (255)
, _displayedColor(Color3B::WHITE)
, _realColor(Color3B::WHITE)
, _cascadeOpacityEnabled(false)
, _cascadeColorEnabled(false)
{}
LayerRGBA::~LayerRGBA() {}
bool LayerRGBA::init()
{
if (Layer::init())
{
_displayedOpacity = _realOpacity = 255;
_displayedColor = _realColor = Color3B::WHITE;
setCascadeOpacityEnabled(false);
setCascadeColorEnabled(false);
return true;
}
else
{
return false;
}
}
GLubyte LayerRGBA::getOpacity() const
{
return _realOpacity;
}
GLubyte LayerRGBA::getDisplayedOpacity() const
{
return _displayedOpacity;
}
/** Override synthesized setOpacity to recurse items */
void LayerRGBA::setOpacity(GLubyte opacity)
{
_displayedOpacity = _realOpacity = opacity;
if( _cascadeOpacityEnabled )
{
GLubyte parentOpacity = 255;
RGBAProtocol *parent = dynamic_cast<RGBAProtocol*>(_parent);
if (parent && parent->isCascadeOpacityEnabled())
{
parentOpacity = parent->getDisplayedOpacity();
}
updateDisplayedOpacity(parentOpacity);
}
}
const Color3B& LayerRGBA::getColor() const
{
return _realColor;
}
const Color3B& LayerRGBA::getDisplayedColor() const
{
return _displayedColor;
}
void LayerRGBA::setColor(const Color3B& color)
{
_displayedColor = _realColor = color;
if (_cascadeColorEnabled)
{
Color3B parentColor = Color3B::WHITE;
RGBAProtocol* parent = dynamic_cast<RGBAProtocol*>(_parent);
if (parent && parent->isCascadeColorEnabled())
{
parentColor = parent->getDisplayedColor();
}
updateDisplayedColor(parentColor);
}
}
void LayerRGBA::updateDisplayedOpacity(GLubyte parentOpacity)
{
_displayedOpacity = _realOpacity * parentOpacity/255.0;
if (_cascadeOpacityEnabled)
{
_children.forEach([this](Node* obj){
RGBAProtocol *item = dynamic_cast<RGBAProtocol*>(obj);
if (item)
{
item->updateDisplayedOpacity(_displayedOpacity);
}
});
}
}
void LayerRGBA::updateDisplayedColor(const Color3B& parentColor)
{
_displayedColor.r = _realColor.r * parentColor.r/255.0;
_displayedColor.g = _realColor.g * parentColor.g/255.0;
_displayedColor.b = _realColor.b * parentColor.b/255.0;
if (_cascadeColorEnabled)
{
_children.forEach([this](Node* obj){
RGBAProtocol *item = dynamic_cast<RGBAProtocol*>(obj);
if (item)
{
item->updateDisplayedColor(_displayedColor);
}
});
}
}
bool LayerRGBA::isCascadeOpacityEnabled() const
{
return _cascadeOpacityEnabled;
}
void LayerRGBA::setCascadeOpacityEnabled(bool cascadeOpacityEnabled)
{
_cascadeOpacityEnabled = cascadeOpacityEnabled;
}
bool LayerRGBA::isCascadeColorEnabled() const
{
return _cascadeColorEnabled;
}
void LayerRGBA::setCascadeColorEnabled(bool cascadeColorEnabled)
{
_cascadeColorEnabled = cascadeColorEnabled;
}
std::string LayerRGBA::getDescription() const
{
return StringUtils::format("<LayerRGBA | Tag = %d>", _tag);
}
/// LayerColor /// LayerColor
LayerColor::LayerColor() LayerColor::LayerColor()
@ -583,40 +448,40 @@ void LayerColor::setBlendFunc(const BlendFunc &var)
LayerColor* LayerColor::create() LayerColor* LayerColor::create()
{ {
LayerColor* pRet = new LayerColor(); LayerColor* ret = new LayerColor();
if (pRet && pRet->init()) if (ret && ret->init())
{ {
pRet->autorelease(); ret->autorelease();
} }
else else
{ {
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
} }
return pRet; return ret;
} }
LayerColor * LayerColor::create(const Color4B& color, GLfloat width, GLfloat height) LayerColor * LayerColor::create(const Color4B& color, GLfloat width, GLfloat height)
{ {
LayerColor * pLayer = new LayerColor(); LayerColor * layer = new LayerColor();
if( pLayer && pLayer->initWithColor(color,width,height)) if( layer && layer->initWithColor(color,width,height))
{ {
pLayer->autorelease(); layer->autorelease();
return pLayer; return layer;
} }
CC_SAFE_DELETE(pLayer); CC_SAFE_DELETE(layer);
return NULL; return nullptr;
} }
LayerColor * LayerColor::create(const Color4B& color) LayerColor * LayerColor::create(const Color4B& color)
{ {
LayerColor * pLayer = new LayerColor(); LayerColor * layer = new LayerColor();
if(pLayer && pLayer->initWithColor(color)) if(layer && layer->initWithColor(color))
{ {
pLayer->autorelease(); layer->autorelease();
return pLayer; return layer;
} }
CC_SAFE_DELETE(pLayer); CC_SAFE_DELETE(layer);
return NULL; return nullptr;
} }
bool LayerColor::init() bool LayerColor::init()
@ -698,6 +563,13 @@ void LayerColor::updateColor()
} }
void LayerColor::draw() void LayerColor::draw()
{
_customCommand.init(0, _vertexZ);
_customCommand.func = CC_CALLBACK_0(LayerColor::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(&_customCommand);
}
void LayerColor::onDraw()
{ {
CC_NODE_DRAW_SETUP(); CC_NODE_DRAW_SETUP();
@ -724,62 +596,49 @@ void LayerColor::draw()
CC_INCREMENT_GL_DRAWS(1); CC_INCREMENT_GL_DRAWS(1);
} }
void LayerColor::setColor(const Color3B &color)
{
LayerRGBA::setColor(color);
updateColor();
}
void LayerColor::setOpacity(GLubyte opacity)
{
LayerRGBA::setOpacity(opacity);
updateColor();
}
std::string LayerColor::getDescription() const std::string LayerColor::getDescription() const
{ {
return StringUtils::format("<LayerColor | Tag = %d>", _tag); return StringUtils::format("<LayerColor | Tag = %d>", _tag);
} }
// //
// LayerGradient // LayerGradient
// //
LayerGradient* LayerGradient::create(const Color4B& start, const Color4B& end) LayerGradient* LayerGradient::create(const Color4B& start, const Color4B& end)
{ {
LayerGradient * pLayer = new LayerGradient(); LayerGradient * layer = new LayerGradient();
if( pLayer && pLayer->initWithColor(start, end)) if( layer && layer->initWithColor(start, end))
{ {
pLayer->autorelease(); layer->autorelease();
return pLayer; return layer;
} }
CC_SAFE_DELETE(pLayer); CC_SAFE_DELETE(layer);
return NULL; return nullptr;
} }
LayerGradient* LayerGradient::create(const Color4B& start, const Color4B& end, const Point& v) LayerGradient* LayerGradient::create(const Color4B& start, const Color4B& end, const Point& v)
{ {
LayerGradient * pLayer = new LayerGradient(); LayerGradient * layer = new LayerGradient();
if( pLayer && pLayer->initWithColor(start, end, v)) if( layer && layer->initWithColor(start, end, v))
{ {
pLayer->autorelease(); layer->autorelease();
return pLayer; return layer;
} }
CC_SAFE_DELETE(pLayer); CC_SAFE_DELETE(layer);
return NULL; return nullptr;
} }
LayerGradient* LayerGradient::create() LayerGradient* LayerGradient::create()
{ {
LayerGradient* pRet = new LayerGradient(); LayerGradient* ret = new LayerGradient();
if (pRet && pRet->init()) if (ret && ret->init())
{ {
pRet->autorelease(); ret->autorelease();
} }
else else
{ {
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
} }
return pRet; return ret;
} }
bool LayerGradient::init() bool LayerGradient::init()
@ -942,9 +801,9 @@ LayerMultiplex::LayerMultiplex()
LayerMultiplex::~LayerMultiplex() LayerMultiplex::~LayerMultiplex()
{ {
_layers.forEach([](Layer* layer){ for(const auto &layer : _layers) {
layer->cleanup(); layer->cleanup();
}); }
} }
LayerMultiplex * LayerMultiplex::create(Layer * layer, ...) LayerMultiplex * LayerMultiplex::create(Layer * layer, ...)
@ -952,49 +811,49 @@ LayerMultiplex * LayerMultiplex::create(Layer * layer, ...)
va_list args; va_list args;
va_start(args,layer); va_start(args,layer);
LayerMultiplex * pMultiplexLayer = new LayerMultiplex(); LayerMultiplex * multiplexLayer = new LayerMultiplex();
if(pMultiplexLayer && pMultiplexLayer->initWithLayers(layer, args)) if(multiplexLayer && multiplexLayer->initWithLayers(layer, args))
{ {
pMultiplexLayer->autorelease(); multiplexLayer->autorelease();
va_end(args); va_end(args);
return pMultiplexLayer; return multiplexLayer;
} }
va_end(args); va_end(args);
CC_SAFE_DELETE(pMultiplexLayer); CC_SAFE_DELETE(multiplexLayer);
return NULL; return nullptr;
} }
LayerMultiplex * LayerMultiplex::createWithLayer(Layer* layer) LayerMultiplex * LayerMultiplex::createWithLayer(Layer* layer)
{ {
return LayerMultiplex::create(layer, NULL); return LayerMultiplex::create(layer, nullptr);
} }
LayerMultiplex* LayerMultiplex::create() LayerMultiplex* LayerMultiplex::create()
{ {
LayerMultiplex* pRet = new LayerMultiplex(); LayerMultiplex* ret = new LayerMultiplex();
if (pRet && pRet->init()) if (ret && ret->init())
{ {
pRet->autorelease(); ret->autorelease();
} }
else else
{ {
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
} }
return pRet; return ret;
} }
LayerMultiplex* LayerMultiplex::createWithArray(const Vector<Layer*>& arrayOfLayers) LayerMultiplex* LayerMultiplex::createWithArray(const Vector<Layer*>& arrayOfLayers)
{ {
LayerMultiplex* pRet = new LayerMultiplex(); LayerMultiplex* ret = new LayerMultiplex();
if (pRet && pRet->initWithArray(arrayOfLayers)) if (ret && ret->initWithArray(arrayOfLayers))
{ {
pRet->autorelease(); ret->autorelease();
} }
else else
{ {
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
} }
return pRet; return ret;
} }
void LayerMultiplex::addLayer(Layer* layer) void LayerMultiplex::addLayer(Layer* layer)
@ -1038,7 +897,7 @@ bool LayerMultiplex::initWithArray(const Vector<Layer*>& arrayOfLayers)
if (Layer::init()) if (Layer::init())
{ {
_layers.reserve(arrayOfLayers.size()); _layers.reserve(arrayOfLayers.size());
_layers.insert(arrayOfLayers); _layers.pushBack(arrayOfLayers);
_enabledLayer = 0; _enabledLayer = 0;
this->addChild(_layers.at(_enabledLayer)); this->addChild(_layers.at(_enabledLayer));

View File

@ -35,6 +35,7 @@ THE SOFTWARE.
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
#include "CCEventKeyboard.h" #include "CCEventKeyboard.h"
#include "renderer/CCCustomCommand.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -195,45 +196,38 @@ private:
- RGB colors - RGB colors
@since 2.1 @since 2.1
*/ */
class CC_DLL LayerRGBA : public Layer, public RGBAProtocol class CC_DLL __LayerRGBA : public Layer, public __RGBAProtocol
{ {
public: public:
CREATE_FUNC(LayerRGBA); CREATE_FUNC(__LayerRGBA);
// //
// Overrides // Overrides
// //
virtual GLubyte getOpacity() const override; virtual GLubyte getOpacity() const override { return Layer::getOpacity(); }
virtual GLubyte getDisplayedOpacity() const override; virtual GLubyte getDisplayedOpacity() const override { return Layer::getDisplayedOpacity(); }
virtual void setOpacity(GLubyte opacity) override; virtual void setOpacity(GLubyte opacity) override { return Layer::setOpacity(opacity); }
virtual void updateDisplayedOpacity(GLubyte parentOpacity) override; virtual void updateDisplayedOpacity(GLubyte parentOpacity) override { return Layer::updateDisplayedOpacity(parentOpacity); }
virtual bool isCascadeOpacityEnabled() const override; virtual bool isCascadeOpacityEnabled() const override { return Layer::isCascadeOpacityEnabled(); }
virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled) override; virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled) override { return Layer::setCascadeOpacityEnabled(cascadeOpacityEnabled); }
virtual const Color3B& getColor() const override;
virtual const Color3B& getDisplayedColor() const override;
virtual void setColor(const Color3B& color) override;
virtual void updateDisplayedColor(const Color3B& parentColor) override;
virtual bool isCascadeColorEnabled() const override;
virtual void setCascadeColorEnabled(bool cascadeColorEnabled) override;
virtual std::string getDescription() const override;
virtual void setOpacityModifyRGB(bool bValue) override {CC_UNUSED_PARAM(bValue);} virtual const Color3B& getColor() const override { return Layer::getColor(); }
virtual bool isOpacityModifyRGB() const override { return false; } virtual const Color3B& getDisplayedColor() const override { return Layer::getDisplayedColor(); }
virtual void setColor(const Color3B& color) override { return Layer::setColor(color); }
virtual void updateDisplayedColor(const Color3B& parentColor) override { return Layer::updateDisplayedColor(parentColor); }
virtual bool isCascadeColorEnabled() const override { return Layer::isCascadeOpacityEnabled(); }
virtual void setCascadeColorEnabled(bool cascadeColorEnabled) override { return Layer::setCascadeColorEnabled(cascadeColorEnabled); }
virtual void setOpacityModifyRGB(bool bValue) override { return Layer::setOpacityModifyRGB(bValue); }
virtual bool isOpacityModifyRGB() const override { return Layer::isOpacityModifyRGB(); }
protected: protected:
LayerRGBA(); __LayerRGBA();
virtual ~LayerRGBA(); virtual ~__LayerRGBA() {}
virtual bool init();
GLubyte _displayedOpacity, _realOpacity;
Color3B _displayedColor, _realColor;
bool _cascadeOpacityEnabled, _cascadeColorEnabled;
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(LayerRGBA); CC_DISALLOW_COPY_AND_ASSIGN(__LayerRGBA);
}; };
// //
@ -245,7 +239,7 @@ All features from Layer are valid, plus the following new features:
- opacity - opacity
- RGB colors - RGB colors
*/ */
class CC_DLL LayerColor : public LayerRGBA, public BlendProtocol class CC_DLL LayerColor : public Layer, public BlendProtocol
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
, public GLBufferedNode , public GLBufferedNode
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
@ -271,8 +265,8 @@ public:
// Overrides // Overrides
// //
virtual void draw() override; virtual void draw() override;
virtual void setColor(const Color3B &color) override; virtual void onDraw();
virtual void setOpacity(GLubyte opacity) override;
virtual void setContentSize(const Size & var) override; virtual void setContentSize(const Size & var) override;
/** BlendFunction. Conforms to BlendProtocol protocol */ /** BlendFunction. Conforms to BlendProtocol protocol */
/** /**
@ -298,11 +292,12 @@ protected:
bool initWithColor(const Color4B& color, GLfloat width, GLfloat height); bool initWithColor(const Color4B& color, GLfloat width, GLfloat height);
bool initWithColor(const Color4B& color); bool initWithColor(const Color4B& color);
virtual void updateColor(); virtual void updateColor() override;
BlendFunc _blendFunc; BlendFunc _blendFunc;
Vertex2F _squareVertices[4]; Vertex2F _squareVertices[4];
Color4F _squareColors[4]; Color4F _squareColors[4];
CustomCommand _customCommand;
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(LayerColor); CC_DISALLOW_COPY_AND_ASSIGN(LayerColor);
@ -359,7 +354,7 @@ public:
/** Whether or not the interpolation will be compressed in order to display all the colors of the gradient both in canonical and non canonical vectors /** Whether or not the interpolation will be compressed in order to display all the colors of the gradient both in canonical and non canonical vectors
Default: true Default: true
*/ */
void setCompressedInterpolation(bool bCompressedInterpolation); void setCompressedInterpolation(bool compressedInterpolation);
bool isCompressedInterpolation() const; bool isCompressedInterpolation() const;
/** Sets the start color of the gradient */ /** Sets the start color of the gradient */

View File

@ -54,7 +54,7 @@ Menu::~Menu()
Menu* Menu::create() Menu* Menu::create()
{ {
return Menu::create(NULL, NULL); return Menu::create(nullptr, nullptr);
} }
Menu * Menu::create(MenuItem* item, ...) Menu * Menu::create(MenuItem* item, ...)
@ -62,11 +62,11 @@ Menu * Menu::create(MenuItem* item, ...)
va_list args; va_list args;
va_start(args,item); va_start(args,item);
Menu *pRet = Menu::createWithItems(item, args); Menu *ret = Menu::createWithItems(item, args);
va_end(args); va_end(args);
return pRet; return ret;
} }
Menu* Menu::createWithArray(const Vector<MenuItem*>& arrayOfItems) Menu* Menu::createWithArray(const Vector<MenuItem*>& arrayOfItems)
@ -103,7 +103,7 @@ Menu* Menu::createWithItems(MenuItem* item, va_list args)
Menu* Menu::createWithItem(MenuItem* item) Menu* Menu::createWithItem(MenuItem* item)
{ {
return Menu::create(item, NULL); return Menu::create(item, nullptr);
} }
bool Menu::init() bool Menu::init()
@ -133,7 +133,7 @@ bool Menu::initWithArray(const Vector<MenuItem*>& arrayOfItems)
z++; z++;
} }
_selectedItem = NULL; _selectedItem = nullptr;
_state = Menu::State::WAITING; _state = Menu::State::WAITING;
// enable cascade color and opacity on menus // enable cascade color and opacity on menus
@ -171,7 +171,7 @@ void Menu::addChild(Node * child, int zOrder)
void Menu::addChild(Node * child, int zOrder, int tag) void Menu::addChild(Node * child, int zOrder, int tag)
{ {
CCASSERT( dynamic_cast<MenuItem*>(child) != NULL, "Menu only supports MenuItem objects as children"); CCASSERT( dynamic_cast<MenuItem*>(child) != nullptr, "Menu only supports MenuItem objects as children");
Layer::addChild(child, zOrder, tag); Layer::addChild(child, zOrder, tag);
} }
@ -187,7 +187,7 @@ void Menu::onExit()
if (_selectedItem) if (_selectedItem)
{ {
_selectedItem->unselected(); _selectedItem->unselected();
_selectedItem = NULL; _selectedItem = nullptr;
} }
_state = Menu::State::WAITING; _state = Menu::State::WAITING;
@ -198,12 +198,12 @@ void Menu::onExit()
void Menu::removeChild(Node* child, bool cleanup) void Menu::removeChild(Node* child, bool cleanup)
{ {
MenuItem *pMenuItem = dynamic_cast<MenuItem*>(child); MenuItem *menuItem = dynamic_cast<MenuItem*>(child);
CCASSERT(pMenuItem != NULL, "Menu only supports MenuItem objects as children"); CCASSERT(menuItem != nullptr, "Menu only supports MenuItem objects as children");
if (_selectedItem == pMenuItem) if (_selectedItem == menuItem)
{ {
_selectedItem = NULL; _selectedItem = nullptr;
} }
Node::removeChild(child, cleanup); Node::removeChild(child, cleanup);
@ -218,7 +218,7 @@ bool Menu::onTouchBegan(Touch* touch, Event* event)
return false; return false;
} }
for (Node *c = this->_parent; c != NULL; c = c->getParent()) for (Node *c = this->_parent; c != nullptr; c = c->getParent())
{ {
if (c->isVisible() == false) if (c->isVisible() == false)
{ {
@ -290,23 +290,16 @@ void Menu::alignItemsVertically()
void Menu::alignItemsVerticallyWithPadding(float padding) void Menu::alignItemsVerticallyWithPadding(float padding)
{ {
float height = -padding; float height = -padding;
_children.forEach([&](Node* child){ for(const auto &child : _children)
if (child) height += child->getContentSize().height * child->getScaleY() + padding;
{
height += child->getContentSize().height * child->getScaleY() + padding;
}
});
float y = height / 2.0f; float y = height / 2.0f;
_children.forEach([&](Node* child){ for(const auto &child : _children) {
if (child) child->setPosition(Point(0, y - child->getContentSize().height * child->getScaleY() / 2.0f));
{ y -= child->getContentSize().height * child->getScaleY() + padding;
child->setPosition(Point(0, y - child->getContentSize().height * child->getScaleY() / 2.0f)); }
y -= child->getContentSize().height * child->getScaleY() + padding;
}
});
} }
void Menu::alignItemsHorizontally(void) void Menu::alignItemsHorizontally(void)
@ -317,22 +310,15 @@ void Menu::alignItemsHorizontally(void)
void Menu::alignItemsHorizontallyWithPadding(float padding) void Menu::alignItemsHorizontallyWithPadding(float padding)
{ {
float width = -padding; float width = -padding;
_children.forEach([&](Node* child){ for(const auto &child : _children)
if (child) width += child->getContentSize().width * child->getScaleX() + padding;
{
width += child->getContentSize().width * child->getScaleX() + padding;
}
});
float x = -width / 2.0f; float x = -width / 2.0f;
_children.forEach([&](Node* child){ for(const auto &child : _children) {
if (child) child->setPosition(Point(x + child->getContentSize().width * child->getScaleX() / 2.0f, 0));
{ x += child->getContentSize().width * child->getScaleX() + padding;
child->setPosition(Point(x + child->getContentSize().width * child->getScaleX() / 2.0f, 0)); }
x += child->getContentSize().width * child->getScaleX() + padding;
}
});
} }
void Menu::alignItemsInColumns(int columns, ...) void Menu::alignItemsInColumns(int columns, ...)
@ -360,34 +346,31 @@ void Menu::alignItemsInColumns(int columns, va_list args)
void Menu::alignItemsInColumnsWithArray(const ValueVector& rows) void Menu::alignItemsInColumnsWithArray(const ValueVector& rows)
{ {
int height = -5; int height = -5;
int row = 0; size_t row = 0;
int rowHeight = 0; int rowHeight = 0;
int columnsOccupied = 0; int columnsOccupied = 0;
int rowColumns = 0; int rowColumns = 0;
_children.forEach([&](Node* child){ for(const auto &child : _children) {
if (child) CCASSERT(row < rows.size(), "");
rowColumns = rows[row].asInt();
// can not have zero columns on a row
CCASSERT(rowColumns, "");
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{ {
CCASSERT(row < rows.size(), ""); height += rowHeight + 5;
rowColumns = rows[row].asInt(); columnsOccupied = 0;
// can not have zero columns on a row rowHeight = 0;
CCASSERT(rowColumns, ""); ++row;
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{
height += rowHeight + 5;
columnsOccupied = 0;
rowHeight = 0;
++row;
}
} }
}); }
// check if too many rows/columns for available menu items // check if too many rows/columns for available menu items
CCASSERT(! columnsOccupied, ""); CCASSERT(! columnsOccupied, "");
@ -401,39 +384,33 @@ void Menu::alignItemsInColumnsWithArray(const ValueVector& rows)
float x = 0.0; float x = 0.0;
float y = (float)(height / 2); float y = (float)(height / 2);
_children.forEach([&](Node* child){ for(const auto &child : _children) {
if (child) if (rowColumns == 0)
{ {
if (child) rowColumns = rows[row].asInt();
{ w = winSize.width / (1 + rowColumns);
if (rowColumns == 0) x = w;
{
rowColumns = rows[row].asInt();
w = winSize.width / (1 + rowColumns);
x = w;
}
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
child->setPosition(Point(x - winSize.width / 2,
y - child->getContentSize().height / 2));
x += w;
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{
y -= rowHeight + 5;
columnsOccupied = 0;
rowColumns = 0;
rowHeight = 0;
++row;
}
}
} }
});
float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
child->setPosition(Point(x - winSize.width / 2,
y - child->getContentSize().height / 2));
x += w;
++columnsOccupied;
if (columnsOccupied >= rowColumns)
{
y -= rowHeight + 5;
columnsOccupied = 0;
rowColumns = 0;
rowHeight = 0;
++row;
}
}
} }
void Menu::alignItemsInRows(int rows, ...) void Menu::alignItemsInRows(int rows, ...)
@ -464,41 +441,38 @@ void Menu::alignItemsInRowsWithArray(const ValueVector& columns)
int width = -10; int width = -10;
int columnHeight = -5; int columnHeight = -5;
int column = 0; size_t column = 0;
int columnWidth = 0; int columnWidth = 0;
int rowsOccupied = 0; int rowsOccupied = 0;
int columnRows; int columnRows;
_children.forEach([&](Node* child){ for(const auto &child : _children) {
if (child) // check if too many menu items for the amount of rows/columns
CCASSERT(column < columns.size(), "");
columnRows = columns[column].asInt();
// can't have zero rows on a column
CCASSERT(columnRows, "");
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
columnHeight += (int)(child->getContentSize().height + 5);
++rowsOccupied;
if (rowsOccupied >= columnRows)
{ {
// check if too many menu items for the amount of rows/columns columnWidths.push_back(columnWidth);
CCASSERT(column < columns.size(), ""); columnHeights.push_back(columnHeight);
width += columnWidth + 10;
columnRows = columns[column].asInt(); rowsOccupied = 0;
// can't have zero rows on a column columnWidth = 0;
CCASSERT(columnRows, ""); columnHeight = -5;
++column;
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
columnHeight += (int)(child->getContentSize().height + 5);
++rowsOccupied;
if (rowsOccupied >= columnRows)
{
columnWidths.push_back(columnWidth);
columnHeights.push_back(columnHeight);
width += columnWidth + 10;
rowsOccupied = 0;
columnWidth = 0;
columnHeight = -5;
++column;
}
} }
}); }
// check if too many rows/columns for available menu items. // check if too many rows/columns for available menu items.
CCASSERT(! rowsOccupied, ""); CCASSERT(! rowsOccupied, "");
@ -511,35 +485,32 @@ void Menu::alignItemsInRowsWithArray(const ValueVector& columns)
float x = (float)(-width / 2); float x = (float)(-width / 2);
float y = 0.0; float y = 0.0;
_children.forEach([&](Node* child){ for(const auto &child : _children) {
if (child) if (columnRows == 0)
{ {
if (columnRows == 0) columnRows = columns[column].asInt();
{ y = (float) columnHeights[column];
columnRows = columns[column].asInt();
y = (float) columnHeights[column];
}
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
child->setPosition(Point(x + columnWidths[column] / 2,
y - winSize.height / 2));
y -= child->getContentSize().height + 10;
++rowsOccupied;
if (rowsOccupied >= columnRows)
{
x += columnWidth + 5;
rowsOccupied = 0;
columnRows = 0;
columnWidth = 0;
++column;
}
} }
});
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
child->setPosition(Point(x + columnWidths[column] / 2,
y - winSize.height / 2));
y -= child->getContentSize().height + 10;
++rowsOccupied;
if (rowsOccupied >= columnRows)
{
x += columnWidth + 5;
rowsOccupied = 0;
columnRows = 0;
columnWidth = 0;
++column;
}
}
} }
MenuItem* Menu::getItemForTouch(Touch *touch) MenuItem* Menu::getItemForTouch(Touch *touch)
@ -565,7 +536,7 @@ MenuItem* Menu::getItemForTouch(Touch *touch)
} }
} }
return NULL; return nullptr;
} }
std::string Menu::getDescription() const std::string Menu::getDescription() const

View File

@ -48,7 +48,7 @@ NS_CC_BEGIN
* - You can add MenuItem objects in runtime using addChild: * - You can add MenuItem objects in runtime using addChild:
* - But the only accepted children are MenuItem objects * - But the only accepted children are MenuItem objects
*/ */
class CC_DLL Menu : public LayerRGBA class CC_DLL Menu : public Layer
{ {
public: public:
enum class State enum class State
@ -125,7 +125,7 @@ protected:
/** /**
* @js ctor * @js ctor
*/ */
Menu() : _selectedItem(NULL) {} Menu() : _selectedItem(nullptr) {}
virtual ~Menu(); virtual ~Menu();
/** initializes an empty Menu */ /** initializes an empty Menu */

View File

@ -299,12 +299,12 @@ void MenuItemLabel::setEnabled(bool enabled)
{ {
if(enabled == false) if(enabled == false)
{ {
_colorBackup = dynamic_cast<RGBAProtocol*>(_label)->getColor(); _colorBackup = _label->getColor();
dynamic_cast<RGBAProtocol*>(_label)->setColor(_disabledColor); _label->setColor(_disabledColor);
} }
else else
{ {
dynamic_cast<RGBAProtocol*>(_label)->setColor(_colorBackup); _label->setColor(_colorBackup);
} }
} }
MenuItem::setEnabled(enabled); MenuItem::setEnabled(enabled);
@ -320,7 +320,7 @@ MenuItemAtlasFont * MenuItemAtlasFont::create(const std::string& value, const st
} }
// XXX: deprecated // XXX: deprecated
MenuItemAtlasFont * MenuItemAtlasFont::create(const char* value, const char* charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) MenuItemAtlasFont * MenuItemAtlasFont::create(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector)
{ {
MenuItemAtlasFont *ret = new MenuItemAtlasFont(); MenuItemAtlasFont *ret = new MenuItemAtlasFont();
ret->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, target, selector); ret->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap, target, selector);
@ -337,7 +337,7 @@ MenuItemAtlasFont * MenuItemAtlasFont::create(const std::string& value, const st
} }
// XXX: deprecated // XXX: deprecated
bool MenuItemAtlasFont::initWithString(const char* value, const char* charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector) bool MenuItemAtlasFont::initWithString(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector)
{ {
_target = target; _target = target;
CC_SAFE_RETAIN(_target); CC_SAFE_RETAIN(_target);
@ -387,7 +387,7 @@ const std::string& MenuItemFont::getFontName()
} }
// XXX: deprecated // XXX: deprecated
MenuItemFont * MenuItemFont::create(const char *value, Object* target, SEL_MenuHandler selector) MenuItemFont * MenuItemFont::create(const std::string& value, Object* target, SEL_MenuHandler selector)
{ {
MenuItemFont *ret = new MenuItemFont(); MenuItemFont *ret = new MenuItemFont();
ret->initWithString(value, target, selector); ret->initWithString(value, target, selector);
@ -422,9 +422,9 @@ MenuItemFont::~MenuItemFont()
} }
// XXX: deprecated // XXX: deprecated
bool MenuItemFont::initWithString(const char *value, Object* target, SEL_MenuHandler selector) bool MenuItemFont::initWithString(const std::string& value, Object* target, SEL_MenuHandler selector)
{ {
CCASSERT( value != NULL && strlen(value) != 0, "Value length must be greater than 0"); CCASSERT( !value.empty(), "Value length must be greater than 0");
_target = target; _target = target;
CC_SAFE_RETAIN(target); CC_SAFE_RETAIN(target);
@ -433,7 +433,7 @@ bool MenuItemFont::initWithString(const char *value, Object* target, SEL_MenuHan
bool MenuItemFont::initWithString(const std::string& value, const ccMenuCallback& callback) bool MenuItemFont::initWithString(const std::string& value, const ccMenuCallback& callback)
{ {
CCASSERT( value.size() >= 0, "Value length must be greater than 0"); CCASSERT( !value.empty(), "Value length must be greater than 0");
_fontName = _globalFontName; _fontName = _globalFontName;
_fontSize = _globalFontSize; _fontSize = _globalFontSize;
@ -479,14 +479,14 @@ const std::string& MenuItemFont::getFontNameObj() const
//CCMenuItemSprite //CCMenuItemSprite
// //
void MenuItemSprite::setNormalImage(Node* pImage) void MenuItemSprite::setNormalImage(Node* image)
{ {
if (pImage != _normalImage) if (image != _normalImage)
{ {
if (pImage) if (image)
{ {
addChild(pImage, 0, kNormalTag); addChild(image, 0, kNormalTag);
pImage->setAnchorPoint(Point(0, 0)); image->setAnchorPoint(Point(0, 0));
} }
if (_normalImage) if (_normalImage)
@ -494,20 +494,20 @@ void MenuItemSprite::setNormalImage(Node* pImage)
removeChild(_normalImage, true); removeChild(_normalImage, true);
} }
_normalImage = pImage; _normalImage = image;
this->setContentSize(_normalImage->getContentSize()); this->setContentSize(_normalImage->getContentSize());
this->updateImagesVisibility(); this->updateImagesVisibility();
} }
} }
void MenuItemSprite::setSelectedImage(Node* pImage) void MenuItemSprite::setSelectedImage(Node* image)
{ {
if (pImage != _normalImage) if (image != _normalImage)
{ {
if (pImage) if (image)
{ {
addChild(pImage, 0, kSelectedTag); addChild(image, 0, kSelectedTag);
pImage->setAnchorPoint(Point(0, 0)); image->setAnchorPoint(Point(0, 0));
} }
if (_selectedImage) if (_selectedImage)
@ -515,19 +515,19 @@ void MenuItemSprite::setSelectedImage(Node* pImage)
removeChild(_selectedImage, true); removeChild(_selectedImage, true);
} }
_selectedImage = pImage; _selectedImage = image;
this->updateImagesVisibility(); this->updateImagesVisibility();
} }
} }
void MenuItemSprite::setDisabledImage(Node* pImage) void MenuItemSprite::setDisabledImage(Node* image)
{ {
if (pImage != _normalImage) if (image != _normalImage)
{ {
if (pImage) if (image)
{ {
addChild(pImage, 0, kDisableTag); addChild(image, 0, kDisableTag);
pImage->setAnchorPoint(Point(0, 0)); image->setAnchorPoint(Point(0, 0));
} }
if (_disabledImage) if (_disabledImage)
@ -535,7 +535,7 @@ void MenuItemSprite::setDisabledImage(Node* pImage)
removeChild(_disabledImage, true); removeChild(_disabledImage, true);
} }
_disabledImage = pImage; _disabledImage = image;
this->updateImagesVisibility(); this->updateImagesVisibility();
} }
} }
@ -552,12 +552,12 @@ MenuItemSprite * MenuItemSprite::create(Node* normalSprite, Node* selectedSprite
// XXX deprecated // XXX deprecated
MenuItemSprite * MenuItemSprite::create(Node* normalSprite, Node* selectedSprite, Object* target, SEL_MenuHandler selector) MenuItemSprite * MenuItemSprite::create(Node* normalSprite, Node* selectedSprite, Object* target, SEL_MenuHandler selector)
{ {
return MenuItemSprite::create(normalSprite, selectedSprite, NULL, target, selector); return MenuItemSprite::create(normalSprite, selectedSprite, nullptr, target, selector);
} }
MenuItemSprite * MenuItemSprite::create(Node* normalSprite, Node* selectedSprite, const ccMenuCallback& callback) MenuItemSprite * MenuItemSprite::create(Node* normalSprite, Node* selectedSprite, const ccMenuCallback& callback)
{ {
return MenuItemSprite::create(normalSprite, selectedSprite, NULL, callback); return MenuItemSprite::create(normalSprite, selectedSprite, nullptr, callback);
} }
// XXX deprecated // XXX deprecated
@ -696,7 +696,7 @@ MenuItemImage* MenuItemImage::create()
return ret; return ret;
} }
CC_SAFE_DELETE(ret); CC_SAFE_DELETE(ret);
return NULL; return nullptr;
} }
bool MenuItemImage::init(void) bool MenuItemImage::init(void)
@ -710,7 +710,7 @@ MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std:
} }
// XXX deprecated // XXX deprecated
MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, Object* target, SEL_MenuHandler selector) MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage, Object* target, SEL_MenuHandler selector)
{ {
return MenuItemImage::create(normalImage, selectedImage, "", target, selector); return MenuItemImage::create(normalImage, selectedImage, "", target, selector);
} }
@ -721,7 +721,7 @@ MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std:
} }
// XXX deprecated // XXX deprecated
MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector) MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, Object* target, SEL_MenuHandler selector)
{ {
MenuItemImage *ret = new MenuItemImage(); MenuItemImage *ret = new MenuItemImage();
if (ret && ret->initWithNormalImage(normalImage, selectedImage, disabledImage, target, selector)) if (ret && ret->initWithNormalImage(normalImage, selectedImage, disabledImage, target, selector))
@ -730,7 +730,7 @@ MenuItemImage * MenuItemImage::create(const char *normalImage, const char *selec
return ret; return ret;
} }
CC_SAFE_DELETE(ret); CC_SAFE_DELETE(ret);
return NULL; return nullptr;
} }
MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback) MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback)
@ -742,7 +742,7 @@ MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std:
return ret; return ret;
} }
CC_SAFE_DELETE(ret); CC_SAFE_DELETE(ret);
return NULL; return nullptr;
} }
MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage) MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage)
@ -754,11 +754,11 @@ MenuItemImage * MenuItemImage::create(const std::string& normalImage, const std:
return ret; return ret;
} }
CC_SAFE_DELETE(ret); CC_SAFE_DELETE(ret);
return NULL; return nullptr;
} }
// XXX: deprecated // XXX: deprecated
bool MenuItemImage::initWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector) bool MenuItemImage::initWithNormalImage(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, Object* target, SEL_MenuHandler selector)
{ {
_target = target; _target = target;
CC_SAFE_RETAIN(_target); CC_SAFE_RETAIN(_target);
@ -766,9 +766,9 @@ bool MenuItemImage::initWithNormalImage(const char *normalImage, const char *sel
} }
bool MenuItemImage::initWithNormalImage(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback) bool MenuItemImage::initWithNormalImage(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback)
{ {
Node *normalSprite = NULL; Node *normalSprite = nullptr;
Node *selectedSprite = NULL; Node *selectedSprite = nullptr;
Node *disabledSprite = NULL; Node *disabledSprite = nullptr;
if (normalImage.size() >0) if (normalImage.size() >0)
{ {
@ -856,7 +856,7 @@ MenuItemToggle * MenuItemToggle::createWithCallback(const ccMenuCallback &callba
MenuItemToggle * MenuItemToggle::create() MenuItemToggle * MenuItemToggle::create()
{ {
MenuItemToggle *ret = new MenuItemToggle(); MenuItemToggle *ret = new MenuItemToggle();
ret->initWithItem(NULL); ret->initWithItem(nullptr);
ret->autorelease(); ret->autorelease();
return ret; return ret;
} }
@ -918,9 +918,9 @@ void MenuItemToggle::addSubItem(MenuItem *item)
MenuItemToggle::~MenuItemToggle() MenuItemToggle::~MenuItemToggle()
{ {
_subItems.forEach([](MenuItem* item){ for(const auto &item : _subItems) {
item->cleanup(); item->cleanup();
}); }
} }
void MenuItemToggle::setSelectedIndex(unsigned int index) void MenuItemToggle::setSelectedIndex(unsigned int index)
@ -970,9 +970,9 @@ void MenuItemToggle::setEnabled(bool enabled)
{ {
MenuItem::setEnabled(enabled); MenuItem::setEnabled(enabled);
_subItems.forEach([&enabled](MenuItem* item){ for(const auto &item : _subItems) {
item->setEnabled(enabled); item->setEnabled(enabled);
}); }
} }
} }

View File

@ -56,7 +56,7 @@ class SpriteFrame;
* *
* Subclass MenuItem (or any subclass) to create your custom MenuItem objects. * Subclass MenuItem (or any subclass) to create your custom MenuItem objects.
*/ */
class CC_DLL MenuItem : public NodeRGBA class CC_DLL MenuItem : public Node
{ {
public: public:
/** Creates a MenuItem with no target/selector */ /** Creates a MenuItem with no target/selector */
@ -105,7 +105,7 @@ protected:
: _selected(false) : _selected(false)
, _enabled(false) , _enabled(false)
, _callback(nullptr) , _callback(nullptr)
, _target(NULL) , _target(nullptr)
{} {}
/** /**
* @js NA * @js NA
@ -181,7 +181,7 @@ protected:
*/ */
MenuItemLabel() MenuItemLabel()
: _originalScale(0.0) : _originalScale(0.0)
, _label(NULL) , _label(nullptr)
{} {}
/** /**
* @js NA * @js NA
@ -217,7 +217,7 @@ public:
/** creates a menu item from a string and atlas with a target/selector */ /** creates a menu item from a string and atlas with a target/selector */
static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap); static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap);
/** creates a menu item from a string and atlas. Use it with MenuItemToggle */ /** creates a menu item from a string and atlas. Use it with MenuItemToggle */
CC_DEPRECATED_ATTRIBUTE static MenuItemAtlasFont* create(const char* value, const char* charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector);
/** creates a menu item from a string and atlas. Use it with MenuItemToggle */ /** creates a menu item from a string and atlas. Use it with MenuItemToggle */
static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback); static MenuItemAtlasFont* create(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback);
@ -233,7 +233,7 @@ protected:
virtual ~MenuItemAtlasFont(){} virtual ~MenuItemAtlasFont(){}
/** initializes a menu item from a string and atlas with a target/selector */ /** initializes a menu item from a string and atlas with a target/selector */
CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, const char *charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE bool initWithString(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, Object* target, SEL_MenuHandler selector);
/** initializes a menu item from a string and atlas with a target/selector */ /** initializes a menu item from a string and atlas with a target/selector */
bool initWithString(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback); bool initWithString(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback);
@ -251,7 +251,7 @@ public:
/** creates a menu item from a string without target/selector. To be used with MenuItemToggle */ /** creates a menu item from a string without target/selector. To be used with MenuItemToggle */
static MenuItemFont * create(const std::string& value = ""); static MenuItemFont * create(const std::string& value = "");
/** creates a menu item from a string with a target/selector */ /** creates a menu item from a string with a target/selector */
CC_DEPRECATED_ATTRIBUTE static MenuItemFont * create(const char *value, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE static MenuItemFont * create(const std::string& value, Object* target, SEL_MenuHandler selector);
/** creates a menu item from a string with a target/selector */ /** creates a menu item from a string with a target/selector */
static MenuItemFont * create(const std::string& value, const ccMenuCallback& callback); static MenuItemFont * create(const std::string& value, const ccMenuCallback& callback);
@ -306,7 +306,7 @@ protected:
virtual ~MenuItemFont(); virtual ~MenuItemFont();
/** initializes a menu item from a string with a target/selector */ /** initializes a menu item from a string with a target/selector */
CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE bool initWithString(const std::string& value, Object* target, SEL_MenuHandler selector);
/** initializes a menu item from a string with a target/selector */ /** initializes a menu item from a string with a target/selector */
bool initWithString(const std::string& value, const ccMenuCallback& callback); bool initWithString(const std::string& value, const ccMenuCallback& callback);
@ -332,7 +332,7 @@ class CC_DLL MenuItemSprite : public MenuItem
{ {
public: public:
/** creates a menu item with a normal, selected and disabled image*/ /** creates a menu item with a normal, selected and disabled image*/
static MenuItemSprite * create(Node* normalSprite, Node* selectedSprite, Node* disabledSprite = NULL); static MenuItemSprite * create(Node* normalSprite, Node* selectedSprite, Node* disabledSprite = nullptr);
/** creates a menu item with a normal and selected image with target/selector */ /** creates a menu item with a normal and selected image with target/selector */
CC_DEPRECATED_ATTRIBUTE static MenuItemSprite * create(Node* normalSprite, Node* selectedSprite, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE static MenuItemSprite * create(Node* normalSprite, Node* selectedSprite, Object* target, SEL_MenuHandler selector);
/** creates a menu item with a normal,selected and disabled image with target/selector */ /** creates a menu item with a normal,selected and disabled image with target/selector */
@ -369,9 +369,9 @@ public:
protected: protected:
MenuItemSprite() MenuItemSprite()
:_normalImage(NULL) :_normalImage(nullptr)
,_selectedImage(NULL) ,_selectedImage(nullptr)
,_disabledImage(NULL) ,_disabledImage(nullptr)
{} {}
/** initializes a menu item with a normal, selected and disabled image with target/selector */ /** initializes a menu item with a normal, selected and disabled image with target/selector */
@ -411,12 +411,12 @@ public:
/** creates a menu item with a normal,selected and disabled image*/ /** creates a menu item with a normal,selected and disabled image*/
static MenuItemImage* create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage); static MenuItemImage* create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage);
/** creates a menu item with a normal and selected image with target/selector */ /** creates a menu item with a normal and selected image with target/selector */
CC_DEPRECATED_ATTRIBUTE static MenuItemImage* create(const char *normalImage, const char *selectedImage, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE static MenuItemImage* create(const std::string& normalImage, const std::string& selectedImage, Object* target, SEL_MenuHandler selector);
/** creates a menu item with a normal and selected image with a callable object */ /** creates a menu item with a normal and selected image with a callable object */
static MenuItemImage* create(const std::string&normalImage, const std::string&selectedImage, const ccMenuCallback& callback); static MenuItemImage* create(const std::string&normalImage, const std::string&selectedImage, const ccMenuCallback& callback);
/** creates a menu item with a normal,selected and disabled image with target/selector */ /** creates a menu item with a normal,selected and disabled image with target/selector */
CC_DEPRECATED_ATTRIBUTE static MenuItemImage* create(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE static MenuItemImage* create(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, Object* target, SEL_MenuHandler selector);
/** creates a menu item with a normal,selected and disabled image with a callable object */ /** creates a menu item with a normal,selected and disabled image with a callable object */
static MenuItemImage* create(const std::string&normalImage, const std::string&selectedImage, const std::string&disabledImage, const ccMenuCallback& callback); static MenuItemImage* create(const std::string&normalImage, const std::string&selectedImage, const std::string&disabledImage, const ccMenuCallback& callback);
@ -440,7 +440,7 @@ protected:
bool init(); bool init();
/** initializes a menu item with a normal, selected and disabled image with target/selector */ /** initializes a menu item with a normal, selected and disabled image with target/selector */
CC_DEPRECATED_ATTRIBUTE bool initWithNormalImage(const char *normalImage, const char *selectedImage, const char *disabledImage, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE bool initWithNormalImage(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, Object* target, SEL_MenuHandler selector);
/** initializes a menu item with a normal, selected and disabled image with a callable object */ /** initializes a menu item with a normal, selected and disabled image with a callable object */
bool initWithNormalImage(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback); bool initWithNormalImage(const std::string& normalImage, const std::string& selectedImage, const std::string& disabledImage, const ccMenuCallback& callback);

View File

@ -30,13 +30,15 @@ THE SOFTWARE.
#include "ccMacros.h" #include "ccMacros.h"
#include "CCDirector.h" #include "CCDirector.h"
#include "CCVertex.h" #include "CCVertex.h"
#include "CCCustomCommand.h"
#include "CCRenderer.h"
NS_CC_BEGIN NS_CC_BEGIN
MotionStreak::MotionStreak() MotionStreak::MotionStreak()
: _fastMode(false) : _fastMode(false)
, _startingPositionInitialized(false) , _startingPositionInitialized(false)
, _texture(NULL) , _texture(nullptr)
, _blendFunc(BlendFunc::ALPHA_NON_PREMULTIPLIED) , _blendFunc(BlendFunc::ALPHA_NON_PREMULTIPLIED)
, _positionR(Point::ZERO) , _positionR(Point::ZERO)
, _stroke(0.0f) , _stroke(0.0f)
@ -45,11 +47,11 @@ MotionStreak::MotionStreak()
, _maxPoints(0) , _maxPoints(0)
, _nuPoints(0) , _nuPoints(0)
, _previousNuPoints(0) , _previousNuPoints(0)
, _pointVertexes(NULL) , _pointVertexes(nullptr)
, _pointState(NULL) , _pointState(nullptr)
, _vertices(NULL) , _vertices(nullptr)
, _colorPointer(NULL) , _colorPointer(nullptr)
, _texCoords(NULL) , _texCoords(nullptr)
{ {
} }
@ -63,35 +65,35 @@ MotionStreak::~MotionStreak()
CC_SAFE_FREE(_texCoords); CC_SAFE_FREE(_texCoords);
} }
MotionStreak* MotionStreak::create(float fade, float minSeg, float stroke, const Color3B& color, const char* path) MotionStreak* MotionStreak::create(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path)
{ {
MotionStreak *pRet = new MotionStreak(); MotionStreak *ret = new MotionStreak();
if (pRet && pRet->initWithFade(fade, minSeg, stroke, color, path)) if (ret && ret->initWithFade(fade, minSeg, stroke, color, path))
{ {
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return nullptr;
} }
MotionStreak* MotionStreak::create(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture) MotionStreak* MotionStreak::create(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture)
{ {
MotionStreak *pRet = new MotionStreak(); MotionStreak *ret = new MotionStreak();
if (pRet && pRet->initWithFade(fade, minSeg, stroke, color, texture)) if (ret && ret->initWithFade(fade, minSeg, stroke, color, texture))
{ {
pRet->autorelease(); ret->autorelease();
return pRet; return ret;
} }
CC_SAFE_DELETE(pRet); CC_SAFE_DELETE(ret);
return NULL; return nullptr;
} }
bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const char* path) bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path)
{ {
CCASSERT(path != NULL, "Invalid filename"); CCASSERT(!path.empty(), "Invalid filename");
Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(path); Texture2D *texture = Director::getInstance()->getTextureCache()->addImage(path);
return initWithFade(fade, minSeg, stroke, color, texture); return initWithFade(fade, minSeg, stroke, color, texture);
@ -322,12 +324,10 @@ void MotionStreak::reset()
_nuPoints = 0; _nuPoints = 0;
} }
void MotionStreak::draw() void MotionStreak::onDraw()
{ {
if(_nuPoints <= 1) getShaderProgram()->use();
return; getShaderProgram()->setUniformsForBuiltins(_cachedMV);
CC_NODE_DRAW_SETUP();
GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX ); GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX );
GL::blendFunc( _blendFunc.src, _blendFunc.dst ); GL::blendFunc( _blendFunc.src, _blendFunc.dst );
@ -351,8 +351,17 @@ void MotionStreak::draw()
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
glDrawArrays(GL_TRIANGLE_STRIP, 0, (GLsizei)_nuPoints*2); glDrawArrays(GL_TRIANGLE_STRIP, 0, (GLsizei)_nuPoints*2);
}
void MotionStreak::draw()
{
if(_nuPoints <= 1)
return;
kmGLGetMatrix(KM_GL_MODELVIEW,&_cachedMV);
_customCommand.init(0,_vertexZ);
_customCommand.func = CC_CALLBACK_0(MotionStreak::onDraw, this);
Director::getInstance()->getRenderer()->addCommand(&_customCommand);
CC_INCREMENT_GL_DRAWS(1);
} }
NS_CC_END NS_CC_END

View File

@ -29,6 +29,7 @@ THE SOFTWARE.
#include "CCTexture2D.h" #include "CCTexture2D.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "CCNode.h" #include "CCNode.h"
#include "renderer/CCCustomCommand.h"
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
#include "CCGLBufferedNode.h" #include "CCGLBufferedNode.h"
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
@ -43,14 +44,14 @@ NS_CC_BEGIN
/** MotionStreak. /** MotionStreak.
Creates a trailing path. Creates a trailing path.
*/ */
class CC_DLL MotionStreak : public NodeRGBA, public TextureProtocol class CC_DLL MotionStreak : public Node, public TextureProtocol
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
, public GLBufferedNode , public GLBufferedNode
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
{ {
public: public:
/** creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture filename */ /** creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture filename */
static MotionStreak* create(float fade, float minSeg, float stroke, const Color3B& color, const char* path); static MotionStreak* create(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path);
/** creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture */ /** creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture */
static MotionStreak* create(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture); static MotionStreak* create(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture);
@ -99,6 +100,11 @@ public:
virtual void setOpacityModifyRGB(bool value) override; virtual void setOpacityModifyRGB(bool value) override;
virtual bool isOpacityModifyRGB() const override; virtual bool isOpacityModifyRGB() const override;
protected:
kmMat4 _cachedMV;
//renderer callback
void onDraw();
protected: protected:
/** /**
* @js ctor * @js ctor
@ -111,7 +117,7 @@ protected:
virtual ~MotionStreak(); virtual ~MotionStreak();
/** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename */ /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture filename */
bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const char* path); bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, const std::string& path);
/** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */ /** initializes a motion streak with fade in seconds, minimum segments, stroke's width, color and texture */
bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture); bool initWithFade(float fade, float minSeg, float stroke, const Color3B& color, Texture2D* texture);
@ -139,6 +145,8 @@ protected:
Vertex2F* _vertices; Vertex2F* _vertices;
GLubyte* _colorPointer; GLubyte* _colorPointer;
Tex2F* _texCoords; Tex2F* _texCoords;
CustomCommand _customCommand;
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(MotionStreak); CC_DISALLOW_COPY_AND_ASSIGN(MotionStreak);

File diff suppressed because it is too large Load Diff

View File

@ -39,22 +39,22 @@
#include "CCProtocols.h" #include "CCProtocols.h"
#include "CCEventDispatcher.h" #include "CCEventDispatcher.h"
#include "CCVector.h" #include "CCVector.h"
#include "kazmath/kazmath.h"
NS_CC_BEGIN NS_CC_BEGIN
class Camera;
class GridBase; class GridBase;
class Point; class Point;
class Touch; class Touch;
class Action; class Action;
class RGBAProtocol;
class LabelProtocol; class LabelProtocol;
class Scheduler; class Scheduler;
class ActionManager; class ActionManager;
class Component; class Component;
class ComponentContainer; class ComponentContainer;
class EventDispatcher; class EventDispatcher;
#ifdef CC_USE_PHYSICS class Scene;
#if CC_USE_PHYSICS
class PhysicsBody; class PhysicsBody;
#endif #endif
@ -98,7 +98,6 @@ class EventListener;
- position - position
- scale (x, y) - scale (x, y)
- rotation (in degrees, clockwise) - rotation (in degrees, clockwise)
- Camera (an interface to gluLookAt )
- GridBase (to do mesh transformations) - GridBase (to do mesh transformations)
- anchor point - anchor point
- size - size
@ -120,18 +119,14 @@ class EventListener;
-# The node will be translated (position) -# The node will be translated (position)
-# The node will be rotated (rotation) -# The node will be rotated (rotation)
-# The node will be scaled (scale) -# The node will be scaled (scale)
-# The node will be moved according to the camera values (camera)
Order in transformations with grid enabled Order in transformations with grid enabled
-# The node will be translated (position) -# The node will be translated (position)
-# The node will be rotated (rotation) -# The node will be rotated (rotation)
-# The node will be scaled (scale) -# The node will be scaled (scale)
-# The grid will capture the screen -# The grid will capture the screen
-# The node will be moved according to the camera values (camera)
-# The grid will render the captured screen -# The grid will render the captured screen
Camera:
- Each node has a camera. By default it points to the center of the Node.
*/ */
class CC_DLL Node : public Object class CC_DLL Node : public Object
@ -595,14 +590,14 @@ public:
* *
* @return a Node object whose tag equals to the input parameter * @return a Node object whose tag equals to the input parameter
*/ */
Node * getChildByTag(int tag); virtual Node * getChildByTag(int tag);
/** /**
* Return an array of children * Return an array of children
* *
* Composing a "tree" structure is a very important feature of Node * Composing a "tree" structure is a very important feature of Node
* Here's a sample code of traversing children array: * Here's a sample code of traversing children array:
@code @code
Node* node = NULL; Node* node = nullptr;
CCARRAY_FOREACH(parent->getChildren(), node) CCARRAY_FOREACH(parent->getChildren(), node)
{ {
node->setPosition(0,0); node->setPosition(0,0);
@ -620,7 +615,7 @@ public:
* *
* @return The amount of children. * @return The amount of children.
*/ */
ssize_t getChildrenCount() const; virtual ssize_t getChildrenCount() const;
/** /**
* Sets the parent node * Sets the parent node
@ -702,34 +697,7 @@ public:
virtual void sortAllChildren(); virtual void sortAllChildren();
/// @} end of Children and Parent /// @} end of Children and Parent
/// @{
/// @name Grid object for effects
/**
* Returns a grid object that is used when applying effects
*
* @return A Grid object that is used when applying effects
* @js NA
*/
virtual GridBase* getGrid() { return _grid; }
/**
* @js NA
*/
virtual const GridBase* getGrid() const { return _grid; }
/**
* Changes a grid object that is used when applying effects
*
* @param grid A Grid object that is used when applying effects
*/
virtual void setGrid(GridBase *grid);
/// @} end of Grid
/// @{ /// @{
/// @name Tag & User data /// @name Tag & User data
@ -749,7 +717,7 @@ public:
parent->addChild(node2); parent->addChild(node2);
parent->addChild(node3); parent->addChild(node3);
// identify by tags // identify by tags
Node* node = NULL; Node* node = nullptr;
CCARRAY_FOREACH(parent->getChildren(), node) CCARRAY_FOREACH(parent->getChildren(), node)
{ {
switch(node->getTag()) switch(node->getTag())
@ -861,19 +829,6 @@ public:
/// @} end of Shader Program /// @} end of Shader Program
/**
* Returns a camera object that lets you move the node using a gluLookAt
*
@code
Camera* camera = node->getCamera();
camera->setEye(0, 0, 415/2);
camera->setCenter(0, 0, 0);
@endcode
*
* @return A Camera object that lets you move the node using a gluLookAt
*/
virtual Camera* getCamera();
/** /**
* Returns whether or not the node accepts event callbacks. * Returns whether or not the node accepts event callbacks.
* *
@ -956,6 +911,11 @@ public:
*/ */
virtual void visit(); virtual void visit();
/** Returns the Scene that contains the Node.
It returns `nullptr` if the node doesn't belong to any Scene.
This function recursively calls parent->getScene() until parent is a Scene object. The results are not cached. It is that the user caches the results in case this functions is being used inside a loop.
*/
virtual Scene* getScene();
/** /**
* Returns a "local" axis aligned bounding box of the node. * Returns a "local" axis aligned bounding box of the node.
@ -1226,35 +1186,45 @@ public:
* Returns the matrix that transform the node's (local) space coordinates into the parent's space coordinates. * Returns the matrix that transform the node's (local) space coordinates into the parent's space coordinates.
* The matrix is in Pixels. * The matrix is in Pixels.
*/ */
virtual const AffineTransform& getNodeToParentTransform() const; virtual const kmMat4& getNodeToParentTransform() const;
virtual AffineTransform getNodeToParentAffineTransform() const;
/**
* Sets the Transformation matrix manually.
*/
virtual void setNodeToParentTransform(const kmMat4& transform);
/** @deprecated use getNodeToParentTransform() instead */ /** @deprecated use getNodeToParentTransform() instead */
CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform nodeToParentTransform() const { return getNodeToParentTransform(); } CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform nodeToParentTransform() const { return getNodeToParentAffineTransform(); }
/** /**
* Returns the matrix that transform parent's space coordinates to the node's (local) space coordinates. * Returns the matrix that transform parent's space coordinates to the node's (local) space coordinates.
* The matrix is in Pixels. * The matrix is in Pixels.
*/ */
virtual const AffineTransform& getParentToNodeTransform() const; virtual const kmMat4& getParentToNodeTransform() const;
virtual AffineTransform getParentToNodeAffineTransform() const;
/** @deprecated Use getParentToNodeTransform() instead */ /** @deprecated Use getParentToNodeTransform() instead */
CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform parentToNodeTransform() const { return getParentToNodeTransform(); } CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform parentToNodeTransform() const { return getParentToNodeAffineTransform(); }
/** /**
* Returns the world affine transform matrix. The matrix is in Pixels. * Returns the world affine transform matrix. The matrix is in Pixels.
*/ */
virtual AffineTransform getNodeToWorldTransform() const; virtual kmMat4 getNodeToWorldTransform() const;
virtual AffineTransform getNodeToWorldAffineTransform() const;
/** @deprecated Use getNodeToWorldTransform() instead */ /** @deprecated Use getNodeToWorldTransform() instead */
CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform nodeToWorldTransform() const { return getNodeToWorldTransform(); } CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform nodeToWorldTransform() const { return getNodeToWorldAffineTransform(); }
/** /**
* Returns the inverse world affine transform matrix. The matrix is in Pixels. * Returns the inverse world affine transform matrix. The matrix is in Pixels.
*/ */
virtual AffineTransform getWorldToNodeTransform() const; virtual kmMat4 getWorldToNodeTransform() const;
virtual AffineTransform getWorldToNodeAffineTransform() const;
/** @deprecated Use worldToNodeTransform() instead */ /** @deprecated Use worldToNodeTransform() instead */
CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform worldToNodeTransform() const { return getWorldToNodeTransform(); } CC_DEPRECATED_ATTRIBUTE inline virtual AffineTransform worldToNodeTransform() const { return getWorldToNodeAffineTransform(); }
/// @} end of Transformations /// @} end of Transformations
@ -1343,6 +1313,7 @@ public:
@endcode @endcode
*/ */
void setAdditionalTransform(const AffineTransform& additionalTransform); void setAdditionalTransform(const AffineTransform& additionalTransform);
void setAdditionalTransform(const kmMat4& additionalTransform);
/// @} end of Coordinate Converters /// @} end of Coordinate Converters
@ -1351,7 +1322,7 @@ public:
/** /**
* gets a component by its name * gets a component by its name
*/ */
Component* getComponent(const char *pName); Component* getComponent(const std::string& pName);
/** /**
* adds a component * adds a component
@ -1361,7 +1332,7 @@ public:
/** /**
* removes a component by its name * removes a component by its name
*/ */
virtual bool removeComponent(const char *pName); virtual bool removeComponent(const std::string& pName);
/** /**
* removes all components * removes all components
@ -1370,7 +1341,7 @@ public:
/// @} end of component functions /// @} end of component functions
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
/** /**
* set the PhysicsBody that let the sprite effect with physics * set the PhysicsBody that let the sprite effect with physics
*/ */
@ -1387,6 +1358,24 @@ public:
virtual bool updatePhysicsTransform(); virtual bool updatePhysicsTransform();
#endif #endif
// overrides
virtual GLubyte getOpacity() const;
virtual GLubyte getDisplayedOpacity() const;
virtual void setOpacity(GLubyte opacity);
virtual void updateDisplayedOpacity(GLubyte parentOpacity);
virtual bool isCascadeOpacityEnabled() const;
virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled);
virtual const Color3B& getColor(void) const;
virtual const Color3B& getDisplayedColor() const;
virtual void setColor(const Color3B& color);
virtual void updateDisplayedColor(const Color3B& parentColor);
virtual bool isCascadeColorEnabled() const;
virtual void setCascadeColorEnabled(bool cascadeColorEnabled);
virtual void setOpacityModifyRGB(bool bValue) {CC_UNUSED_PARAM(bValue);}
virtual bool isOpacityModifyRGB() const { return false; };
protected: protected:
// Nodes should be created using create(); // Nodes should be created using create();
@ -1405,6 +1394,12 @@ protected:
/// 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;
virtual void updateCascadeOpacity();
virtual void disableCascadeOpacity();
virtual void updateCascadeColor();
virtual void disableCascadeColor();
virtual void updateColor() {}
float _rotationX; ///< rotation angle on x-axis float _rotationX; ///< rotation angle on x-axis
@ -1426,17 +1421,14 @@ protected:
Size _contentSize; ///< untransformed size of the node Size _contentSize; ///< untransformed size of the node
// "cache" variables are allowed to be mutable // "cache" variables are allowed to be mutable
mutable AffineTransform _additionalTransform; ///< transform mutable kmMat4 _additionalTransform; ///< transform
mutable AffineTransform _transform; ///< transform mutable kmMat4 _transform; ///< transform
mutable AffineTransform _inverse; ///< inverse transform mutable kmMat4 _inverse; ///< inverse transform
kmMat4 _modelViewTransform; ///< ModelView transform of the Node.
mutable bool _additionalTransformDirty; ///< The flag to check whether the additional transform is dirty mutable bool _additionalTransformDirty; ///< The flag to check whether the additional transform is dirty
mutable bool _transformDirty; ///< transform dirty flag mutable bool _transformDirty; ///< transform dirty flag
mutable bool _inverseDirty; ///< inverse transform dirty flag mutable bool _inverseDirty; ///< inverse transform dirty flag
Camera *_camera; ///< a camera
GridBase *_grid; ///< a grid
int _ZOrder; ///< z-order value that affects the draw order int _ZOrder; ///< z-order value that affects the draw order
Vector<Node*> _children; ///< array of children nodes Vector<Node*> _children; ///< array of children nodes
@ -1473,9 +1465,17 @@ protected:
ComponentContainer *_componentContainer; ///< Dictionary of components ComponentContainer *_componentContainer; ///< Dictionary of components
#ifdef CC_USE_PHYSICS #if CC_USE_PHYSICS
PhysicsBody* _physicsBody; ///< the physicsBody the node have PhysicsBody* _physicsBody; ///< the physicsBody the node have
#endif #endif
// opacity controls
GLubyte _displayedOpacity;
GLubyte _realOpacity;
Color3B _displayedColor;
Color3B _realColor;
bool _cascadeColorEnabled;
bool _cascadeOpacityEnabled;
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(Node); CC_DISALLOW_COPY_AND_ASSIGN(Node);
@ -1484,49 +1484,41 @@ private:
//#pragma mark - NodeRGBA //#pragma mark - NodeRGBA
/** NodeRGBA is a subclass of Node that implements the RGBAProtocol protocol. /** NodeRGBA is a subclass of Node that implements the RGBAProtocol protocol.
All features from Node are valid, plus the following new features: All features from Node are valid, plus the following new features:
- opacity - opacity
- RGB colors - RGB colors
Opacity/Color propagates into children that conform to the RGBAProtocol if cascadeOpacity/cascadeColor is enabled. Opacity/Color propagates into children that conform to the RGBAProtocol if cascadeOpacity/cascadeColor is enabled.
@since v2.1 @since v2.1
*/ */
class CC_DLL NodeRGBA : public Node, public RGBAProtocol class CC_DLL __NodeRGBA : public Node, public __RGBAProtocol
{ {
public: public:
// overrides // overrides
virtual GLubyte getOpacity() const override; virtual GLubyte getOpacity() const override { return Node::getOpacity(); }
virtual GLubyte getDisplayedOpacity() const override; virtual GLubyte getDisplayedOpacity() const override { return Node::getDisplayedOpacity(); }
virtual void setOpacity(GLubyte opacity) override; virtual void setOpacity(GLubyte opacity) override { return Node::setOpacity(opacity); }
virtual void updateDisplayedOpacity(GLubyte parentOpacity) override; virtual void updateDisplayedOpacity(GLubyte parentOpacity) override { return Node::updateDisplayedOpacity(parentOpacity); }
virtual bool isCascadeOpacityEnabled() const override; virtual bool isCascadeOpacityEnabled() const override { return Node::isCascadeOpacityEnabled(); }
virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled) override; virtual void setCascadeOpacityEnabled(bool cascadeOpacityEnabled) override { return Node::setCascadeOpacityEnabled(cascadeOpacityEnabled); }
virtual const Color3B& getColor(void) const override; virtual const Color3B& getColor(void) const override { return Node::getColor(); }
virtual const Color3B& getDisplayedColor() const override; virtual const Color3B& getDisplayedColor() const override { return Node::getDisplayedColor(); }
virtual void setColor(const Color3B& color) override; virtual void setColor(const Color3B& color) override { return Node::setColor(color); }
virtual void updateDisplayedColor(const Color3B& parentColor) override; virtual void updateDisplayedColor(const Color3B& parentColor) override { return Node::updateDisplayedColor(parentColor); }
virtual bool isCascadeColorEnabled() const override; virtual bool isCascadeColorEnabled() const override { return Node::isCascadeColorEnabled(); }
virtual void setCascadeColorEnabled(bool cascadeColorEnabled) override; virtual void setCascadeColorEnabled(bool cascadeColorEnabled) override { return Node::setCascadeColorEnabled(cascadeColorEnabled); }
virtual void setOpacityModifyRGB(bool bValue) override {CC_UNUSED_PARAM(bValue);}; virtual void setOpacityModifyRGB(bool bValue) override { return Node::setOpacityModifyRGB(bValue); }
virtual bool isOpacityModifyRGB() const override { return false; }; virtual bool isOpacityModifyRGB() const override { return Node::isOpacityModifyRGB(); }
protected: protected:
NodeRGBA(); __NodeRGBA();
virtual ~NodeRGBA(); virtual ~__NodeRGBA() {}
virtual bool init();
GLubyte _displayedOpacity;
GLubyte _realOpacity;
Color3B _displayedColor;
Color3B _realColor;
bool _cascadeColorEnabled;
bool _cascadeOpacityEnabled;
private: private:
CC_DISALLOW_COPY_AND_ASSIGN(NodeRGBA); CC_DISALLOW_COPY_AND_ASSIGN(__NodeRGBA);
}; };
// end of base_node group // end of base_node group

171
cocos/2d/CCNodeGrid.cpp Normal file
View File

@ -0,0 +1,171 @@
/****************************************************************************
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 "CCNodeGrid.h"
#include "CCGrid.h"
#include "CCGroupCommand.h"
#include "CCRenderer.h"
#include "CCCustomCommand.h"
NS_CC_BEGIN
NodeGrid* NodeGrid::create()
{
NodeGrid * ret = new NodeGrid();
if (ret && ret->init())
{
ret->autorelease();
}
else
{
CC_SAFE_DELETE(ret);
}
return ret;
}
NodeGrid::NodeGrid()
: _gridTarget(nullptr)
, _nodeGrid(nullptr)
{
}
void NodeGrid::setTarget(Node* target)
{
CC_SAFE_RELEASE(_gridTarget);
CC_SAFE_RETAIN(target);
_gridTarget = target;
}
NodeGrid::~NodeGrid()
{
CC_SAFE_RELEASE(_nodeGrid);
CC_SAFE_RELEASE(_gridTarget);
}
void NodeGrid::onGridBeginDraw()
{
if (_nodeGrid && _nodeGrid->isActive())
{
_nodeGrid->beforeDraw();
}
}
void NodeGrid::onGridEndDraw()
{
if(_nodeGrid && _nodeGrid->isActive())
{
_nodeGrid->afterDraw(this);
}
}
void NodeGrid::visit()
{
// quick return if not visible. children won't be drawn.
if (!_visible)
{
return;
}
Renderer* renderer = Director::getInstance()->getRenderer();
_groupCommand.init(0,_vertexZ);
renderer->addCommand(&_groupCommand);
renderer->pushGroup(_groupCommand.getRenderQueueID());
kmGLPushMatrix();
Director::Projection beforeProjectionType;
if(_nodeGrid && _nodeGrid->isActive())
{
beforeProjectionType = Director::getInstance()->getProjection();
_nodeGrid->set2DProjection();
}
_gridBeginCommand.init(0,_vertexZ);
_gridBeginCommand.func = CC_CALLBACK_0(NodeGrid::onGridBeginDraw, this);
renderer->addCommand(&_gridBeginCommand);
this->transform();
if(_gridTarget)
{
_gridTarget->visit();
}
int i = 0;
if(!_children.empty())
{
sortAllChildren();
// draw children zOrder < 0
for( ; i < _children.size(); i++ )
{
auto node = _children.at(i);
if ( node && node->getZOrder() < 0 )
node->visit();
else
break;
}
// self draw,currently we have nothing to draw on NodeGrid, so there is no need to add render command
this->draw();
for(auto it=_children.cbegin()+i; it != _children.cend(); ++it) {
(*it)->visit();
}
}
else
{
this->draw();
}
// reset for next frame
_orderOfArrival = 0;
if(_nodeGrid && _nodeGrid->isActive())
{
// restore projection
Director *director = Director::getInstance();
director->setProjection(beforeProjectionType);
}
_gridEndCommand.init(0,_vertexZ);
_gridEndCommand.func = CC_CALLBACK_0(NodeGrid::onGridEndDraw, this);
renderer->addCommand(&_gridEndCommand);
renderer->popGroup();
kmGLPopMatrix();
}
void NodeGrid::setGrid(GridBase *grid)
{
CC_SAFE_RELEASE(_nodeGrid);
CC_SAFE_RETAIN(grid);
_nodeGrid = grid;
}
NS_CC_END

78
cocos/2d/CCNodeGrid.h Normal file
View File

@ -0,0 +1,78 @@
/****************************************************************************
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 __MISCNODE_CCGRID_NODE_H__
#define __MISCNODE_CCGRID_NODE_H__
#include "CCNode.h"
#include "kazmath/GL/matrix.h"
#include "renderer/CCGroupCommand.h"
#include "renderer/CCCustomCommand.h"
NS_CC_BEGIN
class GridBase;
class NodeGrid : public Node
{
public:
static NodeGrid* create();
GridBase* getGrid() { return _nodeGrid; }
/**
* @js NA
*/
const GridBase* getGrid() const { return _nodeGrid; }
/**
* Changes a grid object that is used when applying effects
*
* @param grid A Grid object that is used when applying effects
*/
void setGrid(GridBase *grid);
void setTarget(Node *target);
// overrides
virtual void visit() override;
protected:
NodeGrid();
virtual ~NodeGrid();
void onGridBeginDraw();
void onGridEndDraw();
Node* _gridTarget;
GridBase* _nodeGrid;
GroupCommand _groupCommand;
CustomCommand _gridBeginCommand;
CustomCommand _gridEndCommand;
private:
CC_DISALLOW_COPY_AND_ASSIGN(NodeGrid);
};
NS_CC_END
#endif

View File

@ -31,7 +31,7 @@ using namespace std;
NS_CC_BEGIN NS_CC_BEGIN
static NotificationCenter *s_sharedNotifCenter = NULL; static NotificationCenter *s_sharedNotifCenter = nullptr;
NotificationCenter::NotificationCenter() NotificationCenter::NotificationCenter()
: _scriptHandler(0) : _scriptHandler(0)
@ -74,16 +74,16 @@ void NotificationCenter::purgeNotificationCenter(void)
// //
// internal functions // internal functions
// //
bool NotificationCenter::observerExisted(Object *target,const char *name, Object *sender) bool NotificationCenter::observerExisted(Object *target, const std::string& name, Object *sender)
{ {
Object* obj = NULL; Object* obj = nullptr;
CCARRAY_FOREACH(_observers, obj) CCARRAY_FOREACH(_observers, obj)
{ {
NotificationObserver* observer = (NotificationObserver*) obj; NotificationObserver* observer = (NotificationObserver*) obj;
if (!observer) if (!observer)
continue; continue;
if (!strcmp(observer->getName(),name) && observer->getTarget() == target && observer->getSender() == sender) if (observer->getName() == name && observer->getTarget() == target && observer->getSender() == sender)
return true; return true;
} }
return false; return false;
@ -94,7 +94,7 @@ bool NotificationCenter::observerExisted(Object *target,const char *name, Object
// //
void NotificationCenter::addObserver(Object *target, void NotificationCenter::addObserver(Object *target,
SEL_CallFuncO selector, SEL_CallFuncO selector,
const char *name, const std::string& name,
Object *sender) Object *sender)
{ {
if (this->observerExisted(target, name, sender)) if (this->observerExisted(target, name, sender))
@ -108,16 +108,16 @@ void NotificationCenter::addObserver(Object *target,
_observers->addObject(observer); _observers->addObject(observer);
} }
void NotificationCenter::removeObserver(Object *target,const char *name) void NotificationCenter::removeObserver(Object *target, const std::string& name)
{ {
Object* obj = NULL; Object* obj = nullptr;
CCARRAY_FOREACH(_observers, obj) CCARRAY_FOREACH(_observers, obj)
{ {
NotificationObserver* observer = static_cast<NotificationObserver*>(obj); NotificationObserver* observer = static_cast<NotificationObserver*>(obj);
if (!observer) if (!observer)
continue; continue;
if (!strcmp(observer->getName(),name) && observer->getTarget() == target) if (observer->getName() == name && observer->getTarget() == target)
{ {
_observers->removeObject(observer); _observers->removeObject(observer);
return; return;
@ -127,7 +127,7 @@ void NotificationCenter::removeObserver(Object *target,const char *name)
int NotificationCenter::removeAllObservers(Object *target) int NotificationCenter::removeAllObservers(Object *target)
{ {
Object *obj = NULL; Object *obj = nullptr;
__Array *toRemove = __Array::create(); __Array *toRemove = __Array::create();
CCARRAY_FOREACH(_observers, obj) CCARRAY_FOREACH(_observers, obj)
@ -146,13 +146,13 @@ int NotificationCenter::removeAllObservers(Object *target)
return static_cast<int>(toRemove->count()); return static_cast<int>(toRemove->count());
} }
void NotificationCenter::registerScriptObserver( Object *target, int handler,const char* name) void NotificationCenter::registerScriptObserver( Object *target, int handler,const std::string& name)
{ {
if (this->observerExisted(target, name, NULL)) if (this->observerExisted(target, name, nullptr))
return; return;
NotificationObserver *observer = new NotificationObserver(target, NULL, name, NULL); NotificationObserver *observer = new NotificationObserver(target, nullptr, name, nullptr);
if (!observer) if (!observer)
return; return;
@ -161,42 +161,36 @@ void NotificationCenter::registerScriptObserver( Object *target, int handler,con
_observers->addObject(observer); _observers->addObject(observer);
} }
void NotificationCenter::unregisterScriptObserver(Object *target,const char* name) void NotificationCenter::unregisterScriptObserver(Object *target,const std::string& name)
{ {
Object* obj = NULL; Object* obj = nullptr;
CCARRAY_FOREACH(_observers, obj) CCARRAY_FOREACH(_observers, obj)
{ {
NotificationObserver* observer = static_cast<NotificationObserver*>(obj); NotificationObserver* observer = static_cast<NotificationObserver*>(obj);
if (!observer) if (!observer)
continue; continue;
if ( !strcmp(observer->getName(),name) && observer->getTarget() == target) if ( observer->getName() == name && observer->getTarget() == target)
{ {
_observers->removeObject(observer); _observers->removeObject(observer);
} }
} }
} }
void NotificationCenter::postNotification(const char *name, Object *sender) void NotificationCenter::postNotification(const std::string& name, Object *sender)
{ {
__Array* ObserversCopy = __Array::createWithCapacity(_observers->count()); __Array* ObserversCopy = __Array::createWithCapacity(_observers->count());
ObserversCopy->addObjectsFromArray(_observers); ObserversCopy->addObjectsFromArray(_observers);
Object* obj = NULL; Object* obj = nullptr;
CCARRAY_FOREACH(ObserversCopy, obj) CCARRAY_FOREACH(ObserversCopy, obj)
{ {
NotificationObserver* observer = static_cast<NotificationObserver*>(obj); NotificationObserver* observer = static_cast<NotificationObserver*>(obj);
if (!observer) if (!observer)
continue; continue;
if (!strcmp(name,observer->getName()) && (observer->getSender() == sender || observer->getSender() == NULL || sender == NULL)) if (observer->getName() == name && (observer->getSender() == sender || observer->getSender() == nullptr || sender == nullptr))
{ {
if (0 != observer->getHandler()) if (0 == observer->getHandler())
{
BasicScriptData data(this, (void*)name);
ScriptEvent scriptEvent(kNotificationEvent,(void*)&data);
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&scriptEvent);
}
else
{ {
observer->performSelector(sender); observer->performSelector(sender);
} }
@ -204,26 +198,26 @@ void NotificationCenter::postNotification(const char *name, Object *sender)
} }
} }
void NotificationCenter::postNotification(const char *name) void NotificationCenter::postNotification(const std::string& name)
{ {
this->postNotification(name,NULL); this->postNotification(name,nullptr);
} }
int NotificationCenter::getObserverHandlerByName(const char* name) int NotificationCenter::getObserverHandlerByName(const std::string& name)
{ {
if (NULL == name || strlen(name) == 0) if (name.empty())
{ {
return 0; return 0;
} }
Object* obj = NULL; Object* obj = nullptr;
CCARRAY_FOREACH(_observers, obj) CCARRAY_FOREACH(_observers, obj)
{ {
NotificationObserver* observer = static_cast<NotificationObserver*>(obj); NotificationObserver* observer = static_cast<NotificationObserver*>(obj);
if (NULL == observer) if (nullptr == observer)
continue; continue;
if ( 0 == strcmp(observer->getName(),name) ) if ( observer->getName() == name )
{ {
return observer->getHandler(); return observer->getHandler();
break; break;
@ -240,7 +234,7 @@ int NotificationCenter::getObserverHandlerByName(const char* name)
//////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////
NotificationObserver::NotificationObserver(Object *target, NotificationObserver::NotificationObserver(Object *target,
SEL_CallFuncO selector, SEL_CallFuncO selector,
const char *name, const std::string& name,
Object *sender) Object *sender)
{ {
_target = target; _target = target;
@ -278,9 +272,9 @@ SEL_CallFuncO NotificationObserver::getSelector() const
return _selector; return _selector;
} }
const char* NotificationObserver::getName() const const std::string& NotificationObserver::getName() const
{ {
return _name.c_str(); return _name;
} }
Object* NotificationObserver::getSender() const Object* NotificationObserver::getSender() const

View File

@ -63,18 +63,18 @@ 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 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. * @param sender The object whose notifications the target wants to receive. Only notifications sent by this sender are delivered to the target. nullptr 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 std::string& name,
Object *sender); 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.
* @param name The name of this notification. * @param name The name of this notification.
*/ */
void removeObserver(Object *target,const char *name); void removeObserver(Object *target,const std::string& name);
/** @brief Removes all notifications registered by this target /** @brief Removes all notifications registered by this target
* @param target The target of this notification. * @param target The target of this notification.
@ -86,21 +86,21 @@ public:
* @note Only supports Lua Binding now. * @note Only supports Lua Binding now.
* @param handler The lua handler. * @param handler The lua handler.
*/ */
void registerScriptObserver(Object *target,int handler,const char* name); void registerScriptObserver(Object *target,int handler,const std::string& name);
/** Unregisters script observer */ /** Unregisters script observer */
void unregisterScriptObserver(Object *target,const char* name); void unregisterScriptObserver(Object *target,const std::string& name);
/** @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.
*/ */
void postNotification(const char *name); void postNotification(const std::string& name);
/** @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 sender The object posting the notification. Can be NULL * @param sender The object posting the notification. Can be nullptr
*/ */
void postNotification(const char *name, Object *sender); void postNotification(const std::string& name, Object *sender);
/** @brief Gets script handler. /** @brief Gets script handler.
* @note Only supports Lua Binding now. * @note Only supports Lua Binding now.
@ -112,12 +112,12 @@ public:
* @param name The name of this notification. * @param name The name of this notification.
* @return The observer script handle. * @return The observer script handle.
*/ */
int getObserverHandlerByName(const char* name); int getObserverHandlerByName(const std::string& name);
private: 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, Object *sender); bool observerExisted(Object *target,const std::string& name, Object *sender);
// variables // variables
// //
@ -132,13 +132,13 @@ 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 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. * @param sender The object whose notifications the target wants to receive. Only notifications sent by this sender are delivered to the target. nullptr means that the sender is not used to decide whether to deliver the notification to target.
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
NotificationObserver(Object *target, NotificationObserver(Object *target,
SEL_CallFuncO selector, SEL_CallFuncO selector,
const char *name, const std::string& name,
Object *sender); Object *sender);
/** NotificationObserver destructor function /** NotificationObserver destructor function
@ -168,7 +168,7 @@ public:
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
const char* getName() const; const std::string& getName() const;
/** /**
* @js NA * @js NA
* @lua NA * @lua NA

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