-
Notifications
You must be signed in to change notification settings - Fork 296
Expand file tree
/
Copy pathlua-engine.cpp
More file actions
6997 lines (6082 loc) · 188 KB
/
lua-engine.cpp
File metadata and controls
6997 lines (6082 loc) · 188 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
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#if defined(__linux__) || defined(__unix__)
#include <stdlib.h>
#include <unistd.h>
#define SetCurrentDir chdir
#include <sys/types.h>
#include <sys/wait.h>
#include <libgen.h>
#elif __APPLE__
#include <stdlib.h>
#include <unistd.h>
#include <libgen.h>
#include <mach-o/dyld.h>
#define SetCurrentDir chdir
#endif
#ifdef WIN32
#include <Windows.h>
#include <direct.h>
#define SetCurrentDir _chdir
#endif
#include "types.h"
#include "fceu.h"
#include "file.h"
#include "video.h"
#include "debug.h"
#include "debugsymboltable.h"
#include "sound.h"
#include "state.h"
#include "movie.h"
#include "driver.h"
#include "cheat.h"
#include "x6502.h"
#include "ppu.h"
#include "utils/xstring.h"
#include "utils/memory.h"
#include "utils/crc32.h"
#include "fceulua.h"
extern char FileBase[];
#ifdef __WIN_DRIVER__
#include "drivers/win/common.h"
#include "drivers/win/main.h"
#include "drivers/win/taseditor/selection.h"
#include "drivers/win/taseditor/laglog.h"
#include "drivers/win/taseditor/markers.h"
#include "drivers/win/taseditor/snapshot.h"
#include "drivers/win/taseditor/taseditor_lua.h"
#include "drivers/win/cdlogger.h"
extern TASEDITOR_LUA taseditor_lua;
#endif
#ifdef __SDL__
#ifdef __QT_DRIVER__
#include "drivers/Qt/sdl.h"
#include "drivers/Qt/main.h"
#include "drivers/Qt/input.h"
#include "drivers/Qt/fceuWrapper.h"
#include "drivers/Qt/TasEditor/selection.h"
#include "drivers/Qt/TasEditor/laglog.h"
#include "drivers/Qt/TasEditor/markers.h"
#include "drivers/Qt/TasEditor/snapshot.h"
#include "drivers/Qt/TasEditor/taseditor_lua.h"
extern TASEDITOR_LUA *taseditor_lua;
#else
int LoadGame(const char *path, bool silent = false);
int reloadLastGame(void);
void fceuWrapperRequestAppExit(void);
#endif
#endif
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cassert>
#include <cstdlib>
#include <cmath>
#include <zlib.h>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <bitset>
#include "x6502abbrev.h"
bool CheckLua()
{
#ifdef __WIN_DRIVER__
HMODULE mod = LoadLibrary("lua51.dll");
if(!mod)
{
return false;
}
FreeLibrary(mod);
return true;
#else
return true;
#endif
}
bool DemandLua()
{
#ifdef __WIN_DRIVER__
if(!CheckLua())
{
MessageBox(NULL, "lua51.dll was not found. Please get it into your PATH or in the same directory as fceux.exe", "FCEUX", MB_OK | MB_ICONERROR);
return false;
}
return true;
#else
return true;
#endif
}
static void luaReadMemHook(unsigned int address, unsigned int value, void *userData)
{
CallRegisteredLuaMemHook(address, 1, value, LUAMEMHOOK_READ);
}
static void luaWriteMemHook(unsigned int address, unsigned int value, void *userData)
{
CallRegisteredLuaMemHook(address, 1, value, LUAMEMHOOK_WRITE);
}
static void luaExecMemHook(unsigned int address, unsigned int value, void *userData)
{
CallRegisteredLuaMemHook(address, 1, value, LUAMEMHOOK_EXEC);
}
extern "C"
{
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#ifdef WIN32
#include <lstate.h>
int iuplua_open(lua_State * L);
int iupcontrolslua_open(lua_State * L);
int luaopen_winapi(lua_State * L);
int imlua_open (lua_State *L);
int cdlua_open (lua_State *L);
int cdluaim_open(lua_State *L);
//luasocket
int luaopen_socket_core(lua_State *L);
int luaopen_mime_core(lua_State *L);
#endif
}
#ifndef TRUE
#define TRUE 1
#define FALSE 0
#endif
#ifndef _MSC_VER
#define stricmp strcasecmp
#define strnicmp strncasecmp
#ifdef __GNUC__
#define __forceinline __attribute__ ((always_inline))
#else
#define __forceinline
#endif
#endif
#ifdef __WIN_DRIVER__
extern void AddRecentLuaFile(const char *filename);
#endif
extern bool turbo;
extern int32 fps_scale;
struct LuaSaveState {
std::string filename;
EMUFILE_MEMORY *data;
bool anonymous, persisted;
LuaSaveState()
: data(0)
, anonymous(false)
, persisted(false)
{}
~LuaSaveState() {
if(data) delete data;
}
void persist() {
persisted = true;
FILE* outf = fopen(filename.c_str(),"wb");
fwrite(data->buf(),1,data->size(),outf);
fclose(outf);
}
void ensureLoad() {
if(data) return;
persisted = true;
FILE* inf = fopen(filename.c_str(),"rb");
fseek(inf,0,SEEK_END);
long int len = ftell(inf);
fseek(inf,0,SEEK_SET);
data = new EMUFILE_MEMORY(len);
if ( fread(data->buf(),1,len,inf) != static_cast<size_t>(len) )
{
FCEU_printf("Warning: LuaSaveState::ensureLoad failed to load full buffer.\n");
}
fclose(inf);
}
};
static void(*info_print)(intptr_t uid, const char* str);
static void(*info_onstart)(intptr_t uid);
static void(*info_onstop)(intptr_t uid);
static intptr_t info_uid;
#ifdef __WIN_DRIVER__
extern HWND LuaConsoleHWnd;
extern INT_PTR CALLBACK DlgLuaScriptDialog(HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam);
void TaseditorDisableManualFunctionIfNeeded();
#else
int LuaKillMessageBox(void);
#ifdef __linux__
#ifndef __THROWNL
#define __THROWNL throw () // Build fix Alpine Linux libc
#endif
int LuaPrintfToWindowConsole(const char *__restrict format, ...)
__THROWNL __attribute__ ((__format__ (__printf__, 1, 2)));
#else
#ifdef WIN32
int LuaPrintfToWindowConsole(_In_z_ _Printf_format_string_ const char * format, ...);
#else
int LuaPrintfToWindowConsole(const char *__restrict format, ...) throw();
#endif
#endif
#endif
extern void PrintToWindowConsole(intptr_t hDlgAsInt, const char* str);
extern void WinLuaOnStart(intptr_t hDlgAsInt);
extern void WinLuaOnStop(intptr_t hDlgAsInt);
static lua_State *L;
static int luaexiterrorcount = 8;
static int luaCallbackErrorCounter = 0;
// Are we running any code right now?
static char *luaScriptName = NULL;
// Are we running any code right now?
int luaRunning = FALSE;
// True at the frame boundary, false otherwise.
static int frameBoundary = FALSE;
// The execution speed we're running at.
static enum {SPEED_NORMAL, SPEED_NOTHROTTLE, SPEED_TURBO, SPEED_MAXIMUM} speedmode = SPEED_NORMAL;
// Rerecord count skip mode
static int skipRerecords = FALSE;
// Used by the registry to find our functions
static const char *frameAdvanceThread = "FCEU.FrameAdvance";
static const char *guiCallbackTable = "FCEU.GUI";
// True if there's a thread waiting to run after a run of frame-advance.
static int frameAdvanceWaiting = FALSE;
// We save our pause status in the case of a natural death.
//static int wasPaused = FALSE;
// Transparency strength. 255=opaque, 0=so transparent it's invisible
static int transparencyModifier = 255;
// Our zapper.
static int luazapperx = -1;
static int luazappery = -1;
static int luazapperfire = -1;
// Our joypads.
static uint8 luajoypads1[4]= { 0xFF, 0xFF, 0xFF, 0xFF }; //x1
static uint8 luajoypads2[4]= { 0x00, 0x00, 0x00, 0x00 }; //0x
/* Crazy logic stuff.
11 - true 01 - pass-through (default)
00 - false 10 - invert */
static enum { GUI_USED_SINCE_LAST_DISPLAY, GUI_USED_SINCE_LAST_FRAME, GUI_CLEAR } gui_used = GUI_CLEAR;
static uint8 *gui_data = NULL;
static int gui_saw_current_palette = FALSE;
// Protects Lua calls from going nuts.
// We set this to a big number like 1000 and decrement it
// over time. The script gets knifed once this reaches zero.
static int numTries;
// number of registered memory functions (1 per hooked byte)
static unsigned int numMemHooks;
// Look in fceu.h for macros named like JOY_UP to determine the order.
static const char *button_mappings[] = {
"A", "B", "select", "start", "up", "down", "left", "right"
};
#ifdef _MSC_VER
#define snprintf _snprintf
#define vscprintf _vscprintf
#else
#define stricmp strcasecmp
#define strnicmp strncasecmp
#endif
static const char* luaCallIDStrings [] =
{
"CALL_BEFOREEMULATION",
"CALL_AFTEREMULATION",
"CALL_BEFOREEXIT",
"CALL_BEFORESAVE",
"CALL_AFTERLOAD",
"CALL_TASEDITOR_AUTO",
"CALL_TASEDITOR_MANUAL",
};
//make sure we have the right number of strings
CTASSERT(sizeof(luaCallIDStrings)/sizeof(*luaCallIDStrings) == LUACALL_COUNT)
static const char* luaMemHookTypeStrings [] =
{
"MEMHOOK_WRITE",
"MEMHOOK_READ",
"MEMHOOK_EXEC",
};
//make sure we have the right number of strings
CTASSERT(sizeof(luaMemHookTypeStrings)/sizeof(*luaMemHookTypeStrings) == LUAMEMHOOK_COUNT)
static char* rawToCString(lua_State* L, int idx=0);
static const char* toCString(lua_State* L, int idx=0);
static int exitScheduled = FALSE;
/**
* Resets emulator speed / pause states after script exit.
*/
static void FCEU_LuaOnStop()
{
luaRunning = FALSE;
luazapperx = -1;
luazappery = -1;
luazapperfire = -1;
for (int i = 0 ; i < 4 ; i++ ){
luajoypads1[i]= 0xFF; // Set these back to pass-through
luajoypads2[i]= 0x00;
}
gui_used = GUI_CLEAR;
//if (wasPaused && !FCEUI_EmulationPaused())
// FCEUI_ToggleEmulationPause();
//zero 21-nov-2014 - this variable doesnt exist outside windows so it cant have this feature
#ifdef __WIN_DRIVER__
if (fps_scale != 256) //thanks, we already know it's on normal speed
FCEUD_SetEmulationSpeed(EMUSPEED_NORMAL); //TODO: Ideally lua returns the speed to the speed the user set before running the script
//rather than returning it to normal, and turbo off. Perhaps some flags and a FCEUD_GetEmulationSpeed function
#endif
turbo = false;
//FCEUD_TurboOff();
#ifdef __WIN_DRIVER__
TaseditorDisableManualFunctionIfNeeded();
#endif
}
/**
* Asks Lua if it wants control of the emulator's speed.
* Returns 0 if no, 1 if yes. If yes, caller should also
* consult FCEU_LuaFrameSkip().
*/
int FCEU_LuaSpeed() {
if (!L || !luaRunning)
return 0;
//printf("%d\n", speedmode);
switch (speedmode) {
case SPEED_NOTHROTTLE:
case SPEED_TURBO:
case SPEED_MAXIMUM:
return 1;
case SPEED_NORMAL:
default:
return 0;
}
}
/**
* Asks Lua if it wants control whether this frame is skipped.
* Returns 0 if no, 1 if frame should be skipped, -1 if it should not be.
*/
int FCEU_LuaFrameskip() {
if (!L || !luaRunning)
return 0;
switch (speedmode) {
case SPEED_NORMAL:
return 0;
case SPEED_NOTHROTTLE:
return -1;
case SPEED_TURBO:
return 0;
case SPEED_MAXIMUM:
return 1;
}
return 0;
}
/**
* Toggle certain rendering planes
* emu.setrenderingplanes(sprites, background)
* Accepts two (lua) boolean values and acts accordingly
*/
static int emu_setrenderplanes(lua_State *L) {
bool sprites = (lua_toboolean( L, 1 ) == 1);
bool background = (lua_toboolean( L, 2 ) == 1);
FCEUI_SetRenderPlanes(sprites, background);
return 0;
}
///////////////////////////
// emu.speedmode(string mode)
//
// Takes control of the emulation speed
// of the system. Normal is normal speed (60fps, 50 for PAL),
// nothrottle disables speed control but renders every frame,
// turbo renders only a few frames in order to speed up emulation,
// maximum renders no frames
// TODO: better enforcement, done in the same way as basicbot...
static int emu_speedmode(lua_State *L) {
const char *mode = luaL_checkstring(L,1);
if (strcasecmp(mode, "normal")==0) {
speedmode = SPEED_NORMAL;
} else if (strcasecmp(mode, "nothrottle")==0) {
speedmode = SPEED_NOTHROTTLE;
} else if (strcasecmp(mode, "turbo")==0) {
speedmode = SPEED_TURBO;
} else if (strcasecmp(mode, "maximum")==0) {
speedmode = SPEED_MAXIMUM;
} else
luaL_error(L, "Invalid mode %s to emu.speedmode",mode);
//printf("new speed mode: %d\n", speedmode);
if (speedmode == SPEED_NORMAL)
{
FCEUD_SetEmulationSpeed(EMUSPEED_NORMAL);
FCEUD_TurboOff();
}
else if (speedmode == SPEED_TURBO) //adelikat: Making turbo actually use turbo.
FCEUD_TurboOn(); //Turbo and max speed are two different results. Turbo employs frame skipping and sound bypassing if mute turbo option is enabled.
//This makes it faster but with frame skipping. Therefore, maximum is still a useful feature, in case the user is recording an avi or making screenshots (or something else that needs all frames)
else
FCEUD_SetEmulationSpeed(EMUSPEED_FASTEST); //TODO: Make nothrottle turn off throttle, or remove the option
return 0;
}
// emu.poweron()
//
// Executes a power cycle
static int emu_poweron(lua_State *L) {
if (GameInfo)
FCEUI_PowerNES();
return 0;
}
static int emu_debuggerloop(lua_State *L) {
#ifdef __WIN_DRIVER__
extern void win_debuggerLoop();
win_debuggerLoop();
#endif
return 0;
}
static int emu_debuggerloopstep(lua_State *L) {
#ifdef __WIN_DRIVER__
extern void win_debuggerLoopStep();
win_debuggerLoopStep();
#endif
return 0;
}
// emu.softreset()
//
// Executes a power cycle
static int emu_softreset(lua_State *L) {
if (GameInfo)
FCEUI_ResetNES();
return 0;
}
// emu.frameadvance()
//
// Executes a frame advance. Occurs by yielding the coroutine, then re-running
// when we break out.
static int emu_frameadvance(lua_State *L) {
// We're going to sleep for a frame-advance. Take notes.
if (frameAdvanceWaiting)
return luaL_error(L, "can't call emu.frameadvance() from here");
frameAdvanceWaiting = TRUE;
// Now we can yield to the main
return lua_yield(L, 0);
// It's actually rather disappointing...
}
// bool emu.paused()
static int emu_paused(lua_State *L)
{
lua_pushboolean(L, FCEUI_EmulationPaused() != 0);
return 1;
}
// emu.pause()
//
// Pauses the emulator. Returns immediately.
static int emu_pause(lua_State *L)
{
if (!FCEUI_EmulationPaused())
FCEUI_ToggleEmulationPause();
return 0;
}
//emu.unpause()
//
// Unpauses the emulator. Returns immediately.
static int emu_unpause(lua_State *L)
{
if (FCEUI_EmulationPaused())
FCEUI_ToggleEmulationPause();
return 0;
}
// emu.message(string msg)
//
// Displays the given message on the screen.
static int emu_message(lua_State *L) {
const char *msg = luaL_checkstring(L,1);
FCEU_DispMessage("%s",0, msg);
return 0;
}
// emu.getdir()
//
// Returns the path of fceux.exe as a string.
static int emu_getdir(lua_State *L) {
#ifdef WIN32
char fullPath[2048];
char driveLetter[3];
char directory[2048];
char finalPath[2048];
GetModuleFileNameA(NULL, fullPath, 2048);
_splitpath(fullPath, driveLetter, directory, NULL, NULL);
snprintf(finalPath, sizeof(finalPath), "%s%s", driveLetter, directory);
lua_pushstring(L, finalPath);
return 1;
#elif __linux__
char exePath[ 2048 ];
ssize_t count = ::readlink( "/proc/self/exe", exePath, sizeof(exePath)-1 );
if ( count > 0 )
{
char *dir;
exePath[count] = 0;
//printf("EXE Path: '%s' \n", exePath );
dir = ::dirname( exePath );
if ( dir )
{
//printf("DIR Path: '%s' \n", dir );
lua_pushstring(L, dir);
return 1;
}
}
#elif __APPLE__
char exePath[ 2048 ];
uint32_t bufSize = sizeof(exePath);
int result = _NSGetExecutablePath( exePath, &bufSize );
if ( result == 0 )
{
char *dir;
exePath[ sizeof(exePath)-1 ] = 0;
//printf("EXE Path: '%s' \n", exePath );
dir = ::dirname( exePath );
if ( dir )
{
//printf("DIR Path: '%s' \n", dir );
lua_pushstring(L, dir);
return 1;
}
}
#endif
return 0;
}
extern void ReloadRom(void);
//#ifdef __QT_DRIVER__
//static int emu_wait_for_rom_load(lua_State *L)
//{
// fceuWrapperUnLock();
// printf("Waiting for ROM\n");
// #ifdef WIN32
// msleep(1000);
// #else
// usleep(1000000);
// #endif
// fceuWrapperLock();
//
// return 0;
//}
//#endif
// emu.loadrom(string filename)
//
// Loads the rom from the directory relative to the lua script or from the absolute path.
// If the rom can't be loaded, loads the most recent one.
static int emu_loadrom(lua_State *L)
{
#ifdef __WIN_DRIVER__
const char* str = lua_tostring(L,1);
//special case: reload rom
if (!str) {
ReloadRom();
return 0;
}
const char *nameo2 = luaL_checkstring(L,1);
char nameo[2048];
strncpy(nameo, nameo2, sizeof(nameo));
if (!ALoad(nameo)) {
extern void LoadRecentRom(int slot);
LoadRecentRom(0);
}
#elif defined(__QT_DRIVER__)
const char *nameo2 = luaL_checkstring(L,1);
std::string nameo;
nameo.assign( nameo2 );
LoadGameFromLua( nameo.c_str() );
//lua_cpcall(L, emu_wait_for_rom_load, NULL);
//printf("Attempting to Load ROM: '%s'\n", nameo );
//if (!LoadGame(nameo, true))
//{
// //printf("Failed to Load ROM: '%s'\n", nameo );
// reloadLastGame();
//}
#endif
#if defined(__WIN_DRIVER__) || defined(__QT_DRIVER__)
if ( GameInfo )
{
//printf("Currently Loaded ROM: '%s'\n", GameInfo->filename );
lua_pushstring(L, GameInfo->filename);
return 1;
}
#endif
return 0;
}
// emu.exit()
//
// Closes the fceux
static int emu_exit(lua_State *L) {
exitScheduled = TRUE;
return 0;
}
static int emu_registerbefore(lua_State *L) {
if (!lua_isnil(L,1))
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_settop(L,1);
lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFOREEMULATION]);
lua_insert(L,1);
lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFOREEMULATION]);
//StopScriptIfFinished(luaStateToUIDMap[L]);
return 1;
}
static int emu_registerafter(lua_State *L) {
if (!lua_isnil(L,1))
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_settop(L,1);
lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_AFTEREMULATION]);
lua_insert(L,1);
lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_AFTEREMULATION]);
//StopScriptIfFinished(luaStateToUIDMap[L]);
return 1;
}
static int emu_registerexit(lua_State *L) {
if (!lua_isnil(L,1))
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_settop(L,1);
lua_getfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFOREEXIT]);
lua_insert(L,1);
lua_setfield(L, LUA_REGISTRYINDEX, luaCallIDStrings[LUACALL_BEFOREEXIT]);
//StopScriptIfFinished(luaStateToUIDMap[L]);
return 1;
}
static int emu_addgamegenie(lua_State *L) {
const char *msg = luaL_checkstring(L,1);
// Add a Game Genie code if it hasn't already been added
int GGaddr, GGcomp, GGval;
int i=0;
uint32 Caddr;
uint8 Cval;
int Ccompare, Ctype;
if (!FCEUI_DecodeGG(msg, &GGaddr, &GGval, &GGcomp)) {
luaL_error(L, "Failed to decode game genie code");
lua_pushboolean(L, false);
return 1;
}
while (FCEUI_GetCheat(i,NULL,&Caddr,&Cval,&Ccompare,NULL,&Ctype)) {
if ((static_cast<uint32>(GGaddr) == Caddr) && (GGval == static_cast<int>(Cval)) && (GGcomp == Ccompare) && (Ctype == 1)) {
// Already Added, so consider it a success
lua_pushboolean(L, true);
return 1;
}
i = i + 1;
}
if (FCEUI_AddCheat(msg,GGaddr,GGval,GGcomp,1)) {
// Code was added
// Can't manage the display update the way I want, so I won't bother with it
// UpdateCheatsAdded();
lua_pushboolean(L, true);
return 1;
} else {
// Code didn't get added
lua_pushboolean(L, false);
return 1;
}
}
static int emu_delgamegenie(lua_State *L) {
const char *msg = luaL_checkstring(L,1);
// Remove a Game Genie code. Very restrictive about deleted code.
int GGaddr, GGcomp, GGval;
uint32 i=0;
std::string Cname;
uint32 Caddr;
uint8 Cval;
int Ccompare, Ctype;
if (!FCEUI_DecodeGG(msg, &GGaddr, &GGval, &GGcomp)) {
luaL_error(L, "Failed to decode game genie code");
lua_pushboolean(L, false);
return 1;
}
while (FCEUI_GetCheat(i,&Cname,&Caddr,&Cval,&Ccompare,NULL,&Ctype)) {
if ((Cname == msg) && (static_cast<uint32>(GGaddr) == Caddr) && (GGval == static_cast<int>(Cval)) && (GGcomp == Ccompare) && (Ctype == 1)) {
// Delete cheat code
if (FCEUI_DelCheat(i)) {
lua_pushboolean(L, true);
return 1;
}
else {
lua_pushboolean(L, false);
return 1;
}
}
i = i + 1;
}
// Cheat didn't exist, so it's not an error
lua_pushboolean(L, true);
return 1;
}
// can't remember what the best way of doing this is...
#if defined(i386) || defined(__i386) || defined(__i386__) || defined(M_I86) || defined(_M_IX86) || defined(WIN32)
#define IS_LITTLE_ENDIAN
#endif
// push a value's bytes onto the output stack
template<typename T>
void PushBinaryItem(T item, std::vector<unsigned char>& output)
{
unsigned char* buf = (unsigned char*)&item;
#ifdef IS_LITTLE_ENDIAN
for(int i = sizeof(T); i; i--)
output.push_back(*buf++);
#else
int vecsize = output.size();
for(int i = sizeof(T); i; i--)
output.insert(output.begin() + vecsize, *buf++);
#endif
}
// read a value from the byte stream and advance the stream by its size
template<typename T>
T AdvanceByteStream(const unsigned char*& data, unsigned int& remaining)
{
#ifdef IS_LITTLE_ENDIAN
T rv = *(T*)data;
data += sizeof(T);
#else
T rv; unsigned char* rvptr = (unsigned char*)&rv;
for(int i = sizeof(T)-1; i>=0; i--)
rvptr[i] = *data++;
#endif
remaining -= sizeof(T);
return rv;
}
// advance the byte stream by a certain size without reading a value
void AdvanceByteStream(const unsigned char*& data, unsigned int& remaining, int amount)
{
data += amount;
remaining -= amount;
}
#define LUAEXT_TLONG 30 // 0x1E // 4-byte signed integer
#define LUAEXT_TUSHORT 31 // 0x1F // 2-byte unsigned integer
#define LUAEXT_TSHORT 32 // 0x20 // 2-byte signed integer
#define LUAEXT_TBYTE 33 // 0x21 // 1-byte unsigned integer
#define LUAEXT_TNILS 34 // 0x22 // multiple nils represented by a 4-byte integer (warning: becomes multiple stack entities)
#define LUAEXT_TTABLE 0x40 // 0x40 through 0x4F // tables of different sizes:
#define LUAEXT_BITS_1A 0x01 // size of array part fits in a 1-byte unsigned integer
#define LUAEXT_BITS_2A 0x02 // size of array part fits in a 2-byte unsigned integer
#define LUAEXT_BITS_4A 0x03 // size of array part fits in a 4-byte unsigned integer
#define LUAEXT_BITS_1H 0x04 // size of hash part fits in a 1-byte unsigned integer
#define LUAEXT_BITS_2H 0x08 // size of hash part fits in a 2-byte unsigned integer
#define LUAEXT_BITS_4H 0x0C // size of hash part fits in a 4-byte unsigned integer
#define BITMATCH(x,y) (((x) & (y)) == (y))
static void PushNils(std::vector<unsigned char>& output, int& nilcount)
{
int count = nilcount;
nilcount = 0;
static const int minNilsWorthEncoding = 6; // because a LUAEXT_TNILS entry is 5 bytes
if(count < minNilsWorthEncoding)
{
for(int i = 0; i < count; i++)
output.push_back(LUA_TNIL);
}
else
{
output.push_back(LUAEXT_TNILS);
PushBinaryItem<uint32>(count, output);
}
}
static std::vector<const void*> s_tableAddressStack; // prevents infinite recursion of a table within a table (when cycle is found, print something like table:parent)
static std::vector<const void*> s_metacallStack; // prevents infinite recursion if something's __tostring returns another table that contains that something (when cycle is found, print the inner result without using __tostring)
static void LuaStackToBinaryConverter(lua_State* L, int i, std::vector<unsigned char>& output)
{
int type = lua_type(L, i);
// the first byte of every serialized item says what Lua type it is
output.push_back(type & 0xFF);
switch(type)
{
default:
{
char errmsg [1024];
snprintf(errmsg, sizeof(errmsg), "values of type \"%s\" are not allowed to be returned from registered save functions.\r\n", luaL_typename(L,i));
if(info_print)
info_print(info_uid, errmsg);
else
puts(errmsg);
}
break;
case LUA_TNIL:
// no information necessary beyond the type
break;
case LUA_TBOOLEAN:
// serialize as 0 or 1
output.push_back(lua_toboolean(L,i));
break;
case LUA_TSTRING:
// serialize as a 0-terminated string of characters
{
const char* str = lua_tostring(L,i);
while(*str)
output.push_back(*str++);
output.push_back('\0');
}
break;
case LUA_TNUMBER:
{
double num = (double)lua_tonumber(L,i);
int32 inum = (int32)lua_tointeger(L,i);
if(num != inum)
{
PushBinaryItem(num, output);
}
else
{
if((inum & ~0xFF) == 0)
type = LUAEXT_TBYTE;
else if((uint16)(inum & 0xFFFF) == inum)
type = LUAEXT_TUSHORT;
else if((int16)(inum & 0xFFFF) == inum)
type = LUAEXT_TSHORT;
else
type = LUAEXT_TLONG;
output.back() = type;
switch(type)
{
case LUAEXT_TLONG:
PushBinaryItem<int32>(static_cast<int32>(inum), output);
break;
case LUAEXT_TUSHORT:
PushBinaryItem<uint16>(static_cast<uint16>(inum), output);
break;
case LUAEXT_TSHORT:
PushBinaryItem<int16>(static_cast<int16>(inum), output);
break;
case LUAEXT_TBYTE:
output.push_back(static_cast<uint8>(inum));
break;
}
}
}
break;
case LUA_TTABLE:
// serialize as a type that describes how many bytes are used for storing the counts,
// followed by the number of array entries if any, then the number of hash entries if any,
// then a Lua value per array entry, then a (key,value) pair of Lua values per hashed entry
// note that the structure of table references are not faithfully serialized (yet)
{
int outputTypeIndex = output.size() - 1;
int arraySize = 0;
int hashSize = 0;
if(lua_checkstack(L, 4) && std::find(s_tableAddressStack.begin(), s_tableAddressStack.end(), lua_topointer(L,i)) == s_tableAddressStack.end())
{
s_tableAddressStack.push_back(lua_topointer(L,i));
struct Scope { ~Scope(){ s_tableAddressStack.pop_back(); } } scope;
bool wasnil = false;
int nilcount = 0;
arraySize = lua_objlen(L, i);
int arrayValIndex = lua_gettop(L) + 1;
for(int j = 1; j <= arraySize; j++)
{
lua_rawgeti(L, i, j);
bool isnil = lua_isnil(L, arrayValIndex);
if(isnil)
nilcount++;
else
{
if(wasnil)
PushNils(output, nilcount);
LuaStackToBinaryConverter(L, arrayValIndex, output);
}
lua_pop(L, 1);