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

This commit is contained in:
samuelhu 2013-10-29 17:58:00 +08:00
commit b611177a65
125 changed files with 1713 additions and 1371 deletions

View File

@ -59,7 +59,7 @@ THE SOFTWARE.
#include "platform/CCImage.h" #include "platform/CCImage.h"
#include "CCEGLView.h" #include "CCEGLView.h"
#include "CCConfiguration.h" #include "CCConfiguration.h"
#include "CCEventDispatcher.h"
/** /**
Position of the FPS Position of the FPS
@ -143,6 +143,8 @@ bool Director::init(void)
_actionManager = new ActionManager(); _actionManager = new ActionManager();
_scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false); _scheduler->scheduleUpdateForTarget(_actionManager, Scheduler::PRIORITY_SYSTEM, false);
_eventDispatcher = new EventDispatcher();
// create autorelease pool // create autorelease pool
PoolManager::sharedPoolManager()->push(); PoolManager::sharedPoolManager()->push();
@ -162,6 +164,7 @@ Director::~Director(void)
CC_SAFE_RELEASE(_scenesStack); CC_SAFE_RELEASE(_scenesStack);
CC_SAFE_RELEASE(_scheduler); CC_SAFE_RELEASE(_scheduler);
CC_SAFE_RELEASE(_actionManager); CC_SAFE_RELEASE(_actionManager);
CC_SAFE_RELEASE(_eventDispatcher);
// pop the autorelease pool // pop the autorelease pool
PoolManager::sharedPoolManager()->pop(); PoolManager::sharedPoolManager()->pop();
@ -229,8 +232,6 @@ void Director::setGLDefaultValues()
// Draw the Scene // Draw the Scene
void Director::drawScene() void Director::drawScene()
{ {
Node::resetEventPriorityIndex();
// calculate "global" dt // calculate "global" dt
calculateDeltaTime(); calculateDeltaTime();
@ -697,7 +698,6 @@ void Director::purgeDirector()
// cocos2d-x specific data structures // cocos2d-x specific data structures
UserDefault::destroyInstance(); UserDefault::destroyInstance();
NotificationCenter::destroyInstance(); NotificationCenter::destroyInstance();
EventDispatcher::destroyInstance();
GL::invalidateStateCache(); GL::invalidateStateCache();
@ -968,6 +968,21 @@ ActionManager* Director::getActionManager() const
return _actionManager; return _actionManager;
} }
EventDispatcher* Director::getEventDispatcher() const
{
return _eventDispatcher;
}
void Director::setEventDispatcher(EventDispatcher* dispatcher)
{
if (_eventDispatcher != dispatcher)
{
CC_SAFE_RETAIN(dispatcher);
CC_SAFE_RELEASE(_eventDispatcher);
_eventDispatcher = dispatcher;
}
}
/*************************************************** /***************************************************
* implementation of DisplayLinkDirector * implementation of DisplayLinkDirector
**************************************************/ **************************************************/

View File

@ -53,10 +53,7 @@ class DirectorDelegate;
class Node; class Node;
class Scheduler; class Scheduler;
class ActionManager; class ActionManager;
class TouchDispatcher; class EventDispatcher;
class KeyboardDispatcher;
class KeypadDispatcher;
class Accelerometer;
/** /**
@brief Class that creates and handles the main Window and manages how @brief Class that creates and handles the main Window and manages how
@ -351,6 +348,17 @@ public:
@since v2.0 @since v2.0
*/ */
void setActionManager(ActionManager* actionManager); void setActionManager(ActionManager* actionManager);
/** Gets the EventDispatcher associated with this director
@since v3.0
*/
EventDispatcher* getEventDispatcher() const;
/** Sets the EventDispatcher associated with this director
@since v3.0
*/
void setEventDispatcher(EventDispatcher* dispatcher);
/* Gets delta time since last tick to main loop */ /* Gets delta time since last tick to main loop */
float getDeltaTime() const; float getDeltaTime() const;
@ -384,6 +392,11 @@ protected:
*/ */
ActionManager* _actionManager; ActionManager* _actionManager;
/** EventDispatcher associated with this director
@since v3.0
*/
EventDispatcher* _eventDispatcher;
/* delta time since last tick to main loop */ /* delta time since last tick to main loop */
float _deltaTime; float _deltaTime;

View File

@ -26,7 +26,7 @@
NS_CC_BEGIN NS_CC_BEGIN
Event::Event(const std::string& type) Event::Event(Type type)
: _type(type) : _type(type)
, _isStopped(false) , _isStopped(false)
, _currentTarget(nullptr) , _currentTarget(nullptr)

View File

@ -40,15 +40,24 @@ class Node;
*/ */
class Event class Event
{ {
public:
enum class Type
{
TOUCH,
KEYBOARD,
ACCELERATION,
CUSTOM
};
protected: protected:
/** Constructor */ /** Constructor */
Event(const std::string& type); Event(Type type);
public: public:
/** Destructor */ /** Destructor */
virtual ~Event(); virtual ~Event();
/** Gets the event type */ /** Gets the event type */
inline const std::string& getType() const { return _type; }; inline Type getType() const { return _type; };
/** Stops propagation for current event */ /** Stops propagation for current event */
inline void stopPropagation() { _isStopped = true; }; inline void stopPropagation() { _isStopped = true; };
@ -67,7 +76,8 @@ protected:
/** Sets current target */ /** Sets current target */
inline void setCurrentTarget(Node* target) { _currentTarget = target; }; inline void setCurrentTarget(Node* target) { _currentTarget = target; };
std::string _type; ///< Event type Type _type; ///< Event type
bool _isStopped; ///< whether the event has been stopped. bool _isStopped; ///< whether the event has been stopped.
Node* _currentTarget; ///< Current target Node* _currentTarget; ///< Current target

View File

@ -26,10 +26,8 @@
NS_CC_BEGIN NS_CC_BEGIN
const char* EventAcceleration::EVENT_TYPE = "AccelerometerEvent";
EventAcceleration::EventAcceleration(Acceleration acc) EventAcceleration::EventAcceleration(Acceleration acc)
: Event(EVENT_TYPE) : Event(Type::ACCELERATION)
, _acc(acc) , _acc(acc)
{ {
} }

View File

@ -33,7 +33,6 @@ NS_CC_BEGIN
class EventAcceleration : public Event class EventAcceleration : public Event
{ {
public: public:
static const char* EVENT_TYPE;
EventAcceleration(Acceleration acc); EventAcceleration(Acceleration acc);

View File

@ -23,12 +23,15 @@
****************************************************************************/ ****************************************************************************/
#include "CCEventCustom.h" #include "CCEventCustom.h"
#include "ccMacros.h"
#include <functional>
NS_CC_BEGIN NS_CC_BEGIN
EventCustom::EventCustom(const std::string& eventName) EventCustom::EventCustom(const std::string& eventName)
: Event(eventName) : Event(Type::CUSTOM)
, _userData(nullptr) , _userData(nullptr)
, _eventName(eventName)
{ {
} }

View File

@ -35,14 +35,17 @@ public:
/** Constructor */ /** Constructor */
EventCustom(const std::string& eventName); EventCustom(const std::string& eventName);
/** Set user data */ /** Sets user data */
inline void setUserData(void* data) { _userData = data; }; inline void setUserData(void* data) { _userData = data; };
/** Get user data */ /** Gets user data */
inline void* getUserData() const { return _userData; }; inline void* getUserData() const { return _userData; };
/** Gets event name */
inline const std::string& getEventName() const { return _eventName; };
protected: protected:
void* _userData; ///< User data void* _userData; ///< User data
std::string _eventName;
}; };
NS_CC_END NS_CC_END

File diff suppressed because it is too large Load Diff

View File

@ -27,10 +27,11 @@
#include "CCPlatformMacros.h" #include "CCPlatformMacros.h"
#include "CCEventListener.h" #include "CCEventListener.h"
#include "CCEvent.h"
#include <functional> #include <functional>
#include <string> #include <string>
#include <map> #include <unordered_map>
#include <list> #include <list>
#include <vector> #include <vector>
@ -49,15 +50,9 @@ event listeners can be added and removed even
from within an EventListener, while events are being from within an EventListener, while events are being
dispatched. dispatched.
*/ */
class EventDispatcher class EventDispatcher : public Object
{ {
public: public:
/** Gets the singleton of EventDispatcher */
static EventDispatcher* getInstance();
/** Destroys the singleton of EventDispatcher */
static void destroyInstance();
/** Adds a event listener for a specified event with the priority of scene graph. /** Adds a event listener for a specified event with the priority of scene graph.
* @param listener The listener of a specified event. * @param listener The listener of a specified event.
* @param node The priority of the listener is based on the draw order of this node. * @param node The priority of the listener is based on the draw order of this node.
@ -79,11 +74,14 @@ public:
*/ */
void removeEventListener(EventListener* listener); void removeEventListener(EventListener* listener);
/** Removes all listeners with the same event type */ /** Removes all listeners with the same event listener type */
void removeListenersForEventType(const std::string& eventType); void removeEventListeners(EventListener::Type listenerType);
/** Removes all custom listeners with the same event name */
void removeCustomEventListeners(const std::string& customEventName);
/** Removes all listeners */ /** Removes all listeners */
void removeAllListeners(); void removeAllEventListeners();
/** Sets listener's priority with fixed value. */ /** Sets listener's priority with fixed value. */
void setPriority(EventListener* listener, int fixedPriority); void setPriority(EventListener* listener, int fixedPriority);
@ -98,59 +96,134 @@ public:
* Also removes all EventListeners marked for deletion from the * Also removes all EventListeners marked for deletion from the
* event dispatcher list. * event dispatcher list.
*/ */
void dispatchEvent(Event* event, bool forceSortListeners = false); void dispatchEvent(Event* event);
void setDirtyForEventType(const std::string& eventType, bool isDirty); /** Constructor of EventDispatcher */
EventDispatcher();
bool isDirtyForEventType(const std::string& eventType);
public:
/** Destructor of EventDispatcher */ /** Destructor of EventDispatcher */
~EventDispatcher(); ~EventDispatcher();
private: private:
struct EventListenerItem friend class Node;
/** 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.
*/
class EventListenerVector
{ {
int fixedPriority; // The higher the number, the higher the priority public:
Node* node; // Weak reference. EventListenerVector();
EventListener* listener; ~EventListenerVector();
~EventListenerItem(); size_t size() const;
bool empty() const;
void push_back(EventListener* item);
void clearSceneGraphListeners();
void clearFixedListeners();
void clear();
inline std::vector<EventListener*>* getFixedPriorityListeners() const { return _fixedListeners; };
inline std::vector<EventListener*>* getSceneGraphPriorityListeners() const { return _sceneGraphListeners; };
inline int getGt0Index() const { return _gt0Index; };
inline void setGt0Index(int index) { _gt0Index = index; };
private:
std::vector<EventListener*>* _fixedListeners;
std::vector<EventListener*>* _sceneGraphListeners;
int _gt0Index;
}; };
/** Constructor of EventDispatcher */
EventDispatcher();
/** Adds event listener with item */ /** Adds event listener with item */
void addEventListenerWithItem(EventListenerItem* item); void addEventListener(EventListener* listener);
/** Gets event the listener list for the event listener type. */
EventListenerVector* getListeners(EventListener::ListenerID listenerID);
/** Update dirty flag */
void updateDirtyFlagForSceneGraph();
/** Removes all listeners with the same event listener ID */
void removeEventListenersForListenerID(EventListener::ListenerID listenerID);
/** Sort event listener */
void sortEventListeners(EventListener::ListenerID listenerID);
/** Sorts the listeners of specified type by scene graph priority */
void sortEventListenersOfSceneGraphPriority(EventListener::ListenerID listenerID);
/** Sorts the listeners of specified type by fixed priority */
void sortEventListenersOfFixedPriority(EventListener::ListenerID listenerID);
/** Updates all listeners
* 1) Removes all listener items that have been marked as 'removed' when dispatching event.
* 2) Adds all listener items that have been marked as 'added' when dispatching event.
*/
void updateListeners(Event* event);
/** Touch event needs to be processed different with other events since it needs support ALL_AT_ONCE and ONE_BY_NONE mode. */ /** Touch event needs to be processed different with other events since it needs support ALL_AT_ONCE and ONE_BY_NONE mode. */
void dispatchTouchEvent(EventTouch* event); void dispatchTouchEvent(EventTouch* event);
/** Gets event the listener list for the event type. */ /** Associates node with event listener */
std::vector<EventListenerItem*>* getListenerItemsForType(const std::string& eventType); void associateNodeAndEventListener(Node* node, EventListener* listener);
/** Sorts the listeners of specified type by priority */ /** Dissociates node with event listener */
void sortAllEventListenerItemsForType(const std::string& eventType); void dissociateNodeAndEventListener(Node* node, EventListener* listener);
/** Updates all listener items /** Dispatches event to listeners with a specified listener type */
* 1) Removes all listener items that have been marked as 'removed' when dispatching event. void dispatchEventToListeners(EventListenerVector* listeners, std::function<bool(EventListener*)> onEvent);
* 2) Adds all listener items that have been marked as 'added' when dispatching event.
*/
void updateListenerItems();
private:
/**
* Listeners map.
*/
std::map<std::string, std::vector<EventListenerItem*>*> _listeners;
/// Priority dirty flag /// Priority dirty flag
std::map<std::string, bool> _priorityDirtyFlagMap; enum class DirtyFlag
{
NONE = 0,
FIXED_PRITORY = 1 << 0,
SCENE_GRAPH_PRIORITY = 1 << 1,
ALL = FIXED_PRITORY | SCENE_GRAPH_PRIORITY
};
std::vector<EventListenerItem*> _toAddedListeners; /** Sets the dirty flag for a specified listener ID */
void setDirty(EventListener::ListenerID listenerID, DirtyFlag flag);
int _inDispatch; ///< Whether it's in dispatching event /** Walks though scene graph to get the draw order for each node, it's called before sorting event listener with scene graph priority */
bool _isEnabled; ///< Whether to enable dispatching event void visitTarget(Node* node);
private:
/** Listeners map */
std::unordered_map<EventListener::ListenerID, EventListenerVector*> _listeners;
/** The map of dirty flag */
std::unordered_map<EventListener::ListenerID, DirtyFlag> _priorityDirtyFlagMap;
/** The map of node and event listeners */
std::unordered_map<Node*, std::vector<EventListener*>*> _nodeListenersMap;
/** The map of node and its event priority */
std::unordered_map<Node*, int> _nodePriorityMap;
/** The listeners to be added after dispatching event */
std::vector<EventListener*> _toAddedListeners;
/** The nodes were associated with scene graph based priority listeners */
std::set<Node*> _dirtyNodes;
/** Whether the dispatcher is dispatching event */
int _inDispatch;
/** Whether to enable dispatching event */
bool _isEnabled;
int _nodePriorityIndex;
}; };

View File

@ -27,6 +27,10 @@
NS_CC_BEGIN NS_CC_BEGIN
const char* EventKeyboard::EVENT_TYPE = "KeyboardEvent"; EventKeyboard::EventKeyboard(KeyCode keyCode, bool isPressed)
: Event(Type::KEYBOARD)
, _keyCode(keyCode)
, _isPressed(isPressed)
{}
NS_CC_END NS_CC_END

View File

@ -196,13 +196,7 @@ public:
KEY_SEARCH = 0xFFAA KEY_SEARCH = 0xFFAA
}; };
static const char* EVENT_TYPE; EventKeyboard(KeyCode keyCode, bool isPressed);
EventKeyboard(KeyCode keyCode, bool isPressed)
: Event(EVENT_TYPE)
, _keyCode(keyCode)
, _isPressed(isPressed)
{};
private: private:
KeyCode _keyCode; KeyCode _keyCode;

View File

@ -35,16 +35,18 @@ EventListener::~EventListener()
CCLOGINFO("In the destructor of EventListener. %p", this); CCLOGINFO("In the destructor of EventListener. %p", this);
} }
bool EventListener::init(const std::string& t, std::function<void(Event*)> callback) bool EventListener::init(Type t, ListenerID listenerID, std::function<void(Event*)> callback)
{ {
_onEvent = callback; _onEvent = callback;
_type = t; _type = t;
_listenerID = listenerID;
_isRegistered = false; _isRegistered = false;
_paused = true;
return true; return true;
} }
bool EventListener::checkAvaiable() bool EventListener::checkAvailable()
{ {
return (_onEvent != nullptr); return (_onEvent != nullptr);
} }

View File

