minor

refactoring: Resource
This commit is contained in:
Nomango 2019-01-21 21:24:45 +08:00 committed by Nomango
parent ecc0e9cf25
commit 4a71273b35
56 changed files with 430 additions and 635 deletions

View File

@ -125,7 +125,7 @@ namespace easy2d
{ {
} }
Sequence::Sequence(const Actions& actions) Sequence::Sequence(Array<SpAction> const& actions)
: action_index_(0) : action_index_(0)
{ {
this->Add(actions); this->Add(actions);
@ -180,7 +180,7 @@ namespace easy2d
} }
} }
void Sequence::Add(const Actions& actions) void Sequence::Add(Array<SpAction> const& actions)
{ {
for (const auto &action : actions) for (const auto &action : actions)
{ {
@ -227,7 +227,7 @@ namespace easy2d
{ {
} }
Spawn::Spawn(const Actions& actions) Spawn::Spawn(Array<SpAction> const& actions)
{ {
this->Add(actions); this->Add(actions);
} }
@ -289,7 +289,7 @@ namespace easy2d
} }
} }
void Spawn::Add(const Actions& actions) void Spawn::Add(Array<SpAction> const& actions)
{ {
for (const auto &action : actions) for (const auto &action : actions)
{ {

View File

@ -64,13 +64,11 @@ namespace easy2d
class Sequence class Sequence
: public Action : public Action
{ {
using Actions = std::vector<SpAction>;
public: public:
Sequence(); Sequence();
explicit Sequence( explicit Sequence(
Actions const& actions /* 动作列表 */ Array<SpAction> const& actions /* 动作列表 */
); );
virtual ~Sequence(); virtual ~Sequence();
@ -82,7 +80,7 @@ namespace easy2d
// 在结尾添加多个动作 // 在结尾添加多个动作
void Add( void Add(
const Actions& actions /* 动作列表 */ Array<SpAction> const& actions /* 动作列表 */
); );
// 获取该动作的拷贝对象 // 获取该动作的拷贝对象
@ -103,7 +101,7 @@ namespace easy2d
protected: protected:
UINT action_index_; UINT action_index_;
Actions actions_; Array<SpAction> actions_;
}; };
@ -111,13 +109,11 @@ namespace easy2d
class Spawn class Spawn
: public Action : public Action
{ {
using Actions = std::vector<SpAction>;
public: public:
Spawn(); Spawn();
explicit Spawn( explicit Spawn(
const Actions& actions /* 动作列表 */ Array<SpAction> const& actions /* 动作列表 */
); );
virtual ~Spawn(); virtual ~Spawn();
@ -129,7 +125,7 @@ namespace easy2d
// 在结尾添加多个动作 // 在结尾添加多个动作
void Add( void Add(
const Actions& actions /* 动作列表 */ Array<SpAction> const& actions /* 动作列表 */
); );
// 获取该动作的拷贝对象 // 获取该动作的拷贝对象
@ -149,6 +145,6 @@ namespace easy2d
virtual void Update(Node* target, Duration const& dt) override; virtual void Update(Node* target, Duration const& dt) override;
protected: protected:
Actions actions_; Array<SpAction> actions_;
}; };
} }

View File

@ -262,7 +262,7 @@ namespace easy2d
} }
} }
void Canvas::DrawText(std::wstring const & text, Point const & point) void Canvas::DrawText(String const & text, Point const & point)
{ {
if (text.empty()) if (text.empty())
return; return;
@ -416,14 +416,14 @@ namespace easy2d
current_sink_->AddLine(point); current_sink_->AddLine(point);
} }
void Canvas::AddLines(std::vector<Point> const& points) void Canvas::AddLines(Array<Point> const& points)
{ {
if (current_sink_) if (current_sink_)
{ {
if (!points.empty()) if (!points.empty())
{ {
size_t size = points.size(); size_t size = points.size();
std::vector<D2D1_POINT_2F> d2d_points(size); Array<D2D1_POINT_2F> d2d_points(size);
for (size_t i = 0; i < size; ++i) for (size_t i = 0; i < size; ++i)
{ {
d2d_points[i] = points[i]; d2d_points[i] = points[i];

View File

@ -91,7 +91,7 @@ namespace easy2d
// 画文字 // 画文字
void DrawText( void DrawText(
std::wstring const& text, /* 文字 */ String const& text, /* 文字 */
Point const& point /* 文字位置 */ Point const& point /* 文字位置 */
); );
@ -147,7 +147,7 @@ namespace easy2d
// 添加多条线段 // 添加多条线段
void AddLines( void AddLines(
std::vector<Point> const& points Array<Point> const& points
); );
// 添加一条三次方贝塞尔曲线 // 添加一条三次方贝塞尔曲线

View File

@ -50,7 +50,7 @@ namespace easy2d
{ {
} }
void DebugNodeImpl::AddDebugText(std::wstring const & text) void DebugNodeImpl::AddDebugText(String const & text)
{ {
try try
{ {

View File

@ -35,7 +35,7 @@ namespace easy2d
virtual ~DebugNodeImpl(); virtual ~DebugNodeImpl();
void AddDebugText(std::wstring const& text); void AddDebugText(String const& text);
void ClearDebugText(); void ClearDebugText();
@ -44,9 +44,9 @@ namespace easy2d
void OnUpdate(Duration const& dt) override; void OnUpdate(Duration const& dt) override;
protected: protected:
SpText debug_text_; SpText debug_text_;
std::vector<TimePoint> frame_time_; Array<TimePoint> frame_time_;
std::vector<std::wstring> texts_; Array<String> texts_;
}; };
E2D_DECLARE_SINGLETON_TYPE(DebugNodeImpl, DebugNode); E2D_DECLARE_SINGLETON_TYPE(DebugNodeImpl, DebugNode);

View File

@ -50,7 +50,7 @@ namespace easy2d
} }
} }
void EventDispatcher::AddListener(EventType type, EventCallback callback, std::wstring const& name) void EventDispatcher::AddListener(EventType type, EventCallback callback, String const& name)
{ {
SpEventListener listener = new EventListener(type, callback, name); SpEventListener listener = new EventListener(type, callback, name);
if (listener) if (listener)
@ -59,7 +59,7 @@ namespace easy2d
} }
} }
void EventDispatcher::StartListeners(std::wstring const & listener_name) void EventDispatcher::StartListeners(String const & listener_name)
{ {
for (auto listener = listeners_.First(); listener; listener = listener->NextItem()) for (auto listener = listeners_.First(); listener; listener = listener->NextItem())
{ {
@ -70,7 +70,7 @@ namespace easy2d
} }
} }
void EventDispatcher::StopListeners(std::wstring const & listener_name) void EventDispatcher::StopListeners(String const & listener_name)
{ {
for (auto listener = listeners_.First(); listener; listener = listener->NextItem()) for (auto listener = listeners_.First(); listener; listener = listener->NextItem())
{ {
@ -81,7 +81,7 @@ namespace easy2d
} }
} }
void EventDispatcher::RemoveListeners(std::wstring const & listener_name) void EventDispatcher::RemoveListeners(String const & listener_name)
{ {
SpEventListener next; SpEventListener next;
for (auto listener = listeners_.First(); listener; listener = next) for (auto listener = listeners_.First(); listener; listener = next)

View File

@ -37,22 +37,22 @@ namespace easy2d
void AddListener( void AddListener(
EventType type, EventType type,
EventCallback callback, EventCallback callback,
std::wstring const& name = L"" String const& name = L""
); );
// 启动监听器 // 启动监听器
void StartListeners( void StartListeners(
std::wstring const& listener_name String const& listener_name
); );
// 停止监听器 // 停止监听器
void StopListeners( void StopListeners(
std::wstring const& listener_name String const& listener_name
); );
// 移除监听器 // 移除监听器
void RemoveListeners( void RemoveListeners(
std::wstring const& listener_name String const& listener_name
); );
// 启动监听器 // 启动监听器

View File

@ -23,7 +23,7 @@
namespace easy2d namespace easy2d
{ {
EventListener::EventListener(EventType type, EventCallback const & callback, std::wstring const & name) EventListener::EventListener(EventType type, EventCallback const & callback, String const & name)
: type_(type) : type_(type)
, callback_(callback) , callback_(callback)
, name_(name) , name_(name)
@ -50,12 +50,12 @@ namespace easy2d
return running_; return running_;
} }
std::wstring const & EventListener::GetName() const String const & EventListener::GetName() const
{ {
return name_; return name_;
} }
void EventListener::SetName(std::wstring const & name) void EventListener::SetName(String const & name)
{ {
name_ = name; name_ = name;
} }

View File

@ -41,7 +41,7 @@ namespace easy2d
EventListener( EventListener(
EventType type, EventType type,
EventCallback const& callback, EventCallback const& callback,
std::wstring const& name = L"" String const& name = L""
); );
virtual ~EventListener(); virtual ~EventListener();
@ -50,15 +50,15 @@ namespace easy2d
void Stop(); void Stop();
void SetName(std::wstring const& name); void SetName(String const& name);
bool IsRunning() const; bool IsRunning() const;
std::wstring const& GetName() const; String const& GetName() const;
protected: protected:
bool running_; bool running_;
std::wstring name_; String name_;
EventType type_; EventType type_;
EventCallback callback_; EventCallback callback_;
}; };

View File

@ -150,7 +150,7 @@ namespace easy2d
return hr; return hr;
} }
HRESULT FactoryImpl::CreateBitmapFromFile(CpBitmap & bitmap, CpRenderTarget const & rt, std::wstring const & file_path) HRESULT FactoryImpl::CreateBitmapFromFile(CpBitmap & bitmap, CpRenderTarget const & rt, String const & file_path)
{ {
if (imaging_factory_ == nullptr) if (imaging_factory_ == nullptr)
{ {
@ -227,8 +227,9 @@ namespace easy2d
SmartPointer<ID2D1Bitmap> bitmap_tmp; SmartPointer<ID2D1Bitmap> bitmap_tmp;
// ¼ÓÔØ×ÊÔ´ // ¼ÓÔØ×ÊÔ´
ResourceData buffer; LPVOID buffer;
HRESULT hr = res.Load(&buffer) ? S_OK : E_FAIL; DWORD buffer_size;
HRESULT hr = res.Load(buffer, buffer_size) ? S_OK : E_FAIL;
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
{ {
@ -238,8 +239,8 @@ namespace easy2d
if (SUCCEEDED(hr)) if (SUCCEEDED(hr))
{ {
hr = stream->InitializeFromMemory( hr = stream->InitializeFromMemory(
static_cast<WICInProcPointer>(buffer.buffer), static_cast<WICInProcPointer>(buffer),
buffer.buffer_size buffer_size
); );
} }
@ -418,7 +419,7 @@ namespace easy2d
return hr; return hr;
} }
HRESULT FactoryImpl::CreateTextLayout(CpTextLayout & text_layout, Size& layout_size, std::wstring const & text, CpTextFormat const& text_format, TextStyle const & text_style) const HRESULT FactoryImpl::CreateTextLayout(CpTextLayout & text_layout, Size& layout_size, String const & text, CpTextFormat const& text_format, TextStyle const & text_style) const
{ {
if (!write_factory_) if (!write_factory_)
return E_UNEXPECTED; return E_UNEXPECTED;

View File

@ -52,7 +52,7 @@ namespace easy2d
HRESULT CreateBitmapFromFile( HRESULT CreateBitmapFromFile(
CpBitmap& bitmap, CpBitmap& bitmap,
CpRenderTarget const& rt, CpRenderTarget const& rt,
std::wstring const& file_path String const& file_path
); );
HRESULT CreateBitmapFromResource( HRESULT CreateBitmapFromResource(
@ -99,7 +99,7 @@ namespace easy2d
HRESULT CreateTextLayout( HRESULT CreateTextLayout(
CpTextLayout& text_layout, CpTextLayout& text_layout,
Size& layout_size, Size& layout_size,
std::wstring const& text, String const& text,
CpTextFormat const& text_format, CpTextFormat const& text_format,
TextStyle const& text_style TextStyle const& text_style
) const; ) const;

View File

@ -41,17 +41,17 @@ namespace easy2d
class Font class Font
{ {
public: public:
std::wstring family; // ×ÖÌå×å String family; // ×ÖÌå×å
float size; // 字号 float size; // 字号
unsigned int weight; // 粗细值 unsigned int weight; // 粗细值
bool italic; // 是否斜体 bool italic; // 是否斜体
public: public:
Font( Font(
const std::wstring& family = L"", const String& family = L"",
float size = 22, float size = 22,
unsigned int weight = FontWeight::Normal, unsigned int weight = FontWeight::Normal,
bool italic = false bool italic = false
) )
: family(family) : family(family)
, size(size) , size(size)

View File

@ -29,7 +29,7 @@ namespace easy2d
{ {
} }
Frames::Frames(Images const& frames) Frames::Frames(Array<SpImage> const& frames)
: interval_(1) : interval_(1)
{ {
this->Add(frames); this->Add(frames);
@ -40,7 +40,7 @@ namespace easy2d
{ {
} }
Frames::Frames(Duration const& interval, Images const& frames) Frames::Frames(Duration const& interval, Array<SpImage> const& frames)
: interval_(interval) : interval_(interval)
{ {
this->Add(frames); this->Add(frames);
@ -65,7 +65,7 @@ namespace easy2d
} }
} }
void Frames::Add(Images const& frames) void Frames::Add(Array<SpImage> const& frames)
{ {
for (const auto &image : frames) for (const auto &image : frames)
{ {
@ -78,7 +78,7 @@ namespace easy2d
return interval_; return interval_;
} }
Frames::Images const& Frames::GetFrames() const Array<SpImage> const& Frames::GetFrames() const
{ {
return frames_; return frames_;
} }

View File

@ -28,22 +28,20 @@ namespace easy2d
class Frames class Frames
: public Object : public Object
{ {
using Images = std::vector< SpImage >;
public: public:
Frames(); Frames();
explicit Frames( explicit Frames(
Images const& frames /* 关键帧数组 */ Array<SpImage> const& frames /* 关键帧数组 */
); );
explicit Frames( explicit Frames(
Duration const& interval /* 帧间隔 */ Duration const& interval /* 帧间隔 */
); );
explicit Frames( explicit Frames(
Duration const& interval, /* 帧间隔 */ Duration const& interval, /* 帧间隔 */
Images const& frames /* 关键帧数组 */ Array<SpImage> const& frames /* 关键帧数组 */
); );
virtual ~Frames(); virtual ~Frames();
@ -55,14 +53,14 @@ namespace easy2d
// 添加多个关键帧 // 添加多个关键帧
void Add( void Add(
Images const& frames Array<SpImage> const& frames
); );
// 获取帧间隔 // 获取帧间隔
Duration const& GetInterval() const; Duration const& GetInterval() const;
// 获取关键帧 // 获取关键帧
Images const& GetFrames() const; Array<SpImage> const& GetFrames() const;
// 设置每一帧的时间间隔 // 设置每一帧的时间间隔
void SetInterval( void SetInterval(
@ -76,7 +74,7 @@ namespace easy2d
SpFrames Reverse() const; SpFrames Reverse() const;
protected: protected:
Duration interval_; Duration interval_;
Images frames_; Array<SpImage> frames_;
}; };
} }

View File

@ -27,7 +27,6 @@
#include "Transition.h" #include "Transition.h"
#include "KeyEvent.hpp" #include "KeyEvent.hpp"
#include "MouseEvent.hpp" #include "MouseEvent.hpp"
#include "../math/Matrix.hpp"
#include <windowsx.h> #include <windowsx.h>
#include <imm.h> #include <imm.h>
@ -258,10 +257,22 @@ namespace easy2d
::InvalidateRect(hwnd, NULL, FALSE); ::InvalidateRect(hwnd, NULL, FALSE);
} }
bool Game::HandleMessage(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) void Game::Dispatch(Event * event)
{ {
bool unhandled = false; if (transition_)
return;
if (curr_scene_)
curr_scene_->DispatchEvent(event);
}
LRESULT CALLBACK Game::WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
Game * game = reinterpret_cast<Game*>(::GetWindowLongW(hwnd, GWLP_USERDATA));
if (!game)
return ::DefWindowProcW(hwnd, msg, wparam, lparam);
switch (msg) switch (msg)
{ {
case WM_PAINT: case WM_PAINT:
@ -269,10 +280,12 @@ namespace easy2d
PAINTSTRUCT ps; PAINTSTRUCT ps;
::BeginPaint(hwnd, &ps); ::BeginPaint(hwnd, &ps);
Update(); game->Update();
Render(hwnd); game->Render(hwnd);
::EndPaint(hwnd, &ps); ::EndPaint(hwnd, &ps);
return 0;
} }
break; break;
@ -310,7 +323,7 @@ namespace easy2d
if (wparam & MK_LBUTTON || wparam & MK_RBUTTON) if (wparam & MK_LBUTTON || wparam & MK_RBUTTON)
event.button_down = true; event.button_down = true;
Dispatch(&event); game->Dispatch(&event);
} }
break; break;
@ -318,13 +331,14 @@ namespace easy2d
case WM_KEYUP: case WM_KEYUP:
{ {
KeyEvent event(msg, KeyCode(wparam)); KeyEvent event(msg, KeyCode(wparam));
Dispatch(&event); game->Dispatch(&event);
} }
break; break;
case WM_DISPLAYCHANGE: case WM_DISPLAYCHANGE:
{ {
E2D_LOG("The display resolution has changed"); E2D_LOG("The display resolution has changed");
::InvalidateRect(hwnd, nullptr, FALSE); ::InvalidateRect(hwnd, nullptr, FALSE);
} }
break; break;
@ -334,12 +348,13 @@ namespace easy2d
E2D_LOG("Received a message to close the window"); E2D_LOG("Received a message to close the window");
SysEvent event(SysEvent::WindowClose); SysEvent event(SysEvent::WindowClose);
Dispatch(&event); game->Dispatch(&event);
if (OnClose()) if (game->OnClose())
{ {
::DestroyWindow(hwnd); ::DestroyWindow(hwnd);
} }
return 0;
} }
break; break;
@ -347,8 +362,9 @@ namespace easy2d
{ {
E2D_LOG("Window was destroyed"); E2D_LOG("Window was destroyed");
OnExit(); game->OnExit();
::PostQuitMessage(0); ::PostQuitMessage(0);
return 0;
} }
break; break;
@ -356,13 +372,13 @@ namespace easy2d
{ {
if (SIZE_MAXHIDE == wparam || SIZE_MINIMIZED == wparam) if (SIZE_MAXHIDE == wparam || SIZE_MINIMIZED == wparam)
{ {
active_ = false; game->active_ = false;
E2D_LOG("Window minimized"); E2D_LOG("Window minimized");
} }
else if (SIZE_RESTORED == wparam) else if (SIZE_RESTORED == wparam)
{ {
active_ = true; game->active_ = true;
::InvalidateRect(hwnd, nullptr, FALSE); ::InvalidateRect(hwnd, nullptr, FALSE);
E2D_LOG("Window restored"); E2D_LOG("Window restored");
@ -376,69 +392,41 @@ namespace easy2d
// 错误,因为这个错误将在下一次调用 EndDraw 时产生 // 错误,因为这个错误将在下一次调用 EndDraw 时产生
Graphics::Instance()->Resize(width, height); Graphics::Instance()->Resize(width, height);
} }
unhandled = true;
break; break;
case WM_ACTIVATE: case WM_ACTIVATE:
{ {
if (WA_INACTIVE == wparam) bool active = (LOWORD(wparam) != WA_INACTIVE);
{ if (active)
E2D_LOG("Window deactivated");
SysEvent event(SysEvent::WindowDeavtivate);
Dispatch(&event);
}
else
{ {
E2D_LOG("Window activated"); E2D_LOG("Window activated");
SysEvent event(SysEvent::WindowActivate); SysEvent event(SysEvent::WindowActivate);
Dispatch(&event); game->Dispatch(&event);
}
else
{
E2D_LOG("Window deactivated");
SysEvent event(SysEvent::WindowDeavtivate);
game->Dispatch(&event);
} }
} }
unhandled = true;
break; break;
case WM_SETTEXT: case WM_SETTEXT:
{ {
E2D_LOG("Window title changed"); E2D_LOG("Window title changed");
} }
unhandled = true;
break; break;
case WM_SETICON: case WM_SETICON:
{ {
E2D_LOG("Window icon changed"); E2D_LOG("Window icon changed");
} }
unhandled = true;
break; break;
default:
unhandled = true;
break;
} }
return !unhandled;
}
void Game::Dispatch(Event * event)
{
if (transition_)
return;
if (curr_scene_)
curr_scene_->DispatchEvent(event);
}
LRESULT CALLBACK Game::WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam)
{
Game * game = reinterpret_cast<Game*>(
static_cast<LONG_PTR>(::GetWindowLongW(hwnd, GWLP_USERDATA))
);
if (game && game->HandleMessage(hwnd, msg, wparam, lparam))
return 0;
return ::DefWindowProcW(hwnd, msg, wparam, lparam); return ::DefWindowProcW(hwnd, msg, wparam, lparam);
} }
} }

View File

@ -31,12 +31,12 @@ namespace easy2d
{ {
struct Options struct Options
{ {
std::wstring title; // 标题 String title; // 标题
int width; // 宽度 int width; // 宽度
int height; // 高度 int height; // 高度
LPCWSTR icon; // 图标 LPCWSTR icon; // 图标
bool vsync; // 垂直同步 bool vsync; // 垂直同步
bool debug; // 调试模式 bool debug; // 调试模式
Options() Options()
: title(L"Easy2D Game") : title(L"Easy2D Game")
@ -100,13 +100,6 @@ namespace easy2d
void Update(); void Update();
bool HandleMessage(
HWND hwnd,
UINT msg,
WPARAM wparam,
LPARAM lparam
);
void Dispatch( void Dispatch(
Event* event Event* event
); );

View File

@ -324,14 +324,14 @@ namespace easy2d
current_sink_->AddLine(point); current_sink_->AddLine(point);
} }
void PathGeometry::AddLines(std::vector<Point> const& points) void PathGeometry::AddLines(Array<Point> const& points)
{ {
if (current_sink_) if (current_sink_)
{ {
if (!points.empty()) if (!points.empty())
{ {
size_t size = points.size(); size_t size = points.size();
std::vector<D2D1_POINT_2F> d2d_points(size); Array<D2D1_POINT_2F> d2d_points(size);
for (size_t i = 0; i < size; ++i) for (size_t i = 0; i < size; ++i)
{ {
d2d_points[i] = points[i]; d2d_points[i] = points[i];

View File

@ -231,7 +231,7 @@ namespace easy2d
// 添加多条线段 // 添加多条线段
void AddLines( void AddLines(
std::vector<Point> const& points Array<Point> const& points
); );
// 添加一条三次方贝塞尔曲线 // 添加一条三次方贝塞尔曲线

View File

@ -45,19 +45,6 @@ namespace easy2d
this->Crop(crop_rect); this->Crop(crop_rect);
} }
Image::Image(std::wstring const& file_name)
: Image()
{
this->Load(file_name);
}
Image::Image(std::wstring const& file_name, const Rect & crop_rect)
: Image()
{
this->Load(file_name);
this->Crop(crop_rect);
}
Image::Image(CpBitmap const & bitmap) Image::Image(CpBitmap const & bitmap)
: Image() : Image()
{ {
@ -70,38 +57,35 @@ namespace easy2d
bool Image::Load(Resource const& res) bool Image::Load(Resource const& res)
{ {
HRESULT hr = S_OK;
CpBitmap bitmap; CpBitmap bitmap;
HRESULT hr = Graphics::Instance()->CreateBitmapFromResource(bitmap, res);
if (res.IsFile())
{
File image_file;
if (!image_file.Open(res.GetFileName()))
{
logs::Warningln("Image file '%s' not found!", StringWideCharToMultiByte(res.GetFileName()).c_str());
return false;
}
// 用户输入的路径不一定是完整路径,因为用户可能通过 File::AddSearchPath 添加
// 默认搜索路径,所以需要通过 File::GetPath 获取完整路径
String image_file_path = image_file.GetPath();
hr = Graphics::Instance()->CreateBitmapFromFile(bitmap, image_file_path);
}
else
{
hr = Graphics::Instance()->CreateBitmapFromResource(bitmap, res);
}
if (FAILED(hr)) if (FAILED(hr))
{ {
logs::Errorln(hr, "Load Image from resource failed!"); logs::Errorln(hr, "Load image file failed!");
return false;
}
SetBitmap(bitmap);
return true;
}
bool Image::Load(std::wstring const& file_name)
{
File image_file;
if (!image_file.Open(file_name))
{
logs::Warningln("Image file '%s' not found!", StringWideCharToMultiByte(file_name).c_str());
return false; return false;
} }
// 用户输入的路径不一定是完整路径,因为用户可能通过 File::AddSearchPath 添加
// 默认搜索路径,所以需要通过 File::GetPath 获取完整路径
std::wstring image_file_path = image_file.GetPath();
CpBitmap bitmap;
HRESULT hr = Graphics::Instance()->CreateBitmapFromFile(bitmap, image_file_path);
if (FAILED(hr))
{
logs::Errorln(hr, "Load Image from file failed!");
return false;
}
SetBitmap(bitmap); SetBitmap(bitmap);
return true; return true;
} }

View File

@ -40,15 +40,6 @@ namespace easy2d
Rect const& crop_rect /* 裁剪矩形 */ Rect const& crop_rect /* 裁剪矩形 */
); );
explicit Image(
std::wstring const& file_name
);
explicit Image(
std::wstring const& file_name,
Rect const& crop_rect /* ²Ã¼ô¾ØÐÎ */
);
explicit Image( explicit Image(
CpBitmap const& bitmap CpBitmap const& bitmap
); );
@ -60,11 +51,6 @@ namespace easy2d
Resource const& res Resource const& res
); );
// ¼ÓÔØÍ¼Æ¬×ÊÔ´
bool Load(
std::wstring const& file_name
);
// 将图片裁剪为矩形 // 将图片裁剪为矩形
void Crop( void Crop(
Rect const& crop_rect /* 裁剪矩形 */ Rect const& crop_rect /* 裁剪矩形 */

View File

@ -37,22 +37,8 @@ namespace easy2d
{ {
} }
Music::Music(std::wstring const& file_path)
: opened_(false)
, playing_(false)
, wave_data_(nullptr)
, size_(0)
, voice_(nullptr)
{
Load(file_path);
}
Music::Music(Resource const& res) Music::Music(Resource const& res)
: opened_(false) : Music()
, playing_(false)
, wave_data_(nullptr)
, size_(0)
, voice_(nullptr)
{ {
Load(res); Load(res);
} }
@ -62,48 +48,6 @@ namespace easy2d
Close(); Close();
} }
bool Music::Load(std::wstring const& file_path)
{
if (opened_)
{
Close();
}
File music_file;
if (!music_file.Open(file_path))
{
logs::Warningln("Media file '%s' not found", StringWideCharToMultiByte(file_path).c_str());
return false;
}
// 用户输入的路径不一定是完整路径,因为用户可能通过 File::AddSearchPath 添加
// 默认搜索路径,所以需要通过 File::GetPath 获取完整路径
std::wstring music_file_path = music_file.GetPath();
Transcoder transcoder;
HRESULT hr = transcoder.LoadMediaFile(music_file_path.c_str(), &wave_data_, &size_);
if (FAILED(hr))
{
logs::Errorln(hr, "Load media from file failed");
return false;
}
hr = Audio::Instance()->CreateVoice(voice_, transcoder.GetWaveFormatEx());
if (FAILED(hr))
{
if (wave_data_)
{
delete[] wave_data_;
wave_data_ = nullptr;
}
logs::Errorln(hr, "Create source voice failed");
return false;
}
opened_ = true;
return true;
}
bool Music::Load(Resource const& res) bool Music::Load(Resource const& res)
{ {
if (opened_) if (opened_)
@ -111,12 +55,31 @@ namespace easy2d
Close(); Close();
} }
HRESULT hr = S_OK;
Transcoder transcoder; Transcoder transcoder;
HRESULT hr = transcoder.LoadMediaResource(res, &wave_data_, &size_);
if (res.IsFile())
{
File music_file;
if (!music_file.Open(res.GetFileName()))
{
logs::Warningln("Media file '%s' not found", StringWideCharToMultiByte(res.GetFileName()).c_str());
return false;
}
// 用户输入的路径不一定是完整路径,因为用户可能通过 File::AddSearchPath 添加
// 默认搜索路径,所以需要通过 File::GetPath 获取完整路径
String music_file_path = music_file.GetPath();
HRESULT hr = transcoder.LoadMediaFile(music_file_path.c_str(), &wave_data_, &size_);
}
else
{
hr = transcoder.LoadMediaResource(res, &wave_data_, &size_);
}
if (FAILED(hr)) if (FAILED(hr))
{ {
logs::Errorln(hr, "Load media from resource failed"); logs::Errorln(hr, "Load media file failed");
return false; return false;
} }

View File

@ -32,21 +32,12 @@ namespace easy2d
public: public:
Music(); Music();
Music(
std::wstring const& file_path /* 音乐文件路径 */
);
Music( Music(
Resource const& res /* 稜있栗都 */ Resource const& res /* 稜있栗都 */
); );
virtual ~Music(); virtual ~Music();
// 打开音乐文件
bool Load(
std::wstring const& file_path /* 音乐文件路径 */
);
// 댔역稜있栗都 // 댔역稜있栗都
bool Load( bool Load(
Resource const& res /* 稜있栗都 */ Resource const& res /* 稜있栗都 */

View File

@ -346,12 +346,12 @@ namespace easy2d
visible_ = val; visible_ = val;
} }
void Node::SetName(std::wstring const& name) void Node::SetName(String const& name)
{ {
if (name_ != name) if (name_ != name)
{ {
name_ = name; name_ = name;
hash_name_ = std::hash<std::wstring>{}(name); hash_name_ = std::hash<String>{}(name);
} }
} }
@ -470,7 +470,7 @@ namespace easy2d
} }
} }
void Node::AddChildren(const Nodes& children) void Node::AddChildren(Array<SpNode> const& children)
{ {
for (const auto& node : children) for (const auto& node : children)
{ {
@ -483,10 +483,10 @@ namespace easy2d
return Rect(Point{}, size_); return Rect(Point{}, size_);
} }
Node::Nodes Node::GetChildren(std::wstring const& name) const Array<SpNode> Node::GetChildren(String const& name) const
{ {
Nodes children; Array<SpNode> children;
size_t hash_code = std::hash<std::wstring>{}(name); size_t hash_code = std::hash<String>{}(name);
for (Node* child = children_.First().Get(); child; child = child->NextItem().Get()) for (Node* child = children_.First().Get(); child; child = child->NextItem().Get())
{ {
@ -498,9 +498,9 @@ namespace easy2d
return children; return children;
} }
SpNode Node::GetChild(std::wstring const& name) const SpNode Node::GetChild(String const& name) const
{ {
size_t hash_code = std::hash<std::wstring>{}(name); size_t hash_code = std::hash<String>{}(name);
for (Node* child = children_.First().Get(); child; child = child->NextItem().Get()) for (Node* child = children_.First().Get(); child; child = child->NextItem().Get())
{ {
@ -547,14 +547,14 @@ namespace easy2d
return false; return false;
} }
void Node::RemoveChildren(std::wstring const& child_name) void Node::RemoveChildren(String const& child_name)
{ {
if (children_.IsEmpty()) if (children_.IsEmpty())
{ {
return; return;
} }
size_t hash_code = std::hash<std::wstring>{}(child_name); size_t hash_code = std::hash<String>{}(child_name);
Node* next; Node* next;
for (Node* child = children_.First().Get(); child; child = next) for (Node* child = children_.First().Get(); child; child = next)

View File

@ -44,7 +44,6 @@ namespace easy2d
friend class Transition; friend class Transition;
friend class intrusive::List<SpNode>; friend class intrusive::List<SpNode>;
using Nodes = std::vector<SpNode>;
using Children = intrusive::List<SpNode>; using Children = intrusive::List<SpNode>;
public: public:
@ -60,7 +59,7 @@ namespace easy2d
bool IsVisible() const { return visible_; } bool IsVisible() const { return visible_; }
// 获取名称 // 获取名称
std::wstring const& GetName() const { return name_; } String const& GetName() const { return name_; }
// 获取名称的 Hash 值 // 获取名称的 Hash 值
size_t GetHashName() const { return hash_name_; } size_t GetHashName() const { return hash_name_; }
@ -144,7 +143,7 @@ namespace easy2d
// 设置名称 // 设置名称
void SetName( void SetName(
std::wstring const& name String const& name
); );
// 设置横坐标 // 设置横坐标
@ -297,17 +296,17 @@ namespace easy2d
// 添加多个子节点 // 添加多个子节点
void AddChildren( void AddChildren(
const Nodes& children Array<SpNode> const& children
); );
// 获取所有名称相同的子节点 // 获取所有名称相同的子节点
Nodes GetChildren( Array<SpNode> GetChildren(
std::wstring const& name String const& name
) const; ) const;
// 获取名称相同的子节点 // 获取名称相同的子节点
SpNode GetChild( SpNode GetChild(
std::wstring const& name String const& name
) const; ) const;
// 获取全部子节点 // 获取全部子节点
@ -325,7 +324,7 @@ namespace easy2d
// 移除所有名称相同的子节点 // 移除所有名称相同的子节点
void RemoveChildren( void RemoveChildren(
std::wstring const& child_name String const& child_name
); );
// 移除所有节点 // 移除所有节点
@ -354,20 +353,20 @@ namespace easy2d
void SetScene(Scene* scene); void SetScene(Scene* scene);
protected: protected:
bool visible_; bool visible_;
bool hover_; bool hover_;
bool pressed_; bool pressed_;
int z_order_; int z_order_;
float opacity_; float opacity_;
float display_opacity_; float display_opacity_;
std::wstring name_; String name_;
size_t hash_name_; size_t hash_name_;
Transform transform_; Transform transform_;
Point pivot_; Point pivot_;
Size size_; Size size_;
Node* parent_; Node* parent_;
Scene* scene_; Scene* scene_;
Children children_; Children children_;
mutable bool dirty_transform_; mutable bool dirty_transform_;
mutable bool dirty_transform_inverse_; mutable bool dirty_transform_inverse_;

View File

@ -25,7 +25,7 @@ namespace easy2d
namespace namespace
{ {
bool tracing_leaks = true; bool tracing_leaks = true;
std::vector<Object*> tracing_objects; Array<Object*> tracing_objects;
} }
Object::Object() Object::Object()
@ -67,7 +67,7 @@ namespace easy2d
tracing_leaks = false; tracing_leaks = false;
} }
std::vector<Object*> const& easy2d::Object::__GetTracingObjects() Array<Object*> const& easy2d::Object::__GetTracingObjects()
{ {
return tracing_objects; return tracing_objects;
} }

View File

@ -20,7 +20,7 @@
#pragma once #pragma once
#include "RefCounter.hpp" #include "RefCounter.hpp"
#include <vector> #include "helper.hpp"
namespace easy2d namespace easy2d
{ {
@ -40,7 +40,7 @@ namespace easy2d
static void StopTracingLeaks(); static void StopTracingLeaks();
static std::vector<Object*> const& __GetTracingObjects(); static Array<Object*> const& __GetTracingObjects();
protected: protected:
static void __AddObjectToTracingList(Object*); static void __AddObjectToTracingList(Object*);

View File

@ -23,36 +23,45 @@
namespace easy2d namespace easy2d
{ {
Resource::Resource(String file_name)
: type_(Type::File)
, file_name_(file_name)
{
}
Resource::Resource(LPCWSTR file_name)
: type_(Type::File)
, file_name_(file_name)
{
}
Resource::Resource(LPCWSTR name, LPCWSTR type) Resource::Resource(LPCWSTR name, LPCWSTR type)
: name_(name) : type_(Type::Binary)
, type_(type) , bin_name_(name)
, bin_type_(type)
{ {
} }
LPCWSTR Resource::GetName() const Resource::~Resource()
{ {
return name_;
}
LPCWSTR Resource::GetType() const
{
return type_;
} }
size_t Resource::GetHashCode() const size_t Resource::GetHashCode() const
{ {
return std::hash<LPCWSTR>{}(name_); if (type_ == Type::File)
return std::hash<String>{}(file_name_);
return std::hash<LPCWSTR>{}(bin_name_);
} }
bool Resource::Load(ResourceData* buffer) const bool Resource::Load(LPVOID& buffer, DWORD& buffer_size) const
{ {
if (!buffer) if (type_ != Type::Binary)
return false; return false;
HGLOBAL res_data; HGLOBAL res_data;
HRSRC res_info; HRSRC res_info;
res_info = FindResourceW(nullptr, name_, type_); res_info = FindResourceW(nullptr, bin_name_, bin_type_);
if (res_info == nullptr) if (res_info == nullptr)
{ {
logs::Errorln("FindResource"); logs::Errorln("FindResource");
@ -66,15 +75,15 @@ namespace easy2d
return false; return false;
} }
(*buffer).buffer_size = SizeofResource(nullptr, res_info); buffer_size = SizeofResource(nullptr, res_info);
if ((*buffer).buffer_size == 0) if (buffer_size == 0)
{ {
logs::Errorln("SizeofResource"); logs::Errorln("SizeofResource");
return false; return false;
} }
(*buffer).buffer = LockResource(res_data); buffer = LockResource(res_data);
if ((*buffer).buffer == nullptr) if (buffer == nullptr)
{ {
logs::Errorln("LockResource"); logs::Errorln("LockResource");
return false; return false;

View File

@ -19,32 +19,15 @@
// THE SOFTWARE. // THE SOFTWARE.
#pragma once #pragma once
#include "macros.h" #include "helper.hpp"
namespace easy2d namespace easy2d
{ {
// 资源数据
//
// Usage:
// 如果需要手动加载资源, 可以通过 Resource::Load 方法获取资源内容
// ResourceData data;
// if (res.Load(&data)) {
// LPVOID data = data.buffer;
// DWORD size_ = data.buffer_size;
// }
//
struct ResourceData
{
LPVOID buffer;
DWORD buffer_size;
};
// 资源 // 资源
// //
// Usage: // Usage:
// Resource 用于获取可执行文件 (exe) 中的资源, 必须在构造函数中指定它的 // Resource 用于指定一份资源
// 资源类型和名称标识符。 // 资源可以是文件类型,也可以是保存在 exe 中的二进制文件
// 例如, 一份音频资源的类型为 L"WAVE", 名称标识符为 IDR_WAVE_1, // 例如, 一份音频资源的类型为 L"WAVE", 名称标识符为 IDR_WAVE_1,
// 那么可以这样指定该资源: Resource res(MAKEINTRESOURCE(IDR_WAVE_1), L"WAVE"); // 那么可以这样指定该资源: Resource res(MAKEINTRESOURCE(IDR_WAVE_1), L"WAVE");
// //
@ -53,23 +36,50 @@ namespace easy2d
class Resource class Resource
{ {
public: public:
enum class Type { File, Binary };
Resource( Resource(
LPCWSTR name, /* 资源名称 */ String file_name /* 文件路径 */
LPCWSTR type /* 资源类型 */
); );
Resource(
LPCWSTR file_name /* 文件路径 */
);
Resource(
LPCWSTR name, /* 资源名称 */
LPCWSTR type /* 资源类型 */
);
virtual ~Resource();
inline bool IsFile() const { return type_ == Type::File; }
inline Type GetType() const { return type_; }
inline String const& GetFileName() const { return file_name_; }
bool Load( bool Load(
ResourceData* buffer LPVOID& buffer,
DWORD& buffer_size
) const; ) const;
LPCWSTR GetName() const;
LPCWSTR GetType() const;
size_t GetHashCode() const; size_t GetHashCode() const;
private: private:
LPCWSTR name_; Type type_;
LPCWSTR type_; union
{
struct
{
String file_name_;
};
struct
{
LPCWSTR bin_name_;
LPCWSTR bin_type_;
};
};
}; };
} }

View File

@ -47,19 +47,6 @@ namespace easy2d
Crop(crop_rect); Crop(crop_rect);
} }
Sprite::Sprite(std::wstring const& file_name)
: image_(nullptr)
{
Load(file_name);
}
Sprite::Sprite(std::wstring const& file_name, const Rect & crop_rect)
: image_(nullptr)
{
Load(file_name);
Crop(crop_rect);
}
Sprite::~Sprite() Sprite::~Sprite()
{ {
} }
@ -94,24 +81,6 @@ namespace easy2d
return false; return false;
} }
bool Sprite::Load(std::wstring const& file_name)
{
if (!image_)
{
image_ = new (std::nothrow) Image;
}
if (image_)
{
if (image_->Load(file_name))
{
Node::SetSize(image_->GetWidth(), image_->GetHeight());
return true;
}
}
return false;
}
void Sprite::Crop(const Rect& crop_rect) void Sprite::Crop(const Rect& crop_rect)
{ {
image_->Crop(crop_rect); image_->Crop(crop_rect);

View File

@ -44,15 +44,6 @@ namespace easy2d
const Rect& crop_rect /* 裁剪矩形 */ const Rect& crop_rect /* 裁剪矩形 */
); );
explicit Sprite(
std::wstring const& file_name
);
explicit Sprite(
std::wstring const& file_name,
const Rect& crop_rect /* 裁剪矩形 */
);
virtual ~Sprite(); virtual ~Sprite();
// 加载图片文件 // 加载图片文件
@ -60,11 +51,6 @@ namespace easy2d
Resource const& res Resource const& res
); );
// 加载图片文件
bool Load(
std::wstring const& file_name
);
// 加载图片 // 加载图片
bool Load( bool Load(
SpImage const& image SpImage const& image

View File

@ -22,12 +22,12 @@
namespace easy2d namespace easy2d
{ {
Task::Task(Callback const& func, std::wstring const& name) Task::Task(Callback const& func, String const& name)
: Task(func, Duration{}, -1, name) : Task(func, Duration{}, -1, name)
{ {
} }
Task::Task(Callback const& func, Duration const& delay, int times, std::wstring const& name) Task::Task(Callback const& func, Duration const& delay, int times, String const& name)
: running_(true) : running_(true)
, run_times_(0) , run_times_(0)
, total_times_(times) , total_times_(times)
@ -91,7 +91,7 @@ namespace easy2d
return running_; return running_;
} }
std::wstring const& Task::GetName() const String const& Task::GetName() const
{ {
return name_; return name_;
} }

View File

@ -41,14 +41,14 @@ namespace easy2d
public: public:
explicit Task( explicit Task(
Callback const& func, /* 执行函数 */ Callback const& func, /* 执行函数 */
std::wstring const& name = L"" /* ÈÎÎñÃû³Æ */ String const& name = L"" /* ÈÎÎñÃû³Æ */
); );
explicit Task( explicit Task(
Callback const& func, /* 执行函数 */ Callback const& func, /* 执行函数 */
Duration const& delay, /* 时间间隔(秒) */ Duration const& delay, /* 时间间隔(秒) */
int times = -1, /* 执行次数(设 -1 为永久执行) */ int times = -1, /* 执行次数(设 -1 为永久执行) */
std::wstring const& name = L"" /* ÈÎÎñÃû³Æ */ String const& name = L"" /* ÈÎÎñÃû³Æ */
); );
// 启动任务 // 启动任务
@ -61,7 +61,7 @@ namespace easy2d
bool IsRunning() const; bool IsRunning() const;
// 获取任务名称 // 获取任务名称
std::wstring const& GetName() const; String const& GetName() const;
protected: protected:
void Update(Duration const& dt, bool& remove_after_update); void Update(Duration const& dt, bool& remove_after_update);
@ -72,7 +72,7 @@ namespace easy2d
bool running_; bool running_;
int run_times_; int run_times_;
int total_times_; int total_times_;
std::wstring name_; String name_;
Duration delay_; Duration delay_;
Duration delta_; Duration delta_;
Callback callback_; Callback callback_;

View File

@ -52,7 +52,7 @@ namespace easy2d
} }
} }
void TaskManager::StopTasks(std::wstring const& name) void TaskManager::StopTasks(String const& name)
{ {
if (tasks_.IsEmpty()) if (tasks_.IsEmpty())
return; return;
@ -66,7 +66,7 @@ namespace easy2d
} }
} }
void TaskManager::StartTasks(std::wstring const& name) void TaskManager::StartTasks(String const& name)
{ {
if (tasks_.IsEmpty()) if (tasks_.IsEmpty())
return; return;
@ -80,7 +80,7 @@ namespace easy2d
} }
} }
void TaskManager::RemoveTasks(std::wstring const& name) void TaskManager::RemoveTasks(String const& name)
{ {
if (tasks_.IsEmpty()) if (tasks_.IsEmpty())
return; return;

View File

@ -35,17 +35,17 @@ namespace easy2d
// 启动任务 // 启动任务
void StartTasks( void StartTasks(
std::wstring const& task_name String const& task_name
); );
// 停止任务 // 停止任务
void StopTasks( void StopTasks(
std::wstring const& task_name String const& task_name
); );
// 移除任务 // 移除任务
void RemoveTasks( void RemoveTasks(
std::wstring const& task_name String const& task_name
); );
// 启动所有任务 // 启动所有任务

View File

@ -48,22 +48,22 @@ namespace easy2d
{ {
} }
Text::Text(std::wstring const& text) Text::Text(String const& text)
: Text(text, text_default_font, text_default_style) : Text(text, text_default_font, text_default_style)
{ {
} }
Text::Text(std::wstring const& text, const Font & font) Text::Text(String const& text, const Font & font)
: Text(text, font, text_default_style) : Text(text, font, text_default_style)
{ {
} }
Text::Text(std::wstring const& text, const TextStyle & style) Text::Text(String const& text, const TextStyle & style)
: Text(text, text_default_font, style) : Text(text, text_default_font, style)
{ {
} }
Text::Text(std::wstring const& text, const Font & font, const TextStyle & style) Text::Text(String const& text, const Font & font, const TextStyle & style)
: font_(font) : font_(font)
, style_(style) , style_(style)
, text_(text) , text_(text)
@ -75,7 +75,7 @@ namespace easy2d
{ {
} }
std::wstring const& Text::GetText() const String const& Text::GetText() const
{ {
return text_; return text_;
} }
@ -90,7 +90,7 @@ namespace easy2d
return style_; return style_;
} }
std::wstring const& Text::GetFontFamily() const String const& Text::GetFontFamily() const
{ {
return font_.family; return font_.family;
} }
@ -158,7 +158,7 @@ namespace easy2d
return style_.outline; return style_.outline;
} }
void Text::SetText(std::wstring const& text) void Text::SetText(String const& text)
{ {
text_ = text; text_ = text;
UpdateLayout(); UpdateLayout();
@ -176,7 +176,7 @@ namespace easy2d
UpdateLayout(); UpdateLayout();
} }
void Text::SetFontFamily(std::wstring const& family) void Text::SetFontFamily(String const& family)
{ {
if (font_.family != family) if (font_.family != family)
{ {

View File

@ -33,21 +33,21 @@ namespace easy2d
Text(); Text();
explicit Text( explicit Text(
std::wstring const& text /* 文字内容 */ String const& text /* 文字内容 */
); );
explicit Text( explicit Text(
std::wstring const& text, /* 文字内容 */ String const& text, /* 文字内容 */
const Font& font /* 字体 */ const Font& font /* 字体 */
); );
explicit Text( explicit Text(
std::wstring const& text, /* 文字内容 */ String const& text, /* 文字内容 */
const TextStyle& style /* 文本样式 */ const TextStyle& style /* 文本样式 */
); );
explicit Text( explicit Text(
std::wstring const& text, /* 文字内容 */ String const& text, /* 文字内容 */
const Font& font, /* 字体 */ const Font& font, /* 字体 */
const TextStyle& style /* 文本样式 */ const TextStyle& style /* 文本样式 */
); );
@ -55,7 +55,7 @@ namespace easy2d
virtual ~Text(); virtual ~Text();
// 获取文本 // 获取文本
std::wstring const& GetText() const; String const& GetText() const;
// 获取字体 // 获取字体
const Font& GetFont() const; const Font& GetFont() const;
@ -64,7 +64,7 @@ namespace easy2d
const TextStyle& GetStyle() const; const TextStyle& GetStyle() const;
// 获取字体族 // 获取字体族
std::wstring const& GetFontFamily() const; String const& GetFontFamily() const;
// 获取当前字号 // 获取当前字号
float GetFontSize() const; float GetFontSize() const;
@ -101,7 +101,7 @@ namespace easy2d
// 设置文本 // 设置文本
void SetText( void SetText(
std::wstring const& text String const& text
); );
// 设置文本样式 // 设置文本样式
@ -116,7 +116,7 @@ namespace easy2d
// 设置字体族 // 设置字体族
void SetFontFamily( void SetFontFamily(
std::wstring const& family String const& family
); );
// 设置字号(默认值为 22 // 设置字号(默认值为 22
@ -205,7 +205,7 @@ namespace easy2d
void UpdateLayout(); void UpdateLayout();
protected: protected:
std::wstring text_; String text_;
Font font_; Font font_;
TextStyle style_; TextStyle style_;
CpTextFormat text_format_; CpTextFormat text_format_;

View File

@ -20,10 +20,10 @@
#pragma once #pragma once
#include "macros.h" #include "macros.h"
#include "helper.hpp"
#include "Singleton.hpp" #include "Singleton.hpp"
#include "noncopyable.hpp" #include "noncopyable.hpp"
#include <xaudio2.h> #include <xaudio2.h>
#include <unordered_set>
namespace easy2d namespace easy2d
{ {
@ -79,7 +79,7 @@ namespace easy2d
{ {
E2D_DECLARE_SINGLETON(AudioDevice); E2D_DECLARE_SINGLETON(AudioDevice);
using VoiceMap = std::unordered_set<Voice*>; using VoiceMap = UnorderedSet<Voice*>;
public: public:
HRESULT Init(bool debug); HRESULT Init(bool debug);
@ -107,9 +107,9 @@ namespace easy2d
~AudioDevice(); ~AudioDevice();
protected: protected:
IXAudio2* x_audio2_; VoiceMap voice_cache_;
IXAudio2* x_audio2_;
IXAudio2MasteringVoice* mastering_voice_; IXAudio2MasteringVoice* mastering_voice_;
VoiceMap voice_cache_;
}; };
E2D_DECLARE_SINGLETON_TYPE(AudioDevice, Audio); E2D_DECLARE_SINGLETON_TYPE(AudioDevice, Audio);

View File

@ -24,6 +24,12 @@
#include "../math/vector.hpp" #include "../math/vector.hpp"
#include "../math/Rect.hpp" #include "../math/Rect.hpp"
#include "../math/Matrix.hpp" #include "../math/Matrix.hpp"
#include <set>
#include <map>
#include <list>
#include <unordered_set>
#include <unordered_map>
#ifndef E2D_DECLARE_SMART_PTR #ifndef E2D_DECLARE_SMART_PTR
#define E2D_DECLARE_SMART_PTR(class_name)\ #define E2D_DECLARE_SMART_PTR(class_name)\
@ -38,6 +44,30 @@
} }
#endif #endif
namespace easy2d
{
using String = std::wstring;
using StringStream = std::wstringstream;
template<typename T>
using Array = std::vector<T>;
template<typename T>
using List = std::list<T>;
template<typename T>
using Set = std::set<T>;
template<typename T>
using UnorderedSet = std::unordered_set<T>;
template<typename T, typename Y>
using Map = std::map<T, Y>;
template<typename T, typename Y>
using UnorderedMap = std::unordered_map<T, Y>;
}
namespace easy2d namespace easy2d
{ {
// "Sp" is a shorthand for "Smart Pointer" // "Sp" is a shorthand for "Smart Pointer"
@ -94,9 +124,29 @@ namespace easy2d
E2D_DECLARE_NS_SMART_PTR(ui, Button); E2D_DECLARE_NS_SMART_PTR(ui, Button);
E2D_DECLARE_NS_SMART_PTR(ui, Menu); E2D_DECLARE_NS_SMART_PTR(ui, Menu);
using Vector2 = math::Vector2; using namespace math;
using Point = math::Vector2; using namespace ui;
using Size = math::Vector2;
using Rect = math::Rect;
using Matrix = math::Matrix;
} }
namespace easy2d
{
class __SmartPointerMaker
{
public:
static inline __SmartPointerMaker const& Instance()
{
static __SmartPointerMaker maker;
return maker;
}
template<typename T>
inline intrusive::SmartPointer<T> operator- (T* ptr) const
{
return intrusive::SmartPointer<T>(ptr);
}
};
}
#ifndef E_NEW
# define E_NEW (::easy2d::__SmartPointerMaker::Instance()) - new (std::nothrow)
#endif

View File

@ -199,26 +199,4 @@ namespace easy2d
lhs.Swap(rhs); lhs.Swap(rhs);
} }
class SmartMaker
{
public:
static inline SmartMaker const& Instance()
{
static SmartMaker maker;
return maker;
}
template<typename T>
inline intrusive::SmartPointer<T> operator -(T* ptr) const
{
return intrusive::SmartPointer<T>(ptr);
}
};
#ifdef NEW
# undef NEW
#endif
#define NEW ::easy2d::SmartMaker::Instance() - new (std::nothrow)
} }

View File

@ -324,14 +324,14 @@ namespace easy2d
return S_OK; return S_OK;
} }
HRESULT GraphicsDevice::CreateBitmapFromFile(CpBitmap& bitmap, std::wstring const& file_path) HRESULT GraphicsDevice::CreateBitmapFromFile(CpBitmap& bitmap, String const& file_path)
{ {
if (render_target_ == nullptr) if (render_target_ == nullptr)
{ {
return E_UNEXPECTED; return E_UNEXPECTED;
} }
size_t hash_code = std::hash<std::wstring>{}(file_path); size_t hash_code = std::hash<String>{}(file_path);
if (bitmap_cache_.find(hash_code) != bitmap_cache_.end()) if (bitmap_cache_.find(hash_code) != bitmap_cache_.end())
{ {
bitmap = bitmap_cache_[hash_code]; bitmap = bitmap_cache_[hash_code];

View File

@ -43,7 +43,7 @@ namespace easy2d
int primitives; int primitives;
}; };
using BitmapMap = std::unordered_map<size_t, CpBitmap>; using BitmapMap = UnorderedMap<size_t, CpBitmap>;
public: public:
HRESULT Init(HWND hwnd, bool vsync, bool debug); HRESULT Init(HWND hwnd, bool vsync, bool debug);
@ -87,7 +87,7 @@ namespace easy2d
HRESULT CreateBitmapFromFile( HRESULT CreateBitmapFromFile(
CpBitmap& bitmap, CpBitmap& bitmap,
std::wstring const& file_path String const& file_path
); );
HRESULT CreateBitmapFromResource( HRESULT CreateBitmapFromResource(

View File

@ -47,7 +47,7 @@ namespace easy2d
E2D_LOG("Destroying window"); E2D_LOG("Destroying window");
} }
HRESULT WindowImpl::Init(std::wstring title, int width, int height, LPCWSTR icon, WNDPROC proc, bool debug) HRESULT WindowImpl::Init(String title, int width, int height, LPCWSTR icon, WNDPROC proc, bool debug)
{ {
E2D_LOG("Creating window"); E2D_LOG("Creating window");
@ -82,7 +82,7 @@ namespace easy2d
GetContentScale(&scale_x, &scale_y); GetContentScale(&scale_x, &scale_y);
Rect client_rect = LocateWindow(width, height, scale_x, scale_y); Rect client_rect = LocateWindow(width, height, scale_x, scale_y);
handle = ::CreateWindowEx( handle = ::CreateWindowExW(
NULL, NULL,
REGISTER_CLASS, REGISTER_CLASS,
title.c_str(), title.c_str(),
@ -94,7 +94,7 @@ namespace easy2d
nullptr, nullptr,
nullptr, nullptr,
hinstance, hinstance,
this nullptr
); );
if (handle == nullptr) if (handle == nullptr)
@ -105,7 +105,7 @@ namespace easy2d
return S_OK; return S_OK;
} }
std::wstring WindowImpl::GetTitle() const String WindowImpl::GetTitle() const
{ {
if (handle) if (handle)
{ {
@ -113,10 +113,10 @@ namespace easy2d
GetWindowTextW(handle, title, 256); GetWindowTextW(handle, title, 256);
return title; return title;
} }
return std::wstring(); return String();
} }
void WindowImpl::SetTitle(std::wstring const& title) void WindowImpl::SetTitle(String const& title)
{ {
if (handle) if (handle)
::SetWindowText(handle, title.c_str()); ::SetWindowText(handle, title.c_str());
@ -128,12 +128,12 @@ namespace easy2d
{ {
RECT rect; RECT rect;
GetClientRect(handle, &rect); GetClientRect(handle, &rect);
return Size( return Size{
static_cast<float>(rect.right - rect.left), static_cast<float>(rect.right - rect.left),
static_cast<float>(rect.bottom - rect.top) static_cast<float>(rect.bottom - rect.top)
); };
} }
return Size(); return Size{};
} }
float WindowImpl::GetWidth() const float WindowImpl::GetWidth() const

View File

@ -31,7 +31,7 @@ namespace easy2d
public: public:
HRESULT Init( HRESULT Init(
std::wstring title, String title,
int width, int width,
int height, int height,
LPCWSTR icon, LPCWSTR icon,
@ -40,10 +40,10 @@ namespace easy2d
); );
// 获取标题 // 获取标题
std::wstring GetTitle() const; String GetTitle() const;
// 设置标题 // 设置标题
void SetTitle(std::wstring const& title); void SetTitle(String const& title);
// 获取窗口大小 // 获取窗口大小
Size GetSize() const; Size GetSize() const;

View File

@ -84,5 +84,8 @@ namespace easy2d
return reinterpret_cast<D2D1_POINT_2F&>(*this); return reinterpret_cast<D2D1_POINT_2F&>(*this);
} }
}; };
using Point = Vector2;
using Size = Vector2;
} }
} }

