diff --git a/native/.clang-tidy b/native/.clang-tidy index 59e5450400..a9c4982234 100644 --- a/native/.clang-tidy +++ b/native/.clang-tidy @@ -40,6 +40,7 @@ Checks: > -readability-implicit-bool-conversion, -readability-implicit-bool-cast, -readability-magic-numbers, + -readability-identifier-length, -bugprone-branch-clone, -misc-static-assert, diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 25fde6bdff..4482002e58 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -384,6 +384,16 @@ cocos_source_files( cocos/plugins/bus/EventBus.cpp ) +cocos_source_files( + cocos/core/event/Event.h + cocos/core/event/EventBus.h + cocos/core/event/EventBus.cpp + cocos/core/event/EventTarget.h + cocos/core/event/intl/EventIntl.h + cocos/core/event/intl/EventTargetMacros.h + cocos/core/event/intl/EventBusMacros.h +) + ##### base cocos_source_files( cocos/base/Agent.h @@ -484,7 +494,6 @@ endif() ############ platform cocos_source_files( - cocos/platform/IEventDispatch.h cocos/platform/BasePlatform.cpp cocos/platform/BasePlatform.h cocos/platform/UniversalPlatform.cpp @@ -1955,61 +1964,14 @@ cocos_source_files( # builtin cocos/core/builtin/BuiltinResMgr.cpp cocos/core/builtin/BuiltinResMgr.h - # cocos/core/builtin/ShaderSourceAssembly.cpp - # cocos/core/builtin/ShaderSourceAssembly.h - # cocos/core/builtin/Effects.cpp # generated - # cocos/core/builtin/Effects.h - # cocos/core/builtin/shader-sources/glsl1.cpp # generated - # cocos/core/builtin/shader-sources/glsl1.h - # cocos/core/builtin/shader-sources/glsl3.cpp # generated - # cocos/core/builtin/shader-sources/glsl3.h - # cocos/core/builtin/shader-sources/glsl4.cpp # generated - # cocos/core/builtin/shader-sources/glsl4.h - # cocos/core/data/Object.cpp cocos/core/data/Object.h cocos/core/data/JSBNativeDataHolder.h - # cocos/core/data/deserializer/EffectAssetDeserializer.cpp - # cocos/core/data/deserializer/EffectAssetDeserializer.h - # cocos/core/data/deserializer/MeshDeserializer.cpp - # cocos/core/data/deserializer/MeshDeserializer.h - # cocos/core/data/deserializer/MaterialDeserializer.cpp - # cocos/core/data/deserializer/MaterialDeserializer.h - # cocos/core/data/deserializer/ImageAssetDeserializer.cpp - # cocos/core/data/deserializer/ImageAssetDeserializer.h - # cocos/core/data/deserializer/TextureBaseDeserializer.h - # cocos/core/data/deserializer/TextureBaseDeserializer.cpp - # cocos/core/data/deserializer/Texture2DDeserializer.cpp - # cocos/core/data/deserializer/Texture2DDeserializer.h - # cocos/core/data/deserializer/TerrainAssetDeserializer.cpp - # cocos/core/data/deserializer/TerrainAssetDeserializer.h - # cocos/core/data/deserializer/IAssetDeserializer.h - # cocos/core/data/deserializer/AssetDeserializerFactory.cpp - # cocos/core/data/deserializer/AssetDeserializerFactory.h - - cocos/core/event/CallbacksInvoker.cpp - cocos/core/event/CallbacksInvoker.h - cocos/core/event/EventTypesToJS.h - cocos/core/event/EventTypesToJS.cpp - # cocos/core/event/Event.cpp - # cocos/core/event/Event.h - # cocos/core/scene-graph/Find.cpp - # cocos/core/scene-graph/Find.h cocos/core/scene-graph/Layers.h cocos/core/scene-graph/Node.cpp cocos/core/scene-graph/Node.h - # cocos/core/scene-graph/ComponentScheduler.h - # cocos/core/scene-graph/ComponentScheduler.cpp - # cocos/core/scene-graph/NodeActivator.cpp - # cocos/core/scene-graph/NodeActivator.h cocos/core/scene-graph/NodeEnum.h - cocos/core/scene-graph/NodeEvent.cpp - cocos/core/scene-graph/NodeEvent.h - cocos/core/scene-graph/NodeEventProcessor.cpp - cocos/core/scene-graph/NodeEventProcessor.h - # cocos/core/scene-graph/NodeUIProperties.cpp - # cocos/core/scene-graph/NodeUIProperties.h cocos/core/scene-graph/Scene.cpp cocos/core/scene-graph/Scene.h cocos/core/scene-graph/SceneGlobals.cpp @@ -2635,7 +2597,6 @@ cocos_source_files( ) cocos_source_files( - cocos/bindings/event/CustomEventTypes.h cocos/bindings/event/EventDispatcher.cpp cocos/bindings/event/EventDispatcher.h ) diff --git a/native/cocos/3d/models/MorphModel.cpp b/native/cocos/3d/models/MorphModel.cpp index be34145679..429e01670d 100644 --- a/native/cocos/3d/models/MorphModel.cpp +++ b/native/cocos/3d/models/MorphModel.cpp @@ -23,7 +23,6 @@ THE SOFTWARE. ****************************************************************************/ #include "3d/models/MorphModel.h" -#include "core/event/EventTypesToJS.h" namespace cc { diff --git a/native/cocos/application/CocosApplication.cpp b/native/cocos/application/CocosApplication.cpp index e226c7757c..202d5ddf57 100644 --- a/native/cocos/application/CocosApplication.cpp +++ b/native/cocos/application/CocosApplication.cpp @@ -28,7 +28,6 @@ #include "base/Macros.h" #include "ApplicationManager.h" -#include "cocos/bindings/event/CustomEventTypes.h" #include "cocos/bindings/event/EventDispatcher.h" #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_classtype.h" @@ -50,10 +49,7 @@ CocosApplication::~CocosApplication() { void CocosApplication::unregisterAllEngineEvents() { if (_engine != nullptr) { - _engine->offAll(BaseEngine::ON_START); - _engine->offAll(BaseEngine::ON_RESUME); - _engine->offAll(BaseEngine::ON_PAUSE); - _engine->offAll(BaseEngine::ON_CLOSE); + _engine->off(_engineEvents); } } @@ -63,20 +59,25 @@ int CocosApplication::init() { } unregisterAllEngineEvents(); - _engine->on(BaseEngine::ON_START, [this]() { - this->onStart(); - }); - _systemWindow = CC_GET_MAIN_SYSTEM_WINDOW(); - _engine->on(BaseEngine::ON_RESUME, [this]() { - this->onResume(); - }); - _engine->on(BaseEngine::ON_PAUSE, [this]() { - this->onPause(); - }); - _engine->on(BaseEngine::ON_CLOSE, [this]() { - this->onClose(); + _engineEvents = _engine->on([this](BaseEngine * /*emitter*/, BaseEngine::EngineStatus status) { + switch (status) { + case BaseEngine::ON_START: + this->onStart(); + break; + case BaseEngine::ON_RESUME: + this->onResume(); + break; + case BaseEngine::ON_PAUSE: + this->onPause(); + break; + case BaseEngine::ON_CLOSE: + this->onClose(); + break; + default: + CC_ASSERT(false); + } }); se::ScriptEngine *se = se::ScriptEngine::getInstance(); @@ -95,7 +96,8 @@ int CocosApplication::init() { auto logicSize = _systemWindow->getViewSize(); IScreen *screen = _engine->getInterface(); float pixelRatio = screen->getDevicePixelRatio(); - cc::EventDispatcher::dispatchResizeEvent(logicSize.x * pixelRatio, logicSize.y * pixelRatio); + uint32_t windowId = _systemWindow->getWindowId(); + events::Resize::broadcast(logicSize.x * pixelRatio, logicSize.y * pixelRatio, windowId); #endif return 0; } diff --git a/native/cocos/application/CocosApplication.h b/native/cocos/application/CocosApplication.h index fd1305fc32..e69f1c6bc0 100644 --- a/native/cocos/application/CocosApplication.h +++ b/native/cocos/application/CocosApplication.h @@ -131,5 +131,9 @@ private: ISystemWindow *_systemWindow{nullptr}; BaseEngine::Ptr _engine{nullptr}; + + BaseEngine::EngineStatusChange::EventID _engineEvents; + + }; } // namespace cc diff --git a/native/cocos/audio/AudioEngine.cpp b/native/cocos/audio/AudioEngine.cpp index b259113ca6..5fb03611bb 100644 --- a/native/cocos/audio/AudioEngine.cpp +++ b/native/cocos/audio/AudioEngine.cpp @@ -70,8 +70,9 @@ ccstd::unordered_map AudioEngine::sAudioIDInfoMap; AudioEngineImpl *AudioEngine::sAudioEngineImpl = nullptr; float AudioEngine::sVolumeFactor = 1.0F; -uint32_t AudioEngine::sOnPauseListenerID = 0; -uint32_t AudioEngine::sOnResumeListenerID = 0; +events::EnterBackground::Listener AudioEngine::sOnPauseListenerID; +events::EnterForeground::Listener AudioEngine::sOnResumeListenerID; + ccstd::vector AudioEngine::sBreakAudioID; AudioEngine::AudioEngineThreadPool *AudioEngine::sThreadPool = nullptr; @@ -158,15 +159,8 @@ void AudioEngine::end() { delete sDefaultProfileHelper; sDefaultProfileHelper = nullptr; - if (sOnPauseListenerID != 0) { - EventDispatcher::removeCustomEventListener(EVENT_COME_TO_BACKGROUND, sOnPauseListenerID); - sOnPauseListenerID = 0; - } - - if (sOnResumeListenerID != 0) { - EventDispatcher::removeCustomEventListener(EVENT_COME_TO_FOREGROUND, sOnResumeListenerID); - sOnResumeListenerID = 0; - } + sOnPauseListenerID.reset(); + sOnResumeListenerID.reset(); } bool AudioEngine::lazyInit() { @@ -177,8 +171,8 @@ bool AudioEngine::lazyInit() { sAudioEngineImpl = nullptr; return false; } - sOnPauseListenerID = EventDispatcher::addCustomEventListener(EVENT_COME_TO_BACKGROUND, AudioEngine::onEnterBackground); - sOnResumeListenerID = EventDispatcher::addCustomEventListener(EVENT_COME_TO_FOREGROUND, AudioEngine::onEnterForeground); + sOnPauseListenerID.bind(&onEnterBackground); + sOnResumeListenerID.bind(&onEnterForeground); } #if (CC_PLATFORM != CC_PLATFORM_ANDROID) @@ -333,7 +327,7 @@ void AudioEngine::resumeAll() { } } -void AudioEngine::onEnterBackground(const CustomEvent & /*event*/) { +void AudioEngine::onEnterBackground() { auto itEnd = sAudioIDInfoMap.end(); for (auto it = sAudioIDInfoMap.begin(); it != itEnd; ++it) { if (it->second.state == AudioState::PLAYING) { @@ -350,7 +344,7 @@ void AudioEngine::onEnterBackground(const CustomEvent & /*event*/) { #endif } -void AudioEngine::onEnterForeground(const CustomEvent & /*event*/) { +void AudioEngine::onEnterForeground() { auto itEnd = sBreakAudioID.end(); for (auto it = sBreakAudioID.begin(); it != itEnd; ++it) { auto iter = sAudioIDInfoMap.find(*it); diff --git a/native/cocos/audio/android/AudioEngine-inl.cpp b/native/cocos/audio/android/AudioEngine-inl.cpp index 45201c2362..92b525c61b 100644 --- a/native/cocos/audio/android/AudioEngine-inl.cpp +++ b/native/cocos/audio/android/AudioEngine-inl.cpp @@ -52,8 +52,7 @@ #include "audio/android/ICallerThreadUtils.h" #include "audio/android/UrlAudioPlayer.h" #include "audio/android/cutils/log.h" -#include "bindings/event/CustomEventTypes.h" -#include "bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" using namespace cc; //NOLINT diff --git a/native/cocos/audio/include/AudioEngine.h b/native/cocos/audio/include/AudioEngine.h index 66ddfc1a53..1695526fef 100644 --- a/native/cocos/audio/include/AudioEngine.h +++ b/native/cocos/audio/include/AudioEngine.h @@ -36,8 +36,7 @@ #include "base/std/container/string.h" #include "base/std/container/unordered_map.h" #include "base/std/container/vector.h" -#include "bindings/event/CustomEventTypes.h" -#include "bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" #ifdef ERROR #undef ERROR @@ -392,12 +391,12 @@ protected: private: static float sVolumeFactor; - static uint32_t sOnPauseListenerID; - static uint32_t sOnResumeListenerID; + static events::EnterBackground::Listener sOnPauseListenerID; + static events::EnterForeground::Listener sOnResumeListenerID; static ccstd::vector sBreakAudioID; - static void onEnterBackground(const CustomEvent &); - static void onEnterForeground(const CustomEvent &); + static void onEnterBackground(); + static void onEnterForeground(); friend class AudioEngineImpl; }; diff --git a/native/cocos/bindings/auto/jsb_scene_auto.cpp b/native/cocos/bindings/auto/jsb_scene_auto.cpp index ccd56e8a13..8e8c3861ee 100644 --- a/native/cocos/bindings/auto/jsb_scene_auto.cpp +++ b/native/cocos/bindings/auto/jsb_scene_auto.cpp @@ -2287,33 +2287,6 @@ static bool js_cc_Node_getParent(se::State& s) } SE_BIND_FUNC(js_cc_Node_getParent) -static bool js_cc_Node_getEventProcessor(se::State& s) -{ - // js_function - - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::Node *arg1 = (cc::Node *) NULL ; - cc::NodeEventProcessor *result = 0 ; - - if(argc != 0) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; - } - arg1 = SE_THIS_OBJECT(s); - SE_PRECONDITION2(arg1, false, "%s: Invalid Native Object", __FUNCTION__); - result = (cc::NodeEventProcessor *)((cc::Node const *)arg1)->getEventProcessor(); - // %typemap(out) SWIGTYPE* - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Node_getEventProcessor, Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - - return true; -} -SE_BIND_FUNC(js_cc_Node_getEventProcessor) - static bool js_cc_Node_getChildByUuid(se::State& s) { // js_function @@ -4079,7 +4052,6 @@ bool js_register_cc_Node(se::Object* obj) { cls->defineFunction("setSiblingIndex", _SE(js_cc_Node_setSiblingIndex)); cls->defineFunction("isActive", _SE(js_cc_Node_isActive)); cls->defineFunction("getParent", _SE(js_cc_Node_getParent)); - cls->defineFunction("getEventProcessor", _SE(js_cc_Node_getEventProcessor)); cls->defineFunction("getChildByUuid", _SE(js_cc_Node_getChildByUuid)); cls->defineFunction("getChildByName", _SE(js_cc_Node_getChildByName)); cls->defineFunction("getChildByPath", _SE(js_cc_Node_getChildByPath)); @@ -5830,33 +5802,6 @@ static bool js_cc_Root_getDebugViewConfig(se::State& s) } SE_BIND_FUNC(js_cc_Root_getDebugViewConfig) -static bool js_cc_Root_getEventProcessor(se::State& s) -{ - // js_function - - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::Root *arg1 = (cc::Root *) NULL ; - cc::CallbacksInvoker *result = 0 ; - - if(argc != 0) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 0); - return false; - } - arg1 = SE_THIS_OBJECT(s); - SE_PRECONDITION2(arg1, false, "%s: Invalid Native Object", __FUNCTION__); - result = (cc::CallbacksInvoker *)((cc::Root const *)arg1)->getEventProcessor(); - // %typemap(out) SWIGTYPE* - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Root_getEventProcessor, Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - - return true; -} -SE_BIND_FUNC(js_cc_Root_getEventProcessor) - static bool js_cc_Root_createRenderWindowFromSystemWindow__SWIG_0(se::State& s) { // js_overloaded_function @@ -6397,7 +6342,6 @@ bool js_register_cc_Root(se::Object* obj) { cls->defineFunction("getBatcher2D", _SE(js_cc_Root_getBatcher2D)); cls->defineFunction("setDebugViewConfig", _SE(js_cc_Root_setDebugViewConfig)); cls->defineFunction("getDebugViewConfig", _SE(js_cc_Root_getDebugViewConfig)); - cls->defineFunction("getEventProcessor", _SE(js_cc_Root_getEventProcessor)); cls->defineFunction("createRenderWindowFromSystemWindow", _SE(js_cc_Root_createRenderWindowFromSystemWindow)); diff --git a/native/cocos/bindings/event/EventDispatcher.cpp b/native/cocos/bindings/event/EventDispatcher.cpp index 7760db338e..8c9deca07b 100644 --- a/native/cocos/bindings/event/EventDispatcher.cpp +++ b/native/cocos/bindings/event/EventDispatcher.cpp @@ -25,7 +25,6 @@ #include "EventDispatcher.h" #include #include "cocos/application/ApplicationManager.h" -#include "cocos/bindings/event/CustomEventTypes.h" #include "cocos/bindings/jswrapper/HandleObject.h" #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_global_init.h" @@ -42,6 +41,7 @@ se::Object *jsKeyboardEventObj = nullptr; se::Object *jsControllerEventArray = nullptr; se::Object *jsResizeEventObj = nullptr; bool inited = false; +bool busListenerInited = false; // attach the argument object to the function void accessCacheArgObj(se::Object *func, se::Value *argObj, const char *cacheKey = "__reusedArgumentObject") { @@ -55,7 +55,20 @@ void accessCacheArgObj(se::Object *func, se::Value *argObj, const char *cacheKey } // namespace namespace cc { -ccstd::unordered_map EventDispatcher::listeners; +events::EnterForeground::Listener EventDispatcher::listenerEnterForeground; +events::EnterBackground::Listener EventDispatcher::listenerEnterBackground; +events::WindowChanged::Listener EventDispatcher::listenerWindowChanged; +events::LowMemory::Listener EventDispatcher::listenerLowMemory; +events::Touch::Listener EventDispatcher::listenerTouch; +events::Mouse::Listener EventDispatcher::listenerMouse; +events::Keyboard::Listener EventDispatcher::listenerKeyboard; +events::Controller::Listener EventDispatcher::listenerConroller; +events::Tick::Listener EventDispatcher::listenerTick; +events::Resize::Listener EventDispatcher::listenerResize; +events::Orientation::Listener EventDispatcher::listenerOrientation; +events::RestartVM::Listener EventDispatcher::listenerRestartVM; +events::Close::Listener EventDispatcher::listenerClose; + uint32_t EventDispatcher::hashListenerId = 1; bool EventDispatcher::initialized() { @@ -67,11 +80,25 @@ void EventDispatcher::init() { se::ScriptEngine::getInstance()->addBeforeCleanupHook([]() { EventDispatcher::destroy(); }); + + if (!busListenerInited) { + listenerTouch.bind(&dispatchTouchEvent); + listenerMouse.bind(&dispatchMouseEvent); + listenerKeyboard.bind(&dispatchKeyboardEvent); + listenerConroller.bind(&dispatchControllerEvent); + listenerTick.bind(&dispatchTickEvent); + listenerResize.bind(&dispatchResizeEvent); + listenerOrientation.bind(&dispatchOrientationChangeEvent); + listenerEnterBackground.bind(&dispatchEnterBackgroundEvent); + listenerEnterForeground.bind(&dispatchEnterForegroundEvent); + listenerLowMemory.bind(&dispatchMemoryWarningEvent); + listenerClose.bind(&dispatchCloseEvent); + listenerRestartVM.bind(&dispatchRestartVM); + busListenerInited = true; + } } void EventDispatcher::destroy() { - removeAllEventListeners(); - for (auto *touchObj : jsTouchObjPool) { touchObj->unroot(); touchObj->decRef(); @@ -164,7 +191,6 @@ void EventDispatcher::dispatchTouchEvent(const TouchEvent &touchEvent) { args.emplace_back(se::Value(jsTouchObjArray)); args.emplace_back(se::Value(touchEvent.windowId)); EventDispatcher::doDispatchJsEvent(eventName, args); - EventDispatcher::dispatchCustomEvent(eventName, 0); } void EventDispatcher::dispatchMouseEvent(const MouseEvent &mouseEvent) { @@ -195,19 +221,15 @@ void EventDispatcher::dispatchMouseEvent(const MouseEvent &mouseEvent) { const char *jsFunctionName = nullptr; switch (type) { case MouseEvent::Type::DOWN: - eventName = EVENT_MOUSE_DOWN; jsFunctionName = "onMouseDown"; break; case MouseEvent::Type::MOVE: - eventName = EVENT_MOUSE_MOVE; jsFunctionName = "onMouseMove"; break; case MouseEvent::Type::UP: - eventName = EVENT_MOUSE_UP; jsFunctionName = "onMouseUp"; break; case MouseEvent::Type::WHEEL: - eventName = EVENT_MOUSE_WHEEL; jsFunctionName = "onMouseWheel"; break; default: @@ -218,7 +240,6 @@ void EventDispatcher::dispatchMouseEvent(const MouseEvent &mouseEvent) { se::ValueArray args; args.emplace_back(se::Value(jsMouseEventObj)); EventDispatcher::doDispatchJsEvent(jsFunctionName, args); - EventDispatcher::dispatchCustomEvent(eventName, 0); } void EventDispatcher::dispatchKeyboardEvent(const KeyboardEvent &keyboardEvent) { @@ -325,38 +346,21 @@ void EventDispatcher::dispatchTickEvent(float /*dt*/) { tickVal.toObject()->call(tickArgsValArr, nullptr); } } - -void EventDispatcher::dispatchResizeEvent(int width, int height) { +// NOLINTNEXTLINE +void EventDispatcher::dispatchResizeEvent(int width, int height, uint32_t windowId) { se::AutoHandleScope scope; if (!jsResizeEventObj) { jsResizeEventObj = se::Object::createPlainObject(); jsResizeEventObj->root(); } + jsResizeEventObj->setProperty("windowId", se::Value(windowId)); jsResizeEventObj->setProperty("width", se::Value(width)); jsResizeEventObj->setProperty("height", se::Value(height)); se::ValueArray args; args.emplace_back(se::Value(jsResizeEventObj)); EventDispatcher::doDispatchJsEvent("onResize", args); - EventDispatcher::dispatchCustomEvent(EVENT_RESIZE, 0); -} - -void EventDispatcher::dispatchResizeEvent(const WindowEvent &windowEvent) { - se::AutoHandleScope scope; - if (!jsResizeEventObj) { - jsResizeEventObj = se::Object::createPlainObject(); - jsResizeEventObj->root(); - } - - jsResizeEventObj->setProperty("windowId", se::Value(windowEvent.windowId)); - jsResizeEventObj->setProperty("width", se::Value(windowEvent.width)); - jsResizeEventObj->setProperty("height", se::Value(windowEvent.height)); - - se::ValueArray args; - args.emplace_back(se::Value(jsResizeEventObj)); - EventDispatcher::doDispatchJsEvent("onResize", args); - EventDispatcher::dispatchCustomEvent(EVENT_RESIZE, 0); } void EventDispatcher::dispatchOrientationChangeEvent(int orientation) { @@ -382,65 +386,22 @@ void EventDispatcher::dispatchOrientationChangeEvent(int orientation) { void EventDispatcher::dispatchEnterBackgroundEvent() { EventDispatcher::doDispatchJsEvent("onPause", se::EmptyValueArray); - EventDispatcher::dispatchCustomEvent(EVENT_COME_TO_BACKGROUND, 0); } void EventDispatcher::dispatchEnterForegroundEvent() { EventDispatcher::doDispatchJsEvent("onResume", se::EmptyValueArray); - EventDispatcher::dispatchCustomEvent(EVENT_COME_TO_FOREGROUND, 0); } void EventDispatcher::dispatchMemoryWarningEvent() { EventDispatcher::doDispatchJsEvent("onMemoryWarning", se::EmptyValueArray); - EventDispatcher::dispatchCustomEvent(EVENT_MEMORY_WARNING, 0); } void EventDispatcher::dispatchRestartVM() { EventDispatcher::doDispatchJsEvent("onRestartVM", se::EmptyValueArray); - EventDispatcher::dispatchCustomEvent(EVENT_RESTART_VM, 0); } void EventDispatcher::dispatchCloseEvent() { EventDispatcher::doDispatchJsEvent("onClose", se::EmptyValueArray); - EventDispatcher::dispatchCustomEvent(EVENT_CLOSE, 0); -} - -void EventDispatcher::dispatchDestroyWindowEvent() { -#if CC_PLATFORM == CC_PLATFORM_WINDOWS - EventDispatcher::dispatchCustomEvent(EVENT_DESTROY_WINDOW, 1, ISystemWindow::mainWindowId); -#else - EventDispatcher::dispatchCustomEvent(EVENT_DESTROY_WINDOW, 0); -#endif -} - -void EventDispatcher::dispatchDestroyWindowEvent(cc::ISystemWindow *window) { -#if CC_PLATFORM == CC_PLATFORM_WINDOWS - EventDispatcher::dispatchCustomEvent(EVENT_DESTROY_WINDOW, 1, window->getWindowId()); -#else - CC_UNUSED_PARAM(window); - EventDispatcher::dispatchCustomEvent(EVENT_DESTROY_WINDOW, 0); -#endif -} - -void EventDispatcher::dispatchRecreateWindowEvent() { -#if CC_PLATFORM == CC_PLATFORM_WINDOWS - EventDispatcher::dispatchCustomEvent(EVENT_RECREATE_WINDOW, 1, ISystemWindow::mainWindowId); -#else - EventDispatcher::dispatchCustomEvent(EVENT_RECREATE_WINDOW, 0); -#endif -} - -void EventDispatcher::dispatchRecreateWindowEvent(cc::ISystemWindow *window) { -#if CC_PLATFORM == CC_PLATFORM_WINDOWS - EventDispatcher::dispatchCustomEvent(EVENT_RECREATE_WINDOW, 1, window->getWindowId()); -#else - CC_UNUSED_PARAM(window); - EventDispatcher::dispatchCustomEvent(EVENT_RECREATE_WINDOW, 0); -#endif -} - -void EventDispatcher::dispatchSceneLoadEvent() { - EventDispatcher::dispatchCustomEvent(EVENT_SCENE_LOAD, 0); } void EventDispatcher::doDispatchJsEvent(const char *jsFunctionName, const std::vector &args) { @@ -458,107 +419,4 @@ void EventDispatcher::doDispatchJsEvent(const char *jsFunctionName, const std::v } } -uint32_t EventDispatcher::addCustomEventListener(const ccstd::string &eventName, const CustomEventListener &listener) { - Node *newNode = ccnew Node(); - newNode->listener = listener; - newNode->listenerID = hashListenerId; - newNode->next = nullptr; - - auto iter = listeners.find(eventName); - if (iter == listeners.end()) { - listeners.emplace(eventName, newNode); - } else { - Node *node = iter->second; - CC_ASSERT(node != nullptr); - Node *prev = nullptr; - while (node != nullptr) { - prev = node; - node = node->next; - } - prev->next = newNode; - } - return hashListenerId++; -} - -void EventDispatcher::removeCustomEventListener(const ccstd::string &eventName, uint32_t listenerID) { - if (eventName.empty()) { - return; - } - - if (listenerID == 0) { - return; - } - - auto iter = listeners.find(eventName); - if (iter != listeners.end()) { - Node *prev = nullptr; - Node *node = iter->second; - while (node != nullptr) { - if (node->listenerID == listenerID) { - if (prev != nullptr) { - prev->next = node->next; - } else if (node->next) { - listeners[eventName] = node->next; - } else { - listeners.erase(iter); - } - - delete node; - return; - } - - prev = node; - node = node->next; - } - } -} - -void EventDispatcher::removeAllCustomEventListeners(const ccstd::string &eventName) { - auto iter = listeners.find(eventName); - if (iter != listeners.end()) { - Node *node = iter->second; - while (node != nullptr) { - Node *next = node->next; - delete node; - node = next; - } - listeners.erase(iter); - } -} - -void EventDispatcher::removeAllEventListeners() { - for (auto &&node : listeners) { - delete node.second; - } - listeners.clear(); - // start from 1 cuz 0 represents pause and resume - hashListenerId = 1; -} - -void EventDispatcher::dispatchCustomEvent(const char *eventName, int argNum, ...) { - CC_ASSERT(eventName && (strcmp(eventName, "") != 0)); - CustomEvent event; - event.name = eventName; - va_list vl; - va_start(vl, argNum); - // Step through the list. - for (int i = 0; i < argNum; ++i) { - event.args[i] = va_arg(vl, EventParameterType); - } - va_end(vl); - dispatchCustomEvent(event); -} -void EventDispatcher::dispatchCustomEvent(const CustomEvent &event) { - auto iter = listeners.find(event.name); - if (iter != listeners.end()) { - Node *next = nullptr; - Node *node = iter->second; - while (node != nullptr) { - next = node->next; - node->listener(event); - node = next; - } - } -} - } // end of namespace cc diff --git a/native/cocos/bindings/event/EventDispatcher.h b/native/cocos/bindings/event/EventDispatcher.h index c5cdb15948..f3d8899f1d 100644 --- a/native/cocos/bindings/event/EventDispatcher.h +++ b/native/cocos/bindings/event/EventDispatcher.h @@ -27,341 +27,50 @@ #include #include -#include "base/std/container/string.h" -#include "base/std/container/unordered_map.h" -#include "base/std/container/vector.h" + +#include "engine/EngineEvents.h" namespace se { class Value; } namespace cc { - -class ISystemWindow; - -enum class OSEventType { - KEYBOARD_OSEVENT = 0, - TOUCH_OSEVENT = 1, - MOUSE_OSEVENT = 2, - CUSTOM_OSEVENT = 3, - DEVICE_OSEVENT = 4, - WINDOW_OSEVENT = 5, - APP_OSEVENT = 6, - CONTROLLER_OSEVENT = 7, - UNKNOWN_OSEVENT = 8 -}; - -class OSEvent { -public: - explicit OSEvent(OSEventType type) : _type(type) {} - - template - std::enable_if_t::value, const T &> static castEvent(const cc::OSEvent &ev) { - const T &evDetail = dynamic_cast(ev); - return std::move(evDetail); - } - - virtual OSEventType eventType() const { - return _type; - } - -private: - OSEventType _type = OSEventType::UNKNOWN_OSEVENT; -}; - -#define CONSTRUCT_EVENT(name, type) \ - name() : OSEvent(type) {} - -class WindowEvent : public OSEvent { -public: - CONSTRUCT_EVENT(WindowEvent, OSEventType::WINDOW_OSEVENT) - enum class Type { - QUIT = 0, - SHOW, - RESTORED, - SIZE_CHANGED, - RESIZED, - HIDDEN, - MINIMIZED, - CLOSE, - UNKNOWN, - }; - Type type = Type::UNKNOWN; - int width = 0; - int height = 0; - uint32_t windowId = 0; -}; -// Touch event related - -class TouchInfo { -public: - float x = 0; - float y = 0; - int index = 0; - - TouchInfo(float x, float y, int index) - : x(x), - y(y), - index(index) {} -}; - -class TouchEvent : public OSEvent { -public: - CONSTRUCT_EVENT(TouchEvent, OSEventType::TOUCH_OSEVENT) - enum class Type { - BEGAN, - MOVED, - ENDED, - CANCELLED, - UNKNOWN - }; - - ccstd::vector touches; - Type type = Type::UNKNOWN; - uint32_t windowId = 0; -}; - -enum class StickKeyCode { - UNDEFINE = 0, - A, - B, - X, - Y, - L1, - R1, - MINUS, - PLUS, - L3, - R3, - MENU, - START, - TRIGGER_LEFT, - TRIGGER_RIGHT, -}; - -enum class StickAxisCode { - UNDEFINE = 0, - X, - Y, - LEFT_STICK_X, - LEFT_STICK_Y, - RIGHT_STICK_X, - RIGHT_STICK_Y, - L2, - R2, - LEFT_GRIP, - RIGHT_GRIP, -}; - -struct ControllerInfo { - struct AxisInfo { - StickAxisCode axis{StickAxisCode::UNDEFINE}; - float value{0.F}; - AxisInfo(StickAxisCode axis, float value) : axis(axis), value(value) {} - }; - struct ButtonInfo { - StickKeyCode key{StickKeyCode::UNDEFINE}; - bool isPress{false}; - ButtonInfo(StickKeyCode key, bool isPress) : key(key), isPress(isPress) {} - }; - - int napdId{0}; - std::vector axisInfos; - std::vector buttonInfos; -}; - -struct ControllerEvent : public OSEvent { - CONSTRUCT_EVENT(ControllerEvent, OSEventType::CONTROLLER_OSEVENT) - enum class Type { - GAMEPAD, - HANDLE, - UNKNOWN - }; - Type type = Type::UNKNOWN; - std::vector> controllerInfos; -}; - -class MouseEvent : public OSEvent { -public: - CONSTRUCT_EVENT(MouseEvent, OSEventType::MOUSE_OSEVENT) - enum class Type { - DOWN, - UP, - MOVE, - WHEEL, - UNKNOWN - }; - - float x = 0.0F; - float y = 0.0F; - // The button number that was pressed when the mouse event was fired: Left button=0, middle button=1 (if present), right button=2. - // For mice configured for left handed use in which the button actions are reversed the values are instead read from right to left. - uint16_t button = 0; - Type type = Type::UNKNOWN; - uint32_t windowId = 0; -}; - -enum class KeyCode { - /** - * @en The back key on mobile phone - * @zh 移动端返回键 - */ - MOBILE_BACK = 6, - BACKSPACE = 8, - TAB = 9, - NUM_LOCK = 12, - NUMPAD_ENTER = 20013, - ENTER = 13, - SHIFT_RIGHT = 20016, - SHIFT_LEFT = 16, - CONTROL_LEFT = 17, - CONTROL_RIGHT = 20017, - ALT_RIGHT = 20018, - ALT_LEFT = 18, - PAUSE = 19, - CAPS_LOCK = 20, - ESCAPE = 27, - SPACE = 32, - PAGE_UP = 33, - PAGE_DOWN = 34, - END = 35, - HOME = 36, - ARROW_LEFT = 37, - ARROW_UP = 38, - ARROW_RIGHT = 39, - ARROW_DOWN = 40, - INSERT = 45, - DELETE_KEY = 46, //DELETE has conflict - META_LEFT = 91, - CONTEXT_MENU = 20093, - PRINT_SCREEN = 20094, - META_RIGHT = 93, - NUMPAD_MULTIPLY = 106, - NUMPAD_PLUS = 107, - NUMPAD_MINUS = 109, - NUMPAD_DECIMAL = 110, - NUMPAD_DIVIDE = 111, - SCROLLLOCK = 145, - SEMICOLON = 186, - EQUAL = 187, - COMMA = 188, - MINUS = 189, - PERIOD = 190, - SLASH = 191, - BACKQUOTE = 192, - BRACKET_LEFT = 219, - BACKSLASH = 220, - BRACKET_RIGHT = 221, - QUOTE = 222, - NUMPAD_0 = 10048, - NUMPAD_1 = 10049, - NUMPAD_2 = 10050, - NUMPAD_3 = 10051, - NUMPAD_4 = 10052, - NUMPAD_5 = 10053, - NUMPAD_6 = 10054, - NUMPAD_7 = 10055, - NUMPAD_8 = 10056, - NUMPAD_9 = 10057, - DPAD_UP = 1003, - DPAD_LEFT = 1000, - DPAD_DOWN = 1004, - DPAD_RIGHT = 1001, - DPAD_CENTER = 1005 -}; - -class KeyboardEvent : public OSEvent { -public: - CONSTRUCT_EVENT(KeyboardEvent, OSEventType::KEYBOARD_OSEVENT) - enum class Action { - PRESS, - RELEASE, - REPEAT, - UNKNOWN - }; - - uint32_t windowId = 0; - int key = -1; - Action action = Action::UNKNOWN; - bool altKeyActive = false; - bool ctrlKeyActive = false; - bool metaKeyActive = false; - bool shiftKeyActive = false; - // TODO(mingo): support caps lock? -}; -union EventParameterType { - void *ptrVal; - int32_t longVal; - int intVal; - int16_t shortVal; - char charVal; - bool boolVal; -}; - -class CustomEvent : public OSEvent { -public: - CONSTRUCT_EVENT(CustomEvent, OSEventType::CUSTOM_OSEVENT) - ccstd::string name; - EventParameterType args[10]; - - virtual ~CustomEvent() = default; // NOLINT(modernize-use-nullptr) -}; - -class DeviceEvent : public OSEvent { -public: - CONSTRUCT_EVENT(DeviceEvent, OSEventType::DEVICE_OSEVENT) - enum class Type { - MEMORY, - ORIENTATION, - UNKNOWN - }; - EventParameterType args[3]; - Type type{Type::UNKNOWN}; // NOLINT(modernize-use-nullptr) -}; - class EventDispatcher { public: static void init(); static void destroy(); static bool initialized(); + static void doDispatchJsEvent(const char *jsFunctionName, const std::vector &args); + +private: static void dispatchTouchEvent(const TouchEvent &touchEvent); static void dispatchMouseEvent(const MouseEvent &mouseEvent); static void dispatchKeyboardEvent(const KeyboardEvent &keyboardEvent); static void dispatchControllerEvent(const ControllerEvent &controllerEvent); static void dispatchTickEvent(float dt); - static void dispatchResizeEvent(int width, int height); - static void dispatchResizeEvent(const WindowEvent &windowEvent); + static void dispatchResizeEvent(int width, int height, uint32_t windowId = UINT32_MAX); static void dispatchOrientationChangeEvent(int orientation); static void dispatchEnterBackgroundEvent(); static void dispatchEnterForegroundEvent(); static void dispatchMemoryWarningEvent(); static void dispatchRestartVM(); static void dispatchCloseEvent(); - static void dispatchDestroyWindowEvent(); - static void dispatchDestroyWindowEvent(cc::ISystemWindow *window); - static void dispatchRecreateWindowEvent(); - static void dispatchRecreateWindowEvent(cc::ISystemWindow *window); - static void dispatchSceneLoadEvent(); + static uint32_t hashListenerId; // simple increment hash - using CustomEventListener = std::function; - static uint32_t addCustomEventListener(const ccstd::string &eventName, const CustomEventListener &listener); - static void removeCustomEventListener(const ccstd::string &eventName, uint32_t listenerID); - static void removeAllCustomEventListeners(const ccstd::string &eventName); - static void removeAllEventListeners(); - static void dispatchCustomEvent(const CustomEvent &event); - static void doDispatchJsEvent(const char *jsFunctionName, const std::vector &args); - -private: - static void dispatchCustomEvent(const char *eventName, int argNum, ...); - - struct Node { - CustomEventListener listener; - uint32_t listenerID; - struct Node *next = nullptr; - }; - static ccstd::unordered_map listeners; - static uint32_t hashListenerId; //simple increment hash + static events::EnterForeground::Listener listenerEnterForeground; + static events::EnterBackground::Listener listenerEnterBackground; + static events::WindowChanged::Listener listenerWindowChanged; + static events::LowMemory::Listener listenerLowMemory; + static events::Touch::Listener listenerTouch; + static events::Mouse::Listener listenerMouse; + static events::Keyboard::Listener listenerKeyboard; + static events::Controller::Listener listenerConroller; + static events::Tick::Listener listenerTick; + static events::Resize::Listener listenerResize; + static events::Orientation::Listener listenerOrientation; + static events::RestartVM::Listener listenerRestartVM; + static events::Close::Listener listenerClose; }; } // end of namespace cc diff --git a/native/cocos/bindings/jswrapper/PrivateObject.h b/native/cocos/bindings/jswrapper/PrivateObject.h index 2fb2910b08..9b740be739 100644 --- a/native/cocos/bindings/jswrapper/PrivateObject.h +++ b/native/cocos/bindings/jswrapper/PrivateObject.h @@ -201,7 +201,7 @@ inline void inHeap(void *ptr) { auto anchor = reinterpret_cast(&a); auto p = reinterpret_cast(ptr); // must be in heaps - CC_ASSERT(abs(anchor - p) > r); + CC_ASSERT(std::abs(anchor - p) > r); } #endif diff --git a/native/cocos/bindings/manual/jsb_assets_manual.cpp b/native/cocos/bindings/manual/jsb_assets_manual.cpp index 4994d066f4..8cdfda67bc 100644 --- a/native/cocos/bindings/manual/jsb_assets_manual.cpp +++ b/native/cocos/bindings/manual/jsb_assets_manual.cpp @@ -24,8 +24,9 @@ ****************************************************************************/ #include "bindings/auto/jsb_assets_auto.h" +#include "core/assets/Material.h" +#include "core/assets/SimpleTexture.h" #include "core/data/JSBNativeDataHolder.h" -#include "core/event/EventTypesToJS.h" #include "jsb_scene_manual.h" #ifndef JSB_ALLOC @@ -70,14 +71,15 @@ static bool js_assets_SimpleTexture_registerListeners(se::State &s) // NOLINT(re auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "Invalid Native Object"); auto *thisObj = s.thisObject(); - cobj->on(cc::EventTypesToJS::SIMPLE_TEXTURE_GFX_TEXTURE_UPDATED, [thisObj](cc::gfx::Texture *texture) { + + cobj->on([thisObj](cc::SimpleTexture * /*emitter*/, cc::gfx::Texture *texture) { se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(texture, arg0, nullptr); se::ScriptEngine::getInstance()->callFunction(thisObj, "_onGFXTextureUpdated", 1, &arg0); }); - cobj->on(cc::EventTypesToJS::SIMPLE_TEXTURE_AFTER_ASSIGN_IMAGE, [thisObj](cc::ImageAsset *image) { + cobj->on([thisObj](cc::SimpleTexture * /*emitter*/, cc::ImageAsset *image) { se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(image, arg0, nullptr); @@ -93,7 +95,7 @@ static bool js_assets_TextureBase_registerGFXSamplerUpdatedListener(se::State &s auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "Invalid Native Object"); auto *thisObj = s.thisObject(); - cobj->on(cc::EventTypesToJS::TEXTURE_BASE_GFX_SAMPLER_UPDATED, [thisObj](cc::gfx::Sampler *sampler) { + cobj->on([thisObj](cc::TextureBase * /*emitter*/, cc::gfx::Sampler *sampler) { se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(sampler, arg0, nullptr); @@ -109,7 +111,7 @@ static bool js_assets_Material_registerPassesUpdatedListener(se::State &s) // NO auto *cobj = SE_THIS_OBJECT(s); SE_PRECONDITION2(cobj, false, "Invalid Native Object"); auto *thisObj = s.thisObject(); - cobj->on(cc::EventTypesToJS::MATERIAL_PASSES_UPDATED, [thisObj]() { + cobj->on([thisObj](cc::Material * /*emitter*/ ){ se::AutoHandleScope hs; se::ScriptEngine::getInstance()->callFunction(thisObj, "_onPassesUpdated", 0, nullptr); }); diff --git a/native/cocos/bindings/manual/jsb_scene_manual.cpp b/native/cocos/bindings/manual/jsb_scene_manual.cpp index a554d7ace6..47b69c2f5c 100644 --- a/native/cocos/bindings/manual/jsb_scene_manual.cpp +++ b/native/cocos/bindings/manual/jsb_scene_manual.cpp @@ -27,9 +27,7 @@ #include "bindings/auto/jsb_scene_auto.h" #include "bindings/auto/jsb_gfx_auto.h" #include "core/Root.h" -#include "core/event/EventTypesToJS.h" #include "core/scene-graph/Node.h" -#include "core/scene-graph/NodeEvent.h" #include "scene/Model.h" #ifndef JSB_ALLOC @@ -112,7 +110,7 @@ static bool js_root_registerListeners(se::State &s) // NOLINT(readability-identi SE_PRECONDITION2(cobj, false, "Invalid Native Object"); #define DISPATCH_EVENT_TO_JS_ARGS_0(eventType, jsFuncName) \ - cobj->getEventProcessor()->on(eventType, [](cc::Root *rootObj) { \ + cobj->on([](cc::Root *rootObj) { \ se::AutoHandleScope hs; \ se::Value rootVal; \ bool ok = nativevalue_to_se(rootObj, rootVal); \ @@ -120,19 +118,18 @@ static bool js_root_registerListeners(se::State &s) // NOLINT(readability-identi if (rootVal.isObject()) { \ se::ScriptEngine::getInstance()->callFunction(rootVal.toObject(), #jsFuncName, 0, nullptr); \ } \ - }) + }); - DISPATCH_EVENT_TO_JS_ARGS_0(cc::EventTypesToJS::DIRECTOR_BEFORE_COMMIT, _onDirectorBeforeCommit); - DISPATCH_EVENT_TO_JS_ARGS_0(cc::EventTypesToJS::DIRECTOR_BEFORE_RENDER, _onDirectorBeforeRender); + DISPATCH_EVENT_TO_JS_ARGS_0(cc::Root::BeforeCommit, _onDirectorBeforeCommit); + DISPATCH_EVENT_TO_JS_ARGS_0(cc::Root::BeforeRender, _onDirectorBeforeRender); return true; } SE_BIND_FUNC(js_root_registerListeners) // NOLINT(readability-identifier-naming) static void registerOnTransformChanged(cc::Node *node, se::Object *jsObject) { - node->on( - cc::NodeEventType::TRANSFORM_CHANGED, - [jsObject](cc::TransformBit transformBit) { + node->on( + [jsObject](cc::Node * /* emitter*/, cc::TransformBit transformBit) { se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(transformBit, arg0); @@ -141,9 +138,8 @@ static void registerOnTransformChanged(cc::Node *node, se::Object *jsObject) { } static void registerOnParentChanged(cc::Node *node, se::Object *jsObject) { - node->on( - cc::NodeEventType::PARENT_CHANGED, - [jsObject](cc::Node *oldParent) { + node->on( + [jsObject](cc::Node * /*emitter*/, cc::Node *oldParent) { se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(oldParent, arg0); @@ -152,9 +148,8 @@ static void registerOnParentChanged(cc::Node *node, se::Object *jsObject) { } static void registerOnLayerChanged(cc::Node *node, se::Object *jsObject) { - node->on( - cc::NodeEventType::LAYER_CHANGED, - [jsObject](uint32_t layer) { + node->on( + [jsObject](cc::Node * /*emitter*/, uint32_t layer) { se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(layer, arg0); @@ -163,9 +158,8 @@ static void registerOnLayerChanged(cc::Node *node, se::Object *jsObject) { } static void registerOnChildRemoved(cc::Node *node, se::Object *jsObject) { - node->on( - cc::NodeEventType::CHILD_REMOVED, - [jsObject](cc::Node *child) { + node->on( + [jsObject](cc::Node * /* emitter*/, cc::Node *child) { se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(child, arg0); @@ -174,9 +168,8 @@ static void registerOnChildRemoved(cc::Node *node, se::Object *jsObject) { } static void registerOnChildAdded(cc::Node *node, se::Object *jsObject) { - node->on( - cc::NodeEventType::CHILD_ADDED, - [jsObject](cc::Node *child) { + node->on( + [jsObject](cc::Node * /*emitter*/, cc::Node *child) { se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(child, arg0); @@ -185,51 +178,45 @@ static void registerOnChildAdded(cc::Node *node, se::Object *jsObject) { } static void registerOnSiblingOrderChanged(cc::Node *node, se::Object *jsObject) { - node->on( - cc::NodeEventType::SIBLING_ORDER_CHANGED, - [jsObject]() { - se::AutoHandleScope hs; + node->on( + [jsObject](cc::Node * /*emitter*/) { + se::AutoHandleScope scope; se::ScriptEngine::getInstance()->callFunction(jsObject, "_onSiblingOrderChanged", 0, nullptr); }); } static void registerOnActiveNode(cc::Node *node, se::Object *jsObject) { - cc::CallbackID skip; - node->on( - cc::EventTypesToJS::NODE_ACTIVE_NODE, - [jsObject](bool shouldActiveNow) { + node->on( + [jsObject](cc::Node * /*emitter*/, bool shouldActiveNow) { se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(shouldActiveNow, arg0); se::ScriptEngine::getInstance()->callFunction(jsObject, "_onActiveNode", 1, &arg0); - }, - skip); + }); } static void registerOnBatchCreated(cc::Node *node, se::Object *jsObject) { - cc::CallbackID skip; - node->on( - cc::EventTypesToJS::NODE_ON_BATCH_CREATED, - [jsObject](bool dontChildPrefab) { + node->on( + [jsObject](cc::Node * /*emitter*/, bool dontChildPrefab) { se::AutoHandleScope hs; se::Value arg0; nativevalue_to_se(dontChildPrefab, arg0); se::ScriptEngine::getInstance()->callFunction(jsObject, "_onBatchCreated", 1, &arg0); - }, - skip); + }); } static void registerLocalPositionRotationScaleUpdated(cc::Node *node, se::Object *jsObject) { - node->on(cc::EventTypesToJS::NODE_LOCAL_POSITION_UPDATED, [jsObject](float x, float y, float z) { - se::AutoHandleScope hs; - ccstd::array args; - nativevalue_to_se(x, args[0]); - nativevalue_to_se(y, args[1]); - nativevalue_to_se(z, args[2]); - se::ScriptEngine::getInstance()->callFunction(jsObject, "_onLocalPositionUpdated", static_cast(args.size()), args.data()); - }); + node->on( + [jsObject](cc::Node * /*emitter*/, float x, float y, float z) { + se::AutoHandleScope hs; + ccstd::array args; + nativevalue_to_se(x, args[0]); + nativevalue_to_se(y, args[1]); + nativevalue_to_se(z, args[2]); + se::ScriptEngine::getInstance()->callFunction(jsObject, "_onLocalPositionUpdated", static_cast(args.size()), args.data()); + }); - node->on(cc::EventTypesToJS::NODE_LOCAL_ROTATION_UPDATED, [jsObject](float x, float y, float z, float w) { + node->on([jsObject](cc::Node * /*emiiter*/, float x, float y, float z, float w) { se::AutoHandleScope hs; ccstd::array args; nativevalue_to_se(x, args[0]); @@ -239,7 +226,7 @@ static void registerLocalPositionRotationScaleUpdated(cc::Node *node, se::Object se::ScriptEngine::getInstance()->callFunction(jsObject, "_onLocalRotationUpdated", static_cast(args.size()), args.data()); }); - node->on(cc::EventTypesToJS::NODE_LOCAL_SCALE_UPDATED, [jsObject](float x, float y, float z) { + node->on([jsObject](cc::Node * /*emitter*/, float x, float y, float z) { se::AutoHandleScope hs; ccstd::array args; nativevalue_to_se(x, args[0]); @@ -248,24 +235,25 @@ static void registerLocalPositionRotationScaleUpdated(cc::Node *node, se::Object se::ScriptEngine::getInstance()->callFunction(jsObject, "_onLocalScaleUpdated", static_cast(args.size()), args.data()); }); - node->on(cc::EventTypesToJS::NODE_LOCAL_POSITION_ROTATION_SCALE_UPDATED, [jsObject](float px, float py, float pz, float rx, float ry, float rz, float rw, float sx, float sy, float sz) { - se::AutoHandleScope hs; - ccstd::array args; - nativevalue_to_se(px, args[0]); - nativevalue_to_se(py, args[1]); - nativevalue_to_se(pz, args[2]); + node->on( + [jsObject](cc::Node * /*emitter*/, float px, float py, float pz, float rx, float ry, float rz, float rw, float sx, float sy, float sz) { + se::AutoHandleScope hs; + ccstd::array args; + nativevalue_to_se(px, args[0]); + nativevalue_to_se(py, args[1]); + nativevalue_to_se(pz, args[2]); - nativevalue_to_se(rx, args[3]); - nativevalue_to_se(ry, args[4]); - nativevalue_to_se(rz, args[5]); - nativevalue_to_se(rw, args[6]); + nativevalue_to_se(rx, args[3]); + nativevalue_to_se(ry, args[4]); + nativevalue_to_se(rz, args[5]); + nativevalue_to_se(rw, args[6]); - nativevalue_to_se(sx, args[7]); - nativevalue_to_se(sy, args[8]); - nativevalue_to_se(sz, args[9]); + nativevalue_to_se(sx, args[7]); + nativevalue_to_se(sy, args[8]); + nativevalue_to_se(sz, args[9]); - se::ScriptEngine::getInstance()->callFunction(jsObject, "_onLocalPositionRotationScaleUpdated", static_cast(args.size()), args.data()); - }); + se::ScriptEngine::getInstance()->callFunction(jsObject, "_onLocalPositionRotationScaleUpdated", static_cast(args.size()), args.data()); + }); } static bool js_scene_Node_registerListeners(se::State &s) // NOLINT(readability-identifier-naming) @@ -274,28 +262,26 @@ static bool js_scene_Node_registerListeners(se::State &s) // NOLINT(readability- SE_PRECONDITION2(cobj, false, "Invalid Native Object"); auto *jsObject = s.thisObject(); - + se::Value jsThisVal(jsObject); #define NODE_DISPATCH_EVENT_TO_JS(eventType, jsFuncName) \ - cobj->on( \ - eventType, [jsObject]() { \ - se::AutoHandleScope hs; \ - se::ScriptEngine::getInstance()->callFunction(jsObject, #jsFuncName, 0, nullptr); \ + cobj->on( \ + [jsThisVal](cc::Node * /*emitter*/) { \ + se::AutoHandleScope scope; \ + se::ScriptEngine::getInstance()->callFunction(jsThisVal.toObject(), #jsFuncName, 0, nullptr); \ }); registerOnActiveNode(cobj, jsObject); registerOnBatchCreated(cobj, jsObject); - NODE_DISPATCH_EVENT_TO_JS(cc::EventTypesToJS::NODE_REATTACH, _onReAttach); - NODE_DISPATCH_EVENT_TO_JS(cc::EventTypesToJS::NODE_REMOVE_PERSIST_ROOT_NODE, _onRemovePersistRootNode); - NODE_DISPATCH_EVENT_TO_JS(cc::EventTypesToJS::NODE_DESTROY_COMPONENTS, _onDestroyComponents); - // NODE_DISPATCH_EVENT_TO_JS(cc::NodeEventType::SIBLING_ORDER_CHANGED, _onSiblingOrderChanged); + NODE_DISPATCH_EVENT_TO_JS(cc::Node::Reattach, _onReAttach); + NODE_DISPATCH_EVENT_TO_JS(cc::Node::RemovePersistRootNode, _onRemovePersistRootNode); + NODE_DISPATCH_EVENT_TO_JS(cc::Node::DestroyComponents, _onDestroyComponents); - cobj->on( - cc::NodeEventType::NODE_DESTROYED, - [](cc::Node *node) { - se::AutoHandleScope hs; + cobj->on( + [](cc::Node *emitter) { + se::AutoHandleScope scope; se::Value nodeVal; - nativevalue_to_se(node, nodeVal); + nativevalue_to_se(emitter, nodeVal); se::ScriptEngine::getInstance()->callFunction(nodeVal.toObject(), "_onNodeDestroyed", 1, &nodeVal); }); @@ -306,19 +292,21 @@ static bool js_scene_Node_registerListeners(se::State &s) // NOLINT(readability- se::ScriptEngine::getInstance()->callFunction(jsObject, "_onSiblingIndexChanged", 1, &arg0); }; - cobj->on(cc::EventTypesToJS::NODE_SCENE_UPDATED, [jsObject](cc::Scene *scene) { - se::AutoHandleScope hs; - se::Value arg0; - nativevalue_to_se(scene, arg0); - se::ScriptEngine::getInstance()->callFunction(jsObject, "_onSceneUpdated", 1, &arg0); - }); + cobj->on( + [jsObject](cc::Node * /*emitter*/, cc::Scene *scene) { + se::AutoHandleScope hs; + se::Value arg0; + nativevalue_to_se(scene, arg0); + se::ScriptEngine::getInstance()->callFunction(jsObject, "_onSceneUpdated", 1, &arg0); + }); - cobj->on(cc::EventTypesToJS::NODE_EDITOR_ATTACHED, [jsObject](bool attached) { - se::AutoHandleScope hs; - se::Value arg0; - nativevalue_to_se(attached, arg0); - se::ScriptEngine::getInstance()->callFunction(jsObject, "_onEditorAttached", 1, &arg0); - }); + cobj->on( + [jsObject](cc::Node * /*emitter*/, bool attached) { + se::AutoHandleScope hs; + se::Value arg0; + nativevalue_to_se(attached, arg0); + se::ScriptEngine::getInstance()->callFunction(jsObject, "_onEditorAttached", 1, &arg0); + }); registerLocalPositionRotationScaleUpdated(cobj, jsObject); @@ -697,29 +685,30 @@ static bool js_Model_registerListeners(se::State &s) // NOLINT(readability-ident auto *thiz = s.thisObject(); #define MODEL_DISPATCH_EVENT_TO_JS(eventType, jsFuncName) \ - cobj->getEventProcessor().on(eventType, [=](uint32_t stamp) { \ + cobj->on([=](cc::scene::Model * /*emitter*/, uint32_t stamp) { \ cobj->setCalledFromJS(true); \ se::AutoHandleScope hs; \ se::Value stampVal{stamp}; \ se::ScriptEngine::getInstance()->callFunction(thiz, #jsFuncName, 1, &stampVal); \ }) - MODEL_DISPATCH_EVENT_TO_JS(cc::EventTypesToJS::MODEL_UPDATE_TRANSFORM, updateTransform); - MODEL_DISPATCH_EVENT_TO_JS(cc::EventTypesToJS::MODEL_UPDATE_UBO, updateUBOs); + MODEL_DISPATCH_EVENT_TO_JS(cc::scene::Model::UpdateTransform, updateTransform); + MODEL_DISPATCH_EVENT_TO_JS(cc::scene::Model::UpdateUBO, updateUBOs); #undef MODEL_DISPATCH_EVENT_TO_JS - cobj->getEventProcessor().on(cc::EventTypesToJS::MODEL_UPDATE_LOCAL_DESCRIPTORS, [=](index_t subModelIndex, cc::gfx::DescriptorSet *descriptorSet) { - cobj->setCalledFromJS(true); - se::AutoHandleScope hs; + cobj->on( + [=](cc::scene::Model * /*emitter*/, index_t subModelIndex, cc::gfx::DescriptorSet *descriptorSet) { + cobj->setCalledFromJS(true); + se::AutoHandleScope hs; - ccstd::array args; - nativevalue_to_se(subModelIndex, args[0]); - nativevalue_to_se(descriptorSet, args[1]); - se::ScriptEngine::getInstance()->callFunction(thiz, "_updateLocalDescriptors", static_cast(args.size()), args.data()); - }); + ccstd::array args; + nativevalue_to_se(subModelIndex, args[0]); + nativevalue_to_se(descriptorSet, args[1]); + se::ScriptEngine::getInstance()->callFunction(thiz, "_updateLocalDescriptors", static_cast(args.size()), args.data()); + }); - cobj->getEventProcessor().on(cc::EventTypesToJS::MODEL_UPDATE_LOCAL_SH_DESCRIPTORS, [=](index_t subModelIndex, cc::gfx::DescriptorSet *descriptorSet) { + cobj->on([=](cc::scene::Model * /*emitter*/,index_t subModelIndex, cc::gfx::DescriptorSet *descriptorSet) { cobj->setCalledFromJS(true); se::AutoHandleScope hs; @@ -729,7 +718,7 @@ static bool js_Model_registerListeners(se::State &s) // NOLINT(readability-ident se::ScriptEngine::getInstance()->callFunction(thiz, "_updateLocalSHDescriptors", static_cast(args.size()), args.data()); }); - cobj->getEventProcessor().on(cc::EventTypesToJS::MODEL_UPDATE_WORLD_BOUND_DESCRIPTORS, [=](index_t subModelIndex, cc::gfx::DescriptorSet *descriptorSet) { + cobj->on([=](cc::scene::Model * /*emitter*/,index_t subModelIndex, cc::gfx::DescriptorSet *descriptorSet) { cobj->setCalledFromJS(true); se::AutoHandleScope hs; @@ -739,7 +728,7 @@ static bool js_Model_registerListeners(se::State &s) // NOLINT(readability-ident se::ScriptEngine::getInstance()->callFunction(thiz, "_updateWorldBoundDescriptors", static_cast(args.size()), args.data()); }); - cobj->getEventProcessor().on(cc::EventTypesToJS::MODEL_UPDATE_INSTANCED_ATTRIBUTES, [=](const ccstd::vector &attributes, cc::scene::SubModel *subModel) { + cobj->on([=](cc::scene::Model * /*emitter*/,const ccstd::vector &attributes, cc::scene::SubModel *subModel) { cobj->setCalledFromJS(true); se::AutoHandleScope hs; @@ -749,19 +738,20 @@ static bool js_Model_registerListeners(se::State &s) // NOLINT(readability-ident se::ScriptEngine::getInstance()->callFunction(thiz, "_updateInstancedAttributes", static_cast(args.size()), args.data()); }); - cobj->getEventProcessor().on(cc::EventTypesToJS::MODEL_GET_MACRO_PATCHES, [=](index_t subModelIndex, ccstd::vector *pPatches) { - cobj->setCalledFromJS(true); - se::AutoHandleScope hs; + cobj->on( + [=](cc::scene::Model * /*emitter*/, index_t subModelIndex, ccstd::vector *pPatches) { + cobj->setCalledFromJS(true); + se::AutoHandleScope hs; - se::Value rval; - ccstd::array args; - nativevalue_to_se(subModelIndex, args[0]); - bool ok = se::ScriptEngine::getInstance()->callFunction(thiz, "getMacroPatches", static_cast(args.size()), args.data(), &rval); + se::Value rval; + ccstd::array args; + nativevalue_to_se(subModelIndex, args[0]); + bool ok = se::ScriptEngine::getInstance()->callFunction(thiz, "getMacroPatches", static_cast(args.size()), args.data(), &rval); - if (ok) { - sevalue_to_native(rval, pPatches); - } - }); + if (ok) { + sevalue_to_native(rval, pPatches); + } + }); return true; } diff --git a/native/cocos/cocos.h b/native/cocos/cocos.h index ec3edc74cc..b194c20701 100644 --- a/native/cocos/cocos.h +++ b/native/cocos/cocos.h @@ -29,9 +29,9 @@ #include "application/ApplicationManager.h" #include "application/BaseGame.h" -#include "bindings/event/CustomEventTypes.h" #include "bindings/event/EventDispatcher.h" #include "bindings/jswrapper/SeApi.h" #include "bindings/manual/jsb_classtype.h" #include "bindings/manual/jsb_global.h" -#include "bindings/manual/jsb_module_register.h" \ No newline at end of file +#include "bindings/manual/jsb_module_register.h" +#include "core/event/Event.h" \ No newline at end of file diff --git a/native/cocos/core/Root.cpp b/native/cocos/core/Root.cpp index 7d2b1eacd8..8a29945e17 100644 --- a/native/cocos/core/Root.cpp +++ b/native/cocos/core/Root.cpp @@ -26,10 +26,7 @@ #include "core/Root.h" #include "2d/renderer/Batcher2d.h" #include "application/ApplicationManager.h" -#include "bindings/event/CustomEventTypes.h" #include "bindings/event/EventDispatcher.h" -#include "core/event/CallbacksInvoker.h" -#include "core/event/EventTypesToJS.h" #include "platform/interfaces/modules/IScreen.h" #include "platform/interfaces/modules/ISystemWindow.h" #include "platform/interfaces/modules/ISystemWindowManager.h" @@ -47,6 +44,7 @@ #include "scene/Camera.h" #include "scene/DirectionalLight.h" #include "scene/SpotLight.h" +#include "engine/EngineEvents.h" namespace cc { @@ -61,7 +59,6 @@ Root *Root::getInstance() { Root::Root(gfx::Device *device) : _device(device) { instance = this; - _eventProcessor = new CallbacksInvoker(); // TODO(minggo): // this._dataPoolMgr = legacyCC.internal.DataPoolManager && new legacyCC.internal.DataPoolManager(device) as DataPoolManager; @@ -71,7 +68,6 @@ Root::Root(gfx::Device *device) Root::~Root() { destroy(); - CC_SAFE_DELETE(_eventProcessor); instance = nullptr; } @@ -402,8 +398,7 @@ void Root::frameMoveProcess(bool isNeedUpdateScene, int32_t totalFrames, const c void Root::frameMoveEnd() { if (_pipelineRuntime != nullptr && !_cameraList.empty()) { - _eventProcessor->emit(EventTypesToJS::DIRECTOR_BEFORE_COMMIT, this); - + emit(); std::stable_sort(_cameraList.begin(), _cameraList.end(), [](const auto *a, const auto *b) { return a->getPriority() < b->getPriority(); }); @@ -416,7 +411,7 @@ void Root::frameMoveEnd() { } } #endif - _eventProcessor->emit(EventTypesToJS::DIRECTOR_BEFORE_RENDER, this); + emit(); _pipelineRuntime->render(_cameraList); #endif _device->present(); @@ -624,22 +619,22 @@ void Root::doXRFrameMove(int32_t totalFrames) { } void Root::addWindowEventListener() { - _windowDestroyEventId = EventDispatcher::addCustomEventListener(EVENT_DESTROY_WINDOW, [this](const CustomEvent &e) -> void { + _windowDestroyListener.bind([this](uint32_t windowId) -> void { for (const auto &window : _renderWindows) { - window->onNativeWindowDestroy(static_cast(e.args[0].intVal)); + window->onNativeWindowDestroy(windowId); } }); - _windowResumeEventId = EventDispatcher::addCustomEventListener(EVENT_RECREATE_WINDOW, [this](const CustomEvent &e) -> void { + _windowRecreatedListener.bind([this](uint32_t windowId) -> void { for (const auto &window : _renderWindows) { - window->onNativeWindowResume(static_cast(e.args[0].intVal)); + window->onNativeWindowResume(windowId); } }); } -void Root::removeWindowEventListener() const { - EventDispatcher::removeCustomEventListener(EVENT_DESTROY_WINDOW, _windowDestroyEventId); - EventDispatcher::removeCustomEventListener(EVENT_RECREATE_WINDOW, _windowResumeEventId); +void Root::removeWindowEventListener() { + _windowDestroyListener.reset(); + _windowRecreatedListener.reset(); } } // namespace cc diff --git a/native/cocos/core/Root.h b/native/cocos/core/Root.h index c5666e0348..9d47693ce7 100644 --- a/native/cocos/core/Root.h +++ b/native/cocos/core/Root.h @@ -26,6 +26,8 @@ #include //#include "3d/skeletal-animation/DataPoolManager.h" +#include "bindings/event/EventDispatcher.h" +#include "core/event/Event.h" #include "core/memop/Pool.h" #include "renderer/pipeline/RenderPipeline.h" #include "scene/DrawBatch2D.h" @@ -49,7 +51,6 @@ namespace render { class PipelineRuntime; class Pipeline; } // namespace render -class CallbacksInvoker; class Batcher2d; struct CC_DLL DebugViewConfig { @@ -63,11 +64,16 @@ struct CC_DLL DebugViewConfig { struct ISystemWindowInfo; class ISystemWindow; -class Root final { +class Root final : public event::EventTarget { + IMPL_EVENT_TARGET(Root) + DECLARE_TARGET_EVENT_BEGIN(Root) + TARGET_EVENT_ARG0(BeforeCommit) + TARGET_EVENT_ARG0(BeforeRender) + DECLARE_TARGET_EVENT_END() public: - static Root *getInstance(); //cjh todo: put Root Managerment to Director class. + static Root *getInstance(); // cjh todo: put Root Managerment to Director class. explicit Root(gfx::Device *device); - ~Root(); + ~Root() override; // @minggo IRootInfo seems is not use, and how to return Promise? void initialize(gfx::Swapchain *swapchain); @@ -156,7 +162,7 @@ public: #ifndef SWIGCOCOS template ::value>> T *createModel() { - //cjh TODO: need use model pool? + // cjh TODO: need use model pool? T *model = ccnew T(); model->initialize(); return model; @@ -168,7 +174,7 @@ public: #ifndef SWIGCOCOS template ::value>> T *createLight() { - //TODO(xwx): need use model pool? + // TODO(xwx): need use model pool? T *light = ccnew T(); light->initialize(); return light; @@ -287,8 +293,6 @@ public: inline bool isUsingDeferredPipeline() const { return _useDeferredPipeline; } - inline CallbacksInvoker *getEventProcessor() const { return _eventProcessor; } - scene::RenderWindow *createRenderWindowFromSystemWindow(uint32_t windowId); scene::RenderWindow *createRenderWindowFromSystemWindow(cc::ISystemWindow *window); @@ -302,7 +306,7 @@ private: void frameMoveEnd(); void doXRFrameMove(int32_t totalFrames); void addWindowEventListener(); - void removeWindowEventListener() const; + void removeWindowEventListener(); gfx::Device *_device{nullptr}; gfx::Swapchain *_swapchain{nullptr}; @@ -324,15 +328,13 @@ private: uint32_t _fixedFPS{0}; bool _useDeferredPipeline{false}; bool _usesCustomPipeline{true}; - CallbacksInvoker *_eventProcessor{nullptr}; IXRInterface *_xr{nullptr}; - uint32_t _windowDestroyEventId{0}; - uint32_t _windowResumeEventId{0}; + events::WindowDestroy::Listener _windowDestroyListener; + events::WindowRecreated::Listener _windowRecreatedListener; // Cache ccstd::vector to avoid allocate every frame in frameMove ccstd::vector _cameraList; ccstd::vector _swapchains; // }; - } // namespace cc diff --git a/native/cocos/core/assets/Asset.h b/native/cocos/core/assets/Asset.h index 9aa9116f85..26c972ffaa 100644 --- a/native/cocos/core/assets/Asset.h +++ b/native/cocos/core/assets/Asset.h @@ -32,13 +32,13 @@ #include "base/Macros.h" #include "core/Types.h" #include "core/data/Object.h" -#include "core/event/CallbacksInvoker.h" +#include "core/event/EventTarget.h" namespace cc { class Node; -class Asset : public CCObject, public EventTarget { +class Asset : public CCObject, public event::EventTarget { public: using Super = CCObject; diff --git a/native/cocos/core/assets/EffectAsset.cpp b/native/cocos/core/assets/EffectAsset.cpp index 8188882aa7..8da8fccf52 100644 --- a/native/cocos/core/assets/EffectAsset.cpp +++ b/native/cocos/core/assets/EffectAsset.cpp @@ -171,8 +171,10 @@ void EffectAsset::onLoaded() { if (CC_CURRENT_ENGINE()->isInited()) { precompile(); } else { - CC_CURRENT_ENGINE()->on(BaseEngine::ON_START, [this]() { - this->precompile(); + _engineEventId = CC_CURRENT_ENGINE()->on([this](BaseEngine * /*emitter*/, BaseEngine::EngineStatus status) { + if (status == BaseEngine::EngineStatus::ON_START) { + this->precompile(); + } }); } #endif @@ -180,6 +182,9 @@ void EffectAsset::onLoaded() { bool EffectAsset::destroy() { EffectAsset::remove(this); + if (CC_CURRENT_ENGINE()->isInited()) { + CC_CURRENT_ENGINE()->off(_engineEventId); + } return Super::destroy(); } @@ -189,7 +194,7 @@ void EffectAsset::initDefault(const ccstd::optional &uuid) { _name = "builtin-unlit"; _shaders = effect->_shaders; _combinations = effect->_combinations; - _techniques = effect->_techniques; //NOTE: it will copy effect->_techniques to _techniques and _techniques will kept by SE_HOLD_RETURN_VALUE + _techniques = effect->_techniques; // NOTE: it will copy effect->_techniques to _techniques and _techniques will kept by SE_HOLD_RETURN_VALUE } bool EffectAsset::validate() const { @@ -251,7 +256,7 @@ const defines = [ // ... all the combinations (2x4x3 in this case) ]; */ -ccstd::vector EffectAsset::doCombine(const ccstd::vector &cur, const IPreCompileInfo &info, IPreCompileInfo::iterator iter) { //NOLINT(misc-no-recursion) +ccstd::vector EffectAsset::doCombine(const ccstd::vector &cur, const IPreCompileInfo &info, IPreCompileInfo::iterator iter) { // NOLINT(misc-no-recursion) if (iter == info.end()) { return cur; } diff --git a/native/cocos/core/assets/EffectAsset.h b/native/cocos/core/assets/EffectAsset.h index 4ed13f2ed4..7ca4166eb1 100644 --- a/native/cocos/core/assets/EffectAsset.h +++ b/native/cocos/core/assets/EffectAsset.h @@ -33,10 +33,12 @@ #include "base/Value.h" #include "core/Types.h" #include "core/assets/Asset.h" +#include "engine/BaseEngine.h" #include "renderer/core/PassUtils.h" #include "renderer/gfx-base/GFXDef.h" #include "renderer/pipeline/Define.h" + namespace cc { using IPropertyHandleInfo = std::tuple; @@ -348,7 +350,7 @@ using PassOverrides = IPassStates; using PassPropertyInfoMap = ccstd::unordered_map; -struct IPassInfoFull final { //cjh } : public IPassInfo { +struct IPassInfoFull final { // cjh } : public IPassInfo { // IPassStates ccstd::optional priority; ccstd::optional primitive; @@ -465,7 +467,7 @@ struct IAttributeInfo { struct IDefineInfo { ccstd::string name; ccstd::string type; - ccstd::optional> range; //cjh number is float? ?: number[]; + ccstd::optional> range; // cjh number is float? ?: number[]; ccstd::optional> options; ccstd::optional defaultVal; }; @@ -582,6 +584,8 @@ public: bool validate() const override; protected: + BaseEngine::EngineStatusChange::EventID _engineEventId; + static ccstd::vector doCombine(const ccstd::vector &cur, const IPreCompileInfo &info, IPreCompileInfo::iterator iter); static ccstd::vector generateRecords(const ccstd::string &key, const IPreCompileInfoValueType &value); static ccstd::vector insertInfoValue(const ccstd::vector &records, @@ -617,7 +621,7 @@ public: ccstd::vector _combinations; // protected: - static RegisteredEffectAssetMap effects; //cjh TODO: how to clear when game exits. + static RegisteredEffectAssetMap effects; // cjh TODO: how to clear when game exits. static bool layoutValid; CC_DISALLOW_COPY_MOVE_ASSIGN(EffectAsset); diff --git a/native/cocos/core/assets/Material.cpp b/native/cocos/core/assets/Material.cpp index cf468e57ab..fccdf0bc5e 100644 --- a/native/cocos/core/assets/Material.cpp +++ b/native/cocos/core/assets/Material.cpp @@ -29,7 +29,6 @@ #include "core/Root.h" #include "core/assets/EffectAsset.h" #include "core/builtin/BuiltinResMgr.h" -#include "core/event/EventTypesToJS.h" #include "core/platform/Debug.h" #include "math/Color.h" #include "renderer/pipeline/helper/Utils.h" @@ -94,7 +93,7 @@ void Material::doDestroy() { } } passes.clear(); - emit(EventTypesToJS::MATERIAL_PASSES_UPDATED); + emit(); } void Material::recompileShaders(const MacroRecord & /*overrides*/, index_t /*passIdx*/) { @@ -304,7 +303,7 @@ void Material::update(bool keepProps /* = true*/) { } } - emit(EventTypesToJS::MATERIAL_PASSES_UPDATED); + emit(); } _hash = Material::getHashForMaterial(this); } diff --git a/native/cocos/core/assets/Material.h b/native/cocos/core/assets/Material.h index 47e49763b6..f18ee8e675 100644 --- a/native/cocos/core/assets/Material.h +++ b/native/cocos/core/assets/Material.h @@ -31,6 +31,7 @@ #include "base/std/optional.h" #include "base/std/variant.h" #include "core/assets/EffectAsset.h" +#include "core/event/Event.h" namespace cc { @@ -87,6 +88,10 @@ struct IMaterialInfo { }; class Material : public Asset { + IMPL_EVENT_TARGET(Material) + DECLARE_TARGET_EVENT_BEGIN(Material) + TARGET_EVENT_ARG0(PassesUpdated) + DECLARE_TARGET_EVENT_END() public: using Super = Asset; /** diff --git a/native/cocos/core/assets/SceneAsset.cpp b/native/cocos/core/assets/SceneAsset.cpp index 2ac304816e..fc1e32b673 100644 --- a/native/cocos/core/assets/SceneAsset.cpp +++ b/native/cocos/core/assets/SceneAsset.cpp @@ -25,6 +25,7 @@ #include "core/assets/SceneAsset.h" #include "core/scene-graph/Scene.h" +#include "base/memory/Memory.h" namespace cc { diff --git a/native/cocos/core/assets/SimpleTexture.cpp b/native/cocos/core/assets/SimpleTexture.cpp index 630b2228a1..3e53cb76cc 100644 --- a/native/cocos/core/assets/SimpleTexture.cpp +++ b/native/cocos/core/assets/SimpleTexture.cpp @@ -25,7 +25,6 @@ #include "core/assets/SimpleTexture.h" #include "core/assets/ImageAsset.h" -#include "core/event/EventTypesToJS.h" #include "core/platform/Debug.h" #include "core/platform/Macro.h" #include "renderer/gfx-base/GFXDevice.h" @@ -98,7 +97,7 @@ void SimpleTexture::assignImage(ImageAsset *image, uint32_t level, uint32_t arra uploadData(data, level, arrayIndex); checkTextureLoaded(); - emit(EventTypesToJS::SIMPLE_TEXTURE_AFTER_ASSIGN_IMAGE, image); + emit(image); } void SimpleTexture::checkTextureLoaded() { @@ -223,7 +222,7 @@ void SimpleTexture::setMipRangeInternal(uint32_t baseLevel, uint32_t maxLevel) { } void SimpleTexture::notifyTextureUpdated() { - emit(EventTypesToJS::SIMPLE_TEXTURE_GFX_TEXTURE_UPDATED, _gfxTexture.get()); + emit(_gfxTexture.get()); } } // namespace cc diff --git a/native/cocos/core/assets/SimpleTexture.h b/native/cocos/core/assets/SimpleTexture.h index f15867d440..f65de67793 100644 --- a/native/cocos/core/assets/SimpleTexture.h +++ b/native/cocos/core/assets/SimpleTexture.h @@ -40,6 +40,11 @@ class ImageAsset; * 简单贴图允许指定不同的 Mipmap 层级。 */ class SimpleTexture : public TextureBase { + IMPL_EVENT_TARGET(SimpleTexture) + DECLARE_TARGET_EVENT_BEGIN(SimpleTexture) + TARGET_EVENT_ARG1(TextureUpdated, cc::gfx::Texture *) + TARGET_EVENT_ARG1(AfterAssignImage, cc::ImageAsset *) + DECLARE_TARGET_EVENT_END() public: ~SimpleTexture() override; diff --git a/native/cocos/core/assets/TextureBase.cpp b/native/cocos/core/assets/TextureBase.cpp index 4cbbc9ccda..cbfc0ddf49 100644 --- a/native/cocos/core/assets/TextureBase.cpp +++ b/native/cocos/core/assets/TextureBase.cpp @@ -26,7 +26,6 @@ #include "core/assets/TextureBase.h" #include "base/StringUtil.h" #include "cocos/core/platform/Debug.h" -#include "core/event/EventTypesToJS.h" #include "core/utils/IDGenerator.h" #include "renderer/gfx-base/GFXDevice.h" @@ -185,7 +184,8 @@ bool TextureBase::isCompressed() const { } void TextureBase::notifySamplerUpdated() { - emit(EventTypesToJS::TEXTURE_BASE_GFX_SAMPLER_UPDATED, _gfxSampler); + // emit(EventTypesToJS::TEXTURE_BASE_GFX_SAMPLER_UPDATED, _gfxSampler); + emit(_gfxSampler); } } // namespace cc diff --git a/native/cocos/core/assets/TextureBase.h b/native/cocos/core/assets/TextureBase.h index f908a5038b..ba214ea28c 100644 --- a/native/cocos/core/assets/TextureBase.h +++ b/native/cocos/core/assets/TextureBase.h @@ -45,6 +45,10 @@ class Texture; * @zh 贴图资源基类。它定义了所有贴图共用的概念。 */ class TextureBase : public Asset { + IMPL_EVENT_TARGET(TextureBase) + DECLARE_TARGET_EVENT_BEGIN(TextureBase) + TARGET_EVENT_ARG1(SamplerUpdated, cc::gfx::Sampler *) + DECLARE_TARGET_EVENT_END() public: using Super = Asset; diff --git a/native/cocos/core/event/CallbacksInvoker.cpp b/native/cocos/core/event/CallbacksInvoker.cpp deleted file mode 100644 index 6e7af4a9da..0000000000 --- a/native/cocos/core/event/CallbacksInvoker.cpp +++ /dev/null @@ -1,265 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -#include "core/event/CallbacksInvoker.h" -#include "base/Log.h" - -namespace cc { - -uint32_t CallbacksInvoker::cbIDCounter{0}; - -void CallbackList::removeByCallbackID(const CallbackID &cbID) { - for (int32_t i = 0; i < _callbackInfos.size(); ++i) { - const auto &info = _callbackInfos[i]; - if (info->_id == cbID) { - utils::array::fastRemoveAt(_callbackInfos, i); - --i; - } - } -} - -void CallbackList::removeByTarget(void *target) { - for (int32_t i = 0; i < _callbackInfos.size(); ++i) { - auto &info = _callbackInfos[i]; - if (info->_target == target) { - utils::array::fastRemoveAt(_callbackInfos, i); - --i; - } - } -} - -void CallbackList::cancel(index_t index) { - std::shared_ptr *info = nullptr; - if (index >= 0 && index < _callbackInfos.size()) { - info = &_callbackInfos[index]; - } - - if (info) { - if (_isInvoking) { - _callbackInfos[index] = nullptr; - } else { - utils::array::fastRemoveAt(_callbackInfos, index); - } - } - _containCanceled = true; -} - -void CallbackList::cancelAll() { - for (auto &callbackInfo : _callbackInfos) { - callbackInfo = nullptr; - } - _containCanceled = true; -} - -void CallbackList::purgeCanceled() { - for (index_t i = static_cast(_callbackInfos.size()) - 1; i >= 0; --i) { - const auto &info = _callbackInfos[i]; - if (!info) { - utils::array::fastRemoveAt(_callbackInfos, i); - } - } - _containCanceled = false; -} - -void CallbackList::clear() { - cancelAll(); - _callbackInfos.clear(); - _isInvoking = false; - _containCanceled = false; -} - -bool CallbacksInvoker::hasEventListener(const KeyType &key) const { - auto iter = _callbackTable.find(key); - if (iter == _callbackTable.end()) { - return false; - } - - const auto &list = iter->second; - // check any valid callback - const auto &infos = list._callbackInfos; - // Make sure no cancelled callbacks - if (list._isInvoking) { - for (const auto &info : infos) { // NOLINT(readability-use-anyofallof) - if (info != nullptr) { - return true; - } - } - return false; - } - - return !infos.empty(); -} - -bool CallbacksInvoker::hasEventListener(const KeyType &key, const CallbackID &cbID) const { - auto iter = _callbackTable.find(key); - if (iter == _callbackTable.end()) { - return false; - } - - const auto &list = iter->second; - // check any valid callback - const auto &infos = list._callbackInfos; - - for (const auto &info : infos) { // NOLINT(readability-use-anyofallof) - if (info != nullptr && info->check() && info->_id == cbID) { - return true; - } - } - - return false; -} - -bool CallbacksInvoker::hasEventListener(const KeyType &key, void *target) { - auto iter = _callbackTable.find(key); - if (iter == _callbackTable.end()) { - return false; - } - - const auto &list = iter->second; - // check any valid callback - const auto &infos = list._callbackInfos; - - for (const auto &info : infos) { // NOLINT(readability-use-anyofallof) - if (info != nullptr && info->check() && info->_target == target) { - return true; - } - } - - return false; -} - -bool CallbacksInvoker::hasEventListener(const KeyType &key, void *target, const CallbackID &cbID) const { - auto iter = _callbackTable.find(key); - if (iter == _callbackTable.end()) { - return false; - } - - const auto &list = iter->second; - // check any valid callback - const auto &infos = list._callbackInfos; - - for (const auto &info : infos) { // NOLINT(readability-use-anyofallof) - if (info != nullptr && info->check() && info->_target == target && info->_id == cbID) { - return true; - } - } - - return false; -} - -void CallbacksInvoker::offAll(const KeyType &key) { - auto iter = _callbackTable.find(key); - if (iter != _callbackTable.end()) { - auto &list = iter->second; - if (list._isInvoking) { - list.cancelAll(); - } else { - list.clear(); - _callbackTable.erase(iter); - } - } -} - -void CallbacksInvoker::offAll(void *target) { - for (auto &e : _callbackTable) { - auto &list = e.second; - const auto &infos = list._callbackInfos; - if (list._isInvoking) { - index_t i = 0; - for (const auto &info : infos) { - if (info != nullptr && info->_target == target) { - list.cancel(i); - } - ++i; - } - } else { - list.removeByTarget(target); - } - } -} - -void CallbacksInvoker::offAll() { - for (auto iter = _callbackTable.begin(); iter != _callbackTable.end();) { - auto &list = iter->second; - if (list._isInvoking) { - list.cancelAll(); - ++iter; - } else { - list.clear(); - iter = _callbackTable.erase(iter); - } - } -} - -void CallbacksInvoker::off(const KeyType &key, const CallbackID &cbID) { - auto iter = _callbackTable.find(key); - if (iter != _callbackTable.end()) { - auto &list = iter->second; - const auto &infos = list._callbackInfos; - index_t i = 0; - for (const auto &info : infos) { - if (info != nullptr && info->_id == cbID) { - list.cancel(i); - break; - } - ++i; - } - } -} - -void CallbacksInvoker::offAll(const KeyType &key, void *target) { - auto iter = _callbackTable.find(key); - if (iter != _callbackTable.end()) { - auto &list = iter->second; - const auto &infos = list._callbackInfos; - index_t i = 0; - if (list._isInvoking) { - for (const auto &info : infos) { - if (info != nullptr && info->_target == target) { - list.cancel(i); - } - ++i; - } - } else { - list.removeByTarget(target); - } - } -} - -void CallbacksInvoker::off(const CallbackID &cbID) { - for (auto &cbInfo : _callbackTable) { - auto &list = cbInfo.second; - const auto &infos = list._callbackInfos; - index_t i = 0; - for (const auto &info : infos) { - if (info != nullptr && info->_id == cbID) { - list.cancel(i); - break; - } - ++i; - } - } -} - -} // namespace cc diff --git a/native/cocos/core/event/CallbacksInvoker.h b/native/cocos/core/event/CallbacksInvoker.h deleted file mode 100644 index 19cbe18cf7..0000000000 --- a/native/cocos/core/event/CallbacksInvoker.h +++ /dev/null @@ -1,476 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ -#pragma once - -#include -#include -#include -#include "base/std/container/string.h" -#include "base/std/container/unordered_map.h" - -#include "base/Log.h" -#include "base/Macros.h" -#include "base/Utils.h" -#include "core/data/Object.h" - -namespace cc { - -#define CC_CALLBACK_INVOKE_0(__selector__, __target__, ...) std::function(std::bind(&__selector__, __target__, ##__VA_ARGS__)), __target__ -#define CC_CALLBACK_INVOKE_1(__selector__, __target__, Arg0, ...) std::function(std::bind(&__selector__, __target__, std::placeholders::_1, ##__VA_ARGS__)), __target__ -#define CC_CALLBACK_INVOKE_2(__selector__, __target__, Arg0, Arg1, ...) std::function(std::bind(&__selector__, __target__, std::placeholders::_1, std::placeholders::_2, ##__VA_ARGS__)), __target__ -#define CC_CALLBACK_INVOKE_3(__selector__, __target__, Arg0, Arg1, Arg2, ...) std::function(std::bind(&__selector__, __target__, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, ##__VA_ARGS__)), __target__ - -struct CallbackID { - inline bool operator==(const CallbackID &rhs) const noexcept { return value == rhs.value; } - uint32_t value{0}; -}; - -struct CallbackInfoBase { - using FakeCallbackMemberFn = void (CCObject::*)(); - - CallbackInfoBase() = default; - virtual ~CallbackInfoBase() = default; - - virtual bool check() const = 0; - virtual void reset() = 0; - virtual FakeCallbackMemberFn getMemberFn() const = 0; - - void *_target{nullptr}; - CallbackID _id; - bool _once{false}; - bool _isCCObject{false}; -#if CC_DEBUG - ccstd::vector _argTypes; -#endif -}; - -template -struct CallbackInfo final : public CallbackInfoBase { - using CallbackFn = std::function; - using CallbackMemberFn = void (CCObject::*)(Args...); - - CallbackFn _callback{nullptr}; - CallbackMemberFn _memberFn{nullptr}; - - template - void set(CallbackFn &&callback, Target *target, bool once) { - _callback = std::forward(callback); - _target = target; - _once = once; - _isCCObject = std::is_base_of::value; -#if CC_DEBUG - _argTypes = {(typeid(Args).name())...}; -#endif - } - - template ::value>> - void set(CallbackMemberFn memberFn, Target *target, bool once) { - _memberFn = memberFn; - _target = target; - _once = once; - _isCCObject = true; -#if CC_DEBUG - _argTypes = {(typeid(Args).name())...}; -#endif - } - - void reset() override { - _callback = nullptr; - _memberFn = nullptr; - _target = nullptr; - _once = false; - _isCCObject = false; -#if CC_DEBUG - _argTypes.clear(); -#endif - } - - bool check() const override { - // Validation - if (_isCCObject) { - if (!isObjectValid(reinterpret_cast(_target), true)) { - return false; - } - } - return true; - } - - FakeCallbackMemberFn getMemberFn() const override { - return reinterpret_cast(_memberFn); - } -}; - -/** - * @zh 事件监听器列表的简单封装。 - * @en A simple list of event callbacks - */ -class CallbackList final { -public: - ccstd::vector> _callbackInfos; - bool _isInvoking{false}; - bool _containCanceled{false}; - - /** - * @zh 从列表中移除与指定目标相同回调函数的事件。 - * @en Remove the event listeners with the given callback from the list - * - * @param cbID - The callback id to be removed - */ - void removeByCallbackID(const CallbackID &cbID); - - /** - * @zh 从列表中移除与指定目标相同调用者的事件。 - * @en Remove the event listeners with the given target from the list - * @param target - */ - void removeByTarget(void *target); - - /** - * @zh 移除指定编号事件。 - * @en Remove the event listener at the given index - * @param index - */ - void cancel(index_t index); - - /** - * @zh 注销所有事件。 - * @en Cancel all event listeners - */ - void cancelAll(); - - /** - * @zh 立即删除所有取消的回调。(在移除过程中会更加紧凑的排列数组) - * @en Delete all canceled callbacks and compact array - */ - void purgeCanceled(); - - /** - * @zh 清除并重置所有数据。 - * @en Clear all data - */ - void clear(); -}; - -/** - * @zh CallbacksInvoker 用来根据事件名(Key)管理事件监听器列表并调用回调方法。 - * @en CallbacksInvoker is used to manager and invoke event listeners with different event keys, - * each key is mapped to a CallbackList. - */ -class CallbacksInvoker { -public: - using KeyType = uint32_t; - CallbacksInvoker() = default; - virtual ~CallbacksInvoker() = default; - /** - * @zh 向一个事件名注册一个新的事件监听器,包含回调函数和调用者 - * @en Register an event listener to a given event key with callback and target. - * - * @param key - Event type - * @param callback - Callback function when event triggered - * @param target - Callback callee - * @param once - Whether invoke the callback only once (and remove it) - */ - template - void on(const KeyType &key, void (Target::*memberFn)(Args...), Target *target, bool once = false); - - template - void on(const KeyType &key, std::function &&callback, Target *target, bool once = false); - - template - void on(const KeyType &key, std::function &&callback, bool once = false); - - template - std::enable_if_t::value, void> - on(const KeyType &key, LambdaType &&callback, Target *target, bool once = false); - - template - std::enable_if_t::value, void> - on(const KeyType &key, LambdaType &&callback, bool once = false); - - // - template - void on(const KeyType &key, std::function &&callback, Target *target, CallbackID &outCallbackID, bool once = false); - - template - void on(const KeyType &key, std::function &&callback, CallbackID &outCallbackID, bool once = false); - - template - std::enable_if_t::value, void> - on(const KeyType &key, LambdaType &&callback, Target *target, CallbackID &outCallbackID, bool once = false); - - template - std::enable_if_t::value, void> - on(const KeyType &key, LambdaType &&callback, CallbackID &outCallbackID, bool once = false); - - /** - * @zh 检查指定事件是否已注册回调。 - * @en Checks whether there is correspond event listener registered on the given event - * @param key - Event type - * @param cbID - Callback ID - */ - bool hasEventListener(const KeyType &key) const; - bool hasEventListener(const KeyType &key, const CallbackID &cbID) const; - bool hasEventListener(const KeyType &key, void *target); - bool hasEventListener(const KeyType &key, void *target, const CallbackID &cbID) const; - template - bool hasEventListener(const KeyType &key, void (Target::*memberFn)(Args...), Target *target) const; - /** - * @zh 移除在特定事件类型中注册的所有回调或在某个目标中注册的所有回调。 - * @en Removes all callbacks registered in a certain event type or all callbacks registered with a certain target - * @param key - The event type or target with which the listeners will be removed - */ - void offAll(const KeyType &key, void *target); - void offAll(const KeyType &key); - void offAll(void *target); - void offAll(); - - /** - * @zh 删除以指定事件,回调函数,目标注册的回调。 - * @en Remove event listeners registered with the given event key, callback and target - * @param key - Event type - * @param target callback Target - * @param cbID - The callback ID of the event listener, if absent all event listeners for the given type will be removed - */ - void off(const KeyType &key, const CallbackID &cbID); - void off(const CallbackID &cbID); - template - void off(const KeyType &key, void (Target::*memberFn)(Args...), Target *target); - - /** - * @zh 派发一个指定事件,并传递需要的参数 - * @en Trigger an event directly with the event name and necessary arguments. - * @param key - event type - * @param args - The arguments to be passed to the callback - */ - template - void emit(const KeyType &key, Args &&...args); - - template - struct FunctionTraits - : public FunctionTraits { - }; - - template - struct FunctionTraits { - using type = std::function; - }; - - template - struct FunctionTraits { - using type = std::function; - }; - - template - static typename FunctionTraits>::type toFunction(T &&l) { - return typename FunctionTraits>::type{std::forward(l)}; - } - -private: - ccstd::unordered_map _callbackTable; - static uint32_t cbIDCounter; -}; - -template -void CallbacksInvoker::on(const KeyType &key, void (Target::*memberFn)(Args...), Target *target, bool once) { - static_assert(std::is_base_of::value, "Target must be the subclass of CCObject"); - using CallbackInfoType = CallbackInfo; - auto &list = _callbackTable[key]; - auto info = std::make_shared(); - info->_id.value = ++cbIDCounter; - info->set(static_cast(memberFn), target, once); - list._callbackInfos.emplace_back(std::move(info)); -} - -template -void CallbacksInvoker::on(const KeyType &key, std::function &&callback, Target *target, CallbackID &outCallbackID, bool once) { - auto &list = _callbackTable[key]; - auto info = std::make_shared>(); - info->_id.value = ++cbIDCounter; - CallbackID cbID = info->_id; - info->set(std::forward>(callback), target, once); - list._callbackInfos.emplace_back(std::move(info)); - outCallbackID = cbID; -} - -template -void CallbacksInvoker::on(const KeyType &key, std::function &&callback, CallbackID &outCallbackID, bool once) { - on(key, std::forward>(callback), nullptr, outCallbackID, once); -} - -template -std::enable_if_t::value, void> -CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, Target *target, CallbackID &outCallbackID, bool once) { - on(key, toFunction(std::forward(callback)), target, outCallbackID, once); -} - -template -std::enable_if_t::value, void> -CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, CallbackID &outCallbackID, bool once) { - on(key, toFunction(std::forward(callback)), outCallbackID, once); -} - -template -void CallbacksInvoker::on(const KeyType &key, std::function &&callback, Target *target, bool once) { - CallbackID unusedID{0}; - on(key, callback, target, unusedID, once); -} - -template -void CallbacksInvoker::on(const KeyType &key, std::function &&callback, bool once) { - CallbackID unusedID{0}; - on(key, std::forward>(callback), nullptr, unusedID, once); -} - -template -std::enable_if_t::value, void> -CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, Target *target, bool once) { - CallbackID unusedID{0}; - on(key, toFunction(std::forward(callback)), target, unusedID, once); -} - -template -std::enable_if_t::value, void> -CallbacksInvoker::on(const KeyType &key, LambdaType &&callback, bool once) { - CallbackID unusedID{0}; - on(key, toFunction(std::forward(callback)), unusedID, once); -} - -template -void CallbacksInvoker::off(const KeyType &key, void (Target::*memberFn)(Args...), Target *target) { - static_assert(std::is_base_of::value, "Target must be the subclass of CCObject"); - using CallbackFn = void (CCObject::*)(Args...); - auto iter = _callbackTable.find(key); - if (iter != _callbackTable.end()) { - auto &list = iter->second; - const auto &infos = list._callbackInfos; - size_t i = 0; - for (const auto &info : infos) { - if (info != nullptr && reinterpret_cast(info->getMemberFn()) == memberFn && info->_target == target) { - list.cancel(static_cast(i)); - break; - } - ++i; - } - } -} - -template -void CallbacksInvoker::emit(const KeyType &key, Args &&...args) { -#if CC_DEBUG - ccstd::vector argTypes{(typeid(Args).name())...}; -#endif - auto iter = _callbackTable.find(key); - if (iter != _callbackTable.end()) { - auto &list = iter->second; - bool rootInvoker = !list._isInvoking; - list._isInvoking = true; - - auto &infos = list._callbackInfos; - for (auto &i : infos) { - auto &baseInfo = i; - if (baseInfo == nullptr) { - continue; - } - -#if CC_DEBUG - CC_ASSERT(baseInfo->_argTypes.size() == argTypes.size()); - for (size_t i = 0, len = argTypes.size(); i < len; ++i) { - if (baseInfo->_argTypes[i] != argTypes[i]) { - CC_LOG_ERROR("Wrong argument type! baseInfo->_argTypes[%d]=%s, argTypes[%d]=%s", i, baseInfo->_argTypes[i].c_str(), i, argTypes[i].c_str()); - CC_ASSERT(false); - } - } -#endif - using CallbackInfoType = CallbackInfo; - auto info = std::static_pointer_cast(i); - if (info != nullptr) { - if (info->_memberFn != nullptr && info->_target != nullptr) { - auto memberFn = info->_memberFn; - auto *target = reinterpret_cast(info->_target); - - // Pre off once callbacks to avoid influence on logic in callback - if (info->_once) { - off(key, memberFn, target); - } - // Lazy check validity of callback target, - // if target is CCObject and is no longer valid, then remove the callback info directly - if (!info->check()) { - off(key, memberFn, target); - } else { - (target->*memberFn)(std::forward(args)...); - } - } else { - const auto &callback = info->_callback; - const CallbackID &cbID = info->_id; - // Pre off once callbacks to avoid influence on logic in callback - if (info->_once) { - off(key, cbID); - } - // Lazy check validity of callback target, - // if target is CCObject and is no longer valid, then remove the callback info directly - if (!info->check()) { - off(key, cbID); - } else { - callback(std::forward(args)...); - } - } - } else { - CC_ASSERT(false); - } - } - - if (rootInvoker) { - list._isInvoking = false; - if (list._containCanceled) { - list.purgeCanceled(); - } - } - } -} - -template -bool CallbacksInvoker::hasEventListener(const KeyType &key, void (Target::*memberFn)(Args...), Target *target) const { - using CallbackFn = void (CCObject::*)(Args...); - auto iter = _callbackTable.find(key); - if (iter == _callbackTable.end()) { - return false; - } - - const auto &list = iter->second; - // check any valid callback - const auto &infos = list._callbackInfos; - - for (const auto &info : infos) { - if (info != nullptr && info->check() && reinterpret_cast(info->getMemberFn()) == memberFn && info->_target == target) { - return true; - } - } - - return false; -} - -using EventTarget = CallbacksInvoker; - -} // namespace cc diff --git a/native/cocos/bindings/event/CustomEventTypes.h b/native/cocos/core/event/Event.h similarity index 52% rename from native/cocos/bindings/event/CustomEventTypes.h rename to native/cocos/core/event/Event.h index 289e78a658..579baa3c32 100644 --- a/native/cocos/bindings/event/CustomEventTypes.h +++ b/native/cocos/core/event/Event.h @@ -1,8 +1,8 @@ /**************************************************************************** - Copyright (c) 2018-2022 Xiamen Yaji Software Co., Ltd. - + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + http://www.cocos.com - + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated engine source code (the "Software"), a limited, worldwide, royalty-free, non-assignable, revocable and non-exclusive license @@ -10,10 +10,10 @@ not use Cocos Creator software for developing other software or tools that's used for developing games. You are not granted to publish, distribute, sublicense, and/or sell copies of Cocos Creator. - + The software or tools in this License Agreement are licensed, not sold. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -21,21 +21,35 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -****************************************************************************/ - + ****************************************************************************/ #pragma once - -#define EVENT_COME_TO_FOREGROUND "event_come_to_foreground" -#define EVENT_COME_TO_BACKGROUND "event_come_to_background" -#define EVENT_DESTROY_WINDOW "event_destroy_window" -#define EVENT_RESTART_VM "event_restart_vm" -#define EVENT_RECREATE_WINDOW "event_recreate_window" -#define EVENT_MEMORY_WARNING "event_memory_warning" -#define EVENT_RESIZE "event_resize" -#define EVENT_CLOSE "event_close" -#define EVENT_SCENE_LOAD "event_scene_load" - -#define EVENT_MOUSE_DOWN "event_mouse_down" -#define EVENT_MOUSE_UP "event_mouse_up" -#define EVENT_MOUSE_MOVE "event_mouse_move" -#define EVENT_MOUSE_WHEEL "event_mouse_wheel" +#ifdef SWIGCOCOS + #define IMPL_EVENT_TARGET_WITH_PARENT(...) + #define IMPL_EVENT_TARGET(...) + #define DECLARE_TARGET_EVENT_BEGIN(...) + #define DECLARE_TARGET_EVENT_END(...) + #define TARGET_EVENT_ARG0(...) + #define TARGET_EVENT_ARG1(...) + #define TARGET_EVENT_ARG2(...) + #define TARGET_EVENT_ARG3(...) + #define TARGET_EVENT_ARG4(...) + #define TARGET_EVENT_ARG5(...) + #define TARGET_EVENT_ARG6(...) + #define TARGET_EVENT_ARG7(...) + #define TARGET_EVENT_ARG8(...) + #define TARGET_EVENT_ARG9(...) + #define TARGET_EVENT_ARG10(...) + #define TARGET_EVENT_ARG11(...) + #define TARGET_EVENT_ARG12(...) + #define TARGET_EVENT_ARG13(...) + #define TARGET_EVENT_ARG14(...) + #define TARGET_EVENT_ARG15(...) + #define TARGET_EVENT_ARG16(...) + #define TARGET_EVENT_ARG17(...) + #define TARGET_EVENT_ARG18(...) + #define TARGET_EVENT_ARG19(...) + #define TARGET_EVENT_ARG20(...) +#else + #include "EventBus.h" + #include "EventTarget.h" +#endif \ No newline at end of file diff --git a/native/tools/simulator/libsimulator/lib/CustomAppEvent.cpp b/native/cocos/core/event/EventBus.cpp similarity index 55% rename from native/tools/simulator/libsimulator/lib/CustomAppEvent.cpp rename to native/cocos/core/event/EventBus.cpp index 0c5c51c530..db78fee1a2 100644 --- a/native/tools/simulator/libsimulator/lib/CustomAppEvent.cpp +++ b/native/cocos/core/event/EventBus.cpp @@ -1,8 +1,8 @@ /**************************************************************************** - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + http://www.cocos.com - + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated engine source code (the "Software"), a limited, worldwide, royalty-free, non-assignable, revocable and non-exclusive license @@ -10,10 +10,10 @@ not use Cocos Creator software for developing other software or tools that's used for developing games. You are not granted to publish, distribute, sublicense, and/or sell copies of Cocos Creator. - + The software or tools in this License Agreement are licensed, not sold. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -22,38 +22,40 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +#include "EventBus.h" +#include +#include "intl/List.h" -// -// CustomAppEvent.cpp -// Simulator -// -// +namespace cc { +namespace event { -#include "CustomAppEvent.h" - -CustomAppEvent::CustomAppEvent(const std::string& eventName, int type) -: CustomEvent() -, _eventName(eventName) -{ - name = eventName; - setEventType(type); +bool BusEventListenerContainer::addListener(BusEventListenerBase *lis) { + if (_isBroadcasting) { + intl::listAppend(&_pendingNew, lis); + return true; + } + return doAddListener(lis); } -void CustomAppEvent::setEventType(int type) -{ - _eventType = type; -} -int CustomAppEvent::getEventType() -{ - return _eventType; +bool BusEventListenerContainer::removeListener(BusEventListenerBase *lis) { + if (_isBroadcasting) { + intl::listAppend(&_pendingDel, lis); + return true; + } + return doRemoveListener(lis); } -void CustomAppEvent::setDataString(std::string data) -{ - _dataString = data; -} - -std::string CustomAppEvent::getDataString() -{ - return _dataString; +void BusEventListenerContainer::fixPendings() { + EVENT_LIST_LOOP_REV_BEGIN(curr, _pendingDel) + intl::detachFromList(&_pendingDel, curr); + doRemoveListener(curr); + EVENT_LIST_LOOP_REV_END(curr, _pendingDel) + EVENT_LIST_LOOP_REV_BEGIN(curr, _pendingNew) + intl::detachFromList(&_pendingNew, curr); + doAddListener(curr); + EVENT_LIST_LOOP_REV_END(curr, _pendingNew) + _pendingDel = nullptr; + _pendingNew = nullptr; } +} // namespace event +} // namespace cc \ No newline at end of file diff --git a/native/cocos/core/event/EventBus.h b/native/cocos/core/event/EventBus.h new file mode 100644 index 0000000000..88eb442995 --- /dev/null +++ b/native/cocos/core/event/EventBus.h @@ -0,0 +1,215 @@ +/**************************************************************************** + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +#pragma once + +#include +#include +#include + +#include "intl/EventIntl.h" +#include "intl/List.h" + +namespace cc { +namespace event { + +class BusEventListenerBase { +public: + BusEventListenerBase *next{nullptr}; + BusEventListenerBase *prev{nullptr}; +}; + +class BusEventListenerContainer { +public: + BusEventListenerContainer() = default; + virtual ~BusEventListenerContainer() = default; + bool addListener(BusEventListenerBase *); + bool removeListener(BusEventListenerBase *); + + template + bool broadcast(ARGS &&...args); + +private: + bool doAddListener(BusEventListenerBase *listener) { + return intl::listAppend(&_arr, listener); + } + bool doRemoveListener(BusEventListenerBase *listener) { + return intl::detachFromList(&_arr, listener); + } + bool hasPending() const { + return _pendingDel || _pendingNew; + } + void fixPendings(); + +protected: + BusEventListenerBase *_arr{nullptr}; + BusEventListenerBase *_pendingNew{nullptr}; + BusEventListenerBase *_pendingDel{nullptr}; + int _isBroadcasting = 0; +}; + +template +class BusEventBroadcaster : public BusEventListenerContainer { +public: + bool doBroadcast(ARGS &&...args); +}; + +template +bool BusEventListenerContainer::broadcast(ARGS &&...args) { + using BusType = BusEventBroadcaster; + _isBroadcasting++; + auto ret = static_cast(this)->doBroadcast(std::forward(args)...); + _isBroadcasting--; + if (!_isBroadcasting && hasPending()) { + fixPendings(); + } + return false; +} + +template +class BusEventListenerDB final { +public: + static BusEventListenerContainer *container() { + if (ctn == nullptr) { + ctn = new BusEventListenerContainer; + } + return ctn; + } + +private: + static BusEventListenerContainer *ctn; +}; + +template +BusEventListenerContainer *BusEventListenerDB::ctn = nullptr; + +template +struct BusEventTrait { + using bus_type = BusType; + using return_type = R; + using argument_tuple_types = std::tuple; + constexpr static int ARG_COUNT = sizeof...(ARGS); +}; +/** + * Bus Event Listener + */ +template +class Listener : public BusEventListenerBase { +public: + using bus_type = typename EHandler::bus_type; + using return_type = typename EHandler::return_type; + using argument_tuple_types = typename EHandler::argument_tuple_types; + using _argument_wrapper = typename intl::TupleExtractor; + // using func_type = typename _argument_wrapper::func_type; + using std_func_type = typename _argument_wrapper::std_func_type; + + constexpr static const char *BUS_NAME = EHandler::BUS_NAME; + constexpr static const char *HANDLE_CLASS = EHandler::HANDLE_CLASS; + + Listener(); + ~Listener(); + + inline bool isEnabled() const { return _enabled; } + inline void enable() { _enabled = true; } + inline void disable() { _enabled = false; } + inline void reset() { _callback = nullptr; } + + template + bool bind(Fn &&func) { + _callback = intl::convertLambda(std::forward(func)); + return true; + } + + template + void invoke(ARGS &&...args) { + if (_callback && _enabled) { + _callback(std::forward(args)...); + } else { + std::cerr << "[ERROR] listener has no bound function or disabled!" << std::endl; + } + } + + const char *getBusName() const { return BUS_NAME; } + const char *getHanlderName() const { return HANDLE_CLASS; } + +private: + bool _enabled{true}; + std_func_type _callback; +}; + +template +Listener::Listener() { + BusEventListenerDB::container()->addListener(this); +} + +template +Listener::~Listener() { + BusEventListenerDB::container()->removeListener(this); +} + +template +bool BusEventBroadcaster::doBroadcast(ARGS &&...args) { + // broadcast events to all listeners + EVENT_LIST_LOOP_BEGIN(curr, _arr) + static_cast *>(curr)->invoke(std::forward(args)...); + EVENT_LIST_LOOP_END(curr, _arr) + return true; +} + +template +void broadcast(ARGS &&...args) { + static_assert(sizeof...(ARGS) == EHandler::ARG_COUNT, "parameter count incorrect"); + event::intl::validateParameters<0, EHandler, ARGS...>(std::forward(args)...); + auto *listenerSet = BusEventListenerDB::container(); + listenerSet->template broadcast(std::forward(args)...); +} + +} // namespace event +} // namespace cc + +// NOLINTNEXTLINE +#define EventBusName_(n) n##_ebus + +#define DECLARE_EVENT_BUS(EventBusClass) \ + struct EventBusClass##_ebus { \ + constexpr static const char *BUS_NAME = #EventBusClass; \ + }; + +// NOLINTNEXTLINE +#define _DECLARE_BUS_EVENT_VA(BusEventClass, EventBusClass, ...) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + template \ + static inline void emit(ARGS &&...args) { \ + cc::event::emit(std::forward(args)...); \ + } \ + }; + +#include "intl/EventBusMacros.h" diff --git a/native/cocos/core/event/EventTarget.h b/native/cocos/core/event/EventTarget.h new file mode 100644 index 0000000000..c391d8e45e --- /dev/null +++ b/native/cocos/core/event/EventTarget.h @@ -0,0 +1,599 @@ +/**************************************************************************** + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +#pragma once + +#include +#include +#include "base/Macros.h" +#include "intl/EventIntl.h" +#include "intl/List.h" + +namespace cc { +namespace event { + +class TgtEventTraitClass {}; + +enum class EventPhaseType { + CAPTUREING_PHASE = 1, + AT_TARGET = 2, + BUBBLING_PHASE = 3, +}; + +struct TgtEventInfo { + EventPhaseType eventPhase; + bool bubbles{true}; + bool cancelable; + void stopPropagation() { + propagationStopped = true; + } + void preventDefault(); + bool propagationStopped{false}; +}; + +template +struct Event : TgtEventInfo { + using emitter_type = typename TgtEvent::emitter_type; + using argument_tuple_types = typename TgtEvent::argument_tuple_types; + using argument_temp_types = typename TgtEvent::argument_temp_types; + emitter_type *target; + emitter_type *currentTarget; + argument_temp_types args; + + Event() = default; + + explicit Event(const argument_tuple_types &argsIn) : args(argsIn) { + } + + template + auto get() const { + return std::get(args); + } + template + auto get() { + return std::get(args); + } + + template + void set(A &&value) { + std::get(args) = value; + } + void initEvent(bool canBubbleArg, bool cancelableArg) { + // TODO() + } + + template + void update(ARGS &&...values) { + args = std::make_tuple<>(std::forward(values)...); + } +}; + +template +class TgtEventTrait : public TgtEventTraitClass { +public: + using emitter_type = EmitterType; + using argument_tuple_types = std::tuple; + using argument_temp_types = std::tuple>...>; + constexpr static int ARG_COUNT = sizeof...(ARGS); +}; + +class TgtMemberFnCmp { +public: + virtual ~TgtMemberFnCmp() = default; + virtual void *getContext() = 0; + virtual bool equals(TgtMemberFnCmp *) const = 0; +}; + +template +class TgtMemberHandleFn final : public TgtMemberFnCmp { +public: + ~TgtMemberHandleFn() override = default; + void *getContext() override { return context; } + bool equals(TgtMemberFnCmp *other) const override { + auto *fake = reinterpret_cast(other); + return context == fake->context && func == fake->func; + } + Fn func; + void *context; +}; + +class TargetEventListenerBase { +public: + enum class RunState { + NORMAL, + PENDING_ONCE, + ONCE_DONE, + }; + virtual ~TargetEventListenerBase() = default; + virtual void *getContext() const = 0; + virtual const char *getEventType() const { return nullptr; } + + bool isEnabled() const { return _enabled; } + void setOnce() { _state = RunState::PENDING_ONCE; } + inline size_t getEventTypeID() const { return _eventTypeID; } + + int32_t id{-1}; + + TargetEventListenerBase *next{nullptr}; + TargetEventListenerBase *prev{nullptr}; + +protected: + bool _enabled = true; + RunState _state{RunState::NORMAL}; + size_t _eventTypeID; +}; + +template +class TargetEventListener : public TargetEventListenerBase { +public: + using emitter_type = typename TgtEvent::emitter_type; + using event_type = typename TgtEvent::event_type; + using persist_function_type = typename TgtEvent::persist_function_type; + explicit TargetEventListener(persist_function_type func) : _func(func) { + _eventTypeID = TgtEvent::TypeID(); + } + + ~TargetEventListener() override { + delete _fnCmptor; + } + + template + void setMemberFuncAddr(Fn func, void *context) { + auto fctx = new TgtMemberHandleFn; + fctx->func = func; + fctx->context = context; + _fnCmptor = fctx; + } + + void *getContext() const override { + if (_fnCmptor) return _fnCmptor->getContext(); + return nullptr; + } + + void apply(emitter_type *self, event_type *evobj) { + switch (_state) { + case RunState::ONCE_DONE: + return; + case RunState::PENDING_ONCE: + _state = RunState::ONCE_DONE; + break; + default: + break; + } + _func(self, evobj); + } + +protected: + persist_function_type _func; + TgtMemberFnCmp *_fnCmptor{nullptr}; +}; + +using target_event_id_type = int32_t; + +template +class TargetEventID final { +public: + using handle_type = TgtEvent; + using id_type = target_event_id_type; + TargetEventID() = default; + TargetEventID(id_type eventId) : _eventId(eventId) {} // NOLINT + + TargetEventID(const TargetEventID &) = default; + TargetEventID(TargetEventID &&) noexcept = default; + + TargetEventID &operator=(const TargetEventID &) = default; + TargetEventID &operator=(TargetEventID &&) noexcept = default; + + id_type value() { return _eventId; } + +private: + id_type _eventId{}; +}; + +class EventTarget { +public: + static constexpr bool HAS_PARENT = false; + + template + TargetEventID addEventListener(Fn &&func, bool useCapture, bool once) { + // CC_ASSERT(!_emittingEvent); + using func_type = std::conditional_t::IS_LAMBDA, + typename intl::lambda_without_class_t, Fn>; + using wrap_type = intl::TgtEvtFnTrait; + auto stdfn = wrap_type::template wrap(intl::convertLambda(std::forward(func))); + auto *newHandler = new event::TargetEventListener(stdfn); + auto newId = ++_handlerId; + newHandler->id = newId; + if (once) { + newHandler->setOnce(); + } + if constexpr (wrap_type::IS_MEMBER_FUNC) { + newHandler->setMemberFuncAddr(std::forward(func), nullptr); + } + if (useCapture) { + intl::listAppend(&_capturingHandlersMap[TgtEvent::TypeID()], newHandler); + } else { + intl::listAppend(&_bubblingHandlersMap[TgtEvent::TypeID()], newHandler); + } + return TargetEventID(newId); + } + + template + TargetEventID once(Fn &&func, bool useCapture) { + return this->template addEventListener(std::forward(func), useCapture, true); + } + + template + TargetEventID addEventListener(Fn &&func, O *ctx, bool useCapture, bool once) { + // CC_ASSERT(!_emittingEvent); + using wrap_type = event::intl::TgtEvtFnTrait; + auto stdfn = wrap_type::template wrapWithContext(std::forward(func), ctx); + auto *newHandler = new event::TargetEventListener(stdfn); + auto newId = ++_handlerId; + newHandler->id = newId; + if (once) { + newHandler->setOnce(); + } + if constexpr (wrap_type::IS_MEMBER_FUNC) { + newHandler->setMemberFuncAddr(std::forward(func), ctx); + } + if (useCapture) { + intl::listAppend(&_capturingHandlersMap[TgtEvent::TypeID()], newHandler); + } else { + intl::listAppend(&_bubblingHandlersMap[TgtEvent::TypeID()], newHandler); + } + return TargetEventID(newId); + } + + template + TargetEventID once(Fn &&func, O *ctx) { + return this->template addEventListener(std::forward(func), ctx, true); + } + + template + bool off(TargetEventID eventId) { + CC_ASSERT(!_emittingEvent); + + TargetEventListenerBase *&bubblingHandlers = _bubblingHandlersMap[TgtEvent::TypeID()]; + + EVENT_LIST_LOOP_REV_BEGIN(handle, bubblingHandlers) + if (handle && handle->id == eventId.value()) { + CC_ASSERT(handle->getEventTypeID() == TgtEvent::TypeID()); + intl::detachFromList(&bubblingHandlers, handle); + delete handle; + return true; + } + EVENT_LIST_LOOP_REV_END(handle, bubblingHandlers) + TargetEventListenerBase *&capturingHandlers = _capturingHandlersMap[TgtEvent::TypeID()]; + EVENT_LIST_LOOP_REV_BEGIN(handle, capturingHandlers) + if (handle && handle->id == eventId.value()) { + CC_ASSERT(handle->getEventTypeID() == TgtEvent::TypeID()); + intl::detachFromList(&capturingHandlers, handle); + delete handle; + return true; + } + EVENT_LIST_LOOP_REV_END(handle, capturingHandlers) + return false; + } + + void offAll() { + CC_ASSERT(!_emittingEvent); + for (auto &itr : _bubblingHandlersMap) { + TargetEventListenerBase *&handlers = itr.second; + EVENT_LIST_LOOP_REV_BEGIN(handle, handlers) + delete handle; + EVENT_LIST_LOOP_REV_END(handle, handlers) + } + + for (auto &itr : _capturingHandlersMap) { + TargetEventListenerBase *&handlers = itr.second; + EVENT_LIST_LOOP_REV_BEGIN(handle, handlers) + delete handle; + EVENT_LIST_LOOP_REV_END(handle, handlers) + } + + _bubblingHandlersMap.clear(); + _capturingHandlersMap.clear(); + } + + template + void off() { + static_assert(std::is_base_of_v, "incorrect template argument"); + CC_ASSERT(!_emittingEvent); + TargetEventListenerBase *&bubblingHandlers = _bubblingHandlersMap[TgtEvent::TypeID()]; + + EVENT_LIST_LOOP_REV_BEGIN(handle, bubblingHandlers) + if (handle) { + intl::detachFromList(&bubblingHandlers, handle); + delete handle; + } + EVENT_LIST_LOOP_REV_END(handle, bubblingHandlers) + + TargetEventListenerBase *&capturingHandlers = _capturingHandlersMap[TgtEvent::TypeID()]; + EVENT_LIST_LOOP_REV_BEGIN(handle, capturingHandlers) + if (handle) { + intl::detachFromList(&capturingHandlers, handle); + delete handle; + } + EVENT_LIST_LOOP_REV_END(handle, capturingHandlers) + } + + template + void emit(ARGS &&...args) { + // TODO(): statistics + using handler_type = event::TargetEventListener; + using event_type = typename TgtEvent::event_type; + static_assert(sizeof...(ARGS) == TgtEvent::ARG_COUNT, "Parameter count incorrect for function EventTarget::emit"); + event::intl::validateParameters<0, TgtEvent, ARGS...>(std::forward(args)...); + event_type eventObj(std::make_tuple(std::forward(args)...)); + eventObj.target = static_cast(this); + eventObj.currentTarget = static_cast(this); + + emitEvtObj(&eventObj); + } + template + void emitEvtObj(EvtObj *eventObj) { + using event_type = typename TgtEvent::event_type; + using handler_type = event::TargetEventListener; + static_assert(std::is_same_v, "Event type mismatch"); + _emittingEvent++; + if constexpr (useCapture) { + TargetEventListenerBase *&handlers = _capturingHandlersMap[TgtEvent::TypeID()]; + EVENT_LIST_LOOP_BEGIN(handle, handlers) + if (handle && handle->getEventTypeID() == TgtEvent::TypeID() && handle->isEnabled()) { + static_cast(handle)->apply(static_cast(this), eventObj); + } + EVENT_LIST_LOOP_END(handle, handlers); + } else { + TargetEventListenerBase *&handlers = _bubblingHandlersMap[TgtEvent::TypeID()]; + EVENT_LIST_LOOP_BEGIN(handle, handlers) + if (handle && handle->getEventTypeID() == TgtEvent::TypeID() && handle->isEnabled()) { + static_cast(handle)->apply(static_cast(this), eventObj); + } + EVENT_LIST_LOOP_END(handle, handlers); + } + _emittingEvent--; + } + template + std::enable_if_t>, void> + dispatchEvent(EvtType &eventObj) { + if constexpr (Self::HAS_PARENT) { + std::vector parents; + Self *curr = static_cast(this)->Self::evGetParent(); + while (curr) { + if (curr->template hasEventHandler()) { + parents.emplace_back(curr); + } + curr = curr->evGetParent(); + } + for (auto itr = parents.rbegin(); itr != parents.rend(); itr++) { + eventObj.currentTarget = *itr; + (*itr)->template emitEvtObj(&eventObj); + if (eventObj.propagationStopped) { + return; + } + } + } + + eventObj.eventPhase = EventPhaseType::AT_TARGET; + eventObj.currentTarget = static_cast(this); + + emitEvtObj(&eventObj); + if (!eventObj.propagationStopped) { + emitEvtObj(&eventObj); + } + + if constexpr (Self::HAS_PARENT) { + if (!eventObj.propagationStopped && eventObj.bubbles) { + auto *curr = static_cast(this)->Self::evGetParent(); + std::vector parents; + + while (curr) { + if (curr->template hasEventHandler()) { + parents.emplace_back(curr); + } + curr = curr->evGetParent(); + } + for (auto itr = parents.begin(); itr != parents.end(); itr++) { + eventObj.currentTarget = *itr; + (*itr)->template emitEvtObj(&eventObj); + if (eventObj.propagationStopped) { + return; + } + } + } + } + } + + template + std::enable_if_t::head>>), void> + dispatchEvent(ARGS &&...args) { + using handler_type = event::TargetEventListener; + using event_type = typename TgtEvent::event_type; + static_assert(sizeof...(ARGS) == TgtEvent::ARG_COUNT, "Parameter count incorrect for function EventTarget::emit"); + event::intl::validateParameters<0, TgtEvent, ARGS...>(std::forward(args)...); + event_type eventObj(std::make_tuple(std::forward(args)...)); + eventObj.target = static_cast(this); + eventObj.currentTarget = static_cast(this); + eventObj.eventPhase = EventPhaseType::CAPTUREING_PHASE; + dispatchEvent(eventObj); + } + + template + void dispatchEvent() { + using handler_type = event::TargetEventListener; + using event_type = typename TgtEvent::event_type; + static_assert(0 == TgtEvent::ARG_COUNT, "Parameter count incorrect for function EventTarget::emit"); + event_type eventObj; + eventObj.target = static_cast(this); + eventObj.currentTarget = static_cast(this); + eventObj.eventPhase = EventPhaseType::CAPTUREING_PHASE; + dispatchEvent(eventObj); + } + + template + bool hasEventHandler() { + TargetEventListenerBase *&bubblingHandlers = _bubblingHandlersMap[TgtEvent::TypeID()]; + EVENT_LIST_LOOP_BEGIN(handle, bubblingHandlers) + if (handle && handle->isEnabled()) { + return true; + } + EVENT_LIST_LOOP_END(handle, bubblingHandlers); + TargetEventListenerBase *&capturingHandlers = _capturingHandlersMap[TgtEvent::TypeID()]; + EVENT_LIST_LOOP_BEGIN(handle, capturingHandlers) + if (handle && handle->isEnabled()) { + return true; + } + EVENT_LIST_LOOP_END(handle, capturingHandlers); + return false; + } + + template + bool hasEventHandler(Fn func, C *target) { + using wrap_type = event::intl::TgtEvtFnTrait; + using handler_type = event::TargetEventListener; + static_assert(std::is_same::value, "member function type mismatch"); + + TargetEventListenerBase *&bubblingHandlers = _bubblingHandlersMap[TgtEvent::TypeID()]; + EVENT_LIST_LOOP_BEGIN(handle, bubblingHandlers) + if (handle && handle->isEnabled() && handle->getContext() == target) { + auto *ptr = static_cast(handle); + return ptr->getMemberFuncAddr() == func; + } + EVENT_LIST_LOOP_END(handle, bubblingHandlers); + TargetEventListenerBase *&capturingHandlers = _capturingHandlersMap[TgtEvent::TypeID()]; + EVENT_LIST_LOOP_BEGIN(handle, capturingHandlers) + if (handle && handle->isEnabled() && handle->getContext() == target) { + auto *ptr = static_cast(handle); + return ptr->getMemberFuncAddr() == func; + } + EVENT_LIST_LOOP_END(handle, capturingHandlers); + + return false; + } + virtual ~EventTarget() { offAll(); } + +protected: + std::unordered_map _bubblingHandlersMap; + std::unordered_map _capturingHandlersMap; + + target_event_id_type _handlerId{1}; + int _emittingEvent{0}; +}; + +} // namespace event +} // namespace cc + +#define TARGET_EVENT_ARG0(EventType) \ + class EventType final : public cc::event::TgtEventTrait { \ + public: \ + using base_type = cc::event::TgtEventTrait; \ + using event_type = cc::event::Event; \ + using persist_function_type = std::function; \ + using handler_type = std::function; \ + constexpr static const char *EVENT_NAME = #EventType; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#EventType); \ + } \ + }; + +// NOLINTNEXTLINE +#define _DECLARE_TARGET_EVENT_INTER(EventType, ...) \ + class EventType final : public cc::event::TgtEventTrait { \ + public: \ + using base_type = cc::event::TgtEventTrait; \ + using event_type = cc::event::Event; \ + using EventID = cc::event::TargetEventID; \ + using persist_function_type = std::function; \ + using handler_type = std::function; \ + constexpr static const char *EVENT_NAME = #EventType; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#EventType); \ + } \ + }; + +// NOLINTNEXTLINE +#define _IMPL_EVENT_TARGET_(TargetClass) \ + template \ + cc::event::TargetEventID on(Fn &&func, bool useCapture = false) { \ + static_assert(std::is_base_of::value, "mismatch target type"); \ + return EventTarget::template addEventListener(std::forward(func), useCapture, false); \ + } \ + template \ + cc::event::TargetEventID on(Fn &&func, O *ctx, bool useCapture = false) { \ + return EventTarget::template addEventListener(std::forward(func), ctx, useCapture, false); \ + } \ + template \ + cc::event::TargetEventID once(Fn &&func, bool useCapture = false) { \ + static_assert(std::is_base_of::value, "mismatch target type"); \ + return EventTarget::template addEventListener(std::forward(func), useCapture, true); \ + } \ + template \ + cc::event::TargetEventID once(Fn func, O *ctx, bool useCapture = false) { \ + return EventTarget::template addEventListener(std::forward(func), ctx, useCapture, true); \ + } \ + template \ + void off() { \ + static_assert(std::is_base_of::value, "mismatch target type"); \ + EventTarget::template off(); \ + } \ + \ + template \ + bool off(cc::event::TargetEventID eventID) { \ + return EventTarget::off(eventID); \ + } \ + \ + template \ + void emit(ARGS &&...args) { \ + static_assert(std::is_base_of::value, "mismatch target type"); \ + EventTarget::template emit(std::forward(args)...); \ + } \ + template \ + void dispatchEvent(ARGS &&...args) { \ + EventTarget::template dispatchEvent(std::forward(args)...); \ + } + +#define IMPL_EVENT_TARGET(TargetClass) \ +public: \ + static constexpr bool HAS_PARENT = false; \ + _IMPL_EVENT_TARGET_(TargetClass) + +#define IMPL_EVENT_TARGET_WITH_PARENT(TargetClass, getParentMethod) \ +public: \ + static constexpr bool HAS_PARENT = true; \ + TargetClass *evGetParent() { \ + if constexpr (HAS_PARENT) { \ + return getParentMethod(); \ + } else { \ + return nullptr; \ + } \ + } \ + _IMPL_EVENT_TARGET_(TargetClass) + +#define DECLARE_TARGET_EVENT_BEGIN(TargetClass) \ + using EmitterType = TargetClass; + +#define DECLARE_TARGET_EVENT_END() + +#include "intl/EventTargetMacros.h" diff --git a/native/cocos/core/event/EventTypesToJS.cpp b/native/cocos/core/event/EventTypesToJS.cpp deleted file mode 100644 index ae21f2a8f7..0000000000 --- a/native/cocos/core/event/EventTypesToJS.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "core/event/EventTypesToJS.h" - -namespace cc { - -// Internal NodeEventType : 0~99 -// Internal EventTypesToJS : 100~199 -// Internal Game event : 200~299 -// Internal Director Event Type: 300~399 -const CallbacksInvoker::KeyType EventTypesToJS::NODE_REATTACH{104}; //{"NODE_REATTACH"}; -const CallbacksInvoker::KeyType EventTypesToJS::NODE_REMOVE_PERSIST_ROOT_NODE{105}; //{"NODE_REMOVE_PERSIST_ROOT_NODE"}; -const CallbacksInvoker::KeyType EventTypesToJS::NODE_DESTROY_COMPONENTS{106}; //{"NODE_DESTROY_COMPONENTS"}; -const CallbacksInvoker::KeyType EventTypesToJS::NODE_UI_TRANSFORM_DIRTY{107}; //{"NODE_UI_TRANSFORM_DIRTY"}; -const CallbacksInvoker::KeyType EventTypesToJS::NODE_ACTIVE_NODE{108}; //{"NODE_ACTIVE_NODE"}; -const CallbacksInvoker::KeyType EventTypesToJS::NODE_ON_BATCH_CREATED{109}; //{"NODE_ON_BATCH_CREATED"}; - -const CallbacksInvoker::KeyType EventTypesToJS::MODEL_UPDATE_TRANSFORM{110}; //{"MODEL_UPDATE_TRANSFORM"}; -const CallbacksInvoker::KeyType EventTypesToJS::MODEL_UPDATE_UBO{111}; //{"MODEL_UPDATE_UBO"}; -const CallbacksInvoker::KeyType EventTypesToJS::MODEL_UPDATE_LOCAL_DESCRIPTORS{112}; //{"MODEL_UPDATE_LOCAL_DESCRIPTORS"}; -const CallbacksInvoker::KeyType EventTypesToJS::MODEL_UPDATE_LOCAL_SH_DESCRIPTORS{113}; //{"MODEL_UPDATE_LOCAL_SH_DESCRIPTORS"}; -const CallbacksInvoker::KeyType EventTypesToJS::MODEL_UPDATE_WORLD_BOUND_DESCRIPTORS{114}; //{"MODEL_UPDATE_WORLD_BOUND_DESCRIPTORS"}; -const CallbacksInvoker::KeyType EventTypesToJS::MODEL_UPDATE_INSTANCED_ATTRIBUTES{115}; //{"MODEL_UPDATE_INSTANCED_ATTRIBUTES"}; -const CallbacksInvoker::KeyType EventTypesToJS::MODEL_GET_MACRO_PATCHES{116}; //{"MODEL_GET_MACRO_PATCHES"}; - -const CallbacksInvoker::KeyType EventTypesToJS::DIRECTOR_BEFORE_COMMIT{117}; //{"MODEL_GET_MACRO_PATCHES"}; - -const CallbacksInvoker::KeyType EventTypesToJS::SIMPLE_TEXTURE_GFX_TEXTURE_UPDATED{118}; -const CallbacksInvoker::KeyType EventTypesToJS::TEXTURE_BASE_GFX_SAMPLER_UPDATED{119}; - -const CallbacksInvoker::KeyType EventTypesToJS::NODE_SCENE_UPDATED{120}; - -const CallbacksInvoker::KeyType EventTypesToJS::MATERIAL_PASSES_UPDATED{121}; - -const CallbacksInvoker::KeyType EventTypesToJS::NODE_LOCAL_POSITION_UPDATED{122}; -const CallbacksInvoker::KeyType EventTypesToJS::NODE_LOCAL_ROTATION_UPDATED{123}; -const CallbacksInvoker::KeyType EventTypesToJS::NODE_LOCAL_SCALE_UPDATED{124}; -const CallbacksInvoker::KeyType EventTypesToJS::NODE_LOCAL_POSITION_ROTATION_SCALE_UPDATED{125}; - -const CallbacksInvoker::KeyType EventTypesToJS::SIMPLE_TEXTURE_AFTER_ASSIGN_IMAGE{126}; - -const CallbacksInvoker::KeyType EventTypesToJS::NODE_EDITOR_ATTACHED{127}; - -const CallbacksInvoker::KeyType EventTypesToJS::DIRECTOR_BEFORE_RENDER{128}; - -} // namespace cc diff --git a/native/cocos/core/event/EventTypesToJS.h b/native/cocos/core/event/EventTypesToJS.h deleted file mode 100644 index 5485b26849..0000000000 --- a/native/cocos/core/event/EventTypesToJS.h +++ /dev/null @@ -1,66 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#pragma once - -#include "base/std/container/string.h" -#include "core/event/CallbacksInvoker.h" - -namespace cc { - -class EventTypesToJS final { -public: - static const CallbacksInvoker::KeyType NODE_REATTACH; - static const CallbacksInvoker::KeyType NODE_REMOVE_PERSIST_ROOT_NODE; - static const CallbacksInvoker::KeyType NODE_DESTROY_COMPONENTS; - static const CallbacksInvoker::KeyType NODE_UI_TRANSFORM_DIRTY; - static const CallbacksInvoker::KeyType NODE_ACTIVE_NODE; - static const CallbacksInvoker::KeyType NODE_ON_BATCH_CREATED; - static const CallbacksInvoker::KeyType NODE_SCENE_UPDATED; - static const CallbacksInvoker::KeyType NODE_LOCAL_POSITION_UPDATED; - static const CallbacksInvoker::KeyType NODE_LOCAL_ROTATION_UPDATED; - static const CallbacksInvoker::KeyType NODE_LOCAL_SCALE_UPDATED; - static const CallbacksInvoker::KeyType NODE_LOCAL_POSITION_ROTATION_SCALE_UPDATED; - static const CallbacksInvoker::KeyType NODE_EDITOR_ATTACHED; - - static const CallbacksInvoker::KeyType MODEL_UPDATE_TRANSFORM; - static const CallbacksInvoker::KeyType MODEL_UPDATE_UBO; - static const CallbacksInvoker::KeyType MODEL_UPDATE_LOCAL_DESCRIPTORS; - static const CallbacksInvoker::KeyType MODEL_UPDATE_LOCAL_SH_DESCRIPTORS; - static const CallbacksInvoker::KeyType MODEL_UPDATE_WORLD_BOUND_DESCRIPTORS; - static const CallbacksInvoker::KeyType MODEL_UPDATE_INSTANCED_ATTRIBUTES; - static const CallbacksInvoker::KeyType MODEL_GET_MACRO_PATCHES; - - static const CallbacksInvoker::KeyType DIRECTOR_BEFORE_COMMIT; - static const CallbacksInvoker::KeyType DIRECTOR_BEFORE_RENDER; - - static const CallbacksInvoker::KeyType SIMPLE_TEXTURE_GFX_TEXTURE_UPDATED; - static const CallbacksInvoker::KeyType TEXTURE_BASE_GFX_SAMPLER_UPDATED; - - static const CallbacksInvoker::KeyType MATERIAL_PASSES_UPDATED; - static const CallbacksInvoker::KeyType SIMPLE_TEXTURE_AFTER_ASSIGN_IMAGE; -}; - -} // namespace cc diff --git a/native/cocos/core/event/intl/EventBusMacros.h b/native/cocos/core/event/intl/EventBusMacros.h new file mode 100644 index 0000000000..e013de7125 --- /dev/null +++ b/native/cocos/core/event/intl/EventBusMacros.h @@ -0,0 +1,295 @@ +// generated code + +#define DECLARE_BUS_EVENT_ARG0(BusEventClass, EventBusClass) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast() { \ + cc::event::broadcast(); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG1(BusEventClass, EventBusClass, ArgType0) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0) { \ + cc::event::broadcast(arg0); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG2(BusEventClass, EventBusClass, ArgType0, ArgType1) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1) { \ + cc::event::broadcast(arg0, arg1); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG3(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2) { \ + cc::event::broadcast(arg0, arg1, arg2); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG4(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG5(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG6(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4, ArgType5 arg5) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4, arg5); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG7(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4, ArgType5 arg5, ArgType6 arg6) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4, arg5, arg6); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG8(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4, ArgType5 arg5, ArgType6 arg6, ArgType7 arg7) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG9(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4, ArgType5 arg5, ArgType6 arg6, ArgType7 arg7, ArgType8 arg8) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG10(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4, ArgType5 arg5, ArgType6 arg6, ArgType7 arg7, ArgType8 arg8, ArgType9 arg9) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG11(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4, ArgType5 arg5, ArgType6 arg6, ArgType7 arg7, ArgType8 arg8, ArgType9 arg9, ArgType10 arg10) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG12(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4, ArgType5 arg5, ArgType6 arg6, ArgType7 arg7, ArgType8 arg8, ArgType9 arg9, ArgType10 arg10, ArgType11 arg11) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG13(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4, ArgType5 arg5, ArgType6 arg6, ArgType7 arg7, ArgType8 arg8, ArgType9 arg9, ArgType10 arg10, ArgType11 arg11, ArgType12 arg12) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG14(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4, ArgType5 arg5, ArgType6 arg6, ArgType7 arg7, ArgType8 arg8, ArgType9 arg9, ArgType10 arg10, ArgType11 arg11, ArgType12 arg12, ArgType13 arg13) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG15(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4, ArgType5 arg5, ArgType6 arg6, ArgType7 arg7, ArgType8 arg8, ArgType9 arg9, ArgType10 arg10, ArgType11 arg11, ArgType12 arg12, ArgType13 arg13, ArgType14 arg14) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG16(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4, ArgType5 arg5, ArgType6 arg6, ArgType7 arg7, ArgType8 arg8, ArgType9 arg9, ArgType10 arg10, ArgType11 arg11, ArgType12 arg12, ArgType13 arg13, ArgType14 arg14, ArgType15 arg15) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG17(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15, ArgType16) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4, ArgType5 arg5, ArgType6 arg6, ArgType7 arg7, ArgType8 arg8, ArgType9 arg9, ArgType10 arg10, ArgType11 arg11, ArgType12 arg12, ArgType13 arg13, ArgType14 arg14, ArgType15 arg15, ArgType16 arg16) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG18(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15, ArgType16, ArgType17) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4, ArgType5 arg5, ArgType6 arg6, ArgType7 arg7, ArgType8 arg8, ArgType9 arg9, ArgType10 arg10, ArgType11 arg11, ArgType12 arg12, ArgType13 arg13, ArgType14 arg14, ArgType15 arg15, ArgType16 arg16, ArgType17 arg17) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG19(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15, ArgType16, ArgType17, ArgType18) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4, ArgType5 arg5, ArgType6 arg6, ArgType7 arg7, ArgType8 arg8, ArgType9 arg9, ArgType10 arg10, ArgType11 arg11, ArgType12 arg12, ArgType13 arg13, ArgType14 arg14, ArgType15 arg15, ArgType16 arg16, ArgType17 arg17, ArgType18 arg18) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18); \ + } \ + }; + +#define DECLARE_BUS_EVENT_ARG20(BusEventClass, EventBusClass, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15, ArgType16, ArgType17, ArgType18, ArgType19) \ + struct BusEventClass final : cc::event::BusEventTrait { \ + using bus_type = EventBusName_(EventBusClass); \ + using Listener = cc::event::Listener; \ + constexpr static const char *BUS_NAME = EventBusName_(EventBusClass)::BUS_NAME; \ + constexpr static const char *HANDLE_CLASS = #BusEventClass; \ + constexpr static size_t TypeID() { \ + return cc::event::intl::hash(#BusEventClass); \ + } \ + static inline void broadcast(ArgType0 arg0, ArgType1 arg1, ArgType2 arg2, ArgType3 arg3, ArgType4 arg4, ArgType5 arg5, ArgType6 arg6, ArgType7 arg7, ArgType8 arg8, ArgType9 arg9, ArgType10 arg10, ArgType11 arg11, ArgType12 arg12, ArgType13 arg13, ArgType14 arg14, ArgType15 arg15, ArgType16 arg16, ArgType17 arg17, ArgType18 arg18, ArgType19 arg19) { \ + cc::event::broadcast(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19); \ + } \ + }; diff --git a/native/cocos/core/event/intl/EventIntl.h b/native/cocos/core/event/intl/EventIntl.h new file mode 100644 index 0000000000..ee8720eae6 --- /dev/null +++ b/native/cocos/core/event/intl/EventIntl.h @@ -0,0 +1,470 @@ +/**************************************************************************** + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ +#pragma once + +#include +#include +#include +#include +namespace cc { +namespace event { +namespace intl { +template +struct hash_calc { // NOLINT + static constexpr size_t apply(const char (&str)[N]) { + return (hash_calc::apply(str) ^ str[I]) * 16777619U; + }; +}; + +template +struct hash_calc { // NOLINT + static constexpr size_t apply(const char (&/*used*/)[N]) { + return 2166136261U; + }; +}; + +template +constexpr size_t hash(const char (&str)[N]) { + return hash_calc::apply(str); +} + +template +struct HeadType; + +template +struct HeadType { + using head = Head; + using remain = HeadType; +}; + +template +struct HeadType { + using head = Head; + using remain = HeadType<>; +}; + +template <> +struct HeadType<> { + using head = void; + using remain = HeadType<>; +}; + +template +constexpr bool validateParameters() { + return true; +} + +template +constexpr bool validateParameters(Head && /*unused*/) { + using element_t = std::remove_reference_t>; + using head = std::remove_reference_t; + constexpr bool assignable = std::is_assignable_v || std::is_convertible_v; + constexpr bool ret = assignable; + static_assert(ret, "Parameter type incorrect"); + return ret; +} + +template +constexpr bool validateParameters(Head &&head, ARGS &&...remain) { + return validateParameters(std::forward(head)) && validateParameters(std::forward(remain)...); +} + +template +struct TupleExtractor { + using func_type = void(); +}; + +template +struct TupleExtractor> { + using func_type = void(ARGS...); + using std_func_type = std::function; +}; + +template +struct FunctionTrait : public FunctionTrait { + constexpr static bool IS_LAMBDA = true; +}; + +template +struct FunctionTrait { + constexpr static bool IS_LAMBDA = false; + using function_type = R (C::*)(ARGS...); +}; + +template +struct FunctionTrait { + constexpr static bool IS_LAMBDA = false; + using function_type = R (C::*)(ARGS...) const; +}; + +template +struct FunctionTrait { + using function_type = R (*)(ARGS...); + constexpr static bool IS_LAMBDA = false; +}; + +template +struct FunctionTrait { + using function_type = R(ARGS...); + constexpr static bool IS_LAMBDA = false; +}; +template +struct FunctionTrait> { + using function_type = std::function; + constexpr static bool IS_LAMBDA = false; +}; + +template +struct RemoveClass { + using type = T; +}; + +template +struct RemoveClass { + using type = std::function; +}; +template +struct RemoveClass { + using type = std::function; +}; + +template +using function_type_t = typename FunctionTrait::function_type; + +template +using lambda_without_class_t = typename RemoveClass>::type; + +template +inline auto convertLambda(F &&lambda) { + if constexpr (FunctionTrait::IS_LAMBDA) { + return static_cast>(std::forward(lambda)); + } else { + return static_cast>(std::forward(lambda)); + } +} +template +struct TgtEvtFnTrait; + +template +struct TgtEvtFnTrait { + using param0_type = C; + using src_func_type = R(C *, ARGS...); + constexpr static bool IS_MEMBER_FUNC = false; + template + static constexpr bool accept() { + if constexpr (sizeof...(ARGS) == 0) { + using event_type = typename TgtEvent::event_type; + return std::is_same_v; + } else { + return false; + } + } + template + static auto wrap(src_func_type func) { + using event_type = typename TgtEvent::event_type; + using persist_function_type = typename TgtEvent::persist_function_type; + using emitter_type = typename TgtEvent::emitter_type; + persist_function_type ret; + if constexpr (accept()) { + ret = [&func](emitter_type * /*self*/, event_type *event) { + func(event); + }; + } else { + static_assert(std::is_same_v, "mismatch emitter type"); + ret = [func](emitter_type *self, event_type *event) { + return std::apply([self, func](auto &&...args) { func(self, args...); }, event->args); + }; + } + return ret; + } +}; +template +struct TgtEvtFnTrait { + using param0_type = C; + using src_func_type = R(const C *, ARGS...); + constexpr static bool IS_MEMBER_FUNC = false; + template + static constexpr bool accept() { + if constexpr (sizeof...(ARGS) == 0) { + using event_type = typename TgtEvent::event_type; + return std::is_same_v; + } else { + return false; + } + } + template + static auto wrap(src_func_type func) { + using event_type = typename TgtEvent::event_type; + using emitter_type = typename TgtEvent::emitter_type; + using persist_function_type = typename TgtEvent::persist_function_type; + persist_function_type ret; + if constexpr (accept()) { + ret = [func](emitter_type * /*self*/, event_type *event) { + func(event); + }; + } else { + static_assert(std::is_same_v, "mismatch emitter type"); + ret = [func](emitter_type *self, event_type *event) { return std::apply([self, func](auto &&...args) { func(self, args...); }, event->args); }; + } + return ret; + } +}; +template +struct TgtEvtFnTrait { + using param0_type = C; + using src_func_type = R (*)(C *, ARGS...); + constexpr static bool IS_MEMBER_FUNC = false; + template + static constexpr bool accept() { + if constexpr (sizeof...(ARGS) == 0) { + using event_type = typename TgtEvent::event_type; + return std::is_same_v; + } else { + return false; + } + } + template + static auto wrap(src_func_type func) { + using event_type = typename TgtEvent::event_type; + using persist_function_type = typename TgtEvent::persist_function_type; + using emitter_type = typename TgtEvent::emitter_type; + persist_function_type ret; + if constexpr (accept()) { + auto ret2 = [func](emitter_type * /*self*/, event_type *event) { + func(event); + }; + ret = ret2; + } else { + static_assert(std::is_same_v, "mismatch emitter type"); + ret = [func](emitter_type *self, event_type *event) { + return std::apply([self, func](auto &&...args) { func(self, args...); }, event->args); + }; + } + return ret; + } +}; +template +struct TgtEvtFnTrait { + using src_func_type = R (*)(const C *, ARGS...); + using param0_type = C; + constexpr static bool IS_MEMBER_FUNC = false; + template + static constexpr bool accept() { + if constexpr (sizeof...(ARGS) == 0) { + using event_type = typename TgtEvent::event_type; + return std::is_same_v; + } else { + return false; + } + } + template + static auto wrap(src_func_type func) { + using event_type = typename TgtEvent::event_type; + using emitter_type = typename TgtEvent::emitter_type; + using persist_function_type = typename TgtEvent::persist_function_type; + persist_function_type ret; + if constexpr (accept()) { + ret = [&func](emitter_type * /*self*/, event_type *event) { + func(event); + }; + return ret; + } else { + static_assert(std::is_same_v, "mismatch emitter type"); + ret = [func](emitter_type *self, event_type *event) { + return std::apply([self, func](auto &&...args) { func(self, args...); }, event->args); + }; + } + return ret; + } +}; +template +struct TgtEvtFnTrait> { + using src_func_type = std::function; + using param0_type = C; + constexpr static bool IS_MEMBER_FUNC = false; + template + static constexpr bool accept() { + if constexpr (sizeof...(ARGS) == 0) { + using event_type = typename TgtEvent::event_type; + return std::is_same_v; + } else { + return false; + } + } + template + static auto wrap(src_func_type func) { + using event_type = typename TgtEvent::event_type; + using emitter_type = typename TgtEvent::emitter_type; + using persist_function_type = typename TgtEvent::persist_function_type; + persist_function_type ret; + if constexpr (accept()) { + ret = [&func](emitter_type * /*self*/, event_type *event) { + func(event); + }; + } else { + static_assert(std::is_same_v, "mismatch emitter type"); + ret = [func](emitter_type *self, event_type *event) { + return std::apply([self, func](auto &&...args) { func(self, args...); }, event->args); + }; + } + return ret; + } +}; +template +struct TgtEvtFnTrait> { + using param0_type = C; + using src_func_type = std::function; + constexpr static bool IS_MEMBER_FUNC = false; + template + static constexpr bool accept() { + if constexpr (sizeof...(ARGS) == 0) { + using event_type = typename TgtEvent::event_type; + return std::is_same_v; + } else { + return false; + } + } + template + static auto wrap(src_func_type func) { + using event_type = typename TgtEvent::event_type; + using emitter_type = typename TgtEvent::emitter_type; + using persist_function_type = typename TgtEvent::persist_function_type; + persist_function_type ret; + if constexpr (accept()) { + ret = [&func](emitter_type * /*self*/, event_type *event) { + func(event); + }; + } else { + static_assert(std::is_same_v, "mismatch emitter type"); + ret = [func](emitter_type *self, event_type *event) { + return std::apply([self, func](auto &&...args) { func(self, args...); }, event->args); + }; + } + return ret; + } +}; +template +struct TgtEvtFnTrait { + using src_func_type = R (C::*)(ARGS...); + using context_type = C; + using param0_type = typename intl::HeadType::head; + constexpr static bool IS_MEMBER_FUNC = true; + template + static constexpr bool accept() { + if constexpr (sizeof...(ARGS) == 1) { + using event_type = typename TgtEvent::event_type; + return std::is_same_v; + } else { + return false; + } + } + + template + static auto wrap(src_func_type func) { + using event_type = typename TgtEvent::event_type; + using emitter_type = typename TgtEvent::emitter_type; + using persist_function_type = typename TgtEvent::persist_function_type; + persist_function_type ret; + static_assert(std::is_same_v, "mismatch emitter type"); + if constexpr (accept()) { + ret = [&func](emitter_type *self, event_type *event) { + (self->*func)(event); + }; + } else { + ret = [func](emitter_type *self, event_type *event) { + return std::apply([&self, func](auto &&...args) { (self->*func)(args...); }, event->args); + }; + } + return ret; + } + template + static auto wrapWithContext(src_func_type func, context_type *ctx) { + using emitter_type = typename TgtEvent::emitter_type; + using event_type = typename TgtEvent::event_type; + using persist_function_type = typename TgtEvent::persist_function_type; + persist_function_type ret; + if constexpr (accept()) { + ret = [func, ctx](emitter_type * /*self*/, event_type *event) { + (ctx->*func)(event); + }; + } else { + ret = [func, ctx](emitter_type * /*self*/, event_type *event) { + return std::apply([ctx, func](auto... args) { (ctx->*func)(args...); }, event->args); + }; + } + return ret; + } +}; +template +struct TgtEvtFnTrait { + using src_func_type = R (C::*)(ARGS...) const; + using context_type = C; + using param0_type = typename intl::HeadType::head; + constexpr static bool IS_MEMBER_FUNC = true; + + template + static constexpr bool accept() { + if constexpr (sizeof...(ARGS) == 1) { + using event_type = typename TgtEvent::event_type; + return std::is_same_v; + } else { + return false; + } + } + + template + static auto wrap(src_func_type func) { + using event_type = typename TgtEvent::event_type; + using persist_function_type = typename TgtEvent::persist_function_type; + using emitter_type = typename TgtEvent::emitter_type; + persist_function_type ret; + static_assert(std::is_same_v, "mismatch emitter type"); + if constexpr (accept()) { + ret = [&func](context_type *self, event_type *event) { + (self->*func)(event); + }; + } else { + ret = [&func](context_type *self, event_type *event) { + return std::apply([self, func](auto &&...args) { (self->*func)(args...); }, event->args); + }; + } + return ret; + } + + template + static auto wrapWithContext(src_func_type func, context_type *ctx) { + using emitter_type = typename TgtEvent::emitter_type; + using event_type = typename TgtEvent::event_type; + using persist_function_type = typename TgtEvent::persist_function_type; + persist_function_type ret = [func, ctx](emitter_type * /*self*/, event_type *event) { + return std::apply([ctx, func](auto &&...args) { (ctx->*func)(args...); }, event->args); + }; + return ret; + } +}; + +} // namespace intl +} // namespace event +} // namespace cc \ No newline at end of file diff --git a/native/cocos/core/event/intl/EventTargetMacros.h b/native/cocos/core/event/intl/EventTargetMacros.h new file mode 100644 index 0000000000..610ce30639 --- /dev/null +++ b/native/cocos/core/event/intl/EventTargetMacros.h @@ -0,0 +1,64 @@ +// generated code + +#define TARGET_EVENT_ARG1(EventType, ArgType0) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0) + +#define TARGET_EVENT_ARG2(EventType, ArgType0, ArgType1) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1) + +#define TARGET_EVENT_ARG3(EventType, ArgType0, ArgType1, ArgType2) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2) + +#define TARGET_EVENT_ARG4(EventType, ArgType0, ArgType1, ArgType2, ArgType3) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3) + +#define TARGET_EVENT_ARG5(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4) + +#define TARGET_EVENT_ARG6(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5) + +#define TARGET_EVENT_ARG7(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6) + +#define TARGET_EVENT_ARG8(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7) + +#define TARGET_EVENT_ARG9(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8) + +#define TARGET_EVENT_ARG10(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9) + +#define TARGET_EVENT_ARG11(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10) + +#define TARGET_EVENT_ARG12(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11) + +#define TARGET_EVENT_ARG13(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12) + +#define TARGET_EVENT_ARG14(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13) + +#define TARGET_EVENT_ARG15(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14) + +#define TARGET_EVENT_ARG16(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15) + +#define TARGET_EVENT_ARG17(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15, ArgType16) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15, ArgType16) + +#define TARGET_EVENT_ARG18(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15, ArgType16, ArgType17) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15, ArgType16, ArgType17) + +#define TARGET_EVENT_ARG19(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15, ArgType16, ArgType17, ArgType18) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15, ArgType16, ArgType17, ArgType18) + +#define TARGET_EVENT_ARG20(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15, ArgType16, ArgType17, ArgType18, ArgType19) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15, ArgType16, ArgType17, ArgType18, ArgType19) + +#define TARGET_EVENT_ARG21(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15, ArgType16, ArgType17, ArgType18, ArgType19, ArgType20) \ + _DECLARE_TARGET_EVENT_INTER(EventType, ArgType0, ArgType1, ArgType2, ArgType3, ArgType4, ArgType5, ArgType6, ArgType7, ArgType8, ArgType9, ArgType10, ArgType11, ArgType12, ArgType13, ArgType14, ArgType15, ArgType16, ArgType17, ArgType18, ArgType19, ArgType20) diff --git a/native/cocos/core/event/intl/List.h b/native/cocos/core/event/intl/List.h new file mode 100644 index 0000000000..58f0f8afb5 --- /dev/null +++ b/native/cocos/core/event/intl/List.h @@ -0,0 +1,106 @@ +/**************************************************************************** + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + #pragma once + +#include "base/Macros.h" +namespace cc { +namespace event { +namespace intl { + +template +bool listAppend(ListNode **head, ListNode *newNode) { + if (newNode->next != nullptr || newNode->prev != nullptr) { + CC_ASSERT(false); + return false; + } + if (*head == nullptr) { + newNode->next = newNode; + newNode->prev = newNode; + *head = newNode; + } else { + auto *first = *head; + auto *last = (*head)->prev; + newNode->prev = last; + newNode->next = first; + first->prev = newNode; + last->next = newNode; + } + return true; +} + +template +bool detachFromList(ListNode **head, ListNode *node) { + if (*head == nullptr || node->prev == nullptr || node->next == nullptr) { + CC_ASSERT(false); + return false; + } + if (node->prev == node && node->next == node) { // the only node + CC_ASSERT(node == *head); // should be the first + *head = nullptr; + } else { + auto *nextNode = node->next; + auto *prevNode = node->prev; + nextNode->prev = prevNode; + prevNode->next = nextNode; + if (node == *head) { + *head = nextNode; + } + } + node->prev = nullptr; + node->next = nullptr; + return true; +} + +} // namespace intl +} // namespace event +} // namespace cc + +#define EVENT_LIST_LOOP_BEGIN(tempVar, list) \ + if (list) { \ + auto *tempVar = list; \ + do { \ + auto *nextCopy = tempVar->next; + +#define EVENT_LIST_LOOP_END(tempVar, list) \ + tempVar = nextCopy; \ + } \ + while (tempVar != list) \ + ; \ + } + +#define EVENT_LIST_LOOP_REV_BEGIN(tempVar, list) \ + if (list) { \ + auto *tempVar = list->prev; \ + bool isLastListNode = false; \ + do { \ + auto *nextCopy = tempVar->prev; \ + isLastListNode = tempVar == list; + +#define EVENT_LIST_LOOP_REV_END(tempVar, list) \ + tempVar = nextCopy; \ + } \ + while (!isLastListNode) \ + ; \ + } diff --git a/native/cocos/core/scene-graph/Node.cpp b/native/cocos/core/scene-graph/Node.cpp index 5cde1129fd..1859f4ccf8 100644 --- a/native/cocos/core/scene-graph/Node.cpp +++ b/native/cocos/core/scene-graph/Node.cpp @@ -62,11 +62,10 @@ Node::Node(const ccstd::string &name) { } else { _name = name; } - _eventProcessor = ccnew NodeEventProcessor(this); + // _eventProcessor = ccnew NodeEventProcessor(this); } Node::~Node() { - CC_SAFE_DELETE(_eventProcessor); if (!_children.empty()) { // Reset children's _parent to nullptr to avoid dangerous pointer for (const auto &child : _children) { @@ -78,7 +77,7 @@ Node::~Node() { void Node::onBatchCreated(bool dontChildPrefab) { // onBatchCreated was implemented in TS, so code should never go here. CC_ASSERT(false); - emit(EventTypesToJS::NODE_ON_BATCH_CREATED, dontChildPrefab); + emit(dontChildPrefab); } Node *Node::instantiate(Node *cloned, bool isSyncedNode) { @@ -112,7 +111,7 @@ void Node::onHierarchyChangedBase(Node *oldParent) { // NOLINT(misc-unused-param Node *newParent = _parent; auto *scene = dynamic_cast(newParent); if (isPersistNode() && scene == nullptr) { - emit(EventTypesToJS::NODE_REMOVE_PERSIST_ROOT_NODE); + emit(); #if CC_EDITOR debug::warnID(1623); #endif @@ -135,62 +134,7 @@ void Node::onHierarchyChangedBase(Node *oldParent) { // NOLINT(misc-unused-param bool shouldActiveNow = isActive() && !!(newParent && newParent->isActiveInHierarchy()); if (isActiveInHierarchy() != shouldActiveNow) { // Director::getInstance()->getNodeActivator()->activateNode(this, shouldActiveNow); // TODO(xwx): use TS temporarily - emit(EventTypesToJS::NODE_ACTIVE_NODE, shouldActiveNow); - } -} - -void Node::off(const CallbacksInvoker::KeyType &type, bool useCapture) { - _eventProcessor->offAll(type, useCapture); - bool hasListeners = _eventProcessor->hasEventListener(type); - if (!hasListeners) { - if (type == NodeEventType::TRANSFORM_CHANGED) { - _eventMask &= ~TRANSFORM_ON; - } - } -} - -void Node::off(const CallbacksInvoker::KeyType &type, const CallbackID &cbID, bool useCapture) { - _eventProcessor->off(type, cbID, useCapture); - bool hasListeners = _eventProcessor->hasEventListener(type); - if (!hasListeners) { - if (type == NodeEventType::TRANSFORM_CHANGED) { - _eventMask &= ~TRANSFORM_ON; - } - } -} - -void Node::off(const CallbacksInvoker::KeyType &type, void *target, bool useCapture) { - _eventProcessor->off(type, target, useCapture); - bool hasListeners = _eventProcessor->hasEventListener(type); - if (!hasListeners) { - if (type == NodeEventType::TRANSFORM_CHANGED) { - _eventMask &= ~TRANSFORM_ON; - } - } -} - -//void Node::dispatchEvent(event::Event *eve) { -// _eventProcessor->dispatchEvent(eve); -//} - -bool Node::hasEventListener(const CallbacksInvoker::KeyType &type) const { - return _eventProcessor->hasEventListener(type); -} - -bool Node::hasEventListener(const CallbacksInvoker::KeyType &type, const CallbackID &cbID) const { - return _eventProcessor->hasEventListener(type, cbID); -} -bool Node::hasEventListener(const CallbacksInvoker::KeyType &type, void *target) const { - return _eventProcessor->hasEventListener(type, target); -} -bool Node::hasEventListener(const CallbacksInvoker::KeyType &type, void *target, const CallbackID &cbID) const { - return _eventProcessor->hasEventListener(type, target, cbID); -} - -void Node::targetOff(const CallbacksInvoker::KeyType &type) { - _eventProcessor->targetOff(type); - if ((_eventMask & TRANSFORM_ON) && !_eventProcessor->hasEventListener(NodeEventType::TRANSFORM_CHANGED)) { - _eventMask &= ~TRANSFORM_ON; + emit(shouldActiveNow); } } @@ -203,7 +147,7 @@ void Node::setActive(bool isActive) { bool couldActiveInScene = parent->isActiveInHierarchy(); if (couldActiveInScene) { // Director::getInstance()->getNodeActivator()->activateNode(this, isActive); // TODO(xwx): use TS temporarily - emit(EventTypesToJS::NODE_ACTIVE_NODE, isActive); + emit(isActive); } } } @@ -228,7 +172,7 @@ void Node::setParent(Node *parent, bool isKeepWorld /* = false */) { _parent = newParent; _siblingIndex = 0; onSetParent(oldParent, isKeepWorld); - emit(NodeEventType::PARENT_CHANGED, oldParent); + emit(oldParent); if (oldParent) { if (!(oldParent->_objFlags & Flags::DESTROYING)) { index_t removeAt = getIdxOfChild(oldParent->_children, this); @@ -242,7 +186,7 @@ void Node::setParent(Node *parent, bool isKeepWorld /* = false */) { } oldParent->_children.erase(oldParent->_children.begin() + removeAt); oldParent->updateSiblingIndex(); - oldParent->emit(NodeEventType::CHILD_REMOVED, this); + oldParent->emit(this); } } if (newParent) { @@ -253,7 +197,7 @@ void Node::setParent(Node *parent, bool isKeepWorld /* = false */) { #endif newParent->_children.emplace_back(this); _siblingIndex = static_cast(newParent->_children.size() - 1); - newParent->emit(NodeEventType::CHILD_ADDED, this); + newParent->emit(this); } onHierarchyChanged(oldParent); } @@ -262,7 +206,7 @@ void Node::walk(const WalkCallback &preFunc) { walk(preFunc, nullptr); } -void Node::walk(const WalkCallback &preFunc, const WalkCallback &postFunc) { //NOLINT(misc-no-recursion) +void Node::walk(const WalkCallback &preFunc, const WalkCallback &postFunc) { // NOLINT(misc-no-recursion) if (preFunc) { preFunc(this); } @@ -278,23 +222,23 @@ void Node::walk(const WalkCallback &preFunc, const WalkCallback &postFunc) { //N } } -//Component *Node::addComponent(Component *comp) { -// comp->_node = this; // cjh TODO: shared_ptr -// _components.emplace_back(comp); +// Component *Node::addComponent(Component *comp) { +// comp->_node = this; // cjh TODO: shared_ptr +// _components.emplace_back(comp); // -// if (isActiveInHierarchy()) { -// NodeActivator::activateComp(comp); -// } +// if (isActiveInHierarchy()) { +// NodeActivator::activateComp(comp); +// } // -// return comp; -//} +// return comp; +// } // -//void Node::removeComponent(Component *comp) { -// auto iteComp = std::find(_components.begin(), _components.end(), comp); -// if (iteComp != _components.end()) { -// _components.erase(iteComp); -// } -//} +// void Node::removeComponent(Component *comp) { +// auto iteComp = std::find(_components.begin(), _components.end(), comp); +// if (iteComp != _components.end()) { +// _components.erase(iteComp); +// } +// } bool Node::onPreDestroyBase() { Flags destroyingFlag = Flags::DESTROYING; @@ -306,31 +250,31 @@ bool Node::onPreDestroyBase() { } #endif if (isPersistNode()) { - emit(EventTypesToJS::NODE_REMOVE_PERSIST_ROOT_NODE); + emit(); } if (!destroyByParent) { if (_parent) { - emit(NodeEventType::PARENT_CHANGED, this); + emit(this); index_t childIdx = getIdxOfChild(_parent->_children, this); if (childIdx != -1) { _parent->_children.erase(_parent->_children.begin() + childIdx); } _siblingIndex = 0; _parent->updateSiblingIndex(); - _parent->emit(NodeEventType::CHILD_REMOVED, this); + _parent->emit(this); } } - //NOTE: The following code is not needed now since we override Node._onPreDestroy in node.jsb.ts - // and the logic will be done in TS. - // emit(NodeEventType::NODE_DESTROYED, this); - // for (const auto &child : _children) { - // child->destroyImmediate(); - // } + // NOTE: The following code is not needed now since we override Node._onPreDestroy in node.jsb.ts + // and the logic will be done in TS. + // emit(NodeEventType::NODE_DESTROYED, this); + // for (const auto &child : _children) { + // child->destroyImmediate(); + // } // - // emit(EventTypesToJS::NODE_DESTROY_COMPONENTS); + // emit(EventTypesToJS::NODE_DESTROY_COMPONENTS); - _eventProcessor->destroy(); + offAll(); return destroyByParent; } @@ -356,7 +300,7 @@ void Node::updateScene() { return; } _scene = _parent->_scene; - emit(EventTypesToJS::NODE_SCENE_UPDATED, _scene); + emit(_scene); } /* static */ @@ -458,7 +402,7 @@ void Node::setPositionInternal(float x, float y, float z, bool calledFromJS) { invalidateChildren(TransformBit::POSITION); if (_eventMask & TRANSFORM_ON) { - emit(NodeEventType::TRANSFORM_CHANGED, TransformBit::POSITION); + emit(TransformBit::POSITION); } if (!calledFromJS) { @@ -473,7 +417,7 @@ void Node::setRotationInternal(float x, float y, float z, float w, bool calledFr invalidateChildren(TransformBit::ROTATION); if (_eventMask & TRANSFORM_ON) { - emit(NodeEventType::TRANSFORM_CHANGED, TransformBit::ROTATION); + emit(TransformBit::ROTATION); } if (!calledFromJS) { @@ -487,7 +431,7 @@ void Node::setRotationFromEuler(float x, float y, float z) { _eulerDirty = false; invalidateChildren(TransformBit::ROTATION); if (_eventMask & TRANSFORM_ON) { - emit(NodeEventType::TRANSFORM_CHANGED, TransformBit::ROTATION); + emit(TransformBit::ROTATION); } notifyLocalRotationUpdated(); @@ -498,19 +442,19 @@ void Node::setScaleInternal(float x, float y, float z, bool calledFromJS) { invalidateChildren(TransformBit::SCALE); if (_eventMask & TRANSFORM_ON) { - emit(NodeEventType::TRANSFORM_CHANGED, TransformBit::SCALE); + emit(TransformBit::SCALE); } if (!calledFromJS) { notifyLocalScaleUpdated(); } } -void Node::updateWorldTransform() { //NOLINT(misc-no-recursion) +void Node::updateWorldTransform() { // NOLINT(misc-no-recursion) uint32_t dirtyBits = 0; updateWorldTransformRecursive(dirtyBits); } -void Node::updateWorldTransformRecursive(uint32_t &dirtyBits) { //NOLINT(misc-no-recursion) +void Node::updateWorldTransformRecursive(uint32_t &dirtyBits) { // NOLINT(misc-no-recursion) const uint32_t currDirtyBits = getDirtyFlag(); if (!currDirtyBits) { return; @@ -561,7 +505,7 @@ void Node::updateWorldTransformRecursive(uint32_t &dirtyBits) { //NOLINT(misc-no setDirtyFlag(static_cast(TransformBit::NONE)); } -const Mat4 &Node::getWorldMatrix() const { //NOLINT(misc-no-recursion) +const Mat4 &Node::getWorldMatrix() const { // NOLINT(misc-no-recursion) const_cast(this)->updateWorldTransform(); return _worldMatrix; } @@ -580,14 +524,14 @@ Mat4 Node::getWorldRT() { return target; } -void Node::invalidateChildren(TransformBit dirtyBit) { //NOLINT(misc-no-recursion) +void Node::invalidateChildren(TransformBit dirtyBit) { // NOLINT(misc-no-recursion) auto curDirtyBit{static_cast(dirtyBit)}; const uint32_t hasChangedFlags = getChangedFlags(); const uint32_t dirtyFlags = getDirtyFlag(); if (isValid() && (dirtyFlags & hasChangedFlags & curDirtyBit) != curDirtyBit) { setDirtyFlag(dirtyFlags | curDirtyBit); setChangedFlags(hasChangedFlags | curDirtyBit); - emit(NodeEventType::ANCESTOR_TRANSFORM_CHANGED, dirtyBit); + emit(dirtyBit); for (Node *child : getChildren()) { child->invalidateChildren(dirtyBit | TransformBit::POSITION); @@ -610,7 +554,8 @@ void Node::setWorldPosition(float x, float y, float z) { invalidateChildren(TransformBit::POSITION); if (_eventMask & TRANSFORM_ON) { - emit(NodeEventType::TRANSFORM_CHANGED, TransformBit::POSITION); + emit(TransformBit::POSITION); + } } @@ -634,13 +579,13 @@ void Node::setWorldRotation(float x, float y, float z, float w) { invalidateChildren(TransformBit::ROTATION); if (_eventMask & TRANSFORM_ON) { - emit(NodeEventType::TRANSFORM_CHANGED, TransformBit::ROTATION); + emit(TransformBit::ROTATION); } notifyLocalRotationUpdated(); } -const Quaternion &Node::getWorldRotation() const { //NOLINT(misc-no-recursion) +const Quaternion &Node::getWorldRotation() const { // NOLINT(misc-no-recursion) const_cast(this)->updateWorldTransform(); return _worldRotation; } @@ -672,7 +617,7 @@ void Node::setWorldScale(float x, float y, float z) { invalidateChildren(TransformBit::SCALE); if (_eventMask & TRANSFORM_ON) { - emit(NodeEventType::TRANSFORM_CHANGED, TransformBit::SCALE); + emit(TransformBit::SCALE); } } @@ -695,7 +640,7 @@ void Node::setAngle(float val) { _eulerDirty = false; invalidateChildren(TransformBit::ROTATION); if (_eventMask & TRANSFORM_ON) { - emit(NodeEventType::TRANSFORM_CHANGED, TransformBit::ROTATION); + emit(TransformBit::ROTATION); } notifyLocalRotationUpdated(); @@ -747,7 +692,7 @@ void Node::rotate(const Quaternion &rot, NodeSpace ns /* = NodeSpace::LOCAL*/, b _eulerDirty = true; invalidateChildren(TransformBit::ROTATION); if (_eventMask & TRANSFORM_ON) { - emit(NodeEventType::TRANSFORM_CHANGED, TransformBit::ROTATION); + emit(TransformBit::ROTATION); } if (!calledFromJS) { @@ -764,13 +709,13 @@ void Node::lookAt(const Vec3 &pos, const Vec3 &up) { setWorldRotation(qTemp); } -Vec3 Node::inverseTransformPoint(const Vec3 &p) { //NOLINT(misc-no-recursion) +Vec3 Node::inverseTransformPoint(const Vec3 &p) { // NOLINT(misc-no-recursion) Vec3 out(p); inverseTransformPointRecursive(out); return out; } -void Node::inverseTransformPointRecursive(Vec3 &out) const { //NOLINT(misc-no-recursion) +void Node::inverseTransformPointRecursive(Vec3 &out) const { // NOLINT(misc-no-recursion) auto *parent = getParent(); if (!parent) { return; @@ -786,7 +731,7 @@ void Node::setMatrix(const Mat4 &val) { invalidateChildren(TransformBit::TRS); _eulerDirty = true; if (_eventMask & TRANSFORM_ON) { - emit(NodeEventType::TRANSFORM_CHANGED, TransformBit::TRS); + emit(TransformBit::TRS); } } @@ -802,7 +747,7 @@ void Node::setWorldRotationFromEuler(float x, float y, float z) { invalidateChildren(TransformBit::ROTATION); if (_eventMask & TRANSFORM_ON) { - emit(NodeEventType::TRANSFORM_CHANGED, TransformBit::ROTATION); + emit(TransformBit::ROTATION); } notifyLocalRotationUpdated(); @@ -831,7 +776,7 @@ void Node::setRTSInternal(Quaternion *rot, Vec3 *pos, Vec3 *scale, bool calledFr if (dirtyBit) { invalidateChildren(static_cast(dirtyBit)); if (_eventMask & TRANSFORM_ON) { - emit(NodeEventType::TRANSFORM_CHANGED, dirtyBit); + emit(static_cast(dirtyBit)); } } } @@ -885,7 +830,7 @@ void Node::translate(const Vec3 &trans, NodeSpace ns) { invalidateChildren(TransformBit::POSITION); if (_eventMask & TRANSFORM_ON) { - emit(NodeEventType::TRANSFORM_CHANGED, TransformBit::POSITION); + emit(TransformBit::POSITION); } } @@ -896,15 +841,14 @@ bool Node::onPreDestroy() { } void Node::onHierarchyChanged(Node *oldParent) { - emit(EventTypesToJS::NODE_REATTACH); - _eventProcessor->reattach(); + emit(); onHierarchyChangedBase(oldParent); } /* static */ -//Node *Node::find(const ccstd::string &path, Node *referenceNode /* = nullptr*/) { -// return cc::find(path, referenceNode); -//} +// Node *Node::find(const ccstd::string &path, Node *referenceNode /* = nullptr*/) { +// return cc::find(path, referenceNode); +// } // For deserialization // void Node::_setChild(index_t i, Node *child) { diff --git a/native/cocos/core/scene-graph/Node.h b/native/cocos/core/scene-graph/Node.h index dda15d5b45..58df086bbf 100644 --- a/native/cocos/core/scene-graph/Node.h +++ b/native/cocos/core/scene-graph/Node.h @@ -31,12 +31,9 @@ //#include "core/components/Component.h" //#include "core/event/Event.h" #include "core/data/Object.h" -#include "core/event/EventTypesToJS.h" +#include "core/event/EventTarget.h" #include "core/scene-graph/Layers.h" #include "core/scene-graph/NodeEnum.h" -#include "core/scene-graph/NodeEvent.h" -#include "core/scene-graph/NodeEventProcessor.h" - #include "math/Mat3.h" #include "math/Mat4.h" #include "math/Quaternion.h" @@ -46,18 +43,57 @@ namespace cc { class Scene; -class NodeEventProcessor; - /** * Event types emitted by Node */ -using EventType = NodeEventType; /** * Bit masks for Node transformation parts */ using TransformDirtyBit = TransformBit; -class Node : public CCObject { +class Node : public CCObject, public event::EventTarget { + IMPL_EVENT_TARGET_WITH_PARENT(Node, getParent) + DECLARE_TARGET_EVENT_BEGIN(Node) + TARGET_EVENT_ARG0(TouchStart) + TARGET_EVENT_ARG0(TouchMove) + TARGET_EVENT_ARG0(TouchEnd) + TARGET_EVENT_ARG0(TouchCancel) + TARGET_EVENT_ARG0(MouseDown) + TARGET_EVENT_ARG0(MouseMove) + TARGET_EVENT_ARG0(MouseUp) + TARGET_EVENT_ARG0(MouseWheel) + TARGET_EVENT_ARG0(MouseEnter) + TARGET_EVENT_ARG0(MouseLeave) + TARGET_EVENT_ARG0(KeyDown) + TARGET_EVENT_ARG0(KeyUp) + TARGET_EVENT_ARG0(DeviceMotion) + TARGET_EVENT_ARG1(TransformChanged, TransformBit) + TARGET_EVENT_ARG0(SceneChangedForPersist) + TARGET_EVENT_ARG0(SizeChanged) + TARGET_EVENT_ARG0(AnchorChanged) + TARGET_EVENT_ARG0(ColorChanged) + TARGET_EVENT_ARG1(ChildAdded, Node *) + TARGET_EVENT_ARG1(ChildRemoved, Node *) + TARGET_EVENT_ARG1(ParentChanged, Node *) + TARGET_EVENT_ARG0(NodeDestroyed) + TARGET_EVENT_ARG1(LayerChanged, uint32_t) + TARGET_EVENT_ARG0(SiblingOrderChanged) + TARGET_EVENT_ARG0(ActiveInHierarchyChanged) + TARGET_EVENT_ARG0(MobilityChanged) + TARGET_EVENT_ARG1(AncestorTransformChanged, TransformBit) + TARGET_EVENT_ARG0(Reattach) + TARGET_EVENT_ARG0(RemovePersistRootNode) + TARGET_EVENT_ARG0(DestroyComponents) + TARGET_EVENT_ARG0(UITransformDirty) + TARGET_EVENT_ARG1(ActiveNode, bool) + TARGET_EVENT_ARG1(BatchCreated, bool) + TARGET_EVENT_ARG1(SceneUpdated, cc::Scene *) + TARGET_EVENT_ARG3(LocalPositionUpdated, float, float, float) + TARGET_EVENT_ARG4(LocalRotationUpdated, float, float, float, float) + TARGET_EVENT_ARG3(LocalScaleUpdated, float, float, float) + TARGET_EVENT_ARG10(LocalRTSUpdated, float, float, float, float, float, float, float, float, float, float) + TARGET_EVENT_ARG1(EditorAttached, bool) + DECLARE_TARGET_EVENT_END() public: class UserData : public RefCounted { public: @@ -110,97 +146,6 @@ public: void walk(const WalkCallback &preFunc); void walk(const WalkCallback &preFunc, const WalkCallback &postFunc); - //NOTE: swig could not parse template function in a class. - // It will trigger an error: cocos/core/scene-graph/Node.h:115: Error: Syntax error in input(3). - // Therefore, hide them in swig environment. -#ifndef SWIGCOCOS - template - void on(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture = false); - - template - void on(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture = false); - - template - void on(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture = false); - - template - std::enable_if_t::value, void> - on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool useCapture = false); - - template - std::enable_if_t::value, void> - on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool useCapture = false); - - template - void on(const CallbacksInvoker::KeyType &type, std::function &&callback, bool useCapture = false); - - template - void on(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, bool useCapture = false); - - template - std::enable_if_t::value, void> - on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, bool useCapture = false); - - template - std::enable_if_t::value, void> - on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, bool useCapture = false); - - template - void once(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture = false); - - template - void once(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture = false); - - template - void once(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture = false); - - template - std::enable_if_t::value, void> - once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool useCapture = false); - - template - std::enable_if_t::value, void> - once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool useCapture = false); - - template - void once(const CallbacksInvoker::KeyType &type, std::function &&callback, bool useCapture = false); - - template - void once(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, bool useCapture = false); - - template - std::enable_if_t::value, void> - once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, bool useCapture = false); - - template - std::enable_if_t::value, void> - once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, bool useCapture = false); - - void off(const CallbacksInvoker::KeyType &type, bool useCapture = false); - - void off(const CallbacksInvoker::KeyType &type, const CallbackID &cbID, bool useCapture = false); - - void off(const CallbacksInvoker::KeyType &type, void *target, bool useCapture = false); - - template - void off(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture = false); - - template - void emit(const CallbacksInvoker::KeyType &type, Args &&...args); - - // void dispatchEvent(event::Event *event); - bool hasEventListener(const CallbacksInvoker::KeyType &type) const; - bool hasEventListener(const CallbacksInvoker::KeyType &type, const CallbackID &cbID) const; - bool hasEventListener(const CallbacksInvoker::KeyType &type, void *target) const; - bool hasEventListener(const CallbacksInvoker::KeyType &type, void *target, const CallbackID &cbID) const; - - template - bool hasEventListener(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target) const; - - void targetOff(const CallbacksInvoker::KeyType &type); - -#endif // SWIGCOCOS - bool destroy() override { if (CCObject::destroy()) { setActive(false); @@ -220,7 +165,7 @@ public: for (const auto &child : _children) { child->_siblingIndex = i++; } - emit(NodeEventType::SIBLING_ORDER_CHANGED); + emit(); } inline void addChild(Node *node) { node->setParent(this); } @@ -265,7 +210,7 @@ public: inline const ccstd::vector> &getChildren() const { return _children; } inline Node *getParent() const { return _parent; } - inline NodeEventProcessor *getEventProcessor() const { return _eventProcessor; } + // inline NodeEventProcessor *getEventProcessor() const { return _eventProcessor; } Node *getChildByUuid(const ccstd::string &uuid) const; Node *getChildByName(const ccstd::string &name) const; @@ -510,7 +455,7 @@ public: inline void setMobility(MobilityMode m) { _mobility = m; - emit(NodeEventType::MOBILITY_CHANGED); + emit(); } /** @@ -529,7 +474,7 @@ public: inline uint32_t getDirtyFlag() const { return _dirtyFlag; } inline void setLayer(uint32_t layer) { _layer = layer; - emit(NodeEventType::LAYER_CHANGED, layer); + emit(layer); } inline uint32_t getLayer() const { return _layer; } @@ -655,27 +600,27 @@ private: void updateWorldTransformRecursive(uint32_t &superDirtyBits); inline void notifyLocalPositionUpdated() { - emit(EventTypesToJS::NODE_LOCAL_POSITION_UPDATED, _localPosition.x, _localPosition.y, _localPosition.z); + emit(_localPosition.x, _localPosition.y, _localPosition.z); } inline void notifyLocalRotationUpdated() { - emit(EventTypesToJS::NODE_LOCAL_ROTATION_UPDATED, _localRotation.x, _localRotation.y, _localRotation.z, _localRotation.w); + emit(_localRotation.x, _localRotation.y, _localRotation.z, _localRotation.w); } inline void notifyLocalScaleUpdated() { - emit(EventTypesToJS::NODE_LOCAL_SCALE_UPDATED, _localScale.x, _localScale.y, _localScale.z); + emit(_localScale.x, _localScale.y, _localScale.z); } inline void notifyLocalPositionRotationScaleUpdated() { - emit(EventTypesToJS::NODE_LOCAL_POSITION_ROTATION_SCALE_UPDATED, - _localPosition.x, _localPosition.y, _localPosition.z, - _localRotation.x, _localRotation.y, _localRotation.z, _localRotation.w, - _localScale.x, _localScale.y, _localScale.z); + emit( + _localPosition.x, _localPosition.y, _localPosition.z, + _localRotation.x, _localRotation.y, _localRotation.z, _localRotation.w, + _localScale.x, _localScale.y, _localScale.z); } #if CC_EDITOR inline void notifyEditorAttached(bool attached) { - emit(EventTypesToJS::NODE_EDITOR_ATTACHED, attached); + emit(attached); } #endif @@ -686,7 +631,6 @@ private: static uint32_t clearRound; Scene *_scene{nullptr}; - NodeEventProcessor *_eventProcessor{nullptr}; IntrusivePtr _userData; ccstd::vector> _children; @@ -731,149 +675,4 @@ template bool Node::isNode(T *obj) { return dynamic_cast(obj) != nullptr && dynamic_cast(obj) == nullptr; } - -#ifndef SWIGCOCOS - -template -void Node::emit(const CallbacksInvoker::KeyType &type, Args &&...args) { - _eventProcessor->emit(type, std::forward(args)...); -} - -template -void Node::on(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture) { - if (type == NodeEventType::TRANSFORM_CHANGED) { - _eventMask |= TRANSFORM_ON; - } - _eventProcessor->on(type, memberFn, target, useCapture); -} - -template -void Node::on(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture) { - if (type == NodeEventType::TRANSFORM_CHANGED) { - _eventMask |= TRANSFORM_ON; - } - _eventProcessor->on(type, std::forward>(callback), cbID, useCapture); -} - -template -void Node::on(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture) { - if (type == NodeEventType::TRANSFORM_CHANGED) { - _eventMask |= TRANSFORM_ON; - } - _eventProcessor->on(type, std::forward>(callback), target, cbID, useCapture); -} - -template -std::enable_if_t::value, void> -Node::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool useCapture) { - if (type == NodeEventType::TRANSFORM_CHANGED) { - _eventMask |= TRANSFORM_ON; - } - _eventProcessor->on(type, callback, target, cbID, useCapture); -} - -template -std::enable_if_t::value, void> -Node::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool useCapture) { - if (type == NodeEventType::TRANSFORM_CHANGED) { - _eventMask |= TRANSFORM_ON; - } - _eventProcessor->on(type, callback, cbID, useCapture); -} - -template -void Node::on(const CallbacksInvoker::KeyType &type, std::function &&callback, bool useCapture) { - CallbackID unusedID{0}; - on(type, callback, unusedID, useCapture); -} - -template -void Node::on(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, bool useCapture) { - CallbackID unusedID{0}; - on(type, callback, target, unusedID, useCapture); -} - -template -std::enable_if_t::value, void> -Node::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, bool useCapture) { - CallbackID unusedID{0}; - on(type, callback, target, unusedID, useCapture); -} - -template -std::enable_if_t::value, void> -Node::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, bool useCapture) { - CallbackID unusedID{0}; - on(type, callback, unusedID, useCapture); -} -template -void Node::once(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture) { - _eventProcessor->once(type, memberFn, target, useCapture); -} -template -void Node::once(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture) { - _eventProcessor->once(type, callback, cbID, useCapture); -} - -template -void Node::once(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture) { - _eventProcessor->once(type, std::forward>(callback), target, cbID, useCapture); -} - -template -std::enable_if_t::value, void> -Node::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool useCapture) { - _eventProcessor->once(type, callback, cbID, useCapture); -} - -template -std::enable_if_t::value, void> -Node::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool useCapture) { - _eventProcessor->once(type, callback, target, cbID, useCapture); -} - -template -void Node::once(const CallbacksInvoker::KeyType &type, std::function &&callback, bool useCapture) { - CallbackID unusedID{0}; - once(type, callback, unusedID, useCapture); -} - -template -void Node::once(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, bool useCapture) { - CallbackID unusedID{0}; - once(type, callback, target, unusedID, useCapture); -} - -template -std::enable_if_t::value, void> -Node::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, bool useCapture) { - CallbackID unusedID{0}; - once(type, callback, unusedID, useCapture); -} - -template -std::enable_if_t::value, void> -Node::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, bool useCapture) { - CallbackID unusedID{0}; - once(type, callback, target, unusedID, useCapture); -} - -template -void Node::off(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture) { - _eventProcessor->off(type, memberFn, target, useCapture); - bool hasListeners = _eventProcessor->hasEventListener(type); - if (!hasListeners) { - if (type == NodeEventType::TRANSFORM_CHANGED) { - _eventMask &= ~TRANSFORM_ON; - } - } -} - -template -bool Node::hasEventListener(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target) const { - return _eventProcessor->hasEventListener(type, memberFn, target); -} - -#endif // SWIGCOCOS - } // namespace cc diff --git a/native/cocos/core/scene-graph/NodeEvent.cpp b/native/cocos/core/scene-graph/NodeEvent.cpp deleted file mode 100644 index 3d68c15d54..0000000000 --- a/native/cocos/core/scene-graph/NodeEvent.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "core/scene-graph/NodeEvent.h" - -namespace cc { - -// Internal NodeEventType : 0~99 -// Internal EventTypesToJS : 100~199 -// Internal Game event : 200~299 -// Internal Director Event Type: 300~399 -const CallbacksInvoker::KeyType NodeEventType::TOUCH_START{0}; //{"touch-start"}; -const CallbacksInvoker::KeyType NodeEventType::TOUCH_MOVE{1}; //{"touch-move"}; -const CallbacksInvoker::KeyType NodeEventType::TOUCH_END{2}; //{"touch-end"}; -const CallbacksInvoker::KeyType NodeEventType::TOUCH_CANCEL{3}; //{"touch-cancel"}; -const CallbacksInvoker::KeyType NodeEventType::MOUSE_DOWN{4}; //{"mouse-down"}; -const CallbacksInvoker::KeyType NodeEventType::MOUSE_MOVE{5}; //{"mouse-move"}; -const CallbacksInvoker::KeyType NodeEventType::MOUSE_UP{6}; //{"mouse-up"}; -const CallbacksInvoker::KeyType NodeEventType::MOUSE_WHEEL{7}; //{"mouse-wheel"}; -const CallbacksInvoker::KeyType NodeEventType::MOUSE_ENTER{8}; //{"mouse-enter"}; -const CallbacksInvoker::KeyType NodeEventType::MOUSE_LEAVE{9}; //{"mouse-leave"}; -const CallbacksInvoker::KeyType NodeEventType::KEY_DOWN{10}; //{"keydown"}; -const CallbacksInvoker::KeyType NodeEventType::KEY_UP{11}; //{"keyup"}; -const CallbacksInvoker::KeyType NodeEventType::DEVICEMOTION{12}; //{"devicemotion"}; -const CallbacksInvoker::KeyType NodeEventType::TRANSFORM_CHANGED{13}; //{"transform-changed"}; -const CallbacksInvoker::KeyType NodeEventType::ANCESTOR_TRANSFORM_CHANGED{14}; //{"ancestor-transform-changed"}; -const CallbacksInvoker::KeyType NodeEventType::MOBILITY_CHANGED{15}; //{"mobility-changed"}; -const CallbacksInvoker::KeyType NodeEventType::SCENE_CHANGED_FOR_PERSISTS{16}; //{"scene-changed-for-persists"}; -const CallbacksInvoker::KeyType NodeEventType::SIZE_CHANGED{17}; //{"size-changed"}; -const CallbacksInvoker::KeyType NodeEventType::ANCHOR_CHANGED{18}; //{"anchor-changed"}; -const CallbacksInvoker::KeyType NodeEventType::COLOR_CHANGED{19}; //{"color-changed"}; -const CallbacksInvoker::KeyType NodeEventType::CHILD_ADDED{20}; //{"child-added"}; -const CallbacksInvoker::KeyType NodeEventType::CHILD_REMOVED{21}; //{"child-removed"}; -const CallbacksInvoker::KeyType NodeEventType::PARENT_CHANGED{22}; //{"parent-changed"}; -const CallbacksInvoker::KeyType NodeEventType::NODE_DESTROYED{23}; //{"node-destroyed"}; -const CallbacksInvoker::KeyType NodeEventType::LAYER_CHANGED{24}; //{"layer-changed"}; -const CallbacksInvoker::KeyType NodeEventType::SIBLING_ORDER_CHANGED{25}; //{"sibling-order-changed"}; -const CallbacksInvoker::KeyType NodeEventType::ACTIVE_IN_HIERARCHY_CHANGED{26}; //{"active-in-hierarchy-changed"}; -const CallbacksInvoker::KeyType NodeEventType::LIGHT_PROBE_CHANGED{27}; //{"light-probe-changed"}; - -} // namespace cc diff --git a/native/cocos/core/scene-graph/NodeEvent.h b/native/cocos/core/scene-graph/NodeEvent.h deleted file mode 100644 index 2fc0bbc3c1..0000000000 --- a/native/cocos/core/scene-graph/NodeEvent.h +++ /dev/null @@ -1,64 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#pragma once -#include "base/std/container/string.h" -#include "core/event/CallbacksInvoker.h" - -namespace cc { - -class NodeEventType { -public: - static const CallbacksInvoker::KeyType TOUCH_START; - static const CallbacksInvoker::KeyType TOUCH_MOVE; - static const CallbacksInvoker::KeyType TOUCH_END; - static const CallbacksInvoker::KeyType TOUCH_CANCEL; - static const CallbacksInvoker::KeyType MOUSE_DOWN; - static const CallbacksInvoker::KeyType MOUSE_MOVE; - static const CallbacksInvoker::KeyType MOUSE_UP; - static const CallbacksInvoker::KeyType MOUSE_WHEEL; - static const CallbacksInvoker::KeyType MOUSE_ENTER; - static const CallbacksInvoker::KeyType MOUSE_LEAVE; - static const CallbacksInvoker::KeyType KEY_DOWN; - static const CallbacksInvoker::KeyType KEY_UP; - static const CallbacksInvoker::KeyType DEVICEMOTION; - static const CallbacksInvoker::KeyType TRANSFORM_CHANGED; - static const CallbacksInvoker::KeyType ANCESTOR_TRANSFORM_CHANGED; - static const CallbacksInvoker::KeyType MOBILITY_CHANGED; - static const CallbacksInvoker::KeyType SCENE_CHANGED_FOR_PERSISTS; - static const CallbacksInvoker::KeyType SIZE_CHANGED; - static const CallbacksInvoker::KeyType ANCHOR_CHANGED; - static const CallbacksInvoker::KeyType COLOR_CHANGED; - static const CallbacksInvoker::KeyType CHILD_ADDED; - static const CallbacksInvoker::KeyType CHILD_REMOVED; - static const CallbacksInvoker::KeyType PARENT_CHANGED; - static const CallbacksInvoker::KeyType NODE_DESTROYED; - static const CallbacksInvoker::KeyType LAYER_CHANGED; - static const CallbacksInvoker::KeyType SIBLING_ORDER_CHANGED; - static const CallbacksInvoker::KeyType ACTIVE_IN_HIERARCHY_CHANGED; - static const CallbacksInvoker::KeyType LIGHT_PROBE_CHANGED; -}; - -} // namespace cc diff --git a/native/cocos/core/scene-graph/NodeEventProcessor.cpp b/native/cocos/core/scene-graph/NodeEventProcessor.cpp deleted file mode 100644 index 356ee9bf7b..0000000000 --- a/native/cocos/core/scene-graph/NodeEventProcessor.cpp +++ /dev/null @@ -1,584 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#include "core/scene-graph/NodeEventProcessor.h" -// #include "2d/framework/UITransform.h" -// #include "core/Director.h" -//#include "core/components/Component.h" -#include "core/scene-graph/Node.h" -//#include "core/scene-graph/NodeUIProperties.h" -#include "math/Vec2.h" - -namespace { -ccstd::vector cachedArray(16); -cc::Node *currentHovered = nullptr; -cc::Vec2 pos; - -//bool touchStartHandler(cc::event::EventListener *listener, cc::event::Touch *touch, cc::event::Event *event) { -// auto *touchEvent = static_cast(event); -// auto *node = dynamic_cast(listener->owner); -// if (node == nullptr || !node->getUIProps()->getUITransformComp()) { -// return false; -// } -// -// pos = touch->getUILocation(); -// -// if (node->getUIProps()->getUITransformComp()->isHit(pos)) { -// touchEvent->setEventName(cc::NodeEventType::TOUCH_START); -// touchEvent->setTouch(touch); -// touchEvent->setUseBubbles(true); -// node->dispatchEvent(touchEvent); -// return true; -// } -// -// return false; -//} -// -//void touchMoveHandler(cc::event::EventListener *listener, cc::event::Touch *touch, cc::event::Event *event) { -// auto *touchEvent = static_cast(event); -// auto *node = dynamic_cast(listener->owner); -// if (node == nullptr || !node->getUIProps()->getUITransformComp()) { -// return; -// } -// -// touchEvent->setEventName(cc::NodeEventType::TOUCH_MOVE); -// touchEvent->setTouch(touch); -// touchEvent->setUseBubbles(true); -// node->dispatchEvent(touchEvent); -//} -// -//void touchEndHandler(cc::event::EventListener *listener, cc::event::Touch *touch, cc::event::Event *event) { -// auto *touchEvent = static_cast(event); -// auto *node = dynamic_cast(listener->owner); -// if (node == nullptr || !node->getUIProps()->getUITransformComp()) { -// return; -// } -// -// pos = touch->getUILocation(); -// -// if (node->getUIProps()->getUITransformComp()->isHit(pos)) { -// event->setEventName(cc::NodeEventType::TOUCH_END); -// } else { -// event->setEventName(cc::NodeEventType::TOUCH_CANCEL); -// } -// -// touchEvent->setTouch(touch); -// touchEvent->setUseBubbles(true); -// node->dispatchEvent(touchEvent); -//} -// -//void touchCancelHandler(cc::event::EventListener *listener, cc::event::Touch *touch, cc::event::Event *event) { -// auto *touchEvent = static_cast(event); -// auto *node = dynamic_cast(listener->owner); -// if (node == nullptr || !node->getUIProps()->getUITransformComp()) { -// return; -// } -// -// touchEvent->setEventName(cc::NodeEventType::TOUCH_CANCEL); -// touchEvent->setTouch(touch); -// touchEvent->setUseBubbles(true); -// node->dispatchEvent(event); -//} -// -//void mouseDownHandler(cc::event::EventListener *listener, cc::event::EventMouse *mouseEvent) { -// auto *node = dynamic_cast(listener->owner); -// if (node == nullptr || !node->getUIProps()->getUITransformComp()) { -// return; -// } -// -// pos = mouseEvent->getUILocation(); -// -// if (node->getUIProps()->getUITransformComp()->isHit(pos)) { -// mouseEvent->setEventName(cc::NodeEventType::MOUSE_DOWN); -// mouseEvent->setUseBubbles(true); -// node->dispatchEvent(mouseEvent); -// } -//} -// -//void mouseMoveHandler(cc::event::EventListener *listener, cc::event::EventMouse *mouseEvent) { -// auto *node = dynamic_cast(listener->owner); -// if (node == nullptr || !node->getUIProps()->getUITransformComp()) { -// return; -// } -// -// pos = mouseEvent->getUILocation(); -// -// if (node->getUIProps()->getUITransformComp()->isHit(pos)) { -// if (!listener->_previousIn) { -// // Fix issue when hover node switched, previous hovered node won't get MOUSE_LEAVE notification -// if (currentHovered && currentHovered->getEventProcessor()->getMouseListener()) { -// mouseEvent->setEventName(cc::NodeEventType::MOUSE_LEAVE); -// currentHovered->dispatchEvent(mouseEvent); -// if (currentHovered->getEventProcessor()->getMouseListener()) { -// currentHovered->getEventProcessor()->getMouseListener()->_previousIn = false; -// } -// } -// currentHovered = node; -// mouseEvent->setEventName(cc::NodeEventType::MOUSE_ENTER); -// node->dispatchEvent(mouseEvent); -// listener->_previousIn = true; -// } -// mouseEvent->setEventName(cc::NodeEventType::MOUSE_MOVE); -// mouseEvent->setUseBubbles(true); -// node->dispatchEvent(mouseEvent); -// } else if (listener->_previousIn) { -// mouseEvent->setEventName(cc::NodeEventType::MOUSE_LEAVE); -// node->dispatchEvent(mouseEvent); -// listener->_previousIn = false; -// currentHovered = nullptr; -// } else { -// // continue dispatching -// return; -// } -// -// // Event processed, cleanup -// mouseEvent->setPropagationStopped(true); -//} -//void mouseUpHandler(cc::event::EventListener *listener, cc::event::EventMouse *mouseEvent) { -// auto *node = dynamic_cast(listener->owner); -// if (node == nullptr || !node->getUIProps()->getUITransformComp()) { -// return; -// } -// -// pos = mouseEvent->getUILocation(); -// -// if (node->getUIProps()->getUITransformComp()->isHit(pos)) { -// mouseEvent->setEventName(cc::NodeEventType::MOUSE_UP); -// mouseEvent->setUseBubbles(true); -// node->dispatchEvent(mouseEvent); -// mouseEvent->setPropagationStopped(true); -// } -//} -// -//void mouseWheelHandler(cc::event::EventListener *listener, cc::event::EventMouse *mouseEvent) { -// auto *node = dynamic_cast(listener->owner); -// if (node == nullptr || !node->getUIProps()->getUITransformComp()) { -// return; -// } -// -// pos = mouseEvent->getUILocation(); -// -// if (node->getUIProps()->getUITransformComp()->isHit(pos)) { -// mouseEvent->setEventName(cc::NodeEventType::MOUSE_WHEEL); -// mouseEvent->setUseBubbles(true); -// node->dispatchEvent(mouseEvent); -// mouseEvent->setPropagationStopped(true); -// } -//} -// -//void doDispatchEvent(cc::Node *owner, cc::event::Event *event) { -// cc::Node *target = nullptr; -// event->setTarget(owner); -// -// // Event.CAPTURING_PHASE -// cachedArray.clear(); -// owner->getEventProcessor()->getCapturingTargets(event->getEventName(), cachedArray); -// // capturing -// event->setEventPhase(cc::event::Event::Phase::CAPTURING); -// for (auto i = static_cast(cachedArray.size() - 1); i >= 0; --i) { -// target = cachedArray[i]; -// if (target->getEventProcessor()->getCapturingTargets()) { -// event->setCurrentTarget(target); -// // fire event -// target->getEventProcessor()->getCapturingTargets()->emit(event->getEventName(), event, cachedArray); -// // check if propagation stopped -// if (event->isPropagationStopped()) { -// cachedArray.clear(); -// return; -// } -// } -// } -// cachedArray.clear(); -// -// // Event.AT_TARGET -// // checks if destroyed in capturing callbacks -// event->setEventPhase(cc::event::Event::Phase::AT_TARGET); -// event->setCurrentTarget(owner); -// if (owner->getEventProcessor()->getCapturingTargets()) { -// owner->getEventProcessor()->getCapturingTargets()->emit(event->getEventName(), event); -// } -// if (!event->isPropagationImmediateStopped() && owner->getEventProcessor()->getBubblingTargets()) { -// owner->getEventProcessor()->getBubblingTargets()->emit(event->getEventName(), event); -// } -// -// if (!event->isPropagationStopped() && event->isUseBubbles()) { -// // Event.BUBBLING_PHASE -// owner->getEventProcessor()->getBubblingTargets(event->getEventName(), cachedArray); -// // propagate -// event->setEventPhase(cc::event::Event::Phase::BUBBLING); -// for (uint32_t i = 0; i < cachedArray.size(); ++i) { -// target = cachedArray[i]; -// if (target->getEventProcessor()->getBubblingTargets()) { -// event->setCurrentTarget(target); -// // fire event -// target->getEventProcessor()->getBubblingTargets()->emit(event->getEventName(), event); -// // check if propagation stopped -// if (event->isPropagationStopped()) { -// cachedArray.clear(); -// return; -// } -// } -// } -// } -// cachedArray.clear(); -//} -// -//template ::value, T>> -//ccstd::vector searchComponentsInParent(cc::Node *node) { -// index_t index = 0; -// ccstd::vector list; -// -// for (cc::Node *curr = node; curr != nullptr && cc::Node::isNode(curr); curr = curr->getParent(), ++index) { -// auto *comp = curr->getComponent(); -// if (comp != nullptr) { -// list.emplace_back(); -// auto &info = list.back(); -// info.index = index; -// info.comp = comp; -// } -// } -// return list.empty() ? ccstd::vector() : list; -//} - -} // namespace -namespace cc { -NodeEventProcessor::NodeEventProcessor(Node *node) : _node(node) {} - -NodeEventProcessor::~NodeEventProcessor() { - delete _bubblingTargets; - delete _capturingTargets; - // delete _touchListener; - // delete _mouseListener; -} - -bool NodeEventProcessor::checkListeners(cc::Node *node, const ccstd::vector &events) { - if (!node->isPersistNode()) { - if (node->getEventProcessor()->_bubblingTargets) { - for (const auto &event : events) { - if (node->getEventProcessor()->_bubblingTargets->hasEventListener(event)) { - return true; - } - } - } - if (node->getEventProcessor()->_bubblingTargets) { - for (const auto &event : events) { - if (node->getEventProcessor()->_bubblingTargets->hasEventListener(event)) { - return true; - } - } - } - return false; - } - return true; -} - -void NodeEventProcessor::reattach() { - // ccstd::vector currMask; - // _node->walk( - // [&](Node *node) { - // if (currMask.empty()) { - // currMask = searchComponentsInParent(node); - // } - // if (node->getEventProcessor()->_touchListener != nullptr) { - // node->getEventProcessor()->_touchListener->mask = currMask; - // } - // if (node->getEventProcessor()->_mouseListener != nullptr) { - // node->getEventProcessor()->_mouseListener->mask = currMask; - // } - // }); -} - -void NodeEventProcessor::destroy() { - if (currentHovered == _node) { - currentHovered = nullptr; - } - - // Remove all event listeners if necessary - // if (_touchListener || _mouseListener) { - // event::EventManager::getInstance()->removeEventListenersForTarget(_node); - // if (_touchListener) { - // _touchListener->owner = nullptr; - // _touchListener->mask.clear(); - // _touchListener = nullptr; - // } - // if (_mouseListener) { - // _mouseListener->owner = nullptr; - // _mouseListener->mask.clear(); - // _mouseListener = nullptr; - // } - // } - - if (_capturingTargets) _capturingTargets->offAll(); - if (_bubblingTargets) _bubblingTargets->offAll(); -} - -void NodeEventProcessor::off(const CallbacksInvoker::KeyType &type, void *target, bool /*useCapture*/ /* = false*/) { - // bool touchEventExist = std::find(TOUCH_EVENTS.begin(), TOUCH_EVENTS.end(), type) != TOUCH_EVENTS.end(); - // bool mouseEventExist = std::find(MOUSE_EVENTS.begin(), MOUSE_EVENTS.end(), type) != MOUSE_EVENTS.end(); - // if (touchEventExist || mouseEventExist) { - // offDispatch(type, target, useCapture); - // - // if (touchEventExist) { - // if (_touchListener && !checkListeners(_node, TOUCH_EVENTS)) { - // event::EventManager::getInstance()->removeEventListener(_touchListener); - // _touchListener = nullptr; - // } - // } else if (mouseEventExist) { - // if (_mouseListener && !checkListeners(_node, MOUSE_EVENTS)) { - // event::EventManager::getInstance()->removeEventListener(_mouseListener); - // _mouseListener = nullptr; - // } - // } - // } else - if (_bubblingTargets != nullptr) { - _bubblingTargets->offAll(type, target); - } -} - -void NodeEventProcessor::off(const CallbacksInvoker::KeyType &type, const CallbackID &cbID, bool /*useCapture*/) { - // bool touchEventExist = std::find(TOUCH_EVENTS.begin(), TOUCH_EVENTS.end(), type) != TOUCH_EVENTS.end(); - // bool mouseEventExist = std::find(MOUSE_EVENTS.begin(), MOUSE_EVENTS.end(), type) != MOUSE_EVENTS.end(); - // if (touchEventExist || mouseEventExist) { - // offDispatch(type, cbID, useCapture); - // - // if (touchEventExist) { - // if (_touchListener && !checkListeners(_node, TOUCH_EVENTS)) { - // event::EventManager::getInstance()->removeEventListener(_touchListener); - // _touchListener = nullptr; - // } - // } else if (mouseEventExist) { - // if (_mouseListener && !checkListeners(_node, MOUSE_EVENTS)) { - // event::EventManager::getInstance()->removeEventListener(_mouseListener); - // _mouseListener = nullptr; - // } - // } - // } else - if (_bubblingTargets != nullptr) { - _bubblingTargets->off(type, cbID); - } -} - -void NodeEventProcessor::offAll(const CallbacksInvoker::KeyType &type, bool /* useCapture = false*/) { - // bool touchEventExist = std::find(TOUCH_EVENTS.begin(), TOUCH_EVENTS.end(), type) != TOUCH_EVENTS.end(); - // bool mouseEventExist = std::find(MOUSE_EVENTS.begin(), MOUSE_EVENTS.end(), type) != MOUSE_EVENTS.end(); - // if (touchEventExist || mouseEventExist) { - // offDispatch(type, target, useCapture); - // - // if (touchEventExist) { - // if (_touchListener && !checkListeners(_node, TOUCH_EVENTS)) { - // event::EventManager::getInstance()->removeEventListener(_touchListener); - // _touchListener = nullptr; - // } - // } else if (mouseEventExist) { - // if (_mouseListener && !checkListeners(_node, MOUSE_EVENTS)) { - // event::EventManager::getInstance()->removeEventListener(_mouseListener); - // _mouseListener = nullptr; - // } - // } - // } else - if (_bubblingTargets != nullptr) { - _bubblingTargets->offAll(type); - } -} - -//void NodeEventProcessor::dispatchEvent(event::Event *event) { -// doDispatchEvent(_node, event); -// cachedArray.clear(); -//} - -bool NodeEventProcessor::hasEventListener(const CallbacksInvoker::KeyType &type) const { - bool has = false; - if (_bubblingTargets) { - has = _bubblingTargets->hasEventListener(type); - } - if (!has && _capturingTargets) { - has = _capturingTargets->hasEventListener(type); - } - return has; -} - -bool NodeEventProcessor::hasEventListener(const CallbacksInvoker::KeyType &type, const CallbackID &cbID) const { - bool has = false; - if (_bubblingTargets) { - has = _bubblingTargets->hasEventListener(type, cbID); - } - if (!has && _capturingTargets) { - has = _capturingTargets->hasEventListener(type, cbID); - } - return has; -} - -bool NodeEventProcessor::hasEventListener(const CallbacksInvoker::KeyType &type, void *target) const { - bool has = false; - if (_bubblingTargets) { - has = _bubblingTargets->hasEventListener(type, target); - } - if (!has && _capturingTargets) { - has = _capturingTargets->hasEventListener(type, target); - } - return has; -} -bool NodeEventProcessor::hasEventListener(const CallbacksInvoker::KeyType &type, void *target, const CallbackID &cbID) const { - bool has = false; - if (_bubblingTargets) { - has = _bubblingTargets->hasEventListener(type, target, cbID); - } - if (!has && _capturingTargets) { - has = _capturingTargets->hasEventListener(type, target, cbID); - } - return has; -} - -void NodeEventProcessor::targetOff(const CallbacksInvoker::KeyType &target) { - if (_capturingTargets) { - _capturingTargets->offAll(target); - } - if (_bubblingTargets) { - _bubblingTargets->offAll(target); - } - - // if (_touchListener && !checkListeners(_node, TOUCH_EVENTS)) { - // event::EventManager::getInstance()->removeEventListener(_touchListener); - // _touchListener = nullptr; - // } - // if (_mouseListener && !checkListeners(_node, MOUSE_EVENTS)) { - // event::EventManager::getInstance()->removeEventListener(_mouseListener); - // _mouseListener = nullptr; - // } -} - -void NodeEventProcessor::getCapturingTargets(const CallbacksInvoker::KeyType &type, ccstd::vector &targets) const { - auto *parent = _node->getParent(); - while (parent != nullptr) { - if (parent->getEventProcessor()->_capturingTargets != nullptr && parent->getEventProcessor()->_capturingTargets->hasEventListener(type)) { - targets.emplace_back(parent); - } - parent = parent->getParent(); - } -} - -void NodeEventProcessor::getBubblingTargets(const CallbacksInvoker::KeyType &type, ccstd::vector &targets) const { - auto *parent = _node->getParent(); - while (parent != nullptr) { - if (parent->getEventProcessor()->_bubblingTargets != nullptr && parent->getEventProcessor()->_bubblingTargets->hasEventListener(type)) { - targets.emplace_back(parent); - } - parent = parent->getParent(); - } -} - -//bool NodeEventProcessor::checknSetupSysEvent(const CallbacksInvoker::KeyType &type) { -// bool newAdded = false; -// bool forDispatch = false; -// // just for ui -// -// auto *eventManager = event::EventManager::getInstance(); -// if (std::find(TOUCH_EVENTS.begin(), TOUCH_EVENTS.end(), type) != TOUCH_EVENTS.end()) { -// if (_touchListener != nullptr) { -// _touchListener = event::EventListenerTouchOneByOne::create(); -// _touchListener->setSwallowTouches(true); -// _touchListener->owner = _node; -// //cjh TODO: _touchListener->mask = searchComponentsInParent(_node, NodeEventProcessor._comp), -// event::EventListener *listener = _touchListener; -// _touchListener->onTouchBegan = [=](event::Touch *touch, event::Event *event) -> bool { -// return touchStartHandler(listener, touch, event); -// }; -// _touchListener->onTouchMoved = [=](event::Touch *touch, event::Event *event) { -// touchMoveHandler(listener, touch, event); -// }; -// _touchListener->onTouchEnded = [=](event::Touch *touch, event::Event *event) { -// touchEndHandler(listener, touch, event); -// }; -// _touchListener->onTouchCancelled = [=](event::Touch *touch, event::Event *event) { -// touchCancelHandler(listener, touch, event); -// }; -// eventManager->addEventListenerWithSceneGraphPriority(_touchListener, _node); -// newAdded = true; -// } -// forDispatch = true; -// } else if (std::find(MOUSE_EVENTS.begin(), MOUSE_EVENTS.end(), type) != MOUSE_EVENTS.end()) { -// if (_mouseListener != nullptr) { -// _mouseListener = event::EventListenerMouse::create(); -// _mouseListener->_previousIn = false; -// _mouseListener->owner = _node; -// //cjh _mouseListener->mask = searchComponentsInParent(_node, NodeEventProcessor._comp), -// -// event::EventListener *listener = _mouseListener; -// _mouseListener->onMouseDown = [=](event::EventMouse *event) { -// mouseDownHandler(listener, event); -// }; -// -// _mouseListener->onMouseMove = [=](event::EventMouse *event) { -// mouseMoveHandler(listener, event); -// }; -// -// _mouseListener->onMouseUp = [=](event::EventMouse *event) { -// mouseUpHandler(listener, event); -// }; -// -// _mouseListener->onMouseScroll = [=](event::EventMouse *event) { -// mouseWheelHandler(listener, event); -// }; -// -// eventManager->addEventListenerWithSceneGraphPriority(_mouseListener, _node); -// newAdded = true; -// } -// forDispatch = true; -// } -// // TODO(xwx): not sure use scheduler -// // if (newAdded && !_node->isActiveInHierarchy()) { -// // Director::getInstance()->getScheduler()->schedule([](){ -// // if (!_node->isActiveInHierarchy()) { -// // eventManager.pauseTarget(_node); -// // } -// // }, _node, 0, 0, 0, false); -// // } -// return forDispatch; -//} - -void NodeEventProcessor::offDispatch(const CallbacksInvoker::KeyType &type, const CallbackID &cbID, bool useCapture) { - if (cbID.value == 0) { - if (_capturingTargets != nullptr) { - _capturingTargets->offAll(type); - } - if (_bubblingTargets != nullptr) { - _bubblingTargets->offAll(type); - } - } else { - CallbacksInvoker *listeners = useCapture ? _capturingTargets : _bubblingTargets; - if (listeners != nullptr) { - listeners->off(type, cbID); - } - } -} - -void NodeEventProcessor::offDispatch(const CallbacksInvoker::KeyType &type, void *target, bool useCapture) { - CallbacksInvoker *listeners = useCapture ? _capturingTargets : _bubblingTargets; - if (listeners != nullptr) { - listeners->offAll(type, target); - } -} - -} // namespace cc diff --git a/native/cocos/core/scene-graph/NodeEventProcessor.h b/native/cocos/core/scene-graph/NodeEventProcessor.h deleted file mode 100644 index ea233fb1a2..0000000000 --- a/native/cocos/core/scene-graph/NodeEventProcessor.h +++ /dev/null @@ -1,439 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -#pragma once - -#include -#include "base/memory/Memory.h" -#include "base/std/any.h" -#include "base/std/container/string.h" -#include "core/event/CallbacksInvoker.h" -//#include "core/event/Event.h" -#include "core/scene-graph/NodeEvent.h" - -namespace cc { -const ccstd::vector TOUCH_EVENTS{ - cc::NodeEventType::TOUCH_START, - cc::NodeEventType::TOUCH_MOVE, - cc::NodeEventType::TOUCH_END, - cc::NodeEventType::TOUCH_CANCEL}; - -const ccstd::vector MOUSE_EVENTS{ - cc::NodeEventType::MOUSE_DOWN, - cc::NodeEventType::MOUSE_ENTER, - cc::NodeEventType::MOUSE_MOVE, - cc::NodeEventType::MOUSE_LEAVE, - cc::NodeEventType::MOUSE_UP, - cc::NodeEventType::MOUSE_WHEEL}; - -class Node; - -class NodeEventProcessor final { -public: - NodeEventProcessor() = default; - explicit NodeEventProcessor(Node *node); - ~NodeEventProcessor(); - - inline Node *getNode() { return _node; } - void reattach(); - void destroy(); - - /** - * @zh - * 分发事件到事件流中。 - * - * @param event - 分派到事件流中的事件对象。 - */ - // void dispatchEvent(event::Event *event); - - bool hasEventListener(const CallbacksInvoker::KeyType &type) const; - - bool hasEventListener(const CallbacksInvoker::KeyType &type, const CallbackID &cbID) const; - - bool hasEventListener(const CallbacksInvoker::KeyType &type, void *target) const; - - bool hasEventListener(const CallbacksInvoker::KeyType &type, void *target, const CallbackID &cbID) const; - - template - bool hasEventListener(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target) const; - - static bool checkListeners(Node *node, const ccstd::vector &events); - - template - void on(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture = false); - - template - void on(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture = false); - - template - void on(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture = false); - - template - std::enable_if_t::value, void> - on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool useCapture = false); - - template - std::enable_if_t::value, void> - on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool useCapture = false); - - template - void once(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture = false); - - template - void once(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture = false); - - template - void once(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture = false); - - template - std::enable_if_t::value, void> - once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool useCapture = false); - - template - std::enable_if_t::value, void> - once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool useCapture = false); - - void off(const CallbacksInvoker::KeyType &type, const CallbackID &cbID, bool useCapture = false); - - void off(const CallbacksInvoker::KeyType &type, void *target, bool useCapture = false); - - void offAll(const CallbacksInvoker::KeyType &type, bool useCapture = false); - - template - void off(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture = false); - - /** - * @zh - * 通过事件名发送自定义事件 - * - * @param type - event type - * @param args - The arguments to be passed to the callback - */ - template - void emit(const CallbacksInvoker::KeyType &type, Args &&...args); - - void targetOff(const CallbacksInvoker::KeyType &target); - - void getCapturingTargets(const CallbacksInvoker::KeyType &type, ccstd::vector &targets) const; - void getBubblingTargets(const CallbacksInvoker::KeyType &type, ccstd::vector &targets) const; - - inline CallbacksInvoker *getBubblingTargets() const { return _bubblingTargets; } - inline CallbacksInvoker *getCapturingTargets() const { return _capturingTargets; } - // inline event::EventListener *getTouchListener() const { return _touchListener; } - // inline event::EventListener *getMouseListener() const { return _mouseListener; } - -private: - /** - * @zh - * 节点冒泡事件监听器 - */ - CallbacksInvoker *_bubblingTargets{nullptr}; - - /** - * @zh - * 节点捕获事件监听器 - */ - CallbacksInvoker *_capturingTargets{nullptr}; - - // /** - // * @zh - // * 触摸监听器 - // */ - // event::EventListenerTouchOneByOne *_touchListener{nullptr}; - // - // /** - // * @zh - // * 鼠标监听器 - // */ - // event::EventListenerMouse *_mouseListener{nullptr}; - - Node *_node{nullptr}; - - // bool checknSetupSysEvent(const CallbacksInvoker::KeyType &type); - - template - void onDispatch(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture = false); - - template - void onDispatch(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture = false); - - template - void onDispatch(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture = false); - - void offDispatch(const CallbacksInvoker::KeyType &type, const CallbackID &cbID, bool useCapture = false); - void offDispatch(const CallbacksInvoker::KeyType &type, void *target, bool useCapture = false); - - template - void offDispatch(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture = false); - - CC_DISALLOW_COPY_MOVE_ASSIGN(NodeEventProcessor); -}; - -template -void NodeEventProcessor::emit(const CallbacksInvoker::KeyType &type, Args &&...args) { - if (_bubblingTargets != nullptr) { - _bubblingTargets->emit(type, std::forward(args)...); - } -} -template -void NodeEventProcessor::onDispatch(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture) { - CallbacksInvoker *listeners = nullptr; - if (useCapture) { - if (_capturingTargets == nullptr) { - _capturingTargets = ccnew CallbacksInvoker(); - } - listeners = _capturingTargets; - } else { - if (_bubblingTargets == nullptr) { - _bubblingTargets = ccnew CallbacksInvoker(); - } - listeners = _bubblingTargets; - } - if (!listeners->hasEventListener(type)) { - listeners->on(type, std::forward>(callback), cbID); - } -} - -template -void NodeEventProcessor::onDispatch(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture) { - CallbacksInvoker *listeners = nullptr; - if (useCapture) { - if (_capturingTargets == nullptr) { - _capturingTargets = ccnew CallbacksInvoker(); - } - listeners = _capturingTargets; - } else { - if (_bubblingTargets == nullptr) { - _bubblingTargets = ccnew CallbacksInvoker(); - } - listeners = _bubblingTargets; - } - if (!listeners->hasEventListener(type)) { - listeners->on(type, std::forward>(callback), target, cbID); - } -} - -template -void NodeEventProcessor::onDispatch(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture) { - CallbacksInvoker *listeners = nullptr; - if (useCapture) { - if (_capturingTargets == nullptr) { - _capturingTargets = ccnew CallbacksInvoker(); - } - listeners = _capturingTargets; - } else { - if (_bubblingTargets == nullptr) { - _bubblingTargets = ccnew CallbacksInvoker(); - } - listeners = _bubblingTargets; - } - if (!listeners->hasEventListener(type)) { - listeners->on(type, memberFn, target); - } -} - -template -void NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool /*useCapture*/) { - // bool forDispatch = checknSetupSysEvent(type); - // if (forDispatch) { - // onDispatch(type, std::forward>(callback), cbID, useCapture); - // } else - { - if (_bubblingTargets == nullptr) { - _bubblingTargets = ccnew CallbacksInvoker(); - } - _bubblingTargets->on(type, std::forward>(callback), cbID); - } -} - -template -void NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, std::function &&callback, Target * /*target*/, CallbackID &cbID, bool /*useCapture*/) { - // bool forDispatch = checknSetupSysEvent(type); - // if (forDispatch) { - // onDispatch(type, std::forward>(callback), target, cbID, useCapture); - // } else - { - if (_bubblingTargets == nullptr) { - _bubblingTargets = ccnew CallbacksInvoker(); - } - _bubblingTargets->on(type, std::forward>(callback), cbID); - } -} - -template -std::enable_if_t::value, void> -NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool /*useCapture*/) { - // bool forDispatch = checknSetupSysEvent(type); - // if (forDispatch) { - // onDispatch(type, CallbacksInvoker::toFunction(std::forward(callback)), target, cbID, useCapture); - // } else - { - if (_bubblingTargets == nullptr) { - _bubblingTargets = ccnew CallbacksInvoker(); - } - _bubblingTargets->on(type, callback, target, cbID); - } -} - -template -std::enable_if_t::value, void> -NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool /*useCapture*/) { - // bool forDispatch = checknSetupSysEvent(type); - // if (forDispatch) { - // onDispatch(type, CallbacksInvoker::toFunction(std::forward(callback)), cbID, useCapture); - // } else - { - if (_bubblingTargets == nullptr) { - _bubblingTargets = ccnew CallbacksInvoker(); - } - _bubblingTargets->on(type, callback, cbID); - } -} - -template -void NodeEventProcessor::on(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool /*useCapture*/) { - using CallbackInfoType = CallbackInfo; - // bool forDispatch = checknSetupSysEvent(type); - // if (forDispatch) { - // onDispatch(type, memberFn, target, useCapture); - // } else - { - if (_bubblingTargets == nullptr) { - _bubblingTargets = ccnew CallbacksInvoker(); - } - _bubblingTargets->on(type, memberFn, target); - } -} - -template -void NodeEventProcessor::once(const CallbacksInvoker::KeyType &type, std::function &&callback, CallbackID &cbID, bool useCapture /* = false*/) { - once(type, std::forward(callback), nullptr, cbID, useCapture); -} - -template -void NodeEventProcessor::once(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture) { - CallbacksInvoker *listeners = nullptr; - if (useCapture) { - if (_capturingTargets == nullptr) { - _capturingTargets = ccnew CallbacksInvoker(); - } - listeners = _capturingTargets; - } else { - if (_bubblingTargets == nullptr) { - _bubblingTargets = ccnew CallbacksInvoker(); - } - listeners = _bubblingTargets; - } - - listeners->on(type, memberFn, target, true); - listeners->on( - type, [=](Args... /*unused*/) { off(type, memberFn, target); }, true); -} - -template -void NodeEventProcessor::once(const CallbacksInvoker::KeyType &type, std::function &&callback, Target *target, CallbackID &cbID, bool useCapture) { - CallbacksInvoker *listeners = nullptr; - if (useCapture) { - if (_capturingTargets == nullptr) { - _capturingTargets = ccnew CallbacksInvoker(); - } - listeners = _capturingTargets; - } else { - if (_bubblingTargets == nullptr) { - _bubblingTargets = ccnew CallbacksInvoker(); - } - listeners = _bubblingTargets; - } - listeners->on(type, std::forward>(callback), target, cbID, true); - CallbackID cacheID{cbID}; - listeners->on( - type, [=](Args... /*unused*/) { off(type, cacheID); }, target, true); -} - -template -std::enable_if_t::value, void> -NodeEventProcessor::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, Target *target, CallbackID &cbID, bool useCapture) { - once(type, CallbacksInvoker::toFunction(callback), target, cbID, useCapture); -} - -template -std::enable_if_t::value, void> -NodeEventProcessor::once(const CallbacksInvoker::KeyType &type, LambdaType &&callback, CallbackID &cbID, bool useCapture) { - once(type, std::forward(callback), nullptr, cbID, useCapture); -} - -template -void NodeEventProcessor::off(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool /*useCapture*/) { - // bool touchEventExist = std::find(TOUCH_EVENTS.begin(), TOUCH_EVENTS.end(), type) != TOUCH_EVENTS.end(); - // bool mouseEventExist = std::find(MOUSE_EVENTS.begin(), MOUSE_EVENTS.end(), type) != MOUSE_EVENTS.end(); - // if (touchEventExist || mouseEventExist) { - // offDispatch(type, memberFn, target, useCapture); - // - // if (touchEventExist) { - // if (_touchListener && !checkListeners(_node, TOUCH_EVENTS)) { - // event::EventManager::getInstance()->removeEventListener(_touchListener); - // _touchListener = nullptr; - // } - // } else if (mouseEventExist) { - // if (_mouseListener && !checkListeners(_node, MOUSE_EVENTS)) { - // event::EventManager::getInstance()->removeEventListener(_mouseListener); - // _mouseListener = nullptr; - // } - // } - // } else - if (_bubblingTargets != nullptr) { - _bubblingTargets->off(type, memberFn, target); - } -} - -template -void NodeEventProcessor::offDispatch(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target, bool useCapture) { - if (memberFn == nullptr) { - if (_capturingTargets != nullptr) { - _capturingTargets->offAll(type, target); - } - if (_bubblingTargets != nullptr) { - _bubblingTargets->offAll(type, target); - } - } else { - CallbacksInvoker *listeners = useCapture ? _capturingTargets : _bubblingTargets; - if (listeners != nullptr) { - listeners->off(type, memberFn, target); - } - } -} - -template -bool NodeEventProcessor::hasEventListener(const CallbacksInvoker::KeyType &type, void (Target::*memberFn)(Args...), Target *target) const { - bool has = false; - if (_bubblingTargets) { - has = _bubblingTargets->hasEventListener(type, memberFn, target); - } - if (!has && _capturingTargets) { - has = _capturingTargets->hasEventListener(type, memberFn, target); - } - return has; -} -} // namespace cc diff --git a/native/cocos/core/scene-graph/Scene.cpp b/native/cocos/core/scene-graph/Scene.cpp index c59c3596a7..2ba63b8255 100644 --- a/native/cocos/core/scene-graph/Scene.cpp +++ b/native/cocos/core/scene-graph/Scene.cpp @@ -28,7 +28,7 @@ // #include "core/Director.h" #include "core/Root.h" //#include "core/scene-graph/NodeActivator.h" -#include "cocos/bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" namespace cc { @@ -47,7 +47,7 @@ Scene::~Scene() = default; void Scene::setSceneGlobals(SceneGlobals *globals) { _globals = globals; } void Scene::load() { - EventDispatcher::dispatchSceneLoadEvent(); + events::SceneLoad::broadcast(); if (!_inited) { //cjh if (TEST) { // CC_ASSERT(!_activeInHierarchy, 'Should deactivate ActionManager by default'); diff --git a/native/cocos/core/scene-graph/SceneGraphModuleHeader.h b/native/cocos/core/scene-graph/SceneGraphModuleHeader.h index 9847e03b59..08b0770e70 100644 --- a/native/cocos/core/scene-graph/SceneGraphModuleHeader.h +++ b/native/cocos/core/scene-graph/SceneGraphModuleHeader.h @@ -31,8 +31,8 @@ #include "core/scene-graph/Node.h" //#include "core/scene-graph/NodeActivator.h" #include "core/scene-graph/NodeEnum.h" -#include "core/scene-graph/NodeEvent.h" -#include "core/scene-graph/NodeEventProcessor.h" +// #include "core/scene-graph/NodeEvent.h" +// #include "core/scene-graph/NodeEventProcessor.h" //#include "core/scene-graph/NodeUIProperties.h" #include "core/scene-graph/Scene.h" #include "core/scene-graph/SceneGlobals.h" diff --git a/native/cocos/editor-support/TypedArrayPool.cpp b/native/cocos/editor-support/TypedArrayPool.cpp index 223baf3116..6377779a76 100644 --- a/native/cocos/editor-support/TypedArrayPool.cpp +++ b/native/cocos/editor-support/TypedArrayPool.cpp @@ -29,7 +29,6 @@ #include "MiddlewareMacro.h" #include "base/Log.h" #include "base/Macros.h" -#include "cocos/bindings/event/CustomEventTypes.h" #include "cocos/bindings/event/EventDispatcher.h" #define POOL_DEBUG 0 @@ -51,7 +50,7 @@ const static std::size_t MAX_POOL_SIZE = 50; TypedArrayPool *TypedArrayPool::instance = nullptr; TypedArrayPool::TypedArrayPool() { - cc::EventDispatcher::addCustomEventListener(EVENT_CLOSE, [this](const CustomEvent &) { + _closeListener.bind([this]() { clearPool(); }); } diff --git a/native/cocos/editor-support/TypedArrayPool.h b/native/cocos/editor-support/TypedArrayPool.h index ecbf84f6e8..f9dc1f8522 100644 --- a/native/cocos/editor-support/TypedArrayPool.h +++ b/native/cocos/editor-support/TypedArrayPool.h @@ -28,6 +28,7 @@ #include #include "MiddlewareMacro.h" #include "SeApi.h" +#include "engine/EngineEvents.h" MIDDLEWARE_BEGIN /** @@ -75,6 +76,8 @@ private: typeMap _pool; bool _allowPush = true; + cc::events::Close::Listener _closeListener; + public: /** * @brief pop a js TypeArray by given type and size diff --git a/native/cocos/engine/BaseEngine.h b/native/cocos/engine/BaseEngine.h index e4e0288f4c..0a0175c949 100644 --- a/native/cocos/engine/BaseEngine.h +++ b/native/cocos/engine/BaseEngine.h @@ -29,13 +29,12 @@ #include "base/Scheduler.h" #include "base/TypeDef.h" -#include "core/event/CallbacksInvoker.h" +#include "core/event/EventTarget.h" #include "platform/BasePlatform.h" namespace cc { -class CC_DLL BaseEngine : public CallbacksInvoker, - public std::enable_shared_from_this { +class CC_DLL BaseEngine : public std::enable_shared_from_this, public event::EventTarget { public: enum EngineStatus { ON_START, @@ -47,6 +46,11 @@ public: ~BaseEngine() override; using Ptr = std::shared_ptr; + IMPL_EVENT_TARGET(BaseEngine) + + DECLARE_TARGET_EVENT_BEGIN(BaseEngine) + TARGET_EVENT_ARG1(EngineStatusChange, EngineStatus) + DECLARE_TARGET_EVENT_END() /** @brief Get operating system interface template. */ @@ -94,16 +98,6 @@ public: */ virtual void setPreferredFramesPerSecond(int fps) = 0; - using EventCb = std::function; - /** - @brief Add listening event callback. - */ - virtual void addEventCallback(OSEventType evtype, const EventCb &cb) = 0; - /** - @brief Remove listening event callback. - */ - virtual void removeEventCallback(OSEventType evtype) = 0; - using SchedulerPtr = std::shared_ptr; /** @brief Get engine scheduler. diff --git a/native/cocos/engine/Engine.cpp b/native/cocos/engine/Engine.cpp index 1e8a21167d..ec2aa8e346 100644 --- a/native/cocos/engine/Engine.cpp +++ b/native/cocos/engine/Engine.cpp @@ -32,6 +32,7 @@ #include "base/Macros.h" #include "bindings/jswrapper/SeApi.h" #include "core/builtin/BuiltinResMgr.h" +#include "engine/EngineEvents.h" #include "platform/BasePlatform.h" #include "platform/FileUtils.h" #include "renderer/GFXDeviceManager.h" @@ -57,6 +58,7 @@ #include "application/ApplicationManager.h" #include "application/BaseApplication.h" #include "base/Scheduler.h" +#include "bindings/event/EventDispatcher.h" #include "core/assets/FreeTypeFont.h" #include "network/HttpClient.h" #include "platform/UniversalPlatform.h" @@ -77,10 +79,10 @@ bool setCanvasCallback(se::Object * /*global*/) { auto handler = window->getWindowHandle(); auto viewSize = window->getViewSize(); auto dpr = cc::BasePlatform::getPlatform()->getInterface()->getDevicePixelRatio(); - + std::stringstream ss; { - ss << "window.innerWidth = " << static_cast(viewSize.x / dpr) << ";"; + ss << "window.innerWidth = " << static_cast(viewSize.x / dpr) << ";"; ss << "window.innerHeight = " << static_cast(viewSize.y / dpr) << ";"; ss << "window.windowHandler = "; if (sizeof(handler) == 8) { // use bigint @@ -101,6 +103,8 @@ namespace cc { Engine::Engine() { _scriptEngine = ccnew se::ScriptEngine(); + + _windowEventListener.bind([this](const cc::WindowEvent &ev) { redirectWindowEvent(ev); }); } Engine::~Engine() { @@ -129,14 +133,9 @@ int32_t Engine::init() { EventDispatcher::init(); BasePlatform *platform = BasePlatform::getPlatform(); - platform->setHandleEventCallback( - std::bind(&Engine::handleEvent, this, std::placeholders::_1)); // NOLINT(modernize-avoid-bind) - - platform->setHandleTouchEventCallback( - std::bind(&Engine::handleTouchEvent, this, std::placeholders::_1)); // NOLINT(modernize-avoid-bind) se::ScriptEngine::getInstance()->addRegisterCallback(setCanvasCallback); - emit(static_cast(ON_START)); + emit(ON_START); _inited = true; return 0; } @@ -232,7 +231,6 @@ void Engine::close() { // NOLINT cc::DeferredReleasePool::clear(); _scheduler->removeAllFunctionsToBePerformedInCocosThread(); _scheduler->unscheduleAll(); - BasePlatform::getPlatform()->setHandleEventCallback(nullptr); } uint Engine::getTotalFrames() const { @@ -248,21 +246,6 @@ void Engine::setPreferredFramesPerSecond(int fps) { _prefererredNanosecondsPerFrame = static_cast(1.0 / fps * NANOSECONDS_PER_SECOND); //NOLINT(google-runtime-int) } -void Engine::addEventCallback(OSEventType evType, const EventCb &cb) { - _eventCallbacks.insert(std::make_pair(evType, cb)); -} - -void Engine::removeEventCallback(OSEventType evType) { - auto it = _eventCallbacks.find(evType); - if (it != _eventCallbacks.end()) { - _eventCallbacks.erase(it); - return; - } - - // For debugging. Interface does not exist. - CC_ASSERT(false); -} - void Engine::tick() { CC_PROFILER_BEGIN_FRAME; { @@ -295,7 +278,7 @@ void Engine::tick() { _scheduler->update(dt); se::ScriptEngine::getInstance()->handlePromiseExceptions(); - cc::EventDispatcher::dispatchTickEvent(dt); + events::Tick::broadcast(dt); se::ScriptEngine::getInstance()->mainLoopUpdate(); cc::DeferredReleasePool::clear(); @@ -309,89 +292,43 @@ void Engine::tick() { } void Engine::doRestart() { - cc::EventDispatcher::dispatchRestartVM(); + events::RestartVM::broadcast(); destroy(); CC_CURRENT_APPLICATION()->init(); } -bool Engine::handleEvent(const OSEvent &ev) { - bool isHandled = false; - OSEventType type = ev.eventType(); - if (type == OSEventType::TOUCH_OSEVENT) { - cc::EventDispatcher::dispatchTouchEvent(OSEvent::castEvent(ev)); - isHandled = true; - } else if (type == OSEventType::MOUSE_OSEVENT) { - cc::EventDispatcher::dispatchMouseEvent(OSEvent::castEvent(ev)); - isHandled = true; - } else if (type == OSEventType::KEYBOARD_OSEVENT) { - cc::EventDispatcher::dispatchKeyboardEvent(OSEvent::castEvent(ev)); - isHandled = true; - } else if (type == OSEventType::CONTROLLER_OSEVENT) { - cc::EventDispatcher::dispatchControllerEvent(OSEvent::castEvent(ev)); - isHandled = true; - } else if (type == OSEventType::CUSTOM_OSEVENT) { - cc::EventDispatcher::dispatchCustomEvent(OSEvent::castEvent(ev)); - isHandled = true; - } else if (type == OSEventType::WINDOW_OSEVENT) { - isHandled = dispatchWindowEvent(OSEvent::castEvent(ev)); - } else if (type == OSEventType::DEVICE_OSEVENT) { - isHandled = dispatchDeviceEvent(OSEvent::castEvent(ev)); - } - isHandled = dispatchEventToApp(type, ev); - return isHandled; -} - -bool Engine::handleTouchEvent(const TouchEvent &ev) { // NOLINT(readability-convert-member-functions-to-static) - cc::EventDispatcher::dispatchTouchEvent(ev); - return dispatchEventToApp(OSEventType::TOUCH_OSEVENT, ev); -} - Engine::SchedulerPtr Engine::getScheduler() const { return _scheduler; } -bool Engine::dispatchDeviceEvent(const DeviceEvent &ev) { // NOLINT(readability-convert-member-functions-to-static) - bool isHandled = false; - if (ev.type == DeviceEvent::Type::MEMORY) { - cc::EventDispatcher::dispatchMemoryWarningEvent(); - isHandled = true; - } else if (ev.type == DeviceEvent::Type::ORIENTATION) { - cc::EventDispatcher::dispatchOrientationChangeEvent(ev.args[0].intVal); - isHandled = true; - } - return isHandled; -} - -bool Engine::dispatchWindowEvent(const WindowEvent &ev) { +bool Engine::redirectWindowEvent(const WindowEvent &ev) { bool isHandled = false; if (ev.type == WindowEvent::Type::SHOW || ev.type == WindowEvent::Type::RESTORED) { - emit(static_cast(ON_RESUME)); + emit(ON_RESUME); #if CC_PLATFORM == CC_PLATFORM_WINDOWS - ISystemWindow *window = CC_GET_SYSTEM_WINDOW(ev.windowId); - cc::EventDispatcher::dispatchRecreateWindowEvent(window); + events::WindowRecreated::broadcast(ev.windowId); #endif - cc::EventDispatcher::dispatchEnterForegroundEvent(); + events::EnterForeground::broadcast(); isHandled = true; } else if (ev.type == WindowEvent::Type::SIZE_CHANGED || ev.type == WindowEvent::Type::RESIZED) { - cc::EventDispatcher::dispatchResizeEvent(ev); + events::Resize::broadcast(ev.width, ev.height, ev.windowId); auto *w = CC_GET_SYSTEM_WINDOW(ev.windowId); CC_ASSERT(w); w->setViewSize(ev.width, ev.height); isHandled = true; } else if (ev.type == WindowEvent::Type::HIDDEN || ev.type == WindowEvent::Type::MINIMIZED) { - emit(static_cast(ON_PAUSE)); + emit(ON_PAUSE); #if CC_PLATFORM == CC_PLATFORM_WINDOWS - ISystemWindow *window = CC_GET_SYSTEM_WINDOW(ev.windowId); - cc::EventDispatcher::dispatchDestroyWindowEvent(window); + events::WindowDestroy::broadcast(ev.windowId); #endif - cc::EventDispatcher::dispatchEnterBackgroundEvent(); + events::EnterBackground::broadcast(); + isHandled = true; } else if (ev.type == WindowEvent::Type::CLOSE) { - emit(static_cast(ON_CLOSE)); - cc::EventDispatcher::dispatchCloseEvent(); + emit(ON_CLOSE); isHandled = true; } else if (ev.type == WindowEvent::Type::QUIT) { // There is no need to process the quit message, @@ -401,13 +338,4 @@ bool Engine::dispatchWindowEvent(const WindowEvent &ev) { return isHandled; } -bool Engine::dispatchEventToApp(OSEventType type, const OSEvent &ev) { - auto it = _eventCallbacks.find(type); - if (it != _eventCallbacks.end()) { - it->second(ev); - return true; - } - return false; -} - } // namespace cc diff --git a/native/cocos/engine/Engine.h b/native/cocos/engine/Engine.h index 2a37e22a9c..067d5180b4 100644 --- a/native/cocos/engine/Engine.h +++ b/native/cocos/engine/Engine.h @@ -27,8 +27,8 @@ #include "base/Config.h" #include "base/TypeDef.h" -#include "bindings/event/EventDispatcher.h" #include "engine/BaseEngine.h" +#include "engine/EngineEvents.h" #include "math/Vec2.h" #include @@ -96,29 +96,6 @@ public: @brief Gets the total number of frames in the main loop. */ uint getTotalFrames() const override; - /** - @brief Add Event Listening. - @param evtype:event type. - @param cb:event callback. - */ - void addEventCallback(OSEventType evtype, const EventCb &cb) override; - /** - @brief Remove Event Listening. - @param evtype:event type. - */ - void removeEventCallback(OSEventType evtype) override; - /** - @brief Event handling callback. - @param ev:Abstract event. - @return whether it's been handled. - */ - bool handleEvent(const OSEvent &ev); - /** - @brief Touch event handling callback. - @param ev:Touch event. - @return whether it's been handled. - */ - bool handleTouchEvent(const TouchEvent &ev); /** @brief Get engine scheduler. */ @@ -129,9 +106,7 @@ public: private: void destroy(); void tick(); - bool dispatchWindowEvent(const WindowEvent &ev); - bool dispatchDeviceEvent(const DeviceEvent &ev); - bool dispatchEventToApp(OSEventType type, const OSEvent &ev); + bool redirectWindowEvent(const WindowEvent &ev); void doRestart(); bool _close{false}; @@ -158,7 +133,8 @@ private: BuiltinResMgr *_builtinResMgr{nullptr}; ProgramLib *_programLib{nullptr}; - std::map _eventCallbacks; + events::WindowEvent::Listener _windowEventListener; + CC_DISALLOW_COPY_MOVE_ASSIGN(Engine); }; diff --git a/native/cocos/engine/EngineEvents.h b/native/cocos/engine/EngineEvents.h new file mode 100644 index 0000000000..fb6deef235 --- /dev/null +++ b/native/cocos/engine/EngineEvents.h @@ -0,0 +1,317 @@ +/**************************************************************************** + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +#pragma once + +#include +#include "base/std/container/string.h" +#include "base/std/container/unordered_map.h" +#include "base/std/container/vector.h" +#include "core/event/EventBus.h" + +namespace cc { + +class ISystemWindow; + +enum class OSEventType { + KEYBOARD_OSEVENT = 0, + TOUCH_OSEVENT = 1, + MOUSE_OSEVENT = 2, + CUSTOM_OSEVENT = 3, + DEVICE_OSEVENT = 4, + WINDOW_OSEVENT = 5, + APP_OSEVENT = 6, + CONTROLLER_OSEVENT = 7, + UNKNOWN_OSEVENT = 8 +}; + +class WindowEvent { +public: + WindowEvent() = default; + enum class Type { + QUIT = 0, + SHOW, + RESTORED, + SIZE_CHANGED, + RESIZED, + HIDDEN, + MINIMIZED, + CLOSE, + UNKNOWN, + }; + Type type = Type::UNKNOWN; + int width = 0; + int height = 0; + uint32_t windowId = 0; +}; +// Touch event related + +class TouchInfo { +public: + float x = 0; + float y = 0; + int index = 0; + + TouchInfo(float x, float y, int index) + : x(x), + y(y), + index(index) {} +}; + +class TouchEvent { +public: + TouchEvent() = default; + enum class Type { + BEGAN, + MOVED, + ENDED, + CANCELLED, + UNKNOWN + }; + + ccstd::vector touches; + Type type = Type::UNKNOWN; + uint32_t windowId = 0; +}; + +enum class StickKeyCode { + UNDEFINE = 0, + A, + B, + X, + Y, + L1, + R1, + MINUS, + PLUS, + L3, + R3, + MENU, + START, + TRIGGER_LEFT, + TRIGGER_RIGHT, +}; + +enum class StickAxisCode { + UNDEFINE = 0, + X, + Y, + LEFT_STICK_X, + LEFT_STICK_Y, + RIGHT_STICK_X, + RIGHT_STICK_Y, + L2, + R2, + LEFT_GRIP, + RIGHT_GRIP, +}; + +struct ControllerInfo { + struct AxisInfo { + StickAxisCode axis{StickAxisCode::UNDEFINE}; + float value{0.F}; + AxisInfo(StickAxisCode axis, float value) : axis(axis), value(value) {} + }; + struct ButtonInfo { + StickKeyCode key{StickKeyCode::UNDEFINE}; + bool isPress{false}; + ButtonInfo(StickKeyCode key, bool isPress) : key(key), isPress(isPress) {} + }; + + int napdId{0}; + std::vector axisInfos; + std::vector buttonInfos; +}; + +struct ControllerEvent { + ControllerEvent() = default; + enum class Type { + GAMEPAD, + HANDLE, + UNKNOWN + }; + Type type = Type::UNKNOWN; + std::vector> controllerInfos; +}; + +class MouseEvent { +public: + MouseEvent() = default; + enum class Type { + DOWN, + UP, + MOVE, + WHEEL, + UNKNOWN + }; + + float x = 0.0F; + float y = 0.0F; + // The button number that was pressed when the mouse event was fired: Left button=0, middle button=1 (if present), right button=2. + // For mice configured for left handed use in which the button actions are reversed the values are instead read from right to left. + uint16_t button = 0; + Type type = Type::UNKNOWN; + uint32_t windowId = 0; +}; + +enum class KeyCode { + /** + * @en The back key on mobile phone + * @zh 移动端返回键 + */ + MOBILE_BACK = 6, + BACKSPACE = 8, + TAB = 9, + NUM_LOCK = 12, + NUMPAD_ENTER = 20013, + ENTER = 13, + SHIFT_RIGHT = 20016, + SHIFT_LEFT = 16, + CONTROL_LEFT = 17, + CONTROL_RIGHT = 20017, + ALT_RIGHT = 20018, + ALT_LEFT = 18, + PAUSE = 19, + CAPS_LOCK = 20, + ESCAPE = 27, + SPACE = 32, + PAGE_UP = 33, + PAGE_DOWN = 34, + END = 35, + HOME = 36, + ARROW_LEFT = 37, + ARROW_UP = 38, + ARROW_RIGHT = 39, + ARROW_DOWN = 40, + INSERT = 45, + DELETE_KEY = 46, // DELETE has conflict + META_LEFT = 91, + CONTEXT_MENU = 20093, + PRINT_SCREEN = 20094, + META_RIGHT = 93, + NUMPAD_MULTIPLY = 106, + NUMPAD_PLUS = 107, + NUMPAD_MINUS = 109, + NUMPAD_DECIMAL = 110, + NUMPAD_DIVIDE = 111, + SCROLLLOCK = 145, + SEMICOLON = 186, + EQUAL = 187, + COMMA = 188, + MINUS = 189, + PERIOD = 190, + SLASH = 191, + BACKQUOTE = 192, + BRACKET_LEFT = 219, + BACKSLASH = 220, + BRACKET_RIGHT = 221, + QUOTE = 222, + NUMPAD_0 = 10048, + NUMPAD_1 = 10049, + NUMPAD_2 = 10050, + NUMPAD_3 = 10051, + NUMPAD_4 = 10052, + NUMPAD_5 = 10053, + NUMPAD_6 = 10054, + NUMPAD_7 = 10055, + NUMPAD_8 = 10056, + NUMPAD_9 = 10057, + DPAD_UP = 1003, + DPAD_LEFT = 1000, + DPAD_DOWN = 1004, + DPAD_RIGHT = 1001, + DPAD_CENTER = 1005 +}; + +class KeyboardEvent { +public: + KeyboardEvent() = default; + enum class Action { + PRESS, + RELEASE, + REPEAT, + UNKNOWN + }; + + uint32_t windowId = 0; + int key = -1; + Action action = Action::UNKNOWN; + bool altKeyActive = false; + bool ctrlKeyActive = false; + bool metaKeyActive = false; + bool shiftKeyActive = false; + // TODO(mingo): support caps lock? +}; +union EventParameterType { + void *ptrVal; + int32_t longVal; + int intVal; + int16_t shortVal; + char charVal; + bool boolVal; +}; + +class CustomEvent { +public: + CustomEvent() = default; + ccstd::string name; + EventParameterType args[10]; + + virtual ~CustomEvent() = default; // NOLINT(modernize-use-nullptr) +}; + +class DeviceEvent { +public: + DeviceEvent() = default; + enum class Type { + MEMORY, + ORIENTATION, + UNKNOWN + }; + EventParameterType args[3]; + Type type{Type::UNKNOWN}; // NOLINT(modernize-use-nullptr) +}; + +namespace events { +DECLARE_EVENT_BUS(Engine) + +DECLARE_BUS_EVENT_ARG0(EnterForeground, Engine) +DECLARE_BUS_EVENT_ARG0(EnterBackground, Engine) +DECLARE_BUS_EVENT_ARG1(WindowRecreated, Engine, uint32_t /* windowId*/) +DECLARE_BUS_EVENT_ARG1(WindowDestroy, Engine, uint32_t /*windowId*/) +DECLARE_BUS_EVENT_ARG1(WindowEvent, Engine, const cc::WindowEvent &) +DECLARE_BUS_EVENT_ARG1(WindowChanged, Engine, cc::WindowEvent::Type) +DECLARE_BUS_EVENT_ARG0(LowMemory, Engine) +DECLARE_BUS_EVENT_ARG1(Touch, Engine, const cc::TouchEvent &) +DECLARE_BUS_EVENT_ARG1(Mouse, Engine, const cc::MouseEvent &) +DECLARE_BUS_EVENT_ARG1(Keyboard, Engine, const cc::KeyboardEvent &) +DECLARE_BUS_EVENT_ARG1(Controller, Engine, const cc::ControllerEvent &) +DECLARE_BUS_EVENT_ARG1(Tick, Engine, float) +DECLARE_BUS_EVENT_ARG3(Resize, Engine, int, int, uint32_t /* windowId*/) +DECLARE_BUS_EVENT_ARG1(Orientation, Engine, int) +DECLARE_BUS_EVENT_ARG0(RestartVM, Engine) +DECLARE_BUS_EVENT_ARG0(Close, Engine) +DECLARE_BUS_EVENT_ARG0(SceneLoad, Engine) +} // namespace events +} // namespace cc diff --git a/native/cocos/platform/BasePlatform.h b/native/cocos/platform/BasePlatform.h index 28d605b7db..9f25c09cc5 100644 --- a/native/cocos/platform/BasePlatform.h +++ b/native/cocos/platform/BasePlatform.h @@ -28,7 +28,7 @@ #include "base/Log.h" #include "base/Macros.h" -#include "bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" #include "platform/interfaces/modules/ISystem.h" #include @@ -76,27 +76,6 @@ public: virtual OSType getOSType() const = 0; - /** - * @brief Set event handling callback function. - */ - using HandleEventCallback = std::function; - - virtual void setHandleEventCallback(HandleEventCallback cb) = 0; - - /** - * @brief Set touch event handling callback function. - */ - using HandleTouchEventCallback = std::function; - virtual void setHandleTouchEventCallback(HandleTouchEventCallback cb) = 0; - - /** - * @brief Set default event handling callback function. - */ - virtual void setHandleDefaultEventCallback(HandleEventCallback cb) = 0; - /** - * @brief Default event handling. - */ - virtual void handleDefaultEvent(const OSEvent &ev) = 0; /** * @brief Get the SDK version for Android.Other systems also have sdk versions, but they are not currently used. diff --git a/native/cocos/platform/IEventDispatch.h b/native/cocos/platform/IEventDispatch.h deleted file mode 100644 index e40f6f2c77..0000000000 --- a/native/cocos/platform/IEventDispatch.h +++ /dev/null @@ -1,48 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021-2022 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ - -#pragma once - -#include "base/Macros.h" -#include "bindings/event/EventDispatcher.h" - -namespace cc { -class CC_DLL IEventDispatch { -public: - /** - * Destructor of EventDispatchInterface. - */ - virtual ~IEventDispatch() = default; - /** - * Dispatch event interface. - */ - virtual void dispatchEvent(const OSEvent& ev) = 0; - /** - * Dispatch touch event interface. - */ - virtual void dispatchTouchEvent(const TouchEvent& ev) = 0; -}; - -} // namespace cc diff --git a/native/cocos/platform/SDLHelper.cpp b/native/cocos/platform/SDLHelper.cpp index 782f036c46..5a0ae9d6be 100644 --- a/native/cocos/platform/SDLHelper.cpp +++ b/native/cocos/platform/SDLHelper.cpp @@ -28,7 +28,7 @@ #include "SDL2/SDL_main.h" #include "SDL2/SDL_syswm.h" #include "base/Log.h" -#include "platform/IEventDispatch.h" +#include "engine/EngineEvents.h" #include "platform/interfaces/modules/ISystemWindow.h" #include "platform/interfaces/modules/ISystemWindowManager.h" @@ -160,43 +160,43 @@ int SDLHelper::init() { return 0; } -void SDLHelper::dispatchWindowEvent(IEventDispatch *delegate, uint32_t windowId, const SDL_WindowEvent &wevent) { +void SDLHelper::dispatchWindowEvent(uint32_t windowId, const SDL_WindowEvent &wevent) { WindowEvent ev; ev.windowId = windowId; switch (wevent.event) { case SDL_WINDOWEVENT_SHOWN: { ev.type = WindowEvent::Type::SHOW; - delegate->dispatchEvent(ev); + events::WindowEvent::broadcast(ev); break; } case SDL_WINDOWEVENT_RESTORED: { ev.type = WindowEvent::Type::RESTORED; - delegate->dispatchEvent(ev); + events::WindowEvent::broadcast(ev); break; } case SDL_WINDOWEVENT_SIZE_CHANGED: { ev.type = WindowEvent::Type::SIZE_CHANGED; ev.width = wevent.data1; ev.height = wevent.data2; - delegate->dispatchEvent(ev); + events::WindowEvent::broadcast(ev); break; } case SDL_WINDOWEVENT_RESIZED: { ev.type = WindowEvent::Type::RESIZED; ev.width = wevent.data1; ev.height = wevent.data2; - delegate->dispatchEvent(ev); + events::WindowEvent::broadcast(ev); break; } case SDL_WINDOWEVENT_HIDDEN: { ev.type = WindowEvent::Type::HIDDEN; - delegate->dispatchEvent(ev); + events::WindowEvent::broadcast(ev); break; } case SDL_WINDOWEVENT_MINIMIZED: { ev.type = WindowEvent::Type::MINIMIZED; - delegate->dispatchEvent(ev); + events::WindowEvent::broadcast(ev); break; } case SDL_WINDOWEVENT_ENTER: { @@ -205,13 +205,13 @@ void SDLHelper::dispatchWindowEvent(IEventDispatch *delegate, uint32_t windowId, } case SDL_WINDOWEVENT_CLOSE: { ev.type = WindowEvent::Type::CLOSE; - delegate->dispatchEvent(ev); + events::WindowEvent::broadcast(ev); break; } } } -void SDLHelper::dispatchSDLEvent(IEventDispatch *delegate, uint32_t windowId, const SDL_Event &sdlEvent, bool *quit) { +void SDLHelper::dispatchSDLEvent(uint32_t windowId, const SDL_Event &sdlEvent, bool *quit) { cc::TouchEvent touch; cc::MouseEvent mouse; cc::KeyboardEvent keyboard; @@ -229,11 +229,11 @@ void SDLHelper::dispatchSDLEvent(IEventDispatch *delegate, uint32_t windowId, co } WindowEvent ev; ev.type = WindowEvent::Type::QUIT; - delegate->dispatchEvent(ev); + events::WindowEvent::broadcast(ev); break; } case SDL_WINDOWEVENT: { - dispatchWindowEvent(delegate, windowId, sdlEvent.window); + dispatchWindowEvent(windowId, sdlEvent.window); break; } case SDL_MOUSEBUTTONDOWN: { @@ -248,7 +248,7 @@ void SDLHelper::dispatchSDLEvent(IEventDispatch *delegate, uint32_t windowId, co mouse.x = static_cast(event.x); mouse.y = static_cast(event.y); mouse.button = event.button - 1; - delegate->dispatchEvent(mouse); + events::Mouse::broadcast(mouse); break; } case SDL_MOUSEBUTTONUP: { @@ -257,7 +257,7 @@ void SDLHelper::dispatchSDLEvent(IEventDispatch *delegate, uint32_t windowId, co mouse.x = static_cast(event.x); mouse.y = static_cast(event.y); mouse.button = event.button - 1; - delegate->dispatchEvent(mouse); + events::Mouse::broadcast(mouse); break; } case SDL_MOUSEMOTION: { @@ -266,7 +266,7 @@ void SDLHelper::dispatchSDLEvent(IEventDispatch *delegate, uint32_t windowId, co mouse.x = static_cast(event.x); mouse.y = static_cast(event.y); mouse.button = 0; - delegate->dispatchEvent(mouse); + events::Mouse::broadcast(mouse); break; } case SDL_MOUSEWHEEL: { @@ -275,28 +275,28 @@ void SDLHelper::dispatchSDLEvent(IEventDispatch *delegate, uint32_t windowId, co mouse.x = static_cast(event.x); mouse.y = static_cast(event.y); mouse.button = 0; //TODO: direction - delegate->dispatchEvent(mouse); + events::Mouse::broadcast(mouse); break; } case SDL_FINGERUP: { const SDL_TouchFingerEvent &event = sdlEvent.tfinger; touch.type = TouchEvent::Type::ENDED; touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; - delegate->dispatchTouchEvent(touch); + events::Touch::broadcast(touch); break; } case SDL_FINGERDOWN: { const SDL_TouchFingerEvent &event = sdlEvent.tfinger; touch.type = TouchEvent::Type::BEGAN; touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; - delegate->dispatchTouchEvent(touch); + events::Touch::broadcast(touch); break; } case SDL_FINGERMOTION: { const SDL_TouchFingerEvent &event = sdlEvent.tfinger; touch.type = TouchEvent::Type::MOVED; touch.touches = {TouchInfo(event.x, event.y, (int)event.fingerId)}; - delegate->dispatchTouchEvent(touch); + events::Touch::broadcast(touch); break; } case SDL_KEYDOWN: { @@ -308,7 +308,7 @@ void SDLHelper::dispatchSDLEvent(IEventDispatch *delegate, uint32_t windowId, co keyboard.ctrlKeyActive = mode & KMOD_CTRL; keyboard.shiftKeyActive = mode & KMOD_SHIFT; //CC_LOG_DEBUG("==> key %d -> code %d", event.keysym.sym, keyboard.key); - delegate->dispatchEvent(keyboard); + events::Keyboard::broadcast(keyboard); break; } case SDL_KEYUP: { @@ -319,7 +319,8 @@ void SDLHelper::dispatchSDLEvent(IEventDispatch *delegate, uint32_t windowId, co keyboard.altKeyActive = mode & KMOD_ALT; keyboard.ctrlKeyActive = mode & KMOD_CTRL; keyboard.shiftKeyActive = mode & KMOD_SHIFT; - delegate->dispatchEvent(keyboard); + events::Keyboard::broadcast(keyboard); + break; break; } default: diff --git a/native/cocos/platform/SDLHelper.h b/native/cocos/platform/SDLHelper.h index ff3efbee16..7c67d71208 100644 --- a/native/cocos/platform/SDLHelper.h +++ b/native/cocos/platform/SDLHelper.h @@ -25,15 +25,13 @@ #pragma once #include -#include "bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" struct SDL_Window; -class OSEvent; union SDL_Event; struct SDL_WindowEvent; namespace cc { -class IEventDispatch; class SDLHelper { friend class SystemWindowManager; @@ -58,7 +56,7 @@ public: static void setCursorEnabled(bool value); private: - static void dispatchSDLEvent(IEventDispatch* delegate, uint32_t windowId, const SDL_Event& sdlEvent, bool* quit); - static void dispatchWindowEvent(IEventDispatch* delegate, uint32_t windowId, const SDL_WindowEvent& wevent); + static void dispatchSDLEvent( uint32_t windowId, const SDL_Event& sdlEvent, bool* quit); + static void dispatchWindowEvent(uint32_t windowId, const SDL_WindowEvent& wevent); }; } // namespace cc diff --git a/native/cocos/platform/UniversalPlatform.cpp b/native/cocos/platform/UniversalPlatform.cpp index d352e44235..8138806b1f 100644 --- a/native/cocos/platform/UniversalPlatform.cpp +++ b/native/cocos/platform/UniversalPlatform.cpp @@ -35,46 +35,6 @@ UniversalPlatform::OSType UniversalPlatform::getOSType() const { return getInterface()->getOSType(); } -void UniversalPlatform::dispatchEvent(const OSEvent& ev) { - bool isHandled = false; - if (_handleEventCallback) { - isHandled = (_handleEventCallback)(ev); - } - if (isHandled) { - return; - } - if (_handleDefaultEventCallback) { - isHandled = (_handleDefaultEventCallback)(ev); - } - if (!isHandled) { - handleDefaultEvent(ev); - } -} - -void UniversalPlatform::dispatchTouchEvent(const TouchEvent& ev) { - if (_handleTouchEventCallback) { - _handleTouchEventCallback(ev); - } else { - dispatchEvent(ev); - } -} - -void UniversalPlatform::handleDefaultEvent(const OSEvent& ev) { - // TODO(cc) : Follow-up support -} - -void UniversalPlatform::setHandleEventCallback(HandleEventCallback cb) { - _handleEventCallback = cb; -} - -void UniversalPlatform::setHandleTouchEventCallback(HandleTouchEventCallback cb) { - _handleTouchEventCallback = cb; -} - -void UniversalPlatform::setHandleDefaultEventCallback(HandleEventCallback cb) { - _handleDefaultEventCallback = cb; -} - int32_t UniversalPlatform::run(int argc, const char** argv) { if (cocos_main(argc, argv) != 0) { return -1; diff --git a/native/cocos/platform/UniversalPlatform.h b/native/cocos/platform/UniversalPlatform.h index ac04efb527..d5d8375191 100644 --- a/native/cocos/platform/UniversalPlatform.h +++ b/native/cocos/platform/UniversalPlatform.h @@ -26,10 +26,9 @@ #pragma once #include "platform/BasePlatform.h" -#include "platform/IEventDispatch.h" namespace cc { -class CC_DLL UniversalPlatform : public BasePlatform, public IEventDispatch { +class CC_DLL UniversalPlatform : public BasePlatform { public: /** * @brief Start base platform initialization. @@ -40,32 +39,6 @@ public: * @brief Get targe platform type. */ OSType getOSType() const override; - /** - * @brief Set the event handling callback. - */ - void setHandleEventCallback(HandleEventCallback cb) override; - - /** - * @brief Set the touch event handling callback. - */ - void setHandleTouchEventCallback(HandleTouchEventCallback cb) override; - - /** - * @brief Set the event to handle callbacks by default. - */ - void setHandleDefaultEventCallback(HandleEventCallback cb) override; - /** - * @brief Implement dispatch event interface. - */ - void dispatchEvent(const OSEvent &ev) override; - /** - * @brief Implement dispatch touch event interface. - */ - void dispatchTouchEvent(const TouchEvent &ev) override; - /** - * @brief Implement handle default event interface. - */ - void handleDefaultEvent(const OSEvent &ev) override; /** * @brief Get the SDK version for Android.Other systems also have sdk versions, but they are not currently used. @@ -112,10 +85,6 @@ private: ThreadCallback _mainTask{nullptr}; int32_t _fps{60}; - - HandleEventCallback _handleEventCallback{nullptr}; - HandleTouchEventCallback _handleTouchEventCallback{nullptr}; - HandleEventCallback _handleDefaultEventCallback{nullptr}; }; } // namespace cc diff --git a/native/cocos/platform/android/AndroidPlatform.cpp b/native/cocos/platform/android/AndroidPlatform.cpp index 6eaadefee0..f3a7b4ed00 100644 --- a/native/cocos/platform/android/AndroidPlatform.cpp +++ b/native/cocos/platform/android/AndroidPlatform.cpp @@ -29,7 +29,6 @@ #include "application/ApplicationManager.h" #include "base/Log.h" #include "base/memory/Memory.h" -#include "bindings/event/CustomEventTypes.h" #include "game-activity/native_app_glue/android_native_app_glue.h" #include "java/jni/JniHelper.h" #include "modules/Screen.h" @@ -47,7 +46,7 @@ #include "platform/java/modules/XRInterface.h" #include "base/StringUtil.h" -#include "bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" #include "paddleboat.h" #define ABORT_GAME \ @@ -217,6 +216,7 @@ public: return (addedControllerEvent != 0); } + // NOLINTNEXTLINE bool cookGameActivityMotionEvent(GameActivityMotionEvent *motionEvent) { if (motionEvent->pointerCount > 0) { touchEvent.windowId = ISystemWindow::mainWindowId; // must be main window here @@ -257,13 +257,14 @@ public: } } - _androidPlatform->dispatchEvent(touchEvent); + events::Touch::broadcast(touchEvent); touchEvent.touches.clear(); return true; } return false; } + // NOLINTNEXTLINE bool cookGameActivityKeyEvent(GameActivityKeyEvent *keyEvent) { for (const auto &action : INPUT_KEY_ACTIONS) { if (action.buttonMask != keyEvent->keyCode) { @@ -272,12 +273,13 @@ public: keyboardEvent.action = 0 == keyEvent->action ? cc::KeyboardEvent::Action::PRESS : cc::KeyboardEvent::Action::RELEASE; keyboardEvent.key = action.actionCode; - _androidPlatform->dispatchEvent(keyboardEvent); + events::Keyboard::broadcast(keyboardEvent); return true; } return false; } + // NOLINTNEXTLINE void reportKeyState(int keyCode, bool state) { bool wentDown = !keyState[keyCode] && state; bool wentUp = keyState[keyCode] && !state; @@ -286,11 +288,11 @@ public: if (wentUp) { keyboardEvent.key = keyCode; keyboardEvent.action = cc::KeyboardEvent::Action::RELEASE; - _androidPlatform->dispatchEvent(keyboardEvent); + events::Keyboard::broadcast(keyboardEvent); } else if (wentDown) { keyboardEvent.key = keyCode; keyboardEvent.action = cc::KeyboardEvent::Action::PRESS; - _androidPlatform->dispatchEvent(keyboardEvent); + events::Keyboard::broadcast(keyboardEvent); } } @@ -340,11 +342,7 @@ public: auto *windowMgr = _androidPlatform->getInterface(); auto *window = static_cast(windowMgr->getWindow(ISystemWindow::mainWindowId)); window->setWindowHandle(nativeWindow); - - cc::CustomEvent event; - event.name = EVENT_RECREATE_WINDOW; - event.args[0].intVal = ISystemWindow::mainWindowId; - _androidPlatform->dispatchEvent(event); + events::WindowRecreated::broadcast(ISystemWindow::mainWindowId); } break; } @@ -356,10 +354,8 @@ public: if (xr) { xr->onRenderPause(); } - cc::CustomEvent event; - event.name = EVENT_DESTROY_WINDOW; - event.args[0].intVal = ISystemWindow::mainWindowId; - _androidPlatform->dispatchEvent(event); + // NOLINTNEXTLINE + events::WindowDestroy::broadcast(ISystemWindow::mainWindowId); break; } case APP_CMD_GAINED_FOCUS: @@ -387,7 +383,7 @@ public: } WindowEvent ev; ev.type = WindowEvent::Type::CLOSE; - _androidPlatform->dispatchEvent(ev); + events::WindowEvent::broadcast(ev); _androidPlatform->onDestroy(); break; } @@ -397,7 +393,7 @@ public: Paddleboat_onStop(_jniEnv); WindowEvent ev; ev.type = WindowEvent::Type::HIDDEN; - _androidPlatform->dispatchEvent(ev); + events::WindowEvent::broadcast(ev); break; } case APP_CMD_START: { @@ -406,7 +402,7 @@ public: Paddleboat_onStart(_jniEnv); WindowEvent ev; ev.type = WindowEvent::Type::SHOW; - _androidPlatform->dispatchEvent(ev); + events::WindowEvent::broadcast(ev); break; } case APP_CMD_WINDOW_RESIZED: { @@ -415,7 +411,7 @@ public: ev.type = cc::WindowEvent::Type::SIZE_CHANGED; ev.width = ANativeWindow_getWidth(_androidPlatform->_app->window); ev.height = ANativeWindow_getHeight(_androidPlatform->_app->window); - _androidPlatform->dispatchEvent(ev); + events::WindowEvent::broadcast(ev); break; } case APP_CMD_CONFIG_CHANGED: @@ -429,9 +425,7 @@ public: // system told us we have low memory. So if we are not visible, let's // cooperate by deallocating all of our graphic resources. CC_LOG_INFO("AndroidPlatform: APP_CMD_LOW_MEMORY"); - DeviceEvent ev; - ev.type = DeviceEvent::Type::MEMORY; - _androidPlatform->dispatchEvent(ev); + events::LowMemory::broadcast(); break; } case APP_CMD_CONTENT_RECT_CHANGED: diff --git a/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp b/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp index 58c22c0d63..6f174b7ebd 100644 --- a/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp +++ b/native/cocos/platform/android/jni/JniCocosSurfaceView.cpp @@ -30,7 +30,7 @@ #include #include "application/ApplicationManager.h" #include "base/memory/Memory.h" -#include "bindings/event/CustomEventTypes.h" +#include "engine/EngineEvents.h" #include "platform/android/AndroidPlatform.h" #include "platform/java/jni/glue/JniNativeGlue.h" #include "platform/java/modules/SystemWindow.h" @@ -41,8 +41,7 @@ struct cc::TouchEvent touchEvent; class NativeWindowCache { public: - explicit NativeWindowCache(int windowId) :_windowId{windowId} { - + explicit NativeWindowCache(int windowId) : _windowId{windowId} { } ~NativeWindowCache() { @@ -80,32 +79,26 @@ private: extern "C" { -JNIEXPORT jlong Java_com_cocos_lib_CocosSurfaceView_constructNative(JNIEnv *env, jobject /*thiz*/, jint windowId) {//NOLINT JNI function name +JNIEXPORT jlong Java_com_cocos_lib_CocosSurfaceView_constructNative(JNIEnv *env, jobject /*thiz*/, jint windowId) { // NOLINT JNI function name auto *cache = ccnew NativeWindowCache(windowId); cache->env = env; return reinterpret_cast(cache); } -JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_destructNative(JNIEnv * /*env*/, jobject /*thiz*/, jlong handle) { //NOLINT JNI function name +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_destructNative(JNIEnv * /*env*/, jobject /*thiz*/, jlong handle) { // NOLINT JNI function name auto *windowCache = reinterpret_cast(handle); CC_SAFE_DELETE(windowCache); } -JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_onSizeChangedNative(JNIEnv */*env*/, jobject /*thiz*/, jint windowId, jint width, jint height) {//NOLINT JNI function name - cc::WindowEvent ev; - ev.windowId = windowId; - ev.type = cc::WindowEvent::Type::SIZE_CHANGED; - ev.width = width; - ev.height = height; - auto *platform = static_cast(cc::BasePlatform::getPlatform()); - platform->dispatchEvent(ev); +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_onSizeChangedNative(JNIEnv * /*env*/, jobject /*thiz*/, jint windowId, jint width, jint height) { // NOLINT JNI function name + cc::events::Resize::broadcast(width, height, windowId); } -JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_onSurfaceRedrawNeededNative(JNIEnv * /*env*/, jobject /*thiz*/, jlong handle) { //NOLINT JNI function name +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_onSurfaceRedrawNeededNative(JNIEnv * /*env*/, jobject /*thiz*/, jlong handle) { // NOLINT JNI function name // } -JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_onSurfaceCreatedNative(JNIEnv *env, jobject /*thiz*/, jlong handle, jobject surface) { //NOLINT JNI function name +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_onSurfaceCreatedNative(JNIEnv *env, jobject /*thiz*/, jlong handle, jobject surface) { // NOLINT JNI function name CC_UNUSED_PARAM(env); auto *windowCache = reinterpret_cast(handle); ANativeWindow *oldNativeWindow = windowCache->getNativeWindow(); @@ -119,17 +112,13 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_onSurfaceCreatedNativ sysWindow->setWindowHandle(nativeWindow); if (oldNativeWindow) { auto func = [sysWindow]() -> void { - cc::CustomEvent event; - event.name = EVENT_RECREATE_WINDOW; - event.args[0].intVal = sysWindow->getWindowId(); - auto *platform = static_cast(cc::BasePlatform::getPlatform()); - platform->dispatchEvent(event); + cc::events::WindowRecreated::broadcast(sysWindow->getWindowId()); }; CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread(func); } } -JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_onSurfaceChangedNative(JNIEnv *env, //NOLINT JNI function name +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_onSurfaceChangedNative(JNIEnv *env, // NOLINT JNI function name jobject /*thiz*/, jlong handle, jobject surface, @@ -157,11 +146,7 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_onSurfaceChangedNativ sysWindow->setWindowHandle(newNativeWindow); auto func = [sysWindow]() -> void { - cc::CustomEvent event; - event.name = EVENT_RECREATE_WINDOW; - event.args[0].intVal = sysWindow->getWindowId(); - auto *platform = static_cast(cc::BasePlatform::getPlatform()); - platform->dispatchEvent(event); + cc::events::WindowRecreated::broadcast(sysWindow->getWindowId()); }; CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread(func); } @@ -172,7 +157,7 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_onSurfaceChangedNativ } } -JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_onSurfaceDestroyedNative(JNIEnv *env, jobject /*thiz*/, jlong handle) { //NOLINT JNI function name +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_onSurfaceDestroyedNative(JNIEnv *env, jobject /*thiz*/, jlong handle) { // NOLINT JNI function name auto *windowCache = (NativeWindowCache *)handle; ANativeWindow *nativeWindow = windowCache->getNativeWindow(); @@ -182,17 +167,14 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosSurfaceView_onSurfaceDestroyedNat auto *windowMgr = platform->getInterface(); cc::ISystemWindow *window = windowMgr->getWindowFromANativeWindow(nativeWindow); - cc::CustomEvent event; - event.name = EVENT_DESTROY_WINDOW; - event.args[0].intVal = window->getWindowId(); - platform->dispatchEvent(event); + cc::events::WindowDestroy::broadcast(window->getWindowId()); }; CC_CURRENT_ENGINE()->getScheduler()->performFunctionInCocosThread(func); } // NOLINTNEXTLINE JNIEXPORT void JNICALL -Java_com_cocos_lib_CocosTouchHandler_handleActionDown(JNIEnv *env, //NOLINT JNI function name +Java_com_cocos_lib_CocosTouchHandler_handleActionDown(JNIEnv *env, // NOLINT JNI function name jobject obj, jint windowId, jint id, @@ -204,13 +186,12 @@ Java_com_cocos_lib_CocosTouchHandler_handleActionDown(JNIEnv *env, //NOLINT JNI touchEvent.windowId = windowId; touchEvent.type = cc::TouchEvent::Type::BEGAN; touchEvent.touches.emplace_back(x, y, id); - auto *platform = static_cast(cc::BasePlatform::getPlatform()); - platform->dispatchEvent(touchEvent); + cc::events::Touch::broadcast(touchEvent); touchEvent.touches.clear(); } // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionUp(JNIEnv *env, //NOLINT JNI function name +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionUp(JNIEnv *env, // NOLINT JNI function name jobject obj, jint windowId, jint id, @@ -222,13 +203,12 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionUp(JNIEn touchEvent.windowId = windowId; touchEvent.type = cc::TouchEvent::Type::ENDED; touchEvent.touches.emplace_back(x, y, id); - auto *platform = static_cast(cc::BasePlatform::getPlatform()); - platform->dispatchEvent(touchEvent); + cc::events::Touch::broadcast(touchEvent); touchEvent.touches.clear(); } // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionMove(JNIEnv *env, //NOLINT JNI function name +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionMove(JNIEnv *env, // NOLINT JNI function name jobject obj, jint windowId, jintArray ids, @@ -250,13 +230,12 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionMove(JNI touchEvent.touches.emplace_back(x[i], y[i], id[i]); } - auto *platform = static_cast(cc::BasePlatform::getPlatform()); - platform->dispatchEvent(touchEvent); + cc::events::Touch::broadcast(touchEvent); touchEvent.touches.clear(); } // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionCancel(JNIEnv *env, //NOLINT JNI function name +JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionCancel(JNIEnv *env, // NOLINT JNI function name jobject obj, jint windowId, jintArray ids, @@ -277,8 +256,7 @@ JNIEXPORT void JNICALL Java_com_cocos_lib_CocosTouchHandler_handleActionCancel(J for (int i = 0; i < size; i++) { touchEvent.touches.emplace_back(x[i], y[i], id[i]); } - auto *platform = static_cast(cc::BasePlatform::getPlatform()); - platform->dispatchEvent(touchEvent); + cc::events::Touch::broadcast(touchEvent); touchEvent.touches.clear(); } } diff --git a/native/cocos/platform/apple/JsbBridge.mm b/native/cocos/platform/apple/JsbBridge.mm index 908f6325c7..9181037aff 100644 --- a/native/cocos/platform/apple/JsbBridge.mm +++ b/native/cocos/platform/apple/JsbBridge.mm @@ -27,8 +27,7 @@ #import #include "base/std/container/string.h" #include "cocos/bindings/manual/JavaScriptObjCBridge.h" -#include "cocos/bindings/event/EventDispatcher.h" -#include "cocos/bindings/event/CustomEventTypes.h" +#include "engine/EngineEvents.h" bool callPlatformStringMethod(const ccstd::string &arg0, const ccstd::string &arg1) { NSString *oc_arg0 = [NSString stringWithCString:arg0.c_str() encoding:NSUTF8StringEncoding]; @@ -40,6 +39,7 @@ bool callPlatformStringMethod(const ccstd::string &arg0, const ccstd::string &ar @implementation JsbBridge { ICallback callback; + cc::events::Close::Listener closeListener; } static JsbBridge *instance = nil; @@ -63,7 +63,7 @@ static JsbBridge *instance = nil; - (id)init { if (self = [super init]) { - cc::EventDispatcher::addCustomEventListener(EVENT_CLOSE, [&](const cc::CustomEvent& event){ + closeListener.bind([&](){ if ([JsbBridge sharedInstance] != nil) { [[JsbBridge sharedInstance] release]; } diff --git a/native/cocos/platform/apple/JsbBridgeWrapper.mm b/native/cocos/platform/apple/JsbBridgeWrapper.mm index 0699c7c2ae..906ffa9af1 100644 --- a/native/cocos/platform/apple/JsbBridgeWrapper.mm +++ b/native/cocos/platform/apple/JsbBridgeWrapper.mm @@ -26,12 +26,12 @@ #include "base/std/container/string.h" #include "JsbBridge.h" #include "JsbBridgeWrapper.h" -#include "cocos/bindings/event/EventDispatcher.h" -#include "cocos/bindings/event/CustomEventTypes.h" +#include "engine/EngineEvents.h" @implementation JsbBridgeWrapper { JsbBridge* jb; NSMutableDictionary*>* cbDictionnary; + cc::events::Close::Listener closeListener; } static JsbBridgeWrapper* instance = nil; @@ -116,7 +116,7 @@ static ICallback cb = ^void(NSString* _event, NSString* _arg) { return nil; } [jb setCallback:cb]; - cc::EventDispatcher::addCustomEventListener(EVENT_CLOSE, [&](const cc::CustomEvent& event){ + closeListener.bind([&](){ if ([JsbBridgeWrapper sharedInstance] != nil) { [[JsbBridgeWrapper sharedInstance] release]; } diff --git a/native/cocos/platform/empty/modules/SystemWindow.cpp b/native/cocos/platform/empty/modules/SystemWindow.cpp index 9b2e6d7e0b..0fa9d9fda5 100644 --- a/native/cocos/platform/empty/modules/SystemWindow.cpp +++ b/native/cocos/platform/empty/modules/SystemWindow.cpp @@ -27,7 +27,7 @@ #include #include "base/Log.h" #include "base/Macros.h" -#include "bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" #include "platform/IEventDispatch.h" #include "platform/empty/EmptyPlatform.h" diff --git a/native/cocos/platform/interfaces/OSInterface.cpp b/native/cocos/platform/interfaces/OSInterface.cpp index 82006a9137..976e8f64cd 100644 --- a/native/cocos/platform/interfaces/OSInterface.cpp +++ b/native/cocos/platform/interfaces/OSInterface.cpp @@ -24,28 +24,7 @@ ****************************************************************************/ #include "platform/interfaces/OSInterface.h" -#include "platform/IEventDispatch.h" namespace cc { -OSInterface::OSInterface() -: OSInterface(nullptr) { -} - -OSInterface::OSInterface(IEventDispatch *evDispatchInterface) -: _evDispatchInterface(evDispatchInterface) { -} - -void OSInterface::dispatchEvent(const OSEvent &ev) { - if (_evDispatchInterface) { - _evDispatchInterface->dispatchEvent(ev); - } -} - -void OSInterface::dispatchTouchEvent(const TouchEvent &ev) { - if (_evDispatchInterface) { - _evDispatchInterface->dispatchTouchEvent(ev); - } -} - -} // namespace cc \ No newline at end of file +} // namespace cc diff --git a/native/cocos/platform/interfaces/OSInterface.h b/native/cocos/platform/interfaces/OSInterface.h index bde1a288cc..b0880e3fe2 100644 --- a/native/cocos/platform/interfaces/OSInterface.h +++ b/native/cocos/platform/interfaces/OSInterface.h @@ -27,10 +27,9 @@ #include #include "base/Macros.h" -#include "bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" namespace cc { -class IEventDispatch; class CC_DLL OSInterface { public: @@ -38,29 +37,13 @@ public: /** @brief Constructor of OSAbstractInterface. */ - explicit OSInterface(); - /** - @brief Constructor of OSAbstractInterface. - */ - explicit OSInterface(IEventDispatch *); + OSInterface() = default; + /** @brief Destructor of OSAbstractInterface. */ virtual ~OSInterface() = default; - /** - @brief Dispatch event. - @param type : Abstract event - */ - void dispatchEvent(const OSEvent &ev); - /** - @brief Dispatch touch event. - @param type : Touch event - */ - void dispatchTouchEvent(const TouchEvent &ev); - -protected: - IEventDispatch *_evDispatchInterface{nullptr}; private: CC_DISALLOW_COPY_MOVE_ASSIGN(OSInterface); diff --git a/native/cocos/platform/interfaces/modules/ISystemWindow.h b/native/cocos/platform/interfaces/modules/ISystemWindow.h index ac78725c14..0514dbf68d 100644 --- a/native/cocos/platform/interfaces/modules/ISystemWindow.h +++ b/native/cocos/platform/interfaces/modules/ISystemWindow.h @@ -34,7 +34,7 @@ namespace cc { class CC_DLL ISystemWindow : public OSInterface { public: - static const uint32_t mainWindowId = 1; + static constexpr uint32_t mainWindowId = 1; using Size = cc::Vec2; enum WindowFlags { diff --git a/native/cocos/platform/interfaces/modules/ISystemWindowManager.h b/native/cocos/platform/interfaces/modules/ISystemWindowManager.h index 830a7a0ec5..c3e063cc64 100644 --- a/native/cocos/platform/interfaces/modules/ISystemWindowManager.h +++ b/native/cocos/platform/interfaces/modules/ISystemWindowManager.h @@ -28,7 +28,6 @@ namespace cc { class ISystemWindow; -class OSEvent; struct ISystemWindowInfo { ccstd::string title; @@ -43,19 +42,19 @@ struct ISystemWindowInfo { // key: window id using SystemWindowMap = ccstd::unordered_map>; -/** +/** * Responsible for creating, finding ISystemWindow object and message handling */ class ISystemWindowManager : public OSInterface { public: - /** - * Initialize the NativeWindow environment + /** + * Initialize the NativeWindow environment * @return 0 Succeed -1 Failed */ virtual int init() = 0; /** - * Process messages at the PAL layer + * Process messages at the PAL layer */ virtual void processEvent(bool *quit) = 0; @@ -65,14 +64,14 @@ public: virtual void swapWindows() = 0; /** - * Create an ISystemWindow object - * @param info window description + * Create an ISystemWindow object + * @param info window description * @return The created ISystemWindow object,if failed then return nullptr */ virtual ISystemWindow *createWindow(const ISystemWindowInfo &info) = 0; /** - * Find an ISystemWindow object + * Find an ISystemWindow object * @param windowId unique ID of window */ virtual ISystemWindow *getWindow(uint32_t windowId) const = 0; diff --git a/native/cocos/platform/ios/AppDelegateBridge.mm b/native/cocos/platform/ios/AppDelegateBridge.mm index 89dc389f5a..285b2f9a17 100644 --- a/native/cocos/platform/ios/AppDelegateBridge.mm +++ b/native/cocos/platform/ios/AppDelegateBridge.mm @@ -59,14 +59,9 @@ cc::IOSPlatform *_platform = nullptr; _platform = nullptr; } -- (void)dispatchEvent:(const cc::OSEvent &)ev { - _platform->dispatchEvent(ev); -} - (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { - cc::DeviceEvent ev; - ev.type = cc::DeviceEvent::Type::MEMORY; - _platform->dispatchEvent(ev); + cc::events::LowMemory::broadcast(); } - (float)getPixelRatio { @@ -99,9 +94,7 @@ cc::IOSPlatform *_platform = nullptr; cc::DeviceEvent ev; cc::BasePlatform *platform = cc::BasePlatform::getPlatform(); cc::IScreen *screenIntf = platform->getInterface(); - ev.type = cc::DeviceEvent::Type::ORIENTATION; - ev.args[0].intVal = static_cast(screenIntf->getDeviceOrientation()); - _platform->dispatchEvent(ev); + cc::events::Orientation::broadcast((int)screenIntf->getDeviceOrientation()); float pixelRatio = screenIntf->getDevicePixelRatio(); cc::WindowEvent resizeEv; @@ -109,7 +102,7 @@ cc::IOSPlatform *_platform = nullptr; resizeEv.type = cc::WindowEvent::Type::RESIZED; resizeEv.width = size.width * pixelRatio; resizeEv.height = size.height * pixelRatio; - _platform->dispatchEvent(resizeEv); + cc::events::WindowEvent::broadcast(resizeEv); } - (void)dispatchTouchEvent:(cc::TouchEvent::Type)type touches:(NSSet *)touches withEvent:(UIEvent *)event { @@ -121,7 +114,7 @@ cc::IOSPlatform *_platform = nullptr; static_cast([touch locationInView:[touch view]].y), static_cast((intptr_t)touch)}); } - _platform->dispatchTouchEvent(touchEvent); + cc::events::Touch::broadcast(touchEvent); touchEvent.touches.clear(); } diff --git a/native/cocos/platform/ios/IOSPlatform.mm b/native/cocos/platform/ios/IOSPlatform.mm index f41d5e0376..2b7d8e9a72 100644 --- a/native/cocos/platform/ios/IOSPlatform.mm +++ b/native/cocos/platform/ios/IOSPlatform.mm @@ -133,7 +133,7 @@ void IOSPlatform::onPause() { cc::WindowEvent ev; ev.type = cc::WindowEvent::Type::HIDDEN; - dispatchEvent(ev); + cc::events::WindowEvent::broadcast(ev); } void IOSPlatform::onResume() { @@ -141,13 +141,13 @@ void IOSPlatform::onResume() { cc::WindowEvent ev; ev.type = cc::WindowEvent::Type::SHOW; - dispatchEvent(ev); + cc::events::WindowEvent::broadcast(ev); } void IOSPlatform::onClose() { cc::WindowEvent ev; ev.type = cc::WindowEvent::Type::CLOSE; - dispatchEvent(ev); + cc::events::WindowEvent::broadcast(ev); } ISystemWindow *IOSPlatform::createNativeWindow(uint32_t windowId, void *externalHandle) { diff --git a/native/cocos/platform/ios/View.mm b/native/cocos/platform/ios/View.mm index 9fbf7ea0a5..547eec5966 100644 --- a/native/cocos/platform/ios/View.mm +++ b/native/cocos/platform/ios/View.mm @@ -58,7 +58,7 @@ namespace { static_cast((intptr_t)touch)}); } CC_ASSERT(_platform != nullptr); - _platform->dispatchTouchEvent(touchEvent); + cc::events::Touch::broadcast(touchEvent); } - (id)initWithFrame:(CGRect)frame { diff --git a/native/cocos/platform/ios/modules/SystemWindow.mm b/native/cocos/platform/ios/modules/SystemWindow.mm index a5cc193749..0efb75cf05 100644 --- a/native/cocos/platform/ios/modules/SystemWindow.mm +++ b/native/cocos/platform/ios/modules/SystemWindow.mm @@ -46,7 +46,7 @@ void SystemWindow::copyTextToClipboard(const std::string& text) { } void SystemWindow::closeWindow() { // Force quit as there's no API to exit UIApplication - cc::EventDispatcher::dispatchCloseEvent(); + cc::events::Close::broadcast(); exit(0); } uintptr_t SystemWindow::getWindowHandle() const { diff --git a/native/cocos/platform/java/jni/JniCocosKeyCodeHandler.cpp b/native/cocos/platform/java/jni/JniCocosKeyCodeHandler.cpp index 92b69278fc..328bdf2278 100644 --- a/native/cocos/platform/java/jni/JniCocosKeyCodeHandler.cpp +++ b/native/cocos/platform/java/jni/JniCocosKeyCodeHandler.cpp @@ -32,7 +32,7 @@ #endif #include -#include "cocos/bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" #include "platform/java/jni/glue/JniNativeGlue.h" namespace { @@ -53,7 +53,7 @@ ccstd::unordered_map keyCodeMap = { ccstd::unordered_map keyCodeMap = {}; #endif //NOLINTNEXTLINE -void dispatchKeyCodeEvent(int keyCode, cc::KeyboardEvent &event) { +static void dispatchKeyCodeEvent(int keyCode, cc::KeyboardEvent &event) { if (keyCodeMap.count(keyCode) > 0) { keyCode = keyCodeMap[keyCode]; } else { diff --git a/native/cocos/platform/java/jni/JniCocosOrientationHelper.cpp b/native/cocos/platform/java/jni/JniCocosOrientationHelper.cpp index a753068212..6e9684d6fa 100644 --- a/native/cocos/platform/java/jni/JniCocosOrientationHelper.cpp +++ b/native/cocos/platform/java/jni/JniCocosOrientationHelper.cpp @@ -24,39 +24,26 @@ ****************************************************************************/ #include -#include "cocos/bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" #include "platform/interfaces/modules/Device.h" #include "platform/java/jni/JniHelper.h" #include "platform/java/jni/glue/JniNativeGlue.h" -#if CC_PLATFORM == CC_PLATFORM_ANDROID - #include "platform/BasePlatform.h" - #include "platform/android/AndroidPlatform.h" -#endif extern "C" { -//NOLINTNEXTLINE +// NOLINTNEXTLINE JNIEXPORT void JNICALL Java_com_cocos_lib_CocosOrientationHelper_nativeOnOrientationChanged(JNIEnv *env, jclass thiz, jint rotation) { int orientation; switch (rotation) { - case 0: //ROTATION_0 + case 0: // ROTATION_0 orientation = (int)cc::Device::Orientation::PORTRAIT; - case 1: //ROTATION_90 + case 1: // ROTATION_90 orientation = (int)cc::Device::Orientation::LANDSCAPE_RIGHT; - case 2: //ROTATION_180 + case 2: // ROTATION_180 orientation = (int)cc::Device::Orientation::PORTRAIT_UPSIDE_DOWN; - case 3: //ROTATION_270 + case 3: // ROTATION_270 orientation = (int)cc::Device::Orientation::LANDSCAPE_LEFT; } - - cc::DeviceEvent ev; - ev.type = cc::DeviceEvent::Type::ORIENTATION; - ev.args[0].intVal = orientation; -#if CC_PLATFORM == CC_PLATFORM_ANDROID - auto *platform = cc::BasePlatform::getPlatform(); - auto *androidPlatform = static_cast(platform); - androidPlatform->dispatchEvent(ev); -#else - JNI_NATIVE_GLUE()->dispatchEvent(ev); -#endif + // run callbacks in game thread? + cc::events::Orientation::broadcast(orientation); } } diff --git a/native/cocos/platform/java/jni/JniCocosTouchHandler.cpp b/native/cocos/platform/java/jni/JniCocosTouchHandler.cpp index d00f2c4ef1..238dc3c49f 100644 --- a/native/cocos/platform/java/jni/JniCocosTouchHandler.cpp +++ b/native/cocos/platform/java/jni/JniCocosTouchHandler.cpp @@ -24,7 +24,7 @@ ****************************************************************************/ #include -#include "cocos/bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" #include "platform/java/jni/JniHelper.h" #include "platform/java/jni/glue/JniNativeGlue.h" diff --git a/native/cocos/platform/java/jni/glue/JniNativeGlue.cpp b/native/cocos/platform/java/jni/glue/JniNativeGlue.cpp index a576717e25..643b44f6a5 100644 --- a/native/cocos/platform/java/jni/glue/JniNativeGlue.cpp +++ b/native/cocos/platform/java/jni/glue/JniNativeGlue.cpp @@ -26,10 +26,8 @@ #include "platform/java/jni/glue/JniNativeGlue.h" #include #include -#include "cocos/bindings/event/CustomEventTypes.h" -#include "cocos/bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" #include "platform/BasePlatform.h" -#include "platform/IEventDispatch.h" #include "platform/java/jni/JniImp.h" #include "platform/java/jni/glue/MessagePipe.h" #include "platform/java/jni/log.h" @@ -150,22 +148,6 @@ int JniNativeGlue::readCommandWithTimeout(CommandMsg* cmd, int delayMS) { return _messagePipe->readCommandWithTimeout(cmd, sizeof(CommandMsg), delayMS); } -void JniNativeGlue::setEventDispatch(IEventDispatch* eventDispatcher) { - _eventDispatcher = eventDispatcher; -} - -void JniNativeGlue::dispatchEvent(const OSEvent& ev) { - if (_eventDispatcher) { - _eventDispatcher->dispatchEvent(ev); - } -} - -void JniNativeGlue::dispatchTouchEvent(const TouchEvent& ev) { - if (_eventDispatcher) { - _eventDispatcher->dispatchTouchEvent(ev); - } -} - bool JniNativeGlue::isPause() const { if (!_animating) { return true; @@ -236,38 +218,26 @@ void JniNativeGlue::engineHandleCmd(JniCommand cmd) { isWindowInitialized = true; return; } - cc::CustomEvent event; - event.name = EVENT_RECREATE_WINDOW; - event.args->ptrVal = reinterpret_cast(getWindowHandle()); - dispatchEvent(event); + // FIXME: getWindowId + events::WindowRecreated::broadcast((uint32_t)(uintptr_t)getWindowHandle()); // NOLINT } break; case JniCommand::JNI_CMD_TERM_WINDOW: { - cc::CustomEvent event; - event.name = EVENT_DESTROY_WINDOW; - event.args->ptrVal = reinterpret_cast(getWindowHandle()); - dispatchEvent(event); + // FIXME: getWindowId + events::WindowDestroy::broadcast((uint32_t)(uintptr_t)getWindowHandle()); // NOLINT } break; case JniCommand::JNI_CMD_RESUME: { - WindowEvent ev; - ev.type = WindowEvent::Type::SHOW; - dispatchEvent(ev); + events::WindowChanged::broadcast(WindowEvent::Type::SHOW); } break; case JniCommand::JNI_CMD_PAUSE: { - WindowEvent ev; - ev.type = WindowEvent::Type::HIDDEN; - dispatchEvent(ev); + events::WindowChanged::broadcast(WindowEvent::Type::HIDDEN); } break; case JniCommand::JNI_CMD_DESTROY: { LOGV("APP_CMD_DESTROY"); - WindowEvent ev; - ev.type = WindowEvent::Type::CLOSE; - dispatchEvent(ev); + events::WindowChanged::broadcast(WindowEvent::Type::CLOSE); setRunning(false); } break; case JniCommand::JNI_CMD_LOW_MEMORY: { - DeviceEvent ev; - ev.type = DeviceEvent::Type::MEMORY; - dispatchEvent(ev); + events::LowMemory::broadcast(); break; } default: diff --git a/native/cocos/platform/java/jni/glue/JniNativeGlue.h b/native/cocos/platform/java/jni/glue/JniNativeGlue.h index c76e4c5ce9..1ab8782717 100644 --- a/native/cocos/platform/java/jni/glue/JniNativeGlue.h +++ b/native/cocos/platform/java/jni/glue/JniNativeGlue.h @@ -52,7 +52,6 @@ using NativeEnv = void*; //jnienv namespace cc { class IEventDispatch; -class OSEvent; class TouchEvent; class CC_DLL JniNativeGlue { @@ -104,10 +103,6 @@ public: int readCommand(CommandMsg* msg); int readCommandWithTimeout(CommandMsg* cmd, int delayMS); - void setEventDispatch(IEventDispatch* eventDispatcher); - void dispatchEvent(const OSEvent& ev); - void dispatchTouchEvent(const TouchEvent& ev); - void onPause(); void onResume(); void onLowMemory(); diff --git a/native/cocos/platform/java/modules/SystemWindow.cpp b/native/cocos/platform/java/modules/SystemWindow.cpp index 0fb43277be..107a6c6a6b 100644 --- a/native/cocos/platform/java/modules/SystemWindow.cpp +++ b/native/cocos/platform/java/modules/SystemWindow.cpp @@ -42,7 +42,7 @@ namespace { #ifndef JCLS_COCOSACTIVITY -#define JCLS_COCOSACTIVITY "com/cocos/lib/CocosActivity" + #define JCLS_COCOSACTIVITY "com/cocos/lib/CocosActivity" #endif } // namespace @@ -73,9 +73,9 @@ void SystemWindow::setWindowHandle(void *handle) { uintptr_t SystemWindow::getWindowHandle() const { #if (CC_PLATFORM == CC_PLATFORM_ANDROID) - std::lock_guard lock(const_cast(_handleMutex)); + std::lock_guard lock(const_cast(_handleMutex)); if (!_windowHandle) { - auto& future = const_cast&>(_windowHandlePromise); + auto &future = const_cast &>(_windowHandlePromise); future.get_future().get(); } CC_ASSERT(_windowHandle); @@ -101,7 +101,7 @@ void SystemWindow::closeWindow() { #if (CC_PLATFORM == CC_PLATFORM_ANDROID) finishActivity(); #else - cc::EventDispatcher::dispatchCloseEvent(); + events::Close::broadcast(); exit(0); //TODO(cc): better exit for ohos #endif } diff --git a/native/cocos/platform/java/modules/SystemWindowManager.cpp b/native/cocos/platform/java/modules/SystemWindowManager.cpp index 85bf910166..6b1dc9b6c8 100644 --- a/native/cocos/platform/java/modules/SystemWindowManager.cpp +++ b/native/cocos/platform/java/modules/SystemWindowManager.cpp @@ -29,7 +29,6 @@ namespace cc { -SystemWindowManager::SystemWindowManager() = default; int SystemWindowManager::init() { return 0; diff --git a/native/cocos/platform/java/modules/SystemWindowManager.h b/native/cocos/platform/java/modules/SystemWindowManager.h index bef5800bab..7053581e05 100644 --- a/native/cocos/platform/java/modules/SystemWindowManager.h +++ b/native/cocos/platform/java/modules/SystemWindowManager.h @@ -35,7 +35,7 @@ class ISystemWindow; class SystemWindowManager : public ISystemWindowManager { public: - SystemWindowManager(); + SystemWindowManager() = default; int init() override; void processEvent(bool *quit) override; diff --git a/native/cocos/platform/java/modules/XRInterface.cpp b/native/cocos/platform/java/modules/XRInterface.cpp index 4899e13137..e584253d89 100644 --- a/native/cocos/platform/java/modules/XRInterface.cpp +++ b/native/cocos/platform/java/modules/XRInterface.cpp @@ -168,7 +168,7 @@ static void dispatchGamepadEventInternal(const xr::XRControllerEvent &xrControll controllerInfo->napdId = 0; // xr only one gamepad connection controllerEvent.controllerInfos.emplace_back(controllerInfo); controllerEvent.type = ControllerEvent::Type::GAMEPAD; - static_cast(BasePlatform::getPlatform())->dispatchEvent(controllerEvent); + events::Controller::broadcast(controllerEvent); controllerEvent.type = ControllerEvent::Type::UNKNOWN; controllerEvent.controllerInfos.clear(); } @@ -304,7 +304,8 @@ static void dispatchHandleEventInternal(const xr::XRControllerEvent &xrControlle controllerInfo->napdId = 0; // xr only one handle connection controllerEvent.controllerInfos.emplace_back(controllerInfo); controllerEvent.type = ControllerEvent::Type::HANDLE; - EventDispatcher::dispatchControllerEvent(controllerEvent); + events::Controller::broadcast(controllerEvent); + controllerEvent.type = ControllerEvent::Type::UNKNOWN; controllerEvent.controllerInfos.clear(); } else { diff --git a/native/cocos/platform/linux/LinuxPlatform.cpp b/native/cocos/platform/linux/LinuxPlatform.cpp index 6bfcd1c374..a9984176ce 100644 --- a/native/cocos/platform/linux/LinuxPlatform.cpp +++ b/native/cocos/platform/linux/LinuxPlatform.cpp @@ -64,7 +64,7 @@ int32_t LinuxPlatform::init() { registerInterface(std::make_shared()); registerInterface(std::make_shared()); registerInterface(std::make_shared()); - _windowManager = std::make_shared(this); + _windowManager = std::make_shared(); registerInterface(_windowManager); registerInterface(std::make_shared()); return _windowManager->init(); diff --git a/native/cocos/platform/linux/modules/SystemWindow.cpp b/native/cocos/platform/linux/modules/SystemWindow.cpp index 2bad5dcfa3..84a81997d3 100644 --- a/native/cocos/platform/linux/modules/SystemWindow.cpp +++ b/native/cocos/platform/linux/modules/SystemWindow.cpp @@ -33,8 +33,7 @@ #include "SDL2/SDL.h" #include "SDL2/SDL_main.h" #include "SDL2/SDL_syswm.h" -#include "bindings/event/EventDispatcher.h" -#include "platform/IEventDispatch.h" +#include "engine/EngineEvents.h" #include "platform/SDLHelper.h" namespace cc { diff --git a/native/cocos/platform/linux/modules/SystemWindowManager.cpp b/native/cocos/platform/linux/modules/SystemWindowManager.cpp index cc3f045981..e2e0f45f6e 100644 --- a/native/cocos/platform/linux/modules/SystemWindowManager.cpp +++ b/native/cocos/platform/linux/modules/SystemWindowManager.cpp @@ -31,9 +31,6 @@ #include "platform/linux/modules/SystemWindow.h" namespace cc { -SystemWindowManager::SystemWindowManager(IEventDispatch *delegate) -: _eventDispatcher(delegate) { -} int SystemWindowManager::init() { return SDLHelper::init(); @@ -45,12 +42,12 @@ void SystemWindowManager::processEvent(bool *quit) { SDL_Window *sdlWindow = SDL_GetWindowFromID(sdlEvent.window.windowID); // SDL_Event like SDL_QUIT does not associate a window if (!sdlWindow) { - SDLHelper::dispatchSDLEvent(_eventDispatcher, 0, sdlEvent, quit); + SDLHelper::dispatchSDLEvent(0, sdlEvent, quit); } else { ISystemWindow *window = getWindowFromSDLWindow(sdlWindow); CC_ASSERT(window); uint32_t windowId = window->getWindowId(); - SDLHelper::dispatchSDLEvent(_eventDispatcher, windowId, sdlEvent, quit); + SDLHelper::dispatchSDLEvent(windowId, sdlEvent, quit); } if (*quit) { break; diff --git a/native/cocos/platform/linux/modules/SystemWindowManager.h b/native/cocos/platform/linux/modules/SystemWindowManager.h index c26c44567f..c19b454fe0 100644 --- a/native/cocos/platform/linux/modules/SystemWindowManager.h +++ b/native/cocos/platform/linux/modules/SystemWindowManager.h @@ -36,7 +36,7 @@ class ISystemWindow; class SystemWindowManager : public ISystemWindowManager { public: - SystemWindowManager(IEventDispatch *delegate); + SystemWindowManager() = default; int init() override; void processEvent(bool *quit) override; @@ -52,6 +52,5 @@ private: uint32_t _nextWindowId{1}; // start from 1, 0 means an invalid ID SystemWindowMap _windows; - IEventDispatch *_eventDispatcher{nullptr}; }; } // namespace cc diff --git a/native/cocos/platform/mac/AppDelegate.mm b/native/cocos/platform/mac/AppDelegate.mm index 6d90e781ed..53ab328859 100644 --- a/native/cocos/platform/mac/AppDelegate.mm +++ b/native/cocos/platform/mac/AppDelegate.mm @@ -27,7 +27,7 @@ #include "base/std/container/string.h" //#import "Game.h" #import "ViewController.h" -#include "cocos/bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" #include "platform/mac/MacPlatform.h" @interface AppDelegate () { @@ -115,8 +115,4 @@ return YES; } -- (void)dispatchEvent:(const cc::OSEvent&)ev { - _platform->dispatchEvent(ev); -} - @end diff --git a/native/cocos/platform/mac/MacPlatform.mm b/native/cocos/platform/mac/MacPlatform.mm index 6e6b6c0b62..0509d60e96 100644 --- a/native/cocos/platform/mac/MacPlatform.mm +++ b/native/cocos/platform/mac/MacPlatform.mm @@ -148,7 +148,7 @@ void MacPlatform::onPause() { cc::WindowEvent ev; ev.type = cc::WindowEvent::Type::HIDDEN; - dispatchEvent(ev); + cc::events::WindowEvent::broadcast(ev); } void MacPlatform::onResume() { @@ -156,13 +156,13 @@ void MacPlatform::onResume() { cc::WindowEvent ev; ev.type = cc::WindowEvent::Type::SHOW; - dispatchEvent(ev); + cc::events::WindowEvent::broadcast(ev); } void MacPlatform::onClose() { cc::WindowEvent ev; ev.type = cc::WindowEvent::Type::CLOSE; - dispatchEvent(ev); + cc::events::WindowEvent::broadcast(ev); } cc::ISystemWindow *MacPlatform::createNativeWindow(uint32_t windowId, void *externalHandle) { diff --git a/native/cocos/platform/mac/View.mm b/native/cocos/platform/mac/View.mm index a3a858fdde..b707ff4bcb 100644 --- a/native/cocos/platform/mac/View.mm +++ b/native/cocos/platform/mac/View.mm @@ -87,7 +87,6 @@ ev.width = static_cast(size.width); ev.height = static_cast(size.height); [_delegate dispatchEvent:ev]; - //cc::EventDispatcher::dispatchResizeEvent(, ); } - (void)displayLayer:(CALayer *)layer { @@ -131,13 +130,7 @@ if (cc::EventDispatcher::initialized()) { auto *windowMgr = CC_GET_PLATFORM_INTERFACE(cc::SystemWindowManager); auto *window = windowMgr->getWindowFromNSWindow([self window]); - - cc::WindowEvent ev; - ev.type = cc::WindowEvent::Type::RESIZED; - ev.width = static_cast(width); - ev.height = static_cast(height); - ev.windowId = window->getWindowId(); - cc::EventDispatcher::dispatchResizeEvent(ev); + cc::events::Resize::broadcast(static_cast(width), static_cast(height), window->getWindowId()); } } @@ -286,7 +279,7 @@ _mouseEvent.button = button; _mouseEvent.x = pos.x; _mouseEvent.y = contentRect.size.height - pos.y; - [_delegate dispatchEvent:_mouseEvent]; + cc::events::Mouse::broadcast(_mouseEvent); } @end diff --git a/native/cocos/platform/ohos/OhosPlatform.cpp b/native/cocos/platform/ohos/OhosPlatform.cpp index 24141a1ff7..2155e28e36 100644 --- a/native/cocos/platform/ohos/OhosPlatform.cpp +++ b/native/cocos/platform/ohos/OhosPlatform.cpp @@ -75,7 +75,6 @@ void OhosPlatform::waitWindowInitialized() { break; } } - _jniNativeGlue->setEventDispatch(this); } int32_t OhosPlatform::loop() { diff --git a/native/cocos/platform/ohos/View.cpp b/native/cocos/platform/ohos/View.cpp index 732cab98ff..1c3601101f 100644 --- a/native/cocos/platform/ohos/View.cpp +++ b/native/cocos/platform/ohos/View.cpp @@ -24,13 +24,12 @@ ****************************************************************************/ #include "View.h" -#include "cocos/bindings/event/CustomEventTypes.h" -#include "cocos/bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" #include "platform/Application.h" #include "platform/ohos//jni/JniCocosAbility.h" #include "platform/ohos/jni/AbilityConsts.h" -//NOLINTNEXTLINE +// NOLINTNEXTLINE using namespace cc::ohos; namespace cc { @@ -44,17 +43,13 @@ void View::engineHandleCmd(int cmd) { isWindowInitialized = true; return; } else { - cc::CustomEvent event; - event.name = EVENT_RECREATE_WINDOW; - event.args->ptrVal = cocosApp.pendingWindow; - cc::EventDispatcher::dispatchCustomEvent(event); + // FIXME: getWindowId + events::WindowRecreated::broadcast((uint32_t)(uintptr_t)cocosApp.pendingWindow); } break; case ABILITY_CMD_TERM_WINDOW: { - cc::CustomEvent event; - event.name = EVENT_DESTROY_WINDOW; - event.args->ptrVal = cocosApp.pendingWindow; - cc::EventDispatcher::dispatchCustomEvent(event); + // FIXME: getWindowId + events::WindowDestroy::broadcast((uint32_t)(uintptr_t)cocosApp.pendingWindow); } break; case ABILITY_CMD_RESUME: if (Application::getInstance()) { @@ -67,7 +62,7 @@ void View::engineHandleCmd(int cmd) { } break; case ABILITY_CMD_LOW_MEMORY: - cc::EventDispatcher::dispatchMemoryWarningEvent(); + events::LowMemory::broadcast(); break; default: break; diff --git a/native/cocos/platform/win32/WindowsPlatform.cpp b/native/cocos/platform/win32/WindowsPlatform.cpp index 75e446f94c..ded80cd2d2 100644 --- a/native/cocos/platform/win32/WindowsPlatform.cpp +++ b/native/cocos/platform/win32/WindowsPlatform.cpp @@ -98,7 +98,7 @@ int32_t WindowsPlatform::init() { registerInterface(std::make_shared()); registerInterface(std::make_shared()); registerInterface(std::make_shared()); - _windowManager = std::make_shared(this); + _windowManager = std::make_shared(); registerInterface(_windowManager); registerInterface(std::make_shared()); diff --git a/native/cocos/platform/win32/modules/SystemWindow.cpp b/native/cocos/platform/win32/modules/SystemWindow.cpp index 88c5683f5e..c95a50f5e6 100644 --- a/native/cocos/platform/win32/modules/SystemWindow.cpp +++ b/native/cocos/platform/win32/modules/SystemWindow.cpp @@ -27,8 +27,7 @@ #include #include #include "base/Log.h" -#include "bindings/event/EventDispatcher.h" -#include "platform/IEventDispatch.h" +#include "engine/EngineEvents.h" #include "platform/SDLHelper.h" #include "platform/win32/WindowsPlatform.h" #include "sdl2/SDL_clipboard.h" diff --git a/native/cocos/platform/win32/modules/SystemWindowManager.cpp b/native/cocos/platform/win32/modules/SystemWindowManager.cpp index 125c50a7e0..6b0eb496e4 100644 --- a/native/cocos/platform/win32/modules/SystemWindowManager.cpp +++ b/native/cocos/platform/win32/modules/SystemWindowManager.cpp @@ -32,10 +32,6 @@ namespace cc { -SystemWindowManager::SystemWindowManager(IEventDispatch *delegate) -: _eventDispatcher(delegate) { -} - int SystemWindowManager::init() { return SDLHelper::init(); } @@ -46,12 +42,12 @@ void SystemWindowManager::processEvent(bool *quit) { SDL_Window *sdlWindow = SDL_GetWindowFromID(sdlEvent.window.windowID); // SDL_Event like SDL_QUIT does not associate a window if (!sdlWindow) { - SDLHelper::dispatchSDLEvent(_eventDispatcher, 0, sdlEvent, quit); + SDLHelper::dispatchSDLEvent(0, sdlEvent, quit); } else { ISystemWindow *window = getWindowFromSDLWindow(sdlWindow); CC_ASSERT(window); uint32_t windowId = window->getWindowId(); - SDLHelper::dispatchSDLEvent(_eventDispatcher, windowId, sdlEvent, quit); + SDLHelper::dispatchSDLEvent(windowId, sdlEvent, quit); } if (*quit) { break; diff --git a/native/cocos/platform/win32/modules/SystemWindowManager.h b/native/cocos/platform/win32/modules/SystemWindowManager.h index b1f5dc85e5..e35c844b71 100644 --- a/native/cocos/platform/win32/modules/SystemWindowManager.h +++ b/native/cocos/platform/win32/modules/SystemWindowManager.h @@ -36,7 +36,7 @@ class ISystemWindow; class SystemWindowManager : public ISystemWindowManager { public: - explicit SystemWindowManager(IEventDispatch *delegate); + SystemWindowManager() = default; int init() override; void processEvent(bool *quit) override; @@ -52,6 +52,5 @@ private: uint32_t _nextWindowId{1}; // start from 1, 0 means an invalid ID SystemWindowMap _windows; - IEventDispatch *_eventDispatcher{nullptr}; }; } // namespace cc diff --git a/native/cocos/renderer/GFXDeviceManager.h b/native/cocos/renderer/GFXDeviceManager.h index 3f619fc6f1..8e7ebfa5fd 100644 --- a/native/cocos/renderer/GFXDeviceManager.h +++ b/native/cocos/renderer/GFXDeviceManager.h @@ -25,8 +25,7 @@ #pragma once -#include "bindings/event/CustomEventTypes.h" -#include "bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" #include "gfx-agent/DeviceAgent.h" #include "gfx-validator/DeviceValidator.h" diff --git a/native/cocos/renderer/gfx-base/GFXDeviceObject.h b/native/cocos/renderer/gfx-base/GFXDeviceObject.h index 96b2fc96ea..706180e4c5 100644 --- a/native/cocos/renderer/gfx-base/GFXDeviceObject.h +++ b/native/cocos/renderer/gfx-base/GFXDeviceObject.h @@ -23,6 +23,7 @@ THE SOFTWARE. #include "base/Ptr.h" #include "base/Macros.h" +#include namespace cc { namespace gfx { diff --git a/native/cocos/renderer/gfx-metal/MTLDevice.mm b/native/cocos/renderer/gfx-metal/MTLDevice.mm index f9fd4f946d..b53abcdd96 100644 --- a/native/cocos/renderer/gfx-metal/MTLDevice.mm +++ b/native/cocos/renderer/gfx-metal/MTLDevice.mm @@ -43,8 +43,6 @@ #import "MTLSwapchain.h" #import "MTLTexture.h" #import "base/Log.h" -#import "cocos/bindings/event/CustomEventTypes.h" -#import "cocos/bindings/event/EventDispatcher.h" #import "profiler/Profiler.h" @@ -142,8 +140,6 @@ bool CCMTLDevice::doInit(const DeviceInfo &info) { cmdBuffInfo.queue = _queue; _cmdBuff = createCommandBuffer(cmdBuffInfo); - // _memoryAlarmListenerId = EventDispatcher::addCustomEventListener(EVENT_MEMORY_WARNING, std::bind(&CCMTLDevice::onMemoryWarning, this)); - CCMTLGPUGarbageCollectionPool::getInstance()->initialize(std::bind(&CCMTLDevice::currentFrameIndex, this)); CC_LOG_INFO("Metal Feature Set: %s", mu::featureSetToString(MTLFeatureSet(_mtlFeatureSet)).c_str()); @@ -152,10 +148,6 @@ bool CCMTLDevice::doInit(const DeviceInfo &info) { } void CCMTLDevice::doDestroy() { - // if (_memoryAlarmListenerId != 0) { - // EventDispatcher::removeCustomEventListener(EVENT_MEMORY_WARNING, _memoryAlarmListenerId); - // _memoryAlarmListenerId = 0; - // } CC_SAFE_DELETE(_gpuDeviceObj); diff --git a/native/cocos/scene/Model.cpp b/native/cocos/scene/Model.cpp index 988935e861..bde5b4832c 100644 --- a/native/cocos/scene/Model.cpp +++ b/native/cocos/scene/Model.cpp @@ -28,7 +28,6 @@ #include "core/Root.h" #include "core/TypedArray.h" #include "core/assets/Material.h" -#include "core/event/EventTypesToJS.h" #include "gfx-base/GFXTexture.h" #include "gi/light-probe/LightProbe.h" #include "gi/light-probe/SH.h" @@ -105,7 +104,7 @@ void Model::updateTransform(uint32_t stamp) { CC_PROFILE(ModelUpdateTransform); if (isModelImplementedInJS()) { if (!_isCalledFromJS) { - _eventProcessor.emit(EventTypesToJS::MODEL_UPDATE_TRANSFORM, stamp); + emit(stamp); _isCalledFromJS = false; return; } @@ -155,7 +154,7 @@ void Model::updateUBOs(uint32_t stamp) { CC_PROFILE(ModelUpdateUBOs); if (isModelImplementedInJS()) { if (!_isCalledFromJS) { - _eventProcessor.emit(EventTypesToJS::MODEL_UPDATE_UBO, stamp); + emit(stamp); _isCalledFromJS = false; return; } @@ -371,7 +370,7 @@ ccstd::vector Model::getMacroPatches(index_t subModelIndex) { if (isModelImplementedInJS()) { if (!_isCalledFromJS) { ccstd::vector macroPatches; - _eventProcessor.emit(EventTypesToJS::MODEL_GET_MACRO_PATCHES, subModelIndex, ¯oPatches); + emit(subModelIndex, ¯oPatches); _isCalledFromJS = false; return macroPatches; } @@ -414,7 +413,7 @@ void Model::updateAttributesAndBinding(index_t subModelIndex) { void Model::updateInstancedAttributes(const ccstd::vector &attributes, SubModel *subModel) { if (isModelImplementedInJS()) { if (!_isCalledFromJS) { - _eventProcessor.emit(EventTypesToJS::MODEL_UPDATE_INSTANCED_ATTRIBUTES, attributes, subModel); + emit(attributes, subModel); // FIXME _isCalledFromJS = false; return; } @@ -467,7 +466,7 @@ void Model::initWorldBoundDescriptors(index_t /*subModelIndex*/) { void Model::updateLocalDescriptors(index_t subModelIndex, gfx::DescriptorSet *descriptorSet) { if (isModelImplementedInJS()) { if (!_isCalledFromJS) { - _eventProcessor.emit(EventTypesToJS::MODEL_UPDATE_LOCAL_DESCRIPTORS, subModelIndex, descriptorSet); + emit(subModelIndex, descriptorSet); _isCalledFromJS = false; return; } @@ -481,7 +480,7 @@ void Model::updateLocalDescriptors(index_t subModelIndex, gfx::DescriptorSet *de void Model::updateLocalSHDescriptors(index_t subModelIndex, gfx::DescriptorSet *descriptorSet) { if (isModelImplementedInJS()) { if (!_isCalledFromJS) { - _eventProcessor.emit(EventTypesToJS::MODEL_UPDATE_LOCAL_SH_DESCRIPTORS, subModelIndex, descriptorSet); + emit(subModelIndex, descriptorSet); _isCalledFromJS = false; return; } @@ -495,7 +494,7 @@ void Model::updateLocalSHDescriptors(index_t subModelIndex, gfx::DescriptorSet * void Model::updateWorldBoundDescriptors(index_t subModelIndex, gfx::DescriptorSet *descriptorSet) { if (isModelImplementedInJS()) { if (!_isCalledFromJS) { - _eventProcessor.emit(EventTypesToJS::MODEL_UPDATE_WORLD_BOUND_DESCRIPTORS, subModelIndex, descriptorSet); + emit(subModelIndex, descriptorSet); _isCalledFromJS = false; return; } diff --git a/native/cocos/scene/Model.h b/native/cocos/scene/Model.h index 1defc4751f..ac37a6543f 100644 --- a/native/cocos/scene/Model.h +++ b/native/cocos/scene/Model.h @@ -33,7 +33,7 @@ #include "core/assets/RenderingSubMesh.h" #include "core/assets/Texture2D.h" #include "core/builtin/BuiltinResMgr.h" -#include "core/event/CallbacksInvoker.h" +#include "core/event/EventTarget.h" #include "core/geometry/AABB.h" #include "core/scene-graph/Layers.h" #include "core/scene-graph/Node.h" @@ -57,7 +57,18 @@ class Octree; class Pass; struct IMacroPatch; -class Model : public RefCounted { +class Model : public RefCounted, public event::EventTarget { + IMPL_EVENT_TARGET(Model) + + DECLARE_TARGET_EVENT_BEGIN(Model) + TARGET_EVENT_ARG1(UpdateTransform, uint32_t) + TARGET_EVENT_ARG1(UpdateUBO, uint32_t) + TARGET_EVENT_ARG2(UpdateLocalSHDescriptor, index_t, gfx::DescriptorSet *) + TARGET_EVENT_ARG2(UpdateLocalDescriptors, index_t, gfx::DescriptorSet *) + TARGET_EVENT_ARG2(UpdateWorldBound, index_t, gfx::DescriptorSet *) + TARGET_EVENT_ARG2(UpdateInstancedAttributes, const std::vector &, SubModel *) + TARGET_EVENT_ARG2(GetMacroPatches, index_t, std::vector *) + DECLARE_TARGET_EVENT_END() public: enum class Type { DEFAULT, @@ -170,7 +181,6 @@ public: // For JS inline void setCalledFromJS(bool v) { _isCalledFromJS = v; } - inline CallbacksInvoker &getEventProcessor() { return _eventProcessor; } inline void setLocalDataUpdated(bool v) { _localDataUpdated = v; } inline void setWorldBounds(geometry::AABB *bounds) { _worldBounds = bounds; @@ -225,7 +235,7 @@ protected: Vec4 _lightmapUVParam; // For JS - CallbacksInvoker _eventProcessor; + // CallbacksInvoker _eventProcessor; ccstd::vector> _subModels; private: diff --git a/native/cocos/ui/edit-box/EditBox-android.cpp b/native/cocos/ui/edit-box/EditBox-android.cpp index 7deab95cbf..5c63e888ef 100644 --- a/native/cocos/ui/edit-box/EditBox-android.cpp +++ b/native/cocos/ui/edit-box/EditBox-android.cpp @@ -24,7 +24,7 @@ ****************************************************************************/ #include "EditBox.h" -#include "cocos/bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_global.h" #include "platform/java/jni/JniHelper.h" diff --git a/native/cocos/ui/edit-box/EditBox-ios.mm b/native/cocos/ui/edit-box/EditBox-ios.mm index c79162b0b2..06eb1aea71 100644 --- a/native/cocos/ui/edit-box/EditBox-ios.mm +++ b/native/cocos/ui/edit-box/EditBox-ios.mm @@ -53,8 +53,7 @@ #include "EditBox.h" #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_global.h" -#include "cocos/bindings/event/EventDispatcher.h" -#include "cocos/bindings/event/CustomEventTypes.h"" +#include "engine/EngineEvents.h" #import #define ITEM_MARGIN_WIDTH 10 @@ -289,6 +288,10 @@ static ButtonHandler* btnHandler = nil; //recently there'ill be only 2 elements NSMutableDictionary* textInputDictionnary; InputBoxPair* curView; + + cc::events::Resize::Listener resizeListener; + cc::events::Touch::Listener touchListener; + cc::events::Close::Listener closeListener; } static EditboxManager *instance = nil; @@ -322,14 +325,17 @@ static EditboxManager *instance = nil; return nil; } - cc::EventDispatcher::addCustomEventListener(EVENT_RESIZE, [&](const cc::CustomEvent& event) -> void { + resizeListener.bind([&](int /*width*/, int /*height*/ , uint32_t /*windowId*/) { [[EditboxManager sharedInstance] onOrientationChanged]; }); //"onTouchStart" is a sub event for TouchEvent, so we can only add listener for this sub event rather than TouchEvent itself. - cc::EventDispatcher::addCustomEventListener("onTouchStart", [&](const cc::CustomEvent& event) -> void { - cc::EditBox::complete(); + touchListener.bind([&](const cc::TouchEvent& event) { + if(event.type == cc::TouchEvent::Type::BEGAN) { + cc::EditBox::complete(); + } }); - cc::EventDispatcher::addCustomEventListener(EVENT_CLOSE, [&](const cc::CustomEvent& event) -> void { + + closeListener.bind([&]() { [[EditboxManager sharedInstance] dealloc]; }); } diff --git a/native/cocos/ui/edit-box/EditBox-ohos.cpp b/native/cocos/ui/edit-box/EditBox-ohos.cpp index 5b7e2af372..5f07fd2ede 100644 --- a/native/cocos/ui/edit-box/EditBox-ohos.cpp +++ b/native/cocos/ui/edit-box/EditBox-ohos.cpp @@ -24,7 +24,7 @@ ****************************************************************************/ #include "EditBox.h" -#include "cocos/bindings/event/EventDispatcher.h" +#include "engine/EngineEvents.h" #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_global.h" //#include "platform/Application.h" diff --git a/native/tests/.gitignore b/native/tests/.gitignore new file mode 100644 index 0000000000..5bd65451ae --- /dev/null +++ b/native/tests/.gitignore @@ -0,0 +1 @@ +unit-test-win64 diff --git a/native/tools/simulator/frameworks/runtime-src/Classes/Game.cpp b/native/tools/simulator/frameworks/runtime-src/Classes/Game.cpp index 92d899a8c3..e9b788c8f9 100644 --- a/native/tools/simulator/frameworks/runtime-src/Classes/Game.cpp +++ b/native/tools/simulator/frameworks/runtime-src/Classes/Game.cpp @@ -24,8 +24,6 @@ ****************************************************************************/ #include "Game.h" #include "cocos/application/ApplicationManager.h" -#include "cocos/bindings/event/CustomEventTypes.h" -#include "cocos/bindings/event/EventDispatcher.h" #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_classtype.h" #include "cocos/bindings/manual/jsb_global.h" diff --git a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.h b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.h index 10e4892aa4..5d3e3061ae 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.h +++ b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.h @@ -2,19 +2,19 @@ Copyright (c) 2010 cocos2d-x.org Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - + http://www.cocos2d-x.org - + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -24,14 +24,13 @@ THE SOFTWARE. ****************************************************************************/ - //#import //#import "ConsoleWindowController.h" #include +#include "Game.h" #include "ProjectConfig/ProjectConfig.h" #include "ProjectConfig/SimulatorConfig.h" -#include "Game.h" class SimulatorApp { public: @@ -40,6 +39,7 @@ public: int run(); virtual int getWidth() const; virtual int getHegith() const; + protected: SimulatorApp(); diff --git a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.mm b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.mm index 6daa8746d1..989eac59ca 100755 --- a/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.mm +++ b/native/tools/simulator/frameworks/runtime-src/proj.ios_mac/mac/SimulatorApp.mm @@ -65,6 +65,8 @@ //console pipe NSPipe *_pipe; NSFileHandle *_pipeReadHandle; + + SimulatorAppEvent::Listener _appListener; } @property (nonatomic, assign) IBOutlet NSMenu* menu; @@ -532,10 +534,9 @@ std::string getCurAppName(void) ProjectConfig &project = _project; - EventDispatcher::CustomEventListener listener = [self, &project, scaleMenuVector](const CustomEvent& event){ - auto menuEvent = dynamic_cast(event); + _appListener.bind([self, &project, scaleMenuVector](const CustomAppEvent& menuEvent){ rapidjson::Document dArgParse; - dArgParse.Parse<0>(menuEvent.getDataString().c_str()); + dArgParse.Parse<0>(menuEvent.dataString.c_str()); if (dArgParse.HasMember("name")) { @@ -543,7 +544,7 @@ std::string getCurAppName(void) if (strcmd == "menuClicked") { - player::PlayerMenuItem *menuItem = static_cast(menuEvent.args[0].ptrVal); + player::PlayerMenuItem *menuItem = reinterpret_cast(menuEvent.menuItem); if (menuItem) { if (menuItem->isChecked()) @@ -609,8 +610,7 @@ std::string getCurAppName(void) } } } - }; - EventDispatcher::addCustomEventListener(kAppEventName, listener); + }); } diff --git a/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorApp.cpp b/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorApp.cpp index 419a28c2f5..67a4c82345 100644 --- a/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorApp.cpp +++ b/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorApp.cpp @@ -467,15 +467,14 @@ void SimulatorApp::setupUI() { HWND& hwnd = _hwnd; ProjectConfig& project = _project; - EventDispatcher::CustomEventListener listener = [this, &hwnd, &project, scaleMenuVector](const CustomEvent& event) { - auto menuEvent = dynamic_cast(event); + _appListener.bind([this, &hwnd, &project, scaleMenuVector](const CustomAppEvent& menuEvent) { rapidjson::Document dArgParse; - dArgParse.Parse<0>(menuEvent.getDataString().c_str()); + dArgParse.Parse<0>(menuEvent.dataString.c_str()); if (dArgParse.HasMember("name")) { string strcmd = dArgParse["name"].GetString(); if (strcmd == "menuClicked") { - player::PlayerMenuItem* menuItem = static_cast(menuEvent.args[0].ptrVal); + player::PlayerMenuItem* menuItem = reinterpret_cast(menuEvent.menuItem); if (menuItem) { if (menuItem->isChecked()) { return; @@ -524,8 +523,7 @@ void SimulatorApp::setupUI() { } } } - }; - EventDispatcher::addCustomEventListener(kAppEventName, listener); + }); } void SimulatorApp::setZoom(float frameScale) { @@ -707,15 +705,14 @@ LRESULT CALLBACK SimulatorApp::windowProc(HWND hWnd, UINT uMsg, WPARAM wParam, L auto menuItem = menuService->getItemByCommandId(menuId); if (menuItem) { CustomAppEvent event(kAppEventName, APP_EVENT_MENU); - std::stringstream buf; buf << "{\"data\":\"" << menuItem->getMenuId().c_str() << "\""; buf << ",\"name\":" << "\"menuClicked\"" << "}"; - event.setDataString(buf.str()); - event.args[0].ptrVal = (void*)menuItem; - cc::EventDispatcher::dispatchCustomEvent(event); + event.dataString = buf.str(); + event.menuItem = (void*)menuItem; + SimulatorAppEvent::broadcast(event); } if (menuId == ID_HELP_ABOUT) { diff --git a/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorApp.h b/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorApp.h index 73769f08b6..5dc858b3af 100644 --- a/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorApp.h +++ b/native/tools/simulator/frameworks/runtime-src/proj.win32/SimulatorApp.h @@ -25,6 +25,7 @@ #pragma once +#include "CustomAppEvent.h" #include "Game.h" #include "ProjectConfig/ProjectConfig.h" #include "ProjectConfig/SimulatorConfig.h" @@ -55,12 +56,14 @@ protected: SimulatorApp(); static SimulatorApp *_instance; - ProjectConfig _project; - HWND _hwnd; - HWND _hwndConsole; + ProjectConfig _project; + HWND _hwnd; + HWND _hwndConsole; FILE *_writeDebugLogFile; + SimulatorAppEvent::Listener _appListener; + // void setupUI(); void setZoom(float frameScale); @@ -76,10 +79,10 @@ protected: void onDrop(const std::string &path); // helper - std::string convertPathFormatToUnixStyle(const std::string &path); - std::string getUserDocumentPath(); - std::string getApplicationExePath(); - std::string getApplicationPath(); + std::string convertPathFormatToUnixStyle(const std::string &path); + std::string getUserDocumentPath(); + std::string getApplicationExePath(); + std::string getApplicationPath(); static char *convertTCharToUtf8(const TCHAR *src); static LRESULT CALLBACK windowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); diff --git a/native/tools/simulator/libsimulator/CMakeLists.txt b/native/tools/simulator/libsimulator/CMakeLists.txt index e740bc4f65..78f6d24d83 100644 --- a/native/tools/simulator/libsimulator/CMakeLists.txt +++ b/native/tools/simulator/libsimulator/CMakeLists.txt @@ -93,7 +93,6 @@ libsimulator_source_files( lib/runtime/VisibleRect.h ) libsimulator_source_files( - lib/CustomAppEvent.cpp lib/CustomAppEvent.h lib/AppLang.cpp lib/AppLang.h diff --git a/native/tools/simulator/libsimulator/lib/CustomAppEvent.h b/native/tools/simulator/libsimulator/lib/CustomAppEvent.h index 9efd3b6532..bac0c49a3c 100644 --- a/native/tools/simulator/libsimulator/lib/CustomAppEvent.h +++ b/native/tools/simulator/libsimulator/lib/CustomAppEvent.h @@ -39,8 +39,7 @@ #include "json/stringbuffer.h" #include "json/writer.h" -#include "cocos/bindings/event/CustomEventTypes.h" -#include "cocos/bindings/event/EventDispatcher.h" +#include "cocos/core/event/EventBus.h" enum { APP_EVENT_MENU = 1, @@ -49,23 +48,17 @@ enum { #define kAppEventName "APP.EVENT" -class CC_LIBSIM_DLL CustomAppEvent : public cc::CustomEvent { -public: +struct CC_LIBSIM_DLL CustomAppEvent final { /** Constructor */ - CustomAppEvent(const std::string &eventName, int type); + CustomAppEvent(const std::string &eventName, int type) : eventName(eventName), eventType(type) {} - /** Gets event name */ - inline const std::string &getEventName() const { return _eventName; }; - - void setEventType(int type); - int getEventType(); - void setDataString(std::string data); - std::string getDataString(); - -protected: - std::string _eventName; - std::string _dataString; - int _eventType; + std::string eventName; + std::string dataString; + int eventType; + void *menuItem{nullptr}; }; +DECLARE_EVENT_BUS(Simulator) +DECLARE_BUS_EVENT_ARG1(SimulatorAppEvent, Simulator, const CustomAppEvent &) + #endif /* defined(__Simulator__AppEvent__) */ diff --git a/native/tools/simulator/libsimulator/lib/platform/mac/PlayerMenuServiceMac.mm b/native/tools/simulator/libsimulator/lib/platform/mac/PlayerMenuServiceMac.mm index 94985d0028..73fb4120aa 100755 --- a/native/tools/simulator/libsimulator/lib/platform/mac/PlayerMenuServiceMac.mm +++ b/native/tools/simulator/libsimulator/lib/platform/mac/PlayerMenuServiceMac.mm @@ -115,9 +115,9 @@ static bool __G_IS_MENUBAR_ENABLED__ = true; // WTF std::stringstream buf; buf << "{\"data\":\"" << self.macMenuItem->getMenuId().c_str() << "\""; buf << ",\"name\":" << "\"menuClicked\"" << "}"; - event.setDataString(buf.str()); - event.args[0].ptrVal = (void*)self.macMenuItem; - cc::EventDispatcher::dispatchCustomEvent(event); + event.dataString = buf.str(); + event.menuItem = (void*)self.macMenuItem; + SimulatorAppEvent::broadcast(event); } -(BOOL) validateMenuItem:(NSMenuItem *)menuItem diff --git a/native/tools/swig-config/2d.i b/native/tools/swig-config/2d.i index 001d181ecf..53810c1216 100644 --- a/native/tools/swig-config/2d.i +++ b/native/tools/swig-config/2d.i @@ -169,6 +169,8 @@ %import "base/memory/Memory.h" %import "base/RefCounted.h" +%import "core/event/Event.h" + %import "renderer/gfx-base/GFXObject.h" %import "renderer/gfx-base/GFXDef-common.h" %import "renderer/gfx-base/GFXInputAssembler.h" diff --git a/native/tools/swig-config/assets.i b/native/tools/swig-config/assets.i index b9eaede4df..b6f2a701d4 100644 --- a/native/tools/swig-config/assets.i +++ b/native/tools/swig-config/assets.i @@ -184,6 +184,8 @@ %import "base/Ptr.h" %import "base/memory/Memory.h" +%import "core/event/Event.h" + %include "core/Types.h" %import "core/ArrayBuffer.h" diff --git a/native/tools/swig-config/physics.i b/native/tools/swig-config/physics.i index f1c37a9264..9f448d75e9 100644 --- a/native/tools/swig-config/physics.i +++ b/native/tools/swig-config/physics.i @@ -81,6 +81,7 @@ // %import "your_header_file.h" will not generate code for that header file // %import "base/Macros.h" +%import "core/event/Event.h" %import "core/scene-graph/Node.h" %import "core/geometry/Enums.h" diff --git a/native/tools/swig-config/pipeline.i b/native/tools/swig-config/pipeline.i index 3ea8ee5d56..882fdf8ef1 100644 --- a/native/tools/swig-config/pipeline.i +++ b/native/tools/swig-config/pipeline.i @@ -187,6 +187,8 @@ using namespace cc; %import "math/Mat4.h" %import "math/Quaternion.h" +%import "core/event/Event.h" + %import "core/assets/Material.h" %import "renderer/gfx-base/GFXDef-common.h" diff --git a/native/tools/swig-config/scene.i b/native/tools/swig-config/scene.i index ac316a5f37..f7534df1f5 100644 --- a/native/tools/swig-config/scene.i +++ b/native/tools/swig-config/scene.i @@ -69,6 +69,9 @@ using namespace cc; %ignore cc::scene::Pass::getBlocks; %ignore cc::scene::Pass::initPassFromTarget; +%ignore cc::Root::getEventProcessor; +%ignore cc::Node::getEventProcessor; + %ignore cc::Node::setRTSInternal; %ignore cc::Node::setRTS; %ignore cc::scene::Camera::syncCameraEditor; @@ -516,6 +519,8 @@ using namespace cc; %import "math/Mat4.h" %import "math/Quaternion.h" +%import "core/event/Event.h" + // %import "renderer/gfx-base/GFXDef-common.h" %import "core/data/Object.h" %import "renderer/pipeline/RenderPipeline.h" diff --git a/native/utils/compile_file.js b/native/utils/compile_file.js index 651a978c48..d20e4f4754 100644 --- a/native/utils/compile_file.js +++ b/native/utils/compile_file.js @@ -5,7 +5,7 @@ const path = require('path'); const child_process = require('child_process'); const fp = path.join(__dirname, '..', 'compile_commands.json'); -if(!fs.existsSync(fp)) { +if (!fs.existsSync(fp)) { console.error(`File ${fp} is not exists!`); process.exit(-1); } @@ -13,21 +13,33 @@ if(!fs.existsSync(fp)) { const db = JSON.parse(fs.readFileSync(fp).toString('utf8')); let fileName = process.argv[2]; -if(!fileName) { +if (!fileName) { console.error(`argument: file not provided!`); process.exit(-1); } fileName = path.normalize(fileName); -for(let item of db) { +for (let item of db) { let up = path.normalize(item.file); - if(up.indexOf(fileName) > -1) { + if (up.indexOf(fileName) > -1) { console.log(`compiling file ${up}`); - let result = child_process.execSync(item.command, {cwd: item.directory, shell: true}); + console.log("################################################################################"); + console.log("################################################################################"); + console.log("################################################################################"); + console.log(up); + console.log("################################################################################"); + console.log("################################################################################"); + console.log("################################################################################"); + let result = child_process.execSync(item.command, { cwd: item.directory, shell: true }); console.log(result.toString('utf-8')); + console.log("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"); + console.log("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"); + console.log("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"); + console.log("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"); + console.log("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"); process.exit(-1); } } -console.error(' file not found '+ fileName); \ No newline at end of file +console.error(' file not found ' + fileName); \ No newline at end of file