@ -31,40 +31,77 @@
#include <functional> #include <functional>
#include <string> #include <string>
#include <memory> #include <memory>
#include <set>
NS_CC_BEGIN NS_CC_BEGIN
class Event; class Event;
class Node;
/** /**
* The base class of event listener. * The base class of event listener.
* If you need custom listener which with different callback, you need to inherit this class. * If you need custom listener which with different callback, you need to inherit this class.
* For instance, you could refer to AccelerationEventListener, KeyboardEventListener or TouchEventListener, CustomEventListener. * For instance, you could refer to EventListenerAcceleration, EventListenerKeyboard, EventListenerTouchOneByOne, EventListenerCustom.
*/ */
class EventListener : public Object class EventListener : public Object
{ {
public:
enum class Type
{
UNKNOWN,
TOUCH_ONE_BY_ONE,
TOUCH_ALL_AT_ONCE,
KEYBOARD,
ACCELERATION,
CUSTOM
};
typedef int ListenerID;
protected: protected:
/** Constructor */ /** Constructor */
EventListener(); EventListener();
/** Initializes event with type and callback function */ /** Initializes event with type and callback function */
bool init(const std::string& t, std::function<void(Event*)>callback); bool init(Type t, ListenerID listenerID, std::function<void(Event*)>callback);
public: public:
/** Destructor */ /** Destructor */
virtual ~EventListener(); virtual ~EventListener();
/** Checks whether the listener is available. */ /** Checks whether the listener is available. */
virtual bool checkAvaiable() = 0; virtual bool checkAvailable() = 0;
/** Clones the listener, its subclasses have to override this method. */ /** Clones the listener, its subclasses have to override this method. */
virtual EventListener* clone() = 0; virtual EventListener* clone() = 0;
protected: protected:
inline void setPaused(bool paused) { _paused = paused; };
inline bool isPaused() const { return _paused; };
inline void setRegistered(bool registered) { _isRegistered = registered; };
inline bool isRegistered() const { return _isRegistered; };
inline Type getType() const { return _type; };
inline ListenerID getListenerID() const { return _listenerID; };
inline void setFixedPriority(int fixedPriority) { _fixedPriority = fixedPriority; };
inline int getFixedPriority() const { return _fixedPriority; };
inline void setSceneGraphPriority(Node* node) { _node = node; };
inline Node* getSceneGraphPriority() const { return _node; };
std::function<void(Event*)> _onEvent; /// Event callback function std::function<void(Event*)> _onEvent; /// Event callback function
std::string _type; /// Event type
bool _isRegistered; /// Whether the listener has been added to dispatcher. Type _type; /// Event listener type
ListenerID _listenerID; /// Event listener ID
bool _isRegistered; /// Whether the listener has been added to dispatcher.
// The priority of event listener
int _fixedPriority; // The higher the number, the higher the priority, 0 is for scene graph base priority.
Node* _node; // scene graph based priority
bool _paused; // Whether the listener is paused
friend class EventDispatcher; friend class EventDispatcher;
friend class Node;
}; };
NS_CC_END NS_CC_END

View File

