From b4664deed080887d31dd7b7fa71fb9413736ad84 Mon Sep 17 00:00:00 2001 From: Nomango Date: Thu, 16 Apr 2020 09:43:29 +0800 Subject: [PATCH 01/37] [chore] update Doxyfile --- Doxyfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doxyfile b/Doxyfile index 8d683bfe..8f08f32f 100644 --- a/Doxyfile +++ b/Doxyfile @@ -5,7 +5,7 @@ #--------------------------------------------------------------------------- PROJECT_NAME = "Kiwano Engine" -PROJECT_NUMBER = v1.0.14 +PROJECT_NUMBER = v1.0.x PROJECT_BRIEF = PROJECT_LOGO = logo/logo_tiny.png From 178d54b0d14acc2c8a9afabdd888825c1635c347 Mon Sep 17 00:00:00 2001 From: Nomango Date: Thu, 16 Apr 2020 10:06:36 +0800 Subject: [PATCH 02/37] [chore] update Doxygen comments --- src/kiwano/2d/Button.h | 7 +++++++ src/kiwano/2d/Component.h | 12 ++++++++++++ src/kiwano/core/Serializable.h | 16 ++++++++++++++-- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/kiwano/2d/Button.h b/src/kiwano/2d/Button.h index 946f40dc..197be05b 100644 --- a/src/kiwano/2d/Button.h +++ b/src/kiwano/2d/Button.h @@ -26,6 +26,11 @@ namespace kiwano KGE_DECLARE_SMART_PTR(Button); +/** + * \addtogroup Component + * @{ + */ + /** * \~chinese * @brief 按钮 @@ -109,6 +114,8 @@ private: Callback mouse_out_callback_; }; +/** @} */ + inline void Button::SetClickCallback(const Callback& func) { click_callback_ = func; diff --git a/src/kiwano/2d/Component.h b/src/kiwano/2d/Component.h index 8e62ca30..3830b8ba 100644 --- a/src/kiwano/2d/Component.h +++ b/src/kiwano/2d/Component.h @@ -32,6 +32,16 @@ class Event; KGE_DECLARE_SMART_PTR(Component); +/** + * \~chinese + * \defgroup Component 组件 + */ + +/** + * \addtogroup Component + * @{ + */ + /// \~chinese /// @brief 组件列表 typedef IntrusiveList ComponentList; @@ -94,6 +104,8 @@ private: Actor* actor_; }; +/** @} */ + inline bool Component::IsEnable() const { return enabled_; diff --git a/src/kiwano/core/Serializable.h b/src/kiwano/core/Serializable.h index 821865cc..c160cf7d 100644 --- a/src/kiwano/core/Serializable.h +++ b/src/kiwano/core/Serializable.h @@ -24,6 +24,15 @@ namespace kiwano { +/** + * \~chinese + * \defgroup Serialization 序列化 + */ + +/** + * \addtogroup Serialization + * @{ + */ /// \~chinese /// @brief 序列化器 @@ -230,7 +239,7 @@ class Serializable { public: /// \~chinese - /// @brief 序列化为字符串 + /// @brief 序列化为字节串 inline Vector Serialize() const { Vector data; @@ -240,7 +249,7 @@ public: } /// \~chinese - /// @brief 从字符串反序列化 + /// @brief 从字节串反序列化 inline void Deserialize(const Vector& data) { ByteDeserializer deserializer(data); @@ -438,4 +447,7 @@ inline Deserializer& operator>>(Deserializer& deserializer, math::TransformT> transform.position >> transform.rotation >> transform.scale >> transform.skew; } +/** @} */ + + } // namespace kiwano From 8331126bbcb9a2034d94f196add2053334eb435f Mon Sep 17 00:00:00 2001 From: Nomango Date: Thu, 16 Apr 2020 11:36:56 +0800 Subject: [PATCH 03/37] add favicon.ico in Doxyfile --- Doxyfile | 1 + logo/{icon.ico => favicon.ico} | Bin 2 files changed, 1 insertion(+) rename logo/{icon.ico => favicon.ico} (100%) diff --git a/Doxyfile b/Doxyfile index 8f08f32f..56599aa5 100644 --- a/Doxyfile +++ b/Doxyfile @@ -81,6 +81,7 @@ HTML_HEADER = HTML_FOOTER = HTML_STYLESHEET = HTML_EXTRA_STYLESHEET = +HTML_EXTRA_FILES = logo/favicon.ico GENERATE_TREEVIEW = YES ENUM_VALUES_PER_LINE = 4 diff --git a/logo/icon.ico b/logo/favicon.ico similarity index 100% rename from logo/icon.ico rename to logo/favicon.ico From b790bb7315321e607619c73eb0f3a55219dff5b7 Mon Sep 17 00:00:00 2001 From: Nomango Date: Sun, 26 Apr 2020 21:20:58 +0800 Subject: [PATCH 04/37] [deploy] Use Canvas::GetContext2D() instead of drawing functions --- projects/kiwano/kiwano.vcxproj | 8 +- projects/kiwano/kiwano.vcxproj.filters | 24 +- src/kiwano-physics/PhysicWorld.cpp | 35 +-- src/kiwano/2d/Canvas.cpp | 241 +----------------- src/kiwano/2d/Canvas.h | 265 +------------------- src/kiwano/2d/Sprite.h | 2 +- src/kiwano/2d/action/Animation.cpp | 2 +- src/kiwano/2d/action/Animation.h | 2 +- src/kiwano/kiwano.h | 4 +- src/kiwano/{2d => render}/Frame.cpp | 2 +- src/kiwano/{2d => render}/Frame.h | 0 src/kiwano/{2d => render}/FrameSequence.cpp | 2 +- src/kiwano/{2d => render}/FrameSequence.h | 2 +- src/kiwano/render/RenderContext.cpp | 26 ++ src/kiwano/render/RenderContext.h | 25 ++ src/kiwano/utils/ResourceCache.h | 4 +- 16 files changed, 102 insertions(+), 542 deletions(-) rename src/kiwano/{2d => render}/Frame.cpp (98%) rename src/kiwano/{2d => render}/Frame.h (100%) rename src/kiwano/{2d => render}/FrameSequence.cpp (99%) rename src/kiwano/{2d => render}/FrameSequence.h (99%) diff --git a/projects/kiwano/kiwano.vcxproj b/projects/kiwano/kiwano.vcxproj index 06c49d61..f8ae48e0 100644 --- a/projects/kiwano/kiwano.vcxproj +++ b/projects/kiwano/kiwano.vcxproj @@ -11,7 +11,6 @@ - @@ -39,7 +38,6 @@ - @@ -86,6 +84,8 @@ + + @@ -114,8 +114,6 @@ - - @@ -160,6 +158,8 @@ + + diff --git a/projects/kiwano/kiwano.vcxproj.filters b/projects/kiwano/kiwano.vcxproj.filters index 034a860a..86b3cb0b 100644 --- a/projects/kiwano/kiwano.vcxproj.filters +++ b/projects/kiwano/kiwano.vcxproj.filters @@ -84,9 +84,6 @@ 2d - - 2d - 2d\action @@ -108,9 +105,6 @@ utils - - 2d - 2d @@ -327,6 +321,12 @@ core + + render + + + render + @@ -365,9 +365,6 @@ 2d - - 2d - 2d\action @@ -386,9 +383,6 @@ utils - - 2d - 2d @@ -539,6 +533,12 @@ core + + render + + + render + diff --git a/src/kiwano-physics/PhysicWorld.cpp b/src/kiwano-physics/PhysicWorld.cpp index afe7406e..e97384b7 100644 --- a/src/kiwano-physics/PhysicWorld.cpp +++ b/src/kiwano-physics/PhysicWorld.cpp @@ -32,25 +32,23 @@ public: DebugDrawer(const Size& size) { canvas_ = Canvas::Create(size); + ctx_ = canvas_->GetContext2D(); fill_brush_ = Brush::Create(Color::White); line_brush_ = Brush::Create(Color::White); - canvas_->SetFillBrush(fill_brush_); - canvas_->SetStrokeBrush(line_brush_); - b2Draw::SetFlags(b2Draw::e_shapeBit | b2Draw::e_jointBit | b2Draw::e_jointBit | b2Draw::e_centerOfMassBit); } void BeginDraw() { - canvas_->BeginDraw(); - canvas_->Clear(); + ctx_->BeginDraw(); + ctx_->Clear(); } void EndDraw() { - canvas_->EndDraw(); + ctx_->EndDraw(); } void Render(RenderContext& ctx) @@ -61,11 +59,13 @@ public: void SetFillColor(const b2Color& color) { fill_brush_->SetColor(reinterpret_cast(color)); + ctx_->SetCurrentBrush(fill_brush_); } void SetLineColor(const b2Color& color) { line_brush_->SetColor(reinterpret_cast(color)); + ctx_->SetCurrentBrush(line_brush_); } void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) override @@ -76,7 +76,7 @@ public: for (int32 i = 0; i < vertexCount; ++i) { b2Vec2 p2 = vertices[i]; - canvas_->DrawLine(global::WorldToLocal(p1), global::WorldToLocal(p2)); + ctx_->DrawLine(global::WorldToLocal(p1), global::WorldToLocal(p2)); p1 = p2; } } @@ -92,25 +92,25 @@ public: maker.EndPath(true); SetFillColor(color); - canvas_->FillShape(maker.GetShape()); + ctx_->FillShape(*maker.GetShape()); } void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) override { SetLineColor(color); - canvas_->DrawCircle(global::WorldToLocal(center), global::WorldToLocal(radius)); + ctx_->DrawCircle(global::WorldToLocal(center), global::WorldToLocal(radius)); } void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) override { SetFillColor(color); - canvas_->FillCircle(global::WorldToLocal(center), global::WorldToLocal(radius)); + ctx_->FillCircle(global::WorldToLocal(center), global::WorldToLocal(radius)); } void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) override { SetLineColor(color); - canvas_->DrawLine(global::WorldToLocal(p1), global::WorldToLocal(p2)); + ctx_->DrawLine(global::WorldToLocal(p1), global::WorldToLocal(p2)); } void DrawTransform(const b2Transform& xf) override @@ -124,24 +124,25 @@ public: p2 = p1 + k_axisScale * xf.q.GetXAxis(); SetLineColor(red); - canvas_->DrawLine(global::WorldToLocal(p1), global::WorldToLocal(p2)); + ctx_->DrawLine(global::WorldToLocal(p1), global::WorldToLocal(p2)); p2 = p1 + k_axisScale * xf.q.GetYAxis(); SetLineColor(green); - canvas_->DrawLine(global::WorldToLocal(p1), global::WorldToLocal(p2)); + ctx_->DrawLine(global::WorldToLocal(p1), global::WorldToLocal(p2)); } void DrawPoint(const b2Vec2& p, float32 size, const b2Color& color) override { SetFillColor(color); - canvas_->FillCircle(global::WorldToLocal(p), global::WorldToLocal(size)); + ctx_->FillCircle(global::WorldToLocal(p), global::WorldToLocal(size)); } private: - CanvasPtr canvas_; - BrushPtr fill_brush_; - BrushPtr line_brush_; + CanvasPtr canvas_; + RenderContextPtr ctx_; + BrushPtr fill_brush_; + BrushPtr line_brush_; }; class DestructionListener : public b2DestructionListener diff --git a/src/kiwano/2d/Canvas.cpp b/src/kiwano/2d/Canvas.cpp index 661c4e60..0a272d3e 100644 --- a/src/kiwano/2d/Canvas.cpp +++ b/src/kiwano/2d/Canvas.cpp @@ -42,20 +42,11 @@ CanvasPtr Canvas::Create(const Size& size) return ptr; } -Canvas::Canvas() -{ -} +Canvas::Canvas() {} -void Canvas::BeginDraw() +RenderContextPtr Canvas::GetContext2D() const { - KGE_ASSERT(render_ctx_); - render_ctx_->BeginDraw(); -} - -void Canvas::EndDraw() -{ - KGE_ASSERT(render_ctx_); - render_ctx_->EndDraw(); + return render_ctx_; } void Canvas::OnRender(RenderContext& ctx) @@ -66,232 +57,6 @@ void Canvas::OnRender(RenderContext& ctx) } } -void Canvas::SetBrush(BrushPtr brush) -{ - KGE_ASSERT(render_ctx_); - render_ctx_->SetCurrentBrush(brush); -} - -void Canvas::SetBrushTransform(const Transform& transform) -{ - KGE_ASSERT(render_ctx_); - render_ctx_->SetTransform(transform.ToMatrix()); -} - -void Canvas::SetBrushTransform(const Matrix3x2& transform) -{ - KGE_ASSERT(render_ctx_); - render_ctx_->SetTransform(transform); -} - -void Canvas::PushLayer(LayerPtr layer) -{ - KGE_ASSERT(render_ctx_); - if (layer) - { - render_ctx_->PushLayer(*layer); - } -} - -void Canvas::PopLayer() -{ - KGE_ASSERT(render_ctx_); - render_ctx_->PopLayer(); -} - -void Canvas::PushClipRect(const Rect& clip_rect) -{ - KGE_ASSERT(render_ctx_); - render_ctx_->PushClipRect(clip_rect); -} - -void Canvas::PopClipRect() -{ - KGE_ASSERT(render_ctx_); - render_ctx_->PopClipRect(); -} - -void Canvas::DrawShape(ShapePtr shape) -{ - KGE_ASSERT(render_ctx_); - if (shape) - { - render_ctx_->SetCurrentBrush(stroke_brush_); - render_ctx_->SetCurrentStrokeStyle(stroke_style_); - render_ctx_->DrawShape(*shape); - } -} - -void Canvas::DrawLine(const Point& begin, const Point& end) -{ - KGE_ASSERT(render_ctx_); - render_ctx_->SetCurrentBrush(stroke_brush_); - render_ctx_->SetCurrentStrokeStyle(stroke_style_); - render_ctx_->DrawLine(begin, end); -} - -void Canvas::DrawCircle(const Point& center, float radius) -{ - KGE_ASSERT(render_ctx_); - render_ctx_->SetCurrentBrush(stroke_brush_); - render_ctx_->SetCurrentStrokeStyle(stroke_style_); - render_ctx_->DrawEllipse(center, Vec2(radius, radius)); -} - -void Canvas::DrawEllipse(const Point& center, const Vec2& radius) -{ - KGE_ASSERT(render_ctx_); - render_ctx_->SetCurrentBrush(stroke_brush_); - render_ctx_->SetCurrentStrokeStyle(stroke_style_); - render_ctx_->DrawEllipse(center, radius); -} - -void Canvas::DrawRect(const Rect& rect) -{ - KGE_ASSERT(render_ctx_); - render_ctx_->SetCurrentBrush(stroke_brush_); - render_ctx_->SetCurrentStrokeStyle(stroke_style_); - render_ctx_->DrawRectangle(rect); -} - -void Canvas::DrawRoundedRect(const Rect& rect, const Vec2& radius) -{ - KGE_ASSERT(render_ctx_); - render_ctx_->SetCurrentBrush(stroke_brush_); - render_ctx_->SetCurrentStrokeStyle(stroke_style_); - render_ctx_->DrawRoundedRectangle(rect, radius); -} - -void Canvas::FillShape(ShapePtr shape) -{ - KGE_ASSERT(render_ctx_); - if (shape) - { - render_ctx_->SetCurrentBrush(fill_brush_); - render_ctx_->FillShape(*shape); - } -} - -void Canvas::FillCircle(const Point& center, float radius) -{ - KGE_ASSERT(render_ctx_); - render_ctx_->SetCurrentBrush(fill_brush_); - render_ctx_->FillEllipse(center, Vec2(radius, radius)); -} - -void Canvas::FillEllipse(const Point& center, const Vec2& radius) -{ - KGE_ASSERT(render_ctx_); - render_ctx_->SetCurrentBrush(fill_brush_); - render_ctx_->FillEllipse(center, radius); -} - -void Canvas::FillRect(const Rect& rect) -{ - KGE_ASSERT(render_ctx_); - render_ctx_->SetCurrentBrush(fill_brush_); - render_ctx_->FillRectangle(rect); -} - -void Canvas::FillRoundedRect(const Rect& rect, const Vec2& radius) -{ - KGE_ASSERT(render_ctx_); - render_ctx_->SetCurrentBrush(fill_brush_); - render_ctx_->FillRoundedRectangle(rect, radius); -} - -void Canvas::DrawFrame(FramePtr frame, const Point& pos) -{ - KGE_ASSERT(render_ctx_); - if (frame && frame->IsValid()) - { - render_ctx_->DrawTexture(*frame->GetTexture(), &frame->GetCropRect(), &Rect(pos, frame->GetSize())); - } -} - -void Canvas::DrawFrame(FramePtr frame, const Point& pos, const Size& size) -{ - KGE_ASSERT(render_ctx_); - if (frame && frame->IsValid()) - { - render_ctx_->DrawTexture(*frame->GetTexture(), &frame->GetCropRect(), &Rect(pos, size)); - } -} - -void Canvas::DrawTextLayout(const String& text, const TextStyle& style, const Point& point) -{ - if (text.empty()) - return; - - DrawTextLayout(TextLayout::Create(text, style), point); -} - -void Canvas::DrawTextLayout(TextLayoutPtr layout, const Point& point) -{ - KGE_ASSERT(render_ctx_); - if (layout) - { - render_ctx_->DrawTextLayout(*layout, point); - } -} - -void Canvas::BeginPath(const Point& begin_pos) -{ - shape_maker_.BeginPath(begin_pos); -} - -void Canvas::EndPath(bool closed) -{ - shape_maker_.EndPath(closed); -} - -void Canvas::AddLine(const Point& point) -{ - shape_maker_.AddLine(point); -} - -void Canvas::AddLines(const Vector& points) -{ - shape_maker_.AddLines(points); -} - -void Canvas::AddBezier(const Point& point1, const Point& point2, const Point& point3) -{ - shape_maker_.AddBezier(point1, point2, point3); -} - -void Canvas::AddArc(const Point& point, const Size& radius, float rotation, bool clockwise, bool is_small) -{ - shape_maker_.AddArc(point, radius, rotation, clockwise, is_small); -} - -void Canvas::StrokePath() -{ - KGE_ASSERT(render_ctx_); - render_ctx_->SetCurrentBrush(stroke_brush_); - render_ctx_->SetCurrentStrokeStyle(stroke_style_); - render_ctx_->DrawShape(*shape_maker_.GetShape()); -} - -void Canvas::FillPath() -{ - KGE_ASSERT(render_ctx_); - render_ctx_->SetCurrentBrush(fill_brush_); - render_ctx_->FillShape(*shape_maker_.GetShape()); -} - -void Canvas::Clear() -{ - KGE_ASSERT(render_ctx_); - render_ctx_->Clear(); -} - -void Canvas::Clear(const Color& clear_color) -{ - KGE_ASSERT(render_ctx_); - render_ctx_->Clear(clear_color); -} - void Canvas::ResizeAndClear(Size size) { texture_cached_ = memory::New(); diff --git a/src/kiwano/2d/Canvas.h b/src/kiwano/2d/Canvas.h index 2c8b46b2..f0f147f0 100644 --- a/src/kiwano/2d/Canvas.h +++ b/src/kiwano/2d/Canvas.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include #include #include @@ -48,222 +48,12 @@ public: static CanvasPtr Create(const Size& size); /// \~chinese - /// @brief 开始绘图 - void BeginDraw(); - - /// \~chinese - /// @brief 结束绘图 - void EndDraw(); - - /// \~chinese - /// @brief 画形状轮廓 - /// @param shape 形状 - void DrawShape(ShapePtr shape); - - /// \~chinese - /// @brief 画线段 - /// @param begin 线段起点 - /// @param end 线段终点 - void DrawLine(const Point& begin, const Point& end); - - /// \~chinese - /// @brief 画圆形边框 - /// @param center 圆形原点 - /// @param radius 圆形半径 - void DrawCircle(const Point& center, float radius); - - /// \~chinese - /// @brief 画椭圆形边框 - /// @param center 椭圆原点 - /// @param radius 椭圆半径 - void DrawEllipse(const Point& center, const Vec2& radius); - - /// \~chinese - /// @brief 画矩形边框 - /// @param rect 矩形 - void DrawRect(const Rect& rect); - - /// \~chinese - /// @brief 画圆角矩形边框 - /// @param rect 矩形 - /// @param radius 矩形圆角半径 - void DrawRoundedRect(const Rect& rect, const Vec2& radius); - - /// \~chinese - /// @brief 填充形状 - /// @param shape 形状 - void FillShape(ShapePtr shape); - - /// \~chinese - /// @brief 填充圆形 - /// @param center 圆形原点 - /// @param radius 圆形半径 - void FillCircle(const Point& center, float radius); - - /// \~chinese - /// @brief 填充椭圆形 - /// @param center 椭圆原点 - /// @param radius 椭圆半径 - void FillEllipse(const Point& center, const Vec2& radius); - - /// \~chinese - /// @brief 填充矩形 - /// @param rect 矩形 - void FillRect(const Rect& rect); - - /// \~chinese - /// @brief 填充圆角矩形 - /// @param rect 矩形 - /// @param radius 矩形圆角半径 - void FillRoundedRect(const Rect& rect, const Vec2& radius); - - /// \~chinese - /// @brief 绘制图像帧 - /// @param frame 图像帧 - /// @param pos 绘制图像的位置 - void DrawFrame(FramePtr frame, const Point& pos); - - /// \~chinese - /// @brief 绘制图像帧 - /// @param frame 图像帧 - /// @param pos 绘制图像的位置 - /// @param size 渲染的图像大小 - void DrawFrame(FramePtr frame, const Point& pos, const Size& size); - - /// \~chinese - /// @brief 绘制文字布局 - /// @param text 文字 - /// @param style 文字样式 - /// @param point 绘制文字的位置 - void DrawTextLayout(const String& text, const TextStyle& style, const Point& point); - - /// \~chinese - /// @brief 绘制文字布局 - /// @param layout 文字布局 - /// @param point 绘制布局的位置 - void DrawTextLayout(TextLayoutPtr layout, const Point& point); - - /// \~chinese - /// @brief 开始绘制路径 - /// @param begin_pos 路径起始点 - void BeginPath(const Point& begin_pos); - - /// \~chinese - /// @brief 结束路径 - /// @param closed 路径是否闭合 - void EndPath(bool closed = false); - - /// \~chinese - /// @brief 添加一条线段 - /// @param point 端点 - void AddLine(const Point& point); - - /// \~chinese - /// @brief 添加多条线段 - /// @param points 端点集合 - void AddLines(const Vector& points); - - /// \~chinese - /// @brief 添加一条三次方贝塞尔曲线 - /// @param point1 贝塞尔曲线的第一个控制点 - /// @param point2 贝塞尔曲线的第二个控制点 - /// @param point3 贝塞尔曲线的终点 - void AddBezier(const Point& point1, const Point& point2, const Point& point3); - - /// \~chinese - /// @brief 添加弧线 - /// @param point 终点 - /// @param radius 椭圆半径 - /// @param rotation 椭圆旋转角度 - /// @param clockwise 顺时针 or 逆时针 - /// @param is_small 是否取小于 180° 的弧 - void AddArc(const Point& point, const Size& radius, float rotation, bool clockwise = true, bool is_small = true); - - /// \~chinese - /// @brief 以描边的方式绘制路径 - void StrokePath(); - - /// \~chinese - /// @brief 以填充的方式绘制路径 - void FillPath(); - - /// \~chinese - /// @brief 清空画布 - void Clear(); - - /// \~chinese - /// @brief 清空画布 - /// @param clear_color 清空颜色 - void Clear(const Color& clear_color); - - /// \~chinese - /// @brief 设置填充颜色 - /// @param color 填充颜色 - void SetFillColor(const Color& color); - - /// \~chinese - /// @brief 设置填充画刷 - /// @param[in] brush 填充画刷 - void SetFillBrush(BrushPtr brush); - - /// \~chinese - /// @brief 设置轮廓颜色 - /// @param color 轮廓颜色 - void SetStrokeColor(const Color& color); - - /// \~chinese - /// @brief 设置轮廓画刷 - /// @param[in] brush 轮廓画刷 - void SetStrokeBrush(BrushPtr brush); - - /// \~chinese - /// @brief 设置轮廓样式 - /// @param stroke_style 轮廓样式 - void SetStrokeStyle(StrokeStylePtr stroke_style); - - /// \~chinese - /// @brief 设置画刷 - /// @param[in] brush 画刷 - void SetBrush(BrushPtr brush); - - /// \~chinese - /// @brief 设置画刷二维变换 - /// @param transform 二维变换 - void SetBrushTransform(const Transform& transform); - - /// \~chinese - /// @brief 设置画刷二维变换矩阵 - /// @param transform 二维变换矩阵 - void SetBrushTransform(const Matrix3x2& transform); - - /// \~chinese - /// @brief 添加一个图层 - /// @param layer 图层 - void PushLayer(LayerPtr layer); - - /// \~chinese - /// @brief 删除最近添加的图层 - void PopLayer(); - - /// \~chinese - /// @brief 添加一个裁剪区域 - /// @param clip_rect 裁剪矩形 - void PushClipRect(const Rect& clip_rect); - - /// \~chinese - /// @brief 删除最近添加的裁剪区域 - void PopClipRect(); - - /// \~chinese - /// @brief 获取填充画刷 - BrushPtr GetFillBrush() const; - - /// \~chinese - /// @brief 获取轮廓画刷 - BrushPtr GetStrokeBrush() const; + /// @brief 获取2D绘图上下文 + RenderContextPtr GetContext2D() const; /// \~chinese /// @brief 清空画布大小并重设画布大小 + /// @warning 该函数会导致原绘图上下文失效 void ResizeAndClear(Size size); /// \~chinese @@ -276,57 +66,10 @@ private: Canvas(); private: - StrokeStylePtr stroke_style_; - ShapeMaker shape_maker_; - BrushPtr fill_brush_; - BrushPtr stroke_brush_; TexturePtr texture_cached_; RenderContextPtr render_ctx_; }; /** @} */ -inline void Canvas::SetStrokeStyle(StrokeStylePtr stroke_style) -{ - stroke_style_ = stroke_style; -} - -inline void Canvas::SetStrokeColor(const Color& color) -{ - if (!stroke_brush_) - { - stroke_brush_ = memory::New(); - } - stroke_brush_->SetColor(color); -} - -inline void Canvas::SetFillColor(const Color& color) -{ - if (!fill_brush_) - { - fill_brush_ = memory::New(); - } - fill_brush_->SetColor(color); -} - -inline void Canvas::SetFillBrush(BrushPtr brush) -{ - fill_brush_ = brush; -} - -inline void Canvas::SetStrokeBrush(BrushPtr brush) -{ - stroke_brush_ = brush; -} - -inline BrushPtr Canvas::GetFillBrush() const -{ - return fill_brush_; -} - -inline BrushPtr Canvas::GetStrokeBrush() const -{ - return stroke_brush_; -} - } // namespace kiwano diff --git a/src/kiwano/2d/Sprite.h b/src/kiwano/2d/Sprite.h index dbadbc6f..934abbac 100644 --- a/src/kiwano/2d/Sprite.h +++ b/src/kiwano/2d/Sprite.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include namespace kiwano { diff --git a/src/kiwano/2d/action/Animation.cpp b/src/kiwano/2d/action/Animation.cpp index 1abdaae1..bb52344a 100644 --- a/src/kiwano/2d/action/Animation.cpp +++ b/src/kiwano/2d/action/Animation.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include #include diff --git a/src/kiwano/2d/action/Animation.h b/src/kiwano/2d/action/Animation.h index 769b7386..7e991c72 100644 --- a/src/kiwano/2d/action/Animation.h +++ b/src/kiwano/2d/action/Animation.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include #include namespace kiwano diff --git a/src/kiwano/kiwano.h b/src/kiwano/kiwano.h index cc1877cf..f63b0ea0 100644 --- a/src/kiwano/kiwano.h +++ b/src/kiwano/kiwano.h @@ -68,6 +68,8 @@ #include #include #include +#include +#include #include #include #include @@ -82,8 +84,6 @@ #include #include #include -#include -#include #include #include #include diff --git a/src/kiwano/2d/Frame.cpp b/src/kiwano/render/Frame.cpp similarity index 98% rename from src/kiwano/2d/Frame.cpp rename to src/kiwano/render/Frame.cpp index 9e9f95be..2c42cd7c 100644 --- a/src/kiwano/2d/Frame.cpp +++ b/src/kiwano/render/Frame.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include namespace kiwano diff --git a/src/kiwano/2d/Frame.h b/src/kiwano/render/Frame.h similarity index 100% rename from src/kiwano/2d/Frame.h rename to src/kiwano/render/Frame.h diff --git a/src/kiwano/2d/FrameSequence.cpp b/src/kiwano/render/FrameSequence.cpp similarity index 99% rename from src/kiwano/2d/FrameSequence.cpp rename to src/kiwano/render/FrameSequence.cpp index 008517fe..a5ce48fa 100644 --- a/src/kiwano/2d/FrameSequence.cpp +++ b/src/kiwano/render/FrameSequence.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include namespace kiwano diff --git a/src/kiwano/2d/FrameSequence.h b/src/kiwano/render/FrameSequence.h similarity index 99% rename from src/kiwano/2d/FrameSequence.h rename to src/kiwano/render/FrameSequence.h index 681ecfd2..904eba8d 100644 --- a/src/kiwano/2d/FrameSequence.h +++ b/src/kiwano/render/FrameSequence.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include #include #include diff --git a/src/kiwano/render/RenderContext.cpp b/src/kiwano/render/RenderContext.cpp index fcb281d2..0bd36a47 100644 --- a/src/kiwano/render/RenderContext.cpp +++ b/src/kiwano/render/RenderContext.cpp @@ -60,6 +60,22 @@ void RenderContext::EndDraw() } } +void RenderContext::DrawFrame(FramePtr frame, const Point& dest_pos) +{ + if (frame) + { + this->DrawTexture(*frame->GetTexture(), &frame->GetCropRect(), &Rect(dest_pos, frame->GetSize())); + } +} + +void RenderContext::DrawFrame(FramePtr frame, const Rect& dest_rect) +{ + if (frame) + { + this->DrawTexture(*frame->GetTexture(), &frame->GetCropRect(), &dest_rect); + } +} + void RenderContext::SetGlobalTransform(const Matrix3x2* matrix) { if (matrix) @@ -121,4 +137,14 @@ void RenderContext::SetCurrentStrokeStyle(StrokeStylePtr stroke) current_stroke_ = stroke; } +void RenderContext::DrawCircle(const Point& center, float radius) +{ + this->DrawEllipse(center, Vec2(radius, radius)); +} + +void RenderContext::FillCircle(const Point& center, float radius) +{ + this->FillEllipse(center, Vec2(radius, radius)); +} + } // namespace kiwano diff --git a/src/kiwano/render/RenderContext.h b/src/kiwano/render/RenderContext.h index 8bafec7c..6f2199a0 100644 --- a/src/kiwano/render/RenderContext.h +++ b/src/kiwano/render/RenderContext.h @@ -25,6 +25,7 @@ #include #include #include +#include namespace kiwano { @@ -79,6 +80,18 @@ public: virtual void DrawTexture(const Texture& texture, const Rect* src_rect = nullptr, const Rect* dest_rect = nullptr) = 0; + /// \~chinese + /// @brief 绘制图像帧 + /// @param frame 图像帧 + /// @param dest_pos 绘制图像的位置 + virtual void DrawFrame(FramePtr frame, const Point& dest_pos); + + /// \~chinese + /// @brief 绘制图像帧 + /// @param frame 图像帧 + /// @param dest_rect 绘制的目标区域 + virtual void DrawFrame(FramePtr frame, const Rect& dest_rect); + /// \~chinese /// @brief 绘制文本布局 /// @param layout 文本布局 @@ -107,6 +120,12 @@ public: /// @param radius 圆角半径 virtual void DrawRoundedRectangle(const Rect& rect, const Vec2& radius) = 0; + /// \~chinese + /// @brief 绘制圆形边框 + /// @param center 圆心 + /// @param radius 椭圆半径 + virtual void DrawCircle(const Point& center, float radius); + /// \~chinese /// @brief 绘制椭圆边框 /// @param center 圆心 @@ -129,6 +148,12 @@ public: /// @param radius 圆角半径 virtual void FillRoundedRectangle(const Rect& rect, const Vec2& radius) = 0; + /// \~chinese + /// @brief 填充圆形 + /// @param center 圆心 + /// @param radius 椭圆半径 + virtual void FillCircle(const Point& center, float radius); + /// \~chinese /// @brief 填充椭圆 /// @param center 圆心 diff --git a/src/kiwano/utils/ResourceCache.h b/src/kiwano/utils/ResourceCache.h index 7917f30f..6c40b938 100644 --- a/src/kiwano/utils/ResourceCache.h +++ b/src/kiwano/utils/ResourceCache.h @@ -19,8 +19,8 @@ // THE SOFTWARE. #pragma once -#include -#include +#include +#include #include #include #include From 8eb4c2e1ffe75b8cc2a13c4ab40ad7c3b0f41c81 Mon Sep 17 00:00:00 2001 From: "liuhaibo.2020" Date: Thu, 30 Apr 2020 14:41:41 +0800 Subject: [PATCH 05/37] Add configurations for MacOS --- .gitignore | 1 - .vscode/c_cpp_properties.json | 32 ++++++++++++++++++++++++++++++++ .vscode/settings.json | 4 ++++ src/kiwano/core/SmartPtr.hpp | 2 +- src/kiwano/macros.h | 28 +++++++++++++++++++++++++++- 5 files changed, 64 insertions(+), 3 deletions(-) create mode 100644 .vscode/c_cpp_properties.json create mode 100644 .vscode/settings.json diff --git a/.gitignore b/.gitignore index e430d78f..d2193be3 100644 --- a/.gitignore +++ b/.gitignore @@ -8,7 +8,6 @@ Release/ # Application folders .vs -.vscode # vs2010 ipch/ diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 00000000..de7425e9 --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,32 @@ +{ + "configurations": [ + { + "name": "Mac", + "includePath": [ + "${workspaceFolder}/src/**" + ], + "defines": [ + "TARGET_OS_MAC" + ], + "macFrameworkPath": [ + "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks" + ], + "compilerPath": "/usr/bin/clang", + "cStandard": "c11", + "cppStandard": "c++14", + "intelliSenseMode": "clang-x64" + }, + { + "name": "Linux", + "includePath": [ + "${workspaceFolder}/src/**" + ], + "defines": [], + "compilerPath": "/usr/bin/gcc", + "cStandard": "c11", + "cppStandard": "c++14", + "intelliSenseMode": "clang-x64" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..cfc8e1f0 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "files.autoGuessEncoding": true, + "files.encoding": "gb2312" +} \ No newline at end of file diff --git a/src/kiwano/core/SmartPtr.hpp b/src/kiwano/core/SmartPtr.hpp index ba73c09a..9b1989fd 100644 --- a/src/kiwano/core/SmartPtr.hpp +++ b/src/kiwano/core/SmartPtr.hpp @@ -268,7 +268,7 @@ inline bool operator<(const SmartPtr<_Ty, _ProxyTy>& lhs, const SmartPtr<_UTy, _ } // template class cannot specialize std::swap, -// so implement a Swap Function in kiwano namespace +// so implement a swap function in kiwano namespace template inline void swap(SmartPtr<_Ty, _ProxyTy>& lhs, SmartPtr<_Ty, _ProxyTy>& rhs) noexcept { diff --git a/src/kiwano/macros.h b/src/kiwano/macros.h index fd5ab8a7..27d54fb3 100644 --- a/src/kiwano/macros.h +++ b/src/kiwano/macros.h @@ -77,7 +77,7 @@ // ///////////////////////////////////////////////////////////// -#ifdef KGE_PLATFORM_WINDOWS +#if defined(KGE_PLATFORM_WINDOWS) #if KGE_RENDER_ENGINE == KGE_RENDER_ENGINE_NONE # undef KGE_RENDER_ENGINE @@ -157,6 +157,32 @@ KGE_SUPPRESS_WARNING(4251) #include #include +#elif defined(KGE_PLATFORM_MACOS) + +#if KGE_RENDER_ENGINE == KGE_RENDER_ENGINE_NONE +# undef KGE_RENDER_ENGINE +# define KGE_RENDER_ENGINE KGE_RENDER_ENGINE_OPENGL +#endif + +#define KGE_DEPRECATED(...) + +#define KGE_SUPPRESS_WARNING_PUSH +#define KGE_SUPPRESS_WARNING(CODE) +#define KGE_SUPPRESS_WARNING_POP + +#ifndef KGE_API +# if defined(KGE_USE_DLL) +# define KGE_API +# elif defined(KGE_EXPORT_DLL) +# define KGE_API +# endif +#endif + +#ifndef KGE_API +/* Building or calling Kiwano as a static library */ +# define KGE_API +#endif + #else #if KGE_RENDER_ENGINE == KGE_RENDER_ENGINE_DIRECTX From d6088ed79ca60822cba084a8cf4f6115931f8d30 Mon Sep 17 00:00:00 2001 From: "liuhaibo.2020" Date: Thu, 30 Apr 2020 14:48:01 +0800 Subject: [PATCH 06/37] Add Color::RGB() & Color::RGBA() functions --- src/kiwano/render/Color.cpp | 21 +++++++++++++++++++++ src/kiwano/render/Color.h | 30 ++++++++++++++++++++++++++++-- 2 files changed, 49 insertions(+), 2 deletions(-) diff --git a/src/kiwano/render/Color.cpp b/src/kiwano/render/Color.cpp index 023e4d3a..98173ce4 100644 --- a/src/kiwano/render/Color.cpp +++ b/src/kiwano/render/Color.cpp @@ -74,4 +74,25 @@ Color::Color(uint32_t rgb, float alpha) , a(alpha) { } + +Color Color::RGB(float r, float g, float b) +{ + return Color::RGBA(r, g, b, 1.0f); +} + +Color Color::RGB(uint32_t rgb) +{ + return Color::RGBA(rgb, 1.0f); +} + +Color Color::RGBA(float r, float g, float b, float alpha) +{ + return Color(r, g, b, alpha); +} + +Color Color::RGBA(uint32_t rgb, float alpha) +{ + return Color(rgb, alpha); +} + } // namespace kiwano diff --git a/src/kiwano/render/Color.h b/src/kiwano/render/Color.h index dec63edf..d896cd4b 100644 --- a/src/kiwano/render/Color.h +++ b/src/kiwano/render/Color.h @@ -59,7 +59,7 @@ public: /// @param r 红色值,范围 0.0 - 1.0 /// @param g 绿色值,范围 0.0 - 1.0 /// @param b 蓝色值,范围 0.0 - 1.0 - /// @param a Alpha值,范围 0.0 - 1.0 + /// @param alpha Alpha值,范围 0.0 - 1.0 Color(float r, float g, float b, float alpha); /// \~chinese @@ -70,9 +70,35 @@ public: /// \~chinese /// @brief 构造 RGBA 颜色 /// @param rgb 使用16进制整形值表示 RGB 颜色 - /// @param a Alpha值,范围 0.0 - 1.0 + /// @param alpha Alpha值,范围 0.0 - 1.0 Color(uint32_t rgb, float alpha); + /// \~chinese + /// @brief 构造 RGB 颜色 + /// @param r 红色值,范围 0.0 - 1.0 + /// @param g 绿色值,范围 0.0 - 1.0 + /// @param b 蓝色值,范围 0.0 - 1.0 + static Color RGB(float r, float g, float b); + + /// \~chinese + /// @brief 构造 RGB 颜色 + /// @param rgb 使用16进制整形值表示 RGB颜色 + static Color RGB(uint32_t rgb); + + /// \~chinese + /// @brief 构造 RGBA 颜色 + /// @param r 红色值,范围 0.0 - 1.0 + /// @param g 绿色值,范围 0.0 - 1.0 + /// @param b 蓝色值,范围 0.0 - 1.0 + /// @param alpha Alpha值,范围 0.0 - 1.0 + static Color RGBA(float r, float g, float b, float alpha); + + /// \~chinese + /// @brief 构造 RGBA 颜色 + /// @param rgb 使用16进制整形值表示 RGB颜色 + /// @param alpha Alpha值,范围 0.0 - 1.0 + static Color RGBA(uint32_t rgb, float alpha); + bool operator==(const Color& rhs) const; bool operator!=(const Color& rhs) const; From ef8db9023c186af8dab2ca0953dd682888ce0092 Mon Sep 17 00:00:00 2001 From: "liuhaibo.2020" Date: Thu, 30 Apr 2020 14:58:50 +0800 Subject: [PATCH 07/37] Color::RGB() => Color::Rgb() --- src/kiwano/render/Color.cpp | 12 ++++++------ src/kiwano/render/Color.h | 8 ++++---- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/kiwano/render/Color.cpp b/src/kiwano/render/Color.cpp index 98173ce4..7bba4f60 100644 --- a/src/kiwano/render/Color.cpp +++ b/src/kiwano/render/Color.cpp @@ -75,22 +75,22 @@ Color::Color(uint32_t rgb, float alpha) { } -Color Color::RGB(float r, float g, float b) +Color Color::Rgb(float r, float g, float b) { - return Color::RGBA(r, g, b, 1.0f); + return Color::Rgba(r, g, b, 1.0f); } -Color Color::RGB(uint32_t rgb) +Color Color::Rgb(uint32_t rgb) { - return Color::RGBA(rgb, 1.0f); + return Color::Rgba(rgb, 1.0f); } -Color Color::RGBA(float r, float g, float b, float alpha) +Color Color::Rgba(float r, float g, float b, float alpha) { return Color(r, g, b, alpha); } -Color Color::RGBA(uint32_t rgb, float alpha) +Color Color::Rgba(uint32_t rgb, float alpha) { return Color(rgb, alpha); } diff --git a/src/kiwano/render/Color.h b/src/kiwano/render/Color.h index d896cd4b..f91e561d 100644 --- a/src/kiwano/render/Color.h +++ b/src/kiwano/render/Color.h @@ -78,12 +78,12 @@ public: /// @param r 红色值,范围 0.0 - 1.0 /// @param g 绿色值,范围 0.0 - 1.0 /// @param b 蓝色值,范围 0.0 - 1.0 - static Color RGB(float r, float g, float b); + static Color Rgb(float r, float g, float b); /// \~chinese /// @brief 构造 RGB 颜色 /// @param rgb 使用16进制整形值表示 RGB颜色 - static Color RGB(uint32_t rgb); + static Color Rgb(uint32_t rgb); /// \~chinese /// @brief 构造 RGBA 颜色 @@ -91,13 +91,13 @@ public: /// @param g 绿色值,范围 0.0 - 1.0 /// @param b 蓝色值,范围 0.0 - 1.0 /// @param alpha Alpha值,范围 0.0 - 1.0 - static Color RGBA(float r, float g, float b, float alpha); + static Color Rgba(float r, float g, float b, float alpha); /// \~chinese /// @brief 构造 RGBA 颜色 /// @param rgb 使用16进制整形值表示 RGB颜色 /// @param alpha Alpha值,范围 0.0 - 1.0 - static Color RGBA(uint32_t rgb, float alpha); + static Color Rgba(uint32_t rgb, float alpha); bool operator==(const Color& rhs) const; From ae247dd676eadd0608f81f5f42cfe33fd51c5497 Mon Sep 17 00:00:00 2001 From: Nomango Date: Thu, 7 May 2020 21:47:06 +0800 Subject: [PATCH 08/37] fix bug: exiting fullscreen mode makes the window smaller --- src/kiwano/core/event/WindowEvent.cpp | 6 + src/kiwano/core/event/WindowEvent.h | 15 +- src/kiwano/platform/Window.cpp | 6 +- src/kiwano/platform/Window.h | 12 +- src/kiwano/platform/win32/WindowImpl.cpp | 200 ++++++------------ .../render/DirectX/D3D10DeviceResources.cpp | 19 +- .../render/DirectX/D3D11DeviceResources.cpp | 7 + .../render/DirectX/D3DDeviceResourcesBase.h | 2 + 8 files changed, 113 insertions(+), 154 deletions(-) diff --git a/src/kiwano/core/event/WindowEvent.cpp b/src/kiwano/core/event/WindowEvent.cpp index 37cafb2b..2ab6ab75 100644 --- a/src/kiwano/core/event/WindowEvent.cpp +++ b/src/kiwano/core/event/WindowEvent.cpp @@ -39,4 +39,10 @@ WindowClosedEvent::WindowClosedEvent() { } +WindowFullscreenEvent::WindowFullscreenEvent() + : WindowEvent(KGE_EVENT(WindowFullscreenEvent)) + , fullscreen(false) +{ +} + } // namespace kiwano diff --git a/src/kiwano/core/event/WindowEvent.h b/src/kiwano/core/event/WindowEvent.h index 26a28e0d..96e5cfb2 100644 --- a/src/kiwano/core/event/WindowEvent.h +++ b/src/kiwano/core/event/WindowEvent.h @@ -29,6 +29,7 @@ KGE_DECLARE_SMART_PTR(WindowResizedEvent); KGE_DECLARE_SMART_PTR(WindowFocusChangedEvent); KGE_DECLARE_SMART_PTR(WindowTitleChangedEvent); KGE_DECLARE_SMART_PTR(WindowClosedEvent); +KGE_DECLARE_SMART_PTR(WindowFullscreenEvent); /** * \addtogroup Events @@ -93,6 +94,16 @@ public: WindowClosedEvent(); }; +/// \~chinese +/// @brief 窗口切换全屏事件 +class KGE_API WindowFullscreenEvent : public WindowEvent +{ +public: + bool fullscreen; + + WindowFullscreenEvent(); +}; + /** @} */ template <> @@ -102,8 +113,8 @@ struct IsEventType { return evt->GetType() == KGE_EVENT(WindowMovedEvent) || evt->GetType() == KGE_EVENT(WindowResizedEvent) || evt->GetType() == KGE_EVENT(WindowFocusChangedEvent) - || evt->GetType() == KGE_EVENT(WindowTitleChangedEvent) - || evt->GetType() == KGE_EVENT(WindowClosedEvent); + || evt->GetType() == KGE_EVENT(WindowTitleChangedEvent) || evt->GetType() == KGE_EVENT(WindowClosedEvent) + || evt->GetType() == KGE_EVENT(WindowFullscreenEvent); } }; diff --git a/src/kiwano/platform/Window.cpp b/src/kiwano/platform/Window.cpp index e784c7cb..be976cb4 100644 --- a/src/kiwano/platform/Window.cpp +++ b/src/kiwano/platform/Window.cpp @@ -26,6 +26,7 @@ namespace kiwano Window::Window() : handle_(nullptr) , should_close_(false) + , is_fullscreen_(false) , width_(0) , height_(0) { @@ -88,9 +89,4 @@ void Window::PushEvent(EventPtr evt) event_queue_.push(evt); } -void Window::Destroy() -{ - should_close_ = true; -} - } // namespace kiwano diff --git a/src/kiwano/platform/Window.h b/src/kiwano/platform/Window.h index c4b24208..ac1aa963 100644 --- a/src/kiwano/platform/Window.h +++ b/src/kiwano/platform/Window.h @@ -132,8 +132,6 @@ public: * \~chinese * @brief 设置全屏模式 * @param fullscreen 是否全屏 - * @param width 窗口宽度 - * @param height 窗口高度 */ virtual void SetFullscreen(bool fullscreen) = 0; @@ -147,8 +145,7 @@ public: /** * \~chinese * @brief 轮询窗口事件 - * @return 返回事件队列中的第一个事件并将其从队列中移除\n - * 若事件队列为空则返回空指针 + * @return 返回事件队列中的第一个事件并将其从队列中移除, 若队列为空则返回空指针 */ EventPtr PollEvent(); @@ -177,12 +174,6 @@ public: */ void SetShouldClose(bool should); - /** - * \~chinese - * @brief 销毁窗口 - */ - virtual void Destroy(); - protected: Window(); @@ -190,6 +181,7 @@ protected: protected: bool should_close_; + bool is_fullscreen_; uint32_t width_; uint32_t height_; WindowHandle handle_; diff --git a/src/kiwano/platform/win32/WindowImpl.cpp b/src/kiwano/platform/win32/WindowImpl.cpp index 9f7c8e05..6a238585 100644 --- a/src/kiwano/platform/win32/WindowImpl.cpp +++ b/src/kiwano/platform/win32/WindowImpl.cpp @@ -59,8 +59,6 @@ public: void SetCursor(CursorType cursor) override; - void Destroy() override; - void PumpEvents() override; DWORD GetStyle() const; @@ -75,7 +73,6 @@ public: private: bool resizable_; - bool is_fullscreen_; CursorType mouse_cursor_; String device_name_; @@ -136,36 +133,10 @@ void AdjustWindow(uint32_t width, uint32_t height, DWORD style, uint32_t* win_wi *win_height = screenh; } -void ChangeFullScreenResolution(uint32_t width, uint32_t height, const CHAR* device_name) -{ - DEVMODEA mode; - - memset(&mode, 0, sizeof(mode)); - mode.dmSize = sizeof(mode); - mode.dmPelsWidth = width; - mode.dmPelsHeight = height; - mode.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT; - - LONG ret = ::ChangeDisplaySettingsExA(device_name, &mode, NULL, CDS_FULLSCREEN, NULL); - if (ret != DISP_CHANGE_SUCCESSFUL) - { - KGE_ERROR("ChangeDisplaySettings failed with error code %d", ret); - } -} - -void RestoreResolution(const CHAR* device_name) -{ - LONG ret = ::ChangeDisplaySettingsExA(device_name, NULL, NULL, 0, NULL); - if (ret != DISP_CHANGE_SUCCESSFUL) - { - KGE_ERROR("ChangeDisplaySettings failed with error code %d", ret); - } -} } // namespace WindowWin32Impl::WindowWin32Impl() - : is_fullscreen_(false) - , resizable_(false) + : resizable_(false) , mouse_cursor_(CursorType::Arrow) , key_map_{} { @@ -213,7 +184,11 @@ WindowWin32Impl::WindowWin32Impl() WindowWin32Impl::~WindowWin32Impl() { - this->Destroy(); + if (handle_) + { + ::DestroyWindow(handle_); + handle_ = nullptr; + } } void WindowWin32Impl::Init(const String& title, uint32_t width, uint32_t height, uint32_t icon, bool resizable, @@ -255,10 +230,7 @@ void WindowWin32Impl::Init(const String& title, uint32_t width, uint32_t height, int left = -1, top = -1; - resizable_ = resizable; - is_fullscreen_ = fullscreen; - - if (is_fullscreen_) + if (fullscreen) { top = monitor_info_ex.rcMonitor.top; left = monitor_info_ex.rcMonitor.left; @@ -283,7 +255,7 @@ void WindowWin32Impl::Init(const String& title, uint32_t width, uint32_t height, height = win_height; } - handle_ = ::CreateWindowExA(is_fullscreen_ ? WS_EX_TOPMOST : 0, "KiwanoAppWnd", title.c_str(), GetStyle(), + handle_ = ::CreateWindowExA(fullscreen ? WS_EX_TOPMOST : 0, "KiwanoAppWnd", title.c_str(), GetStyle(), left, top, width, height, nullptr, nullptr, hinst, nullptr); if (handle_ == nullptr) @@ -292,8 +264,9 @@ void WindowWin32Impl::Init(const String& title, uint32_t width, uint32_t height, KGE_THROW_SYSTEM_ERROR(HRESULT_FROM_WIN32(GetLastError()), "Create window failed"); } - width_ = width; - height_ = height; + width_ = width; + height_ = height; + resizable_ = resizable; // disable imm ::ImmAssociateContext(handle_, nullptr); @@ -306,7 +279,7 @@ void WindowWin32Impl::Init(const String& title, uint32_t width, uint32_t height, if (is_fullscreen_) { - ChangeFullScreenResolution(width, height, device_name_.c_str()); + SetFullscreen(true); } } @@ -322,58 +295,47 @@ void WindowWin32Impl::PumpEvents() void WindowWin32Impl::SetTitle(const String& title) { - if (handle_) - { - ::SetWindowTextA(handle_, title.c_str()); - } + KGE_ASSERT(handle_); + ::SetWindowTextA(handle_, title.c_str()); } void WindowWin32Impl::SetIcon(uint32_t icon_resource) { - if (handle_) - { - HINSTANCE hinstance = ::GetModuleHandle(nullptr); - HICON icon = (HICON)::LoadImage(hinstance, MAKEINTRESOURCE(icon_resource), IMAGE_ICON, 0, 0, - LR_DEFAULTCOLOR | LR_CREATEDIBSECTION | LR_DEFAULTSIZE); + KGE_ASSERT(handle_); - ::SendMessage(handle_, WM_SETICON, ICON_BIG, (LPARAM)icon); - ::SendMessage(handle_, WM_SETICON, ICON_SMALL, (LPARAM)icon); - } + HINSTANCE hinstance = ::GetModuleHandle(nullptr); + HICON icon = (HICON)::LoadImage(hinstance, MAKEINTRESOURCE(icon_resource), IMAGE_ICON, 0, 0, + LR_DEFAULTCOLOR | LR_CREATEDIBSECTION | LR_DEFAULTSIZE); + + ::SendMessage(handle_, WM_SETICON, ICON_BIG, (LPARAM)icon); + ::SendMessage(handle_, WM_SETICON, ICON_SMALL, (LPARAM)icon); } void WindowWin32Impl::Resize(uint32_t width, uint32_t height) { - if (handle_) + KGE_ASSERT(handle_); + if (!is_fullscreen_) { - if (!is_fullscreen_) - { - MONITORINFOEXA info = GetMoniterInfoEx(handle_); + MONITORINFOEXA info = GetMoniterInfoEx(handle_); - uint32_t screenw = uint32_t(info.rcWork.right - info.rcWork.left); - uint32_t screenh = uint32_t(info.rcWork.bottom - info.rcWork.top); + uint32_t screenw = uint32_t(info.rcWork.right - info.rcWork.left); + uint32_t screenh = uint32_t(info.rcWork.bottom - info.rcWork.top); - RECT rc = { 0, 0, LONG(width), LONG(height) }; - ::AdjustWindowRect(&rc, GetStyle(), false); + RECT rc = { 0, 0, LONG(width), LONG(height) }; + ::AdjustWindowRect(&rc, GetStyle(), false); - width = rc.right - rc.left; - height = rc.bottom - rc.top; + width = rc.right - rc.left; + height = rc.bottom - rc.top; - int left = screenw > width ? ((screenw - width) / 2) : 0; - int top = screenh > height ? ((screenh - height) / 2) : 0; + int left = screenw > width ? ((screenw - width) / 2) : 0; + int top = screenh > height ? ((screenh - height) / 2) : 0; - ::SetWindowPos(handle_, 0, left, top, width, height, SWP_NOZORDER | SWP_NOACTIVATE); - } - else - { - // move window to (0, 0) before display switch - ::SetWindowPos(handle_, HWND_TOPMOST, 0, 0, width, height, SWP_NOACTIVATE); - - ChangeFullScreenResolution(width, height, device_name_.c_str()); - - MONITORINFOEXA info = GetMoniterInfoEx(handle_); - ::SetWindowPos(handle_, HWND_TOPMOST, info.rcMonitor.top, info.rcMonitor.left, width, height, - SWP_NOACTIVATE); - } + ::SetWindowPos(handle_, 0, left, top, width, height, SWP_NOZORDER | SWP_NOACTIVATE); + } + else + { + MONITORINFOEXA info = GetMoniterInfoEx(handle_); + ::SetWindowPos(handle_, HWND_TOPMOST, info.rcMonitor.top, info.rcMonitor.left, width, height, SWP_NOACTIVATE); } } @@ -383,39 +345,32 @@ void WindowWin32Impl::SetFullscreen(bool fullscreen) { is_fullscreen_ = fullscreen; - uint32_t width = GetWidth(); - uint32_t height = GetHeight(); - if (is_fullscreen_) { - // move window to (0, 0) before display switch - ::SetWindowPos(handle_, HWND_TOPMOST, 0, 0, width, height, SWP_NOACTIVATE); - - ChangeFullScreenResolution(width, height, device_name_.c_str()); - - MONITORINFOEXA info = GetMoniterInfoEx(handle_); - + // Reset window style ::SetWindowLongPtrA(handle_, GWL_STYLE, GetStyle()); - ::SetWindowPos(handle_, HWND_TOPMOST, info.rcMonitor.top, info.rcMonitor.left, width, height, + + // Top the window + MONITORINFOEXA info = GetMoniterInfoEx(handle_); + ::SetWindowPos(handle_, HWND_TOPMOST, info.rcMonitor.top, info.rcMonitor.left, width_, height_, SWP_NOACTIVATE); } else { - RestoreResolution(device_name_.c_str()); - - MONITORINFOEXA info = GetMoniterInfoEx(handle_); - - uint32_t screenw = uint32_t(info.rcWork.right - info.rcWork.left); - uint32_t screenh = uint32_t(info.rcWork.bottom - info.rcWork.top); - - int left = screenw > width ? ((screenw - width) / 2) : 0; - int top = screenh > height ? ((screenh - height) / 2) : 0; - + // Reset window style ::SetWindowLongPtrA(handle_, GWL_STYLE, GetStyle()); - ::SetWindowPos(handle_, HWND_NOTOPMOST, left, top, width, height, SWP_DRAWFRAME | SWP_FRAMECHANGED); + + // Unpin the window + ::SetWindowPos(handle_, HWND_NOTOPMOST, 0, 0, 0, 0, + SWP_DRAWFRAME | SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE); } ::ShowWindow(handle_, SW_SHOWNORMAL); + + // Send event + WindowFullscreenEventPtr evt = new WindowFullscreenEvent; + evt->fullscreen = is_fullscreen_; + PushEvent(evt); } } @@ -424,18 +379,26 @@ void WindowWin32Impl::SetCursor(CursorType cursor) mouse_cursor_ = cursor; } -void WindowWin32Impl::Destroy() +void WindowWin32Impl::SetActive(bool actived) { + if (!handle_) + return; + if (is_fullscreen_) - RestoreResolution(device_name_.c_str()); - - if (handle_) { - ::DestroyWindow(handle_); - handle_ = nullptr; + // Hide window when it is not active + if (actived) + { + MONITORINFOEXA info = GetMoniterInfoEx(handle_); + ::SetWindowPos(handle_, HWND_TOPMOST, info.rcMonitor.top, info.rcMonitor.left, width_, height_, + SWP_NOACTIVATE); + } + else + { + ::SetWindowPos(handle_, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); + ::ShowWindow(handle_, SW_MINIMIZE); + } } - - Window::Destroy(); } DWORD WindowWin32Impl::GetStyle() const @@ -476,31 +439,6 @@ void WindowWin32Impl::UpdateCursor() ::SetCursor(::LoadCursor(nullptr, win32_cursor)); } -void WindowWin32Impl::SetActive(bool actived) -{ - if (!handle_) - return; - - if (is_fullscreen_) - { - if (actived) - { - ChangeFullScreenResolution(GetWidth(), GetHeight(), device_name_.c_str()); - - MONITORINFOEXA info = GetMoniterInfoEx(handle_); - ::SetWindowPos(handle_, HWND_TOPMOST, info.rcMonitor.top, info.rcMonitor.left, GetWidth(), GetHeight(), - SWP_NOACTIVATE); - } - else - { - RestoreResolution(device_name_.c_str()); - - ::SetWindowPos(handle_, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); - ::ShowWindow(handle_, SW_MINIMIZE); - } - } -} - LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARAM lparam) { switch (msg) diff --git a/src/kiwano/render/DirectX/D3D10DeviceResources.cpp b/src/kiwano/render/DirectX/D3D10DeviceResources.cpp index 70c4b74b..662cbb90 100644 --- a/src/kiwano/render/DirectX/D3D10DeviceResources.cpp +++ b/src/kiwano/render/DirectX/D3D10DeviceResources.cpp @@ -65,17 +65,19 @@ inline bool SdkLayersAvailable() struct D3D10DeviceResources : public ID3D10DeviceResources { public: - HRESULT Present(bool vsync); + HRESULT Present(bool vsync) override; - void ClearRenderTarget(Color& clear_color); + void ClearRenderTarget(Color& clear_color) override; - HRESULT HandleDeviceLost(); + HRESULT HandleDeviceLost() override; - HRESULT SetLogicalSize(Size logical_size); + HRESULT SetLogicalSize(Size logical_size) override; - HRESULT SetDpi(float dpi); + HRESULT SetDpi(float dpi) override; - void DiscardResources(); + HRESULT SetFullscreenState(bool fullscreen) override; + + void DiscardResources() override; public: unsigned long STDMETHODCALLTYPE AddRef(); @@ -396,6 +398,11 @@ HRESULT D3D10DeviceResources::SetDpi(float dpi) return S_OK; } +HRESULT D3D10DeviceResources::SetFullscreenState(bool fullscreen) +{ + return dxgi_swap_chain_->SetFullscreenState(fullscreen ? TRUE : FALSE, nullptr); +} + STDMETHODIMP_(unsigned long) D3D10DeviceResources::AddRef() { return InterlockedIncrement(&ref_count_); diff --git a/src/kiwano/render/DirectX/D3D11DeviceResources.cpp b/src/kiwano/render/DirectX/D3D11DeviceResources.cpp index a78790d3..fe0b7b12 100644 --- a/src/kiwano/render/DirectX/D3D11DeviceResources.cpp +++ b/src/kiwano/render/DirectX/D3D11DeviceResources.cpp @@ -64,6 +64,8 @@ public: HRESULT SetDpi(float dpi) override; + HRESULT SetFullscreenState(bool fullscreen) override; + void DiscardResources() override; public: @@ -416,6 +418,11 @@ HRESULT D3D11DeviceResources::SetDpi(float dpi) return S_OK; } +HRESULT D3D11DeviceResources::SetFullscreenState(bool fullscreen) +{ + return dxgi_swap_chain_->SetFullscreenState(fullscreen ? TRUE : FALSE, nullptr); +} + STDMETHODIMP_(unsigned long) D3D11DeviceResources::AddRef() { return InterlockedIncrement(&ref_count_); diff --git a/src/kiwano/render/DirectX/D3DDeviceResourcesBase.h b/src/kiwano/render/DirectX/D3DDeviceResourcesBase.h index 5cdde8b1..421376a0 100644 --- a/src/kiwano/render/DirectX/D3DDeviceResourcesBase.h +++ b/src/kiwano/render/DirectX/D3DDeviceResourcesBase.h @@ -37,6 +37,8 @@ public: virtual HRESULT SetDpi(float dpi) = 0; + virtual HRESULT SetFullscreenState(bool fullscreen) = 0; + virtual void DiscardResources() = 0; }; From f8cdbe43358237e81ae15d83b8a4bdf5ec7f539c Mon Sep 17 00:00:00 2001 From: Nomango Date: Fri, 8 May 2020 00:57:28 +0800 Subject: [PATCH 09/37] fix bug: incorrect window size in fullscreen mode --- src/kiwano/platform/Window.h | 2 +- src/kiwano/platform/win32/WindowImpl.cpp | 36 ++++++++++++++-------- src/kiwano/render/DirectX/RendererImpl.cpp | 6 ++++ src/kiwano/render/DirectX/RendererImpl.h | 2 ++ src/kiwano/render/Renderer.cpp | 5 +++ src/kiwano/render/Renderer.h | 2 ++ 6 files changed, 39 insertions(+), 14 deletions(-) diff --git a/src/kiwano/platform/Window.h b/src/kiwano/platform/Window.h index ac1aa963..bd8a973f 100644 --- a/src/kiwano/platform/Window.h +++ b/src/kiwano/platform/Window.h @@ -133,7 +133,7 @@ public: * @brief 设置全屏模式 * @param fullscreen 是否全屏 */ - virtual void SetFullscreen(bool fullscreen) = 0; + virtual void SetFullscreenState(bool fullscreen) = 0; /** * \~chinese diff --git a/src/kiwano/platform/win32/WindowImpl.cpp b/src/kiwano/platform/win32/WindowImpl.cpp index 6a238585..818b6698 100644 --- a/src/kiwano/platform/win32/WindowImpl.cpp +++ b/src/kiwano/platform/win32/WindowImpl.cpp @@ -55,7 +55,7 @@ public: void Resize(uint32_t width, uint32_t height) override; - void SetFullscreen(bool fullscreen) override; + void SetFullscreenState(bool fullscreen) override; void SetCursor(CursorType cursor) override; @@ -279,7 +279,7 @@ void WindowWin32Impl::Init(const String& title, uint32_t width, uint32_t height, if (is_fullscreen_) { - SetFullscreen(true); + SetFullscreenState(true); } } @@ -316,19 +316,17 @@ void WindowWin32Impl::Resize(uint32_t width, uint32_t height) KGE_ASSERT(handle_); if (!is_fullscreen_) { - MONITORINFOEXA info = GetMoniterInfoEx(handle_); - - uint32_t screenw = uint32_t(info.rcWork.right - info.rcWork.left); - uint32_t screenh = uint32_t(info.rcWork.bottom - info.rcWork.top); - RECT rc = { 0, 0, LONG(width), LONG(height) }; ::AdjustWindowRect(&rc, GetStyle(), false); width = rc.right - rc.left; height = rc.bottom - rc.top; - int left = screenw > width ? ((screenw - width) / 2) : 0; - int top = screenh > height ? ((screenh - height) / 2) : 0; + MONITORINFOEXA info = GetMoniterInfoEx(handle_); + uint32_t screenw = uint32_t(info.rcWork.right - info.rcWork.left); + uint32_t screenh = uint32_t(info.rcWork.bottom - info.rcWork.top); + int left = screenw > width ? ((screenw - width) / 2) : 0; + int top = screenh > height ? ((screenh - height) / 2) : 0; ::SetWindowPos(handle_, 0, left, top, width, height, SWP_NOZORDER | SWP_NOACTIVATE); } @@ -339,12 +337,19 @@ void WindowWin32Impl::Resize(uint32_t width, uint32_t height) } } -void WindowWin32Impl::SetFullscreen(bool fullscreen) +void WindowWin32Impl::SetFullscreenState(bool fullscreen) { if (is_fullscreen_ != fullscreen) { is_fullscreen_ = fullscreen; + // Adjust the rect of client area + RECT rc = { 0, 0, LONG(width_), LONG(height_) }; + ::AdjustWindowRect(&rc, GetStyle(), false); + + uint32_t width = uint32_t(rc.right - rc.left); + uint32_t height = uint32_t(rc.bottom - rc.top); + if (is_fullscreen_) { // Reset window style @@ -352,17 +357,22 @@ void WindowWin32Impl::SetFullscreen(bool fullscreen) // Top the window MONITORINFOEXA info = GetMoniterInfoEx(handle_); - ::SetWindowPos(handle_, HWND_TOPMOST, info.rcMonitor.top, info.rcMonitor.left, width_, height_, + ::SetWindowPos(handle_, HWND_TOPMOST, info.rcMonitor.top, info.rcMonitor.left, width, height, SWP_NOACTIVATE); } else { + MONITORINFOEXA info = GetMoniterInfoEx(handle_); + uint32_t screenw = uint32_t(info.rcWork.right - info.rcWork.left); + uint32_t screenh = uint32_t(info.rcWork.bottom - info.rcWork.top); + int left = screenw > width ? ((screenw - width) / 2) : 0; + int top = screenh > height ? ((screenh - height) / 2) : 0; + // Reset window style ::SetWindowLongPtrA(handle_, GWL_STYLE, GetStyle()); // Unpin the window - ::SetWindowPos(handle_, HWND_NOTOPMOST, 0, 0, 0, 0, - SWP_DRAWFRAME | SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE); + ::SetWindowPos(handle_, HWND_NOTOPMOST, left, top, width, height, SWP_DRAWFRAME | SWP_FRAMECHANGED); } ::ShowWindow(handle_, SW_SHOWNORMAL); diff --git a/src/kiwano/render/DirectX/RendererImpl.cpp b/src/kiwano/render/DirectX/RendererImpl.cpp index fe48773c..f0bced1d 100644 --- a/src/kiwano/render/DirectX/RendererImpl.cpp +++ b/src/kiwano/render/DirectX/RendererImpl.cpp @@ -120,6 +120,12 @@ void RendererImpl::MakeContextForWindow(WindowPtr window) KGE_THROW_IF_FAILED(hr, "Create render resources failed"); } +void RendererImpl::SetFullscreenState(bool fullscreen) +{ + KGE_ASSERT(d3d_res_); + d3d_res_->SetFullscreenState(fullscreen); +} + void RendererImpl::Destroy() { KGE_SYS_LOG("Destroying device resources"); diff --git a/src/kiwano/render/DirectX/RendererImpl.h b/src/kiwano/render/DirectX/RendererImpl.h index f2a1e13a..e90d35ac 100644 --- a/src/kiwano/render/DirectX/RendererImpl.h +++ b/src/kiwano/render/DirectX/RendererImpl.h @@ -104,6 +104,8 @@ protected: void MakeContextForWindow(WindowPtr window) override; + void SetFullscreenState(bool fullscreen) override; + void Destroy() override; private: diff --git a/src/kiwano/render/Renderer.cpp b/src/kiwano/render/Renderer.cpp index f25086ef..4c56e029 100644 --- a/src/kiwano/render/Renderer.cpp +++ b/src/kiwano/render/Renderer.cpp @@ -49,6 +49,11 @@ void Renderer::HandleEvent(Event* evt) auto window_evt = dynamic_cast(evt); Resize(window_evt->width, window_evt->height); } + else if (evt->IsType()) + { + auto window_evt = dynamic_cast(evt); + SetFullscreenState(window_evt->fullscreen); + } } void Renderer::BeginDraw() diff --git a/src/kiwano/render/Renderer.h b/src/kiwano/render/Renderer.h index ac03ca20..07bf9ff1 100644 --- a/src/kiwano/render/Renderer.h +++ b/src/kiwano/render/Renderer.h @@ -246,6 +246,8 @@ protected: virtual void MakeContextForWindow(WindowPtr window) = 0; + virtual void SetFullscreenState(bool fullscreen) = 0; + virtual void Destroy() = 0; protected: From 646db73f7356b3cd84701f7616fa585c9a4c1659 Mon Sep 17 00:00:00 2001 From: "liuhaibo.2020" Date: Fri, 15 May 2020 16:29:02 +0800 Subject: [PATCH 10/37] add CMakeLists.txt files --- .gitignore | 11 +- CMakeLists.txt | 26 ++++ src/3rd-party/Box2D/CMakeLists.txt | 98 +++++++++++++++ src/3rd-party/Box2D/Common/b2Math.h | 2 +- src/3rd-party/curl/CMakeLists.txt | 18 +++ src/3rd-party/imgui/CMakeLists.txt | 15 +++ src/3rd-party/nlohmann/CMakeLists.txt | 9 ++ src/3rd-party/pugixml/CMakeLists.txt | 10 ++ src/kiwano-audio/CMakeLists.txt | 16 +++ src/kiwano-imgui/CMakeLists.txt | 15 +++ src/kiwano-network/CMakeLists.txt | 11 ++ src/kiwano-physics/CMakeLists.txt | 25 ++++ src/kiwano/CMakeLists.txt | 175 ++++++++++++++++++++++++++ 13 files changed, 429 insertions(+), 2 deletions(-) create mode 100644 CMakeLists.txt create mode 100644 src/3rd-party/Box2D/CMakeLists.txt create mode 100644 src/3rd-party/curl/CMakeLists.txt create mode 100644 src/3rd-party/imgui/CMakeLists.txt create mode 100644 src/3rd-party/nlohmann/CMakeLists.txt create mode 100644 src/3rd-party/pugixml/CMakeLists.txt create mode 100644 src/kiwano-audio/CMakeLists.txt create mode 100644 src/kiwano-imgui/CMakeLists.txt create mode 100644 src/kiwano-network/CMakeLists.txt create mode 100644 src/kiwano-physics/CMakeLists.txt create mode 100644 src/kiwano/CMakeLists.txt diff --git a/.gitignore b/.gitignore index d2193be3..7c3945ca 100644 --- a/.gitignore +++ b/.gitignore @@ -6,8 +6,13 @@ x64/ Debug/ Release/ +# CMake folders +/cmake-build-release/ +/cmake-build-debug/ + # Application folders .vs +.idea # vs2010 ipch/ @@ -27,4 +32,8 @@ packages/ # Resources bin *.aps -docs/ \ No newline at end of file +# Mac cache files +.DS_Store + +# Documents +docs/ diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 00000000..cd27226e --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.16) +project(Kiwano C CXX) + +set(CMAKE_CXX_STANDARD 17) + +if (WIN32) + message(STATUS "Building on Windows platform.") +elseif (APPLE) + message(STATUS "Building on MacOS platform.") + add_compile_definitions(TARGET_OS_MAC) +elseif (UNIX) + message(STATUS "Building on UNIX-like OS platform.") +endif () + +include_directories(src/3rd-party) +include_directories(src) + +add_subdirectory(src/kiwano) +add_subdirectory(src/kiwano-audio) +add_subdirectory(src/kiwano-imgui) +add_subdirectory(src/kiwano-network) +add_subdirectory(src/kiwano-physics) +add_subdirectory(src/3rd-party/Box2D) +add_subdirectory(src/3rd-party/curl) +add_subdirectory(src/3rd-party/nlohmann) +add_subdirectory(src/3rd-party/pugixml) diff --git a/src/3rd-party/Box2D/CMakeLists.txt b/src/3rd-party/Box2D/CMakeLists.txt new file mode 100644 index 00000000..17f90b54 --- /dev/null +++ b/src/3rd-party/Box2D/CMakeLists.txt @@ -0,0 +1,98 @@ +include_directories(..) + +set(SOURCE_FILES + Collision/Shapes/b2ChainShape.cpp + Collision/Shapes/b2ChainShape.h + Collision/Shapes/b2CircleShape.cpp + Collision/Shapes/b2CircleShape.h + Collision/Shapes/b2EdgeShape.cpp + Collision/Shapes/b2EdgeShape.h + Collision/Shapes/b2PolygonShape.cpp + Collision/Shapes/b2PolygonShape.h + Collision/Shapes/b2Shape.h + Collision/b2BroadPhase.cpp + Collision/b2BroadPhase.h + Collision/b2CollideCircle.cpp + Collision/b2CollideEdge.cpp + Collision/b2CollidePolygon.cpp + Collision/b2Collision.cpp + Collision/b2Collision.h + Collision/b2Distance.cpp + Collision/b2Distance.h + Collision/b2DynamicTree.cpp + Collision/b2DynamicTree.h + Collision/b2TimeOfImpact.cpp + Collision/b2TimeOfImpact.h + Common/b2BlockAllocator.cpp + Common/b2BlockAllocator.h + Common/b2Draw.cpp + Common/b2Draw.h + Common/b2GrowableStack.h + Common/b2Math.cpp + Common/b2Math.h + Common/b2Settings.cpp + Common/b2Settings.h + Common/b2StackAllocator.cpp + Common/b2StackAllocator.h + Common/b2Timer.cpp + Common/b2Timer.h + Dynamics/Contacts/b2ChainAndCircleContact.cpp + Dynamics/Contacts/b2ChainAndCircleContact.h + Dynamics/Contacts/b2ChainAndPolygonContact.cpp + Dynamics/Contacts/b2ChainAndPolygonContact.h + Dynamics/Contacts/b2CircleContact.cpp + Dynamics/Contacts/b2CircleContact.h + Dynamics/Contacts/b2Contact.cpp + Dynamics/Contacts/b2Contact.h + Dynamics/Contacts/b2ContactSolver.cpp + Dynamics/Contacts/b2ContactSolver.h + Dynamics/Contacts/b2EdgeAndCircleContact.cpp + Dynamics/Contacts/b2EdgeAndCircleContact.h + Dynamics/Contacts/b2EdgeAndPolygonContact.cpp + Dynamics/Contacts/b2EdgeAndPolygonContact.h + Dynamics/Contacts/b2PolygonAndCircleContact.cpp + Dynamics/Contacts/b2PolygonAndCircleContact.h + Dynamics/Contacts/b2PolygonContact.cpp + Dynamics/Contacts/b2PolygonContact.h + Dynamics/Joints/b2DistanceJoint.cpp + Dynamics/Joints/b2DistanceJoint.h + Dynamics/Joints/b2FrictionJoint.cpp + Dynamics/Joints/b2FrictionJoint.h + Dynamics/Joints/b2GearJoint.cpp + Dynamics/Joints/b2GearJoint.h + Dynamics/Joints/b2Joint.cpp + Dynamics/Joints/b2Joint.h + Dynamics/Joints/b2MotorJoint.cpp + Dynamics/Joints/b2MotorJoint.h + Dynamics/Joints/b2MouseJoint.cpp + Dynamics/Joints/b2MouseJoint.h + Dynamics/Joints/b2PrismaticJoint.cpp + Dynamics/Joints/b2PrismaticJoint.h + Dynamics/Joints/b2PulleyJoint.cpp + Dynamics/Joints/b2PulleyJoint.h + Dynamics/Joints/b2RevoluteJoint.cpp + Dynamics/Joints/b2RevoluteJoint.h + Dynamics/Joints/b2RopeJoint.cpp + Dynamics/Joints/b2RopeJoint.h + Dynamics/Joints/b2WeldJoint.cpp + Dynamics/Joints/b2WeldJoint.h + Dynamics/Joints/b2WheelJoint.cpp + Dynamics/Joints/b2WheelJoint.h + Dynamics/b2Body.cpp + Dynamics/b2Body.h + Dynamics/b2ContactManager.cpp + Dynamics/b2ContactManager.h + Dynamics/b2Fixture.cpp + Dynamics/b2Fixture.h + Dynamics/b2Island.cpp + Dynamics/b2Island.h + Dynamics/b2TimeStep.h + Dynamics/b2World.cpp + Dynamics/b2World.h + Dynamics/b2WorldCallbacks.cpp + Dynamics/b2WorldCallbacks.h + Rope/b2Rope.cpp + Rope/b2Rope.h + Box2D.h) + +add_library(libbox2d ${SOURCE_FILES}) diff --git a/src/3rd-party/Box2D/Common/b2Math.h b/src/3rd-party/Box2D/Common/b2Math.h index 236c1a4a..ee6d56d7 100644 --- a/src/3rd-party/Box2D/Common/b2Math.h +++ b/src/3rd-party/Box2D/Common/b2Math.h @@ -20,7 +20,7 @@ #define B2_MATH_H #include "b2Settings.h" -#include +#include /// This function is used to ensure that a floating point number is not a NaN or infinity. inline bool b2IsValid(float32 x) diff --git a/src/3rd-party/curl/CMakeLists.txt b/src/3rd-party/curl/CMakeLists.txt new file mode 100644 index 00000000..523ca79c --- /dev/null +++ b/src/3rd-party/curl/CMakeLists.txt @@ -0,0 +1,18 @@ +include_directories(..) + +set(SOURCE_FILES + curl.h + curlbuild.h + curlrules.h + curlver.h + easy.h + mprintf.h + multi.h + stdcheaders.h + typecheck-gcc.h) + +add_library(libcurl ${SOURCE_FILES}) + +target_link_libraries(libcurl ./libs/libcurl.lib) + +set_target_properties(libcurl PROPERTIES LINKER_LANGUAGE CXX) diff --git a/src/3rd-party/imgui/CMakeLists.txt b/src/3rd-party/imgui/CMakeLists.txt new file mode 100644 index 00000000..50957205 --- /dev/null +++ b/src/3rd-party/imgui/CMakeLists.txt @@ -0,0 +1,15 @@ +include_directories(..) + +set(SOURCE_FILES + imconfig.h + imgui.cpp + imgui.h + imgui_demo.cpp + imgui_draw.cpp + imgui_internal.h + imgui_widgets.cpp + imstb_rectpack.h + imstb_textedit.h + imstb_truetype.h) + +add_library(libimgui ${SOURCE_FILES}) diff --git a/src/3rd-party/nlohmann/CMakeLists.txt b/src/3rd-party/nlohmann/CMakeLists.txt new file mode 100644 index 00000000..5d706720 --- /dev/null +++ b/src/3rd-party/nlohmann/CMakeLists.txt @@ -0,0 +1,9 @@ +include_directories(..) + +set(SOURCE_FILES + json.hpp) + +add_library(libnlohmann ${SOURCE_FILES}) + +set_target_properties(libnlohmann PROPERTIES LINKER_LANGUAGE CXX) + diff --git a/src/3rd-party/pugixml/CMakeLists.txt b/src/3rd-party/pugixml/CMakeLists.txt new file mode 100644 index 00000000..d6a7efaf --- /dev/null +++ b/src/3rd-party/pugixml/CMakeLists.txt @@ -0,0 +1,10 @@ +include_directories(..) + +set(SOURCE_FILES + pugiconfig.hpp + pugixml-impl.hpp + pugixml.hpp) + +add_library(libpugixml ${SOURCE_FILES}) + +set_target_properties(libpugixml PROPERTIES LINKER_LANGUAGE CXX) diff --git a/src/kiwano-audio/CMakeLists.txt b/src/kiwano-audio/CMakeLists.txt new file mode 100644 index 00000000..eea58eeb --- /dev/null +++ b/src/kiwano-audio/CMakeLists.txt @@ -0,0 +1,16 @@ +include_directories(..) + +set(SOURCE_FILES + AudioModule.cpp + AudioModule.h + kiwano-audio.h + libraries.cpp + libraries.h + Sound.cpp + Sound.h + SoundPlayer.cpp + SoundPlayer.h + Transcoder.cpp + Transcoder.h) + +add_library(libkiwanoaudio ${SOURCE_FILES}) diff --git a/src/kiwano-imgui/CMakeLists.txt b/src/kiwano-imgui/CMakeLists.txt new file mode 100644 index 00000000..6296cac1 --- /dev/null +++ b/src/kiwano-imgui/CMakeLists.txt @@ -0,0 +1,15 @@ +include_directories(..) + +set(SOURCE_FILES + imgui_impl/imgui_impl.h + imgui_impl/imgui_impl_dx10.cpp + imgui_impl/imgui_impl_dx10.h + imgui_impl/imgui_impl_dx11.cpp + imgui_impl/imgui_impl_dx11.h + ImGuiLayer.cpp + ImGuiLayer.h + ImGuiModule.cpp + ImGuiModule.h + kiwano-imgui.h) + +add_library(libkiwanoimgui ${SOURCE_FILES}) diff --git a/src/kiwano-network/CMakeLists.txt b/src/kiwano-network/CMakeLists.txt new file mode 100644 index 00000000..f804e7ff --- /dev/null +++ b/src/kiwano-network/CMakeLists.txt @@ -0,0 +1,11 @@ +include_directories(..) + +set(SOURCE_FILES + HttpModule.cpp + HttpModule.h + HttpRequest.cpp + HttpRequest.h + HttpResponse.hpp + kiwano-network.h) + +add_library(libkiwanonetwork ${SOURCE_FILES}) diff --git a/src/kiwano-physics/CMakeLists.txt b/src/kiwano-physics/CMakeLists.txt new file mode 100644 index 00000000..7dabf36d --- /dev/null +++ b/src/kiwano-physics/CMakeLists.txt @@ -0,0 +1,25 @@ +include_directories(..) +include_directories(../3rd-party) + +set(SOURCE_FILES + Contact.cpp + Contact.h + ContactEdge.cpp + ContactEdge.h + ContactEvent.cpp + ContactEvent.h + Fixture.cpp + Fixture.h + Global.cpp + Global.h + Joint.cpp + Joint.h + kiwano-physics.h + PhysicBody.cpp + PhysicBody.h + PhysicWorld.cpp + PhysicWorld.h) + +add_library(libkiwanophysics ${SOURCE_FILES}) + +target_link_libraries(libkiwanophysics libbox2d) diff --git a/src/kiwano/CMakeLists.txt b/src/kiwano/CMakeLists.txt new file mode 100644 index 00000000..cbb8d953 --- /dev/null +++ b/src/kiwano/CMakeLists.txt @@ -0,0 +1,175 @@ +include_directories(..) + +set(SOURCE_FILES + 2d/action/Action.cpp + 2d/action/Action.h + 2d/action/ActionDelay.cpp + 2d/action/ActionDelay.h + 2d/action/ActionGroup.cpp + 2d/action/ActionGroup.h + 2d/action/ActionHelper.h + 2d/action/ActionManager.cpp + 2d/action/ActionManager.h + 2d/action/ActionTween.cpp + 2d/action/ActionTween.h + 2d/action/ActionWalk.cpp + 2d/action/ActionWalk.h + 2d/action/Animation.cpp + 2d/action/Animation.h + 2d/Actor.cpp + 2d/Actor.h + 2d/Button.cpp + 2d/Button.h + 2d/Canvas.cpp + 2d/Canvas.h + 2d/Component.cpp + 2d/Component.h + 2d/DebugActor.cpp + 2d/DebugActor.h + 2d/GifSprite.cpp + 2d/GifSprite.h + 2d/LayerActor.cpp + 2d/LayerActor.h + 2d/ShapeActor.cpp + 2d/ShapeActor.h + 2d/Sprite.cpp + 2d/Sprite.h + 2d/Stage.cpp + 2d/Stage.h + 2d/TextActor.cpp + 2d/TextActor.h + 2d/Transition.cpp + 2d/Transition.h + core/event/Event.cpp + core/event/Event.h + core/event/EventType.h + core/event/KeyEvent.cpp + core/event/KeyEvent.h + core/event/MouseEvent.cpp + core/event/MouseEvent.h + core/event/WindowEvent.cpp + core/event/WindowEvent.h + core/Allocator.cpp + core/Allocator.h + core/Any.h + core/Cloneable.h + core/Common.h + core/Director.cpp + core/Director.h + core/EventDispatcher.cpp + core/EventDispatcher.h + core/EventListener.cpp + core/EventListener.h + core/Exception.cpp + core/Exception.h + core/Function.h + core/IntrusiveList.h + core/Json.h + core/Keys.h + core/Library.cpp + core/Library.h + core/Logger.cpp + core/Logger.h + core/Module.cpp + core/Module.h + core/ObjectBase.cpp + core/ObjectBase.h + core/RefCounter.cpp + core/RefCounter.h + core/Resource.cpp + core/Resource.h + core/Serializable.h + core/Singleton.h + core/SmartPtr.hpp + core/String.cpp + core/String.h + core/Time.cpp + core/Time.h + core/Timer.cpp + core/Timer.h + core/TimerManager.cpp + core/TimerManager.h + core/Xml.h + math/Constants.h + math/EaseFunctions.h + math/Math.h + math/Matrix.hpp + math/Random.h + math/Rect.hpp + math/Scalar.h + math/Transform.hpp + math/Vec2.hpp + platform/win32/ComPtr.hpp + platform/win32/libraries.cpp + platform/win32/libraries.h + platform/win32/WindowImpl.cpp + platform/Application.cpp + platform/Application.h + platform/FileSystem.cpp + platform/FileSystem.h + platform/Input.cpp + platform/Input.h + platform/Runner.cpp + platform/Runner.h + platform/Window.cpp + platform/Window.h + render/DirectX/D2DDeviceResources.cpp + render/DirectX/D2DDeviceResources.h + render/DirectX/D3D10DeviceResources.cpp + render/DirectX/D3D10DeviceResources.h + render/DirectX/D3D11DeviceResources.cpp + render/DirectX/D3D11DeviceResources.h + render/DirectX/D3DDeviceResourcesBase.h + render/DirectX/FontCollectionLoader.cpp + render/DirectX/FontCollectionLoader.h + render/DirectX/helper.h + render/DirectX/NativePtr.h + render/DirectX/RenderContextImpl.cpp + render/DirectX/RenderContextImpl.h + render/DirectX/RendererImpl.cpp + render/DirectX/RendererImpl.h + render/DirectX/TextRenderer.cpp + render/DirectX/TextRenderer.h + render/Brush.cpp + render/Brush.h + render/Color.cpp + render/Color.h + render/Font.cpp + render/Font.h + render/Frame.cpp + render/Frame.h + render/FrameSequence.cpp + render/FrameSequence.h + render/GifImage.cpp + render/GifImage.h + render/Layer.cpp + render/Layer.h + render/NativeObject.h + render/RenderContext.cpp + render/RenderContext.h + render/Renderer.cpp + render/Renderer.h + render/Shape.cpp + render/Shape.h + render/ShapeMaker.cpp + render/ShapeMaker.h + render/StrokeStyle.cpp + render/StrokeStyle.h + render/TextLayout.cpp + render/TextLayout.h + render/TextStyle.hpp + render/Texture.cpp + render/Texture.h + render/TextureCache.cpp + render/TextureCache.h + utils/LocalStorage.cpp + utils/LocalStorage.h + utils/ResourceCache.cpp + utils/ResourceCache.h + utils/UserData.cpp + utils/UserData.h + config.h + kiwano.h + macros.h) + +add_library(libkiwano ${SOURCE_FILES}) From b739ef71e28b7a44be4f7eaed46154a27cb3b63e Mon Sep 17 00:00:00 2001 From: "liuhaibo.2020" Date: Fri, 15 May 2020 16:29:20 +0800 Subject: [PATCH 11/37] minor fixes --- src/kiwano-physics/Global.cpp | 1 - src/kiwano/2d/action/Action.cpp | 3 +++ src/kiwano/core/Any.h | 14 +++++++------- src/kiwano/core/Function.h | 18 +++++++++--------- src/kiwano/core/IntrusiveList.h | 8 ++++---- src/kiwano/core/SmartPtr.hpp | 8 ++++---- src/kiwano/render/Brush.h | 1 + 7 files changed, 28 insertions(+), 25 deletions(-) diff --git a/src/kiwano-physics/Global.cpp b/src/kiwano-physics/Global.cpp index ce6eeeba..4c6ee2da 100644 --- a/src/kiwano-physics/Global.cpp +++ b/src/kiwano-physics/Global.cpp @@ -18,7 +18,6 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#pragma once #include namespace kiwano diff --git a/src/kiwano/2d/action/Action.cpp b/src/kiwano/2d/action/Action.cpp index 6dc75105..796fc25b 100644 --- a/src/kiwano/2d/action/Action.cpp +++ b/src/kiwano/2d/action/Action.cpp @@ -65,6 +65,9 @@ void Action::UpdateStep(Actor* target, Duration dt) case Status::Started: Update(target, dt); break; + + default: + break; } if (status_ == Status::Done) diff --git a/src/kiwano/core/Any.h b/src/kiwano/core/Any.h index f530ddb1..461895bf 100644 --- a/src/kiwano/core/Any.h +++ b/src/kiwano/core/Any.h @@ -73,9 +73,9 @@ public: /// \~chinese /// @brief 获取含有对象类型 - inline const type_info& GetType() const noexcept + inline const std::type_info& GetType() const noexcept { - const type_info* const info = GetTypeinfo(); + const std::type_info* const info = GetTypeinfo(); if (info) { return *info; @@ -132,7 +132,7 @@ public: { static_assert(!std::is_void<_Ty>::value, "oc::Any cannot contain void"); - const type_info* const info = GetTypeinfo(); + const std::type_info* const info = GetTypeinfo(); if (info && (*info == typeid(std::decay<_Ty>::type))) { if (HasSmallType()) @@ -193,12 +193,12 @@ public: } private: - const type_info*& GetTypeinfo() + const std::type_info*& GetTypeinfo() { return storage_.small_.info_; } - const type_info* GetTypeinfo() const + const std::type_info* GetTypeinfo() const { return storage_.small_.info_; } @@ -430,14 +430,14 @@ private: private: struct SmallStorage { - const type_info* info_; + const std::type_info* info_; SmallStorageRTTI rtti_; char buffer_[ANY_SMALL_SPACE_SIZE]; }; struct BigStorage { - const type_info* info_; + const std::type_info* info_; BigStorageRTTI rtti_; void* ptr_; }; diff --git a/src/kiwano/core/Function.h b/src/kiwano/core/Function.h index 0f85e1af..8cfcce51 100644 --- a/src/kiwano/core/Function.h +++ b/src/kiwano/core/Function.h @@ -75,9 +75,9 @@ public: virtual void Release() = 0; virtual _Ret Invoke(_Args&&... args) const = 0; - virtual const type_info& TargetType() const noexcept = 0; + virtual const std::type_info& TargetType() const noexcept = 0; - virtual const void* Target(const type_info& type) const noexcept = 0; + virtual const void* Target(const std::type_info& type) const noexcept = 0; }; template @@ -121,12 +121,12 @@ public: return std::invoke(callee_, std::forward<_Args>(args)...); } - virtual const type_info& TargetType() const noexcept + virtual const std::type_info& TargetType() const noexcept { return typeid(_Ty); } - virtual const void* Target(const type_info& type) const noexcept + virtual const void* Target(const std::type_info& type) const noexcept { if (type == this->TargetType()) return &callee_; @@ -153,12 +153,12 @@ public: return std::invoke(func_, ptr_, std::forward<_Args>(args)...); } - virtual const type_info& TargetType() const noexcept + virtual const std::type_info& TargetType() const noexcept { return typeid(ProxyMemCallable); } - virtual const void* Target(const type_info& type) const noexcept + virtual const void* Target(const std::type_info& type) const noexcept { if (type == this->TargetType()) return this; @@ -193,12 +193,12 @@ public: return std::invoke(func_, ptr_, std::forward<_Args>(args)...); } - virtual const type_info& TargetType() const noexcept + virtual const std::type_info& TargetType() const noexcept { return typeid(ProxyConstMemCallable); } - virtual const void* Target(const type_info& type) const noexcept + virtual const void* Target(const std::type_info& type) const noexcept { if (type == this->TargetType()) return this; @@ -321,7 +321,7 @@ public: std::swap(callable_, rhs.callable_); } - const type_info& target_type() const noexcept + const std::type_info& target_type() const noexcept { return callable_->TargetType(); } diff --git a/src/kiwano/core/IntrusiveList.h b/src/kiwano/core/IntrusiveList.h index 3fe724ed..651e2830 100644 --- a/src/kiwano/core/IntrusiveList.h +++ b/src/kiwano/core/IntrusiveList.h @@ -246,13 +246,13 @@ public: } public: - template + template struct Iterator { using iterator_category = std::bidirectional_iterator_tag; - using value_type = _PtrTy; - using pointer = _PtrTy*; - using reference = _PtrTy&; + using value_type = _IterPtrTy; + using pointer = _IterPtrTy*; + using reference = _IterPtrTy&; using difference_type = ptrdiff_t; inline Iterator(value_type ptr = nullptr, bool is_end = false) diff --git a/src/kiwano/core/SmartPtr.hpp b/src/kiwano/core/SmartPtr.hpp index 9b1989fd..ad01496c 100644 --- a/src/kiwano/core/SmartPtr.hpp +++ b/src/kiwano/core/SmartPtr.hpp @@ -73,13 +73,13 @@ public: SmartPtr(pointer_type p) : ptr_(p) { - typename _ProxyTy::Retain(ptr_); + _ProxyTy::Retain(ptr_); } SmartPtr(const SmartPtr& other) : ptr_(other.ptr_) { - typename _ProxyTy::Retain(ptr_); + _ProxyTy::Retain(ptr_); } SmartPtr(SmartPtr&& other) noexcept @@ -97,7 +97,7 @@ public: SmartPtr(const SmartPtr<_UTy, _ProxyTy>& other) { ptr_ = const_cast(dynamic_cast(other.Get())); - typename _ProxyTy::Retain(ptr_); + _ProxyTy::Retain(ptr_); } inline pointer_type Get() noexcept @@ -193,7 +193,7 @@ public: private: void Tidy() { - typename _ProxyTy::Release(ptr_); + _ProxyTy::Release(ptr_); ptr_ = nullptr; } diff --git a/src/kiwano/render/Brush.h b/src/kiwano/render/Brush.h index 32992be7..f2e1648d 100644 --- a/src/kiwano/render/Brush.h +++ b/src/kiwano/render/Brush.h @@ -19,6 +19,7 @@ // THE SOFTWARE. #pragma once +#include #include #include From a2e3a1ea8c18b62d76ef0e2a438f256e50b541a1 Mon Sep 17 00:00:00 2001 From: Nomango Date: Sun, 17 May 2020 20:15:58 +0800 Subject: [PATCH 12/37] Add KGE_LOG_STREAM & KGE_ERROR_STREAM --- src/kiwano/core/Logger.cpp | 2 +- src/kiwano/core/Logger.h | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/kiwano/core/Logger.cpp b/src/kiwano/core/Logger.cpp index 3b958817..25400f0a 100644 --- a/src/kiwano/core/Logger.cpp +++ b/src/kiwano/core/Logger.cpp @@ -298,7 +298,7 @@ void Logger::ResetStreamToStdStream() } // replace the C++ global locale with the user-preferred locale - (void)std::locale::global(std::locale("")); + (void)std::locale::global(std::locale()); (void)std::cout.imbue(std::locale()); (void)std::cerr.imbue(std::locale()); diff --git a/src/kiwano/core/Logger.h b/src/kiwano/core/Logger.h index 8f24fe34..b4177507 100644 --- a/src/kiwano/core/Logger.h +++ b/src/kiwano/core/Logger.h @@ -19,10 +19,9 @@ // THE SOFTWARE. #pragma once -#include #include -#include -#include +#include +#include #ifndef KGE_SYS_LOG #ifdef KGE_DEBUG @@ -49,6 +48,14 @@ #define KGE_LOGF(FORMAT, ...) ::kiwano::Logger::GetInstance().Printf(::kiwano::Logger::Level::Info, FORMAT, __VA_ARGS__) #endif +#ifndef KGE_LOG_STREAM +#define KGE_LOG_STREAM() ::kiwano::Logger::GetInstance().GetOutputStream() +#endif + +#ifndef KGE_ERROR_STREAM +#define KGE_ERROR_STREAM() ::kiwano::Logger::GetInstance().GetErrorStream() +#endif + namespace kiwano { /** From 7cfccdbf3c90b0bc4a6c706162f37ffaf443cb3b Mon Sep 17 00:00:00 2001 From: Nomango Date: Sun, 17 May 2020 20:16:56 +0800 Subject: [PATCH 13/37] Print more info when exception occurred --- src/kiwano/core/Exception.h | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/kiwano/core/Exception.h b/src/kiwano/core/Exception.h index 91cbfda4..9994c376 100644 --- a/src/kiwano/core/Exception.h +++ b/src/kiwano/core/Exception.h @@ -20,19 +20,22 @@ #pragma once #include +#include #include #include -#define KGE_THROW(MESSAGE) \ - do \ - { \ - kiwano::StackTracer().Print(); \ - throw kiwano::RuntimeError(MESSAGE); \ +#define KGE_THROW(MESSAGE) \ + do \ + { \ + KGE_ERROR("An exception occurred: %s", MESSAGE); \ + kiwano::StackTracer().Print(); \ + throw kiwano::RuntimeError(MESSAGE); \ } while (0) #define KGE_THROW_SYSTEM_ERROR(ERRCODE, MESSAGE) \ do \ { \ + KGE_ERROR("An exception occurred (%#x): %s", ERRCODE, MESSAGE); \ kiwano::StackTracer().Print(); \ throw kiwano::SystemError(std::error_code(kiwano::error_enum(ERRCODE)), MESSAGE); \ } while (0) From ce5edaa689369f35384d19da222466e6aff671a7 Mon Sep 17 00:00:00 2001 From: Nomango Date: Sun, 17 May 2020 20:19:03 +0800 Subject: [PATCH 14/37] suppress warning C26812 --- projects/kiwano/cpp.hint | 5 ----- projects/kiwano/kiwano.vcxproj | 2 +- projects/kiwano/kiwano.vcxproj.filters | 2 +- projects/kiwano/suppress_warning.ruleset | 7 +++++++ 4 files changed, 9 insertions(+), 7 deletions(-) delete mode 100644 projects/kiwano/cpp.hint create mode 100644 projects/kiwano/suppress_warning.ruleset diff --git a/projects/kiwano/cpp.hint b/projects/kiwano/cpp.hint deleted file mode 100644 index 6e489168..00000000 --- a/projects/kiwano/cpp.hint +++ /dev/null @@ -1,5 +0,0 @@ -// 鎻愮ず鏂囦欢甯姪 Visual Studio IDE 瑙i噴 Visual C++ 鏍囪瘑绗, -// 濡傚嚱鏁板拰瀹忕殑鍚嶇О銆 -// 鏈夊叧璇︾粏淇℃伅锛岃鍙傝 https://go.microsoft.com/fwlink/?linkid=865984 - -#define KGE_API diff --git a/projects/kiwano/kiwano.vcxproj b/projects/kiwano/kiwano.vcxproj index f8ae48e0..0c019d8f 100644 --- a/projects/kiwano/kiwano.vcxproj +++ b/projects/kiwano/kiwano.vcxproj @@ -185,7 +185,7 @@ - + {FF7F943D-A89C-4E6C-97CF-84F7D8FF8EDF} diff --git a/projects/kiwano/kiwano.vcxproj.filters b/projects/kiwano/kiwano.vcxproj.filters index 86b3cb0b..e4220660 100644 --- a/projects/kiwano/kiwano.vcxproj.filters +++ b/projects/kiwano/kiwano.vcxproj.filters @@ -541,6 +541,6 @@ - + \ No newline at end of file diff --git a/projects/kiwano/suppress_warning.ruleset b/projects/kiwano/suppress_warning.ruleset new file mode 100644 index 00000000..f2abaa0a --- /dev/null +++ b/projects/kiwano/suppress_warning.ruleset @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file From 2ff0d1ad9545e443a95569b377d1598add72bdd3 Mon Sep 17 00:00:00 2001 From: Nomango Date: Sun, 17 May 2020 21:02:43 +0800 Subject: [PATCH 15/37] Add resolution related functions --- src/kiwano/core/event/WindowEvent.cpp | 6 - src/kiwano/core/event/WindowEvent.h | 15 +- src/kiwano/platform/Application.cpp | 33 ++++- src/kiwano/platform/Application.h | 13 +- src/kiwano/platform/Runner.cpp | 9 +- src/kiwano/platform/Window.cpp | 7 +- src/kiwano/platform/Window.h | 13 +- src/kiwano/platform/win32/WindowImpl.cpp | 139 +++++------------- .../render/DirectX/D3D10DeviceResources.cpp | 97 ++++++++++-- .../render/DirectX/D3D11DeviceResources.cpp | 93 ++++++++++-- .../render/DirectX/D3D11DeviceResources.h | 1 + .../render/DirectX/D3DDeviceResourcesBase.h | 4 + src/kiwano/render/DirectX/RendererImpl.cpp | 79 +++++++++- src/kiwano/render/DirectX/RendererImpl.h | 8 +- src/kiwano/render/Renderer.cpp | 5 - src/kiwano/render/Renderer.h | 22 ++- 16 files changed, 358 insertions(+), 186 deletions(-) diff --git a/src/kiwano/core/event/WindowEvent.cpp b/src/kiwano/core/event/WindowEvent.cpp index 2ab6ab75..37cafb2b 100644 --- a/src/kiwano/core/event/WindowEvent.cpp +++ b/src/kiwano/core/event/WindowEvent.cpp @@ -39,10 +39,4 @@ WindowClosedEvent::WindowClosedEvent() { } -WindowFullscreenEvent::WindowFullscreenEvent() - : WindowEvent(KGE_EVENT(WindowFullscreenEvent)) - , fullscreen(false) -{ -} - } // namespace kiwano diff --git a/src/kiwano/core/event/WindowEvent.h b/src/kiwano/core/event/WindowEvent.h index 96e5cfb2..26a28e0d 100644 --- a/src/kiwano/core/event/WindowEvent.h +++ b/src/kiwano/core/event/WindowEvent.h @@ -29,7 +29,6 @@ KGE_DECLARE_SMART_PTR(WindowResizedEvent); KGE_DECLARE_SMART_PTR(WindowFocusChangedEvent); KGE_DECLARE_SMART_PTR(WindowTitleChangedEvent); KGE_DECLARE_SMART_PTR(WindowClosedEvent); -KGE_DECLARE_SMART_PTR(WindowFullscreenEvent); /** * \addtogroup Events @@ -94,16 +93,6 @@ public: WindowClosedEvent(); }; -/// \~chinese -/// @brief 窗口切换全屏事件 -class KGE_API WindowFullscreenEvent : public WindowEvent -{ -public: - bool fullscreen; - - WindowFullscreenEvent(); -}; - /** @} */ template <> @@ -113,8 +102,8 @@ struct IsEventType { return evt->GetType() == KGE_EVENT(WindowMovedEvent) || evt->GetType() == KGE_EVENT(WindowResizedEvent) || evt->GetType() == KGE_EVENT(WindowFocusChangedEvent) - || evt->GetType() == KGE_EVENT(WindowTitleChangedEvent) || evt->GetType() == KGE_EVENT(WindowClosedEvent) - || evt->GetType() == KGE_EVENT(WindowFullscreenEvent); + || evt->GetType() == KGE_EVENT(WindowTitleChangedEvent) + || evt->GetType() == KGE_EVENT(WindowClosedEvent); } }; diff --git a/src/kiwano/platform/Application.cpp b/src/kiwano/platform/Application.cpp index 064f1d94..3c17a16f 100644 --- a/src/kiwano/platform/Application.cpp +++ b/src/kiwano/platform/Application.cpp @@ -35,7 +35,7 @@ int GetVersion() } Application::Application() - : quiting_(false) + : running_(false) , time_scale_(1.f) { Use(Renderer::GetInstance()); @@ -43,7 +43,10 @@ Application::Application() Use(Director::GetInstance()); } -Application::~Application() {} +Application::~Application() +{ + this->Destroy(); +} void Application::Run(RunnerPtr runner, bool debug) { @@ -65,30 +68,34 @@ void Application::Run(RunnerPtr runner, bool debug) // Everything is ready runner->OnReady(); - quiting_ = false; + running_ = true; last_update_time_ = Time::Now(); - while (!quiting_) + while (running_) { const Time now = Time::Now(); const Duration dt = (now - last_update_time_); last_update_time_ = now; if (!runner->MainLoop(dt)) - quiting_ = true; + running_ = false; } - // Destroy all resources - runner->OnDestroy(); this->Destroy(); } void Application::Quit() { - quiting_ = true; + running_ = false; } void Application::Destroy() { + if (runner_) + { + runner_->OnDestroy(); + runner_ = nullptr; + } + // Clear all resources Director::GetInstance().ClearStages(); ResourceCache::GetInstance().Clear(); @@ -98,6 +105,7 @@ void Application::Destroy() { (*iter)->DestroyModule(); } + modules_.clear(); } void Application::Use(Module& module) @@ -124,6 +132,9 @@ void Application::DispatchEvent(EventPtr evt) void Application::DispatchEvent(Event* evt) { + if (!running_) + return; + for (auto comp : modules_) { if (auto event_comp = comp->Cast()) @@ -135,6 +146,9 @@ void Application::DispatchEvent(Event* evt) void Application::Update(Duration dt) { + if (!running_) + return; + // Before update for (auto comp : modules_) { @@ -186,6 +200,9 @@ void Application::Update(Duration dt) void Application::Render() { + if (!running_) + return; + Renderer& renderer = Renderer::GetInstance(); renderer.Clear(); diff --git a/src/kiwano/platform/Application.h b/src/kiwano/platform/Application.h index 1ca1bce2..e64d3e5a 100644 --- a/src/kiwano/platform/Application.h +++ b/src/kiwano/platform/Application.h @@ -77,6 +77,12 @@ public: */ WindowPtr GetMainWindow() const; + /** + * \~chinese + * @brief 是否正在运行 + */ + bool IsRunning() const; + /** * \~chinese * @brief 添加模块 @@ -143,7 +149,7 @@ public: Time GetLastUpdateTime() const; private: - bool quiting_; + bool running_; float time_scale_; RunnerPtr runner_; Time last_update_time_; @@ -163,6 +169,11 @@ inline WindowPtr Application::GetMainWindow() const return runner_->GetMainWindow(); } +inline bool Application::IsRunning() const +{ + return running_; +} + inline Time Application::GetLastUpdateTime() const { return last_update_time_; diff --git a/src/kiwano/platform/Runner.cpp b/src/kiwano/platform/Runner.cpp index 1c261f3e..7417b436 100644 --- a/src/kiwano/platform/Runner.cpp +++ b/src/kiwano/platform/Runner.cpp @@ -71,6 +71,9 @@ Runner::~Runner() {} bool Runner::MainLoop(Duration dt) { + if (!main_window_) + return false; + if (main_window_->ShouldClose()) { if (this->OnClosing()) @@ -81,14 +84,16 @@ bool Runner::MainLoop(Duration dt) Application& app = Application::GetInstance(); + // Update modules before poll events + app.Update(dt); + // Poll events + main_window_->PumpEvents(); while (EventPtr evt = main_window_->PollEvent()) { app.DispatchEvent(evt.Get()); } - // Update & render - app.Update(dt); app.Render(); return true; } diff --git a/src/kiwano/platform/Window.cpp b/src/kiwano/platform/Window.cpp index be976cb4..e132567a 100644 --- a/src/kiwano/platform/Window.cpp +++ b/src/kiwano/platform/Window.cpp @@ -38,8 +38,6 @@ Window::~Window() EventPtr Window::PollEvent() { - PumpEvents(); - EventPtr evt; if (!event_queue_.empty()) { @@ -84,6 +82,11 @@ void Window::SetShouldClose(bool should) should_close_ = should; } +void Window::SetFullscreenState(bool is_fullscreen) +{ + is_fullscreen_ = is_fullscreen; +} + void Window::PushEvent(EventPtr evt) { event_queue_.push(evt); diff --git a/src/kiwano/platform/Window.h b/src/kiwano/platform/Window.h index bd8a973f..be450e37 100644 --- a/src/kiwano/platform/Window.h +++ b/src/kiwano/platform/Window.h @@ -128,13 +128,6 @@ public: */ virtual void Resize(uint32_t width, uint32_t height) = 0; - /** - * \~chinese - * @brief 设置全屏模式 - * @param fullscreen 是否全屏 - */ - virtual void SetFullscreenState(bool fullscreen) = 0; - /** * \~chinese * @brief 设置鼠标指针类型 @@ -174,6 +167,12 @@ public: */ void SetShouldClose(bool should); + /** + * \~chinese + * @brief 设置当前是否是全屏状态 + */ + void SetFullscreenState(bool is_fullscreen); + protected: Window(); diff --git a/src/kiwano/platform/win32/WindowImpl.cpp b/src/kiwano/platform/win32/WindowImpl.cpp index 818b6698..3c8f5322 100644 --- a/src/kiwano/platform/win32/WindowImpl.cpp +++ b/src/kiwano/platform/win32/WindowImpl.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include // GET_X_LPARAM, GET_Y_LPARAM #include // ImmAssociateContext #pragma comment(lib, "imm32.lib") @@ -55,8 +56,6 @@ public: void Resize(uint32_t width, uint32_t height) override; - void SetFullscreenState(bool fullscreen) override; - void SetCursor(CursorType cursor) override; void PumpEvents() override; @@ -65,8 +64,6 @@ public: void UpdateCursor(); - void SetActive(bool actived); - LRESULT MessageProc(HWND, UINT32, WPARAM, LPARAM); static LRESULT CALLBACK StaticWndProc(HWND, UINT32, WPARAM, LPARAM); @@ -97,7 +94,6 @@ namespace kiwano #define WINDOW_FIXED_STYLE WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX #define WINDOW_RESIZABLE_STYLE WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_SIZEBOX | WS_MAXIMIZEBOX -#define WINDOW_FULLSCREEN_STYLE WS_CLIPCHILDREN | WS_POPUP namespace { @@ -276,11 +272,6 @@ void WindowWin32Impl::Init(const String& title, uint32_t width, uint32_t height, ::ShowWindow(handle_, SW_SHOWNORMAL); ::UpdateWindow(handle_); - - if (is_fullscreen_) - { - SetFullscreenState(true); - } } void WindowWin32Impl::PumpEvents() @@ -314,74 +305,20 @@ void WindowWin32Impl::SetIcon(uint32_t icon_resource) void WindowWin32Impl::Resize(uint32_t width, uint32_t height) { KGE_ASSERT(handle_); - if (!is_fullscreen_) - { - RECT rc = { 0, 0, LONG(width), LONG(height) }; - ::AdjustWindowRect(&rc, GetStyle(), false); - width = rc.right - rc.left; - height = rc.bottom - rc.top; + RECT rc = { 0, 0, LONG(width), LONG(height) }; + ::AdjustWindowRect(&rc, GetStyle(), false); - MONITORINFOEXA info = GetMoniterInfoEx(handle_); - uint32_t screenw = uint32_t(info.rcWork.right - info.rcWork.left); - uint32_t screenh = uint32_t(info.rcWork.bottom - info.rcWork.top); - int left = screenw > width ? ((screenw - width) / 2) : 0; - int top = screenh > height ? ((screenh - height) / 2) : 0; + width = rc.right - rc.left; + height = rc.bottom - rc.top; - ::SetWindowPos(handle_, 0, left, top, width, height, SWP_NOZORDER | SWP_NOACTIVATE); - } - else - { - MONITORINFOEXA info = GetMoniterInfoEx(handle_); - ::SetWindowPos(handle_, HWND_TOPMOST, info.rcMonitor.top, info.rcMonitor.left, width, height, SWP_NOACTIVATE); - } -} + MONITORINFOEXA info = GetMoniterInfoEx(handle_); + uint32_t screenw = uint32_t(info.rcWork.right - info.rcWork.left); + uint32_t screenh = uint32_t(info.rcWork.bottom - info.rcWork.top); + int left = screenw > width ? ((screenw - width) / 2) : 0; + int top = screenh > height ? ((screenh - height) / 2) : 0; -void WindowWin32Impl::SetFullscreenState(bool fullscreen) -{ - if (is_fullscreen_ != fullscreen) - { - is_fullscreen_ = fullscreen; - - // Adjust the rect of client area - RECT rc = { 0, 0, LONG(width_), LONG(height_) }; - ::AdjustWindowRect(&rc, GetStyle(), false); - - uint32_t width = uint32_t(rc.right - rc.left); - uint32_t height = uint32_t(rc.bottom - rc.top); - - if (is_fullscreen_) - { - // Reset window style - ::SetWindowLongPtrA(handle_, GWL_STYLE, GetStyle()); - - // Top the window - MONITORINFOEXA info = GetMoniterInfoEx(handle_); - ::SetWindowPos(handle_, HWND_TOPMOST, info.rcMonitor.top, info.rcMonitor.left, width, height, - SWP_NOACTIVATE); - } - else - { - MONITORINFOEXA info = GetMoniterInfoEx(handle_); - uint32_t screenw = uint32_t(info.rcWork.right - info.rcWork.left); - uint32_t screenh = uint32_t(info.rcWork.bottom - info.rcWork.top); - int left = screenw > width ? ((screenw - width) / 2) : 0; - int top = screenh > height ? ((screenh - height) / 2) : 0; - - // Reset window style - ::SetWindowLongPtrA(handle_, GWL_STYLE, GetStyle()); - - // Unpin the window - ::SetWindowPos(handle_, HWND_NOTOPMOST, left, top, width, height, SWP_DRAWFRAME | SWP_FRAMECHANGED); - } - - ::ShowWindow(handle_, SW_SHOWNORMAL); - - // Send event - WindowFullscreenEventPtr evt = new WindowFullscreenEvent; - evt->fullscreen = is_fullscreen_; - PushEvent(evt); - } + ::SetWindowPos(handle_, 0, left, top, width, height, SWP_NOZORDER | SWP_NOACTIVATE); } void WindowWin32Impl::SetCursor(CursorType cursor) @@ -389,31 +326,9 @@ void WindowWin32Impl::SetCursor(CursorType cursor) mouse_cursor_ = cursor; } -void WindowWin32Impl::SetActive(bool actived) -{ - if (!handle_) - return; - - if (is_fullscreen_) - { - // Hide window when it is not active - if (actived) - { - MONITORINFOEXA info = GetMoniterInfoEx(handle_); - ::SetWindowPos(handle_, HWND_TOPMOST, info.rcMonitor.top, info.rcMonitor.left, width_, height_, - SWP_NOACTIVATE); - } - else - { - ::SetWindowPos(handle_, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); - ::ShowWindow(handle_, SW_MINIMIZE); - } - } -} - DWORD WindowWin32Impl::GetStyle() const { - return is_fullscreen_ ? (WINDOW_FULLSCREEN_STYLE) : (resizable_ ? (WINDOW_RESIZABLE_STYLE) : (WINDOW_FIXED_STYLE)); + return (resizable_ ? (WINDOW_RESIZABLE_STYLE) : (WINDOW_FIXED_STYLE)); } void WindowWin32Impl::UpdateCursor() @@ -563,7 +478,7 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA } else { - // KGE_SYS_LOG("Window resized"); + KGE_SYS_LOG("Window resized"); this->width_ = ((uint32_t)(short)LOWORD(lparam)); this->height_ = ((uint32_t)(short)HIWORD(lparam)); @@ -587,16 +502,32 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA case WM_ACTIVATE: { - bool active = (LOWORD(wparam) != WA_INACTIVE); - - this->SetActive(active); - WindowFocusChangedEventPtr evt = new WindowFocusChangedEvent; - evt->focus = active; + evt->focus = (LOWORD(wparam) != WA_INACTIVE); this->PushEvent(evt); } break; + case WM_SETFOCUS: + { + if (is_fullscreen_) + { + // TODO restore to fullscreen mode + // Renderer::GetInstance().SetResolution(); + } + } + break; + + case WM_KILLFOCUS: + { + if (is_fullscreen_) + { + // TODO exit fullscreen mode + // ::ShowWindow(handle_, SW_MINIMIZE); + } + } + break; + case WM_SETTEXT: { KGE_SYS_LOG("Window title changed"); @@ -619,7 +550,7 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA { KGE_SYS_LOG("The display resolution has changed"); - ::InvalidateRect(hwnd, nullptr, FALSE); + ::InvalidateRect(hwnd, NULL, FALSE); } break; diff --git a/src/kiwano/render/DirectX/D3D10DeviceResources.cpp b/src/kiwano/render/DirectX/D3D10DeviceResources.cpp index 662cbb90..e5657f31 100644 --- a/src/kiwano/render/DirectX/D3D10DeviceResources.cpp +++ b/src/kiwano/render/DirectX/D3D10DeviceResources.cpp @@ -77,6 +77,10 @@ public: HRESULT SetFullscreenState(bool fullscreen) override; + HRESULT ResizeTarget(UINT width, UINT height) override; + + HRESULT GetDisplaySettings(DXGI_MODE_DESC** mode_descs, int* num) override; + void DiscardResources() override; public: @@ -217,24 +221,32 @@ HRESULT D3D10DeviceResources::CreateDeviceResources() if (SUCCEEDED(hr)) { dxgi_device_ = dxgi_device; - - ComPtr dxgi_adapter; - hr = dxgi_device_->GetAdapter(&dxgi_adapter); - - if (SUCCEEDED(hr)) - { - ComPtr dxgi_factory; - hr = dxgi_adapter->GetParent(IID_PPV_ARGS(&dxgi_factory)); - - if (SUCCEEDED(hr)) - { - dxgi_factory_ = dxgi_factory; - } - } } } } + if (SUCCEEDED(hr)) + { + ComPtr dxgi_adapter; + hr = dxgi_device_->GetAdapter(&dxgi_adapter); + + if (SUCCEEDED(hr)) + { + ComPtr dxgi_factory; + hr = dxgi_adapter->GetParent(IID_PPV_ARGS(&dxgi_factory)); + + if (SUCCEEDED(hr)) + { + dxgi_factory_ = dxgi_factory; + } + } + + if (SUCCEEDED(hr)) + { + hr = dxgi_factory_->MakeWindowAssociation(hwnd_, DXGI_MWA_NO_ALT_ENTER); + } + } + if (SUCCEEDED(hr)) { // Setup swap chain @@ -246,6 +258,7 @@ HRESULT D3D10DeviceResources::CreateDeviceResources() swap_chain_desc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; swap_chain_desc.BufferDesc.RefreshRate.Numerator = 60; swap_chain_desc.BufferDesc.RefreshRate.Denominator = 1; + swap_chain_desc.BufferDesc.Scaling = DXGI_MODE_SCALING_CENTERED; swap_chain_desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swap_chain_desc.OutputWindow = hwnd_; @@ -400,7 +413,61 @@ HRESULT D3D10DeviceResources::SetDpi(float dpi) HRESULT D3D10DeviceResources::SetFullscreenState(bool fullscreen) { - return dxgi_swap_chain_->SetFullscreenState(fullscreen ? TRUE : FALSE, nullptr); + HRESULT hr = dxgi_swap_chain_->SetFullscreenState(fullscreen ? TRUE : FALSE, nullptr); + return hr; +} + +HRESULT D3D10DeviceResources::ResizeTarget(UINT width, UINT height) +{ + DXGI_MODE_DESC desc = { 0 }; + desc.Width = width; + desc.Height = height; + desc.Format = DXGI_FORMAT_UNKNOWN; + + HRESULT hr = dxgi_swap_chain_->ResizeTarget(&desc); + return hr; +} + +HRESULT D3D10DeviceResources::GetDisplaySettings(DXGI_MODE_DESC** mode_descs, int* num) +{ + ComPtr dxgi_adapter; + + HRESULT hr = dxgi_device_->GetAdapter(&dxgi_adapter); + if (SUCCEEDED(hr)) + { + ComPtr output; + hr = dxgi_adapter->EnumOutputs(0, &output); + + if (SUCCEEDED(hr)) + { + UINT modes_num = 0; + DXGI_FORMAT format = DXGI_FORMAT_B8G8R8A8_UNORM; + UINT flags = DXGI_ENUM_MODES_INTERLACED; + + output->GetDisplayModeList(format, flags, &modes_num, 0); + + if (modes_num > 0) + { + DXGI_MODE_DESC* temp = new DXGI_MODE_DESC[modes_num]; + + hr = output->GetDisplayModeList(format, flags, &modes_num, temp); + if (SUCCEEDED(hr) && mode_descs && num) + { + (*mode_descs) = temp; + (*num) = (int)modes_num; + } + else + { + delete[] temp; + } + } + else + { + hr = E_FAIL; + } + } + } + return hr; } STDMETHODIMP_(unsigned long) D3D10DeviceResources::AddRef() diff --git a/src/kiwano/render/DirectX/D3D11DeviceResources.cpp b/src/kiwano/render/DirectX/D3D11DeviceResources.cpp index fe0b7b12..e07084cd 100644 --- a/src/kiwano/render/DirectX/D3D11DeviceResources.cpp +++ b/src/kiwano/render/DirectX/D3D11DeviceResources.cpp @@ -66,6 +66,10 @@ public: HRESULT SetFullscreenState(bool fullscreen) override; + HRESULT ResizeTarget(UINT width, UINT height) override; + + HRESULT GetDisplaySettings(DXGI_MODE_DESC** mode_descs, int* num) override; + void DiscardResources() override; public: @@ -239,21 +243,29 @@ HRESULT D3D11DeviceResources::CreateDeviceResources() if (SUCCEEDED(hr)) { dxgi_device_ = dxgi_device; + } + } - ComPtr dxgi_adapter; - hr = dxgi_device_->GetAdapter(&dxgi_adapter); + if (SUCCEEDED(hr)) + { + ComPtr dxgi_adapter; + hr = dxgi_device_->GetAdapter(&dxgi_adapter); + + if (SUCCEEDED(hr)) + { + ComPtr dxgi_factory; + hr = dxgi_adapter->GetParent(IID_PPV_ARGS(&dxgi_factory)); if (SUCCEEDED(hr)) { - ComPtr dxgi_factory; - hr = dxgi_adapter->GetParent(IID_PPV_ARGS(&dxgi_factory)); - - if (SUCCEEDED(hr)) - { - dxgi_factory_ = dxgi_factory; - } + dxgi_factory_ = dxgi_factory; } } + + if (SUCCEEDED(hr)) + { + hr = dxgi_factory_->MakeWindowAssociation(hwnd_, DXGI_MWA_NO_ALT_ENTER); + } } } @@ -268,6 +280,7 @@ HRESULT D3D11DeviceResources::CreateDeviceResources() swap_chain_desc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; swap_chain_desc.BufferDesc.RefreshRate.Numerator = 60; swap_chain_desc.BufferDesc.RefreshRate.Denominator = 1; + swap_chain_desc.BufferDesc.Scaling = DXGI_MODE_SCALING_CENTERED; swap_chain_desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; swap_chain_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swap_chain_desc.OutputWindow = hwnd_; @@ -322,8 +335,9 @@ HRESULT D3D11DeviceResources::CreateWindowSizeDependentResources() output_size_.x = std::max(output_size_.x, 1.f); output_size_.y = std::max(output_size_.y, 1.f); - hr = dxgi_swap_chain_->ResizeBuffers(2, // Double-buffered swap chain. - ::lround(output_size_.x), ::lround(output_size_.y), DXGI_FORMAT_UNKNOWN, 0); + hr = dxgi_swap_chain_->ResizeBuffers(2, /* Double-buffered swap chain */ + ::lround(output_size_.x), ::lround(output_size_.y), DXGI_FORMAT_UNKNOWN, + DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH); if (SUCCEEDED(hr)) { @@ -373,7 +387,6 @@ HRESULT D3D11DeviceResources::CreateWindowSizeDependentResources() device_context_->RSSetViewports(1, &screen_viewport); } - return hr; } @@ -420,7 +433,61 @@ HRESULT D3D11DeviceResources::SetDpi(float dpi) HRESULT D3D11DeviceResources::SetFullscreenState(bool fullscreen) { - return dxgi_swap_chain_->SetFullscreenState(fullscreen ? TRUE : FALSE, nullptr); + HRESULT hr = dxgi_swap_chain_->SetFullscreenState(fullscreen ? TRUE : FALSE, nullptr); + return hr; +} + +HRESULT D3D11DeviceResources::ResizeTarget(UINT width, UINT height) +{ + DXGI_MODE_DESC desc = { 0 }; + desc.Width = width; + desc.Height = height; + desc.Format = DXGI_FORMAT_UNKNOWN; + + HRESULT hr = dxgi_swap_chain_->ResizeTarget(&desc); + return hr; +} + +HRESULT D3D11DeviceResources::GetDisplaySettings(DXGI_MODE_DESC** mode_descs, int* num) +{ + ComPtr dxgi_adapter; + + HRESULT hr = dxgi_device_->GetAdapter(&dxgi_adapter); + if (SUCCEEDED(hr)) + { + ComPtr output; + hr = dxgi_adapter->EnumOutputs(0, &output); + + if (SUCCEEDED(hr)) + { + UINT modes_num = 0; + DXGI_FORMAT format = DXGI_FORMAT_B8G8R8A8_UNORM; + UINT flags = DXGI_ENUM_MODES_INTERLACED; + + output->GetDisplayModeList(format, flags, &modes_num, 0); + + if (modes_num > 0) + { + DXGI_MODE_DESC* temp = new DXGI_MODE_DESC[modes_num]; + + hr = output->GetDisplayModeList(format, flags, &modes_num, temp); + if (SUCCEEDED(hr) && mode_descs && num) + { + (*mode_descs) = temp; + (*num) = (int)modes_num; + } + else + { + delete[] temp; + } + } + else + { + hr = E_FAIL; + } + } + } + return hr; } STDMETHODIMP_(unsigned long) D3D11DeviceResources::AddRef() diff --git a/src/kiwano/render/DirectX/D3D11DeviceResources.h b/src/kiwano/render/DirectX/D3D11DeviceResources.h index 1cb12daf..8adf06bd 100644 --- a/src/kiwano/render/DirectX/D3D11DeviceResources.h +++ b/src/kiwano/render/DirectX/D3D11DeviceResources.h @@ -26,6 +26,7 @@ namespace kiwano { + MIDL_INTERFACE("3ede2b87-a202-4799-a39b-2308ad34cae8") KGE_API ID3D11DeviceResources : public ID3DDeviceResourcesBase { diff --git a/src/kiwano/render/DirectX/D3DDeviceResourcesBase.h b/src/kiwano/render/DirectX/D3DDeviceResourcesBase.h index 421376a0..b83e7856 100644 --- a/src/kiwano/render/DirectX/D3DDeviceResourcesBase.h +++ b/src/kiwano/render/DirectX/D3DDeviceResourcesBase.h @@ -39,6 +39,10 @@ public: virtual HRESULT SetFullscreenState(bool fullscreen) = 0; + virtual HRESULT ResizeTarget(UINT width, UINT height) = 0; + + virtual HRESULT GetDisplaySettings(DXGI_MODE_DESC** mode_descs, int* num) = 0; + virtual void DiscardResources() = 0; }; diff --git a/src/kiwano/render/DirectX/RendererImpl.cpp b/src/kiwano/render/DirectX/RendererImpl.cpp index f0bced1d..2b7adb43 100644 --- a/src/kiwano/render/DirectX/RendererImpl.cpp +++ b/src/kiwano/render/DirectX/RendererImpl.cpp @@ -27,6 +27,8 @@ #include #include +#include + namespace kiwano { @@ -120,12 +122,6 @@ void RendererImpl::MakeContextForWindow(WindowPtr window) KGE_THROW_IF_FAILED(hr, "Create render resources failed"); } -void RendererImpl::SetFullscreenState(bool fullscreen) -{ - KGE_ASSERT(d3d_res_); - d3d_res_->SetFullscreenState(fullscreen); -} - void RendererImpl::Destroy() { KGE_SYS_LOG("Destroying device resources"); @@ -953,6 +949,77 @@ RenderContextPtr RendererImpl::CreateTextureRenderContext(Texture& texture, cons return nullptr; } +void RendererImpl::SetResolution(uint32_t width, uint32_t height, bool fullscreen) +{ + KGE_ASSERT(d3d_res_); + + if (fullscreen) + { + HRESULT hr = d3d_res_->ResizeTarget(width, height); + KGE_THROW_IF_FAILED(hr, "DXGI ResizeTarget failed!"); + + hr = d3d_res_->SetFullscreenState(fullscreen); + KGE_THROW_IF_FAILED(hr, "DXGI SetFullscreenState failed!"); + } + else + { + HRESULT hr = d3d_res_->SetFullscreenState(fullscreen); + KGE_THROW_IF_FAILED(hr, "DXGI SetFullscreenState failed!"); + + hr = d3d_res_->ResizeTarget(width, height); + KGE_THROW_IF_FAILED(hr, "DXGI ResizeTarget failed!"); + } + + Application::GetInstance().GetMainWindow()->SetFullscreenState(fullscreen); +} + +Vector RendererImpl::GetResolutions() +{ + if (resolutions_.empty()) + { + + DXGI_MODE_DESC* mode_descs = nullptr; + int mode_num = 0; + + HRESULT hr = d3d_res_->GetDisplaySettings(&mode_descs, &mode_num); + if (SUCCEEDED(hr)) + { + std::unique_ptr mode_list(mode_descs); + + if (mode_list) + { + for (int i = 0; i < mode_num; i++) + { + Resolution res; + res.width = mode_descs[i].Width; + res.height = mode_descs[i].Height; + res.refresh_rate = 0; + + if (mode_descs[i].RefreshRate.Denominator > 0) + { + res.refresh_rate = mode_descs[i].RefreshRate.Numerator / mode_descs[i].RefreshRate.Denominator; + } + + if (!resolutions_.empty()) + { + auto& back = resolutions_.back(); + if (back.width == res.width && back.height == res.height + && back.refresh_rate == res.refresh_rate) + continue; + } + + resolutions_.push_back(res); + } + } + } + else + { + KGE_THROW_IF_FAILED(hr, "DXGI GetDisplaySettings failed!"); + } + } + return resolutions_; +} + void RendererImpl::Resize(uint32_t width, uint32_t height) { HRESULT hr = S_OK; diff --git a/src/kiwano/render/DirectX/RendererImpl.h b/src/kiwano/render/DirectX/RendererImpl.h index e90d35ac..4851229e 100644 --- a/src/kiwano/render/DirectX/RendererImpl.h +++ b/src/kiwano/render/DirectX/RendererImpl.h @@ -82,6 +82,10 @@ public: RenderContextPtr CreateTextureRenderContext(Texture& texture, const Size* desired_size = nullptr) override; + void SetResolution(uint32_t width, uint32_t height, bool fullscreen) override; + + Vector GetResolutions() override; + public: void Clear() override; @@ -104,8 +108,6 @@ protected: void MakeContextForWindow(WindowPtr window) override; - void SetFullscreenState(bool fullscreen) override; - void Destroy() override; private: @@ -114,6 +116,8 @@ private: ComPtr font_collection_loader_; ComPtr res_font_file_loader_; ComPtr res_font_collection_loader_; + + Vector resolutions_; }; /** @} */ diff --git a/src/kiwano/render/Renderer.cpp b/src/kiwano/render/Renderer.cpp index 4c56e029..f25086ef 100644 --- a/src/kiwano/render/Renderer.cpp +++ b/src/kiwano/render/Renderer.cpp @@ -49,11 +49,6 @@ void Renderer::HandleEvent(Event* evt) auto window_evt = dynamic_cast(evt); Resize(window_evt->width, window_evt->height); } - else if (evt->IsType()) - { - auto window_evt = dynamic_cast(evt); - SetFullscreenState(window_evt->fullscreen); - } } void Renderer::BeginDraw() diff --git a/src/kiwano/render/Renderer.h b/src/kiwano/render/Renderer.h index 07bf9ff1..7b2d60f0 100644 --- a/src/kiwano/render/Renderer.h +++ b/src/kiwano/render/Renderer.h @@ -39,6 +39,18 @@ namespace kiwano * @{ */ +/** + * \~chinese + * @brief 分辨率 + */ +struct Resolution +{ + uint32_t width; ///< 分辨率宽度 + uint32_t height; ///< 分辨率高度 + uint32_t refresh_rate; ///< 刷新率 +}; + + /** * \~chinese * @brief 渲染器 @@ -62,6 +74,14 @@ public: /// @brief 开启或关闭垂直同步 virtual void SetVSyncEnabled(bool enabled); + /// \~chinese + /// @brief 设置分辨率 + virtual void SetResolution(uint32_t width, uint32_t height, bool fullscreen) = 0; + + /// \~chinese + /// @brief 获取屏幕分辨率 + virtual Vector GetResolutions() = 0; + /// \~chinese /// @brief 创建纹理内部资源 /// @param[out] texture 纹理 @@ -246,8 +266,6 @@ protected: virtual void MakeContextForWindow(WindowPtr window) = 0; - virtual void SetFullscreenState(bool fullscreen) = 0; - virtual void Destroy() = 0; protected: From 3fd3fbbbd86fc43d3a95ea0aa7aa46cfd70e1d67 Mon Sep 17 00:00:00 2001 From: Nomango Date: Tue, 19 May 2020 21:12:57 +0800 Subject: [PATCH 16/37] update GetDisplaySettings function --- .../render/DirectX/D3D10DeviceResources.cpp | 48 +++++++++---------- .../render/DirectX/D3D11DeviceResources.cpp | 47 +++++++++--------- 2 files changed, 44 insertions(+), 51 deletions(-) diff --git a/src/kiwano/render/DirectX/D3D10DeviceResources.cpp b/src/kiwano/render/DirectX/D3D10DeviceResources.cpp index e5657f31..26897fa8 100644 --- a/src/kiwano/render/DirectX/D3D10DeviceResources.cpp +++ b/src/kiwano/render/DirectX/D3D10DeviceResources.cpp @@ -105,11 +105,13 @@ public: Size logical_size_; Size output_size_; unsigned long ref_count_; + DXGI_FORMAT desired_color_format_; }; D3D10DeviceResources::D3D10DeviceResources() : ref_count_(0) , hwnd_(nullptr) + , desired_color_format_(DXGI_FORMAT_B8G8R8A8_UNORM) { dpi_ = 96.f; // dpi_ = (float)GetDpiForWindow(hwnd); } @@ -255,7 +257,7 @@ HRESULT D3D10DeviceResources::CreateDeviceResources() swap_chain_desc.BufferCount = 2; swap_chain_desc.BufferDesc.Width = ::lround(output_size_.x); swap_chain_desc.BufferDesc.Height = ::lround(output_size_.y); - swap_chain_desc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + swap_chain_desc.BufferDesc.Format = desired_color_format_; swap_chain_desc.BufferDesc.RefreshRate.Numerator = 60; swap_chain_desc.BufferDesc.RefreshRate.Denominator = 1; swap_chain_desc.BufferDesc.Scaling = DXGI_MODE_SCALING_CENTERED; @@ -308,7 +310,7 @@ HRESULT D3D10DeviceResources::CreateWindowSizeDependentResources() if (SUCCEEDED(hr)) { D3D10_RENDER_TARGET_VIEW_DESC renderDesc; - renderDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + renderDesc.Format = desired_color_format_; renderDesc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D; renderDesc.Texture2D.MipSlice = 0; @@ -430,42 +432,36 @@ HRESULT D3D10DeviceResources::ResizeTarget(UINT width, UINT height) HRESULT D3D10DeviceResources::GetDisplaySettings(DXGI_MODE_DESC** mode_descs, int* num) { - ComPtr dxgi_adapter; + KGE_ASSERT(dxgi_swap_chain_); + + ComPtr output; + HRESULT hr = dxgi_swap_chain_->GetContainingOutput(&output); - HRESULT hr = dxgi_device_->GetAdapter(&dxgi_adapter); if (SUCCEEDED(hr)) { - ComPtr output; - hr = dxgi_adapter->EnumOutputs(0, &output); + UINT num_of_supported_modes = 0; + output->GetDisplayModeList(desired_color_format_, 0, &num_of_supported_modes, 0); - if (SUCCEEDED(hr)) + if (num_of_supported_modes > 0) { - UINT modes_num = 0; - DXGI_FORMAT format = DXGI_FORMAT_B8G8R8A8_UNORM; - UINT flags = DXGI_ENUM_MODES_INTERLACED; + DXGI_MODE_DESC* supported_modes = new DXGI_MODE_DESC[num_of_supported_modes]; + ZeroMemory(supported_modes, sizeof(DXGI_MODE_DESC) * num_of_supported_modes); - output->GetDisplayModeList(format, flags, &modes_num, 0); - - if (modes_num > 0) + hr = output->GetDisplayModeList(desired_color_format_, 0, &num_of_supported_modes, supported_modes); + if (SUCCEEDED(hr) && mode_descs && num) { - DXGI_MODE_DESC* temp = new DXGI_MODE_DESC[modes_num]; - - hr = output->GetDisplayModeList(format, flags, &modes_num, temp); - if (SUCCEEDED(hr) && mode_descs && num) - { - (*mode_descs) = temp; - (*num) = (int)modes_num; - } - else - { - delete[] temp; - } + (*mode_descs) = supported_modes; + (*num) = (int)num_of_supported_modes; } else { - hr = E_FAIL; + delete[] supported_modes; } } + else + { + hr = E_FAIL; + } } return hr; } diff --git a/src/kiwano/render/DirectX/D3D11DeviceResources.cpp b/src/kiwano/render/DirectX/D3D11DeviceResources.cpp index e07084cd..e39e69f3 100644 --- a/src/kiwano/render/DirectX/D3D11DeviceResources.cpp +++ b/src/kiwano/render/DirectX/D3D11DeviceResources.cpp @@ -20,6 +20,7 @@ #include #include +#include KGE_SUPPRESS_WARNING_PUSH KGE_SUPPRESS_WARNING(4800) // Implicit conversion from 'type' to bool @@ -96,12 +97,14 @@ public: unsigned long ref_count_; D3D_FEATURE_LEVEL d3d_feature_level_; + DXGI_FORMAT desired_color_format_; }; D3D11DeviceResources::D3D11DeviceResources() : ref_count_(0) , hwnd_(nullptr) , d3d_feature_level_(D3D_FEATURE_LEVEL_9_1) + , desired_color_format_(DXGI_FORMAT_B8G8R8A8_UNORM) { dpi_ = 96.f; // dpi_ = (float)GetDpiForWindow(hwnd); } @@ -277,7 +280,7 @@ HRESULT D3D11DeviceResources::CreateDeviceResources() swap_chain_desc.BufferCount = 2; swap_chain_desc.BufferDesc.Width = ::lround(output_size_.x); swap_chain_desc.BufferDesc.Height = ::lround(output_size_.y); - swap_chain_desc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + swap_chain_desc.BufferDesc.Format = desired_color_format_; swap_chain_desc.BufferDesc.RefreshRate.Numerator = 60; swap_chain_desc.BufferDesc.RefreshRate.Denominator = 1; swap_chain_desc.BufferDesc.Scaling = DXGI_MODE_SCALING_CENTERED; @@ -450,42 +453,36 @@ HRESULT D3D11DeviceResources::ResizeTarget(UINT width, UINT height) HRESULT D3D11DeviceResources::GetDisplaySettings(DXGI_MODE_DESC** mode_descs, int* num) { - ComPtr dxgi_adapter; + KGE_ASSERT(dxgi_swap_chain_); + + ComPtr output; + HRESULT hr = dxgi_swap_chain_->GetContainingOutput(&output); - HRESULT hr = dxgi_device_->GetAdapter(&dxgi_adapter); if (SUCCEEDED(hr)) { - ComPtr output; - hr = dxgi_adapter->EnumOutputs(0, &output); + UINT num_of_supported_modes = 0; + output->GetDisplayModeList(desired_color_format_, 0, &num_of_supported_modes, 0); - if (SUCCEEDED(hr)) + if (num_of_supported_modes > 0) { - UINT modes_num = 0; - DXGI_FORMAT format = DXGI_FORMAT_B8G8R8A8_UNORM; - UINT flags = DXGI_ENUM_MODES_INTERLACED; + DXGI_MODE_DESC* supported_modes = new DXGI_MODE_DESC[num_of_supported_modes]; + ZeroMemory(supported_modes, sizeof(DXGI_MODE_DESC) * num_of_supported_modes); - output->GetDisplayModeList(format, flags, &modes_num, 0); - - if (modes_num > 0) + hr = output->GetDisplayModeList(desired_color_format_, 0, &num_of_supported_modes, supported_modes); + if (SUCCEEDED(hr) && mode_descs && num) { - DXGI_MODE_DESC* temp = new DXGI_MODE_DESC[modes_num]; - - hr = output->GetDisplayModeList(format, flags, &modes_num, temp); - if (SUCCEEDED(hr) && mode_descs && num) - { - (*mode_descs) = temp; - (*num) = (int)modes_num; - } - else - { - delete[] temp; - } + (*mode_descs) = supported_modes; + (*num) = (int)num_of_supported_modes; } else { - hr = E_FAIL; + delete[] supported_modes; } } + else + { + hr = E_FAIL; + } } return hr; } From 41671fa1f3ed6ab6d30afad77016ac38fa68b7a3 Mon Sep 17 00:00:00 2001 From: Nomango Date: Tue, 19 May 2020 21:13:42 +0800 Subject: [PATCH 17/37] Time::now() supports cross-platform --- src/kiwano/core/Time.cpp | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/src/kiwano/core/Time.cpp b/src/kiwano/core/Time.cpp index 49a31ee5..cd3a1f1d 100644 --- a/src/kiwano/core/Time.cpp +++ b/src/kiwano/core/Time.cpp @@ -23,6 +23,7 @@ #include #include #include +#include namespace kiwano { @@ -69,19 +70,32 @@ const Duration Time::operator-(const Time& other) const Time Time::Now() noexcept { - static LARGE_INTEGER freq = {}; - if (freq.QuadPart == 0LL) +#if defined(KGE_PLATFORM_WINDOWS) + + static double millisecs_per_count = {}; + if (millisecs_per_count == 0) { + LARGE_INTEGER freq = {}; // the Function will always succceed on systems that run Windows XP or later QueryPerformanceFrequency(&freq); + millisecs_per_count = 1000.0 / static_cast(freq.QuadPart); } LARGE_INTEGER count; QueryPerformanceCounter(&count); + return Time{ static_cast(count.QuadPart * millisecs_per_count) }; - const long long whole = (count.QuadPart / freq.QuadPart) * 1000LL; - const long long part = (count.QuadPart % freq.QuadPart) * 1000LL / freq.QuadPart; - return Time{ static_cast(whole + part) }; +#else + + using std::chrono::steady_clock; + using std::chrono::duration_cast; + using std::chrono::milliseconds; + + const auto now = steady_clock::now(); + const long long count = duration_cast(now.time_since_epoch()).count(); + return Time{ static_cast(count) }; + +#endif } //------------------------------------------------------- From 430e46a5a3c8b1545fc333b2a06e7611e4c23ba4 Mon Sep 17 00:00:00 2001 From: Nomango Date: Tue, 19 May 2020 21:25:00 +0800 Subject: [PATCH 18/37] Timer => Task --- projects/kiwano/kiwano.vcxproj | 8 +- projects/kiwano/kiwano.vcxproj.filters | 24 +-- src/kiwano/2d/Actor.cpp | 2 +- src/kiwano/2d/Actor.h | 6 +- src/kiwano/core/{Timer.cpp => Task.cpp} | 16 +- src/kiwano/core/{Timer.h => Task.h} | 90 +++++------ src/kiwano/core/TaskManager.cpp | 140 ++++++++++++++++++ .../core/{TimerManager.h => TaskManager.h} | 54 +++---- src/kiwano/core/TimerManager.cpp | 140 ------------------ src/kiwano/kiwano.h | 4 +- src/kiwano/platform/Runner.h | 2 +- 11 files changed, 243 insertions(+), 243 deletions(-) rename src/kiwano/core/{Timer.cpp => Task.cpp} (85%) rename src/kiwano/core/{Timer.h => Task.h} (62%) create mode 100644 src/kiwano/core/TaskManager.cpp rename src/kiwano/core/{TimerManager.h => TaskManager.h} (63%) delete mode 100644 src/kiwano/core/TimerManager.cpp diff --git a/projects/kiwano/kiwano.vcxproj b/projects/kiwano/kiwano.vcxproj index 0c019d8f..c6948709 100644 --- a/projects/kiwano/kiwano.vcxproj +++ b/projects/kiwano/kiwano.vcxproj @@ -53,8 +53,8 @@ - - + + @@ -139,8 +139,8 @@ - - + + diff --git a/projects/kiwano/kiwano.vcxproj.filters b/projects/kiwano/kiwano.vcxproj.filters index e4220660..75592486 100644 --- a/projects/kiwano/kiwano.vcxproj.filters +++ b/projects/kiwano/kiwano.vcxproj.filters @@ -69,12 +69,6 @@ core - - core - - - core - 2d @@ -327,6 +321,12 @@ render + + core + + + core + @@ -350,12 +350,6 @@ platform - - core - - - core - 2d @@ -539,6 +533,12 @@ render + + core + + + core + diff --git a/src/kiwano/2d/Actor.cpp b/src/kiwano/2d/Actor.cpp index 3eca99a6..6e9a0340 100644 --- a/src/kiwano/2d/Actor.cpp +++ b/src/kiwano/2d/Actor.cpp @@ -79,7 +79,7 @@ void Actor::Update(Duration dt) { UpdateActions(this, dt); UpdateComponents(dt); - UpdateTimers(dt); + UpdateTasks(dt); if (!update_pausing_) { diff --git a/src/kiwano/2d/Actor.h b/src/kiwano/2d/Actor.h index 459f1f34..0c552b20 100644 --- a/src/kiwano/2d/Actor.h +++ b/src/kiwano/2d/Actor.h @@ -21,7 +21,7 @@ #pragma once #include #include -#include +#include #include #include #include @@ -58,11 +58,11 @@ typedef IntrusiveList ActorList; * \~chinese * @brief 角色 * @details - * 角色是舞台上最基本的元素,是完成渲染、更新、事件分发等功能的最小单位,也是动画、定时器、事件监听等功能的载体 + * 角色是舞台上最基本的元素,是完成渲染、更新、事件分发等功能的最小单位,也是动画、任务、事件监听等功能的载体 */ class KGE_API Actor : public ObjectBase - , public TimerManager + , public TaskManager , public ActionManager , public EventDispatcher , protected IntrusiveListValue diff --git a/src/kiwano/core/Timer.cpp b/src/kiwano/core/Task.cpp similarity index 85% rename from src/kiwano/core/Timer.cpp rename to src/kiwano/core/Task.cpp index ab72cb03..cea275b6 100644 --- a/src/kiwano/core/Timer.cpp +++ b/src/kiwano/core/Task.cpp @@ -18,14 +18,14 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include namespace kiwano { -TimerPtr Timer::Create(const Callback& cb, Duration interval, int times) +TaskPtr Task::Create(const Callback& cb, Duration interval, int times) { - TimerPtr ptr = memory::New(); + TaskPtr ptr = memory::New(); if (ptr) { ptr->SetCallback(cb); @@ -35,9 +35,9 @@ TimerPtr Timer::Create(const Callback& cb, Duration interval, int times) return ptr; } -TimerPtr Timer::Create(const String& name, const Callback& cb, Duration interval, int times) +TaskPtr Task::Create(const String& name, const Callback& cb, Duration interval, int times) { - TimerPtr ptr = memory::New(); + TaskPtr ptr = memory::New(); if (ptr) { ptr->SetName(name); @@ -48,7 +48,7 @@ TimerPtr Timer::Create(const String& name, const Callback& cb, Duration interval return ptr; } -Timer::Timer() +Task::Task() : running_(true) , removeable_(false) , run_times_(0) @@ -59,7 +59,7 @@ Timer::Timer() { } -void Timer::Update(Duration dt) +void Task::Update(Duration dt) { if (total_times_ == 0) { @@ -87,7 +87,7 @@ void Timer::Update(Duration dt) } } -void Timer::Reset() +void Task::Reset() { elapsed_ = 0; run_times_ = 0; diff --git a/src/kiwano/core/Timer.h b/src/kiwano/core/Task.h similarity index 62% rename from src/kiwano/core/Timer.h rename to src/kiwano/core/Task.h index 07a9480f..8d31ad41 100644 --- a/src/kiwano/core/Timer.h +++ b/src/kiwano/core/Task.h @@ -25,105 +25,105 @@ namespace kiwano { -class TimerManager; +class TaskManager; -KGE_DECLARE_SMART_PTR(Timer); +KGE_DECLARE_SMART_PTR(Task); /// \~chinese -/// @brief 定时器列表 -typedef IntrusiveList TimerList; +/// @brief 任务列表 +typedef IntrusiveList TaskList; /// \~chinese -/// @brief 定时器 -/// @details 定时器用于每隔一段时间执行一次回调函数,且可以指定执行总次数 -class KGE_API Timer +/// @brief 任务 +/// @details 任务用于每隔一段时间执行一次回调函数,且可以指定执行总次数 +class KGE_API Task : public ObjectBase - , protected IntrusiveListValue + , protected IntrusiveListValue { - friend class TimerManager; - friend IntrusiveList; + friend class TaskManager; + friend IntrusiveList; public: /// \~chinese - /// @brief 定时器回调函数 + /// @brief 任务回调函数 /// @details - /// 回调函数第一个参数是定时器自身,第二个参数是距离上次更新的时间间隔 - using Callback = Function; + /// 回调函数第一个参数是任务自身,第二个参数是距离上次执行任务的时间间隔 + using Callback = Function; /// \~chinese - /// @brief 创建定时器 + /// @brief 创建任务 /// @param cb 回调函数 /// @param interval 时间间隔 /// @param times 执行次数(设 -1 为永久执行) - static TimerPtr Create(const Callback& cb, Duration interval, int times = -1); + static TaskPtr Create(const Callback& cb, Duration interval, int times = -1); /// \~chinese - /// @brief 创建定时器 + /// @brief 创建任务 /// @param name 名称 /// @param cb 回调函数 /// @param interval 时间间隔 /// @param times 执行次数(设 -1 为永久执行) - static TimerPtr Create(const String& name, const Callback& cb, Duration interval, int times = -1); + static TaskPtr Create(const String& name, const Callback& cb, Duration interval, int times = -1); /// \~chinese - /// @brief 构造空定时器 - Timer(); + /// @brief 构造空任务 + Task(); /// \~chinese - /// @brief 启动定时器 + /// @brief 启动任务 void Start(); /// \~chinese - /// @brief 停止定时器 + /// @brief 停止任务 void Stop(); /// \~chinese - /// @brief 移除定时器 + /// @brief 移除任务 void Remove(); /// \~chinese - /// @brief 定时器是否在运行 + /// @brief 任务是否在运行 bool IsRunning() const; /// \~chinese - /// @brief 定时器是否可移除 + /// @brief 任务是否可移除 bool IsRemoveable() const; /// \~chinese - /// @brief 获取定时器执行过回调函数的次数 + /// @brief 获取任务执行过回调函数的次数 int GetRunTimes() const; /// \~chinese - /// @brief 获取定时器执行回调函数的总次数 + /// @brief 获取任务执行回调函数的总次数 int GetTotalRunTimes() const; /// \~chinese - /// @brief 设置定时器执行回调函数的总次数 + /// @brief 设置任务执行回调函数的总次数 void SetTotalRunTimes(int times); /// \~chinese - /// @brief 获取定时器执行时间间隔 + /// @brief 获取任务执行时间间隔 Duration GetInterval() const; /// \~chinese - /// @brief 设置定时器执行时间间隔 + /// @brief 设置任务执行时间间隔 void SetInterval(Duration interval); /// \~chinese - /// @brief 获取定时器回调函数 + /// @brief 获取任务回调函数 Callback GetCallback() const; /// \~chinese - /// @brief 设置定时器回调函数 + /// @brief 设置任务回调函数 void SetCallback(const Callback& callback); private: /// \~chinese - /// @brief 更新定时器 + /// @brief 更新任务 void Update(Duration dt); /// \~chinese - /// @brief 重置定时器 + /// @brief 重置任务 void Reset(); private: @@ -136,62 +136,62 @@ private: Callback callback_; }; -inline void Timer::Start() +inline void Task::Start() { running_ = true; } -inline void Timer::Stop() +inline void Task::Stop() { running_ = false; } -inline void Timer::Remove() +inline void Task::Remove() { removeable_ = true; } -inline bool Timer::IsRunning() const +inline bool Task::IsRunning() const { return running_; } -inline bool Timer::IsRemoveable() const +inline bool Task::IsRemoveable() const { return removeable_; } -inline int Timer::GetRunTimes() const +inline int Task::GetRunTimes() const { return run_times_; } -inline int Timer::GetTotalRunTimes() const +inline int Task::GetTotalRunTimes() const { return total_times_; } -inline void Timer::SetTotalRunTimes(int times) +inline void Task::SetTotalRunTimes(int times) { total_times_ = times; } -inline Duration Timer::GetInterval() const +inline Duration Task::GetInterval() const { return interval_; } -inline void Timer::SetInterval(Duration interval) +inline void Task::SetInterval(Duration interval) { interval_ = interval; } -inline Timer::Callback Timer::GetCallback() const +inline Task::Callback Task::GetCallback() const { return callback_; } -inline void Timer::SetCallback(const Timer::Callback& callback) +inline void Task::SetCallback(const Task::Callback& callback) { callback_ = callback; } diff --git a/src/kiwano/core/TaskManager.cpp b/src/kiwano/core/TaskManager.cpp new file mode 100644 index 00000000..ae556aa0 --- /dev/null +++ b/src/kiwano/core/TaskManager.cpp @@ -0,0 +1,140 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#include +#include + +namespace kiwano +{ +void TaskManager::UpdateTasks(Duration dt) +{ + if (tasks_.IsEmpty()) + return; + + TaskPtr next; + for (auto task = tasks_.GetFirst(); task; task = next) + { + next = task->GetNext(); + + task->Update(dt); + + if (task->IsRemoveable()) + tasks_.Remove(task); + } +} + +Task* TaskManager::AddTask(const Task::Callback& cb, Duration interval, int times) +{ + return AddTask(String(), cb, interval, times); +} + +Task* TaskManager::AddTask(const String& name, const Task::Callback& cb, Duration interval, int times) +{ + TaskPtr task = Task::Create(name, cb, interval, times); + return AddTask(task); +} + +Task* TaskManager::AddTask(TaskPtr task) +{ + KGE_ASSERT(task && "AddTask failed, NULL pointer exception"); + + if (task) + { + task->Reset(); + tasks_.PushBack(task); + } + + return task.Get(); +} + +void TaskManager::StopTasks(const String& name) +{ + if (tasks_.IsEmpty()) + return; + + for (auto& task : tasks_) + { + if (task->IsName(name)) + { + task->Stop(); + } + } +} + +void TaskManager::StartTasks(const String& name) +{ + if (tasks_.IsEmpty()) + return; + + for (auto& task : tasks_) + { + if (task->IsName(name)) + { + task->Start(); + } + } +} + +void TaskManager::RemoveTasks(const String& name) +{ + if (tasks_.IsEmpty()) + return; + + for (auto& task : tasks_) + { + if (task->IsName(name)) + { + task->Remove(); + } + } +} + +void TaskManager::StopAllTasks() +{ + if (tasks_.IsEmpty()) + return; + + for (auto& task : tasks_) + { + task->Stop(); + } +} + +void TaskManager::StartAllTasks() +{ + if (tasks_.IsEmpty()) + return; + + for (auto& task : tasks_) + { + task->Start(); + } +} + +void TaskManager::RemoveAllTasks() +{ + tasks_.Clear(); +} + +const TaskList& TaskManager::GetAllTasks() const +{ + return tasks_; +} +} // namespace kiwano diff --git a/src/kiwano/core/TimerManager.h b/src/kiwano/core/TaskManager.h similarity index 63% rename from src/kiwano/core/TimerManager.h rename to src/kiwano/core/TaskManager.h index 5834e424..7cc8e495 100644 --- a/src/kiwano/core/TimerManager.h +++ b/src/kiwano/core/TaskManager.h @@ -19,70 +19,70 @@ // THE SOFTWARE. #pragma once -#include +#include namespace kiwano { /** * \~chinese - * @brief 定时器管理器 + * @brief 任务管理器 */ -class KGE_API TimerManager +class KGE_API TaskManager { public: /// \~chinese - /// @brief 添加定时器 + /// @brief 添加任务 /// @param cb 回调函数 /// @param interval 时间间隔 /// @param times 执行次数(设 -1 为永久执行) - Timer* AddTimer(const Timer::Callback& cb, Duration interval, int times = -1); + Task* AddTask(const Task::Callback& cb, Duration interval, int times = -1); /// \~chinese - /// @brief 添加定时器 - /// @param name 定时器名称 + /// @brief 添加任务 + /// @param name 任务名称 /// @param cb 回调函数 /// @param interval 时间间隔 /// @param times 执行次数(设 -1 为永久执行) - Timer* AddTimer(const String& name, const Timer::Callback& cb, Duration interval, int times = -1); + Task* AddTask(const String& name, const Task::Callback& cb, Duration interval, int times = -1); /// \~chinese - /// @brief 添加定时器 - Timer* AddTimer(TimerPtr timer); + /// @brief 添加任务 + Task* AddTask(TaskPtr task); /// \~chinese - /// @brief 启动定时器 - void StartTimers(const String& timer_name); + /// @brief 启动任务 + void StartTasks(const String& task_name); /// \~chinese - /// @brief 停止定时器 - void StopTimers(const String& timer_name); + /// @brief 停止任务 + void StopTasks(const String& task_name); /// \~chinese - /// @brief 移除定时器 - void RemoveTimers(const String& timer_name); + /// @brief 移除任务 + void RemoveTasks(const String& task_name); /// \~chinese - /// @brief 启动所有定时器 - void StartAllTimers(); + /// @brief 启动所有任务 + void StartAllTasks(); /// \~chinese - /// @brief 停止所有定时器 - void StopAllTimers(); + /// @brief 停止所有任务 + void StopAllTasks(); /// \~chinese - /// @brief 移除所有定时器 - void RemoveAllTimers(); + /// @brief 移除所有任务 + void RemoveAllTasks(); /// \~chinese - /// @brief 获取所有定时器 - const TimerList& GetAllTimers() const; + /// @brief 获取所有任务 + const TaskList& GetAllTasks() const; protected: /// \~chinese - /// @brief 更新定时器 - void UpdateTimers(Duration dt); + /// @brief 更新任务 + void UpdateTasks(Duration dt); private: - TimerList timers_; + TaskList tasks_; }; } // namespace kiwano diff --git a/src/kiwano/core/TimerManager.cpp b/src/kiwano/core/TimerManager.cpp deleted file mode 100644 index bf4d5c92..00000000 --- a/src/kiwano/core/TimerManager.cpp +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) 2016-2018 Kiwano - Nomango -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#include -#include - -namespace kiwano -{ -void TimerManager::UpdateTimers(Duration dt) -{ - if (timers_.IsEmpty()) - return; - - TimerPtr next; - for (auto timer = timers_.GetFirst(); timer; timer = next) - { - next = timer->GetNext(); - - timer->Update(dt); - - if (timer->IsRemoveable()) - timers_.Remove(timer); - } -} - -Timer* TimerManager::AddTimer(const Timer::Callback& cb, Duration interval, int times) -{ - return AddTimer(String(), cb, interval, times); -} - -Timer* TimerManager::AddTimer(const String& name, const Timer::Callback& cb, Duration interval, int times) -{ - TimerPtr timer = Timer::Create(name, cb, interval, times); - return AddTimer(timer); -} - -Timer* TimerManager::AddTimer(TimerPtr timer) -{ - KGE_ASSERT(timer && "AddTimer failed, NULL pointer exception"); - - if (timer) - { - timer->Reset(); - timers_.PushBack(timer); - } - - return timer.Get(); -} - -void TimerManager::StopTimers(const String& name) -{ - if (timers_.IsEmpty()) - return; - - for (auto& timer : timers_) - { - if (timer->IsName(name)) - { - timer->Stop(); - } - } -} - -void TimerManager::StartTimers(const String& name) -{ - if (timers_.IsEmpty()) - return; - - for (auto& timer : timers_) - { - if (timer->IsName(name)) - { - timer->Start(); - } - } -} - -void TimerManager::RemoveTimers(const String& name) -{ - if (timers_.IsEmpty()) - return; - - for (auto& timer : timers_) - { - if (timer->IsName(name)) - { - timer->Remove(); - } - } -} - -void TimerManager::StopAllTimers() -{ - if (timers_.IsEmpty()) - return; - - for (auto& timer : timers_) - { - timer->Stop(); - } -} - -void TimerManager::StartAllTimers() -{ - if (timers_.IsEmpty()) - return; - - for (auto& timer : timers_) - { - timer->Start(); - } -} - -void TimerManager::RemoveAllTimers() -{ - timers_.Clear(); -} - -const TimerList& TimerManager::GetAllTimers() const -{ - return timers_; -} -} // namespace kiwano diff --git a/src/kiwano/kiwano.h b/src/kiwano/kiwano.h index f63b0ea0..42708f53 100644 --- a/src/kiwano/kiwano.h +++ b/src/kiwano/kiwano.h @@ -52,8 +52,8 @@ #include #include #include -#include -#include +#include +#include #include #include #include diff --git a/src/kiwano/platform/Runner.h b/src/kiwano/platform/Runner.h index a156b8a9..c21801a9 100644 --- a/src/kiwano/platform/Runner.h +++ b/src/kiwano/platform/Runner.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include #include namespace kiwano From fed74ddb0afe6dba935a16028eae7691073346bc Mon Sep 17 00:00:00 2001 From: Nomango Date: Tue, 19 May 2020 21:42:06 +0800 Subject: [PATCH 19/37] add Timer --- projects/kiwano/kiwano.vcxproj | 2 + projects/kiwano/kiwano.vcxproj.filters | 6 ++ src/kiwano/core/Timer.cpp | 104 +++++++++++++++++++++++++ src/kiwano/core/Timer.h | 60 ++++++++++++++ 4 files changed, 172 insertions(+) create mode 100644 src/kiwano/core/Timer.cpp create mode 100644 src/kiwano/core/Timer.h diff --git a/projects/kiwano/kiwano.vcxproj b/projects/kiwano/kiwano.vcxproj index c6948709..b356af76 100644 --- a/projects/kiwano/kiwano.vcxproj +++ b/projects/kiwano/kiwano.vcxproj @@ -32,6 +32,7 @@ + @@ -141,6 +142,7 @@ + diff --git a/projects/kiwano/kiwano.vcxproj.filters b/projects/kiwano/kiwano.vcxproj.filters index 75592486..7cb988ec 100644 --- a/projects/kiwano/kiwano.vcxproj.filters +++ b/projects/kiwano/kiwano.vcxproj.filters @@ -327,6 +327,9 @@ core + + core + @@ -539,6 +542,9 @@ core + + core + diff --git a/src/kiwano/core/Timer.cpp b/src/kiwano/core/Timer.cpp new file mode 100644 index 00000000..e86894a7 --- /dev/null +++ b/src/kiwano/core/Timer.cpp @@ -0,0 +1,104 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#include + +namespace kiwano +{ + +Timer::Timer() + : is_stopped_(false) +{ +} + +Timer::~Timer() {} + +Duration Timer::GetDeltaTime() const +{ + return delta_time_; +} + +Duration Timer::GetTotalTime() const +{ + if (is_stopped_) + return paused_time_ - start_time_ - total_idle_time_; + return current_time_ - start_time_ - total_idle_time_; +} + +void Timer::Start() +{ + if (is_stopped_) + { + const auto now = Time::Now(); + + // add the duration of the pause to the total idle time + total_idle_time_ += (now - paused_time_); + + // set the previous time to the current time + previous_time_ = now; + + paused_time_ = Time(); + is_stopped_ = false; + } +} + +void Timer::Stop() +{ + if (!is_stopped_) + { + const auto now = Time::Now(); + + paused_time_ = now; + is_stopped_ = true; + } +} + +void Timer::Tick() +{ + if (is_stopped_) + { + delta_time_ = 0; + return; + } + + current_time_ = Time::Now(); + + // compute the time elapsed since the previous frame + delta_time_ = (current_time_ - previous_time_); + + // set previous time to current time, as in the next tick, this frame will be the previous frame + previous_time_ = current_time_; + + // delta time can be negative if the processor goes idle for example + if (delta_time_ < 0) + delta_time_ = 0; +} + +void Timer::Reset() +{ + const auto now = Time::Now(); + + start_time_ = now; + previous_time_ = now; + paused_time_ = Time(); + is_stopped_ = false; +} + +} // namespace kiwano diff --git a/src/kiwano/core/Timer.h b/src/kiwano/core/Timer.h new file mode 100644 index 00000000..e3b3e2a0 --- /dev/null +++ b/src/kiwano/core/Timer.h @@ -0,0 +1,60 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#pragma once +#include +#include + +namespace kiwano +{ + +KGE_DECLARE_SMART_PTR(Timer); + +class Timer + : public ObjectBase +{ +public: + Timer(); + + virtual ~Timer(); + + Duration GetDeltaTime() const; + + Duration GetTotalTime() const; + + void Start(); + + void Stop(); + + void Tick(); + + void Reset(); + +private: + bool is_stopped_; + Time start_time_; + Time paused_time_; + Time current_time_; + Time previous_time_; + Duration delta_time_; + Duration total_idle_time_; +}; + +} // namespace kiwano From 1805c016f8e7c5627c46bf3db2a22a326dff4839 Mon Sep 17 00:00:00 2001 From: Nomango Date: Wed, 20 May 2020 00:47:46 +0800 Subject: [PATCH 20/37] add Ticker & EventTicker --- projects/kiwano/kiwano.vcxproj | 4 + projects/kiwano/kiwano.vcxproj.filters | 12 ++ src/kiwano/core/EventTicker.cpp | 57 +++++++++ src/kiwano/core/EventTicker.h | 69 +++++++++++ src/kiwano/core/Task.cpp | 55 +++++---- src/kiwano/core/Task.h | 80 +++++-------- src/kiwano/core/TaskManager.cpp | 11 -- src/kiwano/core/TaskManager.h | 15 --- src/kiwano/core/Ticker.cpp | 100 ++++++++++++++++ src/kiwano/core/Ticker.h | 156 +++++++++++++++++++++++++ src/kiwano/core/Timer.cpp | 75 +++++++----- src/kiwano/core/Timer.h | 32 ++++- src/kiwano/kiwano.h | 3 + 13 files changed, 531 insertions(+), 138 deletions(-) create mode 100644 src/kiwano/core/EventTicker.cpp create mode 100644 src/kiwano/core/EventTicker.h create mode 100644 src/kiwano/core/Ticker.cpp create mode 100644 src/kiwano/core/Ticker.h diff --git a/projects/kiwano/kiwano.vcxproj b/projects/kiwano/kiwano.vcxproj index b356af76..6c148289 100644 --- a/projects/kiwano/kiwano.vcxproj +++ b/projects/kiwano/kiwano.vcxproj @@ -17,6 +17,7 @@ + @@ -31,6 +32,7 @@ + @@ -124,6 +126,7 @@ + @@ -139,6 +142,7 @@ + diff --git a/projects/kiwano/kiwano.vcxproj.filters b/projects/kiwano/kiwano.vcxproj.filters index 7cb988ec..3bbe6b4a 100644 --- a/projects/kiwano/kiwano.vcxproj.filters +++ b/projects/kiwano/kiwano.vcxproj.filters @@ -330,6 +330,12 @@ core + + core + + + core + @@ -545,6 +551,12 @@ core + + core + + + core + diff --git a/src/kiwano/core/EventTicker.cpp b/src/kiwano/core/EventTicker.cpp new file mode 100644 index 00000000..b0872b41 --- /dev/null +++ b/src/kiwano/core/EventTicker.cpp @@ -0,0 +1,57 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#include + +namespace kiwano +{ + +TickEvent::TickEvent() + : Event(KGE_EVENT(TickEvent)) + , ticker_(nullptr) +{ +} + +EventTickerPtr EventTicker::Create(Duration interval, int times) +{ + EventTickerPtr ptr = memory::New(); + if (ptr) + { + ptr->SetInterval(interval); + ptr->SetTotalTickTimes(times); + } + return ptr; +} + +bool EventTicker::Tick(Duration dt) +{ + if (Ticker::Tick(dt)) + { + TickEventPtr evt = new TickEvent; + evt->delta_time_ = GetDeltaTime(); + evt->ticker_ = this; + DispatchEvent(evt.Get()); + + return true; + } + return false; +} + +} // namespace kiwano diff --git a/src/kiwano/core/EventTicker.h b/src/kiwano/core/EventTicker.h new file mode 100644 index 00000000..1f070edb --- /dev/null +++ b/src/kiwano/core/EventTicker.h @@ -0,0 +1,69 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#pragma once +#include +#include +#include + +namespace kiwano +{ + +KGE_DECLARE_SMART_PTR(TickEvent); +KGE_DECLARE_SMART_PTR(EventTicker); + +/** + * \addtogroup Events + * @{ + */ + +/// \~chinese +/// @brief 报时时间 +class KGE_API TickEvent : public Event +{ +public: + TickEvent(); + + EventTicker* ticker_; + Duration delta_time_; +}; + +/** + * @} + */ + + +/// \~chinese +/// @brief 事件报时器 +class KGE_API EventTicker + : public Ticker + , public EventDispatcher +{ +public: + /// \~chinese + /// @brief 创建事件报时器 + /// @param interval 报时间隔 + /// @param times 报时次数(设 -1 为永久) + static EventTickerPtr Create(Duration interval, int times = -1); + + bool Tick(Duration dt) override; +}; + +} // namespace kiwano diff --git a/src/kiwano/core/Task.cpp b/src/kiwano/core/Task.cpp index cea275b6..430c6094 100644 --- a/src/kiwano/core/Task.cpp +++ b/src/kiwano/core/Task.cpp @@ -22,75 +22,74 @@ namespace kiwano { - -TaskPtr Task::Create(const Callback& cb, Duration interval, int times) +TaskPtr Task::Create(const Callback& cb, TickerPtr ticker) { TaskPtr ptr = memory::New(); if (ptr) { ptr->SetCallback(cb); - ptr->SetInterval(interval); - ptr->SetTotalRunTimes(times); + ptr->SetTicker(ticker); } return ptr; } -TaskPtr Task::Create(const String& name, const Callback& cb, Duration interval, int times) +TaskPtr Task::Create(const String& name, const Callback& cb, TickerPtr ticker) { - TaskPtr ptr = memory::New(); + TaskPtr ptr = Task::Create(cb, ticker); if (ptr) { ptr->SetName(name); - ptr->SetCallback(cb); - ptr->SetInterval(interval); - ptr->SetTotalRunTimes(times); } return ptr; } +TaskPtr Task::Create(const Callback& cb, Duration interval, int times) +{ + TickerPtr ticker = Ticker::Create(interval, times); + return Task::Create(cb, ticker); +} + +TaskPtr Task::Create(const String& name, const Callback& cb, Duration interval, int times) +{ + TickerPtr ticker = Ticker::Create(interval, times); + return Task::Create(name, cb, ticker); +} + Task::Task() : running_(true) , removeable_(false) - , run_times_(0) - , total_times_(0) - , interval_(0) - , elapsed_(0) , callback_() { } void Task::Update(Duration dt) { - if (total_times_ == 0) + if (!ticker_) { Remove(); return; } - if (IsRunning()) + if (ticker_->GetTotalTickTimes() == 0) { - if (!interval_.IsZero()) - { - elapsed_ += dt; - if (elapsed_ < interval_) - return; - } + Remove(); + return; + } + if (ticker_->Tick(dt)) + { if (callback_) - callback_(this, elapsed_); + callback_(this, ticker_->GetDeltaTime()); - ++run_times_; - elapsed_ = 0; - - if (run_times_ == total_times_) + if (ticker_->GetTickedTimes() == ticker_->GetTotalTickTimes()) Remove(); } } void Task::Reset() { - elapsed_ = 0; - run_times_ = 0; + if (ticker_) + ticker_->Reset(); } } // namespace kiwano diff --git a/src/kiwano/core/Task.h b/src/kiwano/core/Task.h index 8d31ad41..9297d707 100644 --- a/src/kiwano/core/Task.h +++ b/src/kiwano/core/Task.h @@ -19,8 +19,7 @@ // THE SOFTWARE. #pragma once -#include -#include +#include #include namespace kiwano @@ -47,9 +46,22 @@ public: /// \~chinese /// @brief 任务回调函数 /// @details - /// 回调函数第一个参数是任务自身,第二个参数是距离上次执行任务的时间间隔 + /// 回调函数第一个参数是任务自身,第二个参数是时间增量 using Callback = Function; + /// \~chinese + /// @brief 创建任务 + /// @param cb 回调函数 + /// @param 报时器 + static TaskPtr Create(const Callback& cb, TickerPtr ticker); + + /// \~chinese + /// @brief 创建任务 + /// @param name 名称 + /// @param cb 回调函数 + /// @param 报时器 + static TaskPtr Create(const String& name, const Callback& cb, TickerPtr ticker); + /// \~chinese /// @brief 创建任务 /// @param cb 回调函数 @@ -89,26 +101,6 @@ public: /// @brief 任务是否可移除 bool IsRemoveable() const; - /// \~chinese - /// @brief 获取任务执行过回调函数的次数 - int GetRunTimes() const; - - /// \~chinese - /// @brief 获取任务执行回调函数的总次数 - int GetTotalRunTimes() const; - - /// \~chinese - /// @brief 设置任务执行回调函数的总次数 - void SetTotalRunTimes(int times); - - /// \~chinese - /// @brief 获取任务执行时间间隔 - Duration GetInterval() const; - - /// \~chinese - /// @brief 设置任务执行时间间隔 - void SetInterval(Duration interval); - /// \~chinese /// @brief 获取任务回调函数 Callback GetCallback() const; @@ -117,6 +109,14 @@ public: /// @brief 设置任务回调函数 void SetCallback(const Callback& callback); + /// \~chinese + /// @brief 获取任务的报时器 + TickerPtr GetTicker() const; + + /// \~chinese + /// @brief 设置任务的报时器 + void SetTicker(TickerPtr ticker); + private: /// \~chinese /// @brief 更新任务 @@ -127,13 +127,10 @@ private: void Reset(); private: - bool running_; - bool removeable_; - int run_times_; - int total_times_; - Duration interval_; - Duration elapsed_; - Callback callback_; + bool running_; + bool removeable_; + TickerPtr ticker_; + Callback callback_; }; inline void Task::Start() @@ -161,29 +158,14 @@ inline bool Task::IsRemoveable() const return removeable_; } -inline int Task::GetRunTimes() const +inline TickerPtr Task::GetTicker() const { - return run_times_; + return ticker_; } -inline int Task::GetTotalRunTimes() const +inline void Task::SetTicker(TickerPtr ticker) { - return total_times_; -} - -inline void Task::SetTotalRunTimes(int times) -{ - total_times_ = times; -} - -inline Duration Task::GetInterval() const -{ - return interval_; -} - -inline void Task::SetInterval(Duration interval) -{ - interval_ = interval; + ticker_ = ticker; } inline Task::Callback Task::GetCallback() const diff --git a/src/kiwano/core/TaskManager.cpp b/src/kiwano/core/TaskManager.cpp index ae556aa0..740ef94a 100644 --- a/src/kiwano/core/TaskManager.cpp +++ b/src/kiwano/core/TaskManager.cpp @@ -40,17 +40,6 @@ void TaskManager::UpdateTasks(Duration dt) } } -Task* TaskManager::AddTask(const Task::Callback& cb, Duration interval, int times) -{ - return AddTask(String(), cb, interval, times); -} - -Task* TaskManager::AddTask(const String& name, const Task::Callback& cb, Duration interval, int times) -{ - TaskPtr task = Task::Create(name, cb, interval, times); - return AddTask(task); -} - Task* TaskManager::AddTask(TaskPtr task) { KGE_ASSERT(task && "AddTask failed, NULL pointer exception"); diff --git a/src/kiwano/core/TaskManager.h b/src/kiwano/core/TaskManager.h index 7cc8e495..d71d975b 100644 --- a/src/kiwano/core/TaskManager.h +++ b/src/kiwano/core/TaskManager.h @@ -30,21 +30,6 @@ namespace kiwano class KGE_API TaskManager { public: - /// \~chinese - /// @brief 添加任务 - /// @param cb 回调函数 - /// @param interval 时间间隔 - /// @param times 执行次数(设 -1 为永久执行) - Task* AddTask(const Task::Callback& cb, Duration interval, int times = -1); - - /// \~chinese - /// @brief 添加任务 - /// @param name 任务名称 - /// @param cb 回调函数 - /// @param interval 时间间隔 - /// @param times 执行次数(设 -1 为永久执行) - Task* AddTask(const String& name, const Task::Callback& cb, Duration interval, int times = -1); - /// \~chinese /// @brief 添加任务 Task* AddTask(TaskPtr task); diff --git a/src/kiwano/core/Ticker.cpp b/src/kiwano/core/Ticker.cpp new file mode 100644 index 00000000..4d3ac55b --- /dev/null +++ b/src/kiwano/core/Ticker.cpp @@ -0,0 +1,100 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#include + +namespace kiwano +{ + +TickerPtr Ticker::Create(Duration interval, int times) +{ + TickerPtr ptr = memory::New(); + if (ptr) + { + ptr->SetInterval(interval); + ptr->SetTotalTickTimes(times); + } + return ptr; +} + +Ticker::Ticker() + : ticked_times_(0) + , total_times_(0) +{ +} + +bool Ticker::Tick() +{ + if (!timer_) + timer_ = Timer::Create(); + + if (timer_->IsPausing()) + return false; + + timer_->Tick(); + + return this->Tick(timer_->GetDeltaTime()); +} + +bool Ticker::Tick(Duration dt) +{ + if (ticked_times_ == total_times_) + return false; + + elapsed_time_ += dt; + + if (elapsed_time_ + error_time_ > interval_) + { + delta_time_ = elapsed_time_; + error_time_ = (elapsed_time_ + error_time_) - interval_; + elapsed_time_ = 0; + ++ticked_times_; + return true; + } + return false; +} + +Duration Ticker::GetDeltaTime() +{ + return delta_time_; +} + +TimerPtr Ticker::GetTimer() +{ + return timer_; +} + +void Ticker::SetTimer(TimerPtr timer) +{ + timer_ = timer; +} + +void Ticker::Reset() +{ + if (timer_) + timer_->Reset(); + + elapsed_time_ = 0; + delta_time_ = 0; + error_time_ = 0; + ticked_times_ = 0; +} + +} // namespace kiwano diff --git a/src/kiwano/core/Ticker.h b/src/kiwano/core/Ticker.h new file mode 100644 index 00000000..1b7986f8 --- /dev/null +++ b/src/kiwano/core/Ticker.h @@ -0,0 +1,156 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#pragma once +#include + +namespace kiwano +{ + +KGE_DECLARE_SMART_PTR(Ticker); + +/// \~chinese +/// @brief 报时器 +class KGE_API Ticker + : public ObjectBase +{ +public: + /// \~chinese + /// @brief 创建报时器 + /// @param interval 报时间隔 + /// @param times 报时次数(设 -1 为永久) + static TickerPtr Create(Duration interval, int times = -1); + + Ticker(); + + /// \~chinese + /// @brief 计时 + /// @return 是否达到报时时长 + virtual bool Tick(); + + /// \~chinese + /// @brief 计时 + /// @param dt 时间增量 + /// @return 是否达到报时时长 + virtual bool Tick(Duration dt); + + /// \~chinese + /// @brief 获取时间增量 + Duration GetDeltaTime(); + + /// \~chinese + /// @brief 获取暂停状态 + bool IsPausing() const; + + /// \~chinese + /// @brief 暂停报时器 + void Pause(); + + /// \~chinese + /// @brief 继续报时器 + void Resume(); + + /// \~chinese + /// @brief 获取报时器报时次数 + int GetTickedTimes() const; + + /// \~chinese + /// @brief 获取报时器总报时次数 + int GetTotalTickTimes() const; + + /// \~chinese + /// @brief 设置报时器总报时次数 + void SetTotalTickTimes(int times); + + /// \~chinese + /// @brief 获取报时间隔 + Duration GetInterval() const; + + /// \~chinese + /// @brief 设置报时间隔 + void SetInterval(Duration interval); + + /// \~chinese + /// @brief 获取计时器 + TimerPtr GetTimer(); + + /// \~chinese + /// @brief 设置计时器 + void SetTimer(TimerPtr timer); + + /// \~chinese + /// @brief 重置报时器 + void Reset(); + +private: + int ticked_times_; + int total_times_; + Duration interval_; + Duration elapsed_time_; + Duration delta_time_; + Duration error_time_; + TimerPtr timer_; +}; + +inline void Ticker::Pause() +{ + KGE_ASSERT(timer_); + timer_->Pause(); +} + +inline void Ticker::Resume() +{ + KGE_ASSERT(timer_); + timer_->Resume(); +} + +inline bool Ticker::IsPausing() const +{ + if (timer_) + return timer_->IsPausing(); + return true; +} + +inline int Ticker::GetTickedTimes() const +{ + return ticked_times_; +} + +inline int Ticker::GetTotalTickTimes() const +{ + return total_times_; +} + +inline void Ticker::SetTotalTickTimes(int times) +{ + total_times_ = times; +} + +inline Duration Ticker::GetInterval() const +{ + return interval_; +} + +inline void Ticker::SetInterval(Duration interval) +{ + interval_ = interval; +} + +} // namespace kiwano diff --git a/src/kiwano/core/Timer.cpp b/src/kiwano/core/Timer.cpp index e86894a7..aec2bb48 100644 --- a/src/kiwano/core/Timer.cpp +++ b/src/kiwano/core/Timer.cpp @@ -19,13 +19,21 @@ // THE SOFTWARE. #include +#include namespace kiwano { -Timer::Timer() - : is_stopped_(false) +TimerPtr Timer::Create() { + TimerPtr ptr = memory::New(); + return ptr; +} + +Timer::Timer() + : is_paused_(false) +{ + Reset(); } Timer::~Timer() {} @@ -37,42 +45,19 @@ Duration Timer::GetDeltaTime() const Duration Timer::GetTotalTime() const { - if (is_stopped_) + if (is_paused_) return paused_time_ - start_time_ - total_idle_time_; return current_time_ - start_time_ - total_idle_time_; } -void Timer::Start() +bool Timer::IsPausing() const { - if (is_stopped_) - { - const auto now = Time::Now(); - - // add the duration of the pause to the total idle time - total_idle_time_ += (now - paused_time_); - - // set the previous time to the current time - previous_time_ = now; - - paused_time_ = Time(); - is_stopped_ = false; - } -} - -void Timer::Stop() -{ - if (!is_stopped_) - { - const auto now = Time::Now(); - - paused_time_ = now; - is_stopped_ = true; - } + return is_paused_; } void Timer::Tick() { - if (is_stopped_) + if (is_paused_) { delta_time_ = 0; return; @@ -91,14 +76,44 @@ void Timer::Tick() delta_time_ = 0; } +void Timer::Resume() +{ + if (is_paused_) + { + const auto now = Time::Now(); + + // add the duration of the pause to the total idle time + total_idle_time_ += (now - paused_time_); + + // set the previous time to the current time + previous_time_ = now; + + paused_time_ = Time(); + is_paused_ = false; + } +} + +void Timer::Pause() +{ + if (!is_paused_) + { + const auto now = Time::Now(); + + paused_time_ = now; + is_paused_ = true; + } +} + void Timer::Reset() { const auto now = Time::Now(); start_time_ = now; + current_time_ = now; previous_time_ = now; paused_time_ = Time(); - is_stopped_ = false; + delta_time_ = 0; + is_paused_ = false; } } // namespace kiwano diff --git a/src/kiwano/core/Timer.h b/src/kiwano/core/Timer.h index e3b3e2a0..29cb6a1a 100644 --- a/src/kiwano/core/Timer.h +++ b/src/kiwano/core/Timer.h @@ -27,28 +27,50 @@ namespace kiwano KGE_DECLARE_SMART_PTR(Timer); -class Timer +/// \~chinese +/// @brief 计时器 +class KGE_API Timer : public ObjectBase { public: + /// \~chinese + /// @brief 创建计时器 + static TimerPtr Create(); + Timer(); virtual ~Timer(); + /// \~chinese + /// @brief 获取时间增量 Duration GetDeltaTime() const; + /// \~chinese + /// @brief 获取总时长 Duration GetTotalTime() const; - void Start(); - - void Stop(); + /// \~chinese + /// @brief 获取暂停状态 + bool IsPausing() const; + /// \~chinese + /// @brief 计时 void Tick(); + /// \~chinese + /// @brief 继续计时 + void Resume(); + + /// \~chinese + /// @brief 暂停计时 + void Pause(); + + /// \~chinese + /// @brief 重置计时器 void Reset(); private: - bool is_stopped_; + bool is_paused_; Time start_time_; Time paused_time_; Time current_time_; diff --git a/src/kiwano/kiwano.h b/src/kiwano/kiwano.h index 42708f53..92aa77fd 100644 --- a/src/kiwano/kiwano.h +++ b/src/kiwano/kiwano.h @@ -52,6 +52,9 @@ #include #include #include +#include +#include +#include #include #include #include From 86bb0e4239215eeb0f809516981f3d888b90fa9c Mon Sep 17 00:00:00 2001 From: Nomango Date: Wed, 20 May 2020 00:55:51 +0800 Subject: [PATCH 21/37] use application scoped timer --- src/kiwano/platform/Application.cpp | 10 ++++------ src/kiwano/platform/Application.h | 25 ++++++++++++------------ src/kiwano/platform/win32/WindowImpl.cpp | 14 ++++++++++++- 3 files changed, 30 insertions(+), 19 deletions(-) diff --git a/src/kiwano/platform/Application.cpp b/src/kiwano/platform/Application.cpp index 3c17a16f..5222fe11 100644 --- a/src/kiwano/platform/Application.cpp +++ b/src/kiwano/platform/Application.cpp @@ -68,15 +68,13 @@ void Application::Run(RunnerPtr runner, bool debug) // Everything is ready runner->OnReady(); - running_ = true; - last_update_time_ = Time::Now(); + running_ = true; + timer_ = Timer::Create(); while (running_) { - const Time now = Time::Now(); - const Duration dt = (now - last_update_time_); - last_update_time_ = now; + timer_->Tick(); - if (!runner->MainLoop(dt)) + if (!runner->MainLoop(timer_->GetDeltaTime())) running_ = false; } diff --git a/src/kiwano/platform/Application.h b/src/kiwano/platform/Application.h index e64d3e5a..6fe77c3c 100644 --- a/src/kiwano/platform/Application.h +++ b/src/kiwano/platform/Application.h @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -77,6 +78,12 @@ public: */ WindowPtr GetMainWindow() const; + /** + * \~chinese + * @brief 获取计时器 + */ + TimerPtr GetTimer() const; + /** * \~chinese * @brief 是否正在运行 @@ -142,17 +149,11 @@ public: */ void Destroy(); - /** - * \~chinese - * @brief 获取上一次更新时间 - */ - Time GetLastUpdateTime() const; - private: bool running_; float time_scale_; RunnerPtr runner_; - Time last_update_time_; + TimerPtr timer_; List modules_; std::mutex perform_mutex_; Queue> functions_to_perform_; @@ -169,14 +170,14 @@ inline WindowPtr Application::GetMainWindow() const return runner_->GetMainWindow(); } +inline TimerPtr Application::GetTimer() const +{ + return timer_; +} + inline bool Application::IsRunning() const { return running_; } -inline Time Application::GetLastUpdateTime() const -{ - return last_update_time_; -} - } // namespace kiwano diff --git a/src/kiwano/platform/win32/WindowImpl.cpp b/src/kiwano/platform/win32/WindowImpl.cpp index 3c8f5322..38da0b70 100644 --- a/src/kiwano/platform/win32/WindowImpl.cpp +++ b/src/kiwano/platform/win32/WindowImpl.cpp @@ -502,9 +502,21 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA case WM_ACTIVATE: { + bool active = (LOWORD(wparam) != WA_INACTIVE); + WindowFocusChangedEventPtr evt = new WindowFocusChangedEvent; - evt->focus = (LOWORD(wparam) != WA_INACTIVE); + evt->focus = active; this->PushEvent(evt); + + // Pause game when window is inactive + TimerPtr timer = Application::GetInstance().GetTimer(); + if (timer) + { + if (active) + timer->Resume(); + else + timer->Pause(); + } } break; From 01ce68accb577b3d56c6d87359096e0316f21db3 Mon Sep 17 00:00:00 2001 From: Nomango Date: Wed, 20 May 2020 10:16:54 +0800 Subject: [PATCH 22/37] update Ticker --- src/kiwano/core/Ticker.cpp | 7 +++++++ src/kiwano/core/Ticker.h | 11 ++++------- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/kiwano/core/Ticker.cpp b/src/kiwano/core/Ticker.cpp index 4d3ac55b..b3884cd8 100644 --- a/src/kiwano/core/Ticker.cpp +++ b/src/kiwano/core/Ticker.cpp @@ -37,11 +37,15 @@ TickerPtr Ticker::Create(Duration interval, int times) Ticker::Ticker() : ticked_times_(0) , total_times_(0) + , is_paused_(false) { } bool Ticker::Tick() { + if (is_paused_) + return false; + if (!timer_) timer_ = Timer::Create(); @@ -55,6 +59,9 @@ bool Ticker::Tick() bool Ticker::Tick(Duration dt) { + if (is_paused_) + return false; + if (ticked_times_ == total_times_) return false; diff --git a/src/kiwano/core/Ticker.h b/src/kiwano/core/Ticker.h index 1b7986f8..a4663769 100644 --- a/src/kiwano/core/Ticker.h +++ b/src/kiwano/core/Ticker.h @@ -100,6 +100,7 @@ public: void Reset(); private: + bool is_paused_; int ticked_times_; int total_times_; Duration interval_; @@ -111,21 +112,17 @@ private: inline void Ticker::Pause() { - KGE_ASSERT(timer_); - timer_->Pause(); + is_paused_ = true; } inline void Ticker::Resume() { - KGE_ASSERT(timer_); - timer_->Resume(); + is_paused_ = false; } inline bool Ticker::IsPausing() const { - if (timer_) - return timer_->IsPausing(); - return true; + return is_paused_; } inline int Ticker::GetTickedTimes() const From 1de59e3a159f2754dcc6843717e4624d3b4a7c63 Mon Sep 17 00:00:00 2001 From: Nomango Date: Wed, 20 May 2020 11:55:53 +0800 Subject: [PATCH 23/37] add Window::SetMinimumSize() --- src/kiwano/platform/Window.cpp | 2 + src/kiwano/platform/Window.h | 10 ++ src/kiwano/platform/win32/WindowImpl.cpp | 116 +++++++++++++++++++---- 3 files changed, 110 insertions(+), 18 deletions(-) diff --git a/src/kiwano/platform/Window.cpp b/src/kiwano/platform/Window.cpp index e132567a..1fdd40d7 100644 --- a/src/kiwano/platform/Window.cpp +++ b/src/kiwano/platform/Window.cpp @@ -29,6 +29,8 @@ Window::Window() , is_fullscreen_(false) , width_(0) , height_(0) + , min_width_(100) + , min_height_(50) { } diff --git a/src/kiwano/platform/Window.h b/src/kiwano/platform/Window.h index be450e37..a982bfaa 100644 --- a/src/kiwano/platform/Window.h +++ b/src/kiwano/platform/Window.h @@ -128,6 +128,14 @@ public: */ virtual void Resize(uint32_t width, uint32_t height) = 0; + /** + * \~chinese + * @brief 设置窗口最小大小 + * @param width 最小窗口宽度 + * @param height 最小窗口高度 + */ + virtual void SetMinimumSize(uint32_t width, uint32_t height) = 0; + /** * \~chinese * @brief 设置鼠标指针类型 @@ -183,6 +191,8 @@ protected: bool is_fullscreen_; uint32_t width_; uint32_t height_; + uint32_t min_width_; + uint32_t min_height_; WindowHandle handle_; String title_; std::queue event_queue_; diff --git a/src/kiwano/platform/win32/WindowImpl.cpp b/src/kiwano/platform/win32/WindowImpl.cpp index 38da0b70..ffe85838 100644 --- a/src/kiwano/platform/win32/WindowImpl.cpp +++ b/src/kiwano/platform/win32/WindowImpl.cpp @@ -56,6 +56,8 @@ public: void Resize(uint32_t width, uint32_t height) override; + void SetMinimumSize(uint32_t width, uint32_t height) override; + void SetCursor(CursorType cursor) override; void PumpEvents() override; @@ -70,6 +72,8 @@ public: private: bool resizable_; + bool is_resizing_; + bool is_minimized_; CursorType mouse_cursor_; String device_name_; @@ -133,6 +137,8 @@ void AdjustWindow(uint32_t width, uint32_t height, DWORD style, uint32_t* win_wi WindowWin32Impl::WindowWin32Impl() : resizable_(false) + , is_resizing_(false) + , is_minimized_(false) , mouse_cursor_(CursorType::Arrow) , key_map_{} { @@ -321,6 +327,12 @@ void WindowWin32Impl::Resize(uint32_t width, uint32_t height) ::SetWindowPos(handle_, 0, left, top, width, height, SWP_NOZORDER | SWP_NOACTIVATE); } +void WindowWin32Impl::SetMinimumSize(uint32_t width, uint32_t height) +{ + min_width_ = width; + min_height_ = height; +} + void WindowWin32Impl::SetCursor(CursorType cursor) { mouse_cursor_ = cursor; @@ -475,22 +487,93 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA if (SIZE_MAXHIDE == wparam || SIZE_MINIMIZED == wparam) { KGE_SYS_LOG("Window minimized"); + + is_minimized_ = true; + // Pause game when window is minimized + if (Application::GetInstance().IsRunning()) + { + TimerPtr timer = Application::GetInstance().GetTimer(); + timer->Pause(); + } } - else + else if (SIZE_MAXIMIZED == wparam) { - KGE_SYS_LOG("Window resized"); + if (is_minimized_) + { + is_minimized_ = false; + if (Application::GetInstance().IsRunning()) + { + TimerPtr timer = Application::GetInstance().GetTimer(); + timer->Pause(); + } + } + } + else if (wparam == SIZE_RESTORED) + { + if (is_minimized_) + { + KGE_SYS_LOG("Window restored"); - this->width_ = ((uint32_t)(short)LOWORD(lparam)); - this->height_ = ((uint32_t)(short)HIWORD(lparam)); + // the window was restored and was previously minimized + is_minimized_ = false; + if (Application::GetInstance().IsRunning()) + { + TimerPtr timer = Application::GetInstance().GetTimer(); + timer->Pause(); + } + } + else if (is_resizing_) + { + // DO NOTHING until the dragging / resizing has stopped. + } + else + { + KGE_SYS_LOG("Window resized"); - WindowResizedEventPtr evt = new WindowResizedEvent; - evt->width = this->GetWidth(); - evt->height = this->GetHeight(); - this->PushEvent(evt); + this->width_ = ((uint32_t)(short)LOWORD(lparam)); + this->height_ = ((uint32_t)(short)HIWORD(lparam)); + + WindowResizedEventPtr evt = new WindowResizedEvent; + evt->width = this->GetWidth(); + evt->height = this->GetHeight(); + this->PushEvent(evt); + } } } break; + case WM_ENTERSIZEMOVE: + { + is_resizing_ = true; + if (Application::GetInstance().IsRunning()) + { + TimerPtr timer = Application::GetInstance().GetTimer(); + timer->Pause(); + } + return 0; + } + break; + + case WM_EXITSIZEMOVE: + { + is_resizing_ = false; + if (Application::GetInstance().IsRunning()) + { + TimerPtr timer = Application::GetInstance().GetTimer(); + timer->Resume(); + } + return 0; + } + break; + + case WM_GETMINMAXINFO: + { + // prevent the window from becoming too small + ((MINMAXINFO*)lparam)->ptMinTrackSize.x = LONG(min_width_); + ((MINMAXINFO*)lparam)->ptMinTrackSize.y = LONG(min_height_); + } + return 0; + case WM_MOVE: { WindowMovedEventPtr evt = new WindowMovedEvent; @@ -500,6 +583,13 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA } break; + case WM_MENUCHAR: + { + // Disables the crazy beeping sound when pressing a mnemonic key. + // Simply tell Windows that we want the menu closed. + return MAKELRESULT(0, MNC_CLOSE); + } + case WM_ACTIVATE: { bool active = (LOWORD(wparam) != WA_INACTIVE); @@ -507,16 +597,6 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA WindowFocusChangedEventPtr evt = new WindowFocusChangedEvent; evt->focus = active; this->PushEvent(evt); - - // Pause game when window is inactive - TimerPtr timer = Application::GetInstance().GetTimer(); - if (timer) - { - if (active) - timer->Resume(); - else - timer->Pause(); - } } break; From e1ec4f76b7ddc78ed3c1fc05e76690768aa12265 Mon Sep 17 00:00:00 2001 From: Nomango Date: Wed, 20 May 2020 23:38:24 +0800 Subject: [PATCH 24/37] minor fixes --- src/kiwano/platform/Application.cpp | 4 +- src/kiwano/platform/Window.cpp | 6 ++- src/kiwano/platform/Window.h | 10 ++++ src/kiwano/platform/win32/WindowImpl.cpp | 63 ++++++++++++++++++------ 4 files changed, 63 insertions(+), 20 deletions(-) diff --git a/src/kiwano/platform/Application.cpp b/src/kiwano/platform/Application.cpp index 5222fe11..b3f0c3c2 100644 --- a/src/kiwano/platform/Application.cpp +++ b/src/kiwano/platform/Application.cpp @@ -52,6 +52,8 @@ void Application::Run(RunnerPtr runner, bool debug) { KGE_ASSERT(runner); runner_ = runner; + timer_ = Timer::Create(); + running_ = true; // Setup all modules for (auto c : modules_) @@ -68,8 +70,6 @@ void Application::Run(RunnerPtr runner, bool debug) // Everything is ready runner->OnReady(); - running_ = true; - timer_ = Timer::Create(); while (running_) { timer_->Tick(); diff --git a/src/kiwano/platform/Window.cpp b/src/kiwano/platform/Window.cpp index 1fdd40d7..7bff692b 100644 --- a/src/kiwano/platform/Window.cpp +++ b/src/kiwano/platform/Window.cpp @@ -29,8 +29,10 @@ Window::Window() , is_fullscreen_(false) , width_(0) , height_(0) - , min_width_(100) - , min_height_(50) + , min_width_(0) + , min_height_(0) + , max_width_(0) + , max_height_(0) { } diff --git a/src/kiwano/platform/Window.h b/src/kiwano/platform/Window.h index a982bfaa..63dbb122 100644 --- a/src/kiwano/platform/Window.h +++ b/src/kiwano/platform/Window.h @@ -136,6 +136,14 @@ public: */ virtual void SetMinimumSize(uint32_t width, uint32_t height) = 0; + /** + * \~chinese + * @brief 设置窗口最大大小 + * @param width 最大窗口宽度 + * @param height 最大窗口高度 + */ + virtual void SetMaximumSize(uint32_t width, uint32_t height) = 0; + /** * \~chinese * @brief 设置鼠标指针类型 @@ -193,6 +201,8 @@ protected: uint32_t height_; uint32_t min_width_; uint32_t min_height_; + uint32_t max_width_; + uint32_t max_height_; WindowHandle handle_; String title_; std::queue event_queue_; diff --git a/src/kiwano/platform/win32/WindowImpl.cpp b/src/kiwano/platform/win32/WindowImpl.cpp index ffe85838..5fc92edf 100644 --- a/src/kiwano/platform/win32/WindowImpl.cpp +++ b/src/kiwano/platform/win32/WindowImpl.cpp @@ -58,6 +58,8 @@ public: void SetMinimumSize(uint32_t width, uint32_t height) override; + void SetMaximumSize(uint32_t width, uint32_t height) override; + void SetCursor(CursorType cursor) override; void PumpEvents() override; @@ -257,8 +259,11 @@ void WindowWin32Impl::Init(const String& title, uint32_t width, uint32_t height, height = win_height; } - handle_ = ::CreateWindowExA(fullscreen ? WS_EX_TOPMOST : 0, "KiwanoAppWnd", title.c_str(), GetStyle(), - left, top, width, height, nullptr, nullptr, hinst, nullptr); + width_ = width; + height_ = height; + resizable_ = resizable; + handle_ = ::CreateWindowExA(fullscreen ? WS_EX_TOPMOST : 0, "KiwanoAppWnd", title.c_str(), GetStyle(), left, top, + width, height, nullptr, nullptr, hinst, nullptr); if (handle_ == nullptr) { @@ -266,10 +271,6 @@ void WindowWin32Impl::Init(const String& title, uint32_t width, uint32_t height, KGE_THROW_SYSTEM_ERROR(HRESULT_FROM_WIN32(GetLastError()), "Create window failed"); } - width_ = width; - height_ = height; - resizable_ = resizable; - // disable imm ::ImmAssociateContext(handle_, nullptr); @@ -333,6 +334,12 @@ void WindowWin32Impl::SetMinimumSize(uint32_t width, uint32_t height) min_height_ = height; } +void WindowWin32Impl::SetMaximumSize(uint32_t width, uint32_t height) +{ + max_width_ = width; + max_height_ = height; +} + void WindowWin32Impl::SetCursor(CursorType cursor) { mouse_cursor_ = cursor; @@ -498,13 +505,15 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA } else if (SIZE_MAXIMIZED == wparam) { + KGE_SYS_LOG("Window maximized"); + if (is_minimized_) { is_minimized_ = false; if (Application::GetInstance().IsRunning()) { TimerPtr timer = Application::GetInstance().GetTimer(); - timer->Pause(); + timer->Resume(); } } } @@ -519,7 +528,7 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA if (Application::GetInstance().IsRunning()) { TimerPtr timer = Application::GetInstance().GetTimer(); - timer->Pause(); + timer->Resume(); } } else if (is_resizing_) @@ -528,8 +537,6 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA } else { - KGE_SYS_LOG("Window resized"); - this->width_ = ((uint32_t)(short)LOWORD(lparam)); this->height_ = ((uint32_t)(short)HIWORD(lparam)); @@ -537,6 +544,8 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA evt->width = this->GetWidth(); evt->height = this->GetHeight(); this->PushEvent(evt); + + KGE_SYS_LOG("Window resized to (%d, %d)", this->width_, this->height_); } } } @@ -552,7 +561,6 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA } return 0; } - break; case WM_EXITSIZEMOVE: { @@ -562,17 +570,40 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA TimerPtr timer = Application::GetInstance().GetTimer(); timer->Resume(); } + + // Send window resized event when client size changed + RECT client_rect = { 0 }; + ::GetClientRect(hwnd, &client_rect); + + uint32_t client_width = uint32_t(client_rect.right - client_rect.left); + uint32_t client_height = uint32_t(client_rect.bottom - client_rect.top); + if (client_width != this->GetWidth() || client_height != this->GetHeight()) + { + KGE_SYS_LOG("Window resized to (%d, %d)", client_width, client_height); + + this->width_ = client_width; + this->height_ = client_height; + + WindowResizedEventPtr evt = new WindowResizedEvent; + evt->width = this->GetWidth(); + evt->height = this->GetHeight(); + this->PushEvent(evt); + } return 0; } - break; case WM_GETMINMAXINFO: { - // prevent the window from becoming too small - ((MINMAXINFO*)lparam)->ptMinTrackSize.x = LONG(min_width_); - ((MINMAXINFO*)lparam)->ptMinTrackSize.y = LONG(min_height_); + if (min_width_ || min_height_) + { + ((MINMAXINFO*)lparam)->ptMinTrackSize = POINT{ LONG(min_width_), LONG(min_height_) }; + } + if (max_width_ || max_height_) + { + ((MINMAXINFO*)lparam)->ptMaxTrackSize = POINT{ LONG(max_width_), LONG(max_height_) }; + } + return 0; } - return 0; case WM_MOVE: { From e68bb9d94d0d85e70c61cad78d1fa33a7906e622 Mon Sep 17 00:00:00 2001 From: Nomango Date: Wed, 20 May 2020 23:48:56 +0800 Subject: [PATCH 25/37] refactor utils --- projects/kiwano/kiwano.vcxproj | 24 +++++----- projects/kiwano/kiwano.vcxproj.filters | 52 +++++++++++----------- src/kiwano-network/HttpRequest.h | 2 +- src/kiwano/2d/Actor.h | 4 +- src/kiwano/core/ObjectBase.cpp | 2 +- src/kiwano/kiwano.h | 10 ++--- src/kiwano/platform/Application.h | 2 +- src/kiwano/{core => utils}/EventTicker.cpp | 2 +- src/kiwano/{core => utils}/EventTicker.h | 2 +- src/kiwano/{core => utils}/Json.h | 0 src/kiwano/utils/ResourceCache.h | 6 +-- src/kiwano/{core => utils}/Task.cpp | 2 +- src/kiwano/{core => utils}/Task.h | 2 +- src/kiwano/{core => utils}/TaskManager.cpp | 2 +- src/kiwano/{core => utils}/TaskManager.h | 2 +- src/kiwano/{core => utils}/Ticker.cpp | 2 +- src/kiwano/{core => utils}/Ticker.h | 2 +- src/kiwano/{core => utils}/Timer.cpp | 2 +- src/kiwano/{core => utils}/Timer.h | 0 src/kiwano/{core => utils}/Xml.h | 0 20 files changed, 60 insertions(+), 60 deletions(-) rename src/kiwano/{core => utils}/EventTicker.cpp (97%) rename src/kiwano/{core => utils}/EventTicker.h (98%) rename src/kiwano/{core => utils}/Json.h (100%) rename src/kiwano/{core => utils}/Task.cpp (98%) rename src/kiwano/{core => utils}/Task.h (99%) rename src/kiwano/{core => utils}/TaskManager.cpp (98%) rename src/kiwano/{core => utils}/TaskManager.h (98%) rename src/kiwano/{core => utils}/Ticker.cpp (98%) rename src/kiwano/{core => utils}/Ticker.h (99%) rename src/kiwano/{core => utils}/Timer.cpp (98%) rename src/kiwano/{core => utils}/Timer.h (100%) rename src/kiwano/{core => utils}/Xml.h (100%) diff --git a/projects/kiwano/kiwano.vcxproj b/projects/kiwano/kiwano.vcxproj index 6c148289..46c98312 100644 --- a/projects/kiwano/kiwano.vcxproj +++ b/projects/kiwano/kiwano.vcxproj @@ -17,7 +17,6 @@ - @@ -26,16 +25,12 @@ - - - - @@ -56,8 +51,6 @@ - - @@ -101,9 +94,16 @@ + + + + + + + @@ -126,7 +126,6 @@ - @@ -142,11 +141,7 @@ - - - - @@ -176,8 +171,13 @@ + + + + + diff --git a/projects/kiwano/kiwano.vcxproj.filters b/projects/kiwano/kiwano.vcxproj.filters index 3bbe6b4a..8e32b171 100644 --- a/projects/kiwano/kiwano.vcxproj.filters +++ b/projects/kiwano/kiwano.vcxproj.filters @@ -285,12 +285,6 @@ core - - core - - - core - core @@ -321,20 +315,26 @@ render - - core + + utils - - core + + utils - - core + + utils - - core + + utils - - core + + utils + + + utils + + + utils @@ -542,20 +542,20 @@ render - - core + + utils - - core + + utils - - core + + utils - - core + + utils - - core + + utils diff --git a/src/kiwano-network/HttpRequest.h b/src/kiwano-network/HttpRequest.h index fe8bdd6c..626c3b56 100644 --- a/src/kiwano-network/HttpRequest.h +++ b/src/kiwano-network/HttpRequest.h @@ -21,7 +21,7 @@ #pragma once #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/2d/Actor.h b/src/kiwano/2d/Actor.h index 0c552b20..a1af5e8b 100644 --- a/src/kiwano/2d/Actor.h +++ b/src/kiwano/2d/Actor.h @@ -19,11 +19,11 @@ // THE SOFTWARE. #pragma once +#include #include #include -#include #include -#include +#include #include #include diff --git a/src/kiwano/core/ObjectBase.cpp b/src/kiwano/core/ObjectBase.cpp index 9423407c..7fa059f2 100644 --- a/src/kiwano/core/ObjectBase.cpp +++ b/src/kiwano/core/ObjectBase.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/kiwano.h b/src/kiwano/kiwano.h index 92aa77fd..e7cb0773 100644 --- a/src/kiwano/kiwano.h +++ b/src/kiwano/kiwano.h @@ -52,11 +52,6 @@ #include #include #include -#include -#include -#include -#include -#include #include #include #include @@ -120,3 +115,8 @@ #include #include #include +#include +#include +#include +#include +#include diff --git a/src/kiwano/platform/Application.h b/src/kiwano/platform/Application.h index 6fe77c3c..5c2d4e87 100644 --- a/src/kiwano/platform/Application.h +++ b/src/kiwano/platform/Application.h @@ -23,11 +23,11 @@ #include #include #include -#include #include #include #include #include +#include namespace kiwano { diff --git a/src/kiwano/core/EventTicker.cpp b/src/kiwano/utils/EventTicker.cpp similarity index 97% rename from src/kiwano/core/EventTicker.cpp rename to src/kiwano/utils/EventTicker.cpp index b0872b41..f354f081 100644 --- a/src/kiwano/core/EventTicker.cpp +++ b/src/kiwano/utils/EventTicker.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include namespace kiwano { diff --git a/src/kiwano/core/EventTicker.h b/src/kiwano/utils/EventTicker.h similarity index 98% rename from src/kiwano/core/EventTicker.h rename to src/kiwano/utils/EventTicker.h index 1f070edb..37ec50d1 100644 --- a/src/kiwano/core/EventTicker.h +++ b/src/kiwano/utils/EventTicker.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include #include #include diff --git a/src/kiwano/core/Json.h b/src/kiwano/utils/Json.h similarity index 100% rename from src/kiwano/core/Json.h rename to src/kiwano/utils/Json.h diff --git a/src/kiwano/utils/ResourceCache.h b/src/kiwano/utils/ResourceCache.h index 6c40b938..e6aaa9e8 100644 --- a/src/kiwano/utils/ResourceCache.h +++ b/src/kiwano/utils/ResourceCache.h @@ -19,11 +19,11 @@ // THE SOFTWARE. #pragma once +#include +#include +#include #include #include -#include -#include -#include #include #include diff --git a/src/kiwano/core/Task.cpp b/src/kiwano/utils/Task.cpp similarity index 98% rename from src/kiwano/core/Task.cpp rename to src/kiwano/utils/Task.cpp index 430c6094..a1988735 100644 --- a/src/kiwano/core/Task.cpp +++ b/src/kiwano/utils/Task.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include namespace kiwano { diff --git a/src/kiwano/core/Task.h b/src/kiwano/utils/Task.h similarity index 99% rename from src/kiwano/core/Task.h rename to src/kiwano/utils/Task.h index 9297d707..2fcce5f2 100644 --- a/src/kiwano/core/Task.h +++ b/src/kiwano/utils/Task.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include #include namespace kiwano diff --git a/src/kiwano/core/TaskManager.cpp b/src/kiwano/utils/TaskManager.cpp similarity index 98% rename from src/kiwano/core/TaskManager.cpp rename to src/kiwano/utils/TaskManager.cpp index 740ef94a..36afa031 100644 --- a/src/kiwano/core/TaskManager.cpp +++ b/src/kiwano/utils/TaskManager.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include namespace kiwano { diff --git a/src/kiwano/core/TaskManager.h b/src/kiwano/utils/TaskManager.h similarity index 98% rename from src/kiwano/core/TaskManager.h rename to src/kiwano/utils/TaskManager.h index d71d975b..1d2c8669 100644 --- a/src/kiwano/core/TaskManager.h +++ b/src/kiwano/utils/TaskManager.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include namespace kiwano { diff --git a/src/kiwano/core/Ticker.cpp b/src/kiwano/utils/Ticker.cpp similarity index 98% rename from src/kiwano/core/Ticker.cpp rename to src/kiwano/utils/Ticker.cpp index b3884cd8..c072f580 100644 --- a/src/kiwano/core/Ticker.cpp +++ b/src/kiwano/utils/Ticker.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include namespace kiwano { diff --git a/src/kiwano/core/Ticker.h b/src/kiwano/utils/Ticker.h similarity index 99% rename from src/kiwano/core/Ticker.h rename to src/kiwano/utils/Ticker.h index a4663769..0fb86ab0 100644 --- a/src/kiwano/core/Ticker.h +++ b/src/kiwano/utils/Ticker.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include namespace kiwano { diff --git a/src/kiwano/core/Timer.cpp b/src/kiwano/utils/Timer.cpp similarity index 98% rename from src/kiwano/core/Timer.cpp rename to src/kiwano/utils/Timer.cpp index aec2bb48..1c9ce5e2 100644 --- a/src/kiwano/core/Timer.cpp +++ b/src/kiwano/utils/Timer.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include namespace kiwano diff --git a/src/kiwano/core/Timer.h b/src/kiwano/utils/Timer.h similarity index 100% rename from src/kiwano/core/Timer.h rename to src/kiwano/utils/Timer.h diff --git a/src/kiwano/core/Xml.h b/src/kiwano/utils/Xml.h similarity index 100% rename from src/kiwano/core/Xml.h rename to src/kiwano/utils/Xml.h From 6a8b2f528aefc45118fe9110972a659528529b06 Mon Sep 17 00:00:00 2001 From: Nomango Date: Thu, 21 May 2020 00:06:47 +0800 Subject: [PATCH 26/37] TaskManager => TaskScheduler, ActionManager => ActionScheduler --- projects/kiwano/kiwano.vcxproj | 8 +++---- projects/kiwano/kiwano.vcxproj.filters | 24 +++++++++---------- src/kiwano/2d/Actor.cpp | 4 ++-- src/kiwano/2d/Actor.h | 8 +++---- src/kiwano/2d/action/Action.h | 4 ++-- ...{ActionManager.cpp => ActionScheduler.cpp} | 17 ++++++------- .../{ActionManager.h => ActionScheduler.h} | 7 +++--- src/kiwano/kiwano.h | 4 ++-- src/kiwano/utils/Task.h | 4 ++-- .../{TaskManager.cpp => TaskScheduler.cpp} | 20 ++++++++-------- .../utils/{TaskManager.h => TaskScheduler.h} | 10 ++++---- 11 files changed, 55 insertions(+), 55 deletions(-) rename src/kiwano/2d/action/{ActionManager.cpp => ActionScheduler.cpp} (85%) rename src/kiwano/2d/action/{ActionManager.h => ActionScheduler.h} (94%) rename src/kiwano/utils/{TaskManager.cpp => TaskScheduler.cpp} (84%) rename src/kiwano/utils/{TaskManager.h => TaskScheduler.h} (94%) diff --git a/projects/kiwano/kiwano.vcxproj b/projects/kiwano/kiwano.vcxproj index 46c98312..d872159e 100644 --- a/projects/kiwano/kiwano.vcxproj +++ b/projects/kiwano/kiwano.vcxproj @@ -5,7 +5,7 @@ - + @@ -99,7 +99,7 @@ - + @@ -109,7 +109,7 @@ - + @@ -175,7 +175,7 @@ - + diff --git a/projects/kiwano/kiwano.vcxproj.filters b/projects/kiwano/kiwano.vcxproj.filters index 8e32b171..43387c70 100644 --- a/projects/kiwano/kiwano.vcxproj.filters +++ b/projects/kiwano/kiwano.vcxproj.filters @@ -90,9 +90,6 @@ 2d\action - - 2d\action - 2d\action @@ -324,9 +321,6 @@ utils - - utils - utils @@ -336,6 +330,12 @@ utils + + utils + + + 2d\action + @@ -377,9 +377,6 @@ 2d\action - - 2d\action - 2d\action @@ -548,15 +545,18 @@ utils - - utils - utils utils + + utils + + + 2d\action + diff --git a/src/kiwano/2d/Actor.cpp b/src/kiwano/2d/Actor.cpp index 6e9a0340..85cc83c3 100644 --- a/src/kiwano/2d/Actor.cpp +++ b/src/kiwano/2d/Actor.cpp @@ -77,9 +77,9 @@ Actor::~Actor() void Actor::Update(Duration dt) { - UpdateActions(this, dt); + ActionScheduler::Update(this, dt); + TaskScheduler::Update(dt); UpdateComponents(dt); - UpdateTasks(dt); if (!update_pausing_) { diff --git a/src/kiwano/2d/Actor.h b/src/kiwano/2d/Actor.h index a1af5e8b..8ebc92d2 100644 --- a/src/kiwano/2d/Actor.h +++ b/src/kiwano/2d/Actor.h @@ -23,8 +23,8 @@ #include #include #include -#include -#include +#include +#include #include namespace kiwano @@ -62,8 +62,8 @@ typedef IntrusiveList ActorList; */ class KGE_API Actor : public ObjectBase - , public TaskManager - , public ActionManager + , public TaskScheduler + , public ActionScheduler , public EventDispatcher , protected IntrusiveListValue { diff --git a/src/kiwano/2d/action/Action.h b/src/kiwano/2d/action/Action.h index f8d79e4a..8bc67bbb 100644 --- a/src/kiwano/2d/action/Action.h +++ b/src/kiwano/2d/action/Action.h @@ -30,7 +30,7 @@ namespace kiwano { class Actor; -class ActionManager; +class ActionScheduler; KGE_DECLARE_SMART_PTR(Action); @@ -55,7 +55,7 @@ class KGE_API Action , public Cloneable , protected IntrusiveListValue { - friend class ActionManager; + friend class ActionScheduler; friend class ActionGroup; friend IntrusiveList; diff --git a/src/kiwano/2d/action/ActionManager.cpp b/src/kiwano/2d/action/ActionScheduler.cpp similarity index 85% rename from src/kiwano/2d/action/ActionManager.cpp rename to src/kiwano/2d/action/ActionScheduler.cpp index 8c79bfe2..4d8b8765 100644 --- a/src/kiwano/2d/action/ActionManager.cpp +++ b/src/kiwano/2d/action/ActionScheduler.cpp @@ -19,12 +19,13 @@ // THE SOFTWARE. #include -#include +#include #include namespace kiwano { -void ActionManager::UpdateActions(Actor* target, Duration dt) + +void ActionScheduler::Update(Actor* target, Duration dt) { if (actions_.IsEmpty() || !target) return; @@ -42,7 +43,7 @@ void ActionManager::UpdateActions(Actor* target, Duration dt) } } -Action* ActionManager::AddAction(ActionPtr action) +Action* ActionScheduler::AddAction(ActionPtr action) { KGE_ASSERT(action && "AddAction failed, NULL pointer exception"); @@ -53,7 +54,7 @@ Action* ActionManager::AddAction(ActionPtr action) return action.Get(); } -void ActionManager::ResumeAllActions() +void ActionScheduler::ResumeAllActions() { if (actions_.IsEmpty()) return; @@ -64,7 +65,7 @@ void ActionManager::ResumeAllActions() } } -void ActionManager::PauseAllActions() +void ActionScheduler::PauseAllActions() { if (actions_.IsEmpty()) return; @@ -75,7 +76,7 @@ void ActionManager::PauseAllActions() } } -void ActionManager::StopAllActions() +void ActionScheduler::StopAllActions() { if (actions_.IsEmpty()) return; @@ -86,7 +87,7 @@ void ActionManager::StopAllActions() } } -ActionPtr ActionManager::GetAction(const String& name) +ActionPtr ActionScheduler::GetAction(const String& name) { if (actions_.IsEmpty()) return nullptr; @@ -97,7 +98,7 @@ ActionPtr ActionManager::GetAction(const String& name) return nullptr; } -const ActionList& ActionManager::GetAllActions() const +const ActionList& ActionScheduler::GetAllActions() const { return actions_; } diff --git a/src/kiwano/2d/action/ActionManager.h b/src/kiwano/2d/action/ActionScheduler.h similarity index 94% rename from src/kiwano/2d/action/ActionManager.h rename to src/kiwano/2d/action/ActionScheduler.h index 841a4611..34d37421 100644 --- a/src/kiwano/2d/action/ActionManager.h +++ b/src/kiwano/2d/action/ActionScheduler.h @@ -30,9 +30,9 @@ namespace kiwano /** * \~chinese - * @brief 动画管理器 + * @brief 动画调度器 */ -class KGE_API ActionManager +class KGE_API ActionScheduler { public: /// \~chinese @@ -60,10 +60,9 @@ public: /// @brief 获取所有动画 const ActionList& GetAllActions() const; -protected: /// \~chinese /// @brief 更新动画 - void UpdateActions(Actor* target, Duration dt); + void Update(Actor* target, Duration dt); private: ActionList actions_; diff --git a/src/kiwano/kiwano.h b/src/kiwano/kiwano.h index e7cb0773..86e32e0f 100644 --- a/src/kiwano/kiwano.h +++ b/src/kiwano/kiwano.h @@ -93,7 +93,7 @@ #include #include #include -#include +#include #include #include #include @@ -119,4 +119,4 @@ #include #include #include -#include +#include diff --git a/src/kiwano/utils/Task.h b/src/kiwano/utils/Task.h index 2fcce5f2..30e4b652 100644 --- a/src/kiwano/utils/Task.h +++ b/src/kiwano/utils/Task.h @@ -24,7 +24,7 @@ namespace kiwano { -class TaskManager; +class TaskScheduler; KGE_DECLARE_SMART_PTR(Task); @@ -39,7 +39,7 @@ class KGE_API Task : public ObjectBase , protected IntrusiveListValue { - friend class TaskManager; + friend class TaskScheduler; friend IntrusiveList; public: diff --git a/src/kiwano/utils/TaskManager.cpp b/src/kiwano/utils/TaskScheduler.cpp similarity index 84% rename from src/kiwano/utils/TaskManager.cpp rename to src/kiwano/utils/TaskScheduler.cpp index 36afa031..c06d88da 100644 --- a/src/kiwano/utils/TaskManager.cpp +++ b/src/kiwano/utils/TaskScheduler.cpp @@ -19,11 +19,11 @@ // THE SOFTWARE. #include -#include +#include namespace kiwano { -void TaskManager::UpdateTasks(Duration dt) +void TaskScheduler::Update(Duration dt) { if (tasks_.IsEmpty()) return; @@ -40,7 +40,7 @@ void TaskManager::UpdateTasks(Duration dt) } } -Task* TaskManager::AddTask(TaskPtr task) +Task* TaskScheduler::AddTask(TaskPtr task) { KGE_ASSERT(task && "AddTask failed, NULL pointer exception"); @@ -53,7 +53,7 @@ Task* TaskManager::AddTask(TaskPtr task) return task.Get(); } -void TaskManager::StopTasks(const String& name) +void TaskScheduler::StopTasks(const String& name) { if (tasks_.IsEmpty()) return; @@ -67,7 +67,7 @@ void TaskManager::StopTasks(const String& name) } } -void TaskManager::StartTasks(const String& name) +void TaskScheduler::StartTasks(const String& name) { if (tasks_.IsEmpty()) return; @@ -81,7 +81,7 @@ void TaskManager::StartTasks(const String& name) } } -void TaskManager::RemoveTasks(const String& name) +void TaskScheduler::RemoveTasks(const String& name) { if (tasks_.IsEmpty()) return; @@ -95,7 +95,7 @@ void TaskManager::RemoveTasks(const String& name) } } -void TaskManager::StopAllTasks() +void TaskScheduler::StopAllTasks() { if (tasks_.IsEmpty()) return; @@ -106,7 +106,7 @@ void TaskManager::StopAllTasks() } } -void TaskManager::StartAllTasks() +void TaskScheduler::StartAllTasks() { if (tasks_.IsEmpty()) return; @@ -117,12 +117,12 @@ void TaskManager::StartAllTasks() } } -void TaskManager::RemoveAllTasks() +void TaskScheduler::RemoveAllTasks() { tasks_.Clear(); } -const TaskList& TaskManager::GetAllTasks() const +const TaskList& TaskScheduler::GetAllTasks() const { return tasks_; } diff --git a/src/kiwano/utils/TaskManager.h b/src/kiwano/utils/TaskScheduler.h similarity index 94% rename from src/kiwano/utils/TaskManager.h rename to src/kiwano/utils/TaskScheduler.h index 1d2c8669..32ae2c33 100644 --- a/src/kiwano/utils/TaskManager.h +++ b/src/kiwano/utils/TaskScheduler.h @@ -25,9 +25,9 @@ namespace kiwano { /** * \~chinese - * @brief 任务管理器 + * @brief 任务调度器 */ -class KGE_API TaskManager +class KGE_API TaskScheduler { public: /// \~chinese @@ -62,12 +62,12 @@ public: /// @brief 获取所有任务 const TaskList& GetAllTasks() const; -protected: /// \~chinese - /// @brief 更新任务 - void UpdateTasks(Duration dt); + /// @brief 更新调度器 + void Update(Duration dt); private: TaskList tasks_; }; + } // namespace kiwano From fababdbe9b02b9f91e4af72e68ddc39fca0492e8 Mon Sep 17 00:00:00 2001 From: Nomango Date: Thu, 21 May 2020 00:32:43 +0800 Subject: [PATCH 27/37] minor fixes --- src/kiwano/utils/EventTicker.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/kiwano/utils/EventTicker.h b/src/kiwano/utils/EventTicker.h index 37ec50d1..3fffff84 100644 --- a/src/kiwano/utils/EventTicker.h +++ b/src/kiwano/utils/EventTicker.h @@ -63,6 +63,8 @@ public: /// @param times 报时次数(设 -1 为永久) static EventTickerPtr Create(Duration interval, int times = -1); + using Ticker::Tick; + bool Tick(Duration dt) override; }; From 228fc4503563e32c85195466d88a7564983c6a42 Mon Sep 17 00:00:00 2001 From: Nomango Date: Fri, 22 May 2020 21:07:32 +0800 Subject: [PATCH 28/37] make Direct3D resources global --- projects/kiwano/kiwano.vcxproj | 1 + projects/kiwano/kiwano.vcxproj.filters | 3 + src/kiwano-imgui/imgui_impl/imgui_impl.h | 12 +- src/kiwano/platform/Window.cpp | 5 - src/kiwano/platform/Window.h | 32 +++- src/kiwano/platform/win32/WindowImpl.cpp | 78 ++++++++ .../render/DirectX/D2DDeviceResources.cpp | 72 ++++---- .../render/DirectX/D2DDeviceResources.h | 17 +- .../render/DirectX/D3D10DeviceResources.cpp | 166 ++++++++++-------- .../render/DirectX/D3D10DeviceResources.h | 11 +- .../render/DirectX/D3D11DeviceResources.cpp | 166 ++++++++++-------- .../render/DirectX/D3D11DeviceResources.h | 10 +- .../render/DirectX/D3DDeviceResources.h | 54 ++++++ .../render/DirectX/D3DDeviceResourcesBase.h | 11 ++ src/kiwano/render/DirectX/RendererImpl.cpp | 94 ++-------- src/kiwano/render/DirectX/RendererImpl.h | 44 +---- src/kiwano/render/DirectX/helper.h | 2 + src/kiwano/render/Renderer.h | 19 -- 18 files changed, 463 insertions(+), 334 deletions(-) create mode 100644 src/kiwano/render/DirectX/D3DDeviceResources.h diff --git a/projects/kiwano/kiwano.vcxproj b/projects/kiwano/kiwano.vcxproj index 6c148289..7fe3b647 100644 --- a/projects/kiwano/kiwano.vcxproj +++ b/projects/kiwano/kiwano.vcxproj @@ -79,6 +79,7 @@ + diff --git a/projects/kiwano/kiwano.vcxproj.filters b/projects/kiwano/kiwano.vcxproj.filters index 3bbe6b4a..bec9acbc 100644 --- a/projects/kiwano/kiwano.vcxproj.filters +++ b/projects/kiwano/kiwano.vcxproj.filters @@ -336,6 +336,9 @@ core + + render\DirectX + diff --git a/src/kiwano-imgui/imgui_impl/imgui_impl.h b/src/kiwano-imgui/imgui_impl/imgui_impl.h index bd98a2c5..24008337 100644 --- a/src/kiwano-imgui/imgui_impl/imgui_impl.h +++ b/src/kiwano-imgui/imgui_impl/imgui_impl.h @@ -7,13 +7,12 @@ #if !defined(KGE_USE_DIRECTX10) #include -#include +#include inline bool ImGui_Impl_Init() { - ::kiwano::RendererImpl& renderer = ::kiwano::RendererImpl::GetInstance(); - return ImGui_ImplDX11_Init(renderer.GetD3DDeviceResources()->GetDevice(), - renderer.GetD3DDeviceResources()->GetDeviceContext()); + auto d3d = kiwano::graphics::directx::GetD3DDeviceResources(); + return ImGui_ImplDX11_Init(d3d->GetDevice(), d3d->GetDeviceContext()); } inline void ImGui_Impl_Shutdown() @@ -44,11 +43,12 @@ inline bool ImGui_Impl_CreateDeviceObjects() #else #include +#include inline bool ImGui_Impl_Init() { - ::kiwano::RendererImpl& renderer = ::kiwano::RendererImpl::GetInstance(); - return ImGui_ImplDX10_Init(renderer.GetD3DDeviceResources()->GetDevice()); + auto d3d = kiwano::graphics::directx::GetD3DDeviceResources(); + return ImGui_ImplDX10_Init(d3d->GetDevice()); } inline void ImGui_Impl_Shutdown() diff --git a/src/kiwano/platform/Window.cpp b/src/kiwano/platform/Window.cpp index 1fdd40d7..0dcdb4fc 100644 --- a/src/kiwano/platform/Window.cpp +++ b/src/kiwano/platform/Window.cpp @@ -84,11 +84,6 @@ void Window::SetShouldClose(bool should) should_close_ = should; } -void Window::SetFullscreenState(bool is_fullscreen) -{ - is_fullscreen_ = is_fullscreen; -} - void Window::PushEvent(EventPtr evt) { event_queue_.push(evt); diff --git a/src/kiwano/platform/Window.h b/src/kiwano/platform/Window.h index a982bfaa..749a5304 100644 --- a/src/kiwano/platform/Window.h +++ b/src/kiwano/platform/Window.h @@ -45,6 +45,17 @@ enum class CursorType SizeNWSE, ///< 指向左上到右下方向的箭头 }; +/** + * \~chinese + * @brief 分辨率 + */ +struct Resolution +{ + uint32_t width; ///< 分辨率宽度 + uint32_t height; ///< 分辨率高度 + uint32_t refresh_rate; ///< 刷新率 +}; + #if defined(KGE_PLATFORM_WINDOWS) typedef HWND WindowHandle; @@ -143,6 +154,21 @@ public: */ virtual void SetCursor(CursorType cursor) = 0; + /** + * \~chinese + * @brief 设置分辨率 + * @param width 分辨率宽度 + * @param height 分辨率高度 + * @param fullscreen 是否全屏 + */ + virtual void SetResolution(uint32_t width, uint32_t height, bool fullscreen) = 0; + + /** + * \~chinese + * @brief 获取支持的屏幕分辨率列表 + */ + virtual Vector GetResolutions() = 0; + /** * \~chinese * @brief 轮询窗口事件 @@ -175,12 +201,6 @@ public: */ void SetShouldClose(bool should); - /** - * \~chinese - * @brief 设置当前是否是全屏状态 - */ - void SetFullscreenState(bool is_fullscreen); - protected: Window(); diff --git a/src/kiwano/platform/win32/WindowImpl.cpp b/src/kiwano/platform/win32/WindowImpl.cpp index ffe85838..6cd573ea 100644 --- a/src/kiwano/platform/win32/WindowImpl.cpp +++ b/src/kiwano/platform/win32/WindowImpl.cpp @@ -32,6 +32,7 @@ #include #include #include +#include #include // GET_X_LPARAM, GET_Y_LPARAM #include // ImmAssociateContext #pragma comment(lib, "imm32.lib") @@ -60,6 +61,10 @@ public: void SetCursor(CursorType cursor) override; + void SetResolution(uint32_t width, uint32_t height, bool fullscreen) override; + + Vector GetResolutions() override; + void PumpEvents() override; DWORD GetStyle() const; @@ -77,6 +82,7 @@ private: CursorType mouse_cursor_; String device_name_; + Vector resolutions_; std::array key_map_; }; @@ -338,6 +344,78 @@ void WindowWin32Impl::SetCursor(CursorType cursor) mouse_cursor_ = cursor; } +void WindowWin32Impl::SetResolution(uint32_t width, uint32_t height, bool fullscreen) +{ + auto d3d = kiwano::graphics::directx::GetD3DDeviceResources(); + + if (fullscreen) + { + HRESULT hr = d3d->ResizeTarget(width, height); + KGE_THROW_IF_FAILED(hr, "DXGI ResizeTarget failed!"); + + hr = d3d->SetFullscreenState(fullscreen); + KGE_THROW_IF_FAILED(hr, "DXGI SetFullscreenState failed!"); + } + else + { + HRESULT hr = d3d->SetFullscreenState(fullscreen); + KGE_THROW_IF_FAILED(hr, "DXGI SetFullscreenState failed!"); + + hr = d3d->ResizeTarget(width, height); + KGE_THROW_IF_FAILED(hr, "DXGI ResizeTarget failed!"); + } + + is_fullscreen_ = fullscreen; +} + +Vector WindowWin32Impl::GetResolutions() +{ + if (resolutions_.empty()) + { + auto d3d = kiwano::graphics::directx::GetD3DDeviceResources(); + + DXGI_MODE_DESC* mode_descs = nullptr; + int mode_num = 0; + + HRESULT hr = d3d->GetDisplaySettings(&mode_descs, &mode_num); + if (SUCCEEDED(hr)) + { + std::unique_ptr mode_list(mode_descs); + + if (mode_list) + { + for (int i = 0; i < mode_num; i++) + { + Resolution res; + res.width = mode_descs[i].Width; + res.height = mode_descs[i].Height; + res.refresh_rate = 0; + + if (mode_descs[i].RefreshRate.Denominator > 0) + { + res.refresh_rate = mode_descs[i].RefreshRate.Numerator / mode_descs[i].RefreshRate.Denominator; + } + + if (!resolutions_.empty()) + { + auto& back = resolutions_.back(); + if (back.width == res.width && back.height == res.height + && back.refresh_rate == res.refresh_rate) + continue; + } + + resolutions_.push_back(res); + } + } + } + else + { + KGE_THROW_IF_FAILED(hr, "DXGI GetDisplaySettings failed!"); + } + } + return resolutions_; +} + DWORD WindowWin32Impl::GetStyle() const { return (resizable_ ? (WINDOW_RESIZABLE_STYLE) : (WINDOW_FIXED_STYLE)); diff --git a/src/kiwano/render/DirectX/D2DDeviceResources.cpp b/src/kiwano/render/DirectX/D2DDeviceResources.cpp index 3f522162..538725de 100644 --- a/src/kiwano/render/DirectX/D2DDeviceResources.cpp +++ b/src/kiwano/render/DirectX/D2DDeviceResources.cpp @@ -26,6 +26,14 @@ namespace kiwano { +namespace graphics +{ +namespace directx +{ + +// Global pointer for Direct2D device resources +static ComPtr global_d2d_device_resource; + struct D2DDeviceResources : public ID2DDeviceResources { public: @@ -33,6 +41,8 @@ public: virtual ~D2DDeviceResources(); + HRESULT Initialize(_In_ ComPtr dxgi_device, _In_ ComPtr dxgi_swap_chain) override; + HRESULT CreateDeviceIndependentResources(); HRESULT CreateDeviceResources(_In_ ComPtr dxgi_device, _In_ ComPtr dxgi_swap_chain); @@ -57,8 +67,8 @@ public: _In_ ComPtr collection, DWRITE_FONT_WEIGHT weight, DWRITE_FONT_STYLE style, DWRITE_FONT_STRETCH stretch, FLOAT font_size) override; - HRESULT CreateTextLayout(_Out_ ComPtr& text_layout, _In_ LPCWSTR text, - UINT32 length, _In_ ComPtr text_format) override; + HRESULT CreateTextLayout(_Out_ ComPtr& text_layout, _In_ LPCWSTR text, UINT32 length, + _In_ ComPtr text_format) override; HRESULT SetDpi(float dpi) override; @@ -85,40 +95,14 @@ private: ComPtr dxgi_swap_chain_; }; -HRESULT ID2DDeviceResources::Create(_Out_ ID2DDeviceResources** device_resources, _In_ ComPtr dxgi_device, - _In_ ComPtr dxgi_swap_chain) + +ComPtr GetD2DDeviceResources() { - HRESULT hr = E_FAIL; - if (device_resources) + if (!global_d2d_device_resource) { - D2DDeviceResources* res = new (std::nothrow) D2DDeviceResources; - if (res) - { - hr = res->CreateDeviceIndependentResources(); - - if (SUCCEEDED(hr)) - { - hr = res->CreateDeviceResources(dxgi_device, dxgi_swap_chain); - } - - if (SUCCEEDED(hr)) - { - hr = res->CreateWindowSizeDependentResources(); - } - } - - if (SUCCEEDED(hr)) - { - DX::SafeRelease(*device_resources); - (*device_resources) = DX::SafeAcquire(res); - } - else - { - delete res; - res = nullptr; - } + global_d2d_device_resource.Reset(new (std::nothrow) D2DDeviceResources); } - return hr; + return global_d2d_device_resource; } D2DDeviceResources::D2DDeviceResources() @@ -132,6 +116,22 @@ D2DDeviceResources::~D2DDeviceResources() DiscardResources(); } +HRESULT D2DDeviceResources::Initialize(ComPtr dxgi_device, ComPtr dxgi_swap_chain) +{ + HRESULT hr = this->CreateDeviceIndependentResources(); + + if (SUCCEEDED(hr)) + { + hr = this->CreateDeviceResources(dxgi_device, dxgi_swap_chain); + } + + if (SUCCEEDED(hr)) + { + hr = this->CreateWindowSizeDependentResources(); + } + return hr; +} + STDMETHODIMP_(unsigned long) D2DDeviceResources::AddRef() { return InterlockedIncrement(&ref_count_); @@ -423,8 +423,8 @@ HRESULT D2DDeviceResources::CreateTextFormat(_Out_ ComPtr& te return E_UNEXPECTED; ComPtr output; - HRESULT hr = dwrite_factory_->CreateTextFormat(family, collection.Get(), weight, style, stretch, font_size, - L"", &output); + HRESULT hr = + dwrite_factory_->CreateTextFormat(family, collection.Get(), weight, style, stretch, font_size, L"", &output); if (SUCCEEDED(hr)) { @@ -450,4 +450,6 @@ HRESULT D2DDeviceResources::CreateTextLayout(_Out_ ComPtr& te return hr; } +} // namespace directx +} // namespace graphics } // namespace kiwano diff --git a/src/kiwano/render/DirectX/D2DDeviceResources.h b/src/kiwano/render/DirectX/D2DDeviceResources.h index a61e3f24..4c57f263 100644 --- a/src/kiwano/render/DirectX/D2DDeviceResources.h +++ b/src/kiwano/render/DirectX/D2DDeviceResources.h @@ -26,12 +26,16 @@ namespace kiwano { +namespace graphics +{ +namespace directx +{ + MIDL_INTERFACE("5706684a-bf6d-4b03-b627-094758a33032") KGE_API ID2DDeviceResources : public IUnknown { public: - static HRESULT Create(_Out_ ID2DDeviceResources * *device_resources, _In_ ComPtr dxgi_device, - _In_ ComPtr dxgi_swap_chain); + virtual HRESULT Initialize(_In_ ComPtr dxgi_device, _In_ ComPtr dxgi_swap_chain) = 0; virtual HRESULT CreateBitmapConverter(_Out_ ComPtr & converter, _In_opt_ ComPtr source, _In_ REFWICPixelFormatGUID format, @@ -51,8 +55,8 @@ public: _In_ ComPtr collection, DWRITE_FONT_WEIGHT weight, DWRITE_FONT_STYLE style, DWRITE_FONT_STRETCH stretch, FLOAT font_size) = 0; - virtual HRESULT CreateTextLayout(_Out_ ComPtr & text_layout, _In_ LPCWSTR text, - UINT32 length, _In_ ComPtr text_format) = 0; + virtual HRESULT CreateTextLayout(_Out_ ComPtr & text_layout, _In_ LPCWSTR text, UINT32 length, + _In_ ComPtr text_format) = 0; virtual HRESULT SetDpi(float dpi) = 0; @@ -111,4 +115,9 @@ protected: ComPtr dwrite_factory_; }; + +extern ComPtr GetD2DDeviceResources(); + +} +} } // namespace kiwano diff --git a/src/kiwano/render/DirectX/D3D10DeviceResources.cpp b/src/kiwano/render/DirectX/D3D10DeviceResources.cpp index 26897fa8..a5bc29e5 100644 --- a/src/kiwano/render/DirectX/D3D10DeviceResources.cpp +++ b/src/kiwano/render/DirectX/D3D10DeviceResources.cpp @@ -25,9 +25,14 @@ namespace kiwano { - -namespace DX +namespace graphics { +namespace directx +{ + +// Global pointer for Direct3D11 device resources +static ComPtr global_d3d10_device_resources; + HRESULT CreateD3DDevice(IDXGIAdapter* adapter, D3D10_DRIVER_TYPE driver_type, uint32_t flags, ID3D10Device1** device) { HRESULT hr = S_OK; @@ -60,11 +65,11 @@ inline bool SdkLayersAvailable() } #endif -} // namespace DX - struct D3D10DeviceResources : public ID3D10DeviceResources { public: + HRESULT Initialize(HWND hwnd) override; + HRESULT Present(bool vsync) override; void ClearRenderTarget(Color& clear_color) override; @@ -77,6 +82,8 @@ public: HRESULT SetFullscreenState(bool fullscreen) override; + HRESULT GetFullscreenState(bool* fullscreen) override; + HRESULT ResizeTarget(UINT width, UINT height) override; HRESULT GetDisplaySettings(DXGI_MODE_DESC** mode_descs, int* num) override; @@ -108,6 +115,16 @@ public: DXGI_FORMAT desired_color_format_; }; + +ComPtr GetD3D10DeviceResources() +{ + if (!global_d3d10_device_resources) + { + global_d3d10_device_resources.Reset(new (std::nothrow) D3D10DeviceResources); + } + return global_d3d10_device_resources; +} + D3D10DeviceResources::D3D10DeviceResources() : ref_count_(0) , hwnd_(nullptr) @@ -121,55 +138,34 @@ D3D10DeviceResources::~D3D10DeviceResources() DiscardResources(); } -HRESULT ID3D10DeviceResources::Create(ID3D10DeviceResources** device_resources, HWND hwnd) +HRESULT D3D10DeviceResources::Initialize(HWND hwnd) { - HRESULT hr = E_FAIL; + RECT rc; + ::GetClientRect(hwnd, &rc); - if (device_resources) + this->hwnd_ = hwnd; + this->logical_size_.x = float(rc.right - rc.left); + this->logical_size_.y = float(rc.bottom - rc.top); + + HRESULT hr = this->CreateDeviceResources(); + + if (SUCCEEDED(hr)) { - D3D10DeviceResources* res = new (std::nothrow) D3D10DeviceResources; - if (res) - { - RECT rc; - ::GetClientRect(hwnd, &rc); - - res->hwnd_ = hwnd; - res->logical_size_.x = float(rc.right - rc.left); - res->logical_size_.y = float(rc.bottom - rc.top); - - hr = res->CreateDeviceResources(); - - if (SUCCEEDED(hr)) - { - hr = res->CreateWindowSizeDependentResources(); - } - - if (SUCCEEDED(hr)) - { - res->AddRef(); - - if (*device_resources) - { - (*device_resources)->Release(); - } - (*device_resources) = res; - } - else - { - delete res; - res = nullptr; - } - } + hr = this->CreateWindowSizeDependentResources(); } return hr; } HRESULT D3D10DeviceResources::Present(bool vsync) { - KGE_ASSERT(dxgi_swap_chain_ != nullptr); + HRESULT hr = E_FAIL; - // The first argument instructs DXGI to block until VSync. - return dxgi_swap_chain_->Present(vsync ? 1 : 0, 0); + if (dxgi_swap_chain_) + { + // The first argument instructs DXGI to block until VSync. + hr = dxgi_swap_chain_->Present(vsync ? 1 : 0, DXGI_PRESENT_DO_NOT_WAIT); + } + return hr; } void D3D10DeviceResources::ClearRenderTarget(Color& clear_color) @@ -202,14 +198,14 @@ HRESULT D3D10DeviceResources::CreateDeviceResources() uint32_t creation_flags = D3D10_CREATE_DEVICE_BGRA_SUPPORT; #if defined(KGE_DEBUG) && defined(KGE_ENABLE_DX_DEBUG) - if (DX::SdkLayersAvailable()) + if (SdkLayersAvailable()) { creation_flags |= D3D10_CREATE_DEVICE_DEBUG; } #endif ComPtr device; - hr = DX::CreateD3DDevice(NULL, D3D10_DRIVER_TYPE_HARDWARE, creation_flags, &device); + hr = CreateD3DDevice(NULL, D3D10_DRIVER_TYPE_HARDWARE, creation_flags, &device); if (SUCCEEDED(hr)) { @@ -415,53 +411,79 @@ HRESULT D3D10DeviceResources::SetDpi(float dpi) HRESULT D3D10DeviceResources::SetFullscreenState(bool fullscreen) { - HRESULT hr = dxgi_swap_chain_->SetFullscreenState(fullscreen ? TRUE : FALSE, nullptr); + HRESULT hr = E_FAIL; + if (dxgi_swap_chain_) + { + hr = dxgi_swap_chain_->SetFullscreenState(fullscreen ? TRUE : FALSE, nullptr); + } + return hr; +} + +HRESULT D3D10DeviceResources::GetFullscreenState(bool* fullscreen) +{ + HRESULT hr = E_FAIL; + if (dxgi_swap_chain_) + { + BOOL is_fullscreen; + hr = dxgi_swap_chain_->GetFullscreenState(&is_fullscreen, nullptr); + + if (SUCCEEDED(hr)) + { + (*fullscreen) = (is_fullscreen == TRUE); + } + } return hr; } HRESULT D3D10DeviceResources::ResizeTarget(UINT width, UINT height) { - DXGI_MODE_DESC desc = { 0 }; - desc.Width = width; - desc.Height = height; - desc.Format = DXGI_FORMAT_UNKNOWN; + HRESULT hr = E_FAIL; + if (dxgi_swap_chain_) + { + DXGI_MODE_DESC desc = { 0 }; + desc.Width = width; + desc.Height = height; + desc.Format = DXGI_FORMAT_UNKNOWN; - HRESULT hr = dxgi_swap_chain_->ResizeTarget(&desc); + hr = dxgi_swap_chain_->ResizeTarget(&desc); + } return hr; } HRESULT D3D10DeviceResources::GetDisplaySettings(DXGI_MODE_DESC** mode_descs, int* num) { - KGE_ASSERT(dxgi_swap_chain_); - - ComPtr output; - HRESULT hr = dxgi_swap_chain_->GetContainingOutput(&output); - - if (SUCCEEDED(hr)) + HRESULT hr = E_FAIL; + if (dxgi_swap_chain_) { - UINT num_of_supported_modes = 0; - output->GetDisplayModeList(desired_color_format_, 0, &num_of_supported_modes, 0); + ComPtr output; + hr = dxgi_swap_chain_->GetContainingOutput(&output); - if (num_of_supported_modes > 0) + if (SUCCEEDED(hr)) { - DXGI_MODE_DESC* supported_modes = new DXGI_MODE_DESC[num_of_supported_modes]; - ZeroMemory(supported_modes, sizeof(DXGI_MODE_DESC) * num_of_supported_modes); + UINT num_of_supported_modes = 0; + output->GetDisplayModeList(desired_color_format_, 0, &num_of_supported_modes, 0); - hr = output->GetDisplayModeList(desired_color_format_, 0, &num_of_supported_modes, supported_modes); - if (SUCCEEDED(hr) && mode_descs && num) + if (num_of_supported_modes > 0) { - (*mode_descs) = supported_modes; - (*num) = (int)num_of_supported_modes; + DXGI_MODE_DESC* supported_modes = new DXGI_MODE_DESC[num_of_supported_modes]; + ZeroMemory(supported_modes, sizeof(DXGI_MODE_DESC) * num_of_supported_modes); + + hr = output->GetDisplayModeList(desired_color_format_, 0, &num_of_supported_modes, supported_modes); + if (SUCCEEDED(hr) && mode_descs && num) + { + (*mode_descs) = supported_modes; + (*num) = (int)num_of_supported_modes; + } + else + { + delete[] supported_modes; + } } else { - delete[] supported_modes; + hr = E_FAIL; } } - else - { - hr = E_FAIL; - } } return hr; } @@ -509,4 +531,6 @@ STDMETHODIMP D3D10DeviceResources::QueryInterface(const IID& riid, void** object return S_OK; } +} // namespace directx +} // namespace graphics } // namespace kiwano diff --git a/src/kiwano/render/DirectX/D3D10DeviceResources.h b/src/kiwano/render/DirectX/D3D10DeviceResources.h index 7ea02e61..0c12878f 100644 --- a/src/kiwano/render/DirectX/D3D10DeviceResources.h +++ b/src/kiwano/render/DirectX/D3D10DeviceResources.h @@ -26,12 +26,15 @@ namespace kiwano { +namespace graphics +{ +namespace directx +{ + MIDL_INTERFACE("3a150b9d-cc23-4022-a463-7e95452a54c4") KGE_API ID3D10DeviceResources : public ID3DDeviceResourcesBase { public: - static HRESULT Create(ID3D10DeviceResources * *device_resources, HWND hwnd); - inline ID3D10Device* GetDevice() { KGE_ASSERT(device_); @@ -77,4 +80,8 @@ protected: ComPtr dxgi_swap_chain_; }; +extern ComPtr GetD3D11DeviceResources(); + +} // namespace directx +} // namespace graphics } // namespace kiwano diff --git a/src/kiwano/render/DirectX/D3D11DeviceResources.cpp b/src/kiwano/render/DirectX/D3D11DeviceResources.cpp index e39e69f3..65da7e5f 100644 --- a/src/kiwano/render/DirectX/D3D11DeviceResources.cpp +++ b/src/kiwano/render/DirectX/D3D11DeviceResources.cpp @@ -31,9 +31,16 @@ KGE_SUPPRESS_WARNING_POP namespace kiwano { -#if defined(KGE_DEBUG) -namespace DX +namespace graphics { +namespace directx +{ + +// Global pointer for Direct3D11 device resources +static ComPtr global_d3d11_device_resources; + + +#if defined(KGE_DEBUG) inline bool SdkLayersAvailable() { HRESULT hr = D3D11CreateDevice(nullptr, @@ -46,15 +53,15 @@ inline bool SdkLayersAvailable() nullptr, // No need to know the feature level. nullptr // No need to keep the D3D device context reference. ); - return SUCCEEDED(hr); } -} // namespace DX #endif struct D3D11DeviceResources : public ID3D11DeviceResources { public: + HRESULT Initialize(HWND hwnd) override; + HRESULT Present(bool vsync) override; void ClearRenderTarget(Color& clear_color) override; @@ -67,6 +74,8 @@ public: HRESULT SetFullscreenState(bool fullscreen) override; + HRESULT GetFullscreenState(bool* fullscreen) override; + HRESULT ResizeTarget(UINT width, UINT height) override; HRESULT GetDisplaySettings(DXGI_MODE_DESC** mode_descs, int* num) override; @@ -100,6 +109,16 @@ public: DXGI_FORMAT desired_color_format_; }; + +ComPtr GetD3D11DeviceResources() +{ + if (!global_d3d11_device_resources) + { + global_d3d11_device_resources.Reset(new (std::nothrow) D3D11DeviceResources); + } + return global_d3d11_device_resources; +} + D3D11DeviceResources::D3D11DeviceResources() : ref_count_(0) , hwnd_(nullptr) @@ -114,55 +133,34 @@ D3D11DeviceResources::~D3D11DeviceResources() DiscardResources(); } -HRESULT ID3D11DeviceResources::Create(ID3D11DeviceResources** device_resources, HWND hwnd) +HRESULT D3D11DeviceResources::Initialize(HWND hwnd) { - HRESULT hr = E_FAIL; + RECT rc; + ::GetClientRect(hwnd, &rc); - if (device_resources) + this->hwnd_ = hwnd; + this->logical_size_.x = float(rc.right - rc.left); + this->logical_size_.y = float(rc.bottom - rc.top); + + HRESULT hr = this->CreateDeviceResources(); + + if (SUCCEEDED(hr)) { - D3D11DeviceResources* res = new (std::nothrow) D3D11DeviceResources; - if (res) - { - RECT rc; - ::GetClientRect(hwnd, &rc); - - res->hwnd_ = hwnd; - res->logical_size_.x = float(rc.right - rc.left); - res->logical_size_.y = float(rc.bottom - rc.top); - - hr = res->CreateDeviceResources(); - - if (SUCCEEDED(hr)) - { - hr = res->CreateWindowSizeDependentResources(); - } - - if (SUCCEEDED(hr)) - { - res->AddRef(); - - if (*device_resources) - { - (*device_resources)->Release(); - } - (*device_resources) = res; - } - else - { - delete res; - res = nullptr; - } - } + hr = this->CreateWindowSizeDependentResources(); } return hr; } HRESULT D3D11DeviceResources::Present(bool vsync) { - KGE_ASSERT(dxgi_swap_chain_ != nullptr); + HRESULT hr = E_FAIL; - // The first argument instructs DXGI to block until VSync. - return dxgi_swap_chain_->Present(vsync ? 1 : 0, 0); + if (dxgi_swap_chain_) + { + // The first argument instructs DXGI to block until VSync. + hr = dxgi_swap_chain_->Present(vsync ? 1 : 0, DXGI_PRESENT_DO_NOT_WAIT); + } + return hr; } void D3D11DeviceResources::ClearRenderTarget(Color& clear_color) @@ -204,7 +202,7 @@ HRESULT D3D11DeviceResources::CreateDeviceResources() uint32_t creation_flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #if defined(KGE_DEBUG) && defined(KGE_ENABLE_DX_DEBUG) - if (DX::SdkLayersAvailable()) + if (SdkLayersAvailable()) { creation_flags |= D3D11_CREATE_DEVICE_DEBUG; } @@ -436,53 +434,79 @@ HRESULT D3D11DeviceResources::SetDpi(float dpi) HRESULT D3D11DeviceResources::SetFullscreenState(bool fullscreen) { - HRESULT hr = dxgi_swap_chain_->SetFullscreenState(fullscreen ? TRUE : FALSE, nullptr); + HRESULT hr = E_FAIL; + if (dxgi_swap_chain_) + { + hr = dxgi_swap_chain_->SetFullscreenState(fullscreen ? TRUE : FALSE, nullptr); + } + return hr; +} + +HRESULT D3D11DeviceResources::GetFullscreenState(bool* fullscreen) +{ + HRESULT hr = E_FAIL; + if (dxgi_swap_chain_) + { + BOOL is_fullscreen; + hr = dxgi_swap_chain_->GetFullscreenState(&is_fullscreen, nullptr); + + if (SUCCEEDED(hr)) + { + (*fullscreen) = (is_fullscreen == TRUE); + } + } return hr; } HRESULT D3D11DeviceResources::ResizeTarget(UINT width, UINT height) { - DXGI_MODE_DESC desc = { 0 }; - desc.Width = width; - desc.Height = height; - desc.Format = DXGI_FORMAT_UNKNOWN; + HRESULT hr = E_FAIL; + if (dxgi_swap_chain_) + { + DXGI_MODE_DESC desc = { 0 }; + desc.Width = width; + desc.Height = height; + desc.Format = DXGI_FORMAT_UNKNOWN; - HRESULT hr = dxgi_swap_chain_->ResizeTarget(&desc); + hr = dxgi_swap_chain_->ResizeTarget(&desc); + } return hr; } HRESULT D3D11DeviceResources::GetDisplaySettings(DXGI_MODE_DESC** mode_descs, int* num) { - KGE_ASSERT(dxgi_swap_chain_); - - ComPtr output; - HRESULT hr = dxgi_swap_chain_->GetContainingOutput(&output); - - if (SUCCEEDED(hr)) + HRESULT hr = E_FAIL; + if (dxgi_swap_chain_) { - UINT num_of_supported_modes = 0; - output->GetDisplayModeList(desired_color_format_, 0, &num_of_supported_modes, 0); + ComPtr output; + HRESULT hr = dxgi_swap_chain_->GetContainingOutput(&output); - if (num_of_supported_modes > 0) + if (SUCCEEDED(hr)) { - DXGI_MODE_DESC* supported_modes = new DXGI_MODE_DESC[num_of_supported_modes]; - ZeroMemory(supported_modes, sizeof(DXGI_MODE_DESC) * num_of_supported_modes); + UINT num_of_supported_modes = 0; + output->GetDisplayModeList(desired_color_format_, 0, &num_of_supported_modes, 0); - hr = output->GetDisplayModeList(desired_color_format_, 0, &num_of_supported_modes, supported_modes); - if (SUCCEEDED(hr) && mode_descs && num) + if (num_of_supported_modes > 0) { - (*mode_descs) = supported_modes; - (*num) = (int)num_of_supported_modes; + DXGI_MODE_DESC* supported_modes = new DXGI_MODE_DESC[num_of_supported_modes]; + ZeroMemory(supported_modes, sizeof(DXGI_MODE_DESC) * num_of_supported_modes); + + hr = output->GetDisplayModeList(desired_color_format_, 0, &num_of_supported_modes, supported_modes); + if (SUCCEEDED(hr) && mode_descs && num) + { + (*mode_descs) = supported_modes; + (*num) = (int)num_of_supported_modes; + } + else + { + delete[] supported_modes; + } } else { - delete[] supported_modes; + hr = E_FAIL; } } - else - { - hr = E_FAIL; - } } return hr; } @@ -530,4 +554,6 @@ STDMETHODIMP D3D11DeviceResources::QueryInterface(const IID& riid, void** object return S_OK; } +} // namespace directx +} // namespace graphics } // namespace kiwano diff --git a/src/kiwano/render/DirectX/D3D11DeviceResources.h b/src/kiwano/render/DirectX/D3D11DeviceResources.h index 8adf06bd..3950a7e6 100644 --- a/src/kiwano/render/DirectX/D3D11DeviceResources.h +++ b/src/kiwano/render/DirectX/D3D11DeviceResources.h @@ -26,13 +26,15 @@ namespace kiwano { +namespace graphics +{ +namespace directx +{ MIDL_INTERFACE("3ede2b87-a202-4799-a39b-2308ad34cae8") KGE_API ID3D11DeviceResources : public ID3DDeviceResourcesBase { public: - static HRESULT Create(ID3D11DeviceResources * *device_resources, HWND hwnd); - inline ID3D11Device* GetDevice() { KGE_ASSERT(device_); @@ -85,4 +87,8 @@ protected: ComPtr dxgi_swap_chain_; }; +extern ComPtr GetD3D11DeviceResources(); + +} // namespace directx +} // namespace graphics } // namespace kiwano diff --git a/src/kiwano/render/DirectX/D3DDeviceResources.h b/src/kiwano/render/DirectX/D3DDeviceResources.h new file mode 100644 index 00000000..fd625ba5 --- /dev/null +++ b/src/kiwano/render/DirectX/D3DDeviceResources.h @@ -0,0 +1,54 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#pragma once + +#if defined(KGE_USE_DIRECTX10) +#include +#else +#include +#endif + +namespace kiwano +{ +namespace graphics +{ +namespace directx +{ + +#if defined(KGE_USE_DIRECTX10) + using ID3DDeviceResources = kiwano::graphics::directx::ID3D10DeviceResources; + + inline ComPtr GetD3DDeviceResources() + { + return kiwano::graphics::directx::GetD3D10DeviceResources(); + } +#else + using ID3DDeviceResources = kiwano::graphics::directx::ID3D11DeviceResources; + + inline ComPtr GetD3DDeviceResources() + { + return kiwano::graphics::directx::GetD3D11DeviceResources(); + } +#endif + +} // namespace directx +} // namespace graphics +} // namespace kiwano diff --git a/src/kiwano/render/DirectX/D3DDeviceResourcesBase.h b/src/kiwano/render/DirectX/D3DDeviceResourcesBase.h index b83e7856..a14ab67b 100644 --- a/src/kiwano/render/DirectX/D3DDeviceResourcesBase.h +++ b/src/kiwano/render/DirectX/D3DDeviceResourcesBase.h @@ -23,10 +23,17 @@ namespace kiwano { +namespace graphics +{ +namespace directx +{ + MIDL_INTERFACE("fb99fa64-d9cf-4e0e-9c75-90514797b01d") ID3DDeviceResourcesBase : public IUnknown { public: + virtual HRESULT Initialize(HWND hwnd) = 0; + virtual HRESULT Present(bool vsync) = 0; virtual void ClearRenderTarget(Color & clear_color) = 0; @@ -39,6 +46,8 @@ public: virtual HRESULT SetFullscreenState(bool fullscreen) = 0; + virtual HRESULT GetFullscreenState(bool* fullscreen) = 0; + virtual HRESULT ResizeTarget(UINT width, UINT height) = 0; virtual HRESULT GetDisplaySettings(DXGI_MODE_DESC** mode_descs, int* num) = 0; @@ -46,4 +55,6 @@ public: virtual void DiscardResources() = 0; }; +} // namespace directx +} // namespace graphics } // namespace kiwano diff --git a/src/kiwano/render/DirectX/RendererImpl.cpp b/src/kiwano/render/DirectX/RendererImpl.cpp index 2b7adb43..de86e279 100644 --- a/src/kiwano/render/DirectX/RendererImpl.cpp +++ b/src/kiwano/render/DirectX/RendererImpl.cpp @@ -32,6 +32,8 @@ namespace kiwano { +using namespace kiwano::graphics::directx; + Renderer& Renderer::GetInstance() { return RendererImpl::GetInstance(); @@ -64,16 +66,26 @@ void RendererImpl::MakeContextForWindow(WindowPtr window) // Direct3D device resources if (SUCCEEDED(hr)) { - hr = ID3DDeviceResources::Create(&d3d_res_, target_window); + auto d3d_res = graphics::directx::GetD3DDeviceResources(); + + // Initialize Direct3D resources + hr = d3d_res->Initialize(target_window); // Direct2D device resources if (SUCCEEDED(hr)) { - hr = ID2DDeviceResources::Create(&d2d_res_, d3d_res_->GetDXGIDevice(), d3d_res_->GetDXGISwapChain()); + d3d_res_ = d3d_res; + + auto d2d_res = graphics::directx::GetD2DDeviceResources(); + + // Initialize Direct2D resources + hr = d2d_res->Initialize(d3d_res_->GetDXGIDevice(), d3d_res_->GetDXGISwapChain()); - // Other device resources if (SUCCEEDED(hr)) { + d2d_res_ = d2d_res; + + // Initialize other device resources RenderContextImplPtr ctx = memory::New(); hr = ctx->CreateDeviceResources(d2d_res_->GetFactory(), d2d_res_->GetDeviceContext()); @@ -151,7 +163,10 @@ void RendererImpl::Present() KGE_ASSERT(d3d_res_); HRESULT hr = d3d_res_->Present(vsync_); - KGE_THROW_IF_FAILED(hr, "Unexpected DXGI exception"); + if (FAILED(hr) && hr != DXGI_ERROR_WAS_STILL_DRAWING) + { + KGE_THROW_IF_FAILED(hr, "Unexpected DXGI exception"); + } } void RendererImpl::CreateTexture(Texture& texture, const String& file_path) @@ -949,77 +964,6 @@ RenderContextPtr RendererImpl::CreateTextureRenderContext(Texture& texture, cons return nullptr; } -void RendererImpl::SetResolution(uint32_t width, uint32_t height, bool fullscreen) -{ - KGE_ASSERT(d3d_res_); - - if (fullscreen) - { - HRESULT hr = d3d_res_->ResizeTarget(width, height); - KGE_THROW_IF_FAILED(hr, "DXGI ResizeTarget failed!"); - - hr = d3d_res_->SetFullscreenState(fullscreen); - KGE_THROW_IF_FAILED(hr, "DXGI SetFullscreenState failed!"); - } - else - { - HRESULT hr = d3d_res_->SetFullscreenState(fullscreen); - KGE_THROW_IF_FAILED(hr, "DXGI SetFullscreenState failed!"); - - hr = d3d_res_->ResizeTarget(width, height); - KGE_THROW_IF_FAILED(hr, "DXGI ResizeTarget failed!"); - } - - Application::GetInstance().GetMainWindow()->SetFullscreenState(fullscreen); -} - -Vector RendererImpl::GetResolutions() -{ - if (resolutions_.empty()) - { - - DXGI_MODE_DESC* mode_descs = nullptr; - int mode_num = 0; - - HRESULT hr = d3d_res_->GetDisplaySettings(&mode_descs, &mode_num); - if (SUCCEEDED(hr)) - { - std::unique_ptr mode_list(mode_descs); - - if (mode_list) - { - for (int i = 0; i < mode_num; i++) - { - Resolution res; - res.width = mode_descs[i].Width; - res.height = mode_descs[i].Height; - res.refresh_rate = 0; - - if (mode_descs[i].RefreshRate.Denominator > 0) - { - res.refresh_rate = mode_descs[i].RefreshRate.Numerator / mode_descs[i].RefreshRate.Denominator; - } - - if (!resolutions_.empty()) - { - auto& back = resolutions_.back(); - if (back.width == res.width && back.height == res.height - && back.refresh_rate == res.refresh_rate) - continue; - } - - resolutions_.push_back(res); - } - } - } - else - { - KGE_THROW_IF_FAILED(hr, "DXGI GetDisplaySettings failed!"); - } - } - return resolutions_; -} - void RendererImpl::Resize(uint32_t width, uint32_t height) { HRESULT hr = S_OK; diff --git a/src/kiwano/render/DirectX/RendererImpl.h b/src/kiwano/render/DirectX/RendererImpl.h index 4851229e..edddaa45 100644 --- a/src/kiwano/render/DirectX/RendererImpl.h +++ b/src/kiwano/render/DirectX/RendererImpl.h @@ -20,24 +20,14 @@ #pragma once #include +#include #include #include -#if defined(KGE_USE_DIRECTX10) -#include -#else -#include -#endif namespace kiwano { -#if defined(KGE_USE_DIRECTX10) -typedef ID3D10DeviceResources ID3DDeviceResources; -#else -typedef ID3D11DeviceResources ID3DDeviceResources; -#endif - class KGE_API RendererImpl : public Renderer { @@ -82,25 +72,11 @@ public: RenderContextPtr CreateTextureRenderContext(Texture& texture, const Size* desired_size = nullptr) override; - void SetResolution(uint32_t width, uint32_t height, bool fullscreen) override; - - Vector GetResolutions() override; - public: void Clear() override; void Present() override; - /// \~chinese - /// @brief 获取Direct2D设备资源 - ID2DDeviceResources* GetD2DDeviceResources(); - - /// \~chinese - /// @brief 获取Direct3D设备资源 - ID3DDeviceResources* GetD3DDeviceResources(); - - /// \~chinese - /// @brief 重设渲染输出大小 void Resize(uint32_t width, uint32_t height) override; protected: @@ -111,27 +87,17 @@ protected: void Destroy() override; private: + using ID2DDeviceResources = kiwano::graphics::directx::ID2DDeviceResources; + using ID3DDeviceResources = kiwano::graphics::directx::ID3DDeviceResources; + ComPtr d2d_res_; ComPtr d3d_res_; ComPtr font_collection_loader_; ComPtr res_font_file_loader_; ComPtr res_font_collection_loader_; - - Vector resolutions_; }; + /** @} */ -inline ID2DDeviceResources* RendererImpl::GetD2DDeviceResources() -{ - KGE_ASSERT(d2d_res_); - return d2d_res_.Get(); -} - -inline ID3DDeviceResources* RendererImpl::GetD3DDeviceResources() -{ - KGE_ASSERT(d3d_res_); - return d3d_res_.Get(); -} - } // namespace kiwano diff --git a/src/kiwano/render/DirectX/helper.h b/src/kiwano/render/DirectX/helper.h index 53f4ceae..5461cac8 100644 --- a/src/kiwano/render/DirectX/helper.h +++ b/src/kiwano/render/DirectX/helper.h @@ -29,6 +29,7 @@ namespace kiwano { namespace DX { + template inline void SafeRelease(T*& ptr) { @@ -174,5 +175,6 @@ inline float ConvertDipsToPixels(float dips, float dpi) static const float dips_per_inch = 96.0f; return math::Floor(dips * dpi / dips_per_inch + 0.5f); // Round to nearest integer. } + } // namespace DX } // namespace kiwano diff --git a/src/kiwano/render/Renderer.h b/src/kiwano/render/Renderer.h index 7b2d60f0..7b80dae3 100644 --- a/src/kiwano/render/Renderer.h +++ b/src/kiwano/render/Renderer.h @@ -39,17 +39,6 @@ namespace kiwano * @{ */ -/** - * \~chinese - * @brief 分辨率 - */ -struct Resolution -{ - uint32_t width; ///< 分辨率宽度 - uint32_t height; ///< 分辨率高度 - uint32_t refresh_rate; ///< 刷新率 -}; - /** * \~chinese @@ -74,14 +63,6 @@ public: /// @brief 开启或关闭垂直同步 virtual void SetVSyncEnabled(bool enabled); - /// \~chinese - /// @brief 设置分辨率 - virtual void SetResolution(uint32_t width, uint32_t height, bool fullscreen) = 0; - - /// \~chinese - /// @brief 获取屏幕分辨率 - virtual Vector GetResolutions() = 0; - /// \~chinese /// @brief 创建纹理内部资源 /// @param[out] texture 纹理 From 5d7c3f4f9a7ead7b56726ec158356c9081d48248 Mon Sep 17 00:00:00 2001 From: Nomango Date: Sun, 24 May 2020 11:26:21 +0800 Subject: [PATCH 29/37] refactoring project --- projects/kiwano/kiwano.vcxproj | 47 +++--- projects/kiwano/kiwano.vcxproj.filters | 150 +++++++++--------- src/kiwano-audio/AudioModule.cpp | 2 +- src/kiwano-audio/AudioModule.h | 2 +- src/kiwano-audio/Sound.cpp | 2 +- src/kiwano-audio/Sound.h | 2 +- src/kiwano-audio/SoundPlayer.h | 2 +- src/kiwano-audio/Transcoder.cpp | 3 +- src/kiwano-imgui/ImGuiModule.cpp | 3 +- src/kiwano-imgui/ImGuiModule.h | 2 +- src/kiwano-network/HttpModule.cpp | 2 +- src/kiwano-network/HttpModule.h | 2 +- src/kiwano-network/HttpRequest.h | 2 +- src/kiwano/2d/Actor.cpp | 2 +- src/kiwano/2d/Actor.h | 4 +- src/kiwano/2d/Canvas.cpp | 2 +- src/kiwano/2d/Component.h | 2 +- src/kiwano/2d/DebugActor.cpp | 2 +- src/kiwano/2d/ShapeActor.cpp | 2 +- src/kiwano/2d/Stage.cpp | 2 +- src/kiwano/2d/TextActor.cpp | 2 +- src/kiwano/2d/Transition.cpp | 2 +- src/kiwano/2d/action/Action.h | 2 +- src/kiwano/2d/action/ActionGroup.cpp | 2 +- src/kiwano/2d/action/ActionScheduler.cpp | 2 +- src/kiwano/2d/action/ActionTween.h | 2 +- src/kiwano/{core => base}/Director.cpp | 2 +- src/kiwano/{core => base}/Director.h | 2 +- src/kiwano/{core => base}/Module.cpp | 2 +- src/kiwano/{core => base}/Module.h | 0 src/kiwano/{core => base}/ObjectBase.cpp | 4 +- src/kiwano/{core => base}/ObjectBase.h | 4 +- src/kiwano/{core => base}/RefCounter.cpp | 2 +- src/kiwano/{core => base}/RefCounter.h | 0 src/kiwano/core/Exception.cpp | 2 +- src/kiwano/core/Exception.h | 2 +- src/kiwano/core/Resource.cpp | 2 +- src/kiwano/core/SmartPtr.hpp | 2 +- src/kiwano/core/Time.cpp | 2 +- src/kiwano/{core => }/event/Event.cpp | 2 +- src/kiwano/{core => }/event/Event.h | 2 +- .../{core => event}/EventDispatcher.cpp | 4 +- src/kiwano/{core => event}/EventDispatcher.h | 2 +- src/kiwano/{core => event}/EventListener.cpp | 2 +- src/kiwano/{core => event}/EventListener.h | 7 +- src/kiwano/{core => }/event/EventType.h | 0 src/kiwano/event/Events.h | 26 +++ src/kiwano/{core => }/event/KeyEvent.cpp | 2 +- src/kiwano/{core => }/event/KeyEvent.h | 2 +- src/kiwano/{core => }/event/MouseEvent.cpp | 2 +- src/kiwano/{core => }/event/MouseEvent.h | 2 +- src/kiwano/{core => }/event/WindowEvent.cpp | 2 +- src/kiwano/{core => }/event/WindowEvent.h | 2 +- src/kiwano/kiwano.h | 31 ++-- src/kiwano/platform/Application.cpp | 4 +- src/kiwano/platform/Application.h | 4 +- src/kiwano/platform/Input.cpp | 5 +- src/kiwano/platform/Input.h | 4 +- src/kiwano/platform/Window.h | 4 +- src/kiwano/platform/win32/WindowImpl.cpp | 6 +- src/kiwano/platform/win32/libraries.cpp | 2 +- src/kiwano/render/Brush.cpp | 2 +- .../render/DirectX/D2DDeviceResources.cpp | 2 +- .../render/DirectX/D3D10DeviceResources.cpp | 2 +- .../render/DirectX/D3D11DeviceResources.cpp | 2 +- .../render/DirectX/RenderContextImpl.cpp | 2 +- src/kiwano/render/DirectX/RendererImpl.cpp | 4 +- src/kiwano/render/Frame.h | 2 +- src/kiwano/render/FrameSequence.cpp | 2 +- src/kiwano/render/GifImage.cpp | 2 +- src/kiwano/render/NativeObject.h | 2 +- src/kiwano/render/Renderer.cpp | 2 +- src/kiwano/render/Renderer.h | 2 +- src/kiwano/render/TextureCache.cpp | 2 +- src/kiwano/utils/EventTicker.h | 4 +- src/kiwano/utils/LocalStorage.h | 2 +- src/kiwano/{core => utils}/Logger.cpp | 2 +- src/kiwano/{core => utils}/Logger.h | 0 src/kiwano/utils/ResourceCache.cpp | 2 +- src/kiwano/utils/TaskScheduler.cpp | 2 +- src/kiwano/utils/Timer.h | 2 +- 81 files changed, 236 insertions(+), 198 deletions(-) rename src/kiwano/{core => base}/Director.cpp (99%) rename src/kiwano/{core => base}/Director.h (98%) rename src/kiwano/{core => base}/Module.cpp (97%) rename src/kiwano/{core => base}/Module.h (100%) rename src/kiwano/{core => base}/ObjectBase.cpp (98%) rename src/kiwano/{core => base}/ObjectBase.h (98%) rename src/kiwano/{core => base}/RefCounter.cpp (97%) rename src/kiwano/{core => base}/RefCounter.h (100%) rename src/kiwano/{core => }/event/Event.cpp (76%) rename src/kiwano/{core => }/event/Event.h (98%) rename src/kiwano/{core => event}/EventDispatcher.cpp (98%) rename src/kiwano/{core => event}/EventDispatcher.h (98%) rename src/kiwano/{core => event}/EventListener.cpp (97%) rename src/kiwano/{core => event}/EventListener.h (96%) rename src/kiwano/{core => }/event/EventType.h (100%) create mode 100644 src/kiwano/event/Events.h rename src/kiwano/{core => }/event/KeyEvent.cpp (90%) rename src/kiwano/{core => }/event/KeyEvent.h (98%) rename src/kiwano/{core => }/event/MouseEvent.cpp (94%) rename src/kiwano/{core => }/event/MouseEvent.h (98%) rename src/kiwano/{core => }/event/WindowEvent.cpp (94%) rename src/kiwano/{core => }/event/WindowEvent.h (98%) rename src/kiwano/{core => utils}/Logger.cpp (99%) rename src/kiwano/{core => utils}/Logger.h (100%) diff --git a/projects/kiwano/kiwano.vcxproj b/projects/kiwano/kiwano.vcxproj index 2161d336..3946e0bf 100644 --- a/projects/kiwano/kiwano.vcxproj +++ b/projects/kiwano/kiwano.vcxproj @@ -12,16 +12,14 @@ + + + + - - - - - - @@ -31,6 +29,14 @@ + + + + + + + + @@ -43,12 +49,6 @@ - - - - - - @@ -98,6 +98,7 @@ + @@ -126,23 +127,22 @@ + + + + - - - - - - - - - - - + + + + + + @@ -174,6 +174,7 @@ + diff --git a/projects/kiwano/kiwano.vcxproj.filters b/projects/kiwano/kiwano.vcxproj.filters index 4bbf8004..06293856 100644 --- a/projects/kiwano/kiwano.vcxproj.filters +++ b/projects/kiwano/kiwano.vcxproj.filters @@ -22,15 +22,18 @@ {e84dcf9a-e650-473e-8c9c-193804ab9e76} - - {c629aedd-ffb9-4bc1-82c3-f50e77c82e77} - {adb44ca9-674a-4b77-993f-d65193d8ab06} {fd281702-0006-46d2-8fd1-28c502464164} + + {f514ae4f-2f6a-4d47-aa38-245628d6e01c} + + + {b0d28d20-bfaf-4816-8415-28c20ecf9fac} + @@ -42,12 +45,6 @@ 2d - - core - - - core - core @@ -108,12 +105,6 @@ 2d\action - - core - - - core - utils @@ -135,36 +126,15 @@ 2d - - core - platform\win32 platform\win32 - - core\event - - - core\event - - - core\event - - - core\event - - - core\event - 2d - - core - core @@ -267,9 +237,6 @@ render - - core - platform @@ -339,6 +306,45 @@ render\DirectX + + utils + + + base + + + base + + + base + + + base + + + event + + + event + + + event + + + event + + + event + + + event + + + event + + + event + @@ -350,12 +356,6 @@ 2d - - core - - - core - core @@ -398,12 +398,6 @@ 2d\action - - core - - - core - utils @@ -425,30 +419,12 @@ 2d - - core - platform\win32 - - core\event - - - core\event - - - core\event - - - core\event - 2d - - core - platform\win32 @@ -518,9 +494,6 @@ render - - core - platform @@ -560,6 +533,39 @@ 2d\action + + utils + + + base + + + base + + + base + + + base + + + event + + + event + + + event + + + event + + + event + + + event + diff --git a/src/kiwano-audio/AudioModule.cpp b/src/kiwano-audio/AudioModule.cpp index 8b0fbeb2..d8d2c189 100644 --- a/src/kiwano-audio/AudioModule.cpp +++ b/src/kiwano-audio/AudioModule.cpp @@ -20,8 +20,8 @@ #include #include -#include #include +#include namespace kiwano { diff --git a/src/kiwano-audio/AudioModule.h b/src/kiwano-audio/AudioModule.h index 9d69c4de..a97e4078 100644 --- a/src/kiwano-audio/AudioModule.h +++ b/src/kiwano-audio/AudioModule.h @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include namespace kiwano diff --git a/src/kiwano-audio/Sound.cpp b/src/kiwano-audio/Sound.cpp index f344e118..99a590c3 100644 --- a/src/kiwano-audio/Sound.cpp +++ b/src/kiwano-audio/Sound.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include #include namespace kiwano diff --git a/src/kiwano-audio/Sound.h b/src/kiwano-audio/Sound.h index 375da28d..299d9083 100644 --- a/src/kiwano-audio/Sound.h +++ b/src/kiwano-audio/Sound.h @@ -20,8 +20,8 @@ #pragma once #include -#include #include +#include #include #include diff --git a/src/kiwano-audio/SoundPlayer.h b/src/kiwano-audio/SoundPlayer.h index 62d4e25c..789c66b5 100644 --- a/src/kiwano-audio/SoundPlayer.h +++ b/src/kiwano-audio/SoundPlayer.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include namespace kiwano { diff --git a/src/kiwano-audio/Transcoder.cpp b/src/kiwano-audio/Transcoder.cpp index 64af27c7..448e999e 100644 --- a/src/kiwano-audio/Transcoder.cpp +++ b/src/kiwano-audio/Transcoder.cpp @@ -25,9 +25,8 @@ #include #include #include -#include #include -#include +#include #include #include diff --git a/src/kiwano-imgui/ImGuiModule.cpp b/src/kiwano-imgui/ImGuiModule.cpp index 4d9763f9..d5025254 100644 --- a/src/kiwano-imgui/ImGuiModule.cpp +++ b/src/kiwano-imgui/ImGuiModule.cpp @@ -2,8 +2,7 @@ #include -#include -#include +#include #include #include #include diff --git a/src/kiwano-imgui/ImGuiModule.h b/src/kiwano-imgui/ImGuiModule.h index ce4ac610..b5c2d159 100644 --- a/src/kiwano-imgui/ImGuiModule.h +++ b/src/kiwano-imgui/ImGuiModule.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include #include namespace kiwano diff --git a/src/kiwano-network/HttpModule.cpp b/src/kiwano-network/HttpModule.cpp index 6b3865e2..7bd9f26a 100644 --- a/src/kiwano-network/HttpModule.cpp +++ b/src/kiwano-network/HttpModule.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include #include #include #include diff --git a/src/kiwano-network/HttpModule.h b/src/kiwano-network/HttpModule.h index 59264e64..60d326d2 100644 --- a/src/kiwano-network/HttpModule.h +++ b/src/kiwano-network/HttpModule.h @@ -23,7 +23,7 @@ #include #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano-network/HttpRequest.h b/src/kiwano-network/HttpRequest.h index 626c3b56..1760c3ea 100644 --- a/src/kiwano-network/HttpRequest.h +++ b/src/kiwano-network/HttpRequest.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/2d/Actor.cpp b/src/kiwano/2d/Actor.cpp index 85cc83c3..f94ae3fa 100644 --- a/src/kiwano/2d/Actor.cpp +++ b/src/kiwano/2d/Actor.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/2d/Actor.h b/src/kiwano/2d/Actor.h index 8ebc92d2..802a70ed 100644 --- a/src/kiwano/2d/Actor.h +++ b/src/kiwano/2d/Actor.h @@ -20,9 +20,9 @@ #pragma once #include -#include +#include #include -#include +#include #include #include #include diff --git a/src/kiwano/2d/Canvas.cpp b/src/kiwano/2d/Canvas.cpp index 0a272d3e..aa9a0694 100644 --- a/src/kiwano/2d/Canvas.cpp +++ b/src/kiwano/2d/Canvas.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include namespace kiwano { diff --git a/src/kiwano/2d/Component.h b/src/kiwano/2d/Component.h index 3830b8ba..9d486cc6 100644 --- a/src/kiwano/2d/Component.h +++ b/src/kiwano/2d/Component.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include #include #include diff --git a/src/kiwano/2d/DebugActor.cpp b/src/kiwano/2d/DebugActor.cpp index 65d78975..9e39f268 100644 --- a/src/kiwano/2d/DebugActor.cpp +++ b/src/kiwano/2d/DebugActor.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #include #include diff --git a/src/kiwano/2d/ShapeActor.cpp b/src/kiwano/2d/ShapeActor.cpp index a9714e48..5186451a 100644 --- a/src/kiwano/2d/ShapeActor.cpp +++ b/src/kiwano/2d/ShapeActor.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/2d/Stage.cpp b/src/kiwano/2d/Stage.cpp index 24ae8606..ad4b3d36 100644 --- a/src/kiwano/2d/Stage.cpp +++ b/src/kiwano/2d/Stage.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/2d/TextActor.cpp b/src/kiwano/2d/TextActor.cpp index 5c8b7ea4..dfe0010d 100644 --- a/src/kiwano/2d/TextActor.cpp +++ b/src/kiwano/2d/TextActor.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/2d/Transition.cpp b/src/kiwano/2d/Transition.cpp index d831bc10..acf0c722 100644 --- a/src/kiwano/2d/Transition.cpp +++ b/src/kiwano/2d/Transition.cpp @@ -21,7 +21,7 @@ #include #include #include -#include +#include #include #include diff --git a/src/kiwano/2d/action/Action.h b/src/kiwano/2d/action/Action.h index 8bc67bbb..0df4595a 100644 --- a/src/kiwano/2d/action/Action.h +++ b/src/kiwano/2d/action/Action.h @@ -21,7 +21,7 @@ #pragma once #include #include -#include +#include #include #include #include diff --git a/src/kiwano/2d/action/ActionGroup.cpp b/src/kiwano/2d/action/ActionGroup.cpp index 520065c3..3aa633d5 100644 --- a/src/kiwano/2d/action/ActionGroup.cpp +++ b/src/kiwano/2d/action/ActionGroup.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/2d/action/ActionScheduler.cpp b/src/kiwano/2d/action/ActionScheduler.cpp index 4d8b8765..4e1fb3fb 100644 --- a/src/kiwano/2d/action/ActionScheduler.cpp +++ b/src/kiwano/2d/action/ActionScheduler.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/2d/action/ActionTween.h b/src/kiwano/2d/action/ActionTween.h index 6f271cd9..82b777ed 100644 --- a/src/kiwano/2d/action/ActionTween.h +++ b/src/kiwano/2d/action/ActionTween.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include namespace kiwano { diff --git a/src/kiwano/core/Director.cpp b/src/kiwano/base/Director.cpp similarity index 99% rename from src/kiwano/core/Director.cpp rename to src/kiwano/base/Director.cpp index 84f4612f..6b221030 100644 --- a/src/kiwano/core/Director.cpp +++ b/src/kiwano/base/Director.cpp @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/core/Director.h b/src/kiwano/base/Director.h similarity index 98% rename from src/kiwano/core/Director.h rename to src/kiwano/base/Director.h index 8aca9387..fd054672 100644 --- a/src/kiwano/core/Director.h +++ b/src/kiwano/base/Director.h @@ -22,7 +22,7 @@ #include #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/core/Module.cpp b/src/kiwano/base/Module.cpp similarity index 97% rename from src/kiwano/core/Module.cpp rename to src/kiwano/base/Module.cpp index 38a3182b..009100bb 100644 --- a/src/kiwano/core/Module.cpp +++ b/src/kiwano/base/Module.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include namespace kiwano { diff --git a/src/kiwano/core/Module.h b/src/kiwano/base/Module.h similarity index 100% rename from src/kiwano/core/Module.h rename to src/kiwano/base/Module.h diff --git a/src/kiwano/core/ObjectBase.cpp b/src/kiwano/base/ObjectBase.cpp similarity index 98% rename from src/kiwano/core/ObjectBase.cpp rename to src/kiwano/base/ObjectBase.cpp index 7fa059f2..588e0a6e 100644 --- a/src/kiwano/core/ObjectBase.cpp +++ b/src/kiwano/base/ObjectBase.cpp @@ -18,8 +18,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include -#include +#include +#include #include #include diff --git a/src/kiwano/core/ObjectBase.h b/src/kiwano/base/ObjectBase.h similarity index 98% rename from src/kiwano/core/ObjectBase.h rename to src/kiwano/base/ObjectBase.h index 38f3d653..6761c77c 100644 --- a/src/kiwano/core/ObjectBase.h +++ b/src/kiwano/base/ObjectBase.h @@ -19,11 +19,11 @@ // THE SOFTWARE. #pragma once +#include #include #include -#include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/core/RefCounter.cpp b/src/kiwano/base/RefCounter.cpp similarity index 97% rename from src/kiwano/core/RefCounter.cpp rename to src/kiwano/base/RefCounter.cpp index dec905ba..27e44e5e 100644 --- a/src/kiwano/core/RefCounter.cpp +++ b/src/kiwano/base/RefCounter.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include namespace kiwano { diff --git a/src/kiwano/core/RefCounter.h b/src/kiwano/base/RefCounter.h similarity index 100% rename from src/kiwano/core/RefCounter.h rename to src/kiwano/base/RefCounter.h diff --git a/src/kiwano/core/Exception.cpp b/src/kiwano/core/Exception.cpp index 09f454ac..f5346406 100644 --- a/src/kiwano/core/Exception.cpp +++ b/src/kiwano/core/Exception.cpp @@ -20,7 +20,7 @@ #include #include -#include +#include #if defined(KGE_PLATFORM_WINDOWS) #include diff --git a/src/kiwano/core/Exception.h b/src/kiwano/core/Exception.h index 9994c376..3ad24cfc 100644 --- a/src/kiwano/core/Exception.h +++ b/src/kiwano/core/Exception.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include #include #include diff --git a/src/kiwano/core/Resource.cpp b/src/kiwano/core/Resource.cpp index ad44a5ff..99424288 100644 --- a/src/kiwano/core/Resource.cpp +++ b/src/kiwano/core/Resource.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/core/SmartPtr.hpp b/src/kiwano/core/SmartPtr.hpp index ad01496c..f569bb2b 100644 --- a/src/kiwano/core/SmartPtr.hpp +++ b/src/kiwano/core/SmartPtr.hpp @@ -22,7 +22,7 @@ #include #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/core/Time.cpp b/src/kiwano/core/Time.cpp index cd3a1f1d..e08fba77 100644 --- a/src/kiwano/core/Time.cpp +++ b/src/kiwano/core/Time.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #include #include #include diff --git a/src/kiwano/core/event/Event.cpp b/src/kiwano/event/Event.cpp similarity index 76% rename from src/kiwano/core/event/Event.cpp rename to src/kiwano/event/Event.cpp index d793f723..b39e0fb0 100644 --- a/src/kiwano/core/event/Event.cpp +++ b/src/kiwano/event/Event.cpp @@ -1,4 +1,4 @@ -#include +#include namespace kiwano { diff --git a/src/kiwano/core/event/Event.h b/src/kiwano/event/Event.h similarity index 98% rename from src/kiwano/core/event/Event.h rename to src/kiwano/event/Event.h index 09d182e4..16242d27 100644 --- a/src/kiwano/core/event/Event.h +++ b/src/kiwano/event/Event.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/core/EventDispatcher.cpp b/src/kiwano/event/EventDispatcher.cpp similarity index 98% rename from src/kiwano/core/EventDispatcher.cpp rename to src/kiwano/event/EventDispatcher.cpp index 8bde41f2..fa97b779 100644 --- a/src/kiwano/core/EventDispatcher.cpp +++ b/src/kiwano/event/EventDispatcher.cpp @@ -18,8 +18,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include -#include +#include +#include namespace kiwano { diff --git a/src/kiwano/core/EventDispatcher.h b/src/kiwano/event/EventDispatcher.h similarity index 98% rename from src/kiwano/core/EventDispatcher.h rename to src/kiwano/event/EventDispatcher.h index 2eff0bf2..3f53cd81 100644 --- a/src/kiwano/core/EventDispatcher.h +++ b/src/kiwano/event/EventDispatcher.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include namespace kiwano { diff --git a/src/kiwano/core/EventListener.cpp b/src/kiwano/event/EventListener.cpp similarity index 97% rename from src/kiwano/core/EventListener.cpp rename to src/kiwano/event/EventListener.cpp index 79846f30..1549d5d3 100644 --- a/src/kiwano/core/EventListener.cpp +++ b/src/kiwano/event/EventListener.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include namespace kiwano { diff --git a/src/kiwano/core/EventListener.h b/src/kiwano/event/EventListener.h similarity index 96% rename from src/kiwano/core/EventListener.h rename to src/kiwano/event/EventListener.h index 2aee0e19..59d9a10d 100644 --- a/src/kiwano/core/EventListener.h +++ b/src/kiwano/event/EventListener.h @@ -20,13 +20,10 @@ #pragma once #include -#include +#include #include #include -#include -#include -#include -#include +#include namespace kiwano { diff --git a/src/kiwano/core/event/EventType.h b/src/kiwano/event/EventType.h similarity index 100% rename from src/kiwano/core/event/EventType.h rename to src/kiwano/event/EventType.h diff --git a/src/kiwano/event/Events.h b/src/kiwano/event/Events.h new file mode 100644 index 00000000..13312ad8 --- /dev/null +++ b/src/kiwano/event/Events.h @@ -0,0 +1,26 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#pragma once + +#include +#include +#include +#include diff --git a/src/kiwano/core/event/KeyEvent.cpp b/src/kiwano/event/KeyEvent.cpp similarity index 90% rename from src/kiwano/core/event/KeyEvent.cpp rename to src/kiwano/event/KeyEvent.cpp index 0d60eb22..f654ffd1 100644 --- a/src/kiwano/core/event/KeyEvent.cpp +++ b/src/kiwano/event/KeyEvent.cpp @@ -1,4 +1,4 @@ -#include +#include namespace kiwano { diff --git a/src/kiwano/core/event/KeyEvent.h b/src/kiwano/event/KeyEvent.h similarity index 98% rename from src/kiwano/core/event/KeyEvent.h rename to src/kiwano/event/KeyEvent.h index 66ac2cb7..a56ed119 100644 --- a/src/kiwano/core/event/KeyEvent.h +++ b/src/kiwano/event/KeyEvent.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include namespace kiwano { diff --git a/src/kiwano/core/event/MouseEvent.cpp b/src/kiwano/event/MouseEvent.cpp similarity index 94% rename from src/kiwano/core/event/MouseEvent.cpp rename to src/kiwano/event/MouseEvent.cpp index 81c84d1d..7833bea4 100644 --- a/src/kiwano/core/event/MouseEvent.cpp +++ b/src/kiwano/event/MouseEvent.cpp @@ -1,4 +1,4 @@ -#include +#include namespace kiwano { diff --git a/src/kiwano/core/event/MouseEvent.h b/src/kiwano/event/MouseEvent.h similarity index 98% rename from src/kiwano/core/event/MouseEvent.h rename to src/kiwano/event/MouseEvent.h index b6371797..29731d39 100644 --- a/src/kiwano/core/event/MouseEvent.h +++ b/src/kiwano/event/MouseEvent.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/core/event/WindowEvent.cpp b/src/kiwano/event/WindowEvent.cpp similarity index 94% rename from src/kiwano/core/event/WindowEvent.cpp rename to src/kiwano/event/WindowEvent.cpp index 37cafb2b..1d07214d 100644 --- a/src/kiwano/core/event/WindowEvent.cpp +++ b/src/kiwano/event/WindowEvent.cpp @@ -1,4 +1,4 @@ -#include +#include namespace kiwano { diff --git a/src/kiwano/core/event/WindowEvent.h b/src/kiwano/event/WindowEvent.h similarity index 98% rename from src/kiwano/core/event/WindowEvent.h rename to src/kiwano/event/WindowEvent.h index 26a28e0d..4370422d 100644 --- a/src/kiwano/core/event/WindowEvent.h +++ b/src/kiwano/event/WindowEvent.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include namespace kiwano { diff --git a/src/kiwano/kiwano.h b/src/kiwano/kiwano.h index 86e32e0f..8062e660 100644 --- a/src/kiwano/kiwano.h +++ b/src/kiwano/kiwano.h @@ -44,18 +44,30 @@ // #include -#include -#include -#include -#include -#include #include #include #include -#include -#include -#include -#include + +// +// base +// + +#include +#include +#include +#include + + +// +// event +// + +#include +#include +#include +#include +#include +#include // // renderer @@ -112,6 +124,7 @@ // utils // +#include #include #include #include diff --git a/src/kiwano/platform/Application.cpp b/src/kiwano/platform/Application.cpp index b3f0c3c2..78ac7109 100644 --- a/src/kiwano/platform/Application.cpp +++ b/src/kiwano/platform/Application.cpp @@ -20,8 +20,8 @@ #include #include -#include -#include +#include +#include #include #include #include diff --git a/src/kiwano/platform/Application.h b/src/kiwano/platform/Application.h index 5c2d4e87..2a803e1c 100644 --- a/src/kiwano/platform/Application.h +++ b/src/kiwano/platform/Application.h @@ -21,10 +21,10 @@ #pragma once #include #include -#include +#include #include #include -#include +#include #include #include #include diff --git a/src/kiwano/platform/Input.cpp b/src/kiwano/platform/Input.cpp index d79c49a5..8dd82307 100644 --- a/src/kiwano/platform/Input.cpp +++ b/src/kiwano/platform/Input.cpp @@ -18,9 +18,8 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include -#include -#include +#include +#include #include namespace kiwano diff --git a/src/kiwano/platform/Input.h b/src/kiwano/platform/Input.h index 0759bc55..d2a72793 100644 --- a/src/kiwano/platform/Input.h +++ b/src/kiwano/platform/Input.h @@ -21,9 +21,9 @@ #pragma once #include #include -#include +#include #include -#include +#include #include #include diff --git a/src/kiwano/platform/Window.h b/src/kiwano/platform/Window.h index 284cb1db..61324ba9 100644 --- a/src/kiwano/platform/Window.h +++ b/src/kiwano/platform/Window.h @@ -20,8 +20,8 @@ #pragma once #include -#include -#include +#include +#include #include namespace kiwano diff --git a/src/kiwano/platform/win32/WindowImpl.cpp b/src/kiwano/platform/win32/WindowImpl.cpp index 4bf1f36c..83116760 100644 --- a/src/kiwano/platform/win32/WindowImpl.cpp +++ b/src/kiwano/platform/win32/WindowImpl.cpp @@ -26,10 +26,8 @@ #include #include #include -#include -#include -#include -#include +#include +#include #include #include #include diff --git a/src/kiwano/platform/win32/libraries.cpp b/src/kiwano/platform/win32/libraries.cpp index ac0f6bbb..4505ee66 100644 --- a/src/kiwano/platform/win32/libraries.cpp +++ b/src/kiwano/platform/win32/libraries.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/render/Brush.cpp b/src/kiwano/render/Brush.cpp index bab76f91..f106f2de 100644 --- a/src/kiwano/render/Brush.cpp +++ b/src/kiwano/render/Brush.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include #include diff --git a/src/kiwano/render/DirectX/D2DDeviceResources.cpp b/src/kiwano/render/DirectX/D2DDeviceResources.cpp index 538725de..2062ac2d 100644 --- a/src/kiwano/render/DirectX/D2DDeviceResources.cpp +++ b/src/kiwano/render/DirectX/D2DDeviceResources.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #pragma comment(lib, "d2d1.lib") #pragma comment(lib, "dwrite.lib") diff --git a/src/kiwano/render/DirectX/D3D10DeviceResources.cpp b/src/kiwano/render/DirectX/D3D10DeviceResources.cpp index a5bc29e5..e10427db 100644 --- a/src/kiwano/render/DirectX/D3D10DeviceResources.cpp +++ b/src/kiwano/render/DirectX/D3D10DeviceResources.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include #pragma comment(lib, "d3d10_1.lib") diff --git a/src/kiwano/render/DirectX/D3D11DeviceResources.cpp b/src/kiwano/render/DirectX/D3D11DeviceResources.cpp index 65da7e5f..e767c848 100644 --- a/src/kiwano/render/DirectX/D3D11DeviceResources.cpp +++ b/src/kiwano/render/DirectX/D3D11DeviceResources.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include #include diff --git a/src/kiwano/render/DirectX/RenderContextImpl.cpp b/src/kiwano/render/DirectX/RenderContextImpl.cpp index cbf90978..25a4ada6 100644 --- a/src/kiwano/render/DirectX/RenderContextImpl.cpp +++ b/src/kiwano/render/DirectX/RenderContextImpl.cpp @@ -21,7 +21,7 @@ #include #include #include -#include +#include namespace kiwano { diff --git a/src/kiwano/render/DirectX/RendererImpl.cpp b/src/kiwano/render/DirectX/RendererImpl.cpp index de86e279..13e325b7 100644 --- a/src/kiwano/render/DirectX/RendererImpl.cpp +++ b/src/kiwano/render/DirectX/RendererImpl.cpp @@ -19,8 +19,8 @@ // THE SOFTWARE. #include -#include -#include +#include +#include #include #include #include diff --git a/src/kiwano/render/Frame.h b/src/kiwano/render/Frame.h index a425f22b..f0679724 100644 --- a/src/kiwano/render/Frame.h +++ b/src/kiwano/render/Frame.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include #include namespace kiwano diff --git a/src/kiwano/render/FrameSequence.cpp b/src/kiwano/render/FrameSequence.cpp index a5ce48fa..03fd4a85 100644 --- a/src/kiwano/render/FrameSequence.cpp +++ b/src/kiwano/render/FrameSequence.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include namespace kiwano { diff --git a/src/kiwano/render/GifImage.cpp b/src/kiwano/render/GifImage.cpp index 79e942f5..da775009 100644 --- a/src/kiwano/render/GifImage.cpp +++ b/src/kiwano/render/GifImage.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include #include diff --git a/src/kiwano/render/NativeObject.h b/src/kiwano/render/NativeObject.h index 4b83b322..fc020b23 100644 --- a/src/kiwano/render/NativeObject.h +++ b/src/kiwano/render/NativeObject.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include #if KGE_RENDER_ENGINE == KGE_RENDER_ENGINE_DIRECTX #include diff --git a/src/kiwano/render/Renderer.cpp b/src/kiwano/render/Renderer.cpp index f25086ef..be2226b2 100644 --- a/src/kiwano/render/Renderer.cpp +++ b/src/kiwano/render/Renderer.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #include namespace kiwano diff --git a/src/kiwano/render/Renderer.h b/src/kiwano/render/Renderer.h index 7b80dae3..68077fa1 100644 --- a/src/kiwano/render/Renderer.h +++ b/src/kiwano/render/Renderer.h @@ -19,7 +19,7 @@ // THE SOFTWARE. #pragma once -#include +#include #include #include #include diff --git a/src/kiwano/render/TextureCache.cpp b/src/kiwano/render/TextureCache.cpp index 27b74545..847ece2b 100644 --- a/src/kiwano/render/TextureCache.cpp +++ b/src/kiwano/render/TextureCache.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include #include diff --git a/src/kiwano/utils/EventTicker.h b/src/kiwano/utils/EventTicker.h index 3fffff84..c1fd82d3 100644 --- a/src/kiwano/utils/EventTicker.h +++ b/src/kiwano/utils/EventTicker.h @@ -20,8 +20,8 @@ #pragma once #include -#include -#include +#include +#include namespace kiwano { diff --git a/src/kiwano/utils/LocalStorage.h b/src/kiwano/utils/LocalStorage.h index 6972a5c9..d3475cab 100644 --- a/src/kiwano/utils/LocalStorage.h +++ b/src/kiwano/utils/LocalStorage.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include namespace kiwano { diff --git a/src/kiwano/core/Logger.cpp b/src/kiwano/utils/Logger.cpp similarity index 99% rename from src/kiwano/core/Logger.cpp rename to src/kiwano/utils/Logger.cpp index 25400f0a..cc1c42e9 100644 --- a/src/kiwano/core/Logger.cpp +++ b/src/kiwano/utils/Logger.cpp @@ -21,7 +21,7 @@ #include #include #include -#include +#include namespace { diff --git a/src/kiwano/core/Logger.h b/src/kiwano/utils/Logger.h similarity index 100% rename from src/kiwano/core/Logger.h rename to src/kiwano/utils/Logger.h diff --git a/src/kiwano/utils/ResourceCache.cpp b/src/kiwano/utils/ResourceCache.cpp index 11398a40..be4b75bb 100644 --- a/src/kiwano/utils/ResourceCache.cpp +++ b/src/kiwano/utils/ResourceCache.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #include #include #include diff --git a/src/kiwano/utils/TaskScheduler.cpp b/src/kiwano/utils/TaskScheduler.cpp index c06d88da..40030c4d 100644 --- a/src/kiwano/utils/TaskScheduler.cpp +++ b/src/kiwano/utils/TaskScheduler.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include namespace kiwano diff --git a/src/kiwano/utils/Timer.h b/src/kiwano/utils/Timer.h index 29cb6a1a..ab20f4dc 100644 --- a/src/kiwano/utils/Timer.h +++ b/src/kiwano/utils/Timer.h @@ -20,7 +20,7 @@ #pragma once #include -#include +#include namespace kiwano { From dc6dd682ff95318a1f54d734c5f5237262589d34 Mon Sep 17 00:00:00 2001 From: Nomango Date: Sun, 24 May 2020 12:00:47 +0800 Subject: [PATCH 30/37] add ClockTime --- src/kiwano/core/Time.cpp | 82 ++++++++++++++++++++++++++++++++++++++++ src/kiwano/core/Time.h | 45 ++++++++++++++++++++++ 2 files changed, 127 insertions(+) diff --git a/src/kiwano/core/Time.cpp b/src/kiwano/core/Time.cpp index e08fba77..969c4bee 100644 --- a/src/kiwano/core/Time.cpp +++ b/src/kiwano/core/Time.cpp @@ -98,6 +98,88 @@ Time Time::Now() noexcept #endif } +//------------------------------------------------------- +// ClockTime +//------------------------------------------------------- + +ClockTime::ClockTime() + : ms_since_epoch_(0) +{ +} + +long ClockTime::GetTimeStamp() const +{ + using std::chrono::duration_cast; + using std::chrono::milliseconds; + using std::chrono::seconds; + + const auto timestamp = duration_cast(milliseconds(ms_since_epoch_)).count(); + return static_cast(timestamp); +} + +long ClockTime::GetMillisecondsSinceEpoch() const +{ + return ms_since_epoch_; +} + +std::time_t ClockTime::GetCTime() const +{ + return static_cast(GetTimeStamp()); +} + +ClockTime::ClockTime(long ms_since_epoch) + : ms_since_epoch_(ms_since_epoch) +{ +} + +ClockTime ClockTime::FromTimeStamp(long timestamp) noexcept +{ + using std::chrono::duration_cast; + using std::chrono::milliseconds; + using std::chrono::seconds; + + const auto ms = duration_cast(seconds(timestamp)).count(); + return ClockTime(static_cast(ms)); +} + +ClockTime ClockTime::Now() noexcept +{ + using std::chrono::duration_cast; + using std::chrono::milliseconds; + using std::chrono::system_clock; + + const auto now = system_clock::now(); + const long long count = duration_cast(now.time_since_epoch()).count(); + return ClockTime{ static_cast(count) }; +} + +const Duration ClockTime::operator-(const ClockTime& other) const +{ + return Duration(ms_since_epoch_ - other.ms_since_epoch_); +} + +const ClockTime ClockTime::operator+(const Duration& dur) const +{ + return ClockTime{ ms_since_epoch_ + dur.Milliseconds() }; +} + +const ClockTime ClockTime::operator-(const Duration& dur) const +{ + return ClockTime{ ms_since_epoch_ - dur.Milliseconds() }; +} + +ClockTime& ClockTime::operator+=(const Duration& other) +{ + ms_since_epoch_ += other.Milliseconds(); + return (*this); +} + +ClockTime& ClockTime::operator-=(const Duration& other) +{ + ms_since_epoch_ -= other.Milliseconds(); + return (*this); +} + //------------------------------------------------------- // Duration //------------------------------------------------------- diff --git a/src/kiwano/core/Time.h b/src/kiwano/core/Time.h index e563c440..5f86341e 100644 --- a/src/kiwano/core/Time.h +++ b/src/kiwano/core/Time.h @@ -20,6 +20,7 @@ #pragma once #include +#include namespace kiwano { @@ -198,6 +199,49 @@ private: long dur_; }; +/** + * \~chinese + * @brief 时钟时间 + */ +struct KGE_API ClockTime +{ + ClockTime(); + + /// \~chinese + /// @brief 获取当前时间戳 + long GetTimeStamp() const; + + /// \~chinese + /// @brief 获取自纪元以来的毫秒数 + long GetMillisecondsSinceEpoch() const; + + /// \~chinese + /// @brief 获取 C 风格的时间 + std::time_t GetCTime() const; + + /// \~chinese + /// @brief 获取当前时间 + static ClockTime Now() noexcept; + + /// \~chinese + /// @brief 时间戳转化为时间 + static ClockTime FromTimeStamp(long timestamp) noexcept; + + const Duration operator-(const ClockTime&) const; + + const ClockTime operator+(const Duration&) const; + const ClockTime operator-(const Duration&) const; + + ClockTime& operator+=(const Duration&); + ClockTime& operator-=(const Duration&); + +private: + ClockTime(long ms_since_epoch); + +private: + long ms_since_epoch_; +}; + inline long Duration::Milliseconds() const { return milliseconds_; @@ -232,6 +276,7 @@ inline bool Time::IsZero() const { return dur_ == 0; } + } // namespace kiwano #if defined(KGE_HAS_LITERALS) From 76d488b4c5dcc9cc289ec265b22fbc08e5699002 Mon Sep 17 00:00:00 2001 From: Nomango Date: Sun, 24 May 2020 19:49:44 +0800 Subject: [PATCH 31/37] minor fixes --- src/kiwano-audio/libraries.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/kiwano-audio/libraries.cpp b/src/kiwano-audio/libraries.cpp index 9c124cd9..dc954079 100644 --- a/src/kiwano-audio/libraries.cpp +++ b/src/kiwano-audio/libraries.cpp @@ -19,7 +19,7 @@ // THE SOFTWARE. #include -#include +#include #include namespace kiwano From 6d1cf357306057ed3aae56a4e1abf0072345a080 Mon Sep 17 00:00:00 2001 From: Nomango Date: Sun, 24 May 2020 20:46:52 +0800 Subject: [PATCH 32/37] refactoring project --- projects/kiwano/kiwano.vcxproj | 14 +- projects/kiwano/kiwano.vcxproj.filters | 45 +++--- src/kiwano/2d/Actor.cpp | 123 +-------------- src/kiwano/2d/Actor.h | 40 +---- src/kiwano/2d/action/Action.h | 4 - src/kiwano/2d/action/ActionScheduler.h | 4 + src/kiwano/{2d => base/component}/Button.cpp | 2 +- src/kiwano/{2d => base/component}/Button.h | 0 .../{2d => base/component}/Component.cpp | 2 +- src/kiwano/{2d => base/component}/Component.h | 7 +- .../base/component/ComponentManager.cpp | 148 ++++++++++++++++++ src/kiwano/base/component/ComponentManager.h | 92 +++++++++++ src/kiwano/event/EventDispatcher.h | 5 + src/kiwano/event/EventListener.h | 4 - src/kiwano/kiwano.h | 4 +- src/kiwano/utils/Task.h | 4 - src/kiwano/utils/TaskScheduler.h | 5 + 17 files changed, 305 insertions(+), 198 deletions(-) rename src/kiwano/{2d => base/component}/Button.cpp (98%) rename src/kiwano/{2d => base/component}/Button.h (100%) rename src/kiwano/{2d => base/component}/Component.cpp (97%) rename src/kiwano/{2d => base/component}/Component.h (96%) create mode 100644 src/kiwano/base/component/ComponentManager.cpp create mode 100644 src/kiwano/base/component/ComponentManager.h diff --git a/projects/kiwano/kiwano.vcxproj b/projects/kiwano/kiwano.vcxproj index 3946e0bf..06fa487e 100644 --- a/projects/kiwano/kiwano.vcxproj +++ b/projects/kiwano/kiwano.vcxproj @@ -9,9 +9,11 @@ - - + + + + @@ -44,7 +46,6 @@ - @@ -115,18 +116,19 @@ - + - - + + + diff --git a/projects/kiwano/kiwano.vcxproj.filters b/projects/kiwano/kiwano.vcxproj.filters index 06293856..9a950f94 100644 --- a/projects/kiwano/kiwano.vcxproj.filters +++ b/projects/kiwano/kiwano.vcxproj.filters @@ -34,6 +34,9 @@ {b0d28d20-bfaf-4816-8415-28c20ecf9fac} + + {d15f4de1-7c2c-40d6-a3ce-68860b95a61e} + @@ -69,9 +72,6 @@ 2d - - 2d - 2d @@ -132,9 +132,6 @@ platform\win32 - - 2d - core @@ -261,9 +258,6 @@ render - - 2d - core @@ -345,6 +339,18 @@ event + + 2d + + + base\component + + + base\component + + + base\component + @@ -365,9 +371,6 @@ 2d - - 2d - 2d @@ -422,9 +425,6 @@ platform\win32 - - 2d - platform\win32 @@ -503,9 +503,6 @@ render - - 2d - core @@ -566,6 +563,18 @@ event + + 2d + + + base\component + + + base\component + + + base\component + diff --git a/src/kiwano/2d/Actor.cpp b/src/kiwano/2d/Actor.cpp index f94ae3fa..5f54647c 100644 --- a/src/kiwano/2d/Actor.cpp +++ b/src/kiwano/2d/Actor.cpp @@ -46,7 +46,8 @@ ActorPtr Actor::Create() } Actor::Actor() - : visible_(true) + : ComponentManager(this) + , visible_(true) , visible_in_rt_(true) , update_pausing_(false) , hover_(false) @@ -79,7 +80,7 @@ void Actor::Update(Duration dt) { ActionScheduler::Update(this, dt); TaskScheduler::Update(dt); - UpdateComponents(dt); + ComponentManager::Update(dt); if (!update_pausing_) { @@ -112,7 +113,7 @@ void Actor::Render(RenderContext& ctx) if (CheckVisibility(ctx)) { PrepareToRender(ctx); - RenderComponents(ctx); + ComponentManager::Render(ctx); OnRender(ctx); } } @@ -132,7 +133,7 @@ void Actor::Render(RenderContext& ctx) if (CheckVisibility(ctx)) { PrepareToRender(ctx); - RenderComponents(ctx); + ComponentManager::Render(ctx); OnRender(ctx); } @@ -242,19 +243,7 @@ void Actor::DoDeserialize(Deserializer* deserializer) bool Actor::HandleEvent(Event* evt) { - if (!components_.IsEmpty()) - { - ComponentPtr next; - for (auto component = components_.GetFirst(); component; component = next) - { - next = component->GetNext(); - - if (component->IsEnable()) - { - component->HandleEvent(evt); - } - } - } + ComponentManager::DispatchToComponents(evt); if (!EventDispatcher::DispatchEvent(evt)) return false; @@ -304,40 +293,6 @@ bool Actor::HandleEvent(Event* evt) return true; } -void Actor::UpdateComponents(Duration dt) -{ - if (!components_.IsEmpty()) - { - ComponentPtr next; - for (auto component = components_.GetFirst(); component; component = next) - { - next = component->GetNext(); - - if (component->IsEnable()) - { - component->OnUpdate(dt); - } - } - } -} - -void Actor::RenderComponents(RenderContext& ctx) -{ - if (!components_.IsEmpty()) - { - ComponentPtr next; - for (auto component = components_.GetFirst(); component; component = next) - { - next = component->GetNext(); - - if (component->IsEnable()) - { - component->OnRender(ctx); - } - } - } -} - const Matrix3x2& Actor::GetTransformMatrix() const { UpdateTransform(); @@ -657,72 +612,6 @@ void Actor::RemoveFromParent() } } -Component* Actor::AddComponent(ComponentPtr component) -{ - KGE_ASSERT(component && "AddComponent failed, NULL pointer exception"); - - if (component) - { - component->InitComponent(this); - components_.PushBack(component); - } - return component.Get(); -} - -ComponentList& Actor::GetAllComponents() -{ - return components_; -} - -const ComponentList& Actor::GetAllComponents() const -{ - return components_; -} - -void Actor::RemoveComponent(ComponentPtr component) -{ - auto iter = std::find(components_.begin(), components_.end(), component); - if (iter != components_.end()) - { - component->DestroyComponent(); - components_.Remove(component); - } -} - -void Actor::RemoveComponents(const String& name) -{ - if (!components_.IsEmpty()) - { - ComponentPtr next; - for (auto component = components_.GetFirst(); component; component = next) - { - next = component->GetNext(); - - if (component->IsName(name)) - { - component->DestroyComponent(); - components_.Remove(component); - } - } - } -} - -void Actor::RemoveAllComponents() -{ - // Destroy all components - if (!components_.IsEmpty()) - { - ComponentPtr next; - for (auto component = components_.GetFirst(); component; component = next) - { - next = component->GetNext(); - - component->DestroyComponent(); - } - } - components_.Clear(); -} - void Actor::RemoveChild(ActorPtr child) { KGE_ASSERT(child && "Actor::RemoveChild failed, NULL pointer exception"); diff --git a/src/kiwano/2d/Actor.h b/src/kiwano/2d/Actor.h index 802a70ed..f0e258a0 100644 --- a/src/kiwano/2d/Actor.h +++ b/src/kiwano/2d/Actor.h @@ -20,12 +20,12 @@ #pragma once #include -#include #include +#include +#include #include #include #include -#include namespace kiwano { @@ -65,6 +65,7 @@ class KGE_API Actor , public TaskScheduler , public ActionScheduler , public EventDispatcher + , public ComponentManager , protected IntrusiveListValue { friend class Director; @@ -370,32 +371,6 @@ public: /// @brief 从父角色移除 void RemoveFromParent(); - /// \~chinese - /// @brief 添加组件 - /// @param component 组件 - Component* AddComponent(ComponentPtr component); - - /// \~chinese - /// @brief 获取所有组件 - ComponentList& GetAllComponents(); - - /// \~chinese - /// @brief 获取所有组件 - const ComponentList& GetAllComponents() const; - - /// \~chinese - /// @brief 移除组件 - void RemoveComponent(ComponentPtr component); - - /// \~chinese - /// @brief 移除组件 - /// @param name 组件名称 - void RemoveComponents(const String& name); - - /// \~chinese - /// @brief 移除所有组件 - void RemoveAllComponents(); - /// \~chinese /// @brief 暂停角色更新 void PauseUpdating(); @@ -499,14 +474,6 @@ protected: /// @brief 处理事件 bool HandleEvent(Event* evt); - /// \~chinese - /// @brief 更新组件 - void UpdateComponents(Duration dt); - - /// \~chinese - /// @brief 渲染组件 - void RenderComponents(RenderContext& ctx); - private: bool visible_; bool update_pausing_; @@ -524,7 +491,6 @@ private: Point anchor_; Size size_; ActorList children_; - ComponentList components_; UpdateCallback cb_update_; Transform transform_; diff --git a/src/kiwano/2d/action/Action.h b/src/kiwano/2d/action/Action.h index 0df4595a..0de9a0a4 100644 --- a/src/kiwano/2d/action/Action.h +++ b/src/kiwano/2d/action/Action.h @@ -34,10 +34,6 @@ class ActionScheduler; KGE_DECLARE_SMART_PTR(Action); -/// \~chinese -/// @brief 动画列表 -typedef IntrusiveList ActionList; - /** * \~chinese * \defgroup Actions 动画 diff --git a/src/kiwano/2d/action/ActionScheduler.h b/src/kiwano/2d/action/ActionScheduler.h index 34d37421..ccbf4172 100644 --- a/src/kiwano/2d/action/ActionScheduler.h +++ b/src/kiwano/2d/action/ActionScheduler.h @@ -28,6 +28,10 @@ namespace kiwano * @{ */ +/// \~chinese +/// @brief 动画列表 +typedef IntrusiveList ActionList; + /** * \~chinese * @brief 动画调度器 diff --git a/src/kiwano/2d/Button.cpp b/src/kiwano/base/component/Button.cpp similarity index 98% rename from src/kiwano/2d/Button.cpp rename to src/kiwano/base/component/Button.cpp index 061c87fb..c37e207b 100644 --- a/src/kiwano/2d/Button.cpp +++ b/src/kiwano/base/component/Button.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include #include diff --git a/src/kiwano/2d/Button.h b/src/kiwano/base/component/Button.h similarity index 100% rename from src/kiwano/2d/Button.h rename to src/kiwano/base/component/Button.h diff --git a/src/kiwano/2d/Component.cpp b/src/kiwano/base/component/Component.cpp similarity index 97% rename from src/kiwano/2d/Component.cpp rename to src/kiwano/base/component/Component.cpp index a22a9c22..7fbdb59e 100644 --- a/src/kiwano/2d/Component.cpp +++ b/src/kiwano/base/component/Component.cpp @@ -18,7 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -#include +#include #include namespace kiwano diff --git a/src/kiwano/2d/Component.h b/src/kiwano/base/component/Component.h similarity index 96% rename from src/kiwano/2d/Component.h rename to src/kiwano/base/component/Component.h index 9d486cc6..c48a168a 100644 --- a/src/kiwano/2d/Component.h +++ b/src/kiwano/base/component/Component.h @@ -29,6 +29,7 @@ namespace kiwano class Actor; class Event; +class ComponentManager; KGE_DECLARE_SMART_PTR(Component); @@ -42,10 +43,6 @@ KGE_DECLARE_SMART_PTR(Component); * @{ */ -/// \~chinese -/// @brief 组件列表 -typedef IntrusiveList ComponentList; - /** * \~chinese * @brief 组件 @@ -54,7 +51,7 @@ class KGE_API Component : public ObjectBase , protected IntrusiveListValue { - friend class Actor; + friend class ComponentManager; friend IntrusiveList; public: diff --git a/src/kiwano/base/component/ComponentManager.cpp b/src/kiwano/base/component/ComponentManager.cpp new file mode 100644 index 00000000..8f99ce75 --- /dev/null +++ b/src/kiwano/base/component/ComponentManager.cpp @@ -0,0 +1,148 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#include + +namespace kiwano +{ + +ComponentManager::ComponentManager(Actor* target) + : target_(target) +{ +} + +Component* ComponentManager::AddComponent(ComponentPtr component) +{ + KGE_ASSERT(component && "AddComponent failed, NULL pointer exception"); + + if (component) + { + component->InitComponent(target_); + components_.PushBack(component); + } + return component.Get(); +} + +ComponentList& ComponentManager::GetAllComponents() +{ + return components_; +} + +const ComponentList& ComponentManager::GetAllComponents() const +{ + return components_; +} + +void ComponentManager::RemoveComponent(ComponentPtr component) +{ + auto iter = std::find(components_.begin(), components_.end(), component); + if (iter != components_.end()) + { + component->DestroyComponent(); + components_.Remove(component); + } +} + +void ComponentManager::RemoveComponents(const String& name) +{ + if (!components_.IsEmpty()) + { + ComponentPtr next; + for (auto component = components_.GetFirst(); component; component = next) + { + next = component->GetNext(); + + if (component->IsName(name)) + { + component->DestroyComponent(); + components_.Remove(component); + } + } + } +} + +void ComponentManager::RemoveAllComponents() +{ + // Destroy all components + if (!components_.IsEmpty()) + { + ComponentPtr next; + for (auto component = components_.GetFirst(); component; component = next) + { + next = component->GetNext(); + + component->DestroyComponent(); + } + } + components_.Clear(); +} + +void ComponentManager::Update(Duration dt) +{ + if (!components_.IsEmpty()) + { + ComponentPtr next; + for (auto component = components_.GetFirst(); component; component = next) + { + next = component->GetNext(); + + if (component->IsEnable()) + { + component->OnUpdate(dt); + } + } + } +} + +void ComponentManager::Render(RenderContext& ctx) +{ + if (!components_.IsEmpty()) + { + ComponentPtr next; + for (auto component = components_.GetFirst(); component; component = next) + { + next = component->GetNext(); + + if (component->IsEnable()) + { + component->OnRender(ctx); + } + } + } +} + +void ComponentManager::DispatchToComponents(Event* evt) +{ + if (!components_.IsEmpty()) + { + ComponentPtr next; + for (auto component = components_.GetFirst(); component; component = next) + { + next = component->GetNext(); + + if (component->IsEnable()) + { + component->HandleEvent(evt); + } + } + } +} + +} // namespace kiwano diff --git a/src/kiwano/base/component/ComponentManager.h b/src/kiwano/base/component/ComponentManager.h new file mode 100644 index 00000000..469e7eaa --- /dev/null +++ b/src/kiwano/base/component/ComponentManager.h @@ -0,0 +1,92 @@ +// Copyright (c) 2016-2018 Kiwano - Nomango +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#pragma once +#include +#include + +namespace kiwano +{ + +/** + * \addtogroup Component + * @{ + */ + +/// \~chinese +/// @brief 组件列表 +typedef IntrusiveList ComponentList; + +/** + * \~chinese + * @brief 组件管理器 + */ +class KGE_API ComponentManager +{ +public: + /// \~chinese + /// @brief 添加组件 + /// @param component 组件 + Component* AddComponent(ComponentPtr component); + + /// \~chinese + /// @brief 获取所有组件 + ComponentList& GetAllComponents(); + + /// \~chinese + /// @brief 获取所有组件 + const ComponentList& GetAllComponents() const; + + /// \~chinese + /// @brief 移除组件 + void RemoveComponent(ComponentPtr component); + + /// \~chinese + /// @brief 移除组件 + /// @param name 组件名称 + void RemoveComponents(const String& name); + + /// \~chinese + /// @brief 移除所有组件 + void RemoveAllComponents(); + + /// \~chinese + /// @brief 更新组件 + void Update(Duration dt); + + /// \~chinese + /// @brief 渲染组件 + void Render(RenderContext& ctx); + + /// \~chinese + /// @brief 分发事件 + void DispatchToComponents(Event* evt); + +protected: + ComponentManager(Actor* target); + +private: + Actor* target_; + ComponentList components_; +}; + +/** @} */ + +} // namespace kiwano diff --git a/src/kiwano/event/EventDispatcher.h b/src/kiwano/event/EventDispatcher.h index 3f53cd81..35c286d2 100644 --- a/src/kiwano/event/EventDispatcher.h +++ b/src/kiwano/event/EventDispatcher.h @@ -23,6 +23,11 @@ namespace kiwano { + +/// \~chinese +/// @brief 监听器列表 +typedef IntrusiveList ListenerList; + /** * \~chinese * @brief 事件分发系统 diff --git a/src/kiwano/event/EventListener.h b/src/kiwano/event/EventListener.h index 59d9a10d..d179ba11 100644 --- a/src/kiwano/event/EventListener.h +++ b/src/kiwano/event/EventListener.h @@ -31,10 +31,6 @@ class EventDispatcher; KGE_DECLARE_SMART_PTR(EventListener); -/// \~chinese -/// @brief 监听器列表 -typedef IntrusiveList ListenerList; - /** * \~chinese * @brief 事件监听器 diff --git a/src/kiwano/kiwano.h b/src/kiwano/kiwano.h index 8062e660..50ef674e 100644 --- a/src/kiwano/kiwano.h +++ b/src/kiwano/kiwano.h @@ -56,6 +56,9 @@ #include #include #include +#include +#include +#include // @@ -91,7 +94,6 @@ // #include -#include #include #include #include diff --git a/src/kiwano/utils/Task.h b/src/kiwano/utils/Task.h index 30e4b652..09b27dba 100644 --- a/src/kiwano/utils/Task.h +++ b/src/kiwano/utils/Task.h @@ -28,10 +28,6 @@ class TaskScheduler; KGE_DECLARE_SMART_PTR(Task); -/// \~chinese -/// @brief 任务列表 -typedef IntrusiveList TaskList; - /// \~chinese /// @brief 任务 /// @details 任务用于每隔一段时间执行一次回调函数,且可以指定执行总次数 diff --git a/src/kiwano/utils/TaskScheduler.h b/src/kiwano/utils/TaskScheduler.h index 32ae2c33..65ee6b5a 100644 --- a/src/kiwano/utils/TaskScheduler.h +++ b/src/kiwano/utils/TaskScheduler.h @@ -23,6 +23,11 @@ namespace kiwano { + +/// \~chinese +/// @brief 任务列表 +typedef IntrusiveList TaskList; + /** * \~chinese * @brief 任务调度器 From 1af108df9061b0447fc8742cfff20e1d89991a89 Mon Sep 17 00:00:00 2001 From: Nomango Date: Mon, 25 May 2020 16:48:40 +0800 Subject: [PATCH 33/37] add Application::Pause & Application::Resume --- src/kiwano/2d/action/ActionScheduler.h | 1 + src/kiwano/core/Time.cpp | 12 ++++++++ src/kiwano/core/Time.h | 4 +++ src/kiwano/event/EventDispatcher.h | 2 +- src/kiwano/platform/Application.cpp | 39 +++++++++++++++++++----- src/kiwano/platform/Application.h | 33 ++++++++++++++------ src/kiwano/platform/Runner.cpp | 8 +++++ src/kiwano/platform/win32/WindowImpl.cpp | 30 +++--------------- src/kiwano/utils/TaskScheduler.cpp | 1 + 9 files changed, 86 insertions(+), 44 deletions(-) diff --git a/src/kiwano/2d/action/ActionScheduler.h b/src/kiwano/2d/action/ActionScheduler.h index ccbf4172..1cc4f26f 100644 --- a/src/kiwano/2d/action/ActionScheduler.h +++ b/src/kiwano/2d/action/ActionScheduler.h @@ -23,6 +23,7 @@ namespace kiwano { + /** * \addtogroup Actions * @{ diff --git a/src/kiwano/core/Time.cpp b/src/kiwano/core/Time.cpp index 969c4bee..b37c2189 100644 --- a/src/kiwano/core/Time.cpp +++ b/src/kiwano/core/Time.cpp @@ -24,6 +24,7 @@ #include #include #include +#include namespace kiwano { @@ -231,6 +232,17 @@ float Duration::Hours() const return static_cast(hour) + static_cast(ms) / (60 * 60 * 1000.f); } +void Duration::Sleep() const +{ + using std::chrono::milliseconds; + using std::this_thread::sleep_for; + + if (milliseconds_) + { + sleep_for(milliseconds(milliseconds_)); + } +} + String Duration::ToString() const { if (IsZero()) diff --git a/src/kiwano/core/Time.h b/src/kiwano/core/Time.h index 5f86341e..39e0edd8 100644 --- a/src/kiwano/core/Time.h +++ b/src/kiwano/core/Time.h @@ -96,6 +96,10 @@ struct KGE_API Duration /// @param hours 小时数 void SetHours(float hours); + /// \~chinese + /// @brief 休眠 + void Sleep() const; + /// \~chinese /// @brief 转为字符串 String ToString() const; diff --git a/src/kiwano/event/EventDispatcher.h b/src/kiwano/event/EventDispatcher.h index 35c286d2..6e5a0861 100644 --- a/src/kiwano/event/EventDispatcher.h +++ b/src/kiwano/event/EventDispatcher.h @@ -30,7 +30,7 @@ typedef IntrusiveList ListenerList; /** * \~chinese - * @brief 事件分发系统 + * @brief 事件分发器 */ class KGE_API EventDispatcher { diff --git a/src/kiwano/platform/Application.cpp b/src/kiwano/platform/Application.cpp index 78ac7109..52a1533f 100644 --- a/src/kiwano/platform/Application.cpp +++ b/src/kiwano/platform/Application.cpp @@ -36,11 +36,15 @@ int GetVersion() Application::Application() : running_(false) + , is_paused_(false) , time_scale_(1.f) { Use(Renderer::GetInstance()); Use(Input::GetInstance()); Use(Director::GetInstance()); + + ticker_ = Ticker::Create(0); + ticker_->Tick(); } Application::~Application() @@ -52,8 +56,8 @@ void Application::Run(RunnerPtr runner, bool debug) { KGE_ASSERT(runner); runner_ = runner; - timer_ = Timer::Create(); running_ = true; + is_paused_ = false; // Setup all modules for (auto c : modules_) @@ -72,15 +76,34 @@ void Application::Run(RunnerPtr runner, bool debug) while (running_) { - timer_->Tick(); - - if (!runner->MainLoop(timer_->GetDeltaTime())) - running_ = false; + if (ticker_->Tick()) + { + if (!runner->MainLoop(ticker_->GetDeltaTime())) + running_ = false; + } } this->Destroy(); } +void Application::Pause() +{ + is_paused_ = true; + if (ticker_) + { + ticker_->Pause(); + } +} + +void Application::Resume() +{ + is_paused_ = false; + if (ticker_) + { + ticker_->Resume(); + } +} + void Application::Quit() { running_ = false; @@ -130,7 +153,7 @@ void Application::DispatchEvent(EventPtr evt) void Application::DispatchEvent(Event* evt) { - if (!running_) + if (!running_ /* Dispatch events even if application is paused */) return; for (auto comp : modules_) @@ -144,7 +167,7 @@ void Application::DispatchEvent(Event* evt) void Application::Update(Duration dt) { - if (!running_) + if (!running_ || is_paused_) return; // Before update @@ -198,7 +221,7 @@ void Application::Update(Duration dt) void Application::Render() { - if (!running_) + if (!running_ /* Render even if application is paused */) return; Renderer& renderer = Renderer::GetInstance(); diff --git a/src/kiwano/platform/Application.h b/src/kiwano/platform/Application.h index 2a803e1c..10765c55 100644 --- a/src/kiwano/platform/Application.h +++ b/src/kiwano/platform/Application.h @@ -27,7 +27,7 @@ #include #include #include -#include +#include namespace kiwano { @@ -60,6 +60,18 @@ public: */ void Run(RunnerPtr runner, bool debug = false); + /** + * \~chinese + * @brief 暂停应用程序 + */ + void Pause(); + + /** + * \~chinese + * @brief 继续应用程序 + */ + void Resume(); + /** * \~chinese * @brief 终止应用程序 @@ -80,15 +92,15 @@ public: /** * \~chinese - * @brief 获取计时器 + * @brief 获取报时器 */ - TimerPtr GetTimer() const; + TickerPtr GetTicker() const; /** * \~chinese - * @brief 是否正在运行 + * @brief 获取暂停状态 */ - bool IsRunning() const; + bool IsPaused() const; /** * \~chinese @@ -151,9 +163,10 @@ public: private: bool running_; + bool is_paused_; float time_scale_; RunnerPtr runner_; - TimerPtr timer_; + TickerPtr ticker_; List modules_; std::mutex perform_mutex_; Queue> functions_to_perform_; @@ -170,14 +183,14 @@ inline WindowPtr Application::GetMainWindow() const return runner_->GetMainWindow(); } -inline TimerPtr Application::GetTimer() const +inline TickerPtr Application::GetTicker() const { - return timer_; + return ticker_; } -inline bool Application::IsRunning() const +inline bool Application::IsPaused() const { - return running_; + return is_paused_; } } // namespace kiwano diff --git a/src/kiwano/platform/Runner.cpp b/src/kiwano/platform/Runner.cpp index 7417b436..045e2dd4 100644 --- a/src/kiwano/platform/Runner.cpp +++ b/src/kiwano/platform/Runner.cpp @@ -21,6 +21,8 @@ #include #include +#define KGE_MAX_SKIP_FRAMES 10 + namespace kiwano { @@ -95,6 +97,12 @@ bool Runner::MainLoop(Duration dt) } app.Render(); + + if (app.IsPaused()) + { + // Slow down when the application is paused + Duration(5).Sleep(); + } return true; } diff --git a/src/kiwano/platform/win32/WindowImpl.cpp b/src/kiwano/platform/win32/WindowImpl.cpp index 83116760..4025a954 100644 --- a/src/kiwano/platform/win32/WindowImpl.cpp +++ b/src/kiwano/platform/win32/WindowImpl.cpp @@ -573,11 +573,7 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA is_minimized_ = true; // Pause game when window is minimized - if (Application::GetInstance().IsRunning()) - { - TimerPtr timer = Application::GetInstance().GetTimer(); - timer->Pause(); - } + Application::GetInstance().Pause(); } else if (SIZE_MAXIMIZED == wparam) { @@ -586,11 +582,7 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA if (is_minimized_) { is_minimized_ = false; - if (Application::GetInstance().IsRunning()) - { - TimerPtr timer = Application::GetInstance().GetTimer(); - timer->Resume(); - } + Application::GetInstance().Resume(); } } else if (wparam == SIZE_RESTORED) @@ -601,11 +593,7 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA // the window was restored and was previously minimized is_minimized_ = false; - if (Application::GetInstance().IsRunning()) - { - TimerPtr timer = Application::GetInstance().GetTimer(); - timer->Resume(); - } + Application::GetInstance().Resume(); } else if (is_resizing_) { @@ -630,22 +618,14 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA case WM_ENTERSIZEMOVE: { is_resizing_ = true; - if (Application::GetInstance().IsRunning()) - { - TimerPtr timer = Application::GetInstance().GetTimer(); - timer->Pause(); - } + Application::GetInstance().Pause(); return 0; } case WM_EXITSIZEMOVE: { is_resizing_ = false; - if (Application::GetInstance().IsRunning()) - { - TimerPtr timer = Application::GetInstance().GetTimer(); - timer->Resume(); - } + Application::GetInstance().Resume(); // Send window resized event when client size changed RECT client_rect = { 0 }; diff --git a/src/kiwano/utils/TaskScheduler.cpp b/src/kiwano/utils/TaskScheduler.cpp index 40030c4d..bf8ab4e3 100644 --- a/src/kiwano/utils/TaskScheduler.cpp +++ b/src/kiwano/utils/TaskScheduler.cpp @@ -23,6 +23,7 @@ namespace kiwano { + void TaskScheduler::Update(Duration dt) { if (tasks_.IsEmpty()) From c82fd84a0ddb9211884825c633164842098f10b2 Mon Sep 17 00:00:00 2001 From: Nomango Date: Tue, 26 May 2020 00:12:36 +0800 Subject: [PATCH 34/37] fix bugs --- src/kiwano/core/Allocator.cpp | 6 +- src/kiwano/platform/Runner.cpp | 3 + src/kiwano/platform/Window.h | 33 +++----- src/kiwano/platform/win32/WindowImpl.cpp | 82 +++++++------------- src/kiwano/render/DirectX/RendererImpl.cpp | 88 ++++++++-------------- src/kiwano/utils/Ticker.cpp | 14 ++++ src/kiwano/utils/Ticker.h | 10 --- 7 files changed, 95 insertions(+), 141 deletions(-) diff --git a/src/kiwano/core/Allocator.cpp b/src/kiwano/core/Allocator.cpp index 7b890e6a..99c37088 100644 --- a/src/kiwano/core/Allocator.cpp +++ b/src/kiwano/core/Allocator.cpp @@ -25,10 +25,14 @@ namespace kiwano namespace memory { -MemoryAllocator* current_allocator_ = GetGlobalAllocator(); +MemoryAllocator* current_allocator_ = nullptr; MemoryAllocator* GetAllocator() { + if (!current_allocator_) + { + current_allocator_ = GetGlobalAllocator(); + } return current_allocator_; } diff --git a/src/kiwano/platform/Runner.cpp b/src/kiwano/platform/Runner.cpp index 045e2dd4..333df2da 100644 --- a/src/kiwano/platform/Runner.cpp +++ b/src/kiwano/platform/Runner.cpp @@ -18,6 +18,7 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. +#include #include #include @@ -86,6 +87,8 @@ bool Runner::MainLoop(Duration dt) Application& app = Application::GetInstance(); + KGE_LOG(dt.Milliseconds()); + // Update modules before poll events app.Update(dt); diff --git a/src/kiwano/platform/Window.h b/src/kiwano/platform/Window.h index 61324ba9..08b9d25a 100644 --- a/src/kiwano/platform/Window.h +++ b/src/kiwano/platform/Window.h @@ -77,11 +77,10 @@ public: * @param height 高度 * @param icon 图标资源ID * @param resizable 窗口大小可拉伸 - * @param fullscreen 全屏模式 * @throw kiwano::SystemError 窗口创建失败时抛出 */ static WindowPtr Create(const String& title, uint32_t width, uint32_t height, uint32_t icon = 0, - bool resizable = false, bool fullscreen = false); + bool resizable = false); /** * \~chinese @@ -117,6 +116,12 @@ public: */ WindowHandle GetHandle() const; + /** + * \~chinese + * @brief 获取支持的屏幕分辨率列表 + */ + virtual Vector GetResolutions() = 0; + /** * \~chinese * @brief 设置标题 @@ -133,11 +138,12 @@ public: /** * \~chinese - * @brief 重设窗口大小 - * @param width 窗口宽度 - * @param height 窗口高度 + * @brief 设置窗口分辨率 + * @param width 分辨率宽度 + * @param height 分辨率高度 + * @param fullscreen 是否全屏 */ - virtual void Resize(uint32_t width, uint32_t height) = 0; + virtual void SetResolution(uint32_t width, uint32_t height, bool fullscreen) = 0; /** * \~chinese @@ -162,21 +168,6 @@ public: */ virtual void SetCursor(CursorType cursor) = 0; - /** - * \~chinese - * @brief 设置分辨率 - * @param width 分辨率宽度 - * @param height 分辨率高度 - * @param fullscreen 是否全屏 - */ - virtual void SetResolution(uint32_t width, uint32_t height, bool fullscreen) = 0; - - /** - * \~chinese - * @brief 获取支持的屏幕分辨率列表 - */ - virtual Vector GetResolutions() = 0; - /** * \~chinese * @brief 轮询窗口事件 diff --git a/src/kiwano/platform/win32/WindowImpl.cpp b/src/kiwano/platform/win32/WindowImpl.cpp index 4025a954..f6fe696f 100644 --- a/src/kiwano/platform/win32/WindowImpl.cpp +++ b/src/kiwano/platform/win32/WindowImpl.cpp @@ -47,14 +47,12 @@ public: virtual ~WindowWin32Impl(); - void Init(const String& title, uint32_t width, uint32_t height, uint32_t icon, bool resizable, bool fullscreen); + void Init(const String& title, uint32_t width, uint32_t height, uint32_t icon, bool resizable); void SetTitle(const String& title) override; void SetIcon(uint32_t icon_resource) override; - void Resize(uint32_t width, uint32_t height) override; - void SetMinimumSize(uint32_t width, uint32_t height) override; void SetMaximumSize(uint32_t width, uint32_t height) override; @@ -86,13 +84,12 @@ private: std::array key_map_; }; -WindowPtr Window::Create(const String& title, uint32_t width, uint32_t height, uint32_t icon, bool resizable, - bool fullscreen) +WindowPtr Window::Create(const String& title, uint32_t width, uint32_t height, uint32_t icon, bool resizable) { WindowWin32ImplPtr ptr = memory::New(); if (ptr) { - ptr->Init(title, width, height, icon, resizable, fullscreen); + ptr->Init(title, width, height, icon, resizable); } return ptr; } @@ -199,8 +196,7 @@ WindowWin32Impl::~WindowWin32Impl() } } -void WindowWin32Impl::Init(const String& title, uint32_t width, uint32_t height, uint32_t icon, bool resizable, - bool fullscreen) +void WindowWin32Impl::Init(const String& title, uint32_t width, uint32_t height, uint32_t icon, bool resizable) { HINSTANCE hinst = GetModuleHandle(nullptr); WNDCLASSEXA wcex = { 0 }; @@ -236,38 +232,22 @@ void WindowWin32Impl::Init(const String& title, uint32_t width, uint32_t height, // Save the device name device_name_ = monitor_info_ex.szDevice; - int left = -1, top = -1; + uint32_t screenw = monitor_info_ex.rcWork.right - monitor_info_ex.rcWork.left; + uint32_t screenh = monitor_info_ex.rcWork.bottom - monitor_info_ex.rcWork.top; - if (fullscreen) - { - top = monitor_info_ex.rcMonitor.top; - left = monitor_info_ex.rcMonitor.left; + uint32_t win_width, win_height; + AdjustWindow(width, height, GetStyle(), &win_width, &win_height); - if (width > static_cast(monitor_info_ex.rcWork.right - left)) - width = static_cast(monitor_info_ex.rcWork.right - left); - - if (height > static_cast(monitor_info_ex.rcWork.bottom - top)) - height = static_cast(monitor_info_ex.rcWork.bottom - top); - } - else - { - uint32_t screenw = monitor_info_ex.rcWork.right - monitor_info_ex.rcWork.left; - uint32_t screenh = monitor_info_ex.rcWork.bottom - monitor_info_ex.rcWork.top; - - uint32_t win_width, win_height; - AdjustWindow(width, height, GetStyle(), &win_width, &win_height); - - left = monitor_info_ex.rcWork.left + (screenw - win_width) / 2; - top = monitor_info_ex.rcWork.top + (screenh - win_height) / 2; - width = win_width; - height = win_height; - } + int left = monitor_info_ex.rcWork.left + (screenw - win_width) / 2; + int top = monitor_info_ex.rcWork.top + (screenh - win_height) / 2; + width = win_width; + height = win_height; width_ = width; height_ = height; resizable_ = resizable; - handle_ = ::CreateWindowExA(fullscreen ? WS_EX_TOPMOST : 0, "KiwanoAppWnd", title.c_str(), GetStyle(), left, top, - width, height, nullptr, nullptr, hinst, nullptr); + handle_ = ::CreateWindowExA(0, "KiwanoAppWnd", title.c_str(), GetStyle(), left, top, width, height, nullptr, + nullptr, hinst, nullptr); if (handle_ == nullptr) { @@ -283,6 +263,21 @@ void WindowWin32Impl::Init(const String& title, uint32_t width, uint32_t height, ::ShowWindow(handle_, SW_SHOWNORMAL); ::UpdateWindow(handle_); + + // Initialize Direct3D resources + auto d3d_res = graphics::directx::GetD3DDeviceResources(); + + HRESULT hr = d3d_res->Initialize(handle_); + + // Initialize Direct2D resources + if (SUCCEEDED(hr)) + { + auto d2d_res = graphics::directx::GetD2DDeviceResources(); + + hr = d2d_res->Initialize(d3d_res->GetDXGIDevice(), d3d_res->GetDXGISwapChain()); + } + + KGE_THROW_IF_FAILED(hr, "Create DirectX resources failed"); } void WindowWin32Impl::PumpEvents() @@ -313,25 +308,6 @@ void WindowWin32Impl::SetIcon(uint32_t icon_resource) ::SendMessage(handle_, WM_SETICON, ICON_SMALL, (LPARAM)icon); } -void WindowWin32Impl::Resize(uint32_t width, uint32_t height) -{ - KGE_ASSERT(handle_); - - RECT rc = { 0, 0, LONG(width), LONG(height) }; - ::AdjustWindowRect(&rc, GetStyle(), false); - - width = rc.right - rc.left; - height = rc.bottom - rc.top; - - MONITORINFOEXA info = GetMoniterInfoEx(handle_); - uint32_t screenw = uint32_t(info.rcWork.right - info.rcWork.left); - uint32_t screenh = uint32_t(info.rcWork.bottom - info.rcWork.top); - int left = screenw > width ? ((screenw - width) / 2) : 0; - int top = screenh > height ? ((screenh - height) / 2) : 0; - - ::SetWindowPos(handle_, 0, left, top, width, height, SWP_NOZORDER | SWP_NOACTIVATE); -} - void WindowWin32Impl::SetMinimumSize(uint32_t width, uint32_t height) { min_width_ = width; diff --git a/src/kiwano/render/DirectX/RendererImpl.cpp b/src/kiwano/render/DirectX/RendererImpl.cpp index 13e325b7..49f496d8 100644 --- a/src/kiwano/render/DirectX/RendererImpl.cpp +++ b/src/kiwano/render/DirectX/RendererImpl.cpp @@ -58,75 +58,51 @@ void RendererImpl::MakeContextForWindow(WindowPtr window) HWND target_window = window->GetHandle(); output_size_ = window->GetSize(); - d2d_res_ = nullptr; - d3d_res_ = nullptr; + d2d_res_ = graphics::directx::GetD2DDeviceResources(); + d3d_res_ = graphics::directx::GetD3DDeviceResources(); HRESULT hr = target_window ? S_OK : E_FAIL; - // Direct3D device resources + // Initialize other device resources if (SUCCEEDED(hr)) { - auto d3d_res = graphics::directx::GetD3DDeviceResources(); + RenderContextImplPtr ctx = memory::New(); - // Initialize Direct3D resources - hr = d3d_res->Initialize(target_window); - - // Direct2D device resources + hr = ctx->CreateDeviceResources(d2d_res_->GetFactory(), d2d_res_->GetDeviceContext()); if (SUCCEEDED(hr)) { - d3d_res_ = d3d_res; + render_ctx_ = ctx; + } + } - auto d2d_res = graphics::directx::GetD2DDeviceResources(); + // FontFileLoader and FontCollectionLoader + if (SUCCEEDED(hr)) + { + hr = IFontCollectionLoader::Create(&font_collection_loader_); - // Initialize Direct2D resources - hr = d2d_res->Initialize(d3d_res_->GetDXGIDevice(), d3d_res_->GetDXGISwapChain()); + if (SUCCEEDED(hr)) + { + hr = d2d_res_->GetDWriteFactory()->RegisterFontCollectionLoader(font_collection_loader_.Get()); + } + } + + // ResourceFontFileLoader and ResourceFontCollectionLoader + if (SUCCEEDED(hr)) + { + hr = IResourceFontFileLoader::Create(&res_font_file_loader_); + + if (SUCCEEDED(hr)) + { + hr = d2d_res_->GetDWriteFactory()->RegisterFontFileLoader(res_font_file_loader_.Get()); + } + + if (SUCCEEDED(hr)) + { + hr = IResourceFontCollectionLoader::Create(&res_font_collection_loader_, res_font_file_loader_.Get()); if (SUCCEEDED(hr)) { - d2d_res_ = d2d_res; - - // Initialize other device resources - RenderContextImplPtr ctx = memory::New(); - - hr = ctx->CreateDeviceResources(d2d_res_->GetFactory(), d2d_res_->GetDeviceContext()); - if (SUCCEEDED(hr)) - { - render_ctx_ = ctx; - } - } - - // FontFileLoader and FontCollectionLoader - if (SUCCEEDED(hr)) - { - hr = IFontCollectionLoader::Create(&font_collection_loader_); - - if (SUCCEEDED(hr)) - { - hr = d2d_res_->GetDWriteFactory()->RegisterFontCollectionLoader(font_collection_loader_.Get()); - } - } - - // ResourceFontFileLoader and ResourceFontCollectionLoader - if (SUCCEEDED(hr)) - { - hr = IResourceFontFileLoader::Create(&res_font_file_loader_); - - if (SUCCEEDED(hr)) - { - hr = d2d_res_->GetDWriteFactory()->RegisterFontFileLoader(res_font_file_loader_.Get()); - } - - if (SUCCEEDED(hr)) - { - hr = IResourceFontCollectionLoader::Create(&res_font_collection_loader_, - res_font_file_loader_.Get()); - - if (SUCCEEDED(hr)) - { - hr = d2d_res_->GetDWriteFactory()->RegisterFontCollectionLoader( - res_font_collection_loader_.Get()); - } - } + hr = d2d_res_->GetDWriteFactory()->RegisterFontCollectionLoader(res_font_collection_loader_.Get()); } } } diff --git a/src/kiwano/utils/Ticker.cpp b/src/kiwano/utils/Ticker.cpp index c072f580..c2037095 100644 --- a/src/kiwano/utils/Ticker.cpp +++ b/src/kiwano/utils/Ticker.cpp @@ -78,6 +78,20 @@ bool Ticker::Tick(Duration dt) return false; } +void Ticker::Pause() +{ + is_paused_ = true; + if (timer_) + timer_->Pause(); +} + +void Ticker::Resume() +{ + is_paused_ = false; + if (timer_) + timer_->Resume(); +} + Duration Ticker::GetDeltaTime() { return delta_time_; diff --git a/src/kiwano/utils/Ticker.h b/src/kiwano/utils/Ticker.h index 0fb86ab0..5ec16cdd 100644 --- a/src/kiwano/utils/Ticker.h +++ b/src/kiwano/utils/Ticker.h @@ -110,16 +110,6 @@ private: TimerPtr timer_; }; -inline void Ticker::Pause() -{ - is_paused_ = true; -} - -inline void Ticker::Resume() -{ - is_paused_ = false; -} - inline bool Ticker::IsPausing() const { return is_paused_; From f24342acbb6168e6ad163a52ac63dfd68a6c77b4 Mon Sep 17 00:00:00 2001 From: Nomango Date: Tue, 26 May 2020 00:57:07 +0800 Subject: [PATCH 35/37] update Time & Duration --- src/kiwano/core/Time.cpp | 84 ++++++++++++++++++++-------------------- src/kiwano/core/Time.h | 26 ++++++------- 2 files changed, 55 insertions(+), 55 deletions(-) diff --git a/src/kiwano/core/Time.cpp b/src/kiwano/core/Time.cpp index b37c2189..33b120d8 100644 --- a/src/kiwano/core/Time.cpp +++ b/src/kiwano/core/Time.cpp @@ -37,7 +37,7 @@ Time::Time() { } -Time::Time(long dur) +Time::Time(int64_t dur) : dur_(dur) { } @@ -84,7 +84,7 @@ Time Time::Now() noexcept LARGE_INTEGER count; QueryPerformanceCounter(&count); - return Time{ static_cast(count.QuadPart * millisecs_per_count) }; + return Time{ static_cast(count.QuadPart * millisecs_per_count) }; #else @@ -92,9 +92,9 @@ Time Time::Now() noexcept using std::chrono::duration_cast; using std::chrono::milliseconds; - const auto now = steady_clock::now(); - const long long count = duration_cast(now.time_since_epoch()).count(); - return Time{ static_cast(count) }; + const auto now = steady_clock::now(); + const auto count = duration_cast(now.time_since_epoch()).count(); + return Time{ static_cast(count) }; #endif } @@ -108,17 +108,17 @@ ClockTime::ClockTime() { } -long ClockTime::GetTimeStamp() const +int64_t ClockTime::GetTimeStamp() const { using std::chrono::duration_cast; using std::chrono::milliseconds; using std::chrono::seconds; const auto timestamp = duration_cast(milliseconds(ms_since_epoch_)).count(); - return static_cast(timestamp); + return static_cast(timestamp); } -long ClockTime::GetMillisecondsSinceEpoch() const +int64_t ClockTime::GetMillisecondsSinceEpoch() const { return ms_since_epoch_; } @@ -128,19 +128,19 @@ std::time_t ClockTime::GetCTime() const return static_cast(GetTimeStamp()); } -ClockTime::ClockTime(long ms_since_epoch) +ClockTime::ClockTime(int64_t ms_since_epoch) : ms_since_epoch_(ms_since_epoch) { } -ClockTime ClockTime::FromTimeStamp(long timestamp) noexcept +ClockTime ClockTime::FromTimeStamp(int64_t timestamp) noexcept { using std::chrono::duration_cast; using std::chrono::milliseconds; using std::chrono::seconds; const auto ms = duration_cast(seconds(timestamp)).count(); - return ClockTime(static_cast(ms)); + return ClockTime(static_cast(ms)); } ClockTime ClockTime::Now() noexcept @@ -149,9 +149,9 @@ ClockTime ClockTime::Now() noexcept using std::chrono::milliseconds; using std::chrono::system_clock; - const auto now = system_clock::now(); - const long long count = duration_cast(now.time_since_epoch()).count(); - return ClockTime{ static_cast(count) }; + const auto now = system_clock::now(); + const auto count = duration_cast(now.time_since_epoch()).count(); + return ClockTime{ static_cast(count) }; } const Duration ClockTime::operator-(const ClockTime& other) const @@ -206,30 +206,30 @@ Duration::Duration() { } -Duration::Duration(long milliseconds) +Duration::Duration(int64_t milliseconds) : milliseconds_(milliseconds) { } float Duration::Seconds() const { - long sec = milliseconds_ / Second.milliseconds_; - long ms = milliseconds_ % Second.milliseconds_; - return static_cast(sec) + static_cast(ms) / 1000.f; + auto sec = milliseconds_ / Second.milliseconds_; + auto ms = milliseconds_ % Second.milliseconds_; + return static_cast(sec + ms) / 1000.f; } float Duration::Minutes() const { - long min = milliseconds_ / Minute.milliseconds_; - long ms = milliseconds_ % Minute.milliseconds_; - return static_cast(min) + static_cast(ms) / (60 * 1000.f); + auto min = milliseconds_ / Minute.milliseconds_; + auto ms = milliseconds_ % Minute.milliseconds_; + return static_cast(min + ms) / (60 * 1000.f); } float Duration::Hours() const { - long hour = milliseconds_ / Hour.milliseconds_; - long ms = milliseconds_ % Hour.milliseconds_; - return static_cast(hour) + static_cast(ms) / (60 * 60 * 1000.f); + auto hour = milliseconds_ / Hour.milliseconds_; + auto ms = milliseconds_ % Hour.milliseconds_; + return static_cast(hour + ms) / (60 * 60 * 1000.f); } void Duration::Sleep() const @@ -250,18 +250,18 @@ String Duration::ToString() const return String("0s"); } - String result; - long total_ms = milliseconds_; + String result; + int64_t total_ms = milliseconds_; if (total_ms < 0) { result.append("-"); total_ms = -total_ms; } - long hour = total_ms / Hour.milliseconds_; - long min = total_ms / Minute.milliseconds_ - hour * 60; - long sec = total_ms / Second.milliseconds_ - (hour * 60 * 60 + min * 60); - long ms = total_ms % Second.milliseconds_; + int64_t hour = total_ms / Hour.milliseconds_; + int64_t min = total_ms / Minute.milliseconds_ - hour * 60; + int64_t sec = total_ms / Second.milliseconds_ - (hour * 60 * 60 + min * 60); + int64_t ms = total_ms % Second.milliseconds_; if (hour) { @@ -275,7 +275,7 @@ String Duration::ToString() const if (ms != 0) { - result.append(std::to_string(static_cast(sec) + static_cast(ms) / 1000.f)).append("s"); + result.append(std::to_string(static_cast(sec + ms) / 1000.f)).append("s"); } else if (sec != 0) { @@ -341,22 +341,22 @@ const Duration Duration::operator*(int val) const const Duration Duration::operator*(unsigned long long val) const { - return Duration(static_cast(milliseconds_ * val)); + return Duration(static_cast(milliseconds_ * val)); } const Duration Duration::operator*(float val) const { - return Duration(static_cast(milliseconds_ * val)); + return Duration(static_cast(milliseconds_ * val)); } const Duration Duration::operator*(double val) const { - return Duration(static_cast(milliseconds_ * val)); + return Duration(static_cast(milliseconds_ * val)); } const Duration Duration::operator*(long double val) const { - return Duration(static_cast(milliseconds_ * val)); + return Duration(static_cast(milliseconds_ * val)); } const Duration Duration::operator/(int val) const @@ -366,12 +366,12 @@ const Duration Duration::operator/(int val) const const Duration Duration::operator/(float val) const { - return Duration(static_cast(milliseconds_ / val)); + return Duration(static_cast(milliseconds_ / val)); } const Duration Duration::operator/(double val) const { - return Duration(static_cast(milliseconds_ / val)); + return Duration(static_cast(milliseconds_ / val)); } Duration& Duration::operator+=(const Duration& other) @@ -394,31 +394,31 @@ Duration& Duration::operator*=(int val) Duration& Duration::operator/=(int val) { - milliseconds_ = static_cast(milliseconds_ / val); + milliseconds_ = static_cast(milliseconds_ / val); return (*this); } Duration& Duration::operator*=(float val) { - milliseconds_ = static_cast(milliseconds_ * val); + milliseconds_ = static_cast(milliseconds_ * val); return (*this); } Duration& Duration::operator/=(float val) { - milliseconds_ = static_cast(milliseconds_ / val); + milliseconds_ = static_cast(milliseconds_ / val); return (*this); } Duration& Duration::operator*=(double val) { - milliseconds_ = static_cast(milliseconds_ * val); + milliseconds_ = static_cast(milliseconds_ * val); return (*this); } Duration& Duration::operator/=(double val) { - milliseconds_ = static_cast(milliseconds_ / val); + milliseconds_ = static_cast(milliseconds_ / val); return (*this); } diff --git a/src/kiwano/core/Time.h b/src/kiwano/core/Time.h index 39e0edd8..1cf09285 100644 --- a/src/kiwano/core/Time.h +++ b/src/kiwano/core/Time.h @@ -53,11 +53,11 @@ struct KGE_API Duration /// \~chinese /// @brief 构造时间段 /// @param milliseconds 毫秒数 - Duration(long milliseconds); + Duration(int64_t milliseconds); /// \~chinese /// @brief 获取毫秒数 - long Milliseconds() const; + int64_t Milliseconds() const; /// \~chinese /// @brief 获取秒数 @@ -79,7 +79,7 @@ struct KGE_API Duration /// \~chinese /// @brief 设置毫秒数 /// @param ms 毫秒数 - void SetMilliseconds(long ms); + void SetMilliseconds(int64_t ms); /// \~chinese /// @brief 设置秒数 @@ -159,7 +159,7 @@ struct KGE_API Duration friend const Duration operator/(double, const Duration&); private: - long milliseconds_; + int64_t milliseconds_; }; /** @@ -197,10 +197,10 @@ struct KGE_API Time Time& operator-=(const Duration&); private: - Time(long ms); + Time(int64_t ms); private: - long dur_; + int64_t dur_; }; /** @@ -213,11 +213,11 @@ struct KGE_API ClockTime /// \~chinese /// @brief 获取当前时间戳 - long GetTimeStamp() const; + int64_t GetTimeStamp() const; /// \~chinese /// @brief 获取自纪元以来的毫秒数 - long GetMillisecondsSinceEpoch() const; + int64_t GetMillisecondsSinceEpoch() const; /// \~chinese /// @brief 获取 C 风格的时间 @@ -229,7 +229,7 @@ struct KGE_API ClockTime /// \~chinese /// @brief 时间戳转化为时间 - static ClockTime FromTimeStamp(long timestamp) noexcept; + static ClockTime FromTimeStamp(int64_t timestamp) noexcept; const Duration operator-(const ClockTime&) const; @@ -240,13 +240,13 @@ struct KGE_API ClockTime ClockTime& operator-=(const Duration&); private: - ClockTime(long ms_since_epoch); + ClockTime(int64_t ms_since_epoch); private: - long ms_since_epoch_; + int64_t ms_since_epoch_; }; -inline long Duration::Milliseconds() const +inline int64_t Duration::Milliseconds() const { return milliseconds_; } @@ -256,7 +256,7 @@ inline bool Duration::IsZero() const return milliseconds_ == 0LL; } -inline void Duration::SetMilliseconds(long ms) +inline void Duration::SetMilliseconds(int64_t ms) { milliseconds_ = ms; } From 471b6983cd7715845f8e06982f093c3ce490364d Mon Sep 17 00:00:00 2001 From: Nomango Date: Tue, 26 May 2020 15:20:02 +0800 Subject: [PATCH 36/37] update Ticker --- src/kiwano/utils/EventTicker.cpp | 2 +- src/kiwano/utils/Task.cpp | 10 ++-------- src/kiwano/utils/Ticker.cpp | 12 ++++++------ src/kiwano/utils/Ticker.h | 26 +++++++++++++------------- 4 files changed, 22 insertions(+), 28 deletions(-) diff --git a/src/kiwano/utils/EventTicker.cpp b/src/kiwano/utils/EventTicker.cpp index f354f081..609a918c 100644 --- a/src/kiwano/utils/EventTicker.cpp +++ b/src/kiwano/utils/EventTicker.cpp @@ -35,7 +35,7 @@ EventTickerPtr EventTicker::Create(Duration interval, int times) if (ptr) { ptr->SetInterval(interval); - ptr->SetTotalTickTimes(times); + ptr->SetTotalTickCount(times); } return ptr; } diff --git a/src/kiwano/utils/Task.cpp b/src/kiwano/utils/Task.cpp index a1988735..89f25f24 100644 --- a/src/kiwano/utils/Task.cpp +++ b/src/kiwano/utils/Task.cpp @@ -64,13 +64,7 @@ Task::Task() void Task::Update(Duration dt) { - if (!ticker_) - { - Remove(); - return; - } - - if (ticker_->GetTotalTickTimes() == 0) + if (!ticker_ || ticker_->GetTotalTickCount() == 0) { Remove(); return; @@ -81,7 +75,7 @@ void Task::Update(Duration dt) if (callback_) callback_(this, ticker_->GetDeltaTime()); - if (ticker_->GetTickedTimes() == ticker_->GetTotalTickTimes()) + if (ticker_->GetTickedCount() == ticker_->GetTotalTickCount()) Remove(); } } diff --git a/src/kiwano/utils/Ticker.cpp b/src/kiwano/utils/Ticker.cpp index c2037095..d44dc5ac 100644 --- a/src/kiwano/utils/Ticker.cpp +++ b/src/kiwano/utils/Ticker.cpp @@ -29,14 +29,14 @@ TickerPtr Ticker::Create(Duration interval, int times) if (ptr) { ptr->SetInterval(interval); - ptr->SetTotalTickTimes(times); + ptr->SetTotalTickCount(times); } return ptr; } Ticker::Ticker() - : ticked_times_(0) - , total_times_(0) + : ticked_count_(0) + , total_tick_count_(0) , is_paused_(false) { } @@ -62,7 +62,7 @@ bool Ticker::Tick(Duration dt) if (is_paused_) return false; - if (ticked_times_ == total_times_) + if (ticked_count_ == total_tick_count_) return false; elapsed_time_ += dt; @@ -72,7 +72,7 @@ bool Ticker::Tick(Duration dt) delta_time_ = elapsed_time_; error_time_ = (elapsed_time_ + error_time_) - interval_; elapsed_time_ = 0; - ++ticked_times_; + ++ticked_count_; return true; } return false; @@ -115,7 +115,7 @@ void Ticker::Reset() elapsed_time_ = 0; delta_time_ = 0; error_time_ = 0; - ticked_times_ = 0; + ticked_count_ = 0; } } // namespace kiwano diff --git a/src/kiwano/utils/Ticker.h b/src/kiwano/utils/Ticker.h index 5ec16cdd..815bfe8c 100644 --- a/src/kiwano/utils/Ticker.h +++ b/src/kiwano/utils/Ticker.h @@ -35,8 +35,8 @@ public: /// \~chinese /// @brief 创建报时器 /// @param interval 报时间隔 - /// @param times 报时次数(设 -1 为永久) - static TickerPtr Create(Duration interval, int times = -1); + /// @param tick_count 报时次数(设 -1 为永久) + static TickerPtr Create(Duration interval, int tick_count = -1); Ticker(); @@ -69,15 +69,15 @@ public: /// \~chinese /// @brief 获取报时器报时次数 - int GetTickedTimes() const; + int GetTickedCount() const; /// \~chinese /// @brief 获取报时器总报时次数 - int GetTotalTickTimes() const; + int GetTotalTickCount() const; /// \~chinese /// @brief 设置报时器总报时次数 - void SetTotalTickTimes(int times); + void SetTotalTickCount(int count); /// \~chinese /// @brief 获取报时间隔 @@ -101,8 +101,8 @@ public: private: bool is_paused_; - int ticked_times_; - int total_times_; + int ticked_count_; + int total_tick_count_; Duration interval_; Duration elapsed_time_; Duration delta_time_; @@ -115,19 +115,19 @@ inline bool Ticker::IsPausing() const return is_paused_; } -inline int Ticker::GetTickedTimes() const +inline int Ticker::GetTickedCount() const { - return ticked_times_; + return ticked_count_; } -inline int Ticker::GetTotalTickTimes() const +inline int Ticker::GetTotalTickCount() const { - return total_times_; + return total_tick_count_; } -inline void Ticker::SetTotalTickTimes(int times) +inline void Ticker::SetTotalTickCount(int count) { - total_times_ = times; + total_tick_count_ = count; } inline Duration Ticker::GetInterval() const From 97526a67b5451f015d4a4719bfcb15bedf81c204 Mon Sep 17 00:00:00 2001 From: Nomango Date: Tue, 26 May 2020 16:19:24 +0800 Subject: [PATCH 37/37] Renderer ignores window resized messages --- src/kiwano/platform/win32/WindowImpl.cpp | 14 ++++++++++++-- src/kiwano/render/Renderer.cpp | 6 +----- src/kiwano/render/Renderer.h | 24 ++++++++++++------------ 3 files changed, 25 insertions(+), 19 deletions(-) diff --git a/src/kiwano/platform/win32/WindowImpl.cpp b/src/kiwano/platform/win32/WindowImpl.cpp index f6fe696f..be5ae065 100644 --- a/src/kiwano/platform/win32/WindowImpl.cpp +++ b/src/kiwano/platform/win32/WindowImpl.cpp @@ -668,7 +668,7 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA if (is_fullscreen_) { // TODO restore to fullscreen mode - // Renderer::GetInstance().SetResolution(); + // SetResolution(); } } break; @@ -705,7 +705,17 @@ LRESULT WindowWin32Impl::MessageProc(HWND hwnd, UINT32 msg, WPARAM wparam, LPARA { KGE_SYS_LOG("The display resolution has changed"); - ::InvalidateRect(hwnd, NULL, FALSE); + // Check fullscreen state + auto d3d_res = graphics::directx::GetD3DDeviceResources(); + auto swap_chain = d3d_res->GetDXGISwapChain(); + if (swap_chain) + { + BOOL is_fullscreen = FALSE; + if (SUCCEEDED(swap_chain->GetFullscreenState(&is_fullscreen, nullptr))) + { + is_fullscreen_ = !!is_fullscreen; + } + } } break; diff --git a/src/kiwano/render/Renderer.cpp b/src/kiwano/render/Renderer.cpp index be2226b2..a95d65d4 100644 --- a/src/kiwano/render/Renderer.cpp +++ b/src/kiwano/render/Renderer.cpp @@ -44,11 +44,7 @@ void Renderer::DestroyModule() void Renderer::HandleEvent(Event* evt) { - if (evt->IsType()) - { - auto window_evt = dynamic_cast(evt); - Resize(window_evt->width, window_evt->height); - } + // DO NOTHING } void Renderer::BeginDraw() diff --git a/src/kiwano/render/Renderer.h b/src/kiwano/render/Renderer.h index 68077fa1..a42b3c7c 100644 --- a/src/kiwano/render/Renderer.h +++ b/src/kiwano/render/Renderer.h @@ -55,6 +55,18 @@ public: /// @brief 获取清屏颜色 virtual Color GetClearColor() const; + /// \~chinese + /// @brief 获取渲染输出大小 + Size GetOutputSize() const; + + /// \~chinese + /// @brief 获取渲染上下文 + RenderContext& GetContext(); + + /// \~chinese + /// @brief 重设渲染输出大小 + virtual void Resize(uint32_t width, uint32_t height) = 0; + /// \~chinese /// @brief 设置清屏颜色 virtual void SetClearColor(const Color& clear_color); @@ -206,14 +218,6 @@ public: virtual RenderContextPtr CreateTextureRenderContext(Texture& texture, const Size* desired_size = nullptr) = 0; public: - /// \~chinese - /// @brief 获取渲染上下文 - RenderContext& GetContext(); - - /// \~chinese - /// @brief 获取渲染输出大小 - Size GetOutputSize() const; - /// \~chinese /// @brief 开始渲染 virtual void BeginDraw(); @@ -231,10 +235,6 @@ public: /// @throw kiwano::SystemError 呈现失败时抛出 virtual void Present() = 0; - /// \~chinese - /// @brief 重设渲染输出大小 - virtual void Resize(uint32_t width, uint32_t height) = 0; - public: void SetupModule() override;