From 3f4db26a2bc59147447b0c038ce7963c2c7ab2ba Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Fri, 10 Jan 2014 16:02:23 +0800 Subject: [PATCH 01/34] Fixed bugs --- cocos/gui/UIButton.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/cocos/gui/UIButton.cpp b/cocos/gui/UIButton.cpp index 5a6a2dc54f..82ed33dfec 100644 --- a/cocos/gui/UIButton.cpp +++ b/cocos/gui/UIButton.cpp @@ -366,8 +366,7 @@ void Button::onPressStateChangedToNormal() else { _buttonNormalRenderer->stopAllActions(); - Action *zoomAction = ScaleTo::create(0.05f, _normalTextureScaleXInSize, _normalTextureScaleYInSize); - _buttonNormalRenderer->runAction(zoomAction); + _buttonNormalRenderer->setScale(_normalTextureScaleXInSize, _normalTextureScaleYInSize); } } @@ -393,8 +392,7 @@ void Button::onPressStateChangedToPressed() _buttonClickedRenderer->setVisible(true); _buttonDisableRenderer->setVisible(false); _buttonNormalRenderer->stopAllActions(); - Action *zoomAction = ScaleTo::create(0.05f, _pressedTextureScaleXInSize + 0.1f, _pressedTextureScaleYInSize + 0.1f); - _buttonNormalRenderer->runAction(zoomAction); + _buttonNormalRenderer->setScale(_normalTextureScaleXInSize + 0.1f, _normalTextureScaleYInSize + 0.1f); } } From 4e2d6143afbff47eb2d7fad7023e4b6544273b1a Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Fri, 10 Jan 2014 17:02:16 +0800 Subject: [PATCH 02/34] Fixed bug of reader --- .../cocostudio/CCSGUIReader.cpp | 28 ++++++++++++------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index 349bba5dfe..016ddeafb8 100644 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -558,12 +558,16 @@ void WidgetPropertiesReader0250::setPropsForLabelFromJsonDictionary(Widget*widge { label->setFontName(DICTOOL->getStringValue_json(options, "fontName")); } - bool aw = DICTOOL->checkObjectExist_json(options, "areaWidth"); - bool ah = DICTOOL->checkObjectExist_json(options, "areaHeight"); - if (aw && ah) + bool handleDimensions = DICTOOL->getBooleanValue_json(options, "handleDimensions"); + if (handleDimensions) { - Size size = Size(DICTOOL->getFloatValue_json(options, "areaWidth"),DICTOOL->getFloatValue_json(options,"areaHeight")); - label->setTextAreaSize(size); + bool aw = DICTOOL->checkObjectExist_json(options, "areaWidth"); + bool ah = DICTOOL->checkObjectExist_json(options, "areaHeight"); + if (aw && ah) + { + Size size = Size(DICTOOL->getFloatValue_json(options, "areaWidth"),DICTOOL->getFloatValue_json(options,"areaHeight")); + label->setTextAreaSize(size); + } } bool ha = DICTOOL->checkObjectExist_json(options, "hAlignment"); if (ha) @@ -1449,12 +1453,16 @@ void WidgetPropertiesReader0300::setPropsForLabelFromJsonDictionary(Widget*widge { label->setFontName(DICTOOL->getStringValue_json(options, "fontName")); } - bool aw = DICTOOL->checkObjectExist_json(options, "areaWidth"); - bool ah = DICTOOL->checkObjectExist_json(options, "areaHeight"); - if (aw && ah) + bool handleDimensions = DICTOOL->getBooleanValue_json(options, "handleDimensions"); + if (handleDimensions) { - Size size = Size(DICTOOL->getFloatValue_json(options, "areaWidth"),DICTOOL->getFloatValue_json(options,"areaHeight")); - label->setTextAreaSize(size); + bool aw = DICTOOL->checkObjectExist_json(options, "areaWidth"); + bool ah = DICTOOL->checkObjectExist_json(options, "areaHeight"); + if (aw && ah) + { + Size size = Size(DICTOOL->getFloatValue_json(options, "areaWidth"),DICTOOL->getFloatValue_json(options,"areaHeight")); + label->setTextAreaSize(size); + } } bool ha = DICTOOL->checkObjectExist_json(options, "hAlignment"); if (ha) From fdfa84ce20c04dac3f75b359a66a587ff53511ca Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Tue, 14 Jan 2014 14:37:31 +0800 Subject: [PATCH 03/34] Fixed bugs. --- .../cocostudio/CCSGUIReader.cpp | 28 +++++++------------ 1 file changed, 10 insertions(+), 18 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index 016ddeafb8..349bba5dfe 100644 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -558,16 +558,12 @@ void WidgetPropertiesReader0250::setPropsForLabelFromJsonDictionary(Widget*widge { label->setFontName(DICTOOL->getStringValue_json(options, "fontName")); } - bool handleDimensions = DICTOOL->getBooleanValue_json(options, "handleDimensions"); - if (handleDimensions) + bool aw = DICTOOL->checkObjectExist_json(options, "areaWidth"); + bool ah = DICTOOL->checkObjectExist_json(options, "areaHeight"); + if (aw && ah) { - bool aw = DICTOOL->checkObjectExist_json(options, "areaWidth"); - bool ah = DICTOOL->checkObjectExist_json(options, "areaHeight"); - if (aw && ah) - { - Size size = Size(DICTOOL->getFloatValue_json(options, "areaWidth"),DICTOOL->getFloatValue_json(options,"areaHeight")); - label->setTextAreaSize(size); - } + Size size = Size(DICTOOL->getFloatValue_json(options, "areaWidth"),DICTOOL->getFloatValue_json(options,"areaHeight")); + label->setTextAreaSize(size); } bool ha = DICTOOL->checkObjectExist_json(options, "hAlignment"); if (ha) @@ -1453,16 +1449,12 @@ void WidgetPropertiesReader0300::setPropsForLabelFromJsonDictionary(Widget*widge { label->setFontName(DICTOOL->getStringValue_json(options, "fontName")); } - bool handleDimensions = DICTOOL->getBooleanValue_json(options, "handleDimensions"); - if (handleDimensions) + bool aw = DICTOOL->checkObjectExist_json(options, "areaWidth"); + bool ah = DICTOOL->checkObjectExist_json(options, "areaHeight"); + if (aw && ah) { - bool aw = DICTOOL->checkObjectExist_json(options, "areaWidth"); - bool ah = DICTOOL->checkObjectExist_json(options, "areaHeight"); - if (aw && ah) - { - Size size = Size(DICTOOL->getFloatValue_json(options, "areaWidth"),DICTOOL->getFloatValue_json(options,"areaHeight")); - label->setTextAreaSize(size); - } + Size size = Size(DICTOOL->getFloatValue_json(options, "areaWidth"),DICTOOL->getFloatValue_json(options,"areaHeight")); + label->setTextAreaSize(size); } bool ha = DICTOOL->checkObjectExist_json(options, "hAlignment"); if (ha) From fdf5a4c0b530242be7a29259bc376a010afbb236 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Wed, 15 Jan 2014 20:06:49 +0800 Subject: [PATCH 04/34] Fixed bug of reader. --- cocos/editor-support/cocostudio/CCSGUIReader.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index 349bba5dfe..ac3dc907ab 100644 --- a/cocos/editor-support/cocostudio/CCSGUIReader.cpp +++ b/cocos/editor-support/cocostudio/CCSGUIReader.cpp @@ -474,7 +474,7 @@ void WidgetPropertiesReader0250::setPropsForCheckBoxFromJsonDictionary(Widget*wi { checkBox->loadTextures(backGroundFileName_tp, backGroundSelectedFileName_tp, frontCrossFileName_tp,backGroundDisabledFileName_tp,frontCrossDisabledFileName_tp); } - + checkBox->setSelectedState(DICTOOL->getBooleanValue_json(options, "selectedState")); setColorPropsForWidgetFromJsonDictionary(widget,options); } @@ -1364,7 +1364,7 @@ void WidgetPropertiesReader0300::setPropsForCheckBoxFromJsonDictionary(Widget*wi default: break; } - + checkBox->setSelectedState(DICTOOL->getBooleanValue_json(options, "selectedState")); setColorPropsForWidgetFromJsonDictionary(widget,options); } From bea46fa2908335f58b4f803fb849626d88795e7a Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Fri, 17 Jan 2014 13:10:04 +0800 Subject: [PATCH 05/34] Add clone method to LayoutParameter --- cocos/gui/UILayoutParameter.cpp | 93 +++++++++++++++++++++++++-------- cocos/gui/UILayoutParameter.h | 53 +++++++++++-------- cocos/gui/UILoadingBar.cpp | 1 + cocos/gui/UIWidget.cpp | 5 ++ 4 files changed, 108 insertions(+), 44 deletions(-) diff --git a/cocos/gui/UILayoutParameter.cpp b/cocos/gui/UILayoutParameter.cpp index d0a98f4d0d..bbde56f9e3 100644 --- a/cocos/gui/UILayoutParameter.cpp +++ b/cocos/gui/UILayoutParameter.cpp @@ -1,26 +1,26 @@ /**************************************************************************** -Copyright (c) 2013-2014 Chukong Technologies Inc. - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #include "gui/UILayoutParameter.h" #include "gui/UILayout.h" @@ -56,6 +56,23 @@ LayoutParameterType LayoutParameter::getLayoutType() const { return _layoutParameterType; } + +LayoutParameter* LayoutParameter::clone() +{ + LayoutParameter* clonedParameter = createCloneInstance(); + clonedParameter->copyProperties(this); + return clonedParameter; +} + +LayoutParameter* LayoutParameter::createCloneInstance() +{ + return LayoutParameter::create(); +} + +void LayoutParameter::copyProperties(LayoutParameter *model) +{ + _margin = model->_margin; +} LinearLayoutParameter* LinearLayoutParameter::create() { @@ -78,6 +95,21 @@ LinearGravity LinearLayoutParameter::getGravity() const { return _linearGravity; } + +LayoutParameter* LinearLayoutParameter::createCloneInstance() +{ + return LinearLayoutParameter::create(); +} + +void LinearLayoutParameter::copyProperties(LayoutParameter *model) +{ + LayoutParameter::copyProperties(model); + LinearLayoutParameter* parameter = dynamic_cast(model); + if (parameter) + { + setGravity(parameter->_linearGravity); + } +} RelativeLayoutParameter* RelativeLayoutParameter::create() { @@ -120,6 +152,23 @@ const char* RelativeLayoutParameter::getRelativeName() const { return _relativeLayoutName.c_str(); } + +LayoutParameter* RelativeLayoutParameter::createCloneInstance() +{ + return RelativeLayoutParameter::create(); +} + +void RelativeLayoutParameter::copyProperties(LayoutParameter *model) +{ + LayoutParameter::copyProperties(model); + RelativeLayoutParameter* parameter = dynamic_cast(model); + if (parameter) + { + setAlign(parameter->_relativeAlign); + setRelativeName(parameter->_relativeLayoutName.c_str()); + setRelativeToWidgetName(parameter->_relativeWidgetName.c_str()); + } +} } diff --git a/cocos/gui/UILayoutParameter.h b/cocos/gui/UILayoutParameter.h index 9065a16176..e3ad428243 100644 --- a/cocos/gui/UILayoutParameter.h +++ b/cocos/gui/UILayoutParameter.h @@ -1,26 +1,26 @@ /**************************************************************************** -Copyright (c) 2013-2014 Chukong Technologies Inc. - -http://www.cocos2d-x.org - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -****************************************************************************/ + Copyright (c) 2013-2014 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ #ifndef __LAYOUTPARMETER_H__ #define __LAYOUTPARMETER_H__ @@ -86,6 +86,10 @@ public: * @return LayoutParameterType */ LayoutParameterType getLayoutType() const; + + LayoutParameter* clone(); + virtual LayoutParameter* createCloneInstance(); + virtual void copyProperties(LayoutParameter* model); protected: Margin _margin; LayoutParameterType _layoutParameterType; @@ -130,6 +134,8 @@ public: * @return LinearGravity */ LinearGravity getGravity() const; + virtual LayoutParameter* createCloneInstance(); + virtual void copyProperties(LayoutParameter* model); protected: LinearGravity _linearGravity; }; @@ -202,6 +208,9 @@ public: * @return name */ const char* getRelativeName() const; + + virtual LayoutParameter* createCloneInstance(); + virtual void copyProperties(LayoutParameter* model); protected: RelativeAlign _relativeAlign; std::string _relativeWidgetName; diff --git a/cocos/gui/UILoadingBar.cpp b/cocos/gui/UILoadingBar.cpp index b561c3fd7c..15ade85aef 100644 --- a/cocos/gui/UILoadingBar.cpp +++ b/cocos/gui/UILoadingBar.cpp @@ -334,6 +334,7 @@ void LoadingBar::copySpecialProperties(Widget *widget) loadTexture(loadingBar->_textureFile.c_str(), loadingBar->_renderBarTexType); setCapInsets(loadingBar->_capInsets); setPercent(loadingBar->_percent); + setDirection(loadingBar->_barType); } } diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index e28f4d8db0..c475a1c409 100644 --- a/cocos/gui/UIWidget.cpp +++ b/cocos/gui/UIWidget.cpp @@ -1065,6 +1065,11 @@ void Widget::copyProperties(Widget *widget) setOpacity(widget->getOpacity()); setCascadeOpacityEnabled(widget->isCascadeOpacityEnabled()); setCascadeColorEnabled(widget->isCascadeColorEnabled()); + Map& layoutParameterDic = widget->_layoutParameterDictionary; + for (auto iter = layoutParameterDic.begin(); iter != layoutParameterDic.end(); ++iter) + { + setLayoutParameter(iter->second->clone()); + } onSizeChanged(); } From f33064a2fcd2d38f7b882c227fafab2337ea5a8d Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Fri, 17 Jan 2014 15:22:59 +0800 Subject: [PATCH 06/34] Fixed bug of label --- cocos/gui/UIText.cpp | 18 +++++------------- cocos/gui/UIText.h | 1 - 2 files changed, 5 insertions(+), 14 deletions(-) diff --git a/cocos/gui/UIText.cpp b/cocos/gui/UIText.cpp index 1899d7439a..13b014fe66 100644 --- a/cocos/gui/UIText.cpp +++ b/cocos/gui/UIText.cpp @@ -127,14 +127,11 @@ void Text::setTextVerticalAlignment(TextVAlignment alignment) void Text::setTouchScaleChangeEnabled(bool enable) { _touchScaleChangeEnabled = enable; - _normalScaleValueX = getScaleX(); - _normalScaleValueY = getScaleY(); } void Text::setScale(float fScale) { Widget::setScale(fScale); - _normalScaleValueX = _normalScaleValueY = fScale; } void Text::setScaleX(float fScaleX) @@ -158,7 +155,7 @@ void Text::onPressStateChangedToNormal() { return; } - clickScale(_normalScaleValueX, _normalScaleValueY); + _labelRenderer->setScale(_normalScaleValueX, _normalScaleValueY); } void Text::onPressStateChangedToPressed() @@ -167,9 +164,7 @@ void Text::onPressStateChangedToPressed() { return; } - _normalScaleValueX = getScaleX(); - _normalScaleValueY = getScaleY(); - clickScale(_normalScaleValueX + _onSelectedScaleOffset, _normalScaleValueY + _onSelectedScaleOffset); + _labelRenderer->setScale(_normalScaleValueX + _onSelectedScaleOffset, _normalScaleValueY + _onSelectedScaleOffset); } void Text::onPressStateChangedToDisabled() @@ -177,12 +172,6 @@ void Text::onPressStateChangedToDisabled() } -void Text::clickScale(float scaleX, float scaleY) -{ - setScaleX(scaleX); - setScaleY(scaleY); -} - void Text::setFlipX(bool flipX) { _labelRenderer->setFlippedX(flipX); @@ -231,6 +220,7 @@ void Text::labelScaleChangedWithSize() { _labelRenderer->setScale(1.0f); _size = _labelRenderer->getContentSize(); + _normalScaleValueX = _normalScaleValueY = 1.0f; } else { @@ -244,6 +234,8 @@ void Text::labelScaleChangedWithSize() float scaleY = _size.height / textureSize.height; _labelRenderer->setScaleX(scaleX); _labelRenderer->setScaleY(scaleY); + _normalScaleValueX = scaleX; + _normalScaleValueY = scaleY; } } diff --git a/cocos/gui/UIText.h b/cocos/gui/UIText.h index e41b01d321..44d558151a 100644 --- a/cocos/gui/UIText.h +++ b/cocos/gui/UIText.h @@ -166,7 +166,6 @@ protected: virtual void onPressStateChangedToPressed() override; virtual void onPressStateChangedToDisabled() override; virtual void onSizeChanged() override; - void clickScale(float scaleX, float scaleY); void labelScaleChangedWithSize(); virtual Widget* createCloneInstance() override; virtual void copySpecialProperties(Widget* model) override; From f10e1ee04cb3900665e42beb9b44172d724665c6 Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Mon, 20 Jan 2014 13:38:13 +0800 Subject: [PATCH 07/34] optimize scissor clipping --- cocos/gui/UILayout.cpp | 130 ++++++++++++++++++++++------------------- cocos/gui/UILayout.h | 1 + 2 files changed, 70 insertions(+), 61 deletions(-) diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp index 8a64ad7ed4..697c89a243 100644 --- a/cocos/gui/UILayout.cpp +++ b/cocos/gui/UILayout.cpp @@ -67,6 +67,7 @@ _scissorRectDirty(false), _clippingRect(Rect::ZERO), _clippingParent(nullptr), _doLayoutDirty(true), +_clippingRectDirty(true), _currentStencilEnabled(GL_FALSE), _currentStencilWriteMask(~0), _currentStencilFunc(GL_ALWAYS), @@ -95,6 +96,8 @@ void Layout::onEnter() { _clippingStencil->onEnter(); } + _doLayoutDirty = true; + _clippingRectDirty = true; } void Layout::onExit() @@ -421,79 +424,83 @@ void Layout::setStencilClippingSize(const Size &size) const Rect& Layout::getClippingRect() { - Point worldPos = convertToWorldSpace(Point::ZERO); - AffineTransform t = getNodeToWorldAffineTransform(); - float scissorWidth = _size.width*t.a; - float scissorHeight = _size.height*t.d; - Rect parentClippingRect; - Layout* parent = this; - bool firstClippingParentFounded = false; - while (parent) + if (_clippingRectDirty) { - parent = dynamic_cast(parent->getParent()); - if(parent) + Point worldPos = convertToWorldSpace(Point::ZERO); + AffineTransform t = getNodeToWorldAffineTransform(); + float scissorWidth = _size.width*t.a; + float scissorHeight = _size.height*t.d; + Rect parentClippingRect; + Layout* parent = this; + bool firstClippingParentFounded = false; + while (parent) { - if (parent->isClippingEnabled()) + parent = dynamic_cast(parent->getParent()); + if(parent) { - if (!firstClippingParentFounded) + if (parent->isClippingEnabled()) { - _clippingParent = parent; - firstClippingParentFounded = true; - break; + if (!firstClippingParentFounded) + { + _clippingParent = parent; + firstClippingParentFounded = true; + break; + } } } } - } - - if (_clippingParent) - { - parentClippingRect = _clippingParent->getClippingRect(); - float finalX = worldPos.x - (scissorWidth * _anchorPoint.x); - float finalY = worldPos.y - (scissorHeight * _anchorPoint.y); - float finalWidth = scissorWidth; - float finalHeight = scissorHeight; - float leftOffset = worldPos.x - parentClippingRect.origin.x; - if (leftOffset < 0.0f) + if (_clippingParent) { - finalX = parentClippingRect.origin.x; - finalWidth += leftOffset; + parentClippingRect = _clippingParent->getClippingRect(); + float finalX = worldPos.x - (scissorWidth * _anchorPoint.x); + float finalY = worldPos.y - (scissorHeight * _anchorPoint.y); + float finalWidth = scissorWidth; + float finalHeight = scissorHeight; + + float leftOffset = worldPos.x - parentClippingRect.origin.x; + if (leftOffset < 0.0f) + { + finalX = parentClippingRect.origin.x; + finalWidth += leftOffset; + } + float rightOffset = (worldPos.x + scissorWidth) - (parentClippingRect.origin.x + parentClippingRect.size.width); + if (rightOffset > 0.0f) + { + finalWidth -= rightOffset; + } + float topOffset = (worldPos.y + scissorHeight) - (parentClippingRect.origin.y + parentClippingRect.size.height); + if (topOffset > 0.0f) + { + finalHeight -= topOffset; + } + float bottomOffset = worldPos.y - parentClippingRect.origin.y; + if (bottomOffset < 0.0f) + { + finalY = parentClippingRect.origin.x; + finalHeight += bottomOffset; + } + if (finalWidth < 0.0f) + { + finalWidth = 0.0f; + } + if (finalHeight < 0.0f) + { + finalHeight = 0.0f; + } + _clippingRect.origin.x = finalX; + _clippingRect.origin.y = finalY; + _clippingRect.size.width = finalWidth; + _clippingRect.size.height = finalHeight; } - float rightOffset = (worldPos.x + scissorWidth) - (parentClippingRect.origin.x + parentClippingRect.size.width); - if (rightOffset > 0.0f) + else { - finalWidth -= rightOffset; + _clippingRect.origin.x = worldPos.x - (scissorWidth * _anchorPoint.x); + _clippingRect.origin.y = worldPos.y - (scissorHeight * _anchorPoint.y); + _clippingRect.size.width = scissorWidth; + _clippingRect.size.height = scissorHeight; } - float topOffset = (worldPos.y + scissorHeight) - (parentClippingRect.origin.y + parentClippingRect.size.height); - if (topOffset > 0.0f) - { - finalHeight -= topOffset; - } - float bottomOffset = worldPos.y - parentClippingRect.origin.y; - if (bottomOffset < 0.0f) - { - finalY = parentClippingRect.origin.x; - finalHeight += bottomOffset; - } - if (finalWidth < 0.0f) - { - finalWidth = 0.0f; - } - if (finalHeight < 0.0f) - { - finalHeight = 0.0f; - } - _clippingRect.origin.x = finalX; - _clippingRect.origin.y = finalY; - _clippingRect.size.width = finalWidth; - _clippingRect.size.height = finalHeight; - } - else - { - _clippingRect.origin.x = worldPos.x - (scissorWidth * _anchorPoint.x); - _clippingRect.origin.y = worldPos.y - (scissorHeight * _anchorPoint.y); - _clippingRect.size.width = scissorWidth; - _clippingRect.size.height = scissorHeight; + _clippingRectDirty = false; } return _clippingRect; } @@ -504,6 +511,7 @@ void Layout::onSizeChanged() setContentSize(_size); setStencilClippingSize(_size); _doLayoutDirty = true; + _clippingRectDirty = true; if (_backGroundImage) { _backGroundImage->setPosition(Point(_size.width/2.0f, _size.height/2.0f)); diff --git a/cocos/gui/UILayout.h b/cocos/gui/UILayout.h index 327707d7c8..13f7ac1e36 100644 --- a/cocos/gui/UILayout.h +++ b/cocos/gui/UILayout.h @@ -273,6 +273,7 @@ protected: Rect _clippingRect; Layout* _clippingParent; bool _doLayoutDirty; + bool _clippingRectDirty; //clipping From 223857398d4bd16de4087a9b5181f2bd239998bf Mon Sep 17 00:00:00 2001 From: CaiWenzhi Date: Mon, 20 Jan 2014 13:44:44 +0800 Subject: [PATCH 08/34] Add "override" --- cocos/gui/UILayoutParameter.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos/gui/UILayoutParameter.h b/cocos/gui/UILayoutParameter.h index e3ad428243..3e439e4a1a 100644 --- a/cocos/gui/UILayoutParameter.h +++ b/cocos/gui/UILayoutParameter.h @@ -134,8 +134,8 @@ public: * @return LinearGravity */ LinearGravity getGravity() const; - virtual LayoutParameter* createCloneInstance(); - virtual void copyProperties(LayoutParameter* model); + virtual LayoutParameter* createCloneInstance() override; + virtual void copyProperties(LayoutParameter* model) override; protected: LinearGravity _linearGravity; }; @@ -209,8 +209,8 @@ public: */ const char* getRelativeName() const; - virtual LayoutParameter* createCloneInstance(); - virtual void copyProperties(LayoutParameter* model); + virtual LayoutParameter* createCloneInstance() override; + virtual void copyProperties(LayoutParameter* model) override; protected: RelativeAlign _relativeAlign; std::string _relativeWidgetName; From a934d29c57f14a26be746f0726b21492bf527f62 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 28 Feb 2014 15:31:25 +0800 Subject: [PATCH 09/34] issue #4150: Correct body position with the node has a parent. Add set/getPosition/Rotation method. --- cocos/2d/CCNode.cpp | 29 ++++++++++++- cocos/2d/CCNode.h | 2 + cocos/physics/CCPhysicsBody.cpp | 74 +++++++++++++++++++++++---------- cocos/physics/CCPhysicsBody.h | 11 +++++ 4 files changed, 93 insertions(+), 23 deletions(-) diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 49472cf822..69a3454cac 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -419,7 +419,9 @@ void Node::setPosition(const Point& position) #if CC_USE_PHYSICS if (_physicsBody) { - _physicsBody->setPosition(position); + Node* parent = getParent(); + Point pos = parent != nullptr ? parent->convertToWorldSpace(getPosition()) : getPosition(); + _physicsBody->setPosition(pos); } #endif } @@ -534,6 +536,14 @@ const Point& Node::getAnchorPoint() const void Node::setAnchorPoint(const Point& point) { +#if CC_USE_PHYSICS + if (_physicsBody != nullptr && point.equals(Point::ANCHOR_MIDDLE)) + { + CCLOG("Node warning: This node has a physics body, the anchor must be in the middle, you cann't change this to other value."); + return; + } +#endif + if( ! point.equals(_anchorPoint)) { _anchorPoint = point; @@ -719,6 +729,11 @@ void Node::addChild(Node *child, int zOrder, int tag) this->insertChild(child, zOrder); #if CC_USE_PHYSICS + if (child->getPhysicsBody() != nullptr) + { + child->getPhysicsBody()->setPosition(this->convertToWorldSpace(child->getPosition())); + } + for (Node* node = this->getParent(); node != nullptr; node = node->getParent()) { if (dynamic_cast(node) != nullptr) @@ -1511,6 +1526,14 @@ void Node::setPhysicsBody(PhysicsBody* body) { body->_node = this; body->retain(); + + // physics rotation based on body position, but node rotation based on node anthor point + // it cann't support both of them, so I clear the anthor point to default. + if (!getAnchorPoint().equals(Point::ANCHOR_MIDDLE)) + { + CCLOG("Node warning: setPhysicsBody sets anchor point to Point::ANCHOR_MIDDLE."); + setAnchorPoint(Point::ANCHOR_MIDDLE); + } } if (_physicsBody != nullptr) @@ -1529,7 +1552,9 @@ void Node::setPhysicsBody(PhysicsBody* body) _physicsBody = body; if (body != nullptr) { - _physicsBody->setPosition(getPosition()); + Node* parent = getParent(); + Point pos = parent != nullptr ? parent->convertToWorldSpace(getPosition()) : getPosition(); + _physicsBody->setPosition(pos); _physicsBody->setRotation(getRotation()); } } diff --git a/cocos/2d/CCNode.h b/cocos/2d/CCNode.h index 1d00884cda..bd88ec0b2f 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -449,6 +449,7 @@ public: * The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner. * But you can use values higher than (1,1) and lower than (0,0) too. * The default anchorPoint is (0.5,0.5), so it starts in the center of the node. + * @note If node has a physics body, the anchor must be in the middle, you cann't change this to other value. * * @param anchorPoint The anchor point of node. */ @@ -1432,6 +1433,7 @@ public: #if CC_USE_PHYSICS /** * set the PhysicsBody that let the sprite effect with physics + * @note This method will set anchor point to Point::ANCHOR_MIDDLE if body not null, and you cann't change anchor point if node has a physics body. */ void setPhysicsBody(PhysicsBody* body); diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 46b2ab4637..85a2436292 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -75,6 +75,7 @@ PhysicsBody::PhysicsBody() , _group(0) , _positionResetTag(false) , _rotationResetTag(false) +, _rotationOffset(0) { } @@ -347,7 +348,7 @@ void PhysicsBody::setPosition(Point position) { if (!_positionResetTag) { - cpBodySetPos(_info->getBody(), PhysicsHelper::point2cpv(position)); + cpBodySetPos(_info->getBody(), PhysicsHelper::point2cpv(position + _positionOffset)); } _positionResetTag = false; } @@ -356,7 +357,7 @@ void PhysicsBody::setRotation(float rotation) { if (!_rotationResetTag) { - cpBodySetAngle(_info->getBody(), -PhysicsHelper::float2cpfloat(rotation * M_PI / 180.0f)); + cpBodySetAngle(_info->getBody(), -PhysicsHelper::float2cpfloat((rotation + _rotationOffset) * (M_PI / 180.0f))); } _rotationResetTag = false; @@ -365,12 +366,12 @@ void PhysicsBody::setRotation(float rotation) Point PhysicsBody::getPosition() const { cpVect vec = cpBodyGetPos(_info->getBody()); - return PhysicsHelper::cpv2point(vec); + return PhysicsHelper::cpv2point(vec) - _positionOffset; } float PhysicsBody::getRotation() const { - return -PhysicsHelper::cpfloat2float(cpBodyGetAngle(_info->getBody()) / M_PI * 180.0f); + return -PhysicsHelper::cpfloat2float(cpBodyGetAngle(_info->getBody()) * (180.0f / M_PI)) - _rotationOffset; } PhysicsShape* PhysicsBody::addShape(PhysicsShape* shape, bool addMassAndMoment/* = true*/) @@ -767,27 +768,18 @@ void PhysicsBody::setResting(bool rest) const void PhysicsBody::update(float delta) { - if (_node != nullptr && _dynamic && !isResting()) + if (_node != nullptr) { - cpVect pos = cpBodyGetPos(_info->getBody()); - cpVect prePos = _info->getPosition(); - cpVect rot = cpBodyGetRot(_info->getBody()); - cpVect preRot = _info->getRotation(); + Node* parent = _node->getParent(); - // only reset the node position when body position/rotation changed. - if (std::abs(pos.x - prePos.x) >= 0.3f || std::abs(pos.y - prePos.y) >= 0.3f - || std::abs(rot.x - preRot.x) >= 0.01f || std::abs(rot.y - preRot.y) >= 0.01f) - { - _positionResetTag = true; - _rotationResetTag = true; - _node->setPosition(getPosition()); - _info->setPosition(pos); - _node->setRotation(getRotation()); - _info->setRotation(rot); - } + Point position = parent != nullptr ? parent->convertToNodeSpace(getPosition()) : getPosition(); + _positionResetTag = true; + _rotationResetTag = true; + _node->setPosition(position); + _node->setRotation(getRotation()); // damping compute - if (_isDamping) + if (_isDamping && _dynamic && !isResting()) { _info->getBody()->v.x *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); _info->getBody()->v.y *= cpfclamp(1.0f - delta * _linearDamping, 0.0f, 1.0f); @@ -834,6 +826,46 @@ void PhysicsBody::setGroup(int group) } } +void PhysicsBody::setPositionOffset(const Point& position) +{ + if (!_positionOffset.equals(position)) + { + Point pos = getPosition(); + + _positionOffset = position; + + if (_node!= nullptr) + { + setPosition(pos); + } + } +} + +Point PhysicsBody::getPositionOffset() +{ + return _positionOffset; +} + +void PhysicsBody::setRotationOffset(float rotation) +{ + if (std::abs(_rotationOffset - rotation) > 0.5f) + { + float rot = getRotation(); + + _rotationOffset = rotation; + + if (_node != nullptr) + { + setRotation(rot); + } + } +} + +float PhysicsBody::getRotationOffset() +{ + return _rotationOffset; +} + Point PhysicsBody::world2Local(const Point& point) { return PhysicsHelper::cpv2point(cpBodyWorld2Local(_info->getBody(), PhysicsHelper::point2cpv(point))); diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index ea7a80aba5..4f4f9a2425 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -192,6 +192,15 @@ public: /** get the body rotation. */ float getRotation() const; + /** set body position offset, it's the position witch relative to node */ + void setPositionOffset(const Point& position); + /** get body position offset. */ + Point getPositionOffset(); + /** set body rotation offset, it's the rotation witch relative to node */ + void setRotationOffset(float rotation); + /** set the body rotation offset */ + float getRotationOffset(); + /** * @brief test the body is dynamic or not. * a dynamic body will effect with gravity. @@ -332,6 +341,8 @@ protected: bool _positionResetTag; /// To avoid reset the body position when body invoke Node::setPosition(). bool _rotationResetTag; /// To avoid reset the body rotation when body invoke Node::setRotation(). + Point _positionOffset; + float _rotationOffset; friend class PhysicsWorld; friend class PhysicsShape; From 015180bf625e36b680d4c1dab34f21f8f83904f2 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 28 Feb 2014 15:47:49 +0800 Subject: [PATCH 10/34] issue #4150: Add physics position/rotation test --- cocos/physics/CCPhysicsBody.cpp | 14 +----- tests/Classes/PhysicsTest/PhysicsTest.cpp | 59 +++++++++++++++++++++++ tests/Classes/PhysicsTest/PhysicsTest.h | 9 ++++ 3 files changed, 70 insertions(+), 12 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 85a2436292..2f075d311e 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -831,13 +831,8 @@ void PhysicsBody::setPositionOffset(const Point& position) if (!_positionOffset.equals(position)) { Point pos = getPosition(); - _positionOffset = position; - - if (_node!= nullptr) - { - setPosition(pos); - } + setPosition(pos); } } @@ -851,13 +846,8 @@ void PhysicsBody::setRotationOffset(float rotation) if (std::abs(_rotationOffset - rotation) > 0.5f) { float rot = getRotation(); - _rotationOffset = rotation; - - if (_node != nullptr) - { - setRotation(rot); - } + setRotation(rot); } } diff --git a/tests/Classes/PhysicsTest/PhysicsTest.cpp b/tests/Classes/PhysicsTest/PhysicsTest.cpp index dff1bbc35e..6c5347453d 100644 --- a/tests/Classes/PhysicsTest/PhysicsTest.cpp +++ b/tests/Classes/PhysicsTest/PhysicsTest.cpp @@ -18,6 +18,7 @@ namespace CL(PhysicsDemoSlice), CL(PhysicsDemoBug3988), CL(PhysicsContactTest), + CL(PhysicsPositionRotationTest), #else CL(PhysicsDemoDisabled), #endif @@ -1545,4 +1546,62 @@ std::string PhysicsContactTest::subtitle() const return "should not crash"; } +void PhysicsPositionRotationTest::onEnter() +{ + PhysicsDemo::onEnter(); + _scene->toggleDebug(); + _scene->getPhysicsWorld()->setGravity(Point::ZERO); + + auto touchListener = EventListenerTouchOneByOne::create(); + touchListener->onTouchBegan = CC_CALLBACK_2(PhysicsDemo::onTouchBegan, this); + touchListener->onTouchMoved = CC_CALLBACK_2(PhysicsDemo::onTouchMoved, this); + touchListener->onTouchEnded = CC_CALLBACK_2(PhysicsDemo::onTouchEnded, this); + _eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this); + + auto wall = Node::create(); + wall->setPhysicsBody(PhysicsBody::createEdgeBox(VisibleRect::getVisibleRect().size)); + wall->setPosition(VisibleRect::center()); + addChild(wall); + + // anchor test + auto anchorNode = Sprite::create("Images/YellowSquare.png"); + anchorNode->setAnchorPoint(Point(0.1, 0.9)); + anchorNode->setPosition(100, 100); + anchorNode->setScale(0.25); + anchorNode->setPhysicsBody(PhysicsBody::createBox(anchorNode->getContentSize()*anchorNode->getScale())); + anchorNode->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + addChild(anchorNode); + + //parent test + auto parent = Sprite::create("Images/YellowSquare.png"); + parent->setPosition(200, 100); + parent->setScale(0.25); + parent->setPhysicsBody(PhysicsBody::createBox(parent->getContentSize()*anchorNode->getScale())); + parent->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + addChild(parent); + + auto leftBall = Sprite::create("Images/ball.png"); + leftBall->setPosition(-30, 0); + leftBall->cocos2d::Node::setScale(2); + leftBall->setPhysicsBody(PhysicsBody::createCircle(leftBall->getContentSize().width/4)); + leftBall->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + parent->addChild(leftBall); + + // offset position rotation test + auto offsetPosNode = Sprite::create("Images/YellowSquare.png"); + offsetPosNode->setPosition(100, 200); + offsetPosNode->setPhysicsBody(PhysicsBody::createBox(offsetPosNode->getContentSize()/2)); + offsetPosNode->getPhysicsBody()->setPositionOffset(-Point(offsetPosNode->getContentSize()/2)); + offsetPosNode->getPhysicsBody()->setRotationOffset(45); + offsetPosNode->getPhysicsBody()->setTag(DRAG_BODYS_TAG); + addChild(offsetPosNode); + + return; +} + +std::string PhysicsPositionRotationTest::title() const +{ + return "Position/Rotation Test"; +} + #endif // ifndef CC_USE_PHYSICS diff --git a/tests/Classes/PhysicsTest/PhysicsTest.h b/tests/Classes/PhysicsTest/PhysicsTest.h index 585b525cad..a990b3edfd 100644 --- a/tests/Classes/PhysicsTest/PhysicsTest.h +++ b/tests/Classes/PhysicsTest/PhysicsTest.h @@ -216,6 +216,15 @@ private: int _blueTriangleNum; }; +class PhysicsPositionRotationTest : public PhysicsDemo +{ +public: + CREATE_FUNC(PhysicsPositionRotationTest); + + void onEnter() override; + virtual std::string title() const override; +}; + #endif #endif From 5244cb93ed140c2d1806cca071dda6a85b298e3c Mon Sep 17 00:00:00 2001 From: boyu0 Date: Fri, 28 Feb 2014 15:50:38 +0800 Subject: [PATCH 11/34] closed #4150: Delete PhysicsBodyInfo::set/getPosition/Rotation method. --- cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h | 6 ------ 1 file changed, 6 deletions(-) diff --git a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h index ac6ee4fe3b..3cbade4a7b 100644 --- a/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h +++ b/cocos/physics/chipmunk/CCPhysicsBodyInfo_chipmunk.h @@ -39,10 +39,6 @@ class PhysicsBodyInfo public: inline cpBody* getBody() const { return _body; } inline void setBody(cpBody* body) { _body = body; } - inline cpVect getPosition() const { return _position; } - inline void setPosition(cpVect& vect) { _position = vect; } - inline cpVect getRotation() const { return _rotation; } - inline void setRotation(cpVect& vect) { _rotation = vect; } private: PhysicsBodyInfo(); @@ -50,8 +46,6 @@ private: private: cpBody* _body; - cpVect _position; - cpVect _rotation; friend class PhysicsBody; }; From 0837b73dda351ca55daabcc762647af5c37d0bce Mon Sep 17 00:00:00 2001 From: Dhilan007 Date: Fri, 28 Feb 2014 17:34:24 +0800 Subject: [PATCH 12/34] fixed incorrect effect of Gaussian Blur. --- tests/Classes/ShaderTest/ShaderTest.cpp | 77 ++++++++++++++++++------- 1 file changed, 56 insertions(+), 21 deletions(-) diff --git a/tests/Classes/ShaderTest/ShaderTest.cpp b/tests/Classes/ShaderTest/ShaderTest.cpp index 0377617ae5..07d5e086fa 100644 --- a/tests/Classes/ShaderTest/ShaderTest.cpp +++ b/tests/Classes/ShaderTest/ShaderTest.cpp @@ -438,14 +438,21 @@ public: static SpriteBlur* create(const char *pszFileName); - Point blur_; - GLfloat sub_[4]; - - GLuint blurLocation; - GLuint subLocation; protected: void onDraw(); private: + int _blurRadius; + Point _pixelSize; + + int _samplingRadius; + //gaussian = cons * exp( (dx*dx + dy*dy) * scale); + float _scale; + float _cons; + float _weightSum; + + GLuint pixelSizeLocation; + GLuint coefficientLocation; + CustomCommand _customCommand; }; @@ -470,6 +477,7 @@ SpriteBlur* SpriteBlur::create(const char *pszFileName) bool SpriteBlur::initWithTexture(Texture2D* texture, const Rect& rect) { + _blurRadius = 0; if( Sprite::initWithTexture(texture, rect) ) { #if CC_ENABLE_CACHE_TEXTURE_DATA @@ -483,11 +491,10 @@ bool SpriteBlur::initWithTexture(Texture2D* texture, const Rect& rect) auto s = getTexture()->getContentSizeInPixels(); - blur_ = Point(1/s.width, 1/s.height); - sub_[0] = sub_[1] = sub_[2] = sub_[3] = 0; - + _pixelSize = Point(1/s.width, 1/s.height); + _samplingRadius = 0; this->initProgram(); - + return true; } @@ -497,7 +504,7 @@ bool SpriteBlur::initWithTexture(Texture2D* texture, const Rect& rect) void SpriteBlur::initProgram() { GLchar * fragSource = (GLchar*) String::createWithContentsOfFile( - FileUtils::getInstance()->fullPathForFilename("Shaders/example_Blur.fsh").c_str())->getCString(); + FileUtils::getInstance()->fullPathForFilename("Shaders/example_Blur.fsh").c_str())->getCString(); auto pProgram = new GLProgram(); pProgram->initWithVertexShaderByteArray(ccPositionTextureColor_vert, fragSource); setShaderProgram(pProgram); @@ -519,9 +526,9 @@ void SpriteBlur::initProgram() CHECK_GL_ERROR_DEBUG(); - subLocation = glGetUniformLocation( getShaderProgram()->getProgram(), "substract"); - blurLocation = glGetUniformLocation( getShaderProgram()->getProgram(), "blurSize"); - + pixelSizeLocation = glGetUniformLocation( getShaderProgram()->getProgram(), "onePixelSize"); + coefficientLocation = glGetUniformLocation( getShaderProgram()->getProgram(), "gaussianCoefficient"); + CHECK_GL_ERROR_DEBUG(); } @@ -540,8 +547,8 @@ void SpriteBlur::onDraw() getShaderProgram()->use(); getShaderProgram()->setUniformsForBuiltins(); - getShaderProgram()->setUniformLocationWith2f(blurLocation, blur_.x, blur_.y); - getShaderProgram()->setUniformLocationWith4fv(subLocation, sub_, 1); + getShaderProgram()->setUniformLocationWith2f(pixelSizeLocation, _pixelSize.x, _pixelSize.y); + getShaderProgram()->setUniformLocationWith4f(coefficientLocation, _samplingRadius, _scale,_cons,_weightSum); GL::bindTexture2D( getTexture()->getName()); @@ -571,10 +578,37 @@ void SpriteBlur::onDraw() void SpriteBlur::setBlurSize(float f) { - auto s = getTexture()->getContentSizeInPixels(); + if(_blurRadius == (int)f) + return; + _blurRadius = (int)f; - blur_ = Point(1/s.width, 1/s.height); - blur_ = blur_ * f; + _samplingRadius = _blurRadius; + if (_samplingRadius > 10) + { + _samplingRadius = 10; + } + if (_blurRadius > 0) + { + float sigma = _blurRadius / 2.0f; + _scale = -0.5f / (sigma * sigma); + _cons = -1.0f * _scale / 3.141592f; + _weightSum = -_cons; + + float weight; + int squareX; + for(int dx = 0; dx <= _samplingRadius; ++dx) + { + squareX = dx * dx; + weight = _cons * exp(squareX * _scale); + _weightSum += 2.0 * weight; + for (int dy = 1; dy <= _samplingRadius; ++dy) + { + weight = _cons * exp((squareX + dy * dy) * _scale); + _weightSum += 4.0 * weight; + } + } + } + log("_blurRadius:%d",_blurRadius); } // ShaderBlur @@ -597,16 +631,17 @@ std::string ShaderBlur::subtitle() const ControlSlider* ShaderBlur::createSliderCtl() { auto screenSize = Director::getInstance()->getWinSize(); - + ControlSlider *slider = ControlSlider::create("extensions/sliderTrack.png","extensions/sliderProgress.png" ,"extensions/sliderThumb.png"); slider->setAnchorPoint(Point(0.5f, 1.0f)); slider->setMinimumValue(0.0f); // Sets the min value of range - slider->setMaximumValue(3.0f); // Sets the max value of range - slider->setValue(1.0f); + slider->setMaximumValue(25.0f); // Sets the max value of range + slider->setPosition(Point(screenSize.width / 2.0f, screenSize.height / 3.0f)); // When the value of the slider will change, the given selector will be call slider->addTargetWithActionForControlEvents(this, cccontrol_selector(ShaderBlur::sliderAction), Control::EventType::VALUE_CHANGED); + slider->setValue(2.0f); return slider; From d50391e5dd15df1660e422983d10fef81611fe21 Mon Sep 17 00:00:00 2001 From: heliclei Date: Fri, 28 Feb 2014 23:02:22 +0800 Subject: [PATCH 13/34] add CCConosle [autotest run] command --- .../ActionManagerTest/ActionManagerTest.cpp | 15 ++-- .../ActionManagerTest/ActionManagerTest.h | 12 +-- .../ActionsEaseTest/ActionsEaseTest.cpp | 48 ++++++------ .../Classes/ActionsEaseTest/ActionsEaseTest.h | 48 ++++++------ tests/Classes/LayerTest/LayerTest.cpp | 20 ++--- tests/Classes/LayerTest/LayerTest.h | 18 ++--- .../NewRendererTest/NewRendererTest.cpp | 4 +- tests/Classes/NodeTest/NodeTest.cpp | 22 +++--- tests/Classes/NodeTest/NodeTest.h | 22 +++--- tests/Classes/ParticleTest/ParticleTest.cpp | 38 +++++----- tests/Classes/ParticleTest/ParticleTest.h | 38 +++++----- .../SpriteTest/SpriteTest.cpp.REMOVED.git-id | 2 +- tests/Classes/controller.cpp | 74 ++++++++++++++++++- 13 files changed, 217 insertions(+), 144 deletions(-) diff --git a/tests/Classes/ActionManagerTest/ActionManagerTest.cpp b/tests/Classes/ActionManagerTest/ActionManagerTest.cpp index a62e810d4d..112b16e9ca 100644 --- a/tests/Classes/ActionManagerTest/ActionManagerTest.cpp +++ b/tests/Classes/ActionManagerTest/ActionManagerTest.cpp @@ -78,10 +78,13 @@ ActionManagerTest::~ActionManagerTest(void) } std::string ActionManagerTest::title() const +{ + return "ActionManager Test"; +} +std::string ActionManagerTest::subtitle() const { return "No title"; } - void ActionManagerTest::restartCallback(Ref* sender) { auto s = new ActionManagerTestScene(); @@ -144,7 +147,7 @@ void CrashTest::removeThis() nextCallback(this); } -std::string CrashTest::title() const +std::string CrashTest::subtitle() const { return "Test 1. Should not crash"; } @@ -175,7 +178,7 @@ void LogicTest::bugMe(Node* node) node->runAction(ScaleTo::create(2, 2)); } -std::string LogicTest::title() const +std::string LogicTest::subtitle() const { return "Logic test"; } @@ -223,7 +226,7 @@ void PauseTest::unpause(float dt) director->getActionManager()->resumeTarget(node); } -std::string PauseTest::title() const +std::string PauseTest::subtitle() const { return "Pause Test"; } @@ -259,7 +262,7 @@ void RemoveTest::stopAction() sprite->stopActionByTag(kTagSequence); } -std::string RemoveTest::title() const +std::string RemoveTest::subtitle() const { return "Remove Test"; } @@ -269,7 +272,7 @@ std::string RemoveTest::title() const // ResumeTest // //------------------------------------------------------------------ -std::string ResumeTest::title() const +std::string ResumeTest::subtitle() const { return "Resume Test"; } diff --git a/tests/Classes/ActionManagerTest/ActionManagerTest.h b/tests/Classes/ActionManagerTest/ActionManagerTest.h index 91efe57837..4b123cc9b8 100644 --- a/tests/Classes/ActionManagerTest/ActionManagerTest.h +++ b/tests/Classes/ActionManagerTest/ActionManagerTest.h @@ -16,7 +16,7 @@ public: ~ActionManagerTest(void); virtual std::string title() const override; - + virtual std::string subtitle() const override; void restartCallback(Ref* sender); void nextCallback(Ref* sender); void backCallback(Ref* sender); @@ -25,7 +25,7 @@ public: class CrashTest : public ActionManagerTest { public: - virtual std::string title() const override; + virtual std::string subtitle() const override; virtual void onEnter() override; void removeThis(); }; @@ -33,7 +33,7 @@ public: class LogicTest : public ActionManagerTest { public: - virtual std::string title() const override; + virtual std::string subtitle() const override; virtual void onEnter() override; void bugMe(Node* node); }; @@ -41,7 +41,7 @@ public: class PauseTest : public ActionManagerTest { public: - virtual std::string title() const override; + virtual std::string subtitle() const override; virtual void onEnter() override; void unpause(float dt); }; @@ -49,7 +49,7 @@ public: class RemoveTest : public ActionManagerTest { public: - virtual std::string title() const override; + virtual std::string subtitle() const override; virtual void onEnter() override; void stopAction(); }; @@ -57,7 +57,7 @@ public: class ResumeTest : public ActionManagerTest { public: - virtual std::string title() const override; + virtual std::string subtitle() const override; virtual void onEnter() override; void resumeGrossini(float time); }; diff --git a/tests/Classes/ActionsEaseTest/ActionsEaseTest.cpp b/tests/Classes/ActionsEaseTest/ActionsEaseTest.cpp index e3e4976755..03d0b82994 100644 --- a/tests/Classes/ActionsEaseTest/ActionsEaseTest.cpp +++ b/tests/Classes/ActionsEaseTest/ActionsEaseTest.cpp @@ -119,7 +119,7 @@ void SpriteEase::testStopAction(float dt) _grossini->stopActionByTag(1); } -std::string SpriteEase::title() const +std::string SpriteEase::subtitle() const { return "EaseIn - EaseOut - Stop"; } @@ -159,7 +159,7 @@ void SpriteEaseInOut::onEnter() } -std::string SpriteEaseInOut::title() const +std::string SpriteEaseInOut::subtitle() const { return "EaseInOut and rates"; } @@ -196,7 +196,7 @@ void SpriteEaseExponential::onEnter() } -std::string SpriteEaseExponential::title() const +std::string SpriteEaseExponential::subtitle() const { return "ExpIn - ExpOut actions"; } @@ -229,7 +229,7 @@ void SpriteEaseExponentialInOut::onEnter() } -std::string SpriteEaseExponentialInOut::title() const +std::string SpriteEaseExponentialInOut::subtitle() const { return "EaseExponentialInOut action"; } @@ -266,7 +266,7 @@ void SpriteEaseSine::onEnter() } -std::string SpriteEaseSine::title() const +std::string SpriteEaseSine::subtitle() const { return "EaseSineIn - EaseSineOut"; } @@ -298,7 +298,7 @@ void SpriteEaseSineInOut::onEnter() } -std::string SpriteEaseSineInOut::title() const +std::string SpriteEaseSineInOut::subtitle() const { return "EaseSineInOut action"; } @@ -333,7 +333,7 @@ void SpriteEaseElastic::onEnter() } -std::string SpriteEaseElastic::title() const +std::string SpriteEaseElastic::subtitle() const { return "Elastic In - Out actions"; } @@ -371,7 +371,7 @@ void SpriteEaseElasticInOut::onEnter() } -std::string SpriteEaseElasticInOut::title() const +std::string SpriteEaseElasticInOut::subtitle() const { return "EaseElasticInOut action"; } @@ -408,7 +408,7 @@ void SpriteEaseBounce::onEnter() } -std::string SpriteEaseBounce::title() const +std::string SpriteEaseBounce::subtitle() const { return "Bounce In - Out actions"; } @@ -442,7 +442,7 @@ void SpriteEaseBounceInOut::onEnter() } -std::string SpriteEaseBounceInOut::title() const +std::string SpriteEaseBounceInOut::subtitle() const { return "EaseBounceInOut action"; } @@ -478,7 +478,7 @@ void SpriteEaseBack::onEnter() } -std::string SpriteEaseBack::title() const +std::string SpriteEaseBack::subtitle() const { return "Back In - Out actions"; } @@ -511,7 +511,7 @@ void SpriteEaseBackInOut::onEnter() } -std::string SpriteEaseBackInOut::title() const +std::string SpriteEaseBackInOut::subtitle() const { return "EaseBackInOut action"; } @@ -573,7 +573,7 @@ void SpriteEaseBezier::onEnter() } -std::string SpriteEaseBezier::title()const +std::string SpriteEaseBezier::subtitle()const { return "SpriteEaseBezier action"; } @@ -608,7 +608,7 @@ void SpriteEaseQuadratic::onEnter() _kathia->runAction( RepeatForever::create(seq3)); } -std::string SpriteEaseQuadratic::title() const +std::string SpriteEaseQuadratic::subtitle() const { return "SpriteEaseQuadratic action"; } @@ -640,7 +640,7 @@ void SpriteEaseQuadraticInOut::onEnter() _tamara->runAction( RepeatForever::create(seq2)); } -std::string SpriteEaseQuadraticInOut::title()const +std::string SpriteEaseQuadraticInOut::subtitle()const { return "SpriteEaseQuadraticInOut action"; } @@ -676,7 +676,7 @@ void SpriteEaseQuartic::onEnter() _kathia->runAction( RepeatForever::create(seq3)); } -std::string SpriteEaseQuartic::title()const +std::string SpriteEaseQuartic::subtitle()const { return "SpriteEaseQuartic action"; } @@ -708,7 +708,7 @@ void SpriteEaseQuarticInOut::onEnter() _tamara->runAction( RepeatForever::create(seq2)); } -std::string SpriteEaseQuarticInOut::title()const +std::string SpriteEaseQuarticInOut::subtitle()const { return "SpriteEaseQuarticInOut action"; } @@ -743,7 +743,7 @@ void SpriteEaseQuintic::onEnter() _kathia->runAction( RepeatForever::create(seq3)); } -std::string SpriteEaseQuintic::title()const +std::string SpriteEaseQuintic::subtitle()const { return "SpriteEaseQuintic action"; } @@ -776,7 +776,7 @@ void SpriteEaseQuinticInOut::onEnter() _tamara->runAction( RepeatForever::create(seq2)); } -std::string SpriteEaseQuinticInOut::title()const +std::string SpriteEaseQuinticInOut::subtitle()const { return "SpriteEaseQuinticInOut action"; } @@ -811,7 +811,7 @@ void SpriteEaseCircle::onEnter() _kathia->runAction( RepeatForever::create(seq3)); } -std::string SpriteEaseCircle::title()const +std::string SpriteEaseCircle::subtitle()const { return "SpriteEaseCircle action"; } @@ -844,7 +844,7 @@ void SpriteEaseCircleInOut::onEnter() _tamara->runAction( RepeatForever::create(seq2)); } -std::string SpriteEaseCircleInOut::title()const +std::string SpriteEaseCircleInOut::subtitle()const { return "SpriteEaseCircleInOut action"; } @@ -879,7 +879,7 @@ void SpriteEaseCubic::onEnter() _kathia->runAction( RepeatForever::create(seq3)); } -std::string SpriteEaseCubic::title()const +std::string SpriteEaseCubic::subtitle()const { return "SpriteEaseCubic action"; } @@ -964,7 +964,7 @@ void SpeedTest::altertime(float dt) action3->setSpeed( CCRANDOM_MINUS1_1() * 2 ); } -std::string SpeedTest::title() const +std::string SpeedTest::subtitle() const { return "Speed action"; } @@ -1072,7 +1072,7 @@ void EaseSpriteDemo::positionForTwo() } -std::string EaseSpriteDemo::title() const +std::string EaseSpriteDemo::subtitle() const { return "No title"; } diff --git a/tests/Classes/ActionsEaseTest/ActionsEaseTest.h b/tests/Classes/ActionsEaseTest/ActionsEaseTest.h index 9bee8f82c9..f19a4436a8 100644 --- a/tests/Classes/ActionsEaseTest/ActionsEaseTest.h +++ b/tests/Classes/ActionsEaseTest/ActionsEaseTest.h @@ -45,7 +45,7 @@ public: EaseSpriteDemo(void); ~EaseSpriteDemo(void); - virtual std::string title() const override; + virtual std::string subtitle() const override; virtual void onEnter() override; void centerSprites(unsigned int numberOfSprites); @@ -61,7 +61,7 @@ class SpriteEase : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; void testStopAction(float dt); }; @@ -70,126 +70,126 @@ class SpriteEaseInOut : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseExponential : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseExponentialInOut : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseSine : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseSineInOut : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseElastic : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseElasticInOut : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseBounce : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseBounceInOut : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseBack : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseBackInOut : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseBezier : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseQuadratic : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseQuadraticInOut : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseQuartic : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseQuarticInOut : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseQuintic : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseQuinticInOut : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; @@ -197,21 +197,21 @@ class SpriteEaseCircle : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseCircleInOut : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseCubic : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class SpriteEaseCubicInOut : public EaseSpriteDemo @@ -224,7 +224,7 @@ class SpeedTest : public EaseSpriteDemo { public: void onEnter(); - virtual std::string title() const override; + virtual std::string subtitle() const override; void altertime(float dt); }; diff --git a/tests/Classes/LayerTest/LayerTest.cpp b/tests/Classes/LayerTest/LayerTest.cpp index 8e8e2b327a..4597a9a716 100644 --- a/tests/Classes/LayerTest/LayerTest.cpp +++ b/tests/Classes/LayerTest/LayerTest.cpp @@ -78,7 +78,7 @@ std::string LayerTest::subtitle() const std::string LayerTest::title() const { - return "No title"; + return "Layer Test"; } void LayerTest::onEnter() @@ -167,7 +167,7 @@ void LayerTestCascadingOpacityA::onEnter() setEnableRecursiveCascading(this, true); } -std::string LayerTestCascadingOpacityA::title() const +std::string LayerTestCascadingOpacityA::subtitle() const { return "Layer: cascading opacity"; } @@ -219,7 +219,7 @@ void LayerTestCascadingOpacityB::onEnter() setEnableRecursiveCascading(this, true); } -std::string LayerTestCascadingOpacityB::title() const +std::string LayerTestCascadingOpacityB::subtitle() const { return "CCLayerColor: cascading opacity"; } @@ -269,7 +269,7 @@ void LayerTestCascadingOpacityC::onEnter() NULL))); } -std::string LayerTestCascadingOpacityC::title() const +std::string LayerTestCascadingOpacityC::subtitle() const { return "CCLayerColor: non-cascading opacity"; } @@ -323,7 +323,7 @@ void LayerTestCascadingColorA::onEnter() } -std::string LayerTestCascadingColorA::title() const +std::string LayerTestCascadingColorA::subtitle() const { return "Layer: cascading color"; } @@ -375,7 +375,7 @@ void LayerTestCascadingColorB::onEnter() setEnableRecursiveCascading(this, true); } -std::string LayerTestCascadingColorB::title() const +std::string LayerTestCascadingColorB::subtitle() const { return "CCLayerColor: cascading color"; } @@ -424,7 +424,7 @@ void LayerTestCascadingColorC::onEnter() NULL))); } -std::string LayerTestCascadingColorC::title() const +std::string LayerTestCascadingColorC::subtitle() const { return "CCLayerColor: non-cascading color"; } @@ -481,7 +481,7 @@ void LayerTest1::onTouchesEnded(const std::vector& touches, Event *even onTouchesMoved(touches, event); } -std::string LayerTest1::title() const +std::string LayerTest1::subtitle() const { return "ColorLayer resize (tap & move)"; } @@ -517,7 +517,7 @@ void LayerTest2::onEnter() layer2->runAction(seq2); } -std::string LayerTest2::title() const +std::string LayerTest2::subtitle() const { return "ColorLayer: fade and tint"; } @@ -569,7 +569,7 @@ void LayerTestBlend::newBlend(float dt) } -std::string LayerTestBlend::title() const +std::string LayerTestBlend::subtitle() const { return "ColorLayer: blend"; } diff --git a/tests/Classes/LayerTest/LayerTest.h b/tests/Classes/LayerTest/LayerTest.h index 44ba2e4c8e..84c83d6cc9 100644 --- a/tests/Classes/LayerTest/LayerTest.h +++ b/tests/Classes/LayerTest/LayerTest.h @@ -28,7 +28,7 @@ class LayerTestCascadingOpacityA : public LayerTest public: CREATE_FUNC(LayerTestCascadingOpacityA); virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class LayerTestCascadingOpacityB : public LayerTest @@ -36,7 +36,7 @@ class LayerTestCascadingOpacityB : public LayerTest public: CREATE_FUNC(LayerTestCascadingOpacityB); virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class LayerTestCascadingOpacityC : public LayerTest @@ -44,7 +44,7 @@ class LayerTestCascadingOpacityC : public LayerTest public: CREATE_FUNC(LayerTestCascadingOpacityC); virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class LayerTestCascadingColorA : public LayerTest @@ -52,7 +52,7 @@ class LayerTestCascadingColorA : public LayerTest public: CREATE_FUNC(LayerTestCascadingColorA); virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class LayerTestCascadingColorB : public LayerTest @@ -60,7 +60,7 @@ class LayerTestCascadingColorB : public LayerTest public: CREATE_FUNC(LayerTestCascadingColorB); virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class LayerTestCascadingColorC : public LayerTest @@ -68,7 +68,7 @@ class LayerTestCascadingColorC : public LayerTest public: CREATE_FUNC(LayerTestCascadingColorC); virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; @@ -78,7 +78,7 @@ public: CREATE_FUNC(LayerTest1); virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; void updateSize(Point &touchLocation); @@ -92,7 +92,7 @@ class LayerTest2 : public LayerTest public: CREATE_FUNC(LayerTest2); virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; @@ -103,7 +103,7 @@ public: LayerTestBlend(); void newBlend(float dt); - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class LayerGradientTest : public LayerTest diff --git a/tests/Classes/NewRendererTest/NewRendererTest.cpp b/tests/Classes/NewRendererTest/NewRendererTest.cpp index dbbffa9baf..17e78aa0e7 100644 --- a/tests/Classes/NewRendererTest/NewRendererTest.cpp +++ b/tests/Classes/NewRendererTest/NewRendererTest.cpp @@ -91,12 +91,12 @@ MultiSceneTest::~MultiSceneTest() std::string MultiSceneTest::title() const { - return BaseTest::title(); + return "New Renderer"; } std::string MultiSceneTest::subtitle() const { - return BaseTest::subtitle(); + return "MultiSceneTest"; } void MultiSceneTest::onEnter() diff --git a/tests/Classes/NodeTest/NodeTest.cpp b/tests/Classes/NodeTest/NodeTest.cpp index f3e32b6a60..8336b6fbb5 100644 --- a/tests/Classes/NodeTest/NodeTest.cpp +++ b/tests/Classes/NodeTest/NodeTest.cpp @@ -191,7 +191,7 @@ void Test2::onEnter() sp2->runAction(action2); } -std::string Test2::title() const +std::string Test2::subtitle() const { return "anchorPoint and children"; } @@ -233,7 +233,7 @@ void Test4::delay4(float dt) removeChildByTag(3, false); } -std::string Test4::title() const +std::string Test4::subtitle() const { return "tags"; } @@ -286,7 +286,7 @@ void Test5::addAndRemove(float dt) sp2->release(); } -std::string Test5::title() const +std::string Test5::subtitle() const { return "remove and cleanup"; } @@ -347,7 +347,7 @@ void Test6::addAndRemove(float dt) } -std::string Test6::title() const +std::string Test6::subtitle() const { return "remove/cleanup with children"; } @@ -400,7 +400,7 @@ void StressTest1::removeMe(Node* node) } -std::string StressTest1::title() const +std::string StressTest1::subtitle() const { return "stress test #1: no crashes"; } @@ -447,7 +447,7 @@ void StressTest2::shouldNotLeak(float dt) sublayer->removeAllChildrenWithCleanup(true); } -std::string StressTest2::title() const +std::string StressTest2::subtitle() const { return "stress test #2: no leaks"; } @@ -478,7 +478,7 @@ void SchedulerTest1::doSomething(float dt) } -std::string SchedulerTest1::title() const +std::string SchedulerTest1::subtitle() const { return "cocosnode scheduler test #1"; } @@ -517,7 +517,7 @@ NodeToWorld::NodeToWorld() back->runAction(fe2); } -std::string NodeToWorld::title() const +std::string NodeToWorld::subtitle() const { return "nodeToParent transform"; } @@ -566,7 +566,7 @@ NodeToWorld3D::NodeToWorld3D() parent->runAction(orbit); } -std::string NodeToWorld3D::title() const +std::string NodeToWorld3D::subtitle() const { return "nodeToParent transform in 3D"; } @@ -637,7 +637,7 @@ CameraOrbitTest::CameraOrbitTest() setScale( 1 ); } -std::string CameraOrbitTest::title() const +std::string CameraOrbitTest::subtitle() const { return "Camera Orbit test"; } @@ -706,7 +706,7 @@ void CameraZoomTest::update(float dt) // cam->setEye(0, 0, -_z); } -std::string CameraZoomTest::title() const +std::string CameraZoomTest::subtitle() const { return "Camera Zoom test"; } diff --git a/tests/Classes/NodeTest/NodeTest.h b/tests/Classes/NodeTest/NodeTest.h index d30fc391e8..5938eb9a4f 100644 --- a/tests/Classes/NodeTest/NodeTest.h +++ b/tests/Classes/NodeTest/NodeTest.h @@ -52,7 +52,7 @@ class Test2 : public TestCocosNodeDemo public: CREATE_FUNC(Test2); virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class Test4 : public TestCocosNodeDemo @@ -62,7 +62,7 @@ public: void delay2(float dt); void delay4(float dt); - virtual std::string title() const override; + virtual std::string subtitle() const override; protected: Test4(); @@ -74,7 +74,7 @@ public: CREATE_FUNC(Test5); void addAndRemove(float dt); - virtual std::string title() const override; + virtual std::string subtitle() const override; protected: Test5(); @@ -85,7 +85,7 @@ class Test6 : public TestCocosNodeDemo public: CREATE_FUNC(Test6); void addAndRemove(float dt); - virtual std::string title() const override; + virtual std::string subtitle() const override; protected: Test6(); @@ -97,7 +97,7 @@ public: CREATE_FUNC(StressTest1); void shouldNotCrash(float dt); void removeMe(Node* node); - virtual std::string title() const override; + virtual std::string subtitle() const override; protected: StressTest1(); @@ -108,7 +108,7 @@ class StressTest2 : public TestCocosNodeDemo public: CREATE_FUNC(StressTest2); void shouldNotLeak(float dt); - virtual std::string title() const override; + virtual std::string subtitle() const override; protected: StressTest2(); @@ -119,7 +119,7 @@ class SchedulerTest1 : public TestCocosNodeDemo public: CREATE_FUNC(SchedulerTest1); void doSomething(float dt); - virtual std::string title() const override; + virtual std::string subtitle() const override; protected: SchedulerTest1(); @@ -129,7 +129,7 @@ class NodeToWorld : public TestCocosNodeDemo { public: CREATE_FUNC(NodeToWorld); - virtual std::string title() const override; + virtual std::string subtitle() const override; protected: NodeToWorld(); @@ -139,7 +139,7 @@ class NodeToWorld3D : public TestCocosNodeDemo { public: CREATE_FUNC(NodeToWorld3D); - virtual std::string title() const override; + virtual std::string subtitle() const override; protected: NodeToWorld3D(); @@ -151,7 +151,7 @@ public: CREATE_FUNC(CameraOrbitTest); virtual void onEnter() override; virtual void onExit() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; protected: CameraOrbitTest(); @@ -165,7 +165,7 @@ public: virtual void onEnter() override; virtual void onExit() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; protected: CameraZoomTest(); diff --git a/tests/Classes/ParticleTest/ParticleTest.cpp b/tests/Classes/ParticleTest/ParticleTest.cpp index 5ff2d34e6b..91acbfa91a 100644 --- a/tests/Classes/ParticleTest/ParticleTest.cpp +++ b/tests/Classes/ParticleTest/ParticleTest.cpp @@ -27,7 +27,7 @@ void DemoFirework::onEnter() setEmitterPosition(); } -std::string DemoFirework::title() const +std::string DemoFirework::subtitle() const { return "ParticleFireworks"; } @@ -53,7 +53,7 @@ void DemoFire::onEnter() setEmitterPosition(); } -std::string DemoFire::title() const +std::string DemoFire::subtitle() const { return "ParticleFire"; } @@ -76,7 +76,7 @@ void DemoSun::onEnter() setEmitterPosition(); } -std::string DemoSun::title() const +std::string DemoSun::subtitle() const { return "ParticleSun"; } @@ -99,7 +99,7 @@ void DemoGalaxy::onEnter() setEmitterPosition(); } -std::string DemoGalaxy::title() const +std::string DemoGalaxy::subtitle() const { return "ParticleGalaxy"; } @@ -121,7 +121,7 @@ void DemoFlower::onEnter() setEmitterPosition(); } -std::string DemoFlower::title() const +std::string DemoFlower::subtitle() const { return "ParticleFlower"; } @@ -204,7 +204,7 @@ void DemoBigFlower::onEnter() setEmitterPosition(); } -std::string DemoBigFlower::title() const +std::string DemoBigFlower::subtitle() const { return "ParticleBigFlower"; } @@ -288,7 +288,7 @@ void DemoRotFlower::onEnter() setEmitterPosition(); } -std::string DemoRotFlower::title() const +std::string DemoRotFlower::subtitle() const { return "ParticleRotFlower"; } @@ -311,7 +311,7 @@ void DemoMeteor::onEnter() setEmitterPosition(); } -std::string DemoMeteor::title() const +std::string DemoMeteor::subtitle() const { return "ParticleMeteor"; } @@ -334,7 +334,7 @@ void DemoSpiral::onEnter() setEmitterPosition(); } -std::string DemoSpiral::title() const +std::string DemoSpiral::subtitle() const { return "ParticleSpiral"; } @@ -359,7 +359,7 @@ void DemoExplosion::onEnter() setEmitterPosition(); } -std::string DemoExplosion::title() const +std::string DemoExplosion::subtitle() const { return "ParticleExplosion"; } @@ -384,7 +384,7 @@ void DemoSmoke::onEnter() setEmitterPosition(); } -std::string DemoSmoke::title() const +std::string DemoSmoke::subtitle() const { return "ParticleSmoke"; } @@ -432,7 +432,7 @@ void DemoSnow::onEnter() setEmitterPosition(); } -std::string DemoSnow::title() const +std::string DemoSnow::subtitle() const { return "ParticleSnow"; } @@ -459,7 +459,7 @@ void DemoRain::onEnter() setEmitterPosition(); } -std::string DemoRain::title() const +std::string DemoRain::subtitle() const { return "ParticleRain"; } @@ -544,7 +544,7 @@ void DemoModernArt::onEnter() setEmitterPosition(); } -std::string DemoModernArt::title() const +std::string DemoModernArt::subtitle() const { return "Varying size"; } @@ -573,7 +573,7 @@ void DemoRing::onEnter() setEmitterPosition(); } -std::string DemoRing::title() const +std::string DemoRing::subtitle() const { return "Ring Demo"; } @@ -616,7 +616,7 @@ void ParallaxParticle::onEnter() p->runAction(RepeatForever::create(seq)); } -std::string ParallaxParticle::title() const +std::string ParallaxParticle::subtitle() const { return "Parallax + Particles"; } @@ -700,7 +700,7 @@ void RadiusMode1::onEnter() _emitter->setBlendAdditive(false); } -std::string RadiusMode1::title() const +std::string RadiusMode1::subtitle() const { return "Radius Mode: Spiral"; } @@ -784,7 +784,7 @@ void RadiusMode2::onEnter() _emitter->setBlendAdditive(false); } -std::string RadiusMode2::title() const +std::string RadiusMode2::subtitle() const { return "Radius Mode: Semi Circle"; } @@ -1106,7 +1106,7 @@ void ParticleDemo::onEnter(void) std::string ParticleDemo::title() const { - return "No title"; + return "Particle Demo"; } std::string ParticleDemo::subtitle() const diff --git a/tests/Classes/ParticleTest/ParticleTest.h b/tests/Classes/ParticleTest/ParticleTest.h index 42d91981e7..fc328ea3d1 100644 --- a/tests/Classes/ParticleTest/ParticleTest.h +++ b/tests/Classes/ParticleTest/ParticleTest.h @@ -45,112 +45,112 @@ class DemoFirework : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class DemoFire : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class DemoSun : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class DemoGalaxy : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class DemoFlower : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class DemoBigFlower : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class DemoRotFlower : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class DemoMeteor : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class DemoSpiral : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class DemoExplosion : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class DemoSmoke : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class DemoSnow : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class DemoRain : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class DemoModernArt : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class DemoRing : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class ParallaxParticle : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class DemoParticleFromFile : public ParticleDemo @@ -162,7 +162,7 @@ public: _title = file; } virtual void onEnter() override; - virtual std::string title() const override + virtual std::string subtitle() const override { return _title; } @@ -172,14 +172,14 @@ class RadiusMode1 : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class RadiusMode2 : public ParticleDemo { public: virtual void onEnter() override; - virtual std::string title() const override; + virtual std::string subtitle() const override; }; class Issue704 : public ParticleDemo diff --git a/tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id b/tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id index e3d8aeba62..dc9c7fc3e4 100644 --- a/tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id +++ b/tests/Classes/SpriteTest/SpriteTest.cpp.REMOVED.git-id @@ -1 +1 @@ -d381f5336bd2e06ba65eb51a5204c12eebe49c4e \ No newline at end of file +39606c4582eeb2df1285728e81b8f9553a527bc1 \ No newline at end of file diff --git a/tests/Classes/controller.cpp b/tests/Classes/controller.cpp index fbf602c954..ea7ae80d68 100644 --- a/tests/Classes/controller.cpp +++ b/tests/Classes/controller.cpp @@ -3,7 +3,7 @@ #include #include #include - +#include // test inclues #include "AppDelegate.h" #include "BaseTest.h" @@ -111,6 +111,12 @@ static Controller *currentController = nullptr; static Point s_tCurPos = Point::ZERO; +//sleep for t seconds +static void wait(int t) +{ + usleep(t * 1000 * 1000); +} + TestController::TestController() : _beginPos(Point::ZERO) { @@ -337,13 +343,77 @@ void TestController::addConsoleAutoTest() return; } + if(args == "run") + { + for (int i = 0; i < g_testCount; i++) + { + // create the test scene and run it + auto scene = g_aTestNames[i].callback(); + + if (scene) + { + std::string msg("autotest: running test:"); + msg += g_aTestNames[i].test_name; + send(fd, msg.c_str(), strlen(msg.c_str()),0); + send(fd, "\n",1,0); + + currentController = &g_aTestNames[i]; + sched->performFunctionInCocosThread( [&](){ + currentController->callback()->runThisTest(); + currentController->callback()->release(); + } ); + wait(1); + BaseTest* firstTest = app->getCurrentTest(); + if(firstTest == nullptr) + { + continue; + } + std::string t1(""); + t1 += firstTest->subtitle(); + send(fd, t1.c_str(), strlen(t1.c_str()),0); + send(fd, "\n",1,0); + wait(2); + + //printf("rtti:%s", typeid(firstTest).name()); + while(1) + { + //currentTest->nextCallback(nullptr); + sched->performFunctionInCocosThread( [&](){ + BaseTest *t = app->getCurrentTest(); + if(t != nullptr) + { + t->nextCallback(nullptr); + } + } ); + wait(1); + BaseTest * curTest = app->getCurrentTest(); + if(curTest == nullptr) + { + break; + } + std::string title(""); + title += curTest->subtitle(); + send(fd, title.c_str(), strlen(title.c_str()),0); + send(fd, "\n",1,0); + wait(2); + + if(t1 == title) + { + break; + } + + } + } + + } + } + for(int i = 0; i < g_testCount; i++) { if(args == g_aTestNames[i].test_name) { // create the test scene and run it auto scene = g_aTestNames[i].callback(); - if (scene) { std::string msg("autotest: running test:"); From 02bf79f0759e14d635acb083c0f2ecc817394a85 Mon Sep 17 00:00:00 2001 From: heliclei Date: Fri, 28 Feb 2014 23:41:01 +0800 Subject: [PATCH 14/34] fix windows compile error --- tests/Classes/controller.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/Classes/controller.cpp b/tests/Classes/controller.cpp index ea7ae80d68..8ffa816786 100644 --- a/tests/Classes/controller.cpp +++ b/tests/Classes/controller.cpp @@ -3,7 +3,8 @@ #include #include #include -#include +#include +#include // test inclues #include "AppDelegate.h" #include "BaseTest.h" @@ -114,7 +115,8 @@ static Point s_tCurPos = Point::ZERO; //sleep for t seconds static void wait(int t) { - usleep(t * 1000 * 1000); + std::chrono::milliseconds dura( t * 1000 ); + std::this_thread::sleep_for( dura ); } TestController::TestController() From e6d2c4ec731e4b87f79286d32761afe06f430113 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sat, 1 Mar 2014 13:30:20 +0800 Subject: [PATCH 15/34] Refactors Scheduler class. * Timer is an abstract class now. * Adds three new timers ( `TimerTargetSelector`, `TimerTargetCallback`, `TimerScriptHandler`) which are inherited from Timer. * Adds new API 'scheduleCallback` / `unscheduleCallbackForKey', and callback's target could be any classes since we're using `void*` to identify target. * `Scheduler::scheduleCallback` use `std::function`, therefore, it supports passing `lambda`, `member_function` and `global_function`. * The old selector API is still kept since it's very useful when schedule callback is a member function, it doesn't need a `key` to identify the callback function. (+1 squashed commit) * Adds relevant test cases. --- cocos/2d/CCDirector.cpp | 4 +- cocos/2d/CCNode.cpp | 19 +- cocos/2d/CCScheduler.cpp | 397 ++++++++++++------ cocos/2d/CCScheduler.h | 223 ++++++---- cocos/2d/CCScriptSupport.cpp | 4 +- cocos/2d/CCScriptSupport.h | 6 +- cocos/2d/CCTextureCache.cpp | 4 +- tests/Classes/SchedulerTest/SchedulerTest.cpp | 68 ++- tests/Classes/SchedulerTest/SchedulerTest.h | 15 + 9 files changed, 479 insertions(+), 261 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index d5af6ac15b..fb3ddd8d08 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -140,9 +140,7 @@ bool Director::init(void) _scheduler = new Scheduler(); // action manager _actionManager = new ActionManager(); - _scheduler->scheduleUpdate([this](float dt){ - this->_actionManager->update(dt); - }, _actionManager, Scheduler::PRIORITY_SYSTEM, false); + _scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false); _eventDispatcher = new EventDispatcher(); _eventAfterDraw = new EventCustom(EVENT_AFTER_DRAW); diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 49472cf822..581b341e7b 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -1115,7 +1115,7 @@ void Node::setScheduler(Scheduler* scheduler) bool Node::isScheduled(SEL_SCHEDULE selector) { - return _scheduler->isScheduled(this, schedule_selector_to_key(selector)); + return _scheduler->isScheduledForTarget(this, selector); } void Node::scheduleUpdate() @@ -1125,9 +1125,7 @@ void Node::scheduleUpdate() void Node::scheduleUpdateWithPriority(int priority) { - _scheduler->scheduleUpdate([this](float dt){ - this->update(dt); - }, this, priority, !_running); + _scheduler->scheduleUpdateForTarget(this, priority, !_running); } void Node::scheduleUpdateWithPriorityLua(int nHandler, int priority) @@ -1137,14 +1135,13 @@ void Node::scheduleUpdateWithPriorityLua(int nHandler, int priority) #if CC_ENABLE_SCRIPT_BINDING _updateScriptHandler = nHandler; #endif - _scheduler->scheduleUpdate([this](float dt){ - this->update(dt); - }, this, priority, !_running); + + _scheduler->scheduleUpdateForTarget(this, priority, !_running); } void Node::unscheduleUpdate() { - _scheduler->unscheduleUpdate(this); + _scheduler->unscheduleUpdateForTarget(this); #if CC_ENABLE_SCRIPT_BINDING if (_updateScriptHandler) @@ -1170,9 +1167,7 @@ void Node::schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, CCASSERT( selector, "Argument must be non-nil"); CCASSERT( interval >=0, "Argument must be positive"); - _scheduler->schedule([=](float dt){ - (this->*selector)(dt); - }, this, schedule_selector_to_key(selector), interval , repeat, delay, !_running); + _scheduler->scheduleSelector(selector, this, interval , repeat, delay, !_running); } void Node::scheduleOnce(SEL_SCHEDULE selector, float delay) @@ -1186,7 +1181,7 @@ void Node::unschedule(SEL_SCHEDULE selector) if (selector == nullptr) return; - _scheduler->unschedule(this, schedule_selector_to_key(selector)); + _scheduler->unscheduleSelector(selector, this); } void Node::unscheduleAllSelectors() diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index 110f34aad9..9ddb825e18 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -33,28 +33,16 @@ THE SOFTWARE. #include "CCArray.h" #include "CCScriptSupport.h" -using namespace std; - NS_CC_BEGIN -long schedule_selector_to_key(SEL_SCHEDULE selector) -{ - static union{ - SEL_SCHEDULE func; - long key; - }; - func = selector; - return key; -} - // data structures // A list double-linked list used for "updates with priority" typedef struct _listEntry { struct _listEntry *prev, *next; - void *target; ccSchedulerFunc callback; + void *target; int priority; bool paused; bool markedForDeletion; // selector will no longer be called and entry will be removed at end of the next tick @@ -84,65 +72,24 @@ typedef struct _hashSelectorEntry // implementation Timer Timer::Timer() -: _target(nullptr) -, _elapsed(-1) +: _elapsed(-1) , _runForever(false) , _useDelay(false) , _timesExecuted(0) , _repeat(0) , _delay(0.0f) , _interval(0.0f) -, _callback(nullptr) -, _key(0) -#if CC_ENABLE_SCRIPT_BINDING -, _scriptHandler(0) -#endif { } -Timer* Timer::create(const ccSchedulerFunc& callback, void *target, long key, float seconds/* = 0 */) +void Timer::setupTimerWithInterval(float seconds, unsigned int repeat, float delay) { - Timer *timer = new Timer(); - - timer->initWithTarget(callback, target, key, seconds, kRepeatForever, 0.0f); - timer->autorelease(); - - return timer; -} - -#if CC_ENABLE_SCRIPT_BINDING -Timer* Timer::createWithScriptHandler(int handler, float seconds) -{ - Timer *timer = new Timer(); - - timer->initWithScriptHandler(handler, seconds); - timer->autorelease(); - - return timer; -} - -bool Timer::initWithScriptHandler(int handler, float seconds) -{ - _scriptHandler = handler; - _elapsed = -1; - _interval = seconds; - - return true; -} -#endif - -bool Timer::initWithTarget(const ccSchedulerFunc& callback, void *target, long key, float seconds, unsigned int repeat, float delay) -{ - _target = target; - _callback = callback; - _key = key; - _elapsed = -1; - _interval = seconds; - _delay = delay; - _useDelay = (delay > 0.0f) ? true : false; - _repeat = repeat; - _runForever = (repeat == kRepeatForever) ? true : false; - return true; + _elapsed = -1; + _interval = seconds; + _delay = delay; + _useDelay = (_delay > 0.0f) ? true : false; + _repeat = repeat; + _runForever = (_repeat == kRepeatForever) ? true : false; } void Timer::update(float dt) @@ -159,18 +106,8 @@ void Timer::update(float dt) _elapsed += dt; if (_elapsed >= _interval) { - if (_target && _key != 0 && _callback) - { - _callback(_elapsed); - } -#if CC_ENABLE_SCRIPT_BINDING - if (0 != _scriptHandler) - { - SchedulerScriptData data(_scriptHandler,_elapsed); - ScriptEvent event(kScheduleEvent,&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); - } -#endif + trigger(); + _elapsed = 0; } } @@ -181,19 +118,8 @@ void Timer::update(float dt) { if( _elapsed >= _delay ) { - if (_target && _key != 0 && _callback) - { - _callback(_elapsed); - } - -#if CC_ENABLE_SCRIPT_BINDING - if (0 != _scriptHandler) - { - SchedulerScriptData data(_scriptHandler,_elapsed); - ScriptEvent event(kScheduleEvent,&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); - } -#endif + trigger(); + _elapsed = _elapsed - _delay; _timesExecuted += 1; _useDelay = false; @@ -203,19 +129,7 @@ void Timer::update(float dt) { if (_elapsed >= _interval) { - if (_target && _key != 0 && _callback) - { - _callback(_elapsed); - } - -#if CC_ENABLE_SCRIPT_BINDING - if (0 != _scriptHandler) - { - SchedulerScriptData data(_scriptHandler,_elapsed); - ScriptEvent event(kScheduleEvent,&data); - ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); - } -#endif + trigger(); _elapsed = 0; _timesExecuted += 1; @@ -225,12 +139,106 @@ void Timer::update(float dt) if (!_runForever && _timesExecuted > _repeat) { //unschedule timer - Director::getInstance()->getScheduler()->unschedule(_target, _key); + cancel(); } } } } + +// TimerTargetSelector + +TimerTargetSelector::TimerTargetSelector() +: _target(nullptr) +, _selector(nullptr) +{ +} + +bool TimerTargetSelector::initWithSelector(SEL_SCHEDULE selector, Ref* target, float seconds, unsigned int repeat, float delay) +{ + _target = target; + _selector = selector; + setupTimerWithInterval(seconds, repeat, delay); + return true; +} + +void TimerTargetSelector::trigger() +{ + if (_target && _selector) + { + (_target->*_selector)(_elapsed); + } +} + +void TimerTargetSelector::cancel() +{ + Director::getInstance()->getScheduler()->unscheduleSelector(_selector, _target); +} + +// TimerTargetCallback + +TimerTargetCallback::TimerTargetCallback() +: _target(nullptr) +, _callback(nullptr) +{ +} + +bool TimerTargetCallback::initWithLambda(const ccSchedulerFunc& callback, void *target, const std::string& key, float seconds, unsigned int repeat, float delay) +{ + _target = target; + _callback = callback; + _key = key; + setupTimerWithInterval(seconds, repeat, delay); + return true; +} + +void TimerTargetCallback::trigger() +{ + if (_callback) + { + _callback(_elapsed); + } +} + +void TimerTargetCallback::cancel() +{ + Director::getInstance()->getScheduler()->unscheduleCallbackForKey(_key, _target); +} + +#if CC_ENABLE_SCRIPT_BINDING + +// TimerScriptHandler + +bool TimerScriptHandler::initWithScriptHandler(int handler, float seconds) +{ + _scriptHandler = handler; + _elapsed = -1; + _interval = seconds; + + return true; +} + +void TimerScriptHandler::trigger() +{ + if (0 != _scriptHandler) + { + SchedulerScriptData data(_scriptHandler,_elapsed); + ScriptEvent event(kScheduleEvent,&data); + ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event); + } +} + +void TimerScriptHandler::cancel() +{ + if (0 != _scriptHandler) + { + ScriptEngineManager::getInstance()->getScriptEngine()->removeScriptHandler(_scriptHandler); + _scriptHandler = 0; + } +} + +#endif + // implementation of Scheduler // Priority level reserved for system services. @@ -269,15 +277,15 @@ void Scheduler::removeHashElement(_hashSelectorEntry *element) free(element); } -void Scheduler::schedule(const ccSchedulerFunc& callback, void *target, long key, float interval, bool paused) +void Scheduler::scheduleCallback(const ccSchedulerFunc& callback, void *target, const std::string& key, float interval, bool paused) { - this->schedule(callback, target, key, interval, kRepeatForever, 0.0f, paused); + this->scheduleCallback(callback, target, key, interval, kRepeatForever, 0.0f, paused); } -void Scheduler::schedule(const ccSchedulerFunc& callback, void *target, long key, float interval, unsigned int repeat, float delay, bool paused) +void Scheduler::scheduleCallback(const ccSchedulerFunc& callback, void *target, const std::string& key, float interval, unsigned int repeat, float delay, bool paused) { CCASSERT(target, "Argument target must be non-nullptr"); - CCASSERT(key != 0, "key should not be empty!"); + CCASSERT(!key.empty(), "key should not be empty!"); tHashTimerEntry *element = nullptr; HASH_FIND_PTR(_hashForTimers, &target, element); @@ -305,7 +313,7 @@ void Scheduler::schedule(const ccSchedulerFunc& callback, void *target, long key { for (int i = 0; i < element->timers->num; ++i) { - Timer *timer = (Timer*)element->timers->arr[i]; + TimerTargetCallback *timer = static_cast(element->timers->arr[i]); if (key == timer->getKey()) { @@ -317,16 +325,16 @@ void Scheduler::schedule(const ccSchedulerFunc& callback, void *target, long key ccArrayEnsureExtraCapacity(element->timers, 1); } - Timer *timer = new Timer(); - timer->initWithTarget(callback, target, key, interval, repeat, delay); + TimerTargetCallback *timer = new TimerTargetCallback(); + timer->initWithLambda(callback, target, key, interval, repeat, delay); ccArrayAppendObject(element->timers, timer); timer->release(); } -void Scheduler::unschedule(void *target, long key) +void Scheduler::unscheduleCallbackForKey(const std::string &key, void *target) { // explicity handle nil arguments when removing an object - if (target == nullptr || key == 0) + if (target == nullptr || key.empty()) { return; } @@ -341,7 +349,7 @@ void Scheduler::unschedule(void *target, long key) { for (int i = 0; i < element->timers->num; ++i) { - Timer *timer = static_cast(element->timers->arr[i]); + TimerTargetCallback *timer = static_cast(element->timers->arr[i]); if (key == timer->getKey()) { @@ -453,7 +461,7 @@ void Scheduler::appendIn(_listEntry **list, const ccSchedulerFunc& callback, voi HASH_ADD_PTR(_hashForUpdates, target, hashElement); } -void Scheduler::scheduleUpdate(const ccSchedulerFunc& callback, void *target, int priority, bool paused) +void Scheduler::scheduleCallbackPerFrame(const ccSchedulerFunc& callback, void *target, int priority, bool paused) { tHashUpdateEntry *hashElement = nullptr; HASH_FIND_PTR(_hashForUpdates, &target, hashElement); @@ -485,9 +493,9 @@ void Scheduler::scheduleUpdate(const ccSchedulerFunc& callback, void *target, in } } -bool Scheduler::isScheduled(void *target, long key) +bool Scheduler::isScheduledForKey(const std::string& key, void *target) { - CCASSERT(key != 0, "Argument key must be empty"); + CCASSERT(!key.empty(), "Argument key must not be empty"); CCASSERT(target, "Argument target must be non-nullptr"); tHashTimerEntry *element = nullptr; @@ -501,11 +509,12 @@ bool Scheduler::isScheduled(void *target, long key) if (element->timers == nullptr) { return false; - }else + } + else { for (int i = 0; i < element->timers->num; ++i) { - Timer *timer = (Timer*)element->timers->arr[i]; + TimerTargetCallback *timer = static_cast(element->timers->arr[i]); if (key == timer->getKey()) { @@ -536,7 +545,7 @@ void Scheduler::removeUpdateFromHash(struct _listEntry *entry) } } -void Scheduler::unscheduleUpdate(void* target) +void Scheduler::unscheduleUpdateForTarget(void *target) { if (target == nullptr) { @@ -585,7 +594,7 @@ void Scheduler::unscheduleAllWithMinPriority(int minPriority) { if(entry->priority >= minPriority) { - unscheduleUpdate(entry->target); + unscheduleUpdateForTarget(entry->target); } } } @@ -594,7 +603,7 @@ void Scheduler::unscheduleAllWithMinPriority(int minPriority) { DL_FOREACH_SAFE(_updates0List, entry, tmp) { - unscheduleUpdate(entry->target); + unscheduleUpdateForTarget(entry->target); } } @@ -602,7 +611,7 @@ void Scheduler::unscheduleAllWithMinPriority(int minPriority) { if(entry->priority >= minPriority) { - unscheduleUpdate(entry->target); + unscheduleUpdateForTarget(entry->target); } } #if CC_ENABLE_SCRIPT_BINDING @@ -643,7 +652,7 @@ void Scheduler::unscheduleAllForTarget(void *target) } // update selector - unscheduleUpdate(target); + unscheduleUpdateForTarget(target); } #if CC_ENABLE_SCRIPT_BINDING @@ -959,38 +968,146 @@ void Scheduler::update(float dt) } } -//OLD METHODS: void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Ref *target, float interval, unsigned int repeat, float delay, bool paused) { - target->retain(); - this->schedule([=](float dt){ - (target->*selector)(dt); - }, target, schedule_selector_to_key(selector), interval , repeat, delay, paused); + CCASSERT(target, "Argument target must be non-nullptr"); + + tHashTimerEntry *element = nullptr; + HASH_FIND_PTR(_hashForTimers, &target, element); + + if (! element) + { + element = (tHashTimerEntry *)calloc(sizeof(*element), 1); + element->target = target; + + HASH_ADD_PTR(_hashForTimers, target, element); + + // Is this the 1st element ? Then set the pause level to all the selectors of this target + element->paused = paused; + } + else + { + CCASSERT(element->paused == paused, ""); + } + + if (element->timers == nullptr) + { + element->timers = ccArrayNew(10); + } + else + { + for (int i = 0; i < element->timers->num; ++i) + { + TimerTargetSelector *timer = static_cast(element->timers->arr[i]); + + if (selector == timer->getSelector()) + { + CCLOG("CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f", timer->getInterval(), interval); + timer->setInterval(interval); + return; + } + } + ccArrayEnsureExtraCapacity(element->timers, 1); + } + + TimerTargetSelector *timer = new TimerTargetSelector(); + timer->initWithSelector(selector, target, interval, repeat, delay); + ccArrayAppendObject(element->timers, timer); + timer->release(); } void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Ref *target, float interval, bool paused) { - target->retain(); - this->schedule([=](float dt){ - (target->*selector)(dt); - }, target, schedule_selector_to_key(selector), interval, paused); + this->scheduleSelector(selector, target, interval, kRepeatForever, 0.0f, paused); } -bool Scheduler::isScheduledForTarget(SEL_SCHEDULE selector, Ref *target) +bool Scheduler::isScheduledForSelector(SEL_SCHEDULE selector, Ref *target) { - return this->isScheduled(target, schedule_selector_to_key(selector)); + CCASSERT(selector, "Argument selector must be non-nullptr"); + CCASSERT(target, "Argument target must be non-nullptr"); + + tHashTimerEntry *element = nullptr; + HASH_FIND_PTR(_hashForTimers, &target, element); + + if (!element) + { + return false; + } + + if (element->timers == nullptr) + { + return false; + } + else + { + for (int i = 0; i < element->timers->num; ++i) + { + TimerTargetSelector *timer = static_cast(element->timers->arr[i]); + + if (selector == timer->getSelector()) + { + return true; + } + } + + return false; + } + + return false; // should never get here } void Scheduler::unscheduleSelector(SEL_SCHEDULE selector, Ref *target) { - this->unschedule(target, schedule_selector_to_key(selector)); - target->release(); + // explicity handle nil arguments when removing an object + if (target == nullptr || selector == nullptr) + { + return; + } + + //CCASSERT(target); + //CCASSERT(selector); + + tHashTimerEntry *element = nullptr; + HASH_FIND_PTR(_hashForTimers, &target, element); + + if (element) + { + for (int i = 0; i < element->timers->num; ++i) + { + TimerTargetSelector *timer = static_cast(element->timers->arr[i]); + + if (selector == timer->getSelector()) + { + if (timer == element->currentTimer && (! element->currentTimerSalvaged)) + { + element->currentTimer->retain(); + element->currentTimerSalvaged = true; + } + + ccArrayRemoveObjectAtIndex(element->timers, i, true); + + // update timerIndex in case we are in tick:, looping over the actions + if (element->timerIndex >= i) + { + element->timerIndex--; + } + + if (element->timers->num == 0) + { + if (_currentTarget == element) + { + _currentTargetSalvaged = true; + } + else + { + removeHashElement(element); + } + } + + return; + } + } + } } -void Scheduler::unscheduleUpdateForTarget(Ref *target) -{ - this->unscheduleUpdate(target); - target->release(); -}; - NS_CC_END diff --git a/cocos/2d/CCScheduler.h b/cocos/2d/CCScheduler.h index 6c4306d449..2a3d8fabdb 100644 --- a/cocos/2d/CCScheduler.h +++ b/cocos/2d/CCScheduler.h @@ -43,8 +43,6 @@ NS_CC_BEGIN * @{ */ -long schedule_selector_to_key(SEL_SCHEDULE selector); - typedef std::function ccSchedulerFunc; // // Timer @@ -53,46 +51,24 @@ typedef std::function ccSchedulerFunc; // class CC_DLL Timer : public Ref { +protected: + Timer(); public: - /** Allocates a timer with a target, a selector and an interval in seconds. */ - static Timer* create(const ccSchedulerFunc& callback, void *target, long key, float seconds = 0.0f); - -#if CC_ENABLE_SCRIPT_BINDING - /** Allocates a timer with a script callback function and an interval in seconds. - * @js NA - * @lua NA - */ - static Timer* createWithScriptHandler(int handler, float seconds); - - /** Initializes a timer with a script callback function and an interval in seconds. */ - bool initWithScriptHandler(int handler, float seconds); -#endif - - Timer(void); - - /** Initializes a timer with a target, a selector and an interval in seconds, repeat in number of times to repeat, delay in seconds. */ - bool initWithTarget(const ccSchedulerFunc& callback, void *target, long key, float seconds, unsigned int repeat, float delay); - /** get interval in seconds */ inline float getInterval() const { return _interval; }; /** set interval in seconds */ inline void setInterval(float interval) { _interval = interval; }; - /** - * @js NA - * @lua NA - */ - inline const ccSchedulerFunc& getCallback() const { return _callback; }; - inline long getKey() const { return _key; }; + + void setupTimerWithInterval(float seconds, unsigned int repeat, float delay); + + virtual void trigger() = 0; + virtual void cancel() = 0; /** triggers the timer */ void update(float dt); -#if CC_ENABLE_SCRIPT_BINDING - inline int getScriptHandler() const { return _scriptHandler; }; -#endif - protected: - void *_target; + float _elapsed; bool _runForever; bool _useDelay; @@ -100,13 +76,69 @@ protected: unsigned int _repeat; //0 = once, 1 is 2 x executed float _delay; float _interval; - ccSchedulerFunc _callback; - long _key; -#if CC_ENABLE_SCRIPT_BINDING - int _scriptHandler; -#endif }; + +class CC_DLL TimerTargetSelector : public Timer +{ +public: + TimerTargetSelector(); + + /** Initializes a timer with a target, a selector and an interval in seconds, repeat in number of times to repeat, delay in seconds. */ + bool initWithSelector(SEL_SCHEDULE selector, Ref* target, float seconds, unsigned int repeat, float delay); + + inline SEL_SCHEDULE getSelector() const { return _selector; }; + + virtual void trigger() override; + virtual void cancel() override; + +protected: + Ref* _target; + SEL_SCHEDULE _selector; +}; + + +class CC_DLL TimerTargetCallback : public Timer +{ +public: + TimerTargetCallback(); + + /** Initializes a timer with a target, a lambda and an interval in seconds, repeat in number of times to repeat, delay in seconds. */ + bool initWithLambda(const ccSchedulerFunc& callback, void *target, const std::string& key, float seconds, unsigned int repeat, float delay); + + /** + * @js NA + * @lua NA + */ + inline const ccSchedulerFunc& getCallback() const { return _callback; }; + inline const std::string& getKey() const { return _key; }; + + virtual void trigger() override; + virtual void cancel() override; + +protected: + void* _target; + ccSchedulerFunc _callback; + std::string _key; +}; + +#if CC_ENABLE_SCRIPT_BINDING + +class CC_DLL TimerScriptHandler : public Timer +{ +public: + bool initWithScriptHandler(int handler, float seconds); + inline int getScriptHandler() const { return _scriptHandler; }; + + virtual void trigger() override; + virtual void cancel() override; + +private: + int _scriptHandler; +}; + +#endif + // // Scheduler // @@ -145,7 +177,7 @@ public: * @js NA * @lua NA */ - ~Scheduler(void); + virtual ~Scheduler(); inline float getTimeScale() { return _timeScale; } /** Modifies the time of all scheduled callbacks. @@ -164,50 +196,39 @@ public: */ void update(float dt); + // schedule / unschedule 'callback'. Added from v3.0-final + /** The scheduled method will be called every 'interval' seconds. If paused is true, then it won't be called until it is resumed. If 'interval' is 0, it will be called every frame, but if so, it's recommended to use 'scheduleUpdateForTarget:' instead. - If the selector is already scheduled, then only the interval parameter will be updated without re-scheduling it again. + If the 'callback' is already scheduled, then only the interval parameter will be updated without re-scheduling it again. repeat let the action be repeated repeat + 1 times, use kRepeatForever to let the action run continuously delay is the amount of time the action will wait before it'll start - + @param key The key to identify the callback @since v3.0 */ - void schedule(const ccSchedulerFunc& callback, void *target, long key, float interval, unsigned int repeat, float delay, bool paused); + void scheduleCallback(const ccSchedulerFunc& callback, void *target, const std::string& key, float interval, unsigned int repeat, float delay, bool paused); - /** calls scheduleSelector with kRepeatForever and a 0 delay */ - void schedule(const ccSchedulerFunc& callback, void *target, long key, float interval, bool paused); - - /** Schedules the 'update' selector for a given target with a given priority. - The 'update' selector will be called every frame. - The lower the priority, the earlier it is called. + /** Calls scheduleCallback with kRepeatForever and a 0 delay @since v3.0 */ - void scheduleUpdate(const ccSchedulerFunc& callback, void *target, int priority, bool paused); + void scheduleCallback(const ccSchedulerFunc& callback, void *target, const std::string& key, float interval, bool paused); - /** Checks whether a selector for a given taget is scheduled. + /** Checks whether a callback associated with 'key' and 'target' is scheduled. @since v3.0.0 */ - bool isScheduled(void *target, long key); + bool isScheduledForKey(const std::string& key, void *target); - /** Unschedule a selector for a given target. - If you want to unschedule the "update", use unscheudleUpdateForTarget. + /** Unschedules a callback for a key and a given target. + If you want to unschedule the 'callbackPerFrame', use unscheduleUpdate. @since v3.0 */ - void unschedule(void *target, long key); + void unscheduleCallbackForKey(const std::string& key, void *target); - /** Unschedules the update selector for a given target - @since v3.0 - */ - void unscheduleUpdate(void *target); - - /** Unschedules all selectors for a given target. - This also includes the "update" selector. - @since v3.0 - */ - void unscheduleAllForTarget(void *target); - - // OLD METHODS + ///////////////////////////////////// + + // schedule / unschedule 'selector' + /** The scheduled method will be called every 'interval' seconds. If paused is true, then it won't be called until it is resumed. If 'interval' is 0, it will be called every frame, but if so, it's recommended to use 'scheduleUpdateForTarget:' instead. @@ -222,36 +243,59 @@ public: /** calls scheduleSelector with kRepeatForever and a 0 delay */ void scheduleSelector(SEL_SCHEDULE selector, Ref *target, float interval, bool paused); - template - void scheduleUpdateForTarget(T *target, int priority, bool paused) - { - target->retain(); - this->scheduleUpdate([=](float dt){ - target->update(dt); - }, target, priority, paused); - } - - /** Checks whether a selector for a given taget is scheduled. - @since v3.0.0 - */ - bool isScheduledForTarget(SEL_SCHEDULE selector, Ref *target); - /** Unschedule a selector for a given target. If you want to unschedule the "update", use unscheudleUpdateForTarget. @since v0.99.3 */ void unscheduleSelector(SEL_SCHEDULE selector, Ref *target); + /** Checks whether a selector for a given taget is scheduled. + @since v0.99.3 + */ + CC_DEPRECATED_ATTRIBUTE bool isScheduledForTarget(Ref *target, SEL_SCHEDULE selector) { return isScheduledForSelector(selector, target); }; + + /** Checks whether a selector for a given taget is scheduled. + @since v3.0 + */ + bool isScheduledForSelector(SEL_SCHEDULE selector, Ref *target); + + ///////////////////////////////////// + + // schedule / unschedule 'update' + + /** Schedules the 'update' selector for a given target with a given priority. + The 'update' selector will be called every frame. + The lower the priority, the earlier it is called. + @since v0.99.3 + @lua NA + */ + template + void scheduleUpdateForTarget(T *target, int priority, bool paused) + { + this->scheduleCallbackPerFrame([target](float dt){ + target->update(dt); + }, target, priority, paused); + } + /** Unschedules the update selector for a given target @since v0.99.3 */ - void unscheduleUpdateForTarget(Ref *target); + void unscheduleUpdateForTarget(void *target); - /// + ///////////////////////////////////// + + // unschedule all + + /** Unschedules all selectors for a given target. + This also includes the "update" selector. + @since v0.99.3 + @js unscheduleCallbackForTarget + @lua NA + */ + void unscheduleAllForTarget(void *target); /** Unschedules all selectors from all targets. You should NEVER call this method, unless you know what you are doing. - @since v0.99.3 */ void unscheduleAll(void); @@ -262,6 +306,9 @@ public: */ void unscheduleAllWithMinPriority(int minPriority); + ///////////////////////////////////// + + // schedule / unschedule for script bindings #if CC_ENABLE_SCRIPT_BINDING /** The scheduled script callback will be called every 'interval' seconds. If paused is true, then it won't be called until it is resumed. @@ -273,6 +320,9 @@ public: /** Unschedule a script entry. */ void unscheduleScriptEntry(unsigned int scheduleScriptEntryID); #endif + + ///////////////////////////////////// + /** Pauses the target. All scheduled selectors/update for a given target won't be 'ticked' until the target is resumed. If the target is not present, nothing happens. @@ -319,6 +369,15 @@ public: void performFunctionInCocosThread( const std::function &function); protected: + + /** Schedules the 'callback' function for a given target with a given priority. + The 'callback' selector will be called every frame. + The lower the priority, the earlier it is called. + @note This method is only for internal use. + @since v3.0 + */ + void scheduleCallbackPerFrame(const ccSchedulerFunc& callback, void *target, int priority, bool paused); + void removeHashElement(struct _hashSelectorEntry *element); void removeUpdateFromHash(struct _listEntry *entry); diff --git a/cocos/2d/CCScriptSupport.cpp b/cocos/2d/CCScriptSupport.cpp index 36ec7a2db8..78cd476547 100644 --- a/cocos/2d/CCScriptSupport.cpp +++ b/cocos/2d/CCScriptSupport.cpp @@ -74,10 +74,8 @@ SchedulerScriptHandlerEntry* SchedulerScriptHandlerEntry::create(int handler, fl bool SchedulerScriptHandlerEntry::init(float interval, bool paused) { - _timer = new Timer(); + _timer = new TimerScriptHandler(); _timer->initWithScriptHandler(_handler, interval); - _timer->autorelease(); - _timer->retain(); _paused = paused; LUALOG("[LUA] ADD script schedule: %d, entryID: %d", _handler, _entryId); return true; diff --git a/cocos/2d/CCScriptSupport.h b/cocos/2d/CCScriptSupport.h index aa49828ad5..ab0f002803 100644 --- a/cocos/2d/CCScriptSupport.h +++ b/cocos/2d/CCScriptSupport.h @@ -42,7 +42,7 @@ typedef struct lua_State lua_State; NS_CC_BEGIN -class Timer; +class TimerScriptHandler; class Layer; class MenuItem; class CallFunc; @@ -108,7 +108,7 @@ public: * @js NA * @lua NA */ - cocos2d::Timer* getTimer(void) { + TimerScriptHandler* getTimer(void) { return _timer; } /** @@ -143,7 +143,7 @@ private: } bool init(float interval, bool paused); - cocos2d::Timer* _timer; + TimerScriptHandler* _timer; bool _paused; bool _markedForDeletion; }; diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index e22f0645e8..aaa9ccfb4a 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -123,7 +123,7 @@ void TextureCache::addImageAsync(const std::string &path, std::functiongetScheduler()->schedule(CC_CALLBACK_1(TextureCache::addImageAsyncCallBack, this), this, schedule_selector_to_key(schedule_selector(TextureCache::addImageAsyncCallBack)), 0, false); + Director::getInstance()->getScheduler()->scheduleSelector(schedule_selector(TextureCache::addImageAsyncCallBack), this, 0, false); } ++_asyncRefCount; @@ -277,7 +277,7 @@ void TextureCache::addImageAsyncCallBack(float dt) --_asyncRefCount; if (0 == _asyncRefCount) { - Director::getInstance()->getScheduler()->unschedule(this, schedule_selector_to_key(schedule_selector(TextureCache::addImageAsyncCallBack))); + Director::getInstance()->getScheduler()->unscheduleSelector(schedule_selector(TextureCache::addImageAsyncCallBack), this); } } } diff --git a/tests/Classes/SchedulerTest/SchedulerTest.cpp b/tests/Classes/SchedulerTest/SchedulerTest.cpp index ec2dd5ece4..22ffdfe82a 100644 --- a/tests/Classes/SchedulerTest/SchedulerTest.cpp +++ b/tests/Classes/SchedulerTest/SchedulerTest.cpp @@ -27,7 +27,8 @@ static std::function createFunctions[] = { CL(SchedulerUpdateFromCustom), CL(RescheduleSelector), CL(SchedulerDelayAndRepeat), - CL(SchedulerIssue2268) + CL(SchedulerIssue2268), + CL(ScheduleCallbackTest) }; #define MAX_LAYER (sizeof(createFunctions) / sizeof(createFunctions[0])) @@ -430,9 +431,7 @@ void SchedulerUnscheduleAllHard::onExit() if(!_actionManagerActive) { // Restore the director's action manager. auto director = Director::getInstance(); - director->getScheduler()->scheduleUpdate([director](float dt){ - director->getActionManager()->update(dt); - }, director->getActionManager(), Scheduler::PRIORITY_SYSTEM, false); + director->getScheduler()->scheduleUpdateForTarget(director->getActionManager(), Scheduler::PRIORITY_SYSTEM, false); } SchedulerTestLayer::onExit(); @@ -966,15 +965,11 @@ void TwoSchedulers::onEnter() // Create a new scheduler, and link it to the main scheduler sched1 = new Scheduler(); - defaultScheduler->scheduleUpdate([this](float dt){ - this->sched1->update(dt); - }, sched1, 0, false); + defaultScheduler->scheduleUpdateForTarget(sched1, 0, false); // Create a new ActionManager, and link it to the new scheudler actionManager1 = new ActionManager(); - sched1->scheduleUpdate([this](float dt){ - this->actionManager1->update(dt); - }, actionManager1, 0, false); + sched1->scheduleUpdateForTarget(actionManager1, 0, false); for( unsigned int i=0; i < 10; i++ ) { @@ -996,15 +991,11 @@ void TwoSchedulers::onEnter() // Create a new scheduler, and link it to the main scheduler sched2 = new Scheduler();; - defaultScheduler->scheduleUpdate([this](float dt){ - this->sched2->update(dt); - }, sched2, 0, false); + defaultScheduler->scheduleUpdateForTarget(sched2, 0, false); // Create a new ActionManager, and link it to the new scheudler actionManager2 = new ActionManager(); - sched2->scheduleUpdate([this](float dt){ - this->actionManager2->update(dt); - }, actionManager2, 0, false); + sched2->scheduleUpdateForTarget(actionManager2, 0, false); for( unsigned int i=0; i < 10; i++ ) { auto sprite = Sprite::create("Images/grossinis_sister2.png"); @@ -1112,6 +1103,51 @@ std::string SchedulerIssue2268::subtitle() const { return "Should not crash"; } + +// ScheduleCallbackTest + +ScheduleCallbackTest::~ScheduleCallbackTest() +{ + +} + +std::string ScheduleCallbackTest::title() const +{ + return "ScheduleCallbackTest"; +} + +std::string ScheduleCallbackTest::subtitle() const +{ + return "\n\n\n\nPlease see console.\n\ +scheduleCallback(lambda, ...)\n\ +scheduleCallback(CC_CALLBACK_1(XXX::member_function), this), this, ...)\n\ +scheduleCallback(global_function, ...)\n\ +"; +} + +static void ScheduleCallbackTest_global_callback(float dt) +{ + log("In the callback of scheduleCallback(global_function, ...), dt = %f", dt); +} + +void ScheduleCallbackTest::onEnter() +{ + SchedulerTestLayer::onEnter(); + + _scheduler->scheduleCallback([](float dt){ + log("In the callback of scheduleCallback(lambda, ...), dt = %f", dt); + }, this, "lambda", 1.0f, false); + + _scheduler->scheduleCallback(CC_CALLBACK_1(ScheduleCallbackTest::callback, this), this, "member_function", 1.0f, false); + + _scheduler->scheduleCallback(ScheduleCallbackTest_global_callback, this, "global_function", 1.0f, false); +} + +void ScheduleCallbackTest::callback(float dt) +{ + log("In the callback of scheduleCallback(CC_CALLBACK_1(XXX::member_function), this), this, ...), dt = %f", dt); +} + //------------------------------------------------------------------ // // SchedulerTestScene diff --git a/tests/Classes/SchedulerTest/SchedulerTest.h b/tests/Classes/SchedulerTest/SchedulerTest.h index f07ea8a730..57efb807a9 100644 --- a/tests/Classes/SchedulerTest/SchedulerTest.h +++ b/tests/Classes/SchedulerTest/SchedulerTest.h @@ -287,6 +287,21 @@ private: Node *testNode; }; +class ScheduleCallbackTest : public SchedulerTestLayer +{ +public: + CREATE_FUNC(ScheduleCallbackTest); + + ~ScheduleCallbackTest(); + virtual std::string title() const override; + virtual std::string subtitle() const override; + void onEnter(); + + void callback(float dt); + +private: +}; + class SchedulerTestScene : public TestScene { public: From 4f90676e923a5ad69fcdbad9e3e2eaf77a9ae2d9 Mon Sep 17 00:00:00 2001 From: cai wenzhi Date: Sat, 1 Mar 2014 22:34:25 +0800 Subject: [PATCH 16/34] Add method for editor --- cocos/gui/UIButton.cpp | 20 +++++++++++++ cocos/gui/UIButton.h | 8 ++++++ cocos/gui/UIImageView.cpp | 10 +++++++ cocos/gui/UIImageView.h | 4 +++ cocos/gui/UILayout.cpp | 57 ++++++++++++++++++++++++++++++++++++++ cocos/gui/UILayout.h | 36 ++++++++++++++++++++++++ cocos/gui/UIListView.cpp | 5 ++++ cocos/gui/UIListView.h | 2 ++ cocos/gui/UILoadingBar.cpp | 10 +++++++ cocos/gui/UILoadingBar.h | 4 +++ cocos/gui/UIScrollView.cpp | 40 ++++++++++++++++++++++++++ cocos/gui/UIScrollView.h | 16 +++++++++++ cocos/gui/UISlider.cpp | 15 ++++++++++ cocos/gui/UISlider.h | 6 ++++ cocos/gui/UIText.cpp | 25 +++++++++++++++++ cocos/gui/UIText.h | 15 +++++++++- cocos/gui/UITextField.cpp | 25 +++++++++++++++++ cocos/gui/UITextField.h | 5 ++++ 18 files changed, 302 insertions(+), 1 deletion(-) diff --git a/cocos/gui/UIButton.cpp b/cocos/gui/UIButton.cpp index 82ed33dfec..3d08a6f2e3 100644 --- a/cocos/gui/UIButton.cpp +++ b/cocos/gui/UIButton.cpp @@ -152,6 +152,11 @@ void Button::setScale9Enabled(bool able) setCapInsetsDisabledRenderer(_capInsetsDisabled); setBright(_bright); } + +bool Button::isScale9Enabled() +{ + return _scale9Enabled; +} void Button::ignoreContentAdaptWithSize(bool ignore) { @@ -326,6 +331,11 @@ void Button::setCapInsetsNormalRenderer(const Rect &capInsets) } static_cast(_buttonNormalRenderer)->setCapInsets(capInsets); } + +const Rect& Button::getCapInsetsNormalRenderer() +{ + return _capInsetsNormal; +} void Button::setCapInsetsPressedRenderer(const Rect &capInsets) { @@ -336,6 +346,11 @@ void Button::setCapInsetsPressedRenderer(const Rect &capInsets) } static_cast(_buttonClickedRenderer)->setCapInsets(capInsets); } + +const Rect& Button::getCapInsetsPressedRenderer() +{ + return _capInsetsPressed; +} void Button::setCapInsetsDisabledRenderer(const Rect &capInsets) { @@ -346,6 +361,11 @@ void Button::setCapInsetsDisabledRenderer(const Rect &capInsets) } static_cast(_buttonDisableRenderer)->setCapInsets(capInsets); } + +const Rect& Button::getCapInsetsDisabledRenderer() +{ + return _capInsetsDisabled; +} void Button::onPressStateChangedToNormal() { diff --git a/cocos/gui/UIButton.h b/cocos/gui/UIButton.h index c2f7bf30a4..71f624d975 100644 --- a/cocos/gui/UIButton.h +++ b/cocos/gui/UIButton.h @@ -107,6 +107,8 @@ public: */ void setCapInsetsNormalRenderer(const Rect &capInsets); + const Rect& getCapInsetsNormalRenderer(); + /** * Sets capinsets for button, if button is using scale9 renderer. * @@ -114,6 +116,8 @@ public: */ void setCapInsetsPressedRenderer(const Rect &capInsets); + const Rect& getCapInsetsPressedRenderer(); + /** * Sets capinsets for button, if button is using scale9 renderer. * @@ -121,6 +125,8 @@ public: */ void setCapInsetsDisabledRenderer(const Rect &capInsets); + const Rect& getCapInsetsDisabledRenderer(); + //override "setAnchorPoint" of widget. virtual void setAnchorPoint(const Point &pt) override; @@ -131,6 +137,8 @@ public: */ virtual void setScale9Enabled(bool able); + bool isScale9Enabled(); + //override "setFlipX" of widget. virtual void setFlipX(bool flipX) override; diff --git a/cocos/gui/UIImageView.cpp b/cocos/gui/UIImageView.cpp index a77dee73e0..86be041024 100644 --- a/cocos/gui/UIImageView.cpp +++ b/cocos/gui/UIImageView.cpp @@ -206,6 +206,11 @@ void ImageView::setScale9Enabled(bool able) } setCapInsets(_capInsets); } + +bool ImageView::isScale9Enabled() +{ + return _scale9Enabled; +} void ImageView::ignoreContentAdaptWithSize(bool ignore) { @@ -226,6 +231,11 @@ void ImageView::setCapInsets(const Rect &capInsets) STATIC_CAST_SCALE9SPRITE->setCapInsets(capInsets); } +const Rect& ImageView::getCapInsets() +{ + return _capInsets; +} + void ImageView::setAnchorPoint(const Point &pt) { Widget::setAnchorPoint(pt); diff --git a/cocos/gui/UIImageView.h b/cocos/gui/UIImageView.h index df373a67a9..017dab5572 100644 --- a/cocos/gui/UIImageView.h +++ b/cocos/gui/UIImageView.h @@ -75,6 +75,8 @@ public: */ void setScale9Enabled(bool able); + bool isScale9Enabled(); + /** * Sets capinsets for imageview, if imageview is using scale9 renderer. * @@ -82,6 +84,8 @@ public: */ void setCapInsets(const Rect &capInsets); + const Rect& getCapInsets(); + //override "setFlipX" method of widget. virtual void setFlipX(bool flipX) override; diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp index e72d105f30..82d01821e4 100644 --- a/cocos/gui/UILayout.cpp +++ b/cocos/gui/UILayout.cpp @@ -153,6 +153,23 @@ void Layout::addChild(Node *child, int zOrder, int tag) Widget::addChild(child, zOrder, tag); _doLayoutDirty = true; } + +void Layout::removeChild(Node *child, bool cleanup) +{ + Widget::removeChild(child, cleanup); + _doLayoutDirty = true; +} + +void Layout::removeAllChildren() +{ + Widget::removeAllChildren(); +} + +void Layout::removeAllChildrenWithCleanup(bool cleanup) +{ + Widget::removeAllChildrenWithCleanup(cleanup); + _doLayoutDirty = true; +} bool Layout::isClippingEnabled() { @@ -408,6 +425,11 @@ void Layout::setClippingType(LayoutClippingType type) setClippingEnabled(clippingEnabled); } +LayoutClippingType Layout::getClippingType() +{ + return _clippingType; +} + void Layout::setStencilClippingSize(const Size &size) { if (_clippingEnabled && _clippingType == LAYOUT_CLIPPING_STENCIL) @@ -620,6 +642,11 @@ void Layout::setBackGroundImageCapInsets(const Rect &capInsets) static_cast(_backGroundImage)->setCapInsets(capInsets); } } + +const Rect& Layout::getBackGroundImageCapInsets() +{ + return _backGroundImageCapInsets; +} void Layout::supplyTheLayoutParameterLackToChild(Widget *child) { @@ -747,6 +774,11 @@ void Layout::setBackGroundColorType(LayoutBackGroundColorType type) break; } } + +LayoutBackGroundColorType Layout::getBackGroundColorType() +{ + return _colorType; +} void Layout::setBackGroundColor(const Color3B &color) { @@ -756,6 +788,11 @@ void Layout::setBackGroundColor(const Color3B &color) _colorRender->setColor(color); } } + +const Color3B& Layout::getBackGroundColor() +{ + return _cColor; +} void Layout::setBackGroundColor(const Color3B &startColor, const Color3B &endColor) { @@ -770,6 +807,16 @@ void Layout::setBackGroundColor(const Color3B &startColor, const Color3B &endCol _gradientRender->setEndColor(endColor); } } + +const Color3B& Layout::getBackGroundStartColor() +{ + return _gStartColor; +} + +const Color3B& Layout::getBackGroundEndColor() +{ + return _gEndColor; +} void Layout::setBackGroundColorOpacity(int opacity) { @@ -788,6 +835,11 @@ void Layout::setBackGroundColorOpacity(int opacity) break; } } + +int Layout::getBackGroundColorOpacity() +{ + return _cOpacity; +} void Layout::setBackGroundColorVector(const Point &vector) { @@ -797,6 +849,11 @@ void Layout::setBackGroundColorVector(const Point &vector) _gradientRender->setVector(vector); } } + +const Point& Layout::getBackGroundColorVector() +{ + return _alongVector; +} const Size& Layout::getBackGroundImageTextureSize() const { diff --git a/cocos/gui/UILayout.h b/cocos/gui/UILayout.h index 13f7ac1e36..8d876d86e1 100644 --- a/cocos/gui/UILayout.h +++ b/cocos/gui/UILayout.h @@ -91,6 +91,8 @@ public: */ void setBackGroundImageCapInsets(const Rect& capInsets); + const Rect& getBackGroundImageCapInsets(); + /** * Sets Color Type for layout. * @@ -98,6 +100,8 @@ public: */ void setBackGroundColorType(LayoutBackGroundColorType type); + LayoutBackGroundColorType getBackGroundColorType(); + /** * Sets background iamge use scale9 renderer. * @@ -105,6 +109,8 @@ public: */ void setBackGroundImageScale9Enabled(bool enabled); + bool isBackGroundImageScale9Enabled(); + /** * Sets background color for layout, if color type is LAYOUT_COLOR_SOLID * @@ -112,6 +118,8 @@ public: */ void setBackGroundColor(const Color3B &color); + const Color3B& getBackGroundColor(); + /** * Sets background color for layout, if color type is LAYOUT_COLOR_GRADIENT * @@ -121,6 +129,10 @@ public: */ void setBackGroundColor(const Color3B &startColor, const Color3B &endColor); + const Color3B& getBackGroundStartColor(); + + const Color3B& getBackGroundEndColor(); + /** * Sets background opacity layout. * @@ -128,6 +140,8 @@ public: */ void setBackGroundColorOpacity(int opacity); + int getBackGroundColorOpacity(); + /** * Sets background color vector for layout, if color type is LAYOUT_COLOR_GRADIENT * @@ -135,6 +149,8 @@ public: */ void setBackGroundColorVector(const Point &vector); + const Point& getBackGroundColorVector(); + /** * Remove the background image of layout. */ @@ -158,6 +174,8 @@ public: void setClippingType(LayoutClippingType type); + LayoutClippingType getClippingType(); + /** * Gets if layout is clipping enabled. * @@ -209,6 +227,24 @@ public: */ virtual void addChild(Node* child, int zOrder, int tag) override; + virtual void removeChild(Node* child, bool cleanup = true) override; + + /** + * Removes all children from the container with a cleanup. + * + * @see `removeAllChildrenWithCleanup(bool)` + */ + virtual void removeAllChildren() override; + /** + * Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter. + * + * @param cleanup true if all running actions on all children nodes should be cleanup, false oterwise. + * @js removeAllChildren + * @lua removeAllChildren + */ + virtual void removeAllChildrenWithCleanup(bool cleanup) override; + + virtual void visit(); virtual void sortAllChildren() override; diff --git a/cocos/gui/UIListView.cpp b/cocos/gui/UIListView.cpp index 8c732f6e70..a447f46bbe 100644 --- a/cocos/gui/UIListView.cpp +++ b/cocos/gui/UIListView.cpp @@ -347,6 +347,11 @@ void ListView::setItemsMargin(float margin) _itemsMargin = margin; _refreshViewDirty = true; } + +float ListView::getItemsMargin() +{ + return _itemsMargin; +} void ListView::setDirection(SCROLLVIEW_DIR dir) { diff --git a/cocos/gui/UIListView.h b/cocos/gui/UIListView.h index 2a6b2df848..3458b5fd48 100644 --- a/cocos/gui/UIListView.h +++ b/cocos/gui/UIListView.h @@ -150,6 +150,8 @@ public: */ void setItemsMargin(float margin); + float getItemsMargin(); + virtual void sortAllChildren() override; ssize_t getCurSelectedIndex() const; diff --git a/cocos/gui/UILoadingBar.cpp b/cocos/gui/UILoadingBar.cpp index 15ade85aef..542b3fa016 100644 --- a/cocos/gui/UILoadingBar.cpp +++ b/cocos/gui/UILoadingBar.cpp @@ -196,6 +196,11 @@ void LoadingBar::setScale9Enabled(bool enabled) setCapInsets(_capInsets); } +bool LoadingBar::isScale9Enabled() +{ + return _scale9Enabled; +} + void LoadingBar::setCapInsets(const Rect &capInsets) { _capInsets = capInsets; @@ -206,6 +211,11 @@ void LoadingBar::setCapInsets(const Rect &capInsets) static_cast(_barRenderer)->setCapInsets(capInsets); } +const Rect& LoadingBar::getCapInsets() +{ + return _capInsets; +} + void LoadingBar::setPercent(int percent) { if ( percent < 0 || percent > 100) diff --git a/cocos/gui/UILoadingBar.h b/cocos/gui/UILoadingBar.h index b0305951d5..d8b69aa83a 100644 --- a/cocos/gui/UILoadingBar.h +++ b/cocos/gui/UILoadingBar.h @@ -106,6 +106,8 @@ public: */ void setScale9Enabled(bool enabled); + bool isScale9Enabled(); + /** * Sets capinsets for loadingbar, if loadingbar is using scale9 renderer. * @@ -113,6 +115,8 @@ public: */ void setCapInsets(const Rect &capInsets); + const Rect& getCapInsets(); + //override "ignoreContentAdaptWithSize" method of widget. virtual void ignoreContentAdaptWithSize(bool ignore) override; diff --git a/cocos/gui/UIScrollView.cpp b/cocos/gui/UIScrollView.cpp index 8bb23aae8d..553491d408 100644 --- a/cocos/gui/UIScrollView.cpp +++ b/cocos/gui/UIScrollView.cpp @@ -273,6 +273,46 @@ Widget* ScrollView::getChildByName(const char *name) { return _innerContainer->getChildByName(name); } + +void ScrollView::addNode(Node* node) +{ + Layout::addNode(node); +} + +void ScrollView::addNode(Node * node, int zOrder) +{ + Layout::addNode(node, zOrder); +} + +void ScrollView::addNode(Node* node, int zOrder, int tag) +{ + _innerContainer->addNode(node, zOrder, tag); +} + +Node* ScrollView::getNodeByTag(int tag) +{ + return _innerContainer->getNodeByTag(tag); +} + +Vector& ScrollView::getNodes() +{ + return _innerContainer->getNodes(); +} + +void ScrollView::removeNode(Node* node) +{ + _innerContainer->removeNode(node); +} + +void ScrollView::removeNodeByTag(int tag) +{ + _innerContainer->removeNodeByTag(tag); +} + +void ScrollView::removeAllNodes() +{ + _innerContainer->removeAllNodes(); +} void ScrollView::moveChildren(float offsetX, float offsetY) { diff --git a/cocos/gui/UIScrollView.h b/cocos/gui/UIScrollView.h index 0b196cef55..6cb3a554fc 100644 --- a/cocos/gui/UIScrollView.h +++ b/cocos/gui/UIScrollView.h @@ -274,6 +274,22 @@ public: virtual Widget* getChildByName(const char* name) override; + virtual void addNode(Node* node) override; + + virtual void addNode(Node * node, int zOrder) override; + + virtual void addNode(Node* node, int zOrder, int tag) override; + + virtual Node * getNodeByTag(int tag) override; + + virtual Vector& getNodes() override; + + virtual void removeNode(Node* node) override; + + virtual void removeNodeByTag(int tag) override; + + virtual void removeAllNodes() override; + virtual bool onTouchBegan(Touch *touch, Event *unusedEvent) override; virtual void onTouchMoved(Touch *touch, Event *unusedEvent) override; virtual void onTouchEnded(Touch *touch, Event *unusedEvent) override; diff --git a/cocos/gui/UISlider.cpp b/cocos/gui/UISlider.cpp index d138def5a3..e5557b6cbf 100644 --- a/cocos/gui/UISlider.cpp +++ b/cocos/gui/UISlider.cpp @@ -216,6 +216,11 @@ void Slider::setScale9Enabled(bool able) setCapInsetsBarRenderer(_capInsetsBarRenderer); setCapInsetProgressBarRebderer(_capInsetsProgressBarRenderer); } + +bool Slider::isScale9Enabled() +{ + return _scale9Enabled; +} void Slider::ignoreContentAdaptWithSize(bool ignore) { @@ -241,6 +246,11 @@ void Slider::setCapInsetsBarRenderer(const Rect &capInsets) } static_cast(_barRenderer)->setCapInsets(capInsets); } + +const Rect& Slider::getCapInsetsBarRenderer() +{ + return _capInsetsBarRenderer; +} void Slider::setCapInsetProgressBarRebderer(const Rect &capInsets) { @@ -251,6 +261,11 @@ void Slider::setCapInsetProgressBarRebderer(const Rect &capInsets) } static_cast(_progressBarRenderer)->setCapInsets(capInsets); } + +const Rect& Slider::getCapInsetsProgressBarRebderer() +{ + return _capInsetsProgressBarRenderer; +} void Slider::loadSlidBallTextures(const char* normal,const char* pressed,const char* disabled,TextureResType texType) { diff --git a/cocos/gui/UISlider.h b/cocos/gui/UISlider.h index bc952ede15..9f2f175200 100644 --- a/cocos/gui/UISlider.h +++ b/cocos/gui/UISlider.h @@ -77,6 +77,8 @@ public: */ void setScale9Enabled(bool able); + bool isScale9Enabled(); + /** * Sets capinsets for slider, if slider is using scale9 renderer. * @@ -91,6 +93,8 @@ public: */ void setCapInsetsBarRenderer(const Rect &capInsets); + const Rect& getCapInsetsBarRenderer(); + /** * Sets capinsets for slider, if slider is using scale9 renderer. * @@ -98,6 +102,8 @@ public: */ void setCapInsetProgressBarRebderer(const Rect &capInsets); + const Rect& getCapInsetsProgressBarRebderer(); + /** * Load textures for slider ball. * diff --git a/cocos/gui/UIText.cpp b/cocos/gui/UIText.cpp index 13b014fe66..274b28b140 100644 --- a/cocos/gui/UIText.cpp +++ b/cocos/gui/UIText.cpp @@ -98,6 +98,11 @@ void Text::setFontSize(int size) _labelRenderer->setFontSize(size); labelScaleChangedWithSize(); } + +int Text::getFontSize() +{ + return _fontSize; +} void Text::setFontName(const std::string& name) { @@ -105,24 +110,44 @@ void Text::setFontName(const std::string& name) _labelRenderer->setFontName(name); labelScaleChangedWithSize(); } + +const std::string& Text::getFontName() +{ + return _fontName; +} void Text::setTextAreaSize(const Size &size) { _labelRenderer->setDimensions(size); labelScaleChangedWithSize(); } + +const Size& Text::getTextAreaSize() +{ + return _labelRenderer->getDimensions(); +} void Text::setTextHorizontalAlignment(TextHAlignment alignment) { _labelRenderer->setHorizontalAlignment(alignment); labelScaleChangedWithSize(); } + +TextHAlignment Text::getTextHorizontalAlignment() +{ + return _labelRenderer->getHorizontalAlignment(); +} void Text::setTextVerticalAlignment(TextVAlignment alignment) { _labelRenderer->setVerticalAlignment(alignment); labelScaleChangedWithSize(); } + +TextVAlignment Text::getTextVerticalAlignment() +{ + return _labelRenderer->getVerticalAlignment(); +} void Text::setTouchScaleChangeEnabled(bool enable) { diff --git a/cocos/gui/UIText.h b/cocos/gui/UIText.h index 44d558151a..03dc895727 100644 --- a/cocos/gui/UIText.h +++ b/cocos/gui/UIText.h @@ -81,6 +81,8 @@ public: */ void setFontSize(int size); + int getFontSize(); + /** * Sets the font name of label. * @@ -88,6 +90,8 @@ public: */ void setFontName(const std::string& name); + const std::string& getFontName(); + /** * Sets the touch scale enabled of label. * @@ -157,8 +161,17 @@ public: virtual std::string getDescription() const override; void setTextAreaSize(const Size &size); + + const Size& getTextAreaSize(); + void setTextHorizontalAlignment(TextHAlignment alignment); - void setTextVerticalAlignment(TextVAlignment alignment); + + TextHAlignment getTextHorizontalAlignment(); + + void setTextVerticalAlignment(TextVAlignment alignment); + + TextVAlignment getTextVerticalAlignment(); + protected: virtual bool init() override; virtual void initRenderer() override; diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index c463293006..23fffb831e 100644 --- a/cocos/gui/UITextField.cpp +++ b/cocos/gui/UITextField.cpp @@ -319,6 +319,11 @@ void TextField::setTouchSize(const Size &size) _touchWidth = size.width; _touchHeight = size.height; } + +Size TextField::getTouchSize() +{ + return Size(_touchWidth, _touchHeight); +} void TextField::setText(const std::string& text) { @@ -345,18 +350,33 @@ void TextField::setPlaceHolder(const std::string& value) _textFieldRenderer->setPlaceHolder(value); textfieldRendererScaleChangedWithSize(); } + +const std::string& TextField::getPlaceHolder() +{ + return _textFieldRenderer->getPlaceHolder(); +} void TextField::setFontSize(int size) { _textFieldRenderer->setFontSize(size); textfieldRendererScaleChangedWithSize(); } + +int TextField::getFontSize() +{ + return _textFieldRenderer->getFontSize(); +} void TextField::setFontName(const std::string& name) { _textFieldRenderer->setFontName(name); textfieldRendererScaleChangedWithSize(); } + +const std::string& TextField::getFontName() +{ + return _textFieldRenderer->getFontName(); +} void TextField::didNotSelectSelf() { @@ -414,6 +434,11 @@ void TextField::setPasswordStyleText(const char *styleText) _passwordStyleText = styleText; } + +const char* TextField::getPasswordStyleText() +{ + return _passwordStyleText.c_str(); +} void TextField::update(float dt) { diff --git a/cocos/gui/UITextField.h b/cocos/gui/UITextField.h index 1f01103592..1fc3d2cc0b 100644 --- a/cocos/gui/UITextField.h +++ b/cocos/gui/UITextField.h @@ -108,10 +108,14 @@ public: virtual ~TextField(); static TextField* create(); void setTouchSize(const Size &size); + Size getTouchSize(); void setText(const std::string& text); void setPlaceHolder(const std::string& value); + const std::string& getPlaceHolder(); void setFontSize(int size); + int getFontSize(); void setFontName(const std::string& name); + const std::string& getFontName(); virtual void didNotSelectSelf(); const std::string& getStringValue(); virtual bool onTouchBegan(Touch *touch, Event *unusedEvent) override; @@ -122,6 +126,7 @@ public: void setPasswordEnabled(bool enable); bool isPasswordEnabled(); void setPasswordStyleText(const char* styleText); + const char* getPasswordStyleText(); virtual void update(float dt) override; bool getAttachWithIME(); void setAttachWithIME(bool attach); From 30d7130eb02603e3431c586d872cbc3ea7b9688d Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 2 Mar 2014 16:16:03 +0800 Subject: [PATCH 17/34] closed #4160: Out of range exception in EventDispatcher --- cocos/2d/CCEventDispatcher.cpp | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 13b4b35224..ccdb174725 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -479,9 +479,18 @@ void EventDispatcher::removeEventListener(EventListener* listener) auto sceneGraphPriorityListeners = listeners->getSceneGraphPriorityListeners(); removeListenerInVector(sceneGraphPriorityListeners); - if (!isFound) + if (isFound) + { + // fixed #4160: Dirty flag need to be updated after listeners were removed. + setDirty(listener->getListenerID(), DirtyFlag::SCENE_GRAPH_PRIORITY); + } + else { removeListenerInVector(fixedPriorityListeners); + if (isFound) + { + setDirty(listener->getListenerID(), DirtyFlag::FIXED_PRIORITY); + } } if (iter->second->empty()) @@ -554,14 +563,18 @@ void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, s // priority < 0 if (fixedPriorityListeners) { - bool isEmpty = fixedPriorityListeners->empty(); - for (; !isEmpty && i < listeners->getGt0Index(); ++i) + CCASSERT(listeners->getGt0Index() <= fixedPriorityListeners->size(), "Out of range exception!"); + + if (!fixedPriorityListeners->empty()) { - auto l = fixedPriorityListeners->at(i); - if (!l->isPaused() && l->isRegistered() && onEvent(l)) + for (; i < listeners->getGt0Index(); ++i) { - shouldStopPropagation = true; - break; + auto l = fixedPriorityListeners->at(i); + if (!l->isPaused() && l->isRegistered() && onEvent(l)) + { + shouldStopPropagation = true; + break; + } } } } @@ -1082,12 +1095,15 @@ void EventDispatcher::removeEventListenersForListenerID(const EventListener::Lis removeAllListenersInVector(sceneGraphPriorityListeners); removeAllListenersInVector(fixedPriorityListeners); + // Remove the dirty flag according the 'listenerID'. + // No need to check whether the dispatcher is dispatching event. + _priorityDirtyFlagMap.erase(listenerID); + if (!_inDispatch) { listeners->clear(); delete listeners; _listenerMap.erase(listenerItemIter); - _priorityDirtyFlagMap.erase(listenerID); } } From 23f15ed9b547866e39d511af3dab3cd638cfa73b Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 2 Mar 2014 16:22:57 +0800 Subject: [PATCH 18/34] closed #4160: Adds test case for issue 4160. --- .../NewEventDispatcherTest.cpp | 70 ++++++++++++++----- .../NewEventDispatcherTest.h | 12 ++++ 2 files changed, 66 insertions(+), 16 deletions(-) diff --git a/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index c9f1f403d3..2464d7b40f 100644 --- a/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -25,6 +25,7 @@ std::function createFunctions[] = CL(GlobalZTouchTest), CL(StopPropagationTest), CL(Issue4129), + CL(Issue4160) }; unsigned int TEST_CASE_COUNT = sizeof(createFunctions) / sizeof(createFunctions[0]); @@ -231,12 +232,11 @@ public: TouchableSpriteWithFixedPriority() : _listener(nullptr) , _fixedPriority(0) - , _useNodePriority(false) + , _removeListenerOnTouchEnded(false) { } - void setPriority(int fixedPriority) { _fixedPriority = fixedPriority; _useNodePriority = false; }; - void setPriorityWithThis(bool useNodePriority) { _useNodePriority = useNodePriority; _fixedPriority = true; } + void setPriority(int fixedPriority) { _fixedPriority = fixedPriority; }; void onEnter() override { @@ -259,22 +259,17 @@ public: return false; }; - listener->onTouchMoved = [=](Touch* touch, Event* event){ - //this->setPosition(this->getPosition() + touch->getDelta()); - }; - listener->onTouchEnded = [=](Touch* touch, Event* event){ this->setColor(Color3B::WHITE); + + if (_removeListenerOnTouchEnded) + { + _eventDispatcher->removeEventListener(listener); + } }; - if (_useNodePriority) - { - _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); - } - else - { - _eventDispatcher->addEventListenerWithFixedPriority(listener, _fixedPriority); - } + _eventDispatcher->addEventListenerWithFixedPriority(listener, _fixedPriority); + _listener = listener; } @@ -285,10 +280,12 @@ public: Sprite::onExit(); } + void removeListenerOnTouchEnded(bool toRemove) { _removeListenerOnTouchEnded = toRemove; }; + private: EventListener* _listener; int _fixedPriority; - bool _useNodePriority; + bool _removeListenerOnTouchEnded; }; void FixedPriorityTest::onEnter() @@ -1090,6 +1087,7 @@ std::string StopPropagationTest::subtitle() const return "Shouldn't crash and only blue block could be clicked"; } +// Issue4129 Issue4129::Issue4129() : _bugFixed(false) { @@ -1152,3 +1150,43 @@ std::string Issue4129::subtitle() const { return "Should see 'Yeah, this issue was fixed.'"; } + +// Issue4160 +Issue4160::Issue4160() +{ + Point origin = Director::getInstance()->getVisibleOrigin(); + Size size = Director::getInstance()->getVisibleSize(); + + auto sprite1 = TouchableSpriteWithFixedPriority::create(); + sprite1->setTexture("Images/CyanSquare.png"); + sprite1->setPriority(-30); + sprite1->setPosition(origin+Point(size.width/2, size.height/2) + Point(-80, 40)); + addChild(sprite1, -10); + + auto sprite2 = TouchableSpriteWithFixedPriority::create(); + sprite2->setTexture("Images/MagentaSquare.png"); + sprite2->setPriority(-20); + sprite2->removeListenerOnTouchEnded(true); + sprite2->setPosition(origin+Point(size.width/2, size.height/2)); + addChild(sprite2, -20); + + auto sprite3 = TouchableSpriteWithFixedPriority::create(); + sprite3->setTexture("Images/YellowSquare.png"); + sprite3->setPriority(-10); + sprite3->setPosition(Point(0, 0)); + sprite2->addChild(sprite3, -1); +} + +Issue4160::~Issue4160() +{ +} + +std::string Issue4160::title() const +{ + return "Issue 4160: Out of range exception"; +} + +std::string Issue4160::subtitle() const +{ + return "Touch the red block twice \n should not crash and the red one couldn't be touched"; +} diff --git a/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h b/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h index 90b48bf22d..4392998358 100644 --- a/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h +++ b/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h @@ -180,5 +180,17 @@ private: bool _bugFixed; }; +class Issue4160 : public EventDispatcherTestDemo +{ +public: + CREATE_FUNC(Issue4160); + Issue4160(); + virtual ~Issue4160(); + + virtual std::string title() const override; + virtual std::string subtitle() const override; + +private: +}; #endif /* defined(__samples__NewEventDispatcherTest__) */ From f3949e078b4a08807ee449f09d100d8a6d05f193 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 2 Mar 2014 15:54:36 +0800 Subject: [PATCH 19/34] [EventDispatcher] Adds 'pauseEventListenersForTarget', 'resumeEventListenersForTarget' and 'removeEventListenersForTarget'. --- cocos/2d/CCEventDispatcher.cpp | 51 ++++++-- cocos/2d/CCEventDispatcher.h | 40 ++++-- cocos/2d/CCNode.cpp | 8 +- .../NewEventDispatcherTest.cpp | 123 ++++++++++++++---- .../NewEventDispatcherTest.h | 13 ++ 5 files changed, 185 insertions(+), 50 deletions(-) diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index ccdb174725..10776fbe20 100644 --- a/cocos/2d/CCEventDispatcher.cpp +++ b/cocos/2d/CCEventDispatcher.cpp @@ -267,9 +267,9 @@ void EventDispatcher::visitTarget(Node* node, bool isRootNode) } } -void EventDispatcher::pauseTarget(Node* node) +void EventDispatcher::pauseEventListenersForTarget(Node* target, bool recursive/* = false */) { - auto listenerIter = _nodeListenersMap.find(node); + auto listenerIter = _nodeListenersMap.find(target); if (listenerIter != _nodeListenersMap.end()) { auto listeners = listenerIter->second; @@ -278,11 +278,20 @@ void EventDispatcher::pauseTarget(Node* node) l->setPaused(true); } } + + if (recursive) + { + const auto& children = target->getChildren(); + for (const auto& child : children) + { + pauseEventListenersForTarget(child, true); + } + } } -void EventDispatcher::resumeTarget(Node* node) +void EventDispatcher::resumeEventListenersForTarget(Node* target, bool recursive/* = false */) { - auto listenerIter = _nodeListenersMap.find(node); + auto listenerIter = _nodeListenersMap.find(target); if (listenerIter != _nodeListenersMap.end()) { auto listeners = listenerIter->second; @@ -291,12 +300,21 @@ void EventDispatcher::resumeTarget(Node* node) l->setPaused(false); } } - setDirtyForNode(node); + setDirtyForNode(target); + + if (recursive) + { + const auto& children = target->getChildren(); + for (const auto& child : children) + { + resumeEventListenersForTarget(child, true); + } + } } -void EventDispatcher::cleanTarget(Node* node) +void EventDispatcher::removeEventListenersForTarget(Node* target, bool recursive/* = false */) { - auto listenerIter = _nodeListenersMap.find(node); + auto listenerIter = _nodeListenersMap.find(target); if (listenerIter != _nodeListenersMap.end()) { auto listeners = listenerIter->second; @@ -306,6 +324,15 @@ void EventDispatcher::cleanTarget(Node* node) removeEventListener(l); } } + + if (recursive) + { + const auto& children = target->getChildren(); + for (const auto& child : children) + { + removeEventListenersForTarget(child, true); + } + } } void EventDispatcher::associateNodeAndEventListener(Node* node, EventListener* listener) @@ -389,7 +416,7 @@ void EventDispatcher::forceAddEventListener(EventListener* listener) if (node->isRunning()) { - resumeTarget(node); + resumeEventListenersForTarget(node); } } else @@ -430,7 +457,7 @@ void EventDispatcher::addEventListenerWithFixedPriority(EventListener* listener, addEventListener(listener); } -EventListenerCustom* EventDispatcher::addCustomEventListener(const std::string &eventName, std::function callback) +EventListenerCustom* EventDispatcher::addCustomEventListener(const std::string &eventName, const std::function& callback) { EventListenerCustom *listener = EventListenerCustom::create(eventName, callback); addEventListenerWithFixedPriority(listener, 1); @@ -443,7 +470,7 @@ void EventDispatcher::removeEventListener(EventListener* listener) return; bool isFound = false; - + auto removeListenerInVector = [&](std::vector* listeners){ if (listeners == nullptr) return; @@ -553,7 +580,7 @@ void EventDispatcher::setPriority(EventListener* listener, int fixedPriority) } } -void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, std::function onEvent) +void EventDispatcher::dispatchEventToListeners(EventListenerVector* listeners, const std::function& onEvent) { bool shouldStopPropagation = false; auto fixedPriorityListeners = listeners->getFixedPriorityListeners(); @@ -1121,7 +1148,7 @@ void EventDispatcher::removeEventListenersForListenerID(const EventListener::Lis } } -void EventDispatcher::removeEventListeners(EventListener::Type listenerType) +void EventDispatcher::removeEventListenersForType(EventListener::Type listenerType) { if (listenerType == EventListener::Type::TOUCH_ONE_BY_ONE) { diff --git a/cocos/2d/CCEventDispatcher.h b/cocos/2d/CCEventDispatcher.h index 9e9077159d..1178cb8444 100644 --- a/cocos/2d/CCEventDispatcher.h +++ b/cocos/2d/CCEventDispatcher.h @@ -56,6 +56,8 @@ dispatched. class EventDispatcher : public Ref { public: + // Adds event listener + /** Adds a event listener for a specified event with the priority of scene graph. * @param listener The listener of a specified event. * @param node The priority of the listener is based on the draw order of this node. @@ -76,22 +78,41 @@ public: It will use a fixed priority of 1. @return the generated event. Needed in order to remove the event from the dispather */ - EventListenerCustom* addCustomEventListener(const std::string &eventName, std::function callback); + EventListenerCustom* addCustomEventListener(const std::string &eventName, const std::function& callback); + ///////////////////////////////////////////// + + // Removes event listener + /** Remove a listener * @param listener The specified event listener which needs to be removed. */ void removeEventListener(EventListener* listener); /** Removes all listeners with the same event listener type */ - void removeEventListeners(EventListener::Type listenerType); + void removeEventListenersForType(EventListener::Type listenerType); + /** Removes all listeners which are associated with the specified target. */ + void removeEventListenersForTarget(Node* target, bool recursive = false); + /** Removes all custom listeners with the same event name */ void removeCustomEventListeners(const std::string& customEventName); /** Removes all listeners */ void removeAllEventListeners(); + ///////////////////////////////////////////// + + // Pauses / Resumes event listener + + /** Pauses all listeners which are associated the specified target. */ + void pauseEventListenersForTarget(Node* target, bool recursive = false); + + /** Resumes all listeners which are associated the specified target. */ + void resumeEventListenersForTarget(Node* target, bool recursive = false); + + ///////////////////////////////////////////// + /** Sets listener's priority with fixed value. */ void setPriority(EventListener* listener, int fixedPriority); @@ -101,6 +122,8 @@ public: /** Checks whether dispatching events is enabled */ bool isEnabled() const; + ///////////////////////////////////////////// + /** Dispatches the event * Also removes all EventListeners marked for deletion from the * event dispatcher list. @@ -110,6 +133,8 @@ public: /** Dispatches a Custom Event with a event name an optional user data */ void dispatchCustomEvent(const std::string &eventName, void *optionalUserData = nullptr); + ///////////////////////////////////////////// + /** Constructor of EventDispatcher */ EventDispatcher(); /** Destructor of EventDispatcher */ @@ -121,15 +146,6 @@ protected: /** Sets the dirty flag for a node. */ void setDirtyForNode(Node* node); - /** Notifys event dispatcher that the node has been paused. */ - void pauseTarget(Node* node); - - /** Notifys event dispatcher that the node has been resumed. */ - void resumeTarget(Node* node); - - /** Notifys event dispatcher that the node has been deleted. */ - void cleanTarget(Node* node); - /** * The vector to store event listeners with scene graph based priority and fixed priority. */ @@ -202,7 +218,7 @@ protected: void dissociateNodeAndEventListener(Node* node, EventListener* listener); /** Dispatches event to listeners with a specified listener type */ - void dispatchEventToListeners(EventListenerVector* listeners, std::function onEvent); + void dispatchEventToListeners(EventListenerVector* listeners, const std::function& onEvent); /// Priority dirty flag enum class DirtyFlag diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 49472cf822..9bf31270c1 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -156,7 +156,7 @@ Node::~Node() CC_SAFE_RELEASE(_actionManager); CC_SAFE_RELEASE(_scheduler); - _eventDispatcher->cleanTarget(this); + _eventDispatcher->removeEventListenersForTarget(this); CC_SAFE_RELEASE(_eventDispatcher); // attributes @@ -1050,7 +1050,7 @@ void Node::setEventDispatcher(EventDispatcher* dispatcher) { if (dispatcher != _eventDispatcher) { - _eventDispatcher->cleanTarget(this); + _eventDispatcher->removeEventListenersForTarget(this); CC_SAFE_RETAIN(dispatcher); CC_SAFE_RELEASE(_eventDispatcher); _eventDispatcher = dispatcher; @@ -1198,14 +1198,14 @@ void Node::resume() { _scheduler->resumeTarget(this); _actionManager->resumeTarget(this); - _eventDispatcher->resumeTarget(this); + _eventDispatcher->resumeEventListenersForTarget(this); } void Node::pause() { _scheduler->pauseTarget(this); _actionManager->pauseTarget(this); - _eventDispatcher->pauseTarget(this); + _eventDispatcher->pauseEventListenersForTarget(this); } void Node::resumeSchedulerAndActions() diff --git a/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index 2464d7b40f..7b4ff93a6c 100644 --- a/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -24,6 +24,7 @@ std::function createFunctions[] = CL(DirectorEventTest), CL(GlobalZTouchTest), CL(StopPropagationTest), + CL(PauseResumeTargetTest), CL(Issue4129), CL(Issue4160) }; @@ -187,7 +188,7 @@ void TouchableSpriteTest::onEnter() auto senderItem = static_cast(sender); senderItem->setString("Only Next item could be clicked"); - _eventDispatcher->removeEventListeners(EventListener::Type::TOUCH_ONE_BY_ONE); + _eventDispatcher->removeEventListenersForType(EventListener::Type::TOUCH_ONE_BY_ONE); auto nextItem = MenuItemFont::create("Next", [=](Ref* sender){ nextCallback(nullptr); @@ -223,21 +224,32 @@ std::string TouchableSpriteTest::subtitle() const // FixedPriorityChangedTest -class TouchableSpriteWithFixedPriority : public Sprite +class TouchableSprite : public Sprite { public: + static TouchableSprite* create(int priority = 0) + { + auto ret = new TouchableSprite(priority); + if (ret && ret->init()) + { + ret->autorelease(); + } + else + { + CC_SAFE_DELETE(ret); + } + return ret; + } - CREATE_FUNC(TouchableSpriteWithFixedPriority); - - TouchableSpriteWithFixedPriority() +protected: + TouchableSprite(int priority) : _listener(nullptr) - , _fixedPriority(0) + , _fixedPriority(priority) , _removeListenerOnTouchEnded(false) { } - void setPriority(int fixedPriority) { _fixedPriority = fixedPriority; }; - +public: void onEnter() override { Sprite::onEnter(); @@ -268,7 +280,14 @@ public: } }; - _eventDispatcher->addEventListenerWithFixedPriority(listener, _fixedPriority); + if (_fixedPriority != 0) + { + _eventDispatcher->addEventListenerWithFixedPriority(listener, _fixedPriority); + } + else + { + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); + } _listener = listener; } @@ -295,21 +314,18 @@ void FixedPriorityTest::onEnter() Point origin = Director::getInstance()->getVisibleOrigin(); Size size = Director::getInstance()->getVisibleSize(); - auto sprite1 = TouchableSpriteWithFixedPriority::create(); + auto sprite1 = TouchableSprite::create(30); sprite1->setTexture("Images/CyanSquare.png"); - sprite1->setPriority(30); sprite1->setPosition(origin+Point(size.width/2, size.height/2) + Point(-80, 40)); addChild(sprite1, 10); - auto sprite2 = TouchableSpriteWithFixedPriority::create(); + auto sprite2 = TouchableSprite::create(20); sprite2->setTexture("Images/MagentaSquare.png"); - sprite2->setPriority(20); sprite2->setPosition(origin+Point(size.width/2, size.height/2)); addChild(sprite2, 20); - auto sprite3 = TouchableSpriteWithFixedPriority::create(); + auto sprite3 = TouchableSprite::create(10); sprite3->setTexture("Images/YellowSquare.png"); - sprite3->setPriority(10); sprite3->setPosition(Point(0, 0)); sprite2->addChild(sprite3, 1); @@ -701,7 +717,7 @@ void RemoveListenerAfterAddingTest::onEnter() }; _eventDispatcher->addEventListenerWithFixedPriority(listener, -1); - _eventDispatcher->removeEventListeners(EventListener::Type::TOUCH_ONE_BY_ONE); + _eventDispatcher->removeEventListenersForType(EventListener::Type::TOUCH_ONE_BY_ONE); addNextButton(); }); @@ -1087,6 +1103,72 @@ std::string StopPropagationTest::subtitle() const return "Shouldn't crash and only blue block could be clicked"; } +// PauseResumeTargetTest +PauseResumeTargetTest::PauseResumeTargetTest() +{ + Point origin = Director::getInstance()->getVisibleOrigin(); + Size size = Director::getInstance()->getVisibleSize(); + + auto sprite1 = TouchableSprite::create(); + sprite1->setTexture("Images/CyanSquare.png"); + sprite1->setPosition(origin+Point(size.width/2, size.height/2) + Point(-80, 40)); + addChild(sprite1, -10); + + auto sprite2 = TouchableSprite::create(); + sprite2->setTexture("Images/MagentaSquare.png"); + sprite2->setPosition(origin+Point(size.width/2, size.height/2)); + addChild(sprite2, -20); + + auto sprite3 = TouchableSprite::create(); + sprite3->setTexture("Images/YellowSquare.png"); + sprite3->setPosition(Point(0, 0)); + sprite2->addChild(sprite3, -1); + + auto popup = MenuItemFont::create("Popup", [this](Ref* sender){ + + _eventDispatcher->pauseEventListenersForTarget(this, true); + + auto colorLayer = LayerColor::create(Color4B(0, 0, 255, 100)); + this->addChild(colorLayer, 99999); + + auto closeItem = MenuItemFont::create("close", [this, colorLayer](Ref* sender){ + colorLayer->removeFromParent(); + _eventDispatcher->resumeEventListenersForTarget(this, true); + }); + + closeItem->setPosition(VisibleRect::center()); + + auto closeMenu = Menu::create(closeItem, NULL); + closeMenu->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); + closeMenu->setPosition(Point::ZERO); + + colorLayer->addChild(closeMenu); + }); + + popup->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT); + popup->setPosition(VisibleRect::right()); + + auto menu = Menu::create(popup, nullptr); + menu->setAnchorPoint(Point::ANCHOR_BOTTOM_LEFT); + menu->setPosition(Point::ZERO); + + addChild(menu); +} + +PauseResumeTargetTest::~PauseResumeTargetTest() +{ +} + +std::string PauseResumeTargetTest::title() const +{ + return "PauseResumeTargetTest"; +} + +std::string PauseResumeTargetTest::subtitle() const +{ + return ""; +} + // Issue4129 Issue4129::Issue4129() : _bugFixed(false) @@ -1157,22 +1239,19 @@ Issue4160::Issue4160() Point origin = Director::getInstance()->getVisibleOrigin(); Size size = Director::getInstance()->getVisibleSize(); - auto sprite1 = TouchableSpriteWithFixedPriority::create(); + auto sprite1 = TouchableSprite::create(-30); sprite1->setTexture("Images/CyanSquare.png"); - sprite1->setPriority(-30); sprite1->setPosition(origin+Point(size.width/2, size.height/2) + Point(-80, 40)); addChild(sprite1, -10); - auto sprite2 = TouchableSpriteWithFixedPriority::create(); + auto sprite2 = TouchableSprite::create(-20); sprite2->setTexture("Images/MagentaSquare.png"); - sprite2->setPriority(-20); sprite2->removeListenerOnTouchEnded(true); sprite2->setPosition(origin+Point(size.width/2, size.height/2)); addChild(sprite2, -20); - auto sprite3 = TouchableSpriteWithFixedPriority::create(); + auto sprite3 = TouchableSprite::create(-10); sprite3->setTexture("Images/YellowSquare.png"); - sprite3->setPriority(-10); sprite3->setPosition(Point(0, 0)); sprite2->addChild(sprite3, -1); } diff --git a/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h b/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h index 4392998358..e35035b4c6 100644 --- a/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h +++ b/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.h @@ -165,6 +165,19 @@ protected: bool isPointInTopHalfAreaOfScreen(Point pt); }; +class PauseResumeTargetTest : public EventDispatcherTestDemo +{ +public: + CREATE_FUNC(PauseResumeTargetTest); + PauseResumeTargetTest(); + virtual ~PauseResumeTargetTest(); + + virtual std::string title() const override; + virtual std::string subtitle() const override; + +private: +}; + class Issue4129 : public EventDispatcherTestDemo { public: From dceb047ba61e73dc7522987fda89f9acdf181224 Mon Sep 17 00:00:00 2001 From: James Chen Date: Sun, 2 Mar 2014 18:43:17 +0800 Subject: [PATCH 20/34] TimerTargetCallback::initWithLambda -> TimerTargetCallback::initWithCallback. --- cocos/2d/CCScheduler.cpp | 4 ++-- cocos/2d/CCScheduler.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index 9ddb825e18..aa0e5e69d3 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -183,7 +183,7 @@ TimerTargetCallback::TimerTargetCallback() { } -bool TimerTargetCallback::initWithLambda(const ccSchedulerFunc& callback, void *target, const std::string& key, float seconds, unsigned int repeat, float delay) +bool TimerTargetCallback::initWithCallback(const ccSchedulerFunc& callback, void *target, const std::string& key, float seconds, unsigned int repeat, float delay) { _target = target; _callback = callback; @@ -326,7 +326,7 @@ void Scheduler::scheduleCallback(const ccSchedulerFunc& callback, void *target, } TimerTargetCallback *timer = new TimerTargetCallback(); - timer->initWithLambda(callback, target, key, interval, repeat, delay); + timer->initWithCallback(callback, target, key, interval, repeat, delay); ccArrayAppendObject(element->timers, timer); timer->release(); } diff --git a/cocos/2d/CCScheduler.h b/cocos/2d/CCScheduler.h index 2a3d8fabdb..dc5e77e49b 100644 --- a/cocos/2d/CCScheduler.h +++ b/cocos/2d/CCScheduler.h @@ -104,7 +104,7 @@ public: TimerTargetCallback(); /** Initializes a timer with a target, a lambda and an interval in seconds, repeat in number of times to repeat, delay in seconds. */ - bool initWithLambda(const ccSchedulerFunc& callback, void *target, const std::string& key, float seconds, unsigned int repeat, float delay); + bool initWithCallback(const ccSchedulerFunc& callback, void *target, const std::string& key, float seconds, unsigned int repeat, float delay); /** * @js NA From a6e4a5e5aa504db70076d394320c2ee87b6eb976 Mon Sep 17 00:00:00 2001 From: cai wenzhi Date: Sun, 2 Mar 2014 22:41:47 +0800 Subject: [PATCH 21/34] Adjust layout --- cocos/gui/UILayout.cpp | 78 ------------------------------------------ 1 file changed, 78 deletions(-) diff --git a/cocos/gui/UILayout.cpp b/cocos/gui/UILayout.cpp index 1b2c071197..af0d2c8464 100644 --- a/cocos/gui/UILayout.cpp +++ b/cocos/gui/UILayout.cpp @@ -1257,128 +1257,50 @@ void Layout::doLayout() case RELATIVE_LOCATION_ABOVE_LEFTALIGN: finalPosY += mg.bottom; - if (relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_TOP_LEFT - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_NONE - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_TOP_RIGHT) - { - finalPosY += relativeWidgetMargin.top; - } finalPosX += mg.left; break; case RELATIVE_LOCATION_ABOVE_RIGHTALIGN: finalPosY += mg.bottom; - if (relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_TOP_LEFT - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_NONE - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_TOP_RIGHT) - { - finalPosY += relativeWidgetMargin.top; - } finalPosX -= mg.right; break; case RELATIVE_LOCATION_ABOVE_CENTER: finalPosY += mg.bottom; - if (relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_TOP_CENTER_HORIZONTAL - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_TOP_LEFT - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_NONE - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_TOP_RIGHT) - { - finalPosY += relativeWidgetMargin.top; - } break; case RELATIVE_LOCATION_LEFT_OF_TOPALIGN: finalPosX -= mg.right; - if (relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_TOP_LEFT - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_NONE - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_LEFT_BOTTOM - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL) - { - finalPosX -= relativeWidgetMargin.left; - } finalPosY -= mg.top; break; case RELATIVE_LOCATION_LEFT_OF_BOTTOMALIGN: finalPosX -= mg.right; - if (relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_TOP_LEFT - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_NONE - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_LEFT_BOTTOM - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL) - { - finalPosX -= relativeWidgetMargin.left; - } finalPosY += mg.bottom; break; case RELATIVE_LOCATION_LEFT_OF_CENTER: finalPosX -= mg.right; - if (relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_TOP_LEFT - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_NONE - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_LEFT_BOTTOM - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_LEFT_CENTER_VERTICAL) - { - finalPosX -= relativeWidgetMargin.left; - } break; case RELATIVE_LOCATION_RIGHT_OF_TOPALIGN: finalPosX += mg.left; - if (relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_TOP_RIGHT - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL) - { - finalPosX += relativeWidgetMargin.right; - } finalPosY -= mg.top; break; case RELATIVE_LOCATION_RIGHT_OF_BOTTOMALIGN: finalPosX += mg.left; - if (relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_TOP_RIGHT - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL) - { - finalPosX += relativeWidgetMargin.right; - } finalPosY += mg.bottom; break; case RELATIVE_LOCATION_RIGHT_OF_CENTER: finalPosX += mg.left; - if (relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_TOP_RIGHT - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_RIGHT_CENTER_VERTICAL) - { - finalPosX += relativeWidgetMargin.right; - } break; case RELATIVE_LOCATION_BELOW_LEFTALIGN: finalPosY -= mg.top; - if (relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_LEFT_BOTTOM - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL) - { - finalPosY -= relativeWidgetMargin.bottom; - } finalPosX += mg.left; break; case RELATIVE_LOCATION_BELOW_RIGHTALIGN: finalPosY -= mg.top; - if (relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_LEFT_BOTTOM - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL) - { - finalPosY -= relativeWidgetMargin.bottom; - } finalPosX -= mg.right; break; case RELATIVE_LOCATION_BELOW_CENTER: finalPosY -= mg.top; - if (relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_LEFT_BOTTOM - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_RIGHT_BOTTOM - && relativeWidgetLP->getAlign() != RELATIVE_ALIGN_PARENT_BOTTOM_CENTER_HORIZONTAL) - { - finalPosY -= relativeWidgetMargin.bottom; - } break; default: break; From c99b0a0b6a879e9fd5ff0ad9d5dc2c6bfd68fd05 Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 3 Mar 2014 01:48:56 +0800 Subject: [PATCH 22/34] closed #4150: Fix missing "!" --- cocos/2d/CCNode.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 69a3454cac..ef64a15da9 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -537,7 +537,7 @@ const Point& Node::getAnchorPoint() const void Node::setAnchorPoint(const Point& point) { #if CC_USE_PHYSICS - if (_physicsBody != nullptr && point.equals(Point::ANCHOR_MIDDLE)) + if (_physicsBody != nullptr && !point.equals(Point::ANCHOR_MIDDLE)) { CCLOG("Node warning: This node has a physics body, the anchor must be in the middle, you cann't change this to other value."); return; From 8189d153b6dcdac494d12492647388cb51a92c0d Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 3 Mar 2014 10:01:41 +0800 Subject: [PATCH 23/34] add install.py --- install.py | 188 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 188 insertions(+) create mode 100755 install.py diff --git a/install.py b/install.py new file mode 100755 index 0000000000..d2e422196c --- /dev/null +++ b/install.py @@ -0,0 +1,188 @@ +#!/usr/bin/python +#coding=utf-8 +"""**************************************************************************** +Copyright (c) 2014 cocos2d-x.org + +http://www.cocos2d-x.org + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +****************************************************************************""" + +import os +import sys +from optparse import OptionParser + +COCOS_CONSOLE_ROOT = 'COCOS_CONSOLE_ROOT' +NDK_ROOT = 'NDK_ROOT1' + + +class SetEnvVar: + + current_absolute_path = os.path.dirname(os.path.realpath(__file__)) + + @staticmethod + def _isWindows(): + return sys.platform == 'win32' + + @staticmethod + def _isLinux(): + return sys.platform.startswith('linux') + + # modify register table to add an environment variable on windows + # TODO: test in on windows + @staticmethod + def _set_environment_variable_win32(key, value): + + import _winreg + + env = _winreg.OpenKeyEx(_winreg._winreg.HKEY_LOCAL_MACHINE,\ + r'SYSTEM\ControlSet001\Control\Session Manager\Environment',\ + 0, + _winreg.KEY_SET_VALUE|_winreg.KEY_READ) + _winreg.SetValueEx(env, key, 0, _winreg.REG_SZ, value) + + # modify ~/.bash_profile to add an environment variable + @staticmethod + def _set_environment_variable_unix(key, value): + home = os.path.expanduser('~') + profile_path = os.path.join(home, '.bash_profile') + + file = open(profile_path, 'a') + file.write('export %s=%s\n' % (key, value)) + file.write('export PATH=$%s:$PATH\n' % key) + file.close() + + # make it take effect immediately + cmd = 'source ' + profile_path + p = os.popen(cmd) + p.close() + + + @staticmethod + def _set_environment_variable(key, value): + + if SetEnvVar._isWindows(): + _set_environment_variable_win32(key, value) + else: + SetEnvVar._set_environment_variable_unix(key, value) + + @staticmethod + def set_environment_variables(): + + SetEnvVar.set_console_root() + SetEnvVar.set_ndk_root(None) + + @staticmethod + def set_console_root(): + + try: + cocos_console_root = os.environ[COCOS_CONSOLE_ROOT] + except Exception: + cocos_console_root = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'tools/cocos2d-console/bin') + SetEnvVar._set_environment_variable(COCOS_CONSOLE_ROOT, cocos_console_root) + os.environ[COCOS_CONSOLE_ROOT] = cocos_console_root + finally: + print "'COCOS_CONSOLE_ROOT' is %s" % cocos_console_root + + @staticmethod + def _get_ndk_root(): + + ndk_root = None + + # python on linux doesn't include Tkinter model, so let user input in terminal + if SetEnvVar._isLinux(): + print "not linux" + while True: + + ndk_root = raw_input('Enter path of ndk, press enter to skip: ') + if not ndk_root: + break + + if not os.path.exists(ndk_root): + print 'input path %s does not exist' % ndk_root + else: + break + + else: + # pop up a window to let user select path for ndk root + import Tkinter, tkFileDialog + + try: + ndk_root = os.environ[NDK_ROOT] + except Exception: + root = Tkinter.Tk() + SetEnvVar._center(root) + + def callback(): + ndk_root = tkFileDialog.askdirectory() + root.destroy() + + + frame = Tkinter.Frame(root) + Tkinter.Label(frame, text='select path for ndk root').pack(side=Tkinter.LEFT) + Tkinter.Button(frame, text='...', command=callback).pack(side=Tkinter.LEFT) + frame.pack() + root.mainloop() + + return ndk_root + + # display a window in center and put it on top + @staticmethod + def _center(win): + win.update_idletasks() + width = win.winfo_width() + height = win.winfo_height() + x = (win.winfo_screenwidth() / 2) - (width / 2) + y = (win.winfo_screenheight() / 2) - (height / 2) + win.geometry('{}x{}+{}+{}'.format(width, height, x, y)) + win.wm_attributes('-topmost', 1) + + + @staticmethod + def set_ndk_root(value): + + if value: + ndk_root = value + else: + ndk_root = SetEnvVar._get_ndk_root() + + print "ndk_root is %s" % ndk_root + + if ndk_root: + os.environ[NDK_ROOT] = ndk_root + SetEnvVar._set_environment_variable(NDK_ROOT, ndk_root) + +usage = "" + + +if __name__ == '__main__': + + parser = OptionParser() + parser.add_option('-n', '--ndkroot', dest='ndk_root', help='directory of ndk root') + opts, args = parser.parse_args() + + # ndk_root is passed in + if opts.ndk_root: + os.environ[NDK_ROOT] = opts.ndk_root + SetEnvVar.set_ndk_root() + exit(0) + + # set environment variables + SetEnvVar.set_environment_variables() + \ No newline at end of file From e0178ae886b8f88be52a1d0ac7f2757a328189d5 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 3 Mar 2014 10:08:47 +0800 Subject: [PATCH 24/34] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index ebbd7781f7..63ff949ec2 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -3,6 +3,7 @@ cocos2d-x-3.0rc0 Feb.?? 2014 [NEW] Action: RotateBy supports 3D rotations [NEW] Bindings: Using python to automatically generate script bindings [NEW] Bindings: Added JS bindings support for Linux + [NEW] Console: Added command: 'autotest run|main|next|back|restart'. [NEW] Console: Added 'resolution', 'projection' commands. Improved API [NEW] Console: Added more commands: director resume|pause|stopanimation|startanimation. [NEW] Console: Added command: 'touch tap|swipe' to simulating touch events. From 757425c54b7ac069dd2ffe456070a674fb8086ff Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 3 Mar 2014 11:00:30 +0800 Subject: [PATCH 25/34] issue #4165: Scheduler::scheduleCallback -> Scheduler::schedule, Scheduler::scheduleSelector -> Scheduler::schedule. APIs are clear for c++ developers now. --- cocos/2d/CCDirector.cpp | 2 +- cocos/2d/CCNode.cpp | 12 +- cocos/2d/CCScheduler.cpp | 36 ++--- cocos/2d/CCScheduler.h | 126 +++++++++--------- cocos/2d/CCTextureCache.cpp | 4 +- .../cocostudio/CCActionObject.cpp | 6 +- .../cocostudio/CCDataReaderHelper.cpp | 4 +- cocos/network/SocketIO.cpp | 2 +- cocos/network/WebSocket.cpp | 2 +- .../CocoStudioSceneTest/TriggerCode/cons.cpp | 4 +- .../PerformanceTest/PerformanceAllocTest.cpp | 4 +- .../PerformanceContainerTest.cpp | 4 +- .../PerformanceEventDispatcherTest.cpp | 4 +- .../PerformanceTest/PerformanceLabelTest.cpp | 8 +- .../PerformanceNodeChildrenTest.cpp | 4 +- .../PerformanceTest/PerformanceSpriteTest.cpp | 8 +- tests/Classes/SchedulerTest/SchedulerTest.cpp | 30 ++--- 17 files changed, 128 insertions(+), 132 deletions(-) diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index fb3ddd8d08..3a8d7a9c2f 100644 --- a/cocos/2d/CCDirector.cpp +++ b/cocos/2d/CCDirector.cpp @@ -140,7 +140,7 @@ bool Director::init(void) _scheduler = new Scheduler(); // action manager _actionManager = new ActionManager(); - _scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false); + _scheduler->scheduleUpdate(_actionManager, Scheduler::PRIORITY_SYSTEM, false); _eventDispatcher = new EventDispatcher(); _eventAfterDraw = new EventCustom(EVENT_AFTER_DRAW); diff --git a/cocos/2d/CCNode.cpp b/cocos/2d/CCNode.cpp index 581b341e7b..ba50bb10a1 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -1115,7 +1115,7 @@ void Node::setScheduler(Scheduler* scheduler) bool Node::isScheduled(SEL_SCHEDULE selector) { - return _scheduler->isScheduledForTarget(this, selector); + return _scheduler->isScheduled(selector, this); } void Node::scheduleUpdate() @@ -1125,7 +1125,7 @@ void Node::scheduleUpdate() void Node::scheduleUpdateWithPriority(int priority) { - _scheduler->scheduleUpdateForTarget(this, priority, !_running); + _scheduler->scheduleUpdate(this, priority, !_running); } void Node::scheduleUpdateWithPriorityLua(int nHandler, int priority) @@ -1136,12 +1136,12 @@ void Node::scheduleUpdateWithPriorityLua(int nHandler, int priority) _updateScriptHandler = nHandler; #endif - _scheduler->scheduleUpdateForTarget(this, priority, !_running); + _scheduler->scheduleUpdate(this, priority, !_running); } void Node::unscheduleUpdate() { - _scheduler->unscheduleUpdateForTarget(this); + _scheduler->unscheduleUpdate(this); #if CC_ENABLE_SCRIPT_BINDING if (_updateScriptHandler) @@ -1167,7 +1167,7 @@ void Node::schedule(SEL_SCHEDULE selector, float interval, unsigned int repeat, CCASSERT( selector, "Argument must be non-nil"); CCASSERT( interval >=0, "Argument must be positive"); - _scheduler->scheduleSelector(selector, this, interval , repeat, delay, !_running); + _scheduler->schedule(selector, this, interval , repeat, delay, !_running); } void Node::scheduleOnce(SEL_SCHEDULE selector, float delay) @@ -1181,7 +1181,7 @@ void Node::unschedule(SEL_SCHEDULE selector) if (selector == nullptr) return; - _scheduler->unscheduleSelector(selector, this); + _scheduler->unschedule(selector, this); } void Node::unscheduleAllSelectors() diff --git a/cocos/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index aa0e5e69d3..530bb99232 100644 --- a/cocos/2d/CCScheduler.cpp +++ b/cocos/2d/CCScheduler.cpp @@ -172,7 +172,7 @@ void TimerTargetSelector::trigger() void TimerTargetSelector::cancel() { - Director::getInstance()->getScheduler()->unscheduleSelector(_selector, _target); + Director::getInstance()->getScheduler()->unschedule(_selector, _target); } // TimerTargetCallback @@ -202,7 +202,7 @@ void TimerTargetCallback::trigger() void TimerTargetCallback::cancel() { - Director::getInstance()->getScheduler()->unscheduleCallbackForKey(_key, _target); + Director::getInstance()->getScheduler()->unschedule(_key, _target); } #if CC_ENABLE_SCRIPT_BINDING @@ -277,12 +277,12 @@ void Scheduler::removeHashElement(_hashSelectorEntry *element) free(element); } -void Scheduler::scheduleCallback(const ccSchedulerFunc& callback, void *target, const std::string& key, float interval, bool paused) +void Scheduler::schedule(const ccSchedulerFunc& callback, void *target, float interval, bool paused, const std::string& key) { - this->scheduleCallback(callback, target, key, interval, kRepeatForever, 0.0f, paused); + this->schedule(callback, target, interval, kRepeatForever, 0.0f, paused, key); } -void Scheduler::scheduleCallback(const ccSchedulerFunc& callback, void *target, const std::string& key, float interval, unsigned int repeat, float delay, bool paused) +void Scheduler::schedule(const ccSchedulerFunc& callback, void *target, float interval, unsigned int repeat, float delay, bool paused, const std::string& key) { CCASSERT(target, "Argument target must be non-nullptr"); CCASSERT(!key.empty(), "key should not be empty!"); @@ -331,7 +331,7 @@ void Scheduler::scheduleCallback(const ccSchedulerFunc& callback, void *target, timer->release(); } -void Scheduler::unscheduleCallbackForKey(const std::string &key, void *target) +void Scheduler::unschedule(const std::string &key, void *target) { // explicity handle nil arguments when removing an object if (target == nullptr || key.empty()) @@ -461,7 +461,7 @@ void Scheduler::appendIn(_listEntry **list, const ccSchedulerFunc& callback, voi HASH_ADD_PTR(_hashForUpdates, target, hashElement); } -void Scheduler::scheduleCallbackPerFrame(const ccSchedulerFunc& callback, void *target, int priority, bool paused) +void Scheduler::schedulePerFrame(const ccSchedulerFunc& callback, void *target, int priority, bool paused) { tHashUpdateEntry *hashElement = nullptr; HASH_FIND_PTR(_hashForUpdates, &target, hashElement); @@ -493,7 +493,7 @@ void Scheduler::scheduleCallbackPerFrame(const ccSchedulerFunc& callback, void * } } -bool Scheduler::isScheduledForKey(const std::string& key, void *target) +bool Scheduler::isScheduled(const std::string& key, void *target) { CCASSERT(!key.empty(), "Argument key must not be empty"); CCASSERT(target, "Argument target must be non-nullptr"); @@ -545,7 +545,7 @@ void Scheduler::removeUpdateFromHash(struct _listEntry *entry) } } -void Scheduler::unscheduleUpdateForTarget(void *target) +void Scheduler::unscheduleUpdate(void *target) { if (target == nullptr) { @@ -594,7 +594,7 @@ void Scheduler::unscheduleAllWithMinPriority(int minPriority) { if(entry->priority >= minPriority) { - unscheduleUpdateForTarget(entry->target); + unscheduleUpdate(entry->target); } } } @@ -603,7 +603,7 @@ void Scheduler::unscheduleAllWithMinPriority(int minPriority) { DL_FOREACH_SAFE(_updates0List, entry, tmp) { - unscheduleUpdateForTarget(entry->target); + unscheduleUpdate(entry->target); } } @@ -611,7 +611,7 @@ void Scheduler::unscheduleAllWithMinPriority(int minPriority) { if(entry->priority >= minPriority) { - unscheduleUpdateForTarget(entry->target); + unscheduleUpdate(entry->target); } } #if CC_ENABLE_SCRIPT_BINDING @@ -652,7 +652,7 @@ void Scheduler::unscheduleAllForTarget(void *target) } // update selector - unscheduleUpdateForTarget(target); + unscheduleUpdate(target); } #if CC_ENABLE_SCRIPT_BINDING @@ -968,7 +968,7 @@ void Scheduler::update(float dt) } } -void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Ref *target, float interval, unsigned int repeat, float delay, bool paused) +void Scheduler::schedule(SEL_SCHEDULE selector, Ref *target, float interval, unsigned int repeat, float delay, bool paused) { CCASSERT(target, "Argument target must be non-nullptr"); @@ -1016,12 +1016,12 @@ void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Ref *target, float inter timer->release(); } -void Scheduler::scheduleSelector(SEL_SCHEDULE selector, Ref *target, float interval, bool paused) +void Scheduler::schedule(SEL_SCHEDULE selector, Ref *target, float interval, bool paused) { - this->scheduleSelector(selector, target, interval, kRepeatForever, 0.0f, paused); + this->schedule(selector, target, interval, kRepeatForever, 0.0f, paused); } -bool Scheduler::isScheduledForSelector(SEL_SCHEDULE selector, Ref *target) +bool Scheduler::isScheduled(SEL_SCHEDULE selector, Ref *target) { CCASSERT(selector, "Argument selector must be non-nullptr"); CCASSERT(target, "Argument target must be non-nullptr"); @@ -1056,7 +1056,7 @@ bool Scheduler::isScheduledForSelector(SEL_SCHEDULE selector, Ref *target) return false; // should never get here } -void Scheduler::unscheduleSelector(SEL_SCHEDULE selector, Ref *target) +void Scheduler::unschedule(SEL_SCHEDULE selector, Ref *target) { // explicity handle nil arguments when removing an object if (target == nullptr || selector == nullptr) diff --git a/cocos/2d/CCScheduler.h b/cocos/2d/CCScheduler.h index dc5e77e49b..9059611b7f 100644 --- a/cocos/2d/CCScheduler.h +++ b/cocos/2d/CCScheduler.h @@ -151,7 +151,7 @@ class SchedulerScriptHandlerEntry; #endif /** @brief Scheduler is responsible for triggering the scheduled callbacks. -You should not use NSTimer. Instead use this class. +You should not use system timer for your game logic. Instead, use this class. There are 2 different types of callbacks (selectors): @@ -196,7 +196,9 @@ public: */ void update(float dt); - // schedule / unschedule 'callback'. Added from v3.0-final + ///////////////////////////////////// + + // schedule /** The scheduled method will be called every 'interval' seconds. If paused is true, then it won't be called until it is resumed. @@ -207,27 +209,13 @@ public: @param key The key to identify the callback @since v3.0 */ - void scheduleCallback(const ccSchedulerFunc& callback, void *target, const std::string& key, float interval, unsigned int repeat, float delay, bool paused); + void schedule(const ccSchedulerFunc& callback, void *target, float interval, unsigned int repeat, float delay, bool paused, const std::string& key); /** Calls scheduleCallback with kRepeatForever and a 0 delay @since v3.0 */ - void scheduleCallback(const ccSchedulerFunc& callback, void *target, const std::string& key, float interval, bool paused); + void schedule(const ccSchedulerFunc& callback, void *target, float interval, bool paused, const std::string& key); - /** Checks whether a callback associated with 'key' and 'target' is scheduled. - @since v3.0.0 - */ - bool isScheduledForKey(const std::string& key, void *target); - - /** Unschedules a callback for a key and a given target. - If you want to unschedule the 'callbackPerFrame', use unscheduleUpdate. - @since v3.0 - */ - void unscheduleCallbackForKey(const std::string& key, void *target); - - ///////////////////////////////////// - - // schedule / unschedule 'selector' /** The scheduled method will be called every 'interval' seconds. If paused is true, then it won't be called until it is resumed. @@ -236,55 +224,56 @@ public: repeat let the action be repeated repeat + 1 times, use kRepeatForever to let the action run continuously delay is the amount of time the action will wait before it'll start - @since v0.99.3, repeat and delay added in v1.1 + @since v3.0, repeat and delay added in v1.1 */ - void scheduleSelector(SEL_SCHEDULE selector, Ref *target, float interval, unsigned int repeat, float delay, bool paused); + void schedule(SEL_SCHEDULE selector, Ref *target, float interval, unsigned int repeat, float delay, bool paused); /** calls scheduleSelector with kRepeatForever and a 0 delay */ - void scheduleSelector(SEL_SCHEDULE selector, Ref *target, float interval, bool paused); - - /** Unschedule a selector for a given target. - If you want to unschedule the "update", use unscheudleUpdateForTarget. - @since v0.99.3 - */ - void unscheduleSelector(SEL_SCHEDULE selector, Ref *target); - - /** Checks whether a selector for a given taget is scheduled. - @since v0.99.3 - */ - CC_DEPRECATED_ATTRIBUTE bool isScheduledForTarget(Ref *target, SEL_SCHEDULE selector) { return isScheduledForSelector(selector, target); }; - - /** Checks whether a selector for a given taget is scheduled. - @since v3.0 - */ - bool isScheduledForSelector(SEL_SCHEDULE selector, Ref *target); - - ///////////////////////////////////// - - // schedule / unschedule 'update' + void schedule(SEL_SCHEDULE selector, Ref *target, float interval, bool paused); /** Schedules the 'update' selector for a given target with a given priority. The 'update' selector will be called every frame. The lower the priority, the earlier it is called. - @since v0.99.3 + @since v3.0 @lua NA */ template - void scheduleUpdateForTarget(T *target, int priority, bool paused) + void scheduleUpdate(T *target, int priority, bool paused) { - this->scheduleCallbackPerFrame([target](float dt){ + this->schedulePerFrame([target](float dt){ target->update(dt); }, target, priority, paused); } + +#if CC_ENABLE_SCRIPT_BINDING + // schedule for script bindings + /** The scheduled script callback will be called every 'interval' seconds. + If paused is true, then it won't be called until it is resumed. + If 'interval' is 0, it will be called every frame. + return schedule script entry ID, used for unscheduleScriptFunc(). + */ + unsigned int scheduleScriptFunc(unsigned int handler, float interval, bool paused); +#endif + ///////////////////////////////////// + + // unschedule + + /** Unschedules a callback for a key and a given target. + If you want to unschedule the 'callbackPerFrame', use unscheduleUpdate. + @since v3.0 + */ + void unschedule(const std::string& key, void *target); + + /** Unschedule a selector for a given target. + If you want to unschedule the "update", use unscheudleUpdateForTarget. + @since v3.0 + */ + void unschedule(SEL_SCHEDULE selector, Ref *target); /** Unschedules the update selector for a given target @since v0.99.3 */ - void unscheduleUpdateForTarget(void *target); - - ///////////////////////////////////// - - // unschedule all + void unscheduleUpdate(void *target); /** Unschedules all selectors for a given target. This also includes the "update" selector. @@ -301,28 +290,32 @@ public: void unscheduleAll(void); /** Unschedules all selectors from all targets with a minimum priority. - You should only call this with kPriorityNonSystemMin or higher. - @since v2.0.0 - */ - void unscheduleAllWithMinPriority(int minPriority); - - ///////////////////////////////////// - - // schedule / unschedule for script bindings -#if CC_ENABLE_SCRIPT_BINDING - /** The scheduled script callback will be called every 'interval' seconds. - If paused is true, then it won't be called until it is resumed. - If 'interval' is 0, it will be called every frame. - return schedule script entry ID, used for unscheduleScriptFunc(). + You should only call this with kPriorityNonSystemMin or higher. + @since v2.0.0 */ - unsigned int scheduleScriptFunc(unsigned int handler, float interval, bool paused); + void unscheduleAllWithMinPriority(int minPriority); +#if CC_ENABLE_SCRIPT_BINDING /** Unschedule a script entry. */ void unscheduleScriptEntry(unsigned int scheduleScriptEntryID); #endif ///////////////////////////////////// + // isScheduled + + /** Checks whether a callback associated with 'key' and 'target' is scheduled. + @since v3.0.0 + */ + bool isScheduled(const std::string& key, void *target); + + /** Checks whether a selector for a given taget is scheduled. + @since v3.0 + */ + bool isScheduled(SEL_SCHEDULE selector, Ref *target); + + ///////////////////////////////////// + /** Pauses the target. All scheduled selectors/update for a given target won't be 'ticked' until the target is resumed. If the target is not present, nothing happens. @@ -367,7 +360,10 @@ public: @since v3.0 */ void performFunctionInCocosThread( const std::function &function); - + + // Deprecated methods: + + protected: /** Schedules the 'callback' function for a given target with a given priority. @@ -376,7 +372,7 @@ protected: @note This method is only for internal use. @since v3.0 */ - void scheduleCallbackPerFrame(const ccSchedulerFunc& callback, void *target, int priority, bool paused); + void schedulePerFrame(const ccSchedulerFunc& callback, void *target, int priority, bool paused); void removeHashElement(struct _hashSelectorEntry *element); void removeUpdateFromHash(struct _listEntry *entry); diff --git a/cocos/2d/CCTextureCache.cpp b/cocos/2d/CCTextureCache.cpp index aaa9ccfb4a..0ae5763a07 100644 --- a/cocos/2d/CCTextureCache.cpp +++ b/cocos/2d/CCTextureCache.cpp @@ -123,7 +123,7 @@ void TextureCache::addImageAsync(const std::string &path, std::functiongetScheduler()->scheduleSelector(schedule_selector(TextureCache::addImageAsyncCallBack), this, 0, false); + Director::getInstance()->getScheduler()->schedule(schedule_selector(TextureCache::addImageAsyncCallBack), this, 0, false); } ++_asyncRefCount; @@ -277,7 +277,7 @@ void TextureCache::addImageAsyncCallBack(float dt) --_asyncRefCount; if (0 == _asyncRefCount) { - Director::getInstance()->getScheduler()->unscheduleSelector(schedule_selector(TextureCache::addImageAsyncCallBack), this); + Director::getInstance()->getScheduler()->unschedule(schedule_selector(TextureCache::addImageAsyncCallBack), this); } } } diff --git a/cocos/editor-support/cocostudio/CCActionObject.cpp b/cocos/editor-support/cocostudio/CCActionObject.cpp index 62b2b8040f..aaeac50af9 100644 --- a/cocos/editor-support/cocostudio/CCActionObject.cpp +++ b/cocos/editor-support/cocostudio/CCActionObject.cpp @@ -154,11 +154,11 @@ void ActionObject::play() } if (_loop) { - _pScheduler->scheduleSelector(schedule_selector(ActionObject::simulationActionUpdate), this, 0.0f , kRepeatForever, 0.0f, false); + _pScheduler->schedule(schedule_selector(ActionObject::simulationActionUpdate), this, 0.0f , kRepeatForever, 0.0f, false); } else { - _pScheduler->scheduleSelector(schedule_selector(ActionObject::simulationActionUpdate), this, 0.0f, false); + _pScheduler->schedule(schedule_selector(ActionObject::simulationActionUpdate), this, 0.0f, false); } } @@ -178,7 +178,7 @@ void ActionObject::stop() { e->stopAction(); } - _pScheduler->unscheduleSelector(schedule_selector(ActionObject::simulationActionUpdate), this); + _pScheduler->unschedule(schedule_selector(ActionObject::simulationActionUpdate), this); _bPause = false; } diff --git a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp index 895784be29..32e2439644 100644 --- a/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp +++ b/cocos/editor-support/cocostudio/CCDataReaderHelper.cpp @@ -363,7 +363,7 @@ void DataReaderHelper::addDataFromFileAsync(const std::string& imagePath, const if (0 == _asyncRefCount) { - Director::getInstance()->getScheduler()->scheduleSelector(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this, 0, false); + Director::getInstance()->getScheduler()->schedule(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this, 0, false); } ++_asyncRefCount; @@ -466,7 +466,7 @@ void DataReaderHelper::addDataAsyncCallBack(float dt) if (0 == _asyncRefCount) { _asyncRefTotalCount = 0; - Director::getInstance()->getScheduler()->unscheduleSelector(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this); + Director::getInstance()->getScheduler()->unschedule(schedule_selector(DataReaderHelper::addDataAsyncCallBack), this); } } } diff --git a/cocos/network/SocketIO.cpp b/cocos/network/SocketIO.cpp index 23e850d0f6..af7b295543 100644 --- a/cocos/network/SocketIO.cpp +++ b/cocos/network/SocketIO.cpp @@ -359,7 +359,7 @@ void SIOClientImpl::onOpen(WebSocket* ws) iter->second->onOpen(); } - Director::getInstance()->getScheduler()->scheduleSelector(schedule_selector(SIOClientImpl::heartbeat), this, (_heartbeat * .9f), false); + Director::getInstance()->getScheduler()->schedule(schedule_selector(SIOClientImpl::heartbeat), this, (_heartbeat * .9f), false); log("SIOClientImpl::onOpen socket connected!"); } diff --git a/cocos/network/WebSocket.cpp b/cocos/network/WebSocket.cpp index 16a001c6b2..4ba4b708a0 100644 --- a/cocos/network/WebSocket.cpp +++ b/cocos/network/WebSocket.cpp @@ -122,7 +122,7 @@ WsThreadHelper::WsThreadHelper() _UIWsMessageQueue = new std::list(); _subThreadWsMessageQueue = new std::list(); - Director::getInstance()->getScheduler()->scheduleUpdateForTarget(this, 0, false); + Director::getInstance()->getScheduler()->scheduleUpdate(this, 0, false); } WsThreadHelper::~WsThreadHelper() diff --git a/tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.cpp b/tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.cpp index 00b78174f6..ea2f3a3971 100755 --- a/tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.cpp +++ b/tests/Classes/ExtensionsTest/CocoStudioSceneTest/TriggerCode/cons.cpp @@ -24,7 +24,7 @@ TimeElapsed::~TimeElapsed(void) bool TimeElapsed::init() { - _scheduler->scheduleSelector(schedule_selector(TimeElapsed::update), this, 0.0f , kRepeatForever, 0.0f, false); + _scheduler->schedule(schedule_selector(TimeElapsed::update), this, 0.0f , kRepeatForever, 0.0f, false); return true; } @@ -49,7 +49,7 @@ void TimeElapsed::serialize(const rapidjson::Value &val) void TimeElapsed::removeAll() { - _scheduler->unscheduleUpdateForTarget(this); + _scheduler->unschedule(schedule_selector(TimeElapsed::update), this); } void TimeElapsed::update(float dt) diff --git a/tests/Classes/PerformanceTest/PerformanceAllocTest.cpp b/tests/Classes/PerformanceTest/PerformanceAllocTest.cpp index 6559aec82e..e77122a13e 100644 --- a/tests/Classes/PerformanceTest/PerformanceAllocTest.cpp +++ b/tests/Classes/PerformanceTest/PerformanceAllocTest.cpp @@ -197,7 +197,7 @@ void PerformceAllocScene::onExitTransitionDidStart() auto director = Director::getInstance(); auto sched = director->getScheduler(); - sched->unscheduleSelector(SEL_SCHEDULE(&PerformceAllocScene::dumpProfilerInfo), this); + sched->unschedule(schedule_selector(PerformceAllocScene::dumpProfilerInfo), this); } void PerformceAllocScene::onEnterTransitionDidFinish() @@ -208,7 +208,7 @@ void PerformceAllocScene::onEnterTransitionDidFinish() auto sched = director->getScheduler(); CC_PROFILER_PURGE_ALL(); - sched->scheduleSelector(SEL_SCHEDULE(&PerformceAllocScene::dumpProfilerInfo), this, 2, false); + sched->schedule(schedule_selector(PerformceAllocScene::dumpProfilerInfo), this, 2, false); } void PerformceAllocScene::dumpProfilerInfo(float dt) diff --git a/tests/Classes/PerformanceTest/PerformanceContainerTest.cpp b/tests/Classes/PerformanceTest/PerformanceContainerTest.cpp index c8ac4a63a4..657c40b283 100644 --- a/tests/Classes/PerformanceTest/PerformanceContainerTest.cpp +++ b/tests/Classes/PerformanceTest/PerformanceContainerTest.cpp @@ -190,7 +190,7 @@ void PerformanceContainerScene::initWithQuantityOfNodes(unsigned int nNodes) auto sched = director->getScheduler(); CC_PROFILER_PURGE_ALL(); - sched->scheduleSelector(schedule_selector(PerformanceContainerScene::dumpProfilerInfo), this, 2, false); + sched->schedule(schedule_selector(PerformanceContainerScene::dumpProfilerInfo), this, 2, false); this->unscheduleUpdate(); this->scheduleUpdate(); @@ -208,7 +208,7 @@ void PerformanceContainerScene::initWithQuantityOfNodes(unsigned int nNodes) auto director = Director::getInstance(); auto sched = director->getScheduler(); - sched->unscheduleSelector(schedule_selector(PerformanceContainerScene::dumpProfilerInfo), this); + sched->unschedule(schedule_selector(PerformanceContainerScene::dumpProfilerInfo), this); this->unscheduleUpdate(); this->_startItem->setEnabled(true); diff --git a/tests/Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp b/tests/Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp index af0a9e850b..0aa49d2064 100644 --- a/tests/Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp +++ b/tests/Classes/PerformanceTest/PerformanceEventDispatcherTest.cpp @@ -207,7 +207,7 @@ void PerformanceEventDispatcherScene::initWithQuantityOfNodes(unsigned int nNode auto sched = director->getScheduler(); CC_PROFILER_PURGE_ALL(); - sched->scheduleSelector(schedule_selector(PerformanceEventDispatcherScene::dumpProfilerInfo), this, 2, false); + sched->schedule(schedule_selector(PerformanceEventDispatcherScene::dumpProfilerInfo), this, 2, false); this->unscheduleUpdate(); this->scheduleUpdate(); @@ -225,7 +225,7 @@ void PerformanceEventDispatcherScene::initWithQuantityOfNodes(unsigned int nNode auto director = Director::getInstance(); auto sched = director->getScheduler(); - sched->unscheduleSelector(schedule_selector(PerformanceEventDispatcherScene::dumpProfilerInfo), this); + sched->unschedule(schedule_selector(PerformanceEventDispatcherScene::dumpProfilerInfo), this); this->unscheduleUpdate(); this->_startItem->setEnabled(true); diff --git a/tests/Classes/PerformanceTest/PerformanceLabelTest.cpp b/tests/Classes/PerformanceTest/PerformanceLabelTest.cpp index 6fb6ecaf5f..2f91a04792 100644 --- a/tests/Classes/PerformanceTest/PerformanceLabelTest.cpp +++ b/tests/Classes/PerformanceTest/PerformanceLabelTest.cpp @@ -350,19 +350,19 @@ void LabelMainScene::onEnter() auto director = Director::getInstance(); auto sched = director->getScheduler(); - sched->scheduleSelector(SEL_SCHEDULE(&LabelMainScene::updateText), this, 0.0f, false); + sched->schedule(schedule_selector(LabelMainScene::updateText), this, 0.0f, false); _vecFPS.clear(); _executeTimes = 0; - sched->scheduleSelector(SEL_SCHEDULE(&LabelMainScene::updateAutoTest), this, 0.2f, false); + sched->schedule(schedule_selector(LabelMainScene::updateAutoTest), this, 0.2f, false); } void LabelMainScene::onExit() { auto director = Director::getInstance(); auto sched = director->getScheduler(); - sched->unscheduleSelector(SEL_SCHEDULE(&LabelMainScene::updateText), this ); - sched->unscheduleSelector(SEL_SCHEDULE(&LabelMainScene::updateAutoTest), this ); + sched->unschedule(schedule_selector(LabelMainScene::updateText), this ); + sched->unschedule(schedule_selector(LabelMainScene::updateAutoTest), this ); Scene::onExit(); } diff --git a/tests/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp b/tests/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp index 3876465ad9..cf0fd19843 100644 --- a/tests/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp +++ b/tests/Classes/PerformanceTest/PerformanceNodeChildrenTest.cpp @@ -78,7 +78,7 @@ void NodeChildrenMenuLayer::onExitTransitionDidStart() auto director = Director::getInstance(); auto sched = director->getScheduler(); - sched->unscheduleSelector(SEL_SCHEDULE(&NodeChildrenMenuLayer::dumpProfilerInfo), this); + sched->unschedule(schedule_selector(NodeChildrenMenuLayer::dumpProfilerInfo), this); } void NodeChildrenMenuLayer::onEnterTransitionDidFinish() @@ -87,7 +87,7 @@ void NodeChildrenMenuLayer::onEnterTransitionDidFinish() auto sched = director->getScheduler(); CC_PROFILER_PURGE_ALL(); - sched->scheduleSelector(SEL_SCHEDULE(&NodeChildrenMenuLayer::dumpProfilerInfo), this, 2, false); + sched->schedule(schedule_selector(NodeChildrenMenuLayer::dumpProfilerInfo), this, 2, false); } diff --git a/tests/Classes/PerformanceTest/PerformanceSpriteTest.cpp b/tests/Classes/PerformanceTest/PerformanceSpriteTest.cpp index 1116337d5d..45c2f819d5 100644 --- a/tests/Classes/PerformanceTest/PerformanceSpriteTest.cpp +++ b/tests/Classes/PerformanceTest/PerformanceSpriteTest.cpp @@ -596,7 +596,7 @@ void SpriteMainScene::onEnter() auto director = Director::getInstance(); auto sched = director->getScheduler(); - sched->scheduleSelector(SEL_SCHEDULE(&SpriteMainScene::updateAutoTest), this, 0.2f, false); + sched->schedule(schedule_selector(SpriteMainScene::updateAutoTest), this, 0.2f, false); } } @@ -608,7 +608,7 @@ void SpriteMainScene::onExit() auto director = Director::getInstance(); auto sched = director->getScheduler(); - sched->unscheduleSelector(SEL_SCHEDULE(&SpriteMainScene::updateAutoTest), this ); + sched->unschedule(schedule_selector(SpriteMainScene::updateAutoTest), this ); } Scene::onExit(); @@ -674,7 +674,7 @@ void SpriteMainScene::endAutoTest() auto director = Director::getInstance(); auto sched = director->getScheduler(); - sched->unscheduleSelector( SEL_SCHEDULE( &SpriteMainScene::updateAutoTest ), this ); + sched->unschedule( schedule_selector( SpriteMainScene::updateAutoTest ), this ); } void SpriteMainScene::nextAutoTest() @@ -713,7 +713,7 @@ void SpriteMainScene::finishAutoTest() SpriteMainScene::_s_autoTest = false; auto director = Director::getInstance(); auto sched = director->getScheduler(); - sched->unscheduleSelector( SEL_SCHEDULE( &SpriteMainScene::updateAutoTest ), this); + sched->unschedule( schedule_selector( SpriteMainScene::updateAutoTest ), this); auto autoTestMenu = dynamic_cast(getChildByTag(kTagAutoTestMenu)); if (nullptr != autoTestMenu) diff --git a/tests/Classes/SchedulerTest/SchedulerTest.cpp b/tests/Classes/SchedulerTest/SchedulerTest.cpp index 22ffdfe82a..37597f6cb6 100644 --- a/tests/Classes/SchedulerTest/SchedulerTest.cpp +++ b/tests/Classes/SchedulerTest/SchedulerTest.cpp @@ -431,7 +431,7 @@ void SchedulerUnscheduleAllHard::onExit() if(!_actionManagerActive) { // Restore the director's action manager. auto director = Director::getInstance(); - director->getScheduler()->scheduleUpdateForTarget(director->getActionManager(), Scheduler::PRIORITY_SYSTEM, false); + director->getScheduler()->scheduleUpdate(director->getActionManager(), Scheduler::PRIORITY_SYSTEM, false); } SchedulerTestLayer::onExit(); @@ -965,11 +965,11 @@ void TwoSchedulers::onEnter() // Create a new scheduler, and link it to the main scheduler sched1 = new Scheduler(); - defaultScheduler->scheduleUpdateForTarget(sched1, 0, false); + defaultScheduler->scheduleUpdate(sched1, 0, false); // Create a new ActionManager, and link it to the new scheudler actionManager1 = new ActionManager(); - sched1->scheduleUpdateForTarget(actionManager1, 0, false); + sched1->scheduleUpdate(actionManager1, 0, false); for( unsigned int i=0; i < 10; i++ ) { @@ -991,11 +991,11 @@ void TwoSchedulers::onEnter() // Create a new scheduler, and link it to the main scheduler sched2 = new Scheduler();; - defaultScheduler->scheduleUpdateForTarget(sched2, 0, false); + defaultScheduler->scheduleUpdate(sched2, 0, false); // Create a new ActionManager, and link it to the new scheudler actionManager2 = new ActionManager(); - sched2->scheduleUpdateForTarget(actionManager2, 0, false); + sched2->scheduleUpdate(actionManager2, 0, false); for( unsigned int i=0; i < 10; i++ ) { auto sprite = Sprite::create("Images/grossinis_sister2.png"); @@ -1119,33 +1119,33 @@ std::string ScheduleCallbackTest::title() const std::string ScheduleCallbackTest::subtitle() const { return "\n\n\n\nPlease see console.\n\ -scheduleCallback(lambda, ...)\n\ -scheduleCallback(CC_CALLBACK_1(XXX::member_function), this), this, ...)\n\ -scheduleCallback(global_function, ...)\n\ +schedule(lambda, ...)\n\ +schedule(CC_CALLBACK_1(XXX::member_function), this), this, ...)\n\ +schedule(global_function, ...)\n\ "; } static void ScheduleCallbackTest_global_callback(float dt) { - log("In the callback of scheduleCallback(global_function, ...), dt = %f", dt); + log("In the callback of schedule(global_function, ...), dt = %f", dt); } void ScheduleCallbackTest::onEnter() { SchedulerTestLayer::onEnter(); - _scheduler->scheduleCallback([](float dt){ - log("In the callback of scheduleCallback(lambda, ...), dt = %f", dt); - }, this, "lambda", 1.0f, false); + _scheduler->schedule([](float dt){ + log("In the callback of schedule(lambda, ...), dt = %f", dt); + }, this, 1.0f, false, "lambda"); - _scheduler->scheduleCallback(CC_CALLBACK_1(ScheduleCallbackTest::callback, this), this, "member_function", 1.0f, false); + _scheduler->schedule(CC_CALLBACK_1(ScheduleCallbackTest::callback, this), this, 1.0f, false, "member_function"); - _scheduler->scheduleCallback(ScheduleCallbackTest_global_callback, this, "global_function", 1.0f, false); + _scheduler->schedule(ScheduleCallbackTest_global_callback, this, 1.0f, false, "global_function"); } void ScheduleCallbackTest::callback(float dt) { - log("In the callback of scheduleCallback(CC_CALLBACK_1(XXX::member_function), this), this, ...), dt = %f", dt); + log("In the callback of schedule(CC_CALLBACK_1(XXX::member_function), this), this, ...), dt = %f", dt); } //------------------------------------------------------------------ From 09c0bae4a130667efe7bc4716c8b7d8d991f400b Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 3 Mar 2014 11:07:48 +0800 Subject: [PATCH 26/34] closed #4165: Deprecates old methods: Scheduler::(un)scheduleSelector, Scheduler::isScheduleForTarget. --- cocos/2d/CCScheduler.h | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/cocos/2d/CCScheduler.h b/cocos/2d/CCScheduler.h index 9059611b7f..15e57f751b 100644 --- a/cocos/2d/CCScheduler.h +++ b/cocos/2d/CCScheduler.h @@ -361,8 +361,44 @@ public: */ void performFunctionInCocosThread( const std::function &function); + ///////////////////////////////////// + // Deprecated methods: + /** The scheduled method will be called every 'interval' seconds. + If paused is true, then it won't be called until it is resumed. + If 'interval' is 0, it will be called every frame, but if so, it's recommended to use 'scheduleUpdateForTarget:' instead. + If the selector is already scheduled, then only the interval parameter will be updated without re-scheduling it again. + repeat let the action be repeated repeat + 1 times, use kRepeatForever to let the action run continuously + delay is the amount of time the action will wait before it'll start + @deprecated Please use 'Scheduler::schedule' instead. + @since v0.99.3, repeat and delay added in v1.1 + */ + CC_DEPRECATED_ATTRIBUTE void scheduleSelector(SEL_SCHEDULE selector, Ref *target, float interval, unsigned int repeat, float delay, bool paused) + { + schedule(selector, target, interval, repeat, delay, paused); + }; + + /** calls scheduleSelector with kRepeatForever and a 0 delay + * @deprecated Please use 'Scheduler::schedule' instead. + */ + CC_DEPRECATED_ATTRIBUTE void scheduleSelector(SEL_SCHEDULE selector, Ref *target, float interval, bool paused) + { + schedule(selector, target, interval, paused); + }; + + /** Unschedule a selector for a given target. + If you want to unschedule the "update", use unscheudleUpdateForTarget. + @deprecated Please use 'Scheduler::schedule' instead. + @since v0.99.3 + */ + CC_DEPRECATED_ATTRIBUTE void unscheduleSelector(SEL_SCHEDULE selector, Ref *target) { unschedule(selector, target); }; + + /** Checks whether a selector for a given taget is scheduled. + @deprecated Please use 'Scheduler::isScheduled' instead. + @since v0.99.3 + */ + CC_DEPRECATED_ATTRIBUTE bool isScheduledForTarget(Ref *target, SEL_SCHEDULE selector) { return isScheduled(selector, target); }; protected: From 04663b4a9c2cd95bb65a670385ddb6e6a4c5fe15 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 3 Mar 2014 11:12:04 +0800 Subject: [PATCH 27/34] closed #4165: Updates comments. --- cocos/2d/CCScheduler.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/2d/CCScheduler.h b/cocos/2d/CCScheduler.h index 15e57f751b..b3e40d67d4 100644 --- a/cocos/2d/CCScheduler.h +++ b/cocos/2d/CCScheduler.h @@ -202,7 +202,7 @@ public: /** The scheduled method will be called every 'interval' seconds. If paused is true, then it won't be called until it is resumed. - If 'interval' is 0, it will be called every frame, but if so, it's recommended to use 'scheduleUpdateForTarget:' instead. + If 'interval' is 0, it will be called every frame, but if so, it's recommended to use 'scheduleUpdate' instead. If the 'callback' is already scheduled, then only the interval parameter will be updated without re-scheduling it again. repeat let the action be repeated repeat + 1 times, use kRepeatForever to let the action run continuously delay is the amount of time the action will wait before it'll start @@ -219,7 +219,7 @@ public: /** The scheduled method will be called every 'interval' seconds. If paused is true, then it won't be called until it is resumed. - If 'interval' is 0, it will be called every frame, but if so, it's recommended to use 'scheduleUpdateForTarget:' instead. + If 'interval' is 0, it will be called every frame, but if so, it's recommended to use 'scheduleUpdate' instead. If the selector is already scheduled, then only the interval parameter will be updated without re-scheduling it again. repeat let the action be repeated repeat + 1 times, use kRepeatForever to let the action run continuously delay is the amount of time the action will wait before it'll start @@ -265,7 +265,7 @@ public: void unschedule(const std::string& key, void *target); /** Unschedule a selector for a given target. - If you want to unschedule the "update", use unscheudleUpdateForTarget. + If you want to unschedule the "update", use unscheudleUpdate. @since v3.0 */ void unschedule(SEL_SCHEDULE selector, Ref *target); From 1d2d2df1e9ec44de405427767fba742128a06a8f Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 3 Mar 2014 11:57:36 +0800 Subject: [PATCH 28/34] issue #4165: Adds missing deprecated methods in Scheduler class. --- cocos/2d/CCScheduler.h | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/cocos/2d/CCScheduler.h b/cocos/2d/CCScheduler.h index b3e40d67d4..05b4cd3122 100644 --- a/cocos/2d/CCScheduler.h +++ b/cocos/2d/CCScheduler.h @@ -387,9 +387,18 @@ public: schedule(selector, target, interval, paused); }; + /** Schedules the 'update' selector for a given target with a given priority. + The 'update' selector will be called every frame. + The lower the priority, the earlier it is called. + @deprecated Please use 'Scheduler::scheduleUpdate' instead. + @since v0.99.3 + */ + template + CC_DEPRECATED_ATTRIBUTE void scheduleUpdateForTarget(T* target, int priority, bool paused) { scheduleUpdate(target, priority, paused); }; + /** Unschedule a selector for a given target. If you want to unschedule the "update", use unscheudleUpdateForTarget. - @deprecated Please use 'Scheduler::schedule' instead. + @deprecated Please use 'Scheduler::unschedule' instead. @since v0.99.3 */ CC_DEPRECATED_ATTRIBUTE void unscheduleSelector(SEL_SCHEDULE selector, Ref *target) { unschedule(selector, target); }; @@ -400,6 +409,12 @@ public: */ CC_DEPRECATED_ATTRIBUTE bool isScheduledForTarget(Ref *target, SEL_SCHEDULE selector) { return isScheduled(selector, target); }; + /** Unschedules the update selector for a given target + @deprecated Please use 'Scheduler::unscheduleUpdate' instead. + @since v0.99.3 + */ + CC_DEPRECATED_ATTRIBUTE void unscheduleUpdateForTarget(Ref *target) { return unscheduleUpdate(target); }; + protected: /** Schedules the 'callback' function for a given target with a given priority. From 336dc9f7fceca02b4899b5dabc6a58161dd781a3 Mon Sep 17 00:00:00 2001 From: minggo Date: Mon, 3 Mar 2014 14:11:28 +0800 Subject: [PATCH 29/34] check validation of ndk root --- install.py | 52 +++++++++++++++++++++++++++------------------------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/install.py b/install.py index d2e422196c..e5fbda02b4 100755 --- a/install.py +++ b/install.py @@ -35,6 +35,7 @@ NDK_ROOT = 'NDK_ROOT1' class SetEnvVar: current_absolute_path = os.path.dirname(os.path.realpath(__file__)) + ndk_root = None @staticmethod def _isWindows(): @@ -68,12 +69,6 @@ class SetEnvVar: file.write('export PATH=$%s:$PATH\n' % key) file.close() - # make it take effect immediately - cmd = 'source ' + profile_path - p = os.popen(cmd) - p.close() - - @staticmethod def _set_environment_variable(key, value): @@ -103,36 +98,39 @@ class SetEnvVar: @staticmethod def _get_ndk_root(): - ndk_root = None - # python on linux doesn't include Tkinter model, so let user input in terminal if SetEnvVar._isLinux(): - print "not linux" while True: - ndk_root = raw_input('Enter path of ndk, press enter to skip: ') - if not ndk_root: + input_value = raw_input('Enter path of ndk, press enter to skip: ') + if not input_value: break - if not os.path.exists(ndk_root): - print 'input path %s does not exist' % ndk_root - else: + if os.path.exists(input_value): + if SetEnvVar._check_validation_ndk_root(input_value): + print 'warning: %s is not valid path of ndk root' % input_value + break + + SetEnvVar.ndk_root = input_value else: # pop up a window to let user select path for ndk root import Tkinter, tkFileDialog try: - ndk_root = os.environ[NDK_ROOT] + SetEnvVar.ndk_root = os.environ[NDK_ROOT] except Exception: root = Tkinter.Tk() SetEnvVar._center(root) def callback(): - ndk_root = tkFileDialog.askdirectory() + SetEnvVar.ndk_root = tkFileDialog.askdirectory() root.destroy() + # check out if it is a real ndk root + if not SetEnvVar._check_validation_ndk_root(SetEnvVar.ndk_root): + print 'warning: %s is not a valid path of ndk root' % SetEnvVar.ndk_root frame = Tkinter.Frame(root) Tkinter.Label(frame, text='select path for ndk root').pack(side=Tkinter.LEFT) @@ -140,7 +138,13 @@ class SetEnvVar: frame.pack() root.mainloop() - return ndk_root + @staticmethod + def _check_validation_ndk_root(ndk_root): + ndk_build_path = os.path.join(ndk_root, 'ndk-build') + if os.path.isfile(ndk_build_path): + return True + else: + return False # display a window in center and put it on top @staticmethod @@ -158,17 +162,15 @@ class SetEnvVar: def set_ndk_root(value): if value: - ndk_root = value + SetEnvVar.ndk_root = value else: - ndk_root = SetEnvVar._get_ndk_root() + SetEnvVar._get_ndk_root() - print "ndk_root is %s" % ndk_root + print "ndk_root is %s" % SetEnvVar.ndk_root - if ndk_root: - os.environ[NDK_ROOT] = ndk_root - SetEnvVar._set_environment_variable(NDK_ROOT, ndk_root) - -usage = "" + if SetEnvVar.ndk_root: + os.environ[NDK_ROOT] = SetEnvVar.ndk_root + SetEnvVar._set_environment_variable(NDK_ROOT, SetEnvVar.ndk_root) if __name__ == '__main__': From fdcbfa2eca0016c1b8e5fd2c11d5e7e59bdf897e Mon Sep 17 00:00:00 2001 From: boyu0 Date: Mon, 3 Mar 2014 14:35:44 +0800 Subject: [PATCH 30/34] closed #4150: add const to getPosition/RotationOffset method. --- cocos/physics/CCPhysicsBody.cpp | 4 ++-- cocos/physics/CCPhysicsBody.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 2f075d311e..dd577231be 100644 --- a/cocos/physics/CCPhysicsBody.cpp +++ b/cocos/physics/CCPhysicsBody.cpp @@ -836,7 +836,7 @@ void PhysicsBody::setPositionOffset(const Point& position) } } -Point PhysicsBody::getPositionOffset() +Point PhysicsBody::getPositionOffset() const { return _positionOffset; } @@ -851,7 +851,7 @@ void PhysicsBody::setRotationOffset(float rotation) } } -float PhysicsBody::getRotationOffset() +float PhysicsBody::getRotationOffset() const { return _rotationOffset; } diff --git a/cocos/physics/CCPhysicsBody.h b/cocos/physics/CCPhysicsBody.h index 4f4f9a2425..ea09a7f2f1 100644 --- a/cocos/physics/CCPhysicsBody.h +++ b/cocos/physics/CCPhysicsBody.h @@ -195,11 +195,11 @@ public: /** set body position offset, it's the position witch relative to node */ void setPositionOffset(const Point& position); /** get body position offset. */ - Point getPositionOffset(); + Point getPositionOffset() const; /** set body rotation offset, it's the rotation witch relative to node */ void setRotationOffset(float rotation); /** set the body rotation offset */ - float getRotationOffset(); + float getRotationOffset() const; /** * @brief test the body is dynamic or not. From 8f1ba73a525f6307c66d9e8ee524281c797c2669 Mon Sep 17 00:00:00 2001 From: yinkaile Date: Mon, 3 Mar 2014 14:56:56 +0800 Subject: [PATCH 31/34] fixed add ParticleSystem display crashed --- cocos/editor-support/cocostudio/CCDisplayFactory.cpp | 1 + cocos/editor-support/cocostudio/CCDisplayManager.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp index 72428edfff..41430ed223 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp @@ -262,6 +262,7 @@ void DisplayFactory::createParticleDisplay(Bone *bone, DecorativeDisplay *decoDi ParticleSystem *system = ParticleSystemQuad::create(displayData->displayName.c_str()); system->removeFromParent(); + system->cleanup(); Armature *armature = bone->getArmature(); if (armature) diff --git a/cocos/editor-support/cocostudio/CCDisplayManager.cpp b/cocos/editor-support/cocostudio/CCDisplayManager.cpp index 70863f5f92..250180bf0a 100644 --- a/cocos/editor-support/cocostudio/CCDisplayManager.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayManager.cpp @@ -170,6 +170,7 @@ void DisplayManager::addDisplay(Node *display, int index) displayData = ParticleDisplayData::create(); display->removeFromParent(); + display->cleanup(); Armature *armature = _bone->getArmature(); if (armature) From 7d2db27caec22bc0545435238c171ad4d7f97ff7 Mon Sep 17 00:00:00 2001 From: andyque Date: Thu, 27 Feb 2014 19:51:11 +0800 Subject: [PATCH 32/34] fixed #3599. use a scheduler to fix the position of editbox when it's parent postion has been changed --- extensions/GUI/CCEditBox/CCEditBox.cpp | 13 +++++++++++++ extensions/GUI/CCEditBox/CCEditBox.h | 1 + extensions/GUI/CCEditBox/CCEditBoxImpl.h | 5 +++++ extensions/GUI/CCEditBox/CCEditBoxImplIOS.h | 2 +- extensions/GUI/CCEditBox/CCEditBoxImplIOS.mm | 10 +++++++++- extensions/GUI/CCEditBox/CCEditBoxImplMac.h | 1 + extensions/GUI/CCEditBox/CCEditBoxImplMac.mm | 8 ++++++++ 7 files changed, 38 insertions(+), 2 deletions(-) diff --git a/extensions/GUI/CCEditBox/CCEditBox.cpp b/extensions/GUI/CCEditBox/CCEditBox.cpp index dda578f421..6fe32a766c 100644 --- a/extensions/GUI/CCEditBox/CCEditBox.cpp +++ b/extensions/GUI/CCEditBox/CCEditBox.cpp @@ -28,6 +28,8 @@ NS_CC_EXT_BEGIN +static const float CHECK_EDITBOX_POSITION_INTERVAL = 0.1f; + EditBox::EditBox(void) : _editBoxImpl(NULL) , _delegate(NULL) @@ -332,8 +334,19 @@ void EditBox::onEnter(void) { _editBoxImpl->onEnter(); } +#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS || CC_TARGET_PLATFORM == CC_PLATFORM_MAC) + this->schedule(schedule_selector(EditBox::updatePosition), CHECK_EDITBOX_POSITION_INTERVAL); +#endif } +void EditBox::updatePosition(float dt) +{ + if (nullptr != _editBoxImpl) { + _editBoxImpl->updatePosition(dt); + } +} + + void EditBox::onExit(void) { ControlButton::onExit(); diff --git a/extensions/GUI/CCEditBox/CCEditBox.h b/extensions/GUI/CCEditBox/CCEditBox.h index 675dda2bfe..4b1ed288f7 100644 --- a/extensions/GUI/CCEditBox/CCEditBox.h +++ b/extensions/GUI/CCEditBox/CCEditBox.h @@ -418,6 +418,7 @@ public: void touchDownAction(Ref *sender, Control::EventType controlEvent); protected: + void updatePosition(float dt); EditBoxImpl* _editBoxImpl; EditBoxDelegate* _delegate; diff --git a/extensions/GUI/CCEditBox/CCEditBoxImpl.h b/extensions/GUI/CCEditBox/CCEditBoxImpl.h index 7cb6c6ed1c..b066ac7550 100644 --- a/extensions/GUI/CCEditBox/CCEditBoxImpl.h +++ b/extensions/GUI/CCEditBox/CCEditBoxImpl.h @@ -69,6 +69,11 @@ public: virtual void setVisible(bool visible) = 0; virtual void setContentSize(const Size& size) = 0; virtual void setAnchorPoint(const Point& anchorPoint) = 0; + + /** + * check the editbox's position, update it when needed + */ + virtual void updatePosition(float dt){}; /** * @js NA * @lua NA diff --git a/extensions/GUI/CCEditBox/CCEditBoxImplIOS.h b/extensions/GUI/CCEditBox/CCEditBoxImplIOS.h index ce088445d3..b64208f4d2 100644 --- a/extensions/GUI/CCEditBox/CCEditBoxImplIOS.h +++ b/extensions/GUI/CCEditBox/CCEditBoxImplIOS.h @@ -101,6 +101,7 @@ public: virtual void setVisible(bool visible); virtual void setContentSize(const Size& size); virtual void setAnchorPoint(const Point& anchorPoint); + virtual void updatePosition(float dt) override; /** * @js NA * @lua NA @@ -116,7 +117,6 @@ public: virtual void closeKeyboard(); virtual void onEndEditing(); - private: void initInactiveLabels(const Size& size); void setInactiveText(const char* pText); diff --git a/extensions/GUI/CCEditBox/CCEditBoxImplIOS.mm b/extensions/GUI/CCEditBox/CCEditBoxImplIOS.mm index 0b035986fd..cbdd1b9185 100644 --- a/extensions/GUI/CCEditBox/CCEditBoxImplIOS.mm +++ b/extensions/GUI/CCEditBox/CCEditBoxImplIOS.mm @@ -614,7 +614,6 @@ void EditBoxImplIOS::setAnchorPoint(const Point& anchorPoint) void EditBoxImplIOS::visit(void) { - } void EditBoxImplIOS::onEnter(void) @@ -626,6 +625,15 @@ void EditBoxImplIOS::onEnter(void) } } +void EditBoxImplIOS::updatePosition(float dt) +{ + if (nullptr != _systemControl) { + this->adjustTextFieldPosition(); + } +} + + + void EditBoxImplIOS::adjustTextFieldPosition() { Size contentSize = _editBox->getContentSize(); diff --git a/extensions/GUI/CCEditBox/CCEditBoxImplMac.h b/extensions/GUI/CCEditBox/CCEditBoxImplMac.h index 481472dba3..76ad6f9966 100644 --- a/extensions/GUI/CCEditBox/CCEditBoxImplMac.h +++ b/extensions/GUI/CCEditBox/CCEditBoxImplMac.h @@ -107,6 +107,7 @@ public: virtual void doAnimationWhenKeyboardMove(float duration, float distance); virtual void openKeyboard(); virtual void closeKeyboard(); + virtual void updatePosition(float dt) override; /** * @js NA * @lua NA diff --git a/extensions/GUI/CCEditBox/CCEditBoxImplMac.mm b/extensions/GUI/CCEditBox/CCEditBoxImplMac.mm index 31805a9b2b..94567b6356 100644 --- a/extensions/GUI/CCEditBox/CCEditBoxImplMac.mm +++ b/extensions/GUI/CCEditBox/CCEditBoxImplMac.mm @@ -382,6 +382,14 @@ NSPoint EditBoxImplMac::convertDesignCoordToScreenCoord(const Point& designCoord return screenPos; } +void EditBoxImplMac::updatePosition(float dt) +{ + if(nullptr != _sysEdit) + { + adjustTextFieldPosition(); + } +} + void EditBoxImplMac::adjustTextFieldPosition() { Size contentSize = _editBox->getContentSize(); From aeecee86a4e53394b6302fe6c4795e5d2b865e78 Mon Sep 17 00:00:00 2001 From: James Chen Date: Mon, 3 Mar 2014 17:14:16 +0800 Subject: [PATCH 33/34] Update CHANGELOG [ci skip] --- CHANGELOG | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG b/CHANGELOG index 63ff949ec2..c012ff74a3 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -17,6 +17,7 @@ cocos2d-x-3.0rc0 Feb.?? 2014 [NEW] Language: Added Dutch support. [NEW] Sprite: Added auto-culling support + [FIX] EditBox's position would not be updated if its parent's position changed. [FIX] spine::Skeleton would not be updated after being re-added to scene. [FIX] Loading custom fonts from ttf file fails on windows. [FIX] FadeIn and FadeOut behaviours is incorrect if it doesn't start from an edge value( 0 or 255). From f2e9ae97e20e623359aa89f8d6eae46ad58a39ef Mon Sep 17 00:00:00 2001 From: qiaofeng00oo Date: Mon, 3 Mar 2014 17:47:55 +0800 Subject: [PATCH 34/34] modify autotest.py in tools/jenkins-scripts --- tools/jenkins-scripts/autotest.py | 75 +++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100755 tools/jenkins-scripts/autotest.py diff --git a/tools/jenkins-scripts/autotest.py b/tools/jenkins-scripts/autotest.py new file mode 100755 index 0000000000..a5ac0df1a2 --- /dev/null +++ b/tools/jenkins-scripts/autotest.py @@ -0,0 +1,75 @@ +import os +import sys +import subprocess +import socket +import time + +HOST = 'localhost' +PORT = 5678 + +def autotest(): + soc = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) + soc.connect((HOST, PORT)) + time.sleep(3) + print 'autotest run:' + soc.send('autotest run\r\n') + + while True: + buf = soc.recv(64) + print buf + + print 'test end and close socket.' + soc.close() + +#----------------autotest build and run----------------# +sleep_time = 1.5 +def cleanProj(): + infoClean = os.system('xcodebuild -project ./build/cocos2d_tests.xcodeproj -target Test\ cpp\ Mac clean') + print 'infoClean: ', infoClean + if infoClean != 0: + print 'clean **CLEAN FAILED**' + time.sleep(sleep_time) +def buildProj(): + infoBuild = os.system('xcodebuild -project ./build/cocos2d_tests.xcodeproj -target Test\ cpp\ Mac') + print 'infoBuild: ', infoBuild + if infoBuild != 0: + print 'build **BUILD FAILED**' + time.sleep(sleep_time) + return infoBuild +def openProj(): + cmd = 'open ./build/build/Debug/Test\ cpp\ Mac.app' + print 'cmd: ', cmd + infoOpen = os.system(cmd) + print 'infoOpen: ', infoOpen + if infoOpen != 0: + print 'open **OPEN FAILED**' + time.sleep(sleep_time) +def buildAndRun(): + # cleanProj() + if buildProj() != 0: + cleanProj() + buildProj() + openProj() + time.sleep(sleep_time) +#----------------autotest build and run end----------------# + +def main(): + try: + buildAndRun() + except Exception, e: + print 'BUILD FAILED!' + else: + autotest() + + +# -------------- main -------------- +if __name__ == '__main__': + sys_ret = 0 + try: + sys_ret = main() + except: + traceback.print_exc() + sys_ret = 1 + finally: + sys.exit(sys_ret) +