View File

@ -29,7 +29,7 @@ namespace easy2d
{ {
} }
Menu::Menu(const std::vector<SpButton>& buttons) Menu::Menu(Array<SpButton> const& buttons)
: enabled_(true) : enabled_(true)
{ {
for (const auto& button : buttons) for (const auto& button : buttons)
@ -94,7 +94,7 @@ namespace easy2d
return false; return false;
} }
const std::vector<SpButton>& Menu::GetAllButtons() const Array<SpButton> const& Menu::GetAllButtons() const
{ {
return buttons_; return buttons_;
} }

View File

@ -33,7 +33,7 @@ namespace easy2d
Menu(); Menu();
explicit Menu( explicit Menu(
const std::vector<SpButton>& buttons /* 按钮数组 */ Array<SpButton> const& buttons /* 按钮数组 */
); );
// 获取菜单是否禁用 // 获取菜单是否禁用
@ -58,11 +58,11 @@ namespace easy2d
); );
// 获取所有按钮 // 获取所有按钮
const std::vector<SpButton>& GetAllButtons() const; Array<SpButton> const& GetAllButtons() const;
private: private:
bool enabled_; bool enabled_;
std::vector<SpButton> buttons_; Array<SpButton> buttons_;
}; };
} }
} }

View File

@ -20,11 +20,10 @@
#include "Data.h" #include "Data.h"
#include "Path.h" #include "Path.h"
#include "../base/macros.h"
namespace easy2d namespace easy2d
{ {
Data::Data(std::wstring const& key, std::wstring const& field) Data::Data(String const& key, String const& field)
: key_(key) : key_(key)
, field_(field) , field_(field)
, data_path_(Path::GetDataPath()) , data_path_(Path::GetDataPath())
@ -89,7 +88,7 @@ namespace easy2d
return ret == TRUE; return ret == TRUE;
} }
bool Data::SaveString(std::wstring const& val) bool Data::SaveString(String const& val)
{ {
BOOL ret = ::WritePrivateProfileStringW( BOOL ret = ::WritePrivateProfileStringW(
field_.c_str(), field_.c_str(),
@ -134,7 +133,7 @@ namespace easy2d
return nValue == TRUE; return nValue == TRUE;
} }
std::wstring Data::GetString() String Data::GetString()
{ {
wchar_t temp[256] = { 0 }; wchar_t temp[256] = { 0 };
::GetPrivateProfileStringW( ::GetPrivateProfileStringW(

View File

@ -19,7 +19,7 @@
// THE SOFTWARE. // THE SOFTWARE.
#pragma once #pragma once
#include <string> #include "../base/helper.hpp"
namespace easy2d namespace easy2d
{ {
@ -28,8 +28,8 @@ namespace easy2d
{ {
public: public:
Data( Data(
std::wstring const& key, /* 键值 */ String const& key, /* 键值 */
std::wstring const& field = L"Defalut" /* 字段名称 */ String const& field = L"Defalut" /* 字段名称 */
); );
// 该数据是否存在 // 该数据是否存在
@ -55,9 +55,9 @@ namespace easy2d
bool val bool val
); );
// 保存 std::wstring 类型的值 // 保存 String 类型的值
bool SaveString( bool SaveString(
std::wstring const& val String const& val
); );
// 获取 int 类型的值 // 获取 int 类型的值
@ -73,11 +73,11 @@ namespace easy2d
bool GetBool() const; bool GetBool() const;
// 获取 字符串 类型的值 // 获取 字符串 类型的值
std::wstring GetString(); String GetString();
protected: protected:
std::wstring key_; String key_;
std::wstring field_; String field_;
std::wstring const& data_path_; String const& data_path_;
}; };
} }

View File

@ -24,14 +24,14 @@
namespace easy2d namespace easy2d
{ {
std::list<std::wstring> File::search_paths_; std::list<String> File::search_paths_;
File::File() File::File()
: file_path_() : file_path_()
{ {
} }
File::File(std::wstring const& file_name) File::File(String const& file_name)
: file_path_(file_name) : file_path_(file_name)
{ {
this->Open(file_name); this->Open(file_name);
@ -41,12 +41,12 @@ namespace easy2d
{ {
} }
bool File::Open(std::wstring const& file_name) bool File::Open(String const& file_name)
{ {
if (file_name.empty()) if (file_name.empty())
return false; return false;
auto FindFile = [](std::wstring const& path) -> bool auto FindFile = [](String const& path) -> bool
{ {
if (modules::Shlwapi().PathFileExistsW(path.c_str())) if (modules::Shlwapi().PathFileExistsW(path.c_str()))
return true; return true;
@ -77,16 +77,16 @@ namespace easy2d
return false; return false;
} }
std::wstring const& File::GetPath() const String const& File::GetPath() const
{ {
return file_path_; return file_path_;
} }
std::wstring File::GetExtension() const String File::GetExtension() const
{ {
std::wstring file_ext; String file_ext;
size_t pos = file_path_.find_last_of(L'.'); size_t pos = file_path_.find_last_of(L'.');
if (pos != std::wstring::npos) if (pos != String::npos)
{ {
file_ext = file_path_.substr(pos); file_ext = file_path_.substr(pos);
std::transform(file_ext.begin(), file_ext.end(), file_ext.begin(), std::towlower); std::transform(file_ext.begin(), file_ext.end(), file_ext.begin(), std::towlower);
@ -101,7 +101,7 @@ namespace easy2d
return false; return false;
} }
File File::Extract(Resource& res, std::wstring const& dest_file_name) File File::Extract(Resource& res, String const& dest_file_name)
{ {
File file; File file;
HANDLE file_handle = ::CreateFile( HANDLE file_handle = ::CreateFile(
@ -117,12 +117,13 @@ namespace easy2d
if (file_handle == INVALID_HANDLE_VALUE) if (file_handle == INVALID_HANDLE_VALUE)
return file; return file;
ResourceData buffer; LPVOID buffer;
if (res.Load(&buffer)) DWORD buffer_size;
if (res.Load(buffer, buffer_size))
{ {
// дÈëÎļþ // дÈëÎļþ
DWORD written_bytes = 0; DWORD written_bytes = 0;
::WriteFile(file_handle, buffer.buffer, buffer.buffer_size, &written_bytes, NULL); ::WriteFile(file_handle, buffer, buffer_size, &written_bytes, NULL);
::CloseHandle(file_handle); ::CloseHandle(file_handle);
file.Open(dest_file_name); file.Open(dest_file_name);
@ -136,11 +137,11 @@ namespace easy2d
return file; return file;
} }
void File::AddSearchPath(std::wstring const& path) void File::AddSearchPath(String const& path)
{ {
std::wstring tmp = path; String tmp = path;
size_t pos = 0; size_t pos = 0;
while ((pos = tmp.find(L"/", pos)) != std::wstring::npos) while ((pos = tmp.find(L"/", pos)) != String::npos)
{ {
tmp.replace(pos, 1, L"\\"); tmp.replace(pos, 1, L"\\");
pos++; pos++;

View File

@ -19,9 +19,8 @@
// THE SOFTWARE. // THE SOFTWARE.
#pragma once #pragma once
#include "../base/helper.hpp"
#include "../base/Resource.h" #include "../base/Resource.h"
#include <string>
#include <list>
namespace easy2d namespace easy2d
{ {
@ -32,14 +31,14 @@ namespace easy2d
File(); File();
File( File(
std::wstring const& file_name String const& file_name
); );
virtual ~File(); virtual ~File();
// 打开文件 // 打开文件
bool Open( bool Open(
std::wstring const& file_name String const& file_name
); );
// 文件是否存在 // 文件是否存在
@ -49,25 +48,25 @@ namespace easy2d
bool Delete(); bool Delete();
// 获取文件路径 // 获取文件路径
std::wstring const& GetPath() const; String const& GetPath() const;
// 获取文件扩展名 // 获取文件扩展名
std::wstring GetExtension() const; String GetExtension() const;
// 释放资源到临时文件目录 // 释放资源到临时文件目录
static File Extract( static File Extract(
Resource& res, /* 资源 */ Resource& res, /* 资源 */
std::wstring const& dest_file_name /* 目标文件名 */ String const& dest_file_name /* 目标文件名 */
); );
// 添加文件搜索路径 // 添加文件搜索路径
static void AddSearchPath( static void AddSearchPath(
std::wstring const& path String const& path
); );
protected: protected:
std::wstring file_path_; String file_path_;
static std::list<std::wstring> search_paths_; static List<String> search_paths_;
}; };
} }

View File

@ -28,7 +28,7 @@ namespace easy2d
namespace namespace
{ {
// 创建指定文件夹 // 创建指定文件夹
bool CreateFolder(std::wstring const& dir_path) bool CreateFolder(String const& dir_path)
{ {
if (dir_path.empty() || dir_path.size() >= MAX_PATH) if (dir_path.empty() || dir_path.size() >= MAX_PATH)
return false; return false;
@ -55,15 +55,15 @@ namespace easy2d
} }
std::wstring const& Path::GetDataPath() String const& Path::GetDataPath()
{ {
static std::wstring data_path; static String data_path;
if (data_path.empty()) if (data_path.empty())
{ {
// 设置数据的保存路径 // 设置数据的保存路径
std::wstring local_app_data_path = Path::GetLocalAppDataPath(); String local_app_data_path = Path::GetLocalAppDataPath();
std::wstring title = Window::Instance()->GetTitle(); String title = Window::Instance()->GetTitle();
std::wstring folder_name = std::to_wstring(std::hash<std::wstring>{}(title)); String folder_name = std::to_wstring(std::hash<String>{}(title));
if (!local_app_data_path.empty()) if (!local_app_data_path.empty())
{ {
@ -83,15 +83,15 @@ namespace easy2d
return data_path; return data_path;
} }
std::wstring const& Path::GetTemporaryPath() String const& Path::GetTemporaryPath()
{ {
static std::wstring temp_path; static String temp_path;
if (temp_path.empty()) if (temp_path.empty())
{ {
// 设置临时文件保存路径 // 设置临时文件保存路径
wchar_t path[_MAX_PATH]; wchar_t path[_MAX_PATH];
std::wstring title = Window::Instance()->GetTitle(); String title = Window::Instance()->GetTitle();
std::wstring folder_name = std::to_wstring(std::hash<std::wstring>{}(title)); String folder_name = std::to_wstring(std::hash<String>{}(title));
if (0 != ::GetTempPath(_MAX_PATH, path)) if (0 != ::GetTempPath(_MAX_PATH, path))
{ {
@ -110,9 +110,9 @@ namespace easy2d
return temp_path; return temp_path;
} }
std::wstring const& Path::GetLocalAppDataPath() String const& Path::GetLocalAppDataPath()
{ {
static std::wstring local_app_data_path; static String local_app_data_path;
if (local_app_data_path.empty()) if (local_app_data_path.empty())
{ {
// 获取 AppData/Local 文件夹的路径 // 获取 AppData/Local 文件夹的路径
@ -124,9 +124,9 @@ namespace easy2d
return local_app_data_path; return local_app_data_path;
} }
std::wstring const& Path::GetExeFilePath() String const& Path::GetExeFilePath()
{ {
static std::wstring exe_file_path; static String exe_file_path;
if (exe_file_path.empty()) if (exe_file_path.empty())
{ {
TCHAR path[_MAX_PATH] = { 0 }; TCHAR path[_MAX_PATH] = { 0 };

View File

@ -19,7 +19,7 @@
// THE SOFTWARE. // THE SOFTWARE.
#pragma once #pragma once
#include <string> #include "../base/helper.hpp"
namespace easy2d namespace easy2d
{ {
@ -28,15 +28,15 @@ namespace easy2d
{ {
public: public:
// 获取数据的默认保存路径 // 获取数据的默认保存路径
static std::wstring const& GetDataPath(); static String const& GetDataPath();
// 获取临时文件目录 // 获取临时文件目录
static std::wstring const& GetTemporaryPath(); static String const& GetTemporaryPath();
// 获取 LocalAppData 目录 // 获取 LocalAppData 目录
static std::wstring const& GetLocalAppDataPath(); static String const& GetLocalAppDataPath();
// 获取当前程序的运行路径 // 获取当前程序的运行路径
static std::wstring const& GetExeFilePath(); static String const& GetExeFilePath();
}; };
} }

View File

@ -33,84 +33,6 @@ namespace easy2d
ClearCache(); ClearCache();
} }
bool Player::Load(std::wstring const& file_path)
{
if (file_path.empty())
return false;
SpMusic music = new (std::nothrow) Music();
if (music)
{
if (music->Load(file_path))
{
music->SetVolume(volume_);
size_t hash_code = std::hash<std::wstring>{}(file_path);
musics_cache_.insert(std::make_pair(hash_code, music));
return true;
}
}
return false;
}
bool Player::Play(std::wstring const& file_path, int loop_count)
{
if (file_path.empty())
return false;
if (Load(file_path))
{
auto music = musics_cache_[std::hash<std::wstring>{}(file_path)];
if (music->Play(loop_count))
{
return true;
}
}
return false;
}
void Player::Pause(std::wstring const& file_path)
{
if (file_path.empty())
return;
size_t hash_code = std::hash<std::wstring>{}(file_path);
if (musics_cache_.end() != musics_cache_.find(hash_code))
musics_cache_[hash_code]->Pause();
}
void Player::Resume(std::wstring const& file_path)
{
if (file_path.empty())
return;
size_t hash_code = std::hash<std::wstring>{}(file_path);
if (musics_cache_.end() != musics_cache_.find(hash_code))
musics_cache_[hash_code]->Resume();
}
void Player::Stop(std::wstring const& file_path)
{
if (file_path.empty())
return;
size_t hash_code = std::hash<std::wstring>{}(file_path);
if (musics_cache_.end() != musics_cache_.find(hash_code))
musics_cache_[hash_code]->Stop();
}
bool Player::IsPlaying(std::wstring const& file_path)
{
if (file_path.empty())
return false;
size_t hash_code = std::hash<std::wstring>{}(file_path);
if (musics_cache_.end() != musics_cache_.find(hash_code))
return musics_cache_[hash_code]->IsPlaying();
return false;
}
bool Player::Load(Resource const& res) bool Player::Load(Resource const& res)
{ {
size_t hash_code = res.GetHashCode(); size_t hash_code = res.GetHashCode();

View File

@ -29,7 +29,7 @@ namespace easy2d
class Player class Player
: protected Noncopyable : protected Noncopyable
{ {
using MusicMap = std::unordered_map<size_t, SpMusic>; using MusicMap = Map<size_t, SpMusic>;
public: public:
Player(); Player();
@ -38,38 +38,7 @@ namespace easy2d
// 渡속潼稜있栗都 // 渡속潼稜있栗都
bool Load( bool Load(
std::wstring const& file_path /* 音乐文件路径 */ Resource const& res /* 稜있栗都 */
);
// 播放音乐
bool Play(
std::wstring const& file_path, /* 音乐文件路径 */
int loop_count = 0 /* 播放循环次数 (-1 为循环播放) */
);
// 暂停音乐
void Pause(
std::wstring const& file_path /* 音乐文件路径 */
);
// 继续播放音乐
void Resume(
std::wstring const& file_path /* 音乐文件路径 */
);
// 停止音乐
void Stop(
std::wstring const& file_path /* 音乐文件路径 */
);
// 获取音乐播放状态
bool IsPlaying(
std::wstring const& file_path /* 音乐文件路径 */
);
// 预加载音乐资源
bool Load(
Resource const& res /* 音乐资源 */
); );
// 꺄렴稜있 // 꺄렴稜있

View File

@ -76,12 +76,13 @@ namespace easy2d
SmartPointer<IMFByteStream> byte_stream; SmartPointer<IMFByteStream> byte_stream;
SmartPointer<IMFSourceReader> reader; SmartPointer<IMFSourceReader> reader;
ResourceData buffer; LPVOID buffer;
if (!res.Load(&buffer)) { return false; } DWORD buffer_size;
if (!res.Load(buffer, buffer_size)) { return false; }
stream = modules::Shlwapi{}.SHCreateMemStream( stream = modules::Shlwapi{}.SHCreateMemStream(
static_cast<const BYTE*>(buffer.buffer), static_cast<const BYTE*>(buffer),
static_cast<UINT>(buffer.buffer_size) static_cast<UINT>(buffer_size)
); );
if (stream == nullptr) if (stream == nullptr)