open-card-table/main.c

133 lines
3.0 KiB
C

#include <stdio.h>
#include <lua5.3/lualib.h>
#include <lua5.3/lauxlib.h>
#include "termbox_render.h"
#include "oct_termbox_sprite.h"
#include "oct_networking.h"
#define TB_IMPL
#include "termbox.h"
// Errors
#define OCT_NO_LUA_FILE 1
#define OCT_LUA_FILE_NOT_FOUND 2
#define OCT_LUA_FILE_MISSING_OCT_INIT 3
#define OCT_LUA_FILENAME_SIZE 128
int oct_type;
lua_State *L;
struct {
char port[6]; // max 65535 so 6 bytes needed
// Might come in handy later to keep filename
// e.g. if I ever want to allow downloading a script from peer
char lua_file[OCT_LUA_FILENAME_SIZE];
} args;
int process_args(int argc, char* argv[]);
int initialize_everything(char* lua_file);
int deinitialize_everything();
int main(int argc, char* argv[]) {
int process_args_result = process_args(argc, argv);
switch (process_args_result) {
case OCT_NO_LUA_FILE:
fprintf(stderr, "No lua file given\n");
return EXIT_FAILURE;
break;
case OCT_LUA_FILE_NOT_FOUND:
fprintf(stderr, "Could not open file: %s\n", argv[argc-1]);
return EXIT_FAILURE;
break;
}
struct tb_event ev;
int finish = 0;
while (!finish) {
tb_clear();
tb_peek_event(&ev, 10);
if (ev.key == TB_KEY_ESC) {
finish = 1;
}
lua_getglobal(L, "oct_loop");
lua_pushinteger(L, ev.key);
lua_pushinteger(L, ev.ch);
lua_call(L, 2, 0);
for (uint32_t i=0; i < oct_tb_sprite_list.new_index; i++) {
oct_render_termbox_sprite(oct_tb_sprite_list.sprite_list[i]);
}
tb_present();
}
deinitialize_everything();
return EXIT_SUCCESS;
}
int process_args(int argc, char* argv[]) {
if (argc == 1) { // Didn't specify a file
return OCT_NO_LUA_FILE;
}
// Set args.port to default
strncpy(args.port, OCT_DEFAULT_PORT, 6);
for (int i = 1; i < argc-1; i++) {
// argv's are guaranteed to be zero-terminated, so can use
// strcmp instead of strncmp
if (strcmp(argv[i], "-p") == 0) {
if (i != (argc-2)) {
strncpy(args.port, argv[i+1], 6);
i++;
}
}
}
strncpy(args.lua_file, argv[argc-1], OCT_LUA_FILENAME_SIZE);
// TODO define other cmd line args here
return initialize_everything(argv[argc-1]); // lua file should always be last argument
}
int initialize_everything(char* lua_file) {
if (!oct_tb_sprite_list_initialize()) {
return 0;
}
L = luaL_newstate();
if (L == NULL) {
fprintf(stderr, "Can't initialize Lua\n");
return 0;
}
luaL_openlibs(L);
oct_tb_initialize_lua(L);
if (luaL_dofile(L, lua_file)) return OCT_LUA_FILE_NOT_FOUND;
lua_getglobal(L, "oct_init");
lua_call(L, 0, 1);
int type = lua_tointeger(L, -1);
//printf("TYPE: %d\n", type);
if (type == OCT_TYPE_SERVER) {
// TODO make port a command line argument
if (!oct_network_server_init(args.port)) {
printf("Could not establish a socket on port %s\n", args.port);
return 0;
}
}
else if (type == OCT_TYPE_CLIENT) {
//oct_network_client_init();
}
else {
// Do nothing, offline
}
tb_init();
return 0;
}
int deinitialize_everything() {
tb_shutdown();
lua_close(L);
oct_tb_sprite_list_deinitialize();
return 1;
}