@ -37,7 +37,7 @@ EventListenerAcceleration::~EventListenerAcceleration()
CCLOGINFO("In the destructor of AccelerationEventListener. %p", this); CCLOGINFO("In the destructor of AccelerationEventListener. %p", this);
} }
EventListenerAcceleration* EventListenerAcceleration::create(std::function<void(Acceleration*, Event* event)> callback) EventListenerAcceleration* EventListenerAcceleration::create(std::function<void(Acceleration*, Event*)> callback)
{ {
EventListenerAcceleration* ret = new EventListenerAcceleration(); EventListenerAcceleration* ret = new EventListenerAcceleration();
if (ret && ret->init(callback)) if (ret && ret->init(callback))
@ -59,7 +59,7 @@ bool EventListenerAcceleration::init(std::function<void(Acceleration*, Event* ev
this->onAccelerationEvent(&accEvent->_acc, event); this->onAccelerationEvent(&accEvent->_acc, event);
}; };
if (EventListener::init(EventAcceleration::EVENT_TYPE, listener)) if (EventListener::init(Type::ACCELERATION, static_cast<ListenerID>(Type::ACCELERATION), listener))
{ {
onAccelerationEvent = callback; onAccelerationEvent = callback;
return true; return true;
@ -84,7 +84,7 @@ EventListenerAcceleration* EventListenerAcceleration::clone()
return ret; return ret;
} }
bool EventListenerAcceleration::checkAvaiable() bool EventListenerAcceleration::checkAvailable()
{ {
CCASSERT(onAccelerationEvent, ""); CCASSERT(onAccelerationEvent, "");

View File

@ -33,12 +33,12 @@ NS_CC_BEGIN
class EventListenerAcceleration : public EventListener class EventListenerAcceleration : public EventListener
{ {
public: public:
static EventListenerAcceleration* create(std::function<void(Acceleration*, Event* event)> callback); static EventListenerAcceleration* create(std::function<void(Acceleration*, Event*)> callback);
virtual ~EventListenerAcceleration(); virtual ~EventListenerAcceleration();
/// Overrides /// Overrides
virtual EventListenerAcceleration* clone() override; virtual EventListenerAcceleration* clone() override;
virtual bool checkAvaiable() override; virtual bool checkAvailable() override;
private: private:
EventListenerAcceleration(); EventListenerAcceleration();

View File

@ -35,7 +35,7 @@ EventListenerCustom::EventListenerCustom()
EventListenerCustom* EventListenerCustom::create(const std::string& eventName, std::function<void(EventCustom*)> callback) EventListenerCustom* EventListenerCustom::create(const std::string& eventName, std::function<void(EventCustom*)> callback)
{ {
EventListenerCustom* ret = new EventListenerCustom(); EventListenerCustom* ret = new EventListenerCustom();
if (ret && ret->init(eventName, callback)) if (ret && ret->init(std::hash<std::string>()(eventName), callback))
{ {
ret->autorelease(); ret->autorelease();
} }
@ -46,7 +46,7 @@ EventListenerCustom* EventListenerCustom::create(const std::string& eventName, s
return ret; return ret;
} }
bool EventListenerCustom::init(const std::string& eventName, std::function<void(EventCustom*)>callback) bool EventListenerCustom::init(ListenerID listenerId, std::function<void(EventCustom*)>callback)
{ {
bool ret = false; bool ret = false;
@ -59,7 +59,7 @@ bool EventListenerCustom::init(const std::string& eventName, std::function<void(
} }
}; };
if (EventListener::init(eventName, listener)) if (EventListener::init(EventListener::Type::CUSTOM, listenerId, listener))
{ {
ret = true; ret = true;
} }
@ -69,7 +69,7 @@ bool EventListenerCustom::init(const std::string& eventName, std::function<void(
EventListenerCustom* EventListenerCustom::clone() EventListenerCustom* EventListenerCustom::clone()
{ {
EventListenerCustom* ret = new EventListenerCustom(); EventListenerCustom* ret = new EventListenerCustom();
if (ret && ret->init(_type, _onCustomEvent)) if (ret && ret->init(_listenerID, _onCustomEvent))
{ {
ret->autorelease(); ret->autorelease();
} }
@ -80,10 +80,10 @@ EventListenerCustom* EventListenerCustom::clone()
return ret; return ret;
} }
bool EventListenerCustom::checkAvaiable() bool EventListenerCustom::checkAvailable()
{ {
bool ret = false; bool ret = false;
if (EventListener::checkAvaiable() && _onCustomEvent != nullptr) if (EventListener::checkAvailable() && _onCustomEvent != nullptr)
{ {
ret = true; ret = true;
} }

View File

@ -33,21 +33,21 @@ class EventCustom;
/** /**
* Usage: * Usage:
* auto dispatcher = EventDispatcher::getInstance(); * auto dispatcher = Director::getInstance()->getEventDispatcher();
* Adds a listener: * Adds a listener:
* *
* auto callback = [](CustomEvent* event){ do_some_thing(); }; * auto callback = [](EventCustom* event){ do_some_thing(); };
* auto listener = CustomEventListener::create(callback); * auto listener = EventListenerCustom::create(callback);
* dispatcher->addEventListenerWithSceneGraphPriority(listener, one_node); * dispatcher->addEventListenerWithSceneGraphPriority(listener, one_node);
* *
* Dispatchs a custom event: * Dispatchs a custom event:
* *
* Event event("your_event_type"); * EventCustom event("your_event_type");
* dispatcher->dispatchEvent(&event); * dispatcher->dispatchEvent(&event);
* *
* Removes a listener * Removes a listener
* *
* dispatcher->removeListener(listener); * dispatcher->removeEventListener(listener);
*/ */
class EventListenerCustom : public EventListener class EventListenerCustom : public EventListener
{ {
@ -59,7 +59,7 @@ public:
static EventListenerCustom* create(const std::string& eventName, std::function<void(EventCustom*)> callback); static EventListenerCustom* create(const std::string& eventName, std::function<void(EventCustom*)> callback);
/// Overrides /// Overrides
virtual bool checkAvaiable() override; virtual bool checkAvailable() override;
virtual EventListenerCustom* clone() override; virtual EventListenerCustom* clone() override;
protected: protected:
@ -67,7 +67,7 @@ protected:
EventListenerCustom(); EventListenerCustom();
/** Initializes event with type and callback function */ /** Initializes event with type and callback function */
bool init(const std::string& eventName, std::function<void(EventCustom*)> callback); bool init(ListenerID listenerId, std::function<void(EventCustom*)> callback);
std::function<void(EventCustom*)> _onCustomEvent; std::function<void(EventCustom*)> _onCustomEvent;
}; };

View File

@ -29,7 +29,7 @@
NS_CC_BEGIN NS_CC_BEGIN
bool EventListenerKeyboard::checkAvaiable() bool EventListenerKeyboard::checkAvailable()
{ {
CCASSERT(onKeyPressed && onKeyReleased, ""); CCASSERT(onKeyPressed && onKeyReleased, "");
@ -88,7 +88,7 @@ bool EventListenerKeyboard::init()
} }
}; };
if (EventListener::init(EventKeyboard::EVENT_TYPE, listener)) if (EventListener::init(Type::KEYBOARD, static_cast<ListenerID>(Type::KEYBOARD), listener))
{ {
return true; return true;
} }

View File

@ -40,10 +40,10 @@ public:
/// Overrides /// Overrides
virtual EventListenerKeyboard* clone() override; virtual EventListenerKeyboard* clone() override;
virtual bool checkAvaiable() override; virtual bool checkAvailable() override;
std::function<void(EventKeyboard::KeyCode, Event* event)> onKeyPressed; std::function<void(EventKeyboard::KeyCode, Event*)> onKeyPressed;
std::function<void(EventKeyboard::KeyCode, Event* event)> onKeyReleased; std::function<void(EventKeyboard::KeyCode, Event*)> onKeyReleased;
private: private:
EventListenerKeyboard(); EventListenerKeyboard();
bool init(); bool init();

View File

@ -30,46 +30,39 @@
NS_CC_BEGIN NS_CC_BEGIN
EventListenerTouch::EventListenerTouch() EventListenerTouchOneByOne::EventListenerTouchOneByOne()
: onTouchBegan(nullptr) : onTouchBegan(nullptr)
, onTouchMoved(nullptr) , onTouchMoved(nullptr)
, onTouchEnded(nullptr) , onTouchEnded(nullptr)
, onTouchCancelled(nullptr) , onTouchCancelled(nullptr)
, onTouchesBegan(nullptr)
, onTouchesMoved(nullptr)
, onTouchesEnded(nullptr)
, onTouchesCancelled(nullptr)
, _needSwallow(false) , _needSwallow(false)
, _dispatchMode(Touch::DispatchMode::ALL_AT_ONCE)
{ {
} }
EventListenerTouch::~EventListenerTouch() EventListenerTouchOneByOne::~EventListenerTouchOneByOne()
{ {
CCLOGINFO("In the destructor of TouchEventListener, %p", this); CCLOGINFO("In the destructor of EventListenerTouchOneByOne, %p", this);
} }
bool EventListenerTouch::init(Touch::DispatchMode mode) bool EventListenerTouchOneByOne::init()
{ {
if (EventListener::init(EventTouch::EVENT_TYPE, nullptr)) if (EventListener::init(Type::TOUCH_ONE_BY_ONE, static_cast<ListenerID>(Type::TOUCH_ONE_BY_ONE), nullptr))
{ {
_dispatchMode = mode;
return true; return true;
} }
return false; return false;
} }
void EventListenerTouch::setSwallowTouches(bool needSwallow) void EventListenerTouchOneByOne::setSwallowTouches(bool needSwallow)
{ {
CCASSERT(_dispatchMode == Touch::DispatchMode::ONE_BY_ONE, "Swallow touches only available in OneByOne mode.");
_needSwallow = needSwallow; _needSwallow = needSwallow;
} }
EventListenerTouch* EventListenerTouch::create(Touch::DispatchMode mode) EventListenerTouchOneByOne* EventListenerTouchOneByOne::create()
{ {
auto ret = new EventListenerTouch(); auto ret = new EventListenerTouchOneByOne();
if (ret && ret->init(mode)) if (ret && ret->init())
{ {
ret->autorelease(); ret->autorelease();
} }
@ -80,38 +73,22 @@ EventListenerTouch* EventListenerTouch::create(Touch::DispatchMode mode)
return ret; return ret;
} }
bool EventListenerTouch::checkAvaiable() bool EventListenerTouchOneByOne::checkAvailable()
{ {
if (_dispatchMode == Touch::DispatchMode::ALL_AT_ONCE) if (onTouchBegan == nullptr && onTouchMoved == nullptr
&& onTouchEnded == nullptr && onTouchCancelled == nullptr)
{ {
if (onTouchesBegan == nullptr && onTouchesMoved == nullptr CCASSERT(false, "Invalid TouchEventListener.");
&& onTouchesEnded == nullptr && onTouchesCancelled == nullptr) return false;
{
CCASSERT(false, "Invalid TouchEventListener.");
return false;
}
}
else if (_dispatchMode == Touch::DispatchMode::ONE_BY_ONE)
{
if (onTouchBegan == nullptr && onTouchMoved == nullptr
&& onTouchEnded == nullptr && onTouchCancelled == nullptr)
{
CCASSERT(false, "Invalid TouchEventListener.");
return false;
}
}
else
{
CCASSERT(false, "");
} }
return true; return true;
} }
EventListenerTouch* EventListenerTouch::clone() EventListenerTouchOneByOne* EventListenerTouchOneByOne::clone()
{ {
auto ret = new EventListenerTouch(); auto ret = new EventListenerTouchOneByOne();
if (ret && ret->init(_dispatchMode)) if (ret && ret->init())
{ {
ret->autorelease(); ret->autorelease();
@ -119,13 +96,8 @@ EventListenerTouch* EventListenerTouch::clone()
ret->onTouchMoved = onTouchMoved; ret->onTouchMoved = onTouchMoved;
ret->onTouchEnded = onTouchEnded; ret->onTouchEnded = onTouchEnded;
ret->onTouchCancelled = onTouchCancelled; ret->onTouchCancelled = onTouchCancelled;
ret->onTouchesBegan = onTouchesBegan;
ret->onTouchesMoved = onTouchesMoved;
ret->onTouchesEnded = onTouchesEnded;
ret->onTouchesCancelled = onTouchesCancelled;
ret->_claimedTouches = _claimedTouches; ret->_claimedTouches = _claimedTouches;
ret->_dispatchMode = _dispatchMode;
ret->_needSwallow = _needSwallow; ret->_needSwallow = _needSwallow;
} }
else else
@ -135,4 +107,73 @@ EventListenerTouch* EventListenerTouch::clone()
return ret; return ret;
} }
/////////
EventListenerTouchAllAtOnce::EventListenerTouchAllAtOnce()
: onTouchesBegan(nullptr)
, onTouchesMoved(nullptr)
, onTouchesEnded(nullptr)
, onTouchesCancelled(nullptr)
{
}
EventListenerTouchAllAtOnce::~EventListenerTouchAllAtOnce()
{
CCLOGINFO("In the destructor of EventListenerTouchAllAtOnce, %p", this);
}
bool EventListenerTouchAllAtOnce::init()
{
if (EventListener::init(Type::TOUCH_ALL_AT_ONCE, static_cast<ListenerID>(Type::TOUCH_ALL_AT_ONCE), nullptr))
{
return true;
}
return false;
}
EventListenerTouchAllAtOnce* EventListenerTouchAllAtOnce::create()
{
auto ret = new EventListenerTouchAllAtOnce();
if (ret && ret->init())
{
ret->autorelease();
}
else
{
CC_SAFE_DELETE(ret);
}
return ret;
}
bool EventListenerTouchAllAtOnce::checkAvailable()
{
if (onTouchesBegan == nullptr && onTouchesMoved == nullptr
&& onTouchesEnded == nullptr && onTouchesCancelled == nullptr)
{
CCASSERT(false, "Invalid TouchEventListener.");
return false;
}
return true;
}
EventListenerTouchAllAtOnce* EventListenerTouchAllAtOnce::clone()
{
auto ret = new EventListenerTouchAllAtOnce();
if (ret && ret->init())
{
ret->autorelease();
ret->onTouchesBegan = onTouchesBegan;
ret->onTouchesMoved = onTouchesMoved;
ret->onTouchesEnded = onTouchesEnded;
ret->onTouchesCancelled = onTouchesCancelled;
}
else
{
CC_SAFE_DELETE(ret);
}
return ret;
}
NS_CC_END NS_CC_END

View File

@ -33,20 +33,19 @@
NS_CC_BEGIN NS_CC_BEGIN
class EventListenerTouch : public EventListener class EventListenerTouchOneByOne : public EventListener
{ {
public: public:
static EventListenerTouch* create(Touch::DispatchMode mode); static EventListenerTouchOneByOne* create();
virtual ~EventListenerTouchOneByOne();
void setSwallowTouches(bool needSwallow);
/// Overrides /// Overrides
virtual EventListenerTouch* clone() override; virtual EventListenerTouchOneByOne* clone() override;
virtual bool checkAvaiable() override; virtual bool checkAvailable() override;
//
virtual ~EventListenerTouch();
private:
EventListenerTouch();
bool init(Touch::DispatchMode mode);
public: public:
std::function<bool(Touch*, Event*)> onTouchBegan; std::function<bool(Touch*, Event*)> onTouchBegan;
@ -54,17 +53,39 @@ public:
std::function<void(Touch*, Event*)> onTouchEnded; std::function<void(Touch*, Event*)> onTouchEnded;
std::function<void(Touch*, Event*)> onTouchCancelled; std::function<void(Touch*, Event*)> onTouchCancelled;
private:
EventListenerTouchOneByOne();
bool init();
std::vector<Touch*> _claimedTouches;
bool _needSwallow;
friend class EventDispatcher;
};
class EventListenerTouchAllAtOnce : public EventListener
{
public:
static const ListenerID ID = static_cast<ListenerID>(Type::TOUCH_ALL_AT_ONCE);
static EventListenerTouchAllAtOnce* create();
virtual ~EventListenerTouchAllAtOnce();
/// Overrides
virtual EventListenerTouchAllAtOnce* clone() override;
virtual bool checkAvailable() override;
//
public:
std::function<void(const std::vector<Touch*>&, Event*)> onTouchesBegan; std::function<void(const std::vector<Touch*>&, Event*)> onTouchesBegan;
std::function<void(const std::vector<Touch*>&, Event*)> onTouchesMoved; std::function<void(const std::vector<Touch*>&, Event*)> onTouchesMoved;
std::function<void(const std::vector<Touch*>&, Event*)> onTouchesEnded; std::function<void(const std::vector<Touch*>&, Event*)> onTouchesEnded;
std::function<void(const std::vector<Touch*>&, Event*)> onTouchesCancelled; std::function<void(const std::vector<Touch*>&, Event*)> onTouchesCancelled;
void setSwallowTouches(bool needSwallow);
private: private:
std::vector<Touch*> _claimedTouches; EventListenerTouchAllAtOnce();
bool _needSwallow; bool init();
Touch::DispatchMode _dispatchMode; private:
friend class EventDispatcher; friend class EventDispatcher;
}; };

View File

@ -26,6 +26,10 @@
NS_CC_BEGIN NS_CC_BEGIN
const char* EventTouch::EVENT_TYPE = "TouchEvent"; EventTouch::EventTouch()
: Event(Type::TOUCH)
{
_touches.reserve(MAX_TOUCHES);
}
NS_CC_END NS_CC_END

View File

@ -36,7 +36,6 @@ NS_CC_BEGIN
class EventTouch : public Event class EventTouch : public Event
{ {
public: public:
static const char* EVENT_TYPE;
static const int MAX_TOUCHES = 5; static const int MAX_TOUCHES = 5;
enum class EventCode enum class EventCode
@ -47,11 +46,7 @@ public:
CANCELLED CANCELLED
}; };
EventTouch() EventTouch();
: Event(EVENT_TYPE)
{
_touches.reserve(MAX_TOUCHES);
}
EventCode getEventCode() { return _eventCode; }; EventCode getEventCode() { return _eventCode; };
std::vector<Touch*> getTouches() { return _touches; }; std::vector<Touch*> getTouches() { return _touches; };

View File

@ -48,14 +48,6 @@ NS_CC_BEGIN
// Layer // Layer
Layer::Layer() Layer::Layer()
: _touchEnabled(false)
, _accelerometerEnabled(false)
, _keyboardEnabled(false)
, _touchMode(Touch::DispatchMode::ALL_AT_ONCE)
, _swallowsTouches(true)
, _touchListener(nullptr)
, _keyboardListener(nullptr)
, _accelerationListener(nullptr)
{ {
_ignoreAnchorPointForPosition = true; _ignoreAnchorPointForPosition = true;
setAnchorPoint(Point(0.5f, 0.5f)); setAnchorPoint(Point(0.5f, 0.5f));
@ -74,8 +66,6 @@ bool Layer::init()
Director * pDirector; Director * pDirector;
CC_BREAK_IF(!(pDirector = Director::getInstance())); CC_BREAK_IF(!(pDirector = Director::getInstance()));
this->setContentSize(pDirector->getWinSize()); this->setContentSize(pDirector->getWinSize());
setTouchEnabled(false);
setAccelerometerEnabled(false);
// success // success
bRet = true; bRet = true;
} while(0); } while(0);
@ -97,386 +87,6 @@ Layer *Layer::create()
} }
} }
/// Touch and Accelerometer related
void Layer::addTouchListener()
{
if (_touchListener != nullptr)
return;
auto dispatcher = EventDispatcher::getInstance();
if( _touchMode == Touch::DispatchMode::ALL_AT_ONCE )
{
// Register Touch Event
auto listener = EventListenerTouch::create(Touch::DispatchMode::ALL_AT_ONCE);
listener->onTouchesBegan = CC_CALLBACK_2(Layer::onTouchesBegan, this);
listener->onTouchesMoved = CC_CALLBACK_2(Layer::onTouchesMoved, this);
listener->onTouchesEnded = CC_CALLBACK_2(Layer::onTouchesEnded, this);
listener->onTouchesCancelled = CC_CALLBACK_2(Layer::onTouchesCancelled, this);
dispatcher->addEventListenerWithSceneGraphPriority(listener, this);
_touchListener = listener;
}
else
{
// Register Touch Event
auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE);
listener->setSwallowTouches(_swallowsTouches);
listener->onTouchBegan = CC_CALLBACK_2(Layer::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(Layer::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(Layer::onTouchEnded, this);
listener->onTouchCancelled = CC_CALLBACK_2(Layer::onTouchCancelled, this);
dispatcher->addEventListenerWithSceneGraphPriority(listener, this);
_touchListener = listener;
}
}
int Layer::executeScriptTouchHandler(EventTouch::EventCode eventType, Touch* touch)
{
if (kScriptTypeNone != _scriptType)
{
TouchScriptData data(eventType, this, touch);
ScriptEvent event(kTouchEvent, &data);
return ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
}
//can not reach it
return 0;
}
int Layer::executeScriptTouchesHandler(EventTouch::EventCode eventType, const std::vector<Touch*>& touches)
{
if (kScriptTypeNone != _scriptType)
{
TouchesScriptData data(eventType, this, touches);
ScriptEvent event(kTouchesEvent, &data);
return ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
}
return 0;
}
/// isTouchEnabled getter
bool Layer::isTouchEnabled() const
{
return _touchEnabled;
}
/// isTouchEnabled setter
void Layer::setTouchEnabled(bool enabled)
{
if (_touchEnabled != enabled)
{
_touchEnabled = enabled;
if (_running)
{
if (enabled)
{
this->addTouchListener();
}
else
{
EventDispatcher::getInstance()->removeEventListener(_touchListener);
_touchListener = nullptr;
}
}
}
}
void Layer::setTouchMode(Touch::DispatchMode mode)
{
if(_touchMode != mode)
{
_touchMode = mode;
if( _touchEnabled)
{
setTouchEnabled(false);
setTouchEnabled(true);
}
}
}
void Layer::setSwallowsTouches(bool swallowsTouches)
{
if (_swallowsTouches != swallowsTouches)
{
_swallowsTouches = swallowsTouches;
if( _touchEnabled)
{
setTouchEnabled(false);
setTouchEnabled(true);
}
}
}
Touch::DispatchMode Layer::getTouchMode() const
{
return _touchMode;
}
bool Layer::isSwallowsTouches() const
{
return _swallowsTouches;
}
/// isAccelerometerEnabled getter
bool Layer::isAccelerometerEnabled() const
{
return _accelerometerEnabled;
}
/// isAccelerometerEnabled setter
void Layer::setAccelerometerEnabled(bool enabled)
{
if (enabled != _accelerometerEnabled)
{
_accelerometerEnabled = enabled;
Device::setAccelerometerEnabled(enabled);
if (_running)
{
auto dispatcher = EventDispatcher::getInstance();
dispatcher->removeEventListener(_accelerationListener);
_accelerationListener = nullptr;
if (enabled)
{
_accelerationListener = EventListenerAcceleration::create(CC_CALLBACK_2(Layer::onAcceleration, this));
dispatcher->addEventListenerWithSceneGraphPriority(_accelerationListener, this);
}
}
}
}
void Layer::setAccelerometerInterval(double interval) {
if (_accelerometerEnabled)
{
if (_running)
{
Device::setAccelerometerInterval(interval);
}
}
}
void Layer::onAcceleration(Acceleration* pAccelerationValue, Event* event)
{
CC_UNUSED_PARAM(pAccelerationValue);
if(kScriptTypeNone != _scriptType)
{
BasicScriptData data(this,(void*)pAccelerationValue);
ScriptEvent event(kAccelerometerEvent,&data);
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
}
}
void Layer::onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event)
{
CC_UNUSED_PARAM(keyCode);
CC_UNUSED_PARAM(event);
}
void Layer::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event)
{
CC_UNUSED_PARAM(event);
if(kScriptTypeNone != _scriptType)
{
KeypadScriptData data(keyCode, this);
ScriptEvent event(kKeypadEvent,&data);
ScriptEngineManager::getInstance()->getScriptEngine()->sendEvent(&event);
}
}
/// isKeyboardEnabled getter
bool Layer::isKeyboardEnabled() const
{
return _keyboardEnabled;
}
/// isKeyboardEnabled setter
void Layer::setKeyboardEnabled(bool enabled)
{
if (enabled != _keyboardEnabled)
{
_keyboardEnabled = enabled;
auto dispatcher = EventDispatcher::getInstance();
dispatcher->removeEventListener(_keyboardListener);
_keyboardListener = nullptr;
if (enabled)
{
auto listener = EventListenerKeyboard::create();
listener->onKeyPressed = CC_CALLBACK_2(Layer::onKeyPressed, this);
listener->onKeyReleased = CC_CALLBACK_2(Layer::onKeyReleased, this);
dispatcher->addEventListenerWithSceneGraphPriority(listener, this);
_keyboardListener = listener;
}
}
}
/// Callbacks
void Layer::onEnter()
{
// register 'parent' nodes first
// since events are propagated in reverse order
if (_touchEnabled)
{
this->addTouchListener();
}
// then iterate over all the children
Node::onEnter();
// add this layer to concern the Accelerometer Sensor
if (_accelerometerEnabled)
{
auto dispatcher = EventDispatcher::getInstance();
dispatcher->removeEventListener(_accelerationListener);
_accelerationListener = EventListenerAcceleration::create(CC_CALLBACK_2(Layer::onAcceleration, this));
dispatcher->addEventListenerWithSceneGraphPriority(_accelerationListener, this);
}
}
void Layer::onExit()
{
auto dispatcher = EventDispatcher::getInstance();
dispatcher->removeEventListener(_touchListener);
_touchListener = nullptr;
// remove this layer from the delegates who concern Accelerometer Sensor
dispatcher->removeEventListener(_accelerationListener);
_accelerationListener = nullptr;
// remove this layer from the delegates who concern the keypad msg
dispatcher->removeEventListener(_keyboardListener);
_keyboardListener = nullptr;
Node::onExit();
}
void Layer::onEnterTransitionDidFinish()
{
if (_accelerometerEnabled)
{
auto dispatcher = EventDispatcher::getInstance();
dispatcher->removeEventListener(_accelerationListener);
_accelerationListener = EventListenerAcceleration::create(CC_CALLBACK_2(Layer::onAcceleration, this));
dispatcher->addEventListenerWithSceneGraphPriority(_accelerationListener, this);
}
Node::onEnterTransitionDidFinish();
}
bool Layer::onTouchBegan(Touch *pTouch, Event *pEvent)
{
if (kScriptTypeNone != _scriptType)
{
return executeScriptTouchHandler(EventTouch::EventCode::BEGAN, pTouch) == 0 ? false : true;
}
CC_UNUSED_PARAM(pTouch);
CC_UNUSED_PARAM(pEvent);
CCASSERT(false, "Layer#ccTouchBegan override me");
return true;
}
void Layer::onTouchMoved(Touch *pTouch, Event *pEvent)
{
if (kScriptTypeNone != _scriptType)
{
executeScriptTouchHandler(EventTouch::EventCode::MOVED, pTouch);
return;
}
CC_UNUSED_PARAM(pTouch);
CC_UNUSED_PARAM(pEvent);
}
void Layer::onTouchEnded(Touch *pTouch, Event *pEvent)
{
if (kScriptTypeNone != _scriptType)
{
executeScriptTouchHandler(EventTouch::EventCode::ENDED, pTouch);
return;
}
CC_UNUSED_PARAM(pTouch);
CC_UNUSED_PARAM(pEvent);
}
void Layer::onTouchCancelled(Touch *pTouch, Event *pEvent)
{
if (kScriptTypeNone != _scriptType)
{
executeScriptTouchHandler(EventTouch::EventCode::CANCELLED, pTouch);
return;
}
CC_UNUSED_PARAM(pTouch);
CC_UNUSED_PARAM(pEvent);
}
void Layer::onTouchesBegan(const std::vector<Touch*>& pTouches, Event *pEvent)
{
if (kScriptTypeNone != _scriptType)
{
executeScriptTouchesHandler(EventTouch::EventCode::BEGAN, pTouches);
return;
}
CC_UNUSED_PARAM(pTouches);
CC_UNUSED_PARAM(pEvent);
}
void Layer::onTouchesMoved(const std::vector<Touch*>& pTouches, Event *pEvent)
{
if (kScriptTypeNone != _scriptType)
{
executeScriptTouchesHandler(EventTouch::EventCode::MOVED, pTouches);
return;
}
CC_UNUSED_PARAM(pTouches);
CC_UNUSED_PARAM(pEvent);
}
void Layer::onTouchesEnded(const std::vector<Touch*>& pTouches, Event *pEvent)
{
if (kScriptTypeNone != _scriptType)
{
executeScriptTouchesHandler(EventTouch::EventCode::ENDED, pTouches);
return;
}
CC_UNUSED_PARAM(pTouches);
CC_UNUSED_PARAM(pEvent);
}
void Layer::onTouchesCancelled(const std::vector<Touch*>& pTouches, Event *pEvent)
{
if (kScriptTypeNone != _scriptType)
{
executeScriptTouchesHandler(EventTouch::EventCode::CANCELLED, pTouches);
return;
}
CC_UNUSED_PARAM(pTouches);
CC_UNUSED_PARAM(pEvent);
}
#ifdef CC_USE_PHYSICS #ifdef CC_USE_PHYSICS
void Layer::addChild(Node* child) void Layer::addChild(Node* child)
{ {
@ -1015,7 +625,14 @@ LayerMultiplex::LayerMultiplex()
} }
LayerMultiplex::~LayerMultiplex() LayerMultiplex::~LayerMultiplex()
{ {
CC_SAFE_RELEASE(_layers); if (_layers)
{
for (auto& item : *_layers)
{
static_cast<Layer*>(item)->cleanup();
}
_layers->release();
}
} }
LayerMultiplex * LayerMultiplex::create(Layer * layer, ...) LayerMultiplex * LayerMultiplex::create(Layer * layer, ...)

View File

@ -46,10 +46,6 @@ NS_CC_BEGIN
class TouchScriptHandlerEntry; class TouchScriptHandlerEntry;
class EventListenerTouch;
class EventListenerKeyboard;
class EventListenerAcceleration;
// //
// Layer // Layer
// //
@ -86,23 +82,10 @@ public:
CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesEnded(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesEnded(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);}
CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesCancelled(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);} CC_DEPRECATED_ATTRIBUTE virtual void ccTouchesCancelled(Set *pTouches, Event *pEvent) final {CC_UNUSED_PARAM(pTouches); CC_UNUSED_PARAM(pEvent);}
// default implements are used to call script callback if exist
virtual bool onTouchBegan(Touch *touch, Event *event);
virtual void onTouchMoved(Touch *touch, Event *event);
virtual void onTouchEnded(Touch *touch, Event *event);
virtual void onTouchCancelled(Touch *touch, Event *event);
// // default implements are used to call script callback if exist
virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *event);
virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event *event);
virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event *event);
virtual void onTouchesCancelled(const std::vector<Touch*>&touches, Event *event);
/** @deprecated Please override onAcceleration */ /** @deprecated Please override onAcceleration */
CC_DEPRECATED_ATTRIBUTE virtual void didAccelerate(Acceleration* accelerationValue) final {}; CC_DEPRECATED_ATTRIBUTE virtual void didAccelerate(Acceleration* accelerationValue) final {};
virtual void onAcceleration(Acceleration* acc, Event* event);
/** If isTouchEnabled, this method is called onEnter. Override it to change the /** If isTouchEnabled, this method is called onEnter. Override it to change the
way Layer receives touch events. way Layer receives touch events.
( Default: TouchDispatcher::sharedDispatcher()->addStandardDelegate(this,0); ) ( Default: TouchDispatcher::sharedDispatcher()->addStandardDelegate(this,0); )
@ -115,36 +98,6 @@ public:
*/ */
CC_DEPRECATED_ATTRIBUTE virtual void registerWithTouchDispatcher() final {}; CC_DEPRECATED_ATTRIBUTE virtual void registerWithTouchDispatcher() final {};
/** whether or not it will receive Touch events.
You can enable / disable touch events with this property.
Only the touches of this node will be affected. This "method" is not propagated to it's children.
@since v0.8.1
*/
virtual bool isTouchEnabled() const;
virtual void setTouchEnabled(bool value);
virtual void setTouchMode(Touch::DispatchMode mode);
virtual Touch::DispatchMode getTouchMode() const;
/** swallowsTouches of the touch events. Default is true */
virtual void setSwallowsTouches(bool swallowsTouches);
virtual bool isSwallowsTouches() const;
/** whether or not it will receive Accelerometer events
You can enable / disable accelerometer events with this property.
@since v0.8.1
*/
virtual bool isAccelerometerEnabled() const;
virtual void setAccelerometerEnabled(bool value);
virtual void setAccelerometerInterval(double interval);
/** whether or not it will receive keyboard or keypad events
You can enable / disable accelerometer events with this property.
it's new in cocos2d-x
*/
virtual bool isKeyboardEnabled() const;
virtual void setKeyboardEnabled(bool value);
/** Please use onKeyPressed instead. */ /** Please use onKeyPressed instead. */
virtual void keyPressed(int keyCode) final {}; virtual void keyPressed(int keyCode) final {};
@ -152,11 +105,6 @@ public:
/** Please use onKeyReleased instead. */ /** Please use onKeyReleased instead. */
virtual void keyReleased(int keyCode) final {}; virtual void keyReleased(int keyCode) final {};
virtual void onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event);
virtual void onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event);
CC_DEPRECATED_ATTRIBUTE virtual bool isKeypadEnabled() const final { return isKeyboardEnabled(); };
CC_DEPRECATED_ATTRIBUTE virtual void setKeypadEnabled(bool value) { setKeyboardEnabled(value); };
/** @deprecated Please override onKeyReleased and check the keycode of KeyboardEvent::KeyCode::Menu(KEY_BACKSPACE) instead. */ /** @deprecated Please override onKeyReleased and check the keycode of KeyboardEvent::KeyCode::Menu(KEY_BACKSPACE) instead. */
CC_DEPRECATED_ATTRIBUTE virtual void keyBackClicked() final {}; CC_DEPRECATED_ATTRIBUTE virtual void keyBackClicked() final {};
@ -164,43 +112,12 @@ public:
// //
// Overrides // Overrides
// //
/**
* @js NA
* @lua NA
*/
virtual void onEnter() override;
/**
* @js NA
* @lua NA
*/
virtual void onExit() override;
/**
* @js NA
* @lua NA
*/
virtual void onEnterTransitionDidFinish() override;
#ifdef CC_USE_PHYSICS #ifdef CC_USE_PHYSICS
virtual void addChild(Node* child) override; virtual void addChild(Node* child) override;
virtual void addChild(Node* child, int zOrder) override; virtual void addChild(Node* child, int zOrder) override;
virtual void addChild(Node* child, int zOrder, int tag) override; virtual void addChild(Node* child, int zOrder, int tag) override;
#endif // CC_USE_PHYSICS #endif // CC_USE_PHYSICS
protected:
void addTouchListener();
bool _touchEnabled;
bool _accelerometerEnabled;
bool _keyboardEnabled;
EventListenerTouch* _touchListener;
EventListenerKeyboard* _keyboardListener;
EventListenerAcceleration* _accelerationListener;
private:
Touch::DispatchMode _touchMode;
bool _swallowsTouches;
int executeScriptTouchHandler(EventTouch::EventCode eventType, Touch* touch);
int executeScriptTouchesHandler(EventTouch::EventCode eventType, const std::vector<Touch*>& touches);
}; };
#ifdef __apple__ #ifdef __apple__

