From 01ebb2ac29da884a966d6c8c6602ef1baed27cec Mon Sep 17 00:00:00 2001 From: PickleMan Date: Sun, 13 Oct 2013 23:41:55 -0400 Subject: [PATCH 001/193] Added triangle, quad bezier, cubic bezier drawing to DrawNode --- cocos/2d/CCDrawNode.cpp | 80 +++++++++++++++++++++++++++++++++++++++++ cocos/2d/CCDrawNode.h | 9 +++++ 2 files changed, 89 insertions(+) diff --git a/cocos/2d/CCDrawNode.cpp b/cocos/2d/CCDrawNode.cpp index 541bd8974c..288c88aba0 100644 --- a/cocos/2d/CCDrawNode.cpp +++ b/cocos/2d/CCDrawNode.cpp @@ -437,6 +437,86 @@ void DrawNode::drawPolygon(Point *verts, unsigned int count, const Color4F &fill free(extrude); } +void DrawNode::drawTriangle(const Point &p1, const Point &p2, const Point &p3, const Color4F &color) +{ + unsigned int vertex_count = 2*3; + ensureCapacity(vertex_count); + + Color4B col = Color4B(color); + V2F_C4B_T2F a = {Vertex2F(p1.x, p1.y), col, Tex2F(0.0, 0.0) }; + V2F_C4B_T2F b = {Vertex2F(p2.x, p2.y), col, Tex2F(0.0, 0.0) }; + V2F_C4B_T2F c = {Vertex2F(p3.x, p3.y), col, Tex2F(0.0, 0.0) }; + + V2F_C4B_T2F_Triangle *triangles = (V2F_C4B_T2F_Triangle *)(_buffer + _bufferCount); + V2F_C4B_T2F_Triangle triangle = {a, b, c}; + triangles[0] = triangle; + + _bufferCount += vertex_count; + _dirty = true; +} + +void DrawNode::drawCubicBezier(const Point& from, const Point& control1, const Point& control2, const Point& to, unsigned int segments, const Color4F &color) +{ + unsigned int vertex_count = (segments + 1) * 3; + ensureCapacity(vertex_count); + + Tex2F texCoord = Tex2F(0.0, 0.0); + Color4B col = Color4B(color); + Vertex2F vertex; + Vertex2F firstVertex = Vertex2F(from.x, from.y); + Vertex2F lastVertex = Vertex2F(to.x, to.y); + + float t = 0; + for(unsigned int i = segments + 1; i > 0; i--) + { + float x = powf(1 - t, 3) * from.x + 3.0f * powf(1 - t, 2) * t * control1.x + 3.0f * (1 - t) * t * t * control2.x + t * t * t * to.x; + float y = powf(1 - t, 3) * from.y + 3.0f * powf(1 - t, 2) * t * control1.y + 3.0f * (1 - t) * t * t * control2.y + t * t * t * to.y; + vertex = Vertex2F(x, y); + + V2F_C4B_T2F a = {firstVertex, col, texCoord }; + V2F_C4B_T2F b = {lastVertex, col, texCoord }; + V2F_C4B_T2F c = {vertex, col, texCoord }; + V2F_C4B_T2F_Triangle triangle = {a, b, c}; + ((V2F_C4B_T2F_Triangle *)(_buffer + _bufferCount))[0] = triangle; + + lastVertex = vertex; + t += 1.0f / segments; + _bufferCount += 3; + } + _dirty = true; +} + +void DrawNode::drawQuadraticBezier(const Point& from, const Point& control, const Point& to, unsigned int segments, const Color4F &color) +{ + unsigned int vertex_count = (segments + 1) * 3; + ensureCapacity(vertex_count); + + Tex2F texCoord = Tex2F(0.0, 0.0); + Color4B col = Color4B(color); + Vertex2F vertex; + Vertex2F firstVertex = Vertex2F(from.x, from.y); + Vertex2F lastVertex = Vertex2F(to.x, to.y); + + float t = 0; + for(unsigned int i = segments + 1; i > 0; i--) + { + float x = powf(1 - t, 2) * from.x + 2.0f * (1 - t) * t * control.x + t * t * to.x; + float y = powf(1 - t, 2) * from.y + 2.0f * (1 - t) * t * control.y + t * t * to.y; + vertex = Vertex2F(x, y); + + V2F_C4B_T2F a = {firstVertex, col, texCoord }; + V2F_C4B_T2F b = {lastVertex, col, texCoord }; + V2F_C4B_T2F c = {vertex, col, texCoord }; + V2F_C4B_T2F_Triangle triangle = {a, b, c}; + ((V2F_C4B_T2F_Triangle *)(_buffer + _bufferCount))[0] = triangle; + + lastVertex = vertex; + t += 1.0f / segments; + _bufferCount += 3; + } + _dirty = true; +} + void DrawNode::clear() { _bufferCount = 0; diff --git a/cocos/2d/CCDrawNode.h b/cocos/2d/CCDrawNode.h index 9349430880..231c87c07c 100644 --- a/cocos/2d/CCDrawNode.h +++ b/cocos/2d/CCDrawNode.h @@ -72,6 +72,15 @@ public: * @endcode */ void drawPolygon(Point *verts, unsigned int count, const Color4F &fillColor, float borderWidth, const Color4F &borderColor); + + /** draw a triangle with color */ + void drawTriangle(const Point &p1, const Point &p2, const Point &p3, const Color4F &color); + + /** draw a cubic bezier curve with color and number of segments */ + void drawCubicBezier(const Point& from, const Point& control1, const Point& control2, const Point& to, unsigned int segments, const Color4F &color); + + /** draw a quadratic bezier curve with color and number of segments */ + void drawQuadraticBezier(const Point& from, const Point& control, const Point& to, unsigned int segments, const Color4F &color) /** Clear the geometry in the node's buffer. */ void clear(); From 870f7de357c150fb9c7b7f6cc0f2e0aef32d7dfb Mon Sep 17 00:00:00 2001 From: ThePickleMan Date: Sun, 13 Oct 2013 23:12:41 -0500 Subject: [PATCH 002/193] Readded trimmed semicolon --- cocos/2d/CCDrawNode.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCDrawNode.h b/cocos/2d/CCDrawNode.h index 231c87c07c..1978c26ef0 100644 --- a/cocos/2d/CCDrawNode.h +++ b/cocos/2d/CCDrawNode.h @@ -80,7 +80,7 @@ public: void drawCubicBezier(const Point& from, const Point& control1, const Point& control2, const Point& to, unsigned int segments, const Color4F &color); /** draw a quadratic bezier curve with color and number of segments */ - void drawQuadraticBezier(const Point& from, const Point& control, const Point& to, unsigned int segments, const Color4F &color) + void drawQuadraticBezier(const Point& from, const Point& control, const Point& to, unsigned int segments, const Color4F &color); /** Clear the geometry in the node's buffer. */ void clear(); From 3b5ae69ac8e9ffe01dd74034d5d9b7c86718d769 Mon Sep 17 00:00:00 2001 From: PickleMan Date: Mon, 14 Oct 2013 00:52:58 -0400 Subject: [PATCH 003/193] Added triangle, cubic bezier and quad bezier tests to DrawPrimitivesTest --- .../Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp b/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp index ca4f1f2be5..e236a189d9 100644 --- a/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp +++ b/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp @@ -286,6 +286,14 @@ DrawNodeTest::DrawNodeTest() draw->drawSegment(Point(20,s.height), Point(20,s.height/2), 10, Color4F(0, 1, 0, 1)); draw->drawSegment(Point(10,s.height/2), Point(s.width/2, s.height/2), 40, Color4F(1, 0, 1, 0.5)); + + // Draw triangle + draw->drawTriangle(Point(10, 10), Point(70, 30), Point(100, 140), Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5)); + + // Draw some beziers + draw->drawQuadraticBezier(Point(s.width - 150, s.height - 150), Point(s.width - 70, s.height - 10), Point(s.width - 10, s.height - 10), 10, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5)); + + draw->drawCubicBezier(Point(s.width - 250, 40), Point(s.width - 70, 100), Point(s.width - 30, 250), Point(s.width - 10, s.height - 50), 10, Color4F(CCRANDOM_0_1(), CCRANDOM_0_1(), CCRANDOM_0_1(), 0.5)); } string DrawNodeTest::title() From e972c97dcfcbd6459611143db0776dea36b62fab Mon Sep 17 00:00:00 2001 From: WuHuan Date: Sat, 4 Jan 2014 14:40:22 +0800 Subject: [PATCH 004/193] support mingw --- cocos/2d/CCActionCamera.cpp | 6 +++--- cocos/2d/platform/win32/CCStdC.h | 11 ++++++++++- cocos/base/CCConsole.cpp | 20 +++++++++++++++++++- cocos/base/CCConsole.h | 2 +- 4 files changed, 33 insertions(+), 6 deletions(-) diff --git a/cocos/2d/CCActionCamera.cpp b/cocos/2d/CCActionCamera.cpp index 0d8ef23606..7333de1458 100644 --- a/cocos/2d/CCActionCamera.cpp +++ b/cocos/2d/CCActionCamera.cpp @@ -181,11 +181,11 @@ void OrbitCamera::startWithTarget(Node *target) float r, zenith, azimuth; this->sphericalRadius(&r, &zenith, &azimuth); - if( isnan(_radius) ) + if( std::isnan(_radius) ) _radius = r; - if( isnan(_angleZ) ) + if( std::isnan(_angleZ) ) _angleZ = (float)CC_RADIANS_TO_DEGREES(zenith); - if( isnan(_angleX) ) + if( std::isnan(_angleX) ) _angleX = (float)CC_RADIANS_TO_DEGREES(azimuth); _radZ = (float)CC_DEGREES_TO_RADIANS(_angleZ); diff --git a/cocos/2d/platform/win32/CCStdC.h b/cocos/2d/platform/win32/CCStdC.h index 027c8bf3cb..035ff90367 100644 --- a/cocos/2d/platform/win32/CCStdC.h +++ b/cocos/2d/platform/win32/CCStdC.h @@ -108,7 +108,16 @@ NS_CC_END #else -#include +#include +inline int vsnprintf_s(char *buffer, size_t sizeOfBuffer, size_t count, + const char *format, va_list argptr) { + return vsnprintf(buffer, sizeOfBuffer, format, argptr); +} +inline errno_t strcpy_s(char *strDestination, size_t numberOfElements, + const char *strSource) { + strcpy(strDestination, strSource); + return 0; +} #endif // __MINGW32__ diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index e2440a49f7..10a251196b 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -31,7 +31,7 @@ #include #include -#if defined(_MSC_VER) +#if defined(_MSC_VER) || defined(__MINGW32__) #include #include @@ -91,6 +91,24 @@ static void printSceneGraphBoot(int fd) mydprintf(fd, "Total Nodes: %d\n", total); } +#if defined(__MINGW32__) +static const char* inet_ntop(int af, const void* src, char* dst, int cnt) +{ + struct sockaddr_in srcaddr; + + memset(&srcaddr, 0, sizeof(struct sockaddr_in)); + memcpy(&(srcaddr.sin_addr), src, sizeof(srcaddr.sin_addr)); + + srcaddr.sin_family = af; + if (WSAAddressToString((struct sockaddr*) &srcaddr, sizeof(struct sockaddr_in), 0, dst, (LPDWORD) &cnt) != 0) + { + DWORD rv = WSAGetLastError(); + printf("WSAAddressToString() : %d\n",rv); + return NULL; + } + return dst; +} +#endif // // Console code diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index d401991525..43faa3d111 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -26,7 +26,7 @@ #ifndef __CCCONSOLE_H__ #define __CCCONSOLE_H__ -#if defined(_MSC_VER) +#if defined(_MSC_VER) || defined(__MINGW32__) #include //typedef SSIZE_T ssize_t; // ssize_t was redefined as int in libwebsockets.h. From 954ee61022f1a231beb3f50d6f9b865fa90e8a43 Mon Sep 17 00:00:00 2001 From: WuHuan Date: Wed, 8 Jan 2014 16:58:36 +0800 Subject: [PATCH 005/193] testcpp mingw --- CMakeLists.txt | 14 +++++++------- cocos/2d/platform/win32/CCStdC.h | 1 + cocos/audio/CMakeLists.txt | 7 +++++++ cocos/base/CMakeLists.txt | 6 ++++++ cocos/network/CMakeLists.txt | 6 ++---- extensions/CMakeLists.txt | 13 +++++++++++++ .../GUI/CCControlExtension/CCControlUtils.cpp | 2 +- extensions/proj.win32/Win32InputBox.cpp | 4 ++++ samples/Cpp/TestCpp/CMakeLists.txt | 3 +++ 9 files changed, 44 insertions(+), 12 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 086dd47286..a5486c2b41 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -38,15 +38,15 @@ option(USE_CHIPMUNK "Use chipmunk for physics library" ON) option(USE_BOX2D "Use box2d for physics library" OFF) option(DEBUG_MODE "Debug or release?" ON) option(BUILD_LIBS_LUA "Build lua libraries" OFF) -option(BUILD_GUI "Build GUI library" OFF) -option(BUILD_NETWORK "Build network library" OFF) -option(BUILD_EXTENSIONS "Build extension library" OFF) -option(BUILD_EDITOR_SPINE "Build editor support for spine" OFF) -option(BUILD_EDITOR_COCOSTUDIO "Build editor support for cocostudio" OFF) -option(BUILD_EDITOR_COCOSBUILDER "Build editor support for cocosbuilder" OFF) +option(BUILD_GUI "Build GUI library" ON) +option(BUILD_NETWORK "Build network library" ON) +option(BUILD_EXTENSIONS "Build extension library" ON) +option(BUILD_EDITOR_SPINE "Build editor support for spine" ON) +option(BUILD_EDITOR_COCOSTUDIO "Build editor support for cocostudio" ON) +option(BUILD_EDITOR_COCOSBUILDER "Build editor support for cocosbuilder" ON) option(BUILD_HelloCpp "Only build HelloCpp sample" ON) -option(BUILD_TestCpp "Only build TestCpp sample" OFF) +option(BUILD_TestCpp "Only build TestCpp sample" ON) option(BUILD_HelloLua "Only build HelloLua sample" OFF) option(BUILD_TestLua "Only build TestLua sample" OFF) diff --git a/cocos/2d/platform/win32/CCStdC.h b/cocos/2d/platform/win32/CCStdC.h index 035ff90367..d8d8ddb17e 100644 --- a/cocos/2d/platform/win32/CCStdC.h +++ b/cocos/2d/platform/win32/CCStdC.h @@ -109,6 +109,7 @@ NS_CC_END #else #include + inline int vsnprintf_s(char *buffer, size_t sizeOfBuffer, size_t count, const char *format, va_list argptr) { return vsnprintf(buffer, sizeOfBuffer, format, argptr); diff --git a/cocos/audio/CMakeLists.txt b/cocos/audio/CMakeLists.txt index 9ad9e99b12..c2b45816aa 100644 --- a/cocos/audio/CMakeLists.txt +++ b/cocos/audio/CMakeLists.txt @@ -45,4 +45,11 @@ set_target_properties(audio ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" LIBRARY_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" ) + +elseif(WIN32) + +target_link_libraries(audio + Winmm +) + endif() diff --git a/cocos/base/CMakeLists.txt b/cocos/base/CMakeLists.txt index 06d3e582c1..18b7b6bfe6 100644 --- a/cocos/base/CMakeLists.txt +++ b/cocos/base/CMakeLists.txt @@ -21,6 +21,12 @@ add_library(cocosbase STATIC ${COCOS_BASE_SRC} ) +if(WIN32) +target_link_libraries(cocosbase + Ws2_32 +) +endif() + set_target_properties(cocosbase PROPERTIES ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_SOURCE_DIR}/lib" diff --git a/cocos/network/CMakeLists.txt b/cocos/network/CMakeLists.txt index f2deb9b365..eb1fd9877e 100644 --- a/cocos/network/CMakeLists.txt +++ b/cocos/network/CMakeLists.txt @@ -1,6 +1,7 @@ set(NETWORK_SRC HttpClient.cpp SocketIO.cpp + WebSocket.cpp ) add_library(network STATIC @@ -9,10 +10,7 @@ add_library(network STATIC target_link_libraries(network curl - ldap - lber - idn - rtmp + websockets ) set_target_properties(network diff --git a/extensions/CMakeLists.txt b/extensions/CMakeLists.txt index f8083e1220..a6e438340b 100644 --- a/extensions/CMakeLists.txt +++ b/extensions/CMakeLists.txt @@ -24,12 +24,25 @@ set(EXTENSIONS_SRC physics-nodes/CCPhysicsSprite.cpp ) +if(WIN32) + ADD_DEFINITIONS(-DUNICODE -D_UNICODE) + + set(PLATFORM_EXTENSIONS_SRC + proj.win32/Win32InputBox.cpp + ) +elseif(APPLE) + +else() + +endif() + include_directories( .. ) add_library(extensions STATIC ${EXTENSIONS_SRC} + ${PLATFORM_EXTENSIONS_SRC} ) set_target_properties(extensions diff --git a/extensions/GUI/CCControlExtension/CCControlUtils.cpp b/extensions/GUI/CCControlExtension/CCControlUtils.cpp index e660a29d8e..75d246796d 100644 --- a/extensions/GUI/CCControlExtension/CCControlUtils.cpp +++ b/extensions/GUI/CCControlExtension/CCControlUtils.cpp @@ -92,7 +92,7 @@ RGBA ControlUtils::RGBfromHSV(HSV value) if (value.s <= 0.0) // < is bogus, just shuts up warnings { - if (isnan(value.h)) // value.h == NAN + if (std::isnan(value.h)) // value.h == NAN { out.r = value.v; out.g = value.v; diff --git a/extensions/proj.win32/Win32InputBox.cpp b/extensions/proj.win32/Win32InputBox.cpp index 8a0de6ffcb..220a932072 100644 --- a/extensions/proj.win32/Win32InputBox.cpp +++ b/extensions/proj.win32/Win32InputBox.cpp @@ -133,7 +133,11 @@ INT_PTR CWin32InputBox::InputBoxEx(WIN32INPUTBOX_PARAM *param) if (param->DlgTemplateName != 0) { HMODULE hModule = (HMODULE)param->hInstance; +#ifdef __MINGW32__ + HRSRC rcDlg = ::FindResource(hModule, (LPWSTR)(ULONG_PTR)(size_t)(param->DlgTemplateName), RT_DIALOG); +#else HRSRC rcDlg = ::FindResource(hModule, MAKEINTRESOURCE(param->DlgTemplateName), RT_DIALOG); +#endif if (rcDlg == NULL) return 0; diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt index 91db89f44b..35964eb925 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -50,7 +50,10 @@ set(SAMPLE_SRC Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp Classes/ExtensionsTest/ExtensionsTest.cpp Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp + Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp + Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp + Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp From dccd1b40deb829c2890d43e9571dccb6d6416026 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 8 Jan 2014 16:28:18 -0800 Subject: [PATCH 006/193] Adds a new test that shows the problem with the Camera Apprently the bug is in QuadCommand, since if we use CustomCommand the camera works OK. --- .../Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp | 122 ++++++++++++++++++ .../Cpp/TestCpp/Classes/NodeTest/NodeTest.h | 18 +++ 2 files changed, 140 insertions(+) diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp index 77c7c907d7..5c2534dee0 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp @@ -25,6 +25,7 @@ static int sceneIdx = -1; static std::function createFunctions[] = { + CL(CameraTest2), CL(CameraCenterTest), CL(Test2), CL(Test4), @@ -827,6 +828,127 @@ std::string NodeNonOpaqueTest::subtitle() const return "Node rendered with GL_BLEND enabled"; } +//------------------------------------------------------------------ +// +// CameraTest2 +// +//------------------------------------------------------------------ + +class MySprite : public Sprite +{ +public: + static MySprite* create(const std::string &spritefilename) + { + auto sprite = new MySprite; + sprite->initWithFile(spritefilename); + sprite->autorelease(); + + auto shader = CCShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR); + sprite->setShaderProgram(shader); + return sprite; + } + virtual void draw() override; + void onDraw(); + +protected: + CustomCommand _customCommand; +}; + +void MySprite::draw() +{ + _customCommand.init(0, _vertexZ); + _customCommand.func = CC_CALLBACK_0(MySprite::onDraw, this); + Director::getInstance()->getRenderer()->addCommand(&_customCommand); +} + +void MySprite::onDraw() +{ + CC_NODE_DRAW_SETUP(); + + GL::blendFunc( _blendFunc.src, _blendFunc.dst ); + + GL::bindTexture2D( _texture->getName() ); + GL::enableVertexAttribs( GL::VERTEX_ATTRIB_FLAG_POS_COLOR_TEX ); + +#define kQuadSize sizeof(_quad.bl) + long offset = (long)&_quad; + + // vertex + int diff = offsetof( V3F_C4B_T2F, vertices); + glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_POSITION, 3, GL_FLOAT, GL_FALSE, kQuadSize, (void*) (offset + diff)); + + // texCoods + diff = offsetof( V3F_C4B_T2F, texCoords); + glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_TEX_COORDS, 2, GL_FLOAT, GL_FALSE, kQuadSize, (void*)(offset + diff)); + + // color + diff = offsetof( V3F_C4B_T2F, colors); + glVertexAttribPointer(GLProgram::VERTEX_ATTRIB_COLOR, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (void*)(offset + diff)); + + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + + CHECK_GL_ERROR_DEBUG(); + CC_INCREMENT_GL_DRAWS(1); +} +void CameraTest2::onEnter() +{ + TestCocosNodeDemo::onEnter(); + Director::getInstance()->setProjection(Director::Projection::_3D); + Director::getInstance()->setDepthTest(true); +} + +void CameraTest2::onExit() +{ + Director::getInstance()->setProjection(Director::Projection::_2D); + TestCocosNodeDemo::onExit(); +} + +CameraTest2::CameraTest2() +{ + auto s = Director::getInstance()->getWinSize(); + + _sprite1 = MySprite::create(s_back3); + addChild( _sprite1 ); + _sprite1->setPosition( Point(1*s.width/4, s.height/2) ); + _sprite1->setScale(0.5); + + _sprite2 = Sprite::create(s_back3); + addChild( _sprite2 ); + _sprite2->setPosition( Point(3*s.width/4, s.height/2) ); + _sprite2->setScale(0.5); + + scheduleUpdate(); +} + +std::string CameraTest2::title() const +{ + return "Camera Test 2"; +} + +std::string CameraTest2::subtitle() const +{ + return "Background image should be rotated in 3D"; +} + +void CameraTest2::update(float dt) +{ + kmVec3 eye, center, up; + + kmVec3Fill(&eye, 150, 0, 200); + kmVec3Fill(¢er, 0, 0, 0); + kmVec3Fill(&up, 0, 1, 0); + + + kmMat4 lookupMatrix; + kmMat4LookAt(&lookupMatrix, &eye, ¢er, &up); + + _sprite1->setAdditionalTransform(lookupMatrix); + _sprite2->setAdditionalTransform(lookupMatrix); +} + +/// +/// void CocosNodeTestScene::runThisTest() { auto layer = nextCocosNodeAction(); diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h index 3e6f8fa9ce..50959ced5a 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h @@ -148,6 +148,24 @@ protected: CameraCenterTest(); }; +class CameraTest2 : public TestCocosNodeDemo +{ +public: + CREATE_FUNC(CameraTest2); + virtual std::string title() const override; + virtual std::string subtitle() const override; + virtual void onEnter() override; + virtual void onExit() override; + +protected: + virtual void update(float dt) override; + CameraTest2(); + + Sprite *_sprite1; + Sprite *_sprite2; + +}; + class ConvertToNode : public TestCocosNodeDemo { public: From e3667a2894bb7163b478f1f41e9f6f42097cefc8 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Thu, 9 Jan 2014 09:58:27 +0800 Subject: [PATCH 007/193] Fixed bugs. --- cocos/gui/UIPageView.cpp | 7 ++++++- cocos/gui/UIPageView.h | 2 ++ cocos/gui/UIScrollView.cpp | 7 ++++++- cocos/gui/UIScrollView.h | 2 ++ cocos/gui/UITextField.cpp | 12 ++++-------- cocos/gui/UITextField.h | 4 ++-- 6 files changed, 22 insertions(+), 12 deletions(-) diff --git a/cocos/gui/UIPageView.cpp b/cocos/gui/UIPageView.cpp index 9e41a534ed..2ad5a8c533 100644 --- a/cocos/gui/UIPageView.cpp +++ b/cocos/gui/UIPageView.cpp @@ -66,13 +66,18 @@ PageView* PageView::create() CC_SAFE_DELETE(widget); return nullptr; } + +void PageView::onEnter() +{ + Layout::onEnter(); + setUpdateEnabled(true); +} bool PageView::init() { if (Layout::init()) { setClippingEnabled(true); - setUpdateEnabled(true); setTouchEnabled(true); return true; } diff --git a/cocos/gui/UIPageView.h b/cocos/gui/UIPageView.h index 3c98b39c46..4b4a890199 100644 --- a/cocos/gui/UIPageView.h +++ b/cocos/gui/UIPageView.h @@ -159,6 +159,8 @@ public: */ virtual std::string getDescription() const override; + virtual void onEnter() override; + protected: virtual void addChild(Node * child) override; virtual void addChild(Node * child, int zOrder) override; diff --git a/cocos/gui/UIScrollView.cpp b/cocos/gui/UIScrollView.cpp index 11bb00c622..33dee12004 100644 --- a/cocos/gui/UIScrollView.cpp +++ b/cocos/gui/UIScrollView.cpp @@ -93,12 +93,17 @@ ScrollView* ScrollView::create() CC_SAFE_DELETE(widget); return nullptr; } + +void ScrollView::onEnter() +{ + Layout::onEnter(); + setUpdateEnabled(true); +} bool ScrollView::init() { if (Layout::init()) { - setUpdateEnabled(true); setTouchEnabled(true); setClippingEnabled(true); _innerContainer->setTouchEnabled(false); diff --git a/cocos/gui/UIScrollView.h b/cocos/gui/UIScrollView.h index 56e0b27eaf..9a0a9f889b 100644 --- a/cocos/gui/UIScrollView.h +++ b/cocos/gui/UIScrollView.h @@ -314,6 +314,8 @@ public: * Returns the "class name" of widget. */ virtual std::string getDescription() const override; + + virtual void onEnter() override; protected: virtual bool init() override; virtual void initRenderer() override; diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index c6e080fed3..95f5ccaea6 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -300,15 +300,11 @@ TextField* TextField::create() CC_SAFE_DELETE(widget); return nullptr; } - -bool TextField::init() + +void TextField::onEnter() { - if (Widget::init()) - { - setUpdateEnabled(true); - return true; - } - return false; + Widget::onEnter(); + setUpdateEnabled(true); } void TextField::initRenderer() diff --git a/cocos/gui/UITextField.h b/cocos/gui/UITextField.h index 1372696bcb..1f01103592 100644 --- a/cocos/gui/UITextField.h +++ b/cocos/gui/UITextField.h @@ -107,8 +107,6 @@ public: TextField(); virtual ~TextField(); static TextField* create(); - virtual bool init() override; - virtual void initRenderer() override; void setTouchSize(const Size &size); void setText(const std::string& text); void setPlaceHolder(const std::string& value); @@ -145,8 +143,10 @@ public: virtual const Size& getContentSize() const override; virtual Node* getVirtualRenderer() override; void attachWithIME(); + virtual void onEnter() override; protected: // event + virtual void initRenderer() override; void attachWithIMEEvent(); void detachWithIMEEvent(); void insertTextEvent(); From 480a9277daa2463c4ea6d64bdf34f1925a986a35 Mon Sep 17 00:00:00 2001 From: edwardzhou Date: Thu, 9 Jan 2014 13:29:56 +0800 Subject: [PATCH 008/193] fix WebSocket cannot send/receive more than 4096 bytes of data --- cocos/network/WebSocket.cpp | 154 +++++++++++++++++++++++++----------- cocos/network/WebSocket.h | 8 +- 2 files changed, 112 insertions(+), 50 deletions(-) diff --git a/cocos/network/WebSocket.cpp b/cocos/network/WebSocket.cpp index 3a77d75868..3f81e5ba90 100644 --- a/cocos/network/WebSocket.cpp +++ b/cocos/network/WebSocket.cpp @@ -37,6 +37,8 @@ #include "libwebsockets.h" +#define WS_WRITE_BUFFER_SIZE 2048 + NS_CC_BEGIN namespace network { @@ -221,6 +223,9 @@ WebSocket::WebSocket() , _delegate(nullptr) , _SSLConnection(0) , _wsProtocols(nullptr) +, _pending_frame_data_len(0) +, _current_data_len(0) +, _current_data(NULL) { } @@ -497,12 +502,13 @@ int WebSocket::onSocketCallback(struct libwebsocket_context *ctx, case LWS_CALLBACK_CLIENT_WRITEABLE: { + std::lock_guard lk(_wsHelper->_subThreadWsMessageQueueMutex); std::list::iterator iter = _wsHelper->_subThreadWsMessageQueue->begin(); int bytesWrite = 0; - for (; iter != _wsHelper->_subThreadWsMessageQueue->end(); ++iter) + for (; iter != _wsHelper->_subThreadWsMessageQueue->end();) { WsMessage* subThreadMsg = *iter; @@ -511,44 +517,64 @@ int WebSocket::onSocketCallback(struct libwebsocket_context *ctx, { Data* data = (Data*)subThreadMsg->obj; - unsigned char* buf = new unsigned char[LWS_SEND_BUFFER_PRE_PADDING - + data->len + LWS_SEND_BUFFER_POST_PADDING]; + const size_t c_bufferSize = WS_WRITE_BUFFER_SIZE; + + size_t remaining = data->len - data->issued; + size_t n = std::min(remaining, c_bufferSize ); + CCLOG("[websocket:send] total: %d, sent: %d, remaining: %d, buffer size: %d", data->len, data->issued, remaining, n); + + unsigned char* buf = new unsigned char[LWS_SEND_BUFFER_PRE_PADDING + n + LWS_SEND_BUFFER_POST_PADDING]; + + memcpy((char*)&buf[LWS_SEND_BUFFER_PRE_PADDING], data->bytes + data->issued, n); - memset(&buf[LWS_SEND_BUFFER_PRE_PADDING], 0, data->len); - memcpy((char*)&buf[LWS_SEND_BUFFER_PRE_PADDING], data->bytes, data->len); + int writeProtocol; - enum libwebsocket_write_protocol writeProtocol; - - if (WS_MSG_TO_SUBTRHEAD_SENDING_STRING == subThreadMsg->what) - { - writeProtocol = LWS_WRITE_TEXT; + if (data->issued == 0) { + if (WS_MSG_TO_SUBTRHEAD_SENDING_STRING == subThreadMsg->what) + { + writeProtocol = LWS_WRITE_TEXT; + } + else + { + writeProtocol = LWS_WRITE_BINARY; + } + + // If we have more than 1 fragment + if (data->len > c_bufferSize) + writeProtocol |= LWS_WRITE_NO_FIN; + } else { + // we are in the middle of fragments + writeProtocol = LWS_WRITE_CONTINUATION; + // and if not in the last fragment + if (remaining != n) + writeProtocol |= LWS_WRITE_NO_FIN; } - else - { - writeProtocol = LWS_WRITE_BINARY; - } - - bytesWrite = libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], data->len, writeProtocol); - + + bytesWrite = libwebsocket_write(wsi, &buf[LWS_SEND_BUFFER_PRE_PADDING], n, (libwebsocket_write_protocol)writeProtocol); + CCLOG("[websocket:send] bytesWrite => %d", bytesWrite); + + // Buffer overrun? if (bytesWrite < 0) { - CCLOGERROR("%s", "libwebsocket_write error..."); + break; } - if (bytesWrite < data->len) + // Do we have another fragments to send? + else if (remaining != n) { - CCLOGERROR("Partial write LWS_CALLBACK_CLIENT_WRITEABLE\n"); + data->issued += n; + break; + } + // Safely done! + else + { + CC_SAFE_DELETE_ARRAY(data->bytes); + CC_SAFE_DELETE(data); + CC_SAFE_DELETE_ARRAY(buf); + _wsHelper->_subThreadWsMessageQueue->erase(iter++); + CC_SAFE_DELETE(subThreadMsg); } - - CC_SAFE_DELETE_ARRAY(data->bytes); - CC_SAFE_DELETE(data); - CC_SAFE_DELETE_ARRAY(buf); } - - CC_SAFE_DELETE(subThreadMsg); } - - _wsHelper->_subThreadWsMessageQueue->clear(); - /* get notified as soon as we can write again */ @@ -577,32 +603,64 @@ int WebSocket::onSocketCallback(struct libwebsocket_context *ctx, { if (in && len > 0) { - WsMessage* msg = new WsMessage(); - msg->what = WS_MSG_TO_UITHREAD_MESSAGE; - - char* bytes = NULL; - Data* data = new Data(); - - if (lws_frame_is_binary(wsi)) + // Accumulate the data (increasing the buffer as we go) + if (_current_data_len == 0) { - - bytes = new char[len]; - data->isBinary = true; + _current_data = new char[len]; + memcpy (_current_data, in, len); + _current_data_len = len; } else { - bytes = new char[len+1]; - bytes[len] = '\0'; - data->isBinary = false; + char *new_data = new char [_current_data_len + len]; + memcpy (new_data, _current_data, _current_data_len); + memcpy (new_data + _current_data_len, in, len); + CC_SAFE_DELETE_ARRAY(_current_data); + _current_data = new_data; + _current_data_len = _current_data_len + len; } - memcpy(bytes, in, len); + _pending_frame_data_len = libwebsockets_remaining_packet_payload (wsi); + + if (_pending_frame_data_len > 0) + { + //CCLOG("%ld bytes of pending data to receive, consider increasing the libwebsocket rx_buffer_size value.", _pending_frame_data_len); + } - data->bytes = bytes; - data->len = len; - msg->obj = (void*)data; - - _wsHelper->sendMessageToUIThread(msg); + // If no more data pending, send it to the client thread + if (_pending_frame_data_len == 0) + { + WsMessage* msg = new WsMessage(); + msg->what = WS_MSG_TO_UITHREAD_MESSAGE; + + char* bytes = NULL; + Data* data = new Data(); + + if (lws_frame_is_binary(wsi)) + { + + bytes = new char[_current_data_len]; + data->isBinary = true; + } + else + { + bytes = new char[_current_data_len+1]; + bytes[_current_data_len] = '\0'; + data->isBinary = false; + } + + memcpy(bytes, _current_data, _current_data_len); + + data->bytes = bytes; + data->len = _current_data_len; + msg->obj = (void*)data; + + CC_SAFE_DELETE_ARRAY(_current_data); + _current_data = NULL; + _current_data_len = 0; + + _wsHelper->sendMessageToUIThread(msg); + } } } break; diff --git a/cocos/network/WebSocket.h b/cocos/network/WebSocket.h index d9363bb666..830d9fb2ee 100644 --- a/cocos/network/WebSocket.h +++ b/cocos/network/WebSocket.h @@ -62,9 +62,9 @@ public: */ struct Data { - Data():bytes(NULL), len(0), isBinary(false){} + Data():bytes(NULL), len(0), issued(0), isBinary(false){} char* bytes; - ssize_t len; + ssize_t len, issued; bool isBinary; }; @@ -153,6 +153,10 @@ private: unsigned int _port; std::string _path; + size_t _pending_frame_data_len; + unsigned int _current_data_len; + char *_current_data; + friend class WsThreadHelper; WsThreadHelper* _wsHelper; From d15874fdf72f3393fe8b639780cc90d6d92db962 Mon Sep 17 00:00:00 2001 From: walzer Date: Thu, 9 Jan 2014 14:16:26 +0800 Subject: [PATCH 009/193] fixed #3627, an extra benefit from adding LabelAtlas::create() is that we can hide its default constructor into protected. --- cocos/2d/CCDirector.cpp | 9 ++++++--- cocos/2d/CCLabelAtlas.h | 30 +++++++++++++++--------------- cocos/2d/CCMenuItem.cpp | 3 +-- 3 files changed, 22 insertions(+), 20 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 277859644d..428772a367 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -948,17 +948,20 @@ void Director::createStatsLabel() */ float factor = EGLView::getInstance()->getDesignResolutionSize().height / 320.0f; - _FPSLabel = new LabelAtlas; + _FPSLabel = LabelAtlas::create(); + _FPSLabel->retain(); _FPSLabel->setIgnoreContentScaleFactor(true); _FPSLabel->initWithString("00.0", texture, 12, 32 , '.'); _FPSLabel->setScale(factor); - _SPFLabel = new LabelAtlas; + _SPFLabel = LabelAtlas::create(); + _SPFLabel->retain(); _SPFLabel->setIgnoreContentScaleFactor(true); _SPFLabel->initWithString("0.000", texture, 12, 32, '.'); _SPFLabel->setScale(factor); - _drawsLabel = new LabelAtlas; + _drawsLabel = LabelAtlas::create(); + _drawsLabel->retain(); _drawsLabel->setIgnoreContentScaleFactor(true); _drawsLabel->initWithString("000", texture, 12, 32, '.'); _drawsLabel->setScale(factor); diff --git a/cocos/2d/CCLabelAtlas.h b/cocos/2d/CCLabelAtlas.h index f5419b3611..4eb25b67af 100644 --- a/cocos/2d/CCLabelAtlas.h +++ b/cocos/2d/CCLabelAtlas.h @@ -52,21 +52,6 @@ A more flexible class is LabelBMFont. It supports variable width characters and class CC_DLL LabelAtlas : public AtlasNode, public LabelProtocol { public: - /** - * @js ctor - */ - LabelAtlas() - :_string("") - {} - /** - * @js NA - * @lua NA - */ - virtual ~LabelAtlas() - { - _string.clear(); - } - /** creates an empty LabelAtlas, user need to call initWithString(...) later to make this object work properly **/ static LabelAtlas* create(); @@ -101,6 +86,21 @@ public: #endif protected: + /** + * @js ctor + */ + LabelAtlas() + :_string("") + {} + /** + * @js NA + * @lua NA + */ + virtual ~LabelAtlas() + { + _string.clear(); + } + // string to render std::string _string; // the first char in the charmap diff --git a/cocos/2d/CCMenuItem.cpp b/cocos/2d/CCMenuItem.cpp index d097e1d30a..f137404176 100644 --- a/cocos/2d/CCMenuItem.cpp +++ b/cocos/2d/CCMenuItem.cpp @@ -348,9 +348,8 @@ bool MenuItemAtlasFont::initWithString(const std::string& value, const std::stri bool MenuItemAtlasFont::initWithString(const std::string& value, const std::string& charMapFile, int itemWidth, int itemHeight, char startCharMap, const ccMenuCallback& callback) { CCASSERT( value.size() != 0, "value length must be greater than 0"); - LabelAtlas *label = new LabelAtlas(); + LabelAtlas *label = LabelAtlas::create(); label->initWithString(value, charMapFile, itemWidth, itemHeight, startCharMap); - label->autorelease(); if (MenuItemLabel::initWithLabel(label, callback)) { // do something ? From 8da48795609b9ac5a8f8bbbf9af8213a2dd8dfae Mon Sep 17 00:00:00 2001 From: walzer Date: Thu, 9 Jan 2014 14:21:43 +0800 Subject: [PATCH 010/193] issue #3627, remove lua/js doxygen mark from LabelAtals constructor & destructor. --- cocos/2d/CCLabelAtlas.h | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/cocos/2d/CCLabelAtlas.h b/cocos/2d/CCLabelAtlas.h index 4eb25b67af..47064c14c7 100644 --- a/cocos/2d/CCLabelAtlas.h +++ b/cocos/2d/CCLabelAtlas.h @@ -86,16 +86,10 @@ public: #endif protected: - /** - * @js ctor - */ LabelAtlas() :_string("") {} - /** - * @js NA - * @lua NA - */ + virtual ~LabelAtlas() { _string.clear(); From 1ad14340bfd7c5e3269dff3b68c2c32036c412d2 Mon Sep 17 00:00:00 2001 From: walzer Date: Thu, 9 Jan 2014 14:26:34 +0800 Subject: [PATCH 011/193] issue #3627, remove Hungarian Notation in LabelAtlas --- cocos/2d/CCLabelAtlas.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos/2d/CCLabelAtlas.cpp b/cocos/2d/CCLabelAtlas.cpp index 99f7baba0a..200bec0641 100644 --- a/cocos/2d/CCLabelAtlas.cpp +++ b/cocos/2d/CCLabelAtlas.cpp @@ -60,13 +60,13 @@ LabelAtlas* LabelAtlas::create() LabelAtlas* LabelAtlas::create(const std::string& string, const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) { - LabelAtlas *pRet = new LabelAtlas(); - if(pRet && pRet->initWithString(string, charMapFile, itemWidth, itemHeight, startCharMap)) + LabelAtlas* ret = new LabelAtlas(); + if(ret && ret->initWithString(string, charMapFile, itemWidth, itemHeight, startCharMap)) { - pRet->autorelease(); - return pRet; + ret->autorelease(); + return ret; } - CC_SAFE_DELETE(pRet); + CC_SAFE_DELETE(ret); return nullptr; } From 1b339a46352b0302c8dd799dce82e5cb5bd504c8 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Thu, 9 Jan 2014 14:50:29 +0800 Subject: [PATCH 012/193] Add Test Case: LayerColor should not occlude sprites and labels when depth test is true --- .../TestCpp/Classes/LayerTest/LayerTest.cpp | 25 +++++++++++++++++++ .../Cpp/TestCpp/Classes/LayerTest/LayerTest.h | 13 ++++++++++ 2 files changed, 38 insertions(+) diff --git a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp index 1c1ae1084a..0bbb8cc63a 100644 --- a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.cpp @@ -25,6 +25,7 @@ static std::function createFunctions[] = { CL(LayerExtendedBlendOpacityTest), CL(LayerBug3162A), CL(LayerBug3162B), + CL(LayerColorOccludeBug), }; static int sceneIdx=-1; @@ -954,3 +955,27 @@ std::string LayerBug3162B::subtitle() const { return "u and m layer color is effected/diseffected with b layer"; } + +std::string LayerColorOccludeBug::title() const +{ + return "Layer Color Occlude Bug Test"; +} + +std::string LayerColorOccludeBug::subtitle() const +{ + return "Layer Color Should not occlude titles and any sprites"; +} + +void LayerColorOccludeBug::onEnter() +{ + LayerTest::onEnter(); + Director::getInstance()->setDepthTest(true); + _layer = LayerColor::create(Color4B(0, 80, 95, 255)); + addChild(_layer); +} + +void LayerColorOccludeBug::onExit() +{ + LayerTest::onExit(); + Director::getInstance()->setDepthTest(false); +} diff --git a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.h b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.h index 61a8602200..61b4f6fc2c 100644 --- a/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.h +++ b/samples/Cpp/TestCpp/Classes/LayerTest/LayerTest.h @@ -202,6 +202,19 @@ private: LayerColor* _layer[3]; }; +class LayerColorOccludeBug : public LayerTest +{ +public: + CREATE_FUNC(LayerColorOccludeBug); + virtual void onEnter() override; + virtual void onExit() override; + virtual std::string title() const override; + virtual std::string subtitle() const override; + +private: + LayerColor* _layer; +}; + class LayerTestScene : public TestScene { public: From ce0b86e7fe41aebabcada91026560ef038af6e55 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Thu, 9 Jan 2014 06:56:48 +0000 Subject: [PATCH 013/193] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 4a690da567..17d3f11698 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 4a690da5675369f036f3fc3dd553afaa1b10f1de +Subproject commit 17d3f116985b86a820a648927ea1fc5cfe5951d3 From f8d369248b61152fff514be173ad3ebd16605dfd Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 9 Jan 2014 15:18:06 +0800 Subject: [PATCH 014/193] closed #3605: Websocket doesn't support send/receive data which larger than 4096 bytes, renames member variables to follow cocos2d-x coding guide line. --- cocos/network/WebSocket.cpp | 60 ++++++++++++++++++------------------- cocos/network/WebSocket.h | 10 +++---- 2 files changed, 35 insertions(+), 35 deletions(-) diff --git a/cocos/network/WebSocket.cpp b/cocos/network/WebSocket.cpp index 3f81e5ba90..5e17487567 100644 --- a/cocos/network/WebSocket.cpp +++ b/cocos/network/WebSocket.cpp @@ -46,7 +46,7 @@ namespace network { class WsMessage { public: - WsMessage() : what(0), obj(NULL){} + WsMessage() : what(0), obj(nullptr){} unsigned int what; // message type void* obj; }; @@ -114,7 +114,7 @@ public: // Implementation of WsThreadHelper WsThreadHelper::WsThreadHelper() : _subThreadInstance(nullptr) -, _ws(NULL) +, _ws(nullptr) , _needQuit(false) { _UIWsMessageQueue = new std::list(); @@ -183,7 +183,7 @@ void WsThreadHelper::joinSubThread() void WsThreadHelper::update(float dt) { - WsMessage *msg = NULL; + WsMessage *msg = nullptr; // Returns quickly if no message std::lock_guard lk(_UIWsMessageQueueMutex); @@ -223,9 +223,9 @@ WebSocket::WebSocket() , _delegate(nullptr) , _SSLConnection(0) , _wsProtocols(nullptr) -, _pending_frame_data_len(0) -, _current_data_len(0) -, _current_data(NULL) +, _pendingFrameDataLen(0) +, _currentDataLen(0) +, _currentData(nullptr) { } @@ -243,7 +243,7 @@ WebSocket::~WebSocket() bool WebSocket::init(const Delegate& delegate, const std::string& url, - const std::vector* protocols/* = NULL*/) + const std::vector* protocols/* = nullptr*/) { bool ret = false; bool useSSL = false; @@ -604,60 +604,60 @@ int WebSocket::onSocketCallback(struct libwebsocket_context *ctx, if (in && len > 0) { // Accumulate the data (increasing the buffer as we go) - if (_current_data_len == 0) + if (_currentDataLen == 0) { - _current_data = new char[len]; - memcpy (_current_data, in, len); - _current_data_len = len; + _currentData = new char[len]; + memcpy (_currentData, in, len); + _currentDataLen = len; } else { - char *new_data = new char [_current_data_len + len]; - memcpy (new_data, _current_data, _current_data_len); - memcpy (new_data + _current_data_len, in, len); - CC_SAFE_DELETE_ARRAY(_current_data); - _current_data = new_data; - _current_data_len = _current_data_len + len; + char *new_data = new char [_currentDataLen + len]; + memcpy (new_data, _currentData, _currentDataLen); + memcpy (new_data + _currentDataLen, in, len); + CC_SAFE_DELETE_ARRAY(_currentData); + _currentData = new_data; + _currentDataLen = _currentDataLen + len; } - _pending_frame_data_len = libwebsockets_remaining_packet_payload (wsi); + _pendingFrameDataLen = libwebsockets_remaining_packet_payload (wsi); - if (_pending_frame_data_len > 0) + if (_pendingFrameDataLen > 0) { - //CCLOG("%ld bytes of pending data to receive, consider increasing the libwebsocket rx_buffer_size value.", _pending_frame_data_len); + //CCLOG("%ld bytes of pending data to receive, consider increasing the libwebsocket rx_buffer_size value.", _pendingFrameDataLen); } // If no more data pending, send it to the client thread - if (_pending_frame_data_len == 0) + if (_pendingFrameDataLen == 0) { WsMessage* msg = new WsMessage(); msg->what = WS_MSG_TO_UITHREAD_MESSAGE; - char* bytes = NULL; + char* bytes = nullptr; Data* data = new Data(); if (lws_frame_is_binary(wsi)) { - bytes = new char[_current_data_len]; + bytes = new char[_currentDataLen]; data->isBinary = true; } else { - bytes = new char[_current_data_len+1]; - bytes[_current_data_len] = '\0'; + bytes = new char[_currentDataLen+1]; + bytes[_currentDataLen] = '\0'; data->isBinary = false; } - memcpy(bytes, _current_data, _current_data_len); + memcpy(bytes, _currentData, _currentDataLen); data->bytes = bytes; - data->len = _current_data_len; + data->len = _currentDataLen; msg->obj = (void*)data; - CC_SAFE_DELETE_ARRAY(_current_data); - _current_data = NULL; - _current_data_len = 0; + CC_SAFE_DELETE_ARRAY(_currentData); + _currentData = nullptr; + _currentDataLen = 0; _wsHelper->sendMessageToUIThread(msg); } diff --git a/cocos/network/WebSocket.h b/cocos/network/WebSocket.h index 830d9fb2ee..738abf2c2f 100644 --- a/cocos/network/WebSocket.h +++ b/cocos/network/WebSocket.h @@ -62,7 +62,7 @@ public: */ struct Data { - Data():bytes(NULL), len(0), issued(0), isBinary(false){} + Data():bytes(nullptr), len(0), issued(0), isBinary(false){} char* bytes; ssize_t len, issued; bool isBinary; @@ -112,7 +112,7 @@ public: */ bool init(const Delegate& delegate, const std::string& url, - const std::vector* protocols = NULL); + const std::vector* protocols = nullptr); /** * @brief Sends string data to websocket server. @@ -153,9 +153,9 @@ private: unsigned int _port; std::string _path; - size_t _pending_frame_data_len; - unsigned int _current_data_len; - char *_current_data; + size_t _pendingFrameDataLen; + unsigned int _currentDataLen; + char *_currentData; friend class WsThreadHelper; WsThreadHelper* _wsHelper; From e063755596531755527f214a5d9c5a0ea5d14fa3 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 9 Jan 2014 15:26:05 +0800 Subject: [PATCH 015/193] fix Image crashes in mac when load tag file --- cocos/2d/platform/CCImageCommon_cpp.h | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/cocos/2d/platform/CCImageCommon_cpp.h b/cocos/2d/platform/CCImageCommon_cpp.h index 6c5c7a2d96..fa331d313f 100644 --- a/cocos/2d/platform/CCImageCommon_cpp.h +++ b/cocos/2d/platform/CCImageCommon_cpp.h @@ -391,10 +391,7 @@ Image::Image() Image::~Image() { - if (_data != nullptr) - { - free(_data); - } + CC_SAFE_FREE(_data); } bool Image::initWithImageFile(const std::string& path) @@ -1539,7 +1536,7 @@ bool Image::initWithTGAData(tImageTGA* tgaData) }while(false); - if (!ret) + if (ret) { const unsigned char tgaSuffix[] = ".tga"; for(int i = 0; i < 4; ++i) @@ -1556,6 +1553,7 @@ bool Image::initWithTGAData(tImageTGA* tgaData) if (tgaData->imageData != nullptr) { free(tgaData->imageData); + _data = nullptr; } } From b8528351c4ed3a127dbbbb4e59ae855a79eadb02 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 9 Jan 2014 15:26:24 +0800 Subject: [PATCH 016/193] Update AUTHORS [ci skip] --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index 695374eccc..2eb0817f4c 100644 --- a/AUTHORS +++ b/AUTHORS @@ -519,6 +519,7 @@ Developers: Correcting the type detecting order for Lua CCBProxy::getNodeTypeName. Casting variables to their own type, and print warning info if no corresponding lua callback function instead of crash. fix of WebSocket url parse error for 'ws://domain.com/websocket' pattern. + Fixed a bug that Websocket doesn't support send/receive data which larger than 4096 bytes. musikov Fixing a bug that missing precision when getting strokeColor and fontFillColor From 43a9c84cc2a598af31c39c4d83c86cf18d6a9434 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 9 Jan 2014 15:26:54 +0800 Subject: [PATCH 017/193] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 89df2ce901..505c7e208b 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -3,6 +3,7 @@ cocos2d-x-3.0final ?.? ? [FIX] Crash was triggered if there is not `textureFileName`section in particle plist file. [FIX] ControlSlider doesn't support to set selected thumb sprite. [FIX] ControlButton doesn't support to set scale ratio of touchdown state. + [FIX] Websocket doesn't support send/receive data which larger than 4096 bytes. cocos2d-x-3.0beta Jan.7 2014 [All] [NEW] New label: shadow, outline, glow support From 19f0e5546470d97ae060d1f80c013ba49deca16c Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Thu, 9 Jan 2014 15:43:18 +0800 Subject: [PATCH 018/193] fixed bug of layout --- cocos/gui/UILayout.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp index c70f109a14..fcdb4fb621 100644 --- a/cocos/gui/UILayout.cpp +++ b/cocos/gui/UILayout.cpp @@ -490,6 +490,7 @@ const Rect& Layout::getClippingRect() void Layout::onSizeChanged() { Widget::onSizeChanged(); + setContentSize(_size); setStencilClippingSize(_size); _doLayoutDirty = true; if (_backGroundImage) From ccda90cab5d6ff482d5244a4e3f284f79267cbd7 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 9 Jan 2014 15:52:04 +0800 Subject: [PATCH 019/193] fix compiling error in CCControlSlider.cpp on vs. --- extensions/GUI/CCControlExtension/CCControlSlider.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/GUI/CCControlExtension/CCControlSlider.cpp b/extensions/GUI/CCControlExtension/CCControlSlider.cpp index 6dbd30f512..ace6ef2cec 100644 --- a/extensions/GUI/CCControlExtension/CCControlSlider.cpp +++ b/extensions/GUI/CCControlExtension/CCControlSlider.cpp @@ -109,7 +109,7 @@ bool ControlSlider::initWithSprites(Sprite * backgroundSprite, Sprite* progressS Sprite* selectedThumbSprite = Sprite::createWithTexture(thumbSprite->getTexture(), thumbSprite->getTextureRect()); selectedThumbSprite->setColor(Color3B::GRAY); - this->initWithSprites(backgroundSprite, progressSprite, thumbSprite, selectedThumbSprite); + return this->initWithSprites(backgroundSprite, progressSprite, thumbSprite, selectedThumbSprite); } bool ControlSlider::initWithSprites(Sprite * backgroundSprite, Sprite* progressSprite, Sprite* thumbSprite, From e34ef0d38fb67fd38cae826a2fae75cd35dc963e Mon Sep 17 00:00:00 2001 From: boyu0 Date: Thu, 9 Jan 2014 16:33:31 +0800 Subject: [PATCH 020/193] change initialization _data from 0 to nullptr. --- cocos/2d/platform/CCImageCommon_cpp.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/platform/CCImageCommon_cpp.h b/cocos/2d/platform/CCImageCommon_cpp.h index fa331d313f..40eeca0ae7 100644 --- a/cocos/2d/platform/CCImageCommon_cpp.h +++ b/cocos/2d/platform/CCImageCommon_cpp.h @@ -376,7 +376,7 @@ namespace ////////////////////////////////////////////////////////////////////////// Image::Image() -: _data(0) +: _data(nullptr) , _dataLen(0) , _width(0) , _height(0) From f523c1c2fdc9686e820bdb484a3ae2aeb4bedca7 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 9 Jan 2014 17:12:58 +0800 Subject: [PATCH 021/193] Update AUTHORS [ci skip] --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index 2eb0817f4c..f5895c2f29 100644 --- a/AUTHORS +++ b/AUTHORS @@ -356,6 +356,7 @@ Developers: ThePickleMan Adding 'rotationIsDir' property to ParticleSystem. + DrawNode supports to draw triangle, quad bezier, cubic bezier. Jianghua (jxhgzs) Adding an additional transform for CCNode. From ffdfcfbefbd95bbea4ace11256de2f0b0ddb370b Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 9 Jan 2014 17:13:34 +0800 Subject: [PATCH 022/193] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 505c7e208b..420e678c08 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -4,6 +4,7 @@ cocos2d-x-3.0final ?.? ? [FIX] ControlSlider doesn't support to set selected thumb sprite. [FIX] ControlButton doesn't support to set scale ratio of touchdown state. [FIX] Websocket doesn't support send/receive data which larger than 4096 bytes. + [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. cocos2d-x-3.0beta Jan.7 2014 [All] [NEW] New label: shadow, outline, glow support From f14bbd59c95cb3df06b7a4c30b553433856b978b Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 9 Jan 2014 17:16:09 +0800 Subject: [PATCH 023/193] Adding clang build for travis ci. --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 1e67e468bf..d46929bd03 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,6 +3,7 @@ env: matrix: - GEN_JSB=YES - PLATFORM=linux DEBUG=1 + - PLATFORM=linux DEBUG=1 CLANG=1 # Since switching to C++11 only the ARM version of the nactive client # port currently builds. TODO(sbc): Re-enable all architectures. # Disabled travis-ci build for native client port since it doesn't support std::thread, std::mutex. From c60681c556cac9093ed6ca9e3efe752e4c75c9cf Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Thu, 9 Jan 2014 09:17:11 +0000 Subject: [PATCH 024/193] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 17d3f11698..f7835c1364 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 17d3f116985b86a820a648927ea1fc5cfe5951d3 +Subproject commit f7835c13644591879f5a995074ccc8faf70c355e From 2cbe502113bd8f972c1811062eb4e651b5fc74a9 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Thu, 9 Jan 2014 17:23:22 +0800 Subject: [PATCH 025/193] issue #3643:Lua websocket can't receive more than 64 bytes of data --- .../scripting/lua/bindings/Lua_web_socket.cpp | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/cocos/scripting/lua/bindings/Lua_web_socket.cpp b/cocos/scripting/lua/bindings/Lua_web_socket.cpp index 8301c75d8f..4d3b8ae715 100644 --- a/cocos/scripting/lua/bindings/Lua_web_socket.cpp +++ b/cocos/scripting/lua/bindings/Lua_web_socket.cpp @@ -102,18 +102,22 @@ void LuaWebSocket::onMessage(WebSocket* ws, const WebSocket::Data& data) LuaWebSocket* luaWs = dynamic_cast(ws); if (NULL != luaWs) { if (data.isBinary) { - int nHandler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this,ScriptHandlerMgr::HandlerType::WEBSOCKET_MESSAGE); - if (0 != nHandler) { - SendBinaryMessageToLua(nHandler, (const unsigned char*)data.bytes, data.len); + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this,ScriptHandlerMgr::HandlerType::WEBSOCKET_MESSAGE); + if (0 != handler) { + SendBinaryMessageToLua(handler, (const unsigned char*)data.bytes, data.len); } } else{ - int nHandler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this,ScriptHandlerMgr::HandlerType::WEBSOCKET_MESSAGE); - if (0 != nHandler) { - CommonScriptData commonData(nHandler,data.bytes); - ScriptEvent event(kCommonEvent,(void*)&commonData); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this,ScriptHandlerMgr::HandlerType::WEBSOCKET_MESSAGE); + if (0 != handler) + { + LuaStack* stack = LuaEngine::getInstance()->getLuaStack(); + if (nullptr != stack) + { + stack->pushString(data.bytes,data.len); + stack->executeFunctionByHandler(handler, 1); + } } } } From c0195015c3aa82cadfdf267dac0b4eddc1cd978c Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 9 Jan 2014 17:26:33 +0800 Subject: [PATCH 026/193] updates CC and CCX env variables --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d46929bd03..bf21d1dcef 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,7 +3,7 @@ env: matrix: - GEN_JSB=YES - PLATFORM=linux DEBUG=1 - - PLATFORM=linux DEBUG=1 CLANG=1 + - PLATFORM=linux DEBUG=1 CC=/usr/bin/clang CXX=/usr/bin/clang++ # Since switching to C++11 only the ARM version of the nactive client # port currently builds. TODO(sbc): Re-enable all architectures. # Disabled travis-ci build for native client port since it doesn't support std::thread, std::mutex. From 4b4dc160309ac083c6ef89f1406bd3c6c05b354e Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 9 Jan 2014 17:48:08 +0800 Subject: [PATCH 027/193] Exports CC and CXX for gcc and clang. --- .travis.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index bf21d1dcef..762cbcbf06 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,8 +2,8 @@ language: cpp env: matrix: - GEN_JSB=YES - - PLATFORM=linux DEBUG=1 - - PLATFORM=linux DEBUG=1 CC=/usr/bin/clang CXX=/usr/bin/clang++ + - PLATFORM=linux DEBUG=1 CC_COMPILER=gcc CXX_COMPILER=g++ + - PLATFORM=linux DEBUG=1 CC_COMPILER=clang CXX_COMPILER=clang++ # Since switching to C++11 only the ARM version of the nactive client # port currently builds. TODO(sbc): Re-enable all architectures. # Disabled travis-ci build for native client port since it doesn't support std::thread, std::mutex. @@ -24,6 +24,8 @@ env: 9lV+vgJQDRcFe7dKwtC86vk10EU7Ym2bhVmhMxi/AlmJXgavjmPVdizRT7rh X2Ry/Nb6hGRkH3WS0T3D/KG1+e7lP/TMB9bvo6/locLJ2A6Z1YI= script: +- export CC=$CC_COMPILER +- export CXX=$CXX_COMPILER - tools/travis-scripts/run-script.sh before_install: - tools/travis-scripts/before-install.sh From 4dbb0ee1e878da1d1da986455f601355c936f2e2 Mon Sep 17 00:00:00 2001 From: WuHuan Date: Thu, 9 Jan 2014 17:48:37 +0800 Subject: [PATCH 028/193] mingw console --- cocos/base/CCConsole.cpp | 4 +--- samples/Cpp/TestCpp/CMakeLists.txt | 12 +++++++++++- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index f876b4ad48..6eb9256a67 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -102,9 +102,7 @@ static const char* inet_ntop(int af, const void* src, char* dst, int cnt) srcaddr.sin_family = af; if (WSAAddressToString((struct sockaddr*) &srcaddr, sizeof(struct sockaddr_in), 0, dst, (LPDWORD) &cnt) != 0) { - DWORD rv = WSAGetLastError(); - printf("WSAAddressToString() : %d\n",rv); - return NULL; + return nullptr; } return dst; } diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt index 2c3fc4033e..155ad7a2ae 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -1,5 +1,15 @@ set(APP_NAME testcpp) +if(WIN32) + set(PLATFORM_SRC + proj.win32/main.cpp + ) +else() + set(PLATFORM_SRC + proj.linux/main.cpp + ) +endif() + set(SAMPLE_SRC Classes/AccelerometerTest/AccelerometerTest.cpp Classes/ActionManagerTest/ActionManagerTest.cpp @@ -136,7 +146,7 @@ set(SAMPLE_SRC Classes/AppDelegate.cpp Classes/BaseTest.cpp Classes/VisibleRect.cpp - proj.linux/main.cpp + ${PLATFORM_SRC} ) include_directories( From 2e4c76a5d7e4d987d5d967a6a7ad898f09ba0e12 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 9 Jan 2014 18:34:04 +0800 Subject: [PATCH 029/193] closed #3644: Keyboard pressed events are being repeatedly fired before keyboard is released. --- cocos/2d/platform/linux/CCEGLView.cpp | 9 ++++++--- cocos/2d/platform/mac/CCEGLView.mm | 9 ++++++--- cocos/2d/platform/win32/CCEGLView.cpp | 9 ++++++--- 3 files changed, 18 insertions(+), 9 deletions(-) diff --git a/cocos/2d/platform/linux/CCEGLView.cpp b/cocos/2d/platform/linux/CCEGLView.cpp index 2cab145265..ac410b2f74 100644 --- a/cocos/2d/platform/linux/CCEGLView.cpp +++ b/cocos/2d/platform/linux/CCEGLView.cpp @@ -274,9 +274,12 @@ void EGLViewEventHandler::OnGLFWMouseScrollCallback(GLFWwindow* window, double x void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { - EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action || GLFW_REPEAT == action); - auto dispatcher = Director::getInstance()->getEventDispatcher(); - dispatcher->dispatchEvent(&event); + if (GLFW_REPEAT != action) + { + EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); + auto dispatcher = Director::getInstance()->getEventDispatcher(); + dispatcher->dispatchEvent(&event); + } } void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character) diff --git a/cocos/2d/platform/mac/CCEGLView.mm b/cocos/2d/platform/mac/CCEGLView.mm index 920212e5f5..afd9c66b92 100644 --- a/cocos/2d/platform/mac/CCEGLView.mm +++ b/cocos/2d/platform/mac/CCEGLView.mm @@ -279,9 +279,12 @@ void EGLViewEventHandler::OnGLFWMouseScrollCallback(GLFWwindow* window, double x void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { - EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action || GLFW_REPEAT == action); - auto dispatcher = Director::getInstance()->getEventDispatcher(); - dispatcher->dispatchEvent(&event); + if (GLFW_REPEAT != action) + { + EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); + auto dispatcher = Director::getInstance()->getEventDispatcher(); + dispatcher->dispatchEvent(&event); + } } void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character) diff --git a/cocos/2d/platform/win32/CCEGLView.cpp b/cocos/2d/platform/win32/CCEGLView.cpp index 953dede055..b6a7c5e62b 100644 --- a/cocos/2d/platform/win32/CCEGLView.cpp +++ b/cocos/2d/platform/win32/CCEGLView.cpp @@ -374,9 +374,12 @@ void EGLViewEventHandler::OnGLFWMouseScrollCallback(GLFWwindow* window, double x void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { - EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action || GLFW_REPEAT == action); - auto dispatcher = Director::getInstance()->getEventDispatcher(); - dispatcher->dispatchEvent(&event); + if (GLFW_REPEAT != action) + { + EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); + auto dispatcher = Director::getInstance()->getEventDispatcher(); + dispatcher->dispatchEvent(&event); + } } void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character) From c3b7a9645ae805232bba9edfe3bd41d4e6d6adea Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Thu, 9 Jan 2014 19:00:47 +0800 Subject: [PATCH 030/193] Fixed bugs of "anchor point" and "update" --- cocos/gui/UILayout.cpp | 11 +++++++++ cocos/gui/UILayout.h | 2 ++ cocos/gui/UIPageView.cpp | 2 +- cocos/gui/UIScrollView.cpp | 7 +----- cocos/gui/UIScrollView.h | 3 --- cocos/gui/UITextField.cpp | 2 +- cocos/gui/UIWidget.cpp | 49 ++++++++------------------------------ cocos/gui/UIWidget.h | 21 +--------------- 8 files changed, 27 insertions(+), 70 deletions(-) diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp index fcdb4fb621..e4c9c1f66f 100644 --- a/cocos/gui/UILayout.cpp +++ b/cocos/gui/UILayout.cpp @@ -156,6 +156,17 @@ bool Layout::isClippingEnabled() return _clippingEnabled; } +bool Layout::hitTest(const Point &pt) +{ + Point nsp = convertToNodeSpace(pt); + Rect bb = Rect(0.0f, 0.0f, _size.width, _size.height); + if (nsp.x >= bb.origin.x && nsp.x <= bb.origin.x + bb.size.width && nsp.y >= bb.origin.y && nsp.y <= bb.origin.y + bb.size.height) + { + return true; + } + return false; +} + void Layout::visit() { if (!_enabled) diff --git a/cocos/gui/UILayout.h b/cocos/gui/UILayout.h index 2595cf125e..fffb6aaad1 100644 --- a/cocos/gui/UILayout.h +++ b/cocos/gui/UILayout.h @@ -217,6 +217,8 @@ public: virtual void onEnter() override; virtual void onExit() override; + + virtual bool hitTest(const Point &pt); protected: //override "init" method of widget. virtual bool init() override; diff --git a/cocos/gui/UIPageView.cpp b/cocos/gui/UIPageView.cpp index 2ad5a8c533..cc265a7f89 100644 --- a/cocos/gui/UIPageView.cpp +++ b/cocos/gui/UIPageView.cpp @@ -70,7 +70,7 @@ PageView* PageView::create() void PageView::onEnter() { Layout::onEnter(); - setUpdateEnabled(true); + scheduleUpdate(); } bool PageView::init() diff --git a/cocos/gui/UIScrollView.cpp b/cocos/gui/UIScrollView.cpp index 33dee12004..8bb23aae8d 100644 --- a/cocos/gui/UIScrollView.cpp +++ b/cocos/gui/UIScrollView.cpp @@ -97,7 +97,7 @@ ScrollView* ScrollView::create() void ScrollView::onEnter() { Layout::onEnter(); - setUpdateEnabled(true); + scheduleUpdate(); } bool ScrollView::init() @@ -1457,11 +1457,6 @@ void ScrollView::onTouchCancelled(Touch *touch, Event *unusedEvent) handleReleaseLogic(touch->getLocation()); } -void ScrollView::onTouchLongClicked(const Point &touchPoint) -{ - -} - void ScrollView::update(float dt) { if (_autoScroll) diff --git a/cocos/gui/UIScrollView.h b/cocos/gui/UIScrollView.h index 9a0a9f889b..ae49fa02ea 100644 --- a/cocos/gui/UIScrollView.h +++ b/cocos/gui/UIScrollView.h @@ -279,9 +279,6 @@ public: virtual void onTouchEnded(Touch *touch, Event *unusedEvent) override; virtual void onTouchCancelled(Touch *touch, Event *unusedEvent) override; - //override "onTouchLongClicked" method of widget. - virtual void onTouchLongClicked(const Point &touchPoint) override; - virtual void update(float dt) override; void setBounceEnabled(bool enabled); diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index 95f5ccaea6..c463293006 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -304,7 +304,7 @@ TextField* TextField::create() void TextField::onEnter() { Widget::onEnter(); - setUpdateEnabled(true); + scheduleUpdate(); } void TextField::initRenderer() diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index f0a8c1dba9..e28f4d8db0 100644 --- a/cocos/gui/UIWidget.cpp +++ b/cocos/gui/UIWidget.cpp @@ -37,7 +37,6 @@ _touchEnabled(false), _touchPassedEnabled(false), _focus(false), _brightStyle(BRIGHT_NONE), -_updateEnabled(false), _touchStartPos(Point::ZERO), _touchMovePos(Point::ZERO), _touchEndPos(Point::ZERO), @@ -105,6 +104,7 @@ void Widget::onEnter() void Widget::onExit() { + unscheduleUpdate(); Node::onExit(); } @@ -623,28 +623,6 @@ bool Widget::isTouchEnabled() const return _touchEnabled; } -void Widget::setUpdateEnabled(bool enable) -{ - if (enable == _updateEnabled) - { - return; - } - _updateEnabled = enable; - if (enable) - { - scheduleUpdate(); - } - else - { - unscheduleUpdate(); - } -} - -bool Widget::isUpdateEnabled() -{ - return _updateEnabled; -} - bool Widget::isFocused() const { return _focus; @@ -730,11 +708,15 @@ void Widget::didNotSelectSelf() bool Widget::onTouchBegan(Touch *touch, Event *unusedEvent) { - _touchStartPos = touch->getLocation(); - _hitted = isEnabled() - & isTouchEnabled() - & hitTest(_touchStartPos) - & clippingParentAreaContainPoint(_touchStartPos); + _hitted = false; + if (isEnabled() && isTouchEnabled()) + { + _touchStartPos = touch->getLocation(); + if(hitTest(_touchStartPos) && clippingParentAreaContainPoint(_touchStartPos)) + { + _hitted = true; + } + } if (!_hitted) { return false; @@ -787,11 +769,6 @@ void Widget::onTouchCancelled(Touch *touch, Event *unusedEvent) cancelUpEvent(); } -void Widget::onTouchLongClicked(const Point &touchPoint) -{ - longClickEvent(); -} - void Widget::pushDownEvent() { if (_touchEventListener && _touchEventSelector) @@ -824,11 +801,6 @@ void Widget::cancelUpEvent() } } -void Widget::longClickEvent() -{ - -} - void Widget::addTouchEventListener(Object *target, SEL_TouchEvent selector) { _touchEventListener = target; @@ -1069,7 +1041,6 @@ void Widget::copyProperties(Widget *widget) setTouchEnabled(widget->isTouchEnabled()); _touchPassedEnabled = false; setZOrder(widget->getZOrder()); - setUpdateEnabled(widget->isUpdateEnabled()); setTag(widget->getTag()); setName(widget->getName()); setActionTag(widget->getActionTag()); diff --git a/cocos/gui/UIWidget.h b/cocos/gui/UIWidget.h index c0d664d634..d07bc4bee8 100644 --- a/cocos/gui/UIWidget.h +++ b/cocos/gui/UIWidget.h @@ -550,14 +550,7 @@ public: virtual void onTouchMoved(Touch *touch, Event *unusedEvent); virtual void onTouchEnded(Touch *touch, Event *unusedEvent); virtual void onTouchCancelled(Touch *touch, Event *unusedEvent); - - /** - * A call back function called when widget is selected, and on touch long clicked. - * - * @param touch point - */ - virtual void onTouchLongClicked(const Point &touchPoint); - + /** * Sets a LayoutParameter to widget. * @@ -610,16 +603,6 @@ public: */ virtual Node* getVirtualRenderer(); - /** - * Schedules the "update" method. - */ - void setUpdateEnabled(bool enable); - - /** - * is the "update" method scheduled. - */ - bool isUpdateEnabled(); - /** * Gets the content size of widget. * @@ -664,7 +647,6 @@ protected: void moveEvent(); void releaseUpEvent(); void cancelUpEvent(); - void longClickEvent(); void updateAnchorPoint(); void copyProperties(Widget* model); virtual Widget* createCloneInstance(); @@ -678,7 +660,6 @@ protected: bool _touchPassedEnabled; ///< is the touch event should be passed bool _focus; ///< is the widget on focus BrightStyle _brightStyle; ///< bright style - bool _updateEnabled; ///< is "update" method scheduled Point _touchStartPos; ///< touch began point Point _touchMovePos; ///< touch moved point Point _touchEndPos; ///< touch ended point From f87af9e9986bf4f25305c5a84ce10ad4f0bf201c Mon Sep 17 00:00:00 2001 From: WuHuan Date: Thu, 9 Jan 2014 19:49:11 +0800 Subject: [PATCH 031/193] fix linux build --- cocos/network/CMakeLists.txt | 13 +++++++++++-- samples/Cpp/TestCpp/CMakeLists.txt | 6 +++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/cocos/network/CMakeLists.txt b/cocos/network/CMakeLists.txt index ac1088485c..e57b04ccf9 100644 --- a/cocos/network/CMakeLists.txt +++ b/cocos/network/CMakeLists.txt @@ -1,7 +1,16 @@ +if(WIN32) + set(PLATFORM_SRC + WebSocket.cpp + ) + set(PLATFORM_LINK + websockets + ) +endif() + set(NETWORK_SRC HttpClient.cpp SocketIO.cpp - WebSocket.cpp + ${PLATFORM_SRC} ) add_library(network STATIC @@ -10,7 +19,7 @@ add_library(network STATIC target_link_libraries(network curl - websockets + ${PLATFORM_LINK} ) set_target_properties(network diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt index 155ad7a2ae..5f409f7601 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -2,6 +2,9 @@ set(APP_NAME testcpp) if(WIN32) set(PLATFORM_SRC + Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp + Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp + Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp proj.win32/main.cpp ) else() @@ -60,10 +63,7 @@ set(SAMPLE_SRC Classes/ExtensionsTest/TableViewTest/CustomTableViewCell.cpp Classes/ExtensionsTest/ExtensionsTest.cpp Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp - Classes/ExtensionsTest/EditBoxTest/EditBoxTest.cpp Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp - Classes/ExtensionsTest/NetworkTest/WebSocketTest.cpp - Classes/ExtensionsTest/NetworkTest/SocketIOTest.cpp Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp Classes/ExtensionsTest/CocoStudioComponentsTest/ComponentsTestScene.cpp Classes/ExtensionsTest/CocoStudioComponentsTest/EnemyController.cpp From d13612ef32efdaf054d43cb05d4f5c1ee1516447 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 9 Jan 2014 11:38:44 -0800 Subject: [PATCH 032/193] Improves description in camera test --- samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp index 5c2534dee0..8ea66b04b7 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp @@ -852,6 +852,7 @@ public: protected: CustomCommand _customCommand; + }; void MySprite::draw() @@ -928,7 +929,7 @@ std::string CameraTest2::title() const std::string CameraTest2::subtitle() const { - return "Background image should be rotated in 3D"; + return "Both images should look the same"; } void CameraTest2::update(float dt) @@ -948,6 +949,7 @@ void CameraTest2::update(float dt) } /// +/// main /// void CocosNodeTestScene::runThisTest() { From 1dc169b19f170e69c1c28c28b62a903831c1d4c4 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 9 Jan 2014 14:26:22 -0800 Subject: [PATCH 033/193] Camera is working again Projection is passed in the shader. Since P is in the shader, QuadCommand uses `Vec3Transform` instead of `Vec3TransformCoord` since it is faster. --- .../2d/ccShader_PositionTextureColor_noMVP_vert.h | 2 +- cocos/2d/renderer/CCQuadCommand.cpp | 14 ++++---------- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/cocos/2d/ccShader_PositionTextureColor_noMVP_vert.h b/cocos/2d/ccShader_PositionTextureColor_noMVP_vert.h index fb511ba1dd..bae95bcfea 100644 --- a/cocos/2d/ccShader_PositionTextureColor_noMVP_vert.h +++ b/cocos/2d/ccShader_PositionTextureColor_noMVP_vert.h @@ -38,7 +38,7 @@ varying vec2 v_texCoord; \n\ \n\ void main() \n\ { \n\ - gl_Position = a_position; \n\ + gl_Position = CC_PMatrix * a_position; \n\ v_fragmentColor = a_color; \n\ v_texCoord = a_texCoord; \n\ } \n\ diff --git a/cocos/2d/renderer/CCQuadCommand.cpp b/cocos/2d/renderer/CCQuadCommand.cpp index bbb7ba018c..b69fd075d3 100644 --- a/cocos/2d/renderer/CCQuadCommand.cpp +++ b/cocos/2d/renderer/CCQuadCommand.cpp @@ -58,12 +58,6 @@ void QuadCommand::init(int viewport, int32_t depth, GLuint textureID, GLProgram* _capacity = quadCount; } - kmMat4 p, mvp; - kmGLGetMatrix(KM_GL_PROJECTION, &p); - - kmMat4Multiply(&mvp, &p, &mv); - - _quadCount = quadCount; memcpy(_quad, quad, sizeof(V3F_C4B_T2F_Quad) * quadCount); @@ -74,7 +68,7 @@ void QuadCommand::init(int viewport, int32_t depth, GLuint textureID, GLProgram* vec1.x = q->bl.vertices.x; vec1.y = q->bl.vertices.y; vec1.z = q->bl.vertices.z; - kmVec3TransformCoord(&out1, &vec1, &mvp); + kmVec3Transform(&out1, &vec1, &mv); q->bl.vertices.x = out1.x; q->bl.vertices.y = out1.y; q->bl.vertices.z = out1.z; @@ -83,7 +77,7 @@ void QuadCommand::init(int viewport, int32_t depth, GLuint textureID, GLProgram* vec2.x = q->br.vertices.x; vec2.y = q->br.vertices.y; vec2.z = q->br.vertices.z; - kmVec3TransformCoord(&out2, &vec2, &mvp); + kmVec3Transform(&out2, &vec2, &mv); q->br.vertices.x = out2.x; q->br.vertices.y = out2.y; q->br.vertices.z = out2.z; @@ -92,7 +86,7 @@ void QuadCommand::init(int viewport, int32_t depth, GLuint textureID, GLProgram* vec3.x = q->tr.vertices.x; vec3.y = q->tr.vertices.y; vec3.z = q->tr.vertices.z; - kmVec3TransformCoord(&out3, &vec3, &mvp); + kmVec3Transform(&out3, &vec3, &mv); q->tr.vertices.x = out3.x; q->tr.vertices.y = out3.y; q->tr.vertices.z = out3.z; @@ -101,7 +95,7 @@ void QuadCommand::init(int viewport, int32_t depth, GLuint textureID, GLProgram* vec4.x = q->tl.vertices.x; vec4.y = q->tl.vertices.y; vec4.z = q->tl.vertices.z; - kmVec3TransformCoord(&out4, &vec4, &mvp); + kmVec3Transform(&out4, &vec4, &mv); q->tl.vertices.x = out4.x; q->tl.vertices.y = out4.y; q->tl.vertices.z = out4.z; From 95b7196a2a26ee71b2424444bc95a86657b7f094 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 9 Jan 2014 14:26:36 -0800 Subject: [PATCH 034/193] Adds more tests cases for Node Adds more tests cases for Node --- .../Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp | 114 +++++++++++++++++- .../Cpp/TestCpp/Classes/NodeTest/NodeTest.h | 27 ++++- 2 files changed, 134 insertions(+), 7 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp index 8ea66b04b7..843b72bbb6 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp @@ -25,6 +25,7 @@ static int sceneIdx = -1; static std::function createFunctions[] = { + CL(CameraTest1), CL(CameraTest2), CL(CameraCenterTest), CL(Test2), @@ -34,6 +35,7 @@ static std::function createFunctions[] = CL(StressTest1), CL(StressTest2), CL(NodeToWorld), + CL(NodeToWorld3D), CL(SchedulerTest1), CL(CameraOrbitTest), CL(CameraZoomTest), @@ -492,6 +494,56 @@ std::string NodeToWorld::title() const return "nodeToParent transform"; } +//------------------------------------------------------------------ +// +// NodeToWorld3D +// +//------------------------------------------------------------------ +NodeToWorld3D::NodeToWorld3D() +{ + // + // This code tests that nodeToParent works OK: + // - It tests different anchor Points + // - It tests different children anchor points + + Size s = Director::getInstance()->getWinSize(); + auto parent = Node::create(); + parent->setContentSize(s); + parent->setAnchorPoint(Point(0.5, 0.5)); + parent->setPosition(s.width/2, s.height/2); + this->addChild(parent); + + auto back = Sprite::create(s_back3); + parent->addChild( back, -10); + back->setAnchorPoint( Point(0,0) ); + auto backSize = back->getContentSize(); + + auto item = MenuItemImage::create(s_PlayNormal, s_PlaySelect); + auto menu = Menu::create(item, NULL); + menu->alignItemsVertically(); + menu->setPosition( Point(backSize.width/2, backSize.height/2)); + back->addChild(menu); + + auto rot = RotateBy::create(5, 360); + auto fe = RepeatForever::create( rot); + item->runAction( fe ); + + auto move = MoveBy::create(3, Point(200,0)); + auto move_back = move->reverse(); + auto seq = Sequence::create( move, move_back, NULL); + auto fe2 = RepeatForever::create(seq); + back->runAction(fe2); + + auto orbit = OrbitCamera::create(10, 0, 1, 0, 360, 0, 90); + parent->runAction(orbit); +} + +std::string NodeToWorld3D::title() const +{ + return "nodeToParent transform in 3D"; +} + + //------------------------------------------------------------------ // // CameraOrbitTest @@ -828,12 +880,10 @@ std::string NodeNonOpaqueTest::subtitle() const return "Node rendered with GL_BLEND enabled"; } -//------------------------------------------------------------------ -// -// CameraTest2 -// -//------------------------------------------------------------------ +// +// MySprite: Used by CameraTest1 and CameraTest2 +// class MySprite : public Sprite { public: @@ -852,7 +902,7 @@ public: protected: CustomCommand _customCommand; - + }; void MySprite::draw() @@ -892,6 +942,58 @@ void MySprite::onDraw() CHECK_GL_ERROR_DEBUG(); CC_INCREMENT_GL_DRAWS(1); } +//------------------------------------------------------------------ +// +// CameraTest1 +// +//------------------------------------------------------------------ + +void CameraTest1::onEnter() +{ + TestCocosNodeDemo::onEnter(); + Director::getInstance()->setProjection(Director::Projection::_3D); + Director::getInstance()->setDepthTest(true); +} + +void CameraTest1::onExit() +{ + Director::getInstance()->setProjection(Director::Projection::_2D); + TestCocosNodeDemo::onExit(); +} + +CameraTest1::CameraTest1() +{ + auto s = Director::getInstance()->getWinSize(); + + _sprite1 = MySprite::create(s_back3); + addChild( _sprite1 ); + _sprite1->setPosition( Point(1*s.width/4, s.height/2) ); + _sprite1->setScale(0.5); + + _sprite2 = Sprite::create(s_back3); + addChild( _sprite2 ); + _sprite2->setPosition( Point(3*s.width/4, s.height/2) ); + _sprite2->setScale(0.5); + + auto camera = OrbitCamera::create(10, 0, 1, 0, 360, 0, 0); + _sprite1->runAction( camera ); + _sprite2->runAction( camera->clone() ); +} + +std::string CameraTest1::title() const +{ + return "Camera Test 1"; +} + +std::string CameraTest1::subtitle() const +{ + return "Both images should rotate with a 3D effect"; +} +//------------------------------------------------------------------ +// +// CameraTest2 +// +//------------------------------------------------------------------ void CameraTest2::onEnter() { TestCocosNodeDemo::onEnter(); diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h index 50959ced5a..7a6a63d7c2 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h @@ -110,6 +110,16 @@ protected: NodeToWorld(); }; +class NodeToWorld3D : public TestCocosNodeDemo +{ +public: + CREATE_FUNC(NodeToWorld3D); + virtual std::string title() const override; + +protected: + NodeToWorld3D(); +}; + class CameraOrbitTest : public TestCocosNodeDemo { public: @@ -148,6 +158,22 @@ protected: CameraCenterTest(); }; +class CameraTest1 : public TestCocosNodeDemo +{ +public: + CREATE_FUNC(CameraTest1); + virtual std::string title() const override; + virtual std::string subtitle() const override; + virtual void onEnter() override; + virtual void onExit() override; + +protected: + CameraTest1(); + + Sprite *_sprite1; + Sprite *_sprite2; +}; + class CameraTest2 : public TestCocosNodeDemo { public: @@ -163,7 +189,6 @@ protected: Sprite *_sprite1; Sprite *_sprite2; - }; class ConvertToNode : public TestCocosNodeDemo From a1629a09e8bfce94399b36b9cfa2b61caf4d94f7 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Fri, 10 Jan 2014 10:03:47 +0800 Subject: [PATCH 035/193] fix layerColor bug for shader change --- cocos/2d/CCLayer.cpp | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index b8b69f0976..1bae6e040c 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -569,16 +569,11 @@ void LayerColor::draw() _customCommand.func = CC_CALLBACK_0(LayerColor::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); - kmMat4 p, mvp; - kmGLGetMatrix(KM_GL_PROJECTION, &p); - kmGLGetMatrix(KM_GL_MODELVIEW, &mvp); - kmMat4Multiply(&mvp, &p, &mvp); - for(int i = 0; i < 4; ++i) { kmVec3 pos; pos.x = _squareVertices[i].x; pos.y = _squareVertices[i].y; pos.z = _vertexZ; - kmVec3TransformCoord(&pos, &pos, &mvp); + kmVec3TransformCoord(&pos, &pos, &_modelViewTransform); _noMVPVertices[i] = Vertex3F(pos.x,pos.y,pos.z); } From 8b350cb20ab80c16ad8c86b2d4e8b06c6854a94a Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Fri, 10 Jan 2014 03:14:18 +0000 Subject: [PATCH 036/193] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index f7835c1364..f893f6202c 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit f7835c13644591879f5a995074ccc8faf70c355e +Subproject commit f893f6202c6f249f52660876278a1742ba12aefa From 16367b75944b729543241eed867e3b234c9802a4 Mon Sep 17 00:00:00 2001 From: WuHuan Date: Fri, 10 Jan 2014 14:20:00 +0800 Subject: [PATCH 037/193] solve conflicted with math.h isnan --- cocos/2d/CCActionCamera.cpp | 6 +++--- cocos/2d/platform/win32/CCStdC.h | 5 +++++ extensions/GUI/CCControlExtension/CCControlUtils.cpp | 2 +- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/cocos/2d/CCActionCamera.cpp b/cocos/2d/CCActionCamera.cpp index fc05435e3b..c044bdd21a 100644 --- a/cocos/2d/CCActionCamera.cpp +++ b/cocos/2d/CCActionCamera.cpp @@ -182,11 +182,11 @@ void OrbitCamera::startWithTarget(Node *target) float r, zenith, azimuth; this->sphericalRadius(&r, &zenith, &azimuth); - if( std::isnan(_radius) ) + if( isnan(_radius) ) _radius = r; - if( std::isnan(_angleZ) ) + if( isnan(_angleZ) ) _angleZ = (float)CC_RADIANS_TO_DEGREES(zenith); - if( std::isnan(_angleX) ) + if( isnan(_angleX) ) _angleX = (float)CC_RADIANS_TO_DEGREES(azimuth); _radZ = (float)CC_DEGREES_TO_RADIANS(_angleZ); diff --git a/cocos/2d/platform/win32/CCStdC.h b/cocos/2d/platform/win32/CCStdC.h index b477ec575f..19ea8fda7d 100644 --- a/cocos/2d/platform/win32/CCStdC.h +++ b/cocos/2d/platform/win32/CCStdC.h @@ -109,8 +109,13 @@ NS_CC_END #else +#undef _WINSOCKAPI_ #include +// Conflicted with math.h isnan +#include +using std::isnan; + inline int vsnprintf_s(char *buffer, size_t sizeOfBuffer, size_t count, const char *format, va_list argptr) { return vsnprintf(buffer, sizeOfBuffer, format, argptr); diff --git a/extensions/GUI/CCControlExtension/CCControlUtils.cpp b/extensions/GUI/CCControlExtension/CCControlUtils.cpp index 75d246796d..e660a29d8e 100644 --- a/extensions/GUI/CCControlExtension/CCControlUtils.cpp +++ b/extensions/GUI/CCControlExtension/CCControlUtils.cpp @@ -92,7 +92,7 @@ RGBA ControlUtils::RGBfromHSV(HSV value) if (value.s <= 0.0) // < is bogus, just shuts up warnings { - if (std::isnan(value.h)) // value.h == NAN + if (isnan(value.h)) // value.h == NAN { out.r = value.v; out.g = value.v; From 4d873edff1018178a1c5b24489581aa69aff2bf5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 10 Jan 2014 15:15:19 +0800 Subject: [PATCH 038/193] Update AUTHORS [ci skip] --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index f5895c2f29..ac01d86aa8 100644 --- a/AUTHORS +++ b/AUTHORS @@ -711,6 +711,9 @@ Developers: v1ctor ControlSlider supports to set selected thumb sprite. ControlButton supports to set scale ratio of touchdown state + + akof1314 + TestCpp works by using CMake and mingw on Windows. Retired Core Developers: WenSheng Yang From 245fa2efe066634f92f4fec665484c56fcfa6713 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 10 Jan 2014 15:19:32 +0800 Subject: [PATCH 039/193] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 420e678c08..a16751e56c 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -5,6 +5,7 @@ cocos2d-x-3.0final ?.? ? [FIX] ControlButton doesn't support to set scale ratio of touchdown state. [FIX] Websocket doesn't support send/receive data which larger than 4096 bytes. [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. + [FIX] TestCpp works by using CMake on Windows. cocos2d-x-3.0beta Jan.7 2014 [All] [NEW] New label: shadow, outline, glow support From b4a4b70e22ee76a7596839928c7f8d81364b2189 Mon Sep 17 00:00:00 2001 From: heliclei Date: Fri, 10 Jan 2014 17:45:28 +0800 Subject: [PATCH 040/193] rename ghprb.py to pull-request-builder.py --- tools/jenkins-scripts/{ghprb.py => pull-request-builder.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tools/jenkins-scripts/{ghprb.py => pull-request-builder.py} (100%) diff --git a/tools/jenkins-scripts/ghprb.py b/tools/jenkins-scripts/pull-request-builder.py similarity index 100% rename from tools/jenkins-scripts/ghprb.py rename to tools/jenkins-scripts/pull-request-builder.py From 2a6b9fe08e72b5805940098fb6f0a854920f962e Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 10 Jan 2014 17:11:14 -0800 Subject: [PATCH 041/193] Console is a property of Director. By doing this, the console lives as much as the Director. And the Console is not started until the method "listenOnPort" is called. --- cocos/2d/CCDirector.cpp | 53 ++----------------- cocos/2d/CCDirector.h | 25 +++++---- cocos/base/CCConsole.cpp | 18 +++---- cocos/base/CCConsole.h | 20 ++++--- .../Classes/ConsoleTest/ConsoleTest.cpp | 8 +-- 5 files changed, 39 insertions(+), 85 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 428772a367..a0c42973e2 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -61,6 +61,7 @@ THE SOFTWARE. #include "CCEventCustom.h" #include "CCFontFreeType.h" #include "CCRenderer.h" +#include "CCConsole.h" #include "renderer/CCFrustum.h" /** Position of the FPS @@ -116,9 +117,6 @@ bool Director::init(void) _scenesStack.reserve(15); - // projection delegate if "Custom" projection is used - _projectionDelegate = nullptr; - // FPS _accumDt = 0.0f; _frameRate = 0.0f; @@ -163,8 +161,8 @@ bool Director::init(void) //init TextureCache initTextureCache(); - // Renderer _renderer = new Renderer; + _console = new Console; // create autorelease pool PoolManager::sharedPoolManager()->push(); @@ -192,6 +190,7 @@ Director::~Director(void) delete _eventProjectionChanged; delete _renderer; + delete _console; // pop the autorelease pool PoolManager::sharedPoolManager()->pop(); @@ -483,9 +482,8 @@ void Director::setProjection(Projection projection) } case Projection::CUSTOM: - if (_projectionDelegate) - _projectionDelegate->updateProjection(); - + // Projection Delegate is no longer needed + // since the event "PROJECTION CHANGED" is emitted break; default: @@ -973,11 +971,6 @@ void Director::createStatsLabel() _FPSLabel->setPosition(CC_DIRECTOR_STATS_POSITION); } -float Director::getContentScaleFactor() const -{ - return _contentScaleFactor; -} - void Director::setContentScaleFactor(float scaleFactor) { if (scaleFactor != _contentScaleFactor) @@ -987,11 +980,6 @@ void Director::setContentScaleFactor(float scaleFactor) } } -Node* Director::getNotificationNode() -{ - return _notificationNode; -} - void Director::setNotificationNode(Node *node) { CC_SAFE_RELEASE(_notificationNode); @@ -999,16 +987,6 @@ void Director::setNotificationNode(Node *node) CC_SAFE_RETAIN(_notificationNode); } -DirectorDelegate* Director::getDelegate() const -{ - return _projectionDelegate; -} - -void Director::setDelegate(DirectorDelegate* delegate) -{ - _projectionDelegate = delegate; -} - void Director::setScheduler(Scheduler* scheduler) { if (_scheduler != scheduler) @@ -1019,11 +997,6 @@ void Director::setScheduler(Scheduler* scheduler) } } -Scheduler* Director::getScheduler() const -{ - return _scheduler; -} - void Director::setActionManager(ActionManager* actionManager) { if (_actionManager != actionManager) @@ -1034,16 +1007,6 @@ void Director::setActionManager(ActionManager* actionManager) } } -ActionManager* Director::getActionManager() const -{ - return _actionManager; -} - -EventDispatcher* Director::getEventDispatcher() const -{ - return _eventDispatcher; -} - void Director::setEventDispatcher(EventDispatcher* dispatcher) { if (_eventDispatcher != dispatcher) @@ -1054,12 +1017,6 @@ void Director::setEventDispatcher(EventDispatcher* dispatcher) } } -Renderer* Director::getRenderer() const -{ - return _renderer; -} - - /*************************************************** * implementation of DisplayLinkDirector **************************************************/ diff --git a/cocos/2d/CCDirector.h b/cocos/2d/CCDirector.h index 10f46bb539..17616ec408 100644 --- a/cocos/2d/CCDirector.h +++ b/cocos/2d/CCDirector.h @@ -60,6 +60,7 @@ class EventListenerCustom; class TextureCache; class Frustum; class Renderer; +class Console; /** @brief Class that creates and handles the main Window and manages how @@ -186,7 +187,7 @@ public: Useful to hook a notification object, like Notifications (http://github.com/manucorporat/CCNotifications) @since v0.99.5 */ - Node* getNotificationNode(); + Node* getNotificationNode() const { return _notificationNode; } void setNotificationNode(Node *node); /** Director delegate. It shall implement the DirectorDelegate protocol @@ -340,7 +341,7 @@ public: @since v0.99.4 */ void setContentScaleFactor(float scaleFactor); - float getContentScaleFactor() const; + float getContentScaleFactor() const { return _contentScaleFactor; } /** Get the Culling Frustum @@ -351,7 +352,7 @@ public: /** Gets the Scheduler associated with this director @since v2.0 */ - Scheduler* getScheduler() const; + Scheduler* getScheduler() const { return _scheduler; } /** Sets the Scheduler associated with this director @since v2.0 @@ -361,7 +362,7 @@ public: /** Gets the ActionManager associated with this director @since v2.0 */ - ActionManager* getActionManager() const; + ActionManager* getActionManager() const { return _actionManager; } /** Sets the ActionManager associated with this director @since v2.0 @@ -371,7 +372,7 @@ public: /** Gets the EventDispatcher associated with this director @since v3.0 */ - EventDispatcher* getEventDispatcher() const; + EventDispatcher* getEventDispatcher() const { return _eventDispatcher; } /** Sets the EventDispatcher associated with this director @since v3.0 @@ -381,7 +382,12 @@ public: /** Returns the Renderer @since v3.0 */ - Renderer* getRenderer() const; + Renderer* getRenderer() const { return _renderer; } + + /** Returns the Console + @since v3.0 + */ + Console* getConsole() const { return _console; } /* Gets delta time since last tick to main loop */ float getDeltaTime() const; @@ -492,10 +498,11 @@ protected: /* This object will be visited after the scene. Useful to hook a notification node */ Node *_notificationNode; - /* Projection protocol delegate */ - DirectorDelegate *_projectionDelegate; - + /* Renderer for the Director */ Renderer *_renderer; + + /* Console for the director */ + Console *_console; // EGLViewProtocol will recreate stats labels to fit visible rect friend class EGLViewProtocol; diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 6eb9256a67..de7af36737 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -112,14 +112,6 @@ static const char* inet_ntop(int af, const void* src, char* dst, int cnt) // Console code // -Console* Console::create() -{ - auto ret = new Console; - - ret->autorelease(); - return ret; -} - Console::Console() : _listenfd(-1) , _running(false) @@ -152,7 +144,7 @@ Console::Console() Console::~Console() { - cancel(); + stop(); } bool Console::listenOnTCP(int port) @@ -226,14 +218,18 @@ bool Console::listenOnTCP(int port) bool Console::listenOnFileDescriptor(int fd) { - CCASSERT(!_running, "already running"); + if(_running) { + cocos2d::log("Console already started. 'stop' it before calling 'listen' again"); + return false; + } + _listenfd = fd; _thread = std::thread( std::bind( &Console::loop, this) ); return true; } -void Console::cancel() +void Console::stop() { if( _running ) { _endThread = true; diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index 1334ec9506..7385d184ee 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -55,17 +55,19 @@ NS_CC_BEGIN scheduler->performFunctionInCocosThread( ... ); ``` */ -class CC_DLL Console : public Object +class CC_DLL Console { public: - struct Command { const char *name; std::function callback; }; - /** creates a new instnace of the Console */ - static Console* create(); + /** Constructor */ + Console(); + + /** Destructor */ + virtual ~Console(); /** starts listening to specifed TCP port */ bool listenOnTCP(int port); @@ -73,18 +75,14 @@ public: /** starts listening to specifed file descriptor */ bool listenOnFileDescriptor(int fd); - /** cancels the Console. Cancel will be called at destruction time as well */ - void cancel(); + /** stops the Console. 'stop' will be called at destruction time as well */ + void stop(); /** sets user tokens */ void setUserCommands( Command* commands, int numberOfCommands); protected: - Console(); - virtual ~Console(); - void loop(); - ssize_t readline(int fd); bool parseCommand(int fd); void sendPrompt(int fd); @@ -108,7 +106,7 @@ protected: char _buffer[512]; - struct Command _commands[15]; + struct Command _commands[64]; int _maxCommands; struct Command *_userCommands; int _maxUserCommands; diff --git a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp index d5827c25cb..c4269ea2e9 100644 --- a/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ConsoleTest/ConsoleTest.cpp @@ -133,13 +133,11 @@ void ConsoleTestScene::runThisTest() ConsoleTCP::ConsoleTCP() { - _console = Console::create(); - _console->retain(); + _console = Director::getInstance()->getConsole(); } ConsoleTCP::~ConsoleTCP() { - _console->release(); } void ConsoleTCP::onEnter() @@ -167,8 +165,7 @@ std::string ConsoleTCP::subtitle() const ConsoleCustomCommand::ConsoleCustomCommand() { - _console = Console::create(); - _console->retain(); + _console = Director::getInstance()->getConsole(); static struct Console::Command commands[] = { {"hello", [](int fd, const char* command) { @@ -183,7 +180,6 @@ ConsoleCustomCommand::ConsoleCustomCommand() ConsoleCustomCommand::~ConsoleCustomCommand() { - _console->release(); } void ConsoleCustomCommand::onEnter() From 2316e4d55f3de50cc713ce132dc63c6f4858c02c Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 10 Jan 2014 17:58:54 -0800 Subject: [PATCH 042/193] Debug messages are forward to the console --- cocos/2d/platform/mac/CCCommon.mm | 6 +- cocos/base/CCConsole.cpp | 116 +++++++++++++++++++----------- cocos/base/CCConsole.h | 11 +++ 3 files changed, 90 insertions(+), 43 deletions(-) diff --git a/cocos/2d/platform/mac/CCCommon.mm b/cocos/2d/platform/mac/CCCommon.mm index 3e6cb32295..a9ff158eaf 100644 --- a/cocos/2d/platform/mac/CCCommon.mm +++ b/cocos/2d/platform/mac/CCCommon.mm @@ -29,6 +29,8 @@ THE SOFTWARE. #include #include #import "EAGLView.h" +#include "CCConsole.h" +#include "CCDirector.h" NS_CC_BEGIN @@ -57,9 +59,11 @@ void log(const char * format, ...) va_start(ap, format); vsnprintf(buf, kMaxLogLen, format, ap); va_end(ap); + strcat(buf, "\n"); printf("%s", buf); - printf("\n"); fflush(stdout); + + Director::getInstance()->getConsole()->log(buf); } diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index de7af36737..e065b8b94b 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -116,27 +116,35 @@ Console::Console() : _listenfd(-1) , _running(false) , _endThread(false) -, _maxCommands(5) , _userCommands(nullptr) , _maxUserCommands(0) +, _sendDebugStrings(false) { // VS2012 doesn't support initializer list, so we create a new array and assign its elements to '_command'. Command commands[] = { - { "fps on", [](int fd, const char* command) { - Director *dir = Director::getInstance(); - Scheduler *sched = dir->getScheduler(); - sched->performFunctionInCocosThread( std::bind(&Director::setDisplayStats, dir, true)); - } }, - { "fps off", [](int fd, const char* command) { - Director *dir = Director::getInstance(); - Scheduler *sched = dir->getScheduler(); - sched->performFunctionInCocosThread( std::bind(&Director::setDisplayStats, dir, false)); - } }, - { "scene graph", std::bind(&Console::commandSceneGraph, this, std::placeholders::_1, std::placeholders::_2) }, - { "exit", std::bind(&Console::commandExit, this, std::placeholders::_1, std::placeholders::_2) }, - { "help", std::bind(&Console::commandHelp, this, std::placeholders::_1, std::placeholders::_2) } }; + { "debug msg on", [&](int fd, const char* command) { + _sendDebugStrings = true; + } }, + { "debug msg off", [&](int fd, const char* command) { + _sendDebugStrings = false; + } }, + { "exit", std::bind(&Console::commandExit, this, std::placeholders::_1, std::placeholders::_2) }, + { "fps on", [](int fd, const char* command) { + Director *dir = Director::getInstance(); + Scheduler *sched = dir->getScheduler(); + sched->performFunctionInCocosThread( std::bind(&Director::setDisplayStats, dir, true)); + } }, + { "fps off", [](int fd, const char* command) { + Director *dir = Director::getInstance(); + Scheduler *sched = dir->getScheduler(); + sched->performFunctionInCocosThread( std::bind(&Director::setDisplayStats, dir, false)); + } }, + { "help", std::bind(&Console::commandHelp, this, std::placeholders::_1, std::placeholders::_2) }, + { "scene graph", std::bind(&Console::commandSceneGraph, this, std::placeholders::_1, std::placeholders::_2) }, + }; - for (size_t i = 0; i < sizeof(commands)/sizeof(commands[0]) && i < sizeof(_commands)/sizeof(_commands[0]); ++i) + _maxCommands = sizeof(commands)/sizeof(commands[0]); + for (size_t i = 0; i < _maxCommands; ++i) { _commands[i] = commands[i]; } @@ -198,14 +206,14 @@ bool Console::listenOnTCP(int port) char buf[INET_ADDRSTRLEN] = ""; struct sockaddr_in *sin = (struct sockaddr_in*) res->ai_addr; if( inet_ntop(res->ai_family, &sin->sin_addr, buf, sizeof(buf)) != NULL ) - log("Console: listening on %s : %d", buf, ntohs(sin->sin_port)); + cocos2d::log("Console: listening on %s : %d", buf, ntohs(sin->sin_port)); else perror("inet_ntop"); } else if (res->ai_family == AF_INET6) { char buf[INET6_ADDRSTRLEN] = ""; struct sockaddr_in6 *sin = (struct sockaddr_in6*) res->ai_addr; if( inet_ntop(res->ai_family, &sin->sin6_addr, buf, sizeof(buf)) != NULL ) - log("Console: listening on %s : %d", buf, ntohs(sin->sin6_port)); + cocos2d::log("Console: listening on %s : %d", buf, ntohs(sin->sin6_port)); else perror("inet_ntop"); } @@ -372,6 +380,15 @@ void Console::addClient() } } +void Console::log(const char* buf) +{ + if( _sendDebugStrings ) { + _DebugStringsMutex.lock(); + _DebugStrings.push_back(buf); + _DebugStringsMutex.unlock(); + } +} + // // Main Loop // @@ -398,40 +415,55 @@ void Console::loop() timeout_copy = timeout; int nready = select(_maxfd+1, ©_set, NULL, NULL, &timeout_copy); - if( nready == -1 ) { - /* error ?*/ + if( nready == -1 ) + { + /* error */ if(errno != EINTR) log("Abnormal error in select()\n"); continue; - - } else if( nready == 0 ) { - /* timeout ? */ - continue; } - - // new client - if(FD_ISSET(_listenfd, ©_set)) { - addClient(); - if(--nready <= 0) - continue; + else if( nready == 0 ) + { + /* timeout. do somethig ? */ } - - // data from client - std::vector to_remove; - for(const auto &fd: _fds) { - if(FD_ISSET(fd,©_set)) { - if( ! parseCommand(fd) ) { - to_remove.push_back(fd); - } + else + { + /* new client */ + if(FD_ISSET(_listenfd, ©_set)) { + addClient(); if(--nready <= 0) - break; + continue; + } + + /* data from client */ + std::vector to_remove; + for(const auto &fd: _fds) { + if(FD_ISSET(fd,©_set)) { + if( ! parseCommand(fd) ) { + to_remove.push_back(fd); + } + if(--nready <= 0) + break; + } + } + + /* remove closed conections */ + for(int fd: to_remove) { + FD_CLR(fd, &_read_set); + _fds.erase(std::remove(_fds.begin(), _fds.end(), fd), _fds.end()); } } - // remove closed conections - for(int fd: to_remove) { - FD_CLR(fd, &_read_set); - _fds.erase(std::remove(_fds.begin(), _fds.end(), fd), _fds.end()); + /* Any message for the remote console ? send it! */ + if( !_DebugStrings.empty() ) { + _DebugStringsMutex.lock(); + for(const auto &str : _DebugStrings) { + for(const auto &fd : _fds) { + write(fd, str.c_str(), str.length()); + } + } + _DebugStrings.clear(); + _DebugStringsMutex.unlock(); } } diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index 7385d184ee..158ebde7c8 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -39,6 +39,8 @@ typedef int ssize_t; #include #include #include +#include +#include #include "ccMacros.h" #include "CCObject.h" @@ -81,6 +83,9 @@ public: /** sets user tokens */ void setUserCommands( Command* commands, int numberOfCommands); + /** log something in the console */ + void log(const char *buf); + protected: void loop(); ssize_t readline(int fd); @@ -111,6 +116,12 @@ protected: struct Command *_userCommands; int _maxUserCommands; + + // strings generated by cocos2d sent to the remote console + bool _sendDebugStrings; + std::mutex _DebugStringsMutex; + std::vector _DebugStrings; + private: CC_DISALLOW_COPY_AND_ASSIGN(Console); }; From c68ad76bfe6102ecdfe29cfd39aa7587dac4b4fd Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 10 Jan 2014 18:11:35 -0800 Subject: [PATCH 043/193] don't send "unknown command". ... if the command is an empty command --- cocos/2d/platform/ios/CCCommon.mm | 6 +++++- cocos/base/CCConsole.cpp | 2 +- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/cocos/2d/platform/ios/CCCommon.mm b/cocos/2d/platform/ios/CCCommon.mm index 0afbb57e73..0293d79092 100644 --- a/cocos/2d/platform/ios/CCCommon.mm +++ b/cocos/2d/platform/ios/CCCommon.mm @@ -29,6 +29,8 @@ #include #import +#include "CCDirector.h" +#include "CCConsole.h" NS_CC_BEGIN @@ -53,8 +55,10 @@ void log(const char * format, ...) va_start(ap, format); vsnprintf(buf, kMaxLogLen, format, ap); va_end(ap); + strcat(buf, "\n"); printf("%s", buf); - printf("\n"); + + Director::getInstance()->getConsole()->log(buf); } // ios no MessageBox, use log instead diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index e065b8b94b..919d87f678 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -316,7 +316,7 @@ bool Console::parseCommand(int fd) } } - if(!found) { + if(!found && strcmp(_buffer, "\r\n")!=0) { const char err[] = "Unknown command. Type 'help' for options\n"; write(fd, err, sizeof(err)); } From 9386866d5608d4054ff7b04ef4a6e7d2f1b1034a Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 10 Jan 2014 19:04:07 -0800 Subject: [PATCH 044/193] cocos2d::log() moved to CCConsole Unified console code since it is 90% similar to all platforms --- cocos/2d/ccMacros.h | 2 +- cocos/2d/ccUTF8.cpp | 1 + cocos/2d/platform/CCCommon.h | 8 ---- cocos/2d/platform/android/CCCommon.cpp | 22 ----------- cocos/2d/platform/ios/CCCommon.mm | 27 ------------- cocos/2d/platform/linux/CCCommon.cpp | 52 +++----------------------- cocos/2d/platform/mac/CCCommon.mm | 34 ----------------- cocos/2d/platform/win32/CCCommon.cpp | 37 ------------------ cocos/2d/renderer/CCFrustum.cpp | 2 +- cocos/base/CCConsole.cpp | 52 ++++++++++++++++++++++++++ cocos/base/CCConsole.h | 13 ++++++- cocos/base/CCObject.h | 2 + 12 files changed, 74 insertions(+), 178 deletions(-) diff --git a/cocos/2d/ccMacros.h b/cocos/2d/ccMacros.h index 8196fbac0c..e15f4907a3 100644 --- a/cocos/2d/ccMacros.h +++ b/cocos/2d/ccMacros.h @@ -32,7 +32,7 @@ THE SOFTWARE. #define _USE_MATH_DEFINES #endif -#include "platform/CCCommon.h" +#include "CCConsole.h" #include "CCStdC.h" #ifndef CCASSERT diff --git a/cocos/2d/ccUTF8.cpp b/cocos/2d/ccUTF8.cpp index ceb240d2e6..6e70a313d5 100644 --- a/cocos/2d/ccUTF8.cpp +++ b/cocos/2d/ccUTF8.cpp @@ -25,6 +25,7 @@ #include "ccUTF8.h" #include "platform/CCCommon.h" +#include "CCConsole.h" NS_CC_BEGIN diff --git a/cocos/2d/platform/CCCommon.h b/cocos/2d/platform/CCCommon.h index eb4f6fa9cb..fa300cd4fe 100644 --- a/cocos/2d/platform/CCCommon.h +++ b/cocos/2d/platform/CCCommon.h @@ -35,14 +35,6 @@ NS_CC_BEGIN * @{ */ -/// The max length of CCLog message. -static const int kMaxLogLen = 16*1024; - -/** -@brief Output Debug message. -*/ -void CC_DLL log(const char * format, ...) CC_FORMAT_PRINTF(1, 2); - /** * lua can not deal with ... */ diff --git a/cocos/2d/platform/android/CCCommon.cpp b/cocos/2d/platform/android/CCCommon.cpp index a24c002463..b48aff2e5c 100644 --- a/cocos/2d/platform/android/CCCommon.cpp +++ b/cocos/2d/platform/android/CCCommon.cpp @@ -33,28 +33,6 @@ NS_CC_BEGIN #define MAX_LEN (cocos2d::kMaxLogLen + 1) -// XXX deprecated -void CCLog(const char * pszFormat, ...) -{ - va_list args; - va_start(args, pszFormat); - __android_log_vprint(ANDROID_LOG_DEBUG, "cocos2d-x debug info", pszFormat, args); - va_end(args); - -} - -void log(const char * pszFormat, ...) -{ - char buf[MAX_LEN]; - - va_list args; - va_start(args, pszFormat); - vsnprintf(buf, MAX_LEN, pszFormat, args); - va_end(args); - - __android_log_print(ANDROID_LOG_DEBUG, "cocos2d-x debug info", "%s", buf); -} - void MessageBox(const char * pszMsg, const char * pszTitle) { showDialogJNI(pszMsg, pszTitle); diff --git a/cocos/2d/platform/ios/CCCommon.mm b/cocos/2d/platform/ios/CCCommon.mm index 0293d79092..28d0dd0e22 100644 --- a/cocos/2d/platform/ios/CCCommon.mm +++ b/cocos/2d/platform/ios/CCCommon.mm @@ -34,33 +34,6 @@ NS_CC_BEGIN -// XXX deprecated -void CCLog(const char * format, ...) -{ - printf("cocos2d: "); - char buf[kMaxLogLen+1] = {0}; - va_list ap; - va_start(ap, format); - vsnprintf(buf, kMaxLogLen, format, ap); - va_end(ap); - printf("%s", buf); - printf("\n"); -} - -void log(const char * format, ...) -{ - printf("cocos2d: "); - char buf[kMaxLogLen+1] = {0}; - va_list ap; - va_start(ap, format); - vsnprintf(buf, kMaxLogLen, format, ap); - va_end(ap); - strcat(buf, "\n"); - printf("%s", buf); - - Director::getInstance()->getConsole()->log(buf); -} - // ios no MessageBox, use log instead void MessageBox(const char * msg, const char * title) { diff --git a/cocos/2d/platform/linux/CCCommon.cpp b/cocos/2d/platform/linux/CCCommon.cpp index 4b94bcd8e0..c48307192b 100644 --- a/cocos/2d/platform/linux/CCCommon.cpp +++ b/cocos/2d/platform/linux/CCCommon.cpp @@ -24,60 +24,18 @@ THE SOFTWARE. ****************************************************************************/ #include "platform/CCCommon.h" #include "CCStdC.h" +#include "CCConsole.h" NS_CC_BEGIN -#define MAX_LEN (cocos2d::kMaxLogLen + 1) - -// XXX deprecated -void CCLog(const char * pszFormat, ...) +void MessageBox(const char * msg, const char * title) { - char szBuf[MAX_LEN]; - - va_list ap; - va_start(ap, pszFormat); - vsnprintf(szBuf, MAX_LEN, pszFormat, ap); - va_end(ap); - - // Strip any trailing newlines from log message. - size_t len = strlen(szBuf); - while (len && szBuf[len-1] == '\n') - { - szBuf[len-1] = '\0'; - len--; - } - - fprintf(stderr, "cocos2d-x debug info [%s]\n", szBuf); + log("%s: %s", title, msg); } -void log(const char * pszFormat, ...) +void LuaLog(const char * format) { - char szBuf[MAX_LEN]; - - va_list ap; - va_start(ap, pszFormat); - vsnprintf(szBuf, MAX_LEN, pszFormat, ap); - va_end(ap); - - // Strip any trailing newlines from log message. - size_t len = strlen(szBuf); - while (len && szBuf[len-1] == '\n') - { - szBuf[len-1] = '\0'; - len--; - } - - fprintf(stderr, "cocos2d-x debug info [%s]\n", szBuf); -} - -void MessageBox(const char * pszMsg, const char * pszTitle) -{ - log("%s: %s", pszTitle, pszMsg); -} - -void LuaLog(const char * pszFormat) -{ - puts(pszFormat); + puts(format); } NS_CC_END diff --git a/cocos/2d/platform/mac/CCCommon.mm b/cocos/2d/platform/mac/CCCommon.mm index a9ff158eaf..52e4fb7beb 100644 --- a/cocos/2d/platform/mac/CCCommon.mm +++ b/cocos/2d/platform/mac/CCCommon.mm @@ -29,44 +29,10 @@ THE SOFTWARE. #include #include #import "EAGLView.h" -#include "CCConsole.h" -#include "CCDirector.h" NS_CC_BEGIN -// XXX deprecated -void CCLog(const char * format, ...) -{ - printf("Cocos2d: "); - char buf[kMaxLogLen]; - - va_list ap; - va_start(ap, format); - vsnprintf(buf, kMaxLogLen, format, ap); - va_end(ap); - printf("%s", buf); - printf("\n"); - fflush(stdout); -} - -void log(const char * format, ...) -{ - printf("Cocos2d: "); - char buf[kMaxLogLen]; - - va_list ap; - va_start(ap, format); - vsnprintf(buf, kMaxLogLen, format, ap); - va_end(ap); - strcat(buf, "\n"); - printf("%s", buf); - fflush(stdout); - - Director::getInstance()->getConsole()->log(buf); -} - - void LuaLog(const char * format) { puts(format); diff --git a/cocos/2d/platform/win32/CCCommon.cpp b/cocos/2d/platform/win32/CCCommon.cpp index 58651989de..3aa3d6458f 100644 --- a/cocos/2d/platform/win32/CCCommon.cpp +++ b/cocos/2d/platform/win32/CCCommon.cpp @@ -29,43 +29,6 @@ NS_CC_BEGIN #define MAX_LEN (cocos2d::kMaxLogLen + 1) -// XXX deprecated -void CCLog(const char * pszFormat, ...) -{ - char szBuf[MAX_LEN]; - - va_list ap; - va_start(ap, pszFormat); - vsnprintf_s(szBuf, MAX_LEN, MAX_LEN, pszFormat, ap); - va_end(ap); - - WCHAR wszBuf[MAX_LEN] = {0}; - MultiByteToWideChar(CP_UTF8, 0, szBuf, -1, wszBuf, sizeof(wszBuf)); - OutputDebugStringW(wszBuf); - OutputDebugStringA("\n"); - - WideCharToMultiByte(CP_ACP, 0, wszBuf, sizeof(wszBuf), szBuf, sizeof(szBuf), NULL, FALSE); - printf("%s\n", szBuf); -} - -void log(const char * pszFormat, ...) -{ - char szBuf[MAX_LEN]; - - va_list ap; - va_start(ap, pszFormat); - vsnprintf_s(szBuf, MAX_LEN, MAX_LEN, pszFormat, ap); - va_end(ap); - - WCHAR wszBuf[MAX_LEN] = {0}; - MultiByteToWideChar(CP_UTF8, 0, szBuf, -1, wszBuf, sizeof(wszBuf)); - OutputDebugStringW(wszBuf); - OutputDebugStringA("\n"); - - WideCharToMultiByte(CP_ACP, 0, wszBuf, sizeof(wszBuf), szBuf, sizeof(szBuf), NULL, FALSE); - printf("%s\n", szBuf); -} - void MessageBox(const char * pszMsg, const char * pszTitle) { MessageBoxA(NULL, pszMsg, pszTitle, MB_OK); diff --git a/cocos/2d/renderer/CCFrustum.cpp b/cocos/2d/renderer/CCFrustum.cpp index b03c9771ee..cc26b67cab 100644 --- a/cocos/2d/renderer/CCFrustum.cpp +++ b/cocos/2d/renderer/CCFrustum.cpp @@ -23,7 +23,7 @@ ****************************************************************************/ #include "CCFrustum.h" -#include "platform/CCCommon.h" +#include "CCConsole.h" #include diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 919d87f678..682855e05d 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -49,6 +49,7 @@ #include "CCDirector.h" #include "CCScheduler.h" #include "CCScene.h" +#include "CCPlatformConfig.h" NS_CC_BEGIN @@ -108,6 +109,57 @@ static const char* inet_ntop(int af, const void* src, char* dst, int cnt) } #endif + +// +// Free functions to log +// + +// XXX: Deprecated +void CCLog(const char * format, ...) +{ + va_list args; + va_start(args, format); + log(format, args); + va_end(args); +} + +void log(const char * format, ...) +{ + va_list args; + va_start(args, format); + log(format, args); + va_end(args); +} + +void log(const char *format, va_list args) +{ + char buf[MAX_LOG_LENGTH]; + + vsnprintf(buf, MAX_LOG_LENGTH-3, format, args); + strcat(buf, "\n"); + +#if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID + __android_log_print(ANDROID_LOG_DEBUG, "cocos2d-x debug info", "%s", buf); + +#elif CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + WCHAR wszBuf[MAX_LOG_LENGTH] = {0}; + MultiByteToWideChar(CP_UTF8, 0, szBuf, -1, wszBuf, sizeof(wszBuf)); + OutputDebugStringW(wszBuf); + OutputDebugStringA("\n"); + + WideCharToMultiByte(CP_ACP, 0, wszBuf, sizeof(wszBuf), szBuf, sizeof(szBuf), NULL, FALSE); + printf("%s\n", szBuf); + +#else + // Linux, Mac, iOS, etc + fprintf(stdout, "cocos2d: %s", buf); + fflush(stdout); +#endif + + Director::getInstance()->getConsole()->log(buf); +} + + // // Console code // diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index 158ebde7c8..e90dec3c5c 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -42,12 +42,23 @@ typedef int ssize_t; #include #include +#include + #include "ccMacros.h" -#include "CCObject.h" +#include "ccPlatformMacros.h" NS_CC_BEGIN +/// The max length of CCLog message. +static const int MAX_LOG_LENGTH = 16*1024; + +/** + @brief Output Debug message. + */ +void CC_DLL log(const char * format, ...) CC_FORMAT_PRINTF(1, 2); +void CC_DLL log(const char * format, va_list args); + /** Console is helper class that lets the developer control the game from TCP connection. Console will spawn a new thread that will listen to a specified TCP port. Console has a basic token parser. Each token is associated with an std::function. diff --git a/cocos/base/CCObject.h b/cocos/base/CCObject.h index 28bb7da247..e438ac464f 100644 --- a/cocos/base/CCObject.h +++ b/cocos/base/CCObject.h @@ -28,6 +28,7 @@ THE SOFTWARE. #include "CCDataVisitor.h" #include "ccMacros.h" +#include "CCConsole.h" #ifdef EMSCRIPTEN #include @@ -106,6 +107,7 @@ public: */ inline void release() { + cocos2d::log("carlos"); CCASSERT(_reference > 0, "reference count should greater than 0"); --_reference; From dbcf5021a65e4a5f212f1c2f2c614e4a955bb563 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 10 Jan 2014 19:10:35 -0800 Subject: [PATCH 045/193] Compiles on Linux --- cocos/base/CCConsole.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index e90dec3c5c..4175395244 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -45,7 +45,7 @@ typedef int ssize_t; #include #include "ccMacros.h" -#include "ccPlatformMacros.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN From c88f81481bb71e54c730529ae7c351e2500f35d8 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 10 Jan 2014 19:22:04 -0800 Subject: [PATCH 046/193] JSB compiles OK --- cocos/scripting/javascript/bindings/ScriptingCore.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/scripting/javascript/bindings/ScriptingCore.cpp b/cocos/scripting/javascript/bindings/ScriptingCore.cpp index 68ad517f8e..6510b90167 100644 --- a/cocos/scripting/javascript/bindings/ScriptingCore.cpp +++ b/cocos/scripting/javascript/bindings/ScriptingCore.cpp @@ -200,12 +200,12 @@ void js_log(const char *format, ...) { if (_js_log_buf == NULL) { - _js_log_buf = (char *)calloc(sizeof(char), kMaxLogLen+1); - _js_log_buf[kMaxLogLen] = '\0'; + _js_log_buf = (char *)calloc(sizeof(char), MAX_LOG_LENGTH+1); + _js_log_buf[MAX_LOG_LENGTH] = '\0'; } va_list vl; va_start(vl, format); - int len = vsnprintf(_js_log_buf, kMaxLogLen, format, vl); + int len = vsnprintf(_js_log_buf, MAX_LOG_LENGTH, format, vl); va_end(vl); if (len > 0) { From b870180af639be284b84362104ab6e248a29b6d4 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 10 Jan 2014 19:26:03 -0800 Subject: [PATCH 047/193] Mmmm... what? removing useless debug message --- cocos/base/CCObject.h | 1 - 1 file changed, 1 deletion(-) diff --git a/cocos/base/CCObject.h b/cocos/base/CCObject.h index e438ac464f..2280508856 100644 --- a/cocos/base/CCObject.h +++ b/cocos/base/CCObject.h @@ -107,7 +107,6 @@ public: */ inline void release() { - cocos2d::log("carlos"); CCASSERT(_reference > 0, "reference count should greater than 0"); --_reference; From f76fcf7f2aaf7a73cd57ddd073ee5bfb07388032 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Sat, 11 Jan 2014 04:06:53 +0000 Subject: [PATCH 048/193] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index f893f6202c..f4f99502dc 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit f893f6202c6f249f52660876278a1742ba12aefa +Subproject commit f4f99502dc30984897d589d6eeecb63bd9ef563b From f4a99d06271d1e6166c8a29e6943e9fbf17cc6ac Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 10 Jan 2014 20:26:15 -0800 Subject: [PATCH 049/193] Removes DirectorDelegate --- cocos/2d/CCDirector.h | 12 ------------ cocos/base/CCConsole.cpp | 2 +- 2 files changed, 1 insertion(+), 13 deletions(-) diff --git a/cocos/2d/CCDirector.h b/cocos/2d/CCDirector.h index 17616ec408..23bc8cda42 100644 --- a/cocos/2d/CCDirector.h +++ b/cocos/2d/CCDirector.h @@ -190,18 +190,6 @@ public: Node* getNotificationNode() const { return _notificationNode; } void setNotificationNode(Node *node); - /** Director delegate. It shall implement the DirectorDelegate protocol - @since v0.99.5 - * @js NA - * @lua NA - */ - DirectorDelegate* getDelegate() const; - /** - * @js NA - * @lua NA - */ - void setDelegate(DirectorDelegate* delegate); - // window size /** returns the size of the OpenGL view in points. diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 682855e05d..58636d15cf 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -196,7 +196,7 @@ Console::Console() }; _maxCommands = sizeof(commands)/sizeof(commands[0]); - for (size_t i = 0; i < _maxCommands; ++i) + for (int i = 0; i < _maxCommands; ++i) { _commands[i] = commands[i]; } From 95568648c96fa57b4741f92c302ce0bc9495a0ef Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 10 Jan 2014 20:32:39 -0800 Subject: [PATCH 050/193] Console Enabled by default on TestCpp --- samples/Cpp/TestCpp/Classes/AppDelegate.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/samples/Cpp/TestCpp/Classes/AppDelegate.cpp b/samples/Cpp/TestCpp/Classes/AppDelegate.cpp index 3243c8f05c..285d9b17ae 100644 --- a/samples/Cpp/TestCpp/Classes/AppDelegate.cpp +++ b/samples/Cpp/TestCpp/Classes/AppDelegate.cpp @@ -82,6 +82,10 @@ bool AppDelegate::applicationDidFinishLaunching() scene->addChild(layer); director->runWithScene(scene); + // Enable Remote Console + auto console = director->getConsole(); + console->listenOnTCP(5678); + return true; } From b10783972f460bad50040c37c0b589ffd9c6ce67 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Sat, 11 Jan 2014 04:39:03 +0000 Subject: [PATCH 051/193] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index f4f99502dc..74e535d0bd 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit f4f99502dc30984897d589d6eeecb63bd9ef563b +Subproject commit 74e535d0bd9cb4fd53244c46e2011e56367624a4 From 23cf74853467a31c76dfe98bf4d6087cef7f4904 Mon Sep 17 00:00:00 2001 From: martell Date: Sat, 11 Jan 2014 12:31:04 +0000 Subject: [PATCH 052/193] Added x64 support for Windows - CCExtensions --- extensions/proj.win32/Win32InputBox.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/proj.win32/Win32InputBox.cpp b/extensions/proj.win32/Win32InputBox.cpp index 220a932072..1412e1a198 100644 --- a/extensions/proj.win32/Win32InputBox.cpp +++ b/extensions/proj.win32/Win32InputBox.cpp @@ -280,14 +280,14 @@ void CWin32InputBox::InitDialog() // Message handler for about box. LRESULT CALLBACK CWin32InputBox::DlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { - CWin32InputBox *_this = (CWin32InputBox *) ::GetWindowLong(hDlg, GWL_USERDATA); + CWin32InputBox *_this = (CWin32InputBox *) ::GetWindowLongPtr(hDlg, GWLP_USERDATA); WIN32INPUTBOX_PARAM *param = _this ? _this->GetParam() : 0; switch (message) { case WM_INITDIALOG: { - ::SetWindowLong(hDlg, GWL_USERDATA, (LONG) lParam); + SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR) lParam); _this = (CWin32InputBox *) lParam; _this->_param->hDlg = hDlg; From 69c004108b1305a63cf821a0446a3072dabacdd6 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Sat, 11 Jan 2014 22:33:07 +0800 Subject: [PATCH 053/193] issue#3630:Adjust some method for more easily create and change type. --- cocos/2d/CCLabel.cpp | 230 ++++++++++++------ cocos/2d/CCLabel.h | 44 +++- .../cocos2d_specifics.cpp.REMOVED.git-id | 2 +- .../Classes/LabelTest/LabelTestNew.cpp | 121 ++++----- .../NewEventDispatcherTest.cpp | 10 +- .../PerformanceTest/PerformanceLabelTest.cpp | 35 +-- tools/tojs/cocos2dx.ini | 2 +- 7 files changed, 276 insertions(+), 168 deletions(-) diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index d7125bcd30..4775fd2ae8 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -32,73 +32,58 @@ NS_CC_BEGIN -Label* Label::createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize, TextHAlignment alignment, GlyphCollection glyphs, const char *customGlyphs, bool useDistanceField) +Label* Label::create() { - FontAtlas *tmpAtlas = nullptr; - if(useDistanceField) - tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), DISTANCEFIELD_ATLAS_FONTSIZE, glyphs, customGlyphs,true); - else - tmpAtlas = FontAtlasCache::getFontAtlasTTF(fontFilePath.c_str(), fontSize, glyphs, customGlyphs,false); + Label *ret = new Label(); - if (!tmpAtlas) - return nullptr; - - // create the actual label - Label* templabel = Label::createWithAtlas(tmpAtlas, alignment, lineSize, useDistanceField,true); - - if (templabel) - { - if(useDistanceField) - templabel->setFontSize(fontSize); - templabel->setText(label, lineSize, alignment, false); - return templabel; - } - - return nullptr; -} - -Label* Label::createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment, int lineSize) -{ - - FontAtlas *tmpAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath.c_str()); - - if (!tmpAtlas) - return 0; - - Label* templabel = Label::createWithAtlas(tmpAtlas, alignment, lineSize); - - if (templabel) - { - templabel->setText(label, lineSize, alignment, false); - return templabel; - } - else - { - return 0; - } - - return 0; -} - -Label* Label::createWithAtlas(FontAtlas *atlas, TextHAlignment alignment, int lineSize, bool useDistanceField,bool useA8Shader) -{ - Label *ret = new Label(atlas, alignment, useDistanceField,useA8Shader); - if (!ret) - return 0; - - if( ret->init() ) + return nullptr; + + ret->autorelease(); + + return ret; +} + +Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment /* = TextHAlignment::CENTER */, int lineSize /* = 0 */) +{ + Label *ret = new Label(); + + if (!ret) + return nullptr; + + if (ret->setTTFConfig(ttfConfig)) { + if(ttfConfig.distanceFieldEnable) + ret->setFontSize(ttfConfig.fontSize); + ret->setText(text,alignment,lineSize); ret->autorelease(); return ret; } else { delete ret; - return 0; + return nullptr; + } +} + +Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment /* = TextHAlignment::CENTER */, int lineSize /* = 0 */) +{ + Label *ret = new Label(); + + if (!ret) + return nullptr; + + if (ret->setBMFontFilePath(bmfontFilePath)) + { + ret->setText(text,alignment,lineSize); + ret->autorelease(); + return ret; + } + else + { + delete ret; + return nullptr; } - - return ret; } Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,bool useA8Shader) @@ -108,8 +93,8 @@ Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,b , _lineBreakWithoutSpaces(false) , _width(0.0f) , _alignment(alignment) -, _currentUTF16String(0) -, _originalUTF16String(0) +, _currentUTF16String(nullptr) +, _originalUTF16String(nullptr) , _advances(nullptr) , _fontAtlas(atlas) , _isOpacityModifyRGB(true) @@ -118,6 +103,7 @@ Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,b , _fontSize(0) , _uniformEffectColor(0) { + _cascadeColorEnabled = true; } Label::~Label() @@ -137,10 +123,13 @@ bool Label::init() bool ret = true; if(_fontAtlas) { - _reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0)); - _reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB); - ret = SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30); - _reusedLetter->retain(); + if (_reusedLetter == nullptr) + { + _reusedLetter = Sprite::createWithTexture(&_fontAtlas->getTexture(0)); + _reusedLetter->setOpacityModifyRGB(_isOpacityModifyRGB); + _reusedLetter->retain(); + } + ret = SpriteBatchNode::initWithTexture(&_fontAtlas->getTexture(0), 30); } if (_useDistanceField) setLabelEffect(LabelEffect::NORMAL,Color3B::BLACK); @@ -148,24 +137,119 @@ bool Label::init() setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_A8_COLOR)); else setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); + return ret; } -void Label::setString(const std::string &stringToRender) +bool Label::setTTFConfig(const TTFConfig& ttfConfig) +{ + FontAtlas *newAtlas = nullptr; + if(ttfConfig.distanceFieldEnable) + newAtlas = FontAtlasCache::getFontAtlasTTF(ttfConfig.fontFilePath, DISTANCEFIELD_ATLAS_FONTSIZE, ttfConfig.glyphs, ttfConfig.customGlyphs,true); + else + newAtlas = FontAtlasCache::getFontAtlasTTF(ttfConfig.fontFilePath, ttfConfig.fontSize, ttfConfig.glyphs, ttfConfig.customGlyphs,false); + + if (!newAtlas) + return false; + + FontAtlas *oldAtlas = _fontAtlas; + bool oldDistanceFieldEnable = _useDistanceField; + bool oldA8ShaderEnabel = _useA8Shader; + + _fontAtlas = newAtlas; + _useDistanceField = ttfConfig.distanceFieldEnable; + _useA8Shader = true; + + bool ret = Label::init(); + if (oldAtlas) + { + if (ret) + { + FontAtlasCache::releaseFontAtlas(oldAtlas); + } + else + { + _fontAtlas = oldAtlas; + _useDistanceField = oldDistanceFieldEnable; + _useA8Shader = oldA8ShaderEnabel; + Label::init(); + + FontAtlasCache::releaseFontAtlas(newAtlas); + } + } + + if (_fontAtlas) + { + _commonLineHeight = _fontAtlas->getCommonLineHeight(); + if (_currentUTF16String) + { + alignText(); + } + } + + return ret; +} + +bool Label::setBMFontFilePath(const std::string& bmfontFilePath) +{ + FontAtlas *newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath); + + if (!newAtlas) + return false; + + FontAtlas *oldAtlas = _fontAtlas; + bool oldDistanceFieldEnable = _useDistanceField; + bool oldA8ShaderEnabel = _useA8Shader; + + _fontAtlas = newAtlas; + _useDistanceField = false; + _useA8Shader = false; + + bool ret = Label::init(); + if (oldAtlas) + { + if (ret) + { + FontAtlasCache::releaseFontAtlas(oldAtlas); + } + else + { + _fontAtlas = oldAtlas; + _useDistanceField = oldDistanceFieldEnable; + _useA8Shader = oldA8ShaderEnabel; + Label::init(); + + FontAtlasCache::releaseFontAtlas(newAtlas); + } + } + + if (_fontAtlas) + { + _commonLineHeight = _fontAtlas->getCommonLineHeight(); + if (_currentUTF16String) + { + alignText(); + } + } + + return ret; +} + +void Label::setString(const std::string &text) { _multilineEnable = true; - setText(stringToRender, _width, TextHAlignment::CENTER, false); + setText(text, TextHAlignment::CENTER, _width, false); } -void Label::setString(const std::string &stringToRender,bool multilineEnable) +void Label::setString(const std::string &text,bool multilineEnable) { _multilineEnable = multilineEnable; - setText(stringToRender, _width, TextHAlignment::CENTER, false); + setText(text, TextHAlignment::CENTER, _width, false); } -bool Label::setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment, bool lineBreakWithoutSpaces) +bool Label::setText(const std::string& text, const TextHAlignment& alignment /* = TextHAlignment::LEFT */, float lineWidth /* = 0 */, bool lineBreakWithoutSpaces /* = false */) { - if (!_fontAtlas) + if (!_fontAtlas || _commonLineHeight <= 0) return false; // carloX @@ -176,18 +260,10 @@ bool Label::setText(const std::string& stringToRender, float lineWidth, TextHAli _alignment = alignment; _lineBreakWithoutSpaces = lineBreakWithoutSpaces; - // store locally common line height - _commonLineHeight = _fontAtlas->getCommonLineHeight(); - if (_commonLineHeight <= 0) - return false; - -// int numLetter = 0; - unsigned short* utf16String = cc_utf8_to_utf16(stringToRender.c_str()); + unsigned short* utf16String = cc_utf8_to_utf16(text.c_str()); if(!utf16String) return false; - _cascadeColorEnabled = true; - setCurrentString(utf16String); setOriginalString(utf16String); diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index ea7462ab50..4b8de8163e 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -54,23 +54,44 @@ enum class LabelEffect { struct FontLetterDefinition; class FontAtlas; +typedef struct _ttfConfig +{ + std::string fontFilePath; + int fontSize; + GlyphCollection glyphs; + const char *customGlyphs; + bool distanceFieldEnable; + _ttfConfig(const char* filePath,int fontSize = 36, const GlyphCollection& glyphs = GlyphCollection::NEHE, + const char *customGlyphs = nullptr,bool useDistanceField = false) + :fontFilePath(filePath) + ,fontSize(fontSize) + ,glyphs(glyphs) + ,customGlyphs(customGlyphs) + ,distanceFieldEnable(useDistanceField) + {} +}TTFConfig; class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public LabelTextFormatProtocol { public: - - // static create - static Label* createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0, bool useDistanceField = false); - - static Label* createWithBMFont(const std::string& label, const std::string& bmfontFilePath, TextHAlignment alignment = TextHAlignment::CENTER, int lineSize = 0); - - bool setText(const std::string& stringToRender, float lineWidth, TextHAlignment alignment = TextHAlignment::LEFT, bool lineBreakWithoutSpaces = false); + static Label* create(); + static Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment = TextHAlignment::CENTER, int lineWidth = 0); + + static Label* createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment = TextHAlignment::CENTER, int lineWidth = 0); + + bool setTTFConfig(const TTFConfig& ttfConfig); + + bool setBMFontFilePath(const std::string& bmfontFilePath); + + bool setText(const std::string& text, const TextHAlignment& alignment = TextHAlignment::LEFT, float lineWidth = 0, bool lineBreakWithoutSpaces = false); + + //only support for TTF void setLabelEffect(LabelEffect effect,const Color3B& effectColor); - virtual void setString(const std::string &stringToRender) override; - void setString(const std::string &stringToRender,bool multilineEnable); + virtual void setString(const std::string &text) override; + void setString(const std::string &text,bool multilineEnable); virtual void setAlignment(TextHAlignment alignment); virtual void setWidth(float width); virtual void setLineBreakWithoutSpace(bool breakWithoutSpace); @@ -127,15 +148,13 @@ private: /** * @js NA */ - Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField = false,bool useA8Shader = false); + Label(FontAtlas *atlas = nullptr, TextHAlignment alignment = TextHAlignment::CENTER, bool useDistanceField = false,bool useA8Shader = false); /** * @js NA * @lua NA */ ~Label(); - static Label* createWithAtlas(FontAtlas *atlas, TextHAlignment alignment = TextHAlignment::LEFT, int lineSize = 0, bool useDistanceField = false,bool useA8Shader = false); - void setFontSize(int fontSize); bool init(); @@ -151,7 +170,6 @@ private: virtual void updateColor() override; - //! used for optimization Sprite *_reusedLetter; std::vector _lettersInfo; diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index a33c70d7bd..4c9597201a 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -16af4ad046f4db00af7a229d89c406054d8616c3 \ No newline at end of file +52164446e797e85d5d6d746eb85e915c8eb7df15 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp index 9d3d063102..d779ae6a86 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp @@ -158,20 +158,19 @@ LabelTTFAlignmentNew::LabelTTFAlignmentNew() { auto s = Director::getInstance()->getWinSize(); - auto ttf0 = Label::createWithTTF("Alignment 0\nnew line", "fonts/tahoma.ttf", 32); - ttf0->setAlignment(TextHAlignment::LEFT); + TTFConfig config("fonts/tahoma.ttf",32); + + auto ttf0 = Label::createWithTTF(config,"Alignment 0\nnew line",TextHAlignment::LEFT); ttf0->setPosition(Point(s.width/2,(s.height/6)*2 - 30)); ttf0->setAnchorPoint(Point(0.5f,0.5f)); this->addChild(ttf0); - auto ttf1 = Label::createWithTTF("Alignment 1\nnew line", "fonts/tahoma.ttf", 32); - ttf1->setAlignment(TextHAlignment::CENTER); + auto ttf1 = Label::createWithTTF(config,"Alignment 1\nnew line",TextHAlignment::CENTER); ttf1->setPosition(Point(s.width/2,(s.height/6)*3 - 30)); ttf1->setAnchorPoint(Point(0.5f,0.5f)); this->addChild(ttf1); - auto ttf2 = Label::createWithTTF("Alignment 2\nnew line", "fonts/tahoma.ttf", 32); - ttf1->setAlignment(TextHAlignment::RIGHT); + auto ttf2 = Label::createWithTTF(config,"Alignment 2\nnew line",TextHAlignment::RIGHT); ttf2->setPosition(Point(s.width/2,(s.height/6)*4 - 30)); ttf2->setAnchorPoint(Point(0.5f,0.5f)); this->addChild(ttf2); @@ -194,7 +193,7 @@ LabelFNTColorAndOpacity::LabelFNTColorAndOpacity() auto col = LayerColor::create( Color4B(128,128,128,255) ); addChild(col, -10); - auto label1 = Label::createWithBMFont("Test", "fonts/bitmapFontTest2.fnt"); + auto label1 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Test"); label1->setAnchorPoint( Point(0,0) ); addChild(label1, 0, kTagBitmapAtlas1); @@ -204,13 +203,13 @@ LabelFNTColorAndOpacity::LabelFNTColorAndOpacity() auto repeat = RepeatForever::create(seq); label1->runAction(repeat); - auto label2 = Label::createWithBMFont("Test", "fonts/bitmapFontTest2.fnt"); + auto label2 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Test"); label2->setAnchorPoint( Point(0.5f, 0.5f) ); label2->setColor( Color3B::RED ); addChild(label2, 0, kTagBitmapAtlas2); label2->runAction( repeat->clone() ); - auto label3 = Label::createWithBMFont("Test", "fonts/bitmapFontTest2.fnt"); + auto label3 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Test"); label3->setAnchorPoint( Point(1,1) ); addChild(label3, 0, kTagBitmapAtlas3); @@ -252,7 +251,7 @@ LabelFNTSpriteActions::LabelFNTSpriteActions() _time = 0; // Upper Label - auto label = Label::createWithBMFont("Bitmap Font Atlas", "fonts/bitmapFontTest.fnt"); + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "Bitmap Font Atlas"); addChild(label); auto s = Director::getInstance()->getWinSize(); @@ -289,7 +288,7 @@ LabelFNTSpriteActions::LabelFNTSpriteActions() // Bottom Label - auto label2 = Label::createWithBMFont("00.0", "fonts/bitmapFontTest.fnt"); + auto label2 = Label::createWithBMFont("fonts/bitmapFontTest.fnt", "00.0"); addChild(label2, 0, kTagBitmapAtlas2); label2->setPosition( Point(s.width/2.0f, 80) ); @@ -341,7 +340,7 @@ std::string LabelFNTSpriteActions::subtitle() const LabelFNTPadding::LabelFNTPadding() { - auto label = Label::createWithBMFont("abcdefg", "fonts/bitmapFontTest4.fnt"); + auto label = Label::createWithBMFont("fonts/bitmapFontTest4.fnt", "abcdefg"); addChild(label); auto s = Director::getInstance()->getWinSize(); @@ -365,17 +364,17 @@ LabelFNTOffset::LabelFNTOffset() auto s = Director::getInstance()->getWinSize(); Label* label = NULL; - label = Label::createWithBMFont("FaFeFiFoFu", "fonts/bitmapFontTest5.fnt"); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "FaFeFiFoFu"); addChild(label); label->setPosition( Point(s.width/2, s.height/2+50) ); label->setAnchorPoint( Point(0.5f, 0.5f) ) ; - label = Label::createWithBMFont("fafefifofu", "fonts/bitmapFontTest5.fnt"); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "fafefifofu"); addChild(label); label->setPosition( Point(s.width/2, s.height/2) ); label->setAnchorPoint( Point(0.5f, 0.5f) ); - label = Label::createWithBMFont("aeiou", "fonts/bitmapFontTest5.fnt"); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "aeiou"); addChild(label); label->setPosition( Point(s.width/2, s.height/2-50) ); label->setAnchorPoint( Point(0.5f, 0.5f) ); @@ -396,19 +395,19 @@ LabelFNTColor::LabelFNTColor() auto s = Director::getInstance()->getWinSize(); Label* label = NULL; - label = Label::createWithBMFont("Blue", "fonts/bitmapFontTest5.fnt"); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "Blue"); label->setColor( Color3B::BLUE ); addChild(label); label->setPosition( Point(s.width/2, s.height/4) ); label->setAnchorPoint( Point(0.5f, 0.5f) ); - label = Label::createWithBMFont("Red", "fonts/bitmapFontTest5.fnt"); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "Red"); addChild(label); label->setPosition( Point(s.width/2, 2*s.height/4) ); label->setAnchorPoint( Point(0.5f, 0.5f) ); label->setColor( Color3B::RED ); - label = Label::createWithBMFont("G", "fonts/bitmapFontTest5.fnt"); + label = Label::createWithBMFont("fonts/bitmapFontTest5.fnt", "Green"); addChild(label); label->setPosition( Point(s.width/2, 3*s.height/4) ); label->setAnchorPoint( Point(0.5f, 0.5f) ); @@ -433,7 +432,7 @@ LabelFNTHundredLabels::LabelFNTHundredLabels() { char str[6] = {0}; sprintf(str, "-%d-", i); - auto label = Label::createWithBMFont(str, "fonts/bitmapFontTest.fnt"); + auto label = Label::createWithBMFont("fonts/bitmapFontTest.fnt", str); addChild(label); auto s = Director::getInstance()->getWinSize(); @@ -459,7 +458,7 @@ LabelFNTMultiLine::LabelFNTMultiLine() Size s; // Left - auto label1 = Label::createWithBMFont(" Multi line\nLeft", "fonts/bitmapFontTest3.fnt"); + auto label1 = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", " Multi line\nLeft"); label1->setAnchorPoint(Point(0,0)); addChild(label1, 0, kTagBitmapAtlas1); @@ -468,7 +467,7 @@ LabelFNTMultiLine::LabelFNTMultiLine() // Center - auto label2 = Label::createWithBMFont("Multi line\nCenter", "fonts/bitmapFontTest3.fnt"); + auto label2 = Label::createWithBMFont( "fonts/bitmapFontTest3.fnt", "Multi line\nCenter"); label2->setAnchorPoint(Point(0.5f, 0.5f)); addChild(label2, 0, kTagBitmapAtlas2); @@ -476,7 +475,7 @@ LabelFNTMultiLine::LabelFNTMultiLine() CCLOG("content size: %.2fx%.2f", s.width, s.height); // right - auto label3 = Label::createWithBMFont("Multi line\nRight\nThree lines Three", "fonts/bitmapFontTest3.fnt"); + auto label3 = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "Multi line\nRight\nThree lines Three"); label3->setAnchorPoint(Point(1, 1)); addChild(label3, 0, kTagBitmapAtlas3); @@ -504,19 +503,18 @@ LabelFNTandTTFEmpty::LabelFNTandTTFEmpty() float delta = s.height/4; // LabelBMFont - auto label1 = Label::createWithBMFont("", "fonts/bitmapFontTest3.fnt", TextHAlignment::CENTER, s.width); + auto label1 = Label::createWithBMFont("fonts/bitmapFontTest3.fnt", "", TextHAlignment::CENTER, s.width); addChild(label1, 0, kTagBitmapAtlas1); label1->setAnchorPoint(Point(0.5f, 0.5f)); label1->setPosition(Point(s.width/2, delta)); // LabelTTF - auto label2 = Label::createWithTTF("", "fonts/arial.ttf", 48, s.width, TextHAlignment::CENTER,GlyphCollection::NEHE); + TTFConfig ttfConfig("fonts/arial.ttf",48); + auto label2 = Label::createWithTTF(ttfConfig,"", TextHAlignment::CENTER,s.width); addChild(label2, 0, kTagBitmapAtlas2); label2->setAnchorPoint(Point(0.5f, 0.5f)); label2->setPosition(Point(s.width/2, delta * 2)); - - schedule(schedule_selector(LabelFNTandTTFEmpty::updateStrings), 1.0f); setEmpty = false; @@ -558,7 +556,7 @@ LabelFNTRetina::LabelFNTRetina() auto s = Director::getInstance()->getWinSize(); // LabelBMFont - auto label1 = Label::createWithBMFont("TESTING RETINA DISPLAY", "fonts/konqa32.fnt"); + auto label1 = Label::createWithBMFont("fonts/konqa32.fnt", "TESTING RETINA DISPLAY"); label1->setAnchorPoint(Point(0.5f, 0.5f)); addChild(label1); label1->setPosition(Point(s.width/2, s.height/2)); @@ -582,7 +580,7 @@ LabelFNTGlyphDesigner::LabelFNTGlyphDesigner() addChild(layer, -10); // LabelBMFont - auto label1 = Label::createWithBMFont("Testing Glyph Designer", "fonts/futura-48.fnt"); + auto label1 = Label::createWithBMFont("fonts/futura-48.fnt", "Testing Glyph Designer"); label1->setAnchorPoint(Point(0.5f, 0.5f)); addChild(label1); label1->setPosition(Point(s.width/2, s.height/2)); @@ -603,7 +601,8 @@ LabelTTFUnicodeChinese::LabelTTFUnicodeChinese() auto size = Director::getInstance()->getWinSize(); // Adding "啊" letter at the end of string to make VS2012 happy, otherwise VS will generate errors // like "Error 3 error C2146: syntax error : missing ')' before identifier 'label'"; - auto label = Label::createWithTTF("美好的一天啊", "fonts/wt021.ttf", 55, size.width, TextHAlignment::CENTER, GlyphCollection::CUSTOM, "美好的一天啊"); + TTFConfig ttfConfig("fonts/wt021.ttf",55,GlyphCollection::CUSTOM, "美好的一天啊"); + auto label = Label::createWithTTF(ttfConfig,"美好的一天啊", TextHAlignment::CENTER, size.width); label->setAnchorPoint(Point(0.5f, 0.5f)); label->setPosition(Point(size.width / 2, size.height /2)); this->addChild(label); @@ -622,7 +621,7 @@ std::string LabelTTFUnicodeChinese::subtitle() const LabelFNTUnicodeChinese::LabelFNTUnicodeChinese() { auto size = Director::getInstance()->getWinSize(); - auto label = Label::createWithBMFont("中国", "fonts/bitmapFontChinese.fnt"); + auto label = Label::createWithBMFont("fonts/bitmapFontChinese.fnt", "中国"); label->setAnchorPoint(Point(0.5f, 0.5f)); label->setPosition(Point(size.width / 2, size.height /2)); this->addChild(label); @@ -671,8 +670,7 @@ LabelFNTMultiLineAlignment::LabelFNTMultiLineAlignment() auto size = Director::getInstance()->getWinSize(); // create and initialize a Label - this->_labelShouldRetain = Label::createWithBMFont(LongSentencesExample, "fonts/markerFelt.fnt", TextHAlignment::CENTER, size.width/1.5); - //this->_labelShouldRetain = Label::createWithBMFont(LongSentencesExample, "fonts/bitmapFontTest.fnt", TextHAlignment::CENTER, size.width/1.5); + this->_labelShouldRetain = Label::createWithBMFont("fonts/markerFelt.fnt", LongSentencesExample, TextHAlignment::CENTER, size.width/1.5); this->_labelShouldRetain->setAnchorPoint(Point(0.5f, 0.5f)); this->_labelShouldRetain->retain(); @@ -855,22 +853,22 @@ LabelFNTUNICODELanguages::LabelFNTUNICODELanguages() auto s = Director::getInstance()->getWinSize(); - auto label1 = Label::createWithBMFont(spanish, "fonts/arial-unicode-26.fnt", TextHAlignment::CENTER, 200); + auto label1 = Label::createWithBMFont("fonts/arial-unicode-26.fnt", spanish, TextHAlignment::CENTER, 200); addChild(label1); label1->setAnchorPoint(Point(0.5f, 0.5f)); label1->setPosition(Point(s.width/2, s.height/5*3)); - auto label2 = Label::createWithBMFont(chinese, "fonts/arial-unicode-26.fnt"); + auto label2 = Label::createWithBMFont("fonts/arial-unicode-26.fnt", chinese); addChild(label2); label2->setAnchorPoint(Point(0.5f, 0.5f)); label2->setPosition(Point(s.width/2, s.height/5*2.5)); - auto label3 = Label::createWithBMFont(russian, "fonts/arial-26-en-ru.fnt"); + auto label3 = Label::createWithBMFont("fonts/arial-26-en-ru.fnt", russian); addChild(label3); label3->setAnchorPoint(Point(0.5f, 0.5f)); label3->setPosition(Point(s.width/2, s.height/5*2)); - auto label4 = Label::createWithBMFont(japanese, "fonts/arial-unicode-26.fnt"); + auto label4 = Label::createWithBMFont("fonts/arial-unicode-26.fnt", japanese); addChild(label4); label4->setAnchorPoint(Point(0.5f, 0.5f)); label4->setPosition(Point(s.width/2, s.height/5*1.5)); @@ -894,7 +892,7 @@ LabelFNTBounds::LabelFNTBounds() addChild(layer, -10); // LabelBMFont - label1 = Label::createWithBMFont("Testing Glyph Designer", "fonts/boundsTestFont.fnt", TextHAlignment::CENTER, s.width); + label1 = Label::createWithBMFont("fonts/boundsTestFont.fnt", "Testing Glyph Designer", TextHAlignment::CENTER, s.width); label1->setAnchorPoint(Point(0.5f, 0.5f)); addChild(label1); label1->setPosition(Point(s.width/2, s.height/2)); @@ -946,7 +944,8 @@ LabelTTFLongLineWrapping::LabelTTFLongLineWrapping() auto size = Director::getInstance()->getWinSize(); // Long sentence - auto label1 = Label::createWithTTF(LongSentencesExample, "fonts/arial.ttf", 28, size.width, TextHAlignment::CENTER, GlyphCollection::NEHE); + TTFConfig ttfConfig("fonts/arial.ttf", 28); + auto label1 = Label::createWithTTF(ttfConfig, LongSentencesExample, TextHAlignment::CENTER,size.width); label1->setPosition( Point(size.width/2, size.height/2) ); label1->setAnchorPoint(Point(0.5, 1.0)); addChild(label1); @@ -966,22 +965,23 @@ LabelTTFColor::LabelTTFColor() { auto size = Director::getInstance()->getWinSize(); + TTFConfig ttfConfig("fonts/arial.ttf", 35); // Green - auto label1 = Label::createWithTTF("Green", "fonts/arial.ttf", 35, size.width, TextHAlignment::CENTER, GlyphCollection::NEHE); + auto label1 = Label::createWithTTF(ttfConfig,"Green", TextHAlignment::CENTER, size.width); label1->setPosition( Point(size.width/2, size.height/5 * 1.5) ); label1->setColor( Color3B::GREEN ); label1->setAnchorPoint(Point(0.5, 0.5)); addChild(label1); // Red - auto label2 = Label::createWithTTF("Red", "fonts/arial.ttf", 35, size.width, TextHAlignment::CENTER, GlyphCollection::NEHE); + auto label2 = Label::createWithTTF(ttfConfig,"Red", TextHAlignment::CENTER, size.width); label2->setPosition( Point(size.width/2, size.height/5 * 2.0) ); label2->setColor( Color3B::RED ); label2->setAnchorPoint(Point(0.5, 0.5)); addChild(label2); // Blue - auto label3 = Label::createWithTTF("Blue", "fonts/arial.ttf", 35, size.width, TextHAlignment::CENTER, GlyphCollection::NEHE); + auto label3 = Label::createWithTTF(ttfConfig,"Blue", TextHAlignment::CENTER, size.width); label3->setPosition( Point(size.width/2, size.height/5 * 2.5) ); label3->setColor( Color3B::BLUE ); label3->setAnchorPoint(Point(0.5, 0.5)); @@ -1001,12 +1001,10 @@ std::string LabelTTFColor::subtitle() const LabelTTFDynamicAlignment::LabelTTFDynamicAlignment() { auto size = Director::getInstance()->getWinSize(); - - _label = Label::createWithTTF(LongSentencesExample, "fonts/arial.ttf", 45, size.width, TextHAlignment::CENTER, GlyphCollection::NEHE); + TTFConfig ttfConfig("fonts/arial.ttf", 45); + _label = Label::createWithTTF(ttfConfig,LongSentencesExample, TextHAlignment::CENTER, size.width); _label->setPosition( Point(size.width/2, size.height/2) ); - _label->setAnchorPoint(Point(0.5, 0.5)); - - + _label->setAnchorPoint(Point(0.5, 0.5)); auto menu = Menu::create( MenuItemFont::create("Left", CC_CALLBACK_1(LabelTTFDynamicAlignment::setAlignmentLeft, this)), @@ -1074,21 +1072,24 @@ LabelTTFUnicodeNew::LabelTTFUnicodeNew() float vStep = size.height/9; float vSize = size.height; - + TTFConfig ttfConfig("fonts/arial.ttf", 45,GlyphCollection::ASCII); // Spanish - auto label1 = Label::createWithTTF("Buen día, ¿cómo te llamas?", "fonts/arial.ttf", 45, size.width, TextHAlignment::CENTER, GlyphCollection::ASCII); + auto label1 = Label::createWithTTF(ttfConfig,"Buen día, ¿cómo te llamas?", TextHAlignment::CENTER, size.width); label1->setPosition( Point(size.width/2, vSize - (vStep * 4.5)) ); label1->setAnchorPoint(Point(0.5, 0.5)); addChild(label1); // German - auto label2 = Label::createWithTTF("In welcher Straße haben Sie gelebt?", "fonts/arial.ttf", 45, size.width, TextHAlignment::CENTER, GlyphCollection::ASCII); + auto label2 = Label::createWithTTF(ttfConfig,"In welcher Straße haben Sie gelebt?", TextHAlignment::CENTER,size.width); label2->setPosition( Point(size.width/2, vSize - (vStep * 5.5)) ); label2->setAnchorPoint(Point(0.5, 0.5)); addChild(label2); // chinese - auto label3 = Label::createWithTTF(chinese, "fonts/wt021.ttf", 45, size.width, TextHAlignment::CENTER, GlyphCollection::CUSTOM, chinese.c_str()); + ttfConfig.fontFilePath = "fonts/wt021.ttf"; + ttfConfig.glyphs = GlyphCollection::CUSTOM; + ttfConfig.customGlyphs = chinese.c_str(); + auto label3 = Label::createWithTTF(ttfConfig,chinese, TextHAlignment::CENTER,size.width); label3->setPosition( Point(size.width/2, vSize - (vStep * 6.5)) ); label3->setAnchorPoint(Point(0.5, 0.5)); addChild(label3); @@ -1118,9 +1119,10 @@ LabelTTFFontsTestNew::LabelTTFFontsTestNew() #define arraysize(ar) (sizeof(ar) / sizeof(ar[0])) auto size = Director::getInstance()->getWinSize(); - + TTFConfig ttfConfig(ttfpaths[0],40, GlyphCollection::NEHE); for(size_t i=0;i < arraysize(ttfpaths); ++i) { - auto label = Label::createWithTTF( ttfpaths[i], ttfpaths[i], 40, 0, TextHAlignment::CENTER, GlyphCollection::NEHE); + ttfConfig.fontFilePath = ttfpaths[i]; + auto label = Label::createWithTTF(ttfConfig, ttfpaths[i], TextHAlignment::CENTER,0); if( label ) { label->setPosition( Point(size.width/2, ((size.height * 0.6)/arraysize(ttfpaths) * i) + (size.height/5))); @@ -1147,7 +1149,7 @@ LabelBMFontTestNew::LabelBMFontTestNew() { auto size = Director::getInstance()->getWinSize(); - auto label1 = Label::createWithBMFont("Hello World, this is testing the new Label using fnt file", "fonts/bitmapFontTest2.fnt", TextHAlignment::CENTER, size.width); + auto label1 = Label::createWithBMFont("fonts/bitmapFontTest2.fnt", "Hello World, this is testing the new Label using fnt file", TextHAlignment::CENTER, size.width); label1->setPosition( Point(size.width/2, size.height/2) ); label1->setAnchorPoint(Point(0.5, 0.5)); addChild(label1); @@ -1166,8 +1168,9 @@ std::string LabelBMFontTestNew::subtitle() const LabelTTFDistanceField::LabelTTFDistanceField() { auto size = Director::getInstance()->getWinSize(); + TTFConfig ttfConfig("fonts/arial.ttf", 80, GlyphCollection::DYNAMIC,nullptr,true); - auto label1 = Label::createWithTTF("Distance Field", "fonts/arial.ttf", 80, size.width, TextHAlignment::CENTER, GlyphCollection::DYNAMIC,nullptr,true); + auto label1 = Label::createWithTTF(ttfConfig,"Distance Field",TextHAlignment::CENTER,size.width); label1->setPosition( Point(size.width/2, size.height/2) ); label1->setColor( Color3B::GREEN ); label1->setAnchorPoint(Point(0.5, 0.5)); @@ -1180,7 +1183,7 @@ LabelTTFDistanceField::LabelTTFDistanceField() nullptr); label1->runAction(RepeatForever::create(action)); - auto label2 = Label::createWithTTF("Distance Field", "fonts/arial.ttf", 80, size.width, TextHAlignment::CENTER, GlyphCollection::DYNAMIC,nullptr,true); + auto label2 = Label::createWithTTF(ttfConfig,"Distance Field",TextHAlignment::CENTER,size.width); label2->setPosition( Point(size.width/2, size.height/5) ); label2->setColor( Color3B::RED ); label2->setAnchorPoint(Point(0.5, 0.5)); @@ -1205,21 +1208,23 @@ LabelTTFDistanceFieldEffect::LabelTTFDistanceFieldEffect() auto bg = LayerColor::create(Color4B(200,191,231,255)); this->addChild(bg); - auto label1 = Label::createWithTTF("Glow", "fonts/arial.ttf", 80, size.width, TextHAlignment::CENTER, GlyphCollection::DYNAMIC,nullptr,true); + TTFConfig ttfConfig("fonts/arial.ttf", 80, GlyphCollection::DYNAMIC,nullptr,true); + + auto label1 = Label::createWithTTF(ttfConfig,"Glow", TextHAlignment::CENTER, size.width); label1->setPosition( Point(size.width/2, size.height*0.5) ); label1->setColor( Color3B::GREEN ); label1->setAnchorPoint(Point(0.5, 0.5)); label1->setLabelEffect(LabelEffect::GLOW,Color3B::YELLOW); addChild(label1); - auto label2 = Label::createWithTTF("Outline", "fonts/arial.ttf", 80, size.width, TextHAlignment::CENTER, GlyphCollection::DYNAMIC,nullptr,true); + auto label2 = Label::createWithTTF(ttfConfig,"Outline", TextHAlignment::CENTER, size.width); label2->setPosition( Point(size.width/2, size.height*0.375) ); label2->setColor( Color3B::RED ); label2->setAnchorPoint(Point(0.5, 0.5)); label2->setLabelEffect(LabelEffect::OUTLINE,Color3B::BLUE); addChild(label2); - auto label3 = Label::createWithTTF("Shadow", "fonts/arial.ttf", 80, size.width, TextHAlignment::CENTER, GlyphCollection::DYNAMIC,nullptr,true); + auto label3 = Label::createWithTTF(ttfConfig,"Shadow", TextHAlignment::CENTER, size.width); label3->setPosition( Point(size.width/2, size.height*0.25f) ); label3->setColor( Color3B::RED ); label3->setAnchorPoint(Point(0.5, 0.5)); diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index d23091db12..0cee1ffbd1 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -764,20 +764,22 @@ void DirectorEventTest::onEnter() Size s = Director::getInstance()->getWinSize(); - _label1 = Label::createWithTTF("Update: 0", "fonts/arial.ttf", 20); + TTFConfig ttfConfig("fonts/arial.ttf", 20); + + _label1 = Label::createWithTTF(ttfConfig, "Update: 0"); _label1->setPosition(30,s.height/2 + 60); this->addChild(_label1); - _label2 = Label::createWithTTF("Visit: 0", "fonts/arial.ttf", 20); + _label2 = Label::createWithTTF(ttfConfig, "Visit: 0"); _label2->setPosition(30,s.height/2 + 20); this->addChild(_label2); - _label3 = Label::createWithTTF("Draw: 0", "fonts/arial.ttf", 20); + _label3 = Label::createWithTTF(ttfConfig, "Draw: 0"); _label3->setPosition(30,30); _label3->setPosition(30,s.height/2 - 20); this->addChild(_label3); - _label4 = Label::createWithTTF("Projection: 0", "fonts/arial.ttf", 20); + _label4 = Label::createWithTTF(ttfConfig, "Projection: 0"); _label4->setPosition(30,30); _label4->setPosition(30,s.height/2 - 60); this->addChild(_label4); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp index 317bbb8a60..50d60d84fa 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp @@ -86,6 +86,7 @@ void LabelMainScene::initWithSubTest(int nodes) _lastRenderedCount = 0; _quantityNodes = 0; + _accumulativeTime = 0.0f; _labelContainer = Layer::create(); addChild(_labelContainer); @@ -212,15 +213,18 @@ void LabelMainScene::onIncrease(Object* sender) } break; case kCaseLabelUpdate: - for( int i=0;i< kNodesIncrease;i++) { - auto label = Label::createWithTTF("Label", "fonts/arial.ttf", 60, size.width, TextHAlignment::CENTER, GlyphCollection::DYNAMIC,nullptr,true); - label->setPosition(Point((size.width/2 + rand() % 50), ((int)size.height/2 + rand() % 50))); - _labelContainer->addChild(label, 1, _quantityNodes); + TTFConfig ttfConfig("fonts/arial.ttf", 60, GlyphCollection::DYNAMIC, nullptr, true); + for( int i=0;i< kNodesIncrease;i++) + { + auto label = Label::createWithTTF(ttfConfig, "Label", TextHAlignment::CENTER, size.width); + label->setPosition(Point((size.width/2 + rand() % 50), ((int)size.height/2 + rand() % 50))); + _labelContainer->addChild(label, 1, _quantityNodes); - _quantityNodes++; - } - break; + _quantityNodes++; + } + break; + } case kCaseLabelBMFontBigLabels: for( int i=0;i< kNodesIncrease;i++) { @@ -232,15 +236,18 @@ void LabelMainScene::onIncrease(Object* sender) } break; case kCaseLabelBigLabels: - for( int i=0;i< kNodesIncrease;i++) { - auto label = Label::createWithTTF(LongSentencesExample, "fonts/arial.ttf", 60, size.width, TextHAlignment::CENTER, GlyphCollection::DYNAMIC,nullptr); - label->setPosition(Point((rand() % 50), rand()%((int)size.height/3))); - _labelContainer->addChild(label, 1, _quantityNodes); + TTFConfig ttfConfig("fonts/arial.ttf", 60, GlyphCollection::DYNAMIC); + for( int i=0;i< kNodesIncrease;i++) + { + auto label = Label::createWithTTF(ttfConfig, LongSentencesExample, TextHAlignment::CENTER, size.width); + label->setPosition(Point((rand() % 50), rand()%((int)size.height/3))); + _labelContainer->addChild(label, 1, _quantityNodes); - _quantityNodes++; - } - break; + _quantityNodes++; + } + break; + } default: break; } diff --git a/tools/tojs/cocos2dx.ini b/tools/tojs/cocos2dx.ini index 99f57b9e8e..da69f4695d 100644 --- a/tools/tojs/cocos2dx.ini +++ b/tools/tojs/cocos2dx.ini @@ -54,7 +54,7 @@ skip = Node::[^setPosition$ setGLServerState description getUserObject .*UserDat Copying::[*], LabelProtocol::[*], LabelTextFormatProtocol::[*], - Label::[getLettersInfo], + Label::[getLettersInfo createWithTTF setTTFConfig], .*Delegate::[*], PoolManager::[*], Texture2D::[initWithPVRTCData addPVRTCImage releaseData setTexParameters initWithData keepData getPixelFormatInfoMap], From b2038d14d62f36f7ae6a29dc4123a5ce29f1af3a Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Sat, 11 Jan 2014 22:55:23 +0800 Subject: [PATCH 054/193] update lua binding configuration for label. --- tools/tolua/cocos2dx.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/tolua/cocos2dx.ini b/tools/tolua/cocos2dx.ini index a3fced78fd..e1b5611329 100644 --- a/tools/tolua/cocos2dx.ini +++ b/tools/tolua/cocos2dx.ini @@ -48,7 +48,7 @@ skip = Node::[setGLServerState description getUserObject .*UserData getGLServerS Layer.*::[didAccelerate (g|s)etBlendFunc keyPressed keyReleased], Menu.*::[.*Target getSubItems create initWithItems alignItemsInRows alignItemsInColumns], MenuItem.*::[create setCallback initWithCallback], - Label::[getLettersInfo], + Label::[getLettersInfo createWithTTF setTTFConfig], Copying::[*], LabelProtocol::[*], LabelTextFormatProtocol::[*], From d11bfeb8d45389d7f46b3e7afc4f7a015512c52d Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Sun, 12 Jan 2014 11:02:48 +0800 Subject: [PATCH 055/193] fix compiling error on win --- cocos/base/CCConsole.h | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index 4175395244..eb27bcfb34 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -28,6 +28,7 @@ #if defined(_MSC_VER) || defined(__MINGW32__) #include +#include //typedef SSIZE_T ssize_t; // ssize_t was redefined as int in libwebsockets.h. // Therefore, to avoid conflict, we needs the same definition. From 09f23c1bcb12370345d28cff598c23b1a08232cd Mon Sep 17 00:00:00 2001 From: Pisces000221 <1786762946@qq.com> Date: Sun, 12 Jan 2014 14:38:09 +0800 Subject: [PATCH 056/193] Corrected a few mistakes in project-creator README --- tools/project-creator/README.md | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/tools/project-creator/README.md b/tools/project-creator/README.md index a7f888fbfd..7417a3ecdb 100644 --- a/tools/project-creator/README.md +++ b/tools/project-creator/README.md @@ -1,15 +1,19 @@ -#create_project +#Creating A Project -First you need install python environment. +First you need to install the Python environment. -There have double ways create new cocos project. -Notice:The best of generate path is english path. +There are two ways to create a new cocos project. +Notice: The best project path is an English path without spaces. ##1.UI -* Windows: double click "create_project.py" file -* Mac: ./create_project.py -* Linux: The tkinter was not installed in the linux's default python,therefore, in order to use the gui operate, you have to install the tkinter libaray manually. There is another way to create project by command line. see below for details +* Windows: double click the "create_project.py" file +* Mac: use `./create_project.py` +* Linux: The Tkinter library was not installed automatically in Linux, therefore, in order to use the GUI to operate, you have to install Tkinter manually (see http://tkinter.unpythonic.net/wiki/How_to_install_Tkinter). There is another way to create projects by command line. See below for details. + ##2.console +To use this, open the terminal and type: +``` $ cd cocos2d-x/tools/project-creator $ ./project-creator.py --help $ ./project-creator.py -n mygame -k com.your_company.mygame -l cpp -p /home/mygame - $ cd /home/mygame \ No newline at end of file + $ cd /home/mygame +``` From 34a79a02e7d4473ec431c1d7e6022db1197340fd Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Mon, 13 Jan 2014 10:32:34 +0800 Subject: [PATCH 057/193] fix compiling error when CC_ENABLE_CHIPMUNK_INTEGRATION and CC_ENABLE_BOX2D_INTEGRATION are zero. --- extensions/physics-nodes/CCPhysicsSprite.cpp | 2 ++ extensions/physics-nodes/CCPhysicsSprite.h | 3 +++ 2 files changed, 5 insertions(+) diff --git a/extensions/physics-nodes/CCPhysicsSprite.cpp b/extensions/physics-nodes/CCPhysicsSprite.cpp index fa3772fc70..84f60ccb7a 100644 --- a/extensions/physics-nodes/CCPhysicsSprite.cpp +++ b/extensions/physics-nodes/CCPhysicsSprite.cpp @@ -19,6 +19,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ +#if (CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION) #include "CCPhysicsSprite.h" @@ -406,3 +407,4 @@ const kmMat4& PhysicsSprite::getNodeToParentTransform() const } NS_CC_EXT_END +#endif //(CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION) \ No newline at end of file diff --git a/extensions/physics-nodes/CCPhysicsSprite.h b/extensions/physics-nodes/CCPhysicsSprite.h index 50eb8a4158..8175a1c6e3 100644 --- a/extensions/physics-nodes/CCPhysicsSprite.h +++ b/extensions/physics-nodes/CCPhysicsSprite.h @@ -19,6 +19,8 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ +#if (CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION) + #ifndef __PHYSICSNODES_CCPHYSICSSPRITE_H__ #define __PHYSICSNODES_CCPHYSICSSPRITE_H__ @@ -132,3 +134,4 @@ protected: NS_CC_EXT_END #endif // __PHYSICSNODES_CCPHYSICSSPRITE_H__ +#endif //(CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION) \ No newline at end of file From fd11791389b794f472c0d4829177fbc1fc5fcfc7 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Mon, 13 Jan 2014 10:37:31 +0800 Subject: [PATCH 058/193] add a blank line at the file end. --- extensions/physics-nodes/CCPhysicsSprite.cpp | 2 +- extensions/physics-nodes/CCPhysicsSprite.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/physics-nodes/CCPhysicsSprite.cpp b/extensions/physics-nodes/CCPhysicsSprite.cpp index 84f60ccb7a..7a193a312f 100644 --- a/extensions/physics-nodes/CCPhysicsSprite.cpp +++ b/extensions/physics-nodes/CCPhysicsSprite.cpp @@ -407,4 +407,4 @@ const kmMat4& PhysicsSprite::getNodeToParentTransform() const } NS_CC_EXT_END -#endif //(CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION) \ No newline at end of file +#endif //(CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION) diff --git a/extensions/physics-nodes/CCPhysicsSprite.h b/extensions/physics-nodes/CCPhysicsSprite.h index 8175a1c6e3..fcedfca031 100644 --- a/extensions/physics-nodes/CCPhysicsSprite.h +++ b/extensions/physics-nodes/CCPhysicsSprite.h @@ -134,4 +134,4 @@ protected: NS_CC_EXT_END #endif // __PHYSICSNODES_CCPHYSICSSPRITE_H__ -#endif //(CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION) \ No newline at end of file +#endif //(CC_ENABLE_CHIPMUNK_INTEGRATION || CC_ENABLE_BOX2D_INTEGRATION) From d7593fd0f02494ecba85543bc91a4b5245680e5e Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Mon, 13 Jan 2014 11:24:49 +0800 Subject: [PATCH 059/193] fix wrong judgments of conditional compilation. --- extensions/physics-nodes/CCPhysicsSprite.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/physics-nodes/CCPhysicsSprite.cpp b/extensions/physics-nodes/CCPhysicsSprite.cpp index 7a193a312f..93ce054384 100644 --- a/extensions/physics-nodes/CCPhysicsSprite.cpp +++ b/extensions/physics-nodes/CCPhysicsSprite.cpp @@ -23,7 +23,7 @@ #include "CCPhysicsSprite.h" -#if defined(CC_ENABLE_CHIPMUNK_INTEGRATION) && defined(CC_ENABLE_BOX2D_INTEGRATION) +#if (CC_ENABLE_CHIPMUNK_INTEGRATION && CC_ENABLE_BOX2D_INTEGRATION) #error "Either Chipmunk or Box2d should be enabled, but not both at the same time" #endif From fd481d64a0a5525b7555a032b8b8c050b78b30cb Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Mon, 13 Jan 2014 16:32:35 +0800 Subject: [PATCH 060/193] 1.update lua binding configuration for label. 2.recover old method[createWithTTF] --- cocos/2d/CCLabel.cpp | 6 ++++++ cocos/2d/CCLabel.h | 1 + tools/tolua/cocos2dx.ini | 1 - 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 4775fd2ae8..1802cf43e1 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -66,6 +66,12 @@ Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, } } +Label* Label::createWithTTF(const std::string& text, const std::string& fontFilePath, int fontSize, int lineSize /* = 0 */, TextHAlignment alignment /* = TextHAlignment::CENTER */, GlyphCollection glyphs /* = GlyphCollection::NEHE */, const char *customGlyphs /* = 0 */, bool useDistanceField /* = false */) +{ + TTFConfig ttfConfig(fontFilePath.c_str(),fontSize,glyphs,customGlyphs,useDistanceField); + return createWithTTF(ttfConfig,text,alignment,lineSize); +} + Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment /* = TextHAlignment::CENTER */, int lineSize /* = 0 */) { Label *ret = new Label(); diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index 4b8de8163e..f7b92e2021 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -77,6 +77,7 @@ class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public LabelT public: static Label* create(); + CC_DEPRECATED_ATTRIBUTE static Label* createWithTTF(const std::string& label, const std::string& fontFilePath, int fontSize, int lineSize = 0, TextHAlignment alignment = TextHAlignment::CENTER, GlyphCollection glyphs = GlyphCollection::NEHE, const char *customGlyphs = 0, bool useDistanceField = false); static Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment = TextHAlignment::CENTER, int lineWidth = 0); static Label* createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment = TextHAlignment::CENTER, int lineWidth = 0); diff --git a/tools/tolua/cocos2dx.ini b/tools/tolua/cocos2dx.ini index e1b5611329..622b14aaf4 100644 --- a/tools/tolua/cocos2dx.ini +++ b/tools/tolua/cocos2dx.ini @@ -108,7 +108,6 @@ skip = Node::[setGLServerState description getUserObject .*UserData getGLServerS ccFontDefinition::[*], Object::[autorelease isEqual acceptVisitor update], UserDefault::[getInstance (s|g)etDataForKey], - Label::[getLettersInfo], EGLViewProtocol::[setTouchDelegate], EGLView::[end swapBuffers], NewTextureAtlas::[*], From 565288f5876e0ad84b2651399d76a00cee6d57e7 Mon Sep 17 00:00:00 2001 From: BoydTang Date: Mon, 13 Jan 2014 22:54:26 +0800 Subject: [PATCH 061/193] =?UTF-8?q?-=20fix=20long=20string=20will=20be=20c?= =?UTF-8?q?ut=20off=20by=20function=20=E2=80=9Ccc=5Futf8=5Fto=5Futf16?= =?UTF-8?q?=E2=80=9D=20(=20=E2=80=9Ccc=5Futf8=5Fstrlen=E2=80=9D=20returns?= =?UTF-8?q?=20long=20)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/ccUTF8.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/ccUTF8.cpp b/cocos/2d/ccUTF8.cpp index 6e70a313d5..c4b9893a04 100644 --- a/cocos/2d/ccUTF8.cpp +++ b/cocos/2d/ccUTF8.cpp @@ -279,7 +279,7 @@ cc_utf8_get_char (const char * p) unsigned short* cc_utf8_to_utf16(const char* str_old, int length/* = -1 */, int* rUtf16Size/* = nullptr */) { - unsigned short len = cc_utf8_strlen(str_old, length); + long len = cc_utf8_strlen(str_old, length); if (rUtf16Size != nullptr) { *rUtf16Size = len; } From 2e127f819b512b5e1c881d3584f112f8508ff57e Mon Sep 17 00:00:00 2001 From: Nite Luo Date: Mon, 13 Jan 2014 11:37:44 -0800 Subject: [PATCH 062/193] Add Polish the labels for project creator ui --- tools/project-creator/module/ui.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/tools/project-creator/module/ui.py b/tools/project-creator/module/ui.py index 7ad74f302d..e7646e1cef 100644 --- a/tools/project-creator/module/ui.py +++ b/tools/project-creator/module/ui.py @@ -120,7 +120,7 @@ class TkCocosDialog(Frame): self.rowconfigure(5, weight=1) # project name frame - self.labName = Label(self, text="projectName:") + self.labName = Label(self, text="Project Name:") self.strName = StringVar() self.strName.set("MyGame") self.editName = Entry(self, textvariable=self.strName) @@ -128,7 +128,7 @@ class TkCocosDialog(Frame): self.editName.grid(row=0, column=1, columnspan=3,padx=5, pady=2,sticky=E+W) # package name frame - self.labPackage = Label(self, text="packageName:") + self.labPackage = Label(self, text="Package Name:") self.strPackage=StringVar() self.strPackage.set("com.MyCompany.AwesomeGame") self.editPackage = Entry(self, textvariable=self.strPackage) @@ -136,7 +136,7 @@ class TkCocosDialog(Frame): self.editPackage.grid(row=1, column=1, columnspan=3,padx=5, pady=2,sticky=E+W) # project path frame - self.labPath = Label(self, text="projectPath:") + self.labPath = Label(self, text="Project Path:") self.editPath = Entry(self) self.btnPath = Button(self, text="...", width = 6, command = self.pathCallback) self.labPath.grid(row=2, column=0,sticky=W, pady=4, padx=5) @@ -144,12 +144,12 @@ class TkCocosDialog(Frame): self.btnPath.grid(row=2, column=4,) # language frame - self.labLanguage = Label(self, text="language:") + self.labLanguage = Label(self, text="Language:") self.var=IntVar() self.var.set(1) - self.checkcpp = Radiobutton(self, text="cpp", variable=self.var, value=1) - self.checklua = Radiobutton(self, text="lua", variable=self.var, value=2) - self.checkjs = Radiobutton(self, text="javascript", variable=self.var, value=3) + self.checkcpp = Radiobutton(self, text="C++", variable=self.var, value=1) + self.checklua = Radiobutton(self, text="Lua", variable=self.var, value=2) + self.checkjs = Radiobutton(self, text="JavaScript", variable=self.var, value=3) self.labLanguage.grid(row=3, column=0,sticky=W, padx=5) self.checkcpp.grid(row=3, column=1,sticky=N+W) self.checklua.grid(row=3, column=2,padx=5,sticky=N+W) @@ -164,7 +164,7 @@ class TkCocosDialog(Frame): self.text=Text(self,background = '#d9efff') self.text.bind("", lambda e : "break") self.text.grid(row=5, column=0, columnspan=4, rowspan=1, padx=5, sticky=E+W+S+N) - + self.text.config(state=DISABLED) # new project button self.btnCreate = Button(self, text="create", command = self.createBtnCallback) self.btnCreate.grid(row=7, column=3, columnspan=1, rowspan=1,pady=2,ipadx=15,ipady =10, sticky=W) @@ -176,7 +176,7 @@ class TkCocosDialog(Frame): scnHeight = self.parent.winfo_screenheight() tmpcnf = '%dx%d+%d+%d'%(curWidth, curHeight, int((scnWidth-curWidth)/2), int((scnHeight-curHeight)/2)) self.parent.geometry(tmpcnf) - self.parent.title("CocosCreateProject") + self.parent.title("Cocos Project Creator") #fix size #self.parent.maxsize(curWidth, curHeight) From 37522c61c39567bf3920c6fa2e5f270363626a96 Mon Sep 17 00:00:00 2001 From: Nite Luo Date: Mon, 13 Jan 2014 11:54:33 -0800 Subject: [PATCH 063/193] Make the ui look a bit better --- tools/project-creator/module/ui.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tools/project-creator/module/ui.py b/tools/project-creator/module/ui.py index e7646e1cef..98d261cbf0 100644 --- a/tools/project-creator/module/ui.py +++ b/tools/project-creator/module/ui.py @@ -125,7 +125,7 @@ class TkCocosDialog(Frame): self.strName.set("MyGame") self.editName = Entry(self, textvariable=self.strName) self.labName.grid(sticky=W, pady=4, padx=5) - self.editName.grid(row=0, column=1, columnspan=3,padx=5, pady=2,sticky=E+W) + self.editName.grid(row=0, column=1, columnspan=4,padx=5, pady=2,sticky=E+W) # package name frame self.labPackage = Label(self, text="Package Name:") @@ -133,7 +133,7 @@ class TkCocosDialog(Frame): self.strPackage.set("com.MyCompany.AwesomeGame") self.editPackage = Entry(self, textvariable=self.strPackage) self.labPackage.grid(row=1, column=0,sticky=W, padx=5) - self.editPackage.grid(row=1, column=1, columnspan=3,padx=5, pady=2,sticky=E+W) + self.editPackage.grid(row=1, column=1, columnspan=4,padx=5, pady=2,sticky=E+W) # project path frame self.labPath = Label(self, text="Project Path:") @@ -158,13 +158,13 @@ class TkCocosDialog(Frame): # show progress self.progress = Scale(self, state= DISABLED, from_=0, to=100, orient=HORIZONTAL) self.progress.set(0) - self.progress.grid(row=4, column=0, columnspan=4,padx=5, pady=2,sticky=E+W+S+N) + self.progress.grid(row=4, column=0, columnspan=5,padx=5, pady=2,sticky=E+W+S+N) # msg text frame self.text=Text(self,background = '#d9efff') self.text.bind("", lambda e : "break") - self.text.grid(row=5, column=0, columnspan=4, rowspan=1, padx=5, sticky=E+W+S+N) - self.text.config(state=DISABLED) + self.text.grid(row=5, column=0, columnspan=5, rowspan=1, padx=5, sticky=E+W+S+N) + # new project button self.btnCreate = Button(self, text="create", command = self.createBtnCallback) self.btnCreate.grid(row=7, column=3, columnspan=1, rowspan=1,pady=2,ipadx=15,ipady =10, sticky=W) From f2c3d2f3aecdab193b78e07d7e2adfb262444313 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 13 Jan 2014 12:52:07 -0800 Subject: [PATCH 064/193] Camera and Node fixes OrbitCamera: added getters (public). Setters moved from `protected` to `public : Improved API. Instead of using "out" parameters for getters, it returns a `kmVec3` : Setters receives `kmVec3` as well. Old API is still supported Node: `setAdditionalTransform` doesn't get `dirty` on the next frame. Instead, once the additional transform is set, in order to remove it the user needs to pass the identity matrix --- cocos/2d/CCActionCamera.cpp | 60 ++++++++----------- cocos/2d/CCActionCamera.h | 41 ++++++------- cocos/2d/CCNode.cpp | 9 ++- cocos/2d/CCNode.h | 11 ++-- .../Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp | 29 ++++----- .../Cpp/TestCpp/Classes/NodeTest/NodeTest.h | 1 - 6 files changed, 67 insertions(+), 84 deletions(-) diff --git a/cocos/2d/CCActionCamera.cpp b/cocos/2d/CCActionCamera.cpp index c044bdd21a..45560f7ede 100644 --- a/cocos/2d/CCActionCamera.cpp +++ b/cocos/2d/CCActionCamera.cpp @@ -33,6 +33,12 @@ NS_CC_BEGIN // // CameraAction // +ActionCamera::ActionCamera() +{ + kmVec3Fill(&_center, 0, 0, 0); + kmVec3Fill(&_eye, 0, 0, FLT_EPSILON); + kmVec3Fill(&_up, 0, 1, 0); +} void ActionCamera::startWithTarget(Node *target) { ActionInterval::startWithTarget(target); @@ -54,53 +60,39 @@ ActionCamera * ActionCamera::reverse() const void ActionCamera::restore() { - _eyeX = _eyeY = 0.0f; - _eyeZ = FLT_EPSILON; + kmVec3Fill(&_center, 0, 0, 0); + kmVec3Fill(&_eye, 0, 0, FLT_EPSILON); + kmVec3Fill(&_up, 0, 1, 0); +} - _centerX = _centerY = _centerZ = 0.0f; - - _upX = 0.0f; - _upY = 1.0f; - _upZ = 0.0f; +void ActionCamera::setEye(const kmVec3& eye) +{ + _eye = eye; + updateTransform(); } void ActionCamera::setEye(float x, float y, float z) { - _eyeX = x; - _eyeY = y; - _eyeZ = z; - + kmVec3Fill(&_eye, x, y, z); updateTransform(); } -void ActionCamera::setCenter(float centerX, float centerY, float centerZ) +void ActionCamera::setCenter(const kmVec3& center) { - _centerX = centerX; - _centerY = centerY; - _centerZ = centerZ; - + _center = center; updateTransform(); } -void ActionCamera::setUp(float upX, float upY, float upZ) +void ActionCamera::setUp(const kmVec3& up) { - _upX = upX; - _upY = upY; - _upZ = upZ; - + _up = up; updateTransform(); } void ActionCamera::updateTransform() { - kmVec3 eye, center, up; - - kmVec3Fill(&eye, _eyeX, _eyeY , _eyeZ); - kmVec3Fill(¢er, _centerX, _centerY, _centerZ); - kmVec3Fill(&up, _upX, _upY, _upZ); - kmMat4 lookupMatrix; - kmMat4LookAt(&lookupMatrix, &eye, ¢er, &up); + kmMat4LookAt(&lookupMatrix, &_eye, &_center, &_up); Point anchorPoint = _target->getAnchorPointInPoints(); @@ -199,9 +191,9 @@ void OrbitCamera::update(float dt) float za = _radZ + _radDeltaZ * dt; float xa = _radX + _radDeltaX * dt; - float i = sinf(za) * cosf(xa) * r + _centerX; - float j = sinf(za) * sinf(xa) * r + _centerY; - float k = cosf(za) * r + _centerZ; + float i = sinf(za) * cosf(xa) * r + _center.x; + float j = sinf(za) * sinf(xa) * r + _center.y; + float k = cosf(za) * r + _center.z; setEye(i,j,k); } @@ -211,9 +203,9 @@ void OrbitCamera::sphericalRadius(float *newRadius, float *zenith, float *azimut float r; // radius float s; - float x = _eyeX - _centerX; - float y = _eyeY - _centerY; - float z = _eyeZ - _centerZ; + float x = _eye.x - _center.x; + float y = _eye.y - _center.y; + float z = _eye.z - _center.z; r = sqrtf( powf(x,2) + powf(y,2) + powf(z,2)); s = sqrtf( powf(x,2) + powf(y,2)); diff --git a/cocos/2d/CCActionCamera.h b/cocos/2d/CCActionCamera.h index c5515dfcff..2c42590080 100644 --- a/cocos/2d/CCActionCamera.h +++ b/cocos/2d/CCActionCamera.h @@ -50,17 +50,7 @@ public: /** * @js ctor */ - ActionCamera() - :_centerX(0) - ,_centerY(0) - ,_centerZ(0) - ,_eyeX(0) - ,_eyeY(0) - ,_eyeZ(FLT_EPSILON) - ,_upX(0) - ,_upY(1) - ,_upZ(0) - {} + ActionCamera(); /** * @js NA * @lua NA @@ -72,23 +62,28 @@ public: virtual ActionCamera * reverse() const override; virtual ActionCamera *clone() const override; + /* sets the Eye value of the Camera */ + void setEye(const kmVec3 &eye); + void setEye(float x, float y, float z); + /* returns the Eye value of the Camera */ + const kmVec3& getEye() const { return _eye; } + /* sets the Center value of the Camera */ + void setCenter(const kmVec3 ¢er); + /* returns the Center value of the Camera */ + const kmVec3& getCenter() const { return _center; } + /* sets the Up value of the Camera */ + void setUp(const kmVec3 &up); + /* Returns the Up value of the Camera */ + const kmVec3& getUp() const { return _up; } + protected: void restore(); - void setEye(float x, float y, float z); - void setCenter(float x, float y, float z); - void setUp(float x, float y, float z); void updateTransform(); - float _centerX; - float _centerY; - float _centerZ; - float _eyeX; - float _eyeY; - float _eyeZ; - float _upX; - float _upY; - float _upZ; + kmVec3 _center; + kmVec3 _eye; + kmVec3 _up; }; /** diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 6e38937d19..3b7ce1c47c 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -103,7 +103,7 @@ Node::Node(void) , _anchorPointInPoints(Point::ZERO) , _anchorPoint(Point::ZERO) , _contentSize(Size::ZERO) -, _additionalTransformDirty(false) +, _useAdditionalTransform(false) , _transformDirty(true) , _inverseDirty(true) // children (lazy allocs) @@ -1189,10 +1189,9 @@ const kmMat4& Node::getNodeToParentTransform() const // vertex Z _transform.mat[14] = _vertexZ; - if (_additionalTransformDirty) + if (_useAdditionalTransform) { kmMat4Multiply(&_transform, &_transform, &_additionalTransform); - _additionalTransformDirty = false; } _transformDirty = false; @@ -1211,14 +1210,14 @@ void Node::setAdditionalTransform(const AffineTransform& additionalTransform) { CGAffineToGL(additionalTransform, _additionalTransform.mat); _transformDirty = true; - _additionalTransformDirty = true; + _useAdditionalTransform = true; } void Node::setAdditionalTransform(const kmMat4& additionalTransform) { _additionalTransform = additionalTransform; _transformDirty = true; - _additionalTransformDirty = true; + _useAdditionalTransform = true; } diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 09da015dd6..3069fb0a84 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -1266,7 +1266,9 @@ public: Point convertTouchToNodeSpaceAR(Touch * touch) const; /** - * Sets the additional transform. + * Sets an additional transform matrix to the node. + * + * In order to remove it, set the Identity Matrix to the additional transform. * * @note The additional transform will be concatenated at the end of getNodeToParentTransform. * It could be used to simulate `parent-child` relationship between two nodes (e.g. one is in BatchNode, another isn't). @@ -1289,7 +1291,7 @@ public: spriteA->setPosition(Point(200, 200)); // Gets the spriteA's transform. - AffineTransform t = spriteA->getNodeToParentTransform(); + auto t = spriteA->getNodeToParentTransform(); // Sets the additional transform to spriteB, spriteB's postion will based on its pseudo parent i.e. spriteA. spriteB->setAdditionalTransform(t); @@ -1421,12 +1423,13 @@ protected: Size _contentSize; ///< untransformed size of the node + kmMat4 _modelViewTransform; ///< ModelView transform of the Node. + // "cache" variables are allowed to be mutable mutable kmMat4 _additionalTransform; ///< transform mutable kmMat4 _transform; ///< transform mutable kmMat4 _inverse; ///< inverse transform - kmMat4 _modelViewTransform; ///< ModelView transform of the Node. - mutable bool _additionalTransformDirty; ///< The flag to check whether the additional transform is dirty + bool _useAdditionalTransform; ///< The flag to check whether the additional transform is dirty mutable bool _transformDirty; ///< transform dirty flag mutable bool _inverseDirty; ///< inverse transform dirty flag diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp index 843b72bbb6..aefe6a83e4 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp @@ -1021,7 +1021,18 @@ CameraTest2::CameraTest2() _sprite2->setPosition( Point(3*s.width/4, s.height/2) ); _sprite2->setScale(0.5); - scheduleUpdate(); + kmVec3 eye, center, up; + + kmVec3Fill(&eye, 150, 0, 200); + kmVec3Fill(¢er, 0, 0, 0); + kmVec3Fill(&up, 0, 1, 0); + + kmMat4 lookupMatrix; + kmMat4LookAt(&lookupMatrix, &eye, ¢er, &up); + + _sprite1->setAdditionalTransform(lookupMatrix); + _sprite2->setAdditionalTransform(lookupMatrix); + } std::string CameraTest2::title() const @@ -1034,22 +1045,6 @@ std::string CameraTest2::subtitle() const return "Both images should look the same"; } -void CameraTest2::update(float dt) -{ - kmVec3 eye, center, up; - - kmVec3Fill(&eye, 150, 0, 200); - kmVec3Fill(¢er, 0, 0, 0); - kmVec3Fill(&up, 0, 1, 0); - - - kmMat4 lookupMatrix; - kmMat4LookAt(&lookupMatrix, &eye, ¢er, &up); - - _sprite1->setAdditionalTransform(lookupMatrix); - _sprite2->setAdditionalTransform(lookupMatrix); -} - /// /// main /// diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h index 7a6a63d7c2..157d029a49 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h @@ -184,7 +184,6 @@ public: virtual void onExit() override; protected: - virtual void update(float dt) override; CameraTest2(); Sprite *_sprite1; From 6eed3a2b27dda1d541db4f600a31de3c023b8fe5 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Mon, 13 Jan 2014 14:48:12 -0800 Subject: [PATCH 065/193] Adds missing copyright headers in some files --- cocos/2d/CCDirector.cpp | 58 +++++++++---------- .../ActionsEaseTest/ActionsEaseTest.cpp | 25 ++++++++ .../Classes/ActionsEaseTest/ActionsEaseTest.h | 25 ++++++++ .../ActionsProgressTest.cpp | 25 ++++++++ .../ActionsProgressTest/ActionsProgressTest.h | 25 ++++++++ .../Classes/ActionsTest/ActionsTest.cpp | 25 ++++++++ .../TestCpp/Classes/ActionsTest/ActionsTest.h | 25 ++++++++ .../Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp | 25 ++++++++ .../Cpp/TestCpp/Classes/MenuTest/MenuTest.h | 25 ++++++++ .../Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp | 25 ++++++++ .../Cpp/TestCpp/Classes/NodeTest/NodeTest.h | 25 ++++++++ .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- .../Classes/Texture2dTest/Texture2dTest.cpp | 25 ++++++++ .../Classes/Texture2dTest/Texture2dTest.h | 25 ++++++++ .../TransitionsTest/TransitionsTest.cpp | 25 ++++++++ .../Classes/TransitionsTest/TransitionsTest.h | 25 ++++++++ 16 files changed, 380 insertions(+), 30 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index a0c42973e2..d3c53b6f3e 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -129,16 +129,16 @@ bool Director::init(void) // paused ? _paused = false; - + // purge ? _purgeDirectorInNextLoop = false; - _winSizeInPoints = Size::ZERO; + _winSizeInPoints = Size::ZERO; _openGLView = nullptr; - + _cullingFrustum = new Frustum(); - + _contentScaleFactor = 1.0f; // scheduler @@ -169,7 +169,7 @@ bool Director::init(void) return true; } - + Director::~Director(void) { CCLOGINFO("deallocing Director: %p", this); @@ -177,7 +177,7 @@ Director::~Director(void) CC_SAFE_RELEASE(_FPSLabel); CC_SAFE_RELEASE(_SPFLabel); CC_SAFE_RELEASE(_drawsLabel); - + CC_SAFE_RELEASE(_runningScene); CC_SAFE_RELEASE(_notificationNode); CC_SAFE_RELEASE(_scheduler); @@ -283,17 +283,17 @@ void Director::drawScene() } kmGLPushMatrix(); - + //construct the frustum { kmMat4 view; kmMat4 projection; kmGLGetMatrix(KM_GL_PROJECTION, &projection); kmGLGetMatrix(KM_GL_MODELVIEW, &view); - + _cullingFrustum->setupFromMatrix(view, projection); } - + // draw the scene if (_runningScene) { @@ -306,7 +306,7 @@ void Director::drawScene() { _notificationNode->visit(); } - + if (_displayStats) { showStats(); @@ -324,7 +324,7 @@ void Director::drawScene() { _openGLView->swapBuffers(); } - + if (_displayStats) { calculateMPF(); @@ -385,16 +385,16 @@ void Director::setOpenGLView(EGLView *openGLView) // set size _winSizeInPoints = _openGLView->getDesignResolutionSize(); - + createStatsLabel(); - + if (_openGLView) { setGLDefaultValues(); - } - + } + _renderer->initGLView(); - + CHECK_GL_ERROR_DEBUG(); // _touchDispatcher->setDispatchEvents(true); @@ -480,12 +480,12 @@ void Director::setProjection(Projection projection) kmGLMultMatrix(&matrixLookup); break; } - + case Projection::CUSTOM: // Projection Delegate is no longer needed // since the event "PROJECTION CHANGED" is emitted break; - + default: CCLOG("cocos2d: Director: unrecognized projection"); break; @@ -547,10 +547,10 @@ static void GLToClipTransform(kmMat4 *transformOut) { kmMat4 projection; kmGLGetMatrix(KM_GL_PROJECTION, &projection); - + kmMat4 modelview; kmGLGetMatrix(KM_GL_MODELVIEW, &modelview); - + kmMat4Multiply(transformOut, &projection, &modelview); } @@ -558,19 +558,19 @@ Point Director::convertToGL(const Point& uiPoint) { kmMat4 transform; GLToClipTransform(&transform); - + kmMat4 transformInv; kmMat4Inverse(&transformInv, &transform); - + // Calculate z=0 using -> transform*[0, 0, 0, 1]/w kmScalar zClip = transform.mat[14]/transform.mat[15]; - + Size glSize = _openGLView->getDesignResolutionSize(); kmVec3 clipCoord = {2.0f*uiPoint.x/glSize.width - 1.0f, 1.0f - 2.0f*uiPoint.y/glSize.height, zClip}; - + kmVec3 glCoord; kmVec3TransformCoord(&glCoord, &clipCoord, &transformInv); - + return Point(glCoord.x, glCoord.y); } @@ -578,12 +578,12 @@ Point Director::convertToUI(const Point& glPoint) { kmMat4 transform; GLToClipTransform(&transform); - + kmVec3 clipCoord; // Need to calculate the zero depth from the transform. kmVec3 glCoord = {glPoint.x, glPoint.y, 0.0}; kmVec3TransformCoord(&clipCoord, &glCoord, &transform); - + Size glSize = _openGLView->getDesignResolutionSize(); return Point(glSize.width*(clipCoord.x*0.5 + 0.5), glSize.height*(-clipCoord.y*0.5 + 0.5)); } @@ -604,7 +604,7 @@ Size Director::getVisibleSize() const { return _openGLView->getVisibleSize(); } - else + else { return Size::ZERO; } @@ -616,7 +616,7 @@ Point Director::getVisibleOrigin() const { return _openGLView->getVisibleOrigin(); } - else + else { return Point::ZERO; } diff --git a/samples/Cpp/TestCpp/Classes/ActionsEaseTest/ActionsEaseTest.cpp b/samples/Cpp/TestCpp/Classes/ActionsEaseTest/ActionsEaseTest.cpp index 3cf942b540..c05bb831cd 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsEaseTest/ActionsEaseTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ActionsEaseTest/ActionsEaseTest.cpp @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #include "ActionsEaseTest.h" #include "../testResource.h" diff --git a/samples/Cpp/TestCpp/Classes/ActionsEaseTest/ActionsEaseTest.h b/samples/Cpp/TestCpp/Classes/ActionsEaseTest/ActionsEaseTest.h index 7751439668..443c532f32 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsEaseTest/ActionsEaseTest.h +++ b/samples/Cpp/TestCpp/Classes/ActionsEaseTest/ActionsEaseTest.h @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #ifndef _ACTIONS__EASE_TEST_H_ #define _ACTIONS__EASE_TEST_H_ diff --git a/samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.cpp b/samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.cpp index e6c552db69..42f3774e3b 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.cpp @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #include "ActionsProgressTest.h" #include "../testResource.h" diff --git a/samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.h b/samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.h index 1d63fea276..9e16818164 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.h +++ b/samples/Cpp/TestCpp/Classes/ActionsProgressTest/ActionsProgressTest.h @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #ifndef _ACTIONS__PROGRESS_TEST_H_ #define _ACTIONS_PROGRESS_TEST_H_ diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp index 229d6f11e6..fa40b74f0a 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #include "ActionsTest.h" #include "../testResource.h" #include "cocos2d.h" diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h index b5be2b348b..949ad43a38 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h +++ b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.h @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #ifndef _ActionsTest_H_ #define _ActionsTest_H_ diff --git a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp index e91fcdb3f6..f4da9b94c8 100644 --- a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp +++ b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.cpp @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #include "MenuTest.h" #include "../testResource.h" diff --git a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h index db6e0a918d..1910968546 100644 --- a/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h +++ b/samples/Cpp/TestCpp/Classes/MenuTest/MenuTest.h @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #ifndef _MENU_TEST_H_ #define _MENU_TEST_H_ diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp index aefe6a83e4..4d69c14542 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #include "NodeTest.h" #include "../testResource.h" diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h index 157d029a49..2207c65f7c 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #ifndef _NODE_TEST_H_ #define _NODE_TEST_H_ diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index d3578f7962..8f885e907c 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -e14a3c9f23fccd862ac2ffcba41ee7094ab54981 \ No newline at end of file +689b357d7acda141d13a3dfc4cb52aabb274f6cd \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp index 7a096c25cb..95bcb47323 100644 --- a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp +++ b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + // local import #include "Texture2dTest.h" #include "../testResource.h" diff --git a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.h b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.h index cafc812e77..c331e0d254 100644 --- a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.h +++ b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.h @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #ifndef __TEXTURE2D_TEST_H__ #define __TEXTURE2D_TEST_H__ diff --git a/samples/Cpp/TestCpp/Classes/TransitionsTest/TransitionsTest.cpp b/samples/Cpp/TestCpp/Classes/TransitionsTest/TransitionsTest.cpp index 728901b809..7c71d0799e 100644 --- a/samples/Cpp/TestCpp/Classes/TransitionsTest/TransitionsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TransitionsTest/TransitionsTest.cpp @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #include "TransitionsTest.h" #include "../testResource.h" #include "CCConfiguration.h" diff --git a/samples/Cpp/TestCpp/Classes/TransitionsTest/TransitionsTest.h b/samples/Cpp/TestCpp/Classes/TransitionsTest/TransitionsTest.h index ccf7ba3100..c923409816 100644 --- a/samples/Cpp/TestCpp/Classes/TransitionsTest/TransitionsTest.h +++ b/samples/Cpp/TestCpp/Classes/TransitionsTest/TransitionsTest.h @@ -1,3 +1,28 @@ +/**************************************************************************** + Copyright (c) 2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #ifndef _TRANSITIONS_TEST_H_ #define _TRANSITIONS_TEST_H_ From c49aa1f12504e7cb92397a9af217ae9fc84d2a44 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Mon, 13 Jan 2014 23:07:44 +0000 Subject: [PATCH 066/193] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 74e535d0bd..f41186e7ef 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 74e535d0bd9cb4fd53244c46e2011e56367624a4 +Subproject commit f41186e7ef4209597d8c81952c3535b02305a79c From a1d8e8bdb1b7acd0c1ebd346db7d4783b31bb24e Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 14 Jan 2014 12:28:24 +0800 Subject: [PATCH 067/193] fix compiling error cause by macro define on window platform. --- cocos/2d/CCTMXTiledMap.cpp | 2 ++ cocos/2d/renderer/CCFrustum.cpp | 18 +++++++++--------- cocos/base/CCConsole.cpp | 9 ++++++--- cocos/base/CCGeometry.cpp | 2 ++ cocos/network/WebSocket.cpp | 2 ++ .../PerformanceTest/PerformanceLabelTest.cpp | 3 +++ .../PerformanceTest/PerformanceSpriteTest.cpp | 3 +++ .../Classes/TileMapTest/TileMapTest.cpp | 3 +++ 8 files changed, 30 insertions(+), 12 deletions(-) diff --git a/cocos/2d/CCTMXTiledMap.cpp b/cocos/2d/CCTMXTiledMap.cpp index 33a4b77519..2a85788b53 100644 --- a/cocos/2d/CCTMXTiledMap.cpp +++ b/cocos/2d/CCTMXTiledMap.cpp @@ -30,6 +30,8 @@ THE SOFTWARE. #include "CCSprite.h" #include +#undef min +#undef max NS_CC_BEGIN // implementation TMXTiledMap diff --git a/cocos/2d/renderer/CCFrustum.cpp b/cocos/2d/renderer/CCFrustum.cpp index cc26b67cab..e02236e3b0 100644 --- a/cocos/2d/renderer/CCFrustum.cpp +++ b/cocos/2d/renderer/CCFrustum.cpp @@ -173,7 +173,7 @@ Frustum::~Frustum() { } -void Frustum::setupProjectionOrthogonal(const cocos2d::ViewTransform &view, float width, float height, float near, float far) +void Frustum::setupProjectionOrthogonal(const cocos2d::ViewTransform &view, float width, float height, float nearPlane, float farPlane) { kmVec3 cc = view.getPosition(); kmVec3 cDir = view.getDirection(); @@ -189,7 +189,7 @@ void Frustum::setupProjectionOrthogonal(const cocos2d::ViewTransform &view, floa kmVec3 point; kmVec3 normal; normal = cDir; - kmVec3Scale(&point, &cDir, near); + kmVec3Scale(&point, &cDir, nearPlane); kmVec3Add(&point, &point, &cc); kmPlaneFromPointNormal(&_frustumPlanes[FrustumPlane::FRUSTUM_NEAR], &point, &normal); } @@ -199,7 +199,7 @@ void Frustum::setupProjectionOrthogonal(const cocos2d::ViewTransform &view, floa kmVec3 point; kmVec3 normal; kmVec3Scale(&normal, &cDir, -1); - kmVec3Scale(&point, &cDir, far); + kmVec3Scale(&point, &cDir, farPlane); kmVec3Add(&point, &point, &cc); kmPlaneFromPointNormal(&_frustumPlanes[FrustumPlane::FRUSTUM_FAR], &point, &normal); } @@ -245,7 +245,7 @@ void Frustum::setupProjectionOrthogonal(const cocos2d::ViewTransform &view, floa } } -void Frustum::setupProjectionPerspective(const ViewTransform& view, float left, float right, float top, float bottom, float near, float far) +void Frustum::setupProjectionPerspective(const ViewTransform& view, float left, float right, float top, float bottom, float nearPlane, float farPlane) { kmVec3 cc = view.getPosition(); kmVec3 cDir = view.getDirection(); @@ -259,10 +259,10 @@ void Frustum::setupProjectionPerspective(const ViewTransform& view, float left, kmVec3 nearCenter; kmVec3 farCenter; - kmVec3Scale(&nearCenter, &cDir, near); + kmVec3Scale(&nearCenter, &cDir, nearPlane); kmVec3Add(&nearCenter, &nearCenter, &cc); - kmVec3Scale(&farCenter, &cDir, far); + kmVec3Scale(&farCenter, &cDir, farPlane); kmVec3Add(&farCenter, &farCenter, &cc); //near @@ -335,11 +335,11 @@ void Frustum::setupProjectionPerspective(const ViewTransform& view, float left, } -void Frustum::setupProjectionPerspectiveFov(const ViewTransform& view, float fov, float ratio, float near, float far) +void Frustum::setupProjectionPerspectiveFov(const ViewTransform& view, float fov, float ratio, float nearPlane, float farPlane) { - float width = 2 * near * tan(fov * 0.5); + float width = 2 * nearPlane * tan(fov * 0.5); float height = width/ratio; - setupProjectionPerspective(view, -width/2, width/2, height/2, -height/2, near, far); + setupProjectionPerspective(view, -width/2, width/2, height/2, -height/2, nearPlane, farPlane); } void Frustum::setupFromMatrix(const kmMat4 &view, const kmMat4 &projection) diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 58636d15cf..7505ab585e 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -51,6 +51,9 @@ #include "CCScene.h" #include "CCPlatformConfig.h" +#undef min +#undef max + NS_CC_BEGIN @@ -143,12 +146,12 @@ void log(const char *format, va_list args) #elif CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 WCHAR wszBuf[MAX_LOG_LENGTH] = {0}; - MultiByteToWideChar(CP_UTF8, 0, szBuf, -1, wszBuf, sizeof(wszBuf)); + MultiByteToWideChar(CP_UTF8, 0, buf, -1, wszBuf, sizeof(wszBuf)); OutputDebugStringW(wszBuf); OutputDebugStringA("\n"); - WideCharToMultiByte(CP_ACP, 0, wszBuf, sizeof(wszBuf), szBuf, sizeof(szBuf), NULL, FALSE); - printf("%s\n", szBuf); + WideCharToMultiByte(CP_ACP, 0, wszBuf, sizeof(wszBuf), buf, sizeof(buf), NULL, FALSE); + printf("%s\n", buf); #else // Linux, Mac, iOS, etc diff --git a/cocos/base/CCGeometry.cpp b/cocos/base/CCGeometry.cpp index 4be119ff6b..968ff8e0ba 100644 --- a/cocos/base/CCGeometry.cpp +++ b/cocos/base/CCGeometry.cpp @@ -27,6 +27,8 @@ THE SOFTWARE. #include "ccMacros.h" #include +#undef min +#undef max // implementation of Point NS_CC_BEGIN diff --git a/cocos/network/WebSocket.cpp b/cocos/network/WebSocket.cpp index 5e17487567..01432c033e 100644 --- a/cocos/network/WebSocket.cpp +++ b/cocos/network/WebSocket.cpp @@ -39,6 +39,8 @@ #define WS_WRITE_BUFFER_SIZE 2048 +#undef min +#undef max NS_CC_BEGIN namespace network { diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp index 317bbb8a60..3efe4d3993 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp @@ -1,5 +1,8 @@ #include "PerformanceLabelTest.h" +#undef min +#undef max + enum { kMaxNodes = 200, kNodesIncrease = 10, diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp index a9e6f78c94..e1b150278f 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp @@ -1,5 +1,8 @@ #include "PerformanceSpriteTest.h" +#undef min +#undef max + enum { kMaxNodes = 50000, kNodesIncrease = 250, diff --git a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp index 75f0fd6eee..fcde928c1e 100644 --- a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp @@ -3,6 +3,9 @@ #include "renderer/CCRenderer.h" #include "renderer/CCCustomCommand.h" +#undef min +#undef max + enum { kTagTileMap = 1, From 83a42dc760739b01ca679150e367d39ea9c5a8d5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 14 Jan 2014 13:59:00 +0800 Subject: [PATCH 068/193] closed #3698: Wrong display when dragging window through retina and non-retina screen. --- cocos/2d/platform/mac/CCEGLView.h | 6 +- cocos/2d/platform/mac/CCEGLView.mm | 107 +++++++++++++++++++---------- 2 files changed, 76 insertions(+), 37 deletions(-) diff --git a/cocos/2d/platform/mac/CCEGLView.h b/cocos/2d/platform/mac/CCEGLView.h index 6b7495f5d0..5b72a9b66f 100644 --- a/cocos/2d/platform/mac/CCEGLView.h +++ b/cocos/2d/platform/mac/CCEGLView.h @@ -74,6 +74,9 @@ public: /** @deprecated Use getInstance() instead */ CC_DEPRECATED_ATTRIBUTE static EGLView* sharedOpenGLView(); + + inline bool isRetina() { return _isRetina; }; + protected: /* * Set zoom factor for frame. This method is for debugging big resolution (e.g.new ipad) app on desktop. @@ -82,8 +85,8 @@ protected: private: bool _captured; bool _supportTouch; + bool _isRetina; - int _frameBufferSize[2]; float _frameZoomFactor; static EGLView* s_pEglView; public: @@ -93,6 +96,7 @@ public: GLFWwindow* getWindow() const { return _mainWindow; } private: GLFWwindow* _mainWindow; + friend class EGLViewEventHandler; }; NS_CC_END // end of namespace cocos2d diff --git a/cocos/2d/platform/mac/CCEGLView.mm b/cocos/2d/platform/mac/CCEGLView.mm index afd9c66b92..cad82ee6c1 100644 --- a/cocos/2d/platform/mac/CCEGLView.mm +++ b/cocos/2d/platform/mac/CCEGLView.mm @@ -178,25 +178,26 @@ public: static float s_mouseX; static float s_mouseY; - static void OnGLFWError(int errorID, const char* errorDesc); - static void OnGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify); - static void OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y); - static void OnGLFWMouseScrollCallback(GLFWwindow* window, double x, double y); - static void OnGLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); - static void OnGLFWCharCallback(GLFWwindow* window, unsigned int character); - static void OnGLFWWindowPosCallback(GLFWwindow* windows, int x, int y); + static void onGLFWError(int errorID, const char* errorDesc); + static void onGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify); + static void onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y); + static void onGLFWMouseScrollCallback(GLFWwindow* window, double x, double y); + static void onGLFWKeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); + static void onGLFWCharCallback(GLFWwindow* window, unsigned int character); + static void onGLFWWindowPosCallback(GLFWwindow* windows, int x, int y); + static void onGLFWframebuffersize(GLFWwindow* window, int w, int h); }; bool EGLViewEventHandler::s_captured = false; float EGLViewEventHandler::s_mouseX = 0; float EGLViewEventHandler::s_mouseY = 0; -void EGLViewEventHandler::OnGLFWError(int errorID, const char* errorDesc) +void EGLViewEventHandler::onGLFWError(int errorID, const char* errorDesc) { CCLOGERROR("GLFWError #%d Happen, %s\n", errorID, errorDesc); } -void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify) +void EGLViewEventHandler::onGLFWMouseCallBack(GLFWwindow* window, int button, int action, int modify) { EGLView* eglView = EGLView::getInstance(); if(nullptr == eglView) return; @@ -240,10 +241,16 @@ void EGLViewEventHandler::OnGLFWMouseCallBack(GLFWwindow* window, int button, in } } -void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y) +void EGLViewEventHandler::onGLFWMouseMoveCallBack(GLFWwindow* window, double x, double y) { EGLView* eglView = EGLView::getInstance(); if(nullptr == eglView) return; + + if (eglView->isRetina()) { + x *= 2; + y *= 2; + } + s_mouseX = (float)x; s_mouseY = (float)y; @@ -265,7 +272,7 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x, Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); } -void EGLViewEventHandler::OnGLFWMouseScrollCallback(GLFWwindow* window, double x, double y) +void EGLViewEventHandler::onGLFWMouseScrollCallback(GLFWwindow* window, double x, double y) { EGLView* eglView = EGLView::getInstance(); if(nullptr == eglView) return; @@ -277,7 +284,7 @@ void EGLViewEventHandler::OnGLFWMouseScrollCallback(GLFWwindow* window, double x Director::getInstance()->getEventDispatcher()->dispatchEvent(&event); } -void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) +void EGLViewEventHandler::onGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) { if (GLFW_REPEAT != action) { @@ -287,19 +294,40 @@ void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int sca } } -void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character) +void EGLViewEventHandler::onGLFWCharCallback(GLFWwindow *window, unsigned int character) { IMEDispatcher::sharedDispatcher()->dispatchInsertText((const char*) &character, 1); } -void EGLViewEventHandler::OnGLFWWindowPosCallback(GLFWwindow *windows, int x, int y) +void EGLViewEventHandler::onGLFWWindowPosCallback(GLFWwindow *windows, int x, int y) { - if(Director::getInstance()) + Director::getInstance()->setViewport(); +} + +void EGLViewEventHandler::onGLFWframebuffersize(GLFWwindow* window, int w, int h) +{ + auto view = EGLView::getInstance(); + + float frameSizeW = view->getFrameSize().width; + float frameSizeH = view->getFrameSize().height; + float factorX = frameSizeW / w * view->getFrameZoomFactor(); + float factorY = frameSizeH / h * view->getFrameZoomFactor();; + + if (fabs(factorX - 0.5f) < FLT_MIN && fabs(factorY - 0.5f) < FLT_MIN ) { - Director::getInstance()->setViewport(); + view->_isRetina = true; + view->setFrameZoomFactor(2.0f * view->getFrameZoomFactor()); + glfwSetWindowSize(window, static_cast(frameSizeW * 0.5f * view->getFrameZoomFactor()) , static_cast(frameSizeH * 0.5f * view->getFrameZoomFactor())); + } + else if(fabs(factorX - 2.0f) < FLT_MIN && fabs(factorY - 2.0f) < FLT_MIN) + { + view->_isRetina = false; + view->setFrameZoomFactor(0.5f * view->getFrameZoomFactor()); + glfwSetWindowSize(window, static_cast(frameSizeW * view->getFrameZoomFactor()), static_cast(frameSizeH * view->getFrameZoomFactor())); } } + //end EGLViewEventHandler @@ -313,12 +341,13 @@ EGLView::EGLView() : _captured(false) , _frameZoomFactor(1.0f) , _supportTouch(false) +, _isRetina(false) , _mainWindow(nullptr) { CCASSERT(nullptr == s_pEglView, "EGLView is singleton, Should be inited only one time\n"); _viewName = "cocos2dx"; s_pEglView = this; - glfwSetErrorCallback(EGLViewEventHandler::OnGLFWError); + glfwSetErrorCallback(EGLViewEventHandler::onGLFWError); glfwInit(); } @@ -341,15 +370,25 @@ bool EGLView::init(const std::string& viewName, float width, float height, float _mainWindow = glfwCreateWindow(_screenSize.width * _frameZoomFactor, _screenSize.height * _frameZoomFactor, _viewName.c_str(), nullptr, nullptr); glfwMakeContextCurrent(_mainWindow); - glfwGetFramebufferSize(_mainWindow, &_frameBufferSize[0], &_frameBufferSize[1]); + int w, h; + glfwGetWindowSize(_mainWindow, &w, &h); + int frameBufferW, frameBufferH; + glfwGetFramebufferSize(_mainWindow, &frameBufferW, &frameBufferH); - glfwSetMouseButtonCallback(_mainWindow,EGLViewEventHandler::OnGLFWMouseCallBack); - glfwSetCursorPosCallback(_mainWindow,EGLViewEventHandler::OnGLFWMouseMoveCallBack); - glfwSetScrollCallback(_mainWindow, EGLViewEventHandler::OnGLFWMouseScrollCallback); - glfwSetCharCallback(_mainWindow, EGLViewEventHandler::OnGLFWCharCallback); - glfwSetKeyCallback(_mainWindow, EGLViewEventHandler::OnGLFWKeyCallback); - glfwSetWindowPosCallback(_mainWindow, EGLViewEventHandler::OnGLFWWindowPosCallback); + if (frameBufferW == 2 * w && frameBufferH == 2 * h) + { + _isRetina = true; + setFrameZoomFactor(frameZoomFactor * 2); + glfwSetWindowSize(_mainWindow, width/2 * _frameZoomFactor, height/2 * _frameZoomFactor); + } + glfwSetMouseButtonCallback(_mainWindow,EGLViewEventHandler::onGLFWMouseCallBack); + glfwSetCursorPosCallback(_mainWindow,EGLViewEventHandler::onGLFWMouseMoveCallBack); + glfwSetScrollCallback(_mainWindow, EGLViewEventHandler::onGLFWMouseScrollCallback); + glfwSetCharCallback(_mainWindow, EGLViewEventHandler::onGLFWCharCallback); + glfwSetKeyCallback(_mainWindow, EGLViewEventHandler::onGLFWKeyCallback); + glfwSetWindowPosCallback(_mainWindow, EGLViewEventHandler::onGLFWWindowPosCallback); + glfwSetFramebufferSizeCallback(_mainWindow, EGLViewEventHandler::onGLFWframebuffersize); // check OpenGL version at first const GLubyte* glVersion = glGetString(GL_VERSION); @@ -453,22 +492,18 @@ void EGLView::setFrameSize(float width, float height) void EGLView::setViewPortInPoints(float x , float y , float w , float h) { - float frameZoomFactorX = _frameBufferSize[0]/_screenSize.width; - float frameZoomFactorY = _frameBufferSize[1]/_screenSize.height; - glViewport((GLint)(x * _scaleX * frameZoomFactorX + _viewPortRect.origin.x * frameZoomFactorX), - (GLint)(y * _scaleY * frameZoomFactorY + _viewPortRect.origin.y * frameZoomFactorY), - (GLsizei)(w * _scaleX * frameZoomFactorX), - (GLsizei)(h * _scaleY * frameZoomFactorY)); + glViewport((GLint)(x * _scaleX * _frameZoomFactor + _viewPortRect.origin.x * _frameZoomFactor), + (GLint)(y * _scaleY * _frameZoomFactor + _viewPortRect.origin.y * _frameZoomFactor), + (GLsizei)(w * _scaleX * _frameZoomFactor), + (GLsizei)(h * _scaleY * _frameZoomFactor)); } void EGLView::setScissorInPoints(float x , float y , float w , float h) { - float frameZoomFactorX = _frameBufferSize[0]/_screenSize.width; - float frameZoomFactorY = _frameBufferSize[1]/_screenSize.height; - glScissor((GLint)(x * _scaleX * frameZoomFactorX + _viewPortRect.origin.x * frameZoomFactorX), - (GLint)(y * _scaleY * frameZoomFactorY + _viewPortRect.origin.y * frameZoomFactorY), - (GLsizei)(w * _scaleX * frameZoomFactorX), - (GLsizei)(h * _scaleY * frameZoomFactorY)); + glScissor((GLint)(x * _scaleX * _frameZoomFactor + _viewPortRect.origin.x * _frameZoomFactor), + (GLint)(y * _scaleY * _frameZoomFactor + _viewPortRect.origin.y * _frameZoomFactor), + (GLsizei)(w * _scaleX * _frameZoomFactor), + (GLsizei)(h * _scaleY * _frameZoomFactor)); } EGLView* EGLView::getInstance() From 92d345156b093a12f5f8812ec6e215ee3f2fdc69 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 14 Jan 2014 14:20:22 +0800 Subject: [PATCH 069/193] un-define clash with the existing macro definition in platform/win32/CCStdC.h --- cocos/2d/CCTMXTiledMap.cpp | 2 -- cocos/2d/platform/win32/CCStdC.h | 3 +++ cocos/base/CCConsole.cpp | 3 --- cocos/base/CCGeometry.cpp | 2 -- cocos/network/WebSocket.cpp | 2 -- .../TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp | 3 --- .../TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp | 3 --- samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp | 3 --- 8 files changed, 3 insertions(+), 18 deletions(-) diff --git a/cocos/2d/CCTMXTiledMap.cpp b/cocos/2d/CCTMXTiledMap.cpp index 2a85788b53..33a4b77519 100644 --- a/cocos/2d/CCTMXTiledMap.cpp +++ b/cocos/2d/CCTMXTiledMap.cpp @@ -30,8 +30,6 @@ THE SOFTWARE. #include "CCSprite.h" #include -#undef min -#undef max NS_CC_BEGIN // implementation TMXTiledMap diff --git a/cocos/2d/platform/win32/CCStdC.h b/cocos/2d/platform/win32/CCStdC.h index 19ea8fda7d..47677d29c9 100644 --- a/cocos/2d/platform/win32/CCStdC.h +++ b/cocos/2d/platform/win32/CCStdC.h @@ -148,5 +148,8 @@ inline errno_t strcpy_s(char *strDestination, size_t numberOfElements, #undef DELETE #endif +#undef min +#undef max + #endif // __CC_STD_C_H__ diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 7505ab585e..69c44c4494 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -51,9 +51,6 @@ #include "CCScene.h" #include "CCPlatformConfig.h" -#undef min -#undef max - NS_CC_BEGIN diff --git a/cocos/base/CCGeometry.cpp b/cocos/base/CCGeometry.cpp index 968ff8e0ba..4be119ff6b 100644 --- a/cocos/base/CCGeometry.cpp +++ b/cocos/base/CCGeometry.cpp @@ -27,8 +27,6 @@ THE SOFTWARE. #include "ccMacros.h" #include -#undef min -#undef max // implementation of Point NS_CC_BEGIN diff --git a/cocos/network/WebSocket.cpp b/cocos/network/WebSocket.cpp index 01432c033e..5e17487567 100644 --- a/cocos/network/WebSocket.cpp +++ b/cocos/network/WebSocket.cpp @@ -39,8 +39,6 @@ #define WS_WRITE_BUFFER_SIZE 2048 -#undef min -#undef max NS_CC_BEGIN namespace network { diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp index 3efe4d3993..317bbb8a60 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp @@ -1,8 +1,5 @@ #include "PerformanceLabelTest.h" -#undef min -#undef max - enum { kMaxNodes = 200, kNodesIncrease = 10, diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp index e1b150278f..a9e6f78c94 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp @@ -1,8 +1,5 @@ #include "PerformanceSpriteTest.h" -#undef min -#undef max - enum { kMaxNodes = 50000, kNodesIncrease = 250, diff --git a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp index fcde928c1e..75f0fd6eee 100644 --- a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp @@ -3,9 +3,6 @@ #include "renderer/CCRenderer.h" #include "renderer/CCCustomCommand.h" -#undef min -#undef max - enum { kTagTileMap = 1, From 7e1fd18f76009b9e8b7cc317bf853d8a5a308b28 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 14 Jan 2014 14:38:34 +0800 Subject: [PATCH 070/193] =?UTF-8?q?FLT=5FMIN=20=E2=80=94>=20FTL=5FEPSILON.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/platform/mac/CCEGLView.mm | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/2d/platform/mac/CCEGLView.mm b/cocos/2d/platform/mac/CCEGLView.mm index cad82ee6c1..a3635be8ed 100644 --- a/cocos/2d/platform/mac/CCEGLView.mm +++ b/cocos/2d/platform/mac/CCEGLView.mm @@ -313,13 +313,13 @@ void EGLViewEventHandler::onGLFWframebuffersize(GLFWwindow* window, int w, int h float factorX = frameSizeW / w * view->getFrameZoomFactor(); float factorY = frameSizeH / h * view->getFrameZoomFactor();; - if (fabs(factorX - 0.5f) < FLT_MIN && fabs(factorY - 0.5f) < FLT_MIN ) + if (fabs(factorX - 0.5f) < FLT_EPSILON && fabs(factorY - 0.5f) < FLT_EPSILON ) { view->_isRetina = true; view->setFrameZoomFactor(2.0f * view->getFrameZoomFactor()); glfwSetWindowSize(window, static_cast(frameSizeW * 0.5f * view->getFrameZoomFactor()) , static_cast(frameSizeH * 0.5f * view->getFrameZoomFactor())); } - else if(fabs(factorX - 2.0f) < FLT_MIN && fabs(factorY - 2.0f) < FLT_MIN) + else if(fabs(factorX - 2.0f) < FLT_EPSILON && fabs(factorY - 2.0f) < FLT_EPSILON) { view->_isRetina = false; view->setFrameZoomFactor(0.5f * view->getFrameZoomFactor()); From 11d290ab134ba06629a50e953ecdb7db75db4ac8 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 14 Jan 2014 14:54:19 +0800 Subject: [PATCH 071/193] Update AUTHORS [ci skip] --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index ac01d86aa8..27723850a3 100644 --- a/AUTHORS +++ b/AUTHORS @@ -714,6 +714,9 @@ Developers: akof1314 TestCpp works by using CMake and mingw on Windows. + + Pisces000221 + Corrected a few mistakes in the README file of project-creator. Retired Core Developers: WenSheng Yang From d306d5fe581342e4e722fa03214cbdc7e680905a Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 14 Jan 2014 21:51:13 +0800 Subject: [PATCH 072/193] Update AUTHORS [ci skip] --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index 27723850a3..fd5cf6a651 100644 --- a/AUTHORS +++ b/AUTHORS @@ -94,6 +94,7 @@ Developers: use tinyxml2 to replace libxml2 Added Mingw-crt Support without breaking VS SDK CMake support for windows. + Added support for x64 target of windows. mchinen fix emulator issue for OpenGL ES 2.0 on Android From 428afae8e9fd4f92530118c7dbdcffabfb9f6507 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 14 Jan 2014 21:52:04 +0800 Subject: [PATCH 073/193] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index a16751e56c..bf2d63a5c4 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -6,6 +6,7 @@ cocos2d-x-3.0final ?.? ? [FIX] Websocket doesn't support send/receive data which larger than 4096 bytes. [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. [FIX] TestCpp works by using CMake on Windows. + [FIX] There will be some compilation errors when using x64 target on Windows. cocos2d-x-3.0beta Jan.7 2014 [All] [NEW] New label: shadow, outline, glow support From a18788ff0a8fd1012ee015458ef44411ff42a489 Mon Sep 17 00:00:00 2001 From: Nite Luo Date: Tue, 14 Jan 2014 16:45:40 -0800 Subject: [PATCH 074/193] Fix artifects when VBO is full --- cocos/2d/renderer/CCRenderer.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos/2d/renderer/CCRenderer.cpp b/cocos/2d/renderer/CCRenderer.cpp index 1d3b8cd2b4..2763f71ef6 100644 --- a/cocos/2d/renderer/CCRenderer.cpp +++ b/cocos/2d/renderer/CCRenderer.cpp @@ -251,7 +251,9 @@ void Renderer::render() CCASSERT(cmdQuadCount < VBO_SIZE, "VBO is not big enough for quad data, please break the quad data down or use customized render command"); //Draw batched quads if VBO is full + _lastCommand --; drawBatchedQuads(); + _lastCommand ++; } memcpy(_quads + _numQuads, cmd->getQuad(), sizeof(V3F_C4B_T2F_Quad) * cmdQuadCount); @@ -414,7 +416,7 @@ void Renderer::drawBatchedQuads() } - _firstCommand = _lastCommand; + _firstCommand = _lastCommand + 1; _numQuads = 0; } From 5f661babd29931fa102427c4fcf3ce6c1093ea8c Mon Sep 17 00:00:00 2001 From: Nite Luo Date: Tue, 14 Jan 2014 17:03:54 -0800 Subject: [PATCH 075/193] Add VBO full test --- .../NewRendererTest/NewRendererTest.cpp | 30 +++++++++++++++++++ .../Classes/NewRendererTest/NewRendererTest.h | 12 ++++++++ 2 files changed, 42 insertions(+) diff --git a/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp b/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp index 7044ade0ed..56e7c7128d 100644 --- a/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp @@ -38,6 +38,7 @@ static std::function createFunctions[] = CL(NewClippingNodeTest), CL(NewDrawNodeTest), CL(NewCullingTest), + CL(VBOFullTest), }; #define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) @@ -485,3 +486,32 @@ std::string NewCullingTest::subtitle() const return "Culling"; } +VBOFullTest::VBOFullTest() +{ + Size s = Director::getInstance()->getWinSize(); + Node* parent = Node::create(); + parent->setPosition(s.width/2, s.height/2); + addChild(parent); + + for (int i=0; isetPosition(Point(0,0)); + parent->addChild(sprite); + } +} + +VBOFullTest::~VBOFullTest() +{ + +} + +std::string VBOFullTest::title() const +{ + return "New Renderer"; +} + +std::string VBOFullTest::subtitle() const +{ + return "VBO full Test"; +} \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.h b/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.h index 16604b55d1..caf133f7ff 100644 --- a/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.h +++ b/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.h @@ -118,4 +118,16 @@ protected: virtual ~NewCullingTest(); }; +class VBOFullTest : public MultiSceneTest +{ +public: + CREATE_FUNC(VBOFullTest); + virtual std::string title() const override; + virtual std::string subtitle() const override; + +protected: + VBOFullTest(); + virtual ~VBOFullTest(); +}; + #endif //__NewRendererTest_H_ From edc7547f708313389611e487885bb8a70d85164a Mon Sep 17 00:00:00 2001 From: Nite Luo Date: Tue, 14 Jan 2014 17:06:22 -0800 Subject: [PATCH 076/193] add test instructions --- samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp b/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp index 56e7c7128d..a3cbf77add 100644 --- a/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp @@ -513,5 +513,5 @@ std::string VBOFullTest::title() const std::string VBOFullTest::subtitle() const { - return "VBO full Test"; + return "VBO full Test, everthing should render normally"; } \ No newline at end of file From fd04e178084472c7e8a5f2eff177734bb22a2118 Mon Sep 17 00:00:00 2001 From: Nite Luo Date: Tue, 14 Jan 2014 17:11:32 -0800 Subject: [PATCH 077/193] add a new line --- samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp b/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp index a3cbf77add..c88c2a28e1 100644 --- a/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewRendererTest/NewRendererTest.cpp @@ -514,4 +514,4 @@ std::string VBOFullTest::title() const std::string VBOFullTest::subtitle() const { return "VBO full Test, everthing should render normally"; -} \ No newline at end of file +} From c267c479dbdbb82385b4dda3d2370589a024bc39 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Tue, 14 Jan 2014 17:22:45 -0800 Subject: [PATCH 078/193] Performance Test fixes * SpritePerfTest: 3 new tests added * SpritePerfTest: random() always use the same seed * SpritePerfTest: Fixed tests 8 and 9 on retina display machines * Console: Added 3 new commands: 'config', 'fileutils dump', 'textures' --- CHANGELOG | 14 +- cocos/2d/CCConfiguration.cpp | 16 +- cocos/2d/CCConfiguration.h | 4 +- cocos/2d/CCDirector.cpp | 2 +- cocos/2d/CCTextureCache.cpp | 44 ++- cocos/2d/CCTextureCache.h | 2 +- cocos/2d/platform/CCFileUtils.h | 5 +- cocos/base/CCConsole.cpp | 60 ++- cocos/base/CCConsole.h | 3 + samples/Cpp/TestCpp/Classes/BaseTest.cpp | 30 +- samples/Cpp/TestCpp/Classes/BaseTest.h | 30 +- .../ConfigurationTest/ConfigurationTest.cpp | 6 +- .../PerformanceTest/PerformanceSpriteTest.cpp | 346 ++++++++++++------ .../PerformanceTest/PerformanceSpriteTest.h | 67 +++- .../Classes/Texture2dTest/Texture2dTest.cpp | 101 ++--- 15 files changed, 513 insertions(+), 217 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index bf2d63a5c4..68acb827a9 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,12 +1,18 @@ cocos2d-x-3.0final ?.? ? [All] - [FIX] Crash was triggered if there is not `textureFileName`section in particle plist file. + [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands + [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. + [FIX] Configuration: dumpInfo() -> getInfo() [FIX] ControlSlider doesn't support to set selected thumb sprite. [FIX] ControlButton doesn't support to set scale ratio of touchdown state. + [FIX] Particles: Crash was triggered if there is not `textureFileName`section in particle plist file. + [FIX] Tests: TestCpp works with CMake on Windows. + [FIX] Tests: Sprites Performance Test has 3 new tests + [FIX] TextureCache: getTextureForKey and removeTextureForKey work as expected + [FIX] TextureCache: dumpCachedTextureInfo() -> getCachedTextureInfo() [FIX] Websocket doesn't support send/receive data which larger than 4096 bytes. - [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. - [FIX] TestCpp works by using CMake on Windows. - [FIX] There will be some compilation errors when using x64 target on Windows. + [FIX] Windows: There will be some compilation errors when using x64 target on Windows. + cocos2d-x-3.0beta Jan.7 2014 [All] [NEW] New label: shadow, outline, glow support diff --git a/cocos/2d/CCConfiguration.cpp b/cocos/2d/CCConfiguration.cpp index 47a079d415..a576532ade 100644 --- a/cocos/2d/CCConfiguration.cpp +++ b/cocos/2d/CCConfiguration.cpp @@ -88,24 +88,20 @@ Configuration::~Configuration() { } -void Configuration::dumpInfo() const +std::string Configuration::getInfo() const { - // Dump - Value forDump = Value(_valueDict); - CCLOG("%s", forDump.getDescription().c_str()); - // And Dump some warnings as well #if CC_ENABLE_PROFILERS - CCLOG("cocos2d: **** WARNING **** CC_ENABLE_PROFILERS is defined. Disable it when you finish profiling (from ccConfig.h)"); - printf("\n"); + CCLOG("cocos2d: **** WARNING **** CC_ENABLE_PROFILERS is defined. Disable it when you finish profiling (from ccConfig.h)\n"); #endif #if CC_ENABLE_GL_STATE_CACHE == 0 - CCLOG(""); - CCLOG("cocos2d: **** WARNING **** CC_ENABLE_GL_STATE_CACHE is disabled. To improve performance, enable it (from ccConfig.h)"); - printf("\n"); + CCLOG("cocos2d: **** WARNING **** CC_ENABLE_GL_STATE_CACHE is disabled. To improve performance, enable it (from ccConfig.h)\n"); #endif + // Dump + Value forDump = Value(_valueDict); + return forDump.getDescription(); } void Configuration::gatherGPUInfo() diff --git a/cocos/2d/CCConfiguration.h b/cocos/2d/CCConfiguration.h index f2a7e1052c..4a1ec1568c 100644 --- a/cocos/2d/CCConfiguration.h +++ b/cocos/2d/CCConfiguration.h @@ -122,8 +122,8 @@ public: /** sets a new key/value pair in the configuration dictionary */ void setValue(const std::string& key, const Value& value); - /** dumps the current configuration on the console */ - void dumpInfo() const; + /** returns the Configuration info */ + std::string getInfo() const; /** gathers OpenGL / GPU information */ void gatherGPUInfo(); diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index d3c53b6f3e..3e06a99c75 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -377,7 +377,7 @@ void Director::setOpenGLView(EGLView *openGLView) // Configuration. Gather GPU info Configuration *conf = Configuration::getInstance(); conf->gatherGPUInfo(); - conf->dumpInfo(); + CCLOG("%s\n",conf->getInfo().c_str()); // EAGLView is not a Object delete _openGLView; // [openGLView_ release] diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index 4af449c8bf..d6e5bec858 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -97,7 +97,7 @@ void TextureCache::addImageAsync(const std::string &path, std::functionfullPathForFilename(path.c_str()); + std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path); auto it = _textures.find(fullpath); if( it != _textures.end() ) @@ -290,7 +290,7 @@ Texture2D * TextureCache::addImage(const std::string &path) // MUTEX: // Needed since addImageAsync calls this method from a different thread - std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path.c_str()); + std::string fullpath = FileUtils::getInstance()->fullPathForFilename(path); if (fullpath.size() == 0) { return nullptr; @@ -307,7 +307,7 @@ Texture2D * TextureCache::addImage(const std::string &path) image = new Image(); CC_BREAK_IF(nullptr == image); - bool bRet = image->initWithImageFile(fullpath.c_str()); + bool bRet = image->initWithImageFile(fullpath); CC_BREAK_IF(!bRet); texture = new Texture2D(); @@ -417,16 +417,30 @@ void TextureCache::removeTexture(Texture2D* texture) void TextureCache::removeTextureForKey(const std::string &textureKeyName) { - auto it = _textures.find(textureKeyName); + std::string key = textureKeyName; + auto it = _textures.find(key); + + if( it == _textures.end() ) { + key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); + it = _textures.find(key); + } + if( it != _textures.end() ) { (it->second)->release(); _textures.erase(it); } } -Texture2D* TextureCache::getTextureForKey(const std::string &key) const +Texture2D* TextureCache::getTextureForKey(const std::string &textureKeyName) const { + std::string key = textureKeyName; auto it = _textures.find(key); + + if( it == _textures.end() ) { + key = FileUtils::getInstance()->fullPathForFilename(textureKeyName); + it = _textures.find(key); + } + if( it != _textures.end() ) return it->second; return nullptr; @@ -448,20 +462,28 @@ void TextureCache::waitForQuit() if (_loadingThread) _loadingThread->join(); } -void TextureCache::dumpCachedTextureInfo() const +std::string TextureCache::getCachedTextureInfo() const { + char buffer[16386]; + char buftmp[4096]; + + memset(buffer,0,sizeof(buffer)); + unsigned int count = 0; unsigned int totalBytes = 0; for( auto it = _textures.begin(); it != _textures.end(); ++it ) { + memset(buftmp,0,sizeof(buftmp)); + + Texture2D* tex = it->second; unsigned int bpp = tex->getBitsPerPixelForFormat(); // Each texture takes up width * height * bytesPerPixel bytes. auto bytes = tex->getPixelsWide() * tex->getPixelsHigh() * bpp / 8; totalBytes += bytes; count++; - log("cocos2d: \"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB", + snprintf(buftmp,sizeof(buftmp)-1,"\"%s\" rc=%lu id=%lu %lu x %lu @ %ld bpp => %lu KB\n", it->first.c_str(), (long)tex->retainCount(), (long)tex->getName(), @@ -469,9 +491,13 @@ void TextureCache::dumpCachedTextureInfo() const (long)tex->getPixelsHigh(), (long)bpp, (long)bytes / 1024); + strcat(buffer, buftmp); } - log("cocos2d: TextureCache dumpDebugInfo: %ld textures, for %lu KB (%.2f MB)", (long)count, (long)totalBytes / 1024, totalBytes / (1024.0f*1024.0f)); + snprintf(buftmp, sizeof(buftmp)-1, "TextureCache dumpDebugInfo: %ld textures, for %lu KB (%.2f MB)\n", (long)count, (long)totalBytes / 1024, totalBytes / (1024.0f*1024.0f)); + strcat(buffer, buftmp); + + return std::string(buffer); } #if CC_ENABLE_CACHE_TEXTURE_DATA @@ -645,7 +671,7 @@ void VolatileTextureMgr::reloadAllTextures() break; case VolatileTexture::kString: { - vt->_texture->initWithString(vt->_text.c_str(), vt->_fontDefinition); + vt->_texture->initWithString(vt->_text, vt->_fontDefinition); } break; case VolatileTexture::kImage: diff --git a/cocos/2d/CCTextureCache.h b/cocos/2d/CCTextureCache.h index 8d55c93656..f5b187797f 100644 --- a/cocos/2d/CCTextureCache.h +++ b/cocos/2d/CCTextureCache.h @@ -163,7 +163,7 @@ public: * * @since v1.0 */ - void dumpCachedTextureInfo() const; + std::string getCachedTextureInfo() const; //wait for texture cahe to quit befor destroy instance //called by director, please do not called outside diff --git a/cocos/2d/platform/CCFileUtils.h b/cocos/2d/platform/CCFileUtils.h index 0a29d6efe5..be747149cb 100644 --- a/cocos/2d/platform/CCFileUtils.h +++ b/cocos/2d/platform/CCFileUtils.h @@ -326,7 +326,10 @@ public: * @note This method is used internally. */ virtual ValueVector getValueVectorFromFile(const std::string& filename); - + + /** Returns the full path cache */ + const std::unordered_map& getFullPathCache() const { return _fullPathCache; } + protected: /** * The default constructor. diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 69c44c4494..9437fc105c 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -50,6 +50,9 @@ #include "CCScheduler.h" #include "CCScene.h" #include "CCPlatformConfig.h" +#include "CCFileUtils.h" +#include "CCConfiguration.h" +#include "CCTextureCache.h" NS_CC_BEGIN @@ -61,7 +64,7 @@ NS_CC_BEGIN static ssize_t mydprintf(int sock, const char *format, ...) { va_list args; - char buf[1024]; + char buf[16386]; va_start(args, format); vsnprintf(buf, sizeof(buf), format, args); @@ -92,6 +95,33 @@ static void printSceneGraphBoot(int fd) mydprintf(fd, "Total Nodes: %d\n", total); } +static void printFileUtils(int fd) +{ + FileUtils* fu = FileUtils::getInstance(); + + mydprintf(fd, "\nSearch Paths:\n"); + auto list = fu->getSearchPaths(); + for( const auto &item : list) { + mydprintf(fd, "%s\n", item.c_str()); + } + + mydprintf(fd, "\nResolution Order:\n"); + list = fu->getSearchResolutionsOrder(); + for( const auto &item : list) { + mydprintf(fd, "%s\n", item.c_str()); + } + + mydprintf(fd, "\nWriteble Path:\n"); + mydprintf(fd, "%s\n", fu->getWritablePath().c_str()); + + mydprintf(fd, "\nFull Path Cache:\n"); + auto cache = fu->getFullPathCache(); + for( const auto &item : cache) { + mydprintf(fd, "%s -> %s\n", item.first.c_str(), item.second.c_str()); + } +} + + #if defined(__MINGW32__) static const char* inet_ntop(int af, const void* src, char* dst, int cnt) { @@ -174,6 +204,7 @@ Console::Console() { // VS2012 doesn't support initializer list, so we create a new array and assign its elements to '_command'. Command commands[] = { + { "config", std::bind(&Console::commandConfig, this, std::placeholders::_1, std::placeholders::_2) }, { "debug msg on", [&](int fd, const char* command) { _sendDebugStrings = true; } }, @@ -181,6 +212,7 @@ Console::Console() _sendDebugStrings = false; } }, { "exit", std::bind(&Console::commandExit, this, std::placeholders::_1, std::placeholders::_2) }, + { "fileutils dump", std::bind(&Console::commandFileUtilsDump, this, std::placeholders::_1, std::placeholders::_2) }, { "fps on", [](int fd, const char* command) { Director *dir = Director::getInstance(); Scheduler *sched = dir->getScheduler(); @@ -193,6 +225,7 @@ Console::Console() } }, { "help", std::bind(&Console::commandHelp, this, std::placeholders::_1, std::placeholders::_2) }, { "scene graph", std::bind(&Console::commandSceneGraph, this, std::placeholders::_1, std::placeholders::_2) }, + { "textures", std::bind(&Console::commandTextures, this, std::placeholders::_1, std::placeholders::_2) }, }; _maxCommands = sizeof(commands)/sizeof(commands[0]); @@ -340,6 +373,31 @@ void Console::commandSceneGraph(int fd, const char *command) sched->performFunctionInCocosThread( std::bind(&printSceneGraphBoot, fd) ); } +void Console::commandFileUtilsDump(int fd, const char *command) +{ + Scheduler *sched = Director::getInstance()->getScheduler(); + sched->performFunctionInCocosThread( std::bind(&printFileUtils, fd) ); +} + +void Console::commandConfig(int fd, const char *command) +{ + Scheduler *sched = Director::getInstance()->getScheduler(); + sched->performFunctionInCocosThread( [&](){ + mydprintf(fd, "%s", Configuration::getInstance()->getInfo().c_str()); + } + ); +} + +void Console::commandTextures(int fd, const char *command) +{ + Scheduler *sched = Director::getInstance()->getScheduler(); + sched->performFunctionInCocosThread( [&](){ + mydprintf(fd, "%s", TextureCache::getInstance()->getCachedTextureInfo().c_str()); + } + ); +} + + bool Console::parseCommand(int fd) { auto r = readline(fd); diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index eb27bcfb34..1218bf8066 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -109,6 +109,9 @@ protected: void commandHelp(int fd, const char *command); void commandExit(int fd, const char *command); void commandSceneGraph(int fd, const char *command); + void commandFileUtilsDump(int fd, const char *command); + void commandConfig(int fd, const char *command); + void commandTextures(int fd, const char *command); // file descriptor: socket, console, etc. int _listenfd; diff --git a/samples/Cpp/TestCpp/Classes/BaseTest.cpp b/samples/Cpp/TestCpp/Classes/BaseTest.cpp index f0cd18c58a..529a1337ec 100644 --- a/samples/Cpp/TestCpp/Classes/BaseTest.cpp +++ b/samples/Cpp/TestCpp/Classes/BaseTest.cpp @@ -1,10 +1,26 @@ -// -// BaseTest.cpp -// TestCpp -// -// Created by Ricardo Quesada on 6/6/13. -// -// +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "BaseTest.h" #include "VisibleRect.h" diff --git a/samples/Cpp/TestCpp/Classes/BaseTest.h b/samples/Cpp/TestCpp/Classes/BaseTest.h index e6e3ababfa..1c509e1716 100644 --- a/samples/Cpp/TestCpp/Classes/BaseTest.h +++ b/samples/Cpp/TestCpp/Classes/BaseTest.h @@ -1,10 +1,26 @@ -// -// BaseTest.h -// TestCpp -// -// Created by Ricardo Quesada on 6/6/13. -// -// +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #ifndef __TestCpp__BaseTest__ #define __TestCpp__BaseTest__ diff --git a/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.cpp b/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.cpp index 2cfb569796..de6f94c98c 100644 --- a/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ConfigurationTest/ConfigurationTest.cpp @@ -103,7 +103,8 @@ void ConfigurationLoadConfig::onEnter() ConfigurationBase::onEnter(); Configuration::getInstance()->loadConfigFile("configs/config-test-ok.plist"); - Configuration::getInstance()->dumpInfo(); + std::string config = Configuration::getInstance()->getInfo(); + log("%s\n", config.c_str()); } @@ -196,7 +197,8 @@ void ConfigurationSet::onEnter() conf->setValue("this.is.a.bool.value", Value(true) ); conf->setValue("this.is.a.string.value", Value("hello world") ); - conf->dumpInfo(); + auto str = conf->getInfo(); + log("%s\n", str.c_str()); } std::string ConfigurationSet::subtitle() const diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp index a9e6f78c94..431acb25ed 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp @@ -1,3 +1,30 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2011 Zynga Inc. + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #include "PerformanceSpriteTest.h" enum { @@ -21,144 +48,177 @@ enum { //////////////////////////////////////////////////////// SubTest::~SubTest() { - if (batchNode) + if (_batchNode) { - batchNode->release(); - batchNode = NULL; + _batchNode->release(); + _batchNode = NULL; } } -void SubTest::initWithSubTest(int nSubTest, Node* p) +void SubTest::initWithSubTest(int subtest, Node* p) { - subtestNumber = nSubTest; - parent = p; - batchNode = NULL; + srand(0); + + subtestNumber = subtest; + _parent = p; + _batchNode = nullptr; /* - * Tests: - * 1: 1 (32-bit) PNG sprite of 52 x 139 - * 2: 1 (32-bit) PNG Batch Node using 1 sprite of 52 x 139 - * 3: 1 (16-bit) PNG Batch Node using 1 sprite of 52 x 139 - * 4: 1 (4-bit) PVRTC Batch Node using 1 sprite of 52 x 139 + * Tests: + * 1: 1 (32-bit) PNG sprite of 52 x 139 + * 2: 1 (32-bit) PNG sprite of 52 x 139 + * 3: 1 (32-bit) PNG Batch Node using 1 sprite of 52 x 139 + * 4: 1 (16-bit) PNG Batch Node using 1 sprite of 52 x 139 - * 5: 14 (32-bit) PNG sprites of 85 x 121 each - * 6: 14 (32-bit) PNG Batch Node of 85 x 121 each - * 7: 14 (16-bit) PNG Batch Node of 85 x 121 each - * 8: 14 (4-bit) PVRTC Batch Node of 85 x 121 each + * 5: 14 (32-bit) PNG sprites of 85 x 121 each + * 6: 14 (32-bit) PNG sprites of 85 x 121 each that belong to on texture atlas + * 7: 14 (32-bit) PNG Batch Node of 85 x 121 each + * 8: 14 (16-bit) PNG Batch Node of 85 x 121 each - * 9: 64 (32-bit) sprites of 32 x 32 each - *10: 64 (32-bit) PNG Batch Node of 32 x 32 each - *11: 64 (16-bit) PNG Batch Node of 32 x 32 each - *12: 64 (4-bit) PVRTC Batch Node of 32 x 32 each + * 9: 64 (32-bit) sprites of 32 x 32 each + *10: 64 (32-bit) sprites of 32 x 32 each that belong to on texture atlas + *11: 64 (32-bit) PNG Batch Node of 32 x 32 each + *12: 64 (16-bit) PNG Batch Node of 32 x 32 each */ // purge textures auto mgr = Director::getInstance()->getTextureCache(); - // [mgr removeAllTextures]; - mgr->removeTexture(mgr->addImage("Images/grossinis_sister1.png")); - mgr->removeTexture(mgr->addImage("Images/grossini_dance_atlas.png")); - mgr->removeTexture(mgr->addImage("Images/spritesheet1.png")); + mgr->removeTextureForKey("Images/grossinis_sister1.png"); + mgr->removeTextureForKey("Images/grossini_dance_atlas.png"); + mgr->removeTextureForKey("Images/spritesheet1.png"); switch ( subtestNumber) { - case 1: - case 4: - case 7: - break; /// + case 1: + Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); + break; case 2: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - batchNode = SpriteBatchNode::create("Images/grossinis_sister1.png", 100); - p->addChild(batchNode, 0); break; case 3: + Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); + _batchNode = SpriteBatchNode::create("Images/grossinis_sister1.png", 100); + p->addChild(_batchNode, 0); + break; + case 4: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); - batchNode = SpriteBatchNode::create("Images/grossinis_sister1.png", 100); - p->addChild(batchNode, 0); + _batchNode = SpriteBatchNode::create("Images/grossinis_sister1.png", 100); + p->addChild(_batchNode, 0); break; /// case 5: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - batchNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); - p->addChild(batchNode, 0); - break; + break; case 6: + Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); + _batchNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); + break; + case 7: + Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); + _batchNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); + p->addChild(_batchNode, 0); + break; + case 8: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); - batchNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); - p->addChild(batchNode, 0); + _batchNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); + p->addChild(_batchNode, 0); break; /// - case 8: - Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - batchNode = SpriteBatchNode::create("Images/spritesheet1.png", 100); - p->addChild(batchNode, 0); - break; case 9: + Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); + break; + case 10: + Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); + _batchNode = SpriteBatchNode::create("Images/spritesheet1.png", 100); + break; + case 11: + Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); + _batchNode = SpriteBatchNode::create("Images/spritesheet1.png", 100); + p->addChild(_batchNode, 0); + break; + case 12: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); - batchNode = SpriteBatchNode::create("Images/spritesheet1.png", 100); - p->addChild(batchNode, 0); + _batchNode = SpriteBatchNode::create("Images/spritesheet1.png", 100); + p->addChild(_batchNode, 0); break; + /// default: break; } - if (batchNode) + if (_batchNode) { - batchNode->retain(); + _batchNode->retain(); } - - Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); } Sprite* SubTest::createSpriteWithTag(int tag) { - // create - Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - Sprite* sprite = NULL; switch (subtestNumber) { + /// case 1: - { - sprite = Sprite::create("Images/grossinis_sister1.png"); - parent->addChild(sprite, 0, tag+100); - break; - } case 2: - case 3: - { - sprite = Sprite::createWithTexture(batchNode->getTexture(), Rect(0, 0, 52, 139)); - batchNode->addChild(sprite, 0, tag+100); - break; - } + { + sprite = Sprite::create("Images/grossinis_sister1.png"); + _parent->addChild(sprite, 0, tag+100); + break; + } + case 3: case 4: - { - int idx = (CCRANDOM_0_1() * 1400 / 100) + 1; - char str[32] = {0}; - sprintf(str, "Images/grossini_dance_%02d.png", idx); - sprite = Sprite::create(str); - parent->addChild(sprite, 0, tag+100); - break; - } + { + sprite = Sprite::createWithTexture(_batchNode->getTexture(), Rect(0, 0, 52, 139)); + _batchNode->addChild(sprite, 0, tag+100); + break; + } + + /// case 5: + { + int idx = (CCRANDOM_0_1() * 1400 / 100) + 1; + char str[32] = {0}; + sprintf(str, "Images/grossini_dance_%02d.png", idx); + sprite = Sprite::create(str); + _parent->addChild(sprite, 0, tag+100); + break; + } case 6: - { - int y,x; - int r = (CCRANDOM_0_1() * 1400 / 100); + { + int y,x; + int r = (CCRANDOM_0_1() * 1400 / 100); - y = r / 5; - x = r % 5; + y = r / 5; + x = r % 5; - x *= 85; - y *= 121; - sprite = Sprite::createWithTexture(batchNode->getTexture(), Rect(x,y,85,121)); - batchNode->addChild(sprite, 0, tag+100); - break; - } + x *= 85; + y *= 121; + sprite = Sprite::createWithTexture(_batchNode->getTexture(), Rect(x,y,85,121)); + _parent->addChild(sprite, 0, tag+100); + break; + } case 7: + case 8: + { + int y,x; + int r = (CCRANDOM_0_1() * 1400 / 100); + + y = r / 5; + x = r % 5; + + x *= 85; + y *= 121; + sprite = Sprite::createWithTexture(_batchNode->getTexture(), Rect(x,y,85,121)); + _batchNode->addChild(sprite, 0, tag+100); + break; + } + + /// + case 9: { int y,x; int r = (CCRANDOM_0_1() * 6400 / 100); @@ -169,32 +229,45 @@ Sprite* SubTest::createSpriteWithTag(int tag) char str[40] = {0}; sprintf(str, "Images/sprites_test/sprite-%d-%d.png", x, y); sprite = Sprite::create(str); - parent->addChild(sprite, 0, tag+100); + _parent->addChild(sprite, 0, tag+100); break; } - case 8: - case 9: - { - int y,x; - int r = (CCRANDOM_0_1() * 6400 / 100); + case 10: + { + int y,x; + int r = (CCRANDOM_0_1() * 6400 / 100); - y = r / 8; - x = r % 8; + y = r / 8; + x = r % 8; - x *= 32; - y *= 32; - sprite = Sprite::createWithTexture(batchNode->getTexture(), Rect(x,y,32,32)); - batchNode->addChild(sprite, 0, tag+100); - break; - } + x *= 32; + y *= 32; + sprite = Sprite::createWithTexture(_batchNode->getTexture(), CC_RECT_PIXELS_TO_POINTS(Rect(x,y,32,32))); + _parent->addChild(sprite, 0, tag+100); + break; + } + + case 11: + case 12: + { + int y,x; + int r = (CCRANDOM_0_1() * 6400 / 100); + + y = r / 8; + x = r % 8; + + x *= 32; + y *= 32; + sprite = Sprite::createWithTexture(_batchNode->getTexture(), CC_RECT_PIXELS_TO_POINTS(Rect(x,y,32,32))); + _batchNode->addChild(sprite, 0, tag+100); + break; + } default: break; } - Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - return sprite; } @@ -203,18 +276,23 @@ void SubTest::removeByTag(int tag) switch (subtestNumber) { case 1: - case 4: - case 7: - parent->removeChildByTag(tag+100, true); + case 5: + case 9: + _parent->removeChildByTag(tag+100, true); break; + case 2: case 3: - case 5: + case 4: + case 6: + case 7: case 8: - case 9: - batchNode->removeChildAtIndex(tag, true); - // [batchNode removeChildByTag:tag+100 cleanup:YES]; + + case 10: + case 11: + case 12: + _batchNode->removeChildByTag(tag+100, true); break; default: break; @@ -367,7 +445,7 @@ void SpriteMainScene::initWithSubTest(int asubtest, int nNodes) // Sub Tests MenuItemFont::setFontSize(32); auto subMenu = Menu::create(); - for (int i = 1; i <= 9; ++i) + for (int i = 1; i <= 12; ++i) { char str[10] = {0}; sprintf(str, "%d ", i); @@ -375,9 +453,9 @@ void SpriteMainScene::initWithSubTest(int asubtest, int nNodes) itemFont->setTag(i); subMenu->addChild(itemFont, 10); - if( i<= 3) + if( i<= 4) itemFont->setColor(Color3B(200,20,20)); - else if(i <= 6) + else if(i <= 8) itemFont->setColor(Color3B(0,200,20)); else itemFont->setColor(Color3B(0,20,200)); @@ -388,11 +466,21 @@ void SpriteMainScene::initWithSubTest(int asubtest, int nNodes) addChild(subMenu, 2); // add title label - auto label = LabelTTF::create(title().c_str(), "Arial", 40); + auto label = LabelTTF::create(title(), "Arial", 40); addChild(label, 1); label->setPosition(Point(s.width/2, s.height-32)); label->setColor(Color3B(255,255,40)); + + // subtitle + std::string strSubtitle = subtitle(); + if( ! strSubtitle.empty() ) + { + auto l = LabelTTF::create(strSubtitle.c_str(), "Thonburi", 16); + addChild(l, 9999); + l->setPosition( Point(VisibleRect::center().x, VisibleRect::top().y - 60) ); + } + while(quantityNodes < nNodes) onIncrease(this); } @@ -402,6 +490,12 @@ std::string SpriteMainScene::title() const return "No title"; } +std::string SpriteMainScene::subtitle() const +{ + return ""; // override me +} + + SpriteMainScene::~SpriteMainScene() { if (_subTest) @@ -761,6 +855,12 @@ std::string SpritePerformTest1::title() const return strRet; } +std::string SpritePerformTest1::subtitle() const +{ + return "test 1"; +} + + void SpritePerformTest1::doTest(Sprite* sprite) { performancePosition(sprite); @@ -778,6 +878,11 @@ std::string SpritePerformTest2::title() const return strRet; } +std::string SpritePerformTest2::subtitle() const +{ + return "test 2"; +} + void SpritePerformTest2::doTest(Sprite* sprite) { performanceScale(sprite); @@ -796,6 +901,11 @@ std::string SpritePerformTest3::title() const return strRet; } +std::string SpritePerformTest3::subtitle() const +{ + return "test 3"; +} + void SpritePerformTest3::doTest(Sprite* sprite) { performanceRotationScale(sprite); @@ -814,6 +924,11 @@ std::string SpritePerformTest4::title() const return strRet; } +std::string SpritePerformTest4::subtitle() const +{ + return "test 4"; +} + void SpritePerformTest4::doTest(Sprite* sprite) { performanceOut100(sprite); @@ -832,6 +947,11 @@ std::string SpritePerformTest5::title() const return strRet; } +std::string SpritePerformTest5::subtitle() const +{ + return "test 5"; +} + void SpritePerformTest5::doTest(Sprite* sprite) { performanceout20(sprite); @@ -850,6 +970,11 @@ std::string SpritePerformTest6::title() const return strRet; } +std::string SpritePerformTest6::subtitle() const +{ + return "test 6"; +} + void SpritePerformTest6::doTest(Sprite* sprite) { performanceActions(sprite); @@ -868,6 +993,11 @@ std::string SpritePerformTest7::title() const return strRet; } +std::string SpritePerformTest7::subtitle() const +{ + return "test 7"; +} + void SpritePerformTest7::doTest(Sprite* sprite) { performanceActions20(sprite); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.h index 9fb0993441..b6a4910259 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.h +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.h @@ -1,3 +1,30 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2010-2012 cocos2d-x.org + Copyright (c) 2011 Zynga Inc. + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #ifndef __PERFORMANCE_SPRITE_TEST_H__ #define __PERFORMANCE_SPRITE_TEST_H__ @@ -12,9 +39,9 @@ public: void initWithSubTest(int nSubTest, Node* parent); protected: - int subtestNumber; - SpriteBatchNode *batchNode; - Node* parent; + int subtestNumber; + SpriteBatchNode *_batchNode; + Node* _parent; }; class SpriteMenuLayer : public PerformBasicLayer @@ -36,6 +63,7 @@ class SpriteMainScene : public Scene public: virtual ~SpriteMainScene(); virtual std::string title() const; + virtual std::string subtitle() const; void initWithSubTest(int nSubTest, int nNodes); void updateNodes(); @@ -53,23 +81,25 @@ public: virtual void onExit(); void updateAutoTest(float dt); void onAutoTest(Object* sender); -private: + + static bool _s_autoTest; + static int _s_nSpriteCurCase; + +protected: void dumpProfilerFPS(); void beginAutoTest(); void endAutoTest(); void nextAutoTest(); void finishAutoTest(); void autoShowSpriteTests(int curCase, int subTest,int nodes); -public: - static bool _s_autoTest; - static int _s_nSpriteCurCase; -protected: + int lastRenderedCount; int quantityNodes; SubTest *_subTest; int subtestNumber; std::vector _vecFPS; int _executeTimes; + static const int MAX_AUTO_TEST_TIMES = 25; static const int MAX_SPRITE_TEST_CASE = 7; static const int MAX_SUB_TEST_NUMS = 9; @@ -80,50 +110,57 @@ protected: class SpritePerformTest1 : public SpriteMainScene { public: - virtual void doTest(Sprite* sprite); + virtual void doTest(Sprite* sprite) override; virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpritePerformTest2 : public SpriteMainScene { public: - virtual void doTest(Sprite* sprite); + virtual void doTest(Sprite* sprite) override; virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpritePerformTest3 : public SpriteMainScene { public: - virtual void doTest(Sprite* sprite); + virtual void doTest(Sprite* sprite) override; virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpritePerformTest4 : public SpriteMainScene { public: - virtual void doTest(Sprite* sprite); + virtual void doTest(Sprite* sprite) override; virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpritePerformTest5 : public SpriteMainScene { public: - virtual void doTest(Sprite* sprite); + virtual void doTest(Sprite* sprite) override; virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpritePerformTest6 : public SpriteMainScene { public: - virtual void doTest(Sprite* sprite); + virtual void doTest(Sprite* sprite) override; virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpritePerformTest7 : public SpriteMainScene { public: - virtual void doTest(Sprite* sprite); + virtual void doTest(Sprite* sprite) override; virtual std::string title() const override; + virtual std::string subtitle() const override; }; void runSpriteTest(); diff --git a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp index 95bcb47323..a3f4a7d564 100644 --- a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp +++ b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp @@ -150,18 +150,20 @@ void TextureDemo::onEnter() { BaseTest::onEnter(); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + auto textureCache = Director::getInstance()->getTextureCache(); + log("%s\n", textureCache->getCachedTextureInfo().c_str()); auto col = LayerColor::create(Color4B(128,128,128,255)); addChild(col, -10); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", textureCache->getCachedTextureInfo().c_str()); } TextureDemo::~TextureDemo() { - Director::getInstance()->getTextureCache()->removeUnusedTextures(); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + auto textureCache = Director::getInstance()->getTextureCache(); + textureCache->removeUnusedTextures(); + log("%s\n", textureCache->getCachedTextureInfo().c_str()); } void TextureDemo::restartCallback(Object* sender) @@ -209,7 +211,8 @@ void TextureTIFF::onEnter() auto img = Sprite::create("Images/test_image.tiff"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); this->addChild(img); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TextureTIFF::title() const @@ -232,7 +235,7 @@ void TextureTGA::onEnter() auto img = Sprite::create("TileMaps/levelmap.tga"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); this->addChild(img); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TextureTGA::title() const @@ -254,7 +257,7 @@ void TexturePNG::onEnter() auto img = Sprite::create("Images/test_image.png"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePNG::title() const @@ -275,7 +278,7 @@ void TextureJPEG::onEnter() auto img = Sprite::create("Images/test_image.jpeg"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TextureJPEG::title() const @@ -296,7 +299,7 @@ void TextureWEBP::onEnter() auto img = Sprite::create("Images/test_image.webp"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TextureWEBP::title() const @@ -340,7 +343,7 @@ void TextureMipMap::onEnter() img0->runAction(RepeatForever::create(Sequence::create(scale1, sc_back, NULL))); img1->runAction(RepeatForever::create(Sequence::create(scale2, sc_back2, NULL))); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TextureMipMap::title() const @@ -391,7 +394,7 @@ void TexturePVRMipMap::onEnter() imgMipMap->runAction(RepeatForever::create(Sequence::create(scale1, sc_back, NULL))); img->runAction(RepeatForever::create(Sequence::create(scale2, sc_back2, NULL))); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRMipMap::title() const @@ -433,7 +436,7 @@ void TexturePVRMipMap2::onEnter() imgMipMap->runAction(RepeatForever::create(Sequence::create(scale1, sc_back, NULL))); img->runAction(RepeatForever::create(Sequence::create(scale2, sc_back2, NULL))); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRMipMap2::title() const @@ -465,7 +468,7 @@ void TexturePVR2BPP::onEnter() img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVR2BPP::title() const @@ -496,8 +499,8 @@ void TexturePVRTest::onEnter() { log("This test is not supported."); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); - + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); + } std::string TexturePVRTest::title() const @@ -528,7 +531,7 @@ void TexturePVR4BPP::onEnter() { log("This test is not supported in cocos2d-mac"); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVR4BPP::title() const @@ -551,7 +554,7 @@ void TexturePVRRGBA8888::onEnter() auto img = Sprite::create("Images/test_image_rgba8888.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRRGBA8888::title() const @@ -581,7 +584,7 @@ void TexturePVRBGRA8888::onEnter() { log("BGRA8888 images are not supported"); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRBGRA8888::title() const @@ -604,7 +607,7 @@ void TexturePVRRGBA5551::onEnter() auto img = Sprite::create("Images/test_image_rgba5551.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRRGBA5551::title() const @@ -627,7 +630,7 @@ void TexturePVRRGBA4444::onEnter() auto img = Sprite::create("Images/test_image_rgba4444.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRRGBA4444::title() const @@ -655,7 +658,7 @@ void TexturePVRRGBA4444GZ::onEnter() #endif img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRRGBA4444GZ::title() const @@ -683,7 +686,7 @@ void TexturePVRRGBA4444CCZ::onEnter() auto img = Sprite::create("Images/test_image_rgba4444.pvr.ccz"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRRGBA4444CCZ::title() const @@ -711,7 +714,7 @@ void TexturePVRRGB565::onEnter() auto img = Sprite::create("Images/test_image_rgb565.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRRGB565::title() const @@ -734,7 +737,7 @@ void TexturePVRRGB888::onEnter() addChild(img); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRRGB888::title() const @@ -757,7 +760,7 @@ void TexturePVRA8::onEnter() auto img = Sprite::create("Images/test_image_a8.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } @@ -781,7 +784,7 @@ void TexturePVRI8::onEnter() auto img = Sprite::create("Images/test_image_i8.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRI8::title() const @@ -804,7 +807,7 @@ void TexturePVRAI88::onEnter() auto img = Sprite::create("Images/test_image_ai88.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRAI88::title() const @@ -826,7 +829,7 @@ void TexturePVR2BPPv3::onEnter() addChild(img); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVR2BPPv3::title() const @@ -853,7 +856,7 @@ void TexturePVRII2BPPv3::onEnter() addChild(img); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRII2BPPv3::title() const @@ -884,7 +887,7 @@ void TexturePVR4BPPv3::onEnter() log("This test is not supported"); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVR4BPPv3::title() const @@ -919,7 +922,7 @@ void TexturePVRII4BPPv3::onEnter() log("This test is not supported"); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRII4BPPv3::title() const @@ -946,7 +949,7 @@ void TexturePVRRGBA8888v3::onEnter() addChild(img); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRRGBA8888v3::title() const @@ -977,7 +980,7 @@ void TexturePVRBGRA8888v3::onEnter() log("BGRA images are not supported"); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRBGRA8888v3::title() const @@ -1004,7 +1007,7 @@ void TexturePVRRGBA5551v3::onEnter() addChild(img); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRRGBA5551v3::title() const @@ -1031,7 +1034,7 @@ void TexturePVRRGBA4444v3::onEnter() addChild(img); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRRGBA4444v3::title() const @@ -1058,7 +1061,7 @@ void TexturePVRRGB565v3::onEnter() addChild(img); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRRGB565v3::title() const @@ -1085,7 +1088,7 @@ void TexturePVRRGB888v3::onEnter() addChild(img); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRRGB888v3::title() const @@ -1112,7 +1115,7 @@ void TexturePVRA8v3::onEnter() addChild(img); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRA8v3::title() const @@ -1139,7 +1142,7 @@ void TexturePVRI8v3::onEnter() addChild(img); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRI8v3::title() const @@ -1166,7 +1169,7 @@ void TexturePVRAI88v3::onEnter() addChild(img); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRAI88v3::title() const @@ -1222,7 +1225,7 @@ void TexturePVRNonSquare::onEnter() auto img = Sprite::create("Images/grossini_128x256_mipmap.pvr"); img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRNonSquare::title() const @@ -1251,7 +1254,7 @@ void TexturePVRNPOT4444::onEnter() img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRNPOT4444::title() const @@ -1280,7 +1283,7 @@ void TexturePVRNPOT8888::onEnter() img->setPosition(Point( s.width/2.0f, s.height/2.0f)); addChild(img); } - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePVRNPOT8888::title() const @@ -1334,7 +1337,7 @@ void TextureAlias::onEnter() sprite2->runAction(scaleforever); sprite->runAction(scaleToo); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TextureAlias::title() const @@ -1439,7 +1442,7 @@ void TexturePixelFormat::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TexturePixelFormat::title() const @@ -2222,7 +2225,7 @@ void TextureConvertRGB888::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TextureConvertRGB888::title() const @@ -2256,7 +2259,7 @@ void TextureConvertRGBA8888::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TextureConvertRGBA8888::title() const @@ -2290,7 +2293,7 @@ void TextureConvertI8::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TextureConvertI8::title() const @@ -2324,7 +2327,7 @@ void TextureConvertAI88::onEnter() // restore default Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::DEFAULT); - Director::getInstance()->getTextureCache()->dumpCachedTextureInfo(); + log("%s\n", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } std::string TextureConvertAI88::title() const From 82797d84346ec066a184cf1db528286041bf0345 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Wed, 15 Jan 2014 01:37:15 +0000 Subject: [PATCH 079/193] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index f41186e7ef..a54347f346 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit f41186e7ef4209597d8c81952c3535b02305a79c +Subproject commit a54347f3460b1cb2bf5a40fb357458a278826319 From b3f306e742530db02e442b7b794820ea993e87a8 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Tue, 14 Jan 2014 18:30:51 -0800 Subject: [PATCH 080/193] Ignore getFullPathCache() in FileUtils --- tools/tojs/cocos2dx.ini | 3 ++- tools/tolua/cocos2dx.ini | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/tools/tojs/cocos2dx.ini b/tools/tojs/cocos2dx.ini index 99f57b9e8e..dfc3d0c576 100644 --- a/tools/tojs/cocos2dx.ini +++ b/tools/tojs/cocos2dx.ini @@ -105,13 +105,14 @@ skip = Node::[^setPosition$ setGLServerState description getUserObject .*UserDat TextureCache::[addPVRTCImage addImageAsync], Timer::[getSelector createWithScriptHandler], *::[copyWith.* onEnter.* onExit.* ^description$ getObjectType onTouch.* onAcc.* onKey.* onRegisterTouchListener], - FileUtils::[(g|s)etSearchResolutionsOrder$ (g|s)etSearchPaths$ getFileData getDataFromFile], + FileUtils::[(g|s)etSearchResolutionsOrder$ (g|s)etSearchPaths$ getFileData getDataFromFile getFullPathCache], Application::[^application.* ^run$], Camera::[getEyeXYZ getCenterXYZ getUpXYZ], ccFontDefinition::[*], NewTextureAtlas::[*], RenderTexture::[listenToBackground listenToForeground] + rename_functions = SpriteFrameCache::[addSpriteFramesWithFile=addSpriteFrames getSpriteFrameByName=getSpriteFrame], MenuItemFont::[setFontNameObj=setFontName setFontSizeObj=setFontSize getFontSizeObj=getFontSize getFontNameObj=getFontName], ProgressTimer::[setReverseProgress=setReverseDirection], diff --git a/tools/tolua/cocos2dx.ini b/tools/tolua/cocos2dx.ini index a3fced78fd..e8d443afad 100644 --- a/tools/tolua/cocos2dx.ini +++ b/tools/tolua/cocos2dx.ini @@ -102,7 +102,7 @@ skip = Node::[setGLServerState description getUserObject .*UserData getGLServerS TextureCache::[addPVRTCImage addImageAsync], Timer::[getSelector createWithScriptHandler], *::[copyWith.* onEnter.* onExit.* ^description$ getObjectType (g|s)etDelegate onTouch.* onAcc.* onKey.* onRegisterTouchListener], - FileUtils::[(g|s)etSearchResolutionsOrder$ (g|s)etSearchPaths$ getFileData getDataFromFile], + FileUtils::[(g|s)etSearchResolutionsOrder$ (g|s)etSearchPaths$ getFileData getDataFromFile getFullPathCache], Application::[^application.* ^run$], Camera::[getEyeXYZ getCenterXYZ getUpXYZ], ccFontDefinition::[*], From 3b208337fe8d6fd0141805c094bfd07f42458d57 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Wed, 15 Jan 2014 02:39:20 +0000 Subject: [PATCH 081/193] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index a54347f346..bab1d8a7c5 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit a54347f3460b1cb2bf5a40fb357458a278826319 +Subproject commit bab1d8a7c5d8b29f14c8dc19158a8bb994f0e970 From f0537f17da755bd32eb71d1b758bf78f8a7ec0bc Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Tue, 14 Jan 2014 18:55:14 -0800 Subject: [PATCH 082/193] ooops --- cocos/2d/CCTextureCache.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index d6e5bec858..c6527ba07f 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -671,7 +671,7 @@ void VolatileTextureMgr::reloadAllTextures() break; case VolatileTexture::kString: { - vt->_texture->initWithString(vt->_text, vt->_fontDefinition); + vt->_texture->initWithString(vt->_text.c_str(), vt->_fontDefinition); } break; case VolatileTexture::kImage: From 19705fcf376212562cc8ea442a776c65400abcc8 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Wed, 15 Jan 2014 11:27:57 +0800 Subject: [PATCH 083/193] issue #3640: add performance test->renderer LargeTileMap test --- .../project.pbxproj.REMOVED.git-id | 2 +- samples/Cpp/TestCpp/Android.mk | 1 + samples/Cpp/TestCpp/CMakeLists.txt | 1 + .../PerformanceRendererTest.cpp | 55 ++++++++++++++ .../PerformanceTest/PerformanceRendererTest.h | 28 +++++++ .../PerformanceTest/PerformanceTest.cpp | 75 ++++++++++++++++++- .../Classes/PerformanceTest/PerformanceTest.h | 8 ++ .../TileMaps/map/slcj.png.REMOVED.git-id | 1 + 8 files changed, 166 insertions(+), 5 deletions(-) create mode 100644 samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceRendererTest.cpp create mode 100644 samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceRendererTest.h create mode 100644 samples/Cpp/TestCpp/Resources/TileMaps/map/slcj.png.REMOVED.git-id diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 0f53b948c7..2603132689 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -2efefc01ff97bda1498d1d4a850ea1881f751f7c \ No newline at end of file +b6abaf935c97f8f1dc7a7179e54850928015b442 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Android.mk b/samples/Cpp/TestCpp/Android.mk index 32917fb7c3..07d231cbf8 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/samples/Cpp/TestCpp/Android.mk @@ -121,6 +121,7 @@ Classes/PerformanceTest/PerformanceTest.cpp \ Classes/PerformanceTest/PerformanceTextureTest.cpp \ Classes/PerformanceTest/PerformanceTouchesTest.cpp \ Classes/PerformanceTest/PerformanceLabelTest.cpp \ +Classes/PerformanceTest/PerformanceRendererTest.cpp \ Classes/PhysicsTest/PhysicsTest.cpp \ Classes/RenderTextureTest/RenderTextureTest.cpp \ Classes/RotateWorldTest/RotateWorldTest.cpp \ diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt index 5f409f7601..6c10336eb2 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -116,6 +116,7 @@ set(SAMPLE_SRC Classes/PerformanceTest/PerformanceTextureTest.cpp Classes/PerformanceTest/PerformanceTouchesTest.cpp Classes/PerformanceTest/PerformanceLabelTest.cpp + Classes/PerformanceTest/PerformanceRendererTest.cpp Classes/PhysicsTest/PhysicsTest.cpp Classes/RenderTextureTest/RenderTextureTest.cpp Classes/RotateWorldTest/RotateWorldTest.cpp diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceRendererTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceRendererTest.cpp new file mode 100644 index 0000000000..60031018c6 --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceRendererTest.cpp @@ -0,0 +1,55 @@ +// +// PerformanceRendererTest.cpp +// cocos2d_samples +// +// Created by Huabing on 1/10/14. +// +// + +#include "PerformanceRendererTest.h" +#include "PerformanceTextureTest.h" +#include "../testResource.h" + +RenderTestLayer::RenderTestLayer() +: PerformBasicLayer(true, 1, 1) +{ +} + +RenderTestLayer::~RenderTestLayer() +{ +} + +Scene* RenderTestLayer::scene() +{ + auto scene = Scene::create(); + RenderTestLayer *layer = new RenderTestLayer(); + scene->addChild(layer); + layer->release(); + + return scene; +} + +void RenderTestLayer::onEnter() +{ + PerformBasicLayer::onEnter(); + auto map = TMXTiledMap::create("TileMaps/map/sl.tmx"); + + Size CC_UNUSED s = map->getContentSize(); + CCLOG("ContentSize: %f, %f", s.width,s.height); + + addChild(map,-1); + + //map->setAnchorPoint( Point(0, 0) ); + //map->setPosition( Point(-20,-200) ); +} + +void RenderTestLayer::showCurrentTest() +{ + +} + +void runRendererTest() +{ + auto scene = RenderTestLayer::scene(); + Director::getInstance()->replaceScene(scene); +} \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceRendererTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceRendererTest.h new file mode 100644 index 0000000000..07aeb4bc01 --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceRendererTest.h @@ -0,0 +1,28 @@ +// +// PerformanceRendererTest.h +// cocos2d_samples +// +// Created by Huabing on 1/10/14. +// +// + +#ifndef __PERFORMANCE_RENDERER_TEST_H__ +#define __PERFORMANCE_RENDERER_TEST_H__ + +#include "PerformanceTest.h" + +class RenderTestLayer : public PerformBasicLayer +{ + +public: + RenderTestLayer(); + virtual ~RenderTestLayer(); + + virtual void onEnter() override; + virtual void showCurrentTest() override; +public: + static Scene* scene(); +}; + +void runRendererTest(); +#endif diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.cpp index e48ef17f28..9ef97602b6 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.cpp @@ -7,6 +7,7 @@ #include "PerformanceTouchesTest.h" #include "PerformanceAllocTest.h" #include "PerformanceLabelTest.h" +#include "PerformanceRendererTest.h" enum { @@ -26,6 +27,7 @@ struct { { "Texture Perf Test",[](Object*sender){runTextureTest();} }, { "Touches Perf Test",[](Object*sender){runTouchesTest();} }, { "Label Perf Test",[](Object*sender){runLabelTest();} }, + { "Renderer Perf Test",[](Object*sender){runRendererTest();} }, }; static const int g_testMax = sizeof(g_testsName)/sizeof(g_testsName[0]); @@ -41,18 +43,83 @@ void PerformanceMainLayer::onEnter() auto s = Director::getInstance()->getWinSize(); - auto menu = Menu::create(); - menu->setPosition( Point::ZERO ); + _itemMenu = Menu::create(); + _itemMenu->setPosition( Point::ZERO ); MenuItemFont::setFontName("Arial"); MenuItemFont::setFontSize(24); for (int i = 0; i < g_testMax; ++i) { auto pItem = MenuItemFont::create(g_testsName[i].name, g_testsName[i].callback); pItem->setPosition(Point(s.width / 2, s.height - (i + 1) * LINE_SPACE)); - menu->addChild(pItem, kItemTagBasic + i); + _itemMenu->addChild(pItem, kItemTagBasic + i); } - addChild(menu); + addChild(_itemMenu); + + // Register Touch Event + auto listener = EventListenerTouchOneByOne::create(); + listener->setSwallowTouches(true); + + listener->onTouchBegan = CC_CALLBACK_2(PerformanceMainLayer::onTouchBegan, this); + listener->onTouchMoved = CC_CALLBACK_2(PerformanceMainLayer::onTouchMoved, this); + + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); + + auto mouseListener = EventListenerMouse::create(); + mouseListener->onMouseScroll = CC_CALLBACK_1(PerformanceMainLayer::onMouseScroll, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(mouseListener, this); +} + +bool PerformanceMainLayer::onTouchBegan(Touch* touches, Event *event) +{ + _beginPos = touches->getLocation(); + return true; +} +void PerformanceMainLayer::onTouchMoved(Touch* touches, Event *event) +{ + auto touchLocation = touches->getLocation(); + float nMoveY = touchLocation.y - _beginPos.y; + + auto curPos = _itemMenu->getPosition(); + auto nextPos = Point(curPos.x, curPos.y + nMoveY); + + if (nextPos.y < 0.0f) + { + _itemMenu->setPosition(Point::ZERO); + return; + } + + if (nextPos.y > ((g_testMax + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height)) + { + _itemMenu->setPosition(Point(0, ((g_testMax + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height))); + return; + } + + _itemMenu->setPosition(nextPos); + _beginPos = touchLocation; +} + +void PerformanceMainLayer::onMouseScroll(Event *event) +{ + auto mouseEvent = static_cast(event); + float nMoveY = mouseEvent->getScrollY() * 6; + + auto curPos = _itemMenu->getPosition(); + auto nextPos = Point(curPos.x, curPos.y + nMoveY); + + if (nextPos.y < 0.0f) + { + _itemMenu->setPosition(Point::ZERO); + return; + } + + if (nextPos.y > ((g_testMax + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height)) + { + _itemMenu->setPosition(Point(0, ((g_testMax + 1)* LINE_SPACE - VisibleRect::getVisibleRect().size.height))); + return; + } + + _itemMenu->setPosition(nextPos); } //////////////////////////////////////////////////////// diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.h index 7d4766de30..f06a3c9bbd 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.h +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.h @@ -7,6 +7,14 @@ class PerformanceMainLayer : public Layer { public: virtual void onEnter(); + + bool onTouchBegan(Touch* touches, Event *event); + void onTouchMoved(Touch* touches, Event *event); + + void onMouseScroll(Event *event); +protected: + Point _beginPos; + Menu* _itemMenu; }; class PerformBasicLayer : public Layer diff --git a/samples/Cpp/TestCpp/Resources/TileMaps/map/slcj.png.REMOVED.git-id b/samples/Cpp/TestCpp/Resources/TileMaps/map/slcj.png.REMOVED.git-id new file mode 100644 index 0000000000..c7ca23a772 --- /dev/null +++ b/samples/Cpp/TestCpp/Resources/TileMaps/map/slcj.png.REMOVED.git-id @@ -0,0 +1 @@ +64ce8a88d0dee73cf5d9fbb8f3c80673c82b9575 \ No newline at end of file From 25998f023757799fa6764efc4013752e70a1cd67 Mon Sep 17 00:00:00 2001 From: "Huabing.Xu" Date: Wed, 15 Jan 2014 11:44:08 +0800 Subject: [PATCH 084/193] closed #3640: change windows project files --- samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj | 2 ++ samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj index 2815c3c7f3..1e60324f40 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj @@ -187,6 +187,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ + @@ -332,6 +333,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ + diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters index a6990872b6..00e2567c95 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters @@ -715,6 +715,9 @@ Classes\ExtensionsTest\CocoStudioSceneTest\TriggerCode + + Classes\PerformanceTest + @@ -1318,5 +1321,8 @@ Classes\ExtensionsTest\CocoStudioSceneTest\TriggerCode + + Classes\PerformanceTest + \ No newline at end of file From 60009a818ed7ba36f8903d6b70e8392c21c325ff Mon Sep 17 00:00:00 2001 From: zhangbin Date: Wed, 15 Jan 2014 12:05:17 +0800 Subject: [PATCH 085/193] closed #3712, Add relative path for CCFileUtils.h in CCConsole.cpp. --- cocos/base/CCConsole.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 9437fc105c..002fb6e071 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -50,7 +50,7 @@ #include "CCScheduler.h" #include "CCScene.h" #include "CCPlatformConfig.h" -#include "CCFileUtils.h" +#include "platform/CCFileUtils.h" #include "CCConfiguration.h" #include "CCTextureCache.h" From 8fac676a82927e608a858744f120f58c9492ffcc Mon Sep 17 00:00:00 2001 From: hbb Date: Wed, 15 Jan 2014 12:39:56 +0800 Subject: [PATCH 086/193] add check data valid in getStringFromFile so far no check would be crashed when getData faild. maybe return an empty string is better. --- cocos/2d/platform/CCFileUtils.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index 3404675922..1434eea8e6 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -547,6 +547,8 @@ static Data getData(const std::string& filename, bool forString) std::string FileUtils::getStringFromFile(const std::string& filename) { Data data = getData(filename, true); + if (! data.getBytes()) + return ""; std::string ret((const char*)data.getBytes()); return ret; } From 04d8c7514cf76151a0f94593b5f8a8c2809c7bbe Mon Sep 17 00:00:00 2001 From: zhangbin Date: Wed, 15 Jan 2014 16:35:08 +0800 Subject: [PATCH 087/193] closed #3688, Solve the bug : LabelAtlas set a shorter string than before, the effect will be wrong. --- cocos/2d/CCAtlasNode.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index 5e88b70832..4fa8442b92 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -158,7 +158,7 @@ void AtlasNode::draw(void) shader, _blendFunc, _textureAtlas->getQuads(), - _textureAtlas->getTotalQuads(), + _quadsToDraw, _modelViewTransform); Director::getInstance()->getRenderer()->addCommand(&_quadCommand); From 629f111f7d22fd07812c34f9f351ccd0f1138b0b Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Wed, 15 Jan 2014 17:21:08 +0800 Subject: [PATCH 088/193] Relieve inherit from LabelProtocol --- cocos/2d/CCLabel.cpp | 100 ++++++------------ cocos/2d/CCLabel.h | 19 ++-- .../PerformanceTest/PerformanceLabelTest.cpp | 2 +- 3 files changed, 40 insertions(+), 81 deletions(-) diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 1802cf43e1..a267a41938 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -53,9 +53,9 @@ Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, if (ret->setTTFConfig(ttfConfig)) { - if(ttfConfig.distanceFieldEnable) + if(ttfConfig.distanceFieldEnabled) ret->setFontSize(ttfConfig.fontSize); - ret->setText(text,alignment,lineSize); + ret->setString(text,alignment,lineSize); ret->autorelease(); return ret; } @@ -81,7 +81,7 @@ Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::str if (ret->setBMFontFilePath(bmfontFilePath)) { - ret->setText(text,alignment,lineSize); + ret->setString(text,alignment,lineSize); ret->autorelease(); return ret; } @@ -94,7 +94,6 @@ Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::str Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,bool useA8Shader) : _reusedLetter(nullptr) -, _multilineEnable(true) , _commonLineHeight(0.0f) , _lineBreakWithoutSpaces(false) , _width(0.0f) @@ -147,24 +146,15 @@ bool Label::init() return ret; } -bool Label::setTTFConfig(const TTFConfig& ttfConfig) +bool Label::initWithFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled /* = false */, bool useA8Shader /* = false */) { - FontAtlas *newAtlas = nullptr; - if(ttfConfig.distanceFieldEnable) - newAtlas = FontAtlasCache::getFontAtlasTTF(ttfConfig.fontFilePath, DISTANCEFIELD_ATLAS_FONTSIZE, ttfConfig.glyphs, ttfConfig.customGlyphs,true); - else - newAtlas = FontAtlasCache::getFontAtlasTTF(ttfConfig.fontFilePath, ttfConfig.fontSize, ttfConfig.glyphs, ttfConfig.customGlyphs,false); - - if (!newAtlas) - return false; - FontAtlas *oldAtlas = _fontAtlas; bool oldDistanceFieldEnable = _useDistanceField; bool oldA8ShaderEnabel = _useA8Shader; - - _fontAtlas = newAtlas; - _useDistanceField = ttfConfig.distanceFieldEnable; - _useA8Shader = true; + + _fontAtlas = atlas; + _useDistanceField = distanceFieldEnabled; + _useA8Shader = useA8Shader; bool ret = Label::init(); if (oldAtlas) @@ -180,7 +170,7 @@ bool Label::setTTFConfig(const TTFConfig& ttfConfig) _useA8Shader = oldA8ShaderEnabel; Label::init(); - FontAtlasCache::releaseFontAtlas(newAtlas); + FontAtlasCache::releaseFontAtlas(atlas); } } @@ -196,6 +186,20 @@ bool Label::setTTFConfig(const TTFConfig& ttfConfig) return ret; } +bool Label::setTTFConfig(const TTFConfig& ttfConfig) +{ + FontAtlas *newAtlas = nullptr; + if(ttfConfig.distanceFieldEnabled) + newAtlas = FontAtlasCache::getFontAtlasTTF(ttfConfig.fontFilePath, DISTANCEFIELD_ATLAS_FONTSIZE, ttfConfig.glyphs, ttfConfig.customGlyphs,true); + else + newAtlas = FontAtlasCache::getFontAtlasTTF(ttfConfig.fontFilePath, ttfConfig.fontSize, ttfConfig.glyphs, ttfConfig.customGlyphs,false); + + if (!newAtlas) + return false; + + return initWithFontAtlas(newAtlas,ttfConfig.distanceFieldEnabled,true); +} + bool Label::setBMFontFilePath(const std::string& bmfontFilePath) { FontAtlas *newAtlas = FontAtlasCache::getFontAtlasFNT(bmfontFilePath); @@ -203,57 +207,10 @@ bool Label::setBMFontFilePath(const std::string& bmfontFilePath) if (!newAtlas) return false; - FontAtlas *oldAtlas = _fontAtlas; - bool oldDistanceFieldEnable = _useDistanceField; - bool oldA8ShaderEnabel = _useA8Shader; - - _fontAtlas = newAtlas; - _useDistanceField = false; - _useA8Shader = false; - - bool ret = Label::init(); - if (oldAtlas) - { - if (ret) - { - FontAtlasCache::releaseFontAtlas(oldAtlas); - } - else - { - _fontAtlas = oldAtlas; - _useDistanceField = oldDistanceFieldEnable; - _useA8Shader = oldA8ShaderEnabel; - Label::init(); - - FontAtlasCache::releaseFontAtlas(newAtlas); - } - } - - if (_fontAtlas) - { - _commonLineHeight = _fontAtlas->getCommonLineHeight(); - if (_currentUTF16String) - { - alignText(); - } - } - - return ret; + return initWithFontAtlas(newAtlas); } -void Label::setString(const std::string &text) -{ - _multilineEnable = true; - setText(text, TextHAlignment::CENTER, _width, false); -} - -void Label::setString(const std::string &text,bool multilineEnable) -{ - _multilineEnable = multilineEnable; - setText(text, TextHAlignment::CENTER, _width, false); -} - -bool Label::setText(const std::string& text, const TextHAlignment& alignment /* = TextHAlignment::LEFT */, float lineWidth /* = 0 */, bool lineBreakWithoutSpaces /* = false */) +bool Label::setString(const std::string& text, const TextHAlignment& alignment /* = TextHAlignment::CENTER */, float lineWidth /* = -1 */, bool lineBreakWithoutSpaces /* = false */) { if (!_fontAtlas || _commonLineHeight <= 0) return false; @@ -262,7 +219,10 @@ bool Label::setText(const std::string& text, const TextHAlignment& alignment /* // reset the string resetCurrentString(); - _width = lineWidth; + if(lineWidth >= 0) + { + _width = lineWidth; + } _alignment = alignment; _lineBreakWithoutSpaces = lineBreakWithoutSpaces; @@ -381,7 +341,7 @@ void Label::alignText() _textureAtlas->removeAllQuads(); _fontAtlas->prepareLetterDefinitions(_currentUTF16String); LabelTextFormatter::createStringSprites(this); - if(_multilineEnable && LabelTextFormatter::multilineText(this) ) + if(_width > 0 && LabelTextFormatter::multilineText(this) ) LabelTextFormatter::createStringSprites(this); LabelTextFormatter::alignText(this); diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index f7b92e2021..26dcc89f9a 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -60,7 +60,7 @@ typedef struct _ttfConfig int fontSize; GlyphCollection glyphs; const char *customGlyphs; - bool distanceFieldEnable; + bool distanceFieldEnabled; _ttfConfig(const char* filePath,int fontSize = 36, const GlyphCollection& glyphs = GlyphCollection::NEHE, const char *customGlyphs = nullptr,bool useDistanceField = false) @@ -68,11 +68,11 @@ typedef struct _ttfConfig ,fontSize(fontSize) ,glyphs(glyphs) ,customGlyphs(customGlyphs) - ,distanceFieldEnable(useDistanceField) + ,distanceFieldEnabled(useDistanceField) {} }TTFConfig; -class CC_DLL Label : public SpriteBatchNode, public LabelProtocol, public LabelTextFormatProtocol +class CC_DLL Label : public SpriteBatchNode, public LabelTextFormatProtocol { public: static Label* create(); @@ -86,13 +86,11 @@ public: bool setBMFontFilePath(const std::string& bmfontFilePath); - bool setText(const std::string& text, const TextHAlignment& alignment = TextHAlignment::LEFT, float lineWidth = 0, bool lineBreakWithoutSpaces = false); + bool setString(const std::string& text, const TextHAlignment& alignment = TextHAlignment::CENTER, float lineWidth = -1, bool lineBreakWithoutSpaces = false); //only support for TTF void setLabelEffect(LabelEffect effect,const Color3B& effectColor); - virtual void setString(const std::string &text) override; - void setString(const std::string &text,bool multilineEnable); virtual void setAlignment(TextHAlignment alignment); virtual void setWidth(float width); virtual void setLineBreakWithoutSpace(bool breakWithoutSpace); @@ -138,7 +136,7 @@ public: virtual void setLabelContentSize(const Size &newSize) override; // carloX - virtual const std::string& getString() const override { static std::string _ret("not implemented"); return _ret; } + virtual const std::string& getString() const { static std::string _ret("not implemented"); return _ret; } void addChild(Node * child, int zOrder=0, int tag=0) override; virtual std::string getDescription() const override; @@ -156,6 +154,8 @@ private: */ ~Label(); + bool initWithFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled = false, bool useA8Shader = false); + void setFontSize(int fontSize); bool init(); @@ -173,9 +173,8 @@ private: //! used for optimization Sprite *_reusedLetter; - std::vector _lettersInfo; - - bool _multilineEnable; + std::vector _lettersInfo; + float _commonLineHeight; bool _lineBreakWithoutSpaces; float _width; diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp index 50d60d84fa..4c9f561b5d 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceLabelTest.cpp @@ -337,7 +337,7 @@ void LabelMainScene::updateText(float dt) case kCaseLabelUpdate: for(const auto &child : children) { Label* label = (Label*)child; - label->setString(text,false); + label->setString(text); } break; default: From 536eaca24dba05e83a58b4d48daa724373eb928f Mon Sep 17 00:00:00 2001 From: zhangbin Date: Wed, 15 Jan 2014 17:27:53 +0800 Subject: [PATCH 089/193] closed #3714, Remove configurations which are not necessary in AndroidManifest.xml of aneroid projects. --- samples/Cpp/AssetsManagerTest/proj.android/AndroidManifest.xml | 2 +- samples/Cpp/HelloCpp/proj.android/AndroidManifest.xml | 2 +- samples/Cpp/SimpleGame/proj.android/AndroidManifest.xml | 2 +- samples/Cpp/TestCpp/proj.android/AndroidManifest.xml | 2 +- .../Javascript/CocosDragonJS/proj.android/AndroidManifest.xml | 2 +- .../Javascript/CrystalCraze/proj.android/AndroidManifest.xml | 2 +- .../Javascript/MoonWarriors/proj.android/AndroidManifest.xml | 2 +- .../Javascript/TestJavascript/proj.android/AndroidManifest.xml | 2 +- .../WatermelonWithMe/proj.android/AndroidManifest.xml | 2 +- samples/Lua/HelloLua/proj.android/AndroidManifest.xml | 2 +- samples/Lua/TestLua/proj.android/AndroidManifest.xml | 2 +- template/multi-platform-cpp/proj.android/AndroidManifest.xml | 2 +- template/multi-platform-js/proj.android/AndroidManifest.xml | 2 +- template/multi-platform-lua/proj.android/AndroidManifest.xml | 2 +- 14 files changed, 14 insertions(+), 14 deletions(-) diff --git a/samples/Cpp/AssetsManagerTest/proj.android/AndroidManifest.xml b/samples/Cpp/AssetsManagerTest/proj.android/AndroidManifest.xml index b6b69e4442..b236420d07 100644 --- a/samples/Cpp/AssetsManagerTest/proj.android/AndroidManifest.xml +++ b/samples/Cpp/AssetsManagerTest/proj.android/AndroidManifest.xml @@ -14,7 +14,7 @@ android:label="@string/app_name" android:screenOrientation="landscape" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" - android:configChanges="orientation|screenSize|smallestScreenSize"> + android:configChanges="orientation"> + android:configChanges="orientation"> + android:configChanges="orientation"> + android:configChanges="orientation"> + android:configChanges="orientation"> + android:configChanges="orientation"> + android:configChanges="orientation"> + android:configChanges="orientation"> + android:configChanges="orientation"> + android:configChanges="orientation"> + android:configChanges="orientation"> + android:configChanges="orientation"> + android:configChanges="orientation"> + android:configChanges="orientation"> Date: Wed, 15 Jan 2014 17:29:07 +0800 Subject: [PATCH 090/193] fix compiling error --- .../javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index 4c9597201a..e540327313 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -52164446e797e85d5d6d746eb85e915c8eb7df15 \ No newline at end of file +f92acd30f26c52238e94d2ef1f5b11e760980a67 \ No newline at end of file From 4278f024b8b9697ec4b520c6c8c2321d41bd61b7 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 15 Jan 2014 11:17:21 -0800 Subject: [PATCH 091/193] Console::log(format, va_args) is private log(format, va_args) -> static _log(format, va_args) in order to prevent possible resolution errors with overloaded functions. --- CHANGELOG | 1 + cocos/base/CCConsole.cpp | 37 +++++++++++----------- cocos/base/CCConsole.h | 1 - samples/Cpp/TestCpp/Classes/controller.cpp | 1 - 4 files changed, 19 insertions(+), 21 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 68acb827a9..4e7311b166 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -2,6 +2,7 @@ cocos2d-x-3.0final ?.? ? [All] [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. + [FIX] Console: log(format, va_args) is private to prevent possible resolution errors [FIX] Configuration: dumpInfo() -> getInfo() [FIX] ControlSlider doesn't support to set selected thumb sprite. [FIX] ControlButton doesn't support to set scale ratio of touchdown state. diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 002fb6e071..19f7d54048 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -144,24 +144,7 @@ static const char* inet_ntop(int af, const void* src, char* dst, int cnt) // Free functions to log // -// XXX: Deprecated -void CCLog(const char * format, ...) -{ - va_list args; - va_start(args, format); - log(format, args); - va_end(args); -} - -void log(const char * format, ...) -{ - va_list args; - va_start(args, format); - log(format, args); - va_end(args); -} - -void log(const char *format, va_list args) +static void _log(const char *format, va_list args) { char buf[MAX_LOG_LENGTH]; @@ -176,7 +159,7 @@ void log(const char *format, va_list args) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wszBuf, sizeof(wszBuf)); OutputDebugStringW(wszBuf); OutputDebugStringA("\n"); - + WideCharToMultiByte(CP_ACP, 0, wszBuf, sizeof(wszBuf), buf, sizeof(buf), NULL, FALSE); printf("%s\n", buf); @@ -189,6 +172,22 @@ void log(const char *format, va_list args) Director::getInstance()->getConsole()->log(buf); } +// XXX: Deprecated +void CCLog(const char * format, ...) +{ + va_list args; + va_start(args, format); + _log(format, args); + va_end(args); +} + +void log(const char * format, ...) +{ + va_list args; + va_start(args, format); + _log(format, args); + va_end(args); +} // // Console code diff --git a/cocos/base/CCConsole.h b/cocos/base/CCConsole.h index 1218bf8066..7a06d3423f 100644 --- a/cocos/base/CCConsole.h +++ b/cocos/base/CCConsole.h @@ -58,7 +58,6 @@ static const int MAX_LOG_LENGTH = 16*1024; @brief Output Debug message. */ void CC_DLL log(const char * format, ...) CC_FORMAT_PRINTF(1, 2); -void CC_DLL log(const char * format, va_list args); /** Console is helper class that lets the developer control the game from TCP connection. Console will spawn a new thread that will listen to a specified TCP port. diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp index 750ba02a9f..b9713167a1 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -151,7 +151,6 @@ TestController::~TestController() void TestController::menuCallback(Object * sender) { - Director::getInstance()->purgeCachedData(); // get the userdata, it's the index of the menu item clicked From f8dc8f0b380175d4e548543e0bbca935c0a79302 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 15 Jan 2014 14:35:26 -0800 Subject: [PATCH 092/193] Renderer performance fixes QuadCommand no longer stores a copy of the quads. Instead it just stores a reference and the MV matrix. Later, the Renderer when it copies the Quads to the queue, it will convert the Quads to world coordinates --- CHANGELOG | 1 + cocos/2d/renderer/CCQuadCommand.cpp | 58 +++-------------------------- cocos/2d/renderer/CCQuadCommand.h | 15 +++++--- cocos/2d/renderer/CCRenderer.cpp | 47 ++++++++++++++++++++++- cocos/2d/renderer/CCRenderer.h | 3 ++ 5 files changed, 64 insertions(+), 60 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 4e7311b166..3b3b55d33e 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -7,6 +7,7 @@ cocos2d-x-3.0final ?.? ? [FIX] ControlSlider doesn't support to set selected thumb sprite. [FIX] ControlButton doesn't support to set scale ratio of touchdown state. [FIX] Particles: Crash was triggered if there is not `textureFileName`section in particle plist file. + [FIX] Renderer: QuadCommand::init() does not copy the Quads, it only store a reference making the code faster [FIX] Tests: TestCpp works with CMake on Windows. [FIX] Tests: Sprites Performance Test has 3 new tests [FIX] TextureCache: getTextureForKey and removeTextureForKey work as expected diff --git a/cocos/2d/renderer/CCQuadCommand.cpp b/cocos/2d/renderer/CCQuadCommand.cpp index b69fd075d3..f60446871c 100644 --- a/cocos/2d/renderer/CCQuadCommand.cpp +++ b/cocos/2d/renderer/CCQuadCommand.cpp @@ -34,12 +34,11 @@ QuadCommand::QuadCommand() ,_depth(0) ,_textureID(0) ,_blendType(BlendFunc::DISABLE) -,_quadCount(0) -,_capacity(0) +,_quadsCount(0) { _type = RenderCommand::Type::QUAD_COMMAND; _shader = nullptr; - _quad = nullptr; + _quads = nullptr; } void QuadCommand::init(int viewport, int32_t depth, GLuint textureID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, const kmMat4 &mv) @@ -48,63 +47,16 @@ void QuadCommand::init(int viewport, int32_t depth, GLuint textureID, GLProgram* _depth = depth; _textureID = textureID; _blendType = blendType; - _quadCount = quadCount; _shader = shader; - if(quadCount > _capacity ) { - //TODO find a better way to manage quads, current way will result in memory be wasted -// _quad = (V3F_C4B_T2F_Quad*)malloc(sizeof(V3F_C4B_T2F_Quad) * quadCount); - _quad = (V3F_C4B_T2F_Quad*) realloc(_quad, sizeof(*quad) * quadCount ); - _capacity = quadCount; - } + _quadsCount = quadCount; + _quads = quad; - _quadCount = quadCount; - memcpy(_quad, quad, sizeof(V3F_C4B_T2F_Quad) * quadCount); - - for(int i=0; ibl.vertices.x; - vec1.y = q->bl.vertices.y; - vec1.z = q->bl.vertices.z; - kmVec3Transform(&out1, &vec1, &mv); - q->bl.vertices.x = out1.x; - q->bl.vertices.y = out1.y; - q->bl.vertices.z = out1.z; - - kmVec3 vec2, out2; - vec2.x = q->br.vertices.x; - vec2.y = q->br.vertices.y; - vec2.z = q->br.vertices.z; - kmVec3Transform(&out2, &vec2, &mv); - q->br.vertices.x = out2.x; - q->br.vertices.y = out2.y; - q->br.vertices.z = out2.z; - - kmVec3 vec3, out3; - vec3.x = q->tr.vertices.x; - vec3.y = q->tr.vertices.y; - vec3.z = q->tr.vertices.z; - kmVec3Transform(&out3, &vec3, &mv); - q->tr.vertices.x = out3.x; - q->tr.vertices.y = out3.y; - q->tr.vertices.z = out3.z; - - kmVec3 vec4, out4; - vec4.x = q->tl.vertices.x; - vec4.y = q->tl.vertices.y; - vec4.z = q->tl.vertices.z; - kmVec3Transform(&out4, &vec4, &mv); - q->tl.vertices.x = out4.x; - q->tl.vertices.y = out4.y; - q->tl.vertices.z = out4.z; - } + _mv = mv; } QuadCommand::~QuadCommand() { - free(_quad); } int64_t QuadCommand::generateID() diff --git a/cocos/2d/renderer/CCQuadCommand.h b/cocos/2d/renderer/CCQuadCommand.h index 411dc4913b..b21999ea58 100644 --- a/cocos/2d/renderer/CCQuadCommand.h +++ b/cocos/2d/renderer/CCQuadCommand.h @@ -41,7 +41,7 @@ public: QuadCommand(); ~QuadCommand(); - void init(int viewport, int32_t depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, + void init(int viewport, int32_t depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quads, ssize_t quadCount, const kmMat4& mv); // +----------+----------+-----+-----------------------------------+ @@ -60,13 +60,15 @@ public: inline GLuint getTextureID() const { return _textureID; } - inline V3F_C4B_T2F_Quad* getQuad() const { return _quad; } + inline V3F_C4B_T2F_Quad* getQuads() const { return _quads; } - inline ssize_t getQuadCount() const { return _quadCount; } + inline ssize_t getQuadCount() const { return _quadsCount; } inline GLProgram* getShader() const { return _shader; } inline BlendFunc getBlendType() const { return _blendType; } + + inline const kmMat4& getModelView() const { return _mv; } protected: int32_t _materialID; @@ -85,9 +87,10 @@ protected: BlendFunc _blendType; - V3F_C4B_T2F_Quad* _quad; - ssize_t _quadCount; - ssize_t _capacity; + V3F_C4B_T2F_Quad* _quads; + ssize_t _quadsCount; + + kmMat4 _mv; }; NS_CC_END diff --git a/cocos/2d/renderer/CCRenderer.cpp b/cocos/2d/renderer/CCRenderer.cpp index 2763f71ef6..5c97dfdae4 100644 --- a/cocos/2d/renderer/CCRenderer.cpp +++ b/cocos/2d/renderer/CCRenderer.cpp @@ -256,7 +256,9 @@ void Renderer::render() _lastCommand ++; } - memcpy(_quads + _numQuads, cmd->getQuad(), sizeof(V3F_C4B_T2F_Quad) * cmdQuadCount); + memcpy(_quads + _numQuads, cmd->getQuads(), sizeof(V3F_C4B_T2F_Quad) * cmdQuadCount); + convertToWorldCoordiantes(_quads + _numQuads, cmdQuadCount, cmd->getModelView()); + _numQuads += cmdQuadCount; } else if(commandType == RenderCommand::Type::CUSTOM_COMMAND) @@ -319,6 +321,49 @@ void Renderer::render() _lastMaterialID = 0; } +void Renderer::convertToWorldCoordiantes(V3F_C4B_T2F_Quad* quads, ssize_t quantity, const kmMat4& modelView) +{ + for(ssize_t i=0; ibl.vertices.x; + vec1.y = q->bl.vertices.y; + vec1.z = q->bl.vertices.z; + kmVec3Transform(&out1, &vec1, &modelView); + q->bl.vertices.x = out1.x; + q->bl.vertices.y = out1.y; + q->bl.vertices.z = out1.z; + + kmVec3 vec2, out2; + vec2.x = q->br.vertices.x; + vec2.y = q->br.vertices.y; + vec2.z = q->br.vertices.z; + kmVec3Transform(&out2, &vec2, &modelView); + q->br.vertices.x = out2.x; + q->br.vertices.y = out2.y; + q->br.vertices.z = out2.z; + + kmVec3 vec3, out3; + vec3.x = q->tr.vertices.x; + vec3.y = q->tr.vertices.y; + vec3.z = q->tr.vertices.z; + kmVec3Transform(&out3, &vec3, &modelView); + q->tr.vertices.x = out3.x; + q->tr.vertices.y = out3.y; + q->tr.vertices.z = out3.z; + + kmVec3 vec4, out4; + vec4.x = q->tl.vertices.x; + vec4.y = q->tl.vertices.y; + vec4.z = q->tl.vertices.z; + kmVec3Transform(&out4, &vec4, &modelView); + q->tl.vertices.x = out4.x; + q->tl.vertices.y = out4.y; + q->tl.vertices.z = out4.z; + } +} + void Renderer::drawBatchedQuads() { //TODO we can improve the draw performance by insert material switching command before hand. diff --git a/cocos/2d/renderer/CCRenderer.h b/cocos/2d/renderer/CCRenderer.h index e732547130..c2dcdccc6f 100644 --- a/cocos/2d/renderer/CCRenderer.h +++ b/cocos/2d/renderer/CCRenderer.h @@ -75,9 +75,12 @@ protected: void mapBuffers(); void drawBatchedQuads(); + //Draw the previews queued quads and flush previous context void flush(); + void convertToWorldCoordiantes(V3F_C4B_T2F_Quad* quads, ssize_t quantity, const kmMat4& modelView); + std::stack _commandGroupStack; std::stack _renderStack; From 21c4b2c8935f28eb13e07526089f719025e00afd Mon Sep 17 00:00:00 2001 From: Luis Parravicini Date: Wed, 15 Jan 2014 19:44:57 -0300 Subject: [PATCH 093/193] fixes #3720 --- tools/closure-compiler/obfuscate.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tools/closure-compiler/obfuscate.py b/tools/closure-compiler/obfuscate.py index 4979edc50e..9572576278 100755 --- a/tools/closure-compiler/obfuscate.py +++ b/tools/closure-compiler/obfuscate.py @@ -1,6 +1,6 @@ #!/usr/bin/python -# create_project.py -# Create cross-platform cocos2d-x project +# obfuscate.py +# Create Ant buildfile to obfuscate game source code # Copyright (c) 2012 cocos2d-x.org # Author: WangZhe @@ -16,9 +16,9 @@ import sys import os, os.path def dumpUsage(): - print "Usage: generate-config.py -input INPUT_PATH -output OUTPUT_PATH -cocos2d COCOS2D_ROOT_PATH" + print "Usage: %s -input INPUT_PATH -output OUTPUT_PATH -cocos2d COCOS2D_ROOT_PATH" % (os.path.basename(__file__)) print "Options:" - print " -intput INPUT_PATH The path to javscript files directory" + print " -input INPUT_PATH The path to javascript files directory" print " -output OUTPUT_PATH The path to the obfuscated javascript file" print " -cocos2d COCOS2D_ROOT_PATH The root path of cocos2d-x, e.g. /workspace/cocos2d-x" print "" @@ -123,7 +123,7 @@ checkParams() generateXmlForCompiler() # print "running ant to generate obfuscated main.js" # os.popen("ant -buildfile obfuscate.xml") -print "Successful! obfuscate.xml is generated." -print "Note: Please reoder the files sequence in obfuscate.xml, keep it the same order as javascript \"requrie\" instruction," -print "then call \"ant -buildfile obfuscate.xml\" to obfuscate your js codes." +print "Successful! obfuscate.xml generated." +print "Note: Please reorder the file's sequence in obfuscate.xml, keep it the same order as javascript \"require\" instruction," +print "then call \"ant -buildfile obfuscate.xml\" to obfuscate your js code." From 65602a4574750b469c093d1dc7f06a36d6627310 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 15 Jan 2014 16:06:47 -0800 Subject: [PATCH 094/193] Updates Xcode, Android and Linux project with new BatchCommand --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/Android.mk | 1 + cocos/2d/CMakeLists.txt | 1 + cocos/2d/renderer/CCBatchCommand.cpp | 125 ++++++++++++++++++ cocos/2d/renderer/CCBatchCommand.h | 81 ++++++++++++ 5 files changed, 209 insertions(+), 1 deletion(-) create mode 100644 cocos/2d/renderer/CCBatchCommand.cpp create mode 100644 cocos/2d/renderer/CCBatchCommand.h diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index faa1e4571d..e14906c550 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -3d6ada05d55194dd8e4c10ed8316add7c0d8705c \ No newline at end of file +88c095bbe123ab56df3f7870692c6631f4464c8d \ No newline at end of file diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 303a1da40f..9fca766934 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -122,6 +122,7 @@ renderer/CCFrustum.cpp \ renderer/CCGroupCommand.cpp \ renderer/CCMaterialManager.cpp \ renderer/CCQuadCommand.cpp \ +renderer/CCBatchCommand.cpp \ renderer/CCRenderCommand.cpp \ renderer/CCRenderer.cpp \ renderer/CCRenderMaterial.cpp \ diff --git a/cocos/2d/CMakeLists.txt b/cocos/2d/CMakeLists.txt index 88090ec7c5..8340903c8b 100644 --- a/cocos/2d/CMakeLists.txt +++ b/cocos/2d/CMakeLists.txt @@ -144,6 +144,7 @@ set(COCOS2D_SRC renderer/CCGroupCommand.cpp renderer/CCMaterialManager.cpp renderer/CCQuadCommand.cpp + renderer/CCBatchCommand.cpp renderer/CCRenderCommand.cpp renderer/CCRenderer.cpp renderer/CCRenderMaterial.cpp diff --git a/cocos/2d/renderer/CCBatchCommand.cpp b/cocos/2d/renderer/CCBatchCommand.cpp new file mode 100644 index 0000000000..de3fc511cd --- /dev/null +++ b/cocos/2d/renderer/CCBatchCommand.cpp @@ -0,0 +1,125 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + + +#include "renderer/CCBatchCommand.h" +#include "ccGLStateCache.h" +#include "CCTextureAtlas.h" + +NS_CC_BEGIN + +BatchCommand::BatchCommand() +: _viewport(0) +, _depth(0) +, _textureID(0) +, _blendType(BlendFunc::DISABLE) +, _textureAtlas(nullptr) +{ + _type = RenderCommand::Type::BATCH_COMMAND; + _shader = nullptr; +} + +void BatchCommand::init(int viewport, int32_t depth, GLuint textureID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform) +{ + _viewport = viewport; + _depth = depth; + _textureID = textureID; + _blendType = blendType; + _shader = shader; + + _textureAtlas = textureAtlas; + + _mv = modelViewTransform; +} + +BatchCommand::~BatchCommand() +{ +} + +int64_t BatchCommand::generateID() +{ + _id = 0; + + //Generate Material ID + //TODO fix shader ID generation + CCASSERT(_shader->getProgram() < pow(2,10), "ShaderID is greater than 2^10"); + //TODO fix texture ID generation + CCASSERT(_textureID < pow(2,18), "TextureID is greater than 2^18"); + + //TODO fix blend id generation + int blendID = 0; + if(_blendType == BlendFunc::DISABLE) + { + blendID = 0; + } + else if(_blendType == BlendFunc::ALPHA_PREMULTIPLIED) + { + blendID = 1; + } + else if(_blendType == BlendFunc::ALPHA_NON_PREMULTIPLIED) + { + blendID = 2; + } + else if(_blendType == BlendFunc::ADDITIVE) + { + blendID = 3; + } + else + { + blendID = 4; + } + + //TODO Material ID should be part of the ID + // + // Temporal hack (later, these 32-bits should be packed in 24-bits + // + // +---------------------+-------------------+----------------------+ + // | Shader ID (10 bits) | Blend ID (4 bits) | Texture ID (18 bits) | + // +---------------------+-------------------+----------------------+ + + _materialID = (int32_t)_shader->getProgram() << 22 + | (int32_t)blendID << 18 + | (int32_t)_textureID << 0; + + //Generate RenderCommandID + _id = (int64_t)_viewport << 61 + | (int64_t)1 << 60 //translucent + | (int64_t)_depth << 36; + + return _id; +} + +void BatchCommand::execute() +{ + // Set material + _shader->use(); + _shader->setUniformsForBuiltins(_mv); + GL::bindTexture2D(_textureID); + GL::blendFunc(_blendType.src, _blendType.dst); + + // Draw + _textureAtlas->drawQuads(); +} + +NS_CC_END \ No newline at end of file diff --git a/cocos/2d/renderer/CCBatchCommand.h b/cocos/2d/renderer/CCBatchCommand.h new file mode 100644 index 0000000000..d3b2a5245e --- /dev/null +++ b/cocos/2d/renderer/CCBatchCommand.h @@ -0,0 +1,81 @@ +/**************************************************************************** + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef _CC_BATCHCOMMAND_H_ +#define _CC_BATCHCOMMAND_H_ + +#include "CCRenderCommand.h" +#include "CCGLProgram.h" +#include "CCRenderCommandPool.h" +#include "kazmath/kazmath.h" + +NS_CC_BEGIN + +class TextureAtlas; + +#define CC_NO_TEXTURE 0 + +class BatchCommand : public RenderCommand +{ +public: + + BatchCommand(); + ~BatchCommand(); + + void init(int viewport, int32_t depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform); + + // +----------+----------+-----+-----------------------------------+ + // | | | | | | + // | ViewPort | Transluc | | Depth | Material ID | + // | 3 bits | 1 bit | | 24 bits | 24 bit2 | + // +----------+----------+-----+----------------+------------------+ + virtual int64_t generateID(); + + void execute(); + +protected: + int32_t _materialID; + + //Key Data + int _viewport; /// Which view port it belongs to + + //TODO use material to determine if it's translucent + int32_t _depth; + + //Maternal + GLuint _textureID; + + GLProgram* _shader; +// GLuint _shaderID; + + BlendFunc _blendType; + + TextureAtlas *_textureAtlas; + + // ModelView transform + kmMat4 _mv; +}; +NS_CC_END + +#endif //_CC_BATCHCOMMAND_H_ From 938825360678b8a79c218613ca88f515df4f80e5 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 15 Jan 2014 16:07:38 -0800 Subject: [PATCH 095/193] SpriteBatchCommand and ParticleBatchCommand use the BatchCommand BatchCommand is being used by SpriteBatchCommand and ParticlesBatchCommand This improves performance in batches --- cocos/2d/CCParticleBatchNode.cpp | 28 ++++++++------------------- cocos/2d/CCParticleBatchNode.h | 4 ++-- cocos/2d/CCSpriteBatchNode.cpp | 22 +++++++++------------ cocos/2d/CCSpriteBatchNode.h | 4 ++-- cocos/2d/renderer/CCCustomCommand.cpp | 3 +-- cocos/2d/renderer/CCGroupCommand.cpp | 3 +-- cocos/2d/renderer/CCQuadCommand.cpp | 3 +-- cocos/2d/renderer/CCRenderCommand.h | 1 + cocos/2d/renderer/CCRenderer.cpp | 7 +++++++ 9 files changed, 32 insertions(+), 43 deletions(-) diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index 5b78d1256f..773b780997 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -382,26 +382,14 @@ void ParticleBatchNode::draw(void) return; } -// CC_NODE_DRAW_SETUP(); -// -// GL::blendFunc( _blendFunc.src, _blendFunc.dst ); -// -// _textureAtlas->drawQuads(); - - auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); - - kmMat4 mv; - kmGLGetMatrix(KM_GL_MODELVIEW, &mv); - - _quadCommand.init(0, - _vertexZ, - _textureAtlas->getTexture()->getName(), - shader, - _blendFunc, - _textureAtlas->getQuads(), - _textureAtlas->getTotalQuads(), - mv); - Director::getInstance()->getRenderer()->addCommand(&_quadCommand); + _batchCommand.init(0, + _vertexZ, + _textureAtlas->getTexture()->getName(), + _shaderProgram, + _blendFunc, + _textureAtlas, + _modelViewTransform); + Director::getInstance()->getRenderer()->addCommand(&_batchCommand); CC_PROFILER_STOP("CCParticleBatchNode - draw"); } diff --git a/cocos/2d/CCParticleBatchNode.h b/cocos/2d/CCParticleBatchNode.h index d4fd276603..bb092e96d2 100644 --- a/cocos/2d/CCParticleBatchNode.h +++ b/cocos/2d/CCParticleBatchNode.h @@ -32,7 +32,7 @@ #include "CCNode.h" #include "CCProtocols.h" -#include "renderer/CCQuadCommand.h" +#include "renderer/CCBatchCommand.h" NS_CC_BEGIN @@ -146,7 +146,7 @@ private: /** the blend function used for drawing the quads */ BlendFunc _blendFunc; // quad command - QuadCommand _quadCommand; + BatchCommand _batchCommand; }; // end of particle_nodes group diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 3ef2e183e9..502474d00e 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -99,7 +99,7 @@ bool SpriteBatchNode::initWithTexture(Texture2D *tex, ssize_t capacity) _descendants.reserve(capacity); - setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP)); + setShaderProgram(ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); return true; } @@ -356,18 +356,14 @@ void SpriteBatchNode::draw() for(const auto &child: _children) child->updateTransform(); - kmMat4 mv; - kmGLGetMatrix(KM_GL_MODELVIEW, &mv); - - _quadCommand.init(0, - _vertexZ, - _textureAtlas->getTexture()->getName(), - _shaderProgram, - _blendFunc, - _textureAtlas->getQuads(), - _textureAtlas->getTotalQuads(), - mv); - Director::getInstance()->getRenderer()->addCommand(&_quadCommand); + _batchCommand.init(0, + _vertexZ, + _textureAtlas->getTexture()->getName(), + _shaderProgram, + _blendFunc, + _textureAtlas, + _modelViewTransform); + Director::getInstance()->getRenderer()->addCommand(&_batchCommand); } void SpriteBatchNode::increaseAtlasCapacity(void) diff --git a/cocos/2d/CCSpriteBatchNode.h b/cocos/2d/CCSpriteBatchNode.h index fc140aa391..bbb6294e6d 100644 --- a/cocos/2d/CCSpriteBatchNode.h +++ b/cocos/2d/CCSpriteBatchNode.h @@ -35,7 +35,7 @@ THE SOFTWARE. #include "CCProtocols.h" #include "CCTextureAtlas.h" #include "ccMacros.h" -#include "renderer/CCQuadCommand.h" +#include "renderer/CCBatchCommand.h" NS_CC_BEGIN @@ -189,7 +189,7 @@ protected: TextureAtlas *_textureAtlas; BlendFunc _blendFunc; - QuadCommand _quadCommand; // quad command + BatchCommand _batchCommand; // render command // all descendants: children, grand children, etc... // There is not need to retain/release these objects, since they are already retained by _children diff --git a/cocos/2d/renderer/CCCustomCommand.cpp b/cocos/2d/renderer/CCCustomCommand.cpp index 790bd13e69..b0c39f2049 100644 --- a/cocos/2d/renderer/CCCustomCommand.cpp +++ b/cocos/2d/renderer/CCCustomCommand.cpp @@ -27,8 +27,7 @@ NS_CC_BEGIN CustomCommand::CustomCommand() -:RenderCommand() -, func(nullptr) +: func(nullptr) , _viewport(0) , _depth(0) { diff --git a/cocos/2d/renderer/CCGroupCommand.cpp b/cocos/2d/renderer/CCGroupCommand.cpp index 8bd6f85888..4f7707cd76 100644 --- a/cocos/2d/renderer/CCGroupCommand.cpp +++ b/cocos/2d/renderer/CCGroupCommand.cpp @@ -86,8 +86,7 @@ void GroupCommandManager::releaseGroupID(int groupID) } GroupCommand::GroupCommand() -:RenderCommand() -, _viewport(0) +: _viewport(0) , _depth(0) { _type = RenderCommand::Type::GROUP_COMMAND; diff --git a/cocos/2d/renderer/CCQuadCommand.cpp b/cocos/2d/renderer/CCQuadCommand.cpp index f60446871c..a19e3f7053 100644 --- a/cocos/2d/renderer/CCQuadCommand.cpp +++ b/cocos/2d/renderer/CCQuadCommand.cpp @@ -29,8 +29,7 @@ NS_CC_BEGIN QuadCommand::QuadCommand() -:RenderCommand() -,_viewport(0) +:_viewport(0) ,_depth(0) ,_textureID(0) ,_blendType(BlendFunc::DISABLE) diff --git a/cocos/2d/renderer/CCRenderCommand.h b/cocos/2d/renderer/CCRenderCommand.h index 930ed1ecde..7b6ec54e0c 100644 --- a/cocos/2d/renderer/CCRenderCommand.h +++ b/cocos/2d/renderer/CCRenderCommand.h @@ -42,6 +42,7 @@ public: { QUAD_COMMAND, CUSTOM_COMMAND, + BATCH_COMMAND, GROUP_COMMAND, UNKNOWN_COMMAND, }; diff --git a/cocos/2d/renderer/CCRenderer.cpp b/cocos/2d/renderer/CCRenderer.cpp index 5c97dfdae4..4454f1480f 100644 --- a/cocos/2d/renderer/CCRenderer.cpp +++ b/cocos/2d/renderer/CCRenderer.cpp @@ -27,6 +27,7 @@ #include "ccGLStateCache.h" #include "CCCustomCommand.h" #include "renderer/CCQuadCommand.h" +#include "renderer/CCBatchCommand.h" #include "CCGroupCommand.h" #include "CCConfiguration.h" #include "CCDirector.h" @@ -267,6 +268,12 @@ void Renderer::render() CustomCommand* cmd = static_cast(command); cmd->execute(); } + else if(commandType == RenderCommand::Type::BATCH_COMMAND) + { + flush(); + BatchCommand* cmd = static_cast(command); + cmd->execute(); + } else if(commandType == RenderCommand::Type::GROUP_COMMAND) { flush(); From ae84650713ea3cbaf8426b45e721d5cef0cd1e98 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 15 Jan 2014 16:09:38 -0800 Subject: [PATCH 096/193] Updates CHANGELOG --- CHANGELOG | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index 3b3b55d33e..14a94ba772 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -2,12 +2,14 @@ cocos2d-x-3.0final ?.? ? [All] [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. + [NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10% [FIX] Console: log(format, va_args) is private to prevent possible resolution errors [FIX] Configuration: dumpInfo() -> getInfo() [FIX] ControlSlider doesn't support to set selected thumb sprite. [FIX] ControlButton doesn't support to set scale ratio of touchdown state. [FIX] Particles: Crash was triggered if there is not `textureFileName`section in particle plist file. [FIX] Renderer: QuadCommand::init() does not copy the Quads, it only store a reference making the code faster + [FIX] Renderer: Performance improved in Sprite and SpriteBatchNode (and subclasses) sprites in about 20% [FIX] Tests: TestCpp works with CMake on Windows. [FIX] Tests: Sprites Performance Test has 3 new tests [FIX] TextureCache: getTextureForKey and removeTextureForKey work as expected From a410c38e5433097227779443d99abcc20e6a0fce Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 16 Jan 2014 09:55:13 +0800 Subject: [PATCH 097/193] Update VS project file. --- cocos/2d/cocos2d.vcxproj | 2 ++ cocos/2d/cocos2d.vcxproj.filters | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index 90be6eac6d..95f7f385fd 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -317,6 +317,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou + @@ -521,6 +522,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou + diff --git a/cocos/2d/cocos2d.vcxproj.filters b/cocos/2d/cocos2d.vcxproj.filters index b57af69e45..6c887936b6 100644 --- a/cocos/2d/cocos2d.vcxproj.filters +++ b/cocos/2d/cocos2d.vcxproj.filters @@ -598,6 +598,9 @@ renderer + + renderer + @@ -1207,5 +1210,8 @@ renderer + + renderer + \ No newline at end of file From 5ef9eef0aee88a747b62f39de676d4d61a12babe Mon Sep 17 00:00:00 2001 From: hbb Date: Thu, 16 Jan 2014 10:09:04 +0800 Subject: [PATCH 098/193] use data.isNull() instead of !data.getBytes() --- cocos/2d/platform/CCFileUtils.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/platform/CCFileUtils.cpp b/cocos/2d/platform/CCFileUtils.cpp index 1434eea8e6..77988ff696 100644 --- a/cocos/2d/platform/CCFileUtils.cpp +++ b/cocos/2d/platform/CCFileUtils.cpp @@ -547,7 +547,7 @@ static Data getData(const std::string& filename, bool forString) std::string FileUtils::getStringFromFile(const std::string& filename) { Data data = getData(filename, true); - if (! data.getBytes()) + if (data.isNull()) return ""; std::string ret((const char*)data.getBytes()); return ret; From f62c041886df8469706bf793cc132254fa69a455 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 16 Jan 2014 10:27:35 +0800 Subject: [PATCH 099/193] Compilation fix: Updates cocos_files.json and removes unused in template. --- .../multi-platform-cpp/proj.linux/build.sh | 26 ------------------ .../multi-platform-lua/proj.linux/build.sh | 27 ------------------- .../module/cocos_files.json.REMOVED.git-id | 2 +- 3 files changed, 1 insertion(+), 54 deletions(-) delete mode 100755 template/multi-platform-cpp/proj.linux/build.sh delete mode 100755 template/multi-platform-lua/proj.linux/build.sh diff --git a/template/multi-platform-cpp/proj.linux/build.sh b/template/multi-platform-cpp/proj.linux/build.sh deleted file mode 100755 index 99dcf294d3..0000000000 --- a/template/multi-platform-cpp/proj.linux/build.sh +++ /dev/null @@ -1,26 +0,0 @@ -#!/bin/bash - -# Exit on error -set -e - -rm -rf ../bin -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" - -#make global libs -cd ../cocos2d -#install depend libs -sudo ./build/install-deps-linux.sh -mkdir -p linux-build -cd linux-build -cmake .. -DBUILD_LIBS_LUA=OFF -DBUILD_HelloCpp=OFF -DBUILD_TestCpp=OFF -DBUILD_HelloLua=OFF -DBUILD_TestLua=OFF -make -j4 - -#make bin -cd $DIR -rm -rf bin -mkdir -p build -cd build -cmake ../.. -make -j4 -cd .. -mv ../bin bin diff --git a/template/multi-platform-lua/proj.linux/build.sh b/template/multi-platform-lua/proj.linux/build.sh deleted file mode 100755 index d1408e62a4..0000000000 --- a/template/multi-platform-lua/proj.linux/build.sh +++ /dev/null @@ -1,27 +0,0 @@ -#!/bin/bash - -# Exit on error -set -e - -rm -rf ../bin -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" - -#make global libs -cd ../cocos2d -#install depend libs -sudo ./build/install-deps-linux.sh -mkdir -p linux-build -cd linux-build -cmake .. -DBUILD_HelloCpp=OFF -DBUILD_TestCpp=OFF -DBUILD_HelloLua=OFF -DBUILD_TestLua=OFF -make -j4 - -#make bin -cd $DIR -rm -rf bin -mkdir -p build -cd build -cmake ../.. -make -j4 -cd .. -mv ../bin bin -cp ../cocos2d/cocos/scripting/lua/script/* bin/Resources diff --git a/tools/project-creator/module/cocos_files.json.REMOVED.git-id b/tools/project-creator/module/cocos_files.json.REMOVED.git-id index 38b25afe6d..681e527955 100644 --- a/tools/project-creator/module/cocos_files.json.REMOVED.git-id +++ b/tools/project-creator/module/cocos_files.json.REMOVED.git-id @@ -1 +1 @@ -0a2d046187d7848172fadf6ee4a7e80897e6a75c \ No newline at end of file +5ae50c3f2080b46e18ba3f5aee4c5c686d54e13a \ No newline at end of file From 9b490a91240aa27863ebc3629f4b94a6619d036a Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 15 Jan 2014 18:37:07 -0800 Subject: [PATCH 100/193] Sprite: removed _hasChildren _hasChildren has been replaced with !_children.empty() --- CHANGELOG | 3 ++- cocos/2d/CCSprite.cpp | 36 ++++++++++++++---------------------- cocos/2d/CCSprite.h | 1 - 3 files changed, 16 insertions(+), 24 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 14a94ba772..fe83aa6b50 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -9,7 +9,8 @@ cocos2d-x-3.0final ?.? ? [FIX] ControlButton doesn't support to set scale ratio of touchdown state. [FIX] Particles: Crash was triggered if there is not `textureFileName`section in particle plist file. [FIX] Renderer: QuadCommand::init() does not copy the Quads, it only store a reference making the code faster - [FIX] Renderer: Performance improved in Sprite and SpriteBatchNode (and subclasses) sprites in about 20% + [FIX] Renderer: Performance improved in Sprite and SpriteBatchNode (and subclasses) sprites in about 20% + [FIX] Sprite: removed _hasChildren optimization. It uses !_children.empty() now which is super fast as well [FIX] Tests: TestCpp works with CMake on Windows. [FIX] Tests: Sprites Performance Test has 3 new tests [FIX] TextureCache: getTextureForKey and removeTextureForKey work as expected diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 271f1e8db9..8bf5a3d1b1 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -242,9 +242,7 @@ bool Sprite::initWithTexture(Texture2D *texture, const Rect& rect, bool rotated) // zwoptex default values _offsetPosition = Point::ZERO; - - _hasChildren = false; - + // clean the Quad memset(&_quad, 0, sizeof(_quad)); @@ -767,7 +765,6 @@ void Sprite::addChild(Node *child, int zOrder, int tag) } //CCNode already sets isReorderChildDirty_ so this needs to be after batchNode check Node::addChild(child, zOrder, tag); - _hasChildren = true; } void Sprite::reorderChild(Node *child, int zOrder) @@ -813,8 +810,6 @@ void Sprite::removeAllChildrenWithCleanup(bool cleanup) } Node::removeAllChildrenWithCleanup(cleanup); - - _hasChildren = false; } void Sprite::sortAllChildren() @@ -882,27 +877,24 @@ void Sprite::setDirtyRecursively(bool bValue) { _recursiveDirty = bValue; setDirty(bValue); - // recursively set dirty - if (_hasChildren) - { - for(const auto &child: _children) { - Sprite* sp = dynamic_cast(child); - if (sp) - { - sp->setDirtyRecursively(true); - } + + for(const auto &child: _children) { + Sprite* sp = dynamic_cast(child); + if (sp) + { + sp->setDirtyRecursively(true); } } } // XXX HACK: optimization -#define SET_DIRTY_RECURSIVELY() { \ - if (! _recursiveDirty) { \ - _recursiveDirty = true; \ - setDirty(true); \ - if ( _hasChildren) \ - setDirtyRecursively(true); \ - } \ +#define SET_DIRTY_RECURSIVELY() { \ + if (! _recursiveDirty) { \ + _recursiveDirty = true; \ + setDirty(true); \ + if (!_children.empty()) \ + setDirtyRecursively(true); \ + } \ } void Sprite::setPosition(const Point& pos) diff --git a/cocos/2d/CCSprite.h b/cocos/2d/CCSprite.h index 0a937a64e1..2081ef8336 100644 --- a/cocos/2d/CCSprite.h +++ b/cocos/2d/CCSprite.h @@ -538,7 +538,6 @@ protected: bool _dirty; /// Whether the sprite needs to be updated bool _recursiveDirty; /// Whether all of the sprite's children needs to be updated - bool _hasChildren; /// Whether the sprite contains children bool _shouldBeHidden; /// should not be drawn because one of the ancestors is not visible kmMat4 _transformToBatch; From c6445b0640d7117cf6eb013f6306bfedf0a5fedf Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 16 Jan 2014 10:41:04 +0800 Subject: [PATCH 101/193] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index fe83aa6b50..da8bce53e1 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ cocos2d-x-3.0final ?.? ? [All] + [NEW] Label: Uses a struct of TTF configuration for Label::createWithTTF to reduce parameters and make this interface more easily to use. [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. [NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10% From beb7015d7e0ff62f72273265f320c77d29f87594 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Thu, 16 Jan 2014 02:43:13 +0000 Subject: [PATCH 102/193] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index bab1d8a7c5..74cb897b64 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit bab1d8a7c5d8b29f14c8dc19158a8bb994f0e970 +Subproject commit 74cb897b64f7325cf969341e9bc2d87fc7fb1bb7 From 3b20ad5ab7c8f36a96add7bdfed67f5e3d46ab76 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Wed, 15 Jan 2014 19:10:40 -0800 Subject: [PATCH 103/193] More renderer optimizations --- cocos/2d/renderer/CCRenderCommand.h | 7 ++--- cocos/2d/renderer/CCRenderer.cpp | 40 ++++++----------------------- 2 files changed, 12 insertions(+), 35 deletions(-) diff --git a/cocos/2d/renderer/CCRenderCommand.h b/cocos/2d/renderer/CCRenderCommand.h index 7b6ec54e0c..887d717d7e 100644 --- a/cocos/2d/renderer/CCRenderCommand.h +++ b/cocos/2d/renderer/CCRenderCommand.h @@ -50,9 +50,10 @@ public: virtual int64_t generateID() = 0; /** Get Render Command Id */ - virtual inline int64_t getID() { return _id; } - - virtual inline Type getType() { return _type; } + inline int64_t getID() { return _id; } + + /** Returns the Command type */ + inline Type getType() { return _type; } protected: RenderCommand(); diff --git a/cocos/2d/renderer/CCRenderer.cpp b/cocos/2d/renderer/CCRenderer.cpp index 4454f1480f..15da8cfbdd 100644 --- a/cocos/2d/renderer/CCRenderer.cpp +++ b/cocos/2d/renderer/CCRenderer.cpp @@ -333,41 +333,17 @@ void Renderer::convertToWorldCoordiantes(V3F_C4B_T2F_Quad* quads, ssize_t quanti for(ssize_t i=0; ibl.vertices.x; - vec1.y = q->bl.vertices.y; - vec1.z = q->bl.vertices.z; - kmVec3Transform(&out1, &vec1, &modelView); - q->bl.vertices.x = out1.x; - q->bl.vertices.y = out1.y; - q->bl.vertices.z = out1.z; + kmVec3 *vec1 = (kmVec3*)&q->bl.vertices; + kmVec3Transform(vec1, vec1, &modelView); - kmVec3 vec2, out2; - vec2.x = q->br.vertices.x; - vec2.y = q->br.vertices.y; - vec2.z = q->br.vertices.z; - kmVec3Transform(&out2, &vec2, &modelView); - q->br.vertices.x = out2.x; - q->br.vertices.y = out2.y; - q->br.vertices.z = out2.z; + kmVec3 *vec2 = (kmVec3*)&q->br.vertices; + kmVec3Transform(vec2, vec2, &modelView); - kmVec3 vec3, out3; - vec3.x = q->tr.vertices.x; - vec3.y = q->tr.vertices.y; - vec3.z = q->tr.vertices.z; - kmVec3Transform(&out3, &vec3, &modelView); - q->tr.vertices.x = out3.x; - q->tr.vertices.y = out3.y; - q->tr.vertices.z = out3.z; + kmVec3 *vec3 = (kmVec3*)&q->tr.vertices; + kmVec3Transform(vec3, vec3, &modelView); - kmVec3 vec4, out4; - vec4.x = q->tl.vertices.x; - vec4.y = q->tl.vertices.y; - vec4.z = q->tl.vertices.z; - kmVec3Transform(&out4, &vec4, &modelView); - q->tl.vertices.x = out4.x; - q->tl.vertices.y = out4.y; - q->tl.vertices.z = out4.z; + kmVec3 *vec4 = (kmVec3*)&q->tl.vertices; + kmVec3Transform(vec4, vec4, &modelView); } } From 3c816c3c8527dcd9bdddd4418108d099dc3533a9 Mon Sep 17 00:00:00 2001 From: zhangbin Date: Thu, 16 Jan 2014 11:26:23 +0800 Subject: [PATCH 104/193] closed #3723, Make sure the init method of Cocos2dxHelper only invoked once. --- .../src/org/cocos2dx/lib/Cocos2dxHelper.java | 61 ++++++++++--------- 1 file changed, 33 insertions(+), 28 deletions(-) diff --git a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java index e1566df16d..f1e7afb0ed 100644 --- a/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java +++ b/cocos/2d/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java @@ -89,38 +89,43 @@ public class Cocos2dxHelper { jobs.add(r); } + private static boolean sInited = false; public static void init(final Activity activity) { - final ApplicationInfo applicationInfo = activity.getApplicationInfo(); - - initListener(); - - try { - // Get the lib_name from AndroidManifest.xml metadata - ActivityInfo ai = - activity.getPackageManager().getActivityInfo(activity.getIntent().getComponent(), PackageManager.GET_META_DATA); - if (null != ai.metaData) { - String lib_name = ai.metaData.getString(META_DATA_LIB_NAME); - if (null != lib_name) { - System.loadLibrary(lib_name); - } else { - System.loadLibrary(DEFAULT_LIB_NAME); + if (!sInited) { + final ApplicationInfo applicationInfo = activity.getApplicationInfo(); + + initListener(); + + try { + // Get the lib_name from AndroidManifest.xml metadata + ActivityInfo ai = + activity.getPackageManager().getActivityInfo(activity.getIntent().getComponent(), PackageManager.GET_META_DATA); + if (null != ai.metaData) { + String lib_name = ai.metaData.getString(META_DATA_LIB_NAME); + if (null != lib_name) { + System.loadLibrary(lib_name); + } else { + System.loadLibrary(DEFAULT_LIB_NAME); + } } + } catch (PackageManager.NameNotFoundException e) { + throw new RuntimeException("Error getting activity info", e); } - } catch (PackageManager.NameNotFoundException e) { - throw new RuntimeException("Error getting activity info", e); - } + + Cocos2dxHelper.sPackageName = applicationInfo.packageName; + Cocos2dxHelper.sFileDirectory = activity.getFilesDir().getAbsolutePath(); + //Cocos2dxHelper.nativeSetApkPath(applicationInfo.sourceDir); + + Cocos2dxHelper.sCocos2dMusic = new Cocos2dxMusic(activity); + Cocos2dxHelper.sCocos2dSound = new Cocos2dxSound(activity); + Cocos2dxHelper.sAssetManager = activity.getAssets(); + + //Cocos2dxHelper.nativeSetAssetManager(sAssetManager); + Cocos2dxBitmap.setContext(activity); + sActivity = activity; - Cocos2dxHelper.sPackageName = applicationInfo.packageName; - Cocos2dxHelper.sFileDirectory = activity.getFilesDir().getAbsolutePath(); - //Cocos2dxHelper.nativeSetApkPath(applicationInfo.sourceDir); - - Cocos2dxHelper.sCocos2dMusic = new Cocos2dxMusic(activity); - Cocos2dxHelper.sCocos2dSound = new Cocos2dxSound(activity); - Cocos2dxHelper.sAssetManager = activity.getAssets(); - - //Cocos2dxHelper.nativeSetAssetManager(sAssetManager); - Cocos2dxBitmap.setContext(activity); - sActivity = activity; + sInited = true; + } } public static void initListener() { From afe49b3a2bb0c794818e853191067b9782a95c17 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 16 Jan 2014 11:47:06 +0800 Subject: [PATCH 105/193] 1.Fix crash bug when using unknown character 2.Fix text align mistake --- cocos/2d/CCFontAtlas.cpp | 1 + cocos/2d/CCLabelTextFormatter.cpp | 2 -- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index 4d35ce980d..9282956d03 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -100,6 +100,7 @@ bool FontAtlas::getLetterDefinitionForChar(unsigned short letteCharUTF16, FontL } else { + outDefinition.validDefinition = false; return false; } } diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index 956c5c3bb1..b4977c8a92 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -241,8 +241,6 @@ bool LabelTextFormatter::alignText(LabelTextFormatProtocol *theLabel) continue; } int index = static_cast(i + lineLength - 1 + lineNumber); - if(currentChar == 0) - index -= 1; if (index < 0) continue; LetterInfo* info = &leterInfo->at( index ); From f5c93fc9e6d9b9c285d71408e72a478de6ecd176 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 16 Jan 2014 11:55:42 +0800 Subject: [PATCH 106/193] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index da8bce53e1..ce30bb23c5 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ cocos2d-x-3.0final ?.? ? [All] + [FIX] If setting a shorter string than before while using LabelAtlas, the effect will be wrong. [NEW] Label: Uses a struct of TTF configuration for Label::createWithTTF to reduce parameters and make this interface more easily to use. [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. From da32bfd5d7722bc7211d9812dca42d19c844d6dd Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 16 Jan 2014 12:02:37 +0800 Subject: [PATCH 107/193] Update AUTHORS [ci skip] --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index fd5cf6a651..04d52c0ee3 100644 --- a/AUTHORS +++ b/AUTHORS @@ -718,6 +718,9 @@ Developers: Pisces000221 Corrected a few mistakes in the README file of project-creator. + + hbbalfred + Fixed a bug that crash if file doesn't exist when using FileUtils::getStringFromFile. Retired Core Developers: WenSheng Yang From 778292738f09afb2d7c228356c8887e1e9db257a Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 16 Jan 2014 12:03:42 +0800 Subject: [PATCH 108/193] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index ce30bb23c5..f26d648230 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ cocos2d-x-3.0final ?.? ? [All] + [FIX] Crash if file doesn't exist when using FileUtils::getStringFromFile. [FIX] If setting a shorter string than before while using LabelAtlas, the effect will be wrong. [NEW] Label: Uses a struct of TTF configuration for Label::createWithTTF to reduce parameters and make this interface more easily to use. [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands From 18bd9784805433768a51e729d7b79fb3a3a9b493 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 16 Jan 2014 14:37:07 +0800 Subject: [PATCH 109/193] 1.add label crash test 2.fix lose char when label have unknown character. --- cocos/2d/CCLabelTextFormatter.cpp | 12 ++++++--- .../Classes/LabelTest/LabelTestNew.cpp | 25 ++++++++++++++++++- .../TestCpp/Classes/LabelTest/LabelTestNew.h | 10 ++++++++ 3 files changed, 42 insertions(+), 5 deletions(-) diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index b4977c8a92..550d017beb 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -63,20 +63,24 @@ bool LabelTextFormatter::multilineText(LabelTextFormatProtocol *theLabel) { LetterInfo* info = &leterInfo->at(j+skip); - unsigned int justSkipped = 0; + unsigned int justSkipped = 0; while (info->def.validDefinition == false) { justSkipped++; - info = &leterInfo->at( j+skip+justSkipped ); + tIndex = j+skip+justSkipped; + if(tIndex < strLen) + info = &leterInfo->at( tIndex ); + else + break; } skip += justSkipped; tIndex = j + skip; - if (i >= stringLength) + if (tIndex >= stringLength) break; - unsigned short character = strWhole[i]; + unsigned short character = strWhole[tIndex]; if (!isStartOfWord) { diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp index d779ae6a86..2a3334875f 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp @@ -66,7 +66,8 @@ static std::function createFunctions[] = CL(LabelTTFUnicodeNew), CL(LabelBMFontTestNew), CL(LabelTTFDistanceField), - CL(LabelTTFDistanceFieldEffect) + CL(LabelTTFDistanceFieldEffect), + CL(LabelCrashTest) }; #define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) @@ -1242,3 +1243,25 @@ std::string LabelTTFDistanceFieldEffect::subtitle() const { return "Testing effect base on DistanceField"; } + +LabelCrashTest::LabelCrashTest() +{ + auto size = Director::getInstance()->getWinSize(); + + TTFConfig ttfConfig("fonts/arial.ttf", 80, GlyphCollection::DYNAMIC,nullptr,true); + + auto label1 = Label::createWithTTF(ttfConfig,"Test崩溃34324324", TextHAlignment::CENTER, size.width); + label1->setPosition( Point(size.width/2, size.height/2) ); + label1->setAnchorPoint(Point(0.5, 0.5)); + addChild(label1); +} + +std::string LabelCrashTest::title() const +{ + return "New Label Crash Test"; +} + +std::string LabelCrashTest::subtitle() const +{ + return "Should not crash when using unknown character."; +} diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h index ad6b53211c..b0b120b063 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h @@ -347,6 +347,16 @@ public: virtual std::string subtitle() const override; }; +class LabelCrashTest : public AtlasDemoNew +{ +public: + CREATE_FUNC(LabelCrashTest); + + LabelCrashTest(); + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; // we don't support linebreak mode From 4a6e1373893d704f07287b7ea4ca3693a8ea46ce Mon Sep 17 00:00:00 2001 From: andyque Date: Thu, 16 Jan 2014 12:10:41 +0800 Subject: [PATCH 110/193] fixed #3683. fixed convertToWorldSpaceAR of CCSkin returning error coordinate --- .../cocostudio/CCDisplayFactory.cpp | 2 +- cocos/editor-support/cocostudio/CCSkin.cpp | 2 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 16 +++++++++++++++- .../CocoStudioArmatureTest/ArmatureScene.h | 2 ++ 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp index 20f826cb2b..7463ff54ff 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp @@ -115,7 +115,7 @@ void DisplayFactory::updateDisplay(Bone *bone, float dt, bool dirty) anchorPoint = PointApplyTransform(anchorPoint, displayTransform); displayTransform.mat[12] = anchorPoint.x; displayTransform.mat[13] = anchorPoint.y; - kmMat4 t = TransformConcat(displayTransform, bone->getArmature()->getNodeToParentTransform()); + kmMat4 t = TransformConcat( bone->getArmature()->getNodeToParentTransform(),displayTransform); detector->updateTransform(t); } while (0); diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index 94ba291e2b..d26199c205 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -197,7 +197,7 @@ void Skin::updateTransform() kmMat4 Skin::getNodeToWorldTransform() const { - return TransformConcat(_transform, _bone->getArmature()->getNodeToWorldTransform()); + return TransformConcat( _bone->getArmature()->getNodeToWorldTransform(), _transform); } kmMat4 Skin::getNodeToWorldTransformAR() const diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 1349970d67..fdf76c80a0 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -1067,8 +1067,22 @@ void TestColliderDetector::update(float delta) } void TestColliderDetector::draw() { - armature2->drawContour(); + _customCommand.init(0, _vertexZ); + _customCommand.func = CC_CALLBACK_0(TestColliderDetector::onDraw, this); + Director::getInstance()->getRenderer()->addCommand(&_customCommand); } + +void TestColliderDetector::onDraw() +{ + kmMat4 oldMat; + kmGLGetMatrix(KM_GL_MODELVIEW, &oldMat); + kmGLLoadMatrix(&_modelViewTransform); + + armature2->drawContour(); + + kmGLLoadMatrix(&oldMat); +} + #endif diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h index c3b64debb9..9a07cc0d5d 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h @@ -271,6 +271,7 @@ public: virtual std::string title() const override; virtual void update(float delta); virtual void draw(); + void onDraw(); void onFrameEvent(cocostudio::Bone *bone, const std::string& evt, int originFrameIndex, int currentFrameIndex); @@ -278,6 +279,7 @@ public: cocostudio::Armature *armature; cocostudio::Armature *armature2; + CustomCommand _customCommand; //new render needed this for drawing primitives cocos2d::Sprite *bullet; }; #endif From 547ab3ef0a100bb3ab969af1a60c06240b6e9404 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 16 Jan 2014 15:07:20 +0800 Subject: [PATCH 111/193] update subtitle. --- samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp index 2a3334875f..c28585dfbe 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp @@ -1250,7 +1250,7 @@ LabelCrashTest::LabelCrashTest() TTFConfig ttfConfig("fonts/arial.ttf", 80, GlyphCollection::DYNAMIC,nullptr,true); - auto label1 = Label::createWithTTF(ttfConfig,"Test崩溃34324324", TextHAlignment::CENTER, size.width); + auto label1 = Label::createWithTTF(ttfConfig,"Test崩溃123", TextHAlignment::CENTER, size.width); label1->setPosition( Point(size.width/2, size.height/2) ); label1->setAnchorPoint(Point(0.5, 0.5)); addChild(label1); @@ -1263,5 +1263,5 @@ std::string LabelCrashTest::title() const std::string LabelCrashTest::subtitle() const { - return "Should not crash when using unknown character."; + return "Not crash and show [Test123] when using unknown character."; } From 9de4c4fa70f7f00e77bcf77035b75cc27afd8222 Mon Sep 17 00:00:00 2001 From: heliclei Date: Thu, 16 Jan 2014 15:16:12 +0800 Subject: [PATCH 112/193] [jenkins]add job trigger,to update github pull request status instantly --- tools/jenkins-scripts/job-trigger.py | 79 ++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100755 tools/jenkins-scripts/job-trigger.py diff --git a/tools/jenkins-scripts/job-trigger.py b/tools/jenkins-scripts/job-trigger.py new file mode 100755 index 0000000000..5641f26862 --- /dev/null +++ b/tools/jenkins-scripts/job-trigger.py @@ -0,0 +1,79 @@ +#Github pull reqest builder for Jenkins + +import json +import re +import os +import requests +import sys +import traceback + +def main(): + #get payload from os env + payload_str = os.environ['payload'] + #parse to json obj + payload = json.loads(payload_str) + + #get pull number + pr_num = payload['number'] + print 'pr_num:' + str(pr_num) + + #build for pull request action 'open' and 'synchronize', skip 'close' + action = payload['action'] + print 'action: ' + action + + pr = payload['pull_request'] + + url = pr['html_url'] + print "url:" + url + + #get statuses url + statuses_url = pr['statuses_url'] + + #get pr target branch + branch = pr['base']['ref'] + + #set commit status to pending + target_url = os.environ['BUILD_URL'] + + if(action == 'closed'): + print 'pull request #' + str(pr_num) + ' is '+action+', no build triggered' + return(0) + + r = requests.get(pr['url']+"/commits") + commits = r.json() + last_commit = commits[len(commits)-1] + message = last_commit['commit']['message'] + + pattern = re.compile("\[ci(\s+)skip\]", re.I) + result = pattern.search(message) + if result is not None: + print 'skip build for pull request #' + str(pr_num) + return(0) + + data = {"state":"pending", "target_url":target_url} + access_token = os.environ['GITHUB_ACCESS_TOKEN'] + Headers = {"Authorization":"token " + access_token} + + try: + requests.post(statuses_url, data=json.dumps(data), headers=Headers) + except: + traceback.print_exc() + + job_trigger_url = os.environ['JOB_TRIGGER_URL']+access_token + #send trigger and payload + post_data = {'payload':""} + post_data['payload']= payload_str + requests.post(job_trigger_url, data=post_data) + + return(0) + +# -------------- main -------------- +if __name__ == '__main__': + sys_ret = 0 + try: + sys_ret = main() + except: + traceback.print_exc() + sys_ret = 1 + finally: + sys.exit(sys_ret) From 93beb44150a1333f1ccbe3dbeef75766c35f9ee2 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 16 Jan 2014 15:35:46 +0800 Subject: [PATCH 113/193] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index f26d648230..6cb0cd676d 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ cocos2d-x-3.0final ?.? ? [All] + [FIX] CocoStudio: TestColliderDetector in ArmatureTest can't work. [FIX] Crash if file doesn't exist when using FileUtils::getStringFromFile. [FIX] If setting a shorter string than before while using LabelAtlas, the effect will be wrong. [NEW] Label: Uses a struct of TTF configuration for Label::createWithTTF to reduce parameters and make this interface more easily to use. From 191fc763f6acc14f9f68cfa2b72739804fc8fcad Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 16 Jan 2014 16:12:15 +0800 Subject: [PATCH 114/193] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 6cb0cd676d..1e783721d9 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -4,6 +4,7 @@ cocos2d-x-3.0final ?.? ? [FIX] Crash if file doesn't exist when using FileUtils::getStringFromFile. [FIX] If setting a shorter string than before while using LabelAtlas, the effect will be wrong. [NEW] Label: Uses a struct of TTF configuration for Label::createWithTTF to reduce parameters and make this interface more easily to use. + [FIX] Label: Label::createWithTTF crashes when using unknown characters. [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. [NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10% From 925a4f0f30a4cedbf395a300f44bf003106723be Mon Sep 17 00:00:00 2001 From: heliclei Date: Thu, 16 Jan 2014 16:22:04 +0800 Subject: [PATCH 115/193] add reopen support --- tools/jenkins-scripts/pull-request-builder.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/jenkins-scripts/pull-request-builder.py b/tools/jenkins-scripts/pull-request-builder.py index 3f258e4401..0b0733639b 100755 --- a/tools/jenkins-scripts/pull-request-builder.py +++ b/tools/jenkins-scripts/pull-request-builder.py @@ -57,7 +57,7 @@ def main(): set_description(pr_desc, target_url) - if((action != 'opened') and (action != 'synchronize')): + if(action == 'closed'): print 'pull request #' + str(pr_num) + ' is '+action+', no build triggered' return(0) From a765e5e7e1d54cc9f2557734693d6cf1f2d05ea2 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 16 Jan 2014 16:37:29 +0800 Subject: [PATCH 116/193] closed #3628:Integrate LabelAtlas with new Label --- cocos/2d/CCFont.cpp | 16 ++ cocos/2d/CCFont.h | 4 + cocos/2d/CCFontAtlasCache.cpp | 59 ++++++ cocos/2d/CCFontAtlasCache.h | 4 + cocos/2d/CCFontAtlasFactory.cpp | 42 +++++ cocos/2d/CCFontAtlasFactory.h | 4 + cocos/2d/CCFontCharMap.cpp | 171 ++++++++++++++++++ cocos/2d/CCFontCharMap.h | 69 +++++++ cocos/2d/CCLabel.cpp | 87 +++++++++ cocos/2d/CCLabel.h | 18 +- cocos/2d/cocos2d.vcxproj | 2 + cocos/2d/cocos2d.vcxproj.filters | 6 + .../Classes/LabelTest/LabelTestNew.cpp | 47 +++++ .../TestCpp/Classes/LabelTest/LabelTestNew.h | 16 ++ 14 files changed, 540 insertions(+), 5 deletions(-) create mode 100644 cocos/2d/CCFontCharMap.cpp create mode 100644 cocos/2d/CCFontCharMap.h diff --git a/cocos/2d/CCFont.cpp b/cocos/2d/CCFont.cpp index dc363cfe02..1c2d3bab86 100644 --- a/cocos/2d/CCFont.cpp +++ b/cocos/2d/CCFont.cpp @@ -28,6 +28,7 @@ #include "CCFontFNT.h" #include "CCFontFreeType.h" +#include "CCFontCharMap.h" #include "edtaa3func.h" NS_CC_BEGIN @@ -116,6 +117,21 @@ Font* Font::createWithFNT(const std::string& fntFilePath) return FontFNT::create(fntFilePath); } +Font* Font::createWithCharMap(const std::string& plistFile) +{ + return FontCharMap::create(plistFile); +} + +Font* Font::createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) +{ + return FontCharMap::create(texture,itemWidth,itemHeight,startCharMap); +} + +Font* Font::createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +{ + return FontCharMap::create(charMapFile,itemWidth,itemHeight,startCharMap); +} + unsigned char * Font::makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height) { unsigned int pixelAmount = (width + 2 * DistanceMapSpread) * (height + 2 * DistanceMapSpread); diff --git a/cocos/2d/CCFont.h b/cocos/2d/CCFont.h index 440da0808b..abbbf0098d 100644 --- a/cocos/2d/CCFont.h +++ b/cocos/2d/CCFont.h @@ -45,6 +45,10 @@ public: // create the font static Font* createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); static Font* createWithFNT(const std::string& fntFilePath); + + static Font * createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + static Font * createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); + static Font * createWithCharMap(const std::string& plistFile); static unsigned char * makeDistanceMap(unsigned char *img, unsigned int width, unsigned int height); void setDistanceFieldEnabled(bool distanceFieldEnabled); diff --git a/cocos/2d/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp index ccea76b254..3850791f7d 100644 --- a/cocos/2d/CCFontAtlasCache.cpp +++ b/cocos/2d/CCFontAtlasCache.cpp @@ -69,6 +69,65 @@ FontAtlas * FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName) return tempAtlas; } +FontAtlas * FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile) +{ + std::string atlasName = generateFontName(plistFile, 0, GlyphCollection::CUSTOM,false); + FontAtlas *tempAtlas = _atlasMap[atlasName]; + + if ( !tempAtlas ) + { + tempAtlas = FontAtlasFactory::createAtlasFromCharMap(plistFile); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + tempAtlas->retain(); + } + + return tempAtlas; +} + +FontAtlas * FontAtlasCache::getFontAtlasCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) +{ + char tmp[30]; + sprintf_s(tmp,"name:%u_%d_%d_%d",texture->getName(),itemWidth,itemHeight,startCharMap); + std::string atlasName = generateFontName(tmp, 0, GlyphCollection::CUSTOM,false); + FontAtlas *tempAtlas = _atlasMap[atlasName]; + + if ( !tempAtlas ) + { + tempAtlas = FontAtlasFactory::createAtlasFromCharMap(texture,itemWidth,itemHeight,startCharMap); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + tempAtlas->retain(); + } + + return tempAtlas; +} + +FontAtlas * FontAtlasCache::getFontAtlasCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +{ + std::string atlasName = generateFontName(charMapFile, 0, GlyphCollection::CUSTOM,false); + FontAtlas *tempAtlas = _atlasMap[atlasName]; + + if ( !tempAtlas ) + { + tempAtlas = FontAtlasFactory::createAtlasFromCharMap(charMapFile,itemWidth,itemHeight,startCharMap); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + tempAtlas->retain(); + } + + return tempAtlas; +} + std::string FontAtlasCache::generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField) { std::string tempName(fontFileName); diff --git a/cocos/2d/CCFontAtlasCache.h b/cocos/2d/CCFontAtlasCache.h index bdc7dd24d1..f9e84ba904 100644 --- a/cocos/2d/CCFontAtlasCache.h +++ b/cocos/2d/CCFontAtlasCache.h @@ -41,6 +41,10 @@ public: static FontAtlas * getFontAtlasTTF(const std::string& fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false); static FontAtlas * getFontAtlasFNT(const std::string& fontFileName); + + static FontAtlas * getFontAtlasCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + static FontAtlas * getFontAtlasCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); + static FontAtlas * getFontAtlasCharMap(const std::string& plistFile); static bool releaseFontAtlas(FontAtlas *atlas); diff --git a/cocos/2d/CCFontAtlasFactory.cpp b/cocos/2d/CCFontAtlasFactory.cpp index c9d3ebbb3b..3b6d536223 100644 --- a/cocos/2d/CCFontAtlasFactory.cpp +++ b/cocos/2d/CCFontAtlasFactory.cpp @@ -60,4 +60,46 @@ FontAtlas * FontAtlasFactory::createAtlasFromFNT(const std::string& fntFilePath) } } +FontAtlas * FontAtlasFactory::createAtlasFromCharMap(const std::string& plistFile) +{ + Font *font = Font::createWithCharMap(plistFile); + + if(font) + { + return font->createFontAtlas(); + } + else + { + return nullptr; + } +} + +FontAtlas * FontAtlasFactory::createAtlasFromCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) +{ + Font *font = Font::createWithCharMap(texture,itemWidth,itemHeight,startCharMap); + + if(font) + { + return font->createFontAtlas(); + } + else + { + return nullptr; + } +} + +FontAtlas * FontAtlasFactory::createAtlasFromCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +{ + Font *font = Font::createWithCharMap(charMapFile,itemWidth,itemHeight,startCharMap); + + if(font) + { + return font->createFontAtlas(); + } + else + { + return nullptr; + } +} + NS_CC_END diff --git a/cocos/2d/CCFontAtlasFactory.h b/cocos/2d/CCFontAtlasFactory.h index 2a10cc8d63..095ad134ec 100644 --- a/cocos/2d/CCFontAtlasFactory.h +++ b/cocos/2d/CCFontAtlasFactory.h @@ -39,6 +39,10 @@ public: static FontAtlas * createAtlasFromTTF(const std::string& fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false); static FontAtlas * createAtlasFromFNT(const std::string& fntFilePath); + + static FontAtlas * createAtlasFromCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + static FontAtlas * createAtlasFromCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); + static FontAtlas * createAtlasFromCharMap(const std::string& plistFile); private: }; diff --git a/cocos/2d/CCFontCharMap.cpp b/cocos/2d/CCFontCharMap.cpp new file mode 100644 index 0000000000..217312762b --- /dev/null +++ b/cocos/2d/CCFontCharMap.cpp @@ -0,0 +1,171 @@ +/**************************************************************************** + Copyright (c) 2013 Zynga Inc. + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#include "CCFontCharMap.h" +#include "CCFontAtlas.h" + +NS_CC_BEGIN + +FontCharMap * FontCharMap::create(const std::string& plistFile) +{ + std::string pathStr = FileUtils::getInstance()->fullPathForFilename(plistFile); + std::string relPathStr = pathStr.substr(0, pathStr.find_last_of("/"))+"/"; + + ValueMap dict = FileUtils::getInstance()->getValueMapFromFile(pathStr.c_str()); + + CCASSERT(dict["version"].asInt() == 1, "Unsupported version. Upgrade cocos2d version"); + + std::string textureFilename = relPathStr + dict["textureFilename"].asString(); + + unsigned int width = dict["itemWidth"].asInt() / CC_CONTENT_SCALE_FACTOR(); + unsigned int height = dict["itemHeight"].asInt() / CC_CONTENT_SCALE_FACTOR(); + unsigned int startChar = dict["firstChar"].asInt(); + + Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(textureFilename); + if (!tempTexture) + { + return nullptr; + } + + FontCharMap *tempFont = new FontCharMap(tempTexture,width,height,startChar); + + if (!tempFont) + { + return nullptr; + } + tempFont->autorelease(); + return tempFont; +} + +FontCharMap* FontCharMap::create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +{ + Texture2D *tempTexture = Director::getInstance()->getTextureCache()->addImage(charMapFile); + + if (!tempTexture) + { + return nullptr; + } + + FontCharMap *tempFont = new FontCharMap(tempTexture,itemWidth,itemHeight,startCharMap); + + if (!tempFont) + { + return nullptr; + } + tempFont->autorelease(); + return tempFont; +} + +FontCharMap* FontCharMap::create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) +{ + FontCharMap *tempFont = new FontCharMap(texture,itemWidth,itemHeight,startCharMap); + + if (!tempFont) + { + return nullptr; + } + tempFont->autorelease(); + return tempFont; +} + +FontCharMap::~FontCharMap() +{ + +} + +Size * FontCharMap::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const +{ + if (!text) + return 0; + + outNumLetters = cc_wcslen(text); + + if (!outNumLetters) + return 0; + + Size *sizes = new Size[outNumLetters]; + if (!sizes) + return 0; + + int advance = _itemWidth * CC_CONTENT_SCALE_FACTOR(); + for (int c = 0; c < outNumLetters; ++c) + { + sizes[c].width = advance; + } + + return sizes; +} + +Rect FontCharMap::getRectForChar(unsigned short theChar) const +{ + return _charRect; +} + +FontAtlas * FontCharMap::createFontAtlas() +{ + FontAtlas *tempAtlas = new FontAtlas(*this); + if (!tempAtlas) + return nullptr; + + Size s = _texture->getContentSize(); + + int itemsPerColumn = (int)(s.height / _itemHeight); + int itemsPerRow = (int)(s.width / _itemWidth); + + tempAtlas->setCommonLineHeight(_itemHeight); + + FontLetterDefinition tempDefinition; + tempDefinition.textureID = 0; + tempDefinition.anchorX = 0.5f; + tempDefinition.anchorY = 0.5f; + tempDefinition.offsetX = 0.0f; + tempDefinition.offsetY = 0.0f; + tempDefinition.validDefinition = true; + tempDefinition.width = _itemWidth; + tempDefinition.height = _itemHeight; + + int charId = _mapStartChar; + float itemWidthInPixels = _itemWidth * CC_CONTENT_SCALE_FACTOR(); + float itemHeightInPixels = _itemHeight * CC_CONTENT_SCALE_FACTOR(); + for (int row = 0; row < itemsPerColumn; ++row) + { + for (int col = 0; col < itemsPerRow; ++col) + { + tempDefinition.letteCharUTF16 = charId; + + tempDefinition.U = _itemWidth * col; + tempDefinition.V = _itemHeight * row; + + tempAtlas->addLetterDefinition(tempDefinition); + charId++; + } + } + + tempAtlas->addTexture(*_texture,0); + + return tempAtlas; +} + +NS_CC_END \ No newline at end of file diff --git a/cocos/2d/CCFontCharMap.h b/cocos/2d/CCFontCharMap.h new file mode 100644 index 0000000000..f77c855c08 --- /dev/null +++ b/cocos/2d/CCFontCharMap.h @@ -0,0 +1,69 @@ +/**************************************************************************** + Copyright (c) 2013 Zynga Inc. + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +#ifndef _CCFontCharMap_h_ +#define _CCFontCharMap_h_ + +#include "cocos2d.h" +#include "CCFont.h" + +NS_CC_BEGIN + +class FontCharMap : public Font +{ + +public: + + static FontCharMap * create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + static FontCharMap * create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); + static FontCharMap * create(const std::string& plistFile); + + virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override; + virtual Rect getRectForChar(unsigned short theChar) const override; + virtual FontAtlas *createFontAtlas() override; + +protected: + + FontCharMap(Texture2D* texture,int itemWidth, int itemHeight, int startCharMap) : + _texture(texture),_itemWidth(itemWidth),_itemHeight(itemHeight),_mapStartChar(startCharMap),_charRect(0,0,itemWidth,itemHeight){} + /** + * @js NA + * @lua NA + */ + virtual ~FontCharMap(); + +private: + + Texture2D* _texture; + int _mapStartChar; + int _itemWidth; + int _itemHeight; + + Rect _charRect; +}; + +NS_CC_END + +#endif /* defined(_CCFontCharMap_h_) */ diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index a267a41938..1bd74756e8 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -92,6 +92,93 @@ Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::str } } +Label* Label::createWithCharMap(const std::string& plistFile) +{ + Label *ret = new Label(); + + if (!ret) + return nullptr; + + if (ret->setCharMap(plistFile)) + { + ret->autorelease(); + return ret; + } + else + { + delete ret; + return nullptr; + } +} + +Label* Label::createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) +{ + Label *ret = new Label(); + + if (!ret) + return nullptr; + + if (ret->setCharMap(texture,itemWidth,itemHeight,startCharMap)) + { + ret->autorelease(); + return ret; + } + else + { + delete ret; + return nullptr; + } +} + +Label* Label::createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +{ + Label *ret = new Label(); + + if (!ret) + return nullptr; + + if (ret->setCharMap(charMapFile,itemWidth,itemHeight,startCharMap)) + { + ret->autorelease(); + return ret; + } + else + { + delete ret; + return nullptr; + } +} + +bool Label::setCharMap(const std::string& plistFile) +{ + FontAtlas *newAtlas = FontAtlasCache::getFontAtlasCharMap(plistFile); + + if (!newAtlas) + return false; + + return initWithFontAtlas(newAtlas); +} + +bool Label::setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) +{ + FontAtlas *newAtlas = FontAtlasCache::getFontAtlasCharMap(texture,itemWidth,itemHeight,startCharMap); + + if (!newAtlas) + return false; + + return initWithFontAtlas(newAtlas); +} + +bool Label::setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) +{ + FontAtlas *newAtlas = FontAtlasCache::getFontAtlasCharMap(charMapFile,itemWidth,itemHeight,startCharMap); + + if (!newAtlas) + return false; + + return initWithFontAtlas(newAtlas); +} + Label::Label(FontAtlas *atlas, TextHAlignment alignment, bool useDistanceField,bool useA8Shader) : _reusedLetter(nullptr) , _commonLineHeight(0.0f) diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index 26dcc89f9a..1e312d422d 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -62,12 +62,12 @@ typedef struct _ttfConfig const char *customGlyphs; bool distanceFieldEnabled; - _ttfConfig(const char* filePath,int fontSize = 36, const GlyphCollection& glyphs = GlyphCollection::NEHE, - const char *customGlyphs = nullptr,bool useDistanceField = false) + _ttfConfig(const char* filePath,int size = 36, const GlyphCollection& glyphCollection = GlyphCollection::NEHE, + const char *customGlyphCollection = nullptr,bool useDistanceField = false) :fontFilePath(filePath) - ,fontSize(fontSize) - ,glyphs(glyphs) - ,customGlyphs(customGlyphs) + ,fontSize(size) + ,glyphs(glyphCollection) + ,customGlyphs(customGlyphCollection) ,distanceFieldEnabled(useDistanceField) {} }TTFConfig; @@ -82,10 +82,18 @@ public: static Label* createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment = TextHAlignment::CENTER, int lineWidth = 0); + static Label * createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + static Label * createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); + static Label * createWithCharMap(const std::string& plistFile); + bool setTTFConfig(const TTFConfig& ttfConfig); bool setBMFontFilePath(const std::string& bmfontFilePath); + bool setCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); + bool setCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); + bool setCharMap(const std::string& plistFile); + bool setString(const std::string& text, const TextHAlignment& alignment = TextHAlignment::CENTER, float lineWidth = -1, bool lineBreakWithoutSpaces = false); //only support for TTF diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index 95f7f385fd..9c7bd8f40f 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -248,6 +248,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou + @@ -429,6 +430,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou + diff --git a/cocos/2d/cocos2d.vcxproj.filters b/cocos/2d/cocos2d.vcxproj.filters index 6c887936b6..6a28597e2d 100644 --- a/cocos/2d/cocos2d.vcxproj.filters +++ b/cocos/2d/cocos2d.vcxproj.filters @@ -601,6 +601,9 @@ renderer + + label_nodes + @@ -1213,5 +1216,8 @@ renderer + + label_nodes + \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp index c28585dfbe..604ff0cb8b 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp @@ -67,6 +67,7 @@ static std::function createFunctions[] = CL(LabelBMFontTestNew), CL(LabelTTFDistanceField), CL(LabelTTFDistanceFieldEffect), + CL(LabelCharMapTest), CL(LabelCrashTest) }; @@ -1244,6 +1245,52 @@ std::string LabelTTFDistanceFieldEffect::subtitle() const return "Testing effect base on DistanceField"; } +LabelCharMapTest::LabelCharMapTest() +{ + _time = 0.0f; + + auto label1 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); + addChild(label1, 0, kTagSprite1); + label1->setPosition( Point(10,100) ); + label1->setOpacity( 200 ); + + auto label2 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.plist"); + addChild(label2, 0, kTagSprite2); + label2->setPosition( Point(10,160) ); + label2->setOpacity( 32 ); + + auto label3 = Label::createWithCharMap("fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); + label3->setString("123 Test"); + addChild(label3, 0, kTagSprite3); + label3->setPosition( Point(10,220) ); + + schedule(schedule_selector(LabelCharMapTest::step)); +} + +void LabelCharMapTest::step(float dt) +{ + _time += dt; + char string[12] = {0}; + sprintf(string, "%2.2f Test", _time); + + auto label1 = (Label*)getChildByTag(kTagSprite1); + label1->setString(string); + + auto label2 = (Label*)getChildByTag(kTagSprite2); + sprintf(string, "%d", (int)_time); + label2->setString(string); +} + +std::string LabelCharMapTest::title() const +{ + return "New Label + char map file"; +} + +std::string LabelCharMapTest::subtitle() const +{ + return "Updating label should be fast."; +} + LabelCrashTest::LabelCrashTest() { auto size = Director::getInstance()->getWinSize(); diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h index b0b120b063..45d9374d4c 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.h @@ -347,6 +347,22 @@ public: virtual std::string subtitle() const override; }; +class LabelCharMapTest : public AtlasDemoNew +{ +public: + CREATE_FUNC(LabelCharMapTest); + + LabelCharMapTest(); + + virtual std::string title() const override; + virtual std::string subtitle() const override; + + void step(float dt); + +private: + float _time; +}; + class LabelCrashTest : public AtlasDemoNew { public: From 74870aaf92829e1dc022a2f01f6ee4b094afac87 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 16 Jan 2014 17:21:07 +0800 Subject: [PATCH 117/193] Update CHANGELOG [ci skip] --- CHANGELOG | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG b/CHANGELOG index 1e783721d9..68b9b9ac70 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -4,7 +4,7 @@ cocos2d-x-3.0final ?.? ? [FIX] Crash if file doesn't exist when using FileUtils::getStringFromFile. [FIX] If setting a shorter string than before while using LabelAtlas, the effect will be wrong. [NEW] Label: Uses a struct of TTF configuration for Label::createWithTTF to reduce parameters and make this interface more easily to use. - [FIX] Label: Label::createWithTTF crashes when using unknown characters. + [FIX] Label: Crash when using unknown characters. [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. [NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10% From 671b008f3dd2db6c00d67e0b5a25eb18148202e9 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 16 Jan 2014 17:50:09 +0800 Subject: [PATCH 118/193] fix compiling error cause by sprintf_s. --- cocos/2d/CCFontAtlasCache.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp index 3850791f7d..673c15d38a 100644 --- a/cocos/2d/CCFontAtlasCache.cpp +++ b/cocos/2d/CCFontAtlasCache.cpp @@ -91,7 +91,7 @@ FontAtlas * FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile) FontAtlas * FontAtlasCache::getFontAtlasCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) { char tmp[30]; - sprintf_s(tmp,"name:%u_%d_%d_%d",texture->getName(),itemWidth,itemHeight,startCharMap); + sprintf(tmp,"name:%u_%d_%d_%d",texture->getName(),itemWidth,itemHeight,startCharMap); std::string atlasName = generateFontName(tmp, 0, GlyphCollection::CUSTOM,false); FontAtlas *tempAtlas = _atlasMap[atlasName]; From 53be67c6530457dde0d6483ecded287daa75abda Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Thu, 16 Jan 2014 18:12:53 +0800 Subject: [PATCH 119/193] update project file. --- cocos/2d/Android.mk | 1 + cocos/2d/CMakeLists.txt | 1 + tools/project-creator/module/cocos_files.json.REMOVED.git-id | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 9fca766934..2253bcd7d9 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -47,6 +47,7 @@ CCEventListenerTouch.cpp \ CCEventMouse.cpp \ CCEventTouch.cpp \ CCFont.cpp \ +CCFontCharMap.cpp \ CCFontAtlas.cpp \ CCFontAtlasCache.cpp \ CCFontAtlasFactory.cpp \ diff --git a/cocos/2d/CMakeLists.txt b/cocos/2d/CMakeLists.txt index 8340903c8b..886c2ebc21 100644 --- a/cocos/2d/CMakeLists.txt +++ b/cocos/2d/CMakeLists.txt @@ -71,6 +71,7 @@ set(COCOS2D_SRC CCFontDefinition.cpp CCFontFNT.cpp CCFontFreeType.cpp + CCFontCharMap.cpp CCLabel.cpp CCLabelAtlas.cpp CCLabelBMFont.cpp diff --git a/tools/project-creator/module/cocos_files.json.REMOVED.git-id b/tools/project-creator/module/cocos_files.json.REMOVED.git-id index 681e527955..0b8e553434 100644 --- a/tools/project-creator/module/cocos_files.json.REMOVED.git-id +++ b/tools/project-creator/module/cocos_files.json.REMOVED.git-id @@ -1 +1 @@ -5ae50c3f2080b46e18ba3f5aee4c5c686d54e13a \ No newline at end of file +f056b511a4fb5efc921792e46fe57597f669de83 \ No newline at end of file From 3210e12e1cefb3f8e2f57f2726572ba276401f8a Mon Sep 17 00:00:00 2001 From: Luis Parravicini Date: Thu, 16 Jan 2014 14:23:52 -0300 Subject: [PATCH 120/193] fixes #3734 --- cocos/2d/CCLabelBMFont.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/cocos/2d/CCLabelBMFont.cpp b/cocos/2d/CCLabelBMFont.cpp index 539c5dab6a..1b856664fd 100644 --- a/cocos/2d/CCLabelBMFont.cpp +++ b/cocos/2d/CCLabelBMFont.cpp @@ -275,8 +275,7 @@ std::set* CCBMFontConfiguration::parseBinaryConfigFile(unsigned ch unsigned long remains = size; - unsigned char version = pData[3]; - CCASSERT(version == 3, "Only version 3 is supported"); + CCASSERT(pData[3] == 3, "Only version 3 is supported"); pData += 4; remains -= 4; @@ -343,8 +342,7 @@ std::set* CCBMFontConfiguration::parseBinaryConfigFile(unsigned ch */ const char *value = (const char *)pData; - size_t len = strlen(value); - CCASSERT(len < blockSize, "Block size should be less then string"); + CCASSERT(strlen(value) < blockSize, "Block size should be less then string"); _atlasName = FileUtils::getInstance()->fullPathFromRelativeFile(value, controlFile); } From afb4077de573b40a4078fd14c6760ab215d95144 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 16 Jan 2014 12:22:11 -0800 Subject: [PATCH 121/193] Remove Sprites works as expected --- .../Classes/PerformanceTest/PerformanceSpriteTest.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp index 431acb25ed..5ad0cac3e1 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp @@ -276,20 +276,18 @@ void SubTest::removeByTag(int tag) switch (subtestNumber) { case 1: + case 2: case 5: + case 6: case 9: + case 10: _parent->removeChildByTag(tag+100, true); break; - case 2: case 3: case 4: - - case 6: case 7: case 8: - - case 10: case 11: case 12: _batchNode->removeChildByTag(tag+100, true); From 4dba667ea218fc365eb441ef09f23dcc83ee8ac9 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 16 Jan 2014 13:07:56 -0800 Subject: [PATCH 122/193] Adds test '13' to Sprite Test ...and also adds missing Image HD files --- .../PerformanceTest/PerformanceSpriteTest.cpp | 176 ++++++++---------- .../PerformanceTest/PerformanceSpriteTest.h | 3 +- 2 files changed, 82 insertions(+), 97 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp index 5ad0cac3e1..0acc702e08 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.cpp @@ -48,11 +48,7 @@ enum { //////////////////////////////////////////////////////// SubTest::~SubTest() { - if (_batchNode) - { - _batchNode->release(); - _batchNode = NULL; - } + _parentNode->release(); } void SubTest::initWithSubTest(int subtest, Node* p) @@ -60,12 +56,11 @@ void SubTest::initWithSubTest(int subtest, Node* p) srand(0); subtestNumber = subtest; - _parent = p; - _batchNode = nullptr; + _parentNode = nullptr; /* * Tests: * 1: 1 (32-bit) PNG sprite of 52 x 139 - * 2: 1 (32-bit) PNG sprite of 52 x 139 + * 2: 1 (32-bit) PNG sprite of 52 x 139 (same as 1) * 3: 1 (32-bit) PNG Batch Node using 1 sprite of 52 x 139 * 4: 1 (16-bit) PNG Batch Node using 1 sprite of 52 x 139 @@ -90,73 +85,67 @@ void SubTest::initWithSubTest(int subtest, Node* p) { /// case 1: - Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - break; case 2: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); + _parentNode = Node::create(); break; case 3: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - _batchNode = SpriteBatchNode::create("Images/grossinis_sister1.png", 100); - p->addChild(_batchNode, 0); + _parentNode = SpriteBatchNode::create("Images/grossinis_sister1.png", 100); break; case 4: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); - _batchNode = SpriteBatchNode::create("Images/grossinis_sister1.png", 100); - p->addChild(_batchNode, 0); + _parentNode = SpriteBatchNode::create("Images/grossinis_sister1.png", 100); break; /// case 5: - Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - break; case 6: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - _batchNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); + _parentNode = Node::create(); break; case 7: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - _batchNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); - p->addChild(_batchNode, 0); - break; + _parentNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); + break; case 8: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); - _batchNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); - p->addChild(_batchNode, 0); + _parentNode = SpriteBatchNode::create("Images/grossini_dance_atlas.png", 100); break; /// case 9: - Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - break; case 10: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - _batchNode = SpriteBatchNode::create("Images/spritesheet1.png", 100); + _parentNode = Node::create(); break; case 11: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA8888); - _batchNode = SpriteBatchNode::create("Images/spritesheet1.png", 100); - p->addChild(_batchNode, 0); + _parentNode = SpriteBatchNode::create("Images/spritesheet1.png", 100); break; case 12: Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); - _batchNode = SpriteBatchNode::create("Images/spritesheet1.png", 100); - p->addChild(_batchNode, 0); + _parentNode = SpriteBatchNode::create("Images/spritesheet1.png", 100); break; /// + case 13: + Texture2D::setDefaultAlphaPixelFormat(Texture2D::PixelFormat::RGBA4444); + _parentNode = Node::create(); + break; + default: break; } - if (_batchNode) - { - _batchNode->retain(); - } + p->addChild(_parentNode); + _parentNode->retain(); } Sprite* SubTest::createSpriteWithTag(int tag) { + TextureCache *cache = Director::getInstance()->getTextureCache(); + Sprite* sprite = NULL; switch (subtestNumber) { @@ -165,14 +154,15 @@ Sprite* SubTest::createSpriteWithTag(int tag) case 2: { sprite = Sprite::create("Images/grossinis_sister1.png"); - _parent->addChild(sprite, 0, tag+100); + _parentNode->addChild(sprite, 0, tag+100); break; } case 3: case 4: { - sprite = Sprite::createWithTexture(_batchNode->getTexture(), Rect(0, 0, 52, 139)); - _batchNode->addChild(sprite, 0, tag+100); + Texture2D *texture = cache->addImage("Images/grossinis_sister1.png"); + sprite = Sprite::createWithTexture(texture, Rect(0, 0, 52, 139)); + _parentNode->addChild(sprite, 0, tag+100); break; } @@ -183,24 +173,10 @@ Sprite* SubTest::createSpriteWithTag(int tag) char str[32] = {0}; sprintf(str, "Images/grossini_dance_%02d.png", idx); sprite = Sprite::create(str); - _parent->addChild(sprite, 0, tag+100); + _parentNode->addChild(sprite, 0, tag+100); break; } case 6: - { - int y,x; - int r = (CCRANDOM_0_1() * 1400 / 100); - - y = r / 5; - x = r % 5; - - x *= 85; - y *= 121; - sprite = Sprite::createWithTexture(_batchNode->getTexture(), Rect(x,y,85,121)); - _parent->addChild(sprite, 0, tag+100); - break; - } - case 7: case 8: { @@ -212,8 +188,9 @@ Sprite* SubTest::createSpriteWithTag(int tag) x *= 85; y *= 121; - sprite = Sprite::createWithTexture(_batchNode->getTexture(), Rect(x,y,85,121)); - _batchNode->addChild(sprite, 0, tag+100); + Texture2D *texture = cache->addImage("Images/grossini_dance_atlas.png"); + sprite = Sprite::createWithTexture(texture, Rect(x,y,85,121)); + _parentNode->addChild(sprite, 0, tag+100); break; } @@ -229,25 +206,11 @@ Sprite* SubTest::createSpriteWithTag(int tag) char str[40] = {0}; sprintf(str, "Images/sprites_test/sprite-%d-%d.png", x, y); sprite = Sprite::create(str); - _parent->addChild(sprite, 0, tag+100); + _parentNode->addChild(sprite, 0, tag+100); break; } case 10: - { - int y,x; - int r = (CCRANDOM_0_1() * 6400 / 100); - - y = r / 8; - x = r % 8; - - x *= 32; - y *= 32; - sprite = Sprite::createWithTexture(_batchNode->getTexture(), CC_RECT_PIXELS_TO_POINTS(Rect(x,y,32,32))); - _parent->addChild(sprite, 0, tag+100); - break; - } - case 11: case 12: { @@ -259,10 +222,52 @@ Sprite* SubTest::createSpriteWithTag(int tag) x *= 32; y *= 32; - sprite = Sprite::createWithTexture(_batchNode->getTexture(), CC_RECT_PIXELS_TO_POINTS(Rect(x,y,32,32))); - _batchNode->addChild(sprite, 0, tag+100); + Texture2D *texture = cache->addImage("Images/spritesheet1.png"); + sprite = Sprite::createWithTexture(texture, CC_RECT_PIXELS_TO_POINTS(Rect(x,y,32,32))); + _parentNode->addChild(sprite, 0, tag+100); break; } + /// + case 13: + { + int test = (CCRANDOM_0_1() * 3); + + if(test==0) { + // Switch case 1 + sprite = Sprite::create("Images/grossinis_sister1.png"); + _parentNode->addChild(sprite, 0, tag+100); + } + else if(test==1) + { + // Switch case 6 + int y,x; + int r = (CCRANDOM_0_1() * 1400 / 100); + + y = r / 5; + x = r % 5; + + x *= 85; + y *= 121; + Texture2D *texture = cache->addImage("Images/grossini_dance_atlas.png"); + sprite = Sprite::createWithTexture(texture, Rect(x,y,85,121)); + _parentNode->addChild(sprite, 0, tag+100); + + } + else if(test==2) + { + int y,x; + int r = (CCRANDOM_0_1() * 6400 / 100); + + y = r / 8; + x = r % 8; + + x *= 32; + y *= 32; + Texture2D *texture = cache->addImage("Images/spritesheet1.png"); + sprite = Sprite::createWithTexture(texture, CC_RECT_PIXELS_TO_POINTS(Rect(x,y,32,32))); + _parentNode->addChild(sprite, 0, tag+100); + } + } default: break; @@ -273,28 +278,7 @@ Sprite* SubTest::createSpriteWithTag(int tag) void SubTest::removeByTag(int tag) { - switch (subtestNumber) - { - case 1: - case 2: - case 5: - case 6: - case 9: - case 10: - _parent->removeChildByTag(tag+100, true); - break; - - case 3: - case 4: - case 7: - case 8: - case 11: - case 12: - _batchNode->removeChildByTag(tag+100, true); - break; - default: - break; - } + _parentNode->removeChildByTag(tag+100, true); } //////////////////////////////////////////////////////// @@ -441,9 +425,9 @@ void SpriteMainScene::initWithSubTest(int asubtest, int nNodes) addChild( menuAutoTest, 3, kTagAutoTestMenu ); // Sub Tests - MenuItemFont::setFontSize(32); + MenuItemFont::setFontSize(28); auto subMenu = Menu::create(); - for (int i = 1; i <= 12; ++i) + for (int i = 1; i <= 13; ++i) { char str[10] = {0}; sprintf(str, "%d ", i); @@ -455,8 +439,10 @@ void SpriteMainScene::initWithSubTest(int asubtest, int nNodes) itemFont->setColor(Color3B(200,20,20)); else if(i <= 8) itemFont->setColor(Color3B(0,200,20)); - else + else if( i<=12) itemFont->setColor(Color3B(0,20,200)); + else + itemFont->setColor(Color3B::GRAY); } subMenu->alignItemsHorizontally(); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.h index b6a4910259..0aa21356c7 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.h +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceSpriteTest.h @@ -40,8 +40,7 @@ public: protected: int subtestNumber; - SpriteBatchNode *_batchNode; - Node* _parent; + Node *_parentNode; }; class SpriteMenuLayer : public PerformBasicLayer From ce633b44ab9fc94802a7cbfa891ad06cbee8a030 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 16 Jan 2014 13:44:18 -0800 Subject: [PATCH 124/193] Adds GL::activeTexture() `GL::activeTexture()` is the cached version of `glActiveTexture` All code must use it. --- CHANGELOG | 12 +++++++----- cocos/2d/ccGLStateCache.cpp | 17 +++++++++++++++-- cocos/2d/ccGLStateCache.h | 6 ++++++ 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 68b9b9ac70..c76bad7e33 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,13 +1,15 @@ cocos2d-x-3.0final ?.? ? [All] + [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. + [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands + [NEW] GLCache: glActiveTexture() is cached with GL::activeTexture(). All code MUST call the cached version in order to work correctly + [NEW] Label: Uses a struct of TTF configuration for Label::createWithTTF to reduce parameters and make this interface more easily to use. + [NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10% + [FIX] CocoStudio: TestColliderDetector in ArmatureTest can't work. [FIX] Crash if file doesn't exist when using FileUtils::getStringFromFile. [FIX] If setting a shorter string than before while using LabelAtlas, the effect will be wrong. - [NEW] Label: Uses a struct of TTF configuration for Label::createWithTTF to reduce parameters and make this interface more easily to use. [FIX] Label: Crash when using unknown characters. - [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands - [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. - [NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10% [FIX] Console: log(format, va_args) is private to prevent possible resolution errors [FIX] Configuration: dumpInfo() -> getInfo() [FIX] ControlSlider doesn't support to set selected thumb sprite. @@ -17,7 +19,7 @@ cocos2d-x-3.0final ?.? ? [FIX] Renderer: Performance improved in Sprite and SpriteBatchNode (and subclasses) sprites in about 20% [FIX] Sprite: removed _hasChildren optimization. It uses !_children.empty() now which is super fast as well [FIX] Tests: TestCpp works with CMake on Windows. - [FIX] Tests: Sprites Performance Test has 3 new tests + [FIX] Tests: Sprites Performance Test has 4 new tests [FIX] TextureCache: getTextureForKey and removeTextureForKey work as expected [FIX] TextureCache: dumpCachedTextureInfo() -> getCachedTextureInfo() [FIX] Websocket doesn't support send/receive data which larger than 4096 bytes. diff --git a/cocos/2d/ccGLStateCache.cpp b/cocos/2d/ccGLStateCache.cpp index 97599289d1..d8a620f463 100644 --- a/cocos/2d/ccGLStateCache.cpp +++ b/cocos/2d/ccGLStateCache.cpp @@ -44,7 +44,6 @@ namespace static bool s_vertexAttribColor = false; static bool s_vertexAttribTexCoords = false; - #if CC_ENABLE_GL_STATE_CACHE #define kMaxActiveTexture 16 @@ -55,6 +54,8 @@ namespace static GLenum s_blendingDest = -1; static int s_GLServerState = 0; static GLuint s_VAO = 0; + static GLenum s_activeTexture = -1; + #endif // CC_ENABLE_GL_STATE_CACHE } @@ -159,7 +160,7 @@ void bindTexture2DN(GLuint textureUnit, GLuint textureId) if (s_currentBoundTexture[textureUnit] != textureId) { s_currentBoundTexture[textureUnit] = textureId; - glActiveTexture(GL_TEXTURE0 + textureUnit); + activeTexture(GL_TEXTURE0 + textureUnit); glBindTexture(GL_TEXTURE_2D, textureId); } #else @@ -186,6 +187,18 @@ void deleteTextureN(GLuint textureUnit, GLuint textureId) glDeleteTextures(1, &textureId); } +void activeTexture(GLenum texture) +{ +#if CC_ENABLE_GL_STATE_CACHE + if(s_activeTexture != texture) { + s_activeTexture = texture; + glActiveTexture(s_activeTexture); + } +#else + glActiveTexture(texture); +#endif +} + void bindVAO(GLuint vaoId) { if (Configuration::getInstance()->supportsShareableVAO()) diff --git a/cocos/2d/ccGLStateCache.h b/cocos/2d/ccGLStateCache.h index a33f8ba59d..fd94c7006f 100644 --- a/cocos/2d/ccGLStateCache.h +++ b/cocos/2d/ccGLStateCache.h @@ -129,6 +129,12 @@ void CC_DLL deleteTexture(GLuint textureId); */ void CC_DLL deleteTextureN(GLuint textureUnit, GLuint textureId); +/** Select active texture unit. + If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glActiveTexture() directly. + @since v3.0 + */ +void CC_DLL activeTexture(GLenum texture); + /** If the vertex array is not already bound, it binds it. If CC_ENABLE_GL_STATE_CACHE is disabled, it will call glBindVertexArray() directly. @since v2.0.0 From cb9761125bb38a682ed3c2f284c15ee3577911b9 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 16 Jan 2014 15:02:39 -0800 Subject: [PATCH 125/193] Renderer: When not using VAOs, call... ... glBufferData() to update the contents, and not glBufferSubData() since the performance is better --- CHANGELOG | 1 + cocos/2d/CCConfiguration.cpp | 2 +- cocos/2d/renderer/CCQuadCommand.h | 4 ++-- cocos/2d/renderer/CCRenderer.cpp | 6 +++--- cocos/2d/renderer/CCRenderer.h | 8 ++++---- cocos/base/CCConsole.cpp | 2 +- 6 files changed, 12 insertions(+), 11 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index c76bad7e33..fe1e346007 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -17,6 +17,7 @@ cocos2d-x-3.0final ?.? ? [FIX] Particles: Crash was triggered if there is not `textureFileName`section in particle plist file. [FIX] Renderer: QuadCommand::init() does not copy the Quads, it only store a reference making the code faster [FIX] Renderer: Performance improved in Sprite and SpriteBatchNode (and subclasses) sprites in about 20% + [FIX] Renderer: When note using VAO, call glBufferData() instead of glBufferSubData(). [FIX] Sprite: removed _hasChildren optimization. It uses !_children.empty() now which is super fast as well [FIX] Tests: TestCpp works with CMake on Windows. [FIX] Tests: Sprites Performance Test has 4 new tests diff --git a/cocos/2d/CCConfiguration.cpp b/cocos/2d/CCConfiguration.cpp index a576532ade..ddbc3cfae9 100644 --- a/cocos/2d/CCConfiguration.cpp +++ b/cocos/2d/CCConfiguration.cpp @@ -146,7 +146,7 @@ void Configuration::gatherGPUInfo() _supportsShareableVAO = checkForGLExtension("vertex_array_object"); _valueDict["gl.supports_vertex_array_object"] = Value(_supportsShareableVAO); - + CHECK_GL_ERROR_DEBUG(); } diff --git a/cocos/2d/renderer/CCQuadCommand.h b/cocos/2d/renderer/CCQuadCommand.h index b21999ea58..1837919c8d 100644 --- a/cocos/2d/renderer/CCQuadCommand.h +++ b/cocos/2d/renderer/CCQuadCommand.h @@ -56,7 +56,7 @@ public: //TODO use material to decide if it is translucent inline bool isTranslucent() const { return true; } - inline int32_t getMaterialID() const { return _materialID; } + inline uint32_t getMaterialID() const { return _materialID; } inline GLuint getTextureID() const { return _textureID; } @@ -71,7 +71,7 @@ public: inline const kmMat4& getModelView() const { return _mv; } protected: - int32_t _materialID; + uint32_t _materialID; //Key Data int _viewport; /// Which view port it belongs to diff --git a/cocos/2d/renderer/CCRenderer.cpp b/cocos/2d/renderer/CCRenderer.cpp index 15da8cfbdd..3ffa5b583a 100644 --- a/cocos/2d/renderer/CCRenderer.cpp +++ b/cocos/2d/renderer/CCRenderer.cpp @@ -249,7 +249,7 @@ void Renderer::render() //Batch quads if(_numQuads + cmdQuadCount > VBO_SIZE) { - CCASSERT(cmdQuadCount < VBO_SIZE, "VBO is not big enough for quad data, please break the quad data down or use customized render command"); + CCASSERT(cmdQuadCount>=0 && cmdQuadCountgetType() == RenderCommand::Type::QUAD_COMMAND) diff --git a/cocos/2d/renderer/CCRenderer.h b/cocos/2d/renderer/CCRenderer.h index c2dcdccc6f..a856d201c3 100644 --- a/cocos/2d/renderer/CCRenderer.h +++ b/cocos/2d/renderer/CCRenderer.h @@ -42,7 +42,7 @@ typedef std::vector RenderQueue; struct RenderStackElement { int renderQueueID; - size_t currentIndex; + ssize_t currentIndex; }; class Renderer @@ -86,10 +86,10 @@ protected: std::stack _renderStack; std::vector _renderGroups; - int _lastMaterialID; + uint32_t _lastMaterialID; - size_t _firstCommand; - size_t _lastCommand; + ssize_t _firstCommand; + ssize_t _lastCommand; V3F_C4B_T2F_Quad _quads[VBO_SIZE]; GLushort _indices[6 * VBO_SIZE]; diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index 19f7d54048..eea6c483c8 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -391,7 +391,7 @@ void Console::commandTextures(int fd, const char *command) { Scheduler *sched = Director::getInstance()->getScheduler(); sched->performFunctionInCocosThread( [&](){ - mydprintf(fd, "%s", TextureCache::getInstance()->getCachedTextureInfo().c_str()); + mydprintf(fd, "%s", Director::getInstance()->getTextureCache()->getCachedTextureInfo().c_str()); } ); } From f5afa09de10cd36927b166b03c722053238920e2 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Fri, 17 Jan 2014 09:46:59 +0800 Subject: [PATCH 126/193] remove unneeded empty line. --- cocos/2d/CCFontAtlasCache.h | 7 ++----- cocos/2d/CCFontCharMap.h | 8 ++------ cocos/2d/CCLabelTextFormatter.cpp | 2 +- 3 files changed, 5 insertions(+), 12 deletions(-) diff --git a/cocos/2d/CCFontAtlasCache.h b/cocos/2d/CCFontAtlasCache.h index f9e84ba904..31d785dc73 100644 --- a/cocos/2d/CCFontAtlasCache.h +++ b/cocos/2d/CCFontAtlasCache.h @@ -35,10 +35,8 @@ NS_CC_BEGIN class CC_DLL FontAtlasCache -{ - +{ public: - static FontAtlas * getFontAtlasTTF(const std::string& fontFileName, int size, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false); static FontAtlas * getFontAtlasFNT(const std::string& fontFileName); @@ -48,8 +46,7 @@ public: static bool releaseFontAtlas(FontAtlas *atlas); -private: - +private: static std::string generateFontName(const std::string& fontFileName, int size, GlyphCollection theGlyphs, bool useDistanceField); static std::unordered_map _atlasMap; }; diff --git a/cocos/2d/CCFontCharMap.h b/cocos/2d/CCFontCharMap.h index f77c855c08..23caaeff22 100644 --- a/cocos/2d/CCFontCharMap.h +++ b/cocos/2d/CCFontCharMap.h @@ -32,10 +32,8 @@ NS_CC_BEGIN class FontCharMap : public Font -{ - +{ public: - static FontCharMap * create(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); static FontCharMap * create(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); static FontCharMap * create(const std::string& plistFile); @@ -44,8 +42,7 @@ public: virtual Rect getRectForChar(unsigned short theChar) const override; virtual FontAtlas *createFontAtlas() override; -protected: - +protected: FontCharMap(Texture2D* texture,int itemWidth, int itemHeight, int startCharMap) : _texture(texture),_itemWidth(itemWidth),_itemHeight(itemHeight),_mapStartChar(startCharMap),_charRect(0,0,itemWidth,itemHeight){} /** @@ -55,7 +52,6 @@ protected: virtual ~FontCharMap(); private: - Texture2D* _texture; int _mapStartChar; int _itemWidth; diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index 550d017beb..69d6efaae8 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -353,7 +353,7 @@ bool LabelTextFormatter::createStringSprites(LabelTextFormatProtocol *theLabel) Point fontPos = Point((float)nextFontPositionX + charXOffset + charRect.size.width * 0.5f + kerningAmount, - (float)nextFontPositionY + yOffset - charRect.size.height * 0.5f); + (float)nextFontPositionY + yOffset - charRect.size.height * 0.5f); if( theLabel->recordLetterInfo(CC_POINT_PIXELS_TO_POINTS(fontPos),c,i) == false) { From 4302f3886d51cb67f1b68423fabee7f0200405ae Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 16 Jan 2014 10:19:52 +0800 Subject: [PATCH 127/193] issue #2789: Adds performance test for Vector and CCArray. --- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/ccCArray.cpp | 2 +- .../PerformanceContainerTest.cpp | 658 ++++++++++++++++++ .../PerformanceContainerTest.h | 96 +++ .../PerformanceTest/PerformanceTest.cpp | 2 + 5 files changed, 758 insertions(+), 2 deletions(-) create mode 100644 samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp create mode 100644 samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index 2603132689..bb3a11cb54 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -b6abaf935c97f8f1dc7a7179e54850928015b442 \ No newline at end of file +1fa58d8cba77ef923c83d2860d5511d28dad6c27 \ No newline at end of file diff --git a/cocos/2d/ccCArray.cpp b/cocos/2d/ccCArray.cpp index 9c43756ffd..b0827eed5c 100644 --- a/cocos/2d/ccCArray.cpp +++ b/cocos/2d/ccCArray.cpp @@ -73,7 +73,7 @@ void ccArrayEnsureExtraCapacity(ccArray *arr, ssize_t extra) { while (arr->max < arr->num + extra) { - CCLOG("cocos2d: ccCArray: resizing ccArray capacity from [%d] to [%d].", + CCLOGINFO("cocos2d: ccCArray: resizing ccArray capacity from [%d] to [%d].", static_cast(arr->max), static_cast(arr->max*2)); diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp new file mode 100644 index 0000000000..01ee5a2c7b --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp @@ -0,0 +1,658 @@ +/* + * + */ +#include "PerformanceContainerTest.h" + +#include + +// Enable profiles for this file +#undef CC_PROFILER_DISPLAY_TIMERS +#define CC_PROFILER_DISPLAY_TIMERS() Profiler::getInstance()->displayTimers() +#undef CC_PROFILER_PURGE_ALL +#define CC_PROFILER_PURGE_ALL() Profiler::getInstance()->releaseAllTimers() + +#undef CC_PROFILER_START +#define CC_PROFILER_START(__name__) ProfilingBeginTimingBlock(__name__) +#undef CC_PROFILER_STOP +#define CC_PROFILER_STOP(__name__) ProfilingEndTimingBlock(__name__) +#undef CC_PROFILER_RESET +#define CC_PROFILER_RESET(__name__) ProfilingResetTimingBlock(__name__) + +#undef CC_PROFILER_START_CATEGORY +#define CC_PROFILER_START_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingBeginTimingBlock(__name__); } while(0) +#undef CC_PROFILER_STOP_CATEGORY +#define CC_PROFILER_STOP_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingEndTimingBlock(__name__); } while(0) +#undef CC_PROFILER_RESET_CATEGORY +#define CC_PROFILER_RESET_CATEGORY(__cat__, __name__) do{ if(__cat__) ProfilingResetTimingBlock(__name__); } while(0) + +#undef CC_PROFILER_START_INSTANCE +#define CC_PROFILER_START_INSTANCE(__id__, __name__) do{ ProfilingBeginTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0) +#undef CC_PROFILER_STOP_INSTANCE +#define CC_PROFILER_STOP_INSTANCE(__id__, __name__) do{ ProfilingEndTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0) +#undef CC_PROFILER_RESET_INSTANCE +#define CC_PROFILER_RESET_INSTANCE(__id__, __name__) do{ ProfilingResetTimingBlock( String::createWithFormat("%08X - %s", __id__, __name__)->getCString() ); } while(0) + +static std::function createFunctions[] = +{ + CL(TemplateVectorPerfTest), + CL(ArrayPerfTest) +}; + +#define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) + +enum { + kTagInfoLayer = 1, + + kTagBase = 20000, +}; + +enum { + kMaxNodes = 15000, + kNodesIncrease = 500, +}; + +static int g_curCase = 0; + +//////////////////////////////////////////////////////// +// +// ContainerBasicLayer +// +//////////////////////////////////////////////////////// + +ContainerBasicLayer::ContainerBasicLayer(bool bControlMenuVisible, int nMaxCases, int nCurCase) +: PerformBasicLayer(bControlMenuVisible, nMaxCases, nCurCase) +{ +} + +void ContainerBasicLayer::showCurrentTest() +{ + int nodes = ((PerformanceContainerScene*)getParent())->getQuantityOfNodes(); + + auto scene = createFunctions[_curCase](); + + g_curCase = _curCase; + + if (scene) + { + scene->initWithQuantityOfNodes(nodes); + + Director::getInstance()->replaceScene(scene); + } +} + +//////////////////////////////////////////////////////// +// +// PerformanceContainerScene +// +//////////////////////////////////////////////////////// +void PerformanceContainerScene::initWithQuantityOfNodes(unsigned int nNodes) +{ + _type = 0; + //srand(time()); + auto s = Director::getInstance()->getWinSize(); + + // Title + auto label = LabelTTF::create(title().c_str(), "Arial", 40); + addChild(label, 1, TAG_TITLE); + label->setPosition(Point(s.width/2, s.height-32)); + label->setColor(Color3B(255,255,40)); + + // Subtitle + std::string strSubTitle = subtitle(); + if(strSubTitle.length()) + { + auto l = LabelTTF::create(strSubTitle.c_str(), "Thonburi", 16); + addChild(l, 1, TAG_SUBTITLE); + l->setPosition(Point(s.width/2, s.height-80)); + } + + lastRenderedCount = 0; + currentQuantityOfNodes = 0; + quantityOfNodes = nNodes; + + MenuItemFont::setFontSize(65); + auto decrease = MenuItemFont::create(" - ", [&](Object *sender) { + quantityOfNodes -= kNodesIncrease; + if( quantityOfNodes < 0 ) + quantityOfNodes = 0; + + updateQuantityLabel(); + updateQuantityOfNodes(); + updateProfilerName(); + CC_PROFILER_PURGE_ALL(); + srand(0); + }); + decrease->setColor(Color3B(0,200,20)); + _decrease = decrease; + + auto increase = MenuItemFont::create(" + ", [&](Object *sender) { + quantityOfNodes += kNodesIncrease; + if( quantityOfNodes > kMaxNodes ) + quantityOfNodes = kMaxNodes; + + updateQuantityLabel(); + updateQuantityOfNodes(); + updateProfilerName(); + CC_PROFILER_PURGE_ALL(); + srand(0); + }); + increase->setColor(Color3B(0,200,20)); + _increase = increase; + + auto menu = Menu::create(decrease, increase, NULL); + menu->alignItemsHorizontally(); + menu->setPosition(Point(s.width/2, s.height/2+15)); + addChild(menu, 1); + + auto infoLabel = LabelTTF::create("0 nodes", "Marker Felt", 30); + infoLabel->setColor(Color3B(0,200,20)); + infoLabel->setPosition(Point(s.width/2, s.height/2-15)); + addChild(infoLabel, 1, kTagInfoLayer); + + auto menuLayer = new ContainerBasicLayer(true, MAX_LAYER, g_curCase); + addChild(menuLayer); + menuLayer->release(); + + printf("Size of Node: %lu\n", sizeof(Node)); + + int oldFontSize = MenuItemFont::getFontSize(); + MenuItemFont::setFontSize(24); + + Vector toggleItems; + + generateTestFunctions(); + + CCASSERT(!_testFunctions.empty(), "Should not be empty after generate test functions"); + + + for (const auto& f : _testFunctions) + { + toggleItems.pushBack(MenuItemFont::create(f.name)); + } + + auto toggle = MenuItemToggle::createWithCallback([this](Object* sender){ + auto toggle = static_cast(sender); + this->_type = toggle->getSelectedIndex(); + auto label = static_cast(this->getChildByTag(TAG_SUBTITLE)); + label->setString(StringUtils::format("Test '%s', See console", this->_testFunctions[this->_type].name)); + this->updateProfilerName(); + }, toggleItems); + + toggle->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT); + toggle->setPosition(VisibleRect::left()); + _toggle = toggle; + + auto start = MenuItemFont::create("start", [this](Object* sender){ + auto director = Director::getInstance(); + auto sched = director->getScheduler(); + + CC_PROFILER_PURGE_ALL(); + sched->scheduleSelector(schedule_selector(PerformanceContainerScene::dumpProfilerInfo), this, 2, false); + + this->unscheduleUpdate(); + this->scheduleUpdate(); + this->_startItem->setEnabled(false); + this->_stopItem->setEnabled(true); + this->_toggle->setEnabled(false); + this->_increase->setEnabled(false); + this->_decrease->setEnabled(false); + }); + start->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT); + start->setPosition(VisibleRect::right() + Point(0, 40)); + _startItem = start; + + auto stop = MenuItemFont::create("stop", [this](Object* sender){ + auto director = Director::getInstance(); + auto sched = director->getScheduler(); + + sched->unscheduleSelector(schedule_selector(PerformanceContainerScene::dumpProfilerInfo), this); + + this->unscheduleUpdate(); + this->_startItem->setEnabled(true); + this->_stopItem->setEnabled(false); + this->_toggle->setEnabled(true); + this->_increase->setEnabled(true); + this->_decrease->setEnabled(true); + }); + + stop->setEnabled(false); + stop->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT); + stop->setPosition(VisibleRect::right() + Point(0, -40)); + _stopItem = stop; + + auto menu2 = Menu::create(toggle, start, stop, NULL); + menu2->setPosition(Point::ZERO); + addChild(menu2); + + MenuItemFont::setFontSize(oldFontSize); + + updateQuantityLabel(); + updateQuantityOfNodes(); + updateProfilerName(); +} + +std::string PerformanceContainerScene::title() const +{ + return "No title"; +} + +std::string PerformanceContainerScene::subtitle() const +{ + return ""; +} + +void PerformanceContainerScene::updateQuantityLabel() +{ + if( quantityOfNodes != lastRenderedCount ) + { + auto infoLabel = static_cast( getChildByTag(kTagInfoLayer) ); + char str[20] = {0}; + sprintf(str, "%u nodes", quantityOfNodes); + infoLabel->setString(str); + + lastRenderedCount = quantityOfNodes; + } +} + +const char * PerformanceContainerScene::profilerName() +{ + return _profilerName; +} + +void PerformanceContainerScene::updateProfilerName() +{ + snprintf(_profilerName, sizeof(_profilerName)-1, "%s(%d)", testName(), quantityOfNodes); +} + +void PerformanceContainerScene::onExitTransitionDidStart() +{ + Scene::onExitTransitionDidStart(); + + auto director = Director::getInstance(); + auto sched = director->getScheduler(); + + sched->unscheduleSelector(schedule_selector(PerformanceContainerScene::dumpProfilerInfo), this); +} + +void PerformanceContainerScene::onEnterTransitionDidFinish() +{ + Scene::onEnterTransitionDidFinish(); + + auto director = Director::getInstance(); + auto sched = director->getScheduler(); + + CC_PROFILER_PURGE_ALL(); + sched->scheduleSelector(schedule_selector(PerformanceContainerScene::dumpProfilerInfo), this, 2, false); +} + +void PerformanceContainerScene::dumpProfilerInfo(float dt) +{ + CC_PROFILER_DISPLAY_TIMERS(); +} + +void PerformanceContainerScene::update(float dt) +{ + _testFunctions[_type].func(); +} + +void PerformanceContainerScene::updateQuantityOfNodes() +{ + currentQuantityOfNodes = quantityOfNodes; +} + +const char* PerformanceContainerScene::testName() +{ + return _testFunctions[_type].name; +} + +//////////////////////////////////////////////////////// +// +// TemplateVectorPerfTest +// +//////////////////////////////////////////////////////// + +void TemplateVectorPerfTest::generateTestFunctions() +{ + auto createVector = [this](){ + Vector ret; + + for( int i=0; isetTag(i); + ret.pushBack(node); + } + return ret; + }; + + TestFunction nameCBs[] = { + { "pushBack", [=](){ + Vector nodeVector; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + { "insert", [=](){ + Vector nodeVector; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + { "replace", [=](){ + Vector nodeVector = createVector(); + + srand(time(nullptr)); + ssize_t index = rand() % quantityOfNodes; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + { "getIndex", [=](){ + + Vector nodeVector = createVector(); + Node* objToGet = nodeVector.at(quantityOfNodes/3); + ssize_t index = 0; + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + log("index = %d", (int)index); + } } , + { "find", [=](){ + Vector nodeVector = createVector(); + Node* objToGet = nodeVector.at(quantityOfNodes/3); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + { "at", [=](){ + Vector nodeVector = createVector(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + { "contains", [=](){ + Vector nodeVector = createVector(); + Node* objToGet = nodeVector.at(quantityOfNodes/3); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + { "eraseObject", [=](){ + Vector nodeVector = createVector(); + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + + for (int i = 0; i < quantityOfNodes; ++i) + { + nodes[i] = nodeVector.at(i); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + CCASSERT(nodeVector.empty(), "nodeVector was not empty."); + + free(nodes); + } } , + { "erase", [=](){ + Vector nodeVector = createVector(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + CCASSERT(nodeVector.empty(), "nodeVector was not empty."); + + } } , + { "clear", [=](){ + Vector nodeVector = createVector(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + CCASSERT(nodeVector.empty(), "nodeVector was not empty."); + } } , + { "swap by index", [=](){ + Vector nodeVector = createVector(); + + int swapIndex1 = quantityOfNodes / 3; + int swapIndex2 = quantityOfNodes / 3 * 2; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + + { "swap by object", [=](){ + Vector nodeVector = createVector(); + + Node* swapNode1 = nodeVector.at(quantityOfNodes / 3); + Node* swapNode2 = nodeVector.at(quantityOfNodes / 3 * 2); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + + { "reverse", [=](){ + Vector nodeVector = createVector(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + }; + + for (const auto& nameCB : nameCBs) + { + _testFunctions.push_back(nameCB); + } +} + + + +std::string TemplateVectorPerfTest::title() const +{ + return "Vector Perf test"; +} + +std::string TemplateVectorPerfTest::subtitle() const +{ + return "Test 'pushBack', See console"; +} + + + +//////////////////////////////////////////////////////// +// +// ArrayPerfTest +// +//////////////////////////////////////////////////////// + +std::string ArrayPerfTest::title() const +{ + return "Array Perf test"; +} + +std::string ArrayPerfTest::subtitle() const +{ + return "Test addObject, See console"; +} + +void ArrayPerfTest::generateTestFunctions() +{ + auto createArray = [this](){ + Array* ret = Array::create(); + + for( int i=0; isetTag(i); + ret->addObject(node); + } + return ret; + }; + + TestFunction nameCBs[] = { + { "addObject", [=](){ + Array* nodeVector = Array::create(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iaddObject(Node::create()); + CC_PROFILER_STOP(this->profilerName()); + } } , + { "insertObject", [=](){ + Array* nodeVector = Array::create(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iinsertObject(Node::create(), 0); + CC_PROFILER_STOP(this->profilerName()); + } } , + { "setObject", [=](){ + Array* nodeVector = createArray(); + + srand(time(nullptr)); + ssize_t index = rand() % quantityOfNodes; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; isetObject(Node::create(), index); + CC_PROFILER_STOP(this->profilerName()); + } } , + { "getIndexOfObject", [=](){ + Array* nodeVector = createArray(); + Object* objToGet = nodeVector->getObjectAtIndex(quantityOfNodes/3); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; igetIndexOfObject(objToGet); + CC_PROFILER_STOP(this->profilerName()); + + } } , + { "getObjectAtIndex", [=](){ + Array* nodeVector = createArray(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; igetObjectAtIndex(quantityOfNodes/3); + CC_PROFILER_STOP(this->profilerName()); + } } , + { "containsObject", [=](){ + Array* nodeVector = createArray(); + Object* objToGet = nodeVector->getObjectAtIndex(quantityOfNodes/3); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; icontainsObject(objToGet); + CC_PROFILER_STOP(this->profilerName()); + } } , + { "removeObject", [=](){ + Array* nodeVector = createArray(); + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + + for (int i = 0; i < quantityOfNodes; ++i) + { + nodes[i] = static_cast(nodeVector->getObjectAtIndex(i)); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iremoveObject(nodes[i]); + CC_PROFILER_STOP(this->profilerName()); + + CCASSERT(nodeVector->count() == 0, "nodeVector was not empty."); + + free(nodes); + } } , + { "removeObjectAtIndex", [=](){ + Array* nodeVector = createArray(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iremoveObjectAtIndex(0); + CC_PROFILER_STOP(this->profilerName()); + + CCASSERT(nodeVector->count() == 0, "nodeVector was not empty."); + + } } , + { "removeAllObjects", [=](){ + Array* nodeVector = createArray(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iremoveAllObjects(); + CC_PROFILER_STOP(this->profilerName()); + + CCASSERT(nodeVector->count() == 0, "nodeVector was not empty."); + } } , + { "swap by index", [=](){ + Array* nodeVector = createArray(); + + int swapIndex1 = quantityOfNodes / 3; + int swapIndex2 = quantityOfNodes / 3 * 2; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iswap(swapIndex1, swapIndex2); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "swap by object", [=](){ + Array* nodeVector = createArray(); + + Object* swapNode1 = nodeVector->getObjectAtIndex(quantityOfNodes / 3); + Object* swapNode2 = nodeVector->getObjectAtIndex(quantityOfNodes / 3 * 2); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iexchangeObject(swapNode1, swapNode2); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "reverseObjects", [=](){ + Array* nodeVector = createArray(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; ireverseObjects(); + CC_PROFILER_STOP(this->profilerName()); + } } , + }; + + for (const auto& nameCB : nameCBs) + { + _testFunctions.push_back(nameCB); + } +} + +///---------------------------------------- +void runContainerPerformanceTest() +{ + auto scene = createFunctions[g_curCase](); + scene->initWithQuantityOfNodes(kNodesIncrease); + + Director::getInstance()->replaceScene(scene); +} diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h new file mode 100644 index 0000000000..88c1bb3984 --- /dev/null +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h @@ -0,0 +1,96 @@ +/* + * + */ +#ifndef __PERFORMANCE_CONTAINER_TEST_H__ +#define __PERFORMANCE_CONTAINER_TEST_H__ + +#include "PerformanceTest.h" +#include "CCProfiling.h" + +class ContainerBasicLayer : public PerformBasicLayer +{ +public: + ContainerBasicLayer(bool bControlMenuVisible, int nMaxCases = 0, int nCurCase = 0); + + virtual void showCurrentTest(); +}; + +class PerformanceContainerScene : public Scene +{ +public: + + static const int TAG_TITLE = 100; + static const int TAG_SUBTITLE = 101; + + struct TestFunction + { + const char* name; + std::function func; + }; + + virtual void initWithQuantityOfNodes(unsigned int nNodes); + virtual void generateTestFunctions() = 0; + + virtual std::string title() const; + virtual std::string subtitle() const; + virtual void updateQuantityOfNodes(); + + const char* profilerName(); + void updateProfilerName(); + + // for the profiler + virtual const char* testName(); + + void updateQuantityLabel(); + + int getQuantityOfNodes() { return quantityOfNodes; } + + void dumpProfilerInfo(float dt); + + // overrides + virtual void onExitTransitionDidStart() override; + virtual void onEnterTransitionDidFinish() override; + virtual void update(float dt) override; + +protected: + char _profilerName[256]; + int lastRenderedCount; + int quantityOfNodes; + int currentQuantityOfNodes; + unsigned int _type; + std::vector _testFunctions; + + MenuItemFont* _increase; + MenuItemFont* _decrease; + MenuItemFont* _startItem; + MenuItemFont* _stopItem; + MenuItemToggle* _toggle; +}; + +class TemplateVectorPerfTest : public PerformanceContainerScene +{ +public: + CREATE_FUNC(TemplateVectorPerfTest); + + virtual void generateTestFunctions() override; + + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + +class ArrayPerfTest : public PerformanceContainerScene +{ +public: + CREATE_FUNC(ArrayPerfTest); + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + + +void runContainerPerformanceTest(); + +#endif // __PERFORMANCE_CONTAINER_TEST_H__ diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.cpp index 9ef97602b6..7884aec8d3 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceTest.cpp @@ -8,6 +8,7 @@ #include "PerformanceAllocTest.h" #include "PerformanceLabelTest.h" #include "PerformanceRendererTest.h" +#include "PerformanceContainerTest.h" enum { @@ -28,6 +29,7 @@ struct { { "Touches Perf Test",[](Object*sender){runTouchesTest();} }, { "Label Perf Test",[](Object*sender){runLabelTest();} }, { "Renderer Perf Test",[](Object*sender){runRendererTest();} }, + { "Container Perf Test", [](Object* sender ) { runContainerPerformanceTest(); } } }; static const int g_testMax = sizeof(g_testsName)/sizeof(g_testsName[0]); From 811f55bb8daab12e487df97d85dbcd20bf9cae18 Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 16 Jan 2014 14:41:31 +0800 Subject: [PATCH 128/193] issue #2789: Avoids compiler to do optimization. --- .../PerformanceContainerTest.cpp | 48 +++++++++++++++---- 1 file changed, 39 insertions(+), 9 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp index 01ee5a2c7b..9f61b4e4ee 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp @@ -363,33 +363,59 @@ void TemplateVectorPerfTest::generateTestFunctions() index = nodeVector.getIndex(objToGet); CC_PROFILER_STOP(this->profilerName()); - log("index = %d", (int)index); + // Uses `index` to avoids `getIndex` invoking was optimized in release mode + if (index == quantityOfNodes/3) + { + nodeVector.clear(); + } } } , { "find", [=](){ Vector nodeVector = createVector(); Node* objToGet = nodeVector.at(quantityOfNodes/3); + Vector::iterator iter; CC_PROFILER_START(this->profilerName()); for( int i=0; iprofilerName()); + + // Uses `iter` to avoids `find` invoking was optimized in release mode + if (*iter == objToGet) + { + nodeVector.clear(); + } + } } , { "at", [=](){ Vector nodeVector = createVector(); - + Node* objToGet = nullptr; CC_PROFILER_START(this->profilerName()); for( int i=0; iprofilerName()); + + // Uses `objToGet` to avoids `at` invoking was optimized in release mode + if (nodeVector.getIndex(objToGet) == quantityOfNodes/3) + { + nodeVector.clear(); + } } } , { "contains", [=](){ Vector nodeVector = createVector(); Node* objToGet = nodeVector.at(quantityOfNodes/3); + bool ret = false; + CC_PROFILER_START(this->profilerName()); for( int i=0; iprofilerName()); + + // Uses `ret` to avoids `contains` invoking was optimized in release mode + if (ret) + { + nodeVector.clear(); + } } } , { "eraseObject", [=](){ Vector nodeVector = createVector(); @@ -497,7 +523,7 @@ std::string ArrayPerfTest::title() const std::string ArrayPerfTest::subtitle() const { - return "Test addObject, See console"; + return "Test `addObject`, See console"; } void ArrayPerfTest::generateTestFunctions() @@ -545,12 +571,16 @@ void ArrayPerfTest::generateTestFunctions() { "getIndexOfObject", [=](){ Array* nodeVector = createArray(); Object* objToGet = nodeVector->getObjectAtIndex(quantityOfNodes/3); - + ssize_t index = 0; CC_PROFILER_START(this->profilerName()); for( int i=0; igetIndexOfObject(objToGet); + index = nodeVector->getIndexOfObject(objToGet); CC_PROFILER_STOP(this->profilerName()); - + // Uses `index` to avoids `getIndex` invoking was optimized in release mode + if (index == quantityOfNodes/3) + { + nodeVector->removeAllObjects(); + } } } , { "getObjectAtIndex", [=](){ Array* nodeVector = createArray(); From 83b459fcdb057b613216ad0ac481cb8893c0f3fa Mon Sep 17 00:00:00 2001 From: James Chen Date: Thu, 16 Jan 2014 15:51:01 +0800 Subject: [PATCH 129/193] issue #2789: Adds loop test for Vector and Array. --- .../PerformanceContainerTest.cpp | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp index 9f61b4e4ee..75c8f31b44 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp @@ -488,6 +488,17 @@ void TemplateVectorPerfTest::generateTestFunctions() nodeVector.reverse(); CC_PROFILER_STOP(this->profilerName()); } } , + + { "c++11 Range Loop", [=](){ + Vector nodeVector = createVector(); + + CC_PROFILER_START(this->profilerName()); + for (const auto& e : nodeVector) + { + e->setTag(111); + } + CC_PROFILER_STOP(this->profilerName()); + } } , }; for (const auto& nameCB : nameCBs) @@ -670,6 +681,18 @@ void ArrayPerfTest::generateTestFunctions() nodeVector->reverseObjects(); CC_PROFILER_STOP(this->profilerName()); } } , + + { "CCARRAY_FOREACH", [=](){ + Array* nodeVector = createArray(); + Object* obj; + CC_PROFILER_START(this->profilerName()); + + CCARRAY_FOREACH(nodeVector, obj) + { + static_cast(obj)->setTag(111); + } + CC_PROFILER_STOP(this->profilerName()); + } } , }; for (const auto& nameCB : nameCBs) From b3e1319982f7389d2bd7a15700c412f398124563 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 17 Jan 2014 09:44:49 +0800 Subject: [PATCH 130/193] issue #2789: Updates Android.mk and CMakeLists.txt. --- samples/Cpp/TestCpp/Android.mk | 1 + samples/Cpp/TestCpp/CMakeLists.txt | 1 + 2 files changed, 2 insertions(+) diff --git a/samples/Cpp/TestCpp/Android.mk b/samples/Cpp/TestCpp/Android.mk index 07d231cbf8..1d661d5aa1 100644 --- a/samples/Cpp/TestCpp/Android.mk +++ b/samples/Cpp/TestCpp/Android.mk @@ -122,6 +122,7 @@ Classes/PerformanceTest/PerformanceTextureTest.cpp \ Classes/PerformanceTest/PerformanceTouchesTest.cpp \ Classes/PerformanceTest/PerformanceLabelTest.cpp \ Classes/PerformanceTest/PerformanceRendererTest.cpp \ +Classes/PerformanceTest/PerformanceContainerTest.cpp \ Classes/PhysicsTest/PhysicsTest.cpp \ Classes/RenderTextureTest/RenderTextureTest.cpp \ Classes/RotateWorldTest/RotateWorldTest.cpp \ diff --git a/samples/Cpp/TestCpp/CMakeLists.txt b/samples/Cpp/TestCpp/CMakeLists.txt index 6c10336eb2..df0a738a87 100644 --- a/samples/Cpp/TestCpp/CMakeLists.txt +++ b/samples/Cpp/TestCpp/CMakeLists.txt @@ -117,6 +117,7 @@ set(SAMPLE_SRC Classes/PerformanceTest/PerformanceTouchesTest.cpp Classes/PerformanceTest/PerformanceLabelTest.cpp Classes/PerformanceTest/PerformanceRendererTest.cpp + Classes/PerformanceTest/PerformanceContainerTest.cpp Classes/PhysicsTest/PhysicsTest.cpp Classes/RenderTextureTest/RenderTextureTest.cpp Classes/RotateWorldTest/RotateWorldTest.cpp From 3af95f3e843272533a77eb120bde69cacd3ddf77 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 17 Jan 2014 10:05:26 +0800 Subject: [PATCH 131/193] issue #2789: Updates windows projects. --- samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj | 3 +++ samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters | 9 +++++++++ 2 files changed, 12 insertions(+) diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj index 1e60324f40..056b3f6cff 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj @@ -186,6 +186,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ + @@ -332,6 +333,8 @@ xcopy /Y /Q "$(ProjectDir)..\..\..\..\external\websockets\prebuilt\win32\*.*" "$ + + diff --git a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters index 00e2567c95..5cfe11e6c9 100644 --- a/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters +++ b/samples/Cpp/TestCpp/proj.win32/TestCpp.vcxproj.filters @@ -718,6 +718,9 @@ Classes\PerformanceTest + + Classes\PerformanceTest + @@ -1324,5 +1327,11 @@ Classes\PerformanceTest + + Classes\PerformanceTest + + + Classes\PerformanceTest + \ No newline at end of file From b72f309076b32e63f56a61c5fbc799b6c2637974 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Wed, 15 Jan 2014 11:28:59 +0800 Subject: [PATCH 132/193] =?UTF-8?q?issue=20#3626:Add=20namespace=E2=80=99s?= =?UTF-8?q?=20support=20for=20manual=20lua=20binding=20of=20classes=20in?= =?UTF-8?q?=20the=20cocos2d::extension=20and=20cocosbuilder=20namespace=20?= =?UTF-8?q?and=20update=20the=20related=20test=20cases?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/scripting/lua/bindings/CCBProxy.cpp | 36 +++++------ .../lua_cocos2dx_extension_manual.cpp | 62 +++++++++---------- cocos/scripting/lua/script/CCBReaderLoad.lua | 12 ++-- .../ExtensionTest/CocosBuilderTest.lua | 50 +++++++-------- .../luaScript/ExtensionTest/ExtensionTest.lua | 16 ++--- 5 files changed, 88 insertions(+), 88 deletions(-) diff --git a/cocos/scripting/lua/bindings/CCBProxy.cpp b/cocos/scripting/lua/bindings/CCBProxy.cpp index cab487b1d8..f0ba9f92f8 100644 --- a/cocos/scripting/lua/bindings/CCBProxy.cpp +++ b/cocos/scripting/lua/bindings/CCBProxy.cpp @@ -58,75 +58,75 @@ const char* CCBProxy::getNodeTypeName(Node* pNode) } if (NULL != dynamic_cast(pNode)) { - return "LabelTTF"; + return "cc.LabelTTF"; } if (NULL != dynamic_cast(pNode)) { - return "LabelBMFont"; + return "cc.LabelBMFont"; } if (NULL != dynamic_cast(pNode)) { - return "Sprite"; + return "cc.Sprite"; } if (NULL != dynamic_cast(pNode)) { - return "ControlButton"; + return "cc.ControlButton"; } if (NULL != dynamic_cast(pNode)) { - return "LayerGradient"; + return "cc.LayerGradient"; } if (NULL != dynamic_cast(pNode)) { - return "LayerColor"; + return "cc.LayerColor"; } if (NULL != dynamic_cast(pNode)) { - return "LayerGradient"; + return "cc.LayerGradient"; } if (NULL != dynamic_cast(pNode)) { - return "Menu"; + return "cc.Menu"; } if (NULL != dynamic_cast(pNode)) { - return "MenuItemAtlasFont"; + return "cc.MenuItemAtlasFont"; } if (NULL != dynamic_cast(pNode)) { - return "MenuItemFont"; + return "cc.MenuItemFont"; } if (NULL != dynamic_cast(pNode)) { - return "MenuItemLabel"; + return "cc.MenuItemLabel"; } if (NULL != dynamic_cast(pNode)) { - return "MenuItemImage"; + return "cc.MenuItemImage"; } if (NULL != dynamic_cast(pNode)) { - return "MenuItemToggle"; + return "cc.MenuItemToggle"; } if (NULL != dynamic_cast(pNode)) { - return "MenuItemSprite"; + return "cc.MenuItemSprite"; } if (NULL != dynamic_cast(pNode)) { - return "MenuItem"; + return "cc.MenuItem"; } if (NULL != dynamic_cast(pNode)) { - return "Layer"; + return "cc.Layer"; } if (NULL != dynamic_cast(pNode)) { - return "String"; + return "cc.String"; } if (NULL != dynamic_cast(pNode)) { - return "ParticleSystemQuad"; + return "cc.ParticleSystemQuad"; } return "No Support"; diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp index 88b4693c01..195cd72d18 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp @@ -52,7 +52,7 @@ static int tolua_cocos2d_Control_registerControlEventHandler(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"Control",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.Control",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -108,7 +108,7 @@ static int tolua_cocos2d_control_unregisterControlEventHandler(lua_State* tolua_ #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"Control",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.Control",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -153,7 +153,7 @@ tolua_lerror: static void extendControl(lua_State* tolua_S) { - lua_pushstring(tolua_S, "Control"); + lua_pushstring(tolua_S, "cc.Control"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -177,7 +177,7 @@ static int tolua_cocos2d_EditBox_registerScriptEditBoxHandler(lua_State* tolua_S #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"EditBox",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.EditBox",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -226,7 +226,7 @@ static int tolua_cocos2d_EditBox_unregisterScriptEditBoxHandler(lua_State* tolua #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"EditBox",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.EditBox",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -258,7 +258,7 @@ tolua_lerror: static void extendEditBox(lua_State* tolua_S) { - lua_pushstring(tolua_S, "EditBox"); + lua_pushstring(tolua_S, "cc.EditBox"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -281,7 +281,7 @@ static int tolua_cocos2d_CCBProxy_create(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertable(tolua_S,1,"CCBProxy",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertable(tolua_S,1,"cc.CCBProxy",0,&tolua_err)) goto tolua_lerror; #endif argc = lua_gettop(tolua_S) - 1; @@ -291,7 +291,7 @@ static int tolua_cocos2d_CCBProxy_create(lua_State* tolua_S) CCBProxy* tolua_ret = (CCBProxy*)CCBProxy::create(); int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int *pLuaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"CCBProxy"); + toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"cc.CCBProxy"); return 1; } @@ -316,7 +316,7 @@ static int tolua_cocos2d_CCBProxy_createCCBReader(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"CCBProxy",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.CCBProxy",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -335,7 +335,7 @@ static int tolua_cocos2d_CCBProxy_createCCBReader(lua_State* tolua_S) CCBReader* tolua_ret = (CCBReader*) self->createCCBReader(); int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* pLuaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"CCBReader"); + toluafix_pushusertype_ccobject(tolua_S, nID, pLuaID, (void*)tolua_ret,"cc.CCBReader"); return 1; } @@ -366,7 +366,7 @@ static int tolua_cocos2d_CCBProxy_readCCBFromFile(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"CCBProxy",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.CCBProxy",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -384,7 +384,7 @@ static int tolua_cocos2d_CCBProxy_readCCBFromFile(lua_State* tolua_S) { #if COCOS2D_DEBUG >= 1 if (!tolua_isstring(tolua_S, 2, 0, &tolua_err)|| - !tolua_isusertype(tolua_S,3,"CCBReader",0,&tolua_err)|| + !tolua_isusertype(tolua_S,3,"cc.CCBReader",0,&tolua_err)|| !tolua_isboolean(tolua_S,4,1,&tolua_err ) ) goto tolua_lerror; @@ -395,7 +395,7 @@ static int tolua_cocos2d_CCBProxy_readCCBFromFile(lua_State* tolua_S) tolua_ret = (Node*) self->readCCBFromFile(ccbFilePath, ccbReader, setOwner); ID = (tolua_ret) ? (int)tolua_ret->_ID : -1; luaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"Node"); + toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"cc.Node"); return 1; } @@ -420,7 +420,7 @@ static int tolua_cocos2d_CCBProxy_getNodeTypeName(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"CCBProxy",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.CCBProxy",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -437,7 +437,7 @@ static int tolua_cocos2d_CCBProxy_getNodeTypeName(lua_State* tolua_S) if (1 == argc) { #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"Node",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.Node",0,&tolua_err)) goto tolua_lerror; #endif Node* node = static_cast(tolua_tousertype(tolua_S,2,0)); @@ -466,7 +466,7 @@ static int tolua_cocos2d_CCBProxy_setCallback(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"CCBProxy",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.CCBProxy",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -482,7 +482,7 @@ static int tolua_cocos2d_CCBProxy_setCallback(lua_State* tolua_S) if ( argc >= 2 && argc <= 3 ) { #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,2,"Node",0,&tolua_err) || + if (!tolua_isusertype(tolua_S,2,"cc.Node",0,&tolua_err) || !toluafix_isfunction(tolua_S, 3, "LUA_FUNCTION", 0, &tolua_err) || !tolua_isnumber(tolua_S, 4, 1, &tolua_err) ) @@ -510,8 +510,8 @@ int register_cocos2dx_extension_CCBProxy(lua_State* tolua_S) { tolua_module(tolua_S,"cc",0); tolua_beginmodule(tolua_S,"cc"); - tolua_usertype(tolua_S,"CCBProxy"); - tolua_cclass(tolua_S,"CCBProxy","CCBProxy","Layer",NULL); + tolua_usertype(tolua_S,"cc.CCBProxy"); + tolua_cclass(tolua_S,"CCBProxy","cc.CCBProxy","cc.Layer",NULL); tolua_beginmodule(tolua_S,"CCBProxy"); tolua_function(tolua_S, "create", tolua_cocos2d_CCBProxy_create); tolua_function(tolua_S, "createCCBReader", tolua_cocos2d_CCBProxy_createCCBReader); @@ -522,7 +522,7 @@ int register_cocos2dx_extension_CCBProxy(lua_State* tolua_S) tolua_endmodule(tolua_S); std::string typeName = typeid(CCBProxy).name(); - g_luaType[typeName] = "CCBProxy"; + g_luaType[typeName] = "cc.CCBProxy"; return 1; } @@ -537,7 +537,7 @@ static int tolua_cocos2d_CCBReader_load(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"CCBReader",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.CCBReader",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -564,12 +564,12 @@ static int tolua_cocos2d_CCBReader_load(lua_State* tolua_S) Node* tolua_ret = (Node*) self->readNodeGraphFromFile(fileName); int ID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* luaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"Node"); + toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"cc.Node"); return 1; } #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S, 3, "Object", 0, &tolua_err)) + if (!tolua_isusertype(tolua_S, 3, "cc.Object", 0, &tolua_err)) goto tolua_lerror; #endif Object* owner = static_cast(tolua_tousertype(tolua_S, 3, 0)); @@ -579,7 +579,7 @@ static int tolua_cocos2d_CCBReader_load(lua_State* tolua_S) Node* tolua_ret = (Node*) self->readNodeGraphFromFile(fileName,owner); int ID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* luaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"Node"); + toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"cc.Node"); return 1; } @@ -591,7 +591,7 @@ static int tolua_cocos2d_CCBReader_load(lua_State* tolua_S) Node* tolua_ret = (Node*) self->readNodeGraphFromFile(fileName,owner,size); int ID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* luaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"Node"); + toluafix_pushusertype_ccobject(tolua_S, ID, luaID, (void*)tolua_ret,"cc.Node"); return 1; } @@ -608,7 +608,7 @@ tolua_lerror: static void extendCCBReader(lua_State* tolua_S) { - lua_pushstring(tolua_S, "CCBReader"); + lua_pushstring(tolua_S, "cc.CCBReader"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -630,7 +630,7 @@ static int tolua_cocos2d_CCBAnimationManager_setCallFuncForLuaCallbackNamed(lua_ #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(tolua_S,1,"CCBAnimationManager",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.CCBAnimationManager",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(tolua_S,1,0)); @@ -647,7 +647,7 @@ static int tolua_cocos2d_CCBAnimationManager_setCallFuncForLuaCallbackNamed(lua_ { #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,2, "CallFunc", 0, &tolua_err) || + if (!tolua_isusertype(tolua_S,2, "cc.CallFunc", 0, &tolua_err) || !tolua_isstring(tolua_S, 3, 0, &tolua_err) ) goto tolua_lerror; #endif @@ -675,7 +675,7 @@ tolua_lerror: static void extendCCBAnimationManager(lua_State* tolua_S) { - lua_pushstring(tolua_S, "CCBAnimationManager"); + lua_pushstring(tolua_S, "cc.CCBAnimationManager"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -736,7 +736,7 @@ static int lua_cocos2dx_AssetsManager_setDelegate(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"AssetsManager",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.AssetsManager",0,&tolua_err)) goto tolua_lerror; #endif self = (AssetsManager*) tolua_tousertype(L,1,0); @@ -791,7 +791,7 @@ tolua_lerror: static void extendAssetsManager(lua_State* L) { - lua_pushstring(L, "AssetsManager"); + lua_pushstring(L, "cc.AssetsManager"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { diff --git a/cocos/scripting/lua/script/CCBReaderLoad.lua b/cocos/scripting/lua/script/CCBReaderLoad.lua index 733a432317..141a4e5df5 100644 --- a/cocos/scripting/lua/script/CCBReaderLoad.lua +++ b/cocos/scripting/lua/script/CCBReaderLoad.lua @@ -17,7 +17,7 @@ function CCBReaderLoad(strFilePath,proxy,owner) local i = 1 for i = 1,table.getn(ownerCallbackNames) do local callbackName = ownerCallbackNames[i] - local callbackNode = tolua.cast(ownerCallbackNodes[i],"Node") + local callbackNode = tolua.cast(ownerCallbackNodes[i],"cc.Node") if "function" == type(owner[callbackName]) then proxy:setCallback(callbackNode, owner[callbackName], ownerCallbackControlEvents[i]) @@ -33,7 +33,7 @@ function CCBReaderLoad(strFilePath,proxy,owner) for i = 1, table.getn(ownerOutletNames) do local outletName = ownerOutletNames[i] - local outletNode = tolua.cast(ownerOutletNodes[i],"Node") + local outletNode = tolua.cast(ownerOutletNodes[i],"cc.Node") owner[outletName] = outletNode end end @@ -42,8 +42,8 @@ function CCBReaderLoad(strFilePath,proxy,owner) local animationManagersForNodes = ccbReader:getAnimationManagersForNodes() for i = 1 , table.getn(nodesWithAnimationManagers) do - local innerNode = tolua.cast(nodesWithAnimationManagers[i], "Node") - local animationManager = tolua.cast(animationManagersForNodes[i], "CCBAnimationManager") + local innerNode = tolua.cast(nodesWithAnimationManagers[i], "cc.Node") + local animationManager = tolua.cast(animationManagersForNodes[i], "cc.CCBAnimationManager") local documentControllerName = animationManager:getDocumentControllerName() if "" == documentControllerName then @@ -59,7 +59,7 @@ function CCBReaderLoad(strFilePath,proxy,owner) for i = 1,table.getn(documentCallbackNames) do local callbackName = documentCallbackNames[i] - local callbackNode = tolua.cast(documentCallbackNodes[i],"Node") + local callbackNode = tolua.cast(documentCallbackNodes[i],"cc.Node") if "" ~= documentControllerName and nil ~= ccb[documentControllerName] then if "function" == type(ccb[documentControllerName][callbackName]) then proxy:setCallback(callbackNode, ccb[documentControllerName][callbackName], documentCallbackControlEvents[i]) @@ -75,7 +75,7 @@ function CCBReaderLoad(strFilePath,proxy,owner) for i = 1, table.getn(documentOutletNames) do local outletName = documentOutletNames[i] - local outletNode = tolua.cast(documentOutletNodes[i],"Node") + local outletNode = tolua.cast(documentOutletNodes[i],"cc.Node") if nil ~= ccb[documentControllerName] then ccb[documentControllerName][outletName] = tolua.cast(outletNode, proxy:getNodeTypeName(outletNode)) diff --git a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/CocosBuilderTest.lua b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/CocosBuilderTest.lua index a379690f84..590ae907b6 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/CocosBuilderTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/CocosBuilderTest.lua @@ -30,7 +30,7 @@ ccb["TestScrollViewsLayer"] = TestScrollViewsLayer local function onMenuItemAClicked() if nil ~= TestMenusLayer["mMenuItemStatusLabelBMFont"] then - local labelBmFt = tolua.cast(TestMenusLayer["mMenuItemStatusLabelBMFont"],"LabelBMFont") + local labelBmFt = tolua.cast(TestMenusLayer["mMenuItemStatusLabelBMFont"],"cc.LabelBMFont") if nil ~= labelBmFt then labelBmFt:setString("Menu Item A clicked."); end @@ -39,7 +39,7 @@ end local function onMenuItemBClicked() if nil ~= TestMenusLayer["mMenuItemStatusLabelBMFont"] then - local labelBmFt = tolua.cast(TestMenusLayer["mMenuItemStatusLabelBMFont"],"LabelBMFont") + local labelBmFt = tolua.cast(TestMenusLayer["mMenuItemStatusLabelBMFont"],"cc.LabelBMFont") if nil ~= labelBmFt then labelBmFt:setString("Menu Item B clicked."); end @@ -48,7 +48,7 @@ end local function pressedC( ... ) if nil ~= TestMenusLayer["mMenuItemStatusLabelBMFont"] then - local labelBmFt = tolua.cast(TestMenusLayer["mMenuItemStatusLabelBMFont"],"LabelBMFont") + local labelBmFt = tolua.cast(TestMenusLayer["mMenuItemStatusLabelBMFont"],"cc.LabelBMFont") if nil ~= labelBmFt then labelBmFt:setString("Menu Item C clicked."); end @@ -59,9 +59,9 @@ local function onMenuTestClicked() local scene = cc.Scene:create() local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/ccb/TestMenus.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") if nil ~= HelloCocosBuilderLayer["mTestTitleLabelTTF"] then - local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"LabelTTF") + local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:setString("ccb/ccb/TestMenus.ccbi") end @@ -88,9 +88,9 @@ local function onSpriteTestClicked() local scene = cc.Scene:create() local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/ccb/TestSprites.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") if nil ~= HelloCocosBuilderLayer["mTestTitleLabelTTF"] then - local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"LabelTTF") + local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:setString("ccb/ccb/TestSprites.ccbi") end @@ -107,9 +107,9 @@ local function onButtonTestClicked() local scene = cc.Scene:create() local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/ccb/TestButtons.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") if nil ~= HelloCocosBuilderLayer["mTestTitleLabelTTF"] then - local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"LabelTTF") + local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:setString("ccb/ccb/TestButtons.ccbi") end @@ -122,7 +122,7 @@ local function onButtonTestClicked() end local function onCCControlButtonClicked(sender,controlEvent) - local labelTTF = tolua.cast(TestButtonsLayer["mCCControlEventLabel"],"LabelBMFont") + local labelTTF = tolua.cast(TestButtonsLayer["mCCControlEventLabel"],"cc.LabelBMFont") if nil == labelTTF then return @@ -158,9 +158,9 @@ local function onAnimationsTestClicked() local scene = cc.Scene:create() local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/ccb/TestAnimations.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") if nil ~= HelloCocosBuilderLayer["mTestTitleLabelTTF"] then - local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"LabelTTF") + local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:setString("ccb/ccb/TestAnimations.ccbi") end @@ -177,9 +177,9 @@ local function onParticleSystemTestClicked() local scene = cc.Scene:create() local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/ccb/TestParticleSystems.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") if nil ~= HelloCocosBuilderLayer["mTestTitleLabelTTF"] then - local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"LabelTTF") + local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:setString("ccb/ccb/TestParticleSystems.ccbi") end @@ -193,7 +193,7 @@ end local function onCCControlButtonIdleClicked() if nil ~= TestAnimationsLayer["mAnimationManager"] then - local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"CCBAnimationManager") + local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"cc.CCBAnimationManager") if nil ~= animationMgr then animationMgr:runAnimationsForSequenceNamedTweenDuration("Idle", 0.3) end @@ -202,7 +202,7 @@ end local function onCCControlButtonWaveClicked() if nil ~= TestAnimationsLayer["mAnimationManager"] then - local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"CCBAnimationManager") + local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"cc.CCBAnimationManager") if nil ~= animationMgr then animationMgr:runAnimationsForSequenceNamedTweenDuration("Wave", 0.3) end @@ -211,7 +211,7 @@ end local function onCCControlButtonJumpClicked() if nil ~= TestAnimationsLayer["mAnimationManager"] then - local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"CCBAnimationManager") + local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"cc.CCBAnimationManager") if nil ~= animationMgr then animationMgr:runAnimationsForSequenceNamedTweenDuration("Jump", 0.3) end @@ -220,7 +220,7 @@ end local function onCCControlButtonFunkyClicked() if nil ~= TestAnimationsLayer["mAnimationManager"] then - local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"CCBAnimationManager") + local animationMgr = tolua.cast(TestAnimationsLayer["mAnimationManager"],"cc.CCBAnimationManager") if nil ~= animationMgr then animationMgr:runAnimationsForSequenceNamedTweenDuration("Funky", 0.3) end @@ -237,9 +237,9 @@ local function onScrollViewTestClicked() local scene = cc.Scene:create() local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/ccb/TestScrollViews.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") if nil ~= HelloCocosBuilderLayer["mTestTitleLabelTTF"] then - local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"LabelTTF") + local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:setString("ccb/ccb/TestScrollViews.ccbi") end @@ -256,9 +256,9 @@ local function onTimelineCallbackSoundClicked() local scene = cc.Scene:create() local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/ccb/TestTimelineCallback.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") if nil ~= HelloCocosBuilderLayer["mTestTitleLabelTTF"] then - local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"LabelTTF") + local ccLabelTTF = tolua.cast(HelloCocosBuilderLayer["mTestTitleLabelTTF"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:setString("ccb/ccb/TestTimelineCallback.ccbi") end @@ -272,7 +272,7 @@ end function onCallback1() if nil ~= TestTimelineLayer["helloLabel"] then - local ccLabelTTF = tolua.cast(TestTimelineLayer["helloLabel"],"LabelTTF") + local ccLabelTTF = tolua.cast(TestTimelineLayer["helloLabel"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:runAction(cc.RotateBy:create(1, 360)) ccLabelTTF:setString("Callback 1"); @@ -282,7 +282,7 @@ end function onCallback2() if nil ~= TestTimelineLayer["helloLabel"] then - local ccLabelTTF = tolua.cast(TestTimelineLayer["helloLabel"],"LabelTTF") + local ccLabelTTF = tolua.cast(TestTimelineLayer["helloLabel"],"cc.LabelTTF") if nil ~= ccLabelTTF then ccLabelTTF:runAction(cc.RotateBy:create(2, 360)) ccLabelTTF:setString("Callback 2"); @@ -306,7 +306,7 @@ local function HelloCCBTestMainLayer() print(type(cc.Scene)) local proxy = cc.CCBProxy:create() local node = CCBReaderLoad("cocosbuilderRes/ccb/HelloCocosBuilder.ccbi",proxy,HelloCocosBuilderLayer) - local layer = tolua.cast(node,"Layer") + local layer = tolua.cast(node,"cc.Layer") return layer end diff --git a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua index b831962568..4130913dc4 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua @@ -65,7 +65,7 @@ local function runNotificationCenterTest() local s = cc.Director:getInstance():getWinSize() local function toggleSwitch(tag,menuItem) - local toggleItem = tolua.cast(menuItem,"MenuItemToggle") + local toggleItem = tolua.cast(menuItem,"cc.MenuItemToggle") local nIndex = toggleItem:getSelectedIndex() local selectedItem = toggleItem:getSelectedItem() if 0 == nIndex then @@ -151,7 +151,7 @@ local function runNotificationCenterTest() connectitem:setTag(NotificationCenterParam.kTagConnect+i) local function connectToSwitch(tag,menuItem) - local connectMenuitem = tolua.cast(menuItem,"MenuItemToggle") + local connectMenuitem = tolua.cast(menuItem,"cc.MenuItemToggle") local bConnected = true if connectMenuitem:getSelectedIndex() == 0 then bConnected = false @@ -372,7 +372,7 @@ local function runCCControlTest() if nil == pSender or nil == pDisplayValueLabel then return end - local pControl = tolua.cast(pSender,"ControlSlider") + local pControl = tolua.cast(pSender,"cc.ControlSlider") local strFmt = nil if pControl:getTag() == 1 then strFmt = string.format("Upper slider value = %.02f",pControl:getValue()) @@ -430,7 +430,7 @@ local function runCCControlTest() return end - local pPicker = tolua.cast(pSender,"ControlColourPicker") + local pPicker = tolua.cast(pSender,"cc.ControlColourPicker") local strFmt = string.format("#%02X%02X%02X",pPicker:getColor().r, pPicker:getColor().g, pPicker:getColor().b) pColorLabel:setString(strFmt) end @@ -495,7 +495,7 @@ local function runCCControlTest() return end - local pControl = tolua.cast(pSender,"ControlSwitch") + local pControl = tolua.cast(pSender,"cc.ControlSwitch") if pControl:isOn() then pDisplayValueLabel:setString("On") else @@ -770,7 +770,7 @@ local function runCCControlTest() return end - local pControl = tolua.cast(pSender,"ControlPotentiometer") + local pControl = tolua.cast(pSender,"cc.ControlPotentiometer") local strFmt = string.format("%0.2f",pControl:getValue()) pDisplayValueLabel:setString(strFmt ) end @@ -827,7 +827,7 @@ local function runCCControlTest() return end - local pControl = tolua.cast(pSender,"ControlStepper") + local pControl = tolua.cast(pSender,"cc.ControlStepper") local strFmt = string.format("%0.02f",pControl:getValue() ) pDisplayValueLabel:setString(strFmt ) end @@ -913,7 +913,7 @@ local function runEditBoxTest() local EditEmail = nil local function editBoxTextEventHandle(strEventName,pSender) - local edit = tolua.cast(pSender,"EditBox") + local edit = tolua.cast(pSender,"cc.EditBox") local strFmt if strEventName == "began" then strFmt = string.format("editBox %p DidBegin !", edit) From 510fce7b121071978d237b10011b00a20c298413 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Wed, 15 Jan 2014 11:42:47 +0800 Subject: [PATCH 133/193] =?UTF-8?q?issue=20#3626:Add=20namespace=E2=80=99s?= =?UTF-8?q?=20support=20for=20manual=20lua=20binding=20of=20functions=20ab?= =?UTF-8?q?out=20physics?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bindings/lua_cocos2dx_physics_manual.cpp | 83 +++++++++---------- 1 file changed, 39 insertions(+), 44 deletions(-) diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_physics_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_physics_manual.cpp index 0d11f0f9b4..7da290e02a 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_physics_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_physics_manual.cpp @@ -29,7 +29,7 @@ int lua_cocos2dx_physics_PhysicsBody_getJoints(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsBody",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsBody",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsBody*)tolua_tousertype(tolua_S,1,0); @@ -69,7 +69,7 @@ int lua_cocos2dx_physics_PhysicsBody_getJoints(lua_State* tolua_S) if(name != g_luaType.end()){ className = name->second.c_str(); } else { - className = "PhysicsJoint"; + className = "cc.PhysicsJoint"; } lua_pushnumber(tolua_S, (lua_Number)indexTable); @@ -102,7 +102,7 @@ int lua_cocos2dx_physics_PhysicsWorld_getScene(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsWorld",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsWorld",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsWorld*)tolua_tousertype(tolua_S,1,0); @@ -129,7 +129,7 @@ int lua_cocos2dx_physics_PhysicsWorld_getScene(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "Scene"; + className = "cc.Scene"; } int ID = (int)(ret._ID); @@ -162,7 +162,7 @@ int lua_cocos2dx_physics_PhysicsWorld_rayCast(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsWorld",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsWorld",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsWorld*)tolua_tousertype(tolua_S,1,0); @@ -191,7 +191,7 @@ int lua_cocos2dx_physics_PhysicsWorld_rayCast(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsWorld"; + className = "cc.PhysicsWorld"; } tolua_pushusertype(tolua_S, (void*)(&world), className.c_str()); @@ -229,7 +229,7 @@ int lua_cocos2dx_physics_PhysicsWorld_queryRect(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsWorld",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsWorld",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsWorld*)tolua_tousertype(tolua_S,1,0); @@ -257,7 +257,7 @@ int lua_cocos2dx_physics_PhysicsWorld_queryRect(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsWorld"; + className = "cc.PhysicsWorld"; } tolua_pushusertype(tolua_S, (void*)(&world), className.c_str()); @@ -268,7 +268,7 @@ int lua_cocos2dx_physics_PhysicsWorld_queryRect(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsShape"; + className = "cc.PhysicsShape"; } toluafix_pushusertype_ccobject(tolua_S, shape._ID, &shape._luaID, (void*)(&shape), className.c_str()); return LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); @@ -305,7 +305,7 @@ int lua_cocos2dx_physics_PhysicsWorld_queryPoint(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsWorld",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsWorld",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsWorld*)tolua_tousertype(tolua_S,1,0); @@ -333,7 +333,7 @@ int lua_cocos2dx_physics_PhysicsWorld_queryPoint(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsWorld"; + className = "cc.PhysicsWorld"; } tolua_pushusertype(tolua_S, (void*)(&world), className.c_str()); @@ -344,7 +344,7 @@ int lua_cocos2dx_physics_PhysicsWorld_queryPoint(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsShape"; + className = "cc.PhysicsShape"; } toluafix_pushusertype_ccobject(tolua_S, shape._ID, &shape._luaID, (void*)(&shape), className.c_str()); return LuaEngine::getInstance()->getLuaStack()->executeFunctionByHandler(handler, 2); @@ -380,7 +380,7 @@ int lua_cocos2dx_physics_PhysicsBody_createPolygon(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertable(tolua_S,1,"PhysicsBody",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertable(tolua_S,1,"cc.PhysicsBody",0,&tolua_err)) goto tolua_lerror; #endif argc = lua_gettop(tolua_S) - 1; @@ -409,7 +409,7 @@ int lua_cocos2dx_physics_PhysicsBody_createPolygon(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -450,7 +450,7 @@ int lua_cocos2dx_physics_PhysicsBody_createPolygon(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -493,7 +493,7 @@ int lua_cocos2dx_physics_PhysicsBody_createPolygon(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -527,7 +527,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgePolygon(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertable(tolua_S,1,"PhysicsBody",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertable(tolua_S,1,"cc.PhysicsBody",0,&tolua_err)) goto tolua_lerror; #endif argc = lua_gettop(tolua_S) - 1; @@ -556,7 +556,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgePolygon(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -597,7 +597,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgePolygon(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -640,7 +640,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgePolygon(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -674,7 +674,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeChain(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertable(tolua_S,1,"PhysicsBody",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertable(tolua_S,1,"cc.PhysicsBody",0,&tolua_err)) goto tolua_lerror; #endif argc = lua_gettop(tolua_S) - 1; @@ -703,7 +703,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeChain(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -744,7 +744,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeChain(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -787,7 +787,7 @@ int lua_cocos2dx_physics_PhysicsBody_createEdgeChain(lua_State* tolua_S) if(iter != g_luaType.end()){ className = iter->second.c_str(); } else { - className = "PhysicsBody"; + className = "cc.PhysicsBody"; } cocos2d::Object *dynObject = dynamic_cast((cocos2d::PhysicsBody*)ret); if (NULL != dynObject) { @@ -821,7 +821,7 @@ int lua_cocos2dx_physics_PhysicsShape_recenterPoints(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertable(tolua_S,1,"PhysicsShape",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertable(tolua_S,1,"cc.PhysicsShape",0,&tolua_err)) goto tolua_lerror; #endif argc = lua_gettop(tolua_S) - 1; @@ -886,7 +886,7 @@ int lua_cocos2dx_physics_PhysicsShape_getPolyonCenter(lua_State* tolua_S) #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertable(tolua_S,1,"PhysicsShape",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertable(tolua_S,1,"cc.PhysicsShape",0,&tolua_err)) goto tolua_lerror; #endif argc = lua_gettop(tolua_S) - 1; @@ -924,14 +924,13 @@ int lua_cocos2dx_physics_PhysicsShapeBox_getPoints(lua_State* tolua_S) { int argc = 0; cocos2d::PhysicsShapeBox* cobj = nullptr; - bool ok = true; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsShapeBox",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsShapeBox",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsShapeBox*)tolua_tousertype(tolua_S,1,0); @@ -967,14 +966,13 @@ int lua_cocos2dx_physics_PhysicsShapePolygon_getPoints(lua_State* tolua_S) { int argc = 0; cocos2d::PhysicsShapePolygon* cobj = nullptr; - bool ok = true; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsShapePolygon",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsShapePolygon",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsShapePolygon*)tolua_tousertype(tolua_S,1,0); @@ -1012,14 +1010,13 @@ int lua_cocos2dx_physics_PhysicsShapeEdgeBox_getPoints(lua_State* tolua_S) { int argc = 0; cocos2d::PhysicsShapeEdgeBox* cobj = nullptr; - bool ok = true; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsShapeEdgeBox",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsShapeEdgeBox",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsShapeEdgeBox*)tolua_tousertype(tolua_S,1,0); @@ -1057,14 +1054,13 @@ int lua_cocos2dx_physics_PhysicsShapeEdgePolygon_getPoints(lua_State* tolua_S) { int argc = 0; cocos2d::PhysicsShapeEdgePolygon* cobj = nullptr; - bool ok = true; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsShapeEdgePolygon",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsShapeEdgePolygon",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsShapeEdgePolygon*)tolua_tousertype(tolua_S,1,0); @@ -1102,14 +1098,13 @@ int lua_cocos2dx_physics_PhysicsShapeEdgeChain_getPoints(lua_State* tolua_S) { int argc = 0; cocos2d::PhysicsShapeEdgeChain* cobj = nullptr; - bool ok = true; #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; #endif #if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"PhysicsShapeEdgeChain",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(tolua_S,1,"cc.PhysicsShapeEdgeChain",0,&tolua_err)) goto tolua_lerror; #endif cobj = (cocos2d::PhysicsShapeEdgeChain*)tolua_tousertype(tolua_S,1,0); @@ -1145,7 +1140,7 @@ tolua_lerror: int register_all_cocos2dx_physics_manual(lua_State* tolua_S) { - lua_pushstring(tolua_S, "PhysicsBody"); + lua_pushstring(tolua_S, "cc.PhysicsBody"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -1164,7 +1159,7 @@ int register_all_cocos2dx_physics_manual(lua_State* tolua_S) } lua_pop(tolua_S, 1); - lua_pushstring(tolua_S, "PhysicsShape"); + lua_pushstring(tolua_S, "cc.PhysicsShape"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -1177,7 +1172,7 @@ int register_all_cocos2dx_physics_manual(lua_State* tolua_S) } lua_pop(tolua_S, 1); - lua_pushstring(tolua_S, "PhysicsShapeBox"); + lua_pushstring(tolua_S, "cc.PhysicsShapeBox"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -1187,7 +1182,7 @@ int register_all_cocos2dx_physics_manual(lua_State* tolua_S) } lua_pop(tolua_S, 1); - lua_pushstring(tolua_S, "PhysicsShapeEdgeBox"); + lua_pushstring(tolua_S, "cc.PhysicsShapeEdgeBox"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -1197,7 +1192,7 @@ int register_all_cocos2dx_physics_manual(lua_State* tolua_S) } lua_pop(tolua_S, 1); - lua_pushstring(tolua_S, "PhysicsShapePolygon"); + lua_pushstring(tolua_S, "cc.PhysicsShapePolygon"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -1207,7 +1202,7 @@ int register_all_cocos2dx_physics_manual(lua_State* tolua_S) } lua_pop(tolua_S, 1); - lua_pushstring(tolua_S, "PhysicsShapeEdgePolygon"); + lua_pushstring(tolua_S, "cc.PhysicsShapeEdgePolygon"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -1217,7 +1212,7 @@ int register_all_cocos2dx_physics_manual(lua_State* tolua_S) } lua_pop(tolua_S, 1); - lua_pushstring(tolua_S, "PhysicsShapeEdgeChain"); + lua_pushstring(tolua_S, "cc.PhysicsShapeEdgeChain"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { @@ -1227,7 +1222,7 @@ int register_all_cocos2dx_physics_manual(lua_State* tolua_S) } lua_pop(tolua_S, 1); - lua_pushstring(tolua_S, "PhysicsWorld"); + lua_pushstring(tolua_S, "cc.PhysicsWorld"); lua_rawget(tolua_S, LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { From fdac224a7ba8e763c84b851b40af4123a71af7b7 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Wed, 15 Jan 2014 12:08:38 +0800 Subject: [PATCH 134/193] =?UTF-8?q?issue=20#3626:Add=20namespace=E2=80=99s?= =?UTF-8?q?=20support=20for=20manual=20lua=20binding=20functions=20for=20c?= =?UTF-8?q?lasses=20in=20the=20cocostudio=20and=20cocos2d::gui=20namespace?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lua_cocos2dx_coco_studio_manual.cpp | 16 +++++----- .../lua/bindings/lua_cocos2dx_gui_manual.cpp | 30 +++++++++---------- .../CocoStudioArmatureTest.lua | 2 +- .../CocoStudioGUITest.lua.REMOVED.git-id | 2 +- 4 files changed, 25 insertions(+), 25 deletions(-) diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_coco_studio_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_coco_studio_manual.cpp index 5120f1d966..581279907d 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_coco_studio_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_coco_studio_manual.cpp @@ -83,7 +83,7 @@ static int lua_cocos2dx_ArmatureAnimation_setMovementEventCallFunc(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"ArmatureAnimation",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccs.ArmatureAnimation",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -153,7 +153,7 @@ static int lua_cocos2dx_ArmatureAnimation_setFrameEventCallFunc(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"ArmatureAnimation",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccs.ArmatureAnimation",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -217,7 +217,7 @@ tolua_lerror: static void extendArmatureAnimation(lua_State* L) { - lua_pushstring(L, "ArmatureAnimation"); + lua_pushstring(L, "ccs.ArmatureAnimation"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -237,7 +237,7 @@ static int lua_cocos2dx_ArmatureDataManager_addArmatureFileInfoAsyncCallFunc(lua #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"ArmatureDataManager",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccs.ArmatureDataManager",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -309,7 +309,7 @@ tolua_lerror: static void extendArmatureDataManager(lua_State* L) { - lua_pushstring(L, "ArmatureDataManager"); + lua_pushstring(L, "ccs.ArmatureDataManager"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -328,7 +328,7 @@ static int lua_cocos2dx_extension_Bone_setIgnoreMovementBoneData(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"Bone",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccs.Bone",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -373,7 +373,7 @@ static int lua_cocos2dx_extension_Bone_getIgnoreMovementBoneData(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"Bone",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccs.Bone",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -405,7 +405,7 @@ tolua_lerror: static void extendBone(lua_State* L) { - lua_pushstring(L, "Bone"); + lua_pushstring(L, "ccs.Bone"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_gui_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_gui_manual.cpp index ec8a23ccd8..b51979ff53 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_gui_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_gui_manual.cpp @@ -94,7 +94,7 @@ static int lua_cocos2dx_Widget_addTouchEventListener(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"Widget",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.Widget",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -145,7 +145,7 @@ tolua_lerror: static void extendWidget(lua_State* L) { - lua_pushstring(L, "Widget"); + lua_pushstring(L, "ccui.Widget"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -164,7 +164,7 @@ static int lua_cocos2dx_CheckBox_addEventListenerCheckBox(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"CheckBox",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.CheckBox",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -214,7 +214,7 @@ tolua_lerror: static void extendCheckBox(lua_State* L) { - lua_pushstring(L, "CheckBox"); + lua_pushstring(L, "ccui.CheckBox"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -233,7 +233,7 @@ static int lua_cocos2dx_Slider_addEventListenerSlider(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"Slider",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.Slider",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -283,7 +283,7 @@ tolua_lerror: static void extendSlider(lua_State* L) { - lua_pushstring(L, "Slider"); + lua_pushstring(L, "ccui.Slider"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -302,7 +302,7 @@ static int lua_cocos2dx_TextField_addEventListenerTextField(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"TextField",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.TextField",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -352,7 +352,7 @@ tolua_lerror: static void extendTextField(lua_State* L) { - lua_pushstring(L, "TextField"); + lua_pushstring(L, "ccui.TextField"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -371,7 +371,7 @@ static int lua_cocos2dx_PageView_addEventListenerPageView(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"PageView",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.PageView",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -421,7 +421,7 @@ tolua_lerror: static void extendPageView(lua_State* L) { - lua_pushstring(L, "PageView"); + lua_pushstring(L, "ccui.PageView"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -440,7 +440,7 @@ static int lua_cocos2dx_ListView_addEventListenerListView(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"ListView",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.ListView",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -490,7 +490,7 @@ tolua_lerror: static void extendListView(lua_State* L) { - lua_pushstring(L, "ListView"); + lua_pushstring(L, "ccui.ListView"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { @@ -509,7 +509,7 @@ static int lua_cocos2dx_LayoutParameter_setMargin(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"LayoutParameter",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.LayoutParameter",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -577,7 +577,7 @@ static int lua_cocos2dx_LayoutParameter_getMargin(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"LayoutParameter",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"ccui.LayoutParameter",0,&tolua_err)) goto tolua_lerror; #endif self = static_cast(tolua_tousertype(L,1,0)); @@ -628,7 +628,7 @@ tolua_lerror: static void extendLayoutParameter(lua_State* L) { - lua_pushstring(L, "LayoutParameter"); + lua_pushstring(L, "ccui.LayoutParameter"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { diff --git a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua b/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua index d47b24034e..7c15e2900b 100644 --- a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioArmatureTest/CocoStudioArmatureTest.lua @@ -428,7 +428,7 @@ end function TestPerformance:refreshTitle() local subTitleInfo = ArmatureTestLayer.subTitle(5) .. self._armatureCount - local label = tolua.cast(self:getChildByTag(10001),"LabelTTF") + local label = tolua.cast(self:getChildByTag(10001),"cc.LabelTTF") label:setString(subTitleInfo) end diff --git a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioGUITest/CocoStudioGUITest.lua.REMOVED.git-id b/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioGUITest/CocoStudioGUITest.lua.REMOVED.git-id index 8d7bc14119..0279040f69 100644 --- a/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioGUITest/CocoStudioGUITest.lua.REMOVED.git-id +++ b/samples/Lua/TestLua/Resources/luaScript/CocoStudioTest/CocoStudioGUITest/CocoStudioGUITest.lua.REMOVED.git-id @@ -1 +1 @@ -1cb290e913d84d8cd141945c8b4a78ea45481cd5 \ No newline at end of file +09ed3c488f6d182685c416c291f8f325fb5cc2d2 \ No newline at end of file From 811aa69d397d8736239b87bfec43935644529ba7 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Wed, 15 Jan 2014 17:07:05 +0800 Subject: [PATCH 135/193] =?UTF-8?q?issue=20#3626:Add=20namespace=E2=80=99s?= =?UTF-8?q?=20support=20for=20manual=20lua=20binding=20functions=20for=20c?= =?UTF-8?q?lasses=20related=20OpenGL=20and=20update=20the=20related=20test?= =?UTF-8?q?=20cases?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/scripting/lua/bindings/LuaOpengl.cpp.REMOVED.git-id | 2 +- .../Lua/TestLua/Resources/luaScript/OpenGLTest/OpenGLTest.lua | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/scripting/lua/bindings/LuaOpengl.cpp.REMOVED.git-id b/cocos/scripting/lua/bindings/LuaOpengl.cpp.REMOVED.git-id index 42910a1d92..caaa6e32e0 100644 --- a/cocos/scripting/lua/bindings/LuaOpengl.cpp.REMOVED.git-id +++ b/cocos/scripting/lua/bindings/LuaOpengl.cpp.REMOVED.git-id @@ -1 +1 @@ -bcec27eb626dbcf63b810cce7f0f48b2d02c2158 \ No newline at end of file +bc70bac577759c95fbcf25da6937dbd9109da8d5 \ No newline at end of file diff --git a/samples/Lua/TestLua/Resources/luaScript/OpenGLTest/OpenGLTest.lua b/samples/Lua/TestLua/Resources/luaScript/OpenGLTest/OpenGLTest.lua index 91ac6844e4..e34f399e07 100644 --- a/samples/Lua/TestLua/Resources/luaScript/OpenGLTest/OpenGLTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/OpenGLTest/OpenGLTest.lua @@ -147,7 +147,7 @@ local function OpenGLTestMainLayer() local i = 0 local len = table.getn(children) for i= 0 ,len - 1 do - local child = tolua.cast(children[i + 1], "Sprite") + local child = tolua.cast(children[i + 1], "cc.Sprite") local oldPosX,oldPosY = child:getPosition() child:setPosition(oldPosX,math.sin(accum * 2 + i / 2.0) * 20) local scaleY = math.sin(accum * 2 + i / 2.0 + 0.707) @@ -558,7 +558,7 @@ local function OpenGLTestMainLayer() local function getCurrentResult() local var = {} - local glProgam = tolua.cast(sprite:getShaderProgram(),"GLProgram") + local glProgam = tolua.cast(sprite:getShaderProgram(),"cc.GLProgram") if nil ~= glProgam then local p = glProgam:getProgram() local aaSize,aaType,aaName = gl.getActiveAttrib(p,0) From de698aaea794241bc54557666922f127e019d9a1 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Wed, 15 Jan 2014 22:01:13 +0800 Subject: [PATCH 136/193] issue #3626:Add lua binding for ScollView and TableView classes in the cocos2d::extension namespace and the related test cases --- cocos/scripting/lua/bindings/CCLuaEngine.cpp | 96 ++- .../lua/bindings/LuaScriptHandlerMgr.cpp | 6 +- .../lua_cocos2dx_extension_manual.cpp | 666 ++++++++++++++++++ .../bindings/lua_cocos2dx_extension_manual.h | 11 + cocos/scripting/lua/script/Deprecated.lua | 15 + .../scripting/lua/script/DeprecatedClass.lua | 27 + .../luaScript/ExtensionTest/ExtensionTest.lua | 194 ++++- tools/tolua/cocos2dx_extension.ini | 6 +- 8 files changed, 1011 insertions(+), 10 deletions(-) diff --git a/cocos/scripting/lua/bindings/CCLuaEngine.cpp b/cocos/scripting/lua/bindings/CCLuaEngine.cpp index a05fa8f54d..d5980e7828 100644 --- a/cocos/scripting/lua/bindings/CCLuaEngine.cpp +++ b/cocos/scripting/lua/bindings/CCLuaEngine.cpp @@ -859,14 +859,102 @@ int LuaEngine::handleEvent(ScriptHandlerMgr::HandlerType type, void* data, int n int LuaEngine::handleTableViewEvent(ScriptHandlerMgr::HandlerType type,void* data) { - CCASSERT(0, "TableView is not bound yet"); - return 0; + if (nullptr == data) + return 0; + + BasicScriptData* eventData = static_cast(data); + if (nullptr == eventData->nativeObject || nullptr == eventData->value) + return 0; + + LuaTableViewEventData* tableViewData = static_cast(eventData->value); + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)eventData->nativeObject, type); + + if (0 == handler) + return 0; + + Object* obj = static_cast(eventData->nativeObject); + if (nullptr == obj) + return 0; + + int ret = 0; + switch (type) + { + case ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL: + case ScriptHandlerMgr::HandlerType::SCROLLVIEW_ZOOM: + { + toluafix_pushusertype_ccobject(_stack->getLuaState(), obj->_ID, &(obj->_luaID), (void*)(obj),"cc.TableView"); + ret = _stack->executeFunctionByHandler(handler, 1); + } + break; + case ScriptHandlerMgr::HandlerType::TABLECELL_TOUCHED: + case ScriptHandlerMgr::HandlerType::TABLECELL_HIGHLIGHT: + case ScriptHandlerMgr::HandlerType::TABLECELL_UNHIGHLIGHT: + case ScriptHandlerMgr::HandlerType::TABLECELL_WILL_RECYCLE: + { + Object* cellObject = static_cast(tableViewData->value); + if (nullptr == cellObject) { + break; + } + toluafix_pushusertype_ccobject(_stack->getLuaState(), obj->_ID, &(obj->_luaID), (void*)(obj),"cc.TableView"); + toluafix_pushusertype_ccobject(_stack->getLuaState(), cellObject->_ID, &(cellObject->_luaID), (void*)(cellObject),"cc.TableViewCell"); + ret = _stack->executeFunctionByHandler(handler, 2); + } + break; + default: + break; + } + + return ret; + } int LuaEngine::handleTableViewEvent(ScriptHandlerMgr::HandlerType handlerType,void* data, int numResults, const std::function& func) { - CCASSERT(0, "TableView is not bound yet"); - return 0; + if (nullptr == data || numResults <= 0) + return 0; + + BasicScriptData* eventData = static_cast(data); + if (nullptr == eventData->nativeObject || nullptr == eventData->value) + return 0; + + LuaTableViewEventData* tableViewData = static_cast(eventData->value); + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)eventData->nativeObject, handlerType); + + if (0 == handler) + return 0; + + Object* obj = static_cast(eventData->nativeObject); + if (nullptr == obj) + return 0; + + int ret = 0; + switch (handlerType) + { + case ScriptHandlerMgr::HandlerType::TABLECELL_SIZE_FOR_INDEX: + { + toluafix_pushusertype_ccobject(_stack->getLuaState(), obj->_ID, &(obj->_luaID), (void*)(obj),"cc.TableView"); + _stack->pushLong(*((ssize_t*)tableViewData->value)); + ret = _stack->executeFunction(handler, 2, 2, func); + } + break; + case ScriptHandlerMgr::HandlerType::TABLECELL_AT_INDEX: + { + toluafix_pushusertype_ccobject(_stack->getLuaState(), obj->_ID, &(obj->_luaID), (void*)(obj),"cc.TableView"); + _stack->pushLong(*((ssize_t*)tableViewData->value)); + ret = _stack->executeFunction(handler, 2, 1, func); + } + break; + case ScriptHandlerMgr::HandlerType::TABLEVIEW_NUMS_OF_CELLS: + { + toluafix_pushusertype_ccobject(_stack->getLuaState(), obj->_ID, &(obj->_luaID), (void*)(obj),"cc.TableView"); + ret = _stack->executeFunction(handler, 1, 1, func); + } + break; + default: + break; + } + + return ret; } int LuaEngine::handleAssetsManagerEvent(ScriptHandlerMgr::HandlerType type,void* data) diff --git a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp index 81317d65d7..c781d5b1ec 100644 --- a/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp +++ b/cocos/scripting/lua/bindings/LuaScriptHandlerMgr.cpp @@ -282,7 +282,7 @@ static int tolua_Cocos2d_ScriptHandlerMgr_registerScriptHandler00(lua_State* tol #ifndef TOLUA_RELEASE tolua_Error tolua_err; if (!tolua_isusertype(tolua_S,1,"ScriptHandlerMgr",0,&tolua_err) || - !tolua_isusertype(tolua_S, 2, "Object", 0, &tolua_err) || + !tolua_isusertype(tolua_S, 2, "cc.Object", 0, &tolua_err) || !toluafix_isfunction(tolua_S, 3, "LUA_FUNCTION", 0, &tolua_err) || !tolua_isnumber(tolua_S, 4, 0, &tolua_err) || !tolua_isnoobj(tolua_S,5,&tolua_err) ) @@ -316,7 +316,7 @@ static int tolua_Cocos2d_ScriptHandlerMgr_unregisterScriptHandler00(lua_State* t #ifndef TOLUA_RELEASE tolua_Error tolua_err; if (!tolua_isusertype(tolua_S,1,"ScriptHandlerMgr",0,&tolua_err) || - !tolua_isusertype(tolua_S, 2, "Object", 0, &tolua_err) || + !tolua_isusertype(tolua_S, 2, "cc.Object", 0, &tolua_err) || !tolua_isnumber(tolua_S, 3, 0, &tolua_err) || !tolua_isnoobj(tolua_S,4,&tolua_err) ) goto tolua_lerror; @@ -348,7 +348,7 @@ static int tolua_Cocos2d_ScriptHandlerMgr_removeObjectAllHandlers00(lua_State* t #ifndef TOLUA_RELEASE tolua_Error tolua_err; if (!tolua_isusertype(tolua_S,1,"ScriptHandlerMgr",0,&tolua_err) || - !tolua_isusertype(tolua_S, 2, "Object", 0, &tolua_err) || + !tolua_isusertype(tolua_S, 2, "cc.Object", 0, &tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) goto tolua_lerror; else diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp index 195cd72d18..f57d7024e1 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp @@ -42,6 +42,203 @@ USING_NS_CC; USING_NS_CC_EXT; using namespace cocostudio; +class LuaScrollViewDelegate:public Object, public ScrollViewDelegate +{ +public: + virtual ~LuaScrollViewDelegate() + {} + + virtual void scrollViewDidScroll(ScrollView* view) + { + if (nullptr != view) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)view, ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL); + if (0 != handler) + { + CommonScriptData data(handler,""); + ScriptEvent event(kCommonEvent,(void*)&data); + LuaEngine::getInstance()->sendEvent(&event); + } + + } + } + + virtual void scrollViewDidZoom(ScrollView* view) + { + if (nullptr != view) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)view, ScriptHandlerMgr::HandlerType::SCROLLVIEW_ZOOM); + if (0 != handler) + { + CommonScriptData data(handler,""); + ScriptEvent event(kCommonEvent,(void*)&data); + LuaEngine::getInstance()->sendEvent(&event); + } + } + } +}; + +static int tolua_cocos2dx_ScrollView_setDelegate(lua_State* tolua_S) +{ + if (nullptr == tolua_S) + return 0; + + int argc = 0; + ScrollView* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(tolua_S,1,"cc.ScrollView",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (ScrollView*) tolua_tousertype(tolua_S,1,0); +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(tolua_S,"invalid 'self' in function 'tolua_cocos2dx_ScrollView_setDelegate'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S) - 1; + + if (0 == argc) + { + LuaScrollViewDelegate* delegate = new LuaScrollViewDelegate(); + if (nullptr == delegate) + return 0; + + self->setUserObject(delegate); + self->setDelegate(delegate); + + delegate->release(); + + return 0; + } + + CCLOG("'setDelegate' function of ScrollView wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'setDelegate'.",&tolua_err); + return 0; +#endif +} + +static int tolua_cocos2d_ScrollView_registerScriptHandler(lua_State* tolua_S) +{ + if (NULL == tolua_S) + return 0; + + int argc = 0; + ScrollView* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(tolua_S,1,"cc.ScrollView",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(tolua_S,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(tolua_S,"invalid 'self' in function 'tolua_cocos2d_ScrollView_registerScriptHandler'\n", NULL); + return 0; + } +#endif + argc = lua_gettop(tolua_S) - 1; + if (2 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!toluafix_isfunction(tolua_S,2,"LUA_FUNCTION",0,&tolua_err) || + !tolua_isnumber(tolua_S, 3, 0, &tolua_err) ) + { + goto tolua_lerror; + } +#endif + LUA_FUNCTION handler = ( toluafix_ref_function(tolua_S,2,0)); + ScriptHandlerMgr::HandlerType handlerType = (ScriptHandlerMgr::HandlerType) ((int)tolua_tonumber(tolua_S,3,0) + (int)ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL); + + ScriptHandlerMgr::getInstance()->addObjectHandler((void*)self, handler, handlerType); + return 0; + } + + CCLOG("'registerScriptHandler' function of ScrollView has wrong number of arguments: %d, was expecting %d\n", argc, 2); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'registerScriptHandler'.",&tolua_err); + return 0; +#endif +} + +static int tolua_cocos2d_ScrollView_unregisterScriptHandler(lua_State* tolua_S) +{ + if (NULL == tolua_S) + return 0; + + int argc = 0; + ScrollView* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(tolua_S,1,"cc.ScrollView",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(tolua_S,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(tolua_S,"invalid 'self' in function 'tolua_cocos2d_ScrollView_unregisterScriptHandler'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(tolua_S) - 1; + + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isnumber(tolua_S, 2, 0, &tolua_err)) + goto tolua_lerror; +#endif + ScriptHandlerMgr::HandlerType handlerType = (ScriptHandlerMgr::HandlerType) ((int)tolua_tonumber(tolua_S,2,0) + (int)ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL); + ScriptHandlerMgr::getInstance()->removeObjectHandler((void*)self, handlerType); + return 0; + } + + CCLOG("'unregisterScriptHandler' function of ScrollView has wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'unregisterScriptHandler'.",&tolua_err); + return 0; +#endif +} + +static void extendScrollView(lua_State* tolua_S) +{ + lua_pushstring(tolua_S, "cc.ScrollView"); + lua_rawget(tolua_S, LUA_REGISTRYINDEX); + if (lua_istable(tolua_S,-1)) + { + lua_pushstring(tolua_S,"setDelegate"); + lua_pushcfunction(tolua_S,tolua_cocos2dx_ScrollView_setDelegate ); + lua_rawset(tolua_S,-3); + lua_pushstring(tolua_S,"registerScriptHandler"); + lua_pushcfunction(tolua_S,tolua_cocos2d_ScrollView_registerScriptHandler ); + lua_rawset(tolua_S,-3); + lua_pushstring(tolua_S,"unregisterScriptHandler"); + lua_pushcfunction(tolua_S,tolua_cocos2d_ScrollView_unregisterScriptHandler ); + lua_rawset(tolua_S,-3); + } + lua_pop(tolua_S, 1); +} + + static int tolua_cocos2d_Control_registerControlEventHandler(lua_State* tolua_S) { if (NULL == tolua_S) @@ -800,6 +997,473 @@ static void extendAssetsManager(lua_State* L) lua_pop(L, 1); } +#define KEY_TABLEVIEW_DATA_SOURCE "TableViewDataSource" +#define KEY_TABLEVIEW_DELEGATE "TableViewDelegate" + +class LUA_TableViewDelegate:public Object, public TableViewDelegate +{ +public: + LUA_TableViewDelegate(){} + + virtual ~LUA_TableViewDelegate(){} + + + virtual void scrollViewDidScroll(ScrollView* view) + { + if (nullptr != view) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)view, ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL); + if (0 != handler) + { + LuaTableViewEventData eventData; + BasicScriptData data(view,&eventData); + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL, (void*)&data); + } + } + } + + virtual void scrollViewDidZoom(ScrollView* view) + { + if (nullptr != view) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)view, ScriptHandlerMgr::HandlerType::SCROLLVIEW_ZOOM); + if (0 != handler) + { + LuaTableViewEventData eventData; + BasicScriptData data(view,&eventData); + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::SCROLLVIEW_ZOOM, (void*)&data); + } + } + } + + virtual void tableCellTouched(TableView* table, TableViewCell* cell) + { + if (nullptr != table && nullptr != cell) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)table, ScriptHandlerMgr::HandlerType::TABLECELL_TOUCHED); + if (0 != handler) + { + LuaTableViewEventData eventData(cell); + BasicScriptData data(table,&eventData); + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::TABLECELL_TOUCHED,(void*)&data); + } + } + } + + virtual void tableCellHighlight(TableView* table, TableViewCell* cell) + { + if (nullptr != table && nullptr != cell) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)table, ScriptHandlerMgr::HandlerType::TABLECELL_HIGHLIGHT); + if (0 != handler) + { + LuaTableViewEventData eventData(cell); + BasicScriptData data(table,&eventData); + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::TABLECELL_HIGHLIGHT,(void*)&data); + } + } + } + + virtual void tableCellUnhighlight(TableView* table, TableViewCell* cell) + { + if (nullptr != table && nullptr != cell) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)table, ScriptHandlerMgr::HandlerType::TABLECELL_UNHIGHLIGHT); + if (0 != handler) + { + LuaTableViewEventData eventData(cell); + BasicScriptData data(table,&eventData); + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::TABLECELL_UNHIGHLIGHT,(void*)&data); + } + } + } + + virtual void tableCellWillRecycle(TableView* table, TableViewCell* cell) + { + if (nullptr != table && nullptr != cell) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)table, ScriptHandlerMgr::HandlerType::TABLECELL_WILL_RECYCLE); + if (0 != handler) + { + LuaTableViewEventData eventData(cell); + BasicScriptData data(table,&eventData); + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::TABLECELL_WILL_RECYCLE,(void*)&data); + } + } + } +}; + +static int lua_cocos2dx_TableView_setDelegate(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + TableView* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"cc.TableView",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (TableView*) tolua_tousertype(L,1,0); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_TableView_setDelegate'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (0 == argc) + { + LUA_TableViewDelegate* delegate = new LUA_TableViewDelegate(); + if (nullptr == delegate) + return 0; + + Dictionary* userDict = static_cast(self->getUserObject()); + if (nullptr == userDict) + { + userDict = new Dictionary(); + if (NULL == userDict) + return 0; + + self->setUserObject(userDict); + userDict->release(); + } + + userDict->setObject(delegate, KEY_TABLEVIEW_DELEGATE); + self->setDelegate(delegate); + delegate->release(); + + return 0; + } + + CCLOG("'setDelegate' function of TableView wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'setDelegate'.",&tolua_err); + return 0; +#endif +} + +class LUA_TableViewDataSource:public Object,public TableViewDataSource +{ +public: + LUA_TableViewDataSource(){} + virtual ~LUA_TableViewDataSource(){} + + virtual Size tableCellSizeForIndex(TableView *table, ssize_t idx) + { + if (nullptr != table ) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)table, ScriptHandlerMgr::HandlerType::TABLECELL_SIZE_FOR_INDEX); + if (0 != handler) + { + LuaTableViewEventData eventData(&idx); + BasicScriptData data(table,&eventData); + float width = 0.0; + float height = 0.0; + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::TABLECELL_SIZE_FOR_INDEX, (void*)&data,2,[&](lua_State* L,int numReturn){ + CCASSERT(numReturn == 2, "tableCellSizeForIndex return count error"); + ValueVector vec; + width = (float)tolua_tonumber(L, -1, 0); + lua_pop(L, 1); + height = (float)tolua_tonumber(L, -1, 0); + lua_pop(L, 1); + }); + + return Size(width, height); + } + } + + return Size::ZERO; + } + + virtual TableViewCell* tableCellAtIndex(TableView *table, ssize_t idx) + { + if (nullptr != table ) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)table, ScriptHandlerMgr::HandlerType::TABLECELL_AT_INDEX); + if (0 != handler) + { + LuaTableViewEventData eventData(&idx); + BasicScriptData data(table,&eventData); + TableViewCell* viewCell = nullptr; + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::TABLECELL_AT_INDEX, (void*)&data, 1, [&](lua_State* L, int numReturn){ + CCASSERT(numReturn == 1, "tableCellAtIndex return count error"); + viewCell = static_cast(tolua_tousertype(L, -1, nullptr)); + lua_pop(L, 1); + }); + + return viewCell; + } + } + + return NULL; + } + + virtual ssize_t numberOfCellsInTableView(TableView *table) + { + if (nullptr != table ) + { + int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)table, ScriptHandlerMgr::HandlerType::TABLEVIEW_NUMS_OF_CELLS); + if (0 != handler) + { + LuaTableViewEventData eventData; + BasicScriptData data(table,&eventData); + ssize_t counts = 0; + LuaEngine::getInstance()->handleEvent(ScriptHandlerMgr::HandlerType::TABLEVIEW_NUMS_OF_CELLS, (void*)&data,1, [&](lua_State* L, int numReturn){ + CCASSERT(numReturn == 1, "numberOfCellsInTableView return count error"); + counts = (ssize_t)tolua_tonumber(L, -1, 0); + lua_pop(L, 1); + }); + return counts; + } + } + return 0; + } +}; + +static int lua_cocos2dx_TableView_setDataSource(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + TableView* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"cc.TableView",0,&tolua_err)) goto tolua_lerror; +#endif + + self = (TableView*) tolua_tousertype(L,1,0); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) + { + tolua_error(L,"invalid 'self' in function 'lua_cocos2dx_TableView_setDataSource'\n", nullptr); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (0 == argc) + { + LUA_TableViewDataSource* dataSource = new LUA_TableViewDataSource(); + if (nullptr == dataSource) + return 0; + + Dictionary* userDict = static_cast(self->getUserObject()); + if (nullptr == userDict) + { + userDict = new Dictionary(); + if (NULL == userDict) + return 0; + + self->setUserObject(userDict); + userDict->release(); + } + + userDict->setObject(dataSource, KEY_TABLEVIEW_DATA_SOURCE); + + self->setDataSource(dataSource); + + dataSource->release(); + + return 0; + } + + CCLOG("'setDataSource' function of TableView wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'setDataSource'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2dx_TableView_create(lua_State* L) +{ + if (nullptr == L) + return 0; + + int argc = 0; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertable(L,1,"cc.TableView",0,&tolua_err)) goto tolua_lerror; +#endif + + argc = lua_gettop(L) - 1; + + if (2 == argc || 1 == argc) + { + LUA_TableViewDataSource* dataSource = new LUA_TableViewDataSource(); + Size size; + ok &= luaval_to_size(L, 2, &size); + + TableView* ret = nullptr; + + if (1 == argc) + { + ret = TableView::create(dataSource, size); + } + else + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(L,3,"cc.Node",0,&tolua_err)) goto tolua_lerror; +#endif + Node* node = static_cast(tolua_tousertype(L, 3, nullptr)); + ret = TableView::create(dataSource, size, node); + } + + if (nullptr == ret) + return 0; + + ret->reloadData(); + + Dictionary* userDict = new Dictionary(); + userDict->setObject(dataSource, KEY_TABLEVIEW_DATA_SOURCE); + ret->setUserObject(userDict); + userDict->release(); + + dataSource->release(); + + + int nID = (int)ret->_ID; + int* pLuaID = &ret->_luaID; + toluafix_pushusertype_ccobject(L, nID, pLuaID, (void*)ret,"cc.TableView"); + + return 1; + } + CCLOG("'create' function of TableView wrong number of arguments: %d, was expecting %d\n", argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'create'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2d_TableView_registerScriptHandler(lua_State* L) +{ + if (NULL == L) + return 0; + + int argc = 0; + TableView* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"cc.TableView",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(L,"invalid 'self' in function 'tolua_cocos2d_TableView_registerScriptHandler'\n", NULL); + return 0; + } +#endif + argc = lua_gettop(L) - 1; + if (2 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!toluafix_isfunction(L,2,"LUA_FUNCTION",0,&tolua_err) || + !tolua_isnumber(L, 3, 0, &tolua_err) ) + { + goto tolua_lerror; + } +#endif + LUA_FUNCTION handler = ( toluafix_ref_function(L,2,0)); + ScriptHandlerMgr::HandlerType handlerType = (ScriptHandlerMgr::HandlerType) ((int)tolua_tonumber(L,3,0) + (int)ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL); + + ScriptHandlerMgr::getInstance()->addObjectHandler((void*)self, handler, handlerType); + return 0; + } + + CCLOG("'registerScriptHandler' function of TableView has wrong number of arguments: %d, was expecting %d\n", argc, 2); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'registerScriptHandler'.",&tolua_err); + return 0; +#endif +} + +static int lua_cocos2d_TableView_unregisterScriptHandler(lua_State* L) +{ + if (NULL == L) + return 0; + + int argc = 0; + TableView* self = nullptr; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; + if (!tolua_isusertype(L,1,"cc.TableView",0,&tolua_err)) goto tolua_lerror; +#endif + + self = static_cast(tolua_tousertype(L,1,0)); + +#if COCOS2D_DEBUG >= 1 + if (nullptr == self) { + tolua_error(L,"invalid 'self' in function 'lua_cocos2d_TableView_unregisterScriptHandler'\n", NULL); + return 0; + } +#endif + + argc = lua_gettop(L) - 1; + + if (1 == argc) + { +#if COCOS2D_DEBUG >= 1 + if (!tolua_isnumber(L, 2, 0, &tolua_err)) + goto tolua_lerror; +#endif + ScriptHandlerMgr::HandlerType handlerType = (ScriptHandlerMgr::HandlerType) ((int)tolua_tonumber(L,2,0) + (int)ScriptHandlerMgr::HandlerType::SCROLLVIEW_SCROLL); + ScriptHandlerMgr::getInstance()->removeObjectHandler((void*)self, handlerType); + return 0; + } + + CCLOG("'unregisterScriptHandler' function of TableView has wrong number of arguments: %d, was expecting %d\n", argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 +tolua_lerror: + tolua_error(L,"#ferror in function 'unregisterScriptHandler'.",&tolua_err); + return 0; +#endif +} + +static void extendTableView(lua_State* L) +{ + lua_pushstring(L, "cc.TableView"); + lua_rawget(L, LUA_REGISTRYINDEX); + if (lua_istable(L,-1)) + { + tolua_function(L, "setDelegate", lua_cocos2dx_TableView_setDelegate); + tolua_function(L, "setDataSource", lua_cocos2dx_TableView_setDataSource); + tolua_function(L, "create", lua_cocos2dx_TableView_create); + tolua_function(L, "registerScriptHandler", lua_cocos2d_TableView_registerScriptHandler); + tolua_function(L, "unregisterScriptHandler", lua_cocos2d_TableView_unregisterScriptHandler); + } + lua_pop(L, 1); +} + int register_all_cocos2dx_extension_manual(lua_State* tolua_S) { extendControl(tolua_S); @@ -807,5 +1471,7 @@ int register_all_cocos2dx_extension_manual(lua_State* tolua_S) extendCCBReader(tolua_S); extendCCBAnimationManager(tolua_S); extendAssetsManager(tolua_S); + extendScrollView(tolua_S); + extendTableView(tolua_S); return 0; } diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.h b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.h index 1a76eaf316..b150bf3cbd 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.h +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.h @@ -46,5 +46,16 @@ struct LuaAssetsManagerEventData } }; +struct LuaTableViewEventData +{ + void* value; + + // Constructor + LuaTableViewEventData(void* _value = nullptr) + :value(_value) + { + } +}; + #endif // #ifndef COCOS2DX_SCRIPT_LUA_COCOS2DX_SUPPORT_LUA_COCOS2DX_EXTENSION_MANUAL_H diff --git a/cocos/scripting/lua/script/Deprecated.lua b/cocos/scripting/lua/script/Deprecated.lua index e48ba122e9..38ae6ff614 100644 --- a/cocos/scripting/lua/script/Deprecated.lua +++ b/cocos/scripting/lua/script/Deprecated.lua @@ -706,6 +706,21 @@ end rawset(CCEGLView,"sharedOpenGLView",CCEGLViewDeprecated.sharedOpenGLView) --functions of CCFileUtils will be deprecated end +--Enums of CCTableView will be deprecated begin +rawset(CCTableView, "kTableViewScroll",cc.SCROLLVIEW_SCRIPT_SCROLL) +rawset(CCTableView,"kTableViewZoom",cc.SCROLLVIEW_SCRIPT_ZOOM) +rawset(CCTableView,"kTableCellTouched",cc.TABLECELL_TOUCHED) +rawset(CCTableView,"kTableCellSizeForIndex",cc.TABLECELL_SIZE_FOR_INDEX) +rawset(CCTableView,"kTableCellSizeAtIndex",cc.TABLECELL_SIZE_AT_INDEX) +rawset(CCTableView,"kNumberOfCellsInTableView",cc.NUMBER_OF_CELLS_IN_TABLEVIEW) +--Enums of CCTableView will be deprecated end + +--Enums of CCScrollView will be deprecated begin +rawset(CCScrollView, "kScrollViewScroll",cc.SCROLLVIEW_SCRIPT_SCROLL) +rawset(CCScrollView,"kScrollViewZoom",cc.SCROLLVIEW_SCRIPT_ZOOM) +--Enums of CCScrollView will be deprecated end + + --functions of CCApplication will be deprecated end local CCApplicationDeprecated = { } diff --git a/cocos/scripting/lua/script/DeprecatedClass.lua b/cocos/scripting/lua/script/DeprecatedClass.lua index c899d0a0dc..647d92357c 100644 --- a/cocos/scripting/lua/script/DeprecatedClass.lua +++ b/cocos/scripting/lua/script/DeprecatedClass.lua @@ -175,6 +175,15 @@ end _G["CCEaseElasticOut"] = DeprecatedClass.CCEaseElasticOut() --CCEaseElasticOut class will be Deprecated,end +--CCTableViewCell class will be Deprecated,begin +function DeprecatedClass.CCTableViewCell() + deprecatedTip("CCTableViewCell","cc.TableViewCell") + return cc.TableViewCell +end +_G["CCTableViewCell"] = DeprecatedClass.CCTableViewCell() +--CCTableViewCell class will be Deprecated,end + + --CCEaseBackOut class will be Deprecated,begin function DeprecatedClass.CCEaseBackOut() deprecatedTip("CCEaseBackOut","cc.EaseBackOut") @@ -719,6 +728,15 @@ end _G["CCPlace"] = DeprecatedClass.CCPlace() --CCPlace class will be Deprecated,end +--CCScrollView class will be Deprecated,begin +function DeprecatedClass.CCScrollView() + deprecatedTip("CCScrollView","cc.ScrollView") + return cc.ScrollView +end +_G["CCScrollView"] = DeprecatedClass.CCScrollView() +--CCScrollView class will be Deprecated,end + + --CCGLProgram class will be Deprecated,begin function DeprecatedClass.CCGLProgram() deprecatedTip("CCGLProgram","cc.GLProgram") @@ -799,6 +817,15 @@ end _G["CCParticleFlower"] = DeprecatedClass.CCParticleFlower() --CCParticleFlower class will be Deprecated,end +--CCTableView class will be Deprecated,begin +function DeprecatedClass.CCTableView() + deprecatedTip("CCTableView","cc.TableView") + return cc.TableView +end +_G["CCTableView"] = DeprecatedClass.CCTableView() +--CCTableView class will be Deprecated,end + + --CCParticleSmoke class will be Deprecated,begin function DeprecatedClass.CCParticleSmoke() deprecatedTip("CCParticleSmoke","cc.ParticleSmoke") diff --git a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua index 4130913dc4..361dd03615 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/ExtensionTest.lua @@ -11,7 +11,9 @@ local ExtensionTestEnum = TEST_COCOSBUILDER = 2, TEST_WEBSOCKET = 3, TEST_EDITBOX = 4, - TEST_MAX_COUNT = 5, + TEST_TABLEVIEW = 5, + TEST_SCROLLVIEW = 6, + TEST_MAX_COUNT = 7, } local testsName = @@ -21,6 +23,8 @@ local testsName = "CocosBuilderTest", "WebSocketTest", "EditBoxTest", + "TableViewTest", + "ScrollViewTest", } @@ -988,6 +992,192 @@ local function runEditBoxTest() return newScene end +local TableViewTestLayer = class("TableViewTestLayer") +TableViewTestLayer.__index = TableViewTestLayer + +function TableViewTestLayer.extend(target) + local t = tolua.getpeer(target) + if not t then + t = {} + tolua.setpeer(target, t) + end + setmetatable(t, TableViewTestLayer) + return target +end + +function TableViewTestLayer.scrollViewDidScroll(view) + print("scrollViewDidScroll") +end + +function TableViewTestLayer.scrollViewDidZoom(view) + print("scrollViewDidZoom") +end + +function TableViewTestLayer.tableCellTouched(table,cell) + print("cell touched at index: " .. cell:getIdx()) +end + +function TableViewTestLayer.cellSizeForTable(table,idx) + return 60,60 +end + +function TableViewTestLayer.tableCellAtIndex(table, idx) + local strValue = string.format("%d",idx) + local cell = table:dequeueCell() + local label = nil + if nil == cell then + cell = cc.TableViewCell:new() + local sprite = cc.Sprite:create("Images/Icon.png") + sprite:setAnchorPoint(cc.p(0,0)) + sprite:setPosition(cc.p(0, 0)) + cell:addChild(sprite) + + label = cc.LabelTTF:create(strValue, "Helvetica", 20.0) + label:setPosition(cc.p(0,0)) + label:setAnchorPoint(cc.p(0,0)) + label:setTag(123) + cell:addChild(label) + else + label = tolua.cast(cell:getChildByTag(123),"cc.LabelTTF") + if nil ~= label then + label:setString(strValue) + end + end + + return cell +end + +function TableViewTestLayer.numberOfCellsInTableView(table) + return 25 +end + +function TableViewTestLayer:init() + + local winSize = cc.Director:getInstance():getWinSize() + + local tableView = cc.TableView:create(cc.size(600,60)) + tableView:setDirection(cc.SCROLLVIEW_DIRECTION_HORIZONTAL) + tableView:setPosition(cc.p(20, winSize.height / 2 - 150)) + tableView:setDelegate() + self:addChild(tableView) + --registerScriptHandler functions must be before the reloadData funtion + tableView:registerScriptHandler(TableViewTestLayer.numberOfCellsInTableView,cc.NUMBER_OF_CELLS_IN_TABLEVIEW) + tableView:registerScriptHandler(TableViewTestLayer.scrollViewDidScroll,cc.SCROLLVIEW_SCRIPT_SCROLL) + tableView:registerScriptHandler(TableViewTestLayer.scrollViewDidZoom,cc.SCROLLVIEW_SCRIPT_ZOOM) + tableView:registerScriptHandler(TableViewTestLayer.tableCellTouched,cc.TABLECELL_TOUCHED) + tableView:registerScriptHandler(TableViewTestLayer.cellSizeForTable,cc.TABLECELL_SIZE_FOR_INDEX) + tableView:registerScriptHandler(TableViewTestLayer.tableCellAtIndex,cc.TABLECELL_SIZE_AT_INDEX) + tableView:reloadData() + + tableView = cc.TableView:create(cc.size(60, 350)) + tableView:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL) + tableView:setPosition(cc.p(winSize.width - 150, winSize.height / 2 - 150)) + tableView:setDelegate() + tableView:setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN) + self:addChild(tableView) + tableView:registerScriptHandler(TableViewTestLayer.scrollViewDidScroll,cc.SCROLLVIEW_SCRIPT_SCROLL) + tableView:registerScriptHandler(TableViewTestLayer.scrollViewDidZoom,cc.SCROLLVIEW_SCRIPT_ZOOM) + tableView:registerScriptHandler(TableViewTestLayer.tableCellTouched,cc.TABLECELL_TOUCHED) + tableView:registerScriptHandler(TableViewTestLayer.cellSizeForTable,cc.TABLECELL_SIZE_FOR_INDEX) + tableView:registerScriptHandler(TableViewTestLayer.tableCellAtIndex,cc.TABLECELL_SIZE_AT_INDEX) + tableView:registerScriptHandler(TableViewTestLayer.numberOfCellsInTableView,cc.NUMBER_OF_CELLS_IN_TABLEVIEW) + tableView:reloadData() + + -- Back Menu + local pToMainMenu = cc.Menu:create() + CreateExtensionsBasicLayerMenu(pToMainMenu) + pToMainMenu:setPosition(cc.p(0, 0)) + self:addChild(pToMainMenu,10) + + return true +end + +function TableViewTestLayer.create() + local layer = TableViewTestLayer.extend(cc.Layer:create()) + if nil ~= layer then + layer:init() + end + + return layer +end + +local function runTableViewTest() + local newScene = cc.Scene:create() + local newLayer = TableViewTestLayer.create() + newScene:addChild(newLayer) + return newScene +end + +local function runScrollViewTest() + local newScene = cc.Scene:create() + local newLayer = cc.Layer:create() + + -- Back Menu + local pToMainMenu = cc.Menu:create() + CreateExtensionsBasicLayerMenu(pToMainMenu) + pToMainMenu:setPosition(cc.p(0, 0)) + newLayer:addChild(pToMainMenu,10) + + local layerColor = cc.LayerColor:create(cc.c4b(128,64,0,255)) + newLayer:addChild(layerColor) + + local scrollView1 = cc.ScrollView:create() + local screenSize = cc.Director:getInstance():getWinSize() + local function scrollView1DidScroll() + print("scrollView1DidScroll") + end + local function scrollView1DidZoom() + print("scrollView1DidZoom") + end + if nil ~= scrollView1 then + scrollView1:setViewSize(cc.size(screenSize.width / 2,screenSize.height)) + scrollView1:setPosition(cc.p(0,0)) + scrollView1:setScale(1.0) + scrollView1:ignoreAnchorPointForPosition(true) + local flowersprite1 = cc.Sprite:create("ccb/flower.jpg") + if nil ~= flowersprite1 then + scrollView1:setContainer(flowersprite1) + scrollView1:updateInset() + end + scrollView1:setDirection(cc.SCROLLVIEW_DIRECTION_BOTH ) + scrollView1:setClippingToBounds(true) + scrollView1:setBounceable(true) + scrollView1:setDelegate() + scrollView1:registerScriptHandler(scrollView1DidScroll,cc.SCROLLVIEW_SCRIPT_SCROLL) + scrollView1:registerScriptHandler(scrollView1DidZoom,cc.SCROLLVIEW_SCRIPT_ZOOM) + end + newLayer:addChild(scrollView1) + + local scrollView2 = cc.ScrollView:create() + local function scrollView2DidScroll() + print("scrollView2DidScroll") + end + local function scrollView2DidZoom() + print("scrollView2DidZoom") + end + if nil ~= scrollView2 then + scrollView2:setViewSize(cc.size(screenSize.width / 2,screenSize.height)) + scrollView2:setPosition(cc.p(screenSize.width / 2,0)) + scrollView2:setScale(1.0) + scrollView2:ignoreAnchorPointForPosition(true) + local flowersprite2 = cc.Sprite:create("ccb/flower.jpg") + if nil ~= flowersprite2 then + scrollView2:setContainer(flowersprite2) + scrollView2:updateInset() + end + scrollView2:setDirection(cc.SCROLLVIEW_DIRECTION_BOTH ) + scrollView2:setClippingToBounds(true) + scrollView2:setBounceable(true) + scrollView2:setDelegate() + scrollView2:registerScriptHandler(scrollView2DidScroll,cc.SCROLLVIEW_SCRIPT_SCROLL) + scrollView2:registerScriptHandler(scrollView2DidZoom,cc.SCROLLVIEW_SCRIPT_ZOOM) + end + newLayer:addChild(scrollView2) + + newScene:addChild(newLayer) + return newScene +end + local CreateExtensionsTestTable = { runNotificationCenterTest, @@ -995,6 +1185,8 @@ local CreateExtensionsTestTable = runCocosBuilder, runWebSocketTest, runEditBoxTest, + runTableViewTest, + runScrollViewTest, } diff --git a/tools/tolua/cocos2dx_extension.ini b/tools/tolua/cocos2dx_extension.ini index d75f375305..248894593e 100644 --- a/tools/tolua/cocos2dx_extension.ini +++ b/tools/tolua/cocos2dx_extension.ini @@ -27,7 +27,7 @@ headers = %(cocosdir)s/extensions/cocos-ext.h %(cocosdir)s/cocos/editor-support/ # what classes to produce code for. You can use regular expressions here. When testing the regular # expression, it will be enclosed in "^$", like this: "^Menu*$". -classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* EditBox$ +classes = AssetsManager.* CCBReader.* CCBAnimationManager.* Scale9Sprite Control.* ControlButton.* EditBox$ ScrollView$ TableView$ TableViewCell$ # what should we skip? in the format ClassName::[function function] # ClassName is a regular expression, but will be used like this: "^ClassName$" functions are also @@ -46,7 +46,9 @@ skip = CCBReader::[^CCBReader$ addOwnerCallbackName isJSControlled readByte getC AssetsManagerDelegateProtocol::[*], Control::[removeHandleOfControlEvent addHandleOfControlEvent], ControlUtils::[*], - ControlSwitchSprite::[*] + ControlSwitchSprite::[*], + ScrollView::[(g|s)etDelegate$], + TableView::[create (g|s)etDataSource$ (g|s)etDelegate] rename_functions = CCBReader::[getAnimationManager=getActionManager setAnimationManager=setActionManager] From 35d031ea06811491dc0eeb5c5a40131bbec5695c Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Wed, 15 Jan 2014 22:36:10 +0800 Subject: [PATCH 137/193] =?UTF-8?q?issue=20#3626:Make=20the=20lua=20bindin?= =?UTF-8?q?g=20of=20the=20WebSocket=20and=20the=20XMLHttpRequest=20used=20?= =?UTF-8?q?in=20lua=20in=20the=20=E2=80=9Ccc=E2=80=9D=20module?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../scripting/lua/bindings/Lua_web_socket.cpp | 34 +++++++------- .../lua/bindings/lua_xml_http_request.cpp | 46 +++++++++---------- .../luaScript/ExtensionTest/WebProxyTest.lua | 6 +-- .../XMLHttpRequestTest/XMLHttpRequestTest.lua | 8 ++-- 4 files changed, 47 insertions(+), 47 deletions(-) diff --git a/cocos/scripting/lua/bindings/Lua_web_socket.cpp b/cocos/scripting/lua/bindings/Lua_web_socket.cpp index 4d3b8ae715..f508e720f6 100644 --- a/cocos/scripting/lua/bindings/Lua_web_socket.cpp +++ b/cocos/scripting/lua/bindings/Lua_web_socket.cpp @@ -164,7 +164,7 @@ static int tolua_collect_WebSocket (lua_State* tolua_S) /* function to release collected object via destructor */ static void tolua_reg_Web_Socket_type(lua_State* tolua_S) { - tolua_usertype(tolua_S, "WebSocket"); + tolua_usertype(tolua_S, "cc.WebSocket"); } /* method: create of class WebSocket */ @@ -174,7 +174,7 @@ static int tolua_Cocos2d_WebSocket_create00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertable(tolua_S,1,"WebSocket",0,&tolua_err) || + !tolua_isusertable(tolua_S,1,"cc.WebSocket",0,&tolua_err) || !tolua_isstring(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) @@ -185,7 +185,7 @@ static int tolua_Cocos2d_WebSocket_create00(lua_State* tolua_S) const char* urlName = ((const char*) tolua_tostring(tolua_S,2,0)); LuaWebSocket *wSocket = new LuaWebSocket(); wSocket->init(*wSocket, urlName); - tolua_pushusertype(tolua_S,(void*)wSocket,"WebSocket"); + tolua_pushusertype(tolua_S,(void*)wSocket,"cc.WebSocket"); tolua_register_gc(tolua_S,lua_gettop(tolua_S)); } return 1; @@ -204,7 +204,7 @@ static int tolua_Cocos2d_WebSocket_createByAProtocol00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertable(tolua_S,1,"WebSocket",0,&tolua_err) || + !tolua_isusertable(tolua_S,1,"cc.WebSocket",0,&tolua_err) || !tolua_isstring(tolua_S,2,0,&tolua_err) || !tolua_isstring(tolua_S,3,0,&tolua_err) || !tolua_isnoobj(tolua_S,4,&tolua_err) @@ -219,7 +219,7 @@ static int tolua_Cocos2d_WebSocket_createByAProtocol00(lua_State* tolua_S) protocols.push_back(protocol); LuaWebSocket *wSocket = new LuaWebSocket(); wSocket->init(*wSocket, urlName,&protocols); - tolua_pushusertype(tolua_S,(void*)wSocket,"WebSocket"); + tolua_pushusertype(tolua_S,(void*)wSocket,"cc.WebSocket"); tolua_register_gc(tolua_S,lua_gettop(tolua_S)); } return 1; @@ -238,7 +238,7 @@ static int tolua_Cocos2d_WebSocket_createByProtocolArray00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertable(tolua_S,1,"WebSocket",0,&tolua_err) || + !tolua_isusertable(tolua_S,1,"cc.WebSocket",0,&tolua_err) || !tolua_isstring(tolua_S,2,0,&tolua_err) || !tolua_isusertable(tolua_S,3,"CCArray",0,&tolua_err) || !tolua_isnoobj(tolua_S,4,&tolua_err) @@ -262,7 +262,7 @@ static int tolua_Cocos2d_WebSocket_createByProtocolArray00(lua_State* tolua_S) } LuaWebSocket *wSocket = new LuaWebSocket(); wSocket->init(*wSocket, urlName,&protocols); - tolua_pushusertype(tolua_S,(void*)wSocket,"WebSocket"); + tolua_pushusertype(tolua_S,(void*)wSocket,"cc.WebSocket"); tolua_register_gc(tolua_S,lua_gettop(tolua_S)); } return 1; @@ -281,7 +281,7 @@ static int tolua_Cocos2d_WebSocket_getReadyState00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"WebSocket",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"cc.WebSocket",0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; @@ -312,7 +312,7 @@ static int tolua_Cocos2d_WebSocket_close00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"WebSocket",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"cc.WebSocket",0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; @@ -340,7 +340,7 @@ static int tolua_Cocos2d_WebSocket_sendString00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S, 1, "WebSocket", 0, &tolua_err) || + !tolua_isusertype(tolua_S, 1, "cc.WebSocket", 0, &tolua_err) || !tolua_isstring(tolua_S, 2, 0, &tolua_err) || !tolua_isnoobj(tolua_S, 3, &tolua_err) ) @@ -376,12 +376,12 @@ tolua_lerror: TOLUA_API int tolua_web_socket_open(lua_State* tolua_S){ tolua_open(tolua_S); tolua_reg_Web_Socket_type(tolua_S); - tolua_module(tolua_S,NULL,0); - tolua_beginmodule(tolua_S,NULL); + tolua_module(tolua_S,"cc",0); + tolua_beginmodule(tolua_S,"cc"); #ifdef __cplusplus - tolua_cclass(tolua_S,"WebSocket","WebSocket","",tolua_collect_WebSocket); + tolua_cclass(tolua_S,"WebSocket","cc.WebSocket","",tolua_collect_WebSocket); #else - tolua_cclass(tolua_S,"WebSocket","WebSocket","",NULL); + tolua_cclass(tolua_S,"WebSocket","cc.WebSocket","",NULL); #endif tolua_beginmodule(tolua_S,"WebSocket"); tolua_function(tolua_S, "create", tolua_Cocos2d_WebSocket_create00); @@ -400,7 +400,7 @@ int tolua_Cocos2d_WebSocket_registerScriptHandler00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"WebSocket",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"cc.WebSocket",0,&tolua_err) || !toluafix_isfunction(tolua_S,2,"LUA_FUNCTION",0,&tolua_err) || !tolua_isnumber(tolua_S,3,0,&tolua_err) || !tolua_isnoobj(tolua_S,4,&tolua_err) @@ -429,7 +429,7 @@ int tolua_Cocos2d_WebSocket_unregisterScriptHandler00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"WebSocket",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"cc.WebSocket",0,&tolua_err) || !tolua_isnumber(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) @@ -457,7 +457,7 @@ TOLUA_API int register_web_socket_manual(lua_State* tolua_S) if (nullptr == tolua_S) return 0 ; - lua_pushstring(tolua_S,"WebSocket"); + lua_pushstring(tolua_S,"cc.WebSocket"); lua_rawget(tolua_S,LUA_REGISTRYINDEX); if (lua_istable(tolua_S,-1)) { diff --git a/cocos/scripting/lua/bindings/lua_xml_http_request.cpp b/cocos/scripting/lua/bindings/lua_xml_http_request.cpp index 9a7b124ee9..9470afffb1 100644 --- a/cocos/scripting/lua/bindings/lua_xml_http_request.cpp +++ b/cocos/scripting/lua/bindings/lua_xml_http_request.cpp @@ -270,7 +270,7 @@ void LuaMinXmlHttpRequest::getByteData(unsigned char* byteData) /* function to regType */ static void lua_reg_xml_http_request(lua_State* L) { - tolua_usertype(L, "XMLHttpRequest"); + tolua_usertype(L, "cc.XMLHttpRequest"); } static int lua_collect_xml_http_request (lua_State* L) @@ -296,7 +296,7 @@ static int lua_cocos2dx_XMLHttpRequest_constructor(lua_State* L) self->autorelease(); int ID = self? (int)self->_ID : -1; int* luaID = self? &self->_luaID : NULL; - toluafix_pushusertype_ccobject(L, ID, luaID, (void*)self, "XMLHttpRequest"); + toluafix_pushusertype_ccobject(L, ID, luaID, (void*)self, "cc.XMLHttpRequest"); return 1; } @@ -316,7 +316,7 @@ static int lua_get_XMLHttpRequest_responseType(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -345,7 +345,7 @@ static int lua_set_XMLHttpRequest_responseType(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -388,7 +388,7 @@ static int lua_get_XMLHttpRequest_withCredentials(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -417,7 +417,7 @@ static int lua_set_XMLHttpRequest_withCredentials(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -457,7 +457,7 @@ static int lua_get_XMLHttpRequest_timeout(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -486,7 +486,7 @@ static int lua_set_XMLHttpRequest_timeout(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -526,7 +526,7 @@ static int lua_get_XMLHttpRequest_readyState(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -555,7 +555,7 @@ static int lua_get_XMLHttpRequest_status(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -584,7 +584,7 @@ static int lua_get_XMLHttpRequest_statusText(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -613,7 +613,7 @@ static int lua_get_XMLHttpRequest_responseText(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -640,7 +640,7 @@ static int lua_get_XMLHttpRequest_response(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -711,7 +711,7 @@ static int lua_cocos2dx_XMLHttpRequest_open(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -796,7 +796,7 @@ static int lua_cocos2dx_XMLHttpRequest_send(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -855,7 +855,7 @@ static int lua_cocos2dx_XMLHttpRequest_setRequestHeader(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -902,7 +902,7 @@ static int lua_cocos2dx_XMLHttpRequest_getAllResponseHeaders(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -948,7 +948,7 @@ static int lua_cocos2dx_XMLHttpRequest_getResponseHeader(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -1002,7 +1002,7 @@ static int lua_cocos2dx_XMLHttpRequest_registerScriptHandler(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -1046,7 +1046,7 @@ static int lua_cocos2dx_XMLHttpRequest_unregisterScriptHandler(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertype(L,1,"XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertype(L,1,"cc.XMLHttpRequest",0,&tolua_err)) goto tolua_lerror; #endif self = (LuaMinXmlHttpRequest*) tolua_tousertype(L,1,0); @@ -1082,9 +1082,9 @@ TOLUA_API int register_xml_http_request(lua_State* L) { tolua_open(L); lua_reg_xml_http_request(L); - tolua_module(L,NULL,0); - tolua_beginmodule(L,NULL); - tolua_cclass(L,"XMLHttpRequest","XMLHttpRequest","Object",lua_collect_xml_http_request); + tolua_module(L,"cc",0); + tolua_beginmodule(L,"cc"); + tolua_cclass(L,"XMLHttpRequest","cc.XMLHttpRequest","cc.Object",lua_collect_xml_http_request); tolua_beginmodule(L,"XMLHttpRequest"); tolua_variable(L, "responseType", lua_get_XMLHttpRequest_responseType, lua_set_XMLHttpRequest_responseType); tolua_variable(L, "withCredentials", lua_get_XMLHttpRequest_withCredentials, lua_set_XMLHttpRequest_withCredentials); diff --git a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/WebProxyTest.lua b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/WebProxyTest.lua index e27a321cb5..9a2c203ffd 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/WebProxyTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/ExtensionTest/WebProxyTest.lua @@ -83,9 +83,9 @@ toMainMenu:setPosition(cc.p(0, 0)) layer:addChild(toMainMenu,10) - wsSendText = WebSocket:create("ws://echo.websocket.org") - wsSendBinary = WebSocket:create("ws://echo.websocket.org") - wsError = WebSocket:create("ws://invalid.url.com") + wsSendText = cc.WebSocket:create("ws://echo.websocket.org") + wsSendBinary = cc.WebSocket:create("ws://echo.websocket.org") + wsError = cc.WebSocket:create("ws://invalid.url.com") local function wsSendTextOpen(strData) sendTextStatus:setString("Send Text WS was opened.") diff --git a/samples/Lua/TestLua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua b/samples/Lua/TestLua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua index 1cdffa035a..4bec50a734 100644 --- a/samples/Lua/TestLua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/XMLHttpRequestTest/XMLHttpRequestTest.lua @@ -22,7 +22,7 @@ local function XMLHttpRequestLayer() --Get local function onMenuGetClicked() - local xhr = XMLHttpRequest:new() + local xhr = cc.XMLHttpRequest:new() xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING xhr:open("GET", "http://httpbin.org/get") @@ -46,7 +46,7 @@ local function XMLHttpRequestLayer() --Post local function onMenuPostClicked() - local xhr = XMLHttpRequest:new() + local xhr = cc.XMLHttpRequest:new() xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_STRING xhr:open("POST", "http://httpbin.org/post") local function onReadyStateChange() @@ -67,7 +67,7 @@ local function XMLHttpRequestLayer() --Post Binary local function onMenuPostBinaryClicked() - local xhr = XMLHttpRequest:new() + local xhr = cc.XMLHttpRequest:new() xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_ARRAY_BUFFER xhr:open("POST", "http://httpbin.org/post") @@ -102,7 +102,7 @@ local function XMLHttpRequestLayer() --Post Json local function onMenuPostJsonClicked() - local xhr = XMLHttpRequest:new() + local xhr = cc.XMLHttpRequest:new() xhr.responseType = cc.XMLHTTPREQUEST_RESPONSE_JSON xhr:open("POST", "http://httpbin.org/post") From 5859d3866a7d43ff48989c75905c91ae443102fb Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Wed, 15 Jan 2014 23:31:00 +0800 Subject: [PATCH 138/193] =?UTF-8?q?issue=20#3626:Update=20the=20lua=20test?= =?UTF-8?q?=20cases=20which=20used=20the=20=E2=80=9Ctolua.cast=E2=80=9D=20?= =?UTF-8?q?function=20to=20add=20the=20module=20name=20for=20the=20second?= =?UTF-8?q?=20string=20param?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../luaScript/ActionsTest/ActionsTest.lua | 8 +-- .../EffectsAdvancedTest.lua | 2 +- .../luaScript/LabelTest/LabelTest.lua | 30 +++++----- .../luaScript/LayerTest/LayerTest.lua | 12 ++-- .../Resources/luaScript/MenuTest/MenuTest.lua | 38 ++++++------ .../NewEventDispatcherTest.lua | 6 +- .../Resources/luaScript/NodeTest/NodeTest.lua | 12 ++-- .../PerformanceTest/PerformanceTest.lua | 22 +++---- .../luaScript/SpriteTest/SpriteTest.lua | 4 +- .../luaScript/Texture2dTest/Texture2dTest.lua | 30 +++++----- .../luaScript/TileMapTest/TileMapTest.lua | 58 +++++++++---------- 11 files changed, 111 insertions(+), 111 deletions(-) diff --git a/samples/Lua/TestLua/Resources/luaScript/ActionsTest/ActionsTest.lua b/samples/Lua/TestLua/Resources/luaScript/ActionsTest/ActionsTest.lua index 7a26897d9b..9b70078388 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ActionsTest/ActionsTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/ActionsTest/ActionsTest.lua @@ -551,7 +551,7 @@ local function ActionAnimate() local animation3 = animation2:clone() -- problem - tolua.cast(animation3,"Animation"):setLoops(4) + tolua.cast(animation3,"cc.Animation"):setLoops(4) local action3 = cc.Animate:create(animation3) kathia:runAction(action3) @@ -740,7 +740,7 @@ local function ActionRotateToRepeat() local act2 = cc.RotateTo:create(1, 0) local seq = cc.Sequence:create(act1, act2) local rep1 = cc.RepeatForever:create(seq) - local rep2 = cc.Repeat:create(tolua.cast(seq:clone(), "Sequence"), 10) + local rep2 = cc.Repeat:create(tolua.cast(seq:clone(), "cc.Sequence"), 10) tamara:runAction(rep1) kathia:runAction(rep2) @@ -931,8 +931,8 @@ local function ActionOrbit() local seq = cc.Sequence:create(move, move_back) local rfe = cc.RepeatForever:create(seq) kathia:runAction(rfe) - tamara:runAction(tolua.cast(rfe:clone(), "ActionInterval")) - grossini:runAction(tolua.cast(rfe:clone(), "ActionInterval")) + tamara:runAction(tolua.cast(rfe:clone(), "cc.ActionInterval")) + grossini:runAction(tolua.cast(rfe:clone(), "cc.ActionInterval")) Helper.subtitleLabel:setString("OrbitCamera action") diff --git a/samples/Lua/TestLua/Resources/luaScript/EffectsAdvancedTest/EffectsAdvancedTest.lua b/samples/Lua/TestLua/Resources/luaScript/EffectsAdvancedTest/EffectsAdvancedTest.lua index 705ef3fac0..863044cd94 100644 --- a/samples/Lua/TestLua/Resources/luaScript/EffectsAdvancedTest/EffectsAdvancedTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/EffectsAdvancedTest/EffectsAdvancedTest.lua @@ -95,7 +95,7 @@ local function Effect2() local delay = cc.DelayTime:create(1) - target:runAction(cc.Sequence:create(shaky, delay ,reuse, shuffle, tolua.cast(delay:clone(), "Action"), turnoff, turnon)) + target:runAction(cc.Sequence:create(shaky, delay ,reuse, shuffle, tolua.cast(delay:clone(), "cc.Action"), turnoff, turnon)) return ret end diff --git a/samples/Lua/TestLua/Resources/luaScript/LabelTest/LabelTest.lua b/samples/Lua/TestLua/Resources/luaScript/LabelTest/LabelTest.lua index 32649cbdba..3025c2afce 100644 --- a/samples/Lua/TestLua/Resources/luaScript/LabelTest/LabelTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/LabelTest/LabelTest.lua @@ -32,11 +32,11 @@ function LabelAtlasTest.step(dt) local string = string.format("%2.2f Test", m_time) local label1_origin = LabelAtlasTest.layer:getChildByTag(kTagSprite1) - local label1 = tolua.cast(label1_origin, "LabelAtlas") + local label1 = tolua.cast(label1_origin, "cc.LabelAtlas") label1:setString(string) -- local label2_origin = LabelAtlasTest.layer:getChildByTag(kTagSprite2) - local label2 = tolua.cast(label2_origin, "LabelAtlas") + local label2 = tolua.cast(label2_origin, "cc.LabelAtlas") string = string.format("%d", m_time) label2:setString(string) @@ -88,11 +88,11 @@ function LabelAtlasColorTest.step(dt) m_time = m_time + dt local string = string.format("%2.2f Test", m_time) local label1_origin = LabelAtlasColorTest.layer:getChildByTag(kTagSprite1) - local label1 = tolua.cast(label1_origin, "LabelAtlas") + local label1 = tolua.cast(label1_origin, "cc.LabelAtlas") label1:setString(string) local label2_origin = LabelAtlasColorTest.layer:getChildByTag(kTagSprite2) - local label2 = tolua.cast(label2_origin, "LabelAtlas") + local label2 = tolua.cast(label2_origin, "cc.LabelAtlas") string = string.format("%d", m_time) label2:setString(string) @@ -199,7 +199,7 @@ function Atlas3.create() label2:setColor(cc.c3b(255, 0, 0 )) layer:addChild(label2, 0, kTagBitmapAtlas2) - label2:runAction( tolua.cast(repeatAction:clone(), "Action") ) + label2:runAction( tolua.cast(repeatAction:clone(), "cc.Action") ) local label3 = cc.LabelBMFont:create("Test", "fonts/bitmapFontTest2.fnt") -- testing anchors @@ -223,13 +223,13 @@ function Atlas3.step(dt) m_time = m_time + dt local string = string.format("%2.2f Test j", m_time) - local label1 = tolua.cast(Atlas3.layer:getChildByTag(kTagBitmapAtlas1), "LabelBMFont") + local label1 = tolua.cast(Atlas3.layer:getChildByTag(kTagBitmapAtlas1), "cc.LabelBMFont") label1:setString(string) - local label2 = tolua.cast(Atlas3.layer:getChildByTag(kTagBitmapAtlas2), "LabelBMFont") + local label2 = tolua.cast(Atlas3.layer:getChildByTag(kTagBitmapAtlas2), "cc.LabelBMFont") label2:setString(string) - local label3 = tolua.cast(Atlas3.layer:getChildByTag(kTagBitmapAtlas3), "LabelBMFont") + local label3 = tolua.cast(Atlas3.layer:getChildByTag(kTagBitmapAtlas3), "cc.LabelBMFont") label3:setString(string) end @@ -309,7 +309,7 @@ function Atlas4.create() label2:setPosition( cc.p(s.width/2.0, 80) ) local lastChar = label2:getChildByTag(3) - lastChar:runAction(tolua.cast( rot_4ever:clone(), "Action" )) + lastChar:runAction(tolua.cast( rot_4ever:clone(), "cc.Action" )) layer:registerScriptHandler(Atlas4.onNodeEvent) @@ -329,7 +329,7 @@ function Atlas4.step(dt) local string = string.format("%04.1f", m_time) - local label1 = tolua.cast(Atlas4.layer:getChildByTag(kTagBitmapAtlas2), "LabelBMFont") + local label1 = tolua.cast(Atlas4.layer:getChildByTag(kTagBitmapAtlas2), "cc.LabelBMFont") label1:setString(string) end @@ -592,9 +592,9 @@ function LabelsEmpty.create() end function LabelsEmpty.updateStrings(dt) - local label1 = tolua.cast(LabelsEmpty.layer:getChildByTag(kTagBitmapAtlas1), "LabelBMFont") - local label2 = tolua.cast(LabelsEmpty.layer:getChildByTag(kTagBitmapAtlas2), "LabelTTF") - local label3 = tolua.cast(LabelsEmpty.layer:getChildByTag(kTagBitmapAtlas3), "LabelAtlas") + local label1 = tolua.cast(LabelsEmpty.layer:getChildByTag(kTagBitmapAtlas1), "cc.LabelBMFont") + local label2 = tolua.cast(LabelsEmpty.layer:getChildByTag(kTagBitmapAtlas2), "cc.LabelTTF") + local label3 = tolua.cast(LabelsEmpty.layer:getChildByTag(kTagBitmapAtlas3), "cc.LabelAtlas") if( LabelsEmpty.setEmpty == false) then label1:setString("not empty") @@ -1083,7 +1083,7 @@ end function BitmapFontMultiLineAlignment.stringChanged(tag, sender) - local item = tolua.cast(sender, "MenuItemFont") + local item = tolua.cast(sender, "cc.MenuItemFont") item:setColor(cc.c3b(255, 0, 0)) BitmapFontMultiLineAlignment._pLastAlignmentItem:setColor(cc.c3b(255, 255, 255)) BitmapFontMultiLineAlignment._pLastAlignmentItem = item @@ -1101,7 +1101,7 @@ end function BitmapFontMultiLineAlignment.alignmentChanged(tag, sender) -- cclog("BitmapFontMultiLineAlignment.alignmentChanged, tag:"..tag) - local item = tolua.cast(sender, "MenuItemFont") + local item = tolua.cast(sender, "cc.MenuItemFont") item:setColor(cc.c3b(255, 0, 0)) BitmapFontMultiLineAlignment._pLastAlignmentItem:setColor(cc.c3b(255, 255, 255)) BitmapFontMultiLineAlignment._pLastAlignmentItem = item diff --git a/samples/Lua/TestLua/Resources/luaScript/LayerTest/LayerTest.lua b/samples/Lua/TestLua/Resources/luaScript/LayerTest/LayerTest.lua index 991ad016fd..5a8be68410 100644 --- a/samples/Lua/TestLua/Resources/luaScript/LayerTest/LayerTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/LayerTest/LayerTest.lua @@ -316,7 +316,7 @@ local function LayerTest1() local newSize = cc.size( math.abs(x - s.width/2)*2, math.abs(y - s.height/2)*2) - local l = tolua.cast(ret:getChildByTag(kTagLayer), "LayerColor") + local l = tolua.cast(ret:getChildByTag(kTagLayer), "cc.LayerColor") l:setContentSize( newSize ) end @@ -389,7 +389,7 @@ local function LayerTestBlend() local blend = true local function newBlend(dt) - local layer = tolua.cast(ret:getChildByTag(kTagLayer), "LayerColor") + local layer = tolua.cast(ret:getChildByTag(kTagLayer), "cc.LayerColor") local src = 0 local dst = 0 @@ -441,7 +441,7 @@ local function LayerGradient() local function toggleItem(sender) -- cclog("toggleItem") - local gradient = tolua.cast(ret:getChildByTag(kTagLayer), "LayerGradient") + local gradient = tolua.cast(ret:getChildByTag(kTagLayer), "cc.LayerGradient") gradient:setCompressedInterpolation(not gradient:isCompressedInterpolation()) end @@ -462,7 +462,7 @@ local function LayerGradient() local diff = cc.p(movingPos.x - start.x, movingPos.y - start.y) diff = cc.pNormalize(diff) - local gradient = tolua.cast(ret:getChildByTag(1), "LayerGradient") + local gradient = tolua.cast(ret:getChildByTag(1), "cc.LayerGradient") gradient:setVector(diff) end end @@ -487,7 +487,7 @@ local function LayerIgnoreAnchorPointPos() l:setPosition(cc.p( s.width/2, s.height/2)) local move = cc.MoveBy:create(2, cc.p(100,2)) - local back = tolua.cast(move:reverse(), "MoveBy") + local back = tolua.cast(move:reverse(), "cc.MoveBy") local seq = cc.Sequence:create(move, back) l:runAction(cc.RepeatForever:create(seq)) ret:addChild(l, 0, kLayerIgnoreAnchorPoint) @@ -564,7 +564,7 @@ local function LayerIgnoreAnchorPointScale() local scale = cc.ScaleBy:create(2, 2) - local back = tolua.cast(scale:reverse(), "ScaleBy") + local back = tolua.cast(scale:reverse(), "cc.ScaleBy") local seq = cc.Sequence:create(scale, back) l:runAction(cc.RepeatForever:create(seq)) diff --git a/samples/Lua/TestLua/Resources/luaScript/MenuTest/MenuTest.lua b/samples/Lua/TestLua/Resources/luaScript/MenuTest/MenuTest.lua index d2593602e0..7569f70cf2 100644 --- a/samples/Lua/TestLua/Resources/luaScript/MenuTest/MenuTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/MenuTest/MenuTest.lua @@ -34,13 +34,13 @@ local function MenuLayerMainMenu() local function menuCallback(sender) cclog("menuCallback...") - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(1) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(1) end item1:registerScriptTapHandler(menuCallback) -- Image Item local function menuCallback2(sender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(2) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(2) end local item2 = cc.MenuItemImage:create(s_SendScore, s_PressSendScore) @@ -87,7 +87,7 @@ local function MenuLayerMainMenu() cc.MenuItemFont:setFontName("Marker Felt") local function menuCallbackConfig(sender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(3) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(3) end -- Label Item (cc.LabelBMFont) @@ -101,7 +101,7 @@ local function MenuLayerMainMenu() -- Events cc.MenuItemFont:setFontName("Marker Felt") local function menuCallbackBugsTest(pSender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(4) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(4) end -- Bugs Item @@ -117,7 +117,7 @@ local function MenuLayerMainMenu() item7:registerScriptTapHandler(onQuit) local function menuMovingCallback(pSender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(5) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(5) end local item8 = cc.MenuItemFont:create("Remove menu item when moving") @@ -154,7 +154,7 @@ local function MenuLayerMainMenu() if pObject == nil then break end - child = tolua.cast(pObject, "Node") + child = tolua.cast(pObject, "cc.Node") local dstPointX, dstPointY = child:getPosition() local offset = s.width/2 + 50 if i % 2 == 0 then @@ -202,7 +202,7 @@ local function MenuLayer2() local function alignMenusH() local i = 0 for i=0, 1 do - local menu = tolua.cast(ret:getChildByTag(100+i), "Menu") + local menu = tolua.cast(ret:getChildByTag(100+i), "cc.Menu") menu:setPosition( m_centeredMenu ) if i==0 then -- TIP: if no padding, padding = 5 @@ -221,7 +221,7 @@ local function MenuLayer2() local function alignMenusV() local i = 0 for i=0, 1 do - local menu = tolua.cast(ret:getChildByTag(100+i), "Menu") + local menu = tolua.cast(ret:getChildByTag(100+i), "cc.Menu") menu:setPosition( m_centeredMenu ) if i==0 then -- TIP: if no padding, padding = 5 @@ -238,11 +238,11 @@ local function MenuLayer2() end local function menuCallback(sender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(0) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(0) end local function menuCallbackOpacity(tag, sender) - local menu = tolua.cast(sender:getParent(), "Menu") + local menu = tolua.cast(sender:getParent(), "cc.Menu") local opacity = menu:getOpacity() if opacity == 128 then menu:setOpacity(255) @@ -307,7 +307,7 @@ local function MenuLayer3() local m_disabledItem = nil local ret = cc.Layer:create() local function menuCallback(sender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(0) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(0) end local function menuCallback2(sender) @@ -359,8 +359,8 @@ local function MenuLayer3() item2:runAction( cc.RepeatForever:create(cc.Sequence:create( jump, jump:reverse()))) local spin1 = cc.RotateBy:create(3, 360) - local spin2 = tolua.cast(spin1:clone(), "ActionInterval") - local spin3 = tolua.cast(spin1:clone(), "ActionInterval") + local spin2 = tolua.cast(spin1:clone(), "cc.ActionInterval") + local spin3 = tolua.cast(spin1:clone(), "cc.ActionInterval") item1:runAction( cc.RepeatForever:create(spin1) ) item2:runAction( cc.RepeatForever:create(spin2) ) @@ -400,11 +400,11 @@ local function MenuLayer4() local item1 = cc.MenuItemToggle:create(cc.MenuItemFont:create( "On" )) local function menuCallback(tag, sender) - cclog("selected item: tag: %d, index:%d", tag, tolua.cast(sender, "MenuItemToggle"):getSelectedIndex() ) + cclog("selected item: tag: %d, index:%d", tag, tolua.cast(sender, "cc.MenuItemToggle"):getSelectedIndex() ) end local function backCallback(tag, sender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(0) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(0) end item1:registerScriptTapHandler(menuCallback) @@ -477,21 +477,21 @@ end local function BugsTest() local ret = cc.Layer:create() local function issue1410MenuCallback(tag, pSender) - local menu = tolua.cast(pSender:getParent(), "Menu") + local menu = tolua.cast(pSender:getParent(), "cc.Menu") menu:setEnabled(false) menu:setEnabled(true) cclog("NO CRASHES") end local function issue1410v2MenuCallback(tag, pSender) - local menu = tolua.cast(pSender:getParent(), "Menu") + local menu = tolua.cast(pSender:getParent(), "cc.Menu") menu:setEnabled(true) menu:setEnabled(false) cclog("NO CRASHES. AND MENU SHOULD STOP WORKING") end local function backMenuCallback(tag, pSender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(0) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(0) end @@ -528,7 +528,7 @@ local function RemoveMenuItemWhenMove() local back = cc.MenuItemFont:create("go back") local function goBack(tag, pSender) - tolua.cast(ret:getParent(), "LayerMultiplex"):switchTo(0) + tolua.cast(ret:getParent(), "cc.LayerMultiplex"):switchTo(0) end back:registerScriptTapHandler(goBack) diff --git a/samples/Lua/TestLua/Resources/luaScript/NewEventDispatcherTest/NewEventDispatcherTest.lua b/samples/Lua/TestLua/Resources/luaScript/NewEventDispatcherTest/NewEventDispatcherTest.lua index e363ae3141..10be2d574c 100644 --- a/samples/Lua/TestLua/Resources/luaScript/NewEventDispatcherTest/NewEventDispatcherTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/NewEventDispatcherTest/NewEventDispatcherTest.lua @@ -184,7 +184,7 @@ function TouchableSpriteTest:onEnter() sprite2:addChild(sprite3, 1) local function onTouchBegan(touch, event) - local target = tolua.cast(event:getCurrentTarget(),"Sprite") + local target = tolua.cast(event:getCurrentTarget(),"cc.Sprite") local locationInNode = target:convertToNodeSpace(touch:getLocation()) local s = target:getContentSize() @@ -199,14 +199,14 @@ function TouchableSpriteTest:onEnter() end local function onTouchMoved(touch, event) - local target = tolua.cast(event:getCurrentTarget(), "Sprite") + local target = tolua.cast(event:getCurrentTarget(), "cc.Sprite") local posX,posY = target:getPosition() local delta = touch:getDelta() target:setPosition(cc.p(posX + delta.x, posY + delta.y)) end local function onTouchEnded(touch, event) - local target = tolua.cast(event:getCurrentTarget(), "Sprite") + local target = tolua.cast(event:getCurrentTarget(), "cc.Sprite") print("sprite onTouchesEnded..") target:setOpacity(255) if target == sprite2 then diff --git a/samples/Lua/TestLua/Resources/luaScript/NodeTest/NodeTest.lua b/samples/Lua/TestLua/Resources/luaScript/NodeTest/NodeTest.lua index 47e4d0103e..9ffcac5706 100644 --- a/samples/Lua/TestLua/Resources/luaScript/NodeTest/NodeTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/NodeTest/NodeTest.lua @@ -261,10 +261,10 @@ local function Test6() local rot = cc.RotateBy:create(2, 360) local rot_back = rot:reverse() local forever1 = cc.RepeatForever:create(cc.Sequence:create(rot, rot_back)) - local forever11 = tolua.cast(forever1:clone(), "RepeatForever") + local forever11 = tolua.cast(forever1:clone(), "cc.RepeatForever") - local forever2 = tolua.cast(forever1:clone(), "RepeatForever") - local forever21 = tolua.cast(forever1:clone(), "RepeatForever") + local forever2 = tolua.cast(forever1:clone(), "cc.RepeatForever") + local forever21 = tolua.cast(forever1:clone(), "cc.RepeatForever") Test6_layer:addChild(sp1, 0, kTagSprite1) sp1:addChild(sp11) @@ -370,10 +370,10 @@ local function StressTest2() local fire = cc.ParticleFire:create() fire:setTexture(cc.TextureCache:getInstance():addImage("Images/fire.png")) - fire = tolua.cast(fire, "Node") + fire = tolua.cast(fire, "cc.Node") fire:setPosition(80, s.height / 2 - 50) - local copy_seq3 = tolua.cast(seq3:clone(), "Sequence") + local copy_seq3 = tolua.cast(seq3:clone(), "cc.Sequence") fire:runAction(cc.RepeatForever:create(copy_seq3)) sublayer:addChild(fire, 2) @@ -564,7 +564,7 @@ local function ConvertToNode() point:setPosition(sprite:getPosition()) - local copy = tolua.cast(action:clone(), "RepeatForever") + local copy = tolua.cast(action:clone(), "cc.RepeatForever") sprite:runAction(copy) ConvertToNode_layer:addChild(sprite, i) end diff --git a/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceTest.lua b/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceTest.lua index 0267dd0eb0..71f6c569f1 100644 --- a/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceTest.lua @@ -147,7 +147,7 @@ local function runNodeChildrenTest() local function updateQuantityLabel() if nQuantityOfNodes ~= nLastRenderedCount then -- local pInfoLabel = pNewscene:getChildByTag(NodeChildrenTestParam.kTagInfoLayer) - local pInfoLabel = tolua.cast(pNewscene:getChildByTag(NodeChildrenTestParam.kTagInfoLayer), "LabelTTF") + local pInfoLabel = tolua.cast(pNewscene:getChildByTag(NodeChildrenTestParam.kTagInfoLayer), "cc.LabelTTF") local strNode = nQuantityOfNodes.." nodes" pInfoLabel:setString(strNode) nLastRenderedCount = nQuantityOfNodes @@ -166,7 +166,7 @@ local function runNodeChildrenTest() local i = 0 local len = table.getn(pChildren) for i = 0, len - 1, 1 do - local child = tolua.cast(pChildren[i + 1], "Sprite") + local child = tolua.cast(pChildren[i + 1], "cc.Sprite") child:setVisible(false) end end @@ -189,7 +189,7 @@ local function runNodeChildrenTest() end for i = 0 , nTotalToAdd - 1 do - local pChild = tolua.cast(pSprites[i + 1],"Node") + local pChild = tolua.cast(pSprites[i + 1],"cc.Node") pBatchNode:addChild(pChild, zs[i], NodeChildrenTestParam.kTagBase + i) end @@ -216,7 +216,7 @@ local function runNodeChildrenTest() end -- add them with random Z (very important!) for i=0, nTotalToAdd - 1 do - local pChild = tolua.cast(pSprites[i + 1],"Node") + local pChild = tolua.cast(pSprites[i + 1],"cc.Node") pBatchNode:addChild(pChild, math.random(-1,1) * 50, NodeChildrenTestParam.kTagBase + i) end @@ -244,7 +244,7 @@ local function runNodeChildrenTest() --dd them with random Z (very important!) for i = 0, nTotalToAdd - 1 do - local pChild = tolua.cast(pSprites[i + 1] ,"Node") + local pChild = tolua.cast(pSprites[i + 1] ,"cc.Node") pBatchNode:addChild(pChild, math.random(-1,1) * 50, NodeChildrenTestParam.kTagBase + i) end @@ -252,7 +252,7 @@ local function runNodeChildrenTest() -- reorder them for i = 0, nTotalToAdd - 1 do - local pNode = tolua.cast(pSprites[i + 1],"Node") + local pNode = tolua.cast(pSprites[i + 1],"cc.Node") pBatchNode:reorderChild(pNode, math.random(-1,1) * 50) end pBatchNode:sortAllChildren() @@ -508,7 +508,7 @@ local function runParticleTest() local function UpdateQuantityLabel() if nQuantityParticles ~= nLastRenderedCount then - local pInfoLabel = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagInfoLayer), "LabelTTF") + local pInfoLabel = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagInfoLayer), "cc.LabelTTF") local strInfo = string.format("%u particles", nQuantityParticles) pInfoLabel:setString(strInfo) @@ -518,7 +518,7 @@ local function runParticleTest() local function doTest() local s = cc.Director:getInstance():getWinSize() - local pParticleSystem = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagParticleSystem),"ParticleSystem") + local pParticleSystem = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagParticleSystem),"cc.ParticleSystem") if nil == pParticleSystem then return end @@ -763,8 +763,8 @@ local function runParticleTest() end local function step(t) - local pAtlas = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagLabelAtlas),"LabelAtlas") - local pEmitter = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagParticleSystem),"ParticleSystem") + local pAtlas = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagLabelAtlas),"cc.LabelAtlas") + local pEmitter = tolua.cast(pNewScene:getChildByTag(ParticleTestParam.kTagParticleSystem),"cc.ParticleSystem") local strInfo = string.format("%4d",pEmitter:getParticleCount()) pAtlas:setString(strInfo) end @@ -989,7 +989,7 @@ local function runSpriteTest() local function UpdateNodes() if nQuantityNodes ~= nLastRenderedCount then - local pInfoLabel = tolua.cast(pNewScene:getChildByTag(SpriteTestParam.kTagInfoLayer), "LabelTTF") + local pInfoLabel = tolua.cast(pNewScene:getChildByTag(SpriteTestParam.kTagInfoLayer), "cc.LabelTTF") local strInfo = string.format("%u nodes", nQuantityNodes) pInfoLabel:setString(strInfo) nLastRenderedCount = nQuantityNodes diff --git a/samples/Lua/TestLua/Resources/luaScript/SpriteTest/SpriteTest.lua b/samples/Lua/TestLua/Resources/luaScript/SpriteTest/SpriteTest.lua index c6e9c6dd7b..05f6ae2488 100644 --- a/samples/Lua/TestLua/Resources/luaScript/SpriteTest/SpriteTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/SpriteTest/SpriteTest.lua @@ -445,7 +445,7 @@ function SpriteAnchorPoint.initLayer(layer) end point:setPosition( sprite:getPosition() ) - local copy = tolua.cast(action:clone(), "Action") + local copy = tolua.cast(action:clone(), "cc.Action") sprite:runAction(copy) layer:addChild(sprite, i) end @@ -498,7 +498,7 @@ function SpriteBatchNodeAnchorPoint.initLayer(layer) point:setPosition( cc.p(sprite:getPosition()) ) - local copy = tolua.cast(action:clone(), "Action") + local copy = tolua.cast(action:clone(), "cc.Action") sprite:runAction(copy) batch:addChild(sprite, i) end diff --git a/samples/Lua/TestLua/Resources/luaScript/Texture2dTest/Texture2dTest.lua b/samples/Lua/TestLua/Resources/luaScript/Texture2dTest/Texture2dTest.lua index ec191438b1..ff4ffd467e 100644 --- a/samples/Lua/TestLua/Resources/luaScript/Texture2dTest/Texture2dTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/Texture2dTest/Texture2dTest.lua @@ -110,7 +110,7 @@ local function TextureMipMap() local scale1 = cc.EaseOut:create(cc.ScaleBy:create(4, 0.01), 3) local sc_back = scale1:reverse() - local scale2 = tolua.cast(scale1:clone(), "EaseOut") + local scale2 = tolua.cast(scale1:clone(), "cc.EaseOut") local sc_back2 = scale2:reverse() img0:runAction(cc.RepeatForever:create(cc.Sequence:create(scale1, sc_back))) @@ -148,7 +148,7 @@ local function TexturePVRMipMap() local scale1 = cc.EaseOut:create(cc.ScaleBy:create(4, 0.01), 3) local sc_back = scale1:reverse() - local scale2 = tolua.cast(scale1:clone(), "EaseOut") + local scale2 = tolua.cast(scale1:clone(), "cc.EaseOut") local sc_back2 = scale2:reverse() imgMipMap:runAction(cc.RepeatForever:create(cc.Sequence:create(scale1, sc_back))) @@ -182,7 +182,7 @@ local function TexturePVRMipMap2() local scale1 = cc.EaseOut:create(cc.ScaleBy:create(4, 0.01), 3) local sc_back = scale1:reverse() - local scale2 = tolua.cast(scale1:clone(), "EaseOut") + local scale2 = tolua.cast(scale1:clone(), "cc.EaseOut") local sc_back2 = scale2:reverse() imgMipMap:runAction(cc.RepeatForever:create(cc.Sequence:create(scale1, sc_back))) @@ -803,9 +803,9 @@ local function TextureAlias() -- scale them to show local sc = cc.ScaleBy:create(3, 8.0) - local sc_back = tolua.cast(sc:reverse(), "ScaleBy") + local sc_back = tolua.cast(sc:reverse(), "cc.ScaleBy") local scaleforever = cc.RepeatForever:create(cc.Sequence:create(sc, sc_back)) - local scaleToo = tolua.cast(scaleforever:clone(), "RepeatForever") + local scaleToo = tolua.cast(scaleforever:clone(), "cc.RepeatForever") sprite2:runAction(scaleforever) sprite:runAction(scaleToo) @@ -829,7 +829,7 @@ local function TexturePixelFormat() -- 3- 16-bit RGB5A1 -- 4- 16-bit RGB565 - local label = tolua.cast(ret:getChildByTag(kTagLabel), "LabelTTF") + local label = tolua.cast(ret:getChildByTag(kTagLabel), "cc.LabelTTF") label:setColor(cc.c3b(16,16,255)) local s = cc.Director:getInstance():getWinSize() @@ -895,10 +895,10 @@ local function TexturePixelFormat() local fadein = cc.FadeIn:create(2) local seq = cc.Sequence:create(cc.DelayTime:create(2), fadeout, fadein) local seq_4ever = cc.RepeatForever:create(seq) - local seq_4ever2 = tolua.cast(seq_4ever:clone(), "RepeatForever") - local seq_4ever3 = tolua.cast(seq_4ever:clone(), "RepeatForever") - local seq_4ever4 = tolua.cast(seq_4ever:clone(), "RepeatForever") - local seq_4ever5 = tolua.cast(seq_4ever:clone(), "RepeatForever") + local seq_4ever2 = tolua.cast(seq_4ever:clone(), "cc.RepeatForever") + local seq_4ever3 = tolua.cast(seq_4ever:clone(), "cc.RepeatForever") + local seq_4ever4 = tolua.cast(seq_4ever:clone(), "cc.RepeatForever") + local seq_4ever5 = tolua.cast(seq_4ever:clone(), "cc.RepeatForever") sprite1:runAction(seq_4ever) sprite2:runAction(seq_4ever2) @@ -964,12 +964,12 @@ local function TextureAsync() ret:addChild(label, 10) local scale = cc.ScaleBy:create(0.3, 2) - local scale_back = tolua.cast(scale:reverse(), "ScaleBy") + local scale_back = tolua.cast(scale:reverse(), "cc.ScaleBy") local seq = cc.Sequence:create(scale, scale_back) label:runAction(cc.RepeatForever:create(seq)) local function imageLoaded(pObj) - local tex = tolua.cast(pObj, "Texture2D") + local tex = tolua.cast(pObj, "cc.Texture2D") local director = cc.Director:getInstance() --cc.ASSERT( [NSThread currentThread] == [director runningThread], @"FAIL. Callback should be on cocos2d thread") @@ -1043,7 +1043,7 @@ local function TextureGlClamp() local rotate = cc.RotateBy:create(4, 360) sprite:runAction(rotate) local scale = cc.ScaleBy:create(2, 0.04) - local scaleBack = tolua.cast(scale:reverse(), "ScaleBy") + local scaleBack = tolua.cast(scale:reverse(), "cc.ScaleBy") local seq = cc.Sequence:create(scale, scaleBack) sprite:runAction(seq) local function onNodeEvent(event) @@ -1077,7 +1077,7 @@ local function TextureGlRepeat() local rotate = cc.RotateBy:create(4, 360) sprite:runAction(rotate) local scale = cc.ScaleBy:create(2, 0.04) - local scaleBack = tolua.cast(scale:reverse(), "ScaleBy") + local scaleBack = tolua.cast(scale:reverse(), "cc.ScaleBy") local seq = cc.Sequence:create(scale, scaleBack) sprite:runAction(seq) local function onNodeEvent(event) @@ -1338,7 +1338,7 @@ local function TexturePVRv3Premult() local function transformSprite(sprite) local fade = cc.FadeOut:create(2) local dl = cc.DelayTime:create(2) - local fadein = tolua.cast(fade:reverse(), "FadeOut") + local fadein = tolua.cast(fade:reverse(), "cc.FadeOut") local seq = cc.Sequence:create(fade, fadein, dl) local repeatAction = cc.RepeatForever:create(seq) sprite:runAction(repeatAction) diff --git a/samples/Lua/TestLua/Resources/luaScript/TileMapTest/TileMapTest.lua b/samples/Lua/TestLua/Resources/luaScript/TileMapTest/TileMapTest.lua index c2326ca230..66fc8ffac1 100644 --- a/samples/Lua/TestLua/Resources/luaScript/TileMapTest/TileMapTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/TileMapTest/TileMapTest.lua @@ -90,7 +90,7 @@ local function TileMapEditTest() -- The only limitation is that you cannot change an empty, or assign an empty tile to a tile -- The value 0 not rendered so don't assign or change a tile with value 0 - local tilemap = tolua.cast(layer:getChildByTag(kTagTileMap), "TileMapAtlas") + local tilemap = tolua.cast(layer:getChildByTag(kTagTileMap), "cc.TileMapAtlas") -- -- For example you can iterate over all the tiles @@ -165,7 +165,7 @@ local function TMXOrthoTest() local len = table.getn(pChildrenArray) for i = 0, len-1, 1 do pObject = pChildrenArray[i + 1] - child = tolua.cast(pObject, "SpriteBatchNode") + child = tolua.cast(pObject, "cc.SpriteBatchNode") if child == nil then break @@ -219,7 +219,7 @@ local function TMXOrthoTest2() local len = table.getn(pChildrenArray) for i = 0, len-1, 1 do - child = tolua.cast(pChildrenArray[i + 1], "SpriteBatchNode") + child = tolua.cast(pChildrenArray[i + 1], "cc.SpriteBatchNode") if child == nil then break @@ -251,7 +251,7 @@ local function TMXOrthoTest3() local len = table.getn(pChildrenArray) for i = 0, len-1, 1 do - child = tolua.cast(pChildrenArray[i + 1], "SpriteBatchNode") + child = tolua.cast(pChildrenArray[i + 1], "cc.SpriteBatchNode") if child == nil then break @@ -285,7 +285,7 @@ local function TMXOrthoTest4() local len = table.getn(pChildrenArray) for i = 0, len-1, 1 do - child = tolua.cast(pChildrenArray[i + 1], "SpriteBatchNode") + child = tolua.cast(pChildrenArray[i + 1], "cc.SpriteBatchNode") if child == nil then break @@ -312,7 +312,7 @@ local function TMXOrthoTest4() local function removeSprite(dt) scheduler:unscheduleScriptEntry(schedulerEntry) schedulerEntry = nil - local map = tolua.cast(ret:getChildByTag(kTagTileMap), "TMXTiledMap") + local map = tolua.cast(ret:getChildByTag(kTagTileMap), "cc.TMXTiledMap") local layer0 = map:getLayer("Layer 0") local s = layer0:getLayerSize() @@ -376,7 +376,7 @@ local function TMXReadWriteTest() local function removeSprite(sender) --------cclog("removing tile: %x", sender) - local node = tolua.cast(sender, "Node") + local node = tolua.cast(sender, "cc.Node") if nil == node then print("Errro node is nil") end @@ -390,9 +390,9 @@ local function TMXReadWriteTest() local finish = cc.CallFunc:create(removeSprite) local seq0 = cc.Sequence:create(move, rotate, scale, opacity, fadein, scaleback, finish) - local seq1 = tolua.cast(seq0:clone(), "Action") - local seq2 = tolua.cast(seq0:clone(), "Action") - local seq3 = tolua.cast(seq0:clone(), "Action") + local seq1 = tolua.cast(seq0:clone(), "cc.Action") + local seq2 = tolua.cast(seq0:clone(), "cc.Action") + local seq3 = tolua.cast(seq0:clone(), "cc.Action") tile0:runAction(seq0) tile1:runAction(seq1) @@ -408,8 +408,8 @@ local function TMXReadWriteTest() local function updateCol(dt) - local map = tolua.cast(ret:getChildByTag(kTagTileMap), "TMXTiledMap") - local layer = tolua.cast(map:getChildByTag(0), "TMXLayer") + local map = tolua.cast(ret:getChildByTag(kTagTileMap), "cc.TMXTiledMap") + local layer = tolua.cast(map:getChildByTag(0), "cc.TMXLayer") --------cclog("++++atlas quantity: %d", layer:textureAtlas():getTotalQuads()) --------cclog("++++children: %d", layer:getChildren():count() ) @@ -426,8 +426,8 @@ local function TMXReadWriteTest() local function repaintWithGID(dt) -- unschedule:_cmd) - local map = tolua.cast(ret:getChildByTag(kTagTileMap), "TMXTiledMap") - local layer = tolua.cast(map:getChildByTag(0), "TMXLayer") + local map = tolua.cast(ret:getChildByTag(kTagTileMap), "cc.TMXTiledMap") + local layer = tolua.cast(map:getChildByTag(0), "cc.TMXLayer") local s = layer:getLayerSize() local x = 0 @@ -441,8 +441,8 @@ local function TMXReadWriteTest() local function removeTiles(dt) scheduler:unscheduleScriptEntry(removeTilesScheduler) removeTilesScheduler = nil - local map = tolua.cast(ret:getChildByTag(kTagTileMap), "TMXTiledMap") - local layer = tolua.cast(map:getChildByTag(0), "TMXLayer") + local map = tolua.cast(ret:getChildByTag(kTagTileMap), "cc.TMXTiledMap") + local layer = tolua.cast(map:getChildByTag(0), "cc.TMXLayer") local s = layer:getLayerSize() local y = 0 for y=0, s.height-1, 1 do @@ -588,7 +588,7 @@ local function TMXUncompressedTest() local i = 0 local len = table.getn(pChildrenArray) for i = 0, len-1, 1 do - layer = tolua.cast(pChildrenArray[i + 1], "TMXLayer") + layer = tolua.cast(pChildrenArray[i + 1], "cc.TMXLayer") if layer == nil then break end @@ -659,7 +659,7 @@ end local function draw() - local map = tolua.cast(getChildByTag(kTagTileMap), "TMXTiledMap") + local map = tolua.cast(getChildByTag(kTagTileMap), "cc.TMXTiledMap") local group = map:getObjectGroup("Object Group 1") local objects = group:getObjects() @@ -716,7 +716,7 @@ local function TMXIsoObjectsTest() local i = 0 local len = table.getn(objects) for i = 0, len-1, 1 do - dict = tolua.cast(objects[i + 1], "Dictionary") + dict = tolua.cast(objects[i + 1], "cc.Dictionary") if dict == nil then break @@ -728,7 +728,7 @@ end local function draw() - local map = tolua.cast(getChildByTag(kTagTileMap), "TMXTiledMap") + local map = tolua.cast(getChildByTag(kTagTileMap), "cc.TMXTiledMap") local group = map:getObjectGroup("Object Group 1") local objects = group:getObjects() @@ -736,20 +736,20 @@ local function draw() local i = 0 local len = table.getn(objects) for i = 0, len-1, 1 do - dict = tolua.cast(objects[i + 1], "Dictionary") + dict = tolua.cast(objects[i + 1], "cc.Dictionary") if dict == nil then break end local key = "x" - local x = (tolua.cast(dict:objectForKey(key), "String")):intValue()--dynamic_cast(dict:objectForKey("x")):getNumber() + local x = (tolua.cast(dict:objectForKey(key), "cc.String")):intValue()--dynamic_cast(dict:objectForKey("x")):getNumber() key = "y" - local y = (tolua.cast(dict:objectForKey(key), "String")):intValue()--dynamic_cast(dict:objectForKey("y")):getNumber() + local y = (tolua.cast(dict:objectForKey(key), "cc.String")):intValue()--dynamic_cast(dict:objectForKey("y")):getNumber() key = "width" - local width = (tolua.cast(dict:objectForKey(key), "String")):intValue()--dynamic_cast(dict:objectForKey("width")):getNumber() + local width = (tolua.cast(dict:objectForKey(key), "cc.String")):intValue()--dynamic_cast(dict:objectForKey("width")):getNumber() key = "height" - local height = (tolua.cast(dict:objectForKey(key), "String")):intValue()--dynamic_cast(dict:objectForKey("height")):getNumber() + local height = (tolua.cast(dict:objectForKey(key), "cc.String")):intValue()--dynamic_cast(dict:objectForKey("height")):getNumber() glLineWidth(3) @@ -1081,7 +1081,7 @@ local function TMXOrthoFlipTest() local i = 0 for i = 0, table.getn(map:getChildren())-1, 1 do - local child = tolua.cast(map:getChildren()[i + 1], "SpriteBatchNode") + local child = tolua.cast(map:getChildren()[i + 1], "cc.SpriteBatchNode") child:getTexture():setAntiAliasTexParameters() end @@ -1106,7 +1106,7 @@ local function TMXOrthoFlipRunTimeTest() local i = 0 for i = 0, table.getn(map:getChildren())-1, 1 do - local child = tolua.cast(map:getChildren()[i + 1], "SpriteBatchNode") + local child = tolua.cast(map:getChildren()[i + 1], "cc.SpriteBatchNode") child:getTexture():setAntiAliasTexParameters() end @@ -1186,7 +1186,7 @@ local function TMXOrthoFromXMLTest() local i = 0 local len = table.getn(map:getChildren()) for i = 0, len-1, 1 do - local child = tolua.cast(map:getChildren()[i + 1], "SpriteBatchNode") + local child = tolua.cast(map:getChildren()[i + 1], "cc.SpriteBatchNode") child:getTexture():setAntiAliasTexParameters() end @@ -1214,7 +1214,7 @@ local function TMXBug987() local len = table.getn(childs) local pNode = nil for i = 0, len-1, 1 do - pNode = tolua.cast(childs[i + 1], "TMXLayer") + pNode = tolua.cast(childs[i + 1], "cc.TMXLayer") if pNode == nil then break end From d49e28610b84f9a918642c1b86a706c6b8563e3f Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Wed, 15 Jan 2014 23:54:21 +0800 Subject: [PATCH 139/193] issue #3626:Resolve the error that the lua binding of the EventListenerAcceleration and the EventListenerCustom have been bound two times --- cocos/scripting/lua/bindings/CCLuaStack.cpp | 1 - .../lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/cocos/scripting/lua/bindings/CCLuaStack.cpp b/cocos/scripting/lua/bindings/CCLuaStack.cpp index 7215e6afac..9661fb1cd8 100644 --- a/cocos/scripting/lua/bindings/CCLuaStack.cpp +++ b/cocos/scripting/lua/bindings/CCLuaStack.cpp @@ -151,7 +151,6 @@ bool LuaStack::init(void) register_all_cocos2dx_extension(_state); register_all_cocos2dx_deprecated(_state); register_cocos2dx_extension_CCBProxy(_state); - register_cocos2dx_event_releated(_state); tolua_opengl_open(_state); register_all_cocos2dx_gui(_state); register_all_cocos2dx_studio(_state); diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id index e3c65441d6..a2fe6b9f83 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id @@ -1 +1 @@ -f916840e52bdfd7e7283cb9c70ebfaf1c23b9301 \ No newline at end of file +480b4dce08b3e6cf2dcf34701c86bfcb5b0f1223 \ No newline at end of file From 31339d10e5c1de55edf6da5554bbfc0dba090ce4 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Thu, 16 Jan 2014 10:14:47 +0800 Subject: [PATCH 140/193] issue #3626:Add the deprecated support for the WebSocket and the XMLHttpRequest in the script --- cocos/scripting/lua/script/DeprecatedClass.lua | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/cocos/scripting/lua/script/DeprecatedClass.lua b/cocos/scripting/lua/script/DeprecatedClass.lua index 647d92357c..05e476a6fe 100644 --- a/cocos/scripting/lua/script/DeprecatedClass.lua +++ b/cocos/scripting/lua/script/DeprecatedClass.lua @@ -2154,4 +2154,20 @@ end _G["CCBProxy"] = DeprecatedClass.CCBProxy() --CCBProxy class will be Deprecated,end +--WebSocket class will be Deprecated,begin +function DeprecatedClass.WebSocket() + deprecatedTip("WebSocket","cc.WebSocket") + return cc.WebSocket +end +_G["WebSocket"] = DeprecatedClass.WebSocket() +--WebSocket class will be Deprecated,end + +--XMLHttpRequest class will be Deprecated,begin +function DeprecatedClass.XMLHttpRequest() + deprecatedTip("XMLHttpRequest","cc.XMLHttpRequest") + return cc.XMLHttpRequest +end +_G["XMLHttpRequest"] = DeprecatedClass.XMLHttpRequest() +--XMLHttpRequest class will be Deprecated,end + From d086f7a2593200fcf609911fafd61ca3f2ab038e Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Thu, 16 Jan 2014 17:56:44 +0800 Subject: [PATCH 141/193] issue #3626:Add the deprecated support for the tolua.cast --- cocos/scripting/lua/bindings/LuaBasicConversions.cpp | 1 + cocos/scripting/lua/bindings/LuaBasicConversions.h | 1 + cocos/scripting/lua/bindings/lua_cocos2dx_deprecated.cpp | 9 +++++++++ tools/bindings-generator | 2 +- 4 files changed, 12 insertions(+), 1 deletion(-) diff --git a/cocos/scripting/lua/bindings/LuaBasicConversions.cpp b/cocos/scripting/lua/bindings/LuaBasicConversions.cpp index c04df69ce3..ed8178972e 100644 --- a/cocos/scripting/lua/bindings/LuaBasicConversions.cpp +++ b/cocos/scripting/lua/bindings/LuaBasicConversions.cpp @@ -33,6 +33,7 @@ extern "C" { #endif std::unordered_map g_luaType; +std::unordered_map g_typeCast; #if COCOS2D_DEBUG >=1 void luaval_to_native_err(lua_State* L,const char* msg,tolua_Error* err) diff --git a/cocos/scripting/lua/bindings/LuaBasicConversions.h b/cocos/scripting/lua/bindings/LuaBasicConversions.h index 20e4f79d73..9dcc2fc6e2 100644 --- a/cocos/scripting/lua/bindings/LuaBasicConversions.h +++ b/cocos/scripting/lua/bindings/LuaBasicConversions.h @@ -35,6 +35,7 @@ extern "C" { using namespace cocos2d; extern std::unordered_map g_luaType; +extern std::unordered_map g_typeCast; #if COCOS2D_DEBUG >=1 void luaval_to_native_err(lua_State* L,const char* msg,tolua_Error* err); diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_deprecated.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_deprecated.cpp index 0d6d053810..e907189be2 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_deprecated.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_deprecated.cpp @@ -2123,6 +2123,15 @@ static int tolua_bnd_cast_deprecated00(lua_State* tolua_S) } else { + std::string castName = tolua_tostring(tolua_S,2,NULL); + auto iter = g_typeCast.find(castName); + if (iter != g_typeCast.end() ) + { + CCLOG("Cast name %s doesn't include modular name which it belongs to,please add the modular name",iter->first.c_str()); + tolua_pushstring(tolua_S, iter->second.c_str()); + lua_insert(tolua_S, 2); + lua_pop(tolua_S, 1); + } return tolua_bnd_cast(tolua_S); } } diff --git a/tools/bindings-generator b/tools/bindings-generator index 71a0aa4bc7..d12d19dba8 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit 71a0aa4bc70743ae2078f4a43217987751ff17ec +Subproject commit d12d19dba834b945cdee9445d70321a1bbe41ec1 From 508d786fa7773e3b8e3231447a7efd1a579bf4a2 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Fri, 17 Jan 2014 09:21:28 +0800 Subject: [PATCH 142/193] issue #3626:Update the submodule --- tools/bindings-generator | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/bindings-generator b/tools/bindings-generator index d12d19dba8..6fc3372cdf 160000 --- a/tools/bindings-generator +++ b/tools/bindings-generator @@ -1 +1 @@ -Subproject commit d12d19dba834b945cdee9445d70321a1bbe41ec1 +Subproject commit 6fc3372cdfdbf39dd20bdcf1f60eb779773d32d7 From f48f42982539f5c686d570b2c34f227d0dc06fe6 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 17 Jan 2014 10:29:21 +0800 Subject: [PATCH 143/193] issue #2789: Removes unused empty lines and renames some variables. --- .../PerformanceTest/PerformanceContainerTest.cpp | 12 ++++++------ .../PerformanceTest/PerformanceContainerTest.h | 5 ----- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp index 75c8f31b44..75efc640e5 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp @@ -325,7 +325,7 @@ void TemplateVectorPerfTest::generateTestFunctions() return ret; }; - TestFunction nameCBs[] = { + TestFunction testFunctions[] = { { "pushBack", [=](){ Vector nodeVector; @@ -501,9 +501,9 @@ void TemplateVectorPerfTest::generateTestFunctions() } } , }; - for (const auto& nameCB : nameCBs) + for (const auto& func : testFunctions) { - _testFunctions.push_back(nameCB); + _testFunctions.push_back(func); } } @@ -551,7 +551,7 @@ void ArrayPerfTest::generateTestFunctions() return ret; }; - TestFunction nameCBs[] = { + TestFunction testFunctions[] = { { "addObject", [=](){ Array* nodeVector = Array::create(); @@ -695,9 +695,9 @@ void ArrayPerfTest::generateTestFunctions() } } , }; - for (const auto& nameCB : nameCBs) + for (const auto& func : testFunctions) { - _testFunctions.push_back(nameCB); + _testFunctions.push_back(func); } } diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h index 88c1bb3984..d99cac90ff 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h @@ -18,7 +18,6 @@ public: class PerformanceContainerScene : public Scene { public: - static const int TAG_TITLE = 100; static const int TAG_SUBTITLE = 101; @@ -40,11 +39,8 @@ public: // for the profiler virtual const char* testName(); - void updateQuantityLabel(); - int getQuantityOfNodes() { return quantityOfNodes; } - void dumpProfilerInfo(float dt); // overrides @@ -74,7 +70,6 @@ public: virtual void generateTestFunctions() override; - virtual std::string title() const override; virtual std::string subtitle() const override; }; From d309ae76d051076c433017c6175c44e778d397bb Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 17 Jan 2014 11:13:40 +0800 Subject: [PATCH 144/193] issue #3628: Adds missing files for iOS and Mac. --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index e14906c550..b052741ae6 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -88c095bbe123ab56df3f7870692c6631f4464c8d \ No newline at end of file +e1e5a1169e92834330092c45165660c6cbd03609 \ No newline at end of file From cf857aade2f37e3d2250652fc0b112e85cf1c7c2 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Fri, 17 Jan 2014 11:22:03 +0800 Subject: [PATCH 145/193] issue #3626:Modify some files that skipped some modifications because of merge --- cocos/scripting/lua/bindings/CCLuaEngine.cpp | 32 +++++++++---------- .../lua_cocos2dx_manual.cpp.REMOVED.git-id | 2 +- .../ActionsEaseTest/ActionsEaseTest.lua | 4 +-- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/cocos/scripting/lua/bindings/CCLuaEngine.cpp b/cocos/scripting/lua/bindings/CCLuaEngine.cpp index d5980e7828..502909695d 100644 --- a/cocos/scripting/lua/bindings/CCLuaEngine.cpp +++ b/cocos/scripting/lua/bindings/CCLuaEngine.cpp @@ -167,7 +167,7 @@ int LuaEngine::executeEvent(int nHandler, const char* pEventName, Object* pEvent _stack->pushString(pEventName); if (pEventSource) { - _stack->pushObject(pEventSource, pEventSourceClassName ? pEventSourceClassName : "CCObject"); + _stack->pushObject(pEventSource, pEventSourceClassName ? pEventSourceClassName : "cc.Object"); } int ret = _stack->executeFunctionByHandler(nHandler, pEventSource ? 2 : 1); _stack->clean(); @@ -329,7 +329,7 @@ int LuaEngine::handleMenuClickedEvent(void* data) return 0; _stack->pushInt(menuItem->getTag()); - _stack->pushObject(menuItem, "MenuItem"); + _stack->pushObject(menuItem, "cc.MenuItem"); int ret = _stack->executeFunctionByHandler(handler, 2); _stack->clean(); return ret; @@ -352,7 +352,7 @@ int LuaEngine::handleCallFuncActionEvent(void* data) Object* target = static_cast(basicScriptData->value); if (NULL != target) { - _stack->pushObject(target, "Node"); + _stack->pushObject(target, "cc.Node"); } int ret = _stack->executeFunctionByHandler(handler, target ? 1 : 0); _stack->clean(); @@ -447,7 +447,7 @@ int LuaEngine::handleCommonEvent(void* data) } else { - _stack->pushObject(commonInfo->eventSource, "Object"); + _stack->pushObject(commonInfo->eventSource, "cc.Object"); } } int ret = _stack->executeFunctionByHandler(commonInfo->handler, commonInfo->eventSource ? 2 : 1); @@ -585,7 +585,7 @@ int LuaEngine::handlerControlEvent(void* data) if (0 != handler) { - _stack->pushObject((Object*)basicScriptData->nativeObject, "Object"); + _stack->pushObject((Object*)basicScriptData->nativeObject, "cc.Object"); _stack->pushInt(controlEvents); ret = _stack->executeFunctionByHandler(handler, 2); _stack->clean(); @@ -612,7 +612,7 @@ int LuaEngine::handleEventAcc(void* data) lua_State* L = _stack->getLuaState(); LuaEventAccelerationData* eventListennerAcc = static_cast(basicScriptData->value); - toluafix_pushusertype_ccobject(L, eventListennerAcc->event->_ID, &(eventListennerAcc->event->_luaID), (void*)(eventListennerAcc->event),"Event"); + toluafix_pushusertype_ccobject(L, eventListennerAcc->event->_ID, &(eventListennerAcc->event->_luaID), (void*)(eventListennerAcc->event),"cc.Event"); Acceleration* accleration = static_cast(eventListennerAcc->acc); lua_pushnumber(L,accleration->x); lua_pushnumber(L,accleration->y); @@ -640,7 +640,7 @@ int LuaEngine::handleEventKeyboard(ScriptHandlerMgr::HandlerType type, void* dat lua_State* L = _stack->getLuaState(); lua_pushinteger(L, keyboardData->keyCode); - toluafix_pushusertype_ccobject(L, keyboardData->event->_ID, &(keyboardData->event->_luaID), (void*)(keyboardData->event),"Event"); + toluafix_pushusertype_ccobject(L, keyboardData->event->_ID, &(keyboardData->event->_luaID), (void*)(keyboardData->event),"cc.Event"); int ret = _stack->executeFunctionByHandler(handler, 2); _stack->clean(); return ret; @@ -667,8 +667,8 @@ int LuaEngine::handleEventTouch(ScriptHandlerMgr::HandlerType type, void* data) Touch* touch = touchData->touch; if (NULL != touch) { - _stack->pushObject(touchData->touch, "Touch"); - _stack->pushObject(touchData->event, "Event"); + _stack->pushObject(touchData->touch, "cc.Touch"); + _stack->pushObject(touchData->event, "cc.Event"); ret = _stack->executeFunctionByHandler(handler, 2); } _stack->clean(); @@ -702,11 +702,11 @@ int LuaEngine::handleEventTouches(ScriptHandlerMgr::HandlerType type,void* data) for (auto& touch : touchesData->touches) { _stack->pushInt(i); - _stack->pushObject(touch, "Touch"); + _stack->pushObject(touch, "cc.Touch"); lua_rawset(L, -3); ++i; } - _stack->pushObject(touchesData->event, "Event"); + _stack->pushObject(touchesData->event, "cc.Event"); ret = _stack->executeFunctionByHandler(handler, 2); _stack->clean(); @@ -731,7 +731,7 @@ int LuaEngine::handleEventMouse(ScriptHandlerMgr::HandlerType type, void* data) if (0 == handler) return 0; - _stack->pushObject(mouseData->event, "Event"); + _stack->pushObject(mouseData->event, "cc.Event"); int ret = _stack->executeFunctionByHandler(handler, 1); _stack->clean(); @@ -754,7 +754,7 @@ int LuaEngine::handleEvenCustom(void* data) return 0; lua_State* L = _stack->getLuaState(); - toluafix_pushusertype_ccobject(L, eventCustom->_ID, &(eventCustom->_luaID), (void*)(eventCustom),"EventCustom"); + toluafix_pushusertype_ccobject(L, eventCustom->_ID, &(eventCustom->_luaID), (void*)(eventCustom),"cc.EventCustom"); int ret = _stack->executeFunctionByHandler(handler, 1); _stack->clean(); @@ -1013,7 +1013,7 @@ int LuaEngine::handleStudioEventListener(ScriptHandlerMgr::HandlerType type,void if (0 == handler) return 0; - _stack->pushObject(listenerData->objTarget, "Object"); + _stack->pushObject(listenerData->objTarget, "cc.Object"); _stack->pushInt(listenerData->eventType); _stack->executeFunctionByHandler(handler, 2); @@ -1044,7 +1044,7 @@ int LuaEngine::handleArmatureWrapper(ScriptHandlerMgr::HandlerType type,void* da { LuaArmatureMovementEventData* movementData = static_cast(wrapperData->eventData); - _stack->pushObject(movementData->objTarget, "Armature"); + _stack->pushObject(movementData->objTarget, "ccs.Armature"); _stack->pushInt(movementData->movementType); _stack->pushString(movementData->movementID.c_str()); _stack->executeFunctionByHandler(handler, 3); @@ -1054,7 +1054,7 @@ int LuaEngine::handleArmatureWrapper(ScriptHandlerMgr::HandlerType type,void* da { LuaArmatureFrameEventData* frameData = static_cast(wrapperData->eventData); - _stack->pushObject(frameData->objTarget, "Bone"); + _stack->pushObject(frameData->objTarget, "ccs.Bone"); _stack->pushString(frameData->frameEventName.c_str()); _stack->pushInt(frameData->originFrameIndex); _stack->pushInt(frameData->currentFrameIndex); diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id index a2fe6b9f83..e296678e5b 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id @@ -1 +1 @@ -480b4dce08b3e6cf2dcf34701c86bfcb5b0f1223 \ No newline at end of file +9d9d07e19dba691a22e4d184f0ec0e6ae6207a9b \ No newline at end of file diff --git a/samples/Lua/TestLua/Resources/luaScript/ActionsEaseTest/ActionsEaseTest.lua b/samples/Lua/TestLua/Resources/luaScript/ActionsEaseTest/ActionsEaseTest.lua index ae0da8b3bb..7ceb78c0e7 100644 --- a/samples/Lua/TestLua/Resources/luaScript/ActionsEaseTest/ActionsEaseTest.lua +++ b/samples/Lua/TestLua/Resources/luaScript/ActionsEaseTest/ActionsEaseTest.lua @@ -425,10 +425,10 @@ local function SpeedTest() local spawn = cc.Spawn:create(seq3_1, seq3_2) SpeedTest_action1 = cc.Speed:create(cc.RepeatForever:create(spawn), 1.0) - local spawn2 = tolua.cast(spawn:clone(), "Spawn") + local spawn2 = tolua.cast(spawn:clone(), "cc.Spawn") SpeedTest_action2 = cc.Speed:create(cc.RepeatForever:create(spawn2), 1.0) - local spawn3 = tolua.cast(spawn:clone(), "Spawn") + local spawn3 = tolua.cast(spawn:clone(), "cc.Spawn") SpeedTest_action3 = cc.Speed:create(cc.RepeatForever:create(spawn3), 1.0) grossini:runAction(SpeedTest_action2) From 54d587153bbbcfc696db3f3d0a06a189a98ca570 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 17 Jan 2014 11:55:20 +0800 Subject: [PATCH 146/193] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index fe1e346007..c4a8ea7282 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -4,6 +4,7 @@ cocos2d-x-3.0final ?.? ? [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands [NEW] GLCache: glActiveTexture() is cached with GL::activeTexture(). All code MUST call the cached version in order to work correctly [NEW] Label: Uses a struct of TTF configuration for Label::createWithTTF to reduce parameters and make this interface more easily to use. + [NEW] Label: Integrates LabelAtlas into new Label. [NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10% [FIX] CocoStudio: TestColliderDetector in ArmatureTest can't work. From d0dbf343191431f5ee9da9337f811fdaf063499d Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 16 Jan 2014 21:35:58 -0800 Subject: [PATCH 147/193] removes "include "cocos2d.h" from cocos2d files --- cocos/2d/CCAtlasNode.cpp | 2 +- cocos/2d/CCClippingNode.cpp | 7 +- cocos/2d/CCConfiguration.cpp | 2 +- cocos/2d/CCDirector.cpp | 5 +- cocos/2d/CCDrawNode.cpp | 4 +- cocos/2d/CCFont.h | 1 - cocos/2d/CCFontAtlas.cpp | 4 +- cocos/2d/CCFontAtlas.h | 3 + cocos/2d/CCFontAtlasCache.cpp | 2 + cocos/2d/CCFontAtlasCache.h | 2 +- cocos/2d/CCFontAtlasFactory.h | 2 +- cocos/2d/CCFontDefinition.cpp | 3 +- cocos/2d/CCFontFNT.cpp | 4 + cocos/2d/CCFontFNT.h | 3 +- cocos/2d/CCFontFreeType.cpp | 1 + cocos/2d/CCLabel.cpp | 6 + cocos/2d/CCLabel.h | 36 ++--- cocos/2d/CCLabelTextFormatProtocol.h | 15 +- cocos/2d/CCLabelTextFormatter.cpp | 2 +- cocos/2d/CCLayer.cpp | 4 +- cocos/2d/CCMotionStreak.cpp | 4 +- cocos/2d/CCNodeGrid.cpp | 6 +- cocos/2d/CCParticleBatchNode.cpp | 2 +- cocos/2d/CCParticleSystemQuad.cpp | 4 +- cocos/2d/CCProgressTimer.cpp | 4 +- cocos/2d/CCRenderTexture.cpp | 6 +- cocos/2d/CCSprite.cpp | 4 +- cocos/2d/CCSpriteBatchNode.cpp | 2 +- cocos/2d/CCTextImage.cpp | 4 +- cocos/2d/CCTextImage.h | 144 +++++++++--------- cocos/2d/CCTextureAtlas.cpp | 8 +- ...ccShader_PositionTextureColor_noMVP_vert.h | 2 +- cocos/2d/cocos2d.cpp | 2 +- cocos/2d/renderer/CCCustomCommand.cpp | 2 +- cocos/2d/renderer/CCFrustum.cpp | 2 +- cocos/2d/renderer/CCGroupCommand.cpp | 4 +- cocos/2d/renderer/CCRenderer.cpp | 29 ++-- .../cocosbuilder/CCBAnimationManager.h | 6 +- .../editor-support/cocosbuilder/CCBKeyframe.h | 4 +- .../cocosbuilder/CCBMemberVariableAssigner.h | 1 - .../editor-support/cocosbuilder/CCBReader.cpp | 12 +- cocos/editor-support/cocosbuilder/CCBReader.h | 5 +- .../cocosbuilder/CCBSelectorResolver.h | 1 - .../editor-support/cocosbuilder/CCBSequence.h | 3 +- .../cocosbuilder/CCBSequenceProperty.h | 3 +- .../cocosbuilder/CCLabelBMFontLoader.h | 3 + .../cocosbuilder/CCLabelTTFLoader.h | 3 + .../cocosbuilder/CCMenuItemLoader.h | 3 + .../cocosbuilder/CCMenuLoader.h | 2 + .../CCNode+CCBRelativePositioning.h | 1 - .../cocosbuilder/CCNodeLoader.cpp | 3 + .../cocosbuilder/CCNodeLoader.h | 1 - .../cocosbuilder/CCNodeLoaderLibrary.h | 1 - .../cocosbuilder/CCNodeLoaderListener.h | 1 - .../cocosbuilder/CCParticleSystemQuadLoader.h | 3 + .../cocostudio/CCActionEaseEx.h | 1 - .../editor-support/cocostudio/CCActionFrame.h | 3 +- .../cocostudio/CCActionFrameEasing.h | 2 +- .../cocostudio/CCActionManagerEx.h | 1 - .../editor-support/cocostudio/CCActionNode.h | 1 - .../cocostudio/CCActionObject.cpp | 4 + .../cocostudio/CCActionObject.h | 1 - .../editor-support/cocostudio/CCArmature.cpp | 9 +- .../cocostudio/CCArmatureDataManager.cpp | 1 + .../cocostudio/CCArmatureDefine.h | 2 - .../editor-support/cocostudio/CCBatchNode.cpp | 7 +- cocos/editor-support/cocostudio/CCBatchNode.h | 1 + cocos/editor-support/cocostudio/CCComBase.h | 1 - .../cocostudio/CCDataReaderHelper.cpp | 11 +- cocos/editor-support/cocostudio/CCDatas.h | 6 + .../cocostudio/CCDisplayFactory.cpp | 2 + .../cocostudio/CCDisplayManager.cpp | 2 + .../cocostudio/CCInputDelegate.cpp | 5 + .../cocostudio/CCInputDelegate.h | 7 +- .../cocostudio/CCSSceneReader.h | 1 - cocos/editor-support/cocostudio/CCSkin.cpp | 6 + cocos/editor-support/cocostudio/CCSkin.h | 4 +- .../cocostudio/CCSpriteFrameCacheHelper.cpp | 4 +- .../cocostudio/CCSpriteFrameCacheHelper.h | 1 + cocos/editor-support/cocostudio/CCUtilMath.h | 1 + .../cocostudio/DictionaryHelper.cpp | 1 + .../cocostudio/DictionaryHelper.h | 1 - cocos/editor-support/spine/CCSkeleton.h | 6 +- .../spine/CCSkeletonAnimation.h | 1 - cocos/gui/UILayout.cpp | 6 +- cocos/network/HttpClient.cpp | 5 + cocos/network/HttpClient.h | 2 - cocos/network/HttpRequest.h | 3 +- cocos/network/HttpResponse.h | 1 - cocos/physics/CCPhysicsBody.h | 44 +++--- .../lua/bindings/lua_xml_http_request.h | 2 + extensions/GUI/CCControlExtension/CCControl.h | 3 +- .../GUI/CCControlExtension/CCControlButton.h | 1 + .../CCControlPotentiometer.cpp | 1 - .../CCControlPotentiometer.h | 1 + .../GUI/CCControlExtension/CCControlStepper.h | 1 + .../CCControlExtension/CCControlSwitch.cpp | 7 +- .../GUI/CCControlExtension/CCScale9Sprite.cpp | 3 + .../GUI/CCControlExtension/CCScale9Sprite.h | 5 +- extensions/GUI/CCEditBox/CCEditBox.h | 2 +- extensions/GUI/CCEditBox/CCEditBoxImpl.h | 1 - extensions/GUI/CCScrollView/CCScrollView.cpp | 7 + extensions/GUI/CCScrollView/CCScrollView.h | 4 +- extensions/GUI/CCScrollView/CCTableView.cpp | 1 - .../GUI/CCScrollView/CCTableViewCell.cpp | 2 +- extensions/GUI/CCScrollView/CCTableViewCell.h | 4 +- extensions/physics-nodes/CCPhysicsDebugNode.h | 3 +- extensions/physics-nodes/CCPhysicsSprite.h | 2 +- 108 files changed, 368 insertions(+), 229 deletions(-) diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index 4fa8442b92..f86c143d78 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -34,7 +34,7 @@ THE SOFTWARE. #include "ccGLStateCache.h" #include "CCDirector.h" #include "TransformUtils.h" -#include "CCRenderer.h" +#include "renderer/CCRenderer.h" #include "renderer/CCQuadCommand.h" // external diff --git a/cocos/2d/CCClippingNode.cpp b/cocos/2d/CCClippingNode.cpp index cdaf6a3df5..f5bc3bf95d 100644 --- a/cocos/2d/CCClippingNode.cpp +++ b/cocos/2d/CCClippingNode.cpp @@ -31,9 +31,10 @@ #include "CCShaderCache.h" #include "CCDirector.h" #include "CCDrawingPrimitives.h" -#include "CCRenderer.h" -#include "CCGroupCommand.h" -#include "CCCustomCommand.h" + +#include "renderer/CCRenderer.h" +#include "renderer/CCGroupCommand.h" +#include "renderer/CCCustomCommand.h" NS_CC_BEGIN diff --git a/cocos/2d/CCConfiguration.cpp b/cocos/2d/CCConfiguration.cpp index ddbc3cfae9..dbdf12ea14 100644 --- a/cocos/2d/CCConfiguration.cpp +++ b/cocos/2d/CCConfiguration.cpp @@ -31,13 +31,13 @@ THE SOFTWARE. #include "CCDictionary.h" #include "CCInteger.h" #include "CCBool.h" -#include "cocos2d.h" #include "platform/CCFileUtils.h" using namespace std; NS_CC_BEGIN +extern const char* cocos2dVersion(); Configuration* Configuration::s_sharedConfiguration = nullptr; diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index 3e06a99c75..d66385e295 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -60,9 +60,10 @@ THE SOFTWARE. #include "CCEventDispatcher.h" #include "CCEventCustom.h" #include "CCFontFreeType.h" -#include "CCRenderer.h" -#include "CCConsole.h" +#include "renderer/CCRenderer.h" #include "renderer/CCFrustum.h" +#include "CCConsole.h" + /** Position of the FPS diff --git a/cocos/2d/CCDrawNode.cpp b/cocos/2d/CCDrawNode.cpp index b920a311c2..3432ad024f 100644 --- a/cocos/2d/CCDrawNode.cpp +++ b/cocos/2d/CCDrawNode.cpp @@ -26,9 +26,9 @@ #include "CCGL.h" #include "CCEventType.h" #include "CCConfiguration.h" -#include "CCCustomCommand.h" +#include "renderer/CCCustomCommand.h" +#include "renderer/CCRenderer.h" #include "CCDirector.h" -#include "CCRenderer.h" #include "CCEventListenerCustom.h" #include "CCEventDispatcher.h" diff --git a/cocos/2d/CCFont.h b/cocos/2d/CCFont.h index 440da0808b..466336d2a2 100644 --- a/cocos/2d/CCFont.h +++ b/cocos/2d/CCFont.h @@ -28,7 +28,6 @@ #include -#include "cocos2d.h" #include "CCLabel.h" NS_CC_BEGIN diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index 9282956d03..166ec788a9 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -22,10 +22,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "cocos2d.h" + #include "CCFontAtlas.h" #include "CCFont.h" #include "CCFontFreeType.h" +#include "ccUTF8.h" +#include "CCDirector.h" #define PAGE_WIDTH 1024 #define PAGE_HEIGHT 1024 diff --git a/cocos/2d/CCFontAtlas.h b/cocos/2d/CCFontAtlas.h index 0a2d6f215b..b4122e1294 100644 --- a/cocos/2d/CCFontAtlas.h +++ b/cocos/2d/CCFontAtlas.h @@ -26,11 +26,14 @@ #define _CCFontAtlas_h_ #include +#include "CCPlatformMacros.h" +#include "CCObject.h" NS_CC_BEGIN //fwd class Font; +class Texture2D; struct FontLetterDefinition { diff --git a/cocos/2d/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp index ccea76b254..0ae1335f98 100644 --- a/cocos/2d/CCFontAtlasCache.cpp +++ b/cocos/2d/CCFontAtlasCache.cpp @@ -23,6 +23,8 @@ THE SOFTWARE. ****************************************************************************/ +#include + #include "CCFontAtlasCache.h" #include "CCFontAtlasFactory.h" diff --git a/cocos/2d/CCFontAtlasCache.h b/cocos/2d/CCFontAtlasCache.h index bdc7dd24d1..acacf883bb 100644 --- a/cocos/2d/CCFontAtlasCache.h +++ b/cocos/2d/CCFontAtlasCache.h @@ -29,8 +29,8 @@ #include #include -#include "cocos2d.h" #include "CCFontAtlas.h" +#include "CCLabel.h" NS_CC_BEGIN diff --git a/cocos/2d/CCFontAtlasFactory.h b/cocos/2d/CCFontAtlasFactory.h index 2a10cc8d63..1674fe0266 100644 --- a/cocos/2d/CCFontAtlasFactory.h +++ b/cocos/2d/CCFontAtlasFactory.h @@ -26,8 +26,8 @@ #ifndef _CCFontAtlasFactory_h_ #define _CCFontAtlasFactory_h_ -#include "cocos2d.h" #include "CCFontAtlas.h" +#include "CCLabel.h" NS_CC_BEGIN diff --git a/cocos/2d/CCFontDefinition.cpp b/cocos/2d/CCFontDefinition.cpp index c0d8af5051..7fd10d86a1 100644 --- a/cocos/2d/CCFontDefinition.cpp +++ b/cocos/2d/CCFontDefinition.cpp @@ -23,8 +23,9 @@ THE SOFTWARE. ****************************************************************************/ -#include "cocos2d.h" + #include "CCFontDefinition.h" +#include "CCDirector.h" NS_CC_BEGIN diff --git a/cocos/2d/CCFontFNT.cpp b/cocos/2d/CCFontFNT.cpp index 93fd5c2410..53eade4046 100644 --- a/cocos/2d/CCFontFNT.cpp +++ b/cocos/2d/CCFontFNT.cpp @@ -25,6 +25,10 @@ #include "CCFontFNT.h" #include "CCFontAtlas.h" +#include "CCLabelBMFont.h" +#include "CCDirector.h" +#include "CCTextureCache.h" +#include "ccUTF8.h" NS_CC_BEGIN diff --git a/cocos/2d/CCFontFNT.h b/cocos/2d/CCFontFNT.h index eec0bd761c..85588a662a 100644 --- a/cocos/2d/CCFontFNT.h +++ b/cocos/2d/CCFontFNT.h @@ -26,11 +26,12 @@ #ifndef _CCFontFNT_h_ #define _CCFontFNT_h_ -#include "cocos2d.h" #include "CCFont.h" NS_CC_BEGIN +class CCBMFontConfiguration; + class FontFNT : public Font { diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index 60b5a11954..915a333a48 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -31,6 +31,7 @@ THE SOFTWARE. #include "CCTextImage.h" #include "CCFont.h" #include "CCFontDefinition.h" +#include "platform/CCFileUtils.h" NS_CC_BEGIN diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index a267a41938..f97faa808b 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -27,6 +27,12 @@ #include "CCFontDefinition.h" #include "CCFontAtlasCache.h" #include "CCLabelTextFormatter.h" +#include "CCSprite.h" +#include "CCShaderCache.h" +#include "ccUTF8.h" +#include "CCSpriteFrame.h" +#include "CCDirector.h" +#include "renderer/CCRenderer.h" #define DISTANCEFIELD_ATLAS_FONTSIZE 50 diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index 26dcc89f9a..a046dca694 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -172,29 +172,29 @@ private: virtual void updateColor() override; //! used for optimization - Sprite *_reusedLetter; - std::vector _lettersInfo; + Sprite *_reusedLetter; + std::vector _lettersInfo; - float _commonLineHeight; - bool _lineBreakWithoutSpaces; - float _width; - TextHAlignment _alignment; - unsigned short int * _currentUTF16String; - unsigned short int * _originalUTF16String; - Size * _advances; - FontAtlas * _fontAtlas; - bool _isOpacityModifyRGB; + float _commonLineHeight; + bool _lineBreakWithoutSpaces; + float _width; + TextHAlignment _alignment; + unsigned short int * _currentUTF16String; + unsigned short int * _originalUTF16String; + Size * _advances; + FontAtlas * _fontAtlas; + bool _isOpacityModifyRGB; - bool _useDistanceField; - bool _useA8Shader; - int _fontSize; + bool _useDistanceField; + bool _useA8Shader; + int _fontSize; - LabelEffect _currLabelEffect; - Color3B _effectColor; + LabelEffect _currLabelEffect; + Color3B _effectColor; - GLuint _uniformEffectColor; + GLuint _uniformEffectColor; - CustomCommand _customCommand; + CustomCommand _customCommand; }; diff --git a/cocos/2d/CCLabelTextFormatProtocol.h b/cocos/2d/CCLabelTextFormatProtocol.h index bf72775a51..e91d7b875a 100644 --- a/cocos/2d/CCLabelTextFormatProtocol.h +++ b/cocos/2d/CCLabelTextFormatProtocol.h @@ -25,11 +25,16 @@ #ifndef _CCLabelTextFormatProtocol_h_ #define _CCLabelTextFormatProtocol_h_ -#include "CCFontAtlas.h" + #include +#include "CCFontAtlas.h" +#include "CCGeometry.h" +#include "ccTypes.h" + NS_CC_BEGIN +class Sprite; struct LetterInfo { @@ -46,13 +51,13 @@ public: virtual ~LabelTextFormatProtocol() {} - virtual bool recordLetterInfo(const cocos2d::Point& point,unsigned short int theChar, int spriteIndex) = 0; + virtual bool recordLetterInfo(const Point& point,unsigned short int theChar, int spriteIndex) = 0; virtual bool recordPlaceholderInfo(int spriteIndex) = 0; virtual std::vector *getLettersInfo() = 0; virtual float getLetterPosXLeft(int index) const = 0; virtual float getLetterPosXRight(int index) const = 0; // sprite related stuff - virtual cocos2d::Sprite *getLetter(int ID) = 0; + virtual Sprite *getLetter(int ID) = 0; // font related stuff virtual int getCommonLineHeight() const = 0; @@ -60,7 +65,7 @@ public: virtual int getXOffsetForChar(unsigned short c) const = 0; virtual int getYOffsetForChar(unsigned short c) const = 0; virtual int getAdvanceForChar(unsigned short c, int hintPositionInString) const = 0; - virtual cocos2d::Rect getRectForChar(unsigned short c) const = 0; + virtual Rect getRectForChar(unsigned short c) const = 0; // string related stuff virtual int getStringNumLines() const = 0; @@ -68,7 +73,7 @@ public: virtual unsigned short getCharAtStringPosition(int position) const = 0; virtual unsigned short * getUTF8String() const = 0; virtual void assignNewUTF8String(unsigned short *newString) = 0; - virtual TextHAlignment getTextAlignment() const = 0; + virtual TextHAlignment getTextAlignment() const = 0; // label related stuff virtual float getMaxLineWidth() const = 0; diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index 550d017beb..e131cabeec 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -25,9 +25,9 @@ #include -#include "cocos2d.h" #include "ccUTF8.h" #include "CCLabelTextFormatter.h" +#include "CCDirector.h" using namespace std; diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index 1bae6e040c..1b24c97f25 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -44,8 +44,8 @@ THE SOFTWARE. #include "CCEventListenerAcceleration.h" #include "platform/CCDevice.h" #include "CCScene.h" -#include "CCCustomCommand.h" -#include "CCRenderer.h" +#include "renderer/CCCustomCommand.h" +#include "renderer/CCRenderer.h" NS_CC_BEGIN diff --git a/cocos/2d/CCMotionStreak.cpp b/cocos/2d/CCMotionStreak.cpp index 4e248b7ea1..fdb0b70fb8 100644 --- a/cocos/2d/CCMotionStreak.cpp +++ b/cocos/2d/CCMotionStreak.cpp @@ -31,8 +31,8 @@ THE SOFTWARE. #include "ccMacros.h" #include "CCDirector.h" #include "CCVertex.h" -#include "CCCustomCommand.h" -#include "CCRenderer.h" +#include "renderer/CCCustomCommand.h" +#include "renderer/CCRenderer.h" NS_CC_BEGIN diff --git a/cocos/2d/CCNodeGrid.cpp b/cocos/2d/CCNodeGrid.cpp index 90d5647a57..9c24500da0 100644 --- a/cocos/2d/CCNodeGrid.cpp +++ b/cocos/2d/CCNodeGrid.cpp @@ -25,9 +25,9 @@ #include "CCNodeGrid.h" #include "CCGrid.h" -#include "CCGroupCommand.h" -#include "CCRenderer.h" -#include "CCCustomCommand.h" +#include "renderer/CCGroupCommand.h" +#include "renderer/CCRenderer.h" +#include "renderer/CCCustomCommand.h" NS_CC_BEGIN diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index 773b780997..b291910422 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -44,7 +44,7 @@ #include "kazmath/GL/matrix.h" #include "CCProfiling.h" #include "renderer/CCQuadCommand.h" -#include "CCRenderer.h" +#include "renderer/CCRenderer.h" NS_CC_BEGIN diff --git a/cocos/2d/CCParticleSystemQuad.cpp b/cocos/2d/CCParticleSystemQuad.cpp index 579db6c024..8495483116 100644 --- a/cocos/2d/CCParticleSystemQuad.cpp +++ b/cocos/2d/CCParticleSystemQuad.cpp @@ -38,9 +38,9 @@ THE SOFTWARE. #include "TransformUtils.h" #include "CCEventType.h" #include "CCConfiguration.h" -#include "CCRenderer.h" +#include "renderer/CCRenderer.h" #include "renderer/CCQuadCommand.h" -#include "CCCustomCommand.h" +#include "renderer/CCCustomCommand.h" // extern #include "kazmath/GL/matrix.h" diff --git a/cocos/2d/CCProgressTimer.cpp b/cocos/2d/CCProgressTimer.cpp index 7d135a9016..37c754a0ee 100644 --- a/cocos/2d/CCProgressTimer.cpp +++ b/cocos/2d/CCProgressTimer.cpp @@ -33,8 +33,8 @@ THE SOFTWARE. #include "CCDirector.h" #include "TransformUtils.h" #include "CCDrawingPrimitives.h" -#include "CCRenderer.h" -#include "CCCustomCommand.h" +#include "renderer/CCRenderer.h" +#include "renderer/CCCustomCommand.h" // extern #include "kazmath/GL/matrix.h" diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index efaad582ef..fcf00452ed 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -38,9 +38,9 @@ THE SOFTWARE. #include "CCEventType.h" #include "CCGrid.h" -#include "CCRenderer.h" -#include "CCGroupCommand.h" -#include "CCCustomCommand.h" +#include "renderer/CCRenderer.h" +#include "renderer/CCGroupCommand.h" +#include "renderer/CCCustomCommand.h" // extern #include "kazmath/GL/matrix.h" diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 8bf5a3d1b1..c66c811b1b 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -45,9 +45,9 @@ THE SOFTWARE. #include "CCAffineTransform.h" #include "TransformUtils.h" #include "CCProfiling.h" -#include "CCRenderer.h" +#include "renderer/CCRenderer.h" #include "renderer/CCQuadCommand.h" -#include "CCFrustum.h" +#include "renderer/CCFrustum.h" // external #include "kazmath/GL/matrix.h" diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 502474d00e..fde85639aa 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -43,7 +43,7 @@ THE SOFTWARE. #include "CCProfiling.h" #include "CCLayer.h" #include "CCScene.h" -#include "CCRenderer.h" +#include "renderer/CCRenderer.h" #include "renderer/CCQuadCommand.h" // external #include "kazmath/GL/matrix.h" diff --git a/cocos/2d/CCTextImage.cpp b/cocos/2d/CCTextImage.cpp index d47ab768d0..cd972a172e 100644 --- a/cocos/2d/CCTextImage.cpp +++ b/cocos/2d/CCTextImage.cpp @@ -28,10 +28,10 @@ #include #include -#include "cocos2d.h" #include "CCTextImage.h" #include "CCFontFreeType.h" #include "CCFont.h" +#include "ccUTF8.h" NS_CC_BEGIN @@ -295,7 +295,7 @@ bool TextImage::createPageDefinitions(unsigned short int *inText, int imageWidth return true; } -int TextImage::getNumGlyphsFittingInSize(std::map &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize) +int TextImage::getNumGlyphsFittingInSize(std::unordered_map &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize) { if (!strUTF8) return 0; diff --git a/cocos/2d/CCTextImage.h b/cocos/2d/CCTextImage.h index 1c0da97201..b7baddb561 100644 --- a/cocos/2d/CCTextImage.h +++ b/cocos/2d/CCTextImage.h @@ -23,15 +23,19 @@ THE SOFTWARE. ****************************************************************************/ -#ifndef _TextImage_h_ -#define _TextImage_h_ +#ifndef _CCTextImage_h_ +#define _CCTextImage_h_ -//#include "CCFont.h" #include +#include + +#include "CCPlatformMacros.h" +#include "CCGeometry.h" NS_CC_BEGIN class Font; +class Texture2D; /** @brief GlyphDef defines one single glyph (character) in a text image * @@ -43,27 +47,33 @@ class CC_DLL GlyphDef { public: - GlyphDef() : _validGlyph(false) { /*do nothing*/ } - GlyphDef(unsigned short int letterUTF8, const Rect &rect) { _gliphRect = rect; _uTF16Letter = letterUTF8; } + GlyphDef() : _validGlyph(false) {} + GlyphDef(unsigned short int letterUTF8, const Rect &rect) { + _gliphRect = rect; + _uTF16Letter = letterUTF8; + } - void setUTF16Letter(unsigned short int letterUTF8) { _uTF16Letter = letterUTF8; } - void setRect(const Rect & theRect) { _gliphRect = theRect; } - unsigned short int getUTF8Letter() { return _uTF16Letter; } - const Rect & getRect() const { return _gliphRect; } - void setPadding(float padding) { _padding = padding; } - float getPadding() { return _padding; } - void setCommonHeight(float commonHeight) { _commonHeight = commonHeight; } - float getCommonHeight() { return _commonHeight; } - void setValid(bool isValid) { _validGlyph = isValid; } - bool isValid() { return _validGlyph; } + void setUTF16Letter(unsigned short int letterUTF8) { _uTF16Letter = letterUTF8; } + void setRect(const Rect & theRect) { _gliphRect = theRect; } + + unsigned short int getUTF8Letter() const { return _uTF16Letter; } + const Rect& getRect() const { return _gliphRect; } + + void setPadding(float padding) { _padding = padding; } + float getPadding() const { return _padding; } + + void setCommonHeight(float commonHeight) { _commonHeight = commonHeight; } + float getCommonHeight() const { return _commonHeight; } + + void setValid(bool isValid) { _validGlyph = isValid; } + bool isValid() const { return _validGlyph; } -private: - - Rect _gliphRect; - unsigned short int _uTF16Letter; - float _padding; - float _commonHeight; - bool _validGlyph; +protected: + Rect _gliphRect; + unsigned short int _uTF16Letter; + float _padding; + float _commonHeight; + bool _validGlyph; }; @@ -78,23 +88,21 @@ public: TextLineDef(float x, float y, float width, float height); - float getX() const { return _x; } - float getY() const { return _y; } - float getWidth() const { return _width; } - float getHeight() const { return _height; } + float getX() const { return _x; } + float getY() const { return _y; } + float getWidth() const { return _width; } + float getHeight() const { return _height; } - void addGlyph(GlyphDef theGlyph) { _glyphs.push_back(theGlyph); } - int getNumGlyph() const { return static_cast(_glyphs.size()); } - const GlyphDef & getGlyphAt(int index) const { return _glyphs[index]; } - -private: - - float _x; - float _y; - float _width; - float _height; - std::vector _glyphs; + void addGlyph(GlyphDef theGlyph) { _glyphs.push_back(theGlyph); } + int getNumGlyph() const { return static_cast(_glyphs.size()); } + const GlyphDef & getGlyphAt(int index) const { return _glyphs[index]; } +protected: + float _x; + float _y; + float _width; + float _height; + std::vector _glyphs; }; /** @brief TextPageDef defines one text image page (a TextImage can have/use more than one page) @@ -115,28 +123,26 @@ public: */ ~TextPageDef(); - void addLine(TextLineDef *theLine) { _lines.push_back(theLine); } - int getNumLines() const { return static_cast(_lines.size()); } - TextLineDef * getLineAt(int index) const { return _lines[index]; } - int getWidth() const { return _width; } - int getHeight() const { return _height; } - int getPageNumber() const { return _pageNum; } - void setPageData(unsigned char *data) { _pageData = data; } - const unsigned char * getPageData() const { return _pageData; } - Texture2D *getPageTexture(); + void addLine(TextLineDef *theLine) { _lines.push_back(theLine); } + int getNumLines() const { return static_cast(_lines.size()); } + TextLineDef * getLineAt(int index) const { return _lines[index]; } + int getWidth() const { return _width; } + int getHeight() const { return _height; } + int getPageNumber() const { return _pageNum; } + void setPageData(unsigned char *data) { _pageData = data; } + const unsigned char * getPageData() const { return _pageData; } + Texture2D *getPageTexture(); void preparePageTexture(bool releaseRAWData = true); -private: - +protected: bool generatePageTexture(bool releasePageData = false); - int _pageNum; - int _width; - int _height; - unsigned char * _pageData; - Texture2D * _pageTexture; - std::vector _lines; - + int _pageNum; + int _width; + int _height; + unsigned char * _pageData; + Texture2D* _pageTexture; + std::vector _lines; }; /** @brief CCTextFontPages collection of pages (TextPageDef) @@ -156,13 +162,12 @@ public: */ ~TextFontPagesDef(); - void addPage(TextPageDef *newPage) { _pages.push_back(newPage); } - int getNumPages() const { return static_cast(_pages.size()); } - TextPageDef* getPageAt(int index) const { return _pages[index]; } + void addPage(TextPageDef *newPage) { _pages.push_back(newPage); } + int getNumPages() const { return static_cast(_pages.size()); } + TextPageDef* getPageAt(int index) const { return _pages[index]; } -private: - - std::vector _pages; +protected: + std::vector _pages; }; @@ -184,28 +189,27 @@ public: bool initWithString(const char *text, int width, int height, Font* font, bool releaseRAWData = true); - TextFontPagesDef * getPages() const { return _fontPages; } - Font * getFont() const { return _font; } - -private: + TextFontPagesDef* getPages() const { return _fontPages; } + Font* getFont() const { return _font; } +protected: bool createImageDataFromPages(TextFontPagesDef *thePages, bool releaseRAWData = true); bool addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16 = false); bool generateTextGlyphs(const char * text); - int getNumGlyphsFittingInSize(std::map &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize); + int getNumGlyphsFittingInSize(std::unordered_map &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize); bool createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight); unsigned char * preparePageGlyphData(TextPageDef *thePage); // glyph rendering unsigned char * renderGlyphData(TextPageDef *thePage); - std::map _textGlyphs; - TextFontPagesDef * _fontPages; - Font * _font; + std::unordered_map _textGlyphs; + TextFontPagesDef* _fontPages; + Font* _font; }; NS_CC_END -#endif +#endif // _CCTextImage_h_ diff --git a/cocos/2d/CCTextureAtlas.cpp b/cocos/2d/CCTextureAtlas.cpp index 8a9818d8fc..2d2787a25d 100644 --- a/cocos/2d/CCTextureAtlas.cpp +++ b/cocos/2d/CCTextureAtlas.cpp @@ -624,11 +624,11 @@ void TextureAtlas::drawNumberOfQuads(ssize_t numberOfQuads, ssize_t start) { glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]); // option 1: subdata - //glBufferSubData(GL_ARRAY_BUFFER, sizeof(_quads[0])*start, sizeof(_quads[0]) * n , &_quads[start] ); - +// glBufferSubData(GL_ARRAY_BUFFER, sizeof(_quads[0])*start, sizeof(_quads[0]) * n , &_quads[start] ); + // option 2: data - // glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * (n-start), &quads_[start], GL_DYNAMIC_DRAW); - +// glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * (n-start), &quads_[start], GL_DYNAMIC_DRAW); + // option 3: orphaning + glMapBuffer glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * (numberOfQuads-start), nullptr, GL_DYNAMIC_DRAW); void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); diff --git a/cocos/2d/ccShader_PositionTextureColor_noMVP_vert.h b/cocos/2d/ccShader_PositionTextureColor_noMVP_vert.h index bae95bcfea..f2d39c3c10 100644 --- a/cocos/2d/ccShader_PositionTextureColor_noMVP_vert.h +++ b/cocos/2d/ccShader_PositionTextureColor_noMVP_vert.h @@ -38,7 +38,7 @@ varying vec2 v_texCoord; \n\ \n\ void main() \n\ { \n\ - gl_Position = CC_PMatrix * a_position; \n\ + gl_Position = CC_PMatrix * a_position; \n\ v_fragmentColor = a_color; \n\ v_texCoord = a_texCoord; \n\ } \n\ diff --git a/cocos/2d/cocos2d.cpp b/cocos/2d/cocos2d.cpp index 99adc6518c..34b10b7f09 100644 --- a/cocos/2d/cocos2d.cpp +++ b/cocos/2d/cocos2d.cpp @@ -25,7 +25,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -#include "cocos2d.h" +#include "CCPlatformMacros.h" NS_CC_BEGIN diff --git a/cocos/2d/renderer/CCCustomCommand.cpp b/cocos/2d/renderer/CCCustomCommand.cpp index b0c39f2049..5bbf2032ea 100644 --- a/cocos/2d/renderer/CCCustomCommand.cpp +++ b/cocos/2d/renderer/CCCustomCommand.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCCustomCommand.h" +#include "renderer/CCCustomCommand.h" NS_CC_BEGIN diff --git a/cocos/2d/renderer/CCFrustum.cpp b/cocos/2d/renderer/CCFrustum.cpp index e02236e3b0..4f88e2356f 100644 --- a/cocos/2d/renderer/CCFrustum.cpp +++ b/cocos/2d/renderer/CCFrustum.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCFrustum.h" +#include "renderer/CCFrustum.h" #include "CCConsole.h" #include diff --git a/cocos/2d/renderer/CCGroupCommand.cpp b/cocos/2d/renderer/CCGroupCommand.cpp index 4f7707cd76..9c0e57eb92 100644 --- a/cocos/2d/renderer/CCGroupCommand.cpp +++ b/cocos/2d/renderer/CCGroupCommand.cpp @@ -23,8 +23,8 @@ ****************************************************************************/ -#include "CCGroupCommand.h" -#include "CCRenderer.h" +#include "renderer/CCGroupCommand.h" +#include "renderer/CCRenderer.h" #include "CCDirector.h" NS_CC_BEGIN diff --git a/cocos/2d/renderer/CCRenderer.cpp b/cocos/2d/renderer/CCRenderer.cpp index 3ffa5b583a..30495a8aa3 100644 --- a/cocos/2d/renderer/CCRenderer.cpp +++ b/cocos/2d/renderer/CCRenderer.cpp @@ -22,13 +22,13 @@ THE SOFTWARE. ****************************************************************************/ -#include "CCRenderer.h" -#include "CCShaderCache.h" -#include "ccGLStateCache.h" -#include "CCCustomCommand.h" +#include "renderer/CCRenderer.h" #include "renderer/CCQuadCommand.h" #include "renderer/CCBatchCommand.h" -#include "CCGroupCommand.h" +#include "renderer/CCCustomCommand.h" +#include "renderer/CCGroupCommand.h" +#include "CCShaderCache.h" +#include "ccGLStateCache.h" #include "CCConfiguration.h" #include "CCDirector.h" #include "CCEventDispatcher.h" @@ -330,20 +330,24 @@ void Renderer::render() void Renderer::convertToWorldCoordiantes(V3F_C4B_T2F_Quad* quads, ssize_t quantity, const kmMat4& modelView) { +// kmMat4 matrixP, mvp; +// kmGLGetMatrix(KM_GL_PROJECTION, &matrixP); +// kmMat4Multiply(&mvp, &matrixP, &modelView); + for(ssize_t i=0; ibl.vertices; - kmVec3Transform(vec1, vec1, &modelView); + kmVec3TransformCoord(vec1, vec1, &modelView); kmVec3 *vec2 = (kmVec3*)&q->br.vertices; - kmVec3Transform(vec2, vec2, &modelView); + kmVec3TransformCoord(vec2, vec2, &modelView); kmVec3 *vec3 = (kmVec3*)&q->tr.vertices; - kmVec3Transform(vec3, vec3, &modelView); + kmVec3TransformCoord(vec3, vec3, &modelView); kmVec3 *vec4 = (kmVec3*)&q->tl.vertices; - kmVec3Transform(vec4, vec4, &modelView); + kmVec3TransformCoord(vec4, vec4, &modelView); } } @@ -366,6 +370,13 @@ void Renderer::drawBatchedQuads() //Set VBO data glBindBuffer(GL_ARRAY_BUFFER, _buffersVBO[0]); + // option 1: subdata +// glBufferSubData(GL_ARRAY_BUFFER, sizeof(_quads[0])*start, sizeof(_quads[0]) * n , &_quads[start] ); + + // option 2: data +// glBufferData(GL_ARRAY_BUFFER, sizeof(quads_[0]) * (n-start), &quads_[start], GL_DYNAMIC_DRAW); + + // option 3: orphaning + glMapBuffer glBufferData(GL_ARRAY_BUFFER, sizeof(_quads[0]) * (_numQuads), nullptr, GL_DYNAMIC_DRAW); void *buf = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY); memcpy(buf, _quads, sizeof(_quads[0])* (_numQuads)); diff --git a/cocos/editor-support/cocosbuilder/CCBAnimationManager.h b/cocos/editor-support/cocosbuilder/CCBAnimationManager.h index 14328af61d..f1f351a631 100644 --- a/cocos/editor-support/cocosbuilder/CCBAnimationManager.h +++ b/cocos/editor-support/cocosbuilder/CCBAnimationManager.h @@ -1,7 +1,11 @@ #ifndef __CCB_CCBANIMATION_MANAGER_H__ #define __CCB_CCBANIMATION_MANAGER_H__ -#include "cocos2d.h" +#include "CCMap.h" +#include "CCActionInterval.h" +#include "CCActionInstant.h" +#include "CCActionEase.h" + #include "extensions/ExtensionMacros.h" #include "CCBSequence.h" #include "CCBSequenceProperty.h" diff --git a/cocos/editor-support/cocosbuilder/CCBKeyframe.h b/cocos/editor-support/cocosbuilder/CCBKeyframe.h index 49779319cc..e3c009e2df 100644 --- a/cocos/editor-support/cocosbuilder/CCBKeyframe.h +++ b/cocos/editor-support/cocosbuilder/CCBKeyframe.h @@ -1,7 +1,9 @@ #ifndef __CCB_KEYFRAME_H__ #define __CCB_KEYFRAME_H__ -#include "cocos2d.h" +#include "CCObject.h" +#include "CCValue.h" + namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCBMemberVariableAssigner.h b/cocos/editor-support/cocosbuilder/CCBMemberVariableAssigner.h index 7c429ed505..4cafab98d6 100644 --- a/cocos/editor-support/cocosbuilder/CCBMemberVariableAssigner.h +++ b/cocos/editor-support/cocosbuilder/CCBMemberVariableAssigner.h @@ -1,7 +1,6 @@ #ifndef _CCB_CCBMEMBERVARIABLEASSIGNER_H_ #define _CCB_CCBMEMBERVARIABLEASSIGNER_H_ -#include "cocos2d.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index f190b72def..056f2553d0 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -1,7 +1,13 @@ -#include "CCBReader.h" - +#include #include +#include "CCDirector.h" +#include "platform/CCFileUtils.h" +#include "CCScene.h" +#include "CCTextureCache.h" +#include "CCSpriteFrameCache.h" + +#include "CCBReader.h" #include "CCNodeLoader.h" #include "CCNodeLoaderLibrary.h" #include "CCNodeLoaderListener.h" @@ -11,7 +17,7 @@ #include "CCBSequenceProperty.h" #include "CCBKeyframe.h" -#include + using namespace std; using namespace cocos2d; diff --git a/cocos/editor-support/cocosbuilder/CCBReader.h b/cocos/editor-support/cocosbuilder/CCBReader.h index 69306227ed..3c2a39c763 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.h +++ b/cocos/editor-support/cocosbuilder/CCBReader.h @@ -1,9 +1,12 @@ #ifndef _CCB_CCBREADER_H_ #define _CCB_CCBREADER_H_ -#include "cocos2d.h" #include #include +#include "CCNode.h" +#include "CCData.h" +#include "CCMap.h" + #include "CCBSequence.h" #include "extensions/GUI/CCControlExtension/CCControl.h" diff --git a/cocos/editor-support/cocosbuilder/CCBSelectorResolver.h b/cocos/editor-support/cocosbuilder/CCBSelectorResolver.h index f054c284c5..110d2ced61 100644 --- a/cocos/editor-support/cocosbuilder/CCBSelectorResolver.h +++ b/cocos/editor-support/cocosbuilder/CCBSelectorResolver.h @@ -1,7 +1,6 @@ #ifndef _CCB_CCBSELECTORRESOLVER_H_ #define _CCB_CCBSELECTORRESOLVER_H_ -#include "cocos2d.h" #include "extensions//GUI/CCControlExtension/CCInvocation.h" diff --git a/cocos/editor-support/cocosbuilder/CCBSequence.h b/cocos/editor-support/cocosbuilder/CCBSequence.h index dd7c1a899f..045fa536b5 100644 --- a/cocos/editor-support/cocosbuilder/CCBSequence.h +++ b/cocos/editor-support/cocosbuilder/CCBSequence.h @@ -2,7 +2,8 @@ #define __CCB_CCSEQUENCE_H__ #include -#include "cocos2d.h" + +#include "CCObject.h" #include "CCBSequenceProperty.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h index 03ca04799f..fe19b15596 100644 --- a/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h +++ b/cocos/editor-support/cocosbuilder/CCBSequenceProperty.h @@ -1,7 +1,8 @@ #ifndef __CCB_SEQUENCE_PROPERTY_H__ #define __CCB_SEQUENCE_PROPERTY_H__ -#include "cocos2d.h" +#include "CCObject.h" +#include "CCVector.h" #include "CCBKeyframe.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.h b/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.h index ae5cb20011..c24239c3f2 100644 --- a/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.h +++ b/cocos/editor-support/cocosbuilder/CCLabelBMFontLoader.h @@ -1,6 +1,9 @@ #ifndef _CCB_CCLABELBMFONTLOADER_H_ #define _CCB_CCLABELBMFONTLOADER_H_ +#include "CCObject.h" +#include "CCLabelBMFont.h" + #include "CCNodeLoader.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h b/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h index de0ca00d42..aa0fc0cdfe 100644 --- a/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h +++ b/cocos/editor-support/cocosbuilder/CCLabelTTFLoader.h @@ -1,6 +1,9 @@ #ifndef _CCB_CCLABELTTFLOADER_H_ #define _CCB_CCLABELTTFLOADER_H_ +#include "CCObject.h" +#include "CCLabelTTF.h" + #include "CCNodeLoader.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCMenuItemLoader.h b/cocos/editor-support/cocosbuilder/CCMenuItemLoader.h index 5db15eacba..1156a46f13 100644 --- a/cocos/editor-support/cocosbuilder/CCMenuItemLoader.h +++ b/cocos/editor-support/cocosbuilder/CCMenuItemLoader.h @@ -1,6 +1,9 @@ #ifndef _CCB_CCMENUITEMLOADER_H_ #define _CCB_CCMENUITEMLOADER_H_ +#include "CCObject.h" +#include "CCMenuItem.h" + #include "CCLayerLoader.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCMenuLoader.h b/cocos/editor-support/cocosbuilder/CCMenuLoader.h index 851913c74c..75ff815f26 100644 --- a/cocos/editor-support/cocosbuilder/CCMenuLoader.h +++ b/cocos/editor-support/cocosbuilder/CCMenuLoader.h @@ -2,6 +2,8 @@ #define _CCB_CCMENULOADER_H_ #include "CCLayerLoader.h" +#include "CCObject.h" +#include "CCMenu.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.h b/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.h index 7923d3c681..7dd0ed5ea8 100644 --- a/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.h +++ b/cocos/editor-support/cocosbuilder/CCNode+CCBRelativePositioning.h @@ -1,7 +1,6 @@ #ifndef __CCB_CCNODE_RELATIVEPOSITIONING_H__ #define __CCB_CCNODE_RELATIVEPOSITIONING_H__ -#include "cocos2d.h" #include "CCBReader.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp index adb7b8d095..598f6cad11 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp @@ -1,9 +1,12 @@ +#include "cocos2d.h" + #include "CCNodeLoader.h" #include "CCBSelectorResolver.h" #include "CCBMemberVariableAssigner.h" #include "CCBAnimationManager.h" #include "CCNode+CCBRelativePositioning.h" + using namespace std; using namespace cocos2d; using namespace cocos2d::extension; diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoader.h b/cocos/editor-support/cocosbuilder/CCNodeLoader.h index bb18d03866..e67fcb047f 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoader.h +++ b/cocos/editor-support/cocosbuilder/CCNodeLoader.h @@ -2,7 +2,6 @@ #define _CCB_CCNODELOADER_H_ #include "extensions/GUI/CCControlExtension/CCInvocation.h" -#include "cocos2d.h" #include "CCBReader.h" #include "extensions/GUI/CCControlExtension/CCControl.h" diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.h b/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.h index c75276d22f..6fe711feda 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.h +++ b/cocos/editor-support/cocosbuilder/CCNodeLoaderLibrary.h @@ -1,7 +1,6 @@ #ifndef _CCB_CCNODELOADERLIBRARY_H_ #define _CCB_CCNODELOADERLIBRARY_H_ -#include "cocos2d.h" #include "CCBReader.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoaderListener.h b/cocos/editor-support/cocosbuilder/CCNodeLoaderListener.h index cf6c53e543..dedaafa51e 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoaderListener.h +++ b/cocos/editor-support/cocosbuilder/CCNodeLoaderListener.h @@ -1,7 +1,6 @@ #ifndef _CCB_CCNODELOADERLISTENER_H_ #define _CCB_CCNODELOADERLISTENER_H_ -#include "cocos2d.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.h b/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.h index feced7312e..64efbdecba 100644 --- a/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.h +++ b/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.h @@ -1,6 +1,9 @@ #ifndef _CCB_CCPARTICLESYSTEMQUADLOADER_H_ #define _CCB_CCPARTICLESYSTEMQUADLOADER_H_ +#include "CCObject.h" +#include "CCParticleSystemQuad.h" + #include "CCNodeLoader.h" namespace cocosbuilder { diff --git a/cocos/editor-support/cocostudio/CCActionEaseEx.h b/cocos/editor-support/cocostudio/CCActionEaseEx.h index 0350d4d590..0a88c77e69 100644 --- a/cocos/editor-support/cocostudio/CCActionEaseEx.h +++ b/cocos/editor-support/cocostudio/CCActionEaseEx.h @@ -25,7 +25,6 @@ THE SOFTWARE. #ifndef __ActionEaseEx_H__ #define __ActionEaseEx_H__ -#include "cocos2d.h" #include "cocostudio/CocoStudio.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCActionFrame.h b/cocos/editor-support/cocostudio/CCActionFrame.h index 5b152f4eb3..9ff01ddf05 100644 --- a/cocos/editor-support/cocostudio/CCActionFrame.h +++ b/cocos/editor-support/cocostudio/CCActionFrame.h @@ -25,7 +25,8 @@ THE SOFTWARE. #ifndef __ActionFRAME_H__ #define __ActionFRAME_H__ -#include "cocos2d.h" +#include "CCGeometry.h" +#include "CCActionInterval.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCActionFrameEasing.h b/cocos/editor-support/cocostudio/CCActionFrameEasing.h index 65c9ad3a05..1ae824e482 100644 --- a/cocos/editor-support/cocostudio/CCActionFrameEasing.h +++ b/cocos/editor-support/cocostudio/CCActionFrameEasing.h @@ -25,7 +25,7 @@ THE SOFTWARE. #ifndef __ActionFrameEasing_H__ #define __ActionFrameEasing_H__ -#include "cocos2d.h" +#include "CCObject.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCActionManagerEx.h b/cocos/editor-support/cocostudio/CCActionManagerEx.h index e24c48d436..ba4e0c7804 100644 --- a/cocos/editor-support/cocostudio/CCActionManagerEx.h +++ b/cocos/editor-support/cocostudio/CCActionManagerEx.h @@ -25,7 +25,6 @@ THE SOFTWARE. #ifndef __ActionMANAGER_H__ #define __ActionMANAGER_H__ -#include "cocos2d.h" #include "cocostudio/CCActionObject.h" #include "cocostudio/DictionaryHelper.h" diff --git a/cocos/editor-support/cocostudio/CCActionNode.h b/cocos/editor-support/cocostudio/CCActionNode.h index 42e4d0e4ee..9a2195327d 100644 --- a/cocos/editor-support/cocostudio/CCActionNode.h +++ b/cocos/editor-support/cocostudio/CCActionNode.h @@ -25,7 +25,6 @@ THE SOFTWARE. #ifndef __ActionNODE_H__ #define __ActionNODE_H__ -#include "cocos2d.h" #include "cocostudio/CCActionFrame.h" #include "cocostudio/DictionaryHelper.h" diff --git a/cocos/editor-support/cocostudio/CCActionObject.cpp b/cocos/editor-support/cocostudio/CCActionObject.cpp index eeba39d121..57291ae369 100644 --- a/cocos/editor-support/cocostudio/CCActionObject.cpp +++ b/cocos/editor-support/cocostudio/CCActionObject.cpp @@ -25,6 +25,10 @@ THE SOFTWARE. #include "cocostudio/CCActionObject.h" #include "cocostudio/DictionaryHelper.h" +#include "CCDirector.h" +#include "CCScheduler.h" +#include "CCActionInstant.h" + using namespace cocos2d; namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCActionObject.h b/cocos/editor-support/cocostudio/CCActionObject.h index 8d33a2017f..249489b620 100644 --- a/cocos/editor-support/cocostudio/CCActionObject.h +++ b/cocos/editor-support/cocostudio/CCActionObject.h @@ -25,7 +25,6 @@ THE SOFTWARE. #ifndef __ActionObject_H__ #define __ActionObject_H__ -#include "cocos2d.h" #include "CCActionNode.h" #include "cocostudio/DictionaryHelper.h" diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index decc3cc0c2..80d6a4dca7 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -28,9 +28,12 @@ THE SOFTWARE. #include "cocostudio/CCDataReaderHelper.h" #include "cocostudio/CCDatas.h" #include "cocostudio/CCSkin.h" + #include "renderer/CCQuadCommand.h" -#include "CCRenderer.h" -#include "CCGroupCommand.h" +#include "renderer/CCRenderer.h" +#include "renderer/CCGroupCommand.h" +#include "CCShaderCache.h" +#include "CCDrawingPrimitives.h" #if ENABLE_PHYSICS_BOX2D_DETECT #include "Box2D/Box2D.h" @@ -570,7 +573,7 @@ void CCArmature::drawContour() } DrawPrimitives::drawPoly( points, (unsigned int)length, true ); - delete points; + delete []points; } } } diff --git a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp index 0848ab6226..de05838940 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp +++ b/cocos/editor-support/cocostudio/CCArmatureDataManager.cpp @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +#include "CCSpriteFrameCache.h" #include "cocostudio/CCArmatureDataManager.h" #include "cocostudio/CCTransformHelp.h" diff --git a/cocos/editor-support/cocostudio/CCArmatureDefine.h b/cocos/editor-support/cocostudio/CCArmatureDefine.h index 934b7bc43d..8c8eca2608 100644 --- a/cocos/editor-support/cocostudio/CCArmatureDefine.h +++ b/cocos/editor-support/cocostudio/CCArmatureDefine.h @@ -26,8 +26,6 @@ THE SOFTWARE. #define __CCARMATUREDEFINE_H__ -#include "cocos2d.h" - #define VERSION_COMBINED 0.30f #define VERSION_CHANGE_ROTATION_RANGE 1.0f #define VERSION_COLOR_READING 1.1f diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index 45dcade7d6..634630ec64 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -26,8 +26,11 @@ THE SOFTWARE. #include "cocostudio/CCArmatureDefine.h" #include "cocostudio/CCArmature.h" #include "cocostudio/CCSkin.h" -#include "CCRenderer.h" -#include "CCGroupCommand.h" + +#include "renderer/CCRenderer.h" +#include "renderer/CCGroupCommand.h" +#include "CCShaderCache.h" +#include "CCDirector.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/CCBatchNode.h b/cocos/editor-support/cocostudio/CCBatchNode.h index 1de8a963a2..f0ce41df2f 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.h +++ b/cocos/editor-support/cocostudio/CCBatchNode.h @@ -25,6 +25,7 @@ THE SOFTWARE. #ifndef __CCBATCHNODE_H__ #define __CCBATCHNODE_H__ +#include "CCNode.h" #include "cocostudio/CCArmatureDefine.h" namespace cocos2d { diff --git a/cocos/editor-support/cocostudio/CCComBase.h b/cocos/editor-support/cocostudio/CCComBase.h index 59dfccbe7f..2f32d20045 100644 --- a/cocos/editor-support/cocostudio/CCComBase.h +++ b/cocos/editor-support/cocostudio/CCComBase.h @@ -25,7 +25,6 @@ THE SOFTWARE. #ifndef __CC_EXTENTIONS_CCCOMBASE_H__ #define __CC_EXTENTIONS_CCCOMBASE_H__ -#include "cocos2d.h" #include "ObjectFactory.h" #include "DictionaryHelper.h" #include diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index 452f25d9b8..13ceb9db6d 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -22,7 +22,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +#include "platform/CCFileUtils.h" +#include "CCDirector.h" +#include "CCScheduler.h" + #include "tinyxml2.h" + #include "cocostudio/CCDataReaderHelper.h" #include "cocostudio/CCArmatureDataManager.h" #include "cocostudio/CCTransformHelp.h" @@ -288,7 +293,7 @@ void DataReaderHelper::addDataFromFile(const std::string& filePath) std::string str = &filePathStr[startPos]; // Read content from file - std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); + std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); std::string contentStr = FileUtils::getInstance()->getStringFromFile(fullPath); DataInfo dataInfo; @@ -384,7 +389,7 @@ void DataReaderHelper::addDataFromFileAsync(const std::string& imagePath, const size_t startPos = filePathStr.find_last_of("."); std::string str = &filePathStr[startPos]; - std::string fullPath = CCFileUtils::getInstance()->fullPathForFilename(filePath); + std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); // XXX fileContent is being leaked data->fileContent = FileUtils::getInstance()->getStringFromFile(fullPath); @@ -461,7 +466,7 @@ void DataReaderHelper::addDataAsyncCallBack(float dt) if (0 == _asyncRefCount) { _asyncRefTotalCount = 0; - CCDirector::getInstance()->getScheduler()->unscheduleSelector(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this); + Director::getInstance()->getScheduler()->unscheduleSelector(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this); } } } diff --git a/cocos/editor-support/cocostudio/CCDatas.h b/cocos/editor-support/cocostudio/CCDatas.h index 42ac9ae2f6..6ee2adbcf6 100644 --- a/cocos/editor-support/cocostudio/CCDatas.h +++ b/cocos/editor-support/cocostudio/CCDatas.h @@ -25,6 +25,12 @@ THE SOFTWARE. #ifndef __CCARMATURE_DATAS_H__ #define __CCARMATURE_DATAS_H__ +#include "CCObject.h" +#include "ccTypes.h" +#include "CCVector.h" +#include "CCMap.h" +#include "CCAffineTransform.h" +#include "CCNode.h" #include "cocostudio/CCArmatureDefine.h" #include "cocostudio/CCTweenFunction.h" diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp index 7463ff54ff..72428edfff 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp @@ -30,6 +30,8 @@ THE SOFTWARE. #include "cocostudio/CCArmatureDataManager.h" #include "cocostudio/CCTransformHelp.h" +#include "CCParticleSystemQuad.h" + using namespace cocos2d; namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index c2ce242a47..ca07edaae7 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -28,6 +28,8 @@ THE SOFTWARE. #include "cocostudio/CCUtilMath.h" #include "cocostudio/CCSkin.h" +#include "CCParticleSystemQuad.h" + using namespace cocos2d; namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCInputDelegate.cpp b/cocos/editor-support/cocostudio/CCInputDelegate.cpp index 3f3d94745e..14e5f4b6f5 100644 --- a/cocos/editor-support/cocostudio/CCInputDelegate.cpp +++ b/cocos/editor-support/cocostudio/CCInputDelegate.cpp @@ -23,6 +23,11 @@ THE SOFTWARE. ****************************************************************************/ #include "cocostudio/CCInputDelegate.h" +#include "CCDirector.h" +#include "CCDevice.h" +#include "CCEventListenerTouch.h" +#include "CCEventListenerAcceleration.h" +#include "CCEventListenerKeyboard.h" using namespace cocos2d; diff --git a/cocos/editor-support/cocostudio/CCInputDelegate.h b/cocos/editor-support/cocostudio/CCInputDelegate.h index 81cd4c9218..9341179bf8 100644 --- a/cocos/editor-support/cocostudio/CCInputDelegate.h +++ b/cocos/editor-support/cocostudio/CCInputDelegate.h @@ -25,7 +25,12 @@ THE SOFTWARE. #ifndef __CC_EXTENTIONS_CCINPUTDELEGATE_H__ #define __CC_EXTENTIONS_CCINPUTDELEGATE_H__ -#include "cocos2d.h" +#include "CCPlatformMacros.h" +#include "CCTouch.h" +#include "CCEvent.h" +#include "ccTypes.h" +#include "CCEventKeyboard.h" +#include "CCEventListener.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.h b/cocos/editor-support/cocostudio/CCSSceneReader.h index 6b72b82574..19ca837c6a 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.h +++ b/cocos/editor-support/cocostudio/CCSSceneReader.h @@ -25,7 +25,6 @@ THE SOFTWARE. #ifndef __CCSSCENEREADER_H__ #define __CCSSCENEREADER_H__ -#include "cocos2d.h" #include "cocostudio/DictionaryHelper.h" diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index d26199c205..da98e5a736 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -22,11 +22,17 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +#include "CCSpriteFrame.h" +#include "CCSpriteFrameCache.h" +#include "CCDirector.h" +#include "renderer/CCRenderer.h" + #include "cocostudio/CCSkin.h" #include "cocostudio/CCTransformHelp.h" #include "cocostudio/CCSpriteFrameCacheHelper.h" #include "cocostudio/CCArmature.h" + using namespace cocos2d; namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCSkin.h b/cocos/editor-support/cocostudio/CCSkin.h index e0f255e70d..4798b2345b 100644 --- a/cocos/editor-support/cocostudio/CCSkin.h +++ b/cocos/editor-support/cocostudio/CCSkin.h @@ -25,9 +25,11 @@ THE SOFTWARE. #ifndef __CCSKIN_H__ #define __CCSKIN_H__ +#include "CCSprite.h" +#include "renderer/CCQuadCommand.h" + #include "cocostudio/CCArmatureDefine.h" #include "cocostudio/CCBone.h" -#include "renderer/CCQuadCommand.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp index c5399ba479..1c226668db 100644 --- a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp +++ b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.cpp @@ -24,6 +24,8 @@ THE SOFTWARE. #include "cocostudio/CCSpriteFrameCacheHelper.h" +#include "CCSpriteFrameCache.h" + using namespace cocos2d; @@ -49,7 +51,7 @@ void SpriteFrameCacheHelper::purge() void SpriteFrameCacheHelper::addSpriteFrameFromFile(const std::string& plistPath, const std::string& imagePath) { - CCSpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistPath, imagePath); + SpriteFrameCache::getInstance()->addSpriteFramesWithFile(plistPath, imagePath); } SpriteFrameCacheHelper::SpriteFrameCacheHelper() diff --git a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h index 75797c1aa2..d60154f901 100644 --- a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h +++ b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h @@ -24,6 +24,7 @@ THE SOFTWARE. #ifndef __CCSPRITEFRAMECACHEHELPER_H__ #define __CCSPRITEFRAMECACHEHELPER_H__ +#include "CCPlatformMacros.h" #include "cocostudio/CCArmatureDefine.h" #include diff --git a/cocos/editor-support/cocostudio/CCUtilMath.h b/cocos/editor-support/cocostudio/CCUtilMath.h index b10690d620..cc27ccae86 100644 --- a/cocos/editor-support/cocostudio/CCUtilMath.h +++ b/cocos/editor-support/cocostudio/CCUtilMath.h @@ -25,6 +25,7 @@ THE SOFTWARE. #ifndef __CCUTILMATH_H__ #define __CCUTILMATH_H__ +#include "CCSprite.h" #include "cocostudio/CCArmatureDefine.h" #include diff --git a/cocos/editor-support/cocostudio/DictionaryHelper.cpp b/cocos/editor-support/cocostudio/DictionaryHelper.cpp index 0c46694e7b..436c345d0c 100644 --- a/cocos/editor-support/cocostudio/DictionaryHelper.cpp +++ b/cocos/editor-support/cocostudio/DictionaryHelper.cpp @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +#include "CCPlatformMacros.h" #include "cocostudio/DictionaryHelper.h" namespace cocostudio { diff --git a/cocos/editor-support/cocostudio/DictionaryHelper.h b/cocos/editor-support/cocostudio/DictionaryHelper.h index 58f58455f5..cefb9610ff 100644 --- a/cocos/editor-support/cocostudio/DictionaryHelper.h +++ b/cocos/editor-support/cocostudio/DictionaryHelper.h @@ -25,7 +25,6 @@ THE SOFTWARE. #ifndef __DICTIONARYHELPER_H__ #define __DICTIONARYHELPER_H__ -#include "cocos2d.h" #include "json/document.h" #define DICTOOL DictionaryHelper::getInstance() diff --git a/cocos/editor-support/spine/CCSkeleton.h b/cocos/editor-support/spine/CCSkeleton.h index f1cffffea6..a2460ca690 100644 --- a/cocos/editor-support/spine/CCSkeleton.h +++ b/cocos/editor-support/spine/CCSkeleton.h @@ -35,7 +35,11 @@ #define SPINE_CCSKELETON_H_ #include -#include "cocos2d.h" + +#include "CCNode.h" +#include "CCProtocols.h" +#include "CCTextureAtlas.h" +#include "renderer/CCCustomCommand.h" namespace spine { diff --git a/cocos/editor-support/spine/CCSkeletonAnimation.h b/cocos/editor-support/spine/CCSkeletonAnimation.h index 228a07b88e..3c09ee28c3 100644 --- a/cocos/editor-support/spine/CCSkeletonAnimation.h +++ b/cocos/editor-support/spine/CCSkeletonAnimation.h @@ -36,7 +36,6 @@ #include #include -#include "cocos2d.h" namespace spine { diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp index e4c9c1f66f..38c73c5a65 100644 --- a/cocos/gui/UILayout.cpp +++ b/cocos/gui/UILayout.cpp @@ -30,9 +30,9 @@ THE SOFTWARE. #include "CCShaderCache.h" #include "CCDirector.h" #include "CCDrawingPrimitives.h" -#include "CCRenderer.h" -#include "CCGroupCommand.h" -#include "CCCustomCommand.h" +#include "renderer/CCRenderer.h" +#include "renderer/CCGroupCommand.h" +#include "renderer/CCCustomCommand.h" NS_CC_BEGIN diff --git a/cocos/network/HttpClient.cpp b/cocos/network/HttpClient.cpp index cc19b72524..0e833ef6e0 100644 --- a/cocos/network/HttpClient.cpp +++ b/cocos/network/HttpClient.cpp @@ -25,10 +25,15 @@ ****************************************************************************/ #include "HttpClient.h" + #include #include #include +#include "CCVector.h" +#include "CCDirector.h" +#include "CCScheduler.h" + #include "curl/curl.h" #include "platform/CCFileUtils.h" diff --git a/cocos/network/HttpClient.h b/cocos/network/HttpClient.h index 74f498e942..8c57bb2586 100644 --- a/cocos/network/HttpClient.h +++ b/cocos/network/HttpClient.h @@ -27,8 +27,6 @@ #ifndef __CCHTTPREQUEST_H__ #define __CCHTTPREQUEST_H__ -#include "cocos2d.h" - #include "network/HttpRequest.h" #include "network/HttpResponse.h" #include "network/HttpClient.h" diff --git a/cocos/network/HttpRequest.h b/cocos/network/HttpRequest.h index 50d660bca3..8ca5eee84d 100644 --- a/cocos/network/HttpRequest.h +++ b/cocos/network/HttpRequest.h @@ -26,7 +26,8 @@ #ifndef __HTTP_REQUEST_H__ #define __HTTP_REQUEST_H__ -#include "cocos2d.h" +#include "CCPlatformMacros.h" +#include "CCObject.h" NS_CC_BEGIN diff --git a/cocos/network/HttpResponse.h b/cocos/network/HttpResponse.h index 764ddde120..ebad23ec64 100644 --- a/cocos/network/HttpResponse.h +++ b/cocos/network/HttpResponse.h @@ -26,7 +26,6 @@ #ifndef __HTTP_RESPONSE__ #define __HTTP_RESPONSE__ -#include "cocos2d.h" #include "network/HttpRequest.h" NS_CC_BEGIN diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 52ba0f527d..09574a22cc 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -300,29 +300,29 @@ protected: virtual ~PhysicsBody(); protected: - Node* _node; - std::vector _joints; - Vector _shapes; - PhysicsWorld* _world; - PhysicsBodyInfo* _info; - bool _dynamic; - bool _enable; - bool _rotationEnable; - bool _gravityEnable; - bool _massDefault; - bool _momentDefault; - float _mass; - float _area; - float _density; - float _moment; - float _linearDamping; - float _angularDamping; - int _tag; + Node* _node; + std::vector _joints; + Vector _shapes; + PhysicsWorld* _world; + PhysicsBodyInfo* _info; + bool _dynamic; + bool _enable; + bool _rotationEnable; + bool _gravityEnable; + bool _massDefault; + bool _momentDefault; + float _mass; + float _area; + float _density; + float _moment; + float _linearDamping; + float _angularDamping; + int _tag; - int _categoryBitmask; - int _collisionBitmask; - int _contactTestBitmask; - int _group; + int _categoryBitmask; + int _collisionBitmask; + int _contactTestBitmask; + int _group; friend class PhysicsWorld; friend class PhysicsShape; diff --git a/cocos/scripting/lua/bindings/lua_xml_http_request.h b/cocos/scripting/lua/bindings/lua_xml_http_request.h index 8d0ae45394..c76f1ba383 100644 --- a/cocos/scripting/lua/bindings/lua_xml_http_request.h +++ b/cocos/scripting/lua/bindings/lua_xml_http_request.h @@ -32,6 +32,8 @@ extern "C" { } #endif +#include +#include #include "network/HttpClient.h" diff --git a/extensions/GUI/CCControlExtension/CCControl.h b/extensions/GUI/CCControlExtension/CCControl.h index 4e36bbe753..5c1815291f 100644 --- a/extensions/GUI/CCControlExtension/CCControl.h +++ b/extensions/GUI/CCControlExtension/CCControl.h @@ -31,12 +31,11 @@ #define __CCCONTROL_H__ #include "CCControlUtils.h" -#include "cocos2d.h" +#include "CCLayer.h" NS_CC_EXT_BEGIN - class Invocation; /** diff --git a/extensions/GUI/CCControlExtension/CCControlButton.h b/extensions/GUI/CCControlExtension/CCControlButton.h index d4208c0566..35202c6cec 100644 --- a/extensions/GUI/CCControlExtension/CCControlButton.h +++ b/extensions/GUI/CCControlExtension/CCControlButton.h @@ -33,6 +33,7 @@ #include "CCControl.h" #include "CCInvocation.h" #include "CCScale9Sprite.h" +#include "CCMap.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCControlExtension/CCControlPotentiometer.cpp b/extensions/GUI/CCControlExtension/CCControlPotentiometer.cpp index ab3fccdb74..b813750887 100644 --- a/extensions/GUI/CCControlExtension/CCControlPotentiometer.cpp +++ b/extensions/GUI/CCControlExtension/CCControlPotentiometer.cpp @@ -26,7 +26,6 @@ */ #include "CCControlPotentiometer.h" -#include "cocos2d.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCControlExtension/CCControlPotentiometer.h b/extensions/GUI/CCControlExtension/CCControlPotentiometer.h index bebe39b382..74d0219bc9 100644 --- a/extensions/GUI/CCControlExtension/CCControlPotentiometer.h +++ b/extensions/GUI/CCControlExtension/CCControlPotentiometer.h @@ -28,6 +28,7 @@ #define __CCCONTROLPOTENTIOMETER_H__ #include "CCControl.h" +#include "CCProgressTimer.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCControlExtension/CCControlStepper.h b/extensions/GUI/CCControlExtension/CCControlStepper.h index 1741e8c8a8..2376db9c99 100644 --- a/extensions/GUI/CCControlExtension/CCControlStepper.h +++ b/extensions/GUI/CCControlExtension/CCControlStepper.h @@ -29,6 +29,7 @@ #define __CCCONTROLSTEPPER_H__ #include "CCControl.h" +#include "CCLabelTTF.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp index f583398f06..9e18e6c496 100644 --- a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp +++ b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp @@ -26,7 +26,12 @@ */ #include "CCControlSwitch.h" -#include "cocos2d.h" +#include "CCSprite.h" +#include "CCActionTween.h" +#include "CClabelTTF.h" +#include "CCClippingNode.h" +#include "ccShaders.h" +#include "CCRenderTexture.h" NS_CC_EXT_BEGIN // ControlSwitchSprite diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp b/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp index 532c7fcf06..9f1a19e813 100644 --- a/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp +++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.cpp @@ -26,6 +26,9 @@ THE SOFTWARE. ****************************************************************************/ #include "CCScale9Sprite.h" +#include "CCPlatformMacros.h" +#include "CCSprite.h" +#include "CCSpriteFrameCache.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.h b/extensions/GUI/CCControlExtension/CCScale9Sprite.h index 6b91aac717..fbeca870eb 100644 --- a/extensions/GUI/CCControlExtension/CCScale9Sprite.h +++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.h @@ -28,7 +28,10 @@ THE SOFTWARE. #ifndef __CCScale9Sprite_H__ #define __CCScale9Sprite_H__ -#include "cocos2d.h" +#include "CCNode.h" +#include "CCSpriteFrame.h" +#include "CCSpriteBatchNode.h" + #include "../../ExtensionMacros.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCEditBox/CCEditBox.h b/extensions/GUI/CCEditBox/CCEditBox.h index a1aac55d6e..ff6a4149b4 100644 --- a/extensions/GUI/CCEditBox/CCEditBox.h +++ b/extensions/GUI/CCEditBox/CCEditBox.h @@ -26,7 +26,7 @@ #ifndef __CCEDITTEXT_H__ #define __CCEDITTEXT_H__ -#include "cocos2d.h" +#include "CCIMEDelegate.h" #include "extensions/ExtensionMacros.h" #include "../CCControlExtension/CCControlExtensions.h" diff --git a/extensions/GUI/CCEditBox/CCEditBoxImpl.h b/extensions/GUI/CCEditBox/CCEditBoxImpl.h index b01362eff0..7cb6c6ed1c 100644 --- a/extensions/GUI/CCEditBox/CCEditBoxImpl.h +++ b/extensions/GUI/CCEditBox/CCEditBoxImpl.h @@ -26,7 +26,6 @@ #ifndef __CCEditBoxIMPL_H__ #define __CCEditBoxIMPL_H__ -#include "cocos2d.h" #include "extensions/ExtensionMacros.h" #include "CCEditBox.h" diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 05200d32cb..01bfb8ab82 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -24,6 +24,13 @@ ****************************************************************************/ #include "CCScrollView.h" +#include "CCEGLView.h" +#include "CCDevice.h" +#include "CCActionInstant.h" +#include "CCActionInterval.h" +#include "CCActionTween.h" +#include "CCDirector.h" +#include "renderer/CCRenderer.h" #include diff --git a/extensions/GUI/CCScrollView/CCScrollView.h b/extensions/GUI/CCScrollView/CCScrollView.h index c77d74bc13..88fc9b4523 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.h +++ b/extensions/GUI/CCScrollView/CCScrollView.h @@ -26,7 +26,9 @@ #ifndef __CCSCROLLVIEW_H__ #define __CCSCROLLVIEW_H__ -#include "cocos2d.h" +#include "CCLayer.h" +#include "CCEventListenerTouch.h" + #include "extensions/ExtensionMacros.h" NS_CC_EXT_BEGIN diff --git a/extensions/GUI/CCScrollView/CCTableView.cpp b/extensions/GUI/CCScrollView/CCTableView.cpp index ff143f77d5..ad639e4986 100644 --- a/extensions/GUI/CCScrollView/CCTableView.cpp +++ b/extensions/GUI/CCScrollView/CCTableView.cpp @@ -23,7 +23,6 @@ THE SOFTWARE. ****************************************************************************/ -#include "cocos2d.h" #include "CCTableView.h" #include "CCTableViewCell.h" diff --git a/extensions/GUI/CCScrollView/CCTableViewCell.cpp b/extensions/GUI/CCScrollView/CCTableViewCell.cpp index 7df9c478fd..aa1cf70bca 100644 --- a/extensions/GUI/CCScrollView/CCTableViewCell.cpp +++ b/extensions/GUI/CCScrollView/CCTableViewCell.cpp @@ -33,7 +33,7 @@ void TableViewCell::reset() _idx = CC_INVALID_INDEX; } -ssize_t TableViewCell::getIdx() +ssize_t TableViewCell::getIdx() const { return _idx; } diff --git a/extensions/GUI/CCScrollView/CCTableViewCell.h b/extensions/GUI/CCScrollView/CCTableViewCell.h index 33438a0f96..fb0a509df1 100644 --- a/extensions/GUI/CCScrollView/CCTableViewCell.h +++ b/extensions/GUI/CCScrollView/CCTableViewCell.h @@ -26,8 +26,8 @@ #ifndef __CCTABLEVIEWCELL_H__ #define __CCTABLEVIEWCELL_H__ -#include "cocos2d.h" #include "extensions/ExtensionMacros.h" +#include "CCNode.h" NS_CC_EXT_BEGIN @@ -43,7 +43,7 @@ public: /** * The index used internally by SWTableView and its subclasses */ - ssize_t getIdx(); + ssize_t getIdx() const; void setIdx(ssize_t uIdx); /** * Cleans up any resources linked to this cell and resets idx property. diff --git a/extensions/physics-nodes/CCPhysicsDebugNode.h b/extensions/physics-nodes/CCPhysicsDebugNode.h index fe4d167bff..5d4eb2f2f0 100644 --- a/extensions/physics-nodes/CCPhysicsDebugNode.h +++ b/extensions/physics-nodes/CCPhysicsDebugNode.h @@ -23,11 +23,12 @@ #ifndef __PHYSICSNODES_DEBUGNODE_H__ #define __PHYSICSNODES_DEBUGNODE_H__ -#include "cocos2d.h" #include "extensions/ExtensionMacros.h" #if CC_ENABLE_CHIPMUNK_INTEGRATION +#include "CCDrawNode.h" + #include "chipmunk.h" NS_CC_EXT_BEGIN diff --git a/extensions/physics-nodes/CCPhysicsSprite.h b/extensions/physics-nodes/CCPhysicsSprite.h index fcedfca031..e8f9284a98 100644 --- a/extensions/physics-nodes/CCPhysicsSprite.h +++ b/extensions/physics-nodes/CCPhysicsSprite.h @@ -24,7 +24,7 @@ #ifndef __PHYSICSNODES_CCPHYSICSSPRITE_H__ #define __PHYSICSNODES_CCPHYSICSSPRITE_H__ -#include "cocos2d.h" +#include "CCSprite.h" #include "extensions/ExtensionMacros.h" struct cpBody; From cfbceb0e22f7b725d7336d432e66945f2063b772 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 16 Jan 2014 21:49:14 -0800 Subject: [PATCH 148/193] Fixes compilation issues on Linux --- cocos/2d/platform/linux/CCImage.cpp | 2 +- cocos/2d/renderer/CCRenderer.cpp | 10 +++++----- cocos/editor-support/cocostudio/CCDataReaderHelper.h | 1 + .../cocostudio/CCSpriteFrameCacheHelper.h | 1 + cocos/network/HttpClient.cpp | 2 ++ extensions/GUI/CCControlExtension/CCControlSwitch.cpp | 2 +- 6 files changed, 11 insertions(+), 7 deletions(-) diff --git a/cocos/2d/platform/linux/CCImage.cpp b/cocos/2d/platform/linux/CCImage.cpp index 45602638b5..0d53db0c19 100644 --- a/cocos/2d/platform/linux/CCImage.cpp +++ b/cocos/2d/platform/linux/CCImage.cpp @@ -459,7 +459,7 @@ bool Image::initWithString( { bool bRet = false; do - { + { CC_BREAK_IF(! pText); BitmapDC &dc = sharedBitmapDC(); diff --git a/cocos/2d/renderer/CCRenderer.cpp b/cocos/2d/renderer/CCRenderer.cpp index 30495a8aa3..61d0038df6 100644 --- a/cocos/2d/renderer/CCRenderer.cpp +++ b/cocos/2d/renderer/CCRenderer.cpp @@ -338,16 +338,16 @@ void Renderer::convertToWorldCoordiantes(V3F_C4B_T2F_Quad* quads, ssize_t quanti V3F_C4B_T2F_Quad *q = &quads[i]; kmVec3 *vec1 = (kmVec3*)&q->bl.vertices; - kmVec3TransformCoord(vec1, vec1, &modelView); + kmVec3Transform(vec1, vec1, &modelView); kmVec3 *vec2 = (kmVec3*)&q->br.vertices; - kmVec3TransformCoord(vec2, vec2, &modelView); + kmVec3Transform(vec2, vec2, &modelView); kmVec3 *vec3 = (kmVec3*)&q->tr.vertices; - kmVec3TransformCoord(vec3, vec3, &modelView); + kmVec3Transform(vec3, vec3, &modelView); kmVec3 *vec4 = (kmVec3*)&q->tl.vertices; - kmVec3TransformCoord(vec4, vec4, &modelView); + kmVec3Transform(vec4, vec4, &modelView); } } @@ -465,4 +465,4 @@ void Renderer::flush() _lastMaterialID = 0; } -NS_CC_END \ No newline at end of file +NS_CC_END diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.h b/cocos/editor-support/cocostudio/CCDataReaderHelper.h index 03ed25133b..ac580d6385 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.h +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.h @@ -35,6 +35,7 @@ THE SOFTWARE. #include #include #include +#include namespace tinyxml2 { diff --git a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h index d60154f901..452666a67d 100644 --- a/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h +++ b/cocos/editor-support/cocostudio/CCSpriteFrameCacheHelper.h @@ -27,6 +27,7 @@ THE SOFTWARE. #include "CCPlatformMacros.h" #include "cocostudio/CCArmatureDefine.h" #include +#include namespace cocostudio { diff --git a/cocos/network/HttpClient.cpp b/cocos/network/HttpClient.cpp index 0e833ef6e0..771a23c6f8 100644 --- a/cocos/network/HttpClient.cpp +++ b/cocos/network/HttpClient.cpp @@ -28,6 +28,8 @@ #include #include +#include + #include #include "CCVector.h" diff --git a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp index 9e18e6c496..e37c76735f 100644 --- a/extensions/GUI/CCControlExtension/CCControlSwitch.cpp +++ b/extensions/GUI/CCControlExtension/CCControlSwitch.cpp @@ -28,7 +28,7 @@ #include "CCControlSwitch.h" #include "CCSprite.h" #include "CCActionTween.h" -#include "CClabelTTF.h" +#include "CCLabelTTF.h" #include "CCClippingNode.h" #include "ccShaders.h" #include "CCRenderTexture.h" From 1b5b9da102053ca96c15b7c2c1e8d3bfdf417327 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 16 Jan 2014 21:58:14 -0800 Subject: [PATCH 149/193] compiles on Android compiles on Android --- cocos/editor-support/cocostudio/CCInputDelegate.cpp | 2 +- extensions/GUI/CCScrollView/CCScrollView.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCInputDelegate.cpp b/cocos/editor-support/cocostudio/CCInputDelegate.cpp index 14e5f4b6f5..1bafbe42f2 100644 --- a/cocos/editor-support/cocostudio/CCInputDelegate.cpp +++ b/cocos/editor-support/cocostudio/CCInputDelegate.cpp @@ -24,7 +24,7 @@ THE SOFTWARE. #include "cocostudio/CCInputDelegate.h" #include "CCDirector.h" -#include "CCDevice.h" +#include "platform/CCDevice.h" #include "CCEventListenerTouch.h" #include "CCEventListenerAcceleration.h" #include "CCEventListenerKeyboard.h" diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 01bfb8ab82..e1c21ce3a6 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -25,7 +25,7 @@ #include "CCScrollView.h" #include "CCEGLView.h" -#include "CCDevice.h" +#include "platform/CCDevice.h" #include "CCActionInstant.h" #include "CCActionInterval.h" #include "CCActionTween.h" From db4dc28c1a5ba572857d9ddbb63672cef348cce9 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Fri, 17 Jan 2014 14:04:52 +0800 Subject: [PATCH 150/193] close #3678:fix incorrect spacing between characters --- cocos/2d/CCFontAtlas.cpp | 9 +++++---- cocos/2d/CCFontDefinition.cpp | 1 - cocos/2d/CCFontFreeType.cpp | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index 166ec788a9..6327d1cc31 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -130,8 +130,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) Rect tempRect; - FontLetterDefinition tempDef; - tempDef.offsetX = 0; + FontLetterDefinition tempDef; tempDef.anchorX = 0.0f; tempDef.anchorY = 1.0f; @@ -143,7 +142,8 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) tempDef.width = 0; tempDef.height = 0; tempDef.U = 0; - tempDef.V = 0; + tempDef.V = 0; + tempDef.offsetX = 0; tempDef.offsetY = 0; tempDef.textureID = 0; } @@ -152,7 +152,8 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) tempDef.validDefinition = true; tempDef.letteCharUTF16 = utf16String[i]; tempDef.width = tempRect.size.width + _letterPadding; - tempDef.height = _currentPageLineHeight - 1; + tempDef.height = _currentPageLineHeight - 1; + tempDef.offsetX = tempRect.origin.x; tempDef.offsetY = tempRect.origin.y; tempDef.commonLineHeight = _currentPageLineHeight; diff --git a/cocos/2d/CCFontDefinition.cpp b/cocos/2d/CCFontDefinition.cpp index 7fd10d86a1..ebb79f3172 100644 --- a/cocos/2d/CCFontDefinition.cpp +++ b/cocos/2d/CCFontDefinition.cpp @@ -222,7 +222,6 @@ FontAtlas * FontDefinitionTTF::createFontAtlas() if ( item.second.validDefinition ) { FontLetterDefinition tempDefinition = item.second; - tempDefinition.offsetX = 0; tempDefinition.anchorX = 0.0f; tempDefinition.anchorY = 1.0f; retAtlas->addLetterDefinition(tempDefinition); diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index 915a333a48..c503611b71 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -176,7 +176,7 @@ bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect) const return false; // store result in the passed rectangle - outRect.origin.x = 0; + outRect.origin.x = _fontRef->glyph->metrics.horiBearingX >> 6; outRect.origin.y = - (_fontRef->glyph->metrics.horiBearingY >> 6); outRect.size.width = (_fontRef->glyph->metrics.width >> 6); outRect.size.height = (_fontRef->glyph->metrics.height >> 6); @@ -268,7 +268,7 @@ Size * FontFreeType::getAdvancesForTextUTF16(unsigned short *text, int &outNumLe int advance = 0; int kerning = 0; - advance = getAdvanceForChar(text[c]) - getBearingXForChar(text[c]); + advance = getAdvanceForChar(text[c]); if (c < (outNumLetters-1)) kerning = getHorizontalKerningForChars(text[c], text[c+1]); @@ -295,7 +295,7 @@ int FontFreeType::getAdvanceForChar(unsigned short theChar) const return 0; // get to the advance for this glyph - return (static_cast(_fontRef->glyph->advance.x >> 6)); + return (static_cast(_fontRef->glyph->metrics.horiAdvance >> 6)); } int FontFreeType::getBearingXForChar(unsigned short theChar) const From 0c777b0d85c6030f12c9f4cd907f7f38e3111868 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Fri, 17 Jan 2014 06:11:22 +0000 Subject: [PATCH 151/193] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 74cb897b64..f03e84b93a 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 74cb897b64f7325cf969341e9bc2d87fc7fb1bb7 +Subproject commit f03e84b93ae69080e369962ba2e95ea9b2fd91c7 From feec6a1e8a5ce5ebc8bc6f095d0ba83a565d9b37 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Thu, 16 Jan 2014 22:29:25 -0800 Subject: [PATCH 152/193] Adds some Asserts in the renderer Linux still has a bug, but I can't reproduce it all the time. Hoping that these asserts will help me find it --- cocos/2d/CCFontCharMap.h | 9 +++++++-- cocos/2d/renderer/CCRenderCommand.h | 2 +- cocos/2d/renderer/CCRenderer.cpp | 8 ++++++-- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/cocos/2d/CCFontCharMap.h b/cocos/2d/CCFontCharMap.h index 23caaeff22..83352ddb4e 100644 --- a/cocos/2d/CCFontCharMap.h +++ b/cocos/2d/CCFontCharMap.h @@ -43,8 +43,13 @@ public: virtual FontAtlas *createFontAtlas() override; protected: - FontCharMap(Texture2D* texture,int itemWidth, int itemHeight, int startCharMap) : - _texture(texture),_itemWidth(itemWidth),_itemHeight(itemHeight),_mapStartChar(startCharMap),_charRect(0,0,itemWidth,itemHeight){} + FontCharMap(Texture2D* texture,int itemWidth, int itemHeight, int startCharMap) + :_texture(texture) + ,_mapStartChar(startCharMap) + ,_itemWidth(itemWidth) + ,_itemHeight(itemHeight) + ,_charRect(0,0,itemWidth,itemHeight) + {} /** * @js NA * @lua NA diff --git a/cocos/2d/renderer/CCRenderCommand.h b/cocos/2d/renderer/CCRenderCommand.h index 887d717d7e..57fa2e75ce 100644 --- a/cocos/2d/renderer/CCRenderCommand.h +++ b/cocos/2d/renderer/CCRenderCommand.h @@ -40,11 +40,11 @@ public: enum class Type { + UNKNOWN_COMMAND, QUAD_COMMAND, CUSTOM_COMMAND, BATCH_COMMAND, GROUP_COMMAND, - UNKNOWN_COMMAND, }; virtual int64_t generateID() = 0; diff --git a/cocos/2d/renderer/CCRenderer.cpp b/cocos/2d/renderer/CCRenderer.cpp index 61d0038df6..df7d41473a 100644 --- a/cocos/2d/renderer/CCRenderer.cpp +++ b/cocos/2d/renderer/CCRenderer.cpp @@ -177,12 +177,15 @@ void Renderer::mapBuffers() void Renderer::addCommand(RenderCommand* command) { - command->generateID(); - _renderGroups[_commandGroupStack.top()].push_back(command); + int renderQueue =_commandGroupStack.top(); + addCommand(command, renderQueue); } void Renderer::addCommand(RenderCommand* command, int renderQueue) { + CCASSERT(renderQueue >=0, "Invalid render queue"); + CCASSERT(command->getType() != RenderCommand::Type::UNKNOWN_COMMAND, "Invalid Command Type"); + command->generateID(); _renderGroups[renderQueue].push_back(command); } @@ -290,6 +293,7 @@ void Renderer::render() } else { + CCASSERT(true, "Invalid command"); flush(); } } From 38e7f01ee85117e853a6652e2794a973fb051600 Mon Sep 17 00:00:00 2001 From: lm Date: Fri, 17 Jan 2014 17:13:33 +0800 Subject: [PATCH 153/193] decode 'payload' to utf-8 and ignore invalid bytes --- tools/jenkins-scripts/pull-request-builder.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/jenkins-scripts/pull-request-builder.py b/tools/jenkins-scripts/pull-request-builder.py index 0b0733639b..91b54c7f69 100755 --- a/tools/jenkins-scripts/pull-request-builder.py +++ b/tools/jenkins-scripts/pull-request-builder.py @@ -27,6 +27,7 @@ def set_description(desc, url): def main(): #get payload from os env payload_str = os.environ['payload'] + payload_str = payload_str.decode('utf-8','ignore') #parse to json obj payload = json.loads(payload_str) From d485ade977f514550c5c9199c887e5252f2adc60 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Fri, 17 Jan 2014 14:14:30 +0000 Subject: [PATCH 154/193] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index f03e84b93a..53b58840cb 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit f03e84b93ae69080e369962ba2e95ea9b2fd91c7 +Subproject commit 53b58840cb9ad7bf4e8de6c4edb05a6b0d4ef19a From 85539e75488e938c200a3b63c54b23b88466eb59 Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Fri, 17 Jan 2014 22:20:21 +0800 Subject: [PATCH 155/193] =?UTF-8?q?issue=20#3626:Add=20the=20=E2=80=9Cover?= =?UTF-8?q?ride=20=E2=80=9C=20keyword?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/scripting/lua/bindings/LuaOpengl.h | 2 +- cocos/scripting/lua/bindings/Lua_web_socket.h | 8 +++--- .../lua_cocos2dx_extension_manual.cpp | 28 +++++++++---------- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/cocos/scripting/lua/bindings/LuaOpengl.h b/cocos/scripting/lua/bindings/LuaOpengl.h index d4691677ae..9e04ea1322 100644 --- a/cocos/scripting/lua/bindings/LuaOpengl.h +++ b/cocos/scripting/lua/bindings/LuaOpengl.h @@ -36,7 +36,7 @@ extern "C" { class GLNode:public cocos2d::Node { - virtual void draw(); + virtual void draw() override; }; TOLUA_API int tolua_opengl_open(lua_State* tolua_S); diff --git a/cocos/scripting/lua/bindings/Lua_web_socket.h b/cocos/scripting/lua/bindings/Lua_web_socket.h index 5431209d12..d2463af3c2 100644 --- a/cocos/scripting/lua/bindings/Lua_web_socket.h +++ b/cocos/scripting/lua/bindings/Lua_web_socket.h @@ -39,10 +39,10 @@ class LuaWebSocket: public cocos2d::network::WebSocket,public cocos2d::network:: { public: virtual ~LuaWebSocket(); - virtual void onOpen(WebSocket* ws); - virtual void onMessage(WebSocket* ws, const WebSocket::Data& data); - virtual void onClose(WebSocket* ws); - virtual void onError(WebSocket* ws, const WebSocket::ErrorCode& error); + virtual void onOpen(WebSocket* ws) override; + virtual void onMessage(WebSocket* ws, const WebSocket::Data& data) override; + virtual void onClose(WebSocket* ws) override; + virtual void onError(WebSocket* ws, const WebSocket::ErrorCode& error) override; enum WebSocketScriptHandlerType { diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp index f57d7024e1..739abb548c 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_extension_manual.cpp @@ -48,7 +48,7 @@ public: virtual ~LuaScrollViewDelegate() {} - virtual void scrollViewDidScroll(ScrollView* view) + virtual void scrollViewDidScroll(ScrollView* view) override { if (nullptr != view) { @@ -63,7 +63,7 @@ public: } } - virtual void scrollViewDidZoom(ScrollView* view) + virtual void scrollViewDidZoom(ScrollView* view) override { if (nullptr != view) { @@ -889,7 +889,7 @@ public: virtual ~LuaAssetsManagerDelegateProtocol() {} - virtual void onProgress(int percent) + virtual void onProgress(int percent) override { int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this, ScriptHandlerMgr::HandlerType::ASSETSMANAGER_PROGRESS); if (0 != handler) @@ -900,7 +900,7 @@ public: } } - virtual void onSuccess() + virtual void onSuccess() override { int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this, ScriptHandlerMgr::HandlerType::ASSETSMANAGER_SUCCESS); if (0 != handler) @@ -911,7 +911,7 @@ public: } } - virtual void onError(AssetsManager::ErrorCode errorCode) + virtual void onError(AssetsManager::ErrorCode errorCode) override { int handler = ScriptHandlerMgr::getInstance()->getObjectHandler((void*)this, ScriptHandlerMgr::HandlerType::ASSETSMANAGER_ERROR); if (0 != handler) @@ -1008,7 +1008,7 @@ public: virtual ~LUA_TableViewDelegate(){} - virtual void scrollViewDidScroll(ScrollView* view) + virtual void scrollViewDidScroll(ScrollView* view) override { if (nullptr != view) { @@ -1022,7 +1022,7 @@ public: } } - virtual void scrollViewDidZoom(ScrollView* view) + virtual void scrollViewDidZoom(ScrollView* view) override { if (nullptr != view) { @@ -1036,7 +1036,7 @@ public: } } - virtual void tableCellTouched(TableView* table, TableViewCell* cell) + virtual void tableCellTouched(TableView* table, TableViewCell* cell) override { if (nullptr != table && nullptr != cell) { @@ -1050,7 +1050,7 @@ public: } } - virtual void tableCellHighlight(TableView* table, TableViewCell* cell) + virtual void tableCellHighlight(TableView* table, TableViewCell* cell) override { if (nullptr != table && nullptr != cell) { @@ -1064,7 +1064,7 @@ public: } } - virtual void tableCellUnhighlight(TableView* table, TableViewCell* cell) + virtual void tableCellUnhighlight(TableView* table, TableViewCell* cell) override { if (nullptr != table && nullptr != cell) { @@ -1078,7 +1078,7 @@ public: } } - virtual void tableCellWillRecycle(TableView* table, TableViewCell* cell) + virtual void tableCellWillRecycle(TableView* table, TableViewCell* cell) override { if (nullptr != table && nullptr != cell) { @@ -1158,7 +1158,7 @@ public: LUA_TableViewDataSource(){} virtual ~LUA_TableViewDataSource(){} - virtual Size tableCellSizeForIndex(TableView *table, ssize_t idx) + virtual Size tableCellSizeForIndex(TableView *table, ssize_t idx) override { if (nullptr != table ) { @@ -1185,7 +1185,7 @@ public: return Size::ZERO; } - virtual TableViewCell* tableCellAtIndex(TableView *table, ssize_t idx) + virtual TableViewCell* tableCellAtIndex(TableView *table, ssize_t idx) override { if (nullptr != table ) { @@ -1208,7 +1208,7 @@ public: return NULL; } - virtual ssize_t numberOfCellsInTableView(TableView *table) + virtual ssize_t numberOfCellsInTableView(TableView *table) override { if (nullptr != table ) { From 8931d968c0ea639e055440acd194d9397afc8e60 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 17 Jan 2014 16:08:29 -0800 Subject: [PATCH 156/193] Renderer uses a float as a key Instead of using a 64-bit int key with viewport, opaque and depth, it only uses a 32-bit float with only the depth. Saves time in: - No need to convert the 32-bit float into 24-bit int - keys are shorter --- CHANGELOG | 1 + cocos/2d/CCAtlasNode.cpp | 2 +- cocos/2d/CCClippingNode.cpp | 8 +-- cocos/2d/CCDrawNode.cpp | 2 +- cocos/2d/CCLabel.cpp | 2 +- cocos/2d/CCLayer.cpp | 2 +- cocos/2d/CCMotionStreak.cpp | 2 +- cocos/2d/CCNodeGrid.cpp | 6 +- cocos/2d/CCParticleBatchNode.cpp | 2 +- cocos/2d/CCParticleSystemQuad.cpp | 2 +- cocos/2d/CCProgressTimer.cpp | 2 +- cocos/2d/CCRenderTexture.cpp | 12 ++-- cocos/2d/CCSprite.cpp | 2 +- cocos/2d/CCSpriteBatchNode.cpp | 2 +- cocos/2d/CCTransitionPageTurn.cpp | 8 +-- cocos/2d/renderer/CCBatchCommand.cpp | 60 +------------------ cocos/2d/renderer/CCBatchCommand.h | 15 +---- cocos/2d/renderer/CCCustomCommand.cpp | 16 +---- cocos/2d/renderer/CCCustomCommand.h | 11 +--- cocos/2d/renderer/CCGroupCommand.cpp | 16 +---- cocos/2d/renderer/CCGroupCommand.h | 11 +--- cocos/2d/renderer/CCQuadCommand.cpp | 26 +++----- cocos/2d/renderer/CCQuadCommand.h | 16 +---- cocos/2d/renderer/CCRenderCommand.cpp | 8 +-- cocos/2d/renderer/CCRenderCommand.h | 14 +++-- cocos/2d/renderer/CCRenderer.cpp | 4 +- .../editor-support/cocostudio/CCBatchNode.cpp | 2 +- cocos/editor-support/cocostudio/CCSkin.cpp | 2 +- cocos/editor-support/spine/CCSkeleton.cpp | 2 +- cocos/gui/UILayout.cpp | 12 ++-- extensions/GUI/CCScrollView/CCScrollView.cpp | 4 +- .../Classes/ActionsTest/ActionsTest.cpp | 10 ++-- .../Classes/Box2DTestBed/Box2dView.cpp | 2 +- .../ClippingNodeTest/ClippingNodeTest.cpp | 8 +-- .../DrawPrimitivesTest/DrawPrimitivesTest.cpp | 2 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 4 +- .../TestCpp/Classes/LabelTest/LabelTest.cpp | 6 +- .../Classes/LabelTest/LabelTestNew.cpp | 4 +- .../Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp | 2 +- .../RenderTextureTest/RenderTextureTest.cpp | 10 ++-- .../TestCpp/Classes/ShaderTest/ShaderTest.cpp | 4 +- .../Classes/ShaderTest/ShaderTest2.cpp | 2 +- .../Classes/Texture2dTest/Texture2dTest.cpp | 4 +- .../Classes/TileMapTest/TileMapTest.cpp | 6 +- 44 files changed, 100 insertions(+), 238 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index c4a8ea7282..5f24006cb3 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -19,6 +19,7 @@ cocos2d-x-3.0final ?.? ? [FIX] Renderer: QuadCommand::init() does not copy the Quads, it only store a reference making the code faster [FIX] Renderer: Performance improved in Sprite and SpriteBatchNode (and subclasses) sprites in about 20% [FIX] Renderer: When note using VAO, call glBufferData() instead of glBufferSubData(). + [FIX] Renderer: Uses a float as key with only the depth. Viewport, opaque are not needed now [FIX] Sprite: removed _hasChildren optimization. It uses !_children.empty() now which is super fast as well [FIX] Tests: TestCpp works with CMake on Windows. [FIX] Tests: Sprites Performance Test has 4 new tests diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index f86c143d78..03eb16ba18 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -152,7 +152,7 @@ void AtlasNode::draw(void) auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); - _quadCommand.init(0, + _quadCommand.init( _vertexZ, _textureAtlas->getTexture()->getName(), shader, diff --git a/cocos/2d/CCClippingNode.cpp b/cocos/2d/CCClippingNode.cpp index f5bc3bf95d..55be0ef5a8 100644 --- a/cocos/2d/CCClippingNode.cpp +++ b/cocos/2d/CCClippingNode.cpp @@ -210,12 +210,12 @@ void ClippingNode::visit() Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand.init(0,_vertexZ); + _groupCommand.init(_vertexZ); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); - _beforeVisitCmd.init(0,_vertexZ); + _beforeVisitCmd.init(_vertexZ); _beforeVisitCmd.func = CC_CALLBACK_0(ClippingNode::onBeforeVisit, this); renderer->addCommand(&_beforeVisitCmd); if (_alphaThreshold < 1) @@ -238,7 +238,7 @@ void ClippingNode::visit() } _stencil->visit(); - _afterDrawStencilCmd.init(0,_vertexZ); + _afterDrawStencilCmd.init(_vertexZ); _afterDrawStencilCmd.func = CC_CALLBACK_0(ClippingNode::onAfterDrawStencil, this); renderer->addCommand(&_afterDrawStencilCmd); @@ -268,7 +268,7 @@ void ClippingNode::visit() this->draw(); } - _afterVisitCmd.init(0,_vertexZ); + _afterVisitCmd.init(_vertexZ); _afterVisitCmd.func = CC_CALLBACK_0(ClippingNode::onAfterVisit, this); renderer->addCommand(&_afterVisitCmd); diff --git a/cocos/2d/CCDrawNode.cpp b/cocos/2d/CCDrawNode.cpp index 3432ad024f..0e28ee554f 100644 --- a/cocos/2d/CCDrawNode.cpp +++ b/cocos/2d/CCDrawNode.cpp @@ -241,7 +241,7 @@ void DrawNode::render() void DrawNode::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(DrawNode::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 52f817ef7c..c96678fc57 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -666,7 +666,7 @@ void Label::onDraw() void Label::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(Label::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index 1b24c97f25..83629a50ec 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -565,7 +565,7 @@ void LayerColor::updateColor() void LayerColor::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(LayerColor::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/cocos/2d/CCMotionStreak.cpp b/cocos/2d/CCMotionStreak.cpp index fdb0b70fb8..2dc1f49fbb 100644 --- a/cocos/2d/CCMotionStreak.cpp +++ b/cocos/2d/CCMotionStreak.cpp @@ -359,7 +359,7 @@ void MotionStreak::draw() if(_nuPoints <= 1) return; kmGLGetMatrix(KM_GL_MODELVIEW,&_cachedMV); - _customCommand.init(0,_vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(MotionStreak::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/cocos/2d/CCNodeGrid.cpp b/cocos/2d/CCNodeGrid.cpp index 9c24500da0..9f359cf778 100644 --- a/cocos/2d/CCNodeGrid.cpp +++ b/cocos/2d/CCNodeGrid.cpp @@ -92,7 +92,7 @@ void NodeGrid::visit() Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand.init(0,_vertexZ); + _groupCommand.init(_vertexZ); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); @@ -104,7 +104,7 @@ void NodeGrid::visit() _nodeGrid->set2DProjection(); } - _gridBeginCommand.init(0,_vertexZ); + _gridBeginCommand.init(_vertexZ); _gridBeginCommand.func = CC_CALLBACK_0(NodeGrid::onGridBeginDraw, this); renderer->addCommand(&_gridBeginCommand); @@ -152,7 +152,7 @@ void NodeGrid::visit() director->setProjection(beforeProjectionType); } - _gridEndCommand.init(0,_vertexZ); + _gridEndCommand.init(_vertexZ); _gridEndCommand.func = CC_CALLBACK_0(NodeGrid::onGridEndDraw, this); renderer->addCommand(&_gridEndCommand); diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index b291910422..d64d682ce3 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -382,7 +382,7 @@ void ParticleBatchNode::draw(void) return; } - _batchCommand.init(0, + _batchCommand.init( _vertexZ, _textureAtlas->getTexture()->getName(), _shaderProgram, diff --git a/cocos/2d/CCParticleSystemQuad.cpp b/cocos/2d/CCParticleSystemQuad.cpp index 8495483116..cf3725e1a2 100644 --- a/cocos/2d/CCParticleSystemQuad.cpp +++ b/cocos/2d/CCParticleSystemQuad.cpp @@ -439,7 +439,7 @@ void ParticleSystemQuad::draw() auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); - _quadCommand.init(0, _vertexZ, _texture->getName(), shader, _blendFunc, _quads, _particleIdx, _modelViewTransform); + _quadCommand.init(_vertexZ, _texture->getName(), shader, _blendFunc, _quads, _particleIdx, _modelViewTransform); Director::getInstance()->getRenderer()->addCommand(&_quadCommand); } diff --git a/cocos/2d/CCProgressTimer.cpp b/cocos/2d/CCProgressTimer.cpp index 37c754a0ee..b8332e0442 100644 --- a/cocos/2d/CCProgressTimer.cpp +++ b/cocos/2d/CCProgressTimer.cpp @@ -555,7 +555,7 @@ void ProgressTimer::draw() if( ! _vertexData || ! _sprite) return; - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(ProgressTimer::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index fcf00452ed..63bc1a596d 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -322,7 +322,7 @@ void RenderTexture::beginWithClear(float r, float g, float b, float a, float dep this->begin(); //clear screen - _beginWithClearCommand.init(0, _vertexZ); + _beginWithClearCommand.init(_vertexZ); _beginWithClearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this); Director::getInstance()->getRenderer()->addCommand(&_beginWithClearCommand); } @@ -340,7 +340,7 @@ void RenderTexture::clearDepth(float depthValue) this->begin(); - _clearDepthCommand.init(0, _vertexZ); + _clearDepthCommand.init(_vertexZ); _clearDepthCommand.func = CC_CALLBACK_0(RenderTexture::onClearDepth, this); Director::getInstance()->getRenderer()->addCommand(&_clearDepthCommand); @@ -605,7 +605,7 @@ void RenderTexture::draw() begin(); //clear screen - _clearCommand.init(0, _vertexZ); + _clearCommand.init(_vertexZ); _clearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this); Director::getInstance()->getRenderer()->addCommand(&_clearCommand); @@ -648,13 +648,13 @@ void RenderTexture::begin() (float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1,1 ); kmGLMultMatrix(&orthoMatrix); - _groupCommand.init(0, _vertexZ); + _groupCommand.init(_vertexZ); Renderer *renderer = Director::getInstance()->getRenderer(); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); - _beginCommand.init(0, _vertexZ); + _beginCommand.init(_vertexZ); _beginCommand.func = CC_CALLBACK_0(RenderTexture::onBegin, this); Director::getInstance()->getRenderer()->addCommand(&_beginCommand); @@ -662,7 +662,7 @@ void RenderTexture::begin() void RenderTexture::end() { - _endCommand.init(0, _vertexZ); + _endCommand.init(_vertexZ); _endCommand.func = CC_CALLBACK_0(RenderTexture::onEnd, this); Renderer *renderer = Director::getInstance()->getRenderer(); diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index c66c811b1b..fafb509a6b 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -670,7 +670,7 @@ void Sprite::updateTransform(void) void Sprite::draw(void) { //TODO implement z order - _quadCommand.init(0, _vertexZ, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, _modelViewTransform); + _quadCommand.init(_vertexZ, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, _modelViewTransform); // if(culling()) { diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index fde85639aa..6237f92b19 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -356,7 +356,7 @@ void SpriteBatchNode::draw() for(const auto &child: _children) child->updateTransform(); - _batchCommand.init(0, + _batchCommand.init( _vertexZ, _textureAtlas->getTexture()->getName(), _shaderProgram, diff --git a/cocos/2d/CCTransitionPageTurn.cpp b/cocos/2d/CCTransitionPageTurn.cpp index 7ade9878a4..c42bf6e9d2 100644 --- a/cocos/2d/CCTransitionPageTurn.cpp +++ b/cocos/2d/CCTransitionPageTurn.cpp @@ -98,23 +98,23 @@ void TransitionPageTurn::draw() if( _isInSceneOnTop ) { _outSceneProxy->visit(); - _enableOffsetCmd.init(0, _vertexZ); + _enableOffsetCmd.init(_vertexZ); _enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd); _inSceneProxy->visit(); - _disableOffsetCmd.init(0, _vertexZ); + _disableOffsetCmd.init(_vertexZ); _disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd); } else { _inSceneProxy->visit(); - _enableOffsetCmd.init(0, _vertexZ); + _enableOffsetCmd.init(_vertexZ); _enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd); _outSceneProxy->visit(); - _disableOffsetCmd.init(0, _vertexZ); + _disableOffsetCmd.init(_vertexZ); _disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd); } diff --git a/cocos/2d/renderer/CCBatchCommand.cpp b/cocos/2d/renderer/CCBatchCommand.cpp index de3fc511cd..817cfb421c 100644 --- a/cocos/2d/renderer/CCBatchCommand.cpp +++ b/cocos/2d/renderer/CCBatchCommand.cpp @@ -30,9 +30,7 @@ NS_CC_BEGIN BatchCommand::BatchCommand() -: _viewport(0) -, _depth(0) -, _textureID(0) +: _textureID(0) , _blendType(BlendFunc::DISABLE) , _textureAtlas(nullptr) { @@ -40,9 +38,8 @@ BatchCommand::BatchCommand() _shader = nullptr; } -void BatchCommand::init(int viewport, int32_t depth, GLuint textureID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform) +void BatchCommand::init(float depth, GLuint textureID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform) { - _viewport = viewport; _depth = depth; _textureID = textureID; _blendType = blendType; @@ -57,59 +54,6 @@ BatchCommand::~BatchCommand() { } -int64_t BatchCommand::generateID() -{ - _id = 0; - - //Generate Material ID - //TODO fix shader ID generation - CCASSERT(_shader->getProgram() < pow(2,10), "ShaderID is greater than 2^10"); - //TODO fix texture ID generation - CCASSERT(_textureID < pow(2,18), "TextureID is greater than 2^18"); - - //TODO fix blend id generation - int blendID = 0; - if(_blendType == BlendFunc::DISABLE) - { - blendID = 0; - } - else if(_blendType == BlendFunc::ALPHA_PREMULTIPLIED) - { - blendID = 1; - } - else if(_blendType == BlendFunc::ALPHA_NON_PREMULTIPLIED) - { - blendID = 2; - } - else if(_blendType == BlendFunc::ADDITIVE) - { - blendID = 3; - } - else - { - blendID = 4; - } - - //TODO Material ID should be part of the ID - // - // Temporal hack (later, these 32-bits should be packed in 24-bits - // - // +---------------------+-------------------+----------------------+ - // | Shader ID (10 bits) | Blend ID (4 bits) | Texture ID (18 bits) | - // +---------------------+-------------------+----------------------+ - - _materialID = (int32_t)_shader->getProgram() << 22 - | (int32_t)blendID << 18 - | (int32_t)_textureID << 0; - - //Generate RenderCommandID - _id = (int64_t)_viewport << 61 - | (int64_t)1 << 60 //translucent - | (int64_t)_depth << 36; - - return _id; -} - void BatchCommand::execute() { // Set material diff --git a/cocos/2d/renderer/CCBatchCommand.h b/cocos/2d/renderer/CCBatchCommand.h index d3b2a5245e..9ac5b346ee 100644 --- a/cocos/2d/renderer/CCBatchCommand.h +++ b/cocos/2d/renderer/CCBatchCommand.h @@ -43,26 +43,13 @@ public: BatchCommand(); ~BatchCommand(); - void init(int viewport, int32_t depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform); - - // +----------+----------+-----+-----------------------------------+ - // | | | | | | - // | ViewPort | Transluc | | Depth | Material ID | - // | 3 bits | 1 bit | | 24 bits | 24 bit2 | - // +----------+----------+-----+----------------+------------------+ - virtual int64_t generateID(); + void init(float depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform); void execute(); protected: int32_t _materialID; - //Key Data - int _viewport; /// Which view port it belongs to - - //TODO use material to determine if it's translucent - int32_t _depth; - //Maternal GLuint _textureID; diff --git a/cocos/2d/renderer/CCCustomCommand.cpp b/cocos/2d/renderer/CCCustomCommand.cpp index 5bbf2032ea..10992393f7 100644 --- a/cocos/2d/renderer/CCCustomCommand.cpp +++ b/cocos/2d/renderer/CCCustomCommand.cpp @@ -28,15 +28,12 @@ NS_CC_BEGIN CustomCommand::CustomCommand() : func(nullptr) -, _viewport(0) -, _depth(0) { _type = RenderCommand::Type::CUSTOM_COMMAND; } -void CustomCommand::init(int viewport, int32_t depth) +void CustomCommand::init(float depth) { - _viewport = viewport; _depth = depth; } @@ -45,17 +42,6 @@ CustomCommand::~CustomCommand() } -int64_t CustomCommand::generateID() -{ - _id = 0; - - _id = (int64_t)_viewport << 61 - | (int64_t)1 << 60 // translucent - | (int64_t)_depth << 36; - - return _id; -} - void CustomCommand::execute() { if(func) diff --git a/cocos/2d/renderer/CCCustomCommand.h b/cocos/2d/renderer/CCCustomCommand.h index 7ff4c3e3ca..03fdead69a 100644 --- a/cocos/2d/renderer/CCCustomCommand.h +++ b/cocos/2d/renderer/CCCustomCommand.h @@ -39,14 +39,7 @@ public: public: - void init(int viewport, int32_t depth); - - // +----------+----------+-----+-----------------------------------+ - // | | | | | | - // | ViewPort | Transluc | | Depth | | - // | 3 bits | 1 bit | | 24 bits | | - // +----------+----------+-----+----------------+------------------+ - virtual int64_t generateID(); + void init(float depth); void execute(); @@ -54,8 +47,6 @@ public: std::function func; protected: - int _viewport; - int32_t _depth; }; NS_CC_END diff --git a/cocos/2d/renderer/CCGroupCommand.cpp b/cocos/2d/renderer/CCGroupCommand.cpp index 9c0e57eb92..70496b5d1d 100644 --- a/cocos/2d/renderer/CCGroupCommand.cpp +++ b/cocos/2d/renderer/CCGroupCommand.cpp @@ -86,16 +86,13 @@ void GroupCommandManager::releaseGroupID(int groupID) } GroupCommand::GroupCommand() -: _viewport(0) -, _depth(0) { _type = RenderCommand::Type::GROUP_COMMAND; _renderQueueID = GroupCommandManager::getInstance()->getGroupID(); } -void GroupCommand::init(int viewport, int32_t depth) +void GroupCommand::init(float depth) { - _viewport = viewport; _depth = depth; GroupCommandManager::getInstance()->releaseGroupID(_renderQueueID); _renderQueueID = GroupCommandManager::getInstance()->getGroupID(); @@ -106,15 +103,4 @@ GroupCommand::~GroupCommand() GroupCommandManager::getInstance()->releaseGroupID(_renderQueueID); } -int64_t GroupCommand::generateID() -{ - _id = 0; - - _id = (int64_t)_viewport << 61 - | (int64_t)1 << 60 // translucent - | (int64_t)_depth << 36; - - return _id; -} - NS_CC_END diff --git a/cocos/2d/renderer/CCGroupCommand.h b/cocos/2d/renderer/CCGroupCommand.h index 7a6b6e511c..02fe541fd0 100644 --- a/cocos/2d/renderer/CCGroupCommand.h +++ b/cocos/2d/renderer/CCGroupCommand.h @@ -58,21 +58,12 @@ public: public: - void init(int viewport, int32_t depth); - - // +----------+----------+-----+-----------------------------------+ - // | | | | | | - // | ViewPort | Transluc | | Depth | | - // | 3 bits | 1 bit | | 24 bits | | - // +----------+----------+-----+----------------+------------------+ - virtual int64_t generateID() override; + void init(float depth); inline bool isTranslucent() {return true;} inline int getRenderQueueID() {return _renderQueueID;} protected: - int _viewport; - int32_t _depth; int _renderQueueID; }; diff --git a/cocos/2d/renderer/CCQuadCommand.cpp b/cocos/2d/renderer/CCQuadCommand.cpp index a19e3f7053..0d602cee4e 100644 --- a/cocos/2d/renderer/CCQuadCommand.cpp +++ b/cocos/2d/renderer/CCQuadCommand.cpp @@ -29,9 +29,7 @@ NS_CC_BEGIN QuadCommand::QuadCommand() -:_viewport(0) -,_depth(0) -,_textureID(0) +:_textureID(0) ,_blendType(BlendFunc::DISABLE) ,_quadsCount(0) { @@ -40,9 +38,8 @@ QuadCommand::QuadCommand() _quads = nullptr; } -void QuadCommand::init(int viewport, int32_t depth, GLuint textureID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, const kmMat4 &mv) +void QuadCommand::init(float depth, GLuint textureID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, const kmMat4 &mv) { - _viewport = viewport; _depth = depth; _textureID = textureID; _blendType = blendType; @@ -52,16 +49,16 @@ void QuadCommand::init(int viewport, int32_t depth, GLuint textureID, GLProgram* _quads = quad; _mv = mv; + + generateMaterialID(); } QuadCommand::~QuadCommand() { } -int64_t QuadCommand::generateID() +void QuadCommand::generateMaterialID() { - _id = 0; - //Generate Material ID //TODO fix shader ID generation CCASSERT(_shader->getProgram() < pow(2,10), "ShaderID is greater than 2^10"); @@ -99,16 +96,9 @@ int64_t QuadCommand::generateID() // | Shader ID (10 bits) | Blend ID (4 bits) | Texture ID (18 bits) | // +---------------------+-------------------+----------------------+ - _materialID = (int32_t)_shader->getProgram() << 22 - | (int32_t)blendID << 18 - | (int32_t)_textureID << 0; - - //Generate RenderCommandID - _id = (int64_t)_viewport << 61 - | (int64_t)1 << 60 //translucent - | (int64_t)_depth << 36; - - return _id; + _materialID = (uint32_t)_shader->getProgram() << 22 + | (uint32_t)blendID << 18 + | (uint32_t)_textureID << 0; } void QuadCommand::useMaterial() diff --git a/cocos/2d/renderer/CCQuadCommand.h b/cocos/2d/renderer/CCQuadCommand.h index 1837919c8d..e6bb2059b3 100644 --- a/cocos/2d/renderer/CCQuadCommand.h +++ b/cocos/2d/renderer/CCQuadCommand.h @@ -41,21 +41,15 @@ public: QuadCommand(); ~QuadCommand(); - void init(int viewport, int32_t depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quads, ssize_t quadCount, + void init(float depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quads, ssize_t quadCount, const kmMat4& mv); - // +----------+----------+-----+-----------------------------------+ - // | | | | | | - // | ViewPort | Transluc | | Depth | Material ID | - // | 3 bits | 1 bit | | 24 bits | 24 bit2 | - // +----------+----------+-----+----------------+------------------+ - virtual int64_t generateID(); - void useMaterial(); //TODO use material to decide if it is translucent inline bool isTranslucent() const { return true; } + void generateMaterialID(); inline uint32_t getMaterialID() const { return _materialID; } inline GLuint getTextureID() const { return _textureID; } @@ -73,12 +67,6 @@ public: protected: uint32_t _materialID; - //Key Data - int _viewport; /// Which view port it belongs to - - //TODO use material to determine if it's translucent - int32_t _depth; - //Maternal GLuint _textureID; diff --git a/cocos/2d/renderer/CCRenderCommand.cpp b/cocos/2d/renderer/CCRenderCommand.cpp index 71fee4edb0..64157b4739 100644 --- a/cocos/2d/renderer/CCRenderCommand.cpp +++ b/cocos/2d/renderer/CCRenderCommand.cpp @@ -28,9 +28,9 @@ NS_CC_BEGIN RenderCommand::RenderCommand() +: _type(RenderCommand::Type::UNKNOWN_COMMAND) +, _depth(0) { - _id = 0; - _type = RenderCommand::Type::UNKNOWN_COMMAND; } RenderCommand::~RenderCommand() @@ -57,9 +57,7 @@ void printBits(ssize_t const size, void const * const ptr) void RenderCommand::printID() { - printf("CommandID: "); - printBits(sizeof(_id), &_id); - printf("\n"); + printf("Command Depth: %f\n", _depth); } NS_CC_END \ No newline at end of file diff --git a/cocos/2d/renderer/CCRenderCommand.h b/cocos/2d/renderer/CCRenderCommand.h index 57fa2e75ce..9035454bc2 100644 --- a/cocos/2d/renderer/CCRenderCommand.h +++ b/cocos/2d/renderer/CCRenderCommand.h @@ -33,7 +33,9 @@ NS_CC_BEGIN -//TODO make RenderCommand inherent from Object +/** Base class of the RenderCommand hierarchy. + The Renderer knows how to render RenderCommands. + */ class RenderCommand { public: @@ -47,10 +49,8 @@ public: GROUP_COMMAND, }; - virtual int64_t generateID() = 0; - /** Get Render Command Id */ - inline int64_t getID() { return _id; } + inline float getDepth() { return _depth; } /** Returns the Command type */ inline Type getType() { return _type; } @@ -61,9 +61,11 @@ protected: void printID(); - //Generated IDs - int64_t _id; /// used for sorting render commands + // Type used in order to avoid dynamic cast, faster Type _type; + + // commands are sort by depth + float _depth; }; NS_CC_END diff --git a/cocos/2d/renderer/CCRenderer.cpp b/cocos/2d/renderer/CCRenderer.cpp index df7d41473a..5b56fc80cd 100644 --- a/cocos/2d/renderer/CCRenderer.cpp +++ b/cocos/2d/renderer/CCRenderer.cpp @@ -185,8 +185,6 @@ void Renderer::addCommand(RenderCommand* command, int renderQueue) { CCASSERT(renderQueue >=0, "Invalid render queue"); CCASSERT(command->getType() != RenderCommand::Type::UNKNOWN_COMMAND, "Invalid Command Type"); - - command->generateID(); _renderGroups[renderQueue].push_back(command); } @@ -209,7 +207,7 @@ int Renderer::createRenderQueue() bool compareRenderCommand(RenderCommand* a, RenderCommand* b) { - return a->getID() < b->getID(); + return a->getDepth() < b->getDepth(); } void Renderer::render() diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index 634630ec64..20f034c35b 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -156,7 +156,7 @@ void BatchNode::draw() void BatchNode::generateGroupCommand() { Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand->init(0,_vertexZ); + _groupCommand->init(_vertexZ); renderer->addCommand(_groupCommand); renderer->pushGroup(_groupCommand->getRenderQueueID()); diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index da98e5a736..1da40694f7 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -225,7 +225,7 @@ void Skin::draw() kmGLGetMatrix(KM_GL_MODELVIEW, &mv); //TODO implement z order - _quadCommand.init(0, _vertexZ, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, mv); + _quadCommand.init(_vertexZ, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, mv); Director::getInstance()->getRenderer()->addCommand(&_quadCommand); } diff --git a/cocos/editor-support/spine/CCSkeleton.cpp b/cocos/editor-support/spine/CCSkeleton.cpp index 9051679a98..c224e38d4e 100644 --- a/cocos/editor-support/spine/CCSkeleton.cpp +++ b/cocos/editor-support/spine/CCSkeleton.cpp @@ -131,7 +131,7 @@ void Skeleton::draw() kmGLMatrixMode(KM_GL_MODELVIEW); kmGLGetMatrix(KM_GL_MODELVIEW, &_oldTransMatrix); - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(Skeleton::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp index 38c73c5a65..691fb212a2 100644 --- a/cocos/gui/UILayout.cpp +++ b/cocos/gui/UILayout.cpp @@ -210,18 +210,18 @@ void Layout::stencilClippingVisit() Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand.init(0,_vertexZ); + _groupCommand.init(_vertexZ); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); - _beforeVisitCmdStencil.init(0,_vertexZ); + _beforeVisitCmdStencil.init(_vertexZ); _beforeVisitCmdStencil.func = CC_CALLBACK_0(Layout::onBeforeVisitStencil, this); renderer->addCommand(&_beforeVisitCmdStencil); _clippingStencil->visit(); - _afterDrawStencilCmd.init(0,_vertexZ); + _afterDrawStencilCmd.init(_vertexZ); _afterDrawStencilCmd.func = CC_CALLBACK_0(Layout::onAfterDrawStencil, this); renderer->addCommand(&_afterDrawStencilCmd); @@ -251,7 +251,7 @@ void Layout::stencilClippingVisit() this->draw(); } - _afterVisitCmdStencil.init(0,_vertexZ); + _afterVisitCmdStencil.init(_vertexZ); _afterVisitCmdStencil.func = CC_CALLBACK_0(Layout::onAfterVisitStencil, this); renderer->addCommand(&_afterVisitCmdStencil); @@ -336,13 +336,13 @@ void Layout::scissorClippingVisit() { Renderer* renderer = Director::getInstance()->getRenderer(); - _beforeVisitCmdScissor.init(0, _vertexZ); + _beforeVisitCmdScissor.init(_vertexZ); _beforeVisitCmdScissor.func = CC_CALLBACK_0(Layout::onBeforeVisitScissor, this); renderer->addCommand(&_beforeVisitCmdScissor); Node::visit(); - _afterVisitCmdScissor.init(0, _vertexZ); + _afterVisitCmdScissor.init(_vertexZ); _afterVisitCmdScissor.func = CC_CALLBACK_0(Layout::onAfterVisitScissor, this); renderer->addCommand(&_afterVisitCmdScissor); } diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index e1c21ce3a6..bf7e667cc2 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -494,7 +494,7 @@ void ScrollView::addChild(Node * child, int zOrder, int tag) void ScrollView::beforeDraw() { - _beforeDrawCommand.init(0, _vertexZ); + _beforeDrawCommand.init(_vertexZ); _beforeDrawCommand.func = CC_CALLBACK_0(ScrollView::onBeforeDraw, this); Director::getInstance()->getRenderer()->addCommand(&_beforeDrawCommand); } @@ -529,7 +529,7 @@ void ScrollView::onBeforeDraw() void ScrollView::afterDraw() { - _afterDrawCommand.init(0, _vertexZ); + _afterDrawCommand.init(_vertexZ); _afterDrawCommand.func = CC_CALLBACK_0(ScrollView::onAfterDraw, this); Director::getInstance()->getRenderer()->addCommand(&_afterDrawCommand); } diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp index fa40b74f0a..1fea5ffa2a 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp @@ -1314,7 +1314,7 @@ void ActionFollow::onEnter() void ActionFollow::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(ActionFollow::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); @@ -1630,7 +1630,7 @@ void ActionCatmullRomStacked::draw() kmGLPopMatrix(); kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(ActionCatmullRomStacked::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -1745,7 +1745,7 @@ void ActionCardinalSplineStacked::draw() kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); kmGLPopMatrix(); - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(ActionCardinalSplineStacked::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -2107,7 +2107,7 @@ void ActionCatmullRom::draw() kmGLPopMatrix(); kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(ActionCatmullRom::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -2207,7 +2207,7 @@ void ActionCardinalSpline::draw() kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); kmGLPopMatrix(); - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(ActionCardinalSpline::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp index dd8d3f8693..ed1e08da29 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp @@ -211,7 +211,7 @@ void Box2DView::draw() { Layer::draw(); - _customCmd.init(0, _vertexZ); + _customCmd.init(_vertexZ); _customCmd.func = CC_CALLBACK_0(Box2DView::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCmd); } diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp index 68a584d577..b73c205be3 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -611,7 +611,7 @@ void RawStencilBufferTest::draw() auto iter = _renderCmds.begin(); - iter->init(0, _vertexZ); + iter->init(_vertexZ); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onEnableStencil, this); renderer->addCommand(&(*iter)); ++iter; @@ -628,7 +628,7 @@ void RawStencilBufferTest::draw() spritePoint.y = 0; _sprites.at(i)->setPosition( spritePoint ); - iter->init(0, _vertexZ); + iter->init(_vertexZ); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawClip, this, i, stencilPoint); renderer->addCommand(&(*iter)); ++iter; @@ -638,7 +638,7 @@ void RawStencilBufferTest::draw() _sprites.at(i)->visit(); kmGLPopMatrix(); - iter->init(0, _vertexZ); + iter->init(_vertexZ); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawSprite, this, i, winPoint); renderer->addCommand(&(*iter)); ++iter; @@ -649,7 +649,7 @@ void RawStencilBufferTest::draw() kmGLPopMatrix(); } - iter->init(0, _vertexZ); + iter->init(_vertexZ); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onDisableStencil, this); renderer->addCommand(&(*iter)); diff --git a/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp b/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp index 61aa2aa0b2..0e693d640a 100644 --- a/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp +++ b/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp @@ -116,7 +116,7 @@ DrawPrimitivesTest::DrawPrimitivesTest() void DrawPrimitivesTest::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(DrawPrimitivesTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index fdf76c80a0..8e2a0119e4 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -1067,7 +1067,7 @@ void TestColliderDetector::update(float delta) } void TestColliderDetector::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(TestColliderDetector::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -1108,7 +1108,7 @@ std::string TestBoundingBox::title() const } void TestBoundingBox::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(TestBoundingBox::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp index d85049bc94..af89de176c 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp @@ -210,7 +210,7 @@ void Atlas1::draw() // GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY // GL_TEXTURE_2D - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(Atlas1::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); @@ -526,7 +526,7 @@ Atlas4::Atlas4() void Atlas4::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(Atlas4::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -1612,7 +1612,7 @@ std::string LabelBMFontBounds::subtitle() const void LabelBMFontBounds::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(LabelBMFontBounds::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp index 604ff0cb8b..91be90098d 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp @@ -302,7 +302,7 @@ LabelFNTSpriteActions::LabelFNTSpriteActions() void LabelFNTSpriteActions::draw() { - _renderCmd.init(0, _vertexZ); + _renderCmd.init(_vertexZ); _renderCmd.func = CC_CALLBACK_0(LabelFNTSpriteActions::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); @@ -912,7 +912,7 @@ std::string LabelFNTBounds::subtitle() const void LabelFNTBounds::draw() { - _renderCmd.init(0, _vertexZ); + _renderCmd.init(_vertexZ); _renderCmd.func = CC_CALLBACK_0(LabelFNTBounds::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp index 4d69c14542..a0c70d62b5 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp @@ -932,7 +932,7 @@ protected: void MySprite::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(MySprite::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp index 9a18f256be..a90ce6aebc 100644 --- a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp +++ b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp @@ -470,19 +470,19 @@ RenderTextureTestDepthStencil::~RenderTextureTestDepthStencil() void RenderTextureTestDepthStencil::draw() { - _renderCmds[0].init(0, _vertexZ); + _renderCmds[0].init(_vertexZ); _renderCmds[0].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onBeforeClear, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[0]); _rend->beginWithClear(0, 0, 0, 0, 0, 0); - _renderCmds[1].init(0, _vertexZ); + _renderCmds[1].init(_vertexZ); _renderCmds[1].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onBeforeStencil, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[1]); _spriteDS->visit(); - _renderCmds[2].init(0, _vertexZ); + _renderCmds[2].init(_vertexZ); _renderCmds[2].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onBeforDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[2]); @@ -490,7 +490,7 @@ void RenderTextureTestDepthStencil::draw() _rend->end(); - _renderCmds[3].init(0, _vertexZ); + _renderCmds[3].init(_vertexZ); _renderCmds[3].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onAfterDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[3]); @@ -638,7 +638,7 @@ SpriteRenderTextureBug::SimpleSprite* SpriteRenderTextureBug::SimpleSprite::crea void SpriteRenderTextureBug::SimpleSprite::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(SpriteRenderTextureBug::SimpleSprite::onBeforeDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp index ba6c1f01c1..087644545e 100644 --- a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp @@ -193,7 +193,7 @@ void ShaderNode::setPosition(const Point &newPosition) void ShaderNode::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(ShaderNode::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -526,7 +526,7 @@ void SpriteBlur::initProgram() void SpriteBlur::draw() { - _customCommand.init(0, _vertexZ); + _customCommand.init(_vertexZ); _customCommand.func = CC_CALLBACK_0(SpriteBlur::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp index 569bef3915..1d76e56892 100644 --- a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp +++ b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp @@ -178,7 +178,7 @@ void ShaderSprite::initShader() void ShaderSprite::draw() { - _renderCommand.init(0, _vertexZ); + _renderCommand.init(_vertexZ); _renderCommand.func = CC_CALLBACK_0(ShaderSprite::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCommand); diff --git a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp index a3f4a7d564..3324802c9d 100644 --- a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp +++ b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp @@ -1794,7 +1794,7 @@ void TextureDrawAtPoint::draw() { TextureDemo::draw(); - _renderCmd.init(0, _vertexZ); + _renderCmd.init(_vertexZ); _renderCmd.func = CC_CALLBACK_0(TextureDrawAtPoint::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); @@ -1835,7 +1835,7 @@ void TextureDrawInRect::draw() { TextureDemo::draw(); - _renderCmd.init(0, _vertexZ); + _renderCmd.init(_vertexZ); _renderCmd.func = CC_CALLBACK_0(TextureDrawInRect::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); diff --git a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp index 75f0fd6eee..68f3cd5d59 100644 --- a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp @@ -599,7 +599,7 @@ TMXOrthoObjectsTest::TMXOrthoObjectsTest() void TMXOrthoObjectsTest::draw() { - _renderCmd.init(0, _vertexZ); + _renderCmd.init(_vertexZ); _renderCmd.func = CC_CALLBACK_0(TMXOrthoObjectsTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } @@ -672,7 +672,7 @@ TMXIsoObjectsTest::TMXIsoObjectsTest() void TMXIsoObjectsTest::draw() { - _renderCmd.init(0, _vertexZ); + _renderCmd.init(_vertexZ); _renderCmd.func = CC_CALLBACK_0(TMXIsoObjectsTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } @@ -1504,7 +1504,7 @@ TMXGIDObjectsTest::TMXGIDObjectsTest() void TMXGIDObjectsTest::draw() { - _renderCmd.init(0, _vertexZ); + _renderCmd.init(_vertexZ); _renderCmd.func = CC_CALLBACK_0(TMXGIDObjectsTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } From 08bb3b10604d70afc5f7f06b7d4e16b5d3c1b22b Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 18 Jan 2014 10:55:15 +0800 Subject: [PATCH 157/193] Update CHANGELOG [ci skip] --- CHANGELOG | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG b/CHANGELOG index 5f24006cb3..8b476b7457 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -6,7 +6,8 @@ cocos2d-x-3.0final ?.? ? [NEW] Label: Uses a struct of TTF configuration for Label::createWithTTF to reduce parameters and make this interface more easily to use. [NEW] Label: Integrates LabelAtlas into new Label. [NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10% - + [NEW] LuaBindings: Bindings-generator supports to bind namespace for lua. + [FIX] CocoStudio: TestColliderDetector in ArmatureTest can't work. [FIX] Crash if file doesn't exist when using FileUtils::getStringFromFile. [FIX] If setting a shorter string than before while using LabelAtlas, the effect will be wrong. From 86e102ab163161e985e6e5d21a27877ab3309b6b Mon Sep 17 00:00:00 2001 From: edwardzhou Date: Sat, 18 Jan 2014 10:58:17 +0800 Subject: [PATCH 158/193] fix namespace in spine lua manual binding --- .../bindings/lua_cocos2dx_spine_manual.cpp | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_spine_manual.cpp b/cocos/scripting/lua/bindings/lua_cocos2dx_spine_manual.cpp index 593dd3f0a3..63ea2a23cd 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_spine_manual.cpp +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_spine_manual.cpp @@ -94,7 +94,7 @@ static int lua_cocos2dx_CCSkeletonAnimation_createWithFile(lua_State* L) #if COCOS2D_DEBUG >= 1 tolua_Error tolua_err; - if (!tolua_isusertable(L,1,"SkeletonAnimation",0,&tolua_err)) goto tolua_lerror; + if (!tolua_isusertable(L,1,"sp.SkeletonAnimation",0,&tolua_err)) goto tolua_lerror; #endif argc = lua_gettop(L) - 1; @@ -115,7 +115,7 @@ static int lua_cocos2dx_CCSkeletonAnimation_createWithFile(lua_State* L) int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* pLuaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(L, nID, pLuaID, (void*)tolua_ret,"SkeletonAnimation"); + toluafix_pushusertype_ccobject(L, nID, pLuaID, (void*)tolua_ret,"sp.SkeletonAnimation"); return 1; } else if (3 == argc) { @@ -135,7 +135,7 @@ static int lua_cocos2dx_CCSkeletonAnimation_createWithFile(lua_State* L) int nID = (tolua_ret) ? (int)tolua_ret->_ID : -1; int* pLuaID = (tolua_ret) ? &tolua_ret->_luaID : NULL; - toluafix_pushusertype_ccobject(L, nID, pLuaID, (void*)tolua_ret,"SkeletonAnimation"); + toluafix_pushusertype_ccobject(L, nID, pLuaID, (void*)tolua_ret,"sp.SkeletonAnimation"); return 1; } @@ -153,7 +153,7 @@ int tolua_Cocos2d_CCSkeletonAnimation_registerScriptHandler00(lua_State* tolua_S #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"SkeletonAnimation",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"sp.SkeletonAnimation",0,&tolua_err) || !toluafix_isfunction(tolua_S,2,"LUA_FUNCTION",0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) @@ -180,7 +180,7 @@ int tolua_Cocos2d_CCSkeletonAnimation_unregisterScriptHandler00(lua_State* tolua #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"SkeletonAnimation",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"sp.SkeletonAnimation",0,&tolua_err) || !tolua_isnoobj(tolua_S,2,&tolua_err) ) goto tolua_lerror; @@ -205,7 +205,7 @@ static int tolua_Cocos2d_CCSkeletonAnimation_setTimeScale00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"SkeletonAnimation",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"sp.SkeletonAnimation",0,&tolua_err) || !tolua_isnumber(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) @@ -232,7 +232,7 @@ static int tolua_Cocos2d_CCSkeletonAnimation_setDebugSlots00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"SkeletonAnimation",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"sp.SkeletonAnimation",0,&tolua_err) || !tolua_isboolean(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) @@ -259,7 +259,7 @@ static int tolua_Cocos2d_CCSkeletonAnimation_setDebugBones00(lua_State* tolua_S) #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"SkeletonAnimation",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"sp.SkeletonAnimation",0,&tolua_err) || !tolua_isboolean(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) @@ -286,7 +286,7 @@ static int tolua_Cocos2d_CCSkeletonAnimation_setPremultipliedAlpha00(lua_State* #ifndef TOLUA_RELEASE tolua_Error tolua_err; if ( - !tolua_isusertype(tolua_S,1,"SkeletonAnimation",0,&tolua_err) || + !tolua_isusertype(tolua_S,1,"sp.SkeletonAnimation",0,&tolua_err) || !tolua_isboolean(tolua_S,2,0,&tolua_err) || !tolua_isnoobj(tolua_S,3,&tolua_err) ) @@ -311,13 +311,13 @@ tolua_lerror: static int tolua_spine_SkeletoneAnimation_setBlendFunc(lua_State* tolua_S) { - return tolua_cocos2dx_setBlendFunc(tolua_S,"SkeletonAnimation"); + return tolua_cocos2dx_setBlendFunc(tolua_S,"sp.SkeletonAnimation"); } static void extendCCSkeletonAnimation(lua_State* L) { - lua_pushstring(L, "SkeletonAnimation"); + lua_pushstring(L, "sp.SkeletonAnimation"); lua_rawget(L, LUA_REGISTRYINDEX); if (lua_istable(L,-1)) { From 069a4fb170f0e875d73068c1e3cd5e8a0777f4d8 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Fri, 17 Jan 2014 23:10:04 -0800 Subject: [PATCH 159/193] Renderer: Don't sort z=0 Commands If Command has z==0, then those elements won't be sorted. Only Z !=0 will be sorted, and it will use `sort` instead of `stable_sort` for z!=0, since it is faster --- CHANGELOG | 7 ++- cocos/2d/renderer/CCBatchCommand.cpp | 2 +- cocos/2d/renderer/CCBatchCommand.h | 2 +- cocos/2d/renderer/CCCustomCommand.cpp | 2 +- cocos/2d/renderer/CCCustomCommand.h | 2 +- cocos/2d/renderer/CCGroupCommand.h | 5 +- cocos/2d/renderer/CCQuadCommand.cpp | 2 +- cocos/2d/renderer/CCQuadCommand.h | 2 +- cocos/2d/renderer/CCRenderCommand.h | 4 +- cocos/2d/renderer/CCRenderer.cpp | 79 ++++++++++++++++++++++----- cocos/2d/renderer/CCRenderer.h | 21 ++++++- 11 files changed, 98 insertions(+), 30 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 8b476b7457..1497c22df8 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -17,10 +17,11 @@ cocos2d-x-3.0final ?.? ? [FIX] ControlSlider doesn't support to set selected thumb sprite. [FIX] ControlButton doesn't support to set scale ratio of touchdown state. [FIX] Particles: Crash was triggered if there is not `textureFileName`section in particle plist file. - [FIX] Renderer: QuadCommand::init() does not copy the Quads, it only store a reference making the code faster - [FIX] Renderer: Performance improved in Sprite and SpriteBatchNode (and subclasses) sprites in about 20% - [FIX] Renderer: When note using VAO, call glBufferData() instead of glBufferSubData(). [FIX] Renderer: Uses a float as key with only the depth. Viewport, opaque are not needed now + [FIX] Renderer Performance Fix: QuadCommand::init() does not copy the Quads, it only store a reference making the code faster + [FIX] Renderer Performance Fix: Sprite and SpriteBatchNode (and subclasses) has much better performance + [FIX] Renderer Performance Fix: When note using VAO, call glBufferData() instead of glBufferSubData(). + [FIX] Renderer Performance Fix: Doesn't sort z=0 elements. It also uses sort() instead of stable_sort() for z!=0. [FIX] Sprite: removed _hasChildren optimization. It uses !_children.empty() now which is super fast as well [FIX] Tests: TestCpp works with CMake on Windows. [FIX] Tests: Sprites Performance Test has 4 new tests diff --git a/cocos/2d/renderer/CCBatchCommand.cpp b/cocos/2d/renderer/CCBatchCommand.cpp index 817cfb421c..9c60b37455 100644 --- a/cocos/2d/renderer/CCBatchCommand.cpp +++ b/cocos/2d/renderer/CCBatchCommand.cpp @@ -54,7 +54,7 @@ BatchCommand::~BatchCommand() { } -void BatchCommand::execute() +void BatchCommand::execute() const { // Set material _shader->use(); diff --git a/cocos/2d/renderer/CCBatchCommand.h b/cocos/2d/renderer/CCBatchCommand.h index 9ac5b346ee..4ad2e7ae34 100644 --- a/cocos/2d/renderer/CCBatchCommand.h +++ b/cocos/2d/renderer/CCBatchCommand.h @@ -45,7 +45,7 @@ public: void init(float depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform); - void execute(); + void execute() const; protected: int32_t _materialID; diff --git a/cocos/2d/renderer/CCCustomCommand.cpp b/cocos/2d/renderer/CCCustomCommand.cpp index 10992393f7..c521928921 100644 --- a/cocos/2d/renderer/CCCustomCommand.cpp +++ b/cocos/2d/renderer/CCCustomCommand.cpp @@ -42,7 +42,7 @@ CustomCommand::~CustomCommand() } -void CustomCommand::execute() +void CustomCommand::execute() const { if(func) { diff --git a/cocos/2d/renderer/CCCustomCommand.h b/cocos/2d/renderer/CCCustomCommand.h index 03fdead69a..5bf149363e 100644 --- a/cocos/2d/renderer/CCCustomCommand.h +++ b/cocos/2d/renderer/CCCustomCommand.h @@ -41,7 +41,7 @@ public: void init(float depth); - void execute(); + void execute() const; inline bool isTranslucent() { return true; } std::function func; diff --git a/cocos/2d/renderer/CCGroupCommand.h b/cocos/2d/renderer/CCGroupCommand.h index 02fe541fd0..42c23d02b9 100644 --- a/cocos/2d/renderer/CCGroupCommand.h +++ b/cocos/2d/renderer/CCGroupCommand.h @@ -56,12 +56,9 @@ public: GroupCommand(); ~GroupCommand(); -public: - void init(float depth); - inline bool isTranslucent() {return true;} - inline int getRenderQueueID() {return _renderQueueID;} + inline int getRenderQueueID() const {return _renderQueueID;} protected: int _renderQueueID; diff --git a/cocos/2d/renderer/CCQuadCommand.cpp b/cocos/2d/renderer/CCQuadCommand.cpp index 0d602cee4e..333fd834d2 100644 --- a/cocos/2d/renderer/CCQuadCommand.cpp +++ b/cocos/2d/renderer/CCQuadCommand.cpp @@ -101,7 +101,7 @@ void QuadCommand::generateMaterialID() | (uint32_t)_textureID << 0; } -void QuadCommand::useMaterial() +void QuadCommand::useMaterial() const { _shader->use(); diff --git a/cocos/2d/renderer/CCQuadCommand.h b/cocos/2d/renderer/CCQuadCommand.h index e6bb2059b3..42411f48e9 100644 --- a/cocos/2d/renderer/CCQuadCommand.h +++ b/cocos/2d/renderer/CCQuadCommand.h @@ -44,7 +44,7 @@ public: void init(float depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quads, ssize_t quadCount, const kmMat4& mv); - void useMaterial(); + void useMaterial() const; //TODO use material to decide if it is translucent inline bool isTranslucent() const { return true; } diff --git a/cocos/2d/renderer/CCRenderCommand.h b/cocos/2d/renderer/CCRenderCommand.h index 9035454bc2..adb47f2f12 100644 --- a/cocos/2d/renderer/CCRenderCommand.h +++ b/cocos/2d/renderer/CCRenderCommand.h @@ -50,10 +50,10 @@ public: }; /** Get Render Command Id */ - inline float getDepth() { return _depth; } + inline float getDepth() const { return _depth; } /** Returns the Command type */ - inline Type getType() { return _type; } + inline Type getType() const { return _type; } protected: RenderCommand(); diff --git a/cocos/2d/renderer/CCRenderer.cpp b/cocos/2d/renderer/CCRenderer.cpp index 5b56fc80cd..4a137295fe 100644 --- a/cocos/2d/renderer/CCRenderer.cpp +++ b/cocos/2d/renderer/CCRenderer.cpp @@ -37,9 +37,65 @@ #include // for std::stable_sort NS_CC_BEGIN -using namespace std; + +bool compareRenderCommand(RenderCommand* a, RenderCommand* b) +{ + return a->getDepth() < b->getDepth(); +} + +void RenderQueue::push_back(RenderCommand* command) +{ + float z = command->getDepth(); + if(z < 0) + _queueNegZ.push_back(command); + if(z > 0) + _queuePosZ.push_back(command); + else + _queue0.push_back(command); +} + +ssize_t RenderQueue::size() const +{ + return _queueNegZ.size() + _queue0.size() + _queuePosZ.size(); +} + +void RenderQueue::sort() +{ + // Don't sort _queue0, it already comes sorted + std::sort(std::begin(_queueNegZ), std::end(_queueNegZ), compareRenderCommand); + std::sort(std::begin(_queuePosZ), std::end(_queuePosZ), compareRenderCommand); +} + +const RenderCommand* RenderQueue::operator[](ssize_t index) const +{ + if(index < _queueNegZ.size()) + return _queueNegZ[index]; + + index -= _queueNegZ.size(); + + if(index < _queue0.size()) + return _queue0[index]; + + index -= _queue0.size(); + + if(index < _queuePosZ.size()) + return _queuePosZ[index]; + + CCASSERT(false, "invalid index"); + return nullptr; +} + +void RenderQueue::clear() +{ + _queueNegZ.clear(); + _queue0.clear(); + _queuePosZ.clear(); +} +// +// +// #define DEFAULT_RENDER_QUEUE 0 Renderer::Renderer() @@ -205,11 +261,6 @@ int Renderer::createRenderQueue() return (int)_renderGroups.size() - 1; } -bool compareRenderCommand(RenderCommand* a, RenderCommand* b) -{ - return a->getDepth() < b->getDepth(); -} - void Renderer::render() { //Uncomment this once everything is rendered by new renderer @@ -221,9 +272,9 @@ void Renderer::render() { //Process render commands //1. Sort render commands based on ID - for (auto it = _renderGroups.begin(); it != _renderGroups.end(); ++it) + for (auto &renderqueue : _renderGroups) { - std::stable_sort((*it).begin(), (*it).end(), compareRenderCommand); + renderqueue.sort(); } while(!_renderStack.empty()) @@ -244,7 +295,7 @@ void Renderer::render() if(commandType == RenderCommand::Type::QUAD_COMMAND) { - QuadCommand* cmd = static_cast(command); + auto cmd = static_cast(command); ssize_t cmdQuadCount = cmd->getQuadCount(); //Batch quads @@ -266,19 +317,19 @@ void Renderer::render() else if(commandType == RenderCommand::Type::CUSTOM_COMMAND) { flush(); - CustomCommand* cmd = static_cast(command); + auto cmd = static_cast(command); cmd->execute(); } else if(commandType == RenderCommand::Type::BATCH_COMMAND) { flush(); - BatchCommand* cmd = static_cast(command); + auto cmd = static_cast(command); cmd->execute(); } else if(commandType == RenderCommand::Type::GROUP_COMMAND) { flush(); - GroupCommand* cmd = static_cast(command); + auto cmd = static_cast(command); _renderStack.top().currentIndex = i + 1; @@ -413,10 +464,10 @@ void Renderer::drawBatchedQuads() //Start drawing verties in batch for(ssize_t i = _firstCommand; i <= _lastCommand; i++) { - RenderCommand* command = _renderGroups[_renderStack.top().renderQueueID][i]; + auto command = _renderGroups[_renderStack.top().renderQueueID][i]; if (command->getType() == RenderCommand::Type::QUAD_COMMAND) { - QuadCommand* cmd = static_cast(command); + auto cmd = static_cast(command); if(_lastMaterialID != cmd->getMaterialID()) { //Draw quads diff --git a/cocos/2d/renderer/CCRenderer.h b/cocos/2d/renderer/CCRenderer.h index a856d201c3..0921fa6bc7 100644 --- a/cocos/2d/renderer/CCRenderer.h +++ b/cocos/2d/renderer/CCRenderer.h @@ -37,7 +37,26 @@ NS_CC_BEGIN class EventListenerCustom; -typedef std::vector RenderQueue; +/** Class that knows how to sort the Commands. + Since the commands that have z==0 are "pushed back" in + the correct order, the only Commands that need to be sorted, + are the ones that have z <0 and z >0. + And that is what this class does. +*/ +class RenderQueue { + +public: + void push_back(RenderCommand* command); + ssize_t size() const; + void sort(); + const RenderCommand* operator[](ssize_t index) const; + void clear(); + +protected: + std::vector _queueNegZ; + std::vector _queue0; + std::vector _queuePosZ; +}; struct RenderStackElement { From ac50e3f79291a359c5215314be9b629383abba64 Mon Sep 17 00:00:00 2001 From: liang8305 Date: Sat, 18 Jan 2014 15:27:59 +0800 Subject: [PATCH 160/193] =?UTF-8?q?When=20android=20project=20build=20nati?= =?UTF-8?q?ve,=20using=20multiple=20concurrent=20job=20processes;=20androi?= =?UTF-8?q?d=E9=A1=B9=E7=9B=AE=E7=BC=96=E8=AF=91=E6=97=B6,=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E5=88=A9=E7=94=A8"-j"=E5=8F=82=E6=95=B0,=E5=90=AF?= =?UTF-8?q?=E7=94=A8=E8=B7=9Fcpu=E6=95=B0=E7=9B=B8=E5=90=8C=E7=9A=84?= =?UTF-8?q?=E5=A4=9A=E8=BF=9B=E7=A8=8B=E7=BC=96=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../proj.android/build_native.py | 18 +++++++++++++++--- .../proj.android/build_native.py | 16 ++++++++++++++-- .../proj.android/build_native.py | 16 ++++++++++++++-- 3 files changed, 43 insertions(+), 7 deletions(-) diff --git a/template/multi-platform-cpp/proj.android/build_native.py b/template/multi-platform-cpp/proj.android/build_native.py index 03ee8de50f..c702b81a85 100755 --- a/template/multi-platform-cpp/proj.android/build_native.py +++ b/template/multi-platform-cpp/proj.android/build_native.py @@ -8,6 +8,16 @@ import os, os.path import shutil from optparse import OptionParser +def get_num_of_cpu(): + ''' The build process can be accelerated by running multiple concurrent job processes using the -j-option. + ''' + try: + from numpy.distutils import cpuinfo + return cpuinfo.cpu._getNCPUs() + except Exception: + print "Can't know cpuinfo, use default 1 cpu" + return 1 + def check_environment_variables_sdk(): ''' Checking the environment ANDROID_SDK_ROOT, which will be used for building ''' @@ -61,11 +71,13 @@ def do_build(cocos_root, ndk_root, app_android_root,ndk_build_param,sdk_root,and ndk_module_path = 'NDK_MODULE_PATH=%s;%s/external;%s/cocos' % (cocos_root, cocos_root, cocos_root) else: ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) - + + num_of_cpu = get_num_of_cpu() + if ndk_build_param == None: - command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + command = '%s -j%d -C %s %s' % (ndk_path, num_of_cpu, app_android_root, ndk_module_path) else: - command = '%s -C %s %s %s' % (ndk_path, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) + command = '%s -j%d -C %s %s %s' % (ndk_path, num_of_cpu, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) if os.system(command) != 0: raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!") elif android_platform is not None: diff --git a/template/multi-platform-js/proj.android/build_native.py b/template/multi-platform-js/proj.android/build_native.py index 4b20992504..42dd3aa9b6 100755 --- a/template/multi-platform-js/proj.android/build_native.py +++ b/template/multi-platform-js/proj.android/build_native.py @@ -8,6 +8,16 @@ import os, os.path import shutil from optparse import OptionParser +def get_num_of_cpu(): + ''' The build process can be accelerated by running multiple concurrent job processes using the -j-option. + ''' + try: + from numpy.distutils import cpuinfo + return cpuinfo.cpu._getNCPUs() + except Exception: + print "Can't know cpuinfo, use default 1 cpu" + return 1 + def check_environment_variables_sdk(): ''' Checking the environment ANDROID_SDK_ROOT, which will be used for building ''' @@ -62,10 +72,12 @@ def do_build(cocos_root, ndk_root, app_android_root,ndk_build_param,sdk_root,and else: ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) + num_of_cpu = get_num_of_cpu() + if ndk_build_param == None: - command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + command = '%s -j%d -C %s %s' % (ndk_path, num_of_cpu, app_android_root, ndk_module_path) else: - command = '%s -C %s %s %s' % (ndk_path, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) + command = '%s -j%d -C %s %s %s' % (ndk_path, num_of_cpu, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) if os.system(command) != 0: raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!") elif android_platform is not None: diff --git a/template/multi-platform-lua/proj.android/build_native.py b/template/multi-platform-lua/proj.android/build_native.py index 7414dd23af..b6920e2bbe 100755 --- a/template/multi-platform-lua/proj.android/build_native.py +++ b/template/multi-platform-lua/proj.android/build_native.py @@ -8,6 +8,16 @@ import os, os.path import shutil from optparse import OptionParser +def get_num_of_cpu(): + ''' The build process can be accelerated by running multiple concurrent job processes using the -j-option. + ''' + try: + from numpy.distutils import cpuinfo + return cpuinfo.cpu._getNCPUs() + except Exception: + print "Can't know cpuinfo, use default 1 cpu" + return 1 + def check_environment_variables_sdk(): ''' Checking the environment ANDROID_SDK_ROOT, which will be used for building ''' @@ -62,10 +72,12 @@ def do_build(cocos_root, ndk_root, app_android_root,ndk_build_param,sdk_root,and else: ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) + num_of_cpu = get_num_of_cpu() + if ndk_build_param == None: - command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + command = '%s -j%d -C %s %s' % (ndk_path, num_of_cpu, app_android_root, ndk_module_path) else: - command = '%s -C %s %s %s' % (ndk_path, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) + command = '%s -j%d -C %s %s %s' % (ndk_path, num_of_cpu, app_android_root, ''.join(str(e) for e in ndk_build_param), ndk_module_path) if os.system(command) != 0: raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!") elif android_platform is not None: From b32ff0ed497434101f7678685c0abf35e650f410 Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Sat, 18 Jan 2014 11:35:27 -0800 Subject: [PATCH 161/193] GlobalZOrder is used for render priority... ...and not vertexZ Node::setGlobalZOrder() is used to change that. Node::setZOrder() -> Node::setLocalZOrder(); --- CHANGELOG | 3 +- .../project.pbxproj.REMOVED.git-id | 2 +- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/CCAtlasNode.cpp | 2 +- cocos/2d/CCClippingNode.cpp | 8 +- cocos/2d/CCDrawNode.cpp | 2 +- cocos/2d/CCLabel.cpp | 2 +- cocos/2d/CCLayer.cpp | 2 +- cocos/2d/CCMotionStreak.cpp | 2 +- cocos/2d/CCNode.cpp | 33 +++---- cocos/2d/CCNode.h | 92 +++++++++++++------ cocos/2d/CCNodeGrid.cpp | 6 +- cocos/2d/CCParticleBatchNode.cpp | 6 +- cocos/2d/CCParticleSystemQuad.cpp | 2 +- cocos/2d/CCProgressTimer.cpp | 2 +- cocos/2d/CCRenderTexture.cpp | 12 +-- cocos/2d/CCSprite.cpp | 11 +-- cocos/2d/CCSpriteBatchNode.cpp | 2 +- cocos/2d/CCTransitionPageTurn.cpp | 8 +- cocos/2d/renderer/CCBatchCommand.cpp | 6 +- cocos/2d/renderer/CCBatchCommand.h | 2 +- cocos/2d/renderer/CCCustomCommand.cpp | 6 +- cocos/2d/renderer/CCCustomCommand.h | 2 +- cocos/2d/renderer/CCGroupCommand.cpp | 4 +- cocos/2d/renderer/CCQuadCommand.cpp | 4 +- cocos/2d/renderer/CCRenderCommand.cpp | 4 +- cocos/2d/renderer/CCRenderCommand.h | 4 +- cocos/2d/renderer/CCRenderer.cpp | 20 ++-- cocos/2d/renderer/CCRenderer.h | 2 +- .../editor-support/cocostudio/CCBatchNode.cpp | 2 +- cocos/editor-support/cocostudio/CCBone.cpp | 12 +-- cocos/editor-support/cocostudio/CCBone.h | 2 +- .../cocostudio/CCSGUIReader.cpp | 4 +- .../cocostudio/CCSSceneReader.cpp | 2 +- cocos/editor-support/cocostudio/CCSkin.cpp | 2 +- cocos/editor-support/spine/CCSkeleton.cpp | 2 +- cocos/gui/UILayout.cpp | 16 ++-- cocos/gui/UILayout.h | 4 +- cocos/gui/UIListView.cpp | 2 +- cocos/gui/UIScrollView.h | 4 +- cocos/gui/UIWidget.cpp | 2 +- cocos/gui/UIWidget.h | 4 +- extensions/GUI/CCScrollView/CCScrollView.cpp | 4 +- .../Classes/ActionsTest/ActionsTest.cpp | 10 +- .../TestCpp/Classes/Box2DTest/Box2dTest.cpp | 2 +- .../Classes/Box2DTestBed/Box2dView.cpp | 2 +- .../ClippingNodeTest/ClippingNodeTest.cpp | 8 +- .../DrawPrimitivesTest/DrawPrimitivesTest.cpp | 2 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 10 +- .../UIImageViewTest/UIImageViewTest.cpp | 2 +- .../TestCpp/Classes/LabelTest/LabelTest.cpp | 6 +- .../Classes/LabelTest/LabelTestNew.cpp | 4 +- .../NewEventDispatcherTest.cpp | 4 +- .../Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp | 52 ++++++++++- .../Cpp/TestCpp/Classes/NodeTest/NodeTest.h | 14 +++ .../RenderTextureTest/RenderTextureTest.cpp | 10 +- .../TestCpp/Classes/ShaderTest/ShaderTest.cpp | 4 +- .../Classes/ShaderTest/ShaderTest2.cpp | 2 +- .../Classes/Texture2dTest/Texture2dTest.cpp | 4 +- .../Classes/TileMapTest/TileMapTest.cpp | 6 +- 60 files changed, 272 insertions(+), 185 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 1497c22df8..6ad27e8da2 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,10 +1,11 @@ -cocos2d-x-3.0final ?.? ? +cocos2d-x-3.0beta2 ?.? ? [All] [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands [NEW] GLCache: glActiveTexture() is cached with GL::activeTexture(). All code MUST call the cached version in order to work correctly [NEW] Label: Uses a struct of TTF configuration for Label::createWithTTF to reduce parameters and make this interface more easily to use. [NEW] Label: Integrates LabelAtlas into new Label. + [NEW] Node: Added `setGlobalZOrder()`. Useful to change the Node's render order [NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10% [NEW] LuaBindings: Bindings-generator supports to bind namespace for lua. diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index b052741ae6..a520602c3d 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -e1e5a1169e92834330092c45165660c6cbd03609 \ No newline at end of file +63e6598ea5798bf42bbd22c2295e65f7c739695a \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index bb3a11cb54..eac7e38de9 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -1fa58d8cba77ef923c83d2860d5511d28dad6c27 \ No newline at end of file +447e7ba37294e6da0df2e02f5a62f30fb15e3272 \ No newline at end of file diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index 03eb16ba18..15492a651f 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -153,7 +153,7 @@ void AtlasNode::draw(void) auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); _quadCommand.init( - _vertexZ, + _globalZOrder, _textureAtlas->getTexture()->getName(), shader, _blendFunc, diff --git a/cocos/2d/CCClippingNode.cpp b/cocos/2d/CCClippingNode.cpp index 55be0ef5a8..f20b4d2778 100644 --- a/cocos/2d/CCClippingNode.cpp +++ b/cocos/2d/CCClippingNode.cpp @@ -210,12 +210,12 @@ void ClippingNode::visit() Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand.init(_vertexZ); + _groupCommand.init(_globalZOrder); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); - _beforeVisitCmd.init(_vertexZ); + _beforeVisitCmd.init(_globalZOrder); _beforeVisitCmd.func = CC_CALLBACK_0(ClippingNode::onBeforeVisit, this); renderer->addCommand(&_beforeVisitCmd); if (_alphaThreshold < 1) @@ -238,7 +238,7 @@ void ClippingNode::visit() } _stencil->visit(); - _afterDrawStencilCmd.init(_vertexZ); + _afterDrawStencilCmd.init(_globalZOrder); _afterDrawStencilCmd.func = CC_CALLBACK_0(ClippingNode::onAfterDrawStencil, this); renderer->addCommand(&_afterDrawStencilCmd); @@ -268,7 +268,7 @@ void ClippingNode::visit() this->draw(); } - _afterVisitCmd.init(_vertexZ); + _afterVisitCmd.init(_globalZOrder); _afterVisitCmd.func = CC_CALLBACK_0(ClippingNode::onAfterVisit, this); renderer->addCommand(&_afterVisitCmd); diff --git a/cocos/2d/CCDrawNode.cpp b/cocos/2d/CCDrawNode.cpp index 0e28ee554f..003209b6e4 100644 --- a/cocos/2d/CCDrawNode.cpp +++ b/cocos/2d/CCDrawNode.cpp @@ -241,7 +241,7 @@ void DrawNode::render() void DrawNode::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(DrawNode::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index c96678fc57..0cac300283 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -666,7 +666,7 @@ void Label::onDraw() void Label::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Label::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index 83629a50ec..54b9c48cd9 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -565,7 +565,7 @@ void LayerColor::updateColor() void LayerColor::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(LayerColor::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/cocos/2d/CCMotionStreak.cpp b/cocos/2d/CCMotionStreak.cpp index 2dc1f49fbb..735a8edae2 100644 --- a/cocos/2d/CCMotionStreak.cpp +++ b/cocos/2d/CCMotionStreak.cpp @@ -359,7 +359,7 @@ void MotionStreak::draw() if(_nuPoints <= 1) return; kmGLGetMatrix(KM_GL_MODELVIEW,&_cachedMV); - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(MotionStreak::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 3b7ce1c47c..e631d0f02a 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -108,7 +108,8 @@ Node::Node(void) , _inverseDirty(true) // children (lazy allocs) // lazy alloc -, _ZOrder(0) +, _localZOrder(0) +, _globalZOrder(0) , _parent(nullptr) // "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true , _tag(Node::INVALID_TAG) @@ -212,29 +213,22 @@ void Node::setSkewY(float newSkewY) _transformDirty = _inverseDirty = true; } -/// zOrder getter -int Node::getZOrder() const -{ - return _ZOrder; -} /// zOrder setter : private method /// used internally to alter the zOrder variable. DON'T call this method manually -void Node::_setZOrder(int z) +void Node::_setLocalZOrder(int z) { - _ZOrder = z; + _localZOrder = z; } -void Node::setZOrder(int z) +void Node::setLocalZOrder(int z) { + _localZOrder = z; if (_parent) { _parent->reorderChild(this, z); } - // should set "_ZOrder" after reorderChild, because the implementation of reorderChild subclass of Node, such as Sprite, - // will return when _ZOrder value is not changed - _setZOrder(z); - + _eventDispatcher->setDirtyForNode(this); } @@ -246,9 +240,10 @@ float Node::getVertexZ() const /// vertexZ setter -void Node::setVertexZ(float var) +void Node::setVertexZ(float zOrder) { - _vertexZ = var; + _vertexZ = zOrder; + setGlobalZOrder(zOrder); } @@ -650,7 +645,7 @@ void Node::addChild(Node *child, int zOrder) void Node::addChild(Node *child) { CCASSERT( child != nullptr, "Argument must be non-nil"); - this->addChild(child, child->_ZOrder, child->_tag); + this->addChild(child, child->_localZOrder, child->_tag); } void Node::removeFromParent() @@ -767,7 +762,7 @@ void Node::insertChild(Node* child, int z) { _reorderChildDirty = true; _children.pushBack(child); - child->_setZOrder(z); + child->_setLocalZOrder(z); } void Node::reorderChild(Node *child, int zOrder) @@ -775,7 +770,7 @@ void Node::reorderChild(Node *child, int zOrder) CCASSERT( child != nullptr, "Child must be non-nil"); _reorderChildDirty = true; child->setOrderOfArrival(s_globalOrderOfArrival++); - child->_setZOrder(zOrder); + child->_setLocalZOrder(zOrder); } void Node::sortAllChildren() @@ -816,7 +811,7 @@ void Node::visit() { auto node = _children.at(i); - if ( node && node->_ZOrder < 0 ) + if ( node && node->_localZOrder < 0 ) node->visit(); else break; diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 3069fb0a84..0598773a7c 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -161,43 +161,72 @@ public: /// @name Setters & Getters for Graphic Peroperties /** - * Sets the Z order which stands for the drawing order, and reorder this node in its parent's children array. - * - * The Z order of node is relative to its siblings. - * It is not related to the OpenGL's z property. This one only affects the draw order of itself and its siblings. - * Lower Z order number are drawn before higher numbers. - * Please refer to `setVertexZ(float)` for the difference. - * - * @param zOrder Z order of this node. + LocalZOrder is the 'key' used to sort the node relative to its siblings. + + The Node's parent will sort all its children based ont the LocalZOrder value. + If two nodes have the same LocalZOrder, then the node that was added first to the children's array will be in front of the other node in the array. + + Also, the Scene Graph is traversed using the "In-Order" tree traversal algorithm ( http://en.wikipedia.org/wiki/Tree_traversal#In-order ) + And Nodes that have LocalZOder values < 0 are the "left" subtree + While Nodes with LocalZOder >=0 are the "right" subtree. + + @see `setGlobalZOrder` + @see `setVertexZ` */ - virtual void setZOrder(int zOrder); - /* - * Sets the z order which stands for the drawing order - * - * This is an internal method. Don't call it outside the framework. - * The difference between setZOrder(int) and _setOrder(int) is: - * - _setZOrder(int) is a pure setter for _ZOrder memeber variable - * - setZOrder(int) firstly changes _ZOrder, then recorder this node in its parent's chilren array. + virtual void setLocalZOrder(int zOrder); + + CC_DEPRECATED_ATTRIBUTE virtual void setZOrder(int zOrder) { setLocalZOrder(zOrder); } + /* Helper function used by `setLocalZOrder`. Don't use it unless you know what you are doing. */ - virtual void _setZOrder(int z); + virtual void _setLocalZOrder(int z); /** - * Gets the Z order of this node. + * Gets the local Z order of this node. * - * @see `setZOrder(int)` + * @see `setLocalZOrder(int)` * - * @return The Z order. + * @return The local (relative to its siblings) Z order. */ - virtual int getZOrder() const; + virtual int getLocalZOrder() const { return _localZOrder; } + CC_DEPRECATED_ATTRIBUTE virtual int getZOrder() const { return getLocalZOrder(); } /** - * Sets the real OpenGL Z vertex. + Defines the oder in which the nodes are renderer. + Nodes that have a Global Z Order lower, are renderer first. + + In case two or more nodes have the same Global Z Order, the oder is not guaranteed. + The only exception if the Nodes have a Global Z Order == 0. In that case, the Scene Graph order is used. + + By default, all nodes have a Global Z Order = 0. That means that by default, the Scene Graph order is used to render the nodes. + + Global Z Order is useful when you need to render nodes in an order different than the Scene Graph order. + + Limitations: Global Z Order can't be used used by Nodes that have SpriteBatchNode as one of their acenstors. + And if ClippingNode is one of the ancestors, then "global Z order" will be relative to the ClippingNode. + + @see `setLocalZOrder()` + @see `setVertexZ()` + + @since v3.0 + */ + virtual void setGlobalZOrder(float zOrder) { _globalZOrder = zOrder; } + /** + * Returns the Node's Global Z Order. * - * Differences between openGL Z vertex and cocos2d Z order: - * - OpenGL Z modifies the Z vertex, and not the Z order in the relation between parent-children - * - OpenGL Z might require to set 2D projection - * - cocos2d Z order works OK if all the nodes uses the same openGL Z vertex. eg: `vertexZ = 0` + * @see `setGlobalZOrder(int)` * - * @warning Use it at your own risk since it might break the cocos2d parent-children z order + * @return The node's global Z order + */ + virtual float getGlobalZOrder() const { return _globalZOrder; } + + /** + * Sets the 'z' value in the OpenGL Depth Buffer. + * + * The OpenGL depth buffer and depth testing are disabled by default. You need to turn them on + * in order to use this property correctly. + * + * `setVertexZ()` also sets the `setGlobalZValue()` with the vertexZ value. + * + * @see `setGlobalZValue()` * * @param vertexZ OpenGL Z vertex of this node. */ @@ -1411,7 +1440,6 @@ protected: float _scaleX; ///< scaling factor on x-axis float _scaleY; ///< scaling factor on y-axis - float _vertexZ; ///< OpenGL real Z vertex Point _position; ///< position of the node @@ -1433,8 +1461,12 @@ protected: mutable bool _transformDirty; ///< transform dirty flag mutable bool _inverseDirty; ///< inverse transform dirty flag - int _ZOrder; ///< z-order value that affects the draw order - + + int _localZOrder; ///< Local order (relative to its siblings) used to sort the node + float _globalZOrder; ///< Global order used to sort the node + float _vertexZ; ///< OpenGL real Z vertex + + Vector _children; ///< array of children nodes Node *_parent; ///< weak reference to parent node diff --git a/cocos/2d/CCNodeGrid.cpp b/cocos/2d/CCNodeGrid.cpp index 9f359cf778..f8c5d5accb 100644 --- a/cocos/2d/CCNodeGrid.cpp +++ b/cocos/2d/CCNodeGrid.cpp @@ -92,7 +92,7 @@ void NodeGrid::visit() Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand.init(_vertexZ); + _groupCommand.init(_globalZOrder); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); @@ -104,7 +104,7 @@ void NodeGrid::visit() _nodeGrid->set2DProjection(); } - _gridBeginCommand.init(_vertexZ); + _gridBeginCommand.init(_globalZOrder); _gridBeginCommand.func = CC_CALLBACK_0(NodeGrid::onGridBeginDraw, this); renderer->addCommand(&_gridBeginCommand); @@ -152,7 +152,7 @@ void NodeGrid::visit() director->setProjection(beforeProjectionType); } - _gridEndCommand.init(_vertexZ); + _gridEndCommand.init(_globalZOrder); _gridEndCommand.func = CC_CALLBACK_0(NodeGrid::onGridEndDraw, this); renderer->addCommand(&_gridEndCommand); diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index d64d682ce3..bca1c3eb28 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -197,7 +197,7 @@ int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag) _children.insert(pos, child); child->setTag(aTag); - child->_setZOrder(z); + child->_setLocalZOrder(z); child->setParent(this); @@ -264,7 +264,7 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder) } } - child->_setZOrder(zOrder); + child->_setLocalZOrder(zOrder); } void ParticleBatchNode::getCurrentIndex(int* oldIndex, int* newIndex, Node* child, int z) @@ -383,7 +383,7 @@ void ParticleBatchNode::draw(void) } _batchCommand.init( - _vertexZ, + _globalZOrder, _textureAtlas->getTexture()->getName(), _shaderProgram, _blendFunc, diff --git a/cocos/2d/CCParticleSystemQuad.cpp b/cocos/2d/CCParticleSystemQuad.cpp index cf3725e1a2..bd4bef3599 100644 --- a/cocos/2d/CCParticleSystemQuad.cpp +++ b/cocos/2d/CCParticleSystemQuad.cpp @@ -439,7 +439,7 @@ void ParticleSystemQuad::draw() auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); - _quadCommand.init(_vertexZ, _texture->getName(), shader, _blendFunc, _quads, _particleIdx, _modelViewTransform); + _quadCommand.init(_globalZOrder, _texture->getName(), shader, _blendFunc, _quads, _particleIdx, _modelViewTransform); Director::getInstance()->getRenderer()->addCommand(&_quadCommand); } diff --git a/cocos/2d/CCProgressTimer.cpp b/cocos/2d/CCProgressTimer.cpp index b8332e0442..112b34d85b 100644 --- a/cocos/2d/CCProgressTimer.cpp +++ b/cocos/2d/CCProgressTimer.cpp @@ -555,7 +555,7 @@ void ProgressTimer::draw() if( ! _vertexData || ! _sprite) return; - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ProgressTimer::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index 63bc1a596d..57b6a00d24 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -322,7 +322,7 @@ void RenderTexture::beginWithClear(float r, float g, float b, float a, float dep this->begin(); //clear screen - _beginWithClearCommand.init(_vertexZ); + _beginWithClearCommand.init(_globalZOrder); _beginWithClearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this); Director::getInstance()->getRenderer()->addCommand(&_beginWithClearCommand); } @@ -340,7 +340,7 @@ void RenderTexture::clearDepth(float depthValue) this->begin(); - _clearDepthCommand.init(_vertexZ); + _clearDepthCommand.init(_globalZOrder); _clearDepthCommand.func = CC_CALLBACK_0(RenderTexture::onClearDepth, this); Director::getInstance()->getRenderer()->addCommand(&_clearDepthCommand); @@ -605,7 +605,7 @@ void RenderTexture::draw() begin(); //clear screen - _clearCommand.init(_vertexZ); + _clearCommand.init(_globalZOrder); _clearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this); Director::getInstance()->getRenderer()->addCommand(&_clearCommand); @@ -648,13 +648,13 @@ void RenderTexture::begin() (float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1,1 ); kmGLMultMatrix(&orthoMatrix); - _groupCommand.init(_vertexZ); + _groupCommand.init(_globalZOrder); Renderer *renderer = Director::getInstance()->getRenderer(); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); - _beginCommand.init(_vertexZ); + _beginCommand.init(_globalZOrder); _beginCommand.func = CC_CALLBACK_0(RenderTexture::onBegin, this); Director::getInstance()->getRenderer()->addCommand(&_beginCommand); @@ -662,7 +662,7 @@ void RenderTexture::begin() void RenderTexture::end() { - _endCommand.init(_vertexZ); + _endCommand.init(_globalZOrder); _endCommand.func = CC_CALLBACK_0(RenderTexture::onEnd, this); Renderer *renderer = Director::getInstance()->getRenderer(); diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index fafb509a6b..65c7a24b50 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -670,7 +670,7 @@ void Sprite::updateTransform(void) void Sprite::draw(void) { //TODO implement z order - _quadCommand.init(_vertexZ, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, _modelViewTransform); + _quadCommand.init(_globalZOrder, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, _modelViewTransform); // if(culling()) { @@ -769,13 +769,8 @@ void Sprite::addChild(Node *child, int zOrder, int tag) void Sprite::reorderChild(Node *child, int zOrder) { - CCASSERT(child != nullptr, ""); - CCASSERT(_children.contains(child), ""); - - if (zOrder == child->getZOrder()) - { - return; - } + CCASSERT(child != nullptr, "child must be non null"); + CCASSERT(_children.contains(child), "child does not belong to this"); if( _batchNode && ! _reorderChildDirty) { diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 6237f92b19..0526b6768d 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -357,7 +357,7 @@ void SpriteBatchNode::draw() child->updateTransform(); _batchCommand.init( - _vertexZ, + _globalZOrder, _textureAtlas->getTexture()->getName(), _shaderProgram, _blendFunc, diff --git a/cocos/2d/CCTransitionPageTurn.cpp b/cocos/2d/CCTransitionPageTurn.cpp index c42bf6e9d2..7e4102b009 100644 --- a/cocos/2d/CCTransitionPageTurn.cpp +++ b/cocos/2d/CCTransitionPageTurn.cpp @@ -98,23 +98,23 @@ void TransitionPageTurn::draw() if( _isInSceneOnTop ) { _outSceneProxy->visit(); - _enableOffsetCmd.init(_vertexZ); + _enableOffsetCmd.init(_globalZOrder); _enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd); _inSceneProxy->visit(); - _disableOffsetCmd.init(_vertexZ); + _disableOffsetCmd.init(_globalZOrder); _disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd); } else { _inSceneProxy->visit(); - _enableOffsetCmd.init(_vertexZ); + _enableOffsetCmd.init(_globalZOrder); _enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd); _outSceneProxy->visit(); - _disableOffsetCmd.init(_vertexZ); + _disableOffsetCmd.init(_globalZOrder); _disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd); } diff --git a/cocos/2d/renderer/CCBatchCommand.cpp b/cocos/2d/renderer/CCBatchCommand.cpp index 9c60b37455..b9b0c7fab9 100644 --- a/cocos/2d/renderer/CCBatchCommand.cpp +++ b/cocos/2d/renderer/CCBatchCommand.cpp @@ -38,9 +38,9 @@ BatchCommand::BatchCommand() _shader = nullptr; } -void BatchCommand::init(float depth, GLuint textureID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform) +void BatchCommand::init(float globalOrder, GLuint textureID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform) { - _depth = depth; + _globalOrder = globalOrder; _textureID = textureID; _blendType = blendType; _shader = shader; @@ -54,7 +54,7 @@ BatchCommand::~BatchCommand() { } -void BatchCommand::execute() const +void BatchCommand::execute() { // Set material _shader->use(); diff --git a/cocos/2d/renderer/CCBatchCommand.h b/cocos/2d/renderer/CCBatchCommand.h index 4ad2e7ae34..9ac5b346ee 100644 --- a/cocos/2d/renderer/CCBatchCommand.h +++ b/cocos/2d/renderer/CCBatchCommand.h @@ -45,7 +45,7 @@ public: void init(float depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform); - void execute() const; + void execute(); protected: int32_t _materialID; diff --git a/cocos/2d/renderer/CCCustomCommand.cpp b/cocos/2d/renderer/CCCustomCommand.cpp index c521928921..c324032116 100644 --- a/cocos/2d/renderer/CCCustomCommand.cpp +++ b/cocos/2d/renderer/CCCustomCommand.cpp @@ -32,9 +32,9 @@ CustomCommand::CustomCommand() _type = RenderCommand::Type::CUSTOM_COMMAND; } -void CustomCommand::init(float depth) +void CustomCommand::init(float globalOrder) { - _depth = depth; + _globalOrder = globalOrder; } CustomCommand::~CustomCommand() @@ -42,7 +42,7 @@ CustomCommand::~CustomCommand() } -void CustomCommand::execute() const +void CustomCommand::execute() { if(func) { diff --git a/cocos/2d/renderer/CCCustomCommand.h b/cocos/2d/renderer/CCCustomCommand.h index 5bf149363e..03fdead69a 100644 --- a/cocos/2d/renderer/CCCustomCommand.h +++ b/cocos/2d/renderer/CCCustomCommand.h @@ -41,7 +41,7 @@ public: void init(float depth); - void execute() const; + void execute(); inline bool isTranslucent() { return true; } std::function func; diff --git a/cocos/2d/renderer/CCGroupCommand.cpp b/cocos/2d/renderer/CCGroupCommand.cpp index 70496b5d1d..95b9a5ccb5 100644 --- a/cocos/2d/renderer/CCGroupCommand.cpp +++ b/cocos/2d/renderer/CCGroupCommand.cpp @@ -91,9 +91,9 @@ GroupCommand::GroupCommand() _renderQueueID = GroupCommandManager::getInstance()->getGroupID(); } -void GroupCommand::init(float depth) +void GroupCommand::init(float globalOrder) { - _depth = depth; + _globalOrder = globalOrder; GroupCommandManager::getInstance()->releaseGroupID(_renderQueueID); _renderQueueID = GroupCommandManager::getInstance()->getGroupID(); } diff --git a/cocos/2d/renderer/CCQuadCommand.cpp b/cocos/2d/renderer/CCQuadCommand.cpp index 333fd834d2..9cae10d701 100644 --- a/cocos/2d/renderer/CCQuadCommand.cpp +++ b/cocos/2d/renderer/CCQuadCommand.cpp @@ -38,9 +38,9 @@ QuadCommand::QuadCommand() _quads = nullptr; } -void QuadCommand::init(float depth, GLuint textureID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, const kmMat4 &mv) +void QuadCommand::init(float globalOrder, GLuint textureID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, const kmMat4 &mv) { - _depth = depth; + _globalOrder = globalOrder; _textureID = textureID; _blendType = blendType; _shader = shader; diff --git a/cocos/2d/renderer/CCRenderCommand.cpp b/cocos/2d/renderer/CCRenderCommand.cpp index 64157b4739..578f28d426 100644 --- a/cocos/2d/renderer/CCRenderCommand.cpp +++ b/cocos/2d/renderer/CCRenderCommand.cpp @@ -29,7 +29,7 @@ NS_CC_BEGIN RenderCommand::RenderCommand() : _type(RenderCommand::Type::UNKNOWN_COMMAND) -, _depth(0) +, _globalOrder(0) { } @@ -57,7 +57,7 @@ void printBits(ssize_t const size, void const * const ptr) void RenderCommand::printID() { - printf("Command Depth: %f\n", _depth); + printf("Command Depth: %f\n", _globalOrder); } NS_CC_END \ No newline at end of file diff --git a/cocos/2d/renderer/CCRenderCommand.h b/cocos/2d/renderer/CCRenderCommand.h index adb47f2f12..688f65feb7 100644 --- a/cocos/2d/renderer/CCRenderCommand.h +++ b/cocos/2d/renderer/CCRenderCommand.h @@ -50,7 +50,7 @@ public: }; /** Get Render Command Id */ - inline float getDepth() const { return _depth; } + inline float getGlobalOrder() const { return _globalOrder; } /** Returns the Command type */ inline Type getType() const { return _type; } @@ -65,7 +65,7 @@ protected: Type _type; // commands are sort by depth - float _depth; + float _globalOrder; }; NS_CC_END diff --git a/cocos/2d/renderer/CCRenderer.cpp b/cocos/2d/renderer/CCRenderer.cpp index 4a137295fe..6642ddfd6c 100644 --- a/cocos/2d/renderer/CCRenderer.cpp +++ b/cocos/2d/renderer/CCRenderer.cpp @@ -34,21 +34,21 @@ #include "CCEventDispatcher.h" #include "CCEventListenerCustom.h" #include "CCEventType.h" -#include // for std::stable_sort +#include NS_CC_BEGIN bool compareRenderCommand(RenderCommand* a, RenderCommand* b) { - return a->getDepth() < b->getDepth(); + return a->getGlobalOrder() < b->getGlobalOrder(); } void RenderQueue::push_back(RenderCommand* command) { - float z = command->getDepth(); + float z = command->getGlobalOrder(); if(z < 0) _queueNegZ.push_back(command); - if(z > 0) + else if(z > 0) _queuePosZ.push_back(command); else _queue0.push_back(command); @@ -66,7 +66,7 @@ void RenderQueue::sort() std::sort(std::begin(_queuePosZ), std::end(_queuePosZ), compareRenderCommand); } -const RenderCommand* RenderQueue::operator[](ssize_t index) const +RenderCommand* RenderQueue::operator[](ssize_t index) const { if(index < _queueNegZ.size()) return _queueNegZ[index]; @@ -295,7 +295,7 @@ void Renderer::render() if(commandType == RenderCommand::Type::QUAD_COMMAND) { - auto cmd = static_cast(command); + auto cmd = static_cast(command); ssize_t cmdQuadCount = cmd->getQuadCount(); //Batch quads @@ -317,19 +317,19 @@ void Renderer::render() else if(commandType == RenderCommand::Type::CUSTOM_COMMAND) { flush(); - auto cmd = static_cast(command); + auto cmd = static_cast(command); cmd->execute(); } else if(commandType == RenderCommand::Type::BATCH_COMMAND) { flush(); - auto cmd = static_cast(command); + auto cmd = static_cast(command); cmd->execute(); } else if(commandType == RenderCommand::Type::GROUP_COMMAND) { flush(); - auto cmd = static_cast(command); + auto cmd = static_cast(command); _renderStack.top().currentIndex = i + 1; @@ -467,7 +467,7 @@ void Renderer::drawBatchedQuads() auto command = _renderGroups[_renderStack.top().renderQueueID][i]; if (command->getType() == RenderCommand::Type::QUAD_COMMAND) { - auto cmd = static_cast(command); + auto cmd = static_cast(command); if(_lastMaterialID != cmd->getMaterialID()) { //Draw quads diff --git a/cocos/2d/renderer/CCRenderer.h b/cocos/2d/renderer/CCRenderer.h index 0921fa6bc7..39511a04f0 100644 --- a/cocos/2d/renderer/CCRenderer.h +++ b/cocos/2d/renderer/CCRenderer.h @@ -49,7 +49,7 @@ public: void push_back(RenderCommand* command); ssize_t size() const; void sort(); - const RenderCommand* operator[](ssize_t index) const; + RenderCommand* operator[](ssize_t index) const; void clear(); protected: diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index 20f034c35b..752e4911a9 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -156,7 +156,7 @@ void BatchNode::draw() void BatchNode::generateGroupCommand() { Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand->init(_vertexZ); + _groupCommand->init(_globalZOrder); renderer->addCommand(_groupCommand); renderer->pushGroup(_groupCommand->getRenderQueueID()); diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 4bd7883a43..dbaa142020 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -145,7 +145,7 @@ void Bone::setBoneData(BoneData *boneData) } _name = _boneData->name; - _ZOrder = _boneData->zOrder; + _localZOrder = _boneData->zOrder; _displayManager->initDisplayList(boneData); } @@ -283,11 +283,11 @@ void Bone::updateZOrder() if (_dataVersion >= VERSION_COMBINED) { int zorder = _tweenData->zOrder + _boneData->zOrder; - setZOrder(zorder); + setLocalZOrder(zorder); } else { - setZOrder(_tweenData->zOrder); + setLocalZOrder(_tweenData->zOrder); } } @@ -374,10 +374,10 @@ Tween *Bone::getTween() return _tween; } -void Bone::setZOrder(int zOrder) +void Bone::setLocalZOrder(int zOrder) { - if (_ZOrder != zOrder) - Node::setZOrder(zOrder); + if (_localZOrder != zOrder) + Node::setLocalZOrder(zOrder); } kmMat4 Bone::getNodeToArmatureTransform() const diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index db153a1da5..c81583a8c9 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -143,7 +143,7 @@ public: //! Update zorder void updateZOrder(); - virtual void setZOrder(int zOrder) override; + virtual void setLocalZOrder(int zOrder) override; Tween *getTween(); diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index 349bba5dfe..a8bd016948 100644 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -331,7 +331,7 @@ void WidgetPropertiesReader0250::setPropsForWidgetFromJsonDictionary(Widget*widg widget->setVisible(DICTOOL->getBooleanValue_json(options, "visible")); } int z = DICTOOL->getIntValue_json(options, "ZOrder"); - widget->setZOrder(z); + widget->setLocalZOrder(z); } void WidgetPropertiesReader0250::setColorPropsForWidgetFromJsonDictionary(Widget *widget, const rapidjson::Value&options) @@ -1062,7 +1062,7 @@ void WidgetPropertiesReader0300::setPropsForWidgetFromJsonDictionary(Widget*widg widget->setVisible(DICTOOL->getBooleanValue_json(options, "visible")); } int z = DICTOOL->getIntValue_json(options, "ZOrder"); - widget->setZOrder(z); + widget->setLocalZOrder(z); bool layout = DICTOOL->checkObjectExist_json(options, "layoutParameter"); if (layout) diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/CCSSceneReader.cpp index 12b18604ff..e33c4ad86a 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/CCSSceneReader.cpp @@ -203,7 +203,7 @@ void SceneReader::setPropertyFromJsonDict(const rapidjson::Value &root, cocos2d: node->setTag(nTag); int nZorder = DICTOOL->getIntValue_json(root, "zorder"); - node->setZOrder(nZorder); + node->setLocalZOrder(nZorder); float fScaleX = DICTOOL->getFloatValue_json(root, "scalex", 1.0); float fScaleY = DICTOOL->getFloatValue_json(root, "scaley", 1.0); diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index 1da40694f7..440ce92159 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -225,7 +225,7 @@ void Skin::draw() kmGLGetMatrix(KM_GL_MODELVIEW, &mv); //TODO implement z order - _quadCommand.init(_vertexZ, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, mv); + _quadCommand.init(_globalZOrder, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, mv); Director::getInstance()->getRenderer()->addCommand(&_quadCommand); } diff --git a/cocos/editor-support/spine/CCSkeleton.cpp b/cocos/editor-support/spine/CCSkeleton.cpp index c224e38d4e..82c0ed50cd 100644 --- a/cocos/editor-support/spine/CCSkeleton.cpp +++ b/cocos/editor-support/spine/CCSkeleton.cpp @@ -131,7 +131,7 @@ void Skeleton::draw() kmGLMatrixMode(KM_GL_MODELVIEW); kmGLGetMatrix(KM_GL_MODELVIEW, &_oldTransMatrix); - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Skeleton::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp index 691fb212a2..8a64ad7ed4 100644 --- a/cocos/gui/UILayout.cpp +++ b/cocos/gui/UILayout.cpp @@ -210,18 +210,18 @@ void Layout::stencilClippingVisit() Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand.init(_vertexZ); + _groupCommand.init(_globalZOrder); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); - _beforeVisitCmdStencil.init(_vertexZ); + _beforeVisitCmdStencil.init(_globalZOrder); _beforeVisitCmdStencil.func = CC_CALLBACK_0(Layout::onBeforeVisitStencil, this); renderer->addCommand(&_beforeVisitCmdStencil); _clippingStencil->visit(); - _afterDrawStencilCmd.init(_vertexZ); + _afterDrawStencilCmd.init(_globalZOrder); _afterDrawStencilCmd.func = CC_CALLBACK_0(Layout::onAfterDrawStencil, this); renderer->addCommand(&_afterDrawStencilCmd); @@ -251,7 +251,7 @@ void Layout::stencilClippingVisit() this->draw(); } - _afterVisitCmdStencil.init(_vertexZ); + _afterVisitCmdStencil.init(_globalZOrder); _afterVisitCmdStencil.func = CC_CALLBACK_0(Layout::onAfterVisitStencil, this); renderer->addCommand(&_afterVisitCmdStencil); @@ -336,13 +336,13 @@ void Layout::scissorClippingVisit() { Renderer* renderer = Director::getInstance()->getRenderer(); - _beforeVisitCmdScissor.init(_vertexZ); + _beforeVisitCmdScissor.init(_globalZOrder); _beforeVisitCmdScissor.func = CC_CALLBACK_0(Layout::onBeforeVisitScissor, this); renderer->addCommand(&_beforeVisitCmdScissor); Node::visit(); - _afterVisitCmdScissor.init(_vertexZ); + _afterVisitCmdScissor.init(_globalZOrder); _afterVisitCmdScissor.func = CC_CALLBACK_0(Layout::onAfterVisitScissor, this); renderer->addCommand(&_afterVisitCmdScissor); } @@ -651,14 +651,14 @@ void Layout::addBackGroundImage() if (_backGroundScale9Enabled) { _backGroundImage = extension::Scale9Sprite::create(); - _backGroundImage->setZOrder(-1); + _backGroundImage->setLocalZOrder(-1); Node::addChild(_backGroundImage, BACKGROUNDIMAGE_Z, -1); static_cast(_backGroundImage)->setPreferredSize(_size); } else { _backGroundImage = Sprite::create(); - _backGroundImage->setZOrder(-1); + _backGroundImage->setLocalZOrder(-1); Node::addChild(_backGroundImage, BACKGROUNDIMAGE_Z, -1); } _backGroundImage->setPosition(Point(_size.width/2.0f, _size.height/2.0f)); diff --git a/cocos/gui/UILayout.h b/cocos/gui/UILayout.h index fffb6aaad1..327707d7c8 100644 --- a/cocos/gui/UILayout.h +++ b/cocos/gui/UILayout.h @@ -195,7 +195,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) */ virtual void addChild(Node * child, int zOrder) override; /** @@ -204,7 +204,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) * @param tag A interger to identify the node easily. Please refer to setTag(int) */ virtual void addChild(Node* child, int zOrder, int tag) override; diff --git a/cocos/gui/UIListView.cpp b/cocos/gui/UIListView.cpp index ba6a567aef..8c732f6e70 100644 --- a/cocos/gui/UIListView.cpp +++ b/cocos/gui/UIListView.cpp @@ -378,7 +378,7 @@ void ListView::refreshView() for (int i=0; isetZOrder(i); + item->setLocalZOrder(i); remedyLayoutParameter(item); } updateInnerContainerSize(); diff --git a/cocos/gui/UIScrollView.h b/cocos/gui/UIScrollView.h index ae49fa02ea..0b196cef55 100644 --- a/cocos/gui/UIScrollView.h +++ b/cocos/gui/UIScrollView.h @@ -242,7 +242,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) */ virtual void addChild(Node * child, int zOrder) override; /** @@ -251,7 +251,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) * @param tag A interger to identify the node easily. Please refer to setTag(int) */ virtual void addChild(Node* child, int zOrder, int tag) override; diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index e28f4d8db0..d09a8fde39 100644 --- a/cocos/gui/UIWidget.cpp +++ b/cocos/gui/UIWidget.cpp @@ -1040,7 +1040,7 @@ void Widget::copyProperties(Widget *widget) setBright(widget->isBright()); setTouchEnabled(widget->isTouchEnabled()); _touchPassedEnabled = false; - setZOrder(widget->getZOrder()); + setLocalZOrder(widget->getLocalZOrder()); setTag(widget->getTag()); setName(widget->getName()); setActionTag(widget->getActionTag()); diff --git a/cocos/gui/UIWidget.h b/cocos/gui/UIWidget.h index d07bc4bee8..3827c60db2 100644 --- a/cocos/gui/UIWidget.h +++ b/cocos/gui/UIWidget.h @@ -212,7 +212,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) */ virtual void addChild(Node * child, int zOrder) override; /** @@ -221,7 +221,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) * @param tag A interger to identify the node easily. Please refer to setTag(int) */ virtual void addChild(Node* child, int zOrder, int tag) override; diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index bf7e667cc2..0c4fbe72a3 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -494,7 +494,7 @@ void ScrollView::addChild(Node * child, int zOrder, int tag) void ScrollView::beforeDraw() { - _beforeDrawCommand.init(_vertexZ); + _beforeDrawCommand.init(_globalZOrder); _beforeDrawCommand.func = CC_CALLBACK_0(ScrollView::onBeforeDraw, this); Director::getInstance()->getRenderer()->addCommand(&_beforeDrawCommand); } @@ -529,7 +529,7 @@ void ScrollView::onBeforeDraw() void ScrollView::afterDraw() { - _afterDrawCommand.init(_vertexZ); + _afterDrawCommand.init(_globalZOrder); _afterDrawCommand.func = CC_CALLBACK_0(ScrollView::onAfterDraw, this); Director::getInstance()->getRenderer()->addCommand(&_afterDrawCommand); } diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp index 1fea5ffa2a..b290364d39 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp @@ -1314,7 +1314,7 @@ void ActionFollow::onEnter() void ActionFollow::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ActionFollow::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); @@ -1630,7 +1630,7 @@ void ActionCatmullRomStacked::draw() kmGLPopMatrix(); kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ActionCatmullRomStacked::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -1745,7 +1745,7 @@ void ActionCardinalSplineStacked::draw() kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); kmGLPopMatrix(); - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ActionCardinalSplineStacked::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -2107,7 +2107,7 @@ void ActionCatmullRom::draw() kmGLPopMatrix(); kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ActionCatmullRom::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -2207,7 +2207,7 @@ void ActionCardinalSpline::draw() kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); kmGLPopMatrix(); - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ActionCardinalSpline::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp index 70e55dae5d..2dabe08a75 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp +++ b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp @@ -149,7 +149,7 @@ void Box2DTestLayer::draw() kmGLPushMatrix(); kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV); - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Box2DTestLayer::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp index ed1e08da29..2b05f4a60b 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp @@ -211,7 +211,7 @@ void Box2DView::draw() { Layer::draw(); - _customCmd.init(_vertexZ); + _customCmd.init(_globalZOrder); _customCmd.func = CC_CALLBACK_0(Box2DView::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCmd); } diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp index b73c205be3..829c8766dc 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -611,7 +611,7 @@ void RawStencilBufferTest::draw() auto iter = _renderCmds.begin(); - iter->init(_vertexZ); + iter->init(_globalZOrder); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onEnableStencil, this); renderer->addCommand(&(*iter)); ++iter; @@ -628,7 +628,7 @@ void RawStencilBufferTest::draw() spritePoint.y = 0; _sprites.at(i)->setPosition( spritePoint ); - iter->init(_vertexZ); + iter->init(_globalZOrder); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawClip, this, i, stencilPoint); renderer->addCommand(&(*iter)); ++iter; @@ -638,7 +638,7 @@ void RawStencilBufferTest::draw() _sprites.at(i)->visit(); kmGLPopMatrix(); - iter->init(_vertexZ); + iter->init(_globalZOrder); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawSprite, this, i, winPoint); renderer->addCommand(&(*iter)); ++iter; @@ -649,7 +649,7 @@ void RawStencilBufferTest::draw() kmGLPopMatrix(); } - iter->init(_vertexZ); + iter->init(_globalZOrder); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onDisableStencil, this); renderer->addCommand(&(*iter)); diff --git a/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp b/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp index 0e693d640a..622220f09d 100644 --- a/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp +++ b/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp @@ -116,7 +116,7 @@ DrawPrimitivesTest::DrawPrimitivesTest() void DrawPrimitivesTest::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(DrawPrimitivesTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 8e2a0119e4..88a63ce1f9 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -503,7 +503,7 @@ void TestChangeZorder::changeZorder(float dt) Node *node = getChildByTag(currentTag); - node->setZOrder(CCRANDOM_0_1() * 3); + node->setLocalZOrder(CCRANDOM_0_1() * 3); currentTag ++; currentTag = currentTag % 3; @@ -637,7 +637,7 @@ void TestParticleDisplay::onEnter() bone->addDisplay(p1, 0); bone->changeDisplayWithIndex(0, true); bone->setIgnoreMovementBoneData(true); - bone->setZOrder(100); + bone->setLocalZOrder(100); bone->setScale(1.2f); armature->addBone(bone, "bady-a3"); @@ -645,7 +645,7 @@ void TestParticleDisplay::onEnter() bone->addDisplay(p2, 0); bone->changeDisplayWithIndex(0, true); bone->setIgnoreMovementBoneData(true); - bone->setZOrder(100); + bone->setLocalZOrder(100); bone->setScale(1.2f); armature->addBone(bone, "bady-a30"); } @@ -1067,7 +1067,7 @@ void TestColliderDetector::update(float delta) } void TestColliderDetector::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(TestColliderDetector::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -1108,7 +1108,7 @@ std::string TestBoundingBox::title() const } void TestBoundingBox::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(TestBoundingBox::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp index a06f00d592..5253040a66 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp @@ -56,7 +56,7 @@ bool UIImageViewTest::init() _uiLayer->addChild(sprite); */ -// imageView->setZOrder(20); +// imageView->setLocalZOrder(20); return true; } diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp index af89de176c..e09dc7f4fc 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp @@ -210,7 +210,7 @@ void Atlas1::draw() // GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY // GL_TEXTURE_2D - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Atlas1::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); @@ -526,7 +526,7 @@ Atlas4::Atlas4() void Atlas4::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Atlas4::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -1612,7 +1612,7 @@ std::string LabelBMFontBounds::subtitle() const void LabelBMFontBounds::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(LabelBMFontBounds::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp index 91be90098d..a3dff56208 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp @@ -302,7 +302,7 @@ LabelFNTSpriteActions::LabelFNTSpriteActions() void LabelFNTSpriteActions::draw() { - _renderCmd.init(_vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(LabelFNTSpriteActions::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); @@ -912,7 +912,7 @@ std::string LabelFNTBounds::subtitle() const void LabelFNTBounds::draw() { - _renderCmd.init(_vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(LabelFNTBounds::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index 0cee1ffbd1..194a7bc74c 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -166,11 +166,11 @@ void TouchableSpriteTest::onEnter() target->setOpacity(255); if (target == sprite2) { - sprite1->setZOrder(100); + sprite1->setLocalZOrder(100); } else if(target == sprite1) { - sprite1->setZOrder(0); + sprite1->setLocalZOrder(0); } }; diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp index a0c70d62b5..290366c94c 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp @@ -67,6 +67,7 @@ static std::function createFunctions[] = CL(ConvertToNode), CL(NodeOpaqueTest), CL(NodeNonOpaqueTest), + CL(NodeGlobalZValueTest), }; #define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) @@ -905,6 +906,55 @@ std::string NodeNonOpaqueTest::subtitle() const return "Node rendered with GL_BLEND enabled"; } +/// NodeGlobalZValueTest + +NodeGlobalZValueTest::NodeGlobalZValueTest() +{ + Size s = Director::getInstance()->getWinSize(); + for (int i = 0; i < 9; i++) + { + Sprite *sprite; + auto parent = Node::create(); + if(i==4) { + sprite = Sprite::create("Images/grossinis_sister2.png"); + _sprite = sprite; + _sprite->setGlobalZOrder(-1); + } + else + sprite = Sprite::create("Images/grossinis_sister1.png"); + + parent->addChild(sprite); + this->addChild(parent); + + float w = sprite->getContentSize().width; + sprite->setPosition(s.width/2 - w*0.7*(i-5), s.height/2); + } + + this->scheduleUpdate(); +} + +void NodeGlobalZValueTest::update(float dt) +{ + static float accum = 0; + + accum += dt; + if( accum > 1) { + float z = _sprite->getGlobalZOrder(); + _sprite->setGlobalZOrder(-z); + accum = 0; + } +} + +std::string NodeGlobalZValueTest::title() const +{ + return "Global Z Value"; +} + +std::string NodeGlobalZValueTest::subtitle() const +{ + return "Center Sprite should change go from foreground to background"; +} + // // MySprite: Used by CameraTest1 and CameraTest2 @@ -932,7 +982,7 @@ protected: void MySprite::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(MySprite::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h index 2207c65f7c..334e2df08a 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h @@ -249,6 +249,20 @@ protected: NodeNonOpaqueTest(); }; +class NodeGlobalZValueTest : public TestCocosNodeDemo +{ +public: + CREATE_FUNC(NodeGlobalZValueTest); + virtual std::string title() const override; + virtual std::string subtitle() const override; + + virtual void update(float dt) override; + +protected: + NodeGlobalZValueTest(); + Sprite *_sprite; +}; + class CocosNodeTestScene : public TestScene { public: diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp index a90ce6aebc..e893f707f7 100644 --- a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp +++ b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp @@ -470,19 +470,19 @@ RenderTextureTestDepthStencil::~RenderTextureTestDepthStencil() void RenderTextureTestDepthStencil::draw() { - _renderCmds[0].init(_vertexZ); + _renderCmds[0].init(_globalZOrder); _renderCmds[0].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onBeforeClear, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[0]); _rend->beginWithClear(0, 0, 0, 0, 0, 0); - _renderCmds[1].init(_vertexZ); + _renderCmds[1].init(_globalZOrder); _renderCmds[1].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onBeforeStencil, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[1]); _spriteDS->visit(); - _renderCmds[2].init(_vertexZ); + _renderCmds[2].init(_globalZOrder); _renderCmds[2].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onBeforDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[2]); @@ -490,7 +490,7 @@ void RenderTextureTestDepthStencil::draw() _rend->end(); - _renderCmds[3].init(_vertexZ); + _renderCmds[3].init(_globalZOrder); _renderCmds[3].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onAfterDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[3]); @@ -638,7 +638,7 @@ SpriteRenderTextureBug::SimpleSprite* SpriteRenderTextureBug::SimpleSprite::crea void SpriteRenderTextureBug::SimpleSprite::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(SpriteRenderTextureBug::SimpleSprite::onBeforeDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp index 087644545e..443a24d681 100644 --- a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp @@ -193,7 +193,7 @@ void ShaderNode::setPosition(const Point &newPosition) void ShaderNode::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ShaderNode::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -526,7 +526,7 @@ void SpriteBlur::initProgram() void SpriteBlur::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(SpriteBlur::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp index 1d76e56892..e8207b4cb4 100644 --- a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp +++ b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp @@ -178,7 +178,7 @@ void ShaderSprite::initShader() void ShaderSprite::draw() { - _renderCommand.init(_vertexZ); + _renderCommand.init(_globalZOrder); _renderCommand.func = CC_CALLBACK_0(ShaderSprite::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCommand); diff --git a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp index 3324802c9d..a4121f8825 100644 --- a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp +++ b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp @@ -1794,7 +1794,7 @@ void TextureDrawAtPoint::draw() { TextureDemo::draw(); - _renderCmd.init(_vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(TextureDrawAtPoint::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); @@ -1835,7 +1835,7 @@ void TextureDrawInRect::draw() { TextureDemo::draw(); - _renderCmd.init(_vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(TextureDrawInRect::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); diff --git a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp index 68f3cd5d59..1b45442fd5 100644 --- a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp @@ -599,7 +599,7 @@ TMXOrthoObjectsTest::TMXOrthoObjectsTest() void TMXOrthoObjectsTest::draw() { - _renderCmd.init(_vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(TMXOrthoObjectsTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } @@ -672,7 +672,7 @@ TMXIsoObjectsTest::TMXIsoObjectsTest() void TMXIsoObjectsTest::draw() { - _renderCmd.init(_vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(TMXIsoObjectsTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } @@ -1504,7 +1504,7 @@ TMXGIDObjectsTest::TMXGIDObjectsTest() void TMXGIDObjectsTest::draw() { - _renderCmd.init(_vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(TMXGIDObjectsTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } From 5fcbf42356675a9dc16380e677ef86c4768dad8d Mon Sep 17 00:00:00 2001 From: Ricardo Quesada Date: Sat, 18 Jan 2014 11:35:27 -0800 Subject: [PATCH 162/193] GlobalZOrder is used for render priority... ...and not vertexZ Node::setGlobalZOrder() is used to change that. Node::setZOrder() -> Node::setLocalZOrder(); --- CHANGELOG | 3 +- .../project.pbxproj.REMOVED.git-id | 2 +- .../project.pbxproj.REMOVED.git-id | 2 +- cocos/2d/CCAtlasNode.cpp | 2 +- cocos/2d/CCClippingNode.cpp | 8 +- cocos/2d/CCDrawNode.cpp | 2 +- cocos/2d/CCLabel.cpp | 2 +- cocos/2d/CCLayer.cpp | 2 +- cocos/2d/CCMotionStreak.cpp | 2 +- cocos/2d/CCNode.cpp | 33 +++---- cocos/2d/CCNode.h | 92 +++++++++++++------ cocos/2d/CCNodeGrid.cpp | 6 +- cocos/2d/CCParticleBatchNode.cpp | 6 +- cocos/2d/CCParticleSystemQuad.cpp | 2 +- cocos/2d/CCProgressTimer.cpp | 2 +- cocos/2d/CCRenderTexture.cpp | 12 +-- cocos/2d/CCSprite.cpp | 11 +-- cocos/2d/CCSpriteBatchNode.cpp | 2 +- cocos/2d/CCTransitionPageTurn.cpp | 8 +- cocos/2d/renderer/CCBatchCommand.cpp | 6 +- cocos/2d/renderer/CCBatchCommand.h | 2 +- cocos/2d/renderer/CCCustomCommand.cpp | 6 +- cocos/2d/renderer/CCCustomCommand.h | 2 +- cocos/2d/renderer/CCGroupCommand.cpp | 4 +- cocos/2d/renderer/CCQuadCommand.cpp | 4 +- cocos/2d/renderer/CCRenderCommand.cpp | 4 +- cocos/2d/renderer/CCRenderCommand.h | 4 +- cocos/2d/renderer/CCRenderer.cpp | 20 ++-- cocos/2d/renderer/CCRenderer.h | 2 +- .../editor-support/cocostudio/CCBatchNode.cpp | 2 +- cocos/editor-support/cocostudio/CCBone.cpp | 12 +-- cocos/editor-support/cocostudio/CCBone.h | 2 +- .../cocostudio/CCSGUIReader.cpp | 4 +- .../cocostudio/CCSSceneReader.cpp | 2 +- cocos/editor-support/cocostudio/CCSkin.cpp | 2 +- cocos/editor-support/spine/CCSkeleton.cpp | 2 +- cocos/gui/UILayout.cpp | 16 ++-- cocos/gui/UILayout.h | 4 +- cocos/gui/UIListView.cpp | 2 +- cocos/gui/UIScrollView.h | 4 +- cocos/gui/UIWidget.cpp | 2 +- cocos/gui/UIWidget.h | 4 +- extensions/GUI/CCScrollView/CCScrollView.cpp | 4 +- .../Classes/ActionsTest/ActionsTest.cpp | 10 +- .../TestCpp/Classes/Box2DTest/Box2dTest.cpp | 2 +- .../Classes/Box2DTestBed/Box2dView.cpp | 2 +- .../ClippingNodeTest/ClippingNodeTest.cpp | 8 +- .../DrawPrimitivesTest/DrawPrimitivesTest.cpp | 2 +- .../CocoStudioArmatureTest/ArmatureScene.cpp | 10 +- .../UIImageViewTest/UIImageViewTest.cpp | 2 +- .../TestCpp/Classes/LabelTest/LabelTest.cpp | 6 +- .../Classes/LabelTest/LabelTestNew.cpp | 4 +- .../NewEventDispatcherTest.cpp | 4 +- .../Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp | 52 ++++++++++- .../Cpp/TestCpp/Classes/NodeTest/NodeTest.h | 14 +++ .../RenderTextureTest/RenderTextureTest.cpp | 10 +- .../TestCpp/Classes/ShaderTest/ShaderTest.cpp | 4 +- .../Classes/ShaderTest/ShaderTest2.cpp | 2 +- .../Classes/Texture2dTest/Texture2dTest.cpp | 4 +- .../Classes/TileMapTest/TileMapTest.cpp | 6 +- 60 files changed, 272 insertions(+), 185 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 1497c22df8..d2c95e4eca 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,10 +1,11 @@ -cocos2d-x-3.0final ?.? ? +cocos2d-x-3.0beta2 ?.? ? [All] [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands [NEW] GLCache: glActiveTexture() is cached with GL::activeTexture(). All code MUST call the cached version in order to work correctly [NEW] Label: Uses a struct of TTF configuration for Label::createWithTTF to reduce parameters and make this interface more easily to use. [NEW] Label: Integrates LabelAtlas into new Label. + [NEW] Node: Added `setGlobalZOrder()`. Useful to change the Node's render order. Node::setZOrder() -> Node::setLocalZOrder() [NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10% [NEW] LuaBindings: Bindings-generator supports to bind namespace for lua. diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index b052741ae6..a520602c3d 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -e1e5a1169e92834330092c45165660c6cbd03609 \ No newline at end of file +63e6598ea5798bf42bbd22c2295e65f7c739695a \ No newline at end of file diff --git a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id index bb3a11cb54..eac7e38de9 100644 --- a/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_samples.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -1fa58d8cba77ef923c83d2860d5511d28dad6c27 \ No newline at end of file +447e7ba37294e6da0df2e02f5a62f30fb15e3272 \ No newline at end of file diff --git a/cocos/2d/CCAtlasNode.cpp b/cocos/2d/CCAtlasNode.cpp index 03eb16ba18..15492a651f 100644 --- a/cocos/2d/CCAtlasNode.cpp +++ b/cocos/2d/CCAtlasNode.cpp @@ -153,7 +153,7 @@ void AtlasNode::draw(void) auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); _quadCommand.init( - _vertexZ, + _globalZOrder, _textureAtlas->getTexture()->getName(), shader, _blendFunc, diff --git a/cocos/2d/CCClippingNode.cpp b/cocos/2d/CCClippingNode.cpp index 55be0ef5a8..f20b4d2778 100644 --- a/cocos/2d/CCClippingNode.cpp +++ b/cocos/2d/CCClippingNode.cpp @@ -210,12 +210,12 @@ void ClippingNode::visit() Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand.init(_vertexZ); + _groupCommand.init(_globalZOrder); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); - _beforeVisitCmd.init(_vertexZ); + _beforeVisitCmd.init(_globalZOrder); _beforeVisitCmd.func = CC_CALLBACK_0(ClippingNode::onBeforeVisit, this); renderer->addCommand(&_beforeVisitCmd); if (_alphaThreshold < 1) @@ -238,7 +238,7 @@ void ClippingNode::visit() } _stencil->visit(); - _afterDrawStencilCmd.init(_vertexZ); + _afterDrawStencilCmd.init(_globalZOrder); _afterDrawStencilCmd.func = CC_CALLBACK_0(ClippingNode::onAfterDrawStencil, this); renderer->addCommand(&_afterDrawStencilCmd); @@ -268,7 +268,7 @@ void ClippingNode::visit() this->draw(); } - _afterVisitCmd.init(_vertexZ); + _afterVisitCmd.init(_globalZOrder); _afterVisitCmd.func = CC_CALLBACK_0(ClippingNode::onAfterVisit, this); renderer->addCommand(&_afterVisitCmd); diff --git a/cocos/2d/CCDrawNode.cpp b/cocos/2d/CCDrawNode.cpp index 0e28ee554f..003209b6e4 100644 --- a/cocos/2d/CCDrawNode.cpp +++ b/cocos/2d/CCDrawNode.cpp @@ -241,7 +241,7 @@ void DrawNode::render() void DrawNode::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(DrawNode::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index c96678fc57..0cac300283 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -666,7 +666,7 @@ void Label::onDraw() void Label::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Label::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/cocos/2d/CCLayer.cpp b/cocos/2d/CCLayer.cpp index 83629a50ec..54b9c48cd9 100644 --- a/cocos/2d/CCLayer.cpp +++ b/cocos/2d/CCLayer.cpp @@ -565,7 +565,7 @@ void LayerColor::updateColor() void LayerColor::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(LayerColor::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/cocos/2d/CCMotionStreak.cpp b/cocos/2d/CCMotionStreak.cpp index 2dc1f49fbb..735a8edae2 100644 --- a/cocos/2d/CCMotionStreak.cpp +++ b/cocos/2d/CCMotionStreak.cpp @@ -359,7 +359,7 @@ void MotionStreak::draw() if(_nuPoints <= 1) return; kmGLGetMatrix(KM_GL_MODELVIEW,&_cachedMV); - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(MotionStreak::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 3b7ce1c47c..e631d0f02a 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -108,7 +108,8 @@ Node::Node(void) , _inverseDirty(true) // children (lazy allocs) // lazy alloc -, _ZOrder(0) +, _localZOrder(0) +, _globalZOrder(0) , _parent(nullptr) // "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true , _tag(Node::INVALID_TAG) @@ -212,29 +213,22 @@ void Node::setSkewY(float newSkewY) _transformDirty = _inverseDirty = true; } -/// zOrder getter -int Node::getZOrder() const -{ - return _ZOrder; -} /// zOrder setter : private method /// used internally to alter the zOrder variable. DON'T call this method manually -void Node::_setZOrder(int z) +void Node::_setLocalZOrder(int z) { - _ZOrder = z; + _localZOrder = z; } -void Node::setZOrder(int z) +void Node::setLocalZOrder(int z) { + _localZOrder = z; if (_parent) { _parent->reorderChild(this, z); } - // should set "_ZOrder" after reorderChild, because the implementation of reorderChild subclass of Node, such as Sprite, - // will return when _ZOrder value is not changed - _setZOrder(z); - + _eventDispatcher->setDirtyForNode(this); } @@ -246,9 +240,10 @@ float Node::getVertexZ() const /// vertexZ setter -void Node::setVertexZ(float var) +void Node::setVertexZ(float zOrder) { - _vertexZ = var; + _vertexZ = zOrder; + setGlobalZOrder(zOrder); } @@ -650,7 +645,7 @@ void Node::addChild(Node *child, int zOrder) void Node::addChild(Node *child) { CCASSERT( child != nullptr, "Argument must be non-nil"); - this->addChild(child, child->_ZOrder, child->_tag); + this->addChild(child, child->_localZOrder, child->_tag); } void Node::removeFromParent() @@ -767,7 +762,7 @@ void Node::insertChild(Node* child, int z) { _reorderChildDirty = true; _children.pushBack(child); - child->_setZOrder(z); + child->_setLocalZOrder(z); } void Node::reorderChild(Node *child, int zOrder) @@ -775,7 +770,7 @@ void Node::reorderChild(Node *child, int zOrder) CCASSERT( child != nullptr, "Child must be non-nil"); _reorderChildDirty = true; child->setOrderOfArrival(s_globalOrderOfArrival++); - child->_setZOrder(zOrder); + child->_setLocalZOrder(zOrder); } void Node::sortAllChildren() @@ -816,7 +811,7 @@ void Node::visit() { auto node = _children.at(i); - if ( node && node->_ZOrder < 0 ) + if ( node && node->_localZOrder < 0 ) node->visit(); else break; diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 3069fb0a84..0598773a7c 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -161,43 +161,72 @@ public: /// @name Setters & Getters for Graphic Peroperties /** - * Sets the Z order which stands for the drawing order, and reorder this node in its parent's children array. - * - * The Z order of node is relative to its siblings. - * It is not related to the OpenGL's z property. This one only affects the draw order of itself and its siblings. - * Lower Z order number are drawn before higher numbers. - * Please refer to `setVertexZ(float)` for the difference. - * - * @param zOrder Z order of this node. + LocalZOrder is the 'key' used to sort the node relative to its siblings. + + The Node's parent will sort all its children based ont the LocalZOrder value. + If two nodes have the same LocalZOrder, then the node that was added first to the children's array will be in front of the other node in the array. + + Also, the Scene Graph is traversed using the "In-Order" tree traversal algorithm ( http://en.wikipedia.org/wiki/Tree_traversal#In-order ) + And Nodes that have LocalZOder values < 0 are the "left" subtree + While Nodes with LocalZOder >=0 are the "right" subtree. + + @see `setGlobalZOrder` + @see `setVertexZ` */ - virtual void setZOrder(int zOrder); - /* - * Sets the z order which stands for the drawing order - * - * This is an internal method. Don't call it outside the framework. - * The difference between setZOrder(int) and _setOrder(int) is: - * - _setZOrder(int) is a pure setter for _ZOrder memeber variable - * - setZOrder(int) firstly changes _ZOrder, then recorder this node in its parent's chilren array. + virtual void setLocalZOrder(int zOrder); + + CC_DEPRECATED_ATTRIBUTE virtual void setZOrder(int zOrder) { setLocalZOrder(zOrder); } + /* Helper function used by `setLocalZOrder`. Don't use it unless you know what you are doing. */ - virtual void _setZOrder(int z); + virtual void _setLocalZOrder(int z); /** - * Gets the Z order of this node. + * Gets the local Z order of this node. * - * @see `setZOrder(int)` + * @see `setLocalZOrder(int)` * - * @return The Z order. + * @return The local (relative to its siblings) Z order. */ - virtual int getZOrder() const; + virtual int getLocalZOrder() const { return _localZOrder; } + CC_DEPRECATED_ATTRIBUTE virtual int getZOrder() const { return getLocalZOrder(); } /** - * Sets the real OpenGL Z vertex. + Defines the oder in which the nodes are renderer. + Nodes that have a Global Z Order lower, are renderer first. + + In case two or more nodes have the same Global Z Order, the oder is not guaranteed. + The only exception if the Nodes have a Global Z Order == 0. In that case, the Scene Graph order is used. + + By default, all nodes have a Global Z Order = 0. That means that by default, the Scene Graph order is used to render the nodes. + + Global Z Order is useful when you need to render nodes in an order different than the Scene Graph order. + + Limitations: Global Z Order can't be used used by Nodes that have SpriteBatchNode as one of their acenstors. + And if ClippingNode is one of the ancestors, then "global Z order" will be relative to the ClippingNode. + + @see `setLocalZOrder()` + @see `setVertexZ()` + + @since v3.0 + */ + virtual void setGlobalZOrder(float zOrder) { _globalZOrder = zOrder; } + /** + * Returns the Node's Global Z Order. * - * Differences between openGL Z vertex and cocos2d Z order: - * - OpenGL Z modifies the Z vertex, and not the Z order in the relation between parent-children - * - OpenGL Z might require to set 2D projection - * - cocos2d Z order works OK if all the nodes uses the same openGL Z vertex. eg: `vertexZ = 0` + * @see `setGlobalZOrder(int)` * - * @warning Use it at your own risk since it might break the cocos2d parent-children z order + * @return The node's global Z order + */ + virtual float getGlobalZOrder() const { return _globalZOrder; } + + /** + * Sets the 'z' value in the OpenGL Depth Buffer. + * + * The OpenGL depth buffer and depth testing are disabled by default. You need to turn them on + * in order to use this property correctly. + * + * `setVertexZ()` also sets the `setGlobalZValue()` with the vertexZ value. + * + * @see `setGlobalZValue()` * * @param vertexZ OpenGL Z vertex of this node. */ @@ -1411,7 +1440,6 @@ protected: float _scaleX; ///< scaling factor on x-axis float _scaleY; ///< scaling factor on y-axis - float _vertexZ; ///< OpenGL real Z vertex Point _position; ///< position of the node @@ -1433,8 +1461,12 @@ protected: mutable bool _transformDirty; ///< transform dirty flag mutable bool _inverseDirty; ///< inverse transform dirty flag - int _ZOrder; ///< z-order value that affects the draw order - + + int _localZOrder; ///< Local order (relative to its siblings) used to sort the node + float _globalZOrder; ///< Global order used to sort the node + float _vertexZ; ///< OpenGL real Z vertex + + Vector _children; ///< array of children nodes Node *_parent; ///< weak reference to parent node diff --git a/cocos/2d/CCNodeGrid.cpp b/cocos/2d/CCNodeGrid.cpp index 9f359cf778..f8c5d5accb 100644 --- a/cocos/2d/CCNodeGrid.cpp +++ b/cocos/2d/CCNodeGrid.cpp @@ -92,7 +92,7 @@ void NodeGrid::visit() Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand.init(_vertexZ); + _groupCommand.init(_globalZOrder); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); @@ -104,7 +104,7 @@ void NodeGrid::visit() _nodeGrid->set2DProjection(); } - _gridBeginCommand.init(_vertexZ); + _gridBeginCommand.init(_globalZOrder); _gridBeginCommand.func = CC_CALLBACK_0(NodeGrid::onGridBeginDraw, this); renderer->addCommand(&_gridBeginCommand); @@ -152,7 +152,7 @@ void NodeGrid::visit() director->setProjection(beforeProjectionType); } - _gridEndCommand.init(_vertexZ); + _gridEndCommand.init(_globalZOrder); _gridEndCommand.func = CC_CALLBACK_0(NodeGrid::onGridEndDraw, this); renderer->addCommand(&_gridEndCommand); diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index d64d682ce3..bca1c3eb28 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -197,7 +197,7 @@ int ParticleBatchNode::addChildHelper(ParticleSystem* child, int z, int aTag) _children.insert(pos, child); child->setTag(aTag); - child->_setZOrder(z); + child->_setLocalZOrder(z); child->setParent(this); @@ -264,7 +264,7 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder) } } - child->_setZOrder(zOrder); + child->_setLocalZOrder(zOrder); } void ParticleBatchNode::getCurrentIndex(int* oldIndex, int* newIndex, Node* child, int z) @@ -383,7 +383,7 @@ void ParticleBatchNode::draw(void) } _batchCommand.init( - _vertexZ, + _globalZOrder, _textureAtlas->getTexture()->getName(), _shaderProgram, _blendFunc, diff --git a/cocos/2d/CCParticleSystemQuad.cpp b/cocos/2d/CCParticleSystemQuad.cpp index cf3725e1a2..bd4bef3599 100644 --- a/cocos/2d/CCParticleSystemQuad.cpp +++ b/cocos/2d/CCParticleSystemQuad.cpp @@ -439,7 +439,7 @@ void ParticleSystemQuad::draw() auto shader = ShaderCache::getInstance()->getProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP); - _quadCommand.init(_vertexZ, _texture->getName(), shader, _blendFunc, _quads, _particleIdx, _modelViewTransform); + _quadCommand.init(_globalZOrder, _texture->getName(), shader, _blendFunc, _quads, _particleIdx, _modelViewTransform); Director::getInstance()->getRenderer()->addCommand(&_quadCommand); } diff --git a/cocos/2d/CCProgressTimer.cpp b/cocos/2d/CCProgressTimer.cpp index b8332e0442..112b34d85b 100644 --- a/cocos/2d/CCProgressTimer.cpp +++ b/cocos/2d/CCProgressTimer.cpp @@ -555,7 +555,7 @@ void ProgressTimer::draw() if( ! _vertexData || ! _sprite) return; - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ProgressTimer::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/cocos/2d/CCRenderTexture.cpp b/cocos/2d/CCRenderTexture.cpp index 63bc1a596d..57b6a00d24 100644 --- a/cocos/2d/CCRenderTexture.cpp +++ b/cocos/2d/CCRenderTexture.cpp @@ -322,7 +322,7 @@ void RenderTexture::beginWithClear(float r, float g, float b, float a, float dep this->begin(); //clear screen - _beginWithClearCommand.init(_vertexZ); + _beginWithClearCommand.init(_globalZOrder); _beginWithClearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this); Director::getInstance()->getRenderer()->addCommand(&_beginWithClearCommand); } @@ -340,7 +340,7 @@ void RenderTexture::clearDepth(float depthValue) this->begin(); - _clearDepthCommand.init(_vertexZ); + _clearDepthCommand.init(_globalZOrder); _clearDepthCommand.func = CC_CALLBACK_0(RenderTexture::onClearDepth, this); Director::getInstance()->getRenderer()->addCommand(&_clearDepthCommand); @@ -605,7 +605,7 @@ void RenderTexture::draw() begin(); //clear screen - _clearCommand.init(_vertexZ); + _clearCommand.init(_globalZOrder); _clearCommand.func = CC_CALLBACK_0(RenderTexture::onClear, this); Director::getInstance()->getRenderer()->addCommand(&_clearCommand); @@ -648,13 +648,13 @@ void RenderTexture::begin() (float)-1.0 / heightRatio, (float)1.0 / heightRatio, -1,1 ); kmGLMultMatrix(&orthoMatrix); - _groupCommand.init(_vertexZ); + _groupCommand.init(_globalZOrder); Renderer *renderer = Director::getInstance()->getRenderer(); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); - _beginCommand.init(_vertexZ); + _beginCommand.init(_globalZOrder); _beginCommand.func = CC_CALLBACK_0(RenderTexture::onBegin, this); Director::getInstance()->getRenderer()->addCommand(&_beginCommand); @@ -662,7 +662,7 @@ void RenderTexture::begin() void RenderTexture::end() { - _endCommand.init(_vertexZ); + _endCommand.init(_globalZOrder); _endCommand.func = CC_CALLBACK_0(RenderTexture::onEnd, this); Renderer *renderer = Director::getInstance()->getRenderer(); diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index fafb509a6b..65c7a24b50 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -670,7 +670,7 @@ void Sprite::updateTransform(void) void Sprite::draw(void) { //TODO implement z order - _quadCommand.init(_vertexZ, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, _modelViewTransform); + _quadCommand.init(_globalZOrder, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, _modelViewTransform); // if(culling()) { @@ -769,13 +769,8 @@ void Sprite::addChild(Node *child, int zOrder, int tag) void Sprite::reorderChild(Node *child, int zOrder) { - CCASSERT(child != nullptr, ""); - CCASSERT(_children.contains(child), ""); - - if (zOrder == child->getZOrder()) - { - return; - } + CCASSERT(child != nullptr, "child must be non null"); + CCASSERT(_children.contains(child), "child does not belong to this"); if( _batchNode && ! _reorderChildDirty) { diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 6237f92b19..0526b6768d 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -357,7 +357,7 @@ void SpriteBatchNode::draw() child->updateTransform(); _batchCommand.init( - _vertexZ, + _globalZOrder, _textureAtlas->getTexture()->getName(), _shaderProgram, _blendFunc, diff --git a/cocos/2d/CCTransitionPageTurn.cpp b/cocos/2d/CCTransitionPageTurn.cpp index c42bf6e9d2..7e4102b009 100644 --- a/cocos/2d/CCTransitionPageTurn.cpp +++ b/cocos/2d/CCTransitionPageTurn.cpp @@ -98,23 +98,23 @@ void TransitionPageTurn::draw() if( _isInSceneOnTop ) { _outSceneProxy->visit(); - _enableOffsetCmd.init(_vertexZ); + _enableOffsetCmd.init(_globalZOrder); _enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd); _inSceneProxy->visit(); - _disableOffsetCmd.init(_vertexZ); + _disableOffsetCmd.init(_globalZOrder); _disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd); } else { _inSceneProxy->visit(); - _enableOffsetCmd.init(_vertexZ); + _enableOffsetCmd.init(_globalZOrder); _enableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onEnablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_enableOffsetCmd); _outSceneProxy->visit(); - _disableOffsetCmd.init(_vertexZ); + _disableOffsetCmd.init(_globalZOrder); _disableOffsetCmd.func = CC_CALLBACK_0(TransitionPageTurn::onDisablePolygonOffset, this); Director::getInstance()->getRenderer()->addCommand(&_disableOffsetCmd); } diff --git a/cocos/2d/renderer/CCBatchCommand.cpp b/cocos/2d/renderer/CCBatchCommand.cpp index 9c60b37455..b9b0c7fab9 100644 --- a/cocos/2d/renderer/CCBatchCommand.cpp +++ b/cocos/2d/renderer/CCBatchCommand.cpp @@ -38,9 +38,9 @@ BatchCommand::BatchCommand() _shader = nullptr; } -void BatchCommand::init(float depth, GLuint textureID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform) +void BatchCommand::init(float globalOrder, GLuint textureID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform) { - _depth = depth; + _globalOrder = globalOrder; _textureID = textureID; _blendType = blendType; _shader = shader; @@ -54,7 +54,7 @@ BatchCommand::~BatchCommand() { } -void BatchCommand::execute() const +void BatchCommand::execute() { // Set material _shader->use(); diff --git a/cocos/2d/renderer/CCBatchCommand.h b/cocos/2d/renderer/CCBatchCommand.h index 4ad2e7ae34..9ac5b346ee 100644 --- a/cocos/2d/renderer/CCBatchCommand.h +++ b/cocos/2d/renderer/CCBatchCommand.h @@ -45,7 +45,7 @@ public: void init(float depth, GLuint texutreID, GLProgram* shader, BlendFunc blendType, TextureAtlas *textureAtlas, const kmMat4& modelViewTransform); - void execute() const; + void execute(); protected: int32_t _materialID; diff --git a/cocos/2d/renderer/CCCustomCommand.cpp b/cocos/2d/renderer/CCCustomCommand.cpp index c521928921..c324032116 100644 --- a/cocos/2d/renderer/CCCustomCommand.cpp +++ b/cocos/2d/renderer/CCCustomCommand.cpp @@ -32,9 +32,9 @@ CustomCommand::CustomCommand() _type = RenderCommand::Type::CUSTOM_COMMAND; } -void CustomCommand::init(float depth) +void CustomCommand::init(float globalOrder) { - _depth = depth; + _globalOrder = globalOrder; } CustomCommand::~CustomCommand() @@ -42,7 +42,7 @@ CustomCommand::~CustomCommand() } -void CustomCommand::execute() const +void CustomCommand::execute() { if(func) { diff --git a/cocos/2d/renderer/CCCustomCommand.h b/cocos/2d/renderer/CCCustomCommand.h index 5bf149363e..03fdead69a 100644 --- a/cocos/2d/renderer/CCCustomCommand.h +++ b/cocos/2d/renderer/CCCustomCommand.h @@ -41,7 +41,7 @@ public: void init(float depth); - void execute() const; + void execute(); inline bool isTranslucent() { return true; } std::function func; diff --git a/cocos/2d/renderer/CCGroupCommand.cpp b/cocos/2d/renderer/CCGroupCommand.cpp index 70496b5d1d..95b9a5ccb5 100644 --- a/cocos/2d/renderer/CCGroupCommand.cpp +++ b/cocos/2d/renderer/CCGroupCommand.cpp @@ -91,9 +91,9 @@ GroupCommand::GroupCommand() _renderQueueID = GroupCommandManager::getInstance()->getGroupID(); } -void GroupCommand::init(float depth) +void GroupCommand::init(float globalOrder) { - _depth = depth; + _globalOrder = globalOrder; GroupCommandManager::getInstance()->releaseGroupID(_renderQueueID); _renderQueueID = GroupCommandManager::getInstance()->getGroupID(); } diff --git a/cocos/2d/renderer/CCQuadCommand.cpp b/cocos/2d/renderer/CCQuadCommand.cpp index 333fd834d2..9cae10d701 100644 --- a/cocos/2d/renderer/CCQuadCommand.cpp +++ b/cocos/2d/renderer/CCQuadCommand.cpp @@ -38,9 +38,9 @@ QuadCommand::QuadCommand() _quads = nullptr; } -void QuadCommand::init(float depth, GLuint textureID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, const kmMat4 &mv) +void QuadCommand::init(float globalOrder, GLuint textureID, GLProgram* shader, BlendFunc blendType, V3F_C4B_T2F_Quad* quad, ssize_t quadCount, const kmMat4 &mv) { - _depth = depth; + _globalOrder = globalOrder; _textureID = textureID; _blendType = blendType; _shader = shader; diff --git a/cocos/2d/renderer/CCRenderCommand.cpp b/cocos/2d/renderer/CCRenderCommand.cpp index 64157b4739..578f28d426 100644 --- a/cocos/2d/renderer/CCRenderCommand.cpp +++ b/cocos/2d/renderer/CCRenderCommand.cpp @@ -29,7 +29,7 @@ NS_CC_BEGIN RenderCommand::RenderCommand() : _type(RenderCommand::Type::UNKNOWN_COMMAND) -, _depth(0) +, _globalOrder(0) { } @@ -57,7 +57,7 @@ void printBits(ssize_t const size, void const * const ptr) void RenderCommand::printID() { - printf("Command Depth: %f\n", _depth); + printf("Command Depth: %f\n", _globalOrder); } NS_CC_END \ No newline at end of file diff --git a/cocos/2d/renderer/CCRenderCommand.h b/cocos/2d/renderer/CCRenderCommand.h index adb47f2f12..688f65feb7 100644 --- a/cocos/2d/renderer/CCRenderCommand.h +++ b/cocos/2d/renderer/CCRenderCommand.h @@ -50,7 +50,7 @@ public: }; /** Get Render Command Id */ - inline float getDepth() const { return _depth; } + inline float getGlobalOrder() const { return _globalOrder; } /** Returns the Command type */ inline Type getType() const { return _type; } @@ -65,7 +65,7 @@ protected: Type _type; // commands are sort by depth - float _depth; + float _globalOrder; }; NS_CC_END diff --git a/cocos/2d/renderer/CCRenderer.cpp b/cocos/2d/renderer/CCRenderer.cpp index 4a137295fe..6642ddfd6c 100644 --- a/cocos/2d/renderer/CCRenderer.cpp +++ b/cocos/2d/renderer/CCRenderer.cpp @@ -34,21 +34,21 @@ #include "CCEventDispatcher.h" #include "CCEventListenerCustom.h" #include "CCEventType.h" -#include // for std::stable_sort +#include NS_CC_BEGIN bool compareRenderCommand(RenderCommand* a, RenderCommand* b) { - return a->getDepth() < b->getDepth(); + return a->getGlobalOrder() < b->getGlobalOrder(); } void RenderQueue::push_back(RenderCommand* command) { - float z = command->getDepth(); + float z = command->getGlobalOrder(); if(z < 0) _queueNegZ.push_back(command); - if(z > 0) + else if(z > 0) _queuePosZ.push_back(command); else _queue0.push_back(command); @@ -66,7 +66,7 @@ void RenderQueue::sort() std::sort(std::begin(_queuePosZ), std::end(_queuePosZ), compareRenderCommand); } -const RenderCommand* RenderQueue::operator[](ssize_t index) const +RenderCommand* RenderQueue::operator[](ssize_t index) const { if(index < _queueNegZ.size()) return _queueNegZ[index]; @@ -295,7 +295,7 @@ void Renderer::render() if(commandType == RenderCommand::Type::QUAD_COMMAND) { - auto cmd = static_cast(command); + auto cmd = static_cast(command); ssize_t cmdQuadCount = cmd->getQuadCount(); //Batch quads @@ -317,19 +317,19 @@ void Renderer::render() else if(commandType == RenderCommand::Type::CUSTOM_COMMAND) { flush(); - auto cmd = static_cast(command); + auto cmd = static_cast(command); cmd->execute(); } else if(commandType == RenderCommand::Type::BATCH_COMMAND) { flush(); - auto cmd = static_cast(command); + auto cmd = static_cast(command); cmd->execute(); } else if(commandType == RenderCommand::Type::GROUP_COMMAND) { flush(); - auto cmd = static_cast(command); + auto cmd = static_cast(command); _renderStack.top().currentIndex = i + 1; @@ -467,7 +467,7 @@ void Renderer::drawBatchedQuads() auto command = _renderGroups[_renderStack.top().renderQueueID][i]; if (command->getType() == RenderCommand::Type::QUAD_COMMAND) { - auto cmd = static_cast(command); + auto cmd = static_cast(command); if(_lastMaterialID != cmd->getMaterialID()) { //Draw quads diff --git a/cocos/2d/renderer/CCRenderer.h b/cocos/2d/renderer/CCRenderer.h index 0921fa6bc7..39511a04f0 100644 --- a/cocos/2d/renderer/CCRenderer.h +++ b/cocos/2d/renderer/CCRenderer.h @@ -49,7 +49,7 @@ public: void push_back(RenderCommand* command); ssize_t size() const; void sort(); - const RenderCommand* operator[](ssize_t index) const; + RenderCommand* operator[](ssize_t index) const; void clear(); protected: diff --git a/cocos/editor-support/cocostudio/CCBatchNode.cpp b/cocos/editor-support/cocostudio/CCBatchNode.cpp index 20f034c35b..752e4911a9 100644 --- a/cocos/editor-support/cocostudio/CCBatchNode.cpp +++ b/cocos/editor-support/cocostudio/CCBatchNode.cpp @@ -156,7 +156,7 @@ void BatchNode::draw() void BatchNode::generateGroupCommand() { Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand->init(_vertexZ); + _groupCommand->init(_globalZOrder); renderer->addCommand(_groupCommand); renderer->pushGroup(_groupCommand->getRenderQueueID()); diff --git a/cocos/editor-support/cocostudio/CCBone.cpp b/cocos/editor-support/cocostudio/CCBone.cpp index 4bd7883a43..dbaa142020 100644 --- a/cocos/editor-support/cocostudio/CCBone.cpp +++ b/cocos/editor-support/cocostudio/CCBone.cpp @@ -145,7 +145,7 @@ void Bone::setBoneData(BoneData *boneData) } _name = _boneData->name; - _ZOrder = _boneData->zOrder; + _localZOrder = _boneData->zOrder; _displayManager->initDisplayList(boneData); } @@ -283,11 +283,11 @@ void Bone::updateZOrder() if (_dataVersion >= VERSION_COMBINED) { int zorder = _tweenData->zOrder + _boneData->zOrder; - setZOrder(zorder); + setLocalZOrder(zorder); } else { - setZOrder(_tweenData->zOrder); + setLocalZOrder(_tweenData->zOrder); } } @@ -374,10 +374,10 @@ Tween *Bone::getTween() return _tween; } -void Bone::setZOrder(int zOrder) +void Bone::setLocalZOrder(int zOrder) { - if (_ZOrder != zOrder) - Node::setZOrder(zOrder); + if (_localZOrder != zOrder) + Node::setLocalZOrder(zOrder); } kmMat4 Bone::getNodeToArmatureTransform() const diff --git a/cocos/editor-support/cocostudio/CCBone.h b/cocos/editor-support/cocostudio/CCBone.h index db153a1da5..c81583a8c9 100644 --- a/cocos/editor-support/cocostudio/CCBone.h +++ b/cocos/editor-support/cocostudio/CCBone.h @@ -143,7 +143,7 @@ public: //! Update zorder void updateZOrder(); - virtual void setZOrder(int zOrder) override; + virtual void setLocalZOrder(int zOrder) override; Tween *getTween(); diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index 349bba5dfe..a8bd016948 100644 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -331,7 +331,7 @@ void WidgetPropertiesReader0250::setPropsForWidgetFromJsonDictionary(Widget*widg widget->setVisible(DICTOOL->getBooleanValue_json(options, "visible")); } int z = DICTOOL->getIntValue_json(options, "ZOrder"); - widget->setZOrder(z); + widget->setLocalZOrder(z); } void WidgetPropertiesReader0250::setColorPropsForWidgetFromJsonDictionary(Widget *widget, const rapidjson::Value&options) @@ -1062,7 +1062,7 @@ void WidgetPropertiesReader0300::setPropsForWidgetFromJsonDictionary(Widget*widg widget->setVisible(DICTOOL->getBooleanValue_json(options, "visible")); } int z = DICTOOL->getIntValue_json(options, "ZOrder"); - widget->setZOrder(z); + widget->setLocalZOrder(z); bool layout = DICTOOL->checkObjectExist_json(options, "layoutParameter"); if (layout) diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/CCSSceneReader.cpp index 12b18604ff..e33c4ad86a 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/CCSSceneReader.cpp @@ -203,7 +203,7 @@ void SceneReader::setPropertyFromJsonDict(const rapidjson::Value &root, cocos2d: node->setTag(nTag); int nZorder = DICTOOL->getIntValue_json(root, "zorder"); - node->setZOrder(nZorder); + node->setLocalZOrder(nZorder); float fScaleX = DICTOOL->getFloatValue_json(root, "scalex", 1.0); float fScaleY = DICTOOL->getFloatValue_json(root, "scaley", 1.0); diff --git a/cocos/editor-support/cocostudio/CCSkin.cpp b/cocos/editor-support/cocostudio/CCSkin.cpp index 1da40694f7..440ce92159 100644 --- a/cocos/editor-support/cocostudio/CCSkin.cpp +++ b/cocos/editor-support/cocostudio/CCSkin.cpp @@ -225,7 +225,7 @@ void Skin::draw() kmGLGetMatrix(KM_GL_MODELVIEW, &mv); //TODO implement z order - _quadCommand.init(_vertexZ, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, mv); + _quadCommand.init(_globalZOrder, _texture->getName(), _shaderProgram, _blendFunc, &_quad, 1, mv); Director::getInstance()->getRenderer()->addCommand(&_quadCommand); } diff --git a/cocos/editor-support/spine/CCSkeleton.cpp b/cocos/editor-support/spine/CCSkeleton.cpp index c224e38d4e..82c0ed50cd 100644 --- a/cocos/editor-support/spine/CCSkeleton.cpp +++ b/cocos/editor-support/spine/CCSkeleton.cpp @@ -131,7 +131,7 @@ void Skeleton::draw() kmGLMatrixMode(KM_GL_MODELVIEW); kmGLGetMatrix(KM_GL_MODELVIEW, &_oldTransMatrix); - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Skeleton::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp index 691fb212a2..8a64ad7ed4 100644 --- a/cocos/gui/UILayout.cpp +++ b/cocos/gui/UILayout.cpp @@ -210,18 +210,18 @@ void Layout::stencilClippingVisit() Renderer* renderer = Director::getInstance()->getRenderer(); - _groupCommand.init(_vertexZ); + _groupCommand.init(_globalZOrder); renderer->addCommand(&_groupCommand); renderer->pushGroup(_groupCommand.getRenderQueueID()); - _beforeVisitCmdStencil.init(_vertexZ); + _beforeVisitCmdStencil.init(_globalZOrder); _beforeVisitCmdStencil.func = CC_CALLBACK_0(Layout::onBeforeVisitStencil, this); renderer->addCommand(&_beforeVisitCmdStencil); _clippingStencil->visit(); - _afterDrawStencilCmd.init(_vertexZ); + _afterDrawStencilCmd.init(_globalZOrder); _afterDrawStencilCmd.func = CC_CALLBACK_0(Layout::onAfterDrawStencil, this); renderer->addCommand(&_afterDrawStencilCmd); @@ -251,7 +251,7 @@ void Layout::stencilClippingVisit() this->draw(); } - _afterVisitCmdStencil.init(_vertexZ); + _afterVisitCmdStencil.init(_globalZOrder); _afterVisitCmdStencil.func = CC_CALLBACK_0(Layout::onAfterVisitStencil, this); renderer->addCommand(&_afterVisitCmdStencil); @@ -336,13 +336,13 @@ void Layout::scissorClippingVisit() { Renderer* renderer = Director::getInstance()->getRenderer(); - _beforeVisitCmdScissor.init(_vertexZ); + _beforeVisitCmdScissor.init(_globalZOrder); _beforeVisitCmdScissor.func = CC_CALLBACK_0(Layout::onBeforeVisitScissor, this); renderer->addCommand(&_beforeVisitCmdScissor); Node::visit(); - _afterVisitCmdScissor.init(_vertexZ); + _afterVisitCmdScissor.init(_globalZOrder); _afterVisitCmdScissor.func = CC_CALLBACK_0(Layout::onAfterVisitScissor, this); renderer->addCommand(&_afterVisitCmdScissor); } @@ -651,14 +651,14 @@ void Layout::addBackGroundImage() if (_backGroundScale9Enabled) { _backGroundImage = extension::Scale9Sprite::create(); - _backGroundImage->setZOrder(-1); + _backGroundImage->setLocalZOrder(-1); Node::addChild(_backGroundImage, BACKGROUNDIMAGE_Z, -1); static_cast(_backGroundImage)->setPreferredSize(_size); } else { _backGroundImage = Sprite::create(); - _backGroundImage->setZOrder(-1); + _backGroundImage->setLocalZOrder(-1); Node::addChild(_backGroundImage, BACKGROUNDIMAGE_Z, -1); } _backGroundImage->setPosition(Point(_size.width/2.0f, _size.height/2.0f)); diff --git a/cocos/gui/UILayout.h b/cocos/gui/UILayout.h index fffb6aaad1..327707d7c8 100644 --- a/cocos/gui/UILayout.h +++ b/cocos/gui/UILayout.h @@ -195,7 +195,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) */ virtual void addChild(Node * child, int zOrder) override; /** @@ -204,7 +204,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) * @param tag A interger to identify the node easily. Please refer to setTag(int) */ virtual void addChild(Node* child, int zOrder, int tag) override; diff --git a/cocos/gui/UIListView.cpp b/cocos/gui/UIListView.cpp index ba6a567aef..8c732f6e70 100644 --- a/cocos/gui/UIListView.cpp +++ b/cocos/gui/UIListView.cpp @@ -378,7 +378,7 @@ void ListView::refreshView() for (int i=0; isetZOrder(i); + item->setLocalZOrder(i); remedyLayoutParameter(item); } updateInnerContainerSize(); diff --git a/cocos/gui/UIScrollView.h b/cocos/gui/UIScrollView.h index ae49fa02ea..0b196cef55 100644 --- a/cocos/gui/UIScrollView.h +++ b/cocos/gui/UIScrollView.h @@ -242,7 +242,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) */ virtual void addChild(Node * child, int zOrder) override; /** @@ -251,7 +251,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) * @param tag A interger to identify the node easily. Please refer to setTag(int) */ virtual void addChild(Node* child, int zOrder, int tag) override; diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index e28f4d8db0..d09a8fde39 100644 --- a/cocos/gui/UIWidget.cpp +++ b/cocos/gui/UIWidget.cpp @@ -1040,7 +1040,7 @@ void Widget::copyProperties(Widget *widget) setBright(widget->isBright()); setTouchEnabled(widget->isTouchEnabled()); _touchPassedEnabled = false; - setZOrder(widget->getZOrder()); + setLocalZOrder(widget->getLocalZOrder()); setTag(widget->getTag()); setName(widget->getName()); setActionTag(widget->getActionTag()); diff --git a/cocos/gui/UIWidget.h b/cocos/gui/UIWidget.h index d07bc4bee8..3827c60db2 100644 --- a/cocos/gui/UIWidget.h +++ b/cocos/gui/UIWidget.h @@ -212,7 +212,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) */ virtual void addChild(Node * child, int zOrder) override; /** @@ -221,7 +221,7 @@ public: * If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately. * * @param child A child node - * @param zOrder Z order for drawing priority. Please refer to setZOrder(int) + * @param zOrder Z order for drawing priority. Please refer to setLocalZOrder(int) * @param tag A interger to identify the node easily. Please refer to setTag(int) */ virtual void addChild(Node* child, int zOrder, int tag) override; diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index bf7e667cc2..0c4fbe72a3 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -494,7 +494,7 @@ void ScrollView::addChild(Node * child, int zOrder, int tag) void ScrollView::beforeDraw() { - _beforeDrawCommand.init(_vertexZ); + _beforeDrawCommand.init(_globalZOrder); _beforeDrawCommand.func = CC_CALLBACK_0(ScrollView::onBeforeDraw, this); Director::getInstance()->getRenderer()->addCommand(&_beforeDrawCommand); } @@ -529,7 +529,7 @@ void ScrollView::onBeforeDraw() void ScrollView::afterDraw() { - _afterDrawCommand.init(_vertexZ); + _afterDrawCommand.init(_globalZOrder); _afterDrawCommand.func = CC_CALLBACK_0(ScrollView::onAfterDraw, this); Director::getInstance()->getRenderer()->addCommand(&_afterDrawCommand); } diff --git a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp index 1fea5ffa2a..b290364d39 100644 --- a/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ActionsTest/ActionsTest.cpp @@ -1314,7 +1314,7 @@ void ActionFollow::onEnter() void ActionFollow::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ActionFollow::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); @@ -1630,7 +1630,7 @@ void ActionCatmullRomStacked::draw() kmGLPopMatrix(); kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ActionCatmullRomStacked::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -1745,7 +1745,7 @@ void ActionCardinalSplineStacked::draw() kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); kmGLPopMatrix(); - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ActionCardinalSplineStacked::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -2107,7 +2107,7 @@ void ActionCatmullRom::draw() kmGLPopMatrix(); kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ActionCatmullRom::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -2207,7 +2207,7 @@ void ActionCardinalSpline::draw() kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV2); kmGLPopMatrix(); - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ActionCardinalSpline::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp index 70e55dae5d..2dabe08a75 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp +++ b/samples/Cpp/TestCpp/Classes/Box2DTest/Box2dTest.cpp @@ -149,7 +149,7 @@ void Box2DTestLayer::draw() kmGLPushMatrix(); kmGLGetMatrix(KM_GL_MODELVIEW, &_modelViewMV); - _customCommand.init(0, _vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Box2DTestLayer::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp index ed1e08da29..2b05f4a60b 100644 --- a/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp +++ b/samples/Cpp/TestCpp/Classes/Box2DTestBed/Box2dView.cpp @@ -211,7 +211,7 @@ void Box2DView::draw() { Layer::draw(); - _customCmd.init(_vertexZ); + _customCmd.init(_globalZOrder); _customCmd.func = CC_CALLBACK_0(Box2DView::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCmd); } diff --git a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp index b73c205be3..829c8766dc 100644 --- a/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ClippingNodeTest/ClippingNodeTest.cpp @@ -611,7 +611,7 @@ void RawStencilBufferTest::draw() auto iter = _renderCmds.begin(); - iter->init(_vertexZ); + iter->init(_globalZOrder); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onEnableStencil, this); renderer->addCommand(&(*iter)); ++iter; @@ -628,7 +628,7 @@ void RawStencilBufferTest::draw() spritePoint.y = 0; _sprites.at(i)->setPosition( spritePoint ); - iter->init(_vertexZ); + iter->init(_globalZOrder); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawClip, this, i, stencilPoint); renderer->addCommand(&(*iter)); ++iter; @@ -638,7 +638,7 @@ void RawStencilBufferTest::draw() _sprites.at(i)->visit(); kmGLPopMatrix(); - iter->init(_vertexZ); + iter->init(_globalZOrder); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onBeforeDrawSprite, this, i, winPoint); renderer->addCommand(&(*iter)); ++iter; @@ -649,7 +649,7 @@ void RawStencilBufferTest::draw() kmGLPopMatrix(); } - iter->init(_vertexZ); + iter->init(_globalZOrder); iter->func = CC_CALLBACK_0(RawStencilBufferTest::onDisableStencil, this); renderer->addCommand(&(*iter)); diff --git a/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp b/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp index 0e693d640a..622220f09d 100644 --- a/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp +++ b/samples/Cpp/TestCpp/Classes/DrawPrimitivesTest/DrawPrimitivesTest.cpp @@ -116,7 +116,7 @@ DrawPrimitivesTest::DrawPrimitivesTest() void DrawPrimitivesTest::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(DrawPrimitivesTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index 8e2a0119e4..88a63ce1f9 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -503,7 +503,7 @@ void TestChangeZorder::changeZorder(float dt) Node *node = getChildByTag(currentTag); - node->setZOrder(CCRANDOM_0_1() * 3); + node->setLocalZOrder(CCRANDOM_0_1() * 3); currentTag ++; currentTag = currentTag % 3; @@ -637,7 +637,7 @@ void TestParticleDisplay::onEnter() bone->addDisplay(p1, 0); bone->changeDisplayWithIndex(0, true); bone->setIgnoreMovementBoneData(true); - bone->setZOrder(100); + bone->setLocalZOrder(100); bone->setScale(1.2f); armature->addBone(bone, "bady-a3"); @@ -645,7 +645,7 @@ void TestParticleDisplay::onEnter() bone->addDisplay(p2, 0); bone->changeDisplayWithIndex(0, true); bone->setIgnoreMovementBoneData(true); - bone->setZOrder(100); + bone->setLocalZOrder(100); bone->setScale(1.2f); armature->addBone(bone, "bady-a30"); } @@ -1067,7 +1067,7 @@ void TestColliderDetector::update(float delta) } void TestColliderDetector::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(TestColliderDetector::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -1108,7 +1108,7 @@ std::string TestBoundingBox::title() const } void TestBoundingBox::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(TestBoundingBox::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp index a06f00d592..5253040a66 100644 --- a/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioGUITest/UIImageViewTest/UIImageViewTest.cpp @@ -56,7 +56,7 @@ bool UIImageViewTest::init() _uiLayer->addChild(sprite); */ -// imageView->setZOrder(20); +// imageView->setLocalZOrder(20); return true; } diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp index af89de176c..e09dc7f4fc 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTest.cpp @@ -210,7 +210,7 @@ void Atlas1::draw() // GL_VERTEX_ARRAY, GL_COLOR_ARRAY, GL_TEXTURE_COORD_ARRAY // GL_TEXTURE_2D - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Atlas1::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); @@ -526,7 +526,7 @@ Atlas4::Atlas4() void Atlas4::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(Atlas4::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -1612,7 +1612,7 @@ std::string LabelBMFontBounds::subtitle() const void LabelBMFontBounds::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(LabelBMFontBounds::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp index 91be90098d..a3dff56208 100644 --- a/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp +++ b/samples/Cpp/TestCpp/Classes/LabelTest/LabelTestNew.cpp @@ -302,7 +302,7 @@ LabelFNTSpriteActions::LabelFNTSpriteActions() void LabelFNTSpriteActions::draw() { - _renderCmd.init(_vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(LabelFNTSpriteActions::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); @@ -912,7 +912,7 @@ std::string LabelFNTBounds::subtitle() const void LabelFNTBounds::draw() { - _renderCmd.init(_vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(LabelFNTBounds::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index 0cee1ffbd1..194a7bc74c 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -166,11 +166,11 @@ void TouchableSpriteTest::onEnter() target->setOpacity(255); if (target == sprite2) { - sprite1->setZOrder(100); + sprite1->setLocalZOrder(100); } else if(target == sprite1) { - sprite1->setZOrder(0); + sprite1->setLocalZOrder(0); } }; diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp index a0c70d62b5..290366c94c 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.cpp @@ -67,6 +67,7 @@ static std::function createFunctions[] = CL(ConvertToNode), CL(NodeOpaqueTest), CL(NodeNonOpaqueTest), + CL(NodeGlobalZValueTest), }; #define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) @@ -905,6 +906,55 @@ std::string NodeNonOpaqueTest::subtitle() const return "Node rendered with GL_BLEND enabled"; } +/// NodeGlobalZValueTest + +NodeGlobalZValueTest::NodeGlobalZValueTest() +{ + Size s = Director::getInstance()->getWinSize(); + for (int i = 0; i < 9; i++) + { + Sprite *sprite; + auto parent = Node::create(); + if(i==4) { + sprite = Sprite::create("Images/grossinis_sister2.png"); + _sprite = sprite; + _sprite->setGlobalZOrder(-1); + } + else + sprite = Sprite::create("Images/grossinis_sister1.png"); + + parent->addChild(sprite); + this->addChild(parent); + + float w = sprite->getContentSize().width; + sprite->setPosition(s.width/2 - w*0.7*(i-5), s.height/2); + } + + this->scheduleUpdate(); +} + +void NodeGlobalZValueTest::update(float dt) +{ + static float accum = 0; + + accum += dt; + if( accum > 1) { + float z = _sprite->getGlobalZOrder(); + _sprite->setGlobalZOrder(-z); + accum = 0; + } +} + +std::string NodeGlobalZValueTest::title() const +{ + return "Global Z Value"; +} + +std::string NodeGlobalZValueTest::subtitle() const +{ + return "Center Sprite should change go from foreground to background"; +} + // // MySprite: Used by CameraTest1 and CameraTest2 @@ -932,7 +982,7 @@ protected: void MySprite::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(MySprite::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h index 2207c65f7c..334e2df08a 100644 --- a/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h +++ b/samples/Cpp/TestCpp/Classes/NodeTest/NodeTest.h @@ -249,6 +249,20 @@ protected: NodeNonOpaqueTest(); }; +class NodeGlobalZValueTest : public TestCocosNodeDemo +{ +public: + CREATE_FUNC(NodeGlobalZValueTest); + virtual std::string title() const override; + virtual std::string subtitle() const override; + + virtual void update(float dt) override; + +protected: + NodeGlobalZValueTest(); + Sprite *_sprite; +}; + class CocosNodeTestScene : public TestScene { public: diff --git a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp index a90ce6aebc..e893f707f7 100644 --- a/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp +++ b/samples/Cpp/TestCpp/Classes/RenderTextureTest/RenderTextureTest.cpp @@ -470,19 +470,19 @@ RenderTextureTestDepthStencil::~RenderTextureTestDepthStencil() void RenderTextureTestDepthStencil::draw() { - _renderCmds[0].init(_vertexZ); + _renderCmds[0].init(_globalZOrder); _renderCmds[0].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onBeforeClear, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[0]); _rend->beginWithClear(0, 0, 0, 0, 0, 0); - _renderCmds[1].init(_vertexZ); + _renderCmds[1].init(_globalZOrder); _renderCmds[1].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onBeforeStencil, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[1]); _spriteDS->visit(); - _renderCmds[2].init(_vertexZ); + _renderCmds[2].init(_globalZOrder); _renderCmds[2].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onBeforDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[2]); @@ -490,7 +490,7 @@ void RenderTextureTestDepthStencil::draw() _rend->end(); - _renderCmds[3].init(_vertexZ); + _renderCmds[3].init(_globalZOrder); _renderCmds[3].func = CC_CALLBACK_0(RenderTextureTestDepthStencil::onAfterDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmds[3]); @@ -638,7 +638,7 @@ SpriteRenderTextureBug::SimpleSprite* SpriteRenderTextureBug::SimpleSprite::crea void SpriteRenderTextureBug::SimpleSprite::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(SpriteRenderTextureBug::SimpleSprite::onBeforeDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp index 087644545e..443a24d681 100644 --- a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest.cpp @@ -193,7 +193,7 @@ void ShaderNode::setPosition(const Point &newPosition) void ShaderNode::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(ShaderNode::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } @@ -526,7 +526,7 @@ void SpriteBlur::initProgram() void SpriteBlur::draw() { - _customCommand.init(_vertexZ); + _customCommand.init(_globalZOrder); _customCommand.func = CC_CALLBACK_0(SpriteBlur::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_customCommand); } diff --git a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp index 1d76e56892..e8207b4cb4 100644 --- a/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp +++ b/samples/Cpp/TestCpp/Classes/ShaderTest/ShaderTest2.cpp @@ -178,7 +178,7 @@ void ShaderSprite::initShader() void ShaderSprite::draw() { - _renderCommand.init(_vertexZ); + _renderCommand.init(_globalZOrder); _renderCommand.func = CC_CALLBACK_0(ShaderSprite::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCommand); diff --git a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp index 3324802c9d..a4121f8825 100644 --- a/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp +++ b/samples/Cpp/TestCpp/Classes/Texture2dTest/Texture2dTest.cpp @@ -1794,7 +1794,7 @@ void TextureDrawAtPoint::draw() { TextureDemo::draw(); - _renderCmd.init(_vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(TextureDrawAtPoint::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); @@ -1835,7 +1835,7 @@ void TextureDrawInRect::draw() { TextureDemo::draw(); - _renderCmd.init(_vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(TextureDrawInRect::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); diff --git a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp index 68f3cd5d59..1b45442fd5 100644 --- a/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp +++ b/samples/Cpp/TestCpp/Classes/TileMapTest/TileMapTest.cpp @@ -599,7 +599,7 @@ TMXOrthoObjectsTest::TMXOrthoObjectsTest() void TMXOrthoObjectsTest::draw() { - _renderCmd.init(_vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(TMXOrthoObjectsTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } @@ -672,7 +672,7 @@ TMXIsoObjectsTest::TMXIsoObjectsTest() void TMXIsoObjectsTest::draw() { - _renderCmd.init(_vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(TMXIsoObjectsTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } @@ -1504,7 +1504,7 @@ TMXGIDObjectsTest::TMXGIDObjectsTest() void TMXGIDObjectsTest::draw() { - _renderCmd.init(_vertexZ); + _renderCmd.init(_globalZOrder); _renderCmd.func = CC_CALLBACK_0(TMXGIDObjectsTest::onDraw, this); Director::getInstance()->getRenderer()->addCommand(&_renderCmd); } From 47c82438121333a6f9d24e210709bb09f9cfdc18 Mon Sep 17 00:00:00 2001 From: CocosRobot Date: Sat, 18 Jan 2014 19:53:43 +0000 Subject: [PATCH 163/193] [AUTO] : updating submodule reference to latest autogenerated bindings --- cocos/scripting/auto-generated | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/auto-generated b/cocos/scripting/auto-generated index 53b58840cb..de699f63ae 160000 --- a/cocos/scripting/auto-generated +++ b/cocos/scripting/auto-generated @@ -1 +1 @@ -Subproject commit 53b58840cb9ad7bf4e8de6c4edb05a6b0d4ef19a +Subproject commit de699f63aef423c3d90725171b0f020a719ef572 From a3285792389bf5507541825249f76bb53ef14802 Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 20 Jan 2014 09:43:45 +0800 Subject: [PATCH 164/193] [ci skip] --- AUTHORS | 3 +++ 1 file changed, 3 insertions(+) diff --git a/AUTHORS b/AUTHORS index 04d52c0ee3..c37354a317 100644 --- a/AUTHORS +++ b/AUTHORS @@ -721,6 +721,9 @@ Developers: hbbalfred Fixed a bug that crash if file doesn't exist when using FileUtils::getStringFromFile. + + liang8305 + Use multiple processes according the number of cores to build android project Retired Core Developers: WenSheng Yang From a0b86abcf42f008b53b8e5cffb864f3d0b869a0e Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Mon, 20 Jan 2014 10:32:12 +0800 Subject: [PATCH 165/193] close #3765:Simplify label.Remove FontAtlasFactory,FontDefinition and TextImage. --- cocos/2d/Android.mk | 3 - cocos/2d/CCFont.cpp | 29 -- cocos/2d/CCFont.h | 10 +- cocos/2d/CCFontAtlas.cpp | 14 +- cocos/2d/CCFontAtlasCache.cpp | 81 ++++-- cocos/2d/CCFontAtlasFactory.cpp | 105 ------- cocos/2d/CCFontAtlasFactory.h | 52 ---- cocos/2d/CCFontDefinition.cpp | 235 --------------- cocos/2d/CCFontDefinition.h | 70 ----- cocos/2d/CCFontFreeType.cpp | 101 +------ cocos/2d/CCFontFreeType.h | 9 +- cocos/2d/CCTextImage.cpp | 478 ------------------------------- cocos/2d/CCTextImage.h | 215 -------------- cocos/2d/CMakeLists.txt | 3 - cocos/2d/cocos2d.vcxproj | 6 - cocos/2d/cocos2d.vcxproj.filters | 18 -- 16 files changed, 82 insertions(+), 1347 deletions(-) delete mode 100644 cocos/2d/CCFontAtlasFactory.cpp delete mode 100644 cocos/2d/CCFontAtlasFactory.h delete mode 100644 cocos/2d/CCFontDefinition.cpp delete mode 100644 cocos/2d/CCFontDefinition.h delete mode 100644 cocos/2d/CCTextImage.cpp delete mode 100644 cocos/2d/CCTextImage.h diff --git a/cocos/2d/Android.mk b/cocos/2d/Android.mk index 2253bcd7d9..432ace90c5 100644 --- a/cocos/2d/Android.mk +++ b/cocos/2d/Android.mk @@ -50,8 +50,6 @@ CCFont.cpp \ CCFontCharMap.cpp \ CCFontAtlas.cpp \ CCFontAtlasCache.cpp \ -CCFontAtlasFactory.cpp \ -CCFontDefinition.cpp \ CCFontFNT.cpp \ CCFontFreeType.cpp \ ccFPSImages.c \ @@ -91,7 +89,6 @@ CCSpriteBatchNode.cpp \ CCSpriteFrame.cpp \ CCSpriteFrameCache.cpp \ CCTextFieldTTF.cpp \ -CCTextImage.cpp \ CCTexture2D.cpp \ CCTextureAtlas.cpp \ CCTextureCache.cpp \ diff --git a/cocos/2d/CCFont.cpp b/cocos/2d/CCFont.cpp index 1c2d3bab86..14ff1b3651 100644 --- a/cocos/2d/CCFont.cpp +++ b/cocos/2d/CCFont.cpp @@ -25,10 +25,6 @@ #include "CCFont.h" #include "ccUTF8.h" - -#include "CCFontFNT.h" -#include "CCFontFreeType.h" -#include "CCFontCharMap.h" #include "edtaa3func.h" NS_CC_BEGIN @@ -107,31 +103,6 @@ const char * Font::getCurrentGlyphCollection() const } } -Font* Font::createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) -{ - return FontFreeType::create(fntName, fontSize, glyphs, customGlyphs); -} - -Font* Font::createWithFNT(const std::string& fntFilePath) -{ - return FontFNT::create(fntFilePath); -} - -Font* Font::createWithCharMap(const std::string& plistFile) -{ - return FontCharMap::create(plistFile); -} - -Font* Font::createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) -{ - return FontCharMap::create(texture,itemWidth,itemHeight,startCharMap); -} - -Font* Font::createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) -{ - return FontCharMap::create(charMapFile,itemWidth,itemHeight,startCharMap); -} - unsigned char * Font::makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height) { unsigned int pixelAmount = (width + 2 * DistanceMapSpread) * (height + 2 * DistanceMapSpread); diff --git a/cocos/2d/CCFont.h b/cocos/2d/CCFont.h index f8bb2b5201..b164468d40 100644 --- a/cocos/2d/CCFont.h +++ b/cocos/2d/CCFont.h @@ -33,7 +33,6 @@ NS_CC_BEGIN // fwd -class GlyphDef; class FontAtlas; @@ -41,13 +40,6 @@ class CC_DLL Font : public Object { public: static const int DistanceMapSpread; - // create the font - static Font* createWithTTF(const std::string& fntName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); - static Font* createWithFNT(const std::string& fntFilePath); - - static Font * createWithCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); - static Font * createWithCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); - static Font * createWithCharMap(const std::string& plistFile); static unsigned char * makeDistanceMap(unsigned char *img, unsigned int width, unsigned int height); void setDistanceFieldEnabled(bool distanceFieldEnabled); @@ -61,7 +53,7 @@ public: virtual int getLetterPadding() const { return 0; } virtual unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const { return 0; } - virtual GlyphDef* getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text = false) const { return 0; } + virtual int getFontMaxHeight() const { return 0; } virtual Rect getRectForChar(unsigned short theChar) const; diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index 6327d1cc31..70d87f679b 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -24,7 +24,6 @@ ****************************************************************************/ #include "CCFontAtlas.h" -#include "CCFont.h" #include "CCFontFreeType.h" #include "ccUTF8.h" #include "CCDirector.h" @@ -42,7 +41,7 @@ _currentPageData(nullptr) _makeDistanceMap = _font->isDistanceFieldEnabled(); FontFreeType* fontTTf = dynamic_cast(_font); - if (fontTTf && fontTTf->isDynamicGlyphCollection()) + if (fontTTf) { _currentPageLineHeight = _font->getFontMaxHeight(); _commonLineHeight = _currentPageLineHeight * 0.8f; @@ -55,13 +54,9 @@ _currentPageData(nullptr) if(_makeDistanceMap) { _commonLineHeight += 2 * Font::DistanceMapSpread; - _letterPadding += 2 * Font::DistanceMapSpread; - _currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1); - } - else - { - _currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1); + _letterPadding += 2 * Font::DistanceMapSpread; } + _currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1); _currentPageData = new unsigned char[_currentPageDataSize]; memset(_currentPageData, 0, _currentPageDataSize); @@ -165,7 +160,8 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) Size _pageContentSize = Size(PAGE_WIDTH,PAGE_HEIGHT); float scaleFactor = CC_CONTENT_SCALE_FACTOR(); float glyphWidth; - Texture2D::PixelFormat pixelFormat = _makeDistanceMap ? Texture2D::PixelFormat::A8 : Texture2D::PixelFormat::A8; + Texture2D::PixelFormat pixelFormat = Texture2D::PixelFormat::A8; + for(auto it = fontDefs.begin(); it != fontDefs.end(); it++) { diff --git a/cocos/2d/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp index ce0f18a54e..44439e2437 100644 --- a/cocos/2d/CCFontAtlasCache.cpp +++ b/cocos/2d/CCFontAtlasCache.cpp @@ -26,8 +26,10 @@ #include #include "CCFontAtlasCache.h" -#include "CCFontAtlasFactory.h" +#include "CCFontFNT.h" +#include "CCFontFreeType.h" +#include "CCFontCharMap.h" NS_CC_BEGIN @@ -40,15 +42,24 @@ FontAtlas * FontAtlasCache::getFontAtlasTTF(const std::string& fontFileName, int if ( !tempAtlas ) { - tempAtlas = FontAtlasFactory::createAtlasFromTTF(fontFileName, size, glyphs, customGlyphs, useDistanceField); - if (tempAtlas) - _atlasMap[atlasName] = tempAtlas; + Font *font = FontFreeType::create(fontFileName, size, glyphs, customGlyphs); + if (font) + { + font->setDistanceFieldEnabled(useDistanceField); + tempAtlas = font->createFontAtlas(); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + return nullptr; + } } else { tempAtlas->retain(); } - + return tempAtlas; } @@ -59,9 +70,18 @@ FontAtlas * FontAtlasCache::getFontAtlasFNT(const std::string& fontFileName) if ( !tempAtlas ) { - tempAtlas = FontAtlasFactory::createAtlasFromFNT(fontFileName); - if (tempAtlas) - _atlasMap[atlasName] = tempAtlas; + Font *font = FontFNT::create(fontFileName); + + if(font) + { + tempAtlas = font->createFontAtlas(); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + return nullptr; + } } else { @@ -78,9 +98,18 @@ FontAtlas * FontAtlasCache::getFontAtlasCharMap(const std::string& plistFile) if ( !tempAtlas ) { - tempAtlas = FontAtlasFactory::createAtlasFromCharMap(plistFile); - if (tempAtlas) - _atlasMap[atlasName] = tempAtlas; + Font *font = FontCharMap::create(plistFile); + + if(font) + { + tempAtlas = font->createFontAtlas(); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + return nullptr; + } } else { @@ -99,9 +128,18 @@ FontAtlas * FontAtlasCache::getFontAtlasCharMap(Texture2D* texture, int itemWidt if ( !tempAtlas ) { - tempAtlas = FontAtlasFactory::createAtlasFromCharMap(texture,itemWidth,itemHeight,startCharMap); - if (tempAtlas) - _atlasMap[atlasName] = tempAtlas; + Font *font = FontCharMap::create(texture,itemWidth,itemHeight,startCharMap); + + if(font) + { + tempAtlas = font->createFontAtlas(); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + return nullptr; + } } else { @@ -118,9 +156,18 @@ FontAtlas * FontAtlasCache::getFontAtlasCharMap(const std::string& charMapFile, if ( !tempAtlas ) { - tempAtlas = FontAtlasFactory::createAtlasFromCharMap(charMapFile,itemWidth,itemHeight,startCharMap); - if (tempAtlas) - _atlasMap[atlasName] = tempAtlas; + Font *font = FontCharMap::create(charMapFile,itemWidth,itemHeight,startCharMap); + + if(font) + { + tempAtlas = font->createFontAtlas(); + if (tempAtlas) + _atlasMap[atlasName] = tempAtlas; + } + else + { + return nullptr; + } } else { diff --git a/cocos/2d/CCFontAtlasFactory.cpp b/cocos/2d/CCFontAtlasFactory.cpp deleted file mode 100644 index 3b6d536223..0000000000 --- a/cocos/2d/CCFontAtlasFactory.cpp +++ /dev/null @@ -1,105 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "CCFontAtlasFactory.h" -#include "CCFontFNT.h" - -// carloX this NEEDS to be changed -#include "CCLabelBMFont.h" - -NS_CC_BEGIN - -FontAtlas * FontAtlasFactory::createAtlasFromTTF(const std::string& fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs, bool useDistanceField) -{ - - Font *font = Font::createWithTTF(fntFilePath, fontSize, glyphs, customGlyphs); - if (font) - { - font->setDistanceFieldEnabled(useDistanceField); - return font->createFontAtlas(); - } - else - { - return nullptr; - } -} - -FontAtlas * FontAtlasFactory::createAtlasFromFNT(const std::string& fntFilePath) -{ - Font *font = Font::createWithFNT(fntFilePath); - - if(font) - { - return font->createFontAtlas(); - } - else - { - return nullptr; - } -} - -FontAtlas * FontAtlasFactory::createAtlasFromCharMap(const std::string& plistFile) -{ - Font *font = Font::createWithCharMap(plistFile); - - if(font) - { - return font->createFontAtlas(); - } - else - { - return nullptr; - } -} - -FontAtlas * FontAtlasFactory::createAtlasFromCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap) -{ - Font *font = Font::createWithCharMap(texture,itemWidth,itemHeight,startCharMap); - - if(font) - { - return font->createFontAtlas(); - } - else - { - return nullptr; - } -} - -FontAtlas * FontAtlasFactory::createAtlasFromCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap) -{ - Font *font = Font::createWithCharMap(charMapFile,itemWidth,itemHeight,startCharMap); - - if(font) - { - return font->createFontAtlas(); - } - else - { - return nullptr; - } -} - -NS_CC_END diff --git a/cocos/2d/CCFontAtlasFactory.h b/cocos/2d/CCFontAtlasFactory.h deleted file mode 100644 index 7c97430fa4..0000000000 --- a/cocos/2d/CCFontAtlasFactory.h +++ /dev/null @@ -1,52 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef _CCFontAtlasFactory_h_ -#define _CCFontAtlasFactory_h_ - -#include "CCFontAtlas.h" -#include "CCLabel.h" - - -NS_CC_BEGIN - -class CC_DLL FontAtlasFactory -{ - -public: - - static FontAtlas * createAtlasFromTTF(const std::string& fntFilePath, int fontSize, GlyphCollection glyphs, const char *customGlyphs = 0, bool useDistanceField = false); - static FontAtlas * createAtlasFromFNT(const std::string& fntFilePath); - - static FontAtlas * createAtlasFromCharMap(const std::string& charMapFile, int itemWidth, int itemHeight, int startCharMap); - static FontAtlas * createAtlasFromCharMap(Texture2D* texture, int itemWidth, int itemHeight, int startCharMap); - static FontAtlas * createAtlasFromCharMap(const std::string& plistFile); - -private: -}; - -NS_CC_END - -#endif /* defined(_CCFontAtlasFactory_h_) */ diff --git a/cocos/2d/CCFontDefinition.cpp b/cocos/2d/CCFontDefinition.cpp deleted file mode 100644 index ebb79f3172..0000000000 --- a/cocos/2d/CCFontDefinition.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - - -#include "CCFontDefinition.h" -#include "CCDirector.h" - -NS_CC_BEGIN - -const int FontDefinitionTTF::DEFAUL_ATLAS_TEXTURE_SIZE = 1024; - -FontDefinitionTTF::FontDefinitionTTF():_textImages(0), _commonLineHeight(0) -{ -} - -FontDefinitionTTF* FontDefinitionTTF::create(Font *font, int textureSize) -{ - if (textureSize == 0) - textureSize = DEFAUL_ATLAS_TEXTURE_SIZE; - - FontDefinitionTTF *ret = new FontDefinitionTTF; - - if (!ret) - return 0; - - const char *glyph = font->getCurrentGlyphCollection(); - if (!glyph) - return nullptr; - - if (ret->initDefinition(font, glyph, textureSize)) - { - ret->autorelease(); - return ret; - } - else - { - delete ret; - return 0; - } -} - -FontDefinitionTTF::~FontDefinitionTTF() -{ - if (_textImages) - { - delete _textImages; - } -} - -bool FontDefinitionTTF::prepareLetterDefinitions(TextFontPagesDef *pageDefs) -{ - // get all the pages - TextFontPagesDef *pages = pageDefs; - if (!pages) - return (false); - - float maxLineHeight = -1; - - // loops all the pages - for (int cPages = 0; cPages < pages->getNumPages(); ++cPages) - { - // loops all the lines in this page - for (int cLines = 0; cLinesgetPageAt(cPages)->getNumLines(); ++cLines) - { - float posXUV = 0.0; - float posYUV = pages->getPageAt(cPages)->getLineAt(cLines)->getY(); - - int charsCounter = 0; - - for (int c = 0; c < pages->getPageAt(cPages)->getLineAt(cLines)->getNumGlyph(); ++c) - { - // the current glyph - GlyphDef currentGlyph = pages->getPageAt(cPages)->getLineAt(cLines)->getGlyphAt(c); - - // letter width - float letterWidth = currentGlyph.getRect().size.width; - - // letter height - float letterHeight = pages->getPageAt(cPages)->getLineAt(cLines)->getHeight(); - - // add this letter definition - FontLetterDefinition tempDef; - - - // carloX little hack (this should be done outside the loop) - if (posXUV == 0.0) - posXUV = currentGlyph.getPadding(); - - tempDef.validDefinition = currentGlyph.isValid(); - - if (tempDef.validDefinition) - { - tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter(); - tempDef.width = letterWidth + currentGlyph.getPadding(); - tempDef.height = (letterHeight - 1); - tempDef.U = (posXUV - 1); - tempDef.V = posYUV; - tempDef.offsetX = currentGlyph.getRect().origin.x; - tempDef.offsetY = currentGlyph.getRect().origin.y; - tempDef.textureID = cPages; - tempDef.commonLineHeight = currentGlyph.getCommonHeight(); - - // take from pixels to points - tempDef.width = tempDef.width / CC_CONTENT_SCALE_FACTOR(); - tempDef.height = tempDef.height / CC_CONTENT_SCALE_FACTOR(); - tempDef.U = tempDef.U / CC_CONTENT_SCALE_FACTOR(); - tempDef.V = tempDef.V / CC_CONTENT_SCALE_FACTOR(); - - if (tempDef.commonLineHeight>maxLineHeight) - maxLineHeight = tempDef.commonLineHeight; - } - else - { - tempDef.letteCharUTF16 = currentGlyph.getUTF8Letter(); - tempDef.commonLineHeight = 0; - tempDef.width = 0; - tempDef.height = 0; - tempDef.U = 0; - tempDef.V = 0; - tempDef.offsetX = 0; - tempDef.offsetY = 0; - tempDef.textureID = 0; - } - - - // add this definition - addLetterDefinition(tempDef); - - // move bounding box to the next letter - posXUV += letterWidth + currentGlyph.getPadding(); - - // next char in the string - ++charsCounter; - } - } - } - - // store the common line height - _commonLineHeight = maxLineHeight; - - // - return true; -} - -bool FontDefinitionTTF::initDefinition(cocos2d::Font *font, const char *letters, int textureSize) -{ - // preare texture/image stuff - _textImages = new TextImage(); - if (!_textImages) - return false; - - if (!_textImages->initWithString(letters, textureSize, textureSize, font, true)) - { - delete _textImages; - _textImages = 0; - return false; - } - - // prepare the new letter definition - return prepareLetterDefinitions(_textImages->getPages()); -} - -void FontDefinitionTTF::addLetterDefinition(const FontLetterDefinition &defToAdd) -{ - if (_fontLettersDefinitionUTF16.find(defToAdd.letteCharUTF16) == _fontLettersDefinitionUTF16.end()) - { - _fontLettersDefinitionUTF16[defToAdd.letteCharUTF16] = defToAdd; - } -} - -FontAtlas * FontDefinitionTTF::createFontAtlas() -{ - int numTextures = 0; - TextFontPagesDef *pages = _textImages->getPages(); - - if (pages) - numTextures = pages->getNumPages(); - else - return nullptr; - - if (!numTextures) - return nullptr; - - FontAtlas *retAtlas = new FontAtlas(*_textImages->getFont()); - - if (!retAtlas) - return 0; - - for (int c = 0; c < numTextures; ++c) - { - TextFontPagesDef *pPages = _textImages->getPages(); - retAtlas->addTexture(*(pPages->getPageAt(c)->getPageTexture()), c); - } - - // set the common line height - retAtlas->setCommonLineHeight(_commonLineHeight * 0.8); - - for( auto &item: _fontLettersDefinitionUTF16 ) - { - if ( item.second.validDefinition ) - { - FontLetterDefinition tempDefinition = item.second; - tempDefinition.anchorX = 0.0f; - tempDefinition.anchorY = 1.0f; - retAtlas->addLetterDefinition(tempDefinition); - } - } - - // done here - return retAtlas; -} - -NS_CC_END diff --git a/cocos/2d/CCFontDefinition.h b/cocos/2d/CCFontDefinition.h deleted file mode 100644 index 5bec2bb098..0000000000 --- a/cocos/2d/CCFontDefinition.h +++ /dev/null @@ -1,70 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef _FontDefinition_h_ -#define _FontDefinition_h_ - -#include - -#include "CCTextImage.h" -#include "CCFont.h" -#include "CCFontAtlas.h" - -NS_CC_BEGIN - -/** - */ -class CC_DLL FontDefinitionTTF : public Object -{ -public: - - static FontDefinitionTTF* create(Font *font, int textureSize = 0); - FontAtlas * createFontAtlas(); - -private: - /** - * @js ctor - */ - FontDefinitionTTF(); - /** - * @js NA - * @lua NA - */ - ~FontDefinitionTTF(); - - bool initDefinition(Font *font, const char *letters, int textureSize); - bool prepareLetterDefinitions(TextFontPagesDef *pageDefs); - void addLetterDefinition(const FontLetterDefinition &defToAdd); - - TextImage * _textImages; - std::unordered_map _fontLettersDefinitionUTF16; - float _commonLineHeight; - - static const int DEFAUL_ATLAS_TEXTURE_SIZE; -}; - -NS_CC_END - -#endif diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index c503611b71..1adc138b0f 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -28,9 +28,6 @@ THE SOFTWARE. #include "ccUTF8.h" #include "CCFontFreeType.h" -#include "CCTextImage.h" -#include "CCFont.h" -#include "CCFontDefinition.h" #include "platform/CCFileUtils.h" NS_CC_BEGIN @@ -41,11 +38,7 @@ bool FontFreeType::_FTInitialized = false; FontFreeType * FontFreeType::create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) { - bool dynamicGlyphCollection = false; - if(glyphs == GlyphCollection::DYNAMIC) - dynamicGlyphCollection = true; - - FontFreeType *tempFont = new FontFreeType(dynamicGlyphCollection); + FontFreeType *tempFont = new FontFreeType(); if (!tempFont) return nullptr; @@ -89,10 +82,9 @@ FT_Library FontFreeType::getFTLibrary() return _FTlibrary; } -FontFreeType::FontFreeType(bool dynamicGlyphCollection) +FontFreeType::FontFreeType() : _fontRef(nullptr), -_letterPadding(5), -_dynamicGlyphCollection(dynamicGlyphCollection) +_letterPadding(5) { if(_distanceFieldEnabled) _letterPadding += 2 * DistanceMapSpread; @@ -141,23 +133,13 @@ FontFreeType::~FontFreeType() FontAtlas * FontFreeType::createFontAtlas() { - if (_dynamicGlyphCollection) + FontAtlas *atlas = new FontAtlas(*this); + if (_usedGlyphs != GlyphCollection::DYNAMIC) { - FontAtlas *atlas = new FontAtlas(*this); - this->release(); - return atlas; - } - else - { - FontDefinitionTTF *def = FontDefinitionTTF::create(this); - - if (!def) - return nullptr; - - FontAtlas *atlas = def->createFontAtlas(); - - return atlas; - } + atlas->prepareLetterDefinitions(cc_utf8_to_utf16(getCurrentGlyphCollection())); + } + this->release(); + return atlas; } bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect) const @@ -184,71 +166,6 @@ bool FontFreeType::getBBOXFotChar(unsigned short theChar, Rect &outRect) const return true; } -GlyphDef * FontFreeType::getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text) const -{ - unsigned short* utf16String = 0; - - if (UTF16text) - { - utf16String = (unsigned short*) text; - } - else - { - utf16String = cc_utf8_to_utf16(text); - } - - // - if (!utf16String) - return 0; - - int numChar = cc_wcslen(utf16String); - if (!numChar) - return 0; - - // allocate the needed Glyphs - GlyphDef *glyphs = new GlyphDef[numChar]; - assert(glyphs != nullptr); - if (!glyphs) - return 0; - - // sore result as CCRect - for (int c = 0; c < numChar; ++c) - { - Rect tempRect; - - if (!getBBOXFotChar(utf16String[c], tempRect)) - { - log("Warning: Cannot find definition for glyph: %c in font:%s", utf16String[c], _fontName.c_str()); - - tempRect.origin.x = 0; - tempRect.origin.y = 0; - tempRect.size.width = 0; - tempRect.size.height = 0; - - glyphs[c].setRect(tempRect); - glyphs[c].setUTF16Letter(utf16String[c]); - glyphs[c].setValid(false); - glyphs[c].setPadding(_letterPadding); - } - else - { - glyphs[c].setRect(tempRect); - glyphs[c].setUTF16Letter(utf16String[c]); - glyphs[c].setPadding(_letterPadding); - glyphs[c].setValid(true); - } - } - - outNumGlyphs = numChar; - - // free memory - if (!UTF16text) - delete [] utf16String; - - // done - return glyphs; -} - Size * FontFreeType::getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const { if (!text) diff --git a/cocos/2d/CCFontFreeType.h b/cocos/2d/CCFontFreeType.h index bd86c5effc..bcae504c35 100644 --- a/cocos/2d/CCFontFreeType.h +++ b/cocos/2d/CCFontFreeType.h @@ -46,18 +46,16 @@ public: virtual FontAtlas * createFontAtlas() override; virtual Size * getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override; - virtual GlyphDef * getGlyphDefintionsForText(const char *text, int &outNumGlyphs, bool UTF16text = false) const override; + unsigned char * getGlyphBitmap(unsigned short theChar, int &outWidth, int &outHeight) const override; virtual int getFontMaxHeight() const override; virtual int getLetterPadding() const override; - bool getBBOXFotChar(unsigned short theChar, Rect &outRect) const; - - inline bool isDynamicGlyphCollection() { return _dynamicGlyphCollection;} + bool getBBOXFotChar(unsigned short theChar, Rect &outRect) const; protected: - FontFreeType(bool dynamicGlyphCollection = false); + FontFreeType(); virtual ~FontFreeType(); bool createFontObject(const std::string &fontName, int fontSize); @@ -76,7 +74,6 @@ private: int _letterPadding; std::string _fontName; Data _ttfData; - bool _dynamicGlyphCollection; }; NS_CC_END diff --git a/cocos/2d/CCTextImage.cpp b/cocos/2d/CCTextImage.cpp deleted file mode 100644 index cd972a172e..0000000000 --- a/cocos/2d/CCTextImage.cpp +++ /dev/null @@ -1,478 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include -#include -#include -#include - -#include "CCTextImage.h" -#include "CCFontFreeType.h" -#include "CCFont.h" -#include "ccUTF8.h" - -NS_CC_BEGIN - - -TextLineDef::TextLineDef(float x, float y, float width, float height) :_x(x), _y(y), _width(width), _height(height) -{ -} - -TextPageDef::TextPageDef(int pageNum, int width, int height): _pageNum(pageNum), - _width(width), - _height(height), - _pageData(0), - _pageTexture(0) -{ -} - -TextPageDef::~TextPageDef() -{ - size_t numLines = _lines.size(); - - for( size_t c = 0; crelease(); - } -} - -bool TextPageDef::generatePageTexture(bool releasePageData) -{ - if (!_pageData) - return false; - - if (_pageTexture) - { - _pageTexture->release(); - _pageTexture = 0; - } - - Size imageSize = Size((float)(_width), (float)(_height)); - if((imageSize.width <= 0) || (imageSize.height <= 0)) - return false; - - _pageTexture = new Texture2D(); - if (!_pageTexture) - return false; - - int dataLenght = (_width * _height * 1); - bool textureCreated = _pageTexture->initWithData(_pageData, dataLenght, Texture2D::PixelFormat::A8, _width, _height, imageSize); - - // release the page data if requested - if (releasePageData && textureCreated) - { - delete [] _pageData; - _pageData = 0; - } - - return textureCreated; -} - -void TextPageDef::preparePageTexture(bool releaseRAWData) -{ - generatePageTexture(releaseRAWData); -} - -Texture2D *TextPageDef::getPageTexture() -{ - if (!_pageTexture) - { - generatePageTexture(); - } - - return _pageTexture; -} - -TextFontPagesDef::TextFontPagesDef() -{ -} - -TextFontPagesDef::~TextFontPagesDef() -{ - size_t numPages = _pages.size(); - for( size_t c = 0; c < numPages; ++c ) - { - if (_pages[c]) - delete _pages[c]; - } -} - -TextImage::TextImage(): _fontPages(0), _font(0) -{ -} - -TextImage::~TextImage() -{ - if (_fontPages) - delete _fontPages; - - if (_font) - _font->release(); -} - -bool TextImage::initWithString(const char *text, int width, int height, cocos2d::Font* font, bool releaseRAWData) -{ - bool textIsUTF16 = false; - - if (_font) - { - _font->release(); - _font = 0; - } - - // carloX - _font = font; - - // generate the glyphs for the requested text (glyphs are latter's bounding boxes) - if (!generateTextGlyphs(text)) - return false; - - Size constrainSize; - unsigned short int *strUTF16 = 0; - - int stringNumChars; - if (textIsUTF16) - { - strUTF16 = (unsigned short int *)text; - stringNumChars = cc_wcslen(strUTF16); - } - else - { - // string needs to go to unicode - strUTF16 = _font->getUTF16Text(text, stringNumChars); - } - - if (!strUTF16 || !stringNumChars) - return false; - - // create all the needed pages - if (!createPageDefinitions(strUTF16, width, height, _font->getFontMaxHeight())) - return false; - - // release the original string if needed - if (!textIsUTF16) - delete [] strUTF16; - - // actually create the needed images - return createImageDataFromPages(_fontPages, releaseRAWData); - - return true; -} - -bool TextImage::createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight) -{ - bool needToReleaseText = false; - int delta = 0; - int currentPage = 0; - float currentY = 0.0; - - // - unsigned short int *strUTF16 = inText; - - if (_fontPages) - delete _fontPages; - - // create pages for the font - _fontPages = new TextFontPagesDef(); - if (!_fontPages) - return false; - - // create the first page (ther is going to be at least one page) - TextPageDef *currentPageDef = new TextPageDef(currentPage, imageWidth, imageHeight); - if (!currentPageDef) - return false; - - // add the current page - _fontPages->addPage(currentPageDef); - - // work out creating pages - - do { - - // choose texture page - if ((currentY + lineHeight) > imageHeight) - { - currentY = 0; - currentPage += 1; - - // create a new page and add - currentPageDef = new TextPageDef(currentPage, imageWidth, imageHeight); - if (!currentPageDef) - return false; - - _fontPages->addPage(currentPageDef); - } - - // get the new fitting string - Size tempSize; - tempSize.width = imageWidth; - tempSize.height = imageHeight; - - // figure out how many glyphs fit in this line - int newLineSize = 0; - int numFittingChar = getNumGlyphsFittingInSize(_textGlyphs, strUTF16, _font, &tempSize, newLineSize); - - // crete the temporary new string - unsigned short int *pTempString = 0; - pTempString = _font->trimUTF16Text(strUTF16, 0, (numFittingChar - 1)); - - // create the new line and add to the current page - TextLineDef *newLine = new TextLineDef(0.0, currentY, newLineSize, lineHeight); - if (!newLine) - return false; - - // add all the glyphs to this line - addGlyphsToLine(newLine, (const char *)pTempString, true); - - // add the line the to current page - currentPageDef->addLine(newLine); - - // can now release the string - delete [] pTempString; - - // create the new string - int stringLenght = _font->getUTF16TextLenght(strUTF16); - delta = (stringLenght - numFittingChar); - - // there is still some leftover, need to work on it - if (delta) - { - // create the new string - unsigned short int *tempS = _font->trimUTF16Text(strUTF16, numFittingChar, (stringLenght - 1)); - - if (needToReleaseText) - delete [] strUTF16; - - // a copy of the string has been created, so next time I'll need to release it - needToReleaseText = true; - - // assign pointer - strUTF16 = tempS; - } - - // go to next line - currentY += lineHeight; - - } while(delta); - - if (needToReleaseText) - delete [] strUTF16; - - return true; -} - -int TextImage::getNumGlyphsFittingInSize(std::unordered_map &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize) -{ - if (!strUTF8) - return 0; - - float widthWithBBX = 0.0f; - float lastWidth = 0.0f; - - // get the string to UTF8 - int numChar = cc_wcslen(strUTF8); - - for (int c = 0; c < numChar; ++c) - { - widthWithBBX += (glyphDefs[strUTF8[c]].getRect().size.width + glyphDefs[strUTF8[c]].getPadding()); - - if (widthWithBBX >= constrainSize->width) - { - outNewSize = lastWidth; - return c; - } - - lastWidth = widthWithBBX; - } - - outNewSize = constrainSize->width; - return numChar; -} - -bool TextImage::addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16) -{ - if (!_font) - return false; - - int numLetters = 0; - unsigned short int *UTF16string = 0; - - if (textIsUTF16) - { - UTF16string = (unsigned short int *)lineText; - numLetters = cc_wcslen(UTF16string); - } - else - { - UTF16string = _font->getUTF16Text(lineText, numLetters); - } - - for (int c = 0; c < numLetters; ++c) - { - _textGlyphs[UTF16string[c]].setCommonHeight(line->getHeight()); - line->addGlyph(_textGlyphs[UTF16string[c]] ); - } - - if(!textIsUTF16) - delete [] UTF16string; - - return true; -} - -bool TextImage::generateTextGlyphs(const char * text) -{ - if (!_font) - return false; - - int numGlyphs = 0; - GlyphDef *newGlyphs = _font->getGlyphDefintionsForText(text, numGlyphs); - - if (!newGlyphs) - return false; - - if (!_textGlyphs.empty()) - _textGlyphs.clear(); - - for (int c = 0; c < numGlyphs; ++c) - _textGlyphs[newGlyphs[c].getUTF8Letter()] = newGlyphs[c]; - - delete [] newGlyphs; - return true; -} - -bool TextImage::createImageDataFromPages(TextFontPagesDef *thePages, bool releaseRAWData) -{ - int numPages = thePages->getNumPages(); - if (!numPages) - return false; - - for (int c = 0; c < numPages; ++c) - { - unsigned char *pageData = 0; - pageData = preparePageGlyphData(thePages->getPageAt(c)); - - if (pageData) - { - // set the page data - thePages->getPageAt(c)->setPageData(pageData); - - // crete page texture and relase RAW data - thePages->getPageAt(c)->preparePageTexture(releaseRAWData); - } - else - { - return false; - } - } - - return true; -} - -unsigned char * TextImage::preparePageGlyphData(TextPageDef *thePage) -{ - return renderGlyphData(thePage); -} - -unsigned char * TextImage::renderGlyphData(TextPageDef *thePage) -{ - if (!thePage) - return 0; - - if (!_font) - return 0; - - if (thePage->getNumLines() == 0) - return nullptr; - - int pageWidth = thePage->getWidth(); - int pageHeight = thePage->getHeight(); - - // prepare memory and clean to 0 - int sizeInBytes = (pageWidth * pageHeight * 1); - unsigned char* data = new unsigned char[sizeInBytes]; - - if (!data) - return 0; - - memset(data, 0, sizeInBytes); - - int numLines = thePage->getNumLines(); - - for (int c = 0; c < numLines; ++c) - { - TextLineDef *currentLine = thePage->getLineAt(c); - - float origX = _font->getLetterPadding(); - float origY = currentLine->getY(); - - int numGlyphToRender = currentLine->getNumGlyph(); - - for (int cglyph = 0; cglyph < numGlyphToRender; ++cglyph) - { - GlyphDef currGlyph = currentLine->getGlyphAt(cglyph); - _font->renderCharAt(currGlyph.getUTF8Letter(), origX, origY, data, pageWidth); - origX += (currGlyph.getRect().size.width + _font->getLetterPadding()); - } - } - -#ifdef _DEBUG_FONTS_ - static int counter = 0; - char outFilename[512]; - sprintf(outFilename,"testIMG%d", counter); - ++counter; - Image *image = new Image; - image->initWithRawData(data, (pageWidth * pageWidth * 4), 1024, 1024, 8, false); - image->saveToFile(outFilename); -#endif - - // we are done here - return data; -} - -NS_CC_END - - - - - - - - - - - - diff --git a/cocos/2d/CCTextImage.h b/cocos/2d/CCTextImage.h deleted file mode 100644 index b7baddb561..0000000000 --- a/cocos/2d/CCTextImage.h +++ /dev/null @@ -1,215 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013 Zynga Inc. - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#ifndef _CCTextImage_h_ -#define _CCTextImage_h_ - -#include -#include - -#include "CCPlatformMacros.h" -#include "CCGeometry.h" - -NS_CC_BEGIN - -class Font; -class Texture2D; - -/** @brief GlyphDef defines one single glyph (character) in a text image - * - * it defines the bounding box for the glyph in the texture page, the character the padding (spacing) between characters - * - */ - -class CC_DLL GlyphDef -{ -public: - - GlyphDef() : _validGlyph(false) {} - GlyphDef(unsigned short int letterUTF8, const Rect &rect) { - _gliphRect = rect; - _uTF16Letter = letterUTF8; - } - - void setUTF16Letter(unsigned short int letterUTF8) { _uTF16Letter = letterUTF8; } - void setRect(const Rect & theRect) { _gliphRect = theRect; } - - unsigned short int getUTF8Letter() const { return _uTF16Letter; } - const Rect& getRect() const { return _gliphRect; } - - void setPadding(float padding) { _padding = padding; } - float getPadding() const { return _padding; } - - void setCommonHeight(float commonHeight) { _commonHeight = commonHeight; } - float getCommonHeight() const { return _commonHeight; } - - void setValid(bool isValid) { _validGlyph = isValid; } - bool isValid() const { return _validGlyph; } - -protected: - Rect _gliphRect; - unsigned short int _uTF16Letter; - float _padding; - float _commonHeight; - bool _validGlyph; - -}; - -/** @brief TextLineDef define a line of text in a text image texture page - * - * conllects all the GlyphDef for a text line plus line size and line position in text image space - * - */ -class CC_DLL TextLineDef -{ -public: - - TextLineDef(float x, float y, float width, float height); - - float getX() const { return _x; } - float getY() const { return _y; } - float getWidth() const { return _width; } - float getHeight() const { return _height; } - - void addGlyph(GlyphDef theGlyph) { _glyphs.push_back(theGlyph); } - int getNumGlyph() const { return static_cast(_glyphs.size()); } - const GlyphDef & getGlyphAt(int index) const { return _glyphs[index]; } - -protected: - float _x; - float _y; - float _width; - float _height; - std::vector _glyphs; -}; - -/** @brief TextPageDef defines one text image page (a TextImage can have/use more than one page) - * - * collects all the TextLineDef for one page, the witdh and height of the page and the graphics (texture) for the page - * - */ -class CC_DLL TextPageDef -{ -public: - /** - * @js NA - */ - TextPageDef(int pageNum, int width, int height); - /** - * @js NA - * @lua NA - */ - ~TextPageDef(); - - void addLine(TextLineDef *theLine) { _lines.push_back(theLine); } - int getNumLines() const { return static_cast(_lines.size()); } - TextLineDef * getLineAt(int index) const { return _lines[index]; } - int getWidth() const { return _width; } - int getHeight() const { return _height; } - int getPageNumber() const { return _pageNum; } - void setPageData(unsigned char *data) { _pageData = data; } - const unsigned char * getPageData() const { return _pageData; } - Texture2D *getPageTexture(); - void preparePageTexture(bool releaseRAWData = true); - -protected: - bool generatePageTexture(bool releasePageData = false); - - int _pageNum; - int _width; - int _height; - unsigned char * _pageData; - Texture2D* _pageTexture; - std::vector _lines; -}; - -/** @brief CCTextFontPages collection of pages (TextPageDef) - * - * A TextImage is composed by one or more text pages. This calss collects all of those pages - */ -class CC_DLL TextFontPagesDef -{ -public: - /** - * @js ctor - */ - TextFontPagesDef(); - /** - * @js NA - * @lua NA - */ - ~TextFontPagesDef(); - - void addPage(TextPageDef *newPage) { _pages.push_back(newPage); } - int getNumPages() const { return static_cast(_pages.size()); } - TextPageDef* getPageAt(int index) const { return _pages[index]; } - -protected: - std::vector _pages; - -}; - -/** @brief TextImage - * - */ -class CC_DLL TextImage -{ -public: - /** - * @js ctor - */ - TextImage(); - /** - * @js NA - * @lua NA - */ - ~TextImage(); - - bool initWithString(const char *text, int width, int height, Font* font, bool releaseRAWData = true); - - TextFontPagesDef* getPages() const { return _fontPages; } - Font* getFont() const { return _font; } - -protected: - bool createImageDataFromPages(TextFontPagesDef *thePages, bool releaseRAWData = true); - bool addGlyphsToLine(TextLineDef *line, const char *lineText, bool textIsUTF16 = false); - bool generateTextGlyphs(const char * text); - int getNumGlyphsFittingInSize(std::unordered_map &glyphDefs, unsigned short int *strUTF8, Font *font, Size *constrainSize, int &outNewSize); - bool createPageDefinitions(unsigned short int *inText, int imageWidth, int imageHeight, int lineHeight); - unsigned char * preparePageGlyphData(TextPageDef *thePage); - - // glyph rendering - unsigned char * renderGlyphData(TextPageDef *thePage); - - std::unordered_map _textGlyphs; - TextFontPagesDef* _fontPages; - Font* _font; -}; - - -NS_CC_END - - -#endif // _CCTextImage_h_ diff --git a/cocos/2d/CMakeLists.txt b/cocos/2d/CMakeLists.txt index 886c2ebc21..d32040f867 100644 --- a/cocos/2d/CMakeLists.txt +++ b/cocos/2d/CMakeLists.txt @@ -67,8 +67,6 @@ set(COCOS2D_SRC CCFont.cpp CCFontAtlas.cpp CCFontAtlasCache.cpp - CCFontAtlasFactory.cpp - CCFontDefinition.cpp CCFontFNT.cpp CCFontFreeType.cpp CCFontCharMap.cpp @@ -77,7 +75,6 @@ set(COCOS2D_SRC CCLabelBMFont.cpp CCLabelTTF.cpp CCLabelTextFormatter.cpp - CCTextImage.cpp CCLayer.cpp CCScene.cpp CCTransition.cpp diff --git a/cocos/2d/cocos2d.vcxproj b/cocos/2d/cocos2d.vcxproj index 9c7bd8f40f..123231cb40 100644 --- a/cocos/2d/cocos2d.vcxproj +++ b/cocos/2d/cocos2d.vcxproj @@ -247,9 +247,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - - @@ -288,7 +286,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - @@ -429,9 +426,7 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - - @@ -490,7 +485,6 @@ xcopy /Y /Q "$(ProjectDir)..\..\external\win32-specific\gles\prebuilt\*.*" "$(Ou - diff --git a/cocos/2d/cocos2d.vcxproj.filters b/cocos/2d/cocos2d.vcxproj.filters index 6a28597e2d..6b63c0cf67 100644 --- a/cocos/2d/cocos2d.vcxproj.filters +++ b/cocos/2d/cocos2d.vcxproj.filters @@ -318,12 +318,6 @@ label_nodes - - label_nodes - - - label_nodes - label_nodes @@ -345,9 +339,6 @@ label_nodes - - label_nodes - platform\etc @@ -834,12 +825,6 @@ label_nodes - - label_nodes - - - label_nodes - label_nodes @@ -864,9 +849,6 @@ label_nodes - - label_nodes - platform\etc From bf99e10c10bdb212e31484675b97368c9642fab7 Mon Sep 17 00:00:00 2001 From: liang8305 Date: Mon, 20 Jan 2014 10:37:01 +0800 Subject: [PATCH 166/193] get number of cpu, using multiple concurrent job processes; --- build/android-build.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/build/android-build.py b/build/android-build.py index 3285c690e9..0309cf008b 100755 --- a/build/android-build.py +++ b/build/android-build.py @@ -12,6 +12,16 @@ LUA_SAMPLES = ['hellolua', 'testlua'] JSB_SAMPLES = ['cocosdragon', 'crystalcraze', 'moonwarriors', 'testjavascript', 'watermelonwithme'] ALL_SAMPLES = CPP_SAMPLES + LUA_SAMPLES + JSB_SAMPLES +def get_num_of_cpu(): + ''' The build process can be accelerated by running multiple concurrent job processes using the -j-option. + ''' + try: + from numpy.distutils import cpuinfo + return cpuinfo.cpu._getNCPUs() + except Exception: + print "Can't know cpuinfo, use default 1 cpu" + return 1 + def check_environment_variables(): ''' Checking the environment NDK_ROOT, which will be used for building ''' @@ -94,10 +104,12 @@ def do_build(cocos_root, ndk_root, app_android_root, ndk_build_param,sdk_root,an else: ndk_module_path = 'NDK_MODULE_PATH=%s:%s/external:%s/cocos' % (cocos_root, cocos_root, cocos_root) + num_of_cpu = get_num_of_cpu() if ndk_build_param == None: - command = '%s -C %s %s' % (ndk_path, app_android_root, ndk_module_path) + command = '%s -j%d -C %s %s' % (ndk_path, num_of_cpu, app_android_root, ndk_module_path) else: - command = '%s -C %s %s %s' % (ndk_path, app_android_root, ndk_build_param, ndk_module_path) + command = '%s -j%d -C %s %s %s' % (ndk_path, num_of_cpu, app_android_root, ndk_build_param, ndk_module_path) + print command if os.system(command) != 0: raise Exception("Build dynamic library for project [ " + app_android_root + " ] fails!") elif android_platform is not None: From b11ef3069fb5509393af019ea04fbb7e17cd1391 Mon Sep 17 00:00:00 2001 From: James Chen Date: Fri, 17 Jan 2014 13:57:58 +0800 Subject: [PATCH 167/193] issue #2789: Adds Map, Dictionary perf test, not yet finished. --- .../PerformanceContainerTest.cpp | 170 +++++++++++++++++- .../PerformanceContainerTest.h | 21 +++ 2 files changed, 188 insertions(+), 3 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp index 75efc640e5..775950c366 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp @@ -35,7 +35,9 @@ static std::function createFunctions[] = { CL(TemplateVectorPerfTest), - CL(ArrayPerfTest) + CL(ArrayPerfTest), + CL(TemplateMapPerfTest), + CL(DictionaryPerfTest) }; #define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) @@ -519,8 +521,6 @@ std::string TemplateVectorPerfTest::subtitle() const return "Test 'pushBack', See console"; } - - //////////////////////////////////////////////////////// // // ArrayPerfTest @@ -701,6 +701,170 @@ void ArrayPerfTest::generateTestFunctions() } } +//////////////////////////////////////////////////////// +// +// TemplateMapPerfTest +// +//////////////////////////////////////////////////////// + +void TemplateMapPerfTest::generateTestFunctions() +{ + auto createMap = [this](){ + Map ret; + + for( int i=0; isetTag(i); + ret.insert(StringUtils::format("key_%d", i), node); + } + return ret; + }; + + TestFunction nameCBs[] = { + { "insert", [=](){ + Map map; + + std::string* keys = new std::string[quantityOfNodes]; + + for (int i = 0; i < quantityOfNodes; ++i) + { + keys[i] = StringUtils::format("key_%d", i); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + CC_SAFE_DELETE_ARRAY(keys); + } } , + + { "at", [=](){ + Map map = createMap(); + + std::string* keys = new std::string[quantityOfNodes]; + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + for (int i = 0; i < quantityOfNodes; ++i) + { + keys[i] = StringUtils::format("key_%d", i); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + CC_SAFE_DELETE_ARRAY(keys); + + for (int i = 0; i < quantityOfNodes; ++i) + { + nodes[i]->setTag(100); + } + + CC_SAFE_FREE(nodes); + } } , + }; + + for (const auto& nameCB : nameCBs) + { + _testFunctions.push_back(nameCB); + } +} + + + +std::string TemplateMapPerfTest::title() const +{ + return "Map Perf test"; +} + +std::string TemplateMapPerfTest::subtitle() const +{ + return "Test 'insert', See console"; +} + +//////////////////////////////////////////////////////// +// +// DictionaryPerfTest +// +//////////////////////////////////////////////////////// + +std::string DictionaryPerfTest::title() const +{ + return "Array Perf test"; +} + +std::string DictionaryPerfTest::subtitle() const +{ + return "Test `addObject`, See console"; +} + +void DictionaryPerfTest::generateTestFunctions() +{ + auto createDict = [this](){ + Dictionary* ret = Dictionary::create(); + + for( int i=0; isetTag(i); + ret->setObject(node, StringUtils::format("key_%d", i)); + } + return ret; + }; + + TestFunction testFunctions[] = { + { "setObject", [=](){ + Dictionary* dict = Dictionary::create(); + + std::string* keys = new std::string[quantityOfNodes]; + + for (int i = 0; i < quantityOfNodes; ++i) + { + keys[i] = StringUtils::format("key_%d", i); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; isetObject(Node::create(), keys[i]); + CC_PROFILER_STOP(this->profilerName()); + + CC_SAFE_DELETE_ARRAY(keys); + } } , + + { "objectForKey", [=](){ + auto dict = createDict(); + + std::string* keys = new std::string[quantityOfNodes]; + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + for (int i = 0; i < quantityOfNodes; ++i) + { + keys[i] = StringUtils::format("key_%d", i); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; i(dict->objectForKey(keys[i])); + CC_PROFILER_STOP(this->profilerName()); + + CC_SAFE_DELETE_ARRAY(keys); + + for (int i = 0; i < quantityOfNodes; ++i) + { + nodes[i]->setTag(100); + } + + CC_SAFE_FREE(nodes); + } } , + }; + + for (const auto& func : testFunctions) + { + _testFunctions.push_back(func); + } +} + ///---------------------------------------- void runContainerPerformanceTest() { diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h index d99cac90ff..7f04c113f2 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h @@ -85,6 +85,27 @@ public: virtual std::string subtitle() const override; }; +class TemplateMapPerfTest : public PerformanceContainerScene +{ +public: + CREATE_FUNC(TemplateMapPerfTest); + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + +class DictionaryPerfTest : public PerformanceContainerScene +{ +public: + CREATE_FUNC(DictionaryPerfTest); + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; void runContainerPerformanceTest(); From 5018c9ba6cab6d150b5e0ea7e41d2ed5a19c24d2 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 20 Jan 2014 11:10:04 +0800 Subject: [PATCH 168/193] Removes unused cast in CCTMXTiledMap.cpp. --- cocos/2d/CCTMXTiledMap.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCTMXTiledMap.cpp b/cocos/2d/CCTMXTiledMap.cpp index 33a4b77519..54fecd658b 100644 --- a/cocos/2d/CCTMXTiledMap.cpp +++ b/cocos/2d/CCTMXTiledMap.cpp @@ -174,7 +174,7 @@ void TMXTiledMap::buildWithMapInfo(TMXMapInfo* mapInfo) if (layerInfo->_visible) { TMXLayer *child = parseLayer(layerInfo, mapInfo); - addChild((Node*)child, idx, idx); + addChild(child, idx, idx); // update content size with the max size const Size& childSize = child->getContentSize(); From 0d4d4c53f4aefa9bcf0e2deec1e252c1aa956638 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 20 Jan 2014 11:10:53 +0800 Subject: [PATCH 169/193] issue #2789: Improves performance for Map::keys. --- cocos/base/CCMap.h | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index 450b39bc2e..4b940f2a78 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -144,9 +144,11 @@ public: std::vector keys() const { std::vector keys; - + if (!_data.empty()) { + keys.reserve(_data.size()); + for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter) { keys.push_back(iter->first); @@ -160,14 +162,21 @@ public: { std::vector keys; - for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter) + if (!_data.empty()) { - if (iter->second == object) + keys.reserve(_data.size() / 10); + + for (auto iter = _data.cbegin(); iter != _data.cend(); ++iter) { - keys.push_back(iter->first); + if (iter->second == object) + { + keys.push_back(iter->first); + } } } + keys.shrink_to_fit(); + return keys; } From b116a11c3ca6b822f2ccfea04afdc5cb1d0b8786 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 20 Jan 2014 11:12:29 +0800 Subject: [PATCH 170/193] issue #2789: Adds performance test for Map and Dictionary. --- .../PerformanceContainerTest.cpp | 588 ++++++++++++++++-- .../PerformanceContainerTest.h | 32 +- 2 files changed, 567 insertions(+), 53 deletions(-) diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp index 775950c366..7754582947 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.cpp @@ -36,8 +36,10 @@ static std::function createFunctions[] = { CL(TemplateVectorPerfTest), CL(ArrayPerfTest), - CL(TemplateMapPerfTest), - CL(DictionaryPerfTest) + CL(TemplateMapStringKeyPerfTest), + CL(DictionaryStringKeyPerfTest), + CL(TemplateMapIntKeyPerfTest), + CL(DictionaryIntKeyPerfTest) }; #define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) @@ -266,27 +268,6 @@ void PerformanceContainerScene::updateProfilerName() snprintf(_profilerName, sizeof(_profilerName)-1, "%s(%d)", testName(), quantityOfNodes); } -void PerformanceContainerScene::onExitTransitionDidStart() -{ - Scene::onExitTransitionDidStart(); - - auto director = Director::getInstance(); - auto sched = director->getScheduler(); - - sched->unscheduleSelector(schedule_selector(PerformanceContainerScene::dumpProfilerInfo), this); -} - -void PerformanceContainerScene::onEnterTransitionDidFinish() -{ - Scene::onEnterTransitionDidFinish(); - - auto director = Director::getInstance(); - auto sched = director->getScheduler(); - - CC_PROFILER_PURGE_ALL(); - sched->scheduleSelector(schedule_selector(PerformanceContainerScene::dumpProfilerInfo), this, 2, false); -} - void PerformanceContainerScene::dumpProfilerInfo(float dt) { CC_PROFILER_DISPLAY_TIMERS(); @@ -509,8 +490,6 @@ void TemplateVectorPerfTest::generateTestFunctions() } } - - std::string TemplateVectorPerfTest::title() const { return "Vector Perf test"; @@ -703,11 +682,11 @@ void ArrayPerfTest::generateTestFunctions() //////////////////////////////////////////////////////// // -// TemplateMapPerfTest +// TemplateMapStringKeyPerfTest // //////////////////////////////////////////////////////// -void TemplateMapPerfTest::generateTestFunctions() +void TemplateMapStringKeyPerfTest::generateTestFunctions() { auto createMap = [this](){ Map ret; @@ -721,7 +700,7 @@ void TemplateMapPerfTest::generateTestFunctions() return ret; }; - TestFunction nameCBs[] = { + TestFunction testFunctions[] = { { "insert", [=](){ Map map; @@ -764,43 +743,129 @@ void TemplateMapPerfTest::generateTestFunctions() CC_SAFE_FREE(nodes); } } , + + { "erase", [=](){ + auto map = createMap(); + + std::string* keys = new std::string[quantityOfNodes]; + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + for (int i = 0; i < quantityOfNodes; ++i) + { + keys[i] = StringUtils::format("key_%d", i); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + CC_SAFE_DELETE_ARRAY(keys); + + CC_SAFE_FREE(nodes); + } } , + + { "clear", [=](){ + auto map = createMap(); + + CC_PROFILER_START(this->profilerName()); + map.clear(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "size", [=](){ + auto map = createMap(); + + ssize_t size = 0; + CC_PROFILER_START(this->profilerName()); + size = map.size(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "keys(all)", [=](){ + auto map = createMap(); + + CC_PROFILER_START(this->profilerName()); + auto keys = map.keys(); + CC_PROFILER_STOP(this->profilerName()); + + std::string allKeysString; + for (const auto& key : keys) + { + allKeysString += "_" + key; + } + } } , + + { "keys(object)", [=](){ + Map map; + + Node** nodes = (Node**) malloc(sizeof(Node*) * quantityOfNodes); + Node* sameNode = Node::create(); + + for( int i=0; isetTag(i); + map.insert(StringUtils::format("key_%d", i), node); + } + } + + CC_PROFILER_START(this->profilerName()); + auto keys = map.keys(sameNode); + CC_PROFILER_STOP(this->profilerName()); + + std::string allKeysString; + for (const auto& key : keys) + { + allKeysString += "_" + key; + } + + CC_SAFE_FREE(nodes); + } } , + + { "c++11 range loop", [=](){ + auto map = createMap(); + + CC_PROFILER_START(this->profilerName()); + + for (const auto& e : map) + { + e.second->setTag(100); + } + + CC_PROFILER_STOP(this->profilerName()); + } } , + }; - for (const auto& nameCB : nameCBs) + for (const auto& func : testFunctions) { - _testFunctions.push_back(nameCB); + _testFunctions.push_back(func); } } - - -std::string TemplateMapPerfTest::title() const +std::string TemplateMapStringKeyPerfTest::title() const { - return "Map Perf test"; + return "Map String Key Perf test"; } -std::string TemplateMapPerfTest::subtitle() const +std::string TemplateMapStringKeyPerfTest::subtitle() const { return "Test 'insert', See console"; } //////////////////////////////////////////////////////// // -// DictionaryPerfTest +// DictionaryStringKeyPerfTest // //////////////////////////////////////////////////////// -std::string DictionaryPerfTest::title() const -{ - return "Array Perf test"; -} - -std::string DictionaryPerfTest::subtitle() const -{ - return "Test `addObject`, See console"; -} - -void DictionaryPerfTest::generateTestFunctions() +void DictionaryStringKeyPerfTest::generateTestFunctions() { auto createDict = [this](){ Dictionary* ret = Dictionary::create(); @@ -857,6 +922,108 @@ void DictionaryPerfTest::generateTestFunctions() CC_SAFE_FREE(nodes); } } , + + { "removeObjectForKey", [=](){ + auto dict = createDict(); + + std::string* keys = new std::string[quantityOfNodes]; + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + for (int i = 0; i < quantityOfNodes; ++i) + { + keys[i] = StringUtils::format("key_%d", i); + } + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iremoveObjectForKey(keys[i]); + CC_PROFILER_STOP(this->profilerName()); + + CC_SAFE_DELETE_ARRAY(keys); + + CC_SAFE_FREE(nodes); + } } , + + { "removeAllObjects", [=](){ + auto dict = createDict(); + + CC_PROFILER_START(this->profilerName()); + dict->removeAllObjects(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "count", [=](){ + auto dict = createDict(); + + ssize_t size = 0; + CC_PROFILER_START(this->profilerName()); + size = dict->count(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "allKeys", [=](){ + auto dict = createDict(); + + CC_PROFILER_START(this->profilerName()); + auto keys = dict->allKeys(); + CC_PROFILER_STOP(this->profilerName()); + + std::string allKeysString; + Object* obj; + CCARRAY_FOREACH(keys, obj) + { + auto key = static_cast(obj); + allKeysString += (std::string("_") + key->getCString()); + } + } } , + + { "allKeysForObject", [=](){ + Dictionary* dict = Dictionary::create(); + + Node** nodes = (Node**) malloc(sizeof(Node*) * quantityOfNodes); + Node* sameNode = Node::create(); + + for( int i=0; isetObject(sameNode, StringUtils::format("key_%d", i)); + } + else + { + auto node = Node::create(); + node->setTag(i); + dict->setObject(node, StringUtils::format("key_%d", i)); + } + } + + CC_PROFILER_START(this->profilerName()); + auto keys = dict->allKeysForObject(sameNode); + CC_PROFILER_STOP(this->profilerName()); + + std::string allKeysString; + Object* obj; + CCARRAY_FOREACH(keys, obj) + { + auto key = static_cast(obj); + allKeysString += (std::string("_") + key->getCString()); + } + + CC_SAFE_FREE(nodes); + } } , + + { "CCDICT_FOREACH", [=](){ + auto dict = createDict(); + + CC_PROFILER_START(this->profilerName()); + + DictElement* e = nullptr; + CCDICT_FOREACH(dict, e) + { + static_cast(e->getObject())->setTag(100); + } + + CC_PROFILER_STOP(this->profilerName()); + } } , }; for (const auto& func : testFunctions) @@ -865,6 +1032,333 @@ void DictionaryPerfTest::generateTestFunctions() } } +std::string DictionaryStringKeyPerfTest::title() const +{ + return "Dictionary String Key Perf test"; +} + +std::string DictionaryStringKeyPerfTest::subtitle() const +{ + return "Test `setObject`, See console"; +} + + +//////////////////////////////////////////////////////// +// +// TemplateMapIntKeyPerfTest +// +//////////////////////////////////////////////////////// + +void TemplateMapIntKeyPerfTest::generateTestFunctions() +{ + auto createMap = [this](){ + Map ret; + + for( int i=0; isetTag(i); + ret.insert(100+i, node); + } + return ret; + }; + + TestFunction testFunctions[] = { + { "insert", [=](){ + Map map; + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + } } , + + { "at", [=](){ + auto map = createMap(); + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + for (int i = 0; i < quantityOfNodes; ++i) + { + nodes[i]->setTag(100); + } + + CC_SAFE_FREE(nodes); + } } , + + { "erase", [=](){ + auto map = createMap(); + + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iprofilerName()); + + CC_SAFE_FREE(nodes); + } } , + + { "clear", [=](){ + auto map = createMap(); + + CC_PROFILER_START(this->profilerName()); + map.clear(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "size", [=](){ + auto map = createMap(); + + ssize_t size = 0; + CC_PROFILER_START(this->profilerName()); + size = map.size(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "keys(all)", [=](){ + auto map = createMap(); + + CC_PROFILER_START(this->profilerName()); + auto keys = map.keys(); + CC_PROFILER_STOP(this->profilerName()); + + int allKeysInt = 0; + for (const auto& key : keys) + { + allKeysInt += key; + } + } } , + + { "keys(object)", [=](){ + Map map; + + Node** nodes = (Node**) malloc(sizeof(Node*) * quantityOfNodes); + Node* sameNode = Node::create(); + + for( int i=0; isetTag(i); + map.insert(100 + i, node); + } + } + + CC_PROFILER_START(this->profilerName()); + auto keys = map.keys(sameNode); + CC_PROFILER_STOP(this->profilerName()); + + int allKeysInt = 0; + for (const auto& key : keys) + { + allKeysInt += key; + } + + CC_SAFE_FREE(nodes); + } } , + + { "c++11 range loop", [=](){ + auto map = createMap(); + + CC_PROFILER_START(this->profilerName()); + + for (const auto& e : map) + { + e.second->setTag(100); + } + + CC_PROFILER_STOP(this->profilerName()); + } } , + + }; + + for (const auto& func : testFunctions) + { + _testFunctions.push_back(func); + } +} + +std::string TemplateMapIntKeyPerfTest::title() const +{ + return "Map Integer Key Perf test"; +} + +std::string TemplateMapIntKeyPerfTest::subtitle() const +{ + return "Test 'insert', See console"; +} + +//////////////////////////////////////////////////////// +// +// DictionaryIntKeyPerfTest +// +//////////////////////////////////////////////////////// + +void DictionaryIntKeyPerfTest::generateTestFunctions() +{ + auto createDict = [this](){ + Dictionary* ret = Dictionary::create(); + + for( int i=0; isetTag(i); + ret->setObject(node, 100 + i); + } + return ret; + }; + + TestFunction testFunctions[] = { + { "setObject", [=](){ + Dictionary* dict = Dictionary::create(); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; isetObject(Node::create(), 100 + i); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "objectForKey", [=](){ + auto dict = createDict(); + + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; i(dict->objectForKey(100 + i)); + CC_PROFILER_STOP(this->profilerName()); + + for (int i = 0; i < quantityOfNodes; ++i) + { + nodes[i]->setTag(100); + } + + CC_SAFE_FREE(nodes); + } } , + + { "removeObjectForKey", [=](){ + auto dict = createDict(); + + Node** nodes = (Node**)malloc(sizeof(Node*) * quantityOfNodes); + + CC_PROFILER_START(this->profilerName()); + for( int i=0; iremoveObjectForKey(100 + i); + CC_PROFILER_STOP(this->profilerName()); + + CC_SAFE_FREE(nodes); + } } , + + { "removeAllObjects", [=](){ + auto dict = createDict(); + + CC_PROFILER_START(this->profilerName()); + dict->removeAllObjects(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "count", [=](){ + auto dict = createDict(); + + unsigned int size = 0; + CC_PROFILER_START(this->profilerName()); + size = dict->count(); + CC_PROFILER_STOP(this->profilerName()); + } } , + + { "allKeys", [=](){ + auto dict = createDict(); + + CC_PROFILER_START(this->profilerName()); + auto keys = dict->allKeys(); + CC_PROFILER_STOP(this->profilerName()); + + int allKeysInt = 0; + Object* obj; + CCARRAY_FOREACH(keys, obj) + { + auto key = static_cast(obj); + allKeysInt += key->getValue(); + } + } } , + + { "allKeysForObject", [=](){ + Dictionary* dict = Dictionary::create(); + + Node** nodes = (Node**) malloc(sizeof(Node*) * quantityOfNodes); + Node* sameNode = Node::create(); + + for( int i=0; isetObject(sameNode, 100 + i); + } + else + { + auto node = Node::create(); + node->setTag(i); + dict->setObject(node, 100 + i); + } + } + + CC_PROFILER_START(this->profilerName()); + auto keys = dict->allKeysForObject(sameNode); + CC_PROFILER_STOP(this->profilerName()); + + int allKeysInt = 0; + Object* obj; + CCARRAY_FOREACH(keys, obj) + { + auto key = static_cast(obj); + allKeysInt += key->getValue(); + } + + CC_SAFE_FREE(nodes); + } } , + + { "CCDICT_FOREACH", [=](){ + auto dict = createDict(); + + CC_PROFILER_START(this->profilerName()); + + DictElement* e = nullptr; + CCDICT_FOREACH(dict, e) + { + static_cast(e->getObject())->setTag(100); + } + + CC_PROFILER_STOP(this->profilerName()); + } } , + }; + + for (const auto& func : testFunctions) + { + _testFunctions.push_back(func); + } +} + +std::string DictionaryIntKeyPerfTest::title() const +{ + return "Dictionary Integer Key Perf test"; +} + +std::string DictionaryIntKeyPerfTest::subtitle() const +{ + return "Test `setObject`, See console"; +} + + ///---------------------------------------- void runContainerPerformanceTest() { diff --git a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h index 7f04c113f2..603c759f76 100644 --- a/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h +++ b/samples/Cpp/TestCpp/Classes/PerformanceTest/PerformanceContainerTest.h @@ -44,8 +44,6 @@ public: void dumpProfilerInfo(float dt); // overrides - virtual void onExitTransitionDidStart() override; - virtual void onEnterTransitionDidFinish() override; virtual void update(float dt) override; protected: @@ -85,10 +83,10 @@ public: virtual std::string subtitle() const override; }; -class TemplateMapPerfTest : public PerformanceContainerScene +class TemplateMapStringKeyPerfTest : public PerformanceContainerScene { public: - CREATE_FUNC(TemplateMapPerfTest); + CREATE_FUNC(TemplateMapStringKeyPerfTest); virtual void generateTestFunctions() override; @@ -96,10 +94,32 @@ public: virtual std::string subtitle() const override; }; -class DictionaryPerfTest : public PerformanceContainerScene +class DictionaryStringKeyPerfTest : public PerformanceContainerScene { public: - CREATE_FUNC(DictionaryPerfTest); + CREATE_FUNC(DictionaryStringKeyPerfTest); + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + +class TemplateMapIntKeyPerfTest : public PerformanceContainerScene +{ +public: + CREATE_FUNC(TemplateMapIntKeyPerfTest); + + virtual void generateTestFunctions() override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + +class DictionaryIntKeyPerfTest : public PerformanceContainerScene +{ +public: + CREATE_FUNC(DictionaryIntKeyPerfTest); virtual void generateTestFunctions() override; From 9f9e289f8c875d1e79e33a2693ad4454331ff991 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Mon, 20 Jan 2014 11:30:35 +0800 Subject: [PATCH 171/193] update xcode project. --- build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id index a520602c3d..208a3edca1 100644 --- a/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id +++ b/build/cocos2d_libs.xcodeproj/project.pbxproj.REMOVED.git-id @@ -1 +1 @@ -63e6598ea5798bf42bbd22c2295e65f7c739695a \ No newline at end of file +df164052374ec5c6ec61d99f36a20cc99638b631 \ No newline at end of file From 7d44da43c4354db622d7caaa5595ffbbfdcf74b8 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Mon, 20 Jan 2014 11:34:31 +0800 Subject: [PATCH 172/193] fix compiling error cause by include a non-existent file. --- cocos/2d/CCLabel.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 0cac300283..8f704fb17d 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -24,7 +24,6 @@ ****************************************************************************/ #include "CCLabel.h" -#include "CCFontDefinition.h" #include "CCFontAtlasCache.h" #include "CCLabelTextFormatter.h" #include "CCSprite.h" From 802fc092be76b49a0b7e2f694289e5dca3b81d25 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Mon, 20 Jan 2014 11:43:13 +0800 Subject: [PATCH 173/193] fix compiling error cause by miss include header file. --- cocos/2d/CCLabel.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 8f704fb17d..f5cceec2f4 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -32,6 +32,7 @@ #include "CCSpriteFrame.h" #include "CCDirector.h" #include "renderer/CCRenderer.h" +#include "CCFont.h" #define DISTANCEFIELD_ATLAS_FONTSIZE 50 From f97b40187c8e2e5ad991f6091eb2821eade089e8 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 20 Jan 2014 12:01:40 +0800 Subject: [PATCH 174/193] =?UTF-8?q?closed=20#2789:=20Adds=20a=20macro=20?= =?UTF-8?q?=E2=80=98=E2=80=99USE=5FSTD=5FUNORDERED=5FMAP=E2=80=9D=20for=20?= =?UTF-8?q?switching=20the=20implementation=20of=20Map=20between?= =?UTF-8?q?=20using=20std::unordered=5Fmap=20and=20std::map.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/base/CCMap.h | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/cocos/base/CCMap.h b/cocos/base/CCMap.h index 4b940f2a78..9f7b6b17f6 100644 --- a/cocos/base/CCMap.h +++ b/cocos/base/CCMap.h @@ -25,10 +25,17 @@ #ifndef __CCMAP_H__ #define __CCMAP_H__ +#define USE_STD_UNORDERED_MAP 1 + #include "ccMacros.h" #include "CCObject.h" #include + +#if USE_STD_UNORDERED_MAP #include +#else +#include +#endif NS_CC_BEGIN @@ -44,7 +51,11 @@ public: // ------------------------------------------ // Iterators // ------------------------------------------ +#if USE_STD_UNORDERED_MAP typedef std::unordered_map RefMap; +#else + typedef std::map RefMap; +#endif typedef typename RefMap::iterator iterator; typedef typename RefMap::const_iterator const_iterator; @@ -104,25 +115,39 @@ public: /** Sets capacity of the map */ void reserve(ssize_t capacity) { +#if USE_STD_UNORDERED_MAP _data.reserve(capacity); +#endif } /** Returns the number of buckets in the Map container. */ ssize_t bucketCount() const { +#if USE_STD_UNORDERED_MAP return _data.bucket_count(); +#else + return 0; +#endif } /** Returns the number of elements in bucket n. */ ssize_t bucketSize(ssize_t n) const { +#if USE_STD_UNORDERED_MAP return _data.bucket_size(n); +#else + return 0; +#endif } /** Returns the bucket number where the element with key k is located. */ ssize_t bucket(const K& k) const { +#if USE_STD_UNORDERED_MAP return _data.bucket(k); +#else + return 0; +#endif } /** The number of elements in the map. */ From 87c3f533ea10bd4dc7401eba09704f2277f165e0 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 20 Jan 2014 12:05:06 +0800 Subject: [PATCH 175/193] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index d2c95e4eca..e77a4728ac 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,6 @@ cocos2d-x-3.0beta2 ?.? ? [All] + [NEW] Adds performance test for Containers(Vector<>, Array, Map, Dictionary). [NEW] DrawNode supports to draw triangle, quad bezier, cubic bezier. [NEW] Console: added the 'textures', 'fileutils dump' and 'config' commands [NEW] GLCache: glActiveTexture() is cached with GL::activeTexture(). All code MUST call the cached version in order to work correctly From 0468a1234b4f1196327f8c0c2668799de1954eca Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 20 Jan 2014 14:22:30 +0800 Subject: [PATCH 176/193] =?UTF-8?q?A=20typo=20fix=20in=20EventDispatcher,?= =?UTF-8?q?=20DirtyFlag::FIXED=5FPRITORY=20=E2=80=94>=20DirtyFlag::FIXED?= =?UTF-8?q?=5FPRIORITY.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCEventDispatcher.cpp | 6 +++--- cocos/2d/CCEventDispatcher.h | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 609b67c3cd..66f502a5ff 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -354,7 +354,7 @@ void EventDispatcher::forceAddEventListener(EventListener* listener) } else { - setDirty(listenerID, DirtyFlag::FIXED_PRITORY); + setDirty(listenerID, DirtyFlag::FIXED_PRIORITY); } } @@ -496,7 +496,7 @@ void EventDispatcher::setPriority(EventListener* listener, int fixedPriority) if (listener->getFixedPriority() != fixedPriority) { listener->setFixedPriority(fixedPriority); - setDirty(listener->getListenerID(), DirtyFlag::FIXED_PRITORY); + setDirty(listener->getListenerID(), DirtyFlag::FIXED_PRIORITY); } return; } @@ -921,7 +921,7 @@ void EventDispatcher::sortEventListeners(const EventListener::ListenerID& listen if (dirtyFlag != DirtyFlag::NONE) { - if ((int)dirtyFlag & (int)DirtyFlag::FIXED_PRITORY) + if ((int)dirtyFlag & (int)DirtyFlag::FIXED_PRIORITY) { sortEventListenersOfFixedPriority(listenerID); } diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index cb62e4711b..69f7683b8e 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -207,9 +207,9 @@ protected: enum class DirtyFlag { NONE = 0, - FIXED_PRITORY = 1 << 0, + FIXED_PRIORITY = 1 << 0, SCENE_GRAPH_PRIORITY = 1 << 1, - ALL = FIXED_PRITORY | SCENE_GRAPH_PRIORITY + ALL = FIXED_PRIORITY | SCENE_GRAPH_PRIORITY }; /** Sets the dirty flag for a specified listener ID */ From 9f793f8a9b0f9aa120795f9e72c0411c3a2e86d6 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 20 Jan 2014 15:03:30 +0800 Subject: [PATCH 177/193] =?UTF-8?q?Warning=20fixes:=201)=20getZOrder=20?= =?UTF-8?q?=E2=80=94>=20getLocalZOrder.=202)=20long=20=E2=80=94>=20int?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCClippingNode.cpp | 2 +- cocos/2d/CCEventDispatcher.cpp | 2 +- cocos/2d/CCNode.cpp | 8 ++++---- cocos/2d/CCNodeGrid.cpp | 2 +- cocos/2d/CCParticleBatchNode.cpp | 6 +++--- cocos/2d/CCSprite.cpp | 4 ++-- cocos/2d/CCSpriteBatchNode.cpp | 12 ++++++------ cocos/2d/ccUTF8.cpp | 2 +- cocos/editor-support/spine/Atlas.cpp | 10 +++++----- cocos/gui/UILayout.cpp | 2 +- cocos/gui/UIWidget.cpp | 2 +- cocos/network/WebSocket.cpp | 4 +++- cocos/network/WebSocket.h | 9 ++++++--- extensions/GUI/CCScrollView/CCScrollView.cpp | 2 +- .../TestCpp/Classes/ParticleTest/ParticleTest.cpp | 2 +- .../Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- samples/Cpp/TestCpp/Classes/controller.cpp | 2 +- 17 files changed, 39 insertions(+), 34 deletions(-) diff --git a/cocos/2d/CCClippingNode.cpp b/cocos/2d/CCClippingNode.cpp index f20b4d2778..47cd72a881 100644 --- a/cocos/2d/CCClippingNode.cpp +++ b/cocos/2d/CCClippingNode.cpp @@ -252,7 +252,7 @@ void ClippingNode::visit() { auto node = _children.at(i); - if ( node && node->getZOrder() < 0 ) + if ( node && node->getLocalZOrder() < 0 ) node->visit(); else break; diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 66f502a5ff..49b9411db7 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -206,7 +206,7 @@ void EventDispatcher::visitTarget(Node* node) { child = children.at(i); - if ( child && child->getZOrder() < 0 ) + if ( child && child->getLocalZOrder() < 0 ) visitTarget(child); else break; diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index e631d0f02a..f28ca6ebc2 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -72,8 +72,8 @@ bool nodeComparisonLess(const RCPtr& pp1, const RCPtr& pp2) Node *n1 = static_cast(p1); Node *n2 = static_cast(p2); - return( n1->getZOrder() < n2->getZOrder() || - ( n1->getZOrder() == n2->getZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() ) + return( n1->getLocalZOrder() < n2->getLocalZOrder() || + ( n1->getLocalZOrder() == n2->getLocalZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() ) ); } #else @@ -82,8 +82,8 @@ bool nodeComparisonLess(Object* p1, Object* p2) Node *n1 = static_cast(p1); Node *n2 = static_cast(p2); - return( n1->getZOrder() < n2->getZOrder() || - ( n1->getZOrder() == n2->getZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() ) + return( n1->getLocalZOrder() < n2->getLocalZOrder() || + ( n1->getLocalZOrder() == n2->getLocalZOrder() && n1->getOrderOfArrival() < n2->getOrderOfArrival() ) ); } #endif diff --git a/cocos/2d/CCNodeGrid.cpp b/cocos/2d/CCNodeGrid.cpp index f8c5d5accb..be7c1d1a8c 100644 --- a/cocos/2d/CCNodeGrid.cpp +++ b/cocos/2d/CCNodeGrid.cpp @@ -125,7 +125,7 @@ void NodeGrid::visit() { auto node = _children.at(i); - if ( node && node->getZOrder() < 0 ) + if ( node && node->getLocalZOrder() < 0 ) node->visit(); else break; diff --git a/cocos/2d/CCParticleBatchNode.cpp b/cocos/2d/CCParticleBatchNode.cpp index bca1c3eb28..f54d823b1b 100644 --- a/cocos/2d/CCParticleBatchNode.cpp +++ b/cocos/2d/CCParticleBatchNode.cpp @@ -218,7 +218,7 @@ void ParticleBatchNode::reorderChild(Node * aChild, int zOrder) ParticleSystem* child = static_cast(aChild); - if( zOrder == child->getZOrder() ) + if( zOrder == child->getLocalZOrder() ) { return; } @@ -280,7 +280,7 @@ void ParticleBatchNode::getCurrentIndex(int* oldIndex, int* newIndex, Node* chil Node* pNode = _children.at(i); // new index - if( pNode->getZOrder() > z && ! foundNewIdx ) + if( pNode->getLocalZOrder() > z && ! foundNewIdx ) { *newIndex = i; foundNewIdx = true; @@ -325,7 +325,7 @@ int ParticleBatchNode::searchNewPositionInChildrenForZ(int z) for( int i=0; i < count; i++ ) { Node *child = _children.at(i); - if (child->getZOrder() > z) + if (child->getLocalZOrder() > z) { return i; } diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index 65c7a24b50..264e29c693 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -822,8 +822,8 @@ void Sprite::sortAllChildren() auto tempJ = static_cast( _children->getObjectAtIndex(j) ); //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller - while(j>=0 && ( tempI->getZOrder() < tempJ->getZOrder() || - ( tempI->getZOrder() == tempJ->getZOrder() && + while(j>=0 && ( tempI->getLocalZOrder() < tempJ->getLocalZOrder() || + ( tempI->getLocalZOrder() == tempJ->getLocalZOrder() && tempI->getOrderOfArrival() < tempJ->getOrderOfArrival() ) ) ) { _children->fastSetObject( tempJ, j+1 ); diff --git a/cocos/2d/CCSpriteBatchNode.cpp b/cocos/2d/CCSpriteBatchNode.cpp index 0526b6768d..e8dc9cf8cb 100644 --- a/cocos/2d/CCSpriteBatchNode.cpp +++ b/cocos/2d/CCSpriteBatchNode.cpp @@ -179,7 +179,7 @@ void SpriteBatchNode::reorderChild(Node *child, int zOrder) CCASSERT(child != nullptr, "the child should not be null"); CCASSERT(_children.contains(child), "Child doesn't belong to Sprite"); - if (zOrder == child->getZOrder()) + if (zOrder == child->getLocalZOrder()) { return; } @@ -277,7 +277,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, ssize_t* curIndex) { bool needNewIndex=true; - if (array.at(0)->getZOrder() >= 0) + if (array.at(0)->getLocalZOrder() >= 0) { //all children are in front of the parent oldIndex = sprite->getAtlasIndex(); @@ -294,7 +294,7 @@ void SpriteBatchNode::updateAtlasIndex(Sprite* sprite, ssize_t* curIndex) for(const auto &child: array) { Sprite* sp = static_cast(child); - if (needNewIndex && sp->getZOrder() >= 0) + if (needNewIndex && sp->getLocalZOrder() >= 0) { oldIndex = sprite->getAtlasIndex(); sprite->setAtlasIndex(*curIndex); @@ -392,7 +392,7 @@ ssize_t SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, ssize_t index) auto& children = parent->getChildren(); for(const auto &child: children) { Sprite* sp = static_cast(child); - if (sp && (sp->getZOrder() < 0)) + if (sp && (sp->getLocalZOrder() < 0)) { index = rebuildIndexInOrder(sp, index); } @@ -407,7 +407,7 @@ ssize_t SpriteBatchNode::rebuildIndexInOrder(Sprite *parent, ssize_t index) for(const auto &child: children) { Sprite* sp = static_cast(child); - if (sp && (sp->getZOrder() >= 0)) + if (sp && (sp->getLocalZOrder() >= 0)) { index = rebuildIndexInOrder(sp, index); } @@ -488,7 +488,7 @@ ssize_t SpriteBatchNode::atlasIndexForChild(Sprite *sprite, int nZ) else { // previous & sprite belong to the same branch - if ((prev->getZOrder() < 0 && nZ < 0) || (prev->getZOrder() >= 0 && nZ >= 0)) + if ((prev->getLocalZOrder() < 0 && nZ < 0) || (prev->getLocalZOrder() >= 0 && nZ >= 0)) { return highestAtlasIndexInChild(prev) + 1; } diff --git a/cocos/2d/ccUTF8.cpp b/cocos/2d/ccUTF8.cpp index c4b9893a04..7ebf8a0e31 100644 --- a/cocos/2d/ccUTF8.cpp +++ b/cocos/2d/ccUTF8.cpp @@ -281,7 +281,7 @@ unsigned short* cc_utf8_to_utf16(const char* str_old, int length/* = -1 */, int* { long len = cc_utf8_strlen(str_old, length); if (rUtf16Size != nullptr) { - *rUtf16Size = len; + *rUtf16Size = static_cast(len); } unsigned short* str_new = new unsigned short[len + 1]; diff --git a/cocos/editor-support/spine/Atlas.cpp b/cocos/editor-support/spine/Atlas.cpp index b63c923618..8addbc11d5 100644 --- a/cocos/editor-support/spine/Atlas.cpp +++ b/cocos/editor-support/spine/Atlas.cpp @@ -142,7 +142,7 @@ static int readTuple (const char* end, Str tuple[]) { } static char* mallocString (Str* str) { - int length = str->end - str->begin; + long length = str->end - str->begin; char* string = MALLOC(char, length + 1); memcpy(string, str->begin, length); string[length] = '\0'; @@ -150,7 +150,7 @@ static char* mallocString (Str* str) { } static int indexOf (const char** array, int count, Str* str) { - int length = str->end - str->begin; + long length = str->end - str->begin; int i; for (i = count - 1; i >= 0; i--) if (strncmp(array[i], str->begin, length) == 0) return i; @@ -162,7 +162,7 @@ static int equals (Str* str, const char* other) { } static int toInt (Str* str) { - return strtol(str->begin, (char**)&str->end, 10); + return static_cast(strtol(str->begin, (char**)&str->end, 10)); } static spAtlas* abortAtlas (spAtlas* self) { @@ -177,7 +177,7 @@ static const char* textureFilterNames[] = {"Nearest", "Linear", "MipMap", "MipMa spAtlas* spAtlas_readAtlas (const char* begin, int length, const char* dir) { int count; const char* end = begin + length; - int dirLength = strlen(dir); + size_t dirLength = strlen(dir); int needsSlash = dirLength > 0 && dir[dirLength - 1] != '/' && dir[dirLength - 1] != '\\'; spAtlas* self = NEW(spAtlas); @@ -289,7 +289,7 @@ spAtlas* spAtlas_readAtlas (const char* begin, int length, const char* dir) { } spAtlas* spAtlas_readAtlasFile (const char* path) { - int dirLength; + long dirLength; char *dir; int length; const char* data; diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp index 8a64ad7ed4..e73a2cab3a 100644 --- a/cocos/gui/UILayout.cpp +++ b/cocos/gui/UILayout.cpp @@ -235,7 +235,7 @@ void Layout::stencilClippingVisit() { auto node = _children.at(i); - if ( node && node->getZOrder() < 0 ) + if ( node && node->getLocalZOrder() < 0 ) node->visit(); else break; diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index d09a8fde39..d83c7a42db 100644 --- a/cocos/gui/UIWidget.cpp +++ b/cocos/gui/UIWidget.cpp @@ -255,7 +255,7 @@ Widget* Widget::getChildByName(const char *name) void Widget::addNode(Node* node) { - addNode(node, node->getZOrder(), node->getTag()); + addNode(node, node->getLocalZOrder(), node->getTag()); } void Widget::addNode(Node * node, int zOrder) diff --git a/cocos/network/WebSocket.cpp b/cocos/network/WebSocket.cpp index 5e17487567..3b5b3559f7 100644 --- a/cocos/network/WebSocket.cpp +++ b/cocos/network/WebSocket.cpp @@ -28,6 +28,8 @@ ****************************************************************************/ #include "WebSocket.h" +#include "CCDirector.h" +#include "CCScheduler.h" #include #include @@ -521,7 +523,7 @@ int WebSocket::onSocketCallback(struct libwebsocket_context *ctx, size_t remaining = data->len - data->issued; size_t n = std::min(remaining, c_bufferSize ); - CCLOG("[websocket:send] total: %d, sent: %d, remaining: %d, buffer size: %d", data->len, data->issued, remaining, n); + CCLOG("[websocket:send] total: %d, sent: %d, remaining: %d, buffer size: %d", static_cast(data->len), static_cast(data->issued), static_cast(remaining), static_cast(n)); unsigned char* buf = new unsigned char[LWS_SEND_BUFFER_PRE_PADDING + n + LWS_SEND_BUFFER_POST_PADDING]; diff --git a/cocos/network/WebSocket.h b/cocos/network/WebSocket.h index 738abf2c2f..fb3badd62b 100644 --- a/cocos/network/WebSocket.h +++ b/cocos/network/WebSocket.h @@ -30,8 +30,11 @@ #ifndef __CC_WEBSOCKET_H__ #define __CC_WEBSOCKET_H__ -#include "cocos2d.h" +#include "CCPlatformMacros.h" + #include +#include +#include struct libwebsocket; struct libwebsocket_context; @@ -153,8 +156,8 @@ private: unsigned int _port; std::string _path; - size_t _pendingFrameDataLen; - unsigned int _currentDataLen; + ssize_t _pendingFrameDataLen; + ssize_t _currentDataLen; char *_currentData; friend class WsThreadHelper; diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 0c4fbe72a3..4cc76e6dde 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -572,7 +572,7 @@ void ScrollView::visit() for( ; i < _children.size(); i++ ) { Node *child = _children.at(i); - if ( child->getZOrder() < 0 ) + if ( child->getLocalZOrder() < 0 ) { child->visit(); } diff --git a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp index 54a2095f42..4893e74bdb 100644 --- a/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp +++ b/samples/Cpp/TestCpp/Classes/ParticleTest/ParticleTest.cpp @@ -1790,7 +1790,7 @@ void ReorderParticleSystems::onEnter() void ReorderParticleSystems::reorderSystem(float time) { auto system = static_cast(_batchNode->getChildren().at(1)); - _batchNode->reorderChild(system, system->getZOrder() - 1); + _batchNode->reorderChild(system, system->getLocalZOrder() - 1); } diff --git a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index 8f885e907c..e747e4ff8e 100644 --- a/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/samples/Cpp/TestCpp/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -689b357d7acda141d13a3dfc4cb52aabb274f6cd \ No newline at end of file +c098eac3962854bc7d1981ec16aad7d2907c0e33 \ No newline at end of file diff --git a/samples/Cpp/TestCpp/Classes/controller.cpp b/samples/Cpp/TestCpp/Classes/controller.cpp index b9713167a1..471a399298 100644 --- a/samples/Cpp/TestCpp/Classes/controller.cpp +++ b/samples/Cpp/TestCpp/Classes/controller.cpp @@ -155,7 +155,7 @@ void TestController::menuCallback(Object * sender) // get the userdata, it's the index of the menu item clicked auto menuItem = static_cast(sender); - int idx = menuItem->getZOrder() - 10000; + int idx = menuItem->getLocalZOrder() - 10000; // create the test scene and run it auto scene = g_aTestNames[idx].callback(); From 432534d85757b6767ab334b2ab0a027bc91eadca Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 20 Jan 2014 17:31:12 +0800 Subject: [PATCH 178/193] =?UTF-8?q?#include=20=E2=80=9Ccocos2d.h=E2=80=9D?= =?UTF-8?q?=20was=20FORBIDDEN=20in=20cocos=20modules.=20Reduces=20the=20de?= =?UTF-8?q?pendence=20=20when=20header=20file=20changes.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCFontCharMap.cpp | 4 ++++ cocos/2d/CCFontCharMap.h | 1 - cocos/network/SocketIO.cpp | 3 +++ cocos/network/SocketIO.h | 5 ++++- cocos/storage/local-storage/LocalStorage.cpp | 2 +- cocos/storage/local-storage/LocalStorageAndroid.cpp | 2 +- 6 files changed, 13 insertions(+), 4 deletions(-) diff --git a/cocos/2d/CCFontCharMap.cpp b/cocos/2d/CCFontCharMap.cpp index 217312762b..85f61d57de 100644 --- a/cocos/2d/CCFontCharMap.cpp +++ b/cocos/2d/CCFontCharMap.cpp @@ -25,6 +25,10 @@ #include "CCFontCharMap.h" #include "CCFontAtlas.h" +#include "CCFileUtils.h" +#include "CCDirector.h" +#include "CCTextureCache.h" +#include "ccUTF8.h" NS_CC_BEGIN diff --git a/cocos/2d/CCFontCharMap.h b/cocos/2d/CCFontCharMap.h index 83352ddb4e..a39b5f7032 100644 --- a/cocos/2d/CCFontCharMap.h +++ b/cocos/2d/CCFontCharMap.h @@ -26,7 +26,6 @@ #ifndef _CCFontCharMap_h_ #define _CCFontCharMap_h_ -#include "cocos2d.h" #include "CCFont.h" NS_CC_BEGIN diff --git a/cocos/network/SocketIO.cpp b/cocos/network/SocketIO.cpp index c38ed4c70d..cc4b489e32 100644 --- a/cocos/network/SocketIO.cpp +++ b/cocos/network/SocketIO.cpp @@ -28,9 +28,12 @@ ****************************************************************************/ #include "SocketIO.h" +#include "CCDirector.h" +#include "CCScheduler.h" #include "WebSocket.h" #include "HttpClient.h" #include +#include NS_CC_BEGIN diff --git a/cocos/network/SocketIO.h b/cocos/network/SocketIO.h index 599a6c4cd0..8562fc1ba9 100644 --- a/cocos/network/SocketIO.h +++ b/cocos/network/SocketIO.h @@ -59,7 +59,10 @@ in the onClose method the pointer should be set to NULL or used to connect to a #ifndef __CC_SOCKETIO_H__ #define __CC_SOCKETIO_H__ -#include "cocos2d.h" +#include "CCPlatformMacros.h" +#include "CCMap.h" + +#include NS_CC_BEGIN diff --git a/cocos/storage/local-storage/LocalStorage.cpp b/cocos/storage/local-storage/LocalStorage.cpp index 436432abce..dd0b5e3635 100644 --- a/cocos/storage/local-storage/LocalStorage.cpp +++ b/cocos/storage/local-storage/LocalStorage.cpp @@ -27,7 +27,7 @@ Works on cocos2d-iphone and cocos2d-x. */ -#include "cocos2d.h" +#include "CCPlatformMacros.h" #if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) diff --git a/cocos/storage/local-storage/LocalStorageAndroid.cpp b/cocos/storage/local-storage/LocalStorageAndroid.cpp index 93de8f5dc2..40b4d27bda 100644 --- a/cocos/storage/local-storage/LocalStorageAndroid.cpp +++ b/cocos/storage/local-storage/LocalStorageAndroid.cpp @@ -28,7 +28,7 @@ Works on cocos2d-iphone and cocos2d-x. */ -#include "cocos2d.h" +#include "CCPlatformMacros.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) From 43b2217fcfdff700eaa9182928cefbd69122e075 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 20 Jan 2014 21:30:32 +0800 Subject: [PATCH 179/193] =?UTF-8?q?Include=20fix:=20CCFileUtils.h=20?= =?UTF-8?q?=E2=80=94>=20platform/CCFileUtils.h?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/2d/CCFontCharMap.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCFontCharMap.cpp b/cocos/2d/CCFontCharMap.cpp index 85f61d57de..3036295315 100644 --- a/cocos/2d/CCFontCharMap.cpp +++ b/cocos/2d/CCFontCharMap.cpp @@ -25,7 +25,7 @@ #include "CCFontCharMap.h" #include "CCFontAtlas.h" -#include "CCFileUtils.h" +#include "platform/CCFileUtils.h" #include "CCDirector.h" #include "CCTextureCache.h" #include "ccUTF8.h" From 8b6763a6ac7d1dd4272493eaf6821da7cc8c1182 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 20 Jan 2014 22:31:56 +0800 Subject: [PATCH 180/193] =?UTF-8?q?LocalStorage:=20const=20char*=20?= =?UTF-8?q?=E2=80=94>=20const=20std::string&.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cocos/storage/local-storage/LocalStorage.cpp | 20 +++--- cocos/storage/local-storage/LocalStorage.h | 11 ++-- .../local-storage/LocalStorageAndroid.cpp | 62 ++++++++++--------- 3 files changed, 47 insertions(+), 46 deletions(-) diff --git a/cocos/storage/local-storage/LocalStorage.cpp b/cocos/storage/local-storage/LocalStorage.cpp index dd0b5e3635..38adfb4f8e 100644 --- a/cocos/storage/local-storage/LocalStorage.cpp +++ b/cocos/storage/local-storage/LocalStorage.cpp @@ -55,16 +55,16 @@ static void localStorageCreateTable() printf("Error in CREATE TABLE\n"); } -void localStorageInit( const char *fullpath) +void localStorageInit( const std::string& fullpath/* = "" */) { if( ! _initialized ) { int ret = 0; - if (!fullpath) + if (fullpath.empty()) ret = sqlite3_open(":memory:",&_db); else - ret = sqlite3_open(fullpath, &_db); + ret = sqlite3_open(fullpath.c_str(), &_db); localStorageCreateTable(); @@ -103,12 +103,12 @@ void localStorageFree() } /** sets an item in the LS */ -void localStorageSetItem( const char *key, const char *value) +void localStorageSetItem( const std::string& key, const std::string& value) { assert( _initialized ); - int ok = sqlite3_bind_text(_stmt_update, 1, key, -1, SQLITE_TRANSIENT); - ok |= sqlite3_bind_text(_stmt_update, 2, value, -1, SQLITE_TRANSIENT); + int ok = sqlite3_bind_text(_stmt_update, 1, key.c_str(), -1, SQLITE_TRANSIENT); + ok |= sqlite3_bind_text(_stmt_update, 2, value.c_str(), -1, SQLITE_TRANSIENT); ok |= sqlite3_step(_stmt_update); @@ -119,13 +119,13 @@ void localStorageSetItem( const char *key, const char *value) } /** gets an item from the LS */ -const char* localStorageGetItem( const char *key ) +std::string localStorageGetItem( const std::string& key ) { assert( _initialized ); int ok = sqlite3_reset(_stmt_select); - ok |= sqlite3_bind_text(_stmt_select, 1, key, -1, SQLITE_TRANSIENT); + ok |= sqlite3_bind_text(_stmt_select, 1, key.c_str(), -1, SQLITE_TRANSIENT); ok |= sqlite3_step(_stmt_select); const unsigned char *ret = sqlite3_column_text(_stmt_select, 0); @@ -137,11 +137,11 @@ const char* localStorageGetItem( const char *key ) } /** removes an item from the LS */ -void localStorageRemoveItem( const char *key ) +void localStorageRemoveItem( const std::string& key ) { assert( _initialized ); - int ok = sqlite3_bind_text(_stmt_remove, 1, key, -1, SQLITE_TRANSIENT); + int ok = sqlite3_bind_text(_stmt_remove, 1, key.c_str(), -1, SQLITE_TRANSIENT); ok |= sqlite3_step(_stmt_remove); diff --git a/cocos/storage/local-storage/LocalStorage.h b/cocos/storage/local-storage/LocalStorage.h index c38704616d..c79d46b1ee 100644 --- a/cocos/storage/local-storage/LocalStorage.h +++ b/cocos/storage/local-storage/LocalStorage.h @@ -30,22 +30,21 @@ THE SOFTWARE. #ifndef __JSB_LOCALSTORAGE_H #define __JSB_LOCALSTORAGE_H -#include -#include +#include /** Initializes the database. If path is null, it will create an in-memory DB */ -void localStorageInit( const char *fullpath); +void localStorageInit( const std::string& fullpath = ""); /** Frees the allocated resources */ void localStorageFree(); /** sets an item in the LS */ -void localStorageSetItem( const char *key, const char *value); +void localStorageSetItem( const std::string& key, const std::string& value); /** gets an item from the LS */ -const char* localStorageGetItem( const char *key ); +std::string localStorageGetItem( const std::string& key ); /** removes an item from the LS */ -void localStorageRemoveItem( const char *key ); +void localStorageRemoveItem( const std::string& key ); #endif // __JSB_LOCALSTORAGE_H diff --git a/cocos/storage/local-storage/LocalStorageAndroid.cpp b/cocos/storage/local-storage/LocalStorageAndroid.cpp index 40b4d27bda..39cc8fa523 100644 --- a/cocos/storage/local-storage/LocalStorageAndroid.cpp +++ b/cocos/storage/local-storage/LocalStorageAndroid.cpp @@ -52,27 +52,28 @@ static void splitFilename (std::string& str) } } -void localStorageInit( const char *fullpath) +void localStorageInit( const std::string& fullpath) { - if (fullpath == NULL || strlen(fullpath) == 0) return; + if (fullpath.emty()) + return; - if( ! _initialized ) { - JniMethodInfo t; + if( ! _initialized ) + { + JniMethodInfo t; - if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxLocalStorage", "init", "(Ljava/lang/String;Ljava/lang/String;)Z")) { - std::string strDBFilename = fullpath; - splitFilename(strDBFilename); - jstring jdbName = t.env->NewStringUTF(strDBFilename.c_str()); - jstring jtableName = t.env->NewStringUTF("data"); - jboolean ret = t.env->CallStaticBooleanMethod(t.classID, t.methodID, jdbName, jtableName); - t.env->DeleteLocalRef(jdbName); - t.env->DeleteLocalRef(jtableName); - t.env->DeleteLocalRef(t.classID); - if (ret) { - _initialized = 1; - } - } - + if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxLocalStorage", "init", "(Ljava/lang/String;Ljava/lang/String;)Z")) { + std::string strDBFilename = fullpath; + splitFilename(strDBFilename); + jstring jdbName = t.env->NewStringUTF(strDBFilename.c_str()); + jstring jtableName = t.env->NewStringUTF("data"); + jboolean ret = t.env->CallStaticBooleanMethod(t.classID, t.methodID, jdbName, jtableName); + t.env->DeleteLocalRef(jdbName); + t.env->DeleteLocalRef(jtableName); + t.env->DeleteLocalRef(t.classID); + if (ret) { + _initialized = 1; + } + } } } @@ -93,15 +94,15 @@ void localStorageFree() } /** sets an item in the LS */ -void localStorageSetItem( const char *key, const char *value) +void localStorageSetItem( const std::string& key, const std::string& value) { assert( _initialized ); JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxLocalStorage", "setItem", "(Ljava/lang/String;Ljava/lang/String;)V")) { - jstring jkey = t.env->NewStringUTF(key); - jstring jvalue = t.env->NewStringUTF(value); + jstring jkey = t.env->NewStringUTF(key.c_str()); + jstring jvalue = t.env->NewStringUTF(value.c_str()); t.env->CallStaticVoidMethod(t.classID, t.methodID, jkey, jvalue); t.env->DeleteLocalRef(jkey); t.env->DeleteLocalRef(jvalue); @@ -110,30 +111,31 @@ void localStorageSetItem( const char *key, const char *value) } /** gets an item from the LS */ -const char* localStorageGetItem( const char *key ) +std::string localStorageGetItem( const std::string& key ) { assert( _initialized ); JniMethodInfo t; - String* pStr = NULL; + + std::string ret; if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxLocalStorage", "getItem", "(Ljava/lang/String;)Ljava/lang/String;")) { - jstring jkey = t.env->NewStringUTF(key); - jstring ret = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID, jkey); - pStr = String::create(JniHelper::jstring2string(ret)); - t.env->DeleteLocalRef(ret); + jstring jkey = t.env->NewStringUTF(key.c_str()); + jstring jret = (jstring)t.env->CallStaticObjectMethod(t.classID, t.methodID, jkey); + ret = JniHelper::jstring2string(jret); + t.env->DeleteLocalRef(jret); t.env->DeleteLocalRef(jkey); t.env->DeleteLocalRef(t.classID); } - return pStr ? pStr->getCString() : NULL; + return ret; } /** removes an item from the LS */ -void localStorageRemoveItem( const char *key ) +void localStorageRemoveItem( const std::string& key ) { assert( _initialized ); JniMethodInfo t; if (JniHelper::getStaticMethodInfo(t, "org/cocos2dx/lib/Cocos2dxLocalStorage", "removeItem", "(Ljava/lang/String;)V")) { - jstring jkey = t.env->NewStringUTF(key); + jstring jkey = t.env->NewStringUTF(key.c_str()); t.env->CallStaticVoidMethod(t.classID, t.methodID, jkey); t.env->DeleteLocalRef(jkey); t.env->DeleteLocalRef(t.classID); From b6be58482a6cb6e841f755111d3715a93e54305a Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 20 Jan 2014 22:32:20 +0800 Subject: [PATCH 181/193] [Travis CI] Removes -j10. --- tools/travis-scripts/run-script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index aa9c47f5c6..9a83cb77f4 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -50,7 +50,7 @@ elif [ "$PLATFORM"x = "android"x ]; then # Build all samples echo "Building all samples ..." cd $COCOS2DX_ROOT/build - ./android-build.py -n "NDK_BUG=0 -j10" all + ./android-build.py -n "NDK_BUG=0" all # Build template # echo "Building template ..." From e5f723774d0ba284db11a956b2079f18af58c74d Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 20 Jan 2014 22:45:40 +0800 Subject: [PATCH 182/193] Updates jsbindings and localStorage. --- .../js_bindings_system_functions.cpp | 24 +++++++++---------- .../local-storage/LocalStorageAndroid.cpp | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.cpp b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.cpp index 7d1a819fc8..42f3b25597 100644 --- a/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.cpp +++ b/cocos/scripting/javascript/bindings/localstorage/js_bindings_system_functions.cpp @@ -24,15 +24,15 @@ JSBool JSB_localStorageGetItem(JSContext *cx, uint32_t argc, jsval *vp) { JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); JSBool ok = JS_TRUE; - const char* arg0; + std::string arg0; - ok &= jsval_to_charptr( cx, *argvp++, &arg0 ); + ok &= jsval_to_std_string( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - const char* ret_val; + std::string ret_val; - ret_val = localStorageGetItem((char*)arg0 ); + ret_val = localStorageGetItem(arg0); - jsval ret_jsval = c_string_to_jsval(cx, ret_val ? ret_val : ""); + jsval ret_jsval = std_string_to_jsval(cx, ret_val); JS_SET_RVAL(cx, vp, ret_jsval ); return JS_TRUE; @@ -44,12 +44,12 @@ JSBool JSB_localStorageRemoveItem(JSContext *cx, uint32_t argc, jsval *vp) { JSB_PRECONDITION2( argc == 1, cx, JS_FALSE, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); JSBool ok = JS_TRUE; - const char* arg0; + std::string arg0; - ok &= jsval_to_charptr( cx, *argvp++, &arg0 ); + ok &= jsval_to_std_string( cx, *argvp++, &arg0 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - localStorageRemoveItem((char*)arg0 ); + localStorageRemoveItem(arg0); JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; } @@ -60,13 +60,13 @@ JSBool JSB_localStorageSetItem(JSContext *cx, uint32_t argc, jsval *vp) { JSB_PRECONDITION2( argc == 2, cx, JS_FALSE, "Invalid number of arguments" ); jsval *argvp = JS_ARGV(cx,vp); JSBool ok = JS_TRUE; - const char* arg0; const char* arg1; + std::string arg0; std::string arg1; - ok &= jsval_to_charptr( cx, *argvp++, &arg0 ); - ok &= jsval_to_charptr( cx, *argvp++, &arg1 ); + ok &= jsval_to_std_string( cx, *argvp++, &arg0 ); + ok &= jsval_to_std_string( cx, *argvp++, &arg1 ); JSB_PRECONDITION2(ok, cx, JS_FALSE, "Error processing arguments"); - localStorageSetItem((char*)arg0 , (char*)arg1 ); + localStorageSetItem(arg0 , arg1); JS_SET_RVAL(cx, vp, JSVAL_VOID); return JS_TRUE; } diff --git a/cocos/storage/local-storage/LocalStorageAndroid.cpp b/cocos/storage/local-storage/LocalStorageAndroid.cpp index 39cc8fa523..b95fc483ad 100644 --- a/cocos/storage/local-storage/LocalStorageAndroid.cpp +++ b/cocos/storage/local-storage/LocalStorageAndroid.cpp @@ -54,7 +54,7 @@ static void splitFilename (std::string& str) void localStorageInit( const std::string& fullpath) { - if (fullpath.emty()) + if (fullpath.empty()) return; if( ! _initialized ) From 84479b5df08236c1383d43b8e0eef887f6e864c4 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 20 Jan 2014 22:47:23 +0800 Subject: [PATCH 183/193] Reverts run-script.sh. add -j10 to improve build. --- tools/travis-scripts/run-script.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/travis-scripts/run-script.sh b/tools/travis-scripts/run-script.sh index 9a83cb77f4..aa9c47f5c6 100755 --- a/tools/travis-scripts/run-script.sh +++ b/tools/travis-scripts/run-script.sh @@ -50,7 +50,7 @@ elif [ "$PLATFORM"x = "android"x ]; then # Build all samples echo "Building all samples ..." cd $COCOS2DX_ROOT/build - ./android-build.py -n "NDK_BUG=0" all + ./android-build.py -n "NDK_BUG=0 -j10" all # Build template # echo "Building template ..." From 1c318715437e6f81e5dac7a2ab7cd97bb1da78e2 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 20 Jan 2014 23:01:44 +0800 Subject: [PATCH 184/193] Compilation fixes in LocalStorage. include localStorage.h. --- cocos/storage/local-storage/LocalStorage.cpp | 1 + cocos/storage/local-storage/LocalStorageAndroid.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos/storage/local-storage/LocalStorage.cpp b/cocos/storage/local-storage/LocalStorage.cpp index 38adfb4f8e..b612c49a47 100644 --- a/cocos/storage/local-storage/LocalStorage.cpp +++ b/cocos/storage/local-storage/LocalStorage.cpp @@ -27,6 +27,7 @@ Works on cocos2d-iphone and cocos2d-x. */ +#include "LocalStorage.h" #include "CCPlatformMacros.h" #if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) diff --git a/cocos/storage/local-storage/LocalStorageAndroid.cpp b/cocos/storage/local-storage/LocalStorageAndroid.cpp index b95fc483ad..e95d40cf71 100644 --- a/cocos/storage/local-storage/LocalStorageAndroid.cpp +++ b/cocos/storage/local-storage/LocalStorageAndroid.cpp @@ -28,6 +28,7 @@ Works on cocos2d-iphone and cocos2d-x. */ +#include "LocalStorage.h" #include "CCPlatformMacros.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID) @@ -35,7 +36,6 @@ #include #include #include -#include #include "jni.h" #include "jni/JniHelper.h" From 27811768d41ab7b8a3182073eaae61fbcfc3f36b Mon Sep 17 00:00:00 2001 From: Pisces000221 <1786762946@qq.com> Date: Tue, 21 Jan 2014 09:33:20 +0800 Subject: [PATCH 185/193] Correct a mistake in README --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ea9fa791ca..7036f82ffb 100644 --- a/README.md +++ b/README.md @@ -24,12 +24,12 @@ How to start a new game 1. Download the code from [cocos2d download site][4] 2. Enter `tools/project-creator` -3. Run the `create-projects.py` script +3. Run the `create_project.py` script Example: $ cd cocos2d-x/tools/project-creator - $ ./project-creator.py -n mygame -k com.your_company.mygame -l cpp -p /home/mygame + $ ./create_project.py -n mygame -k com.your_company.mygame -l cpp -p /home/mygame $ cd /home/mygame ### Build new project for android ### From 40983801007e3423ef6b39df2bfa905aa3a28cad Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 21 Jan 2014 09:52:37 +0800 Subject: [PATCH 186/193] Update AUTHORS [ci skip] --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index c37354a317..2f5146308e 100644 --- a/AUTHORS +++ b/AUTHORS @@ -718,6 +718,7 @@ Developers: Pisces000221 Corrected a few mistakes in the README file of project-creator. + Corrected a mistake in README. hbbalfred Fixed a bug that crash if file doesn't exist when using FileUtils::getStringFromFile. From d0e3a81d183246d5985180f4dfdab2998f815c31 Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 21 Jan 2014 09:52:43 +0800 Subject: [PATCH 187/193] fix compiling error cause by undefined ssize_t on vs. --- cocos/network/WebSocket.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/network/WebSocket.h b/cocos/network/WebSocket.h index fb3badd62b..3d4e9bf737 100644 --- a/cocos/network/WebSocket.h +++ b/cocos/network/WebSocket.h @@ -31,7 +31,7 @@ #define __CC_WEBSOCKET_H__ #include "CCPlatformMacros.h" - +#include "CCStdC.h" #include #include #include From 0f9c3fa59c94f15da0438fb0802f5bf0de1967c0 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 21 Jan 2014 10:23:05 +0800 Subject: [PATCH 188/193] closed #3789: EventDispatcher supports sorting listeners by global Z and local Z order. And adds relevant test case. --- cocos/2d/CCEventDispatcher.cpp | 43 ++++++++-- cocos/2d/CCEventDispatcher.h | 5 +- cocos/2d/CCNode.cpp | 9 ++ cocos/2d/CCNode.h | 2 +- .../NewEventDispatcherTest.cpp | 85 +++++++++++++++++++ .../NewEventDispatcherTest.h | 16 ++++ 6 files changed, 152 insertions(+), 8 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 49b9411db7..538a26fd13 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -191,7 +191,7 @@ EventDispatcher::~EventDispatcher() removeAllEventListeners(); } -void EventDispatcher::visitTarget(Node* node) +void EventDispatcher::visitTarget(Node* node, bool isRootNode) { int i = 0; auto& children = node->getChildren(); @@ -207,23 +207,54 @@ void EventDispatcher::visitTarget(Node* node) child = children.at(i); if ( child && child->getLocalZOrder() < 0 ) - visitTarget(child); + visitTarget(child, false); else break; } - _nodePriorityMap.insert(std::make_pair(node, ++_nodePriorityIndex)); + if (_nodeListenersMap.find(node) != _nodeListenersMap.end()) + { + _globalZOrderNodeMap[node->getGlobalZOrder()].push_back(node); + } for( ; i < childrenCount; i++ ) { child = children.at(i); if (child) - visitTarget(child); + visitTarget(child, false); } } else { - _nodePriorityMap.insert(std::make_pair(node, ++_nodePriorityIndex)); + if (_nodeListenersMap.find(node) != _nodeListenersMap.end()) + { + _globalZOrderNodeMap[node->getGlobalZOrder()].push_back(node); + } + } + + if (isRootNode) + { + std::vector globalZOrders; + globalZOrders.reserve(_globalZOrderNodeMap.size()); + + for (const auto& e : _globalZOrderNodeMap) + { + globalZOrders.push_back(e.first); + } + + std::sort(globalZOrders.begin(), globalZOrders.end(), [](const int a, const int b){ + return a < b; + }); + + for (const auto& globalZ : globalZOrders) + { + for (const auto& n : _globalZOrderNodeMap[globalZ]) + { + _nodePriorityMap[n] = ++_nodePriorityIndex; + } + } + + _globalZOrderNodeMap.clear(); } } @@ -947,7 +978,7 @@ void EventDispatcher::sortEventListenersOfSceneGraphPriority(const EventListener _nodePriorityIndex = 0; _nodePriorityMap.clear(); - visitTarget(rootNode); + visitTarget(rootNode, true); // After sort: priority < 0, > 0 auto sceneGraphlisteners = listeners->getSceneGraphPriorityListeners(); diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index 69f7683b8e..13cfe77232 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -216,7 +216,7 @@ protected: void setDirty(const EventListener::ListenerID& listenerID, DirtyFlag flag); /** Walks though scene graph to get the draw order for each node, it's called before sorting event listener with scene graph priority */ - void visitTarget(Node* node); + void visitTarget(Node* node, bool isRootNode); /** Listeners map */ std::unordered_map _listeners; @@ -230,6 +230,9 @@ protected: /** The map of node and its event priority */ std::unordered_map _nodePriorityMap; + /** key: Global Z Order, value: Sorted Nodes */ + std::unordered_map> _globalZOrderNodeMap; + /** The listeners to be added after dispatching event */ std::vector _toAddedListeners; diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index f28ca6ebc2..56cc9b8c10 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -232,6 +232,15 @@ void Node::setLocalZOrder(int z) _eventDispatcher->setDirtyForNode(this); } +void Node::setGlobalZOrder(float zOrder) +{ + if (_globalZOrder != zOrder) + { + _globalZOrder = zOrder; + _eventDispatcher->setDirtyForNode(this); + } +} + /// vertexZ getter float Node::getVertexZ() const { diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 0598773a7c..df2f29d86d 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -208,7 +208,7 @@ public: @since v3.0 */ - virtual void setGlobalZOrder(float zOrder) { _globalZOrder = zOrder; } + virtual void setGlobalZOrder(float zOrder); /** * Returns the Node's Global Z Order. * diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index 194a7bc74c..59ed1fb06f 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -22,6 +22,7 @@ std::function createFunctions[] = CL(RemoveAndRetainNodeTest), CL(RemoveListenerAfterAddingTest), CL(DirectorEventTest), + CL(GlobalZTouchTest), }; unsigned int TEST_CASE_COUNT = sizeof(createFunctions) / sizeof(createFunctions[0]); @@ -859,4 +860,88 @@ std::string DirectorEventTest::subtitle() const return "after visit, after draw, after update, projection changed"; } +// GlobalZTouchTest +GlobalZTouchTest::GlobalZTouchTest() +: _sprite(nullptr) +, _accum(0) +{ + + auto listener1 = EventListenerTouchOneByOne::create(); + listener1->setSwallowTouches(true); + + listener1->onTouchBegan = [](Touch* touch, Event* event){ + auto target = static_cast(event->getCurrentTarget()); + + Point locationInNode = target->convertToNodeSpace(touch->getLocation()); + Size s = target->getContentSize(); + Rect rect = Rect(0, 0, s.width, s.height); + + if (rect.containsPoint(locationInNode)) + { + log("sprite began... x = %f, y = %f", locationInNode.x, locationInNode.y); + target->setOpacity(180); + return true; + } + return false; + }; + + listener1->onTouchMoved = [](Touch* touch, Event* event){ + auto target = static_cast(event->getCurrentTarget()); + target->setPosition(target->getPosition() + touch->getDelta()); + }; + + listener1->onTouchEnded = [=](Touch* touch, Event* event){ + auto target = static_cast(event->getCurrentTarget()); + log("sprite onTouchesEnded.. "); + target->setOpacity(255); + }; + + const int SPRITE_COUNT = 8; + + for (int i = 0; i < SPRITE_COUNT; i++) + { + Sprite *sprite; + auto parent = Node::create(); + if(i==4) + { + sprite = Sprite::create("Images/CyanSquare.png"); + _sprite = sprite; + _sprite->setGlobalZOrder(-1); + } + else + { + sprite = Sprite::create("Images/YellowSquare.png"); + } + + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener1->clone(), sprite); + + parent->addChild(sprite); + this->addChild(parent); + + Size visibleSize = Director::getInstance()->getVisibleSize(); + sprite->setPosition(VisibleRect::left().x + visibleSize.width / (SPRITE_COUNT - 1) * i, VisibleRect::center().y); + } + + this->scheduleUpdate(); +} + +void GlobalZTouchTest::update(float dt) +{ + _accum += dt; + if( _accum > 2.0f) { + float z = _sprite->getGlobalZOrder(); + _sprite->setGlobalZOrder(-z); + _accum = 0; + } +} + +std::string GlobalZTouchTest::title() const +{ + return "Global Z Value, Try touch blue sprite"; +} + +std::string GlobalZTouchTest::subtitle() const +{ + return "Blue Sprite should change go from foreground to background"; +} diff --git a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h index 2de772a6af..aa8d4c4c85 100644 --- a/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h +++ b/samples/Cpp/TestCpp/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h @@ -135,4 +135,20 @@ protected: EventListenerCustom *_event1, *_event2, *_event3, *_event4; }; +class GlobalZTouchTest : public EventDispatcherTestDemo +{ +public: + CREATE_FUNC(GlobalZTouchTest); + GlobalZTouchTest(); + + virtual void update(float dt) override; + + virtual std::string title() const override; + virtual std::string subtitle() const override; + +protected: + Sprite* _sprite; + float _accum; +}; + #endif /* defined(__samples__NewEventDispatcherTest__) */ From f22e4d474f348885080664dbdc38089b2e772d9c Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 21 Jan 2014 10:36:32 +0800 Subject: [PATCH 189/193] move some method to FontFreeType that only relating to FontFreeType from Font. --- cocos/2d/CCFont.cpp | 162 --------------------------------- cocos/2d/CCFont.h | 8 -- cocos/2d/CCFontAtlas.cpp | 16 ++-- cocos/2d/CCFontAtlasCache.cpp | 2 +- cocos/2d/CCFontFreeType.cpp | 165 +++++++++++++++++++++++++++++++++- cocos/2d/CCFontFreeType.h | 8 +- 6 files changed, 181 insertions(+), 180 deletions(-) diff --git a/cocos/2d/CCFont.cpp b/cocos/2d/CCFont.cpp index 14ff1b3651..3c44e8d5d3 100644 --- a/cocos/2d/CCFont.cpp +++ b/cocos/2d/CCFont.cpp @@ -25,12 +25,9 @@ #include "CCFont.h" #include "ccUTF8.h" -#include "edtaa3func.h" NS_CC_BEGIN -const int Font::DistanceMapSpread = 3; - const char * Font::_glyphASCII = "\"!#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþ "; const char * Font::_glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ "; @@ -39,7 +36,6 @@ const char * Font::_glyphNEHE = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLM Font::Font() : _usedGlyphs(GlyphCollection::ASCII) , _customGlyphs(nullptr) -,_distanceFieldEnabled(false) { } @@ -103,164 +99,6 @@ const char * Font::getCurrentGlyphCollection() const } } -unsigned char * Font::makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height) -{ - unsigned int pixelAmount = (width + 2 * DistanceMapSpread) * (height + 2 * DistanceMapSpread); - - short * xdist = (short *) malloc( pixelAmount * sizeof(short) ); - short * ydist = (short *) malloc( pixelAmount * sizeof(short) ); - double * gx = (double *) calloc( pixelAmount, sizeof(double) ); - double * gy = (double *) calloc( pixelAmount, sizeof(double) ); - double * data = (double *) calloc( pixelAmount, sizeof(double) ); - double * outside = (double *) calloc( pixelAmount, sizeof(double) ); - double * inside = (double *) calloc( pixelAmount, sizeof(double) ); - unsigned int i,j; - - // Convert img into double (data) rescale image levels between 0 and 1 - unsigned int outWidth = width + 2 * DistanceMapSpread; - for (i = 0; i < width; ++i) - { - for (j = 0; j < height; ++j) - { - data[j * outWidth + DistanceMapSpread + i] = img[j * width + i] / 255.0; - } - } - - width += 2 * DistanceMapSpread; - height += 2 * DistanceMapSpread; - - // Transform background (outside contour, in areas of 0's) - computegradient( data, width, height, gx, gy); - edtaa3(data, gx, gy, width, height, xdist, ydist, outside); - for( i=0; i< pixelAmount; i++) - if( outside[i] < 0.0 ) - outside[i] = 0.0; - - // Transform foreground (inside contour, in areas of 1's) - for( i=0; i< pixelAmount; i++) - data[i] = 1 - data[i]; - computegradient( data, width, height, gx, gy); - edtaa3(data, gx, gy, width, height, xdist, ydist, inside); - for( i=0; i< pixelAmount; i++) - if( inside[i] < 0.0 ) - inside[i] = 0.0; - - // The bipolar distance field is now outside-inside - double dist; - /* Single channel 8-bit output (bad precision and range, but simple) */ - unsigned char *out = (unsigned char *) malloc( pixelAmount * sizeof(unsigned char) ); - for( i=0; i < pixelAmount; i++) - { - dist = outside[i] - inside[i]; - dist = 128.0 - dist*16; - if( dist < 0 ) dist = 0; - if( dist > 255 ) dist = 255; - out[i] = (unsigned char) dist; - } - /* Dual channel 16-bit output (more complicated, but good precision and range) */ - /*unsigned char *out = (unsigned char *) malloc( pixelAmount * 3 * sizeof(unsigned char) ); - for( i=0; i< pixelAmount; i++) - { - dist = outside[i] - inside[i]; - dist = 128.0 - dist*16; - if( dist < 0.0 ) dist = 0.0; - if( dist >= 256.0 ) dist = 255.999; - // R channel is a copy of the original grayscale image - out[3*i] = img[i]; - // G channel is fraction - out[3*i + 1] = (unsigned char) ( 256 - (dist - floor(dist)* 256.0 )); - // B channel is truncated integer part - out[3*i + 2] = (unsigned char)dist; - }*/ - - free( xdist ); - free( ydist ); - free( gx ); - free( gy ); - free( data ); - free( outside ); - free( inside ); - - return out; -} - -void Font::setDistanceFieldEnabled(bool distanceFieldEnabled) -{ - _distanceFieldEnabled = distanceFieldEnabled; -} - -bool Font::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize) -{ - unsigned char *sourceBitmap = 0; - int sourceWidth = 0; - int sourceHeight = 0; - - sourceBitmap = getGlyphBitmap(charToRender, sourceWidth, sourceHeight); - - if (!sourceBitmap) - return false; - - if (_distanceFieldEnabled) - { - unsigned char * out = makeDistanceMap(sourceBitmap,sourceWidth,sourceHeight); - - int iX = posX; - int iY = posY; - - sourceWidth += 2 * DistanceMapSpread; - sourceHeight += 2 * DistanceMapSpread; - - for (int y = 0; y < sourceHeight; ++y) - { - int bitmap_y = y * sourceWidth; - - for (int x = 0; x < sourceWidth; ++x) - { - /* Dual channel 16-bit output (more complicated, but good precision and range) */ - /*int index = (iX + ( iY * destSize )) * 3; - int index2 = (bitmap_y + x)*3; - destMemory[index] = out[index2]; - destMemory[index + 1] = out[index2 + 1]; - destMemory[index + 2] = out[index2 + 2];*/ - - //Single channel 8-bit output - destMemory[iX + ( iY * destSize )] = out[bitmap_y + x]; - - iX += 1; - } - - iX = posX; - iY += 1; - } - free(out); - return true; - } - - int iX = posX; - int iY = posY; - - for (int y = 0; y < sourceHeight; ++y) - { - int bitmap_y = y * sourceWidth; - - for (int x = 0; x < sourceWidth; ++x) - { - unsigned char cTemp = sourceBitmap[bitmap_y + x]; - - // the final pixel - destMemory[(iX + ( iY * destSize ) )] = cTemp; - - iX += 1; - } - - iX = posX; - iY += 1; - } - - //everything good - return true; -} - unsigned short int * Font::getUTF16Text(const char *text, int &outNumLetters) const { unsigned short* utf16String = cc_utf8_to_utf16(text); diff --git a/cocos/2d/CCFont.h b/cocos/2d/CCFont.h index b164468d40..4b0fbe1171 100644 --- a/cocos/2d/CCFont.h +++ b/cocos/2d/CCFont.h @@ -39,13 +39,6 @@ class FontAtlas; class CC_DLL Font : public Object { public: - static const int DistanceMapSpread; - - static unsigned char * makeDistanceMap(unsigned char *img, unsigned int width, unsigned int height); - void setDistanceFieldEnabled(bool distanceFieldEnabled); - bool isDistanceFieldEnabled() const { return _distanceFieldEnabled;} - bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); - virtual FontAtlas *createFontAtlas() = 0; virtual Size* getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const = 0; @@ -77,7 +70,6 @@ protected: char * _customGlyphs; static const char * _glyphASCII; static const char * _glyphNEHE; - bool _distanceFieldEnabled; }; diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index 70d87f679b..a878aa9203 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -38,7 +38,6 @@ _font(&theFont), _currentPageData(nullptr) { _font->retain(); - _makeDistanceMap = _font->isDistanceFieldEnabled(); FontFreeType* fontTTf = dynamic_cast(_font); if (fontTTf) @@ -50,11 +49,12 @@ _currentPageData(nullptr) _currentPageOrigX = 0; _currentPageOrigY = 0; _letterPadding = 5; - + + _makeDistanceMap = fontTTf->isDistanceFieldEnabled(); if(_makeDistanceMap) { - _commonLineHeight += 2 * Font::DistanceMapSpread; - _letterPadding += 2 * Font::DistanceMapSpread; + _commonLineHeight += 2 * FontFreeType::DistanceMapSpread; + _letterPadding += 2 * FontFreeType::DistanceMapSpread; } _currentPageDataSize = (PAGE_WIDTH * PAGE_HEIGHT * 1); @@ -63,6 +63,10 @@ _currentPageData(nullptr) addTexture(*tex,0); tex->release(); } + else + { + _makeDistanceMap = false; + } } FontAtlas::~FontAtlas() @@ -190,7 +194,7 @@ bool FontAtlas::prepareLetterDefinitions(unsigned short *utf16String) tex->release(); } } - _font->renderCharAt(it->second.letteCharUTF16,_currentPageOrigX,_currentPageOrigY,_currentPageData,PAGE_WIDTH); + fontTTf->renderCharAt(it->second.letteCharUTF16,_currentPageOrigX,_currentPageOrigY,_currentPageData,PAGE_WIDTH); it->second.U = _currentPageOrigX - 1; it->second.V = _currentPageOrigY; @@ -231,7 +235,7 @@ float FontAtlas::getCommonLineHeight() const void FontAtlas::setCommonLineHeight(float newHeight) { if(_makeDistanceMap) - newHeight += 2 * Font::DistanceMapSpread; + newHeight += 2 * FontFreeType::DistanceMapSpread; _commonLineHeight = newHeight; } diff --git a/cocos/2d/CCFontAtlasCache.cpp b/cocos/2d/CCFontAtlasCache.cpp index 44439e2437..1701ac3701 100644 --- a/cocos/2d/CCFontAtlasCache.cpp +++ b/cocos/2d/CCFontAtlasCache.cpp @@ -42,7 +42,7 @@ FontAtlas * FontAtlasCache::getFontAtlasTTF(const std::string& fontFileName, int if ( !tempAtlas ) { - Font *font = FontFreeType::create(fontFileName, size, glyphs, customGlyphs); + FontFreeType *font = FontFreeType::create(fontFileName, size, glyphs, customGlyphs); if (font) { font->setDistanceFieldEnabled(useDistanceField); diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index 1adc138b0f..a3afb8d317 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -29,12 +29,14 @@ THE SOFTWARE. #include "ccUTF8.h" #include "CCFontFreeType.h" #include "platform/CCFileUtils.h" +#include "edtaa3func.h" NS_CC_BEGIN FT_Library FontFreeType::_FTlibrary; bool FontFreeType::_FTInitialized = false; +const int FontFreeType::DistanceMapSpread = 3; FontFreeType * FontFreeType::create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs) { @@ -85,9 +87,8 @@ FT_Library FontFreeType::getFTLibrary() FontFreeType::FontFreeType() : _fontRef(nullptr), _letterPadding(5) +,_distanceFieldEnabled(false) { - if(_distanceFieldEnabled) - _letterPadding += 2 * DistanceMapSpread; } bool FontFreeType::createFontObject(const std::string &fontName, int fontSize) @@ -297,4 +298,164 @@ int FontFreeType::getLetterPadding() const return _letterPadding; } +unsigned char * makeDistanceMap( unsigned char *img, unsigned int width, unsigned int height) +{ + unsigned int pixelAmount = (width + 2 * FontFreeType::DistanceMapSpread) * (height + 2 * FontFreeType::DistanceMapSpread); + + short * xdist = (short *) malloc( pixelAmount * sizeof(short) ); + short * ydist = (short *) malloc( pixelAmount * sizeof(short) ); + double * gx = (double *) calloc( pixelAmount, sizeof(double) ); + double * gy = (double *) calloc( pixelAmount, sizeof(double) ); + double * data = (double *) calloc( pixelAmount, sizeof(double) ); + double * outside = (double *) calloc( pixelAmount, sizeof(double) ); + double * inside = (double *) calloc( pixelAmount, sizeof(double) ); + unsigned int i,j; + + // Convert img into double (data) rescale image levels between 0 and 1 + unsigned int outWidth = width + 2 * FontFreeType::DistanceMapSpread; + for (i = 0; i < width; ++i) + { + for (j = 0; j < height; ++j) + { + data[j * outWidth + FontFreeType::DistanceMapSpread + i] = img[j * width + i] / 255.0; + } + } + + width += 2 * FontFreeType::DistanceMapSpread; + height += 2 * FontFreeType::DistanceMapSpread; + + // Transform background (outside contour, in areas of 0's) + computegradient( data, width, height, gx, gy); + edtaa3(data, gx, gy, width, height, xdist, ydist, outside); + for( i=0; i< pixelAmount; i++) + if( outside[i] < 0.0 ) + outside[i] = 0.0; + + // Transform foreground (inside contour, in areas of 1's) + for( i=0; i< pixelAmount; i++) + data[i] = 1 - data[i]; + computegradient( data, width, height, gx, gy); + edtaa3(data, gx, gy, width, height, xdist, ydist, inside); + for( i=0; i< pixelAmount; i++) + if( inside[i] < 0.0 ) + inside[i] = 0.0; + + // The bipolar distance field is now outside-inside + double dist; + /* Single channel 8-bit output (bad precision and range, but simple) */ + unsigned char *out = (unsigned char *) malloc( pixelAmount * sizeof(unsigned char) ); + for( i=0; i < pixelAmount; i++) + { + dist = outside[i] - inside[i]; + dist = 128.0 - dist*16; + if( dist < 0 ) dist = 0; + if( dist > 255 ) dist = 255; + out[i] = (unsigned char) dist; + } + /* Dual channel 16-bit output (more complicated, but good precision and range) */ + /*unsigned char *out = (unsigned char *) malloc( pixelAmount * 3 * sizeof(unsigned char) ); + for( i=0; i< pixelAmount; i++) + { + dist = outside[i] - inside[i]; + dist = 128.0 - dist*16; + if( dist < 0.0 ) dist = 0.0; + if( dist >= 256.0 ) dist = 255.999; + // R channel is a copy of the original grayscale image + out[3*i] = img[i]; + // G channel is fraction + out[3*i + 1] = (unsigned char) ( 256 - (dist - floor(dist)* 256.0 )); + // B channel is truncated integer part + out[3*i + 2] = (unsigned char)dist; + }*/ + + free( xdist ); + free( ydist ); + free( gx ); + free( gy ); + free( data ); + free( outside ); + free( inside ); + + return out; +} + +void FontFreeType::setDistanceFieldEnabled(bool distanceFieldEnabled) +{ + if(distanceFieldEnabled) + _letterPadding += 2 * DistanceMapSpread; + _distanceFieldEnabled = distanceFieldEnabled; +} + +bool FontFreeType::renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize) +{ + unsigned char *sourceBitmap = 0; + int sourceWidth = 0; + int sourceHeight = 0; + + sourceBitmap = getGlyphBitmap(charToRender, sourceWidth, sourceHeight); + + if (!sourceBitmap) + return false; + + if (_distanceFieldEnabled) + { + unsigned char * out = makeDistanceMap(sourceBitmap,sourceWidth,sourceHeight); + + int iX = posX; + int iY = posY; + + sourceWidth += 2 * DistanceMapSpread; + sourceHeight += 2 * DistanceMapSpread; + + for (int y = 0; y < sourceHeight; ++y) + { + int bitmap_y = y * sourceWidth; + + for (int x = 0; x < sourceWidth; ++x) + { + /* Dual channel 16-bit output (more complicated, but good precision and range) */ + /*int index = (iX + ( iY * destSize )) * 3; + int index2 = (bitmap_y + x)*3; + destMemory[index] = out[index2]; + destMemory[index + 1] = out[index2 + 1]; + destMemory[index + 2] = out[index2 + 2];*/ + + //Single channel 8-bit output + destMemory[iX + ( iY * destSize )] = out[bitmap_y + x]; + + iX += 1; + } + + iX = posX; + iY += 1; + } + free(out); + return true; + } + + int iX = posX; + int iY = posY; + + for (int y = 0; y < sourceHeight; ++y) + { + int bitmap_y = y * sourceWidth; + + for (int x = 0; x < sourceWidth; ++x) + { + unsigned char cTemp = sourceBitmap[bitmap_y + x]; + + // the final pixel + destMemory[(iX + ( iY * destSize ) )] = cTemp; + + iX += 1; + } + + iX = posX; + iY += 1; + } + + //everything good + return true; +} + NS_CC_END \ No newline at end of file diff --git a/cocos/2d/CCFontFreeType.h b/cocos/2d/CCFontFreeType.h index bcae504c35..33f3f76b36 100644 --- a/cocos/2d/CCFontFreeType.h +++ b/cocos/2d/CCFontFreeType.h @@ -39,11 +39,16 @@ NS_CC_BEGIN class CC_DLL FontFreeType : public Font { public: - + static const int DistanceMapSpread; + static FontFreeType * create(const std::string &fontName, int fontSize, GlyphCollection glyphs, const char *customGlyphs); static void shutdownFreeType(); + void setDistanceFieldEnabled(bool distanceFieldEnabled); + bool isDistanceFieldEnabled() const { return _distanceFieldEnabled;} + bool renderCharAt(unsigned short int charToRender, int posX, int posY, unsigned char *destMemory, int destSize); + virtual FontAtlas * createFontAtlas() override; virtual Size * getAdvancesForTextUTF16(unsigned short *text, int &outNumLetters) const override; @@ -74,6 +79,7 @@ private: int _letterPadding; std::string _fontName; Data _ttfData; + bool _distanceFieldEnabled; }; NS_CC_END From b8adba4c6407791e12812ba0f005b13f0cd78fad Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Tue, 21 Jan 2014 11:59:43 +0800 Subject: [PATCH 190/193] fix crash cause by string(null). --- .../javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id index e540327313..e4b6fdaae3 100644 --- a/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id +++ b/cocos/scripting/javascript/bindings/cocos2d_specifics.cpp.REMOVED.git-id @@ -1 +1 @@ -f92acd30f26c52238e94d2ef1f5b11e760980a67 \ No newline at end of file +46ff200bdf412bcf4cfe2d6ceebadf60657fc4eb \ No newline at end of file From 89c8e7e2fb3e415422f70dabdad1710648a0b8c2 Mon Sep 17 00:00:00 2001 From: zhangbin Date: Tue, 21 Jan 2014 16:25:35 +0800 Subject: [PATCH 191/193] closed #2572, The arithmetic of child's position in ParallaxNode::addChild() is wrong. --- cocos/2d/CCParallaxNode.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/2d/CCParallaxNode.cpp b/cocos/2d/CCParallaxNode.cpp index a2e165ce85..d5f44a5693 100644 --- a/cocos/2d/CCParallaxNode.cpp +++ b/cocos/2d/CCParallaxNode.cpp @@ -101,8 +101,8 @@ void ParallaxNode::addChild(Node *child, int z, const Point& ratio, const Point& ccArrayAppendObjectWithResize(_parallaxArray, (Object*)obj); Point pos = _position; - pos.x = pos.x * ratio.x + offset.x; - pos.y = pos.y * ratio.y + offset.y; + pos.x = -pos.x + pos.x * ratio.x + offset.x; + pos.y = -pos.y + pos.y * ratio.y + offset.y; child->setPosition(pos); Node::addChild(child, z, child->getTag()); From da8e208f47321218c363b140fa8ce8943ec6a02b Mon Sep 17 00:00:00 2001 From: samuele3hu Date: Tue, 21 Jan 2014 16:36:29 +0800 Subject: [PATCH 192/193] close #3802: Add some manual lua-binding functions for the Lable and update the related test cases --- .../lua_cocos2dx_manual.cpp.REMOVED.git-id | 2 +- .../scripting/lua/script/Cocos2dConstants.lua | 8 + .../luaScript/LabelTestNew/LabelTestNew.lua | 309 ++++++++++++++---- 3 files changed, 262 insertions(+), 57 deletions(-) diff --git a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id index e296678e5b..4089e57f63 100644 --- a/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id +++ b/cocos/scripting/lua/bindings/lua_cocos2dx_manual.cpp.REMOVED.git-id @@ -1 +1 @@ -9d9d07e19dba691a22e4d184f0ec0e6ae6207a9b \ No newline at end of file +85c7400aec0f87b3851772fbdbc01bf59f5402d8 \ No newline at end of file diff --git a/cocos/scripting/lua/script/Cocos2dConstants.lua b/cocos/scripting/lua/script/Cocos2dConstants.lua index 9e12b80b6a..2bcb461d27 100644 --- a/cocos/scripting/lua/script/Cocos2dConstants.lua +++ b/cocos/scripting/lua/script/Cocos2dConstants.lua @@ -359,3 +359,11 @@ cc.GLYPHCOLLECTION_NEHE = 1 cc.GLYPHCOLLECTION_ASCII = 2 cc.GLYPHCOLLECTION_CUSTOM = 3 +cc.LabelEffect = +{ + NORMAL = 0, + OUTLINE = 1, + SHADOW = 2, + GLOW = 3, +} + diff --git a/samples/Lua/TestLua/Resources/luaScript/LabelTestNew/LabelTestNew.lua b/samples/Lua/TestLua/Resources/luaScript/LabelTestNew/LabelTestNew.lua index 375f710ddd..68108fc1d9 100644 --- a/samples/Lua/TestLua/Resources/luaScript/LabelTestNew/LabelTestNew.lua +++ b/samples/Lua/TestLua/Resources/luaScript/LabelTestNew/LabelTestNew.lua @@ -42,7 +42,7 @@ function LabelFNTColorAndOpacity.create() local col = cc.LayerColor:create( cc.c4b(128,128,128,255) ) layer:addChild(col, -10) - local label1 = cc.Label:createWithBMFont("Test", "fonts/bitmapFontTest2.fnt") + local label1 = cc.Label:createWithBMFont("fonts/bitmapFontTest2.fnt", "Test") -- testing anchors label1:setAnchorPoint( cc.p(0,0) ) @@ -55,15 +55,15 @@ function LabelFNTColorAndOpacity.create() local repeatAction = cc.RepeatForever:create(seq) label1:runAction(repeatAction) - local label2 = cc.Label:createWithBMFont("Test", "fonts/bitmapFontTest2.fnt") + local label2 = cc.Label:createWithBMFont("fonts/bitmapFontTest2.fnt", "Test") -- testing anchors label2:setAnchorPoint( cc.p(0.5, 0.5) ) label2:setColor(cc.c3b(255, 0, 0 )) layer:addChild(label2, 0, kTagBitmapAtlas2) - label2:runAction( tolua.cast(repeatAction:clone(), "Action") ) + label2:runAction( tolua.cast(repeatAction:clone(), "cc.Action") ) - local label3 = cc.Label:createWithBMFont("Test", "fonts/bitmapFontTest2.fnt") + local label3 = cc.Label:createWithBMFont("fonts/bitmapFontTest2.fnt", "Test") -- testing anchors label3:setAnchorPoint( cc.p(1,1) ) layer:addChild(label3, 0, kTagBitmapAtlas3) @@ -85,13 +85,13 @@ function LabelFNTColorAndOpacity.step(dt) m_time = m_time + dt local string = string.format("%2.2f Test j", m_time) - local label1 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas1), "Label") + local label1 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas1), "cc.Label") label1:setString(string) - local label2 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas2), "Label") + local label2 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas2), "cc.Label") label2:setString(string) - local label3 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas3), "Label") + local label3 = tolua.cast(LabelFNTColorAndOpacity.layer:getChildByTag(kTagBitmapAtlas3), "cc.Label") label3:setString(string) end @@ -121,7 +121,7 @@ function LabelFNTSpriteActions.create() LabelFNTSpriteActions.layer = layer -- Upper Label - local label = cc.Label:createWithBMFont("Bitmap Font Atlas", "fonts/bitmapFontTest.fnt") + local label = cc.Label:createWithBMFont("fonts/bitmapFontTest.fnt", "Bitmap Font Atlas") layer:addChild(label) local s = cc.Director:getInstance():getWinSize() @@ -160,12 +160,12 @@ function LabelFNTSpriteActions.create() -- Bottom Label - local label2 = cc.Label:createWithBMFont("00.0", "fonts/bitmapFontTest.fnt") + local label2 = cc.Label:createWithBMFont("fonts/bitmapFontTest.fnt", "00.0") layer:addChild(label2, 0, kTagBitmapAtlas2) label2:setPosition( cc.p(s.width/2.0, 80) ) local lastChar = label2:getLetter(3) - lastChar:runAction(tolua.cast( rot_4ever:clone(), "Action" )) + lastChar:runAction(tolua.cast( rot_4ever:clone(), "cc.Action" )) layer:registerScriptHandler(LabelFNTSpriteActions.onNodeEvent) @@ -203,7 +203,7 @@ function LabelFNTPadding:create() Helper.initWithLayer(layer) LabelFNTPadding.layer = layer - local label = cc.Label:createWithBMFont("abcdefg", "fonts/bitmapFontTest4.fnt") + local label = cc.Label:createWithBMFont("fonts/bitmapFontTest4.fnt", "abcdefg") layer:addChild(label) local s = cc.Director:getInstance():getWinSize() @@ -231,17 +231,17 @@ function LabelFNTOffset:create() LabelFNTOffset.layer = layer local s = cc.Director:getInstance():getWinSize() - local label = cc.Label:createWithBMFont("FaFeFiFoFu", "fonts/bitmapFontTest5.fnt") + local label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "FaFeFiFoFu") layer:addChild(label) label:setPosition( cc.p(s.width/2, s.height/2+50) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) - label = cc.Label:createWithBMFont("fafefifofu", "fonts/bitmapFontTest5.fnt") + label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "fafefifofu") layer:addChild(label) label:setPosition( cc.p(s.width/2, s.height/2) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) - label = cc.Label:createWithBMFont("aeiou", "fonts/bitmapFontTest5.fnt") + label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "aeiou") layer:addChild(label) label:setPosition( cc.p(s.width/2, s.height/2-50) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) @@ -264,19 +264,19 @@ function LabelFNTColor:create() local s = cc.Director:getInstance():getWinSize() - local label = cc.Label:createWithBMFont("Blue", "fonts/bitmapFontTest5.fnt") + local label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "Blue") label:setColor( cc.c3b(0, 0, 255 )) layer:addChild(label) label:setPosition( cc.p(s.width/2, s.height/4) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) - label = cc.Label:createWithBMFont("Red", "fonts/bitmapFontTest5.fnt") + label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "Red") layer:addChild(label) label:setPosition( cc.p(s.width/2, 2*s.height/4) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) label:setColor( cc.c3b(255, 0, 0) ) - label = cc.Label:createWithBMFont("G", "fonts/bitmapFontTest5.fnt") + label = cc.Label:createWithBMFont("fonts/bitmapFontTest5.fnt", "Green") layer:addChild(label) label:setPosition( cc.p(s.width/2, 3*s.height/4) ) label:setAnchorPoint( cc.p(0.5, 0.5) ) @@ -301,20 +301,23 @@ function LabelTTFColor:create() Helper.initWithLayer(layer) local s = cc.Director:getInstance():getWinSize() + local ttfConfig = {} + ttfConfig.fontFilePath="fonts/arial.ttf" + ttfConfig.fontSize=35 - local label1 = cc.Label:createWithTTF("Green", "fonts/arial.ttf", 35, s.width, cc.VERTICAL_TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_NEHE) + local label1 = cc.Label:createWithTTF(ttfConfig,"Green", cc.VERTICAL_TEXT_ALIGNMENT_CENTER, s.width) label1:setColor( cc.c3b(0, 255, 0 )) layer:addChild(label1) label1:setPosition( cc.p(s.width/2, s.height/5 * 1.5) ) label1:setAnchorPoint( cc.p(0.5, 0.5) ) - local label2 = cc.Label:createWithTTF("Red", "fonts/arial.ttf", 35, s.width, cc.VERTICAL_TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_NEHE) + local label2 = cc.Label:createWithTTF(ttfConfig, "Red", cc.VERTICAL_TEXT_ALIGNMENT_CENTER, s.width) layer:addChild(label2) label2:setPosition( cc.p(s.width/2, s.height/5 * 2.0) ) label2:setAnchorPoint( cc.p(0.5, 0.5) ) label2:setColor( cc.c3b(255, 0, 0) ) - local label3 = cc.Label:createWithTTF("Blue", "fonts/arial.ttf", 35, s.width, cc.VERTICAL_TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_NEHE) + local label3 = cc.Label:createWithTTF(ttfConfig, "Blue", cc.VERTICAL_TEXT_ALIGNMENT_CENTER, s.width) layer:addChild(label3) label3:setPosition( cc.p(s.width/2, s.height/5 * 2.5) ) label3:setAnchorPoint( cc.p(0.5, 0.5) ) @@ -342,7 +345,7 @@ function LabelFNTHundredLabels:create() local i = 0 for i = 0, 100, 1 do local str = string.format("-%d-", i) - local label = cc.Label:createWithBMFont(str, "fonts/bitmapFontTest.fnt") + local label = cc.Label:createWithBMFont("fonts/bitmapFontTest.fnt", str) layer:addChild(label) local s = cc.Director:getInstance():getWinSize() @@ -353,7 +356,7 @@ function LabelFNTHundredLabels:create() end Helper.titleLabel:setString("New Label + .FNT file") - Helper.subtitleLabel:setString("Creating several Labels using the same FNT file; should be fast") + Helper.subtitleLabel:setString("Creating several Labels using the same FNT file should be fast") return layer end @@ -371,7 +374,7 @@ function LabelFNTMultiLine:create() local s = nil -- Left - local label1 = cc.Label:createWithBMFont(" Multi line\nLeft", "fonts/bitmapFontTest3.fnt") + local label1 = cc.Label:createWithBMFont("fonts/bitmapFontTest3.fnt", " Multi line\nLeft") label1:setAnchorPoint(cc.p(0,0)) layer:addChild(label1, 0, kTagBitmapAtlas1) @@ -380,7 +383,7 @@ function LabelFNTMultiLine:create() -- Center - local label2 = cc.Label:createWithBMFont("Multi line\nCenter", "fonts/bitmapFontTest3.fnt") + local label2 = cc.Label:createWithBMFont("fonts/bitmapFontTest3.fnt", "Multi line\nCenter") label2:setAnchorPoint(cc.p(0.5, 0.5)) layer:addChild(label2, 0, kTagBitmapAtlas2) @@ -388,7 +391,7 @@ function LabelFNTMultiLine:create() cclog("content size: %.2fx%.2f", s.width, s.height) -- right - local label3 = cc.Label:createWithBMFont("Multi line\nRight\nThree lines Three", "fonts/bitmapFontTest3.fnt") + local label3 = cc.Label:createWithBMFont("fonts/bitmapFontTest3.fnt", "Multi line\nRight\nThree lines Three") label3:setAnchorPoint(cc.p(1, 1)) layer:addChild(label3, 0, kTagBitmapAtlas3) @@ -433,13 +436,17 @@ function LabelFNTandTTFEmpty.create() local s = cc.Director:getInstance():getWinSize() -- cc.LabelBMFont - local label1 = cc.Label:createWithBMFont("", "fonts/bitmapFontTest3.fnt",cc.TEXT_ALIGNMENT_CENTER,s.width) + local label1 = cc.Label:createWithBMFont("fonts/bitmapFontTest3.fnt", "", cc.TEXT_ALIGNMENT_CENTER,s.width) layer:addChild(label1, 0, kTagBitmapAtlas1) label1:setPosition(cc.p(s.width/2, s.height-100)) -- cc.LabelTTF - local label2 = cc.Label:createWithTTF("", "fonts/arial.ttf", 48, s.width, cc.TEXT_ALIGNMENT_CENTER,cc.GLYPHCOLLECTION_NEHE) + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 48 + local label2 = cc.Label:createWithTTF(ttfConfig, "", cc.TEXT_ALIGNMENT_CENTER, s.width) layer:addChild(label2, 0, kTagBitmapAtlas2) + label2:setAnchorPoint(cc.p(0.5, 0.5)) label2:setPosition(cc.p(s.width/2, s.height/2)) layer:registerScriptHandler(LabelFNTandTTFEmpty.onNodeEvent) @@ -481,7 +488,7 @@ function LabelFNTRetina.create() local s = cc.Director:getInstance():getWinSize() -- cc.LabelBMFont - local label1 = cc.Label:createWithBMFont("TESTING RETINA DISPLAY", "fonts/konqa32.fnt") + local label1 = cc.Label:createWithBMFont("fonts/konqa32.fnt", "TESTING RETINA DISPLAY") label1:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label1) label1:setPosition(cc.p(s.width/2, s.height/2)) @@ -503,7 +510,7 @@ function LabelFNTGlyphDesigner.create() local s = cc.Director:getInstance():getWinSize() - local label1 = cc.Label:createWithBMFont("TESTING RETINA DISPLAY", "fonts/futura-48.fnt") + local label1 = cc.Label:createWithBMFont("fonts/futura-48.fnt", "TESTING RETINA DISPLAY") label1:setAnchorPoint(cc.p(0.5, 0.5)) layer:addChild(label1) @@ -523,8 +530,13 @@ function LabelTTFUnicodeChinese.create() Helper.subtitleLabel:setString("Testing new Label + TTF with Chinese character") local s = cc.Director:getInstance():getWinSize() - - local label1 = cc.Label:createWithTTF("美好的一天啊", "fonts/wt021.ttf", 55, s.width, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_CUSTOM, "美好的一天啊") + local ttfConfig = {} + ttfConfig.fontFilePath="fonts/wt021.ttf" + ttfConfig.fontSize=55 + ttfConfig.glyphs=cc.GLYPHCOLLECTION_CUSTOM + ttfConfig.customGlyphs="美好的一天啊" + + local label1 = cc.Label:createWithTTF(ttfConfig,"美好的一天啊", cc.TEXT_ALIGNMENT_CENTER, s.width) label1:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label1) label1:setPosition(cc.p(s.width/2, s.height/2)) @@ -542,7 +554,7 @@ function LabelFNTUnicodeChinese.create() Helper.initWithLayer(layer) local size = cc.Director:getInstance():getWinSize() - local lable = cc.Label:createWithBMFont("中国", "fonts/bitmapFontChinese.fnt") + local lable = cc.Label:createWithBMFont("fonts/bitmapFontChinese.fnt", "中国") lable:setAnchorPoint(cc.p(0.5,0.5)) lable:setPosition(cc.p(size.width / 2, size.height /2)) layer:addChild(lable) @@ -591,7 +603,7 @@ function LabelFNTMultiLineAlignment.create() local size = cc.Director:getInstance():getWinSize() -- create and initialize a Label - LabelFNTMultiLineAlignment._pLabelShouldRetain = cc.Label:createWithBMFont(LongSentencesExample, "fonts/markerFelt.fnt", cc.TEXT_ALIGNMENT_CENTER, size.width/1.5) + LabelFNTMultiLineAlignment._pLabelShouldRetain = cc.Label:createWithBMFont("fonts/markerFelt.fnt", LongSentencesExample, cc.TEXT_ALIGNMENT_CENTER, size.width/1.5) LabelFNTMultiLineAlignment._pLabelShouldRetain:setAnchorPoint(cc.p(0.5, 0.5)) LabelFNTMultiLineAlignment._pLabelShouldRetain:retain() @@ -677,7 +689,7 @@ end function LabelFNTMultiLineAlignment.stringChanged(tag, sender) - local item = tolua.cast(sender, "MenuItemFont") + local item = tolua.cast(sender, "cc.MenuItemFont") item:setColor(cc.c3b(255, 0, 0)) LabelFNTMultiLineAlignment._pLastAlignmentItem:setColor(cc.c3b(255, 255, 255)) LabelFNTMultiLineAlignment._pLastAlignmentItem = item @@ -695,7 +707,7 @@ end function LabelFNTMultiLineAlignment.alignmentChanged(tag, sender) -- cclog("LabelFNTMultiLineAlignment.alignmentChanged, tag:"..tag) - local item = tolua.cast(sender, "MenuItemFont") + local item = tolua.cast(sender, "cc.MenuItemFont") item:setColor(cc.c3b(255, 0, 0)) LabelFNTMultiLineAlignment._pLastAlignmentItem:setColor(cc.c3b(255, 255, 255)) LabelFNTMultiLineAlignment._pLastAlignmentItem = item @@ -759,17 +771,17 @@ function LabelFNTUNICODELanguages.create() local s = cc.Director:getInstance():getWinSize() - local label1 = cc.Label:createWithBMFont("Buen día", "fonts/arial-unicode-26.fnt", 200, cc.TEXT_ALIGNMENT_LEFT) + local label1 = cc.Label:createWithBMFont("fonts/arial-unicode-26.fnt", "Buen día", cc.TEXT_ALIGNMENT_CENTER, 200) label1:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label1) label1:setPosition(cc.p(s.width/2, s.height/4*3)) - local label2 = cc.Label:createWithBMFont("美好的一天", "fonts/arial-unicode-26.fnt") + local label2 = cc.Label:createWithBMFont("fonts/arial-unicode-26.fnt", "美好的一天") label2:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label2) label2:setPosition(cc.p(s.width/2, s.height/4*2)) - local label3 = cc.Label:createWithBMFont("良い一日を", "fonts/arial-unicode-26.fnt") + local label3 = cc.Label:createWithBMFont("fonts/arial-unicode-26.fnt", "良い一日を") label3:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label3) label3:setPosition(cc.p(s.width/2, s.height/4*1)) @@ -788,21 +800,20 @@ function LabelTTFAlignmentNew.create() Helper.subtitleLabel:setString("Tests alignment values") local s = cc.Director:getInstance():getWinSize() - - local ttf0 = cc.Label:createWithTTF("Alignment 0\nnew line", "fonts/tahoma.ttf", 32) - ttf0:setAlignment(cc.TEXT_ALIGNMENT_LEFT) + local ttfConfig = {} + ttfConfig.fontFilePath="fonts/tahoma.ttf" + ttfConfig.fontSize=32 + local ttf0 = cc.Label:createWithTTF(ttfConfig, "Alignment 0\nnew line", cc.TEXT_ALIGNMENT_LEFT) ttf0:setPosition(cc.p(s.width/2,(s.height/6)*2 - 30)) ttf0:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(ttf0) - local ttf1 = cc.Label:createWithTTF("Alignment 1\nnew line", "fonts/tahoma.ttf", 32) - ttf1:setAlignment(cc.TEXT_ALIGNMENT_CENTER) + local ttf1 = cc.Label:createWithTTF(ttfConfig, "Alignment 1\nnew line", cc.TEXT_ALIGNMENT_CENTER) ttf1:setPosition(cc.p(s.width/2,(s.height/6)*3 - 30)) ttf1:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(ttf1) - local ttf2 = cc.Label:createWithTTF("Alignment 2\nnew line", "fonts/tahoma.ttf", 32) - ttf2:setAlignment(cc.TEXT_ALIGNMENT_RIGHT) + local ttf2 = cc.Label:createWithTTF(ttfConfig, "Alignment 2\nnew line", cc.TEXT_ALIGNMENT_RIGHT) ttf2:setPosition(cc.p(s.width/2,(s.height/6)*4 - 30)) ttf2:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(ttf2) @@ -824,18 +835,26 @@ function LabelTTFUnicodeNew.create() local s = cc.Director:getInstance():getWinSize() local vStep = s.height/9 local vSize = s.height + + local ttfConfig = {} + ttfConfig.fontFilePath="fonts/arial.ttf" + ttfConfig.fontSize=45 + ttfConfig.glyphs=cc.GLYPHCOLLECTION_ASCII - local label1 = cc.Label:createWithTTF("Buen día, ¿cómo te llamas?", "fonts/arial.ttf", 45, s.width, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_ASCII) + local label1 = cc.Label:createWithTTF(ttfConfig,"Buen día, ¿cómo te llamas?", cc.TEXT_ALIGNMENT_CENTER, s.width) label1:setAnchorPoint(cc.p(0.5,0.5)) label1:setPosition(cc.p(s.width/2, vSize - vStep * 4.5)) layer:addChild(label1) - local label2 = cc.Label:createWithTTF("In welcher Straße haben Sie gelebt?", "fonts/arial.ttf", 45, s.width, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_ASCII) + local label2 = cc.Label:createWithTTF(ttfConfig, "In welcher Straße haben Sie gelebt?", cc.TEXT_ALIGNMENT_CENTER, s.width) label2:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label2) label2:setPosition(cc.p(s.width/2, vSize - vStep * 5.5)) - local label3 = cc.Label:createWithTTF("美好的一天", "fonts/wt021.ttf", 45, s.width, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_CUSTOM, "美好的一天") + ttfConfig.fontFilePath = "fonts/wt021.ttf" + ttfConfig.glyphs = cc.GLYPHCOLLECTION_CUSTOM + ttfConfig.customGlyphs = "美好的一天" + local label3 = cc.Label:createWithTTF(ttfConfig, "美好的一天", cc.TEXT_ALIGNMENT_CENTER, s.width) label3:setAnchorPoint(cc.p(0.5,0.5)) layer:addChild(label3) label3:setPosition(cc.p(s.width/2, vSize - vStep * 6.5)) @@ -862,7 +881,7 @@ function LabelFNTBounds.create() layer:addChild(colorlayer, -10) -- cc.LabelBMFont - local label1 = cc.Label:createWithBMFont("Testing Glyph Designer", "fonts/boundsTestFont.fnt", cc.TEXT_ALIGNMENT_CENTER, s.width) + local label1 = cc.Label:createWithBMFont("fonts/boundsTestFont.fnt", "Testing Glyph Designer", cc.TEXT_ALIGNMENT_CENTER, s.width) label1:setAnchorPoint(cc.p(0.5, 0.5)) layer:addChild(label1) @@ -899,8 +918,10 @@ function LabelTTFLongLineWrapping.create() Helper.subtitleLabel:setString("Uses the new Label with TTF. Testing auto-wrapping") local s = cc.Director:getInstance():getWinSize() - - local label1 = cc.Label:createWithTTF(LongSentencesExample, "fonts/arial.ttf", 28, s.width,cc.TEXT_ALIGNMENT_LEFT, cc.GLYPHCOLLECTION_NEHE) + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 28 + local label1 = cc.Label:createWithTTF(ttfConfig, LongSentencesExample, cc.TEXT_ALIGNMENT_LEFT, s.width) label1:setAnchorPoint(cc.p(0.5,1.0)) label1:setPosition(cc.p(s.width/2, s.height/2)) layer:addChild(label1) @@ -927,8 +948,10 @@ function LabelTTFDynamicAlignment.create() LabelTTFDynamicAlignment._eHorizAlign = cc.TEXT_ALIGNMENT_LEFT local s = cc.Director:getInstance():getWinSize() - - LabelTTFDynamicAlignment._label = cc.Label:createWithTTF(LongSentencesExample, "fonts/arial.ttf", 45, s.width, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_NEHE) + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 45 + LabelTTFDynamicAlignment._label = cc.Label:createWithTTF(ttfConfig, LongSentencesExample, cc.TEXT_ALIGNMENT_CENTER, s.width) LabelTTFDynamicAlignment._label:setPosition( cc.p(s.width/2, s.height/2) ) LabelTTFDynamicAlignment._label:setAnchorPoint(cc.p(0.5, 0.5)) layer:addChild(LabelTTFDynamicAlignment._label) @@ -1000,9 +1023,12 @@ function LabelTTFFontsTestNew.create() "fonts/Schwarzwald Regular.ttf", "fonts/Scissor Cuts.ttf", } - + local ttfConfig = {} + ttfConfig.fontFilePath = ttfPaths[0] + ttfConfig.fontSize = 40 for i=1, table.getn(ttfPaths) do - local label = cc.Label:createWithTTF( ttfPaths[i], ttfPaths[i], 40, 0, cc.TEXT_ALIGNMENT_CENTER, cc.GLYPHCOLLECTION_NEHE) + ttfConfig.fontFilePath = ttfPaths[i] + local label = cc.Label:createWithTTF( ttfConfig, ttfPaths[i], cc.TEXT_ALIGNMENT_CENTER, 0) if nil ~= label then label:setPosition( cc.p(s.width/2, ((s.height * 0.6)/table.getn(ttfPaths) * (i -1)) + (s.height/5))) layer:addChild(label) @@ -1029,13 +1055,180 @@ function LabelBMFontTestNew.create() local s = cc.Director:getInstance():getWinSize() - local label1 = cc.Label:createWithBMFont("Hello World, this is testing the new Label using fnt file", "fonts/bitmapFontTest2.fnt", cc.TEXT_ALIGNMENT_CENTER, s.width) + local label1 = cc.Label:createWithBMFont("fonts/bitmapFontTest2.fnt", "Hello World, this is testing the new Label using fnt file", cc.TEXT_ALIGNMENT_CENTER, s.width) label1:setAnchorPoint(cc.p(0.5,0.5)) label1:setPosition(cc.p(s.width/2, s.height/2)) layer:addChild(label1) return layer end + +-------------------------------------------------------- +----- LabelTTFDistanceField +-------------------------------------------------------- +local LabelTTFDistanceField = {} +function LabelTTFDistanceField.create() + local layer = cc.Layer:create() + Helper.initWithLayer(layer) + Helper.titleLabel:setString("New Label + .TTF") + Helper.subtitleLabel:setString("Testing rendering base on DistanceField") + + local s = cc.Director:getInstance():getWinSize() + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 80 + ttfConfig.glyphs = cc.GLYPHCOLLECTION_DYNAMIC + ttfConfig.customGlyphs = nil + ttfConfig.distanceFieldEnabled = true + + local label1 = cc.Label:createWithTTF(ttfConfig,"Distance Field",cc.TEXT_ALIGNMENT_CENTER,s.width) + label1:setAnchorPoint(cc.p(0.5,0.5)) + label1:setPosition(cc.p(s.width/2, s.height/2)) + label1:setColor( cc.c3b(0, 255, 0) ) + local action = cc.Sequence:create(cc.DelayTime:create(1.0), + cc.ScaleTo:create(6.0,5.0,5.0), + cc.ScaleTo:create(6.0,1.0,1.0)) + label1:runAction(cc.RepeatForever:create(action)) + layer:addChild(label1) + + local label2 = cc.Label:createWithTTF(ttfConfig,"Distance Field",cc.TEXT_ALIGNMENT_CENTER,s.width) + label2:setPosition( cc.p(s.width/2, s.height/5) ) + label2:setColor( cc.c3b(255, 0, 0)) + label2:setAnchorPoint(cc.p(0.5, 0.5)) + layer:addChild(label2) + + return layer +end + +-------------------------------------------------------- +----- LabelTTFDistanceFieldEffect +-------------------------------------------------------- +local LabelTTFDistanceFieldEffect = {} +function LabelTTFDistanceFieldEffect.create() + local layer = cc.Layer:create() + Helper.initWithLayer(layer) + Helper.titleLabel:setString("New Label + .TTF") + Helper.subtitleLabel:setString("Testing effect base on DistanceField") + + local s = cc.Director:getInstance():getWinSize() + + local col = cc.LayerColor:create( cc.c4b(200, 191, 231, 255)) + layer:addChild(col) + + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 80 + ttfConfig.glyphs = cc.GLYPHCOLLECTION_DYNAMIC + ttfConfig.customGlyphs = nil + ttfConfig.distanceFieldEnabled = true + + local label1 = cc.Label:createWithTTF(ttfConfig,"Glow",cc.TEXT_ALIGNMENT_CENTER,s.width) + label1:setAnchorPoint(cc.p(0.5,0.5)) + label1:setPosition(cc.p(s.width/2, s.height/2)) + label1:setColor( cc.c3b(0, 255, 0) ) + label1:setLabelEffect(cc.LabelEffect.GLOW, cc.c3b(255, 255, 0)) + layer:addChild(label1) + + local label2 = cc.Label:createWithTTF(ttfConfig,"Outline",cc.TEXT_ALIGNMENT_CENTER,s.width) + label2:setPosition( cc.p(s.width/2, s.height * 0.375)) + label2:setColor( cc.c3b(255, 0, 0)) + label2:setAnchorPoint(cc.p(0.5, 0.5)) + label2:setLabelEffect(cc.LabelEffect.OUTLINE, cc.c3b(0, 0, 255)) + layer:addChild(label2) + + local label3 = cc.Label:createWithTTF(ttfConfig,"Shadow",cc.TEXT_ALIGNMENT_CENTER,s.width) + label3:setPosition( cc.p(s.width/2, s.height * 0.25)) + label3:setColor( cc.c3b(255, 0, 0)) + label3:setAnchorPoint(cc.p(0.5, 0.5)) + label3:setLabelEffect(cc.LabelEffect.SHADOW, cc.c3b(0, 0, 0)) + layer:addChild(label3) + + return layer +end + + +-------------------------------------------------------------------- +-- +-- LabelCharMapTest +-- +-------------------------------------------------------------------- +local LabelCharMapTest = {} + +function LabelCharMapTest.create() + local layer = cc.Layer:create() + Helper.initWithLayer(layer) + Helper.titleLabel:setString("New Label + char map file") + Helper.subtitleLabel:setString("Updating label should be fast.") + + time = 0 + + local label1 = cc.Label:createWithCharMap("fonts/tuffy_bold_italic-charmap.plist") + layer:addChild(label1, 0, kTagSprite1) + label1:setPosition( cc.p(10,100) ) + label1:setOpacity( 200 ) + + local label2 = cc.Label:createWithCharMap("fonts/tuffy_bold_italic-charmap.plist") + layer:addChild(label2, 0, kTagSprite2) + label2:setPosition( cc.p(10,160) ) + label2:setOpacity( 32 ) + + local label3 = cc.Label:createWithCharMap("fonts/tuffy_bold_italic-charmap.png", 48, 64, 32)--32 means Space key + label3:setString("123 Test") + layer:addChild(label3, 0, kTagSprite3) + label3:setPosition(cc.p(10,220)) + + local function step(dt) + time = time + dt + local info = string.format("%2.2f Test", time) + + local label1 = layer:getChildByTag(kTagSprite1) + label1:setString(info) + + local label2 = layer:getChildByTag(kTagSprite2) + info = string.format("%d",time) + label2:setString(info) + end + + layer:scheduleUpdateWithPriorityLua(step, 0) + + function onNodeEvent(tag) + if tag == "exit" then + layer:unscheduleUpdate() + end + end + + layer:registerScriptHandler(onNodeEvent) + + return layer +end + + +-------------------------------------------------------- +----- LabelCrashTest +-------------------------------------------------------- +local LabelCrashTest = {} +function LabelCrashTest.create() + local layer = cc.Layer:create() + Helper.initWithLayer(layer) + Helper.titleLabel:setString("New Label + .TTF") + Helper.subtitleLabel:setString("Testing rendering base on DistanceField") + + local ttfConfig = {} + ttfConfig.fontFilePath = "fonts/arial.ttf" + ttfConfig.fontSize = 80 + ttfConfig.glyphs = cc.GLYPHCOLLECTION_DYNAMIC + ttfConfig.customGlyphs = nil + ttfConfig.distanceFieldEnabled = true + local s = cc.Director:getInstance():getWinSize() + local label1 = cc.Label:createWithTTF(ttfConfig,"Test崩溃123", cc.TEXT_ALIGNMENT_CENTER, s.width) + label1:setPosition( cc.p(s.width/2, s.height/2) ) + label1:setAnchorPoint(cc.p(0.5, 0.5)) + layer:addChild(label1) + + return layer +end + +------------ function LabelTestNew() cclog("LabelTestNew") m_time = 0 @@ -1064,6 +1257,10 @@ function LabelTestNew() LabelTTFDynamicAlignment.create, LabelTTFFontsTestNew.create, LabelBMFontTestNew.create, + LabelTTFDistanceField.create, + LabelTTFDistanceFieldEffect.create, + LabelCharMapTest.create, + LabelCrashTest.create, } scene:addChild(LabelFNTColorAndOpacity.create()) scene:addChild(CreateBackMenuItem()) From 7712ab7406b501af19b8dfb1e96f7c33bb240f91 Mon Sep 17 00:00:00 2001 From: James Chen Date: Tue, 21 Jan 2014 17:56:24 +0800 Subject: [PATCH 193/193] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index e77a4728ac..6c63702bca 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -10,6 +10,7 @@ cocos2d-x-3.0beta2 ?.? ? [NEW] Renderer: Added BatchCommand. This command is not "batchable" with other commands, but improves performance in about 10% [NEW] LuaBindings: Bindings-generator supports to bind namespace for lua. + [FIX] Wrong arithmetic of child's position in ParallaxNode::addChild() [FIX] CocoStudio: TestColliderDetector in ArmatureTest can't work. [FIX] Crash if file doesn't exist when using FileUtils::getStringFromFile. [FIX] If setting a shorter string than before while using LabelAtlas, the effect will be wrong.