summaryrefslogtreecommitdiff
path: root/src/main.c
blob: 9b83a8f30b9271022ea735b048f6f1f19ff8db08 (plain)
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
#include "honey.h"

int main(int argc, char** argv)
{
    honey_options opts;
    if (!honey_parse_options(&opts, argc, argv)) {
        return 0;
    }

    lua_State* L;

    if (!honey_setup(&L))
        return 1;

    lua_getglobal(L, "honey");
    lua_getfield(L, -1, "window");
    lua_getfield(L, -1, "internal");
    honey_window_information* info = lua_touserdata(L, -1);
    lua_pop(L, 2);
    honey_window window = info->window;

    char* script;
    honey_result res = honey_format_string(&script,
                                           "%s/main.lua",
                                           opts.script_directory);
    if (res != HONEY_OK) {
        fprintf(stderr, "[honey] FATAL: could not allocate space for script filename!");
        return 1;
    }
    
    if (luaL_loadfile(L, script) == 0) {
        if (!honey_lua_pcall(L, 0, 1) == 0) {
            const char* error = lua_tostring(L, -1);
            fprintf(stderr, "[honey] ERROR: %s\n", error);
            return 1;
        }
    }
    else {
        fprintf(stderr, "ERROR: failed to open %s!\n", script);
        return 1;
    }

    int update_callback = honey_get_callback(L, "update");
    int draw_callback   = honey_get_callback(L, "draw");
    
    float prevTime = 0;
    float currentTime = 0;
    float dt;
    
    while (!glfwWindowShouldClose(window)) {
        currentTime = (float) glfwGetTime();
        dt = currentTime - prevTime;
        prevTime = currentTime;
        glfwPollEvents();

        if (update_callback != LUA_NOREF) {
            lua_rawgeti(L, LUA_REGISTRYINDEX, update_callback);
            lua_pushnumber(L, dt);
            int result = honey_lua_pcall(L, 1, 0);
            if (result != 0) {
                const char* error = lua_tostring(L, -1);
                fprintf(stderr, "[honey] ERROR: %s\n", error);
                glfwSetWindowShouldClose(window, true);
            }
        }

        if (draw_callback != LUA_NOREF) {
            lua_rawgeti(L, LUA_REGISTRYINDEX, draw_callback);
            int result = honey_lua_pcall(L, 0, 0);
            if (result != 0) {
                const char* error = lua_tostring(L, -1);
                fprintf(stderr, "[honey] ERROR: %s\n", error);
                glfwSetWindowShouldClose(window, true);
            }
        }
    }

    lua_close(L);
    
    glfwTerminate();
    return 0;
}