dark-hammer / src / engine / script.c

The branch 'v0.4' does not exist.
  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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/***********************************************************************************
 * Copyright (c) 2012, Sepehr Taghdisian
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice, 
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation 
 *   and/or other materials provided with the distribution.
 *
 ***********************************************************************************/

/**
 * notice: script executation is not currently thread-safe
 * but loading in another thread and memory management IS thread-safe */

#include "core/core.h"
#include "core/file-mgr.h"
#include "core/freelist-alloc.h"
#include "core/array.h"
#include "core/mutex.h"
#include "core/timer.h"

#include "script.h"

#include "lua/lua.h"
#include "lua/lualib.h"
#include "lua/lauxlib.h"

#include "mem-ids.h"
#include "console.h"
#include "debug-hud.h"
#include "engine.h"
#include "res-mgr.h"

/*************************************************************************************************
 * types 
 */
struct sct_timer_event
{
    uint32 id;
    char funcname[32];
    reshandle_t hdl;
    fl32 dt; /* in seconds */
    fl32 timeout;   /* in seconds */
    struct linked_list lnode;
};

struct sct_mgr
{
    struct freelist_alloc buff; 
    lua_State* cur_ls;  /* current running lua script (=NULL if nothing's running) */
    reshandle_t cur_hdl;    /* current running script handle */
    mutex_t mem_mtx;
    struct timer* tm;
    struct linked_list* tm_events;
    struct array garbage_scripts;   /* scripts that were not unloaded immediately (have events) 
                                       but now are garbage */
};

/*************************************************************************************************
 * fwd declerations
 */

/* callback for lua_State allocation 
 * see (lua_Alloc): http://www.lua.org/manual/5.1/manual.html */
void* sct_lua_alloc_callback(void* ud, void* ptr, size_t osize, size_t nsize);

/* callback for lua_State panic */
int sct_lua_panic_callback(lua_State* l);

/* bindings */
int luaopen_core(lua_State* l);
int luaopen_eng(lua_State* l);

/* console commands */
result_t sct_console_runfile(uint32 argc, const char** argv, void* param);
result_t sct_console_run(uint32 argc, const char** argv, void* param);

/* if fname=NULL, runs the whole script */
void sct_call(reshandle_t s_hdl, const char* fname, uint32 param1);

bool_t sct_checkresident(reshandle_t hdl);
void sct_collectgarbage();
void sct_addgarbage(reshandle_t hdl);
void sct_removealltimers();

/*************************************************************************************************
 * globals
 */
static struct sct_mgr g_sct;

/*************************************************************************************************
 * inlines
 */
INLINE const char* sct_geterror(lua_State* l)
{
    ASSERT(lua_isstring(l, -1))
    return lua_tostring(l, -1);
}

/*************************************************************************************************/
void sct_zero()
{
    memset(&g_sct, 0x00, sizeof(g_sct));
}

result_t sct_init(size_t mem_sz)
{
    result_t r;

    r = mem_freelist_create(mem_heap(), &g_sct.buff, mem_sz, MID_SCT);
    if (IS_FAIL(r)) {
        err_printn(__FILE__, __LINE__, RET_OUTOFMEMORY);
        return RET_OUTOFMEMORY;
    }

    r = arr_create(mem_heap(), &g_sct.garbage_scripts, sizeof(reshandle_t), 10, 10, MID_SCT);
    if (IS_FAIL(r)) {
        err_printn(__FILE__, __LINE__, RET_OUTOFMEMORY);
        return RET_OUTOFMEMORY;
    }

    g_sct.tm = timer_add(TRUE);

    mt_createmutex(&g_sct.mem_mtx);

    /* console commands */
    con_register_cmd("lua_runfile", sct_console_runfile, NULL, "lua_runfile [lua_file]");
    con_register_cmd("lua_run", sct_console_run, NULL, "lua_run [lua_script]");

    return RET_OK;
}

