Debian Codegraph @

CorsixTH/Src/sdl_core.cpp

raw
1 /*
2 Copyright (c) 2009 Peter "Corsix" Cawley
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 of the Software, and to permit persons to whom the Software is furnished to do
9 so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23 #include "sdl_core.h"
24
25 #include <SDL.h>
26
27 #ifdef TRACY_ENABLE
28 #include <tracy/Tracy.hpp>
29 #endif
30
31 #include <array>
32 #include <cstdio>
33 #include <cstring>
34 #include <string_view>
35
36 #include "lua.hpp"
37 #include "lua_sdl.h"
38 #include "th_lua.h"
39
40 namespace {
41
42 int l_init(lua_State* L) {
43 Uint32 flags = 0;
44 int i;
45 int argc = lua_gettop(L);
46 for (i = 1; i <= argc; ++i) {
47 const char* s = luaL_checkstring(L, i);
48 if (std::strcmp(s, "video") == 0)
49 flags |= SDL_INIT_VIDEO;
50 else if (std::strcmp(s, "audio") == 0)
51 flags |= SDL_INIT_AUDIO;
52 else if (std::strcmp(s, "timer") == 0)
53 flags |= SDL_INIT_TIMER;
54 else if (std::strcmp(s, "*") == 0)
55 flags |= SDL_INIT_EVERYTHING;
56 else
57 luaL_argerror(L, i, "Expected SDL part name");
58 }
59 if (SDL_Init(flags) != 0) {
60 std::fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
61 lua_pushboolean(L, 0);
62 return 1;
63 }
64
65 lua_pushboolean(L, 1);
66 return 1;
67 }
68
69 Uint32 timer_frame_callback(Uint32 interval, void* param) {
70 SDL_Event e;
71 e.type = SDL_USEREVENT_TICK;
72 SDL_PushEvent(&e);
73 return interval;
74 }
75
76 class fps_ctrl {
77 public:
78 bool limit_fps{true};
79 bool track_fps{true};
80
81 size_t q_front{0};
82 size_t q_back{0};
83 int frame_count{0};
84 std::array<Uint32, 4096> frame_time{};
85
86 void init() {
87 limit_fps = true;
88 track_fps = true;
89 q_front = 0;
90 q_back = 0;
91 frame_count = 0;
92 }
93
94 void count_frame() {
95 Uint32 now = SDL_GetTicks();
96 frame_time[q_front] = now;
97 q_front = (q_front + 1) % frame_time.size();
98 if (q_front == q_back) {
99 q_back = (q_back + 1) % frame_time.size();
100 } else {
101 ++frame_count;
102 }
103
104 if (now < 1000) {
105 now = 0;
106 } else {
107 now -= 1000;
108 }
109
110 while (frame_time[q_back] < now) {
111 --frame_count;
112 q_back = (q_back + 1) % frame_time.size();
113 }
114 }
115 };
116
117 fps_ctrl fps;
118 constexpr uint32_t infinite_loop_limit{100};
119 uint32_t infinite_loop_counter{0};
120
121 void l_infinite_loop_hook(lua_State* L, lua_Debug*) {
122 infinite_loop_counter++;
123 if (infinite_loop_counter >= infinite_loop_limit) {
124 luaL_error(L, "Suspected infinite loop");
125 }
126 }
127
128 void l_push_modifiers_table(lua_State* L, Uint16 mod) {
129 lua_newtable(L);
130 if ((mod & KMOD_SHIFT) != 0) {
131 luaT_pushtablebool(L, "shift", true);
132 }
133 if ((mod & KMOD_ALT) != 0) {
134 luaT_pushtablebool(L, "alt", true);
135 }
136 if ((mod & KMOD_CTRL) != 0) {
137 luaT_pushtablebool(L, "ctrl", true);
138 }
139 if ((mod & KMOD_GUI) != 0) {
140 luaT_pushtablebool(L, "gui", true);
141 }
142 if ((mod & KMOD_NUM) != 0) {
143 luaT_pushtablebool(L, "numlockactive", true);
144 }
145 }
146
147 int l_get_key_modifiers(lua_State* L) {
148 l_push_modifiers_table(L, SDL_GetModState());
149 return 1;
150 }
151
152 int l_quit(lua_State*) {
153 SDL_Event e;
154 e.type = SDL_QUIT;
155 SDL_PushEvent(&e);
156 return 0;
157 }
158
159 /// Lua CFunction error handler for dispatch calls
160 /**
161 * Calls TheApp:errorHandler with the dispatch type and stacktrace of the
162 * error.
163 */
164 int l_error_handler(lua_State* L) {
165 lua_getglobal(L, "debug");
166 lua_getfield(L, -1, "traceback");
167 int traceArgs = 1;
168 if (lua_type(L, 1) == LUA_TSTRING) {
169 traceArgs = 2;
170 lua_pushvalue(L, 1);
171 }
172 lua_pushinteger(L, 2); // skip this level of the traceback
173 int err = lua_pcall(L, traceArgs, 1, 0);
174 if (err != LUA_OK) {
175 return err;
176 }
177
178 lua_getglobal(L, "TheApp");
179 lua_getfield(L, -1, "errorHandler");
180 lua_pushvalue(L, -2); // TheApp
181 lua_pushvalue(L, lua_upvalueindex(1));
182 lua_pushvalue(L, -5); // The traceback result
183
184 err = lua_pcall(L, 3, 0, 0);
185 lua_pushinteger(L, err);
186 return 1;
187 }
188
189 /// Add dispatch call to the stack
190 /**
191 * The resulting lua stack becomes:
192 * L(-4) - error handler function
193 * L(-3) - dispatch function
194 * L(-2) - TheApp global (first argument)
195 * L(-1) - dispatch type string
196 *
197 * Further arguments can be added before calling with lua_pcall
198 */
199 void push_app_dispatch(lua_State* L, std::string_view dispatch_event) {
200 lua_pushlstring(L, dispatch_event.data(), dispatch_event.size());
201 lua_pushcclosure(L, &l_error_handler, 1);
202 lua_getglobal(L, "TheApp");
203 lua_getfield(L, -1, "dispatch");
204 lua_pushvalue(L, -2);
205 lua_pushlstring(L, dispatch_event.data(), dispatch_event.size());
206
207 lua_remove(L, -4); // TheApp global
208 }
209
210 int l_track_fps(lua_State* L) {
211 fps.track_fps = lua_isnone(L, 1) ? true : (lua_toboolean(L, 1) != 0);
212 return 0;
213 }
214
215 int l_limit_fps(lua_State* L) {
216 fps.limit_fps = lua_isnone(L, 1) ? true : (lua_toboolean(L, 1) != 0);
217 return 0;
218 }
219
220 int l_get_fps(lua_State* L) {
221 if (fps.track_fps) {
222 lua_pushinteger(L, fps.frame_count);
223 } else {
224 lua_pushnil(L);
225 }
226 return 1;
227 }
228
229 int l_get_ticks(lua_State* L) {
230 lua_pushinteger(L, SDL_GetTicks());
231 return 1;
232 }
233
234 constexpr std::array<luaL_Reg, 8> sdllib{
235 {{"init", l_init},
236 {"quit", l_quit},
237 {"getTicks", l_get_ticks},
238 {"getKeyModifiers", l_get_key_modifiers},
239 {"getFPS", l_get_fps},
240 {"trackFPS", l_track_fps},
241 {"limitFPS", l_limit_fps},
242 {nullptr, nullptr}}};
243
244 void load_extra(lua_State* L, const char* name, lua_CFunction fn) {
245 luaT_pushcfunction(L, fn);
246 lua_call(L, 0, 1);
247 lua_setfield(L, -2, name);
248 }
249
250 } // namespace
251
252 constexpr std::string_view dispatch_keydown("keydown");
253 constexpr std::string_view dispatch_keyup("keyup");
254 constexpr std::string_view dispatch_textinput("textinput");
255 constexpr std::string_view dispatch_textediting("textediting");
256 constexpr std::string_view dispatch_buttondown("buttondown");
257 constexpr std::string_view dispatch_buttonup("buttonup");
258 constexpr std::string_view dispatch_mousewheel("mousewheel");
259 constexpr std::string_view dispatch_motion("motion");
260 constexpr std::string_view dispatch_multigesture("multigesture");
261 constexpr std::string_view dispatch_active("active");
262 constexpr std::string_view dispatch_music_over("music_over");
263 constexpr std::string_view dispatch_movie_over("movie_over");
264 constexpr std::string_view dispatch_sound_over("sound_over");
265 constexpr std::string_view dispatch_timer("timer");
266 constexpr std::string_view dispatch_callback("callback");
267 constexpr std::string_view dispatch_window_resize("window_resize");
268 constexpr std::string_view dispatch_frame("frame");
269
270 void mainloop(lua_State* L) {
271 SDL_TimerID timer =
272 SDL_AddTimer(usertick_period_ms, timer_frame_callback, nullptr);
273 SDL_Event e;
274
275 #ifndef TRACY_ENABLE
276 lua_Hook hookFn = lua_gethook(L);
277 if (!hookFn) {
278 lua_sethook(L, l_infinite_loop_hook, LUA_MASKCOUNT, 1e7);
279 } else {
280 std::printf(
281 "Warning: Infinite loop detection disabled due to existing Lua hook\n");
282 }
283 #endif
284
285 std::string_view last_dispatch;
286 int wait_error = 0;
287
288 while ((wait_error = SDL_WaitEvent(&e)) != 0) {
289 bool do_frame = false;
290 bool do_timer = false;
291 do {
292 int nargs;
293 switch (e.type) {
294 case SDL_QUIT:
295 goto leave_loop;
296 case SDL_KEYDOWN:
297 last_dispatch = dispatch_keydown;
298 push_app_dispatch(L, last_dispatch);
299 lua_pushstring(L, SDL_GetKeyName(e.key.keysym.sym));
300 l_push_modifiers_table(L, e.key.keysym.mod);
301 lua_pushboolean(L, e.key.repeat != 0);
302 nargs = 4;
303 break;
304 case SDL_KEYUP:
305 last_dispatch = dispatch_keyup;
306 push_app_dispatch(L, last_dispatch);
307 lua_pushstring(L, SDL_GetKeyName(e.key.keysym.sym));
308 l_push_modifiers_table(L, e.key.keysym.mod);
309 nargs = 3;
310 break;
311 case SDL_TEXTINPUT:
312 last_dispatch = dispatch_textinput;
313 push_app_dispatch(L, last_dispatch);
314 lua_pushstring(L, e.text.text);
315 nargs = 2;
316 break;
317 case SDL_TEXTEDITING:
318 last_dispatch = dispatch_textediting;
319 push_app_dispatch(L, dispatch_textediting);
320 lua_pushstring(L, e.edit.text);
321 lua_pushinteger(L, e.edit.start);
322 lua_pushinteger(L, e.edit.length);
323 nargs = 4;
324 break;
325 case SDL_MOUSEBUTTONDOWN:
326 last_dispatch = dispatch_buttondown;
327 push_app_dispatch(L, last_dispatch);
328 lua_pushinteger(L, e.button.button);
329 lua_pushinteger(L, e.button.x);
330 lua_pushinteger(L, e.button.y);
331 nargs = 4;
332 break;
333 case SDL_MOUSEBUTTONUP:
334 last_dispatch = dispatch_buttonup;
335 push_app_dispatch(L, dispatch_buttonup);
336 lua_pushinteger(L, e.button.button);
337 lua_pushinteger(L, e.button.x);
338 lua_pushinteger(L, e.button.y);
339 nargs = 4;
340 break;
341 case SDL_MOUSEWHEEL:
342 last_dispatch = dispatch_mousewheel;
343 push_app_dispatch(L, last_dispatch);
344 lua_pushinteger(L, e.wheel.x);
345 lua_pushinteger(L, e.wheel.y);
346 nargs = 3;
347 break;
348 case SDL_MOUSEMOTION:
349 last_dispatch = dispatch_motion;
350 push_app_dispatch(L, last_dispatch);
351 lua_pushinteger(L, e.motion.x);
352 lua_pushinteger(L, e.motion.y);
353 lua_pushinteger(L, e.motion.xrel);
354 lua_pushinteger(L, e.motion.yrel);
355 nargs = 5;
356 break;
357 case SDL_MULTIGESTURE:
358 last_dispatch = dispatch_multigesture;
359 push_app_dispatch(L, last_dispatch);
360 lua_pushinteger(L, e.mgesture.numFingers);
361 lua_pushnumber(L, e.mgesture.dTheta);
362 lua_pushnumber(L, e.mgesture.dDist);
363 lua_pushnumber(L, e.mgesture.x);
364 lua_pushnumber(L, e.mgesture.y);
365 nargs = 6;
366 break;
367 case SDL_WINDOWEVENT:
368 switch (e.window.event) {
369 case SDL_WINDOWEVENT_FOCUS_GAINED:
370 last_dispatch = dispatch_active;
371 push_app_dispatch(L, last_dispatch);
372 lua_pushinteger(L, 1);
373 nargs = 2;
374 break;
375 case SDL_WINDOWEVENT_FOCUS_LOST:
376 last_dispatch = dispatch_active;
377 push_app_dispatch(L, last_dispatch);
378 lua_pushinteger(L, 0);
379 nargs = 2;
380 break;
381 case SDL_WINDOWEVENT_SIZE_CHANGED:
382 last_dispatch = dispatch_window_resize;
383 push_app_dispatch(L, last_dispatch);
384 lua_pushinteger(L, e.window.data1);
385 lua_pushinteger(L, e.window.data2);
386 nargs = 3;
387 break;
388 default:
389 nargs = 0;
390 break;
391 }
392 break;
393 case SDL_USEREVENT_MUSIC_OVER:
394 last_dispatch = dispatch_music_over;
395 push_app_dispatch(L, last_dispatch);
396 nargs = 1;
397 break;
398 case SDL_USEREVENT_MUSIC_LOADED:
399 last_dispatch = dispatch_callback;
400 lua_pushlstring(L, last_dispatch.data(), last_dispatch.size());
401 lua_pushcclosure(L, &l_error_handler, 1);
402 lua_pushcfunction(L, &l_load_music_async_callback);
403 lua_pushlightuserdata(L, e.user.data1);
404 if (lua_pcall(L, 1, 0, -3) != LUA_OK) {
405 SDL_RemoveTimer(timer);
406 }
407 lua_pop(L, 1); // Remove l_error_handler
408 nargs = 0;
409 break;
410 case SDL_USEREVENT_TICK:
411 do_timer = true;
412 nargs = 0;
413 break;
414 case SDL_USEREVENT_MOVIE_OVER:
415 last_dispatch = dispatch_movie_over;
416 push_app_dispatch(L, last_dispatch);
417 nargs = 1;
418 break;
419 case SDL_USEREVENT_SOUND_OVER:
420 last_dispatch = dispatch_sound_over;
421 push_app_dispatch(L, last_dispatch);
422 lua_pushinteger(L, *(static_cast<int*>(e.user.data1)));
423 nargs = 2;
424 break;
425 default:
426 nargs = 0;
427 break;
428 }
429 if (nargs != 0) {
430 int res = lua_pcall(L, nargs + 1, 1, -3 - nargs);
431 if (res != LUA_OK) {
432 std::fprintf(stderr, "Error in %.*s: %s\n",
433 static_cast<int>(last_dispatch.size()),
434 last_dispatch.data(), lua_tostring(L, -1));
435 }
436 do_frame = do_frame || (lua_toboolean(L, -1) != 0);
437 lua_pop(L, 2);
438 }
439 } while (SDL_PollEvent(&e) != 0);
440 if (do_timer) {
441 last_dispatch = dispatch_timer;
442 push_app_dispatch(L, last_dispatch);
443 int res = lua_pcall(L, 2, 1, -4);
444 if (res != LUA_OK) {
445 std::fprintf(stderr, "Error in timer callback: %s\n",
446 lua_tostring(L, -1));
447 }
448 do_frame = do_frame || (lua_toboolean(L, -1) != 0);
449 lua_pop(L, 2);
450 }
451 if (do_frame || !fps.limit_fps) {
452 last_dispatch = dispatch_frame;
453 do {
454 if (fps.track_fps) {
455 fps.count_frame();
456 }
457 push_app_dispatch(L, last_dispatch);
458 int res = lua_pcall(L, 2, 1, -4);
459 if (res != LUA_OK) {
460 std::fprintf(stderr, "Error in frame callback: %s\n",
461 lua_tostring(L, -1));
462 } else {
463 do_frame = do_frame || (lua_toboolean(L, -1) != 0);
464 lua_pop(L, 2);
465 }
466 infinite_loop_counter = 0;
467 } while (fps.limit_fps == false && SDL_PollEvent(nullptr) == 0);
468 }
469
470 // No events pending - a good time to do a bit of garbage collection
471 lua_gc(L, LUA_GCSTEP, 2);
472 infinite_loop_counter = 0;
473 }
474
475 if (wait_error != 0) {
476 std::fprintf(stderr, "%s\n", SDL_GetError());
477 }
478
479 leave_loop:
480 SDL_RemoveTimer(timer);
481 }
482
483 int luaopen_sdl(lua_State* L) {
484 fps.init();
485 luaT_register(L, "sdl", sdllib);
486 load_extra(L, "audio", luaopen_sdl_audio);
487 load_extra(L, "wm", luaopen_sdl_wm);
488
489 return 1;
490 }