refactoring: add RefPtr & RefObject & ObjectPool

This commit is contained in:
Nomango 2020-07-22 16:52:32 +08:00
parent 765d20c988
commit c0f90d235a
69 changed files with 330 additions and 313 deletions

View File

@ -17,7 +17,7 @@
<ClInclude Include="..\..\src\kiwano\base\Module.h" />
<ClInclude Include="..\..\src\kiwano\base\ObjectBase.h" />
<ClInclude Include="..\..\src\kiwano\base\ObjectPool.h" />
<ClInclude Include="..\..\src\kiwano\base\RefCounter.h" />
<ClInclude Include="..\..\src\kiwano\base\RefObject.h" />
<ClInclude Include="..\..\src\kiwano\core\Allocator.h" />
<ClInclude Include="..\..\src\kiwano\core\Any.h" />
<ClInclude Include="..\..\src\kiwano\core\Cloneable.h" />
@ -52,7 +52,7 @@
<ClInclude Include="..\..\src\kiwano\2d\TextActor.h" />
<ClInclude Include="..\..\src\kiwano\2d\Transition.h" />
<ClInclude Include="..\..\src\kiwano\core\Resource.h" />
<ClInclude Include="..\..\src\kiwano\core\SmartPtr.hpp" />
<ClInclude Include="..\..\src\kiwano\core\RefPtr.hpp" />
<ClInclude Include="..\..\src\kiwano\math\Constants.h" />
<ClInclude Include="..\..\src\kiwano\math\EaseFunctions.h" />
<ClInclude Include="..\..\src\kiwano\math\Math.h" />
@ -134,7 +134,7 @@
<ClCompile Include="..\..\src\kiwano\base\Module.cpp" />
<ClCompile Include="..\..\src\kiwano\base\ObjectBase.cpp" />
<ClCompile Include="..\..\src\kiwano\base\ObjectPool.cpp" />
<ClCompile Include="..\..\src\kiwano\base\RefCounter.cpp" />
<ClCompile Include="..\..\src\kiwano\base\RefObject.cpp" />
<ClCompile Include="..\..\src\kiwano\core\Allocator.cpp" />
<ClCompile Include="..\..\src\kiwano\core\Exception.cpp" />
<ClCompile Include="..\..\src\kiwano\core\Library.cpp" />

View File

@ -65,9 +65,6 @@
<ClInclude Include="..\..\src\kiwano\math\Vec2.hpp">
<Filter>math</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\core\SmartPtr.hpp">
<Filter>core</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\kiwano.h" />
<ClInclude Include="..\..\src\kiwano\2d\GifSprite.h">
<Filter>2d</Filter>
@ -303,9 +300,6 @@
<ClInclude Include="..\..\src\kiwano\base\ObjectBase.h">
<Filter>base</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\base\RefCounter.h">
<Filter>base</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\event\Event.h">
<Filter>event</Filter>
</ClInclude>
@ -354,6 +348,12 @@
<ClInclude Include="..\..\src\kiwano\2d\action\Action.h">
<Filter>2d\action</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\core\RefPtr.hpp">
<Filter>core</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\base\RefObject.h">
<Filter>base</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\src\kiwano\2d\Canvas.cpp">
@ -539,9 +539,6 @@
<ClCompile Include="..\..\src\kiwano\base\ObjectBase.cpp">
<Filter>base</Filter>
</ClCompile>
<ClCompile Include="..\..\src\kiwano\base\RefCounter.cpp">
<Filter>base</Filter>
</ClCompile>
<ClCompile Include="..\..\src\kiwano\event\Event.cpp">
<Filter>event</Filter>
</ClCompile>
@ -581,6 +578,9 @@
<ClCompile Include="..\..\src\kiwano\2d\action\Action.cpp">
<Filter>2d\action</Filter>
</ClCompile>
<ClCompile Include="..\..\src\kiwano\base\RefObject.cpp">
<Filter>base</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="suppress_warning.ruleset" />

View File

