refactor(core): 重构生命周期管理,引入Lifecycle统一管理模块和服务

重构模块和服务初始化流程,使用Lifecycle类统一管理依赖和生命周期
移除旧的ServiceLocator和Registry,简化架构
添加模块和服务依赖声明功能,支持自动拓扑排序
优化初始化顺序,支持并行初始化独立模块
更新相关模块和服务以适配新生命周期管理接口
This commit is contained in:
ChestnutYueyue 2026-02-23 06:00:35 +08:00
parent d3973cd820
commit 174d7327ef
25 changed files with 1537 additions and 1594 deletions

View File

@ -1,12 +1,12 @@
#pragma once
#include <extra2d/core/service_locator.h>
#include <extra2d/core/lifecycle.h>
#include <extra2d/core/types.h>
#include <string>
namespace extra2d {
class Window;
class WindowModule;
/**
* @brief
@ -21,6 +21,49 @@ public:
std::string name = "Extra2D App";
std::string version = "1.0.0";
/**
* @brief
* @tparam T
* @tparam Args
* @param args
* @return
*/
template <typename T, typename... Args> T *useModule(Args &&...args) {
return Lifecycle::instance().createModule<T>(std::forward<Args>(args)...);
}
/**
* @brief
* @tparam T
* @return
*/
template <typename T> T *module() const {
return Lifecycle::instance().module<T>();
}
/**
* @brief
* @tparam T
* @tparam Impl
* @tparam Args
* @param args
* @return
*/
template <typename T, typename Impl, typename... Args>
Ref<T> useService(Args &&...args) {
return Lifecycle::instance().createService<T, Impl>(
std::forward<Args>(args)...);
}
/**
* @brief
* @tparam T
* @return
*/
template <typename T> Ref<T> service() const {
return Lifecycle::instance().service<T>();
}
bool init();
void shutdown();
void run();
@ -28,14 +71,14 @@ public:
bool paused() const { return paused_; }
bool running() const { return running_; }
Window* window() const { return window_; }
WindowModule *windowModule() const;
f32 dt() const { return dt_; }
f32 totalTime() const { return totalTime_; }
int fps() const { return fps_; }
private:
Application() = default;
Application();
~Application();
void mainLoop();
@ -43,7 +86,6 @@ private:
bool initialized_ = false;
bool running_ = false;
bool paused_ = false;
Window* window_ = nullptr;
f32 dt_ = 0.0f;
f32 totalTime_ = 0.0f;

View File

@ -0,0 +1,350 @@
#pragma once
#include <extra2d/core/module.h>
#include <extra2d/core/service_interface.h>
#include <extra2d/core/types.h>
#include <functional>
#include <mutex>
#include <shared_mutex>
#include <typeindex>
#include <vector>
namespace extra2d {
class Application;
/**
* @brief ID
*/
using TypeId = size_t;
namespace detail {
inline TypeId nextTypeId() {
static TypeId id = 0;
return ++id;
}
template<typename T>
inline TypeId getTypeId() {
static TypeId id = nextTypeId();
return id;
}
} // namespace detail
/**
* @brief
*/
enum class UnitType : u8 {
Module,
Service
};
/**
* @brief
*
*/
class Lifecycle {
public:
/**
* @brief
* @return Lifecycle
*/
static Lifecycle& instance();
Lifecycle(const Lifecycle&) = delete;
Lifecycle& operator=(const Lifecycle&) = delete;
// ========== 注册接口 ==========
/**
* @brief
* @tparam T
* @param module
*/
template<typename T>
void addModule(Unique<T> module) {
static_assert(std::is_base_of_v<Module, T>, "T must derive from Module");
std::unique_lock<std::shared_mutex> lock(mutex_);
auto typeId = detail::getTypeId<T>();
for (const auto& entry : modules_) {
if (entry.id == typeId) {
return;
}
}
ModuleEntry entry;
entry.id = typeId;
entry.module = std::move(module);
modules_.push_back(std::move(entry));
}
/**
* @brief
* @tparam T
* @tparam Args
* @param args
* @return
*/
template<typename T, typename... Args>
T* createModule(Args&&... args) {
static_assert(std::is_base_of_v<Module, T>, "T must derive from Module");
auto module = ptr::unique<T>(std::forward<Args>(args)...);
T* ptr = module.get();
module->setApp(app_);
addModule<T>(std::move(module));
return ptr;
}
/**
* @brief
* @tparam T
* @param service
*/
template<typename T>
void addService(Ref<T> service) {
static_assert(std::is_base_of_v<IService, T>, "T must derive from IService");
std::unique_lock<std::shared_mutex> lock(mutex_);
auto typeId = std::type_index(typeid(T));
for (const auto& entry : services_) {
if (entry.id == typeId) {
return;
}
}
ServiceEntry entry;
entry.id = typeId;
entry.service = std::static_pointer_cast<IService>(service);
services_.push_back(std::move(entry));
}
/**
* @brief
* @tparam T
* @tparam Impl
* @tparam Args
* @param args
* @return
*/
template<typename T, typename Impl, typename... Args>
Ref<T> createService(Args&&... args) {
static_assert(std::is_base_of_v<IService, T>, "T must derive from IService");
static_assert(std::is_base_of_v<T, Impl>, "Impl must derive from T");
auto service = ptr::make<Impl>(std::forward<Args>(args)...);
auto result = std::static_pointer_cast<T>(service);
addService<T>(result);
return result;
}
// ========== 获取接口 ==========
/**
* @brief
* @tparam T
* @return nullptr
*/
template<typename T>
T* module() const {
static_assert(std::is_base_of_v<Module, T>, "T must derive from Module");
std::shared_lock<std::shared_mutex> lock(mutex_);
auto typeId = detail::getTypeId<T>();
for (const auto& entry : modules_) {
if (entry.id == typeId && entry.module) {
return static_cast<T*>(entry.module.get());
}
}
return nullptr;
}
/**
* @brief
* @tparam T
* @return nullptr
*/
template<typename T>
Ref<T> service() const {
static_assert(std::is_base_of_v<IService, T>, "T must derive from IService");
std::shared_lock<std::shared_mutex> lock(mutex_);
auto typeId = std::type_index(typeid(T));
for (const auto& entry : services_) {
if (entry.id == typeId && entry.service) {
return std::static_pointer_cast<T>(entry.service);
}
}
return nullptr;
}
/**
* @brief
* @tparam T
* @return true
*/
template<typename T>
bool hasModule() const {
std::shared_lock<std::shared_mutex> lock(mutex_);
auto typeId = detail::getTypeId<T>();
for (const auto& entry : modules_) {
if (entry.id == typeId) {
return true;
}
}
return false;
}
/**
* @brief
* @tparam T
* @return true
*/
template<typename T>
bool hasService() const {
std::shared_lock<std::shared_mutex> lock(mutex_);
auto typeId = std::type_index(typeid(T));
for (const auto& entry : services_) {
if (entry.id == typeId) {
return true;
}
}
return false;
}
// ========== 生命周期控制 ==========
/**
* @brief
* @return true
*/
bool init();
/**
* @brief
* @param dt
*/
void update(f32 dt);
/**
* @brief
*/
void pause();
/**
* @brief
*/
void resume();
/**
* @brief
*/
void shutdown();
/**
* @brief
*/
void clear();
// ========== 配置接口 ==========
/**
* @brief Application
* @param app Application
*/
void setApp(Application* app) { app_ = app; }
// ========== 查询接口 ==========
/**
* @brief
* @return
*/
size_t size() const {
std::shared_lock<std::shared_mutex> lock(mutex_);
return modules_.size() + services_.size();
}
/**
* @brief
* @return
*/
size_t moduleCount() const {
std::shared_lock<std::shared_mutex> lock(mutex_);
return modules_.size();
}
/**
* @brief
* @return
*/
size_t serviceCount() const {
std::shared_lock<std::shared_mutex> lock(mutex_);
return services_.size();
}
private:
Lifecycle() = default;
~Lifecycle() = default;
/**
* @brief
*/
struct UnitIndex {
UnitType type;
size_t index;
};
/**
* @brief
*/
struct ModuleEntry {
TypeId id = 0;
Unique<Module> module;
};
/**
* @brief
*/
struct ServiceEntry {
std::type_index id;
Ref<IService> service;
ServiceEntry() : id(typeid(void)) {}
};
/**
* @brief
*/
std::vector<std::vector<UnitIndex>> groupByLevel();
/**
* @brief
* @param type
* @return SIZE_MAX
*/
size_t findModuleIndex(std::type_index type) const;
/**
* @brief
* @param type
* @return SIZE_MAX
*/
size_t findServiceIndex(std::type_index type) const;
std::vector<ModuleEntry> modules_;
std::vector<ServiceEntry> services_;
mutable std::shared_mutex mutex_;
Application* app_ = nullptr;
};
} // namespace extra2d

View File

@ -1,9 +1,8 @@
#pragma once
#include <extra2d/core/types.h>
#include <string>
#include <vector>
#include <typeindex>
#include <vector>
namespace extra2d {
@ -52,6 +51,12 @@ public:
*/
virtual std::vector<std::type_index> deps() const { return {}; }
/**
* @brief
* @return
*/
virtual std::vector<std::type_index> needsServices() const { return {}; }
/**
* @brief
* @return true

View File

@ -1,166 +0,0 @@
#pragma once
#include <array>
#include <extra2d/core/module.h>
#include <extra2d/core/types.h>
#include <typeindex>
#include <vector>
namespace extra2d {
class Application;
/**
* @brief ID生成器
*/
using TypeId = size_t;
namespace detail {
inline TypeId nextTypeId() {
static TypeId id = 0;
return ++id;
}
template <typename T> inline TypeId getTypeId() {
static TypeId id = nextTypeId();
return id;
}
} // namespace detail
/**
* @brief
*
*/
class Registry {
public:
static constexpr size_t MAX_MODULES = 64;
static Registry &instance();
Registry(const Registry &) = delete;
Registry &operator=(const Registry &) = delete;
/**
* @brief
* @tparam T
* @tparam Args
* @param args
* @return
*/
template <typename T, typename... Args> T *use(Args &&...args) {
static_assert(std::is_base_of_v<Module, T>, "T must derive from Module");
TypeId typeId = detail::getTypeId<T>();
// 数组查找O(n) 但 n 很小,缓存友好
for (size_t i = 0; i < moduleCount_; ++i) {
if (modules_[i].id == typeId) {
return static_cast<T *>(modules_[i].module.get());
}
}
// 添加新模块
if (moduleCount_ >= MAX_MODULES) {
return nullptr; // 模块数量超过上限
}
auto module = ptr::unique<T>(std::forward<Args>(args)...);
T *ptr = module.get();
module->setApp(app_);
modules_[moduleCount_].id = typeId;
modules_[moduleCount_].module = std::move(module);
modules_[moduleCount_].valid = true;
++moduleCount_;
return ptr;
}
/**
* @brief
* @tparam T
* @return nullptr
*/
template <typename T> T *get() const {
TypeId typeId = detail::getTypeId<T>();
for (size_t i = 0; i < moduleCount_; ++i) {
if (modules_[i].id == typeId && modules_[i].valid) {
return static_cast<T *>(modules_[i].module.get());
}
}
return nullptr;
}
/**
* @brief
* @param typeIdx
* @return
*/
Module *get(std::type_index typeIdx) const {
for (size_t i = 0; i < moduleCount_; ++i) {
if (modules_[i].valid) {
Module *mod = modules_[i].module.get();
if (std::type_index(typeid(*mod)) == typeIdx) {
return mod;
}
}
}
return nullptr;
}
/**
* @brief Application
*/
void setApp(Application *app) { app_ = app; }
/**
* @brief
* @return true
*/
bool init();
/**
* @brief
*/
void shutdown();
/**
* @brief
*/
void clear();
/**
* @brief
*/
size_t size() const { return moduleCount_; }
private:
Registry() = default;
~Registry() = default;
struct ModuleEntry {
TypeId id = 0;
Unique<Module> module;
bool valid = false;
};
/**
* @brief
* @return
*/
std::vector<Module *> sort();
/**
* @brief
*
* @return
*/
std::vector<std::vector<Module *>> group();
std::array<ModuleEntry, MAX_MODULES> modules_;
size_t moduleCount_ = 0;
Application *app_ = nullptr;
};
} // namespace extra2d

View File

@ -1,398 +0,0 @@
#pragma once
#include <extra2d/core/types.h>
#include <string>
#include <variant>
namespace extra2d {
/**
* @brief
*/
enum class ErrorCode {
None = 0,
Unknown = 1,
InvalidArgument = 2,
OutOfMemory = 3,
FileNotFound = 4,
PermissionDenied = 5,
NotImplemented = 6,
AlreadyExists = 7,
NotInitialized = 8,
AlreadyInitialized = 9,
OperationFailed = 10,
Timeout = 11,
Cancelled = 12,
InvalidState = 13,
ResourceExhausted = 14,
Unavailable = 15,
DataLoss = 16,
Unauthenticated = 17,
PermissionDenied2 = 18,
ResourceNotFound = 19,
Aborted = 20,
OutOfRange = 21,
Unimplemented = 22,
Internal = 23,
DataCorrupted = 24,
RequestTooLarge = 25,
ResourceBusy = 26,
QuotaExceeded = 27,
DeadlineExceeded = 28,
LoadBalancing = 29,
NetworkError = 30,
ProtocolError = 31,
ServiceUnavailable = 32,
GatewayError = 33,
RateLimited = 34,
BadRequest = 35,
Unauthorized = 36,
Forbidden = 37,
NotFound = 38,
MethodNotAllowed = 39,
Conflict = 40,
Gone = 41,
LengthRequired = 42,
PreconditionFailed = 43,
PayloadTooLarge = 44,
UriTooLong = 45,
UnsupportedMediaType = 46,
RangeNotSatisfiable = 47,
ExpectationFailed = 48,
ImATeapot = 49,
MisdirectedRequest = 50,
UnprocessableEntity = 51,
Locked = 52,
FailedDependency = 53,
TooEarly = 54,
UpgradeRequired = 55,
PreconditionRequired = 56,
TooManyRequests = 57,
RequestHeaderFieldsTooLarge = 58,
UnavailableForLegalReasons = 59
};
/**
* @brief
*/
struct Error {
ErrorCode code = ErrorCode::None;
std::string message;
std::string file;
int line = 0;
Error() = default;
Error(ErrorCode c, const std::string& msg) : code(c), message(msg) {}
Error(ErrorCode c, const std::string& msg, const std::string& f, int l)
: code(c), message(msg), file(f), line(l) {}
bool ok() const { return code == ErrorCode::None; }
static Error none() { return Error(); }
static Error unknown(const std::string& msg) { return Error(ErrorCode::Unknown, msg); }
static Error invalidArgument(const std::string& msg) { return Error(ErrorCode::InvalidArgument, msg); }
static Error outOfMemory(const std::string& msg) { return Error(ErrorCode::OutOfMemory, msg); }
static Error fileNotFound(const std::string& msg) { return Error(ErrorCode::FileNotFound, msg); }
static Error permissionDenied(const std::string& msg) { return Error(ErrorCode::PermissionDenied, msg); }
static Error notImplemented(const std::string& msg) { return Error(ErrorCode::NotImplemented, msg); }
static Error alreadyExists(const std::string& msg) { return Error(ErrorCode::AlreadyExists, msg); }
static Error notInitialized(const std::string& msg) { return Error(ErrorCode::NotInitialized, msg); }
static Error alreadyInitialized(const std::string& msg) { return Error(ErrorCode::AlreadyInitialized, msg); }
static Error operationFailed(const std::string& msg) { return Error(ErrorCode::OperationFailed, msg); }
static Error timeout(const std::string& msg) { return Error(ErrorCode::Timeout, msg); }
static Error cancelled(const std::string& msg) { return Error(ErrorCode::Cancelled, msg); }
static Error invalidState(const std::string& msg) { return Error(ErrorCode::InvalidState, msg); }
static Error resourceExhausted(const std::string& msg) { return Error(ErrorCode::ResourceExhausted, msg); }
static Error unavailable(const std::string& msg) { return Error(ErrorCode::Unavailable, msg); }
static Error dataLoss(const std::string& msg) { return Error(ErrorCode::DataLoss, msg); }
static Error unauthenticated(const std::string& msg) { return Error(ErrorCode::Unauthenticated, msg); }
static Error permissionDenied2(const std::string& msg) { return Error(ErrorCode::PermissionDenied2, msg); }
static Error resourceNotFound(const std::string& msg) { return Error(ErrorCode::ResourceNotFound, msg); }
static Error aborted(const std::string& msg) { return Error(ErrorCode::Aborted, msg); }
static Error outOfRange(const std::string& msg) { return Error(ErrorCode::OutOfRange, msg); }
static Error unimplemented(const std::string& msg) { return Error(ErrorCode::Unimplemented, msg); }
static Error internal(const std::string& msg) { return Error(ErrorCode::Internal, msg); }
static Error dataCorrupted(const std::string& msg) { return Error(ErrorCode::DataCorrupted, msg); }
static Error requestTooLarge(const std::string& msg) { return Error(ErrorCode::RequestTooLarge, msg); }
static Error resourceBusy(const std::string& msg) { return Error(ErrorCode::ResourceBusy, msg); }
static Error quotaExceeded(const std::string& msg) { return Error(ErrorCode::QuotaExceeded, msg); }
static Error deadlineExceeded(const std::string& msg) { return Error(ErrorCode::DeadlineExceeded, msg); }
static Error loadBalancing(const std::string& msg) { return Error(ErrorCode::LoadBalancing, msg); }
static Error networkError(const std::string& msg) { return Error(ErrorCode::NetworkError, msg); }
static Error protocolError(const std::string& msg) { return Error(ErrorCode::ProtocolError, msg); }
static Error serviceUnavailable(const std::string& msg) { return Error(ErrorCode::ServiceUnavailable, msg); }
static Error gatewayError(const std::string& msg) { return Error(ErrorCode::GatewayError, msg); }
static Error rateLimited(const std::string& msg) { return Error(ErrorCode::RateLimited, msg); }
static Error badRequest(const std::string& msg) { return Error(ErrorCode::BadRequest, msg); }
static Error unauthorized(const std::string& msg) { return Error(ErrorCode::Unauthorized, msg); }
static Error forbidden(const std::string& msg) { return Error(ErrorCode::Forbidden, msg); }
static Error notFound(const std::string& msg) { return Error(ErrorCode::NotFound, msg); }
static Error methodNotAllowed(const std::string& msg) { return Error(ErrorCode::MethodNotAllowed, msg); }
static Error conflict(const std::string& msg) { return Error(ErrorCode::Conflict, msg); }
static Error gone(const std::string& msg) { return Error(ErrorCode::Gone, msg); }
static Error lengthRequired(const std::string& msg) { return Error(ErrorCode::LengthRequired, msg); }
static Error preconditionFailed(const std::string& msg) { return Error(ErrorCode::PreconditionFailed, msg); }
static Error payloadTooLarge(const std::string& msg) { return Error(ErrorCode::PayloadTooLarge, msg); }
static Error uriTooLong(const std::string& msg) { return Error(ErrorCode::UriTooLong, msg); }
static Error unsupportedMediaType(const std::string& msg) { return Error(ErrorCode::UnsupportedMediaType, msg); }
static Error rangeNotSatisfiable(const std::string& msg) { return Error(ErrorCode::RangeNotSatisfiable, msg); }
static Error expectationFailed(const std::string& msg) { return Error(ErrorCode::ExpectationFailed, msg); }
static Error imATeapot(const std::string& msg) { return Error(ErrorCode::ImATeapot, msg); }
static Error misdirectedRequest(const std::string& msg) { return Error(ErrorCode::MisdirectedRequest, msg); }
static Error unprocessableEntity(const std::string& msg) { return Error(ErrorCode::UnprocessableEntity, msg); }
static Error locked(const std::string& msg) { return Error(ErrorCode::Locked, msg); }
static Error failedDependency(const std::string& msg) { return Error(ErrorCode::FailedDependency, msg); }
static Error tooEarly(const std::string& msg) { return Error(ErrorCode::TooEarly, msg); }
static Error upgradeRequired(const std::string& msg) { return Error(ErrorCode::UpgradeRequired, msg); }
static Error preconditionRequired(const std::string& msg) { return Error(ErrorCode::PreconditionRequired, msg); }
static Error tooManyRequests(const std::string& msg) { return Error(ErrorCode::TooManyRequests, msg); }
static Error requestHeaderFieldsTooLarge(const std::string& msg) { return Error(ErrorCode::RequestHeaderFieldsTooLarge, msg); }
static Error unavailableForLegalReasons(const std::string& msg) { return Error(ErrorCode::UnavailableForLegalReasons, msg); }
};
/**
* @brief Result类型
* @tparam T
* @tparam E Error
*/
template<typename T, typename E = Error>
class Result {
public:
Result() : hasValue_(false) {
new (&storage_.error) E();
}
~Result() {
if (hasValue_) {
storage_.value.~T();
} else {
storage_.error.~E();
}
}
Result(const Result& other) : hasValue_(other.hasValue_) {
if (hasValue_) {
new (&storage_.value) T(other.storage_.value);
} else {
new (&storage_.error) E(other.storage_.error);
}
}
Result(Result&& other) noexcept : hasValue_(other.hasValue_) {
if (hasValue_) {
new (&storage_.value) T(std::move(other.storage_.value));
} else {
new (&storage_.error) E(std::move(other.storage_.error));
}
}
Result& operator=(const Result& other) {
if (this != &other) {
this->~Result();
hasValue_ = other.hasValue_;
if (hasValue_) {
new (&storage_.value) T(other.storage_.value);
} else {
new (&storage_.error) E(other.storage_.error);
}
}
return *this;
}
Result& operator=(Result&& other) noexcept {
if (this != &other) {
this->~Result();
hasValue_ = other.hasValue_;
if (hasValue_) {
new (&storage_.value) T(std::move(other.storage_.value));
} else {
new (&storage_.error) E(std::move(other.storage_.error));
}
}
return *this;
}
static Result<T, E> ok(T value) {
Result<T, E> result;
result.hasValue_ = true;
new (&result.storage_.value) T(std::move(value));
return result;
}
static Result<T, E> err(E error) {
Result<T, E> result;
result.hasValue_ = false;
new (&result.storage_.error) E(std::move(error));
return result;
}
bool ok() const { return hasValue_; }
bool isOk() const { return hasValue_; }
bool isErr() const { return !hasValue_; }
T& value() & {
return storage_.value;
}
const T& value() const & {
return storage_.value;
}
T&& value() && {
return std::move(storage_.value);
}
E& error() & {
return storage_.error;
}
const E& error() const & {
return storage_.error;
}
E&& error() && {
return std::move(storage_.error);
}
T valueOr(T defaultValue) const {
return hasValue_ ? storage_.value : std::move(defaultValue);
}
template<typename F>
Result<T, E> map(F&& f) {
if (hasValue_) {
return Result<T, E>::ok(f(storage_.value));
}
return *this;
}
template<typename F>
Result<T, E> mapErr(F&& f) {
if (!hasValue_) {
return Result<T, E>::err(f(storage_.error));
}
return *this;
}
template<typename F>
auto andThen(F&& f) -> decltype(f(std::declval<T>())) {
if (hasValue_) {
return f(storage_.value);
}
return Result<typename decltype(f(std::declval<T>()))::ValueType, E>::err(storage_.error);
}
template<typename F>
Result<T, E> orElse(F&& f) {
if (!hasValue_) {
return f(storage_.error);
}
return *this;
}
private:
union Storage {
T value;
E error;
Storage() {}
~Storage() {}
} storage_;
bool hasValue_;
};
// 特化void类型
template<typename E>
class Result<void, E> {
public:
Result() : hasValue_(true) {}
~Result() {
if (!hasValue_) {
storage_.error.~E();
}
}
Result(const Result& other) : hasValue_(other.hasValue_) {
if (!hasValue_) {
new (&storage_.error) E(other.storage_.error);
}
}
Result(Result&& other) noexcept : hasValue_(other.hasValue_) {
if (!hasValue_) {
new (&storage_.error) E(std::move(other.storage_.error));
}
}
Result& operator=(const Result& other) {
if (this != &other) {
this->~Result();
hasValue_ = other.hasValue_;
if (!hasValue_) {
new (&storage_.error) E(other.storage_.error);
}
}
return *this;
}
Result& operator=(Result&& other) noexcept {
if (this != &other) {
this->~Result();
hasValue_ = other.hasValue_;
if (!hasValue_) {
new (&storage_.error) E(std::move(other.storage_.error));
}
}
return *this;
}
static Result<void, E> ok() {
return Result<void, E>();
}
static Result<void, E> err(E error) {
Result<void, E> result;
result.hasValue_ = false;
new (&result.storage_.error) E(std::move(error));
return result;
}
bool ok() const { return hasValue_; }
bool isOk() const { return hasValue_; }
bool isErr() const { return !hasValue_; }
E& error() & {
return storage_.error;
}
const E& error() const & {
return storage_.error;
}
E&& error() && {
return std::move(storage_.error);
}
private:
union Storage {
E error;
Storage() {}
~Storage() {}
} storage_;
bool hasValue_;
};
// 便捷宏
#define E2D_TRY(result) \
do { \
auto _res = (result); \
if (!_res.ok()) { \
return Result<decltype(_res)::ValueType, decltype(_res)::ErrorType>::err(_res.error()); \
} \
} while(0)
} // namespace extra2d

View File

@ -2,6 +2,8 @@
#include <extra2d/core/types.h>
#include <string>
#include <typeindex>
#include <vector>
namespace extra2d {
@ -48,6 +50,7 @@ struct ServiceInfo {
*/
class IService {
friend class ServiceLocator;
friend class Lifecycle;
public:
virtual ~IService() = default;
@ -69,6 +72,18 @@ public:
*/
virtual void shutdown() = 0;
/**
* @brief
* @return
*/
virtual std::vector<std::type_index> deps() const { return {}; }
/**
* @brief
* @return
*/
virtual std::vector<std::type_index> needsModules() const { return {}; }
/**
* @brief
*/

View File

@ -1,307 +0,0 @@
#pragma once
#include <algorithm>
#include <extra2d/core/service_interface.h>
#include <extra2d/core/types.h>
#include <functional>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <typeindex>
#include <unordered_map>
#include <vector>
namespace extra2d {
/**
* @brief
*/
template <typename T> using ServiceFactory = Fn<Ref<T>()>;
/**
* @brief
*
*
*
* -
* -
* -
* - 线
* - Mock
*/
class ServiceLocator {
public:
/**
* @brief
* @return
*/
static ServiceLocator &instance();
ServiceLocator(const ServiceLocator &) = delete;
ServiceLocator &operator=(const ServiceLocator &) = delete;
/**
* @brief
* @tparam T
* @param svc
*/
template <typename T> void add(Ref<T> svc) {
static_assert(std::is_base_of_v<IService, T>,
"T must derive from IService");
std::unique_lock<std::shared_mutex> lock(mutex_);
auto typeId = std::type_index(typeid(T));
services_[typeId] = std::static_pointer_cast<IService>(svc);
orderedServices_.push_back(svc);
sort();
}
/**
* @brief
* @tparam T
* @param fn
*/
template <typename T> void setFactory(ServiceFactory<T> fn) {
static_assert(std::is_base_of_v<IService, T>,
"T must derive from IService");
std::unique_lock<std::shared_mutex> lock(mutex_);
auto typeId = std::type_index(typeid(T));
factories_[typeId] = [fn]() -> Ref<IService> {
return std::static_pointer_cast<IService>(fn());
};
// 立即创建服务实例并添加到有序列表
auto svc = factories_[typeId]();
services_[typeId] = svc;
orderedServices_.push_back(svc);
sort();
}
/**
* @brief
* @tparam T
* @return nullptr
*/
template <typename T> Ref<T> get() const {
static_assert(std::is_base_of_v<IService, T>,
"T must derive from IService");
auto typeId = std::type_index(typeid(T));
// 读锁查询
std::shared_lock<std::shared_mutex> lock(mutex_);
auto it = services_.find(typeId);
if (it != services_.end()) {
return std::static_pointer_cast<T>(it->second);
}
auto factoryIt = factories_.find(typeId);
if (factoryIt != factories_.end()) {
auto svc = factoryIt->second();
services_[typeId] = svc;
return std::static_pointer_cast<T>(svc);
}
return nullptr;
}
/**
* @brief
* @tparam T
* @return nullptr
*/
template <typename T> Ref<T> tryGet() const {
static_assert(std::is_base_of_v<IService, T>,
"T must derive from IService");
auto typeId = std::type_index(typeid(T));
// 读锁查询
std::shared_lock<std::shared_mutex> lock(mutex_);
auto it = services_.find(typeId);
if (it != services_.end()) {
return std::static_pointer_cast<T>(it->second);
}
return nullptr;
}
/**
* @brief
* @tparam T
* @return true
*/
template <typename T> bool has() const {
std::shared_lock<std::shared_mutex> lock(mutex_);
auto typeId = std::type_index(typeid(T));
return services_.find(typeId) != services_.end() ||
factories_.find(typeId) != factories_.end();
}
/**
* @brief
* @tparam T
*/
template <typename T> void remove() {
std::unique_lock<std::shared_mutex> lock(mutex_);
auto typeId = std::type_index(typeid(T));
auto it = services_.find(typeId);
if (it != services_.end()) {
auto svc = it->second;
services_.erase(it);
auto orderIt =
std::find(orderedServices_.begin(), orderedServices_.end(), svc);
if (orderIt != orderedServices_.end()) {
orderedServices_.erase(orderIt);
}
}
factories_.erase(typeId);
}
/**
* @brief
* @return true
*/
bool init();
/**
* @brief
*/
void shutdown();
/**
* @brief
* @param dt
*/
void update(f32 dt);
/**
* @brief
*/
void pause();
/**
* @brief
*/
void resume();
/**
* @brief
* @return
*/
std::vector<Ref<IService>> all() const;
/**
* @brief
*/
void clear();
/**
* @brief
* @return
*/
size_t size() const { return services_.size(); }
private:
ServiceLocator() = default;
~ServiceLocator() = default;
/**
* @brief
*/
void sort();
mutable std::unordered_map<std::type_index, Ref<IService>> services_;
std::unordered_map<std::type_index, std::function<Ref<IService>()>>
factories_;
std::vector<Ref<IService>> orderedServices_;
mutable std::shared_mutex mutex_;
};
/**
* @brief
*
*/
template <typename Interface, typename Implementation> class ServiceRegistrar {
public:
explicit ServiceRegistrar(ServiceFactory<Interface> fn = nullptr) {
if (fn) {
ServiceLocator::instance().setFactory<Interface>(fn);
} else {
ServiceLocator::instance().setFactory<Interface>(
[]() -> Ref<Interface> {
return ptr::make<Implementation>();
});
}
}
};
/**
* @brief
* 使
*
*/
template <typename Interface, typename Implementation> struct ServiceAutoReg {
/**
* @brief 访
*/
static const bool registered;
/**
* @brief
* @return true
*/
static bool doRegister() {
::extra2d::ServiceLocator::instance().setFactory<Interface>(
[]() -> ::extra2d::Ref<Interface> {
return ::extra2d::ptr::make<Implementation>();
});
return true;
}
};
// 静态成员定义,在此处触发注册
template <typename Interface, typename Implementation>
const bool ServiceAutoReg<Interface, Implementation>::registered =
ServiceAutoReg<Interface, Implementation>::doRegister();
/**
* @brief
*/
template <typename Interface> struct ServiceAutoRegFactory {
template <typename Factory> struct Impl {
static const bool registered;
static bool doRegister(Factory fn) {
::extra2d::ServiceLocator::instance().setFactory<Interface>(fn);
return true;
}
};
};
template <typename Interface>
template <typename Factory>
const bool ServiceAutoRegFactory<Interface>::Impl<Factory>::registered =
ServiceAutoRegFactory<Interface>::Impl<Factory>::doRegister(Factory{});
/**
* @brief
* 使
*
*/
#define E2D_AUTO_REGISTER_SERVICE(Interface, Implementation) \
static inline const bool E2D_CONCAT(_service_reg_, __LINE__) = \
ServiceAutoReg<Interface, Implementation>::registered
/**
* @brief
*/
#define E2D_AUTO_REGISTER_SERVICE_FACTORY(Interface, Factory) \
static inline const bool E2D_CONCAT(_service_factory_reg_, __LINE__) = \
ServiceAutoRegFactory<Interface>::Impl<Factory>::registered
} // namespace extra2d

View File

@ -1,137 +0,0 @@
#pragma once
#include <extra2d/core/service_interface.h>
#include <extra2d/core/service_locator.h>
#include <functional>
#include <vector>
#include <string>
namespace extra2d {
/**
* @brief
*/
struct ServiceRegistration {
std::string name;
ServicePriority priority;
std::function<Ref<IService>()> factory;
bool enabled = true;
};
/**
* @brief
*
*/
class ServiceRegistry {
public:
/**
* @brief
* @return
*/
static ServiceRegistry& instance();
ServiceRegistry(const ServiceRegistry&) = delete;
ServiceRegistry& operator=(const ServiceRegistry&) = delete;
/**
* @brief
* @tparam T
* @tparam Impl
* @param name
* @param priority
*/
template<typename T, typename Impl>
void add(const std::string& name, ServicePriority priority) {
static_assert(std::is_base_of_v<IService, T>,
"T must derive from IService");
static_assert(std::is_base_of_v<T, Impl>,
"Impl must derive from T");
ServiceRegistration reg;
reg.name = name;
reg.priority = priority;
reg.factory = []() -> Ref<IService> {
return std::static_pointer_cast<IService>(ptr::make<Impl>());
};
registrations_.push_back(reg);
}
/**
* @brief
* @tparam T
* @param name
* @param priority
* @param factory
*/
template<typename T>
void addWithFactory(
const std::string& name,
ServicePriority priority,
std::function<Ref<T>()> factory) {
static_assert(std::is_base_of_v<IService, T>,
"T must derive from IService");
ServiceRegistration reg;
reg.name = name;
reg.priority = priority;
reg.factory = [factory]() -> Ref<IService> {
return std::static_pointer_cast<IService>(factory());
};
registrations_.push_back(reg);
}
/**
* @brief /
* @param name
* @param enabled
*/
void setEnabled(const std::string& name, bool enabled);
/**
* @brief
* ServiceLocator
*/
void createAll();
/**
* @brief
* @return
*/
const std::vector<ServiceRegistration>& all() const {
return registrations_;
}
/**
* @brief
*/
void clear() {
registrations_.clear();
}
private:
ServiceRegistry() = default;
~ServiceRegistry() = default;
std::vector<ServiceRegistration> registrations_;
};
/**
* @brief
* 使
*/
template<typename Interface, typename Implementation>
class AutoServiceRegistrar {
public:
AutoServiceRegistrar(const std::string& name, ServicePriority priority) {
ServiceRegistry::instance().add<Interface, Implementation>(
name, priority);
}
};
}
#define E2D_REGISTER_SERVICE_AUTO(Interface, Implementation, Name, Priority) \
namespace { \
static ::extra2d::AutoServiceRegistrar<Interface, Implementation> \
E2D_CONCAT(auto_service_registrar_, __LINE__)(Name, Priority); \
}

View File

@ -5,14 +5,15 @@
// Core
#include <extra2d/core/color.h>
#include <extra2d/core/lifecycle.h>
#include <extra2d/core/math_types.h>
#include <extra2d/core/module.h>
#include <extra2d/core/registry.h>
#include <extra2d/core/types.h>
// Window
#include <extra2d/window/keys.h>
#include <extra2d/window/window.h>
#include <extra2d/window/window_module.h>
#include <extra2d/window/event_converter.h>
// Window - SDL2 + OpenGL
@ -21,6 +22,7 @@
#include <extra2d/render/buffer.h>
#include <extra2d/render/render_context.h>
#include <extra2d/render/render_device.h>
#include <extra2d/render/render_module.h>
#include <extra2d/render/render_queue.h>
#include <extra2d/render/render_stats.h>
#include <extra2d/render/render_types.h>

View File

@ -0,0 +1,129 @@
#pragma once
#include <extra2d/core/module.h>
#include <extra2d/render/render_device.h>
#include <extra2d/services/logger_service.h>
#include <extra2d/window/window_module.h>
#include <functional>
#include <typeindex>
namespace extra2d {
/**
* @brief
*/
struct RenderCfg {
int glMajor = 4;
int glMinor = 5;
bool useES = false;
int redBits = 8;
int greenBits = 8;
int blueBits = 8;
int alphaBits = 8;
int depthBits = 24;
int stencilBits = 8;
bool doubleBuffer = true;
int msaaSamples = 0;
bool vsync = true;
int priority = 10;
RenderCfg() = default;
};
/**
* @brief
* OpenGL
*/
class RenderModule : public Module {
public:
/**
* @brief Lambda
* @param configFn
*/
explicit RenderModule(std::function<void(RenderCfg &)> configFn);
/**
* @brief
*/
~RenderModule() override;
/**
* @brief
* @return true
*/
bool init() override;
/**
* @brief
*/
void shutdown() override;
/**
* @brief
* @return true
*/
bool ok() const override { return initialized_; }
/**
* @brief
* @return
*/
const char *name() const override { return "RenderModule"; }
/**
* @brief
* @return
*/
int priority() const override { return cfg_.priority; }
/**
* @brief
* @return WindowModule
*/
std::vector<std::type_index> deps() const override {
return {std::type_index(typeid(WindowModule))};
}
/**
* @brief
* @return ILogger
*/
std::vector<std::type_index> needsServices() const override {
return {std::type_index(typeid(ILogger))};
}
/**
* @brief OpenGL
* @return false
*/
bool parallel() const override { return false; }
/**
* @brief
*/
void swapBuffers();
/**
* @brief VSync
* @param enabled
*/
void setVSync(bool enabled);
/**
* @brief
* @return
*/
RenderDevice &device() { return RenderDevice::instance(); }
/**
* @brief
* @return
*/
const RenderCaps &caps() const { return RenderDevice::instance().caps(); }
private:
RenderCfg cfg_;
bool initialized_ = false;
};
} // namespace extra2d

View File

@ -9,8 +9,8 @@
#include <extra2d/asset/asset_types.h>
#include <extra2d/asset/data_processor.h>
#include <extra2d/core/service_interface.h>
#include <extra2d/core/service_locator.h>
#include <extra2d/core/types.h>
#include <extra2d/services/logger_service.h>
#include <functional>
#include <future>
#include <memory>
@ -232,6 +232,13 @@ public:
return i;
}
/**
* @brief
*/
std::vector<std::type_index> deps() const override {
return { std::type_index(typeid(ILogger)) };
}
bool init() override;
void shutdown() override;
@ -327,8 +334,6 @@ private:
* @return
*/
std::type_index inferType(const std::string &path);
E2D_AUTO_REGISTER_SERVICE(IAssetService, AssetService);
};
} // namespace extra2d

View File

@ -1,9 +1,13 @@
#pragma once
#include <extra2d/core/service_interface.h>
#include <extra2d/core/service_locator.h>
#include <extra2d/core/types.h>
#include <extra2d/event/event_dispatcher.h>
#include <extra2d/event/event_queue.h>
#include <extra2d/services/logger_service.h>
#include <extra2d/window/window_module.h>
#include <typeindex>
#include <vector>
namespace extra2d {
@ -41,6 +45,20 @@ public:
ServiceInfo info() const override;
/**
* @brief
*/
std::vector<std::type_index> deps() const override {
return {std::type_index(typeid(ILogger))};
}
/**
* @brief
*/
std::vector<std::type_index> needsModules() const override {
return {std::type_index(typeid(WindowModule))};
}
bool init() override;
void shutdown() override;
void update(f32 dt) override;
@ -69,9 +87,6 @@ public:
private:
EventQueue queue_;
EventDispatcher dispatcher_;
// 服务注册元数据
E2D_AUTO_REGISTER_SERVICE(IEventService, EventService);
};
}
} // namespace extra2d

