[deploy]Merge pull request #64 from KiwanoEngine/dev

Merge dev branch
This commit is contained in:
Haibo 2020-07-29 12:03:26 +08:00 committed by GitHub
commit 2cc623b6b2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
137 changed files with 2416 additions and 2739 deletions

View File

@ -16,8 +16,8 @@
<ClInclude Include="..\..\src\kiwano\base\Director.h" /> <ClInclude Include="..\..\src\kiwano\base\Director.h" />
<ClInclude Include="..\..\src\kiwano\base\Module.h" /> <ClInclude Include="..\..\src\kiwano\base\Module.h" />
<ClInclude Include="..\..\src\kiwano\base\ObjectBase.h" /> <ClInclude Include="..\..\src\kiwano\base\ObjectBase.h" />
<ClInclude Include="..\..\src\kiwano\base\ObjectPool.h" /> <ClInclude Include="..\..\src\kiwano\base\RefObject.h" />
<ClInclude Include="..\..\src\kiwano\base\RefCounter.h" /> <ClInclude Include="..\..\src\kiwano\base\RefPtr.h" />
<ClInclude Include="..\..\src\kiwano\core\Allocator.h" /> <ClInclude Include="..\..\src\kiwano\core\Allocator.h" />
<ClInclude Include="..\..\src\kiwano\core\Any.h" /> <ClInclude Include="..\..\src\kiwano\core\Any.h" />
<ClInclude Include="..\..\src\kiwano\core\Cloneable.h" /> <ClInclude Include="..\..\src\kiwano\core\Cloneable.h" />
@ -52,7 +52,7 @@
<ClInclude Include="..\..\src\kiwano\2d\TextActor.h" /> <ClInclude Include="..\..\src\kiwano\2d\TextActor.h" />
<ClInclude Include="..\..\src\kiwano\2d\Transition.h" /> <ClInclude Include="..\..\src\kiwano\2d\Transition.h" />
<ClInclude Include="..\..\src\kiwano\core\Resource.h" /> <ClInclude Include="..\..\src\kiwano\core\Resource.h" />
<ClInclude Include="..\..\src\kiwano\core\SmartPtr.hpp" /> <ClInclude Include="..\..\src\kiwano\core\RefBasePtr.hpp" />
<ClInclude Include="..\..\src\kiwano\math\Constants.h" /> <ClInclude Include="..\..\src\kiwano\math\Constants.h" />
<ClInclude Include="..\..\src\kiwano\math\EaseFunctions.h" /> <ClInclude Include="..\..\src\kiwano\math\EaseFunctions.h" />
<ClInclude Include="..\..\src\kiwano\math\Math.h" /> <ClInclude Include="..\..\src\kiwano\math\Math.h" />
@ -102,6 +102,7 @@
<ClInclude Include="..\..\src\kiwano\utils\Json.h" /> <ClInclude Include="..\..\src\kiwano\utils\Json.h" />
<ClInclude Include="..\..\src\kiwano\utils\Logger.h" /> <ClInclude Include="..\..\src\kiwano\utils\Logger.h" />
<ClInclude Include="..\..\src\kiwano\utils\ResourceCache.h" /> <ClInclude Include="..\..\src\kiwano\utils\ResourceCache.h" />
<ClInclude Include="..\..\src\kiwano\utils\ResourceLoader.h" />
<ClInclude Include="..\..\src\kiwano\utils\Task.h" /> <ClInclude Include="..\..\src\kiwano\utils\Task.h" />
<ClInclude Include="..\..\src\kiwano\utils\TaskScheduler.h" /> <ClInclude Include="..\..\src\kiwano\utils\TaskScheduler.h" />
<ClInclude Include="..\..\src\kiwano\utils\Ticker.h" /> <ClInclude Include="..\..\src\kiwano\utils\Ticker.h" />
@ -133,8 +134,7 @@
<ClCompile Include="..\..\src\kiwano\base\Director.cpp" /> <ClCompile Include="..\..\src\kiwano\base\Director.cpp" />
<ClCompile Include="..\..\src\kiwano\base\Module.cpp" /> <ClCompile Include="..\..\src\kiwano\base\Module.cpp" />
<ClCompile Include="..\..\src\kiwano\base\ObjectBase.cpp" /> <ClCompile Include="..\..\src\kiwano\base\ObjectBase.cpp" />
<ClCompile Include="..\..\src\kiwano\base\ObjectPool.cpp" /> <ClCompile Include="..\..\src\kiwano\base\RefObject.cpp" />
<ClCompile Include="..\..\src\kiwano\base\RefCounter.cpp" />
<ClCompile Include="..\..\src\kiwano\core\Allocator.cpp" /> <ClCompile Include="..\..\src\kiwano\core\Allocator.cpp" />
<ClCompile Include="..\..\src\kiwano\core\Exception.cpp" /> <ClCompile Include="..\..\src\kiwano\core\Exception.cpp" />
<ClCompile Include="..\..\src\kiwano\core\Library.cpp" /> <ClCompile Include="..\..\src\kiwano\core\Library.cpp" />
@ -180,6 +180,7 @@
<ClCompile Include="..\..\src\kiwano\utils\EventTicker.cpp" /> <ClCompile Include="..\..\src\kiwano\utils\EventTicker.cpp" />
<ClCompile Include="..\..\src\kiwano\utils\Logger.cpp" /> <ClCompile Include="..\..\src\kiwano\utils\Logger.cpp" />
<ClCompile Include="..\..\src\kiwano\utils\ResourceCache.cpp" /> <ClCompile Include="..\..\src\kiwano\utils\ResourceCache.cpp" />
<ClCompile Include="..\..\src\kiwano\utils\ResourceLoader.cpp" />
<ClCompile Include="..\..\src\kiwano\utils\Task.cpp" /> <ClCompile Include="..\..\src\kiwano\utils\Task.cpp" />
<ClCompile Include="..\..\src\kiwano\utils\TaskScheduler.cpp" /> <ClCompile Include="..\..\src\kiwano\utils\TaskScheduler.cpp" />
<ClCompile Include="..\..\src\kiwano\utils\Ticker.cpp" /> <ClCompile Include="..\..\src\kiwano\utils\Ticker.cpp" />

View File

@ -65,9 +65,6 @@
<ClInclude Include="..\..\src\kiwano\math\Vec2.hpp"> <ClInclude Include="..\..\src\kiwano\math\Vec2.hpp">
<Filter>math</Filter> <Filter>math</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="..\..\src\kiwano\core\SmartPtr.hpp">
<Filter>core</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\kiwano.h" /> <ClInclude Include="..\..\src\kiwano\kiwano.h" />
<ClInclude Include="..\..\src\kiwano\2d\GifSprite.h"> <ClInclude Include="..\..\src\kiwano\2d\GifSprite.h">
<Filter>2d</Filter> <Filter>2d</Filter>
@ -303,9 +300,6 @@
<ClInclude Include="..\..\src\kiwano\base\ObjectBase.h"> <ClInclude Include="..\..\src\kiwano\base\ObjectBase.h">
<Filter>base</Filter> <Filter>base</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="..\..\src\kiwano\base\RefCounter.h">
<Filter>base</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\event\Event.h"> <ClInclude Include="..\..\src\kiwano\event\Event.h">
<Filter>event</Filter> <Filter>event</Filter>
</ClInclude> </ClInclude>
@ -345,15 +339,24 @@
<ClInclude Include="..\..\src\kiwano\utils\ConfigIni.h"> <ClInclude Include="..\..\src\kiwano\utils\ConfigIni.h">
<Filter>utils</Filter> <Filter>utils</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="..\..\src\kiwano\base\ObjectPool.h">
<Filter>base</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\core\Defer.h"> <ClInclude Include="..\..\src\kiwano\core\Defer.h">
<Filter>core</Filter> <Filter>core</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="..\..\src\kiwano\2d\action\Action.h"> <ClInclude Include="..\..\src\kiwano\2d\action\Action.h">
<Filter>2d\action</Filter> <Filter>2d\action</Filter>
</ClInclude> </ClInclude>
<ClInclude Include="..\..\src\kiwano\base\RefObject.h">
<Filter>base</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\core\RefBasePtr.hpp">
<Filter>core</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\base\RefPtr.h">
<Filter>base</Filter>
</ClInclude>
<ClInclude Include="..\..\src\kiwano\utils\ResourceLoader.h">
<Filter>utils</Filter>
</ClInclude>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ClCompile Include="..\..\src\kiwano\2d\Canvas.cpp"> <ClCompile Include="..\..\src\kiwano\2d\Canvas.cpp">
@ -539,9 +542,6 @@
<ClCompile Include="..\..\src\kiwano\base\ObjectBase.cpp"> <ClCompile Include="..\..\src\kiwano\base\ObjectBase.cpp">
<Filter>base</Filter> <Filter>base</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="..\..\src\kiwano\base\RefCounter.cpp">
<Filter>base</Filter>
</ClCompile>
<ClCompile Include="..\..\src\kiwano\event\Event.cpp"> <ClCompile Include="..\..\src\kiwano\event\Event.cpp">
<Filter>event</Filter> <Filter>event</Filter>
</ClCompile> </ClCompile>
@ -575,12 +575,15 @@
<ClCompile Include="..\..\src\kiwano\utils\ConfigIni.cpp"> <ClCompile Include="..\..\src\kiwano\utils\ConfigIni.cpp">
<Filter>utils</Filter> <Filter>utils</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="..\..\src\kiwano\base\ObjectPool.cpp">
<Filter>base</Filter>
</ClCompile>
<ClCompile Include="..\..\src\kiwano\2d\action\Action.cpp"> <ClCompile Include="..\..\src\kiwano\2d\action\Action.cpp">
<Filter>2d\action</Filter> <Filter>2d\action</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="..\..\src\kiwano\base\RefObject.cpp">
<Filter>base</Filter>
</ClCompile>
<ClCompile Include="..\..\src\kiwano\utils\ResourceLoader.cpp">
<Filter>utils</Filter>
</ClCompile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="suppress_warning.ruleset" /> <None Include="suppress_warning.ruleset" />

View File

