diff --git a/CHANGELOG b/CHANGELOG index e2dd788f49..53537c3b14 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -4,6 +4,7 @@ cocos2d-x-3.0rc0 Feb.?? 2014 [NEW] Bindings: Using python to automatically generate script bindings [NEW] Bindings: Added JS bindings support for Linux [NEW] ccConfig.h: removed support for CC_TEXTURE_ATLAS_USE_TRIANGLE_STRIP + [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. @@ -18,6 +19,7 @@ cocos2d-x-3.0rc0 Feb.?? 2014 [NEW] Language: Added Dutch support. [NEW] Sprite: Added auto-culling support. Performance increased in about 100% when many sprites are outside the screen + [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). diff --git a/cocos/2d/CCDirector.cpp b/cocos/2d/CCDirector.cpp index de204a7ca4..4d6f9b2d51 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->scheduleUpdate(_actionManager, Scheduler::PRIORITY_SYSTEM, false); _eventDispatcher = new EventDispatcher(); _eventAfterDraw = new EventCustom(EVENT_AFTER_DRAW); diff --git a/cocos/2d/CCEventDispatcher.cpp b/cocos/2d/CCEventDispatcher.cpp index 13b4b35224..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; @@ -479,9 +506,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()) @@ -544,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(); @@ -554,14 +590,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 +1122,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); } } @@ -1105,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 57dbdd415a..ed6ffdd038 100644 --- a/cocos/2d/CCNode.cpp +++ b/cocos/2d/CCNode.cpp @@ -157,7 +157,7 @@ Node::~Node() CC_SAFE_RELEASE(_actionManager); CC_SAFE_RELEASE(_scheduler); - _eventDispatcher->cleanTarget(this); + _eventDispatcher->removeEventListenersForTarget(this); CC_SAFE_RELEASE(_eventDispatcher); // attributes @@ -420,7 +420,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 } @@ -535,6 +537,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; @@ -720,6 +730,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) @@ -1058,7 +1073,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; @@ -1123,7 +1138,7 @@ void Node::setScheduler(Scheduler* scheduler) bool Node::isScheduled(SEL_SCHEDULE selector) { - return _scheduler->isScheduled(this, schedule_selector_to_key(selector)); + return _scheduler->isScheduled(selector, this); } void Node::scheduleUpdate() @@ -1133,9 +1148,7 @@ void Node::scheduleUpdate() void Node::scheduleUpdateWithPriority(int priority) { - _scheduler->scheduleUpdate([this](float dt){ - this->update(dt); - }, this, priority, !_running); + _scheduler->scheduleUpdate(this, priority, !_running); } void Node::scheduleUpdateWithPriorityLua(int nHandler, int priority) @@ -1145,9 +1158,8 @@ 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->scheduleUpdate(this, priority, !_running); } void Node::unscheduleUpdate() @@ -1178,9 +1190,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->schedule(selector, this, interval , repeat, delay, !_running); } void Node::scheduleOnce(SEL_SCHEDULE selector, float delay) @@ -1194,7 +1204,7 @@ void Node::unschedule(SEL_SCHEDULE selector) if (selector == nullptr) return; - _scheduler->unschedule(this, schedule_selector_to_key(selector)); + _scheduler->unschedule(selector, this); } void Node::unscheduleAllSelectors() @@ -1206,14 +1216,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() @@ -1524,6 +1534,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) @@ -1542,7 +1560,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 7e13a8fb1d..9cb773e069 100644 --- a/cocos/2d/CCNode.h +++ b/cocos/2d/CCNode.h @@ -450,6 +450,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. */ @@ -1384,6 +1385,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/2d/CCScheduler.cpp b/cocos/2d/CCScheduler.cpp index 110f34aad9..530bb99232 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()->unschedule(_selector, _target); +} + +// TimerTargetCallback + +TimerTargetCallback::TimerTargetCallback() +: _target(nullptr) +, _callback(nullptr) +{ +} + +bool TimerTargetCallback::initWithCallback(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()->unschedule(_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::schedule(const ccSchedulerFunc& callback, void *target, float interval, bool paused, const std::string& key) { - this->schedule(callback, target, key, interval, kRepeatForever, 0.0f, paused); + this->schedule(callback, target, interval, kRepeatForever, 0.0f, paused, key); } -void Scheduler::schedule(const ccSchedulerFunc& callback, void *target, long 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 != 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->initWithCallback(callback, target, key, interval, repeat, delay); ccArrayAppendObject(element->timers, timer); timer->release(); } -void Scheduler::unschedule(void *target, long key) +void Scheduler::unschedule(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::schedulePerFrame(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::isScheduled(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::unscheduleUpdate(void *target) { if (target == nullptr) { @@ -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) +void Scheduler::schedule(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) +void Scheduler::schedule(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->schedule(selector, target, interval, kRepeatForever, 0.0f, paused); } -bool Scheduler::isScheduledForTarget(SEL_SCHEDULE selector, Ref *target) +bool Scheduler::isScheduled(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) +void Scheduler::unschedule(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..05b4cd3122 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 initWithCallback(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 // @@ -119,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): @@ -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,115 +196,126 @@ public: */ void update(float dt); + ///////////////////////////////////// + + // schedule + /** 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 + @param key The key to identify the callback + @since v3.0 + */ + 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 schedule(const ccSchedulerFunc& callback, void *target, float interval, bool paused, const std::string& key); + + + /** 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 '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 - - @since v3.0 + + @since v3.0, repeat and delay added in v1.1 */ - void schedule(const ccSchedulerFunc& callback, void *target, long key, 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 schedule(const ccSchedulerFunc& callback, void *target, long key, float interval, bool paused); + 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 v3.0 + @lua NA */ - void scheduleUpdate(const ccSchedulerFunc& callback, void *target, int priority, bool paused); - - /** Checks whether a selector for a given taget is scheduled. - @since v3.0.0 - */ - bool isScheduled(void *target, long key); - - /** Unschedule a selector for a given target. - If you want to unschedule the "update", use unscheudleUpdateForTarget. - @since v3.0 - */ - void unschedule(void *target, long key); - - /** 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 - /** 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 - - @since v0.99.3, repeat and delay added in v1.1 - */ - void scheduleSelector(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); - template - void scheduleUpdateForTarget(T *target, int priority, bool paused) + void scheduleUpdate(T *target, int priority, bool paused) { - target->retain(); - this->scheduleUpdate([=](float dt){ + this->schedulePerFrame([target](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); - - /** Unschedules the update selector for a given target - @since v0.99.3 - */ - void unscheduleUpdateForTarget(Ref *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); - - /** 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); #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 unscheudleUpdate. + @since v3.0 + */ + void unschedule(SEL_SCHEDULE selector, Ref *target); + + /** Unschedules the update selector for a given target + @since v0.99.3 + */ + void unscheduleUpdate(void *target); + + /** 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); + + /** 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); + +#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. @@ -317,8 +360,71 @@ public: @since v3.0 */ 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); + }; + + /** 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::unschedule' 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); }; + + /** 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. + 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 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/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..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()->schedule(CC_CALLBACK_1(TextureCache::addImageAsyncCallBack, this), this, schedule_selector_to_key(schedule_selector(TextureCache::addImageAsyncCallBack)), 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()->unschedule(this, schedule_selector_to_key(schedule_selector(TextureCache::addImageAsyncCallBack))); + 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/editor-support/cocostudio/CCDisplayFactory.cpp b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp index d3f894cf42..e8943fed7a 100644 --- a/cocos/editor-support/cocostudio/CCDisplayFactory.cpp +++ b/cocos/editor-support/cocostudio/CCDisplayFactory.cpp @@ -263,6 +263,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) diff --git a/cocos/editor-support/cocostudio/CCSGUIReader.cpp b/cocos/editor-support/cocostudio/CCSGUIReader.cpp index 71bab642b7..6148c1b8dc 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); } diff --git a/cocos/gui/UIButton.cpp b/cocos/gui/UIButton.cpp index 724c6633fe..de0d0c56f2 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() { @@ -366,8 +386,7 @@ void Button::onPressStateChangedToNormal() else { _buttonNormalRenderer->stopAllActions(); - Action *zoomAction = ScaleTo::create(0.05f, _normalTextureScaleXInSize, _normalTextureScaleYInSize); - _buttonNormalRenderer->runAction(zoomAction); + _buttonNormalRenderer->setScale(_normalTextureScaleXInSize, _normalTextureScaleYInSize); } } @@ -393,8 +412,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); } } diff --git a/cocos/gui/UIButton.h b/cocos/gui/UIButton.h index f23139d39f..b339239293 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 5e9771b4b3..815cd23a17 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 76669ab8d9..51a30f26e3 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 3a13abc41e..31438e76ba 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() @@ -150,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() { @@ -410,6 +430,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) @@ -427,79 +452,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; } @@ -510,6 +539,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)); @@ -617,6 +647,11 @@ void Layout::setBackGroundImageCapInsets(const Rect &capInsets) static_cast(_backGroundImage)->setCapInsets(capInsets); } } + +const Rect& Layout::getBackGroundImageCapInsets() +{ + return _backGroundImageCapInsets; +} void Layout::supplyTheLayoutParameterLackToChild(Widget *child) { @@ -744,6 +779,11 @@ void Layout::setBackGroundColorType(LayoutBackGroundColorType type) break; } } + +LayoutBackGroundColorType Layout::getBackGroundColorType() +{ + return _colorType; +} void Layout::setBackGroundColor(const Color3B &color) { @@ -753,6 +793,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) { @@ -767,6 +812,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) { @@ -785,6 +840,11 @@ void Layout::setBackGroundColorOpacity(int opacity) break; } } + +int Layout::getBackGroundColorOpacity() +{ + return _cOpacity; +} void Layout::setBackGroundColorVector(const Point &vector) { @@ -794,6 +854,11 @@ void Layout::setBackGroundColorVector(const Point &vector) _gradientRender->setVector(vector); } } + +const Point& Layout::getBackGroundColorVector() +{ + return _alongVector; +} const Size& Layout::getBackGroundImageTextureSize() const { @@ -1197,128 +1262,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; diff --git a/cocos/gui/UILayout.h b/cocos/gui/UILayout.h index 67b9006c8f..4d50b7a252 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. * @@ -210,7 +228,24 @@ public: virtual void addChild(Node* child, int zOrder, int tag) override; virtual void visit(Renderer *renderer, const kmMat4 &parentTransform, bool parentTransformUpdated) 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 sortAllChildren() override; void requestDoLayout(); @@ -273,6 +308,7 @@ protected: Rect _clippingRect; Layout* _clippingParent; bool _doLayoutDirty; + bool _clippingRectDirty; //clipping diff --git a/cocos/gui/UILayoutParameter.cpp b/cocos/gui/UILayoutParameter.cpp index 137647d306..93ba0edf31 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 ce3bec9d73..bf3dae2d6a 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() override; + virtual void copyProperties(LayoutParameter* model) override; protected: LinearGravity _linearGravity; }; @@ -202,6 +208,9 @@ public: * @return name */ const char* getRelativeName() const; + + virtual LayoutParameter* createCloneInstance() override; + virtual void copyProperties(LayoutParameter* model) override; protected: RelativeAlign _relativeAlign; std::string _relativeWidgetName; diff --git a/cocos/gui/UIListView.cpp b/cocos/gui/UIListView.cpp index 10bcb24a83..10e1e3a637 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 ff24bf9838..454f5d6465 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 ec006e4a72..38d8ac5611 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) @@ -334,6 +344,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/UILoadingBar.h b/cocos/gui/UILoadingBar.h index 7998869c3d..ac8512e747 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 658796d7ac..dcf4436b40 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 07e1fd14e7..edc8291d1a 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 49d7a3c7fe..9a1da92498 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 75277b43e0..4cbe585fe2 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 c747ccf834..137545e3c7 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,36 +110,53 @@ 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) { _touchScaleChangeEnabled = enable; - _normalScaleValueX = getScaleX(); - _normalScaleValueY = getScaleY(); } void Text::setScale(float fScale) { Widget::setScale(fScale); - _normalScaleValueX = _normalScaleValueY = fScale; } void Text::setScaleX(float fScaleX) @@ -158,7 +180,7 @@ void Text::onPressStateChangedToNormal() { return; } - clickScale(_normalScaleValueX, _normalScaleValueY); + _labelRenderer->setScale(_normalScaleValueX, _normalScaleValueY); } void Text::onPressStateChangedToPressed() @@ -167,9 +189,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 +197,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 +245,7 @@ void Text::labelScaleChangedWithSize() { _labelRenderer->setScale(1.0f); _size = _labelRenderer->getContentSize(); + _normalScaleValueX = _normalScaleValueY = 1.0f; } else { @@ -244,6 +259,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 327b9d52a1..73abdaf10e 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; @@ -166,7 +179,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; diff --git a/cocos/gui/UITextField.cpp b/cocos/gui/UITextField.cpp index 4a1d2ca327..3a7d68657d 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 27d3ceb5a5..1c3ef3b74d 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); diff --git a/cocos/gui/UIWidget.cpp b/cocos/gui/UIWidget.cpp index 7ecfe2f93a..ae9968c77d 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(); } 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/cocos/physics/CCPhysicsBody.cpp b/cocos/physics/CCPhysicsBody.cpp index 46b2ab4637..dd577231be 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,36 @@ void PhysicsBody::setGroup(int group) } } +void PhysicsBody::setPositionOffset(const Point& position) +{ + if (!_positionOffset.equals(position)) + { + Point pos = getPosition(); + _positionOffset = position; + setPosition(pos); + } +} + +Point PhysicsBody::getPositionOffset() const +{ + return _positionOffset; +} + +void PhysicsBody::setRotationOffset(float rotation) +{ + if (std::abs(_rotationOffset - rotation) > 0.5f) + { + float rot = getRotation(); + _rotationOffset = rotation; + setRotation(rot); + } +} + +float PhysicsBody::getRotationOffset() const +{ + 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..ea09a7f2f1 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() const; + /** set body rotation offset, it's the rotation witch relative to node */ + void setRotationOffset(float rotation); + /** set the body rotation offset */ + float getRotationOffset() const; + /** * @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; 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; }; diff --git a/extensions/GUI/CCEditBox/CCEditBox.cpp b/extensions/GUI/CCEditBox/CCEditBox.cpp index 479f28b905..32f37f6e4f 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 90b962d516..5ecb9cca27 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(); diff --git a/install.py b/install.py new file mode 100755 index 0000000000..e5fbda02b4 --- /dev/null +++ b/install.py @@ -0,0 +1,190 @@ +#!/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__)) + ndk_root = None + + @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() + + @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(): + + # python on linux doesn't include Tkinter model, so let user input in terminal + if SetEnvVar._isLinux(): + while True: + + input_value = raw_input('Enter path of ndk, press enter to skip: ') + if not input_value: + break + + 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: + SetEnvVar.ndk_root = os.environ[NDK_ROOT] + except Exception: + root = Tkinter.Tk() + SetEnvVar._center(root) + + def callback(): + 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) + Tkinter.Button(frame, text='...', command=callback).pack(side=Tkinter.LEFT) + frame.pack() + root.mainloop() + + @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 + 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: + SetEnvVar.ndk_root = value + else: + SetEnvVar._get_ndk_root() + + print "ndk_root is %s" % SetEnvVar.ndk_root + + if SetEnvVar.ndk_root: + os.environ[NDK_ROOT] = SetEnvVar.ndk_root + SetEnvVar._set_environment_variable(NDK_ROOT, SetEnvVar.ndk_root) + + +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 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/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/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/NewEventDispatcherTest/NewEventDispatcherTest.cpp b/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp index c9f1f403d3..7b4ff93a6c 100644 --- a/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp +++ b/tests/Classes/NewEventDispatcherTest/NewEventDispatcherTest.cpp @@ -24,7 +24,9 @@ std::function createFunctions[] = CL(DirectorEventTest), CL(GlobalZTouchTest), CL(StopPropagationTest), + CL(PauseResumeTargetTest), CL(Issue4129), + CL(Issue4160) }; unsigned int TEST_CASE_COUNT = sizeof(createFunctions) / sizeof(createFunctions[0]); @@ -186,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); @@ -222,22 +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) - , _useNodePriority(false) + , _fixedPriority(priority) + , _removeListenerOnTouchEnded(false) { } - void setPriority(int fixedPriority) { _fixedPriority = fixedPriority; _useNodePriority = false; }; - void setPriorityWithThis(bool useNodePriority) { _useNodePriority = useNodePriority; _fixedPriority = true; } - +public: void onEnter() override { Sprite::onEnter(); @@ -259,22 +271,24 @@ 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 + if (_fixedPriority != 0) { _eventDispatcher->addEventListenerWithFixedPriority(listener, _fixedPriority); } + else + { + _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this); + } + _listener = listener; } @@ -285,10 +299,12 @@ public: Sprite::onExit(); } + void removeListenerOnTouchEnded(bool toRemove) { _removeListenerOnTouchEnded = toRemove; }; + private: EventListener* _listener; int _fixedPriority; - bool _useNodePriority; + bool _removeListenerOnTouchEnded; }; void FixedPriorityTest::onEnter() @@ -298,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); @@ -704,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(); }); @@ -1090,6 +1103,73 @@ 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) { @@ -1152,3 +1232,40 @@ 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 = TouchableSprite::create(-30); + 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(-20); + sprite2->setTexture("Images/MagentaSquare.png"); + sprite2->removeListenerOnTouchEnded(true); + sprite2->setPosition(origin+Point(size.width/2, size.height/2)); + addChild(sprite2, -20); + + auto sprite3 = TouchableSprite::create(-10); + sprite3->setTexture("Images/YellowSquare.png"); + 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..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: @@ -180,5 +193,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__) */ 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 27dcc0f6ce..36d975b188 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 0d91cb729a..8192242bf2 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 6ca6cc1240..b490ecb4a6 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/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/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 diff --git a/tests/Classes/SchedulerTest/SchedulerTest.cpp b/tests/Classes/SchedulerTest/SchedulerTest.cpp index ec2dd5ece4..37597f6cb6 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()->scheduleUpdate(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->scheduleUpdate(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->scheduleUpdate(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->scheduleUpdate(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->scheduleUpdate(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\ +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 schedule(global_function, ...), dt = %f", dt); +} + +void ScheduleCallbackTest::onEnter() +{ + SchedulerTestLayer::onEnter(); + + _scheduler->schedule([](float dt){ + log("In the callback of schedule(lambda, ...), dt = %f", dt); + }, this, 1.0f, false, "lambda"); + + _scheduler->schedule(CC_CALLBACK_1(ScheduleCallbackTest::callback, this), this, 1.0f, false, "member_function"); + + _scheduler->schedule(ScheduleCallbackTest_global_callback, this, 1.0f, false, "global_function"); +} + +void ScheduleCallbackTest::callback(float dt) +{ + log("In the callback of schedule(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: diff --git a/tests/Classes/ShaderTest/ShaderTest.cpp b/tests/Classes/ShaderTest/ShaderTest.cpp index 5fccff59f5..21e4a9e43a 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; 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..8ffa816786 100644 --- a/tests/Classes/controller.cpp +++ b/tests/Classes/controller.cpp @@ -3,7 +3,8 @@ #include #include #include - +#include +#include // test inclues #include "AppDelegate.h" #include "BaseTest.h" @@ -111,6 +112,13 @@ static Controller *currentController = nullptr; static Point s_tCurPos = Point::ZERO; +//sleep for t seconds +static void wait(int t) +{ + std::chrono::milliseconds dura( t * 1000 ); + std::this_thread::sleep_for( dura ); +} + TestController::TestController() : _beginPos(Point::ZERO) { @@ -337,13 +345,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:"); 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) +