diff --git a/.gitignore b/.gitignore index 7682ccb859f2..8ab3121379d2 100644 --- a/.gitignore +++ b/.gitignore @@ -146,3 +146,4 @@ tests/cpp-tests/Resources/audio /*/*/prebuilt-mk/Android.mk /*/*/*/prebuilt-mk/Android.mk /*/*/*/*/prebuilt-mk/Android.mk +*.xcscmblueprint diff --git a/build/cocos2d_tests.xcodeproj/project.pbxproj b/build/cocos2d_tests.xcodeproj/project.pbxproj index 8b250e7b2fdc..0aa43d8f458c 100644 --- a/build/cocos2d_tests.xcodeproj/project.pbxproj +++ b/build/cocos2d_tests.xcodeproj/project.pbxproj @@ -883,6 +883,10 @@ 688669711AE8E8B500C2CFD9 /* SpritePolygonTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6886696F1AE8E8B500C2CFD9 /* SpritePolygonTest.cpp */; }; 688669721AE8E8B500C2CFD9 /* SpritePolygonTest.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 6886696F1AE8E8B500C2CFD9 /* SpritePolygonTest.cpp */; }; 826294431AAF071500CB7CF7 /* Security.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 826294421AAF071500CB7CF7 /* Security.framework */; }; + 94D793D91B4B7A3600F60F10 /* Bug-CCDrawNode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 94D793D51B4B7A3600F60F10 /* Bug-CCDrawNode.cpp */; }; + 94D793DA1B4B7A3600F60F10 /* Bug-CCDrawNode.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 94D793D51B4B7A3600F60F10 /* Bug-CCDrawNode.cpp */; }; + 94D793DB1B4B7A3600F60F10 /* Bug-PageViewLayout.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 94D793D71B4B7A3600F60F10 /* Bug-PageViewLayout.cpp */; }; + 94D793DC1B4B7A3600F60F10 /* Bug-PageViewLayout.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 94D793D71B4B7A3600F60F10 /* Bug-PageViewLayout.cpp */; }; A05FCACA177C124500BE600E /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 15C64822165F391E007D4F18 /* Cocoa.framework */; }; A07A521E1783A1D20073F6A7 /* libz.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 15C6482E165F399D007D4F18 /* libz.dylib */; }; A07A521F1783A1D20073F6A7 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 15C64832165F3AFD007D4F18 /* Foundation.framework */; }; @@ -1945,6 +1949,10 @@ 70A7F72D191D3E4900F0F206 /* shaderTest.psh.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = shaderTest.psh.h; sourceTree = ""; }; 70A7F730191D421B00F0F206 /* ShaderTest.vsh.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ShaderTest.vsh.h; sourceTree = ""; }; 826294421AAF071500CB7CF7 /* Security.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Security.framework; path = System/Library/Frameworks/Security.framework; sourceTree = SDKROOT; }; + 94D793D51B4B7A3600F60F10 /* Bug-CCDrawNode.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "Bug-CCDrawNode.cpp"; sourceTree = ""; }; + 94D793D61B4B7A3600F60F10 /* Bug-CCDrawNode.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "Bug-CCDrawNode.h"; sourceTree = ""; }; + 94D793D71B4B7A3600F60F10 /* Bug-PageViewLayout.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = "Bug-PageViewLayout.cpp"; sourceTree = ""; }; + 94D793D81B4B7A3600F60F10 /* Bug-PageViewLayout.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "Bug-PageViewLayout.h"; sourceTree = ""; }; A035A71117822E9E00987F6C /* libsqlite3.dylib */ = {isa = PBXFileReference; lastKnownFileType = "compiled.mach-o.dylib"; name = libsqlite3.dylib; path = usr/lib/libsqlite3.dylib; sourceTree = SDKROOT; }; A07A52291783A1D20073F6A7 /* cpp-tests iOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "cpp-tests iOS.app"; sourceTree = BUILT_PRODUCTS_DIR; }; A07A52B71783AE6D0073F6A7 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk/System/Library/Frameworks/UIKit.framework; sourceTree = DEVELOPER_DIR; }; @@ -2733,6 +2741,10 @@ 1AC3597618CECF0B00F37B72 /* BugsTest */ = { isa = PBXGroup; children = ( + 94D793D51B4B7A3600F60F10 /* Bug-CCDrawNode.cpp */, + 94D793D61B4B7A3600F60F10 /* Bug-CCDrawNode.h */, + 94D793D71B4B7A3600F60F10 /* Bug-PageViewLayout.cpp */, + 94D793D81B4B7A3600F60F10 /* Bug-PageViewLayout.h */, 1AC3597718CECF0B00F37B72 /* Bug-1159.cpp */, 1AC3597818CECF0B00F37B72 /* Bug-1159.h */, 1AC3597918CECF0B00F37B72 /* Bug-1174.cpp */, @@ -5388,6 +5400,7 @@ 1AC35BEB18CECF0C00F37B72 /* CCControlSliderTest.cpp in Sources */, 1AC35C4D18CECF0C00F37B72 /* SpineTest.cpp in Sources */, 3E92EA821921A1400094CD21 /* Sprite3DTest.cpp in Sources */, + 94D793DB1B4B7A3600F60F10 /* Bug-PageViewLayout.cpp in Sources */, 1AC35C1D18CECF0C00F37B72 /* NewRendererTest.cpp in Sources */, 1AC35B6718CECF0C00F37B72 /* AnimationsTestLayer.cpp in Sources */, 29080DB7191B595E0066F8DF /* UIListViewTest_Editor.cpp in Sources */, @@ -5533,6 +5546,7 @@ 1AC35B2518CECF0C00F37B72 /* ActionsProgressTest.cpp in Sources */, 1AC35B6518CECF0C00F37B72 /* EffectsTest.cpp in Sources */, 1AC35B7118CECF0C00F37B72 /* TestHeaderLayer.cpp in Sources */, + 94D793D91B4B7A3600F60F10 /* Bug-CCDrawNode.cpp in Sources */, 29080D93191B595E0066F8DF /* CustomImageTest.cpp in Sources */, 1AC35B2118CECF0C00F37B72 /* ActionManagerTest.cpp in Sources */, 1AC35C3D18CECF0C00F37B72 /* PhysicsTest.cpp in Sources */, @@ -5673,6 +5687,7 @@ 1AC35B2818CECF0C00F37B72 /* ActionsTest.cpp in Sources */, 1AC35C4A18CECF0C00F37B72 /* ShaderTest.cpp in Sources */, B609E67419C18DAD003D0074 /* BillBoardTest.cpp in Sources */, + 94D793DC1B4B7A3600F60F10 /* Bug-PageViewLayout.cpp in Sources */, C04F935B1941B05400E9FEAB /* TileMapTest2.cpp in Sources */, 1AC35B4418CECF0C00F37B72 /* Bug-624.cpp in Sources */, 1AC35BF818CECF0C00F37B72 /* SocketIOTest.cpp in Sources */, @@ -5781,6 +5796,7 @@ 1AC35BEA18CECF0C00F37B72 /* CCControlSceneManager.cpp in Sources */, 182C5CBB1A95B30500C30D34 /* CocosStudio3DTest.cpp in Sources */, 1AC35B7418CECF0C00F37B72 /* TimelineCallbackTestLayer.cpp in Sources */, + 94D793DA1B4B7A3600F60F10 /* Bug-CCDrawNode.cpp in Sources */, 29080D9E191B595E0066F8DF /* CustomParticleWidgetReader.cpp in Sources */, 1AC35BFC18CECF0C00F37B72 /* NotificationCenterTest.cpp in Sources */, 29FBBBFF196A9ECD00E65826 /* CocostudioParserJsonTest.cpp in Sources */, diff --git a/cocos/2d/CCAction.cpp b/cocos/2d/CCAction.cpp index 24b8a6eaa638..589f3884ebb2 100644 --- a/cocos/2d/CCAction.cpp +++ b/cocos/2d/CCAction.cpp @@ -40,6 +40,7 @@ Action::Action() :_originalTarget(nullptr) ,_target(nullptr) ,_tag(Action::INVALID_TAG) +,_flags(0) { } diff --git a/cocos/2d/CCAction.h b/cocos/2d/CCAction.h index d98f90971dcc..68c9e9e19a95 100644 --- a/cocos/2d/CCAction.h +++ b/cocos/2d/CCAction.h @@ -143,6 +143,16 @@ class CC_DLL Action : public Ref, public Clonable * @param tag Used to identify the action easily. */ inline void setTag(int tag) { _tag = tag; } + /** Returns a flag field that is used to group the actions easily. + * + * @return A tag. + */ + inline unsigned int getFlags() const { return _flags; } + /** Changes the flag field that is used to group the actions easily. + * + * @param tag Used to identify the action easily. + */ + inline void setFlags(unsigned int flags) { _flags = flags; } CC_CONSTRUCTOR_ACCESS: Action(); @@ -159,6 +169,8 @@ class CC_DLL Action : public Ref, public Clonable Node *_target; /** The action tag. An identifier of the action. */ int _tag; + /** The action flag field. To categorize action into certain groups.*/ + unsigned int _flags; private: CC_DISALLOW_COPY_AND_ASSIGN(Action); diff --git a/cocos/2d/CCActionEase.cpp b/cocos/2d/CCActionEase.cpp index 46335fd0aacc..fff07e2c2b88 100644 --- a/cocos/2d/CCActionEase.cpp +++ b/cocos/2d/CCActionEase.cpp @@ -46,7 +46,7 @@ NS_CC_BEGIN bool ActionEase::initWithAction(ActionInterval *action) { - CCASSERT(action != nullptr, ""); + CCASSERT(action != nullptr, "action couldn't be nullptr!"); if (ActionInterval::initWithDuration(action->getDuration())) { diff --git a/cocos/2d/CCActionGrid.cpp b/cocos/2d/CCActionGrid.cpp index 0c42ef8cfbeb..d00e8b50e956 100644 --- a/cocos/2d/CCActionGrid.cpp +++ b/cocos/2d/CCActionGrid.cpp @@ -57,13 +57,13 @@ void GridAction::startWithTarget(Node *target) if (targetGrid && targetGrid->getReuseGrid() > 0) { if (targetGrid->isActive() && targetGrid->getGridSize().width == _gridSize.width - && targetGrid->getGridSize().height == _gridSize.height /*&& dynamic_cast(targetGrid) != nullptr*/) + && targetGrid->getGridSize().height == _gridSize.height) { targetGrid->reuse(); } else { - CCASSERT(0, ""); + CCASSERT(0, "Invalid grid parameters!"); } } else @@ -93,7 +93,7 @@ GridAction* GridAction::reverse() const GridBase* GridAction::getGrid() { // Abstract class needs implementation - CCASSERT(0, ""); + CCASSERT(0, "Subclass should implement this method!"); return nullptr; } diff --git a/cocos/2d/CCActionInterval.cpp b/cocos/2d/CCActionInterval.cpp index b325894baba8..9c9eec5bc8c3 100644 --- a/cocos/2d/CCActionInterval.cpp +++ b/cocos/2d/CCActionInterval.cpp @@ -134,13 +134,13 @@ void ActionInterval::setAmplitudeRate(float amp) { CC_UNUSED_PARAM(amp); // Abstract class needs implementation - CCASSERT(0, ""); + CCASSERT(0, "Subclass should implement this method!"); } float ActionInterval::getAmplitudeRate() { // Abstract class needs implementation - CCASSERT(0, ""); + CCASSERT(0, "Subclass should implement this method!"); return 0; } @@ -248,8 +248,8 @@ Sequence* Sequence::create(const Vector& arrayOfActions) bool Sequence::initWithTwoActions(FiniteTimeAction *actionOne, FiniteTimeAction *actionTwo) { - CCASSERT(actionOne != nullptr, ""); - CCASSERT(actionTwo != nullptr, ""); + CCASSERT(actionOne != nullptr, "actionOne can't be nullptr!"); + CCASSERT(actionTwo != nullptr, "actionTwo can't be nullptr!"); float d = actionOne->getDuration() + actionTwo->getDuration(); ActionInterval::initWithDuration(d); @@ -504,7 +504,7 @@ RepeatForever *RepeatForever::create(ActionInterval *action) bool RepeatForever::initWithAction(ActionInterval *action) { - CCASSERT(action != nullptr, ""); + CCASSERT(action != nullptr, "action can't be nullptr!"); action->retain(); _innerAction = action; return true; @@ -645,8 +645,8 @@ Spawn* Spawn::createWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction * bool Spawn::initWithTwoActions(FiniteTimeAction *action1, FiniteTimeAction *action2) { - CCASSERT(action1 != nullptr, ""); - CCASSERT(action2 != nullptr, ""); + CCASSERT(action1 != nullptr, "action1 can't be nullptr!"); + CCASSERT(action2 != nullptr, "action2 can't be nullptr!"); bool ret = false; @@ -2189,8 +2189,8 @@ ReverseTime* ReverseTime::create(FiniteTimeAction *action) bool ReverseTime::initWithAction(FiniteTimeAction *action) { - CCASSERT(action != nullptr, ""); - CCASSERT(action != _other, ""); + CCASSERT(action != nullptr, "action can't be nullptr!"); + CCASSERT(action != _other, "action doesn't equal to _other!"); if (ActionInterval::initWithDuration(action->getDuration())) { @@ -2270,6 +2270,7 @@ Animate::Animate() , _executedLoops(0) , _animation(nullptr) , _frameDisplayedEvent(nullptr) +, _currFrameIndex(0) { } @@ -2383,7 +2384,8 @@ void Animate::update(float t) float splitTime = _splitTimes->at(i); if( splitTime <= t ) { - AnimationFrame* frame = frames.at(i); + _currFrameIndex = i; + AnimationFrame* frame = frames.at(_currFrameIndex); frameToDisplay = frame->getSpriteFrame(); static_cast(_target)->setSpriteFrame(frameToDisplay); diff --git a/cocos/2d/CCActionInterval.h b/cocos/2d/CCActionInterval.h index cf0b1f492650..b424c6be368d 100644 --- a/cocos/2d/CCActionInterval.h +++ b/cocos/2d/CCActionInterval.h @@ -1439,6 +1439,11 @@ class CC_DLL Animate : public ActionInterval Animation* getAnimation() { return _animation; } const Animation* getAnimation() const { return _animation; } + /** + * Gets the index of sprite frame currently displayed. + * @return int the index of sprite frame currently displayed. + */ + int getCurrentFrameIndex() { return _currFrameIndex; } // // Overrides // @@ -1462,6 +1467,7 @@ class CC_DLL Animate : public ActionInterval std::vector* _splitTimes; int _nextFrame; SpriteFrame* _origFrame; + int _currFrameIndex; unsigned int _executedLoops; Animation* _animation; diff --git a/cocos/2d/CCActionManager.cpp b/cocos/2d/CCActionManager.cpp index 4739541b2441..3fc938cc291c 100644 --- a/cocos/2d/CCActionManager.cpp +++ b/cocos/2d/CCActionManager.cpp @@ -168,8 +168,8 @@ void ActionManager::resumeTargets(const Vector& targetsToResume) void ActionManager::addAction(Action *action, Node *target, bool paused) { - CCASSERT(action != nullptr, ""); - CCASSERT(target != nullptr, ""); + CCASSERT(action != nullptr, "action can't be nullptr!"); + CCASSERT(target != nullptr, "target can't be nullptr!"); tHashElement *element = nullptr; // we should convert it to Ref*, because we save it as Ref* @@ -186,7 +186,7 @@ void ActionManager::addAction(Action *action, Node *target, bool paused) actionAllocWithHashElement(element); - CCASSERT(! ccArrayContainsObject(element->actions, action), ""); + CCASSERT(! ccArrayContainsObject(element->actions, action), "action already be added!"); ccArrayAppendObject(element->actions, action); action->startWithTarget(target); @@ -265,8 +265,8 @@ void ActionManager::removeAction(Action *action) void ActionManager::removeActionByTag(int tag, Node *target) { - CCASSERT(tag != Action::INVALID_TAG, ""); - CCASSERT(target != nullptr, ""); + CCASSERT(tag != Action::INVALID_TAG, "Invalid tag value!"); + CCASSERT(target != nullptr, "target can't be nullptr!"); tHashElement *element = nullptr; HASH_FIND_PTR(_targets, &target, element); @@ -289,8 +289,8 @@ void ActionManager::removeActionByTag(int tag, Node *target) void ActionManager::removeAllActionsByTag(int tag, Node *target) { - CCASSERT(tag != Action::INVALID_TAG, ""); - CCASSERT(target != nullptr, ""); + CCASSERT(tag != Action::INVALID_TAG, "Invalid tag value!"); + CCASSERT(target != nullptr, "target can't be nullptr!"); tHashElement *element = nullptr; HASH_FIND_PTR(_targets, &target, element); @@ -315,13 +315,44 @@ void ActionManager::removeAllActionsByTag(int tag, Node *target) } } +void ActionManager::removeActionsByFlags(unsigned int flags, Node *target) +{ + if (flags == 0) + { + return; + } + CCASSERT(target != nullptr, "target can't be nullptr!"); + + tHashElement *element = nullptr; + HASH_FIND_PTR(_targets, &target, element); + + if (element) + { + auto limit = element->actions->num; + for (int i = 0; i < limit;) + { + Action *action = (Action*)element->actions->arr[i]; + + if ((action->getFlags() & flags) != 0 && action->getOriginalTarget() == target) + { + removeActionAtIndex(i, element); + --limit; + } + else + { + ++i; + } + } + } +} + // get // FIXME: Passing "const O *" instead of "const O&" because HASH_FIND_IT requries the address of a pointer // and, it is not possible to get the address of a reference Action* ActionManager::getActionByTag(int tag, const Node *target) const { - CCASSERT(tag != Action::INVALID_TAG, ""); + CCASSERT(tag != Action::INVALID_TAG, "Invalid tag value!"); tHashElement *element = nullptr; HASH_FIND_PTR(_targets, &target, element); diff --git a/cocos/2d/CCActionManager.h b/cocos/2d/CCActionManager.h index 68d8656f4c2f..404292192c92 100644 --- a/cocos/2d/CCActionManager.h +++ b/cocos/2d/CCActionManager.h @@ -114,6 +114,14 @@ class CC_DLL ActionManager : public Ref */ void removeAllActionsByTag(int tag, Node *target); + /** Removes all actions matching at least one bit in flags and the target. + * + * @param flags The flag field to match the actions' flags based on bitwise AND. + * @param target A certain target. + * @js NA + */ + void removeActionsByFlags(unsigned int flags, Node *target); + /** Gets an action given its tag an a target. * * @param tag The action's tag. diff --git a/cocos/2d/CCCamera.cpp b/cocos/2d/CCCamera.cpp index 880d3ee3d76c..c62171c54cf5 100644 --- a/cocos/2d/CCCamera.cpp +++ b/cocos/2d/CCCamera.cpp @@ -238,7 +238,7 @@ Vec2 Camera::project(const Vec3& src) const Vec4 clipPos; getViewProjectionMatrix().transformVector(Vec4(src.x, src.y, src.z, 1.0f), &clipPos); - CCASSERT(clipPos.w != 0.0f, ""); + CCASSERT(clipPos.w != 0.0f, "clipPos.w can't be 0.0f!"); float ndcX = clipPos.x / clipPos.w; float ndcY = clipPos.y / clipPos.w; @@ -255,7 +255,7 @@ Vec2 Camera::projectGL(const Vec3& src) const Vec4 clipPos; getViewProjectionMatrix().transformVector(Vec4(src.x, src.y, src.z, 1.0f), &clipPos); - CCASSERT(clipPos.w != 0.0f, ""); + CCASSERT(clipPos.w != 0.0f, "clipPos.w can't be 0.0f!"); float ndcX = clipPos.x / clipPos.w; float ndcY = clipPos.y / clipPos.w; diff --git a/cocos/2d/CCDrawNode.cpp b/cocos/2d/CCDrawNode.cpp index e959584dab3d..1fb58dd32318 100644 --- a/cocos/2d/CCDrawNode.cpp +++ b/cocos/2d/CCDrawNode.cpp @@ -374,7 +374,9 @@ void DrawNode::onDrawGLLine(const Mat4 &transform, uint32_t flags) auto glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR); glProgram->use(); glProgram->setUniformsForBuiltins(transform); - + + GL::blendFunc(_blendFunc.src, _blendFunc.dst); + if (_dirtyGLLine) { glBindBuffer(GL_ARRAY_BUFFER, _vboGLLine); @@ -415,7 +417,9 @@ void DrawNode::onDrawGLPoint(const Mat4 &transform, uint32_t flags) auto glProgram = GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_COLOR_TEXASPOINTSIZE); glProgram->use(); glProgram->setUniformsForBuiltins(transform); - + + GL::blendFunc(_blendFunc.src, _blendFunc.dst); + if (_dirtyGLPoint) { glBindBuffer(GL_ARRAY_BUFFER, _vboGLPoint); diff --git a/cocos/2d/CCFontAtlas.cpp b/cocos/2d/CCFontAtlas.cpp index a2d2d2942e9e..b30309037e8b 100644 --- a/cocos/2d/CCFontAtlas.cpp +++ b/cocos/2d/CCFontAtlas.cpp @@ -204,7 +204,7 @@ bool FontAtlas::prepareLetterDefinitions(const std::u16string& utf16String) if (bitmapHeight > _currLineHeight) { - _currLineHeight = bitmapHeight + 1; + _currLineHeight = static_cast(bitmapHeight) + 1; } if (_currentPageOrigX + tempDef.width > CacheTextureWidth) { diff --git a/cocos/2d/CCFontFreeType.cpp b/cocos/2d/CCFontFreeType.cpp index e3d02c919188..dae7b877442a 100644 --- a/cocos/2d/CCFontFreeType.cpp +++ b/cocos/2d/CCFontFreeType.cpp @@ -137,9 +137,28 @@ bool FontFreeType::createFontObject(const std::string &fontName, int fontSize) if (FT_New_Memory_Face(getFTLibrary(), s_cacheFontData[fontName].data.getBytes(), s_cacheFontData[fontName].data.getSize(), 0, &face )) return false; - //we want to use unicode if (FT_Select_Charmap(face, FT_ENCODING_UNICODE)) - return false; + { + int foundIndex = -1; + for (int charmapIndex = 0; charmapIndex < face->num_charmaps; charmapIndex++) + { + if (face->charmaps[charmapIndex]->encoding != FT_ENCODING_NONE) + { + foundIndex = charmapIndex; + break; + } + } + + if (foundIndex == -1) + { + return false; + } + + if (FT_Select_Charmap(face, face->charmaps[foundIndex]->encoding)) + { + return false; + } + } // set the requested font size int dpi = 72; diff --git a/cocos/2d/CCGrid.cpp b/cocos/2d/CCGrid.cpp index 9ccbd06b90a0..5426ad3bd1a7 100644 --- a/cocos/2d/CCGrid.cpp +++ b/cocos/2d/CCGrid.cpp @@ -245,17 +245,17 @@ void GridBase::afterDraw(cocos2d::Node *target) void GridBase::blit(void) { - CCASSERT(0, ""); + CCASSERT(0, "Subclass should implement it."); } void GridBase::reuse(void) { - CCASSERT(0, ""); + CCASSERT(0, "Subclass should implement it!"); } void GridBase::calculateVertexPoints(void) { - CCASSERT(0, ""); + CCASSERT(0, "Subclass should implement it."); } // implementation of Grid3D diff --git a/cocos/2d/CCLabel.cpp b/cocos/2d/CCLabel.cpp index 5104d3417958..287011a9c730 100644 --- a/cocos/2d/CCLabel.cpp +++ b/cocos/2d/CCLabel.cpp @@ -162,7 +162,7 @@ Label* Label::create(const std::string& text, const std::string& font, float fon Label* Label::createWithSystemFont(const std::string& text, const std::string& font, float fontSize, const Size& dimensions /* = Size::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextVAlignment vAlignment /* = TextVAlignment::TOP */) { - auto ret = new (std::nothrow) Label(nullptr,hAlignment,vAlignment); + auto ret = new (std::nothrow) Label(hAlignment,vAlignment); if (ret) { @@ -182,7 +182,7 @@ Label* Label::createWithSystemFont(const std::string& text, const std::string& f Label* Label::createWithTTF(const std::string& text, const std::string& fontFile, float fontSize, const Size& dimensions /* = Size::ZERO */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, TextVAlignment vAlignment /* = TextVAlignment::TOP */) { - auto ret = new (std::nothrow) Label(nullptr,hAlignment,vAlignment); + auto ret = new (std::nothrow) Label(hAlignment,vAlignment); if (ret && FileUtils::getInstance()->isFileExist(fontFile)) { @@ -202,9 +202,9 @@ Label* Label::createWithTTF(const std::string& text, const std::string& fontFile return nullptr; } -Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment alignment /* = TextHAlignment::CENTER */, int maxLineWidth /* = 0 */) +Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment hAlignment /* = TextHAlignment::CENTER */, int maxLineWidth /* = 0 */) { - auto ret = new (std::nothrow) Label(nullptr,alignment); + auto ret = new (std::nothrow) Label(hAlignment); if (ret && FileUtils::getInstance()->isFileExist(ttfConfig.fontFilePath) && ret->setTTFConfig(ttfConfig)) { @@ -219,9 +219,9 @@ Label* Label::createWithTTF(const TTFConfig& ttfConfig, const std::string& text, return nullptr; } -Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& alignment /* = TextHAlignment::LEFT */, int maxLineWidth /* = 0 */, const Vec2& imageOffset /* = Vec2::ZERO */) +Label* Label::createWithBMFont(const std::string& bmfontFilePath, const std::string& text,const TextHAlignment& hAlignment /* = TextHAlignment::LEFT */, int maxLineWidth /* = 0 */, const Vec2& imageOffset /* = Vec2::ZERO */) { - auto ret = new (std::nothrow) Label(nullptr,alignment); + auto ret = new (std::nothrow) Label(hAlignment); if (ret && ret->setBMFontFilePath(bmfontFilePath,imageOffset)) { @@ -326,36 +326,18 @@ bool Label::setCharMap(const std::string& charMapFile, int itemWidth, int itemHe return true; } -Label::Label(FontAtlas *atlas /* = nullptr */, TextHAlignment hAlignment /* = TextHAlignment::LEFT */, - TextVAlignment vAlignment /* = TextVAlignment::TOP */,bool useDistanceField /* = false */,bool useA8Shader /* = false */) -: _isOpacityModifyRGB(false) -, _contentDirty(false) -, _fontAtlas(atlas) -, _textSprite(nullptr) -, _compatibleMode(false) +Label::Label(TextHAlignment hAlignment /* = TextHAlignment::LEFT */, + TextVAlignment vAlignment /* = TextVAlignment::TOP */) +: _textSprite(nullptr) +, _shadowNode(nullptr) +, _fontAtlas(nullptr) , _reusedLetter(nullptr) -, _additionalKerning(0.0f) -, _commonLineHeight(0.0f) -, _lineBreakWithoutSpaces(false) , _horizontalKernings(nullptr) -, _maxLineWidth(0.0f) -, _labelDimensions(Size::ZERO) -, _labelWidth(0.0f) -, _labelHeight(0.0f) -, _hAlignment(hAlignment) -, _vAlignment(vAlignment) -, _currNumLines(-1) -, _fontScale(1.0f) -, _useDistanceField(useDistanceField) -, _useA8Shader(useA8Shader) -, _effectColorF(Color4F::BLACK) -, _uniformEffectColor(0) -, _shadowDirty(false) -, _blendFunc(BlendFunc::ALPHA_PREMULTIPLIED) -, _insideBounds(true) { setAnchorPoint(Vec2::ANCHOR_MIDDLE); reset(); + _hAlignment = hAlignment; + _vAlignment = vAlignment; _purgeTextureListener = EventListenerCustom::create(FontAtlas::CMD_PURGE_FONTATLAS, [this](EventCustom* event){ if (_fontAtlas && _currentLabelType == LabelType::TTF && event->getUserData() == _fontAtlas) @@ -394,27 +376,27 @@ Label::~Label() if (_fontAtlas) { + Node::removeAllChildrenWithCleanup(true); + CC_SAFE_RELEASE_NULL(_reusedLetter); + _batchNodes.clear(); FontAtlasCache::releaseFontAtlas(_fontAtlas); } _eventDispatcher->removeEventListener(_purgeTextureListener); _eventDispatcher->removeEventListener(_resetTextureListener); - CC_SAFE_RELEASE_NULL(_reusedLetter); CC_SAFE_RELEASE_NULL(_textSprite); CC_SAFE_RELEASE_NULL(_shadowNode); } void Label::reset() { - TTFConfig temp; - _fontConfig = temp; - - _systemFontDirty = false; - _systemFont = "Helvetica"; - _systemFontSize = 12; - + CC_SAFE_RELEASE_NULL(_textSprite); + CC_SAFE_RELEASE_NULL(_shadowNode); + Node::removeAllChildrenWithCleanup(true); + CC_SAFE_RELEASE_NULL(_reusedLetter); + _letters.clear(); _batchNodes.clear(); - + _lettersInfo.clear(); if (_fontAtlas) { FontAtlasCache::releaseFontAtlas(_fontAtlas); @@ -423,21 +405,53 @@ void Label::reset() _currentLabelType = LabelType::STRING_TEXTURE; _currLabelEffect = LabelEffect::NORMAL; - _shadowBlurRadius = 0; - - Node::removeAllChildrenWithCleanup(true); - _textSprite = nullptr; - _shadowNode = nullptr; + _contentDirty = false; + _currNumLines = 0; + _limitShowCount = 0; + _currentUTF16String.clear(); + _originalUTF8String.clear(); - CC_SAFE_RELEASE_NULL(_reusedLetter); + TTFConfig temp; + _fontConfig = temp; + _outlineSize = 0.f; + _bmFontPath = ""; + _systemFontDirty = false; + _systemFont = "Helvetica"; + _systemFontSize = 12; + if (_horizontalKernings) + { + delete[] _horizontalKernings; + _horizontalKernings = nullptr; + } + _additionalKerning = 0.f; + _commonLineHeight = 0.f; + _maxLineWidth = 0.f; + _labelDimensions.width = 0.f; + _labelDimensions.height = 0.f; + _labelWidth = 0.f; + _labelHeight = 0.f; + _lineBreakWithoutSpaces = false; + _hAlignment = TextHAlignment::LEFT; + _vAlignment = TextVAlignment::TOP; + + _effectColorF = Color4F::BLACK; _textColor = Color4B::WHITE; _textColorF = Color4F::WHITE; setColor(Color3B::WHITE); + _shadowDirty = false; _shadowEnabled = false; + _shadowBlurRadius = 0.f; + + _correctionScale = 1.f; + _useDistanceField = false; + _useA8Shader = false; _clipEnabled = false; _blendFuncDirty = false; + _blendFunc = BlendFunc::ALPHA_PREMULTIPLIED; + _isOpacityModifyRGB = false; + _insideBounds = true; } void Label::updateShaderProgram() @@ -481,6 +495,7 @@ void Label::setFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled /* = false * if (_fontAtlas) { + _batchNodes.clear(); FontAtlasCache::releaseFontAtlas(_fontAtlas); _fontAtlas = nullptr; } @@ -538,7 +553,7 @@ bool Label::setTTFConfig(const TTFConfig& ttfConfig) updateShaderProgram(); if(ttfConfig.distanceFieldEnabled) { - this->setFontScale(1.0f * ttfConfig.fontSize / DistanceFieldFontSize); + this->setCorrectionScale(1.0f * ttfConfig.fontSize / DistanceFieldFontSize); } } @@ -623,7 +638,7 @@ void Label::setScale(float scale) { if (_useDistanceField) { - scale *= _fontScale; + scale *= _correctionScale; } Node::setScale(scale); } @@ -632,7 +647,7 @@ void Label::setScaleX(float scaleX) { if (_useDistanceField) { - scaleX *= _fontScale; + scaleX *= _correctionScale; } Node::setScaleX(scaleX); } @@ -641,7 +656,7 @@ void Label::setScaleY(float scaleY) { if (_useDistanceField) { - scaleY *= _fontScale; + scaleY *= _correctionScale; } Node::setScaleY(scaleY); } @@ -650,7 +665,7 @@ float Label::getScaleY() const { if (_useDistanceField) { - return _scaleY / _fontScale; + return _scaleY / _correctionScale; } else { @@ -662,7 +677,7 @@ float Label::getScaleX() const { if (_useDistanceField) { - return _scaleX / _fontScale; + return _scaleX / _correctionScale; } else { @@ -781,19 +796,7 @@ void Label::updateQuads() _reusedRect.size.width = letterDef.width; _reusedRect.origin.x = letterDef.U; _reusedRect.origin.y = letterDef.V; - if (_labelHeight > 0.f) - { - if (_lettersInfo[ctr].position.y > _contentSize.height) - { - auto clipTop = _lettersInfo[ctr].position.y - _contentSize.height; - _reusedRect.origin.y += clipTop; - _lettersInfo[ctr].position.y -= clipTop; - } - if (_lettersInfo[ctr].position.y - letterDef.height < 0.f) - { - _reusedRect.size.height = _lettersInfo[ctr].position.y < 0.f ? 0.f : _lettersInfo[ctr].position.y; - } - } + _reusedLetter->setTextureRect(_reusedRect,false,_reusedRect.size); _reusedLetter->setPosition(_lettersInfo[ctr].position); @@ -848,11 +851,10 @@ void Label::enableGlow(const Color4B& glowColor) _contentDirty = true; } _currLabelEffect = LabelEffect::GLOW; - _effectColor = glowColor; - _effectColorF.r = _effectColor.r / 255.0f; - _effectColorF.g = _effectColor.g / 255.0f; - _effectColorF.b = _effectColor.b / 255.0f; - _effectColorF.a = _effectColor.a / 255.0f; + _effectColorF.r = glowColor.r / 255.0f; + _effectColorF.g = glowColor.g / 255.0f; + _effectColorF.b = glowColor.b / 255.0f; + _effectColorF.a = glowColor.a / 255.0f; updateShaderProgram(); } } @@ -876,9 +878,12 @@ void Label::enableOutline(const Color4B& outlineColor,int outlineSize /* = -1 */ setTTFConfig(_fontConfig); } } - else if (_effectColor != outlineColor || _outlineSize != outlineSize) + else if (_effectColorF != outlineColor || _outlineSize != outlineSize) { - _effectColor = outlineColor; + _effectColorF.r = outlineColor.r / 255.f; + _effectColorF.g = outlineColor.g / 255.f; + _effectColorF.b = outlineColor.b / 255.f; + _effectColorF.a = outlineColor.a / 255.f; _outlineSize = outlineSize; _currLabelEffect = LabelEffect::OUTLINE; _contentDirty = true; @@ -895,7 +900,6 @@ void Label::enableShadow(const Color4B& shadowColor /* = Color4B::BLACK */,const _shadowOffset.width = offset.width * contentScaleFactor; _shadowOffset.height = offset.height * contentScaleFactor; //TODO: support blur for shadow - _shadowBlurRadius = 0; _shadowColor3B.r = shadowColor.r; _shadowColor3B.g = shadowColor.g; @@ -904,13 +908,14 @@ void Label::enableShadow(const Color4B& shadowColor /* = Color4B::BLACK */,const if (!_systemFontDirty && !_contentDirty && _textSprite) { + auto fontDef = _getFontDefinition(); if (_shadowNode) { if (shadowColor != _shadowColor4F) { _shadowNode->release(); _shadowNode = nullptr; - createShadowSpriteForSystemFont(); + createShadowSpriteForSystemFont(fontDef); } else { @@ -919,7 +924,7 @@ void Label::enableShadow(const Color4B& shadowColor /* = Color4B::BLACK */,const } else { - createShadowSpriteForSystemFont(); + createShadowSpriteForSystemFont(fontDef); } } @@ -981,59 +986,18 @@ void Label::disableEffect(LabelEffect effect) } } -void Label::setFontScale(float fontScale) +void Label::setCorrectionScale(float correctionScale) { - _fontScale = fontScale * CC_CONTENT_SCALE_FACTOR(); - Node::setScale(_fontScale); + _correctionScale = correctionScale * CC_CONTENT_SCALE_FACTOR(); + Node::setScale(_correctionScale); } -void Label::createSpriteForSystemFont() +void Label::createSpriteForSystemFont(const FontDefinition& fontDef) { _currentLabelType = LabelType::STRING_TEXTURE; - if (!_compatibleMode) - { - _fontDefinition._fontName = _systemFont; - _fontDefinition._fontSize = _systemFontSize; - - _fontDefinition._alignment = _hAlignment; - _fontDefinition._vertAlignment = _vAlignment; - - _fontDefinition._dimensions.width = _labelWidth; - _fontDefinition._dimensions.height = _labelHeight; - - _fontDefinition._fontFillColor.r = _textColor.r; - _fontDefinition._fontFillColor.g = _textColor.g; - _fontDefinition._fontFillColor.b = _textColor.b; - _fontDefinition._fontAlpha = _textColor.a; - - _fontDefinition._shadow._shadowEnabled = false; - - if (_currLabelEffect == LabelEffect::OUTLINE && _outlineSize > 0) - { - _fontDefinition._stroke._strokeEnabled = true; - _fontDefinition._stroke._strokeSize = _outlineSize; - _fontDefinition._stroke._strokeColor.r = _effectColor.r; - _fontDefinition._stroke._strokeColor.g = _effectColor.g; - _fontDefinition._stroke._strokeColor.b = _effectColor.b; - _fontDefinition._stroke._strokeAlpha = _effectColor.a; - } - else - { - _fontDefinition._stroke._strokeEnabled = false; - } - -#if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) - if (_fontDefinition._stroke._strokeEnabled) - { - CCLOGERROR("Currently only supported on iOS and Android!"); - } - _fontDefinition._stroke._strokeEnabled = false; -#endif - } - auto texture = new (std::nothrow) Texture2D; - texture->initWithString(_originalUTF8String.c_str(), _fontDefinition); + texture->initWithString(_originalUTF8String.c_str(), fontDef); _textSprite = Sprite::createWithTexture(texture); //set camera mask using label's camera mask, because _textSprite may be null when setting camera mask to label @@ -1051,16 +1015,16 @@ void Label::createSpriteForSystemFont() _textSprite->updateDisplayedOpacity(_displayedOpacity); } -void Label::createShadowSpriteForSystemFont() +void Label::createShadowSpriteForSystemFont(const FontDefinition& fontDef) { - if (!_fontDefinition._stroke._strokeEnabled && _fontDefinition._fontFillColor == _shadowColor3B - && (_fontDefinition._fontAlpha == _shadowOpacity)) + if (!fontDef._stroke._strokeEnabled && fontDef._fontFillColor == _shadowColor3B + && (fontDef._fontAlpha == _shadowOpacity)) { _shadowNode = Sprite::createWithTexture(_textSprite->getTexture()); } else { - auto shadowFontDefinition = _fontDefinition; + FontDefinition shadowFontDefinition = fontDef; shadowFontDefinition._fontFillColor.r = _shadowColor3B.r; shadowFontDefinition._fontFillColor.g = _shadowColor3B.g; shadowFontDefinition._fontFillColor.b = _shadowColor3B.b; @@ -1107,20 +1071,35 @@ void Label::setCameraMask(unsigned short mask, bool applyChildren) void Label::setFontDefinition(const FontDefinition& textDefinition) { - _fontDefinition = textDefinition; + _systemFont = textDefinition._fontName; + _systemFontSize = textDefinition._fontSize; + _hAlignment = textDefinition._alignment; + _vAlignment = textDefinition._vertAlignment; + setDimensions(textDefinition._dimensions.width, textDefinition._dimensions.height); + Color4B textColor = Color4B(textDefinition._fontFillColor); + textColor.a = textDefinition._fontAlpha; + setTextColor(textColor); + #if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) - if (_fontDefinition._stroke._strokeEnabled) + if (textDefinition._stroke._strokeEnabled) { CCLOGERROR("Currently only supported on iOS and Android!"); } - _fontDefinition._stroke._strokeEnabled = false; + _outlineSize = 0.f; +#else + if (textDefinition._stroke._strokeEnabled && textDefinition._stroke._strokeSize > 0.f) + { + Color4B outlineColor = Color4B(textDefinition._stroke._strokeColor); + outlineColor.a = textDefinition._stroke._strokeAlpha; + enableOutline(outlineColor, textDefinition._stroke._strokeSize); + } #endif - if (_fontDefinition._shadow._shadowEnabled) + + if (textDefinition._shadow._shadowEnabled) { - _fontDefinition._shadow._shadowEnabled = false; - enableShadow(Color4B(0,0,0,255 * _fontDefinition._shadow._shadowOpacity),_fontDefinition._shadow._shadowOffset,_fontDefinition._shadow._shadowBlur); + enableShadow(Color4B(0, 0, 0, 255 * textDefinition._shadow._shadowOpacity), + textDefinition._shadow._shadowOffset, textDefinition._shadow._shadowBlur); } - _compatibleMode = true; } void Label::updateContent() @@ -1155,10 +1134,11 @@ void Label::updateContent() } else { - createSpriteForSystemFont(); + auto fontDef = _getFontDefinition(); + createSpriteForSystemFont(fontDef); if (_shadowEnabled) { - createShadowSpriteForSystemFont(); + createShadowSpriteForSystemFont(fontDef); } } _contentDirty = false; @@ -1296,8 +1276,7 @@ void Label::visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t pare uint32_t flags = processParentFlags(parentTransform, parentFlags); - if (!_originalUTF8String.empty() && _shadowEnabled && _shadowBlurRadius <= 0 - && (_shadowDirty || (flags & FLAGS_DIRTY_MASK))) + if (!_originalUTF8String.empty() && _shadowEnabled && (_shadowDirty || (flags & FLAGS_DIRTY_MASK))) { _position.x += _shadowOffset.width; _position.y += _shadowOffset.height; @@ -1525,11 +1504,6 @@ int Label::getStringLength() const } // RGBA protocol -bool Label::isOpacityModifyRGB() const -{ - return _isOpacityModifyRGB; -} - void Label::setOpacityModifyRGB(bool isOpacityModifyRGB) { if (isOpacityModifyRGB != _isOpacityModifyRGB) @@ -1571,20 +1545,16 @@ void Label::setTextColor(const Color4B &color) { CCASSERT(_currentLabelType == LabelType::TTF || _currentLabelType == LabelType::STRING_TEXTURE, "Only supported system font and ttf!"); + if (_currentLabelType == LabelType::STRING_TEXTURE && _textColor != color) + { + _contentDirty = true; + } + _textColor = color; _textColorF.r = _textColor.r / 255.0f; _textColorF.g = _textColor.g / 255.0f; _textColorF.b = _textColor.b / 255.0f; _textColorF.a = _textColor.a / 255.0f; - - if (_currentLabelType == LabelType::STRING_TEXTURE) - { - if (_fontDefinition._fontFillColor.r != _textColor.r || _fontDefinition._fontFillColor.g != _textColor.g - || _fontDefinition._fontFillColor.b != _textColor.b || _fontDefinition._fontAlpha != _textColor.a) - { - _contentDirty = true; - } - } } void Label::updateColor() @@ -1679,4 +1649,44 @@ void Label::removeChild(Node* child, bool cleanup /* = true */) } } +FontDefinition Label::_getFontDefinition() const +{ + FontDefinition systemFontDef; + systemFontDef._fontName = _systemFont; + systemFontDef._fontSize = _systemFontSize; + systemFontDef._alignment = _hAlignment; + systemFontDef._vertAlignment = _vAlignment; + systemFontDef._dimensions.width = _labelWidth; + systemFontDef._dimensions.height = _labelHeight; + systemFontDef._fontFillColor.r = _textColor.r; + systemFontDef._fontFillColor.g = _textColor.g; + systemFontDef._fontFillColor.b = _textColor.b; + systemFontDef._fontAlpha = _textColor.a; + systemFontDef._shadow._shadowEnabled = false; + + if (_currLabelEffect == LabelEffect::OUTLINE && _outlineSize > 0.f) + { + systemFontDef._stroke._strokeEnabled = true; + systemFontDef._stroke._strokeSize = _outlineSize; + systemFontDef._stroke._strokeColor.r = _effectColorF.r * 255; + systemFontDef._stroke._strokeColor.g = _effectColorF.g * 255; + systemFontDef._stroke._strokeColor.b = _effectColorF.b * 255; + systemFontDef._stroke._strokeAlpha = _effectColorF.a * 255; + } + else + { + systemFontDef._stroke._strokeEnabled = false; + } + +#if (CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID) && (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) + if (systemFontDef._stroke._strokeEnabled) + { + CCLOGERROR("Currently only supported on iOS and Android!"); + } + systemFontDef._stroke._strokeEnabled = false; +#endif + + return systemFontDef; +} + NS_CC_END diff --git a/cocos/2d/CCLabel.h b/cocos/2d/CCLabel.h index db9f19fafa9b..f7389f55aba7 100644 --- a/cocos/2d/CCLabel.h +++ b/cocos/2d/CCLabel.h @@ -162,7 +162,8 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol * @return An automatically released Label object. * @see TTFConfig setTTFConfig setMaxLineWidth */ - static Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text, TextHAlignment hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0); + static Label* createWithTTF(const TTFConfig& ttfConfig, const std::string& text, + TextHAlignment hAlignment = TextHAlignment::LEFT, int maxLineWidth = 0); /** * Allocates and initializes a Label, with a bitmap font file. @@ -441,7 +442,7 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol virtual const BlendFunc& getBlendFunc() const override { return _blendFunc; } virtual void setBlendFunc(const BlendFunc &blendFunc) override; - virtual bool isOpacityModifyRGB() const override; + virtual bool isOpacityModifyRGB() const override { return _isOpacityModifyRGB; } virtual void setOpacityModifyRGB(bool isOpacityModifyRGB) override; virtual void updateDisplayedColor(const Color3B& parentColor) override; virtual void updateDisplayedOpacity(GLubyte parentOpacity) override; @@ -455,7 +456,6 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol virtual std::string getDescription() const override; virtual const Size& getContentSize() const override; - virtual Rect getBoundingBox() const override; virtual void visit(Renderer *renderer, const Mat4 &parentTransform, uint32_t parentFlags) override; @@ -469,13 +469,8 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol CC_DEPRECATED_ATTRIBUTE static Label* create(const std::string& text, const std::string& font, float fontSize, const Size& dimensions = Size::ZERO, TextHAlignment hAlignment = TextHAlignment::LEFT, TextVAlignment vAlignment = TextVAlignment::TOP); - CC_DEPRECATED_ATTRIBUTE virtual void setFontDefinition(const FontDefinition& textDefinition); - CC_DEPRECATED_ATTRIBUTE const FontDefinition& getFontDefinition() const { return _fontDefinition; } - - /** - * @deprecated Use `getLineHeight` instead. - */ + CC_DEPRECATED_ATTRIBUTE FontDefinition getFontDefinition() const { return _getFontDefinition(); } CC_DEPRECATED_ATTRIBUTE int getCommonLineHeight() const { return (int)getLineHeight();} CC_CONSTRUCTOR_ACCESS: @@ -483,8 +478,8 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol * Constructor of Label. * @js NA */ - Label(FontAtlas *atlas = nullptr, TextHAlignment hAlignment = TextHAlignment::LEFT, - TextVAlignment vAlignment = TextVAlignment::TOP,bool useDistanceField = false,bool useA8Shader = false); + Label(TextHAlignment hAlignment = TextHAlignment::LEFT, + TextVAlignment vAlignment = TextVAlignment::TOP); /** * Destructor of Label. @@ -494,132 +489,124 @@ class CC_DLL Label : public Node, public LabelProtocol, public BlendProtocol virtual ~Label(); protected: - void onDraw(const Mat4& transform, bool transformUpdated); - void onDrawShadow(GLProgram* glProgram); - struct LetterInfo { FontLetterDefinition def; - Vec2 position; Size contentSize; int atlasIndex; }; - enum class LabelType { + enum class LabelType { TTF, BMFONT, CHARMAP, STRING_TEXTURE }; - virtual void setFontAtlas(FontAtlas* atlas,bool distanceFieldEnabled = false, bool useA8Shader = false); + virtual void setFontAtlas(FontAtlas* atlas, bool distanceFieldEnabled = false, bool useA8Shader = false); - bool recordLetterInfo(const cocos2d::Vec2& point,const FontLetterDefinition& letterDef, int spriteIndex); - bool recordPlaceholderInfo(int spriteIndex); + void setCorrectionScale(float fontScale); - void setFontScale(float fontScale); + void computeStringNumLines(); - virtual void alignText(); + void onDraw(const Mat4& transform, bool transformUpdated); + void onDrawShadow(GLProgram* glProgram); + void drawSelf(Renderer* renderer, uint32_t flags); + virtual void alignText(); bool computeHorizontalKernings(const std::u16string& stringToRender); - - void computeStringNumLines(); - + bool recordLetterInfo(const cocos2d::Vec2& point,const FontLetterDefinition& letterDef, int spriteIndex); + bool recordPlaceholderInfo(int spriteIndex); + void updateQuads(); - virtual void updateColor() override; + void createSpriteForSystemFont(const FontDefinition& fontDef); + void createShadowSpriteForSystemFont(const FontDefinition& fontDef); virtual void updateShaderProgram(); - void createSpriteForSystemFont(); - - void createShadowSpriteForSystemFont(); - void reset(); - void drawSelf(Renderer* renderer, uint32_t flags); + FontDefinition _getFontDefinition() const; - std::string _bmFontPath; + virtual void updateColor() override; - bool _isOpacityModifyRGB; + LabelType _currentLabelType; bool _contentDirty; + std::u16string _currentUTF16String; + std::string _originalUTF8String; + int _currNumLines; + + std::string _bmFontPath; + TTFConfig _fontConfig; + float _outlineSize; bool _systemFontDirty; std::string _systemFont; - float _systemFontSize; - LabelType _currentLabelType; + float _systemFontSize; + Sprite* _textSprite; + Sprite* _shadowNode; + FontAtlas* _fontAtlas; Vector _batchNodes; - FontAtlas * _fontAtlas; - std::vector _lettersInfo; - EventListenerCustom* _purgeTextureListener; - EventListenerCustom* _resetTextureListener; - - TTFConfig _fontConfig; - - //compatibility with older LabelTTF - Sprite* _textSprite; - FontDefinition _fontDefinition; - bool _compatibleMode; + std::vector _lettersInfo; //! used for optimization Sprite *_reusedLetter; Rect _reusedRect; int _limitShowCount; - float _additionalKerning; + //layout relevant properties. float _commonLineHeight; - bool _lineBreakWithoutSpaces; - int * _horizontalKernings; - + float _additionalKerning; + int* _horizontalKernings; + bool _lineBreakWithoutSpaces; float _maxLineWidth; - Size _labelDimensions; + Size _labelDimensions; float _labelWidth; float _labelHeight; TextHAlignment _hAlignment; TextVAlignment _vAlignment; - int _currNumLines; - std::u16string _currentUTF16String; - std::string _originalUTF8String; - - float _fontScale; - - bool _useDistanceField; - bool _useA8Shader; + //the correction scale for distance field. + float _correctionScale; LabelEffect _currLabelEffect; - Color4B _effectColor; Color4F _effectColorF; + Color4B _textColor; + Color4F _textColorF; + CustomCommand _customCommand; + Mat4 _shadowTransform; GLuint _uniformEffectColor; GLuint _uniformTextColor; - CustomCommand _customCommand; + bool _useDistanceField; + bool _useA8Shader; - bool _shadowDirty; - bool _shadowEnabled; - Size _shadowOffset; - int _shadowBlurRadius; - Mat4 _shadowTransform; + bool _shadowDirty; + bool _shadowEnabled; + Size _shadowOffset; + Color4F _shadowColor4F; Color3B _shadowColor3B; GLubyte _shadowOpacity; - Sprite* _shadowNode; - - int _outlineSize; - - Color4B _textColor; - Color4F _textColorF; + float _shadowBlurRadius; bool _clipEnabled; bool _blendFuncDirty; BlendFunc _blendFunc; - /// whether or not the sprite was inside bounds the previous frame + + /// whether or not the label was inside bounds the previous frame bool _insideBounds; + bool _isOpacityModifyRGB; + std::unordered_map _letters; + EventListenerCustom* _purgeTextureListener; + EventListenerCustom* _resetTextureListener; + private: CC_DISALLOW_COPY_AND_ASSIGN(Label); diff --git a/cocos/2d/CCLabelTTF.cpp b/cocos/2d/CCLabelTTF.cpp index 205cce2c3e02..c19c037fc548 100644 --- a/cocos/2d/CCLabelTTF.cpp +++ b/cocos/2d/CCLabelTTF.cpp @@ -223,9 +223,11 @@ void LabelTTF::setTextDefinition(const FontDefinition& theDefinition) _contentDirty = true; } -const FontDefinition& LabelTTF::getTextDefinition() const +const FontDefinition& LabelTTF::getTextDefinition() { - return _renderLabel->getFontDefinition(); + auto fontDef = _renderLabel->getFontDefinition(); + memcpy(&_fontDef, &fontDef, sizeof(FontDefinition)); + return _fontDef; } void LabelTTF::setBlendFunc(const BlendFunc &blendFunc) diff --git a/cocos/2d/CCLabelTTF.h b/cocos/2d/CCLabelTTF.h index c4313a961f69..cae01b65c118 100644 --- a/cocos/2d/CCLabelTTF.h +++ b/cocos/2d/CCLabelTTF.h @@ -100,7 +100,7 @@ class CC_DLL CC_DEPRECATED_ATTRIBUTE LabelTTF : public Node, public LabelProtoco void setTextDefinition(const FontDefinition& theDefinition); /** get the text definition used by this label */ - const FontDefinition& getTextDefinition() const; + const FontDefinition& getTextDefinition(); @@ -163,6 +163,7 @@ class CC_DLL CC_DEPRECATED_ATTRIBUTE LabelTTF : public Node, public LabelProtoco protected: Label* _renderLabel; bool _contentDirty; + FontDefinition _fontDef; }; diff --git a/cocos/2d/CCLabelTextFormatter.cpp b/cocos/2d/CCLabelTextFormatter.cpp index 638897965e44..a99a76bb7c8d 100644 --- a/cocos/2d/CCLabelTextFormatter.cpp +++ b/cocos/2d/CCLabelTextFormatter.cpp @@ -316,7 +316,7 @@ bool LabelTextFormatter::createStringSprites(Label *theLabel) auto labelHeightPixel = theLabel->_labelHeight * contentScaleFactor; if (totalHeight > labelHeightPixel) { - int numLines = MIN(ceil(labelHeightPixel / theLabel->_commonLineHeight), theLabel->_currNumLines); + int numLines = labelHeightPixel / theLabel->_commonLineHeight; totalHeight = numLines * theLabel->_commonLineHeight; } switch (theLabel->_vAlignment) @@ -379,7 +379,7 @@ bool LabelTextFormatter::createStringSprites(Label *theLabel) nextFontPositionY -= theLabel->_commonLineHeight; theLabel->recordPlaceholderInfo(i); - if(nextFontPositionY < 0.f) + if (nextFontPositionY < theLabel->_commonLineHeight) break; lineStart = true; diff --git a/cocos/2d/CCMenu.cpp b/cocos/2d/CCMenu.cpp index 2b8ceea7d555..2a17e75578e9 100644 --- a/cocos/2d/CCMenu.cpp +++ b/cocos/2d/CCMenu.cpp @@ -376,11 +376,11 @@ void Menu::alignItemsInColumnsWithArray(const ValueVector& rows) int rowColumns = 0; for(const auto &child : _children) { - CCASSERT(row < rows.size(), ""); + CCASSERT(row < rows.size(), "row should less than rows.size()!"); rowColumns = rows[row].asInt(); // can not have zero columns on a row - CCASSERT(rowColumns, ""); + CCASSERT(rowColumns, "rowColumns can't be 0."); float tmp = child->getContentSize().height; rowHeight = (unsigned int)((rowHeight >= tmp || isnan(tmp)) ? rowHeight : tmp); @@ -397,7 +397,7 @@ void Menu::alignItemsInColumnsWithArray(const ValueVector& rows) } // check if too many rows/columns for available menu items - CCASSERT(! columnsOccupied, ""); + CCASSERT(! columnsOccupied, "columnsOccupied should be 0."); Size winSize = Director::getInstance()->getWinSize(); @@ -472,11 +472,11 @@ void Menu::alignItemsInRowsWithArray(const ValueVector& columns) for(const auto &child : _children) { // check if too many menu items for the amount of rows/columns - CCASSERT(column < columns.size(), ""); + CCASSERT(column < columns.size(), "column should be less than columns.size()."); columnRows = columns[column].asInt(); // can't have zero rows on a column - CCASSERT(columnRows, ""); + CCASSERT(columnRows, "columnRows can't be 0."); // columnWidth = fmaxf(columnWidth, [item contentSize].width); float tmp = child->getContentSize().width; @@ -499,7 +499,7 @@ void Menu::alignItemsInRowsWithArray(const ValueVector& columns) } // check if too many rows/columns for available menu items. - CCASSERT(! rowsOccupied, ""); + CCASSERT(! rowsOccupied, "rowsOccupied should be 0."); Size winSize = Director::getInstance()->getWinSize(); diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 946b40bf2817..17dd5b9de4a4 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -1576,6 +1576,14 @@ void Node::stopAllActionsByTag(int tag) _actionManager->removeAllActionsByTag(tag, this); } +void Node::stopActionsByFlags(unsigned int flags) +{ + if (flags > 0) + { + _actionManager->removeActionsByFlags(flags, this); + } +} + Action * Node::getActionByTag(int tag) { CCASSERT( tag != Action::INVALID_TAG, "Invalid tag"); diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 77ab67766fc4..8d0674f1493c 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -1228,6 +1228,13 @@ class CC_DLL Node : public Ref */ void stopAllActionsByTag(int tag); + /** + * Removes all actions from the running action list by its flags. + * + * @param flags A flag field that removes actions based on bitwise AND. + */ + void stopActionsByFlags(unsigned int flags); + /** * Gets an action from the running action list by its tag. * diff --git a/cocos/2d/CCParticleSystem.cpp b/cocos/2d/CCParticleSystem.cpp index 170c8231a0a1..92d485d1e32c 100644 --- a/cocos/2d/CCParticleSystem.cpp +++ b/cocos/2d/CCParticleSystem.cpp @@ -384,7 +384,7 @@ bool ParticleSystem::initWithDictionary(ValueMap& dictionary, const std::string& else if( dictionary.find("textureImageData") != dictionary.end() ) { std::string textureData = dictionary.at("textureImageData").asString(); - CCASSERT(!textureData.empty(), ""); + CCASSERT(!textureData.empty(), "textureData can't be empty!"); auto dataLen = textureData.size(); if (dataLen != 0) diff --git a/cocos/2d/CCSprite.cpp b/cocos/2d/CCSprite.cpp index faa5b61e79da..7f02f088d0ae 100644 --- a/cocos/2d/CCSprite.cpp +++ b/cocos/2d/CCSprite.cpp @@ -205,7 +205,7 @@ bool Sprite::initWithSpriteFrameName(const std::string& spriteFrameName) bool Sprite::initWithSpriteFrame(SpriteFrame *spriteFrame) { - CCASSERT(spriteFrame != nullptr, ""); + CCASSERT(spriteFrame != nullptr, "spriteFrame can't be nullptr!"); bool bRet = initWithTexture(spriteFrame->getTexture(), spriteFrame->getRect()); setSpriteFrame(spriteFrame); @@ -673,7 +673,7 @@ void Sprite::addChild(Node *child, int zOrder, int tag) { Sprite* childSprite = dynamic_cast(child); CCASSERT( childSprite, "CCSprite only supports Sprites as children when using SpriteBatchNode"); - CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(), ""); + CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(), "childSprite's texture name should be equal to _textureAtlas's texture name!"); //put it in descendants array of batch node _batchNode->appendChild(childSprite); @@ -694,7 +694,8 @@ void Sprite::addChild(Node *child, int zOrder, const std::string &name) { Sprite* childSprite = dynamic_cast(child); CCASSERT( childSprite, "CCSprite only supports Sprites as children when using SpriteBatchNode"); - CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(), ""); + CCASSERT(childSprite->getTexture()->getName() == _textureAtlas->getTexture()->getName(), + "childSprite's texture name should be equal to _textureAtlas's texture name."); //put it in descendants array of batch node _batchNode->appendChild(childSprite); diff --git a/cocos/2d/CCTMXXMLParser.cpp b/cocos/2d/CCTMXXMLParser.cpp index 1d163af57b3d..a6b318f74119 100644 --- a/cocos/2d/CCTMXXMLParser.cpp +++ b/cocos/2d/CCTMXXMLParser.cpp @@ -454,7 +454,7 @@ void TMXMapInfo::startElement(void *ctx, const char *name, const char **atts) // Y int y = attributeDict["y"].asInt(); - Vec2 p(x + objectGroup->getPositionOffset().x, _mapSize.height * _tileSize.height - y - objectGroup->getPositionOffset().x - attributeDict["height"].asInt()); + Vec2 p(x + objectGroup->getPositionOffset().x, _mapSize.height * _tileSize.height - y - objectGroup->getPositionOffset().y - attributeDict["height"].asInt()); p = CC_POINT_PIXELS_TO_POINTS(p); dict["x"] = Value(p.x); dict["y"] = Value(p.y); @@ -643,7 +643,7 @@ void TMXMapInfo::endElement(void *ctx, const char *name) ssize_t sizeHint = s.width * s.height * sizeof(unsigned int); ssize_t CC_UNUSED inflatedLen = ZipUtils::inflateMemoryWithHint(buffer, len, &deflated, sizeHint); - CCASSERT(inflatedLen == sizeHint, ""); + CCASSERT(inflatedLen == sizeHint, "inflatedLen should be equal to sizeHint!"); free(buffer); buffer = nullptr; diff --git a/cocos/3d/CCBundle3D.cpp b/cocos/3d/CCBundle3D.cpp index b683e93e844e..f8dbc9ff76eb 100644 --- a/cocos/3d/CCBundle3D.cpp +++ b/cocos/3d/CCBundle3D.cpp @@ -216,73 +216,24 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas, MaterialDatas& materialdatas, NodeD else mtlPath = fullPath.substr(0, fullPath.find_last_of("\\/") + 1).c_str(); - ObjLoader::shapes_t shapes; - auto ret = ObjLoader::LoadObj(shapes, fullPath.c_str(), mtlPath.c_str()); + std::vector shapes; + std::vector materials; + auto ret = tinyobj::LoadObj(shapes, materials, fullPath.c_str(), mtlPath.c_str()); if (ret.empty()) { //fill data - MeshData* meshdata = new (std::nothrow) MeshData(); - MeshVertexAttrib attrib; - attrib.size = 3; - attrib.type = GL_FLOAT; - if (shapes.positions.size()) - { - attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_POSITION; - attrib.attribSizeBytes = attrib.size * sizeof(float); - meshdata->attribs.push_back(attrib); - - } - bool hasnormal = false, hastex = false; - if (shapes.normals.size()) - { - hasnormal = true; - attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_NORMAL; - attrib.attribSizeBytes = attrib.size * sizeof(float);; - meshdata->attribs.push_back(attrib); - } - if (shapes.texcoords.size()) - { - hastex = true; - attrib.size = 2; - attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_TEX_COORD; - attrib.attribSizeBytes = attrib.size * sizeof(float); - meshdata->attribs.push_back(attrib); - } - auto vertexNum = shapes.positions.size() / 3; - for(unsigned int i = 0; i < vertexNum; i++) - { - meshdata->vertex.push_back(shapes.positions[i * 3]); - meshdata->vertex.push_back(shapes.positions[i * 3 + 1]); - meshdata->vertex.push_back(shapes.positions[i * 3 + 2]); - - if (hasnormal) - { - meshdata->vertex.push_back(shapes.normals[i * 3]); - meshdata->vertex.push_back(shapes.normals[i * 3 + 1]); - meshdata->vertex.push_back(shapes.normals[i * 3 + 2]); - } - - if (hastex) - { - meshdata->vertex.push_back(shapes.texcoords[i * 2]); - meshdata->vertex.push_back(shapes.texcoords[i * 2 + 1]); - } - } - meshdatas.meshDatas.push_back(meshdata); - + //convert material int i = 0; char str[20]; std::string dir = ""; auto last = fullPath.rfind("/"); if (last != -1) dir = fullPath.substr(0, last + 1); - - for (const auto& it : shapes.shapes) - { + for (auto& material : materials) { NMaterialData materialdata; NTextureData tex; - tex.filename = it.material.diffuse_texname.empty() ? it.material.diffuse_texname : dir + it.material.diffuse_texname; + tex.filename = material.diffuse_texname.empty() ? material.diffuse_texname : dir + material.diffuse_texname; tex.type = NTextureData::Usage::Diffuse; tex.wrapS = GL_CLAMP_TO_EDGE; tex.wrapT = GL_CLAMP_TO_EDGE; @@ -290,19 +241,91 @@ bool Bundle3D::loadObj(MeshDatas& meshdatas, MaterialDatas& materialdatas, NodeD sprintf(str, "%d", i++); materialdata.textures.push_back(tex); materialdata.id = str; + material.name = str; materialdatas.materials.push_back(materialdata); - - meshdata->subMeshIndices.push_back(it.mesh.indices); - meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), it.mesh.indices)); - meshdata->subMeshIds.push_back(str); + } + + //convert mesh + i = 0; + for (auto& shape : shapes) { + auto mesh = shape.mesh; + MeshData* meshdata = new (std::nothrow) MeshData(); + MeshVertexAttrib attrib; + attrib.size = 3; + attrib.type = GL_FLOAT; + + if (mesh.positions.size()) + { + attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_POSITION; + attrib.attribSizeBytes = attrib.size * sizeof(float); + meshdata->attribs.push_back(attrib); + + } + bool hasnormal = false, hastex = false; + if (mesh.normals.size()) + { + hasnormal = true; + attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_NORMAL; + attrib.attribSizeBytes = attrib.size * sizeof(float);; + meshdata->attribs.push_back(attrib); + } + if (mesh.texcoords.size()) + { + hastex = true; + attrib.size = 2; + attrib.vertexAttrib = GLProgram::VERTEX_ATTRIB_TEX_COORD; + attrib.attribSizeBytes = attrib.size * sizeof(float); + meshdata->attribs.push_back(attrib); + } + + auto vertexNum = mesh.positions.size() / 3; + for(unsigned int k = 0; k < vertexNum; k++) + { + meshdata->vertex.push_back(mesh.positions[k * 3]); + meshdata->vertex.push_back(mesh.positions[k * 3 + 1]); + meshdata->vertex.push_back(mesh.positions[k * 3 + 2]); + + if (hasnormal) + { + meshdata->vertex.push_back(mesh.normals[k * 3]); + meshdata->vertex.push_back(mesh.normals[k * 3 + 1]); + meshdata->vertex.push_back(mesh.normals[k * 3 + 2]); + } + + if (hastex) + { + meshdata->vertex.push_back(mesh.texcoords[k * 2]); + meshdata->vertex.push_back(mesh.texcoords[k * 2 + 1]); + } + } + + //split into submesh according to material + std::map > subMeshMap; + for (size_t k = 0; k < mesh.material_ids.size(); k++) { + int id = mesh.material_ids[k]; + size_t idx = k * 3; + subMeshMap[id].push_back(mesh.indices[idx]); + subMeshMap[id].push_back(mesh.indices[idx + 1]); + subMeshMap[id].push_back(mesh.indices[idx + 2]); + } + auto node = new (std::nothrow) NodeData(); - auto modelnode = new (std::nothrow) ModelData(); - modelnode->matrialId = str; - modelnode->subMeshId = str; - node->id = it.name; - node->modelNodeDatas.push_back(modelnode); + node->id = shape.name; + for (auto& submesh : subMeshMap) { + meshdata->subMeshIndices.push_back(submesh.second); + meshdata->subMeshAABB.push_back(calculateAABB(meshdata->vertex, meshdata->getPerVertexSize(), submesh.second)); + sprintf(str, "%d", i++); + meshdata->subMeshIds.push_back(str); + + auto modelnode = new (std::nothrow) ModelData(); + modelnode->matrialId = submesh.first == -1 ? "" : materials[submesh.first].name; + modelnode->subMeshId = str; + node->modelNodeDatas.push_back(modelnode); + } nodedatas.nodes.push_back(node); + meshdatas.meshDatas.push_back(meshdata); } + return true; } CCLOG("warning: load %s file error: %s", fullPath.c_str(), ret.c_str()); diff --git a/cocos/3d/CCMesh.cpp b/cocos/3d/CCMesh.cpp index 8fc83e59f3b0..8239f9085f46 100644 --- a/cocos/3d/CCMesh.cpp +++ b/cocos/3d/CCMesh.cpp @@ -273,6 +273,9 @@ void Mesh::setTexture(Texture2D* tex) // Texture must be saved for future use // it doesn't matter if the material is already set or not // This functionality is added for compatibility issues + if (tex == nullptr) + tex = getDummyTexture(); + if (tex != _texture) { CC_SAFE_RETAIN(tex); diff --git a/cocos/3d/CCObjLoader.cpp b/cocos/3d/CCObjLoader.cpp index f4e8bb2ae1b2..02ed032caddf 100644 --- a/cocos/3d/CCObjLoader.cpp +++ b/cocos/3d/CCObjLoader.cpp @@ -1,725 +1,900 @@ // -// Copyright 2012-2013, Syoyo Fujita. +// Copyright 2012-2015, Syoyo Fujita. // // Licensed under 2-clause BSD liecense. // // -// version 0.9.6: Support Ni(index of refraction) mtl parameter. -// Parse transmittance material parameter correctly. -// version 0.9.5: Parse multiple group name. -// Add support of specifying the base path to load material file. -// version 0.9.4: Initial suupport of group tag(g) -// version 0.9.3: Fix parsing triple 'x/y/z' -// version 0.9.2: Add more .mtl load support -// version 0.9.1: Add initial .mtl load support -// version 0.9.0: Initial +// version 0.9.13: Report "Material file not found message" in `err`(#46) +// version 0.9.12: Fix groups being ignored if they have 'usemtl' just before 'g' (#44) +// version 0.9.11: Invert `Tr` parameter(#43) +// version 0.9.10: Fix seg fault on windows. +// version 0.9.9 : Replace atof() with custom parser. +// version 0.9.8 : Fix multi-materials(per-face material ID). +// version 0.9.7 : Support multi-materials(per-face material ID) per +// object/group. +// version 0.9.6 : Support Ni(index of refraction) mtl parameter. +// Parse transmittance material parameter correctly. +// version 0.9.5 : Parse multiple group name. +// Add support of specifying the base path to load material file. +// version 0.9.4 : Initial suupport of group tag(g) +// version 0.9.3 : Fix parsing triple 'x/y/z' +// version 0.9.2 : Add more .mtl load support +// version 0.9.1 : Add initial .mtl load support +// version 0.9.0 : Initial // -#include "CCObjLoader.h" +#include +#include +#include +#include +#include +#include +#include +#include #include #include - #include "platform/CCFileUtils.h" #include "base/ccUtils.h" -NS_CC_BEGIN - -struct vertex_index -{ - int v_idx, vt_idx, vn_idx; - vertex_index() {}; - vertex_index(int idx) : v_idx(idx), vt_idx(idx), vn_idx(idx) {}; - vertex_index(int vidx, int vtidx, int vnidx) : v_idx(vidx), vt_idx(vtidx), vn_idx(vnidx) {}; - -}; -// for std::map -static inline bool operator<(const vertex_index& a, const vertex_index& b) -{ - if (a.v_idx != b.v_idx) return (a.v_idx < b.v_idx); - if (a.vn_idx != b.vn_idx) return (a.vn_idx < b.vn_idx); - if (a.vt_idx != b.vt_idx) return (a.vt_idx < b.vt_idx); - return false; -} - -struct obj_shape -{ - std::vector v; - std::vector vn; - std::vector vt; -}; - -static inline bool isSpace(const char c) -{ - return (c == ' ') || (c == '\t'); -} - -static inline bool isNewLine(const char c) -{ - return (c == '\r') || (c == '\n') || (c == '\0'); -} - -// Make index zero-base, and also support relative index. -static inline int fixIndex(int idx, int n) -{ - int i; - - if (idx > 0) { - i = idx - 1; - } else if (idx == 0) { - i = 0; - } else { // negative value = relative - i = n + idx; - } - return i; -} - -static inline std::string parseString(const char*& token) -{ - std::string s; - auto b = strspn(token, " \t"); - auto e = strcspn(token, " \t\r"); - s = std::string(&token[b], &token[e]); - - token += (e - b); - return s; -} - -static inline int parseInt(const char*& token) -{ - token += strspn(token, " \t"); - int i = atoi(token); - token += strcspn(token, " \t\r"); - return i; -} - -static inline float parseFloat(const char*& token) -{ - token += strspn(token, " \t"); - float f = (float)utils::atof(token); - token += strcspn(token, " \t\r"); - return f; -} - -static inline void parseFloat2(float& x, float& y, const char*& token) -{ - x = parseFloat(token); - y = parseFloat(token); -} - -static inline void parseFloat3(float& x, float& y, float& z, const char*& token) -{ - x = parseFloat(token); - y = parseFloat(token); - z = parseFloat(token); -} +#include "CCObjLoader.h" -// Parse triples: i, i/j/k, i//k, i/j -static vertex_index parseTriple(const char* &token, int vsize, int vnsize, int vtsize) -{ - vertex_index vi(-1); +namespace tinyobj { - vi.v_idx = fixIndex(atoi(token), vsize); - token += strcspn(token, "/ \t\r"); - if (token[0] != '/') { - return vi; - } - token++; +#define TINYOBJ_SSCANF_BUFFER_SIZE (4096) - // i//k - if (token[0] == '/') { - token++; - vi.vn_idx = fixIndex(atoi(token), vnsize); - token += strcspn(token, "/ \t\r"); - return vi; + struct vertex_index { + int v_idx, vt_idx, vn_idx; + vertex_index(){}; + vertex_index(int idx) : v_idx(idx), vt_idx(idx), vn_idx(idx){}; + vertex_index(int vidx, int vtidx, int vnidx) + : v_idx(vidx), vt_idx(vtidx), vn_idx(vnidx){}; + }; + // for std::map + static inline bool operator<(const vertex_index &a, const vertex_index &b) { + if (a.v_idx != b.v_idx) + return (a.v_idx < b.v_idx); + if (a.vn_idx != b.vn_idx) + return (a.vn_idx < b.vn_idx); + if (a.vt_idx != b.vt_idx) + return (a.vt_idx < b.vt_idx); + + return false; } - // i/j/k or i/j - vi.vt_idx = fixIndex(atoi(token), vtsize); - token += strcspn(token, "/ \t\r"); - if (token[0] != '/') { - return vi; - } + struct obj_shape { + std::vector v; + std::vector vn; + std::vector vt; + }; - // i/j/k - token++; // skip '/' - vi.vn_idx = fixIndex(atoi(token), vnsize); - token += strcspn(token, "/ \t\r"); - return vi; -} - -static ssize_t updateVertex( std::map& vertexCache, std::vector& positions, std::vector& normals, - std::vector& texcoords, const std::vector& in_positions, const std::vector& in_normals, const std::vector& in_texcoords, - const vertex_index& i) -{ - const auto it = vertexCache.find(i); + static inline bool isSpace(const char c) { return (c == ' ') || (c == '\t'); } - if (it != vertexCache.end()) - { - // found cache - return it->second; + static inline bool isNewLine(const char c) { + return (c == '\r') || (c == '\n') || (c == '\0'); } - assert(in_positions.size() > static_cast(3*i.v_idx+2)); - - positions.push_back(in_positions[3*i.v_idx+0]); - positions.push_back(in_positions[3*i.v_idx+1]); - positions.push_back(in_positions[3*i.v_idx+2]); - - if (i.vn_idx >= 0) - { - normals.push_back(in_normals[3*i.vn_idx+0]); - normals.push_back(in_normals[3*i.vn_idx+1]); - normals.push_back(in_normals[3*i.vn_idx+2]); + // Make index zero-base, and also support relative index. + static inline int fixIndex(int idx, int n) { + if (idx > 0) return idx - 1; + if (idx == 0) return 0; + return n + idx; // negative value = relative } - if (i.vt_idx >= 0) - { - texcoords.push_back(in_texcoords[2*i.vt_idx+0]); - texcoords.push_back(in_texcoords[2*i.vt_idx+1]); + static inline std::string parseString(const char *&token) { + std::string s; + token += strspn(token, " \t"); + size_t e = strcspn(token, " \t\r"); + s = std::string(token, &token[e]); + token += e; + return s; } - auto idx = positions.size() / 3 - 1; - vertexCache[i] = idx; - - return idx; -} - -static bool exportFaceGroupToShape( std::map& vertexCache, ObjLoader::shapes_t& shapes, const std::vector &in_positions, - const std::vector &in_normals, const std::vector &in_texcoords, const std::vector >& faceGroup, - const ObjLoader::material_t &material, const std::string &name) -{ - if (faceGroup.empty()) - { - return false; + static inline int parseInt(const char *&token) { + token += strspn(token, " \t"); + int i = atoi(token); + token += strcspn(token, " \t\r"); + return i; } - // Flattened version of vertex data - std::vector& positions = shapes.positions; - std::vector& normals = shapes.normals; - std::vector& texcoords = shapes.texcoords; - std::vector indices; - // Flatten vertices and indices - for (size_t i = 0; i < faceGroup.size(); i++) + // Tries to parse a floating point number located at s. + // + // s_end should be a location in the string where reading should absolutely + // stop. For example at the end of the string, to prevent buffer overflows. + // + // Parses the following EBNF grammar: + // sign = "+" | "-" ; + // END = ? anything not in digit ? + // digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ; + // integer = [sign] , digit , {digit} ; + // decimal = integer , ["." , integer] ; + // float = ( decimal , END ) | ( decimal , ("E" | "e") , integer , END ) ; + // + // Valid strings are for example: + // -0 +3.1417e+2 -0.0E-3 1.0324 -1.41 11e2 + // + // If the parsing is a success, result is set to the parsed value and true + // is returned. + // + // The function is greedy and will parse until any of the following happens: + // - a non-conforming character is encountered. + // - s_end is reached. + // + // The following situations triggers a failure: + // - s >= s_end. + // - parse failure. + // + static bool tryParseDouble(const char *s, const char *s_end, double *result) { - const std::vector& face = faceGroup[i]; + if (s >= s_end) + { + return false; + } - vertex_index i0 = face[0]; - vertex_index i1(-1); - vertex_index i2 = face[1]; + double mantissa = 0.0; + // This exponent is base 2 rather than 10. + // However the exponent we parse is supposed to be one of ten, + // thus we must take care to convert the exponent/and or the + // mantissa to a * 2^E, where a is the mantissa and E is the + // exponent. + // To get the final double we will use ldexp, it requires the + // exponent to be in base 2. + int exponent = 0; - size_t npolys = face.size(); + // NOTE: THESE MUST BE DECLARED HERE SINCE WE ARE NOT ALLOWED + // TO JUMP OVER DEFINITIONS. + char sign = '+'; + char exp_sign = '+'; + char const *curr = s; - // Polygon -> triangle fan conversion - for (size_t k = 2; k < npolys; k++) - { - i1 = i2; - i2 = face[k]; - - unsigned short v0 = updateVertex(vertexCache, positions, normals, texcoords, in_positions, in_normals, in_texcoords, i0); - unsigned short v1 = updateVertex(vertexCache, positions, normals, texcoords, in_positions, in_normals, in_texcoords, i1); - unsigned short v2 = updateVertex(vertexCache, positions, normals, texcoords, in_positions, in_normals, in_texcoords, i2); - - indices.push_back(v0); - indices.push_back(v1); - indices.push_back(v2); - } - } - - ObjLoader::shape_t shape; - shape.name = name; - shape.material = material; - shape.mesh.indices.swap(indices); - - shapes.shapes.push_back(shape); - return true; - -} - -std::string trim(const std::string& str) -{ - if (str.empty()) - return str; - auto len = str.length(); - char c = str[len - 1]; - while (c == '\r' || c == '\n') - { - len--; - c = str[len - 1]; - } - return str.substr(0, len); -} - -void InitMaterial(ObjLoader::material_t& material) -{ - material.name = ""; - material.ambient_texname = ""; - material.diffuse_texname = ""; - material.specular_texname = ""; - material.normal_texname = ""; - for (int i = 0; i < 3; i ++) - { - material.ambient[i] = 0.f; - material.diffuse[i] = 0.f; - material.specular[i] = 0.f; - material.transmittance[i] = 0.f; - material.emission[i] = 0.f; - } - material.illum = 0; - material.dissolve = 1.f; - material.shininess = 1.f; - material.unknown_parameter.clear(); -} - -static std::string& replacePathSeperator(std::string& path) -{ - for (size_t i = 0; i < path.size(); i++) { - if (path[i] == '\\') - path[i] = '/'; - } - return path; -} - -std::string LoadMtl ( std::map& material_map, const char* filename, const char* mtl_basepath) -{ - material_map.clear(); - std::stringstream err; - - std::string filepath; - - if (mtl_basepath) - { - filepath = std::string(mtl_basepath) + std::string(filename); - } - else - { - filepath = std::string(filename); - } - - std::istringstream ifs(FileUtils::getInstance()->getStringFromFile(filepath)); - if (!ifs) - { - err << "Cannot open file [" << filepath << "]" << std::endl; - return err.str(); - } - - ObjLoader::material_t material; - - int maxchars = 8192; // Alloc enough size. - std::vector buf(maxchars); // Alloc enough size. - while (ifs.peek() != -1) - { - ifs.getline(&buf[0], maxchars); + // How many characters were read in a loop. + int read = 0; + // Tells whether a loop terminated due to reaching s_end. + bool end_not_reached = false; - std::string linebuf(&buf[0]); + /* + BEGIN PARSING. + */ - // Trim newline '\r\n' or '\r' - if (linebuf.size() > 0) + // Find out what sign we've got. + if (*curr == '+' || *curr == '-') { - if (linebuf[linebuf.size()-1] == '\n') linebuf.erase(linebuf.size()-1); + sign = *curr; + curr++; } - if (linebuf.size() > 0) + else if (isdigit(*curr)) { /* Pass through. */ } + else { - if (linebuf[linebuf.size()-1] == '\n') linebuf.erase(linebuf.size()-1); + goto fail; } - // Skip if empty line. - if (linebuf.empty()) + // Read the integer part. + while ((end_not_reached = (curr != s_end)) && isdigit(*curr)) { - continue; + mantissa *= 10; + mantissa += static_cast(*curr - 0x30); + curr++; read++; } - // Skip leading space. - const char* token = linebuf.c_str(); - token += strspn(token, " \t"); - - assert(token); - if (token[0] == '\0') continue; // empty line + // We must make sure we actually got something. + if (read == 0) + goto fail; + // We allow numbers of form "#", "###" etc. + if (!end_not_reached) + goto assemble; - if (token[0] == '#') continue; // comment line - - // new mtl - if ((0 == strncmp(token, "newmtl", 6)) && isSpace((token[6]))) + // Read the decimal part. + if (*curr == '.') { - // flush previous material. - material_map.insert(std::pair(material.name, material)); - - // initial temporary material - InitMaterial(material); - - // set new mtl name - char namebuf[4096]; - token += 7; - sscanf(token, "%s", namebuf); - material.name = namebuf; - continue; + curr++; + read = 1; + while ((end_not_reached = (curr != s_end)) && isdigit(*curr)) + { + // NOTE: Don't use powf here, it will absolutely murder precision. + mantissa += static_cast(*curr - 0x30) * pow(10.0, -read); + read++; curr++; + } } - - // ambient - if (token[0] == 'K' && token[1] == 'a' && isSpace((token[2]))) + else if (*curr == 'e' || *curr == 'E') {} + else { - token += 2; - float r, g, b; - parseFloat3(r, g, b, token); - material.ambient[0] = r; - material.ambient[1] = g; - material.ambient[2] = b; - continue; + goto assemble; } - // diffuse - if (token[0] == 'K' && token[1] == 'd' && isSpace((token[2]))) - { - token += 2; - float r, g, b; - parseFloat3(r, g, b, token); - material.diffuse[0] = r; - material.diffuse[1] = g; - material.diffuse[2] = b; - continue; - } + if (!end_not_reached) + goto assemble; - // specular - if (token[0] == 'K' && token[1] == 's' && isSpace((token[2]))) + // Read the exponent part. + if (*curr == 'e' || *curr == 'E') { - token += 2; - float r, g, b; - parseFloat3(r, g, b, token); - material.specular[0] = r; - material.specular[1] = g; - material.specular[2] = b; - continue; + curr++; + // Figure out if a sign is present and if it is. + if ((end_not_reached = (curr != s_end)) && (*curr == '+' || *curr == '-')) + { + exp_sign = *curr; + curr++; + } + else if (isdigit(*curr)) { /* Pass through. */ } + else + { + // Empty E is not allowed. + goto fail; + } + + read = 0; + while ((end_not_reached = (curr != s_end)) && isdigit(*curr)) + { + exponent *= 10; + exponent += static_cast(*curr - 0x30); + curr++; read++; + } + exponent *= (exp_sign == '+'? 1 : -1); + if (read == 0) + goto fail; } - // transmittance - if (token[0] == 'K' && token[1] == 't' && isSpace((token[2]))) - { - token += 2; - float r, g, b; - parseFloat3(r, g, b, token); - material.transmittance[0] = r; - material.transmittance[1] = g; - material.transmittance[2] = b; - continue; - } + assemble: + *result = (sign == '+'? 1 : -1) * ldexp(mantissa * pow(5.0, exponent), exponent); + return true; + fail: + return false; + } + static inline float parseFloat(const char *&token) { + token += strspn(token, " \t"); +#ifdef TINY_OBJ_LOADER_OLD_FLOAT_PARSER + float f = (float)utils::atof(token); + token += strcspn(token, " \t\r"); +#else + const char *end = token + strcspn(token, " \t\r"); + double val = 0.0; + tryParseDouble(token, end, &val); + float f = static_cast(val); + token = end; +#endif + return f; + } + + + static inline void parseFloat2(float &x, float &y, const char *&token) { + x = parseFloat(token); + y = parseFloat(token); + } + + static inline void parseFloat3(float &x, float &y, float &z, + const char *&token) { + x = parseFloat(token); + y = parseFloat(token); + z = parseFloat(token); + } + + // Parse triples: i, i/j/k, i//k, i/j + static vertex_index parseTriple(const char *&token, int vsize, int vnsize, + int vtsize) { + vertex_index vi(-1); - // ior(index of refraction) - if (token[0] == 'N' && token[1] == 'i' && isSpace((token[2]))) - { - token += 2; - material.ior = parseFloat(token); - continue; + vi.v_idx = fixIndex(atoi(token), vsize); + token += strcspn(token, "/ \t\r"); + if (token[0] != '/') { + return vi; } + token++; - // emission - if(token[0] == 'K' && token[1] == 'e' && isSpace(token[2])) - { - token += 2; - float r, g, b; - parseFloat3(r, g, b, token); - material.emission[0] = r; - material.emission[1] = g; - material.emission[2] = b; - continue; + // i//k + if (token[0] == '/') { + token++; + vi.vn_idx = fixIndex(atoi(token), vnsize); + token += strcspn(token, "/ \t\r"); + return vi; } - // shininess - if(token[0] == 'N' && token[1] == 's' && isSpace(token[2])) - { - token += 2; - material.shininess = parseFloat(token); - continue; + // i/j/k or i/j + vi.vt_idx = fixIndex(atoi(token), vtsize); + token += strcspn(token, "/ \t\r"); + if (token[0] != '/') { + return vi; } - // illum model - if (0 == strncmp(token, "illum", 5) && isSpace(token[5])) - { - token += 6; - material.illum = parseInt(token); - continue; - } + // i/j/k + token++; // skip '/' + vi.vn_idx = fixIndex(atoi(token), vnsize); + token += strcspn(token, "/ \t\r"); + return vi; + } + + static unsigned int + updateVertex(std::map &vertexCache, + std::vector &positions, std::vector &normals, + std::vector &texcoords, + const std::vector &in_positions, + const std::vector &in_normals, + const std::vector &in_texcoords, const vertex_index &i) { + const std::map::iterator it = vertexCache.find(i); - // dissolve - if ((token[0] == 'd' && isSpace(token[1]))) - { - token += 1; - material.dissolve = parseFloat(token); - continue; - } - if (token[0] == 'T' && token[1] == 'r' && isSpace(token[2])) - { - token += 2; - material.dissolve = parseFloat(token); - continue; + if (it != vertexCache.end()) { + // found cache + return it->second; } - // ambient texture - if ((0 == strncmp(token, "map_Ka", 6)) && isSpace(token[6])) - { - token += 7; - material.ambient_texname = trim(token); - replacePathSeperator(material.ambient_texname); - continue; - } + assert(in_positions.size() > (unsigned int)(3 * i.v_idx + 2)); - // diffuse texture - if ((0 == strncmp(token, "map_Kd", 6)) && isSpace(token[6])) - { - token += 7; - material.diffuse_texname = trim(token); - replacePathSeperator(material.diffuse_texname); - continue; - } + positions.push_back(in_positions[3 * i.v_idx + 0]); + positions.push_back(in_positions[3 * i.v_idx + 1]); + positions.push_back(in_positions[3 * i.v_idx + 2]); - // specular texture - if ((0 == strncmp(token, "map_Ks", 6)) && isSpace(token[6])) - { - token += 7; - material.specular_texname = trim(token); - replacePathSeperator(material.specular_texname); - continue; + if (i.vn_idx >= 0) { + normals.push_back(in_normals[3 * i.vn_idx + 0]); + normals.push_back(in_normals[3 * i.vn_idx + 1]); + normals.push_back(in_normals[3 * i.vn_idx + 2]); } - // normal texture - if ((0 == strncmp(token, "map_Ns", 6)) && isSpace(token[6])) - { - token += 7; - material.normal_texname = trim(token); - replacePathSeperator(material.normal_texname); - continue; + if (i.vt_idx >= 0) { + texcoords.push_back(in_texcoords[2 * i.vt_idx + 0]); + texcoords.push_back(in_texcoords[2 * i.vt_idx + 1]); } - // unknown parameter - const char* _space = strchr(token, ' '); - if(!_space) - { - _space = strchr(token, '\t'); - } - if(_space) - { - auto len = _space - token; - std::string key(token, len); - std::string value = _space + 1; - material.unknown_parameter.insert(std::pair(key, value)); - } + unsigned int idx = static_cast(positions.size() / 3 - 1); + vertexCache[i] = idx; + + return idx; } - // flush last material. - material_map.insert(std::pair(material.name, material)); - return err.str(); -} - -std::string ObjLoader::LoadObj(shapes_t& shapes, const char* filename, const char* mtl_basepath) -{ - shapes.reset(); - std::stringstream err; - std::istringstream ifs(FileUtils::getInstance()->getStringFromFile(filename)); - std::map vertexCache; - //std::ifstream ifs(filename); - - if (!ifs) - { - err << "Cannot open file [" << filename << "]" << std::endl; - return err.str(); + void InitMaterial(material_t &material) { + material.name = ""; + material.ambient_texname = ""; + material.diffuse_texname = ""; + material.specular_texname = ""; + material.normal_texname = ""; + for (int i = 0; i < 3; i++) { + material.ambient[i] = 0.f; + material.diffuse[i] = 0.f; + material.specular[i] = 0.f; + material.transmittance[i] = 0.f; + material.emission[i] = 0.f; + } + material.illum = 0; + material.dissolve = 1.f; + material.shininess = 1.f; + material.ior = 1.f; + material.unknown_parameter.clear(); } - std::vector v; - std::vector vn; - std::vector vt; - std::vector > faceGroup; - std::string name; - - // material - std::map material_map; - material_t material; - - int maxchars = 8192; // Alloc enough size. - std::vector buf(maxchars); // Alloc enough size. - while (ifs.peek() != -1) - { - ifs.getline(&buf[0], maxchars); + static bool exportFaceGroupToShape( + shape_t &shape, std::map vertexCache, + const std::vector &in_positions, + const std::vector &in_normals, + const std::vector &in_texcoords, + const std::vector > &faceGroup, + const int material_id, const std::string &name, bool clearCache) { + if (faceGroup.empty()) { + return false; + } + + // Flatten vertices and indices + for (size_t i = 0; i < faceGroup.size(); i++) { + const std::vector &face = faceGroup[i]; + + vertex_index i0 = face[0]; + vertex_index i1(-1); + vertex_index i2 = face[1]; + + size_t npolys = face.size(); + + // Polygon -> triangle fan conversion + for (size_t k = 2; k < npolys; k++) { + i1 = i2; + i2 = face[k]; + + unsigned int v0 = updateVertex( + vertexCache, shape.mesh.positions, shape.mesh.normals, + shape.mesh.texcoords, in_positions, in_normals, in_texcoords, i0); + unsigned int v1 = updateVertex( + vertexCache, shape.mesh.positions, shape.mesh.normals, + shape.mesh.texcoords, in_positions, in_normals, in_texcoords, i1); + unsigned int v2 = updateVertex( + vertexCache, shape.mesh.positions, shape.mesh.normals, + shape.mesh.texcoords, in_positions, in_normals, in_texcoords, i2); + + shape.mesh.indices.push_back(v0); + shape.mesh.indices.push_back(v1); + shape.mesh.indices.push_back(v2); + + shape.mesh.material_ids.push_back(material_id); + } + } - std::string linebuf(&buf[0]); + shape.name = name; - // Trim newline '\r\n' or '\r' - if (linebuf.size() > 0) - { - if (linebuf[linebuf.size()-1] == '\n') linebuf.erase(linebuf.size()-1); + if (clearCache) + vertexCache.clear(); + + return true; + } + + static std::string& replacePathSeperator(std::string& path) + { + for (std::string::size_type i = 0; i < path.size(); i++) { + if (path[i] == '\\') + path[i] = '/'; } - if (linebuf.size() > 0) - { - if (linebuf[linebuf.size()-1] == '\n') linebuf.erase(linebuf.size()-1); + return path; + } + + std::string LoadMtl(std::map &material_map, + std::vector &materials, + std::istream &inStream) { + std::stringstream err; + + // Create a default material anyway. + material_t material; + InitMaterial(material); + + int maxchars = 8192; // Alloc enough size. + std::vector buf(maxchars); // Alloc enough size. + while (inStream.peek() != -1) { + inStream.getline(&buf[0], maxchars); + + std::string linebuf(&buf[0]); + + // Trim newline '\r\n' or '\n' + if (linebuf.size() > 0) { + if (linebuf[linebuf.size() - 1] == '\n') + linebuf.erase(linebuf.size() - 1); + } + if (linebuf.size() > 0) { + if (linebuf[linebuf.size() - 1] == '\r') + linebuf.erase(linebuf.size() - 1); + } + + // Skip if empty line. + if (linebuf.empty()) { + continue; + } + + // Skip leading space. + const char *token = linebuf.c_str(); + token += strspn(token, " \t"); + + assert(token); + if (token[0] == '\0') + continue; // empty line + + if (token[0] == '#') + continue; // comment line + + // new mtl + if ((0 == strncmp(token, "newmtl", 6)) && isSpace((token[6]))) { + // flush previous material. + if (!material.name.empty()) { + material_map.insert( + std::pair(material.name, static_cast(materials.size()))); + materials.push_back(material); + } + + // initial temporary material + InitMaterial(material); + + // set new mtl name + char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE]; + token += 7; +#ifdef _MSC_VER + sscanf_s(token, "%s", namebuf, _countof(namebuf)); +#else + sscanf(token, "%s", namebuf); +#endif + material.name = namebuf; + continue; + } + + // ambient + if (token[0] == 'K' && token[1] == 'a' && isSpace((token[2]))) { + token += 2; + float r, g, b; + parseFloat3(r, g, b, token); + material.ambient[0] = r; + material.ambient[1] = g; + material.ambient[2] = b; + continue; + } + + // diffuse + if (token[0] == 'K' && token[1] == 'd' && isSpace((token[2]))) { + token += 2; + float r, g, b; + parseFloat3(r, g, b, token); + material.diffuse[0] = r; + material.diffuse[1] = g; + material.diffuse[2] = b; + continue; + } + + // specular + if (token[0] == 'K' && token[1] == 's' && isSpace((token[2]))) { + token += 2; + float r, g, b; + parseFloat3(r, g, b, token); + material.specular[0] = r; + material.specular[1] = g; + material.specular[2] = b; + continue; + } + + // transmittance + if (token[0] == 'K' && token[1] == 't' && isSpace((token[2]))) { + token += 2; + float r, g, b; + parseFloat3(r, g, b, token); + material.transmittance[0] = r; + material.transmittance[1] = g; + material.transmittance[2] = b; + continue; + } + + // ior(index of refraction) + if (token[0] == 'N' && token[1] == 'i' && isSpace((token[2]))) { + token += 2; + material.ior = parseFloat(token); + continue; + } + + // emission + if (token[0] == 'K' && token[1] == 'e' && isSpace(token[2])) { + token += 2; + float r, g, b; + parseFloat3(r, g, b, token); + material.emission[0] = r; + material.emission[1] = g; + material.emission[2] = b; + continue; + } + + // shininess + if (token[0] == 'N' && token[1] == 's' && isSpace(token[2])) { + token += 2; + material.shininess = parseFloat(token); + continue; + } + + // illum model + if (0 == strncmp(token, "illum", 5) && isSpace(token[5])) { + token += 6; + material.illum = parseInt(token); + continue; + } + + // dissolve + if ((token[0] == 'd' && isSpace(token[1]))) { + token += 1; + material.dissolve = parseFloat(token); + continue; + } + if (token[0] == 'T' && token[1] == 'r' && isSpace(token[2])) { + token += 2; + // Invert value of Tr(assume Tr is in range [0, 1]) + material.dissolve = 1.0 - parseFloat(token); + continue; + } + + // ambient texture + if ((0 == strncmp(token, "map_Ka", 6)) && isSpace(token[6])) { + token += 7; + material.ambient_texname = token; + replacePathSeperator(material.ambient_texname); + continue; + } + + // diffuse texture + if ((0 == strncmp(token, "map_Kd", 6)) && isSpace(token[6])) { + token += 7; + material.diffuse_texname = token; + replacePathSeperator(material.diffuse_texname); + continue; + } + + // specular texture + if ((0 == strncmp(token, "map_Ks", 6)) && isSpace(token[6])) { + token += 7; + material.specular_texname = token; + replacePathSeperator(material.specular_texname); + continue; + } + + // normal texture + if ((0 == strncmp(token, "map_Ns", 6)) && isSpace(token[6])) { + token += 7; + material.normal_texname = token; + replacePathSeperator(material.normal_texname); + continue; + } + + // unknown parameter + const char *_space = strchr(token, ' '); + if (!_space) { + _space = strchr(token, '\t'); + } + if (_space) { + std::ptrdiff_t len = _space - token; + std::string key(token, len); + std::string value = _space + 1; + material.unknown_parameter.insert( + std::pair(key, value)); + } } + // flush last material. + material_map.insert( + std::pair(material.name, static_cast(materials.size()))); + materials.push_back(material); - // Skip if empty line. - if (linebuf.empty()) - { - continue; - } + return err.str(); + } + + std::string MaterialFileReader::operator()(const std::string &matId, + std::vector &materials, + std::map &matMap) { + std::string filepath; - // Skip leading space. - const char* token = linebuf.c_str(); - token += strspn(token, " \t"); + if (!m_mtlBasePath.empty()) { + filepath = std::string(m_mtlBasePath) + matId; + } else { + filepath = matId; + } - assert(token); - if (token[0] == '\0') continue; // empty line + std::istringstream matIStream(cocos2d::FileUtils::getInstance()->getStringFromFile(filepath)); + std::string err = LoadMtl(matMap, materials, matIStream); + if (!matIStream) { + std::stringstream ss; + ss << "WARN: Material file [ " << filepath << " ] not found. Created a default material."; + err += ss.str(); + } + return err; + } + + std::string LoadObj(std::vector &shapes, + std::vector &materials, // [output] + const char *filename, const char *mtl_basepath) { - if (token[0] == '#') continue; // comment line + shapes.clear(); - // vertex - if (token[0] == 'v' && isSpace((token[1]))) - { - token += 2; - float x, y, z; - parseFloat3(x, y, z, token); - v.push_back(x); - v.push_back(y); - v.push_back(z); - continue; - } + std::stringstream err; - // normal - if (token[0] == 'v' && token[1] == 'n' && isSpace((token[2]))) - { - token += 3; - float x, y, z; - parseFloat3(x, y, z, token); - vn.push_back(x); - vn.push_back(y); - vn.push_back(z); - continue; + std::istringstream ifs(cocos2d::FileUtils::getInstance()->getStringFromFile(filename)); + if (!ifs) { + err << "Cannot open file [" << filename << "]" << std::endl; + return err.str(); } - // texcoord - if (token[0] == 'v' && token[1] == 't' && isSpace((token[2]))) - { - token += 3; - float x, y; - parseFloat2(x, y, token); - vt.push_back(x); - vt.push_back(y); - continue; + std::string basePath; + if (mtl_basepath) { + basePath = mtl_basepath; } + MaterialFileReader matFileReader(basePath); - // face - if (token[0] == 'f' && isSpace((token[1]))) - { - token += 2; - token += strspn(token, " \t"); + return LoadObj(shapes, materials, ifs, matFileReader); + } + + std::string LoadObj(std::vector &shapes, + std::vector &materials, // [output] + std::istream &inStream, MaterialReader &readMatFn) { + std::stringstream err; + + std::vector v; + std::vector vn; + std::vector vt; + std::vector > faceGroup; + std::string name; + + // material + std::map material_map; + std::map vertexCache; + int material = -1; + + shape_t shape; + + int maxchars = 8192; // Alloc enough size. + std::vector buf(maxchars); // Alloc enough size. + while (inStream.peek() != -1) { + inStream.getline(&buf[0], maxchars); - std::vector face; - while (!isNewLine(token[0])) { - // fix warning, cast to int, i think int is enough - vertex_index vi = parseTriple(token, (int)v.size() / 3, (int)vn.size() / 3, (int)vt.size() / 2); - face.push_back(vi); - auto n = strspn(token, " \t\r"); - token += n; + std::string linebuf(&buf[0]); + + // Trim newline '\r\n' or '\n' + if (linebuf.size() > 0) { + if (linebuf[linebuf.size() - 1] == '\n') + linebuf.erase(linebuf.size() - 1); + } + if (linebuf.size() > 0) { + if (linebuf[linebuf.size() - 1] == '\r') + linebuf.erase(linebuf.size() - 1); } - faceGroup.push_back(face); + // Skip if empty line. + if (linebuf.empty()) { + continue; + } - continue; - } - - // use mtl - if ((0 == strncmp(token, "usemtl", 6)) && isSpace((token[6]))) - { - exportFaceGroupToShape(vertexCache, shapes, v, vn, vt, faceGroup, material, name); - faceGroup.clear(); + // Skip leading space. + const char *token = linebuf.c_str(); + token += strspn(token, " \t"); - char namebuf[4096]; - token += 7; - sscanf(token, "%s", namebuf); + assert(token); + if (token[0] == '\0') + continue; // empty line - if (material_map.find(namebuf) != material_map.end()) - { - material = material_map[namebuf]; - } - else - { - // { error!! material not found } - InitMaterial(material); + if (token[0] == '#') + continue; // comment line + + // vertex + if (token[0] == 'v' && isSpace((token[1]))) { + token += 2; + float x, y, z; + parseFloat3(x, y, z, token); + v.push_back(x); + v.push_back(y); + v.push_back(z); + continue; } - continue; - } - - // load mtl - if ((0 == strncmp(token, "mtllib", 6)) && isSpace((token[6]))) - { - char namebuf[4096]; - token += 7; - sscanf(token, "%s", namebuf); + // normal + if (token[0] == 'v' && token[1] == 'n' && isSpace((token[2]))) { + token += 3; + float x, y, z; + parseFloat3(x, y, z, token); + vn.push_back(x); + vn.push_back(y); + vn.push_back(z); + continue; + } - std::string err_mtl = LoadMtl(material_map, namebuf, mtl_basepath); - if (!err_mtl.empty()) - { - faceGroup.clear(); // for safety - //return err_mtl; + // texcoord + if (token[0] == 'v' && token[1] == 't' && isSpace((token[2]))) { + token += 3; + float x, y; + parseFloat2(x, y, token); + vt.push_back(x); + vt.push_back(y); + continue; } - continue; - } - - // group name - if (token[0] == 'g' && isSpace((token[1]))) - { - // flush previous face group. - shape_t shape; - exportFaceGroupToShape(vertexCache, shapes, v, vn, vt, faceGroup, material, name); - faceGroup.clear(); + // face + if (token[0] == 'f' && isSpace((token[1]))) { + token += 2; + token += strspn(token, " \t"); + + std::vector face; + while (!isNewLine(token[0])) { + vertex_index vi = + parseTriple(token, static_cast(v.size() / 3), static_cast(vn.size() / 3), static_cast(vt.size() / 2)); + face.push_back(vi); + size_t n = strspn(token, " \t\r"); + token += n; + } + + faceGroup.push_back(face); + + continue; + } - std::vector names; - while (!isNewLine(token[0])) - { - std::string str = parseString(token); - names.push_back(str); - token += strspn(token, " \t\r"); // skip tag + // use mtl + if ((0 == strncmp(token, "usemtl", 6)) && isSpace((token[6]))) { + + char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE]; + token += 7; +#ifdef _MSC_VER + sscanf_s(token, "%s", namebuf, _countof(namebuf)); +#else + sscanf(token, "%s", namebuf); +#endif + + // Create face group per material. + bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, + faceGroup, material, name, true); + if (ret) { + shapes.push_back(shape); + } + shape = shape_t(); + faceGroup.clear(); + + if (material_map.find(namebuf) != material_map.end()) { + material = material_map[namebuf]; + } else { + // { error!! material not found } + material = -1; + } + + continue; } - assert(names.size() > 0); + // load mtl + if ((0 == strncmp(token, "mtllib", 6)) && isSpace((token[6]))) { + char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE]; + token += 7; +#ifdef _MSC_VER + sscanf_s(token, "%s", namebuf, _countof(namebuf)); +#else + sscanf(token, "%s", namebuf); +#endif + + std::string err_mtl = readMatFn(namebuf, materials, material_map); + if (!err_mtl.empty()) { + faceGroup.clear(); // for safety + return err_mtl; + } + + continue; + } - // names[0] must be 'g', so skipt 0th element. - if (names.size() > 1) - { - name = names[1]; + // group name + if (token[0] == 'g' && isSpace((token[1]))) { + + // flush previous face group. + bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, + faceGroup, material, name, true); + if (ret) { + shapes.push_back(shape); + } + + shape = shape_t(); + + // material = -1; + faceGroup.clear(); + + std::vector names; + while (!isNewLine(token[0])) { + std::string str = parseString(token); + names.push_back(str); + token += strspn(token, " \t\r"); // skip tag + } + + assert(names.size() > 0); + + // names[0] must be 'g', so skip the 0th element. + if (names.size() > 1) { + name = names[1]; + } else { + name = ""; + } + + continue; } - else - { - name = ""; + + // object name + if (token[0] == 'o' && isSpace((token[1]))) { + + // flush previous face group. + bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, + faceGroup, material, name, true); + if (ret) { + shapes.push_back(shape); + } + + // material = -1; + faceGroup.clear(); + shape = shape_t(); + + // @todo { multiple object name? } + char namebuf[TINYOBJ_SSCANF_BUFFER_SIZE]; + token += 2; +#ifdef _MSC_VER + sscanf_s(token, "%s", namebuf, _countof(namebuf)); +#else + sscanf(token, "%s", namebuf); +#endif + name = std::string(namebuf); + + continue; } - continue; + // Ignore unknown command. } - // object name - if (token[0] == 'o' && isSpace((token[1]))) - { - // flush previous face group. - shape_t shape; - exportFaceGroupToShape(vertexCache, shapes, v, vn, vt, faceGroup, material, name); - - faceGroup.clear(); - - // @todo { multiple object name? } - char namebuf[4096]; - token += 2; - sscanf(token, "%s", namebuf); - name = std::string(namebuf); - - continue; + bool ret = exportFaceGroupToShape(shape, vertexCache, v, vn, vt, faceGroup, + material, name, true); + if (ret) { + shapes.push_back(shape); } + faceGroup.clear(); // for safety - // Ignore unknown command. + return err.str(); } - - shape_t shape; - exportFaceGroupToShape(vertexCache, shapes, v, vn, vt, faceGroup, material, name); - faceGroup.clear(); // for safety - - return err.str(); } - -NS_CC_END diff --git a/cocos/3d/CCObjLoader.h b/cocos/3d/CCObjLoader.h index 3a9d38b3d552..2c23dd4b5a60 100644 --- a/cocos/3d/CCObjLoader.h +++ b/cocos/3d/CCObjLoader.h @@ -1,40 +1,19 @@ // -// Copyright 2012-2013, Syoyo Fujita. +// Copyright 2012-2015, Syoyo Fujita. // // Licensed under 2-clause BSD liecense. // -// copied from Syoyo Fujita -// https://github.com/syoyo/tinyobjloader - -#ifndef __CCOBJLOADER_H__ -#define __CCOBJLOADER_H__ +//https://github.com/syoyo/tinyobjloader +#ifndef _TINY_OBJ_LOADER_H +#define _TINY_OBJ_LOADER_H #include #include #include -#include "base/ccTypes.h" - -NS_CC_BEGIN - -/** - * @addtogroup _3d - * @{ - */ -/** - * @brief .obj file Loader - * @js NA - * @lua NA - **/ -class ObjLoader -{ -public: - - /** - * model's material struct - **/ - typedef struct - { +namespace tinyobj { + + typedef struct { std::string name; float ambient[3]; @@ -43,8 +22,8 @@ class ObjLoader float transmittance[3]; float emission[3]; float shininess; - float ior; // index of refraction - float dissolve; // 1 == opaque; 0 == fully transparent + float ior; // index of refraction + float dissolve; // 1 == opaque; 0 == fully transparent // illumination model (see http://www.fileformat.info/format/material/) int illum; @@ -55,61 +34,62 @@ class ObjLoader std::map unknown_parameter; } material_t; - /** - * model's indices struct - **/ - typedef struct - { - std::vector indices; + typedef struct { + std::vector positions; + std::vector normals; + std::vector texcoords; + std::vector indices; + std::vector material_ids; // per-mesh material ID } mesh_t; - /** - * model's shape struct - **/ - typedef struct - { - std::string name; - material_t material; - mesh_t mesh; + typedef struct { + std::string name; + mesh_t mesh; } shape_t; - /** - * model's shapes struct - **/ - typedef struct - { - std::vector positions; - std::vector normals; - std::vector texcoords; + class MaterialReader { + public: + MaterialReader() {} + virtual ~MaterialReader() {} - std::vector shapes; + virtual std::string operator()(const std::string &matId, + std::vector &materials, + std::map &matMap) = 0; + }; + + class MaterialFileReader : public MaterialReader { + public: + MaterialFileReader(const std::string &mtl_basepath) + : m_mtlBasePath(mtl_basepath) {} + virtual ~MaterialFileReader() {} + virtual std::string operator()(const std::string &matId, + std::vector &materials, + std::map &matMap); - void reset() - { - positions.clear(); - normals.clear(); - texcoords.clear(); - shapes.clear(); - } - }shapes_t; + private: + std::string m_mtlBasePath; + }; - /** - * Loads .obj from a file. - * @param shapes will be filled with parsed shape data - * @param filename the .obj file path . - * @param mtl_basepath It's optional, and used for base path for .mtl file - * @return The function returns error string, return empty string when loading .obj success. - */ - static std::string LoadObj( - shapes_t& shapes, // [output] - const char* filename, - const char* mtl_basepath = NULL); - -}; - -// end of 3d group -/// @} - -NS_CC_END + /// Loads .obj from a file. + /// 'shapes' will be filled with parsed shape data + /// The function returns error string. + /// Returns empty string when loading .obj success. + /// 'mtl_basepath' is optional, and used for base path for .mtl file. + std::string LoadObj(std::vector &shapes, // [output] + std::vector &materials, // [output] + const char *filename, const char *mtl_basepath = NULL); + + /// Loads object from a std::istream, uses GetMtlIStreamFn to retrieve + /// std::istream for materials. + /// Returns empty string when loading .obj success. + std::string LoadObj(std::vector &shapes, // [output] + std::vector &materials, // [output] + std::istream &inStream, MaterialReader &readMatFn); + + /// Loads materials into std::map + /// Returns an empty string if successful + std::string LoadMtl(std::map &material_map, + std::vector &materials, std::istream &inStream); +} -#endif // _TINY_OBJ_LOADER_H +#endif // _TINY_OBJ_LOADER_H diff --git a/cocos/3d/CCSprite3D.cpp b/cocos/3d/CCSprite3D.cpp index 2b60a9c530cd..48992ac6e361 100644 --- a/cocos/3d/CCSprite3D.cpp +++ b/cocos/3d/CCSprite3D.cpp @@ -352,8 +352,7 @@ Sprite3D* Sprite3D::createSprite3DNode(NodeData* nodedata,ModelData* modeldata,c if (modeldata->matrialId == "" && materialdatas.materials.size()) { const NTextureData* textureData = materialdatas.materials[0].getTextureData(NTextureData::Usage::Diffuse); - if (!textureData->filename.empty()) - mesh->setTexture(textureData->filename); + mesh->setTexture(textureData->filename); } else { @@ -361,9 +360,10 @@ Sprite3D* Sprite3D::createSprite3DNode(NodeData* nodedata,ModelData* modeldata,c if(materialData) { const NTextureData* textureData = materialData->getTextureData(NTextureData::Usage::Diffuse); - if(textureData && !textureData->filename.empty()) + if(textureData) { - auto tex = Director::getInstance()->getTextureCache()->addImage(textureData->filename); + mesh->setTexture(textureData->filename); + auto tex = mesh->getTexture(); if(tex) { Texture2D::TexParams texParams; @@ -372,10 +372,8 @@ Sprite3D* Sprite3D::createSprite3DNode(NodeData* nodedata,ModelData* modeldata,c texParams.wrapS = textureData->wrapS; texParams.wrapT = textureData->wrapT; tex->setTexParameters(texParams); - mesh->setTexture(tex); mesh->_isTransparent = (materialData->getTextureData(NTextureData::Usage::Transparency) != nullptr); } - } } } @@ -506,9 +504,10 @@ void Sprite3D::createNode(NodeData* nodedata, Node* root, const MaterialDatas& m if(materialData) { const NTextureData* textureData = materialData->getTextureData(NTextureData::Usage::Diffuse); - if(textureData && !textureData->filename.empty()) + if(textureData) { - auto tex = Director::getInstance()->getTextureCache()->addImage(textureData->filename); + mesh->setTexture(textureData->filename); + auto tex = mesh->getTexture(); if(tex) { Texture2D::TexParams texParams; @@ -517,10 +516,8 @@ void Sprite3D::createNode(NodeData* nodedata, Node* root, const MaterialDatas& m texParams.wrapS = textureData->wrapS; texParams.wrapT = textureData->wrapT; tex->setTexParameters(texParams); - mesh->setTexture(tex); mesh->_isTransparent = (materialData->getTextureData(NTextureData::Usage::Transparency) != nullptr); } - } } } @@ -982,7 +979,10 @@ static GLProgramState* getGLProgramStateForAttribs(MeshVertexData* meshVertexDat } else { - shader = GLProgram::SHADER_3D_POSITION; + if (hasNormal && usesLight) + shader = GLProgram::SHADER_3D_POSITION_NORMAL; + else + shader = GLProgram::SHADER_3D_POSITION; } CCASSERT(shader, "Couldn't find shader for sprite"); diff --git a/cocos/audio/AudioEngine.cpp b/cocos/audio/AudioEngine.cpp index 252c8de835c1..2e2b68e847a4 100644 --- a/cocos/audio/AudioEngine.cpp +++ b/cocos/audio/AudioEngine.cpp @@ -23,6 +23,7 @@ ****************************************************************************/ #include "platform/CCPlatformConfig.h" +#include #if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 @@ -61,8 +62,110 @@ AudioEngine::ProfileHelper* AudioEngine::_defaultProfileHelper = nullptr; std::unordered_map AudioEngine::_audioIDInfoMap; AudioEngineImpl* AudioEngine::_audioEngineImpl = nullptr; +AudioEngine::AudioEngineThreadPool* AudioEngine::s_threadPool = nullptr; + +class AudioEngine::AudioEngineThreadPool +{ +public: + AudioEngineThreadPool(bool detach) + : _numThread(6) + , _detach(detach) + { + s_threadPool = this; + + _threads.reserve(_numThread); + _tasks.reserve(_numThread); + + for (int index = 0; index < _numThread; ++index) { + _tasks.push_back(nullptr); + _threads.push_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this, index))); + if (_detach) + { + _threads[index].detach(); + } + } + } + + void addTask(const std::function &task){ + _taskMutex.lock(); + int targetIndex = -1; + for (int index = 0; index < _numThread; ++index) { + if (_tasks[index] == nullptr) { + targetIndex = index; + _tasks[index] = task; + break; + } + } + if (targetIndex == -1) { + _tasks.push_back(task); + _threads.push_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this, _numThread))); + if (_detach) + { + _threads[_numThread].detach(); + } + _numThread++; + } + _taskMutex.unlock(); + _sleepCondition.notify_all(); + } + + void destroy() + { + std::unique_lock lk(_sleepMutex); + _sleepCondition.notify_all(); + + if (!_detach) + { + for (int index = 0; index < _numThread; ++index) { + _threads[index].join(); + } + } + } + +private: + std::vector _threads; + std::vector< std::function > _tasks; + + void threadFunc(int index) + { + while (s_threadPool == this) { + std::function task = nullptr; + _taskMutex.lock(); + task = _tasks[index]; + _taskMutex.unlock(); + + if (nullptr == task) + { + std::unique_lock lk(_sleepMutex); + _sleepCondition.wait(lk); + continue; + } + + task(); + + _taskMutex.lock(); + _tasks[index] = nullptr; + _taskMutex.unlock(); + } + } + + int _numThread; + + std::mutex _taskMutex; + std::mutex _sleepMutex; + std::condition_variable _sleepCondition; + bool _detach; +}; + void AudioEngine::end() { + if (s_threadPool) + { + s_threadPool->destroy(); + delete s_threadPool; + s_threadPool = nullptr; + } + delete _audioEngineImpl; _audioEngineImpl = nullptr; @@ -82,6 +185,18 @@ bool AudioEngine::lazyInit() } } +#if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 + if (_audioEngineImpl && s_threadPool == nullptr) + { + s_threadPool = new (std::nothrow) AudioEngineThreadPool(true); + } +#elif CC_TARGET_PLATFORM != CC_PLATFORM_ANDROID + if (_audioEngineImpl && s_threadPool == nullptr) + { + s_threadPool = new (std::nothrow) AudioEngineThreadPool(false); + } +#endif + return true; } @@ -415,4 +530,28 @@ AudioProfile* AudioEngine::getProfile(const std::string &name) } } +void AudioEngine::preload(const std::string& filePath) +{ + lazyInit(); + + if (_audioEngineImpl) + { + if (!FileUtils::getInstance()->isFileExist(filePath)){ + return; + } + + _audioEngineImpl->preload(filePath); + } +} + +void AudioEngine::addTask(const std::function &task) +{ + lazyInit(); + + if (_audioEngineImpl && s_threadPool) + { + s_threadPool->addTask(task); + } +} + #endif diff --git a/cocos/audio/android/AudioEngine-inl.cpp b/cocos/audio/android/AudioEngine-inl.cpp index cc939d140b8b..ec755a9a7a63 100644 --- a/cocos/audio/android/AudioEngine-inl.cpp +++ b/cocos/audio/android/AudioEngine-inl.cpp @@ -1,5 +1,5 @@ /**************************************************************************** - Copyright (c) 2014 Chukong Technologies Inc. + Copyright (c) 2014-2015 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -432,4 +432,9 @@ void AudioEngineImpl::setFinishCallback(int audioID, const std::function &task){ - _taskMutex.lock(); - int targetIndex = -1; - for (int index = 0; index < _numThread; ++index) { - if (_tasks[index] == nullptr) { - targetIndex = index; - _tasks[index] = task; - break; - } - } - if (targetIndex == -1) { - _tasks.push_back(task); - _threads.push_back( std::thread( std::bind(&AudioEngineThreadPool::threadFunc,this,_numThread) ) ); - - _numThread++; - } - _taskMutex.unlock(); - - _sleepCondition.notify_all(); - } - - void destroy() - { - _running = false; - _sleepCondition.notify_all(); - - for (int index = 0; index < _numThread; ++index) { - _threads[index].join(); - } - } - - private: - bool _running; - std::vector _threads; - std::vector< std::function > _tasks; - - void threadFunc(int index) - { - while (_running) { - std::function task = nullptr; - _taskMutex.lock(); - task = _tasks[index]; - _taskMutex.unlock(); - - if (nullptr == task) - { - std::unique_lock lk(_sleepMutex); - _sleepCondition.wait(lk); - continue; - } - - task(); - - _taskMutex.lock(); - _tasks[index] = nullptr; - _taskMutex.unlock(); - } - } - - int _numThread; - - std::mutex _taskMutex; - std::mutex _sleepMutex; - std::condition_variable _sleepCondition; - - }; - } -} - #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS @interface AudioEngineSessionHandler : NSObject { @@ -220,8 +133,7 @@ -(void) dealloc #endif AudioEngineImpl::AudioEngineImpl() -: _threadPool(nullptr) -, _lazyInitLoop(true) +: _lazyInitLoop(true) , _currentAudioID(0) { @@ -240,10 +152,7 @@ -(void) dealloc if (s_ALDevice) { alcCloseDevice(s_ALDevice); } - if (_threadPool) { - _threadPool->destroy(); - delete _threadPool; - } + #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS [s_AudioEngineSessionHandler release]; #endif @@ -275,7 +184,6 @@ -(void) dealloc _alSourceUsed[_alSources[i]] = false; } - _threadPool = new (std::nothrow) AudioEngineThreadPool(); ret = true; } }while (false); @@ -283,6 +191,24 @@ -(void) dealloc return ret; } +AudioCache* AudioEngineImpl::preload(const std::string& filePath) +{ + AudioCache* audioCache = nullptr; + + auto it = _audioCaches.find(filePath); + if (it == _audioCaches.end()) { + audioCache = &_audioCaches[filePath]; + audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath); + + AudioEngine::addTask(std::bind(&AudioCache::readDataTask, audioCache)); + } + else { + audioCache = &it->second; + } + + return audioCache; +} + int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume) { if (s_ALDevice == nullptr) { @@ -303,16 +229,9 @@ -(void) dealloc return AudioEngine::INVALID_AUDIO_ID; } - AudioCache* audioCache = nullptr; - auto it = _audioCaches.find(filePath); - if (it == _audioCaches.end()) { - audioCache = &_audioCaches[filePath]; - audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath); - - _threadPool->addTask(std::bind(&AudioCache::readDataTask, audioCache)); - } - else { - audioCache = &it->second; + AudioCache* audioCache = preload(filePath); + if (audioCache == nullptr) { + return AudioEngine::INVALID_AUDIO_ID; } auto player = &_audioPlayers[_currentAudioID]; diff --git a/cocos/audio/include/AudioEngine.h b/cocos/audio/include/AudioEngine.h index 6b3945fb613c..374a363e946f 100644 --- a/cocos/audio/include/AudioEngine.h +++ b/cocos/audio/include/AudioEngine.h @@ -281,8 +281,14 @@ class EXPORT_DLL AudioEngine */ static AudioProfile* getProfile(const std::string &profileName); + /** + * Preload audio file. + * @param filePath The file path of an audio. + */ + static void preload(const std::string& filePath); + protected: - + static void addTask(const std::function &task); static void remove(int audioID); struct ProfileHelper @@ -335,6 +341,9 @@ class EXPORT_DLL AudioEngine static ProfileHelper* _defaultProfileHelper; static AudioEngineImpl* _audioEngineImpl; + + class AudioEngineThreadPool; + static AudioEngineThreadPool* s_threadPool; friend class AudioEngineImpl; }; diff --git a/cocos/audio/win32/AudioEngine-win32.cpp b/cocos/audio/win32/AudioEngine-win32.cpp index 573daa28674f..b8629cfa3e5c 100644 --- a/cocos/audio/win32/AudioEngine-win32.cpp +++ b/cocos/audio/win32/AudioEngine-win32.cpp @@ -26,7 +26,7 @@ #if CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 #include "AudioEngine-win32.h" -#include + #ifdef OPENAL_PLAIN_INCLUDES #include "alc.h" #include "alext.h" @@ -47,95 +47,9 @@ static ALCdevice *s_ALDevice = nullptr; static ALCcontext *s_ALContext = nullptr; static bool MPG123_LAZYINIT = true; -namespace cocos2d { - namespace experimental { - class AudioEngineThreadPool - { - public: - AudioEngineThreadPool() - : _running(true) - , _numThread(6) - { - _threads.reserve(_numThread); - _tasks.reserve(_numThread); - - for (int index = 0; index < _numThread; ++index) { - _tasks.push_back(nullptr); - _threads.push_back( std::thread( std::bind(&AudioEngineThreadPool::threadFunc,this,index) ) ); - _threads[index].detach(); - } - } - - void addTask(const std::function &task){ - _taskMutex.lock(); - int targetIndex = -1; - for (int index = 0; index < _numThread; ++index) { - if (_tasks[index] == nullptr) { - targetIndex = index; - _tasks[index] = task; - break; - } - } - if (targetIndex == -1) { - _tasks.push_back(task); - _threads.push_back( std::thread( std::bind(&AudioEngineThreadPool::threadFunc,this,_numThread) ) ); - _threads[_numThread].detach(); - _numThread++; - } - _taskMutex.unlock(); - _sleepCondition.notify_all(); - } - - void destroy() - { - _running = false; - _sleepCondition.notify_all(); - - for (int index = 0; index < _numThread; ++index) { - _threads[index].join(); - } - } - private: - bool _running; - std::vector _threads; - std::vector< std::function > _tasks; - - void threadFunc(int index) - { - while (_running) { - std::function task = nullptr; - _taskMutex.lock(); - task = _tasks[index]; - _taskMutex.unlock(); - - if (nullptr == task) - { - std::unique_lock lk(_sleepMutex); - _sleepCondition.wait(lk); - continue; - } - - task(); - - _taskMutex.lock(); - _tasks[index] = nullptr; - _taskMutex.unlock(); - } - } - - int _numThread; - - std::mutex _taskMutex; - std::mutex _sleepMutex; - std::condition_variable _sleepCondition; - }; - } -} - AudioEngineImpl::AudioEngineImpl() : _lazyInitLoop(true) , _currentAudioID(0) -, _threadPool(nullptr) { } @@ -155,10 +69,6 @@ AudioEngineImpl::~AudioEngineImpl() alcCloseDevice(s_ALDevice); s_ALDevice = nullptr; } - if (_threadPool) { - _threadPool->destroy(); - delete _threadPool; - } mpg123_exit(); MPG123_LAZYINIT = true; @@ -186,7 +96,6 @@ bool AudioEngineImpl::init() _alSourceUsed[_alSources[i]] = false; } - _threadPool = new (std::nothrow) AudioEngineThreadPool(); ret = true; } }while (false); @@ -194,63 +103,73 @@ bool AudioEngineImpl::init() return ret; } -int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume) +AudioCache* AudioEngineImpl::preload(const std::string& filePath) { - bool availableSourceExist = false; - ALuint alSource; - for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) { - alSource = _alSources[i]; - if ( !_alSourceUsed[alSource]) { - availableSourceExist = true; + AudioCache* audioCache = nullptr; + + do + { + auto it = _audioCaches.find(filePath); + if (it != _audioCaches.end()) + { + audioCache = &it->second; break; } - } - if(!availableSourceExist){ - return AudioEngine::INVALID_AUDIO_ID; - } - - AudioCache* audioCache = nullptr; - auto it = _audioCaches.find(filePath); - if (it == _audioCaches.end()) { - audioCache = &_audioCaches[filePath]; + auto ext = strchr(filePath.c_str(), '.'); - bool eraseCache = true; + AudioCache::FileFormat fileFormat = AudioCache::FileFormat::UNKNOWN; if (_stricmp(ext, ".ogg") == 0){ - audioCache->_fileFormat = AudioCache::FileFormat::OGG; - eraseCache = false; + fileFormat = AudioCache::FileFormat::OGG; } else if (_stricmp(ext, ".mp3") == 0){ - audioCache->_fileFormat = AudioCache::FileFormat::MP3; + fileFormat = AudioCache::FileFormat::MP3; if (MPG123_LAZYINIT){ auto error = mpg123_init(); - if(error == MPG123_OK){ + if (error == MPG123_OK){ MPG123_LAZYINIT = false; - eraseCache = false; } else{ log("Basic setup goes wrong: %s", mpg123_plain_strerror(error)); + break; } } - else{ - eraseCache = false; - } } else{ log("unsupported media type:%s\n", ext); + break; } - - if (eraseCache){ - _audioCaches.erase(filePath); - return AudioEngine::INVALID_AUDIO_ID; - } + + audioCache = &_audioCaches[filePath]; + audioCache->_fileFormat = fileFormat; audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath); - _threadPool->addTask(std::bind(&AudioCache::readDataTask, audioCache)); + AudioEngine::addTask(std::bind(&AudioCache::readDataTask, audioCache)); + } while (false); + + return audioCache; +} + +int AudioEngineImpl::play2d(const std::string &filePath ,bool loop ,float volume) +{ + bool availableSourceExist = false; + ALuint alSource; + for (int i = 0; i < MAX_AUDIOINSTANCES; ++i) { + alSource = _alSources[i]; + if ( !_alSourceUsed[alSource]) { + availableSourceExist = true; + break; + } } - else { - audioCache = &it->second; + if(!availableSourceExist){ + return AudioEngine::INVALID_AUDIO_ID; + } + + AudioCache* audioCache = preload(filePath); + if (audioCache == nullptr) + { + return AudioEngine::INVALID_AUDIO_ID; } auto player = &_audioPlayers[_currentAudioID]; diff --git a/cocos/audio/win32/AudioEngine-win32.h b/cocos/audio/win32/AudioEngine-win32.h index 8103f3d02701..23aa2e2bba09 100644 --- a/cocos/audio/win32/AudioEngine-win32.h +++ b/cocos/audio/win32/AudioEngine-win32.h @@ -38,8 +38,6 @@ NS_CC_BEGIN namespace experimental{ #define MAX_AUDIOINSTANCES 32 -class AudioEngineThreadPool; - class CC_DLL AudioEngineImpl : public cocos2d::Ref { public: @@ -61,14 +59,13 @@ class CC_DLL AudioEngineImpl : public cocos2d::Ref void uncache(const std::string& filePath); void uncacheAll(); + AudioCache* preload(const std::string& filePath); void update(float dt); private: void _play2d(AudioCache *cache, int audioID); - AudioEngineThreadPool* _threadPool; - ALuint _alSources[MAX_AUDIOINSTANCES]; //source,used diff --git a/cocos/audio/winrt/AudioEngine-winrt.cpp b/cocos/audio/winrt/AudioEngine-winrt.cpp index 22a322171ec7..7ba1af2c0917 100644 --- a/cocos/audio/winrt/AudioEngine-winrt.cpp +++ b/cocos/audio/winrt/AudioEngine-winrt.cpp @@ -21,101 +21,13 @@ #if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT #include "AudioEngine-winrt.h" -#include - using namespace cocos2d; using namespace cocos2d::experimental; - -namespace cocos2d { - namespace experimental { - class AudioEngineThreadPool - { - public: - AudioEngineThreadPool() - : _running(true) - , _numThread(6) - { - _threads.reserve(_numThread); - _tasks.reserve(_numThread); - - for (int index = 0; index < _numThread; ++index) { - _tasks.push_back(nullptr); - _threads.push_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this, index))); - } - } - - void addTask(const std::function &task){ - _taskMutex.lock(); - int targetIndex = -1; - for (int index = 0; index < _numThread; ++index) { - if (_tasks[index] == nullptr) { - targetIndex = index; - _tasks[index] = task; - break; - } - } - if (targetIndex == -1) { - _tasks.push_back(task); - _threads.push_back(std::thread(std::bind(&AudioEngineThreadPool::threadFunc, this, _numThread))); - - _numThread++; - } - _taskMutex.unlock(); - _sleepCondition.notify_all(); - } - - void destroy() - { - _running = false; - _sleepCondition.notify_all(); - - for (int index = 0; index < _numThread; ++index) { - _threads[index].join(); - } - } - private: - bool _running; - std::vector _threads; - std::vector< std::function > _tasks; - - void threadFunc(int index) - { - while (_running) { - std::function task = nullptr; - _taskMutex.lock(); - task = _tasks[index]; - _taskMutex.unlock(); - - if (nullptr == task) - { - std::unique_lock lk(_sleepMutex); - _sleepCondition.wait(lk); - continue; - } - - task(); - - _taskMutex.lock(); - _tasks[index] = nullptr; - _taskMutex.unlock(); - } - } - - int _numThread; - - std::mutex _taskMutex; - std::mutex _sleepMutex; - std::condition_variable _sleepCondition; - }; - } -} - AudioEngineImpl::AudioEngineImpl() : _lazyInitLoop(true) , _currentAudioID(0) - , _threadPool(nullptr) { } @@ -123,64 +35,63 @@ AudioEngineImpl::AudioEngineImpl() AudioEngineImpl::~AudioEngineImpl() { _audioCaches.clear(); - - if (_threadPool) { - _threadPool->destroy(); - delete _threadPool; - } } bool AudioEngineImpl::init() { bool ret = false; - if (nullptr == _threadPool) { - _threadPool = new (std::nothrow) AudioEngineThreadPool(); - } - ret = true; return ret; } -int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume) +AudioCache* AudioEngineImpl::preload(const std::string& filePath) { AudioCache* audioCache = nullptr; - auto it = _audioCaches.find(filePath); - if (it == _audioCaches.end()) { - audioCache = &_audioCaches[filePath]; + do + { + auto it = _audioCaches.find(filePath); + if (it == _audioCaches.end()) { + FileFormat fileFormat = FileFormat::UNKNOWN; - auto ext = filePath.substr(filePath.rfind('.')); - transform(ext.begin(), ext.end(), ext.begin(), tolower); + auto ext = filePath.substr(filePath.rfind('.')); + transform(ext.begin(), ext.end(), ext.begin(), tolower); + + if (ext.compare(".wav") == 0){ + fileFormat = FileFormat::WAV; + } + else if (ext.compare(".ogg") == 0){ + fileFormat = FileFormat::OGG; + } + else if (ext.compare(".mp3") == 0){ + fileFormat = FileFormat::MP3; + } + else{ + log("unsupported media type:%s\n", ext.c_str()); + break; + } - bool eraseCache = true; + audioCache = &_audioCaches[filePath]; + audioCache->_fileFormat = fileFormat; - if (ext.compare(".wav") == 0){ - audioCache->_fileFormat = FileFormat::WAV; - eraseCache = false; - } - else if (ext.compare(".ogg") == 0){ - audioCache->_fileFormat = FileFormat::OGG; - eraseCache = false; + std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); + audioCache->_fileFullPath = fullPath; + AudioEngine::addTask(std::bind(&AudioCache::readDataTask, audioCache)); } - else if (ext.compare(".mp3") == 0){ - audioCache->_fileFormat = FileFormat::MP3; - eraseCache = false; - } - else{ - log("unsupported media type:%s\n", ext.c_str()); + else { + audioCache = &it->second; } + } while (false); - if (eraseCache){ - _audioCaches.erase(filePath); - return AudioEngine::INVALID_AUDIO_ID; - } + return audioCache; +} - std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filePath); - audioCache->_fileFullPath = fullPath; - _threadPool->addTask(std::bind(&AudioCache::readDataTask, audioCache)); - } - else { - audioCache = &it->second; +int AudioEngineImpl::play2d(const std::string &filePath, bool loop, float volume) +{ + auto audioCache = preload(filePath); + if (audioCache == nullptr) + { + return AudioEngine::INVALID_AUDIO_ID; } auto player = &_audioPlayers[_currentAudioID]; diff --git a/cocos/audio/winrt/AudioEngine-winrt.h b/cocos/audio/winrt/AudioEngine-winrt.h index 906ab7ff3105..97d84411dc06 100644 --- a/cocos/audio/winrt/AudioEngine-winrt.h +++ b/cocos/audio/winrt/AudioEngine-winrt.h @@ -35,9 +35,6 @@ NS_CC_BEGIN namespace experimental{ #define MAX_AUDIOINSTANCES 32 - - class AudioEngineThreadPool; - class CC_DLL AudioEngineImpl : public cocos2d::Ref { public: @@ -58,6 +55,7 @@ NS_CC_BEGIN void setFinishCallback(int audioID, const std::function &callback); void uncache(const std::string& filePath); void uncacheAll(); + AudioCache* preload(const std::string& filePath); void update(float dt); private: @@ -72,7 +70,6 @@ NS_CC_BEGIN std::vector _toRemoveAudioIDs; bool _lazyInitLoop; int _currentAudioID; - AudioEngineThreadPool* _threadPool; }; } diff --git a/cocos/base/CCConfiguration.cpp b/cocos/base/CCConfiguration.cpp index 0667ccc8d745..8ade3f0c554d 100644 --- a/cocos/base/CCConfiguration.cpp +++ b/cocos/base/CCConfiguration.cpp @@ -50,7 +50,7 @@ Configuration::Configuration() , _maxDirLightInShader(1) , _maxPointLightInShader(1) , _maxSpotLightInShader(1) -, _animate3DQuality(Animate3DQuality::QUALITY_HIGH) +, _animate3DQuality(Animate3DQuality::QUALITY_LOW) { } diff --git a/cocos/base/CCConsole.cpp b/cocos/base/CCConsole.cpp index aa306ce6bce9..9433a377141e 100644 --- a/cocos/base/CCConsole.cpp +++ b/cocos/base/CCConsole.cpp @@ -123,12 +123,12 @@ static bool isFloat( std::string myString ) { static ssize_t mydprintf(int sock, const char *format, ...) { va_list args; - char buf[16386]; + char buf[16386]; - va_start(args, format); - vsnprintf(buf, sizeof(buf), format, args); - va_end(args); - return send(sock, buf, strlen(buf),0); + va_start(args, format); + vsnprintf(buf, sizeof(buf), format, args); + va_end(args); + return send(sock, buf, strlen(buf),0); } static void sendPrompt(int fd) @@ -235,20 +235,53 @@ void SendLogToWindow(const char *log) static void _log(const char *format, va_list args) { - char buf[MAX_LOG_LENGTH]; + int bufferSize = MAX_LOG_LENGTH; + char* buf = nullptr; + + do + { + buf = new (std::nothrow) char[bufferSize]; + if (buf == nullptr) + return; // not enough memory + + int ret = vsnprintf(buf, bufferSize - 3, format, args); + if (ret < 0) + { + bufferSize *= 2; + + delete [] buf; + } + else + break; + + } while (true); - 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); + __android_log_print(ANDROID_LOG_DEBUG, "cocos2d-x debug info", "%s", buf); #elif CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT - WCHAR wszBuf[MAX_LOG_LENGTH] = {0}; - MultiByteToWideChar(CP_UTF8, 0, buf, -1, wszBuf, sizeof(wszBuf)); - OutputDebugStringW(wszBuf); - WideCharToMultiByte(CP_ACP, 0, wszBuf, -1, buf, sizeof(buf), nullptr, FALSE); - printf("%s", buf); + + int pos = 0; + int len = strlen(buf); + char tempBuf[MAX_LOG_LENGTH + 1] = { 0 }; + WCHAR wszBuf[MAX_LOG_LENGTH + 1] = { 0 }; + + do + { + std::copy(buf + pos, buf + pos + MAX_LOG_LENGTH, tempBuf); + + tempBuf[MAX_LOG_LENGTH] = 0; + + MultiByteToWideChar(CP_UTF8, 0, tempBuf, -1, wszBuf, sizeof(wszBuf)); + OutputDebugStringW(wszBuf); + WideCharToMultiByte(CP_ACP, 0, wszBuf, -1, tempBuf, sizeof(tempBuf), nullptr, FALSE); + printf("%s", tempBuf); + + pos += MAX_LOG_LENGTH; + + } while (pos < len); SendLogToWindow(buf); fflush(stdout); #else @@ -258,7 +291,7 @@ static void _log(const char *format, va_list args) #endif Director::getInstance()->getConsole()->log(buf); - + delete [] buf; } // FIXME: Deprecated @@ -290,7 +323,7 @@ Console::Console() , _bindAddress("") { // VS2012 doesn't support initializer list, so we create a new array and assign its elements to '_command'. - Command commands[] = { + Command commands[] = { { "allocator", "Display allocator diagnostics for all allocators", std::bind(&Console::commandAllocator, this, std::placeholders::_1, std::placeholders::_2) }, { "config", "Print the Configuration object", std::bind(&Console::commandConfig, this, std::placeholders::_1, std::placeholders::_2) }, { "debugmsg", "Whether or not to forward the debug messages on the console. Args: [on | off]", [&](int fd, const std::string& args) { @@ -326,10 +359,10 @@ Console::Console() }; ; - for (int i = 0; i < sizeof(commands)/sizeof(commands[0]); ++i) - { - _commands[commands[i].name] = commands[i]; - } + for (int i = 0; i < sizeof(commands)/sizeof(commands[0]); ++i) + { + _commands[commands[i].name] = commands[i]; + } } Console::~Console() @@ -1190,7 +1223,7 @@ void Console::loop() #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) closesocket(_listenfd); - WSACleanup(); + WSACleanup(); #else close(_listenfd); #endif diff --git a/cocos/base/CCEventDispatcher.cpp b/cocos/base/CCEventDispatcher.cpp index 914a8d34d6c2..8b5428d4af3d 100644 --- a/cocos/base/CCEventDispatcher.cpp +++ b/cocos/base/CCEventDispatcher.cpp @@ -1027,7 +1027,8 @@ void EventDispatcher::dispatchTouchEvent(EventTouch* event) return true; } - CCASSERT((*touchesIter)->getID() == (*mutableTouchesIter)->getID(), ""); + CCASSERT((*touchesIter)->getID() == (*mutableTouchesIter)->getID(), + "touchesIter ID should be equal to mutableTouchesIter's ID."); if (isClaimed && listener->_isRegistered && listener->_needSwallow) { diff --git a/cocos/base/CCEventListenerAcceleration.cpp b/cocos/base/CCEventListenerAcceleration.cpp index 099919be9752..4bcdb6ce0843 100644 --- a/cocos/base/CCEventListenerAcceleration.cpp +++ b/cocos/base/CCEventListenerAcceleration.cpp @@ -89,7 +89,7 @@ EventListenerAcceleration* EventListenerAcceleration::clone() bool EventListenerAcceleration::checkAvailable() { - CCASSERT(onAccelerationEvent, ""); + CCASSERT(onAccelerationEvent, "onAccelerationEvent can't be nullptr!"); return true; } diff --git a/cocos/base/CCScheduler.cpp b/cocos/base/CCScheduler.cpp index 8ed57ecab65b..63fb852354b6 100644 --- a/cocos/base/CCScheduler.cpp +++ b/cocos/base/CCScheduler.cpp @@ -300,7 +300,7 @@ void Scheduler::schedule(const ccSchedulerFunc& callback, void *target, float in } else { - CCASSERT(element->paused == paused, ""); + CCASSERT(element->paused == paused, "element's paused should be paused!"); } if (element->timers == nullptr) @@ -694,7 +694,7 @@ void Scheduler::unscheduleScriptEntry(unsigned int scheduleScriptEntryID) void Scheduler::resumeTarget(void *target) { - CCASSERT(target != nullptr, ""); + CCASSERT(target != nullptr, "target can't be nullptr!"); // custom selectors tHashTimerEntry *element = nullptr; @@ -709,14 +709,14 @@ void Scheduler::resumeTarget(void *target) HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate); if (elementUpdate) { - CCASSERT(elementUpdate->entry != nullptr, ""); + CCASSERT(elementUpdate->entry != nullptr, "elementUpdate's entry can't be nullptr!"); elementUpdate->entry->paused = false; } } void Scheduler::pauseTarget(void *target) { - CCASSERT(target != nullptr, ""); + CCASSERT(target != nullptr, "target can't be nullptr!"); // custom selectors tHashTimerEntry *element = nullptr; @@ -731,7 +731,7 @@ void Scheduler::pauseTarget(void *target) HASH_FIND_PTR(_hashForUpdates, &target, elementUpdate); if (elementUpdate) { - CCASSERT(elementUpdate->entry != nullptr, ""); + CCASSERT(elementUpdate->entry != nullptr, "elementUpdate's entry can't be nullptr!"); elementUpdate->entry->paused = true; } } @@ -1001,7 +1001,7 @@ void Scheduler::schedule(SEL_SCHEDULE selector, Ref *target, float interval, uns } else { - CCASSERT(element->paused == paused, ""); + CCASSERT(element->paused == paused, "element's paused should be paused."); } if (element->timers == nullptr) diff --git a/cocos/base/ZipUtils.cpp b/cocos/base/ZipUtils.cpp index 2110643d415c..30ac76fd9421 100644 --- a/cocos/base/ZipUtils.cpp +++ b/cocos/base/ZipUtils.cpp @@ -252,8 +252,8 @@ int ZipUtils::inflateGZipFile(const char *path, unsigned char **out) int len; unsigned int offset = 0; - CCASSERT(out, ""); - CCASSERT(&*out, ""); + CCASSERT(out, "out can't be nullptr."); + CCASSERT(&*out, "&*out can't be nullptr."); gzFile inFile = gzopen(path, "rb"); if( inFile == nullptr ) { diff --git a/cocos/editor-support/cocosbuilder/CCBReader.cpp b/cocos/editor-support/cocosbuilder/CCBReader.cpp index c0a408bb2005..6b7d9c8f8af3 100644 --- a/cocos/editor-support/cocosbuilder/CCBReader.cpp +++ b/cocos/editor-support/cocosbuilder/CCBReader.cpp @@ -128,7 +128,7 @@ CCBReader::~CCBReader() void CCBReader::setCCBRootPath(const char* ccbRootPath) { - CCASSERT(ccbRootPath != nullptr, ""); + CCASSERT(ccbRootPath != nullptr, "ccbRootPath can't be nullptr!"); _CCBRootPath = ccbRootPath; } diff --git a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp index 071f3e3e681f..d1febae81660 100644 --- a/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp +++ b/cocos/editor-support/cocosbuilder/CCNodeLoader.cpp @@ -99,11 +99,11 @@ void NodeLoader::parseProperties(Node * pNode, Node * pParent, CCBReader * ccbRe __Array *extraPropsNames = static_cast<__Array*>(pNode->getUserObject()); if (! extraPropsNames) { - extraPropsNames = Array::create(); + extraPropsNames = __Array::create(); pNode->setUserObject(extraPropsNames); } - extraPropsNames->addObject(String::create(propertyName)); + extraPropsNames->addObject(__String::create(propertyName)); } switch(type) @@ -968,7 +968,8 @@ Node * NodeLoader::parsePropTypeCCBFile(Node * pNode, Node * pParent, CCBReader auto& ownerCallbackNodes = reader->getOwnerCallbackNodes(); if (!ownerCallbackNames.empty() && !ownerCallbackNodes.empty()) { - CCASSERT(ownerCallbackNames.size() == ownerCallbackNodes.size(), ""); + CCASSERT(ownerCallbackNames.size() == ownerCallbackNodes.size(), + "ownerCallbackNames size should equal to ownerCallbackNodes size."); ssize_t nCount = ownerCallbackNames.size(); for (ssize_t i = 0 ; i < nCount; i++) @@ -982,7 +983,8 @@ Node * NodeLoader::parsePropTypeCCBFile(Node * pNode, Node * pParent, CCBReader auto ownerOutletNodes = reader->getOwnerOutletNodes(); if (!ownerOutletNames.empty() && !ownerOutletNodes.empty()) { - CCASSERT(ownerOutletNames.size() == ownerOutletNodes.size(), ""); + CCASSERT(ownerOutletNames.size() == ownerOutletNodes.size(), + "ownerOutletNames size should be equal to ownerOutletNodes's size."); ssize_t nCount = ownerOutletNames.size(); for (ssize_t i = 0 ; i < nCount; i++) diff --git a/cocos/editor-support/cocostudio/ActionTimeline/CSLoader.cpp b/cocos/editor-support/cocostudio/ActionTimeline/CSLoader.cpp index 11b19c115dc6..bc25b17887c3 100644 --- a/cocos/editor-support/cocostudio/ActionTimeline/CSLoader.cpp +++ b/cocos/editor-support/cocostudio/ActionTimeline/CSLoader.cpp @@ -611,7 +611,7 @@ Node* CSLoader::loadSprite(const rapidjson::Value& json) if(!sprite) { - sprite = CCSprite::create(); + sprite = Sprite::create(); CCLOG("filePath is empty. Create a sprite with no texture"); } } @@ -844,7 +844,7 @@ Node* CSLoader::nodeWithFlatBuffersFile(const std::string &fileName, const ccNod if (csBuildId) { CCASSERT(strcmp(_csBuildID.c_str(), csBuildId->c_str()) == 0, - String::createWithFormat("%s%s%s%s%s%s%s%s%s%s", + StringUtils::format("%s%s%s%s%s%s%s%s%s%s", "The reader build id of your Cocos exported file(", csBuildId->c_str(), ") and the reader build id in your Cocos2d-x(", @@ -854,7 +854,7 @@ Node* CSLoader::nodeWithFlatBuffersFile(const std::string &fileName, const ccNod csBuildId->c_str(), ")from ", "http://www.cocos2d-x.org/filedown/cocos-reader", - " and replace it in your Cocos2d-x")->getCString()); + " and replace it in your Cocos2d-x").c_str()); } // decode plist diff --git a/cocos/editor-support/cocostudio/CCArmature.cpp b/cocos/editor-support/cocostudio/CCArmature.cpp index c0b9cf485345..396f7bf30a0d 100644 --- a/cocos/editor-support/cocostudio/CCArmature.cpp +++ b/cocos/editor-support/cocostudio/CCArmature.cpp @@ -137,7 +137,7 @@ bool Armature::init(const std::string& name) ArmatureData *armatureData = armatureDataManager->getArmatureData(name); - CCASSERT(armatureData, ""); + CCASSERT(armatureData, "armatureData doesn't exists!"); _armatureData = armatureData; diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index 1843c6450e49..b2945725499b 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -246,7 +246,7 @@ void DisplayManager::changeDisplayWithIndex(int index, bool force) setCurrentDecorativeDisplay(decoDisplay); } -void CCDisplayManager::changeDisplayWithName(const std::string& name, bool force) +void DisplayManager::changeDisplayWithName(const std::string& name, bool force) { for (int i = 0; i<_decoDisplayList.size(); i++) { diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index 34cc2ee17a9e..e7701289f8d1 100644 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -493,7 +493,7 @@ Widget* WidgetPropertiesReader0250::createWidget(const rapidjson::Value& data, c const char* file = DICTOOL->getStringValueFromArray_json(data, "textures", i); std::string tp = fullPath; tp.append(file); - CCSpriteFrameCache::getInstance()->addSpriteFramesWithFile(tp.c_str()); + SpriteFrameCache::getInstance()->addSpriteFramesWithFile(tp.c_str()); } float fileDesignWidth = DICTOOL->getFloatValue_json(data, "designWidth"); float fileDesignHeight = DICTOOL->getFloatValue_json(data, "designHeight"); @@ -713,7 +713,7 @@ void WidgetPropertiesReader0250::setPropsForButtonFromJsonDictionary(Widget*widg if (useMergedTexture) { - button->loadTextures(normalFileName, pressedFileName, disabledFileName,TextureResType::PLIST); + button->loadTextures(normalFileName, pressedFileName, disabledFileName,Widget::TextureResType::PLIST); } else { @@ -733,7 +733,7 @@ void WidgetPropertiesReader0250::setPropsForButtonFromJsonDictionary(Widget*widg { if (useMergedTexture) { - button->loadTextures(normalFileName, pressedFileName, disabledFileName,TextureResType::PLIST); + button->loadTextures(normalFileName, pressedFileName, disabledFileName,Widget::TextureResType::PLIST); } else { @@ -794,7 +794,7 @@ void WidgetPropertiesReader0250::setPropsForCheckBoxFromJsonDictionary(Widget*wi if (useMergedTexture) { - checkBox->loadTextures(backGroundFileName, backGroundSelectedFileName, frontCrossFileName,backGroundDisabledFileName,frontCrossDisabledFileName,TextureResType::PLIST); + checkBox->loadTextures(backGroundFileName, backGroundSelectedFileName, frontCrossFileName,backGroundDisabledFileName,frontCrossDisabledFileName,Widget::TextureResType::PLIST); } else { @@ -829,7 +829,7 @@ void WidgetPropertiesReader0250::setPropsForImageViewFromJsonDictionary(Widget*w { if (useMergedTexture) { - imageView->loadTexture(imageFileName,TextureResType::PLIST); + imageView->loadTexture(imageFileName,Widget::TextureResType::PLIST); } else { @@ -856,7 +856,7 @@ void WidgetPropertiesReader0250::setPropsForImageViewFromJsonDictionary(Widget*w { if (useMergedTexture) { - imageView->loadTexture(imageFileName,TextureResType::PLIST); + imageView->loadTexture(imageFileName,Widget::TextureResType::PLIST); } else { @@ -974,7 +974,7 @@ void WidgetPropertiesReader0250::setPropsForLayoutFromJsonDictionary(Widget*widg float ch = DICTOOL->getFloatValue_json(options, "capInsetsHeight"); if (useMergedTexture) { - panel->setBackGroundImage(imageFileName,TextureResType::PLIST); + panel->setBackGroundImage(imageFileName,Widget::TextureResType::PLIST); } else { @@ -987,7 +987,7 @@ void WidgetPropertiesReader0250::setPropsForLayoutFromJsonDictionary(Widget*widg if (useMergedTexture) { - panel->setBackGroundImage(imageFileName,TextureResType::PLIST); + panel->setBackGroundImage(imageFileName,Widget::TextureResType::PLIST); } else { @@ -1029,7 +1029,7 @@ void WidgetPropertiesReader0250::setPropsForSliderFromJsonDictionary(Widget*widg const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr; if (useMergedTexture) { - slider->loadBarTexture(imageFileName,TextureResType::PLIST); + slider->loadBarTexture(imageFileName,Widget::TextureResType::PLIST); } else { @@ -1044,7 +1044,7 @@ void WidgetPropertiesReader0250::setPropsForSliderFromJsonDictionary(Widget*widg const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr; if (useMergedTexture) { - slider->loadBarTexture(imageFileName,TextureResType::PLIST); + slider->loadBarTexture(imageFileName,Widget::TextureResType::PLIST); } else { @@ -1065,7 +1065,7 @@ void WidgetPropertiesReader0250::setPropsForSliderFromJsonDictionary(Widget*widg const char* disabledFileName_tp = (disabledFileName && (strcmp(disabledFileName, "") != 0))?tp_d.append(disabledFileName).c_str():nullptr; if (useMergedTexture) { - slider->loadSlidBallTextures(normalFileName,pressedFileName,disabledFileName,TextureResType::PLIST); + slider->loadSlidBallTextures(normalFileName,pressedFileName,disabledFileName,Widget::TextureResType::PLIST); } else { @@ -1078,7 +1078,7 @@ void WidgetPropertiesReader0250::setPropsForSliderFromJsonDictionary(Widget*widg const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr; if (useMergedTexture) { - slider->loadProgressBarTexture(imageFileName, TextureResType::PLIST); + slider->loadProgressBarTexture(imageFileName, Widget::TextureResType::PLIST); } else { @@ -1147,7 +1147,7 @@ void WidgetPropertiesReader0250::setPropsForLoadingBarFromJsonDictionary(Widget const char* imageFileName_tp = (imageFileName && (strcmp(imageFileName, "") != 0))?tp_b.append(imageFileName).c_str():nullptr; if (useMergedTexture) { - loadingBar->loadTexture(imageFileName,TextureResType::PLIST); + loadingBar->loadTexture(imageFileName,Widget::TextureResType::PLIST); } else { diff --git a/cocos/editor-support/cocostudio/CCSSceneReader.cpp b/cocos/editor-support/cocostudio/CCSSceneReader.cpp index 593eaeba32ac..66c92706a6bf 100644 --- a/cocos/editor-support/cocostudio/CCSSceneReader.cpp +++ b/cocos/editor-support/cocostudio/CCSSceneReader.cpp @@ -79,7 +79,7 @@ cocos2d::Node* SceneReader::createNodeWithSceneFile(const std::string &fileName, else if(file_extension == ".CSB") { do { - std::string binaryFilePath = CCFileUtils::getInstance()->fullPathForFilename(fileName); + std::string binaryFilePath = FileUtils::getInstance()->fullPathForFilename(fileName); auto fileData = FileUtils::getInstance()->getDataFromFile(binaryFilePath); auto fileDataBytes = fileData.getBytes(); CC_BREAK_IF(fileData.isNull()); @@ -429,7 +429,7 @@ cocos2d::Node* SceneReader::createObject(CocoLoader *cocoLoader, stExpCocoNode * { if (pRender == nullptr || attachComponent == AttachComponentType::EMPTY_NODE) { - gb = CCNode::create(); + gb = Node::create(); if (pRender != nullptr) { _vecComs.push_back(pRender); diff --git a/cocos/editor-support/cocostudio/TriggerObj.cpp b/cocos/editor-support/cocostudio/TriggerObj.cpp index f2316466d0ae..018c4b468c03 100755 --- a/cocos/editor-support/cocostudio/TriggerObj.cpp +++ b/cocos/editor-support/cocostudio/TriggerObj.cpp @@ -185,10 +185,10 @@ void TriggerObj::serialize(const rapidjson::Value &val) if(con == nullptr) { CCLOG("class %s can not be implemented!", classname); - CCASSERT(con != nullptr, ""); + CCASSERT(con != nullptr, "con can't be nullptr!"); } - CCASSERT(con != nullptr, ""); + CCASSERT(con != nullptr, "con can't be nullptr!"); con->serialize(subDict); con->init(); _cons.pushBack(con); @@ -207,7 +207,7 @@ void TriggerObj::serialize(const rapidjson::Value &val) if(act == nullptr) { CCLOG("class %s can not be implemented!", classname); - CCASSERT(act != nullptr, ""); + CCASSERT(act != nullptr, "act can't be nullptr!"); } act->serialize(subDict); act->init(); diff --git a/cocos/editor-support/cocostudio/WidgetReader/GameMapReader/GameMapReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/GameMapReader/GameMapReader.cpp index 903bba18119c..476fa9b59e85 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/GameMapReader/GameMapReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/GameMapReader/GameMapReader.cpp @@ -238,15 +238,12 @@ namespace cocostudio setPropsWithFlatBuffers(tmx, (Table*)gameMapOptions); } } - //else - //{ - // Node* node = Node::create(); - // setPropsWithFlatBuffers(node, (Table*)gameMapOptions); - // auto label = Label::create(); - // label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); - // node->addChild(label); - // return node; - //} + else + { + Node* node = Node::create(); + setPropsWithFlatBuffers(node, (Table*)gameMapOptions); + return node; + } return tmx; } diff --git a/cocos/editor-support/cocostudio/WidgetReader/ParticleReader/ParticleReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/ParticleReader/ParticleReader.cpp index 51f4f79e25b5..9e27769f0dd1 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/ParticleReader/ParticleReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/ParticleReader/ParticleReader.cpp @@ -153,11 +153,11 @@ namespace cocostudio void ParticleReader::setPropsWithFlatBuffers(cocos2d::Node *node, const flatbuffers::Table *particleOptions) { - auto particle = static_cast(node); + auto particle = dynamic_cast(node); auto options = (ParticleSystemOptions*)particleOptions; auto f_blendFunc = options->blendFunc(); - if (f_blendFunc) + if (particle && f_blendFunc) { cocos2d::BlendFunc blendFunc = cocos2d::BlendFunc::ALPHA_PREMULTIPLIED; blendFunc.src = f_blendFunc->src(); @@ -208,15 +208,12 @@ namespace cocostudio particle->setPositionType(ParticleSystem::PositionType::GROUPED); } } - //else - //{ - // Node* node = Node::create(); - // setPropsWithFlatBuffers(node, (Table*)particleOptions); - // auto label = Label::create(); - // label->setString(__String::createWithFormat("%s missed", errorFilePath.c_str())->getCString()); - // node->addChild(label); - // return node; - //} + else + { + Node* node = Node::create(); + setPropsWithFlatBuffers(node, (Table*)particleOptions); + return node; + } return particle; } diff --git a/cocos/editor-support/cocostudio/WidgetReader/SliderReader/SliderReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/SliderReader/SliderReader.cpp index 4ca33378ceac..18db60f41030 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/SliderReader/SliderReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/SliderReader/SliderReader.cpp @@ -466,7 +466,7 @@ namespace cocostudio auto options = (SliderOptions*)sliderOptions; int percent = options->percent(); - slider->setPercent(percent); + //slider->setPercent(percent); bool imageFileExist = false; std::string imageErrorFilePath = ""; @@ -798,7 +798,7 @@ namespace cocostudio auto widgetReader = WidgetReader::getInstance(); widgetReader->setPropsWithFlatBuffers(node, (Table*)options->widgetOptions()); - + slider->setPercent(percent); } Node* SliderReader::createNodeWithFlatBuffers(const flatbuffers::Table *sliderOptions) diff --git a/cocos/editor-support/cocostudio/WidgetReader/UserCameraReader/UserCameraReader.cpp b/cocos/editor-support/cocostudio/WidgetReader/UserCameraReader/UserCameraReader.cpp index 6f3fa906e4de..f05bd905f378 100644 --- a/cocos/editor-support/cocostudio/WidgetReader/UserCameraReader/UserCameraReader.cpp +++ b/cocos/editor-support/cocostudio/WidgetReader/UserCameraReader/UserCameraReader.cpp @@ -125,6 +125,7 @@ namespace cocostudio else if(value == "USER1") cameraFlag = 1 << 1; else if(value == "USER2") cameraFlag = 1 << 2; else if(value == "USER3") cameraFlag = 1 << 3; + else if(value == "USER4") cameraFlag = 1 << 4; } attribute = attribute->Next(); diff --git a/cocos/editor-support/spine/SkeletonRenderer.h b/cocos/editor-support/spine/SkeletonRenderer.h index 7d6055d7bbc7..e39cd9b26687 100644 --- a/cocos/editor-support/spine/SkeletonRenderer.h +++ b/cocos/editor-support/spine/SkeletonRenderer.h @@ -91,10 +91,10 @@ class SkeletonRenderer: public cocos2d::Node, public cocos2d::BlendProtocol { bool setAttachment (const std::string& slotName, const char* attachmentName); // --- BlendProtocol - virtual void setBlendFunc (const cocos2d::BlendFunc& blendFunc); - virtual const cocos2d::BlendFunc& getBlendFunc () const; - virtual void setOpacityModifyRGB (bool value); - virtual bool isOpacityModifyRGB () const; + virtual void setBlendFunc (const cocos2d::BlendFunc& blendFunc)override; + virtual const cocos2d::BlendFunc& getBlendFunc () const override; + virtual void setOpacityModifyRGB (bool value)override; + virtual bool isOpacityModifyRGB () const override; CC_CONSTRUCTOR_ACCESS: SkeletonRenderer (); diff --git a/cocos/navmesh/CCNavMeshDebugDraw.h b/cocos/navmesh/CCNavMeshDebugDraw.h index 528737806dd0..cf116d2778d1 100644 --- a/cocos/navmesh/CCNavMeshDebugDraw.h +++ b/cocos/navmesh/CCNavMeshDebugDraw.h @@ -49,8 +49,8 @@ class NavMeshDebugDraw : public duDebugDraw NavMeshDebugDraw(); virtual ~NavMeshDebugDraw(); - virtual void depthMask(bool state); - virtual void texture(bool state){}; + virtual void depthMask(bool state)override; + virtual void texture(bool state)override{}; virtual void begin(duDebugDrawPrimitives prim, float size = 1.0f) override; virtual void vertex(const float* pos, unsigned int color) override; diff --git a/cocos/platform/CCFileUtils.cpp b/cocos/platform/CCFileUtils.cpp index f3e2f1dbc179..29aa9953989b 100644 --- a/cocos/platform/CCFileUtils.cpp +++ b/cocos/platform/CCFileUtils.cpp @@ -41,24 +41,12 @@ THE SOFTWARE. #endif #include -#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 || CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) -#include -#endif - -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -#include -#endif +NS_CC_BEGIN -#if (CC_TARGET_PLATFORM != CC_PLATFORM_WIN32) && (CC_TARGET_PLATFORM != CC_PLATFORM_WINRT) -#include -#include -#include -#endif +// Implement DictMaker #if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC) -NS_CC_BEGIN - typedef enum { SAX_NONE = 0, @@ -540,7 +528,6 @@ static tinyxml2::XMLElement* generateElementForArray(const ValueVector& array, t } #else -NS_CC_BEGIN /* The subclass FileUtilsApple should override these two method. */ ValueMap FileUtils::getValueMapFromFile(const std::string& filename) {return ValueMap();} @@ -550,6 +537,7 @@ bool FileUtils::writeToFile(ValueMap& dict, const std::string &fullPath) {return #endif /* (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_MAC) */ +// Implement FileUtils FileUtils* FileUtils::s_sharedFileUtils = nullptr; void FileUtils::destroyInstance() @@ -584,7 +572,6 @@ bool FileUtils::writeStringToFile(std::string dataStr, const std::string& fullPa bool FileUtils::writeDataToFile(Data retData, const std::string& fullPath) { - unsigned char* buffer = nullptr; size_t size = 0; const char* mode = "wb"; @@ -1038,36 +1025,6 @@ bool FileUtils::isAbsolutePath(const std::string& path) const return (path[0] == '/'); } -bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const -{ -#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) - WIN32_FILE_ATTRIBUTE_DATA wfad; - std::wstring wdirPath(dirPath.begin(), dirPath.end()); - if (GetFileAttributesEx(wdirPath.c_str(), GetFileExInfoStandard, &wfad)) - { - return true; - } - return false; -#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) - unsigned long fAttrib = GetFileAttributesA(dirPath.c_str()); - if (fAttrib != INVALID_FILE_ATTRIBUTES && - (fAttrib & FILE_ATTRIBUTE_DIRECTORY)) - { - return true; - } - return false; -#else - struct stat st; - if (stat(dirPath.c_str(), &st) == 0) - { - return S_ISDIR(st.st_mode); - } - return false; -#endif - - -} - bool FileUtils::isDirectoryExist(const std::string& dirPath) const { CCASSERT(!dirPath.empty(), "Invalid path"); @@ -1098,7 +1055,60 @@ bool FileUtils::isDirectoryExist(const std::string& dirPath) const } } } + return false; +} + +#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) +// windows os implement should override in platform specific FileUtiles class +bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const +{ + CCASSERT(false, "FileUtils not support isDirectoryExistInternal"); + return false; +} + +bool FileUtils::createDirectory(const std::string& path) +{ + CCASSERT(false, "FileUtils not support createDirectory"); + return false; +} + +bool FileUtils::removeDirectory(const std::string& path) +{ + CCASSERT(false, "FileUtils not support removeDirectory"); + return false; +} + +bool FileUtils::removeFile(const std::string &path) +{ + CCASSERT(false, "FileUtils not support removeFile"); + return false; +} +bool FileUtils::renameFile(const std::string &path, const std::string &oldname, const std::string &name) +{ + CCASSERT(false, "FileUtils not support renameFile"); + return false; +} + +std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const +{ + CCASSERT(false, "getSuitableFOpen should be override by platform FileUtils"); + return filenameUtf8; +} + +#else +// default implements for unix like os +#include +#include +#include + +bool FileUtils::isDirectoryExistInternal(const std::string& dirPath) const +{ + struct stat st; + if (stat(dirPath.c_str(), &st) == 0) + { + return S_ISDIR(st.st_mode); + } return false; } @@ -1135,47 +1145,6 @@ bool FileUtils::createDirectory(const std::string& path) } } - -#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) - WIN32_FILE_ATTRIBUTE_DATA wfad; - std::wstring wpath(path.begin(), path.end()); - if (!(GetFileAttributesEx(wpath.c_str(), GetFileExInfoStandard, &wfad))) - { - subpath = ""; - for(unsigned int i = 0 ; i < dirs.size() ; ++i) - { - subpath += dirs[i]; - if (i > 0 && !isDirectoryExist(subpath)) - { - std::wstring wsubpath(subpath.begin(), subpath.end()); - BOOL ret = CreateDirectory(wsubpath.c_str(), NULL); - if (!ret && ERROR_ALREADY_EXISTS != GetLastError()) - { - return false; - } - } - } - } - return true; -#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) - if ((GetFileAttributesA(path.c_str())) == INVALID_FILE_ATTRIBUTES) - { - subpath = ""; - for (unsigned int i = 0; i < dirs.size(); ++i) - { - subpath += dirs[i]; - if (!isDirectoryExist(subpath)) - { - BOOL ret = CreateDirectoryA(subpath.c_str(), NULL); - if (!ret && ERROR_ALREADY_EXISTS != GetLastError()) - { - return false; - } - } - } - } - return true; -#else DIR *dir = NULL; // Create path recursively @@ -1204,22 +1173,8 @@ bool FileUtils::createDirectory(const std::string& path) } } return true; -#endif } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) -static int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) -{ - auto ret = remove(fpath); - if (ret) - { - log("Fail to remove: %s ",fpath); - } - - return ret; -} -#endif - bool FileUtils::removeDirectory(const std::string& path) { if (path.size() > 0 && path[path.size() - 1] != '/') @@ -1228,58 +1183,6 @@ bool FileUtils::removeDirectory(const std::string& path) return false; } - // Remove downloaded files - -#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) - std::wstring wpath = std::wstring(path.begin(), path.end()); - std::wstring files = wpath + L"*.*"; - WIN32_FIND_DATA wfd; - HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0); - bool ret=true; - if (search!=INVALID_HANDLE_VALUE) - { - BOOL find=true; - while (find) - { - //. .. - if(wfd.cFileName[0]!='.') - { - std::wstring temp = wpath + wfd.cFileName; - if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) - { - temp += '/'; - ret = ret && this->removeDirectory(std::string(temp.begin(), temp.end())); - } - else - { - SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL); - ret = ret && DeleteFile(temp.c_str()); - } - } - find = FindNextFile(search, &wfd); - } - FindClose(search); - } - if (ret && RemoveDirectory(wpath.c_str())) - { - return true; - } - return false; -#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) - std::string command = "cmd /c rd /s /q "; - // Path may include space. - command += "\"" + path + "\""; - - if (WinExec(command.c_str(), SW_HIDE) > 31) - return true; - else - return false; -#elif (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) - if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS)) - return false; - else - return true; -#else std::string command = "rm -r "; // Path may include space. command += "\"" + path + "\""; @@ -1287,44 +1190,15 @@ bool FileUtils::removeDirectory(const std::string& path) return true; else return false; -#endif } bool FileUtils::removeFile(const std::string &path) { - // Remove downloaded file - -#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) - std::wstring wpath(path.begin(), path.end()); - if (DeleteFile(wpath.c_str())) - { - return true; - } - return false; -#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) - std::string command = "cmd /c del /q "; - std::string win32path = path; - int len = win32path.length(); - for (int i = 0; i < len; ++i) - { - if (win32path[i] == '/') - { - win32path[i] = '\\'; - } - } - command += win32path; - - if (WinExec(command.c_str(), SW_HIDE) > 31) - return true; - else - return false; -#else if (remove(path.c_str())) { return false; } else { return true; } -#endif } bool FileUtils::renameFile(const std::string &path, const std::string &oldname, const std::string &name) @@ -1333,41 +1207,6 @@ bool FileUtils::renameFile(const std::string &path, const std::string &oldname, std::string oldPath = path + oldname; std::string newPath = path + name; - // Rename a file -#if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) - std::regex pat("\\/"); - std::string _old = std::regex_replace(oldPath, pat, "\\"); - std::string _new = std::regex_replace(newPath, pat, "\\"); - if (MoveFileEx(std::wstring(_old.begin(), _old.end()).c_str(), - std::wstring(_new.begin(), _new.end()).c_str(), - MOVEFILE_REPLACE_EXISTING & MOVEFILE_WRITE_THROUGH)) - { - return true; - } - return false; -#elif (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) - std::regex pat("\\/"); - std::string _old = std::regex_replace(oldPath, pat, "\\"); - std::string _new = std::regex_replace(newPath, pat, "\\"); - - if(FileUtils::getInstance()->isFileExist(_new)) - { - if (!DeleteFileA(_new.c_str())) - { - CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newPath.c_str(), GetLastError()); - } - } - - if (MoveFileA(_old.c_str(), _new.c_str())) - { - return true; - } - else - { - CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldPath.c_str(), newPath.c_str(), GetLastError()); - return false; - } -#else int errorCode = rename(oldPath.c_str(), newPath.c_str()); if (0 != errorCode) @@ -1376,9 +1215,15 @@ bool FileUtils::renameFile(const std::string &path, const std::string &oldname, return false; } return true; -#endif } +std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const +{ + return filenameUtf8; +} + +#endif + long FileUtils::getFileSize(const std::string &filepath) { CCASSERT(!filepath.empty(), "Invalid path"); @@ -1422,68 +1267,5 @@ bool FileUtils::isPopupNotify() const return s_popupNotify; } -#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) -static std::wstring StringUtf8ToWideChar(const std::string& strUtf8) -{ - std::wstring ret; - if (!strUtf8.empty()) - { - int nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, nullptr, 0); - if (nNum) - { - WCHAR* wideCharString = new WCHAR[nNum + 1]; - wideCharString[0] = 0; - - nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, wideCharString, nNum + 1); - - ret = wideCharString; - delete[] wideCharString; - } - else - { - CCLOG("Wrong convert to WideChar code:0x%x", GetLastError()); - } - } - return ret; -} - -static std::string UTF8StringToMultiByte(const std::string& strUtf8) -{ - std::string ret; - if (!strUtf8.empty()) - { - std::wstring strWideChar = StringUtf8ToWideChar(strUtf8); - int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE); - if (nNum) - { - char* ansiString = new char[nNum + 1]; - ansiString[0] = 0; - - nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, ansiString, nNum + 1, nullptr, FALSE); - - ret = ansiString; - delete[] ansiString; - } - else - { - CCLOG("Wrong convert to Ansi code:0x%x", GetLastError()); - } - } - - return ret; -} - -std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const -{ - return UTF8StringToMultiByte(filenameUtf8); -} -#else -std::string FileUtils::getSuitableFOpen(const std::string& filenameUtf8) const -{ - return filenameUtf8; -} - -#endif - NS_CC_END diff --git a/cocos/platform/android/CCApplication-android.cpp b/cocos/platform/android/CCApplication-android.cpp index 1b5b5c8829a0..8d802a18147d 100644 --- a/cocos/platform/android/CCApplication-android.cpp +++ b/cocos/platform/android/CCApplication-android.cpp @@ -77,7 +77,7 @@ void Application::setAnimationInterval(float interval) { JniMethodInfo methodInfo; if (! JniHelper::getStaticMethodInfo(methodInfo, "org/cocos2dx/lib/Cocos2dxRenderer", "setAnimationInterval", - "(D)V")) + "(F)V")) { CCLOG("%s %d: error to get methodInfo", __FILE__, __LINE__); } diff --git a/cocos/platform/android/CCFileUtils-android.cpp b/cocos/platform/android/CCFileUtils-android.cpp index 265380f3f268..ba78367fc37a 100644 --- a/cocos/platform/android/CCFileUtils-android.cpp +++ b/cocos/platform/android/CCFileUtils-android.cpp @@ -33,6 +33,7 @@ THE SOFTWARE. #include "android/asset_manager_jni.h" #include "jni/CocosPlayClient.h" #include +#include #define LOG_TAG "CCFileUtils-android.cpp" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__) @@ -187,6 +188,59 @@ bool FileUtilsAndroid::isFileExistInternal(const std::string& strFilePath) const return bFound; } +bool FileUtilsAndroid::isDirectoryExistInternal(const std::string& dirPath) const +{ + if (dirPath.empty()) + { + return false; + } + + const char* s = dirPath.c_str(); + bool startWithAssets = (dirPath.find("assets/") == 0); + int lenOfAssets = 7; + + std::string tmpStr; + if (cocosplay::isEnabled() && !cocosplay::isDemo()) + { + // redirect assets/*** path to cocosplay resource dir + tmpStr.append(_defaultResRootPath); + if ('/' != tmpStr[tmpStr.length() - 1]) + { + tmpStr += '/'; + } + tmpStr.append(s + lenOfAssets); + } + + // find absolute path in flash memory + if (s[0] == '/') + { + CCLOG("find in flash memory dirPath(%s)", s); + struct stat st; + if (stat(s, &st) == 0) + { + return S_ISDIR(st.st_mode); + } + } + + // find it in apk's assets dir + // Found "assets/" at the beginning of the path and we don't want it + CCLOG("find in apk dirPath(%s)", s); + if (startWithAssets) + { + s += lenOfAssets; + } + if (FileUtilsAndroid::assetmanager) + { + AAssetDir* aa = AAssetManager_openDir(FileUtilsAndroid::assetmanager, s); + if (aa && AAssetDir_getNextFileName(aa)) + { + AAssetDir_close(aa); + return true; + } + } + return false; +} + bool FileUtilsAndroid::isAbsolutePath(const std::string& strPath) const { // On Android, there are two situations for full path. diff --git a/cocos/platform/android/CCFileUtils-android.h b/cocos/platform/android/CCFileUtils-android.h index 7f65d4aa8eed..edea6fbc47f9 100644 --- a/cocos/platform/android/CCFileUtils-android.h +++ b/cocos/platform/android/CCFileUtils-android.h @@ -81,7 +81,8 @@ class CC_DLL FileUtilsAndroid : public FileUtils virtual bool isAbsolutePath(const std::string& strPath) const; private: - virtual bool isFileExistInternal(const std::string& strFilePath) const; + virtual bool isFileExistInternal(const std::string& strFilePath) const override; + virtual bool isDirectoryExistInternal(const std::string& dirPath) const override; Data getData(const std::string& filename, bool forString); static AAssetManager* assetmanager; diff --git a/cocos/platform/android/ControllerManualAdapter/libs/nibiru_lib.jar b/cocos/platform/android/ControllerManualAdapter/libs/nibiru_lib.jar new file mode 100644 index 000000000000..5b4dc2f919a2 Binary files /dev/null and b/cocos/platform/android/ControllerManualAdapter/libs/nibiru_lib.jar differ diff --git a/cocos/platform/android/ControllerManualAdapter/libs/nibiru_lib_2_1_8.jar b/cocos/platform/android/ControllerManualAdapter/libs/nibiru_lib_2_1_8.jar deleted file mode 100644 index 5aa738c2966c..000000000000 Binary files a/cocos/platform/android/ControllerManualAdapter/libs/nibiru_lib_2_1_8.jar and /dev/null differ diff --git a/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerActivity.java b/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerActivity.java index b5277517788c..ba58296795a0 100644 --- a/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerActivity.java +++ b/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerActivity.java @@ -36,271 +36,271 @@ of this software and associated documentation files (the "Software"), to deal import android.util.Log; public abstract class GameControllerActivity extends Cocos2dxActivity implements InputDeviceListener { - // =========================================================== - // Constants - // =========================================================== + // =========================================================== + // Constants + // =========================================================== - private final static String TAG = GameControllerActivity.class.getSimpleName(); + private final static String TAG = GameControllerActivity.class.getSimpleName(); - public static final int DRIVERTYPE_NIBIRU = 0; - public static final int DRIVERTYPE_MOGA = 1; - public static final int DRIVERTYPE_OUYA = 2; - public static final int DRIVERTYPE_STANDARD = 3; - public static final int DRIVERTYPE_UNKNOWN = 4; - - // =========================================================== - // Fields - // =========================================================== - private static GameControllerActivity sGameControllerActivity; - private InputManagerCompat mInputManager = null; - - protected GameControllerHelper mControllerHelper = null; - - protected GameControllerDelegate mControllerNibiru = null; - protected GameControllerDelegate mControllerMoga = null; - protected GameControllerDelegate mControllerOuya = null; - - public void connectController(int driveType){ - try { - - ClassLoader loader = sGameControllerActivity.getClassLoader(); - Class controllerDelegate = null; - if (driveType == DRIVERTYPE_MOGA) { - if (mControllerMoga != null) { - return; - } - controllerDelegate = loader.loadClass("org.cocos2dx.lib.GameControllerMoga"); - } else if (driveType == DRIVERTYPE_NIBIRU) { - if (mControllerNibiru != null) { - mControllerNibiru.onCreate(sGameControllerActivity); - mControllerNibiru.onResume(); - return; - } - controllerDelegate = loader.loadClass("org.cocos2dx.lib.GameControllerNibiru"); - } else if (driveType == DRIVERTYPE_OUYA) { - if (mControllerOuya != null) { - return; - } - controllerDelegate = loader.loadClass("org.cocos2dx.lib.GameControllerOuya"); - } - - GameControllerDelegate instance = (GameControllerDelegate)controllerDelegate.newInstance(); - sGameControllerActivity.setGameControllerInstance(instance, driveType); - - if (driveType == DRIVERTYPE_NIBIRU) { - Method method = controllerDelegate.getDeclaredMethod("onResume"); - method.invoke(instance); - } - } - catch (Exception e) { - e.printStackTrace(); - } - } - - public void setGameControllerInstance(GameControllerDelegate controllerDelegate, int driveType) { - if (driveType == DRIVERTYPE_NIBIRU) { - mControllerNibiru = controllerDelegate; - }else if (driveType == DRIVERTYPE_MOGA) { - mControllerMoga = controllerDelegate; - } - else if (driveType == DRIVERTYPE_OUYA) { - mControllerOuya = controllerDelegate; - } - controllerDelegate.setControllerEventListener(mControllerEventListener); - controllerDelegate.onCreate(sGameControllerActivity); - } - - public GameControllerDelegate getGameControllerDelegate(int driveType){ - if (driveType == DRIVERTYPE_NIBIRU) { - return mControllerNibiru; - }else if (driveType == DRIVERTYPE_MOGA) { - return mControllerMoga; - } - else if (driveType == DRIVERTYPE_OUYA) { - return mControllerOuya; - } - - return null; - } - - ControllerEventListener mControllerEventListener = new ControllerEventListener() { - - @Override - public void onButtonEvent(String vendorName, int controller, int button, - boolean isPressed, float value, boolean isAnalog) { - GameControllerAdapter.onButtonEvent(vendorName, controller, button, isPressed, value, isAnalog); - } - - @Override - public void onAxisEvent(String vendorName, int controller, int axisID, - float value, boolean isAnalog) { - GameControllerAdapter.onAxisEvent(vendorName, controller, axisID, value, isAnalog); - } + public static final int DRIVERTYPE_NIBIRU = 0; + public static final int DRIVERTYPE_MOGA = 1; + public static final int DRIVERTYPE_OUYA = 2; + public static final int DRIVERTYPE_STANDARD = 3; + public static final int DRIVERTYPE_UNKNOWN = 4; + + // =========================================================== + // Fields + // =========================================================== + private static GameControllerActivity sGameControllerActivity; + private InputManagerCompat mInputManager = null; + + protected GameControllerHelper mControllerHelper = null; + + protected GameControllerDelegate mControllerNibiru = null; + protected GameControllerDelegate mControllerMoga = null; + protected GameControllerDelegate mControllerOuya = null; + + public void connectController(int driveType){ + try { + + ClassLoader loader = sGameControllerActivity.getClassLoader(); + Class controllerDelegate = null; + if (driveType == DRIVERTYPE_MOGA) { + if (mControllerMoga != null) { + return; + } + controllerDelegate = loader.loadClass("org.cocos2dx.lib.GameControllerMoga"); + } else if (driveType == DRIVERTYPE_NIBIRU) { + if (mControllerNibiru != null) { + mControllerNibiru.onCreate(sGameControllerActivity); + mControllerNibiru.onResume(); + return; + } + controllerDelegate = loader.loadClass("org.cocos2dx.lib.GameControllerNibiru"); + } else if (driveType == DRIVERTYPE_OUYA) { + if (mControllerOuya != null) { + return; + } + controllerDelegate = loader.loadClass("org.cocos2dx.lib.GameControllerOuya"); + } + + GameControllerDelegate instance = (GameControllerDelegate)controllerDelegate.newInstance(); + sGameControllerActivity.setGameControllerInstance(instance, driveType); + + if (driveType == DRIVERTYPE_NIBIRU) { + Method method = controllerDelegate.getDeclaredMethod("onResume"); + method.invoke(instance); + } + } + catch (Exception e) { + e.printStackTrace(); + } + } + + public void setGameControllerInstance(GameControllerDelegate controllerDelegate, int driveType) { + if (driveType == DRIVERTYPE_NIBIRU) { + mControllerNibiru = controllerDelegate; + }else if (driveType == DRIVERTYPE_MOGA) { + mControllerMoga = controllerDelegate; + } + else if (driveType == DRIVERTYPE_OUYA) { + mControllerOuya = controllerDelegate; + } + controllerDelegate.setControllerEventListener(mControllerEventListener); + controllerDelegate.onCreate(sGameControllerActivity); + } + + public GameControllerDelegate getGameControllerDelegate(int driveType){ + if (driveType == DRIVERTYPE_NIBIRU) { + return mControllerNibiru; + }else if (driveType == DRIVERTYPE_MOGA) { + return mControllerMoga; + } + else if (driveType == DRIVERTYPE_OUYA) { + return mControllerOuya; + } + + return null; + } + + ControllerEventListener mControllerEventListener = new ControllerEventListener() { + + @Override + public void onButtonEvent(String vendorName, int controller, int button, + boolean isPressed, float value, boolean isAnalog) { + GameControllerAdapter.onButtonEvent(vendorName, controller, button, isPressed, value, isAnalog); + } + + @Override + public void onAxisEvent(String vendorName, int controller, int axisID, + float value, boolean isAnalog) { + GameControllerAdapter.onAxisEvent(vendorName, controller, axisID, value, isAnalog); + } - @Override - public void onConnected(String vendorName, int controller) { - GameControllerAdapter.onConnected(vendorName, controller); - } + @Override + public void onConnected(String vendorName, int controller) { + GameControllerAdapter.onConnected(vendorName, controller); + } - @Override - public void onDisconnected(String vendorName, int controller) { - GameControllerAdapter.onDisconnected(vendorName, controller); - } - }; - - // =========================================================== - // Constructors - // =========================================================== - - @Override - protected void onCreate(final Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - sGameControllerActivity = this; - mInputManager = InputManagerCompat.Factory.getInputManager(this); - mInputManager.registerInputDeviceListener(this, null); - - if (mControllerNibiru != null) { - mControllerNibiru.onCreate(this); - } - if (mControllerMoga != null) { - mControllerMoga.onCreate(this); - } - if (mControllerOuya != null) { - mControllerOuya.onCreate(this); - } - if (mControllerHelper == null) { - mControllerHelper = new GameControllerHelper(this); - } - } - - // =========================================================== - // Getter & Setter - // =========================================================== + @Override + public void onDisconnected(String vendorName, int controller) { + GameControllerAdapter.onDisconnected(vendorName, controller); + } + }; + + // =========================================================== + // Constructors + // =========================================================== + + @Override + protected void onCreate(final Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + sGameControllerActivity = this; + mInputManager = InputManagerCompat.Factory.getInputManager(this); + mInputManager.registerInputDeviceListener(this, null); + + if (mControllerNibiru != null) { + mControllerNibiru.onCreate(this); + } + if (mControllerMoga != null) { + mControllerMoga.onCreate(this); + } + if (mControllerOuya != null) { + mControllerOuya.onCreate(this); + } + if (mControllerHelper == null) { + mControllerHelper = new GameControllerHelper(this); + } + } + + // =========================================================== + // Getter & Setter + // =========================================================== - // =========================================================== - // Methods for/from SuperClass/Interfaces - // =========================================================== + // =========================================================== + // Methods for/from SuperClass/Interfaces + // =========================================================== - @Override - public boolean dispatchKeyEvent(KeyEvent event) { - boolean handled = false; - if (mControllerNibiru != null) { - handled |= mControllerNibiru.dispatchKeyEvent(event); - } - if (handled == false && mControllerMoga != null) { - handled |= mControllerMoga.dispatchKeyEvent(event); - } - if (handled == false && mControllerOuya != null) { - handled |= mControllerOuya.dispatchKeyEvent(event); - } - - if (handled == false) { - handled |= mControllerHelper.dispatchKeyEvent(event); - } - - return handled || super.dispatchKeyEvent(event); - } - - @Override - public boolean dispatchGenericMotionEvent(MotionEvent event) { - boolean handled = false; - if (mControllerNibiru != null) { - handled |= mControllerNibiru.dispatchGenericMotionEvent(event); - } - if (handled == false && mControllerMoga != null) { - handled |= mControllerMoga.dispatchGenericMotionEvent(event); - } - if (handled == false && mControllerOuya != null) { - handled |= mControllerOuya.dispatchGenericMotionEvent(event); - } - - if (handled == false) { - handled |= mControllerHelper.dispatchGenericMotionEvent(event); - } - - return handled || super.dispatchGenericMotionEvent(event); - } - - @Override - public void onInputDeviceAdded(int deviceId) { - Log.d(TAG,"onInputDeviceAdded:" + deviceId); - - mControllerHelper.onInputDeviceAdded(deviceId); - } - /* - * This is an unusual case. Input devices don't typically change, but they - * certainly can --- for example a device may have different modes. We use - * this to make sure that the ship has an up-to-date InputDevice. - * - * @see - * com.example.inputmanagercompat.InputManagerCompat.InputDeviceListener - * #onInputDeviceChanged(int) - */ - @Override - public void onInputDeviceChanged(int deviceId) { - Log.w(TAG,"onInputDeviceChanged:" + deviceId); - } - - /* - * Remove any ship associated with the ID. - * - * @see - * com.example.inputmanagercompat.InputManagerCompat.InputDeviceListener - * #onInputDeviceRemoved(int) - */ - @Override - public void onInputDeviceRemoved(int deviceId) { - Log.d(TAG,"onInputDeviceRemoved:" + deviceId); - - mControllerHelper.onInputDeviceRemoved(deviceId); - } + @Override + public boolean dispatchKeyEvent(KeyEvent event) { + boolean handled = false; + if (mControllerNibiru != null) { + handled |= mControllerNibiru.dispatchKeyEvent(event); + } + if (handled == false && mControllerMoga != null) { + handled |= mControllerMoga.dispatchKeyEvent(event); + } + if (handled == false && mControllerOuya != null) { + handled |= mControllerOuya.dispatchKeyEvent(event); + } + + if (handled == false) { + handled |= mControllerHelper.dispatchKeyEvent(event); + } + + return handled || super.dispatchKeyEvent(event); + } + + @Override + public boolean dispatchGenericMotionEvent(MotionEvent event) { + boolean handled = false; + if (mControllerNibiru != null) { + handled |= mControllerNibiru.dispatchGenericMotionEvent(event); + } + if (handled == false && mControllerMoga != null) { + handled |= mControllerMoga.dispatchGenericMotionEvent(event); + } + if (handled == false && mControllerOuya != null) { + handled |= mControllerOuya.dispatchGenericMotionEvent(event); + } + + if (handled == false) { + handled |= mControllerHelper.dispatchGenericMotionEvent(event); + } + + return handled || super.dispatchGenericMotionEvent(event); + } + + @Override + public void onInputDeviceAdded(int deviceId) { + Log.d(TAG,"onInputDeviceAdded:" + deviceId); + + mControllerHelper.onInputDeviceAdded(deviceId); + } + /* + * This is an unusual case. Input devices don't typically change, but they + * certainly can --- for example a device may have different modes. We use + * this to make sure that the ship has an up-to-date InputDevice. + * + * @see + * com.example.inputmanagercompat.InputManagerCompat.InputDeviceListener + * #onInputDeviceChanged(int) + */ + @Override + public void onInputDeviceChanged(int deviceId) { + Log.w(TAG,"onInputDeviceChanged:" + deviceId); + } + + /* + * Remove any ship associated with the ID. + * + * @see + * com.example.inputmanagercompat.InputManagerCompat.InputDeviceListener + * #onInputDeviceRemoved(int) + */ + @Override + public void onInputDeviceRemoved(int deviceId) { + Log.d(TAG,"onInputDeviceRemoved:" + deviceId); + + mControllerHelper.onInputDeviceRemoved(deviceId); + } - @Override - protected void onResume() { - super.onResume(); - - if (mControllerNibiru != null) { - mControllerNibiru.onResume(); - } - if (mControllerMoga != null) { - mControllerMoga.onResume(); - } - if (mControllerOuya != null) { - mControllerOuya.onResume(); - } - - GameControllerHelper.gatherControllers(mControllerHelper.mGameController); - } - - @Override - protected void onPause() { - if (mControllerNibiru != null) { - mControllerNibiru.onPause(); - } - if (mControllerMoga != null) { - mControllerMoga.onPause(); - } - if (mControllerOuya != null) { - mControllerOuya.onPause(); - } - - super.onPause(); - } - - @Override - protected void onDestroy() { - if (mControllerNibiru != null) { - mControllerNibiru.onDestroy(); - } - if (mControllerMoga != null) { - mControllerMoga.onDestroy(); - } - if (mControllerOuya != null) { - mControllerOuya.onDestroy(); - } - - super.onDestroy(); - } + @Override + protected void onResume() { + super.onResume(); + + if (mControllerNibiru != null) { + mControllerNibiru.onResume(); + } + if (mControllerMoga != null) { + mControllerMoga.onResume(); + } + if (mControllerOuya != null) { + mControllerOuya.onResume(); + } + + GameControllerHelper.gatherControllers(mControllerHelper.mGameController); + } + + @Override + protected void onPause() { + if (mControllerNibiru != null) { + mControllerNibiru.onPause(); + } + if (mControllerMoga != null) { + mControllerMoga.onPause(); + } + if (mControllerOuya != null) { + mControllerOuya.onPause(); + } + + super.onPause(); + } + + @Override + protected void onDestroy() { + if (mControllerNibiru != null) { + mControllerNibiru.onDestroy(); + } + if (mControllerMoga != null) { + mControllerMoga.onDestroy(); + } + if (mControllerOuya != null) { + mControllerOuya.onDestroy(); + } + + super.onDestroy(); + } } \ No newline at end of file diff --git a/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerHelper.java b/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerHelper.java index f1cec07d113d..0a4ce8b822b8 100644 --- a/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerHelper.java +++ b/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerHelper.java @@ -10,248 +10,248 @@ public class GameControllerHelper { - public static final String StandardControllerName = "Standard"; - - SparseIntArray ControllerKeyMap; - - private static final int AXIS_X = 0; - private static final int AXIS_Y = 1; - private static final int AXIS_Z = 11; - private static final int AXIS_RZ = 14; - private static final int AXIS_LTRIGGER = 17; - private static final int AXIS_RTRIGGER = 18; - public static final int AXIS_GAS = 22; - private static final int AXIS_BRAKE = 23; - private static final int AXIS_THROTTLE = 19; - - public GameControllerHelper(GameControllerActivity activity){ - - ControllerKeyMap = new SparseIntArray(25); - ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_A, GameControllerDelegate.BUTTON_A); - ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_B, GameControllerDelegate.BUTTON_B); - ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_C, GameControllerDelegate.BUTTON_C); - ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_X, GameControllerDelegate.BUTTON_X); - ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_Y, GameControllerDelegate.BUTTON_Y); - ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_Z, GameControllerDelegate.BUTTON_Z); - - ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_UP, GameControllerDelegate.BUTTON_DPAD_UP); - ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_DOWN, GameControllerDelegate.BUTTON_DPAD_DOWN); - ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_LEFT, GameControllerDelegate.BUTTON_DPAD_LEFT); - ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_RIGHT, GameControllerDelegate.BUTTON_DPAD_RIGHT); - ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_CENTER, GameControllerDelegate.BUTTON_DPAD_CENTER); - - ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBL, GameControllerDelegate.BUTTON_LEFT_THUMBSTICK); - ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBR, GameControllerDelegate.BUTTON_RIGHT_THUMBSTICK); - - ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_L1, GameControllerDelegate.BUTTON_LEFT_SHOULDER); - ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_R1, GameControllerDelegate.BUTTON_RIGHT_SHOULDER); - ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_L2, GameControllerDelegate.BUTTON_LEFT_TRIGGER); - ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_R2, GameControllerDelegate.BUTTON_RIGHT_TRIGGER); - - ControllerKeyMap.put(AXIS_X, GameControllerDelegate.THUMBSTICK_LEFT_X); - ControllerKeyMap.put(AXIS_Y, GameControllerDelegate.THUMBSTICK_LEFT_Y); - ControllerKeyMap.put(AXIS_Z, GameControllerDelegate.THUMBSTICK_RIGHT_X); - ControllerKeyMap.put(AXIS_RZ, GameControllerDelegate.THUMBSTICK_RIGHT_Y); - - ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_START, GameControllerDelegate.BUTTON_START); - ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_SELECT, GameControllerDelegate.BUTTON_SELECT); - } - - private float mOldLeftThumbstickX = 0.0f; - private float mOldLeftThumbstickY = 0.0f; - private float mOldRightThumbstickX = 0.0f; - private float mOldRightThumbstickY = 0.0f; - - private float mOldLeftTrigger = 0.0f; - private float mOldRightTrigger = 0.0f; - private float mOldThrottle = 0.0f; - private float mOldBrake = 0.0f; - private float mOldGas = 0.0f; - - public boolean dispatchGenericMotionEvent(MotionEvent event) { - boolean handled = false; - - int eventSource = event.getSource(); - + public static final String StandardControllerName = "Standard"; + + SparseIntArray ControllerKeyMap; + + private static final int AXIS_X = 0; + private static final int AXIS_Y = 1; + private static final int AXIS_Z = 11; + private static final int AXIS_RZ = 14; + private static final int AXIS_LTRIGGER = 17; + private static final int AXIS_RTRIGGER = 18; + public static final int AXIS_GAS = 22; + private static final int AXIS_BRAKE = 23; + private static final int AXIS_THROTTLE = 19; + + public GameControllerHelper(GameControllerActivity activity){ + + ControllerKeyMap = new SparseIntArray(25); + ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_A, GameControllerDelegate.BUTTON_A); + ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_B, GameControllerDelegate.BUTTON_B); + ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_C, GameControllerDelegate.BUTTON_C); + ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_X, GameControllerDelegate.BUTTON_X); + ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_Y, GameControllerDelegate.BUTTON_Y); + ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_Z, GameControllerDelegate.BUTTON_Z); + + ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_UP, GameControllerDelegate.BUTTON_DPAD_UP); + ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_DOWN, GameControllerDelegate.BUTTON_DPAD_DOWN); + ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_LEFT, GameControllerDelegate.BUTTON_DPAD_LEFT); + ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_RIGHT, GameControllerDelegate.BUTTON_DPAD_RIGHT); + ControllerKeyMap.put(KeyEvent.KEYCODE_DPAD_CENTER, GameControllerDelegate.BUTTON_DPAD_CENTER); + + ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBL, GameControllerDelegate.BUTTON_LEFT_THUMBSTICK); + ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBR, GameControllerDelegate.BUTTON_RIGHT_THUMBSTICK); + + ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_L1, GameControllerDelegate.BUTTON_LEFT_SHOULDER); + ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_R1, GameControllerDelegate.BUTTON_RIGHT_SHOULDER); + ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_L2, GameControllerDelegate.BUTTON_LEFT_TRIGGER); + ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_R2, GameControllerDelegate.BUTTON_RIGHT_TRIGGER); + + ControllerKeyMap.put(AXIS_X, GameControllerDelegate.THUMBSTICK_LEFT_X); + ControllerKeyMap.put(AXIS_Y, GameControllerDelegate.THUMBSTICK_LEFT_Y); + ControllerKeyMap.put(AXIS_Z, GameControllerDelegate.THUMBSTICK_RIGHT_X); + ControllerKeyMap.put(AXIS_RZ, GameControllerDelegate.THUMBSTICK_RIGHT_Y); + + ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_START, GameControllerDelegate.BUTTON_START); + ControllerKeyMap.put(KeyEvent.KEYCODE_BUTTON_SELECT, GameControllerDelegate.BUTTON_SELECT); + } + + private float mOldLeftThumbstickX = 0.0f; + private float mOldLeftThumbstickY = 0.0f; + private float mOldRightThumbstickX = 0.0f; + private float mOldRightThumbstickY = 0.0f; + + private float mOldLeftTrigger = 0.0f; + private float mOldRightTrigger = 0.0f; + private float mOldThrottle = 0.0f; + private float mOldBrake = 0.0f; + private float mOldGas = 0.0f; + + public boolean dispatchGenericMotionEvent(MotionEvent event) { + boolean handled = false; + + int eventSource = event.getSource(); + if ( ((eventSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) - || ((eventSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) ) - { - if (event.getAction() == MotionEvent.ACTION_MOVE) { - int deviceId = event.getDeviceId(); - String deviceName = event.getDevice().getName(); - if(mGameController.get(deviceId) == null){ - gatherControllers(mGameController); - mGameController.append(deviceId, deviceName); - } - - float newAXIS_LX = event.getAxisValue(AXIS_X); - if (Float.compare(newAXIS_LX , mOldLeftThumbstickX) != 0) { - GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_X, newAXIS_LX, true); - mOldLeftThumbstickX = newAXIS_LX; - handled = true; - } - - float newAXIS_LY = event.getAxisValue(AXIS_Y); - if (Float.compare(newAXIS_LY , mOldLeftThumbstickY) != 0) { - GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_Y, newAXIS_LY, true); - mOldLeftThumbstickY = newAXIS_LY; - handled = true; - } - - float newAXIS_RX = event.getAxisValue(AXIS_Z); - if (Float.compare(newAXIS_RX , mOldRightThumbstickX) != 0) { - GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_X, newAXIS_RX, true); - mOldRightThumbstickX = newAXIS_RX; - handled = true; - } - - float newAXIS_RY = event.getAxisValue(AXIS_RZ); - if (Float.compare(newAXIS_RY , mOldRightThumbstickY) != 0) { - GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, newAXIS_RY, true); - mOldRightThumbstickY = newAXIS_RY; - handled = true; - } - - float newAXIS_LTRIGGER = event.getAxisValue(AXIS_LTRIGGER); - if (Float.compare(newAXIS_LTRIGGER , mOldLeftTrigger) != 0) { - GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, newAXIS_LTRIGGER, true); - mOldLeftTrigger = newAXIS_LTRIGGER; - handled = true; - } - - float newAXIS_RTRIGGER = event.getAxisValue(AXIS_RTRIGGER); - if (Float.compare(newAXIS_RTRIGGER , mOldRightTrigger) != 0) { - GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newAXIS_RTRIGGER, true); - mOldRightTrigger = newAXIS_RTRIGGER; - handled = true; - } - - float newAXIS_BRAKE = event.getAxisValue(AXIS_BRAKE); - if (Float.compare(newAXIS_BRAKE , mOldBrake) != 0) { - GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, newAXIS_BRAKE, true); - mOldBrake = newAXIS_BRAKE; - handled = true; - } - - float newAXIS_THROTTLE = event.getAxisValue(AXIS_THROTTLE); - if (Float.compare(newAXIS_THROTTLE , mOldThrottle) != 0) { - GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newAXIS_THROTTLE, true); - mOldThrottle = newAXIS_THROTTLE; - handled = true; - } - - float newAXIS_GAS = event.getAxisValue(AXIS_GAS); - if (Float.compare(newAXIS_GAS , mOldGas) != 0) { - GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newAXIS_GAS, true); - mOldGas = newAXIS_GAS; - handled = true; - } - } + || ((eventSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) ) + { + if (event.getAction() == MotionEvent.ACTION_MOVE) { + int deviceId = event.getDeviceId(); + String deviceName = event.getDevice().getName(); + if(mGameController.get(deviceId) == null){ + gatherControllers(mGameController); + mGameController.append(deviceId, deviceName); + } + + float newAXIS_LX = event.getAxisValue(AXIS_X); + if (Float.compare(newAXIS_LX , mOldLeftThumbstickX) != 0) { + GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_X, newAXIS_LX, true); + mOldLeftThumbstickX = newAXIS_LX; + handled = true; + } + + float newAXIS_LY = event.getAxisValue(AXIS_Y); + if (Float.compare(newAXIS_LY , mOldLeftThumbstickY) != 0) { + GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_Y, newAXIS_LY, true); + mOldLeftThumbstickY = newAXIS_LY; + handled = true; + } + + float newAXIS_RX = event.getAxisValue(AXIS_Z); + if (Float.compare(newAXIS_RX , mOldRightThumbstickX) != 0) { + GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_X, newAXIS_RX, true); + mOldRightThumbstickX = newAXIS_RX; + handled = true; + } + + float newAXIS_RY = event.getAxisValue(AXIS_RZ); + if (Float.compare(newAXIS_RY , mOldRightThumbstickY) != 0) { + GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, newAXIS_RY, true); + mOldRightThumbstickY = newAXIS_RY; + handled = true; + } + + float newAXIS_LTRIGGER = event.getAxisValue(AXIS_LTRIGGER); + if (Float.compare(newAXIS_LTRIGGER , mOldLeftTrigger) != 0) { + GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, newAXIS_LTRIGGER, true); + mOldLeftTrigger = newAXIS_LTRIGGER; + handled = true; + } + + float newAXIS_RTRIGGER = event.getAxisValue(AXIS_RTRIGGER); + if (Float.compare(newAXIS_RTRIGGER , mOldRightTrigger) != 0) { + GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newAXIS_RTRIGGER, true); + mOldRightTrigger = newAXIS_RTRIGGER; + handled = true; + } + + float newAXIS_BRAKE = event.getAxisValue(AXIS_BRAKE); + if (Float.compare(newAXIS_BRAKE , mOldBrake) != 0) { + GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, newAXIS_BRAKE, true); + mOldBrake = newAXIS_BRAKE; + handled = true; + } + + float newAXIS_THROTTLE = event.getAxisValue(AXIS_THROTTLE); + if (Float.compare(newAXIS_THROTTLE , mOldThrottle) != 0) { + GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newAXIS_THROTTLE, true); + mOldThrottle = newAXIS_THROTTLE; + handled = true; + } + + float newAXIS_GAS = event.getAxisValue(AXIS_GAS); + if (Float.compare(newAXIS_GAS , mOldGas) != 0) { + GameControllerAdapter.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newAXIS_GAS, true); + mOldGas = newAXIS_GAS; + handled = true; + } + } + } + + return handled; + } + + private static SparseArray> mControllerExtendKey = new SparseArray>(); + + public boolean dispatchKeyEvent(KeyEvent event) { + boolean handled = false; + + int eventSource = event.getSource(); + int keyCode = event.getKeyCode(); + int controllerKey = ControllerKeyMap.get(keyCode); + + if (((eventSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) + || ((eventSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) ) + { + int deviceId = event.getDeviceId(); + String deviceName = event.getDevice().getName(); + + if(mGameController.get(deviceId) == null){ + gatherControllers(mGameController); + mGameController.append(deviceId, deviceName); + } + + if (controllerKey == 0) { + if (mControllerExtendKey.get(deviceId) != null && mControllerExtendKey.get(deviceId).contains(keyCode)) { + controllerKey = keyCode; + }else { + return false; + } + } + + int action = event.getAction(); + if (action == KeyEvent.ACTION_DOWN) { + handled = true; + GameControllerAdapter.onButtonEvent(deviceName, deviceId, controllerKey,true, 1.0f, false); + }else if (action == KeyEvent.ACTION_UP) { + handled = true; + GameControllerAdapter.onButtonEvent(deviceName, deviceId, controllerKey,false, 0.0f, false); + } } - return handled; - } - - private static SparseArray> mControllerExtendKey = new SparseArray>(); - - public boolean dispatchKeyEvent(KeyEvent event) { - boolean handled = false; - - int eventSource = event.getSource(); - int keyCode = event.getKeyCode(); - int controllerKey = ControllerKeyMap.get(keyCode); - - if (((eventSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) - || ((eventSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) ) - { - int deviceId = event.getDeviceId(); - String deviceName = event.getDevice().getName(); - - if(mGameController.get(deviceId) == null){ - gatherControllers(mGameController); - mGameController.append(deviceId, deviceName); - } - - if (controllerKey == 0) { - if (mControllerExtendKey.get(deviceId) != null && mControllerExtendKey.get(deviceId).contains(keyCode)) { - controllerKey = keyCode; - }else { - return false; - } - } - - int action = event.getAction(); - if (action == KeyEvent.ACTION_DOWN) { - handled = true; - GameControllerAdapter.onButtonEvent(deviceName, deviceId, controllerKey,true, 1.0f, false); - }else if (action == KeyEvent.ACTION_UP) { - handled = true; - GameControllerAdapter.onButtonEvent(deviceName, deviceId, controllerKey,false, 0.0f, false); - } - } - - return handled; + return handled; + } + + public static void receiveExternalKeyEvent(int deviceId,int externalKeyCode,boolean receive) { + if (receive) { + if (mControllerExtendKey.get(deviceId) == null) { + mControllerExtendKey.put(deviceId, new ArrayList()); + } + mControllerExtendKey.get(deviceId).add(externalKeyCode); + } else { + if (mControllerExtendKey.get(deviceId) != null) { + mControllerExtendKey.get(deviceId).remove(Integer.valueOf(externalKeyCode)); + } + } + } + + SparseArray mGameController = new SparseArray(); + + void onInputDeviceAdded(int deviceId){ + try { + InputDevice device = InputDevice.getDevice(deviceId); + int deviceSource = device.getSources(); + + if ( ((deviceSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) + || ((deviceSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) ) + { + String deviceName = device.getName(); + mGameController.append(deviceId, deviceName); + GameControllerAdapter.onConnected(deviceName, deviceId); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + void onInputDeviceChanged(int deviceId){ + gatherControllers(mGameController); + } + + void onInputDeviceRemoved(int deviceId) { + if (mGameController.get(deviceId) != null) { + GameControllerAdapter.onDisconnected(mGameController.get(deviceId), deviceId); + mGameController.delete(deviceId); + } + } + + static void gatherControllers(SparseArray controllers){ + int controllerCount = controllers.size(); + for (int i = 0; i < controllerCount; i++) { + try { + int controllerDeveceId = controllers.keyAt(i); + InputDevice device = InputDevice.getDevice(controllerDeveceId); + if (device == null) { + GameControllerAdapter.onDisconnected(controllers.get(controllerDeveceId), controllerDeveceId); + controllers.delete(controllerDeveceId); + } + } catch (Exception e) { + int controllerDeveceId = controllers.keyAt(i); + GameControllerAdapter.onDisconnected(controllers.get(controllerDeveceId), controllerDeveceId); + controllers.delete(controllerDeveceId); + e.printStackTrace(); + } + } } - - public static void receiveExternalKeyEvent(int deviceId,int externalKeyCode,boolean receive) { - if (receive) { - if (mControllerExtendKey.get(deviceId) == null) { - mControllerExtendKey.put(deviceId, new ArrayList()); - } - mControllerExtendKey.get(deviceId).add(externalKeyCode); - } else { - if (mControllerExtendKey.get(deviceId) != null) { - mControllerExtendKey.get(deviceId).remove(Integer.valueOf(externalKeyCode)); - } - } - } - - SparseArray mGameController = new SparseArray(); - - void onInputDeviceAdded(int deviceId){ - try { - InputDevice device = InputDevice.getDevice(deviceId); - int deviceSource = device.getSources(); - - if ( ((deviceSource & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) - || ((deviceSource & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK) ) - { - String deviceName = device.getName(); - mGameController.append(deviceId, deviceName); - GameControllerAdapter.onConnected(deviceName, deviceId); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - void onInputDeviceChanged(int deviceId){ - gatherControllers(mGameController); - } - - void onInputDeviceRemoved(int deviceId) { - if (mGameController.get(deviceId) != null) { - GameControllerAdapter.onDisconnected(mGameController.get(deviceId), deviceId); - mGameController.delete(deviceId); - } - } - - static void gatherControllers(SparseArray controllers){ - int controllerCount = controllers.size(); - for (int i = 0; i < controllerCount; i++) { - try { - int controllerDeveceId = controllers.keyAt(i); - InputDevice device = InputDevice.getDevice(controllerDeveceId); - if (device == null) { - GameControllerAdapter.onDisconnected(controllers.get(controllerDeveceId), controllerDeveceId); - controllers.delete(controllerDeveceId); - } - } catch (Exception e) { - int controllerDeveceId = controllers.keyAt(i); - GameControllerAdapter.onDisconnected(controllers.get(controllerDeveceId), controllerDeveceId); - controllers.delete(controllerDeveceId); - e.printStackTrace(); - } - } - } } diff --git a/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerMoga.java b/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerMoga.java index 2fe73a642b89..fc11024bbc86 100644 --- a/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerMoga.java +++ b/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerMoga.java @@ -14,205 +14,205 @@ public class GameControllerMoga implements ControllerListener, GameControllerDelegate { - private static final String mVendorName = "Moga"; - - private float mOldLeftThumbstickX = 0.0f; - private float mOldLeftThumbstickY = 0.0f; - private float mOldRightThumbstickX = 0.0f; - private float mOldRightThumbstickY = 0.0f; - - private float mOldLeftTrigger = 0.0f; - private float mOldRightTrigger = 0.0f; - - private SparseIntArray mKeyMap = null; - - public GameControllerMoga() { - mKeyMap = new SparseIntArray(20); - mKeyMap.put(KeyEvent.KEYCODE_BUTTON_A, GameControllerDelegate.BUTTON_A); - mKeyMap.put(KeyEvent.KEYCODE_BUTTON_B, GameControllerDelegate.BUTTON_B); - mKeyMap.put(KeyEvent.KEYCODE_BUTTON_X, GameControllerDelegate.BUTTON_X); - mKeyMap.put(KeyEvent.KEYCODE_BUTTON_Y, GameControllerDelegate.BUTTON_Y); - - mKeyMap.put(KeyEvent.KEYCODE_BUTTON_L1, - GameControllerDelegate.BUTTON_LEFT_SHOULDER); - mKeyMap.put(KeyEvent.KEYCODE_BUTTON_R1, - GameControllerDelegate.BUTTON_RIGHT_SHOULDER); - mKeyMap.put(KeyEvent.KEYCODE_BUTTON_L2, - GameControllerDelegate.BUTTON_LEFT_TRIGGER); - mKeyMap.put(KeyEvent.KEYCODE_BUTTON_R2, - GameControllerDelegate.BUTTON_RIGHT_TRIGGER); - - mKeyMap.put(KeyEvent.KEYCODE_DPAD_UP, - GameControllerDelegate.BUTTON_DPAD_UP); - mKeyMap.put(KeyEvent.KEYCODE_DPAD_DOWN, - GameControllerDelegate.BUTTON_DPAD_DOWN); - mKeyMap.put(KeyEvent.KEYCODE_DPAD_LEFT, - GameControllerDelegate.BUTTON_DPAD_LEFT); - mKeyMap.put(KeyEvent.KEYCODE_DPAD_RIGHT, - GameControllerDelegate.BUTTON_DPAD_RIGHT); - - mKeyMap.put(KeyEvent.KEYCODE_BUTTON_START, - GameControllerDelegate.BUTTON_START); - mKeyMap.put(KeyEvent.KEYCODE_BUTTON_SELECT, - GameControllerDelegate.BUTTON_SELECT); - mKeyMap.put(KeyEvent.KEYCODE_BUTTON_START, - GameControllerDelegate.BUTTON_START); - mKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBL, - GameControllerDelegate.BUTTON_LEFT_THUMBSTICK); - mKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBR, - GameControllerDelegate.BUTTON_RIGHT_THUMBSTICK); - } - - public void onKeyEvent(KeyEvent event) { - int keycode = event.getKeyCode(); - if (keycode == KeyEvent.KEYCODE_BUTTON_L2 - || keycode == KeyEvent.KEYCODE_BUTTON_R2) { - return; - } - boolean isPressed = event.getAction() == KeyEvent.ACTION_DOWN; - boolean isAnalog = false; - - if (keycode == KeyEvent.KEYCODE_BUTTON_THUMBL - || keycode == KeyEvent.KEYCODE_BUTTON_THUMBR) { - isAnalog = true; - } - - if (mKeyMap.get(keycode, Integer.MIN_VALUE) != Integer.MIN_VALUE && mControllerEventListener != null) { - mControllerEventListener.onButtonEvent(mVendorName, - event.getControllerId(), mKeyMap.get(keycode), isPressed, - isPressed ? 1.0f : 0.0f, isAnalog); - } - } - - @Override - public void onMotionEvent(MotionEvent event) { - if (mControllerEventListener == null) { - return; - } - int controllerId = event.getControllerId(); - - float newLeftThumbstickX = event.getAxisValue(MotionEvent.AXIS_X); - if (newLeftThumbstickX != mOldLeftThumbstickX) { - mControllerEventListener.onAxisEvent(mVendorName, - controllerId, - GameControllerDelegate.THUMBSTICK_LEFT_X, - newLeftThumbstickX, true); - mOldLeftThumbstickX = newLeftThumbstickX; - } - - float newLeftThumbstickY = event.getAxisValue(MotionEvent.AXIS_Y); - if (newLeftThumbstickY != mOldLeftThumbstickY) { - mControllerEventListener.onAxisEvent(mVendorName, - controllerId, - GameControllerDelegate.THUMBSTICK_LEFT_Y, - newLeftThumbstickY, true); - mOldLeftThumbstickY = newLeftThumbstickY; - } - - float newRightThumbstickX = event.getAxisValue(MotionEvent.AXIS_Z); - if (newRightThumbstickX != mOldRightThumbstickX) { - mControllerEventListener.onAxisEvent(mVendorName, - controllerId, - GameControllerDelegate.THUMBSTICK_RIGHT_X, - newRightThumbstickX, true); - mOldRightThumbstickX = newRightThumbstickX; - } - - float newRightThumbstickY = event.getAxisValue(MotionEvent.AXIS_RZ); - if (newRightThumbstickY != mOldRightThumbstickY) { - mControllerEventListener.onAxisEvent(mVendorName, - controllerId, - GameControllerDelegate.THUMBSTICK_RIGHT_Y, - newRightThumbstickY, true); - mOldRightThumbstickY = newRightThumbstickY; - } - - float newLeftTrigger = event.getAxisValue(MotionEvent.AXIS_LTRIGGER); - if (newLeftTrigger != mOldLeftTrigger) { - mControllerEventListener.onAxisEvent(mVendorName, - controllerId, - GameControllerDelegate.BUTTON_LEFT_TRIGGER, - newLeftTrigger, true); - mOldLeftTrigger = newLeftTrigger; - } - - float newRightTrigger = event.getAxisValue(MotionEvent.AXIS_RTRIGGER); - if (newRightTrigger != mOldRightTrigger) { - mControllerEventListener.onAxisEvent(mVendorName, - controllerId, - GameControllerDelegate.BUTTON_RIGHT_TRIGGER, - newRightTrigger, true); - mOldRightTrigger = newRightTrigger; - } - } - - @Override - public void onStateEvent(StateEvent event) { - if (mControllerEventListener != null) { - switch (event.getState()) { - case StateEvent.STATE_CONNECTION: - switch (event.getAction()) { - case StateEvent.ACTION_DISCONNECTED: - // disconnected from controller - mControllerEventListener.onDisconnected(mVendorName, - event.getControllerId()); - break; - case StateEvent.ACTION_CONNECTED: - // connected to controller - mControllerEventListener.onConnected(mVendorName, - event.getControllerId()); - break; - case StateEvent.ACTION_CONNECTING: - // attempting to connect to controller - break; - } - break; - case StateEvent.STATE_POWER_LOW: - if (event.getAction() == StateEvent.ACTION_TRUE) { - // controller has entered low power state - } else { - // controller has entered normal power state - } - break; - } - } - } - - private Controller mController = null; - - public void onCreate(Context context) { - mController = Controller.getInstance(context); - - mController.init(); - mController.setListener(this, new Handler()); - } - - public void onPause() { - mController.onPause(); - } - - public void onResume() { - mController.onResume(); - } - - public void onDestroy() { - mController.exit(); - } - - private ControllerEventListener mControllerEventListener; - @Override - public void setControllerEventListener(ControllerEventListener listener) { - mControllerEventListener = listener; - } - - @Override - public boolean dispatchKeyEvent(android.view.KeyEvent event) { - return false; - } - - @Override - public boolean dispatchGenericMotionEvent(android.view.MotionEvent event) { - return false; - } + private static final String mVendorName = "Moga"; + + private float mOldLeftThumbstickX = 0.0f; + private float mOldLeftThumbstickY = 0.0f; + private float mOldRightThumbstickX = 0.0f; + private float mOldRightThumbstickY = 0.0f; + + private float mOldLeftTrigger = 0.0f; + private float mOldRightTrigger = 0.0f; + + private SparseIntArray mKeyMap = null; + + public GameControllerMoga() { + mKeyMap = new SparseIntArray(20); + mKeyMap.put(KeyEvent.KEYCODE_BUTTON_A, GameControllerDelegate.BUTTON_A); + mKeyMap.put(KeyEvent.KEYCODE_BUTTON_B, GameControllerDelegate.BUTTON_B); + mKeyMap.put(KeyEvent.KEYCODE_BUTTON_X, GameControllerDelegate.BUTTON_X); + mKeyMap.put(KeyEvent.KEYCODE_BUTTON_Y, GameControllerDelegate.BUTTON_Y); + + mKeyMap.put(KeyEvent.KEYCODE_BUTTON_L1, + GameControllerDelegate.BUTTON_LEFT_SHOULDER); + mKeyMap.put(KeyEvent.KEYCODE_BUTTON_R1, + GameControllerDelegate.BUTTON_RIGHT_SHOULDER); + mKeyMap.put(KeyEvent.KEYCODE_BUTTON_L2, + GameControllerDelegate.BUTTON_LEFT_TRIGGER); + mKeyMap.put(KeyEvent.KEYCODE_BUTTON_R2, + GameControllerDelegate.BUTTON_RIGHT_TRIGGER); + + mKeyMap.put(KeyEvent.KEYCODE_DPAD_UP, + GameControllerDelegate.BUTTON_DPAD_UP); + mKeyMap.put(KeyEvent.KEYCODE_DPAD_DOWN, + GameControllerDelegate.BUTTON_DPAD_DOWN); + mKeyMap.put(KeyEvent.KEYCODE_DPAD_LEFT, + GameControllerDelegate.BUTTON_DPAD_LEFT); + mKeyMap.put(KeyEvent.KEYCODE_DPAD_RIGHT, + GameControllerDelegate.BUTTON_DPAD_RIGHT); + + mKeyMap.put(KeyEvent.KEYCODE_BUTTON_START, + GameControllerDelegate.BUTTON_START); + mKeyMap.put(KeyEvent.KEYCODE_BUTTON_SELECT, + GameControllerDelegate.BUTTON_SELECT); + mKeyMap.put(KeyEvent.KEYCODE_BUTTON_START, + GameControllerDelegate.BUTTON_START); + mKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBL, + GameControllerDelegate.BUTTON_LEFT_THUMBSTICK); + mKeyMap.put(KeyEvent.KEYCODE_BUTTON_THUMBR, + GameControllerDelegate.BUTTON_RIGHT_THUMBSTICK); + } + + public void onKeyEvent(KeyEvent event) { + int keycode = event.getKeyCode(); + if (keycode == KeyEvent.KEYCODE_BUTTON_L2 + || keycode == KeyEvent.KEYCODE_BUTTON_R2) { + return; + } + boolean isPressed = event.getAction() == KeyEvent.ACTION_DOWN; + boolean isAnalog = false; + + if (keycode == KeyEvent.KEYCODE_BUTTON_THUMBL + || keycode == KeyEvent.KEYCODE_BUTTON_THUMBR) { + isAnalog = true; + } + + if (mKeyMap.get(keycode, Integer.MIN_VALUE) != Integer.MIN_VALUE && mControllerEventListener != null) { + mControllerEventListener.onButtonEvent(mVendorName, + event.getControllerId(), mKeyMap.get(keycode), isPressed, + isPressed ? 1.0f : 0.0f, isAnalog); + } + } + + @Override + public void onMotionEvent(MotionEvent event) { + if (mControllerEventListener == null) { + return; + } + int controllerId = event.getControllerId(); + + float newLeftThumbstickX = event.getAxisValue(MotionEvent.AXIS_X); + if (newLeftThumbstickX != mOldLeftThumbstickX) { + mControllerEventListener.onAxisEvent(mVendorName, + controllerId, + GameControllerDelegate.THUMBSTICK_LEFT_X, + newLeftThumbstickX, true); + mOldLeftThumbstickX = newLeftThumbstickX; + } + + float newLeftThumbstickY = event.getAxisValue(MotionEvent.AXIS_Y); + if (newLeftThumbstickY != mOldLeftThumbstickY) { + mControllerEventListener.onAxisEvent(mVendorName, + controllerId, + GameControllerDelegate.THUMBSTICK_LEFT_Y, + newLeftThumbstickY, true); + mOldLeftThumbstickY = newLeftThumbstickY; + } + + float newRightThumbstickX = event.getAxisValue(MotionEvent.AXIS_Z); + if (newRightThumbstickX != mOldRightThumbstickX) { + mControllerEventListener.onAxisEvent(mVendorName, + controllerId, + GameControllerDelegate.THUMBSTICK_RIGHT_X, + newRightThumbstickX, true); + mOldRightThumbstickX = newRightThumbstickX; + } + + float newRightThumbstickY = event.getAxisValue(MotionEvent.AXIS_RZ); + if (newRightThumbstickY != mOldRightThumbstickY) { + mControllerEventListener.onAxisEvent(mVendorName, + controllerId, + GameControllerDelegate.THUMBSTICK_RIGHT_Y, + newRightThumbstickY, true); + mOldRightThumbstickY = newRightThumbstickY; + } + + float newLeftTrigger = event.getAxisValue(MotionEvent.AXIS_LTRIGGER); + if (newLeftTrigger != mOldLeftTrigger) { + mControllerEventListener.onAxisEvent(mVendorName, + controllerId, + GameControllerDelegate.BUTTON_LEFT_TRIGGER, + newLeftTrigger, true); + mOldLeftTrigger = newLeftTrigger; + } + + float newRightTrigger = event.getAxisValue(MotionEvent.AXIS_RTRIGGER); + if (newRightTrigger != mOldRightTrigger) { + mControllerEventListener.onAxisEvent(mVendorName, + controllerId, + GameControllerDelegate.BUTTON_RIGHT_TRIGGER, + newRightTrigger, true); + mOldRightTrigger = newRightTrigger; + } + } + + @Override + public void onStateEvent(StateEvent event) { + if (mControllerEventListener != null) { + switch (event.getState()) { + case StateEvent.STATE_CONNECTION: + switch (event.getAction()) { + case StateEvent.ACTION_DISCONNECTED: + // disconnected from controller + mControllerEventListener.onDisconnected(mVendorName, + event.getControllerId()); + break; + case StateEvent.ACTION_CONNECTED: + // connected to controller + mControllerEventListener.onConnected(mVendorName, + event.getControllerId()); + break; + case StateEvent.ACTION_CONNECTING: + // attempting to connect to controller + break; + } + break; + case StateEvent.STATE_POWER_LOW: + if (event.getAction() == StateEvent.ACTION_TRUE) { + // controller has entered low power state + } else { + // controller has entered normal power state + } + break; + } + } + } + + private Controller mController = null; + + public void onCreate(Context context) { + mController = Controller.getInstance(context); + + mController.init(); + mController.setListener(this, new Handler()); + } + + public void onPause() { + mController.onPause(); + } + + public void onResume() { + mController.onResume(); + } + + public void onDestroy() { + mController.exit(); + } + + private ControllerEventListener mControllerEventListener; + @Override + public void setControllerEventListener(ControllerEventListener listener) { + mControllerEventListener = listener; + } + + @Override + public boolean dispatchKeyEvent(android.view.KeyEvent event) { + return false; + } + + @Override + public boolean dispatchGenericMotionEvent(android.view.MotionEvent event) { + return false; + } } diff --git a/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerNibiru.java b/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerNibiru.java index ec3aeb972334..a1e60a5d2178 100644 --- a/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerNibiru.java +++ b/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerNibiru.java @@ -26,16 +26,16 @@ public class GameControllerNibiru implements OnControllerSeviceListener, OnKeyListener, OnSimpleStickListener, OnAccListener, OnGyroListener, OnStateListener, GameControllerDelegate { - private static final String TAG = "NibiruTag"; - - private Context mContext; - private SparseIntArray mKeyMap; - private ControllerEventListener mControllerEventListener = null; - private ControllerService mControllerService = null; - - public GameControllerNibiru() { - mKeyMap = new SparseIntArray(20); - + private static final String TAG = "NibiruTag"; + + private Context mContext; + private SparseIntArray mKeyMap; + private ControllerEventListener mControllerEventListener = null; + private ControllerService mControllerService = null; + + public GameControllerNibiru() { + mKeyMap = new SparseIntArray(20); + mKeyMap.put(ControllerKeyEvent.KEYCODE_BUTTON_A , GameControllerDelegate.BUTTON_A); mKeyMap.put(ControllerKeyEvent.KEYCODE_BUTTON_B , GameControllerDelegate.BUTTON_B); mKeyMap.put(ControllerKeyEvent.KEYCODE_BUTTON_X , GameControllerDelegate.BUTTON_X); @@ -52,188 +52,188 @@ public GameControllerNibiru() { mKeyMap.put(ControllerKeyEvent.KEYCODE_BUTTON_SELECT , GameControllerDelegate.BUTTON_SELECT); mKeyMap.put(ControllerKeyEvent.KEYCODE_BUTTON_THUMBL , GameControllerDelegate.BUTTON_LEFT_THUMBSTICK); mKeyMap.put(ControllerKeyEvent.KEYCODE_BUTTON_THUMBR , GameControllerDelegate.BUTTON_RIGHT_THUMBSTICK); - } - - @Override - public void setControllerEventListener(ControllerEventListener listener) { - mControllerEventListener = listener; - } - - public void onCreate(Context context) { - mContext = context; - - mControllerService = Controller.getControllerService(); - if (mControllerService != null) { - mControllerService.setControllerServiceListener(this); - mControllerService.setStateListener(this); - mControllerService.setKeyListener(this); - mControllerService.setSimpleStickListener(this); - //mControllerService.setAccListener(this); - //mControllerService.setGyroListener(this); - mControllerService.setEnableLR2(true); - mControllerService.setAutoKeyUpMode(false); - - mControllerService.checkNibiruInstall(mContext, false); - } - } - - public void onPause() { - if (mControllerService != null) { - mControllerService.setEnable(false); - } - } - - public void onResume() { - if (mControllerService != null) { - if (mControllerService.isServiceEnable()) { - //onControllerServiceReady(true); - } else { - if (mControllerService.checkNibiruInstall(mContext, false)) { - try { - mControllerService.register(mContext); - } catch (ControllerServiceException e) { - e.printStackTrace(); - } - } - } - - mControllerService.setEnable(true); - } - } - - public void onDestroy() { - if( mControllerService != null ){ - mControllerService.unregister(); - } - } + } + + @Override + public void setControllerEventListener(ControllerEventListener listener) { + mControllerEventListener = listener; + } + + public void onCreate(Context context) { + mContext = context; + + mControllerService = Controller.getControllerService(context); + if (mControllerService != null) { + mControllerService.setControllerServiceListener(this); + mControllerService.setStateListener(this); + mControllerService.setKeyListener(this); + mControllerService.setSimpleStickListener(this); + //mControllerService.setAccListener(this); + //mControllerService.setGyroListener(this); + mControllerService.setEnableL2R2(true); + mControllerService.setAutoKeyUpMode(false); + + mControllerService.checkNibiruInstall(mContext, false); + } + } + + public void onPause() { + if (mControllerService != null) { + mControllerService.setEnable(false); + } + } + + public void onResume() { + if (mControllerService != null) { + if (mControllerService.isServiceEnable()) { + //onControllerServiceReady(true); + } else { + if (mControllerService.checkNibiruInstall(mContext, false)) { + try { + mControllerService.register(mContext); + } catch (ControllerServiceException e) { + e.printStackTrace(); + } + } + } + + mControllerService.setEnable(true); + } + } + + public void onDestroy() { + if( mControllerService != null ){ + mControllerService.unregister(); + } + } - @Override - public void onControllerServiceReady(boolean isSucc) { - if( isSucc ) - { - if( !mControllerService.hasDeviceConnected() ){ - Bundle bun = new Bundle(); - bun.putBoolean(ControllerService.FLAG_IS_SHOW_GAMEPAD_TIP, false); - try { - mControllerService.showDeviceManagerUI(mContext, bun); - } catch (ControllerServiceException e) { - e.printStackTrace(); - } - } - } - } + @Override + public void onControllerServiceReady(boolean isSucc) { + if( isSucc ) + { + if( !mControllerService.hasDeviceConnected() ){ + Bundle bun = new Bundle(); + bun.putBoolean(ControllerService.FLAG_IS_SHOW_GAMEPAD_TIP, false); + /*try { + mControllerService.showDeviceManagerUI(mContext, bun); + } catch (ControllerServiceException e) { + e.printStackTrace(); + }*/ + } + } + } - @Override - public void onControllerKeyDown(int playerOrder, int keyCode, ControllerKeyEvent event) { - if (mKeyMap.get(keyCode) == 0) { - Log.e(TAG, "Didn't map the key: " + keyCode); - return; - } - - if (mControllerEventListener != null) { - try { - ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder); - - mControllerEventListener.onButtonEvent(controllerDevice.getDeviceName(), controllerDevice.getDeviceId(), - mKeyMap.get(keyCode), true, 1.0f, false); - } catch (ControllerServiceException e) { - e.printStackTrace(); - } - } - } + @Override + public void onControllerKeyDown(int playerOrder, int keyCode, ControllerKeyEvent event) { + if (mKeyMap.get(keyCode) == 0) { + Log.e(TAG, "Didn't map the key: " + keyCode); + return; + } + + if (mControllerEventListener != null) { + try { + ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder); + + mControllerEventListener.onButtonEvent(controllerDevice.getDeviceName(), controllerDevice.getDeviceId(), + mKeyMap.get(keyCode), true, 1.0f, false); + } catch (ControllerServiceException e) { + e.printStackTrace(); + } + } + } - @Override - public void onControllerKeyUp(int playerOrder, int keyCode, ControllerKeyEvent event) { - if (mKeyMap.get(keyCode) == 0) { - Log.e(TAG, "Didn't map the key: " + keyCode); - return; - } - - if (mControllerEventListener != null) { - try { - ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder); - - mControllerEventListener.onButtonEvent(controllerDevice.getDeviceName(), controllerDevice.getDeviceId(), - mKeyMap.get(keyCode), false, 0.0f, false); - } catch (ControllerServiceException e) { - e.printStackTrace(); - } - } - } + @Override + public void onControllerKeyUp(int playerOrder, int keyCode, ControllerKeyEvent event) { + if (mKeyMap.get(keyCode) == 0) { + Log.e(TAG, "Didn't map the key: " + keyCode); + return; + } + + if (mControllerEventListener != null) { + try { + ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder); + + mControllerEventListener.onButtonEvent(controllerDevice.getDeviceName(), controllerDevice.getDeviceId(), + mKeyMap.get(keyCode), false, 0.0f, false); + } catch (ControllerServiceException e) { + e.printStackTrace(); + } + } + } - @Override - public void onLeftStickChanged(int playerOrder, float x, float y) { - if (mControllerEventListener != null) { - try { - ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder); - - String deviceName = controllerDevice.getDeviceName(); - int deviceId = controllerDevice.getDeviceId(); - - mControllerEventListener.onAxisEvent(deviceName, deviceId, - GameControllerDelegate.THUMBSTICK_LEFT_X, x, true); - mControllerEventListener.onAxisEvent(deviceName, deviceId, - GameControllerDelegate.THUMBSTICK_LEFT_Y, y, true); - } catch (ControllerServiceException e) { - e.printStackTrace(); - } - } - } + @Override + public void onLeftStickChanged(int playerOrder, float x, float y) { + if (mControllerEventListener != null) { + try { + ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder); + + String deviceName = controllerDevice.getDeviceName(); + int deviceId = controllerDevice.getDeviceId(); + + mControllerEventListener.onAxisEvent(deviceName, deviceId, + GameControllerDelegate.THUMBSTICK_LEFT_X, x, true); + mControllerEventListener.onAxisEvent(deviceName, deviceId, + GameControllerDelegate.THUMBSTICK_LEFT_Y, y, true); + } catch (ControllerServiceException e) { + e.printStackTrace(); + } + } + } - @Override - public void onRightStickChanged(int playerOrder, float x, float y) { - if (mControllerEventListener != null) { - try { - ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder); - - String deviceName = controllerDevice.getDeviceName(); - int deviceId = controllerDevice.getDeviceId(); - - mControllerEventListener.onAxisEvent(deviceName, deviceId, - GameControllerDelegate.THUMBSTICK_RIGHT_X, x, true); - mControllerEventListener.onAxisEvent(deviceName, deviceId, - GameControllerDelegate.THUMBSTICK_RIGHT_Y, y, true); - } catch (ControllerServiceException e) { - e.printStackTrace(); - } - } - } - - @Override - public void onControllerStateChanged(int playerOrder, int state, ControllerDevice device) { - if (mControllerEventListener != null) { - if (state == ControllerDevice.STATE_CONN) - { - mControllerEventListener.onConnected(device.getDeviceName(), device.getDeviceId()); - } - else if (state == ControllerDevice.STATE_DISCONN) - { - mControllerEventListener.onDisconnected(device.getDeviceName(), device.getDeviceId()); - } - } - } + @Override + public void onRightStickChanged(int playerOrder, float x, float y) { + if (mControllerEventListener != null) { + try { + ControllerDevice controllerDevice = mControllerService.getDeviceByPlayerOrder(playerOrder); + + String deviceName = controllerDevice.getDeviceName(); + int deviceId = controllerDevice.getDeviceId(); + + mControllerEventListener.onAxisEvent(deviceName, deviceId, + GameControllerDelegate.THUMBSTICK_RIGHT_X, x, true); + mControllerEventListener.onAxisEvent(deviceName, deviceId, + GameControllerDelegate.THUMBSTICK_RIGHT_Y, y, true); + } catch (ControllerServiceException e) { + e.printStackTrace(); + } + } + } + + @Override + public void onControllerStateChanged(int playerOrder, int state, ControllerDevice device) { + if (mControllerEventListener != null) { + if (state == ControllerDevice.STATE_CONN) + { + mControllerEventListener.onConnected(device.getDeviceName(), device.getDeviceId()); + } + else if (state == ControllerDevice.STATE_DISCONN) + { + mControllerEventListener.onDisconnected(device.getDeviceName(), device.getDeviceId()); + } + } + } - public boolean dispatchGenericMotionEvent(MotionEvent event){ - return mControllerService.handleExternalInput(event); - } - - public boolean dispatchKeyEvent(KeyEvent event){ - return mControllerService.handleExternalInput(event); - } - - @Override - public void onControllerAccEvent(int playerOrder, AccEvent event) { - - } + public boolean dispatchGenericMotionEvent(MotionEvent event){ + return mControllerService.handleExternalInput(event); + } + + public boolean dispatchKeyEvent(KeyEvent event){ + return mControllerService.handleExternalInput(event); + } + + @Override + public void onControllerAccEvent(int playerOrder, AccEvent event) { + + } - @Override - public void onControllerGyroEvent(int playerOrder, GyroEvent event) { - - } + @Override + public void onControllerGyroEvent(int playerOrder, GyroEvent event) { + + } - @Override - public void onBluetoothStateChanged(int state) { - Log.d(TAG, "onBluetoothStateChanged:"+state); - } + @Override + public void onBluetoothStateChanged(int state) { + Log.d(TAG, "onBluetoothStateChanged:"+state); + } } diff --git a/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerOuya.java b/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerOuya.java index fab0fdc80ab5..a750b5835146 100644 --- a/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerOuya.java +++ b/cocos/platform/android/ControllerManualAdapter/src/org/cocos2dx/lib/GameControllerOuya.java @@ -11,17 +11,17 @@ import android.view.MotionEvent; public class GameControllerOuya implements GameControllerDelegate{ - - private SparseIntArray mKeyMap; - private SparseArray mGameController = new SparseArray(); - - public GameControllerOuya(){ - mKeyMap = new SparseIntArray(20); - mKeyMap.put(OuyaController.BUTTON_A, GameControllerDelegate.BUTTON_B); - mKeyMap.put(OuyaController.BUTTON_O, GameControllerDelegate.BUTTON_A); - mKeyMap.put(OuyaController.BUTTON_U, GameControllerDelegate.BUTTON_X); - mKeyMap.put(OuyaController.BUTTON_Y, GameControllerDelegate.BUTTON_Y); + private SparseIntArray mKeyMap; + + private SparseArray mGameController = new SparseArray(); + + public GameControllerOuya(){ + mKeyMap = new SparseIntArray(20); + mKeyMap.put(OuyaController.BUTTON_A, GameControllerDelegate.BUTTON_B); + mKeyMap.put(OuyaController.BUTTON_O, GameControllerDelegate.BUTTON_A); + mKeyMap.put(OuyaController.BUTTON_U, GameControllerDelegate.BUTTON_X); + mKeyMap.put(OuyaController.BUTTON_Y, GameControllerDelegate.BUTTON_Y); mKeyMap.put(OuyaController.BUTTON_DPAD_DOWN, GameControllerDelegate.BUTTON_DPAD_DOWN); mKeyMap.put(OuyaController.BUTTON_DPAD_LEFT, GameControllerDelegate.BUTTON_DPAD_LEFT); mKeyMap.put(OuyaController.BUTTON_DPAD_RIGHT, GameControllerDelegate.BUTTON_DPAD_RIGHT); @@ -34,150 +34,142 @@ public GameControllerOuya(){ } public void onCreate(Context context) { - OuyaController.init(context); - /*GameControllerAdapter.addRunnableToFrameStartList(new Runnable() { - - @Override - public void run() { - OuyaController.startOfFrame(); - } - - });*/ + OuyaController.init(context); } private float mOldLeftThumbstickX = 0.0f; - private float mOldLeftThumbstickY = 0.0f; - private float mOldRightThumbstickX = 0.0f; - private float mOldRightThumbstickY = 0.0f; - + private float mOldLeftThumbstickY = 0.0f; + private float mOldRightThumbstickX = 0.0f; + private float mOldRightThumbstickY = 0.0f; + private float mOldLeftTrigger = 0.0f; - private float mOldRightTrigger = 0.0f; - + private float mOldRightTrigger = 0.0f; + public boolean dispatchGenericMotionEvent(MotionEvent event) { boolean handled = OuyaController.onGenericMotionEvent(event); if (handled && mControllerEventListener != null) { - int deviceId = event.getDeviceId(); - String deviceName = event.getDevice().getName(); - OuyaController c = OuyaController.getControllerByDeviceId(deviceId); - if (mGameController.get(deviceId) == null) { - GameControllerHelper.gatherControllers(mGameController); - mGameController.append(deviceId, deviceName); - } - - float newLeftTrigger = c.getAxisValue(OuyaController.AXIS_L2); - if (Float.compare(newLeftTrigger, mOldLeftTrigger) != 0) { - mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, newLeftTrigger, true); - mOldLeftTrigger = newLeftTrigger; - } - - float newRightTrigger = c.getAxisValue(OuyaController.AXIS_R2); - if (Float.compare(newRightTrigger, mOldRightTrigger) != 0) { - mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newRightTrigger, true); - mOldRightTrigger = newRightTrigger; - } - - float newLeftThumbstickX = c.getAxisValue(OuyaController.AXIS_LS_X); - if (Float.compare(newLeftThumbstickX, mOldLeftThumbstickX) != 0) { - if (Float.compare(newLeftThumbstickX, 0.0f) == 0) { - mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_X, 0.0f, true); - }else { - mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_X, newLeftThumbstickX, true); - } - mOldLeftThumbstickX = newLeftThumbstickX; - } - - float newLeftThumbstickY = c.getAxisValue(OuyaController.AXIS_LS_Y); - if (Float.compare(newLeftThumbstickY, mOldLeftThumbstickY) != 0) { - if (Float.compare(newLeftThumbstickY, 0.0f) == 0) { - mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_Y, 0.0f, true); - }else { - mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_Y, newLeftThumbstickY, true); - } - mOldLeftThumbstickY = newLeftThumbstickY; - } - - float newRightThumbstickX = c.getAxisValue(OuyaController.AXIS_RS_X); - if (Float.compare(newRightThumbstickX, mOldRightThumbstickX) != 0) { - if (Float.compare(newRightThumbstickX, 0.0f) == 0) { - mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_X, 0.0f, true); - }else { - mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_X, newRightThumbstickX, true); - } - mOldRightThumbstickX = newRightThumbstickX; - } - - float newRightThumbstickY = c.getAxisValue(OuyaController.AXIS_RS_Y); - if (Float.compare(newRightThumbstickY, mOldRightThumbstickY) != 0) { - if (Float.compare(newRightThumbstickY, 0.0f) == 0) { - mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, 0.0f, true); - }else { - mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, newRightThumbstickY, true); - } - mOldRightThumbstickY = newRightThumbstickY; - } + int deviceId = event.getDeviceId(); + String deviceName = event.getDevice().getName(); + OuyaController c = OuyaController.getControllerByDeviceId(deviceId); + if (mGameController.get(deviceId) == null) { + GameControllerHelper.gatherControllers(mGameController); + mGameController.append(deviceId, deviceName); + } + + float newLeftTrigger = c.getAxisValue(OuyaController.AXIS_L2); + if (Float.compare(newLeftTrigger, mOldLeftTrigger) != 0) { + mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_LEFT_TRIGGER, newLeftTrigger, true); + mOldLeftTrigger = newLeftTrigger; + } + + float newRightTrigger = c.getAxisValue(OuyaController.AXIS_R2); + if (Float.compare(newRightTrigger, mOldRightTrigger) != 0) { + mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.BUTTON_RIGHT_TRIGGER, newRightTrigger, true); + mOldRightTrigger = newRightTrigger; + } + + float newLeftThumbstickX = c.getAxisValue(OuyaController.AXIS_LS_X); + if (Float.compare(newLeftThumbstickX, mOldLeftThumbstickX) != 0) { + if (Float.compare(newLeftThumbstickX, 0.0f) == 0) { + mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_X, 0.0f, true); + }else { + mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_X, newLeftThumbstickX, true); + } + mOldLeftThumbstickX = newLeftThumbstickX; + } + + float newLeftThumbstickY = c.getAxisValue(OuyaController.AXIS_LS_Y); + if (Float.compare(newLeftThumbstickY, mOldLeftThumbstickY) != 0) { + if (Float.compare(newLeftThumbstickY, 0.0f) == 0) { + mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_Y, 0.0f, true); + }else { + mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_LEFT_Y, newLeftThumbstickY, true); + } + mOldLeftThumbstickY = newLeftThumbstickY; + } + + float newRightThumbstickX = c.getAxisValue(OuyaController.AXIS_RS_X); + if (Float.compare(newRightThumbstickX, mOldRightThumbstickX) != 0) { + if (Float.compare(newRightThumbstickX, 0.0f) == 0) { + mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_X, 0.0f, true); + }else { + mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_X, newRightThumbstickX, true); + } + mOldRightThumbstickX = newRightThumbstickX; + } + + float newRightThumbstickY = c.getAxisValue(OuyaController.AXIS_RS_Y); + if (Float.compare(newRightThumbstickY, mOldRightThumbstickY) != 0) { + if (Float.compare(newRightThumbstickY, 0.0f) == 0) { + mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, 0.0f, true); + }else { + mControllerEventListener.onAxisEvent(deviceName, deviceId, GameControllerDelegate.THUMBSTICK_RIGHT_Y, newRightThumbstickY, true); + } + mOldRightThumbstickY = newRightThumbstickY; + } } return handled; } public boolean dispatchKeyEvent(KeyEvent event) { - boolean handled = false; - - int action = event.getAction(); - int keyCode = event.getKeyCode(); - - if (action == KeyEvent.ACTION_DOWN) { - handled = OuyaController.onKeyDown(keyCode, event); - } - else if (action == KeyEvent.ACTION_UP) { - handled = OuyaController.onKeyUp(keyCode, event); - } - - if (handled && mControllerEventListener != null) { - boolean isAnalog = false; - - if (keyCode == KeyEvent.KEYCODE_BUTTON_THUMBL || keyCode == KeyEvent.KEYCODE_BUTTON_THUMBR){ - isAnalog = true; - } - - int deviceId = event.getDeviceId(); - String deviceName = event.getDevice().getName(); - - if (mGameController.get(deviceId) == null) { - GameControllerHelper.gatherControllers(mGameController); - mGameController.append(deviceId, deviceName); - } - if (action == KeyEvent.ACTION_DOWN) { - mControllerEventListener.onButtonEvent(deviceName, deviceId, mKeyMap.get(keyCode), true, 1.0f, isAnalog); - }else { - mControllerEventListener.onButtonEvent(deviceName, deviceId, mKeyMap.get(keyCode), false, 0.0f, isAnalog); - } - } - - return handled; + boolean handled = false; + + int action = event.getAction(); + int keyCode = event.getKeyCode(); + + if (action == KeyEvent.ACTION_DOWN) { + handled = OuyaController.onKeyDown(keyCode, event); + } + else if (action == KeyEvent.ACTION_UP) { + handled = OuyaController.onKeyUp(keyCode, event); + } + + if (handled && mControllerEventListener != null) { + boolean isAnalog = false; + + if (keyCode == KeyEvent.KEYCODE_BUTTON_THUMBL || keyCode == KeyEvent.KEYCODE_BUTTON_THUMBR){ + isAnalog = true; + } + + int deviceId = event.getDeviceId(); + String deviceName = event.getDevice().getName(); + + if (mGameController.get(deviceId) == null) { + GameControllerHelper.gatherControllers(mGameController); + mGameController.append(deviceId, deviceName); + } + if (action == KeyEvent.ACTION_DOWN) { + mControllerEventListener.onButtonEvent(deviceName, deviceId, mKeyMap.get(keyCode), true, 1.0f, isAnalog); + }else { + mControllerEventListener.onButtonEvent(deviceName, deviceId, mKeyMap.get(keyCode), false, 0.0f, isAnalog); + } + } + + return handled; } - public void onPause() { + public void onPause() { // show the mouse cursor OuyaController.showCursor(true); - } - - public void onResume() { + } + + public void onResume() { // hide the mouse cursor OuyaController.showCursor(false); - } - - public void onDestroy() { - - } + } + + public void onDestroy() { + + } - private ControllerEventListener mControllerEventListener; - - @Override - public void setControllerEventListener(ControllerEventListener listener) { - mControllerEventListener = listener; - } - + private ControllerEventListener mControllerEventListener; + + @Override + public void setControllerEventListener(ControllerEventListener listener) { + mControllerEventListener = listener; + } + } diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java index cf8d82670f62..5e27b4c0c6f9 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java @@ -44,7 +44,6 @@ of this software and associated documentation files (the "Software"), to deal import android.util.Log; import android.view.ViewGroup; import android.widget.FrameLayout; -import android.opengl.GLSurfaceView; public abstract class Cocos2dxActivity extends Activity implements Cocos2dxHelperListener { // =========================================================== @@ -213,7 +212,7 @@ protected void onLoadNativeLibraries() { // =========================================================== // Constructors // =========================================================== - + @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -252,17 +251,25 @@ protected void onCreate(final Bundle savedInstanceState) { @Override protected void onResume() { super.onResume(); - - Cocos2dxHelper.onResume(); - this.mGLSurfaceView.onResume(); + } + + @Override + public void onWindowFocusChanged(boolean hasFocus) { + super.onWindowFocusChanged(hasFocus); + + if (hasFocus) { + Cocos2dxHelper.onResume(); + mGLSurfaceView.onResume(); + } + else { + Cocos2dxHelper.onPause(); + mGLSurfaceView.onPause(); + } } @Override protected void onPause() { super.onPause(); - - Cocos2dxHelper.onPause(); - this.mGLSurfaceView.onPause(); } @Override diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java index 6eefcd775aee..867e94206376 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHelper.java @@ -49,7 +49,7 @@ of this software and associated documentation files (the "Software"), to deal import android.util.Log; //Enhance API modification import android.view.Display; import android.view.WindowManager; -import android.content.ServiceConnection; //Enhance API modification +import android.content.ServiceConnection; //Enhance API modification import com.enhance.gameservice.IGameTuningService; //Enhance API modification diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java index 00ddc97845ac..9c7a2a7a6456 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxHttpURLConnection.java @@ -144,7 +144,7 @@ static void setVerifySSL(HttpURLConnection urlConnection, String sslFilename) { } } - //Add header + //Add header static void addRequestHeader(HttpURLConnection urlConnection, String key, String value) { urlConnection.setRequestProperty(key, value); } @@ -181,7 +181,7 @@ static void sendRequest(HttpURLConnection http, byte[] byteArray) { } static String getResponseHeaders(HttpURLConnection http) { - Map> headers = http.getHeaderFields(); + Map> headers = http.getHeaderFields(); if (null == headers) { return null; } diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxJavascriptJavaBridge.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxJavascriptJavaBridge.java index 996bda03c2e5..9c7cf963598e 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxJavascriptJavaBridge.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxJavascriptJavaBridge.java @@ -23,5 +23,5 @@ package org.cocos2dx.lib; public class Cocos2dxJavascriptJavaBridge { - public static native int evalString(String value); + public static native int evalString(String value); } diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java index 70264590df67..7a1b0d320485 100644 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxRenderer.java @@ -147,12 +147,12 @@ public void handleKeyUp(final int keyCode) { } public void handleOnPause() { - /** - * onPause may be invoked before onSurfaceCreated, - * and engine will be initialized correctly after - * onSurfaceCreated is invoked. Can not invoke any - * native method before onSurfaceCreated is invoked - */ + /** + * onPause may be invoked before onSurfaceCreated, + * and engine will be initialized correctly after + * onSurfaceCreated is invoked. Can not invoke any + * native method before onSurfaceCreated is invoked + */ if (! mNativeInitCompleted) return; diff --git a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java index 5160f680db5e..ff9105fdbb0d 100755 --- a/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java +++ b/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxWebViewHelper.java @@ -126,7 +126,7 @@ public static void loadData(final int index, final String data, final String mim public void run() { Cocos2dxWebView webView = webViews.get(index); if (webView != null) { - webView.loadDataWithBaseURL(baseURL, data, mimeType, encoding, null); + webView.loadDataWithBaseURL(baseURL, data, mimeType, encoding, null); } } }); @@ -138,7 +138,7 @@ public static void loadHTMLString(final int index, final String data, final Stri public void run() { Cocos2dxWebView webView = webViews.get(index); if (webView != null) { - webView.loadDataWithBaseURL(baseUrl, data, null, null, null); + webView.loadDataWithBaseURL(baseUrl, data, null, null, null); } } }); diff --git a/cocos/platform/apple/CCFileUtils-apple.h b/cocos/platform/apple/CCFileUtils-apple.h index 9838947bfc80..dd1fc94bcc24 100644 --- a/cocos/platform/apple/CCFileUtils-apple.h +++ b/cocos/platform/apple/CCFileUtils-apple.h @@ -50,13 +50,15 @@ class CC_DLL FileUtilsApple : public FileUtils virtual std::string getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const override; virtual ValueMap getValueMapFromFile(const std::string& filename) override; - virtual ValueMap getValueMapFromData(const char* filedata, int filesize); + virtual ValueMap getValueMapFromData(const char* filedata, int filesize)override; virtual bool writeToFile(ValueMap& dict, const std::string& fullPath) override; virtual ValueVector getValueVectorFromFile(const std::string& filename) override; void setBundle(NSBundle* bundle); private: virtual bool isFileExistInternal(const std::string& filePath) const override; + virtual bool removeDirectory(const std::string& dirPath) override; + NSBundle* getBundle() const; NSBundle* _bundle; }; diff --git a/cocos/platform/apple/CCFileUtils-apple.mm b/cocos/platform/apple/CCFileUtils-apple.mm index e56b5a2e8b7a..d4aa2e76dfbf 100644 --- a/cocos/platform/apple/CCFileUtils-apple.mm +++ b/cocos/platform/apple/CCFileUtils-apple.mm @@ -27,6 +27,8 @@ of this software and associated documentation files (the "Software"), to deal #include "CCFileUtils-apple.h" +#include + #include #include @@ -392,6 +394,31 @@ static void addObjectToNSDict(const std::string& key, const Value& value, NSMuta return ret; } +static int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) +{ + auto ret = remove(fpath); + if (ret) + { + log("Fail to remove: %s ",fpath); + } + + return ret; +} + +bool FileUtilsApple::removeDirectory(const std::string& path) +{ + if (path.size() > 0 && path[path.size() - 1] != '/') + { + CCLOGERROR("Fail to remove directory, path must termniate with '/': %s", path.c_str()); + return false; + } + + if (nftw(path.c_str(),unlink_cb, 64, FTW_DEPTH | FTW_PHYS)) + return false; + else + return true; +} + std::string FileUtilsApple::getFullPathForDirectoryAndFilename(const std::string& directory, const std::string& filename) const { if (directory[0] != '/') diff --git a/cocos/platform/linux/CCFileUtils-linux.cpp b/cocos/platform/linux/CCFileUtils-linux.cpp index f2d7335af2b3..cd915e940dda 100644 --- a/cocos/platform/linux/CCFileUtils-linux.cpp +++ b/cocos/platform/linux/CCFileUtils-linux.cpp @@ -35,6 +35,7 @@ THE SOFTWARE. #include #include #include +#include #ifndef CC_RESOURCE_FOLDER_LINUX #define CC_RESOURCE_FOLDER_LINUX ("/Resources/") diff --git a/cocos/platform/linux/CCFileUtils-linux.h b/cocos/platform/linux/CCFileUtils-linux.h index 89b38d57021d..2cddbb5ecb8d 100644 --- a/cocos/platform/linux/CCFileUtils-linux.h +++ b/cocos/platform/linux/CCFileUtils-linux.h @@ -52,7 +52,7 @@ class CC_DLL FileUtilsLinux : public FileUtils bool init(); virtual std::string getWritablePath() const; private: - virtual bool isFileExistInternal(const std::string& strFilePath) const; + virtual bool isFileExistInternal(const std::string& strFilePath) const override; }; // end of platform group diff --git a/cocos/platform/win32/CCFileUtils-win32.cpp b/cocos/platform/win32/CCFileUtils-win32.cpp index 31bccff66688..b27b725c3a42 100644 --- a/cocos/platform/win32/CCFileUtils-win32.cpp +++ b/cocos/platform/win32/CCFileUtils-win32.cpp @@ -30,6 +30,7 @@ THE SOFTWARE. #include "platform/CCCommon.h" #include #include +#include using namespace std; @@ -56,6 +57,81 @@ static inline std::string convertPathFormatToUnixStyle(const std::string& path) return ret; } +static std::wstring StringUtf8ToWideChar(const std::string& strUtf8) +{ + std::wstring ret; + if (!strUtf8.empty()) + { + int nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, nullptr, 0); + if (nNum) + { + WCHAR* wideCharString = new WCHAR[nNum + 1]; + wideCharString[0] = 0; + + nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, wideCharString, nNum + 1); + + ret = wideCharString; + delete[] wideCharString; + } + else + { + CCLOG("Wrong convert to WideChar code:0x%x", GetLastError()); + } + } + return ret; +} + +static std::string StringWideCharToUtf8(const std::wstring& strWideChar) +{ + std::string ret; + if (!strWideChar.empty()) + { + int nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE); + if (nNum) + { + char* utf8String = new char[nNum + 1]; + utf8String[0] = 0; + + nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, utf8String, nNum + 1, nullptr, FALSE); + + ret = utf8String; + delete[] utf8String; + } + else + { + CCLOG("Wrong convert to Utf8 code:0x%x", GetLastError()); + } + } + + return ret; +} + +static std::string UTF8StringToMultiByte(const std::string& strUtf8) +{ + std::string ret; + if (!strUtf8.empty()) + { + std::wstring strWideChar = StringUtf8ToWideChar(strUtf8); + int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE); + if (nNum) + { + char* ansiString = new char[nNum + 1]; + ansiString[0] = 0; + + nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, ansiString, nNum + 1, nullptr, FALSE); + + ret = ansiString; + delete[] ansiString; + } + else + { + CCLOG("Wrong convert to Ansi code:0x%x", GetLastError()); + } + } + + return ret; +} + static void _checkPath() { if (0 == s_resourcePath.length()) @@ -99,6 +175,22 @@ bool FileUtilsWin32::init() return FileUtils::init(); } +bool FileUtilsWin32::isDirectoryExistInternal(const std::string& dirPath) const +{ + unsigned long fAttrib = GetFileAttributes(StringUtf8ToWideChar(dirPath).c_str()); + if (fAttrib != INVALID_FILE_ATTRIBUTES && + (fAttrib & FILE_ATTRIBUTE_DIRECTORY)) + { + return true; + } + return false; +} + +std::string FileUtilsWin32::getSuitableFOpen(const std::string& filenameUtf8) const +{ + return UTF8StringToMultiByte(filenameUtf8); +} + bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const { if (0 == strFilePath.length()) @@ -112,10 +204,7 @@ bool FileUtilsWin32::isFileExistInternal(const std::string& strFilePath) const strPath.insert(0, _defaultResRootPath); } - WCHAR utf16Buf[CC_MAX_PATH] = {0}; - MultiByteToWideChar(CP_UTF8, 0, strPath.c_str(), -1, utf16Buf, sizeof(utf16Buf)/sizeof(utf16Buf[0])); - - DWORD attr = GetFileAttributesW(utf16Buf); + DWORD attr = GetFileAttributesW(StringUtf8ToWideChar(strPath).c_str()); if(attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY)) return false; // not a file return true; @@ -162,7 +251,6 @@ static bool checkFileName(const std::string& fullPath, const std::string& filena CCLOG("%s", msg.c_str()); return false; } - } else { @@ -193,12 +281,9 @@ static Data getData(const std::string& filename, bool forString) std::string fullPath = FileUtils::getInstance()->fullPathForFilename(filename); // check if the filename uses correct case characters - CC_BREAK_IF(!checkFileName(fullPath, filename)); + checkFileName(fullPath, filename); - WCHAR wszBuf[CC_MAX_PATH] = {0}; - MultiByteToWideChar(CP_UTF8, 0, fullPath.c_str(), -1, wszBuf, sizeof(wszBuf)/sizeof(wszBuf[0])); - - HANDLE fileHandle = ::CreateFileW(wszBuf, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr); + HANDLE fileHandle = ::CreateFile(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr); CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE); size = ::GetFileSize(fileHandle, nullptr); @@ -278,12 +363,9 @@ unsigned char* FileUtilsWin32::getFileData(const std::string& filename, const ch std::string fullPath = fullPathForFilename(filename); // check if the filename uses correct case characters - CC_BREAK_IF(!checkFileName(fullPath, filename)); - - WCHAR wszBuf[CC_MAX_PATH] = {0}; - MultiByteToWideChar(CP_UTF8, 0, fullPath.c_str(), -1, wszBuf, sizeof(wszBuf)/sizeof(wszBuf[0])); + checkFileName(fullPath, filename); - HANDLE fileHandle = ::CreateFileW(wszBuf, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr); + HANDLE fileHandle = ::CreateFile(StringUtf8ToWideChar(fullPath).c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, nullptr); CC_BREAK_IF(fileHandle == INVALID_HANDLE_VALUE); *size = ::GetFileSize(fileHandle, nullptr); @@ -340,49 +422,191 @@ string FileUtilsWin32::getWritablePath() const } // Get full path of executable, e.g. c:\Program Files (x86)\My Game Folder\MyGame.exe - char full_path[CC_MAX_PATH + 1]; - ::GetModuleFileNameA(nullptr, full_path, CC_MAX_PATH + 1); + WCHAR full_path[CC_MAX_PATH + 1] = { 0 }; + ::GetModuleFileName(nullptr, full_path, CC_MAX_PATH + 1); // Debug app uses executable directory; Non-debug app uses local app data directory //#ifndef _DEBUG - // Get filename of executable only, e.g. MyGame.exe - char *base_name = strrchr(full_path, '\\'); + // Get filename of executable only, e.g. MyGame.exe + WCHAR *base_name = wcsrchr(full_path, '\\'); + wstring retPath; + if(base_name) + { + WCHAR app_data_path[CC_MAX_PATH + 1]; - if(base_name) + // Get local app data directory, e.g. C:\Documents and Settings\username\Local Settings\Application Data + if (SUCCEEDED(SHGetFolderPath(nullptr, CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, app_data_path))) { - char app_data_path[CC_MAX_PATH + 1]; + wstring ret(app_data_path); + + // Adding executable filename, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame.exe + ret += base_name; - // Get local app data directory, e.g. C:\Documents and Settings\username\Local Settings\Application Data - if (SUCCEEDED(SHGetFolderPathA(nullptr, CSIDL_LOCAL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, app_data_path))) + // Remove ".exe" extension, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame + ret = ret.substr(0, ret.rfind(L".")); + + ret += L"\\"; + + // Create directory + if (SUCCEEDED(SHCreateDirectoryEx(nullptr, ret.c_str(), nullptr))) { - string ret((char*)app_data_path); + retPath = ret; + } + } + } + if (retPath.empty()) +//#endif // not defined _DEBUG + { + // If fetching of local app data directory fails, use the executable one + retPath = full_path; + + // remove xxx.exe + retPath = retPath.substr(0, retPath.rfind(L"\\") + 1); + } + + return convertPathFormatToUnixStyle(StringWideCharToUtf8(retPath)); +} + +bool FileUtilsWin32::renameFile(const std::string &path, const std::string &oldname, const std::string &name) +{ + CCASSERT(!path.empty(), "Invalid path"); + std::string oldPath = path + oldname; + std::string newPath = path + name; - // Adding executable filename, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame.exe - ret += base_name; + std::regex pat("\\/"); + std::string _old = std::regex_replace(oldPath, pat, "\\"); + std::string _new = std::regex_replace(newPath, pat, "\\"); - // Remove ".exe" extension, e.g. C:\Documents and Settings\username\Local Settings\Application Data\MyGame - ret = ret.substr(0, ret.rfind(".")); + std::wstring _wNew = StringUtf8ToWideChar(_new); - ret += "\\"; + if (FileUtils::getInstance()->isFileExist(_new)) + { + if (!DeleteFile(_wNew.c_str())) + { + CCLOGERROR("Fail to delete file %s !Error code is 0x%x", newPath.c_str(), GetLastError()); + } + } - // Create directory - if (SUCCEEDED(SHCreateDirectoryExA(nullptr, ret.c_str(), nullptr))) + if (MoveFile(StringUtf8ToWideChar(_old).c_str(), _wNew.c_str())) + { + return true; + } + else + { + CCLOGERROR("Fail to rename file %s to %s !Error code is 0x%x", oldPath.c_str(), newPath.c_str(), GetLastError()); + return false; + } +} + +bool FileUtilsWin32::createDirectory(const std::string& dirPath) +{ + CCASSERT(!dirPath.empty(), "Invalid path"); + + if (isDirectoryExist(dirPath)) + return true; + + std::wstring path = StringUtf8ToWideChar(dirPath); + + // Split the path + size_t start = 0; + size_t found = path.find_first_of(L"/\\", start); + std::wstring subpath; + std::vector dirs; + + if (found != std::wstring::npos) + { + while (true) + { + subpath = path.substr(start, found - start + 1); + if (!subpath.empty()) + dirs.push_back(subpath); + start = found + 1; + found = path.find_first_of(L"/\\", start); + if (found == std::wstring::npos) + { + if (start < path.length()) { - return convertPathFormatToUnixStyle(ret); + dirs.push_back(path.substr(start)); } + break; } } -//#endif // not defined _DEBUG + } - // If fetching of local app data directory fails, use the executable one - string ret((char*)full_path); + if ((GetFileAttributes(path.c_str())) == INVALID_FILE_ATTRIBUTES) + { + subpath = L""; + for (unsigned int i = 0; i < dirs.size(); ++i) + { + subpath += dirs[i]; - // remove xxx.exe - ret = ret.substr(0, ret.rfind("\\") + 1); + std::string utf8Path = StringWideCharToUtf8(subpath); + if (!isDirectoryExist(utf8Path)) + { + BOOL ret = CreateDirectory(subpath.c_str(), NULL); + if (!ret && ERROR_ALREADY_EXISTS != GetLastError()) + { + CCLOGERROR("Fail create directory %s !Error code is 0x%x", utf8Path.c_str(), GetLastError()); + return false; + } + } + } + } + return true; +} - ret = convertPathFormatToUnixStyle(ret); +bool FileUtilsWin32::removeFile(const std::string &filepath) +{ + std::regex pat("\\/"); + std::string win32path = std::regex_replace(filepath, pat, "\\"); - return ret; + if (DeleteFile(StringUtf8ToWideChar(win32path).c_str())) + { + return true; + } + else + { + CCLOGERROR("Fail remove file %s !Error code is 0x%x", filepath.c_str(), GetLastError()); + return false; + } +} + +bool FileUtilsWin32::removeDirectory(const std::string& dirPath) +{ + std::wstring wpath = StringUtf8ToWideChar(dirPath); + std::wstring files = wpath + L"*.*"; + WIN32_FIND_DATA wfd; + HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0); + bool ret = true; + if (search != INVALID_HANDLE_VALUE) + { + BOOL find = true; + while (find) + { + //. .. + if (wfd.cFileName[0] != '.') + { + std::wstring temp = wpath + wfd.cFileName; + if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + temp += '/'; + ret = ret && this->removeDirectory(StringWideCharToUtf8(temp)); + } + else + { + SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL); + ret = ret && DeleteFile(temp.c_str()); + } + } + find = FindNextFile(search, &wfd); + } + FindClose(search); + } + if (ret && RemoveDirectory(wpath.c_str())) + { + return true; + } + return false; } NS_CC_END diff --git a/cocos/platform/win32/CCFileUtils-win32.h b/cocos/platform/win32/CCFileUtils-win32.h index 17f6c1ec01b8..fdb57df7ab37 100644 --- a/cocos/platform/win32/CCFileUtils-win32.h +++ b/cocos/platform/win32/CCFileUtils-win32.h @@ -49,11 +49,53 @@ class CC_DLL FileUtilsWin32 : public FileUtils public: /* override funtions */ bool init(); - virtual std::string getWritablePath() const; - virtual bool isAbsolutePath(const std::string& strPath) const; + virtual std::string getWritablePath() const override; + virtual bool isAbsolutePath(const std::string& strPath) const override; + virtual std::string getSuitableFOpen(const std::string& filenameUtf8) const override; protected: - virtual bool isFileExistInternal(const std::string& strFilePath) const; + virtual bool isFileExistInternal(const std::string& strFilePath) const override; + + /** + * Renames a file under the given directory. + * + * @param path The parent directory path of the file, it must be an absolute path. + * @param oldname The current name of the file. + * @param name The new name of the file. + * @return True if the file have been renamed successfully, false if not. + */ + virtual bool renameFile(const std::string &path, const std::string &oldname, const std::string &name) override; + + /** + * Checks whether a directory exists without considering search paths and resolution orders. + * @param dirPath The directory (with absolute path) to look up for + * @return Returns true if the directory found at the given absolute path, otherwise returns false + */ + virtual bool isDirectoryExistInternal(const std::string& dirPath) const override; + + /** + * Removes a file. + * + * @param filepath The full path of the file, it must be an absolute path. + * @return True if the file have been removed successfully, false if not. + */ + virtual bool removeFile(const std::string &filepath) override; + + /** + * Creates a directory. + * + * @param dirPath The path of the directory, it must be an absolute path. + * @return True if the directory have been created successfully, false if not. + */ + virtual bool createDirectory(const std::string& dirPath) override; + + /** + * Removes a directory. + * + * @param dirPath The full path of the directory, it must be an absolute path. + * @return True if the directory have been removed successfully, false if not. + */ + virtual bool removeDirectory(const std::string& dirPath) override; /** * Gets resource file data @@ -64,7 +106,7 @@ class CC_DLL FileUtilsWin32 : public FileUtils * @return Upon success, a pointer to the data is returned, otherwise NULL. * @warning Recall: you are responsible for calling delete[] on any Non-NULL pointer returned. */ - virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t * size) override; + CC_DEPRECATED_ATTRIBUTE virtual unsigned char* getFileData(const std::string& filename, const char* mode, ssize_t * size) override; /** * Gets string from a file. diff --git a/cocos/platform/winrt/CCFileUtilsWinRT.cpp b/cocos/platform/winrt/CCFileUtilsWinRT.cpp index 4b8c68a5936c..5a474b83fbc5 100644 --- a/cocos/platform/winrt/CCFileUtilsWinRT.cpp +++ b/cocos/platform/winrt/CCFileUtilsWinRT.cpp @@ -23,9 +23,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "CCFileUtilsWinRT.h" +#include #include "CCWinRTUtils.h" #include "platform/CCCommon.h" - using namespace std; NS_CC_BEGIN @@ -47,6 +47,80 @@ static inline std::string convertPathFormatToUnixStyle(const std::string& path) return ret; } +static std::wstring StringUtf8ToWideChar(const std::string& strUtf8) +{ + std::wstring ret; + if (!strUtf8.empty()) + { + int nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, nullptr, 0); + if (nNum) + { + WCHAR* wideCharString = new WCHAR[nNum + 1]; + wideCharString[0] = 0; + + nNum = MultiByteToWideChar(CP_UTF8, 0, strUtf8.c_str(), -1, wideCharString, nNum + 1); + + ret = wideCharString; + delete[] wideCharString; + } + else + { + CCLOG("Wrong convert to WideChar code:0x%x", GetLastError()); + } + } + return ret; +} + +static std::string StringWideCharToUtf8(const std::wstring& strWideChar) +{ + std::string ret; + if (!strWideChar.empty()) + { + int nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE); + if (nNum) + { + char* utf8String = new char[nNum + 1]; + utf8String[0] = 0; + + nNum = WideCharToMultiByte(CP_UTF8, 0, strWideChar.c_str(), -1, utf8String, nNum + 1, nullptr, FALSE); + + ret = utf8String; + delete[] utf8String; + } + else + { + CCLOG("Wrong convert to Utf8 code:0x%x", GetLastError()); + } + } + + return ret; +} + +static std::string UTF8StringToMultiByte(const std::string& strUtf8) +{ + std::string ret; + if (!strUtf8.empty()) + { + std::wstring strWideChar = StringUtf8ToWideChar(strUtf8); + int nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, nullptr, 0, nullptr, FALSE); + if (nNum) + { + char* ansiString = new char[nNum + 1]; + ansiString[0] = 0; + + nNum = WideCharToMultiByte(CP_ACP, 0, strWideChar.c_str(), -1, ansiString, nNum + 1, nullptr, FALSE); + + ret = ansiString; + delete[] ansiString; + } + else + { + CCLOG("Wrong convert to Ansi code:0x%x", GetLastError()); + } + } + + return ret; +} static void _checkPath() { @@ -72,7 +146,6 @@ FileUtils* FileUtils::getInstance() return s_sharedFileUtils; } - CCFileUtilsWinRT::CCFileUtilsWinRT() { } @@ -100,6 +173,11 @@ std::string CCFileUtilsWinRT::getFullPathForDirectoryAndFilename(const std::stri return FileUtils::getFullPathForDirectoryAndFilename(unixDirectory, unixFilename); } +std::string CCFileUtilsWinRT::getSuitableFOpen(const std::string& filenameUtf8) const +{ + return UTF8StringToMultiByte(filenameUtf8); +} + bool CCFileUtilsWinRT::isFileExistInternal(const std::string& strFilePath) const { bool ret = false; @@ -121,6 +199,110 @@ bool CCFileUtilsWinRT::isFileExistInternal(const std::string& strFilePath) const return ret; } +bool CCFileUtilsWinRT::isDirectoryExistInternal(const std::string& dirPath) const +{ + WIN32_FILE_ATTRIBUTE_DATA wfad; + std::wstring wdirPath(dirPath.begin(), dirPath.end()); + if (GetFileAttributesEx(wdirPath.c_str(), GetFileExInfoStandard, &wfad)) + { + return true; + } + return false; +} + +bool CCFileUtilsWinRT::createDirectory(const std::string& path) +{ + CCASSERT(!path.empty(), "Invalid path"); + + if (isDirectoryExist(path)) + return true; + + // Split the path + size_t start = 0; + size_t found = path.find_first_of("/\\", start); + std::string subpath; + std::vector dirs; + + if (found != std::string::npos) + { + while (true) + { + subpath = path.substr(start, found - start + 1); + if (!subpath.empty()) + dirs.push_back(subpath); + start = found + 1; + found = path.find_first_of("/\\", start); + if (found == std::string::npos) + { + if (start < path.length()) + { + dirs.push_back(path.substr(start)); + } + break; + } + } + } + + WIN32_FILE_ATTRIBUTE_DATA wfad; + std::wstring wpath(path.begin(), path.end()); + if (!(GetFileAttributesEx(wpath.c_str(), GetFileExInfoStandard, &wfad))) + { + subpath = ""; + for (unsigned int i = 0; i < dirs.size(); ++i) + { + subpath += dirs[i]; + if (i > 0 && !isDirectoryExist(subpath)) + { + std::wstring wsubpath(subpath.begin(), subpath.end()); + BOOL ret = CreateDirectory(wsubpath.c_str(), NULL); + if (!ret && ERROR_ALREADY_EXISTS != GetLastError()) + { + return false; + } + } + } + } + return true; +} + +bool CCFileUtilsWinRT::removeDirectory(const std::string& path) +{ + std::wstring wpath = std::wstring(path.begin(), path.end()); + std::wstring files = wpath + L"*.*"; + WIN32_FIND_DATA wfd; + HANDLE search = FindFirstFileEx(files.c_str(), FindExInfoStandard, &wfd, FindExSearchNameMatch, NULL, 0); + bool ret = true; + if (search != INVALID_HANDLE_VALUE) + { + BOOL find = true; + while (find) + { + //. .. + if (wfd.cFileName[0] != '.') + { + std::wstring temp = wpath + wfd.cFileName; + if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + temp += '/'; + ret = ret && this->removeDirectory(std::string(temp.begin(), temp.end())); + } + else + { + SetFileAttributes(temp.c_str(), FILE_ATTRIBUTE_NORMAL); + ret = ret && DeleteFile(temp.c_str()); + } + } + find = FindNextFile(search, &wfd); + } + FindClose(search); + } + if (ret && RemoveDirectory(wpath.c_str())) + { + return true; + } + return false; +} + bool CCFileUtilsWinRT::isAbsolutePath(const std::string& strPath) const { if ( strPath.length() > 2 @@ -132,6 +314,34 @@ bool CCFileUtilsWinRT::isAbsolutePath(const std::string& strPath) const return false; } +bool CCFileUtilsWinRT::removeFile(const std::string &path) +{ + std::wstring wpath(path.begin(), path.end()); + if (DeleteFile(wpath.c_str())) + { + return true; + } + return false; +} + +bool CCFileUtilsWinRT::renameFile(const std::string &path, const std::string &oldname, const std::string &name) +{ + CCASSERT(!path.empty(), "Invalid path"); + std::string oldPath = path + oldname; + std::string newPath = path + name; + + std::regex pat("\\/"); + std::string _old = std::regex_replace(oldPath, pat, "\\"); + std::string _new = std::regex_replace(newPath, pat, "\\"); + if (MoveFileEx(std::wstring(_old.begin(), _old.end()).c_str(), + std::wstring(_new.begin(), _new.end()).c_str(), + MOVEFILE_REPLACE_EXISTING & MOVEFILE_WRITE_THROUGH)) + { + return true; + } + return false; +} + static Data getData(const std::string& filename, bool forString) { if (filename.empty()) diff --git a/cocos/platform/winrt/CCFileUtilsWinRT.h b/cocos/platform/winrt/CCFileUtilsWinRT.h index 90b450a084da..e6db42abe4b9 100644 --- a/cocos/platform/winrt/CCFileUtilsWinRT.h +++ b/cocos/platform/winrt/CCFileUtilsWinRT.h @@ -49,13 +49,55 @@ class CC_DLL CCFileUtilsWinRT : public FileUtils bool init(); virtual std::string getWritablePath() const; virtual bool isAbsolutePath(const std::string& strPath) const; - virtual std::string getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) const override; + virtual std::string getPathForFilename(const std::string& filename, const std::string& resolutionDirectory, const std::string& searchPath) const override; virtual std::string getFullPathForDirectoryAndFilename(const std::string& strDirectory, const std::string& strFilename) const override; virtual std::string getStringFromFile(const std::string& filename) override; + virtual std::string getSuitableFOpen(const std::string& filenameUtf8) const override; static std::string getAppPath(); private: - virtual bool isFileExistInternal(const std::string& strFilePath) const; + virtual bool isFileExistInternal(const std::string& strFilePath) const override; + + /** + * Renames a file under the given directory. + * + * @param path The parent directory path of the file, it must be an absolute path. + * @param oldname The current name of the file. + * @param name The new name of the file. + * @return True if the file have been renamed successfully, false if not. + */ + virtual bool renameFile(const std::string &path, const std::string &oldname, const std::string &name) override; + + /** + * Checks whether a directory exists without considering search paths and resolution orders. + * @param dirPath The directory (with absolute path) to look up for + * @return Returns true if the directory found at the given absolute path, otherwise returns false + */ + virtual bool isDirectoryExistInternal(const std::string& dirPath) const override; + + /** + * Removes a file. + * + * @param filepath The full path of the file, it must be an absolute path. + * @return True if the file have been removed successfully, false if not. + */ + virtual bool removeFile(const std::string &filepath) override; + + /** + * Creates a directory. + * + * @param dirPath The path of the directory, it must be an absolute path. + * @return True if the directory have been created successfully, false if not. + */ + virtual bool createDirectory(const std::string& dirPath) override; + + /** + * Removes a directory. + * + * @param dirPath The full path of the directory, it must be an absolute path. + * @return True if the directory have been removed successfully, false if not. + */ + virtual bool removeDirectory(const std::string& dirPath) override; }; // end of platform group diff --git a/cocos/renderer/CCGLProgramState.cpp b/cocos/renderer/CCGLProgramState.cpp index 616e5b2d92a2..b5728c6a174d 100644 --- a/cocos/renderer/CCGLProgramState.cpp +++ b/cocos/renderer/CCGLProgramState.cpp @@ -239,7 +239,7 @@ void UniformValue::setVec4v(ssize_t size, const Vec4* pointer) void UniformValue::setMat4(const Mat4& value) { - CCASSERT(_uniform->type == GL_FLOAT_MAT4, ""); + CCASSERT(_uniform->type == GL_FLOAT_MAT4, "_uniform's type should be equal GL_FLOAT_MAT4."); memcpy(_value.matrixValue, &value, sizeof(_value.matrixValue)); _type = Type::VALUE; } diff --git a/cocos/renderer/CCTexture2D.cpp b/cocos/renderer/CCTexture2D.cpp index 634c7c0f1cb6..b9e0a581ae10 100644 --- a/cocos/renderer/CCTexture2D.cpp +++ b/cocos/renderer/CCTexture2D.cpp @@ -670,7 +670,7 @@ bool Texture2D::initWithMipmaps(MipmapInfo* mipmaps, int mipmapsNum, PixelFormat CCLOG("cocos2d: Texture2D. WARNING. Mipmap level %u is not squared. Texture won't render correctly. width=%d != height=%d", i, width, height); } - GLenum err = glGetError(); + err = glGetError(); if (err != GL_NO_ERROR) { CCLOG("cocos2d: Texture2D: Error uploading compressed texture level: %u . glError: 0x%04X", i, err); diff --git a/cocos/renderer/CCTextureAtlas.cpp b/cocos/renderer/CCTextureAtlas.cpp index 630236c571b9..fde935cac59c 100644 --- a/cocos/renderer/CCTextureAtlas.cpp +++ b/cocos/renderer/CCTextureAtlas.cpp @@ -171,7 +171,7 @@ bool TextureAtlas::initWithTexture(Texture2D *texture, ssize_t capacity) CC_SAFE_RETAIN(_texture); // Re-initialization is not allowed - CCASSERT(_quads == nullptr && _indices == nullptr, ""); + CCASSERT(_quads == nullptr && _indices == nullptr, "_quads and _indices should be nullptr."); _quads = (V3F_C4B_T2F_Quad*)malloc( _capacity * sizeof(V3F_C4B_T2F_Quad) ); _indices = (GLushort *)malloc( _capacity * 6 * sizeof(GLushort) ); diff --git a/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js b/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js index af7782712ed4..ad5cd9dd0e4e 100644 --- a/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js +++ b/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_auto_api.js @@ -896,6 +896,16 @@ func { }, +/** + * @method stopActionsByFlags + * @param {unsigned int} arg0 + */ +stopActionsByFlags : function ( +int +) +{ +}, + /** * @method setNormalizedPosition * @param {vec2_object} arg0 @@ -3244,6 +3254,16 @@ getTarget : function ( return cc.Node; }, +/** + * @method getFlags + * @return {unsigned int} + */ +getFlags : function ( +) +{ + return 0; +}, + /** * @method step * @param {float} arg0 @@ -3264,6 +3284,16 @@ int { }, +/** + * @method setFlags + * @param {unsigned int} arg0 + */ +setFlags : function ( +int +) +{ +}, + /** * @method getTag * @return {int} @@ -5173,6 +5203,18 @@ ReverseTime : function ( */ cc.Animate = { +/** + * @method initWithAnimation + * @param {cc.Animation} arg0 + * @return {bool} + */ +initWithAnimation : function ( +animation +) +{ + return false; +}, + /** * @method getAnimation * @return {cc.Animation|cc.Animation} @@ -5184,15 +5226,13 @@ getAnimation : function( }, /** - * @method initWithAnimation - * @param {cc.Animation} arg0 - * @return {bool} + * @method getCurrentFrameIndex + * @return {int} */ -initWithAnimation : function ( -animation +getCurrentFrameIndex : function ( ) { - return false; + return 0; }, /** @@ -9533,6 +9573,18 @@ node { }, +/** + * @method removeActionsByFlags + * @param {unsigned int} arg0 + * @param {cc.Node} arg1 + */ +removeActionsByFlags : function ( +int, +node +) +{ +}, + /** * @method removeAllActions */ diff --git a/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_experimental_video_auto_api.js b/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_experimental_video_auto_api.js index 56ed6cefae43..1751546076b1 100644 --- a/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_experimental_video_auto_api.js +++ b/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_experimental_video_auto_api.js @@ -36,14 +36,6 @@ play : function ( { }, -/** - * @method pause - */ -pause : function ( -) -{ -}, - /** * @method setKeepAspectRatioEnabled * @param {bool} arg0 @@ -54,14 +46,6 @@ bool { }, -/** - * @method resume - */ -resume : function ( -) -{ -}, - /** * @method stop */ diff --git a/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_spine_auto_api.js b/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_spine_auto_api.js index 6bb5bad6f663..750786bfd720 100644 --- a/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_spine_auto_api.js +++ b/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_spine_auto_api.js @@ -50,16 +50,6 @@ setBonesToSetupPose : function ( { }, -/** - * @method isOpacityModifyRGB - * @return {bool} - */ -isOpacityModifyRGB : function ( -) -{ - return false; -}, - /** * @method initWithData * @param {spSkeletonData} arg0 @@ -90,16 +80,6 @@ setSlotsToSetupPose : function ( { }, -/** - * @method setOpacityModifyRGB - * @param {bool} arg0 - */ -setOpacityModifyRGB : function ( -bool -) -{ -}, - /** * @method setToSetupPose */ diff --git a/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_ui_auto_api.js b/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_ui_auto_api.js index fd20a292f21d..c5dd20afa5d2 100644 --- a/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_ui_auto_api.js +++ b/cocos/scripting/js-bindings/auto/api/jsb_cocos2dx_ui_auto_api.js @@ -2683,6 +2683,16 @@ bool { }, +/** + * @method setScrollBarOpacity + * @param {unsigned char} arg0 + */ +setScrollBarOpacity : function ( +char +) +{ +}, + /** * @method setScrollBarEnabled * @param {bool} arg0 @@ -2767,6 +2777,16 @@ jumpToBottom : function ( { }, +/** + * @method setInnerContainerPosition + * @param {vec2_object} arg0 + */ +setInnerContainerPosition : function ( +vec2 +) +{ +}, + /** * @method setDirection * @param {ccui.ScrollView::Direction} arg0 @@ -2815,6 +2835,16 @@ size { }, +/** + * @method getInnerContainerPosition + * @return {vec2_object} + */ +getInnerContainerPosition : function ( +) +{ + return cc.Vec2; +}, + /** * @method getInnerContainerSize * @return {size_object} @@ -2875,6 +2905,16 @@ bool { }, +/** + * @method setScrollBarAutoHideEnabled + * @param {bool} arg0 + */ +setScrollBarAutoHideEnabled : function ( +bool +) +{ +}, + /** * @method getScrollBarColor * @return {color3b_object} @@ -3008,13 +3048,13 @@ bool }, /** - * @method setScrollBarAutoHideEnabled - * @param {bool} arg0 + * @method getScrollBarOpacity + * @return {unsigned char} */ -setScrollBarAutoHideEnabled : function ( -bool +getScrollBarOpacity : function ( ) { + return 0; }, /** diff --git a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_3d_auto.cpp b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_3d_auto.cpp index b8f339ad416f..5981ba627b42 100644 --- a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_3d_auto.cpp +++ b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_3d_auto.cpp @@ -3532,6 +3532,7 @@ void js_register_cocos2dx_3d_Sprite3D(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { jsb.Sprite3D.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_Sprite3DCache_class; diff --git a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp index b0a958349ec6..86b3b6d09d8b 100644 --- a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp +++ b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.cpp @@ -2385,6 +2385,26 @@ bool js_cocos2dx_Node_setOnEnterCallback(JSContext *cx, uint32_t argc, jsval *vp JS_ReportError(cx, "js_cocos2dx_Node_setOnEnterCallback : wrong number of arguments: %d, was expecting %d", argc, 1); return false; } +bool js_cocos2dx_Node_stopActionsByFlags(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::Node* cobj = (cocos2d::Node *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Node_stopActionsByFlags : Invalid Native Object"); + if (argc == 1) { + unsigned int arg0; + ok &= jsval_to_uint32(cx, args.get(0), &arg0); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_Node_stopActionsByFlags : Error processing arguments"); + cobj->stopActionsByFlags(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_Node_stopActionsByFlags : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} bool js_cocos2dx_Node_setNormalizedPosition(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); @@ -4909,6 +4929,7 @@ void js_register_cocos2dx_Node(JSContext *cx, JS::HandleObject global) { JS_FN("setSkewX", js_cocos2dx_Node_setSkewX, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setGLProgramState", js_cocos2dx_Node_setGLProgramState, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setOnEnterCallback", js_cocos2dx_Node_setOnEnterCallback, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("stopActionsByFlags", js_cocos2dx_Node_stopActionsByFlags, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setNormalizedPosition", js_cocos2dx_Node_setNormalizedPosition, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setonExitTransitionDidStartCallback", js_cocos2dx_Node_setonExitTransitionDidStartCallback, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("convertTouchToNodeSpace", js_cocos2dx_Node_convertTouchToNodeSpace, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), @@ -5047,6 +5068,7 @@ void js_register_cocos2dx_Node(JSContext *cx, JS::HandleObject global) { p->parentProto = NULL; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.Node.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d___NodeRGBA_class; @@ -5155,6 +5177,7 @@ void js_register_cocos2dx___NodeRGBA(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.NodeRGBA.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_Scene_class; @@ -5458,6 +5481,7 @@ void js_register_cocos2dx_Scene(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.Scene.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_GLView_class; @@ -8088,6 +8112,24 @@ bool js_cocos2dx_Action_getTarget(JSContext *cx, uint32_t argc, jsval *vp) JS_ReportError(cx, "js_cocos2dx_Action_getTarget : wrong number of arguments: %d, was expecting %d", argc, 0); return false; } +bool js_cocos2dx_Action_getFlags(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::Action* cobj = (cocos2d::Action *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Action_getFlags : Invalid Native Object"); + if (argc == 0) { + unsigned int ret = cobj->getFlags(); + jsval jsret = JSVAL_NULL; + jsret = uint32_to_jsval(cx, ret); + args.rval().set(jsret); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_Action_getFlags : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} bool js_cocos2dx_Action_step(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); @@ -8128,6 +8170,26 @@ bool js_cocos2dx_Action_setTag(JSContext *cx, uint32_t argc, jsval *vp) JS_ReportError(cx, "js_cocos2dx_Action_setTag : wrong number of arguments: %d, was expecting %d", argc, 1); return false; } +bool js_cocos2dx_Action_setFlags(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::Action* cobj = (cocos2d::Action *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Action_setFlags : Invalid Native Object"); + if (argc == 1) { + unsigned int arg0; + ok &= jsval_to_uint32(cx, args.get(0), &arg0); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_Action_setFlags : Error processing arguments"); + cobj->setFlags(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_Action_setFlags : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} bool js_cocos2dx_Action_getTag(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); @@ -8249,8 +8311,10 @@ void js_register_cocos2dx_Action(JSContext *cx, JS::HandleObject global) { JS_FN("stop", js_cocos2dx_Action_stop, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("update", js_cocos2dx_Action_update, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getTarget", js_cocos2dx_Action_getTarget, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("getFlags", js_cocos2dx_Action_getFlags, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("step", js_cocos2dx_Action_step, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setTag", js_cocos2dx_Action_setTag, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("setFlags", js_cocos2dx_Action_setFlags, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getTag", js_cocos2dx_Action_getTag, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setTarget", js_cocos2dx_Action_setTarget, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("isDone", js_cocos2dx_Action_isDone, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), @@ -9628,6 +9692,7 @@ void js_register_cocos2dx_SpriteFrame(JSContext *cx, JS::HandleObject global) { p->parentProto = NULL; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.SpriteFrame.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_AnimationFrame_class; @@ -14715,6 +14780,36 @@ void js_register_cocos2dx_ReverseTime(JSContext *cx, JS::HandleObject global) { JSClass *jsb_cocos2d_Animate_class; JSObject *jsb_cocos2d_Animate_prototype; +bool js_cocos2dx_Animate_initWithAnimation(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::Animate* cobj = (cocos2d::Animate *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Animate_initWithAnimation : Invalid Native Object"); + if (argc == 1) { + cocos2d::Animation* arg0; + do { + if (args.get(0).isNull()) { arg0 = nullptr; break; } + if (!args.get(0).isObject()) { ok = false; break; } + js_proxy_t *jsProxy; + JSObject *tmpObj = args.get(0).toObjectOrNull(); + jsProxy = jsb_get_js_proxy(tmpObj); + arg0 = (cocos2d::Animation*)(jsProxy ? jsProxy->ptr : NULL); + JSB_PRECONDITION2( arg0, cx, false, "Invalid Native Object"); + } while (0); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_Animate_initWithAnimation : Error processing arguments"); + bool ret = cobj->initWithAnimation(arg0); + jsval jsret = JSVAL_NULL; + jsret = BOOLEAN_TO_JSVAL(ret); + args.rval().set(jsret); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_Animate_initWithAnimation : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} bool js_cocos2dx_Animate_getAnimation(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); @@ -14763,34 +14858,22 @@ bool js_cocos2dx_Animate_getAnimation(JSContext *cx, uint32_t argc, jsval *vp) JS_ReportError(cx, "js_cocos2dx_Animate_getAnimation : wrong number of arguments"); return false; } -bool js_cocos2dx_Animate_initWithAnimation(JSContext *cx, uint32_t argc, jsval *vp) +bool js_cocos2dx_Animate_getCurrentFrameIndex(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); - bool ok = true; JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); js_proxy_t *proxy = jsb_get_js_proxy(obj); cocos2d::Animate* cobj = (cocos2d::Animate *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Animate_initWithAnimation : Invalid Native Object"); - if (argc == 1) { - cocos2d::Animation* arg0; - do { - if (args.get(0).isNull()) { arg0 = nullptr; break; } - if (!args.get(0).isObject()) { ok = false; break; } - js_proxy_t *jsProxy; - JSObject *tmpObj = args.get(0).toObjectOrNull(); - jsProxy = jsb_get_js_proxy(tmpObj); - arg0 = (cocos2d::Animation*)(jsProxy ? jsProxy->ptr : NULL); - JSB_PRECONDITION2( arg0, cx, false, "Invalid Native Object"); - } while (0); - JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_Animate_initWithAnimation : Error processing arguments"); - bool ret = cobj->initWithAnimation(arg0); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_Animate_getCurrentFrameIndex : Invalid Native Object"); + if (argc == 0) { + int ret = cobj->getCurrentFrameIndex(); jsval jsret = JSVAL_NULL; - jsret = BOOLEAN_TO_JSVAL(ret); + jsret = int32_to_jsval(cx, ret); args.rval().set(jsret); return true; } - JS_ReportError(cx, "js_cocos2dx_Animate_initWithAnimation : wrong number of arguments: %d, was expecting %d", argc, 1); + JS_ReportError(cx, "js_cocos2dx_Animate_getCurrentFrameIndex : wrong number of arguments: %d, was expecting %d", argc, 0); return false; } bool js_cocos2dx_Animate_setAnimation(JSContext *cx, uint32_t argc, jsval *vp) @@ -14909,8 +14992,9 @@ void js_register_cocos2dx_Animate(JSContext *cx, JS::HandleObject global) { }; static JSFunctionSpec funcs[] = { - JS_FN("getAnimation", js_cocos2dx_Animate_getAnimation, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("initWithAnimation", js_cocos2dx_Animate_initWithAnimation, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("getAnimation", js_cocos2dx_Animate_getAnimation, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("getCurrentFrameIndex", js_cocos2dx_Animate_getCurrentFrameIndex, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setAnimation", js_cocos2dx_Animate_setAnimation, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FS_END }; @@ -15219,6 +15303,7 @@ void js_register_cocos2dx_TargetedAction(JSContext *cx, JS::HandleObject global) p->parentProto = jsb_cocos2d_ActionInterval_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.TargetedAction.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ActionFloat_class; @@ -15432,6 +15517,7 @@ void js_register_cocos2dx_ActionFloat(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ActionInterval_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.ActionFloat.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_Configuration_class; @@ -20403,6 +20489,7 @@ void js_register_cocos2dx_ActionCamera(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ActionInterval_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.ActionCamera.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_OrbitCamera_class; @@ -24019,6 +24106,7 @@ void js_register_cocos2dx_EaseBezierAction(JSContext *cx, JS::HandleObject globa p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseBezierAction.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_EaseQuadraticActionIn_class; @@ -24163,6 +24251,7 @@ void js_register_cocos2dx_EaseQuadraticActionIn(JSContext *cx, JS::HandleObject p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseQuadraticActionIn.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_EaseQuadraticActionOut_class; @@ -24307,6 +24396,7 @@ void js_register_cocos2dx_EaseQuadraticActionOut(JSContext *cx, JS::HandleObject p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseQuadraticActionOut.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_EaseQuadraticActionInOut_class; @@ -24451,6 +24541,7 @@ void js_register_cocos2dx_EaseQuadraticActionInOut(JSContext *cx, JS::HandleObje p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseQuadraticActionInOut.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_EaseQuarticActionIn_class; @@ -24595,6 +24686,7 @@ void js_register_cocos2dx_EaseQuarticActionIn(JSContext *cx, JS::HandleObject gl p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseQuarticActionIn.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_EaseQuarticActionOut_class; @@ -24739,6 +24831,7 @@ void js_register_cocos2dx_EaseQuarticActionOut(JSContext *cx, JS::HandleObject g p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseQuarticActionOut.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_EaseQuarticActionInOut_class; @@ -24883,6 +24976,7 @@ void js_register_cocos2dx_EaseQuarticActionInOut(JSContext *cx, JS::HandleObject p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseQuarticActionInOut.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_EaseQuinticActionIn_class; @@ -25027,6 +25121,7 @@ void js_register_cocos2dx_EaseQuinticActionIn(JSContext *cx, JS::HandleObject gl p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseQuinticActionIn.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_EaseQuinticActionOut_class; @@ -25171,6 +25266,7 @@ void js_register_cocos2dx_EaseQuinticActionOut(JSContext *cx, JS::HandleObject g p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseQuinticActionOut.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_EaseQuinticActionInOut_class; @@ -25315,6 +25411,7 @@ void js_register_cocos2dx_EaseQuinticActionInOut(JSContext *cx, JS::HandleObject p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseQuinticActionInOut.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_EaseCircleActionIn_class; @@ -25459,6 +25556,7 @@ void js_register_cocos2dx_EaseCircleActionIn(JSContext *cx, JS::HandleObject glo p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseCircleActionIn.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_EaseCircleActionOut_class; @@ -25603,6 +25701,7 @@ void js_register_cocos2dx_EaseCircleActionOut(JSContext *cx, JS::HandleObject gl p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseCircleActionOut.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_EaseCircleActionInOut_class; @@ -25747,6 +25846,7 @@ void js_register_cocos2dx_EaseCircleActionInOut(JSContext *cx, JS::HandleObject p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseCircleActionInOut.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_EaseCubicActionIn_class; @@ -25891,6 +25991,7 @@ void js_register_cocos2dx_EaseCubicActionIn(JSContext *cx, JS::HandleObject glob p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseCubicActionIn.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_EaseCubicActionOut_class; @@ -26035,6 +26136,7 @@ void js_register_cocos2dx_EaseCubicActionOut(JSContext *cx, JS::HandleObject glo p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseCubicActionOut.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_EaseCubicActionInOut_class; @@ -26179,6 +26281,7 @@ void js_register_cocos2dx_EaseCubicActionInOut(JSContext *cx, JS::HandleObject g p->parentProto = jsb_cocos2d_ActionEase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.EaseCubicActionInOut.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ActionInstant_class; @@ -29900,6 +30003,36 @@ bool js_cocos2dx_ActionManager_removeActionByTag(JSContext *cx, uint32_t argc, j JS_ReportError(cx, "js_cocos2dx_ActionManager_removeActionByTag : wrong number of arguments: %d, was expecting %d", argc, 2); return false; } +bool js_cocos2dx_ActionManager_removeActionsByFlags(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::ActionManager* cobj = (cocos2d::ActionManager *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_ActionManager_removeActionsByFlags : Invalid Native Object"); + if (argc == 2) { + unsigned int arg0; + cocos2d::Node* arg1; + ok &= jsval_to_uint32(cx, args.get(0), &arg0); + do { + if (args.get(1).isNull()) { arg1 = nullptr; break; } + if (!args.get(1).isObject()) { ok = false; break; } + js_proxy_t *jsProxy; + JSObject *tmpObj = args.get(1).toObjectOrNull(); + jsProxy = jsb_get_js_proxy(tmpObj); + arg1 = (cocos2d::Node*)(jsProxy ? jsProxy->ptr : NULL); + JSB_PRECONDITION2( arg1, cx, false, "Invalid Native Object"); + } while (0); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_ActionManager_removeActionsByFlags : Error processing arguments"); + cobj->removeActionsByFlags(arg0, arg1); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_ActionManager_removeActionsByFlags : wrong number of arguments: %d, was expecting %d", argc, 2); + return false; +} bool js_cocos2dx_ActionManager_removeAllActions(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); @@ -30258,6 +30391,7 @@ void js_register_cocos2dx_ActionManager(JSContext *cx, JS::HandleObject global) static JSFunctionSpec funcs[] = { JS_FN("getActionByTag", js_cocos2dx_ActionManager_getActionByTag, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("removeActionByTag", js_cocos2dx_ActionManager_removeActionByTag, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("removeActionsByFlags", js_cocos2dx_ActionManager_removeActionsByFlags, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("removeAllActions", js_cocos2dx_ActionManager_removeAllActions, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("addAction", js_cocos2dx_ActionManager_addAction, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("resumeTarget", js_cocos2dx_ActionManager_resumeTarget, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), @@ -30301,6 +30435,7 @@ void js_register_cocos2dx_ActionManager(JSContext *cx, JS::HandleObject global) p->parentProto = NULL; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.ActionManager.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_PageTurn3D_class; @@ -32937,6 +33072,7 @@ void js_register_cocos2dx_ActionTween(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ActionInterval_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.ActionTween.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_GLProgramState_class; @@ -35685,6 +35821,7 @@ void js_register_cocos2dx_DrawNode(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.DrawNode.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_Label_class; @@ -37165,6 +37302,7 @@ void js_register_cocos2dx_Label(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.Label.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_LabelAtlas_class; @@ -37484,6 +37622,7 @@ void js_register_cocos2dx_LabelAtlas(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_AtlasNode_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.LabelAtlas.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_LabelBMFont_class; @@ -38022,6 +38161,7 @@ void js_register_cocos2dx_LabelBMFont(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.LabelBMFont.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_LabelTTF_class; @@ -38929,6 +39069,7 @@ void js_register_cocos2dx_LabelTTF(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.LabelTTF.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_Layer_class; @@ -39061,6 +39202,7 @@ void js_register_cocos2dx_Layer(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.Layer.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d___LayerRGBA_class; @@ -39509,6 +39651,7 @@ void js_register_cocos2dx_LayerColor(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Layer_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.LayerColor.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_LayerGradient_class; @@ -39983,6 +40126,7 @@ void js_register_cocos2dx_LayerGradient(JSContext *cx, JS::HandleObject global) p->parentProto = jsb_cocos2d_LayerColor_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.LayerGradient.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_LayerMultiplex_class; @@ -40185,6 +40329,7 @@ void js_register_cocos2dx_LayerMultiplex(JSContext *cx, JS::HandleObject global) p->parentProto = jsb_cocos2d_Layer_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.LayerMultiplex.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_MenuItem_class; @@ -40473,6 +40618,7 @@ void js_register_cocos2dx_MenuItem(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.MenuItem.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_MenuItemLabel_class; @@ -40758,6 +40904,7 @@ void js_register_cocos2dx_MenuItemLabel(JSContext *cx, JS::HandleObject global) p->parentProto = jsb_cocos2d_MenuItem_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.MenuItemLabel.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_MenuItemAtlasFont_class; @@ -40927,6 +41074,7 @@ void js_register_cocos2dx_MenuItemAtlasFont(JSContext *cx, JS::HandleObject glob p->parentProto = jsb_cocos2d_MenuItemLabel_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.MenuItemAtlasFont.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_MenuItemFont_class; @@ -41234,6 +41382,7 @@ void js_register_cocos2dx_MenuItemFont(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_MenuItemLabel_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.MenuItemFont.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_MenuItemSprite_class; @@ -41643,6 +41792,7 @@ void js_register_cocos2dx_MenuItemSprite(JSContext *cx, JS::HandleObject global) p->parentProto = jsb_cocos2d_MenuItem_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.MenuItemSprite.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_MenuItemImage_class; @@ -41914,6 +42064,7 @@ void js_register_cocos2dx_MenuItemImage(JSContext *cx, JS::HandleObject global) p->parentProto = jsb_cocos2d_MenuItemSprite_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.MenuItemImage.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_MenuItemToggle_class; @@ -42169,6 +42320,7 @@ void js_register_cocos2dx_MenuItemToggle(JSContext *cx, JS::HandleObject global) p->parentProto = jsb_cocos2d_MenuItem_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.MenuItemToggle.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_Menu_class; @@ -42416,6 +42568,7 @@ void js_register_cocos2dx_Menu(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Layer_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.Menu.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_MotionStreak_class; @@ -42932,6 +43085,7 @@ void js_register_cocos2dx_MotionStreak(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.MotionStreak.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_NodeGrid_class; @@ -43645,6 +43799,7 @@ void js_register_cocos2dx_ParticleBatchNode(JSContext *cx, JS::HandleObject glob p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.ParticleBatchNode.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ParticleSystem_class; @@ -45837,6 +45992,7 @@ void js_register_cocos2dx_ParticleSystem(JSContext *cx, JS::HandleObject global) p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.ParticleSystem.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ParticleSystemQuad_class; @@ -48525,6 +48681,7 @@ void js_register_cocos2dx_ProgressTimer(JSContext *cx, JS::HandleObject global) p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.ProgressTimer.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ProtectedNode_class; @@ -50399,6 +50556,7 @@ void js_register_cocos2dx_Sprite(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.Sprite.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_RenderTexture_class; @@ -51200,6 +51358,7 @@ void js_register_cocos2dx_RenderTexture(JSContext *cx, JS::HandleObject global) p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.RenderTexture.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_TransitionEaseScene_class; @@ -51557,6 +51716,7 @@ void js_register_cocos2dx_TransitionScene(JSContext *cx, JS::HandleObject global p->parentProto = jsb_cocos2d_Scene_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.TransitionScene.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_TransitionSceneOriented_class; @@ -58200,6 +58360,7 @@ void js_register_cocos2dx_GridBase(JSContext *cx, JS::HandleObject global) { p->parentProto = NULL; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.GridBase.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_Grid3D_class; @@ -58412,6 +58573,7 @@ void js_register_cocos2dx_Grid3D(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_GridBase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.Grid3D.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_TiledGrid3D_class; @@ -58584,6 +58746,7 @@ void js_register_cocos2dx_TiledGrid3D(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_GridBase_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.TiledGrid3D.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_BaseLight_class; @@ -60404,6 +60567,7 @@ void js_register_cocos2dx_GLProgram(JSContext *cx, JS::HandleObject global) { p->parentProto = NULL; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.GLProgram.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_GLProgramCache_class; @@ -63776,6 +63940,7 @@ void js_register_cocos2dx_SpriteBatchNode(JSContext *cx, JS::HandleObject global p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.SpriteBatchNode.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_SpriteFrameCache_class; @@ -64624,6 +64789,7 @@ void js_register_cocos2dx_TextFieldTTF(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Label_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.TextFieldTTF.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ParallaxNode_class; @@ -64869,6 +65035,7 @@ void js_register_cocos2dx_ParallaxNode(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.ParallaxNode.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_TMXObjectGroup_class; @@ -66321,6 +66488,7 @@ void js_register_cocos2dx_TMXMapInfo(JSContext *cx, JS::HandleObject global) { p->parentProto = NULL; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.TMXMapInfo.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_TMXLayer_class; @@ -67042,6 +67210,7 @@ void js_register_cocos2dx_TMXLayer(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_SpriteBatchNode_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.TMXLayer.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_TMXTiledMap_class; @@ -67605,6 +67774,7 @@ void js_register_cocos2dx_TMXTiledMap(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.TMXTiledMap.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_TileMapAtlas_class; @@ -67880,6 +68050,7 @@ void js_register_cocos2dx_TileMapAtlas(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_AtlasNode_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.TileMapAtlas.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_Component_class; @@ -68165,6 +68336,7 @@ void js_register_cocos2dx_Component(JSContext *cx, JS::HandleObject global) { p->parentProto = NULL; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.Component.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ComponentContainer_class; diff --git a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp index bc50f1abfd9d..e4359a14ecdb 100644 --- a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp +++ b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_auto.hpp @@ -127,6 +127,7 @@ bool js_cocos2dx_Node_getEventDispatcher(JSContext *cx, uint32_t argc, jsval *vp bool js_cocos2dx_Node_setSkewX(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Node_setGLProgramState(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Node_setOnEnterCallback(JSContext *cx, uint32_t argc, jsval *vp); +bool js_cocos2dx_Node_stopActionsByFlags(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Node_setNormalizedPosition(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Node_setonExitTransitionDidStartCallback(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Node_convertTouchToNodeSpace(JSContext *cx, uint32_t argc, jsval *vp); @@ -410,8 +411,10 @@ bool js_cocos2dx_Action_getOriginalTarget(JSContext *cx, uint32_t argc, jsval *v bool js_cocos2dx_Action_stop(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Action_update(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Action_getTarget(JSContext *cx, uint32_t argc, jsval *vp); +bool js_cocos2dx_Action_getFlags(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Action_step(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Action_setTag(JSContext *cx, uint32_t argc, jsval *vp); +bool js_cocos2dx_Action_setFlags(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Action_getTag(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Action_setTarget(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Action_isDone(JSContext *cx, uint32_t argc, jsval *vp); @@ -810,8 +813,9 @@ bool js_cocos2dx_Animate_constructor(JSContext *cx, uint32_t argc, jsval *vp); void js_cocos2dx_Animate_finalize(JSContext *cx, JSObject *obj); void js_register_cocos2dx_Animate(JSContext *cx, JS::HandleObject global); void register_all_cocos2dx(JSContext* cx, JS::HandleObject obj); -bool js_cocos2dx_Animate_getAnimation(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Animate_initWithAnimation(JSContext *cx, uint32_t argc, jsval *vp); +bool js_cocos2dx_Animate_getAnimation(JSContext *cx, uint32_t argc, jsval *vp); +bool js_cocos2dx_Animate_getCurrentFrameIndex(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Animate_setAnimation(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Animate_create(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_Animate_Animate(JSContext *cx, uint32_t argc, jsval *vp); @@ -1839,6 +1843,7 @@ void js_register_cocos2dx_ActionManager(JSContext *cx, JS::HandleObject global); void register_all_cocos2dx(JSContext* cx, JS::HandleObject obj); bool js_cocos2dx_ActionManager_getActionByTag(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ActionManager_removeActionByTag(JSContext *cx, uint32_t argc, jsval *vp); +bool js_cocos2dx_ActionManager_removeActionsByFlags(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ActionManager_removeAllActions(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ActionManager_addAction(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ActionManager_resumeTarget(JSContext *cx, uint32_t argc, jsval *vp); diff --git a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_experimental_video_auto.cpp b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_experimental_video_auto.cpp index 421cdde6f86b..27619f14e375 100644 --- a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_experimental_video_auto.cpp +++ b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_experimental_video_auto.cpp @@ -97,22 +97,6 @@ bool js_cocos2dx_experimental_video_VideoPlayer_play(JSContext *cx, uint32_t arg JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_play : wrong number of arguments: %d, was expecting %d", argc, 0); return false; } -bool js_cocos2dx_experimental_video_VideoPlayer_pause(JSContext *cx, uint32_t argc, jsval *vp) -{ - JS::CallArgs args = JS::CallArgsFromVp(argc, vp); - JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_pause : Invalid Native Object"); - if (argc == 0) { - cobj->pause(); - args.rval().setUndefined(); - return true; - } - - JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_pause : wrong number of arguments: %d, was expecting %d", argc, 0); - return false; -} bool js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); @@ -133,22 +117,6 @@ bool js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled(JSCont JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled : wrong number of arguments: %d, was expecting %d", argc, 1); return false; } -bool js_cocos2dx_experimental_video_VideoPlayer_resume(JSContext *cx, uint32_t argc, jsval *vp) -{ - JS::CallArgs args = JS::CallArgsFromVp(argc, vp); - JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - cocos2d::experimental::ui::VideoPlayer* cobj = (cocos2d::experimental::ui::VideoPlayer *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_experimental_video_VideoPlayer_resume : Invalid Native Object"); - if (argc == 0) { - cobj->resume(); - args.rval().setUndefined(); - return true; - } - - JS_ReportError(cx, "js_cocos2dx_experimental_video_VideoPlayer_resume : wrong number of arguments: %d, was expecting %d", argc, 0); - return false; -} bool js_cocos2dx_experimental_video_VideoPlayer_stop(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); @@ -398,9 +366,7 @@ void js_register_cocos2dx_experimental_video_VideoPlayer(JSContext *cx, JS::Hand JS_FN("getFileName", js_cocos2dx_experimental_video_VideoPlayer_getFileName, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getURL", js_cocos2dx_experimental_video_VideoPlayer_getURL, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("play", js_cocos2dx_experimental_video_VideoPlayer_play, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FN("pause", js_cocos2dx_experimental_video_VideoPlayer_pause, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setKeepAspectRatioEnabled", js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FN("resume", js_cocos2dx_experimental_video_VideoPlayer_resume, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("stop", js_cocos2dx_experimental_video_VideoPlayer_stop, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setFullScreenEnabled", js_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setFileName", js_cocos2dx_experimental_video_VideoPlayer_setFileName, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), diff --git a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_experimental_video_auto.hpp b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_experimental_video_auto.hpp index e5360f85451d..4c1419a75968 100644 --- a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_experimental_video_auto.hpp +++ b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_experimental_video_auto.hpp @@ -16,9 +16,7 @@ void register_all_cocos2dx_experimental_video(JSContext* cx, JS::HandleObject ob bool js_cocos2dx_experimental_video_VideoPlayer_getFileName(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_experimental_video_VideoPlayer_getURL(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_experimental_video_VideoPlayer_play(JSContext *cx, uint32_t argc, jsval *vp); -bool js_cocos2dx_experimental_video_VideoPlayer_pause(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled(JSContext *cx, uint32_t argc, jsval *vp); -bool js_cocos2dx_experimental_video_VideoPlayer_resume(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_experimental_video_VideoPlayer_stop(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_experimental_video_VideoPlayer_setFileName(JSContext *cx, uint32_t argc, jsval *vp); diff --git a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_extension_auto.cpp b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_extension_auto.cpp index a32be2994e7b..076a3a35e545 100644 --- a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_extension_auto.cpp +++ b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_extension_auto.cpp @@ -1566,6 +1566,7 @@ void js_register_cocos2dx_extension_ControlButton(JSContext *cx, JS::HandleObjec p->parentProto = jsb_cocos2d_extension_Control_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.ControlButton.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_extension_ControlHuePicker_class; @@ -2619,6 +2620,7 @@ void js_register_cocos2dx_extension_ControlColourPicker(JSContext *cx, JS::Handl p->parentProto = jsb_cocos2d_extension_Control_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.ControlColourPicker.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_extension_ControlPotentiometer_class; @@ -3197,6 +3199,7 @@ void js_register_cocos2dx_extension_ControlPotentiometer(JSContext *cx, JS::Hand p->parentProto = jsb_cocos2d_extension_Control_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.ControlPotentiometer.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_extension_ControlSlider_class; @@ -4044,6 +4047,7 @@ void js_register_cocos2dx_extension_ControlSlider(JSContext *cx, JS::HandleObjec p->parentProto = jsb_cocos2d_extension_Control_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.ControlSlider.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_extension_ControlStepper_class; @@ -4680,6 +4684,7 @@ void js_register_cocos2dx_extension_ControlStepper(JSContext *cx, JS::HandleObje p->parentProto = jsb_cocos2d_extension_Control_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.ControlStepper.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_extension_ControlSwitch_class; @@ -5193,6 +5198,7 @@ void js_register_cocos2dx_extension_ControlSwitch(JSContext *cx, JS::HandleObjec p->parentProto = jsb_cocos2d_extension_Control_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.ControlSwitch.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_extension_ScrollView_class; @@ -6096,6 +6102,7 @@ void js_register_cocos2dx_extension_ScrollView(JSContext *cx, JS::HandleObject g p->parentProto = jsb_cocos2d_Layer_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.ScrollView.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_extension_TableViewCell_class; @@ -6285,6 +6292,7 @@ void js_register_cocos2dx_extension_TableViewCell(JSContext *cx, JS::HandleObjec p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.TableViewCell.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_extension_TableView_class; @@ -6687,6 +6695,7 @@ void js_register_cocos2dx_extension_TableView(JSContext *cx, JS::HandleObject gl p->parentProto = jsb_cocos2d_extension_ScrollView_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { cc.TableView.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_extension_EventAssetsManagerEx_class; diff --git a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_spine_auto.cpp b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_spine_auto.cpp index a61a06fbd62d..9635a4f260c8 100644 --- a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_spine_auto.cpp +++ b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_spine_auto.cpp @@ -145,24 +145,6 @@ bool js_cocos2dx_spine_SkeletonRenderer_setBonesToSetupPose(JSContext *cx, uint3 JS_ReportError(cx, "js_cocos2dx_spine_SkeletonRenderer_setBonesToSetupPose : wrong number of arguments: %d, was expecting %d", argc, 0); return false; } -bool js_cocos2dx_spine_SkeletonRenderer_isOpacityModifyRGB(JSContext *cx, uint32_t argc, jsval *vp) -{ - JS::CallArgs args = JS::CallArgsFromVp(argc, vp); - JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - spine::SkeletonRenderer* cobj = (spine::SkeletonRenderer *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_spine_SkeletonRenderer_isOpacityModifyRGB : Invalid Native Object"); - if (argc == 0) { - bool ret = cobj->isOpacityModifyRGB(); - jsval jsret = JSVAL_NULL; - jsret = BOOLEAN_TO_JSVAL(ret); - args.rval().set(jsret); - return true; - } - - JS_ReportError(cx, "js_cocos2dx_spine_SkeletonRenderer_isOpacityModifyRGB : wrong number of arguments: %d, was expecting %d", argc, 0); - return false; -} bool js_cocos2dx_spine_SkeletonRenderer_initWithData(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); @@ -231,26 +213,6 @@ bool js_cocos2dx_spine_SkeletonRenderer_setSlotsToSetupPose(JSContext *cx, uint3 JS_ReportError(cx, "js_cocos2dx_spine_SkeletonRenderer_setSlotsToSetupPose : wrong number of arguments: %d, was expecting %d", argc, 0); return false; } -bool js_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB(JSContext *cx, uint32_t argc, jsval *vp) -{ - JS::CallArgs args = JS::CallArgsFromVp(argc, vp); - bool ok = true; - JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); - js_proxy_t *proxy = jsb_get_js_proxy(obj); - spine::SkeletonRenderer* cobj = (spine::SkeletonRenderer *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB : Invalid Native Object"); - if (argc == 1) { - bool arg0; - arg0 = JS::ToBoolean(args.get(0)); - JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB : Error processing arguments"); - cobj->setOpacityModifyRGB(arg0); - args.rval().setUndefined(); - return true; - } - - JS_ReportError(cx, "js_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB : wrong number of arguments: %d, was expecting %d", argc, 1); - return false; -} bool js_cocos2dx_spine_SkeletonRenderer_setToSetupPose(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); @@ -914,11 +876,9 @@ void js_register_cocos2dx_spine_SkeletonRenderer(JSContext *cx, JS::HandleObject JS_FN("getDebugSlotsEnabled", js_cocos2dx_spine_SkeletonRenderer_getDebugSlotsEnabled, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setAttachment", js_cocos2dx_spine_SkeletonRenderer_setAttachment, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setBonesToSetupPose", js_cocos2dx_spine_SkeletonRenderer_setBonesToSetupPose, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FN("isOpacityModifyRGB", js_cocos2dx_spine_SkeletonRenderer_isOpacityModifyRGB, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("initWithData", js_cocos2dx_spine_SkeletonRenderer_initWithData, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setDebugSlotsEnabled", js_cocos2dx_spine_SkeletonRenderer_setDebugSlotsEnabled, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setSlotsToSetupPose", js_cocos2dx_spine_SkeletonRenderer_setSlotsToSetupPose, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FN("setOpacityModifyRGB", js_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setToSetupPose", js_cocos2dx_spine_SkeletonRenderer_setToSetupPose, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getBlendFunc", js_cocos2dx_spine_SkeletonRenderer_getBlendFunc, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("drawSkeleton", js_cocos2dx_spine_SkeletonRenderer_drawSkeleton, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), @@ -1883,6 +1843,7 @@ void js_register_cocos2dx_spine_SkeletonAnimation(JSContext *cx, JS::HandleObjec p->parentProto = jsb_spine_SkeletonRenderer_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { sp.SkeletonAnimation.extend = cc.Class.extend; })()"); } void register_all_cocos2dx_spine(JSContext* cx, JS::HandleObject obj) { diff --git a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_spine_auto.hpp b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_spine_auto.hpp index fa5f388102b4..cde2a264c771 100644 --- a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_spine_auto.hpp +++ b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_spine_auto.hpp @@ -16,11 +16,9 @@ bool js_cocos2dx_spine_SkeletonRenderer_setTimeScale(JSContext *cx, uint32_t arg bool js_cocos2dx_spine_SkeletonRenderer_getDebugSlotsEnabled(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_spine_SkeletonRenderer_setAttachment(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_spine_SkeletonRenderer_setBonesToSetupPose(JSContext *cx, uint32_t argc, jsval *vp); -bool js_cocos2dx_spine_SkeletonRenderer_isOpacityModifyRGB(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_spine_SkeletonRenderer_initWithData(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_spine_SkeletonRenderer_setDebugSlotsEnabled(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_spine_SkeletonRenderer_setSlotsToSetupPose(JSContext *cx, uint32_t argc, jsval *vp); -bool js_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_spine_SkeletonRenderer_setToSetupPose(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_spine_SkeletonRenderer_getBlendFunc(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_spine_SkeletonRenderer_drawSkeleton(JSContext *cx, uint32_t argc, jsval *vp); diff --git a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_studio_auto.cpp b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_studio_auto.cpp index 442488d907d0..efdab06895dd 100644 --- a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_studio_auto.cpp +++ b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_studio_auto.cpp @@ -6670,6 +6670,7 @@ void js_register_cocos2dx_studio_Armature(JSContext *cx, JS::HandleObject global p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccs.Armature.extend = cc.Class.extend; })()"); } JSClass *jsb_cocostudio_Skin_class; @@ -8398,6 +8399,7 @@ void js_register_cocos2dx_studio_ComController(JSContext *cx, JS::HandleObject g p->parentProto = jsb_cocos2d_Component_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccs.ComController.extend = cc.Class.extend; })()"); } JSClass *jsb_cocostudio_ComRender_class; diff --git a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_ui_auto.cpp b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_ui_auto.cpp index 3440f30625c5..fec24aae7528 100644 --- a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_ui_auto.cpp +++ b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_ui_auto.cpp @@ -2390,6 +2390,7 @@ void js_register_cocos2dx_ui_Widget(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ProtectedNode_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.Widget.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_Layout_class; @@ -3222,6 +3223,7 @@ void js_register_cocos2dx_ui_Layout(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ui_Widget_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.Layout.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_Button_class; @@ -4168,6 +4170,7 @@ void js_register_cocos2dx_ui_Button(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ui_Widget_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.Button.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_AbstractCheckButton_class; @@ -4834,6 +4837,7 @@ void js_register_cocos2dx_ui_CheckBox(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ui_AbstractCheckButton_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.CheckBox.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_RadioButton_class; @@ -5780,6 +5784,7 @@ void js_register_cocos2dx_ui_ImageView(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ui_Widget_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.ImageView.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_Text_class; @@ -6501,6 +6506,7 @@ void js_register_cocos2dx_ui_Text(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ui_Widget_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.Text.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_TextAtlas_class; @@ -6795,6 +6801,7 @@ void js_register_cocos2dx_ui_TextAtlas(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ui_Widget_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.TextAtlas.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_LoadingBar_class; @@ -7233,6 +7240,7 @@ void js_register_cocos2dx_ui_LoadingBar(JSContext *cx, JS::HandleObject global) p->parentProto = jsb_cocos2d_ui_Widget_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.LoadingBar.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_ScrollView_class; @@ -7284,6 +7292,26 @@ bool js_cocos2dx_ui_ScrollView_scrollToPercentHorizontal(JSContext *cx, uint32_t JS_ReportError(cx, "js_cocos2dx_ui_ScrollView_scrollToPercentHorizontal : wrong number of arguments: %d, was expecting %d", argc, 3); return false; } +bool js_cocos2dx_ui_ScrollView_setScrollBarOpacity(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::ui::ScrollView* cobj = (cocos2d::ui::ScrollView *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_ui_ScrollView_setScrollBarOpacity : Invalid Native Object"); + if (argc == 1) { + uint16_t arg0; + ok &= jsval_to_uint16(cx, args.get(0), &arg0); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_ui_ScrollView_setScrollBarOpacity : Error processing arguments"); + cobj->setScrollBarOpacity(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_ui_ScrollView_setScrollBarOpacity : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} bool js_cocos2dx_ui_ScrollView_setScrollBarEnabled(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); @@ -7447,6 +7475,26 @@ bool js_cocos2dx_ui_ScrollView_jumpToBottom(JSContext *cx, uint32_t argc, jsval JS_ReportError(cx, "js_cocos2dx_ui_ScrollView_jumpToBottom : wrong number of arguments: %d, was expecting %d", argc, 0); return false; } +bool js_cocos2dx_ui_ScrollView_setInnerContainerPosition(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::ui::ScrollView* cobj = (cocos2d::ui::ScrollView *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_ui_ScrollView_setInnerContainerPosition : Invalid Native Object"); + if (argc == 1) { + cocos2d::Vec2 arg0; + ok &= jsval_to_vector2(cx, args.get(0), &arg0); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_ui_ScrollView_setInnerContainerPosition : Error processing arguments"); + cobj->setInnerContainerPosition(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_ui_ScrollView_setInnerContainerPosition : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} bool js_cocos2dx_ui_ScrollView_setDirection(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); @@ -7541,6 +7589,24 @@ bool js_cocos2dx_ui_ScrollView_setInnerContainerSize(JSContext *cx, uint32_t arg JS_ReportError(cx, "js_cocos2dx_ui_ScrollView_setInnerContainerSize : wrong number of arguments: %d, was expecting %d", argc, 1); return false; } +bool js_cocos2dx_ui_ScrollView_getInnerContainerPosition(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::ui::ScrollView* cobj = (cocos2d::ui::ScrollView *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_ui_ScrollView_getInnerContainerPosition : Invalid Native Object"); + if (argc == 0) { + cocos2d::Vec2 ret = cobj->getInnerContainerPosition(); + jsval jsret = JSVAL_NULL; + jsret = vector2_to_jsval(cx, ret); + args.rval().set(jsret); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_ui_ScrollView_getInnerContainerPosition : wrong number of arguments: %d, was expecting %d", argc, 0); + return false; +} bool js_cocos2dx_ui_ScrollView_getInnerContainerSize(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); @@ -7657,6 +7723,26 @@ bool js_cocos2dx_ui_ScrollView_setInertiaScrollEnabled(JSContext *cx, uint32_t a JS_ReportError(cx, "js_cocos2dx_ui_ScrollView_setInertiaScrollEnabled : wrong number of arguments: %d, was expecting %d", argc, 1); return false; } +bool js_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled(JSContext *cx, uint32_t argc, jsval *vp) +{ + JS::CallArgs args = JS::CallArgsFromVp(argc, vp); + bool ok = true; + JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); + js_proxy_t *proxy = jsb_get_js_proxy(obj); + cocos2d::ui::ScrollView* cobj = (cocos2d::ui::ScrollView *)(proxy ? proxy->ptr : NULL); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled : Invalid Native Object"); + if (argc == 1) { + bool arg0; + arg0 = JS::ToBoolean(args.get(0)); + JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled : Error processing arguments"); + cobj->setScrollBarAutoHideEnabled(arg0); + args.rval().setUndefined(); + return true; + } + + JS_ReportError(cx, "js_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled : wrong number of arguments: %d, was expecting %d", argc, 1); + return false; +} bool js_cocos2dx_ui_ScrollView_getScrollBarColor(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); @@ -7907,24 +7993,22 @@ bool js_cocos2dx_ui_ScrollView_scrollToBottom(JSContext *cx, uint32_t argc, jsva JS_ReportError(cx, "js_cocos2dx_ui_ScrollView_scrollToBottom : wrong number of arguments: %d, was expecting %d", argc, 2); return false; } -bool js_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled(JSContext *cx, uint32_t argc, jsval *vp) +bool js_cocos2dx_ui_ScrollView_getScrollBarOpacity(JSContext *cx, uint32_t argc, jsval *vp) { JS::CallArgs args = JS::CallArgsFromVp(argc, vp); - bool ok = true; JS::RootedObject obj(cx, args.thisv().toObjectOrNull()); js_proxy_t *proxy = jsb_get_js_proxy(obj); cocos2d::ui::ScrollView* cobj = (cocos2d::ui::ScrollView *)(proxy ? proxy->ptr : NULL); - JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled : Invalid Native Object"); - if (argc == 1) { - bool arg0; - arg0 = JS::ToBoolean(args.get(0)); - JSB_PRECONDITION2(ok, cx, false, "js_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled : Error processing arguments"); - cobj->setScrollBarAutoHideEnabled(arg0); - args.rval().setUndefined(); + JSB_PRECONDITION2( cobj, cx, false, "js_cocos2dx_ui_ScrollView_getScrollBarOpacity : Invalid Native Object"); + if (argc == 0) { + uint16_t ret = cobj->getScrollBarOpacity(); + jsval jsret = JSVAL_NULL; + jsret = uint32_to_jsval(cx, ret); + args.rval().set(jsret); return true; } - JS_ReportError(cx, "js_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled : wrong number of arguments: %d, was expecting %d", argc, 1); + JS_ReportError(cx, "js_cocos2dx_ui_ScrollView_getScrollBarOpacity : wrong number of arguments: %d, was expecting %d", argc, 0); return false; } bool js_cocos2dx_ui_ScrollView_scrollToBottomRight(JSContext *cx, uint32_t argc, jsval *vp) @@ -8252,6 +8336,7 @@ void js_register_cocos2dx_ui_ScrollView(JSContext *cx, JS::HandleObject global) static JSFunctionSpec funcs[] = { JS_FN("scrollToTop", js_cocos2dx_ui_ScrollView_scrollToTop, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("scrollToPercentHorizontal", js_cocos2dx_ui_ScrollView_scrollToPercentHorizontal, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("setScrollBarOpacity", js_cocos2dx_ui_ScrollView_setScrollBarOpacity, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setScrollBarEnabled", js_cocos2dx_ui_ScrollView_setScrollBarEnabled, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("isInertiaScrollEnabled", js_cocos2dx_ui_ScrollView_isInertiaScrollEnabled, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("scrollToPercentBothDirection", js_cocos2dx_ui_ScrollView_scrollToPercentBothDirection, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE), @@ -8260,17 +8345,20 @@ void js_register_cocos2dx_ui_ScrollView(JSContext *cx, JS::HandleObject global) JS_FN("scrollToBottomLeft", js_cocos2dx_ui_ScrollView_scrollToBottomLeft, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getInnerContainer", js_cocos2dx_ui_ScrollView_getInnerContainer, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("jumpToBottom", js_cocos2dx_ui_ScrollView_jumpToBottom, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("setInnerContainerPosition", js_cocos2dx_ui_ScrollView_setInnerContainerPosition, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setDirection", js_cocos2dx_ui_ScrollView_setDirection, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("scrollToTopLeft", js_cocos2dx_ui_ScrollView_scrollToTopLeft, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("jumpToTopRight", js_cocos2dx_ui_ScrollView_jumpToTopRight, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("jumpToBottomLeft", js_cocos2dx_ui_ScrollView_jumpToBottomLeft, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setInnerContainerSize", js_cocos2dx_ui_ScrollView_setInnerContainerSize, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("getInnerContainerPosition", js_cocos2dx_ui_ScrollView_getInnerContainerPosition, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getInnerContainerSize", js_cocos2dx_ui_ScrollView_getInnerContainerSize, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("isBounceEnabled", js_cocos2dx_ui_ScrollView_isBounceEnabled, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("jumpToPercentVertical", js_cocos2dx_ui_ScrollView_jumpToPercentVertical, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setScrollBarAutoHideTime", js_cocos2dx_ui_ScrollView_setScrollBarAutoHideTime, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setScrollBarPositionFromCornerForHorizontal", js_cocos2dx_ui_ScrollView_setScrollBarPositionFromCornerForHorizontal, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setInertiaScrollEnabled", js_cocos2dx_ui_ScrollView_setInertiaScrollEnabled, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("setScrollBarAutoHideEnabled", js_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("getScrollBarColor", js_cocos2dx_ui_ScrollView_getScrollBarColor, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("jumpToTopLeft", js_cocos2dx_ui_ScrollView_jumpToTopLeft, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("jumpToPercentHorizontal", js_cocos2dx_ui_ScrollView_jumpToPercentHorizontal, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), @@ -8284,7 +8372,7 @@ void js_register_cocos2dx_ui_ScrollView(JSContext *cx, JS::HandleObject global) JS_FN("getScrollBarPositionFromCornerForVertical", js_cocos2dx_ui_ScrollView_getScrollBarPositionFromCornerForVertical, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("scrollToPercentVertical", js_cocos2dx_ui_ScrollView_scrollToPercentVertical, 3, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("scrollToBottom", js_cocos2dx_ui_ScrollView_scrollToBottom, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), - JS_FN("setScrollBarAutoHideEnabled", js_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), + JS_FN("getScrollBarOpacity", js_cocos2dx_ui_ScrollView_getScrollBarOpacity, 0, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("scrollToBottomRight", js_cocos2dx_ui_ScrollView_scrollToBottomRight, 2, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setScrollBarPositionFromCorner", js_cocos2dx_ui_ScrollView_setScrollBarPositionFromCorner, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), JS_FN("setScrollBarPositionFromCornerForVertical", js_cocos2dx_ui_ScrollView_setScrollBarPositionFromCornerForVertical, 1, JSPROP_PERMANENT | JSPROP_ENUMERATE), @@ -8332,6 +8420,7 @@ void js_register_cocos2dx_ui_ScrollView(JSContext *cx, JS::HandleObject global) p->parentProto = jsb_cocos2d_ui_Layout_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.ScrollView.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_ListView_class; @@ -8879,6 +8968,7 @@ void js_register_cocos2dx_ui_ListView(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ui_ScrollView_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.ListView.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_Slider_class; @@ -9557,6 +9647,7 @@ void js_register_cocos2dx_ui_Slider(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ui_Widget_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.Slider.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_UICCTextField_class; @@ -11220,6 +11311,7 @@ void js_register_cocos2dx_ui_TextField(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ui_Widget_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.TextField.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_TextBMFont_class; @@ -11480,6 +11572,7 @@ void js_register_cocos2dx_ui_TextBMFont(JSContext *cx, JS::HandleObject global) p->parentProto = jsb_cocos2d_ui_Widget_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.TextBMFont.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_PageView_class; @@ -11963,6 +12056,7 @@ void js_register_cocos2dx_ui_PageView(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ui_Layout_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.PageView.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_Helper_class; @@ -12354,6 +12448,7 @@ void js_register_cocos2dx_ui_RichElement(JSContext *cx, JS::HandleObject global) p->parentProto = NULL; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.RichElement.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_RichElementText_class; @@ -12533,6 +12628,7 @@ void js_register_cocos2dx_ui_RichElementText(JSContext *cx, JS::HandleObject glo p->parentProto = jsb_cocos2d_ui_RichElement_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.RichElementText.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_RichElementImage_class; @@ -12704,6 +12800,7 @@ void js_register_cocos2dx_ui_RichElementImage(JSContext *cx, JS::HandleObject gl p->parentProto = jsb_cocos2d_ui_RichElement_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.RichElementImage.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_RichElementCustomNode_class; @@ -12891,6 +12988,7 @@ void js_register_cocos2dx_ui_RichElementCustomNode(JSContext *cx, JS::HandleObje p->parentProto = jsb_cocos2d_ui_RichElement_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.RichElementCustomNode.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_RichText_class; @@ -13166,6 +13264,7 @@ void js_register_cocos2dx_ui_RichText(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ui_Widget_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.RichText.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_HBox_class; @@ -13344,6 +13443,7 @@ void js_register_cocos2dx_ui_HBox(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ui_Layout_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.HBox.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_VBox_class; @@ -13522,6 +13622,7 @@ void js_register_cocos2dx_ui_VBox(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ui_Layout_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.VBox.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_RelativeBox_class; @@ -13700,6 +13801,7 @@ void js_register_cocos2dx_ui_RelativeBox(JSContext *cx, JS::HandleObject global) p->parentProto = jsb_cocos2d_ui_Layout_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.RelativeBox.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_Scale9Sprite_class; @@ -14990,6 +15092,7 @@ void js_register_cocos2dx_ui_Scale9Sprite(JSContext *cx, JS::HandleObject global p->parentProto = jsb_cocos2d_Node_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.Scale9Sprite.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_EditBox_class; @@ -15741,6 +15844,7 @@ void js_register_cocos2dx_ui_EditBox(JSContext *cx, JS::HandleObject global) { p->parentProto = jsb_cocos2d_ui_Widget_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.EditBox.extend = cc.Class.extend; })()"); } JSClass *jsb_cocos2d_ui_LayoutComponent_class; @@ -16886,6 +16990,7 @@ void js_register_cocos2dx_ui_LayoutComponent(JSContext *cx, JS::HandleObject glo p->parentProto = jsb_cocos2d_Component_prototype; _js_global_type_map.insert(std::make_pair(typeName, p)); } + anonEvaluate(cx, global, "(function () { ccui.LayoutComponent.extend = cc.Class.extend; })()"); } void register_all_cocos2dx_ui(JSContext* cx, JS::HandleObject obj) { diff --git a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_ui_auto.hpp b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_ui_auto.hpp index 60f36ffb88c9..648e9811a867 100644 --- a/cocos/scripting/js-bindings/auto/jsb_cocos2dx_ui_auto.hpp +++ b/cocos/scripting/js-bindings/auto/jsb_cocos2dx_ui_auto.hpp @@ -367,6 +367,7 @@ void js_register_cocos2dx_ui_ScrollView(JSContext *cx, JS::HandleObject global); void register_all_cocos2dx_ui(JSContext* cx, JS::HandleObject obj); bool js_cocos2dx_ui_ScrollView_scrollToTop(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_scrollToPercentHorizontal(JSContext *cx, uint32_t argc, jsval *vp); +bool js_cocos2dx_ui_ScrollView_setScrollBarOpacity(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_setScrollBarEnabled(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_isInertiaScrollEnabled(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_scrollToPercentBothDirection(JSContext *cx, uint32_t argc, jsval *vp); @@ -375,17 +376,20 @@ bool js_cocos2dx_ui_ScrollView_setScrollBarColor(JSContext *cx, uint32_t argc, j bool js_cocos2dx_ui_ScrollView_scrollToBottomLeft(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_getInnerContainer(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_jumpToBottom(JSContext *cx, uint32_t argc, jsval *vp); +bool js_cocos2dx_ui_ScrollView_setInnerContainerPosition(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_setDirection(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_scrollToTopLeft(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_jumpToTopRight(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_jumpToBottomLeft(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_setInnerContainerSize(JSContext *cx, uint32_t argc, jsval *vp); +bool js_cocos2dx_ui_ScrollView_getInnerContainerPosition(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_getInnerContainerSize(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_isBounceEnabled(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_jumpToPercentVertical(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_setScrollBarAutoHideTime(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_setScrollBarPositionFromCornerForHorizontal(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_setInertiaScrollEnabled(JSContext *cx, uint32_t argc, jsval *vp); +bool js_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_getScrollBarColor(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_jumpToTopLeft(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_jumpToPercentHorizontal(JSContext *cx, uint32_t argc, jsval *vp); @@ -399,7 +403,7 @@ bool js_cocos2dx_ui_ScrollView_jumpToPercentBothDirection(JSContext *cx, uint32_ bool js_cocos2dx_ui_ScrollView_getScrollBarPositionFromCornerForVertical(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_scrollToPercentVertical(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_scrollToBottom(JSContext *cx, uint32_t argc, jsval *vp); -bool js_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled(JSContext *cx, uint32_t argc, jsval *vp); +bool js_cocos2dx_ui_ScrollView_getScrollBarOpacity(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_scrollToBottomRight(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_setScrollBarPositionFromCorner(JSContext *cx, uint32_t argc, jsval *vp); bool js_cocos2dx_ui_ScrollView_setScrollBarPositionFromCornerForVertical(JSContext *cx, uint32_t argc, jsval *vp); diff --git a/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp b/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp index 87603e33ed58..1eb050e93551 100644 --- a/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp +++ b/cocos/scripting/js-bindings/manual/cocos2d_specifics.cpp @@ -50,7 +50,8 @@ JSTouchDelegate::~JSTouchDelegate() void JSTouchDelegate::setDelegateForJSObject(JSObject* pJSObj, JSTouchDelegate* pDelegate) { - CCASSERT(sTouchDelegateMap.find(pJSObj) == sTouchDelegateMap.end(), ""); + CCASSERT(sTouchDelegateMap.find(pJSObj) == sTouchDelegateMap.end(), + "pJSObj can't be found in sTouchDelegateMap."); sTouchDelegateMap.insert(TouchDelegatePair(pJSObj, pDelegate)); } @@ -68,7 +69,7 @@ JSTouchDelegate* JSTouchDelegate::getDelegateForJSObject(JSObject* pJSObj) void JSTouchDelegate::removeDelegateForJSObject(JSObject* pJSObj) { TouchDelegateMap::iterator iter = sTouchDelegateMap.find(pJSObj); - CCASSERT(iter != sTouchDelegateMap.end(), ""); + CCASSERT(iter != sTouchDelegateMap.end(), "pJSObj can't be found in sTouchDelegateMap!"); sTouchDelegateMap.erase(pJSObj); } @@ -1386,7 +1387,7 @@ void JSScheduleWrapper::dump() jsfuncTargetCount++; } } - CCASSERT(nativeTargetsCount == jsfuncTargetCount, ""); + CCASSERT(nativeTargetsCount == jsfuncTargetCount, "nativeTargetsCount should be equal to jsfuncTargetCount."); CCLOG("\n---------JSScheduleWrapper dump end--------------\n"); #endif } diff --git a/cocos/scripting/js-bindings/script/studio/jsb_studio_load.js b/cocos/scripting/js-bindings/script/studio/jsb_studio_load.js index 0c0e533e613d..1b8ae731d869 100644 --- a/cocos/scripting/js-bindings/script/studio/jsb_studio_load.js +++ b/cocos/scripting/js-bindings/script/studio/jsb_studio_load.js @@ -140,8 +140,8 @@ ccs._parser = cc.Class.extend({ return json["widgetTree"]; }, - parse: function(file, json){ - var resourcePath = this._dirname(file); + parse: function(file, json, resourcePath){ + resourcePath = resourcePath || this._dirname(file); this.pretreatment(json, resourcePath); var node = this.parseNode(this.getNodeJson(json), resourcePath, file); node && this.deferred(json, resourcePath, node, file); diff --git a/cocos/scripting/js-bindings/script/studio/parsers/timelineParser-2.x.js b/cocos/scripting/js-bindings/script/studio/parsers/timelineParser-2.x.js index 403eb6c6792f..eb3f4782801f 100644 --- a/cocos/scripting/js-bindings/script/studio/parsers/timelineParser-2.x.js +++ b/cocos/scripting/js-bindings/script/studio/parsers/timelineParser-2.x.js @@ -161,6 +161,9 @@ var node = new cc.Node(); this.generalAttributes(node, json); + var color = json["CColor"]; + if(color != null) + node.setColor(getColor(color)); return node; }; diff --git a/cocos/scripting/lua-bindings/auto/api/Action.lua b/cocos/scripting/lua-bindings/auto/api/Action.lua index 135b42c4c70a..db7269266580 100644 --- a/cocos/scripting/lua-bindings/auto/api/Action.lua +++ b/cocos/scripting/lua-bindings/auto/api/Action.lua @@ -63,6 +63,13 @@ -- @param self -- @return Node#Node ret (return value: cc.Node) +-------------------------------- +-- Returns a flag field that is used to group the actions easily.
+-- return A tag. +-- @function [parent=#Action] getFlags +-- @param self +-- @return unsigned int#unsigned int ret (return value: unsigned int) + -------------------------------- -- Called every frame with it's delta time, dt in seconds. DON'T override unless you know what you are doing.
-- param dt In seconds. @@ -79,6 +86,14 @@ -- @param #int tag -- @return Action#Action self (return value: cc.Action) +-------------------------------- +-- Changes the flag field that is used to group the actions easily.
+-- param tag Used to identify the action easily. +-- @function [parent=#Action] setFlags +-- @param self +-- @param #unsigned int flags +-- @return Action#Action self (return value: cc.Action) + -------------------------------- -- Returns a tag that is used to identify the action easily.
-- return A tag. diff --git a/cocos/scripting/lua-bindings/auto/api/ActionManager.lua b/cocos/scripting/lua-bindings/auto/api/ActionManager.lua index 60770f450f14..7fa1fe9771ff 100644 --- a/cocos/scripting/lua-bindings/auto/api/ActionManager.lua +++ b/cocos/scripting/lua-bindings/auto/api/ActionManager.lua @@ -25,6 +25,17 @@ -- @param #cc.Node target -- @return ActionManager#ActionManager self (return value: cc.ActionManager) +-------------------------------- +-- Removes all actions matching at least one bit in flags and the target.
+-- param flags The flag field to match the actions' flags based on bitwise AND.
+-- param target A certain target.
+-- js NA +-- @function [parent=#ActionManager] removeActionsByFlags +-- @param self +-- @param #unsigned int flags +-- @param #cc.Node target +-- @return ActionManager#ActionManager self (return value: cc.ActionManager) + -------------------------------- -- Removes all actions from all the targets. -- @function [parent=#ActionManager] removeAllActions diff --git a/cocos/scripting/lua-bindings/auto/api/Animate.lua b/cocos/scripting/lua-bindings/auto/api/Animate.lua index 219d5cfe36f6..a7bc3bba4ae6 100644 --- a/cocos/scripting/lua-bindings/auto/api/Animate.lua +++ b/cocos/scripting/lua-bindings/auto/api/Animate.lua @@ -4,6 +4,13 @@ -- @extend ActionInterval -- @parent_module cc +-------------------------------- +-- initializes the action with an Animation and will restore the original frame when the animation is over +-- @function [parent=#Animate] initWithAnimation +-- @param self +-- @param #cc.Animation animation +-- @return bool#bool ret (return value: bool) + -------------------------------- -- @overload self -- @overload self @@ -12,11 +19,11 @@ -- @return Animation#Animation ret (return value: cc.Animation) -------------------------------- --- initializes the action with an Animation and will restore the original frame when the animation is over --- @function [parent=#Animate] initWithAnimation +-- Gets the index of sprite frame currently displayed.
+-- return int the index of sprite frame currently displayed. +-- @function [parent=#Animate] getCurrentFrameIndex -- @param self --- @param #cc.Animation animation --- @return bool#bool ret (return value: bool) +-- @return int#int ret (return value: int) -------------------------------- -- Sets the Animation object to be animated
diff --git a/cocos/scripting/lua-bindings/auto/api/AudioEngine.lua b/cocos/scripting/lua-bindings/auto/api/AudioEngine.lua index 9fcf68b38206..5f4387f5dd2c 100644 --- a/cocos/scripting/lua-bindings/auto/api/AudioEngine.lua +++ b/cocos/scripting/lua-bindings/auto/api/AudioEngine.lua @@ -121,6 +121,14 @@ -- @param #float volume -- @return experimental::AudioEngine#experimental::AudioEngine self (return value: cc.experimental::AudioEngine) +-------------------------------- +-- Preload audio file.
+-- param filePath The file path of an audio. +-- @function [parent=#AudioEngine] preload +-- @param self +-- @param #string filePath +-- @return experimental::AudioEngine#experimental::AudioEngine self (return value: cc.experimental::AudioEngine) + -------------------------------- -- Play 2d sound.
-- param filePath The path of an audio file.
diff --git a/cocos/scripting/lua-bindings/auto/api/Frame.lua b/cocos/scripting/lua-bindings/auto/api/Frame.lua index dacd214807af..9be7ffcdeef1 100644 --- a/cocos/scripting/lua-bindings/auto/api/Frame.lua +++ b/cocos/scripting/lua-bindings/auto/api/Frame.lua @@ -10,6 +10,13 @@ -- @param self -- @return Frame#Frame ret (return value: ccs.Frame) +-------------------------------- +-- +-- @function [parent=#Frame] setTweenType +-- @param self +-- @param #int tweenType +-- @return Frame#Frame self (return value: ccs.Frame) + -------------------------------- -- -- @function [parent=#Frame] setNode @@ -30,6 +37,12 @@ -- @param self -- @return bool#bool ret (return value: bool) +-------------------------------- +-- +-- @function [parent=#Frame] getTweenType +-- @param self +-- @return int#int ret (return value: int) + -------------------------------- -- -- @function [parent=#Frame] getEasingParams diff --git a/cocos/scripting/lua-bindings/auto/api/Node.lua b/cocos/scripting/lua-bindings/auto/api/Node.lua index 7fd90a8953ad..cafaffb4fb30 100644 --- a/cocos/scripting/lua-bindings/auto/api/Node.lua +++ b/cocos/scripting/lua-bindings/auto/api/Node.lua @@ -305,6 +305,14 @@ -- @param #function callback -- @return Node#Node self (return value: cc.Node) +-------------------------------- +-- Removes all actions from the running action list by its flags.
+-- param flags A flag field that removes actions based on bitwise AND. +-- @function [parent=#Node] stopActionsByFlags +-- @param self +-- @param #unsigned int flags +-- @return Node#Node self (return value: cc.Node) + -------------------------------- -- Sets the position (x,y) using values between 0 and 1.
-- The positions in pixels is calculated like the following:
diff --git a/cocos/scripting/lua-bindings/auto/api/ScrollView.lua b/cocos/scripting/lua-bindings/auto/api/ScrollView.lua index 9dbbcbbbaacd..d73edbdb3d24 100644 --- a/cocos/scripting/lua-bindings/auto/api/ScrollView.lua +++ b/cocos/scripting/lua-bindings/auto/api/ScrollView.lua @@ -26,6 +26,14 @@ -- @param #bool attenuated -- @return ScrollView#ScrollView self (return value: ccui.ScrollView) +-------------------------------- +-- brief Set the scroll bar's opacity
+-- param the scroll bar's opacity +-- @function [parent=#ScrollView] setScrollBarOpacity +-- @param self +-- @param #unsigned char opacity +-- @return ScrollView#ScrollView self (return value: ccui.ScrollView) + -------------------------------- -- brief Toggle scroll bar enabled.
-- param enabled True if enable scroll bar, false otherwise. @@ -93,6 +101,14 @@ -- @param self -- @return ScrollView#ScrollView self (return value: ccui.ScrollView) +-------------------------------- +-- Set inner container position
+-- param pos Inner container position. +-- @function [parent=#ScrollView] setInnerContainerPosition +-- @param self +-- @param #vec2_table pos +-- @return ScrollView#ScrollView self (return value: ccui.ScrollView) + -------------------------------- -- Changes scroll direction of scrollview.
-- see `Direction`
@@ -133,6 +149,13 @@ -- @param #size_table size -- @return ScrollView#ScrollView self (return value: ccui.ScrollView) +-------------------------------- +-- Get inner container position
+-- return The inner container position. +-- @function [parent=#ScrollView] getInnerContainerPosition +-- @param self +-- @return vec2_table#vec2_table ret (return value: vec2_table) + -------------------------------- -- Get inner container size of scrollview.
-- Inner container size must be larger than or equal scrollview's size.
@@ -188,6 +211,14 @@ -- @param #bool enabled -- @return ScrollView#ScrollView self (return value: ccui.ScrollView) +-------------------------------- +-- brief Set scroll bar auto hide state
+-- param scroll bar auto hide state +-- @function [parent=#ScrollView] setScrollBarAutoHideEnabled +-- @param self +-- @param #bool autoHideEnabled +-- @return ScrollView#ScrollView self (return value: ccui.ScrollView) + -------------------------------- -- brief Get the scroll bar's color
-- return the scroll bar's color @@ -292,12 +323,11 @@ -- @return ScrollView#ScrollView self (return value: ccui.ScrollView) -------------------------------- --- brief Set scroll bar auto hide state
--- param scroll bar auto hide state --- @function [parent=#ScrollView] setScrollBarAutoHideEnabled +-- brief Get the scroll bar's opacity
+-- return the scroll bar's opacity +-- @function [parent=#ScrollView] getScrollBarOpacity -- @param self --- @param #bool autoHideEnabled --- @return ScrollView#ScrollView self (return value: ccui.ScrollView) +-- @return unsigned char#unsigned char ret (return value: unsigned char) -------------------------------- -- Scroll inner container to bottom and right boundary of scrollview.
diff --git a/cocos/scripting/lua-bindings/auto/api/SkeletonRenderer.lua b/cocos/scripting/lua-bindings/auto/api/SkeletonRenderer.lua index 02c244ef4900..bbf8e93347a1 100644 --- a/cocos/scripting/lua-bindings/auto/api/SkeletonRenderer.lua +++ b/cocos/scripting/lua-bindings/auto/api/SkeletonRenderer.lua @@ -23,12 +23,6 @@ -- @param self -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) --------------------------------- --- --- @function [parent=#SkeletonRenderer] isOpacityModifyRGB --- @param self --- @return bool#bool ret (return value: bool) - -------------------------------- -- -- @function [parent=#SkeletonRenderer] initWithData @@ -50,13 +44,6 @@ -- @param self -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) --------------------------------- --- --- @function [parent=#SkeletonRenderer] setOpacityModifyRGB --- @param self --- @param #bool value --- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) - -------------------------------- -- -- @function [parent=#SkeletonRenderer] setToSetupPose @@ -137,22 +124,35 @@ -------------------------------- -- --- @function [parent=#SkeletonRenderer] getBoundingBox +-- @function [parent=#SkeletonRenderer] onEnter -- @param self --- @return rect_table#rect_table ret (return value: rect_table) +-- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- --- @function [parent=#SkeletonRenderer] onEnter +-- @function [parent=#SkeletonRenderer] onExit -- @param self -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) -------------------------------- -- --- @function [parent=#SkeletonRenderer] onExit +-- @function [parent=#SkeletonRenderer] setOpacityModifyRGB -- @param self +-- @param #bool value -- @return SkeletonRenderer#SkeletonRenderer self (return value: sp.SkeletonRenderer) +-------------------------------- +-- +-- @function [parent=#SkeletonRenderer] getBoundingBox +-- @param self +-- @return rect_table#rect_table ret (return value: rect_table) + +-------------------------------- +-- +-- @function [parent=#SkeletonRenderer] isOpacityModifyRGB +-- @param self +-- @return bool#bool ret (return value: bool) + -------------------------------- -- @overload self, spSkeletonData, bool -- @overload self diff --git a/cocos/scripting/lua-bindings/auto/api/VideoPlayer.lua b/cocos/scripting/lua-bindings/auto/api/VideoPlayer.lua index b216cd505434..f70018cab429 100644 --- a/cocos/scripting/lua-bindings/auto/api/VideoPlayer.lua +++ b/cocos/scripting/lua-bindings/auto/api/VideoPlayer.lua @@ -24,12 +24,6 @@ -- @param self -- @return experimental::ui::VideoPlayer#experimental::ui::VideoPlayer self (return value: cc.experimental::ui::VideoPlayer) --------------------------------- --- Pauses playback. --- @function [parent=#VideoPlayer] pause --- @param self --- @return experimental::ui::VideoPlayer#experimental::ui::VideoPlayer self (return value: cc.experimental::ui::VideoPlayer) - -------------------------------- -- Causes the video player to keep aspect ratio or no when displaying the video.
-- param enable Specify true to keep aspect ratio or false to scale the video until
@@ -39,12 +33,6 @@ -- @param #bool enable -- @return experimental::ui::VideoPlayer#experimental::ui::VideoPlayer self (return value: cc.experimental::ui::VideoPlayer) --------------------------------- --- Resumes playback. --- @function [parent=#VideoPlayer] resume --- @param self --- @return experimental::ui::VideoPlayer#experimental::ui::VideoPlayer self (return value: cc.experimental::ui::VideoPlayer) - -------------------------------- -- Stops playback. -- @function [parent=#VideoPlayer] stop @@ -124,6 +112,12 @@ -- @param #unsigned int flags -- @return experimental::ui::VideoPlayer#experimental::ui::VideoPlayer self (return value: cc.experimental::ui::VideoPlayer) +-------------------------------- +-- Pauses playback. +-- @function [parent=#VideoPlayer] pause +-- @param self +-- @return experimental::ui::VideoPlayer#experimental::ui::VideoPlayer self (return value: cc.experimental::ui::VideoPlayer) + -------------------------------- -- -- @function [parent=#VideoPlayer] setVisible @@ -131,6 +125,12 @@ -- @param #bool visible -- @return experimental::ui::VideoPlayer#experimental::ui::VideoPlayer self (return value: cc.experimental::ui::VideoPlayer) +-------------------------------- +-- Resumes playback. +-- @function [parent=#VideoPlayer] resume +-- @param self +-- @return experimental::ui::VideoPlayer#experimental::ui::VideoPlayer self (return value: cc.experimental::ui::VideoPlayer) + -------------------------------- -- -- @function [parent=#VideoPlayer] VideoPlayer diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.cpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.cpp index cd28c13787f6..a899e762edb2 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.cpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.cpp @@ -590,6 +590,42 @@ int lua_cocos2dx_audioengine_AudioEngine_setVolume(lua_State* tolua_S) #endif return 0; } +int lua_cocos2dx_audioengine_AudioEngine_preload(lua_State* tolua_S) +{ + int argc = 0; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertable(tolua_S,1,"ccexp.AudioEngine",0,&tolua_err)) goto tolua_lerror; +#endif + + argc = lua_gettop(tolua_S) - 1; + + if (argc == 1) + { + std::string arg0; + ok &= luaval_to_std_string(tolua_S, 2,&arg0, "ccexp.AudioEngine:preload"); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_audioengine_AudioEngine_preload'", nullptr); + return 0; + } + cocos2d::experimental::AudioEngine::preload(arg0); + lua_settop(tolua_S, 1); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d\n ", "ccexp.AudioEngine:preload",argc, 1); + return 0; +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_audioengine_AudioEngine_preload'.",&tolua_err); +#endif + return 0; +} int lua_cocos2dx_audioengine_AudioEngine_play2d(lua_State* tolua_S) { int argc = 0; @@ -968,6 +1004,7 @@ int lua_register_cocos2dx_audioengine_AudioEngine(lua_State* tolua_S) tolua_function(tolua_S,"pauseAll", lua_cocos2dx_audioengine_AudioEngine_pauseAll); tolua_function(tolua_S,"uncacheAll", lua_cocos2dx_audioengine_AudioEngine_uncacheAll); tolua_function(tolua_S,"setVolume", lua_cocos2dx_audioengine_AudioEngine_setVolume); + tolua_function(tolua_S,"preload", lua_cocos2dx_audioengine_AudioEngine_preload); tolua_function(tolua_S,"play2d", lua_cocos2dx_audioengine_AudioEngine_play2d); tolua_function(tolua_S,"getState", lua_cocos2dx_audioengine_AudioEngine_getState); tolua_function(tolua_S,"resume", lua_cocos2dx_audioengine_AudioEngine_resume); diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.hpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.hpp index 8986dd181d8d..01e014651068 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.hpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_audioengine_auto.hpp @@ -37,6 +37,7 @@ int register_all_cocos2dx_audioengine(lua_State* tolua_S); + #endif // __cocos2dx_audioengine_h__ diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp index 2425ad5cfbe8..57906b2b5881 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.cpp @@ -4681,6 +4681,56 @@ int lua_cocos2dx_Node_setOnEnterCallback(lua_State* tolua_S) return 0; } +int lua_cocos2dx_Node_stopActionsByFlags(lua_State* tolua_S) +{ + int argc = 0; + cocos2d::Node* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"cc.Node",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocos2d::Node*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_Node_stopActionsByFlags'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 1) + { + unsigned int arg0; + + ok &= luaval_to_uint32(tolua_S, 2,&arg0, "cc.Node:stopActionsByFlags"); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Node_stopActionsByFlags'", nullptr); + return 0; + } + cobj->stopActionsByFlags(arg0); + lua_settop(tolua_S, 1); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Node:stopActionsByFlags",argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_Node_stopActionsByFlags'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_Node_setNormalizedPosition(lua_State* tolua_S) { int argc = 0; @@ -9585,6 +9635,7 @@ int lua_register_cocos2dx_Node(lua_State* tolua_S) tolua_function(tolua_S,"setSkewX",lua_cocos2dx_Node_setSkewX); tolua_function(tolua_S,"setGLProgramState",lua_cocos2dx_Node_setGLProgramState); tolua_function(tolua_S,"setOnEnterCallback",lua_cocos2dx_Node_setOnEnterCallback); + tolua_function(tolua_S,"stopActionsByFlags",lua_cocos2dx_Node_stopActionsByFlags); tolua_function(tolua_S,"setNormalizedPosition",lua_cocos2dx_Node_setNormalizedPosition); tolua_function(tolua_S,"setonExitTransitionDidStartCallback",lua_cocos2dx_Node_setonExitTransitionDidStartCallback); tolua_function(tolua_S,"convertTouchToNodeSpace",lua_cocos2dx_Node_convertTouchToNodeSpace); @@ -15853,6 +15904,53 @@ int lua_cocos2dx_Action_getTarget(lua_State* tolua_S) return 0; } +int lua_cocos2dx_Action_getFlags(lua_State* tolua_S) +{ + int argc = 0; + cocos2d::Action* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"cc.Action",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocos2d::Action*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_Action_getFlags'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 0) + { + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Action_getFlags'", nullptr); + return 0; + } + unsigned int ret = cobj->getFlags(); + tolua_pushnumber(tolua_S,(lua_Number)ret); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Action:getFlags",argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_Action_getFlags'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_Action_step(lua_State* tolua_S) { int argc = 0; @@ -15953,6 +16051,56 @@ int lua_cocos2dx_Action_setTag(lua_State* tolua_S) return 0; } +int lua_cocos2dx_Action_setFlags(lua_State* tolua_S) +{ + int argc = 0; + cocos2d::Action* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"cc.Action",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocos2d::Action*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_Action_setFlags'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 1) + { + unsigned int arg0; + + ok &= luaval_to_uint32(tolua_S, 2,&arg0, "cc.Action:setFlags"); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Action_setFlags'", nullptr); + return 0; + } + cobj->setFlags(arg0); + lua_settop(tolua_S, 1); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Action:setFlags",argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_Action_setFlags'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_Action_getTag(lua_State* tolua_S) { int argc = 0; @@ -16163,8 +16311,10 @@ int lua_register_cocos2dx_Action(lua_State* tolua_S) tolua_function(tolua_S,"stop",lua_cocos2dx_Action_stop); tolua_function(tolua_S,"update",lua_cocos2dx_Action_update); tolua_function(tolua_S,"getTarget",lua_cocos2dx_Action_getTarget); + tolua_function(tolua_S,"getFlags",lua_cocos2dx_Action_getFlags); tolua_function(tolua_S,"step",lua_cocos2dx_Action_step); tolua_function(tolua_S,"setTag",lua_cocos2dx_Action_setTag); + tolua_function(tolua_S,"setFlags",lua_cocos2dx_Action_setFlags); tolua_function(tolua_S,"getTag",lua_cocos2dx_Action_getTag); tolua_function(tolua_S,"setTarget",lua_cocos2dx_Action_setTarget); tolua_function(tolua_S,"isDone",lua_cocos2dx_Action_isDone); @@ -23618,6 +23768,56 @@ int lua_register_cocos2dx_DelayTime(lua_State* tolua_S) return 1; } +int lua_cocos2dx_Animate_initWithAnimation(lua_State* tolua_S) +{ + int argc = 0; + cocos2d::Animate* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"cc.Animate",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocos2d::Animate*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_Animate_initWithAnimation'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 1) + { + cocos2d::Animation* arg0; + + ok &= luaval_to_object(tolua_S, 2, "cc.Animation",&arg0, "cc.Animate:initWithAnimation"); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Animate_initWithAnimation'", nullptr); + return 0; + } + bool ret = cobj->initWithAnimation(arg0); + tolua_pushboolean(tolua_S,(bool)ret); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Animate:initWithAnimation",argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_Animate_initWithAnimation'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_Animate_getAnimation(lua_State* tolua_S) { int argc = 0; @@ -23665,7 +23865,7 @@ int lua_cocos2dx_Animate_getAnimation(lua_State* tolua_S) return 0; } -int lua_cocos2dx_Animate_initWithAnimation(lua_State* tolua_S) +int lua_cocos2dx_Animate_getCurrentFrameIndex(lua_State* tolua_S) { int argc = 0; cocos2d::Animate* cobj = nullptr; @@ -23685,32 +23885,29 @@ int lua_cocos2dx_Animate_initWithAnimation(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 if (!cobj) { - tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_Animate_initWithAnimation'", nullptr); + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_Animate_getCurrentFrameIndex'", nullptr); return 0; } #endif argc = lua_gettop(tolua_S)-1; - if (argc == 1) + if (argc == 0) { - cocos2d::Animation* arg0; - - ok &= luaval_to_object(tolua_S, 2, "cc.Animation",&arg0, "cc.Animate:initWithAnimation"); if(!ok) { - tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Animate_initWithAnimation'", nullptr); + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_Animate_getCurrentFrameIndex'", nullptr); return 0; } - bool ret = cobj->initWithAnimation(arg0); - tolua_pushboolean(tolua_S,(bool)ret); + int ret = cobj->getCurrentFrameIndex(); + tolua_pushnumber(tolua_S,(lua_Number)ret); return 1; } - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Animate:initWithAnimation",argc, 1); + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.Animate:getCurrentFrameIndex",argc, 0); return 0; #if COCOS2D_DEBUG >= 1 tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_Animate_initWithAnimation'.",&tolua_err); + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_Animate_getCurrentFrameIndex'.",&tolua_err); #endif return 0; @@ -23851,8 +24048,9 @@ int lua_register_cocos2dx_Animate(lua_State* tolua_S) tolua_beginmodule(tolua_S,"Animate"); tolua_function(tolua_S,"new",lua_cocos2dx_Animate_constructor); - tolua_function(tolua_S,"getAnimation",lua_cocos2dx_Animate_getAnimation); tolua_function(tolua_S,"initWithAnimation",lua_cocos2dx_Animate_initWithAnimation); + tolua_function(tolua_S,"getAnimation",lua_cocos2dx_Animate_getAnimation); + tolua_function(tolua_S,"getCurrentFrameIndex",lua_cocos2dx_Animate_getCurrentFrameIndex); tolua_function(tolua_S,"setAnimation",lua_cocos2dx_Animate_setAnimation); tolua_function(tolua_S,"create", lua_cocos2dx_Animate_create); tolua_endmodule(tolua_S); @@ -40509,6 +40707,59 @@ int lua_cocos2dx_ActionManager_removeActionByTag(lua_State* tolua_S) return 0; } +int lua_cocos2dx_ActionManager_removeActionsByFlags(lua_State* tolua_S) +{ + int argc = 0; + cocos2d::ActionManager* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"cc.ActionManager",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocos2d::ActionManager*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_ActionManager_removeActionsByFlags'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 2) + { + unsigned int arg0; + cocos2d::Node* arg1; + + ok &= luaval_to_uint32(tolua_S, 2,&arg0, "cc.ActionManager:removeActionsByFlags"); + + ok &= luaval_to_object(tolua_S, 3, "cc.Node",&arg1, "cc.ActionManager:removeActionsByFlags"); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ActionManager_removeActionsByFlags'", nullptr); + return 0; + } + cobj->removeActionsByFlags(arg0, arg1); + lua_settop(tolua_S, 1); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "cc.ActionManager:removeActionsByFlags",argc, 2); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_ActionManager_removeActionsByFlags'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_ActionManager_removeAllActions(lua_State* tolua_S) { int argc = 0; @@ -41114,6 +41365,7 @@ int lua_register_cocos2dx_ActionManager(lua_State* tolua_S) tolua_function(tolua_S,"new",lua_cocos2dx_ActionManager_constructor); tolua_function(tolua_S,"getActionByTag",lua_cocos2dx_ActionManager_getActionByTag); tolua_function(tolua_S,"removeActionByTag",lua_cocos2dx_ActionManager_removeActionByTag); + tolua_function(tolua_S,"removeActionsByFlags",lua_cocos2dx_ActionManager_removeActionsByFlags); tolua_function(tolua_S,"removeAllActions",lua_cocos2dx_ActionManager_removeAllActions); tolua_function(tolua_S,"addAction",lua_cocos2dx_ActionManager_addAction); tolua_function(tolua_S,"resumeTarget",lua_cocos2dx_ActionManager_resumeTarget); diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp index ccd719643231..aa18db277ab3 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_auto.hpp @@ -2065,6 +2065,11 @@ int register_all_cocos2dx(lua_State* tolua_S); + + + + + diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_experimental_video_auto.cpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_experimental_video_auto.cpp index 64d3c0f76dad..159182cde6cf 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_experimental_video_auto.cpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_experimental_video_auto.cpp @@ -146,53 +146,6 @@ int lua_cocos2dx_experimental_video_VideoPlayer_play(lua_State* tolua_S) return 0; } -int lua_cocos2dx_experimental_video_VideoPlayer_pause(lua_State* tolua_S) -{ - int argc = 0; - cocos2d::experimental::ui::VideoPlayer* cobj = nullptr; - bool ok = true; - -#if COCOS2D_DEBUG >= 1 - tolua_Error tolua_err; -#endif - - -#if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror; -#endif - - cobj = (cocos2d::experimental::ui::VideoPlayer*)tolua_tousertype(tolua_S,1,0); - -#if COCOS2D_DEBUG >= 1 - if (!cobj) - { - tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_experimental_video_VideoPlayer_pause'", nullptr); - return 0; - } -#endif - - argc = lua_gettop(tolua_S)-1; - if (argc == 0) - { - if(!ok) - { - tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_pause'", nullptr); - return 0; - } - cobj->pause(); - lua_settop(tolua_S, 1); - return 1; - } - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:pause",argc, 0); - return 0; - -#if COCOS2D_DEBUG >= 1 - tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_pause'.",&tolua_err); -#endif - - return 0; -} int lua_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled(lua_State* tolua_S) { int argc = 0; @@ -243,53 +196,6 @@ int lua_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled(lua_St return 0; } -int lua_cocos2dx_experimental_video_VideoPlayer_resume(lua_State* tolua_S) -{ - int argc = 0; - cocos2d::experimental::ui::VideoPlayer* cobj = nullptr; - bool ok = true; - -#if COCOS2D_DEBUG >= 1 - tolua_Error tolua_err; -#endif - - -#if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"ccexp.VideoPlayer",0,&tolua_err)) goto tolua_lerror; -#endif - - cobj = (cocos2d::experimental::ui::VideoPlayer*)tolua_tousertype(tolua_S,1,0); - -#if COCOS2D_DEBUG >= 1 - if (!cobj) - { - tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_experimental_video_VideoPlayer_resume'", nullptr); - return 0; - } -#endif - - argc = lua_gettop(tolua_S)-1; - if (argc == 0) - { - if(!ok) - { - tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_experimental_video_VideoPlayer_resume'", nullptr); - return 0; - } - cobj->resume(); - lua_settop(tolua_S, 1); - return 1; - } - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccexp.VideoPlayer:resume",argc, 0); - return 0; - -#if COCOS2D_DEBUG >= 1 - tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_experimental_video_VideoPlayer_resume'.",&tolua_err); -#endif - - return 0; -} int lua_cocos2dx_experimental_video_VideoPlayer_stop(lua_State* tolua_S) { int argc = 0; @@ -815,9 +721,7 @@ int lua_register_cocos2dx_experimental_video_VideoPlayer(lua_State* tolua_S) tolua_function(tolua_S,"getFileName",lua_cocos2dx_experimental_video_VideoPlayer_getFileName); tolua_function(tolua_S,"getURL",lua_cocos2dx_experimental_video_VideoPlayer_getURL); tolua_function(tolua_S,"play",lua_cocos2dx_experimental_video_VideoPlayer_play); - tolua_function(tolua_S,"pause",lua_cocos2dx_experimental_video_VideoPlayer_pause); tolua_function(tolua_S,"setKeepAspectRatioEnabled",lua_cocos2dx_experimental_video_VideoPlayer_setKeepAspectRatioEnabled); - tolua_function(tolua_S,"resume",lua_cocos2dx_experimental_video_VideoPlayer_resume); tolua_function(tolua_S,"stop",lua_cocos2dx_experimental_video_VideoPlayer_stop); tolua_function(tolua_S,"setFullScreenEnabled",lua_cocos2dx_experimental_video_VideoPlayer_setFullScreenEnabled); tolua_function(tolua_S,"setFileName",lua_cocos2dx_experimental_video_VideoPlayer_setFileName); diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_experimental_video_auto.hpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_experimental_video_auto.hpp index 44597483da4f..5f9cf0537b67 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_experimental_video_auto.hpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_experimental_video_auto.hpp @@ -29,7 +29,5 @@ int register_all_cocos2dx_experimental_video(lua_State* tolua_S); - - #endif // __cocos2dx_experimental_video_h__ #endif //#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS) diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_spine_auto.cpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_spine_auto.cpp index 00a9ed6e1bf8..63214e30e23b 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_spine_auto.cpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_spine_auto.cpp @@ -148,53 +148,6 @@ int lua_cocos2dx_spine_SkeletonRenderer_setBonesToSetupPose(lua_State* tolua_S) return 0; } -int lua_cocos2dx_spine_SkeletonRenderer_isOpacityModifyRGB(lua_State* tolua_S) -{ - int argc = 0; - spine::SkeletonRenderer* cobj = nullptr; - bool ok = true; - -#if COCOS2D_DEBUG >= 1 - tolua_Error tolua_err; -#endif - - -#if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"sp.SkeletonRenderer",0,&tolua_err)) goto tolua_lerror; -#endif - - cobj = (spine::SkeletonRenderer*)tolua_tousertype(tolua_S,1,0); - -#if COCOS2D_DEBUG >= 1 - if (!cobj) - { - tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_spine_SkeletonRenderer_isOpacityModifyRGB'", nullptr); - return 0; - } -#endif - - argc = lua_gettop(tolua_S)-1; - if (argc == 0) - { - if(!ok) - { - tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_spine_SkeletonRenderer_isOpacityModifyRGB'", nullptr); - return 0; - } - bool ret = cobj->isOpacityModifyRGB(); - tolua_pushboolean(tolua_S,(bool)ret); - return 1; - } - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "sp.SkeletonRenderer:isOpacityModifyRGB",argc, 0); - return 0; - -#if COCOS2D_DEBUG >= 1 - tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_spine_SkeletonRenderer_isOpacityModifyRGB'.",&tolua_err); -#endif - - return 0; -} int lua_cocos2dx_spine_SkeletonRenderer_initWithData(lua_State* tolua_S) { int argc = 0; @@ -361,56 +314,6 @@ int lua_cocos2dx_spine_SkeletonRenderer_setSlotsToSetupPose(lua_State* tolua_S) return 0; } -int lua_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB(lua_State* tolua_S) -{ - int argc = 0; - spine::SkeletonRenderer* cobj = nullptr; - bool ok = true; - -#if COCOS2D_DEBUG >= 1 - tolua_Error tolua_err; -#endif - - -#if COCOS2D_DEBUG >= 1 - if (!tolua_isusertype(tolua_S,1,"sp.SkeletonRenderer",0,&tolua_err)) goto tolua_lerror; -#endif - - cobj = (spine::SkeletonRenderer*)tolua_tousertype(tolua_S,1,0); - -#if COCOS2D_DEBUG >= 1 - if (!cobj) - { - tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB'", nullptr); - return 0; - } -#endif - - argc = lua_gettop(tolua_S)-1; - if (argc == 1) - { - bool arg0; - - ok &= luaval_to_boolean(tolua_S, 2,&arg0, "sp.SkeletonRenderer:setOpacityModifyRGB"); - if(!ok) - { - tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB'", nullptr); - return 0; - } - cobj->setOpacityModifyRGB(arg0); - lua_settop(tolua_S, 1); - return 1; - } - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "sp.SkeletonRenderer:setOpacityModifyRGB",argc, 1); - return 0; - -#if COCOS2D_DEBUG >= 1 - tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB'.",&tolua_err); -#endif - - return 0; -} int lua_cocos2dx_spine_SkeletonRenderer_setToSetupPose(lua_State* tolua_S) { int argc = 0; @@ -1216,11 +1119,9 @@ int lua_register_cocos2dx_spine_SkeletonRenderer(lua_State* tolua_S) tolua_function(tolua_S,"setTimeScale",lua_cocos2dx_spine_SkeletonRenderer_setTimeScale); tolua_function(tolua_S,"getDebugSlotsEnabled",lua_cocos2dx_spine_SkeletonRenderer_getDebugSlotsEnabled); tolua_function(tolua_S,"setBonesToSetupPose",lua_cocos2dx_spine_SkeletonRenderer_setBonesToSetupPose); - tolua_function(tolua_S,"isOpacityModifyRGB",lua_cocos2dx_spine_SkeletonRenderer_isOpacityModifyRGB); tolua_function(tolua_S,"initWithData",lua_cocos2dx_spine_SkeletonRenderer_initWithData); tolua_function(tolua_S,"setDebugSlotsEnabled",lua_cocos2dx_spine_SkeletonRenderer_setDebugSlotsEnabled); tolua_function(tolua_S,"setSlotsToSetupPose",lua_cocos2dx_spine_SkeletonRenderer_setSlotsToSetupPose); - tolua_function(tolua_S,"setOpacityModifyRGB",lua_cocos2dx_spine_SkeletonRenderer_setOpacityModifyRGB); tolua_function(tolua_S,"setToSetupPose",lua_cocos2dx_spine_SkeletonRenderer_setToSetupPose); tolua_function(tolua_S,"getBlendFunc",lua_cocos2dx_spine_SkeletonRenderer_getBlendFunc); tolua_function(tolua_S,"initialize",lua_cocos2dx_spine_SkeletonRenderer_initialize); diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_spine_auto.hpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_spine_auto.hpp index 553ec82c5b2e..f9bcf11d4f4c 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_spine_auto.hpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_spine_auto.hpp @@ -41,8 +41,6 @@ int register_all_cocos2dx_spine(lua_State* tolua_S); - - diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp index e7b77f2c612f..ac4bfc445785 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.cpp @@ -15792,6 +15792,56 @@ int lua_cocos2dx_studio_Frame_clone(lua_State* tolua_S) return 0; } +int lua_cocos2dx_studio_Frame_setTweenType(lua_State* tolua_S) +{ + int argc = 0; + cocostudio::timeline::Frame* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"ccs.Frame",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocostudio::timeline::Frame*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_studio_Frame_setTweenType'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 1) + { + cocos2d::tweenfunc::TweenType arg0; + + ok &= luaval_to_int32(tolua_S, 2,(int *)&arg0, "ccs.Frame:setTweenType"); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Frame_setTweenType'", nullptr); + return 0; + } + cobj->setTweenType(arg0); + lua_settop(tolua_S, 1); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccs.Frame:setTweenType",argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_studio_Frame_setTweenType'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_studio_Frame_setNode(lua_State* tolua_S) { int argc = 0; @@ -15939,6 +15989,53 @@ int lua_cocos2dx_studio_Frame_isEnterWhenPassed(lua_State* tolua_S) return 0; } +int lua_cocos2dx_studio_Frame_getTweenType(lua_State* tolua_S) +{ + int argc = 0; + cocostudio::timeline::Frame* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"ccs.Frame",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocostudio::timeline::Frame*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_studio_Frame_getTweenType'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 0) + { + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_studio_Frame_getTweenType'", nullptr); + return 0; + } + int ret = (int)cobj->getTweenType(); + tolua_pushnumber(tolua_S,(lua_Number)ret); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccs.Frame:getTweenType",argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_studio_Frame_getTweenType'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_studio_Frame_getEasingParams(lua_State* tolua_S) { int argc = 0; @@ -16387,9 +16484,11 @@ int lua_register_cocos2dx_studio_Frame(lua_State* tolua_S) tolua_beginmodule(tolua_S,"Frame"); tolua_function(tolua_S,"clone",lua_cocos2dx_studio_Frame_clone); + tolua_function(tolua_S,"setTweenType",lua_cocos2dx_studio_Frame_setTweenType); tolua_function(tolua_S,"setNode",lua_cocos2dx_studio_Frame_setNode); tolua_function(tolua_S,"setTimeline",lua_cocos2dx_studio_Frame_setTimeline); tolua_function(tolua_S,"isEnterWhenPassed",lua_cocos2dx_studio_Frame_isEnterWhenPassed); + tolua_function(tolua_S,"getTweenType",lua_cocos2dx_studio_Frame_getTweenType); tolua_function(tolua_S,"getEasingParams",lua_cocos2dx_studio_Frame_getEasingParams); tolua_function(tolua_S,"setEasingParams",lua_cocos2dx_studio_Frame_setEasingParams); tolua_function(tolua_S,"getFrameIndex",lua_cocos2dx_studio_Frame_getFrameIndex); diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.hpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.hpp index 41c31388e844..60e3ce9e08cf 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.hpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_studio_auto.hpp @@ -512,6 +512,8 @@ int register_all_cocos2dx_studio(lua_State* tolua_S); + + diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp index c67cf3c6610f..664d0a9fcfe0 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.cpp @@ -11205,6 +11205,56 @@ int lua_cocos2dx_ui_ScrollView_scrollToPercentHorizontal(lua_State* tolua_S) return 0; } +int lua_cocos2dx_ui_ScrollView_setScrollBarOpacity(lua_State* tolua_S) +{ + int argc = 0; + cocos2d::ui::ScrollView* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"ccui.ScrollView",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocos2d::ui::ScrollView*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_ui_ScrollView_setScrollBarOpacity'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 1) + { + uint16_t arg0; + + ok &= luaval_to_uint16(tolua_S, 2,&arg0, "ccui.ScrollView:setScrollBarOpacity"); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_ScrollView_setScrollBarOpacity'", nullptr); + return 0; + } + cobj->setScrollBarOpacity(arg0); + lua_settop(tolua_S, 1); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.ScrollView:setScrollBarOpacity",argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_ui_ScrollView_setScrollBarOpacity'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_ui_ScrollView_setScrollBarEnabled(lua_State* tolua_S) { int argc = 0; @@ -11602,6 +11652,56 @@ int lua_cocos2dx_ui_ScrollView_jumpToBottom(lua_State* tolua_S) return 0; } +int lua_cocos2dx_ui_ScrollView_setInnerContainerPosition(lua_State* tolua_S) +{ + int argc = 0; + cocos2d::ui::ScrollView* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"ccui.ScrollView",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocos2d::ui::ScrollView*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_ui_ScrollView_setInnerContainerPosition'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 1) + { + cocos2d::Vec2 arg0; + + ok &= luaval_to_vec2(tolua_S, 2, &arg0, "ccui.ScrollView:setInnerContainerPosition"); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_ScrollView_setInnerContainerPosition'", nullptr); + return 0; + } + cobj->setInnerContainerPosition(arg0); + lua_settop(tolua_S, 1); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.ScrollView:setInnerContainerPosition",argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_ui_ScrollView_setInnerContainerPosition'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_ui_ScrollView_setDirection(lua_State* tolua_S) { int argc = 0; @@ -11849,6 +11949,53 @@ int lua_cocos2dx_ui_ScrollView_setInnerContainerSize(lua_State* tolua_S) return 0; } +int lua_cocos2dx_ui_ScrollView_getInnerContainerPosition(lua_State* tolua_S) +{ + int argc = 0; + cocos2d::ui::ScrollView* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"ccui.ScrollView",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocos2d::ui::ScrollView*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_ui_ScrollView_getInnerContainerPosition'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 0) + { + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_ScrollView_getInnerContainerPosition'", nullptr); + return 0; + } + cocos2d::Vec2 ret = cobj->getInnerContainerPosition(); + vec2_to_luaval(tolua_S, ret); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.ScrollView:getInnerContainerPosition",argc, 0); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_ui_ScrollView_getInnerContainerPosition'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_ui_ScrollView_getInnerContainerSize(lua_State* tolua_S) { int argc = 0; @@ -12197,6 +12344,56 @@ int lua_cocos2dx_ui_ScrollView_setInertiaScrollEnabled(lua_State* tolua_S) return 0; } +int lua_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled(lua_State* tolua_S) +{ + int argc = 0; + cocos2d::ui::ScrollView* cobj = nullptr; + bool ok = true; + +#if COCOS2D_DEBUG >= 1 + tolua_Error tolua_err; +#endif + + +#if COCOS2D_DEBUG >= 1 + if (!tolua_isusertype(tolua_S,1,"ccui.ScrollView",0,&tolua_err)) goto tolua_lerror; +#endif + + cobj = (cocos2d::ui::ScrollView*)tolua_tousertype(tolua_S,1,0); + +#if COCOS2D_DEBUG >= 1 + if (!cobj) + { + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled'", nullptr); + return 0; + } +#endif + + argc = lua_gettop(tolua_S)-1; + if (argc == 1) + { + bool arg0; + + ok &= luaval_to_boolean(tolua_S, 2,&arg0, "ccui.ScrollView:setScrollBarAutoHideEnabled"); + if(!ok) + { + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled'", nullptr); + return 0; + } + cobj->setScrollBarAutoHideEnabled(arg0); + lua_settop(tolua_S, 1); + return 1; + } + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.ScrollView:setScrollBarAutoHideEnabled",argc, 1); + return 0; + +#if COCOS2D_DEBUG >= 1 + tolua_lerror: + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled'.",&tolua_err); +#endif + + return 0; +} int lua_cocos2dx_ui_ScrollView_getScrollBarColor(lua_State* tolua_S) { int argc = 0; @@ -12841,7 +13038,7 @@ int lua_cocos2dx_ui_ScrollView_scrollToBottom(lua_State* tolua_S) return 0; } -int lua_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled(lua_State* tolua_S) +int lua_cocos2dx_ui_ScrollView_getScrollBarOpacity(lua_State* tolua_S) { int argc = 0; cocos2d::ui::ScrollView* cobj = nullptr; @@ -12861,32 +13058,29 @@ int lua_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled(lua_State* tolua_S) #if COCOS2D_DEBUG >= 1 if (!cobj) { - tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled'", nullptr); + tolua_error(tolua_S,"invalid 'cobj' in function 'lua_cocos2dx_ui_ScrollView_getScrollBarOpacity'", nullptr); return 0; } #endif argc = lua_gettop(tolua_S)-1; - if (argc == 1) + if (argc == 0) { - bool arg0; - - ok &= luaval_to_boolean(tolua_S, 2,&arg0, "ccui.ScrollView:setScrollBarAutoHideEnabled"); if(!ok) { - tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled'", nullptr); + tolua_error(tolua_S,"invalid arguments in function 'lua_cocos2dx_ui_ScrollView_getScrollBarOpacity'", nullptr); return 0; } - cobj->setScrollBarAutoHideEnabled(arg0); - lua_settop(tolua_S, 1); + uint16_t ret = cobj->getScrollBarOpacity(); + tolua_pushnumber(tolua_S,(lua_Number)ret); return 1; } - luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.ScrollView:setScrollBarAutoHideEnabled",argc, 1); + luaL_error(tolua_S, "%s has wrong number of arguments: %d, was expecting %d \n", "ccui.ScrollView:getScrollBarOpacity",argc, 0); return 0; #if COCOS2D_DEBUG >= 1 tolua_lerror: - tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled'.",&tolua_err); + tolua_error(tolua_S,"#ferror in function 'lua_cocos2dx_ui_ScrollView_getScrollBarOpacity'.",&tolua_err); #endif return 0; @@ -13552,6 +13746,7 @@ int lua_register_cocos2dx_ui_ScrollView(lua_State* tolua_S) tolua_function(tolua_S,"new",lua_cocos2dx_ui_ScrollView_constructor); tolua_function(tolua_S,"scrollToTop",lua_cocos2dx_ui_ScrollView_scrollToTop); tolua_function(tolua_S,"scrollToPercentHorizontal",lua_cocos2dx_ui_ScrollView_scrollToPercentHorizontal); + tolua_function(tolua_S,"setScrollBarOpacity",lua_cocos2dx_ui_ScrollView_setScrollBarOpacity); tolua_function(tolua_S,"setScrollBarEnabled",lua_cocos2dx_ui_ScrollView_setScrollBarEnabled); tolua_function(tolua_S,"isInertiaScrollEnabled",lua_cocos2dx_ui_ScrollView_isInertiaScrollEnabled); tolua_function(tolua_S,"scrollToPercentBothDirection",lua_cocos2dx_ui_ScrollView_scrollToPercentBothDirection); @@ -13560,11 +13755,13 @@ int lua_register_cocos2dx_ui_ScrollView(lua_State* tolua_S) tolua_function(tolua_S,"scrollToBottomLeft",lua_cocos2dx_ui_ScrollView_scrollToBottomLeft); tolua_function(tolua_S,"getInnerContainer",lua_cocos2dx_ui_ScrollView_getInnerContainer); tolua_function(tolua_S,"jumpToBottom",lua_cocos2dx_ui_ScrollView_jumpToBottom); + tolua_function(tolua_S,"setInnerContainerPosition",lua_cocos2dx_ui_ScrollView_setInnerContainerPosition); tolua_function(tolua_S,"setDirection",lua_cocos2dx_ui_ScrollView_setDirection); tolua_function(tolua_S,"scrollToTopLeft",lua_cocos2dx_ui_ScrollView_scrollToTopLeft); tolua_function(tolua_S,"jumpToTopRight",lua_cocos2dx_ui_ScrollView_jumpToTopRight); tolua_function(tolua_S,"jumpToBottomLeft",lua_cocos2dx_ui_ScrollView_jumpToBottomLeft); tolua_function(tolua_S,"setInnerContainerSize",lua_cocos2dx_ui_ScrollView_setInnerContainerSize); + tolua_function(tolua_S,"getInnerContainerPosition",lua_cocos2dx_ui_ScrollView_getInnerContainerPosition); tolua_function(tolua_S,"getInnerContainerSize",lua_cocos2dx_ui_ScrollView_getInnerContainerSize); tolua_function(tolua_S,"isBounceEnabled",lua_cocos2dx_ui_ScrollView_isBounceEnabled); tolua_function(tolua_S,"jumpToPercentVertical",lua_cocos2dx_ui_ScrollView_jumpToPercentVertical); @@ -13572,6 +13769,7 @@ int lua_register_cocos2dx_ui_ScrollView(lua_State* tolua_S) tolua_function(tolua_S,"setScrollBarAutoHideTime",lua_cocos2dx_ui_ScrollView_setScrollBarAutoHideTime); tolua_function(tolua_S,"setScrollBarPositionFromCornerForHorizontal",lua_cocos2dx_ui_ScrollView_setScrollBarPositionFromCornerForHorizontal); tolua_function(tolua_S,"setInertiaScrollEnabled",lua_cocos2dx_ui_ScrollView_setInertiaScrollEnabled); + tolua_function(tolua_S,"setScrollBarAutoHideEnabled",lua_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled); tolua_function(tolua_S,"getScrollBarColor",lua_cocos2dx_ui_ScrollView_getScrollBarColor); tolua_function(tolua_S,"jumpToTopLeft",lua_cocos2dx_ui_ScrollView_jumpToTopLeft); tolua_function(tolua_S,"jumpToPercentHorizontal",lua_cocos2dx_ui_ScrollView_jumpToPercentHorizontal); @@ -13585,7 +13783,7 @@ int lua_register_cocos2dx_ui_ScrollView(lua_State* tolua_S) tolua_function(tolua_S,"getScrollBarPositionFromCornerForVertical",lua_cocos2dx_ui_ScrollView_getScrollBarPositionFromCornerForVertical); tolua_function(tolua_S,"scrollToPercentVertical",lua_cocos2dx_ui_ScrollView_scrollToPercentVertical); tolua_function(tolua_S,"scrollToBottom",lua_cocos2dx_ui_ScrollView_scrollToBottom); - tolua_function(tolua_S,"setScrollBarAutoHideEnabled",lua_cocos2dx_ui_ScrollView_setScrollBarAutoHideEnabled); + tolua_function(tolua_S,"getScrollBarOpacity",lua_cocos2dx_ui_ScrollView_getScrollBarOpacity); tolua_function(tolua_S,"scrollToBottomRight",lua_cocos2dx_ui_ScrollView_scrollToBottomRight); tolua_function(tolua_S,"setScrollBarPositionFromCorner",lua_cocos2dx_ui_ScrollView_setScrollBarPositionFromCorner); tolua_function(tolua_S,"setScrollBarPositionFromCornerForVertical",lua_cocos2dx_ui_ScrollView_setScrollBarPositionFromCornerForVertical); diff --git a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.hpp b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.hpp index a450edd5dc60..04b1db275398 100644 --- a/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.hpp +++ b/cocos/scripting/lua-bindings/auto/lua_cocos2dx_ui_auto.hpp @@ -565,6 +565,10 @@ int register_all_cocos2dx_ui(lua_State* tolua_S); + + + + diff --git a/cocos/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp b/cocos/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp index 3862c9fd0c70..df1514c1c595 100644 --- a/cocos/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp +++ b/cocos/scripting/lua-bindings/manual/network/lua_xml_http_request.cpp @@ -59,6 +59,7 @@ LuaMinXmlHttpRequest::~LuaMinXmlHttpRequest() { _httpHeader.clear(); _requestHeader.clear(); + CC_SAFE_RELEASE_NULL(_httpRequest); } /** @@ -268,7 +269,7 @@ void LuaMinXmlHttpRequest::_sendRequest() release(); }); network::HttpClient::getInstance()->sendImmediate(_httpRequest); - _httpRequest->release(); + CC_SAFE_RELEASE_NULL(_httpRequest); retain(); } diff --git a/cocos/ui/UILayoutComponent.cpp b/cocos/ui/UILayoutComponent.cpp index 200a2714f2fa..50a01a7d85f6 100644 --- a/cocos/ui/UILayoutComponent.cpp +++ b/cocos/ui/UILayoutComponent.cpp @@ -21,7 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - +#include "UIPageView.h" #include "UILayoutComponent.h" #include "2d/CCNode.h" #include "GUIDefine.h" @@ -667,7 +667,21 @@ namespace ui { _owner->setPosition(ownerPosition); _owner->setContentSize(ownerSize); - ui::Helper::doLayout(_owner); + if (typeid(*_owner) == typeid(PageView)) + { + PageView* page = static_cast(_owner); + page->forceDoLayout(); + + Vector _layoutVector = page->getPages(); + for(auto& item : _layoutVector) + { + ui::Helper::doLayout(item); + } + } + else + { + ui::Helper::doLayout(_owner); + } } void LayoutComponent::setActiveEnabled(bool enable) diff --git a/cocos/ui/UIScrollView.cpp b/cocos/ui/UIScrollView.cpp index f32cac06beed..51b9d1f5f5da 100644 --- a/cocos/ui/UIScrollView.cpp +++ b/cocos/ui/UIScrollView.cpp @@ -149,7 +149,7 @@ void ScrollView::onSizeChanged() float innerSizeWidth = MAX(orginInnerSizeWidth, _contentSize.width); float innerSizeHeight = MAX(orginInnerSizeHeight, _contentSize.height); _innerContainer->setContentSize(Size(innerSizeWidth, innerSizeHeight)); - _innerContainer->setPosition(Vec2(0, _contentSize.height - _innerContainer->getContentSize().height)); + setInnerContainerPosition(Vec2(0, _contentSize.height - _innerContainer->getContentSize().height)); } void ScrollView::setInnerContainerSize(const Size &size) @@ -193,7 +193,7 @@ void ScrollView::setInnerContainerSize(const Size &size) { pos.y = _contentSize.height - (1.0f - _innerContainer->getAnchorPoint().y) * _innerContainer->getContentSize().height; } - _innerContainer->setPosition(pos); + setInnerContainerPosition(pos); } const Size& ScrollView::getInnerContainerSize() const @@ -201,6 +201,27 @@ const Size& ScrollView::getInnerContainerSize() const return _innerContainer->getContentSize(); } +void ScrollView::setInnerContainerPosition(const Vec2 &position) +{ + _innerContainer->setPosition(position); + + this->retain(); + if (_eventCallback) + { + _eventCallback(this, EventType::CONTAINER_MOVED); + } + if (_ccEventCallback) + { + _ccEventCallback(this, static_cast(EventType::CONTAINER_MOVED)); + } + this->release(); +} + +const Vec2 ScrollView::getInnerContainerPosition() const +{ + return _innerContainer->getPosition(); +} + void ScrollView::addChild(Node* child) { ScrollView::addChild(child, child->getLocalZOrder(), child->getTag()); @@ -269,7 +290,7 @@ void ScrollView::moveChildren(float offsetX, float offsetY) void ScrollView::moveChildrenToPosition(const Vec2& position) { - _innerContainer->setPosition(position); + setInnerContainerPosition(position); Vec2 outOfBoundary = getHowMuchOutOfBoundary(Vec2::ZERO); updateScrollBar(outOfBoundary); @@ -345,6 +366,7 @@ void ScrollView::processAutoScrolling(float deltaTime) percentage = tweenfunc::quintEaseOut(percentage); } Vec2 moveDelta = _autoScrollTargetDelta * percentage; + moveChildrenToPosition(_autoScrollStartPosition + moveDelta); // Dispatch related events if bouncing if(_bouncingBack) @@ -366,7 +388,6 @@ void ScrollView::processAutoScrolling(float deltaTime) processScrollEvent(MoveDirection::BOTTOM, true); } } - moveChildrenToPosition(_autoScrollStartPosition + moveDelta); } } @@ -494,8 +515,6 @@ void ScrollView::processInertiaScrolling(float dt) bool ScrollView::scrollChildren(float touchOffsetX, float touchOffsetY) { - processScrollingEvent(); - touchOffsetX = (_direction == Direction::VERTICAL ? 0 : touchOffsetX); touchOffsetY = (_direction == Direction::HORIZONTAL ? 0 : touchOffsetY); if(_bounceEnabled) @@ -508,7 +527,10 @@ bool ScrollView::scrollChildren(float touchOffsetX, float touchOffsetY) float realOffsetX = touchOffsetX; float realOffsetY = touchOffsetY; - bool scrollEnabledUpDown = true; + bool scrolledToLeft = false; + bool scrolledToRight = false; + bool scrolledToTop = false; + bool scrolledToBottom = false; if (touchOffsetY > 0.0f) // up { float icBottomPos = _innerContainer->getBottomBoundary(); @@ -518,8 +540,7 @@ bool ScrollView::scrollChildren(float touchOffsetX, float touchOffsetY) { realOffsetY = _bottomBoundary - icBottomPos; } - processScrollEvent(MoveDirection::BOTTOM, false); - scrollEnabledUpDown = false; + scrolledToBottom = true; } } else if (touchOffsetY < 0.0f) // down @@ -531,12 +552,10 @@ bool ScrollView::scrollChildren(float touchOffsetX, float touchOffsetY) { realOffsetY = _topBoundary - icTopPos; } - processScrollEvent(MoveDirection::TOP, false); - scrollEnabledUpDown = false; + scrolledToTop = true; } } - bool scrollEnabledLeftRight = true; if (touchOffsetX < 0.0f) // left { float icRightPos = _innerContainer->getRightBoundary(); @@ -546,8 +565,7 @@ bool ScrollView::scrollChildren(float touchOffsetX, float touchOffsetY) { realOffsetX = _rightBoundary - icRightPos; } - processScrollEvent(MoveDirection::RIGHT, false); - scrollEnabledLeftRight = false; + scrolledToRight = true; } } else if (touchOffsetX > 0.0f) // right @@ -559,11 +577,34 @@ bool ScrollView::scrollChildren(float touchOffsetX, float touchOffsetY) { realOffsetX = _leftBoundary - icLeftPos; } - processScrollEvent(MoveDirection::LEFT, false); - scrollEnabledLeftRight = false; + scrolledToLeft = true; } } moveChildren(realOffsetX, realOffsetY); + + if(realOffsetX != 0 || realOffsetY != 0) + { + processScrollingEvent(); + } + if(scrolledToBottom) + { + processScrollEvent(MoveDirection::BOTTOM, false); + } + if(scrolledToTop) + { + processScrollEvent(MoveDirection::TOP, false); + } + if(scrolledToLeft) + { + processScrollEvent(MoveDirection::LEFT, false); + } + if(scrolledToRight) + { + processScrollEvent(MoveDirection::RIGHT, false); + } + + bool scrollEnabledUpDown = (!scrolledToBottom && !scrolledToTop); + bool scrollEnabledLeftRight = (!scrolledToLeft && !scrolledToRight); return scrollEnabledUpDown || scrollEnabledLeftRight; } @@ -1149,6 +1190,33 @@ const Color3B& ScrollView::getScrollBarColor() const return Color3B::WHITE; } +void ScrollView::setScrollBarOpacity(GLubyte opacity) +{ + CCASSERT(_scrollBarEnabled, "Scroll bar should be enabled!"); + if(_verticalScrollBar != nullptr) + { + _verticalScrollBar->setOpacity(opacity); + } + if(_horizontalScrollBar != nullptr) + { + _horizontalScrollBar->setOpacity(opacity); + } +} + +GLubyte ScrollView::getScrollBarOpacity() const +{ + CCASSERT(_scrollBarEnabled, "Scroll bar should be enabled!"); + if(_verticalScrollBar != nullptr) + { + return _verticalScrollBar->getOpacity(); + } + else if(_horizontalScrollBar != nullptr) + { + return _horizontalScrollBar->getOpacity(); + } + return -1; +} + void ScrollView::setScrollBarAutoHideEnabled(bool autoHideEnabled) { CCASSERT(_scrollBarEnabled, "Scroll bar should be enabled!"); diff --git a/cocos/ui/UIScrollView.h b/cocos/ui/UIScrollView.h index 18f318e3a941..8f311ee458e7 100644 --- a/cocos/ui/UIScrollView.h +++ b/cocos/ui/UIScrollView.h @@ -99,7 +99,8 @@ class CC_GUI_DLL ScrollView : public Layout BOUNCE_TOP, BOUNCE_BOTTOM, BOUNCE_LEFT, - BOUNCE_RIGHT + BOUNCE_RIGHT, + CONTAINER_MOVED }; /** @@ -308,6 +309,20 @@ class CC_GUI_DLL ScrollView : public Layout * @return The inner container size. */ const Size& getInnerContainerSize() const; + + /** + * Set inner container position + * + * @param pos Inner container position. + */ + void setInnerContainerPosition(const Vec2 &pos); + + /** + * Get inner container position + * + * @return The inner container position. + */ + const Vec2 getInnerContainerPosition() const; /** * Add callback function which will be called when scrollview event triggered. @@ -449,6 +464,20 @@ class CC_GUI_DLL ScrollView : public Layout */ const Color3B& getScrollBarColor() const; + /** + * @brief Set the scroll bar's opacity + * + * @param the scroll bar's opacity + */ + void setScrollBarOpacity(GLubyte opacity); + + /** + * @brief Get the scroll bar's opacity + * + * @return the scroll bar's opacity + */ + GLubyte getScrollBarOpacity() const; + /** * @brief Set scroll bar auto hide state * diff --git a/cocos/ui/UIScrollViewBar.cpp b/cocos/ui/UIScrollViewBar.cpp index e005d93d6aa4..21413d3574c6 100644 --- a/cocos/ui/UIScrollViewBar.cpp +++ b/cocos/ui/UIScrollViewBar.cpp @@ -31,8 +31,8 @@ NS_CC_BEGIN namespace ui { -static const char* HALF_CIRCLE_IMAGE = "iVBORw0KGgoAAAANSUhEUgAAAAwAAAAGCAMAAADAMI+zAAAAIVBMVEX///////////////////////////////////////////9/gMdvAAAAC3RSTlMAAgMLLFBTYWNkZuZhN4QAAAAvSURBVAjXRchBDgAgCAPBIi0q/3+wxBiZU7cAjJpTNBSPvMLrf7tqgPkR6hB2xzpFkgIfM9q/8QAAAABJRU5ErkJggg=="; -static const char* BODY_IMAGE_1_PIXEL_HEIGHT = "iVBORw0KGgoAAAANSUhEUgAAAAwAAAABCAMAAADdNb8LAAAAA1BMVEX///+nxBvIAAAAAXRSTlNm5DccCwAAAApJREFUeAFjQAYAAA0AAWHNnKQAAAAASUVORK5CYII="; +static const char* HALF_CIRCLE_IMAGE = "iVBORw0KGgoAAAANSUhEUgAAAAwAAAAGCAMAAADAMI+zAAAAJ1BMVEX///////////////////////////////////////////////////9Ruv0SAAAADHRSTlMABgcbbW7Hz9Dz+PmlcJP5AAAAMElEQVR4AUXHwQ2AQAhFwYcLH1H6r1djzDK3ASxUpTBeK/uTCyz7dx54b44m4p5cD1MwAooEJyk3AAAAAElFTkSuQmCC"; +static const char* BODY_IMAGE_1_PIXEL_HEIGHT = "iVBORw0KGgoAAAANSUhEUgAAAAwAAAABCAMAAADdNb8LAAAAA1BMVEX///+nxBvIAAAACklEQVR4AWNABgAADQABYc2cpAAAAABJRU5ErkJggg=="; static const Color3B DEFAULT_COLOR(52, 65, 87); static const float DEFAULT_MARGIN = 20; @@ -65,6 +65,7 @@ _direction(direction), _upperHalfCircle(nullptr), _lowerHalfCircle(nullptr), _body(nullptr), +_opacity(100), _marginFromBoundary(DEFAULT_MARGIN), _marginForLength(DEFAULT_MARGIN), _touching(false), @@ -103,16 +104,16 @@ bool ScrollViewBar::init() _upperHalfCircle = createSpriteFromBase64(HALF_CIRCLE_IMAGE); _upperHalfCircle->setAnchorPoint(Vec2::ANCHOR_MIDDLE_BOTTOM); - addChild(_upperHalfCircle); + addProtectedChild(_upperHalfCircle); _lowerHalfCircle = Sprite::createWithTexture(_upperHalfCircle->getTexture(), _upperHalfCircle->getTextureRect(), _upperHalfCircle->isTextureRectRotated()); _lowerHalfCircle->setScaleY(-1); _lowerHalfCircle->setAnchorPoint(Vec2::ANCHOR_MIDDLE_BOTTOM); - addChild(_lowerHalfCircle); + addProtectedChild(_lowerHalfCircle); _body = createSpriteFromBase64(BODY_IMAGE_1_PIXEL_HEIGHT); _body->setAnchorPoint(Vec2::ANCHOR_MIDDLE_BOTTOM); - addChild(_body); + addProtectedChild(_body); setColor(DEFAULT_COLOR); @@ -123,7 +124,7 @@ bool ScrollViewBar::init() if(_autoHideEnabled) { - setOpacity(0); + ProtectedNode::setOpacity(0); } return true; } @@ -165,7 +166,7 @@ void ScrollViewBar::setWidth(float width) void ScrollViewBar::setAutoHideEnabled(bool autoHideEnabled) { _autoHideEnabled = autoHideEnabled; - setOpacity(255); + ProtectedNode::setOpacity(_opacity); } float ScrollViewBar::getWidth() const @@ -202,7 +203,7 @@ void ScrollViewBar::update(float deltaTime) if(_autoHideRemainingTime <= _autoHideTime) { _autoHideRemainingTime = MAX(0, _autoHideRemainingTime); - this->setOpacity(255 * (_autoHideRemainingTime / _autoHideTime)); + ProtectedNode::setOpacity(_opacity * (_autoHideRemainingTime / _autoHideTime)); } } @@ -236,7 +237,7 @@ void ScrollViewBar::onScrolled(const Vec2& outOfBoundary) if(_autoHideEnabled) { _autoHideRemainingTime = _autoHideTime; - setOpacity(255); + ProtectedNode::setOpacity(_opacity); } Layout* innerContainer = _parent->getInnerContainer(); diff --git a/cocos/ui/UIScrollViewBar.h b/cocos/ui/UIScrollViewBar.h index 8503c6344d6a..2331720c8b1c 100644 --- a/cocos/ui/UIScrollViewBar.h +++ b/cocos/ui/UIScrollViewBar.h @@ -130,6 +130,8 @@ class CC_GUI_DLL ScrollViewBar : public ProtectedNode /** * @lua NA */ + virtual void setOpacity(GLubyte opacity) override { _opacity = opacity; } + virtual GLubyte getOpacity() const override { return _opacity; } virtual void onEnter() override; virtual void update(float deltaTime) override; @@ -158,6 +160,8 @@ class CC_GUI_DLL ScrollViewBar : public ProtectedNode Sprite* _upperHalfCircle; Sprite* _lowerHalfCircle; Sprite* _body; + + GLubyte _opacity; float _marginFromBoundary; float _marginForLength; diff --git a/cocos/ui/UISlider.cpp b/cocos/ui/UISlider.cpp index 900a58be6b9e..a827b6e87a6e 100644 --- a/cocos/ui/UISlider.cpp +++ b/cocos/ui/UISlider.cpp @@ -563,12 +563,14 @@ void Slider::barRendererScaleChangedWithSize() if (btextureSize.width <= 0.0f || btextureSize.height <= 0.0f) { _barRenderer->setScale(1.0f); - return; } - float bscaleX = _contentSize.width / btextureSize.width; - float bscaleY = _contentSize.height / btextureSize.height; - _barRenderer->setScaleX(bscaleX); - _barRenderer->setScaleY(bscaleY); + else + { + float bscaleX = _contentSize.width / btextureSize.width; + float bscaleY = _contentSize.height / btextureSize.height; + _barRenderer->setScaleX(bscaleX); + _barRenderer->setScaleY(bscaleY); + } } } _barRenderer->setPosition(_contentSize.width / 2.0f, _contentSize.height / 2.0f); diff --git a/cocos/ui/UIVideoPlayer.h b/cocos/ui/UIVideoPlayer.h index 81b688a22ae5..45950edb985f 100644 --- a/cocos/ui/UIVideoPlayer.h +++ b/cocos/ui/UIVideoPlayer.h @@ -103,12 +103,12 @@ namespace experimental{ /** * Pauses playback. */ - virtual void pause(); + virtual void pause()override; /** * Resumes playback. */ - virtual void resume(); + virtual void resume()override; /** * Stops playback. diff --git a/cocos/ui/UIWidget.cpp b/cocos/ui/UIWidget.cpp index 54c16e0f167d..86bd7c53877b 100644 --- a/cocos/ui/UIWidget.cpp +++ b/cocos/ui/UIWidget.cpp @@ -1296,7 +1296,7 @@ void Widget::copyProperties(Widget *widget) float Widget::getScale()const { - CCASSERT(this->getScaleX() == this->getScaleY(), ""); + CCASSERT(this->getScaleX() == this->getScaleY(), "scaleX should be equal to scaleY."); return this->getScaleX(); } diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md index 15ee6023a742..796ab78e829f 100644 --- a/docs/RELEASE_NOTES.md +++ b/docs/RELEASE_NOTES.md @@ -27,6 +27,7 @@ - [Nine Patch format support](#nine-patch-format-support) - [Android Studio support](#android-studio-support) - [Samsung Enhanced API support](#samsung-enhanced-api-support) + - [SDKBOX](#sdkbox) - [The Next Step](#the-next-step) @@ -65,9 +66,9 @@ You can use [Cocos Console](www.cocos2d-x.org/wiki/Cocos2d-console) command line In console application: ``` // Enter cpp test folder -cd tests/cpp-tests +cd tests/cpp-tests // Or enter js test folder -cd tests/js-tests +cd tests/js-tests // Or enter lua test folder cd tests/lua-tests @@ -168,6 +169,7 @@ cocos new -l cpp|js|lua MyGame * JS: Merged JSB and web engine into Cocos2d-x for a All-in-one engine * JS: Added `ccui.VideoPlayer` and `ccui.WebView` for iOS/Android/Web * console: Supported build & run Android Studio project with cocos console +* sdkbox: super EASY way to integrate 3rd party SDKs into cocos2d-x ## Download @@ -234,10 +236,30 @@ Samsung have provided a series of Enhanced API to optimize Cocos2d-x games for S In the previous versions, the resources file name's case is ignored on win32 platform, but not ignored in other platforms. This will lead to some unexpected issues, especially when user develop with win32 platform and pulish to other platforms like Android. In win32, the file name may be found without matching the case, but on other platforms it won't be found. So we decided to make win32 platform's resources case sensitive. Please make sure you are using the correct file name for your resources. +### SDKBOX +SDKBOX is a project that's built by part of the cocos2d-x team, in order to makes integrating 3rd party SDKs super EASY. +With SDKBOX you can integrate services like In App Purchase with one command +``` +sdkbox import -b iap +``` +Currently supported service including + +* [Tune](http://cocos2d-x.org/sdkbox/tune) +* [In App Purchase](http://cocos2d-x.org/sdkbox/iap) +* [AdColony](http://cocos2d-x.org/sdkbox/adcolony) +* [Vungle](http://cocos2d-x.org/sdkbox/vungle) +* [Chartboost](http://cocos2d-x.org/sdkbox/chartboost) +* [Kochava](http://cocos2d-x.org/sdkbox/kochava) +* [Google Analytics](http://cocos2d-x.org/sdkbox/googleanalytics) +* [Flurry Analytics](http://cocos2d-x.org/sdkbox/flurryanalytics) + + + + ## The Next Step As you can see, in v3.7, we have enhanced our 2d rendering with material system and integrated polygon sprite. More importantly, our 3d features become more and more complete, 3d Physics and Navigation Mesh with the previous Camera, 3d Sprite, 3d Particle System, 3d Light, 3d Terrain, Skybox, now you can really start to use Cocos to make a 3d game. In v3.8, we won't do much more features, but we'd like to slow down and refine our current 3D and 2D modules. -[The v3.8 milestone tasks](https://github.com/cocos2d/cocos2d-x/milestones/v3.8) \ No newline at end of file +[The v3.8 milestone tasks](https://github.com/cocos2d/cocos2d-x/milestones/v3.8) diff --git a/extensions/GUI/CCScrollView/CCScrollView.cpp b/extensions/GUI/CCScrollView/CCScrollView.cpp index 74683aa522b3..7cf34a2502b8 100644 --- a/extensions/GUI/CCScrollView/CCScrollView.cpp +++ b/extensions/GUI/CCScrollView/CCScrollView.cpp @@ -436,8 +436,8 @@ void ScrollView::deaccelerateScrolling(float dt) if ((fabsf(_scrollDistance.x) <= SCROLL_DEACCEL_DIST && fabsf(_scrollDistance.y) <= SCROLL_DEACCEL_DIST) || - newY >= maxInset.y || newY <= minInset.y || - newX >= maxInset.x || newX <= minInset.x) + ((_direction == Direction::BOTH || _direction == Direction::VERTICAL) && (newY >= maxInset.y || newY <= minInset.y)) || + ((_direction == Direction::BOTH || _direction == Direction::HORIZONTAL) && (newX >= maxInset.x || newX <= minInset.x))) { this->unschedule(CC_SCHEDULE_SELECTOR(ScrollView::deaccelerateScrolling)); this->relocateContainer(true); diff --git a/templates/js-template-default/CMakeLists.txt b/templates/js-template-default/CMakeLists.txt index fd463d9e7eb9..aa19beb0197e 100644 --- a/templates/js-template-default/CMakeLists.txt +++ b/templates/js-template-default/CMakeLists.txt @@ -257,6 +257,9 @@ message(STATUS "Flatbuffers include dirs: ${FLATBUFFERS_INCLUDE_DIRS}") add_subdirectory(frameworks/cocos2d-x/external/xxhash) include_directories(frameworks/cocos2d-x/external/xxhash) +#buid recast +add_subdirectory(frameworks/cocos2d-x/external/recast) + set(GAME_SRC frameworks/runtime-src/proj.linux/main.cpp frameworks/runtime-src/Classes/AppDelegate.cpp @@ -277,6 +280,7 @@ add_executable(${APP_NAME} target_link_libraries(${APP_NAME} jscocos2d cocos2d + recast ) set(APP_BIN_DIR "${CMAKE_BINARY_DIR}/bin") diff --git a/tests/cpp-tests/CMakeLists.txt b/tests/cpp-tests/CMakeLists.txt index 532be1fb286a..19d0e6824e40 100644 --- a/tests/cpp-tests/CMakeLists.txt +++ b/tests/cpp-tests/CMakeLists.txt @@ -29,6 +29,8 @@ set(TESTS_SRC Classes/AppDelegate.cpp Classes/BaseTest.cpp Classes/BillBoardTest/BillBoardTest.cpp + Classes/BugsTest/Bug-CCDrawNode.cpp + Classes/BugsTest/Bug-PageViewLayout.cpp Classes/BugsTest/Bug-1159.cpp Classes/BugsTest/Bug-1174.cpp Classes/BugsTest/Bug-350.cpp diff --git a/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.cpp b/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.cpp index c0bb7b5582f1..d8f0b9f4aa6f 100644 --- a/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.cpp +++ b/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.cpp @@ -18,6 +18,7 @@ ActionManagerTests::ActionManagerTests() ADD_TEST_CASE(PauseTest); ADD_TEST_CASE(StopActionTest); ADD_TEST_CASE(StopAllActionsTest); + ADD_TEST_CASE(StopActionsByFlagsTest); ADD_TEST_CASE(ResumeTest); } @@ -291,3 +292,53 @@ void ResumeTest::resumeGrossini(float time) auto director = Director::getInstance(); director->getActionManager()->resumeTarget(pGrossini); } + +//------------------------------------------------------------------ +// +// StopActionsByFlagsTest +// +//------------------------------------------------------------------ +void StopActionsByFlagsTest::onEnter() +{ + ActionManagerTest::onEnter(); + + auto l = Label::createWithTTF("Should stop scale & move after 4 seconds but keep rotate", "fonts/Thonburi.ttf", 16.0f); + addChild(l); + l->setPosition( Vec2(VisibleRect::center().x, VisibleRect::top().y - 75) ); + + auto pMove1 = MoveBy::create(2, Vec2(200, 0)); + auto pMove2 = MoveBy::create(2, Vec2(-200, 0)); + auto pSequenceMove = Sequence::createWithTwoActions(pMove1, pMove2); + auto pRepeatMove = RepeatForever::create(pSequenceMove); + pRepeatMove->setFlags(kMoveFlag | kRepeatForeverFlag); + + auto pScale1 = ScaleBy::create(2, 1.5f); + auto pScale2 = ScaleBy::create(2, 1.0f/1.5f); + auto pSequenceScale = Sequence::createWithTwoActions(pScale1, pScale2); + auto pRepeatScale = RepeatForever::create(pSequenceScale); + pRepeatScale->setFlags(kScaleFlag | kRepeatForeverFlag); + + auto pRotate = RotateBy::create(2, 360); + auto pRepeatRotate = RepeatForever::create(pRotate); + pRepeatRotate->setFlags(kRotateFlag | kRepeatForeverFlag); + + auto pChild = Sprite::create(s_pathGrossini); + pChild->setPosition( VisibleRect::center() ); + + addChild(pChild, 1, kTagGrossini); + pChild->runAction(pRepeatMove); + pChild->runAction(pRepeatScale); + pChild->runAction(pRepeatRotate); + this->scheduleOnce((SEL_SCHEDULE)&StopActionsByFlagsTest::stopAction, 4); +} + +void StopActionsByFlagsTest::stopAction(float time) +{ + auto sprite = getChildByTag(kTagGrossini); + sprite->stopActionsByFlags(kMoveFlag | kScaleFlag); +} + +std::string StopActionsByFlagsTest::subtitle() const +{ + return "Stop All Actions By Flags Test"; +} diff --git a/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.h b/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.h index 0c1183bf329d..a63b0a7e394c 100644 --- a/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.h +++ b/tests/cpp-tests/Classes/ActionManagerTest/ActionManagerTest.h @@ -80,4 +80,19 @@ class ResumeTest : public ActionManagerTest void resumeGrossini(float time); }; +class StopActionsByFlagsTest : public ActionManagerTest +{ +public: + CREATE_FUNC(StopActionsByFlagsTest); + + virtual std::string subtitle() const override; + virtual void onEnter() override; + void stopAction(float time); +protected: + const unsigned int kMoveFlag = 0x01; + const unsigned int kScaleFlag = 0x02; + const unsigned int kRotateFlag = 0x04; + const unsigned int kRepeatForeverFlag = 0x08; // You don't need this for the test, but it's for demonstration how to activate several flags on an action. +}; + #endif diff --git a/tests/cpp-tests/Classes/Box2DTestBed/Box2dView.h b/tests/cpp-tests/Classes/Box2DTestBed/Box2dView.h index 2eae062302b3..a3a3dbf26637 100644 --- a/tests/cpp-tests/Classes/Box2DTestBed/Box2dView.h +++ b/tests/cpp-tests/Classes/Box2DTestBed/Box2dView.h @@ -41,12 +41,12 @@ class Box2DView : public cocos2d::Layer virtual void draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags) override; // virtual void registerWithTouchDispatcher(); - bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event); - void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event); - void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event); + bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event)override; + void onTouchMoved(cocos2d::Touch* touch, cocos2d::Event* event)override; + void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event)override; - void onKeyPressed(cocos2d::EventKeyboard::KeyCode code, cocos2d::Event* event); - void onKeyReleased(cocos2d::EventKeyboard::KeyCode code, cocos2d::Event* event); + void onKeyPressed(cocos2d::EventKeyboard::KeyCode code, cocos2d::Event* event)override; + void onKeyReleased(cocos2d::EventKeyboard::KeyCode code, cocos2d::Event* event)override; //virtual void accelerometer(UIAccelerometer* accelerometer, cocos2d::Acceleration* acceleration); static Box2DView* viewWithEntryID(int entryId); diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.cpp new file mode 100644 index 000000000000..60913d0c14a7 --- /dev/null +++ b/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.cpp @@ -0,0 +1,42 @@ +// +// CCDrawNode::onDrawGLPoint & CCDrawNode::onDrawGLLine miss +// calling GL::blendFunc, so when a sprite set blendFunc, these +// function will get a wrong result. +// In this test, see a red line when bug resolved. +// + +#include "Bug-CCDrawNode.h" + +USING_NS_CC; + +bool BugDrawNodeLayer::init() +{ + if (BugsTestBase::init()) + { + auto size = Director::getInstance()->getWinSize(); + auto testSprite = Sprite::create("cocosui/CloseNormal.png"); + BlendFunc blend; + blend.src = GL_ZERO; + blend.dst = GL_ONE_MINUS_SRC_ALPHA; + testSprite->setBlendFunc(blend); + testSprite->setPosition(Vec2(size.width / 2, size.height / 2)); + testSprite->setScale(10); + addChild(testSprite); + + auto drawNode = DrawNode::create(); + drawNode->drawLine(Vec2(0, 0), Vec2(size.width, size.height), Color4F(1, 0, 0, 0.5f)); + Vec2 point = Vec2(size.width / 2, size.height / 2); + drawNode->drawPoint(point, 8, Color4F(1, 0, 0, 0.5f)); + addChild(drawNode); + + auto label = Label::create(); + label->setString(std::string("If you see a red line with a block at center, the bug is fixed!")); + label->setPosition(size.width / 2, size.height / 4); + label->setTextColor(Color4B::ORANGE); + addChild(label); + + return true; + } + + return false; +} diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.h b/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.h new file mode 100644 index 000000000000..d55729d2a6c9 --- /dev/null +++ b/tests/cpp-tests/Classes/BugsTest/Bug-CCDrawNode.h @@ -0,0 +1,14 @@ +#ifndef __BUG_CCDRAWNODE_H__ +#define __BUG_CCDRAWNODE_H__ + +#include "BugsTest.h" + +class BugDrawNodeLayer : public BugsTestBase +{ +public: + CREATE_FUNC(BugDrawNodeLayer); + + virtual bool init() override; +}; + +#endif \ No newline at end of file diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-PageViewLayout.cpp b/tests/cpp-tests/Classes/BugsTest/Bug-PageViewLayout.cpp new file mode 100644 index 000000000000..3572c5f41b5b --- /dev/null +++ b/tests/cpp-tests/Classes/BugsTest/Bug-PageViewLayout.cpp @@ -0,0 +1,40 @@ +// +// When a pageview set to relative position & size, if it +// has child widget set to relative position & size either, +// when change layer size, relayout won't correctly effect +// to the child. +// In this test, if button at the center of panel, bug is fixed! +// + +#include "Bug-PageViewLayout.h" +#include "cocostudio/CocoStudio.h" +#include "ui/CocosGUI.h" +#include "platform/CCFileUtils.h" + +USING_NS_CC; +using namespace ui; + +bool BugPageViewLayer::init() +{ + if (BugsTestBase::init()) + { + auto size = Director::getInstance()->getWinSize(); + + FileUtils::getInstance()->addSearchPath("ccs-res/cocosui/CustomTest/CustomWidgetCallbackBindTest"); + auto rootNode = CSLoader::createNode("cocosui/CustomTest/CustomWidgetCallbackBindTest/PageViewBugScene.csb"); + auto child = rootNode->getChildByName("ProjectNode_1"); + child->setContentSize(Size(480, 320)); + Helper::doLayout(child); + addChild(rootNode); + + auto label = Label::create(); + label->setString(std::string("If button is at the center of panel, the bug is fixed!")); + label->setPosition(size.width / 2, size.height / 4); + label->setTextColor(Color4B::ORANGE); + this->addChild(label); + + return true; + } + + return false; +} diff --git a/tests/cpp-tests/Classes/BugsTest/Bug-PageViewLayout.h b/tests/cpp-tests/Classes/BugsTest/Bug-PageViewLayout.h new file mode 100644 index 000000000000..a8218d7a2888 --- /dev/null +++ b/tests/cpp-tests/Classes/BugsTest/Bug-PageViewLayout.h @@ -0,0 +1,14 @@ +#ifndef __BUG_PAGEVIEWLAYOUT_H__ +#define __BUG_PAGEVIEWLAYOUT_H__ + +#include "BugsTest.h" + +class BugPageViewLayer : public BugsTestBase +{ +public: + CREATE_FUNC(BugPageViewLayer); + + virtual bool init() override; +}; + +#endif // !__BUG_PAGEVIEWLAYOUT_H__ diff --git a/tests/cpp-tests/Classes/BugsTest/BugsTest.cpp b/tests/cpp-tests/Classes/BugsTest/BugsTest.cpp index f2bfecc07a5c..c2323763a3b2 100644 --- a/tests/cpp-tests/Classes/BugsTest/BugsTest.cpp +++ b/tests/cpp-tests/Classes/BugsTest/BugsTest.cpp @@ -9,6 +9,8 @@ #include "Bug-1159.h" #include "Bug-1174.h" #include "Bug-Child.h" +#include "Bug-CCDrawNode.h" +#include "Bug-PageViewLayout.h" BugsTests::BugsTests() { @@ -23,4 +25,6 @@ BugsTests::BugsTests() ADD_TEST_CASE(Bug1174Layer); ADD_TEST_CASE(BugChild); ADD_TEST_CASE(BugCameraMask); + ADD_TEST_CASE(BugDrawNodeLayer); + ADD_TEST_CASE(BugPageViewLayer); } diff --git a/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.cpp b/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.cpp index c9115dcf4393..05c4476313ef 100644 --- a/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.cpp +++ b/tests/cpp-tests/Classes/Camera3DTest/Camera3DTest.cpp @@ -87,7 +87,7 @@ CameraRotationTest::CameraRotationTest() l1->setScale(3); bill1->addChild(l1); - auto p1 = CCParticleSystemQuad::create("Particles/SmallSun.plist"); + auto p1 = ParticleSystemQuad::create("Particles/SmallSun.plist"); p1->setPosition(30,80); bill1->addChild(p1); @@ -103,7 +103,7 @@ CameraRotationTest::CameraRotationTest() l2->setScale(3); bill2->addChild(l2); - auto p2 = CCParticleSystemQuad::create("Particles/SmallSun.plist"); + auto p2 = ParticleSystemQuad::create("Particles/SmallSun.plist"); p2->setPosition(30,80); bill2->addChild(p2); diff --git a/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.cpp b/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.cpp index 8bdee03d4403..ee2e636d61ea 100644 --- a/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.cpp +++ b/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.cpp @@ -61,14 +61,14 @@ void PrettyPrinterDemo::onEnter() PrettyPrinter vistor; // print dictionary - auto dict = Dictionary::createWithContentsOfFile("animations/animations.plist"); + auto dict = __Dictionary::createWithContentsOfFile("animations/animations.plist"); dict->acceptVisitor(vistor); log("%s", vistor.getResult().c_str()); log("-------------------------------"); __Set myset; for (int i = 0; i < 30; ++i) { - myset.addObject(String::createWithFormat("str: %d", i)); + myset.addObject(__String::createWithFormat("str: %d", i)); } vistor.clear(); myset.acceptVisitor(vistor); diff --git a/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.h b/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.h index a1ed575cd27e..be384034866b 100644 --- a/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.h +++ b/tests/cpp-tests/Classes/DataVisitorTest/DataVisitorTest.h @@ -11,8 +11,8 @@ class PrettyPrinterDemo : public TestCase { public: CREATE_FUNC(PrettyPrinterDemo); - virtual std::string title() const; - virtual std::string subtitle() const; + virtual std::string title() const override; + virtual std::string subtitle() const override; virtual void onEnter() override; void addSprite(); protected: diff --git a/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.h b/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.h index f9d8bffbd58a..72aad734dc55 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/AssetsManagerExTest/AssetsManagerExTest.h @@ -15,7 +15,7 @@ class AssetsManagerExLoaderScene : public TestCase void startDownloadCallback(cocos2d::Ref* sender); - virtual std::string title() const; + virtual std::string title() const override; virtual bool init() override; virtual void onExit() override; diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioActionTimelineTest/ActionTimelineTestScene.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioActionTimelineTest/ActionTimelineTestScene.cpp index 5810de2f67b8..592387ccc5c9 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioActionTimelineTest/ActionTimelineTestScene.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioActionTimelineTest/ActionTimelineTestScene.cpp @@ -42,7 +42,7 @@ bool ActionTimelineBaseTest::init() addChild(bg); - setGLProgram(ShaderCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); + setGLProgram(GLProgramCache::getInstance()->getGLProgram(GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR)); return true; } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioActionTimelineTest/ActionTimelineTestScene.h b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioActionTimelineTest/ActionTimelineTestScene.h index 38a23ceb01ef..270409db0d04 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioActionTimelineTest/ActionTimelineTestScene.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioActionTimelineTest/ActionTimelineTestScene.h @@ -15,7 +15,7 @@ class CocoStudioActionTimelineTests : public TestSuite class ActionTimelineBaseTest : public TestCase { public: - virtual std::string title() const; + virtual std::string title() const override; virtual bool init() override; diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp index a7950f977cab..1bd5418de104 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.cpp @@ -446,8 +446,8 @@ void TestParticleDisplay::onEnter() addChild(armature); - ParticleSystem *p1 = CCParticleSystemQuad::create("Particles/SmallSun.plist"); - ParticleSystem *p2 = CCParticleSystemQuad::create("Particles/SmallSun.plist"); + ParticleSystem *p1 = ParticleSystemQuad::create("Particles/SmallSun.plist"); + ParticleSystem *p2 = ParticleSystemQuad::create("Particles/SmallSun.plist"); cocostudio::Bone *bone = cocostudio::Bone::create("p1"); bone->addDisplay(p1, 0); @@ -607,7 +607,7 @@ void TestColliderDetector::onFrameEvent(cocostudio::Bone *bone, const std::strin bullet->setPosition(p.x + 60, p.y); bullet->stopAllActions(); - bullet->runAction(CCMoveBy::create(1.5f, Vec2(350, 0))); + bullet->runAction(MoveBy::create(1.5f, Vec2(350, 0))); } @@ -1102,7 +1102,7 @@ void TestArmatureNesting2::onEnter() touchedMenu = false; auto label = Label::createWithTTF("Change Mount", "fonts/arial.ttf", 20); - MenuItemLabel* pMenuItem = CCMenuItemLabel::create(label, CC_CALLBACK_1(TestArmatureNesting2::changeMountCallback, this)); + MenuItemLabel* pMenuItem = MenuItemLabel::create(label, CC_CALLBACK_1(TestArmatureNesting2::changeMountCallback, this)); Menu* pMenu =Menu::create(pMenuItem, nullptr); @@ -1154,7 +1154,7 @@ void TestArmatureNesting2::onTouchesEnded(const std::vector& touches, Ev armature->setScaleX(1); } - ActionInterval *move = CCMoveTo::create(2, point); + ActionInterval *move = MoveTo::create(2, point); armature->stopAllActions(); armature->runAction(Sequence::create(move, nullptr)); } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h index d5e0a44846e8..c9ed316f1c85 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioArmatureTest/ArmatureScene.h @@ -26,7 +26,7 @@ class CocoStudioArmatureTests : public TestSuite class ArmatureBaseTest : public TestCase { public: - virtual std::string title() const; + virtual std::string title() const override; virtual bool init() override; protected: @@ -105,8 +105,8 @@ class TestPerformanceBatchNode : public TestPerformance virtual void onEnter() override; virtual std::string title() const override; - virtual void addArmatureToParent(cocostudio::Armature *armature); - virtual void removeArmatureFromParent(int tag); + virtual void addArmatureToParent(cocostudio::Armature *armature)override; + virtual void removeArmatureFromParent(int tag)override; cocostudio::BatchNode *batchNode; }; @@ -260,7 +260,7 @@ class TestColliderDetector : public ArmatureBaseTest virtual void onEnter() override; virtual std::string title() const override; - virtual void update(float delta); + virtual void update(float delta)override; virtual void draw(cocos2d::Renderer* renderer, const cocos2d::Mat4& transform, uint32_t flags) override; void onFrameEvent(cocostudio::Bone *bone, const std::string& evt, int originFrameIndex, int currentFrameIndex); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp index 5dfdccba32a3..816eeb4ab0e1 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp @@ -32,8 +32,8 @@ bool SceneEditorTestBase::init() _isCsbLoad = false; _loadtypelb = cocos2d::Label::createWithSystemFont(_loadtypeStr[0], "Arial", 12); // #endif - MenuItemLabel* itemlb = CCMenuItemLabel::create(_loadtypelb, CC_CALLBACK_1(SceneEditorTestBase::changeLoadTypeCallback, this)); - Menu* loadtypemenu = CCMenu::create(itemlb, nullptr); + MenuItemLabel* itemlb = MenuItemLabel::create(_loadtypelb, CC_CALLBACK_1(SceneEditorTestBase::changeLoadTypeCallback, this)); + Menu* loadtypemenu = Menu::create(itemlb, nullptr); loadtypemenu->setPosition(Point(VisibleRect::rightTop().x - 50, VisibleRect::rightTop().y - 20)); addChild(loadtypemenu, 100); @@ -188,8 +188,8 @@ cocos2d::Node* SpriteComponentTest::createGameScene() void SpriteComponentTest::defaultPlay() { - ActionInterval* action1 = CCBlink::create(2, 10); - ActionInterval* action2 = CCBlink::create(2, 5); + ActionInterval* action1 = Blink::create(2, 10); + ActionInterval* action2 = Blink::create(2, 5); ComRender *pSister1 = static_cast(_rootNode->getChildByTag(10003)->getComponent("CCSprite")); pSister1->getNode()->runAction(action1); @@ -309,10 +309,10 @@ void UIComponentTest::touchEvent(Ref *pSender, ui::Widget::TouchEventType type) case ui::Widget::TouchEventType::BEGAN: { ComRender *pBlowFish = static_cast(_rootNode->getChildByTag(10010)->getComponent("CCArmature")); - pBlowFish->getNode()->runAction(CCMoveBy::create(10.0f, Vec2(-1000.0f, 0))); + pBlowFish->getNode()->runAction(MoveBy::create(10.0f, Vec2(-1000.0f, 0))); ComRender *pButterflyfish = static_cast(_rootNode->getChildByTag(10011)->getComponent("CCArmature")); - pButterflyfish->getNode()->runAction(CCMoveBy::create(10.0f, Vec2(-1000.0f, 0))); + pButterflyfish->getNode()->runAction(MoveBy::create(10.0f, Vec2(-1000.0f, 0))); } break; default: @@ -379,17 +379,17 @@ cocos2d::Node* TmxMapComponentTest::createGameScene() void TmxMapComponentTest::defaultPlay() { ComRender *tmxMap = static_cast(_rootNode->getChildByTag(10015)->getComponent("CCTMXTiledMap")); - ActionInterval *actionTo = CCSkewTo::create(2, 0.f, 2.f); - ActionInterval *rotateTo = CCRotateTo::create(2, 61.0f); - ActionInterval *actionScaleTo = CCScaleTo::create(2, -0.44f, 0.47f); + ActionInterval *actionTo = SkewTo::create(2, 0.f, 2.f); + ActionInterval *rotateTo = RotateTo::create(2, 61.0f); + ActionInterval *actionScaleTo = ScaleTo::create(2, -0.44f, 0.47f); - ActionInterval *actionScaleToBack = CCScaleTo::create(2, 1.0f, 1.0f); - ActionInterval *rotateToBack = CCRotateTo::create(2, 0); - ActionInterval *actionToBack = CCSkewTo::create(2, 0, 0); + ActionInterval *actionScaleToBack = ScaleTo::create(2, 1.0f, 1.0f); + ActionInterval *rotateToBack = RotateTo::create(2, 0); + ActionInterval *actionToBack = SkewTo::create(2, 0, 0); - tmxMap->getNode()->runAction(CCSequence::create(actionTo, actionToBack, nullptr)); - tmxMap->getNode()->runAction(CCSequence::create(rotateTo, rotateToBack, nullptr)); - tmxMap->getNode()->runAction(CCSequence::create(actionScaleTo, actionScaleToBack, nullptr)); + tmxMap->getNode()->runAction(Sequence::create(actionTo, actionToBack, nullptr)); + tmxMap->getNode()->runAction(Sequence::create(rotateTo, rotateToBack, nullptr)); + tmxMap->getNode()->runAction(Sequence::create(actionScaleTo, actionScaleToBack, nullptr)); } ParticleComponentTest::ParticleComponentTest() @@ -441,8 +441,8 @@ cocos2d::Node* ParticleComponentTest::createGameScene() void ParticleComponentTest::defaultPlay() { ComRender* Particle = static_cast(_rootNode->getChildByTag(10020)->getComponent("CCParticleSystemQuad")); - ActionInterval* jump = CCJumpBy::create(5, Point(-500,0), 50, 4); - FiniteTimeAction* action = CCSequence::create( jump, jump->reverse(), nullptr); + ActionInterval* jump = JumpBy::create(5, Point(-500,0), 50, 4); + FiniteTimeAction* action = Sequence::create( jump, jump->reverse(), nullptr); Particle->getNode()->runAction(action); } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.h b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.h index 9b08e2c83d7d..8fecd7bad66e 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.h @@ -48,7 +48,7 @@ class LoadSceneEdtiorFileTest : public SceneEditorTestBase virtual void onExit() override; cocos2d::Node* createGameScene(); private: - void defaultPlay(); + void defaultPlay()override; }; @@ -66,7 +66,7 @@ class SpriteComponentTest : public SceneEditorTestBase cocos2d::Node* createGameScene(); private: - void defaultPlay(); + void defaultPlay()override; }; class ArmatureComponentTest : public SceneEditorTestBase @@ -83,7 +83,7 @@ class ArmatureComponentTest : public SceneEditorTestBase cocos2d::Node* createGameScene(); private: - void defaultPlay(); + void defaultPlay()override; }; class UIComponentTest : public SceneEditorTestBase @@ -100,7 +100,7 @@ class UIComponentTest : public SceneEditorTestBase cocos2d::Node* createGameScene(); void touchEvent(cocos2d::Ref *pSender, cocos2d::ui::Widget::TouchEventType type); private: - void defaultPlay(); + void defaultPlay()override; }; class TmxMapComponentTest : public SceneEditorTestBase @@ -116,7 +116,7 @@ class TmxMapComponentTest : public SceneEditorTestBase virtual void onExit() override; cocos2d::Node* createGameScene(); private: - void defaultPlay(); + void defaultPlay()override; }; @@ -133,7 +133,7 @@ class ParticleComponentTest : public SceneEditorTestBase virtual void onExit() override; cocos2d::Node* createGameScene(); protected: - void defaultPlay(); + void defaultPlay()override; }; class EffectComponentTest : public SceneEditorTestBase @@ -150,7 +150,7 @@ class EffectComponentTest : public SceneEditorTestBase cocos2d::Node* createGameScene(); void animationEvent(cocostudio::Armature *armature, cocostudio::MovementEventType movementType, const std::string& movementID); private: - void defaultPlay(); + void defaultPlay()override; }; @@ -167,7 +167,7 @@ class BackgroundComponentTest : public SceneEditorTestBase virtual void onExit() override; cocos2d::Node* createGameScene(); private: - void defaultPlay(); + void defaultPlay()override; }; class AttributeComponentTest : public SceneEditorTestBase @@ -185,7 +185,7 @@ class AttributeComponentTest : public SceneEditorTestBase cocos2d::Node* createGameScene(); private: - void defaultPlay(); + void defaultPlay()override; }; class TriggerTest : public SceneEditorTestBase @@ -213,7 +213,7 @@ class TriggerTest : public SceneEditorTestBase cocos2d::Node* createGameScene(); private: - void defaultPlay(); + void defaultPlay()override; cocos2d::EventListener* _touchListener; }; diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp index 28eb7a08a334..8f010bed89ef 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.cpp @@ -243,7 +243,7 @@ void TMoveBy::done() if (_reverse == true) { ActionInterval* actionByBack = actionBy->reverse(); - node->runAction( CCSequence::create(actionBy, actionByBack, nullptr)); + node->runAction( Sequence::create(actionBy, actionByBack, nullptr)); } else { diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.h b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.h index 97b8aaebb43b..124eea3c6dbd 100755 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/acts.h @@ -13,10 +13,10 @@ class PlayMusic: public cocostudio::BaseTriggerAction virtual ~PlayMusic(void); virtual bool init() override; - virtual void done(); - virtual void serialize(const rapidjson::Value &val); - virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode); - virtual void removeAll(); + virtual void done()override; + virtual void serialize(const rapidjson::Value &val)override; + virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)override; + virtual void removeAll()override; private: int _tag; std::string _comName; @@ -31,10 +31,10 @@ class TMoveTo: public cocostudio::BaseTriggerAction virtual ~TMoveTo(void); virtual bool init() override; - virtual void done(); - virtual void serialize(const rapidjson::Value &val); - virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode); - virtual void removeAll(); + virtual void done()override; + virtual void serialize(const rapidjson::Value &val)override; + virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)override; + virtual void removeAll()override; private: int _tag; float _duration; @@ -50,10 +50,10 @@ class TMoveBy : public cocostudio::BaseTriggerAction virtual ~TMoveBy(void); virtual bool init() override; - virtual void done(); - virtual void serialize(const rapidjson::Value &val); - virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode); - virtual void removeAll(); + virtual void done()override; + virtual void serialize(const rapidjson::Value &val)override; + virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)override; + virtual void removeAll()override; private: int _tag; float _duration; @@ -70,10 +70,10 @@ class TRotateTo : public cocostudio::BaseTriggerAction virtual ~TRotateTo(void); virtual bool init() override; - virtual void done(); - virtual void serialize(const rapidjson::Value &val); - virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode); - virtual void removeAll(); + virtual void done()override; + virtual void serialize(const rapidjson::Value &val)override; + virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)override; + virtual void removeAll()override; private: int _tag; float _duration; @@ -89,10 +89,10 @@ class TRotateBy : public cocostudio::BaseTriggerAction virtual ~TRotateBy(void); virtual bool init() override; - virtual void done(); - virtual void serialize(const rapidjson::Value &val); - virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode); - virtual void removeAll(); + virtual void done()override; + virtual void serialize(const rapidjson::Value &val)override; + virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)override; + virtual void removeAll()override; private: int _tag; float _duration; @@ -109,10 +109,10 @@ class TScaleTo : public cocostudio::BaseTriggerAction virtual ~TScaleTo(void); virtual bool init() override; - virtual void done(); - virtual void serialize(const rapidjson::Value &val); - virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode); - virtual void removeAll(); + virtual void done()override; + virtual void serialize(const rapidjson::Value &val)override; + virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)override; + virtual void removeAll()override; private: int _tag; float _duration; @@ -128,10 +128,10 @@ class TScaleBy : public cocostudio::BaseTriggerAction virtual ~TScaleBy(void); virtual bool init() override; - virtual void done(); - virtual void serialize(const rapidjson::Value &val); - virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode); - virtual void removeAll(); + virtual void done()override; + virtual void serialize(const rapidjson::Value &val)override; + virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)override; + virtual void removeAll()override; private: int _tag; float _duration; @@ -149,10 +149,10 @@ class TSkewTo : public cocostudio::BaseTriggerAction virtual ~TSkewTo(void); virtual bool init() override; - virtual void done(); - virtual void serialize(const rapidjson::Value &val); - virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode); - virtual void removeAll(); + virtual void done()override; + virtual void serialize(const rapidjson::Value &val)override; + virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)override; + virtual void removeAll()override; private: int _tag; float _duration; @@ -168,10 +168,10 @@ class TSkewBy : public cocostudio::BaseTriggerAction virtual ~TSkewBy(void); virtual bool init() override; - virtual void done(); - virtual void serialize(const rapidjson::Value &val); - virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode); - virtual void removeAll(); + virtual void done()override; + virtual void serialize(const rapidjson::Value &val)override; + virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)override; + virtual void removeAll()override; private: int _tag; float _duration; @@ -188,10 +188,10 @@ class TriggerState : public cocostudio::BaseTriggerAction virtual ~TriggerState(void); virtual bool init() override; - virtual void done(); - virtual void serialize(const rapidjson::Value &val); - virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode); - virtual void removeAll(); + virtual void done()override; + virtual void serialize(const rapidjson::Value &val)override; + virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)override; + virtual void removeAll()override; private: int _id; int _state; @@ -205,10 +205,10 @@ class ArmaturePlayAction : public cocostudio::BaseTriggerAction virtual ~ArmaturePlayAction(void); virtual bool init() override; - virtual void done(); - virtual void serialize(const rapidjson::Value &val); - virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode); - virtual void removeAll(); + virtual void done()override; + virtual void serialize(const rapidjson::Value &val)override; + virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)override; + virtual void removeAll()override; private: int _tag; std::string _comName; diff --git a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.h b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.h index a8648bd519c1..068f955f87b8 100755 --- a/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.h @@ -13,10 +13,10 @@ class TimeElapsed : public cocostudio::BaseTriggerCondition virtual ~TimeElapsed(void); virtual bool init() override; - virtual bool detect(); - virtual void serialize(const rapidjson::Value &val); - virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode); - virtual void removeAll(); + virtual bool detect()override; + virtual void serialize(const rapidjson::Value &val)override; + virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)override; + virtual void removeAll()override; virtual void update(float dt); private: float _totalTime; @@ -34,10 +34,10 @@ class ArmatureActionState : public cocostudio::BaseTriggerCondition virtual ~ArmatureActionState(void); virtual bool init() override; - virtual bool detect(); - virtual void serialize(const rapidjson::Value &val); - virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode); - virtual void removeAll(); + virtual bool detect()override; + virtual void serialize(const rapidjson::Value &val)override; + virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)override; + virtual void removeAll()override; void animationEvent(cocostudio::Armature *armature, cocostudio::MovementEventType movementType, const std::string& movementID); private: int _tag; @@ -56,10 +56,10 @@ class NodeInRect : public cocostudio::BaseTriggerCondition virtual ~NodeInRect(void); virtual bool init() override; - virtual bool detect(); - virtual void serialize(const rapidjson::Value &val); - virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode); - virtual void removeAll(); + virtual bool detect()override; + virtual void serialize(const rapidjson::Value &val)override; + virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)override; + virtual void removeAll()override; private: int _tag; cocos2d::Vec2 _origin; @@ -74,10 +74,10 @@ class NodeVisible : public cocostudio::BaseTriggerCondition virtual ~NodeVisible(void); virtual bool init() override; - virtual bool detect(); - virtual void serialize(const rapidjson::Value &val); - virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode); - virtual void removeAll(); + virtual bool detect()override; + virtual void serialize(const rapidjson::Value &val)override; + virtual void serialize(cocostudio::CocoLoader *pCocoLoader, cocostudio::stExpCocoNode *pCocoNode)override; + virtual void removeAll()override; private: int _tag; bool _visible; diff --git a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp index 9ecb163a1ec7..9c8ccae21eff 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlButtonTest/CCControlButtonTest.cpp @@ -82,7 +82,7 @@ bool ControlButtonTest_HelloVariableSize::init() layer->setPosition(screenSize.width / 2.0f, screenSize.height / 2.0f); // Add the black background - auto background = Scale9Sprite::create("extensions/buttonBackground.png"); + auto background = ui::Scale9Sprite::create("extensions/buttonBackground.png"); background->setContentSize(Size(total_width + 14, height + 14)); background->setPosition(screenSize.width / 2.0f, screenSize.height / 2.0f); addChild(background); @@ -94,8 +94,8 @@ bool ControlButtonTest_HelloVariableSize::init() ControlButton *ControlButtonTest_HelloVariableSize::standardButtonWithTitle(const char * title) { /** Creates and return a button with a default background and title color. */ - auto backgroundButton = cocos2d::extension::Scale9Sprite::create("extensions/button.png"); - auto backgroundHighlightedButton = cocos2d::extension::Scale9Sprite::create("extensions/buttonHighlighted.png"); + auto backgroundButton = ui::Scale9Sprite::create("extensions/button.png"); + auto backgroundHighlightedButton = ui::Scale9Sprite::create("extensions/buttonHighlighted.png"); auto titleButton = Label::createWithTTF(title, "fonts/Marker Felt.ttf", 30); @@ -140,8 +140,8 @@ bool ControlButtonTest_Event::init() addChild(_displayBitmaskLabel, 1); // Add the button - auto backgroundButton = Scale9Sprite::create("extensions/button.png"); - auto backgroundHighlightedButton = Scale9Sprite::create("extensions/buttonHighlighted.png"); + auto backgroundButton = ui::Scale9Sprite::create("extensions/button.png"); + auto backgroundHighlightedButton = ui::Scale9Sprite::create("extensions/buttonHighlighted.png"); auto titleButton = Label::createWithTTF("Touch Me!", "fonts/Marker Felt.ttf", 30); @@ -156,7 +156,7 @@ bool ControlButtonTest_Event::init() addChild(controlButton, 1); // Add the black background - auto background = Scale9Sprite::create("extensions/buttonBackground.png"); + auto background = ui::Scale9Sprite::create("extensions/buttonBackground.png"); background->setContentSize(Size(300, 170)); background->setPosition(screenSize.width / 2.0f, screenSize.height / 2.0f); addChild(background); @@ -181,47 +181,47 @@ bool ControlButtonTest_Event::init() void ControlButtonTest_Event::touchBitmaskAction(Ref *senderz, Control::EventType controlEvent) { - _displayBitmaskLabel->setString(String::createWithFormat("using bitmask (%d)", controlEvent)->getCString()); + _displayBitmaskLabel->setString(StringUtils::format("using bitmask (%d)", controlEvent)); } void ControlButtonTest_Event::touchDownAction(Ref *senderz, Control::EventType controlEvent) { - _displayValueLabel->setString(String::createWithFormat("Touch Down")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Down")); } void ControlButtonTest_Event::touchDragInsideAction(Ref *sender, Control::EventType controlEvent) { - _displayValueLabel->setString(String::createWithFormat("Drag Inside")->getCString()); + _displayValueLabel->setString(StringUtils::format("Drag Inside")); } void ControlButtonTest_Event::touchDragOutsideAction(Ref *sender, Control::EventType controlEvent) { - _displayValueLabel->setString(String::createWithFormat("Drag Outside")->getCString()); + _displayValueLabel->setString(StringUtils::format("Drag Outside")); } void ControlButtonTest_Event::touchDragEnterAction(Ref *sender, Control::EventType controlEvent) { - _displayValueLabel->setString(String::createWithFormat("Drag Enter")->getCString()); + _displayValueLabel->setString(StringUtils::format("Drag Enter")); } void ControlButtonTest_Event::touchDragExitAction(Ref *sender, Control::EventType controlEvent) { - _displayValueLabel->setString(String::createWithFormat("Drag Exit")->getCString()); + _displayValueLabel->setString(StringUtils::format("Drag Exit")); } void ControlButtonTest_Event::touchUpInsideAction(Ref *sender, Control::EventType controlEvent) { - _displayValueLabel->setString(String::createWithFormat("Touch Up Inside.")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Up Inside.")); } void ControlButtonTest_Event::touchUpOutsideAction(Ref *sender, Control::EventType controlEvent) { - _displayValueLabel->setString(String::createWithFormat("Touch Up Outside.")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Up Outside.")); } void ControlButtonTest_Event::touchCancelAction(Ref *sender, Control::EventType controlEvent) { - _displayValueLabel->setString(String::createWithFormat("Touch Cancel")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Cancel")); } @@ -244,7 +244,7 @@ bool ControlButtonTest_Styling::init() for (int j = 0; j < 3; j++) { // Add the buttons - ControlButton *button = standardButtonWithTitle(String::createWithFormat("%d",rand() % 30)->getCString()); + ControlButton *button = standardButtonWithTitle(StringUtils::format("%d",rand() % 30).c_str()); button->setAdjustBackgroundImage(false); // Tells the button that the background image must not be adjust // It'll use the prefered size of the background image button->setPosition(button->getContentSize().width / 2 + (button->getContentSize().width + space) * i, @@ -261,7 +261,7 @@ bool ControlButtonTest_Styling::init() layer->setPosition(screenSize.width / 2.0f, screenSize.height / 2.0f); // Add the black background - auto backgroundButton = cocos2d::extension::Scale9Sprite::create("extensions/buttonBackground.png"); + auto backgroundButton = ui::Scale9Sprite::create("extensions/buttonBackground.png"); backgroundButton->setContentSize(Size(max_w + 14, max_h + 14)); backgroundButton->setPosition(screenSize.width / 2.0f, screenSize.height / 2.0f); addChild(backgroundButton); @@ -276,9 +276,9 @@ bool ControlButtonTest_Styling::init() ControlButton *ControlButtonTest_Styling::standardButtonWithTitle(const char *title) { /** Creates and return a button with a default background and title color. */ - auto backgroundButton = Scale9Sprite::create("extensions/button.png"); + auto backgroundButton = ui::Scale9Sprite::create("extensions/button.png"); backgroundButton->setPreferredSize(Size(45, 45)); // Set the prefered size - auto backgroundHighlightedButton = Scale9Sprite::create("extensions/buttonHighlighted.png"); + auto backgroundHighlightedButton = ui::Scale9Sprite::create("extensions/buttonHighlighted.png"); backgroundHighlightedButton->setPreferredSize(Size(45, 45)); // Set the prefered size auto titleButton = Label::createWithTTF(title, "fonts/Marker Felt.ttf", 30); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp index 084a4fab865d..ab0de6f4f3e5 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlColourPicker/CCControlColourPickerTest.cpp @@ -35,7 +35,7 @@ bool ControlColourPickerTest::init() layer_width += colourPicker->getContentSize().width; // Add the black background for the text - auto background = Scale9Sprite::create("extensions/buttonBackground.png"); + auto background = ui::Scale9Sprite::create("extensions/buttonBackground.png"); background->setContentSize(Size(150, 50)); background->setPosition(layer_width + background->getContentSize().width / 2.0f, 0); layer->addChild(background); @@ -68,7 +68,7 @@ ControlColourPickerTest::~ControlColourPickerTest() void ControlColourPickerTest::colourValueChanged(Ref *sender, Control::EventType controlEvent) { ControlColourPicker* pPicker = (ControlColourPicker*)sender; - _colorLabel->setString(String::createWithFormat("#%02X%02X%02X",pPicker->getColor().r, pPicker->getColor().g, pPicker->getColor().b)->getCString()); + _colorLabel->setString(StringUtils::format("#%02X%02X%02X",pPicker->getColor().r, pPicker->getColor().g, pPicker->getColor().b)); } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp index 0eae3a82297a..06a714144e15 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlPotentiometerTest/CCControlPotentiometerTest.cpp @@ -51,7 +51,7 @@ bool ControlPotentiometerTest::init() double layer_width = 0; // Add the black background for the text - auto background = Scale9Sprite::create("extensions/buttonBackground.png"); + auto background = ui::Scale9Sprite::create("extensions/buttonBackground.png"); background->setContentSize(Size(80, 50)); background->setPosition(layer_width + background->getContentSize().width / 2.0f, 0); layer->addChild(background); @@ -91,6 +91,6 @@ void ControlPotentiometerTest::valueChanged(Ref *sender, Control::EventType cont { ControlPotentiometer* pControl = (ControlPotentiometer*)sender; // Change value of label. - _displayValueLabel->setString(String::createWithFormat("%.02f", pControl->getValue())->getCString()); + _displayValueLabel->setString(StringUtils::format("%.02f", pControl->getValue())); } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp index 7e4b4daa24c0..ed6049b8f19a 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlScene.cpp @@ -40,7 +40,7 @@ bool ControlScene::init() addChild(background); // Add the ribbon - auto ribbon = Scale9Sprite::create("extensions/ribbon.png", Rect(1, 1, 48, 55)); + auto ribbon = ui::Scale9Sprite::create("extensions/ribbon.png", Rect(1, 1, 48, 55)); ribbon->setContentSize(Size(VisibleRect::getVisibleRect().size.width, 57)); ribbon->setPosition(VisibleRect::center().x, VisibleRect::top().y - ribbon->getContentSize().height / 2.0f); addChild(ribbon); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp index 6d8d46daf67d..2d1d25af595e 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlSliderTest/CCControlSliderTest.cpp @@ -85,8 +85,8 @@ void ControlSliderTest::valueChanged(Ref *sender, Control::EventType controlEven ControlSlider* pSlider = (ControlSlider*)sender; // Change value of label. if(pSlider->getTag() == 1) - _displayValueLabel->setString(String::createWithFormat("Upper slider value = %.02f", pSlider->getValue())->getCString()); + _displayValueLabel->setString(StringUtils::format("Upper slider value = %.02f", pSlider->getValue())); if(pSlider->getTag() == 2) - _displayValueLabel->setString(String::createWithFormat("Lower slider value = %.02f", pSlider->getValue())->getCString()); + _displayValueLabel->setString(StringUtils::format("Lower slider value = %.02f", pSlider->getValue())); } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp index 8f20a9810d32..1d4db3a81490 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlStepperTest/CCControlStepperTest.cpp @@ -52,7 +52,7 @@ bool ControlStepperTest::init() double layer_width = 0; // Add the black background for the text - auto background = Scale9Sprite::create("extensions/buttonBackground.png"); + auto background = ui::Scale9Sprite::create("extensions/buttonBackground.png"); background->setContentSize(Size(100, 50)); background->setPosition(layer_width + background->getContentSize().width / 2.0f, 0); layer->addChild(background); @@ -94,6 +94,6 @@ void ControlStepperTest::valueChanged(Ref *sender, Control::EventType controlEve { ControlStepper* pControl = (ControlStepper*)sender; // Change value of label. - _displayValueLabel->setString(String::createWithFormat("%0.02f", (float)pControl->getValue())->getCString()); + _displayValueLabel->setString(StringUtils::format("%0.02f", (float)pControl->getValue())); } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp index 25b09bb9e596..e922ae0e234e 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.cpp @@ -47,7 +47,7 @@ bool ControlSwitchTest::init() double layer_width = 0; // Add the black background for the text - auto background = Scale9Sprite::create("extensions/buttonBackground.png"); + auto background = ui::Scale9Sprite::create("extensions/buttonBackground.png"); background->setContentSize(Size(80, 50)); background->setPosition(layer_width + background->getContentSize().width / 2.0f, 0); layer->addChild(background); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h b/tests/cpp-tests/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h index 9b0d770199b4..9923e4a69b23 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/NetworkTest/SocketIOTest.h @@ -46,11 +46,11 @@ class SocketIOTest: public TestCase /** * @brief Used for network level socket close (not for disconnect from the socket.io server) */ - virtual void onClose(cocos2d::network::SIOClient* client); + virtual void onClose(cocos2d::network::SIOClient* client)override; /** * @brief Used for network level socket error (not for disconnect from the socket.io server) **/ - virtual void onError(cocos2d::network::SIOClient* client, const std::string& data); + virtual void onError(cocos2d::network::SIOClient* client, const std::string& data)override; /** * @brief Common function to call on both socket.io disconnect and websocket close **/ diff --git a/tests/cpp-tests/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h b/tests/cpp-tests/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h index b5dc73a7233e..5385337cf0e6 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/NetworkTest/WebSocketTest.h @@ -25,10 +25,10 @@ class WebSocketTest : public TestCase WebSocketTest(); virtual ~WebSocketTest(); - virtual void onOpen(cocos2d::network::WebSocket* ws); - virtual void onMessage(cocos2d::network::WebSocket* ws, const cocos2d::network::WebSocket::Data& data); - virtual void onClose(cocos2d::network::WebSocket* ws); - virtual void onError(cocos2d::network::WebSocket* ws, const cocos2d::network::WebSocket::ErrorCode& error); + virtual void onOpen(cocos2d::network::WebSocket* ws)override; + virtual void onMessage(cocos2d::network::WebSocket* ws, const cocos2d::network::WebSocket::Data& data)override; + virtual void onClose(cocos2d::network::WebSocket* ws)override; + virtual void onError(cocos2d::network::WebSocket* ws, const cocos2d::network::WebSocket::ErrorCode& error)override; // Menu Callbacks void onMenuSendTextClicked(cocos2d::Ref *sender); diff --git a/tests/cpp-tests/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp b/tests/cpp-tests/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp index 22e9ab4bc5b9..6765d6dd0bdb 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.cpp @@ -38,7 +38,7 @@ Light::Light() Light::~Light() { - NotificationCenter::getInstance()->removeObserver(this, MSG_SWITCH_STATE); + __NotificationCenter::getInstance()->removeObserver(this, MSG_SWITCH_STATE); } Light* Light::lightWithFile(const char* name) @@ -54,11 +54,11 @@ void Light::setIsConnectToSwitch(bool bConnectToSwitch) _connected = bConnectToSwitch; if (_connected) { - NotificationCenter::getInstance()->addObserver(this, CC_CALLFUNCO_SELECTOR(Light::switchStateChanged), MSG_SWITCH_STATE, nullptr); + __NotificationCenter::getInstance()->addObserver(this, CC_CALLFUNCO_SELECTOR(Light::switchStateChanged), MSG_SWITCH_STATE, nullptr); } else { - NotificationCenter::getInstance()->removeObserver(this, MSG_SWITCH_STATE); + __NotificationCenter::getInstance()->removeObserver(this, MSG_SWITCH_STATE); } updateLightState(); } @@ -123,18 +123,18 @@ NotificationCenterTest::NotificationCenterTest() light->setIsConnectToSwitch(bConnected); } - NotificationCenter::getInstance()->postNotification(MSG_SWITCH_STATE, (Ref*)(intptr_t)item->getSelectedIndex()); + __NotificationCenter::getInstance()->postNotification(MSG_SWITCH_STATE, (Ref*)(intptr_t)item->getSelectedIndex()); /* for testing removeAllObservers */ - NotificationCenter::getInstance()->addObserver(this, CC_CALLFUNCO_SELECTOR(NotificationCenterTest::doNothing), "random-observer1", nullptr); - NotificationCenter::getInstance()->addObserver(this, CC_CALLFUNCO_SELECTOR(NotificationCenterTest::doNothing), "random-observer2", nullptr); - NotificationCenter::getInstance()->addObserver(this, CC_CALLFUNCO_SELECTOR(NotificationCenterTest::doNothing), "random-observer3", nullptr); + __NotificationCenter::getInstance()->addObserver(this, CC_CALLFUNCO_SELECTOR(NotificationCenterTest::doNothing), "random-observer1", nullptr); + __NotificationCenter::getInstance()->addObserver(this, CC_CALLFUNCO_SELECTOR(NotificationCenterTest::doNothing), "random-observer2", nullptr); + __NotificationCenter::getInstance()->addObserver(this, CC_CALLFUNCO_SELECTOR(NotificationCenterTest::doNothing), "random-observer3", nullptr); } NotificationCenterTest::~NotificationCenterTest() { /* for testing removeAllObservers */ - int CC_UNUSED numObserversRemoved = NotificationCenter::getInstance()->removeAllObservers(this); + int CC_UNUSED numObserversRemoved = __NotificationCenter::getInstance()->removeAllObservers(this); CCASSERT(numObserversRemoved >= 3, "All observers were not removed!"); } @@ -142,7 +142,7 @@ void NotificationCenterTest::toggleSwitch(Ref *sender) { auto item = (MenuItemToggle*)sender; int index = item->getSelectedIndex(); - NotificationCenter::getInstance()->postNotification(MSG_SWITCH_STATE, (Ref*)(intptr_t)index); + __NotificationCenter::getInstance()->postNotification(MSG_SWITCH_STATE, (Ref*)(intptr_t)index); } void NotificationCenterTest::connectToSwitch(Ref *sender) diff --git a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp index 77c1d6e34e43..2d74de23f563 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp +++ b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.cpp @@ -53,7 +53,7 @@ Size TableViewTest::tableCellSizeForIndex(TableView *table, ssize_t idx) TableViewCell* TableViewTest::tableCellAtIndex(TableView *table, ssize_t idx) { - auto string = String::createWithFormat("%ld", idx); + auto string = StringUtils::format("%ld", idx); TableViewCell *cell = table->dequeueCell(); if (!cell) { cell = new (std::nothrow) CustomTableViewCell(); @@ -63,7 +63,7 @@ TableViewCell* TableViewTest::tableCellAtIndex(TableView *table, ssize_t idx) sprite->setPosition(Vec2(0, 0)); cell->addChild(sprite); - auto label = Label::createWithSystemFont(string->getCString(), "Helvetica", 20.0); + auto label = Label::createWithSystemFont(string, "Helvetica", 20.0); label->setPosition(Vec2::ZERO); label->setAnchorPoint(Vec2::ZERO); label->setTag(123); @@ -72,7 +72,7 @@ TableViewCell* TableViewTest::tableCellAtIndex(TableView *table, ssize_t idx) else { auto label = (Label*)cell->getChildByTag(123); - label->setString(string->getCString()); + label->setString(string); } diff --git a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h index 286c185a5152..48f081be94f6 100644 --- a/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h +++ b/tests/cpp-tests/Classes/ExtensionsTest/TableViewTest/TableViewTestScene.h @@ -14,12 +14,12 @@ class TableViewTest : public TestCase, public cocos2d::extension::TableViewDataS virtual bool init() override; - virtual void scrollViewDidScroll(cocos2d::extension::ScrollView* view) {}; - virtual void scrollViewDidZoom(cocos2d::extension::ScrollView* view) {} - virtual void tableCellTouched(cocos2d::extension::TableView* table, cocos2d::extension::TableViewCell* cell); - virtual cocos2d::Size tableCellSizeForIndex(cocos2d::extension::TableView *table, ssize_t idx); - virtual cocos2d::extension::TableViewCell* tableCellAtIndex(cocos2d::extension::TableView *table, ssize_t idx); - virtual ssize_t numberOfCellsInTableView(cocos2d::extension::TableView *table); + virtual void scrollViewDidScroll(cocos2d::extension::ScrollView* view)override {}; + virtual void scrollViewDidZoom(cocos2d::extension::ScrollView* view)override {} + virtual void tableCellTouched(cocos2d::extension::TableView* table, cocos2d::extension::TableViewCell* cell)override; + virtual cocos2d::Size tableCellSizeForIndex(cocos2d::extension::TableView *table, ssize_t idx)override; + virtual cocos2d::extension::TableViewCell* tableCellAtIndex(cocos2d::extension::TableView *table, ssize_t idx)override; + virtual ssize_t numberOfCellsInTableView(cocos2d::extension::TableView *table)override; }; #endif // __TABLEVIEWTESTSCENE_H__ diff --git a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp index b21c4c7ad9ca..c6df43d6c07f 100644 --- a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp +++ b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.cpp @@ -8,6 +8,7 @@ FileUtilsTests::FileUtilsTests() ADD_TEST_CASE(TestSearchPath); ADD_TEST_CASE(TestFilenameLookup); ADD_TEST_CASE(TestIsFileExist); + ADD_TEST_CASE(TestIsDirectoryExist); ADD_TEST_CASE(TestFileFuncs); ADD_TEST_CASE(TestDirectoryFuncs); ADD_TEST_CASE(TextWritePlist); @@ -15,6 +16,7 @@ FileUtilsTests::FileUtilsTests() ADD_TEST_CASE(TestWriteData); ADD_TEST_CASE(TestWriteValueMap); ADD_TEST_CASE(TestWriteValueVector); + ADD_TEST_CASE(TestUnicodePath); } // TestResolutionDirectories @@ -45,9 +47,9 @@ void TestResolutionDirectories::onEnter() sharedFileUtils->setSearchResolutionsOrder(resolutionsOrder); for( int i=1; i<7; i++) { - auto filename = String::createWithFormat("test%d.txt", i); - ret = sharedFileUtils->fullPathForFilename(filename->getCString()); - log("%s -> %s", filename->getCString(), ret.c_str()); + auto filename = StringUtils::format("test%d.txt", i); + ret = sharedFileUtils->fullPathForFilename(filename); + log("%s -> %s", filename.c_str(), ret.c_str()); } } @@ -108,9 +110,9 @@ void TestSearchPath::onEnter() sharedFileUtils->setSearchResolutionsOrder(resolutionsOrder); for( int i=1; i<3; i++) { - auto filename = String::createWithFormat("file%d.txt", i); - ret = sharedFileUtils->fullPathForFilename(filename->getCString()); - log("%s -> %s", filename->getCString(), ret.c_str()); + auto filename = StringUtils::format("file%d.txt", i); + ret = sharedFileUtils->fullPathForFilename(filename); + log("%s -> %s", filename.c_str(), ret.c_str()); } // Gets external.txt from writable path @@ -122,7 +124,7 @@ void TestSearchPath::onEnter() if (fp) { char szReadBuf[100] = {0}; - size_t read = fread(szReadBuf, 1, strlen(szBuf), fp); + size_t read = fread(szReadBuf, 1, strlen(szReadBuf), fp); if (read > 0) log("The content of file from writable path: %s", szReadBuf); fclose(fp); @@ -232,6 +234,61 @@ std::string TestIsFileExist::subtitle() const return ""; } +// TestIsDirectoryExist + +void TestIsDirectoryExist::onEnter() +{ + FileUtilsDemo::onEnter(); + auto s = Director::getInstance()->getWinSize(); + auto util = FileUtils::getInstance(); + int x = s.width/2, y = s.height/3; + + Label* label = nullptr; + std::string dir; + char msg[512]; + auto getMsg = [&dir, &msg](bool b)->const char * + { + snprintf((char *)msg, 512, "%s for dir: \"%s\"", b ? "success" : "failed", dir.c_str()); + return msg; + }; + + dir = "Images"; + label = Label::createWithSystemFont(getMsg(util->isDirectoryExist(dir)), "", 20); + label->setPosition(x, y * 2); + this->addChild(label); + + dir = util->getWritablePath(); + label = Label::createWithSystemFont(getMsg(util->isDirectoryExist(dir)), "", 20); + label->setPosition(x, y * 1); + this->addChild(label); + + dir = util->getWritablePath(); + label = Label::createWithSystemFont(getMsg(util->isDirectoryExist(dir)), "", 20); + label->setPosition(x, y * 1); + this->addChild(label); +} + +void TestIsDirectoryExist::onExit() +{ + + FileUtils *sharedFileUtils = FileUtils::getInstance(); + + // reset filename lookup + sharedFileUtils->purgeCachedEntries(); + + FileUtilsDemo::onExit(); +} + +std::string TestIsDirectoryExist::title() const +{ + return "FileUtils: check whether the directory exists"; +} + +std::string TestIsDirectoryExist::subtitle() const +{ + return ""; +} + // TestFileFuncs void TestFileFuncs::onEnter() @@ -399,43 +456,43 @@ std::string TestDirectoryFuncs::subtitle() const void TextWritePlist::onEnter() { FileUtilsDemo::onEnter(); - auto root = Dictionary::create(); - auto string = String::create("string element value"); + auto root = __Dictionary::create(); + auto string = __String::create("string element value"); root->setObject(string, "string element key"); - auto array = Array::create(); + auto array = __Array::create(); - auto dictInArray = Dictionary::create(); - dictInArray->setObject(String::create("string in dictInArray value 0"), "string in dictInArray key 0"); - dictInArray->setObject(String::create("string in dictInArray value 1"), "string in dictInArray key 1"); + auto dictInArray = __Dictionary::create(); + dictInArray->setObject(__String::create("string in dictInArray value 0"), "string in dictInArray key 0"); + dictInArray->setObject(__String::create("string in dictInArray value 1"), "string in dictInArray key 1"); array->addObject(dictInArray); - array->addObject(String::create("string in array")); + array->addObject(__String::create("string in array")); - auto arrayInArray = Array::create(); - arrayInArray->addObject(String::create("string 0 in arrayInArray")); - arrayInArray->addObject(String::create("string 1 in arrayInArray")); + auto arrayInArray = __Array::create(); + arrayInArray->addObject(__String::create("string 0 in arrayInArray")); + arrayInArray->addObject(__String::create("string 1 in arrayInArray")); array->addObject(arrayInArray); root->setObject(array, "array"); - auto dictInDict = Dictionary::create(); - dictInDict->setObject(String::create("string in dictInDict value"), "string in dictInDict key"); + auto dictInDict = __Dictionary::create(); + dictInDict->setObject(__String::create("string in dictInDict value"), "string in dictInDict key"); //add boolean to the plist - auto booleanObject = Bool::create(true); + auto booleanObject = __Bool::create(true); dictInDict->setObject(booleanObject, "bool"); //add interger to the plist - auto intObject = Integer::create(1024); + auto intObject = __Integer::create(1024); dictInDict->setObject(intObject, "integer"); //add float to the plist - auto floatObject = Float::create(1024.1024f); + auto floatObject = __Float::create(1024.1024f); dictInDict->setObject(floatObject, "float"); //add double to the plist - auto doubleObject = Double::create(1024.123); + auto doubleObject = __Double::create(1024.123); dictInDict->setObject(doubleObject, "double"); @@ -801,3 +858,101 @@ std::string TestWriteValueVector::subtitle() const { return ""; } + +// TestUnicodePath + +void TestUnicodePath::onEnter() +{ + FileUtilsDemo::onEnter(); + auto s = Director::getInstance()->getWinSize(); + auto util = FileUtils::getInstance(); + + int x = s.width/2, + y = s.height/5; + Label* label = nullptr; + + std::string dir = "中文路径/"; + std::string filename = "测试文件.test"; + + std::string act; + char msg[512]; + auto getMsg = [&act, &msg](bool b, const std::string& path)->const char * + { + snprintf((char *)msg, 512, "%s for %s path: \"%s\"", b ? "success" : "failed", act.c_str(), path.c_str()); + return msg; + }; + + // Check whether unicode dir should be create or not + std::string dirPath = util->getWritablePath() + dir; + if (!util->isDirectoryExist(dirPath)) + { + util->createDirectory(dirPath); + } + + act = "create"; + bool isExist = util->isDirectoryExist(dirPath); + label = Label::createWithSystemFont(getMsg(isExist, dirPath), "", 12, Size(s.width, 0)); + label->setPosition(x, y * 4); + this->addChild(label); + + if (isExist) + { + // Check whether unicode file should be create or not + std::string filePath = dirPath + filename; + if (! util->isFileExist(filePath)) + { + std::string writeDataStr = " 测试字符串."; + Data writeData; + writeData.copy((unsigned char *)writeDataStr.c_str(), writeDataStr.size()); + util->writeDataToFile(writeData, filePath); + } + + isExist = util->isFileExist(filePath); + label = Label::createWithSystemFont(getMsg(isExist, filePath), "", 12, Size(s.width, 0)); + label->setPosition(x, y * 3); + this->addChild(label); + + act = "remove"; + if (isExist) + { + // read file content and log it + unsigned char* buffer = nullptr; + Data readData = util->getDataFromFile(filePath); + buffer = (unsigned char*)malloc(sizeof(unsigned char) * (readData.getSize() + 1)); + memcpy(buffer, readData.getBytes(), readData.getSize()); + buffer[readData.getSize()] = '\0'; + // vc can't treat unicode string correctly, don't use unicode string in code + log("The content of file from writable path: %s", buffer); + free(buffer); + + // remove test file + label = Label::createWithSystemFont(getMsg(util->removeFile(filePath), filePath), "", 12, Size(s.width, 0)); + label->setPosition(x, y * 2); + this->addChild(label); + } + + // remove test dir + label = Label::createWithSystemFont(getMsg(util->removeDirectory(dirPath), dirPath), "", 12, Size(s.width, 0)); + label->setPosition(x, y * 1); + this->addChild(label); + } +} + +void TestUnicodePath::onExit() +{ + + FileUtils *sharedFileUtils = FileUtils::getInstance(); + sharedFileUtils->purgeCachedEntries(); + sharedFileUtils->setFilenameLookupDictionary(ValueMap()); + FileUtilsDemo::onExit(); +} + +std::string TestUnicodePath::title() const +{ + return "FileUtils: check unicode path"; +} + +std::string TestUnicodePath::subtitle() const +{ + return ""; +} diff --git a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.h b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.h index b177ed075523..e8f6856fd51b 100644 --- a/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.h +++ b/tests/cpp-tests/Classes/FileUtilsTest/FileUtilsTest.h @@ -60,6 +60,17 @@ class TestIsFileExist : public FileUtilsDemo virtual std::string subtitle() const override; }; +class TestIsDirectoryExist : public FileUtilsDemo +{ +public: + CREATE_FUNC(TestIsDirectoryExist); + + virtual void onEnter() override; + virtual void onExit() override; + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + class TestFileFuncs : public FileUtilsDemo { public: @@ -134,4 +145,16 @@ class TestWriteValueVector : public FileUtilsDemo virtual std::string title() const override; virtual std::string subtitle() const override; }; + +class TestUnicodePath : public FileUtilsDemo +{ +public: + CREATE_FUNC(TestUnicodePath); + + virtual void onEnter() override; + virtual void onExit() override; + virtual std::string title() const override; + virtual std::string subtitle() const override; +}; + #endif /* __FILEUTILSTEST_H__ */ diff --git a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp index 4513b1d6b850..0b79bd2f1223 100644 --- a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp +++ b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.cpp @@ -78,9 +78,9 @@ NewLabelTests::NewLabelTests() ADD_TEST_CASE(LabelIssue10773Test); ADD_TEST_CASE(LabelIssue11576Test); ADD_TEST_CASE(LabelIssue11699Test); - ADD_TEST_CASE(LabelIssue12259Test); ADD_TEST_CASE(LabelIssue12409Test); ADD_TEST_CASE(LabelAddChildTest); + ADD_TEST_CASE(LabelIssue12775Test); }; LabelTTFAlignmentNew::LabelTTFAlignmentNew() @@ -1581,7 +1581,7 @@ const char* LabelAlignmentTest::getCurrentAlignment() break; } - return String::createWithFormat("Alignment %s %s", vertical, horizontal)->getCString(); + return StringUtils::format("Alignment %s %s", vertical, horizontal).c_str(); } std::string LabelAlignmentTest::title() const @@ -1938,43 +1938,6 @@ std::string LabelIssue11699Test::subtitle() const return "Outline should match with the characters exactly."; } -LabelIssue12259Test::LabelIssue12259Test() -{ - auto center = VisibleRect::center(); - - auto label = Label::createWithTTF("Hello", "fonts/arial.ttf", 100); - label->setDimensions(0, 70); - label->setPosition(center.x, center.y); - addChild(label); - - auto drawNode = DrawNode::create(); - auto labelSize = label->getContentSize(); - auto origin = Director::getInstance()->getWinSize(); - - origin.width = origin.width / 2 - (labelSize.width / 2); - origin.height = origin.height / 2 - (labelSize.height / 2); - - Vec2 vertices[4] = - { - Vec2(origin.width, origin.height), - Vec2(labelSize.width + origin.width, origin.height), - Vec2(labelSize.width + origin.width, labelSize.height + origin.height), - Vec2(origin.width, labelSize.height + origin.height) - }; - drawNode->drawPoly(vertices, 4, true, Color4F::WHITE); - addChild(drawNode); -} - -std::string LabelIssue12259Test::title() const -{ - return "Test for Issue #12259"; -} - -std::string LabelIssue12259Test::subtitle() const -{ - return "the texture of character should be cropped."; -} - LabelIssue12409Test::LabelIssue12409Test() { auto center = VisibleRect::center(); @@ -2035,3 +1998,22 @@ std::string LabelAddChildTest::title() const { return "Label support add child nodes"; } + +LabelIssue12775Test::LabelIssue12775Test() +{ + auto center = VisibleRect::center(); + + auto label = Label::createWithTTF("Hello", "fonts/xingkai-incomplete.ttf", 30); + label->setPosition(center.x, center.y); + addChild(label); +} + +std::string LabelIssue12775Test::title() const +{ + return "Test for Issue #12775"; +} + +std::string LabelIssue12775Test::subtitle() const +{ + return "Should not crash if the font not contain a Unicode charmap."; +} diff --git a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.h b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.h index beeb51b7c881..6b170d28ffd1 100644 --- a/tests/cpp-tests/Classes/LabelTest/LabelTestNew.h +++ b/tests/cpp-tests/Classes/LabelTest/LabelTestNew.h @@ -587,36 +587,36 @@ class LabelIssue11699Test : public AtlasDemoNew virtual std::string subtitle() const override; }; -class LabelIssue12259Test : public AtlasDemoNew +class LabelIssue12409Test : public AtlasDemoNew { public: - CREATE_FUNC(LabelIssue12259Test); + CREATE_FUNC(LabelIssue12409Test); - LabelIssue12259Test(); + LabelIssue12409Test(); virtual std::string title() const override; virtual std::string subtitle() const override; }; -class LabelIssue12409Test : public AtlasDemoNew +class LabelAddChildTest : public AtlasDemoNew { public: - CREATE_FUNC(LabelIssue12409Test); + CREATE_FUNC(LabelAddChildTest); - LabelIssue12409Test(); + LabelAddChildTest(); virtual std::string title() const override; - virtual std::string subtitle() const override; }; -class LabelAddChildTest : public AtlasDemoNew +class LabelIssue12775Test : public AtlasDemoNew { public: - CREATE_FUNC(LabelAddChildTest); + CREATE_FUNC(LabelIssue12775Test); - LabelAddChildTest(); + LabelIssue12775Test(); virtual std::string title() const override; + virtual std::string subtitle() const override; }; #endif diff --git a/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.h b/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.h index 146ca249ec71..d83edd2cc0d8 100644 --- a/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.h +++ b/tests/cpp-tests/Classes/NavMeshTest/NavMeshTest.h @@ -88,9 +88,9 @@ class NavMeshBasicTestDemo : public NavMeshBaseTestDemo protected: - virtual void touchesBegan(const std::vector& touches, cocos2d::Event *event){}; - virtual void touchesMoved(const std::vector& touches, cocos2d::Event *event){}; - virtual void touchesEnded(const std::vector& touches, cocos2d::Event *event); + virtual void touchesBegan(const std::vector& touches, cocos2d::Event *event)override{}; + virtual void touchesMoved(const std::vector& touches, cocos2d::Event *event)override{}; + virtual void touchesEnded(const std::vector& touches, cocos2d::Event *event)override; protected: cocos2d::Label *_debugLabel; @@ -112,9 +112,9 @@ class NavMeshAdvanceTestDemo : public NavMeshBaseTestDemo protected: - virtual void touchesBegan(const std::vector& touches, cocos2d::Event *event){}; - virtual void touchesMoved(const std::vector& touches, cocos2d::Event *event){}; - virtual void touchesEnded(const std::vector& touches, cocos2d::Event *event); + virtual void touchesBegan(const std::vector& touches, cocos2d::Event *event)override{}; + virtual void touchesMoved(const std::vector& touches, cocos2d::Event *event)override{}; + virtual void touchesEnded(const std::vector& touches, cocos2d::Event *event)override; protected: cocos2d::Label *_obstacleLabel; diff --git a/tests/cpp-tests/Classes/NewAudioEngineTest/NewAudioEngineTest.cpp b/tests/cpp-tests/Classes/NewAudioEngineTest/NewAudioEngineTest.cpp index a506c286a58e..deddfa470b68 100644 --- a/tests/cpp-tests/Classes/NewAudioEngineTest/NewAudioEngineTest.cpp +++ b/tests/cpp-tests/Classes/NewAudioEngineTest/NewAudioEngineTest.cpp @@ -303,7 +303,7 @@ bool AudioControlTest::init() } }); _playItem = playItem; - playItem->setPosition(layerSize.width * 0.3f,layerSize.height * 0.7f); + playItem->setPosition(layerSize.width * 0.3f,layerSize.height * 0.8f); addChild(playItem); auto stopItem = TextButton::create("stop", [&](TextButton* button){ @@ -314,7 +314,7 @@ bool AudioControlTest::init() ((TextButton*)_playItem)->setEnabled(true); } }); - stopItem->setPosition(layerSize.width * 0.7f,layerSize.height * 0.7f); + stopItem->setPosition(layerSize.width * 0.7f,layerSize.height * 0.8f); addChild(stopItem); auto pauseItem = TextButton::create("pause", [&](TextButton* button){ @@ -322,7 +322,7 @@ bool AudioControlTest::init() AudioEngine::pause(_audioID); } }); - pauseItem->setPosition(layerSize.width * 0.3f,layerSize.height * 0.6f); + pauseItem->setPosition(layerSize.width * 0.3f,layerSize.height * 0.7f); addChild(pauseItem); auto resumeItem = TextButton::create("resume", [&](TextButton* button){ @@ -330,32 +330,38 @@ bool AudioControlTest::init() AudioEngine::resume(_audioID); } }); - resumeItem->setPosition(layerSize.width * 0.7f,layerSize.height * 0.6f); + resumeItem->setPosition(layerSize.width * 0.7f,layerSize.height * 0.7f); addChild(resumeItem); auto loopItem = TextButton::create("enable-loop", [&](TextButton* button){ _loopEnabled = !_loopEnabled; - - if (_audioID != AudioEngine::INVALID_AUDIO_ID ) { + + if (_audioID != AudioEngine::INVALID_AUDIO_ID) { AudioEngine::setLoop(_audioID, _loopEnabled); } - if(_loopEnabled){ + if (_loopEnabled){ button->setString("disable-loop"); } else { button->setString("enable-loop"); } }); - loopItem->setPosition(layerSize.width * 0.3f,layerSize.height * 0.5f); + loopItem->setPosition(layerSize.width * 0.5f, layerSize.height * 0.5f); addChild(loopItem); + auto preloadItem = TextButton::create("preload", [&](TextButton* button){ + AudioEngine::preload("background.mp3"); + }); + preloadItem->setPosition(layerSize.width * 0.3f, layerSize.height * 0.6f); + addChild(preloadItem); + auto uncacheItem = TextButton::create("uncache", [&](TextButton* button){ AudioEngine::uncache("background.mp3"); _audioID = AudioEngine::INVALID_AUDIO_ID; ((TextButton*)_playItem)->setEnabled(true); }); - uncacheItem->setPosition(layerSize.width * 0.7f,layerSize.height * 0.5f); + uncacheItem->setPosition(layerSize.width * 0.7f,layerSize.height * 0.6f); addChild(uncacheItem); auto volumeSlider = SliderEx::create(); diff --git a/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp b/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp index ecaa86d5e41f..d43e3ad46c25 100644 --- a/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp +++ b/tests/cpp-tests/Classes/ParticleTest/ParticleTest.cpp @@ -1316,7 +1316,7 @@ void ParticleReorder::reorderParticles(float dt) class RainbowEffect : public ParticleSystemQuad { public: - bool init(); + bool init()override; virtual bool initWithTotalParticles(int numberOfParticles) override; virtual void update(float dt) override; }; diff --git a/tests/cpp-tests/Classes/ParticleTest/ParticleTest.h b/tests/cpp-tests/Classes/ParticleTest/ParticleTest.h index 56d4220c8f55..a7c5a8cbba77 100644 --- a/tests/cpp-tests/Classes/ParticleTest/ParticleTest.h +++ b/tests/cpp-tests/Classes/ParticleTest/ParticleTest.h @@ -15,7 +15,7 @@ class ParticleDemo : public TestCase public: ~ParticleDemo(); - virtual void onEnter(); + virtual void onEnter()override; virtual std::string title() const override; virtual std::string subtitle() const override; diff --git a/tests/cpp-tests/Classes/PerformanceTest/PerformanceAllocTest.h b/tests/cpp-tests/Classes/PerformanceTest/PerformanceAllocTest.h index fd70b950df72..6221a6a7eb0b 100644 --- a/tests/cpp-tests/Classes/PerformanceTest/PerformanceAllocTest.h +++ b/tests/cpp-tests/Classes/PerformanceTest/PerformanceAllocTest.h @@ -13,8 +13,8 @@ class PerformceAllocScene : public TestCase public: virtual bool init() override; virtual void initWithQuantityOfNodes(unsigned int nNodes); - virtual std::string title() const; - virtual std::string subtitle() const; + virtual std::string title() const override; + virtual std::string subtitle() const override; virtual void updateQuantityOfNodes() = 0; const char* profilerName(); diff --git a/tests/cpp-tests/Classes/PerformanceTest/PerformanceCallbackTest.h b/tests/cpp-tests/Classes/PerformanceTest/PerformanceCallbackTest.h index bed606e66f5f..cce620f34d4a 100644 --- a/tests/cpp-tests/Classes/PerformanceTest/PerformanceCallbackTest.h +++ b/tests/cpp-tests/Classes/PerformanceTest/PerformanceCallbackTest.h @@ -12,8 +12,8 @@ class PerformanceCallbackScene : public TestCase { public: virtual void onEnter() override; - virtual std::string title() const; - virtual std::string subtitle() const; + virtual std::string title() const override; + virtual std::string subtitle() const override; virtual void onUpdate(float dt) {}; void dumpProfilerInfo(float dt); diff --git a/tests/cpp-tests/Classes/PerformanceTest/PerformanceContainerTest.cpp b/tests/cpp-tests/Classes/PerformanceTest/PerformanceContainerTest.cpp index 5cd175312209..853e151e9537 100644 --- a/tests/cpp-tests/Classes/PerformanceTest/PerformanceContainerTest.cpp +++ b/tests/cpp-tests/Classes/PerformanceTest/PerformanceContainerTest.cpp @@ -482,7 +482,7 @@ std::string ArrayPerfTest::subtitle() const void ArrayPerfTest::generateTestFunctions() { auto createArray = [this](){ - __Array* ret = Array::create(); + __Array* ret = __Array::create(); for( int i=0; iprofilerName()); for( int i=0; iprofilerName()); } } , { "insertObject", [=](){ - __Array* nodeVector = Array::create(); + __Array* nodeVector = __Array::create(); CC_PROFILER_START(this->profilerName()); for( int i=0; iprofilerName()); for( int i=0; isetPosition(itemPos); _playerDlg->addChild(itemBg); - auto item = ui::Button::create("crystal.png", "", "", ui::TextureResType::PLIST); + auto item = ui::Button::create("crystal.png", "", "", ui::Widget::TextureResType::PLIST); item->setTitleText("Crystal"); item->setScale(1.5); item->setAnchorPoint(itemAnchor); diff --git a/tests/cpp-tests/Classes/ShaderTest/ShaderTest.cpp b/tests/cpp-tests/Classes/ShaderTest/ShaderTest.cpp index 46a6ee9c8db0..4a73940f36e2 100644 --- a/tests/cpp-tests/Classes/ShaderTest/ShaderTest.cpp +++ b/tests/cpp-tests/Classes/ShaderTest/ShaderTest.cpp @@ -401,8 +401,8 @@ bool SpriteBlur::initWithTexture(Texture2D* texture, const Rect& rect) void SpriteBlur::initGLProgram() { - GLchar * fragSource = (GLchar*) String::createWithContentsOfFile( - FileUtils::getInstance()->fullPathForFilename("Shaders/example_Blur.fsh").c_str())->getCString(); + GLchar * fragSource = (GLchar*) FileUtils::getInstance()->getStringFromFile( + FileUtils::getInstance()->fullPathForFilename("Shaders/example_Blur.fsh")).c_str(); auto program = GLProgram::createWithByteArrays(ccPositionTextureColor_noMVP_vert, fragSource); auto glProgramState = GLProgramState::getOrCreateWithGLProgram(program); @@ -530,7 +530,7 @@ bool ShaderRetroEffect::init() { if( ShaderTestDemo::init() ) { - GLchar * fragSource = (GLchar*) String::createWithContentsOfFile(FileUtils::getInstance()->fullPathForFilename("Shaders/example_HorizontalColor.fsh"))->getCString(); + GLchar * fragSource = (GLchar*) FileUtils::getInstance()->getStringFromFile(FileUtils::getInstance()->fullPathForFilename("Shaders/example_HorizontalColor.fsh")).c_str(); auto p = GLProgram::createWithByteArrays(ccPositionTexture_vert, fragSource); auto director = Director::getInstance(); diff --git a/tests/cpp-tests/Classes/Sprite3DTest/Sprite3DTest.cpp b/tests/cpp-tests/Classes/Sprite3DTest/Sprite3DTest.cpp index 12ff471c23ce..b66d1af49a94 100644 --- a/tests/cpp-tests/Classes/Sprite3DTest/Sprite3DTest.cpp +++ b/tests/cpp-tests/Classes/Sprite3DTest/Sprite3DTest.cpp @@ -57,6 +57,7 @@ Sprite3DTests::Sprite3DTests() ADD_TEST_CASE(NodeAnimationTest); ADD_TEST_CASE(Issue9767); ADD_TEST_CASE(Sprite3DClippingTest); + ADD_TEST_CASE(Sprite3DTestMeshLight); }; //------------------------------------------------------------------ @@ -1185,7 +1186,7 @@ AsyncLoadSprite3DTest::AsyncLoadSprite3DTest() auto s = Director::getInstance()->getWinSize(); item1->setPosition( s.width * .5f, s.height * .8f); - auto pMenu1 = CCMenu::create(item1, nullptr); + auto pMenu1 = Menu::create(item1, nullptr); pMenu1->setPosition(Vec2(0,0)); this->addChild(pMenu1, 10); @@ -1243,17 +1244,17 @@ Sprite3DWithSkinTest::Sprite3DWithSkinTest() listener->onTouchesEnded = CC_CALLBACK_2(Sprite3DWithSkinTest::onTouchesEnded, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - // swich camera + // swich animation quality. In fact, you can set the sprite3d out of frustum to Animate3DQuality::QUALITY_NONE, it can save a lot of cpu time MenuItemFont::setFontName("fonts/arial.ttf"); MenuItemFont::setFontSize(15); - _menuItem = MenuItemFont::create("High Quality", CC_CALLBACK_1(Sprite3DWithSkinTest::switchAnimationQualityCallback,this)); + _animateQuality = (int)Animate3DQuality::QUALITY_LOW; + _menuItem = MenuItemFont::create(getAnimationQualityMessage(), CC_CALLBACK_1(Sprite3DWithSkinTest::switchAnimationQualityCallback,this)); _menuItem->setColor(Color3B(0,200,20)); auto menu = Menu::create(_menuItem,NULL); menu->setPosition(Vec2::ZERO); _menuItem->setPosition(VisibleRect::left().x + 50, VisibleRect::top().y -70); addChild(menu, 1); - - _animateQuality = (int)Animate3DQuality::QUALITY_HIGH; + _sprits.clear(); auto s = Director::getInstance()->getWinSize(); @@ -1303,18 +1304,25 @@ void Sprite3DWithSkinTest::addNewSpriteWithCoords(Vec2 p) } } +std::string Sprite3DWithSkinTest::getAnimationQualityMessage() const +{ + if (_animateQuality == (int)Animate3DQuality::QUALITY_NONE) + return "None Quality"; + else if (_animateQuality == (int)Animate3DQuality::QUALITY_LOW) + return "Low Quality"; + else if (_animateQuality == (int)Animate3DQuality::QUALITY_HIGH) + return "High Quality"; + + return ""; +} + void Sprite3DWithSkinTest::switchAnimationQualityCallback(Ref* sender) { ++_animateQuality; if (_animateQuality > (int)Animate3DQuality::QUALITY_HIGH) _animateQuality = (int)Animate3DQuality::QUALITY_NONE; - if (_animateQuality == (int)Animate3DQuality::QUALITY_NONE) - _menuItem->setString("None Quality"); - else if (_animateQuality == (int)Animate3DQuality::QUALITY_LOW) - _menuItem->setString("Low Quality"); - else if (_animateQuality == (int)Animate3DQuality::QUALITY_HIGH) - _menuItem->setString("High Quality"); + _menuItem->setString(getAnimationQualityMessage()); for (auto iter: _sprits) { @@ -1630,7 +1638,7 @@ Sprite3DReskinTest::Sprite3DReskinTest() item3->setUserData((void*)SkinType::UPPER_BODY); item4->setUserData((void*)SkinType::PANTS); item5->setUserData((void*)SkinType::SHOES); - auto pMenu1 = CCMenu::create(item1, item2, item3, item4, item5, nullptr); + auto pMenu1 = Menu::create(item1, item2, item3, item4, item5, nullptr); pMenu1->setPosition(Vec2(0,0)); this->addChild(pMenu1, 10); @@ -2223,7 +2231,7 @@ void UseCaseSprite3D::switchCase() item1->setPosition( Vec2(s.width * 0.5f - item1->getContentSize().width * 0.5f, s.height * 0.5f - item1->getContentSize().height ) ); item2->setPosition( Vec2(s.width * 0.5f - item1->getContentSize().width * 0.5f, s.height * 0.5f - item1->getContentSize().height * 2.f ) ); - auto pMenu1 = CCMenu::create(item1, item2, nullptr); + auto pMenu1 = Menu::create(item1, item2, nullptr); pMenu1->setPosition(Vec2(0,0)); layer->addChild(pMenu1); @@ -2535,7 +2543,7 @@ Issue9767::Issue9767() item1->setPosition( Vec2(s.width * 0.9f - item1->getContentSize().width * 0.5f, s.height * 0.5f - item1->getContentSize().height ) ); - auto pMenu1 = CCMenu::create(item1, nullptr); + auto pMenu1 = Menu::create(item1, nullptr); pMenu1->setPosition(Vec2(0,0)); addChild(pMenu1); } @@ -2609,3 +2617,35 @@ std::string Sprite3DClippingTest::subtitle() const { return ""; } + +Sprite3DTestMeshLight::Sprite3DTestMeshLight() +{ + auto s = Director::getInstance()->getWinSize(); + + auto _sprite = Sprite3D::create("Sprite3DTest/mesh_model.c3b"); + _sprite->setPosition(Vec2(0, 0)); + _sprite->setScale(0.05f); + _sprite->setCameraMask(2); + + PointLight * light = PointLight::create(Vec3(0, 0, 400), Color3B(255, 255, 255), 1000.0f); + + //setup camera + auto camera = Camera::createPerspective(40, s.width / s.height, 0.01f, 1000.f); + camera->setCameraFlag(CameraFlag::USER1); + camera->setPosition3D(Vec3(0.f, 30.f, 100.f)); + camera->lookAt(Vec3(0.f, 0.f, 0.f)); + addChild(camera); + + addChild(_sprite); + addChild(light); +} + +std::string Sprite3DTestMeshLight::title() const +{ + return "3D mesh with light without texture"; +} + +std::string Sprite3DTestMeshLight::subtitle() const +{ + return ""; +} \ No newline at end of file diff --git a/tests/cpp-tests/Classes/Sprite3DTest/Sprite3DTest.h b/tests/cpp-tests/Classes/Sprite3DTest/Sprite3DTest.h index 1a5a0e8fb2c0..eaf8695e3485 100644 --- a/tests/cpp-tests/Classes/Sprite3DTest/Sprite3DTest.h +++ b/tests/cpp-tests/Classes/Sprite3DTest/Sprite3DTest.h @@ -287,6 +287,8 @@ class Sprite3DWithSkinTest : public Sprite3DTestDemo void switchAnimationQualityCallback(cocos2d::Ref* sender); void onTouchesEnded(const std::vector& touches, cocos2d::Event* event); + + std::string getAnimationQualityMessage() const; private: std::vector _sprits; int _animateQuality; @@ -565,4 +567,16 @@ class Sprite3DClippingTest : public Sprite3DTestDemo virtual std::string subtitle() const override; }; +class Sprite3DTestMeshLight : public Sprite3DTestDemo +{ +public: + CREATE_FUNC(Sprite3DTestMeshLight); + Sprite3DTestMeshLight(); + virtual std::string title() const override; + virtual std::string subtitle() const override; + +protected: + cocos2d::Sprite3D* _sprite; +}; + #endif diff --git a/tests/cpp-tests/Classes/SpritePolygonTest/SpritePolygonTest.h b/tests/cpp-tests/Classes/SpritePolygonTest/SpritePolygonTest.h index 13f8a9386812..72373fbf8df7 100644 --- a/tests/cpp-tests/Classes/SpritePolygonTest/SpritePolygonTest.h +++ b/tests/cpp-tests/Classes/SpritePolygonTest/SpritePolygonTest.h @@ -8,7 +8,7 @@ DEFINE_TEST_SUITE(SpritePolygonTest); class SpritePolygonTestCase : public TestCase { protected: - virtual void onBackCallback(Ref* sender); + virtual void onBackCallback(Ref* sender)override; std::string _title; std::string _subtitle; virtual std::string title() const override {return _title;}; diff --git a/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp b/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp index 7454a0290340..dbfeedd6af90 100644 --- a/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp +++ b/tests/cpp-tests/Classes/SpriteTest/SpriteTest.cpp @@ -584,7 +584,7 @@ std::string SpriteBatchNodeZOrder::subtitle() const SpriteBatchNodeReorder::SpriteBatchNodeReorder() { - auto a = Array::createWithCapacity(10); + auto a = __Array::createWithCapacity(10); auto asmtest = SpriteBatchNode::create("animations/ghosts.png"); for(int i=0; i<10; i++) diff --git a/tests/cpp-tests/Classes/TextInputTest/TextInputTest.h b/tests/cpp-tests/Classes/TextInputTest/TextInputTest.h index 5e6668ae7fd0..0ea4f15dbe64 100644 --- a/tests/cpp-tests/Classes/TextInputTest/TextInputTest.h +++ b/tests/cpp-tests/Classes/TextInputTest/TextInputTest.h @@ -18,7 +18,7 @@ class KeyboardNotificationLayer : public TestCase, public cocos2d::IMEDelegate virtual std::string title() const override; virtual void onClickTrackNode(bool bClicked) = 0; - virtual void keyboardWillShow(cocos2d::IMEKeyboardNotificationInfo& info); + virtual void keyboardWillShow(cocos2d::IMEKeyboardNotificationInfo& info)override; bool onTouchBegan(cocos2d::Touch* touch, cocos2d::Event* event); void onTouchEnded(cocos2d::Touch* touch, cocos2d::Event* event); diff --git a/tests/cpp-tests/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.h b/tests/cpp-tests/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.h index c525cf53c527..a87ef0177027 100644 --- a/tests/cpp-tests/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.h +++ b/tests/cpp-tests/Classes/TexturePackerEncryptionTest/TextureAtlasEncryptionTest.h @@ -12,7 +12,7 @@ class TextureAtlasEncryptionDemo : public TestCase public: CREATE_FUNC(TextureAtlasEncryptionDemo); - virtual std::string title() const; + virtual std::string title() const override; virtual void onEnter() override; protected: diff --git a/tests/cpp-tests/Classes/TileMapTest/TileMapTest.cpp b/tests/cpp-tests/Classes/TileMapTest/TileMapTest.cpp index 62480a131a31..676df1d2f9ff 100644 --- a/tests/cpp-tests/Classes/TileMapTest/TileMapTest.cpp +++ b/tests/cpp-tests/Classes/TileMapTest/TileMapTest.cpp @@ -1294,7 +1294,7 @@ TMXOrthoFromXMLTest::TMXOrthoFromXMLTest() std::string resources = "TileMaps"; // partial paths are OK as resource paths. std::string file = resources + "/orthogonal-test1.tmx"; - auto str = String::createWithContentsOfFile(FileUtils::getInstance()->fullPathForFilename(file.c_str()).c_str()); + auto str = __String::createWithContentsOfFile(FileUtils::getInstance()->fullPathForFilename(file.c_str()).c_str()); CCASSERT(str != nullptr, "Unable to open file"); auto map = TMXTiledMap::createWithXML(str->getCString() ,resources.c_str()); diff --git a/tests/cpp-tests/Classes/TileMapTest/TileMapTest.h b/tests/cpp-tests/Classes/TileMapTest/TileMapTest.h index 72f4bacdfe9c..831aa18610f7 100644 --- a/tests/cpp-tests/Classes/TileMapTest/TileMapTest.h +++ b/tests/cpp-tests/Classes/TileMapTest/TileMapTest.h @@ -186,7 +186,7 @@ class TMXIsoZorder : public TileDemo TMXIsoZorder(); virtual std::string title() const override; virtual std::string subtitle() const override; - virtual void onExit(); + virtual void onExit()override; ~TMXIsoZorder(); void repositionSprite(float dt); diff --git a/tests/cpp-tests/Classes/TileMapTest/TileMapTest2.cpp b/tests/cpp-tests/Classes/TileMapTest/TileMapTest2.cpp index 8468e44720f8..83d4f5ab5578 100644 --- a/tests/cpp-tests/Classes/TileMapTest/TileMapTest2.cpp +++ b/tests/cpp-tests/Classes/TileMapTest/TileMapTest2.cpp @@ -1211,7 +1211,7 @@ TMXOrthoFromXMLTestNew::TMXOrthoFromXMLTestNew() std::string resources = "TileMaps"; // partial paths are OK as resource paths. std::string file = resources + "/orthogonal-test1.tmx"; - auto str = String::createWithContentsOfFile(FileUtils::getInstance()->fullPathForFilename(file.c_str()).c_str()); + auto str = __String::createWithContentsOfFile(FileUtils::getInstance()->fullPathForFilename(file.c_str()).c_str()); CCASSERT(str != nullptr, "Unable to open file"); auto map = cocos2d::experimental::TMXTiledMap::createWithXML(str->getCString() ,resources.c_str()); diff --git a/tests/cpp-tests/Classes/TileMapTest/TileMapTest2.h b/tests/cpp-tests/Classes/TileMapTest/TileMapTest2.h index b88b76f60bac..181586439d00 100644 --- a/tests/cpp-tests/Classes/TileMapTest/TileMapTest2.h +++ b/tests/cpp-tests/Classes/TileMapTest/TileMapTest2.h @@ -173,7 +173,7 @@ class TMXIsoZorderNew : public TileDemoNew TMXIsoZorderNew(); virtual std::string title() const override; virtual std::string subtitle() const override; - virtual void onExit(); + virtual void onExit()override; ~TMXIsoZorderNew(); void repositionSprite(float dt); diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/CustomWidget/CustomParticleWidget.h b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/CustomWidget/CustomParticleWidget.h index 51ea40700fff..61c049096a76 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/CustomWidget/CustomParticleWidget.h +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/CustomWidget/CustomParticleWidget.h @@ -37,9 +37,9 @@ class CustomParticleWidget : public cocos2d::ui::Widget protected: virtual bool init() override; - virtual void initRenderer(); + virtual void initRenderer()override; - virtual void removeAllChildren(); + virtual void removeAllChildren()override; protected: cocos2d::ParticleSystem* _emitter; diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp index 3db6191344e3..6d64f1e43b23 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIButtonTest/UIButtonTest.cpp @@ -86,16 +86,16 @@ void UIButtonTest::touchEvent(Ref *pSender, Widget::TouchEventType type) switch (type) { case Widget::TouchEventType::BEGAN: - _displayValueLabel->setString(String::createWithFormat("Touch Down")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Down")); break; case Widget::TouchEventType::MOVED: - _displayValueLabel->setString(String::createWithFormat("Touch Move")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Move")); break; case Widget::TouchEventType::ENDED: { - _displayValueLabel->setString(String::createWithFormat("Touch Up")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Up")); ImageView* imageView = (ImageView*)_uiLayer->getChildByTag(12); imageView->setVisible(false); imageView->loadTexture("cocosui/ccicon.png"); @@ -108,7 +108,7 @@ void UIButtonTest::touchEvent(Ref *pSender, Widget::TouchEventType type) break; case Widget::TouchEventType::CANCELED: - _displayValueLabel->setString(String::createWithFormat("Touch Cancelled")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Cancelled")); break; default: @@ -177,16 +177,16 @@ void UIButtonTest_Scale9::touchEvent(Ref *pSender, Widget::TouchEventType type) switch (type) { case Widget::TouchEventType::BEGAN: - _displayValueLabel->setString(String::createWithFormat("Touch Down")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Down")); break; case Widget::TouchEventType::MOVED: - _displayValueLabel->setString(String::createWithFormat("Touch Move")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Move")); break; case Widget::TouchEventType::ENDED: { - _displayValueLabel->setString(String::createWithFormat("Touch Up")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Up")); Button *btn = (Button*)_uiLayer->getChildByName("normal"); btn->loadTextureNormal("cocosui/animationbuttonnormal.png"); btn->loadTexturePressed("cocosui/animationbuttonpressed.png"); @@ -195,7 +195,7 @@ void UIButtonTest_Scale9::touchEvent(Ref *pSender, Widget::TouchEventType type) break; case Widget::TouchEventType::CANCELED: - _displayValueLabel->setString(String::createWithFormat("Touch Cancelled")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Cancelled")); break; default: @@ -266,16 +266,16 @@ void UIButtonTest_Scale9_State_Change::touchEvent(Ref *pSender, Widget::TouchEve switch (type) { case Widget::TouchEventType::BEGAN: - _displayValueLabel->setString(String::createWithFormat("Touch Down")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Down")); break; case Widget::TouchEventType::MOVED: - _displayValueLabel->setString(String::createWithFormat("Touch Move")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Move")); break; case Widget::TouchEventType::ENDED: { - _displayValueLabel->setString(String::createWithFormat("Touch Up")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Up")); Button *btn = (Button*)pSender; if (btn->isScale9Enabled()) { @@ -287,7 +287,7 @@ void UIButtonTest_Scale9_State_Change::touchEvent(Ref *pSender, Widget::TouchEve break; case Widget::TouchEventType::CANCELED: - _displayValueLabel->setString(String::createWithFormat("Touch Cancelled")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Cancelled")); break; default: @@ -351,16 +351,16 @@ void UIButtonTest_PressedAction::touchEvent(Ref *pSender, Widget::TouchEventType switch (type) { case Widget::TouchEventType::BEGAN: - _displayValueLabel->setString(String::createWithFormat("Touch Down")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Down")); break; case Widget::TouchEventType::MOVED: - _displayValueLabel->setString(String::createWithFormat("Touch Move")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Move")); break; case Widget::TouchEventType::ENDED: { - _displayValueLabel->setString(String::createWithFormat("Touch Up")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Up")); Button* btn = (Button*)_uiLayer->getChildByName("button"); btn->loadTextureNormal("cocosui/animationbuttonnormal.png"); @@ -370,7 +370,7 @@ void UIButtonTest_PressedAction::touchEvent(Ref *pSender, Widget::TouchEventType break; case Widget::TouchEventType::CANCELED: - _displayValueLabel->setString(String::createWithFormat("Touch Cancelled")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Cancelled")); break; default: @@ -451,16 +451,16 @@ void UIButtonTest_Title::touchEvent(Ref *pSender, Widget::TouchEventType type) switch (type) { case Widget::TouchEventType::BEGAN: - _displayValueLabel->setString(String::createWithFormat("Touch Down")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Down")); break; case Widget::TouchEventType::MOVED: - _displayValueLabel->setString(String::createWithFormat("Touch Move")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Move")); break; case Widget::TouchEventType::ENDED: { - _displayValueLabel->setString(String::createWithFormat("Touch Up")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Up")); TextBMFont *text = (TextBMFont*)_uiLayer->getChildByName("text"); text->setFntFile("cocosui/bitmapFontTest2.fnt"); if (text->getString() == "BMFont") { @@ -473,7 +473,7 @@ void UIButtonTest_Title::touchEvent(Ref *pSender, Widget::TouchEventType type) break; case Widget::TouchEventType::CANCELED: - _displayValueLabel->setString(String::createWithFormat("Touch Cancelled")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Cancelled")); break; default: @@ -544,23 +544,23 @@ void UIButtonTestRemoveSelf::touchEvent(Ref *pSender, Widget::TouchEventType typ switch (type) { case Widget::TouchEventType::BEGAN: - _displayValueLabel->setString(String::createWithFormat("Touch Down")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Down")); break; case Widget::TouchEventType::MOVED: - _displayValueLabel->setString(String::createWithFormat("Touch Move")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Move")); break; case Widget::TouchEventType::ENDED: { - _displayValueLabel->setString(String::createWithFormat("Touch Up")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Up")); auto layout = _uiLayer->getChildByTag(12); layout->removeFromParentAndCleanup(true); } break; case Widget::TouchEventType::CANCELED: - _displayValueLabel->setString(String::createWithFormat("Touch Cancelled")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Cancelled")); break; default: @@ -614,16 +614,16 @@ void UIButtonTestSwitchScale9::touchEvent(Ref *pSender, Widget::TouchEventType t switch (type) { case Widget::TouchEventType::BEGAN: - _displayValueLabel->setString(String::createWithFormat("Touch Down")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Down")); break; case Widget::TouchEventType::MOVED: - _displayValueLabel->setString(String::createWithFormat("Touch Move")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Move")); break; case Widget::TouchEventType::ENDED: { - _displayValueLabel->setString(String::createWithFormat("Touch Up")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Up")); auto btn = ((Button*)pSender); btn->setScale9Enabled(!btn->isScale9Enabled()); btn->setContentSize(Size(200,100)); @@ -631,7 +631,7 @@ void UIButtonTestSwitchScale9::touchEvent(Ref *pSender, Widget::TouchEventType t break; case Widget::TouchEventType::CANCELED: - _displayValueLabel->setString(String::createWithFormat("Touch Cancelled")->getCString()); + _displayValueLabel->setString(StringUtils::format("Touch Cancelled")); break; default: @@ -700,7 +700,7 @@ void UIButtonTestZoomScale::sliderEvent(Ref *pSender, Slider::EventType type) Button* btn = (Button*)_uiLayer->getChildByName("button"); float zoomScale = percent * 0.01; btn->setZoomScale(zoomScale); - _displayValueLabel->setString(String::createWithFormat("Zoom Scale: %f", zoomScale)->getCString()); + _displayValueLabel->setString(StringUtils::format("Zoom Scale: %f", zoomScale)); } } diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp index f073d331bcf6..746705dc4127 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UICheckBoxTest/UICheckBoxTest.cpp @@ -60,11 +60,11 @@ void UICheckBoxTest::selectedEvent(Ref* pSender,CheckBox::EventType type) switch (type) { case CheckBox::EventType::SELECTED: - _displayValueLabel->setString(String::createWithFormat("Selected")->getCString()); + _displayValueLabel->setString(StringUtils::format("Selected")); break; case CheckBox::EventType::UNSELECTED: - _displayValueLabel->setString(String::createWithFormat("Unselected")->getCString()); + _displayValueLabel->setString(StringUtils::format("Unselected")); break; default: diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIEditBoxTest.h b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIEditBoxTest.h index 11b60eabbbf1..c4680c30c6a5 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIEditBoxTest.h +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIEditBoxTest.h @@ -36,10 +36,10 @@ class UIEditBoxTest : public UIScene, public cocos2d::ui::EditBoxDelegate virtual bool init() override; - virtual void editBoxEditingDidBegin(cocos2d::ui::EditBox* editBox); - virtual void editBoxEditingDidEnd(cocos2d::ui::EditBox* editBox); - virtual void editBoxTextChanged(cocos2d::ui::EditBox* editBox, const std::string& text); - virtual void editBoxReturn(cocos2d::ui::EditBox* editBox); + virtual void editBoxEditingDidBegin(cocos2d::ui::EditBox* editBox)override; + virtual void editBoxEditingDidEnd(cocos2d::ui::EditBox* editBox)override; + virtual void editBoxTextChanged(cocos2d::ui::EditBox* editBox, const std::string& text)override; + virtual void editBoxReturn(cocos2d::ui::EditBox* editBox)override; protected: diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILayoutTest/UILayoutTest.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILayoutTest/UILayoutTest.cpp index b38944ac00c6..02cdb5d4d5e1 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILayoutTest/UILayoutTest.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILayoutTest/UILayoutTest.cpp @@ -361,7 +361,7 @@ bool UILayoutTest_Layout_Linear_Vertical::init() // Create the layout Layout* layout = Layout::create(); - layout->setLayoutType(LayoutType::VERTICAL); + layout->setLayoutType(Layout::Type::VERTICAL); layout->setContentSize(Size(280, 150)); Size backgroundSize = background->getContentSize(); layout->setPosition(Vec2((widgetSize.width - backgroundSize.width) / 2.0f + @@ -435,7 +435,7 @@ bool UILayoutTest_Layout_Linear_Horizontal::init() // Create the layout Layout* layout = Layout::create(); - layout->setLayoutType(LayoutType::HORIZONTAL); + layout->setLayoutType(Layout::Type::HORIZONTAL); layout->setClippingEnabled(true); layout->setContentSize(Size(280, 150)); Size backgroundSize = background->getContentSize(); @@ -509,7 +509,7 @@ bool UILayoutTest_Layout_Relative_Align_Parent::init() // Create the layout Layout* layout = Layout::create(); - layout->setLayoutType(LayoutType::RELATIVE); + layout->setLayoutType(Layout::Type::RELATIVE); layout->setContentSize(Size(280, 150)); layout->setBackGroundColorType(Layout::BackGroundColorType::SOLID); layout->setBackGroundColor(Color3B::GREEN); @@ -644,7 +644,7 @@ bool UILayoutTest_Layout_Relative_Location::init() // Create the layout Layout* layout = Layout::create(); - layout->setLayoutType(LayoutType::RELATIVE); + layout->setLayoutType(Layout::Type::RELATIVE); layout->setContentSize(Size(280, 150)); Size backgroundSize = background->getContentSize(); layout->setPosition(Vec2((widgetSize.width - backgroundSize.width) / 2.0f + diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILayoutTest/UILayoutTest_Editor.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILayoutTest/UILayoutTest_Editor.cpp index ba91c867dbf6..a5501f5f59e4 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILayoutTest/UILayoutTest_Editor.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILayoutTest/UILayoutTest_Editor.cpp @@ -457,7 +457,7 @@ void UILayoutComponentTest_Editor::onChangeLayoutComponent(Ref* sender) } } - statusPin = String::createWithFormat("Pin:%s%s", hPinStatus.c_str(), vPinStatus.c_str())->getCString(); + statusPin = StringUtils::format("Pin:%s%s", hPinStatus.c_str(), vPinStatus.c_str()); _textPin->setString(statusPin); auto layoutComponent = ui::LayoutComponent::bindLayoutComponent(_widget); diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.cpp index db674baa1d52..e147286811be 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIListViewTest/UIListViewTest_Editor.cpp @@ -52,7 +52,7 @@ void UIListViewTest_Vertical_Editor::setupListView(ListView* listView) float itemMargin = listView->getItemsMargin(); auto item0 = Text::create(); - item0->setString(String::createWithFormat("Item margin: %d", static_cast(itemMargin))->getCString()); + item0->setString(StringUtils::format("Item margin: %d", static_cast(itemMargin))); listView->addChild(item0); auto item1 = Layout::create(); diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.h b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.h index c5a2e588654e..d70d73c8d460 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.h +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest.h @@ -37,7 +37,7 @@ class UILoadingBarTest_Left : public UIScene UILoadingBarTest_Left(); ~UILoadingBarTest_Left(); virtual bool init() override; - void update(float delta); + void update(float delta)override; protected: int _count; @@ -51,7 +51,7 @@ class UILoadingBarTest_Right : public UIScene UILoadingBarTest_Right(); ~UILoadingBarTest_Right(); virtual bool init() override; - void update(float delta); + void update(float delta)override; protected: int _count; @@ -65,7 +65,7 @@ class UILoadingBarTest_Left_Scale9 : public UIScene UILoadingBarTest_Left_Scale9(); ~UILoadingBarTest_Left_Scale9(); virtual bool init() override; - void update(float delta); + void update(float delta)override; protected: int _count; @@ -79,7 +79,7 @@ class UILoadingBarTest_Right_Scale9 : public UIScene UILoadingBarTest_Right_Scale9(); ~UILoadingBarTest_Right_Scale9(); virtual bool init() override; - void update(float delta); + void update(float delta)override; protected: int _count; diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest_Editor.h b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest_Editor.h index 5d12bb196a94..60b4d4a9ab93 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest_Editor.h +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UILoadingBarTest/UILoadingBarTest_Editor.h @@ -15,7 +15,7 @@ class UILoadingBarTest_Editor : public UIScene_Editor UILoadingBarTest_Editor(); ~UILoadingBarTest_Editor(); virtual bool init() override; - void update(float delta); + void update(float delta)override; virtual void configureGUIScene() override; protected: diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp index cb31870d9431..fac654eb94fd 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIPageViewTest/UIPageViewTest.cpp @@ -99,7 +99,7 @@ void UIPageViewTest::pageViewEvent(Ref *pSender, PageView::EventType type) { PageView* pageView = dynamic_cast(pSender); - _displayValueLabel->setString(CCString::createWithFormat("page = %ld", pageView->getCurPageIndex() + 1)->getCString()); + _displayValueLabel->setString(StringUtils::format("page = %ld", pageView->getCurPageIndex() + 1)); } break; @@ -209,7 +209,7 @@ void UIPageViewButtonTest::pageViewEvent(Ref *pSender, PageView::EventType type) { PageView* pageView = dynamic_cast(pSender); - _displayValueLabel->setString(CCString::createWithFormat("page = %ld", pageView->getCurPageIndex() + 1)->getCString()); + _displayValueLabel->setString(StringUtils::format("page = %ld", pageView->getCurPageIndex() + 1)); } break; @@ -314,7 +314,7 @@ void UIPageViewCustomScrollThreshold::sliderEvent(Ref *pSender, Slider::EventTyp } pageView->setCustomScrollThreshold(percent * 0.01 * pageView->getContentSize().width); - _displayValueLabel->setString(String::createWithFormat("Scroll Threshold: %f", pageView->getCustomScrollThreshold())->getCString()); + _displayValueLabel->setString(StringUtils::format("Scroll Threshold: %f", pageView->getCustomScrollThreshold())); } } @@ -505,7 +505,7 @@ void UIPageViewTouchPropagationTest::pageViewEvent(Ref *pSender, PageView::Event { PageView* pageView = dynamic_cast(pSender); - _displayValueLabel->setString(CCString::createWithFormat("page = %ld", pageView->getCurPageIndex() + 1)->getCString()); + _displayValueLabel->setString(StringUtils::format("page = %ld", pageView->getCurPageIndex() + 1)); } break; @@ -626,7 +626,7 @@ bool UIPageViewDynamicAddAndRemoveTest::init() } pageView->addPage(outerBox); - _displayValueLabel->setString(CCString::createWithFormat("page count = %ld", pageView->getPages().size())->getCString()); + _displayValueLabel->setString(StringUtils::format("page count = %ld", pageView->getPages().size())); }); _uiLayer->addChild(button); @@ -647,7 +647,7 @@ bool UIPageViewDynamicAddAndRemoveTest::init() { CCLOG("There is no page to remove!"); } - _displayValueLabel->setString(CCString::createWithFormat("page count = %ld", pageView->getPages().size())->getCString()); + _displayValueLabel->setString(StringUtils::format("page count = %ld", pageView->getPages().size())); }); _uiLayer->addChild(button2); @@ -661,7 +661,7 @@ bool UIPageViewDynamicAddAndRemoveTest::init() button3->addClickEventListener([=](Ref* sender) { pageView->removeAllPages(); - _displayValueLabel->setString(CCString::createWithFormat("page count = %ld", pageView->getPages().size())->getCString()); + _displayValueLabel->setString(StringUtils::format("page count = %ld", pageView->getPages().size())); }); _uiLayer->addChild(button3); @@ -682,7 +682,7 @@ void UIPageViewDynamicAddAndRemoveTest::pageViewEvent(Ref *pSender, PageView::Ev { PageView* pageView = dynamic_cast(pSender); - _displayValueLabel->setString(CCString::createWithFormat("page = %ld", pageView->getCurPageIndex() + 1)->getCString()); + _displayValueLabel->setString(StringUtils::format("page = %ld", pageView->getCurPageIndex() + 1)); } break; diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIRadioButtonTest/UIRadioButtonTest.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIRadioButtonTest/UIRadioButtonTest.cpp index 00d46b8ea534..0b2c83d5545b 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIRadioButtonTest/UIRadioButtonTest.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIRadioButtonTest/UIRadioButtonTest.cpp @@ -220,17 +220,17 @@ bool UIRadioButtonTwoGroupsTest::init() void UIRadioButtonTwoGroupsTest::onChangedRadioButtonGroup1(RadioButton* radioButton, int index, cocos2d::ui::RadioButtonGroup::EventType type) { CCASSERT(index == _radioButtonGroups[0]->getSelectedButtonIndex(), "The two indexes must match!"); - __String* text = String::createWithFormat("RadioButtonGroup1 : %d", index); - _groupEventLabel->setString(text->getCString()); - addLog(text->getCString()); + auto text = StringUtils::format("RadioButtonGroup1 : %d", index); + _groupEventLabel->setString(text); + addLog(text); } void UIRadioButtonTwoGroupsTest::onChangedRadioButtonGroup2(RadioButton* radioButton, int index, cocos2d::ui::RadioButtonGroup::EventType type) { CCASSERT(index == _radioButtonGroups[1]->getSelectedButtonIndex(), "The two indexes must match!"); - __String* text = String::createWithFormat("RadioButtonGroup2 : %d", index); - _groupEventLabel->setString(text->getCString()); - addLog(text->getCString()); + auto text = StringUtils::format("RadioButtonGroup2 : %d", index); + _groupEventLabel->setString(text); + addLog(text); } void UIRadioButtonTwoGroupsTest::onChangedRadioButtonSelect(RadioButton* radioButton, RadioButton::EventType type) @@ -239,25 +239,25 @@ void UIRadioButtonTwoGroupsTest::onChangedRadioButtonSelect(RadioButton* radioBu { return; } - __String* text = String::createWithFormat("RadioButton %d : ", radioButton->getTag()); + auto text = StringUtils::format("RadioButton %d : ", radioButton->getTag()); switch (type) { case RadioButton::EventType::SELECTED: { - text->append("Selected"); + text.append("Selected"); break; } case RadioButton::EventType::UNSELECTED: { - text->append("Unselected"); + text.append("Unselected"); break; } default: break; } - _buttonEventLabel->setString(text->getCString()); - addLog(text->getCString()); + _buttonEventLabel->setString(text); + addLog(text); } void UIRadioButtonTwoGroupsTest::clearRadioButtonGroup(Ref* sender) @@ -317,9 +317,9 @@ bool UIRadioButtonTabTest::init() float startPosX = widgetSize.width / 2.0f - ((NUMBER_OF_BUTTONS - 1) / 2.0f) * buttonWidth; for(int i = 0; i < NUMBER_OF_BUTTONS; ++i) { - __String* filePathNormal = String::createWithFormat("cocosui/btn_exercise%02d_n.png", i + 1); - __String* filePathSelected = String::createWithFormat("cocosui/btn_exercise%02d_p.png", i + 1); - RadioButton* radioButton = RadioButton::create(filePathNormal->getCString(), filePathSelected->getCString()); + auto filePathNormal = StringUtils::format("cocosui/btn_exercise%02d_n.png", i + 1); + auto filePathSelected = StringUtils::format("cocosui/btn_exercise%02d_p.png", i + 1); + RadioButton* radioButton = RadioButton::create(filePathNormal, filePathSelected); float posX = startPosX + buttonWidth * i; radioButton->setPosition(Vec2(posX, widgetSize.height / 2.0f)); radioButton->setScale(BUTTON_SCALE); diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIScene.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIScene.cpp index 90b86c1d2224..339b993bf70a 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIScene.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIScene.cpp @@ -29,7 +29,7 @@ bool UIScene::init() _widget = dynamic_cast(cocostudio::GUIReader::getInstance()->widgetFromJsonFile("cocosui/UITest/UITest.json")); _uiLayer->addChild(_widget); - Size screenSize = CCDirector::getInstance()->getWinSize(); + Size screenSize = Director::getInstance()->getWinSize(); Size rootSize = _widget->getContentSize(); _uiLayer->setPosition(Vec2((screenSize.width - rootSize.width) / 2, (screenSize.height - rootSize.height) / 2)); diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIScene_Editor.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIScene_Editor.cpp index 300650cb2ae9..3aafb8d7588e 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIScene_Editor.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIScene_Editor.cpp @@ -53,7 +53,7 @@ void UIScene_Editor::configureGUIScene() { if (_touchGroup) { - Size screenSize = CCDirector::getInstance()->getWinSize(); + Size screenSize = Director::getInstance()->getWinSize(); Size rootSize = _layout->getContentSize(); _touchGroup->setPosition(Vec2((screenSize.width - rootSize.width) / 2, (screenSize.height - rootSize.height) / 2)); diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest_Editor.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest_Editor.cpp index 37c7ba913e0e..bf9780efe671 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest_Editor.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UIScrollViewTest/UIScrollViewTest_Editor.cpp @@ -125,7 +125,7 @@ bool UIScrollViewTest_ScrollToPercentBothDirection_Editor::init() { _layout = static_cast(cocostudio::GUIReader::getInstance()->widgetFromBinaryFile("cocosui/UITest/UITest.csb")); _touchGroup->addChild(_layout); - Size screenSize = CCDirector::getInstance()->getWinSize(); + Size screenSize = Director::getInstance()->getWinSize(); Size rootSize = _layout->getContentSize(); _touchGroup->setPosition(Vec2((screenSize.width - rootSize.width) / 2, (screenSize.height - rootSize.height) / 2)); @@ -154,7 +154,7 @@ bool UIScrollViewTest_ScrollToPercentBothDirection_Bounce_Editor::init() { _layout = static_cast(cocostudio::GUIReader::getInstance()->widgetFromBinaryFile("cocosui/UITest/UITest.csb")); _touchGroup->addChild(_layout); - Size screenSize = CCDirector::getInstance()->getWinSize(); + Size screenSize = Director::getInstance()->getWinSize(); Size rootSize = _layout->getContentSize(); _touchGroup->setPosition(Vec2((screenSize.width - rootSize.width) / 2, (screenSize.height - rootSize.height) / 2)); diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp index 3dd0e3ff9312..608370450263 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISliderTest/UISliderTest.cpp @@ -349,6 +349,7 @@ bool UISliderNewEventCallbackTest::init() slider->addEventListener([=](Ref* widget,Slider::EventType type) { Slider* slider = (Slider*)widget; + CC_UNUSED_PARAM(slider); if(type == Slider::EventType::ON_SLIDEBALL_DOWN) { CCLOG("slider button pressed!"); diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISliderTest/UISliderTest_Editor.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISliderTest/UISliderTest_Editor.cpp index ac2ad352b95f..83e5c2cff257 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISliderTest/UISliderTest_Editor.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UISliderTest/UISliderTest_Editor.cpp @@ -64,7 +64,7 @@ void UISliderTest_Editor::sliderEvent(Ref *pSender, Slider::EventType type) case Slider::EventType::ON_PERCENTAGE_CHANGED: { Slider* slider = static_cast(pSender); - _displayValueLabel->setString(CCString::createWithFormat("percent %d", slider->getPercent())->getCString()); + _displayValueLabel->setString(StringUtils::format("percent %d", slider->getPercent())); } break; diff --git a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp index f8f8476124a7..f05513dfa09e 100644 --- a/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp +++ b/tests/cpp-tests/Classes/UITest/CocoStudioGUITest/UITextFieldTest/UITextFieldTest.cpp @@ -62,28 +62,28 @@ void UITextFieldTest::textFieldEvent(Ref *pSender, TextField::EventType type) case TextField::EventType::ATTACH_WITH_IME: { TextField* textField = dynamic_cast(pSender); - Size screenSize = CCDirector::getInstance()->getWinSize(); - textField->runAction(CCMoveTo::create(0.225f, + Size screenSize = Director::getInstance()->getWinSize(); + textField->runAction(MoveTo::create(0.225f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f + textField->getContentSize().height / 2.0f))); - _displayValueLabel->setString(String::createWithFormat("attach with IME")->getCString()); + _displayValueLabel->setString(StringUtils::format("attach with IME")); } break; case TextField::EventType::DETACH_WITH_IME: { TextField* textField = dynamic_cast(pSender); - Size screenSize = CCDirector::getInstance()->getWinSize(); - textField->runAction(CCMoveTo::create(0.175f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f))); - _displayValueLabel->setString(String::createWithFormat("detach with IME")->getCString()); + Size screenSize = Director::getInstance()->getWinSize(); + textField->runAction(MoveTo::create(0.175f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f))); + _displayValueLabel->setString(StringUtils::format("detach with IME")); } break; case TextField::EventType::INSERT_TEXT: - _displayValueLabel->setString(String::createWithFormat("insert words")->getCString()); + _displayValueLabel->setString(StringUtils::format("insert words")); break; case TextField::EventType::DELETE_BACKWARD: - _displayValueLabel->setString(String::createWithFormat("delete word")->getCString()); + _displayValueLabel->setString(StringUtils::format("delete word")); break; default: @@ -106,7 +106,7 @@ bool UITextFieldTest_MaxLength::init() { if (UIScene::init()) { - Size screenSize = CCDirector::getInstance()->getWinSize(); + Size screenSize = Director::getInstance()->getWinSize(); // Add a label in which the textfield events will be displayed _displayValueLabel = Text::create("No Event","fonts/Marker Felt.ttf",32); @@ -140,33 +140,33 @@ void UITextFieldTest_MaxLength::textFieldEvent(Ref *pSender, TextField::EventTyp case TextField::EventType::ATTACH_WITH_IME: { TextField* textField = dynamic_cast(pSender); - Size screenSize = CCDirector::getInstance()->getWinSize(); - textField->runAction(CCMoveTo::create(0.225f, + Size screenSize = Director::getInstance()->getWinSize(); + textField->runAction(MoveTo::create(0.225f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f + textField->getContentSize().height / 2.0f))); - _displayValueLabel->setString(String::createWithFormat("attach with IME max length %d", textField->getMaxLength())->getCString()); + _displayValueLabel->setString(StringUtils::format("attach with IME max length %d", textField->getMaxLength())); } break; case TextField::EventType::DETACH_WITH_IME: { TextField* textField = dynamic_cast(pSender); - Size screenSize = CCDirector::getInstance()->getWinSize(); - textField->runAction(CCMoveTo::create(0.175f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f))); - _displayValueLabel->setString(String::createWithFormat("detach with IME max length %d", textField->getMaxLength())->getCString()); + Size screenSize = Director::getInstance()->getWinSize(); + textField->runAction(MoveTo::create(0.175f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f))); + _displayValueLabel->setString(StringUtils::format("detach with IME max length %d", textField->getMaxLength())); } break; case TextField::EventType::INSERT_TEXT: { TextField* textField = dynamic_cast(pSender); - _displayValueLabel->setString(String::createWithFormat("insert words max length %d", textField->getMaxLength())->getCString()); + _displayValueLabel->setString(StringUtils::format("insert words max length %d", textField->getMaxLength())); } break; case TextField::EventType::DELETE_BACKWARD: { TextField* textField = dynamic_cast(pSender); - _displayValueLabel->setString(String::createWithFormat("delete word max length %d", textField->getMaxLength())->getCString()); + _displayValueLabel->setString(StringUtils::format("delete word max length %d", textField->getMaxLength())); } break; @@ -190,7 +190,7 @@ bool UITextFieldTest_Password::init() { if (UIScene::init()) { - Size screenSize = CCDirector::getInstance()->getWinSize(); + Size screenSize = Director::getInstance()->getWinSize(); // Add a label in which the textfield events will be displayed _displayValueLabel = Text::create("No Event","fonts/Marker Felt.ttf",32); @@ -224,28 +224,28 @@ void UITextFieldTest_Password::textFieldEvent(Ref *pSender, TextField::EventType case TextField::EventType::ATTACH_WITH_IME: { TextField* textField = dynamic_cast(pSender); - Size screenSize = CCDirector::getInstance()->getWinSize(); - textField->runAction(CCMoveTo::create(0.225f, + Size screenSize = Director::getInstance()->getWinSize(); + textField->runAction(MoveTo::create(0.225f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f + textField->getContentSize().height / 2.0f))); - _displayValueLabel->setString(String::createWithFormat("attach with IME password")->getCString()); + _displayValueLabel->setString(StringUtils::format("attach with IME password")); } break; case TextField::EventType::DETACH_WITH_IME: { TextField* textField = dynamic_cast(pSender); - Size screenSize = CCDirector::getInstance()->getWinSize(); - textField->runAction(CCMoveTo::create(0.175f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f))); - _displayValueLabel->setString(String::createWithFormat("detach with IME password")->getCString()); + Size screenSize = Director::getInstance()->getWinSize(); + textField->runAction(MoveTo::create(0.175f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f))); + _displayValueLabel->setString(StringUtils::format("detach with IME password")); } break; case TextField::EventType::INSERT_TEXT: - _displayValueLabel->setString(String::createWithFormat("insert words password")->getCString()); + _displayValueLabel->setString(StringUtils::format("insert words password")); break; case TextField::EventType::DELETE_BACKWARD: - _displayValueLabel->setString(String::createWithFormat("delete word password")->getCString()); + _displayValueLabel->setString(StringUtils::format("delete word password")); break; default: @@ -308,12 +308,12 @@ void UITextFieldTest_LineWrap::textFieldEvent(Ref *pSender, TextField::EventType { TextField* textField = dynamic_cast(pSender); Size widgetSize = _widget->getContentSize(); - textField->runAction(CCMoveTo::create(0.225f, + textField->runAction(MoveTo::create(0.225f, Vec2(widgetSize.width / 2.0f, widgetSize.height / 2.0f + 30))); textField->setTextHorizontalAlignment(TextHAlignment::LEFT); textField->setTextVerticalAlignment(TextVAlignment::TOP); - _displayValueLabel->setString(CCString::createWithFormat("attach with IME")->getCString()); + _displayValueLabel->setString(StringUtils::format("attach with IME")); } break; @@ -321,20 +321,20 @@ void UITextFieldTest_LineWrap::textFieldEvent(Ref *pSender, TextField::EventType { TextField* textField = dynamic_cast(pSender); Size widgetSize = _widget->getContentSize(); - textField->runAction(CCMoveTo::create(0.175f, Vec2(widgetSize.width / 2.0f, widgetSize.height / 2.0f))); + textField->runAction(MoveTo::create(0.175f, Vec2(widgetSize.width / 2.0f, widgetSize.height / 2.0f))); textField->setTextHorizontalAlignment(TextHAlignment::CENTER); textField->setTextVerticalAlignment(TextVAlignment::CENTER); - _displayValueLabel->setString(CCString::createWithFormat("detach with IME")->getCString()); + _displayValueLabel->setString(StringUtils::format("detach with IME")); } break; case TextField::EventType::INSERT_TEXT: - _displayValueLabel->setString(CCString::createWithFormat("insert words")->getCString()); + _displayValueLabel->setString(StringUtils::format("insert words")); break; case TextField::EventType::DELETE_BACKWARD: - _displayValueLabel->setString(CCString::createWithFormat("delete word")->getCString()); + _displayValueLabel->setString(StringUtils::format("delete word")); break; default: @@ -390,28 +390,28 @@ void UITextFieldTest_TrueTypeFont::textFieldEvent(Ref *pSender, TextField::Event case TextField::EventType::ATTACH_WITH_IME: { TextField* textField = dynamic_cast(pSender); - Size screenSize = CCDirector::getInstance()->getWinSize(); - textField->runAction(CCMoveTo::create(0.225f, + Size screenSize = Director::getInstance()->getWinSize(); + textField->runAction(MoveTo::create(0.225f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f + textField->getContentSize().height / 2.0f))); - _displayValueLabel->setString(String::createWithFormat("attach with IME")->getCString()); + _displayValueLabel->setString(StringUtils::format("attach with IME")); } break; case TextField::EventType::DETACH_WITH_IME: { TextField* textField = dynamic_cast(pSender); - Size screenSize = CCDirector::getInstance()->getWinSize(); - textField->runAction(CCMoveTo::create(0.175f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f))); - _displayValueLabel->setString(String::createWithFormat("detach with IME")->getCString()); + Size screenSize = Director::getInstance()->getWinSize(); + textField->runAction(MoveTo::create(0.175f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f))); + _displayValueLabel->setString(StringUtils::format("detach with IME")); } break; case TextField::EventType::INSERT_TEXT: - _displayValueLabel->setString(String::createWithFormat("insert words")->getCString()); + _displayValueLabel->setString(StringUtils::format("insert words")); break; case TextField::EventType::DELETE_BACKWARD: - _displayValueLabel->setString(String::createWithFormat("delete word")->getCString()); + _displayValueLabel->setString(StringUtils::format("delete word")); break; default: @@ -467,31 +467,31 @@ void UITextFieldTest_PlaceHolderColor::textFieldEvent(Ref *pSender, TextField::E case TextField::EventType::ATTACH_WITH_IME: { TextField* textField = dynamic_cast(pSender); - Size screenSize = CCDirector::getInstance()->getWinSize(); - textField->runAction(CCMoveTo::create(0.225f, + Size screenSize = Director::getInstance()->getWinSize(); + textField->runAction(MoveTo::create(0.225f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f + textField->getContentSize().height / 2.0f))); - _displayValueLabel->setString(String::createWithFormat("attach with IME")->getCString()); + _displayValueLabel->setString(StringUtils::format("attach with IME")); } break; case TextField::EventType::DETACH_WITH_IME: { TextField* textField = dynamic_cast(pSender); - Size screenSize = CCDirector::getInstance()->getWinSize(); - textField->runAction(CCMoveTo::create(0.175f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f))); - _displayValueLabel->setString(String::createWithFormat("detach with IME")->getCString()); + Size screenSize = Director::getInstance()->getWinSize(); + textField->runAction(MoveTo::create(0.175f, Vec2(screenSize.width / 2.0f, screenSize.height / 2.0f))); + _displayValueLabel->setString(StringUtils::format("detach with IME")); } break; case TextField::EventType::INSERT_TEXT: { - _displayValueLabel->setString(String::createWithFormat("insert words")->getCString()); + _displayValueLabel->setString(StringUtils::format("insert words")); CCLOG("%f, %f", dynamic_cast(pSender)->getContentSize().width, dynamic_cast(pSender)->getContentSize().height); } break; case TextField::EventType::DELETE_BACKWARD: - _displayValueLabel->setString(String::createWithFormat("delete word")->getCString()); + _displayValueLabel->setString(StringUtils::format("delete word")); break; default: diff --git a/tests/cpp-tests/Classes/UnitTest/UnitTest.cpp b/tests/cpp-tests/Classes/UnitTest/UnitTest.cpp index 4bf497f36952..33d11f9507fa 100644 --- a/tests/cpp-tests/Classes/UnitTest/UnitTest.cpp +++ b/tests/cpp-tests/Classes/UnitTest/UnitTest.cpp @@ -60,51 +60,51 @@ void TemplateVectorTest::onEnter() UnitTestDemo::onEnter(); Vector vec; - CCASSERT(vec.empty(), ""); - CCASSERT(vec.capacity() == 0, ""); - CCASSERT(vec.size() == 0, ""); - CCASSERT(vec.max_size() > 0, ""); + CCASSERT(vec.empty(), "vec should be empty."); + CCASSERT(vec.capacity() == 0, "vec.capacity should be 0."); + CCASSERT(vec.size() == 0, "vec.size should be 0."); + CCASSERT(vec.max_size() > 0, "vec.max_size should > 0."); auto node1 = Node::create(); node1->setTag(1); vec.pushBack(node1); - CCASSERT(node1->getReferenceCount() == 2, ""); + CCASSERT(node1->getReferenceCount() == 2, "node1->getReferenceCount should be 2."); auto node2 = Node::create(); node2->setTag(2); vec.pushBack(node2); - CCASSERT(vec.getIndex(node1) == 0, ""); - CCASSERT(vec.getIndex(node2) == 1, ""); + CCASSERT(vec.getIndex(node1) == 0, "node1 should at index 0 in vec."); + CCASSERT(vec.getIndex(node2) == 1, "node2 should at index 1 in vec."); auto node3 = Node::create(); node3->setTag(3); vec.insert(1, node3); - CCASSERT(vec.at(0)->getTag() == 1, ""); - CCASSERT(vec.at(1)->getTag() == 3, ""); - CCASSERT(vec.at(2)->getTag() == 2, ""); + CCASSERT(vec.at(0)->getTag() == 1, "The element at 0, tag should be 1."); + CCASSERT(vec.at(1)->getTag() == 3, "The element at 1, tag should be 3."); + CCASSERT(vec.at(2)->getTag() == 2, "The element at 2, tag should be 2."); // Test copy constructor Vector vec2(vec); - CCASSERT(vec2.size() == vec.size(), ""); + CCASSERT(vec2.size() == vec.size(), "vec2 and vec should have equal size."); ssize_t size = vec.size(); for (ssize_t i = 0; i < size; ++i) { - CCASSERT(vec2.at(i) == vec.at(i), ""); - CCASSERT(vec.at(i)->getReferenceCount() == 3, ""); - CCASSERT(vec2.at(i)->getReferenceCount() == 3, ""); + CCASSERT(vec2.at(i) == vec.at(i), "The element at the same index in vec2 and vec2 should be equal."); + CCASSERT(vec.at(i)->getReferenceCount() == 3, "The reference cound of element in vec is 3. "); + CCASSERT(vec2.at(i)->getReferenceCount() == 3, "The reference cound of element in vec2 is 3. "); } // Test copy assignment operator Vector vec3; vec3 = vec2; - CCASSERT(vec3.size() == vec2.size(), ""); + CCASSERT(vec3.size() == vec2.size(), "vec3 and vec2 should have equal size."); size = vec3.size(); for (ssize_t i = 0; i < size; ++i) { - CCASSERT(vec3.at(i) == vec2.at(i), ""); - CCASSERT(vec3.at(i)->getReferenceCount() == 4, ""); - CCASSERT(vec2.at(i)->getReferenceCount() == 4, ""); - CCASSERT(vec.at(i)->getReferenceCount() == 4, ""); + CCASSERT(vec3.at(i) == vec2.at(i), "The element at the same index in vec3 and vec2 should be equal."); + CCASSERT(vec3.at(i)->getReferenceCount() == 4, "The reference cound of element in vec3 is 4. "); + CCASSERT(vec2.at(i)->getReferenceCount() == 4, "The reference cound of element in vec2 is 4. "); + CCASSERT(vec.at(i)->getReferenceCount() == 4, "The reference cound of element in vec is 4. "); } // Test move constructor @@ -130,75 +130,75 @@ void TemplateVectorTest::onEnter() for (const auto& child : vec4) { CC_UNUSED_PARAM(child); - CCASSERT(child->getReferenceCount() == 2, ""); + CCASSERT(child->getReferenceCount() == 2, "child's reference count should be 2."); } // Test init Vector with capacity Vector vec5(10); - CCASSERT(vec5.capacity() == 10, ""); + CCASSERT(vec5.capacity() == 10, "vec5's capacity should be 10."); vec5.reserve(20); - CCASSERT(vec5.capacity() == 20, ""); + CCASSERT(vec5.capacity() == 20, "vec5's capacity should be 20."); - CCASSERT(vec5.size() == 0, ""); - CCASSERT(vec5.empty(), ""); + CCASSERT(vec5.size() == 0, "vec5's size should be 0."); + CCASSERT(vec5.empty(), "vec5 is empty now."); auto toRemovedNode = Node::create(); vec5.pushBack(toRemovedNode); - CCASSERT(toRemovedNode->getReferenceCount() == 2, ""); + CCASSERT(toRemovedNode->getReferenceCount() == 2, "toRemovedNode's reference count is 2."); // Test move assignment operator vec5 = createVector(); - CCASSERT(toRemovedNode->getReferenceCount() == 1, ""); + CCASSERT(toRemovedNode->getReferenceCount() == 1, "toRemovedNode's reference count is 1."); CCASSERT(vec5.size() == 20, "size should be 20"); for (const auto& child : vec5) { CC_UNUSED_PARAM(child); - CCASSERT(child->getReferenceCount() == 2, ""); + CCASSERT(child->getReferenceCount() == 2, "child's reference count is 2."); } // Test Vector::find - CCASSERT(vec.find(node3) == (vec.begin() + 1), ""); - CCASSERT(std::find(std::begin(vec), std::end(vec), node2) == (vec.begin() + 2), ""); + CCASSERT(vec.find(node3) == (vec.begin() + 1), "node3 is the 2nd element in vec."); + CCASSERT(std::find(std::begin(vec), std::end(vec), node2) == (vec.begin() + 2), "node2 is the 3rd element in vec."); - CCASSERT(vec.front()->getTag() == 1, ""); - CCASSERT(vec.back()->getTag() == 2, ""); + CCASSERT(vec.front()->getTag() == 1, "vec's front element's tag is 1."); + CCASSERT(vec.back()->getTag() == 2, "vec's back element's tag is 2."); - CCASSERT(vec.getRandomObject(), ""); - CCASSERT(!vec.contains(Node::create()), ""); - CCASSERT(vec.contains(node1), ""); - CCASSERT(vec.contains(node2), ""); - CCASSERT(vec.contains(node3), ""); - CCASSERT(vec.equals(vec2), ""); - CCASSERT(vec.equals(vec3), ""); + CCASSERT(vec.getRandomObject(), "vec getRandomObject should return true."); + CCASSERT(!vec.contains(Node::create()), "vec doesn't contain a empty Node instance."); + CCASSERT(vec.contains(node1), "vec contains node1."); + CCASSERT(vec.contains(node2), "vec contains node2."); + CCASSERT(vec.contains(node3), "vec contains node3."); + CCASSERT(vec.equals(vec2), "vec is equal to vec2."); + CCASSERT(vec.equals(vec3), "vec is equal to vec3."); // Insert vec5.insert(2, node1); - CCASSERT(vec5.at(2)->getTag() == 1, ""); - CCASSERT(vec5.size() == 21, ""); + CCASSERT(vec5.at(2)->getTag() == 1, "vec5's 3rd element's tag is 1."); + CCASSERT(vec5.size() == 21, "vec5's size is 21."); vec5.back()->setTag(100); vec5.popBack(); - CCASSERT(vec5.size() == 20, ""); - CCASSERT(vec5.back()->getTag() != 100, ""); + CCASSERT(vec5.size() == 20, "vec5's size is 20."); + CCASSERT(vec5.back()->getTag() != 100, "the back element of vec5's tag is 100."); // Erase and clear Vector vec6 = createVector(); Vector vec7 = vec6; // Copy for check - CCASSERT(vec6.size() == 20, ""); + CCASSERT(vec6.size() == 20, "vec6's size is 20."); vec6.erase(vec6.begin() + 1); // - CCASSERT(vec6.size() == 19, ""); - CCASSERT((*(vec6.begin() + 1))->getTag() == 1002, ""); + CCASSERT(vec6.size() == 19, "vec6's size is 19."); + CCASSERT((*(vec6.begin() + 1))->getTag() == 1002, "The 2rd element in vec6's tag is 1002."); vec6.erase(vec6.begin() + 2, vec6.begin() + 10); - CCASSERT(vec6.size() == 11, ""); - CCASSERT(vec6.at(0)->getTag() == 1000, ""); - CCASSERT(vec6.at(1)->getTag() == 1002, ""); - CCASSERT(vec6.at(2)->getTag() == 1011, ""); - CCASSERT(vec6.at(3)->getTag() == 1012, ""); + CCASSERT(vec6.size() == 11, "vec6's size is 11."); + CCASSERT(vec6.at(0)->getTag() == 1000, "vec6's first element's tag is 1000."); + CCASSERT(vec6.at(1)->getTag() == 1002, "vec6's second element's tag is 1002."); + CCASSERT(vec6.at(2)->getTag() == 1011, "vec6's third element's tag is 1011."); + CCASSERT(vec6.at(3)->getTag() == 1012, "vec6's fouth element's tag is 1012."); vec6.erase(3); - CCASSERT(vec6.at(3)->getTag() == 1013, ""); + CCASSERT(vec6.at(3)->getTag() == 1013, "vec6's 4th elemetn's tag is 1013."); vec6.eraseObject(vec6.at(2)); - CCASSERT(vec6.at(2)->getTag() == 1013, ""); + CCASSERT(vec6.at(2)->getTag() == 1013, "vec6's 3rd element's tag is 1013."); vec6.clear(); auto objA = Node::create(); // retain count is 1 @@ -220,9 +220,9 @@ void TemplateVectorTest::onEnter() for (auto obj : array1) { array2.eraseObject(obj); } - CCASSERT(objA->getReferenceCount() == 4, ""); + CCASSERT(objA->getReferenceCount() == 4, "objA's reference count is 4."); } - CCASSERT(objA->getReferenceCount() == 1, ""); + CCASSERT(objA->getReferenceCount() == 1, "objA's reference count is 1."); { Vector array1; @@ -230,24 +230,24 @@ void TemplateVectorTest::onEnter() array1.pushBack(objA); // retain count is 2 array1.pushBack(objA); // retain count is 3 array1.pushBack(objA); // retain count is 4 - CCASSERT(objA->getReferenceCount() == 4, ""); + CCASSERT(objA->getReferenceCount() == 4, "objA's reference count is 4."); array1.eraseObject(objA, true); // Remove all occurrences in the Vector. - CCASSERT(objA->getReferenceCount() == 1, ""); + CCASSERT(objA->getReferenceCount() == 1, "objA's reference count is 1."); array1.pushBack(objA); // retain count is 2 array1.pushBack(objA); // retain count is 3 array1.pushBack(objA); // retain count is 4 array1.eraseObject(objA, false); - CCASSERT(objA->getReferenceCount() == 3, ""); // Only remove the first occurrence in the Vector. + CCASSERT(objA->getReferenceCount() == 3, "objA's reference count is 3."); // Only remove the first occurrence in the Vector. } // Check the retain count in vec7 - CCASSERT(vec7.size() == 20, ""); + CCASSERT(vec7.size() == 20, "vec7's size is 20."); for (const auto& child : vec7) { CC_UNUSED_PARAM(child); - CCASSERT(child->getReferenceCount() == 2, ""); + CCASSERT(child->getReferenceCount() == 2, "child's reference count is 2."); } // Sort @@ -258,32 +258,32 @@ void TemplateVectorTest::onEnter() for (int i = 0; i < 20; ++i) { - CCASSERT(vecForSort.at(i)->getTag() - 1000 == (19 - i), ""); + CCASSERT(vecForSort.at(i)->getTag() - 1000 == (19 - i), "vecForSort's element's tag is invalid."); } // Reverse vecForSort.reverse(); for (int i = 0; i < 20; ++i) { - CCASSERT(vecForSort.at(i)->getTag() - 1000 == i, ""); + CCASSERT(vecForSort.at(i)->getTag() - 1000 == i, "vecForSort's element's tag is invalid."); } // Swap Vector vecForSwap = createVector(); vecForSwap.swap(2, 4); - CCASSERT(vecForSwap.at(2)->getTag() == 1004, ""); - CCASSERT(vecForSwap.at(4)->getTag() == 1002, ""); + CCASSERT(vecForSwap.at(2)->getTag() == 1004, "vecForSwap's 3nd element's tag is 1004."); + CCASSERT(vecForSwap.at(4)->getTag() == 1002, "vecForSwap's 5rd element's tag is 1002."); vecForSwap.swap(vecForSwap.at(2), vecForSwap.at(4)); - CCASSERT(vecForSwap.at(2)->getTag() == 1002, ""); - CCASSERT(vecForSwap.at(4)->getTag() == 1004, ""); + CCASSERT(vecForSwap.at(2)->getTag() == 1002, "vecForSwap's 3rd element's tag is 1002."); + CCASSERT(vecForSwap.at(4)->getTag() == 1004, "vecForSwap's 5rd element's tag is 1004."); // shrinkToFit Vector vecForShrink = createVector(); vecForShrink.reserve(100); - CCASSERT(vecForShrink.capacity() == 100, ""); + CCASSERT(vecForShrink.capacity() == 100, "vecForShrink's capacity is 100."); vecForShrink.pushBack(Node::create()); vecForShrink.shrinkToFit(); - CCASSERT(vecForShrink.capacity() == 21, ""); + CCASSERT(vecForShrink.capacity() == 21, "vecForShrink's capacity is 21."); // get random object // Set the seed by time @@ -299,21 +299,21 @@ void TemplateVectorTest::onEnter() // Self assignment Vector vecSelfAssign = createVector(); vecSelfAssign = vecSelfAssign; - CCASSERT(vecSelfAssign.size() == 20, ""); + CCASSERT(vecSelfAssign.size() == 20, "vecSelfAssign's size is 20."); for (const auto& child : vecSelfAssign) { CC_UNUSED_PARAM(child); - CCASSERT(child->getReferenceCount() == 2, ""); + CCASSERT(child->getReferenceCount() == 2, "child's reference count is 2."); } vecSelfAssign = std::move(vecSelfAssign); - CCASSERT(vecSelfAssign.size() == 20, ""); + CCASSERT(vecSelfAssign.size() == 20, "vecSelfAssign's size is 20."); for (const auto& child : vecSelfAssign) { CC_UNUSED_PARAM(child); - CCASSERT(child->getReferenceCount() == 2, ""); + CCASSERT(child->getReferenceCount() == 2, "child's reference count is 2."); } // const at @@ -352,17 +352,17 @@ void TemplateMapTest::onEnter() // Default constructor Map map1; - CCASSERT(map1.empty(), ""); - CCASSERT(map1.size() == 0, ""); - CCASSERT(map1.keys().empty(), ""); - CCASSERT(map1.keys(Node::create()).empty(), ""); + CCASSERT(map1.empty(), "map1 is empty."); + CCASSERT(map1.size() == 0, "map1's size is 0."); + CCASSERT(map1.keys().empty(), "map1's keys are empty."); + CCASSERT(map1.keys(Node::create()).empty(), "map1's keys don't contain a empty Node."); // Move constructor Map map2 = createMap(); for (const auto& e : map2) { CC_UNUSED_PARAM(e); - CCASSERT(e.second->getReferenceCount() == 2, ""); + CCASSERT(e.second->getReferenceCount() == 2, "e.second element's reference count is 2."); } // Copy constructor @@ -370,7 +370,7 @@ void TemplateMapTest::onEnter() for (const auto& e : map3) { CC_UNUSED_PARAM(e); - CCASSERT(e.second->getReferenceCount() == 3, ""); + CCASSERT(e.second->getReferenceCount() == 3, "e.second's reference count is 3."); } // Move assignment operator @@ -378,11 +378,11 @@ void TemplateMapTest::onEnter() auto unusedNode = Node::create(); map4.insert("unused",unusedNode); map4 = createMap(); - CCASSERT(unusedNode->getReferenceCount() == 1, ""); + CCASSERT(unusedNode->getReferenceCount() == 1, "unusedNode's reference count is 1."); for (const auto& e : map4) { CC_UNUSED_PARAM(e); - CCASSERT(e.second->getReferenceCount() == 2, ""); + CCASSERT(e.second->getReferenceCount() == 2, "e.second's reference count is 2."); } // Copy assignment operator @@ -391,16 +391,16 @@ void TemplateMapTest::onEnter() for (const auto& e : map5) { CC_UNUSED_PARAM(e); - CCASSERT(e.second->getReferenceCount() == 3, ""); + CCASSERT(e.second->getReferenceCount() == 3, "e.second's reference count is 3."); } // Check size - CCASSERT(map4.size() == map5.size(), ""); + CCASSERT(map4.size() == map5.size(), "map4's size is equal to map5.size."); for (const auto& e : map4) { CC_UNUSED_PARAM(e); - CCASSERT(e.second == map5.find(e.first)->second, ""); + CCASSERT(e.second == map5.find(e.first)->second, "e.second can't be found in map5."); } // bucket_count, bucket_size(n), bucket @@ -444,7 +444,7 @@ void TemplateMapTest::onEnter() // find auto nodeToFind = map4.find("10"); CC_UNUSED_PARAM(nodeToFind); - CCASSERT(nodeToFind->second->getTag() == 1010, ""); + CCASSERT(nodeToFind->second->getTag() == 1010, "nodeToFind's tag value is 1010."); // insert Map map6; @@ -458,29 +458,29 @@ void TemplateMapTest::onEnter() map6.insert("insert02", node2); map6.insert("insert03", node3); - CCASSERT(node1->getReferenceCount() == 2, ""); - CCASSERT(node2->getReferenceCount() == 2, ""); - CCASSERT(node3->getReferenceCount() == 2, ""); - CCASSERT(map6.at("insert01") == node1, ""); - CCASSERT(map6.at("insert02") == node2, ""); - CCASSERT(map6.at("insert03") == node3, ""); + CCASSERT(node1->getReferenceCount() == 2, "node1's reference count is 2."); + CCASSERT(node2->getReferenceCount() == 2, "node2's reference count is 2."); + CCASSERT(node3->getReferenceCount() == 2, "node3's reference count is 2."); + CCASSERT(map6.at("insert01") == node1, "The element at insert01 is equal to node1."); + CCASSERT(map6.at("insert02") == node2, "The element at insert02 is equal to node2."); + CCASSERT(map6.at("insert03") == node3, "The element at insert03 is equal to node3."); // erase Map mapForErase = createMap(); mapForErase.erase(mapForErase.find("9")); - CCASSERT(mapForErase.find("9") == mapForErase.end(), ""); - CCASSERT(mapForErase.size() == 19, ""); + CCASSERT(mapForErase.find("9") == mapForErase.end(), "9 is already removed."); + CCASSERT(mapForErase.size() == 19, "mapForErase's size is 19."); mapForErase.erase("7"); - CCASSERT(mapForErase.find("7") == mapForErase.end(), ""); - CCASSERT(mapForErase.size() == 18, ""); + CCASSERT(mapForErase.find("7") == mapForErase.end(), "7 is already removed."); + CCASSERT(mapForErase.size() == 18, "mapForErase's size is 18."); std::vector itemsToRemove; itemsToRemove.push_back("2"); itemsToRemove.push_back("3"); itemsToRemove.push_back("4"); mapForErase.erase(itemsToRemove); - CCASSERT(mapForErase.size() == 15, ""); + CCASSERT(mapForErase.size() == 15, "mapForErase's size is 15."); // clear Map mapForClear = createMap(); @@ -490,7 +490,7 @@ void TemplateMapTest::onEnter() for (const auto& e : mapForClearCopy) { CC_UNUSED_PARAM(e); - CCASSERT(e.second->getReferenceCount() == 2, ""); + CCASSERT(e.second->getReferenceCount() == 2, "e.second's reference count is 2."); } // get random object @@ -507,21 +507,21 @@ void TemplateMapTest::onEnter() // Self assignment Map mapForSelfAssign = createMap(); mapForSelfAssign = mapForSelfAssign; - CCASSERT(mapForSelfAssign.size() == 20, ""); + CCASSERT(mapForSelfAssign.size() == 20, "mapForSelfAssign's size is 20."); for (const auto& e : mapForSelfAssign) { CC_UNUSED_PARAM(e); - CCASSERT(e.second->getReferenceCount() == 2, ""); + CCASSERT(e.second->getReferenceCount() == 2, "e.second's reference count is 2."); } mapForSelfAssign = std::move(mapForSelfAssign); - CCASSERT(mapForSelfAssign.size() == 20, ""); + CCASSERT(mapForSelfAssign.size() == 20, "mapForSelfAssign's size is 20."); for (const auto& e : mapForSelfAssign) { CC_UNUSED_PARAM(e); - CCASSERT(e.second->getReferenceCount() == 2, ""); + CCASSERT(e.second->getReferenceCount() == 2, "e.second's reference's count is 2."); } } @@ -543,37 +543,37 @@ void ValueTest::onEnter() UnitTestDemo::onEnter(); Value v1; - CCASSERT(v1.getType() == Value::Type::NONE, ""); - CCASSERT(v1.isNull(), ""); + CCASSERT(v1.getType() == Value::Type::NONE, "v1's value type should be VALUE::Type::NONE."); + CCASSERT(v1.isNull(), "v1 is null."); Value v2(100); - CCASSERT(v2.getType() == Value::Type::INTEGER, ""); - CCASSERT(!v2.isNull(), ""); + CCASSERT(v2.getType() == Value::Type::INTEGER, "v2's value type should be VALUE::Type::INTEGER."); + CCASSERT(!v2.isNull(), "v2 is not null."); Value v3(101.4f); - CCASSERT(v3.getType() == Value::Type::FLOAT, ""); - CCASSERT(!v3.isNull(), ""); + CCASSERT(v3.getType() == Value::Type::FLOAT, "v3's value type should be VALUE::Type::FLOAT."); + CCASSERT(!v3.isNull(), "v3 is not null."); Value v4(106.1); - CCASSERT(v4.getType() == Value::Type::DOUBLE, ""); - CCASSERT(!v4.isNull(), ""); + CCASSERT(v4.getType() == Value::Type::DOUBLE, "v4's value type should be VALUE::Type::DOUBLE."); + CCASSERT(!v4.isNull(), "v4 is not null."); unsigned char byte = 50; Value v5(byte); - CCASSERT(v5.getType() == Value::Type::BYTE, ""); - CCASSERT(!v5.isNull(), ""); + CCASSERT(v5.getType() == Value::Type::BYTE, "v5's value type should be Value::Type::BTYE."); + CCASSERT(!v5.isNull(), "v5 is not null."); Value v6(true); - CCASSERT(v6.getType() == Value::Type::BOOLEAN, ""); - CCASSERT(!v6.isNull(), ""); + CCASSERT(v6.getType() == Value::Type::BOOLEAN, "v6's value type is Value::Type::BOOLEAN."); + CCASSERT(!v6.isNull(), "v6 is not null."); Value v7("string"); - CCASSERT(v7.getType() == Value::Type::STRING, ""); - CCASSERT(!v7.isNull(), ""); + CCASSERT(v7.getType() == Value::Type::STRING, "v7's value type is Value::type::STRING."); + CCASSERT(!v7.isNull(), "v7 is not null."); Value v8(std::string("string2")); - CCASSERT(v8.getType() == Value::Type::STRING, ""); - CCASSERT(!v8.isNull(), ""); + CCASSERT(v8.getType() == Value::Type::STRING, "v8's value type is Value::Type::STRING."); + CCASSERT(!v8.isNull(), "v8 is not null."); auto createValueVector = [&](){ ValueVector ret; @@ -585,8 +585,8 @@ void ValueTest::onEnter() Value v9(createValueVector()); - CCASSERT(v9.getType() == Value::Type::VECTOR, ""); - CCASSERT(!v9.isNull(), ""); + CCASSERT(v9.getType() == Value::Type::VECTOR, "v9's value type is Value::Type::VECTOR."); + CCASSERT(!v9.isNull(), "v9 is not null."); auto createValueMap = [&](){ ValueMap ret; @@ -597,8 +597,8 @@ void ValueTest::onEnter() }; Value v10(createValueMap()); - CCASSERT(v10.getType() == Value::Type::MAP, ""); - CCASSERT(!v10.isNull(), ""); + CCASSERT(v10.getType() == Value::Type::MAP, "v10's value type is Value::Type::MAP."); + CCASSERT(!v10.isNull(), "v10 is not null."); auto createValueMapIntKey = [&](){ ValueMapIntKey ret; @@ -609,8 +609,8 @@ void ValueTest::onEnter() }; Value v11(createValueMapIntKey()); - CCASSERT(v11.getType() == Value::Type::INT_KEY_MAP, ""); - CCASSERT(!v11.isNull(), ""); + CCASSERT(v11.getType() == Value::Type::INT_KEY_MAP, "v11's value type is Value::Type::INT_KEY_MAP."); + CCASSERT(!v11.isNull(), "v11 is not null."); } std::string ValueTest::subtitle() const diff --git a/tests/cpp-tests/Classes/VibrateTest/VibrateTest.cpp b/tests/cpp-tests/Classes/VibrateTest/VibrateTest.cpp index 6ec2a23c1f16..aaddebc3e98b 100644 --- a/tests/cpp-tests/Classes/VibrateTest/VibrateTest.cpp +++ b/tests/cpp-tests/Classes/VibrateTest/VibrateTest.cpp @@ -278,9 +278,9 @@ bool VibrateControlTest::init() vibrateItem->setPosition(layerSize.width * 0.5f, layerSize.height * 0.7f); addChild(vibrateItem); - auto durationLabelValue = CCString::createWithFormat("duration: %.3fs", _duration); + auto durationLabelValue = StringUtils::format("duration: %.3fs", _duration); - auto durationLabel = Label::createWithTTF(durationLabelValue->getCString(), fontFilePath, 20); + auto durationLabel = Label::createWithTTF(durationLabelValue, fontFilePath, 20); durationLabel->setAnchorPoint(Vec2::ANCHOR_MIDDLE); durationLabel->setPosition(layerSize.width * 0.5f, layerSize.height * 0.5f); addChild(durationLabel); @@ -290,8 +290,8 @@ bool VibrateControlTest::init() durationSlider->setPercent(0); durationSlider->setCallBack([&](SliderEx* sender, float ratio, SliderEx::TouchEvent event){ _duration = ratio * 1.9f + 0.1f; // From 0.1s to 2s - auto durationLabelValue = CCString::createWithFormat("duration: %.3fs", _duration); - (static_cast(_durationLabel))->setString(durationLabelValue->getCString()); + auto durationLabelValue = StringUtils::format("duration: %.3fs", _duration); + (static_cast(_durationLabel))->setString(durationLabelValue); }); durationSlider->setPosition(Vec2(layerSize.width * 0.5f, layerSize.height * 0.35f)); addChild(durationSlider); diff --git a/tests/cpp-tests/Classes/VibrateTest/VibrateTest.h b/tests/cpp-tests/Classes/VibrateTest/VibrateTest.h index d5899abae365..e5d52a4ff44f 100644 --- a/tests/cpp-tests/Classes/VibrateTest/VibrateTest.h +++ b/tests/cpp-tests/Classes/VibrateTest/VibrateTest.h @@ -46,7 +46,7 @@ class VibrateControlTest : public VibrateTestDemo CREATE_FUNC(VibrateControlTest); virtual ~VibrateControlTest(); - virtual bool init(); + virtual bool init()override; virtual std::string title() const override; private: diff --git a/tests/cpp-tests/Resources/Sprite3DTest/mesh_model.c3b b/tests/cpp-tests/Resources/Sprite3DTest/mesh_model.c3b new file mode 100644 index 000000000000..50f51efac06b Binary files /dev/null and b/tests/cpp-tests/Resources/Sprite3DTest/mesh_model.c3b differ diff --git a/tests/cpp-tests/Resources/fonts/xingkai-incomplete.ttf b/tests/cpp-tests/Resources/fonts/xingkai-incomplete.ttf new file mode 100644 index 000000000000..60f0900bf3be Binary files /dev/null and b/tests/cpp-tests/Resources/fonts/xingkai-incomplete.ttf differ diff --git a/tests/cpp-tests/proj.android-studio/app/jni/Android.mk b/tests/cpp-tests/proj.android-studio/app/jni/Android.mk index bc7073018c20..7bd9cf20cb6d 100644 --- a/tests/cpp-tests/proj.android-studio/app/jni/Android.mk +++ b/tests/cpp-tests/proj.android-studio/app/jni/Android.mk @@ -20,6 +20,8 @@ LOCAL_SRC_FILES := main.cpp \ ../../../Classes/Box2DTestBed/GLES-Render.cpp \ ../../../Classes/Box2DTestBed/Test.cpp \ ../../../Classes/Box2DTestBed/TestEntries.cpp \ +../../../Classes/BugsTest/Bug-CCDrawNode.cpp \ +../../../Classes/BugsTest/Bug-PageViewLayout.cpp \ ../../../Classes/BugsTest/Bug-1159.cpp \ ../../../Classes/BugsTest/Bug-1174.cpp \ ../../../Classes/BugsTest/Bug-350.cpp \ @@ -95,6 +97,7 @@ LOCAL_SRC_FILES := main.cpp \ ../../../Classes/NewAudioEngineTest/NewAudioEngineTest.cpp \ ../../../Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp \ ../../../Classes/NewRendererTest/NewRendererTest.cpp \ +../../../Classes/NavMeshTest/NavMeshTest.cpp \ ../../../Classes/NodeTest/NodeTest.cpp \ ../../../Classes/OpenURLTest/OpenURLTest.cpp \ ../../../Classes/ParallaxTest/ParallaxTest.cpp \ @@ -201,10 +204,10 @@ LOCAL_SRC_FILES := main.cpp \ ../../../Classes/UnitTest/UnitTest.cpp \ ../../../Classes/UserDefaultTest/UserDefaultTest.cpp \ ../../../Classes/VisibleRect.cpp \ +../../../Classes/VibrateTest/VibrateTest.cpp \ ../../../Classes/ZwoptexTest/ZwoptexTest.cpp \ ../../../Classes/controller.cpp \ -../../../Classes/testBasic.cpp \ -../../../Classes/NavMeshTest/NavMeshTest.cpp +../../../Classes/testBasic.cpp LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../../Classes \ $(LOCAL_PATH)/../../../../.. diff --git a/tests/cpp-tests/proj.android/jni/Android.mk b/tests/cpp-tests/proj.android/jni/Android.mk index 29c34700cd7a..12fc64221172 100644 --- a/tests/cpp-tests/proj.android/jni/Android.mk +++ b/tests/cpp-tests/proj.android/jni/Android.mk @@ -20,6 +20,8 @@ LOCAL_SRC_FILES := main.cpp \ ../../Classes/Box2DTestBed/GLES-Render.cpp \ ../../Classes/Box2DTestBed/Test.cpp \ ../../Classes/Box2DTestBed/TestEntries.cpp \ +../../Classes/BugsTest/Bug-CCDrawNode.cpp \ +../../Classes/BugsTest/Bug-PageViewLayout.cpp \ ../../Classes/BugsTest/Bug-1159.cpp \ ../../Classes/BugsTest/Bug-1174.cpp \ ../../Classes/BugsTest/Bug-350.cpp \ diff --git a/tests/cpp-tests/proj.win10/cpp-tests.vcxproj b/tests/cpp-tests/proj.win10/cpp-tests.vcxproj index c433af34120b..5a0427832510 100644 --- a/tests/cpp-tests/proj.win10/cpp-tests.vcxproj +++ b/tests/cpp-tests/proj.win10/cpp-tests.vcxproj @@ -298,6 +298,8 @@ + + @@ -547,6 +549,8 @@ + + diff --git a/tests/cpp-tests/proj.win10/cpp-tests.vcxproj.filters b/tests/cpp-tests/proj.win10/cpp-tests.vcxproj.filters index e7927f6838f7..2221de3dcc74 100644 --- a/tests/cpp-tests/proj.win10/cpp-tests.vcxproj.filters +++ b/tests/cpp-tests/proj.win10/cpp-tests.vcxproj.filters @@ -470,6 +470,12 @@ Classes\BugsTest + + Classes\BugsTest + + + Classes\BugsTest + Classes\BugsTest @@ -1215,6 +1221,12 @@ Classes\BugsTest + + Classes\BugsTest + + + Classes\BugsTest + Classes\BugsTest diff --git a/tests/cpp-tests/proj.win32/cpp-tests.vcxproj b/tests/cpp-tests/proj.win32/cpp-tests.vcxproj index be5fa255e945..599f26c03b91 100644 --- a/tests/cpp-tests/proj.win32/cpp-tests.vcxproj +++ b/tests/cpp-tests/proj.win32/cpp-tests.vcxproj @@ -151,7 +151,9 @@ xcopy "$(OutDir)..\*.dll" "$(OutDir)" /D /Y + + @@ -356,7 +358,9 @@ xcopy "$(OutDir)..\*.dll" "$(OutDir)" /D /Y + + diff --git a/tests/cpp-tests/proj.win32/cpp-tests.vcxproj.filters b/tests/cpp-tests/proj.win32/cpp-tests.vcxproj.filters index 147da5417f8d..958fd9354fa2 100644 --- a/tests/cpp-tests/proj.win32/cpp-tests.vcxproj.filters +++ b/tests/cpp-tests/proj.win32/cpp-tests.vcxproj.filters @@ -969,6 +969,12 @@ Classes\Scene3DTest + + Classes\BugsTest + + + Classes\BugsTest + @@ -1760,5 +1766,11 @@ Classes\Scene3DTest + + Classes\BugsTest + + + Classes\BugsTest + diff --git a/tests/cpp-tests/proj.win8.1-universal/cpp-tests.Shared/cpp-tests.Shared.vcxitems b/tests/cpp-tests/proj.win8.1-universal/cpp-tests.Shared/cpp-tests.Shared.vcxitems index 8cbc4645b6d5..859a4dfe8710 100644 --- a/tests/cpp-tests/proj.win8.1-universal/cpp-tests.Shared/cpp-tests.Shared.vcxitems +++ b/tests/cpp-tests/proj.win8.1-universal/cpp-tests.Shared/cpp-tests.Shared.vcxitems @@ -48,7 +48,9 @@ + + @@ -303,7 +305,9 @@ + + diff --git a/tests/cpp-tests/proj.win8.1-universal/cpp-tests.Shared/cpp-tests.Shared.vcxitems.filters b/tests/cpp-tests/proj.win8.1-universal/cpp-tests.Shared/cpp-tests.Shared.vcxitems.filters index b245f7bcdcd0..ffc10a447a47 100644 --- a/tests/cpp-tests/proj.win8.1-universal/cpp-tests.Shared/cpp-tests.Shared.vcxitems.filters +++ b/tests/cpp-tests/proj.win8.1-universal/cpp-tests.Shared/cpp-tests.Shared.vcxitems.filters @@ -1,4 +1,4 @@ - + @@ -799,6 +799,13 @@ Classes\NavMeshTest + + Classes\BugsTest + + + Classes\BugsTest + + @@ -1260,9 +1267,6 @@ Classes\UITest\CocostudioGUISceneTest\UICheckBoxTest - - Classes\UITest\CocostudioGUISceneTest\UIRadioButtonTest - Classes\UITest\CocostudioGUISceneTest\UIFocusTest @@ -1779,5 +1783,11 @@ Classes\NavMeshTest + + Classes\BugsTest + + + Classes\BugsTest + diff --git a/tests/game-controller-test/Resources/nibirusdk.config b/tests/game-controller-test/Resources/nibirusdk.config new file mode 100644 index 000000000000..00e1a4d45c15 --- /dev/null +++ b/tests/game-controller-test/Resources/nibirusdk.config @@ -0,0 +1,2 @@ +support_lr2=1 +sdk=nibiru \ No newline at end of file diff --git a/tests/game-controller-test/proj.android-studio/app/AndroidManifest.xml b/tests/game-controller-test/proj.android-studio/app/AndroidManifest.xml index 12ce1f878c08..2bdd039e17e1 100644 --- a/tests/game-controller-test/proj.android-studio/app/AndroidManifest.xml +++ b/tests/game-controller-test/proj.android-studio/app/AndroidManifest.xml @@ -9,15 +9,17 @@ + + - - + + + + + + + + + + diff --git a/tests/game-controller-test/proj.android-studio/app/src/org/cocos2dx/game_controller_test/AppActivity.java b/tests/game-controller-test/proj.android-studio/app/src/org/cocos2dx/game_controller_test/AppActivity.java index 97b31b36d497..58936a529346 100644 --- a/tests/game-controller-test/proj.android-studio/app/src/org/cocos2dx/game_controller_test/AppActivity.java +++ b/tests/game-controller-test/proj.android-studio/app/src/org/cocos2dx/game_controller_test/AppActivity.java @@ -29,16 +29,17 @@ of this software and associated documentation files (the "Software"), to deal import android.os.Bundle; public class AppActivity extends GameControllerActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - //The standard controller,without doing anything special. e.g: Amazon Fire TV - - //Manually specify an adapter. - this.connectController(DRIVERTYPE_NIBIRU); - this.connectController(DRIVERTYPE_MOGA); - this.connectController(DRIVERTYPE_OUYA); - } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + //The standard controller,without doing anything special. e.g: Amazon Fire TV + + //Manually specify an adapter. + this.connectController(DRIVERTYPE_NIBIRU); + //Nibiru SDK have already integrated with MOGA service. + //this.connectController(DRIVERTYPE_MOGA); + this.connectController(DRIVERTYPE_OUYA); + } } diff --git a/tests/game-controller-test/proj.android/AndroidManifest.xml b/tests/game-controller-test/proj.android/AndroidManifest.xml index ee6c0a0fb380..5385ef9c4bb5 100644 --- a/tests/game-controller-test/proj.android/AndroidManifest.xml +++ b/tests/game-controller-test/proj.android/AndroidManifest.xml @@ -12,13 +12,15 @@ + + + android:icon="@drawable/icon"> - - + + + + + + + + + +