View File

@ -1,7 +1,7 @@
#pragma once
#include <extra2d/core/lifecycle.h>
#include <extra2d/core/service_interface.h>
#include <extra2d/core/service_locator.h>
#include <extra2d/core/types.h>
#include <string>
#include <type_traits>
@ -74,6 +74,11 @@ public:
i.priority = ServicePriority::Core;
return i;
}
/**
* @brief
*/
std::vector<std::type_index> deps() const override { return {}; }
};
/**
@ -117,8 +122,6 @@ private:
LogColor levelColors_[7];
class Impl;
Unique<Impl> impl_;
E2D_AUTO_REGISTER_SERVICE(ILogger, ConsoleLogger);
};
} // namespace extra2d
@ -173,16 +176,16 @@ inline std::string format_str(const char *fmt) { return fmt; }
// 日志宏
#define E2D_LOG(lvl, ...) \
do { \
if (auto log = ::extra2d::ServiceLocator::instance() \
.tryGet<::extra2d::ILogger>()) \
if (auto log = \
::extra2d::Lifecycle::instance().service<::extra2d::ILogger>()) \
if (log->enabled(lvl)) \
log->log(lvl, ::extra2d::format_str(__VA_ARGS__)); \
} while (0)
#define E2D_LOG_CAT(lvl, cat, ...) \
do { \
if (auto log = ::extra2d::ServiceLocator::instance() \
.tryGet<::extra2d::ILogger>()) \
if (auto log = \
::extra2d::Lifecycle::instance().service<::extra2d::ILogger>()) \
if (log->enabled(lvl)) { \
std::string _e2d_msg = ::extra2d::format_str(__VA_ARGS__); \
log->log(lvl, ::extra2d::format_str("[{}] {}", cat, _e2d_msg)); \

View File

@ -1,8 +1,11 @@
#pragma once
#include <extra2d/core/service_interface.h>
#include <extra2d/core/service_locator.h>
#include <extra2d/core/types.h>
#include <extra2d/services/logger_service.h>
#include <extra2d/utils/timer.h>
#include <typeindex>
#include <vector>
namespace extra2d {
@ -32,6 +35,13 @@ public:
ServiceInfo info() const override;
/**
* @brief
*/
std::vector<std::type_index> deps() const override {
return { std::type_index(typeid(ILogger)) };
}
bool init() override;
void shutdown() override;
void update(f32 dt) override;
@ -49,9 +59,6 @@ public:
private:
TimerManager mgr_;
// 服务注册元数据
E2D_AUTO_REGISTER_SERVICE(ITimerService, TimerService);
};
}