View File

@ -127,9 +127,6 @@ bool Menu::initWithArray(Array* pArrayOfItems)
{ {
if (Layer::init()) if (Layer::init())
{ {
setTouchMode(Touch::DispatchMode::ONE_BY_ONE);
setTouchEnabled(true);
_enabled = true; _enabled = true;
// menu in the center of the screen // menu in the center of the screen
Size s = Director::getInstance()->getWinSize(); Size s = Director::getInstance()->getWinSize();
@ -188,8 +185,15 @@ void Menu::onEnter()
{ {
Layer::onEnter(); Layer::onEnter();
setTouchEnabled(true); auto touchListener = EventListenerTouchOneByOne::create();
setTouchMode(Touch::DispatchMode::ONE_BY_ONE); touchListener->setSwallowTouches(true);
touchListener->onTouchBegan = CC_CALLBACK_2(Menu::onTouchBegan, this);
touchListener->onTouchMoved = CC_CALLBACK_2(Menu::onTouchMoved, this);
touchListener->onTouchEnded = CC_CALLBACK_2(Menu::onTouchEnded, this);
touchListener->onTouchCancelled = CC_CALLBACK_2(Menu::onTouchCancelled, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
} }
void Menu::onExit() void Menu::onExit()
@ -253,22 +257,26 @@ bool Menu::onTouchBegan(Touch* touch, Event* event)
void Menu::onTouchEnded(Touch* touch, Event* event) void Menu::onTouchEnded(Touch* touch, Event* event)
{ {
CCASSERT(_state == Menu::State::TRACKING_TOUCH, "[Menu ccTouchEnded] -- invalid state"); CCASSERT(_state == Menu::State::TRACKING_TOUCH, "[Menu ccTouchEnded] -- invalid state");
this->retain();
if (_selectedItem) if (_selectedItem)
{ {
_selectedItem->unselected(); _selectedItem->unselected();
_selectedItem->activate(); _selectedItem->activate();
} }
_state = Menu::State::WAITING; _state = Menu::State::WAITING;
this->release();
} }
void Menu::onTouchCancelled(Touch* touch, Event* event) void Menu::onTouchCancelled(Touch* touch, Event* event)
{ {
CCASSERT(_state == Menu::State::TRACKING_TOUCH, "[Menu ccTouchCancelled] -- invalid state"); CCASSERT(_state == Menu::State::TRACKING_TOUCH, "[Menu ccTouchCancelled] -- invalid state");
this->retain();
if (_selectedItem) if (_selectedItem)
{ {
_selectedItem->unselected(); _selectedItem->unselected();
} }
_state = Menu::State::WAITING; _state = Menu::State::WAITING;
this->release();
} }
void Menu::onTouchMoved(Touch* touch, Event* event) void Menu::onTouchMoved(Touch* touch, Event* event)

View File

@ -112,6 +112,11 @@ public:
virtual bool isEnabled() const { return _enabled; } virtual bool isEnabled() const { return _enabled; }
virtual void setEnabled(bool value) { _enabled = value; }; virtual void setEnabled(bool value) { _enabled = value; };
virtual bool onTouchBegan(Touch* touch, Event* event);
virtual void onTouchEnded(Touch* touch, Event* event);
virtual void onTouchCancelled(Touch* touch, Event* event);
virtual void onTouchMoved(Touch* touch, Event* event);
// overrides // overrides
virtual void removeChild(Node* child, bool cleanup) override; virtual void removeChild(Node* child, bool cleanup) override;
@ -119,11 +124,6 @@ public:
virtual void addChild(Node * child, int zOrder) override; virtual void addChild(Node * child, int zOrder) override;
virtual void addChild(Node * child, int zOrder, int tag) override; virtual void addChild(Node * child, int zOrder, int tag) override;
virtual bool onTouchBegan(Touch* touch, Event* event) override;
virtual void onTouchEnded(Touch* touch, Event* event) override;
virtual void onTouchCancelled(Touch* touch, Event* event) override;
virtual void onTouchMoved(Touch* touch, Event* event) override;
virtual void onEnter() override; virtual void onEnter() override;
virtual void onExit() override; virtual void onExit() override;
virtual void setOpacityModifyRGB(bool bValue) override {CC_UNUSED_PARAM(bValue);} virtual void setOpacityModifyRGB(bool bValue) override {CC_UNUSED_PARAM(bValue);}

View File

@ -410,6 +410,15 @@ MenuItemFont * MenuItemFont::create(const char *value)
return pRet; return pRet;
} }
MenuItemFont::MenuItemFont()
: _fontSize(0), _fontName("")
{}
MenuItemFont::~MenuItemFont()
{
CCLOGINFO("In the destructor of MenuItemFont (%p).", this);
}
// XXX: deprecated // XXX: deprecated
bool MenuItemFont::initWithString(const char *value, Object* target, SEL_MenuHandler selector) bool MenuItemFont::initWithString(const char *value, Object* target, SEL_MenuHandler selector)
{ {
@ -925,7 +934,14 @@ void MenuItemToggle::addSubItem(MenuItem *item)
MenuItemToggle::~MenuItemToggle() MenuItemToggle::~MenuItemToggle()
{ {
CC_SAFE_RELEASE(_subItems); if (_subItems)
{
for (auto& item : *_subItems)
{
static_cast<MenuItem*>(item)->cleanup();
}
_subItems->release();
}
} }
void MenuItemToggle::setSelectedIndex(unsigned int index) void MenuItemToggle::setSelectedIndex(unsigned int index)

View File

@ -241,12 +241,12 @@ public:
/** /**
* @js ctor * @js ctor
*/ */
MenuItemFont() : _fontSize(0), _fontName(""){} MenuItemFont();
/** /**
* @js NA * @js NA
* @lua NA * @lua NA
*/ */
virtual ~MenuItemFont(){} virtual ~MenuItemFont();
/** initializes a menu item from a string with a target/selector */ /** initializes a menu item from a string with a target/selector */
CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, Object* target, SEL_MenuHandler selector); CC_DEPRECATED_ATTRIBUTE bool initWithString(const char *value, Object* target, SEL_MenuHandler selector);

View File

@ -89,7 +89,6 @@ bool nodeComparisonLess(Object* p1, Object* p2)
// XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered. // XXX: Yes, nodes might have a sort problem once every 15 days if the game runs at 60 FPS and each frame sprites are reordered.
static int s_globalOrderOfArrival = 1; static int s_globalOrderOfArrival = 1;
int Node::_globalEventPriorityIndex = 0;
Node::Node(void) Node::Node(void)
: _rotationX(0.0f) : _rotationX(0.0f)
@ -130,8 +129,6 @@ Node::Node(void)
, _isTransitionFinished(false) , _isTransitionFinished(false)
, _updateScriptHandler(0) , _updateScriptHandler(0)
, _componentContainer(NULL) , _componentContainer(NULL)
, _eventPriority(0)
, _oldEventPriority(0)
#ifdef CC_USE_PHYSICS #ifdef CC_USE_PHYSICS
, _physicsBody(nullptr) , _physicsBody(nullptr)
#endif #endif
@ -142,6 +139,8 @@ Node::Node(void)
_actionManager->retain(); _actionManager->retain();
_scheduler = director->getScheduler(); _scheduler = director->getScheduler();
_scheduler->retain(); _scheduler->retain();
_eventDispatcher = director->getEventDispatcher();
_eventDispatcher->retain();
ScriptEngineProtocol* pEngine = ScriptEngineManager::getInstance()->getScriptEngine(); ScriptEngineProtocol* pEngine = ScriptEngineManager::getInstance()->getScriptEngine();
_scriptType = pEngine != NULL ? pEngine->getScriptType() : kScriptTypeNone; _scriptType = pEngine != NULL ? pEngine->getScriptType() : kScriptTypeNone;
@ -158,6 +157,10 @@ Node::~Node()
CC_SAFE_RELEASE(_actionManager); CC_SAFE_RELEASE(_actionManager);
CC_SAFE_RELEASE(_scheduler); CC_SAFE_RELEASE(_scheduler);
_eventDispatcher->cleanTarget(this);
CC_SAFE_RELEASE(_eventDispatcher);
// attributes // attributes
CC_SAFE_RELEASE(_camera); CC_SAFE_RELEASE(_camera);
@ -185,8 +188,6 @@ Node::~Node()
CC_SAFE_DELETE(_componentContainer); CC_SAFE_DELETE(_componentContainer);
removeAllEventListeners();
#ifdef CC_USE_PHYSICS #ifdef CC_USE_PHYSICS
CC_SAFE_RELEASE(_physicsBody); CC_SAFE_RELEASE(_physicsBody);
#endif #endif
@ -240,6 +241,8 @@ void Node::setZOrder(int z)
{ {
_parent->reorderChild(this, z); _parent->reorderChild(this, z);
} }
_eventDispatcher->setDirtyForNode(this);
} }
/// vertexZ getter /// vertexZ getter
@ -859,7 +862,6 @@ void Node::visit()
} }
// self draw // self draw
this->draw(); this->draw();
updateEventPriorityIndex();
for( ; i < _children->count(); i++ ) for( ; i < _children->count(); i++ )
{ {
@ -871,7 +873,6 @@ void Node::visit()
else else
{ {
this->draw(); this->draw();
updateEventPriorityIndex();
} }
// reset for next frame // reset for next frame
@ -934,7 +935,7 @@ void Node::onEnter()
arrayMakeObjectsPerformSelector(_children, onEnter, Node*); arrayMakeObjectsPerformSelector(_children, onEnter, Node*);
this->resumeSchedulerAndActions(); this->resume();
_running = true; _running = true;
@ -976,7 +977,7 @@ void Node::onExitTransitionDidStart()
void Node::onExit() void Node::onExit()
{ {
this->pauseSchedulerAndActions(); this->pause();
_running = false; _running = false;
if (_scriptType != kScriptTypeNone) if (_scriptType != kScriptTypeNone)
@ -988,8 +989,17 @@ void Node::onExit()
} }
arrayMakeObjectsPerformSelector(_children, onExit, Node*); arrayMakeObjectsPerformSelector(_children, onExit, Node*);
}
removeAllEventListeners(); void Node::setEventDispatcher(EventDispatcher* dispatcher)
{
if (dispatcher != _eventDispatcher)
{
_eventDispatcher->cleanTarget(this);
CC_SAFE_RETAIN(dispatcher);
CC_SAFE_RELEASE(_eventDispatcher);
_eventDispatcher = dispatcher;
}
} }
void Node::setActionManager(ActionManager* actionManager) void Node::setActionManager(ActionManager* actionManager)
@ -1117,16 +1127,28 @@ void Node::unscheduleAllSelectors()
_scheduler->unscheduleAllForTarget(this); _scheduler->unscheduleAllForTarget(this);
} }
void Node::resumeSchedulerAndActions() void Node::resume()
{ {
_scheduler->resumeTarget(this); _scheduler->resumeTarget(this);
_actionManager->resumeTarget(this); _actionManager->resumeTarget(this);
_eventDispatcher->resumeTarget(this);
}
void Node::pause()
{
_scheduler->pauseTarget(this);
_actionManager->pauseTarget(this);
_eventDispatcher->pauseTarget(this);
}
void Node::resumeSchedulerAndActions()
{
resume();
} }
void Node::pauseSchedulerAndActions() void Node::pauseSchedulerAndActions()
{ {
_scheduler->pauseTarget(this); pause();
_actionManager->pauseTarget(this);
} }
// override me // override me
@ -1342,43 +1364,6 @@ void Node::removeAllComponents()
_componentContainer->removeAll(); _componentContainer->removeAll();
} }
void Node::resetEventPriorityIndex()
{
_globalEventPriorityIndex = 0;
}
void Node::associateEventListener(EventListener* listener)
{
_eventlisteners.insert(listener);
}
void Node::dissociateEventListener(EventListener* listener)
{
_eventlisteners.erase(listener);
}
void Node::removeAllEventListeners()
{
auto dispatcher = EventDispatcher::getInstance();
auto eventListenersCopy = _eventlisteners;
for (auto& listener : eventListenersCopy)
{
dispatcher->removeEventListener(listener);
}
}
void Node::setDirtyForAllEventListeners()
{
auto dispatcher = EventDispatcher::getInstance();
for (auto& listener : _eventlisteners)
{
dispatcher->setDirtyForEventType(listener->_type, true);
}
}
#ifdef CC_USE_PHYSICS #ifdef CC_USE_PHYSICS
void Node::setPhysicsBody(PhysicsBody* body) void Node::setPhysicsBody(PhysicsBody* body)
{ {

View File

@ -995,6 +995,9 @@ public:
/** @deprecated Use getBoundingBox instead */ /** @deprecated Use getBoundingBox instead */
CC_DEPRECATED_ATTRIBUTE inline virtual Rect boundingBox() const { return getBoundingBox(); } CC_DEPRECATED_ATTRIBUTE inline virtual Rect boundingBox() const { return getBoundingBox(); }
virtual void setEventDispatcher(EventDispatcher* dispatcher);
virtual EventDispatcher* getEventDispatcher() const { return _eventDispatcher; };
/// @{ /// @{
/// @name Actions /// @name Actions
@ -1193,15 +1196,26 @@ public:
void unscheduleAllSelectors(void); void unscheduleAllSelectors(void);
/** /**
* Resumes all scheduled selectors and actions. * Resumes all scheduled selectors, actions and event listeners.
* This method is called internally by onEnter * This method is called internally by onEnter
*/ */
void resumeSchedulerAndActions(void); void resume(void);
/** /**
* Pauses all scheduled selectors and actions. * Pauses all scheduled selectors, actions and event listeners..
* This method is called internally by onExit * This method is called internally by onExit
*/ */
void pauseSchedulerAndActions(void); void pause(void);
/**
* Resumes all scheduled selectors, actions and event listeners.
* This method is called internally by onEnter
*/
CC_DEPRECATED_ATTRIBUTE void resumeSchedulerAndActions(void);
/**
* Pauses all scheduled selectors, actions and event listeners..
* This method is called internally by onExit
*/
CC_DEPRECATED_ATTRIBUTE void pauseSchedulerAndActions(void);
/* /*
* Update method will be called automatically every frame if "scheduleUpdate" is called, and the node is "live" * Update method will be called automatically every frame if "scheduleUpdate" is called, and the node is "live"
@ -1398,37 +1412,8 @@ public:
#endif #endif
private:
friend class Director;
friend class EventDispatcher;
int getEventPriority() const { return _eventPriority; };
void associateEventListener(EventListener* listener);
void dissociateEventListener(EventListener* listener);
static void resetEventPriorityIndex();
std::set<EventListener*> _eventlisteners;
protected: protected:
/// Upates event priority for this node.
inline void updateEventPriorityIndex() {
_oldEventPriority = _eventPriority;
_eventPriority = ++_globalEventPriorityIndex;
if (_oldEventPriority != _eventPriority)
{
setDirtyForAllEventListeners();
}
};
/// Removes all event listeners that associated with this node.
void removeAllEventListeners();
/// Sets dirty for event listener.
void setDirtyForAllEventListeners();
/// lazy allocs /// lazy allocs
void childrenAlloc(void); void childrenAlloc(void);
@ -1490,6 +1475,8 @@ protected:
ActionManager *_actionManager; ///< a pointer to ActionManager singleton, which is used to handle all the actions ActionManager *_actionManager; ///< a pointer to ActionManager singleton, which is used to handle all the actions
EventDispatcher* _eventDispatcher; ///< event dispatcher used to dispatch all kinds of events
bool _running; ///< is running bool _running; ///< is running
bool _visible; ///< is this node visible bool _visible; ///< is this node visible
@ -1506,10 +1493,6 @@ protected:
ComponentContainer *_componentContainer; ///< Dictionary of components ComponentContainer *_componentContainer; ///< Dictionary of components
int _eventPriority; ///< The scene graph based priority of event listener.
int _oldEventPriority; ///< The old scene graph based priority of event listener.
static int _globalEventPriorityIndex; ///< The index of global event priority.
#ifdef CC_USE_PHYSICS #ifdef CC_USE_PHYSICS
PhysicsBody* _physicsBody; ///< the physicsBody the node have PhysicsBody* _physicsBody; ///< the physicsBody the node have
#endif #endif

View File

@ -144,7 +144,6 @@ void ParticleBatchNode::visit()
transform(); transform();
draw(); draw();
updateEventPriorityIndex();
if ( _grid && _grid->isActive()) if ( _grid && _grid->isActive())
{ {

View File

@ -465,7 +465,6 @@ void RenderTexture::visit()
transform(); transform();
_sprite->visit(); _sprite->visit();
draw(); draw();
updateEventPriorityIndex();
if (_grid && _grid->isActive()) if (_grid && _grid->isActive())
{ {

View File

@ -158,7 +158,6 @@ void SpriteBatchNode::visit(void)
transform(); transform();
draw(); draw();
updateEventPriorityIndex();
if (_grid && _grid->isActive()) if (_grid && _grid->isActive())
{ {

View File

@ -160,9 +160,7 @@ void TransitionScene::onEnter()
Scene::onEnter(); Scene::onEnter();
// disable events while transitions // disable events while transitions
// Director::getInstance()->getTouchDispatcher()->setDispatchEvents(false); _eventDispatcher->setEnabled(false);
EventDispatcher::getInstance()->setEnabled(false);
// outScene should not receive the onEnter callback // outScene should not receive the onEnter callback
// only the onExitTransitionDidStart // only the onExitTransitionDidStart
@ -177,9 +175,7 @@ void TransitionScene::onExit()
Scene::onExit(); Scene::onExit();
// enable events while transitions // enable events while transitions
// Director::getInstance()->getTouchDispatcher()->setDispatchEvents(true); _eventDispatcher->setEnabled(true);
EventDispatcher::getInstance()->setEnabled(true);
_outScene->onExit(); _outScene->onExit();
// _inScene should not receive the onEnter callback // _inScene should not receive the onEnter callback

View File

@ -247,7 +247,8 @@ void EGLViewProtocol::handleTouchesBegin(int num, int ids[], float xs[], float y
} }
touchEvent._eventCode = EventTouch::EventCode::BEGAN; touchEvent._eventCode = EventTouch::EventCode::BEGAN;
EventDispatcher::getInstance()->dispatchEvent(&touchEvent); auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&touchEvent);
} }
void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[]) void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[])
@ -294,7 +295,8 @@ void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys
} }
touchEvent._eventCode = EventTouch::EventCode::MOVED; touchEvent._eventCode = EventTouch::EventCode::MOVED;
EventDispatcher::getInstance()->dispatchEvent(&touchEvent); auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&touchEvent);
} }
void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[]) void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode, int num, int ids[], float xs[], float ys[])
@ -347,7 +349,8 @@ void EGLViewProtocol::handleTouchesOfEndOrCancel(EventTouch::EventCode eventCode
} }
touchEvent._eventCode = eventCode; touchEvent._eventCode = eventCode;
EventDispatcher::getInstance()->dispatchEvent(&touchEvent); auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&touchEvent);
for (auto& touch : touchEvent._touches) for (auto& touch : touchEvent._touches)
{ {

View File

@ -422,18 +422,20 @@ static int32_t handle_key_input(AInputEvent *event)
{ {
if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_UP) if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_UP)
{ {
auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
switch (AKeyEvent_getKeyCode(event)) switch (AKeyEvent_getKeyCode(event))
{ {
case AKEYCODE_BACK: case AKEYCODE_BACK:
{ {
cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_BACKSPACE, false); cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_BACKSPACE, false);
cocos2d::EventDispatcher::getInstance()->dispatchEvent(&event); dispatcher->dispatchEvent(&event);
} }
return 1; return 1;
case AKEYCODE_MENU: case AKEYCODE_MENU:
{ {
cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_MENU, false); cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_MENU, false);
cocos2d::EventDispatcher::getInstance()->dispatchEvent(&event); dispatcher->dispatchEvent(&event);
} }
return 1; return 1;
default: default:
@ -629,8 +631,8 @@ void android_main(struct android_app* state) {
acc.z = event.acceleration.z/10; acc.z = event.acceleration.z/10;
acc.timestamp = 0; acc.timestamp = 0;
cocos2d::EventAcceleration accEvent(acc); cocos2d::EventAcceleration accEvent(acc);
auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
cocos2d::EventDispatcher::getInstance()->dispatchEvent(&accEvent); dispatcher->dispatchEvent(&accEvent);
} else { } else {
// ACONFIGURATION_ORIENTATION_LAND // ACONFIGURATION_ORIENTATION_LAND
// swap x and y parameters // swap x and y parameters
@ -640,8 +642,8 @@ void android_main(struct android_app* state) {
acc.z = event.acceleration.z/10; acc.z = event.acceleration.z/10;
acc.timestamp = 0; acc.timestamp = 0;
cocos2d::EventAcceleration accEvent(acc); cocos2d::EventAcceleration accEvent(acc);
auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
cocos2d::EventDispatcher::getInstance()->dispatchEvent(&accEvent); dispatcher->dispatchEvent(&accEvent);
} }
} }
} }

View File

@ -2,7 +2,7 @@
#include "ccTypes.h" #include "ccTypes.h"
#include "CCEventDispatcher.h" #include "CCEventDispatcher.h"
#include "CCEventAcceleration.h" #include "CCEventAcceleration.h"
#include "CCDirector.h"
#import <UIKit/UIKit.h> #import <UIKit/UIKit.h>
// Accelerometer // Accelerometer
@ -100,7 +100,8 @@ static CCAccelerometerDispatcher* s_pAccelerometerDispatcher;
} }
cocos2d::EventAcceleration event(*_acceleration); cocos2d::EventAcceleration event(*_acceleration);
cocos2d::EventDispatcher::getInstance()->dispatchEvent(&event); auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&event);
} }
@end @end

View File

@ -223,7 +223,8 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x,
void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods)
{ {
EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action);
EventDispatcher::getInstance()->dispatchEvent(&event); auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&event);
} }
void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character) void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character)

View File

@ -239,7 +239,8 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x,
void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods)
{ {
EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action);
EventDispatcher::getInstance()->dispatchEvent(&event); auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&event);
} }
void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character) void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character)

View File

@ -341,7 +341,8 @@ void EGLViewEventHandler::OnGLFWMouseMoveCallBack(GLFWwindow* window, double x,
void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) void EGLViewEventHandler::OnGLFWKeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods)
{ {
EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action); EventKeyboard event(g_keyCodeMap[key], GLFW_PRESS == action);
EventDispatcher::getInstance()->dispatchEvent(&event); auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->dispatchEvent(&event);
} }
void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character) void EGLViewEventHandler::OnGLFWCharCallback(GLFWwindow *window, unsigned int character)

View File

@ -14,9 +14,9 @@ namespace cocosbuilder {
void LayerLoader::onHandlePropTypeCheck(Node * pNode, Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader) { void LayerLoader::onHandlePropTypeCheck(Node * pNode, Node * pParent, const char * pPropertyName, bool pCheck, CCBReader * ccbReader) {
if(strcmp(pPropertyName, PROPERTY_TOUCH_ENABLED) == 0) { if(strcmp(pPropertyName, PROPERTY_TOUCH_ENABLED) == 0) {
((Layer *)pNode)->setTouchEnabled(pCheck); // FIXME: ((Layer *)pNode)->setTouchEnabled(pCheck);
} else if(strcmp(pPropertyName, PROPERTY_ACCELEROMETER_ENABLED) == 0) { } else if(strcmp(pPropertyName, PROPERTY_ACCELEROMETER_ENABLED) == 0) {
((Layer *)pNode)->setAccelerometerEnabled(pCheck); // FIXME: ((Layer *)pNode)->setAccelerometerEnabled(pCheck);
} else if(strcmp(pPropertyName, PROPERTY_MOUSE_ENABLED) == 0) { } else if(strcmp(pPropertyName, PROPERTY_MOUSE_ENABLED) == 0) {
// TODO XXX // TODO XXX
CCLOG("The property '%s' is not supported!", PROPERTY_MOUSE_ENABLED); CCLOG("The property '%s' is not supported!", PROPERTY_MOUSE_ENABLED);

View File

@ -624,7 +624,6 @@ void Armature::visit()
transform(); transform();
sortAllChildren(); sortAllChildren();
draw(); draw();
updateEventPriorityIndex();
// reset for next frame // reset for next frame
_orderOfArrival = 0; _orderOfArrival = 0;

View File

@ -81,7 +81,6 @@ void BatchNode::visit()
transform(); transform();
sortAllChildren(); sortAllChildren();
draw(); draw();
updateEventPriorityIndex();
// reset for next frame // reset for next frame
_orderOfArrival = 0; _orderOfArrival = 0;

View File

@ -43,7 +43,7 @@ InputDelegate::InputDelegate(void)
InputDelegate::~InputDelegate(void) InputDelegate::~InputDelegate(void)
{ {
auto dispatcher = EventDispatcher::getInstance(); auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->removeEventListener(_touchListener); dispatcher->removeEventListener(_touchListener);
dispatcher->removeEventListener(_keyboardListener); dispatcher->removeEventListener(_keyboardListener);
dispatcher->removeEventListener(_accelerometerListener); dispatcher->removeEventListener(_accelerometerListener);
@ -107,23 +107,24 @@ void InputDelegate::setTouchEnabled(bool enabled)
{ {
if (_touchEnabled != enabled) if (_touchEnabled != enabled)
{ {
auto dispatcher = Director::getInstance()->getEventDispatcher();
_touchEnabled = enabled; _touchEnabled = enabled;
if (enabled) if (enabled)
{ {
if( _touchMode == Touch::DispatchMode::ALL_AT_ONCE ) { if( _touchMode == Touch::DispatchMode::ALL_AT_ONCE ) {
// Register Touch Event // Register Touch Event
auto listener = EventListenerTouch::create(Touch::DispatchMode::ALL_AT_ONCE); auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(InputDelegate::onTouchesBegan, this); listener->onTouchesBegan = CC_CALLBACK_2(InputDelegate::onTouchesBegan, this);
listener->onTouchesMoved = CC_CALLBACK_2(InputDelegate::onTouchesMoved, this); listener->onTouchesMoved = CC_CALLBACK_2(InputDelegate::onTouchesMoved, this);
listener->onTouchesEnded = CC_CALLBACK_2(InputDelegate::onTouchesEnded, this); listener->onTouchesEnded = CC_CALLBACK_2(InputDelegate::onTouchesEnded, this);
listener->onTouchesCancelled = CC_CALLBACK_2(InputDelegate::onTouchesCancelled, this); listener->onTouchesCancelled = CC_CALLBACK_2(InputDelegate::onTouchesCancelled, this);
EventDispatcher::getInstance()->addEventListenerWithFixedPriority(listener, _touchPriority); dispatcher->addEventListenerWithFixedPriority(listener, _touchPriority);
_touchListener = listener; _touchListener = listener;
} else { } else {
// Register Touch Event // Register Touch Event
auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true); listener->setSwallowTouches(true);
listener->onTouchBegan = CC_CALLBACK_2(InputDelegate::onTouchBegan, this); listener->onTouchBegan = CC_CALLBACK_2(InputDelegate::onTouchBegan, this);
@ -131,13 +132,13 @@ void InputDelegate::setTouchEnabled(bool enabled)
listener->onTouchEnded = CC_CALLBACK_2(InputDelegate::onTouchEnded, this); listener->onTouchEnded = CC_CALLBACK_2(InputDelegate::onTouchEnded, this);
listener->onTouchCancelled = CC_CALLBACK_2(InputDelegate::onTouchCancelled, this); listener->onTouchCancelled = CC_CALLBACK_2(InputDelegate::onTouchCancelled, this);
EventDispatcher::getInstance()->addEventListenerWithFixedPriority(listener, _touchPriority); dispatcher->addEventListenerWithFixedPriority(listener, _touchPriority);
_touchListener = listener; _touchListener = listener;
} }
} }
else else
{ {
EventDispatcher::getInstance()->removeEventListener(_touchListener); dispatcher->removeEventListener(_touchListener);
} }
} }
} }
@ -191,7 +192,7 @@ void InputDelegate::setAccelerometerEnabled(bool enabled)
{ {
_accelerometerEnabled = enabled; _accelerometerEnabled = enabled;
auto dispatcher = EventDispatcher::getInstance(); auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->removeEventListener(_accelerometerListener); dispatcher->removeEventListener(_accelerometerListener);
_accelerometerListener = nullptr; _accelerometerListener = nullptr;
@ -215,7 +216,8 @@ void InputDelegate::setKeypadEnabled(bool enabled)
{ {
_keypadEnabled = enabled; _keypadEnabled = enabled;
EventDispatcher::getInstance()->removeEventListener(_keyboardListener); auto dispatcher = Director::getInstance()->getEventDispatcher();
dispatcher->removeEventListener(_keyboardListener);
if (enabled) if (enabled)
{ {
@ -223,7 +225,7 @@ void InputDelegate::setKeypadEnabled(bool enabled)
listener->onKeyPressed = CC_CALLBACK_2(InputDelegate::onKeyPressed, this); listener->onKeyPressed = CC_CALLBACK_2(InputDelegate::onKeyPressed, this);
listener->onKeyReleased = CC_CALLBACK_2(InputDelegate::onKeyReleased, this); listener->onKeyReleased = CC_CALLBACK_2(InputDelegate::onKeyReleased, this);
EventDispatcher::getInstance()->addEventListenerWithFixedPriority(listener, -1); dispatcher->addEventListenerWithFixedPriority(listener, -1);
_keyboardListener = listener; _keyboardListener = listener;
} }
} }

View File

@ -74,15 +74,21 @@ UILayer* UILayer::create(void)
void UILayer::onEnter() void UILayer::onEnter()
{ {
setTouchMode(Touch::DispatchMode::ONE_BY_ONE);
setTouchEnabled(true);
CCLayer::onEnter(); CCLayer::onEnter();
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
listener->onTouchBegan = CC_CALLBACK_2(UILayer::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(UILayer::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(UILayer::onTouchEnded, this);
listener->onTouchCancelled = CC_CALLBACK_2(UILayer::onTouchCancelled, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
} }
void UILayer::onExit() void UILayer::onExit()
{ {
setTouchEnabled(false);
CCLayer::onExit(); CCLayer::onExit();
} }

@ -1 +1 @@
Subproject commit 2f3c5316657e64ec38b8ed3ea6826eb48c46f32c Subproject commit 4fd4e14912165a2c8a5a6faacda2626035af6f36

View File

@ -1 +1 @@
33fef8c7bc7006ad55c27fd0ed9c9dd2c8064079 1475f1478d176a00cc8d0f9b3302881dee7a8437

View File

@ -199,7 +199,8 @@ private:
typedef std::pair<JSObject*, JSTouchDelegate*> TouchDelegatePair; typedef std::pair<JSObject*, JSTouchDelegate*> TouchDelegatePair;
static TouchDelegateMap sTouchDelegateMap; static TouchDelegateMap sTouchDelegateMap;
bool _needUnroot; bool _needUnroot;
EventListenerTouch* _touchListener; EventListenerTouchOneByOne* _touchListenerOneByOne;
EventListenerTouchAllAtOnce* _touchListenerAllAtOnce;
}; };

View File

@ -93,17 +93,18 @@ Control::~Control()
CC_SAFE_RELEASE(_dispatchTable); CC_SAFE_RELEASE(_dispatchTable);
} }
////Menu - Events
//void Control::registerWithTouchDispatcher()
//{
// Director::getInstance()->getTouchDispatcher()->addTargetedDelegate(this, getTouchPriority(), true);
//}
void Control::onEnter() void Control::onEnter()
{ {
Layer::onEnter(); Layer::onEnter();
this->setTouchMode(Touch::DispatchMode::ONE_BY_ONE); auto dispatcher = Director::getInstance()->getEventDispatcher();
auto touchListener = EventListenerTouchOneByOne::create();
touchListener->onTouchBegan = CC_CALLBACK_2(Control::onTouchBegan, this);
touchListener->onTouchMoved = CC_CALLBACK_2(Control::onTouchMoved, this);
touchListener->onTouchEnded = CC_CALLBACK_2(Control::onTouchEnded, this);
touchListener->onTouchCancelled = CC_CALLBACK_2(Control::onTouchCancelled, this);
dispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
} }
void Control::onExit() void Control::onExit()

View File

@ -96,7 +96,6 @@ bool ControlButton::initWithLabelAndBackgroundSprite(Node* node, Scale9Sprite* b
this->setTitleLabelDispatchTable(Dictionary::create()); this->setTitleLabelDispatchTable(Dictionary::create());
this->setBackgroundSpriteDispatchTable(Dictionary::create()); this->setBackgroundSpriteDispatchTable(Dictionary::create());
setTouchEnabled(true);
_isPushed = false; _isPushed = false;
_zoomOnTouchDown = true; _zoomOnTouchDown = true;

View File

@ -54,7 +54,6 @@ bool ControlColourPicker::init()
{ {
if (Control::init()) if (Control::init())
{ {
setTouchEnabled(true);
// Cache the sprites // Cache the sprites
SpriteFrameCache::getInstance()->addSpriteFramesWithFile("extensions/CCControlColourPickerSpriteSheet.plist"); SpriteFrameCache::getInstance()->addSpriteFramesWithFile("extensions/CCControlColourPickerSpriteSheet.plist");

View File

@ -62,7 +62,6 @@ bool ControlHuePicker::initWithTargetAndPos(Node* target, Point pos)
{ {
if (Control::init()) if (Control::init())
{ {
setTouchEnabled(true);
// Add background and slider sprites // Add background and slider sprites
this->setBackground(ControlUtils::addSpriteToTargetWithPosAndAnchor("huePickerBackground.png", target, pos, Point(0.0f, 0.0f))); this->setBackground(ControlUtils::addSpriteToTargetWithPosAndAnchor("huePickerBackground.png", target, pos, Point(0.0f, 0.0f)));
this->setSlider(ControlUtils::addSpriteToTargetWithPosAndAnchor("colourPicker.png", target, pos, Point(0.5f, 0.5f))); this->setSlider(ControlUtils::addSpriteToTargetWithPosAndAnchor("colourPicker.png", target, pos, Point(0.5f, 0.5f)));

View File

@ -76,8 +76,6 @@ bool ControlPotentiometer::initWithTrackSprite_ProgressTimer_ThumbSprite(Sprite*
{ {
if (Control::init()) if (Control::init())
{ {
setTouchEnabled(true);
setProgressTimer(progressTimer); setProgressTimer(progressTimer);
setThumbSprite(thumbSprite); setThumbSprite(thumbSprite);
thumbSprite->setPosition(progressTimer->getPosition()); thumbSprite->setPosition(progressTimer->getPosition());

View File

@ -60,7 +60,6 @@ bool ControlSaturationBrightnessPicker::initWithTargetAndPos(Node* target, Point
{ {
if (Control::init()) if (Control::init())
{ {
setTouchEnabled(true);
// Add background and slider sprites // Add background and slider sprites
_background=ControlUtils::addSpriteToTargetWithPosAndAnchor("colourPickerBackground.png", target, pos, Point(0.0f, 0.0f)); _background=ControlUtils::addSpriteToTargetWithPosAndAnchor("colourPickerBackground.png", target, pos, Point(0.0f, 0.0f));
_overlay=ControlUtils::addSpriteToTargetWithPosAndAnchor("colourPickerOverlay.png", target, pos, Point(0.0f, 0.0f)); _overlay=ControlUtils::addSpriteToTargetWithPosAndAnchor("colourPickerOverlay.png", target, pos, Point(0.0f, 0.0f));

View File

@ -84,7 +84,6 @@ ControlSlider* ControlSlider::create(Sprite * backgroundSprite, Sprite* pogressS
CCASSERT(thumbSprite, "Thumb sprite must be not nil"); CCASSERT(thumbSprite, "Thumb sprite must be not nil");
ignoreAnchorPointForPosition(false); ignoreAnchorPointForPosition(false);
setTouchEnabled(true);
this->setBackgroundSprite(backgroundSprite); this->setBackgroundSprite(backgroundSprite);
this->setProgressSprite(progressSprite); this->setProgressSprite(progressSprite);

View File

@ -74,8 +74,6 @@ bool ControlStepper::initWithMinusSpriteAndPlusSprite(Sprite *minusSprite, Sprit
CCASSERT(minusSprite, "Minus sprite must be not nil"); CCASSERT(minusSprite, "Minus sprite must be not nil");
CCASSERT(plusSprite, "Plus sprite must be not nil"); CCASSERT(plusSprite, "Plus sprite must be not nil");
setTouchEnabled(true);
// Set the default values // Set the default values
_autorepeat = true; _autorepeat = true;
_continuous = true; _continuous = true;

View File

@ -346,7 +346,6 @@ bool ControlSwitch::initWithMaskSprite(Sprite *maskSprite, Sprite * onSprite, Sp
CCASSERT(offSprite, "offSprite must not be nil."); CCASSERT(offSprite, "offSprite must not be nil.");
CCASSERT(thumbSprite, "thumbSprite must not be nil."); CCASSERT(thumbSprite, "thumbSprite must not be nil.");
setTouchEnabled(true);
_on = true; _on = true;
_switchSprite = new ControlSwitchSprite(); _switchSprite = new ControlSwitchSprite();

View File

@ -56,6 +56,7 @@ ScrollView::ScrollView()
, _touchLength(0.0f) , _touchLength(0.0f)
, _minScale(0.0f) , _minScale(0.0f)
, _maxScale(0.0f) , _maxScale(0.0f)
, _touchListener(nullptr)
{ {
} }
@ -110,7 +111,6 @@ bool ScrollView::initWithViewSize(Size size, Node *container/* = NULL*/)
this->setViewSize(size); this->setViewSize(size);
setTouchEnabled(true); setTouchEnabled(true);
setTouchMode(Touch::DispatchMode::ONE_BY_ONE);
_touches.reserve(EventTouch::MAX_TOUCHES); _touches.reserve(EventTouch::MAX_TOUCHES);
@ -151,7 +151,7 @@ bool ScrollView::isNodeVisible(Node* node)
void ScrollView::pause(Object* sender) void ScrollView::pause(Object* sender)
{ {
_container->pauseSchedulerAndActions(); _container->pause();
Object* pObj = NULL; Object* pObj = NULL;
Array* pChildren = _container->getChildren(); Array* pChildren = _container->getChildren();
@ -159,7 +159,7 @@ void ScrollView::pause(Object* sender)
CCARRAY_FOREACH(pChildren, pObj) CCARRAY_FOREACH(pChildren, pObj)
{ {
Node* pChild = static_cast<Node*>(pObj); Node* pChild = static_cast<Node*>(pObj);
pChild->pauseSchedulerAndActions(); pChild->pause();
} }
} }
@ -171,16 +171,27 @@ void ScrollView::resume(Object* sender)
CCARRAY_FOREACH(pChildren, pObj) CCARRAY_FOREACH(pChildren, pObj)
{ {
Node* pChild = static_cast<Node*>(pObj); Node* pChild = static_cast<Node*>(pObj);
pChild->resumeSchedulerAndActions(); pChild->resume();
} }
_container->resumeSchedulerAndActions(); _container->resume();
} }
void ScrollView::setTouchEnabled(bool e) void ScrollView::setTouchEnabled(bool enabled)
{ {
Layer::setTouchEnabled(e); _eventDispatcher->removeEventListener(_touchListener);
if (!e)
if (enabled)
{
_touchListener = EventListenerTouchOneByOne::create();
_touchListener->onTouchBegan = CC_CALLBACK_2(ScrollView::onTouchBegan, this);
_touchListener->onTouchMoved = CC_CALLBACK_2(ScrollView::onTouchMoved, this);
_touchListener->onTouchEnded = CC_CALLBACK_2(ScrollView::onTouchEnded, this);
_touchListener->onTouchCancelled = CC_CALLBACK_2(ScrollView::onTouchCancelled, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(_touchListener, this);
}
else
{ {
_dragging = false; _dragging = false;
_touchMoved = false; _touchMoved = false;
@ -570,7 +581,6 @@ void ScrollView::visit()
// this draw // this draw
this->draw(); this->draw();
updateEventPriorityIndex();
// draw children zOrder >= 0 // draw children zOrder >= 0
for( ; i < _children->count(); i++ ) for( ; i < _children->count(); i++ )
@ -583,7 +593,6 @@ void ScrollView::visit()
else else
{ {
this->draw(); this->draw();
updateEventPriorityIndex();
} }
this->afterDraw(); this->afterDraw();

View File

@ -166,7 +166,7 @@ public:
*/ */
void resume(Object* sender); void resume(Object* sender);
void setTouchEnabled(bool enabled);
bool isDragging() const {return _dragging;} bool isDragging() const {return _dragging;}
bool isTouchMoved() const { return _touchMoved; } bool isTouchMoved() const { return _touchMoved; }
bool isBounceable() const { return _bounceable; } bool isBounceable() const { return _bounceable; }
@ -216,10 +216,6 @@ public:
virtual void onTouchCancelled(Touch *touch, Event *event); virtual void onTouchCancelled(Touch *touch, Event *event);
// Overrides // Overrides
// virtual bool ccTouchBegan(Touch *pTouch, Event *pEvent) override;
// virtual void ccTouchMoved(Touch *pTouch, Event *pEvent) override;
// virtual void ccTouchEnded(Touch *pTouch, Event *pEvent) override;
// virtual void ccTouchCancelled(Touch *pTouch, Event *pEvent) override;
virtual void setContentSize(const Size & size) override; virtual void setContentSize(const Size & size) override;
virtual const Size& getContentSize() const override; virtual const Size& getContentSize() const override;
/** /**
@ -230,7 +226,6 @@ public:
virtual void addChild(Node * child, int zOrder, int tag) override; virtual void addChild(Node * child, int zOrder, int tag) override;
virtual void addChild(Node * child, int zOrder) override; virtual void addChild(Node * child, int zOrder) override;
virtual void addChild(Node * child) override; virtual void addChild(Node * child) override;
void setTouchEnabled(bool e) override;
protected: protected:
/** /**
@ -352,6 +347,9 @@ protected:
*/ */
Rect _parentScissorRect; Rect _parentScissorRect;
bool _scissorRestored; bool _scissorRestored;
/** Touch listener */
EventListenerTouchOneByOne* _touchListener;
}; };
// end of GUI group // end of GUI group

View File

@ -30,7 +30,7 @@ public:
void updateGame(float dt); void updateGame(float dt);
virtual void onTouchesEnded(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* event) override; void onTouchesEnded(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* event) override;
protected: protected:

View File

@ -32,8 +32,8 @@ void AccelerometerTest::onEnter()
{ {
Layer::onEnter(); Layer::onEnter();
setAccelerometerEnabled(true); auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(AccelerometerTest::onAcceleration, this));
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
auto label = LabelTTF::create(title().c_str(), "Arial", 32); auto label = LabelTTF::create(title().c_str(), "Arial", 32);
addChild(label, 1); addChild(label, 1);

View File

@ -15,7 +15,7 @@ public:
AccelerometerTest(void); AccelerometerTest(void);
~AccelerometerTest(void); ~AccelerometerTest(void);
virtual void onAcceleration(Acceleration* acc, Event* event) override; virtual void onAcceleration(Acceleration* acc, Event* event);
virtual std::string title(); virtual std::string title();
virtual void onEnter(); virtual void onEnter();

View File

@ -1375,7 +1375,9 @@ void ActionStacked::onEnter()
this->centerSprites(0); this->centerSprites(0);
this->setTouchEnabled(true); auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesEnded = CC_CALLBACK_2(ActionStacked::onTouchesEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
auto s = Director::getInstance()->getWinSize(); auto s = Director::getInstance()->getWinSize();
this->addNewSpriteWithCoords(Point(s.width/2, s.height/2)); this->addNewSpriteWithCoords(Point(s.width/2, s.height/2));

View File

@ -305,7 +305,7 @@ public:
virtual std::string subtitle(); virtual std::string subtitle();
virtual void addNewSpriteWithCoords(Point p); virtual void addNewSpriteWithCoords(Point p);
virtual void runActionsInSprite(Sprite* sprite); virtual void runActionsInSprite(Sprite* sprite);
virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event* event); void onTouchesEnded(const std::vector<Touch*>& touches, Event* event);
}; };
class ActionMoveStacked : public ActionStacked class ActionMoveStacked : public ActionStacked

View File

@ -21,7 +21,7 @@ public:
void addNewSpriteAtPosition(Point p); void addNewSpriteAtPosition(Point p);
void update(float dt); void update(float dt);
virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event* event) override; void onTouchesEnded(const std::vector<Touch*>& touches, Event* event);
//CREATE_NODE(Box2DTestLayer); //CREATE_NODE(Box2DTestLayer);
} ; } ;