void sct_release()
{
    /* cleanup */
    sct_removealltimers();

    if (!arr_isempty(&g_sct.garbage_scripts)) {
        log_printf(LOG_INFO, "script: unloading %d resident scripts", 
            g_sct.garbage_scripts.item_cnt);
    }
    sct_collectgarbage();

    /* */
    uint32 leak_cnt = mem_freelist_getleaks(&g_sct.buff, NULL);
    if (leak_cnt > 0)   {
        log_printf(LOG_WARNING, "script: %d leaks detected:", leak_cnt);
        void** ptrs = (void**)ALLOC(sizeof(void*)*leak_cnt, MID_SCT);
        ASSERT(ptrs);
        mem_freelist_getleaks(&g_sct.buff, ptrs);
        for (uint32 i = 0; i < leak_cnt; i++) 
            log_printf(LOG_INFO, "\t0x%x", ptrs[i]);
        FREE(ptrs);
    }

    timer_remove(g_sct.tm);
    arr_destroy(&g_sct.garbage_scripts);
    mem_freelist_destroy(&g_sct.buff);
    mt_destroymutex(&g_sct.mem_mtx);
    sct_zero();
}

void sct_reload(const char* filepath, uint64 hdl, uptr_t param1, uptr_t param2)
{
    if (!rs_isinit())
        return;

    rs_load_script(filepath, RS_LOAD_REFRESH);
}

sct_t sct_load(const char* lua_filepath)
{
    struct allocator* tmp_alloc = eng_get_framealloc();
    eng_save_framealloc();

    /* load file data */
    file_t f = io_file_openmem(tmp_alloc, lua_filepath, FALSE, MID_SCT);
    if (f == FILE_NULL) {
        eng_load_framealloc();
        err_printf(__FILE__, __LINE__, "script: could not open file '%s'", lua_filepath);
        return NULL;
    }
    size_t size;
    void* buff = io_file_detachmem(f, &size, NULL);
    io_file_close(f); 

    /* create lua_state and open libraries */
    lua_State* ls = lua_newstate(sct_lua_alloc_callback, NULL);
    if (ls == NULL) {
        A_FREE(tmp_alloc, buff);
        eng_load_framealloc();
        err_printf(__FILE__, __LINE__, "script: could not create lua_State for '%s'", 
            lua_filepath);
        return NULL;
    }
    lua_atpanic(ls, sct_lua_panic_callback);

    luaopen_table(ls);
    luaopen_string(ls);
    luaopen_math(ls);
    luaopen_core(ls);
    luaopen_eng(ls);

    /* compile code */
    int r = luaL_loadbuffer(ls, buff, size, lua_filepath);
    A_FREE(tmp_alloc, buff);
    eng_load_framealloc();

    if (r != 0) {
        err_printf(__FILE__, __LINE__, "script: lua script '%s' failed: %s", 
            lua_filepath, sct_geterror(ls));
        return NULL;
    }

    /* ok */
    return ls;
}

void sct_unload(sct_t s)
{
    ASSERT(s);
    lua_close((lua_State*)s);
}

void* sct_lua_alloc_callback(void* ud, void* ptr, size_t osize, size_t nsize)
{
    mt_lockmutex(&g_sct.mem_mtx);
    void* rptr;
    if (ptr == NULL && nsize != 0)    { /* normal malloc */
        rptr = mem_freelist_alloc(&g_sct.buff, nsize, MID_SCT);
    }   else if (ptr != NULL && nsize == 0)   { /* free */
        mem_freelist_free(&g_sct.buff, ptr);
        rptr = NULL;
    }   else if (ptr != NULL && nsize != 0)   { /* realloc */
        void* tmp = mem_freelist_alloc(&g_sct.buff, nsize, MID_SCT);
        memcpy(tmp, ptr, minun(nsize, mem_freelist_getsize(&g_sct.buff, ptr)));
        mem_freelist_free(&g_sct.buff, ptr);
        rptr = tmp;
    }   else    {
        rptr = NULL;
    }
    mt_unlockmutex(&g_sct.mem_mtx);
    return rptr;
}

int sct_lua_panic_callback(lua_State* l)
{
    log_printf(LOG_ERROR, "lua: unprotected error: %s", sct_geterror(l));
    return 0;
}

void sct_throwerror(const char* fmt, ...)
{
    if (g_sct.cur_ls != NULL)   {
        char text[512];

        va_list args;
        va_start(args, fmt);
        vsnprintf(text, sizeof(text), fmt, args);
        va_end(args);

        luaL_error(g_sct.cur_ls, text);
    }
}

result_t sct_console_runfile(uint32 argc, const char** argv, void* param)
{
    if (argc != 1)
        return RET_INVALIDARG;
    sct_runfile(argv[0]);
    return RET_OK;
}