@ -27,26 +27,16 @@ namespace kiwano
{ {
namespace audio namespace audio
{ {
SoundPtr Sound::Create(const String& file_path) Sound::Sound(const String& file_path)
: Sound()
{ {
SoundPtr ptr = new (std::nothrow) Sound; Load(file_path);
if (ptr)
{
if (!ptr->Load(file_path))
return nullptr;
}
return ptr;
} }
SoundPtr Sound::Create(const Resource& res) Sound::Sound(const Resource& res)
: Sound()
{ {
SoundPtr ptr = new (std::nothrow) Sound; Load(res);
if (ptr)
{
if (!ptr->Load(res))
return nullptr;
}
return ptr;
} }
Sound::Sound() Sound::Sound()

View File

@ -50,12 +50,12 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建音频对象 /// @brief 创建音频对象
/// @param res 本地音频文件路径 /// @param res 本地音频文件路径
static SoundPtr Create(const String& file_path); Sound(const String& file_path);
/// \~chinese /// \~chinese
/// @brief 创建音频对象 /// @brief 创建音频对象
/// @param res 音频资源 /// @param res 音频资源
static SoundPtr Create(const Resource& res); Sound(const Resource& res);
Sound(); Sound();

View File

@ -25,12 +25,6 @@ namespace kiwano
namespace audio namespace audio
{ {
SoundPlayerPtr SoundPlayer::Create()
{
SoundPlayerPtr ptr = new (std::nothrow) SoundPlayer;
return ptr;
}
SoundPlayer::SoundPlayer() SoundPlayer::SoundPlayer()
: volume_(1.f) : volume_(1.f)
{ {
@ -47,8 +41,7 @@ size_t SoundPlayer::Load(const String& file_path)
if (sound_cache_.end() != sound_cache_.find(hash)) if (sound_cache_.end() != sound_cache_.find(hash))
return hash; return hash;
SoundPtr sound = new (std::nothrow) Sound; SoundPtr sound = MakePtr<Sound>();
if (sound) if (sound)
{ {
if (sound->Load(file_path)) if (sound->Load(file_path))
@ -67,7 +60,7 @@ size_t SoundPlayer::Load(const Resource& res)
if (sound_cache_.end() != sound_cache_.find(hash_code)) if (sound_cache_.end() != sound_cache_.find(hash_code))
return hash_code; return hash_code;
SoundPtr sound = new (std::nothrow) Sound; SoundPtr sound = MakePtr<Sound>();
if (sound) if (sound)
{ {

View File

@ -40,10 +40,6 @@ KGE_DECLARE_SMART_PTR(SoundPlayer);
class KGE_API SoundPlayer : public ObjectBase class KGE_API SoundPlayer : public ObjectBase
{ {
public: public:
/// \~chinese
/// @brief 创建音频播放器
static SoundPlayerPtr Create();
SoundPlayer(); SoundPlayer();
~SoundPlayer(); ~SoundPlayer();

View File

@ -25,27 +25,17 @@ namespace kiwano
namespace imgui namespace imgui
{ {
ImGuiLayerPtr ImGuiLayer::Create()
{
ImGuiLayerPtr ptr = new (std::nothrow) ImGuiLayer;
return ptr;
}
ImGuiLayerPtr ImGuiLayer::Create(const String& name, const ImGuiPipeline& item)
{
ImGuiLayerPtr ptr = new (std::nothrow) ImGuiLayer;
if (ptr)
{
ptr->AddItem(name, item);
}
return ptr;
}
ImGuiLayer::ImGuiLayer() ImGuiLayer::ImGuiLayer()
{ {
SetSwallowEvents(true); SetSwallowEvents(true);
} }
ImGuiLayer::ImGuiLayer(const String& name, const ImGuiPipeline& item)
: ImGuiLayer()
{
AddItem(name, item);
}
ImGuiLayer::~ImGuiLayer() {} ImGuiLayer::~ImGuiLayer() {}
void ImGuiLayer::OnRender(RenderContext& ctx) void ImGuiLayer::OnRender(RenderContext& ctx)

View File

@ -38,17 +38,13 @@ using ImGuiPipeline = Function<void()>;
class ImGuiLayer : public LayerActor class ImGuiLayer : public LayerActor
{ {
public: public:
/// \~chinese ImGuiLayer();
/// @brief ´´½¨ImGuiͼ²ã
static ImGuiLayerPtr Create();
/// \~chinese /// \~chinese
/// @brief ´´½¨ImGuiͼ²ã /// @brief ´´½¨ImGuiͼ²ã
/// @param name ÔªËØÃû³Æ /// @param name ÔªËØÃû³Æ
/// @param item ¹ÜµÀ /// @param item ¹ÜµÀ
static ImGuiLayerPtr Create(const String& name, const ImGuiPipeline& item); ImGuiLayer(const String& name, const ImGuiPipeline& item);
ImGuiLayer();
virtual ~ImGuiLayer(); virtual ~ImGuiLayer();

View File

@ -65,12 +65,12 @@ void ImGuiModule::DestroyModule()
ImGui::DestroyContext(); ImGui::DestroyContext();
} }
void ImGuiModule::OnUpdate(Duration dt) void ImGuiModule::OnUpdate(UpdateModuleContext& ctx)
{ {
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
// Setup time step // Setup time step
io.DeltaTime = dt.Seconds(); io.DeltaTime = ctx.dt.Seconds();
// Read keyboard modifiers inputs // Read keyboard modifiers inputs
io.KeyCtrl = Input::GetInstance().IsDown(KeyCode::Ctrl); io.KeyCtrl = Input::GetInstance().IsDown(KeyCode::Ctrl);
@ -84,9 +84,11 @@ void ImGuiModule::OnUpdate(Duration dt)
// Update OS mouse cursor with the cursor requested by imgui // Update OS mouse cursor with the cursor requested by imgui
UpdateMouseCursor(); UpdateMouseCursor();
ctx.Next();
} }
void ImGuiModule::BeforeRender() void ImGuiModule::BeforeRender(RenderModuleContext& ctx)
{ {
ImGui_Impl_NewFrame(); ImGui_Impl_NewFrame();
@ -100,70 +102,74 @@ void ImGuiModule::BeforeRender()
ImGui::NewFrame(); ImGui::NewFrame();
} }
void ImGuiModule::AfterRender() void ImGuiModule::AfterRender(RenderModuleContext& ctx)
{ {
ImGui::Render(); ImGui::Render();
ImGui_Impl_RenderDrawData(ImGui::GetDrawData()); ImGui_Impl_RenderDrawData(ImGui::GetDrawData());
} }
void ImGuiModule::HandleEvent(Event* evt) void ImGuiModule::HandleEvent(EventModuleContext& ctx)
{ {
if (ImGui::GetCurrentContext() == NULL) if (ImGui::GetCurrentContext() != NULL)
return; {
Event* evt = ctx.evt;
ImGuiIO& io = ImGui::GetIO(); ImGuiIO& io = ImGui::GetIO();
if (evt->IsType<MouseEvent>()) if (evt->IsType<MouseEvent>())
{
if (evt->IsType<MouseDownEvent>())
{ {
MouseButton button = dynamic_cast<MouseDownEvent*>(evt)->button; if (evt->IsType<MouseDownEvent>())
int index = 0; {
if (button == MouseButton::Left) MouseButton button = dynamic_cast<MouseDownEvent*>(evt)->button;
index = 0; int index = 0;
else if (button == MouseButton::Right) if (button == MouseButton::Left)
index = 1; index = 0;
else if (button == MouseButton::Middle) else if (button == MouseButton::Right)
index = 2; index = 1;
io.MouseDown[index] = true; else if (button == MouseButton::Middle)
index = 2;
io.MouseDown[index] = true;
}
else if (evt->IsType<MouseUpEvent>())
{
MouseButton button = dynamic_cast<MouseUpEvent*>(evt)->button;
int index = 0;
if (button == MouseButton::Left)
index = 0;
else if (button == MouseButton::Right)
index = 1;
else if (button == MouseButton::Middle)
index = 2;
io.MouseDown[index] = false;
}
else if (evt->IsType<MouseWheelEvent>())
{
float wheel = dynamic_cast<MouseWheelEvent*>(evt)->wheel;
io.MouseWheel += wheel;
}
} }
else if (evt->IsType<MouseUpEvent>()) else if (evt->IsType<KeyEvent>())
{ {
MouseButton button = dynamic_cast<MouseUpEvent*>(evt)->button; if (evt->IsType<KeyDownEvent>())
int index = 0; {
if (button == MouseButton::Left) KeyCode key = dynamic_cast<KeyDownEvent*>(evt)->code;
index = 0; io.KeysDown[(int)key] = true;
else if (button == MouseButton::Right) }
index = 1; else if (evt->IsType<KeyUpEvent>())
else if (button == MouseButton::Middle) {
index = 2; KeyCode key = dynamic_cast<KeyUpEvent*>(evt)->code;
io.MouseDown[index] = false; io.KeysDown[(int)key] = false;
} }
else if (evt->IsType<MouseWheelEvent>()) else if (evt->IsType<KeyCharEvent>())
{ {
float wheel = dynamic_cast<MouseWheelEvent*>(evt)->wheel; // You can also use ToAscii()+GetKeyboardState() to retrieve characters.
io.MouseWheel += wheel; char ch = dynamic_cast<KeyCharEvent*>(evt)->value;
} io.AddInputCharacter(static_cast<ImWchar>(ch));
} }
else if (evt->IsType<KeyEvent>())
{
if (evt->IsType<KeyDownEvent>())
{
KeyCode key = dynamic_cast<KeyDownEvent*>(evt)->code;
io.KeysDown[(int)key] = true;
}
else if (evt->IsType<KeyUpEvent>())
{
KeyCode key = dynamic_cast<KeyUpEvent*>(evt)->code;
io.KeysDown[(int)key] = false;
}
else if (evt->IsType<KeyCharEvent>())
{
// You can also use ToAscii()+GetKeyboardState() to retrieve characters.
char ch = dynamic_cast<KeyCharEvent*>(evt)->value;
io.AddInputCharacter(static_cast<ImWchar>(ch));
} }
} }
ctx.Next();
} }
void ImGuiModule::UpdateMousePos() void ImGuiModule::UpdateMousePos()

View File

@ -34,9 +34,7 @@ namespace imgui
*/ */
class ImGuiModule class ImGuiModule
: public Singleton<ImGuiModule> : public Singleton<ImGuiModule>
, public RenderModule , public Module
, public UpdateModule
, public EventModule
{ {
friend Singleton<ImGuiModule>; friend Singleton<ImGuiModule>;
@ -47,13 +45,13 @@ public:
void DestroyModule() override; void DestroyModule() override;
void BeforeRender() override; void OnUpdate(UpdateModuleContext& ctx) override;
void AfterRender() override; void BeforeRender(RenderModuleContext& ctx) override;
void HandleEvent(Event* evt) override; void AfterRender(RenderModuleContext& ctx) override;
void OnUpdate(Duration dt) override; void HandleEvent(EventModuleContext& ctx) override;
private: private:
void UpdateMousePos(); void UpdateMousePos();

View File

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

View File

@ -26,42 +26,23 @@ namespace kiwano
namespace network namespace network
{ {
HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const ResponseCallback& callback) HttpRequest::HttpRequest(const String& url, HttpType type, const ResponseCallback& callback)
: type_(type)
, url_(url)
, response_cb_(callback)
{ {
HttpRequestPtr ptr = new (std::nothrow) HttpRequest;
if (ptr)
{
ptr->SetUrl(url);
ptr->SetType(type);
ptr->SetResponseCallback(callback);
}
return ptr;
} }
HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const String& data, const ResponseCallback& callback) HttpRequest::HttpRequest(const String& url, HttpType type, const String& data, const ResponseCallback& callback)
: HttpRequest(url, type, callback)
{ {
HttpRequestPtr ptr = new (std::nothrow) HttpRequest; SetData(data);
if (ptr)
{
ptr->SetUrl(url);
ptr->SetType(type);
ptr->SetData(data);
ptr->SetResponseCallback(callback);
}
return ptr;
} }
HttpRequestPtr HttpRequest::Create(const String& url, HttpType type, const Json& json, const ResponseCallback& callback) HttpRequest::HttpRequest(const String& url, HttpType type, const Json& json, const ResponseCallback& callback)
: HttpRequest(url, type, callback)
{ {
HttpRequestPtr ptr = new (std::nothrow) HttpRequest; SetJsonData(json);
if (ptr)
{
ptr->SetUrl(url);
ptr->SetType(type);
ptr->SetJsonData(json);
ptr->SetResponseCallback(callback);
}
return ptr;
} }
void HttpRequest::SetJsonData(const Json& json) void HttpRequest::SetJsonData(const Json& json)

View File

@ -63,7 +63,7 @@ public:
/// @param url 请求地址 /// @param url 请求地址
/// @param type 请求类型 /// @param type 请求类型
/// @param callback 响应回调函数 /// @param callback 响应回调函数
static HttpRequestPtr Create(const String& url, HttpType type, const ResponseCallback& callback); HttpRequest(const String& url, HttpType type, const ResponseCallback& callback);
/// \~chinese /// \~chinese
/// @brief 创建HTTP请求 /// @brief 创建HTTP请求
@ -71,7 +71,7 @@ public:
/// @param type 请求类型 /// @param type 请求类型
/// @param data 请求数据 /// @param data 请求数据
/// @param callback 响应回调函数 /// @param callback 响应回调函数
static HttpRequestPtr Create(const String& url, HttpType type, const String& data, const ResponseCallback& callback); HttpRequest(const String& url, HttpType type, const String& data, const ResponseCallback& callback);
/// \~chinese /// \~chinese
/// @brief 创建HTTP请求 /// @brief 创建HTTP请求
@ -79,12 +79,10 @@ public:
/// @param type 请求类型 /// @param type 请求类型
/// @param json 请求的JSON数据 /// @param json 请求的JSON数据
/// @param callback 响应回调函数 /// @param callback 响应回调函数
static HttpRequestPtr Create(const String& url, HttpType type, const Json& json, const ResponseCallback& callback); HttpRequest(const String& url, HttpType type, const Json& json, const ResponseCallback& callback);
HttpRequest(); HttpRequest();
HttpRequest(HttpType type);
/// \~chinese /// \~chinese
/// @brief 设置请求地址 /// @brief 设置请求地址
void SetUrl(const String& url); void SetUrl(const String& url);
@ -152,11 +150,6 @@ inline HttpRequest::HttpRequest()
{ {
} }
inline HttpRequest::HttpRequest(HttpType type)
: type_(type)
{
}
inline void HttpRequest::SetUrl(const String& url) inline void HttpRequest::SetUrl(const String& url)
{ {
url_ = url; url_ = url;

View File

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

View File

@ -107,18 +107,9 @@ void Joint::Destroy()
// DistanceJoint // DistanceJoint
// //
DistanceJointPtr DistanceJoint::Create(const Param& param) DistanceJoint::DistanceJoint(const Param& param)
{ : param_(param)
DistanceJointPtr ptr = new (std::nothrow) DistanceJoint; , raw_joint_(nullptr)
if (ptr)
{
ptr->param_ = param;
}
return ptr;
}
DistanceJoint::DistanceJoint()
: raw_joint_(nullptr)
{ {
} }
@ -154,18 +145,9 @@ float DistanceJoint::GetLength() const
// FrictionJoint // FrictionJoint
// //
FrictionJointPtr FrictionJoint::Create(const Param& param) FrictionJoint::FrictionJoint(const Param& param)
{ : param_(param)
FrictionJointPtr ptr = new (std::nothrow) FrictionJoint; , raw_joint_(nullptr)
if (ptr)
{
ptr->param_ = param;
}
return ptr;
}
FrictionJoint::FrictionJoint()
: raw_joint_(nullptr)
{ {
} }
@ -212,18 +194,9 @@ float FrictionJoint::GetMaxTorque() const
// GearJoint // GearJoint
// //
GearJointPtr GearJoint::Create(const Param& param) GearJoint::GearJoint(const Param& param)
{ : param_(param)
GearJointPtr ptr = new (std::nothrow) GearJoint; , raw_joint_(nullptr)
if (ptr)
{
ptr->param_ = param;
}
return ptr;
}
GearJoint::GearJoint()
: raw_joint_(nullptr)
{ {
} }
@ -258,18 +231,9 @@ float GearJoint::GetRatio() const
// MotorJoint // MotorJoint
// //
MotorJointPtr MotorJoint::Create(const Param& param) MotorJoint::MotorJoint(const Param& param)
{ : param_(param)
MotorJointPtr ptr = new (std::nothrow) MotorJoint; , raw_joint_(nullptr)
if (ptr)
{
ptr->param_ = param;
}
return ptr;
}
MotorJoint::MotorJoint()
: raw_joint_(nullptr)
{ {
} }
@ -317,18 +281,9 @@ float MotorJoint::GetMaxTorque() const
// PrismaticJoint // PrismaticJoint
// //
PrismaticJointPtr PrismaticJoint::Create(const Param& param) PrismaticJoint::PrismaticJoint(const Param& param)
{ : param_(param)
PrismaticJointPtr ptr = new (std::nothrow) PrismaticJoint; , raw_joint_(nullptr)
if (ptr)
{
ptr->param_ = param;
}
return ptr;
}
PrismaticJoint::PrismaticJoint()
: raw_joint_(nullptr)
{ {
} }
@ -386,18 +341,9 @@ void PrismaticJoint::SetLimits(float lower, float upper)
// PulleyJoint // PulleyJoint
// //
PulleyJointPtr PulleyJoint::Create(const Param& param) PulleyJoint::PulleyJoint(const Param& param)
{ : param_(param)
PulleyJointPtr ptr = new (std::nothrow) PulleyJoint; , raw_joint_(nullptr)
if (ptr)
{
ptr->param_ = param;
}
return ptr;
}
PulleyJoint::PulleyJoint()
: raw_joint_(nullptr)
{ {
} }
@ -462,18 +408,9 @@ float PulleyJoint::GetCurrentLengthB() const
// RevoluteJoint // RevoluteJoint
// //
RevoluteJointPtr RevoluteJoint::Create(const Param& param) RevoluteJoint::RevoluteJoint(const Param& param)
{ : param_(param)
RevoluteJointPtr ptr = new (std::nothrow) RevoluteJoint; , raw_joint_(nullptr)
if (ptr)
{
ptr->param_ = param;
}
return ptr;
}
RevoluteJoint::RevoluteJoint()
: raw_joint_(nullptr)
{ {
} }
@ -542,18 +479,9 @@ float RevoluteJoint::GetMaxMotorTorque() const
// RopeJoint // RopeJoint
// //
RopeJointPtr RopeJoint::Create(const Param& param) RopeJoint::RopeJoint(const Param& param)
{ : param_(param)
RopeJointPtr ptr = new (std::nothrow) RopeJoint; , raw_joint_(nullptr)
if (ptr)
{
ptr->param_ = param;
}
return ptr;
}
RopeJoint::RopeJoint()
: raw_joint_(nullptr)
{ {
} }
@ -590,18 +518,9 @@ float RopeJoint::GetMaxLength() const
// WeldJoint // WeldJoint
// //
WeldJointPtr WeldJoint::Create(const Param& param) WeldJoint::WeldJoint(const Param& param)
{ : param_(param)
WeldJointPtr ptr = new (std::nothrow) WeldJoint; , raw_joint_(nullptr)
if (ptr)
{
ptr->param_ = param;
}
return ptr;
}
WeldJoint::WeldJoint()
: raw_joint_(nullptr)
{ {
} }
@ -624,18 +543,9 @@ bool WeldJoint::Init(PhysicWorld* world)
// WheelJoint // WheelJoint
// //
WheelJointPtr WheelJoint::Create(const Param& param) WheelJoint::WheelJoint(const Param& param)
{ : param_(param)
WheelJointPtr ptr = new (std::nothrow) WheelJoint; , raw_joint_(nullptr)
if (ptr)
{
ptr->param_ = param;
}
return ptr;
}
WheelJoint::WheelJoint()
: raw_joint_(nullptr)
{ {
} }
@ -686,18 +596,9 @@ float WheelJoint::GetMaxMotorTorque() const
// MouseJoint // MouseJoint
// //
MouseJointPtr MouseJoint::Create(const Param& param) MouseJoint::MouseJoint(const Param& param)
{ : param_(param)
MouseJointPtr ptr = new (std::nothrow) MouseJoint; , raw_joint_(nullptr)
if (ptr)
{
ptr->param_ = param;
}
return ptr;
}
MouseJoint::MouseJoint()
: raw_joint_(nullptr)
{ {
} }

View File

@ -161,9 +161,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建固定距离关节 /// @brief 创建固定距离关节
/// @param param 关节参数 /// @param param 关节参数
static DistanceJointPtr Create(const Param& param); DistanceJoint(const Param& param);
DistanceJoint();
/// \~chinese /// \~chinese
/// @brief 初始化关节 /// @brief 初始化关节
@ -226,9 +224,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建摩擦关节 /// @brief 创建摩擦关节
/// @param param 关节参数 /// @param param 关节参数
static FrictionJointPtr Create(const Param& param); FrictionJoint(const Param& param);
FrictionJoint();
/// \~chinese /// \~chinese
/// @brief 初始化关节 /// @brief 初始化关节
@ -285,9 +281,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建齿轮关节 /// @brief 创建齿轮关节
/// @param param 关节参数 /// @param param 关节参数
static GearJointPtr Create(const Param& param); GearJoint(const Param& param);
GearJoint();
/// \~chinese /// \~chinese
/// @brief 初始化关节 /// @brief 初始化关节
@ -336,9 +330,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建马达关节 /// @brief 创建马达关节
/// @param param 关节参数 /// @param param 关节参数
static MotorJointPtr Create(const Param& param); MotorJoint(const Param& param);
MotorJoint();
/// \~chinese /// \~chinese
/// @brief 初始化关节 /// @brief 初始化关节
@ -405,9 +397,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建平移关节 /// @brief 创建平移关节
/// @param param 关节参数 /// @param param 关节参数
static PrismaticJointPtr Create(const Param& param); PrismaticJoint(const Param& param);
PrismaticJoint();
/// \~chinese /// \~chinese
/// @brief 初始化关节 /// @brief 初始化关节
@ -509,9 +499,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建滑轮关节 /// @brief 创建滑轮关节
/// @param param 关节参数 /// @param param 关节参数
static PulleyJointPtr Create(const Param& param); PulleyJoint(const Param& param);
PulleyJoint();
/// \~chinese /// \~chinese
/// @brief 初始化关节 /// @brief 初始化关节
@ -588,9 +576,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建旋转关节 /// @brief 创建旋转关节
/// @param param 关节参数 /// @param param 关节参数
static RevoluteJointPtr Create(const Param& param); RevoluteJoint(const Param& param);
RevoluteJoint();
/// \~chinese /// \~chinese
/// @brief 初始化关节 /// @brief 初始化关节
@ -687,9 +673,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建绳关节 /// @brief 创建绳关节
/// @param param 关节参数 /// @param param 关节参数
static RopeJointPtr Create(const Param& param); RopeJoint(const Param& param);
RopeJoint();
/// \~chinese /// \~chinese
/// @brief 初始化关节 /// @brief 初始化关节
@ -738,9 +722,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建焊接关节 /// @brief 创建焊接关节
/// @param param 关节参数 /// @param param 关节参数
static WeldJointPtr Create(const Param& param); WeldJoint(const Param& param);
WeldJoint();
/// \~chinese /// \~chinese
/// @brief 初始化关节 /// @brief 初始化关节
@ -809,9 +791,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建轮关节 /// @brief 创建轮关节
/// @param param 关节参数 /// @param param 关节参数
static WheelJointPtr Create(const Param& param); WheelJoint(const Param& param);
WheelJoint();
/// \~chinese /// \~chinese
/// @brief 初始化关节 /// @brief 初始化关节
@ -911,9 +891,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建鼠标关节 /// @brief 创建鼠标关节
/// @param param 关节参数 /// @param param 关节参数
static MouseJointPtr Create(const Param& param); MouseJoint(const Param& param);
MouseJoint();
/// \~chinese /// \~chinese
/// @brief 初始化关节 /// @brief 初始化关节

View File

@ -28,37 +28,25 @@ namespace kiwano
namespace physics namespace physics
{ {
PhysicBodyPtr PhysicBody::Create(PhysicWorldPtr world, Type type) PhysicBody::PhysicBody(PhysicWorld* world, Type type)
{
return PhysicBody::Create(world.Get(), type);
}
PhysicBodyPtr PhysicBody::Create(PhysicWorld* world, Type type)
{
KGE_ASSERT(world);
PhysicBodyPtr ptr = new (std::nothrow) PhysicBody;
if (ptr)
{
ptr->SetType(type);
if (ptr->Init(world))
{
world->AddBody(ptr);
return ptr;
}
}
return nullptr;
}
PhysicBody::PhysicBody()
: body_(nullptr) : body_(nullptr)
, world_(nullptr) , world_(world)
, type_(Type::Static) , type_(type)
, category_bits_(0x0001) , category_bits_(0x0001)
, mask_bits_(0xFFFF) , mask_bits_(0xFFFF)
, group_index_(0) , group_index_(0)
{ {
SetName(KGE_PHYSIC_COMP_NAME); SetName(KGE_PHYSIC_COMP_NAME);
if (Init(world))
{
world->AddBody(this);
}
}
PhysicBody::PhysicBody(PhysicWorldPtr world, Type type)
: PhysicBody(world.Get(), type)
{
} }
PhysicBody::~PhysicBody() {} PhysicBody::~PhysicBody() {}
@ -88,11 +76,6 @@ void PhysicBody::DestroyComponent()
} }
} }
bool PhysicBody::Init(PhysicWorldPtr world)
{
return Init(world.Get());
}
bool PhysicBody::Init(PhysicWorld* world) bool PhysicBody::Init(PhysicWorld* world)
{ {
KGE_ASSERT(body_ == nullptr); KGE_ASSERT(body_ == nullptr);

View File

@ -54,23 +54,16 @@ public:
/// @brief 初始化物体 /// @brief 初始化物体
/// @param world 物理世界 /// @param world 物理世界
/// @param type 物体类型 /// @param type 物体类型
static PhysicBodyPtr Create(PhysicWorldPtr world, Type type); PhysicBody(PhysicWorld* world, Type type);
/// \~chinese /// \~chinese
/// @brief 初始化物体 /// @brief 初始化物体
/// @param world 物理世界 /// @param world 物理世界
/// @param type 物体类型 /// @param type 物体类型
static PhysicBodyPtr Create(PhysicWorld* world, Type type); PhysicBody(PhysicWorldPtr world, Type type);
PhysicBody();
virtual ~PhysicBody(); virtual ~PhysicBody();
/// \~chinese
/// @brief 初始化物体
/// @param[in] world 物理世界
bool Init(PhysicWorldPtr world);
/// \~chinese /// \~chinese
/// @brief 初始化物体 /// @brief 初始化物体
/// @param[in] world 物理世界 /// @param[in] world 物理世界

View File

@ -31,11 +31,11 @@ class PhysicWorld::DebugDrawer : public b2Draw
public: public:
DebugDrawer(const Size& size) DebugDrawer(const Size& size)
{ {
canvas_ = Canvas::Create(size); canvas_ = MakePtr<Canvas>(size);
ctx_ = canvas_->GetContext2D(); ctx_ = canvas_->GetContext2D();
fill_brush_ = Brush::Create(Color::White); fill_brush_ = MakePtr<Brush>(Color::White);
line_brush_ = Brush::Create(Color::White); line_brush_ = MakePtr<Brush>(Color::White);
b2Draw::SetFlags(b2Draw::e_shapeBit | b2Draw::e_jointBit | b2Draw::e_jointBit | b2Draw::e_centerOfMassBit); b2Draw::SetFlags(b2Draw::e_shapeBit | b2Draw::e_jointBit | b2Draw::e_jointBit | b2Draw::e_centerOfMassBit);
} }
@ -211,20 +211,10 @@ public:
} }
}; };
PhysicWorldPtr PhysicWorld::Create() PhysicWorld::PhysicWorld(const Vec2& gravity)
: PhysicWorld()
{ {
PhysicWorldPtr ptr = new (std::nothrow) PhysicWorld; SetGravity(gravity);
return ptr;
}
PhysicWorldPtr PhysicWorld::Create(const Vec2& gravity)
{
PhysicWorldPtr ptr = new (std::nothrow) PhysicWorld;
if (ptr)
{
ptr->SetGravity(gravity);
}
return ptr;
} }
PhysicWorld::PhysicWorld() PhysicWorld::PhysicWorld()

View File

@ -47,16 +47,12 @@ class KGE_API PhysicWorld : public Component
friend class Joint; friend class Joint;
public: public:
/// \~chinese PhysicWorld();
/// @brief 创建物理世界
static PhysicWorldPtr Create();
/// \~chinese /// \~chinese
/// @brief 创建物理世界 /// @brief 创建物理世界
/// @param gravity 重力 /// @param gravity 重力
static PhysicWorldPtr Create(const Vec2& gravity); PhysicWorld(const Vec2& gravity);
PhysicWorld();
virtual ~PhysicWorld(); virtual ~PhysicWorld();

View File

@ -39,12 +39,6 @@ void Actor::SetDefaultAnchor(float anchor_x, float anchor_y)
default_anchor_y = anchor_y; default_anchor_y = anchor_y;
} }
ActorPtr Actor::Create()
{
ActorPtr ptr = memory::New<Actor>();
return ptr;
}
Actor::Actor() Actor::Actor()
: ComponentManager(this) : ComponentManager(this)
, visible_(true) , visible_(true)
@ -264,8 +258,8 @@ bool Actor::HandleEvent(Event* evt)
{ {
hover_ = true; hover_ = true;
MouseHoverEventPtr hover = memory::New<MouseHoverEvent>(); MouseHoverEventPtr hover = new MouseHoverEvent;
hover->pos = mouse_evt->pos; hover->pos = mouse_evt->pos;
HandleEvent(hover.Get()); HandleEvent(hover.Get());
} }
else if (hover_ && !contains) else if (hover_ && !contains)
@ -273,8 +267,8 @@ bool Actor::HandleEvent(Event* evt)
hover_ = false; hover_ = false;
pressed_ = false; pressed_ = false;
MouseOutEventPtr out = memory::New<MouseOutEvent>(); MouseOutEventPtr out = new MouseOutEvent;
out->pos = mouse_evt->pos; out->pos = mouse_evt->pos;
HandleEvent(out.Get()); HandleEvent(out.Get());
} }
} }
@ -290,7 +284,7 @@ bool Actor::HandleEvent(Event* evt)
auto mouse_up_evt = dynamic_cast<MouseUpEvent*>(evt); auto mouse_up_evt = dynamic_cast<MouseUpEvent*>(evt);
MouseClickEventPtr click = memory::New<MouseClickEvent>(); MouseClickEventPtr click = new MouseClickEvent;
click->pos = mouse_up_evt->pos; click->pos = mouse_up_evt->pos;
click->button = mouse_up_evt->button; click->button = mouse_up_evt->button;
HandleEvent(click.Get()); HandleEvent(click.Get());
@ -523,8 +517,6 @@ void Actor::SetRotation(float angle)
void Actor::AddChild(ActorPtr child, int zorder) void Actor::AddChild(ActorPtr child, int zorder)
{ {
KGE_ASSERT(child && "Actor::AddChild failed, NULL pointer exception");
if (child) if (child)
{ {
KGE_ASSERT(!child->parent_ && "Actor::AddChild failed, the actor to be added already has a parent"); KGE_ASSERT(!child->parent_ && "Actor::AddChild failed, the actor to be added already has a parent");
@ -551,6 +543,10 @@ void Actor::AddChild(ActorPtr child, int zorder)
child->Reorder(); child->Reorder();
child->UpdateOpacity(); child->UpdateOpacity();
} }
else
{
Fail("Actor::AddChild failed, NULL pointer exception");
}
} }
void Actor::AddChildren(const Vector<ActorPtr>& children) void Actor::AddChildren(const Vector<ActorPtr>& children)
@ -620,8 +616,6 @@ void Actor::RemoveFromParent()
void Actor::RemoveChild(ActorPtr child) void Actor::RemoveChild(ActorPtr child)
{ {
KGE_ASSERT(child && "Actor::RemoveChild failed, NULL pointer exception");
if (children_.IsEmpty()) if (children_.IsEmpty())
return; return;
@ -632,6 +626,10 @@ void Actor::RemoveChild(ActorPtr child)
child->SetStage(nullptr); child->SetStage(nullptr);
children_.Remove(child); children_.Remove(child);
} }
else
{
Fail("Actor::RemoveChild failed, NULL pointer exception");
}
} }
void Actor::RemoveChildren(const String& child_name) void Actor::RemoveChildren(const String& child_name)

View File

@ -77,10 +77,6 @@ public:
/// @brief 角色更新回调函数 /// @brief 角色更新回调函数
typedef Function<void(Duration)> UpdateCallback; typedef Function<void(Duration)> UpdateCallback;
/// \~chinese
/// @brief ´´˝¨˝ÇÉŤ
static ActorPtr Create();
Actor(); Actor();
virtual ~Actor(); virtual ~Actor();

View File

@ -24,26 +24,18 @@
namespace kiwano namespace kiwano
{ {
CanvasPtr Canvas::Create(const Size& size) Canvas::Canvas(const Size& size)
{ {
void* mem = memory::Alloc(sizeof(Canvas)); try
CanvasPtr ptr = ::new (mem) Canvas;
if (ptr)
{ {
try ResizeAndClear(size);
{ }
ptr->ResizeAndClear(size); catch (Exception& e)
} {
catch (std::exception) Fail(String("Canvas::ResizeAndClear failed: ") + e.what());
{
return nullptr;
}
} }
return ptr;
} }
Canvas::Canvas() {}
RenderContextPtr Canvas::GetContext2D() const RenderContextPtr Canvas::GetContext2D() const
{ {
return render_ctx_; return render_ctx_;
@ -59,10 +51,17 @@ void Canvas::OnRender(RenderContext& ctx)
void Canvas::ResizeAndClear(Size size) void Canvas::ResizeAndClear(Size size)
{ {
texture_cached_ = memory::New<Texture>(); texture_cached_ = MakePtr<Texture>();
render_ctx_ = RenderContext::Create(*texture_cached_, size); render_ctx_ = RenderContext::Create(*texture_cached_, size);
SetSize(render_ctx_->GetSize()); if (render_ctx_)
{
SetSize(render_ctx_->GetSize());
}
else
{
Fail("Canvas::ResizeAndClear failed");
}
} }
TexturePtr Canvas::ExportToTexture() const TexturePtr Canvas::ExportToTexture() const

View File

@ -45,7 +45,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建画布 /// @brief 创建画布
/// @param size 画布大小 /// @param size 画布大小
static CanvasPtr Create(const Size& size); Canvas(const Size& size);
/// \~chinese /// \~chinese
/// @brief 获取2D绘图上下文 /// @brief 获取2D绘图上下文
@ -62,9 +62,6 @@ public:
void OnRender(RenderContext& ctx) override; void OnRender(RenderContext& ctx) override;
private:
Canvas();
private: private:
TexturePtr texture_cached_; TexturePtr texture_cached_;
RenderContextPtr render_ctx_; RenderContextPtr render_ctx_;

View File

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

View File

@ -25,38 +25,6 @@
namespace kiwano namespace kiwano
{ {
GifSpritePtr GifSprite::Create(const String& file_path)
{
GifSpritePtr ptr = memory::New<GifSprite>();
if (ptr)
{
if (!ptr->Load(file_path))
return nullptr;
}
return ptr;
}
GifSpritePtr GifSprite::Create(const Resource& res)
{
GifSpritePtr ptr = memory::New<GifSprite>();
if (ptr)
{
if (!ptr->Load(res))
return nullptr;
}
return ptr;
}
GifSpritePtr GifSprite::Create(GifImagePtr gif)
{
GifSpritePtr ptr = memory::New<GifSprite>();
if (ptr)
{
ptr->SetGifImage(gif);
}
return ptr;
}
GifSprite::GifSprite() GifSprite::GifSprite()
: animating_(false) : animating_(false)
, next_index_(0) , next_index_(0)
@ -65,6 +33,24 @@ GifSprite::GifSprite()
{ {
} }
GifSprite::GifSprite(const String& file_path)
: GifSprite()
{
Load(file_path);
}
GifSprite::GifSprite(const Resource& res)
: GifSprite()
{
Load(res);
}
GifSprite::GifSprite(GifImagePtr gif)
: GifSprite()
{
SetGifImage(gif);
}
bool GifSprite::Load(const String& file_path) bool GifSprite::Load(const String& file_path)
{ {
GifImagePtr image = TextureCache::GetInstance().AddOrGetGifImage(file_path); GifImagePtr image = TextureCache::GetInstance().AddOrGetGifImage(file_path);
@ -92,17 +78,27 @@ bool GifSprite::Load(GifImagePtr gif)
frame_rt_.Reset(); frame_rt_.Reset();
Size frame_size = Size(float(gif_->GetWidthInPixels()), float(gif_->GetHeightInPixels())); Size frame_size = Size(float(gif_->GetWidthInPixels()), float(gif_->GetHeightInPixels()));
frame_to_render_ = memory::New<Texture>(); frame_to_render_ = MakePtr<Texture>();
frame_rt_ = RenderContext::Create(*frame_to_render_, frame_size); frame_rt_ = RenderContext::Create(*frame_to_render_, frame_size);
SetSize(frame_rt_->GetSize()); if (frame_rt_)
if (gif_->GetFramesCount() > 0)
{ {
ComposeNextFrame(); SetSize(frame_rt_->GetSize());
if (gif_->GetFramesCount() > 0)
{
ComposeNextFrame();
}
return true;
}
else
{
Fail("GifSprite::Load failed: RenderContext::Create returns null");
return false;
} }
return true;
} }
Fail("GifSprite::Load failed: GifImage is invalid");
return false; return false;
} }
@ -229,7 +225,7 @@ void GifSprite::SaveComposedFrame()
if (!saved_frame_) if (!saved_frame_)
{ {
saved_frame_ = memory::New<Texture>(); saved_frame_ = MakePtr<Texture>();
frame_rt_->CreateTexture(*saved_frame_, frame_to_render_->GetSizeInPixels()); frame_rt_->CreateTexture(*saved_frame_, frame_to_render_->GetSizeInPixels());
} }
saved_frame_->CopyFrom(frame_to_render_); saved_frame_->CopyFrom(frame_to_render_);

View File

@ -48,22 +48,22 @@ public:
/// @brief GIF²¥·Å½áÊø»Øµ÷ /// @brief GIF²¥·Å½áÊø»Øµ÷
using DoneCallback = Function<void()>; using DoneCallback = Function<void()>;
GifSprite();
/// \~chinese /// \~chinese
/// @brief ´´½¨GIF¾«Áé /// @brief ´´½¨GIF¾«Áé
/// @param file_path GIFͼƬ·¾¶ /// @param file_path GIFͼƬ·¾¶
static GifSpritePtr Create(const String& file_path); GifSprite(const String& file_path);
/// \~chinese /// \~chinese
/// @brief ´´½¨GIF¾«Áé /// @brief ´´½¨GIF¾«Áé
/// @param res GIFͼƬ×ÊÔ´ /// @param res GIFͼƬ×ÊÔ´
static GifSpritePtr Create(const Resource& res); GifSprite(const Resource& res);
/// \~chinese /// \~chinese
/// @brief ´´½¨GIF¾«Áé /// @brief ´´½¨GIF¾«Áé
/// @param gif GIFͼƬ /// @param gif GIFͼƬ
static GifSpritePtr Create(GifImagePtr gif); GifSprite(GifImagePtr gif);
GifSprite();
/// \~chinese /// \~chinese
/// @brief ¼ÓÔØGIFͼƬ /// @brief ¼ÓÔØGIFͼƬ

View File

@ -25,12 +25,6 @@
namespace kiwano namespace kiwano
{ {
LayerActorPtr LayerActor::Create()
{
LayerActorPtr ptr = memory::New<LayerActor>();
return ptr;
}
LayerActor::LayerActor() LayerActor::LayerActor()
: swallow_(false) : swallow_(false)
{ {

View File

@ -39,10 +39,6 @@ KGE_DECLARE_SMART_PTR(LayerActor);
class KGE_API LayerActor : public Actor class KGE_API LayerActor : public Actor
{ {
public: public:
/// \~chinese
/// @brief ´´˝¨Íź˛ă
static LayerActorPtr Create();
LayerActor(); LayerActor();
virtual ~LayerActor(); virtual ~LayerActor();

View File

@ -25,40 +25,25 @@
namespace kiwano namespace kiwano
{ {
ShapeActorPtr ShapeActor::Create(ShapePtr shape) ShapeActor::ShapeActor() {}
ShapeActor::ShapeActor(ShapePtr shape)
{ {
ShapeActorPtr ptr = memory::New<ShapeActor>(); SetShape(shape);
if (ptr)
{
ptr->SetShape(shape);
}
return ptr;
} }
ShapeActorPtr ShapeActor::Create(ShapePtr shape, const Color& fill_color, const Color& stroke_color) ShapeActor::ShapeActor(ShapePtr shape, const Color& fill_color, const Color& stroke_color)
: ShapeActor(shape)
{ {
ShapeActorPtr ptr = ShapeActor::Create(shape); SetFillColor(fill_color);
if (ptr) SetStrokeColor(stroke_color);
{
ptr->SetFillColor(fill_color);
ptr->SetStrokeColor(stroke_color);
}
return ptr;
} }
ShapeActorPtr ShapeActor::Create(ShapePtr shape, BrushPtr fill_brush, BrushPtr stroke_brush) ShapeActor::ShapeActor(ShapePtr shape, BrushPtr fill_brush, BrushPtr stroke_brush)
{ : ShapeActor(shape)
ShapeActorPtr ptr = ShapeActor::Create(shape);
if (ptr)
{
ptr->SetFillBrush(fill_brush);
ptr->SetStrokeBrush(stroke_brush);
}
return ptr;
}
ShapeActor::ShapeActor()
{ {
SetFillBrush(fill_brush);
SetStrokeBrush(stroke_brush);
} }
ShapeActor::~ShapeActor() {} ShapeActor::~ShapeActor() {}
@ -127,18 +112,13 @@ bool ShapeActor::CheckVisibility(RenderContext& ctx) const
// LineActor // LineActor
//------------------------------------------------------- //-------------------------------------------------------
LineActorPtr LineActor::Create(const Point& begin, const Point& end)
{
LineActorPtr ptr = memory::New<LineActor>();
if (ptr)
{
ptr->SetLine(begin, end);
}
return ptr;
}
LineActor::LineActor() {} LineActor::LineActor() {}
LineActor::LineActor(const Point& begin, const Point& end)
{
SetLine(begin, end);
}
LineActor::~LineActor() {} LineActor::~LineActor() {}
void LineActor::SetLine(const Point& begin, const Point& end) void LineActor::SetLine(const Point& begin, const Point& end)
@ -155,18 +135,13 @@ void LineActor::SetLine(const Point& begin, const Point& end)
// RectActor // RectActor
//------------------------------------------------------- //-------------------------------------------------------
RectActorPtr RectActor::Create(const Size& size)
{
RectActorPtr ptr = memory::New<RectActor>();
if (ptr)
{
ptr->SetRectSize(size);
}
return ptr;
}
RectActor::RectActor() {} RectActor::RectActor() {}
RectActor::RectActor(const Size& size)
{
SetRectSize(size);
}
RectActor::~RectActor() {} RectActor::~RectActor() {}
void RectActor::SetRectSize(const Size& size) void RectActor::SetRectSize(const Size& size)
@ -182,18 +157,13 @@ void RectActor::SetRectSize(const Size& size)
// RoundedRectActor // RoundedRectActor
//------------------------------------------------------- //-------------------------------------------------------
RoundedRectActorPtr RoundedRectActor::Create(const Size& size, const Vec2& radius)
{
RoundedRectActorPtr ptr = memory::New<RoundedRectActor>();
if (ptr)
{
ptr->SetRoundedRect(size, radius);
}
return ptr;
}
RoundedRectActor::RoundedRectActor() {} RoundedRectActor::RoundedRectActor() {}
RoundedRectActor::RoundedRectActor(const Size& size, const Vec2& radius)
{
SetRoundedRect(size, radius);
}
RoundedRectActor::~RoundedRectActor() {} RoundedRectActor::~RoundedRectActor() {}
void RoundedRectActor::SetRadius(const Vec2& radius) void RoundedRectActor::SetRadius(const Vec2& radius)
@ -220,21 +190,17 @@ void RoundedRectActor::SetRoundedRect(const Size& size, const Vec2& radius)
// CircleActor // CircleActor
//------------------------------------------------------- //-------------------------------------------------------
CircleActorPtr CircleActor::Create(float radius)
{
CircleActorPtr ptr = memory::New<CircleActor>();
if (ptr)
{
ptr->SetRadius(radius);
}
return ptr;
}
CircleActor::CircleActor() CircleActor::CircleActor()
: radius_(0.f) : radius_(0.f)
{ {
} }
CircleActor::CircleActor(float radius)
: radius_(0.f)
{
SetRadius(radius);
}
CircleActor::~CircleActor() {} CircleActor::~CircleActor() {}
void CircleActor::SetRadius(float radius) void CircleActor::SetRadius(float radius)
@ -250,18 +216,13 @@ void CircleActor::SetRadius(float radius)
// EllipseActor // EllipseActor
//------------------------------------------------------- //-------------------------------------------------------
EllipseActorPtr EllipseActor::Create(const Vec2& radius)
{
EllipseActorPtr ptr = memory::New<EllipseActor>();
if (ptr)
{
ptr->SetRadius(radius);
}
return ptr;
}
EllipseActor::EllipseActor() {} EllipseActor::EllipseActor() {}
EllipseActor::EllipseActor(const Vec2& radius)
{
SetRadius(radius);
}
EllipseActor::~EllipseActor() {} EllipseActor::~EllipseActor() {}
void EllipseActor::SetRadius(const Vec2& radius) void EllipseActor::SetRadius(const Vec2& radius)
@ -277,30 +238,25 @@ void EllipseActor::SetRadius(const Vec2& radius)
// PolygonActor // PolygonActor
//------------------------------------------------------- //-------------------------------------------------------
PolygonActorPtr PolygonActor::Create(const Vector<Point>& points)
{
PolygonActorPtr ptr = memory::New<PolygonActor>();
if (ptr)
{
ptr->SetVertices(points);
}
return ptr;
}
PolygonActor::PolygonActor() {} PolygonActor::PolygonActor() {}
PolygonActor::PolygonActor(const Vector<Point>& points)
{
SetVertices(points);
}
PolygonActor::~PolygonActor() {} PolygonActor::~PolygonActor() {}
void PolygonActor::SetVertices(const Vector<Point>& points) void PolygonActor::SetVertices(const Vector<Point>& points)
{ {
if (points.size() > 1) if (points.size() > 1)
{ {
ShapeMakerPtr maker = ShapeMaker::Create(); ShapeMaker maker;
maker->BeginPath(points[0]); maker.BeginPath(points[0]);
maker->AddLines(&points[1], points.size() - 1); maker.AddLines(&points[1], points.size() - 1);
maker->EndPath(true); maker.EndPath(true);
SetShape(maker->GetShape()); SetShape(maker.GetShape());
} }
} }

View File

@ -48,28 +48,26 @@ KGE_DECLARE_SMART_PTR(PolygonActor);
class KGE_API ShapeActor : public Actor class KGE_API ShapeActor : public Actor
{ {
public: public:
ShapeActor();
/// \~chinese /// \~chinese
/// @brief 创建形状角色 /// @brief 创建形状角色
/// @param shape 形状 /// @param shape 形状
static ShapeActorPtr Create(ShapePtr shape); ShapeActor(ShapePtr shape);
/// \~chinese /// \~chinese
/// @brief 创建形状角色 /// @brief 创建形状角色
/// @param shape 形状 /// @param shape 形状
/// @param fill_color 填充颜色 /// @param fill_color 填充颜色
/// @param stroke_color 轮廓颜色 /// @param stroke_color 轮廓颜色
static ShapeActorPtr Create(ShapePtr shape, const Color& fill_color, const Color& stroke_color); ShapeActor(ShapePtr shape, const Color& fill_color, const Color& stroke_color);
/// \~chinese /// \~chinese
/// @brief 创建形状角色 /// @brief 创建形状角色
/// @param shape 形状 /// @param shape 形状
/// @param fill_brush 填充画刷 /// @param fill_brush 填充画刷
/// @param stroke_brush 轮廓画刷 /// @param stroke_brush 轮廓画刷
static ShapeActorPtr Create(ShapePtr shape, BrushPtr fill_brush, BrushPtr stroke_brush); ShapeActor(ShapePtr shape, BrushPtr fill_brush, BrushPtr stroke_brush);
/// \~chinese
/// @brief ¹¹ÔìÐÎ×´½ÇÉ«
ShapeActor();
virtual ~ShapeActor(); virtual ~ShapeActor();
@ -147,13 +145,13 @@ private:
class KGE_API LineActor : public ShapeActor class KGE_API LineActor : public ShapeActor
{ {
public: public:
LineActor();
/// \~chinese /// \~chinese
/// @brief 创建线段角色 /// @brief 创建线段角色
/// @param begin 线段起点 /// @param begin 线段起点
/// @param end 线段终点 /// @param end 线段终点
static LineActorPtr Create(const Point& begin, const Point& end); LineActor(const Point& begin, const Point& end);
LineActor();
virtual ~LineActor(); virtual ~LineActor();
@ -191,12 +189,12 @@ private:
class KGE_API RectActor : public ShapeActor class KGE_API RectActor : public ShapeActor
{ {
public: public:
RectActor();
/// \~chinese /// \~chinese
/// @brief 创建矩形角色 /// @brief 创建矩形角色
/// @param size 矩形大小 /// @param size 矩形大小
static RectActorPtr Create(const Size& size); RectActor(const Size& size);
RectActor();
virtual ~RectActor(); virtual ~RectActor();
@ -218,13 +216,13 @@ private:
class KGE_API RoundedRectActor : public ShapeActor class KGE_API RoundedRectActor : public ShapeActor
{ {
public: public:
RoundedRectActor();
/// \~chinese /// \~chinese
/// @brief 创建圆角矩形角色 /// @brief 创建圆角矩形角色
/// @param size 圆角矩形大小 /// @param size 圆角矩形大小
/// @param radius 圆角半径 /// @param radius 圆角半径
static RoundedRectActorPtr Create(const Size& size, const Vec2& radius); RoundedRectActor(const Size& size, const Vec2& radius);
RoundedRectActor();
virtual ~RoundedRectActor(); virtual ~RoundedRectActor();
@ -262,12 +260,12 @@ private:
class KGE_API CircleActor : public ShapeActor class KGE_API CircleActor : public ShapeActor
{ {
public: public:
CircleActor();
/// \~chinese /// \~chinese
/// @brief 创建圆形角色 /// @brief 创建圆形角色
/// @param radius 圆形半径 /// @param radius 圆形半径
static CircleActorPtr Create(float radius); CircleActor(float radius);
CircleActor();
virtual ~CircleActor(); virtual ~CircleActor();
@ -289,12 +287,12 @@ private:
class KGE_API EllipseActor : public ShapeActor class KGE_API EllipseActor : public ShapeActor
{ {
public: public:
EllipseActor();
/// \~chinese /// \~chinese
/// @brief 创建椭圆角色 /// @brief 创建椭圆角色
/// @param radius 椭圆半径 /// @param radius 椭圆半径
static EllipseActorPtr Create(const Vec2& radius); EllipseActor(const Vec2& radius);
EllipseActor();
virtual ~EllipseActor(); virtual ~EllipseActor();
@ -316,12 +314,12 @@ private:
class KGE_API PolygonActor : public ShapeActor class KGE_API PolygonActor : public ShapeActor
{ {
public: public:
PolygonActor();
/// \~chinese /// \~chinese
/// @brief 创建多边形角色 /// @brief 创建多边形角色
/// @param points 多边形端点集合 /// @param points 多边形端点集合
static PolygonActorPtr Create(const Vector<Point>& points); PolygonActor(const Vector<Point>& points);
PolygonActor();
virtual ~PolygonActor(); virtual ~PolygonActor();
@ -338,7 +336,7 @@ inline void ShapeActor::SetStrokeColor(const Color& color)
{ {
if (!stroke_brush_) if (!stroke_brush_)
{ {
stroke_brush_ = memory::New<Brush>(); stroke_brush_ = MakePtr<Brush>();
} }
stroke_brush_->SetColor(color); stroke_brush_->SetColor(color);
} }
@ -347,7 +345,7 @@ inline void ShapeActor::SetFillColor(const Color& color)
{ {
if (!fill_brush_) if (!fill_brush_)
{ {
fill_brush_ = memory::New<Brush>(); fill_brush_ = MakePtr<Brush>();
} }
fill_brush_->SetColor(color); fill_brush_->SetColor(color);
} }

View File

@ -24,81 +24,58 @@
namespace kiwano namespace kiwano
{ {
SpritePtr Sprite::Create(const String& file_path)
{
SpritePtr ptr = memory::New<Sprite>();
if (ptr)
{
if (!ptr->Load(file_path))
return nullptr;
}
return ptr;
}
SpritePtr Sprite::Create(const Resource& res)
{
SpritePtr ptr = memory::New<Sprite>();
if (ptr)
{
if (!ptr->Load(res))
return nullptr;
}
return ptr;
}
SpritePtr Sprite::Create(FramePtr frame)
{
SpritePtr ptr = memory::New<Sprite>();
if (ptr)
{
ptr->SetFrame(frame);
}
return ptr;
}
SpritePtr Sprite::Create(const String& file_path, const Rect& crop_rect)
{
SpritePtr ptr = Sprite::Create(file_path);
if (ptr)
{
ptr->SetCropRect(crop_rect);
}
return ptr;
}
SpritePtr Sprite::Create(const Resource& res, const Rect& crop_rect)
{
SpritePtr ptr = Sprite::Create(res);
if (ptr)
{
ptr->SetCropRect(crop_rect);
}
return ptr;
}
Sprite::Sprite() {} Sprite::Sprite() {}
Sprite::Sprite(const String& file_path)
{
Load(file_path);
}
Sprite::Sprite(const Resource& res)
{
Load(res);
}
Sprite::Sprite(FramePtr frame)
{
SetFrame(frame);
}
Sprite::Sprite(const String& file_path, const Rect& crop_rect)
: Sprite(file_path)
{
SetCropRect(crop_rect);
}
Sprite::Sprite(const Resource& res, const Rect& crop_rect)
: Sprite(res)
{
SetCropRect(crop_rect);
}
Sprite::~Sprite() {} Sprite::~Sprite() {}
bool Sprite::Load(const String& file_path, bool autoresize) bool Sprite::Load(const String& file_path, bool autoresize)
{ {
FramePtr frame = Frame::Create(file_path); FramePtr frame = MakePtr<Frame>(file_path);
if (frame) if (frame && frame->IsValid())
{ {
SetFrame(frame, autoresize); SetFrame(frame, autoresize);
return true; return true;
} }
Fail("Sprite::Load failed");
return false; return false;
} }
bool Sprite::Load(const Resource& res, bool autoresize) bool Sprite::Load(const Resource& res, bool autoresize)
{ {
FramePtr frame = Frame::Create(res); FramePtr frame = MakePtr<Frame>(res);
if (frame) if (frame)
{ {
SetFrame(frame, autoresize); SetFrame(frame, autoresize);
return true; return true;
} }
Fail("Sprite::Load failed");
return false; return false;
} }

View File

@ -38,34 +38,34 @@ KGE_DECLARE_SMART_PTR(Sprite);
class KGE_API Sprite : public Actor class KGE_API Sprite : public Actor
{ {
public: public:
Sprite();
/// \~chinese /// \~chinese
/// @brief 创建精灵 /// @brief 创建精灵
/// @param file_path 本地图片路径 /// @param file_path 本地图片路径
static SpritePtr Create(const String& file_path); Sprite(const String& file_path);
/// \~chinese /// \~chinese
/// @brief 创建精灵 /// @brief 创建精灵
/// @param res 图片资源 /// @param res 图片资源
static SpritePtr Create(const Resource& res); Sprite(const Resource& res);
/// \~chinese /// \~chinese
/// @brief 创建精灵 /// @brief 创建精灵
/// @param frame 图像帧 /// @param frame 图像帧
static SpritePtr Create(FramePtr frame); Sprite(FramePtr frame);
/// \~chinese /// \~chinese
/// @brief 创建精灵 /// @brief 创建精灵
/// @param file_path 本地图片路径 /// @param file_path 本地图片路径
/// @param crop_rect 裁剪矩形 /// @param crop_rect 裁剪矩形
static SpritePtr Create(const String& file_path, const Rect& crop_rect); Sprite(const String& file_path, const Rect& crop_rect);
/// \~chinese /// \~chinese
/// @brief 创建精灵 /// @brief 创建精灵
/// @param res 图片资源 /// @param res 图片资源
/// @param crop_rect 裁剪矩形 /// @param crop_rect 裁剪矩形
static SpritePtr Create(const Resource& res, const Rect& crop_rect); Sprite(const Resource& res, const Rect& crop_rect);
Sprite();
virtual ~Sprite(); virtual ~Sprite();

View File

@ -25,12 +25,6 @@
namespace kiwano namespace kiwano
{ {
StagePtr Stage::Create()
{
StagePtr ptr = memory::New<Stage>();
return ptr;
}
Stage::Stage() Stage::Stage()
{ {
SetStage(this); SetStage(this);
@ -57,13 +51,13 @@ void Stage::RenderBorder(RenderContext& ctx)
if (!border_fill_brush_) if (!border_fill_brush_)
{ {
border_fill_brush_ = memory::New<Brush>(); border_fill_brush_ = MakePtr<Brush>();
border_fill_brush_->SetColor(Color(Color::Red, .4f)); border_fill_brush_->SetColor(Color(Color::Red, .4f));
} }
if (!border_stroke_brush_) if (!border_stroke_brush_)
{ {
border_stroke_brush_ = memory::New<Brush>(); border_stroke_brush_ = MakePtr<Brush>();
border_stroke_brush_->SetColor(Color(Color::Red, .8f)); border_stroke_brush_->SetColor(Color(Color::Red, .8f));
} }

View File

@ -43,10 +43,6 @@ class KGE_API Stage : public Actor
friend class Director; friend class Director;
public: public:
/// \~chinese
/// @brief 进入舞台时
static StagePtr Create();
Stage(); Stage();
virtual ~Stage(); virtual ~Stage();

View File

@ -25,24 +25,17 @@
namespace kiwano namespace kiwano
{ {
TextActorPtr TextActor::Create(const String& text) TextActor::TextActor() {}
TextActor::TextActor(const String& text)
: TextActor(text, TextStyle())
{ {
return TextActor::Create(text, TextStyle());
} }
TextActorPtr TextActor::Create(const String& text, const TextStyle& style) TextActor::TextActor(const String& text, const TextStyle& style)
{
TextActorPtr ptr = memory::New<TextActor>();
if (ptr)
{
ptr->SetStyle(style);
ptr->SetText(text);
}
return ptr;
}
TextActor::TextActor()
{ {
SetStyle(style);
SetText(text);
} }
TextActor::~TextActor() {} TextActor::~TextActor() {}
@ -65,9 +58,17 @@ void TextActor::SetText(const String& text)
{ {
if (!layout_) if (!layout_)
{ {
layout_ = TextLayout::Create(); layout_ = MakePtr<TextLayout>();
}
try
{
layout_->Reset(text, style_);
}
catch (SystemError& e)
{
Fail(String("TextActor::SetText failed: ") + e.what());
} }
layout_->Reset(text, style_);
} }
void TextActor::SetStyle(const TextStyle& style) void TextActor::SetStyle(const TextStyle& style)
@ -215,7 +216,7 @@ void TextActor::SetFillColor(const Color& color)
} }
else else
{ {
SetFillBrush(Brush::Create(color)); SetFillBrush(MakePtr<Brush>(color));
} }
} }
@ -227,7 +228,7 @@ void TextActor::SetOutlineColor(const Color& outline_color)
} }
else else
{ {
SetFillBrush(Brush::Create(outline_color)); SetFillBrush(MakePtr<Brush>(outline_color));
} }
} }

View File

@ -39,18 +39,18 @@ KGE_DECLARE_SMART_PTR(TextActor);
class KGE_API TextActor : public Actor class KGE_API TextActor : public Actor
{ {
public: public:
TextActor();
/// \~chinese /// \~chinese
/// @brief 创建文本角色 /// @brief 创建文本角色
/// @param text 文字内容 /// @param text 文字内容
static TextActorPtr Create(const String& text); TextActor(const String& text);
/// \~chinese /// \~chinese
/// @brief 创建文本角色 /// @brief 创建文本角色
/// @param text 文字内容 /// @param text 文字内容
/// @param style 文本样式 /// @param style 文本样式
static TextActorPtr Create(const String& text, const TextStyle& style); TextActor(const String& text, const TextStyle& style);
TextActor();
virtual ~TextActor(); virtual ~TextActor();

View File

@ -51,7 +51,7 @@ bool Transition::IsDone()
return done_; return done_;
} }
void Transition::Init(StagePtr prev, StagePtr next) void Transition::Init(Stage* prev, Stage* next)
{ {
process_ = 0; process_ = 0;
delta_ = Duration{}; delta_ = Duration{};
@ -126,19 +126,14 @@ void Transition::Stop()
// BoxTransition // BoxTransition
//------------------------------------------------------- //-------------------------------------------------------
BoxTransitionPtr BoxTransition::Create(Duration duration) BoxTransition::BoxTransition(Duration duration)
{ {
BoxTransitionPtr ptr = memory::New<BoxTransition>(); SetDuration(duration);
if (ptr)
{
ptr->SetDuration(duration);
}
return ptr;
} }
BoxTransition::BoxTransition() {} BoxTransition::BoxTransition() {}
void BoxTransition::Init(StagePtr prev, StagePtr next) void BoxTransition::Init(Stage* prev, Stage* next)
{ {
Transition::Init(prev, next); Transition::Init(prev, next);
@ -167,19 +162,14 @@ void BoxTransition::Update(Duration dt)
// EmergeTransition // EmergeTransition
//------------------------------------------------------- //-------------------------------------------------------
EmergeTransitionPtr EmergeTransition::Create(Duration duration) EmergeTransition::EmergeTransition(Duration duration)
{ {
EmergeTransitionPtr ptr = memory::New<EmergeTransition>(); SetDuration(duration);
if (ptr)
{
ptr->SetDuration(duration);
}
return ptr;
} }
EmergeTransition::EmergeTransition() {} EmergeTransition::EmergeTransition() {}
void EmergeTransition::Init(StagePtr prev, StagePtr next) void EmergeTransition::Init(Stage* prev, Stage* next)
{ {
Transition::Init(prev, next); Transition::Init(prev, next);
@ -199,19 +189,14 @@ void EmergeTransition::Update(Duration dt)
// FadeTransition // FadeTransition
//------------------------------------------------------- //-------------------------------------------------------
FadeTransitionPtr FadeTransition::Create(Duration duration) FadeTransition::FadeTransition(Duration duration)
{ {
FadeTransitionPtr ptr = memory::New<FadeTransition>(); SetDuration(duration);
if (ptr)
{
ptr->SetDuration(duration);
}
return ptr;
} }
FadeTransition::FadeTransition() {} FadeTransition::FadeTransition() {}
void FadeTransition::Init(StagePtr prev, StagePtr next) void FadeTransition::Init(Stage* prev, Stage* next)
{ {
Transition::Init(prev, next); Transition::Init(prev, next);
@ -239,15 +224,10 @@ void FadeTransition::Update(Duration dt)
// MoveTransition // MoveTransition
//------------------------------------------------------- //-------------------------------------------------------
MoveTransitionPtr MoveTransition::Create(Duration duration, Type type) MoveTransition::MoveTransition(Duration duration, Type type)
: type_(type)
{ {
MoveTransitionPtr ptr = memory::New<MoveTransition>(); SetDuration(duration);
if (ptr)
{
ptr->type_ = type;
ptr->SetDuration(duration);
}
return ptr;
} }
MoveTransition::MoveTransition() MoveTransition::MoveTransition()
@ -255,7 +235,7 @@ MoveTransition::MoveTransition()
{ {
} }
void MoveTransition::Init(StagePtr prev, StagePtr next) void MoveTransition::Init(Stage* prev, Stage* next)
{ {
Transition::Init(prev, next); Transition::Init(prev, next);
@ -328,15 +308,10 @@ void MoveTransition::Reset()
// RotationTransition // RotationTransition
//------------------------------------------------------- //-------------------------------------------------------
RotationTransitionPtr RotationTransition::Create(Duration duration, float rotation) RotationTransition::RotationTransition(Duration duration, float rotation)
: rotation_(rotation)
{ {
RotationTransitionPtr ptr = memory::New<RotationTransition>(); SetDuration(duration);
if (ptr)
{
ptr->rotation_ = rotation;
ptr->SetDuration(duration);
}
return ptr;
} }
RotationTransition::RotationTransition() RotationTransition::RotationTransition()
@ -344,7 +319,7 @@ RotationTransition::RotationTransition()
{ {
} }
void RotationTransition::Init(StagePtr prev, StagePtr next) void RotationTransition::Init(Stage* prev, Stage* next)
{ {
Transition::Init(prev, next); Transition::Init(prev, next);

View File

@ -66,7 +66,7 @@ protected:
* @param[in] prev * @param[in] prev
* @param[in] next * @param[in] next
*/ */
virtual void Init(StagePtr prev, StagePtr next); virtual void Init(Stage* prev, Stage* next);
/** /**
* \~chinese * \~chinese
@ -95,15 +95,15 @@ protected:
virtual void Reset() {} virtual void Reset() {}
protected: protected:
bool done_; bool done_;
float process_; float process_;
Duration duration_; Duration duration_;
Duration delta_; Duration delta_;
Size window_size_; Size window_size_;
StagePtr out_stage_; StagePtr out_stage_;
StagePtr in_stage_; StagePtr in_stage_;
Layer out_layer_; Layer out_layer_;
Layer in_layer_; Layer in_layer_;
}; };
/** /**
@ -119,14 +119,14 @@ public:
* @brief * @brief
* @param duration * @param duration
*/ */
static FadeTransitionPtr Create(Duration duration); FadeTransition(Duration duration);
FadeTransition(); FadeTransition();
protected: protected:
void Update(Duration dt) override; void Update(Duration dt) override;
virtual void Init(StagePtr prev, StagePtr next) override; virtual void Init(Stage* prev, Stage* next) override;
}; };
/** /**
@ -142,14 +142,14 @@ public:
* @brief * @brief
* @param duration * @param duration
*/ */
static EmergeTransitionPtr Create(Duration duration); EmergeTransition(Duration duration);
EmergeTransition(); EmergeTransition();
protected: protected:
void Update(Duration dt) override; void Update(Duration dt) override;
virtual void Init(StagePtr prev, StagePtr next) override; virtual void Init(Stage* prev, Stage* next) override;
}; };
/** /**
@ -165,14 +165,14 @@ public:
* @brief * @brief
* @param duration * @param duration
*/ */
static BoxTransitionPtr Create(Duration duration); BoxTransition(Duration duration);
BoxTransition(); BoxTransition();
protected: protected:
void Update(Duration dt) override; void Update(Duration dt) override;
virtual void Init(StagePtr prev, StagePtr next) override; virtual void Init(Stage* prev, Stage* next) override;
}; };
/** /**
@ -201,14 +201,14 @@ public:
* @param duration * @param duration
* @param type * @param type
*/ */
static MoveTransitionPtr Create(Duration duration, Type type); MoveTransition(Duration duration, Type type);
MoveTransition(); MoveTransition();
protected: protected:
void Update(Duration dt) override; void Update(Duration dt) override;
virtual void Init(StagePtr prev, StagePtr next) override; virtual void Init(Stage* prev, Stage* next) override;
void Reset() override; void Reset() override;
@ -232,14 +232,14 @@ public:
* @param duration * @param duration
* @param rotation * @param rotation
*/ */
static RotationTransitionPtr Create(Duration duration, float rotation = 360.0f); RotationTransition(Duration duration, float rotation = 360.0f);
RotationTransition(); RotationTransition();
protected: protected:
void Update(Duration dt) override; void Update(Duration dt) override;
virtual void Init(StagePtr prev, StagePtr next) override; virtual void Init(Stage* prev, Stage* next) override;
void Reset() override; void Reset() override;

View File

@ -106,7 +106,7 @@ void ActionEntity::Reset()
loops_done_ = 0; loops_done_ = 0;
} }
ActionEntityPtr ActionEntity::DoClone(ActionEntityPtr to) const void ActionEntity::DoClone(ActionEntity* to) const
{ {
if (to) if (to)
{ {
@ -116,7 +116,6 @@ ActionEntityPtr ActionEntity::DoClone(ActionEntityPtr to) const
to->SetLoops(this->GetLoops()); to->SetLoops(this->GetLoops());
to->SetName(this->GetName()); to->SetName(this->GetName());
} }
return to;
} }
} // namespace kiwano } // namespace kiwano

View File

@ -22,7 +22,6 @@
#include <kiwano/core/Common.h> #include <kiwano/core/Common.h>
#include <kiwano/core/Cloneable.h> #include <kiwano/core/Cloneable.h>
#include <kiwano/base/ObjectBase.h> #include <kiwano/base/ObjectBase.h>
#include <kiwano/core/SmartPtr.hpp>
#include <kiwano/core/Time.h> #include <kiwano/core/Time.h>
#include <kiwano/core/IntrusiveList.h> #include <kiwano/core/IntrusiveList.h>
#include <kiwano/math/Math.h> #include <kiwano/math/Math.h>
@ -103,7 +102,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取动画的倒转 /// @brief 获取动画的倒转
virtual ActionEntityPtr Reverse() const = 0; virtual ActionEntity* Reverse() const = 0;
/// \~chinese /// \~chinese
/// @brief 获取动画的运行状态 /// @brief 获取动画的运行状态
@ -183,7 +182,7 @@ protected:
/// \~chinese /// \~chinese
/// @brief 执行克隆 /// @brief 执行克隆
ActionEntityPtr DoClone(ActionEntityPtr to) const; void DoClone(ActionEntity* to) const;
private: private:
Status status_; Status status_;
@ -300,6 +299,11 @@ public:
return Get(); return Get();
} }
inline operator ActionEntity*() const
{
return Get();
}
inline operator ActionEntityPtr() const inline operator ActionEntityPtr() const
{ {
return ptr; return ptr;

View File

@ -25,27 +25,24 @@ namespace kiwano
ActionDelay::ActionDelay(Duration delay) ActionDelay::ActionDelay(Duration delay)
{ {
SetEntity(ActionDelayEntity::Create(delay)); SetEntity(MakePtr<ActionDelayEntity>(delay));
} }
ActionDelayEntityPtr ActionDelayEntity::Create(Duration delay) ActionDelayEntity::ActionDelayEntity(Duration delay)
{ {
ActionDelayEntityPtr ptr = memory::New<ActionDelayEntity>(); this->SetDelay(delay);
if (ptr) }
{
ptr->SetDelay(delay); ActionDelayEntity* ActionDelayEntity::Clone() const
} {
ActionDelayEntity* ptr = new ActionDelayEntity(GetDelay());
DoClone(ptr);
return ptr; return ptr;
} }
ActionEntityPtr ActionDelayEntity::Clone() const ActionDelayEntity* ActionDelayEntity::Reverse() const
{ {
return DoClone(ActionDelayEntity::Create(GetDelay())); return Clone();
}
ActionEntityPtr ActionDelayEntity::Reverse() const
{
return DoClone(ActionDelayEntity::Create(GetDelay()));
} }
} // namespace kiwano } // namespace kiwano

View File

@ -50,15 +50,15 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建延时动画 /// @brief 创建延时动画
/// @param delay 延时时长 /// @param delay 延时时长
static ActionDelayEntityPtr Create(Duration delay); ActionDelayEntity(Duration delay);
/// \~chinese /// \~chinese
/// @brief 获取该动画的拷贝对象 /// @brief 获取该动画的拷贝对象
ActionEntityPtr Clone() const override; ActionDelayEntity* Clone() const override;
/// \~chinese /// \~chinese
/// @brief 获取该动画的倒转 /// @brief 获取该动画的倒转
ActionEntityPtr Reverse() const override; ActionDelayEntity* Reverse() const override;
}; };
/** @} */ /** @} */

View File

@ -27,18 +27,7 @@ namespace kiwano
ActionGroup::ActionGroup(const Vector<ActionEntityPtr>& actions, bool parallel) ActionGroup::ActionGroup(const Vector<ActionEntityPtr>& actions, bool parallel)
{ {
SetEntity(ActionGroupEntity::Create(actions, parallel)); SetEntity(MakePtr<ActionGroupEntity>(actions, parallel));
}
ActionGroupEntityPtr ActionGroupEntity::Create(const Vector<ActionEntityPtr>& actions, bool parallel)
{
ActionGroupEntityPtr ptr = memory::New<ActionGroupEntity>();
if (ptr)
{
ptr->parallel_ = parallel;
ptr->AddActions(actions);
}
return ptr;
} }
ActionGroupEntity::ActionGroupEntity() ActionGroupEntity::ActionGroupEntity()
@ -46,9 +35,10 @@ ActionGroupEntity::ActionGroupEntity()
{ {
} }
ActionGroupEntity::ActionGroupEntity(bool parallel) ActionGroupEntity::ActionGroupEntity(const Vector<ActionEntityPtr>& actions, bool parallel)
: parallel_(parallel) : parallel_(parallel)
{ {
AddActions(actions);
} }
ActionGroupEntity::~ActionGroupEntity() {} ActionGroupEntity::~ActionGroupEntity() {}
@ -123,7 +113,7 @@ void ActionGroupEntity::AddActions(const Vector<ActionEntityPtr>& actions)
AddAction(action); AddAction(action);
} }
ActionEntityPtr ActionGroupEntity::Clone() const ActionGroupEntity* ActionGroupEntity::Clone() const
{ {
Vector<ActionEntityPtr> actions; Vector<ActionEntityPtr> actions;
if (!actions_.IsEmpty()) if (!actions_.IsEmpty())
@ -133,10 +123,12 @@ ActionEntityPtr ActionGroupEntity::Clone() const
actions.push_back(action->Clone()); actions.push_back(action->Clone());
} }
} }
return DoClone(ActionGroupEntity::Create(actions, parallel_)); ActionGroupEntity* ptr = new ActionGroupEntity(actions, parallel_);
DoClone(ptr);
return ptr;
} }
ActionEntityPtr ActionGroupEntity::Reverse() const ActionGroupEntity* ActionGroupEntity::Reverse() const
{ {
Vector<ActionEntityPtr> actions; Vector<ActionEntityPtr> actions;
if (!actions_.IsEmpty()) if (!actions_.IsEmpty())
@ -146,7 +138,9 @@ ActionEntityPtr ActionGroupEntity::Reverse() const
actions.push_back(action->Reverse()); actions.push_back(action->Reverse());
} }
} }
return DoClone(ActionGroupEntity::Create(actions, parallel_)); ActionGroupEntity* ptr = new ActionGroupEntity(actions, parallel_);
DoClone(ptr);
return ptr;
} }
} // namespace kiwano } // namespace kiwano

View File

@ -47,15 +47,13 @@ public:
class KGE_API ActionGroupEntity : public ActionEntity class KGE_API ActionGroupEntity : public ActionEntity
{ {
public: public:
ActionGroupEntity();
/// \~chinese /// \~chinese
/// @brief 创建动画组合 /// @brief 创建动画组合
/// @param actions 动画集合 /// @param actions 动画集合
/// @param parallel 同步执行 /// @param parallel 同步执行
static ActionGroupEntityPtr Create(const Vector<ActionEntityPtr>& actions, bool parallel = false); ActionGroupEntity(const Vector<ActionEntityPtr>& actions, bool parallel = false);
ActionGroupEntity();
ActionGroupEntity(bool parallel);
virtual ~ActionGroupEntity(); virtual ~ActionGroupEntity();
@ -75,11 +73,11 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取该动画的拷贝对象 /// @brief 获取该动画的拷贝对象
ActionEntityPtr Clone() const override; ActionGroupEntity* Clone() const override;
/// \~chinese /// \~chinese
/// @brief 获取该动画的倒转 /// @brief 获取该动画的倒转
ActionEntityPtr Reverse() const override; ActionGroupEntity* Reverse() const override;
protected: protected:
void Init(Actor* target) override; void Init(Actor* target) override;

View File

@ -87,14 +87,14 @@ void ActionScheduler::StopAllActions()
} }
} }
ActionEntityPtr ActionScheduler::GetAction(const String& name) ActionEntity* ActionScheduler::GetAction(const String& name)
{ {
if (actions_.IsEmpty()) if (actions_.IsEmpty())
return nullptr; return nullptr;
for (auto& action : actions_) for (auto& action : actions_)
if (action->IsName(name)) if (action->IsName(name))
return action; return action.Get();
return nullptr; return nullptr;
} }

View File

@ -55,7 +55,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取指定名称的动画 /// @brief 获取指定名称的动画
/// @param name 动画名称 /// @param name 动画名称
ActionEntityPtr GetAction(const String& name); ActionEntity* GetAction(const String& name);
/// \~chinese /// \~chinese
/// @brief 获取所有动画 /// @brief 获取所有动画

View File

@ -95,9 +95,9 @@ ActionTweenEntity::ActionTweenEntity()
{ {
} }
ActionTweenEntity::ActionTweenEntity(Duration duration, EaseFunc func) ActionTweenEntity::ActionTweenEntity(Duration duration)
: dur_(duration) : dur_(duration)
, ease_func_(func) , ease_func_(nullptr)
{ {
} }
@ -129,33 +129,26 @@ void ActionTweenEntity::Update(Actor* target, Duration dt)
UpdateTween(target, percent); UpdateTween(target, percent);
} }
ActionEntityPtr ActionTweenEntity::DoClone(ActionTweenEntityPtr to) const void ActionTweenEntity::DoClone(ActionTweenEntity* to) const
{ {
if (to) if (to)
{ {
ActionEntity::DoClone(to);
to->SetDuration(this->GetDuration()); to->SetDuration(this->GetDuration());
to->SetEaseFunc(this->GetEaseFunc()); to->SetEaseFunc(this->GetEaseFunc());
} }
return ActionEntity::DoClone(to);
} }
//------------------------------------------------------- //-------------------------------------------------------
// Move Action // Move Action
//------------------------------------------------------- //-------------------------------------------------------
ActionMoveByEntityPtr ActionMoveByEntity::Create(Duration duration, const Vec2& displacement) ActionMoveByEntity::ActionMoveByEntity(Duration duration, const Vec2& displacement)
: ActionTweenEntity(duration)
, displacement_(displacement)
{ {
ActionMoveByEntityPtr ptr = memory::New<ActionMoveByEntity>();
if (ptr)
{
ptr->SetDuration(duration);
ptr->SetDisplacement(displacement);
}
return ptr;
} }
ActionMoveByEntity::ActionMoveByEntity() {}
void ActionMoveByEntity::Init(Actor* target) void ActionMoveByEntity::Init(Actor* target)
{ {
if (target) if (target)
@ -175,32 +168,31 @@ void ActionMoveByEntity::UpdateTween(Actor* target, float percent)
prev_pos_ = new_pos; prev_pos_ = new_pos;
} }
ActionEntityPtr ActionMoveByEntity::Clone() const ActionMoveByEntity* ActionMoveByEntity::Clone() const
{ {
return DoClone(ActionMoveByEntity::Create(GetDuration(), displacement_)); ActionMoveByEntity* ptr = new ActionMoveByEntity(GetDuration(), displacement_);
} DoClone(ptr);
ActionEntityPtr ActionMoveByEntity::Reverse() const
{
return DoClone(ActionMoveByEntity::Create(GetDuration(), -displacement_));
}
ActionMoveToEntityPtr ActionMoveToEntity::Create(Duration duration, const Point& distination)
{
ActionMoveToEntityPtr ptr = memory::New<ActionMoveToEntity>();
if (ptr)
{
ptr->SetDuration(duration);
ptr->SetDistination(distination);
}
return ptr; return ptr;
} }
ActionMoveToEntity::ActionMoveToEntity() {} ActionMoveByEntity* ActionMoveByEntity::Reverse() const
ActionEntityPtr ActionMoveToEntity::Clone() const
{ {
return DoClone(ActionMoveToEntity::Create(GetDuration(), distination_)); ActionMoveByEntity* ptr = new ActionMoveByEntity(GetDuration(), -displacement_);
DoClone(ptr);
return ptr;
}
ActionMoveToEntity::ActionMoveToEntity(Duration duration, const Point& distination)
: ActionMoveByEntity(duration, Vec2())
, distination_(distination)
{
}
ActionMoveToEntity* ActionMoveToEntity::Clone() const
{
ActionMoveToEntity* ptr = new ActionMoveToEntity(GetDuration(), distination_);
DoClone(ptr);
return ptr;
} }
void ActionMoveToEntity::Init(Actor* target) void ActionMoveToEntity::Init(Actor* target)
@ -213,33 +205,26 @@ void ActionMoveToEntity::Init(Actor* target)
// Jump Action // Jump Action
//------------------------------------------------------- //-------------------------------------------------------
ActionJumpByEntityPtr ActionJumpByEntity::Create(Duration duration, const Vec2& displacement, float height, int count) ActionJumpByEntity::ActionJumpByEntity(Duration duration, const Vec2& displacement, float height, int count)
: ActionTweenEntity(duration)
, height_(height)
, jump_count_(count)
, displacement_(displacement)
{ {
ActionJumpByEntityPtr ptr = memory::New<ActionJumpByEntity>(); }
if (ptr)
{ ActionJumpByEntity* ActionJumpByEntity::Clone() const
ptr->SetDuration(duration); {
ptr->SetJumpHeight(height); ActionJumpByEntity* ptr = new ActionJumpByEntity(GetDuration(), displacement_, height_, jump_count_);
ptr->SetJumpCount(count); DoClone(ptr);
ptr->SetDisplacement(displacement);
}
return ptr; return ptr;
} }
ActionJumpByEntity::ActionJumpByEntity() ActionJumpByEntity* ActionJumpByEntity::Reverse() const
: height_(0.0f)
, jump_count_(0)
{ {
} ActionJumpByEntity* ptr = new ActionJumpByEntity(GetDuration(), -displacement_, height_, jump_count_);
DoClone(ptr);
ActionEntityPtr ActionJumpByEntity::Clone() const return ptr;
{
return DoClone(ActionJumpByEntity::Create(GetDuration(), displacement_, height_, jump_count_));
}
ActionEntityPtr ActionJumpByEntity::Reverse() const
{
return DoClone(ActionJumpByEntity::Create(GetDuration(), -displacement_, height_, jump_count_));
} }
void ActionJumpByEntity::Init(Actor* target) void ActionJumpByEntity::Init(Actor* target)
@ -266,24 +251,17 @@ void ActionJumpByEntity::UpdateTween(Actor* target, float percent)
prev_pos_ = new_pos; prev_pos_ = new_pos;
} }
ActionJumpToEntityPtr ActionJumpToEntity::Create(Duration duration, const Point& distination, float height, int count) ActionJumpToEntity::ActionJumpToEntity(Duration duration, const Point& distination, float height, int count)
: ActionJumpByEntity(duration, Vec2(), height, count)
, distination_(distination)
{ {
ActionJumpToEntityPtr ptr = memory::New<ActionJumpToEntity>();
if (ptr)
{
ptr->SetDuration(duration);
ptr->SetJumpHeight(height);
ptr->SetJumpCount(count);
ptr->SetDistination(distination);
}
return ptr;
} }
ActionJumpToEntity::ActionJumpToEntity() {} ActionJumpToEntity* ActionJumpToEntity::Clone() const
ActionEntityPtr ActionJumpToEntity::Clone() const
{ {
return DoClone(ActionJumpToEntity::Create(GetDuration(), distination_, height_, jump_count_)); ActionJumpToEntity* ptr = new ActionJumpToEntity(GetDuration(), distination_, height_, jump_count_);
DoClone(ptr);
return ptr;
} }
void ActionJumpToEntity::Init(Actor* target) void ActionJumpToEntity::Init(Actor* target)
@ -296,21 +274,10 @@ void ActionJumpToEntity::Init(Actor* target)
// Scale Action // Scale Action
//------------------------------------------------------- //-------------------------------------------------------
ActionScaleByEntityPtr ActionScaleByEntity::Create(Duration duration, float scale_x, float scale_y) ActionScaleByEntity::ActionScaleByEntity(Duration duration, float scale_x, float scale_y)
{ : ActionTweenEntity(duration)
ActionScaleByEntityPtr ptr = memory::New<ActionScaleByEntity>(); , delta_x_(scale_x)
if (ptr) , delta_y_(scale_y)
{
ptr->SetDuration(duration);
ptr->SetScaleX(scale_x);
ptr->SetScaleY(scale_y);
}
return ptr;
}
ActionScaleByEntity::ActionScaleByEntity()
: delta_x_(0.0f)
, delta_y_(0.0f)
, start_scale_x_(0.f) , start_scale_x_(0.f)
, start_scale_y_(0.f) , start_scale_y_(0.f)
{ {
@ -330,37 +297,32 @@ void ActionScaleByEntity::UpdateTween(Actor* target, float percent)
target->SetScale(Vec2{ start_scale_x_ + delta_x_ * percent, start_scale_y_ + delta_y_ * percent }); target->SetScale(Vec2{ start_scale_x_ + delta_x_ * percent, start_scale_y_ + delta_y_ * percent });
} }
ActionEntityPtr ActionScaleByEntity::Clone() const ActionScaleByEntity* ActionScaleByEntity::Clone() const
{ {
return DoClone(ActionScaleByEntity::Create(GetDuration(), delta_x_, delta_y_)); ActionScaleByEntity* ptr = new ActionScaleByEntity(GetDuration(), delta_x_, delta_y_);
} DoClone(ptr);
ActionEntityPtr ActionScaleByEntity::Reverse() const
{
return DoClone(ActionScaleByEntity::Create(GetDuration(), -delta_x_, -delta_y_));
}
ActionScaleToEntityPtr ActionScaleToEntity::Create(Duration duration, float scale_x, float scale_y)
{
ActionScaleToEntityPtr ptr = memory::New<ActionScaleToEntity>();
if (ptr)
{
ptr->SetDuration(duration);
ptr->SetTargetScaleX(scale_x);
ptr->SetTargetScaleY(scale_y);
}
return ptr; return ptr;
} }
ActionScaleToEntity::ActionScaleToEntity() ActionScaleByEntity* ActionScaleByEntity::Reverse() const
: end_scale_x_(0.0f) {
, end_scale_y_(0.0f) ActionScaleByEntity* ptr = new ActionScaleByEntity(GetDuration(), -delta_x_, -delta_y_);
DoClone(ptr);
return ptr;
}
ActionScaleToEntity::ActionScaleToEntity(Duration duration, float scale_x, float scale_y)
: ActionScaleByEntity(duration, 0, 0)
, end_scale_x_(scale_x)
, end_scale_y_(scale_y)
{ {
} }
ActionEntityPtr ActionScaleToEntity::Clone() const ActionScaleToEntity* ActionScaleToEntity::Clone() const
{ {
return DoClone(ActionScaleToEntity::Create(GetDuration(), end_scale_x_, end_scale_y_)); ActionScaleToEntity* ptr = new ActionScaleToEntity(GetDuration(), end_scale_x_, end_scale_y_);
DoClone(ptr);
return ptr;
} }
void ActionScaleToEntity::Init(Actor* target) void ActionScaleToEntity::Init(Actor* target)
@ -374,21 +336,11 @@ void ActionScaleToEntity::Init(Actor* target)
// Opacity Action // Opacity Action
//------------------------------------------------------- //-------------------------------------------------------
ActionFadeToEntityPtr ActionFadeToEntity::Create(Duration duration, float opacity) ActionFadeToEntity::ActionFadeToEntity(Duration duration, float opacity)
{ : ActionTweenEntity(duration)
ActionFadeToEntityPtr ptr = memory::New<ActionFadeToEntity>(); , delta_val_(0.0f)
if (ptr)
{
ptr->SetDuration(duration);
ptr->SetTargetOpacity(opacity);
}
return ptr;
}
ActionFadeToEntity::ActionFadeToEntity()
: delta_val_(0.0f)
, start_val_(0.f) , start_val_(0.f)
, end_val_(0.0f) , end_val_(opacity)
{ {
} }
@ -406,29 +358,21 @@ void ActionFadeToEntity::UpdateTween(Actor* target, float percent)
target->SetOpacity(start_val_ + delta_val_ * percent); target->SetOpacity(start_val_ + delta_val_ * percent);
} }
ActionEntityPtr ActionFadeToEntity::Clone() const ActionFadeToEntity* ActionFadeToEntity::Clone() const
{ {
return DoClone(ActionFadeToEntity::Create(GetDuration(), end_val_)); ActionFadeToEntity* ptr = new ActionFadeToEntity(GetDuration(), end_val_);
DoClone(ptr);
return ptr;
} }
//------------------------------------------------------- //-------------------------------------------------------
// Rotate Action // Rotate Action
//------------------------------------------------------- //-------------------------------------------------------
ActionRotateByEntityPtr ActionRotateByEntity::Create(Duration duration, float rotation) ActionRotateByEntity::ActionRotateByEntity(Duration duration, float rotation)
{ : ActionTweenEntity(duration)
ActionRotateByEntityPtr ptr = memory::New<ActionRotateByEntity>(); , delta_val_(rotation)
if (ptr) , start_val_(0.0f)
{
ptr->SetDuration(duration);
ptr->SetRotation(rotation);
}
return ptr;
}
ActionRotateByEntity::ActionRotateByEntity()
: start_val_(0.0f)
, delta_val_(0.0f)
{ {
} }
@ -449,35 +393,31 @@ void ActionRotateByEntity::UpdateTween(Actor* target, float percent)
target->SetRotation(rotation); target->SetRotation(rotation);
} }
ActionEntityPtr ActionRotateByEntity::Clone() const ActionRotateByEntity* ActionRotateByEntity::Clone() const
{ {
return DoClone(ActionRotateByEntity::Create(GetDuration(), delta_val_)); ActionRotateByEntity* ptr = new ActionRotateByEntity(GetDuration(), delta_val_);
} DoClone(ptr);
ActionEntityPtr ActionRotateByEntity::Reverse() const
{
return DoClone(ActionRotateByEntity::Create(GetDuration(), -delta_val_));
}
ActionRotateToEntityPtr ActionRotateToEntity::Create(Duration duration, float rotation)
{
ActionRotateToEntityPtr ptr = memory::New<ActionRotateToEntity>();
if (ptr)
{
ptr->SetDuration(duration);
ptr->SetTargetRotation(rotation);
}
return ptr; return ptr;
} }
ActionRotateToEntity::ActionRotateToEntity() ActionRotateByEntity* ActionRotateByEntity::Reverse() const
: end_val_(0.0f) {
ActionRotateByEntity* ptr = new ActionRotateByEntity(GetDuration(), -delta_val_);
DoClone(ptr);
return ptr;
}
ActionRotateToEntity::ActionRotateToEntity(Duration duration, float rotation)
: ActionRotateByEntity(duration, 0)
, end_val_(rotation)
{ {
} }
ActionEntityPtr ActionRotateToEntity::Clone() const ActionRotateToEntity* ActionRotateToEntity::Clone() const
{ {
return DoClone(ActionRotateToEntity::Create(GetDuration(), end_val_)); ActionRotateToEntity* ptr = new ActionRotateToEntity(GetDuration(), end_val_);
DoClone(ptr);
return ptr;
} }
void ActionRotateToEntity::Init(Actor* target) void ActionRotateToEntity::Init(Actor* target)
@ -490,22 +430,17 @@ void ActionRotateToEntity::Init(Actor* target)
// ActionCustomEntity // ActionCustomEntity
//------------------------------------------------------- //-------------------------------------------------------
ActionCustomEntityPtr ActionCustomEntity::Create(Duration duration, ActionCustom::TweenFunc tween_func) ActionCustomEntity::ActionCustomEntity(Duration duration, ActionCustom::TweenFunc tween_func)
: ActionTweenEntity(duration)
, tween_func_(tween_func)
{ {
ActionCustomEntityPtr ptr = memory::New<ActionCustomEntity>();
if (ptr)
{
ptr->SetDuration(duration);
ptr->SetTweenFunc(tween_func);
}
return ptr;
} }
ActionCustomEntity::ActionCustomEntity() {} ActionCustomEntity* ActionCustomEntity::Clone() const
ActionEntityPtr ActionCustomEntity::Clone() const
{ {
return DoClone(ActionCustomEntity::Create(GetDuration(), tween_func_)); ActionCustomEntity* ptr = new ActionCustomEntity(GetDuration(), tween_func_);
DoClone(ptr);
return ptr;
} }
void ActionCustomEntity::Init(Actor* target) void ActionCustomEntity::Init(Actor* target)
@ -522,72 +457,72 @@ void ActionCustomEntity::UpdateTween(Actor* target, float percent)
ActionMoveBy::ActionMoveBy(Duration duration, const Vec2& displacement) ActionMoveBy::ActionMoveBy(Duration duration, const Vec2& displacement)
{ {
SetEntity(ActionMoveByEntity::Create(duration, displacement)); SetEntity(MakePtr<ActionMoveByEntity>(duration, displacement));
} }
ActionMoveTo::ActionMoveTo(Duration duration, const Point& distination) ActionMoveTo::ActionMoveTo(Duration duration, const Point& distination)
{ {
SetEntity(ActionMoveToEntity::Create(duration, distination)); SetEntity(MakePtr<ActionMoveToEntity>(duration, distination));
} }
ActionJumpBy::ActionJumpBy(Duration duration, const Vec2& displacement, float height, int count) ActionJumpBy::ActionJumpBy(Duration duration, const Vec2& displacement, float height, int count)
{ {
SetEntity(ActionJumpByEntity::Create(duration, displacement, height, count)); SetEntity(MakePtr<ActionJumpByEntity>(duration, displacement, height, count));
} }
ActionJumpTo::ActionJumpTo(Duration duration, const Point& distination, float height, int count) ActionJumpTo::ActionJumpTo(Duration duration, const Point& distination, float height, int count)
{ {
SetEntity(ActionJumpToEntity::Create(duration, distination, height, count)); SetEntity(MakePtr<ActionJumpToEntity>(duration, distination, height, count));
} }
ActionScaleBy::ActionScaleBy(Duration duration, float scale_x, float scale_y) ActionScaleBy::ActionScaleBy(Duration duration, float scale_x, float scale_y)
{ {
SetEntity(ActionScaleByEntity::Create(duration, scale_x, scale_y)); SetEntity(MakePtr<ActionScaleByEntity>(duration, scale_x, scale_y));
} }
ActionScaleBy::ActionScaleBy(Duration duration, Vec2 scale) ActionScaleBy::ActionScaleBy(Duration duration, Vec2 scale)
{ {
SetEntity(ActionScaleByEntity::Create(duration, scale.x, scale.y)); SetEntity(MakePtr<ActionScaleByEntity>(duration, scale.x, scale.y));
} }
ActionScaleTo::ActionScaleTo(Duration duration, float scale_x, float scale_y) ActionScaleTo::ActionScaleTo(Duration duration, float scale_x, float scale_y)
{ {
SetEntity(ActionScaleToEntity::Create(duration, scale_x, scale_y)); SetEntity(MakePtr<ActionScaleToEntity>(duration, scale_x, scale_y));
} }
ActionScaleTo::ActionScaleTo(Duration duration, Vec2 scale) ActionScaleTo::ActionScaleTo(Duration duration, Vec2 scale)
{ {
SetEntity(ActionScaleToEntity::Create(duration, scale.x, scale.y)); SetEntity(MakePtr<ActionScaleToEntity>(duration, scale.x, scale.y));
} }
ActionFadeTo::ActionFadeTo(Duration duration, float opacity) ActionFadeTo::ActionFadeTo(Duration duration, float opacity)
{ {
SetEntity(ActionFadeToEntity::Create(duration, opacity)); SetEntity(MakePtr<ActionFadeToEntity>(duration, opacity));
} }
ActionFadeIn::ActionFadeIn(Duration duration) ActionFadeIn::ActionFadeIn(Duration duration)
{ {
SetEntity(ActionFadeToEntity::Create(duration, 1.0f)); SetEntity(MakePtr<ActionFadeToEntity>(duration, 1.0f));
} }
ActionFadeOut::ActionFadeOut(Duration duration) ActionFadeOut::ActionFadeOut(Duration duration)
{ {
SetEntity(ActionFadeToEntity::Create(duration, 0.0f)); SetEntity(MakePtr<ActionFadeToEntity>(duration, 0.0f));
} }
ActionRotateBy::ActionRotateBy(Duration duration, float rotation) ActionRotateBy::ActionRotateBy(Duration duration, float rotation)
{ {
SetEntity(ActionRotateByEntity::Create(duration, rotation)); SetEntity(MakePtr<ActionRotateByEntity>(duration, rotation));
} }
ActionRotateTo::ActionRotateTo(Duration duration, float rotation) ActionRotateTo::ActionRotateTo(Duration duration, float rotation)
{ {
SetEntity(ActionRotateToEntity::Create(duration, rotation)); SetEntity(MakePtr<ActionRotateToEntity>(duration, rotation));
} }
ActionCustom::ActionCustom(Duration duration, TweenFunc tween_func) ActionCustom::ActionCustom(Duration duration, TweenFunc tween_func)
{ {
SetEntity(ActionCustomEntity::Create(duration, tween_func)); SetEntity(MakePtr<ActionCustomEntity>(duration, tween_func));
} }
} // namespace kiwano } // namespace kiwano

View File

@ -88,14 +88,6 @@ KGE_DECLARE_SMART_PTR(ActionCustomEntity);
class KGE_API ActionTweenEntity : public ActionEntity class KGE_API ActionTweenEntity : public ActionEntity
{ {
public: public:
ActionTweenEntity();
/// \~chinese
/// @brief 补间动画
/// @param duration 动画时长
/// @param func 动画速度缓动函数
ActionTweenEntity(Duration duration, EaseFunc ease);
/// \~chinese /// \~chinese
/// @brief 获取动画时长 /// @brief 获取动画时长
Duration GetDuration() const; Duration GetDuration() const;
@ -113,11 +105,19 @@ public:
void SetEaseFunc(const EaseFunc& func); void SetEaseFunc(const EaseFunc& func);
protected: protected:
ActionTweenEntity();
/// \~chinese
/// @brief 补间动画
/// @param duration 动画时长
/// @param func 动画速度缓动函数
ActionTweenEntity(Duration duration);
void Update(Actor* target, Duration dt) override; void Update(Actor* target, Duration dt) override;
virtual void UpdateTween(Actor* target, float percent) = 0; virtual void UpdateTween(Actor* target, float percent) = 0;
ActionEntityPtr DoClone(ActionTweenEntityPtr to) const; void DoClone(ActionTweenEntity* to) const;
private: private:
Duration dur_; Duration dur_;
@ -132,8 +132,8 @@ public:
ActionTween() = default; ActionTween() = default;
inline ActionTween(ActionTweenEntityPtr ptr) inline ActionTween(ActionTweenEntityPtr ptr)
: Action(ptr.Get())
{ {
SetEntity(ptr);
} }
/// \~chinese /// \~chinese
@ -150,14 +150,14 @@ public:
/// @brief 获取指针 /// @brief 获取指针
inline ActionTweenEntity* Get() const inline ActionTweenEntity* Get() const
{ {
return const_cast<ActionTweenEntity*>(static_cast<const ActionTweenEntity*>(ptr.Get())); return static_cast<ActionTweenEntity*>(Action::Get());
} }
/// \~chinese /// \~chinese
/// @brief 设置动画实体 /// @brief 设置动画实体
inline void SetEntity(ActionTweenEntityPtr tween_ptr) inline void SetEntity(ActionTweenEntityPtr tween_ptr)
{ {
this->ptr = static_cast<ActionEntity*>(tween_ptr.Get()); Action::SetEntity(tween_ptr.Get());
} }
inline ActionTweenEntity* operator->() const inline ActionTweenEntity* operator->() const
@ -187,9 +187,7 @@ public:
/// @brief 创建相对位移动画 /// @brief 创建相对位移动画
/// @param duration 动画时长 /// @param duration 动画时长
/// @param displacement 位移向量 /// @param displacement 位移向量
static ActionMoveByEntityPtr Create(Duration duration, const Vec2& displacement); ActionMoveByEntity(Duration duration, const Vec2& displacement);
ActionMoveByEntity();
/// \~chinese /// \~chinese
/// @brief 获取位移向量 /// @brief 获取位移向量
@ -201,11 +199,11 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取该动画的拷贝对象 /// @brief 获取该动画的拷贝对象
ActionEntityPtr Clone() const override; ActionMoveByEntity* Clone() const override;
/// \~chinese /// \~chinese
/// @brief 获取该动画的倒转 /// @brief 获取该动画的倒转
ActionEntityPtr Reverse() const override; ActionMoveByEntity* Reverse() const override;
protected: protected:
void Init(Actor* target) override; void Init(Actor* target) override;
@ -239,9 +237,7 @@ public:
/// @brief 创建位移动画 /// @brief 创建位移动画
/// @param duration 动画时长 /// @param duration 动画时长
/// @param distination 目的坐标 /// @param distination 目的坐标
static ActionMoveToEntityPtr Create(Duration duration, const Point& distination); ActionMoveToEntity(Duration duration, const Point& distination);
ActionMoveToEntity();
/// \~chinese /// \~chinese
/// @brief 获取目的坐标 /// @brief 获取目的坐标
@ -253,11 +249,11 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取该动画的拷贝对象 /// @brief 获取该动画的拷贝对象
ActionEntityPtr Clone() const override; ActionMoveToEntity* Clone() const override;
/// \~chinese /// \~chinese
/// @brief 获取该动画的倒转 /// @brief 获取该动画的倒转
virtual ActionEntityPtr Reverse() const override ActionMoveToEntity* Reverse() const override
{ {
KGE_ERRORF("Reverse() not supported in ActionMoveToEntity"); KGE_ERRORF("Reverse() not supported in ActionMoveToEntity");
return nullptr; return nullptr;
@ -295,9 +291,7 @@ public:
/// @param displacement 跳跃位移向量 /// @param displacement 跳跃位移向量
/// @param height 跳跃高度 /// @param height 跳跃高度
/// @param count 跳跃次数 /// @param count 跳跃次数
static ActionJumpByEntityPtr Create(Duration duration, const Vec2& displacement, float height, int count = 1); ActionJumpByEntity(Duration duration, const Vec2& displacement, float height, int count = 1);
ActionJumpByEntity();
/// \~chinese /// \~chinese
/// @brief 获取跳跃位移 /// @brief 获取跳跃位移
@ -325,11 +319,11 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取该动画的拷贝对象 /// @brief 获取该动画的拷贝对象
ActionEntityPtr Clone() const override; ActionJumpByEntity* Clone() const override;
/// \~chinese /// \~chinese
/// @brief 获取该动画的倒转 /// @brief 获取该动画的倒转
ActionEntityPtr Reverse() const override; ActionJumpByEntity* Reverse() const override;
protected: protected:
void Init(Actor* target) override; void Init(Actor* target) override;
@ -369,9 +363,7 @@ public:
/// @param distination 目的坐标 /// @param distination 目的坐标
/// @param height 跳跃高度 /// @param height 跳跃高度
/// @param count 跳跃次数 /// @param count 跳跃次数
static ActionJumpToEntityPtr Create(Duration duration, const Point& distination, float height, int count = 1); ActionJumpToEntity(Duration duration, const Point& distination, float height, int count = 1);
ActionJumpToEntity();
/// \~chinese /// \~chinese
/// @brief 获取目的坐标 /// @brief 获取目的坐标
@ -383,11 +375,11 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取该动画的拷贝对象 /// @brief 获取该动画的拷贝对象
ActionEntityPtr Clone() const override; ActionJumpToEntity* Clone() const override;
/// \~chinese /// \~chinese
/// @brief 获取该动画的倒转 /// @brief 获取该动画的倒转
virtual ActionEntityPtr Reverse() const override ActionJumpToEntity* Reverse() const override
{ {
KGE_ERRORF("Reverse() not supported in ActionJumpToEntity"); KGE_ERRORF("Reverse() not supported in ActionJumpToEntity");
return nullptr; return nullptr;
@ -429,9 +421,7 @@ public:
/// @param duration 动画时长 /// @param duration 动画时长
/// @param scale_x 横向缩放相对变化值 /// @param scale_x 横向缩放相对变化值
/// @param scale_y 纵向缩放相对变化值 /// @param scale_y 纵向缩放相对变化值
static ActionScaleByEntityPtr Create(Duration duration, float scale_x, float scale_y); ActionScaleByEntity(Duration duration, float scale_x, float scale_y);
ActionScaleByEntity();
/// \~chinese /// \~chinese
/// @brief 获取横向缩放相对变化值 /// @brief 获取横向缩放相对变化值
@ -451,11 +441,11 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取该动画的拷贝对象 /// @brief 获取该动画的拷贝对象
ActionEntityPtr Clone() const override; ActionScaleByEntity* Clone() const override;
/// \~chinese /// \~chinese
/// @brief 获取该动画的倒转 /// @brief 获取该动画的倒转
ActionEntityPtr Reverse() const override; ActionScaleByEntity* Reverse() const override;
protected: protected:
void Init(Actor* target) override; void Init(Actor* target) override;
@ -498,9 +488,7 @@ public:
/// @param duration 动画时长 /// @param duration 动画时长
/// @param scale_x 横向缩放目标值 /// @param scale_x 横向缩放目标值
/// @param scale_y 纵向缩放目标值 /// @param scale_y 纵向缩放目标值
static ActionScaleToEntityPtr Create(Duration duration, float scale_x, float scale_y); ActionScaleToEntity(Duration duration, float scale_x, float scale_y);
ActionScaleToEntity();
/// \~chinese /// \~chinese
/// @brief 获取横向缩放目标值 /// @brief 获取横向缩放目标值
@ -520,11 +508,11 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取该动画的拷贝对象 /// @brief 获取该动画的拷贝对象
ActionEntityPtr Clone() const override; ActionScaleToEntity* Clone() const override;
/// \~chinese /// \~chinese
/// @brief 获取该动画的倒转 /// @brief 获取该动画的倒转
virtual ActionEntityPtr Reverse() const override ActionScaleToEntity* Reverse() const override
{ {
KGE_ERRORF("Reverse() not supported in ActionScaleToEntity"); KGE_ERRORF("Reverse() not supported in ActionScaleToEntity");
return nullptr; return nullptr;
@ -581,9 +569,7 @@ public:
/// @brief 创建透明度渐变动画 /// @brief 创建透明度渐变动画
/// @param duration 动画时长 /// @param duration 动画时长
/// @param opacity 目标透明度 /// @param opacity 目标透明度
static ActionFadeToEntityPtr Create(Duration duration, float opacity); ActionFadeToEntity(Duration duration, float opacity);
ActionFadeToEntity();
/// \~chinese /// \~chinese
/// @brief 获取目标透明度 /// @brief 获取目标透明度
@ -595,11 +581,11 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取该动画的拷贝对象 /// @brief 获取该动画的拷贝对象
ActionEntityPtr Clone() const override; ActionFadeToEntity* Clone() const override;
/// \~chinese /// \~chinese
/// @brief 获取该动画的倒转 /// @brief 获取该动画的倒转
virtual ActionEntityPtr Reverse() const override ActionFadeToEntity* Reverse() const override
{ {
KGE_ERRORF("Reverse() not supported in ActionFadeToEntity"); KGE_ERRORF("Reverse() not supported in ActionFadeToEntity");
return nullptr; return nullptr;
@ -637,9 +623,7 @@ public:
/// @brief 创建相对旋转动画 /// @brief 创建相对旋转动画
/// @param duration 动画时长 /// @param duration 动画时长
/// @param rotation 角度相对变化值 /// @param rotation 角度相对变化值
static ActionRotateByEntityPtr Create(Duration duration, float rotation); ActionRotateByEntity(Duration duration, float rotation);
ActionRotateByEntity();
/// \~chinese /// \~chinese
/// @brief 获取角度相对变化值 /// @brief 获取角度相对变化值
@ -651,11 +635,11 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取该动画的拷贝对象 /// @brief 获取该动画的拷贝对象
ActionEntityPtr Clone() const override; ActionRotateByEntity* Clone() const override;
/// \~chinese /// \~chinese
/// @brief 获取该动画的倒转 /// @brief 获取该动画的倒转
ActionEntityPtr Reverse() const override; ActionRotateByEntity* Reverse() const override;
protected: protected:
void Init(Actor* target) override; void Init(Actor* target) override;
@ -688,9 +672,7 @@ public:
/// @brief 创建旋转动画 /// @brief 创建旋转动画
/// @param duration 动画时长 /// @param duration 动画时长
/// @param rotation 目标角度 /// @param rotation 目标角度
static ActionRotateToEntityPtr Create(Duration duration, float rotation); ActionRotateToEntity(Duration duration, float rotation);
ActionRotateToEntity();
/// \~chinese /// \~chinese
/// @brief 获取目标角度 /// @brief 获取目标角度
@ -702,11 +684,11 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取该动画的拷贝对象 /// @brief 获取该动画的拷贝对象
ActionEntityPtr Clone() const override; ActionRotateToEntity* Clone() const override;
/// \~chinese /// \~chinese
/// @brief 获取该动画的倒转 /// @brief 获取该动画的倒转
virtual ActionEntityPtr Reverse() const override ActionRotateToEntity* Reverse() const override
{ {
KGE_ERRORF("Reverse() not supported in ActionRotateToEntity"); KGE_ERRORF("Reverse() not supported in ActionRotateToEntity");
return nullptr; return nullptr;
@ -745,9 +727,7 @@ public:
/// @brief 创建自定义动画 /// @brief 创建自定义动画
/// @param duration 动画时长 /// @param duration 动画时长
/// @param tween_func 动画回调函数 /// @param tween_func 动画回调函数
static ActionCustomEntityPtr Create(Duration duration, ActionCustom::TweenFunc tween_func); ActionCustomEntity(Duration duration, ActionCustom::TweenFunc tween_func);
ActionCustomEntity();
/// \~chinese /// \~chinese
/// @brief 获取动画回调函数 /// @brief 获取动画回调函数
@ -759,11 +739,11 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取该动画的拷贝对象 /// @brief 获取该动画的拷贝对象
ActionEntityPtr Clone() const override; ActionCustomEntity* Clone() const override;
/// \~chinese /// \~chinese
/// @brief 获取该动画的倒转 /// @brief 获取该动画的倒转
ActionEntityPtr Reverse() const override ActionCustomEntity* Reverse() const override
{ {
KGE_ERRORF("Reverse() not supported in ActionCustomEntity"); KGE_ERRORF("Reverse() not supported in ActionCustomEntity");
return nullptr; return nullptr;

View File

@ -26,39 +26,31 @@ namespace kiwano
ActionWalk::ActionWalk(Duration duration, ShapePtr path, bool rotating, float start, float end) ActionWalk::ActionWalk(Duration duration, ShapePtr path, bool rotating, float start, float end)
{ {
SetEntity(ActionWalkEntity::Create(duration, path, rotating, start, end)); SetEntity(MakePtr<ActionWalkEntity>(duration, path, rotating, start, end));
} }
ActionWalkEntityPtr ActionWalkEntity::Create(Duration duration, ShapePtr path, bool rotating, float start, float end) ActionWalkEntity::ActionWalkEntity(Duration duration, ShapePtr path, bool rotating, float start, float end)
: ActionTweenEntity(duration)
, start_(start)
, end_(end)
, rotating_(rotating)
, length_(0.f)
, path_(path)
{ {
ActionWalkEntityPtr ptr = memory::New<ActionWalkEntity>(); }
if (ptr)
{ ActionWalkEntity* ActionWalkEntity::Clone() const
ptr->SetDuration(duration); {
ptr->SetPath(path); ActionWalkEntity* ptr = new ActionWalkEntity(GetDuration(), path_, rotating_, start_, end_);
ptr->SetRotating(rotating); DoClone(ptr);
ptr->SetStartValue(start);
ptr->SetEndValue(end);
}
return ptr; return ptr;
} }
ActionWalkEntity::ActionWalkEntity() ActionWalkEntity* ActionWalkEntity::Reverse() const
: start_(0.0f)
, end_(1.0f)
, rotating_(false)
, length_(0.f)
{ {
} ActionWalkEntity* ptr = new ActionWalkEntity(GetDuration(), path_, rotating_, end_, start_);
DoClone(ptr);
ActionEntityPtr ActionWalkEntity::Clone() const return ptr;
{
return DoClone(ActionWalkEntity::Create(GetDuration(), path_, rotating_, start_, end_));
}
ActionEntityPtr ActionWalkEntity::Reverse() const
{
return DoClone(ActionWalkEntity::Create(GetDuration(), path_, rotating_, end_, start_));
} }
void ActionWalkEntity::Init(Actor* target) void ActionWalkEntity::Init(Actor* target)

View File

@ -59,10 +59,7 @@ public:
/// @param rotating 是否沿路径切线方向旋转 /// @param rotating 是否沿路径切线方向旋转
/// @param start 路径起点(百分比) /// @param start 路径起点(百分比)
/// @param end 路径终点(百分比) /// @param end 路径终点(百分比)
static ActionWalkEntityPtr Create(Duration duration, ShapePtr path, bool rotating = false, float start = 0.f, ActionWalkEntity(Duration duration, ShapePtr path, bool rotating = false, float start = 0.f, float end = 1.f);
float end = 1.f);
ActionWalkEntity();
/// \~chinese /// \~chinese
/// @brief 获取路线 /// @brief 获取路线
@ -98,11 +95,11 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取该动画的拷贝对象 /// @brief 获取该动画的拷贝对象
ActionEntityPtr Clone() const override; ActionWalkEntity* Clone() const override;
/// \~chinese /// \~chinese
/// @brief 获取该动画的倒转 /// @brief 获取该动画的倒转
ActionEntityPtr Reverse() const override; ActionWalkEntity* Reverse() const override;
protected: protected:
void Init(Actor* target) override; void Init(Actor* target) override;

View File

@ -27,18 +27,7 @@ namespace kiwano
Animation::Animation(Duration dur, FrameSequencePtr frame_seq) Animation::Animation(Duration dur, FrameSequencePtr frame_seq)
{ {
SetEntity(AnimationEntity::Create(dur, frame_seq)); SetEntity(MakePtr<AnimationEntity>(dur, frame_seq));
}
AnimationEntityPtr AnimationEntity::Create(Duration dur, FrameSequencePtr frame_seq)
{
AnimationEntityPtr ptr = memory::New<AnimationEntity>();
if (ptr)
{
ptr->SetDuration(dur);
ptr->SetFrameSequence(frame_seq);
}
return ptr;
} }
AnimationEntity::AnimationEntity() AnimationEntity::AnimationEntity()
@ -46,6 +35,12 @@ AnimationEntity::AnimationEntity()
{ {
} }
AnimationEntity::AnimationEntity(Duration dur, FrameSequencePtr frame_seq)
: ActionTweenEntity(dur)
, frame_seq_(frame_seq)
{
}
AnimationEntity::~AnimationEntity() {} AnimationEntity::~AnimationEntity() {}
FrameSequencePtr AnimationEntity::GetFrameSequence() const FrameSequencePtr AnimationEntity::GetFrameSequence() const
@ -90,26 +85,24 @@ void AnimationEntity::UpdateTween(Actor* target, float percent)
} }
} }
ActionEntityPtr AnimationEntity::Clone() const AnimationEntity* AnimationEntity::Clone() const
{ {
if (frame_seq_) AnimationEntity* ptr = new AnimationEntity(GetDuration(), frame_seq_);
{ DoClone(ptr);
return DoClone(AnimationEntity::Create(GetDuration(), frame_seq_)); return ptr;
}
return nullptr;
} }
ActionEntityPtr AnimationEntity::Reverse() const AnimationEntity* AnimationEntity::Reverse() const
{ {
AnimationEntity* ptr = new AnimationEntity(GetDuration(), nullptr);
DoClone(ptr);
if (frame_seq_) if (frame_seq_)
{ {
FrameSequencePtr frames = frame_seq_->Reverse(); FrameSequencePtr frames = frame_seq_->Reverse();
if (frames) ptr->SetFrameSequence(frames);
{
return DoClone(AnimationEntity::Create(GetDuration(), frames));
}
} }
return nullptr; return ptr;
} }
} // namespace kiwano } // namespace kiwano

View File

@ -49,13 +49,13 @@ public:
class KGE_API AnimationEntity : public ActionTweenEntity class KGE_API AnimationEntity : public ActionTweenEntity
{ {
public: public:
AnimationEntity();
/// \~chinese /// \~chinese
/// @brief 创建帧动画 /// @brief 创建帧动画
/// @param dur 动画时长 /// @param dur 动画时长
/// @param frame_seq 序列帧 /// @param frame_seq 序列帧
static AnimationEntityPtr Create(Duration dur, FrameSequencePtr frame_seq); AnimationEntity(Duration dur, FrameSequencePtr frame_seq);
AnimationEntity();
virtual ~AnimationEntity(); virtual ~AnimationEntity();
@ -70,11 +70,11 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取该动画的拷贝对象 /// @brief 获取该动画的拷贝对象
ActionEntityPtr Clone() const override; AnimationEntity* Clone() const override;
/// \~chinese /// \~chinese
/// @brief 获取该动画的倒转 /// @brief 获取该动画的倒转
ActionEntityPtr Reverse() const override; AnimationEntity* Reverse() const override;
protected: protected:
void Init(Actor* target) override; void Init(Actor* target) override;
@ -86,4 +86,5 @@ private:
}; };
/** @} */ /** @} */
} // namespace kiwano } // namespace kiwano

View File

@ -23,10 +23,10 @@
#include <kiwano/2d/Stage.h> #include <kiwano/2d/Stage.h>
#include <kiwano/2d/Transition.h> #include <kiwano/2d/Transition.h>
#include <kiwano/base/Director.h> #include <kiwano/base/Director.h>
#include <kiwano/render/RenderContext.h>
namespace kiwano namespace kiwano
{ {
Director::Director() Director::Director()
: render_border_enabled_(false) : render_border_enabled_(false)
{ {
@ -50,7 +50,7 @@ void Director::EnterStage(StagePtr stage, TransitionPtr transition)
transition_->Stop(); transition_->Stop();
} }
transition_ = transition; transition_ = transition;
transition_->Init(current_stage_, next_stage_); transition_->Init(current_stage_.Get(), next_stage_.Get());
} }
} }
@ -81,7 +81,7 @@ void Director::PopStage(TransitionPtr transition)
transition_->Stop(); transition_->Stop();
} }
transition_ = transition; transition_ = transition;
transition_->Init(current_stage_, next_stage_); transition_->Init(current_stage_.Get(), next_stage_.Get());
} }
} }
@ -100,7 +100,7 @@ void Director::ShowDebugInfo(bool show)
if (show) if (show)
{ {
if (!debug_actor_) if (!debug_actor_)
debug_actor_ = memory::New<DebugActor>(); debug_actor_ = MakePtr<DebugActor>();
} }
else else
{ {
@ -119,11 +119,11 @@ void Director::ClearStages()
debug_actor_.Reset(); debug_actor_.Reset();
} }
void Director::OnUpdate(Duration dt) void Director::OnUpdate(UpdateModuleContext& ctx)
{ {
if (transition_) if (transition_)
{ {
transition_->Update(dt); transition_->Update(ctx.dt);
if (transition_->IsDone()) if (transition_->IsDone())
transition_ = nullptr; transition_ = nullptr;
@ -143,47 +143,47 @@ void Director::OnUpdate(Duration dt)
} }
if (current_stage_) if (current_stage_)
current_stage_->Update(dt); current_stage_->Update(ctx.dt);
if (next_stage_) if (next_stage_)
next_stage_->Update(dt); next_stage_->Update(ctx.dt);
if (debug_actor_) if (debug_actor_)
debug_actor_->Update(dt); debug_actor_->Update(ctx.dt);
} }
void Director::OnRender(RenderContext& ctx) void Director::OnRender(RenderModuleContext& ctx)
{ {
if (transition_) if (transition_)
{ {
transition_->Render(ctx); transition_->Render(ctx.render_ctx);
} }
else if (current_stage_) else if (current_stage_)
{ {
current_stage_->Render(ctx); current_stage_->Render(ctx.render_ctx);
if (render_border_enabled_) if (render_border_enabled_)
{ {
current_stage_->RenderBorder(ctx); current_stage_->RenderBorder(ctx.render_ctx);
} }
} }
if (debug_actor_) if (debug_actor_)
{ {
debug_actor_->Render(ctx); debug_actor_->Render(ctx.render_ctx);
} }
} }
void Director::HandleEvent(Event* evt) void Director::HandleEvent(EventModuleContext& ctx)
{ {
if (current_stage_) if (current_stage_)
current_stage_->DispatchEvent(evt); current_stage_->DispatchEvent(ctx.evt);
if (next_stage_) if (next_stage_)
next_stage_->DispatchEvent(evt); next_stage_->DispatchEvent(ctx.evt);
if (debug_actor_) if (debug_actor_)
debug_actor_->DispatchEvent(evt); debug_actor_->DispatchEvent(ctx.evt);
} }
} // namespace kiwano } // namespace kiwano

View File

@ -34,9 +34,7 @@ namespace kiwano
*/ */
class KGE_API Director class KGE_API Director
: public Singleton<Director> : public Singleton<Director>
, public UpdateModule , public Module
, public RenderModule
, public EventModule
{ {
friend Singleton<Director>; friend Singleton<Director>;
@ -92,15 +90,11 @@ public:
void ClearStages(); void ClearStages();
public: public:
void SetupModule() override {} void OnUpdate(UpdateModuleContext& ctx) override;
void DestroyModule() override {} void OnRender(RenderModuleContext& ctx) override;
void OnUpdate(Duration dt) override; void HandleEvent(EventModuleContext& ctx) override;
void OnRender(RenderContext& ctx) override;
void HandleEvent(Event* evt) override;
virtual ~Director(); virtual ~Director();

View File

@ -19,28 +19,118 @@
// THE SOFTWARE. // THE SOFTWARE.
#include <kiwano/base/Module.h> #include <kiwano/base/Module.h>
#include <kiwano/render/RenderContext.h>
namespace kiwano namespace kiwano
{ {
Module::Module() ModuleContext::ModuleContext(ModuleList& modules)
: flag_(0) : index_(-1)
, modules_(modules)
{ {
} }
RenderModule::RenderModule() ModuleContext::~ModuleContext() {}
void ModuleContext::ResetIndex()
{ {
flag_ |= ModuleFlag<RenderModule>::value; index_ = -1;
} }
UpdateModule::UpdateModule() void ModuleContext::Next()
{ {
flag_ |= ModuleFlag<UpdateModule>::value; index_++;
for (; index_ < (int)modules_.size(); index_++)
{
this->Handle(modules_.at(index_));
}
} }
EventModule::EventModule() RenderModuleContext::RenderModuleContext(ModuleList& modules, RenderContext& ctx)
: ModuleContext(modules)
, step_(Step::Before)
, render_ctx(ctx)
{
this->Next();
this->ResetIndex();
render_ctx.BeginDraw();
step_ = Step::Rendering;
}
RenderModuleContext::~RenderModuleContext()
{
render_ctx.EndDraw();
step_ = Step::After;
this->ResetIndex();
this->Next();
}
void RenderModuleContext::Handle(Module* m)
{
switch (step_)
{
case RenderModuleContext::Step::Before:
m->BeforeRender(*this);
break;
case RenderModuleContext::Step::Rendering:
m->OnRender(*this);
break;
case RenderModuleContext::Step::After:
m->AfterRender(*this);
break;
default:
break;
}
}
UpdateModuleContext::UpdateModuleContext(ModuleList& modules, Duration dt)
: ModuleContext(modules)
, dt(dt)
{
}
void UpdateModuleContext::Handle(Module* m)
{
m->OnUpdate(*this);
}
EventModuleContext::EventModuleContext(ModuleList& modules, Event* evt)
: ModuleContext(modules)
, evt(evt)
{
}
void EventModuleContext::Handle(Module* m)
{
m->HandleEvent(*this);
}
Module::Module() {}
void Module::SetupModule() {}
void Module::DestroyModule() {}
void Module::OnRender(RenderModuleContext& ctx)
{
}
void Module::OnUpdate(UpdateModuleContext& ctx)
{
}
void Module::HandleEvent(EventModuleContext& ctx)
{
}
void Module::BeforeRender(RenderModuleContext& ctx)
{
}
void Module::AfterRender(RenderModuleContext& ctx)
{ {
flag_ |= ModuleFlag<EventModule>::value;
} }
} // namespace kiwano } // namespace kiwano

View File

@ -25,124 +25,126 @@ namespace kiwano
{ {
class RenderContext; class RenderContext;
class Event; class Event;
class Module;
template <typename _CompTy> /// \~chinese
struct ModuleFlag; /// @brief 模块列表
typedef Vector<Module*> ModuleList;
/// \~chinese
/// @brief 模块上下文
class KGE_API ModuleContext
{
public:
void Next();
protected:
ModuleContext(ModuleList& modules);
virtual ~ModuleContext();
virtual void Handle(Module* m) = 0;
void ResetIndex();
private:
int index_;
ModuleList& modules_;
};
/// \~chinese
/// @brief 渲染模块上下文
class KGE_API RenderModuleContext : public ModuleContext
{
public:
RenderContext& render_ctx;
RenderModuleContext(ModuleList& modules, RenderContext& ctx);
virtual ~RenderModuleContext();
protected:
void Handle(Module* m) override;
private:
enum class Step
{
Before,
Rendering,
After,
};
Step step_;
};
/// \~chinese
/// @brief 更新模块上下文
class KGE_API UpdateModuleContext : public ModuleContext
{
public:
Duration dt;
UpdateModuleContext(ModuleList& modules, Duration dt);
protected:
void Handle(Module* m) override;
};
/// \~chinese
/// @brief 时间模块上下文
class KGE_API EventModuleContext : public ModuleContext
{
public:
Event* evt;
EventModuleContext(ModuleList& modules, Event* evt);
protected:
void Handle(Module* m) override;
};
/** /**
* \~chinese * \~chinese
* @brief * @brief
*/ */
class KGE_API Module class KGE_API Module : Noncopyable
{ {
public: public:
/// \~chinese /// \~chinese
/// @brief 启动模块 /// @brief 启动模块
virtual void SetupModule() {} virtual void SetupModule();
/// \~chinese /// \~chinese
/// @brief 销毁模块 /// @brief 销毁模块
virtual void DestroyModule() {} virtual void DestroyModule();
template <typename _CompTy> /// \~chinese
_CompTy* Cast() /// @brief 更新时
{ /// @param ctx 更新上下文
if (flag_ & ModuleFlag<_CompTy>::value) virtual void OnUpdate(UpdateModuleContext& ctx);
return dynamic_cast<_CompTy*>(this);
return nullptr;
}
protected: /// \~chinese
Module(); /// @brief 事件处理
/// @param ctx 事件上下文
virtual void HandleEvent(EventModuleContext& ctx);
protected:
int flag_;
};
/**
* \~chinese
* @brief
*/
class KGE_API RenderModule : public virtual Module
{
public:
/// \~chinese /// \~chinese
/// @brief 渲染前 /// @brief 渲染前
virtual void BeforeRender() {} /// @param ctx 渲染上下文
virtual void BeforeRender(RenderModuleContext& ctx);
/// \~chinese /// \~chinese
/// @brief 渲染时 /// @brief 渲染时
/// @param ctx 渲染上下文 /// @param ctx 渲染上下文
virtual void OnRender(RenderContext& ctx) {} virtual void OnRender(RenderModuleContext& ctx);
/// \~chinese /// \~chinese
/// @brief 渲染后 /// @brief 渲染后
virtual void AfterRender() {} /// @param ctx 渲染上下文
virtual void AfterRender(RenderModuleContext& ctx);
public: protected:
RenderModule(); Module();
}; };
/**
* \~chinese
* @brief
*/
class KGE_API UpdateModule : public virtual Module
{
public:
/// \~chinese
/// @brief 更新前
virtual void BeforeUpdate() {}
/// \~chinese
/// @brief 更新时
/// @param dt 间隔时间
virtual void OnUpdate(Duration dt) {}
/// \~chinese
/// @brief 更新后
virtual void AfterUpdate() {}
public:
UpdateModule();
};
/**
* \~chinese
* @brief
*/
class KGE_API EventModule : public virtual Module
{
public:
/// \~chinese
/// @brief 事件处理
/// @param evt 事件
virtual void HandleEvent(Event* evt) {}
public:
EventModule();
};
#define KGE_DEFINE_COMPONENT_FLAG(OFFSET) (0x01 << (OFFSET % 32))
template <>
struct ModuleFlag<RenderModule>
{
static constexpr int value = KGE_DEFINE_COMPONENT_FLAG(0);
};
template <>
struct ModuleFlag<UpdateModule>
{
static constexpr int value = KGE_DEFINE_COMPONENT_FLAG(1);
};
template <>
struct ModuleFlag<EventModule>
{
static constexpr int value = KGE_DEFINE_COMPONENT_FLAG(2);
};
#undef KGE_DEFINE_COMPONENT_FLAG
} // namespace kiwano } // namespace kiwano

View File

@ -18,25 +18,75 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
#include <typeinfo>
#include <atomic>
#include <kiwano/base/ObjectBase.h> #include <kiwano/base/ObjectBase.h>
#include <kiwano/base/ObjectPool.h>
#include <kiwano/utils/Logger.h> #include <kiwano/utils/Logger.h>
#include <kiwano/utils/Json.h> #include <kiwano/utils/Json.h>
#include <typeinfo>
namespace kiwano namespace kiwano
{ {
namespace namespace
{ {
bool tracing_leaks = false;
Vector<ObjectBase*> tracing_objects; bool tracing_leaks = false;
uint32_t last_object_id = 0; Vector<ObjectBase*> tracing_objects;
std::atomic<uint64_t> last_object_id = 0;
ObjectPolicyFunc object_policy_ = ObjectPolicy::ErrorLog();
} // namespace } // namespace
ObjectFailException::ObjectFailException(ObjectBase* obj, const ObjectStatus& status)
: obj_(obj)
, status_(status)
{
}
char const* ObjectFailException::what() const
{
return status_.msg.empty() ? "Object operation failed" : status_.msg.c_str();
}
ObjectPolicyFunc ObjectPolicy::WarnLog(int threshold)
{
return [=](ObjectBase* obj, const ObjectStatus& status)
{
if (!obj->IsValid() || status.code <= threshold)
{
KGE_WARNF("Object operation failed: obj(%p), code(%d), msg(%s)", obj, status.code, status.msg.c_str());
}
};
}
ObjectPolicyFunc ObjectPolicy::ErrorLog(int threshold)
{
return [=](ObjectBase* obj, const ObjectStatus& status)
{
if (!obj->IsValid() || status.code <= threshold)
{
KGE_ERRORF("Object operation failed: obj(%p), code(%d), msg(%s)", obj, status.code, status.msg.c_str());
}
};
}
ObjectPolicyFunc ObjectPolicy::Exception(int threshold)
{
return [=](ObjectBase* obj, const ObjectStatus& status)
{
if (!obj->IsValid() || status.code <= threshold)
{
throw ObjectFailException(obj, status);
}
};
}
ObjectBase::ObjectBase() ObjectBase::ObjectBase()
: tracing_leak_(false) : tracing_leak_(false)
, name_(nullptr) , name_(nullptr)
, user_data_() , user_data_(nullptr)
, status_(nullptr)
, id_(++last_object_id) , id_(++last_object_id)
{ {
#ifdef KGE_DEBUG #ifdef KGE_DEBUG
@ -52,22 +102,19 @@ ObjectBase::~ObjectBase()
name_ = nullptr; name_ = nullptr;
} }
ClearStatus();
#ifdef KGE_DEBUG #ifdef KGE_DEBUG
ObjectBase::RemoveObjectFromTracingList(this); ObjectBase::RemoveObjectFromTracingList(this);
#endif #endif
} }
void ObjectBase::AutoRelease() void* ObjectBase::GetUserData() const
{
ObjectPool::GetInstance().AddObject(this);
}
const Any& ObjectBase::GetUserData() const
{ {
return user_data_; return user_data_;
} }
void ObjectBase::SetUserData(const Any& data) void ObjectBase::SetUserData(void* data)
{ {
user_data_ = data; user_data_ = data;
} }
@ -105,6 +152,54 @@ void ObjectBase::DoDeserialize(Deserializer* deserializer)
SetName(name); SetName(name);
} }
bool ObjectBase::IsValid() const
{
return status_ ? status_->Success() : true;
}
ObjectStatus* ObjectBase::GetStatus() const
{
return status_;
}
void ObjectBase::SetStatus(const ObjectStatus& status)
{
if (!status_)
{
status_ = new ObjectStatus;
}
status_->msg = status.msg;
if (status_->code != status.code)
{
status_->code = status.code;
if (object_policy_)
{
object_policy_(this, *status_);
}
}
}
void ObjectBase::Fail(const String& msg, int code)
{
SetStatus(ObjectStatus(code, msg));
}
void ObjectBase::ClearStatus()
{
if (status_)
{
delete status_;
status_ = nullptr;
}
}
void ObjectBase::SetObjectPolicy(const ObjectPolicyFunc& policy)
{
object_policy_ = policy;
}
bool ObjectBase::IsTracingLeaks() bool ObjectBase::IsTracingLeaks()
{ {
return tracing_leaks; return tracing_leaks;

View File

@ -21,20 +21,118 @@
#pragma once #pragma once
#include <kiwano/macros.h> #include <kiwano/macros.h>
#include <kiwano/core/Common.h> #include <kiwano/core/Common.h>
#include <kiwano/core/Exception.h>
#include <kiwano/core/Serializable.h> #include <kiwano/core/Serializable.h>
#include <kiwano/core/SmartPtr.hpp> #include <kiwano/base/RefObject.h>
#include <kiwano/base/RefCounter.h> #include <kiwano/base/RefPtr.h>
namespace kiwano namespace kiwano
{ {
KGE_DECLARE_SMART_PTR(ObjectBase); KGE_DECLARE_SMART_PTR(ObjectBase);
/**
* \~chinese
* @brief
*/
struct ObjectStatus
{
int code = 0; ///< 状态码,等于 0 时为成功状态,否则为失败状态
String msg; ///< 状态信息
ObjectStatus() = default;
ObjectStatus(int code, const String& msg)
: code(code)
, msg(msg)
{
}
/// \~chinese
/// @brief 对象状态是否成功
inline bool Success() const
{
return this->code == 0;
}
/// \~chinese
/// @brief 对象失败状态
static const int fail = -1;
};
/**
* \~chinese
* @brief
*/
class ObjectFailException : public Exception
{
public:
ObjectFailException(ObjectBase* obj, const ObjectStatus& status);
/// \~chinese
/// @brief 获取失败的对象指针
inline ObjectBase* GetObj() const
{
return obj_;
}
/// \~chinese
/// @brief 获取对象状态
inline ObjectStatus GetStatus() const
{
return status_;
}
virtual char const* what() const override;
private:
ObjectBase* obj_;
ObjectStatus status_;
};
/**
* \~chinese
* @brief
*/
typedef Function<void(ObjectBase*, const ObjectStatus&)> ObjectPolicyFunc;
/**
* \~chinese
* @brief
*/
struct ObjectPolicy
{
/// \~chinese
/// @brief 忽略对象失败状态
static inline ObjectPolicyFunc Ignore()
{
return nullptr;
}
/// \~chinese
/// @brief 在对象状态变为失败时打印警告日志
/// @param threshold 触发阈值
/// @return 对象处理策略方法
static ObjectPolicyFunc WarnLog(int threshold = ObjectStatus::fail);
/// \~chinese
/// @brief 在对象状态变为失败时打印错误日志(默认策略)
/// @param threshold 触发阈值
/// @return 对象处理策略方法
static ObjectPolicyFunc ErrorLog(int threshold = ObjectStatus::fail);
/// \~chinese
/// @brief 在对象状态变为失败时抛出 ObjectFailException
/// @param threshold 触发阈值
/// @return 对象处理策略方法
static ObjectPolicyFunc Exception(int threshold = ObjectStatus::fail);
};
/** /**
* \~chinese * \~chinese
* @brief * @brief
*/ */
class KGE_API ObjectBase class KGE_API ObjectBase
: public RefCounter : public RefObject
, public Serializable , public Serializable
{ {
public: public:
@ -44,10 +142,6 @@ public:
virtual ~ObjectBase(); virtual ~ObjectBase();
/// \~chinese
/// @brief ×Ô¶¯ÊÍ·Å
void AutoRelease();
/// \~chinese /// \~chinese
/// @brief 设置对象名 /// @brief 设置对象名
void SetName(const String& name); void SetName(const String& name);
@ -63,15 +157,15 @@ public:
/// \~chinese /// \~chinese
/// @brief 获取用户数据 /// @brief 获取用户数据
const Any& GetUserData() const; void* GetUserData() const;
/// \~chinese /// \~chinese
/// @brief 设置用户数据 /// @brief 设置用户数据
void SetUserData(const Any& data); void SetUserData(void* data);
/// \~chinese /// \~chinese
/// @brief 获取对象ID /// @brief 获取对象ID
uint32_t GetObjectID() const; uint64_t GetObjectID() const;
/// \~chinese /// \~chinese
/// @brief 序列化 /// @brief 序列化
@ -81,6 +175,30 @@ public:
/// @brief 反序列化 /// @brief 反序列化
void DoDeserialize(Deserializer* deserializer) override; void DoDeserialize(Deserializer* deserializer) override;
/// \~chinese
/// @brief 判断对象是否有效
virtual bool IsValid() const;
/// \~chinese
/// @brief 获取对象状态
ObjectStatus* GetStatus() const;
/// \~chinese
/// @brief 设置对象状态
void SetStatus(const ObjectStatus& status);
/// \~chinese
/// @brief 将对象标记为失败状态
void Fail(const String& msg, int code = ObjectStatus::fail);
/// \~chinese
/// @brief 清除对象状态
void ClearStatus();
/// \~chinese
/// @brief 设置对象处理策略
static void SetObjectPolicy(const ObjectPolicyFunc& policy);
public: public:
/// \~chinese /// \~chinese
/// @brief 是否启用了内存泄漏追踪 /// @brief 是否启用了内存泄漏追踪
@ -108,11 +226,13 @@ private:
static void RemoveObjectFromTracingList(ObjectBase*); static void RemoveObjectFromTracingList(ObjectBase*);
private: private:
const uint32_t id_; const uint64_t id_;
bool tracing_leak_; bool tracing_leak_;
String* name_; String* name_;
Any user_data_; void* user_data_;
ObjectStatus* status_;
}; };
inline String ObjectBase::GetName() const inline String ObjectBase::GetName() const
@ -127,7 +247,7 @@ inline bool ObjectBase::IsName(const String& name) const
return name_ ? (*name_ == name) : name.empty(); return name_ ? (*name_ == name) : name.empty();
} }
inline uint32_t ObjectBase::GetObjectID() const inline uint64_t ObjectBase::GetObjectID() const
{ {
return id_; return id_;
} }

View File

@ -18,29 +18,84 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
#include <kiwano/base/RefCounter.h> #include <kiwano/base/RefObject.h>
namespace kiwano namespace kiwano
{ {
RefCounter::RefCounter()
RefObject::RefObject()
: ref_count_(0) : ref_count_(0)
{ {
} }
RefCounter::~RefCounter() {} RefObject::~RefObject() {}
void RefCounter::Retain() void RefObject::Retain()
{ {
++ref_count_; ++ref_count_;
} }
void RefCounter::Release() void RefObject::Release()
{ {
--ref_count_; --ref_count_;
if (ref_count_ == 0) if (ref_count_ == 0)
{ {
memory::Delete(this); delete this;
} }
} }
uint32_t RefObject::GetRefCount() const
{
return ref_count_.load();
}
void* RefObject::operator new(size_t size)
{
void* ptr = memory::Alloc(size);
if (!ptr)
{
throw std::bad_alloc();
}
return ptr;
}
void RefObject::operator delete(void* ptr)
{
memory::Free(ptr);
}
void* RefObject::operator new(size_t size, std::nothrow_t const&)
{
try
{
void* ptr = memory::Alloc(size);
return ptr;
}
catch (...)
{
}
return nullptr;
}
void RefObject::operator delete(void* ptr, std::nothrow_t const&)
{
try
{
memory::Free(ptr);
}
catch (...)
{
}
}
void* RefObject::operator new(size_t size, void* ptr)
{
return ::operator new(size, ptr);
}
void RefObject::operator delete(void* ptr, void* place) noexcept
{
::operator delete(ptr, place);
}
} // namespace kiwano } // namespace kiwano

View File

@ -24,17 +24,14 @@
namespace kiwano namespace kiwano
{ {
/** /**
* \~chinese * \~chinese
* @brief * @brief
*/ */
class KGE_API RefCounter : protected Noncopyable class KGE_API RefObject : protected Noncopyable
{ {
public: public:
RefCounter();
virtual ~RefCounter();
/// \~chinese /// \~chinese
/// @brief 增加引用计数 /// @brief 增加引用计数
void Retain(); void Retain();
@ -47,13 +44,25 @@ public:
/// @brief 获取引用计数 /// @brief 获取引用计数
uint32_t GetRefCount() const; uint32_t GetRefCount() const;
static void* operator new(size_t size);
static void operator delete(void* ptr);
static void* operator new(size_t size, std::nothrow_t const&) noexcept;
static void operator delete(void* ptr, std::nothrow_t const&) noexcept;
static void* operator new(size_t size, void* ptr) noexcept;
static void operator delete(void* ptr, void* place) noexcept;
virtual ~RefObject();
protected:
RefObject();
private: private:
std::atomic<uint32_t> ref_count_; std::atomic<uint32_t> ref_count_;
}; };
inline uint32_t RefCounter::GetRefCount() const
{
return ref_count_;
}
} // namespace kiwano } // namespace kiwano

View File

@ -18,69 +18,57 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
#include <kiwano/base/ObjectPool.h> #pragma once
#include <kiwano/base/RefObject.h>
#include <kiwano/core/RefBasePtr.hpp>
namespace kiwano namespace kiwano
{ {
List<ObjectPool*> ObjectPool::pools_; /// \~chinese
/// @brief 默认的智能指针引用计数策略
ObjectPool& ObjectPool::GetInstance() struct DefaultRefPtrPolicy
{ {
static ObjectPool instance; inline void Retain(RefObject* ptr)
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)
{
if (obj)
{ {
if (!Contains(obj)) if (ptr)
{ ptr->Retain();
obj->Retain();
std::lock_guard<std::mutex> lock(mutex_);
objects_.push_back(obj);
}
}
}
bool ObjectPool::Contains(ObjectBase* 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;
}
void ObjectPool::Clear()
{
Vector<ObjectBase*> copied;
{
std::lock_guard<std::mutex> lock(mutex_);
copied = std::move(objects_);
} }
for (auto obj : copied) inline void Release(RefObject* ptr)
obj->Release(); {
if (ptr)
ptr->Release();
}
};
/// \~chinese
/// @brief 引用计数对象智能指针
template <typename _Ty>
using RefPtr = RefBasePtr<_Ty, DefaultRefPtrPolicy>;
/// \~chinese
/// @brief 构造引用计数对象智能指针
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");
return RefPtr<_Ty>(new _Ty(std::forward<_Args>(args)...));
}
/// \~chinese
/// @brief 构造引用计数对象智能指针
template <typename _Ty>
inline RefPtr<_Ty> MakePtr(_Ty* ptr)
{
static_assert(std::is_base_of<RefObject, _Ty>::value, "_Ty must be derived from RefObject");
return RefPtr<_Ty>(ptr);
} }
} // namespace kiwano } // namespace kiwano
#ifndef KGE_DECLARE_SMART_PTR
#define KGE_DECLARE_SMART_PTR(CLASS) \
class CLASS; \
typedef ::kiwano::RefPtr<CLASS> CLASS##Ptr;
#endif

View File

@ -25,23 +25,19 @@
namespace kiwano namespace kiwano
{ {
ButtonPtr Button::Create(const Callback& click) Button::Button(const Callback& click)
: Button(click, nullptr, nullptr, nullptr)
{ {
return Button::Create(click, nullptr, nullptr, nullptr);
} }
ButtonPtr Button::Create(const Callback& click, const Callback& pressed, const Callback& mouse_over, Button::Button(const Callback& click, const Callback& pressed, const Callback& mouse_over, const Callback& mouse_out)
const Callback& mouse_out) : status_(Status::Normal)
, click_callback_(click)
, pressed_callback_(pressed)
, mouse_over_callback_(mouse_over)
, mouse_out_callback_(mouse_out)
{ {
ButtonPtr ptr = memory::New<Button>(); SetName("__KGE_BUTTON__");
if (ptr)
{
ptr->SetClickCallback(click);
ptr->SetPressedCallback(pressed);
ptr->SetMouseOverCallback(mouse_over);
ptr->SetMouseOutCallback(mouse_out);
}
return ptr;
} }
Button::Button() Button::Button()

View File

@ -45,7 +45,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建按钮 /// @brief 创建按钮
/// @param click 按钮点击回调函数 /// @param click 按钮点击回调函数
static ButtonPtr Create(const Callback& click); Button(const Callback& click);
/// \~chinese /// \~chinese
/// @brief 创建按钮 /// @brief 创建按钮
@ -53,8 +53,7 @@ public:
/// @param pressed 按钮按下回调函数 /// @param pressed 按钮按下回调函数
/// @param mouse_over 按钮移入回调函数 /// @param mouse_over 按钮移入回调函数
/// @param mouse_out 按钮移出回调函数 /// @param mouse_out 按钮移出回调函数
static ButtonPtr Create(const Callback& click, const Callback& pressed, const Callback& mouse_over, Button(const Callback& click, const Callback& pressed, const Callback& mouse_over, const Callback& mouse_out);
const Callback& mouse_out);
Button(); Button();

View File

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

View File

@ -40,7 +40,7 @@ public:
/// \~chinese /// \~chinese
/// @brief 释放内存 /// @brief 释放内存
virtual void Free(void* ptr, size_t size) = 0; virtual void Free(void* ptr) = 0;
}; };
/// \~chinese /// \~chinese
@ -60,52 +60,12 @@ inline void* Alloc(size_t size)
/// \~chinese /// \~chinese
/// @brief 使用当前内存分配器释放内存 /// @brief 使用当前内存分配器释放内存
inline void Free(void* ptr, size_t size) inline void Free(void* ptr)
{ {
memory::GetAllocator()->Free(ptr, size); memory::GetAllocator()->Free(ptr);
}
/// \~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 /// \~chinese
/// @brief 分配器 /// @brief 分配器
@ -153,19 +113,19 @@ public:
inline void deallocate(void* ptr, size_t count) inline void deallocate(void* ptr, size_t count)
{ {
memory::Free(ptr, sizeof(_Ty) * count); memory::Free(ptr /*, sizeof(_Ty) * count */);
} }
template <typename _UTy, typename... _Args> template <typename _UTy, typename... _Args>
inline void construct(_UTy* ptr, _Args&&... args) inline void construct(_UTy* const ptr, _Args&&... args)
{ {
memory::Construct<_UTy>(ptr, std::forward<_Args>(args)...); ::new (const_cast<void*>(static_cast<const volatile void*>(ptr))) _Ty(std::forward<_Args>(args)...);
} }
template <typename _UTy> template <typename _UTy>
inline void destroy(_UTy* ptr) inline void destroy(_UTy* ptr)
{ {
memory::Destroy<_UTy>(ptr); ptr->~_UTy();
} }
size_t max_size() const noexcept size_t max_size() const noexcept
@ -215,5 +175,4 @@ bool operator!=(const Allocator<_Ty>&, const Allocator<_Other>&) noexcept
return false; return false;
} }
} // namespace memory
} // namespace kiwano } // namespace kiwano

View File

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

View File

@ -56,23 +56,28 @@ using WideStringStream = std::wstringstream;
/// \~chinese /// \~chinese
/// @brief 线性数组容器 /// @brief 线性数组容器
template <typename _Ty, typename... _Args> template <typename _Ty, typename _Alloc = std::allocator<_Ty>>
using Vector = std::vector<_Ty, _Args...>; using Vector = std::vector<_Ty, _Alloc>;
/// \~chinese /// \~chinese
/// @brief 链表容器 /// @brief 链表容器
template <typename _Ty, typename... _Args> template <typename _Ty, typename _Alloc = std::allocator<_Ty>>
using List = std::list<_Ty, _Args...>; using List = std::list<_Ty, _Alloc>;
/// \~chinese
/// @brief 双端队列容器
template <typename _Ty, typename _Alloc = std::allocator<_Ty>>
using Deque = std::deque<_Ty, _Alloc>;
/// \~chinese /// \~chinese
/// @brief 队列容器 /// @brief 队列容器
template <typename _Ty, typename... _Args> template <typename _Ty, typename _Container = Deque<_Ty>>
using Queue = std::queue<_Ty, _Args...>; using Queue = std::queue<_Ty, _Container>;
/// \~chinese /// \~chinese
/// @brief 集合容器 /// @brief 集合容器
template <typename _Ty, typename... _Args> template <typename _Kty, typename _Compare = std::less<_Kty>, typename _Alloc = std::allocator<_Kty>>
using Set = std::set<_Ty, _Args...>; using Set = std::set<_Kty, _Compare, _Alloc>;
/// \~chinese /// \~chinese
/// @brief 对容器 /// @brief 对容器
@ -81,23 +86,25 @@ using Pair = std::pair<_Ty1, _Ty2>;
/// \~chinese /// \~chinese
/// @brief 无序集合容器 /// @brief 无序集合容器
template <typename _Ty, typename... _Args> template <typename _Kty, typename _Hash = std::hash<_Kty>, typename _Keq = std::equal_to<_Kty>,
using UnorderedSet = std::unordered_set<_Ty, _Args...>; typename _Alloc = std::allocator<_Kty>>
using UnorderedSet = std::unordered_set<_Kty, _Hash, _Keq, _Alloc>;
/// \~chinese /// \~chinese
/// @brief 栈容器 /// @brief 栈容器
template <typename _Ty, typename... _Args> template <typename _Ty, typename _Container = Deque<_Ty>>
using Stack = std::stack<_Ty, _Args...>; using Stack = std::stack<_Ty, _Container>;
/// \~chinese /// \~chinese
/// @brief ×Ö·û´®ÈÝÆ÷ /// @brief 排序关联容器
template <typename _Kty, typename _Ty, typename... _Args> template <typename _Kty, typename _Ty, typename _Compare = std::less<_Kty>, typename _Alloc = std::allocator<Pair<const _Kty, _Ty>>>
using Map = std::map<_Kty, _Ty, _Args...>; using Map = std::map<_Kty, _Ty, _Compare, _Alloc>;
/// \~chinese /// \~chinese
/// @brief ×Ö·û´®ÈÝÆ÷ /// @brief 非排序关联容器
template <typename _Kty, typename _Ty, typename... _Args> template <typename _Kty, typename _Ty, typename _Hash = std::hash<_Kty>, typename _Keq = std::equal_to<_Kty>,
using UnorderedMap = std::unordered_map<_Kty, _Ty, _Args...>; typename _Alloc = std::allocator<Pair<const _Kty, _Ty>>>
using UnorderedMap = std::unordered_map<_Kty, _Ty, _Hash, _Keq, _Alloc>;
/// \~chinese /// \~chinese
/// @brief 不可拷贝对象 /// @brief 不可拷贝对象

View File

@ -20,26 +20,9 @@
#pragma once #pragma once
#include <kiwano/core/Common.h> #include <kiwano/core/Common.h>
#include <kiwano/utils/Logger.h>
#include <stdexcept> #include <stdexcept>
#include <system_error> #include <system_error>
#define KGE_THROW(MESSAGE) \
do \
{ \
KGE_ERRORF("An exception occurred: %s", MESSAGE); \
kiwano::StackTracer().Print(); \
throw kiwano::RuntimeError(MESSAGE); \
} while (0)
#define KGE_THROW_SYSTEM_ERROR(ERRCODE, MESSAGE) \
do \
{ \
KGE_ERRORF("An exception occurred (%#x): %s", ERRCODE, MESSAGE); \
kiwano::StackTracer().Print(); \
throw kiwano::SystemError(std::error_code(kiwano::error_enum(ERRCODE)), MESSAGE); \
} while (0)
namespace kiwano namespace kiwano
{ {
@ -104,12 +87,6 @@ inline std::error_condition make_error_condition(kiwano::error_enum errc) noexce
return std::error_condition(static_cast<int>(errc), kiwano::com_category()); return std::error_condition(static_cast<int>(errc), kiwano::com_category());
} }
#define KGE_THROW_IF_FAILED(HR, MESSAGE) \
if (FAILED(HR)) \
{ \
KGE_THROW_SYSTEM_ERROR(HR, MESSAGE); \
}
} // namespace kiwano } // namespace kiwano
#endif // KGE_PLATFORM_WINDOWS #endif // KGE_PLATFORM_WINDOWS

View File

@ -22,36 +22,16 @@
#include <utility> #include <utility>
#include <type_traits> #include <type_traits>
#include <kiwano/core/Common.h> #include <kiwano/core/Common.h>
#include <kiwano/base/RefCounter.h>
namespace kiwano namespace kiwano
{ {
/** /**
* \~chinese * \~chinese
* @brief * @brief ÒýÓüÆÊýÖÇÄÜÖ¸Õë
*/ */
struct DefaultSmartPtrRefProxy template <typename _Ty, typename _RefPolicy>
{ class RefBasePtr : protected _RefPolicy
static inline void Retain(RefCounter* ptr)
{
if (ptr)
ptr->Retain();
}
static inline void Release(RefCounter* ptr)
{
if (ptr)
ptr->Release();
}
};
/**
* \~chinese
* @brief
*/
template <typename _Ty, typename _ProxyTy = DefaultSmartPtrRefProxy>
class SmartPtr
{ {
public: public:
using value_type = _Ty; using value_type = _Ty;
@ -60,65 +40,66 @@ public:
using reference_type = _Ty&; using reference_type = _Ty&;
using const_reference_type = const _Ty&; using const_reference_type = const _Ty&;
SmartPtr() noexcept RefBasePtr() noexcept
: ptr_(nullptr) : ptr_(nullptr)
{ {
} }
SmartPtr(std::nullptr_t) noexcept RefBasePtr(std::nullptr_t) noexcept
: ptr_(nullptr) : ptr_(nullptr)
{ {
} }
SmartPtr(pointer_type p) RefBasePtr(pointer_type p)
: ptr_(p) : ptr_(p)
{ {
_ProxyTy::Retain(ptr_); _RefPolicy::Retain(ptr_);
} }
SmartPtr(const SmartPtr& other) RefBasePtr(const RefBasePtr& other)
: ptr_(other.ptr_) : ptr_(other.ptr_)
{ {
_ProxyTy::Retain(ptr_); _RefPolicy::Retain(ptr_);
} }
SmartPtr(SmartPtr&& other) noexcept RefBasePtr(RefBasePtr&& other) noexcept
: ptr_(nullptr) : ptr_(nullptr)
{ {
Swap(other); Swap(other);
} }
~SmartPtr() ~RefBasePtr()
{ {
Tidy(); Tidy();
} }
template <typename _UTy, typename std::enable_if<std::is_base_of<_Ty, _UTy>::value, int>::type = 0> template <typename _UTy, typename std::enable_if<std::is_convertible<_UTy*, _Ty*>::value, int>::type = 0>
SmartPtr(const SmartPtr<_UTy, _ProxyTy>& other) RefBasePtr(const RefBasePtr<_UTy, _RefPolicy>& other)
{ {
ptr_ = const_cast<pointer_type>(dynamic_cast<const_pointer_type>(other.Get())); ptr_ = dynamic_cast<pointer_type>(other.Get());
_ProxyTy::Retain(ptr_); _RefPolicy::Retain(ptr_);
} }
inline pointer_type Get() noexcept inline pointer_type Get() const noexcept
{ {
return ptr_; 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) inline void Reset(pointer_type ptr = nullptr)
{ {
if (ptr) if (ptr)
SmartPtr(ptr).Swap(*this); RefBasePtr(ptr).Swap(*this);
else else
Tidy(); Tidy();
} }
inline void Swap(SmartPtr& other) noexcept inline void Swap(RefBasePtr& other) noexcept
{ {
std::swap(ptr_, other.ptr_); std::swap(ptr_, other.ptr_);
} }
@ -149,8 +130,7 @@ public:
inline pointer_type* operator&() inline pointer_type* operator&()
{ {
KGE_ASSERT(ptr_ == nullptr && "Memory leak"); return this->GetAddressOfAndRelease();
return &ptr_;
} }
inline operator bool() const noexcept inline operator bool() const noexcept
@ -163,28 +143,36 @@ public:
return ptr_ == 0; return ptr_ == 0;
} }
inline SmartPtr& operator=(const SmartPtr& other) inline RefBasePtr& operator=(const RefBasePtr& other)
{ {
if (other.ptr_ != ptr_) if (other.ptr_ != ptr_)
SmartPtr(other).Swap(*this); RefBasePtr(other).Swap(*this);
return (*this); return (*this);
} }
inline SmartPtr& operator=(SmartPtr&& other) noexcept inline RefBasePtr& operator=(RefBasePtr&& other) noexcept
{ {
if (other.ptr_ != ptr_) if (other.ptr_ != ptr_)
other.Swap(*this); other.Swap(*this);
return (*this); return (*this);
} }
inline SmartPtr& operator=(pointer_type p) inline RefBasePtr& operator=(pointer_type p)
{ {
if (p != ptr_) if (p != ptr_)
SmartPtr(p).Swap(*this); RefBasePtr(p).Swap(*this);
return (*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 RefBasePtr& operator=(const RefBasePtr<_UTy, _RefPolicy>& other)
{
if (other.Get() != ptr_)
RefBasePtr(dynamic_cast<pointer_type>(other.Get())).Swap(*this);
return (*this);
}
inline RefBasePtr& operator=(std::nullptr_t)
{ {
Tidy(); Tidy();
return *this; return *this;
@ -193,7 +181,7 @@ public:
private: private:
void Tidy() void Tidy()
{ {
_ProxyTy::Release(ptr_); _RefPolicy::Release(ptr_);
ptr_ = nullptr; ptr_ = nullptr;
} }
@ -201,84 +189,78 @@ private:
pointer_type ptr_; pointer_type ptr_;
}; };
template <class _Ty, class _UTy, class _ProxyTy> template <class _Ty, class _UTy, class _RefPolicy>
inline bool operator==(const SmartPtr<_Ty, _ProxyTy>& lhs, const SmartPtr<_UTy, _ProxyTy>& rhs) noexcept inline bool operator==(const RefBasePtr<_Ty, _RefPolicy>& lhs, const RefBasePtr<_UTy, _RefPolicy>& rhs) noexcept
{ {
return lhs.Get() == rhs.Get(); return lhs.Get() == rhs.Get();
} }
template <class _Ty, class _ProxyTy> template <class _Ty, class _RefPolicy>
inline bool operator==(const SmartPtr<_Ty, _ProxyTy>& lhs, _Ty* rhs) noexcept inline bool operator==(const RefBasePtr<_Ty, _RefPolicy>& lhs, _Ty* rhs) noexcept
{ {
return lhs.Get() == rhs; return lhs.Get() == rhs;
} }
template <class _Ty, class _ProxyTy> template <class _Ty, class _RefPolicy>
inline bool operator==(_Ty* lhs, const SmartPtr<_Ty, _ProxyTy>& rhs) noexcept inline bool operator==(_Ty* lhs, const RefBasePtr<_Ty, _RefPolicy>& rhs) noexcept
{ {
return lhs == rhs.Get(); return lhs == rhs.Get();
} }
template <class _Ty, class _ProxyTy> template <class _Ty, class _RefPolicy>
inline bool operator==(const SmartPtr<_Ty, _ProxyTy>& lhs, std::nullptr_t) noexcept inline bool operator==(const RefBasePtr<_Ty, _RefPolicy>& lhs, std::nullptr_t) noexcept
{ {
return !static_cast<bool>(lhs); return !static_cast<bool>(lhs);
} }
template <class _Ty, class _ProxyTy> template <class _Ty, class _RefPolicy>
inline bool operator==(std::nullptr_t, const SmartPtr<_Ty, _ProxyTy>& rhs) noexcept inline bool operator==(std::nullptr_t, const RefBasePtr<_Ty, _RefPolicy>& rhs) noexcept
{ {
return !static_cast<bool>(rhs); return !static_cast<bool>(rhs);
} }
template <class _Ty, class _UTy, class _ProxyTy> template <class _Ty, class _UTy, class _RefPolicy>
inline bool operator!=(const SmartPtr<_Ty, _ProxyTy>& lhs, const SmartPtr<_UTy, _ProxyTy>& rhs) noexcept inline bool operator!=(const RefBasePtr<_Ty, _RefPolicy>& lhs, const RefBasePtr<_UTy, _RefPolicy>& rhs) noexcept
{ {
return !(lhs == rhs); return !(lhs == rhs);
} }
template <class _Ty, class _ProxyTy> template <class _Ty, class _RefPolicy>
inline bool operator!=(const SmartPtr<_Ty, _ProxyTy>& lhs, _Ty* rhs) noexcept inline bool operator!=(const RefBasePtr<_Ty, _RefPolicy>& lhs, _Ty* rhs) noexcept
{ {
return lhs.Get() != rhs; return lhs.Get() != rhs;
} }
template <class _Ty, class _ProxyTy> template <class _Ty, class _RefPolicy>
inline bool operator!=(_Ty* lhs, const SmartPtr<_Ty, _ProxyTy>& rhs) noexcept inline bool operator!=(_Ty* lhs, const RefBasePtr<_Ty, _RefPolicy>& rhs) noexcept
{ {
return lhs != rhs.Get(); return lhs != rhs.Get();
} }
template <class _Ty, class _ProxyTy> template <class _Ty, class _RefPolicy>
inline bool operator!=(const SmartPtr<_Ty, _ProxyTy>& lhs, std::nullptr_t) noexcept inline bool operator!=(const RefBasePtr<_Ty, _RefPolicy>& lhs, std::nullptr_t) noexcept
{ {
return static_cast<bool>(lhs); return static_cast<bool>(lhs);
} }
template <class _Ty, class _ProxyTy> template <class _Ty, class _RefPolicy>
inline bool operator!=(std::nullptr_t, const SmartPtr<_Ty, _ProxyTy>& rhs) noexcept inline bool operator!=(std::nullptr_t, const RefBasePtr<_Ty, _RefPolicy>& rhs) noexcept
{ {
return static_cast<bool>(rhs); return static_cast<bool>(rhs);
} }
template <class _Ty, class _UTy, class _ProxyTy> template <class _Ty, class _UTy, class _RefPolicy>
inline bool operator<(const SmartPtr<_Ty, _ProxyTy>& lhs, const SmartPtr<_UTy, _ProxyTy>& rhs) noexcept inline bool operator<(const RefBasePtr<_Ty, _RefPolicy>& lhs, const RefBasePtr<_UTy, _RefPolicy>& rhs) noexcept
{ {
return lhs.Get() < rhs.Get(); return lhs.Get() < rhs.Get();
} }
// template class cannot specialize std::swap, // template class cannot specialize std::swap,
// so implement a swap function in kiwano namespace // so implement a swap function in kiwano namespace
template <class _Ty, class _ProxyTy> template <class _Ty, class _RefPolicy>
inline void swap(SmartPtr<_Ty, _ProxyTy>& lhs, SmartPtr<_Ty, _ProxyTy>& rhs) noexcept inline void swap(RefBasePtr<_Ty, _RefPolicy>& lhs, RefBasePtr<_Ty, _RefPolicy>& rhs) noexcept
{ {
lhs.Swap(rhs); lhs.Swap(rhs);
} }
} // namespace kiwano } // namespace kiwano
#ifndef KGE_DECLARE_SMART_PTR
#define KGE_DECLARE_SMART_PTR(CLASS) \
class CLASS; \
typedef ::kiwano::SmartPtr<CLASS> CLASS##Ptr;
#endif

View File

@ -18,13 +18,12 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
#include <kiwano/core/Exception.h>
#include <kiwano/utils/Logger.h>
#include <kiwano/core/Time.h>
#include <regex> #include <regex>
#include <unordered_map> #include <unordered_map>
#include <chrono> #include <chrono>
#include <thread> #include <thread>
#include <kiwano/core/Time.h>
#include <kiwano/utils/Logger.h>
namespace kiwano namespace kiwano
{ {

View File

@ -19,7 +19,8 @@
// THE SOFTWARE. // THE SOFTWARE.
#pragma once #pragma once
#include <kiwano/core/SmartPtr.hpp> #include <kiwano/base/RefObject.h>
#include <kiwano/base/RefPtr.h>
#include <kiwano/event/EventType.h> #include <kiwano/event/EventType.h>
#include <kiwano/math/Math.h> #include <kiwano/math/Math.h>
@ -39,7 +40,7 @@ KGE_DECLARE_SMART_PTR(Event);
/// \~chinese /// \~chinese
/// @brief 事件 /// @brief 事件
class KGE_API Event : public RefCounter class KGE_API Event : public RefObject
{ {
public: public:
/// \~chinese /// \~chinese
@ -74,13 +75,6 @@ private:
const EventType type_; const EventType type_;
}; };
/// \~chinese
/// @brief 事件特性:判断是否是事件
template <typename _Ty>
struct IsBaseOfEvent : public std::bool_constant<std::is_base_of<Event, _Ty>::value || std::is_same<Event, _Ty>::value>
{
};
/// \~chinese /// \~chinese
/// @brief 事件特性:判断事件类型是否相同 /// @brief 事件特性:判断事件类型是否相同
template <typename _Ty> template <typename _Ty>
@ -88,7 +82,7 @@ struct IsSameEventType
{ {
inline bool operator()(const Event* evt) const inline bool operator()(const Event* evt) const
{ {
static_assert(kiwano::IsBaseOfEvent<_Ty>::value, "_Ty is not an event type."); static_assert(std::is_base_of<Event, _Ty>::value, "_Ty is not an event type.");
return evt->GetType() == KGE_EVENT(_Ty); return evt->GetType() == KGE_EVENT(_Ty);
} }
}; };
@ -103,7 +97,7 @@ inline const EventType& Event::GetType() const
template <typename _Ty> template <typename _Ty>
inline bool Event::IsType() const inline bool Event::IsType() const
{ {
static_assert(kiwano::IsBaseOfEvent<_Ty>::value, "_Ty is not an event type."); static_assert(std::is_base_of<Event, _Ty>::value, "_Ty is not an event type.");
return IsSameEventType<_Ty>()(this); return IsSameEventType<_Ty>()(this);
} }

View File

@ -58,14 +58,14 @@ EventListener* EventDispatcher::AddListener(EventListenerPtr listener)
EventListener* EventDispatcher::AddListener(const String& name, EventType type, EventListener::Callback callback) EventListener* EventDispatcher::AddListener(const String& name, EventType type, EventListener::Callback callback)
{ {
EventListenerPtr listener = EventListener::Create(name, type, callback); auto lis = MakePtr<EventListener>(name, type, callback);
return AddListener(listener); return AddListener(lis);
} }
EventListener* EventDispatcher::AddListener(EventType type, EventListener::Callback callback) EventListener* EventDispatcher::AddListener(EventType type, EventListener::Callback callback)
{ {
EventListenerPtr listener = EventListener::Create(type, callback); auto lis = MakePtr<EventListener>(type, callback);
return AddListener(listener); return AddListener(lis);
} }
void EventDispatcher::StartListeners(const String& name) void EventDispatcher::StartListeners(const String& name)

View File

@ -59,7 +59,7 @@ public:
template <typename _EventTy> template <typename _EventTy>
EventListener* AddListener(EventListener::Callback callback) EventListener* AddListener(EventListener::Callback callback)
{ {
static_assert(kiwano::IsBaseOfEvent<_EventTy>::value, "_EventTy is not an event type."); static_assert(std::is_base_of<Event, _EventTy>::value, "_EventTy is not an event type.");
return AddListener(KGE_EVENT(_EventTy), callback); return AddListener(KGE_EVENT(_EventTy), callback);
} }
@ -71,7 +71,7 @@ public:
template <typename _EventTy> template <typename _EventTy>
EventListener* AddListener(const String& name, EventListener::Callback callback) EventListener* AddListener(const String& name, EventListener::Callback callback)
{ {
static_assert(kiwano::IsBaseOfEvent<_EventTy>::value, "_EventTy is not an event type."); static_assert(std::is_base_of<Event, _EventTy>::value, "_EventTy is not an event type.");
return AddListener(name, KGE_EVENT(_EventTy), callback); return AddListener(name, KGE_EVENT(_EventTy), callback);
} }

View File

@ -24,29 +24,6 @@
namespace kiwano namespace kiwano
{ {
EventListenerPtr EventListener::Create(EventType type, const Callback& callback)
{
EventListenerPtr ptr = memory::New<EventListener>();
if (ptr)
{
ptr->SetEventType(type);
ptr->SetCallback(callback);
}
return ptr;
}
EventListenerPtr EventListener::Create(const String& name, EventType type, const Callback& callback)
{
EventListenerPtr ptr = memory::New<EventListener>();
if (ptr)
{
ptr->SetName(name);
ptr->SetEventType(type);
ptr->SetCallback(callback);
}
return ptr;
}
EventListener::EventListener() EventListener::EventListener()
: type_() : type_()
, callback_() , callback_()
@ -56,6 +33,19 @@ EventListener::EventListener()
{ {
} }
EventListener::EventListener(EventType type, const Callback& callback)
: EventListener()
{
this->SetEventType(type);
this->SetCallback(callback);
}
EventListener::EventListener(const String& name, EventType type, const Callback& callback)
: EventListener(type, callback)
{
this->SetName(name);
}
EventListener::~EventListener() {} EventListener::~EventListener() {}
void EventListener::Receive(Event* evt) void EventListener::Receive(Event* evt)

View File

@ -20,9 +20,8 @@
#pragma once #pragma once
#include <kiwano/core/Common.h> #include <kiwano/core/Common.h>
#include <kiwano/base/ObjectBase.h>
#include <kiwano/core/SmartPtr.hpp>
#include <kiwano/core/IntrusiveList.h> #include <kiwano/core/IntrusiveList.h>
#include <kiwano/base/ObjectBase.h>
#include <kiwano/event/Events.h> #include <kiwano/event/Events.h>
namespace kiwano namespace kiwano
@ -47,44 +46,21 @@ public:
/// @brief 监听器回调函数 /// @brief 监听器回调函数
using Callback = Function<void(Event*)>; using Callback = Function<void(Event*)>;
/// \~chinese
/// @brief 创建监听器
/// @param type 监听的事件类型
/// @param callback 回调函数
static EventListenerPtr Create(EventType type, const Callback& callback);
/// \~chinese
/// @brief 创建监听器
/// @param name 监听器名称
/// @param type 监听的事件类型
/// @param callback 回调函数
static EventListenerPtr Create(const String& name, EventType type, const Callback& callback);
/// \~chinese
/// @brief 创建监听器
/// @tparam _EventTy 事件类型
/// @param callback 回调函数
template <typename _EventTy>
static inline EventListenerPtr Create(const Callback& callback)
{
static_assert(kiwano::IsBaseOfEvent<_EventTy>::value, "_EventTy is not an event type.");
return EventListener::Create(KGE_EVENT(_EventTy), callback);
}
/// \~chinese
/// @brief 创建监听器
/// @tparam _EventTy 事件类型
/// @param name 监听器名称
/// @param callback 回调函数
template <typename _EventTy>
static inline EventListenerPtr Create(const String& name, const Callback& callback)
{
static_assert(kiwano::IsBaseOfEvent<_EventTy>::value, "_EventTy is not an event type.");
return EventListener::Create(name, KGE_EVENT(_EventTy), callback);
}
EventListener(); EventListener();
/// \~chinese
/// @brief 创建监听器
/// @param type 监听的事件类型
/// @param callback 回调函数
EventListener(EventType type, const Callback& callback);
/// \~chinese
/// @brief 创建监听器
/// @param name 监听器名称
/// @param type 监听的事件类型
/// @param callback 回调函数
EventListener(const String& name, EventType type, const Callback& callback);
virtual ~EventListener(); virtual ~EventListener();
/// \~chinese /// \~chinese
@ -142,7 +118,7 @@ public:
template <typename _EventTy> template <typename _EventTy>
inline void SetEventType() inline void SetEventType()
{ {
static_assert(kiwano::IsBaseOfEvent<_EventTy>::value, "_EventTy is not an event type."); static_assert(std::is_base_of<Event, _EventTy>::value, "_EventTy is not an event type.");
SetEventType(KGE_EVENT(_EventTy)); SetEventType(KGE_EVENT(_EventTy));
} }

View File

@ -46,14 +46,14 @@
#include <kiwano/core/Common.h> #include <kiwano/core/Common.h>
#include <kiwano/core/Defer.h> #include <kiwano/core/Defer.h>
#include <kiwano/core/Resource.h> #include <kiwano/core/Resource.h>
#include <kiwano/core/SmartPtr.hpp> #include <kiwano/core/RefBasePtr.hpp>
#include <kiwano/core/Time.h> #include <kiwano/core/Time.h>
// //
// base // base
// //
#include <kiwano/base/RefCounter.h> #include <kiwano/base/RefObject.h>
#include <kiwano/base/ObjectBase.h> #include <kiwano/base/ObjectBase.h>
#include <kiwano/base/Director.h> #include <kiwano/base/Director.h>
#include <kiwano/base/Module.h> #include <kiwano/base/Module.h>
@ -128,6 +128,7 @@
#include <kiwano/utils/Logger.h> #include <kiwano/utils/Logger.h>
#include <kiwano/utils/ResourceCache.h> #include <kiwano/utils/ResourceCache.h>
#include <kiwano/utils/ResourceLoader.h>
#include <kiwano/utils/UserData.h> #include <kiwano/utils/UserData.h>
#include <kiwano/utils/Timer.h> #include <kiwano/utils/Timer.h>
#include <kiwano/utils/Ticker.h> #include <kiwano/utils/Ticker.h>

View File

@ -23,7 +23,6 @@
#include <kiwano/base/Director.h> #include <kiwano/base/Director.h>
#include <kiwano/render/Renderer.h> #include <kiwano/render/Renderer.h>
#include <kiwano/render/TextureCache.h> #include <kiwano/render/TextureCache.h>
#include <kiwano/utils/ResourceCache.h>
#include <kiwano/utils/Logger.h> #include <kiwano/utils/Logger.h>
namespace kiwano namespace kiwano
@ -51,7 +50,7 @@ void Application::Run(RunnerPtr runner)
running_ = true; running_ = true;
is_paused_ = false; is_paused_ = false;
runner_ = runner; runner_ = runner;
timer_ = Timer::Create(); timer_ = MakePtr<Timer>();
// Initialize runner // Initialize runner
runner->InitSettings(); runner->InitSettings();
@ -122,7 +121,6 @@ void Application::Destroy()
// Clear user resources // Clear user resources
Director::GetInstance().ClearStages(); Director::GetInstance().ClearStages();
ResourceCache::GetInstance().Clear();
for (auto iter = modules_.rbegin(); iter != modules_.rend(); ++iter) for (auto iter = modules_.rbegin(); iter != modules_.rend(); ++iter)
{ {
@ -162,13 +160,8 @@ void Application::DispatchEvent(Event* evt)
if (!running_ /* Dispatch events even if application is paused */) if (!running_ /* Dispatch events even if application is paused */)
return; return;
for (auto comp : modules_) auto ctx = EventModuleContext(modules_, evt);
{ ctx.Next();
if (auto event_comp = comp->Cast<EventModule>())
{
event_comp->HandleEvent(evt);
}
}
} }
void Application::Update(Duration dt) void Application::Update(Duration dt)
@ -176,51 +169,24 @@ void Application::Update(Duration dt)
if (!running_ || is_paused_) if (!running_ || is_paused_)
return; return;
// Before update auto ctx = UpdateModuleContext(modules_, dt);
for (auto comp : modules_) ctx.Next();
{
if (auto update_comp = comp->Cast<UpdateModule>())
{
update_comp->BeforeUpdate();
}
}
// perform functions // perform functions
if (!functions_to_perform_.empty())
{ {
if (!functions_to_perform_.empty()) perform_mutex_.lock();
{ auto functions = std::move(functions_to_perform_);
perform_mutex_.lock(); perform_mutex_.unlock();
auto functions = std::move(functions_to_perform_);
perform_mutex_.unlock();
while (!functions.empty()) while (!functions.empty())
{
auto& func = functions.front();
if (func)
{ {
auto& func = functions.front(); func();
if (func)
{
func();
}
functions.pop();
} }
} functions.pop();
}
// Updating
Duration scaled_dt = dt * time_scale_;
for (auto comp : modules_)
{
if (auto update_comp = comp->Cast<UpdateModule>())
{
update_comp->OnUpdate(scaled_dt);
}
}
// After update
for (auto rit = modules_.rbegin(); rit != modules_.rend(); ++rit)
{
if (auto update_comp = (*rit)->Cast<UpdateModule>())
{
update_comp->AfterUpdate();
} }
} }
} }
@ -233,33 +199,9 @@ void Application::Render()
Renderer& renderer = Renderer::GetInstance(); Renderer& renderer = Renderer::GetInstance();
renderer.Clear(); renderer.Clear();
// Before render
for (auto comp : modules_)
{ {
if (auto render_comp = comp->Cast<RenderModule>()) auto ctx = RenderModuleContext(modules_, renderer.GetContext());
{ ctx.Next();
render_comp->BeforeRender();
}
}
// Rendering
renderer.BeginDraw();
for (auto comp : modules_)
{
if (auto render_comp = comp->Cast<RenderModule>())
{
render_comp->OnRender(renderer.GetContext());
}
}
renderer.EndDraw();
// After render
for (auto rit = modules_.rbegin(); rit != modules_.rend(); ++rit)
{
if (auto render_comp = (*rit)->Cast<RenderModule>())
{
render_comp->AfterRender();
}
} }
renderer.Present(); renderer.Present();

View File

@ -42,7 +42,8 @@ extern KGE_API int GetVersion();
* \~chinese * \~chinese
* @brief * @brief
*/ */
class KGE_API Application : public Singleton<Application> class KGE_API Application
: public Singleton<Application>
{ {
friend Singleton<Application>; friend Singleton<Application>;
@ -169,7 +170,7 @@ private:
float time_scale_; float time_scale_;
RunnerPtr runner_; RunnerPtr runner_;
TimerPtr timer_; TimerPtr timer_;
List<Module*> modules_; ModuleList modules_;
std::mutex perform_mutex_; std::mutex perform_mutex_;
Queue<Function<void()>> functions_to_perform_; Queue<Function<void()>> functions_to_perform_;
}; };

View File

@ -34,21 +34,6 @@ Input::Input()
Input::~Input() {} Input::~Input() {}
void Input::AfterUpdate()
{
if (want_update_keys_)
{
want_update_keys_ = false;
::memcpy(keys_[Prev].data(), keys_[Current].data(), KEY_NUM * sizeof(bool));
}
if (want_update_buttons_)
{
want_update_buttons_ = false;
buttons_[Prev] = buttons_[Current];
}
}
bool Input::IsDown(KeyCode key) const bool Input::IsDown(KeyCode key) const
{ {
if (key == KeyCode::Unknown || key == KeyCode::Last) if (key == KeyCode::Unknown || key == KeyCode::Last)
@ -129,8 +114,27 @@ void Input::UpdateMousePos(const Point& pos)
mouse_pos_ = pos; mouse_pos_ = pos;
} }
void Input::HandleEvent(Event* evt) void Input::OnUpdate(UpdateModuleContext& ctx)
{ {
ctx.Next();
if (want_update_keys_)
{
want_update_keys_ = false;
::memcpy(keys_[Prev].data(), keys_[Current].data(), KEY_NUM * sizeof(bool));
}
if (want_update_buttons_)
{
want_update_buttons_ = false;
buttons_[Prev] = buttons_[Current];
}
}
void Input::HandleEvent(EventModuleContext& ctx)
{
Event* evt = ctx.evt;
if (evt->IsType<MouseEvent>()) if (evt->IsType<MouseEvent>())
{ {
if (evt->IsType<MouseMoveEvent>()) if (evt->IsType<MouseMoveEvent>())
@ -158,4 +162,5 @@ void Input::HandleEvent(Event* evt)
} }
} }
} }
} // namespace kiwano } // namespace kiwano

View File

@ -33,10 +33,9 @@ namespace kiwano
* \~chinese * \~chinese
* @brief * @brief
*/ */
class KGE_API Input class KGE_API Input final
: public Singleton<Input> : public Singleton<Input>
, public UpdateModule , public Module
, public EventModule
{ {
friend Singleton<Input>; friend Singleton<Input>;
@ -104,13 +103,9 @@ public:
Point GetMousePos() const; Point GetMousePos() const;
public: public:
void SetupModule() override {} void OnUpdate(UpdateModuleContext& ctx) override;
void DestroyModule() override {} void HandleEvent(EventModuleContext& ctx) override;
void AfterUpdate() override;
void HandleEvent(Event* evt) override;
~Input(); ~Input();

View File

@ -28,45 +28,9 @@
namespace kiwano namespace kiwano
{ {
RunnerPtr Runner::Create(Settings settings) Runner::Runner(const Settings& settings)
: settings_(settings)
{ {
RunnerPtr ptr = memory::New<Runner>();
if (ptr)
{
ptr->SetSettings(settings);
}
return ptr;
}
RunnerPtr Runner::Create(Settings settings, Function<void()> on_ready, Function<void()> on_destroy)
{
class CallbackRunner : public Runner
{
public:
void OnReady() override
{
if (on_ready)
on_ready();
}
void OnDestroy() override
{
if (on_destroy)
on_destroy();
}
Function<void()> on_ready;
Function<void()> on_destroy;
};
SmartPtr<CallbackRunner> ptr = memory::New<CallbackRunner>();
if (ptr)
{
ptr->on_ready = on_ready;
ptr->on_destroy = on_destroy;
ptr->SetSettings(settings);
}
return ptr;
} }
Runner::Runner() {} Runner::Runner() {}
@ -91,6 +55,7 @@ void Runner::InitSettings()
Renderer::GetInstance().SetVSyncEnabled(settings_.vsync_enabled); Renderer::GetInstance().SetVSyncEnabled(settings_.vsync_enabled);
// Use defaut modules // Use defaut modules
Application::GetInstance().Use(Renderer::GetInstance());
Application::GetInstance().Use(Input::GetInstance()); Application::GetInstance().Use(Input::GetInstance());
Application::GetInstance().Use(Director::GetInstance()); Application::GetInstance().Use(Director::GetInstance());
@ -104,7 +69,7 @@ void Runner::InitSettings()
// Create frame ticker // Create frame ticker
if (!settings_.frame_interval.IsZero()) if (!settings_.frame_interval.IsZero())
{ {
frame_ticker_ = Ticker::Create(settings_.frame_interval, -1); frame_ticker_ = MakePtr<Ticker>(settings_.frame_interval, -1);
} }
} }

View File

@ -62,20 +62,13 @@ struct Settings
class KGE_API Runner : public ObjectBase class KGE_API Runner : public ObjectBase
{ {
public: public:
/// \~chinese
/// @brief 创建程序运行器
/// @param main_window 主窗口
static RunnerPtr Create(Settings settings);
/// \~chinese
/// @brief 创建程序运行器
/// @param main_window 主窗口
/// @param on_ready 应用程序初始化完成后执行的回调函数
/// @param on_destroy 应用程序销毁时执行的回调函数
static RunnerPtr Create(Settings settings, Function<void()> on_ready, Function<void()> on_destroy = nullptr);
Runner(); Runner();
/// \~chinese
/// @brief 创建程序运行器
/// @param main_window 主窗口
Runner(const Settings& settings);
virtual ~Runner(); virtual ~Runner();
/// \~chinese /// \~chinese
@ -99,16 +92,12 @@ public:
/// @param dt 时间间隔 /// @param dt 时间间隔
/// @details 重载该函数以控制程序主循环 /// @details 重载该函数以控制程序主循环
/// @return 返回false退出主循环否则继续运行主循环 /// @return 返回false退出主循环否则继续运行主循环
virtual bool MainLoop(Duration dt); bool MainLoop(Duration dt);
/// \~chinese /// \~chinese
/// @brief 获取窗口 /// @brief 获取窗口
WindowPtr GetWindow() const; WindowPtr GetWindow() const;
/// \~chinese
/// @brief 设置窗口
void SetWindow(WindowPtr window);
/// \~chinese /// \~chinese
/// @brief 获取设置 /// @brief 获取设置
Settings GetSettings() const; Settings GetSettings() const;
@ -126,6 +115,10 @@ protected:
/// @brief 修改设置 /// @brief 修改设置
void SetSettings(Settings settings); void SetSettings(Settings settings);
/// \~chinese
/// @brief 设置窗口
void SetWindow(WindowPtr window);
private: private:
friend class Application; friend class Application;

View File

@ -21,20 +21,20 @@
#pragma once #pragma once
#include <type_traits> #include <type_traits>
#include <kiwano/core/Common.h> #include <kiwano/core/Common.h>
#include <kiwano/core/SmartPtr.hpp> #include <kiwano/core/RefBasePtr.hpp>
#include <Unknwnbase.h> #include <Unknwnbase.h>
namespace kiwano namespace kiwano
{ {
struct ComPtrProxy struct ComPtrPolicy
{ {
static inline void Retain(IUnknown* ptr) inline void Retain(IUnknown* ptr)
{ {
if (ptr) if (ptr)
ptr->AddRef(); ptr->AddRef();
} }
static inline void Release(IUnknown* ptr) inline void Release(IUnknown* ptr)
{ {
if (ptr) if (ptr)
ptr->Release(); ptr->Release();
@ -43,6 +43,6 @@ struct ComPtrProxy
// ComPtr<> is a smart pointer for COM // ComPtr<> is a smart pointer for COM
template <typename _Ty, typename = typename std::enable_if<std::is_base_of<IUnknown, _Ty>::value, int>::type> template <typename _Ty, typename = typename std::enable_if<std::is_base_of<IUnknown, _Ty>::value, int>::type>
using ComPtr = SmartPtr<_Ty, ComPtrProxy>; using ComPtr = RefBasePtr<_Ty, ComPtrPolicy>;
} // namespace kiwano } // namespace kiwano

View File

@ -25,7 +25,6 @@
#include <memory> #include <memory>
#include <array> #include <array>
#include <kiwano/core/Keys.h> #include <kiwano/core/Keys.h>
#include <kiwano/core/Exception.h>
#include <kiwano/utils/Logger.h> #include <kiwano/utils/Logger.h>
#include <kiwano/event/Events.h> #include <kiwano/event/Events.h>
#include <kiwano/platform/Application.h> #include <kiwano/platform/Application.h>
@ -90,7 +89,7 @@ private:
WindowPtr Window::Create(const WindowConfig& config) WindowPtr Window::Create(const WindowConfig& config)
{ {
WindowWin32ImplPtr ptr = memory::New<WindowWin32Impl>(); WindowWin32ImplPtr ptr = MakePtr<WindowWin32Impl>();
if (ptr) if (ptr)
{ {
ptr->Init(config); ptr->Init(config);

View File

@ -18,7 +18,6 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
#include <kiwano/core/Exception.h>
#include <kiwano/utils/Logger.h> #include <kiwano/utils/Logger.h>
#include <kiwano/platform/win32/libraries.h> #include <kiwano/platform/win32/libraries.h>

View File

@ -59,34 +59,22 @@ RadialGradientStyle::RadialGradientStyle(const Point& center, const Vec2& offset
{ {
} }
BrushPtr Brush::Create(const Color& color) Brush::Brush(const Color& color)
: Brush()
{ {
BrushPtr ptr = memory::New<Brush>(); SetColor(color);
if (ptr)
{
ptr->SetColor(color);
}
return ptr;
} }
BrushPtr Brush::Create(const LinearGradientStyle& style) Brush::Brush(const LinearGradientStyle& style)
: Brush()
{ {
BrushPtr ptr = memory::New<Brush>(); SetStyle(style);
if (ptr)
{
ptr->SetStyle(style);
}
return ptr;
} }
BrushPtr Brush::Create(const RadialGradientStyle& style) Brush::Brush(const RadialGradientStyle& style)
: Brush()
{ {
BrushPtr ptr = memory::New<Brush>(); SetStyle(style);
if (ptr)
{
ptr->SetStyle(style);
}
return ptr;
} }
Brush::Brush() Brush::Brush()

View File

@ -92,17 +92,17 @@ public:
/// \~chinese /// \~chinese
/// @brief 创建纯色画刷 /// @brief 创建纯色画刷
/// @param color 画刷颜色 /// @param color 画刷颜色
static BrushPtr Create(const Color& color); Brush(const Color& color);
/// \~chinese /// \~chinese
/// @brief 创建线性渐变样式 /// @brief 创建线性渐变样式
/// @param style 线性渐变样式 /// @param style 线性渐变样式
static BrushPtr Create(const LinearGradientStyle& style); Brush(const LinearGradientStyle& style);
/// \~chinese /// \~chinese
/// @brief 创建径向渐变样式 /// @brief 创建径向渐变样式
/// @param style 径向渐变样式 /// @param style 径向渐变样式
static BrushPtr Create(const RadialGradientStyle& style); Brush(const RadialGradientStyle& style);
Brush(); Brush();

View File

@ -20,7 +20,6 @@
#pragma once #pragma once
#include <kiwano/core/Common.h> #include <kiwano/core/Common.h>
#include <kiwano/macros.h>
namespace kiwano namespace kiwano
{ {

View File

@ -19,7 +19,6 @@
// THE SOFTWARE. // THE SOFTWARE.
#include <kiwano/render/DirectX/D2DDeviceResources.h> #include <kiwano/render/DirectX/D2DDeviceResources.h>
#include <kiwano/utils/Logger.h>
#pragma comment(lib, "d2d1.lib") #pragma comment(lib, "d2d1.lib")
#pragma comment(lib, "dwrite.lib") #pragma comment(lib, "dwrite.lib")
@ -70,6 +69,12 @@ public:
HRESULT CreateTextLayout(_Out_ ComPtr<IDWriteTextLayout>& text_layout, _In_ LPCWSTR text, UINT32 length, HRESULT CreateTextLayout(_Out_ ComPtr<IDWriteTextLayout>& text_layout, _In_ LPCWSTR text, UINT32 length,
_In_ ComPtr<IDWriteTextFormat> text_format) override; _In_ ComPtr<IDWriteTextFormat> text_format) override;
HRESULT CreateFontCollectionFromFiles(_Out_ ComPtr<IDWriteFontCollection>& font_collection,
const Vector<String>& file_paths) override;
HRESULT CreateFontCollectionFromResources(_Out_ ComPtr<IDWriteFontCollection>& font_collection,
const Vector<Resource>& resources) override;
HRESULT SetDpi(float dpi) override; HRESULT SetDpi(float dpi) override;
HRESULT SetLogicalSize(float width, float height) override; HRESULT SetLogicalSize(float width, float height) override;
@ -93,6 +98,10 @@ private:
float dpi_; float dpi_;
ComPtr<IDXGISwapChain> dxgi_swap_chain_; ComPtr<IDXGISwapChain> dxgi_swap_chain_;
ComPtr<IFontCollectionLoader> font_collection_loader_;
ComPtr<IResourceFontFileLoader> res_font_file_loader_;
ComPtr<IResourceFontCollectionLoader> res_font_collection_loader_;
}; };
@ -173,13 +182,34 @@ STDMETHODIMP D2DDeviceResources::QueryInterface(const IID& riid, void** object)
void D2DDeviceResources::DiscardResources() void D2DDeviceResources::DiscardResources()
{ {
factory_.Reset(); if (dwrite_factory_)
device_.Reset(); {
device_context_.Reset(); if (font_collection_loader_)
target_bitmap_.Reset(); {
dwrite_factory_->UnregisterFontCollectionLoader(font_collection_loader_.Get());
font_collection_loader_.Reset();
}
if (res_font_file_loader_)
{
dwrite_factory_->UnregisterFontFileLoader(res_font_file_loader_.Get());
res_font_file_loader_.Reset();
}
if (res_font_collection_loader_)
{
dwrite_factory_->UnregisterFontCollectionLoader(res_font_collection_loader_.Get());
res_font_collection_loader_.Reset();
}
}
target_bitmap_.Reset();
device_context_.Reset();
device_.Reset();
imaging_factory_.Reset();
dwrite_factory_.Reset(); dwrite_factory_.Reset();
imaging_factory_.Reset();
factory_.Reset();
} }
HRESULT D2DDeviceResources::CreateDeviceIndependentResources() HRESULT D2DDeviceResources::CreateDeviceIndependentResources()
@ -225,6 +255,38 @@ HRESULT D2DDeviceResources::CreateDeviceIndependentResources()
dwrite_factory_ = dwrite_factory; dwrite_factory_ = dwrite_factory;
} }
} }
// FontFileLoader and FontCollectionLoader
if (SUCCEEDED(hr))
{
hr = IFontCollectionLoader::Create(&font_collection_loader_);
if (SUCCEEDED(hr))
{
hr = dwrite_factory->RegisterFontCollectionLoader(font_collection_loader_.Get());
}
}
// ResourceFontFileLoader and ResourceFontCollectionLoader
if (SUCCEEDED(hr))
{
hr = IResourceFontFileLoader::Create(&res_font_file_loader_);
if (SUCCEEDED(hr))
{
hr = dwrite_factory->RegisterFontFileLoader(res_font_file_loader_.Get());
}
if (SUCCEEDED(hr))
{
hr = IResourceFontCollectionLoader::Create(&res_font_collection_loader_, res_font_file_loader_.Get());
if (SUCCEEDED(hr))
{
hr = dwrite_factory->RegisterFontCollectionLoader(res_font_collection_loader_.Get());
}
}
}
return hr; return hr;
} }
@ -450,6 +512,43 @@ HRESULT D2DDeviceResources::CreateTextLayout(_Out_ ComPtr<IDWriteTextLayout>& te
return hr; return hr;
} }
HRESULT D2DDeviceResources::CreateFontCollectionFromFiles(ComPtr<IDWriteFontCollection>& font_collection,
const Vector<String>& file_paths)
{
if (!dwrite_factory_ || !font_collection_loader_)
return E_UNEXPECTED;
LPVOID key = nullptr;
uint32_t key_size = 0;
HRESULT hr = font_collection_loader_->AddFilePaths(file_paths, &key, &key_size);
if (SUCCEEDED(hr))
{
hr =
dwrite_factory_->CreateCustomFontCollection(font_collection_loader_.Get(), key, key_size, &font_collection);
}
return hr;
}
HRESULT D2DDeviceResources::CreateFontCollectionFromResources(ComPtr<IDWriteFontCollection>& font_collection,
const Vector<Resource>& resources)
{
if (!dwrite_factory_ || !res_font_collection_loader_)
return E_UNEXPECTED;
LPVOID key = nullptr;
uint32_t key_size = 0;
HRESULT hr = res_font_collection_loader_->AddResources(resources, &key, &key_size);
if (SUCCEEDED(hr))
{
hr = dwrite_factory_->CreateCustomFontCollection(res_font_collection_loader_.Get(), key, key_size, &font_collection);
}
return hr;
}
} // namespace directx } // namespace directx
} // namespace graphics } // namespace graphics
} // namespace kiwano } // namespace kiwano

View File

@ -20,9 +20,7 @@
#pragma once #pragma once
#include <kiwano/render/DirectX/helper.h> #include <kiwano/render/DirectX/helper.h>
#include <d2d1.h> #include <kiwano/render/DirectX/FontCollectionLoader.h>
#include <d2d1_1.h>
#include <dwrite.h>
namespace kiwano namespace kiwano
{ {
@ -58,6 +56,12 @@ public:
virtual HRESULT CreateTextLayout(_Out_ ComPtr<IDWriteTextLayout> & text_layout, _In_ LPCWSTR text, UINT32 length, virtual HRESULT CreateTextLayout(_Out_ ComPtr<IDWriteTextLayout> & text_layout, _In_ LPCWSTR text, UINT32 length,
_In_ ComPtr<IDWriteTextFormat> text_format) = 0; _In_ ComPtr<IDWriteTextFormat> text_format) = 0;
virtual HRESULT CreateFontCollectionFromFiles(_Out_ ComPtr<IDWriteFontCollection> & font_collection,
const Vector<String>& file_paths) = 0;
virtual HRESULT CreateFontCollectionFromResources(_Out_ ComPtr<IDWriteFontCollection> & font_collection,
const Vector<Resource>& resources) = 0;
virtual HRESULT SetDpi(float dpi) = 0; virtual HRESULT SetDpi(float dpi) = 0;
virtual HRESULT SetLogicalSize(float width, float height) = 0; virtual HRESULT SetLogicalSize(float width, float height) = 0;

View File

@ -20,7 +20,6 @@
#include <kiwano/utils/Logger.h> #include <kiwano/utils/Logger.h>
#include <kiwano/render/DirectX/D3D11DeviceResources.h> #include <kiwano/render/DirectX/D3D11DeviceResources.h>
#include <memory>
KGE_SUPPRESS_WARNING_PUSH KGE_SUPPRESS_WARNING_PUSH
KGE_SUPPRESS_WARNING(4800) // Implicit conversion from 'type' to bool KGE_SUPPRESS_WARNING(4800) // Implicit conversion from 'type' to bool

View File

@ -20,7 +20,8 @@
#pragma once #pragma once
#include <kiwano/core/Resource.h> #include <kiwano/core/Resource.h>
#include <kiwano/render/DirectX/D2DDeviceResources.h> #include <kiwano/render/DirectX/helper.h>
#include <dwrite.h>
namespace kiwano namespace kiwano
{ {

View File

@ -18,16 +18,18 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE. // THE SOFTWARE.
#include <kiwano/core/Exception.h>
#include <kiwano/utils/Logger.h> #include <kiwano/utils/Logger.h>
#include <kiwano/event/WindowEvent.h>
#include <kiwano/platform/FileSystem.h> #include <kiwano/platform/FileSystem.h>
#include <kiwano/platform/Application.h> #include <kiwano/platform/Application.h>
#include <kiwano/render/ShapeMaker.h> #include <kiwano/render/ShapeMaker.h>
#include <kiwano/render/DirectX/RendererImpl.h> #include <kiwano/render/DirectX/RendererImpl.h>
#include <kiwano/render/DirectX/NativePtr.h> #include <kiwano/render/DirectX/NativePtr.h>
#include <memory> #define KGE_SET_STATUS_IF_FAILED(ERRCODE, OBJ, MESSAGE) \
if (FAILED(ERRCODE)) \
{ \
OBJ.Fail(strings::Format("%s failed (%#x): %s", __FUNCTION__, ERRCODE, MESSAGE)); \
}
namespace kiwano namespace kiwano
{ {
@ -93,11 +95,10 @@ void RendererImpl::MakeContextForWindow(WindowPtr window)
} }
} }
// Initialize other device resources // Initialize other device resources
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
{ {
RenderContextImplPtr ctx = memory::New<RenderContextImpl>(); RenderContextImplPtr ctx = MakePtr<RenderContextImpl>();
hr = ctx->CreateDeviceResources(d2d_res_->GetFactory(), d2d_res_->GetDeviceContext()); hr = ctx->CreateDeviceResources(d2d_res_->GetFactory(), d2d_res_->GetDeviceContext());
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
@ -106,38 +107,6 @@ void RendererImpl::MakeContextForWindow(WindowPtr window)
} }
} }
// FontFileLoader and FontCollectionLoader
if (SUCCEEDED(hr))
{
hr = IFontCollectionLoader::Create(&font_collection_loader_);
if (SUCCEEDED(hr))
{
hr = d2d_res_->GetDWriteFactory()->RegisterFontCollectionLoader(font_collection_loader_.Get());
}
}
// ResourceFontFileLoader and ResourceFontCollectionLoader
if (SUCCEEDED(hr))
{
hr = IResourceFontFileLoader::Create(&res_font_file_loader_);
if (SUCCEEDED(hr))
{
hr = d2d_res_->GetDWriteFactory()->RegisterFontFileLoader(res_font_file_loader_.Get());
}
if (SUCCEEDED(hr))
{
hr = IResourceFontCollectionLoader::Create(&res_font_collection_loader_, res_font_file_loader_.Get());
if (SUCCEEDED(hr))
{
hr = d2d_res_->GetDWriteFactory()->RegisterFontCollectionLoader(res_font_collection_loader_.Get());
}
}
}
KGE_THROW_IF_FAILED(hr, "Create render resources failed"); KGE_THROW_IF_FAILED(hr, "Create render resources failed");
} }
@ -147,14 +116,9 @@ void RendererImpl::Destroy()
if (d2d_res_) if (d2d_res_)
{ {
d2d_res_->GetDWriteFactory()->UnregisterFontFileLoader(res_font_file_loader_.Get());
res_font_file_loader_.Reset();
d2d_res_->GetDWriteFactory()->UnregisterFontCollectionLoader(res_font_collection_loader_.Get());
res_font_collection_loader_.Reset();
render_ctx_.Reset(); render_ctx_.Reset();
d2d_res_->DiscardResources(); d2d_res_->DiscardResources();
d2d_res_.Reset();
} }
if (d3d_res_) if (d3d_res_)
@ -194,8 +158,10 @@ void RendererImpl::CreateTexture(Texture& texture, const String& file_path)
if (!FileSystem::GetInstance().IsFileExists(file_path)) if (!FileSystem::GetInstance().IsFileExists(file_path))
{ {
KGE_WARNF("Texture file '%s' not found!", file_path.c_str());
hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND); hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
KGE_SET_STATUS_IF_FAILED(hr, texture,
strings::Format("Texture file '%s' not found!", file_path.c_str()).c_str());
return;
} }
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
@ -234,10 +200,7 @@ void RendererImpl::CreateTexture(Texture& texture, const String& file_path)
} }
} }
if (FAILED(hr)) KGE_SET_STATUS_IF_FAILED(hr, texture, "Load texture failed");
{
KGE_THROW_IF_FAILED(hr, "Load texture failed");
}
} }
void RendererImpl::CreateTexture(Texture& texture, const Resource& resource) void RendererImpl::CreateTexture(Texture& texture, const Resource& resource)
@ -289,10 +252,7 @@ void RendererImpl::CreateTexture(Texture& texture, const Resource& resource)
} }
} }
if (FAILED(hr)) KGE_SET_STATUS_IF_FAILED(hr, texture, "Load texture failed");
{
KGE_WARNF("Load texture failed with HRESULT of %08X!", hr);
}
} }
void RendererImpl::CreateGifImage(GifImage& gif, const String& file_path) void RendererImpl::CreateGifImage(GifImage& gif, const String& file_path)
@ -305,8 +265,10 @@ void RendererImpl::CreateGifImage(GifImage& gif, const String& file_path)
if (!FileSystem::GetInstance().IsFileExists(file_path)) if (!FileSystem::GetInstance().IsFileExists(file_path))
{ {
KGE_WARNF("Gif texture file '%s' not found!", file_path.c_str());
hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND); hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
KGE_SET_STATUS_IF_FAILED(hr, gif,
strings::Format("Gif texture file '%s' not found!", file_path.c_str()).c_str());
return;
} }
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
@ -322,10 +284,7 @@ void RendererImpl::CreateGifImage(GifImage& gif, const String& file_path)
} }
} }
if (FAILED(hr)) KGE_SET_STATUS_IF_FAILED(hr, gif, "Load GIF texture failed");
{
KGE_WARNF("Load GIF texture failed with HRESULT of %08X!", hr);
}
} }
void RendererImpl::CreateGifImage(GifImage& gif, const Resource& resource) void RendererImpl::CreateGifImage(GifImage& gif, const Resource& resource)
@ -354,10 +313,7 @@ void RendererImpl::CreateGifImage(GifImage& gif, const Resource& resource)
} }
} }
if (FAILED(hr)) KGE_SET_STATUS_IF_FAILED(hr, gif, "Load GIF texture failed");
{
KGE_WARNF("Load GIF texture failed with HRESULT of %08X!", hr);
}
} }
void RendererImpl::CreateGifImageFrame(GifImage::Frame& frame, const GifImage& gif, size_t frame_index) void RendererImpl::CreateGifImageFrame(GifImage::Frame& frame, const GifImage& gif, size_t frame_index)
@ -394,7 +350,7 @@ void RendererImpl::CreateGifImageFrame(GifImage::Frame& frame, const GifImage& g
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
{ {
frame.texture = memory::New<Texture>(); frame.texture = MakePtr<Texture>();
NativePtr::Set(frame.texture, bitmap); NativePtr::Set(frame.texture, bitmap);
frame.texture->SetSize({ bitmap->GetSize().width, bitmap->GetSize().height }); frame.texture->SetSize({ bitmap->GetSize().width, bitmap->GetSize().height });
@ -518,10 +474,7 @@ void RendererImpl::CreateGifImageFrame(GifImage::Frame& frame, const GifImage& g
} }
} }
if (FAILED(hr)) KGE_SET_STATUS_IF_FAILED(hr, const_cast<GifImage&>(gif), "Load GIF frame failed");
{
KGE_WARNF("Load GIF frame failed with HRESULT of %08X!", hr);
}
} }
void RendererImpl::CreateFontCollection(Font& font, const String& file_path) void RendererImpl::CreateFontCollection(Font& font, const String& file_path)
@ -536,33 +489,26 @@ void RendererImpl::CreateFontCollection(Font& font, const String& file_path)
{ {
if (!FileSystem::GetInstance().IsFileExists(file_path)) if (!FileSystem::GetInstance().IsFileExists(file_path))
{ {
KGE_WARNF("Font file '%s' not found!", file_path.c_str());
hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND); hr = HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND);
KGE_SET_STATUS_IF_FAILED(hr, font, strings::Format("Font file '%s' not found!", file_path.c_str()).c_str());
return;
} }
} }
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
{ {
LPVOID key = nullptr; String full_path = FileSystem::GetInstance().GetFullPathForFile(file_path);
uint32_t key_size = 0;
String full_path = FileSystem::GetInstance().GetFullPathForFile(file_path);
hr = font_collection_loader_->AddFilePaths({ full_path }, &key, &key_size); ComPtr<IDWriteFontCollection> font_collection;
hr = d2d_res_->CreateFontCollectionFromFiles(font_collection, { full_path });
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
{ {
ComPtr<IDWriteFontCollection> font_collection; NativePtr::Set(font, font_collection);
hr = d2d_res_->GetDWriteFactory()->CreateCustomFontCollection(font_collection_loader_.Get(), key, key_size,
&font_collection);
if (SUCCEEDED(hr))
{
NativePtr::Set(font, font_collection);
}
} }
} }
KGE_THROW_IF_FAILED(hr, "Create font collection failed"); KGE_SET_STATUS_IF_FAILED(hr, font, "Create font collection failed");
} }
void RendererImpl::CreateFontCollection(Font& font, const Resource& res) void RendererImpl::CreateFontCollection(Font& font, const Resource& res)
@ -575,25 +521,16 @@ void RendererImpl::CreateFontCollection(Font& font, const Resource& res)
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
{ {
LPVOID key = nullptr; ComPtr<IDWriteFontCollection> font_collection;
uint32_t key_size = 0; hr = d2d_res_->CreateFontCollectionFromResources(font_collection, Vector<Resource>{ res });
hr = res_font_collection_loader_->AddResources(Vector<Resource>{ res }, &key, &key_size);
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
{ {
ComPtr<IDWriteFontCollection> font_collection; NativePtr::Set(font, font_collection);
hr = d2d_res_->GetDWriteFactory()->CreateCustomFontCollection(res_font_collection_loader_.Get(), key,
key_size, &font_collection);
if (SUCCEEDED(hr))
{
NativePtr::Set(font, font_collection);
}
} }
} }
KGE_THROW_IF_FAILED(hr, "Create font collection failed"); KGE_SET_STATUS_IF_FAILED(hr, font, "Create font collection failed");
} }
void RendererImpl::CreateTextLayout(TextLayout& layout, const String& content, const TextStyle& style) void RendererImpl::CreateTextLayout(TextLayout& layout, const String& content, const TextStyle& style)
@ -637,7 +574,7 @@ void RendererImpl::CreateTextLayout(TextLayout& layout, const String& content, c
} }
} }
KGE_THROW_IF_FAILED(hr, "Create text layout failed"); KGE_SET_STATUS_IF_FAILED(hr, layout, "Create text layout failed");
} }
void RendererImpl::CreateLineShape(Shape& shape, const Point& begin_pos, const Point& end_pos) void RendererImpl::CreateLineShape(Shape& shape, const Point& begin_pos, const Point& end_pos)
@ -673,7 +610,7 @@ void RendererImpl::CreateLineShape(Shape& shape, const Point& begin_pos, const P
} }
} }
KGE_THROW_IF_FAILED(hr, "Create ID2D1PathGeometry failed"); KGE_SET_STATUS_IF_FAILED(hr, shape, "Create ID2D1PathGeometry failed");
} }
void RendererImpl::CreateRectShape(Shape& shape, const Rect& rect) void RendererImpl::CreateRectShape(Shape& shape, const Rect& rect)
@ -695,7 +632,7 @@ void RendererImpl::CreateRectShape(Shape& shape, const Rect& rect)
NativePtr::Set(shape, output); NativePtr::Set(shape, output);
} }
KGE_THROW_IF_FAILED(hr, "Create ID2D1RectangleGeometry failed"); KGE_SET_STATUS_IF_FAILED(hr, shape, "Create ID2D1RectangleGeometry failed");
} }
void RendererImpl::CreateRoundedRectShape(Shape& shape, const Rect& rect, const Vec2& radius) void RendererImpl::CreateRoundedRectShape(Shape& shape, const Rect& rect, const Vec2& radius)
@ -718,7 +655,7 @@ void RendererImpl::CreateRoundedRectShape(Shape& shape, const Rect& rect, const
NativePtr::Set(shape, output); NativePtr::Set(shape, output);
} }
KGE_THROW_IF_FAILED(hr, "Create ID2D1RoundedRectangleGeometry failed"); KGE_SET_STATUS_IF_FAILED(hr, shape, "Create ID2D1RoundedRectangleGeometry failed");
} }
void RendererImpl::CreateEllipseShape(Shape& shape, const Point& center, const Vec2& radius) void RendererImpl::CreateEllipseShape(Shape& shape, const Point& center, const Vec2& radius)
@ -741,7 +678,7 @@ void RendererImpl::CreateEllipseShape(Shape& shape, const Point& center, const V
NativePtr::Set(shape, output); NativePtr::Set(shape, output);
} }
KGE_THROW_IF_FAILED(hr, "Create ID2D1EllipseGeometry failed"); KGE_SET_STATUS_IF_FAILED(hr, shape, "Create ID2D1EllipseGeometry failed");
} }
void RendererImpl::CreateShapeSink(ShapeMaker& maker) void RendererImpl::CreateShapeSink(ShapeMaker& maker)
@ -760,13 +697,13 @@ void RendererImpl::CreateShapeSink(ShapeMaker& maker)
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
{ {
ShapePtr shape = memory::New<Shape>(); ShapePtr shape = MakePtr<Shape>();
NativePtr::Set(shape, geometry); NativePtr::Set(shape, geometry);
maker.SetShape(shape); maker.SetShape(shape);
} }
} }
KGE_THROW_IF_FAILED(hr, "Create ID2D1PathGeometry failed"); KGE_SET_STATUS_IF_FAILED(hr, maker, "Create ID2D1PathGeometry failed");
} }
void RendererImpl::CreateBrush(Brush& brush, const Color& color) void RendererImpl::CreateBrush(Brush& brush, const Color& color)
@ -800,7 +737,7 @@ void RendererImpl::CreateBrush(Brush& brush, const Color& color)
} }
} }
KGE_THROW_IF_FAILED(hr, "Create ID2D1SolidBrush failed"); KGE_SET_STATUS_IF_FAILED(hr, brush, "Create ID2D1SolidBrush failed");
} }
void RendererImpl::CreateBrush(Brush& brush, const LinearGradientStyle& style) void RendererImpl::CreateBrush(Brush& brush, const LinearGradientStyle& style)
@ -832,7 +769,7 @@ void RendererImpl::CreateBrush(Brush& brush, const LinearGradientStyle& style)
} }
} }
KGE_THROW_IF_FAILED(hr, "Create ID2D1LinearGradientBrush failed"); KGE_SET_STATUS_IF_FAILED(hr, brush, "Create ID2D1LinearGradientBrush failed");
} }
void RendererImpl::CreateBrush(Brush& brush, const RadialGradientStyle& style) void RendererImpl::CreateBrush(Brush& brush, const RadialGradientStyle& style)
@ -865,7 +802,7 @@ void RendererImpl::CreateBrush(Brush& brush, const RadialGradientStyle& style)
} }
} }
KGE_THROW_IF_FAILED(hr, "Create ID2D1RadialGradientBrush failed"); KGE_SET_STATUS_IF_FAILED(hr, brush, "Create ID2D1RadialGradientBrush failed");
} }
void RendererImpl::CreateBrush(Brush& brush, TexturePtr texture) void RendererImpl::CreateBrush(Brush& brush, TexturePtr texture)
@ -892,7 +829,7 @@ void RendererImpl::CreateBrush(Brush& brush, TexturePtr texture)
} }
} }
KGE_THROW_IF_FAILED(hr, "Create ID2D1RadialGradientBrush failed"); KGE_SET_STATUS_IF_FAILED(hr, brush, "Create ID2D1RadialGradientBrush failed");
} }
void RendererImpl::CreateStrokeStyle(StrokeStyle& stroke_style) void RendererImpl::CreateStrokeStyle(StrokeStyle& stroke_style)
@ -931,12 +868,12 @@ void RendererImpl::CreateStrokeStyle(StrokeStyle& stroke_style)
} }
} }
KGE_THROW_IF_FAILED(hr, "Create ID2D1StrokeStyle failed"); KGE_SET_STATUS_IF_FAILED(hr, stroke_style, "Create ID2D1StrokeStyle failed");
} }
RenderContextPtr RendererImpl::CreateTextureRenderContext(Texture& texture, const Size* desired_size) RenderContextPtr RendererImpl::CreateTextureRenderContext(Texture& texture, const Size* desired_size)
{ {
RenderContextImplPtr ptr = memory::New<RenderContextImpl>(); RenderContextImplPtr ptr = MakePtr<RenderContextImpl>();
HRESULT hr = S_OK; HRESULT hr = S_OK;
if (!d2d_res_) if (!d2d_res_)

View File

@ -21,10 +21,8 @@
#pragma once #pragma once
#include <kiwano/render/Renderer.h> #include <kiwano/render/Renderer.h>
#include <kiwano/render/DirectX/D3DDeviceResources.h> #include <kiwano/render/DirectX/D3DDeviceResources.h>
#include <kiwano/render/DirectX/FontCollectionLoader.h>
#include <kiwano/render/DirectX/RenderContextImpl.h> #include <kiwano/render/DirectX/RenderContextImpl.h>
namespace kiwano namespace kiwano
{ {
@ -92,9 +90,6 @@ private:
ComPtr<ID2DDeviceResources> d2d_res_; ComPtr<ID2DDeviceResources> d2d_res_;
ComPtr<ID3DDeviceResources> d3d_res_; ComPtr<ID3DDeviceResources> d3d_res_;
ComPtr<IFontCollectionLoader> font_collection_loader_;
ComPtr<IResourceFontFileLoader> res_font_file_loader_;
ComPtr<IResourceFontCollectionLoader> res_font_collection_loader_;
}; };

View File

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

View File

@ -20,10 +20,11 @@
#pragma once #pragma once
#include <kiwano/math/Math.h> #include <kiwano/math/Math.h>
#include <kiwano/core/Exception.h> #include <kiwano/utils/Logger.h>
#include <kiwano/render/Color.h> #include <kiwano/render/Color.h>
#include <kiwano/platform/win32/ComPtr.hpp> #include <kiwano/platform/win32/ComPtr.hpp>
#include <d2d1.h> #include <d2d1.h>
#include <d2d1_1.h>
namespace kiwano namespace kiwano
{ {

View File

@ -24,26 +24,14 @@
namespace kiwano namespace kiwano
{ {
FontPtr Font::Create(const String& file) Font::Font(const String& file)
{ {
FontPtr ptr = memory::New<Font>(); Load(file);
if (ptr)
{
if (!ptr->Load(file))
return nullptr;
}
return ptr;
} }
FontPtr Font::Create(const Resource& resource) Font::Font(const Resource& resource)
{ {
FontPtr ptr = memory::New<Font>(); Load(resource);
if (ptr)
{
if (!ptr->Load(resource))
return nullptr;
}
return ptr;
} }
Font::Font() {} Font::Font() {}

View File

@ -44,11 +44,11 @@ class Font : public NativeObject
public: public:
/// \~chinese /// \~chinese
/// @brief ´´½¨×ÖÌå /// @brief ´´½¨×ÖÌå
static FontPtr Create(const String& file); Font(const String& file);
/// \~chinese /// \~chinese
/// @brief ´´½¨×ÖÌå /// @brief ´´½¨×ÖÌå
static FontPtr Create(const Resource& resource); Font(const Resource& resource);
Font(); Font();

View File

@ -24,36 +24,19 @@
namespace kiwano namespace kiwano
{ {
FramePtr Frame::Create(const String& file_path) Frame::Frame(const String& file_path)
{ {
FramePtr ptr = memory::New<Frame>(); Load(file_path);
if (ptr)
{
if (!ptr->Load(file_path))
return nullptr;
}
return ptr;
} }
FramePtr Frame::Create(const Resource& res) Frame::Frame(const Resource& res)
{ {
FramePtr ptr = memory::New<Frame>(); Load(res);
if (ptr)
{
if (!ptr->Load(res))
return nullptr;
}
return ptr;
} }
FramePtr Frame::Create(TexturePtr texture) Frame::Frame(TexturePtr texture)
{ {
FramePtr ptr = memory::New<Frame>(); SetTexture(texture);
if (ptr)
{
ptr->SetTexture(texture);
}
return ptr;
} }
Frame::Frame() {} Frame::Frame() {}

Some files were not shown because too many files have changed in this diff Show More