Merge branch 'develop' of https://github.com/cocos2d/cocos2d-x into TestSample

This commit is contained in:
samuele3hu 2013-07-26 21:39:34 +08:00
commit 70fcf47a3e
506 changed files with 7111 additions and 10233 deletions

View File

@ -414,6 +414,9 @@ Developers:
Added some guards to prevent Eclipse to compile twice the same class. Added some guards to prevent Eclipse to compile twice the same class.
Linux Eclipse projects updates Linux Eclipse projects updates
Refactored emscripten-build.sh, it's no longer need to be edited to make emscripten work. Refactored emscripten-build.sh, it's no longer need to be edited to make emscripten work.
Creation of CCDeprecated-ext.h
Use of a single emscripten HTML template file.
Added some guards in fileutils. Fixed a bug in emscripten file utils.
elmiro elmiro
Correction of passed buffer size to readlink and verification of result return by readlink. Correction of passed buffer size to readlink and verification of result return by readlink.
@ -537,6 +540,9 @@ Developers:
Rafael (rafaelx) Rafael (rafaelx)
A warning fix of AL_INVALID_NAME and AL_INVALID_OPERATION in SimpleAudioEngineOpenAL.cpp. A warning fix of AL_INVALID_NAME and AL_INVALID_OPERATION in SimpleAudioEngineOpenAL.cpp.
metalbass
Fixing an issue that sigslot::_connection_base# (from 0 to 8) don't have virtual destructors.
Retired Core Developers: Retired Core Developers:
WenSheng Yang WenSheng Yang

View File

@ -66,7 +66,7 @@
<ClCompile> <ClCompile>
<Optimization>Disabled</Optimization> <Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;..\Include;"$(ProjectDir)..\..\cocos2dx";"$(ProjectDir)..\..\cocos2dx\include";"$(ProjectDir)..\..\cocos2dx\kazmath\include";"$(ProjectDir)..\..\cocos2dx\platform\win32";"$(ProjectDir)..\..\cocos2dx\platform\third_party\win32\OGLES";%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;..\Include;"$(ProjectDir)..\..\cocos2dx";"$(ProjectDir)..\..\cocos2dx\include";"$(ProjectDir)..\..\cocos2dx\kazmath\include";"$(ProjectDir)..\..\cocos2dx\platform\win32";"$(ProjectDir)..\..\cocos2dx\platform\third_party\win32\OGLES";%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_USRDLL;COCOSDENSHIONWIN32_EXPORTS;_EXPORT_DLL_;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>false</MinimalRebuild> <MinimalRebuild>false</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks> <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary> <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
@ -90,7 +90,7 @@
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile> <ClCompile>
<AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;..\Include;"$(ProjectDir)..\..\cocos2dx";"$(ProjectDir)..\..\cocos2dx\include";"$(ProjectDir)..\..\cocos2dx\kazmath\include";"$(ProjectDir)..\..\cocos2dx\platform\win32";"$(ProjectDir)..\..\cocos2dx\platform\third_party\win32\OGLES";%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories> <AdditionalIncludeDirectories>$(MSBuildProgramFiles32)\Microsoft SDKs\Windows\v7.1A\include;..\Include;"$(ProjectDir)..\..\cocos2dx";"$(ProjectDir)..\..\cocos2dx\include";"$(ProjectDir)..\..\cocos2dx\kazmath\include";"$(ProjectDir)..\..\cocos2dx\platform\win32";"$(ProjectDir)..\..\cocos2dx\platform\third_party\win32\OGLES";%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_USRDLL;COCOSDENSHIONWIN32_EXPORTS;_EXPORT_DLL_;%(PreprocessorDefinitions)</PreprocessorDefinitions> <PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary> <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<PrecompiledHeader> <PrecompiledHeader>
</PrecompiledHeader> </PrecompiledHeader>

View File

@ -1 +1 @@
b58c6efb737f16d40b382a25cea15fdb09764372 a30cd2dad1df734bd988309d3b344ff946601cb4

View File

@ -8,6 +8,7 @@ LOCAL_MODULE_FILENAME := libcocos2d
LOCAL_SRC_FILES := \ LOCAL_SRC_FILES := \
CCConfiguration.cpp \ CCConfiguration.cpp \
CCDeprecated.cpp \
CCScheduler.cpp \ CCScheduler.cpp \
CCCamera.cpp \ CCCamera.cpp \
ccFPSImages.c \ ccFPSImages.c \
@ -170,8 +171,8 @@ LOCAL_WHOLE_STATIC_LIBRARIES += cocos_libtiff_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_libwebp_static LOCAL_WHOLE_STATIC_LIBRARIES += cocos_libwebp_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 -Wno-deprecated-declarations -DUSE_FILE32API LOCAL_CFLAGS := -Wno-psabi -DUSE_FILE32API
LOCAL_EXPORT_CFLAGS := -Wno-psabi -Wno-deprecated-declarations -DUSE_FILE32API LOCAL_EXPORT_CFLAGS := -Wno-psabi -DUSE_FILE32API
include $(BUILD_STATIC_LIBRARY) include $(BUILD_STATIC_LIBRARY)

View File

@ -35,15 +35,6 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
typedef enum _ccConfigurationType {
ConfigurationError,
ConfigurationString,
ConfigurationInt,
ConfigurationDouble,
ConfigurationBoolean
} ccConfigurationType;
/** /**
* @addtogroup global * @addtogroup global
* @{ * @{
@ -55,6 +46,7 @@ typedef enum _ccConfigurationType {
class CC_DLL Configuration : public Object class CC_DLL Configuration : public Object
{ {
public: public:
/** returns a shared instance of Configuration */ /** returns a shared instance of Configuration */
static Configuration *getInstance(); static Configuration *getInstance();

299
cocos2dx/CCDeprecated.cpp Normal file
View File

@ -0,0 +1,299 @@
/****************************************************************************
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 "cocos2d.h"
NS_CC_BEGIN
const Point CCPointZero = Point::ZERO;
/* The "zero" size -- equivalent to Size(0, 0). */
const Size CCSizeZero = Size::ZERO;
/* The "zero" rectangle -- equivalent to Rect(0, 0, 0, 0). */
const Rect CCRectZero = Rect::ZERO;
const Color3B ccWHITE = Color3B::WHITE;
const Color3B ccYELLOW = Color3B::YELLOW;
const Color3B ccGREEN = Color3B::GREEN;
const Color3B ccBLUE = Color3B::BLUE;
const Color3B ccRED = Color3B::RED;
const Color3B ccMAGENTA = Color3B::MAGENTA;
const Color3B ccBLACK = Color3B::BLACK;
const Color3B ccORANGE = Color3B::ORANGE;
const Color3B ccGRAY = Color3B::GRAY;
const BlendFunc kCCBlendFuncDisable = BlendFunc::DISABLE;
const int kCCVertexAttrib_Position = GLProgram::VERTEX_ATTRIB_POSITION;
const int kCCVertexAttrib_Color = GLProgram::VERTEX_ATTRIB_COLOR;
const int kCCVertexAttrib_TexCoords = GLProgram::VERTEX_ATTRIB_TEX_COORDS;
const int kCCVertexAttrib_MAX = GLProgram::VERTEX_ATTRIB_MAX;
const int kCCUniformPMatrix = GLProgram::UNIFORM_P_MATRIX;
const int kCCUniformMVMatrix = GLProgram::UNIFORM_MV_MATRIX;
const int kCCUniformMVPMatrix = GLProgram::UNIFORM_MVP_MATRIX;
const int kCCUniformTime = GLProgram::UNIFORM_TIME;
const int kCCUniformSinTime = GLProgram::UNIFORM_SIN_TIME;
const int kCCUniformCosTime = GLProgram::UNIFORM_COS_TIME;
const int kCCUniformRandom01 = GLProgram::UNIFORM_RANDOM01;
const int kCCUniformSampler = GLProgram::UNIFORM_SAMPLER;
const int kCCUniform_MAX = GLProgram::UNIFORM_MAX;
const char* kCCShader_PositionTextureColor = GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR;
const char* kCCShader_PositionTextureColorAlphaTest = GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST;
const char* kCCShader_PositionColor = GLProgram::SHADER_NAME_POSITION_COLOR;
const char* kCCShader_PositionTexture = GLProgram::SHADER_NAME_POSITION_TEXTURE;
const char* kCCShader_PositionTexture_uColor = GLProgram::SHADER_NAME_POSITION_TEXTURE_U_COLOR;
const char* kCCShader_PositionTextureA8Color = GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR;
const char* kCCShader_Position_uColor = GLProgram::SHADER_NAME_POSITION_U_COLOR;
const char* kCCShader_PositionLengthTexureColor = GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR;
// uniform names
const char* kCCUniformPMatrix_s = GLProgram::UNIFORM_NAME_P_MATRIX;
const char* kCCUniformMVMatrix_s = GLProgram::UNIFORM_NAME_MV_MATRIX;
const char* kCCUniformMVPMatrix_s = GLProgram::UNIFORM_NAME_MVP_MATRIX;
const char* kCCUniformTime_s = GLProgram::UNIFORM_NAME_TIME;
const char* kCCUniformSinTime_s = GLProgram::UNIFORM_NAME_SIN_TIME;
const char* kCCUniformCosTime_s = GLProgram::UNIFORM_NAME_COS_TIME;
const char* kCCUniformRandom01_s = GLProgram::UNIFORM_NAME_RANDOM01;
const char* kCCUniformSampler_s = GLProgram::UNIFORM_NAME_SAMPLER;
const char* kCCUniformAlphaTestValue = GLProgram::UNIFORM_NAME_ALPHA_TEST_VALUE;
// Attribute names
const char* kCCAttributeNameColor = GLProgram::ATTRIBUTE_NAME_COLOR;
const char* kCCAttributeNamePosition = GLProgram::ATTRIBUTE_NAME_POSITION;
const char* kCCAttributeNameTexCoord = GLProgram::ATTRIBUTE_NAME_TEX_COORD;
const int kCCVertexAttribFlag_None = GL::VERTEX_ATTRIB_FLAT_NONE;
const int kCCVertexAttribFlag_Position = GL::VERTEX_ATTRIB_FLAG_POSITION;
const int kCCVertexAttribFlag_Color = GL::VERTEX_ATTRIB_FLAG_COLOR;
const int kCCVertexAttribFlag_TexCoords = GL::VERTEX_ATTRIB_FLAG_TEX_COORDS;
const int kCCVertexAttribFlag_PosColorTex = GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX;
const ProgressTimer::Type kCCProgressTimerTypeRadial = ProgressTimer::Type::RADIAL;
const ProgressTimer::Type kCCProgressTimerTypeBar = ProgressTimer::Type::BAR;
const Director::Projection kCCDirectorProjection2D = Director::Projection::_2D;
const Director::Projection kCCDirectorProjection3D = Director::Projection::_3D;
const Director::Projection kCCDirectorProjectionCustom = Director::Projection::CUSTOM;
const Director::Projection kCCDirectorProjectionDefault = Director::Projection::DEFAULT;
const int kCCParticleDurationInfinity = ParticleSystem::DURATION_INFINITY;
const int kCCParticleStartSizeEqualToEndSize = ParticleSystem::START_SIZE_EQUAL_TO_END_SIZE;
const int kCCParticleStartRadiusEqualToEndRadius = ParticleSystem::START_RADIUS_EQUAL_TO_END_RADIUS;
const ParticleSystem::Mode kCCParticleModeGravity = ParticleSystem::Mode::GRAVITY;
const ParticleSystem::Mode kCCParticleModeRadius = ParticleSystem::Mode::RADIUS;
const int kCCParticleDefaultCapacity = kParticleDefaultCapacity;
const ParticleSystem::PositionType kCCPositionTypeFree = ParticleSystem::PositionType::FREE;
const ParticleSystem::PositionType kCCPositionTypeRelative = ParticleSystem::PositionType::RELATIVE;
const ParticleSystem::PositionType kCCPositionTypeGrouped = ParticleSystem::PositionType::GROUPED;
const Label::VAlignment kCCVerticalTextAlignmentTop = Label::VAlignment::TOP;
const Label::VAlignment kCCVerticalTextAlignmentCenter = Label::VAlignment::CENTER;
const Label::VAlignment kCCVerticalTextAlignmentBottom = Label::VAlignment::BOTTOM;
const Label::HAlignment kCCTextAlignmentLeft = Label::HAlignment::LEFT;
const Label::HAlignment kCCTextAlignmentCenter = Label::HAlignment::CENTER;
const Label::HAlignment kCCTextAlignmentRight = Label::HAlignment::RIGHT;
const Texture2D::PixelFormat kCCTexture2DPixelFormat_RGBA8888 = Texture2D::PixelFormat::RGBA8888;
const Texture2D::PixelFormat kCCTexture2DPixelFormat_RGB888 = Texture2D::PixelFormat::RGB888;
const Texture2D::PixelFormat kCCTexture2DPixelFormat_RGB565 = Texture2D::PixelFormat::RGB565;
const Texture2D::PixelFormat kCCTexture2DPixelFormat_A8 = Texture2D::PixelFormat::A8;
const Texture2D::PixelFormat kCCTexture2DPixelFormat_I8 = Texture2D::PixelFormat::I8;
const Texture2D::PixelFormat kCCTexture2DPixelFormat_AI88 = Texture2D::PixelFormat::AI88;
const Texture2D::PixelFormat kCCTexture2DPixelFormat_RGBA4444 = Texture2D::PixelFormat::RGBA4444;
const Texture2D::PixelFormat kCCTexture2DPixelFormat_RGB5A1 = Texture2D::PixelFormat::RGB5A1;
const Texture2D::PixelFormat kCCTexture2DPixelFormat_PVRTC4 = Texture2D::PixelFormat::PRVTC4;
const Texture2D::PixelFormat kCCTexture2DPixelFormat_PVRTC2 = Texture2D::PixelFormat::PRVTC2;
const Texture2D::PixelFormat kCCTexture2DPixelFormat_Default = Texture2D::PixelFormat::DEFAULT;
const int kCCMenuHandlerPriority = Menu::HANDLER_PRIORITY;
const Menu::State kCCMenuStateWaiting = Menu::State::WAITING;
const Menu::State kCCMenuStateTrackingTouch = Menu::State::TRACKING_TOUCH;
const Touch::DispatchMode kCCTouchesOneByOne = Touch::DispatchMode::ONE_BY_ONE;
const Touch::DispatchMode kCCTouchesAllAtOnce = Touch::DispatchMode::ALL_AT_ONCE;
const Image::Format kCCImageFormatPNG = Image::Format::PNG;
const Image::Format kCCImageFormatJPEG = Image::Format::JPG;
const TransitionScene::Orientation kCCTransitionOrientationLeftOver = TransitionScene::Orientation::LEFT_OVER;
const TransitionScene::Orientation kCCTransitionOrientationRightOver = TransitionScene::Orientation::RIGHT_OVER;
const TransitionScene::Orientation kCCTransitionOrientationUpOver = TransitionScene::Orientation::UP_OVER;
const TransitionScene::Orientation kCCTransitionOrientationDownOver = TransitionScene::Orientation::DOWN_OVER;
const int kCCPrioritySystem = Scheduler::PRIORITY_SYSTEM;
const int kCCPriorityNonSystemMin = Scheduler::PRIORITY_NON_SYSTEM_MIN;
const int kCCActionTagInvalid = kActionTagInvalid;
const int kCCNodeTagInvalid = kNodeTagInvalid;
const int kCCNodeOnEnter = kNodeOnEnter;
const int kCCNodeOnExit = kNodeOnExit;
const int kCCNodeOnEnterTransitionDidFinish = kNodeOnEnterTransitionDidFinish;
const int kCCNodeOnExitTransitionDidStart = kNodeOnExitTransitionDidStart;
const int kCCNodeOnCleanup = kNodeOnCleanup;
const LanguageType kLanguageEnglish = LanguageType::ENGLISH;
const LanguageType kLanguageChinese = LanguageType::CHINESE;
const LanguageType kLanguageFrench = LanguageType::FRENCH;
const LanguageType kLanguageItalian = LanguageType::ITALIAN;
const LanguageType kLanguageGerman = LanguageType::GERMAN;
const LanguageType kLanguageSpanish = LanguageType::SPANISH;
const LanguageType kLanguageRussian = LanguageType::RUSSIAN;
const LanguageType kLanguageKorean = LanguageType::KOREAN;
const LanguageType kLanguageJapanese = LanguageType::JAPANESE;
const LanguageType kLanguageHungarian = LanguageType::HUNGARIAN;
const LanguageType kLanguagePortuguese = LanguageType::PORTUGUESE;
const LanguageType kLanguageArabic = LanguageType::ARABIC;
const LanguageType kLanguageNorwegian = LanguageType::NORWEGIAN;
const LanguageType kLanguagePolish = LanguageType::POLISH;
const Application::Platform kTargetWindows = Application::Platform::OS_WINDOWS;
const Application::Platform kTargetLinux = Application::Platform::OS_LINUX;
const Application::Platform kTargetMacOS = Application::Platform::OS_MAC;
const Application::Platform kTargetAndroid = Application::Platform::OS_ANDROID;
const Application::Platform kTargetIphone = Application::Platform::OS_IPHONE;
const Application::Platform kTargetIpad = Application::Platform::OS_IPAD;
const Application::Platform kTargetBlackBerry = Application::Platform::OS_BLACKBERRY;
const Application::Platform kTargetNaCl = Application::Platform::OS_NACL;
const Application::Platform kTargetEmscripten = Application::Platform::OS_EMSCRIPTEN;
const Application::Platform kTargetTizen = Application::Platform::OS_TIZEN;
const ResolutionPolicy kResolutionExactFit = ResolutionPolicy::EXACT_FIT;
const ResolutionPolicy kResolutionNoBorder = ResolutionPolicy::NO_BORDER;
const ResolutionPolicy kResolutionShowAll = ResolutionPolicy::SHOW_ALL;
const ResolutionPolicy kResolutionFixedHeight = ResolutionPolicy::FIXED_HEIGHT;
const ResolutionPolicy kResolutionFixedWidth = ResolutionPolicy::FIXED_WIDTH;
const ResolutionPolicy kResolutionUnKnown = ResolutionPolicy::UNKNOWN;
void ccDrawInit()
{
DrawPrimitives::init();
}
void ccDrawFree()
{
DrawPrimitives::free();
}
void ccDrawPoint( const Point& point )
{
DrawPrimitives::drawPoint(point);
}
void ccDrawPoints( const Point *points, unsigned int numberOfPoints )
{
DrawPrimitives::drawPoints(points, numberOfPoints);
}
void ccDrawLine( const Point& origin, const Point& destination )
{
DrawPrimitives::drawLine(origin, destination);
}
void ccDrawRect( Point origin, Point destination )
{
DrawPrimitives::drawRect(origin, destination);
}
void ccDrawSolidRect( Point origin, Point destination, Color4F color )
{
DrawPrimitives::drawSolidRect(origin, destination, color);
}
void ccDrawPoly( const Point *vertices, unsigned int numOfVertices, bool closePolygon )
{
DrawPrimitives::drawPoly(vertices, numOfVertices, closePolygon);
}
void ccDrawSolidPoly( const Point *poli, unsigned int numberOfPoints, Color4F color )
{
DrawPrimitives::drawSolidPoly(poli, numberOfPoints, color);
}
void ccDrawCircle( const Point& center, float radius, float angle, unsigned int segments, bool drawLineToCenter, float scaleX, float scaleY)
{
DrawPrimitives::drawCircle(center, radius, angle, segments, drawLineToCenter, scaleX, scaleY);
}
void ccDrawCircle( const Point& center, float radius, float angle, unsigned int segments, bool drawLineToCenter)
{
DrawPrimitives::drawCircle(center, radius, angle, segments, drawLineToCenter);
}
void ccDrawSolidCircle( const Point& center, float radius, float angle, unsigned int segments, float scaleX, float scaleY)
{
DrawPrimitives::drawSolidCircle(center, radius, angle, segments, scaleX, scaleY);
}
void ccDrawSolidCircle( const Point& center, float radius, float angle, unsigned int segments)
{
DrawPrimitives::drawSolidCircle(center, radius, angle, segments);
}
void ccDrawQuadBezier(const Point& origin, const Point& control, const Point& destination, unsigned int segments)
{
DrawPrimitives::drawQuadBezier(origin, control, destination, segments);
}
void ccDrawCubicBezier(const Point& origin, const Point& control1, const Point& control2, const Point& destination, unsigned int segments)
{
DrawPrimitives::drawCubicBezier(origin, control1, control2, destination, segments);
}
void ccDrawCatmullRom( PointArray *arrayOfControlPoints, unsigned int segments )
{
DrawPrimitives::drawCatmullRom(arrayOfControlPoints, segments);
}
void ccDrawCardinalSpline( PointArray *config, float tension, unsigned int segments )
{
DrawPrimitives::drawCardinalSpline(config, tension, segments);
}
void ccDrawColor4B( GLubyte r, GLubyte g, GLubyte b, GLubyte a )
{
DrawPrimitives::setDrawColor4B(r, g, b, a);
}
void ccDrawColor4F( GLfloat r, GLfloat g, GLfloat b, GLfloat a )
{
DrawPrimitives::setDrawColor4F(r, g, b, a);
}
void ccPointSize( GLfloat pointSize )
{
DrawPrimitives::setPointSize(pointSize);
}
NS_CC_END

View File

@ -146,7 +146,7 @@ bool Director::init(void)
_scheduler = new Scheduler(); _scheduler = new Scheduler();
// action manager // action manager
_actionManager = new ActionManager(); _actionManager = new ActionManager();
_scheduler->scheduleUpdateForTarget(_actionManager, kPrioritySystem, false); _scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false);
// touchDispatcher // touchDispatcher
_touchDispatcher = new TouchDispatcher(); _touchDispatcher = new TouchDispatcher();
_touchDispatcher->init(); _touchDispatcher->init();
@ -210,22 +210,22 @@ void Director::setDefaultValues(void)
// GL projection // GL projection
const char *projection = conf->getCString("cocos2d.x.gl.projection", "3d"); const char *projection = conf->getCString("cocos2d.x.gl.projection", "3d");
if( strcmp(projection, "3d") == 0 ) if( strcmp(projection, "3d") == 0 )
_projection = kDirectorProjection3D; _projection = Projection::_3D;
else if (strcmp(projection, "2d") == 0) else if (strcmp(projection, "2d") == 0)
_projection = kDirectorProjection2D; _projection = Projection::_2D;
else if (strcmp(projection, "custom") == 0) else if (strcmp(projection, "custom") == 0)
_projection = kDirectorProjectionCustom; _projection = Projection::CUSTOM;
else else
CCASSERT(false, "Invalid projection value"); CCASSERT(false, "Invalid projection value");
// Default pixel format for PNG images with alpha // Default pixel format for PNG images with alpha
const char *pixel_format = conf->getCString("cocos2d.x.texture.pixel_format_for_png", "rgba8888"); const char *pixel_format = conf->getCString("cocos2d.x.texture.pixel_format_for_png", "rgba8888");
if( strcmp(pixel_format, "rgba8888") == 0 ) if( strcmp(pixel_format, "rgba8888") == 0 )
Texture2D::setDefaultAlphaPixelFormat(kTexture2DPixelFormat_RGBA8888); Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888);
else if( strcmp(pixel_format, "rgba4444") == 0 ) else if( strcmp(pixel_format, "rgba4444") == 0 )
Texture2D::setDefaultAlphaPixelFormat(kTexture2DPixelFormat_RGBA4444); Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444);
else if( strcmp(pixel_format, "rgba5551") == 0 ) else if( strcmp(pixel_format, "rgba5551") == 0 )
Texture2D::setDefaultAlphaPixelFormat(kTexture2DPixelFormat_RGB5A1); Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGB5A1);
// PVR v2 has alpha premultiplied ? // PVR v2 has alpha premultiplied ?
bool pvr_alpha_premultipled = conf->getBool("cocos2d.x.texture.pvrv2_has_alpha_premultiplied", false); bool pvr_alpha_premultipled = conf->getBool("cocos2d.x.texture.pvrv2_has_alpha_premultiplied", false);
@ -385,16 +385,15 @@ void Director::setNextDeltaTimeZero(bool bNextDeltaTimeZero)
_nextDeltaTimeZero = bNextDeltaTimeZero; _nextDeltaTimeZero = bNextDeltaTimeZero;
} }
void Director::setProjection(ccDirectorProjection kProjection) void Director::setProjection(Projection projection)
{ {
Size size = _winSizeInPoints; Size size = _winSizeInPoints;
setViewport(); setViewport();
switch (kProjection) switch (projection)
{ {
case kDirectorProjection2D: case Projection::_2D:
{
kmGLMatrixMode(KM_GL_PROJECTION); kmGLMatrixMode(KM_GL_PROJECTION);
kmGLLoadIdentity(); kmGLLoadIdentity();
kmMat4 orthoMatrix; kmMat4 orthoMatrix;
@ -402,10 +401,9 @@ void Director::setProjection(ccDirectorProjection kProjection)
kmGLMultMatrix(&orthoMatrix); kmGLMultMatrix(&orthoMatrix);
kmGLMatrixMode(KM_GL_MODELVIEW); kmGLMatrixMode(KM_GL_MODELVIEW);
kmGLLoadIdentity(); kmGLLoadIdentity();
} break;
break;
case kDirectorProjection3D: case Projection::_3D:
{ {
float zeye = this->getZEye(); float zeye = this->getZEye();
@ -428,23 +426,21 @@ void Director::setProjection(ccDirectorProjection kProjection)
kmVec3Fill( &up, 0.0f, 1.0f, 0.0f); kmVec3Fill( &up, 0.0f, 1.0f, 0.0f);
kmMat4LookAt(&matrixLookup, &eye, &center, &up); kmMat4LookAt(&matrixLookup, &eye, &center, &up);
kmGLMultMatrix(&matrixLookup); kmGLMultMatrix(&matrixLookup);
break;
} }
break;
case kDirectorProjectionCustom: case Projection::CUSTOM:
if (_projectionDelegate) if (_projectionDelegate)
{ _projectionDelegate->updateProjection();
_projectionDelegate->updateProjection(); break;
}
break;
default: default:
CCLOG("cocos2d: Director: unrecognized projection"); CCLOG("cocos2d: Director: unrecognized projection");
break; break;
} }
_projection = kProjection; _projection = projection;
ccSetProjectionMatrixDirty(); GL::setProjectionMatrixDirty();
} }
void Director::purgeCachedData(void) void Director::purgeCachedData(void)
@ -467,11 +463,11 @@ void Director::setAlphaBlending(bool bOn)
{ {
if (bOn) if (bOn)
{ {
ccGLBlendFunc(CC_BLEND_SRC, CC_BLEND_DST); GL::blendFunc(CC_BLEND_SRC, CC_BLEND_DST);
} }
else else
{ {
ccGLBlendFunc(GL_ONE, GL_ZERO); GL::blendFunc(GL_ONE, GL_ZERO);
} }
CHECK_GL_ERROR_DEBUG(); CHECK_GL_ERROR_DEBUG();
@ -705,7 +701,7 @@ void Director::purgeDirector()
LabelBMFont::purgeCachedData(); LabelBMFont::purgeCachedData();
// purge all managed caches // purge all managed caches
ccDrawFree(); DrawPrimitives::free();
AnimationCache::destroyInstance(); AnimationCache::destroyInstance();
SpriteFrameCache::destroyInstance(); SpriteFrameCache::destroyInstance();
TextureCache::destroyInstance(); TextureCache::destroyInstance();
@ -717,7 +713,7 @@ void Director::purgeDirector()
UserDefault::destroyInstance(); UserDefault::destroyInstance();
NotificationCenter::destroyInstance(); NotificationCenter::destroyInstance();
ccGLInvalidateStateCache(); GL::invalidateStateCache();
CHECK_GL_ERROR_DEBUG(); CHECK_GL_ERROR_DEBUG();
@ -864,8 +860,8 @@ void Director::createStatsLabel()
FileUtils::getInstance()->purgeCachedEntries(); FileUtils::getInstance()->purgeCachedEntries();
} }
Texture2DPixelFormat currentFormat = Texture2D::getDefaultAlphaPixelFormat(); Texture2D::PixelFormat currentFormat = Texture2D::getDefaultAlphaPixelFormat();
Texture2D::setDefaultAlphaPixelFormat(kTexture2DPixelFormat_RGBA4444); Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444);
unsigned char *data = NULL; unsigned char *data = NULL;
unsigned int data_len = 0; unsigned int data_len = 0;
getFPSImageData(&data, &data_len); getFPSImageData(&data, &data_len);

View File

@ -46,23 +46,6 @@ NS_CC_BEGIN
* @{ * @{
*/ */
/** @typedef ccDirectorProjection
Possible OpenGL projections used by director
*/
typedef enum {
/// sets a 2D projection (orthogonal projection)
kDirectorProjection2D,
/// sets a 3D projection with a fovy=60, znear=0.5f and zfar=1500.
kDirectorProjection3D,
/// it calls "updateProjection" on the projection delegate.
kDirectorProjectionCustom,
/// Default projection is 3D projection
kDirectorProjectionDefault = kDirectorProjection3D,
} ccDirectorProjection;
/* Forward declarations. */ /* Forward declarations. */
class LabelAtlas; class LabelAtlas;
class Scene; class Scene;
@ -99,6 +82,24 @@ and when to execute the Scenes.
class CC_DLL Director : public Object, public TypeInfo class CC_DLL Director : public Object, public TypeInfo
{ {
public: public:
/** @typedef ccDirectorProjection
Possible OpenGL projections used by director
*/
enum class Projection
{
/// sets a 2D projection (orthogonal projection)
_2D,
/// sets a 3D projection with a fovy=60, znear=0.5f and zfar=1500.
_3D,
/// it calls "updateProjection" on the projection delegate.
CUSTOM,
/// Default projection is 3D projection
DEFAULT = _3D,
};
/** returns a shared instance of the director */ /** returns a shared instance of the director */
static Director* getInstance(); static Director* getInstance();
@ -126,7 +127,7 @@ public:
/** Whether or not to display the FPS on the bottom-left corner */ /** Whether or not to display the FPS on the bottom-left corner */
inline bool isDisplayStats(void) { return _displayStats; } inline bool isDisplayStats(void) { return _displayStats; }
/** Display the FPS on the bottom-left corner */ /** Display the FPS on the bottom-left corner */
inline void setDisplayStats(bool bDisplayStats) { _displayStats = bDisplayStats; } inline void setDisplayStats(bool displayStats) { _displayStats = displayStats; }
/** seconds per frame */ /** seconds per frame */
inline float getSecondsPerFrame() { return _secondsPerFrame; } inline float getSecondsPerFrame() { return _secondsPerFrame; }
@ -136,7 +137,7 @@ public:
void setOpenGLView(EGLView *pobOpenGLView); void setOpenGLView(EGLView *pobOpenGLView);
inline bool isNextDeltaTimeZero(void) { return _nextDeltaTimeZero; } inline bool isNextDeltaTimeZero(void) { return _nextDeltaTimeZero; }
void setNextDeltaTimeZero(bool bNextDeltaTimeZero); void setNextDeltaTimeZero(bool nextDeltaTimeZero);
/** Whether or not the Director is paused */ /** Whether or not the Director is paused */
inline bool isPaused(void) { return _paused; } inline bool isPaused(void) { return _paused; }
@ -147,8 +148,8 @@ public:
/** Sets an OpenGL projection /** Sets an OpenGL projection
@since v0.8.2 @since v0.8.2
*/ */
inline ccDirectorProjection getProjection(void) { return _projection; } inline Projection getProjection(void) { return _projection; }
void setProjection(ccDirectorProjection kProjection); void setProjection(Projection projection);
/** Sets the glViewport*/ /** Sets the glViewport*/
void setViewport(); void setViewport();
@ -200,12 +201,12 @@ public:
/** converts a UIKit coordinate to an OpenGL coordinate /** converts a UIKit coordinate to an OpenGL coordinate
Useful to convert (multi) touch coordinates to the current layout (portrait or landscape) Useful to convert (multi) touch coordinates to the current layout (portrait or landscape)
*/ */
Point convertToGL(const Point& obPoint); Point convertToGL(const Point& point);
/** converts an OpenGL coordinate to a UIKit coordinate /** converts an OpenGL coordinate to a UIKit coordinate
Useful to convert node points to window points for calls such as glScissor Useful to convert node points to window points for calls such as glScissor
*/ */
Point convertToUI(const Point& obPoint); Point convertToUI(const Point& point);
/// XXX: missing description /// XXX: missing description
float getZEye(void) const; float getZEye(void) const;
@ -218,14 +219,14 @@ public:
* *
* It will call pushScene: and then it will call startAnimation * It will call pushScene: and then it will call startAnimation
*/ */
void runWithScene(Scene *pScene); void runWithScene(Scene *scene);
/** Suspends the execution of the running scene, pushing it on the stack of suspended scenes. /** Suspends the execution of the running scene, pushing it on the stack of suspended scenes.
* The new scene will be executed. * The new scene will be executed.
* Try to avoid big stacks of pushed scenes to reduce memory allocation. * Try to avoid big stacks of pushed scenes to reduce memory allocation.
* ONLY call it if there is a running scene. * ONLY call it if there is a running scene.
*/ */
void pushScene(Scene *pScene); void pushScene(Scene *scene);
/** Pops out a scene from the queue. /** Pops out a scene from the queue.
* This scene will replace the running one. * This scene will replace the running one.
@ -250,7 +251,7 @@ public:
/** Replaces the running scene with a new one. The running scene is terminated. /** Replaces the running scene with a new one. The running scene is terminated.
* ONLY call it if there is a running scene. * ONLY call it if there is a running scene.
*/ */
void replaceScene(Scene *pScene); void replaceScene(Scene *scene);
/** Ends the execution, releases the running scene. /** Ends the execution, releases the running scene.
It doesn't remove the OpenGL view from its parent. You have to do it manually. It doesn't remove the OpenGL view from its parent. You have to do it manually.
@ -477,7 +478,7 @@ protected:
bool _nextDeltaTimeZero; bool _nextDeltaTimeZero;
/* projection used */ /* projection used */
ccDirectorProjection _projection; Projection _projection;
/* window size in points */ /* window size in points */
Size _winSizeInPoints; Size _winSizeInPoints;

View File

@ -240,6 +240,12 @@ SEL_SCHEDULE Timer::getSelector() const
// implementation of Scheduler // implementation of Scheduler
// Priority level reserved for system services.
const int Scheduler::PRIORITY_SYSTEM = INT_MIN;
// Minimum priority level for user scheduling.
const int Scheduler::PRIORITY_NON_SYSTEM_MIN = PRIORITY_SYSTEM + 1;
Scheduler::Scheduler(void) Scheduler::Scheduler(void)
: _timeScale(1.0f) : _timeScale(1.0f)
, _updatesNegList(NULL) , _updatesNegList(NULL)
@ -577,7 +583,7 @@ void Scheduler::unscheduleUpdateForTarget(const Object *target)
void Scheduler::unscheduleAll(void) void Scheduler::unscheduleAll(void)
{ {
unscheduleAllWithMinPriority(kPrioritySystem); unscheduleAllWithMinPriority(PRIORITY_SYSTEM);
} }
void Scheduler::unscheduleAllWithMinPriority(int nMinPriority) void Scheduler::unscheduleAllWithMinPriority(int nMinPriority)
@ -759,7 +765,7 @@ bool Scheduler::isTargetPaused(Object *target)
Set* Scheduler::pauseAllTargets() Set* Scheduler::pauseAllTargets()
{ {
return pauseAllTargetsWithMinPriority(kPrioritySystem); return pauseAllTargetsWithMinPriority(PRIORITY_SYSTEM);
} }
Set* Scheduler::pauseAllTargetsWithMinPriority(int nMinPriority) Set* Scheduler::pauseAllTargetsWithMinPriority(int nMinPriority)

View File

@ -37,12 +37,6 @@ NS_CC_BEGIN
* @{ * @{
*/ */
// Priority level reserved for system services.
#define kPrioritySystem INT_MIN
// Minimum priority level for user scheduling.
#define kPriorityNonSystemMin (kPrioritySystem+1)
class Set; class Set;
// //
// Timer // Timer
@ -121,6 +115,12 @@ The 'custom selectors' should be avoided when possible. It is faster, and consum
class CC_DLL Scheduler : public Object class CC_DLL Scheduler : public Object
{ {
public: public:
// Priority level reserved for system services.
static const int PRIORITY_SYSTEM;
// Minimum priority level for user scheduling.
static const int PRIORITY_NON_SYSTEM_MIN;
Scheduler(); Scheduler();
~Scheduler(void); ~Scheduler(void);

View File

@ -201,8 +201,11 @@ Instead of using Camera as a "follower", use this action instead.
class CC_DLL Follow : public Action class CC_DLL Follow : public Action
{ {
public: public:
/** creates the action with a set boundary, /**
It will work with no boundary if @param rect is equal to Rect::ZERO. * Creates the action with a set boundary or with no boundary.
*
* @param rect The boundary. If \p rect is equal to Rect::ZERO, it'll work
* with no boundary.
*/ */
static Follow* create(Node *pFollowedNode, const Rect& rect = Rect::ZERO); static Follow* create(Node *pFollowedNode, const Rect& rect = Rect::ZERO);
@ -222,7 +225,12 @@ public:
/** alter behavior - turn on/off boundary */ /** alter behavior - turn on/off boundary */
inline void setBoudarySet(bool bValue) { _boundarySet = bValue; } inline void setBoudarySet(bool bValue) { _boundarySet = bValue; }
/** initializes the action with a set boundary */ /**
* Initializes the action with a set boundary or with no boundary.
*
* @param rect The boundary. If \p rect is equal to Rect::ZERO, it'll work
* with no boundary.
*/
bool initWithTarget(Node *pFollowedNode, const Rect& rect = Rect::ZERO); bool initWithTarget(Node *pFollowedNode, const Rect& rect = Rect::ZERO);
// //

View File

@ -29,6 +29,13 @@
#include "sprite_nodes/CCSprite.h" #include "sprite_nodes/CCSprite.h"
#include "script_support/CCScriptSupport.h" #include "script_support/CCScriptSupport.h"
#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#elif _MSC_VER >= 1400 //vs 2005 or higher
#pragma warning (push)
#pragma warning (disable: 4996)
#endif
NS_CC_BEGIN NS_CC_BEGIN
// //
// InstantAction // InstantAction
@ -473,5 +480,137 @@ CallFuncN * CallFuncN::clone() const
return a; return a;
} }
//
// CallFuncND
//
__CCCallFuncND * __CCCallFuncND::create(Object* selectorTarget, SEL_CallFuncND selector, void* d)
{
__CCCallFuncND* pRet = new __CCCallFuncND();
if (pRet && pRet->initWithTarget(selectorTarget, selector, d)) {
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool __CCCallFuncND::initWithTarget(Object* selectorTarget, SEL_CallFuncND selector, void* d)
{
if (CallFunc::initWithTarget(selectorTarget))
{
_data = d;
_callFuncND = selector;
return true;
}
return false;
}
void __CCCallFuncND::execute()
{
if (_callFuncND)
{
(_selectorTarget->*_callFuncND)(_target, _data);
}
}
__CCCallFuncND * __CCCallFuncND::clone() const
{
// no copy constructor
auto a = new __CCCallFuncND();
if( _selectorTarget)
{
a->initWithTarget(_selectorTarget, _callFuncND, _data);
}
a->autorelease();
return a;
}
//
// CallFuncO
//
__CCCallFuncO::__CCCallFuncO() :
_object(NULL)
{
}
__CCCallFuncO::~__CCCallFuncO()
{
CC_SAFE_RELEASE(_object);
}
void __CCCallFuncO::execute()
{
if (_callFuncO) {
(_selectorTarget->*_callFuncO)(_object);
}
}
__CCCallFuncO * __CCCallFuncO::create(Object* selectorTarget, SEL_CallFuncO selector, Object* object)
{
__CCCallFuncO *pRet = new __CCCallFuncO();
if (pRet && pRet->initWithTarget(selectorTarget, selector, object)) {
pRet->autorelease();
return pRet;
}
CC_SAFE_DELETE(pRet);
return NULL;
}
bool __CCCallFuncO::initWithTarget(Object* selectorTarget, SEL_CallFuncO selector, Object* object)
{
if (CallFunc::initWithTarget(selectorTarget))
{
_object = object;
CC_SAFE_RETAIN(_object);
_callFuncO = selector;
return true;
}
return false;
}
__CCCallFuncO * __CCCallFuncO::clone() const
{
// no copy constructor
auto a = new __CCCallFuncO();
if( _selectorTarget)
{
a->initWithTarget(_selectorTarget, _callFuncO, _object);
}
a->autorelease();
return a;
}
Object* __CCCallFuncO::getObject() const
{
return _object;
}
void __CCCallFuncO::setObject(Object* obj)
{
if (obj != _object)
{
CC_SAFE_RELEASE(_object);
_object = obj;
CC_SAFE_RETAIN(_object);
}
}
NS_CC_END NS_CC_END
#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
#elif _MSC_VER >= 1400 //vs 2005 or higher
#pragma warning (pop)
#endif

View File

@ -341,6 +341,87 @@ protected:
std::function<void(Node*)> _functionN; std::function<void(Node*)> _functionN;
}; };
/**
@deprecated Please use CallFuncN instead.
@brief Calls a 'callback' with the node as the first argument and the 2nd argument is data
* ND means: Node and Data. Data is void *, so it could be anything.
*/
class CC_DLL __CCCallFuncND : public CallFunc
{
public:
/** creates the action with the callback and the data to pass as an argument */
CC_DEPRECATED_ATTRIBUTE static __CCCallFuncND * create(Object* selectorTarget, SEL_CallFuncND selector, void* d);
virtual long getClassTypeInfo() {
static const long id = cocos2d::getHashCodeByString(typeid(cocos2d::CallFunc).name());
return id;
}
protected:
/** initializes the action with the callback and the data to pass as an argument */
bool initWithTarget(Object* selectorTarget, SEL_CallFuncND selector, void* d);
public:
//
// Overrides
//
virtual __CCCallFuncND* clone() const override;
virtual void execute() override;
protected:
SEL_CallFuncND _callFuncND;
void* _data;
};
/**
@deprecated Please use CallFuncN instead.
@brief Calls a 'callback' with an object as the first argument.
O means Object.
@since v0.99.5
*/
class CC_DLL __CCCallFuncO : public CallFunc, public TypeInfo
{
public:
/** creates the action with the callback
typedef void (Object::*SEL_CallFuncO)(Object*);
*/
CC_DEPRECATED_ATTRIBUTE static __CCCallFuncO * create(Object* selectorTarget, SEL_CallFuncO selector, Object* object);
__CCCallFuncO();
virtual ~__CCCallFuncO();
virtual long getClassTypeInfo() {
static const long id = cocos2d::getHashCodeByString(typeid(cocos2d::CallFunc).name());
return id;
}
protected:
/** initializes the action with the callback
typedef void (Object::*SEL_CallFuncO)(Object*);
*/
bool initWithTarget(Object* selectorTarget, SEL_CallFuncO selector, Object* object);
public:
//
// Overrides
//
virtual __CCCallFuncO* clone() const override;
virtual void execute() override;
Object* getObject() const;
void setObject(Object* obj);
protected:
/** object to be passed as argument */
Object* _object;
SEL_CallFuncO _callFuncO;
};
// end of actions group // end of actions group
/// @} /// @}

View File

@ -90,8 +90,7 @@ bool AtlasNode::initWithTexture(Texture2D* texture, unsigned int tileWidth, unsi
_colorUnmodified = Color3B::WHITE; _colorUnmodified = Color3B::WHITE;
_isOpacityModifyRGB = true; _isOpacityModifyRGB = true;
_blendFunc.src = CC_BLEND_SRC; _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
_blendFunc.dst = CC_BLEND_DST;
_textureAtlas = new TextureAtlas(); _textureAtlas = new TextureAtlas();
_textureAtlas->initWithTexture(texture, itemsToRender); _textureAtlas->initWithTexture(texture, itemsToRender);
@ -110,7 +109,7 @@ bool AtlasNode::initWithTexture(Texture2D* texture, unsigned int tileWidth, unsi
_quadsToDraw = itemsToRender; _quadsToDraw = itemsToRender;
// shader stuff // shader stuff
setShaderProgram(ShaderCache::getInstance()->programForKey(kShader_PositionTexture_uColor)); setShaderProgram(ShaderCache::getInstance()->programForKey(GLProgram::SHADER_NAME_POSITION_TEXTURE_U_COLOR));
_uniformColor = glGetUniformLocation( getShaderProgram()->getProgram(), "u_color"); _uniformColor = glGetUniformLocation( getShaderProgram()->getProgram(), "u_color");
return true; return true;
@ -142,7 +141,7 @@ void AtlasNode::draw(void)
{ {
CC_NODE_DRAW_SETUP(); CC_NODE_DRAW_SETUP();
ccGLBlendFunc( _blendFunc.src, _blendFunc.dst ); GL::blendFunc( _blendFunc.src, _blendFunc.dst );
GLfloat colors[4] = {_displayedColor.r / 255.0f, _displayedColor.g / 255.0f, _displayedColor.b / 255.0f, _displayedOpacity / 255.0f}; GLfloat colors[4] = {_displayedColor.r / 255.0f, _displayedColor.g / 255.0f, _displayedColor.b / 255.0f, _displayedOpacity / 255.0f};
getShaderProgram()->setUniformLocationWith4fv(_uniformColor, colors, 1); getShaderProgram()->setUniformLocationWith4fv(_uniformColor, colors, 1);
@ -220,10 +219,8 @@ void AtlasNode::setBlendFunc(const BlendFunc &blendFunc)
void AtlasNode::updateBlendFunc() void AtlasNode::updateBlendFunc()
{ {
if( ! _textureAtlas->getTexture()->hasPremultipliedAlpha() ) { if( ! _textureAtlas->getTexture()->hasPremultipliedAlpha() )
_blendFunc.src = GL_SRC_ALPHA; _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED;
_blendFunc.dst = GL_ONE_MINUS_SRC_ALPHA;
}
} }
void AtlasNode::setTexture(Texture2D *texture) void AtlasNode::setTexture(Texture2D *texture)

View File

@ -77,7 +77,6 @@ Node::Node(void)
, _userData(NULL) , _userData(NULL)
, _userObject(NULL) , _userObject(NULL)
, _shaderProgram(NULL) , _shaderProgram(NULL)
, _GLServerState(ccGLServerState(0))
, _orderOfArrival(0) , _orderOfArrival(0)
, _running(false) , _running(false)
, _transformDirty(true) , _transformDirty(true)
@ -125,10 +124,10 @@ Node::~Node()
Object* child; Object* child;
CCARRAY_FOREACH(_children, child) CCARRAY_FOREACH(_children, child)
{ {
Node* pChild = static_cast<Node*>(child); Node* node = static_cast<Node*>(child);
if (pChild) if (node)
{ {
pChild->_parent = NULL; node->_parent = NULL;
} }
} }
} }
@ -456,16 +455,6 @@ void Node::setOrderOfArrival(int orderOfArrival)
_orderOfArrival = orderOfArrival; _orderOfArrival = orderOfArrival;
} }
ccGLServerState Node::getGLServerState() const
{
return _GLServerState;
}
void Node::setGLServerState(ccGLServerState glServerState)
{
_GLServerState = glServerState;
}
void Node::setUserObject(Object *pUserObject) void Node::setUserObject(Object *pUserObject)
{ {
CC_SAFE_RETAIN(pUserObject); CC_SAFE_RETAIN(pUserObject);

View File

@ -515,19 +515,10 @@ public:
virtual int getOrderOfArrival() const; virtual int getOrderOfArrival() const;
/** /** @deprecated No longer needed */
* Sets the state of OpenGL server side. CC_DEPRECATED_ATTRIBUTE void setGLServerState(int serverState) { /* ignore */ };
* /** @deprecated No longer needed */
* @param glServerState The state of OpenGL server side. CC_DEPRECATED_ATTRIBUTE int getGLServerState() const { return 0; }
*/
virtual void setGLServerState(ccGLServerState serverState);
/**
* Returns the state of OpenGL server side.
*
* @return The state of OpenGL server side.
*/
virtual ccGLServerState getGLServerState() const;
/** /**
* Sets whether the anchor point will be (0,0) when you position this node. * Sets whether the anchor point will be (0,0) when you position this node.
@ -823,7 +814,7 @@ public:
* Since v2.0, each rendering node must set its shader program. * Since v2.0, each rendering node must set its shader program.
* It should be set in initialize phase. * It should be set in initialize phase.
* @code * @code
* node->setShaderProgram(ShaderCache::getInstance()->programForKey(kShader_PositionTextureColor)); * node->setShaderProgram(ShaderCache::getInstance()->programForKey(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
* @endcode * @endcode
* *
* @param The shader program which fetchs from ShaderCache. * @param The shader program which fetchs from ShaderCache.
@ -1359,9 +1350,7 @@ protected:
Object *_userObject; ///< A user assigned Object Object *_userObject; ///< A user assigned Object
GLProgram *_shaderProgram; ///< OpenGL shader GLProgram *_shaderProgram; ///< OpenGL shader
ccGLServerState _GLServerState; ///< OpenGL servier side state
int _orderOfArrival; ///< used to preserve sequence while sorting children with the same zOrder int _orderOfArrival; ///< used to preserve sequence while sorting children with the same zOrder
Scheduler *_scheduler; ///< scheduler used to schedule timers and updates Scheduler *_scheduler; ///< scheduler used to schedule timers and updates

View File

@ -43,6 +43,9 @@ Color4B::Color4B(const Color4F &color4F)
a((GLubyte)(color4F.a * 255.0f)) a((GLubyte)(color4F.a * 255.0f))
{} {}
const BlendFunc BlendFunc::BLEND_FUNC_DISABLE = {GL_ONE, GL_ZERO}; const BlendFunc BlendFunc::DISABLE = {GL_ONE, GL_ZERO};
const BlendFunc BlendFunc::ALPHA_PREMULTIPLIED = {GL_ONE, GL_ONE_MINUS_SRC_ALPHA};
const BlendFunc BlendFunc::ALPHA_NON_PREMULTIPLIED = {GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA};
const BlendFunc BlendFunc::ADDITIVE = {GL_SRC_ALPHA, GL_ONE};
NS_CC_END NS_CC_END

View File

@ -227,12 +227,12 @@ String* String::createWithFormat(const char* format, ...)
return pRet; return pRet;
} }
String* String::createWithContentsOfFile(const char* pszFileName) String* String::createWithContentsOfFile(const char* filename)
{ {
unsigned long size = 0; unsigned long size = 0;
unsigned char* pData = 0; unsigned char* pData = 0;
String* pRet = NULL; String* pRet = NULL;
pData = FileUtils::getInstance()->getFileData(pszFileName, "rb", &size); pData = FileUtils::getInstance()->getFileData(filename, "rb", &size);
pRet = String::createWithData(pData, size); pRet = String::createWithData(pData, size);
CC_SAFE_DELETE_ARRAY(pData); CC_SAFE_DELETE_ARRAY(pData);
return pRet; return pRet;

View File

@ -115,7 +115,7 @@ public:
* @return A String pointer which is an autorelease object pointer, * @return A String pointer which is an autorelease object pointer,
* it means that you needn't do a release operation unless you retain it. * it means that you needn't do a release operation unless you retain it.
*/ */
static String* createWithContentsOfFile(const char* pszFileName); static String* createWithContentsOfFile(const char* filename);
virtual void acceptVisitor(DataVisitor &visitor); virtual void acceptVisitor(DataVisitor &visitor);
virtual String* clone() const; virtual String* clone() const;

View File

@ -30,7 +30,7 @@ NS_CC_BEGIN
const char* cocos2dVersion() const char* cocos2dVersion()
{ {
return "3.0-alpha0-pre"; return "3.0-pre-alpha0";
} }
NS_CC_END NS_CC_END

View File

@ -103,8 +103,7 @@ DrawNode::DrawNode()
, _buffer(NULL) , _buffer(NULL)
, _dirty(false) , _dirty(false)
{ {
_blendFunc.src = CC_BLEND_SRC; _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
_blendFunc.dst = CC_BLEND_DST;
} }
DrawNode::~DrawNode() DrawNode::~DrawNode()
@ -117,7 +116,7 @@ DrawNode::~DrawNode()
#if CC_TEXTURE_ATLAS_USE_VAO #if CC_TEXTURE_ATLAS_USE_VAO
glDeleteVertexArrays(1, &_vao); glDeleteVertexArrays(1, &_vao);
ccGLBindVAO(0); GL::bindVAO(0);
_vao = 0; _vao = 0;
#endif #endif
@ -154,35 +153,34 @@ void DrawNode::ensureCapacity(int count)
bool DrawNode::init() bool DrawNode::init()
{ {
_blendFunc.src = CC_BLEND_SRC; _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
_blendFunc.dst = CC_BLEND_DST;
setShaderProgram(ShaderCache::getInstance()->programForKey(kShader_PositionLengthTexureColor)); setShaderProgram(ShaderCache::getInstance()->programForKey(GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR));
ensureCapacity(512); ensureCapacity(512);
#if CC_TEXTURE_ATLAS_USE_VAO #if CC_TEXTURE_ATLAS_USE_VAO
glGenVertexArrays(1, &_vao); glGenVertexArrays(1, &_vao);
ccGLBindVAO(_vao); GL::bindVAO(_vao);
#endif #endif
glGenBuffers(1, &_vbo); glGenBuffers(1, &_vbo);
glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBindBuffer(GL_ARRAY_BUFFER, _vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(V2F_C4B_T2F)* _bufferCapacity, _buffer, GL_STREAM_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(V2F_C4B_T2F)* _bufferCapacity, _buffer, GL_STREAM_DRAW);
glEnableVertexAttribArray(kVertexAttrib_Position); glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_POSITION);
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, vertices)); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, vertices));
glEnableVertexAttribArray(kVertexAttrib_Color); glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_COLOR);
glVertexAttribPointer(kVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, colors)); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, colors));
glEnableVertexAttribArray(kVertexAttrib_TexCoords); glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_TEX_COORDS);
glVertexAttribPointer(kVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, texCoords)); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, texCoords));
glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0);
#if CC_TEXTURE_ATLAS_USE_VAO #if CC_TEXTURE_ATLAS_USE_VAO
ccGLBindVAO(0); GL::bindVAO(0);
#endif #endif
CHECK_GL_ERROR_DEBUG(); CHECK_GL_ERROR_DEBUG();
@ -209,19 +207,19 @@ void DrawNode::render()
_dirty = false; _dirty = false;
} }
#if CC_TEXTURE_ATLAS_USE_VAO #if CC_TEXTURE_ATLAS_USE_VAO
ccGLBindVAO(_vao); GL::bindVAO(_vao);
#else #else
ccGLEnableVertexAttribs(kVertexAttribFlag_PosColorTex); GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX);
glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBindBuffer(GL_ARRAY_BUFFER, _vbo);
// vertex // vertex
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, vertices)); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, vertices));
// color // color
glVertexAttribPointer(kVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, colors)); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, colors));
// texcood // texcood
glVertexAttribPointer(kVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, texCoords)); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid *)offsetof(V2F_C4B_T2F, texCoords));
#endif #endif
glDrawArrays(GL_TRIANGLES, 0, _bufferCount); glDrawArrays(GL_TRIANGLES, 0, _bufferCount);
@ -234,7 +232,7 @@ void DrawNode::render()
void DrawNode::draw() void DrawNode::draw()
{ {
CC_NODE_DRAW_SETUP(); CC_NODE_DRAW_SETUP();
ccGLBlendFunc(_blendFunc.src, _blendFunc.dst); GL::blendFunc(_blendFunc.src, _blendFunc.dst);
render(); render();
} }

View File

@ -52,12 +52,14 @@ NS_CC_BEGIN
#define M_PI 3.14159265358979323846 #define M_PI 3.14159265358979323846
#endif #endif
static bool s_bInitialized = false; namespace DrawPrimitives {
static GLProgram* s_pShader = NULL;
static int s_nColorLocation = -1; static bool s_initialized = false;
static Color4F s_tColor(1.0f,1.0f,1.0f,1.0f); static GLProgram* s_shader = NULL;
static int s_nPointSizeLocation = -1; static int s_colorLocation = -1;
static GLfloat s_fPointSize = 1.0f; static Color4F s_color(1.0f,1.0f,1.0f,1.0f);
static int s_pointSizeLocation = -1;
static GLfloat s_pointSize = 1.0f;
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
static GLuint s_bufferObject = 0; static GLuint s_bufferObject = 0;
@ -88,36 +90,36 @@ static void setGLBufferData(void *buf, GLuint bufSize)
static void lazy_init( void ) static void lazy_init( void )
{ {
if( ! s_bInitialized ) { if( ! s_initialized ) {
// //
// Position and 1 color passed as a uniform (to simulate glColor4ub ) // Position and 1 color passed as a uniform (to simulate glColor4ub )
// //
s_pShader = ShaderCache::getInstance()->programForKey(kShader_Position_uColor); s_shader = ShaderCache::getInstance()->programForKey(GLProgram::SHADER_NAME_POSITION_U_COLOR);
s_pShader->retain(); s_shader->retain();
s_nColorLocation = glGetUniformLocation( s_pShader->getProgram(), "u_color"); s_colorLocation = glGetUniformLocation( s_shader->getProgram(), "u_color");
CHECK_GL_ERROR_DEBUG(); CHECK_GL_ERROR_DEBUG();
s_nPointSizeLocation = glGetUniformLocation( s_pShader->getProgram(), "u_pointSize"); s_pointSizeLocation = glGetUniformLocation( s_shader->getProgram(), "u_pointSize");
CHECK_GL_ERROR_DEBUG(); CHECK_GL_ERROR_DEBUG();
s_bInitialized = true; s_initialized = true;
} }
} }
// When switching from backround to foreground on android, we want the params to be initialized again // When switching from backround to foreground on android, we want the params to be initialized again
void ccDrawInit() void init()
{ {
lazy_init(); lazy_init();
} }
void ccDrawFree() void free()
{ {
CC_SAFE_RELEASE_NULL(s_pShader); CC_SAFE_RELEASE_NULL(s_shader);
s_bInitialized = false; s_initialized = false;
} }
void ccDrawPoint( const Point& point ) void drawPoint( const Point& point )
{ {
lazy_init(); lazy_init();
@ -125,18 +127,18 @@ void ccDrawPoint( const Point& point )
p.x = point.x; p.x = point.x;
p.y = point.y; p.y = point.y;
ccGLEnableVertexAttribs( kVertexAttribFlag_Position ); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
s_pShader->use(); s_shader->use();
s_pShader->setUniformsForBuiltins(); s_shader->setUniformsForBuiltins();
s_pShader->setUniformLocationWith4fv(s_nColorLocation, (GLfloat*) &s_tColor.r, 1); s_shader->setUniformLocationWith4fv(s_colorLocation, (GLfloat*) &s_color.r, 1);
s_pShader->setUniformLocationWith1f(s_nPointSizeLocation, s_fPointSize); s_shader->setUniformLocationWith1f(s_pointSizeLocation, s_pointSize);
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
setGLBufferData(&p, 8); setGLBufferData(&p, 8);
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else #else
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, &p); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, &p);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
glDrawArrays(GL_POINTS, 0, 1); glDrawArrays(GL_POINTS, 0, 1);
@ -144,15 +146,15 @@ void ccDrawPoint( const Point& point )
CC_INCREMENT_GL_DRAWS(1); CC_INCREMENT_GL_DRAWS(1);
} }
void ccDrawPoints( const Point *points, unsigned int numberOfPoints ) void drawPoints( const Point *points, unsigned int numberOfPoints )
{ {
lazy_init(); lazy_init();
ccGLEnableVertexAttribs( kVertexAttribFlag_Position ); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
s_pShader->use(); s_shader->use();
s_pShader->setUniformsForBuiltins(); s_shader->setUniformsForBuiltins();
s_pShader->setUniformLocationWith4fv(s_nColorLocation, (GLfloat*) &s_tColor.r, 1); s_shader->setUniformLocationWith4fv(s_colorLocation, (GLfloat*) &s_color.r, 1);
s_pShader->setUniformLocationWith1f(s_nPointSizeLocation, s_fPointSize); s_shader->setUniformLocationWith1f(s_pointSizeLocation, s_pointSize);
// XXX: Mac OpenGL error. arrays can't go out of scope before draw is executed // XXX: Mac OpenGL error. arrays can't go out of scope before draw is executed
Vertex2F* newPoints = new Vertex2F[numberOfPoints]; Vertex2F* newPoints = new Vertex2F[numberOfPoints];
@ -162,9 +164,9 @@ void ccDrawPoints( const Point *points, unsigned int numberOfPoints )
{ {
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
setGLBufferData((void*) points, numberOfPoints * sizeof(Point)); setGLBufferData((void*) points, numberOfPoints * sizeof(Point));
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else #else
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, points); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, points);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
} }
else else
@ -178,9 +180,9 @@ void ccDrawPoints( const Point *points, unsigned int numberOfPoints )
// Suspect Emscripten won't be emitting 64-bit code for a while yet, // Suspect Emscripten won't be emitting 64-bit code for a while yet,
// but want to make sure this continues to work even if they do. // but want to make sure this continues to work even if they do.
setGLBufferData(newPoints, numberOfPoints * sizeof(Vertex2F)); setGLBufferData(newPoints, numberOfPoints * sizeof(Vertex2F));
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else #else
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, newPoints); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, newPoints);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
} }
@ -192,7 +194,7 @@ void ccDrawPoints( const Point *points, unsigned int numberOfPoints )
} }
void ccDrawLine( const Point& origin, const Point& destination ) void drawLine( const Point& origin, const Point& destination )
{ {
lazy_init(); lazy_init();
@ -201,31 +203,31 @@ void ccDrawLine( const Point& origin, const Point& destination )
Vertex2F(destination.x, destination.y) Vertex2F(destination.x, destination.y)
}; };
s_pShader->use(); s_shader->use();
s_pShader->setUniformsForBuiltins(); s_shader->setUniformsForBuiltins();
s_pShader->setUniformLocationWith4fv(s_nColorLocation, (GLfloat*) &s_tColor.r, 1); s_shader->setUniformLocationWith4fv(s_colorLocation, (GLfloat*) &s_color.r, 1);
ccGLEnableVertexAttribs( kVertexAttribFlag_Position ); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
setGLBufferData(vertices, 16); setGLBufferData(vertices, 16);
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else #else
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, vertices); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
glDrawArrays(GL_LINES, 0, 2); glDrawArrays(GL_LINES, 0, 2);
CC_INCREMENT_GL_DRAWS(1); CC_INCREMENT_GL_DRAWS(1);
} }
void ccDrawRect( Point origin, Point destination ) void drawRect( Point origin, Point destination )
{ {
ccDrawLine(Point(origin.x, origin.y), Point(destination.x, origin.y)); drawLine(Point(origin.x, origin.y), Point(destination.x, origin.y));
ccDrawLine(Point(destination.x, origin.y), Point(destination.x, destination.y)); drawLine(Point(destination.x, origin.y), Point(destination.x, destination.y));
ccDrawLine(Point(destination.x, destination.y), Point(origin.x, destination.y)); drawLine(Point(destination.x, destination.y), Point(origin.x, destination.y));
ccDrawLine(Point(origin.x, destination.y), Point(origin.x, origin.y)); drawLine(Point(origin.x, destination.y), Point(origin.x, origin.y));
} }
void ccDrawSolidRect( Point origin, Point destination, Color4F color ) void drawSolidRect( Point origin, Point destination, Color4F color )
{ {
Point vertices[] = { Point vertices[] = {
origin, origin,
@ -234,27 +236,27 @@ void ccDrawSolidRect( Point origin, Point destination, Color4F color )
Point(origin.x, destination.y) Point(origin.x, destination.y)
}; };
ccDrawSolidPoly(vertices, 4, color ); drawSolidPoly(vertices, 4, color );
} }
void ccDrawPoly( const Point *poli, unsigned int numberOfPoints, bool closePolygon ) void drawPoly( const Point *poli, unsigned int numberOfPoints, bool closePolygon )
{ {
lazy_init(); lazy_init();
s_pShader->use(); s_shader->use();
s_pShader->setUniformsForBuiltins(); s_shader->setUniformsForBuiltins();
s_pShader->setUniformLocationWith4fv(s_nColorLocation, (GLfloat*) &s_tColor.r, 1); s_shader->setUniformLocationWith4fv(s_colorLocation, (GLfloat*) &s_color.r, 1);
ccGLEnableVertexAttribs( kVertexAttribFlag_Position ); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
// iPhone and 32-bit machines optimization // iPhone and 32-bit machines optimization
if( sizeof(Point) == sizeof(Vertex2F) ) if( sizeof(Point) == sizeof(Vertex2F) )
{ {
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
setGLBufferData((void*) poli, numberOfPoints * sizeof(Point)); setGLBufferData((void*) poli, numberOfPoints * sizeof(Point));
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else #else
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, poli); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, poli);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
if( closePolygon ) if( closePolygon )
@ -273,9 +275,9 @@ void ccDrawPoly( const Point *poli, unsigned int numberOfPoints, bool closePolyg
} }
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
setGLBufferData(newPoli, numberOfPoints * sizeof(Vertex2F)); setGLBufferData(newPoli, numberOfPoints * sizeof(Vertex2F));
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else #else
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, newPoli); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, newPoli);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
if( closePolygon ) if( closePolygon )
@ -289,15 +291,15 @@ void ccDrawPoly( const Point *poli, unsigned int numberOfPoints, bool closePolyg
CC_INCREMENT_GL_DRAWS(1); CC_INCREMENT_GL_DRAWS(1);
} }
void ccDrawSolidPoly( const Point *poli, unsigned int numberOfPoints, Color4F color ) void drawSolidPoly( const Point *poli, unsigned int numberOfPoints, Color4F color )
{ {
lazy_init(); lazy_init();
s_pShader->use(); s_shader->use();
s_pShader->setUniformsForBuiltins(); s_shader->setUniformsForBuiltins();
s_pShader->setUniformLocationWith4fv(s_nColorLocation, (GLfloat*) &color.r, 1); s_shader->setUniformLocationWith4fv(s_colorLocation, (GLfloat*) &color.r, 1);
ccGLEnableVertexAttribs( kVertexAttribFlag_Position ); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
// XXX: Mac OpenGL error. arrays can't go out of scope before draw is executed // XXX: Mac OpenGL error. arrays can't go out of scope before draw is executed
Vertex2F* newPoli = new Vertex2F[numberOfPoints]; Vertex2F* newPoli = new Vertex2F[numberOfPoints];
@ -307,9 +309,9 @@ void ccDrawSolidPoly( const Point *poli, unsigned int numberOfPoints, Color4F co
{ {
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
setGLBufferData((void*) poli, numberOfPoints * sizeof(Point)); setGLBufferData((void*) poli, numberOfPoints * sizeof(Point));
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else #else
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, poli); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, poli);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
} }
else else
@ -321,9 +323,9 @@ void ccDrawSolidPoly( const Point *poli, unsigned int numberOfPoints, Color4F co
} }
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
setGLBufferData(newPoli, numberOfPoints * sizeof(Vertex2F)); setGLBufferData(newPoli, numberOfPoints * sizeof(Vertex2F));
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else #else
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, newPoli); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, newPoli);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
} }
@ -333,7 +335,7 @@ void ccDrawSolidPoly( const Point *poli, unsigned int numberOfPoints, Color4F co
CC_INCREMENT_GL_DRAWS(1); CC_INCREMENT_GL_DRAWS(1);
} }
void ccDrawCircle( const Point& center, float radius, float angle, unsigned int segments, bool drawLineToCenter, float scaleX, float scaleY) void drawCircle( const Point& center, float radius, float angle, unsigned int segments, bool drawLineToCenter, float scaleX, float scaleY)
{ {
lazy_init(); lazy_init();
@ -358,31 +360,31 @@ void ccDrawCircle( const Point& center, float radius, float angle, unsigned int
vertices[(segments+1)*2] = center.x; vertices[(segments+1)*2] = center.x;
vertices[(segments+1)*2+1] = center.y; vertices[(segments+1)*2+1] = center.y;
s_pShader->use(); s_shader->use();
s_pShader->setUniformsForBuiltins(); s_shader->setUniformsForBuiltins();
s_pShader->setUniformLocationWith4fv(s_nColorLocation, (GLfloat*) &s_tColor.r, 1); s_shader->setUniformLocationWith4fv(s_colorLocation, (GLfloat*) &s_color.r, 1);
ccGLEnableVertexAttribs( kVertexAttribFlag_Position ); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
setGLBufferData(vertices, sizeof(GLfloat)*2*(segments+2)); setGLBufferData(vertices, sizeof(GLfloat)*2*(segments+2));
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else #else
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, vertices); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
glDrawArrays(GL_LINE_STRIP, 0, (GLsizei) segments+additionalSegment); glDrawArrays(GL_LINE_STRIP, 0, (GLsizei) segments+additionalSegment);
free( vertices ); ::free( vertices );
CC_INCREMENT_GL_DRAWS(1); CC_INCREMENT_GL_DRAWS(1);
} }
void CC_DLL ccDrawCircle( const Point& center, float radius, float angle, unsigned int segments, bool drawLineToCenter) void drawCircle( const Point& center, float radius, float angle, unsigned int segments, bool drawLineToCenter)
{ {
ccDrawCircle(center, radius, angle, segments, drawLineToCenter, 1.0f, 1.0f); drawCircle(center, radius, angle, segments, drawLineToCenter, 1.0f, 1.0f);
} }
void ccDrawSolidCircle( const Point& center, float radius, float angle, unsigned int segments, float scaleX, float scaleY) void drawSolidCircle( const Point& center, float radius, float angle, unsigned int segments, float scaleX, float scaleY)
{ {
lazy_init(); lazy_init();
@ -403,32 +405,32 @@ void ccDrawSolidCircle( const Point& center, float radius, float angle, unsigned
vertices[(segments+1)*2] = center.x; vertices[(segments+1)*2] = center.x;
vertices[(segments+1)*2+1] = center.y; vertices[(segments+1)*2+1] = center.y;
s_pShader->use(); s_shader->use();
s_pShader->setUniformsForBuiltins(); s_shader->setUniformsForBuiltins();
s_pShader->setUniformLocationWith4fv(s_nColorLocation, (GLfloat*) &s_tColor.r, 1); s_shader->setUniformLocationWith4fv(s_colorLocation, (GLfloat*) &s_color.r, 1);
ccGLEnableVertexAttribs( kVertexAttribFlag_Position ); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
setGLBufferData(vertices, sizeof(GLfloat)*2*(segments+2)); setGLBufferData(vertices, sizeof(GLfloat)*2*(segments+2));
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else #else
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, vertices); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
glDrawArrays(GL_TRIANGLE_FAN, 0, (GLsizei) segments+1); glDrawArrays(GL_TRIANGLE_FAN, 0, (GLsizei) segments+1);
free( vertices ); ::free( vertices );
CC_INCREMENT_GL_DRAWS(1); CC_INCREMENT_GL_DRAWS(1);
} }
void CC_DLL ccDrawSolidCircle( const Point& center, float radius, float angle, unsigned int segments) void drawSolidCircle( const Point& center, float radius, float angle, unsigned int segments)
{ {
ccDrawSolidCircle(center, radius, angle, segments, 1.0f, 1.0f); drawSolidCircle(center, radius, angle, segments, 1.0f, 1.0f);
} }
void ccDrawQuadBezier(const Point& origin, const Point& control, const Point& destination, unsigned int segments) void drawQuadBezier(const Point& origin, const Point& control, const Point& destination, unsigned int segments)
{ {
lazy_init(); lazy_init();
@ -444,17 +446,17 @@ void ccDrawQuadBezier(const Point& origin, const Point& control, const Point& de
vertices[segments].x = destination.x; vertices[segments].x = destination.x;
vertices[segments].y = destination.y; vertices[segments].y = destination.y;
s_pShader->use(); s_shader->use();
s_pShader->setUniformsForBuiltins(); s_shader->setUniformsForBuiltins();
s_pShader->setUniformLocationWith4fv(s_nColorLocation, (GLfloat*) &s_tColor.r, 1); s_shader->setUniformLocationWith4fv(s_colorLocation, (GLfloat*) &s_color.r, 1);
ccGLEnableVertexAttribs( kVertexAttribFlag_Position ); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
setGLBufferData(vertices, (segments + 1) * sizeof(Vertex2F)); setGLBufferData(vertices, (segments + 1) * sizeof(Vertex2F));
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else #else
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, vertices); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
glDrawArrays(GL_LINE_STRIP, 0, (GLsizei) segments + 1); glDrawArrays(GL_LINE_STRIP, 0, (GLsizei) segments + 1);
CC_SAFE_DELETE_ARRAY(vertices); CC_SAFE_DELETE_ARRAY(vertices);
@ -462,12 +464,12 @@ void ccDrawQuadBezier(const Point& origin, const Point& control, const Point& de
CC_INCREMENT_GL_DRAWS(1); CC_INCREMENT_GL_DRAWS(1);
} }
void ccDrawCatmullRom( PointArray *points, unsigned int segments ) void drawCatmullRom( PointArray *points, unsigned int segments )
{ {
ccDrawCardinalSpline( points, 0.5f, segments ); drawCardinalSpline( points, 0.5f, segments );
} }
void ccDrawCardinalSpline( PointArray *config, float tension, unsigned int segments ) void drawCardinalSpline( PointArray *config, float tension, unsigned int segments )
{ {
lazy_init(); lazy_init();
@ -501,17 +503,17 @@ void ccDrawCardinalSpline( PointArray *config, float tension, unsigned int segm
vertices[i].y = newPos.y; vertices[i].y = newPos.y;
} }
s_pShader->use(); s_shader->use();
s_pShader->setUniformsForBuiltins(); s_shader->setUniformsForBuiltins();
s_pShader->setUniformLocationWith4fv(s_nColorLocation, (GLfloat*)&s_tColor.r, 1); s_shader->setUniformLocationWith4fv(s_colorLocation, (GLfloat*)&s_color.r, 1);
ccGLEnableVertexAttribs( kVertexAttribFlag_Position ); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
setGLBufferData(vertices, (segments + 1) * sizeof(Vertex2F)); setGLBufferData(vertices, (segments + 1) * sizeof(Vertex2F));
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else #else
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, vertices); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
glDrawArrays(GL_LINE_STRIP, 0, (GLsizei) segments + 1); glDrawArrays(GL_LINE_STRIP, 0, (GLsizei) segments + 1);
@ -519,7 +521,7 @@ void ccDrawCardinalSpline( PointArray *config, float tension, unsigned int segm
CC_INCREMENT_GL_DRAWS(1); CC_INCREMENT_GL_DRAWS(1);
} }
void ccDrawCubicBezier(const Point& origin, const Point& control1, const Point& control2, const Point& destination, unsigned int segments) void drawCubicBezier(const Point& origin, const Point& control1, const Point& control2, const Point& destination, unsigned int segments)
{ {
lazy_init(); lazy_init();
@ -535,17 +537,17 @@ void ccDrawCubicBezier(const Point& origin, const Point& control1, const Point&
vertices[segments].x = destination.x; vertices[segments].x = destination.x;
vertices[segments].y = destination.y; vertices[segments].y = destination.y;
s_pShader->use(); s_shader->use();
s_pShader->setUniformsForBuiltins(); s_shader->setUniformsForBuiltins();
s_pShader->setUniformLocationWith4fv(s_nColorLocation, (GLfloat*) &s_tColor.r, 1); s_shader->setUniformLocationWith4fv(s_colorLocation, (GLfloat*) &s_color.r, 1);
ccGLEnableVertexAttribs( kVertexAttribFlag_Position ); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION );
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
setGLBufferData(vertices, (segments + 1) * sizeof(Vertex2F)); setGLBufferData(vertices, (segments + 1) * sizeof(Vertex2F));
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else #else
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, vertices); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, vertices);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
glDrawArrays(GL_LINE_STRIP, 0, (GLsizei) segments + 1); glDrawArrays(GL_LINE_STRIP, 0, (GLsizei) segments + 1);
CC_SAFE_DELETE_ARRAY(vertices); CC_SAFE_DELETE_ARRAY(vertices);
@ -553,28 +555,30 @@ void ccDrawCubicBezier(const Point& origin, const Point& control1, const Point&
CC_INCREMENT_GL_DRAWS(1); CC_INCREMENT_GL_DRAWS(1);
} }
void ccDrawColor4F( GLfloat r, GLfloat g, GLfloat b, GLfloat a ) void setDrawColor4F( GLfloat r, GLfloat g, GLfloat b, GLfloat a )
{ {
s_tColor.r = r; s_color.r = r;
s_tColor.g = g; s_color.g = g;
s_tColor.b = b; s_color.b = b;
s_tColor.a = a; s_color.a = a;
} }
void ccPointSize( GLfloat pointSize ) void setPointSize( GLfloat pointSize )
{ {
s_fPointSize = pointSize * CC_CONTENT_SCALE_FACTOR(); s_pointSize = pointSize * CC_CONTENT_SCALE_FACTOR();
//TODO :glPointSize( pointSize ); //TODO :glPointSize( pointSize );
} }
void ccDrawColor4B( GLubyte r, GLubyte g, GLubyte b, GLubyte a ) void setDrawColor4B( GLubyte r, GLubyte g, GLubyte b, GLubyte a )
{ {
s_tColor.r = r/255.0f; s_color.r = r/255.0f;
s_tColor.g = g/255.0f; s_color.g = g/255.0f;
s_tColor.b = b/255.0f; s_color.b = b/255.0f;
s_tColor.a = a/255.0f; s_color.a = a/255.0f;
} }
} // DrawPrimitives namespace
NS_CC_END NS_CC_END

View File

@ -47,18 +47,18 @@ THE SOFTWARE.
/** /**
@file @file
Drawing OpenGL ES primitives. Drawing OpenGL ES primitives.
- ccDrawPoint, ccDrawPoints - drawPoint, drawPoints
- ccDrawLine - drawLine
- ccDrawRect, ccDrawSolidRect - drawRect, drawSolidRect
- ccDrawPoly, ccDrawSolidPoly - drawPoly, drawSolidPoly
- ccDrawCircle - drawCircle
- ccDrawQuadBezier - drawQuadBezier
- ccDrawCubicBezier - drawCubicBezier
- ccDrawCatmullRom - drawCatmullRom
- ccDrawCardinalSpline - drawCardinalSpline
You can change the color, point size, width by calling: You can change the color, point size, width by calling:
- ccDrawColor4B(), ccDrawColor4F() - drawColor4B(), drawColor4F()
- ccPointSize() - ccPointSize()
- glLineWidth() - glLineWidth()
@ -75,86 +75,90 @@ NS_CC_BEGIN
class PointArray; class PointArray;
/** Initializes the drawing primitives */ namespace DrawPrimitives
void CC_DLL ccDrawInit(); {
/** Initializes the drawing primitives */
void init();
/** Frees allocated resources by the drawing primitives */ /** Frees allocated resources by the drawing primitives */
void CC_DLL ccDrawFree(); void free();
/** draws a point given x and y coordinate measured in points */ /** draws a point given x and y coordinate measured in points */
void CC_DLL ccDrawPoint( const Point& point ); void drawPoint( const Point& point );
/** draws an array of points. /** draws an array of points.
@since v0.7.2 @since v0.7.2
*/ */
void CC_DLL ccDrawPoints( const Point *points, unsigned int numberOfPoints ); void drawPoints( const Point *points, unsigned int numberOfPoints );
/** draws a line given the origin and destination point measured in points */ /** draws a line given the origin and destination point measured in points */
void CC_DLL ccDrawLine( const Point& origin, const Point& destination ); void drawLine( const Point& origin, const Point& destination );
/** draws a rectangle given the origin and destination point measured in points. */ /** draws a rectangle given the origin and destination point measured in points. */
void CC_DLL ccDrawRect( Point origin, Point destination ); void drawRect( Point origin, Point destination );
/** draws a solid rectangle given the origin and destination point measured in points. /** draws a solid rectangle given the origin and destination point measured in points.
@since 1.1 @since 1.1
*/ */
void CC_DLL ccDrawSolidRect( Point origin, Point destination, Color4F color ); void drawSolidRect( Point origin, Point destination, Color4F color );
/** draws a polygon given a pointer to Point coordinates and the number of vertices measured in points. /** draws a polygon given a pointer to Point coordinates and the number of vertices measured in points.
The polygon can be closed or open The polygon can be closed or open
*/ */
void CC_DLL ccDrawPoly( const Point *vertices, unsigned int numOfVertices, bool closePolygon ); void drawPoly( const Point *vertices, unsigned int numOfVertices, bool closePolygon );
/** draws a solid polygon given a pointer to CGPoint coordinates, the number of vertices measured in points, and a color. /** draws a solid polygon given a pointer to CGPoint coordinates, the number of vertices measured in points, and a color.
*/ */
void CC_DLL ccDrawSolidPoly( const Point *poli, unsigned int numberOfPoints, Color4F color ); void drawSolidPoly( const Point *poli, unsigned int numberOfPoints, Color4F color );
/** draws a circle given the center, radius and number of segments. */ /** draws a circle given the center, radius and number of segments. */
void CC_DLL ccDrawCircle( const Point& center, float radius, float angle, unsigned int segments, bool drawLineToCenter, float scaleX, float scaleY); void drawCircle( const Point& center, float radius, float angle, unsigned int segments, bool drawLineToCenter, float scaleX, float scaleY);
void CC_DLL ccDrawCircle( const Point& center, float radius, float angle, unsigned int segments, bool drawLineToCenter); void drawCircle( const Point& center, float radius, float angle, unsigned int segments, bool drawLineToCenter);
/** draws a solid circle given the center, radius and number of segments. */ /** draws a solid circle given the center, radius and number of segments. */
void CC_DLL ccDrawSolidCircle( const Point& center, float radius, float angle, unsigned int segments, float scaleX, float scaleY); void drawSolidCircle( const Point& center, float radius, float angle, unsigned int segments, float scaleX, float scaleY);
void CC_DLL ccDrawSolidCircle( const Point& center, float radius, float angle, unsigned int segments); void drawSolidCircle( const Point& center, float radius, float angle, unsigned int segments);
/** draws a quad bezier path /** draws a quad bezier path
@warning This function could be pretty slow. Use it only for debugging purposes. @warning This function could be pretty slow. Use it only for debugging purposes.
@since v0.8 @since v0.8
*/ */
void CC_DLL ccDrawQuadBezier(const Point& origin, const Point& control, const Point& destination, unsigned int segments); void drawQuadBezier(const Point& origin, const Point& control, const Point& destination, unsigned int segments);
/** draws a cubic bezier path /** draws a cubic bezier path
@warning This function could be pretty slow. Use it only for debugging purposes. @warning This function could be pretty slow. Use it only for debugging purposes.
@since v0.8 @since v0.8
*/ */
void CC_DLL ccDrawCubicBezier(const Point& origin, const Point& control1, const Point& control2, const Point& destination, unsigned int segments); void drawCubicBezier(const Point& origin, const Point& control1, const Point& control2, const Point& destination, unsigned int segments);
/** draws a Catmull Rom path. /** draws a Catmull Rom path.
@warning This function could be pretty slow. Use it only for debugging purposes. @warning This function could be pretty slow. Use it only for debugging purposes.
@since v2.0 @since v2.0
*/ */
void CC_DLL ccDrawCatmullRom( PointArray *arrayOfControlPoints, unsigned int segments ); void drawCatmullRom( PointArray *arrayOfControlPoints, unsigned int segments );
/** draws a Cardinal Spline path. /** draws a Cardinal Spline path.
@warning This function could be pretty slow. Use it only for debugging purposes. @warning This function could be pretty slow. Use it only for debugging purposes.
@since v2.0 @since v2.0
*/ */
void CC_DLL ccDrawCardinalSpline( PointArray *config, float tension, unsigned int segments ); void drawCardinalSpline( PointArray *config, float tension, unsigned int segments );
/** set the drawing color with 4 unsigned bytes /** set the drawing color with 4 unsigned bytes
@since v2.0 @since v2.0
*/ */
void CC_DLL ccDrawColor4B( GLubyte r, GLubyte g, GLubyte b, GLubyte a ); void setDrawColor4B( GLubyte r, GLubyte g, GLubyte b, GLubyte a );
/** set the drawing color with 4 floats /** set the drawing color with 4 floats
@since v2.0 @since v2.0
*/ */
void CC_DLL ccDrawColor4F( GLfloat r, GLfloat g, GLfloat b, GLfloat a ); void setDrawColor4F( GLfloat r, GLfloat g, GLfloat b, GLfloat a );
/** set the point size in points. Default 1. /** set the point size in points. Default 1.
@since v2.0 @since v2.0
*/ */
void CC_DLL ccPointSize( GLfloat pointSize ); void setPointSize( GLfloat pointSize );
};
// end of global group // end of global group
/// @} /// @}

View File

@ -38,7 +38,7 @@ Grabber::Grabber(void)
glGenFramebuffers(1, &_FBO); glGenFramebuffers(1, &_FBO);
} }
void Grabber::grab(Texture2D *pTexture) void Grabber::grab(Texture2D *texture)
{ {
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO); glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO);
@ -46,7 +46,7 @@ void Grabber::grab(Texture2D *pTexture)
glBindFramebuffer(GL_FRAMEBUFFER, _FBO); glBindFramebuffer(GL_FRAMEBUFFER, _FBO);
// associate texture with FBO // associate texture with FBO
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, pTexture->getName(), 0); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture->getName(), 0);
// check if it worked (probably worth doing :) ) // check if it worked (probably worth doing :) )
GLuint status = glCheckFramebufferStatus(GL_FRAMEBUFFER); GLuint status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
@ -58,9 +58,9 @@ void Grabber::grab(Texture2D *pTexture)
glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO); glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO);
} }
void Grabber::beforeRender(Texture2D *pTexture) void Grabber::beforeRender(Texture2D *texture)
{ {
CC_UNUSED_PARAM(pTexture); CC_UNUSED_PARAM(texture);
glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO); glGetIntegerv(GL_FRAMEBUFFER_BINDING, &_oldFBO);
glBindFramebuffer(GL_FRAMEBUFFER, _FBO); glBindFramebuffer(GL_FRAMEBUFFER, _FBO);
@ -80,9 +80,9 @@ void Grabber::beforeRender(Texture2D *pTexture)
// glColorMask(true, true, true, false); // #631 // glColorMask(true, true, true, false); // #631
} }
void Grabber::afterRender(cocos2d::Texture2D *pTexture) void Grabber::afterRender(cocos2d::Texture2D *texture)
{ {
CC_UNUSED_PARAM(pTexture); CC_UNUSED_PARAM(texture);
glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO); glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO);
// glColorMask(true, true, true, true); // #631 // glColorMask(true, true, true, true); // #631

View File

@ -45,9 +45,9 @@ public:
Grabber(void); Grabber(void);
~Grabber(void); ~Grabber(void);
void grab(Texture2D *pTexture); void grab(Texture2D *texture);
void beforeRender(Texture2D *pTexture); void beforeRender(Texture2D *texture);
void afterRender(Texture2D *pTexture); void afterRender(Texture2D *texture);
protected: protected:
GLuint _FBO; GLuint _FBO;

View File

@ -76,7 +76,7 @@ GridBase* GridBase::create(const Size& gridSize, Texture2D *texture, bool flippe
return pGridBase; return pGridBase;
} }
bool GridBase::initWithSize(const Size& gridSize, Texture2D *pTexture, bool bFlipped) bool GridBase::initWithSize(const Size& gridSize, Texture2D *texture, bool bFlipped)
{ {
bool bRet = true; bool bRet = true;
@ -84,7 +84,7 @@ bool GridBase::initWithSize(const Size& gridSize, Texture2D *pTexture, bool bFli
_reuseGrid = 0; _reuseGrid = 0;
_gridSize = gridSize; _gridSize = gridSize;
_texture = pTexture; _texture = texture;
CC_SAFE_RETAIN(_texture); CC_SAFE_RETAIN(_texture);
_isTextureFlipped = bFlipped; _isTextureFlipped = bFlipped;
@ -102,7 +102,7 @@ bool GridBase::initWithSize(const Size& gridSize, Texture2D *pTexture, bool bFli
bRet = false; bRet = false;
} }
_shaderProgram = ShaderCache::getInstance()->programForKey(kShader_PositionTexture); _shaderProgram = ShaderCache::getInstance()->programForKey(GLProgram::SHADER_NAME_POSITION_TEXTURE);
calculateVertexPoints(); calculateVertexPoints();
return bRet; return bRet;
@ -117,7 +117,7 @@ bool GridBase::initWithSize(const Size& gridSize)
unsigned long POTHigh = ccNextPOT((unsigned int)s.height); unsigned long POTHigh = ccNextPOT((unsigned int)s.height);
// we only use rgba8888 // we only use rgba8888
Texture2DPixelFormat format = kTexture2DPixelFormat_RGBA8888; Texture2D::PixelFormat format = Texture2D::PixelFormat::RGBA8888;
void *data = calloc((int)(POTWide * POTHigh * 4), 1); void *data = calloc((int)(POTWide * POTHigh * 4), 1);
if (! data) if (! data)
@ -127,20 +127,20 @@ bool GridBase::initWithSize(const Size& gridSize)
return false; return false;
} }
Texture2D *pTexture = new Texture2D(); Texture2D *texture = new Texture2D();
pTexture->initWithData(data, format, POTWide, POTHigh, s); texture->initWithData(data, format, POTWide, POTHigh, s);
free(data); free(data);
if (! pTexture) if (! texture)
{ {
CCLOG("cocos2d: Grid: error creating texture"); CCLOG("cocos2d: Grid: error creating texture");
return false; return false;
} }
initWithSize(gridSize, pTexture, false); initWithSize(gridSize, texture, false);
pTexture->release(); texture->release();
return true; return true;
} }
@ -161,7 +161,7 @@ void GridBase::setActive(bool bActive)
if (! bActive) if (! bActive)
{ {
Director *pDirector = Director::getInstance(); Director *pDirector = Director::getInstance();
ccDirectorProjection proj = pDirector->getProjection(); Director::Projection proj = pDirector->getProjection();
pDirector->setProjection(proj); pDirector->setProjection(proj);
} }
} }
@ -192,8 +192,7 @@ void GridBase::set2DProjection()
kmGLMatrixMode(KM_GL_MODELVIEW); kmGLMatrixMode(KM_GL_MODELVIEW);
kmGLLoadIdentity(); kmGLLoadIdentity();
GL::setProjectionMatrixDirty();
ccSetProjectionMatrixDirty();
} }
void GridBase::beforeDraw(void) void GridBase::beforeDraw(void)
@ -203,7 +202,7 @@ void GridBase::beforeDraw(void)
_directorProjection = director->getProjection(); _directorProjection = director->getProjection();
// 2d projection // 2d projection
// [director setProjection:kDirectorProjection2D]; // [director setProjection:Director::Projection::_2D];
set2DProjection(); set2DProjection();
_grabber->beforeRender(_texture); _grabber->beforeRender(_texture);
} }
@ -228,7 +227,7 @@ void GridBase::afterDraw(cocos2d::Node *target)
kmGLTranslatef(-offset.x, -offset.y, 0); kmGLTranslatef(-offset.x, -offset.y, 0);
} }
ccGLBindTexture2D(_texture->getName()); GL::bindTexture2D(_texture->getName());
// restore projection for default FBO .fixed bug #543 #544 // restore projection for default FBO .fixed bug #543 #544
//TODO: Director::getInstance()->setProjection(Director::getInstance()->getProjection()); //TODO: Director::getInstance()->setProjection(Director::getInstance()->getProjection());
@ -253,13 +252,13 @@ void GridBase::calculateVertexPoints(void)
// implementation of Grid3D // implementation of Grid3D
Grid3D* Grid3D::create(const Size& gridSize, Texture2D *pTexture, bool bFlipped) Grid3D* Grid3D::create(const Size& gridSize, Texture2D *texture, bool bFlipped)
{ {
Grid3D *pRet= new Grid3D(); Grid3D *pRet= new Grid3D();
if (pRet) if (pRet)
{ {
if (pRet->initWithSize(gridSize, pTexture, bFlipped)) if (pRet->initWithSize(gridSize, texture, bFlipped))
{ {
pRet->autorelease(); pRet->autorelease();
} }
@ -315,7 +314,7 @@ void Grid3D::blit(void)
{ {
int n = _gridSize.width * _gridSize.height; int n = _gridSize.width * _gridSize.height;
ccGLEnableVertexAttribs( kVertexAttribFlag_Position | kVertexAttribFlag_TexCoords ); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION | GL::VERTEX_ATTRIB_FLAG_TEX_COORDS );
_shaderProgram->use(); _shaderProgram->use();
_shaderProgram->setUniformsForBuiltins();; _shaderProgram->setUniformsForBuiltins();;
@ -328,20 +327,20 @@ void Grid3D::blit(void)
// position // position
setGLBufferData(_vertices, numOfPoints * sizeof(Vertex3F), 0); setGLBufferData(_vertices, numOfPoints * sizeof(Vertex3F), 0);
glVertexAttribPointer(kVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, 0, 0);
// texCoords // texCoords
setGLBufferData(_texCoordinates, numOfPoints * sizeof(Vertex2F), 1); setGLBufferData(_texCoordinates, numOfPoints * sizeof(Vertex2F), 1);
glVertexAttribPointer(kVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, 0, 0);
setGLIndexData(_indices, n * 12, 0); setGLIndexData(_indices, n * 12, 0);
glDrawElements(GL_TRIANGLES, (GLsizei) n*6, GL_UNSIGNED_SHORT, 0); glDrawElements(GL_TRIANGLES, (GLsizei) n*6, GL_UNSIGNED_SHORT, 0);
#else #else
// position // position
glVertexAttribPointer(kVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, 0, _vertices); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, 0, _vertices);
// texCoords // texCoords
glVertexAttribPointer(kVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, _texCoordinates); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, 0, _texCoordinates);
glDrawElements(GL_TRIANGLES, (GLsizei) n*6, GL_UNSIGNED_SHORT, _indices); glDrawElements(GL_TRIANGLES, (GLsizei) n*6, GL_UNSIGNED_SHORT, _indices);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
@ -486,13 +485,13 @@ TiledGrid3D::~TiledGrid3D(void)
CC_SAFE_FREE(_indices); CC_SAFE_FREE(_indices);
} }
TiledGrid3D* TiledGrid3D::create(const Size& gridSize, Texture2D *pTexture, bool bFlipped) TiledGrid3D* TiledGrid3D::create(const Size& gridSize, Texture2D *texture, bool bFlipped)
{ {
TiledGrid3D *pRet= new TiledGrid3D(); TiledGrid3D *pRet= new TiledGrid3D();
if (pRet) if (pRet)
{ {
if (pRet->initWithSize(gridSize, pTexture, bFlipped)) if (pRet->initWithSize(gridSize, texture, bFlipped))
{ {
pRet->autorelease(); pRet->autorelease();
} }
@ -537,26 +536,26 @@ void TiledGrid3D::blit(void)
// //
// Attributes // Attributes
// //
ccGLEnableVertexAttribs( kVertexAttribFlag_Position | kVertexAttribFlag_TexCoords ); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION | GL::VERTEX_ATTRIB_FLAG_TEX_COORDS );
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
int numQuads = _gridSize.width * _gridSize.height; int numQuads = _gridSize.width * _gridSize.height;
// position // position
setGLBufferData(_vertices, (numQuads*4*sizeof(Vertex3F)), 0); setGLBufferData(_vertices, (numQuads*4*sizeof(Vertex3F)), 0);
glVertexAttribPointer(kVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, 0, 0);
// texCoords // texCoords
setGLBufferData(_texCoordinates, (numQuads*4*sizeof(Vertex2F)), 1); setGLBufferData(_texCoordinates, (numQuads*4*sizeof(Vertex2F)), 1);
glVertexAttribPointer(kVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, 0, 0);
setGLIndexData(_indices, n * 12, 0); setGLIndexData(_indices, n * 12, 0);
glDrawElements(GL_TRIANGLES, (GLsizei) n*6, GL_UNSIGNED_SHORT, 0); glDrawElements(GL_TRIANGLES, (GLsizei) n*6, GL_UNSIGNED_SHORT, 0);
#else #else
// position // position
glVertexAttribPointer(kVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, 0, _vertices); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, 0, _vertices);
// texCoords // texCoords
glVertexAttribPointer(kVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, _texCoordinates); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, 0, _texCoordinates);
glDrawElements(GL_TRIANGLES, (GLsizei)n*6, GL_UNSIGNED_SHORT, _indices); glDrawElements(GL_TRIANGLES, (GLsizei)n*6, GL_UNSIGNED_SHORT, _indices);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN

View File

@ -59,7 +59,7 @@ public:
virtual ~GridBase(void); virtual ~GridBase(void);
bool initWithSize(const Size& gridSize, Texture2D *pTexture, bool bFlipped); bool initWithSize(const Size& gridSize, Texture2D *texture, bool bFlipped);
bool initWithSize(const Size& gridSize); bool initWithSize(const Size& gridSize);
/** whether or not the grid is active */ /** whether or not the grid is active */
@ -99,7 +99,7 @@ protected:
Grabber *_grabber; Grabber *_grabber;
bool _isTextureFlipped; bool _isTextureFlipped;
GLProgram* _shaderProgram; GLProgram* _shaderProgram;
ccDirectorProjection _directorProjection; Director::Projection _directorProjection;
}; };
/** /**
@ -112,7 +112,7 @@ class CC_DLL Grid3D : public GridBase
{ {
public: public:
/** create one Grid */ /** create one Grid */
static Grid3D* create(const Size& gridSize, Texture2D *pTexture, bool bFlipped); static Grid3D* create(const Size& gridSize, Texture2D *texture, bool bFlipped);
/** create one Grid */ /** create one Grid */
static Grid3D* create(const Size& gridSize); static Grid3D* create(const Size& gridSize);
@ -154,7 +154,7 @@ class CC_DLL TiledGrid3D : public GridBase
{ {
public: public:
/** create one Grid */ /** create one Grid */
static TiledGrid3D* create(const Size& gridSize, Texture2D *pTexture, bool bFlipped); static TiledGrid3D* create(const Size& gridSize, Texture2D *texture, bool bFlipped);
/** create one Grid */ /** create one Grid */
static TiledGrid3D* create(const Size& gridSize); static TiledGrid3D* create(const Size& gridSize);

View File

@ -390,26 +390,26 @@ CC_DEPRECATED_ATTRIBUTE inline Rect CCRectMake(float x, float y, float width, fl
} }
CC_DEPRECATED_ATTRIBUTE const Point CCPointZero = Point::ZERO; CC_DEPRECATED_ATTRIBUTE extern const Point CCPointZero;
/* The "zero" size -- equivalent to Size(0, 0). */ /* The "zero" size -- equivalent to Size(0, 0). */
CC_DEPRECATED_ATTRIBUTE const Size CCSizeZero = Size::ZERO; CC_DEPRECATED_ATTRIBUTE extern const Size CCSizeZero;
/* The "zero" rectangle -- equivalent to Rect(0, 0, 0, 0). */ /* The "zero" rectangle -- equivalent to Rect(0, 0, 0, 0). */
CC_DEPRECATED_ATTRIBUTE const Rect CCRectZero = Rect::ZERO; CC_DEPRECATED_ATTRIBUTE extern const Rect CCRectZero;
CC_DEPRECATED_ATTRIBUTE const Color3B ccWHITE = Color3B::WHITE; CC_DEPRECATED_ATTRIBUTE extern const Color3B ccWHITE;
CC_DEPRECATED_ATTRIBUTE const Color3B ccYELLOW = Color3B::YELLOW; CC_DEPRECATED_ATTRIBUTE extern const Color3B ccYELLOW;
CC_DEPRECATED_ATTRIBUTE const Color3B ccGREEN = Color3B::GREEN; CC_DEPRECATED_ATTRIBUTE extern const Color3B ccGREEN;
CC_DEPRECATED_ATTRIBUTE const Color3B ccBLUE = Color3B::BLUE; CC_DEPRECATED_ATTRIBUTE extern const Color3B ccBLUE;
CC_DEPRECATED_ATTRIBUTE const Color3B ccRED = Color3B::RED; CC_DEPRECATED_ATTRIBUTE extern const Color3B ccRED;
CC_DEPRECATED_ATTRIBUTE const Color3B ccMAGENTA = Color3B::MAGENTA; CC_DEPRECATED_ATTRIBUTE extern const Color3B ccMAGENTA;
CC_DEPRECATED_ATTRIBUTE const Color3B ccBLACK = Color3B::BLACK; CC_DEPRECATED_ATTRIBUTE extern const Color3B ccBLACK;
CC_DEPRECATED_ATTRIBUTE const Color3B ccORANGE = Color3B::ORANGE; CC_DEPRECATED_ATTRIBUTE extern const Color3B ccORANGE;
CC_DEPRECATED_ATTRIBUTE const Color3B ccGRAY = Color3B::GRAY; CC_DEPRECATED_ATTRIBUTE extern const Color3B ccGRAY;
CC_DEPRECATED_ATTRIBUTE const BlendFunc kBlendFuncDisable = BlendFunc::BLEND_FUNC_DISABLE; CC_DEPRECATED_ATTRIBUTE extern const BlendFunc kCCBlendFuncDisable;
CC_DEPRECATED_ATTRIBUTE static inline Color3B ccc3(GLubyte r, GLubyte g, GLubyte b) CC_DEPRECATED_ATTRIBUTE static inline Color3B ccc3(GLubyte r, GLubyte g, GLubyte b)
{ {
@ -471,9 +471,20 @@ CC_DEPRECATED_ATTRIBUTE static inline Tex2F tex2(const float u, const float v)
return t; return t;
} }
#define CCAffineTransformMake AffineTransformMake CC_DEPRECATED_ATTRIBUTE static inline AffineTransform CCAffineTransformMake(float a, float b, float c, float d, float tx, float ty)
#define CCPointApplyAffineTransform PointApplyAffineTransform {
#define CCSizeApplyAffineTransform SizeApplyAffineTransform return AffineTransformMake(a, b, c, d, tx, ty);
}
CC_DEPRECATED_ATTRIBUTE static inline Point CCPointApplyAffineTransform(const Point& point, const AffineTransform& t)
{
return PointApplyAffineTransform(point, t);
}
CC_DEPRECATED_ATTRIBUTE static inline Size CCSizeApplyAffineTransform(const Size& size, const AffineTransform& t)
{
return SizeApplyAffineTransform(size, t);
}
CC_DEPRECATED_ATTRIBUTE static inline AffineTransform CCAffineTransformMakeIdentity() CC_DEPRECATED_ATTRIBUTE static inline AffineTransform CCAffineTransformMakeIdentity()
{ {
@ -515,8 +526,10 @@ CC_DEPRECATED_ATTRIBUTE static inline AffineTransform CCAffineTransformInvert(co
return AffineTransformInvert(t); return AffineTransformInvert(t);
} }
#define CCAffineTransformIdentity AffineTransformIdentity CC_DEPRECATED_ATTRIBUTE static inline AffineTransform CCAffineTransformIdentity()
{
return AffineTransformMakeIdentity();
}
// CC prefix compatibility // CC prefix compatibility
CC_DEPRECATED_ATTRIBUTE typedef Object CCObject; CC_DEPRECATED_ATTRIBUTE typedef Object CCObject;
@ -622,6 +635,9 @@ CC_DEPRECATED_ATTRIBUTE typedef FlipX CCFlipX;
CC_DEPRECATED_ATTRIBUTE typedef FlipY CCFlipY; CC_DEPRECATED_ATTRIBUTE typedef FlipY CCFlipY;
CC_DEPRECATED_ATTRIBUTE typedef Place CCPlace; CC_DEPRECATED_ATTRIBUTE typedef Place CCPlace;
CC_DEPRECATED_ATTRIBUTE typedef CallFunc CCCallFunc; CC_DEPRECATED_ATTRIBUTE typedef CallFunc CCCallFunc;
CC_DEPRECATED_ATTRIBUTE typedef CallFuncN CCCallFuncN;
CC_DEPRECATED_ATTRIBUTE typedef __CCCallFuncND CCCallFuncND;
CC_DEPRECATED_ATTRIBUTE typedef __CCCallFuncO CCCallFuncO;
CC_DEPRECATED_ATTRIBUTE typedef GridAction CCGridAction; CC_DEPRECATED_ATTRIBUTE typedef GridAction CCGridAction;
CC_DEPRECATED_ATTRIBUTE typedef Grid3DAction CCGrid3DAction; CC_DEPRECATED_ATTRIBUTE typedef Grid3DAction CCGrid3DAction;
CC_DEPRECATED_ATTRIBUTE typedef TiledGrid3DAction CCTiledGrid3DAction; CC_DEPRECATED_ATTRIBUTE typedef TiledGrid3DAction CCTiledGrid3DAction;
@ -760,6 +776,7 @@ CC_DEPRECATED_ATTRIBUTE typedef Timer CCTimer;
CC_DEPRECATED_ATTRIBUTE typedef Scheduler CCScheduler; CC_DEPRECATED_ATTRIBUTE typedef Scheduler CCScheduler;
CC_DEPRECATED_ATTRIBUTE typedef EGLView CCEGLView; CC_DEPRECATED_ATTRIBUTE typedef EGLView CCEGLView;
CC_DEPRECATED_ATTRIBUTE typedef Component CCComponent;
CC_DEPRECATED_ATTRIBUTE typedef AffineTransform CCAffineTransform; CC_DEPRECATED_ATTRIBUTE typedef AffineTransform CCAffineTransform;
CC_DEPRECATED_ATTRIBUTE typedef Point CCPoint; CC_DEPRECATED_ATTRIBUTE typedef Point CCPoint;
CC_DEPRECATED_ATTRIBUTE typedef Size CCSize; CC_DEPRECATED_ATTRIBUTE typedef Size CCSize;
@ -787,119 +804,175 @@ CC_DEPRECATED_ATTRIBUTE typedef FontShadow ccFontShadow;
CC_DEPRECATED_ATTRIBUTE typedef FontStroke ccFontStroke; CC_DEPRECATED_ATTRIBUTE typedef FontStroke ccFontStroke;
CC_DEPRECATED_ATTRIBUTE typedef FontDefinition ccFontDefinition; CC_DEPRECATED_ATTRIBUTE typedef FontDefinition ccFontDefinition;
CC_DEPRECATED_ATTRIBUTE typedef VerticalTextAlignment CCVerticalTextAlignment; CC_DEPRECATED_ATTRIBUTE typedef Label::VAlignment CCVerticalTextAlignment;
CC_DEPRECATED_ATTRIBUTE typedef TextAlignment CCTextAlignment; CC_DEPRECATED_ATTRIBUTE typedef Label::HAlignment CCTextAlignment;
CC_DEPRECATED_ATTRIBUTE typedef ProgressTimerType CCProgressTimerType; CC_DEPRECATED_ATTRIBUTE typedef ProgressTimer::Type CCProgressTimerType;
CC_DEPRECATED_ATTRIBUTE typedef void* CCZone; CC_DEPRECATED_ATTRIBUTE typedef void* CCZone;
#define kCCVertexAttrib_Position kVertexAttrib_Position CC_DEPRECATED_ATTRIBUTE extern const int kCCVertexAttrib_Position;
#define kCCVertexAttrib_Color kVertexAttrib_Color CC_DEPRECATED_ATTRIBUTE extern const int kCCVertexAttrib_Color;
#define kCCVertexAttrib_TexCoords kVertexAttrib_TexCoords CC_DEPRECATED_ATTRIBUTE extern const int kCCVertexAttrib_TexCoords;
#define kCCVertexAttrib_MAX kVertexAttrib_MAX CC_DEPRECATED_ATTRIBUTE extern const int kCCVertexAttrib_MAX;
#define kCCUniformPMatrix kUniformPMatrix CC_DEPRECATED_ATTRIBUTE extern const int kCCUniformPMatrix;
#define kCCUniformMVMatrix kUniformMVMatrix CC_DEPRECATED_ATTRIBUTE extern const int kCCUniformMVMatrix;
#define kCCUniformMVPMatrix kUniformMVPMatrix CC_DEPRECATED_ATTRIBUTE extern const int kCCUniformMVPMatrix;
#define kCCUniformTime kUniformTime CC_DEPRECATED_ATTRIBUTE extern const int kCCUniformTime;
#define kCCUniformSinTime kUniformSinTime CC_DEPRECATED_ATTRIBUTE extern const int kCCUniformSinTime;
#define kCCUniformCosTime kUniformCosTime CC_DEPRECATED_ATTRIBUTE extern const int kCCUniformCosTime;
#define kCCUniformRandom01 kUniformRandom01 CC_DEPRECATED_ATTRIBUTE extern const int kCCUniformRandom01;
#define kCCUniformSampler kUniformSampler CC_DEPRECATED_ATTRIBUTE extern const int kCCUniformSampler;
#define kCCUniform_MAX kUniform_MAX CC_DEPRECATED_ATTRIBUTE extern const int kCCUniform_MAX;
CC_DEPRECATED_ATTRIBUTE extern const char* kCCShader_PositionTextureColor;
#define kCCShader_PositionTextureColor kShader_PositionTextureColor CC_DEPRECATED_ATTRIBUTE extern const char* kCCShader_PositionTextureColorAlphaTest;
#define kCCShader_PositionTextureColorAlphaTest kShader_PositionTextureColorAlphaTest CC_DEPRECATED_ATTRIBUTE extern const char* kCCShader_PositionColor;
#define kCCShader_PositionColor kShader_PositionColor CC_DEPRECATED_ATTRIBUTE extern const char* kCCShader_PositionTexture;
#define kCCShader_PositionTexture kShader_PositionTexture CC_DEPRECATED_ATTRIBUTE extern const char* kCCShader_PositionTexture_uColor;
#define kCCShader_PositionTexture_uColor kShader_PositionTexture_uColor CC_DEPRECATED_ATTRIBUTE extern const char* kCCShader_PositionTextureA8Color;
#define kCCShader_PositionTextureA8Color kShader_PositionTextureA8Color CC_DEPRECATED_ATTRIBUTE extern const char* kCCShader_Position_uColor;
#define kCCShader_Position_uColor kShader_Position_uColor CC_DEPRECATED_ATTRIBUTE extern const char* kCCShader_PositionLengthTexureColor;
#define kCCShader_PositionLengthTexureColor kShader_PositionLengthTexureColor
// uniform names // uniform names
#define kCCUniformPMatrix_s kUniformPMatrix_s CC_DEPRECATED_ATTRIBUTE extern const char* kCCUniformPMatrix_s;
#define kCCUniformMVMatrix_s kUniformMVMatrix_s CC_DEPRECATED_ATTRIBUTE extern const char* kCCUniformMVMatrix_s;
#define kCCUniformMVPMatrix_s kUniformMVPMatrix_s CC_DEPRECATED_ATTRIBUTE extern const char* kCCUniformMVPMatrix_s;
#define kCCUniformTime_s kUniformTime_s CC_DEPRECATED_ATTRIBUTE extern const char* kCCUniformTime_s;
#define kCCUniformSinTime_s kUniformSinTime_s CC_DEPRECATED_ATTRIBUTE extern const char* kCCUniformSinTime_s;
#define kCCUniformCosTime_s kUniformCosTime_s CC_DEPRECATED_ATTRIBUTE extern const char* kCCUniformCosTime_s;
#define kCCUniformRandom01_s kUniformRandom01_s CC_DEPRECATED_ATTRIBUTE extern const char* kCCUniformRandom01_s;
#define kCCUniformSampler_s kUniformSampler_s CC_DEPRECATED_ATTRIBUTE extern const char* kCCUniformSampler_s;
#define kCCUniformAlphaTestValue kUniformAlphaTestValue CC_DEPRECATED_ATTRIBUTE extern const char* kCCUniformAlphaTestValue;
// Attribute names // Attribute names
#define kCCAttributeNameColor kAttributeNameColor CC_DEPRECATED_ATTRIBUTE extern const char* kCCAttributeNameColor;
#define kCCAttributeNamePosition kAttributeNamePosition CC_DEPRECATED_ATTRIBUTE extern const char* kCCAttributeNamePosition;
#define kCCAttributeNameTexCoord kAttributeNameTexCoord CC_DEPRECATED_ATTRIBUTE extern const char* kCCAttributeNameTexCoord;
#define kCCVertexAttribFlag_None kVertexAttribFlag_None CC_DEPRECATED_ATTRIBUTE extern const int kCCVertexAttribFlag_None;
#define kCCVertexAttribFlag_Position kVertexAttribFlag_Position CC_DEPRECATED_ATTRIBUTE extern const int kCCVertexAttribFlag_Position;
#define kCCVertexAttribFlag_Color kVertexAttribFlag_Color CC_DEPRECATED_ATTRIBUTE extern const int kCCVertexAttribFlag_Color;
#define kCCVertexAttribFlag_TexCoords kVertexAttribFlag_TexCoords CC_DEPRECATED_ATTRIBUTE extern const int kCCVertexAttribFlag_TexCoords;
#define kCCVertexAttribFlag_PosColorTex kVertexAttribFlag_PosColorTex CC_DEPRECATED_ATTRIBUTE extern const int kCCVertexAttribFlag_PosColorTex;
#define kCCProgressTimerTypeRadial kProgressTimerTypeRadial CC_DEPRECATED_ATTRIBUTE extern const ProgressTimer::Type kCCProgressTimerTypeRadial;
#define kCCProgressTimerTypeBar kProgressTimerTypeBar CC_DEPRECATED_ATTRIBUTE extern const ProgressTimer::Type kCCProgressTimerTypeBar;
CC_DEPRECATED_ATTRIBUTE typedef ProgressTimer::Type ProgressTimerType;
#define kCCDirectorProjection2D kDirectorProjection2D CC_DEPRECATED_ATTRIBUTE extern const Director::Projection kCCDirectorProjection2D;
#define kCCDirectorProjection3D kDirectorProjection3D CC_DEPRECATED_ATTRIBUTE extern const Director::Projection kCCDirectorProjection3D;
#define kCCDirectorProjectionCustom kDirectorProjectionCustom CC_DEPRECATED_ATTRIBUTE extern const Director::Projection kCCDirectorProjectionCustom;
#define kCCDirectorProjectionDefault kDirectorProjectionDefault CC_DEPRECATED_ATTRIBUTE extern const Director::Projection kCCDirectorProjectionDefault;
CC_DEPRECATED_ATTRIBUTE typedef Director::Projection ccDirectorProjection;
#define kCCVerticalTextAlignmentTop kVerticalTextAlignmentTop CC_DEPRECATED_ATTRIBUTE extern const Label::VAlignment kCCVerticalTextAlignmentTop;
#define kCCVerticalTextAlignmentCenter kVerticalTextAlignmentCenter CC_DEPRECATED_ATTRIBUTE extern const Label::VAlignment kCCVerticalTextAlignmentCenter;
#define kCCVerticalTextAlignmentBottom kVerticalTextAlignmentBottom CC_DEPRECATED_ATTRIBUTE extern const Label::VAlignment kCCVerticalTextAlignmentBottom;
#define kCCTextAlignmentLeft kTextAlignmentLeft CC_DEPRECATED_ATTRIBUTE extern const Label::HAlignment kCCTextAlignmentLeft;
#define kCCTextAlignmentCenter kTextAlignmentCenter CC_DEPRECATED_ATTRIBUTE extern const Label::HAlignment kCCTextAlignmentCenter;
#define kCCTextAlignmentRight kTextAlignmentRight CC_DEPRECATED_ATTRIBUTE extern const Label::HAlignment kCCTextAlignmentRight;
CC_DEPRECATED_ATTRIBUTE extern const Texture2D::PixelFormat kCCTexture2DPixelFormat_RGBA8888;
#define kCCTexture2DPixelFormat_RGBA8888 kTexture2DPixelFormat_RGBA8888 CC_DEPRECATED_ATTRIBUTE extern const Texture2D::PixelFormat kCCTexture2DPixelFormat_RGB888;
#define kCCTexture2DPixelFormat_RGB888 kTexture2DPixelFormat_RGB888 CC_DEPRECATED_ATTRIBUTE extern const Texture2D::PixelFormat kCCTexture2DPixelFormat_RGB565;
#define kCCTexture2DPixelFormat_RGB565 kTexture2DPixelFormat_RGB565 CC_DEPRECATED_ATTRIBUTE extern const Texture2D::PixelFormat kCCTexture2DPixelFormat_A8;
#define kCCTexture2DPixelFormat_A8 kTexture2DPixelFormat_A8 CC_DEPRECATED_ATTRIBUTE extern const Texture2D::PixelFormat kCCTexture2DPixelFormat_I8;
#define kCCTexture2DPixelFormat_I8 kTexture2DPixelFormat_I8 CC_DEPRECATED_ATTRIBUTE extern const Texture2D::PixelFormat kCCTexture2DPixelFormat_AI88;
#define kCCTexture2DPixelFormat_AI88 kTexture2DPixelFormat_AI88 CC_DEPRECATED_ATTRIBUTE extern const Texture2D::PixelFormat kCCTexture2DPixelFormat_RGBA4444;
#define kCCTexture2DPixelFormat_RGBA4444 kTexture2DPixelFormat_RGBA4444 CC_DEPRECATED_ATTRIBUTE extern const Texture2D::PixelFormat kCCTexture2DPixelFormat_RGB5A1;
#define kCCTexture2DPixelFormat_RGB5A1 kTexture2DPixelFormat_RGB5A1 CC_DEPRECATED_ATTRIBUTE extern const Texture2D::PixelFormat kCCTexture2DPixelFormat_PVRTC4;
#define kCCTexture2DPixelFormat_PVRTC4 kTexture2DPixelFormat_PVRTC4 CC_DEPRECATED_ATTRIBUTE extern const Texture2D::PixelFormat kCCTexture2DPixelFormat_PVRTC2;
#define kCCTexture2DPixelFormat_PVRTC2 kTexture2DPixelFormat_PVRTC2 CC_DEPRECATED_ATTRIBUTE extern const Texture2D::PixelFormat kCCTexture2DPixelFormat_Default;
#define kCCTexture2DPixelFormat_Default kTexture2DPixelFormat_Default CC_DEPRECATED_ATTRIBUTE typedef Texture2D::PixelFormat CCTexture2DPixelFormat;
#define kCCLabelAutomaticWidth kLabelAutomaticWidth #define kCCLabelAutomaticWidth kLabelAutomaticWidth
#define kCCParticleDurationInfinity kParticleDurationInfinity CC_DEPRECATED_ATTRIBUTE extern const int kCCParticleDurationInfinity;
#define kCCParticleStartSizeEqualToEndSize kParticleStartSizeEqualToEndSize CC_DEPRECATED_ATTRIBUTE extern const int kCCParticleStartSizeEqualToEndSize;
#define kCCParticleStartRadiusEqualToEndRadius kParticleStartRadiusEqualToEndRadius CC_DEPRECATED_ATTRIBUTE extern const int kCCParticleStartRadiusEqualToEndRadius;
#define kCCParticleModeGravity kParticleModeGravity CC_DEPRECATED_ATTRIBUTE extern const ParticleSystem::Mode kCCParticleModeGravity;
#define kCCParticleModeRadius kParticleModeRadius CC_DEPRECATED_ATTRIBUTE extern const ParticleSystem::Mode kCCParticleModeRadius;
#define kCCPositionTypeFree kPositionTypeFree
#define kCCPositionTypeRelative kPositionTypeRelative
#define kCCPositionTypeGrouped kPositionTypeGrouped
#define kCCBlendFuncDisable kBlendFuncDisable CC_DEPRECATED_ATTRIBUTE extern const int kCCParticleDefaultCapacity;
#define kCCMenuHandlerPriority kMenuHandlerPriority CC_DEPRECATED_ATTRIBUTE extern const ParticleSystem::PositionType kCCPositionTypeFree;
#define kCCMenuStateWaiting kMenuStateWaiting CC_DEPRECATED_ATTRIBUTE extern const ParticleSystem::PositionType kCCPositionTypeRelative;
#define kCCMenuStateTrackingTouch kMenuStateTrackingTouch CC_DEPRECATED_ATTRIBUTE extern const ParticleSystem::PositionType kCCPositionTypeGrouped;
CC_DEPRECATED_ATTRIBUTE typedef ParticleSystem::PositionType tPositionType;
#define kCCTouchesOneByOne kTouchesOneByOne CC_DEPRECATED_ATTRIBUTE extern const int kCCMenuHandlerPriority;
#define kCCTouchesAllAtOnce kTouchesAllAtOnce CC_DEPRECATED_ATTRIBUTE extern const Menu::State kCCMenuStateWaiting;
CC_DEPRECATED_ATTRIBUTE extern const Menu::State kCCMenuStateTrackingTouch;
CC_DEPRECATED_ATTRIBUTE typedef Menu::State tMenuState;
#define kCCImageFormatPNG kImageFormatPNG CC_DEPRECATED_ATTRIBUTE extern const Touch::DispatchMode kCCTouchesOneByOne;
#define kCCImageFormatJPEG kImageFormatJPEG CC_DEPRECATED_ATTRIBUTE extern const Touch::DispatchMode kCCTouchesAllAtOnce;
CC_DEPRECATED_ATTRIBUTE typedef Touch::DispatchMode ccTouchesMode;
#define kCCTransitionOrientationLeftOver kTransitionOrientationLeftOver CC_DEPRECATED_ATTRIBUTE extern const Image::Format kCCImageFormatPNG;
#define kCCTransitionOrientationRightOver kTransitionOrientationRightOver CC_DEPRECATED_ATTRIBUTE extern const Image::Format kCCImageFormatJPEG;
#define kCCTransitionOrientationUpOver kTransitionOrientationUpOver CC_DEPRECATED_ATTRIBUTE typedef Image::Format tImageFormat;
#define kCCTransitionOrientationDownOver kTransitionOrientationDownOver
#define kCCPrioritySystem kPrioritySystem CC_DEPRECATED_ATTRIBUTE extern const TransitionScene::Orientation kCCTransitionOrientationLeftOver;
#define kCCPriorityNonSystemMin kPriorityNonSystemMin CC_DEPRECATED_ATTRIBUTE extern const TransitionScene::Orientation kCCTransitionOrientationRightOver;
CC_DEPRECATED_ATTRIBUTE extern const TransitionScene::Orientation kCCTransitionOrientationUpOver;
CC_DEPRECATED_ATTRIBUTE extern const TransitionScene::Orientation kCCTransitionOrientationDownOver;
CC_DEPRECATED_ATTRIBUTE typedef TransitionScene::Orientation tOrientation;
CC_DEPRECATED_ATTRIBUTE extern const int kCCPrioritySystem;
CC_DEPRECATED_ATTRIBUTE extern const int kCCPriorityNonSystemMin;
CC_DEPRECATED_ATTRIBUTE extern const int kCCActionTagInvalid;
CC_DEPRECATED_ATTRIBUTE extern const int kCCNodeTagInvalid;
CC_DEPRECATED_ATTRIBUTE extern const int kCCNodeOnEnter;
CC_DEPRECATED_ATTRIBUTE extern const int kCCNodeOnExit;
CC_DEPRECATED_ATTRIBUTE extern const int kCCNodeOnEnterTransitionDidFinish;
CC_DEPRECATED_ATTRIBUTE extern const int kCCNodeOnExitTransitionDidStart;
CC_DEPRECATED_ATTRIBUTE extern const int kCCNodeOnCleanup;
CC_DEPRECATED_ATTRIBUTE extern const LanguageType kLanguageEnglish;
CC_DEPRECATED_ATTRIBUTE extern const LanguageType kLanguageChinese;
CC_DEPRECATED_ATTRIBUTE extern const LanguageType kLanguageFrench;
CC_DEPRECATED_ATTRIBUTE extern const LanguageType kLanguageItalian;
CC_DEPRECATED_ATTRIBUTE extern const LanguageType kLanguageGerman;
CC_DEPRECATED_ATTRIBUTE extern const LanguageType kLanguageSpanish;
CC_DEPRECATED_ATTRIBUTE extern const LanguageType kLanguageRussian;
CC_DEPRECATED_ATTRIBUTE extern const LanguageType kLanguageKorean;
CC_DEPRECATED_ATTRIBUTE extern const LanguageType kLanguageJapanese;
CC_DEPRECATED_ATTRIBUTE extern const LanguageType kLanguageHungarian;
CC_DEPRECATED_ATTRIBUTE extern const LanguageType kLanguagePortuguese;
CC_DEPRECATED_ATTRIBUTE extern const LanguageType kLanguageArabic;
CC_DEPRECATED_ATTRIBUTE extern const LanguageType kLanguageNorwegian;
CC_DEPRECATED_ATTRIBUTE extern const LanguageType kLanguagePolish;
CC_DEPRECATED_ATTRIBUTE typedef LanguageType ccLanguageType;
CC_DEPRECATED_ATTRIBUTE extern const Application::Platform kTargetWindows;
CC_DEPRECATED_ATTRIBUTE extern const Application::Platform kTargetLinux;
CC_DEPRECATED_ATTRIBUTE extern const Application::Platform kTargetMacOS;
CC_DEPRECATED_ATTRIBUTE extern const Application::Platform kTargetAndroid;
CC_DEPRECATED_ATTRIBUTE extern const Application::Platform kTargetIphone;
CC_DEPRECATED_ATTRIBUTE extern const Application::Platform kTargetIpad;
CC_DEPRECATED_ATTRIBUTE extern const Application::Platform kTargetBlackBerry;
CC_DEPRECATED_ATTRIBUTE extern const Application::Platform kTargetNaCl;
CC_DEPRECATED_ATTRIBUTE extern const Application::Platform kTargetEmscripten;
CC_DEPRECATED_ATTRIBUTE extern const Application::Platform kTargetTizen;
CC_DEPRECATED_ATTRIBUTE typedef Application::Platform TargetPlatform;
CC_DEPRECATED_ATTRIBUTE extern const ResolutionPolicy kResolutionExactFit;
CC_DEPRECATED_ATTRIBUTE extern const ResolutionPolicy kResolutionNoBorder;
CC_DEPRECATED_ATTRIBUTE extern const ResolutionPolicy kResolutionShowAll;
CC_DEPRECATED_ATTRIBUTE extern const ResolutionPolicy kResolutionFixedHeight;
CC_DEPRECATED_ATTRIBUTE extern const ResolutionPolicy kResolutionFixedWidth;
CC_DEPRECATED_ATTRIBUTE extern const ResolutionPolicy kResolutionUnKnown;
#define kCCTMXTileHorizontalFlag kTMXTileHorizontalFlag #define kCCTMXTileHorizontalFlag kTMXTileHorizontalFlag
#define kCCTMXTileVerticalFlag kTMXTileVerticalFlag #define kCCTMXTileVerticalFlag kTMXTileVerticalFlag
@ -911,8 +984,42 @@ CC_DEPRECATED_ATTRIBUTE typedef void* CCZone;
/** use log() instead */ /** use log() instead */
CC_DEPRECATED_ATTRIBUTE void CC_DLL CCLog(const char * pszFormat, ...) CC_FORMAT_PRINTF(1, 2); CC_DEPRECATED_ATTRIBUTE void CC_DLL CCLog(const char * pszFormat, ...) CC_FORMAT_PRINTF(1, 2);
// end of data_structures group CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawInit();
/// @} CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawFree();
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawPoint( const Point& point );
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawPoints( const Point *points, unsigned int numberOfPoints );
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawLine( const Point& origin, const Point& destination );
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawRect( Point origin, Point destination );
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawSolidRect( Point origin, Point destination, Color4F color );
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawPoly( const Point *vertices, unsigned int numOfVertices, bool closePolygon );
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawSolidPoly( const Point *poli, unsigned int numberOfPoints, Color4F color );
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawCircle( const Point& center, float radius, float angle, unsigned int segments, bool drawLineToCenter, float scaleX, float scaleY);
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawCircle( const Point& center, float radius, float angle, unsigned int segments, bool drawLineToCenter);
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawSolidCircle( const Point& center, float radius, float angle, unsigned int segments, float scaleX, float scaleY);
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawSolidCircle( const Point& center, float radius, float angle, unsigned int segments);
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawQuadBezier(const Point& origin, const Point& control, const Point& destination, unsigned int segments);
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawCubicBezier(const Point& origin, const Point& control1, const Point& control2, const Point& destination, unsigned int segments);
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawCatmullRom( PointArray *arrayOfControlPoints, unsigned int segments );
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawCardinalSpline( PointArray *config, float tension, unsigned int segments );
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawColor4B( GLubyte r, GLubyte g, GLubyte b, GLubyte a );
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccDrawColor4F( GLfloat r, GLfloat g, GLfloat b, GLfloat a );
CC_DEPRECATED_ATTRIBUTE void CC_DLL ccPointSize( GLfloat pointSize );
CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLInvalidateStateCache() { GL::invalidateStateCache(); }
CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLUseProgram(GLuint program) { GL::useProgram(program); }
CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLDeleteProgram(GLuint program){ GL::deleteProgram(program); }
CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLBlendFunc(GLenum sfactor, GLenum dfactor) { GL::blendFunc(sfactor, dfactor); }
CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLBlendResetToCache() { GL::blendResetToCache(); }
CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccSetProjectionMatrixDirty() { GL::setProjectionMatrixDirty(); }
CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLEnableVertexAttribs(unsigned int flags) { GL::enableVertexAttribs(flags); }
CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLBindTexture2D(GLuint textureId) { GL::bindTexture2D(textureId); }
CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLBindTexture2DN(GLuint textureUnit, GLuint textureId) { GL::bindTexture2DN(textureUnit, textureId); }
CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLDeleteTexture(GLuint textureId) { GL::deleteTexture(textureId); }
CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLDeleteTextureN(GLuint textureUnit, GLuint textureId) { GL::deleteTextureN(textureUnit, textureId); }
CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLBindVAO(GLuint vaoId) { GL::bindVAO(vaoId); }
CC_DEPRECATED_ATTRIBUTE inline void CC_DLL ccGLEnable( int flags ) { /* ignore */ };
CC_DEPRECATED_ATTRIBUTE typedef int ccGLServerState;
NS_CC_END NS_CC_END

View File

@ -51,10 +51,10 @@ THE SOFTWARE.
If enabled, cocos2d will maintain an OpenGL state cache internally to avoid unnecessary switches. If enabled, cocos2d will maintain an OpenGL state cache internally to avoid unnecessary switches.
In order to use them, you have to use the following functions, instead of the the GL ones: In order to use them, you have to use the following functions, instead of the the GL ones:
- ccGLUseProgram() instead of glUseProgram() - ccGLUseProgram() instead of glUseProgram()
- ccGLDeleteProgram() instead of glDeleteProgram() - GL::deleteProgram() instead of glDeleteProgram()
- ccGLBlendFunc() instead of glBlendFunc() - GL::blendFunc() instead of glBlendFunc()
If this functionality is disabled, then ccGLUseProgram(), ccGLDeleteProgram(), ccGLBlendFunc() will call the GL ones, without using the cache. If this functionality is disabled, then ccGLUseProgram(), GL::deleteProgram(), GL::blendFunc() will call the GL ones, without using the cache.
It is recommended to enable whenever possible to improve speed. It is recommended to enable whenever possible to improve speed.
If you are migrating your code from GL ES 1.1, then keep it disabled. Once all your code works as expected, turn it on. If you are migrating your code from GL ES 1.1, then keep it disabled. Once all your code works as expected, turn it on.

View File

@ -97,7 +97,6 @@ default gl blend src function. Compatible with premultiplied alpha images.
*/ */
#define CC_NODE_DRAW_SETUP() \ #define CC_NODE_DRAW_SETUP() \
do { \ do { \
ccGLEnable(_GLServerState); \
CCASSERT(getShaderProgram(), "No shader program set for this node"); \ CCASSERT(getShaderProgram(), "No shader program set for this node"); \
{ \ { \
getShaderProgram()->use(); \ getShaderProgram()->use(); \

View File

@ -42,9 +42,9 @@ struct Color3B
Color3B(): r(0), g(0), b(0) {} Color3B(): r(0), g(0), b(0) {}
Color3B(GLubyte _r, GLubyte _g, GLubyte _b) Color3B(GLubyte _r, GLubyte _g, GLubyte _b)
:r(_r), : r(_r)
g(_g), , g(_g)
b(_b) , b(_b)
{} {}
bool equals(const Color3B &other) bool equals(const Color3B &other)
@ -77,13 +77,13 @@ struct Color4F;
struct Color4B struct Color4B
{ {
Color4B(GLubyte _r, GLubyte _g, GLubyte _b, GLubyte _a) Color4B(GLubyte _r, GLubyte _g, GLubyte _b, GLubyte _a)
:r(_r), : r(_r)
g(_g), , g(_g)
b(_b), , b(_b)
a(_a) , a(_a)
{} {}
Color4B(): r(0.f), g(0.f), b(0.f), a(0.f) {} Color4B(): r(0), g(0), b(0), a(0) {}
// This function should use Color4F, so implement it in .cpp file. // This function should use Color4F, so implement it in .cpp file.
explicit Color4B(const Color4F &color4F); explicit Color4B(const Color4F &color4F);
@ -101,24 +101,24 @@ struct Color4B
struct Color4F struct Color4F
{ {
Color4F(float _r, float _g, float _b, float _a) Color4F(float _r, float _g, float _b, float _a)
:r(_r), : r(_r)
g(_g), , g(_g)
b(_b), , b(_b)
a(_a) , a(_a)
{} {}
explicit Color4F(const Color3B &color3B) explicit Color4F(const Color3B &color3B)
:r(color3B.r) : r(color3B.r)
,g(color3B.g) , g(color3B.g)
,b(color3B.b) , b(color3B.b)
,a(1.f) , a(1.f)
{} {}
explicit Color4F(const Color4B &color4B) explicit Color4F(const Color4B &color4B)
:r(color4B.r / 255.0f), : r(color4B.r / 255.0f)
g(color4B.g / 255.0f), , g(color4B.g / 255.0f)
b(color4B.b / 255.0f), , b(color4B.b / 255.0f)
a(color4B.a / 255.0f) , a(color4B.a / 255.0f)
{} {}
Color4F(): r(0.f), g(0.f), b(0.f), a(0.f) {} Color4F(): r(0.f), g(0.f), b(0.f), a(0.f) {}
@ -157,9 +157,9 @@ struct Vertex2F
struct Vertex3F struct Vertex3F
{ {
Vertex3F(float _x, float _y, float _z) Vertex3F(float _x, float _y, float _z)
:x(_x), : x(_x)
y(_y), , y(_y)
z(_z) , z(_z)
{} {}
Vertex3F(): x(0.f), y(0.f), z(0.f) {} Vertex3F(): x(0.f), y(0.f), z(0.f) {}
@ -300,27 +300,38 @@ struct BlendFunc
GLenum src; GLenum src;
//! destination blend function //! destination blend function
GLenum dst; GLenum dst;
const static BlendFunc BLEND_FUNC_DISABLE; //! Blending disabled. Uses {GL_ONE, GL_ZERO}
const static BlendFunc DISABLE;
//! Blending enabled for textures with Alpha premultiplied. Uses {GL_ONE, GL_ONE_MINUS_SRC_ALPHA}
const static BlendFunc ALPHA_PREMULTIPLIED;
//! Blending enabled for textures with Alpha NON premultiplied. Uses {GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA}
const static BlendFunc ALPHA_NON_PREMULTIPLIED;
//! Enables Additive blending. Uses {GL_SRC_ALPHA, GL_ONE}
const static BlendFunc ADDITIVE;
}; };
// XXX: If any of these enums are edited and/or reordered, update Texture2D.m class Label : public Object
//! Vertical text alignment type
typedef enum
{ {
kVerticalTextAlignmentTop, public:
kVerticalTextAlignmentCenter, // XXX: If any of these enums are edited and/or reordered, update Texture2D.m
kVerticalTextAlignmentBottom, //! Vertical text alignment type
} VerticalTextAlignment; enum class VAlignment
{
// XXX: If any of these enums are edited and/or reordered, update Texture2D.m TOP,
//! Horizontal text alignment type CENTER,
typedef enum BOTTOM,
{ };
kTextAlignmentLeft,
kTextAlignmentCenter, // XXX: If any of these enums are edited and/or reordered, update Texture2D.m
kTextAlignmentRight, //! Horizontal text alignment type
} TextAlignment; enum class HAlignment
{
LEFT,
CENTER,
RIGHT,
};
};
// types for animation in particle systems // types for animation in particle systems
@ -345,8 +356,6 @@ struct AnimationFrameData
Size size; Size size;
}; };
/** /**
types used for defining fonts properties (i.e. font name, size, stroke or shadow) types used for defining fonts properties (i.e. font name, size, stroke or shadow)
*/ */
@ -357,10 +366,12 @@ struct FontShadow
public: public:
// shadow is not enabled by default // shadow is not enabled by default
FontShadow(): _shadowEnabled(false), FontShadow()
_shadowBlur(0), : _shadowEnabled(false)
_shadowOpacity(0){} , _shadowBlur(0)
, _shadowOpacity(0)
{}
// true if shadow enabled // true if shadow enabled
bool _shadowEnabled; bool _shadowEnabled;
// shadow x and y offset // shadow x and y offset
@ -381,7 +392,7 @@ public:
: _strokeEnabled(false) : _strokeEnabled(false)
, _strokeColor(Color3B::BLACK) , _strokeColor(Color3B::BLACK)
, _strokeSize(0) , _strokeSize(0)
{} {}
// true if stroke enabled // true if stroke enabled
bool _strokeEnabled; bool _strokeEnabled;
@ -397,20 +408,22 @@ struct FontDefinition
{ {
public: public:
FontDefinition():_fontSize(0), FontDefinition()
_alignment(kTextAlignmentCenter), : _fontSize(0)
_vertAlignment(kVerticalTextAlignmentTop), , _alignment(Label::HAlignment::CENTER)
_fontFillColor(Color3B::WHITE) , _vertAlignment(Label::VAlignment::TOP)
{ _dimensions = Size(0,0); } , _fontFillColor(Color3B::WHITE)
, _dimensions(Size::ZERO)
{}
// font name // font name
std::string _fontName; std::string _fontName;
// font size // font size
int _fontSize; int _fontSize;
// horizontal alignment // horizontal alignment
TextAlignment _alignment; Label::HAlignment _alignment;
// vertical alignment // vertical alignment
VerticalTextAlignment _vertAlignment; Label::VAlignment _vertAlignment;
// renering box // renering box
Size _dimensions; Size _dimensions;
// font color // font color

View File

@ -430,23 +430,23 @@ LabelBMFont * LabelBMFont::create()
return NULL; return NULL;
} }
LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile, float width, TextAlignment alignment) LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile, float width, Label::HAlignment alignment)
{ {
return LabelBMFont::create(str, fntFile, width, alignment, Point::ZERO); return LabelBMFont::create(str, fntFile, width, alignment, Point::ZERO);
} }
LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile, float width) LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile, float width)
{ {
return LabelBMFont::create(str, fntFile, width, kTextAlignmentLeft, Point::ZERO); return LabelBMFont::create(str, fntFile, width, Label::HAlignment::LEFT, Point::ZERO);
} }
LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile) LabelBMFont * LabelBMFont::create(const char *str, const char *fntFile)
{ {
return LabelBMFont::create(str, fntFile, kLabelAutomaticWidth, kTextAlignmentLeft, Point::ZERO); return LabelBMFont::create(str, fntFile, kLabelAutomaticWidth, Label::HAlignment::LEFT, Point::ZERO);
} }
//LabelBMFont - Creation & Init //LabelBMFont - Creation & Init
LabelBMFont *LabelBMFont::create(const char *str, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextAlignment alignment/* = kTextAlignmentLeft*/, Point imageOffset/* = Point::ZERO*/) LabelBMFont *LabelBMFont::create(const char *str, const char *fntFile, float width/* = kLabelAutomaticWidth*/, Label::HAlignment alignment/* = Label::HAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/)
{ {
LabelBMFont *pRet = new LabelBMFont(); LabelBMFont *pRet = new LabelBMFont();
if(pRet && pRet->initWithString(str, fntFile, width, alignment, imageOffset)) if(pRet && pRet->initWithString(str, fntFile, width, alignment, imageOffset))
@ -460,10 +460,10 @@ LabelBMFont *LabelBMFont::create(const char *str, const char *fntFile, float wid
bool LabelBMFont::init() bool LabelBMFont::init()
{ {
return initWithString(NULL, NULL, kLabelAutomaticWidth, kTextAlignmentLeft, Point::ZERO); return initWithString(NULL, NULL, kLabelAutomaticWidth, Label::HAlignment::LEFT, Point::ZERO);
} }
bool LabelBMFont::initWithString(const char *theString, const char *fntFile, float width/* = kLabelAutomaticWidth*/, TextAlignment alignment/* = kTextAlignmentLeft*/, Point imageOffset/* = Point::ZERO*/) bool LabelBMFont::initWithString(const char *theString, const char *fntFile, float width/* = kLabelAutomaticWidth*/, Label::HAlignment alignment/* = Label::HAlignment::LEFT*/, Point imageOffset/* = Point::ZERO*/)
{ {
CCASSERT(!_configuration, "re-init is no longer supported"); CCASSERT(!_configuration, "re-init is no longer supported");
CCASSERT( (theString && fntFile) || (theString==NULL && fntFile==NULL), "Invalid params for LabelBMFont"); CCASSERT( (theString && fntFile) || (theString==NULL && fntFile==NULL), "Invalid params for LabelBMFont");
@ -530,7 +530,7 @@ bool LabelBMFont::initWithString(const char *theString, const char *fntFile, flo
LabelBMFont::LabelBMFont() LabelBMFont::LabelBMFont()
: _string(NULL) : _string(NULL)
, _initialString(NULL) , _initialString(NULL)
, _alignment(kTextAlignmentCenter) , _alignment(Label::HAlignment::CENTER)
, _width(-1.0f) , _width(-1.0f)
, _configuration(NULL) , _configuration(NULL)
, _lineBreakWithoutSpaces(false) , _lineBreakWithoutSpaces(false)
@ -1094,7 +1094,7 @@ void LabelBMFont::updateLabel()
} }
// Step 2: Make alignment // Step 2: Make alignment
if (_alignment != kTextAlignmentLeft) if (_alignment != Label::HAlignment::LEFT)
{ {
int i = 0; int i = 0;
@ -1125,10 +1125,10 @@ void LabelBMFont::updateLabel()
float shift = 0; float shift = 0;
switch (_alignment) switch (_alignment)
{ {
case kTextAlignmentCenter: case Label::HAlignment::CENTER:
shift = getContentSize().width/2.0f - lineWidth/2.0f; shift = getContentSize().width/2.0f - lineWidth/2.0f;
break; break;
case kTextAlignmentRight: case Label::HAlignment::RIGHT:
shift = getContentSize().width - lineWidth; shift = getContentSize().width - lineWidth;
break; break;
default: default:
@ -1160,7 +1160,7 @@ void LabelBMFont::updateLabel()
} }
// LabelBMFont - Alignment // LabelBMFont - Alignment
void LabelBMFont::setAlignment(TextAlignment alignment) void LabelBMFont::setAlignment(Label::HAlignment alignment)
{ {
this->_alignment = alignment; this->_alignment = alignment;
updateLabel(); updateLabel();

View File

@ -192,9 +192,9 @@ public:
static void purgeCachedData(); static void purgeCachedData();
/** creates a bitmap font atlas with an initial string and the FNT file */ /** creates a bitmap font atlas with an initial string and the FNT file */
static LabelBMFont * create(const char *str, const char *fntFile, float width, TextAlignment alignment, Point imageOffset); static LabelBMFont * create(const char *str, const char *fntFile, float width, Label::HAlignment alignment, Point imageOffset);
static LabelBMFont * create(const char *str, const char *fntFile, float width, TextAlignment alignment); static LabelBMFont * create(const char *str, const char *fntFile, float width, Label::HAlignment alignment);
static LabelBMFont * create(const char *str, const char *fntFile, float width); static LabelBMFont * create(const char *str, const char *fntFile, float width);
@ -206,7 +206,7 @@ public:
bool init(); bool init();
/** init a bitmap font atlas with an initial string and the FNT file */ /** init a bitmap font atlas with an initial string and the FNT file */
bool initWithString(const char *str, const char *fntFile, float width = kLabelAutomaticWidth, TextAlignment alignment = kTextAlignmentLeft, Point imageOffset = Point::ZERO); bool initWithString(const char *str, const char *fntFile, float width = kLabelAutomaticWidth, Label::HAlignment alignment = Label::HAlignment::LEFT, Point imageOffset = Point::ZERO);
/** updates the font chars based on the string to render */ /** updates the font chars based on the string to render */
void createFontChars(); void createFontChars();
@ -218,7 +218,7 @@ public:
virtual void setCString(const char *label); virtual void setCString(const char *label);
virtual void setAnchorPoint(const Point& var); virtual void setAnchorPoint(const Point& var);
virtual void updateLabel(); virtual void updateLabel();
virtual void setAlignment(TextAlignment alignment); virtual void setAlignment(Label::HAlignment 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); virtual void setScale(float scale);
@ -265,7 +265,7 @@ protected:
std::string _initialStringUTF8; std::string _initialStringUTF8;
// alignment of all lines // alignment of all lines
TextAlignment _alignment; Label::HAlignment _alignment;
// max width until a line break is added // max width until a line break is added
float _width; float _width;

View File

@ -31,17 +31,17 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
#if CC_USE_LA88_LABELS #if CC_USE_LA88_LABELS
#define SHADER_PROGRAM kShader_PositionTextureColor #define SHADER_PROGRAM GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR
#else #else
#define SHADER_PROGRAM kShader_PositionTextureA8Color #define SHADER_PROGRAM GLProgram::SHADER_NAME_POSITION_TEXTUREA8Color
#endif #endif
// //
//CCLabelTTF //CCLabelTTF
// //
LabelTTF::LabelTTF() LabelTTF::LabelTTF()
: _alignment(kTextAlignmentCenter) : _alignment(Label::HAlignment::CENTER)
, _vAlignment(kVerticalTextAlignmentTop) , _vAlignment(Label::VAlignment::TOP)
, _fontName(NULL) , _fontName(NULL)
, _fontSize(0.0) , _fontSize(0.0)
, _string("") , _string("")
@ -73,18 +73,18 @@ LabelTTF * LabelTTF::create()
LabelTTF * LabelTTF::create(const char *string, const char *fontName, float fontSize) LabelTTF * LabelTTF::create(const char *string, const char *fontName, float fontSize)
{ {
return LabelTTF::create(string, fontName, fontSize, return LabelTTF::create(string, fontName, fontSize,
Size::ZERO, kTextAlignmentCenter, kVerticalTextAlignmentTop); Size::ZERO, Label::HAlignment::CENTER, Label::VAlignment::TOP);
} }
LabelTTF * LabelTTF::create(const char *string, const char *fontName, float fontSize, LabelTTF * LabelTTF::create(const char *string, const char *fontName, float fontSize,
const Size& dimensions, TextAlignment hAlignment) const Size& dimensions, Label::HAlignment hAlignment)
{ {
return LabelTTF::create(string, fontName, fontSize, dimensions, hAlignment, kVerticalTextAlignmentTop); return LabelTTF::create(string, fontName, fontSize, dimensions, hAlignment, Label::VAlignment::TOP);
} }
LabelTTF* LabelTTF::create(const char *string, const char *fontName, float fontSize, LabelTTF* LabelTTF::create(const char *string, const char *fontName, float fontSize,
const Size &dimensions, TextAlignment hAlignment, const Size &dimensions, Label::HAlignment hAlignment,
VerticalTextAlignment vAlignment) Label::VAlignment vAlignment)
{ {
LabelTTF *pRet = new LabelTTF(); LabelTTF *pRet = new LabelTTF();
if(pRet && pRet->initWithString(string, fontName, fontSize, dimensions, hAlignment, vAlignment)) if(pRet && pRet->initWithString(string, fontName, fontSize, dimensions, hAlignment, vAlignment))
@ -114,20 +114,20 @@ bool LabelTTF::init()
} }
bool LabelTTF::initWithString(const char *label, const char *fontName, float fontSize, bool LabelTTF::initWithString(const char *label, const char *fontName, float fontSize,
const Size& dimensions, TextAlignment alignment) const Size& dimensions, Label::HAlignment alignment)
{ {
return this->initWithString(label, fontName, fontSize, dimensions, alignment, kVerticalTextAlignmentTop); return this->initWithString(label, fontName, fontSize, dimensions, alignment, Label::VAlignment::TOP);
} }
bool LabelTTF::initWithString(const char *label, const char *fontName, float fontSize) bool LabelTTF::initWithString(const char *label, const char *fontName, float fontSize)
{ {
return this->initWithString(label, fontName, fontSize, return this->initWithString(label, fontName, fontSize,
Size::ZERO, kTextAlignmentLeft, kVerticalTextAlignmentTop); Size::ZERO, Label::HAlignment::LEFT, Label::VAlignment::TOP);
} }
bool LabelTTF::initWithString(const char *string, const char *fontName, float fontSize, bool LabelTTF::initWithString(const char *string, const char *fontName, float fontSize,
const cocos2d::Size &dimensions, TextAlignment hAlignment, const cocos2d::Size &dimensions, Label::HAlignment hAlignment,
VerticalTextAlignment vAlignment) Label::VAlignment vAlignment)
{ {
if (Sprite::init()) if (Sprite::init())
{ {
@ -193,12 +193,12 @@ const char* LabelTTF::description() const
return String::createWithFormat("<LabelTTF | FontName = %s, FontSize = %.1f>", _fontName->c_str(), _fontSize)->getCString(); return String::createWithFormat("<LabelTTF | FontName = %s, FontSize = %.1f>", _fontName->c_str(), _fontSize)->getCString();
} }
TextAlignment LabelTTF::getHorizontalAlignment() const Label::HAlignment LabelTTF::getHorizontalAlignment() const
{ {
return _alignment; return _alignment;
} }
void LabelTTF::setHorizontalAlignment(TextAlignment alignment) void LabelTTF::setHorizontalAlignment(Label::HAlignment alignment)
{ {
if (alignment != _alignment) if (alignment != _alignment)
{ {
@ -212,12 +212,12 @@ void LabelTTF::setHorizontalAlignment(TextAlignment alignment)
} }
} }
VerticalTextAlignment LabelTTF::getVerticalAlignment() const Label::VAlignment LabelTTF::getVerticalAlignment() const
{ {
return _vAlignment; return _vAlignment;
} }
void LabelTTF::setVerticalAlignment(VerticalTextAlignment verticalAlignment) void LabelTTF::setVerticalAlignment(Label::VAlignment verticalAlignment)
{ {
if (verticalAlignment != _vAlignment) if (verticalAlignment != _vAlignment)
{ {

View File

@ -48,9 +48,9 @@ NS_CC_BEGIN
* Custom ttf file can be put in assets/ or external storage that the Application can access. * Custom ttf file can be put in assets/ or external storage that the Application can access.
* @code * @code
* LabelTTF *label1 = LabelTTF::create("alignment left", "A Damn Mess", fontSize, blockSize, * LabelTTF *label1 = LabelTTF::create("alignment left", "A Damn Mess", fontSize, blockSize,
* kTextAlignmentLeft, kVerticalTextAlignmentCenter); * Label::HAlignment::LEFT, Label::VAlignment::CENTER);
* LabelTTF *label2 = LabelTTF::create("alignment right", "/mnt/sdcard/Scissor Cuts.ttf", fontSize, blockSize, * LabelTTF *label2 = LabelTTF::create("alignment right", "/mnt/sdcard/Scissor Cuts.ttf", fontSize, blockSize,
* kTextAlignmentLeft, kVerticalTextAlignmentCenter); * Label::HAlignment::LEFT, Label::VAlignment::CENTER);
* @endcode * @endcode
* *
*/ */
@ -70,14 +70,14 @@ public:
@since v2.0.1 @since v2.0.1
*/ */
static LabelTTF * create(const char *string, const char *fontName, float fontSize, static LabelTTF * create(const char *string, const char *fontName, float fontSize,
const Size& dimensions, TextAlignment hAlignment); const Size& dimensions, Label::HAlignment hAlignment);
/** creates a Label from a fontname, alignment, dimension in points and font size in points /** creates a Label from a fontname, alignment, dimension in points and font size in points
@since v2.0.1 @since v2.0.1
*/ */
static LabelTTF * create(const char *string, const char *fontName, float fontSize, static LabelTTF * create(const char *string, const char *fontName, float fontSize,
const Size& dimensions, TextAlignment hAlignment, const Size& dimensions, Label::HAlignment hAlignment,
VerticalTextAlignment vAlignment); Label::VAlignment vAlignment);
/** Create a lable with string and a font definition*/ /** Create a lable with string and a font definition*/
@ -88,12 +88,12 @@ public:
/** initializes the LabelTTF with a font name, alignment, dimension and font size */ /** initializes the LabelTTF with a font name, alignment, dimension and font size */
bool initWithString(const char *string, const char *fontName, float fontSize, bool initWithString(const char *string, const char *fontName, float fontSize,
const Size& dimensions, TextAlignment hAlignment); const Size& dimensions, Label::HAlignment hAlignment);
/** initializes the LabelTTF with a font name, alignment, dimension and font size */ /** initializes the LabelTTF with a font name, alignment, dimension and font size */
bool initWithString(const char *string, const char *fontName, float fontSize, bool initWithString(const char *string, const char *fontName, float fontSize,
const Size& dimensions, TextAlignment hAlignment, const Size& dimensions, Label::HAlignment hAlignment,
VerticalTextAlignment vAlignment); Label::VAlignment vAlignment);
/** initializes the LabelTTF with a font name, alignment, dimension and font size */ /** initializes the LabelTTF with a font name, alignment, dimension and font size */
bool initWithStringAndTextDefinition(const char *string, FontDefinition &textDefinition); bool initWithStringAndTextDefinition(const char *string, FontDefinition &textDefinition);
@ -136,11 +136,11 @@ public:
virtual void setString(const char *label); virtual void setString(const char *label);
virtual const char* getString(void) const; virtual const char* getString(void) const;
TextAlignment getHorizontalAlignment() const; Label::HAlignment getHorizontalAlignment() const;
void setHorizontalAlignment(TextAlignment alignment); void setHorizontalAlignment(Label::HAlignment alignment);
VerticalTextAlignment getVerticalAlignment() const; Label::VAlignment getVerticalAlignment() const;
void setVerticalAlignment(VerticalTextAlignment verticalAlignment); void setVerticalAlignment(Label::VAlignment verticalAlignment);
const Size& getDimensions() const; const Size& getDimensions() const;
void setDimensions(const Size &dim); void setDimensions(const Size &dim);
@ -162,9 +162,9 @@ protected:
/** Dimensions of the label in Points */ /** Dimensions of the label in Points */
Size _dimensions; Size _dimensions;
/** The alignment of the label */ /** The alignment of the label */
TextAlignment _alignment; Label::HAlignment _alignment;
/** The vertical alignment of the label */ /** The vertical alignment of the label */
VerticalTextAlignment _vAlignment; Label::VAlignment _vAlignment;
/** Font name used in the label */ /** Font name used in the label */
std::string * _fontName; std::string * _fontName;
/** Font size of the label */ /** Font size of the label */

View File

@ -48,7 +48,8 @@ Layer::Layer()
, _keyboardEnabled(false) , _keyboardEnabled(false)
, _keypadEnabled(false) , _keypadEnabled(false)
, _touchPriority(0) , _touchPriority(0)
, _touchMode(kTouchesAllAtOnce) , _touchMode(Touch::DispatchMode::ALL_AT_ONCE)
, _swallowsTouches(true)
{ {
_ignoreAnchorPointForPosition = true; _ignoreAnchorPointForPosition = true;
setAnchorPoint(Point(0.5f, 0.5f)); setAnchorPoint(Point(0.5f, 0.5f));
@ -96,10 +97,10 @@ void Layer::registerWithTouchDispatcher()
{ {
TouchDispatcher* pDispatcher = Director::getInstance()->getTouchDispatcher(); TouchDispatcher* pDispatcher = Director::getInstance()->getTouchDispatcher();
if( _touchMode == kTouchesAllAtOnce ) { if( _touchMode == Touch::DispatchMode::ALL_AT_ONCE ) {
pDispatcher->addStandardDelegate(this, 0); pDispatcher->addStandardDelegate(this, 0);
} else { } else {
pDispatcher->addTargetedDelegate(this, _touchPriority, true); pDispatcher->addTargetedDelegate(this, _touchPriority, _swallowsTouches);
} }
} }
@ -155,7 +156,7 @@ void Layer::setTouchEnabled(bool enabled)
} }
} }
void Layer::setTouchMode(ccTouchesMode mode) void Layer::setTouchMode(Touch::DispatchMode mode)
{ {
if(_touchMode != mode) if(_touchMode != mode)
{ {
@ -183,16 +184,38 @@ void Layer::setTouchPriority(int priority)
} }
} }
void Layer::setSwallowsTouches(bool swallowsTouches)
{
if (_swallowsTouches != swallowsTouches)
{
_swallowsTouches = swallowsTouches;
if( _touchEnabled)
{
setTouchEnabled(false);
setTouchEnabled(true);
}
}
}
int Layer::getTouchPriority() const int Layer::getTouchPriority() const
{ {
return _touchPriority; return _touchPriority;
} }
int Layer::getTouchMode() const Touch::DispatchMode Layer::getTouchMode() const
{ {
return _touchMode; return _touchMode;
} }
bool Layer::isSwallowsTouches() const
{
return _swallowsTouches;
}
/// isAccelerometerEnabled getter /// isAccelerometerEnabled getter
bool Layer::isAccelerometerEnabled() const bool Layer::isAccelerometerEnabled() const
{ {
@ -237,7 +260,7 @@ void Layer::didAccelerate(Acceleration* pAccelerationValue)
{ {
CC_UNUSED_PARAM(pAccelerationValue); CC_UNUSED_PARAM(pAccelerationValue);
if(kScriptTypeNone == _scriptType) if(kScriptTypeNone != _scriptType)
{ {
BasicScriptData data(this,(void*)pAccelerationValue); BasicScriptData data(this,(void*)pAccelerationValue);
ScriptEvent event(kAccelerometerEvent,&data); ScriptEvent event(kAccelerometerEvent,&data);
@ -622,8 +645,7 @@ void LayerRGBA::setCascadeColorEnabled(bool cascadeColorEnabled)
LayerColor::LayerColor() LayerColor::LayerColor()
{ {
// default blend function // default blend function
_blendFunc.src = CC_BLEND_SRC; _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
_blendFunc.dst = CC_BLEND_DST;
} }
LayerColor::~LayerColor() LayerColor::~LayerColor()
@ -691,8 +713,7 @@ bool LayerColor::initWithColor(const Color4B& color, GLfloat w, GLfloat h)
{ {
// default blend function // default blend function
_blendFunc.src = GL_SRC_ALPHA; _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED;
_blendFunc.dst = GL_ONE_MINUS_SRC_ALPHA;
_displayedColor.r = _realColor.r = color.r; _displayedColor.r = _realColor.r = color.r;
_displayedColor.g = _realColor.g = color.g; _displayedColor.g = _realColor.g = color.g;
@ -708,7 +729,7 @@ bool LayerColor::initWithColor(const Color4B& color, GLfloat w, GLfloat h)
updateColor(); updateColor();
setContentSize(Size(w, h)); setContentSize(Size(w, h));
setShaderProgram(ShaderCache::getInstance()->programForKey(kShader_PositionColor)); setShaderProgram(ShaderCache::getInstance()->programForKey(GLProgram::SHADER_NAME_POSITION_COLOR));
return true; return true;
} }
return false; return false;
@ -762,23 +783,23 @@ void LayerColor::draw()
{ {
CC_NODE_DRAW_SETUP(); CC_NODE_DRAW_SETUP();
ccGLEnableVertexAttribs( kVertexAttribFlag_Position | kVertexAttribFlag_Color ); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POSITION | GL::VERTEX_ATTRIB_FLAG_COLOR );
// //
// Attributes // Attributes
// //
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
setGLBufferData(_squareVertices, 4 * sizeof(Vertex2F), 0); setGLBufferData(_squareVertices, 4 * sizeof(Vertex2F), 0);
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
setGLBufferData(_squareColors, 4 * sizeof(Color4F), 1); setGLBufferData(_squareColors, 4 * sizeof(Color4F), 1);
glVertexAttribPointer(kVertexAttrib_Color, 4, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_FLOAT, GL_FALSE, 0, 0);
#else #else
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, _squareVertices); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, _squareVertices);
glVertexAttribPointer(kVertexAttrib_Color, 4, GL_FLOAT, GL_FALSE, 0, _squareColors); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_FLOAT, GL_FALSE, 0, _squareColors);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
ccGLBlendFunc( _blendFunc.src, _blendFunc.dst ); GL::blendFunc( _blendFunc.src, _blendFunc.dst );
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

View File

@ -39,11 +39,6 @@ THE SOFTWARE.
NS_CC_BEGIN NS_CC_BEGIN
typedef enum {
kTouchesAllAtOnce,
kTouchesOneByOne,
} ccTouchesMode;
/** /**
* @addtogroup layer * @addtogroup layer
* @{ * @{
@ -62,7 +57,7 @@ All features from Node are valid, plus the following new features:
*/ */
class CC_DLL Layer : public Node, public TouchDelegate, public KeypadDelegate class CC_DLL Layer : public Node, public TouchDelegate, public KeypadDelegate
{ {
public: public:
/** creates a fullscreen black layer */ /** creates a fullscreen black layer */
static Layer *create(void); static Layer *create(void);
Layer(); Layer();
@ -70,18 +65,18 @@ public:
virtual bool init(); virtual bool init();
// default implements are used to call script callback if exist // default implements are used to call script callback if exist
virtual bool ccTouchBegan(Touch *pTouch, Event *pEvent); virtual bool ccTouchBegan(Touch *touch, Event *event);
virtual void ccTouchMoved(Touch *pTouch, Event *pEvent); virtual void ccTouchMoved(Touch *touch, Event *event);
virtual void ccTouchEnded(Touch *pTouch, Event *pEvent); virtual void ccTouchEnded(Touch *touch, Event *event);
virtual void ccTouchCancelled(Touch *pTouch, Event *pEvent); virtual void ccTouchCancelled(Touch *touch, Event *event);
// default implements are used to call script callback if exist // default implements are used to call script callback if exist
virtual void ccTouchesBegan(Set *pTouches, Event *pEvent); virtual void ccTouchesBegan(Set *touches, Event *event);
virtual void ccTouchesMoved(Set *pTouches, Event *pEvent); virtual void ccTouchesMoved(Set *touches, Event *event);
virtual void ccTouchesEnded(Set *pTouches, Event *pEvent); virtual void ccTouchesEnded(Set *touches, Event *event);
virtual void ccTouchesCancelled(Set *pTouches, Event *pEvent); virtual void ccTouchesCancelled(Set *touches, Event *event);
virtual void didAccelerate(Acceleration* pAccelerationValue); virtual void didAccelerate(Acceleration* accelerationValue);
/** If isTouchEnabled, this method is called onEnter. Override it to change the /** If isTouchEnabled, this method is called onEnter. Override it to change the
way Layer receives touch events. way Layer receives touch events.
@ -103,13 +98,17 @@ public:
virtual bool isTouchEnabled() const; virtual bool isTouchEnabled() const;
virtual void setTouchEnabled(bool value); virtual void setTouchEnabled(bool value);
virtual void setTouchMode(ccTouchesMode mode); virtual void setTouchMode(Touch::DispatchMode mode);
virtual int getTouchMode() const; virtual Touch::DispatchMode getTouchMode() const;
/** priority of the touch events. Default is 0 */ /** priority of the touch events. Default is 0 */
virtual void setTouchPriority(int priority); virtual void setTouchPriority(int priority);
virtual int getTouchPriority() const; virtual int getTouchPriority() const;
/** swallowsTouches of the touch events. Default is true */
virtual void setSwallowsTouches(bool swallowsTouches);
virtual bool isSwallowsTouches() const;
/** whether or not it will receive Accelerometer events /** whether or not it will receive Accelerometer events
You can enable / disable accelerometer events with this property. You can enable / disable accelerometer events with this property.
@since v0.8.1 @since v0.8.1
@ -148,7 +147,8 @@ protected:
private: private:
int _touchPriority; int _touchPriority;
ccTouchesMode _touchMode; Touch::DispatchMode _touchMode;
bool _swallowsTouches;
int executeScriptTouchHandler(int eventType, Touch* touch); int executeScriptTouchHandler(int eventType, Touch* touch);
int executeScriptTouchesHandler(int eventType, Set* touches); int executeScriptTouchesHandler(int eventType, Set* touches);

View File

@ -206,7 +206,7 @@ TransitionSceneOriented::~TransitionSceneOriented()
{ {
} }
TransitionSceneOriented * TransitionSceneOriented::create(float t, Scene *scene, tOrientation orientation) TransitionSceneOriented * TransitionSceneOriented::create(float t, Scene *scene, Orientation orientation)
{ {
TransitionSceneOriented * pScene = new TransitionSceneOriented(); TransitionSceneOriented * pScene = new TransitionSceneOriented();
pScene->initWithDuration(t,scene,orientation); pScene->initWithDuration(t,scene,orientation);
@ -214,7 +214,7 @@ TransitionSceneOriented * TransitionSceneOriented::create(float t, Scene *scene,
return pScene; return pScene;
} }
bool TransitionSceneOriented::initWithDuration(float t, Scene *scene, tOrientation orientation) bool TransitionSceneOriented::initWithDuration(float t, Scene *scene, Orientation orientation)
{ {
if ( TransitionScene::initWithDuration(t, scene) ) if ( TransitionScene::initWithDuration(t, scene) )
{ {
@ -740,7 +740,7 @@ void TransitionFlipX::onEnter()
float inDeltaZ, inAngleZ; float inDeltaZ, inAngleZ;
float outDeltaZ, outAngleZ; float outDeltaZ, outAngleZ;
if( _orientation == kTransitionOrientationRightOver ) if( _orientation == TransitionScene::Orientation::RIGHT_OVER )
{ {
inDeltaZ = 90; inDeltaZ = 90;
inAngleZ = 270; inAngleZ = 270;
@ -776,7 +776,7 @@ void TransitionFlipX::onEnter()
_outScene->runAction(outA); _outScene->runAction(outA);
} }
TransitionFlipX* TransitionFlipX::create(float t, Scene* s, tOrientation o) TransitionFlipX* TransitionFlipX::create(float t, Scene* s, Orientation o)
{ {
TransitionFlipX* pScene = new TransitionFlipX(); TransitionFlipX* pScene = new TransitionFlipX();
pScene->initWithDuration(t, s, o); pScene->initWithDuration(t, s, o);
@ -787,7 +787,7 @@ TransitionFlipX* TransitionFlipX::create(float t, Scene* s, tOrientation o)
TransitionFlipX* TransitionFlipX::create(float t, Scene* s) TransitionFlipX* TransitionFlipX::create(float t, Scene* s)
{ {
return TransitionFlipX::create(t, s, kTransitionOrientationRightOver); return TransitionFlipX::create(t, s, TransitionScene::Orientation::RIGHT_OVER);
} }
// //
@ -810,7 +810,7 @@ void TransitionFlipY::onEnter()
float inDeltaZ, inAngleZ; float inDeltaZ, inAngleZ;
float outDeltaZ, outAngleZ; float outDeltaZ, outAngleZ;
if( _orientation == kTransitionOrientationUpOver ) if( _orientation == TransitionScene::Orientation::UP_OVER )
{ {
inDeltaZ = 90; inDeltaZ = 90;
inAngleZ = 270; inAngleZ = 270;
@ -846,7 +846,7 @@ void TransitionFlipY::onEnter()
} }
TransitionFlipY* TransitionFlipY::create(float t, Scene* s, tOrientation o) TransitionFlipY* TransitionFlipY::create(float t, Scene* s, Orientation o)
{ {
TransitionFlipY* pScene = new TransitionFlipY(); TransitionFlipY* pScene = new TransitionFlipY();
pScene->initWithDuration(t, s, o); pScene->initWithDuration(t, s, o);
@ -857,7 +857,7 @@ TransitionFlipY* TransitionFlipY::create(float t, Scene* s, tOrientation o)
TransitionFlipY* TransitionFlipY::create(float t, Scene* s) TransitionFlipY* TransitionFlipY::create(float t, Scene* s)
{ {
return TransitionFlipY::create(t, s, kTransitionOrientationUpOver); return TransitionFlipY::create(t, s, TransitionScene::Orientation::UP_OVER);
} }
// //
@ -881,7 +881,7 @@ void TransitionFlipAngular::onEnter()
float inDeltaZ, inAngleZ; float inDeltaZ, inAngleZ;
float outDeltaZ, outAngleZ; float outDeltaZ, outAngleZ;
if( _orientation == kTransitionOrientationRightOver ) if( _orientation == TransitionScene::Orientation::RIGHT_OVER )
{ {
inDeltaZ = 90; inDeltaZ = 90;
inAngleZ = 270; inAngleZ = 270;
@ -916,7 +916,7 @@ void TransitionFlipAngular::onEnter()
_outScene->runAction(outA); _outScene->runAction(outA);
} }
TransitionFlipAngular* TransitionFlipAngular::create(float t, Scene* s, tOrientation o) TransitionFlipAngular* TransitionFlipAngular::create(float t, Scene* s, Orientation o)
{ {
TransitionFlipAngular* pScene = new TransitionFlipAngular(); TransitionFlipAngular* pScene = new TransitionFlipAngular();
pScene->initWithDuration(t, s, o); pScene->initWithDuration(t, s, o);
@ -927,7 +927,7 @@ TransitionFlipAngular* TransitionFlipAngular::create(float t, Scene* s, tOrienta
TransitionFlipAngular* TransitionFlipAngular::create(float t, Scene* s) TransitionFlipAngular* TransitionFlipAngular::create(float t, Scene* s)
{ {
return TransitionFlipAngular::create(t, s, kTransitionOrientationRightOver); return TransitionFlipAngular::create(t, s, TransitionScene::Orientation::RIGHT_OVER);
} }
// //
@ -950,7 +950,7 @@ void TransitionZoomFlipX::onEnter()
float inDeltaZ, inAngleZ; float inDeltaZ, inAngleZ;
float outDeltaZ, outAngleZ; float outDeltaZ, outAngleZ;
if( _orientation == kTransitionOrientationRightOver ) { if( _orientation == TransitionScene::Orientation::RIGHT_OVER ) {
inDeltaZ = 90; inDeltaZ = 90;
inAngleZ = 270; inAngleZ = 270;
outDeltaZ = 90; outDeltaZ = 90;
@ -994,7 +994,7 @@ void TransitionZoomFlipX::onEnter()
_outScene->runAction(outA); _outScene->runAction(outA);
} }
TransitionZoomFlipX* TransitionZoomFlipX::create(float t, Scene* s, tOrientation o) TransitionZoomFlipX* TransitionZoomFlipX::create(float t, Scene* s, Orientation o)
{ {
TransitionZoomFlipX* pScene = new TransitionZoomFlipX(); TransitionZoomFlipX* pScene = new TransitionZoomFlipX();
pScene->initWithDuration(t, s, o); pScene->initWithDuration(t, s, o);
@ -1005,7 +1005,7 @@ TransitionZoomFlipX* TransitionZoomFlipX::create(float t, Scene* s, tOrientation
TransitionZoomFlipX* TransitionZoomFlipX::create(float t, Scene* s) TransitionZoomFlipX* TransitionZoomFlipX::create(float t, Scene* s)
{ {
return TransitionZoomFlipX::create(t, s, kTransitionOrientationRightOver); return TransitionZoomFlipX::create(t, s, TransitionScene::Orientation::RIGHT_OVER);
} }
// //
@ -1029,7 +1029,7 @@ void TransitionZoomFlipY::onEnter()
float inDeltaZ, inAngleZ; float inDeltaZ, inAngleZ;
float outDeltaZ, outAngleZ; float outDeltaZ, outAngleZ;
if( _orientation== kTransitionOrientationUpOver ) { if( _orientation== TransitionScene::Orientation::UP_OVER ) {
inDeltaZ = 90; inDeltaZ = 90;
inAngleZ = 270; inAngleZ = 270;
outDeltaZ = 90; outDeltaZ = 90;
@ -1073,7 +1073,7 @@ void TransitionZoomFlipY::onEnter()
_outScene->runAction(outA); _outScene->runAction(outA);
} }
TransitionZoomFlipY* TransitionZoomFlipY::create(float t, Scene* s, tOrientation o) TransitionZoomFlipY* TransitionZoomFlipY::create(float t, Scene* s, Orientation o)
{ {
TransitionZoomFlipY* pScene = new TransitionZoomFlipY(); TransitionZoomFlipY* pScene = new TransitionZoomFlipY();
pScene->initWithDuration(t, s, o); pScene->initWithDuration(t, s, o);
@ -1084,7 +1084,7 @@ TransitionZoomFlipY* TransitionZoomFlipY::create(float t, Scene* s, tOrientation
TransitionZoomFlipY* TransitionZoomFlipY::create(float t, Scene* s) TransitionZoomFlipY* TransitionZoomFlipY::create(float t, Scene* s)
{ {
return TransitionZoomFlipY::create(t, s, kTransitionOrientationUpOver); return TransitionZoomFlipY::create(t, s, TransitionScene::Orientation::UP_OVER);
} }
// //
@ -1108,7 +1108,7 @@ void TransitionZoomFlipAngular::onEnter()
float inDeltaZ, inAngleZ; float inDeltaZ, inAngleZ;
float outDeltaZ, outAngleZ; float outDeltaZ, outAngleZ;
if( _orientation == kTransitionOrientationRightOver ) { if( _orientation == TransitionScene::Orientation::RIGHT_OVER ) {
inDeltaZ = 90; inDeltaZ = 90;
inAngleZ = 270; inAngleZ = 270;
outDeltaZ = 90; outDeltaZ = 90;
@ -1154,7 +1154,7 @@ void TransitionZoomFlipAngular::onEnter()
_outScene->runAction(outA); _outScene->runAction(outA);
} }
TransitionZoomFlipAngular* TransitionZoomFlipAngular::create(float t, Scene* s, tOrientation o) TransitionZoomFlipAngular* TransitionZoomFlipAngular::create(float t, Scene* s, Orientation o)
{ {
TransitionZoomFlipAngular* pScene = new TransitionZoomFlipAngular(); TransitionZoomFlipAngular* pScene = new TransitionZoomFlipAngular();
pScene->initWithDuration(t, s, o); pScene->initWithDuration(t, s, o);
@ -1165,7 +1165,7 @@ TransitionZoomFlipAngular* TransitionZoomFlipAngular::create(float t, Scene* s,
TransitionZoomFlipAngular* TransitionZoomFlipAngular::create(float t, Scene* s) TransitionZoomFlipAngular* TransitionZoomFlipAngular::create(float t, Scene* s)
{ {
return TransitionZoomFlipAngular::create(t, s, kTransitionOrientationRightOver); return TransitionZoomFlipAngular::create(t, s, TransitionScene::Orientation::RIGHT_OVER);
} }
// //

View File

@ -56,31 +56,25 @@ public:
virtual ActionInterval * easeActionWithAction(ActionInterval * action) = 0; virtual ActionInterval * easeActionWithAction(ActionInterval * action) = 0;
}; };
/** Orientation Type used by some transitions
*/
typedef enum {
/// An horizontal orientation where the Left is nearer
kTransitionOrientationLeftOver = 0,
/// An horizontal orientation where the Right is nearer
kTransitionOrientationRightOver = 1,
/// A vertical orientation where the Up is nearer
kTransitionOrientationUpOver = 0,
/// A vertical orientation where the Bottom is nearer
kTransitionOrientationDownOver = 1,
// Deprecated
// kOrientationLeftOver = kTransitionOrientationLeftOver,
// kOrientationRightOver = kTransitionOrientationRightOver,
// kOrientationUpOver = kTransitionOrientationUpOver,
// kOrientationDownOver = kTransitionOrientationDownOver,
} tOrientation;
/** @brief Base class for Transition scenes /** @brief Base class for Transition scenes
*/ */
class CC_DLL TransitionScene : public Scene class CC_DLL TransitionScene : public Scene
{ {
public: public:
/** Orientation Type used by some transitions
*/
enum class Orientation
{
/// An horizontal orientation where the Left is nearer
LEFT_OVER = 0,
/// An horizontal orientation where the Right is nearer
RIGHT_OVER = 1,
/// A vertical orientation where the Up is nearer
UP_OVER = 0,
/// A vertical orientation where the Bottom is nearer
DOWN_OVER = 1,
};
/** creates a base transition with duration and incoming scene */ /** creates a base transition with duration and incoming scene */
static TransitionScene * create(float t, Scene *scene); static TransitionScene * create(float t, Scene *scene);
@ -125,16 +119,16 @@ class CC_DLL TransitionSceneOriented : public TransitionScene
{ {
public: public:
/** creates a base transition with duration and incoming scene */ /** creates a base transition with duration and incoming scene */
static TransitionSceneOriented * create(float t,Scene* scene, tOrientation orientation); static TransitionSceneOriented * create(float t,Scene* scene, Orientation orientation);
TransitionSceneOriented(); TransitionSceneOriented();
virtual ~TransitionSceneOriented(); virtual ~TransitionSceneOriented();
/** initializes a transition with duration and incoming scene */ /** initializes a transition with duration and incoming scene */
bool initWithDuration(float t,Scene* scene,tOrientation orientation); bool initWithDuration(float t,Scene* scene,Orientation orientation);
protected: protected:
tOrientation _orientation; Orientation _orientation;
}; };
/** @brief TransitionRotoZoom: /** @brief TransitionRotoZoom:
@ -345,7 +339,7 @@ The front face is the outgoing scene and the back face is the incoming scene.
class CC_DLL TransitionFlipX : public TransitionSceneOriented class CC_DLL TransitionFlipX : public TransitionSceneOriented
{ {
public: public:
static TransitionFlipX* create(float t, Scene* s, tOrientation o); static TransitionFlipX* create(float t, Scene* s, Orientation o);
static TransitionFlipX* create(float t, Scene* s); static TransitionFlipX* create(float t, Scene* s);
TransitionFlipX(); TransitionFlipX();
@ -364,7 +358,7 @@ The front face is the outgoing scene and the back face is the incoming scene.
class CC_DLL TransitionFlipY : public TransitionSceneOriented class CC_DLL TransitionFlipY : public TransitionSceneOriented
{ {
public: public:
static TransitionFlipY* create(float t, Scene* s, tOrientation o); static TransitionFlipY* create(float t, Scene* s, Orientation o);
static TransitionFlipY* create(float t, Scene* s); static TransitionFlipY* create(float t, Scene* s);
TransitionFlipY(); TransitionFlipY();
@ -383,7 +377,7 @@ The front face is the outgoing scene and the back face is the incoming scene.
class CC_DLL TransitionFlipAngular : public TransitionSceneOriented class CC_DLL TransitionFlipAngular : public TransitionSceneOriented
{ {
public: public:
static TransitionFlipAngular* create(float t, Scene* s, tOrientation o); static TransitionFlipAngular* create(float t, Scene* s, Orientation o);
static TransitionFlipAngular* create(float t, Scene* s); static TransitionFlipAngular* create(float t, Scene* s);
TransitionFlipAngular(); TransitionFlipAngular();
@ -402,7 +396,7 @@ The front face is the outgoing scene and the back face is the incoming scene.
class CC_DLL TransitionZoomFlipX : public TransitionSceneOriented class CC_DLL TransitionZoomFlipX : public TransitionSceneOriented
{ {
public: public:
static TransitionZoomFlipX* create(float t, Scene* s, tOrientation o); static TransitionZoomFlipX* create(float t, Scene* s, Orientation o);
static TransitionZoomFlipX* create(float t, Scene* s); static TransitionZoomFlipX* create(float t, Scene* s);
TransitionZoomFlipX(); TransitionZoomFlipX();
@ -421,7 +415,7 @@ The front face is the outgoing scene and the back face is the incoming scene.
class CC_DLL TransitionZoomFlipY : public TransitionSceneOriented class CC_DLL TransitionZoomFlipY : public TransitionSceneOriented
{ {
public: public:
static TransitionZoomFlipY* create(float t, Scene* s, tOrientation o); static TransitionZoomFlipY* create(float t, Scene* s, Orientation o);
static TransitionZoomFlipY* create(float t, Scene* s); static TransitionZoomFlipY* create(float t, Scene* s);
TransitionZoomFlipY(); TransitionZoomFlipY();
@ -440,7 +434,7 @@ The front face is the outgoing scene and the back face is the incoming scene.
class CC_DLL TransitionZoomFlipAngular : public TransitionSceneOriented class CC_DLL TransitionZoomFlipAngular : public TransitionSceneOriented
{ {
public: public:
static TransitionZoomFlipAngular* create(float t, Scene* s, tOrientation o); static TransitionZoomFlipAngular* create(float t, Scene* s, Orientation o);
static TransitionZoomFlipAngular* create(float t, Scene* s); static TransitionZoomFlipAngular* create(float t, Scene* s);
TransitionZoomFlipAngular(); TransitionZoomFlipAngular();

View File

@ -140,7 +140,7 @@ ProgressTimer* TransitionProgressRadialCCW::progressTimerNodeWithRenderTexture(R
// but it is flipped upside down so we flip the sprite // but it is flipped upside down so we flip the sprite
pNode->getSprite()->setFlipY(true); pNode->getSprite()->setFlipY(true);
pNode->setType(kProgressTimerTypeRadial); pNode->setType(ProgressTimer::Type::RADIAL);
// Return the radial type that we want to use // Return the radial type that we want to use
pNode->setReverseDirection(false); pNode->setReverseDirection(false);
@ -184,7 +184,7 @@ ProgressTimer* TransitionProgressRadialCW::progressTimerNodeWithRenderTexture(Re
// but it is flipped upside down so we flip the sprite // but it is flipped upside down so we flip the sprite
pNode->getSprite()->setFlipY(true); pNode->getSprite()->setFlipY(true);
pNode->setType( kProgressTimerTypeRadial ); pNode->setType( ProgressTimer::Type::RADIAL );
// Return the radial type that we want to use // Return the radial type that we want to use
pNode->setReverseDirection(true); pNode->setReverseDirection(true);
@ -216,7 +216,7 @@ ProgressTimer* TransitionProgressHorizontal::progressTimerNodeWithRenderTexture(
// but it is flipped upside down so we flip the sprite // but it is flipped upside down so we flip the sprite
pNode->getSprite()->setFlipY(true); pNode->getSprite()->setFlipY(true);
pNode->setType( kProgressTimerTypeBar); pNode->setType( ProgressTimer::Type::BAR);
pNode->setMidpoint(Point(1, 0)); pNode->setMidpoint(Point(1, 0));
pNode->setBarChangeRate(Point(1,0)); pNode->setBarChangeRate(Point(1,0));
@ -249,7 +249,7 @@ ProgressTimer* TransitionProgressVertical::progressTimerNodeWithRenderTexture(Re
// but it is flipped upside down so we flip the sprite // but it is flipped upside down so we flip the sprite
pNode->getSprite()->setFlipY(true); pNode->getSprite()->setFlipY(true);
pNode->setType(kProgressTimerTypeBar); pNode->setType(ProgressTimer::Type::BAR);
pNode->setMidpoint(Point(0, 0)); pNode->setMidpoint(Point(0, 0));
pNode->setBarChangeRate(Point(0,1)); pNode->setBarChangeRate(Point(0,1));
@ -295,7 +295,7 @@ ProgressTimer* TransitionProgressInOut::progressTimerNodeWithRenderTexture(Rende
// but it is flipped upside down so we flip the sprite // but it is flipped upside down so we flip the sprite
pNode->getSprite()->setFlipY(true); pNode->getSprite()->setFlipY(true);
pNode->setType( kProgressTimerTypeBar); pNode->setType( ProgressTimer::Type::BAR);
pNode->setMidpoint(Point(0.5f, 0.5f)); pNode->setMidpoint(Point(0.5f, 0.5f));
pNode->setBarChangeRate(Point(1, 1)); pNode->setBarChangeRate(Point(1, 1));
@ -329,7 +329,7 @@ ProgressTimer* TransitionProgressOutIn::progressTimerNodeWithRenderTexture(Rende
// but it is flipped upside down so we flip the sprite // but it is flipped upside down so we flip the sprite
pNode->getSprite()->setFlipY(true); pNode->getSprite()->setFlipY(true);
pNode->setType( kProgressTimerTypeBar ); pNode->setType( ProgressTimer::Type::BAR );
pNode->setMidpoint(Point(0.5f, 0.5f)); pNode->setMidpoint(Point(0.5f, 0.5f));
pNode->setBarChangeRate(Point(1, 1)); pNode->setBarChangeRate(Point(1, 1));

View File

@ -121,8 +121,8 @@ bool Menu::initWithArray(Array* pArrayOfItems)
{ {
if (Layer::init()) if (Layer::init())
{ {
setTouchPriority(kMenuHandlerPriority); setTouchPriority(Menu::HANDLER_PRIORITY);
setTouchMode(kTouchesOneByOne); setTouchMode(Touch::DispatchMode::ONE_BY_ONE);
setTouchEnabled(true); setTouchEnabled(true);
_enabled = true; _enabled = true;
@ -149,7 +149,7 @@ bool Menu::initWithArray(Array* pArrayOfItems)
// [self alignItemsVertically]; // [self alignItemsVertically];
_selectedItem = NULL; _selectedItem = NULL;
_state = kMenuStateWaiting; _state = Menu::State::WAITING;
// enable cascade color and opacity on menus // enable cascade color and opacity on menus
setCascadeColorEnabled(true); setCascadeColorEnabled(true);
@ -181,7 +181,7 @@ void Menu::addChild(Node * child, int zOrder, int tag)
void Menu::onExit() void Menu::onExit()
{ {
if (_state == kMenuStateTrackingTouch) if (_state == Menu::State::TRACKING_TOUCH)
{ {
if (_selectedItem) if (_selectedItem)
{ {
@ -189,7 +189,7 @@ void Menu::onExit()
_selectedItem = NULL; _selectedItem = NULL;
} }
_state = kMenuStateWaiting; _state = Menu::State::WAITING;
} }
Layer::onExit(); Layer::onExit();
@ -225,7 +225,7 @@ void Menu::registerWithTouchDispatcher()
bool Menu::ccTouchBegan(Touch* touch, Event* event) bool Menu::ccTouchBegan(Touch* touch, Event* event)
{ {
CC_UNUSED_PARAM(event); CC_UNUSED_PARAM(event);
if (_state != kMenuStateWaiting || ! _visible || !_enabled) if (_state != Menu::State::WAITING || ! _visible || !_enabled)
{ {
return false; return false;
} }
@ -241,7 +241,7 @@ bool Menu::ccTouchBegan(Touch* touch, Event* event)
_selectedItem = this->itemForTouch(touch); _selectedItem = this->itemForTouch(touch);
if (_selectedItem) if (_selectedItem)
{ {
_state = kMenuStateTrackingTouch; _state = Menu::State::TRACKING_TOUCH;
_selectedItem->selected(); _selectedItem->selected();
return true; return true;
} }
@ -252,31 +252,31 @@ void Menu::ccTouchEnded(Touch *touch, Event* event)
{ {
CC_UNUSED_PARAM(touch); CC_UNUSED_PARAM(touch);
CC_UNUSED_PARAM(event); CC_UNUSED_PARAM(event);
CCASSERT(_state == kMenuStateTrackingTouch, "[Menu ccTouchEnded] -- invalid state"); CCASSERT(_state == Menu::State::TRACKING_TOUCH, "[Menu ccTouchEnded] -- invalid state");
if (_selectedItem) if (_selectedItem)
{ {
_selectedItem->unselected(); _selectedItem->unselected();
_selectedItem->activate(); _selectedItem->activate();
} }
_state = kMenuStateWaiting; _state = Menu::State::WAITING;
} }
void Menu::ccTouchCancelled(Touch *touch, Event* event) void Menu::ccTouchCancelled(Touch *touch, Event* event)
{ {
CC_UNUSED_PARAM(touch); CC_UNUSED_PARAM(touch);
CC_UNUSED_PARAM(event); CC_UNUSED_PARAM(event);
CCASSERT(_state == kMenuStateTrackingTouch, "[Menu ccTouchCancelled] -- invalid state"); CCASSERT(_state == Menu::State::TRACKING_TOUCH, "[Menu ccTouchCancelled] -- invalid state");
if (_selectedItem) if (_selectedItem)
{ {
_selectedItem->unselected(); _selectedItem->unselected();
} }
_state = kMenuStateWaiting; _state = Menu::State::WAITING;
} }
void Menu::ccTouchMoved(Touch* touch, Event* event) void Menu::ccTouchMoved(Touch* touch, Event* event)
{ {
CC_UNUSED_PARAM(event); CC_UNUSED_PARAM(event);
CCASSERT(_state == kMenuStateTrackingTouch, "[Menu ccTouchMoved] -- invalid state"); CCASSERT(_state == Menu::State::TRACKING_TOUCH, "[Menu ccTouchMoved] -- invalid state");
MenuItem *currentItem = this->itemForTouch(touch); MenuItem *currentItem = this->itemForTouch(touch);
if (currentItem != _selectedItem) if (currentItem != _selectedItem)
{ {
@ -306,10 +306,10 @@ void Menu::alignItemsVerticallyWithPadding(float padding)
Object* pObject = NULL; Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject) CCARRAY_FOREACH(_children, pObject)
{ {
Node* pChild = dynamic_cast<Node*>(pObject); Node* child = dynamic_cast<Node*>(pObject);
if (pChild) if (child)
{ {
height += pChild->getContentSize().height * pChild->getScaleY() + padding; height += child->getContentSize().height * child->getScaleY() + padding;
} }
} }
} }
@ -320,11 +320,11 @@ void Menu::alignItemsVerticallyWithPadding(float padding)
Object* pObject = NULL; Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject) CCARRAY_FOREACH(_children, pObject)
{ {
Node* pChild = dynamic_cast<Node*>(pObject); Node* child = dynamic_cast<Node*>(pObject);
if (pChild) if (child)
{ {
pChild->setPosition(Point(0, y - pChild->getContentSize().height * pChild->getScaleY() / 2.0f)); child->setPosition(Point(0, y - child->getContentSize().height * child->getScaleY() / 2.0f));
y -= pChild->getContentSize().height * pChild->getScaleY() + padding; y -= child->getContentSize().height * child->getScaleY() + padding;
} }
} }
} }
@ -344,10 +344,10 @@ void Menu::alignItemsHorizontallyWithPadding(float padding)
Object* pObject = NULL; Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject) CCARRAY_FOREACH(_children, pObject)
{ {
Node* pChild = dynamic_cast<Node*>(pObject); Node* child = dynamic_cast<Node*>(pObject);
if (pChild) if (child)
{ {
width += pChild->getContentSize().width * pChild->getScaleX() + padding; width += child->getContentSize().width * child->getScaleX() + padding;
} }
} }
} }
@ -358,11 +358,11 @@ void Menu::alignItemsHorizontallyWithPadding(float padding)
Object* pObject = NULL; Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject) CCARRAY_FOREACH(_children, pObject)
{ {
Node* pChild = dynamic_cast<Node*>(pObject); Node* child = dynamic_cast<Node*>(pObject);
if (pChild) if (child)
{ {
pChild->setPosition(Point(x + pChild->getContentSize().width * pChild->getScaleX() / 2.0f, 0)); child->setPosition(Point(x + child->getContentSize().width * child->getScaleX() / 2.0f, 0));
x += pChild->getContentSize().width * pChild->getScaleX() + padding; x += child->getContentSize().width * child->getScaleX() + padding;
} }
} }
} }
@ -405,8 +405,8 @@ void Menu::alignItemsInColumnsWithArray(Array* rowsArray)
Object* pObject = NULL; Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject) CCARRAY_FOREACH(_children, pObject)
{ {
Node* pChild = dynamic_cast<Node*>(pObject); Node* child = dynamic_cast<Node*>(pObject);
if (pChild) if (child)
{ {
CCASSERT(row < rows.size(), ""); CCASSERT(row < rows.size(), "");
@ -414,7 +414,7 @@ void Menu::alignItemsInColumnsWithArray(Array* rowsArray)
// can not have zero columns on a row // can not have zero columns on a row
CCASSERT(rowColumns, ""); CCASSERT(rowColumns, "");
float tmp = pChild->getContentSize().height; float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp); rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
++columnsOccupied; ++columnsOccupied;
@ -447,8 +447,8 @@ void Menu::alignItemsInColumnsWithArray(Array* rowsArray)
Object* pObject = NULL; Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject) CCARRAY_FOREACH(_children, pObject)
{ {
Node* pChild = dynamic_cast<Node*>(pObject); Node* child = dynamic_cast<Node*>(pObject);
if (pChild) if (child)
{ {
if (rowColumns == 0) if (rowColumns == 0)
{ {
@ -457,11 +457,11 @@ void Menu::alignItemsInColumnsWithArray(Array* rowsArray)
x = w; x = w;
} }
float tmp = pChild->getContentSize().height; float tmp = child->getContentSize().height;
rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp); rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp);
pChild->setPosition(Point(x - winSize.width / 2, child->setPosition(Point(x - winSize.width / 2,
y - pChild->getContentSize().height / 2)); y - child->getContentSize().height / 2));
x += w; x += w;
++columnsOccupied; ++columnsOccupied;
@ -520,8 +520,8 @@ void Menu::alignItemsInRowsWithArray(Array* columnArray)
Object* pObject = NULL; Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject) CCARRAY_FOREACH(_children, pObject)
{ {
Node* pChild = dynamic_cast<Node*>(pObject); Node* child = dynamic_cast<Node*>(pObject);
if (pChild) if (child)
{ {
// check if too many menu items for the amount of rows/columns // check if too many menu items for the amount of rows/columns
CCASSERT(column < columns.size(), ""); CCASSERT(column < columns.size(), "");
@ -531,10 +531,10 @@ void Menu::alignItemsInRowsWithArray(Array* columnArray)
CCASSERT(columnRows, ""); CCASSERT(columnRows, "");
// columnWidth = fmaxf(columnWidth, [item contentSize].width); // columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = pChild->getContentSize().width; float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp); columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
columnHeight += (int)(pChild->getContentSize().height + 5); columnHeight += (int)(child->getContentSize().height + 5);
++rowsOccupied; ++rowsOccupied;
if (rowsOccupied >= columnRows) if (rowsOccupied >= columnRows)
@ -568,8 +568,8 @@ void Menu::alignItemsInRowsWithArray(Array* columnArray)
Object* pObject = NULL; Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject) CCARRAY_FOREACH(_children, pObject)
{ {
Node* pChild = dynamic_cast<Node*>(pObject); Node* child = dynamic_cast<Node*>(pObject);
if (pChild) if (child)
{ {
if (columnRows == 0) if (columnRows == 0)
{ {
@ -578,13 +578,13 @@ void Menu::alignItemsInRowsWithArray(Array* columnArray)
} }
// columnWidth = fmaxf(columnWidth, [item contentSize].width); // columnWidth = fmaxf(columnWidth, [item contentSize].width);
float tmp = pChild->getContentSize().width; float tmp = child->getContentSize().width;
columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp); columnWidth = (unsigned int)((columnWidth >= tmp || isnan(tmp)) ? columnWidth : tmp);
pChild->setPosition(Point(x + columnWidths[column] / 2, child->setPosition(Point(x + columnWidths[column] / 2,
y - winSize.height / 2)); y - winSize.height / 2));
y -= pChild->getContentSize().height + 10; y -= child->getContentSize().height + 10;
++rowsOccupied; ++rowsOccupied;
if (rowsOccupied >= columnRows) if (rowsOccupied >= columnRows)
@ -609,16 +609,16 @@ MenuItem* Menu::itemForTouch(Touch *touch)
Object* pObject = NULL; Object* pObject = NULL;
CCARRAY_FOREACH(_children, pObject) CCARRAY_FOREACH(_children, pObject)
{ {
MenuItem* pChild = dynamic_cast<MenuItem*>(pObject); MenuItem* child = dynamic_cast<MenuItem*>(pObject);
if (pChild && pChild->isVisible() && pChild->isEnabled()) if (child && child->isVisible() && child->isEnabled())
{ {
Point local = pChild->convertToNodeSpace(touchLocation); Point local = child->convertToNodeSpace(touchLocation);
Rect r = pChild->rect(); Rect r = child->rect();
r.origin = Point::ZERO; r.origin = Point::ZERO;
if (r.containsPoint(local)) if (r.containsPoint(local))
{ {
return pChild; return child;
} }
} }
} }

View File

@ -36,16 +36,8 @@ NS_CC_BEGIN
* @addtogroup menu * @addtogroup menu
* @{ * @{
*/ */
typedef enum
{
kMenuStateWaiting,
kMenuStateTrackingTouch
} tMenuState;
enum {
//* priority used by the menu for the event handler
kMenuHandlerPriority = -128,
};
/** @brief A Menu /** @brief A Menu
* *
@ -56,6 +48,17 @@ enum {
class CC_DLL Menu : public LayerRGBA class CC_DLL Menu : public LayerRGBA
{ {
public: public:
enum
{
HANDLER_PRIORITY = -128,
};
enum class State
{
WAITING,
TRACKING_TOUCH,
};
/** creates an empty Menu */ /** creates an empty Menu */
static Menu* create(); static Menu* create();
@ -133,7 +136,7 @@ protected:
bool _enabled; bool _enabled;
MenuItem* itemForTouch(Touch * touch); MenuItem* itemForTouch(Touch * touch);
tMenuState _state; State _state;
MenuItem *_selectedItem; MenuItem *_selectedItem;
}; };

View File

@ -33,6 +33,13 @@ THE SOFTWARE.
#include <stdarg.h> #include <stdarg.h>
#include <cstring> #include <cstring>
#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#elif _MSC_VER >= 1400 //vs 2005 or higher
#pragma warning (push)
#pragma warning (disable: 4996)
#endif
NS_CC_BEGIN NS_CC_BEGIN
static unsigned int _globalFontSize = kItemSize; static unsigned int _globalFontSize = kItemSize;
@ -986,3 +993,9 @@ MenuItem* MenuItemToggle::getSelectedItem()
} }
NS_CC_END NS_CC_END
#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
#elif _MSC_VER >= 1400 //vs 2005 or higher
#pragma warning (pop)
#endif

View File

@ -151,7 +151,7 @@ void ClippingNode::drawFullScreenQuadClearStencil()
kmGLPushMatrix(); kmGLPushMatrix();
kmGLLoadIdentity(); kmGLLoadIdentity();
ccDrawSolidRect(Point(-1,-1), Point(1,1), Color4F(1, 1, 1, 1)); DrawPrimitives::drawSolidRect(Point(-1,-1), Point(1,1), Color4F(1, 1, 1, 1));
kmGLMatrixMode(KM_GL_PROJECTION); kmGLMatrixMode(KM_GL_PROJECTION);
kmGLPopMatrix(); kmGLPopMatrix();
@ -308,8 +308,8 @@ void ClippingNode::visit()
#else #else
// since glAlphaTest do not exists in OES, use a shader that writes // since glAlphaTest do not exists in OES, use a shader that writes
// pixel only if greater than an alpha threshold // pixel only if greater than an alpha threshold
GLProgram *program = ShaderCache::getInstance()->programForKey(kShader_PositionTextureColorAlphaTest); GLProgram *program = ShaderCache::getInstance()->programForKey(GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST);
GLint alphaValueLocation = glGetUniformLocation(program->getProgram(), kUniformAlphaTestValue); GLint alphaValueLocation = glGetUniformLocation(program->getProgram(), GLProgram::UNIFORM_NAME_ALPHA_TEST_VALUE);
// set our alphaThreshold // set our alphaThreshold
program->setUniformLocationWith1f(alphaValueLocation, _alphaThreshold); program->setUniformLocationWith1f(alphaValueLocation, _alphaThreshold);
// 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

View File

@ -49,9 +49,8 @@ MotionStreak::MotionStreak()
, _vertices(NULL) , _vertices(NULL)
, _colorPointer(NULL) , _colorPointer(NULL)
, _texCoords(NULL) , _texCoords(NULL)
, _blendFunc(BlendFunc::ALPHA_NON_PREMULTIPLIED)
{ {
_blendFunc.src = GL_SRC_ALPHA;
_blendFunc.dst = GL_ONE_MINUS_SRC_ALPHA;
} }
MotionStreak::~MotionStreak() MotionStreak::~MotionStreak()
@ -123,11 +122,10 @@ bool MotionStreak::initWithFade(float fade, float minSeg, float stroke, const Co
_colorPointer = (GLubyte*)malloc(sizeof(GLubyte) * _maxPoints * 2 * 4); _colorPointer = (GLubyte*)malloc(sizeof(GLubyte) * _maxPoints * 2 * 4);
// Set blend mode // Set blend mode
_blendFunc.src = GL_SRC_ALPHA; _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED;
_blendFunc.dst = GL_ONE_MINUS_SRC_ALPHA;
// shader program // shader program
setShaderProgram(ShaderCache::getInstance()->programForKey(kShader_PositionTextureColor)); setShaderProgram(ShaderCache::getInstance()->programForKey(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
setTexture(texture); setTexture(texture);
setColor(color); setColor(color);
@ -331,25 +329,25 @@ void MotionStreak::draw()
CC_NODE_DRAW_SETUP(); CC_NODE_DRAW_SETUP();
ccGLEnableVertexAttribs(kVertexAttribFlag_PosColorTex ); GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX );
ccGLBlendFunc( _blendFunc.src, _blendFunc.dst ); GL::blendFunc( _blendFunc.src, _blendFunc.dst );
ccGLBindTexture2D( _texture->getName() ); GL::bindTexture2D( _texture->getName() );
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
// Size calculations from ::initWithFade // Size calculations from ::initWithFade
setGLBufferData(_vertices, (sizeof(Vertex2F) * _maxPoints * 2), 0); setGLBufferData(_vertices, (sizeof(Vertex2F) * _maxPoints * 2), 0);
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, 0);
setGLBufferData(_texCoords, (sizeof(Tex2F) * _maxPoints * 2), 1); setGLBufferData(_texCoords, (sizeof(Tex2F) * _maxPoints * 2), 1);
glVertexAttribPointer(kVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, 0, 0);
setGLBufferData(_colorPointer, (sizeof(GLubyte) * _maxPoints * 2 * 4), 2); setGLBufferData(_colorPointer, (sizeof(GLubyte) * _maxPoints * 2 * 4), 2);
glVertexAttribPointer(kVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0);
#else #else
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, _vertices); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, 0, _vertices);
glVertexAttribPointer(kVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, _texCoords); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, 0, _texCoords);
glVertexAttribPointer(kVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, _colorPointer); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, _colorPointer);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
glDrawArrays(GL_TRIANGLE_STRIP, 0, (GLsizei)_nuPoints*2); glDrawArrays(GL_TRIANGLE_STRIP, 0, (GLsizei)_nuPoints*2);

View File

@ -45,7 +45,7 @@ const char kProgressTextureCoords = 0x4b;
ProgressTimer::ProgressTimer() ProgressTimer::ProgressTimer()
:_type(kProgressTimerTypeRadial) :_type(Type::RADIAL)
,_percentage(0.0f) ,_percentage(0.0f)
,_sprite(NULL) ,_sprite(NULL)
,_vertexDataCount(0) ,_vertexDataCount(0)
@ -78,13 +78,13 @@ bool ProgressTimer::initWithSprite(Sprite* sp)
_vertexDataCount = 0; _vertexDataCount = 0;
setAnchorPoint(Point(0.5f,0.5f)); setAnchorPoint(Point(0.5f,0.5f));
_type = kProgressTimerTypeRadial; _type = Type::RADIAL;
_reverseDirection = false; _reverseDirection = false;
setMidpoint(Point(0.5f, 0.5f)); setMidpoint(Point(0.5f, 0.5f));
setBarChangeRate(Point(1,1)); setBarChangeRate(Point(1,1));
setSprite(sp); setSprite(sp);
// shader program // shader program
setShaderProgram(ShaderCache::getInstance()->programForKey(kShader_PositionTextureColor)); setShaderProgram(ShaderCache::getInstance()->programForKey(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
return true; return true;
} }
@ -121,7 +121,7 @@ void ProgressTimer::setSprite(Sprite *pSprite)
} }
} }
void ProgressTimer::setType(ProgressTimerType type) void ProgressTimer::setType(Type type)
{ {
if (type != _type) if (type != _type)
{ {
@ -225,10 +225,10 @@ void ProgressTimer::updateProgress(void)
{ {
switch (_type) switch (_type)
{ {
case kProgressTimerTypeRadial: case Type::RADIAL:
updateRadial(); updateRadial();
break; break;
case kProgressTimerTypeBar: case Type::BAR:
updateBar(); updateBar();
break; break;
default: default:
@ -504,34 +504,34 @@ void ProgressTimer::draw(void)
CC_NODE_DRAW_SETUP(); CC_NODE_DRAW_SETUP();
ccGLBlendFunc( _sprite->getBlendFunc().src, _sprite->getBlendFunc().dst ); GL::blendFunc( _sprite->getBlendFunc().src, _sprite->getBlendFunc().dst );
ccGLEnableVertexAttribs(kVertexAttribFlag_PosColorTex ); GL::enableVertexAttribs(GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX );
ccGLBindTexture2D( _sprite->getTexture()->getName() ); GL::bindTexture2D( _sprite->getTexture()->getName() );
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
setGLBufferData((void*) _vertexData, (_vertexDataCount * sizeof(V2F_C4B_T2F)), 0); setGLBufferData((void*) _vertexData, (_vertexDataCount * sizeof(V2F_C4B_T2F)), 0);
int offset = 0; int offset = 0;
glVertexAttribPointer( kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid*)offset); glVertexAttribPointer( GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid*)offset);
offset += sizeof(Vertex2F); offset += sizeof(Vertex2F);
glVertexAttribPointer( kVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid*)offset); glVertexAttribPointer( GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(V2F_C4B_T2F), (GLvoid*)offset);
offset += sizeof(Color4B); offset += sizeof(Color4B);
glVertexAttribPointer( kVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid*)offset); glVertexAttribPointer( GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, sizeof(V2F_C4B_T2F), (GLvoid*)offset);
#else #else
glVertexAttribPointer( kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, sizeof(_vertexData[0]) , &_vertexData[0].vertices); glVertexAttribPointer( GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, sizeof(_vertexData[0]) , &_vertexData[0].vertices);
glVertexAttribPointer( kVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, sizeof(_vertexData[0]), &_vertexData[0].texCoords); glVertexAttribPointer( GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, sizeof(_vertexData[0]), &_vertexData[0].texCoords);
glVertexAttribPointer( kVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(_vertexData[0]), &_vertexData[0].colors); glVertexAttribPointer( GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(_vertexData[0]), &_vertexData[0].colors);
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
if(_type == kProgressTimerTypeRadial) if(_type == Type::RADIAL)
{ {
glDrawArrays(GL_TRIANGLE_FAN, 0, _vertexDataCount); glDrawArrays(GL_TRIANGLE_FAN, 0, _vertexDataCount);
} }
else if (_type == kProgressTimerTypeBar) else if (_type == Type::BAR)
{ {
if (!_reverseDirection) if (!_reverseDirection)
{ {

View File

@ -37,16 +37,6 @@ NS_CC_BEGIN
* @{ * @{
*/ */
/** Types of progress
@since v0.99.1
*/
typedef enum {
/// Radial Counter-Clockwise
kProgressTimerTypeRadial,
/// Bar
kProgressTimerTypeBar,
} ProgressTimerType;
/** /**
@brief ProgressTimer is a subclass of Node. @brief ProgressTimer is a subclass of Node.
It renders the inner sprite according to the percentage. It renders the inner sprite according to the percentage.
@ -59,6 +49,17 @@ class CC_DLL ProgressTimer : public NodeRGBA
#endif // EMSCRIPTEN #endif // EMSCRIPTEN
{ {
public: public:
/** Types of progress
@since v0.99.1
*/
enum class Type
{
/// Radial Counter-Clockwise
RADIAL,
/// Bar
BAR,
};
/** Creates a progress timer with the sprite as the shape the timer goes through */ /** Creates a progress timer with the sprite as the shape the timer goes through */
static ProgressTimer* create(Sprite* sp); static ProgressTimer* create(Sprite* sp);
@ -69,7 +70,7 @@ public:
bool initWithSprite(Sprite* sp); bool initWithSprite(Sprite* sp);
/** Change the percentage to change progress. */ /** Change the percentage to change progress. */
inline ProgressTimerType getType() const { return _type; } inline Type getType() const { return _type; }
/** Percentages are from 0 to 100 */ /** Percentages are from 0 to 100 */
inline float getPercentage() const {return _percentage; } inline float getPercentage() const {return _percentage; }
@ -79,7 +80,7 @@ public:
void setPercentage(float fPercentage); void setPercentage(float fPercentage);
void setSprite(Sprite *pSprite); void setSprite(Sprite *pSprite);
void setType(ProgressTimerType type); void setType(Type type);
void setReverseProgress(bool reverse); void setReverseProgress(bool reverse);
inline bool isReverseDirection() { return _reverseDirection; }; inline bool isReverseDirection() { return _reverseDirection; };
@ -126,7 +127,7 @@ protected:
void updateColor(void); void updateColor(void);
Point boundaryTexCoord(char index); Point boundaryTexCoord(char index);
ProgressTimerType _type; Type _type;
Point _midpoint; Point _midpoint;
Point _barChangeRate; Point _barChangeRate;
float _percentage; float _percentage;

View File

@ -51,7 +51,7 @@ RenderTexture::RenderTexture()
, _texture(0) , _texture(0)
, _textureCopy(0) , _textureCopy(0)
, _UITextureImage(NULL) , _UITextureImage(NULL)
, _pixelFormat(kTexture2DPixelFormat_RGBA8888) , _pixelFormat(Texture2D::PixelFormat::RGBA8888)
, _clearFlags(0) , _clearFlags(0)
, _clearColor(Color4F(0,0,0,0)) , _clearColor(Color4F(0,0,0,0))
, _clearDepth(0.0f) , _clearDepth(0.0f)
@ -102,11 +102,11 @@ void RenderTexture::listenToBackground(cocos2d::Object *obj)
if (_UITextureImage) if (_UITextureImage)
{ {
const Size& s = _texture->getContentSizeInPixels(); const Size& s = _texture->getContentSizeInPixels();
VolatileTexture::addDataTexture(_texture, _UITextureImage->getData(), kTexture2DPixelFormat_RGBA8888, s); VolatileTexture::addDataTexture(_texture, _UITextureImage->getData(), Texture2D::PixelFormat::RGBA8888, s);
if ( _textureCopy ) if ( _textureCopy )
{ {
VolatileTexture::addDataTexture(_textureCopy, _UITextureImage->getData(), kTexture2DPixelFormat_RGBA8888, s); VolatileTexture::addDataTexture(_textureCopy, _UITextureImage->getData(), Texture2D::PixelFormat::RGBA8888, s);
} }
} }
else else
@ -140,7 +140,7 @@ void RenderTexture::listenToForeground(cocos2d::Object *obj)
#endif #endif
} }
RenderTexture * RenderTexture::create(int w, int h, Texture2DPixelFormat eFormat) RenderTexture * RenderTexture::create(int w, int h, Texture2D::PixelFormat eFormat)
{ {
RenderTexture *pRet = new RenderTexture(); RenderTexture *pRet = new RenderTexture();
@ -153,7 +153,7 @@ RenderTexture * RenderTexture::create(int w, int h, Texture2DPixelFormat eFormat
return NULL; return NULL;
} }
RenderTexture * RenderTexture::create(int w ,int h, Texture2DPixelFormat eFormat, GLuint uDepthStencilFormat) RenderTexture * RenderTexture::create(int w ,int h, Texture2D::PixelFormat eFormat, GLuint uDepthStencilFormat)
{ {
RenderTexture *pRet = new RenderTexture(); RenderTexture *pRet = new RenderTexture();
@ -170,7 +170,7 @@ RenderTexture * RenderTexture::create(int w, int h)
{ {
RenderTexture *pRet = new RenderTexture(); RenderTexture *pRet = new RenderTexture();
if(pRet && pRet->initWithWidthAndHeight(w, h, kTexture2DPixelFormat_RGBA8888, 0)) if(pRet && pRet->initWithWidthAndHeight(w, h, Texture2D::PixelFormat::RGBA8888, 0))
{ {
pRet->autorelease(); pRet->autorelease();
return pRet; return pRet;
@ -179,14 +179,14 @@ RenderTexture * RenderTexture::create(int w, int h)
return NULL; return NULL;
} }
bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2DPixelFormat eFormat) bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat eFormat)
{ {
return initWithWidthAndHeight(w, h, eFormat, 0); return initWithWidthAndHeight(w, h, eFormat, 0);
} }
bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2DPixelFormat eFormat, GLuint uDepthStencilFormat) bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat eFormat, GLuint uDepthStencilFormat)
{ {
CCASSERT(eFormat != kTexture2DPixelFormat_A8, "only RGB and RGBA formats are valid for a render texture"); CCASSERT(eFormat != Texture2D::PixelFormat::A8, "only RGB and RGBA formats are valid for a render texture");
bool bRet = false; bool bRet = false;
void *data = NULL; void *data = NULL;
@ -221,7 +221,7 @@ bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2DPixelFormat eF
_texture = new Texture2D(); _texture = new Texture2D();
if (_texture) if (_texture)
{ {
_texture->initWithData(data, (Texture2DPixelFormat)_pixelFormat, powW, powH, Size((float)w, (float)h)); _texture->initWithData(data, (Texture2D::PixelFormat)_pixelFormat, powW, powH, Size((float)w, (float)h));
} }
else else
{ {
@ -235,7 +235,7 @@ bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2DPixelFormat eF
_textureCopy = new Texture2D(); _textureCopy = new Texture2D();
if (_textureCopy) if (_textureCopy)
{ {
_textureCopy->initWithData(data, (Texture2DPixelFormat)_pixelFormat, powW, powH, Size((float)w, (float)h)); _textureCopy->initWithData(data, (Texture2D::PixelFormat)_pixelFormat, powW, powH, Size((float)w, (float)h));
} }
else else
{ {
@ -276,8 +276,7 @@ bool RenderTexture::initWithWidthAndHeight(int w, int h, Texture2DPixelFormat eF
_texture->release(); _texture->release();
_sprite->setScaleY(-1); _sprite->setScaleY(-1);
BlendFunc tBlendFunc = {GL_ONE, GL_ONE_MINUS_SRC_ALPHA }; _sprite->setBlendFunc( BlendFunc::ALPHA_PREMULTIPLIED );
_sprite->setBlendFunc(tBlendFunc);
glBindRenderbuffer(GL_RENDERBUFFER, oldRBO); glBindRenderbuffer(GL_RENDERBUFFER, oldRBO);
glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO); glBindFramebuffer(GL_FRAMEBUFFER, _oldFBO);
@ -531,11 +530,11 @@ void RenderTexture::draw()
Object *pElement; Object *pElement;
CCARRAY_FOREACH(_children, pElement) CCARRAY_FOREACH(_children, pElement)
{ {
Node *pChild = static_cast<Node*>(pElement); Node *child = static_cast<Node*>(pElement);
if (pChild != _sprite) if (child != _sprite)
{ {
pChild->visit(); child->visit();
} }
} }
@ -545,40 +544,40 @@ void RenderTexture::draw()
bool RenderTexture::saveToFile(const char *szFilePath) bool RenderTexture::saveToFile(const char *szFilePath)
{ {
bool bRet = false; bool ret = false;
Image *pImage = newImage(true); Image *image = newImage(true);
if (pImage) if (image)
{ {
bRet = pImage->saveToFile(szFilePath, kImageFormatJPEG); ret = image->saveToFile(szFilePath);
} }
CC_SAFE_DELETE(pImage); CC_SAFE_DELETE(image);
return bRet; return ret;
} }
bool RenderTexture::saveToFile(const char *fileName, tImageFormat format) bool RenderTexture::saveToFile(const char *fileName, Image::Format format)
{ {
bool bRet = false; bool bRet = false;
CCASSERT(format == kImageFormatJPEG || format == kImageFormatPNG, CCASSERT(format == Image::Format::JPG || format == Image::Format::PNG,
"the image can only be saved as JPG or PNG format"); "the image can only be saved as JPG or PNG format");
Image *pImage = newImage(true); Image *image = newImage(true);
if (pImage) if (image)
{ {
std::string fullpath = FileUtils::getInstance()->getWritablePath() + fileName; std::string fullpath = FileUtils::getInstance()->getWritablePath() + fileName;
bRet = pImage->saveToFile(fullpath.c_str(), true); bRet = image->saveToFile(fullpath.c_str(), true);
} }
CC_SAFE_DELETE(pImage); CC_SAFE_DELETE(image);
return bRet; return bRet;
} }
/* get buffer as Image */ /* get buffer as Image */
Image* RenderTexture::newImage(bool flipImage) Image* RenderTexture::newImage(bool fliimage)
{ {
CCASSERT(_pixelFormat == kTexture2DPixelFormat_RGBA8888, "only RGBA8888 can be saved as image"); CCASSERT(_pixelFormat == Texture2D::PixelFormat::RGBA8888, "only RGBA8888 can be saved as image");
if (NULL == _texture) if (NULL == _texture)
{ {
@ -595,7 +594,7 @@ Image* RenderTexture::newImage(bool flipImage)
GLubyte *pBuffer = NULL; GLubyte *pBuffer = NULL;
GLubyte *pTempData = NULL; GLubyte *pTempData = NULL;
Image *pImage = new Image(); Image *image = new Image();
do do
{ {
@ -613,7 +612,7 @@ Image* RenderTexture::newImage(bool flipImage)
glReadPixels(0,0,nSavedBufferWidth, nSavedBufferHeight,GL_RGBA,GL_UNSIGNED_BYTE, pTempData); glReadPixels(0,0,nSavedBufferWidth, nSavedBufferHeight,GL_RGBA,GL_UNSIGNED_BYTE, pTempData);
this->end(); this->end();
if ( flipImage ) // -- flip is only required when saving image to file if ( fliimage ) // -- flip is only required when saving image to file
{ {
// to get the actual texture data // to get the actual texture data
// #640 the image read from rendertexture is dirty // #640 the image read from rendertexture is dirty
@ -624,11 +623,11 @@ Image* RenderTexture::newImage(bool flipImage)
nSavedBufferWidth * 4); nSavedBufferWidth * 4);
} }
pImage->initWithImageData(pBuffer, nSavedBufferWidth * nSavedBufferHeight * 4, Image::kFmtRawData, nSavedBufferWidth, nSavedBufferHeight, 8); image->initWithImageData(pBuffer, nSavedBufferWidth * nSavedBufferHeight * 4, Image::Format::RAW_DATA, nSavedBufferWidth, nSavedBufferHeight, 8);
} }
else else
{ {
pImage->initWithImageData(pTempData, nSavedBufferWidth * nSavedBufferHeight * 4, Image::kFmtRawData, nSavedBufferWidth, nSavedBufferHeight, 8); image->initWithImageData(pTempData, nSavedBufferWidth * nSavedBufferHeight * 4, Image::Format::RAW_DATA, nSavedBufferWidth, nSavedBufferHeight, 8);
} }
} while (0); } while (0);
@ -636,7 +635,7 @@ Image* RenderTexture::newImage(bool flipImage)
CC_SAFE_DELETE_ARRAY(pBuffer); CC_SAFE_DELETE_ARRAY(pBuffer);
CC_SAFE_DELETE_ARRAY(pTempData); CC_SAFE_DELETE_ARRAY(pTempData);
return pImage; return image;
} }
NS_CC_END NS_CC_END

View File

@ -28,6 +28,7 @@ THE SOFTWARE.
#include "base_nodes/CCNode.h" #include "base_nodes/CCNode.h"
#include "sprite_nodes/CCSprite.h" #include "sprite_nodes/CCSprite.h"
#include "kazmath/mat4.h" #include "kazmath/mat4.h"
#include "platform/CCImage.h"
NS_CC_BEGIN NS_CC_BEGIN
@ -36,11 +37,6 @@ NS_CC_BEGIN
* @{ * @{
*/ */
typedef enum eImageFormat
{
kImageFormatJPEG = 0,
kImageFormatPNG = 1,
} tImageFormat;
/** /**
@brief RenderTexture is a generic rendering target. To render things into it, @brief RenderTexture is a generic rendering target. To render things into it,
simply construct a render target, call begin on it, call visit on any cocos simply construct a render target, call begin on it, call visit on any cocos
@ -55,10 +51,10 @@ class CC_DLL RenderTexture : public Node
{ {
public: public:
/** initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats are valid ) and depthStencil format*/ /** initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats are valid ) and depthStencil format*/
static RenderTexture * create(int w ,int h, Texture2DPixelFormat eFormat, GLuint uDepthStencilFormat); static RenderTexture * create(int w ,int h, Texture2D::PixelFormat eFormat, GLuint uDepthStencilFormat);
/** creates a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid */ /** creates a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid */
static RenderTexture * create(int w, int h, Texture2DPixelFormat eFormat); static RenderTexture * create(int w, int h, Texture2D::PixelFormat eFormat);
/** creates a RenderTexture object with width and height in Points, pixel format is RGBA8888 */ /** creates a RenderTexture object with width and height in Points, pixel format is RGBA8888 */
static RenderTexture * create(int w, int h); static RenderTexture * create(int w, int h);
@ -67,10 +63,10 @@ public:
virtual ~RenderTexture(); virtual ~RenderTexture();
/** initializes a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid */ /** initializes a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid */
bool initWithWidthAndHeight(int w, int h, Texture2DPixelFormat eFormat); bool initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat eFormat);
/** initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats are valid ) and depthStencil format*/ /** initializes a RenderTexture object with width and height in Points and a pixel format( only RGB and RGBA formats are valid ) and depthStencil format*/
bool initWithWidthAndHeight(int w, int h, Texture2DPixelFormat eFormat, GLuint uDepthStencilFormat); bool initWithWidthAndHeight(int w, int h, Texture2D::PixelFormat eFormat, GLuint uDepthStencilFormat);
/** starts grabbing */ /** starts grabbing */
void begin(); void begin();
@ -104,7 +100,10 @@ public:
/* creates a new Image from with the texture's data. /* creates a new Image from with the texture's data.
Caller is responsible for releasing it by calling delete. Caller is responsible for releasing it by calling delete.
*/ */
Image* newImage(bool flipImage = true); Image* newImage(bool flipImage = true);
CC_DEPRECATED_ATTRIBUTE Image* newCCImage(bool flipImage = true) { return newImage(flipImage); };
/** saves the texture into a file using JPEG format. The file will be saved in the Documents folder. /** saves the texture into a file using JPEG format. The file will be saved in the Documents folder.
Returns YES if the operation is successful. Returns YES if the operation is successful.
@ -114,7 +113,7 @@ public:
/** saves the texture into a file. The format could be JPG or PNG. The file will be saved in the Documents folder. /** saves the texture into a file. The format could be JPG or PNG. The file will be saved in the Documents folder.
Returns YES if the operation is successful. Returns YES if the operation is successful.
*/ */
bool saveToFile(const char *name, tImageFormat format); bool saveToFile(const char *name, Image::Format format);
/** Listen "come to background" message, and save render texture. /** Listen "come to background" message, and save render texture.
It only has effect on Android. It only has effect on Android.
@ -140,7 +139,7 @@ public:
/** Value for clear Stencil. Valid only when autoDraw is true */ /** Value for clear Stencil. Valid only when autoDraw is true */
inline int getClearStencil() const { return _clearStencil; }; inline int getClearStencil() const { return _clearStencil; };
inline void setClearStencil(float clearStencil) { _clearStencil = clearStencil; }; inline void setClearStencil(int clearStencil) { _clearStencil = clearStencil; };
/** When enabled, it will render its children into the texture automatically. Disabled by default for compatiblity reasons. /** When enabled, it will render its children into the texture automatically. Disabled by default for compatiblity reasons.
Will be enabled in the future. Will be enabled in the future.
@ -172,7 +171,7 @@ protected:
Texture2D* _texture; Texture2D* _texture;
Texture2D* _textureCopy; // a copy of _texture Texture2D* _textureCopy; // a copy of _texture
Image* _UITextureImage; Image* _UITextureImage;
GLenum _pixelFormat; Texture2D::PixelFormat _pixelFormat;
// code for "auto" update // code for "auto" update
GLbitfield _clearFlags; GLbitfield _clearFlags;

View File

@ -99,10 +99,9 @@ bool ParticleBatchNode::initWithTexture(Texture2D *tex, unsigned int capacity)
_children = new Array(); _children = new Array();
_children->initWithCapacity(capacity); _children->initWithCapacity(capacity);
_blendFunc.src = CC_BLEND_SRC; _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
_blendFunc.dst = CC_BLEND_DST;
setShaderProgram(ShaderCache::getInstance()->programForKey(kShader_PositionTextureColor)); setShaderProgram(ShaderCache::getInstance()->programForKey(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
return true; return true;
} }
@ -165,22 +164,22 @@ void ParticleBatchNode::addChild(Node * child, int zOrder)
Node::addChild(child, zOrder); Node::addChild(child, zOrder);
} }
void ParticleBatchNode::addChild(Node * child, int zOrder, int tag) void ParticleBatchNode::addChild(Node * aChild, int zOrder, int tag)
{ {
CCASSERT( child != NULL, "Argument must be non-NULL"); CCASSERT( aChild != NULL, "Argument must be non-NULL");
CCASSERT( dynamic_cast<ParticleSystem*>(child) != NULL, "CCParticleBatchNode only supports QuadParticleSystems as children"); CCASSERT( dynamic_cast<ParticleSystem*>(aChild) != NULL, "CCParticleBatchNode only supports QuadParticleSystems as children");
ParticleSystem* pChild = (ParticleSystem*)child; ParticleSystem* child = static_cast<ParticleSystem*>(aChild);
CCASSERT( pChild->getTexture()->getName() == _textureAtlas->getTexture()->getName(), "CCParticleSystem is not using the same texture id"); CCASSERT( child->getTexture()->getName() == _textureAtlas->getTexture()->getName(), "CCParticleSystem is not using the same texture id");
// If this is the 1st children, then copy blending function // If this is the 1st children, then copy blending function
if( _children->count() == 0 ) if( _children->count() == 0 )
{ {
setBlendFunc(pChild->getBlendFunc()); setBlendFunc(child->getBlendFunc());
} }
CCASSERT( _blendFunc.src == pChild->getBlendFunc().src && _blendFunc.dst == pChild->getBlendFunc().dst, "Can't add a PaticleSystem that uses a different blending function"); CCASSERT( _blendFunc.src == child->getBlendFunc().src && _blendFunc.dst == child->getBlendFunc().dst, "Can't add a PaticleSystem that uses a different blending function");
//no lazy sorting, so don't call super addChild, call helper instead //no lazy sorting, so don't call super addChild, call helper instead
unsigned int pos = addChildHelper(pChild,zOrder,tag); unsigned int pos = addChildHelper(child,zOrder,tag);
//get new atlasIndex //get new atlasIndex
int atlasIndex = 0; int atlasIndex = 0;
@ -196,10 +195,10 @@ void ParticleBatchNode::addChild(Node * child, int zOrder, int tag)
atlasIndex = 0; atlasIndex = 0;
} }
insertChild(pChild, atlasIndex); insertChild(child, atlasIndex);
// update quad info // update quad info
pChild->setBatchNode(this); child->setBatchNode(this);
} }
// don't use lazy sorting, reordering the particle systems quads afterwards would be too complex // don't use lazy sorting, reordering the particle systems quads afterwards would be too complex
@ -236,13 +235,13 @@ unsigned int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int
} }
// Reorder will be done in this function, no "lazy" reorder to particles // Reorder will be done in this function, no "lazy" reorder to particles
void ParticleBatchNode::reorderChild(Node * child, int zOrder) void ParticleBatchNode::reorderChild(Node * aChild, int zOrder)
{ {
CCASSERT( child != NULL, "Child must be non-NULL"); CCASSERT( aChild != NULL, "Child must be non-NULL");
CCASSERT( dynamic_cast<ParticleSystem*>(child) != NULL, "CCParticleBatchNode only supports QuadParticleSystems as children"); CCASSERT( dynamic_cast<ParticleSystem*>(aChild) != NULL, "CCParticleBatchNode only supports QuadParticleSystems as children");
CCASSERT( _children->containsObject(child), "Child doesn't belong to batch" ); CCASSERT( _children->containsObject(aChild), "Child doesn't belong to batch" );
ParticleSystem* pChild = (ParticleSystem*)(child); ParticleSystem* child = static_cast<ParticleSystem*>(aChild);
if( zOrder == child->getZOrder() ) if( zOrder == child->getZOrder() )
{ {
@ -254,19 +253,19 @@ void ParticleBatchNode::reorderChild(Node * child, int zOrder)
{ {
unsigned int newIndex = 0, oldIndex = 0; unsigned int newIndex = 0, oldIndex = 0;
getCurrentIndex(&oldIndex, &newIndex, pChild, zOrder); getCurrentIndex(&oldIndex, &newIndex, child, zOrder);
if( oldIndex != newIndex ) if( oldIndex != newIndex )
{ {
// reorder _children->array // reorder _children->array
pChild->retain(); child->retain();
_children->removeObjectAtIndex(oldIndex); _children->removeObjectAtIndex(oldIndex);
_children->insertObject(pChild, newIndex); _children->insertObject(child, newIndex);
pChild->release(); child->release();
// save old altasIndex // save old altasIndex
int oldAtlasIndex = pChild->getAtlasIndex(); int oldAtlasIndex = child->getAtlasIndex();
// update atlas index // update atlas index
updateAllAtlasIndexes(); updateAllAtlasIndexes();
@ -276,21 +275,21 @@ void ParticleBatchNode::reorderChild(Node * child, int zOrder)
for( unsigned int i=0;i < _children->count();i++) for( unsigned int i=0;i < _children->count();i++)
{ {
ParticleSystem* pNode = (ParticleSystem*)_children->objectAtIndex(i); ParticleSystem* pNode = (ParticleSystem*)_children->objectAtIndex(i);
if( pNode == pChild ) if( pNode == child )
{ {
newAtlasIndex = pChild->getAtlasIndex(); newAtlasIndex = child->getAtlasIndex();
break; break;
} }
} }
// reorder textureAtlas quads // reorder textureAtlas quads
_textureAtlas->moveQuadsFromIndex(oldAtlasIndex, pChild->getTotalParticles(), newAtlasIndex); _textureAtlas->moveQuadsFromIndex(oldAtlasIndex, child->getTotalParticles(), newAtlasIndex);
pChild->updateWithNoTime(); child->updateWithNoTime();
} }
} }
pChild->_setZOrder(zOrder); child->_setZOrder(zOrder);
} }
void ParticleBatchNode::getCurrentIndex(unsigned int* oldIndex, unsigned int* newIndex, Node* child, int z) void ParticleBatchNode::getCurrentIndex(unsigned int* oldIndex, unsigned int* newIndex, Node* child, int z)
@ -360,28 +359,26 @@ unsigned int ParticleBatchNode::searchNewPositionInChildrenForZ(int z)
} }
// override removeChild: // override removeChild:
void ParticleBatchNode::removeChild(Node* child, bool cleanup) void ParticleBatchNode::removeChild(Node* aChild, bool cleanup)
{ {
// explicit nil handling // explicit nil handling
if (child == NULL) if (aChild == NULL)
{
return; return;
}
CCASSERT( dynamic_cast<ParticleSystem*>(child) != NULL, "CCParticleBatchNode only supports QuadParticleSystems as children"); CCASSERT( dynamic_cast<ParticleSystem*>(aChild) != NULL, "CCParticleBatchNode only supports QuadParticleSystems as children");
CCASSERT(_children->containsObject(child), "CCParticleBatchNode doesn't contain the sprite. Can't remove it"); CCASSERT(_children->containsObject(aChild), "CCParticleBatchNode doesn't contain the sprite. Can't remove it");
ParticleSystem* pChild = (ParticleSystem*)child; ParticleSystem* child = static_cast<ParticleSystem*>(aChild);
Node::removeChild(pChild, cleanup); Node::removeChild(child, cleanup);
// remove child helper // remove child helper
_textureAtlas->removeQuadsAtIndex(pChild->getAtlasIndex(), pChild->getTotalParticles()); _textureAtlas->removeQuadsAtIndex(child->getAtlasIndex(), child->getTotalParticles());
// after memmove of data, empty the quads at the end of array // after memmove of data, empty the quads at the end of array
_textureAtlas->fillWithEmptyQuadsFromIndex(_textureAtlas->getTotalQuads(), pChild->getTotalParticles()); _textureAtlas->fillWithEmptyQuadsFromIndex(_textureAtlas->getTotalQuads(), child->getTotalParticles());
// particle could be reused for self rendering // particle could be reused for self rendering
pChild->setBatchNode(NULL); child->setBatchNode(NULL);
updateAllAtlasIndexes(); updateAllAtlasIndexes();
} }
@ -411,7 +408,7 @@ void ParticleBatchNode::draw(void)
CC_NODE_DRAW_SETUP(); CC_NODE_DRAW_SETUP();
ccGLBlendFunc( _blendFunc.src, _blendFunc.dst ); GL::blendFunc( _blendFunc.src, _blendFunc.dst );
_textureAtlas->drawQuads(); _textureAtlas->drawQuads();
@ -443,26 +440,26 @@ void ParticleBatchNode::disableParticle(unsigned int particleIndex)
// ParticleBatchNode - add / remove / reorder helper methods // ParticleBatchNode - add / remove / reorder helper methods
// add child helper // add child helper
void ParticleBatchNode::insertChild(ParticleSystem* pSystem, int index) void ParticleBatchNode::insertChild(ParticleSystem* system, int index)
{ {
pSystem->setAtlasIndex(index); system->setAtlasIndex(index);
if(_textureAtlas->getTotalQuads() + pSystem->getTotalParticles() > _textureAtlas->getCapacity()) if(_textureAtlas->getTotalQuads() + system->getTotalParticles() > _textureAtlas->getCapacity())
{ {
increaseAtlasCapacityTo(_textureAtlas->getTotalQuads() + pSystem->getTotalParticles()); increaseAtlasCapacityTo(_textureAtlas->getTotalQuads() + system->getTotalParticles());
// after a realloc empty quads of textureAtlas can be filled with gibberish (realloc doesn't perform calloc), insert empty quads to prevent it // after a realloc empty quads of textureAtlas can be filled with gibberish (realloc doesn't perform calloc), insert empty quads to prevent it
_textureAtlas->fillWithEmptyQuadsFromIndex(_textureAtlas->getCapacity() - pSystem->getTotalParticles(), pSystem->getTotalParticles()); _textureAtlas->fillWithEmptyQuadsFromIndex(_textureAtlas->getCapacity() - system->getTotalParticles(), system->getTotalParticles());
} }
// make room for quads, not necessary for last child // make room for quads, not necessary for last child
if (pSystem->getAtlasIndex() + pSystem->getTotalParticles() != _textureAtlas->getTotalQuads()) if (system->getAtlasIndex() + system->getTotalParticles() != _textureAtlas->getTotalQuads())
{ {
_textureAtlas->moveQuadsFromIndex(index, index+pSystem->getTotalParticles()); _textureAtlas->moveQuadsFromIndex(index, index+system->getTotalParticles());
} }
// increase totalParticles here for new particles, update method of particle-system will fill the quads // increase totalParticles here for new particles, update method of particle-system will fill the quads
_textureAtlas->increaseTotalQuadsWith(pSystem->getTotalParticles()); _textureAtlas->increaseTotalQuadsWith(system->getTotalParticles());
updateAllAtlasIndexes(); updateAllAtlasIndexes();
} }
@ -485,10 +482,8 @@ void ParticleBatchNode::updateAllAtlasIndexes()
void ParticleBatchNode::updateBlendFunc(void) void ParticleBatchNode::updateBlendFunc(void)
{ {
if( ! _textureAtlas->getTexture()->hasPremultipliedAlpha()) { if( ! _textureAtlas->getTexture()->hasPremultipliedAlpha())
_blendFunc.src = GL_SRC_ALPHA; _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED;
_blendFunc.dst = GL_ONE_MINUS_SRC_ALPHA;
}
} }
void ParticleBatchNode::setTexture(Texture2D* texture) void ParticleBatchNode::setTexture(Texture2D* texture)
@ -498,8 +493,7 @@ void ParticleBatchNode::setTexture(Texture2D* texture)
// If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it // If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it
if( texture && ! texture->hasPremultipliedAlpha() && ( _blendFunc.src == CC_BLEND_SRC && _blendFunc.dst == CC_BLEND_DST ) ) if( texture && ! texture->hasPremultipliedAlpha() && ( _blendFunc.src == CC_BLEND_SRC && _blendFunc.dst == CC_BLEND_DST ) )
{ {
_blendFunc.src = GL_SRC_ALPHA; _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED;
_blendFunc.dst = GL_ONE_MINUS_SRC_ALPHA;
} }
} }

View File

@ -83,7 +83,7 @@ public:
bool initWithFile(const char* fileImage, unsigned int capacity); bool initWithFile(const char* fileImage, unsigned int capacity);
/** Inserts a child into the ParticleBatchNode */ /** Inserts a child into the ParticleBatchNode */
void insertChild(ParticleSystem* pSystem, int index); void insertChild(ParticleSystem* system, int index);
void removeChildAtIndex(unsigned int index, bool doCleanup); void removeChildAtIndex(unsigned int index, bool doCleanup);
void removeAllChildrenWithCleanup(bool doCleanup); void removeAllChildrenWithCleanup(bool doCleanup);

View File

@ -36,26 +36,26 @@ NS_CC_BEGIN
static Texture2D* getDefaultTexture() static Texture2D* getDefaultTexture()
{ {
Texture2D* pTexture = NULL; Texture2D* texture = NULL;
Image* pImage = NULL; Image* pImage = NULL;
do do
{ {
bool bRet = false; bool bRet = false;
const char* key = "__firePngData"; const char* key = "__firePngData";
pTexture = TextureCache::getInstance()->textureForKey(key); texture = TextureCache::getInstance()->textureForKey(key);
CC_BREAK_IF(pTexture != NULL); CC_BREAK_IF(texture != NULL);
pImage = new Image(); pImage = new Image();
CC_BREAK_IF(NULL == pImage); CC_BREAK_IF(NULL == pImage);
bRet = pImage->initWithImageData((void*)__firePngData, sizeof(__firePngData), Image::kFmtPng); bRet = pImage->initWithImageData((void*)__firePngData, sizeof(__firePngData), Image::Format::PNG);
CC_BREAK_IF(!bRet); CC_BREAK_IF(!bRet);
pTexture = TextureCache::getInstance()->addUIImage(pImage, key); texture = TextureCache::getInstance()->addUIImage(pImage, key);
} while (0); } while (0);
CC_SAFE_RELEASE(pImage); CC_SAFE_RELEASE(pImage);
return pTexture; return texture;
} }
ParticleFire* ParticleFire::create() ParticleFire* ParticleFire::create()
@ -91,10 +91,10 @@ bool ParticleFire::initWithTotalParticles(unsigned int numberOfParticles)
if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) )
{ {
// duration // duration
_duration = kParticleDurationInfinity; _duration = DURATION_INFINITY;
// Gravity Mode // Gravity Mode
this->_emitterMode = kParticleModeGravity; this->_emitterMode = Mode::GRAVITY;
// Gravity Mode: gravity // Gravity Mode: gravity
this->modeA.gravity = Point(0,0); this->modeA.gravity = Point(0,0);
@ -124,7 +124,7 @@ bool ParticleFire::initWithTotalParticles(unsigned int numberOfParticles)
// size, in pixels // size, in pixels
_startSize = 54.0f; _startSize = 54.0f;
_startSizeVar = 10.0f; _startSizeVar = 10.0f;
_endSize = kParticleStartSizeEqualToEndSize; _endSize = START_SIZE_EQUAL_TO_END_SIZE;
// emits per frame // emits per frame
_emissionRate = _totalParticles/_life; _emissionRate = _totalParticles/_life;
@ -147,10 +147,10 @@ bool ParticleFire::initWithTotalParticles(unsigned int numberOfParticles)
_endColorVar.b = 0.0f; _endColorVar.b = 0.0f;
_endColorVar.a = 0.0f; _endColorVar.a = 0.0f;
Texture2D* pTexture = getDefaultTexture(); Texture2D* texture = getDefaultTexture();
if (pTexture != NULL) if (texture != NULL)
{ {
setTexture(pTexture); setTexture(texture);
} }
// additive // additive
@ -196,10 +196,10 @@ bool ParticleFireworks::initWithTotalParticles(unsigned int numberOfParticles)
if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) )
{ {
// duration // duration
_duration= kParticleDurationInfinity; _duration= DURATION_INFINITY;
// Gravity Mode // Gravity Mode
this->_emitterMode = kParticleModeGravity; this->_emitterMode = Mode::GRAVITY;
// Gravity Mode: gravity // Gravity Mode: gravity
this->modeA.gravity = Point(0,-90); this->modeA.gravity = Point(0,-90);
@ -248,12 +248,12 @@ bool ParticleFireworks::initWithTotalParticles(unsigned int numberOfParticles)
// size, in pixels // size, in pixels
_startSize = 8.0f; _startSize = 8.0f;
_startSizeVar = 2.0f; _startSizeVar = 2.0f;
_endSize = kParticleStartSizeEqualToEndSize; _endSize = START_SIZE_EQUAL_TO_END_SIZE;
Texture2D* pTexture = getDefaultTexture(); Texture2D* texture = getDefaultTexture();
if (pTexture != NULL) if (texture != NULL)
{ {
setTexture(pTexture); setTexture(texture);
} }
// additive // additive
this->setBlendAdditive(false); this->setBlendAdditive(false);
@ -300,10 +300,10 @@ bool ParticleSun::initWithTotalParticles(unsigned int numberOfParticles)
this->setBlendAdditive(true); this->setBlendAdditive(true);
// duration // duration
_duration = kParticleDurationInfinity; _duration = DURATION_INFINITY;
// Gravity Mode // Gravity Mode
setEmitterMode(kParticleModeGravity); setEmitterMode(Mode::GRAVITY);
// Gravity Mode: gravity // Gravity Mode: gravity
setGravity(Point(0,0)); setGravity(Point(0,0));
@ -333,7 +333,7 @@ bool ParticleSun::initWithTotalParticles(unsigned int numberOfParticles)
// size, in pixels // size, in pixels
_startSize = 30.0f; _startSize = 30.0f;
_startSizeVar = 10.0f; _startSizeVar = 10.0f;
_endSize = kParticleStartSizeEqualToEndSize; _endSize = START_SIZE_EQUAL_TO_END_SIZE;
// emits per seconds // emits per seconds
_emissionRate = _totalParticles/_life; _emissionRate = _totalParticles/_life;
@ -356,10 +356,10 @@ bool ParticleSun::initWithTotalParticles(unsigned int numberOfParticles)
_endColorVar.b = 0.0f; _endColorVar.b = 0.0f;
_endColorVar.a = 0.0f; _endColorVar.a = 0.0f;
Texture2D* pTexture = getDefaultTexture(); Texture2D* texture = getDefaultTexture();
if (pTexture != NULL) if (texture != NULL)
{ {
setTexture(pTexture); setTexture(texture);
} }
return true; return true;
@ -404,10 +404,10 @@ bool ParticleGalaxy::initWithTotalParticles(unsigned int numberOfParticles)
if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) )
{ {
// duration // duration
_duration = kParticleDurationInfinity; _duration = DURATION_INFINITY;
// Gravity Mode // Gravity Mode
setEmitterMode(kParticleModeGravity); setEmitterMode(Mode::GRAVITY);
// Gravity Mode: gravity // Gravity Mode: gravity
setGravity(Point(0,0)); setGravity(Point(0,0));
@ -440,7 +440,7 @@ bool ParticleGalaxy::initWithTotalParticles(unsigned int numberOfParticles)
// size, in pixels // size, in pixels
_startSize = 37.0f; _startSize = 37.0f;
_startSizeVar = 10.0f; _startSizeVar = 10.0f;
_endSize = kParticleStartSizeEqualToEndSize; _endSize = START_SIZE_EQUAL_TO_END_SIZE;
// emits per second // emits per second
_emissionRate = _totalParticles/_life; _emissionRate = _totalParticles/_life;
@ -463,10 +463,10 @@ bool ParticleGalaxy::initWithTotalParticles(unsigned int numberOfParticles)
_endColorVar.b = 0.0f; _endColorVar.b = 0.0f;
_endColorVar.a = 0.0f; _endColorVar.a = 0.0f;
Texture2D* pTexture = getDefaultTexture(); Texture2D* texture = getDefaultTexture();
if (pTexture != NULL) if (texture != NULL)
{ {
setTexture(pTexture); setTexture(texture);
} }
// additive // additive
@ -513,10 +513,10 @@ bool ParticleFlower::initWithTotalParticles(unsigned int numberOfParticles)
if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) )
{ {
// duration // duration
_duration = kParticleDurationInfinity; _duration = DURATION_INFINITY;
// Gravity Mode // Gravity Mode
setEmitterMode(kParticleModeGravity); setEmitterMode(Mode::GRAVITY);
// Gravity Mode: gravity // Gravity Mode: gravity
setGravity(Point(0,0)); setGravity(Point(0,0));
@ -549,7 +549,7 @@ bool ParticleFlower::initWithTotalParticles(unsigned int numberOfParticles)
// size, in pixels // size, in pixels
_startSize = 30.0f; _startSize = 30.0f;
_startSizeVar = 10.0f; _startSizeVar = 10.0f;
_endSize = kParticleStartSizeEqualToEndSize; _endSize = START_SIZE_EQUAL_TO_END_SIZE;
// emits per second // emits per second
_emissionRate = _totalParticles/_life; _emissionRate = _totalParticles/_life;
@ -572,10 +572,10 @@ bool ParticleFlower::initWithTotalParticles(unsigned int numberOfParticles)
_endColorVar.b = 0.0f; _endColorVar.b = 0.0f;
_endColorVar.a = 0.0f; _endColorVar.a = 0.0f;
Texture2D* pTexture = getDefaultTexture(); Texture2D* texture = getDefaultTexture();
if (pTexture != NULL) if (texture != NULL)
{ {
setTexture(pTexture); setTexture(texture);
} }
// additive // additive
@ -621,10 +621,10 @@ bool ParticleMeteor::initWithTotalParticles(unsigned int numberOfParticles)
if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) )
{ {
// duration // duration
_duration = kParticleDurationInfinity; _duration = DURATION_INFINITY;
// Gravity Mode // Gravity Mode
setEmitterMode(kParticleModeGravity); setEmitterMode(Mode::GRAVITY);
// Gravity Mode: gravity // Gravity Mode: gravity
setGravity(Point(-200,200)); setGravity(Point(-200,200));
@ -657,7 +657,7 @@ bool ParticleMeteor::initWithTotalParticles(unsigned int numberOfParticles)
// size, in pixels // size, in pixels
_startSize = 60.0f; _startSize = 60.0f;
_startSizeVar = 10.0f; _startSizeVar = 10.0f;
_endSize = kParticleStartSizeEqualToEndSize; _endSize = START_SIZE_EQUAL_TO_END_SIZE;
// emits per second // emits per second
_emissionRate = _totalParticles/_life; _emissionRate = _totalParticles/_life;
@ -680,10 +680,10 @@ bool ParticleMeteor::initWithTotalParticles(unsigned int numberOfParticles)
_endColorVar.b = 0.0f; _endColorVar.b = 0.0f;
_endColorVar.a = 0.0f; _endColorVar.a = 0.0f;
Texture2D* pTexture = getDefaultTexture(); Texture2D* texture = getDefaultTexture();
if (pTexture != NULL) if (texture != NULL)
{ {
setTexture(pTexture); setTexture(texture);
} }
// additive // additive
@ -730,10 +730,10 @@ bool ParticleSpiral::initWithTotalParticles(unsigned int numberOfParticles)
if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) )
{ {
// duration // duration
_duration = kParticleDurationInfinity; _duration = DURATION_INFINITY;
// Gravity Mode // Gravity Mode
setEmitterMode(kParticleModeGravity); setEmitterMode(Mode::GRAVITY);
// Gravity Mode: gravity // Gravity Mode: gravity
setGravity(Point(0,0)); setGravity(Point(0,0));
@ -766,7 +766,7 @@ bool ParticleSpiral::initWithTotalParticles(unsigned int numberOfParticles)
// size, in pixels // size, in pixels
_startSize = 20.0f; _startSize = 20.0f;
_startSizeVar = 0.0f; _startSizeVar = 0.0f;
_endSize = kParticleStartSizeEqualToEndSize; _endSize = START_SIZE_EQUAL_TO_END_SIZE;
// emits per second // emits per second
_emissionRate = _totalParticles/_life; _emissionRate = _totalParticles/_life;
@ -789,10 +789,10 @@ bool ParticleSpiral::initWithTotalParticles(unsigned int numberOfParticles)
_endColorVar.b = 0.5f; _endColorVar.b = 0.5f;
_endColorVar.a = 0.0f; _endColorVar.a = 0.0f;
Texture2D* pTexture = getDefaultTexture(); Texture2D* texture = getDefaultTexture();
if (pTexture != NULL) if (texture != NULL)
{ {
setTexture(pTexture); setTexture(texture);
} }
// additive // additive
@ -841,7 +841,7 @@ bool ParticleExplosion::initWithTotalParticles(unsigned int numberOfParticles)
// duration // duration
_duration = 0.1f; _duration = 0.1f;
setEmitterMode(kParticleModeGravity); setEmitterMode(Mode::GRAVITY);
// Gravity Mode: gravity // Gravity Mode: gravity
setGravity(Point(0,0)); setGravity(Point(0,0));
@ -874,7 +874,7 @@ bool ParticleExplosion::initWithTotalParticles(unsigned int numberOfParticles)
// size, in pixels // size, in pixels
_startSize = 15.0f; _startSize = 15.0f;
_startSizeVar = 10.0f; _startSizeVar = 10.0f;
_endSize = kParticleStartSizeEqualToEndSize; _endSize = START_SIZE_EQUAL_TO_END_SIZE;
// emits per second // emits per second
_emissionRate = _totalParticles/_duration; _emissionRate = _totalParticles/_duration;
@ -897,10 +897,10 @@ bool ParticleExplosion::initWithTotalParticles(unsigned int numberOfParticles)
_endColorVar.b = 0.5f; _endColorVar.b = 0.5f;
_endColorVar.a = 0.0f; _endColorVar.a = 0.0f;
Texture2D* pTexture = getDefaultTexture(); Texture2D* texture = getDefaultTexture();
if (pTexture != NULL) if (texture != NULL)
{ {
setTexture(pTexture); setTexture(texture);
} }
// additive // additive
@ -947,10 +947,10 @@ bool ParticleSmoke::initWithTotalParticles(unsigned int numberOfParticles)
if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) )
{ {
// duration // duration
_duration = kParticleDurationInfinity; _duration = DURATION_INFINITY;
// Emitter mode: Gravity Mode // Emitter mode: Gravity Mode
setEmitterMode(kParticleModeGravity); setEmitterMode(Mode::GRAVITY);
// Gravity Mode: gravity // Gravity Mode: gravity
setGravity(Point(0,0)); setGravity(Point(0,0));
@ -979,7 +979,7 @@ bool ParticleSmoke::initWithTotalParticles(unsigned int numberOfParticles)
// size, in pixels // size, in pixels
_startSize = 60.0f; _startSize = 60.0f;
_startSizeVar = 10.0f; _startSizeVar = 10.0f;
_endSize = kParticleStartSizeEqualToEndSize; _endSize = START_SIZE_EQUAL_TO_END_SIZE;
// emits per frame // emits per frame
_emissionRate = _totalParticles/_life; _emissionRate = _totalParticles/_life;
@ -1002,10 +1002,10 @@ bool ParticleSmoke::initWithTotalParticles(unsigned int numberOfParticles)
_endColorVar.b = 0.0f; _endColorVar.b = 0.0f;
_endColorVar.a = 0.0f; _endColorVar.a = 0.0f;
Texture2D* pTexture = getDefaultTexture(); Texture2D* texture = getDefaultTexture();
if (pTexture != NULL) if (texture != NULL)
{ {
setTexture(pTexture); setTexture(texture);
} }
// additive // additive
@ -1052,10 +1052,10 @@ bool ParticleSnow::initWithTotalParticles(unsigned int numberOfParticles)
if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) )
{ {
// duration // duration
_duration = kParticleDurationInfinity; _duration = DURATION_INFINITY;
// set gravity mode. // set gravity mode.
setEmitterMode(kParticleModeGravity); setEmitterMode(Mode::GRAVITY);
// Gravity Mode: gravity // Gravity Mode: gravity
setGravity(Point(0,-1)); setGravity(Point(0,-1));
@ -1088,7 +1088,7 @@ bool ParticleSnow::initWithTotalParticles(unsigned int numberOfParticles)
// size, in pixels // size, in pixels
_startSize = 10.0f; _startSize = 10.0f;
_startSizeVar = 5.0f; _startSizeVar = 5.0f;
_endSize = kParticleStartSizeEqualToEndSize; _endSize = START_SIZE_EQUAL_TO_END_SIZE;
// emits per second // emits per second
_emissionRate = 10; _emissionRate = 10;
@ -1111,10 +1111,10 @@ bool ParticleSnow::initWithTotalParticles(unsigned int numberOfParticles)
_endColorVar.b = 0.0f; _endColorVar.b = 0.0f;
_endColorVar.a = 0.0f; _endColorVar.a = 0.0f;
Texture2D* pTexture = getDefaultTexture(); Texture2D* texture = getDefaultTexture();
if (pTexture != NULL) if (texture != NULL)
{ {
setTexture(pTexture); setTexture(texture);
} }
// additive // additive
@ -1160,9 +1160,9 @@ bool ParticleRain::initWithTotalParticles(unsigned int numberOfParticles)
if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) ) if( ParticleSystemQuad::initWithTotalParticles(numberOfParticles) )
{ {
// duration // duration
_duration = kParticleDurationInfinity; _duration = DURATION_INFINITY;
setEmitterMode(kParticleModeGravity); setEmitterMode(Mode::GRAVITY);
// Gravity Mode: gravity // Gravity Mode: gravity
setGravity(Point(10,-10)); setGravity(Point(10,-10));
@ -1196,7 +1196,7 @@ bool ParticleRain::initWithTotalParticles(unsigned int numberOfParticles)
// size, in pixels // size, in pixels
_startSize = 4.0f; _startSize = 4.0f;
_startSizeVar = 2.0f; _startSizeVar = 2.0f;
_endSize = kParticleStartSizeEqualToEndSize; _endSize = START_SIZE_EQUAL_TO_END_SIZE;
// emits per second // emits per second
_emissionRate = 20; _emissionRate = 20;
@ -1219,10 +1219,10 @@ bool ParticleRain::initWithTotalParticles(unsigned int numberOfParticles)
_endColorVar.b = 0.0f; _endColorVar.b = 0.0f;
_endColorVar.a = 0.0f; _endColorVar.a = 0.0f;
Texture2D* pTexture = getDefaultTexture(); Texture2D* texture = getDefaultTexture();
if (pTexture != NULL) if (texture != NULL)
{ {
setTexture(pTexture); setTexture(texture);
} }
// additive // additive

View File

@ -42,6 +42,9 @@ THE SOFTWARE.
// //
#include "CCParticleSystem.h" #include "CCParticleSystem.h"
#include <string>
#include "CCParticleBatchNode.h" #include "CCParticleBatchNode.h"
#include "ccTypes.h" #include "ccTypes.h"
#include "textures/CCTextureCache.h" #include "textures/CCTextureCache.h"
@ -55,8 +58,6 @@ THE SOFTWARE.
// opengl // opengl
#include "CCGL.h" #include "CCGL.h"
#include <string>
using namespace std; using namespace std;
@ -111,9 +112,10 @@ ParticleSystem::ParticleSystem()
, _texture(NULL) , _texture(NULL)
, _opacityModifyRGB(false) , _opacityModifyRGB(false)
, _isBlendAdditive(false) , _isBlendAdditive(false)
, _positionType(kPositionTypeFree) , _positionType(PositionType::FREE)
, _isAutoRemoveOnFinish(false) , _isAutoRemoveOnFinish(false)
, _emitterMode(kParticleModeGravity) , _emitterMode(Mode::GRAVITY)
, _blendFunc(BlendFunc::ALPHA_PREMULTIPLIED)
{ {
modeA.gravity = Point::ZERO; modeA.gravity = Point::ZERO;
modeA.speed = 0; modeA.speed = 0;
@ -129,8 +131,6 @@ ParticleSystem::ParticleSystem()
modeB.endRadiusVar = 0; modeB.endRadiusVar = 0;
modeB.rotatePerSecond = 0; modeB.rotatePerSecond = 0;
modeB.rotatePerSecondVar = 0; modeB.rotatePerSecondVar = 0;
_blendFunc.src = CC_BLEND_SRC;
_blendFunc.dst = CC_BLEND_DST;
} }
// implementation ParticleSystem // implementation ParticleSystem
@ -256,10 +256,10 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirn
_endSpin= dictionary->valueForKey("rotationEnd")->floatValue(); _endSpin= dictionary->valueForKey("rotationEnd")->floatValue();
_endSpinVar= dictionary->valueForKey("rotationEndVariance")->floatValue(); _endSpinVar= dictionary->valueForKey("rotationEndVariance")->floatValue();
_emitterMode = dictionary->valueForKey("emitterType")->intValue(); _emitterMode = (Mode) dictionary->valueForKey("emitterType")->intValue();
// Mode A: Gravity + tangential accel + radial accel // Mode A: Gravity + tangential accel + radial accel
if( _emitterMode == kParticleModeGravity ) if (_emitterMode == Mode::GRAVITY)
{ {
// gravity // gravity
modeA.gravity.x = dictionary->valueForKey("gravityx")->floatValue(); modeA.gravity.x = dictionary->valueForKey("gravityx")->floatValue();
@ -282,7 +282,7 @@ bool ParticleSystem::initWithDictionary(Dictionary *dictionary, const char *dirn
} }
// or Mode B: radius movement // or Mode B: radius movement
else if( _emitterMode == kParticleModeRadius ) else if (_emitterMode == Mode::RADIUS)
{ {
modeB.startRadius = dictionary->valueForKey("maxRadius")->floatValue(); modeB.startRadius = dictionary->valueForKey("maxRadius")->floatValue();
modeB.startRadiusVar = dictionary->valueForKey("maxRadiusVariance")->floatValue(); modeB.startRadiusVar = dictionary->valueForKey("maxRadiusVariance")->floatValue();
@ -414,14 +414,13 @@ bool ParticleSystem::initWithTotalParticles(unsigned int numberOfParticles)
_isActive = true; _isActive = true;
// default blend function // default blend function
_blendFunc.src = CC_BLEND_SRC; _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
_blendFunc.dst = CC_BLEND_DST;
// default movement type; // default movement type;
_positionType = kPositionTypeFree; _positionType = PositionType::FREE;
// by default be in mode A: // by default be in mode A:
_emitterMode = kParticleModeGravity; _emitterMode = Mode::GRAVITY;
// default: modulate // default: modulate
// XXX: not used // XXX: not used
@ -501,7 +500,7 @@ void ParticleSystem::initParticle(tParticle* particle)
particle->size = startS; particle->size = startS;
if( _endSize == kParticleStartSizeEqualToEndSize ) if (_endSize == START_SIZE_EQUAL_TO_END_SIZE)
{ {
particle->deltaSize = 0; particle->deltaSize = 0;
} }
@ -519,11 +518,11 @@ void ParticleSystem::initParticle(tParticle* particle)
particle->deltaRotation = (endA - startA) / particle->timeToLive; particle->deltaRotation = (endA - startA) / particle->timeToLive;
// position // position
if( _positionType == kPositionTypeFree ) if (_positionType == PositionType::FREE)
{ {
particle->startPos = this->convertToWorldSpace(Point::ZERO); particle->startPos = this->convertToWorldSpace(Point::ZERO);
} }
else if ( _positionType == kPositionTypeRelative ) else if (_positionType == PositionType::RELATIVE)
{ {
particle->startPos = _position; particle->startPos = _position;
} }
@ -532,7 +531,7 @@ void ParticleSystem::initParticle(tParticle* particle)
float a = CC_DEGREES_TO_RADIANS( _angle + _angleVar * CCRANDOM_MINUS1_1() ); float a = CC_DEGREES_TO_RADIANS( _angle + _angleVar * CCRANDOM_MINUS1_1() );
// Mode Gravity: A // Mode Gravity: A
if (_emitterMode == kParticleModeGravity) if (_emitterMode == Mode::GRAVITY)
{ {
Point v(cosf( a ), sinf( a )); Point v(cosf( a ), sinf( a ));
float s = modeA.speed + modeA.speedVar * CCRANDOM_MINUS1_1(); float s = modeA.speed + modeA.speedVar * CCRANDOM_MINUS1_1();
@ -561,7 +560,7 @@ void ParticleSystem::initParticle(tParticle* particle)
particle->modeB.radius = startRadius; particle->modeB.radius = startRadius;
if(modeB.endRadius == kParticleStartRadiusEqualToEndRadius) if (modeB.endRadius == START_RADIUS_EQUAL_TO_END_RADIUS)
{ {
particle->modeB.deltaRadius = 0; particle->modeB.deltaRadius = 0;
} }
@ -627,11 +626,11 @@ void ParticleSystem::update(float dt)
_particleIdx = 0; _particleIdx = 0;
Point currentPosition = Point::ZERO; Point currentPosition = Point::ZERO;
if (_positionType == kPositionTypeFree) if (_positionType == PositionType::FREE)
{ {
currentPosition = this->convertToWorldSpace(Point::ZERO); currentPosition = this->convertToWorldSpace(Point::ZERO);
} }
else if (_positionType == kPositionTypeRelative) else if (_positionType == PositionType::RELATIVE)
{ {
currentPosition = _position; currentPosition = _position;
} }
@ -648,7 +647,7 @@ void ParticleSystem::update(float dt)
if (p->timeToLive > 0) if (p->timeToLive > 0)
{ {
// Mode A: gravity, direction, tangential accel & radial accel // Mode A: gravity, direction, tangential accel & radial accel
if (_emitterMode == kParticleModeGravity) if (_emitterMode == Mode::GRAVITY)
{ {
Point tmp, radial, tangential; Point tmp, radial, tangential;
@ -705,7 +704,7 @@ void ParticleSystem::update(float dt)
Point newPos; Point newPos;
if (_positionType == kPositionTypeFree || _positionType == kPositionTypeRelative) if (_positionType == PositionType::FREE || _positionType == PositionType::RELATIVE)
{ {
Point diff = currentPosition - p->startPos; Point diff = currentPosition - p->startPos;
newPos = p->pos - diff; newPos = p->pos - diff;
@ -814,8 +813,7 @@ void ParticleSystem::updateBlendFunc()
} }
else else
{ {
_blendFunc.src = GL_SRC_ALPHA; _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED;
_blendFunc.dst = GL_ONE_MINUS_SRC_ALPHA;
} }
} }
} }
@ -831,21 +829,14 @@ void ParticleSystem::setBlendAdditive(bool additive)
{ {
if( additive ) if( additive )
{ {
_blendFunc.src = GL_SRC_ALPHA; _blendFunc = BlendFunc::ADDITIVE;
_blendFunc.dst = GL_ONE;
} }
else else
{ {
if( _texture && ! _texture->hasPremultipliedAlpha() ) if( _texture && ! _texture->hasPremultipliedAlpha() )
{ _blendFunc = BlendFunc::ALPHA_NON_PREMULTIPLIED;
_blendFunc.src = GL_SRC_ALPHA;
_blendFunc.dst = GL_ONE_MINUS_SRC_ALPHA;
}
else else
{ _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED;
_blendFunc.src = CC_BLEND_SRC;
_blendFunc.dst = CC_BLEND_DST;
}
} }
} }
@ -857,170 +848,170 @@ bool ParticleSystem::isBlendAdditive() const
// ParticleSystem - Properties of Gravity Mode // ParticleSystem - Properties of Gravity Mode
void ParticleSystem::setTangentialAccel(float t) void ParticleSystem::setTangentialAccel(float t)
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT( _emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
modeA.tangentialAccel = t; modeA.tangentialAccel = t;
} }
float ParticleSystem::getTangentialAccel() const float ParticleSystem::getTangentialAccel() const
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT( _emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
return modeA.tangentialAccel; return modeA.tangentialAccel;
} }
void ParticleSystem::setTangentialAccelVar(float t) void ParticleSystem::setTangentialAccelVar(float t)
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
modeA.tangentialAccelVar = t; modeA.tangentialAccelVar = t;
} }
float ParticleSystem::getTangentialAccelVar() const float ParticleSystem::getTangentialAccelVar() const
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
return modeA.tangentialAccelVar; return modeA.tangentialAccelVar;
} }
void ParticleSystem::setRadialAccel(float t) void ParticleSystem::setRadialAccel(float t)
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
modeA.radialAccel = t; modeA.radialAccel = t;
} }
float ParticleSystem::getRadialAccel() const float ParticleSystem::getRadialAccel() const
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
return modeA.radialAccel; return modeA.radialAccel;
} }
void ParticleSystem::setRadialAccelVar(float t) void ParticleSystem::setRadialAccelVar(float t)
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
modeA.radialAccelVar = t; modeA.radialAccelVar = t;
} }
float ParticleSystem::getRadialAccelVar() const float ParticleSystem::getRadialAccelVar() const
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
return modeA.radialAccelVar; return modeA.radialAccelVar;
} }
void ParticleSystem::setRotationIsDir(bool t) void ParticleSystem::setRotationIsDir(bool t)
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
modeA.rotationIsDir = t; modeA.rotationIsDir = t;
} }
bool ParticleSystem::getRotationIsDir() const bool ParticleSystem::getRotationIsDir() const
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
return modeA.rotationIsDir; return modeA.rotationIsDir;
} }
void ParticleSystem::setGravity(const Point& g) void ParticleSystem::setGravity(const Point& g)
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
modeA.gravity = g; modeA.gravity = g;
} }
const Point& ParticleSystem::getGravity() const Point& ParticleSystem::getGravity()
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
return modeA.gravity; return modeA.gravity;
} }
void ParticleSystem::setSpeed(float speed) void ParticleSystem::setSpeed(float speed)
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
modeA.speed = speed; modeA.speed = speed;
} }
float ParticleSystem::getSpeed() const float ParticleSystem::getSpeed() const
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
return modeA.speed; return modeA.speed;
} }
void ParticleSystem::setSpeedVar(float speedVar) void ParticleSystem::setSpeedVar(float speedVar)
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
modeA.speedVar = speedVar; modeA.speedVar = speedVar;
} }
float ParticleSystem::getSpeedVar() const float ParticleSystem::getSpeedVar() const
{ {
CCASSERT( _emitterMode == kParticleModeGravity, "Particle Mode should be Gravity"); CCASSERT(_emitterMode == Mode::GRAVITY, "Particle Mode should be Gravity");
return modeA.speedVar; return modeA.speedVar;
} }
// ParticleSystem - Properties of Radius Mode // ParticleSystem - Properties of Radius Mode
void ParticleSystem::setStartRadius(float startRadius) void ParticleSystem::setStartRadius(float startRadius)
{ {
CCASSERT( _emitterMode == kParticleModeRadius, "Particle Mode should be Radius"); CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
modeB.startRadius = startRadius; modeB.startRadius = startRadius;
} }
float ParticleSystem::getStartRadius() const float ParticleSystem::getStartRadius() const
{ {
CCASSERT( _emitterMode == kParticleModeRadius, "Particle Mode should be Radius"); CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
return modeB.startRadius; return modeB.startRadius;
} }
void ParticleSystem::setStartRadiusVar(float startRadiusVar) void ParticleSystem::setStartRadiusVar(float startRadiusVar)
{ {
CCASSERT( _emitterMode == kParticleModeRadius, "Particle Mode should be Radius"); CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
modeB.startRadiusVar = startRadiusVar; modeB.startRadiusVar = startRadiusVar;
} }
float ParticleSystem::getStartRadiusVar() const float ParticleSystem::getStartRadiusVar() const
{ {
CCASSERT( _emitterMode == kParticleModeRadius, "Particle Mode should be Radius"); CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
return modeB.startRadiusVar; return modeB.startRadiusVar;
} }
void ParticleSystem::setEndRadius(float endRadius) void ParticleSystem::setEndRadius(float endRadius)
{ {
CCASSERT( _emitterMode == kParticleModeRadius, "Particle Mode should be Radius"); CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
modeB.endRadius = endRadius; modeB.endRadius = endRadius;
} }
float ParticleSystem::getEndRadius() const float ParticleSystem::getEndRadius() const
{ {
CCASSERT( _emitterMode == kParticleModeRadius, "Particle Mode should be Radius"); CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
return modeB.endRadius; return modeB.endRadius;
} }
void ParticleSystem::setEndRadiusVar(float endRadiusVar) void ParticleSystem::setEndRadiusVar(float endRadiusVar)
{ {
CCASSERT( _emitterMode == kParticleModeRadius, "Particle Mode should be Radius"); CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
modeB.endRadiusVar = endRadiusVar; modeB.endRadiusVar = endRadiusVar;
} }
float ParticleSystem::getEndRadiusVar() const float ParticleSystem::getEndRadiusVar() const
{ {
CCASSERT( _emitterMode == kParticleModeRadius, "Particle Mode should be Radius"); CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
return modeB.endRadiusVar; return modeB.endRadiusVar;
} }
void ParticleSystem::setRotatePerSecond(float degrees) void ParticleSystem::setRotatePerSecond(float degrees)
{ {
CCASSERT( _emitterMode == kParticleModeRadius, "Particle Mode should be Radius"); CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
modeB.rotatePerSecond = degrees; modeB.rotatePerSecond = degrees;
} }
float ParticleSystem::getRotatePerSecond() const float ParticleSystem::getRotatePerSecond() const
{ {
CCASSERT( _emitterMode == kParticleModeRadius, "Particle Mode should be Radius"); CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
return modeB.rotatePerSecond; return modeB.rotatePerSecond;
} }
void ParticleSystem::setRotatePerSecondVar(float degrees) void ParticleSystem::setRotatePerSecondVar(float degrees)
{ {
CCASSERT( _emitterMode == kParticleModeRadius, "Particle Mode should be Radius"); CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
modeB.rotatePerSecondVar = degrees; modeB.rotatePerSecondVar = degrees;
} }
float ParticleSystem::getRotatePerSecondVar() const float ParticleSystem::getRotatePerSecondVar() const
{ {
CCASSERT( _emitterMode == kParticleModeRadius, "Particle Mode should be Radius"); CCASSERT(_emitterMode == Mode::RADIUS, "Particle Mode should be Radius");
return modeB.rotatePerSecondVar; return modeB.rotatePerSecondVar;
} }

View File

@ -40,45 +40,6 @@ NS_CC_BEGIN
class ParticleBatchNode; class ParticleBatchNode;
//* @enum
enum {
/** The Particle emitter lives forever */
kParticleDurationInfinity = -1,
/** The starting size of the particle is equal to the ending size */
kParticleStartSizeEqualToEndSize = -1,
/** The starting radius of the particle is equal to the ending radius */
kParticleStartRadiusEqualToEndRadius = -1
};
//* @enum
enum {
/** Gravity mode (A mode) */
kParticleModeGravity,
/** Radius mode (B mode) */
kParticleModeRadius,
};
/** @typedef tPositionType
possible types of particle positions
*/
typedef enum {
/** Living particles are attached to the world and are unaffected by emitter repositioning. */
kPositionTypeFree,
/** Living particles are attached to the world but will follow the emitter repositioning.
Use case: Attach an emitter to an sprite, and you want that the emitter follows the sprite.
*/
kPositionTypeRelative,
/** Living particles are attached to the emitter and are translated along with it. */
kPositionTypeGrouped,
}tPositionType;
/** /**
Structure that contains the values of each particle Structure that contains the values of each particle
*/ */
@ -166,6 +127,41 @@ emitter.startSpin = 0;
class CC_DLL ParticleSystem : public Node, public TextureProtocol class CC_DLL ParticleSystem : public Node, public TextureProtocol
{ {
public: public:
enum class Mode
{
GRAVITY,
RADIUS,
};
/** @typedef PositionType
possible types of particle positions
*/
enum class PositionType
{
/** Living particles are attached to the world and are unaffected by emitter repositioning. */
FREE,
/** Living particles are attached to the world but will follow the emitter repositioning.
Use case: Attach an emitter to an sprite, and you want that the emitter follows the sprite.
*/
RELATIVE,
/** Living particles are attached to the emitter and are translated along with it. */
GROUPED,
};
//* @enum
enum {
/** The Particle emitter lives forever */
DURATION_INFINITY = -1,
/** The starting size of the particle is equal to the ending size */
START_SIZE_EQUAL_TO_END_SIZE = -1,
/** The starting radius of the particle is equal to the ending radius */
START_RADIUS_EQUAL_TO_END_RADIUS = -1,
};
/** creates an initializes a ParticleSystem from a plist file. /** creates an initializes a ParticleSystem from a plist file.
This plist files can be created manually or with Particle Designer: This plist files can be created manually or with Particle Designer:
http://particledesigner.71squared.com/ http://particledesigner.71squared.com/
@ -304,8 +300,8 @@ public:
- kParticleModeGravity: uses gravity, speed, radial and tangential acceleration - kParticleModeGravity: uses gravity, speed, radial and tangential acceleration
- kParticleModeRadius: uses radius movement + rotation - kParticleModeRadius: uses radius movement + rotation
*/ */
inline int getEmitterMode() const { return _emitterMode; }; inline Mode getEmitterMode() const { return _emitterMode; };
inline void setEmitterMode(int mode) { _emitterMode = mode; }; inline void setEmitterMode(Mode mode) { _emitterMode = mode; };
/** start size in pixels of each particle */ /** start size in pixels of each particle */
inline float getStartSize() const { return _startSize; }; inline float getStartSize() const { return _startSize; };
@ -371,8 +367,8 @@ public:
/** particles movement type: Free or Grouped /** particles movement type: Free or Grouped
@since v0.8 @since v0.8
*/ */
inline tPositionType getPositionType() const { return _positionType; }; inline PositionType getPositionType() const { return _positionType; };
inline void setPositionType(tPositionType type) { _positionType = type; }; inline void setPositionType(PositionType type) { _positionType = type; };
// Overrides // Overrides
virtual void update(float dt) override; virtual void update(float dt) override;
@ -491,7 +487,7 @@ protected:
- kParticleModeGravity: uses gravity, speed, radial and tangential acceleration - kParticleModeGravity: uses gravity, speed, radial and tangential acceleration
- kParticleModeRadius: uses radius movement + rotation - kParticleModeRadius: uses radius movement + rotation
*/ */
int _emitterMode; Mode _emitterMode;
/** start size in pixels of each particle */ /** start size in pixels of each particle */
float _startSize; float _startSize;
@ -531,7 +527,7 @@ protected:
/** particles movement type: Free or Grouped /** particles movement type: Free or Grouped
@since v0.8 @since v0.8
*/ */
tPositionType _positionType; PositionType _positionType;
}; };
// end of particle_nodes group // end of particle_nodes group

View File

@ -63,7 +63,7 @@ bool ParticleSystemQuad::initWithTotalParticles(unsigned int numberOfParticles)
setupVBO(); setupVBO();
#endif #endif
setShaderProgram(ShaderCache::getInstance()->programForKey(kShader_PositionTextureColor)); setShaderProgram(ShaderCache::getInstance()->programForKey(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR));
#if CC_ENABLE_CACHE_TEXTURE_DATA #if CC_ENABLE_CACHE_TEXTURE_DATA
// Need to listen the event only when not use batchnode, because it will use VBO // Need to listen the event only when not use batchnode, because it will use VBO
@ -97,7 +97,7 @@ ParticleSystemQuad::~ParticleSystemQuad()
glDeleteBuffers(2, &_buffersVBO[0]); glDeleteBuffers(2, &_buffersVBO[0]);
#if CC_TEXTURE_ATLAS_USE_VAO #if CC_TEXTURE_ATLAS_USE_VAO
glDeleteVertexArrays(1, &_VAOname); glDeleteVertexArrays(1, &_VAOname);
ccGLBindVAO(0); GL::bindVAO(0);
#endif #endif
} }
@ -350,8 +350,8 @@ void ParticleSystemQuad::draw()
CC_NODE_DRAW_SETUP(); CC_NODE_DRAW_SETUP();
ccGLBindTexture2D( _texture->getName() ); GL::bindTexture2D( _texture->getName() );
ccGLBlendFunc( _blendFunc.src, _blendFunc.dst ); GL::blendFunc( _blendFunc.src, _blendFunc.dst );
CCASSERT( _particleIdx == _particleCount, "Abnormal error in particle quad"); CCASSERT( _particleIdx == _particleCount, "Abnormal error in particle quad");
@ -359,7 +359,7 @@ void ParticleSystemQuad::draw()
// //
// Using VBO and VAO // Using VBO and VAO
// //
ccGLBindVAO(_VAOname); GL::bindVAO(_VAOname);
#if CC_REBIND_INDICES_BUFFER #if CC_REBIND_INDICES_BUFFER
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
@ -378,15 +378,15 @@ void ParticleSystemQuad::draw()
#define kQuadSize sizeof(_quads[0].bl) #define kQuadSize sizeof(_quads[0].bl)
ccGLEnableVertexAttribs( kVertexAttribFlag_PosColorTex ); GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX );
glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]); glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]);
// vertices // vertices
glVertexAttribPointer(kVertexAttrib_Position, 3, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, vertices)); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, vertices));
// colors // colors
glVertexAttribPointer(kVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, colors)); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, colors));
// tex coords // tex coords
glVertexAttribPointer(kVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, texCoords)); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, texCoords));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
@ -474,10 +474,10 @@ void ParticleSystemQuad::setupVBOandVAO()
// clean VAO // clean VAO
glDeleteBuffers(2, &_buffersVBO[0]); glDeleteBuffers(2, &_buffersVBO[0]);
glDeleteVertexArrays(1, &_VAOname); glDeleteVertexArrays(1, &_VAOname);
ccGLBindVAO(0); GL::bindVAO(0);
glGenVertexArrays(1, &_VAOname); glGenVertexArrays(1, &_VAOname);
ccGLBindVAO(_VAOname); GL::bindVAO(_VAOname);
#define kQuadSize sizeof(_quads[0].bl) #define kQuadSize sizeof(_quads[0].bl)
@ -487,22 +487,22 @@ void ParticleSystemQuad::setupVBOandVAO()
glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * _totalParticles, _quads, GL_DYNAMIC_DRAW); glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * _totalParticles, _quads, GL_DYNAMIC_DRAW);
// vertices // vertices
glEnableVertexAttribArray(kVertexAttrib_Position); glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_POSITION);
glVertexAttribPointer(kVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, vertices)); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, vertices));
// colors // colors
glEnableVertexAttribArray(kVertexAttrib_Color); glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_COLOR);
glVertexAttribPointer(kVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, colors)); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, colors));
// tex coords // tex coords
glEnableVertexAttribArray(kVertexAttrib_TexCoords); glEnableVertexAttribArray(GLProgram::VERTEX_ATTRIB_TEX_COORDS);
glVertexAttribPointer(kVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, texCoords)); glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, kQuadSize, (GLvoid*) offsetof( V3F_C4B_T2F, texCoords));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _buffersVBO[1]);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(_indices[0]) * _totalParticles * 6, _indices, GL_STATIC_DRAW); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(_indices[0]) * _totalParticles * 6, _indices, GL_STATIC_DRAW);
// Must unbind the VAO before changing the element buffer. // Must unbind the VAO before changing the element buffer.
ccGLBindVAO(0); GL::bindVAO(0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ARRAY_BUFFER, 0);
@ -598,7 +598,7 @@ void ParticleSystemQuad::setBatchNode(ParticleBatchNode * batchNode)
glDeleteBuffers(2, &_buffersVBO[0]); glDeleteBuffers(2, &_buffersVBO[0]);
#if CC_TEXTURE_ATLAS_USE_VAO #if CC_TEXTURE_ATLAS_USE_VAO
glDeleteVertexArrays(1, &_VAOname); glDeleteVertexArrays(1, &_VAOname);
ccGLBindVAO(0); GL::bindVAO(0);
#endif #endif
} }
} }

View File

@ -3,20 +3,6 @@
NS_CC_BEGIN NS_CC_BEGIN
enum TargetPlatform
{
kTargetWindows,
kTargetLinux,
kTargetMacOS,
kTargetAndroid,
kTargetIphone,
kTargetIpad,
kTargetBlackBerry,
kTargetNaCl,
kTargetEmscripten,
kTargetTizen
};
/** /**
* @addtogroup platform * @addtogroup platform
* @{ * @{
@ -26,6 +12,23 @@ class CC_DLL ApplicationProtocol
{ {
public: public:
// Since WINDOWS and ANDROID are defined as macros, we could not just use these keywords in enumeration(Platform).
// Therefore, 'OS_' prefix is added to avoid conflicts with the definitions of system macros.
enum class Platform
{
OS_WINDOWS,
OS_LINUX,
OS_MAC,
OS_ANDROID,
OS_IPHONE,
OS_IPAD,
OS_BLACKBERRY,
OS_NACL,
OS_EMSCRIPTEN,
OS_TIZEN
};
virtual ~ApplicationProtocol() {} virtual ~ApplicationProtocol() {}
/** /**
@ -57,12 +60,12 @@ public:
@brief Get current language config @brief Get current language config
@return Current language config @return Current language config
*/ */
virtual ccLanguageType getCurrentLanguage() = 0; virtual LanguageType getCurrentLanguage() = 0;
/** /**
@brief Get target platform @brief Get target platform
*/ */
virtual TargetPlatform getTargetPlatform() = 0; virtual Platform getTargetPlatform() = 0;
}; };
// end of platform group // end of platform group

View File

@ -55,25 +55,25 @@ void CC_DLL MessageBox(const char * pszMsg, const char * pszTitle);
/** /**
@brief Enum the language type supported now @brief Enum the language type supported now
*/ */
typedef enum LanguageType enum class LanguageType
{ {
kLanguageEnglish = 0, ENGLISH = 0,
kLanguageChinese, CHINESE,
kLanguageFrench, FRENCH,
kLanguageItalian, ITALIAN,
kLanguageGerman, GERMAN,
kLanguageSpanish, SPANISH,
kLanguageRussian, RUSSIAN,
kLanguageKorean, KOREAN,
kLanguageJapanese, JAPANESE,
kLanguageHungarian, HUNGARIAN,
kLanguagePortuguese, PORTUGUESE,
kLanguageArabic, ARABIC,
kLanguageNorwegian, NORWEGIAN,
kLanguagePolish POLISH
} ccLanguageType; };
// end of platform group // END of platform group
/// @} /// @}
NS_CC_END NS_CC_END

View File

@ -46,7 +46,7 @@ EGLViewProtocol::EGLViewProtocol()
: _delegate(NULL) : _delegate(NULL)
, _scaleX(1.0f) , _scaleX(1.0f)
, _scaleY(1.0f) , _scaleY(1.0f)
, _resolutionPolicy(kResolutionUnKnown) , _resolutionPolicy(ResolutionPolicy::UNKNOWN)
{ {
} }
@ -57,7 +57,7 @@ EGLViewProtocol::~EGLViewProtocol()
void EGLViewProtocol::setDesignResolutionSize(float width, float height, ResolutionPolicy resolutionPolicy) void EGLViewProtocol::setDesignResolutionSize(float width, float height, ResolutionPolicy resolutionPolicy)
{ {
CCASSERT(resolutionPolicy != kResolutionUnKnown, "should set resolutionPolicy"); CCASSERT(resolutionPolicy != ResolutionPolicy::UNKNOWN, "should set resolutionPolicy");
if (width == 0.0f || height == 0.0f) if (width == 0.0f || height == 0.0f)
{ {
@ -69,22 +69,22 @@ void EGLViewProtocol::setDesignResolutionSize(float width, float height, Resolut
_scaleX = (float)_screenSize.width / _designResolutionSize.width; _scaleX = (float)_screenSize.width / _designResolutionSize.width;
_scaleY = (float)_screenSize.height / _designResolutionSize.height; _scaleY = (float)_screenSize.height / _designResolutionSize.height;
if (resolutionPolicy == kResolutionNoBorder) if (resolutionPolicy == ResolutionPolicy::NO_BORDER)
{ {
_scaleX = _scaleY = MAX(_scaleX, _scaleY); _scaleX = _scaleY = MAX(_scaleX, _scaleY);
} }
if (resolutionPolicy == kResolutionShowAll) if (resolutionPolicy == ResolutionPolicy::SHOW_ALL)
{ {
_scaleX = _scaleY = MIN(_scaleX, _scaleY); _scaleX = _scaleY = MIN(_scaleX, _scaleY);
} }
if ( resolutionPolicy == kResolutionFixedHeight) { if ( resolutionPolicy == ResolutionPolicy::FIXED_HEIGHT) {
_scaleX = _scaleY; _scaleX = _scaleY;
_designResolutionSize.width = ceilf(_screenSize.width/_scaleX); _designResolutionSize.width = ceilf(_screenSize.width/_scaleX);
} }
if ( resolutionPolicy == kResolutionFixedWidth) { if ( resolutionPolicy == ResolutionPolicy::FIXED_WIDTH) {
_scaleY = _scaleX; _scaleY = _scaleX;
_designResolutionSize.height = ceilf(_screenSize.height/_scaleY); _designResolutionSize.height = ceilf(_screenSize.height/_scaleY);
} }
@ -120,7 +120,7 @@ void EGLViewProtocol::setFrameSize(float width, float height)
Size EGLViewProtocol::getVisibleSize() const Size EGLViewProtocol::getVisibleSize() const
{ {
if (_resolutionPolicy == kResolutionNoBorder) if (_resolutionPolicy == ResolutionPolicy::NO_BORDER)
{ {
return Size(_screenSize.width/_scaleX, _screenSize.height/_scaleY); return Size(_screenSize.width/_scaleX, _screenSize.height/_scaleY);
} }
@ -132,7 +132,7 @@ Size EGLViewProtocol::getVisibleSize() const
Point EGLViewProtocol::getVisibleOrigin() const Point EGLViewProtocol::getVisibleOrigin() const
{ {
if (_resolutionPolicy == kResolutionNoBorder) if (_resolutionPolicy == ResolutionPolicy::NO_BORDER)
{ {
return Point((_designResolutionSize.width - _screenSize.width/_scaleX)/2, return Point((_designResolutionSize.width - _screenSize.width/_scaleX)/2,
(_designResolutionSize.height - _screenSize.height/_scaleY)/2); (_designResolutionSize.height - _screenSize.height/_scaleY)/2);

View File

@ -3,29 +3,29 @@
#include "ccTypes.h" #include "ccTypes.h"
enum ResolutionPolicy enum class ResolutionPolicy
{ {
// The entire application is visible in the specified area without trying to preserve the original aspect ratio. // The entire application is visible in the specified area without trying to preserve the original aspect ratio.
// Distortion can occur, and the application may appear stretched or compressed. // Distortion can occur, and the application may appear stretched or compressed.
kResolutionExactFit, EXACT_FIT,
// The entire application fills the specified area, without distortion but possibly with some cropping, // The entire application fills the specified area, without distortion but possibly with some cropping,
// while maintaining the original aspect ratio of the application. // while maintaining the original aspect ratio of the application.
kResolutionNoBorder, NO_BORDER,
// The entire application is visible in the specified area without distortion while maintaining the original // The entire application is visible in the specified area without distortion while maintaining the original
// aspect ratio of the application. Borders can appear on two sides of the application. // aspect ratio of the application. Borders can appear on two sides of the application.
kResolutionShowAll, SHOW_ALL,
// The application takes the height of the design resolution size and modifies the width of the internal // The application takes the height of the design resolution size and modifies the width of the internal
// canvas so that it fits the aspect ratio of the device // canvas so that it fits the aspect ratio of the device
// no distortion will occur however you must make sure your application works on different // no distortion will occur however you must make sure your application works on different
// aspect ratios // aspect ratios
kResolutionFixedHeight, FIXED_HEIGHT,
// The application takes the width of the design resolution size and modifies the height of the internal // The application takes the width of the design resolution size and modifies the height of the internal
// canvas so that it fits the aspect ratio of the device // canvas so that it fits the aspect ratio of the device
// no distortion will occur however you must make sure your application works on different // no distortion will occur however you must make sure your application works on different
// aspect ratios // aspect ratios
kResolutionFixedWidth, FIXED_WIDTH,
kResolutionUnKnown, UNKNOWN,
}; };
NS_CC_BEGIN NS_CC_BEGIN
@ -84,9 +84,9 @@ public:
* @param width Design resolution width. * @param width Design resolution width.
* @param height Design resolution height. * @param height Design resolution height.
* @param resolutionPolicy The resolution policy desired, you may choose: * @param resolutionPolicy The resolution policy desired, you may choose:
* [1] kResolutionExactFit Fill screen by stretch-to-fit: if the design resolution ratio of width to height is different from the screen resolution ratio, your game view will be stretched. * [1] EXACT_FIT Fill screen by stretch-to-fit: if the design resolution ratio of width to height is different from the screen resolution ratio, your game view will be stretched.
* [2] kResolutionNoBorder Full screen without black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two areas of your game view will be cut. * [2] NO_BORDER Full screen without black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two areas of your game view will be cut.
* [3] kResolutionShowAll Full screen with black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two black borders will be shown. * [3] SHOW_ALL Full screen with black border: if the design resolution ratio of width to height is different from the screen resolution ratio, two black borders will be shown.
*/ */
virtual void setDesignResolutionSize(float width, float height, ResolutionPolicy resolutionPolicy); virtual void setDesignResolutionSize(float width, float height, ResolutionPolicy resolutionPolicy);

View File

@ -498,15 +498,15 @@ void FileUtils::purgeCachedEntries()
_fullPathCache.clear(); _fullPathCache.clear();
} }
unsigned char* FileUtils::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize) unsigned char* FileUtils::getFileData(const char* filename, const char* pszMode, unsigned long * pSize)
{ {
unsigned char * pBuffer = NULL; unsigned char * pBuffer = NULL;
CCASSERT(pszFileName != NULL && pSize != NULL && pszMode != NULL, "Invalid parameters."); CCASSERT(filename != NULL && pSize != NULL && pszMode != NULL, "Invalid parameters.");
*pSize = 0; *pSize = 0;
do do
{ {
// read the file from hardware // read the file from hardware
std::string fullPath = fullPathForFilename(pszFileName); std::string fullPath = fullPathForFilename(filename);
FILE *fp = fopen(fullPath.c_str(), pszMode); FILE *fp = fopen(fullPath.c_str(), pszMode);
CC_BREAK_IF(!fp); CC_BREAK_IF(!fp);
@ -521,14 +521,14 @@ unsigned char* FileUtils::getFileData(const char* pszFileName, const char* pszMo
if (! pBuffer) if (! pBuffer)
{ {
std::string msg = "Get data from file("; std::string msg = "Get data from file(";
msg.append(pszFileName).append(") failed!"); msg.append(filename).append(") failed!");
CCLOG("%s", msg.c_str()); CCLOG("%s", msg.c_str());
} }
return pBuffer; return pBuffer;
} }
unsigned char* FileUtils::getFileDataFromZip(const char* pszZipFilePath, const char* pszFileName, unsigned long * pSize) unsigned char* FileUtils::getFileDataFromZip(const char* pszZipFilePath, const char* filename, unsigned long * pSize)
{ {
unsigned char * pBuffer = NULL; unsigned char * pBuffer = NULL;
unzFile pFile = NULL; unzFile pFile = NULL;
@ -536,13 +536,13 @@ unsigned char* FileUtils::getFileDataFromZip(const char* pszZipFilePath, const c
do do
{ {
CC_BREAK_IF(!pszZipFilePath || !pszFileName); CC_BREAK_IF(!pszZipFilePath || !filename);
CC_BREAK_IF(strlen(pszZipFilePath) == 0); CC_BREAK_IF(strlen(pszZipFilePath) == 0);
pFile = unzOpen(pszZipFilePath); pFile = unzOpen(pszZipFilePath);
CC_BREAK_IF(!pFile); CC_BREAK_IF(!pFile);
int nRet = unzLocateFile(pFile, pszFileName, 1); int nRet = unzLocateFile(pFile, filename, 1);
CC_BREAK_IF(UNZ_OK != nRet); CC_BREAK_IF(UNZ_OK != nRet);
char szFilePathA[260]; char szFilePathA[260];
@ -569,13 +569,13 @@ unsigned char* FileUtils::getFileDataFromZip(const char* pszZipFilePath, const c
return pBuffer; return pBuffer;
} }
std::string FileUtils::getNewFilename(const char* pszFileName) std::string FileUtils::getNewFilename(const char* filename)
{ {
const char* pszNewFileName = NULL; const char* pszNewFileName = NULL;
// in Lookup Filename dictionary ? // in Lookup Filename dictionary ?
String* fileNameFound = _filenameLookupDict ? (String*)_filenameLookupDict->objectForKey(pszFileName) : NULL; String* fileNameFound = _filenameLookupDict ? (String*)_filenameLookupDict->objectForKey(filename) : NULL;
if( NULL == fileNameFound || fileNameFound->length() == 0) { if( NULL == fileNameFound || fileNameFound->length() == 0) {
pszNewFileName = pszFileName; pszNewFileName = filename;
} }
else { else {
pszNewFileName = fileNameFound->getCString(); pszNewFileName = fileNameFound->getCString();
@ -607,19 +607,19 @@ std::string FileUtils::getPathForFilename(const std::string& filename, const std
} }
std::string FileUtils::fullPathForFilename(const char* pszFileName) std::string FileUtils::fullPathForFilename(const char* filename)
{ {
CCASSERT(pszFileName != NULL, "CCFileUtils: Invalid path"); CCASSERT(filename != NULL, "CCFileUtils: Invalid path");
std::string strFileName = pszFileName; std::string strFileName = filename;
if (isAbsolutePath(pszFileName)) if (isAbsolutePath(filename))
{ {
//CCLOG("Return absolute path( %s ) directly.", pszFileName); //CCLOG("Return absolute path( %s ) directly.", filename);
return pszFileName; return filename;
} }
// Already Cached ? // Already Cached ?
std::map<std::string, std::string>::iterator cacheIter = _fullPathCache.find(pszFileName); std::map<std::string, std::string>::iterator cacheIter = _fullPathCache.find(filename);
if (cacheIter != _fullPathCache.end()) if (cacheIter != _fullPathCache.end())
{ {
//CCLOG("Return full path from cache: %s", cacheIter->second.c_str()); //CCLOG("Return full path from cache: %s", cacheIter->second.c_str());
@ -627,7 +627,7 @@ std::string FileUtils::fullPathForFilename(const char* pszFileName)
} }
// Get the new file name. // Get the new file name.
std::string newFilename = getNewFilename(pszFileName); std::string newFilename = getNewFilename(filename);
string fullpath = ""; string fullpath = "";
@ -643,25 +643,25 @@ std::string FileUtils::fullPathForFilename(const char* pszFileName)
if (fullpath.length() > 0) if (fullpath.length() > 0)
{ {
// Using the filename passed in as key. // Using the filename passed in as key.
_fullPathCache.insert(std::pair<std::string, std::string>(pszFileName, fullpath)); _fullPathCache.insert(std::pair<std::string, std::string>(filename, fullpath));
// CCLOG("Returning path: %s", fullpath.c_str()); // CCLOG("Returning path: %s", fullpath.c_str());
return fullpath; return fullpath;
} }
} }
} }
// CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", pszFileName); // CCLOG("cocos2d: fullPathForFilename: No file found at %s. Possible missing file.", filename);
// The file wasn't found, return the file name passed in. // The file wasn't found, return the file name passed in.
return pszFileName; return filename;
} }
const char* FileUtils::fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile) const char* FileUtils::fullPathFromRelativeFile(const char *filename, const char *pszRelativeFile)
{ {
std::string relativeFile = pszRelativeFile; std::string relativeFile = pszRelativeFile;
String *pRet = String::create(""); String *pRet = String::create("");
pRet->_string = relativeFile.substr(0, relativeFile.rfind('/')+1); pRet->_string = relativeFile.substr(0, relativeFile.rfind('/')+1);
pRet->_string += getNewFilename(pszFilename); pRet->_string += getNewFilename(filename);
return pRet->getCString(); return pRet->getCString();
} }

View File

@ -90,23 +90,23 @@ public:
/** /**
* Gets resource file data * Gets resource file data
* *
* @param[in] pszFileName The resource file name which contains the path. * @param[in] filename The resource file name which contains the path.
* @param[in] pszMode The read mode of the file. * @param[in] pszMode The read mode of the file.
* @param[out] pSize If the file read operation succeeds, it will be the data size, otherwise 0. * @param[out] pSize If the file read operation succeeds, it will be the data size, otherwise 0.
* @return Upon success, a pointer to the data is returned, otherwise NULL. * @return Upon success, a pointer to the data is returned, otherwise NULL.
* @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned. * @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned.
*/ */
virtual unsigned char* getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize); virtual unsigned char* getFileData(const char* filename, const char* pszMode, unsigned long * pSize);
/** /**
* Gets resource file data from a zip file. * Gets resource file data from a zip file.
* *
* @param[in] pszFileName The resource file name which contains the relative path of the zip file. * @param[in] filename The resource file name which contains the relative path of the zip file.
* @param[out] pSize If the file read operation succeeds, it will be the data size, otherwise 0. * @param[out] pSize If the file read operation succeeds, it will be the data size, otherwise 0.
* @return Upon success, a pointer to the data is returned, otherwise NULL. * @return Upon success, a pointer to the data is returned, otherwise NULL.
* @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned. * @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned.
*/ */
virtual unsigned char* getFileDataFromZip(const char* pszZipFilePath, const char* pszFileName, unsigned long * pSize); virtual unsigned char* getFileDataFromZip(const char* pszZipFilePath, const char* filename, unsigned long * pSize);
/** Returns the fullpath for a given filename. /** Returns the fullpath for a given filename.
@ -147,14 +147,14 @@ public:
internal_dir/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz (if not found, search next) internal_dir/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz (if not found, search next)
internal_dir/gamescene/uilayer/sprite.pvr.gz (if not found, return "gamescene/uilayer/sprite.png") internal_dir/gamescene/uilayer/sprite.pvr.gz (if not found, return "gamescene/uilayer/sprite.png")
If the new file can't be found on the file system, it will return the parameter pszFileName directly. If the new file can't be found on the file system, it will return the parameter filename directly.
This method was added to simplify multiplatform support. Whether you are using cocos2d-js or any cross-compilation toolchain like StellaSDK or Apportable, This method was added to simplify multiplatform support. Whether you are using cocos2d-js or any cross-compilation toolchain like StellaSDK or Apportable,
you might need to load different resources for a given file in the different platforms. you might need to load different resources for a given file in the different platforms.
@since v2.1 @since v2.1
*/ */
virtual std::string fullPathForFilename(const char* pszFileName); virtual std::string fullPathForFilename(const char* filename);
/** /**
* Loads the filenameLookup dictionary from the contents of a filename. * Loads the filenameLookup dictionary from the contents of a filename.
@ -199,14 +199,14 @@ public:
/** /**
* Gets full path from a file name and the path of the reletive file. * Gets full path from a file name and the path of the reletive file.
* @param pszFilename The file name. * @param filename The file name.
* @param pszRelativeFile The path of the relative file. * @param pszRelativeFile The path of the relative file.
* @return The full path. * @return The full path.
* e.g. pszFilename: hello.png, pszRelativeFile: /User/path1/path2/hello.plist * e.g. filename: hello.png, pszRelativeFile: /User/path1/path2/hello.plist
* Return: /User/path1/path2/hello.pvr (If there a a key(hello.png)-value(hello.pvr) in FilenameLookup dictionary. ) * Return: /User/path1/path2/hello.pvr (If there a a key(hello.png)-value(hello.pvr) in FilenameLookup dictionary. )
* *
*/ */
virtual const char* fullPathFromRelativeFile(const char *pszFilename, const char *pszRelativeFile); virtual const char* fullPathFromRelativeFile(const char *filename, const char *pszRelativeFile);
/** /**
* Sets the array that contains the search order of the resources. * Sets the array that contains the search order of the resources.
@ -318,11 +318,11 @@ protected:
/** /**
* Gets the new filename from the filename lookup dictionary. * Gets the new filename from the filename lookup dictionary.
* @param pszFileName The original filename. * @param filename The original filename.
* @return The new filename after searching in the filename lookup dictionary. * @return The new filename after searching in the filename lookup dictionary.
* If the original filename wasn't in the dictionary, it will return the original filename. * If the original filename wasn't in the dictionary, it will return the original filename.
*/ */
virtual std::string getNewFilename(const char* pszFileName); virtual std::string getNewFilename(const char* filename);
/** /**
* Gets full path for filename, resolution directory and search path. * Gets full path for filename, resolution directory and search path.

View File

@ -50,15 +50,22 @@ public:
Image(); Image();
virtual ~Image(); virtual ~Image();
typedef enum /** Supported formats for Image */
enum class Format
{ {
kFmtJpg = 0, //! JPEG
kFmtPng, JPG,
kFmtTiff, //! PNG
kFmtWebp, PNG,
kFmtRawData, //! TIFF
kFmtUnKnown TIFF,
}EImageFormat; //! WebP
WEBP,
//! Raw Data
RAW_DATA,
//! Unknown format
UNKOWN
};
typedef enum typedef enum
{ {
@ -79,7 +86,7 @@ public:
@param imageType the type of image, currently only supporting two types. @param imageType the type of image, currently only supporting two types.
@return true if loaded correctly. @return true if loaded correctly.
*/ */
bool initWithImageFile(const char * strPath, EImageFormat imageType = kFmtPng); bool initWithImageFile(const char * strPath, Format imageType = Format::PNG);
/** /**
@brief Load image from stream buffer. @brief Load image from stream buffer.
@ -92,7 +99,7 @@ public:
*/ */
bool initWithImageData(void * pData, bool initWithImageData(void * pData,
int nDataLen, int nDataLen,
EImageFormat eFmt = kFmtUnKnown, Format eFmt = Format::UNKOWN,
int nWidth = 0, int nWidth = 0,
int nHeight = 0, int nHeight = 0,
int nBitsPerComponent = 8); int nBitsPerComponent = 8);
@ -165,13 +172,13 @@ public:
// //
protected: protected:
bool _initWithJpgData(void *pData, int nDatalen); bool initWithJpgData(void *pData, int nDatalen);
bool _initWithPngData(void *pData, int nDatalen); bool initWithPngData(void *pData, int nDatalen);
bool _initWithTiffData(void *pData, int nDataLen); bool initWithTiffData(void *pData, int nDataLen);
bool _initWithWebpData(void *pData, int nDataLen); bool initWithWebpData(void *pData, int nDataLen);
bool _saveImageToPNG(const char *pszFilePath, bool bIsToRGB = true); bool saveImageToPNG(const char *pszFilePath, bool bIsToRGB = true);
bool _saveImageToJPG(const char *pszFilePath); bool saveImageToJPG(const char *pszFilePath);
unsigned short _width; unsigned short _width;
unsigned short _height; unsigned short _height;
@ -194,7 +201,7 @@ private:
@param imageType the type of image, currently only supporting two types. @param imageType the type of image, currently only supporting two types.
@return true if loaded correctly. @return true if loaded correctly.
*/ */
bool initWithImageFileThreadSafe(const char *fullpath, EImageFormat imageType = kFmtPng); bool initWithImageFileThreadSafe(const char *fullpath, Format imageType = Format::PNG);
}; };
// end of platform group // end of platform group

View File

@ -38,7 +38,7 @@
NS_CC_BEGIN NS_CC_BEGIN
bool Image::_initWithWebpData(void *pData, int nDataLen) bool Image::initWithWebpData(void *pData, int nDataLen)
{ {
bool bRet = false; bool bRet = false;
do do

View File

@ -91,16 +91,17 @@ Image::~Image()
CC_SAFE_DELETE_ARRAY(_data); CC_SAFE_DELETE_ARRAY(_data);
} }
bool Image::initWithImageFile(const char * strPath, EImageFormat eImgFmt/* = eFmtPng*/) bool Image::initWithImageFile(const char * strPath, Format eImgFmt/* = eFmtPng*/)
{ {
bool bRet = false; bool bRet = false;
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(strPath);
#ifdef EMSCRIPTEN #ifdef EMSCRIPTEN
// Emscripten includes a re-implementation of SDL that uses HTML5 canvas // Emscripten includes a re-implementation of SDL that uses HTML5 canvas
// operations underneath. Consequently, loading images via IMG_Load (an SDL // operations underneath. Consequently, loading images via IMG_Load (an SDL
// API) will be a lot faster than running libpng et al as compiled with // API) will be a lot faster than running libpng et al as compiled with
// Emscripten. // Emscripten.
SDL_Surface *iSurf = IMG_Load(strPath); SDL_Surface *iSurf = IMG_Load(fullPath.c_str());
int size = 4 * (iSurf->w * iSurf->h); int size = 4 * (iSurf->w * iSurf->h);
bRet = initWithRawData((void*)iSurf->pixels, size, iSurf->w, iSurf->h, 8, true); bRet = initWithRawData((void*)iSurf->pixels, size, iSurf->w, iSurf->h, 8, true);
@ -116,7 +117,6 @@ bool Image::initWithImageFile(const char * strPath, EImageFormat eImgFmt/* = eFm
SDL_FreeSurface(iSurf); SDL_FreeSurface(iSurf);
#else #else
unsigned long nSize = 0; unsigned long nSize = 0;
std::string fullPath = FileUtils::getInstance()->fullPathForFilename(strPath);
unsigned char* pBuffer = FileUtils::getInstance()->getFileData(fullPath.c_str(), "rb", &nSize); unsigned char* pBuffer = FileUtils::getInstance()->getFileData(fullPath.c_str(), "rb", &nSize);
if (pBuffer != NULL && nSize > 0) if (pBuffer != NULL && nSize > 0)
{ {
@ -128,7 +128,7 @@ bool Image::initWithImageFile(const char * strPath, EImageFormat eImgFmt/* = eFm
return bRet; return bRet;
} }
bool Image::initWithImageFileThreadSafe(const char *fullpath, EImageFormat imageType) bool Image::initWithImageFileThreadSafe(const char *fullpath, Format imageType)
{ {
bool bRet = false; bool bRet = false;
unsigned long nSize = 0; unsigned long nSize = 0;
@ -148,7 +148,7 @@ bool Image::initWithImageFileThreadSafe(const char *fullpath, EImageFormat image
bool Image::initWithImageData(void * pData, bool Image::initWithImageData(void * pData,
int nDataLen, int nDataLen,
EImageFormat eFmt/* = eSrcFmtPng*/, Format eFmt/* = eSrcFmtPng*/,
int nWidth/* = 0*/, int nWidth/* = 0*/,
int nHeight/* = 0*/, int nHeight/* = 0*/,
int nBitsPerComponent/* = 8*/) int nBitsPerComponent/* = 8*/)
@ -158,27 +158,27 @@ bool Image::initWithImageData(void * pData,
{ {
CC_BREAK_IF(! pData || nDataLen <= 0); CC_BREAK_IF(! pData || nDataLen <= 0);
if (kFmtPng == eFmt) if (Format::PNG == eFmt)
{ {
bRet = _initWithPngData(pData, nDataLen); bRet = initWithPngData(pData, nDataLen);
break; break;
} }
else if (kFmtJpg == eFmt) else if (Format::JPG == eFmt)
{ {
bRet = _initWithJpgData(pData, nDataLen); bRet = initWithJpgData(pData, nDataLen);
break; break;
} }
else if (kFmtTiff == eFmt) else if (Format::TIFF == eFmt)
{ {
bRet = _initWithTiffData(pData, nDataLen); bRet = initWithTiffData(pData, nDataLen);
break; break;
} }
else if (kFmtWebp == eFmt) else if (Format::WEBP == eFmt)
{ {
bRet = _initWithWebpData(pData, nDataLen); bRet = initWithWebpData(pData, nDataLen);
break; break;
} }
else if (kFmtRawData == eFmt) else if (Format::RAW_DATA == eFmt)
{ {
bRet = initWithRawData(pData, nDataLen, nWidth, nHeight, nBitsPerComponent, false); bRet = initWithRawData(pData, nDataLen, nWidth, nHeight, nBitsPerComponent, false);
break; break;
@ -198,7 +198,7 @@ bool Image::initWithImageData(void * pData,
&& pHead[6] == 0x1A && pHead[6] == 0x1A
&& pHead[7] == 0x0A) && pHead[7] == 0x0A)
{ {
bRet = _initWithPngData(pData, nDataLen); bRet = initWithPngData(pData, nDataLen);
break; break;
} }
} }
@ -211,7 +211,7 @@ bool Image::initWithImageData(void * pData,
|| (pHead[0] == 0x4d && pHead[1] == 0x4d) || (pHead[0] == 0x4d && pHead[1] == 0x4d)
) )
{ {
bRet = _initWithTiffData(pData, nDataLen); bRet = initWithTiffData(pData, nDataLen);
break; break;
} }
} }
@ -223,7 +223,7 @@ bool Image::initWithImageData(void * pData,
if ( pHead[0] == 0xff if ( pHead[0] == 0xff
&& pHead[1] == 0xd8) && pHead[1] == 0xd8)
{ {
bRet = _initWithJpgData(pData, nDataLen); bRet = initWithJpgData(pData, nDataLen);
break; break;
} }
} }
@ -281,7 +281,7 @@ my_error_exit (j_common_ptr cinfo)
longjmp(myerr->setjmp_buffer, 1); longjmp(myerr->setjmp_buffer, 1);
} }
bool Image::_initWithJpgData(void * data, int nSize) bool Image::initWithJpgData(void * data, int nSize)
{ {
/* these are standard libjpeg structures for reading(decompression) */ /* these are standard libjpeg structures for reading(decompression) */
struct jpeg_decompress_struct cinfo; struct jpeg_decompress_struct cinfo;
@ -378,7 +378,7 @@ bool Image::_initWithJpgData(void * data, int nSize)
return bRet; return bRet;
} }
bool Image::_initWithPngData(void * pData, int nDatalen) bool Image::initWithPngData(void * pData, int nDatalen)
{ {
// length of bytes to check if it is a valid png file // length of bytes to check if it is a valid png file
#define PNGSIGSIZE 8 #define PNGSIGSIZE 8
@ -611,7 +611,7 @@ static void _tiffUnmapProc(thandle_t fd, void* base, toff_t size)
CC_UNUSED_PARAM(size); CC_UNUSED_PARAM(size);
} }
bool Image::_initWithTiffData(void* pData, int nDataLen) bool Image::initWithTiffData(void* pData, int nDataLen)
{ {
bool bRet = false; bool bRet = false;
do do
@ -726,11 +726,11 @@ bool Image::saveToFile(const char *pszFilePath, bool bIsToRGB)
if (std::string::npos != strLowerCasePath.find(".png")) if (std::string::npos != strLowerCasePath.find(".png"))
{ {
CC_BREAK_IF(!_saveImageToPNG(pszFilePath, bIsToRGB)); CC_BREAK_IF(!saveImageToPNG(pszFilePath, bIsToRGB));
} }
else if (std::string::npos != strLowerCasePath.find(".jpg")) else if (std::string::npos != strLowerCasePath.find(".jpg"))
{ {
CC_BREAK_IF(!_saveImageToJPG(pszFilePath)); CC_BREAK_IF(!saveImageToJPG(pszFilePath));
} }
else else
{ {
@ -743,7 +743,7 @@ bool Image::saveToFile(const char *pszFilePath, bool bIsToRGB)
return bRet; return bRet;
} }
bool Image::_saveImageToPNG(const char * pszFilePath, bool bIsToRGB) bool Image::saveImageToPNG(const char * pszFilePath, bool bIsToRGB)
{ {
bool bRet = false; bool bRet = false;
do do
@ -883,7 +883,7 @@ bool Image::_saveImageToPNG(const char * pszFilePath, bool bIsToRGB)
} while (0); } while (0);
return bRet; return bRet;
} }
bool Image::_saveImageToJPG(const char * pszFilePath) bool Image::saveImageToJPG(const char * pszFilePath)
{ {
bool bRet = false; bool bRet = false;
do do

View File

@ -67,74 +67,74 @@ Application* Application::sharedApplication()
return Application::getInstance(); return Application::getInstance();
} }
ccLanguageType Application::getCurrentLanguage() LanguageType Application::getCurrentLanguage()
{ {
std::string languageName = getCurrentLanguageJNI(); std::string languageName = getCurrentLanguageJNI();
const char* pLanguageName = languageName.c_str(); const char* pLanguageName = languageName.c_str();
ccLanguageType ret = kLanguageEnglish; LanguageType ret = LanguageType::ENGLISH;
if (0 == strcmp("zh", pLanguageName)) if (0 == strcmp("zh", pLanguageName))
{ {
ret = kLanguageChinese; ret = LanguageType::CHINESE;
} }
else if (0 == strcmp("en", pLanguageName)) else if (0 == strcmp("en", pLanguageName))
{ {
ret = kLanguageEnglish; ret = LanguageType::ENGLISH;
} }
else if (0 == strcmp("fr", pLanguageName)) else if (0 == strcmp("fr", pLanguageName))
{ {
ret = kLanguageFrench; ret = LanguageType::FRENCH;
} }
else if (0 == strcmp("it", pLanguageName)) else if (0 == strcmp("it", pLanguageName))
{ {
ret = kLanguageItalian; ret = LanguageType::ITALIAN;
} }
else if (0 == strcmp("de", pLanguageName)) else if (0 == strcmp("de", pLanguageName))
{ {
ret = kLanguageGerman; ret = LanguageType::GERMAN;
} }
else if (0 == strcmp("es", pLanguageName)) else if (0 == strcmp("es", pLanguageName))
{ {
ret = kLanguageSpanish; ret = LanguageType::SPANISH;
} }
else if (0 == strcmp("ru", pLanguageName)) else if (0 == strcmp("ru", pLanguageName))
{ {
ret = kLanguageRussian; ret = LanguageType::RUSSIAN;
} }
else if (0 == strcmp("ko", pLanguageName)) else if (0 == strcmp("ko", pLanguageName))
{ {
ret = kLanguageKorean; ret = LanguageType::KOREAN;
} }
else if (0 == strcmp("ja", pLanguageName)) else if (0 == strcmp("ja", pLanguageName))
{ {
ret = kLanguageJapanese; ret = LanguageType::JAPANESE;
} }
else if (0 == strcmp("hu", pLanguageName)) else if (0 == strcmp("hu", pLanguageName))
{ {
ret = kLanguageHungarian; ret = LanguageType::HUNGARIAN;
} }
else if (0 == strcmp("pt", pLanguageName)) else if (0 == strcmp("pt", pLanguageName))
{ {
ret = kLanguagePortuguese; ret = LanguageType::PORTUGUESE;
} }
else if (0 == strcmp("ar", pLanguageName)) else if (0 == strcmp("ar", pLanguageName))
{ {
ret = kLanguageArabic; ret = LanguageType::ARABIC;
} }
else if (0 == strcmp("nb", pLanguageName)) else if (0 == strcmp("nb", pLanguageName))
{ {
ret = kLanguageNorwegian; ret = LanguageType::NORWEGIAN;
} }
else if (0 == strcmp("pl", pLanguageName)) else if (0 == strcmp("pl", pLanguageName))
{ {
ret = kLanguagePolish; ret = LanguageType::POLISH;
} }
return ret; return ret;
} }
TargetPlatform Application::getTargetPlatform() Application::Platform Application::getTargetPlatform()
{ {
return kTargetAndroid; return Platform::OS_ANDROID;
} }
NS_CC_END NS_CC_END

View File

@ -38,12 +38,12 @@ public:
@brief Get current language config @brief Get current language config
@return Current language config @return Current language config
*/ */
virtual ccLanguageType getCurrentLanguage(); virtual LanguageType getCurrentLanguage();
/** /**
@brief Get target platform @brief Get target platform
*/ */
virtual TargetPlatform getTargetPlatform(); virtual Platform getTargetPlatform();
protected: protected:
static Application * sm_pSharedApplication; static Application * sm_pSharedApplication;

View File

@ -59,7 +59,12 @@ FileUtils* FileUtils::getInstance()
if (s_sharedFileUtils == NULL) if (s_sharedFileUtils == NULL)
{ {
s_sharedFileUtils = new FileUtilsAndroid(); s_sharedFileUtils = new FileUtilsAndroid();
s_sharedFileUtils->init(); if(!s_sharedFileUtils->init())
{
delete s_sharedFileUtils;
s_sharedFileUtils = NULL;
CCLOG("ERROR: Could not init CCFileUtilsAndroid");
}
} }
return s_sharedFileUtils; return s_sharedFileUtils;
} }
@ -132,35 +137,35 @@ bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath)
} }
unsigned char* FileUtilsAndroid::getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize) unsigned char* FileUtilsAndroid::getFileData(const char* filename, const char* pszMode, unsigned long * pSize)
{ {
return doGetFileData(pszFileName, pszMode, pSize, false); return doGetFileData(filename, pszMode, pSize, false);
} }
unsigned char* FileUtilsAndroid::getFileDataForAsync(const char* pszFileName, const char* pszMode, unsigned long * pSize) unsigned char* FileUtilsAndroid::getFileDataForAsync(const char* filename, const char* pszMode, unsigned long * pSize)
{ {
return doGetFileData(pszFileName, pszMode, pSize, true); return doGetFileData(filename, pszMode, pSize, true);
} }
unsigned char* FileUtilsAndroid::doGetFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize, bool forAsync) unsigned char* FileUtilsAndroid::doGetFileData(const char* filename, const char* pszMode, unsigned long * pSize, bool forAsync)
{ {
unsigned char * pData = 0; unsigned char * pData = 0;
if ((! pszFileName) || (! pszMode) || 0 == strlen(pszFileName)) if ((! filename) || (! pszMode) || 0 == strlen(filename))
{ {
return 0; return 0;
} }
string fullPath = fullPathForFilename(pszFileName); string fullPath = fullPathForFilename(filename);
if (fullPath[0] != '/') if (fullPath[0] != '/')
{ {
string fullPath(pszFileName); string fullPath(filename);
// fullPathForFilename is not thread safe. // fullPathForFilename is not thread safe.
if (! forAsync) if (! forAsync)
{ {
fullPath = fullPathForFilename(pszFileName); fullPath = fullPathForFilename(filename);
} }
const char* relativepath = fullPath.c_str(); const char* relativepath = fullPath.c_str();
@ -200,7 +205,7 @@ unsigned char* FileUtilsAndroid::doGetFileData(const char* pszFileName, const ch
do do
{ {
// read rrom other path than user set it // read rrom other path than user set it
//CCLOG("GETTING FILE ABSOLUTE DATA: %s", pszFileName); //CCLOG("GETTING FILE ABSOLUTE DATA: %s", filename);
FILE *fp = fopen(fullPath.c_str(), pszMode); FILE *fp = fopen(fullPath.c_str(), pszMode);
CC_BREAK_IF(!fp); CC_BREAK_IF(!fp);
@ -222,7 +227,7 @@ unsigned char* FileUtilsAndroid::doGetFileData(const char* pszFileName, const ch
if (! pData) if (! pData)
{ {
std::string msg = "Get data from file("; std::string msg = "Get data from file(";
msg.append(pszFileName).append(") failed!"); msg.append(filename).append(") failed!");
CCLOG(msg.c_str()); CCLOG(msg.c_str());
} }

View File

@ -54,7 +54,7 @@ public:
/* override funtions */ /* override funtions */
bool init(); bool init();
virtual unsigned char* getFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize); virtual unsigned char* getFileData(const char* filename, const char* pszMode, unsigned long * pSize);
virtual std::string getWritablePath(); virtual std::string getWritablePath();
virtual bool isFileExist(const std::string& strFilePath); virtual bool isFileExist(const std::string& strFilePath);
virtual bool isAbsolutePath(const std::string& strPath); virtual bool isAbsolutePath(const std::string& strPath);
@ -62,10 +62,10 @@ public:
/** This function is android specific. It is used for TextureCache::addImageAsync(). /** This function is android specific. It is used for TextureCache::addImageAsync().
Don't use it in your codes. Don't use it in your codes.
*/ */
unsigned char* getFileDataForAsync(const char* pszFileName, const char* pszMode, unsigned long * pSize); unsigned char* getFileDataForAsync(const char* filename, const char* pszMode, unsigned long * pSize);
private: private:
unsigned char* doGetFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize, bool forAsync); unsigned char* doGetFileData(const char* filename, const char* pszMode, unsigned long * pSize, bool forAsync);
}; };
// end of platform group // end of platform group

View File

@ -85,9 +85,9 @@ const std::string& Application::getResourceRootPath(void)
return _resourceRootPath; return _resourceRootPath;
} }
TargetPlatform Application::getTargetPlatform() Application::Platform Application::getTargetPlatform()
{ {
return kTargetEmscripten; return Platform::OS_EMSCRIPTEN;
} }
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
@ -105,9 +105,9 @@ Application* Application::sharedApplication()
return Application::getInstance(); return Application::getInstance();
} }
ccLanguageType Application::getCurrentLanguage() LanguageType Application::getCurrentLanguage()
{ {
return kLanguageEnglish; return LanguageType::ENGLISH;
} }
NS_CC_END; NS_CC_END;

View File

@ -38,12 +38,12 @@ public:
@brief Get current language config @brief Get current language config
@return Current language config @return Current language config
*/ */
virtual ccLanguageType getCurrentLanguage(); virtual LanguageType getCurrentLanguage();
/** /**
@brief Get target platform @brief Get target platform
*/ */
virtual TargetPlatform getTargetPlatform(); virtual Platform getTargetPlatform();
/** /**

View File

@ -14,7 +14,12 @@ FileUtils* FileUtils::getInstance()
if (s_sharedFileUtils == NULL) if (s_sharedFileUtils == NULL)
{ {
s_sharedFileUtils = new FileUtilsEmscripten(); s_sharedFileUtils = new FileUtilsEmscripten();
s_sharedFileUtils->init(); if(!s_sharedFileUtils->init())
{
delete s_sharedFileUtils;
s_sharedFileUtils = NULL;
CCLOG("ERROR: Could not init CCFileUtilsEmscripten");
}
} }
return s_sharedFileUtils; return s_sharedFileUtils;
} }
@ -24,7 +29,7 @@ FileUtilsEmscripten::FileUtilsEmscripten()
bool FileUtilsEmscripten::init() bool FileUtilsEmscripten::init()
{ {
_defaultResRootPath = "app/native/Resources/"; _defaultResRootPath = "/";
return FileUtils::init(); return FileUtils::init();
} }

View File

@ -49,7 +49,7 @@ public:
*/ */
static Application* getInstance(); static Application* getInstance();
/** @deprecated Use getInstance() instead */ /** @deprecated Use getInstance() instead */
CC_DEPRECATED_ATTRIBUTE static Application* sharedApplication(); CC_DEPRECATED_ATTRIBUTE static Application* sharedApplication();
/** /**
@ -62,12 +62,12 @@ public:
@brief Get current language config @brief Get current language config
@return Current language config @return Current language config
*/ */
virtual ccLanguageType getCurrentLanguage(); virtual LanguageType getCurrentLanguage();
/** /**
@brief Get target platform @brief Get target platform
*/ */
virtual TargetPlatform getTargetPlatform(); virtual Platform getTargetPlatform();
protected: protected:
static Application * sm_pSharedApplication; static Application * sm_pSharedApplication;

View File

@ -75,7 +75,7 @@ Application* Application::sharedApplication()
return Application::getInstance(); return Application::getInstance();
} }
ccLanguageType Application::getCurrentLanguage() LanguageType Application::getCurrentLanguage()
{ {
// get the current language and country config // get the current language and country config
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
@ -86,63 +86,63 @@ ccLanguageType Application::getCurrentLanguage()
NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage];
NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode]; NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode];
ccLanguageType ret = kLanguageEnglish; LanguageType ret = LanguageType::ENGLISH;
if ([languageCode isEqualToString:@"zh"]) if ([languageCode isEqualToString:@"zh"])
{ {
ret = kLanguageChinese; ret = LanguageType::CHINESE;
} }
else if ([languageCode isEqualToString:@"en"]) else if ([languageCode isEqualToString:@"en"])
{ {
ret = kLanguageEnglish; ret = LanguageType::ENGLISH;
} }
else if ([languageCode isEqualToString:@"fr"]){ else if ([languageCode isEqualToString:@"fr"]){
ret = kLanguageFrench; ret = LanguageType::FRENCH;
} }
else if ([languageCode isEqualToString:@"it"]){ else if ([languageCode isEqualToString:@"it"]){
ret = kLanguageItalian; ret = LanguageType::ITALIAN;
} }
else if ([languageCode isEqualToString:@"de"]){ else if ([languageCode isEqualToString:@"de"]){
ret = kLanguageGerman; ret = LanguageType::GERMAN;
} }
else if ([languageCode isEqualToString:@"es"]){ else if ([languageCode isEqualToString:@"es"]){
ret = kLanguageSpanish; ret = LanguageType::SPANISH;
} }
else if ([languageCode isEqualToString:@"ru"]){ else if ([languageCode isEqualToString:@"ru"]){
ret = kLanguageRussian; ret = LanguageType::RUSSIAN;
} }
else if ([languageCode isEqualToString:@"ko"]){ else if ([languageCode isEqualToString:@"ko"]){
ret = kLanguageKorean; ret = LanguageType::KOREAN;
} }
else if ([languageCode isEqualToString:@"ja"]){ else if ([languageCode isEqualToString:@"ja"]){
ret = kLanguageJapanese; ret = LanguageType::JAPANESE;
} }
else if ([languageCode isEqualToString:@"hu"]){ else if ([languageCode isEqualToString:@"hu"]){
ret = kLanguageHungarian; ret = LanguageType::HUNGARIAN;
} }
else if ([languageCode isEqualToString:@"pt"]){ else if ([languageCode isEqualToString:@"pt"]){
ret = kLanguagePortuguese; ret = LanguageType::PORTUGUESE;
} }
else if ([languageCode isEqualToString:@"ar"]){ else if ([languageCode isEqualToString:@"ar"]){
ret = kLanguageArabic; ret = LanguageType::ARABIC;
} }
else if ([languageCode isEqualToString:@"nb"]){ else if ([languageCode isEqualToString:@"nb"]){
ret = kLanguageNorwegian; ret = LanguageType::NORWEGIAN;
} }
else if ([languageCode isEqualToString:@"pl"]){ else if ([languageCode isEqualToString:@"pl"]){
ret = kLanguagePolish; ret = LanguageType::POLISH;
} }
return ret; return ret;
} }
TargetPlatform Application::getTargetPlatform() Application::Platform Application::getTargetPlatform()
{ {
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) // idiom for iOS <= 3.2, otherwise: [UIDevice userInterfaceIdiom] is faster. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) // idiom for iOS <= 3.2, otherwise: [UIDevice userInterfaceIdiom] is faster.
{ {
return kTargetIpad; return Platform::OS_IPAD;
} }
else else
{ {
return kTargetIphone; return Platform::OS_IPHONE;
} }
} }

View File

@ -48,7 +48,7 @@ bool EGLView::isOpenGLReady()
bool EGLView::setContentScaleFactor(float contentScaleFactor) bool EGLView::setContentScaleFactor(float contentScaleFactor)
{ {
assert(_resolutionPolicy == kResolutionUnKnown); // cannot enable retina mode assert(_resolutionPolicy == ResolutionPolicy::UNKNOWN); // cannot enable retina mode
_scaleX = _scaleY = contentScaleFactor; _scaleX = _scaleY = contentScaleFactor;
[[CCEAGLView sharedEGLView] setNeedsLayout]; [[CCEAGLView sharedEGLView] setNeedsLayout];

View File

@ -213,7 +213,12 @@ FileUtils* FileUtils::getInstance()
if (s_sharedFileUtils == NULL) if (s_sharedFileUtils == NULL)
{ {
s_sharedFileUtils = new FileUtilsIOS(); s_sharedFileUtils = new FileUtilsIOS();
s_sharedFileUtils->init(); if(!s_sharedFileUtils->init())
{
delete s_sharedFileUtils;
s_sharedFileUtils = NULL;
CCLOG("ERROR: Could not init CCFileUtilsIOS");
}
} }
return s_sharedFileUtils; return s_sharedFileUtils;
} }

View File

@ -416,7 +416,7 @@ Image::~Image()
CC_SAFE_DELETE_ARRAY(_data); CC_SAFE_DELETE_ARRAY(_data);
} }
bool Image::initWithImageFile(const char * strPath, EImageFormat eImgFmt/* = eFmtPng*/) bool Image::initWithImageFile(const char * strPath, Format eImgFmt/* = eFmtPng*/)
{ {
bool bRet = false; bool bRet = false;
unsigned long nSize = 0; unsigned long nSize = 0;
@ -433,7 +433,7 @@ bool Image::initWithImageFile(const char * strPath, EImageFormat eImgFmt/* = eFm
return bRet; return bRet;
} }
bool Image::initWithImageFileThreadSafe(const char *fullpath, EImageFormat imageType) bool Image::initWithImageFileThreadSafe(const char *fullpath, Format imageType)
{ {
/* /*
* FileUtils::fullPathFromRelativePath() is not thread-safe. * FileUtils::fullPathFromRelativePath() is not thread-safe.
@ -451,7 +451,7 @@ bool Image::initWithImageFileThreadSafe(const char *fullpath, EImageFormat image
bool Image::initWithImageData(void * pData, bool Image::initWithImageData(void * pData,
int nDataLen, int nDataLen,
EImageFormat eFmt, Format eFmt,
int nWidth, int nWidth,
int nHeight, int nHeight,
int nBitsPerComponent) int nBitsPerComponent)
@ -465,13 +465,13 @@ bool Image::initWithImageData(void * pData,
do do
{ {
CC_BREAK_IF(! pData || nDataLen <= 0); CC_BREAK_IF(! pData || nDataLen <= 0);
if (eFmt == kFmtRawData) if (eFmt == Format::RAW_DATA)
{ {
bRet = initWithRawData(pData, nDataLen, nWidth, nHeight, nBitsPerComponent, false); bRet = initWithRawData(pData, nDataLen, nWidth, nHeight, nBitsPerComponent, false);
} }
else if (eFmt == kFmtWebp) else if (eFmt == Format::WEBP)
{ {
bRet = _initWithWebpData(pData, nDataLen); bRet = initWithWebpData(pData, nDataLen);
} }
else // init with png or jpg file data else // init with png or jpg file data
{ {
@ -515,25 +515,25 @@ bool Image::initWithRawData(void *pData, int nDatalen, int nWidth, int nHeight,
return bRet; return bRet;
} }
bool Image::_initWithJpgData(void *pData, int nDatalen) bool Image::initWithJpgData(void *pData, int nDatalen)
{ {
assert(0); assert(0);
return false; return false;
} }
bool Image::_initWithPngData(void *pData, int nDatalen) bool Image::initWithPngData(void *pData, int nDatalen)
{ {
assert(0); assert(0);
return false; return false;
} }
bool Image::_saveImageToPNG(const char *pszFilePath, bool bIsToRGB) bool Image::saveImageToPNG(const char *pszFilePath, bool bIsToRGB)
{ {
assert(0); assert(0);
return false; return false;
} }
bool Image::_saveImageToJPG(const char *pszFilePath) bool Image::saveImageToJPG(const char *pszFilePath)
{ {
assert(0); assert(0);
return false; return false;

View File

@ -84,9 +84,9 @@ const std::string& Application::getResourceRootPath(void)
return _resourceRootPath; return _resourceRootPath;
} }
TargetPlatform Application::getTargetPlatform() Application::Platform Application::getTargetPlatform()
{ {
return kTargetLinux; return Platform::OS_LINUX;
} }
////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////
@ -104,75 +104,75 @@ Application* Application::sharedApplication()
return Application::getInstance(); return Application::getInstance();
} }
ccLanguageType Application::getCurrentLanguage() LanguageType Application::getCurrentLanguage()
{ {
char *pLanguageName = getenv("LANG"); char *pLanguageName = getenv("LANG");
ccLanguageType ret = kLanguageEnglish; LanguageType ret = LanguageType::ENGLISH;
if (!pLanguageName) if (!pLanguageName)
{ {
return kLanguageEnglish; return LanguageType::ENGLISH;
} }
strtok(pLanguageName, "_"); strtok(pLanguageName, "_");
if (!pLanguageName) if (!pLanguageName)
{ {
return kLanguageEnglish; return LanguageType::ENGLISH;
} }
if (0 == strcmp("zh", pLanguageName)) if (0 == strcmp("zh", pLanguageName))
{ {
ret = kLanguageChinese; ret = LanguageType::CHINESE;
} }
else if (0 == strcmp("en", pLanguageName)) else if (0 == strcmp("en", pLanguageName))
{ {
ret = kLanguageEnglish; ret = LanguageType::ENGLISH;
} }
else if (0 == strcmp("fr", pLanguageName)) else if (0 == strcmp("fr", pLanguageName))
{ {
ret = kLanguageFrench; ret = LanguageType::FRENCH;
} }
else if (0 == strcmp("it", pLanguageName)) else if (0 == strcmp("it", pLanguageName))
{ {
ret = kLanguageItalian; ret = LanguageType::ITALIAN;
} }
else if (0 == strcmp("de", pLanguageName)) else if (0 == strcmp("de", pLanguageName))
{ {
ret = kLanguageGerman; ret = LanguageType::GERMAN;
} }
else if (0 == strcmp("es", pLanguageName)) else if (0 == strcmp("es", pLanguageName))
{ {
ret = kLanguageSpanish; ret = LanguageType::SPANISH;
} }
else if (0 == strcmp("ru", pLanguageName)) else if (0 == strcmp("ru", pLanguageName))
{ {
ret = kLanguageRussian; ret = LanguageType::RUSSIAN;
} }
else if (0 == strcmp("ko", pLanguageName)) else if (0 == strcmp("ko", pLanguageName))
{ {
ret = kLanguageKorean; ret = LanguageType::KOREAN;
} }
else if (0 == strcmp("ja", pLanguageName)) else if (0 == strcmp("ja", pLanguageName))
{ {
ret = kLanguageJapanese; ret = LanguageType::JAPANESE;
} }
else if (0 == strcmp("hu", pLanguageName)) else if (0 == strcmp("hu", pLanguageName))
{ {
ret = kLanguageHungarian; ret = LanguageType::HUNGARIAN;
} }
else if (0 == strcmp("pt", pLanguageName)) else if (0 == strcmp("pt", pLanguageName))
{ {
ret = kLanguagePortuguese; ret = LanguageType::PORTUGUESE;
} }
else if (0 == strcmp("ar", pLanguageName)) else if (0 == strcmp("ar", pLanguageName))
{ {
ret = kLanguageArabic; ret = LanguageType::ARABIC;
} }
else if (0 == strcmp("nb", pLanguageName)) else if (0 == strcmp("nb", pLanguageName))
{ {
ret = kLanguageNorwegian; ret = LanguageType::NORWEGIAN;
} }
else if (0 == strcmp("pl", pLanguageName)) else if (0 == strcmp("pl", pLanguageName))
{ {
ret = kLanguagePolish; ret = LanguageType::POLISH;
} }
return ret; return ret;

View File

@ -42,7 +42,7 @@ public:
CC_DEPRECATED_ATTRIBUTE static Application* sharedApplication(); CC_DEPRECATED_ATTRIBUTE static Application* sharedApplication();
/* override functions */ /* override functions */
virtual ccLanguageType getCurrentLanguage(); virtual LanguageType getCurrentLanguage();
/** /**
* Sets the Resource root path. * Sets the Resource root path.
@ -59,7 +59,7 @@ public:
/** /**
@brief Get target platform @brief Get target platform
*/ */
virtual TargetPlatform getTargetPlatform(); virtual Platform getTargetPlatform();
protected: protected:
long _animationInterval; //micro second long _animationInterval; //micro second
std::string _resourceRootPath; std::string _resourceRootPath;

View File

@ -23,7 +23,12 @@ FileUtils* FileUtils::getInstance()
if (s_sharedFileUtils == NULL) if (s_sharedFileUtils == NULL)
{ {
s_sharedFileUtils = new FileUtilsLinux(); s_sharedFileUtils = new FileUtilsLinux();
s_sharedFileUtils->init(); if(!s_sharedFileUtils->init())
{
delete s_sharedFileUtils;
s_sharedFileUtils = NULL;
CCLOG("ERROR: Could not init CCFileUtilsLinux");
}
} }
return s_sharedFileUtils; return s_sharedFileUtils;
} }

View File

@ -65,12 +65,12 @@ public:
@brief Get current language config @brief Get current language config
@return Current language config @return Current language config
*/ */
virtual ccLanguageType getCurrentLanguage(); virtual LanguageType getCurrentLanguage();
/** /**
@brief Get target platform @brief Get target platform
*/ */
virtual TargetPlatform getTargetPlatform(); virtual Platform getTargetPlatform();
/** /**
* Sets the Resource root path. * Sets the Resource root path.

View File

@ -60,9 +60,9 @@ void Application::setAnimationInterval(double interval)
[[CCDirectorCaller sharedDirectorCaller] setAnimationInterval: interval ]; [[CCDirectorCaller sharedDirectorCaller] setAnimationInterval: interval ];
} }
TargetPlatform Application::getTargetPlatform() Application::Platform Application::getTargetPlatform()
{ {
return kTargetMacOS; return Platform::OS_MAC;
} }
///////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////
@ -81,7 +81,7 @@ Application* Application::sharedApplication()
return Application::getInstance(); return Application::getInstance();
} }
ccLanguageType Application::getCurrentLanguage() LanguageType Application::getCurrentLanguage()
{ {
// get the current language and country config // get the current language and country config
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
@ -92,52 +92,52 @@ ccLanguageType Application::getCurrentLanguage()
NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage]; NSDictionary* temp = [NSLocale componentsFromLocaleIdentifier:currentLanguage];
NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode]; NSString * languageCode = [temp objectForKey:NSLocaleLanguageCode];
ccLanguageType ret = kLanguageEnglish; LanguageType ret = LanguageType::ENGLISH;
if ([languageCode isEqualToString:@"zh"]) if ([languageCode isEqualToString:@"zh"])
{ {
ret = kLanguageChinese; ret = LanguageType::CHINESE;
} }
else if ([languageCode isEqualToString:@"en"]) else if ([languageCode isEqualToString:@"en"])
{ {
ret = kLanguageEnglish; ret = LanguageType::ENGLISH;;
} }
else if ([languageCode isEqualToString:@"fr"]){ else if ([languageCode isEqualToString:@"fr"]){
ret = kLanguageFrench; ret = LanguageType::FRENCH;
} }
else if ([languageCode isEqualToString:@"it"]){ else if ([languageCode isEqualToString:@"it"]){
ret = kLanguageItalian; ret = LanguageType::ITALIAN;
} }
else if ([languageCode isEqualToString:@"de"]){ else if ([languageCode isEqualToString:@"de"]){
ret = kLanguageGerman; ret = LanguageType::GERMAN;
} }
else if ([languageCode isEqualToString:@"es"]){ else if ([languageCode isEqualToString:@"es"]){
ret = kLanguageSpanish; ret = LanguageType::SPANISH;
} }
else if ([languageCode isEqualToString:@"ru"]){ else if ([languageCode isEqualToString:@"ru"]){
ret = kLanguageRussian; ret = LanguageType::RUSSIAN;
} }
else if ([languageCode isEqualToString:@"ko"]){ else if ([languageCode isEqualToString:@"ko"]){
ret = kLanguageKorean; ret = LanguageType::KOREAN;
} }
else if ([languageCode isEqualToString:@"ja"]){ else if ([languageCode isEqualToString:@"ja"]){
ret = kLanguageJapanese; ret = LanguageType::JAPANESE;
} }
else if ([languageCode isEqualToString:@"hu"]){ else if ([languageCode isEqualToString:@"hu"]){
ret = kLanguageHungarian; ret = LanguageType::HUNGARIAN;
} }
else if ([languageCode isEqualToString:@"pt"]) else if ([languageCode isEqualToString:@"pt"])
{ {
ret = kLanguagePortuguese; ret = LanguageType::PORTUGUESE;
} }
else if ([languageCode isEqualToString:@"ar"]) else if ([languageCode isEqualToString:@"ar"])
{ {
ret = kLanguageArabic; ret = LanguageType::ARABIC;
} }
else if ([languageCode isEqualToString:@"nb"]){ else if ([languageCode isEqualToString:@"nb"]){
ret = kLanguageNorwegian; ret = LanguageType::NORWEGIAN;
} }
else if ([languageCode isEqualToString:@"pl"]){ else if ([languageCode isEqualToString:@"pl"]){
ret = kLanguagePolish; ret = LanguageType::POLISH;
} }
return ret; return ret;
} }

View File

@ -210,7 +210,12 @@ FileUtils* FileUtils::getInstance()
if (s_sharedFileUtils == NULL) if (s_sharedFileUtils == NULL)
{ {
s_sharedFileUtils = new FileUtilsMac(); s_sharedFileUtils = new FileUtilsMac();
s_sharedFileUtils->init(); if(!s_sharedFileUtils->init())
{
delete s_sharedFileUtils;
s_sharedFileUtils = NULL;
CCLOG("ERROR: Could not init CCFileUtilsMac");
}
} }
return s_sharedFileUtils; return s_sharedFileUtils;
} }

View File

@ -68,7 +68,7 @@ static bool _initPremultipliedATextureWithImage(CGImageRef image, NSUInteger POT
bool hasAlpha; bool hasAlpha;
CGImageAlphaInfo info; CGImageAlphaInfo info;
CGSize imageSize; CGSize imageSize;
Texture2DPixelFormat pixelFormat; Texture2D::PixelFormat pixelFormat;
info = CGImageGetAlphaInfo(image); info = CGImageGetAlphaInfo(image);
hasAlpha = ((info == kCGImageAlphaPremultipliedLast) || (info == kCGImageAlphaPremultipliedFirst) || (info == kCGImageAlphaLast) || (info == kCGImageAlphaFirst) ? YES : NO); hasAlpha = ((info == kCGImageAlphaPremultipliedLast) || (info == kCGImageAlphaPremultipliedFirst) || (info == kCGImageAlphaLast) || (info == kCGImageAlphaFirst) ? YES : NO);
@ -80,17 +80,17 @@ static bool _initPremultipliedATextureWithImage(CGImageRef image, NSUInteger POT
{ {
if(hasAlpha || bpp >= 8) if(hasAlpha || bpp >= 8)
{ {
pixelFormat = kTexture2DPixelFormat_Default; pixelFormat = Texture2D::PixelFormat::DEFAULT;
} }
else else
{ {
pixelFormat = kTexture2DPixelFormat_RGB565; pixelFormat = Texture2D::PixelFormat::RGB565;
} }
} }
else else
{ {
// NOTE: No colorspace means a mask image // NOTE: No colorspace means a mask image
pixelFormat = kTexture2DPixelFormat_A8; pixelFormat = Texture2D::PixelFormat::A8;
} }
imageSize.width = CGImageGetWidth(image); imageSize.width = CGImageGetWidth(image);
@ -100,9 +100,9 @@ static bool _initPremultipliedATextureWithImage(CGImageRef image, NSUInteger POT
switch(pixelFormat) switch(pixelFormat)
{ {
case kTexture2DPixelFormat_RGBA8888: case Texture2D::PixelFormat::RGBA8888:
case kTexture2DPixelFormat_RGBA4444: case Texture2D::PixelFormat::RGBA4444:
case kTexture2DPixelFormat_RGB5A1: case Texture2D::PixelFormat::RGB5A1:
colorSpace = CGColorSpaceCreateDeviceRGB(); colorSpace = CGColorSpaceCreateDeviceRGB();
data = new unsigned char[POTHigh * POTWide * 4]; data = new unsigned char[POTHigh * POTWide * 4];
info = hasAlpha ? kCGImageAlphaPremultipliedLast : kCGImageAlphaNoneSkipLast; info = hasAlpha ? kCGImageAlphaPremultipliedLast : kCGImageAlphaNoneSkipLast;
@ -110,14 +110,14 @@ static bool _initPremultipliedATextureWithImage(CGImageRef image, NSUInteger POT
CGColorSpaceRelease(colorSpace); CGColorSpaceRelease(colorSpace);
break; break;
case kTexture2DPixelFormat_RGB565: case Texture2D::PixelFormat::RGB565:
colorSpace = CGColorSpaceCreateDeviceRGB(); colorSpace = CGColorSpaceCreateDeviceRGB();
data = new unsigned char[POTHigh * POTWide * 4]; data = new unsigned char[POTHigh * POTWide * 4];
info = kCGImageAlphaNoneSkipLast; info = kCGImageAlphaNoneSkipLast;
context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, 4 * POTWide, colorSpace, info | kCGBitmapByteOrder32Big); context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, 4 * POTWide, colorSpace, info | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace); CGColorSpaceRelease(colorSpace);
break; break;
case kTexture2DPixelFormat_A8: case Texture2D::PixelFormat::A8:
data = new unsigned char[POTHigh * POTWide]; data = new unsigned char[POTHigh * POTWide];
info = kCGImageAlphaOnly; info = kCGImageAlphaOnly;
context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, POTWide, NULL, info); context = CGBitmapContextCreate(data, POTWide, POTHigh, 8, POTWide, NULL, info);
@ -138,7 +138,7 @@ static bool _initPremultipliedATextureWithImage(CGImageRef image, NSUInteger POT
// Repack the pixel data into the right format // Repack the pixel data into the right format
if(pixelFormat == kTexture2DPixelFormat_RGB565) if(pixelFormat == Texture2D::PixelFormat::RGB565)
{ {
//Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB" //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB"
tempData = new unsigned char[POTHigh * POTWide * 2]; tempData = new unsigned char[POTHigh * POTWide * 2];
@ -153,7 +153,7 @@ static bool _initPremultipliedATextureWithImage(CGImageRef image, NSUInteger POT
data = tempData; data = tempData;
} }
else if (pixelFormat == kTexture2DPixelFormat_RGBA4444) else if (pixelFormat == Texture2D::PixelFormat::RGBA4444)
{ {
//Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRGGGGBBBBAAAA" //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRGGGGBBBBAAAA"
tempData = new unsigned char[POTHigh * POTWide * 2]; tempData = new unsigned char[POTHigh * POTWide * 2];
@ -172,7 +172,7 @@ static bool _initPremultipliedATextureWithImage(CGImageRef image, NSUInteger POT
data = tempData; data = tempData;
} }
else if (pixelFormat == kTexture2DPixelFormat_RGB5A1) else if (pixelFormat == Texture2D::PixelFormat::RGB5A1)
{ {
//Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA" //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA"
tempData = new unsigned char[POTHigh * POTWide * 2]; tempData = new unsigned char[POTHigh * POTWide * 2];
@ -542,7 +542,7 @@ Image::~Image()
CC_SAFE_DELETE_ARRAY(_data); CC_SAFE_DELETE_ARRAY(_data);
} }
bool Image::initWithImageFile(const char * strPath, EImageFormat eImgFmt/* = eFmtPng*/) bool Image::initWithImageFile(const char * strPath, Format eImgFmt/* = eFmtPng*/)
{ {
std::string strTemp = FileUtils::getInstance()->fullPathForFilename(strPath); std::string strTemp = FileUtils::getInstance()->fullPathForFilename(strPath);
if (_enabledScale) if (_enabledScale)
@ -585,7 +585,7 @@ bool Image::initWithImageFile(const char * strPath, EImageFormat eImgFmt/* = eFm
return ret; return ret;
} }
bool Image::initWithImageFileThreadSafe(const char *fullpath, EImageFormat imageType) bool Image::initWithImageFileThreadSafe(const char *fullpath, Format imageType)
{ {
/* /*
* FileUtils::fullPathFromRelativePath() is not thread-safe, it use autorelease(). * FileUtils::fullPathFromRelativePath() is not thread-safe, it use autorelease().
@ -612,7 +612,7 @@ bool Image::potImageData(unsigned int POTWide, unsigned int POTHigh)
unsigned int* inPixel32 = NULL; unsigned int* inPixel32 = NULL;
unsigned short* outPixel16 = NULL; unsigned short* outPixel16 = NULL;
bool hasAlpha; bool hasAlpha;
Texture2DPixelFormat pixelFormat; Texture2D::PixelFormat pixelFormat;
hasAlpha = this->hasAlpha(); hasAlpha = this->hasAlpha();
@ -627,21 +627,21 @@ bool Image::potImageData(unsigned int POTWide, unsigned int POTHigh)
{ {
if (bpp >= 8) if (bpp >= 8)
{ {
pixelFormat = kTexture2DPixelFormat_RGB888; pixelFormat = Texture2D::PixelFormat::RGB888;
} }
else else
{ {
CCLOG("cocos2d: Texture2D: Using RGB565 texture since image has no alpha"); CCLOG("cocos2d: Texture2D: Using RGB565 texture since image has no alpha");
pixelFormat = kTexture2DPixelFormat_RGB565; pixelFormat = Texture2D::PixelFormat::RGB565;
} }
} }
switch(pixelFormat) { switch(pixelFormat) {
case kTexture2DPixelFormat_RGBA8888: case Texture2D::PixelFormat::RGBA8888:
case kTexture2DPixelFormat_RGBA4444: case Texture2D::PixelFormat::RGBA4444:
case kTexture2DPixelFormat_RGB5A1: case Texture2D::PixelFormat::RGB5A1:
case kTexture2DPixelFormat_RGB565: case Texture2D::PixelFormat::RGB565:
case kTexture2DPixelFormat_A8: case Texture2D::PixelFormat::A8:
tempData = (unsigned char*)(this->getData()); tempData = (unsigned char*)(this->getData());
CCASSERT(tempData != NULL, "NULL image data."); CCASSERT(tempData != NULL, "NULL image data.");
@ -666,7 +666,7 @@ bool Image::potImageData(unsigned int POTWide, unsigned int POTHigh)
} }
break; break;
case kTexture2DPixelFormat_RGB888: case Texture2D::PixelFormat::RGB888:
tempData = (unsigned char*)(this->getData()); tempData = (unsigned char*)(this->getData());
CCASSERT(tempData != NULL, "NULL image data."); CCASSERT(tempData != NULL, "NULL image data.");
if(this->getWidth() == (short)POTWide && this->getHeight() == (short)POTHigh) if(this->getWidth() == (short)POTWide && this->getHeight() == (short)POTHigh)
@ -695,7 +695,7 @@ bool Image::potImageData(unsigned int POTWide, unsigned int POTHigh)
// Repack the pixel data into the right format // Repack the pixel data into the right format
if(pixelFormat == kTexture2DPixelFormat_RGB565) { if(pixelFormat == Texture2D::PixelFormat::RGB565) {
//Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB" //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB"
tempData = new unsigned char[POTHigh * POTWide * 2]; tempData = new unsigned char[POTHigh * POTWide * 2];
inPixel32 = (unsigned int*)data; inPixel32 = (unsigned int*)data;
@ -713,7 +713,7 @@ bool Image::potImageData(unsigned int POTWide, unsigned int POTHigh)
delete [] data; delete [] data;
data = tempData; data = tempData;
} }
else if (pixelFormat == kTexture2DPixelFormat_RGBA4444) { else if (pixelFormat == Texture2D::PixelFormat::RGBA4444) {
//Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRGGGGBBBBAAAA" //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRGGGGBBBBAAAA"
tempData = new unsigned char[POTHigh * POTWide * 2]; tempData = new unsigned char[POTHigh * POTWide * 2];
inPixel32 = (unsigned int*)data; inPixel32 = (unsigned int*)data;
@ -732,7 +732,7 @@ bool Image::potImageData(unsigned int POTWide, unsigned int POTHigh)
delete [] data; delete [] data;
data = tempData; data = tempData;
} }
else if (pixelFormat == kTexture2DPixelFormat_RGB5A1) { else if (pixelFormat == Texture2D::PixelFormat::RGB5A1) {
//Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA" //Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA"
tempData = new unsigned char[POTHigh * POTWide * 2]; tempData = new unsigned char[POTHigh * POTWide * 2];
inPixel32 = (unsigned int*)data; inPixel32 = (unsigned int*)data;
@ -751,10 +751,10 @@ bool Image::potImageData(unsigned int POTWide, unsigned int POTHigh)
delete []data; delete []data;
data = tempData; data = tempData;
} }
else if (pixelFormat == kTexture2DPixelFormat_A8) else if (pixelFormat == Texture2D::PixelFormat::A8)
{ {
// fix me, how to convert to A8 // fix me, how to convert to A8
pixelFormat = kTexture2DPixelFormat_RGBA8888; pixelFormat = Texture2D::PixelFormat::RGBA8888;
// //
//The code can not work, how to convert to A8? //The code can not work, how to convert to A8?
@ -786,7 +786,7 @@ bool Image::potImageData(unsigned int POTWide, unsigned int POTHigh)
//bool Image::initWithImageData(void * pData, int nDataLen, EImageFormat eFmt/* = eSrcFmtPng*/) //bool Image::initWithImageData(void * pData, int nDataLen, EImageFormat eFmt/* = eSrcFmtPng*/)
bool Image::initWithImageData(void * pData, bool Image::initWithImageData(void * pData,
int nDataLen, int nDataLen,
EImageFormat eFmt, Format eFmt,
int nWidth, int nWidth,
int nHeight, int nHeight,
int nBitsPerComponent) int nBitsPerComponent)
@ -797,13 +797,13 @@ bool Image::initWithImageData(void * pData,
{ {
CC_BREAK_IF(! pData || nDataLen <= 0); CC_BREAK_IF(! pData || nDataLen <= 0);
if (eFmt == kFmtRawData) if (eFmt == Format::RAW_DATA)
{ {
bRet = initWithRawData(pData, nDataLen, nWidth, nHeight, nBitsPerComponent, false); bRet = initWithRawData(pData, nDataLen, nWidth, nHeight, nBitsPerComponent, false);
} }
else if (eFmt == Image::kFmtWebp) else if (eFmt == Image::Format::WEBP)
{ {
bRet = _initWithWebpData(pData, nDataLen); bRet = initWithWebpData(pData, nDataLen);
} }
else else
{ {
@ -813,7 +813,7 @@ bool Image::initWithImageData(void * pData,
_height = (short)info.height; _height = (short)info.height;
_width = (short)info.width; _width = (short)info.width;
_bitsPerComponent = info.bitsPerComponent; _bitsPerComponent = info.bitsPerComponent;
if (eFmt == kFmtJpg) if (eFmt == Format::JPG)
{ {
_hasAlpha = true; _hasAlpha = true;
_preMulti = false; _preMulti = false;

View File

@ -90,9 +90,9 @@ void Application::setAnimationInterval(double interval)
_animationInterval = interval * 1000.0f; _animationInterval = interval * 1000.0f;
} }
TargetPlatform Application::getTargetPlatform() Application::Platform Application::getTargetPlatform()
{ {
return kTargetNaCl; return Platform::OS_NACL;
} }
Application* Application::getInstance() Application* Application::getInstance()
@ -107,9 +107,9 @@ Application* Application::sharedApplication()
return Application::getInstance(); return Application::getInstance();
} }
ccLanguageType Application::getCurrentLanguage() LanguageType Application::getCurrentLanguage()
{ {
ccLanguageType ret = kLanguageEnglish; LanguageType ret = LanguageType::ENGLISH;
return ret; return ret;
} }

View File

@ -58,12 +58,12 @@ public:
CC_DEPRECATED_ATTRIBUTE static Application* sharedApplication(); CC_DEPRECATED_ATTRIBUTE static Application* sharedApplication();
/* override functions */ /* override functions */
virtual ccLanguageType getCurrentLanguage(); virtual LanguageType getCurrentLanguage();
/** /**
@brief Get target platform @brief Get target platform
*/ */
virtual TargetPlatform getTargetPlatform(); virtual Platform getTargetPlatform();
static bool isRunning() { return s_running; } static bool isRunning() { return s_running; }
protected: protected:

View File

@ -35,7 +35,12 @@ FileUtils* FileUtils::getInstance()
if (s_sharedFileUtils == NULL) if (s_sharedFileUtils == NULL)
{ {
s_sharedFileUtils = new FileUtilsNaCl(); s_sharedFileUtils = new FileUtilsNaCl();
s_sharedFileUtils->init(); if(!s_sharedFileUtils->init())
{
delete s_sharedFileUtils;
s_sharedFileUtils = NULL;
CCLOG("ERROR: Could not init CCFileUtilsNacl");
}
} }
return s_sharedFileUtils; return s_sharedFileUtils;
} }

View File

@ -84,12 +84,12 @@ Application* Application::sharedApplication()
return Application::getInstance(); return Application::getInstance();
} }
ccLanguageType Application::getCurrentLanguage() LanguageType Application::getCurrentLanguage()
{ {
result r = E_SUCCESS; result r = E_SUCCESS;
int index = 0; int index = 0;
Tizen::Base::String localelanguageCode, languageCode; Tizen::Base::String localelanguageCode, languageCode;
ccLanguageType ret = kLanguageEnglish; LanguageType ret = LanguageType::ENGLISH;
r = SettingInfo::GetValue(L"http://tizen.org/setting/locale.language", localelanguageCode); r = SettingInfo::GetValue(L"http://tizen.org/setting/locale.language", localelanguageCode);
TryLog(!IsFailed(r), "[%s] Cannot get the current language setting", GetErrorMessage(r)); TryLog(!IsFailed(r), "[%s] Cannot get the current language setting", GetErrorMessage(r));
@ -98,66 +98,66 @@ ccLanguageType Application::getCurrentLanguage()
if (0 == languageCode.CompareTo(L"zho")) if (0 == languageCode.CompareTo(L"zho"))
{ {
ret = kLanguageChinese; ret = LanguageType::CHINESE;
} }
else if (0 == languageCode.CompareTo(L"eng")) else if (0 == languageCode.CompareTo(L"eng"))
{ {
ret = kLanguageEnglish; ret = LanguageType::ENGLISH;
} }
else if (0 == languageCode.CompareTo(L"fre")) else if (0 == languageCode.CompareTo(L"fre"))
{ {
ret = kLanguageFrench; ret = LanguageType::FRENCH;
} }
else if (0 == languageCode.CompareTo(L"ita")) else if (0 == languageCode.CompareTo(L"ita"))
{ {
ret = kLanguageItalian; ret = LanguageType::ITALIAN;
} }
else if (0 == languageCode.CompareTo(L"deu")) else if (0 == languageCode.CompareTo(L"deu"))
{ {
ret = kLanguageGerman; ret = LanguageType::GERMAN;
} }
else if (0 == languageCode.CompareTo(L"spa")) else if (0 == languageCode.CompareTo(L"spa"))
{ {
ret = kLanguageSpanish; ret = LanguageType::SPANISH;
} }
else if (0 == languageCode.CompareTo(L"rus")) else if (0 == languageCode.CompareTo(L"rus"))
{ {
ret = kLanguageRussian; ret = LanguageType::RUSSIAN;
} }
else if (0 == languageCode.CompareTo(L"kor")) else if (0 == languageCode.CompareTo(L"kor"))
{ {
ret = kLanguageKorean; ret = LanguageType::KOREAN;
} }
else if (0 == languageCode.CompareTo(L"jpn")) else if (0 == languageCode.CompareTo(L"jpn"))
{ {
ret = kLanguageJapanese; ret = LanguageType::JAPANESE;
} }
else if (0 == languageCode.CompareTo(L"hun")) else if (0 == languageCode.CompareTo(L"hun"))
{ {
ret = kLanguageHungarian; ret = LanguageType::HUNGARIAN;
} }
else if (0 == languageCode.CompareTo(L"por")) else if (0 == languageCode.CompareTo(L"por"))
{ {
ret = kLanguagePortuguese; ret = LanguageType::PORTUGUESE;
} }
else if (0 == languageCode.CompareTo(L"ara")) else if (0 == languageCode.CompareTo(L"ara"))
{ {
ret = kLanguageArabic; ret = LanguageType::ARABIC;
} }
else if (0 == languageCode.CompareTo(L"nor")) else if (0 == languageCode.CompareTo(L"nor"))
{ {
ret = kLanguageNorwegian; ret = LanguageType::NORWEGIAN;
} }
else if (0 == languageCode.CompareTo(L"pol")) else if (0 == languageCode.CompareTo(L"pol"))
{ {
ret = kLanguagePolish; ret = LanguageType::POLISH;
} }
return ret; return ret;
} }
TargetPlatform Application::getTargetPlatform() Application::Platform Application::getTargetPlatform()
{ {
return kTargetTizen; return Platform::OS_TIZEN;
} }
NS_CC_END NS_CC_END

View File

@ -66,12 +66,12 @@ public:
@brief Get current language config @brief Get current language config
@return Current language config @return Current language config
*/ */
virtual ccLanguageType getCurrentLanguage(); virtual LanguageType getCurrentLanguage();
/** /**
@brief Get target platform @brief Get target platform
*/ */
virtual TargetPlatform getTargetPlatform(); virtual Platform getTargetPlatform();
protected: protected:
static Application * sm_pSharedApplication; static Application * sm_pSharedApplication;

View File

@ -45,7 +45,12 @@ FileUtils* FileUtils::getInstance()
if (s_sharedFileUtils == NULL) if (s_sharedFileUtils == NULL)
{ {
s_sharedFileUtils = new FileUtilsTizen(); s_sharedFileUtils = new FileUtilsTizen();
s_sharedFileUtils->init(); if(!s_sharedFileUtils->init())
{
delete s_sharedFileUtils;
s_sharedFileUtils = NULL;
CCLOG("ERROR: Could not init CCFileUtilsTizen");
}
} }
return s_sharedFileUtils; return s_sharedFileUtils;
} }

View File

@ -112,9 +112,9 @@ Application* Application::sharedApplication()
return Application::getInstance(); return Application::getInstance();
} }
ccLanguageType Application::getCurrentLanguage() LanguageType Application::getCurrentLanguage()
{ {
ccLanguageType ret = kLanguageEnglish; LanguageType ret = LanguageType::ENGLISH;
LCID localeID = GetUserDefaultLCID(); LCID localeID = GetUserDefaultLCID();
unsigned short primaryLanguageID = localeID & 0xFF; unsigned short primaryLanguageID = localeID & 0xFF;
@ -122,55 +122,55 @@ ccLanguageType Application::getCurrentLanguage()
switch (primaryLanguageID) switch (primaryLanguageID)
{ {
case LANG_CHINESE: case LANG_CHINESE:
ret = kLanguageChinese; ret = LanguageType::CHINESE;
break; break;
case LANG_ENGLISH: case LANG_ENGLISH:
ret = kLanguageEnglish; ret = LanguageType::ENGLISH;
break; break;
case LANG_FRENCH: case LANG_FRENCH:
ret = kLanguageFrench; ret = LanguageType::FRENCH;
break; break;
case LANG_ITALIAN: case LANG_ITALIAN:
ret = kLanguageItalian; ret = LanguageType::ITALIAN;
break; break;
case LANG_GERMAN: case LANG_GERMAN:
ret = kLanguageGerman; ret = LanguageType::GERMAN;
break; break;
case LANG_SPANISH: case LANG_SPANISH:
ret = kLanguageSpanish; ret = LanguageType::SPANISH;
break; break;
case LANG_RUSSIAN: case LANG_RUSSIAN:
ret = kLanguageRussian; ret = LanguageType::RUSSIAN;
break; break;
case LANG_KOREAN: case LANG_KOREAN:
ret = kLanguageKorean; ret = LanguageType::KOREAN;
break; break;
case LANG_JAPANESE: case LANG_JAPANESE:
ret = kLanguageJapanese; ret = LanguageType::JAPANESE;
break; break;
case LANG_HUNGARIAN: case LANG_HUNGARIAN:
ret = kLanguageHungarian; ret = LanguageType::HUNGARIAN;
break; break;
case LANG_PORTUGUESE: case LANG_PORTUGUESE:
ret = kLanguagePortuguese; ret = LanguageType::PORTUGUESE;
break; break;
case LANG_ARABIC: case LANG_ARABIC:
ret = kLanguageArabic; ret = LanguageType::ARABIC;
break; break;
case LANG_NORWEGIAN: case LANG_NORWEGIAN:
ret = kLanguageNorwegian; ret = LanguageType::NORWEGIAN;
break; break;
case LANG_POLISH: case LANG_POLISH:
ret = kLanguagePolish; ret = LanguageType::POLISH;
break; break;
} }
return ret; return ret;
} }
TargetPlatform Application::getTargetPlatform() Application::Platform Application::getTargetPlatform()
{ {
return kTargetWindows; return Platform::OS_WINDOWS;
} }
void Application::setResourceRootPath(const std::string& rootResDir) void Application::setResourceRootPath(const std::string& rootResDir)

View File

@ -32,12 +32,12 @@ public:
/* override functions */ /* override functions */
virtual void setAnimationInterval(double interval); virtual void setAnimationInterval(double interval);
virtual ccLanguageType getCurrentLanguage(); virtual LanguageType getCurrentLanguage();
/** /**
@brief Get target platform @brief Get target platform
*/ */
virtual TargetPlatform getTargetPlatform(); virtual Platform getTargetPlatform();
/** /**
* Sets the Resource root path. * Sets the Resource root path.

View File

@ -48,7 +48,12 @@ FileUtils* FileUtils::getInstance()
if (s_sharedFileUtils == NULL) if (s_sharedFileUtils == NULL)
{ {
s_sharedFileUtils = new FileUtilsWin32(); s_sharedFileUtils = new FileUtilsWin32();
s_sharedFileUtils->init(); if(!s_sharedFileUtils->init())
{
delete s_sharedFileUtils;
s_sharedFileUtils = NULL;
CCLOG("ERROR: Could not init CCFileUtilsWin32");
}
} }
return s_sharedFileUtils; return s_sharedFileUtils;
} }

View File

@ -103,5 +103,9 @@ NS_CC_END
#undef MessageBox #undef MessageBox
#endif #endif
#ifdef RELATIVE
#undef RELATIVE
#endif
#endif // __CC_STD_C_H__ #endif // __CC_STD_C_H__

View File

@ -97,9 +97,12 @@ STATICLIBS = \
SHAREDLIBS += -L$(LIB_DIR) -Wl,-rpath,$(RPATH_REL)/$(LIB_DIR) SHAREDLIBS += -L$(LIB_DIR) -Wl,-rpath,$(RPATH_REL)/$(LIB_DIR)
LIBS = -lrt -lz LIBS = -lrt -lz
HTMLTPL_DIR = $(COCOS_ROOT)/tools/emscripten-template
HTMLTPL_FILE = index.html
clean: clean:
rm -rf $(OBJ_DIR) rm -rf $(OBJ_DIR)
rm -f $(TARGET).js $(TARGET).data $(TARGET).data.js $(BIN_DIR)/index.html core rm -rf $(TARGET).js $(TARGET).data $(TARGET).data.js $(BIN_DIR) core
.PHONY: all clean .PHONY: all clean
@ -108,7 +111,7 @@ clean:
ifdef EXECUTABLE ifdef EXECUTABLE
TARGET := $(BIN_DIR)/$(EXECUTABLE) TARGET := $(BIN_DIR)/$(EXECUTABLE)
all: $(TARGET).js $(TARGET).data $(BIN_DIR)/index.html all: $(TARGET).js $(TARGET).data $(BIN_DIR)/$(HTMLTPL_FILE)
run: $(TARGET) run: $(TARGET)
cd $(dir $^) && ./$(notdir $^) cd $(dir $^) && ./$(notdir $^)

View File

@ -136,7 +136,8 @@ SOURCES = ../actions/CCAction.cpp \
../CCScheduler.cpp \ ../CCScheduler.cpp \
../ccFPSImages.c \ ../ccFPSImages.c \
../ccTypes.cpp \ ../ccTypes.cpp \
../cocos2d.cpp ../cocos2d.cpp \
../CCDeprecated.cpp
COCOS_ROOT = ../.. COCOS_ROOT = ../..

View File

@ -130,7 +130,8 @@ SOURCES = ../actions/CCAction.cpp \
../CCScheduler.cpp \ ../CCScheduler.cpp \
../ccFPSImages.c \ ../ccFPSImages.c \
../ccTypes.cpp \ ../ccTypes.cpp \
../cocos2d.cpp ../cocos2d.cpp \
../CCDeprecated.cpp
include cocos2dx.mk include cocos2dx.mk

View File

@ -142,6 +142,7 @@ xcopy /Y /Q "$(ProjectDir)..\platform\third_party\win32\libraries\*.*" "$(OutDir
<ItemGroup> <ItemGroup>
<ClCompile Include="..\base_nodes\CCAtlasNode.cpp" /> <ClCompile Include="..\base_nodes\CCAtlasNode.cpp" />
<ClCompile Include="..\base_nodes\CCNode.cpp" /> <ClCompile Include="..\base_nodes\CCNode.cpp" />
<ClCompile Include="..\CCDeprecated.cpp" />
<ClCompile Include="..\ccFPSImages.c" /> <ClCompile Include="..\ccFPSImages.c" />
<ClCompile Include="..\ccTypes.cpp" /> <ClCompile Include="..\ccTypes.cpp" />
<ClCompile Include="..\cocoa\CCAffineTransform.cpp" /> <ClCompile Include="..\cocoa\CCAffineTransform.cpp" />

View File

@ -481,6 +481,7 @@
<Filter>keyboard_dispatcher</Filter> <Filter>keyboard_dispatcher</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="..\ccTypes.cpp" /> <ClCompile Include="..\ccTypes.cpp" />
<ClCompile Include="..\CCDeprecated.cpp" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClInclude Include="..\base_nodes\CCAtlasNode.h"> <ClInclude Include="..\base_nodes\CCAtlasNode.h">

View File

@ -45,6 +45,31 @@ typedef struct _hashUniformEntry
UT_hash_handle hh; // hash entry UT_hash_handle hh; // hash entry
} tHashUniformEntry; } tHashUniformEntry;
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR = "ShaderPositionTextureColor";
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST = "ShaderPositionTextureColorAlphaTest";
const char* GLProgram::SHADER_NAME_POSITION_COLOR = "ShaderPositionColor";
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE = "ShaderPositionTexture";
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_U_COLOR = "ShaderPositionTexture_uColor";
const char* GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR = "ShaderPositionTextureA8Color";
const char* GLProgram::SHADER_NAME_POSITION_U_COLOR = "ShaderPosition_uColor";
const char* GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR = "ShaderPositionLengthTextureColor";
// uniform names
const char* GLProgram::UNIFORM_NAME_P_MATRIX = "CC_PMatrix";
const char* GLProgram::UNIFORM_NAME_MV_MATRIX = "CC_MVMatrix";
const char* GLProgram::UNIFORM_NAME_MVP_MATRIX = "CC_MVPMatrix";
const char* GLProgram::UNIFORM_NAME_TIME = "CC_Time";
const char* GLProgram::UNIFORM_NAME_SIN_TIME = "CC_SinTime";
const char* GLProgram::UNIFORM_NAME_COS_TIME = "CC_CosTime";
const char* GLProgram::UNIFORM_NAME_RANDOM01 = "CC_Random01";
const char* GLProgram::UNIFORM_NAME_SAMPLER = "CC_Texture0";
const char* GLProgram::UNIFORM_NAME_ALPHA_TEST_VALUE = "CC_alpha_value";
// Attribute names
const char* GLProgram::ATTRIBUTE_NAME_COLOR = "a_color";
const char* GLProgram::ATTRIBUTE_NAME_POSITION = "a_position";
const char* GLProgram::ATTRIBUTE_NAME_TEX_COORD = "a_texCoord";
GLProgram::GLProgram() GLProgram::GLProgram()
: _program(0) : _program(0)
, _vertShader(0) , _vertShader(0)
@ -65,7 +90,7 @@ GLProgram::~GLProgram()
if (_program) if (_program)
{ {
ccGLDeleteProgram(_program); GL::deleteProgram(_program);
} }
tHashUniformEntry *current_element, *tmp; tHashUniformEntry *current_element, *tmp;
@ -197,28 +222,28 @@ void GLProgram::addAttribute(const char* attributeName, GLuint index)
void GLProgram::updateUniforms() void GLProgram::updateUniforms()
{ {
_uniforms[kUniformPMatrix] = glGetUniformLocation(_program, kUniformPMatrix_s); _uniforms[UNIFORM_P_MATRIX] = glGetUniformLocation(_program, UNIFORM_NAME_P_MATRIX);
_uniforms[kUniformMVMatrix] = glGetUniformLocation(_program, kUniformMVMatrix_s); _uniforms[UNIFORM_MV_MATRIX] = glGetUniformLocation(_program, GLProgram::UNIFORM_NAME_MV_MATRIX);
_uniforms[kUniformMVPMatrix] = glGetUniformLocation(_program, kUniformMVPMatrix_s); _uniforms[UNIFORM_MVP_MATRIX] = glGetUniformLocation(_program, GLProgram::UNIFORM_NAME_MVP_MATRIX);
_uniforms[kUniformTime] = glGetUniformLocation(_program, kUniformTime_s); _uniforms[GLProgram::UNIFORM_TIME] = glGetUniformLocation(_program, GLProgram::UNIFORM_NAME_TIME);
_uniforms[kUniformSinTime] = glGetUniformLocation(_program, kUniformSinTime_s); _uniforms[GLProgram::UNIFORM_SIN_TIME] = glGetUniformLocation(_program, GLProgram::UNIFORM_NAME_SIN_TIME);
_uniforms[kUniformCosTime] = glGetUniformLocation(_program, kUniformCosTime_s); _uniforms[GLProgram::UNIFORM_COS_TIME] = glGetUniformLocation(_program, GLProgram::UNIFORM_NAME_COS_TIME);
_usesTime = ( _usesTime = (
_uniforms[kUniformTime] != -1 || _uniforms[GLProgram::UNIFORM_TIME] != -1 ||
_uniforms[kUniformSinTime] != -1 || _uniforms[GLProgram::UNIFORM_SIN_TIME] != -1 ||
_uniforms[kUniformCosTime] != -1 _uniforms[GLProgram::UNIFORM_COS_TIME] != -1
); );
_uniforms[kUniformRandom01] = glGetUniformLocation(_program, kUniformRandom01_s); _uniforms[UNIFORM_RANDOM01] = glGetUniformLocation(_program, UNIFORM_NAME_RANDOM01);
_uniforms[kUniformSampler] = glGetUniformLocation(_program, kUniformSampler_s); _uniforms[UNIFORM_SAMPLER] = glGetUniformLocation(_program, UNIFORM_NAME_SAMPLER);
this->use(); this->use();
// Since sample most probably won't change, set it to 0 now. // Since sample most probably won't change, set it to 0 now.
this->setUniformLocationWith1i(_uniforms[kUniformSampler], 0); this->setUniformLocationWith1i(_uniforms[GLProgram::UNIFORM_SAMPLER], 0);
} }
bool GLProgram::link() bool GLProgram::link()
@ -247,7 +272,7 @@ bool GLProgram::link()
if (status == GL_FALSE) if (status == GL_FALSE)
{ {
CCLOG("cocos2d: ERROR: Failed to link program: %i", _program); CCLOG("cocos2d: ERROR: Failed to link program: %i", _program);
ccGLDeleteProgram(_program); GL::deleteProgram(_program);
_program = 0; _program = 0;
} }
#endif #endif
@ -257,7 +282,7 @@ bool GLProgram::link()
void GLProgram::use() void GLProgram::use()
{ {
ccGLUseProgram(_program); GL::useProgram(_program);
} }
const char* GLProgram::logForOpenGLObject(GLuint object, GLInfoFunction infoFunc, GLLogFunction logFunc) const const char* GLProgram::logForOpenGLObject(GLuint object, GLInfoFunction infoFunc, GLLogFunction logFunc) const
@ -509,9 +534,9 @@ void GLProgram::setUniformsForBuiltins()
kmMat4Multiply(&matrixMVP, &matrixP, &matrixMV); kmMat4Multiply(&matrixMVP, &matrixP, &matrixMV);
setUniformLocationWithMatrix4fv(_uniforms[kUniformPMatrix], matrixP.mat, 1); setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_P_MATRIX], matrixP.mat, 1);
setUniformLocationWithMatrix4fv(_uniforms[kUniformMVMatrix], matrixMV.mat, 1); setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_MV_MATRIX], matrixMV.mat, 1);
setUniformLocationWithMatrix4fv(_uniforms[kUniformMVPMatrix], matrixMVP.mat, 1); setUniformLocationWithMatrix4fv(_uniforms[UNIFORM_MVP_MATRIX], matrixMVP.mat, 1);
if(_usesTime) if(_usesTime)
{ {
@ -521,14 +546,14 @@ void GLProgram::setUniformsForBuiltins()
// Getting Mach time per frame per shader using time could be extremely expensive. // Getting Mach time per frame per shader using time could be extremely expensive.
float time = director->getTotalFrames() * director->getAnimationInterval(); float time = director->getTotalFrames() * director->getAnimationInterval();
setUniformLocationWith4f(_uniforms[kUniformTime], time/10.0, time, time*2, time*4); setUniformLocationWith4f(_uniforms[GLProgram::UNIFORM_TIME], time/10.0, time, time*2, time*4);
setUniformLocationWith4f(_uniforms[kUniformSinTime], time/8.0, time/4.0, time/2.0, sinf(time)); setUniformLocationWith4f(_uniforms[GLProgram::UNIFORM_SIN_TIME], time/8.0, time/4.0, time/2.0, sinf(time));
setUniformLocationWith4f(_uniforms[kUniformCosTime], time/8.0, time/4.0, time/2.0, cosf(time)); setUniformLocationWith4f(_uniforms[GLProgram::UNIFORM_COS_TIME], time/8.0, time/4.0, time/2.0, cosf(time));
} }
if (_uniforms[kUniformRandom01] != -1) if (_uniforms[GLProgram::UNIFORM_RANDOM01] != -1)
{ {
setUniformLocationWith4f(_uniforms[kUniformRandom01], CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1()); setUniformLocationWith4f(_uniforms[GLProgram::UNIFORM_RANDOM01], CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1());
} }
} }
@ -539,7 +564,7 @@ void GLProgram::reset()
// it is already deallocated by android // it is already deallocated by android
//ccGLDeleteProgram(_program); //GL::deleteProgram(_program);
_program = 0; _program = 0;

View File

@ -40,52 +40,6 @@ NS_CC_BEGIN
* @{ * @{
*/ */
enum {
kVertexAttrib_Position,
kVertexAttrib_Color,
kVertexAttrib_TexCoords,
kVertexAttrib_MAX,
};
enum {
kUniformPMatrix,
kUniformMVMatrix,
kUniformMVPMatrix,
kUniformTime,
kUniformSinTime,
kUniformCosTime,
kUniformRandom01,
kUniformSampler,
kUniform_MAX,
};
#define kShader_PositionTextureColor "ShaderPositionTextureColor"
#define kShader_PositionTextureColorAlphaTest "ShaderPositionTextureColorAlphaTest"
#define kShader_PositionColor "ShaderPositionColor"
#define kShader_PositionTexture "ShaderPositionTexture"
#define kShader_PositionTexture_uColor "ShaderPositionTexture_uColor"
#define kShader_PositionTextureA8Color "ShaderPositionTextureA8Color"
#define kShader_Position_uColor "ShaderPosition_uColor"
#define kShader_PositionLengthTexureColor "ShaderPositionLengthTextureColor"
// uniform names
#define kUniformPMatrix_s "CC_PMatrix"
#define kUniformMVMatrix_s "CC_MVMatrix"
#define kUniformMVPMatrix_s "CC_MVPMatrix"
#define kUniformTime_s "CC_Time"
#define kUniformSinTime_s "CC_SinTime"
#define kUniformCosTime_s "CC_CosTime"
#define kUniformRandom01_s "CC_Random01"
#define kUniformSampler_s "CC_Texture0"
#define kUniformAlphaTestValue "CC_alpha_value"
// Attribute names
#define kAttributeNameColor "a_color"
#define kAttributeNamePosition "a_position"
#define kAttributeNameTexCoord "a_texCoord"
struct _hashUniformEntry; struct _hashUniformEntry;
typedef void (*GLInfoFunction)(GLuint program, GLenum pname, GLint* params); typedef void (*GLInfoFunction)(GLuint program, GLenum pname, GLint* params);
@ -100,6 +54,54 @@ typedef void (*GLLogFunction) (GLuint program, GLsizei bufsize, GLsizei* length,
class CC_DLL GLProgram : public Object class CC_DLL GLProgram : public Object
{ {
public: public:
enum
{
VERTEX_ATTRIB_POSITION,
VERTEX_ATTRIB_COLOR,
VERTEX_ATTRIB_TEX_COORDS,
VERTEX_ATTRIB_MAX,
};
enum
{
UNIFORM_P_MATRIX,
UNIFORM_MV_MATRIX,
UNIFORM_MVP_MATRIX,
UNIFORM_TIME,
UNIFORM_SIN_TIME,
UNIFORM_COS_TIME,
UNIFORM_RANDOM01,
UNIFORM_SAMPLER,
UNIFORM_MAX,
};
static const char* SHADER_NAME_POSITION_TEXTURE_COLOR;
static const char* SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST;
static const char* SHADER_NAME_POSITION_COLOR;
static const char* SHADER_NAME_POSITION_TEXTURE;
static const char* SHADER_NAME_POSITION_TEXTURE_U_COLOR;
static const char* SHADER_NAME_POSITION_TEXTURE_A8_COLOR;
static const char* SHADER_NAME_POSITION_U_COLOR;
static const char* SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR;
// uniform names
static const char* UNIFORM_NAME_P_MATRIX;
static const char* UNIFORM_NAME_MV_MATRIX;
static const char* UNIFORM_NAME_MVP_MATRIX;
static const char* UNIFORM_NAME_TIME;
static const char* UNIFORM_NAME_SIN_TIME;
static const char* UNIFORM_NAME_COS_TIME;
static const char* UNIFORM_NAME_RANDOM01;
static const char* UNIFORM_NAME_SAMPLER;
static const char* UNIFORM_NAME_ALPHA_TEST_VALUE;
// Attribute names
static const char* ATTRIBUTE_NAME_COLOR;
static const char* ATTRIBUTE_NAME_POSITION;
static const char* ATTRIBUTE_NAME_TEX_COORD;
GLProgram(); GLProgram();
virtual ~GLProgram(); virtual ~GLProgram();
/** Initializes the GLProgram with a vertex and fragment with bytes array */ /** Initializes the GLProgram with a vertex and fragment with bytes array */
@ -116,9 +118,9 @@ public:
- kUniformPMatrix - kUniformPMatrix
- kUniformMVMatrix - kUniformMVMatrix
- kUniformMVPMatrix - kUniformMVPMatrix
- kUniformSampler - GLProgram::UNIFORM_SAMPLER
And it will bind "kUniformSampler" to 0 And it will bind "GLProgram::UNIFORM_SAMPLER" to 0
*/ */
void updateUniforms(); void updateUniforms();
@ -198,7 +200,7 @@ private:
GLuint _program; GLuint _program;
GLuint _vertShader; GLuint _vertShader;
GLuint _fragShader; GLuint _fragShader;
GLint _uniforms[kUniform_MAX]; GLint _uniforms[UNIFORM_MAX];
struct _hashUniformEntry* _hashForUniforms; struct _hashUniformEntry* _hashForUniforms;
bool _usesTime; bool _usesTime;
}; };

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