result_t sct_console_run(uint32 argc, const char** argv, void* param)
{
    if (argc != 1)
        return RET_INVALIDARG;

    sct_runstring(argv[0]);
    return RET_OK;
}

result_t sct_runfile(const char* lua_filepath)
{
    /* create and load the script */
    reshandle_t shdl = rs_load_script(lua_filepath, 0);
    if (shdl == INVALID_HANDLE)
        return RET_FAIL;

    /* run main script code */
    sct_call(shdl, NULL, 0);

    /* unload only if script is not resident */
    if (!sct_checkresident(shdl))
        rs_unload(shdl);

    return RET_OK;
}

void sct_runstring(const char* lua_script)
{

}

void sct_call(reshandle_t s_hdl, const char* fname, uint32 param1)
{
    lua_State* ls = rs_get_script(s_hdl); 
    g_sct.cur_ls = ls;
    g_sct.cur_hdl = s_hdl;

    int r;
    if (fname == NULL)  {
        r = lua_pcall(ls, 0, LUA_MULTRET, 0);
    }   else    {
        lua_getglobal(ls, fname);
        lua_pushinteger(ls, param1);
        r = lua_pcall(ls, 1, 0, 0);
    }
    
    g_sct.cur_ls = NULL;
    g_sct.cur_hdl = INVALID_HANDLE;

    if (r != 0) {
        log_printf(LOG_WARNING, "script: running '%s' failed: %s", 
            fname == NULL ? "(main)" : fname, sct_geterror(ls));
        return;
    }
}

void sct_update()
{
    fl32 dt = g_sct.tm->dt;

    /* call timer events in the scripts */
    struct linked_list* node = g_sct.tm_events;
    while (node != NULL)    {
        struct sct_timer_event* e = node->data;
        struct linked_list* next = node->next;
        e->dt += dt;
        if (e->dt > e->timeout) {
            e->dt = 0.0f;
            sct_call(e->hdl, e->funcname, e->id);
        }
        node = next;
    }

    sct_collectgarbage();
}

uint32 sct_addtimer(uint32 timeout, const char* funcname)
{
    static uint32 id = 1;

    struct sct_timer_event* e = ALLOC(sizeof(struct sct_timer_event), MID_SCT);
    memset(e, 0x00, sizeof(struct sct_timer_event));

    e->id = id++;
    str_safecpy(e->funcname, sizeof(e->funcname), funcname);
    e->hdl = g_sct.cur_hdl;
    e->timeout = ((fl32)timeout) / 1000.0f;
    
    list_add(&g_sct.tm_events, &e->lnode, e);
    return e->id;
}

void sct_removetimer(uint32 tid)
{
    struct linked_list* node = g_sct.tm_events;
    while (node != NULL)    {
        struct sct_timer_event* e = node->data;
        struct linked_list* next = node->next;
        if (e->id == tid)   {
            list_remove(&g_sct.tm_events, node);
            sct_addgarbage(e->hdl);
            FREE(e);
            break;
        }
        node = next;
    }
}

void sct_addgarbage(reshandle_t hdl)
{
    /* check if we have anymore pending events from the script */
    if (!sct_checkresident(hdl)) {
        reshandle_t* pres = arr_add(&g_sct.garbage_scripts);
        *pres = hdl;
    }
}

bool_t sct_checkresident(reshandle_t hdl)
{
    struct linked_list* node = g_sct.tm_events;
    while (node != NULL)    {
        struct sct_timer_event* e = node->data;
        if (e->hdl == hdl)
            return TRUE;
        node = node->next;
    }

    return FALSE;
}

void sct_collectgarbage()
{
    uint32 cnt = g_sct.garbage_scripts.item_cnt;
    reshandle_t* ress = g_sct.garbage_scripts.buffer;

    for (uint32 i = 0; i < cnt; i++)    {
        ASSERT(ress[i] != INVALID_HANDLE);
        rs_unload(ress[i]);
    }

    arr_clear(&g_sct.garbage_scripts);
}

void sct_removealltimers()
{
    struct linked_list* node = g_sct.tm_events;
    while (node != NULL)    {
        struct sct_timer_event* e = node->data;
        struct linked_list* next = node->next;

        list_remove(&g_sct.tm_events, node);
        sct_addgarbage(e->hdl);
        FREE(e);

        node = next;
    }
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.