Brenta Engine 1.2
Loading...
Searching...
No Matches
script.cpp
1// SPDX-License-Identifier: MIT
2// Author: Giovanni Santini
3// Mail: giovanni.santini@proton.me
4// Github: @San7o
5
6#include <brenta/script.hpp>
7#include <brenta/node.hpp>
8#include <brenta/logger.hpp>
9
10extern "C"
11{
12#include <lua/lua.h>
13#include <lua/lualib.h>
14#include <lua/lauxlib.h>
15}
16
17using namespace brenta;
18
19Node* Script::current_node = nullptr;
20
21Script::~Script()
22{
23 if (!this->state) return;
24
25 lua_close(this->state);
26 this->state = nullptr;
27}
28
29int Script::lua_get_position(lua_State* L)
30{
31 auto* node = Script::current_node;
32 if (!node) goto error;
33
34 lua_pushnumber(L, node->transform.position.x);
35 lua_pushnumber(L, node->transform.position.y);
36 lua_pushnumber(L, node->transform.position.z);
37 return 3;
38
39 error:
40 lua_pushnumber(L, 0);
41 lua_pushnumber(L, 0);
42 lua_pushnumber(L, 0);
43 return 3;
44}
45
46int Script::lua_set_position(lua_State* L)
47{
48 auto* node = Script::current_node;
49 if (!node) return 0;
50
51 float x = (float)luaL_checknumber(L, 1);
52 float y = (float)luaL_checknumber(L, 2);
53 float z = (float)luaL_checknumber(L, 3);
54
55 node->transform.position.x = x;
56 node->transform.position.y = y;
57 node->transform.position.z = z;
58 return 0;
59}
60
61void Script::init()
62{
63 if (this->state != nullptr) return;
64
65 this->state = luaL_newstate();
66 luaL_openlibs(this->state);
67
68 if (this->path)
69 {
70 if (!luaL_dofile(this->state, this->path->string().c_str()) == LUA_OK)
71 {
72 ERROR("Script: error running script {}: {}",
73 path->string(), lua_tostring(this->state, -1));
74 }
75 }
76 else if (this->source)
77 {
78 if (!luaL_dostring(this->state, this->source->c_str()) == LUA_OK)
79 {
80 ERROR("Script: error running script: {}",
81 lua_tostring(this->state, -1));
82 }
83 }
84 else
85 {
86 ERROR("Script: tried to run script with no source");
87 }
88
89 // Functions
90
91 lua_pushcfunction(this->state, lua_get_position);
92 lua_setglobal(this->state, "get_position");
93 lua_pushcfunction(this->state, lua_set_position);
94 lua_setglobal(this->state, "set_position");
95
96 DEBUG("Script: initialized");
97}
98
99void Script::reload()
100{
101 if (this->state != nullptr)
102 {
103 lua_close(this->state);
104 this->state = nullptr;
105 }
106
107 this->init();
108 DEBUG("Script: reloaded");
109}
110
111void Script::update(float delta_time)
112{
113 lua_getglobal(this->state, "update");
114 if (!lua_isfunction(this->state, -1))
115 {
116 lua_pop(this->state, 1);
117 return;
118 }
119
120 lua_pushnumber(this->state, delta_time);
121
122 if (lua_pcall(this->state, 1, 0, 0) != LUA_OK)
123 {
124 ERROR("Lua: Error: {}", lua_tostring(this->state, -1));
125 lua_pop(this->state, 1);
126 }
127}