-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtinybit.c
More file actions
297 lines (245 loc) · 8.52 KB
/
Copy pathtinybit.c
File metadata and controls
297 lines (245 loc) · 8.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
#include "tinybit.h"
#include <inttypes.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "lua_functions.h"
#include "lua_pool.h"
#include "cartridge.h"
#include "graphics.h"
#include "memory.h"
#include "audio.h"
#include "input.h"
#include "font.h"
#include "lua_scripts.h"
#include "lua/lua.h"
#include "lua/lualib.h"
#include "lua/lauxlib.h"
static bool running = true;
static int sleep_ms = 0;
static int sleep_start_time = 0;
long max_memory_usage = 0;
static lua_State* L;
static void (*error_func)(const char* message, const char* traceback) = NULL;
static void (*frame_func)();
static void (*input_func)();
static int (*get_ticks_ms_func)();
static void (*audio_queue_func)();
// Lua message handler used as the msgh arg of the runtime lua_pcall.
// Receives the original error on the stack, returns a string that is
// "<original>\nstack traceback:\n<frames…>".
static int err_msgh(lua_State* l) {
const char* msg = lua_tostring(l, 1);
if (!msg) msg = "(non-string error)";
luaL_traceback(l, l, msg, 1);
return 1;
}
// Pops the error from the top of the Lua stack and, if error_func is set,
// invokes it. For runtime errors (with_trace != 0), splits the combined
// "msg\nstack traceback:\nframes" string from err_msgh into two parts.
static void emit_lua_error(lua_State* l, int with_trace) {
const char* raw = lua_tostring(l, -1);
if (!raw) raw = "(non-string error)";
if (error_func) {
if (with_trace) {
const char* sep = strstr(raw, "\nstack traceback:");
if (sep) {
size_t msg_len = (size_t)(sep - raw);
static char msg_buf[4096];
if (msg_len >= sizeof(msg_buf)) msg_len = sizeof(msg_buf) - 1;
memcpy(msg_buf, raw, msg_len);
msg_buf[msg_len] = '\0';
const char* trace = sep + 1; // skip leading newline
error_func(msg_buf, trace);
} else {
error_func(raw, NULL);
}
} else {
error_func(raw, NULL);
}
}
lua_pop(l, 1);
}
// Initialize the TinyBit system with memory, input state, and audio buffer pointers
void tinybit_init(struct TinyBitMemory* memory) {
if (!memory) {
return; // Error: null pointer
}
tinybit_memory = memory;
// initialize memory
srand(time(NULL));
memory_init();
lua_pool_reset();
tb_audio_init();
cartridge_init();
graphics_init();
font_init();
// reset frame loop state so a re-init mid-session starts from a clean slate
running = true;
sleep_ms = 0;
sleep_start_time = 0;
// set up lua VM
L = lua_pool_newstate();
// add special functions to lua for reading game files
cartridge_register_lua(L);
// initialize the game loader as the default "game"
memcpy(tinybit_memory->script, launcher, strlen(launcher) + 1); // copy script to memory
}
// Start executing the Lua script currently loaded in memory
bool tinybit_start(){
const char* script = (const char*)tinybit_memory->script;
size_t script_len = strlen(script);
if (luaL_loadbuffer(L, script, script_len, "=script") != LUA_OK) {
// Compile error — no Lua stack yet, so no traceback.
emit_lua_error(L, /*with_trace=*/0);
return false;
}
// Load succeeded — install the message handler below the loaded chunk so
// a top-level runtime error in the script gets a traceback.
int msgh_idx = lua_gettop(L); // index of the loaded chunk
lua_pushcfunction(L, err_msgh); // [..., chunk, err_msgh]
lua_insert(L, msgh_idx); // [..., err_msgh, chunk]
if (lua_pcall(L, 0, 0, msgh_idx) != LUA_OK) {
emit_lua_error(L, /*with_trace=*/1);
lua_remove(L, msgh_idx);
return false;
}
lua_remove(L, msgh_idx);
return true;
}
// Reset the Lua state and start a new game
bool tinybit_restart(){
lua_close(L);
L = lua_pool_newstate();
draw_cls();
return tinybit_start();
}
// Signal the emulation loop to quit
void tinybit_stop() {
running = false;
lua_close(L);
L = NULL;
cartridge_destroy();
}
void tinybit_sleep(int ms) {
sleep_ms = ms;
sleep_start_time = get_ticks_ms_func();
}
// Current Lua heap usage in bytes; capacity is TB_MEM_LUA_STATE_SIZE.
size_t tinybit_lua_memory_used() {
return lua_pool_get_used();
}
// Feed cartridge PNG data to the TinyBit decoder
bool tinybit_feed_cartridge(const uint8_t* buffer, size_t size){
return cartridge_feed(buffer, size);
}
// Main emulation loop - handles input, executes Lua draw function, and renders frames
void tinybit_loop() {
uint32_t start_time;
uint32_t render_time;
uint32_t input_time;
uint32_t display_time;
uint32_t audio_time;
frame_time = get_ticks_ms_func();
start_time = frame_time;
// INPUT
input_func();
input_time = get_ticks_ms_func() - start_time;
start_time += input_time;
// LOGIC
if(sleep_ms == 0 || get_ticks_ms_func() - sleep_start_time >= sleep_ms) {
sleep_ms = 0;
lua_pushcfunction(L, err_msgh);
int msgh_idx = lua_gettop(L);
lua_getglobal(L, "_draw");
int status = lua_pcall(L, 0, 1, msgh_idx);
if (status == LUA_OK) {
lua_pop(L, 1); // pop the (unused) result
lua_remove(L, msgh_idx); // pop the message handler
} else {
emit_lua_error(L, /*with_trace=*/1); // pops the error (with traceback)
lua_remove(L, msgh_idx); // pop the message handler
audio_stop_all();
// error_screen is a hand-written clean script; tinybit_restart()
// will tinybit_start() it and the new path will not re-fire emit_lua_error.
strcpy((char*)tinybit_memory->script, error_screen);
tinybit_restart();
}
}
// deferred game load
if (cartridge_load_pending()) {
return;
}
render_time = get_ticks_ms_func() - start_time;
start_time += render_time;
// save current button state
save_button_state();
// AUDIO
process_audio();
if (audio_queue_func) {
audio_queue_func();
}
audio_time = get_ticks_ms_func() - start_time;
start_time += audio_time;
// RENDER
if (frame_func) {
frame_func();
}
display_time = get_ticks_ms_func() - start_time;
start_time += display_time;
// size_t used_memory = lua_pool_get_used();
// if (used_memory > max_memory_usage) {
// max_memory_usage = used_memory;
// printf("[TinyBit] New max memory usage: %zu bytes\n", max_memory_usage);
// }
// printf("[TinyBit] Frame time: %d ms (render: %d ms, display: %d ms, audio: %d ms)\n", get_ticks_ms_func() - frame_time, render_time, display_time, audio_time);
}
// Set callback function that gets called when a new frame should be drawn
void tinybit_render_cb(void (*render_func_ptr)()) {
if (!render_func_ptr) {
return; // Error: null pointer
}
frame_func = render_func_ptr;
}
// Set callback function that gets called to read button state
void tinybit_poll_input_cb(void (*poll_input_func_ptr)()) {
if (!poll_input_func_ptr) {
return; // Error: null pointer
}
input_func = poll_input_func_ptr;
}
void tinybit_log_cb(void (*log_func_ptr)(const char*)){
if (!log_func_ptr) {
return; // Error: null pointer
}
log_func = log_func_ptr;
}
void tinybit_error_cb(void (*error_func_ptr)(const char* message, const char* traceback)) {
error_func = error_func_ptr;
}
void tinybit_get_ticks_ms_cb(int (*get_ticks_ms_func_ptr)()) {
if (!get_ticks_ms_func_ptr) {
return; // Error: null pointer
}
get_ticks_ms_func = get_ticks_ms_func_ptr;
}
// Set callback function for queuing audio each frame
void tinybit_audio_queue_cb(void (*audio_queue_func_ptr)()) {
if (!audio_queue_func_ptr) {
return; // Error: null pointer
}
audio_queue_func = audio_queue_func_ptr;
}
void tinybit_gamecount_cb(int (*gamecount_func_ptr)()) {
if (!gamecount_func_ptr) {
return;
}
gamecount_func = gamecount_func_ptr;
}
void tinybit_gameload_cb(void (*gameload_func_ptr)(int index)) {
if (!gameload_func_ptr) {
return;
}
gameload_func = gameload_func_ptr;
}