View File

@ -33,6 +33,7 @@ MenuLayer::MenuLayer(void)
MenuLayer::~MenuLayer(void) MenuLayer::~MenuLayer(void)
{ {
_eventDispatcher->removeEventListener(_touchListener);
} }
MenuLayer* MenuLayer::menuWithEntryID(int entryId) MenuLayer* MenuLayer::menuWithEntryID(int entryId)
@ -52,9 +53,6 @@ bool MenuLayer::initWithEntryID(int entryId)
m_entryID = entryId; m_entryID = entryId;
setTouchEnabled( true );
setTouchMode(Touch::DispatchMode::ONE_BY_ONE);
Box2DView* view = Box2DView::viewWithEntryID( entryId ); Box2DView* view = Box2DView::viewWithEntryID( entryId );
addChild(view, 0, kTagBox2DNode); addChild(view, 0, kTagBox2DNode);
view->setScale(15); view->setScale(15);
@ -81,18 +79,17 @@ bool MenuLayer::initWithEntryID(int entryId)
addChild(menu, 1); addChild(menu, 1);
// Removes touch event listener
EventDispatcher::getInstance()->removeEventListener(_touchListener);
// Adds touch event listener // Adds touch event listener
auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true); listener->setSwallowTouches(true);
listener->onTouchBegan = CC_CALLBACK_2(MenuLayer::onTouchBegan, this); listener->onTouchBegan = CC_CALLBACK_2(MenuLayer::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(MenuLayer::onTouchMoved, this); listener->onTouchMoved = CC_CALLBACK_2(MenuLayer::onTouchMoved, this);
EventDispatcher::getInstance()->addEventListenerWithFixedPriority(listener, 1); _eventDispatcher->addEventListenerWithFixedPriority(listener, 1);
_touchListener = listener; _touchListener = listener;
return true; return true;
} }
@ -179,27 +176,21 @@ Box2DView* Box2DView::viewWithEntryID(int entryId)
bool Box2DView::initWithEntryID(int entryId) bool Box2DView::initWithEntryID(int entryId)
{ {
// setIsAccelerometerEnabled( true );
setTouchEnabled( true );
schedule( schedule_selector(Box2DView::tick) ); schedule( schedule_selector(Box2DView::tick) );
m_entry = g_testEntries + entryId; m_entry = g_testEntries + entryId;
m_test = m_entry->createFcn(); m_test = m_entry->createFcn();
setTouchMode(Touch::DispatchMode::ONE_BY_ONE);
// Removes Touch Event Listener
EventDispatcher::getInstance()->removeEventListener(_touchListener);
// Adds Touch Event Listener // Adds Touch Event Listener
auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true); listener->setSwallowTouches(true);
listener->onTouchBegan = CC_CALLBACK_2(Box2DView::onTouchBegan, this); listener->onTouchBegan = CC_CALLBACK_2(Box2DView::onTouchBegan, this);
listener->onTouchMoved = CC_CALLBACK_2(Box2DView::onTouchMoved, this); listener->onTouchMoved = CC_CALLBACK_2(Box2DView::onTouchMoved, this);
listener->onTouchEnded = CC_CALLBACK_2(Box2DView::onTouchEnded, this); listener->onTouchEnded = CC_CALLBACK_2(Box2DView::onTouchEnded, this);
EventDispatcher::getInstance()->addEventListenerWithFixedPriority(listener, -10); _eventDispatcher->addEventListenerWithFixedPriority(listener, -10);
_touchListener = listener; _touchListener = listener;
return true; return true;
@ -232,6 +223,8 @@ void Box2DView::draw()
Box2DView::~Box2DView() Box2DView::~Box2DView()
{ {
// Removes Touch Event Listener
_eventDispatcher->removeEventListener(_touchListener);
delete m_test; delete m_test;
} }
// //

View File

@ -7,7 +7,7 @@
class MenuLayer : public Layer class MenuLayer : public Layer
{ {
int m_entryID; int m_entryID;
EventListenerTouchOneByOne* _touchListener;
public: public:
MenuLayer(void); MenuLayer(void);
virtual ~MenuLayer(void); virtual ~MenuLayer(void);
@ -19,8 +19,8 @@ public:
void backCallback(Object* sender); void backCallback(Object* sender);
virtual bool onTouchBegan(Touch* touch, Event* event); bool onTouchBegan(Touch* touch, Event* event);
virtual void onTouchMoved(Touch* touch, Event* event); void onTouchMoved(Touch* touch, Event* event);
public: public:
static MenuLayer* menuWithEntryID(int entryId); static MenuLayer* menuWithEntryID(int entryId);
@ -30,6 +30,7 @@ struct TestEntry;
class Test; class Test;
class Box2DView : public Layer class Box2DView : public Layer
{ {
EventListenerTouchOneByOne* _touchListener;
TestEntry* m_entry; TestEntry* m_entry;
Test* m_test; Test* m_test;
int m_entryID; int m_entryID;
@ -43,9 +44,9 @@ public:
void draw(); void draw();
// virtual void registerWithTouchDispatcher(); // virtual void registerWithTouchDispatcher();
virtual bool onTouchBegan(Touch* touch, Event* event); bool onTouchBegan(Touch* touch, Event* event);
virtual void onTouchMoved(Touch* touch, Event* event); void onTouchMoved(Touch* touch, Event* event);
virtual void onTouchEnded(Touch* touch, Event* event); void onTouchEnded(Touch* touch, Event* event);
//virtual void accelerometer(UIAccelerometer* accelerometer, Acceleration* acceleration); //virtual void accelerometer(UIAccelerometer* accelerometer, Acceleration* acceleration);
static Box2DView* viewWithEntryID(int entryId); static Box2DView* viewWithEntryID(int entryId);

View File

@ -28,7 +28,7 @@ void Bug422Layer::reset()
// => CRASH BOOM BANG // => CRASH BOOM BANG
auto node = getChildByTag(localtag-1); auto node = getChildByTag(localtag-1);
log("Menu: %p", node); log("Menu: %p", node);
removeChild(node, false); removeChild(node, true);
// [self removeChildByTag:localtag-1 cleanup:NO]; // [self removeChildByTag:localtag-1 cleanup:NO];
auto item1 = MenuItemFont::create("One", CC_CALLBACK_1(Bug422Layer::menuCallback, this) ); auto item1 = MenuItemFont::create("One", CC_CALLBACK_1(Bug422Layer::menuCallback, this) );

View File

@ -19,7 +19,10 @@ bool Bug624Layer::init()
label->setPosition(Point(size.width/2, size.height/2)); label->setPosition(Point(size.width/2, size.height/2));
addChild(label); addChild(label);
setAccelerometerEnabled(true);
auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer::onAcceleration, this));
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
schedule(schedule_selector(Bug624Layer::switchLayer), 5.0f); schedule(schedule_selector(Bug624Layer::switchLayer), 5.0f);
return true; return true;
@ -56,7 +59,11 @@ bool Bug624Layer2::init()
label->setPosition(Point(size.width/2, size.height/2)); label->setPosition(Point(size.width/2, size.height/2));
addChild(label); addChild(label);
setAccelerometerEnabled(true);
auto listener = EventListenerAcceleration::create(CC_CALLBACK_2(Bug624Layer2::onAcceleration, this));
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
schedule(schedule_selector(Bug624Layer2::switchLayer), 5.0f); schedule(schedule_selector(Bug624Layer2::switchLayer), 5.0f);
return true; return true;

View File

@ -30,7 +30,11 @@ bool Bug914Layer::init()
// Apple recommends to re-assign "self" with the "super" return value // Apple recommends to re-assign "self" with the "super" return value
if (BugsTestBaseLayer::init()) if (BugsTestBaseLayer::init())
{ {
setTouchEnabled(true); auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(Bug914Layer::onTouchesBegan, this);
listener->onTouchesMoved = CC_CALLBACK_2(Bug914Layer::onTouchesMoved, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
// ask director the the window size // ask director the the window size
auto size = Director::getInstance()->getWinSize(); auto size = Director::getInstance()->getWinSize();
LayerColor *layer; LayerColor *layer;

View File

@ -9,8 +9,8 @@ public:
static Scene* scene(); static Scene* scene();
virtual bool init(); virtual bool init();
virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event * event) override; void onTouchesMoved(const std::vector<Touch*>& touches, Event * event);
virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event * event) override; void onTouchesBegan(const std::vector<Touch*>& touches, Event * event);
void restart(Object* sender); void restart(Object* sender);
CREATE_FUNC(Bug914Layer); CREATE_FUNC(Bug914Layer);

View File

@ -67,7 +67,12 @@ void BugsTestMainLayer::onEnter()
_itmeMenu->setPosition(s_tCurPos); _itmeMenu->setPosition(s_tCurPos);
addChild(_itmeMenu); addChild(_itmeMenu);
setTouchEnabled(true);
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(BugsTestMainLayer::onTouchesBegan, this);
listener->onTouchesMoved = CC_CALLBACK_2(BugsTestMainLayer::onTouchesMoved, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
} }
void BugsTestMainLayer::onTouchesBegan(const std::vector<Touch*>& touches, Event *event) void BugsTestMainLayer::onTouchesBegan(const std::vector<Touch*>& touches, Event *event)

View File

@ -8,8 +8,8 @@ class BugsTestMainLayer : public Layer
public: public:
virtual void onEnter(); virtual void onEnter();
virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *event) override; void onTouchesBegan(const std::vector<Touch*>& touches, Event *event);
virtual void onTouchesMoved(const std::vector<Touch*>&touches, Event *event) override; void onTouchesMoved(const std::vector<Touch*>&touches, Event *event);
protected: protected:
Point _beginPos; Point _beginPos;

View File

@ -21,8 +21,13 @@ ChipmunkTestLayer::ChipmunkTestLayer()
{ {
#if CC_ENABLE_CHIPMUNK_INTEGRATION #if CC_ENABLE_CHIPMUNK_INTEGRATION
// enable events // enable events
setTouchEnabled(true);
setAccelerometerEnabled(true); auto touchListener = EventListenerTouchAllAtOnce::create();
touchListener->onTouchesEnded = CC_CALLBACK_2(ChipmunkTestLayer::onTouchesEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(touchListener, this);
auto accListener = EventListenerAcceleration::create(CC_CALLBACK_2(ChipmunkTestLayer::onAcceleration, this));
_eventDispatcher->addEventListenerWithSceneGraphPriority(accListener, this);
// title // title
auto label = LabelTTF::create("Multi touch the screen", "Marker Felt", 36); auto label = LabelTTF::create("Multi touch the screen", "Marker Felt", 36);

View File

@ -24,8 +24,8 @@ public:
void addNewSpriteAtPosition(Point p); void addNewSpriteAtPosition(Point p);
void update(float dt); void update(float dt);
void toggleDebugCallback(Object* sender); void toggleDebugCallback(Object* sender);
virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event* event) override; void onTouchesEnded(const std::vector<Touch*>& touches, Event* event);
virtual void onAcceleration(Acceleration* acc, Event* event) override; virtual void onAcceleration(Acceleration* acc, Event* event);
private: private:
Texture2D* _spriteTexture; // weak ref Texture2D* _spriteTexture; // weak ref

View File

@ -17,8 +17,10 @@ void ClickAndMoveTestScene::runThisTest()
MainLayer::MainLayer() MainLayer::MainLayer()
{ {
setTouchEnabled(true); auto listener = EventListenerTouchOneByOne::create();
setTouchMode(Touch::DispatchMode::ONE_BY_ONE); listener->onTouchBegan = CC_CALLBACK_2(MainLayer::onTouchBegan, this);
listener->onTouchEnded = CC_CALLBACK_2(MainLayer::onTouchEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
auto sprite = Sprite::create(s_pathGrossini); auto sprite = Sprite::create(s_pathGrossini);

View File

@ -13,8 +13,8 @@ class MainLayer : public Layer
{ {
public: public:
MainLayer(); MainLayer();
virtual bool onTouchBegan(Touch* touch, Event *event) override; bool onTouchBegan(Touch* touch, Event *event);
virtual void onTouchEnded(Touch* touch, Event *event) override; void onTouchEnded(Touch* touch, Event *event);
}; };
#endif #endif

View File

@ -449,7 +449,9 @@ void HoleDemo::setup()
this->addChild(_outerClipper); this->addChild(_outerClipper);
this->setTouchEnabled(true); auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(HoleDemo::onTouchesBegan, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
} }
void HoleDemo::pokeHoleAtPoint(Point point) void HoleDemo::pokeHoleAtPoint(Point point)
@ -526,7 +528,11 @@ void ScrollViewDemo::setup()
_scrolling = false; _scrolling = false;
this->setTouchEnabled(true); auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(ScrollViewDemo::onTouchesBegan, this);
listener->onTouchesMoved = CC_CALLBACK_2(ScrollViewDemo::onTouchesMoved, this);
listener->onTouchesEnded = CC_CALLBACK_2(ScrollViewDemo::onTouchesEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
} }
void ScrollViewDemo::onTouchesBegan(const std::vector<Touch*>& touches, Event *event) void ScrollViewDemo::onTouchesBegan(const std::vector<Touch*>& touches, Event *event)

View File

@ -98,7 +98,7 @@ public:
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void pokeHoleAtPoint(Point point); void pokeHoleAtPoint(Point point);
virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *event) override; void onTouchesBegan(const std::vector<Touch*>& touches, Event *event);
private: private:
ClippingNode* _outerClipper; ClippingNode* _outerClipper;
Node* _holes; Node* _holes;
@ -111,9 +111,9 @@ public:
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void setup(); virtual void setup();
virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *event); void onTouchesBegan(const std::vector<Touch*>& touches, Event *event);
virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event *event); void onTouchesMoved(const std::vector<Touch*>& touches, Event *event);
virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event *event); void onTouchesEnded(const std::vector<Touch*>& touches, Event *event);
private: private:
bool _scrolling; bool _scrolling;
Point _lastPoint; Point _lastPoint;

View File

@ -65,14 +65,14 @@ private:
// Director::getInstance()->getTouchDispatcher()->addTargetedDelegate(this, 100, true); // Director::getInstance()->getTouchDispatcher()->addTargetedDelegate(this, 100, true);
// Register Touch Event // Register Touch Event
auto listener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true); listener->setSwallowTouches(true);
listener->onTouchBegan = CC_CALLBACK_2(Button::onTouchBegan, this); listener->onTouchBegan = CC_CALLBACK_2(Button::onTouchBegan, this);
listener->onTouchEnded = CC_CALLBACK_2(Button::onTouchEnded, this); listener->onTouchEnded = CC_CALLBACK_2(Button::onTouchEnded, this);
listener->onTouchCancelled = CC_CALLBACK_2(Button::onTouchCancelled, this); listener->onTouchCancelled = CC_CALLBACK_2(Button::onTouchCancelled, this);
EventDispatcher::getInstance()->addEventListenerWithSceneGraphPriority(listener, this); _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
} }
@ -227,19 +227,6 @@ _sliderMusicVolume(NULL)
addSliders(); addSliders();
schedule(schedule_selector(CocosDenshionTest::updateVolumes)); schedule(schedule_selector(CocosDenshionTest::updateVolumes));
// SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
// std::string testItems[] = {
// "unload effect",
// "pause effect",
// "resume effect",
// "pause all effects",
// "resume all effects",
// "stop all effects"
// };
setTouchEnabled(true);
// preload background music and effect // preload background music and effect
SimpleAudioEngine::getInstance()->preloadBackgroundMusic( MUSIC_FILE ); SimpleAudioEngine::getInstance()->preloadBackgroundMusic( MUSIC_FILE );
SimpleAudioEngine::getInstance()->preloadEffect( EFFECT_FILE ); SimpleAudioEngine::getInstance()->preloadEffect( EFFECT_FILE );

