-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathui_main.cpp
565 lines (497 loc) · 12.5 KB
/
ui_main.cpp
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
// DyLua: SimpleGraphic
// (c) David Gowor, 2014
//
// Module: UI Main
//
#include "ui_local.h"
// ======
// Locals
// ======
static struct {
int key;
const char* str;
} ui_keyNameMap[] = {
KEY_LMOUSE, "LEFTBUTTON",
KEY_MMOUSE, "MIDDLEBUTTON",
KEY_RMOUSE, "RIGHTBUTTON",
KEY_MOUSE4, "MOUSE4",
KEY_MOUSE5, "MOUSE5",
KEY_MWHEELUP, "WHEELUP",
KEY_MWHEELDOWN, "WHEELDOWN",
KEY_BACK, "BACK",
KEY_TAB, "TAB",
KEY_RETURN, "RETURN",
KEY_ESCAPE, "ESCAPE",
KEY_SHIFT, "SHIFT",
KEY_CTRL, "CTRL",
KEY_ALT, "ALT",
KEY_PAUSE, "PAUSE",
KEY_PGUP, "PAGEUP",
KEY_PGDN, "PAGEDOWN",
KEY_END, "END",
KEY_HOME, "HOME",
KEY_PRINTSCRN, "PRINTSCREEN",
KEY_INSERT, "INSERT",
KEY_DELETE, "DELETE",
KEY_UP, "UP",
KEY_DOWN, "DOWN",
KEY_LEFT, "LEFT",
KEY_RIGHT, "RIGHT",
KEY_F1, "F1",
KEY_F2, "F2",
KEY_F3, "F3",
KEY_F4, "F4",
KEY_F5, "F5",
KEY_F6, "F6",
KEY_F7, "F7",
KEY_F8, "F8",
KEY_F9, "F9",
KEY_F10, "F10",
KEY_F11, "F11",
KEY_F12, "F12",
KEY_F13, "F13",
KEY_F14, "F14",
KEY_F15, "F15",
KEY_NUMLOCK, "NUMLOCK",
KEY_SCROLL, "SCROLLLOCK",
0, 0
};
// ==================
// ui_IMain Interface
// ==================
ui_IMain* ui_IMain::GetHandle(sys_IMain* sysHnd, core_IMain* coreHnd)
{
return new ui_main_c(sysHnd, coreHnd);
}
void ui_IMain::FreeHandle(ui_IMain* hnd)
{
delete (ui_main_c*)hnd;
}
ui_main_c::ui_main_c(sys_IMain* sysHnd, core_IMain* coreHnd)
: sys(sysHnd), core(coreHnd), framesSinceWindowHidden(0)
{
renderer = NULL;
}
// =======================
// Lua Interface Utilities
// =======================
void ui_main_c::LAssert(lua_State* L, int cond, const char* fmt, ...)
{
if ( !cond ) {
va_list va;
va_start(va, fmt);
lua_pushvfstring(L, fmt, va);
va_end(va);
lua_error(L);
}
}
void ui_main_c::LExpect(lua_State* L, int cond, const char* fmt, ...)
{
if (!cond) {
va_list va;
va_start(va, fmt);
lua_pushvfstring(L, fmt, va);
va_end(va);
throw ui_expectationFailed_s{};
}
}
int ui_main_c::IsUserData(lua_State* L, int index, const char* metaName)
{
if (lua_type(L, index) != LUA_TUSERDATA || lua_getmetatable(L, index) == 0) {
return 0;
}
lua_getfield(L, LUA_REGISTRYINDEX, metaName);
int ret = lua_rawequal(L, -2, -1);
lua_pop(L, 2);
return ret;
}
int ui_main_c::PushCallback(const char* name)
{
lua_getfield(L, LUA_REGISTRYINDEX, "uicallbacks");
lua_getfield(L, -1, name); // Index callbacks table
// Stack: -2 = callbacks table, -1 = function or nil
if (lua_isfunction(L, -1)) {
lua_remove(L, -2); // Remove callbacks table
return 0;
} else {
lua_pop(L, 1); // Pop nil value
lua_getfield(L, -1, "MainObject"); // Index callbacks table
lua_remove(L, -2); // Remove callbacks table
// Stack: -1 = main object or nil
if (lua_istable(L, -1)) {
lua_getfield(L, -1, name); // Index main object
// Stack: -2 = main object, -1 = function or nil
if (lua_isfunction(L, -1)) {
lua_insert(L, -2); // Insert function before main object
return 1;
} else {
lua_pop(L, 2); // Pop main object, nil value
}
} else {
lua_pop(L, 1); // Pop nil value
}
}
return -1;
}
void ui_main_c::PCall(int narg, int nret)
{
sys->SetWorkDir(scriptWorkDir);
inLua = true;
int err = lua_pcall(L, narg, nret, 1);
inLua = false;
sys->SetWorkDir();
if (err && !didExit) {
DoError("Runtime error in", lua_tostring(L, -1));
}
}
void ui_main_c::DoError(const char* msg, const char* error)
{
auto scriptStr = scriptName.generic_u8string();
char* errText = AllocStringLen(strlen(msg) + scriptStr.size() + strlen(error) + 30);
sprintf(errText, "--- SCRIPT ERROR ---\n%s '%s':\n%s\n", msg, scriptStr.c_str(), error);
sys->Exit(errText);
FreeString(errText);
didExit = true;
}
// From lua.c
static int traceback (lua_State *L) {
if (!lua_isstring(L, 1)) /* 'message' not a string? */
return 1; /* keep it intact */
lua_getglobal(L, "debug");
if (!lua_istable(L, -1)) {
lua_pop(L, 1);
return 1;
}
lua_getfield(L, -1, "traceback");
if (!lua_isfunction(L, -1)) {
lua_pop(L, 2);
return 1;
}
lua_pushvalue(L, 1); /* pass error message */
lua_pushinteger(L, 2); /* skip this function and traceback */
lua_call(L, 2, 1); /* call debug.traceback */
return 1;
}
static int l_panicFunc(lua_State* L)
{
lua_rawgeti(L, LUA_REGISTRYINDEX, ui_main_c::REGISTRY_KEY);
ui_main_c* ui = (ui_main_c*)lua_touserdata(L, -1);
lua_pop(L, 1);
ui->sys->Error("Unprotected Lua error:\n%s", lua_tostring(L, -1));
return 0;
}
// ======================
// UI Init/Frame/Shutdown
// ======================
void ui_main_c::Init(int argc, char** argv)
{
// Find paths
scriptName = std::filesystem::u8path(argv[0]);
if (scriptName.is_relative()) {
scriptName = sys->basePath / scriptName;
}
scriptName = canonical(scriptName);
scriptCfg = scriptName;
scriptCfg.replace_extension(".cfg");
auto scriptParent = scriptName.parent_path();
scriptPath = scriptParent;
scriptWorkDir = scriptParent;
scriptArgc = argc;
scriptArgv = new char*[argc];
for (int a = 0; a < argc; a++) {
scriptArgv[a] = AllocString(argv[a]);
}
// Load config files
core->config->LoadConfig("SimpleGraphic/SimpleGraphic.cfg");
core->config->LoadConfig("SimpleGraphic/SimpleGraphicAuto.cfg");
if (core->config->LoadConfig(scriptCfg)) {
scriptCfg.clear();
}
// Initialise script
ScriptInit();
while (restartFlag && !didExit) {
ScriptShutdown();
ScriptInit();
}
}
void ui_main_c::RenderInit(r_featureFlag_e features)
{
if (renderer) {
return;
}
sys->SetWorkDir();
sys->con->ExecCommands(true);
// Initialise window
core->video->Apply();
// Initialise renderer
renderer = r_IRenderer::GetHandle(sys);
renderer->Init(features);
// Create UI console handler
conUI = ui_IConsole::GetHandle(this);
sys->con->Printf("\n");
sys->SetWorkDir(scriptWorkDir);
}
void ui_main_c::ScriptInit()
{
sys->con->PrintFunc("UI Init");
sys->con->Printf("Script: %s\n", scriptName.generic_u8string().c_str());
if (!scriptPath.empty()) {
sys->con->Printf("Script working directory: %s\n", scriptWorkDir.generic_u8string().c_str());
}
sys->video->SetTitle(scriptName.generic_u8string().c_str());
restartFlag = false;
didExit = false;
renderEnable = false;
inLua = false;
// Initialise Lua
sys->con->Printf("Initialising Lua...\n");
solState.emplace();
L = solState->lua_state();
if ( !L ) sys->Error("Error: unable to create Lua state.");
lua_atpanic(L, l_panicFunc);
lua_pushlightuserdata(L, this);
lua_seti(L, LUA_REGISTRYINDEX, ui_main_c::REGISTRY_KEY);
lua_pushcfunction(L, traceback);
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, "traceback");
#if _WIN32
lua_pushboolean(L, 1);
lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
#endif
// Add libraries and APIs
lua_gc(L, LUA_GCSTOP, 0);
lua_pushcfunction(L, InitAPI);
int err = lua_pcall(L, 0, 0, 0);
if (err) sys->Error("Error initialising Lua environment: \n%s\n", lua_tostring(L, -1));
lua_gc(L, LUA_GCRESTART, -1);
// Setup debug system
debug = ui_IDebug::GetHandle(this);
// Setup subscript system
subScriptSize = 16;
subScriptList = new ui_ISubScript*[subScriptSize];
for (dword i = 0; i < subScriptSize; i++) {
subScriptList[i] = NULL;
}
// Load the script file
sys->SetWorkDir(scriptWorkDir);
err = luaL_loadfile(L, scriptName.filename().generic_u8string().c_str());
if (err) {
DoError("Error loading", lua_tostring(L, -1));
return;
}
sys->SetWorkDir();
// Run the script
sys->con->Printf("Running script...\n");
for (int i = 0; i < scriptArgc; i++) {
lua_pushstring(L, scriptArgv[i]);
}
lua_createtable(L, scriptArgc - 1, 1);
for (int i = 0; i < scriptArgc; i++) {
lua_pushstring(L, scriptArgv[i]);
lua_rawseti(L, -2, i);
}
lua_setglobal(L, "arg");
PCall(scriptArgc, 0);
if ( !didExit && !restartFlag ) {
// Run initialisation callback
int extraArgs = PushCallback("OnInit");
if (extraArgs >= 0) {
PCall(extraArgs, 0);
}
}
if ( !didExit && !restartFlag ) {
// Check for frame callback
int extraArgs = PushCallback("OnFrame");
if (extraArgs >= 0) {
lua_pop(L, 1 + extraArgs);
} else {
sys->con->Printf("\nScript didn't set frame callback, exiting...\n");
sys->Exit();
}
}
}
void ui_main_c::Frame()
{
if (!sys->video->IsVisible() || sys->conWin->IsVisible() || restartFlag || didExit) {
framesSinceWindowHidden = 0;
}
else if (framesSinceWindowHidden <= 10) {
framesSinceWindowHidden++;
}
else if (!sys->video->IsActive() && !sys->video->IsCursorOverWindow()) {
sys->Sleep(100);
return;
}
if (renderer) {
// Prepare for rendering
renderer->BeginFrame();
sys->video->GetRelativeCursor(cursorX, cursorY);
}
renderEnable = true;
// Run subscript system
for (dword i = 0; i < subScriptSize; i++) {
if (subScriptList[i]) {
subScriptList[i]->SubScriptFrame();
if ( !subScriptList[i]->IsRunning() ) {
ui_ISubScript::FreeHandle(subScriptList[i]);
subScriptList[i] = NULL;
}
}
}
// Run script
//sys->con->Printf("OnFrame...\n");
int extraArgs = PushCallback("OnFrame");
if (extraArgs >= 0) {
PCall(extraArgs, 0);
}
renderEnable = false;
if (renderer) {
// Render console
//sys->con->Printf("Render console...\n");
renderer->SetDrawLayer(10000);
conUI->Render();
// Finish up
//sys->con->Printf("EndFrame...\n");
renderer->EndFrame();
}
//sys->con->Printf("Finishing up...\n");
if ( !sys->video->IsActive() ) {
sys->Sleep(100);
}
while (restartFlag) {
ScriptShutdown();
if (renderer) {
renderer->PurgeShaders();
}
ScriptInit();
}
}
void ui_main_c::ScriptShutdown()
{
// Run exit callback
int extraArgs = PushCallback("OnExit");
if (extraArgs >= 0) {
PCall(extraArgs, 0);
}
// Shutdown subscript and debug systems
for (dword i = 0; i < subScriptSize; i++) {
if (subScriptList[i]) {
ui_ISubScript::FreeHandle(subScriptList[i]);
}
}
delete subScriptList;
ui_IDebug::FreeHandle(debug);
// Shutdown Lua
L = NULL;
solState.reset();
}
void ui_main_c::Shutdown()
{
// Shutdown script
ScriptShutdown();
if (renderer) {
ui_IConsole::FreeHandle(conUI);
// Shutdown renderer
renderer->Shutdown();
r_IRenderer::FreeHandle(renderer);
// Shutdown window
sys->video->SetVisible(false);
core->video->Save();
}
// Save config
if (!scriptCfg.empty()) {
core->config->SaveConfig(scriptCfg);
} else {
core->config->SaveConfig("SimpleGraphic/SimpleGraphic.cfg");
}
for (int a = 0; a < scriptArgc; a++) {
FreeString(scriptArgv[a]);
}
delete scriptArgv;
}
bool ui_main_c::CanExit()
{
bool ret = true;
int extraArgs = PushCallback("CanExit");
if (extraArgs >= 0) {
PCall(extraArgs, 1);
ret = !!lua_toboolean(L, -1);
lua_pop(L, 1);
}
return ret;
}
// ==============
// Input Handling
// ==============
void ui_main_c::KeyEvent(int key, int type)
{
if (conUI->KeyEvent(key, type)) {
return;
}
switch (type) {
case KE_CHAR:
CallKeyHandler("OnChar", key, false);
break;
case KE_KEYDOWN:
case KE_DBLCLK:
CallKeyHandler("OnKeyDown", key, type == KE_DBLCLK);
break;
case KE_KEYUP:
switch (key) {
case KEY_F10:
renderer->ToggleDebugImGui();
break;
case KEY_PAUSE:
if (sys->IsKeyDown(KEY_SHIFT)) {
debug->ToggleProfiling();
break;
}
default:
CallKeyHandler("OnKeyUp", key, false);
break;
}
break;
}
}
void ui_main_c::CallKeyHandler(const char* hname, int key, bool dblclk)
{
if ( !L ) return;
int extraArgs = PushCallback(hname);
if (extraArgs < 0) {
return;
}
if (key < 128) {
lua_pushfstring(L, "%c", key);
} else {
lua_pushstring(L, NameForKey(key));
}
lua_pushboolean(L, dblclk);
PCall(2 + extraArgs, 0);
}
const char* ui_main_c::NameForKey(int key)
{
for (int i = 0; ui_keyNameMap[i].key; i++) {
if (ui_keyNameMap[i].key == key) {
return ui_keyNameMap[i].str;
}
}
return "?";
}
int ui_main_c::KeyForName(const char* keyName)
{
if (keyName[1]) {
// > 1 character in length, do a lookup
for (int i = 0; ui_keyNameMap[i].key; i++) {
if ( !_stricmp(keyName, ui_keyNameMap[i].str) ) {
return ui_keyNameMap[i].key;
}
}
} else {
if (isalpha(*keyName)) {
return tolower(*keyName);
} else if (*keyName == ' ' || isdigit(*keyName)) {
return *keyName;
}
}
return 0;
}