Add allocator

This commit is contained in:
Nomango 2020-02-20 22:27:09 +08:00
parent ceb5e3b260
commit d6b95e3b40
46 changed files with 324 additions and 138 deletions

View File

@ -13,6 +13,7 @@
<ClInclude Include="..\..\src\kiwano\2d\Component.h" />
<ClInclude Include="..\..\src\kiwano\2d\Frame.h" />
<ClInclude Include="..\..\src\kiwano\2d\GifSprite.h" />
<ClInclude Include="..\..\src\kiwano\core\Allocator.h" />
<ClInclude Include="..\..\src\kiwano\core\Any.h" />
<ClInclude Include="..\..\src\kiwano\core\Common.h" />
<ClInclude Include="..\..\src\kiwano\core\Director.h" />
@ -121,6 +122,7 @@
<ClCompile Include="..\..\src\kiwano\2d\Sprite.cpp" />
<ClCompile Include="..\..\src\kiwano\2d\TextActor.cpp" />
<ClCompile Include="..\..\src\kiwano\2d\Transition.cpp" />
<ClCompile Include="..\..\src\kiwano\core\Allocator.cpp" />
<ClCompile Include="..\..\src\kiwano\core\Module.cpp" />
<ClCompile Include="..\..\src\kiwano\core\Director.cpp" />
<ClCompile Include="..\..\src\kiwano\core\EventDispatcher.cpp" />

View File

@ -318,6 +318,9 @@
<ClInclude Include="..\..\src\kiwano\2d\Component.h">
<Filter>2d</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\core\Allocator.h">
<Filter>core</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\..\src\kiwano\2d\Canvas.cpp">
@ -527,5 +530,8 @@
<ClCompile Include="..\..\src\kiwano\2d\Component.cpp">
<Filter>2d</Filter>
</ClCompile>
<ClCompile Include="..\..\src\kiwano\core\Allocator.cpp">
<Filter>core</Filter>
</ClCompile>
</ItemGroup>
</Project>