View File

@ -9,7 +9,9 @@ CurlTest::CurlTest()
addChild(label, 0); addChild(label, 0);
label->setPosition( Point(VisibleRect::center().x, VisibleRect::top().y-50) ); label->setPosition( Point(VisibleRect::center().x, VisibleRect::top().y-50) );
setTouchEnabled(true); auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesEnded = CC_CALLBACK_2(CurlTest::onTouchesEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
// create a label to display the tip string // create a label to display the tip string
_label = LabelTTF::create("Touch the screen to connect", "Arial", 22); _label = LabelTTF::create("Touch the screen to connect", "Arial", 22);

View File

@ -10,7 +10,7 @@ public:
CurlTest(); CurlTest();
~CurlTest(); ~CurlTest();
virtual void onTouchesEnded(const std::vector<Touch*>& touches, cocos2d::Event *event) override; void onTouchesEnded(const std::vector<Touch*>& touches, cocos2d::Event *event);
private: private:
cocos2d::LabelTTF* _label; cocos2d::LabelTTF* _label;

View File

@ -477,7 +477,10 @@ void TestAnimationEvent::callback2()
void TestParticleDisplay::onEnter() void TestParticleDisplay::onEnter()
{ {
ArmatureTestLayer::onEnter(); ArmatureTestLayer::onEnter();
setTouchEnabled(true);
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesEnded = CC_CALLBACK_2(TestParticleDisplay::onTouchesEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
animationID = 0; animationID = 0;
@ -534,7 +537,10 @@ void TestParticleDisplay::onTouchesEnded(const std::vector<Touch*>& touches, Eve
void TestUseMutiplePicture::onEnter() void TestUseMutiplePicture::onEnter()
{ {
ArmatureTestLayer::onEnter(); ArmatureTestLayer::onEnter();
setTouchEnabled(true);
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesEnded = CC_CALLBACK_2(TestUseMutiplePicture::onTouchesEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
displayIndex = 0; displayIndex = 0;
@ -935,7 +941,10 @@ std::string TestAnchorPoint::title()
void TestArmatureNesting::onEnter() void TestArmatureNesting::onEnter()
{ {
ArmatureTestLayer::onEnter(); ArmatureTestLayer::onEnter();
setTouchEnabled(true);
auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesEnded = CC_CALLBACK_2(TestArmatureNesting::onTouchesEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
armature = Armature::create("cyborg"); armature = Armature::create("cyborg");
armature->getAnimation()->playByIndex(1); armature->getAnimation()->playByIndex(1);

View File

@ -138,7 +138,7 @@ class TestUseMutiplePicture : public ArmatureTestLayer
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event* event) override; void onTouchesEnded(const std::vector<Touch*>& touches, Event* event);
int displayIndex; int displayIndex;
cocostudio::Armature *armature; cocostudio::Armature *armature;
@ -150,7 +150,7 @@ class TestParticleDisplay : public ArmatureTestLayer
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event* event); void onTouchesEnded(const std::vector<Touch*>& touches, Event* event);
int animationID; int animationID;
cocostudio::Armature *armature; cocostudio::Armature *armature;
@ -251,7 +251,7 @@ public:
virtual void onEnter(); virtual void onEnter();
virtual void onExit(); virtual void onExit();
virtual std::string title(); virtual std::string title();
virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event* event); void onTouchesEnded(const std::vector<Touch*>& touches, Event* event);
cocostudio::Armature *armature; cocostudio::Armature *armature;
int weaponIndex; int weaponIndex;

View File

@ -13,7 +13,7 @@ protected:
virtual ~PlayerController(void); virtual ~PlayerController(void);
public: public:
virtual void onTouchesEnded(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event) override; void onTouchesEnded(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event *event) override;
public: public:
virtual bool init(); virtual bool init();

View File

@ -118,7 +118,11 @@ void ExtensionsMainLayer::onEnter()
_itemMenu->addChild(pItem, kItemTagBasic + i); _itemMenu->addChild(pItem, kItemTagBasic + i);
} }
setTouchEnabled(true); auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(ExtensionsMainLayer::onTouchesBegan, this);
listener->onTouchesMoved = CC_CALLBACK_2(ExtensionsMainLayer::onTouchesMoved, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
addChild(_itemMenu); addChild(_itemMenu);
} }

View File

@ -8,8 +8,8 @@ class ExtensionsMainLayer : public Layer
public: public:
virtual void onEnter(); virtual void onEnter();
virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *event); void onTouchesBegan(const std::vector<Touch*>& touches, Event *event);
virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event *event); void onTouchesMoved(const std::vector<Touch*>& touches, Event *event);
Point _beginPos; Point _beginPos;
Menu* _itemMenu; Menu* _itemMenu;

View File

@ -7,7 +7,11 @@ KeyboardTest::KeyboardTest()
addChild(label, 0); addChild(label, 0);
label->setPosition( Point(s.width/2, s.height-50) ); label->setPosition( Point(s.width/2, s.height-50) );
setKeyboardEnabled(true); auto listener = EventListenerKeyboard::create();
listener->onKeyPressed = CC_CALLBACK_2(KeyboardTest::onKeyPressed, this);
listener->onKeyReleased = CC_CALLBACK_2(KeyboardTest::onKeyReleased, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
// create a label to display the tip string // create a label to display the tip string
_label = LabelTTF::create("Please press any key and see console log...", "Arial", 22); _label = LabelTTF::create("Please press any key and see console log...", "Arial", 22);

View File

@ -7,7 +7,10 @@ KeypadTest::KeypadTest()
addChild(label, 0); addChild(label, 0);
label->setPosition( Point(s.width/2, s.height-50) ); label->setPosition( Point(s.width/2, s.height-50) );
setKeyboardEnabled(true); auto listener = EventListenerKeyboard::create();
listener->onKeyReleased = CC_CALLBACK_2(KeypadTest::onKeyReleased, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
// create a label to display the tip string // create a label to display the tip string
_label = LabelTTF::create("Please press any key...", "Arial", 22); _label = LabelTTF::create("Please press any key...", "Arial", 22);

View File

@ -10,7 +10,7 @@ public:
KeypadTest(); KeypadTest();
~KeypadTest(); ~KeypadTest();
virtual void onKeyReleased(EventKeyboard::KeyCode keycode, Event* event) override; virtual void onKeyReleased(EventKeyboard::KeyCode keycode, Event* event);
private: private:
LabelTTF* _label; LabelTTF* _label;

View File

@ -1135,7 +1135,12 @@ static float alignmentItemPadding = 50;
static float menuItemPaddingCenter = 50; static float menuItemPaddingCenter = 50;
BitmapFontMultiLineAlignment::BitmapFontMultiLineAlignment() BitmapFontMultiLineAlignment::BitmapFontMultiLineAlignment()
{ {
this->setTouchEnabled(true); auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(BitmapFontMultiLineAlignment::onTouchesBegan, this);
listener->onTouchesMoved = CC_CALLBACK_2(BitmapFontMultiLineAlignment::onTouchesMoved, this);
listener->onTouchesEnded = CC_CALLBACK_2(BitmapFontMultiLineAlignment::onTouchesEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
// ask director the the window size // ask director the the window size
auto size = Director::getInstance()->getWinSize(); auto size = Director::getInstance()->getWinSize();

View File

@ -228,9 +228,9 @@ public:
virtual std::string subtitle(); virtual std::string subtitle();
void stringChanged(Object *sender); void stringChanged(Object *sender);
void alignmentChanged(Object *sender); void alignmentChanged(Object *sender);
virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *event); void onTouchesBegan(const std::vector<Touch*>& touches, Event *event);
virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event *event); void onTouchesEnded(const std::vector<Touch*>& touches, Event *event);
virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event *event); void onTouchesMoved(const std::vector<Touch*>& touches, Event *event);
public: public:
LabelBMFont *_labelShouldRetain; LabelBMFont *_labelShouldRetain;

View File

@ -650,8 +650,12 @@ static float menuItemPaddingCenter = 50;
LabelFNTMultiLineAlignment::LabelFNTMultiLineAlignment() LabelFNTMultiLineAlignment::LabelFNTMultiLineAlignment()
{ {
this->setTouchEnabled(true); auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesBegan, this);
listener->onTouchesMoved = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesMoved, this);
listener->onTouchesEnded = CC_CALLBACK_2(LabelFNTMultiLineAlignment::onTouchesEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
// ask director the the window size // ask director the the window size
auto size = Director::getInstance()->getWinSize(); auto size = Director::getInstance()->getWinSize();

View File

@ -156,9 +156,9 @@ public:
virtual std::string subtitle(); virtual std::string subtitle();
void stringChanged(Object *sender); void stringChanged(Object *sender);
void alignmentChanged(Object *sender); void alignmentChanged(Object *sender);
virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *event); void onTouchesBegan(const std::vector<Touch*>& touches, Event *event);
virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event *event); void onTouchesEnded(const std::vector<Touch*>& touches, Event *event);
virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event *event); void onTouchesMoved(const std::vector<Touch*>& touches, Event *event);
public: public:
Label *_labelShouldRetain; Label *_labelShouldRetain;

View File

@ -449,7 +449,12 @@ void LayerTest1::onEnter()
{ {
LayerTest::onEnter(); LayerTest::onEnter();
setTouchEnabled(true); auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesBegan = CC_CALLBACK_2(LayerTest1::onTouchesBegan, this);
listener->onTouchesMoved = CC_CALLBACK_2(LayerTest1::onTouchesMoved, this);
listener->onTouchesEnded = CC_CALLBACK_2(LayerTest1::onTouchesEnded, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
auto s = Director::getInstance()->getWinSize(); auto s = Director::getInstance()->getWinSize();
auto layer = LayerColor::create( Color4B(0xFF, 0x00, 0x00, 0x80), 200, 200); auto layer = LayerColor::create( Color4B(0xFF, 0x00, 0x00, 0x80), 200, 200);
@ -590,7 +595,9 @@ LayerGradientTest::LayerGradientTest()
auto layer1 = LayerGradient::create(Color4B(255,0,0,255), Color4B(0,255,0,255), Point(0.9f, 0.9f)); auto layer1 = LayerGradient::create(Color4B(255,0,0,255), Color4B(0,255,0,255), Point(0.9f, 0.9f));
addChild(layer1, 0, kTagLayer); addChild(layer1, 0, kTagLayer);
setTouchEnabled(true); auto listener = EventListenerTouchAllAtOnce::create();
listener->onTouchesMoved = CC_CALLBACK_2(LayerGradientTest::onTouchesMoved, this);
_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
auto label1 = LabelTTF::create("Compressed Interpolation: Enabled", "Marker Felt", 26); auto label1 = LabelTTF::create("Compressed Interpolation: Enabled", "Marker Felt", 26);
auto label2 = LabelTTF::create("Compressed Interpolation: Disabled", "Marker Felt", 26); auto label2 = LabelTTF::create("Compressed Interpolation: Disabled", "Marker Felt", 26);

View File

@ -74,9 +74,9 @@ public:
void updateSize(Point &touchLocation); void updateSize(Point &touchLocation);
virtual void onTouchesBegan(const std::vector<Touch*>& touches, Event *event); void onTouchesBegan(const std::vector<Touch*>& touches, Event *event);
virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event *event); void onTouchesMoved(const std::vector<Touch*>& touches, Event *event);
virtual void onTouchesEnded(const std::vector<Touch*>& touches, Event *event); void onTouchesEnded(const std::vector<Touch*>& touches, Event *event);
}; };
class LayerTest2 : public LayerTest class LayerTest2 : public LayerTest
@ -99,7 +99,7 @@ class LayerGradientTest : public LayerTest
{ {
public: public:
LayerGradientTest(); LayerGradientTest();
virtual void onTouchesMoved(const std::vector<Touch*>& touches, Event *event); void onTouchesMoved(const std::vector<Touch*>& touches, Event *event);
virtual std::string title(); virtual std::string title();
virtual std::string subtitle(); virtual std::string subtitle();
void toggleItem(cocos2d::Object *sender); void toggleItem(cocos2d::Object *sender);

View File

@ -25,8 +25,14 @@ enum {
//------------------------------------------------------------------ //------------------------------------------------------------------
MenuLayerMainMenu::MenuLayerMainMenu() MenuLayerMainMenu::MenuLayerMainMenu()
{ {
setTouchEnabled(true); _touchListener = EventListenerTouchOneByOne::create();
setTouchMode(Touch::DispatchMode::ONE_BY_ONE); _touchListener->setSwallowTouches(true);
_touchListener->onTouchBegan = CC_CALLBACK_2(MenuLayerMainMenu::onTouchBegan, this);
_touchListener->onTouchMoved = CC_CALLBACK_2(MenuLayerMainMenu::onTouchMoved, this);
_touchListener->onTouchEnded = CC_CALLBACK_2(MenuLayerMainMenu::onTouchEnded, this);
_touchListener->onTouchCancelled = CC_CALLBACK_2(MenuLayerMainMenu::onTouchCancelled, this);
_eventDispatcher->addEventListenerWithFixedPriority(_touchListener, 1);
// Font Item // Font Item
auto spriteNormal = Sprite::create(s_MenuItem, Rect(0,23*2,115,23)); auto spriteNormal = Sprite::create(s_MenuItem, Rect(0,23*2,115,23));
@ -132,6 +138,7 @@ void MenuLayerMainMenu::onTouchMoved(Touch *touch, Event * event)
MenuLayerMainMenu::~MenuLayerMainMenu() MenuLayerMainMenu::~MenuLayerMainMenu()
{ {
_eventDispatcher->removeEventListener(_touchListener);
_disabledItem->release(); _disabledItem->release();
} }
@ -147,8 +154,7 @@ void MenuLayerMainMenu::menuCallbackConfig(Object* sender)
void MenuLayerMainMenu::allowTouches(float dt) void MenuLayerMainMenu::allowTouches(float dt)
{ {
// auto director = Director::getInstance(); _eventDispatcher->setPriority(_touchListener, 1);
// director->getTouchDispatcher()->setPriority(Menu::HANDLER_PRIORITY+1, this);
unscheduleAllSelectors(); unscheduleAllSelectors();
log("TOUCHES ALLOWED AGAIN"); log("TOUCHES ALLOWED AGAIN");
} }
@ -156,8 +162,7 @@ void MenuLayerMainMenu::allowTouches(float dt)
void MenuLayerMainMenu::menuCallbackDisabled(Object* sender) void MenuLayerMainMenu::menuCallbackDisabled(Object* sender)
{ {
// hijack all touch events for 5 seconds // hijack all touch events for 5 seconds
// auto director = Director::getInstance(); _eventDispatcher->setPriority(_touchListener, -1);
// director->getTouchDispatcher()->setPriority(Menu::HANDLER_PRIORITY-1, this);
schedule(schedule_selector(MenuLayerMainMenu::allowTouches), 5.0f); schedule(schedule_selector(MenuLayerMainMenu::allowTouches), 5.0f);
log("TOUCHES DISABLED FOR 5 SECONDS"); log("TOUCHES DISABLED FOR 5 SECONDS");
} }
@ -532,8 +537,8 @@ BugsTest::BugsTest()
void BugsTest::issue1410MenuCallback(Object *sender) void BugsTest::issue1410MenuCallback(Object *sender)
{ {
auto menu = static_cast<Menu*>( static_cast<Node*>(sender)->getParent() ); auto menu = static_cast<Menu*>( static_cast<Node*>(sender)->getParent() );
menu->setTouchEnabled(false); menu->setEnabled(false);
menu->setTouchEnabled(true); menu->setEnabled(true);
log("NO CRASHES"); log("NO CRASHES");
} }
@ -541,8 +546,8 @@ void BugsTest::issue1410MenuCallback(Object *sender)
void BugsTest::issue1410v2MenuCallback(cocos2d::Object *pSender) void BugsTest::issue1410v2MenuCallback(cocos2d::Object *pSender)
{ {
auto menu = static_cast<Menu*>( static_cast<MenuItem*>(pSender)->getParent() ); auto menu = static_cast<Menu*>( static_cast<MenuItem*>(pSender)->getParent() );
menu->setTouchEnabled(true); menu->setEnabled(true);
menu->setTouchEnabled(false); menu->setEnabled(false);
log("NO CRASHES. AND MENU SHOULD STOP WORKING"); log("NO CRASHES. AND MENU SHOULD STOP WORKING");
} }
@ -571,17 +576,14 @@ RemoveMenuItemWhenMove::RemoveMenuItemWhenMove()
menu->setPosition(Point(s.width/2, s.height/2)); menu->setPosition(Point(s.width/2, s.height/2));
setTouchEnabled(true);
setTouchMode(Touch::DispatchMode::ONE_BY_ONE);
// Register Touch Event // Register Touch Event
_touchListener = EventListenerTouch::create(Touch::DispatchMode::ONE_BY_ONE); _touchListener = EventListenerTouchOneByOne::create();
_touchListener->setSwallowTouches(false); _touchListener->setSwallowTouches(false);
_touchListener->onTouchBegan = CC_CALLBACK_2(RemoveMenuItemWhenMove::onTouchBegan, this); _touchListener->onTouchBegan = CC_CALLBACK_2(RemoveMenuItemWhenMove::onTouchBegan, this);
_touchListener->onTouchMoved = CC_CALLBACK_2(RemoveMenuItemWhenMove::onTouchMoved, this); _touchListener->onTouchMoved = CC_CALLBACK_2(RemoveMenuItemWhenMove::onTouchMoved, this);
EventDispatcher::getInstance()->addEventListenerWithFixedPriority(_touchListener, -129); _eventDispatcher->addEventListenerWithFixedPriority(_touchListener, -129);
} }
@ -592,7 +594,7 @@ void RemoveMenuItemWhenMove::goBack(Object *pSender)
RemoveMenuItemWhenMove::~RemoveMenuItemWhenMove() RemoveMenuItemWhenMove::~RemoveMenuItemWhenMove()
{ {
EventDispatcher::getInstance()->removeEventListener(_touchListener); _eventDispatcher->removeEventListener(_touchListener);
CC_SAFE_RELEASE(item); CC_SAFE_RELEASE(item);
} }

View File

@ -8,16 +8,17 @@ class MenuLayerMainMenu : public Layer
{ {
protected: protected:
MenuItem* _disabledItem; MenuItem* _disabledItem;
EventListenerTouchOneByOne* _touchListener;
public: public:
MenuLayerMainMenu(void); MenuLayerMainMenu(void);
~MenuLayerMainMenu(); ~MenuLayerMainMenu();
public: public:
virtual bool onTouchBegan(Touch *touch, Event * event); bool onTouchBegan(Touch *touch, Event * event);
virtual void onTouchEnded(Touch *touch, Event * event); void onTouchEnded(Touch *touch, Event * event);
virtual void onTouchCancelled(Touch *touch, Event * event); void onTouchCancelled(Touch *touch, Event * event);
virtual void onTouchMoved(Touch *touch, Event * event); void onTouchMoved(Touch *touch, Event * event);
void allowTouches(float dt); void allowTouches(float dt);
void menuCallback(Object* sender); void menuCallback(Object* sender);
@ -106,13 +107,14 @@ class RemoveMenuItemWhenMove : public Layer
public: public:
RemoveMenuItemWhenMove(); RemoveMenuItemWhenMove();
~RemoveMenuItemWhenMove(); ~RemoveMenuItemWhenMove();
virtual bool onTouchBegan(Touch *touch, Event *event); bool onTouchBegan(Touch *touch, Event *event);
virtual void onTouchMoved(Touch *touch, Event *event); void onTouchMoved(Touch *touch, Event *event);
void goBack(Object *pSender); void goBack(Object *pSender);
private: private:
MenuItemFont *item; MenuItemFont *item;
EventListenerTouchOneByOne* _touchListener;
}; };

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