@ -29,7 +29,7 @@ namespace audio
{
SoundPtr Sound::Create(const String& file_path)
{
SoundPtr ptr = new (std::nothrow) Sound;
SoundPtr ptr = new (autogc) Sound;
if (ptr)
{
if (!ptr->Load(file_path))
@ -40,7 +40,7 @@ SoundPtr Sound::Create(const String& file_path)
SoundPtr Sound::Create(const Resource& res)
{
SoundPtr ptr = new (std::nothrow) Sound;
SoundPtr ptr = new (autogc) Sound;
if (ptr)
{
if (!ptr->Load(res))

View File

@ -27,7 +27,7 @@ namespace audio
SoundPlayerPtr SoundPlayer::Create()
{
SoundPlayerPtr ptr = new (std::nothrow) SoundPlayer;
SoundPlayerPtr ptr = new (autogc) SoundPlayer;
return ptr;
}
@ -47,8 +47,7 @@ size_t SoundPlayer::Load(const String& file_path)
if (sound_cache_.end() != sound_cache_.find(hash))
return hash;
SoundPtr sound = new (std::nothrow) Sound;
SoundPtr sound = new (autogc) Sound;
if (sound)
{
if (sound->Load(file_path))
@ -67,7 +66,7 @@ size_t SoundPlayer::Load(const Resource& res)
if (sound_cache_.end() != sound_cache_.find(hash_code))
return hash_code;
SoundPtr sound = new (std::nothrow) Sound;
SoundPtr sound = new (autogc) Sound;
if (sound)
{

View File

@ -27,13 +27,13 @@ namespace imgui
ImGuiLayerPtr ImGuiLayer::Create()
{
ImGuiLayerPtr ptr = new (std::nothrow) ImGuiLayer;
ImGuiLayerPtr ptr = new (autogc) ImGuiLayer;
return ptr;
}
ImGuiLayerPtr ImGuiLayer::Create(const String& name, const ImGuiPipeline& item)
{
ImGuiLayerPtr ptr = new (std::nothrow) ImGuiLayer;
ImGuiLayerPtr ptr = new (autogc) ImGuiLayer;
if (ptr)
{
ptr->AddItem(name, item);

View File

@ -253,7 +253,7 @@ void HttpModule::NetworkThread()
return;
}
HttpResponsePtr response = new (std::nothrow) HttpResponse(request);
HttpResponsePtr response = new (autogc) HttpResponse(request);
Perform(request, response);
response_mutex_.lock();

View File

@ -28,7 +28,7 @@ namespace network
HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const ResponseCallback& callback)
{
HttpRequestPtr ptr = new (std::nothrow) HttpRequest;
HttpRequestPtr ptr = new (autogc) HttpRequest;
if (ptr)
{
ptr->SetUrl(url);
@ -40,7 +40,7 @@ HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const Respo
HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const String& data, const ResponseCallback& callback)
{
HttpRequestPtr ptr = new (std::nothrow) HttpRequest;
HttpRequestPtr ptr = new (autogc) HttpRequest;
if (ptr)
{
ptr->SetUrl(url);
@ -53,7 +53,7 @@ HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const Strin
HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const Json& json, const ResponseCallback& callback)
{
HttpRequestPtr ptr = new (std::nothrow) HttpRequest;
HttpRequestPtr ptr = new (autogc) HttpRequest;
if (ptr)
{
ptr->SetUrl(url);

View File

@ -29,7 +29,7 @@ namespace physics
FixturePtr Fixture::CreateCircle(const Param& param, float radius, const Point& offset)
{
FixturePtr ptr = new (std::nothrow) Fixture;
FixturePtr ptr = new (autogc) Fixture;
if (ptr)
{
auto shape = std::make_unique<b2CircleShape>();
@ -44,7 +44,7 @@ FixturePtr Fixture::CreateCircle(const Param& param, float radius, const Point&
FixturePtr Fixture::CreateRect(const Param& param, const Size& size, const Point& offset, float rotation)
{
FixturePtr ptr = new (std::nothrow) Fixture;
FixturePtr ptr = new (autogc) Fixture;
if (ptr)
{
b2Vec2 b2size = global::LocalToWorld(size);
@ -61,7 +61,7 @@ FixturePtr Fixture::CreateRect(const Param& param, const Size& size, const Point
FixturePtr Fixture::CreatePolygon(const Param& param, const Vector<Point>& vertexs)
{
FixturePtr ptr = new (std::nothrow) Fixture;
FixturePtr ptr = new (autogc) Fixture;
if (ptr)
{
Vector<b2Vec2> b2vertexs;
@ -82,7 +82,7 @@ FixturePtr Fixture::CreatePolygon(const Param& param, const Vector<Point>& verte
FixturePtr Fixture::CreateEdge(const Param& param, const Point& p1, const Point& p2)
{
FixturePtr ptr = new (std::nothrow) Fixture;
FixturePtr ptr = new (autogc) Fixture;
if (ptr)
{
b2Vec2 start = global::LocalToWorld(p1);
@ -99,7 +99,7 @@ FixturePtr Fixture::CreateEdge(const Param& param, const Point& p1, const Point&
FixturePtr Fixture::CreateChain(const Param& param, const Vector<Point>& vertices, bool loop)
{
FixturePtr ptr = new (std::nothrow) Fixture;
FixturePtr ptr = new (autogc) Fixture;
if (ptr)
{
Vector<b2Vec2> b2vertices;

View File

@ -109,7 +109,7 @@ void Joint::Destroy()
DistanceJointPtr DistanceJoint::Create(const Param& param)
{
DistanceJointPtr ptr = new (std::nothrow) DistanceJoint;
DistanceJointPtr ptr = new (autogc) DistanceJoint;
if (ptr)
{
ptr->param_ = param;
@ -156,7 +156,7 @@ float DistanceJoint::GetLength() const
FrictionJointPtr FrictionJoint::Create(const Param& param)
{
FrictionJointPtr ptr = new (std::nothrow) FrictionJoint;
FrictionJointPtr ptr = new (autogc) FrictionJoint;
if (ptr)
{
ptr->param_ = param;
@ -214,7 +214,7 @@ float FrictionJoint::GetMaxTorque() const
GearJointPtr GearJoint::Create(const Param& param)
{
GearJointPtr ptr = new (std::nothrow) GearJoint;
GearJointPtr ptr = new (autogc) GearJoint;
if (ptr)
{
ptr->param_ = param;
@ -260,7 +260,7 @@ float GearJoint::GetRatio() const
MotorJointPtr MotorJoint::Create(const Param& param)
{
MotorJointPtr ptr = new (std::nothrow) MotorJoint;
MotorJointPtr ptr = new (autogc) MotorJoint;
if (ptr)
{
ptr->param_ = param;
@ -319,7 +319,7 @@ float MotorJoint::GetMaxTorque() const
PrismaticJointPtr PrismaticJoint::Create(const Param& param)
{
PrismaticJointPtr ptr = new (std::nothrow) PrismaticJoint;
PrismaticJointPtr ptr = new (autogc) PrismaticJoint;
if (ptr)
{
ptr->param_ = param;
@ -388,7 +388,7 @@ void PrismaticJoint::SetLimits(float lower, float upper)
PulleyJointPtr PulleyJoint::Create(const Param& param)
{
PulleyJointPtr ptr = new (std::nothrow) PulleyJoint;
PulleyJointPtr ptr = new (autogc) PulleyJoint;
if (ptr)
{
ptr->param_ = param;
@ -464,7 +464,7 @@ float PulleyJoint::GetCurrentLengthB() const
RevoluteJointPtr RevoluteJoint::Create(const Param& param)
{
RevoluteJointPtr ptr = new (std::nothrow) RevoluteJoint;
RevoluteJointPtr ptr = new (autogc) RevoluteJoint;
if (ptr)
{
ptr->param_ = param;
@ -544,7 +544,7 @@ float RevoluteJoint::GetMaxMotorTorque() const
RopeJointPtr RopeJoint::Create(const Param& param)
{
RopeJointPtr ptr = new (std::nothrow) RopeJoint;
RopeJointPtr ptr = new (autogc) RopeJoint;
if (ptr)
{
ptr->param_ = param;
@ -592,7 +592,7 @@ float RopeJoint::GetMaxLength() const
WeldJointPtr WeldJoint::Create(const Param& param)
{
WeldJointPtr ptr = new (std::nothrow) WeldJoint;
WeldJointPtr ptr = new (autogc) WeldJoint;
if (ptr)
{
ptr->param_ = param;
@ -626,7 +626,7 @@ bool WeldJoint::Init(PhysicWorld* world)
WheelJointPtr WheelJoint::Create(const Param& param)
{
WheelJointPtr ptr = new (std::nothrow) WheelJoint;
WheelJointPtr ptr = new (autogc) WheelJoint;
if (ptr)
{
ptr->param_ = param;
@ -688,7 +688,7 @@ float WheelJoint::GetMaxMotorTorque() const
MouseJointPtr MouseJoint::Create(const Param& param)
{
MouseJointPtr ptr = new (std::nothrow) MouseJoint;
MouseJointPtr ptr = new (autogc) MouseJoint;
if (ptr)
{
ptr->param_ = param;

View File

@ -37,7 +37,7 @@ PhysicBodyPtr PhysicBody::Create(PhysicWorld* world, Type type)
{
KGE_ASSERT(world);
PhysicBodyPtr ptr = new (std::nothrow) PhysicBody;
PhysicBodyPtr ptr = new (autogc) PhysicBody;
if (ptr)
{
ptr->SetType(type);

View File

@ -213,13 +213,13 @@ public:
PhysicWorldPtr PhysicWorld::Create()
{
PhysicWorldPtr ptr = new (std::nothrow) PhysicWorld;
PhysicWorldPtr ptr = new (autogc) PhysicWorld;
return ptr;
}
PhysicWorldPtr PhysicWorld::Create(const Vec2& gravity)
{
PhysicWorldPtr ptr = new (std::nothrow) PhysicWorld;
PhysicWorldPtr ptr = new (autogc) PhysicWorld;
if (ptr)
{
ptr->SetGravity(gravity);

View File

@ -41,7 +41,7 @@ void Actor::SetDefaultAnchor(float anchor_x, float anchor_y)
ActorPtr Actor::Create()
{
ActorPtr ptr = memory::New<Actor>();
ActorPtr ptr = new (autogc) Actor;
return ptr;
}
@ -264,7 +264,7 @@ bool Actor::HandleEvent(Event* evt)
{
hover_ = true;
MouseHoverEventPtr hover = memory::New<MouseHoverEvent>();
MouseHoverEventPtr hover = new (autogc) MouseHoverEvent;
hover->pos = mouse_evt->pos;
HandleEvent(hover.Get());
}
@ -273,7 +273,7 @@ bool Actor::HandleEvent(Event* evt)
hover_ = false;
pressed_ = false;
MouseOutEventPtr out = memory::New<MouseOutEvent>();
MouseOutEventPtr out = new (autogc) MouseOutEvent;
out->pos = mouse_evt->pos;
HandleEvent(out.Get());
}
@ -290,7 +290,7 @@ bool Actor::HandleEvent(Event* evt)
auto mouse_up_evt = dynamic_cast<MouseUpEvent*>(evt);
MouseClickEventPtr click = memory::New<MouseClickEvent>();
MouseClickEventPtr click = new (autogc) MouseClickEvent;
click->pos = mouse_up_evt->pos;
click->button = mouse_up_evt->button;
HandleEvent(click.Get());

View File

@ -26,8 +26,7 @@ namespace kiwano
CanvasPtr Canvas::Create(const Size& size)
{
void* mem = memory::Alloc(sizeof(Canvas));
CanvasPtr ptr = ::new (mem) Canvas;
CanvasPtr ptr = new (autogc) Canvas;
if (ptr)
{
try
@ -59,7 +58,7 @@ void Canvas::OnRender(RenderContext& ctx)
void Canvas::ResizeAndClear(Size size)
{
texture_cached_ = memory::New<Texture>();
texture_cached_ = new (autogc) Texture;
render_ctx_ = RenderContext::Create(*texture_cached_, size);
SetSize(render_ctx_->GetSize());

View File

@ -54,10 +54,10 @@ DebugActor::DebugActor()
comma_locale_ = std::locale(std::locale(), new comma_numpunct);
background_brush_ = memory::New<Brush>();
background_brush_ = new (autogc) Brush;
background_brush_->SetColor(Color::Rgba(0x000000, 0.7f));
BrushPtr fill_brush = memory::New<Brush>();
BrushPtr fill_brush = new (autogc) Brush;
fill_brush->SetColor(Color::White);
debug_text_style_.font_family = "Arial";

View File

@ -27,7 +27,7 @@ namespace kiwano
GifSpritePtr GifSprite::Create(const String& file_path)
{
GifSpritePtr ptr = memory::New<GifSprite>();
GifSpritePtr ptr = new (autogc) GifSprite;
if (ptr)
{
if (!ptr->Load(file_path))
@ -38,7 +38,7 @@ GifSpritePtr GifSprite::Create(const String& file_path)
GifSpritePtr GifSprite::Create(const Resource& res)
{
GifSpritePtr ptr = memory::New<GifSprite>();
GifSpritePtr ptr = new (autogc) GifSprite;
if (ptr)
{
if (!ptr->Load(res))
@ -49,7 +49,7 @@ GifSpritePtr GifSprite::Create(const Resource& res)
GifSpritePtr GifSprite::Create(GifImagePtr gif)
{
GifSpritePtr ptr = memory::New<GifSprite>();
GifSpritePtr ptr = new (autogc) GifSprite;
if (ptr)
{
ptr->SetGifImage(gif);
@ -92,7 +92,7 @@ bool GifSprite::Load(GifImagePtr gif)
frame_rt_.Reset();
Size frame_size = Size(float(gif_->GetWidthInPixels()), float(gif_->GetHeightInPixels()));
frame_to_render_ = memory::New<Texture>();
frame_to_render_ = new (autogc) Texture;
frame_rt_ = RenderContext::Create(*frame_to_render_, frame_size);
SetSize(frame_rt_->GetSize());
@ -229,7 +229,7 @@ void GifSprite::SaveComposedFrame()
if (!saved_frame_)
{
saved_frame_ = memory::New<Texture>();
saved_frame_ = new (autogc) Texture;
frame_rt_->CreateTexture(*saved_frame_, frame_to_render_->GetSizeInPixels());
}
saved_frame_->CopyFrom(frame_to_render_);

View File

@ -27,7 +27,7 @@ namespace kiwano
LayerActorPtr LayerActor::Create()
{
LayerActorPtr ptr = memory::New<LayerActor>();
LayerActorPtr ptr = new (autogc) LayerActor;
return ptr;
}

View File

@ -27,7 +27,7 @@ namespace kiwano
ShapeActorPtr ShapeActor::Create(ShapePtr shape)
{
ShapeActorPtr ptr = memory::New<ShapeActor>();
ShapeActorPtr ptr = new (autogc) ShapeActor;
if (ptr)
{
ptr->SetShape(shape);
@ -129,7 +129,7 @@ bool ShapeActor::CheckVisibility(RenderContext& ctx) const
LineActorPtr LineActor::Create(const Point& begin, const Point& end)
{
LineActorPtr ptr = memory::New<LineActor>();
LineActorPtr ptr = new (autogc) LineActor;
if (ptr)
{
ptr->SetLine(begin, end);
@ -157,7 +157,7 @@ void LineActor::SetLine(const Point& begin, const Point& end)
RectActorPtr RectActor::Create(const Size& size)
{
RectActorPtr ptr = memory::New<RectActor>();
RectActorPtr ptr = new (autogc) RectActor;
if (ptr)
{
ptr->SetRectSize(size);
@ -184,7 +184,7 @@ void RectActor::SetRectSize(const Size& size)
RoundedRectActorPtr RoundedRectActor::Create(const Size& size, const Vec2& radius)
{
RoundedRectActorPtr ptr = memory::New<RoundedRectActor>();
RoundedRectActorPtr ptr = new (autogc) RoundedRectActor;
if (ptr)
{
ptr->SetRoundedRect(size, radius);
@ -222,7 +222,7 @@ void RoundedRectActor::SetRoundedRect(const Size& size, const Vec2& radius)
CircleActorPtr CircleActor::Create(float radius)
{
CircleActorPtr ptr = memory::New<CircleActor>();
CircleActorPtr ptr = new (autogc) CircleActor;
if (ptr)
{
ptr->SetRadius(radius);
@ -252,7 +252,7 @@ void CircleActor::SetRadius(float radius)
EllipseActorPtr EllipseActor::Create(const Vec2& radius)
{
EllipseActorPtr ptr = memory::New<EllipseActor>();
EllipseActorPtr ptr = new (autogc) EllipseActor;
if (ptr)
{
ptr->SetRadius(radius);
@ -279,7 +279,7 @@ void EllipseActor::SetRadius(const Vec2& radius)
PolygonActorPtr PolygonActor::Create(const Vector<Point>& points)
{
PolygonActorPtr ptr = memory::New<PolygonActor>();
PolygonActorPtr ptr = new (autogc) PolygonActor;
if (ptr)
{
ptr->SetVertices(points);

View File

@ -338,7 +338,7 @@ inline void ShapeActor::SetStrokeColor(const Color& color)
{
if (!stroke_brush_)
{
stroke_brush_ = memory::New<Brush>();
stroke_brush_ = new (autogc) Brush;
}
stroke_brush_->SetColor(color);
}
@ -347,7 +347,7 @@ inline void ShapeActor::SetFillColor(const Color& color)
{
if (!fill_brush_)
{
fill_brush_ = memory::New<Brush>();
fill_brush_ = new (autogc) Brush;
}
fill_brush_->SetColor(color);
}

View File

@ -26,7 +26,7 @@ namespace kiwano
SpritePtr Sprite::Create(const String& file_path)
{
SpritePtr ptr = memory::New<Sprite>();
SpritePtr ptr = new (autogc) Sprite;
if (ptr)
{
if (!ptr->Load(file_path))
@ -37,7 +37,7 @@ SpritePtr Sprite::Create(const String& file_path)
SpritePtr Sprite::Create(const Resource& res)
{
SpritePtr ptr = memory::New<Sprite>();
SpritePtr ptr = new (autogc) Sprite;
if (ptr)
{
if (!ptr->Load(res))
@ -48,7 +48,7 @@ SpritePtr Sprite::Create(const Resource& res)
SpritePtr Sprite::Create(FramePtr frame)
{
SpritePtr ptr = memory::New<Sprite>();
SpritePtr ptr = new (autogc) Sprite;
if (ptr)
{
ptr->SetFrame(frame);

View File

@ -27,7 +27,7 @@ namespace kiwano
StagePtr Stage::Create()
{
StagePtr ptr = memory::New<Stage>();
StagePtr ptr = new (autogc) Stage;
return ptr;
}
@ -57,13 +57,13 @@ void Stage::RenderBorder(RenderContext& ctx)
if (!border_fill_brush_)
{
border_fill_brush_ = memory::New<Brush>();
border_fill_brush_ = new (autogc) Brush;
border_fill_brush_->SetColor(Color(Color::Red, .4f));
}
if (!border_stroke_brush_)
{
border_stroke_brush_ = memory::New<Brush>();
border_stroke_brush_ = new (autogc) Brush;
border_stroke_brush_->SetColor(Color(Color::Red, .8f));
}

View File

@ -32,7 +32,7 @@ TextActorPtr TextActor::Create(const String& text)
TextActorPtr TextActor::Create(const String& text, const TextStyle& style)
{
TextActorPtr ptr = memory::New<TextActor>();
TextActorPtr ptr = new (autogc) TextActor;
if (ptr)
{
ptr->SetStyle(style);

View File

@ -128,7 +128,7 @@ void Transition::Stop()
BoxTransitionPtr BoxTransition::Create(Duration duration)
{
BoxTransitionPtr ptr = memory::New<BoxTransition>();
BoxTransitionPtr ptr = new (autogc) BoxTransition;
if (ptr)
{
ptr->SetDuration(duration);
@ -169,7 +169,7 @@ void BoxTransition::Update(Duration dt)
EmergeTransitionPtr EmergeTransition::Create(Duration duration)
{
EmergeTransitionPtr ptr = memory::New<EmergeTransition>();
EmergeTransitionPtr ptr = new (autogc) EmergeTransition;
if (ptr)
{
ptr->SetDuration(duration);
@ -201,7 +201,7 @@ void EmergeTransition::Update(Duration dt)
FadeTransitionPtr FadeTransition::Create(Duration duration)
{
FadeTransitionPtr ptr = memory::New<FadeTransition>();
FadeTransitionPtr ptr = new (autogc) FadeTransition;
if (ptr)
{
ptr->SetDuration(duration);
@ -241,7 +241,7 @@ void FadeTransition::Update(Duration dt)
MoveTransitionPtr MoveTransition::Create(Duration duration, Type type)
{
MoveTransitionPtr ptr = memory::New<MoveTransition>();
MoveTransitionPtr ptr = new (autogc) MoveTransition;
if (ptr)
{
ptr->type_ = type;
@ -330,7 +330,7 @@ void MoveTransition::Reset()
RotationTransitionPtr RotationTransition::Create(Duration duration, float rotation)
{
RotationTransitionPtr ptr = memory::New<RotationTransition>();
RotationTransitionPtr ptr = new (autogc) RotationTransition;
if (ptr)
{
ptr->rotation_ = rotation;

View File

@ -22,7 +22,7 @@
#include <kiwano/core/Common.h>
#include <kiwano/core/Cloneable.h>
#include <kiwano/base/ObjectBase.h>
#include <kiwano/core/SmartPtr.hpp>
#include <kiwano/core/RefPtr.hpp>
#include <kiwano/core/Time.h>
#include <kiwano/core/IntrusiveList.h>
#include <kiwano/math/Math.h>

View File

@ -30,7 +30,7 @@ ActionDelay::ActionDelay(Duration delay)
ActionDelayEntityPtr ActionDelayEntity::Create(Duration delay)
{
ActionDelayEntityPtr ptr = memory::New<ActionDelayEntity>();
ActionDelayEntityPtr ptr = new (autogc) ActionDelayEntity;
if (ptr)
{
ptr->SetDelay(delay);

View File

@ -32,7 +32,7 @@ ActionGroup::ActionGroup(const Vector<ActionEntityPtr>& actions, bool parallel)
ActionGroupEntityPtr ActionGroupEntity::Create(const Vector<ActionEntityPtr>& actions, bool parallel)
{
ActionGroupEntityPtr ptr = memory::New<ActionGroupEntity>();
ActionGroupEntityPtr ptr = new (autogc) ActionGroupEntity;
if (ptr)
{
ptr->parallel_ = parallel;

View File

@ -145,7 +145,7 @@ ActionEntityPtr ActionTweenEntity::DoClone(ActionTweenEntityPtr to) const
ActionMoveByEntityPtr ActionMoveByEntity::Create(Duration duration, const Vec2& displacement)
{
ActionMoveByEntityPtr ptr = memory::New<ActionMoveByEntity>();
ActionMoveByEntityPtr ptr = new (autogc) ActionMoveByEntity;
if (ptr)
{
ptr->SetDuration(duration);
@ -187,7 +187,7 @@ ActionEntityPtr ActionMoveByEntity::Reverse() const
ActionMoveToEntityPtr ActionMoveToEntity::Create(Duration duration, const Point& distination)
{
ActionMoveToEntityPtr ptr = memory::New<ActionMoveToEntity>();
ActionMoveToEntityPtr ptr = new (autogc) ActionMoveToEntity;
if (ptr)
{
ptr->SetDuration(duration);
@ -215,7 +215,7 @@ void ActionMoveToEntity::Init(Actor* target)
ActionJumpByEntityPtr ActionJumpByEntity::Create(Duration duration, const Vec2& displacement, float height, int count)
{
ActionJumpByEntityPtr ptr = memory::New<ActionJumpByEntity>();
ActionJumpByEntityPtr ptr = new (autogc) ActionJumpByEntity;
if (ptr)
{
ptr->SetDuration(duration);
@ -268,7 +268,7 @@ void ActionJumpByEntity::UpdateTween(Actor* target, float percent)
ActionJumpToEntityPtr ActionJumpToEntity::Create(Duration duration, const Point& distination, float height, int count)
{
ActionJumpToEntityPtr ptr = memory::New<ActionJumpToEntity>();
ActionJumpToEntityPtr ptr = new (autogc) ActionJumpToEntity;
if (ptr)
{
ptr->SetDuration(duration);
@ -298,7 +298,7 @@ void ActionJumpToEntity::Init(Actor* target)
ActionScaleByEntityPtr ActionScaleByEntity::Create(Duration duration, float scale_x, float scale_y)
{
ActionScaleByEntityPtr ptr = memory::New<ActionScaleByEntity>();
ActionScaleByEntityPtr ptr = new (autogc) ActionScaleByEntity;
if (ptr)
{
ptr->SetDuration(duration);
@ -342,7 +342,7 @@ ActionEntityPtr ActionScaleByEntity::Reverse() const
ActionScaleToEntityPtr ActionScaleToEntity::Create(Duration duration, float scale_x, float scale_y)
{
ActionScaleToEntityPtr ptr = memory::New<ActionScaleToEntity>();
ActionScaleToEntityPtr ptr = new (autogc) ActionScaleToEntity;
if (ptr)
{
ptr->SetDuration(duration);
@ -376,7 +376,7 @@ void ActionScaleToEntity::Init(Actor* target)
ActionFadeToEntityPtr ActionFadeToEntity::Create(Duration duration, float opacity)
{
ActionFadeToEntityPtr ptr = memory::New<ActionFadeToEntity>();
ActionFadeToEntityPtr ptr = new (autogc) ActionFadeToEntity;
if (ptr)
{
ptr->SetDuration(duration);
@ -417,7 +417,7 @@ ActionEntityPtr ActionFadeToEntity::Clone() const
ActionRotateByEntityPtr ActionRotateByEntity::Create(Duration duration, float rotation)
{
ActionRotateByEntityPtr ptr = memory::New<ActionRotateByEntity>();
ActionRotateByEntityPtr ptr = new (autogc) ActionRotateByEntity;
if (ptr)
{
ptr->SetDuration(duration);
@ -461,7 +461,7 @@ ActionEntityPtr ActionRotateByEntity::Reverse() const
ActionRotateToEntityPtr ActionRotateToEntity::Create(Duration duration, float rotation)
{
ActionRotateToEntityPtr ptr = memory::New<ActionRotateToEntity>();
ActionRotateToEntityPtr ptr = new (autogc) ActionRotateToEntity;
if (ptr)
{
ptr->SetDuration(duration);
@ -492,7 +492,7 @@ void ActionRotateToEntity::Init(Actor* target)
ActionCustomEntityPtr ActionCustomEntity::Create(Duration duration, ActionCustom::TweenFunc tween_func)
{
ActionCustomEntityPtr ptr = memory::New<ActionCustomEntity>();
ActionCustomEntityPtr ptr = new (autogc) ActionCustomEntity;
if (ptr)
{
ptr->SetDuration(duration);

View File

@ -31,7 +31,7 @@ ActionWalk::ActionWalk(Duration duration, ShapePtr path, bool rotating, float st
ActionWalkEntityPtr ActionWalkEntity::Create(Duration duration, ShapePtr path, bool rotating, float start, float end)
{
ActionWalkEntityPtr ptr = memory::New<ActionWalkEntity>();
ActionWalkEntityPtr ptr = new (autogc) ActionWalkEntity;
if (ptr)
{
ptr->SetDuration(duration);

View File

@ -32,7 +32,7 @@ Animation::Animation(Duration dur, FrameSequencePtr frame_seq)
AnimationEntityPtr AnimationEntity::Create(Duration dur, FrameSequencePtr frame_seq)
{
AnimationEntityPtr ptr = memory::New<AnimationEntity>();
AnimationEntityPtr ptr = new (autogc) AnimationEntity;
if (ptr)
{
ptr->SetDuration(dur);

View File

@ -99,7 +99,7 @@ void Director::ShowDebugInfo(bool show)
if (show)
{
if (!debug_actor_)
debug_actor_ = memory::New<DebugActor>();
debug_actor_ = new (autogc) DebugActor;
}
else
{

View File

@ -19,7 +19,6 @@
// THE SOFTWARE.
#include <kiwano/base/ObjectBase.h>
#include <kiwano/base/ObjectPool.h>
#include <kiwano/utils/Logger.h>
#include <kiwano/utils/Json.h>
#include <typeinfo>
@ -28,9 +27,11 @@ namespace kiwano
{
namespace
{
bool tracing_leaks = false;
Vector<ObjectBase*> tracing_objects;
uint32_t last_object_id = 0;
} // namespace
ObjectBase::ObjectBase()
@ -57,11 +58,6 @@ ObjectBase::~ObjectBase()
#endif
}
void ObjectBase::AutoRelease()
{
ObjectPool::GetInstance().AddObject(this);
}
const Any& ObjectBase::GetUserData() const
{
return user_data_;

View File

@ -22,8 +22,8 @@
#include <kiwano/macros.h>
#include <kiwano/core/Common.h>
#include <kiwano/core/Serializable.h>
#include <kiwano/core/SmartPtr.hpp>
#include <kiwano/base/RefCounter.h>
#include <kiwano/core/RefPtr.hpp>
#include <kiwano/base/RefObject.h>
namespace kiwano
{
@ -34,7 +34,7 @@ KGE_DECLARE_SMART_PTR(ObjectBase);
* @brief
*/
class KGE_API ObjectBase
: public RefCounter
: public RefObject
, public Serializable
{
public:
@ -44,10 +44,6 @@ public:
virtual ~ObjectBase();
/// \~chinese
/// @brief 自动释放
void AutoRelease();
/// \~chinese
/// @brief 设置对象名
void SetName(const String& name);

View File

@ -23,56 +23,35 @@
namespace kiwano
{
List<ObjectPool*> ObjectPool::pools_;
ObjectPool& ObjectPool::GetInstance()
{
static ObjectPool instance;
return *pools_.back();
}
ObjectPool::ObjectPool()
{
pools_.push_back(this);
}
ObjectPool::~ObjectPool()
{
Clear();
auto iter = std::find(pools_.begin(), pools_.end(), this);
if (iter != pools_.end())
pools_.erase(iter);
}
void ObjectPool::AddObject(ObjectBase* obj)
void ObjectPool::AddObject(RefObject* obj)
{
if (obj)
{
std::lock_guard<std::mutex> lock(mutex_);
if (!Contains(obj))
{
obj->Retain();
std::lock_guard<std::mutex> lock(mutex_);
objects_.push_back(obj);
}
}
}
bool ObjectPool::Contains(ObjectBase* obj) const
bool ObjectPool::Contains(RefObject* obj) const
{
std::lock_guard<std::mutex> lock(const_cast<std::mutex&>(mutex_));
for (auto iter = pools_.rbegin(); iter != pools_.rend(); iter++)
for (const auto o : (*iter)->objects_)
if (obj == o)
return true;
return false;
return std::find(objects_.begin(), objects_.end(), obj) != objects_.end();
}
void ObjectPool::Clear()
{
Vector<ObjectBase*> copied;
Vector<RefObject*> copied;
{
std::lock_guard<std::mutex> lock(mutex_);

View File

@ -19,21 +19,22 @@
// THE SOFTWARE.
#pragma once
#include <kiwano/core/Singleton.h>
#include <kiwano/base/ObjectBase.h>
#include <mutex>
namespace kiwano
{
/**
* \~chinese
* @brief
*/
class KGE_API ObjectPool
: public Noncopyable
class KGE_API ObjectPool : public Singleton<ObjectPool>
{
public:
static ObjectPool& GetInstance();
friend Singleton<ObjectPool>;
public:
ObjectPool();
virtual ~ObjectPool();
@ -41,16 +42,16 @@ public:
/**
* \~chinese
* @brief
* @param[in] obj
* @param[in] obj
*/
void AddObject(ObjectBase* obj);
void AddObject(RefObject* obj);
/**
* \~chinese
* @brief
* @param[in] obj
* @param[in] obj
*/
bool Contains(ObjectBase* obj) const;
bool Contains(RefObject* obj) const;
/**
* \~chinese
@ -65,8 +66,7 @@ private:
private:
std::mutex mutex_;
Vector<ObjectBase*> objects_;
static List<ObjectPool*> pools_;
Vector<RefObject*> objects_;
};
} // namespace kiwano

View File

@ -18,29 +18,63 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <kiwano/base/RefCounter.h>
#include <kiwano/base/RefObject.h>
#include <kiwano/base/ObjectPool.h>
namespace kiwano
{
RefCounter::RefCounter()
: ref_count_(0)
autogc_t const autogc;
RefObject::RefObject()
: ref_count_(1)
{
}
RefCounter::~RefCounter() {}
RefObject::~RefObject() {}
void RefCounter::Retain()
void RefObject::Retain()
{
++ref_count_;
}
void RefCounter::Release()
void RefObject::Release()
{
--ref_count_;
if (ref_count_ == 0)
{
memory::Delete(this);
delete this;
}
}
void RefObject::AutoRelease()
{
ObjectPool::GetInstance().AddObject(this);
}
void* RefObject::operator new(std::size_t size)
{
return memory::Alloc(size);
}
void* RefObject::operator new(std::size_t size, autogc_t const&)
{
void* ptr = memory::Alloc(size);
if (ptr)
{
ObjectPool::GetInstance().AddObject((ObjectBase*)ptr);
}
return ptr;
}
void RefObject::operator delete(void* ptr)
{
memory::Free(ptr);
}
void RefObject::operator delete(void* ptr, autogc_t const&)
{
memory::Free(ptr);
}
} // namespace kiwano

View File

@ -24,17 +24,21 @@
namespace kiwano
{
struct autogc_t
{
autogc_t() = default;
};
extern autogc_t const autogc;
/**
* \~chinese
* @brief
*/
class KGE_API RefCounter : protected Noncopyable
class KGE_API RefObject : protected Noncopyable
{
public:
RefCounter();
virtual ~RefCounter();
/// \~chinese
/// @brief 增加引用计数
void Retain();
@ -43,17 +47,34 @@ public:
/// @brief 减少引用计数
void Release();
/// \~chinese
/// @brief ×Ô¶¯ÊÍ·Å
void AutoRelease();
/// \~chinese
/// @brief 获取引用计数
uint32_t GetRefCount() const;
void* operator new(std::size_t size);
void* operator new(std::size_t size, autogc_t const&);
void operator delete(void* ptr);
void operator delete(void* ptr, autogc_t const&);
protected:
RefObject();
virtual ~RefObject();
private:
std::atomic<uint32_t> ref_count_;
};
inline uint32_t RefCounter::GetRefCount() const
inline uint32_t RefObject::GetRefCount() const
{
return ref_count_;
return ref_count_.load();
}
} // namespace kiwano

View File

@ -33,7 +33,7 @@ ButtonPtr Button::Create(const Callback& click)
ButtonPtr Button::Create(const Callback& click, const Callback& pressed, const Callback& mouse_over,
const Callback& mouse_out)
{
ButtonPtr ptr = memory::New<Button>();
ButtonPtr ptr = new (autogc) Button;
if (ptr)
{
ptr->SetClickCallback(click);

View File

@ -37,9 +37,9 @@ MemoryAllocator* GetGlobalAllocator()
return ::operator new(size);
}
virtual void Free(void* ptr, size_t size) override
virtual void Free(void* ptr, size_t) override
{
::operator delete(ptr, size);
::operator delete(ptr);
}
};

View File

@ -40,7 +40,7 @@ public:
/// \~chinese
/// @brief 释放内存
virtual void Free(void* ptr, size_t size) = 0;
virtual void Free(void* ptr, size_t size = 0) = 0;
};
/// \~chinese
@ -58,6 +58,13 @@ inline void* Alloc(size_t size)
return memory::GetAllocator()->Alloc(size);
}
/// \~chinese
/// @brief 使用当前内存分配器释放内存
inline void Free(void* ptr)
{
memory::GetAllocator()->Free(ptr);
}
/// \~chinese
/// @brief 使用当前内存分配器释放内存
inline void Free(void* ptr, size_t size)
@ -65,47 +72,7 @@ inline void Free(void* ptr, size_t size)
memory::GetAllocator()->Free(ptr, size);
}
/// \~chinese
/// @brief 构造对象
template <typename _Ty, typename... _Args>
inline _Ty* Construct(void* ptr, _Args&&... args)
{
return ::new (ptr) _Ty(std::forward<_Args>(args)...);
}
/// \~chinese
/// @brief 销毁对象
template <typename _Ty, typename... _Args>
inline void Destroy(_Ty* ptr)
{
ptr->~_Ty();
}
/// \~chinese
/// @brief 使用当前内存分配器创建对象
template <typename _Ty, typename... _Args>
inline _Ty* New(_Args&&... args)
{
void* ptr = memory::Alloc(sizeof(_Ty));
if (ptr)
{
return memory::Construct<_Ty>(ptr, std::forward<_Args>(args)...);
}
return nullptr;
}
/// \~chinese
/// @brief 使用当前内存分配器销毁对象
template <typename _Ty>
inline void Delete(_Ty* ptr)
{
if (ptr)
{
memory::Destroy<_Ty>(ptr);
memory::Free(ptr, sizeof(_Ty));
}
}
} // namespace memory
/// \~chinese
/// @brief 分配器
@ -159,13 +126,13 @@ public:
template <typename _UTy, typename... _Args>
inline void construct(_UTy* ptr, _Args&&... args)
{
memory::Construct<_UTy>(ptr, std::forward<_Args>(args)...);
::new (ptr) _Ty(std::forward<_Args>(args)...);
}
template <typename _UTy>
inline void destroy(_UTy* ptr)
{
memory::Destroy<_UTy>(ptr);
ptr->~_UTy();
}
size_t max_size() const noexcept
@ -215,5 +182,4 @@ bool operator!=(const Allocator<_Ty>&, const Allocator<_Other>&) noexcept
return false;
}
} // namespace memory
} // namespace kiwano

View File

@ -19,7 +19,7 @@
// THE SOFTWARE.
#pragma once
#include <kiwano/core/SmartPtr.hpp>
#include <kiwano/core/RefPtr.hpp>
namespace kiwano
{
@ -28,7 +28,7 @@ template <typename _Ty>
class Cloneable
{
public:
virtual SmartPtr<_Ty> Clone() const = 0;
virtual RefPtr<_Ty> Clone() const = 0;
protected:
Cloneable() = default;

View File

@ -22,7 +22,7 @@
#include <utility>
#include <type_traits>
#include <kiwano/core/Common.h>
#include <kiwano/base/RefCounter.h>
#include <kiwano/base/RefObject.h>
namespace kiwano
{
@ -31,15 +31,15 @@ namespace kiwano
* \~chinese
* @brief
*/
struct DefaultSmartPtrRefProxy
struct DefaultRefPtrRefProxy
{
static inline void Retain(RefCounter* ptr)
static inline void Retain(RefObject* ptr)
{
if (ptr)
ptr->Retain();
}
static inline void Release(RefCounter* ptr)
static inline void Release(RefObject* ptr)
{
if (ptr)
ptr->Release();
@ -48,10 +48,10 @@ struct DefaultSmartPtrRefProxy
/**
* \~chinese
* @brief ÇÖÈëʽÖÇÄÜÖ¸Õë
* @brief ÒýÓüÆÊýÖÇÄÜÖ¸Õë
*/
template <typename _Ty, typename _ProxyTy = DefaultSmartPtrRefProxy>
class SmartPtr
template <typename _Ty, typename _ProxyTy = DefaultRefPtrRefProxy>
class RefPtr
{
public:
using value_type = _Ty;
@ -60,65 +60,66 @@ public:
using reference_type = _Ty&;
using const_reference_type = const _Ty&;
SmartPtr() noexcept
RefPtr() noexcept
: ptr_(nullptr)
{
}
SmartPtr(std::nullptr_t) noexcept
RefPtr(std::nullptr_t) noexcept
: ptr_(nullptr)
{
}
SmartPtr(pointer_type p)
RefPtr(pointer_type p)
: ptr_(p)
{
_ProxyTy::Retain(ptr_);
}
SmartPtr(const SmartPtr& other)
RefPtr(const RefPtr& other)
: ptr_(other.ptr_)
{
_ProxyTy::Retain(ptr_);
}
SmartPtr(SmartPtr&& other) noexcept
RefPtr(RefPtr&& other) noexcept
: ptr_(nullptr)
{
Swap(other);
}
~SmartPtr()
~RefPtr()
{
Tidy();
}
template <typename _UTy, typename std::enable_if<std::is_base_of<_Ty, _UTy>::value, int>::type = 0>
SmartPtr(const SmartPtr<_UTy, _ProxyTy>& other)
template <typename _UTy, typename std::enable_if<std::is_convertible<_UTy*, _Ty*>::value, int>::type = 0>
RefPtr(const RefPtr<_UTy, _ProxyTy>& other)
{
ptr_ = const_cast<pointer_type>(dynamic_cast<const_pointer_type>(other.Get()));
ptr_ = dynamic_cast<pointer_type>(other.Get());
_ProxyTy::Retain(ptr_);
}
inline pointer_type Get() noexcept
inline pointer_type Get() const noexcept
{
return ptr_;
}
inline const_pointer_type Get() const noexcept
inline pointer_type* GetAddressOfAndRelease()
{
return ptr_;
Tidy();
return &ptr_;
}
inline void Reset(pointer_type ptr = nullptr)
{
if (ptr)
SmartPtr(ptr).Swap(*this);
RefPtr(ptr).Swap(*this);
else
Tidy();
}
inline void Swap(SmartPtr& other) noexcept
inline void Swap(RefPtr& other) noexcept
{
std::swap(ptr_, other.ptr_);
}
@ -149,8 +150,7 @@ public:
inline pointer_type* operator&()
{
KGE_ASSERT(ptr_ == nullptr && "Memory leak");
return &ptr_;
return this->GetAddressOfAndRelease();
}
inline operator bool() const noexcept
@ -163,28 +163,36 @@ public:
return ptr_ == 0;
}
inline SmartPtr& operator=(const SmartPtr& other)
inline RefPtr& operator=(const RefPtr& other)
{
if (other.ptr_ != ptr_)
SmartPtr(other).Swap(*this);
RefPtr(other).Swap(*this);
return (*this);
}
inline SmartPtr& operator=(SmartPtr&& other) noexcept
inline RefPtr& operator=(RefPtr&& other) noexcept
{
if (other.ptr_ != ptr_)
other.Swap(*this);
return (*this);
}
inline SmartPtr& operator=(pointer_type p)
inline RefPtr& operator=(pointer_type p)
{
if (p != ptr_)
SmartPtr(p).Swap(*this);
RefPtr(p).Swap(*this);
return (*this);
}
inline SmartPtr& operator=(std::nullptr_t)
template <typename _UTy, typename std::enable_if<std::is_convertible<_UTy*, _Ty*>::value, int>::type = 0>
inline RefPtr& operator=(const RefPtr<_UTy, _ProxyTy>& other)
{
if (other.Get() != ptr_)
RefPtr(dynamic_cast<pointer_type>(other.Get())).Swap(*this);
return (*this);
}
inline RefPtr& operator=(std::nullptr_t)
{
Tidy();
return *this;
@ -202,67 +210,67 @@ private:
};
template <class _Ty, class _UTy, class _ProxyTy>
inline bool operator==(const SmartPtr<_Ty, _ProxyTy>& lhs, const SmartPtr<_UTy, _ProxyTy>& rhs) noexcept
inline bool operator==(const RefPtr<_Ty, _ProxyTy>& lhs, const RefPtr<_UTy, _ProxyTy>& rhs) noexcept
{
return lhs.Get() == rhs.Get();
}
template <class _Ty, class _ProxyTy>
inline bool operator==(const SmartPtr<_Ty, _ProxyTy>& lhs, _Ty* rhs) noexcept
inline bool operator==(const RefPtr<_Ty, _ProxyTy>& lhs, _Ty* rhs) noexcept
{
return lhs.Get() == rhs;
}
template <class _Ty, class _ProxyTy>
inline bool operator==(_Ty* lhs, const SmartPtr<_Ty, _ProxyTy>& rhs) noexcept
inline bool operator==(_Ty* lhs, const RefPtr<_Ty, _ProxyTy>& rhs) noexcept
{
return lhs == rhs.Get();
}
template <class _Ty, class _ProxyTy>
inline bool operator==(const SmartPtr<_Ty, _ProxyTy>& lhs, std::nullptr_t) noexcept
inline bool operator==(const RefPtr<_Ty, _ProxyTy>& lhs, std::nullptr_t) noexcept
{
return !static_cast<bool>(lhs);
}
template <class _Ty, class _ProxyTy>
inline bool operator==(std::nullptr_t, const SmartPtr<_Ty, _ProxyTy>& rhs) noexcept
inline bool operator==(std::nullptr_t, const RefPtr<_Ty, _ProxyTy>& rhs) noexcept
{
return !static_cast<bool>(rhs);
}
template <class _Ty, class _UTy, class _ProxyTy>
inline bool operator!=(const SmartPtr<_Ty, _ProxyTy>& lhs, const SmartPtr<_UTy, _ProxyTy>& rhs) noexcept
inline bool operator!=(const RefPtr<_Ty, _ProxyTy>& lhs, const RefPtr<_UTy, _ProxyTy>& rhs) noexcept
{
return !(lhs == rhs);
}
template <class _Ty, class _ProxyTy>
inline bool operator!=(const SmartPtr<_Ty, _ProxyTy>& lhs, _Ty* rhs) noexcept
inline bool operator!=(const RefPtr<_Ty, _ProxyTy>& lhs, _Ty* rhs) noexcept
{
return lhs.Get() != rhs;
}
template <class _Ty, class _ProxyTy>
inline bool operator!=(_Ty* lhs, const SmartPtr<_Ty, _ProxyTy>& rhs) noexcept
inline bool operator!=(_Ty* lhs, const RefPtr<_Ty, _ProxyTy>& rhs) noexcept
{
return lhs != rhs.Get();
}
template <class _Ty, class _ProxyTy>
inline bool operator!=(const SmartPtr<_Ty, _ProxyTy>& lhs, std::nullptr_t) noexcept
inline bool operator!=(const RefPtr<_Ty, _ProxyTy>& lhs, std::nullptr_t) noexcept
{
return static_cast<bool>(lhs);
}
template <class _Ty, class _ProxyTy>
inline bool operator!=(std::nullptr_t, const SmartPtr<_Ty, _ProxyTy>& rhs) noexcept
inline bool operator!=(std::nullptr_t, const RefPtr<_Ty, _ProxyTy>& rhs) noexcept
{
return static_cast<bool>(rhs);
}
template <class _Ty, class _UTy, class _ProxyTy>
inline bool operator<(const SmartPtr<_Ty, _ProxyTy>& lhs, const SmartPtr<_UTy, _ProxyTy>& rhs) noexcept
inline bool operator<(const RefPtr<_Ty, _ProxyTy>& lhs, const RefPtr<_UTy, _ProxyTy>& rhs) noexcept
{
return lhs.Get() < rhs.Get();
}
@ -270,15 +278,27 @@ 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
template <class _Ty, class _ProxyTy>
inline void swap(SmartPtr<_Ty, _ProxyTy>& lhs, SmartPtr<_Ty, _ProxyTy>& rhs) noexcept
inline void swap(RefPtr<_Ty, _ProxyTy>& lhs, RefPtr<_Ty, _ProxyTy>& rhs) noexcept
{
lhs.Swap(rhs);
}
template <typename _Ty, typename... _Args>
inline RefPtr<_Ty> MakePtr(_Args&&... args)
{
static_assert(std::is_base_of<RefObject, _Ty>::value, "_Ty must be derived from RefObject");
RefPtr<_Ty> ptr;
_Ty** pptr = ptr.GetAddressOfAndRelease();
(*pptr) = new _Ty(std::forward<_Args>(args)...);
return ptr;
}
} // namespace kiwano
#ifndef KGE_DECLARE_SMART_PTR
#define KGE_DECLARE_SMART_PTR(CLASS) \
class CLASS; \
typedef ::kiwano::SmartPtr<CLASS> CLASS##Ptr;
typedef ::kiwano::RefPtr<CLASS> CLASS##Ptr;
#endif

View File

@ -19,7 +19,7 @@
// THE SOFTWARE.
#pragma once
#include <kiwano/core/SmartPtr.hpp>
#include <kiwano/core/RefPtr.hpp>
#include <kiwano/event/EventType.h>
#include <kiwano/math/Math.h>
@ -39,7 +39,7 @@ KGE_DECLARE_SMART_PTR(Event);
/// \~chinese
/// @brief 事件
class KGE_API Event : public RefCounter
class KGE_API Event : public RefObject
{
public:
/// \~chinese

View File

@ -26,7 +26,7 @@ namespace kiwano
EventListenerPtr EventListener::Create(EventType type, const Callback& callback)
{
EventListenerPtr ptr = memory::New<EventListener>();
EventListenerPtr ptr = new (autogc) EventListener;
if (ptr)
{
ptr->SetEventType(type);
@ -37,7 +37,7 @@ EventListenerPtr EventListener::Create(EventType type, const Callback& callback)
EventListenerPtr EventListener::Create(const String& name, EventType type, const Callback& callback)
{
EventListenerPtr ptr = memory::New<EventListener>();
EventListenerPtr ptr = new (autogc) EventListener;
if (ptr)
{
ptr->SetName(name);

View File

@ -21,7 +21,7 @@
#pragma once
#include <kiwano/core/Common.h>
#include <kiwano/base/ObjectBase.h>
#include <kiwano/core/SmartPtr.hpp>
#include <kiwano/core/RefPtr.hpp>
#include <kiwano/core/IntrusiveList.h>
#include <kiwano/event/Events.h>

View File

@ -46,14 +46,14 @@
#include <kiwano/core/Common.h>
#include <kiwano/core/Defer.h>
#include <kiwano/core/Resource.h>
#include <kiwano/core/SmartPtr.hpp>
#include <kiwano/core/RefPtr.hpp>
#include <kiwano/core/Time.h>
//
// base
//
#include <kiwano/base/RefCounter.h>
#include <kiwano/base/RefObject.h>
#include <kiwano/base/ObjectBase.h>
#include <kiwano/base/Director.h>
#include <kiwano/base/Module.h>

View File

@ -21,6 +21,7 @@
#include <kiwano/platform/Application.h>
#include <kiwano/core/Defer.h>
#include <kiwano/base/Director.h>
#include <kiwano/base/ObjectPool.h>
#include <kiwano/render/Renderer.h>
#include <kiwano/render/TextureCache.h>
#include <kiwano/utils/ResourceCache.h>
@ -82,6 +83,9 @@ void Application::Run(RunnerPtr runner)
// Execute main loop
if (!runner->MainLoop(timer_->GetDeltaTime()))
running_ = false;
// Clear objects
ObjectPool::GetInstance().Clear();
}
}
@ -133,6 +137,9 @@ void Application::Destroy()
// Clear device resources
TextureCache::GetInstance().Clear();
Renderer::GetInstance().Destroy();
// Clear objects
ObjectPool::GetInstance().Clear();
}
void Application::Use(Module& module)

View File

@ -30,7 +30,7 @@ namespace kiwano
RunnerPtr Runner::Create(Settings settings)
{
RunnerPtr ptr = memory::New<Runner>();
RunnerPtr ptr = new (autogc) Runner;
if (ptr)
{
ptr->SetSettings(settings);
@ -59,7 +59,7 @@ RunnerPtr Runner::Create(Settings settings, Function<void()> on_ready, Function<
Function<void()> on_destroy;
};
SmartPtr<CallbackRunner> ptr = memory::New<CallbackRunner>();
RefPtr<CallbackRunner> ptr = new (autogc) CallbackRunner;
if (ptr)
{
ptr->on_ready = on_ready;

View File

@ -21,7 +21,7 @@
#pragma once
#include <type_traits>
#include <kiwano/core/Common.h>
#include <kiwano/core/SmartPtr.hpp>
#include <kiwano/core/RefPtr.hpp>
#include <Unknwnbase.h>
namespace kiwano
@ -43,6 +43,6 @@ struct ComPtrProxy
// ComPtr<> is a smart pointer for COM
template <typename _Ty, typename = typename std::enable_if<std::is_base_of<IUnknown, _Ty>::value, int>::type>
using ComPtr = SmartPtr<_Ty, ComPtrProxy>;
using ComPtr = RefPtr<_Ty, ComPtrProxy>;
} // namespace kiwano

View File

@ -90,7 +90,7 @@ private:
WindowPtr Window::Create(const WindowConfig& config)
{
WindowWin32ImplPtr ptr = memory::New<WindowWin32Impl>();
WindowWin32ImplPtr ptr = new (autogc) WindowWin32Impl;
if (ptr)
{
ptr->Init(config);

View File

@ -61,7 +61,7 @@ RadialGradientStyle::RadialGradientStyle(const Point& center, const Vec2& offset
BrushPtr Brush::Create(const Color& color)
{
BrushPtr ptr = memory::New<Brush>();
BrushPtr ptr = new (autogc) Brush;
if (ptr)
{
ptr->SetColor(color);
@ -71,7 +71,7 @@ BrushPtr Brush::Create(const Color& color)
BrushPtr Brush::Create(const LinearGradientStyle& style)
{
BrushPtr ptr = memory::New<Brush>();
BrushPtr ptr = new (autogc) Brush;
if (ptr)
{
ptr->SetStyle(style);
@ -81,7 +81,7 @@ BrushPtr Brush::Create(const LinearGradientStyle& style)
BrushPtr Brush::Create(const RadialGradientStyle& style)
{
BrushPtr ptr = memory::New<Brush>();
BrushPtr ptr = new (autogc) Brush;
if (ptr)
{
ptr->SetStyle(style);

View File

@ -97,7 +97,7 @@ void RendererImpl::MakeContextForWindow(WindowPtr window)
// Initialize other device resources
if (SUCCEEDED(hr))
{
RenderContextImplPtr ctx = memory::New<RenderContextImpl>();
RenderContextImplPtr ctx = new (autogc) RenderContextImpl;
hr = ctx->CreateDeviceResources(d2d_res_->GetFactory(), d2d_res_->GetDeviceContext());
if (SUCCEEDED(hr))
@ -403,7 +403,7 @@ void RendererImpl::CreateGifImageFrame(GifImage::Frame& frame, const GifImage& g
if (SUCCEEDED(hr))
{
frame.texture = memory::New<Texture>();
frame.texture = new (autogc) Texture;
NativePtr::Set(frame.texture, bitmap);
frame.texture->SetSize({ bitmap->GetSize().width, bitmap->GetSize().height });
@ -769,7 +769,7 @@ void RendererImpl::CreateShapeSink(ShapeMaker& maker)
if (SUCCEEDED(hr))
{
ShapePtr shape = memory::New<Shape>();
ShapePtr shape = new (autogc) Shape;
NativePtr::Set(shape, geometry);
maker.SetShape(shape);
@ -945,7 +945,7 @@ void RendererImpl::CreateStrokeStyle(StrokeStyle& stroke_style)
RenderContextPtr RendererImpl::CreateTextureRenderContext(Texture& texture, const Size* desired_size)
{
RenderContextImplPtr ptr = memory::New<RenderContextImpl>();
RenderContextImplPtr ptr = new (autogc) RenderContextImpl;
HRESULT hr = S_OK;
if (!d2d_res_)

View File

@ -82,7 +82,7 @@ HRESULT ITextRenderer::Create(_Out_ ITextRenderer** ppTextRenderer, _In_ ID2D1Re
if (ppTextRenderer)
{
TextRenderer* pTextRenderer = memory::New<TextRenderer>();
TextRenderer* pTextRenderer = new (std::nothrow) TextRenderer;
if (pTextRenderer)
{
hr = pTextRenderer->CreateDeviceResources(pRT);

View File

@ -26,7 +26,7 @@ namespace kiwano
FontPtr Font::Create(const String& file)
{
FontPtr ptr = memory::New<Font>();
FontPtr ptr = new (autogc) Font;
if (ptr)
{
if (!ptr->Load(file))
@ -37,7 +37,7 @@ FontPtr Font::Create(const String& file)
FontPtr Font::Create(const Resource& resource)
{
FontPtr ptr = memory::New<Font>();
FontPtr ptr = new (autogc) Font;
if (ptr)
{
if (!ptr->Load(resource))

View File

@ -26,7 +26,7 @@ namespace kiwano
FramePtr Frame::Create(const String& file_path)
{
FramePtr ptr = memory::New<Frame>();
FramePtr ptr = new (autogc) Frame;
if (ptr)
{
if (!ptr->Load(file_path))
@ -37,7 +37,7 @@ FramePtr Frame::Create(const String& file_path)
FramePtr Frame::Create(const Resource& res)
{
FramePtr ptr = memory::New<Frame>();
FramePtr ptr = new (autogc) Frame;
if (ptr)
{
if (!ptr->Load(res))
@ -48,7 +48,7 @@ FramePtr Frame::Create(const Resource& res)
FramePtr Frame::Create(TexturePtr texture)
{
FramePtr ptr = memory::New<Frame>();
FramePtr ptr = new (autogc) Frame;
if (ptr)
{
ptr->SetTexture(texture);

View File

@ -26,13 +26,13 @@ namespace kiwano
FrameSequencePtr FrameSequence::Create()
{
FrameSequencePtr ptr = memory::New<FrameSequence>();
FrameSequencePtr ptr = new (autogc) FrameSequence;
return ptr;
}
FrameSequencePtr FrameSequence::Create(const Vector<FramePtr>& frames)
{
FrameSequencePtr ptr = memory::New<FrameSequence>();
FrameSequencePtr ptr = new (autogc) FrameSequence;
if (ptr)
{
ptr->AddFrames(frames);
@ -43,7 +43,7 @@ FrameSequencePtr FrameSequence::Create(const Vector<FramePtr>& frames)
FrameSequencePtr FrameSequence::Create(FramePtr frame, int cols, int rows, int max_num, float padding_x,
float padding_y)
{
FrameSequencePtr ptr = memory::New<FrameSequence>();
FrameSequencePtr ptr = new (autogc) FrameSequence;
if (ptr)
{
ptr->AddFrames(frame, cols, rows, max_num, padding_x, padding_y);
@ -103,7 +103,7 @@ void FrameSequence::AddFrames(FramePtr frame, int cols, int rows, int max_num, f
for (int j = 0; j < cols; j++)
{
FramePtr ptr = memory::New<Frame>();
FramePtr ptr = new (autogc) Frame;
if (ptr)
{
ptr->SetTexture(frame->GetTexture());
@ -140,7 +140,7 @@ size_t FrameSequence::GetFramesCount() const
FrameSequencePtr FrameSequence::Clone() const
{
auto frame_seq = memory::New<FrameSequence>();
auto frame_seq = new (autogc) FrameSequence;
if (frame_seq)
{
frame_seq->AddFrames(frames_);
@ -150,7 +150,7 @@ FrameSequencePtr FrameSequence::Clone() const
FrameSequencePtr FrameSequence::Reverse() const
{
auto frame_seq = memory::New<FrameSequence>();
auto frame_seq = new (autogc) FrameSequence;
if (!frames_.empty())
{
for (auto iter = frames_.crbegin(), crend = frames_.crend(); iter != crend; ++iter)

View File

@ -27,7 +27,7 @@ namespace kiwano
GifImagePtr GifImage::Create(const String& file_path)
{
GifImagePtr ptr = memory::New<GifImage>();
GifImagePtr ptr = new (autogc) GifImage;
if (ptr)
{
if (!ptr->Load(file_path))
@ -38,7 +38,7 @@ GifImagePtr GifImage::Create(const String& file_path)
GifImagePtr GifImage::Create(const Resource& res)
{
GifImagePtr ptr = memory::New<GifImage>();
GifImagePtr ptr = new (autogc) GifImage;
if (ptr)
{
if (!ptr->Load(res))

View File

@ -136,35 +136,35 @@ bool Shape::ContainsPoint(const Point& point, const Matrix3x2* transform) const
ShapePtr Shape::CreateLine(const Point& begin, const Point& end)
{
ShapePtr output = memory::New<Shape>();
ShapePtr output = new (autogc) Shape;
Renderer::GetInstance().CreateLineShape(*output, begin, end);
return output;
}
ShapePtr Shape::CreateRect(const Rect& rect)
{
ShapePtr output = memory::New<Shape>();
ShapePtr output = new (autogc) Shape;
Renderer::GetInstance().CreateRectShape(*output, rect);
return output;
}
ShapePtr Shape::CreateRoundedRect(const Rect& rect, const Vec2& radius)
{
ShapePtr output = memory::New<Shape>();
ShapePtr output = new (autogc) Shape;
Renderer::GetInstance().CreateRoundedRectShape(*output, rect, radius);
return output;
}
ShapePtr Shape::CreateCircle(const Point& center, float radius)
{
ShapePtr output = memory::New<Shape>();
ShapePtr output = new (autogc) Shape;
Renderer::GetInstance().CreateEllipseShape(*output, center, Vec2{ radius, radius });
return output;
}
ShapePtr Shape::CreateEllipse(const Point& center, const Vec2& radius)
{
ShapePtr output = memory::New<Shape>();
ShapePtr output = new (autogc) Shape;
Renderer::GetInstance().CreateEllipseShape(*output, center, radius);
return output;
}

View File

@ -30,8 +30,8 @@ namespace kiwano
ShapeMakerPtr ShapeMaker::Create()
{
ShapeMakerPtr maker = memory::New<ShapeMaker>();
return maker;
ShapeMakerPtr ptr = new (autogc) ShapeMaker;
return ptr;
}
ShapeMaker::ShapeMaker() {}

View File

@ -32,7 +32,7 @@ StrokeStylePtr StrokeStyle::Create(float width, CapStyle cap, LineJoinStyle line
StrokeStylePtr StrokeStyle::Create(float width, CapStyle cap, LineJoinStyle line_join, DashStyle dash,
float dash_offset)
{
StrokeStylePtr ptr = memory::New<StrokeStyle>();
StrokeStylePtr ptr = new (autogc) StrokeStyle;
if (ptr)
{
ptr->SetStrokeWidth(width);
@ -47,7 +47,7 @@ StrokeStylePtr StrokeStyle::Create(float width, CapStyle cap, LineJoinStyle line
StrokeStylePtr StrokeStyle::Create(float width, CapStyle cap, LineJoinStyle line_join, const float* dash_array,
size_t dash_size, float dash_offset)
{
StrokeStylePtr ptr = memory::New<StrokeStyle>();
StrokeStylePtr ptr = new (autogc) StrokeStyle;
if (ptr)
{
ptr->SetStrokeWidth(width);

View File

@ -30,13 +30,13 @@ namespace kiwano
TextLayoutPtr TextLayout::Create()
{
TextLayoutPtr ptr = memory::New<TextLayout>();
TextLayoutPtr ptr = new (autogc) TextLayout;
return ptr;
}
TextLayoutPtr TextLayout::Create(const String& content, const TextStyle& style)
{
TextLayoutPtr ptr = memory::New<TextLayout>();
TextLayoutPtr ptr = new (autogc) TextLayout;
if (ptr)
{
ptr->Reset(content, style);

View File

@ -32,7 +32,7 @@ InterpolationMode Texture::default_interpolation_mode_ = InterpolationMode::Line
TexturePtr Texture::Create(const String& file_path)
{
TexturePtr ptr = memory::New<Texture>();
TexturePtr ptr = new (autogc) Texture;
if (ptr)
{
if (!ptr->Load(file_path))
@ -43,7 +43,7 @@ TexturePtr Texture::Create(const String& file_path)
TexturePtr Texture::Create(const Resource& res)
{
TexturePtr ptr = memory::New<Texture>();
TexturePtr ptr = new (autogc) Texture;
if (ptr)
{
if (!ptr->Load(res))

View File

@ -25,7 +25,7 @@
namespace kiwano
{
template <typename _Ty, typename _PathTy, typename _CacheTy>
SmartPtr<_Ty> CreateOrGetCache(_CacheTy& cache, const _PathTy& path, size_t hash)
RefPtr<_Ty> CreateOrGetCache(_CacheTy& cache, const _PathTy& path, size_t hash)
{
auto iter = cache.find(hash);
if (iter != cache.end())
@ -33,7 +33,7 @@ SmartPtr<_Ty> CreateOrGetCache(_CacheTy& cache, const _PathTy& path, size_t hash
return iter->second;
}
SmartPtr<_Ty> texture = memory::New<_Ty>();
RefPtr<_Ty> texture = new (autogc) _Ty;
if (texture->Load(path))
{
cache.insert(std::make_pair(hash, texture));

View File

@ -96,7 +96,7 @@ public:
ConfigIniPtr ConfigIni::Create(const String& file_path)
{
ConfigIniPtr ptr = memory::New<ConfigIni>();
ConfigIniPtr ptr = new (autogc) ConfigIni;
if (ptr)
{
if (!ptr->Load(file_path))

View File

@ -31,7 +31,7 @@ TickEvent::TickEvent()
EventTickerPtr EventTicker::Create(Duration interval, int times)
{
EventTickerPtr ptr = memory::New<EventTicker>();
EventTickerPtr ptr = new (autogc) EventTicker;
if (ptr)
{
ptr->SetInterval(interval);

View File

@ -244,7 +244,7 @@ ConsoleLogProvider::ConsoleColor ConsoleLogProvider::GetColor(LogLevel level)
LogProviderPtr FileLogProvider::Create(const String& filepath, std::ios_base::openmode mode)
{
SmartPtr<FileLogProvider> ptr = new FileLogProvider;
RefPtr<FileLogProvider> ptr = new FileLogProvider;
if (ptr)
{
ptr->ofs_.open(filepath, mode);

View File

@ -214,7 +214,7 @@ bool LoadTexturesFromData(ResourceCache* loader, GlobalData* gdata, const String
if (type == "gif")
{
// GIF image
GifImagePtr gif = memory::New<GifImage>();
GifImagePtr gif = new (autogc) GifImage;
if (gif && gif->Load(gdata->path + file))
{
return loader->AddObject(id, gif);
@ -224,7 +224,7 @@ bool LoadTexturesFromData(ResourceCache* loader, GlobalData* gdata, const String
if (!file.empty())
{
// Simple image
FramePtr frame = memory::New<Frame>();
FramePtr frame = new (autogc) Frame;
if (frame && frame->Load(gdata->path + file))
{
return loader->AddObject(id, frame);
@ -246,7 +246,7 @@ bool LoadTexturesFromData(ResourceCache* loader, GlobalData* gdata, const String
frames.reserve(files.size());
for (const auto& file : files)
{
FramePtr frame = memory::New<Frame>();
FramePtr frame = new (autogc) Frame;
if (frame->Load(gdata->path + file))
{
frames.push_back(frame);
@ -271,10 +271,10 @@ bool LoadTexturesFromData(ResourceCache* loader, GlobalData* gdata, const String
if (rows || cols)
{
// Frame slices
FramePtr frame = memory::New<Frame>();
FramePtr frame = new (autogc) Frame;
if (frame && frame->Load(gdata->path + file))
{
FrameSequencePtr frame_seq = memory::New<FrameSequence>();
FrameSequencePtr frame_seq = new (autogc) FrameSequence;
if (frame_seq)
{
frame_seq->AddFrames(frame, cols, rows, max_num, padding_x, padding_y);
@ -285,7 +285,7 @@ bool LoadTexturesFromData(ResourceCache* loader, GlobalData* gdata, const String
else
{
// Simple image
FramePtr frame = memory::New<Frame>();
FramePtr frame = new (autogc) Frame;
if (frame && frame->Load(gdata->path + file))
{
return loader->AddObject(id, frame);
@ -300,7 +300,7 @@ bool LoadFontsFromData(ResourceCache* loader, GlobalData* gdata, const String& i
if (!gdata)
return false;
FontPtr font = memory::New<Font>();
FontPtr font = new (autogc) Font;
if (font && font->Load(gdata->path + file))
{
return loader->AddObject(id, font);

View File

@ -68,7 +68,7 @@ public:
/// @param id 对象ID
/// @return 指定对象类型的指针
template <typename _Ty>
SmartPtr<_Ty> Get(const String& id) const
RefPtr<_Ty> Get(const String& id) const
{
return dynamic_cast<_Ty*>(Get(id).Get());
}

View File

@ -24,7 +24,7 @@ namespace kiwano
{
TaskPtr Task::Create(const Callback& cb, TickerPtr ticker)
{
TaskPtr ptr = memory::New<Task>();
TaskPtr ptr = new (autogc) Task;
if (ptr)
{
ptr->SetCallback(cb);

View File

@ -25,7 +25,7 @@ namespace kiwano
TickerPtr Ticker::Create(Duration interval, int times)
{
TickerPtr ptr = memory::New<Ticker>();
TickerPtr ptr = new (autogc) Ticker;
if (ptr)
{
ptr->SetInterval(interval);

View File

@ -26,7 +26,7 @@ namespace kiwano
TimerPtr Timer::Create()
{
TimerPtr ptr = memory::New<Timer>();
TimerPtr ptr = new (autogc) Timer;
return ptr;
}