add vec2, vec3, vec4 libraries

This commit is contained in:
MihailRis 2024-06-25 17:25:42 +03:00
parent 6f618ae3ff
commit 5ede84edc7
5 changed files with 54 additions and 14 deletions

View File

@ -22,6 +22,9 @@ extern const luaL_Reg packlib [];
extern const luaL_Reg playerlib [];
extern const luaL_Reg timelib [];
extern const luaL_Reg tomllib [];
extern const luaL_Reg vec2lib [];
extern const luaL_Reg vec3lib [];
extern const luaL_Reg vec4lib [];
extern const luaL_Reg worldlib [];
// Lua Overrides

View File

@ -60,9 +60,9 @@ static int l_mul(lua::State* L) {
}
case 3: {
if (len2 == 4) {
return lua::setvec4(L, 3, matrix1 * lua::tovec4(L, 2));
return lua::setvec(L, 3, matrix1 * lua::tovec4(L, 2));
} else if (len2 == 3) {
return lua::setvec3(L, 3, matrix1 * glm::vec4(lua::tovec3(L, 2), 1.0f));
return lua::setvec(L, 3, matrix1 * glm::vec4(lua::tovec3(L, 2), 1.0f));
}
return lua::setmat4(L, 3, matrix1 * lua::tomat4(L, 2));
}

View File

@ -0,0 +1,43 @@
#include "api_lua.hpp"
#include <glm/glm.hpp>
template<
uint n,
glm::vec<n, float>(*tofunc)(lua::State*, int),
int(*setfunc)(lua::State*, int, glm::vec<n, float>)
>
static int l_add(lua::State* L) {
uint argc = lua::gettop(L);
auto a = tofunc(L, 1);
auto b = tofunc(L, 2);
switch (argc) {
case 2:
lua::createtable(L, n, 0);
for (uint i = 0; i < n; i++) {
lua::pushnumber(L, a[i]+b[i]);
lua::rawseti(L, i+1);
}
return 1;
case 3:
return setfunc(L, 3, a + b);
default: {
throw std::runtime_error("invalid arguments number (2 or 3 expected)");
}
}
}
const luaL_Reg vec2lib [] = {
{"add", lua::wrap<l_add<2, lua::tovec2, lua::setvec<2>>>},
{NULL, NULL}
};
const luaL_Reg vec3lib [] = {
{"add", lua::wrap<l_add<3, lua::tovec3, lua::setvec<3>>>},
{NULL, NULL}
};
const luaL_Reg vec4lib [] = {
{"add", lua::wrap<l_add<4, lua::tovec4, lua::setvec<4>>>},
{NULL, NULL}
};

View File

@ -42,6 +42,9 @@ static void create_libs(lua::State* L) {
openlib(L, "player", playerlib);
openlib(L, "time", timelib);
openlib(L, "toml", tomllib);
openlib(L, "vec2", vec2lib);
openlib(L, "vec3", vec3lib);
openlib(L, "vec4", vec4lib);
openlib(L, "world", worldlib);
addfunc(L, "print", lua::wrap<l_print>);

View File

@ -221,19 +221,10 @@ namespace lua {
}
return 1;
}
/// @brief pushes vector table to the stack and updates it with glm vec4
inline int setvec4(lua::State* L, int idx, glm::vec4 vec) {
template<int n>
inline int setvec(lua::State* L, int idx, glm::vec<n, float> vec) {
pushvalue(L, idx);
for (uint i = 0; i < 4; i++) {
pushnumber(L, vec[i]);
rawseti(L, i+1);
}
return 1;
}
/// @brief pushes vector table to the stack and updates it with glm vec3
inline int setvec3(lua::State* L, int idx, glm::vec3 vec) {
pushvalue(L, idx);
for (uint i = 0; i < 3; i++) {
for (int i = 0; i < n; i++) {
pushnumber(L, vec[i]);
rawseti(L, i+1);
}