View File

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

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 = new (std::nothrow) Button;
ButtonPtr ptr = memory::New<Button>();
if (ptr)
{
ptr->SetClickCallback(click);

View File

@ -26,7 +26,8 @@ namespace kiwano
CanvasPtr Canvas::Create(const Size& size)
{
CanvasPtr ptr = new (std::nothrow) Canvas;
void* mem = memory::Alloc<Canvas>();
CanvasPtr ptr = ::new (mem) Canvas;
if (ptr)
{
try
@ -296,7 +297,7 @@ void Canvas::Clear(const Color& clear_color)
void Canvas::ResizeAndClear(Size size)
{
texture_cached_ = new Texture;
texture_cached_ = memory::New<Texture>();
render_ctx_ = RenderContext::Create(*texture_cached_, size);
SetSize(render_ctx_->GetSize());

View File

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

View File

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

View File

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

View File

@ -26,13 +26,13 @@ namespace kiwano
FrameSequencePtr FrameSequence::Create()
{
FrameSequencePtr ptr = new (std::nothrow) FrameSequence;
FrameSequencePtr ptr = memory::New<FrameSequence>();
return ptr;
}
FrameSequencePtr FrameSequence::Create(const Vector<FramePtr>& frames)
{
FrameSequencePtr ptr = new (std::nothrow) FrameSequence;
FrameSequencePtr ptr = memory::New<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 = new (std::nothrow) FrameSequence;
FrameSequencePtr ptr = memory::New<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 = new (std::nothrow) Frame;
FramePtr ptr = memory::New<Frame>();
if (ptr)
{
ptr->SetTexture(frame->GetTexture());
@ -140,7 +140,7 @@ size_t FrameSequence::GetFramesCount() const
FrameSequencePtr FrameSequence::Clone() const
{
auto frame_seq = new (std::nothrow) FrameSequence;
auto frame_seq = memory::New<FrameSequence>();
if (frame_seq)
{
frame_seq->AddFrames(frames_);
@ -150,7 +150,7 @@ FrameSequencePtr FrameSequence::Clone() const
FrameSequencePtr FrameSequence::Reverse() const
{
auto frame_seq = new (std::nothrow) FrameSequence;
auto frame_seq = memory::New<FrameSequence>();
if (!frames_.empty())
{
for (auto iter = frames_.crbegin(), crend = frames_.crend(); iter != crend; ++iter)

View File

@ -27,7 +27,7 @@ namespace kiwano
GifSpritePtr GifSprite::Create(const String& file_path)
{
GifSpritePtr ptr = new (std::nothrow) GifSprite;
GifSpritePtr ptr = memory::New<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 = new (std::nothrow) GifSprite;
GifSpritePtr ptr = memory::New<GifSprite>();
if (ptr)
{
if (!ptr->Load(res))
@ -49,7 +49,7 @@ GifSpritePtr GifSprite::Create(const Resource& res)
GifSpritePtr GifSprite::Create(GifImagePtr gif)
{
GifSpritePtr ptr = new (std::nothrow) GifSprite;
GifSpritePtr ptr = memory::New<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_ = new Texture;
frame_to_render_ = memory::New<Texture>();
frame_rt_ = RenderContext::Create(*frame_to_render_, frame_size);
SetSize(frame_rt_->GetSize());
@ -231,7 +231,7 @@ void GifSprite::SaveComposedFrame()
if (!saved_frame_)
{
saved_frame_ = new Texture;
saved_frame_ = memory::New<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 = new (std::nothrow) LayerActor;
LayerActorPtr ptr = memory::New<LayerActor>();
return ptr;
}

View File

@ -27,7 +27,7 @@ namespace kiwano
ShapeActorPtr ShapeActor::Create(ShapePtr shape)
{
ShapeActorPtr ptr = new (std::nothrow) ShapeActor;
ShapeActorPtr ptr = memory::New<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 = new (std::nothrow) LineActor;
LineActorPtr ptr = memory::New<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 = new (std::nothrow) RectActor;
RectActorPtr ptr = memory::New<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 = new (std::nothrow) RoundedRectActor;
RoundedRectActorPtr ptr = memory::New<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 = new (std::nothrow) CircleActor;
CircleActorPtr ptr = memory::New<CircleActor>();
if (ptr)
{
ptr->SetRadius(radius);
@ -252,7 +252,7 @@ void CircleActor::SetRadius(float radius)
EllipseActorPtr EllipseActor::Create(const Vec2& radius)
{
EllipseActorPtr ptr = new (std::nothrow) EllipseActor;
EllipseActorPtr ptr = memory::New<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 = new (std::nothrow) PolygonActor;
PolygonActorPtr ptr = memory::New<PolygonActor>();
if (ptr)
{
ptr->SetVertices(points);

View File

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

View File

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

View File

@ -27,7 +27,7 @@ namespace kiwano
StagePtr Stage::Create()
{
StagePtr ptr = new (std::nothrow) Stage;
StagePtr ptr = memory::New<Stage>();
return ptr;
}
@ -57,13 +57,13 @@ void Stage::RenderBorder(RenderContext& ctx)
if (!border_fill_brush_)
{
border_fill_brush_ = new Brush;
border_fill_brush_ = memory::New<Brush>();
border_fill_brush_->SetColor(Color(Color::Red, .4f));
}
if (!border_stroke_brush_)
{
border_stroke_brush_ = new Brush;
border_stroke_brush_ = memory::New<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 = new (std::nothrow) TextActor;
TextActorPtr ptr = memory::New<TextActor>();
if (ptr)
{
ptr->SetStyle(style);

View File

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

View File

@ -25,7 +25,7 @@ namespace kiwano
ActionDelayPtr ActionDelay::Create(Duration delay)
{
ActionDelayPtr ptr = new (std::nothrow) ActionDelay;
ActionDelayPtr ptr = memory::New<ActionDelay>();
if (ptr)
{
ptr->SetDelay(delay);

View File

@ -27,9 +27,10 @@ namespace kiwano
ActionGroupPtr ActionGroup::Create(const Vector<ActionPtr>& actions, bool sync)
{
ActionGroupPtr ptr = new (std::nothrow) ActionGroup(sync);
ActionGroupPtr ptr = memory::New<ActionGroup>();
if (ptr)
{
ptr->sync_ = sync;
ptr->AddActions(actions);
}
return ptr;

View File

@ -146,7 +146,7 @@ ActionPtr ActionTween::InnerClone(ActionTweenPtr to) const
ActionMoveByPtr ActionMoveBy::Create(Duration duration, const Vec2& displacement)
{
ActionMoveByPtr ptr = new (std::nothrow) ActionMoveBy;
ActionMoveByPtr ptr = memory::New<ActionMoveBy>();
if (ptr)
{
ptr->SetDuration(duration);
@ -188,7 +188,7 @@ ActionPtr ActionMoveBy::Reverse() const
ActionMoveToPtr ActionMoveTo::Create(Duration duration, const Point& distination)
{
ActionMoveToPtr ptr = new (std::nothrow) ActionMoveTo;
ActionMoveToPtr ptr = memory::New<ActionMoveTo>();
if (ptr)
{
ptr->SetDuration(duration);
@ -217,7 +217,7 @@ void ActionMoveTo::Init(Actor* target)
ActionJumpByPtr ActionJumpBy::Create(Duration duration, const Vec2& displacement, float height, int count,
EaseFunc ease)
{
ActionJumpByPtr ptr = new (std::nothrow) ActionJumpBy;
ActionJumpByPtr ptr = memory::New<ActionJumpBy>();
if (ptr)
{
ptr->SetDuration(duration);
@ -272,7 +272,7 @@ void ActionJumpBy::UpdateTween(Actor* target, float percent)
ActionJumpToPtr ActionJumpTo::Create(Duration duration, const Point& distination, float height, int count,
EaseFunc ease)
{
ActionJumpToPtr ptr = new (std::nothrow) ActionJumpTo;
ActionJumpToPtr ptr = memory::New<ActionJumpTo>();
if (ptr)
{
ptr->SetDuration(duration);
@ -303,7 +303,7 @@ void ActionJumpTo::Init(Actor* target)
ActionScaleByPtr ActionScaleBy::Create(Duration duration, float scale_x, float scale_y)
{
ActionScaleByPtr ptr = new (std::nothrow) ActionScaleBy;
ActionScaleByPtr ptr = memory::New<ActionScaleBy>();
if (ptr)
{
ptr->SetDuration(duration);
@ -347,7 +347,7 @@ ActionPtr ActionScaleBy::Reverse() const
ActionScaleToPtr ActionScaleTo::Create(Duration duration, float scale_x, float scale_y)
{
ActionScaleToPtr ptr = new (std::nothrow) ActionScaleTo;
ActionScaleToPtr ptr = memory::New<ActionScaleTo>();
if (ptr)
{
ptr->SetDuration(duration);
@ -381,7 +381,7 @@ void ActionScaleTo::Init(Actor* target)
ActionFadeToPtr ActionFadeTo::Create(Duration duration, float opacity)
{
ActionFadeToPtr ptr = new (std::nothrow) ActionFadeTo;
ActionFadeToPtr ptr = memory::New<ActionFadeTo>();
if (ptr)
{
ptr->SetDuration(duration);
@ -418,7 +418,7 @@ ActionPtr ActionFadeTo::Clone() const
ActionFadeInPtr ActionFadeIn::Create(Duration duration)
{
ActionFadeInPtr ptr = new (std::nothrow) ActionFadeIn;
ActionFadeInPtr ptr = memory::New<ActionFadeIn>();
if (ptr)
{
ptr->SetDuration(duration);
@ -429,7 +429,7 @@ ActionFadeInPtr ActionFadeIn::Create(Duration duration)
ActionFadeOutPtr ActionFadeOut::Create(Duration duration)
{
ActionFadeOutPtr ptr = new (std::nothrow) ActionFadeOut;
ActionFadeOutPtr ptr = memory::New<ActionFadeOut>();
if (ptr)
{
ptr->SetDuration(duration);
@ -444,7 +444,7 @@ ActionFadeOutPtr ActionFadeOut::Create(Duration duration)
ActionRotateByPtr ActionRotateBy::Create(Duration duration, float rotation)
{
ActionRotateByPtr ptr = new (std::nothrow) ActionRotateBy;
ActionRotateByPtr ptr = memory::New<ActionRotateBy>();
if (ptr)
{
ptr->SetDuration(duration);
@ -488,7 +488,7 @@ ActionPtr ActionRotateBy::Reverse() const
ActionRotateToPtr ActionRotateTo::Create(Duration duration, float rotation)
{
ActionRotateToPtr ptr = new (std::nothrow) ActionRotateTo;
ActionRotateToPtr ptr = memory::New<ActionRotateTo>();
if (ptr)
{
ptr->SetDuration(duration);
@ -519,7 +519,7 @@ void ActionRotateTo::Init(Actor* target)
ActionCustomPtr ActionCustom::Create(Duration duration, TweenFunc tween_func)
{
ActionCustomPtr ptr = new (std::nothrow) ActionCustom;
ActionCustomPtr ptr = memory::New<ActionCustom>();
if (ptr)
{
ptr->SetDuration(duration);

View File

@ -26,7 +26,7 @@ namespace kiwano
ActionWalkPtr ActionWalk::Create(Duration duration, ShapePtr path, bool rotating, float start, float end)
{
ActionWalkPtr ptr = new (std::nothrow) ActionWalk;
ActionWalkPtr ptr = memory::New<ActionWalk>();
if (ptr)
{
ptr->SetDuration(duration);

View File

@ -27,7 +27,7 @@ namespace kiwano
AnimationPtr Animation::Create(Duration duration, FrameSequencePtr frame_seq)
{
AnimationPtr ptr = new (std::nothrow) Animation;
AnimationPtr ptr = memory::New<Animation>();
if (ptr)
{
ptr->SetDuration(duration);

View File

@ -0,0 +1,58 @@
// 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 <kiwano/core/Allocator.h>
namespace kiwano
{
namespace memory
{
MemoryAllocator* current_allocator_ = GetGlobalAllocator();
MemoryAllocator* GetAllocator()
{
return current_allocator_;
}
void SetAllocator(MemoryAllocator* allocator)
{
KGE_ASSERT(allocator);
current_allocator_ = allocator;
}
GlobalAllocator* GetGlobalAllocator()
{
static GlobalAllocator global_allocator;
return &global_allocator;
}
void* GlobalAllocator::Alloc(size_t size)
{
return ::malloc(size);
}
void GlobalAllocator::Free(void* ptr)
{
::free(ptr);
}
} // namespace memory
} // namespace kiwano

125
src/kiwano/core/Allocator.h Normal file
View File

@ -0,0 +1,125 @@
// 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 <utility>
#include <type_traits>
#include <kiwano/macros.h>
namespace kiwano
{
namespace memory
{
/// \~chinese
/// @brief 内存分配器
class KGE_API MemoryAllocator
{
public:
/// \~chinese
/// @brief 申请内存
virtual void* Alloc(size_t size) = 0;
/// \~chinese
/// @brief 释放内存
virtual void Free(void* ptr) = 0;
};
/// \~chinese
/// @brief 获取当前内存分配器
MemoryAllocator* GetAllocator();
/// \~chinese
/// @brief 设置当前内存分配器
void SetAllocator(MemoryAllocator* allocator);
/// \~chinese
/// @brief 使用当前内存分配器分配内存
template <typename _Ty>
inline void* Alloc()
{
return memory::GetAllocator()->Alloc(sizeof(_Ty));
}
/// \~chinese
/// @brief 使用当前内存分配器释放内存
inline void Free(void* ptr)
{
return memory::GetAllocator()->Free(ptr);
}
/// \~chinese
/// @brief 使用当前内存分配器创建对象
template <typename _Ty>
inline _Ty* New()
{
void* ptr = memory::Alloc<_Ty>();
if (ptr)
{
return ::new (ptr) _Ty;
}
return nullptr;
}
/// \~chinese
/// @brief 使用当前内存分配器创建对象
template <typename _Ty, typename... _Args>
inline _Ty* New(_Args&&... args)
{
void* ptr = memory::Alloc<_Ty>();
if (ptr)
{
return ::new (ptr) _Ty(std::forward<_Args>(args)...);
}
return nullptr;
}
/// \~chinese
/// @brief 使用当前内存分配器销毁对象
template <typename _Ty>
inline void Delete(_Ty* ptr)
{
if (ptr)
{
ptr->~_Ty();
memory::Free(ptr);
}
}
/// \~chinese
/// @brief 全局内存分配器使用malloc和free分配内存
class KGE_API GlobalAllocator : public MemoryAllocator
{
public:
/// \~chinese
/// @brief 申请内存
virtual void* Alloc(size_t size) override;
/// \~chinese
/// @brief 释放内存
virtual void Free(void* ptr) override;
};
/// \~chinese
/// @brief 获取全局内存分配器
GlobalAllocator* GetGlobalAllocator();
} // namespace memory
} // namespace kiwano

View File

@ -33,6 +33,7 @@
#include <kiwano/core/Function.h>
#include <kiwano/core/Singleton.h>
#include <kiwano/core/Any.h>
#include <kiwano/core/Allocator.h>
namespace kiwano
{

View File

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

View File

@ -26,7 +26,7 @@ namespace kiwano
EventListenerPtr EventListener::Create(EventType type, const Callback& callback)
{
EventListenerPtr ptr = new (std::nothrow) EventListener;
EventListenerPtr ptr = memory::New<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 = new (std::nothrow) EventListener;
EventListenerPtr ptr = memory::New<EventListener>();
if (ptr)
{
ptr->SetName(name);

View File

@ -35,7 +35,6 @@ uint32_t last_object_id = 0;
ObjectBase::ObjectBase()
: tracing_leak_(false)
, user_data_()
, name_(nullptr)
, id_(++last_object_id)
{
#ifdef KGE_DEBUG
@ -45,11 +44,7 @@ ObjectBase::ObjectBase()
ObjectBase::~ObjectBase()
{
if (name_)
{
delete name_;
name_ = nullptr;
}
name_.reset();
#ifdef KGE_DEBUG
ObjectBase::RemoveObjectFromTracingList(this);
@ -80,7 +75,7 @@ void ObjectBase::SetName(const String& name)
if (!name_)
{
name_ = new (std::nothrow) String(name);
name_ = std::make_unique<String>(name);
return;
}

View File

@ -97,11 +97,12 @@ private:
static void RemoveObjectFromTracingList(ObjectBase*);
private:
bool tracing_leak_;
Any user_data_;
String* name_;
const uint32_t id_;
bool tracing_leak_;
Any user_data_;
std::unique_ptr<String> name_;
};
inline String ObjectBase::GetName() const

View File

@ -37,8 +37,10 @@ void RefCounter::Retain()
void RefCounter::Release()
{
--ref_count_;
if (ref_count_ <= 0)
delete this;
if (ref_count_ == 0)
{
memory::Delete(this);
}
}
} // namespace kiwano

View File

@ -31,6 +31,10 @@ namespace kiwano
class KGE_API RefCounter : protected Noncopyable
{
public:
RefCounter();
virtual ~RefCounter();
/// \~chinese
/// @brief 增加引用计数
void Retain();
@ -43,11 +47,6 @@ public:
/// @brief 获取引用计数
uint32_t GetRefCount() const;
protected:
RefCounter();
virtual ~RefCounter();
private:
std::atomic<uint32_t> ref_count_;
};

View File

@ -25,7 +25,7 @@ namespace kiwano
TimerPtr Timer::Create(const Callback& cb, Duration interval, int times)
{
TimerPtr ptr = new (std::nothrow) Timer;
TimerPtr ptr = memory::New<Timer>();
if (ptr)
{
ptr->SetCallback(cb);
@ -37,7 +37,7 @@ TimerPtr Timer::Create(const Callback& cb, Duration interval, int times)
TimerPtr Timer::Create(const String& name, const Callback& cb, Duration interval, int times)
{
TimerPtr ptr = new (std::nothrow) Timer;
TimerPtr ptr = memory::New<Timer>();
if (ptr)
{
ptr->SetName(name);

View File

@ -26,7 +26,7 @@ namespace kiwano
RunnerPtr Runner::Create(WindowPtr main_window)
{
RunnerPtr ptr = new (std::nothrow) Runner;
RunnerPtr ptr = memory::New<Runner>();
if (ptr)
{
ptr->SetMainWindow(main_window);
@ -55,7 +55,7 @@ RunnerPtr Runner::Create(WindowPtr main_window, Function<void()> on_ready, Funct
Function<void()> on_destroy;
};
SmartPtr<CallbackRunner> ptr = new (std::nothrow) CallbackRunner;
SmartPtr<CallbackRunner> ptr = memory::New<CallbackRunner>();
if (ptr)
{
ptr->on_ready = on_ready;

View File

@ -75,16 +75,16 @@ public:
private:
bool resizable_;
bool is_fullscreen_;
wchar_t* device_name_;
CursorType mouse_cursor_;
std::array<KeyCode, 256> key_map_;
std::unique_ptr<wchar_t[]> device_name_;
std::array<KeyCode, 256> key_map_;
};
WindowPtr Window::Create(const String& title, uint32_t width, uint32_t height, uint32_t icon, bool resizable,
bool fullscreen)
{
WindowWin32ImplPtr ptr = new (std::nothrow) WindowWin32Impl;
WindowWin32ImplPtr ptr = memory::New<WindowWin32Impl>();
if (ptr)
{
ptr->Init(title, width, height, icon, resizable, fullscreen);
@ -158,8 +158,7 @@ void RestoreResolution(WCHAR* device_name)
} // namespace
WindowWin32Impl::WindowWin32Impl()
: device_name_(nullptr)
, is_fullscreen_(false)
: is_fullscreen_(false)
, resizable_(false)
, mouse_cursor_(CursorType::Arrow)
, key_map_{}
@ -245,8 +244,8 @@ void WindowWin32Impl::Init(const String& title, uint32_t width, uint32_t height,
// Save the device name
int len = lstrlenW(monitor_info_ex.szDevice);
device_name_ = new wchar_t[len + 1];
lstrcpyW(device_name_, monitor_info_ex.szDevice);
device_name_ = std::unique_ptr<wchar_t[]>(new wchar_t[len + 1]);
lstrcpyW(device_name_.get(), monitor_info_ex.szDevice);
int left = -1, top = -1;
@ -303,7 +302,7 @@ void WindowWin32Impl::Init(const String& title, uint32_t width, uint32_t height,
if (is_fullscreen_)
{
ChangeFullScreenResolution(width, height, device_name_);
ChangeFullScreenResolution(width, height, device_name_.get());
}
}
@ -366,7 +365,7 @@ void WindowWin32Impl::SetFullscreen(bool fullscreen)
// move window to (0, 0) before display switch
::SetWindowPos(handle_, HWND_TOPMOST, 0, 0, width, height, SWP_NOACTIVATE);
ChangeFullScreenResolution(width, height, device_name_);
ChangeFullScreenResolution(width, height, device_name_.get());
MONITORINFOEX info = GetMoniterInfoEx(handle_);
@ -376,7 +375,7 @@ void WindowWin32Impl::SetFullscreen(bool fullscreen)
}
else
{
RestoreResolution(device_name_);
RestoreResolution(device_name_.get());
MONITORINFOEX info = GetMoniterInfoEx(handle_);
@ -402,13 +401,9 @@ void WindowWin32Impl::SetCursor(CursorType cursor)
void WindowWin32Impl::Destroy()
{
if (is_fullscreen_)
RestoreResolution(device_name_);
RestoreResolution(device_name_.get());
if (device_name_)
{
delete[] device_name_;
device_name_ = nullptr;
}
device_name_.reset();
if (handle_)
{
@ -466,7 +461,7 @@ void WindowWin32Impl::SetActive(bool actived)
{
if (actived)
{
ChangeFullScreenResolution(GetWidth(), GetHeight(), device_name_);
ChangeFullScreenResolution(GetWidth(), GetHeight(), device_name_.get());
MONITORINFOEX info = GetMoniterInfoEx(handle_);
::SetWindowPos(handle_, HWND_TOPMOST, info.rcMonitor.top, info.rcMonitor.left, GetWidth(), GetHeight(),
@ -474,7 +469,7 @@ void WindowWin32Impl::SetActive(bool actived)
}
else
{
RestoreResolution(device_name_);
RestoreResolution(device_name_.get());
::SetWindowPos(handle_, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
::ShowWindow(handle_, SW_MINIMIZE);

View File

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

View File

@ -72,7 +72,7 @@ void RendererImpl::MakeContextForWindow(WindowPtr window)
// Other device resources
if (SUCCEEDED(hr))
{
RenderContextImplPtr ctx = new RenderContextImpl;
RenderContextImplPtr ctx = memory::New<RenderContextImpl>();
hr = ctx->CreateDeviceResources(d2d_res_->GetFactory(), d2d_res_->GetDeviceContext());
if (SUCCEEDED(hr))
@ -362,7 +362,7 @@ void RendererImpl::CreateGifImageFrame(GifImage::Frame& frame, const GifImage& g
if (SUCCEEDED(hr))
{
frame.texture = new Texture;
frame.texture = memory::New<Texture>();
NativePtr::Set(frame.texture, bitmap);
frame.texture->SetSize({ bitmap->GetSize().width, bitmap->GetSize().height });
@ -728,7 +728,7 @@ void RendererImpl::CreateShapeSink(ShapeMaker& maker)
if (SUCCEEDED(hr))
{
ShapePtr shape = new Shape;
ShapePtr shape = memory::New<Shape>();
NativePtr::Set(shape, geometry);
maker.SetShape(shape);
@ -904,7 +904,7 @@ void RendererImpl::CreateStrokeStyle(StrokeStyle& stroke_style)
RenderContextPtr RendererImpl::CreateTextureRenderContext(Texture& texture, const Size* desired_size)
{
RenderContextImplPtr ptr = new RenderContextImpl;
RenderContextImplPtr ptr = memory::New<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 = new (std::nothrow) TextRenderer;
TextRenderer* pTextRenderer = memory::New<TextRenderer>();
if (pTextRenderer)
{
hr = pTextRenderer->CreateDeviceResources(pRT);

View File

@ -26,7 +26,7 @@ namespace kiwano
FontPtr Font::Create(const String& file)
{
FontPtr ptr = new (std::nothrow) Font;
FontPtr ptr = memory::New<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 = new (std::nothrow) Font;
FontPtr ptr = memory::New<Font>();
if (ptr)
{
if (!ptr->Load(resource))

View File

@ -27,7 +27,7 @@ namespace kiwano
GifImagePtr GifImage::Create(const String& file_path)
{
GifImagePtr ptr = new (std::nothrow) GifImage;
GifImagePtr ptr = memory::New<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 = new (std::nothrow) GifImage;
GifImagePtr ptr = memory::New<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 = new Shape;
ShapePtr output = memory::New<Shape>();
Renderer::GetInstance().CreateLineShape(*output, begin, end);
return output;
}
ShapePtr Shape::CreateRect(const Rect& rect)
{
ShapePtr output = new Shape;
ShapePtr output = memory::New<Shape>();
Renderer::GetInstance().CreateRectShape(*output, rect);
return output;
}
ShapePtr Shape::CreateRoundedRect(const Rect& rect, const Vec2& radius)
{
ShapePtr output = new Shape;
ShapePtr output = memory::New<Shape>();
Renderer::GetInstance().CreateRoundedRectShape(*output, rect, radius);
return output;
}
ShapePtr Shape::CreateCircle(const Point& center, float radius)
{
ShapePtr output = new Shape;
ShapePtr output = memory::New<Shape>();
Renderer::GetInstance().CreateEllipseShape(*output, center, Vec2{ radius, radius });
return output;
}
ShapePtr Shape::CreateEllipse(const Point& center, const Vec2& radius)
{
ShapePtr output = new Shape;
ShapePtr output = memory::New<Shape>();
Renderer::GetInstance().CreateEllipseShape(*output, center, radius);
return output;
}

View File

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

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 = new (std::nothrow) StrokeStyle;
StrokeStylePtr ptr = memory::New<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 = new (std::nothrow) StrokeStyle;
StrokeStylePtr ptr = memory::New<StrokeStyle>();
if (ptr)
{
ptr->SetStrokeWidth(width);

View File

@ -30,13 +30,13 @@ namespace kiwano
TextLayoutPtr TextLayout::Create()
{
TextLayoutPtr ptr = new (std::nothrow) TextLayout;
TextLayoutPtr ptr = memory::New<TextLayout>();
return ptr;
}
TextLayoutPtr TextLayout::Create(const String& content, const TextStyle& style)
{
TextLayoutPtr ptr = new (std::nothrow) TextLayout;
TextLayoutPtr ptr = memory::New<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 = new (std::nothrow) Texture;
TexturePtr ptr = memory::New<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 = new (std::nothrow) Texture;
TexturePtr ptr = memory::New<Texture>();
if (ptr)
{
if (!ptr->Load(res))

View File

@ -33,7 +33,7 @@ SmartPtr<_Ty> CreateOrGetCache(_CacheTy& cache, const _PathTy& path, size_t hash
return iter->second;
}
SmartPtr<_Ty> texture = new _Ty;
SmartPtr<_Ty> texture = memory::New<_Ty>();
if (texture->Load(path))
{
cache.insert(std::make_pair(hash, texture));

View File

@ -214,7 +214,7 @@ bool LoadTexturesFromData(ResourceCache* loader, GlobalData* gdata, const String
if (type == "gif")
{
// GIF image
GifImagePtr gif = new (std::nothrow) GifImage;
GifImagePtr gif = memory::New<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 = new (std::nothrow) Frame;
FramePtr frame = memory::New<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 = new Frame;
FramePtr frame = memory::New<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 = new (std::nothrow) Frame;
FramePtr frame = memory::New<Frame>();
if (frame && frame->Load(gdata->path + file))
{
FrameSequencePtr frame_seq = new (std::nothrow) FrameSequence;
FrameSequencePtr frame_seq = memory::New<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 = new (std::nothrow) Frame;
FramePtr frame = memory::New<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 = new (std::nothrow) Font;
FontPtr font = memory::New<Font>();
if (font && font->Load(gdata->path + file))
{
return loader->AddObject(id, font);