From 765d20c9883240295fbc91ee1331d54a1a25ca45 Mon Sep 17 00:00:00 2001 From: Nomango Date: Tue, 21 Jul 2020 20:56:49 +0800 Subject: [PATCH 01/12] update: middleware-styled module --- src/kiwano-imgui/ImGuiModule.cpp | 157 ++++++++-------- src/kiwano-imgui/ImGuiModule.h | 12 +- src/kiwano/base/Director.cpp | 35 ++-- src/kiwano/base/Director.h | 14 +- src/kiwano/base/Module.cpp | 74 +++++++- src/kiwano/base/Module.h | 168 ++++++++---------- src/kiwano/platform/Application.cpp | 88 ++------- src/kiwano/platform/Application.h | 5 +- src/kiwano/platform/Input.cpp | 39 ++-- src/kiwano/platform/Input.h | 11 +- src/kiwano/platform/Runner.cpp | 1 + .../render/DirectX/D3D11DeviceResources.cpp | 1 - src/kiwano/render/DirectX/RendererImpl.cpp | 9 + src/kiwano/render/DirectX/RendererImpl.h | 2 + src/kiwano/render/Renderer.cpp | 16 -- src/kiwano/render/Renderer.h | 10 +- 16 files changed, 310 insertions(+), 332 deletions(-) diff --git a/src/kiwano-imgui/ImGuiModule.cpp b/src/kiwano-imgui/ImGuiModule.cpp index ccfe6a28..84d1dff8 100644 --- a/src/kiwano-imgui/ImGuiModule.cpp +++ b/src/kiwano-imgui/ImGuiModule.cpp @@ -65,12 +65,12 @@ void ImGuiModule::DestroyModule() ImGui::DestroyContext(); } -void ImGuiModule::OnUpdate(Duration dt) +void ImGuiModule::OnUpdate(UpdateModuleContext& ctx) { ImGuiIO& io = ImGui::GetIO(); // Setup time step - io.DeltaTime = dt.Seconds(); + io.DeltaTime = ctx.dt.Seconds(); // Read keyboard modifiers inputs io.KeyCtrl = Input::GetInstance().IsDown(KeyCode::Ctrl); @@ -84,86 +84,97 @@ void ImGuiModule::OnUpdate(Duration dt) // Update OS mouse cursor with the cursor requested by imgui UpdateMouseCursor(); + + ctx.Next(); } -void ImGuiModule::BeforeRender() +void ImGuiModule::OnRender(RenderModuleContext& ctx) { - ImGui_Impl_NewFrame(); - - ImGuiIO& io = ImGui::GetIO(); - KGE_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built!"); - - // Setup display size (every frame to accommodate for window resizing) - Size display_size = Renderer::GetInstance().GetOutputSize(); - io.DisplaySize = ImVec2(display_size.x, display_size.y); - - ImGui::NewFrame(); -} - -void ImGuiModule::AfterRender() -{ - ImGui::Render(); - - ImGui_Impl_RenderDrawData(ImGui::GetDrawData()); -} - -void ImGuiModule::HandleEvent(Event* evt) -{ - if (ImGui::GetCurrentContext() == NULL) - return; - - ImGuiIO& io = ImGui::GetIO(); - if (evt->IsType()) + // Before render { - if (evt->IsType()) + ImGui_Impl_NewFrame(); + + ImGuiIO& io = ImGui::GetIO(); + KGE_ASSERT(io.Fonts->IsBuilt() && "Font atlas not built!"); + + // Setup display size (every frame to accommodate for window resizing) + Size display_size = Renderer::GetInstance().GetOutputSize(); + io.DisplaySize = ImVec2(display_size.x, display_size.y); + + ImGui::NewFrame(); + } + + ctx.Next(); + + // After render + { + ImGui::Render(); + + ImGui_Impl_RenderDrawData(ImGui::GetDrawData()); + } +} + +void ImGuiModule::HandleEvent(EventModuleContext& ctx) +{ + if (ImGui::GetCurrentContext() != NULL) + { + Event* evt = ctx.evt; + + ImGuiIO& io = ImGui::GetIO(); + if (evt->IsType()) { - MouseButton button = dynamic_cast(evt)->button; - int index = 0; - if (button == MouseButton::Left) - index = 0; - else if (button == MouseButton::Right) - index = 1; - else if (button == MouseButton::Middle) - index = 2; - io.MouseDown[index] = true; + if (evt->IsType()) + { + MouseButton button = dynamic_cast(evt)->button; + int index = 0; + if (button == MouseButton::Left) + index = 0; + else if (button == MouseButton::Right) + index = 1; + else if (button == MouseButton::Middle) + index = 2; + io.MouseDown[index] = true; + } + else if (evt->IsType()) + { + MouseButton button = dynamic_cast(evt)->button; + int index = 0; + if (button == MouseButton::Left) + index = 0; + else if (button == MouseButton::Right) + index = 1; + else if (button == MouseButton::Middle) + index = 2; + io.MouseDown[index] = false; + } + else if (evt->IsType()) + { + float wheel = dynamic_cast(evt)->wheel; + io.MouseWheel += wheel; + } } - else if (evt->IsType()) + else if (evt->IsType()) { - MouseButton button = dynamic_cast(evt)->button; - int index = 0; - if (button == MouseButton::Left) - index = 0; - else if (button == MouseButton::Right) - index = 1; - else if (button == MouseButton::Middle) - index = 2; - io.MouseDown[index] = false; - } - else if (evt->IsType()) - { - float wheel = dynamic_cast(evt)->wheel; - io.MouseWheel += wheel; - } - } - else if (evt->IsType()) - { - if (evt->IsType()) - { - KeyCode key = dynamic_cast(evt)->code; - io.KeysDown[(int)key] = true; - } - else if (evt->IsType()) - { - KeyCode key = dynamic_cast(evt)->code; - io.KeysDown[(int)key] = false; - } - else if (evt->IsType()) - { - // You can also use ToAscii()+GetKeyboardState() to retrieve characters. - char ch = dynamic_cast(evt)->value; - io.AddInputCharacter(static_cast(ch)); + if (evt->IsType()) + { + KeyCode key = dynamic_cast(evt)->code; + io.KeysDown[(int)key] = true; + } + else if (evt->IsType()) + { + KeyCode key = dynamic_cast(evt)->code; + io.KeysDown[(int)key] = false; + } + else if (evt->IsType()) + { + // You can also use ToAscii()+GetKeyboardState() to retrieve characters. + char ch = dynamic_cast(evt)->value; + io.AddInputCharacter(static_cast(ch)); + } } } + + ctx.Next(); } void ImGuiModule::UpdateMousePos() diff --git a/src/kiwano-imgui/ImGuiModule.h b/src/kiwano-imgui/ImGuiModule.h index b5c2d159..53ec924c 100644 --- a/src/kiwano-imgui/ImGuiModule.h +++ b/src/kiwano-imgui/ImGuiModule.h @@ -34,9 +34,7 @@ namespace imgui */ class ImGuiModule : public Singleton - , public RenderModule - , public UpdateModule - , public EventModule + , public Module { friend Singleton; @@ -47,13 +45,11 @@ public: void DestroyModule() override; - void BeforeRender() override; + void OnUpdate(UpdateModuleContext& ctx) override; - void AfterRender() override; + void OnRender(RenderModuleContext& ctx) override; - void HandleEvent(Event* evt) override; - - void OnUpdate(Duration dt) override; + void HandleEvent(EventModuleContext& ctx) override; private: void UpdateMousePos(); diff --git a/src/kiwano/base/Director.cpp b/src/kiwano/base/Director.cpp index 6b221030..d4d09a92 100644 --- a/src/kiwano/base/Director.cpp +++ b/src/kiwano/base/Director.cpp @@ -23,7 +23,6 @@ #include #include #include -#include namespace kiwano { @@ -119,11 +118,11 @@ void Director::ClearStages() debug_actor_.Reset(); } -void Director::OnUpdate(Duration dt) +void Director::OnUpdate(UpdateModuleContext& ctx) { if (transition_) { - transition_->Update(dt); + transition_->Update(ctx.dt); if (transition_->IsDone()) transition_ = nullptr; @@ -143,47 +142,53 @@ void Director::OnUpdate(Duration dt) } if (current_stage_) - current_stage_->Update(dt); + current_stage_->Update(ctx.dt); if (next_stage_) - next_stage_->Update(dt); + next_stage_->Update(ctx.dt); if (debug_actor_) - debug_actor_->Update(dt); + debug_actor_->Update(ctx.dt); + + ctx.Next(); } -void Director::OnRender(RenderContext& ctx) +void Director::OnRender(RenderModuleContext& ctx) { if (transition_) { - transition_->Render(ctx); + transition_->Render(ctx.render_ctx); } else if (current_stage_) { - current_stage_->Render(ctx); + current_stage_->Render(ctx.render_ctx); if (render_border_enabled_) { - current_stage_->RenderBorder(ctx); + current_stage_->RenderBorder(ctx.render_ctx); } } if (debug_actor_) { - debug_actor_->Render(ctx); + debug_actor_->Render(ctx.render_ctx); } + + ctx.Next(); } -void Director::HandleEvent(Event* evt) +void Director::HandleEvent(EventModuleContext& ctx) { if (current_stage_) - current_stage_->DispatchEvent(evt); + current_stage_->DispatchEvent(ctx.evt); if (next_stage_) - next_stage_->DispatchEvent(evt); + next_stage_->DispatchEvent(ctx.evt); if (debug_actor_) - debug_actor_->DispatchEvent(evt); + debug_actor_->DispatchEvent(ctx.evt); + + ctx.Next(); } } // namespace kiwano diff --git a/src/kiwano/base/Director.h b/src/kiwano/base/Director.h index 6a775670..c216e590 100644 --- a/src/kiwano/base/Director.h +++ b/src/kiwano/base/Director.h @@ -34,9 +34,7 @@ namespace kiwano */ class KGE_API Director : public Singleton - , public UpdateModule - , public RenderModule - , public EventModule + , public Module { friend Singleton; @@ -92,15 +90,11 @@ public: void ClearStages(); public: - void SetupModule() override {} + void OnUpdate(UpdateModuleContext& ctx) override; - void DestroyModule() override {} + void OnRender(RenderModuleContext& ctx) override; - void OnUpdate(Duration dt) override; - - void OnRender(RenderContext& ctx) override; - - void HandleEvent(Event* evt) override; + void HandleEvent(EventModuleContext& ctx) override; virtual ~Director(); diff --git a/src/kiwano/base/Module.cpp b/src/kiwano/base/Module.cpp index 009100bb..5f492049 100644 --- a/src/kiwano/base/Module.cpp +++ b/src/kiwano/base/Module.cpp @@ -19,28 +19,86 @@ // THE SOFTWARE. #include +#include namespace kiwano { -Module::Module() - : flag_(0) +ModuleContext::ModuleContext(ModuleList& modules) + : index_(-1) + , modules_(modules) { } -RenderModule::RenderModule() +ModuleContext::~ModuleContext() {} + +void ModuleContext::Next() { - flag_ |= ModuleFlag::value; + index_++; + for (; index_ < (int)modules_.size(); index_++) + { + this->Handle(modules_.at(index_)); + } } -UpdateModule::UpdateModule() +RenderModuleContext::RenderModuleContext(ModuleList& modules, RenderContext& ctx) + : ModuleContext(modules) + , render_ctx(ctx) { - flag_ |= ModuleFlag::value; + render_ctx.BeginDraw(); } -EventModule::EventModule() +RenderModuleContext::~RenderModuleContext() { - flag_ |= ModuleFlag::value; + render_ctx.EndDraw(); +} + +void RenderModuleContext::Handle(Module* m) +{ + m->OnRender(*this); +} + +UpdateModuleContext::UpdateModuleContext(ModuleList& modules, Duration dt) + : ModuleContext(modules) + , dt(dt) +{ +} + +void UpdateModuleContext::Handle(Module* m) +{ + m->OnUpdate(*this); +} + +EventModuleContext::EventModuleContext(ModuleList& modules, Event* evt) + : ModuleContext(modules) + , evt(evt) +{ +} + +void EventModuleContext::Handle(Module* m) +{ + m->HandleEvent(*this); +} + +Module::Module() {} + +void Module::SetupModule() {} + +void Module::DestroyModule() {} + +void Module::OnRender(RenderModuleContext& ctx) +{ + ctx.Next(); +} + +void Module::OnUpdate(UpdateModuleContext& ctx) +{ + ctx.Next(); +} + +void Module::HandleEvent(EventModuleContext& ctx) +{ + ctx.Next(); } } // namespace kiwano diff --git a/src/kiwano/base/Module.h b/src/kiwano/base/Module.h index f9a95340..68c66676 100644 --- a/src/kiwano/base/Module.h +++ b/src/kiwano/base/Module.h @@ -25,124 +25,104 @@ namespace kiwano { class RenderContext; class Event; +class Module; -template -struct ModuleFlag; +/// \~chinese +/// @brief 模块列表 +typedef Vector ModuleList; + +/// \~chinese +/// @brief 模块上下文 +class KGE_API ModuleContext +{ +public: + void Next(); + +protected: + ModuleContext(ModuleList& modules); + + virtual ~ModuleContext(); + + virtual void Handle(Module* m) = 0; + +private: + int index_; + ModuleList& modules_; +}; + +/// \~chinese +/// @brief 渲染模块上下文 +class KGE_API RenderModuleContext : public ModuleContext +{ +public: + RenderContext& render_ctx; + + RenderModuleContext(ModuleList& modules, RenderContext& ctx); + + virtual ~RenderModuleContext(); + +protected: + void Handle(Module* m) override; +}; + +/// \~chinese +/// @brief 更新模块上下文 +class KGE_API UpdateModuleContext : public ModuleContext +{ +public: + Duration dt; + + UpdateModuleContext(ModuleList& modules, Duration dt); + +protected: + void Handle(Module* m) override; +}; + +/// \~chinese +/// @brief 时间模块上下文 +class KGE_API EventModuleContext : public ModuleContext +{ +public: + Event* evt; + + EventModuleContext(ModuleList& modules, Event* evt); + +protected: + void Handle(Module* m) override; +}; /** * \~chinese * @brief 基础模块 */ -class KGE_API Module +class KGE_API Module : Noncopyable { public: /// \~chinese /// @brief 启动模块 - virtual void SetupModule() {} + virtual void SetupModule(); /// \~chinese /// @brief 销毁模块 - virtual void DestroyModule() {} - - template - _CompTy* Cast() - { - if (flag_ & ModuleFlag<_CompTy>::value) - return dynamic_cast<_CompTy*>(this); - return nullptr; - } - -protected: - Module(); - -protected: - int flag_; -}; - -/** - * \~chinese - * @brief 渲染模块 - */ -class KGE_API RenderModule : public virtual Module -{ -public: - /// \~chinese - /// @brief 渲染前 - virtual void BeforeRender() {} + virtual void DestroyModule(); /// \~chinese /// @brief 渲染时 /// @param ctx 渲染上下文 - virtual void OnRender(RenderContext& ctx) {} - - /// \~chinese - /// @brief 渲染后 - virtual void AfterRender() {} - -public: - RenderModule(); -}; - -/** - * \~chinese - * @brief 更新模块 - */ -class KGE_API UpdateModule : public virtual Module -{ -public: - /// \~chinese - /// @brief 更新前 - virtual void BeforeUpdate() {} + virtual void OnRender(RenderModuleContext& ctx); /// \~chinese /// @brief 更新时 - /// @param dt 间隔时间 - virtual void OnUpdate(Duration dt) {} + /// @param ctx 更新上下文 + virtual void OnUpdate(UpdateModuleContext& ctx); - /// \~chinese - /// @brief 更新后 - virtual void AfterUpdate() {} - -public: - UpdateModule(); -}; - -/** - * \~chinese - * @brief 事件模块 - */ -class KGE_API EventModule : public virtual Module -{ -public: /// \~chinese /// @brief 事件处理 - /// @param evt 事件 - virtual void HandleEvent(Event* evt) {} + /// @param ctx 事件上下文 + virtual void HandleEvent(EventModuleContext& ctx); -public: - EventModule(); +protected: + Module(); }; -#define KGE_DEFINE_COMPONENT_FLAG(OFFSET) (0x01 << (OFFSET % 32)) - -template <> -struct ModuleFlag -{ - static constexpr int value = KGE_DEFINE_COMPONENT_FLAG(0); -}; - -template <> -struct ModuleFlag -{ - static constexpr int value = KGE_DEFINE_COMPONENT_FLAG(1); -}; - -template <> -struct ModuleFlag -{ - static constexpr int value = KGE_DEFINE_COMPONENT_FLAG(2); -}; - -#undef KGE_DEFINE_COMPONENT_FLAG - } // namespace kiwano diff --git a/src/kiwano/platform/Application.cpp b/src/kiwano/platform/Application.cpp index a117aa31..8e94e6bd 100644 --- a/src/kiwano/platform/Application.cpp +++ b/src/kiwano/platform/Application.cpp @@ -162,13 +162,8 @@ void Application::DispatchEvent(Event* evt) if (!running_ /* Dispatch events even if application is paused */) return; - for (auto comp : modules_) - { - if (auto event_comp = comp->Cast()) - { - event_comp->HandleEvent(evt); - } - } + auto ctx = EventModuleContext(modules_, evt); + ctx.Next(); } void Application::Update(Duration dt) @@ -176,51 +171,24 @@ void Application::Update(Duration dt) if (!running_ || is_paused_) return; - // Before update - for (auto comp : modules_) - { - if (auto update_comp = comp->Cast()) - { - update_comp->BeforeUpdate(); - } - } + auto ctx = UpdateModuleContext(modules_, dt); + ctx.Next(); // perform functions + if (!functions_to_perform_.empty()) { - if (!functions_to_perform_.empty()) - { - perform_mutex_.lock(); - auto functions = std::move(functions_to_perform_); - perform_mutex_.unlock(); + perform_mutex_.lock(); + auto functions = std::move(functions_to_perform_); + perform_mutex_.unlock(); - while (!functions.empty()) + while (!functions.empty()) + { + auto& func = functions.front(); + if (func) { - auto& func = functions.front(); - if (func) - { - func(); - } - functions.pop(); + func(); } - } - } - - // Updating - Duration scaled_dt = dt * time_scale_; - for (auto comp : modules_) - { - if (auto update_comp = comp->Cast()) - { - update_comp->OnUpdate(scaled_dt); - } - } - - // After update - for (auto rit = modules_.rbegin(); rit != modules_.rend(); ++rit) - { - if (auto update_comp = (*rit)->Cast()) - { - update_comp->AfterUpdate(); + functions.pop(); } } } @@ -233,33 +201,9 @@ void Application::Render() Renderer& renderer = Renderer::GetInstance(); renderer.Clear(); - // Before render - for (auto comp : modules_) { - if (auto render_comp = comp->Cast()) - { - render_comp->BeforeRender(); - } - } - - // Rendering - renderer.BeginDraw(); - for (auto comp : modules_) - { - if (auto render_comp = comp->Cast()) - { - render_comp->OnRender(renderer.GetContext()); - } - } - renderer.EndDraw(); - - // After render - for (auto rit = modules_.rbegin(); rit != modules_.rend(); ++rit) - { - if (auto render_comp = (*rit)->Cast()) - { - render_comp->AfterRender(); - } + auto ctx = RenderModuleContext(modules_, renderer.GetContext()); + ctx.Next(); } renderer.Present(); diff --git a/src/kiwano/platform/Application.h b/src/kiwano/platform/Application.h index 670440c3..85e0fc21 100644 --- a/src/kiwano/platform/Application.h +++ b/src/kiwano/platform/Application.h @@ -42,7 +42,8 @@ extern KGE_API int GetVersion(); * \~chinese * @brief 应用程序,控制游戏的整个生命周期,包括初始化、启动、结束以及事件分发等 */ -class KGE_API Application : public Singleton +class KGE_API Application + : public Singleton { friend Singleton; @@ -169,7 +170,7 @@ private: float time_scale_; RunnerPtr runner_; TimerPtr timer_; - List modules_; + ModuleList modules_; std::mutex perform_mutex_; Queue> functions_to_perform_; }; diff --git a/src/kiwano/platform/Input.cpp b/src/kiwano/platform/Input.cpp index 8dd82307..d5451c0e 100644 --- a/src/kiwano/platform/Input.cpp +++ b/src/kiwano/platform/Input.cpp @@ -34,21 +34,6 @@ Input::Input() Input::~Input() {} -void Input::AfterUpdate() -{ - if (want_update_keys_) - { - want_update_keys_ = false; - ::memcpy(keys_[Prev].data(), keys_[Current].data(), KEY_NUM * sizeof(bool)); - } - - if (want_update_buttons_) - { - want_update_buttons_ = false; - buttons_[Prev] = buttons_[Current]; - } -} - bool Input::IsDown(KeyCode key) const { if (key == KeyCode::Unknown || key == KeyCode::Last) @@ -129,8 +114,27 @@ void Input::UpdateMousePos(const Point& pos) mouse_pos_ = pos; } -void Input::HandleEvent(Event* evt) +void Input::OnUpdate(UpdateModuleContext& ctx) { + ctx.Next(); + + if (want_update_keys_) + { + want_update_keys_ = false; + ::memcpy(keys_[Prev].data(), keys_[Current].data(), KEY_NUM * sizeof(bool)); + } + + if (want_update_buttons_) + { + want_update_buttons_ = false; + buttons_[Prev] = buttons_[Current]; + } +} + +void Input::HandleEvent(EventModuleContext& ctx) +{ + Event* evt = ctx.evt; + if (evt->IsType()) { if (evt->IsType()) @@ -157,5 +161,8 @@ void Input::HandleEvent(Event* evt) UpdateKey(dynamic_cast(evt)->code, false); } } + + ctx.Next(); } + } // namespace kiwano diff --git a/src/kiwano/platform/Input.h b/src/kiwano/platform/Input.h index 2bd4ad84..b731e0a5 100644 --- a/src/kiwano/platform/Input.h +++ b/src/kiwano/platform/Input.h @@ -35,8 +35,7 @@ namespace kiwano */ class KGE_API Input : public Singleton - , public UpdateModule - , public EventModule + , public Module { friend Singleton; @@ -104,13 +103,9 @@ public: Point GetMousePos() const; public: - void SetupModule() override {} + void OnUpdate(UpdateModuleContext& ctx) override; - void DestroyModule() override {} - - void AfterUpdate() override; - - void HandleEvent(Event* evt) override; + void HandleEvent(EventModuleContext& ctx) override; ~Input(); diff --git a/src/kiwano/platform/Runner.cpp b/src/kiwano/platform/Runner.cpp index e2e0463c..642704b1 100644 --- a/src/kiwano/platform/Runner.cpp +++ b/src/kiwano/platform/Runner.cpp @@ -91,6 +91,7 @@ void Runner::InitSettings() Renderer::GetInstance().SetVSyncEnabled(settings_.vsync_enabled); // Use defaut modules + Application::GetInstance().Use(Renderer::GetInstance()); Application::GetInstance().Use(Input::GetInstance()); Application::GetInstance().Use(Director::GetInstance()); diff --git a/src/kiwano/render/DirectX/D3D11DeviceResources.cpp b/src/kiwano/render/DirectX/D3D11DeviceResources.cpp index 31e0c3f4..3f5408ca 100644 --- a/src/kiwano/render/DirectX/D3D11DeviceResources.cpp +++ b/src/kiwano/render/DirectX/D3D11DeviceResources.cpp @@ -20,7 +20,6 @@ #include #include -#include KGE_SUPPRESS_WARNING_PUSH KGE_SUPPRESS_WARNING(4800) // Implicit conversion from 'type' to bool diff --git a/src/kiwano/render/DirectX/RendererImpl.cpp b/src/kiwano/render/DirectX/RendererImpl.cpp index 0fc654fa..ef4d04b7 100644 --- a/src/kiwano/render/DirectX/RendererImpl.cpp +++ b/src/kiwano/render/DirectX/RendererImpl.cpp @@ -166,6 +166,15 @@ void RendererImpl::Destroy() ::CoUninitialize(); } +void RendererImpl::HandleEvent(EventModuleContext& ctx) +{ + if (ctx.evt->IsType()) + { + auto evt = ctx.evt->SafeCast(); + Resize(evt->width, evt->height); + } +} + void RendererImpl::Clear() { KGE_ASSERT(d3d_res_); diff --git a/src/kiwano/render/DirectX/RendererImpl.h b/src/kiwano/render/DirectX/RendererImpl.h index 8825d135..dfce0ea0 100644 --- a/src/kiwano/render/DirectX/RendererImpl.h +++ b/src/kiwano/render/DirectX/RendererImpl.h @@ -83,6 +83,8 @@ public: void Destroy() override; + void HandleEvent(EventModuleContext& ctx) override; + protected: RendererImpl(); diff --git a/src/kiwano/render/Renderer.cpp b/src/kiwano/render/Renderer.cpp index ef165491..53904c2c 100644 --- a/src/kiwano/render/Renderer.cpp +++ b/src/kiwano/render/Renderer.cpp @@ -19,8 +19,6 @@ // THE SOFTWARE. #include -#include -#include namespace kiwano { @@ -31,18 +29,4 @@ Renderer::Renderer() { } -void Renderer::BeginDraw() -{ - KGE_ASSERT(render_ctx_); - - render_ctx_->BeginDraw(); -} - -void Renderer::EndDraw() -{ - KGE_ASSERT(render_ctx_); - - render_ctx_->EndDraw(); -} - } // namespace kiwano diff --git a/src/kiwano/render/Renderer.h b/src/kiwano/render/Renderer.h index 742cfb11..48005faf 100644 --- a/src/kiwano/render/Renderer.h +++ b/src/kiwano/render/Renderer.h @@ -44,7 +44,7 @@ namespace kiwano * \~chinese * @brief 渲染器 */ -class KGE_API Renderer : public Noncopyable +class KGE_API Renderer : public Module { public: /// \~chinese @@ -218,14 +218,6 @@ public: virtual RenderContextPtr CreateTextureRenderContext(Texture& texture, const Size* desired_size = nullptr) = 0; public: - /// \~chinese - /// @brief 开始渲染 - virtual void BeginDraw(); - - /// \~chinese - /// @brief 结束渲染 - virtual void EndDraw(); - /// \~chinese /// @brief 清除绘制内容 virtual void Clear() = 0; From c0f90d235a513a540219ecabbfcfb883c881bcfb Mon Sep 17 00:00:00 2001 From: Nomango Date: Wed, 22 Jul 2020 16:52:32 +0800 Subject: [PATCH 02/12] refactoring: add RefPtr & RefObject & ObjectPool --- projects/kiwano/kiwano.vcxproj | 6 +- projects/kiwano/kiwano.vcxproj.filters | 18 +-- src/kiwano-audio/Sound.cpp | 4 +- src/kiwano-audio/SoundPlayer.cpp | 7 +- src/kiwano-imgui/ImGuiLayer.cpp | 4 +- src/kiwano-network/HttpModule.cpp | 2 +- src/kiwano-network/HttpRequest.cpp | 6 +- src/kiwano-physics/Fixture.cpp | 10 +- src/kiwano-physics/Joint.cpp | 22 ++-- src/kiwano-physics/PhysicBody.cpp | 2 +- src/kiwano-physics/PhysicWorld.cpp | 4 +- src/kiwano/2d/Actor.cpp | 8 +- src/kiwano/2d/Canvas.cpp | 5 +- src/kiwano/2d/DebugActor.cpp | 4 +- src/kiwano/2d/GifSprite.cpp | 10 +- src/kiwano/2d/LayerActor.cpp | 2 +- src/kiwano/2d/ShapeActor.cpp | 14 +-- src/kiwano/2d/ShapeActor.h | 4 +- src/kiwano/2d/Sprite.cpp | 6 +- src/kiwano/2d/Stage.cpp | 6 +- src/kiwano/2d/TextActor.cpp | 2 +- src/kiwano/2d/Transition.cpp | 10 +- src/kiwano/2d/action/Action.h | 2 +- src/kiwano/2d/action/ActionDelay.cpp | 2 +- src/kiwano/2d/action/ActionGroup.cpp | 2 +- src/kiwano/2d/action/ActionTween.cpp | 20 ++-- src/kiwano/2d/action/ActionWalk.cpp | 2 +- src/kiwano/2d/action/Animation.cpp | 2 +- src/kiwano/base/Director.cpp | 2 +- src/kiwano/base/ObjectBase.cpp | 8 +- src/kiwano/base/ObjectBase.h | 10 +- src/kiwano/base/ObjectPool.cpp | 31 +----- src/kiwano/base/ObjectPool.h | 22 ++-- .../base/{RefCounter.cpp => RefObject.cpp} | 48 ++++++-- src/kiwano/base/{RefCounter.h => RefObject.h} | 35 ++++-- src/kiwano/base/component/Button.cpp | 2 +- src/kiwano/core/Allocator.cpp | 4 +- src/kiwano/core/Allocator.h | 56 ++-------- src/kiwano/core/Cloneable.h | 4 +- src/kiwano/core/{SmartPtr.hpp => RefPtr.hpp} | 104 +++++++++++------- src/kiwano/event/Event.h | 4 +- src/kiwano/event/EventListener.cpp | 4 +- src/kiwano/event/EventListener.h | 2 +- src/kiwano/kiwano.h | 4 +- src/kiwano/platform/Application.cpp | 7 ++ src/kiwano/platform/Runner.cpp | 4 +- src/kiwano/platform/win32/ComPtr.hpp | 4 +- src/kiwano/platform/win32/WindowImpl.cpp | 2 +- src/kiwano/render/Brush.cpp | 6 +- src/kiwano/render/DirectX/RendererImpl.cpp | 8 +- src/kiwano/render/DirectX/TextRenderer.cpp | 2 +- src/kiwano/render/Font.cpp | 4 +- src/kiwano/render/Frame.cpp | 6 +- src/kiwano/render/FrameSequence.cpp | 12 +- src/kiwano/render/GifImage.cpp | 4 +- src/kiwano/render/Shape.cpp | 10 +- src/kiwano/render/ShapeMaker.cpp | 4 +- src/kiwano/render/StrokeStyle.cpp | 4 +- src/kiwano/render/TextLayout.cpp | 4 +- src/kiwano/render/Texture.cpp | 4 +- src/kiwano/render/TextureCache.cpp | 4 +- src/kiwano/utils/ConfigIni.cpp | 2 +- src/kiwano/utils/EventTicker.cpp | 2 +- src/kiwano/utils/Logger.cpp | 2 +- src/kiwano/utils/ResourceCache.cpp | 14 +-- src/kiwano/utils/ResourceCache.h | 2 +- src/kiwano/utils/Task.cpp | 2 +- src/kiwano/utils/Ticker.cpp | 2 +- src/kiwano/utils/Timer.cpp | 2 +- 69 files changed, 330 insertions(+), 313 deletions(-) rename src/kiwano/base/{RefCounter.cpp => RefObject.cpp} (61%) rename src/kiwano/base/{RefCounter.h => RefObject.h} (74%) rename src/kiwano/core/{SmartPtr.hpp => RefPtr.hpp} (61%) diff --git a/projects/kiwano/kiwano.vcxproj b/projects/kiwano/kiwano.vcxproj index 11cb1697..ee563d2b 100644 --- a/projects/kiwano/kiwano.vcxproj +++ b/projects/kiwano/kiwano.vcxproj @@ -17,7 +17,7 @@ - + @@ -52,7 +52,7 @@ - + @@ -134,7 +134,7 @@ - + diff --git a/projects/kiwano/kiwano.vcxproj.filters b/projects/kiwano/kiwano.vcxproj.filters index c0a05373..95c61c79 100644 --- a/projects/kiwano/kiwano.vcxproj.filters +++ b/projects/kiwano/kiwano.vcxproj.filters @@ -65,9 +65,6 @@ math - - core - 2d @@ -303,9 +300,6 @@ base - - base - event @@ -354,6 +348,12 @@ 2d\action + + core + + + base + @@ -539,9 +539,6 @@ base - - base - event @@ -581,6 +578,9 @@ 2d\action + + base + diff --git a/src/kiwano-audio/Sound.cpp b/src/kiwano-audio/Sound.cpp index 4f3b2636..c8da50d7 100644 --- a/src/kiwano-audio/Sound.cpp +++ b/src/kiwano-audio/Sound.cpp @@ -29,7 +29,7 @@ namespace audio { SoundPtr Sound::Create(const String& file_path) { - SoundPtr ptr = new (std::nothrow) Sound; + SoundPtr ptr = new (autogc) Sound; if (ptr) { if (!ptr->Load(file_path)) @@ -40,7 +40,7 @@ SoundPtr Sound::Create(const String& file_path) SoundPtr Sound::Create(const Resource& res) { - SoundPtr ptr = new (std::nothrow) Sound; + SoundPtr ptr = new (autogc) Sound; if (ptr) { if (!ptr->Load(res)) diff --git a/src/kiwano-audio/SoundPlayer.cpp b/src/kiwano-audio/SoundPlayer.cpp index dde27202..31efc911 100644 --- a/src/kiwano-audio/SoundPlayer.cpp +++ b/src/kiwano-audio/SoundPlayer.cpp @@ -27,7 +27,7 @@ namespace audio SoundPlayerPtr SoundPlayer::Create() { - SoundPlayerPtr ptr = new (std::nothrow) SoundPlayer; + SoundPlayerPtr ptr = new (autogc) SoundPlayer; return ptr; } @@ -47,8 +47,7 @@ size_t SoundPlayer::Load(const String& file_path) if (sound_cache_.end() != sound_cache_.find(hash)) return hash; - SoundPtr sound = new (std::nothrow) Sound; - + SoundPtr sound = new (autogc) Sound; if (sound) { if (sound->Load(file_path)) @@ -67,7 +66,7 @@ size_t SoundPlayer::Load(const Resource& res) if (sound_cache_.end() != sound_cache_.find(hash_code)) return hash_code; - SoundPtr sound = new (std::nothrow) Sound; + SoundPtr sound = new (autogc) Sound; if (sound) { diff --git a/src/kiwano-imgui/ImGuiLayer.cpp b/src/kiwano-imgui/ImGuiLayer.cpp index aecd488d..68b2d161 100644 --- a/src/kiwano-imgui/ImGuiLayer.cpp +++ b/src/kiwano-imgui/ImGuiLayer.cpp @@ -27,13 +27,13 @@ namespace imgui ImGuiLayerPtr ImGuiLayer::Create() { - ImGuiLayerPtr ptr = new (std::nothrow) ImGuiLayer; + ImGuiLayerPtr ptr = new (autogc) ImGuiLayer; return ptr; } ImGuiLayerPtr ImGuiLayer::Create(const String& name, const ImGuiPipeline& item) { - ImGuiLayerPtr ptr = new (std::nothrow) ImGuiLayer; + ImGuiLayerPtr ptr = new (autogc) ImGuiLayer; if (ptr) { ptr->AddItem(name, item); diff --git a/src/kiwano-network/HttpModule.cpp b/src/kiwano-network/HttpModule.cpp index 4fae5217..ab1d9f88 100644 --- a/src/kiwano-network/HttpModule.cpp +++ b/src/kiwano-network/HttpModule.cpp @@ -253,7 +253,7 @@ void HttpModule::NetworkThread() return; } - HttpResponsePtr response = new (std::nothrow) HttpResponse(request); + HttpResponsePtr response = new (autogc) HttpResponse(request); Perform(request, response); response_mutex_.lock(); diff --git a/src/kiwano-network/HttpRequest.cpp b/src/kiwano-network/HttpRequest.cpp index 7392aa9c..18ef0abf 100644 --- a/src/kiwano-network/HttpRequest.cpp +++ b/src/kiwano-network/HttpRequest.cpp @@ -28,7 +28,7 @@ namespace network HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const ResponseCallback& callback) { - HttpRequestPtr ptr = new (std::nothrow) HttpRequest; + HttpRequestPtr ptr = new (autogc) HttpRequest; if (ptr) { ptr->SetUrl(url); @@ -40,7 +40,7 @@ HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const Respo HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const String& data, const ResponseCallback& callback) { - HttpRequestPtr ptr = new (std::nothrow) HttpRequest; + HttpRequestPtr ptr = new (autogc) HttpRequest; if (ptr) { ptr->SetUrl(url); @@ -53,7 +53,7 @@ HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const Strin HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const Json& json, const ResponseCallback& callback) { - HttpRequestPtr ptr = new (std::nothrow) HttpRequest; + HttpRequestPtr ptr = new (autogc) HttpRequest; if (ptr) { ptr->SetUrl(url); diff --git a/src/kiwano-physics/Fixture.cpp b/src/kiwano-physics/Fixture.cpp index 2576a707..d6e14cbd 100644 --- a/src/kiwano-physics/Fixture.cpp +++ b/src/kiwano-physics/Fixture.cpp @@ -29,7 +29,7 @@ namespace physics FixturePtr Fixture::CreateCircle(const Param& param, float radius, const Point& offset) { - FixturePtr ptr = new (std::nothrow) Fixture; + FixturePtr ptr = new (autogc) Fixture; if (ptr) { auto shape = std::make_unique(); @@ -44,7 +44,7 @@ FixturePtr Fixture::CreateCircle(const Param& param, float radius, const Point& FixturePtr Fixture::CreateRect(const Param& param, const Size& size, const Point& offset, float rotation) { - FixturePtr ptr = new (std::nothrow) Fixture; + FixturePtr ptr = new (autogc) Fixture; if (ptr) { b2Vec2 b2size = global::LocalToWorld(size); @@ -61,7 +61,7 @@ FixturePtr Fixture::CreateRect(const Param& param, const Size& size, const Point FixturePtr Fixture::CreatePolygon(const Param& param, const Vector& vertexs) { - FixturePtr ptr = new (std::nothrow) Fixture; + FixturePtr ptr = new (autogc) Fixture; if (ptr) { Vector b2vertexs; @@ -82,7 +82,7 @@ FixturePtr Fixture::CreatePolygon(const Param& param, const Vector& verte FixturePtr Fixture::CreateEdge(const Param& param, const Point& p1, const Point& p2) { - FixturePtr ptr = new (std::nothrow) Fixture; + FixturePtr ptr = new (autogc) Fixture; if (ptr) { b2Vec2 start = global::LocalToWorld(p1); @@ -99,7 +99,7 @@ FixturePtr Fixture::CreateEdge(const Param& param, const Point& p1, const Point& FixturePtr Fixture::CreateChain(const Param& param, const Vector& vertices, bool loop) { - FixturePtr ptr = new (std::nothrow) Fixture; + FixturePtr ptr = new (autogc) Fixture; if (ptr) { Vector b2vertices; diff --git a/src/kiwano-physics/Joint.cpp b/src/kiwano-physics/Joint.cpp index bef942a6..220d3d29 100644 --- a/src/kiwano-physics/Joint.cpp +++ b/src/kiwano-physics/Joint.cpp @@ -109,7 +109,7 @@ void Joint::Destroy() DistanceJointPtr DistanceJoint::Create(const Param& param) { - DistanceJointPtr ptr = new (std::nothrow) DistanceJoint; + DistanceJointPtr ptr = new (autogc) DistanceJoint; if (ptr) { ptr->param_ = param; @@ -156,7 +156,7 @@ float DistanceJoint::GetLength() const FrictionJointPtr FrictionJoint::Create(const Param& param) { - FrictionJointPtr ptr = new (std::nothrow) FrictionJoint; + FrictionJointPtr ptr = new (autogc) FrictionJoint; if (ptr) { ptr->param_ = param; @@ -214,7 +214,7 @@ float FrictionJoint::GetMaxTorque() const GearJointPtr GearJoint::Create(const Param& param) { - GearJointPtr ptr = new (std::nothrow) GearJoint; + GearJointPtr ptr = new (autogc) GearJoint; if (ptr) { ptr->param_ = param; @@ -260,7 +260,7 @@ float GearJoint::GetRatio() const MotorJointPtr MotorJoint::Create(const Param& param) { - MotorJointPtr ptr = new (std::nothrow) MotorJoint; + MotorJointPtr ptr = new (autogc) MotorJoint; if (ptr) { ptr->param_ = param; @@ -319,7 +319,7 @@ float MotorJoint::GetMaxTorque() const PrismaticJointPtr PrismaticJoint::Create(const Param& param) { - PrismaticJointPtr ptr = new (std::nothrow) PrismaticJoint; + PrismaticJointPtr ptr = new (autogc) PrismaticJoint; if (ptr) { ptr->param_ = param; @@ -388,7 +388,7 @@ void PrismaticJoint::SetLimits(float lower, float upper) PulleyJointPtr PulleyJoint::Create(const Param& param) { - PulleyJointPtr ptr = new (std::nothrow) PulleyJoint; + PulleyJointPtr ptr = new (autogc) PulleyJoint; if (ptr) { ptr->param_ = param; @@ -464,7 +464,7 @@ float PulleyJoint::GetCurrentLengthB() const RevoluteJointPtr RevoluteJoint::Create(const Param& param) { - RevoluteJointPtr ptr = new (std::nothrow) RevoluteJoint; + RevoluteJointPtr ptr = new (autogc) RevoluteJoint; if (ptr) { ptr->param_ = param; @@ -544,7 +544,7 @@ float RevoluteJoint::GetMaxMotorTorque() const RopeJointPtr RopeJoint::Create(const Param& param) { - RopeJointPtr ptr = new (std::nothrow) RopeJoint; + RopeJointPtr ptr = new (autogc) RopeJoint; if (ptr) { ptr->param_ = param; @@ -592,7 +592,7 @@ float RopeJoint::GetMaxLength() const WeldJointPtr WeldJoint::Create(const Param& param) { - WeldJointPtr ptr = new (std::nothrow) WeldJoint; + WeldJointPtr ptr = new (autogc) WeldJoint; if (ptr) { ptr->param_ = param; @@ -626,7 +626,7 @@ bool WeldJoint::Init(PhysicWorld* world) WheelJointPtr WheelJoint::Create(const Param& param) { - WheelJointPtr ptr = new (std::nothrow) WheelJoint; + WheelJointPtr ptr = new (autogc) WheelJoint; if (ptr) { ptr->param_ = param; @@ -688,7 +688,7 @@ float WheelJoint::GetMaxMotorTorque() const MouseJointPtr MouseJoint::Create(const Param& param) { - MouseJointPtr ptr = new (std::nothrow) MouseJoint; + MouseJointPtr ptr = new (autogc) MouseJoint; if (ptr) { ptr->param_ = param; diff --git a/src/kiwano-physics/PhysicBody.cpp b/src/kiwano-physics/PhysicBody.cpp index 6652b5d6..770b7101 100644 --- a/src/kiwano-physics/PhysicBody.cpp +++ b/src/kiwano-physics/PhysicBody.cpp @@ -37,7 +37,7 @@ PhysicBodyPtr PhysicBody::Create(PhysicWorld* world, Type type) { KGE_ASSERT(world); - PhysicBodyPtr ptr = new (std::nothrow) PhysicBody; + PhysicBodyPtr ptr = new (autogc) PhysicBody; if (ptr) { ptr->SetType(type); diff --git a/src/kiwano-physics/PhysicWorld.cpp b/src/kiwano-physics/PhysicWorld.cpp index e97384b7..b712a343 100644 --- a/src/kiwano-physics/PhysicWorld.cpp +++ b/src/kiwano-physics/PhysicWorld.cpp @@ -213,13 +213,13 @@ public: PhysicWorldPtr PhysicWorld::Create() { - PhysicWorldPtr ptr = new (std::nothrow) PhysicWorld; + PhysicWorldPtr ptr = new (autogc) PhysicWorld; return ptr; } PhysicWorldPtr PhysicWorld::Create(const Vec2& gravity) { - PhysicWorldPtr ptr = new (std::nothrow) PhysicWorld; + PhysicWorldPtr ptr = new (autogc) PhysicWorld; if (ptr) { ptr->SetGravity(gravity); diff --git a/src/kiwano/2d/Actor.cpp b/src/kiwano/2d/Actor.cpp index c7a65db2..cc8265d4 100644 --- a/src/kiwano/2d/Actor.cpp +++ b/src/kiwano/2d/Actor.cpp @@ -41,7 +41,7 @@ void Actor::SetDefaultAnchor(float anchor_x, float anchor_y) ActorPtr Actor::Create() { - ActorPtr ptr = memory::New(); + ActorPtr ptr = new (autogc) Actor; return ptr; } @@ -264,7 +264,7 @@ bool Actor::HandleEvent(Event* evt) { hover_ = true; - MouseHoverEventPtr hover = memory::New(); + MouseHoverEventPtr hover = new (autogc) MouseHoverEvent; hover->pos = mouse_evt->pos; HandleEvent(hover.Get()); } @@ -273,7 +273,7 @@ bool Actor::HandleEvent(Event* evt) hover_ = false; pressed_ = false; - MouseOutEventPtr out = memory::New(); + MouseOutEventPtr out = new (autogc) MouseOutEvent; out->pos = mouse_evt->pos; HandleEvent(out.Get()); } @@ -290,7 +290,7 @@ bool Actor::HandleEvent(Event* evt) auto mouse_up_evt = dynamic_cast(evt); - MouseClickEventPtr click = memory::New(); + MouseClickEventPtr click = new (autogc) MouseClickEvent; click->pos = mouse_up_evt->pos; click->button = mouse_up_evt->button; HandleEvent(click.Get()); diff --git a/src/kiwano/2d/Canvas.cpp b/src/kiwano/2d/Canvas.cpp index 1cbbd781..cc848a26 100644 --- a/src/kiwano/2d/Canvas.cpp +++ b/src/kiwano/2d/Canvas.cpp @@ -26,8 +26,7 @@ namespace kiwano CanvasPtr Canvas::Create(const Size& size) { - void* mem = memory::Alloc(sizeof(Canvas)); - CanvasPtr ptr = ::new (mem) Canvas; + CanvasPtr ptr = new (autogc) Canvas; if (ptr) { try @@ -59,7 +58,7 @@ void Canvas::OnRender(RenderContext& ctx) void Canvas::ResizeAndClear(Size size) { - texture_cached_ = memory::New(); + texture_cached_ = new (autogc) Texture; render_ctx_ = RenderContext::Create(*texture_cached_, size); SetSize(render_ctx_->GetSize()); diff --git a/src/kiwano/2d/DebugActor.cpp b/src/kiwano/2d/DebugActor.cpp index 92cf5989..048c29c1 100644 --- a/src/kiwano/2d/DebugActor.cpp +++ b/src/kiwano/2d/DebugActor.cpp @@ -54,10 +54,10 @@ DebugActor::DebugActor() comma_locale_ = std::locale(std::locale(), new comma_numpunct); - background_brush_ = memory::New(); + background_brush_ = new (autogc) Brush; background_brush_->SetColor(Color::Rgba(0x000000, 0.7f)); - BrushPtr fill_brush = memory::New(); + BrushPtr fill_brush = new (autogc) Brush; fill_brush->SetColor(Color::White); debug_text_style_.font_family = "Arial"; diff --git a/src/kiwano/2d/GifSprite.cpp b/src/kiwano/2d/GifSprite.cpp index 5cd2cf19..68996b63 100644 --- a/src/kiwano/2d/GifSprite.cpp +++ b/src/kiwano/2d/GifSprite.cpp @@ -27,7 +27,7 @@ namespace kiwano GifSpritePtr GifSprite::Create(const String& file_path) { - GifSpritePtr ptr = memory::New(); + GifSpritePtr ptr = new (autogc) GifSprite; if (ptr) { if (!ptr->Load(file_path)) @@ -38,7 +38,7 @@ GifSpritePtr GifSprite::Create(const String& file_path) GifSpritePtr GifSprite::Create(const Resource& res) { - GifSpritePtr ptr = memory::New(); + GifSpritePtr ptr = new (autogc) GifSprite; if (ptr) { if (!ptr->Load(res)) @@ -49,7 +49,7 @@ GifSpritePtr GifSprite::Create(const Resource& res) GifSpritePtr GifSprite::Create(GifImagePtr gif) { - GifSpritePtr ptr = memory::New(); + GifSpritePtr ptr = new (autogc) GifSprite; if (ptr) { ptr->SetGifImage(gif); @@ -92,7 +92,7 @@ bool GifSprite::Load(GifImagePtr gif) frame_rt_.Reset(); Size frame_size = Size(float(gif_->GetWidthInPixels()), float(gif_->GetHeightInPixels())); - frame_to_render_ = memory::New(); + frame_to_render_ = new (autogc) Texture; frame_rt_ = RenderContext::Create(*frame_to_render_, frame_size); SetSize(frame_rt_->GetSize()); @@ -229,7 +229,7 @@ void GifSprite::SaveComposedFrame() if (!saved_frame_) { - saved_frame_ = memory::New(); + saved_frame_ = new (autogc) Texture; frame_rt_->CreateTexture(*saved_frame_, frame_to_render_->GetSizeInPixels()); } saved_frame_->CopyFrom(frame_to_render_); diff --git a/src/kiwano/2d/LayerActor.cpp b/src/kiwano/2d/LayerActor.cpp index 4daaddd8..f49ffe26 100644 --- a/src/kiwano/2d/LayerActor.cpp +++ b/src/kiwano/2d/LayerActor.cpp @@ -27,7 +27,7 @@ namespace kiwano LayerActorPtr LayerActor::Create() { - LayerActorPtr ptr = memory::New(); + LayerActorPtr ptr = new (autogc) LayerActor; return ptr; } diff --git a/src/kiwano/2d/ShapeActor.cpp b/src/kiwano/2d/ShapeActor.cpp index 5186451a..c837cf43 100644 --- a/src/kiwano/2d/ShapeActor.cpp +++ b/src/kiwano/2d/ShapeActor.cpp @@ -27,7 +27,7 @@ namespace kiwano ShapeActorPtr ShapeActor::Create(ShapePtr shape) { - ShapeActorPtr ptr = memory::New(); + ShapeActorPtr ptr = new (autogc) ShapeActor; if (ptr) { ptr->SetShape(shape); @@ -129,7 +129,7 @@ bool ShapeActor::CheckVisibility(RenderContext& ctx) const LineActorPtr LineActor::Create(const Point& begin, const Point& end) { - LineActorPtr ptr = memory::New(); + LineActorPtr ptr = new (autogc) LineActor; if (ptr) { ptr->SetLine(begin, end); @@ -157,7 +157,7 @@ void LineActor::SetLine(const Point& begin, const Point& end) RectActorPtr RectActor::Create(const Size& size) { - RectActorPtr ptr = memory::New(); + RectActorPtr ptr = new (autogc) RectActor; if (ptr) { ptr->SetRectSize(size); @@ -184,7 +184,7 @@ void RectActor::SetRectSize(const Size& size) RoundedRectActorPtr RoundedRectActor::Create(const Size& size, const Vec2& radius) { - RoundedRectActorPtr ptr = memory::New(); + RoundedRectActorPtr ptr = new (autogc) RoundedRectActor; if (ptr) { ptr->SetRoundedRect(size, radius); @@ -222,7 +222,7 @@ void RoundedRectActor::SetRoundedRect(const Size& size, const Vec2& radius) CircleActorPtr CircleActor::Create(float radius) { - CircleActorPtr ptr = memory::New(); + CircleActorPtr ptr = new (autogc) CircleActor; if (ptr) { ptr->SetRadius(radius); @@ -252,7 +252,7 @@ void CircleActor::SetRadius(float radius) EllipseActorPtr EllipseActor::Create(const Vec2& radius) { - EllipseActorPtr ptr = memory::New(); + EllipseActorPtr ptr = new (autogc) EllipseActor; if (ptr) { ptr->SetRadius(radius); @@ -279,7 +279,7 @@ void EllipseActor::SetRadius(const Vec2& radius) PolygonActorPtr PolygonActor::Create(const Vector& points) { - PolygonActorPtr ptr = memory::New(); + PolygonActorPtr ptr = new (autogc) PolygonActor; if (ptr) { ptr->SetVertices(points); diff --git a/src/kiwano/2d/ShapeActor.h b/src/kiwano/2d/ShapeActor.h index 6dcaf82b..ae4074f1 100644 --- a/src/kiwano/2d/ShapeActor.h +++ b/src/kiwano/2d/ShapeActor.h @@ -338,7 +338,7 @@ inline void ShapeActor::SetStrokeColor(const Color& color) { if (!stroke_brush_) { - stroke_brush_ = memory::New(); + stroke_brush_ = new (autogc) Brush; } stroke_brush_->SetColor(color); } @@ -347,7 +347,7 @@ inline void ShapeActor::SetFillColor(const Color& color) { if (!fill_brush_) { - fill_brush_ = memory::New(); + fill_brush_ = new (autogc) Brush; } fill_brush_->SetColor(color); } diff --git a/src/kiwano/2d/Sprite.cpp b/src/kiwano/2d/Sprite.cpp index 1a717463..34be7de6 100644 --- a/src/kiwano/2d/Sprite.cpp +++ b/src/kiwano/2d/Sprite.cpp @@ -26,7 +26,7 @@ namespace kiwano SpritePtr Sprite::Create(const String& file_path) { - SpritePtr ptr = memory::New(); + SpritePtr ptr = new (autogc) Sprite; if (ptr) { if (!ptr->Load(file_path)) @@ -37,7 +37,7 @@ SpritePtr Sprite::Create(const String& file_path) SpritePtr Sprite::Create(const Resource& res) { - SpritePtr ptr = memory::New(); + SpritePtr ptr = new (autogc) Sprite; if (ptr) { if (!ptr->Load(res)) @@ -48,7 +48,7 @@ SpritePtr Sprite::Create(const Resource& res) SpritePtr Sprite::Create(FramePtr frame) { - SpritePtr ptr = memory::New(); + SpritePtr ptr = new (autogc) Sprite; if (ptr) { ptr->SetFrame(frame); diff --git a/src/kiwano/2d/Stage.cpp b/src/kiwano/2d/Stage.cpp index 2c65c309..2a9ce6e3 100644 --- a/src/kiwano/2d/Stage.cpp +++ b/src/kiwano/2d/Stage.cpp @@ -27,7 +27,7 @@ namespace kiwano StagePtr Stage::Create() { - StagePtr ptr = memory::New(); + StagePtr ptr = new (autogc) Stage; return ptr; } @@ -57,13 +57,13 @@ void Stage::RenderBorder(RenderContext& ctx) if (!border_fill_brush_) { - border_fill_brush_ = memory::New(); + border_fill_brush_ = new (autogc) Brush; border_fill_brush_->SetColor(Color(Color::Red, .4f)); } if (!border_stroke_brush_) { - border_stroke_brush_ = memory::New(); + border_stroke_brush_ = new (autogc) Brush; border_stroke_brush_->SetColor(Color(Color::Red, .8f)); } diff --git a/src/kiwano/2d/TextActor.cpp b/src/kiwano/2d/TextActor.cpp index dfe0010d..0acea3ec 100644 --- a/src/kiwano/2d/TextActor.cpp +++ b/src/kiwano/2d/TextActor.cpp @@ -32,7 +32,7 @@ TextActorPtr TextActor::Create(const String& text) TextActorPtr TextActor::Create(const String& text, const TextStyle& style) { - TextActorPtr ptr = memory::New(); + TextActorPtr ptr = new (autogc) TextActor; if (ptr) { ptr->SetStyle(style); diff --git a/src/kiwano/2d/Transition.cpp b/src/kiwano/2d/Transition.cpp index acf0c722..fcd9c7a7 100644 --- a/src/kiwano/2d/Transition.cpp +++ b/src/kiwano/2d/Transition.cpp @@ -128,7 +128,7 @@ void Transition::Stop() BoxTransitionPtr BoxTransition::Create(Duration duration) { - BoxTransitionPtr ptr = memory::New(); + BoxTransitionPtr ptr = new (autogc) BoxTransition; if (ptr) { ptr->SetDuration(duration); @@ -169,7 +169,7 @@ void BoxTransition::Update(Duration dt) EmergeTransitionPtr EmergeTransition::Create(Duration duration) { - EmergeTransitionPtr ptr = memory::New(); + EmergeTransitionPtr ptr = new (autogc) EmergeTransition; if (ptr) { ptr->SetDuration(duration); @@ -201,7 +201,7 @@ void EmergeTransition::Update(Duration dt) FadeTransitionPtr FadeTransition::Create(Duration duration) { - FadeTransitionPtr ptr = memory::New(); + FadeTransitionPtr ptr = new (autogc) FadeTransition; if (ptr) { ptr->SetDuration(duration); @@ -241,7 +241,7 @@ void FadeTransition::Update(Duration dt) MoveTransitionPtr MoveTransition::Create(Duration duration, Type type) { - MoveTransitionPtr ptr = memory::New(); + MoveTransitionPtr ptr = new (autogc) MoveTransition; if (ptr) { ptr->type_ = type; @@ -330,7 +330,7 @@ void MoveTransition::Reset() RotationTransitionPtr RotationTransition::Create(Duration duration, float rotation) { - RotationTransitionPtr ptr = memory::New(); + RotationTransitionPtr ptr = new (autogc) RotationTransition; if (ptr) { ptr->rotation_ = rotation; diff --git a/src/kiwano/2d/action/Action.h b/src/kiwano/2d/action/Action.h index f9d0ac5c..2a48709a 100644 --- a/src/kiwano/2d/action/Action.h +++ b/src/kiwano/2d/action/Action.h @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include #include #include diff --git a/src/kiwano/2d/action/ActionDelay.cpp b/src/kiwano/2d/action/ActionDelay.cpp index 06f1023f..1b7750d9 100644 --- a/src/kiwano/2d/action/ActionDelay.cpp +++ b/src/kiwano/2d/action/ActionDelay.cpp @@ -30,7 +30,7 @@ ActionDelay::ActionDelay(Duration delay) ActionDelayEntityPtr ActionDelayEntity::Create(Duration delay) { - ActionDelayEntityPtr ptr = memory::New(); + ActionDelayEntityPtr ptr = new (autogc) ActionDelayEntity; if (ptr) { ptr->SetDelay(delay); diff --git a/src/kiwano/2d/action/ActionGroup.cpp b/src/kiwano/2d/action/ActionGroup.cpp index f11b7509..2128c3b2 100644 --- a/src/kiwano/2d/action/ActionGroup.cpp +++ b/src/kiwano/2d/action/ActionGroup.cpp @@ -32,7 +32,7 @@ ActionGroup::ActionGroup(const Vector& actions, bool parallel) ActionGroupEntityPtr ActionGroupEntity::Create(const Vector& actions, bool parallel) { - ActionGroupEntityPtr ptr = memory::New(); + ActionGroupEntityPtr ptr = new (autogc) ActionGroupEntity; if (ptr) { ptr->parallel_ = parallel; diff --git a/src/kiwano/2d/action/ActionTween.cpp b/src/kiwano/2d/action/ActionTween.cpp index c0c65865..4669db6c 100644 --- a/src/kiwano/2d/action/ActionTween.cpp +++ b/src/kiwano/2d/action/ActionTween.cpp @@ -145,7 +145,7 @@ ActionEntityPtr ActionTweenEntity::DoClone(ActionTweenEntityPtr to) const ActionMoveByEntityPtr ActionMoveByEntity::Create(Duration duration, const Vec2& displacement) { - ActionMoveByEntityPtr ptr = memory::New(); + ActionMoveByEntityPtr ptr = new (autogc) ActionMoveByEntity; if (ptr) { ptr->SetDuration(duration); @@ -187,7 +187,7 @@ ActionEntityPtr ActionMoveByEntity::Reverse() const ActionMoveToEntityPtr ActionMoveToEntity::Create(Duration duration, const Point& distination) { - ActionMoveToEntityPtr ptr = memory::New(); + ActionMoveToEntityPtr ptr = new (autogc) ActionMoveToEntity; if (ptr) { ptr->SetDuration(duration); @@ -215,7 +215,7 @@ void ActionMoveToEntity::Init(Actor* target) ActionJumpByEntityPtr ActionJumpByEntity::Create(Duration duration, const Vec2& displacement, float height, int count) { - ActionJumpByEntityPtr ptr = memory::New(); + ActionJumpByEntityPtr ptr = new (autogc) ActionJumpByEntity; if (ptr) { ptr->SetDuration(duration); @@ -268,7 +268,7 @@ void ActionJumpByEntity::UpdateTween(Actor* target, float percent) ActionJumpToEntityPtr ActionJumpToEntity::Create(Duration duration, const Point& distination, float height, int count) { - ActionJumpToEntityPtr ptr = memory::New(); + ActionJumpToEntityPtr ptr = new (autogc) ActionJumpToEntity; if (ptr) { ptr->SetDuration(duration); @@ -298,7 +298,7 @@ void ActionJumpToEntity::Init(Actor* target) ActionScaleByEntityPtr ActionScaleByEntity::Create(Duration duration, float scale_x, float scale_y) { - ActionScaleByEntityPtr ptr = memory::New(); + ActionScaleByEntityPtr ptr = new (autogc) ActionScaleByEntity; if (ptr) { ptr->SetDuration(duration); @@ -342,7 +342,7 @@ ActionEntityPtr ActionScaleByEntity::Reverse() const ActionScaleToEntityPtr ActionScaleToEntity::Create(Duration duration, float scale_x, float scale_y) { - ActionScaleToEntityPtr ptr = memory::New(); + ActionScaleToEntityPtr ptr = new (autogc) ActionScaleToEntity; if (ptr) { ptr->SetDuration(duration); @@ -376,7 +376,7 @@ void ActionScaleToEntity::Init(Actor* target) ActionFadeToEntityPtr ActionFadeToEntity::Create(Duration duration, float opacity) { - ActionFadeToEntityPtr ptr = memory::New(); + ActionFadeToEntityPtr ptr = new (autogc) ActionFadeToEntity; if (ptr) { ptr->SetDuration(duration); @@ -417,7 +417,7 @@ ActionEntityPtr ActionFadeToEntity::Clone() const ActionRotateByEntityPtr ActionRotateByEntity::Create(Duration duration, float rotation) { - ActionRotateByEntityPtr ptr = memory::New(); + ActionRotateByEntityPtr ptr = new (autogc) ActionRotateByEntity; if (ptr) { ptr->SetDuration(duration); @@ -461,7 +461,7 @@ ActionEntityPtr ActionRotateByEntity::Reverse() const ActionRotateToEntityPtr ActionRotateToEntity::Create(Duration duration, float rotation) { - ActionRotateToEntityPtr ptr = memory::New(); + ActionRotateToEntityPtr ptr = new (autogc) ActionRotateToEntity; if (ptr) { ptr->SetDuration(duration); @@ -492,7 +492,7 @@ void ActionRotateToEntity::Init(Actor* target) ActionCustomEntityPtr ActionCustomEntity::Create(Duration duration, ActionCustom::TweenFunc tween_func) { - ActionCustomEntityPtr ptr = memory::New(); + ActionCustomEntityPtr ptr = new (autogc) ActionCustomEntity; if (ptr) { ptr->SetDuration(duration); diff --git a/src/kiwano/2d/action/ActionWalk.cpp b/src/kiwano/2d/action/ActionWalk.cpp index 8a1eb12c..db197249 100644 --- a/src/kiwano/2d/action/ActionWalk.cpp +++ b/src/kiwano/2d/action/ActionWalk.cpp @@ -31,7 +31,7 @@ ActionWalk::ActionWalk(Duration duration, ShapePtr path, bool rotating, float st ActionWalkEntityPtr ActionWalkEntity::Create(Duration duration, ShapePtr path, bool rotating, float start, float end) { - ActionWalkEntityPtr ptr = memory::New(); + ActionWalkEntityPtr ptr = new (autogc) ActionWalkEntity; if (ptr) { ptr->SetDuration(duration); diff --git a/src/kiwano/2d/action/Animation.cpp b/src/kiwano/2d/action/Animation.cpp index 3e494f48..4828db46 100644 --- a/src/kiwano/2d/action/Animation.cpp +++ b/src/kiwano/2d/action/Animation.cpp @@ -32,7 +32,7 @@ Animation::Animation(Duration dur, FrameSequencePtr frame_seq) AnimationEntityPtr AnimationEntity::Create(Duration dur, FrameSequencePtr frame_seq) { - AnimationEntityPtr ptr = memory::New(); + AnimationEntityPtr ptr = new (autogc) AnimationEntity; if (ptr) { ptr->SetDuration(dur); diff --git a/src/kiwano/base/Director.cpp b/src/kiwano/base/Director.cpp index d4d09a92..263d1564 100644 --- a/src/kiwano/base/Director.cpp +++ b/src/kiwano/base/Director.cpp @@ -99,7 +99,7 @@ void Director::ShowDebugInfo(bool show) if (show) { if (!debug_actor_) - debug_actor_ = memory::New(); + debug_actor_ = new (autogc) DebugActor; } else { diff --git a/src/kiwano/base/ObjectBase.cpp b/src/kiwano/base/ObjectBase.cpp index 339350ea..99c05f9e 100644 --- a/src/kiwano/base/ObjectBase.cpp +++ b/src/kiwano/base/ObjectBase.cpp @@ -19,7 +19,6 @@ // THE SOFTWARE. #include -#include #include #include #include @@ -28,9 +27,11 @@ namespace kiwano { namespace { + bool tracing_leaks = false; Vector tracing_objects; uint32_t last_object_id = 0; + } // namespace ObjectBase::ObjectBase() @@ -57,11 +58,6 @@ ObjectBase::~ObjectBase() #endif } -void ObjectBase::AutoRelease() -{ - ObjectPool::GetInstance().AddObject(this); -} - const Any& ObjectBase::GetUserData() const { return user_data_; diff --git a/src/kiwano/base/ObjectBase.h b/src/kiwano/base/ObjectBase.h index 927e2549..7f7859bd 100644 --- a/src/kiwano/base/ObjectBase.h +++ b/src/kiwano/base/ObjectBase.h @@ -22,8 +22,8 @@ #include #include #include -#include -#include +#include +#include namespace kiwano { @@ -34,7 +34,7 @@ KGE_DECLARE_SMART_PTR(ObjectBase); * @brief 基础对象 */ class KGE_API ObjectBase - : public RefCounter + : public RefObject , public Serializable { public: @@ -44,10 +44,6 @@ public: virtual ~ObjectBase(); - /// \~chinese - /// @brief 自动释放 - void AutoRelease(); - /// \~chinese /// @brief 设置对象名 void SetName(const String& name); diff --git a/src/kiwano/base/ObjectPool.cpp b/src/kiwano/base/ObjectPool.cpp index 66ba259c..189a43de 100644 --- a/src/kiwano/base/ObjectPool.cpp +++ b/src/kiwano/base/ObjectPool.cpp @@ -23,56 +23,35 @@ namespace kiwano { -List ObjectPool::pools_; - -ObjectPool& ObjectPool::GetInstance() -{ - static ObjectPool instance; - return *pools_.back(); -} - ObjectPool::ObjectPool() { - pools_.push_back(this); } ObjectPool::~ObjectPool() { Clear(); - - auto iter = std::find(pools_.begin(), pools_.end(), this); - if (iter != pools_.end()) - pools_.erase(iter); } -void ObjectPool::AddObject(ObjectBase* obj) +void ObjectPool::AddObject(RefObject* obj) { if (obj) { + std::lock_guard lock(mutex_); if (!Contains(obj)) { - obj->Retain(); - - std::lock_guard lock(mutex_); objects_.push_back(obj); } } } -bool ObjectPool::Contains(ObjectBase* obj) const +bool ObjectPool::Contains(RefObject* obj) const { - std::lock_guard lock(const_cast(mutex_)); - - for (auto iter = pools_.rbegin(); iter != pools_.rend(); iter++) - for (const auto o : (*iter)->objects_) - if (obj == o) - return true; - return false; + return std::find(objects_.begin(), objects_.end(), obj) != objects_.end(); } void ObjectPool::Clear() { - Vector copied; + Vector copied; { std::lock_guard lock(mutex_); diff --git a/src/kiwano/base/ObjectPool.h b/src/kiwano/base/ObjectPool.h index 72ac3d5b..af17d68f 100644 --- a/src/kiwano/base/ObjectPool.h +++ b/src/kiwano/base/ObjectPool.h @@ -19,21 +19,22 @@ // THE SOFTWARE. #pragma once +#include #include #include namespace kiwano { + /** * \~chinese * @brief 对象池 */ -class KGE_API ObjectPool - : public Noncopyable +class KGE_API ObjectPool : public Singleton { -public: - static ObjectPool& GetInstance(); + friend Singleton; +public: ObjectPool(); virtual ~ObjectPool(); @@ -41,16 +42,16 @@ public: /** * \~chinese * @brief 添加对象到内存池 - * @param[in] obj 基础对象 + * @param[in] obj 引用计数对象 */ - void AddObject(ObjectBase* obj); + void AddObject(RefObject* obj); /** * \~chinese * @brief 判断对象是否在对象池中 - * @param[in] obj 基础对象 + * @param[in] obj 引用计数对象 */ - bool Contains(ObjectBase* obj) const; + bool Contains(RefObject* obj) const; /** * \~chinese @@ -65,8 +66,7 @@ private: private: std::mutex mutex_; - Vector objects_; - - static List pools_; + Vector objects_; }; + } // namespace kiwano diff --git a/src/kiwano/base/RefCounter.cpp b/src/kiwano/base/RefObject.cpp similarity index 61% rename from src/kiwano/base/RefCounter.cpp rename to src/kiwano/base/RefObject.cpp index 27e44e5e..04464071 100644 --- a/src/kiwano/base/RefCounter.cpp +++ b/src/kiwano/base/RefObject.cpp @@ -18,29 +18,63 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include +#include namespace kiwano { -RefCounter::RefCounter() - : ref_count_(0) + +autogc_t const autogc; + +RefObject::RefObject() + : ref_count_(1) { } -RefCounter::~RefCounter() {} +RefObject::~RefObject() {} -void RefCounter::Retain() +void RefObject::Retain() { ++ref_count_; } -void RefCounter::Release() +void RefObject::Release() { --ref_count_; if (ref_count_ == 0) { - memory::Delete(this); + delete this; } } +void RefObject::AutoRelease() +{ + ObjectPool::GetInstance().AddObject(this); +} + +void* RefObject::operator new(std::size_t size) +{ + return memory::Alloc(size); +} + +void* RefObject::operator new(std::size_t size, autogc_t const&) +{ + void* ptr = memory::Alloc(size); + if (ptr) + { + ObjectPool::GetInstance().AddObject((ObjectBase*)ptr); + } + return ptr; +} + +void RefObject::operator delete(void* ptr) +{ + memory::Free(ptr); +} + +void RefObject::operator delete(void* ptr, autogc_t const&) +{ + memory::Free(ptr); +} + } // namespace kiwano diff --git a/src/kiwano/base/RefCounter.h b/src/kiwano/base/RefObject.h similarity index 74% rename from src/kiwano/base/RefCounter.h rename to src/kiwano/base/RefObject.h index 9a030876..ede57076 100644 --- a/src/kiwano/base/RefCounter.h +++ b/src/kiwano/base/RefObject.h @@ -24,17 +24,21 @@ namespace kiwano { + +struct autogc_t +{ + autogc_t() = default; +}; + +extern autogc_t const autogc; + /** * \~chinese * @brief 引用计数器 */ -class KGE_API RefCounter : protected Noncopyable +class KGE_API RefObject : protected Noncopyable { public: - RefCounter(); - - virtual ~RefCounter(); - /// \~chinese /// @brief 增加引用计数 void Retain(); @@ -43,17 +47,34 @@ public: /// @brief 减少引用计数 void Release(); + /// \~chinese + /// @brief 自动释放 + void AutoRelease(); + /// \~chinese /// @brief 获取引用计数 uint32_t GetRefCount() const; + void* operator new(std::size_t size); + + void* operator new(std::size_t size, autogc_t const&); + + void operator delete(void* ptr); + + void operator delete(void* ptr, autogc_t const&); + +protected: + RefObject(); + + virtual ~RefObject(); + private: std::atomic ref_count_; }; -inline uint32_t RefCounter::GetRefCount() const +inline uint32_t RefObject::GetRefCount() const { - return ref_count_; + return ref_count_.load(); } } // namespace kiwano diff --git a/src/kiwano/base/component/Button.cpp b/src/kiwano/base/component/Button.cpp index c8fbc49b..64388a98 100644 --- a/src/kiwano/base/component/Button.cpp +++ b/src/kiwano/base/component/Button.cpp @@ -33,7 +33,7 @@ ButtonPtr Button::Create(const Callback& click) ButtonPtr Button::Create(const Callback& click, const Callback& pressed, const Callback& mouse_over, const Callback& mouse_out) { - ButtonPtr ptr = memory::New