View File

@ -8,6 +8,9 @@
namespace extra2d {
/**
* @brief
*/
struct WindowConfig {
std::string title = "Extra2D Application";
int width = 1280;

View File

@ -0,0 +1,164 @@
#pragma once
#include <extra2d/core/module.h>
#include <extra2d/services/logger_service.h>
#include <extra2d/window/window.h>
#include <functional>
#include <string>
#include <typeindex>
namespace extra2d {
/**
* @brief
*/
struct WindowCfg {
std::string title = "Extra2D";
int width = 1280;
int height = 720;
bool fullscreen = false;
bool resizable = true;
bool centerWindow = true;
int priority = 0;
WindowCfg() = default;
};
/**
* @brief
*
*/
class WindowModule : public Module {
public:
/**
* @brief Lambda
* @param configFn
*/
explicit WindowModule(std::function<void(WindowCfg &)> configFn);
/**
* @brief
*/
~WindowModule() override;
/**
* @brief
* @return true
*/
bool init() override;
/**
* @brief
*/
void shutdown() override;
/**
* @brief
* @return true
*/
bool ok() const override { return initialized_; }
/**
* @brief
* @return
*/
const char *name() const override { return "WindowModule"; }
/**
* @brief
* @return
*/
int priority() const override { return cfg_.priority; }
/**
* @brief
* @return ILogger
*/
std::vector<std::type_index> needsServices() const override {
return {std::type_index(typeid(ILogger))};
}
/**
* @brief SDL
* @return false
*/
bool parallel() const override { return false; }
/**
* @brief
*/
void poll();
/**
* @brief
* @return true
*/
bool shouldClose() const;
/**
* @brief
*/
void close();
/**
* @brief
* @param title
*/
void setTitle(const std::string &title);
/**
* @brief
* @param width
* @param height
*/
void setSize(int width, int height);
/**
* @brief
* @param fullscreen
*/
void setFullscreen(bool fullscreen);
/**
* @brief
* @return
*/
int width() const;
/**
* @brief
* @return
*/
int height() const;
/**
* @brief
* @return true
*/
bool fullscreen() const;
/**
* @brief
* @param cb
*/
void onEvent(std::function<void(const SDL_Event &)> cb);
/**
* @brief
* @return SDL
*/
SDL_Window *native() const;
/**
* @brief
* @return
*/
Window *win() const { return window_.get(); }
private:
WindowCfg cfg_;
Unique<Window> window_;
bool initialized_ = false;
};
} // namespace extra2d

View File

@ -1,14 +1,17 @@
#include <extra2d/app/application.h>
#include <extra2d/render/render_device.h>
#include <extra2d/core/lifecycle.h>
#include <extra2d/render/render_module.h>
#include <extra2d/services/event_service.h>
#include <extra2d/services/logger_service.h>
#include <extra2d/window/event_converter.h>
#include <extra2d/window/window.h>
#include <extra2d/window/window_module.h>
#include <SDL.h>
namespace extra2d {
Application::Application() { Lifecycle::instance().setApp(this); }
Application &Application::instance() {
static Application app;
return app;
@ -20,37 +23,24 @@ bool Application::init() {
if (initialized_)
return true;
// 先初始化服务定位器(包括日志服务)
ServiceLocator::instance().init();
E2D_INFO(CAT_APP, "应用程序初始化中:{}", name);
window_ = new Window();
if (!window_->create({.title = name, .width = 1280, .height = 720})) {
E2D_ERROR(CAT_APP, "创建窗口失败");
delete window_;
window_ = nullptr;
if (!Lifecycle::instance().init()) {
E2D_ERROR(CAT_APP, "初始化失败");
return false;
}
// 设置事件回调,将 SDL 事件转换为 Extra2D 事件
window_->onEvent([](const SDL_Event &e) {
auto *winMod = module<WindowModule>();
if (winMod && winMod->win()) {
winMod->onEvent([](const SDL_Event &e) {
Event event = EventConverter::convert(e);
if (event.type != EventType::None) {
auto eventService = ServiceLocator::instance().get<IEventService>();
auto eventService = Lifecycle::instance().service<IEventService>();
if (eventService) {
eventService->push(event);
}
}
});
auto &device = RenderDevice::instance();
if (!device.init(window_->native())) {
E2D_ERROR(CAT_APP, "渲染设备初始化失败");
window_->destroy();
delete window_;
window_ = nullptr;
return false;
}
initialized_ = true;
@ -67,15 +57,7 @@ void Application::shutdown() {
E2D_INFO(CAT_APP, "应用程序正在关闭");
RenderDevice::instance().shutdown();
if (window_) {
window_->destroy();
delete window_;
window_ = nullptr;
}
ServiceLocator::instance().shutdown();
Lifecycle::instance().clear();
initialized_ = false;
running_ = false;
@ -85,13 +67,19 @@ void Application::run() {
if (!initialized_)
return;
while (running_ && !window_->shouldClose()) {
auto *winMod = module<WindowModule>();
if (!winMod || !winMod->win())
return;
while (running_ && !winMod->shouldClose()) {
mainLoop();
}
}
void Application::quit() { running_ = false; }
WindowModule *Application::windowModule() const { return module<WindowModule>(); }
void Application::mainLoop() {
u64 currentTime = SDL_GetPerformanceCounter();
u64 frequency = SDL_GetPerformanceFrequency();
@ -109,9 +97,16 @@ void Application::mainLoop() {
fpsTimer_ -= 1.0f;
}
window_->poll();
ServiceLocator::instance().update(dt_);
RenderDevice::instance().swapBuffers();
auto *winMod = module<WindowModule>();
if (winMod) {
winMod->poll();
}
Lifecycle::instance().update(dt_);
auto *renderMod = module<RenderModule>();
if (renderMod) {
renderMod->swapBuffers();
}
}
} // namespace extra2d

View File

@ -0,0 +1,329 @@
#include <extra2d/core/lifecycle.h>
#include <extra2d/services/logger_service.h>
#include <algorithm>
#include <future>
#include <iostream>
#include <queue>
namespace extra2d {
Lifecycle& Lifecycle::instance() {
static Lifecycle instance;
return instance;
}
size_t Lifecycle::findModuleIndex(std::type_index type) const {
for (size_t i = 0; i < modules_.size(); ++i) {
if (modules_[i].module &&
std::type_index(typeid(*modules_[i].module)) == type) {
return i;
}
}
return SIZE_MAX;
}
size_t Lifecycle::findServiceIndex(std::type_index type) const {
for (size_t i = 0; i < services_.size(); ++i) {
if (services_[i].id == type) {
return i;
}
}
return SIZE_MAX;
}
std::vector<std::vector<Lifecycle::UnitIndex>> Lifecycle::groupByLevel() {
std::vector<std::vector<UnitIndex>> levels;
size_t totalUnits = modules_.size() + services_.size();
std::vector<int> inDegree(totalUnits, 0);
std::vector<std::vector<size_t>> adj(totalUnits);
for (size_t i = 0; i < modules_.size(); ++i) {
if (!modules_[i].module) continue;
auto* mod = modules_[i].module.get();
for (auto& depType : mod->deps()) {
size_t depIdx = findModuleIndex(depType);
if (depIdx != SIZE_MAX) {
adj[depIdx].push_back(i);
inDegree[i]++;
}
}
for (auto& depType : mod->needsServices()) {
size_t depIdx = findServiceIndex(depType);
if (depIdx != SIZE_MAX) {
adj[modules_.size() + depIdx].push_back(i);
inDegree[i]++;
}
}
}
for (size_t i = 0; i < services_.size(); ++i) {
if (!services_[i].service) continue;
auto* svc = services_[i].service.get();
for (auto& depType : svc->deps()) {
size_t depIdx = findServiceIndex(depType);
if (depIdx != SIZE_MAX) {
adj[modules_.size() + depIdx].push_back(modules_.size() + i);
inDegree[modules_.size() + i]++;
}
}
for (auto& depType : svc->needsModules()) {
size_t depIdx = findModuleIndex(depType);
if (depIdx != SIZE_MAX) {
adj[depIdx].push_back(modules_.size() + i);
inDegree[modules_.size() + i]++;
}
}
}
std::queue<size_t> q;
std::vector<int> levelMap(totalUnits, -1);
for (size_t i = 0; i < totalUnits; ++i) {
if (inDegree[i] == 0) {
q.push(i);
levelMap[i] = 0;
}
}
while (!q.empty()) {
size_t curr = q.front();
q.pop();
int currLevel = levelMap[curr];
if (levels.size() <= static_cast<size_t>(currLevel)) {
levels.resize(currLevel + 1);
}
UnitIndex ui;
if (curr < modules_.size()) {
ui.type = UnitType::Module;
ui.index = curr;
} else {
ui.type = UnitType::Service;
ui.index = curr - modules_.size();
}
levels[currLevel].push_back(ui);
for (size_t next : adj[curr]) {
inDegree[next]--;
if (inDegree[next] == 0) {
q.push(next);
levelMap[next] = currLevel + 1;
}
}
}
return levels;
}
bool Lifecycle::init() {
auto levels = groupByLevel();
std::cout << "[INFO] [生命周期] 正在初始化 " << modules_.size() + services_.size()
<< " 个单元,共 " << levels.size() << " 个层级..." << std::endl;
for (size_t level = 0; level < levels.size(); ++level) {
auto& units = levels[level];
bool hasParallelUnits = false;
for (auto& ui : units) {
if (ui.type == UnitType::Module) {
if (modules_[ui.index].module &&
modules_[ui.index].module->parallel()) {
hasParallelUnits = true;
break;
}
}
}
if (units.size() <= 1 || !hasParallelUnits) {
for (auto& ui : units) {
if (ui.type == UnitType::Module) {
auto* mod = modules_[ui.index].module.get();
if (!mod) continue;
std::cout << "[INFO] [模块系统] 正在初始化模块: " << mod->name()
<< " (层级 " << level << ")" << std::endl;
if (!mod->init()) {
std::cerr << "[ERROR] [模块系统] 初始化模块失败: " << mod->name() << std::endl;
return false;
}
std::cout << "[INFO] [模块系统] 模块 " << mod->name() << " 初始化成功" << std::endl;
} else {
auto& svc = services_[ui.index].service;
if (!svc) continue;
auto info = svc->info();
if (!info.enabled) continue;
std::cout << "[INFO] [服务系统] 正在初始化服务: " << info.name
<< " (层级 " << level << ")" << std::endl;
svc->setState(ServiceState::Initializing);
if (!svc->init()) {
svc->setState(ServiceState::Stopped);
std::cerr << "[ERROR] [服务系统] 初始化服务失败: " << info.name << std::endl;
return false;
}
svc->setState(ServiceState::Running);
std::cout << "[INFO] [服务系统] 服务 " << info.name << " 初始化成功" << std::endl;
}
}
} else {
std::cout << "[INFO] [生命周期] 正在并行初始化 " << units.size()
<< " 个单元 (层级 " << level << ")..." << std::endl;
std::vector<std::future<std::pair<UnitIndex, bool>>> futures;
std::vector<UnitIndex> serialUnits;
for (auto& ui : units) {
if (ui.type == UnitType::Module) {
auto* mod = modules_[ui.index].module.get();
if (!mod) continue;
if (mod->parallel()) {
futures.push_back(std::async(std::launch::async,
[this, ui, level]() -> std::pair<UnitIndex, bool> {
auto* m = modules_[ui.index].module.get();
std::cout << "[INFO] [模块系统] 正在初始化模块: " << m->name()
<< " (层级 " << level << ")" << std::endl;
bool success = m->init();
if (success) {
std::cout << "[INFO] [模块系统] 模块 " << m->name()
<< " 初始化成功 (并行)" << std::endl;
}
return {ui, success};
}));
} else {
serialUnits.push_back(ui);
}
} else {
serialUnits.push_back(ui);
}
}
for (auto& future : futures) {
auto [ui, success] = future.get();
if (!success) {
if (ui.type == UnitType::Module) {
auto* mod = modules_[ui.index].module.get();
std::cerr << "[ERROR] [模块系统] 初始化模块失败: " << mod->name() << std::endl;
}
return false;
}
}
for (auto& ui : serialUnits) {
if (ui.type == UnitType::Module) {
auto* mod = modules_[ui.index].module.get();
if (!mod) continue;
std::cout << "[INFO] [模块系统] 正在初始化模块: " << mod->name()
<< " (串行, 层级 " << level << ")" << std::endl;
if (!mod->init()) {
std::cerr << "[ERROR] [模块系统] 初始化模块失败: " << mod->name() << std::endl;
return false;
}
std::cout << "[INFO] [模块系统] 模块 " << mod->name() << " 初始化成功" << std::endl;
} else {
auto& svc = services_[ui.index].service;
if (!svc) continue;
auto info = svc->info();
if (!info.enabled) continue;
std::cout << "[INFO] [服务系统] 正在初始化服务: " << info.name
<< " (层级 " << level << ")" << std::endl;
svc->setState(ServiceState::Initializing);
if (!svc->init()) {
svc->setState(ServiceState::Stopped);
std::cerr << "[ERROR] [服务系统] 初始化服务失败: " << info.name << std::endl;
return false;
}
svc->setState(ServiceState::Running);
std::cout << "[INFO] [服务系统] 服务 " << info.name << " 初始化成功" << std::endl;
}
}
}
std::cout << "[INFO] [生命周期] 层级 " << level << " 初始化完成" << std::endl;
}
std::cout << "[INFO] [生命周期] 所有单元初始化完成" << std::endl;
return true;
}
void Lifecycle::update(f32 dt) {
for (auto& entry : services_) {
if (entry.service && entry.service->initialized()) {
auto state = entry.service->state();
if (state == ServiceState::Running) {
entry.service->update(dt);
}
}
}
}
void Lifecycle::pause() {
for (auto& entry : services_) {
if (entry.service && entry.service->initialized()) {
entry.service->pause();
}
}
}
void Lifecycle::resume() {
for (auto& entry : services_) {
if (entry.service && entry.service->initialized()) {
entry.service->resume();
}
}
}
void Lifecycle::shutdown() {
auto levels = groupByLevel();
for (auto it = levels.rbegin(); it != levels.rend(); ++it) {
for (auto& ui : *it) {
if (ui.type == UnitType::Module) {
auto* mod = modules_[ui.index].module.get();
if (mod && mod->ok()) {
E2D_INFO(CAT_MODULES, "正在关闭模块: {}", mod->name());
mod->shutdown();
}
} else {
auto& svc = services_[ui.index].service;
if (svc && svc->initialized()) {
E2D_INFO(CAT_SERVICES, "正在关闭服务: {}", svc->name());
svc->setState(ServiceState::Stopping);
svc->shutdown();
svc->setState(ServiceState::Stopped);
}
}
}
}
}
void Lifecycle::clear() {
shutdown();
modules_.clear();
services_.clear();
}
} // namespace extra2d

View File

@ -1,224 +0,0 @@
#include <extra2d/core/registry.h>
#include <extra2d/services/logger_service.h>
#include <future>
#include <queue>
namespace extra2d {
Registry &Registry::instance() {
static Registry instance;
return instance;
}
bool Registry::init() {
auto levels = group();
E2D_INFO(CAT_MODULES, "正在初始化 {} 个模块,共 {} 个层级...", moduleCount_,
levels.size());
for (size_t level = 0; level < levels.size(); ++level) {
auto &modules = levels[level];
// 检查当前层级是否有支持并行初始化的模块
bool hasParallelModules = false;
for (auto *module : modules) {
if (module->parallel()) {
hasParallelModules = true;
break;
}
}
// 如果只有一个模块或不支持并行,使用串行初始化
if (modules.size() <= 1 || !hasParallelModules) {
for (auto *module : modules) {
E2D_INFO(CAT_MODULES, "正在初始化模块: {} (层级 {})", module->name(),
level);
if (!module->init()) {
E2D_ERROR(CAT_MODULES, "初始化模块失败: {}", module->name());
return false;
}
E2D_INFO(CAT_MODULES, "模块 {} 初始化成功", module->name());
}
} else {
// 并行初始化当前层级的模块
E2D_INFO(CAT_MODULES, "正在并行初始化 {} 个模块 (层级 {})...",
modules.size(), level);
std::vector<std::future<std::pair<Module *, bool>>> futures;
std::vector<Module *> serialModules;
// 分离支持并行和不支持并行的模块
for (auto *module : modules) {
if (module->parallel()) {
futures.push_back(std::async(std::launch::async, [module]() {
return std::make_pair(module, module->init());
}));
} else {
serialModules.push_back(module);
}
}
// 等待并行模块完成
for (auto &future : futures) {
auto [module, success] = future.get();
if (!success) {
E2D_ERROR(CAT_MODULES, "初始化模块失败: {}", module->name());
return false;
}
E2D_INFO(CAT_MODULES, "模块 {} 初始化成功 (并行)", module->name());
}
// 串行初始化不支持并行的模块
for (auto *module : serialModules) {
E2D_INFO(CAT_MODULES, "正在初始化模块: {} (串行, 层级 {})",
module->name(), level);
if (!module->init()) {
E2D_ERROR(CAT_MODULES, "初始化模块失败: {}", module->name());
return false;
}
E2D_INFO(CAT_MODULES, "模块 {} 初始化成功", module->name());
}
}
E2D_INFO(CAT_MODULES, "层级 {} 初始化完成", level);
}
E2D_INFO(CAT_MODULES, "所有模块初始化完成");
return true;
}
void Registry::shutdown() {
// 从后向前关闭模块
for (size_t i = moduleCount_; i > 0; --i) {
if (modules_[i - 1].valid && modules_[i - 1].module) {
modules_[i - 1].module->shutdown();
}
}
}
void Registry::clear() {
shutdown();
// 销毁所有模块
for (size_t i = 0; i < moduleCount_; ++i) {
modules_[i].module.reset();
modules_[i].valid = false;
}
moduleCount_ = 0;
}
std::vector<Module *> Registry::sort() {
std::vector<Module *> result;
std::vector<int> inDegree(moduleCount_, 0);
std::vector<std::vector<size_t>> adj(moduleCount_);
// 构建依赖图
for (size_t i = 0; i < moduleCount_; ++i) {
if (!modules_[i].valid)
continue;
auto deps = modules_[i].module->deps();
for (auto &depType : deps) {
// 查找依赖模块的索引
for (size_t j = 0; j < moduleCount_; ++j) {
auto &mod = *modules_[j].module;
if (modules_[j].valid && std::type_index(typeid(mod)) == depType) {
adj[j].push_back(i);
inDegree[i]++;
break;
}
}
}
}
// 使用优先队列,按优先级排序
auto cmp = [this](size_t a, size_t b) {
return modules_[a].module->priority() > modules_[b].module->priority();
};
std::priority_queue<size_t, std::vector<size_t>, decltype(cmp)> pq(cmp);
for (size_t i = 0; i < moduleCount_; ++i) {
if (inDegree[i] == 0) {
pq.push(i);
}
}
while (!pq.empty()) {
size_t curr = pq.top();
pq.pop();
result.push_back(modules_[curr].module.get());
for (size_t next : adj[curr]) {
inDegree[next]--;
if (inDegree[next] == 0) {
pq.push(next);
}
}
}
return result;
}
std::vector<std::vector<Module *>> Registry::group() {
std::vector<std::vector<Module *>> levels;
std::vector<int> inDegree(moduleCount_, 0);
std::vector<std::vector<size_t>> adj(moduleCount_);
// 构建依赖图
for (size_t i = 0; i < moduleCount_; ++i) {
if (!modules_[i].valid)
continue;
auto deps = modules_[i].module->deps();
for (auto &depType : deps) {
for (size_t j = 0; j < moduleCount_; ++j) {
auto &mod = *modules_[j].module;
if (modules_[j].valid && std::type_index(typeid(mod)) == depType) {
adj[j].push_back(i);
inDegree[i]++;
break;
}
}
}
}
// 使用 BFS 按层级分组
std::queue<size_t> q;
std::vector<int> levelMap(moduleCount_, -1);
// 找到所有入度为 0 的模块(第一层)
for (size_t i = 0; i < moduleCount_; ++i) {
if (inDegree[i] == 0) {
q.push(i);
levelMap[i] = 0;
}
}
// BFS 遍历
while (!q.empty()) {
size_t curr = q.front();
q.pop();
int currLevel = levelMap[curr];
// 确保当前层级存在
if (levels.size() <= static_cast<size_t>(currLevel)) {
levels.resize(currLevel + 1);
}
levels[currLevel].push_back(modules_[curr].module.get());
// 处理依赖当前模块的其他模块
for (size_t next : adj[curr]) {
inDegree[next]--;
if (inDegree[next] == 0) {
q.push(next);
levelMap[next] = currLevel + 1;
}
}
}
return levels;
}
} // namespace extra2d

View File

@ -1,110 +0,0 @@
#include <extra2d/core/service_locator.h>
#include <algorithm>
namespace extra2d {
ServiceLocator& ServiceLocator::instance() {
static ServiceLocator instance;
return instance;
}
bool ServiceLocator::init() {
std::shared_lock<std::shared_mutex> lock(mutex_);
for (auto& svc : orderedServices_) {
if (!svc) continue;
auto info = svc->info();
if (!info.enabled) continue;
if (!svc->initialized()) {
svc->setState(ServiceState::Initializing);
if (!svc->init()) {
svc->setState(ServiceState::Stopped);
return false;
}
svc->setState(ServiceState::Running);
}
}
return true;
}
void ServiceLocator::shutdown() {
std::shared_lock<std::shared_mutex> lock(mutex_);
for (auto it = orderedServices_.rbegin();
it != orderedServices_.rend(); ++it) {
if (*it && (*it)->initialized()) {
(*it)->setState(ServiceState::Stopping);
(*it)->shutdown();
(*it)->setState(ServiceState::Stopped);
}
}
}
void ServiceLocator::update(f32 dt) {
std::shared_lock<std::shared_mutex> lock(mutex_);
for (auto& svc : orderedServices_) {
if (svc && svc->initialized()) {
auto state = svc->state();
if (state == ServiceState::Running) {
svc->update(dt);
}
}
}
}
void ServiceLocator::pause() {
std::shared_lock<std::shared_mutex> lock(mutex_);
for (auto& svc : orderedServices_) {
if (svc && svc->initialized()) {
svc->pause();
}
}
}
void ServiceLocator::resume() {
std::shared_lock<std::shared_mutex> lock(mutex_);
for (auto& svc : orderedServices_) {
if (svc && svc->initialized()) {
svc->resume();
}
}
}
std::vector<Ref<IService>> ServiceLocator::all() const {
std::shared_lock<std::shared_mutex> lock(mutex_);
return orderedServices_;
}
void ServiceLocator::clear() {
std::unique_lock<std::shared_mutex> lock(mutex_);
for (auto it = orderedServices_.rbegin();
it != orderedServices_.rend(); ++it) {
if (*it && (*it)->initialized()) {
(*it)->setState(ServiceState::Stopping);
(*it)->shutdown();
(*it)->setState(ServiceState::Stopped);
}
}
services_.clear();
factories_.clear();
orderedServices_.clear();
}
void ServiceLocator::sort() {
std::stable_sort(orderedServices_.begin(), orderedServices_.end(),
[](const Ref<IService>& a, const Ref<IService>& b) {
if (!a || !b) return false;
return static_cast<int>(a->info().priority) <
static_cast<int>(b->info().priority);
});
}
}

View File

@ -1,37 +0,0 @@
#include <extra2d/core/service_registry.h>
namespace extra2d {
ServiceRegistry& ServiceRegistry::instance() {
static ServiceRegistry instance;
return instance;
}
void ServiceRegistry::setEnabled(const std::string& name, bool enabled) {
for (auto& reg : registrations_) {
if (reg.name == name) {
reg.enabled = enabled;
break;
}
}
}
void ServiceRegistry::createAll() {
std::sort(registrations_.begin(), registrations_.end(),
[](const ServiceRegistration& a, const ServiceRegistration& b) {
return static_cast<int>(a.priority) < static_cast<int>(b.priority);
});
for (const auto& reg : registrations_) {
if (!reg.enabled) {
continue;
}
auto service = reg.factory();
if (service) {
ServiceLocator::instance().add<IService>(service);
}
}
}
}

View File

@ -0,0 +1,91 @@
#include <extra2d/app/application.h>
#include <extra2d/render/render_module.h>
#include <extra2d/services/logger_service.h>
#include <extra2d/window/window_module.h>
namespace extra2d {
/**
* @brief
* 使 Lambda
*/
RenderModule::RenderModule(std::function<void(RenderCfg &)> configFn) {
if (configFn) {
configFn(cfg_);
}
}
/**
* @brief
*/
RenderModule::~RenderModule() { shutdown(); }
/**
* @brief
* OpenGL
*/
bool RenderModule::init() {
if (initialized_) {
return true;
}
// 获取窗口模块
auto *winMod = app()->module<WindowModule>();
if (!winMod || !winMod->win()) {
E2D_ERROR(CAT_RENDER, "WindowModule 未初始化");
return false;
}
// 转换配置
RenderDeviceConfig config;
config.glMajor = cfg_.glMajor;
config.glMinor = cfg_.glMinor;
config.useES = cfg_.useES;
config.redBits = cfg_.redBits;
config.greenBits = cfg_.greenBits;
config.blueBits = cfg_.blueBits;
config.alphaBits = cfg_.alphaBits;
config.depthBits = cfg_.depthBits;
config.stencilBits = cfg_.stencilBits;
config.doubleBuffer = cfg_.doubleBuffer;
config.msaaSamples = cfg_.msaaSamples;
config.vsync = cfg_.vsync;
auto &device = RenderDevice::instance();
if (!device.init(winMod->native(), config)) {
E2D_ERROR(CAT_RENDER, "RenderDevice 初始化失败");
return false;
}
initialized_ = true;
E2D_INFO(CAT_RENDER, "RenderModule initialized");
return true;
}
/**
* @brief
*/
void RenderModule::shutdown() {
if (!initialized_) {
return;
}
RenderDevice::instance().shutdown();
initialized_ = false;
}
/**
* @brief
*/
void RenderModule::swapBuffers() { RenderDevice::instance().swapBuffers(); }
/**
* @brief VSync
*/
void RenderModule::setVSync(bool enabled) {
RenderDevice::instance().setVSync(enabled);
}
} // namespace extra2d

View File

@ -1,4 +1,5 @@
#include <SDL.h>
#include <chrono>
#include <cstdarg>
#include <cstdio>
#include <cstring>
@ -96,7 +97,11 @@ static void SDLCALL logOutput(void *userdata, int category,
const char *content;
parseCategory(message, cat, content);
Uint32 ticks = SDL_GetTicks();
// 使用 std::chrono 替代 SDL_GetTicks(),避免 SDL 未初始化的问题
auto now = std::chrono::steady_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
now.time_since_epoch());
Uint32 ticks = static_cast<Uint32>(ms.count() % (24 * 60 * 60 * 1000));
Uint32 seconds = ticks / 1000;
Uint32 minutes = seconds / 60;
Uint32 hours = minutes / 60;

View File

@ -0,0 +1,156 @@
#include <extra2d/window/window_module.h>
namespace extra2d {
/**
* @brief
* 使 Lambda
*/
WindowModule::WindowModule(std::function<void(WindowCfg&)> configFn) {
if (configFn) {
configFn(cfg_);
}
}
/**
* @brief
*/
WindowModule::~WindowModule() {
shutdown();
}
/**
* @brief
*
*/
bool WindowModule::init() {
if (initialized_) {
return true;
}
window_ = ptr::unique<Window>();
WindowConfig config;
config.title = cfg_.title;
config.width = cfg_.width;
config.height = cfg_.height;
config.fullscreen = cfg_.fullscreen;
config.resizable = cfg_.resizable;
config.centerWindow = cfg_.centerWindow;
if (!window_->create(config)) {
window_.reset();
return false;
}
initialized_ = true;
return true;
}
/**
* @brief
*
*/
void WindowModule::shutdown() {
if (!initialized_) {
return;
}
if (window_) {
window_->destroy();
window_.reset();
}
initialized_ = false;
}
/**
* @brief
*/
void WindowModule::poll() {
if (window_) {
window_->poll();
}
}
/**
* @brief
*/
bool WindowModule::shouldClose() const {
return window_ ? window_->shouldClose() : true;
}
/**
* @brief
*/
void WindowModule::close() {
if (window_) {
window_->close();
}
}
/**
* @brief
*/
void WindowModule::setTitle(const std::string& title) {
if (window_) {
window_->setTitle(title);
}
}
/**
* @brief
*/
void WindowModule::setSize(int width, int height) {
if (window_) {
window_->setSize(width, height);
}
}
/**
* @brief
*/
void WindowModule::setFullscreen(bool fullscreen) {
if (window_) {
window_->setFullscreen(fullscreen);
}
}
/**
* @brief
*/
int WindowModule::width() const {
return window_ ? window_->width() : 0;
}
/**
* @brief
*/
int WindowModule::height() const {
return window_ ? window_->height() : 0;
}
/**
* @brief
*/
bool WindowModule::fullscreen() const {
return window_ ? window_->fullscreen() : false;
}
/**
* @brief
*/
void WindowModule::onEvent(std::function<void(const SDL_Event&)> cb) {
if (window_) {
window_->onEvent(cb);
}
}
/**
* @brief
*/
SDL_Window* WindowModule::native() const {
return window_ ? window_->native() : nullptr;
}
} // namespace extra2d

View File

@ -2,27 +2,36 @@
using namespace extra2d;
// ============================================================================
// Hello World 示例
// ============================================================================
int main(int argc, char **argv) {
E2D_INFO(CAT_APP, "========================");
E2D_INFO(CAT_APP, "Extra2D Hello World Demo");
E2D_INFO(CAT_APP, "========================");
// 获取应用实例并初始化
auto &app = Application::instance();
app.name = "Hello World";
// 注册服务和模块顺序无关Lifecycle 会自动按依赖拓扑排序)
app.useService<ILogger, ConsoleLogger>();
app.useService<IEventService, EventService>();
app.useService<ITimerService, TimerService>();
app.useModule<WindowModule>([](WindowCfg &cfg) {
cfg.title = "Extra2D - Hello World";
cfg.width = 1280;
cfg.height = 720;
});
app.useModule<RenderModule>([](RenderCfg &cfg) {
cfg.glMajor = 4;
cfg.glMinor = 5;
cfg.vsync = true;
});
if (!app.init()) {
E2D_ERROR(CAT_APP, "应用初始化失败!");
return -1;
}
// 获取事件服务并订阅键盘事件
auto eventService = ServiceLocator::instance().get<IEventService>();
auto eventService = Lifecycle::instance().service<IEventService>();
if (eventService) {
// 订阅 ESC 键退出
eventService->on(EventType::KeyPressed, [&app](Event &e) {
auto &keyEvent = std::get<KeyEvent>(e.data);
if (keyEvent.key == static_cast<i32>(Key::Escape)) {
@ -31,7 +40,6 @@ int main(int argc, char **argv) {
}
});
// 订阅手柄按钮退出
eventService->on(EventType::GamepadButtonPressed, [&app](Event &e) {
auto &btnEvent = std::get<GamepadButtonEvent>(e.data);
if (btnEvent.button == static_cast<i32>(Gamepad::Start)) {
@ -42,11 +50,9 @@ int main(int argc, char **argv) {
}
E2D_INFO(CAT_APP, "开始主循环...");
// 运行应用
app.run();
E2D_INFO(CAT_APP, "应用结束");
app.shutdown();
return 0;
}