* lua绑定库替换为sol2

This commit is contained in:
2026-04-05 16:12:20 +08:00
parent 556ad75f61
commit ee346c8f28
19 changed files with 362 additions and 503 deletions
+1 -1
View File
@@ -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)
+3 -2
View File
@@ -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")
+58 -44
View File
@@ -661,7 +661,7 @@ inline std::vector<std::string> Split(const std::string& str, char d)
split(str, d, ret);
return ret;
}
inline std::vector<std::string_view> Split(std::string_view str, char d)
inline std::vector<std::string_view> SplitView(std::string_view str, char d)
{
std::vector<std::string_view> ret;
split(str, d, ret);
@@ -677,13 +677,34 @@ inline std::vector<std::string> Split(const std::string& str, const std::string&
split_sub(str, d, ret);
return ret;
}
inline std::vector<std::string_view> Split(std::string_view str, std::string_view d)
inline std::vector<std::string_view> SplitView(std::string_view str, std::string_view d)
{
std::vector<std::string_view> ret;
split_sub(str, d, ret);
return ret;
}
/**
* @brief 分割字符串(连续跳过匹配字符)
*/
inline std::vector<std::string> SplitNoEmpty(const std::string& str, char d)
{
std::vector<std::string> ret;
split_no_empty(str, d, ret);
return ret;
}
/**
* @brief 分割字符串(连续跳过匹配字符)
*/
inline std::vector<std::string_view> SplitViewNoEmpty(std::string_view str, char d)
{
std::vector<std::string_view> ret;
split_no_empty(str, d, ret);
return ret;
}
/**
* @brief 处理子字符串(通过特定字符分割)
* @param[in] str 整个字符串
@@ -713,48 +734,41 @@ inline std::vector<std::string_view> 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<std::string_view> SplitView(std::string_view str, std::string_view vec_ch)
{
std::vector<std::string_view> 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<std::string_view> SplitView(std::string_view str,
const std::vector<char>& vec_ch)
{
return SplitView(str, std::string_view{ vec_ch.data(), vec_ch.size() });
}
/**
* @brief 分割字符串(连续跳过匹配字符)
*/
inline std::vector<std::string> SplitNoEmpty(const std::string& str, char d)
{
std::vector<std::string> ret;
split_no_empty(str, d, ret);
return ret;
}
///**
//* @brief 处理子字符串(通过特定字符分割)
//* @param[in] str 整个字符串
//* @param[in] vec_ch 匹配的字符
//* @note 连续匹配返回空串
//*/
//inline std::vector<std::string_view> SplitView(std::string_view str, std::string_view vec_ch)
//{
// std::vector<std::string_view> 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<std::string_view> SplitView(std::string_view str,
// const std::vector<char>& vec_ch)
//{
// return SplitView(str, std::string_view{ vec_ch.data(), vec_ch.size() });
//}
/**
* @brief 移除末尾格式,移除后不包含.
+18 -2
View File
@@ -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<std::string_view> 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);
+5 -1
View File
@@ -52,7 +52,7 @@ class GC
public:
GC() :_p(nullptr), _ref(nullptr) {}
GC(const GC<T>& 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()
{
+2 -2
View File
@@ -45,7 +45,7 @@ namespace dl
ValueTypeInfo String2ValueTypeEx(std::string_view str)
{
ValueTypeInfo ret;
std::vector<std::string_view> vec = String::Split(str, '<');
std::vector<std::string_view> 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<std::string_view> vec1 = String::Split(vec[1], ',');
std::vector<std::string_view> vec1 = String::SplitView(vec[1], ',');
if (vec1.size() > 0)
{
ret._strType1 = vec1[0];
+22 -18
View File
@@ -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);
}
}
+7 -31
View File
@@ -17,10 +17,9 @@
#include <string>
#include <unordered_map>
#define LUA_USE_APICHECK
#define LUABRIDGE_HAS_EXCEPTIONS 0
#include <lua.hpp>
#include <LuaBridge/LuaBridge.h>
#define SOL_ALL_SAFETIES_ON 1
#define SOL_PRINT_ERRORS 0
#include <sol/sol.hpp>
#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 <typename T, typename ...Args>
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;
+190 -203
View File
@@ -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<dl::File::CopyMode> : luabridge::Enum<dl::File::CopyMode,
dl::File::CopyMode::NONE,
dl::File::CopyMode::OVERRIDE,
dl::File::CopyMode::SKIP>
{
};
#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 <typename T>
struct unique_usertype_traits<GC<T>>
{
typedef T type;
typedef GC<T> 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<Position2> : std::true_type {};*/
//template <>
//struct usertype_container<not_my_type> {
// ...
// // see below for implemetation details
//};
/*template <typename T, size_t N>
struct is_container<Array<T, N>> : std::true_type {};
template <typename T, size_t N>
struct usertype_container<Array<T, N>> {
static int size(lua_State* L)
{
Array<T, N>& v = sol::stack::get<Array<T, N>&>(L, 1);
return stack::push(L, N);
}
static int get(lua_State* L) {
Array<T, N>& v = sol::stack::get<Array<T, N>&>(L, 1);
std::ptrdiff_t idx = sol::stack::unqualified_get<std::ptrdiff_t>(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<T, N>& v = sol::stack::get<Array<T, N>&>(L, 1);
ret = v[0];
return {};
}
static void end(lua_State* L, T& ret)
{
Array<T, N>& v = sol::stack::get<Array<T, N>&>(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<const Position2&>(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<std::string_view, std::string_view>(String::ReplaceExtension))
.addFunction("EraseFilename",
luabridge::overload<std::string_view>(String::EraseFilename))
.endNamespace();
l.new_usertype<Position>("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<const Image*, float>(Img::Resize),
luabridge::overload<const Image*, const Size&>(Img::Resize))
.addFunction("SetAlphaZero",
luabridge::overload<Image*>(Img::SetAlphaZero),
luabridge::overload<Image*, uint8_t, uint32_t>(Img::SetAlphaZero))
.addFunction("Create",
luabridge::overload<std::string_view>(Img::Create),
luabridge::overload<const Size&, const Color&>(Img::Create))
.addFunction("Save", Img::Save)
.endNamespace();
{
sol::table ll = l["String"].get_or_create<sol::table>();
ll["ErasePath"] = String::ErasePath;
ll["GetFileStem"] = String::GetFileStem;
ll["toPosition2"] = String::toPosition2;
ll["ReplaceExtension"] = sol::resolve<std::string_view, std::string_view>(
String::ReplaceExtension);
ll["EraseFilename"] = sol::resolve<std::string_view>(
String::EraseFilename);
}
{
sol::table ll = l["Img"].get_or_create<sol::table>();
ll["REGEX_FORMAT"] = Img::REGEX_FORMAT;
ll["Resize"] = sol::overload(
sol::resolve<const Image*, float>(Img::Resize),
sol::resolve<const Image*, const Size&>(Img::Resize));
ll["SetAlphaZero"] = sol::overload(
sol::resolve<Image*, uint8_t, uint32_t>(Img::SetAlphaZero),
sol::resolve<void(Image*)>(Img::SetAlphaZero));
ll["Create"] = sol::overload(
sol::resolve<const Size&, const Color&>(Img::Create),
sol::resolve<std::string_view>(Img::Create));
ll["Save"] = Img::Save;
}
luabridge::getGlobalNamespace(L)
.beginClass<Image>("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>("ParamWindow")
.addConstructor<void (*)()>() // 忽略这个构造会出错……
.addProperty("title", &ParamWindow::_strTitle)
.endClass();
l.new_usertype<ParamWindow>("ParamWindow",
"title", &ParamWindow::_strTitle);
luabridge::getGlobalNamespace(L)
.beginClass<System>("System")
.addFunction("SetFuncInit", &System::lua_SetFuncInit)
.addFunction("SetFuncRun", &System::lua_SetFuncUpdate)
.addFunction("Start", (void(System::*)(const ParamWindow&))&System::Start)
.endClass();
l.new_usertype<System>("System", sol::no_constructor,
"SetFuncInit", &System::lua_SetFuncInit,
"SetFuncRun", &System::lua_SetFuncRun,
"Start", sol::resolve<void(const ParamWindow&)>(&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<sol::table>();
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<std::string_view, std::string_view>(File::SaveString))
.endNamespace();
{
sol::table ll = l["File"].get_or_create<sol::table>();
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<std::string_view, std::string_view>(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>("Graphics")
.addFunction("Rectangle2D", &Graphics::Rectangle2D)
.endClass();
l.new_usertype<Graphics>("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<Panel>("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>("Factory")
.addFunction("CreateText", &Factory::CreateText)
.addFunction("CreateTextDefault", &Factory::CreateTextDefault)
.addFunction("CreateSprite",
luabridge::overload<std::string_view, size_t>(&Factory::CreateSprite),
luabridge::overload<const SpriteID&>(&Factory::CreateSprite))
.addFunction("SetPath", &Factory::SetPath)
.endClass();
l.new_usertype<Factory>("Factory", sol::no_constructor,
"SetPath", &Factory::SetPath,
"CreateText", &Factory::CreateText,
"CreateTextDefault", &Factory::CreateTextDefault,
"CreateSprite", sol::overload(
sol::resolve<gcSprite(std::string_view, size_t)>(&Factory::CreateSprite),
sol::resolve<gcSprite(const SpriteID&)>(&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>("Sprite")
.addFunction("Render", &Sprite::Render)
.addFunction("SetColor",
luabridge::overload<const Color&>(&Sprite::SetColor),
luabridge::overload<const Color&, size_t>(&Sprite::SetColor))
.endClass();
luabridge::getGlobalNamespace(L)
.beginClass<gcSprite>("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>("Sprite",
"Render", &Sprite::Render,
"SetColor", sol::overload(
sol::resolve<void(const Color&)>(&Sprite::SetColor),
sol::resolve<void(const Color&, size_t)>(&Sprite::SetColor)
));
}
void lua_register_text(lua_State* L)
void lua_register_text(sol::state& l)
{
luabridge::getGlobalNamespace(L)
.beginClass<Text>("Text")
.addFunction("Render", &Text::Render)
.addFunction("SetString", &Text::SetString)
.endClass();
luabridge::getGlobalNamespace(L)
.beginClass<gcText>("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>("Text",
"Render", &Text::Render,
"SetString", &Text::SetString);
}
#if DL_PLATFORM == DL_PLATFORM_WIN32
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
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
}
+10 -9
View File
@@ -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);
}
+2 -141
View File
@@ -11,147 +11,8 @@
*/
#pragma once
#include <LuaBridge/Array.h>
#include <LuaBridge/Vector.h>
// Array 绑定
namespace luabridge {
namespace sol {
//=================================================================================================
/**
* @brief Stack specialization for `dl::Array`.
*/
template <class T, std::size_t Size>
struct Stack<dl::Array<T, Size>>
{
using Type = dl::Array<T, Size>;
[[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<int>(Size), 0);
for (std::size_t i = 0; i < Size; ++i)
{
lua_pushinteger(L, static_cast<lua_Integer>(i + 1));
auto result = Stack<T>::push(L, array[i]);
if (!result)
return result;
lua_settable(L, -3);
}
stackRestore.reset();
return {};
}
[[nodiscard]] static TypeResult<Type> 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<T>::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 <class T, class Index>
struct Stack<dl::Vector2<T, Index>, T>
{
using Type = dl::Vector2<T, Index>;
[[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<int>(vec.size()));
for (auto it = vec.begin(); it != vec.end(); ++it)
{
auto result = Stack<T>::push(L, *it);
if (!result)
return result;
lua_settable(L, -3);
}
stackRestore.reset();
return {};
}
[[nodiscard]] static TypeResult<Type> 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<T>::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
+6 -11
View File
@@ -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)
+4 -4
View File
@@ -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);
+2 -2
View File
@@ -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]);
@@ -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
@@ -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)
+11 -11
View File
@@ -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)
+4 -4
View File
@@ -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)
+2 -2
View File
@@ -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