diff --git a/CMakeLists.txt b/CMakeLists.txt index ffec4a0d..1be01989 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -177,7 +177,7 @@ message("------------------angelscript 脚本语言库-----------") add_subdirectory ("third/angelscript/angelscript/projects/cmake") message("------------------lua 脚本语言库-----------") add_subdirectory ("third/lua") -add_subdirectory ("third/LuaBridge3") +add_subdirectory ("third/sol2") message("------------------infoware 硬件信息库-----------") if (CMAKE_HOST_SYSTEM_PROCESSOR MATCHES "AMD64") set(INFOWARE_PCI_IDS_PATH ${CMAKE_SOURCE_DIR}/third/infoware/pci.ids CACHE FILEPATH "使用本地piiids" FORCE) diff --git a/dl/CMakeLists.txt b/dl/CMakeLists.txt index 847a9e5f..745dc0b2 100644 --- a/dl/CMakeLists.txt +++ b/dl/CMakeLists.txt @@ -182,8 +182,9 @@ include_directories(${CMAKE_SOURCE_DIR}/third/angelscript/add_on) target_link_libraries(${PROJECT_NAME} PRIVATE angelscript) # lua target_link_libraries(${PROJECT_NAME} PRIVATE lua) -# lua bridge -target_link_libraries(${PROJECT_NAME} PRIVATE LuaBridge) +# lua sol2 +target_link_libraries(${PROJECT_NAME} PRIVATE sol2) +include_directories(${CMAKE_SOURCE_DIR}/third/sol2) # infoware if (CMAKE_SYSTEM_NAME MATCHES "Windows" OR CMAKE_SYSTEM_NAME MATCHES "Linux") diff --git a/dl/base/dl_string.h b/dl/base/dl_string.h index f4949dd5..0afd08ae 100644 --- a/dl/base/dl_string.h +++ b/dl/base/dl_string.h @@ -661,7 +661,7 @@ inline std::vector Split(const std::string& str, char d) split(str, d, ret); return ret; } -inline std::vector Split(std::string_view str, char d) +inline std::vector SplitView(std::string_view str, char d) { std::vector ret; split(str, d, ret); @@ -677,13 +677,34 @@ inline std::vector Split(const std::string& str, const std::string& split_sub(str, d, ret); return ret; } -inline std::vector Split(std::string_view str, std::string_view d) +inline std::vector SplitView(std::string_view str, std::string_view d) { std::vector ret; split_sub(str, d, ret); return ret; } +/** +* @brief 分割字符串(连续跳过匹配字符) +*/ +inline std::vector SplitNoEmpty(const std::string& str, char d) +{ + std::vector ret; + split_no_empty(str, d, ret); + return ret; +} + +/** +* @brief 分割字符串(连续跳过匹配字符) +*/ +inline std::vector SplitViewNoEmpty(std::string_view str, char d) +{ + std::vector ret; + split_no_empty(str, d, ret); + return ret; +} + + /** * @brief 处理子字符串(通过特定字符分割) * @param[in] str 整个字符串 @@ -713,48 +734,41 @@ inline std::vector SplitViewNoEmpty(std::string_view str, { return SplitViewNoEmpty(str, std::string_view{ vec_ch.data(), vec_ch.size() }); } -/** -* @brief 处理子字符串(通过特定字符分割) -* @param[in] str 整个字符串 -* @param[in] vec_ch 匹配的字符 -* @note 连续匹配返回空串 -*/ -inline std::vector SplitView(std::string_view str, std::string_view vec_ch) -{ - std::vector ret; - size_t beg = 0; - size_t cur = 0; - for (; cur < str.size(); ++cur) - { - if (Any::Equal(vec_ch, str[cur])) - { - if (beg != cur) - ret.push_back({ str.data() + beg, str.data() + cur }); - else - ret.push_back({}); - beg = cur + 1; - } - } - if (beg != cur) - ret.push_back({ str.data() + beg, str.data() + cur }); - else - ret.push_back({}); - return ret; -} -inline std::vector SplitView(std::string_view str, - const std::vector& vec_ch) -{ - return SplitView(str, std::string_view{ vec_ch.data(), vec_ch.size() }); -} -/** -* @brief 分割字符串(连续跳过匹配字符) -*/ -inline std::vector SplitNoEmpty(const std::string& str, char d) -{ - std::vector ret; - split_no_empty(str, d, ret); - return ret; -} +///** +//* @brief 处理子字符串(通过特定字符分割) +//* @param[in] str 整个字符串 +//* @param[in] vec_ch 匹配的字符 +//* @note 连续匹配返回空串 +//*/ +//inline std::vector SplitView(std::string_view str, std::string_view vec_ch) +//{ +// std::vector ret; +// size_t beg = 0; +// size_t cur = 0; +// for (; cur < str.size(); ++cur) +// { +// if (Any::Equal(vec_ch, str[cur])) +// { +// if (beg != cur) +// ret.push_back({ str.data() + beg, str.data() + cur }); +// else +// ret.push_back({}); +// beg = cur + 1; +// } +// } +// if (beg != cur) +// ret.push_back({ str.data() + beg, str.data() + cur }); +// else +// ret.push_back({}); +// return ret; +//} +//inline std::vector SplitView(std::string_view str, +// const std::vector& vec_ch) +//{ +// return SplitView(str, std::string_view{ vec_ch.data(), vec_ch.size() }); +//} + + /** * @brief 移除末尾格式,移除后不包含. diff --git a/dl/io/dl_log.cpp b/dl/io/dl_log.cpp index a4f249eb..cad0730a 100644 --- a/dl/io/dl_log.cpp +++ b/dl/io/dl_log.cpp @@ -219,7 +219,8 @@ void log_imp(std::string_view str, const std::source_location location) // 堆栈信息 if (setting._bStackTrace) { - Output(std::to_string(std::stacktrace::current())); + // 文本始终打印完整的调用堆栈 + Output(std::to_string(std::stacktrace::current(3))); OutputEndl(); } // 关闭日志暂用 @@ -232,7 +233,22 @@ void log_imp(std::string_view str, const std::source_location location) std::string title = fmt::format("{}({}) {} {}", location.file_name(), location.line(), Time::TimeStamp2String(time(0)), LogSystem::Level2String(setting._level)); - int ret = MessageBoxW(NULL, CodeCvt::Utf8ToWideChar(str + "\n\n" + std::to_string(std::stacktrace::current())).c_str(), + std::string str_stack; + { + std::string str = std::to_string(std::stacktrace::current(3)); + + std::vector vec_str = String::SplitView(str, '\n'); + for (auto& iter : vec_str) + { + if (String::IsSub(iter, "dl\\dl") + || String::IsSub(iter, "dl\\project")) + { + str_stack += iter; + str_stack += '\n'; + } + } + } + int ret = MessageBoxW(NULL, CodeCvt::Utf8ToWideChar(str + "\n\n" + str_stack).c_str(), CodeCvt::Utf8ToWideChar(title).c_str(), MB_ABORTRETRYIGNORE | MB_ICONERROR | MB_DEFBUTTON3); if (ret == IDABORT) exit(1); diff --git a/dl/memory/dl_memory_pool.h b/dl/memory/dl_memory_pool.h index b206aea0..4c73d9e2 100644 --- a/dl/memory/dl_memory_pool.h +++ b/dl/memory/dl_memory_pool.h @@ -52,7 +52,7 @@ class GC public: GC() :_p(nullptr), _ref(nullptr) {} GC(const GC& b) : _p(b._p), _ref(b._ref) { if (_ref)++_ref->_count; } - operator bool() + operator bool() const { return _p != nullptr; } @@ -118,6 +118,10 @@ public: { return _p; } + const T* GetPointer() const + { + return _p; + } ~GC() { diff --git a/dl/misc/dl_value.cpp b/dl/misc/dl_value.cpp index 6214350a..25a1cfeb 100644 --- a/dl/misc/dl_value.cpp +++ b/dl/misc/dl_value.cpp @@ -45,7 +45,7 @@ namespace dl ValueTypeInfo String2ValueTypeEx(std::string_view str) { ValueTypeInfo ret; - std::vector vec = String::Split(str, '<'); + std::vector vec = String::SplitView(str, '<'); if (vec.size() < 2) return ret; // 记录主类型 @@ -54,7 +54,7 @@ namespace dl return ret; vec[1] = vec[1].substr(0, vec[1].size() - 1); - std::vector vec1 = String::Split(vec[1], ','); + std::vector vec1 = String::SplitView(vec[1], ','); if (vec1.size() > 0) { ret._strType1 = vec1[0]; diff --git a/dl/script/dl_lua.cpp b/dl/script/dl_lua.cpp index 46d9d56d..b6e5b9b2 100644 --- a/dl/script/dl_lua.cpp +++ b/dl/script/dl_lua.cpp @@ -13,27 +13,22 @@ namespace dl LuaScript::LuaScript() { - L = luaL_newstate(); - luaL_openlibs(L); + _l.open_libraries(sol::lib::base, sol::lib::string, sol::lib::math); } LuaScript::~LuaScript() { - lua_close(L); } bool LuaScript::DoString(std::string_view str) { - int ret = luaL_loadstring(L, str.data()); - if (ret) + try { - log_err("lua 解析失败[{}]:\n{}", lua_tostring(L, -1), str); - return false; + auto ret = _l.script(str); } - ret = lua_pcall(L, 0, 0, 0); - if (ret) + catch (sol::error& e) { - log_err("lua 执行失败[{}]:\n{}", lua_tostring(L, -1), str); + log_warn("{}\n{}", e.what(), str); return false; } return true; @@ -41,17 +36,26 @@ namespace dl bool LuaScript::DoFile(std::string_view path_name) { - Buffer buf = File::GetBuffer(path_name); - int ret = luaL_loadbuffer(L, (const char*)buf.data(), buf.size(), path_name.data()); - if (ret) + try { - log_err("lua 解析(加载)失败[{}]:{}", path_name, lua_tostring(L, -1)); + std::string str = File::GetString(path_name); + auto ret = _l.script(str, std::string{ path_name }); + } + catch (sol::error& e) + { + log_warn("{}", e.what()); return false; } - ret = lua_pcall(L, 0, 0, 0); - if (ret) + return true; + } + + bool LuaScript::ExcuteFunction(sol::function func) + { + sol::function_result ret = func(); + if (!ret.valid()) { - log_err("lua 执行失败[{}]:{}", path_name, lua_tostring(L, -1)); + sol::error e = ret; + log_warn("{}", e.what()); return false; } return true; @@ -59,7 +63,7 @@ namespace dl void LuaScript::RegisterAll() { - lua_register_all(L); + lua_register_all(_l); } } \ No newline at end of file diff --git a/dl/script/dl_lua.h b/dl/script/dl_lua.h index a5f91a04..bd864395 100644 --- a/dl/script/dl_lua.h +++ b/dl/script/dl_lua.h @@ -17,10 +17,9 @@ #include #include -#define LUA_USE_APICHECK -#define LUABRIDGE_HAS_EXCEPTIONS 0 -#include -#include +#define SOL_ALL_SAFETIES_ON 1 +#define SOL_PRINT_ERRORS 0 +#include #include "dl_io.h" @@ -47,41 +46,18 @@ public: bool DoString(std::string_view str); bool DoFile(std::string_view path_name); - bool ExcuteFunction(std::string_view name) - { - luabridge::LuaRef v = luabridge::getGlobal(L, name.data()); - luabridge::LuaResult ret = v(); - if (ret.hasFailed()) - { - log_warn("{}", ret.errorMessage()); - return false; - } - // todo ret - return true; - } - template - bool ExcuteFunction(std::string_view name, Args&&... args) - { - luabridge::LuaRef v = luabridge::getGlobal(L, name.data()); - luabridge::LuaResult ret = v(args...); - if (ret.hasFailed()) - { - log_warn("{}", ret.errorMessage()); - return false; - } - // todo ret - return true; - } + bool ExcuteFunction(sol::function func); Env& GetEnv() { return _env; } - lua_State* GetL() { return L; } + sol::state& GetL() { return _l; } // 由引擎调用 void RegisterAll(); private: - lua_State* L; Env _env; std::string _pathRoot; + + sol::state _l; }; extern LuaScript* g_lua; diff --git a/dl/script/dl_lua_register.cpp b/dl/script/dl_lua_register.cpp index 00081a89..ad31ef18 100644 --- a/dl/script/dl_lua_register.cpp +++ b/dl/script/dl_lua_register.cpp @@ -1,21 +1,86 @@ #include "dl_lua_register.h" -#include "dl_io.h" -#include "render/dl_graphics.h" -#include "system/dl_system.h" -#include "script/dl_lua.h" -#include "ui/dl_ui_manager.h" -#include "render/dl_image.h" -#include "script/dl_lua_register_container.h" -// 枚举类绑定 -template <> -struct luabridge::Stack : luabridge::Enum -{ -}; +#include "base/dl_type_def.h" +#include "render/dl_image.h" +#include "base/dl_string.h" +#include "render/dl_factory.h" +#include "system/dl_system.h" +#include "render/dl_graphics.h" + + +namespace sol { + using namespace dl; + + // GC类声明 + template + struct unique_usertype_traits> + { + typedef T type; + typedef GC actual_type; + static const bool value = true; + + static bool is_null(const actual_type& ptr) + { + return !ptr; + } + + static type* get(const actual_type& ptr) + { + return (type*)ptr.GetPointer(); + } + }; + + // 自定义容器 + /*template <> + struct is_container : std::true_type {};*/ + + //template <> + //struct usertype_container { + + // ... + // // see below for implemetation details + //}; + + /*template + struct is_container> : std::true_type {}; + + template + struct usertype_container> { + static int size(lua_State* L) + { + Array& v = sol::stack::get&>(L, 1); + return stack::push(L, N); + } + + static int get(lua_State* L) { + Array& v = sol::stack::get&>(L, 1); + std::ptrdiff_t idx = sol::stack::unqualified_get(L, 2); + + if (idx < 0 || idx >= N) + return sol::stack::push(L, sol::lua_nil); + + return sol::stack::push(L, v[idx]); + } + + static int index_get(lua_State* L) { + return get(L); + } + + static void begin(lua_State* L, T& ret) + { + Array& v = sol::stack::get&>(L, 1); + ret = v[0]; + return {}; + } + static void end(lua_State* L, T& ret) + { + Array& v = sol::stack::get&>(L, 1); + ret = v[N]; + return {}; + } + };*/ +} namespace dl { @@ -31,124 +96,112 @@ namespace dl std::string lua_to_string(const Position2& pos) { - return to_string(pos); + return dl::to_string(pos); } - void lua_register_base(lua_State* L) + void lua_register_base(sol::state& l) { - luabridge::getGlobalNamespace(L) - .addFunction("log", lua_log) - .addFunction("delete", lua_delete) - .addFunction("to_string", - luabridge::overload(lua_to_string)); + l["log"]= lua_log; + l["delete"]= lua_delete; + l["to_string"]= lua_to_string; - luabridge::getGlobalNamespace(L) - .beginNamespace("String") - .addFunction("ErasePath", String::ErasePath) - .addFunction("GetFileStem", String::GetFileStem) - .addFunction("toPosition2", String::toPosition2) - .addFunction("ReplaceExtension", - luabridge::overload(String::ReplaceExtension)) - .addFunction("EraseFilename", - luabridge::overload(String::EraseFilename)) - .endNamespace(); + l.new_usertype("Position", + sol::call_constructor, + sol::factories([](float x, float y) { + return Position{ x, y }; + }), + "x", &Position::x, + "y", &Position::y); - luabridge::getGlobalNamespace(L) - .beginNamespace("Img") - .addVariable("REGEX_FORMAT", Img::REGEX_FORMAT) - .addFunction("Resize", - luabridge::overload(Img::Resize), - luabridge::overload(Img::Resize)) - .addFunction("SetAlphaZero", - luabridge::overload(Img::SetAlphaZero), - luabridge::overload(Img::SetAlphaZero)) - .addFunction("Create", - luabridge::overload(Img::Create), - luabridge::overload(Img::Create)) - .addFunction("Save", Img::Save) - .endNamespace(); + { + sol::table ll = l["String"].get_or_create(); + ll["ErasePath"] = String::ErasePath; + ll["GetFileStem"] = String::GetFileStem; + ll["toPosition2"] = String::toPosition2; + ll["ReplaceExtension"] = sol::resolve( + String::ReplaceExtension); + ll["EraseFilename"] = sol::resolve( + String::EraseFilename); + } + + { + sol::table ll = l["Img"].get_or_create(); + ll["REGEX_FORMAT"] = Img::REGEX_FORMAT; + ll["Resize"] = sol::overload( + sol::resolve(Img::Resize), + sol::resolve(Img::Resize)); + ll["SetAlphaZero"] = sol::overload( + sol::resolve(Img::SetAlphaZero), + sol::resolve(Img::SetAlphaZero)); + ll["Create"] = sol::overload( + sol::resolve(Img::Create), + sol::resolve(Img::Create)); + ll["Save"] = Img::Save; + } - luabridge::getGlobalNamespace(L) - .beginClass("Image") - .endClass(); - - luabridge::getGlobalNamespace(L) - .beginNamespace("ColorDef") -.addVariable("NONE", ColorDef::NONE) -.addVariable("RED", ColorDef::RED) - .endNamespace(); + l.new_enum("ColorDef", + "NONE", ColorDef::NONE, + "RED", ColorDef::RED); } - void lua_register_system(lua_State* L) + void lua_register_system(sol::state& l) { #ifndef DL_DISABLE_RENDER - luabridge::getGlobalNamespace(L) - .beginClass("ParamWindow") - .addConstructor() // 忽略这个构造会出错…… - .addProperty("title", &ParamWindow::_strTitle) - .endClass(); + l.new_usertype("ParamWindow", + "title", &ParamWindow::_strTitle); - luabridge::getGlobalNamespace(L) - .beginClass("System") - .addFunction("SetFuncInit", &System::lua_SetFuncInit) - .addFunction("SetFuncRun", &System::lua_SetFuncUpdate) - .addFunction("Start", (void(System::*)(const ParamWindow&))&System::Start) - .endClass(); + l.new_usertype("System", sol::no_constructor, + "SetFuncInit", &System::lua_SetFuncInit, + "SetFuncRun", &System::lua_SetFuncRun, + "Start", sol::resolve(&System::Start)); - auto result = luabridge::push(L, g_system); - lua_setglobal(L, "g_system"); + l["g_system"] = g_system; #endif } - void lua_register_file(lua_State* L) + void lua_register_file(sol::state& l) { using namespace File::Lua; + { + sol::table ll = l["File"].get_or_create(); + ll.new_enum("CopyMode", + "NONE", File::CopyMode::NONE, + "OVERRIDE", File::CopyMode::OVERRIDE, + "SKIP", File::CopyMode::SKIP); + } - luabridge::getGlobalNamespace(L) - .beginNamespace("g_file") - .beginNamespace("CopyMode") - .addVariable("NONE", File::CopyMode::NONE) - .addVariable("OVERRIDE", File::CopyMode::OVERRIDE) - .addVariable("SKIP",File::CopyMode::SKIP) - .endNamespace() - .endNamespace(); - - luabridge::getGlobalNamespace(L) - .beginNamespace("g_file") - .addFunction("GetPathFileAll", lua_GetPathFileAll_3, lua_GetPathFileAll_2, lua_GetPathFileAll_1) - .addFunction("GetAbsolute", File::GetAbsolute) - .addFunction("GetRelative", File::GetRelative) - .addFunction("CreateFolder", File::CreateFolder) - .addFunction("DeleteContent", File::DeleteContent) - .addFunction("Rename", File::Rename) - .addFunction("Copy", File::Copy) - .addFunction("GetFilePath", File::GetFilePath) - .addFunction("GetFileName", File::GetFileName) - .addFunction("GetString", File::GetString) - .addFunction("SaveString", - luabridge::overload(File::SaveString)) - .endNamespace(); + { + sol::table ll = l["File"].get_or_create(); + ll["GetPathFileAll"] = sol::overload(lua_GetPathFileAll_3, lua_GetPathFileAll_2, lua_GetPathFileAll_1); + ll["GetAbsolute"] = File::GetAbsolute; + ll["GetRelative"] = File::GetRelative; + ll["CreateFolder"] = File::CreateFolder; + ll["DeleteContent"] = File::DeleteContent; + ll["Rename"] = File::Rename; + ll["Copy"] = File::Copy; + ll["GetFilePath"] = File::GetFilePath; + ll["GetFileName"] = File::GetFileName; + ll["GetString"] = File::GetString; + ll["SaveString"] = sol::resolve(File::SaveString); + } } - void lua_register_gfx(lua_State* L) + void lua_register_gfx(sol::state& l) { #ifndef DL_DISABLE_RENDER - luabridge::getGlobalNamespace(L) - .beginClass("Graphics") - .addFunction("Rectangle2D", &Graphics::Rectangle2D) - .endClass(); + l.new_usertype("Graphics", sol::no_constructor, + "Rectangle2D", &Graphics::Rectangle2D); - auto result = luabridge::push(L, g_gfx); - lua_setglobal(L, "g_gfx"); + l["g_gfx"] = g_gfx; #endif } - void lua_register_ui(lua_State* L) + void lua_register_ui(sol::state& l) { #ifndef DL_DISABLE_RENDER - using namespace UI; + /*using namespace UI; luabridge::getGlobalNamespace(L) .beginClass("UIPanel") .addFunction("Add", (void(Panel::*)(UI::Text*))&Panel::Add) @@ -168,130 +221,64 @@ namespace dl .endClass(); auto result = luabridge::push(L, g_ui); - lua_setglobal(L, "g_ui"); + lua_setglobal(L, "g_ui");*/ #endif } - void lua_register_factory(lua_State* L) + void lua_register_factory(sol::state& l) { - luabridge::getGlobalNamespace(L) - .beginClass("Factory") - .addFunction("CreateText", &Factory::CreateText) - .addFunction("CreateTextDefault", &Factory::CreateTextDefault) - .addFunction("CreateSprite", - luabridge::overload(&Factory::CreateSprite), - luabridge::overload(&Factory::CreateSprite)) - .addFunction("SetPath", &Factory::SetPath) - .endClass(); + l.new_usertype("Factory", sol::no_constructor, + "SetPath", &Factory::SetPath, + "CreateText", &Factory::CreateText, + "CreateTextDefault", &Factory::CreateTextDefault, + "CreateSprite", sol::overload( + sol::resolve(&Factory::CreateSprite), + sol::resolve(&Factory::CreateSprite)) + ); - auto result = luabridge::push(L, g_factory); - lua_setglobal(L, "g_factory"); + l["g_factory"] = g_factory; } - void lua_register_sprite(lua_State* L) + void lua_register_sprite(sol::state& l) { - luabridge::getGlobalNamespace(L) - .beginClass("Sprite") - .addFunction("Render", &Sprite::Render) - .addFunction("SetColor", - luabridge::overload(&Sprite::SetColor), - luabridge::overload(&Sprite::SetColor)) - .endClass(); - - - luabridge::getGlobalNamespace(L) - .beginClass("gcSprite") - .addFunction("GetPointer", &gcSprite::GetPointer) - .addIndexMetaMethod([](gcSprite& self, const luabridge::LuaRef& key, lua_State* L) -> luabridge::LuaRef - { - if (key.tostring() == "GetPointer") - {// 不清楚为何存在 GetPointer,还是会触发元函数 - luabridge::LuaRef ref_class = luabridge::getGlobal(L, "gcSprite"); - luabridge::LuaRef ref_func = ref_class[key]; - return ref_func; - } - // 获取到原Sprite函数 - luabridge::LuaRef ref_class = luabridge::getGlobal(L, "Sprite"); - luabridge::LuaRef ref_func = ref_class[key]; - luabridge::setGlobal(L, ref_func, "__dl_sprite_func"); - // 调用代理函数 - luabridge::LuaRef ref_proxy = luabridge::getGlobal(L, "__dl_sprite_proxy"); - return ref_proxy; - }) - .endClass(); - - // 注册sprite代理函数 - g_lua->DoString(R"( -__dl_sprite_func = nil -__dl_sprite_proxy = function(obj, ...) - __dl_sprite_func(obj:GetPointer(), ...) -end -)"); + l.new_usertype("Sprite", + "Render", &Sprite::Render, + "SetColor", sol::overload( + sol::resolve(&Sprite::SetColor), + sol::resolve(&Sprite::SetColor) + )); } - void lua_register_text(lua_State* L) + void lua_register_text(sol::state& l) { - luabridge::getGlobalNamespace(L) - .beginClass("Text") - .addFunction("Render", &Text::Render) - .addFunction("SetString", &Text::SetString) - .endClass(); - - - luabridge::getGlobalNamespace(L) - .beginClass("gcText") - .addFunction("GetPointer", &gcText::GetPointer) - .addIndexMetaMethod([](gcText& self, const luabridge::LuaRef& key, lua_State* L) -> luabridge::LuaRef - { - if (key.tostring() == "GetPointer") - {// 不清楚为何存在 GetPointer,还是会触发元函数 - luabridge::LuaRef ref_class = luabridge::getGlobal(L, "gcText"); - luabridge::LuaRef ref_func = ref_class[key]; - return ref_func; - } - // 获取到原Text函数 - luabridge::LuaRef ref_class = luabridge::getGlobal(L, "Text"); - luabridge::LuaRef ref_func = ref_class[key]; - luabridge::setGlobal(L, ref_func, "__dl_text_func"); - // 调用代理函数 - luabridge::LuaRef ref_proxy = luabridge::getGlobal(L, "__dl_text_proxy"); - return ref_proxy; - }) - .endClass(); - - // 注册sprite代理函数 - g_lua->DoString(R"( -__dl_text_func = nil -__dl_text_proxy = function(obj, ...) - __dl_text_func(obj:GetPointer(), ...) -end -)"); + l.new_usertype("Text", + "Render", &Text::Render, + "SetString", &Text::SetString); } #if DL_PLATFORM == DL_PLATFORM_WIN32 #define WIN32_LEAN_AND_MEAN #include - void lua_register_win32(lua_State* L) + void lua_register_win32(sol::state& l) { - luabridge::getGlobalNamespace(L) - .addFunction("system", &system); + l["system"] = system; } #endif - void lua_register_all(lua_State* L) + void lua_register_all(sol::state& l) { - lua_register_base(L); - lua_register_system(L); - lua_register_file(L); - lua_register_gfx(L); - lua_register_ui(L); - lua_register_factory(L); - lua_register_sprite(L); - lua_register_text(L); + lua_register_base(l); + lua_register_system(l); + lua_register_file(l); + lua_register_gfx(l); + lua_register_ui(l); + lua_register_factory(l); + lua_register_sprite(l); + lua_register_text(l); #if DL_PLATFORM == DL_PLATFORM_WIN32 - lua_register_win32(L); + lua_register_win32(l); #endif } diff --git a/dl/script/dl_lua_register.h b/dl/script/dl_lua_register.h index 04a57cec..35e00d66 100644 --- a/dl/script/dl_lua_register.h +++ b/dl/script/dl_lua_register.h @@ -11,16 +11,17 @@ */ #pragma once -struct lua_State; +#include "script/dl_lua.h" + namespace dl { - void lua_register_base(lua_State* L); - void lua_register_system(lua_State* L); - void lua_register_gfx(lua_State* L); - void lua_register_ui(lua_State* L); - void lua_register_factory(lua_State* L); - void lua_register_sprite(lua_State* L); - void lua_register_text(lua_State* L); - void lua_register_all(lua_State* L); + void lua_register_base(sol::state& l); + void lua_register_system(sol::state& l); + void lua_register_gfx(sol::state& l); + void lua_register_ui(sol::state& l); + void lua_register_factory(sol::state& l); + void lua_register_sprite(sol::state& l); + void lua_register_text(sol::state& l); + void lua_register_all(sol::state& l); } \ No newline at end of file diff --git a/dl/script/dl_lua_register_container.h b/dl/script/dl_lua_register_container.h index 07c75057..2f5b5ff6 100644 --- a/dl/script/dl_lua_register_container.h +++ b/dl/script/dl_lua_register_container.h @@ -11,147 +11,8 @@ */ #pragma once -#include -#include - // Array 绑定 -namespace luabridge { +namespace sol { - //================================================================================================= - /** - * @brief Stack specialization for `dl::Array`. - */ - template - struct Stack> - { - using Type = dl::Array; - - [[nodiscard]] static Result push(lua_State* L, const Type& array) - { -#if LUABRIDGE_SAFE_STACK_CHECKS - if (!lua_checkstack(L, 3)) - return makeErrorCode(ErrorCode::LuaStackOverflow); -#endif - - StackRestore stackRestore(L); - - lua_createtable(L, static_cast(Size), 0); - - for (std::size_t i = 0; i < Size; ++i) - { - lua_pushinteger(L, static_cast(i + 1)); - - auto result = Stack::push(L, array[i]); - if (!result) - return result; - - lua_settable(L, -3); - } - - stackRestore.reset(); - return {}; - } - - [[nodiscard]] static TypeResult get(lua_State* L, int index) - { - if (!lua_istable(L, index)) - return makeErrorCode(ErrorCode::InvalidTypeCast); - - if (get_length(L, index) != Size) - return makeErrorCode(ErrorCode::InvalidTableSizeInCast); - - const StackRestore stackRestore(L); - - Type array; - - int absIndex = lua_absindex(L, index); - lua_pushnil(L); - - int arrayIndex = 0; - while (lua_next(L, absIndex) != 0) - { - auto item = Stack::get(L, -1); - if (!item) - return makeErrorCode(ErrorCode::InvalidTypeCast); - - array[arrayIndex++] = *item; - lua_pop(L, 1); - } - - return array; - } - - [[nodiscard]] static bool isInstance(lua_State* L, int index) - { - return lua_istable(L, index) && get_length(L, index) == Size; - } - }; - -} // namespace luabridge - -namespace luabridge{ -//================================================================================================= -/** - * @brief Stack specialization for `dl::Vector2`. - */ -template -struct Stack, T> -{ - using Type = dl::Vector2; - - [[nodiscard]] static Result push(lua_State* L, const Type& vec) - { -#if LUABRIDGE_SAFE_STACK_CHECKS - if (!lua_checkstack(L, 3)) - return makeErrorCode(ErrorCode::LuaStackOverflow); -#endif - - StackRestore stackRestore(L); - - lua_createtable(L, 0, static_cast(vec.size())); - - for (auto it = vec.begin(); it != vec.end(); ++it) - { - auto result = Stack::push(L, *it); - if (!result) - return result; - - lua_settable(L, -3); - } - - stackRestore.reset(); - return {}; - } - - [[nodiscard]] static TypeResult get(lua_State* L, int index) - { - if (!lua_istable(L, index)) - return makeErrorCode(ErrorCode::InvalidTypeCast); - - const StackRestore stackRestore(L); - - Type vec; - - int absIndex = lua_absindex(L, index); - lua_pushnil(L); - - while (lua_next(L, absIndex) != 0) - { - auto value = Stack::get(L, -1); - if (!value) - return makeErrorCode(ErrorCode::InvalidTypeCast); - - vec.emplace_back(*value); - lua_pop(L, 1); - } - - return vec; - } - - [[nodiscard]] static bool isInstance(lua_State* L, int index) - { - return lua_istable(L, index); - } + }; - -} // namespace luabridge \ No newline at end of file diff --git a/dl/system/dl_system.cpp b/dl/system/dl_system.cpp index ba2e01d6..182b69a5 100644 --- a/dl/system/dl_system.cpp +++ b/dl/system/dl_system.cpp @@ -144,8 +144,7 @@ System::System() : _funcRun{ nullptr }, _fullScreenMode{ FullScreenMode::WINDOW }, _step{ SystemStep::START }, - _dir{ WindowDirection::UP }, - _lua{ g_lua->GetL() } + _dir{ WindowDirection::UP } { _imp = new SystemImp; } @@ -181,10 +180,7 @@ void System::Start(const ParamWindow& param) g_vk->GfxLock(); g_scene->_update(); if (_funcRun) _funcRun();//帧函数 - if (!_lua._funcUpdate.empty()) - { - g_lua->ExcuteFunction(_lua._funcUpdate); - } + g_lua->ExcuteFunction(_lua._funcRun); _step = SystemStep::RENDER; g_factory->_clear_pickup(); // 统一在Render处理OrderPickup @@ -612,14 +608,14 @@ void System::_resize() } -void System::lua_SetFuncInit(luabridge::LuaRef func) +void System::lua_SetFuncInit(sol::object func) { _lua._funcInit = func; } -void System::lua_SetFuncUpdate(std::string_view str) +void System::lua_SetFuncRun(sol::object func) { - _lua._funcUpdate = str; + _lua._funcRun = func; } const RenderInfo2D& System::GetRenderInfo2D() @@ -713,8 +709,7 @@ bool System::_start_init(const ParamWindow& param) //g_ui->_resize(); // 不应该调用(默认值就应该正确) if (_funcInit) _funcInit(); // 初始化函数(此时设置ui标准大小) - if (_lua._funcInit) - _lua._funcInit(); + g_lua->ExcuteFunction(_lua._funcInit); g_factory->_save_cache(); //-----------------游戏循环----------------------- #if (DL_PLATFORM == DL_PLATFORM_WIN32) diff --git a/dl/system/dl_system.h b/dl/system/dl_system.h index 1d1d84b2..5c164281 100644 --- a/dl/system/dl_system.h +++ b/dl/system/dl_system.h @@ -223,8 +223,8 @@ public: void _convert_glfw_to_system(Point& xy); void _convert_system_to_glfw(Point& xy); //--------------------------lua---------------------------- - void lua_SetFuncInit(luabridge::LuaRef func); - void lua_SetFuncUpdate(std::string_view str); + void lua_SetFuncInit(sol::object func); + void lua_SetFuncRun(sol::object func); private: SystemImp* _imp; Func _funcInit; @@ -243,8 +243,8 @@ private: struct { - luabridge::LuaRef _funcInit; - std::string _funcUpdate; + sol::function _funcInit; + sol::function _funcRun; }_lua; bool _start_init(const ParamWindow& param); diff --git a/project/dl_console/main.cpp b/project/dl_console/main.cpp index f45cad40..858d240e 100644 --- a/project/dl_console/main.cpp +++ b/project/dl_console/main.cpp @@ -20,8 +20,8 @@ int main(int argc, char* argv[]) #ifndef NDEBUG //lua_file = "批量小写文件名.lua"; //lua_file = "批量清除图片透明色.lua"; - lua_file = "窗口示例.lua"; - //lua_file = "批量缩放图片.lua"; + //lua_file = "窗口示例.lua"; + lua_file = "批量缩放图片.lua"; #else if(argc > 1) lua_file = CodeCvt::MultiByteToUtf8(argv[1]); diff --git a/project/dl_console/res/批量小写文件名.lua b/project/dl_console/res/批量小写文件名.lua index 31735a0e..a8ebdf70 100644 --- a/project/dl_console/res/批量小写文件名.lua +++ b/project/dl_console/res/批量小写文件名.lua @@ -1,19 +1,19 @@ -local path_src = g_file.GetAbsolute("./src/") -local path_out = g_file.GetAbsolute("./out/") +local path_src = File.GetAbsolute("./src/") +local path_out = File.GetAbsolute("./out/") -- 创建输出目录 -g_file.CreateFolder(path_out) -g_file.Copy(path_src, path_out, g_file.CopyMode.OVERRIDE, true) +File.CreateFolder(path_out) +File.Copy(path_src, path_out, File.CopyMode.OVERRIDE, true) -local ret_files = g_file.GetPathFileAll(path_out) +local ret_files = File.GetPathFileAll(path_out) for key, value in pairs(ret_files) do - local path = g_file.GetFilePath(value) - local filename = g_file.GetFileName(value) + local path = File.GetFilePath(value) + local filename = File.GetFileName(value) local out = path_out .. string.lower(filename) - g_file.Rename(value, out) + File.Rename(value, out) print(value.."->"..out) end diff --git a/project/dl_console/res/批量清除图片透明色.lua b/project/dl_console/res/批量清除图片透明色.lua index 7d499a6b..3e57efba 100644 --- a/project/dl_console/res/批量清除图片透明色.lua +++ b/project/dl_console/res/批量清除图片透明色.lua @@ -1,16 +1,16 @@ -local path_src = g_file.GetAbsolute("./src/") -local path_out = g_file.GetAbsolute("./out/") +local path_src = File.GetAbsolute("./src/") +local path_out = File.GetAbsolute("./out/") -- 创建输出目录 -g_file.DeleteContent(path_out) -g_file.CreateFolder(path_out) +File.DeleteContent(path_out) +File.CreateFolder(path_out) -local ret_files = g_file.GetPathFileAll(path_src, Img.REGEX_FORMAT, false) +local ret_files = File.GetPathFileAll(path_src, Img.REGEX_FORMAT, false) for key, value in pairs(ret_files) do - local path = g_file.GetFilePath(value) - local filename = g_file.GetFileName(value) + local path = File.GetFilePath(value) + local filename = File.GetFileName(value) local out = path_out .. string.lower(filename) diff --git a/project/dl_console/res/批量缩放图片.lua b/project/dl_console/res/批量缩放图片.lua index b40f70a4..19c0b1da 100644 --- a/project/dl_console/res/批量缩放图片.lua +++ b/project/dl_console/res/批量缩放图片.lua @@ -1,16 +1,16 @@ -local path_src = g_file.GetAbsolute("./src/") -local path_out = g_file.GetAbsolute("./out/") +local path_src = File.GetAbsolute("./src/") +local path_out = File.GetAbsolute("./out/") local scale = 0.5 -- 创建输出目录 -g_file.CreateFolder(path_out) +File.CreateFolder(path_out) -local ret_files = g_file.GetPathFileAll(path_src, Img.REGEX_FORMAT, false) +local ret_files = File.GetPathFileAll(path_src, Img.REGEX_FORMAT, false) for key, value in pairs(ret_files) do -- local img = Img.Create(value) - local out = path_out .. g_file.GetRelative(value, path_src) + local out = path_out .. File.GetRelative(value, path_src) out = String.ReplaceExtension(out, "png") local img_out = Img.Resize(img, scale) @@ -22,19 +22,19 @@ for key, value in pairs(ret_files) do local mata_name = String.EraseFilename(value) mata_name = mata_name .. "Placements/".. String.GetFileStem(value) .. ".txt" local out_name = String.EraseFilename(out) - g_file.CreateFolder(out_name .. "Placements/") + File.CreateFolder(out_name .. "Placements/") out_name = out_name .. "Placements/".. String.GetFileStem(value) .. ".txt" - local str = g_file.GetString(mata_name) + local str = File.GetString(mata_name) if #str > 0 then print(str) local pos = String.toPosition2(str, '\n') - pos[1] = math.floor(pos[1] * scale) - pos[2] = math.floor(pos[2] * scale) - str = pos[1]..'\n'..pos[2] + pos.x = math.floor(pos.x * scale) + pos.y = math.floor(pos.y * scale) + str = pos.x..'\n'..pos.y - g_file.SaveString(str, out_name) + File.SaveString(str, out_name) end print(value .. "->" .. out) diff --git a/project/dl_console/res/窗口示例.lua b/project/dl_console/res/窗口示例.lua index 7d03be23..7c7e9abb 100644 --- a/project/dl_console/res/窗口示例.lua +++ b/project/dl_console/res/窗口示例.lua @@ -7,9 +7,9 @@ function Init() txt:SetString("文本绘制测试") end -function Update() +function Run() -- log("额 hello dl! 22") - g_gfx:Rectangle2D({50, 100}, {950, 1000}) + g_gfx:Rectangle2D(Position(50, 100), Position(950, 1000)) spr:SetColor(ColorDef.NONE, 0) spr:Render() @@ -26,11 +26,11 @@ log("hello dl!") g_factory:SetPath("src/", "model/", "binary/", "temp/"); -local param = ParamWindow() +local param = ParamWindow.new() param.title = "dl lua" g_system:SetFuncInit(Init) -g_system:SetFuncRun("Update") +g_system:SetFuncRun(Run) g_system:Start(param) diff --git a/project/project.cmake b/project/project.cmake index b6ef40d6..fea06be6 100644 --- a/project/project.cmake +++ b/project/project.cmake @@ -73,8 +73,8 @@ include_directories(${CMAKE_SOURCE_DIR}/third/asio/include) include_directories(${CMAKE_SOURCE_DIR}/third/angelscript/angelscript/include) # lua include_directories(${CMAKE_SOURCE_DIR}/third/lua) -# lua bridge -include_directories(${CMAKE_SOURCE_DIR}/third/LuaBridge3/Source) +# sol2 +include_directories(${CMAKE_SOURCE_DIR}/third/sol2/include) # infoware include_directories(${CMAKE_SOURCE_DIR}/third/infoware/include) # simd