-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathPsyX_main.cpp
More file actions
1036 lines (835 loc) · 22.6 KB
/
Copy pathPsyX_main.cpp
File metadata and controls
1036 lines (835 loc) · 22.6 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
#include "PsyX_main.h"
#include "PsyX/PsyX_version.h"
#include "PsyX/PsyX_globals.h"
#include "PsyX/PsyX_public.h"
#include "PsyX/util/timer.h"
#include "gpu/PsyX_GPU.h"
#include "pad/PsyX_pad.h"
#include "platform.h"
#include "util/crash_handler.h"
#include "psx/libetc.h"
#include "psx/libgte.h"
#include "psx/libgpu.h"
#include "psx/libspu.h"
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <SDL.h>
#include "PsyX/PsyX_render.h"
#ifdef _WIN32
#include <windows.h>
#include <pla.h>
#endif // _WIN32
#ifdef __EMSCRIPTEN__
int strcasecmp(const char* _l, const char* _r)
{
const u_char* l = (u_char*)_l, * r = (u_char*)_r;
for (; *l && *r && (*l == *r || tolower(*l) == tolower(*r)); l++, r++);
return tolower(*l) - tolower(*r);
}
#elif !defined(_WIN32)
#include <strings.h>
#endif
SDL_Window* g_window = NULL;
int g_swapInterval = 1;
int g_enableSwapInterval = 1;
int g_skipSwapInterval = 0;
timerCtx_t g_vblTimer;
int g_cfg_swapInterval = 0;
PsyXKeyboardMapping g_cfg_keyboardMapping;
PsyXControllerMapping g_cfg_controllerMapping;
GameOnTextInputHandler g_cfg_gameOnTextInput = NULL;
GameDebugKeysHandlerFunc g_dbg_gameDebugKeys = NULL;
GameDebugMouseHandlerFunc g_dbg_gameDebugMouse = NULL;
int g_dbg_polygonSelected = 0;
enum EPsxCounters
{
PsxCounter_VBLANK,
PsxCounter_Num
};
volatile int g_psxSysCounters[PsxCounter_Num];
SDL_Thread* g_intrThread = NULL;
SDL_mutex* g_intrMutex = NULL;
volatile char g_stopIntrThread = 0;
#if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus)
extern "C" {
#endif
extern void(*vsync_callback)(void);
#if defined(_LANGUAGE_C_PLUS_PLUS)||defined(__cplusplus)||defined(c_plusplus)
}
#endif
extern int PsyX_Pad_InitSystem();
extern void PsyX_Pad_Event_ControllerRemoved(Sint32 deviceId);
extern void PsyX_Pad_Event_ControllerAdded(Sint32 deviceId);
extern int GR_InitialisePSX();
extern int GR_InitialiseRender(char* windowName, int width, int height, int fullscreen);
extern void GR_ResetDevice();
extern void GR_Shutdown();
extern void GR_BeginScene();
extern void GR_EndScene();
extern void GR_UpdateSwapIntervalState(int swapInterval);
int g_vmode = -1;
int g_frameSkip = 0;
#ifdef __EMSCRIPTEN__
int g_emIntrInterval = -1;
int g_intrVMode = MODE_NTSC;
double g_emOldDate = 0;
void emIntrCallback(void* userData)
{
double timestep = g_vmode == MODE_NTSC ? FIXED_TIME_STEP_NTSC : FIXED_TIME_STEP_PAL;
int newVBlank = (Util_GetHPCTime(&g_vblTimer, 0) / timestep) + g_frameSkip;
int diff = newVBlank - g_psxSysCounters[PsxCounter_VBLANK];
while (diff--)
{
if (vsync_callback)
vsync_callback();
g_psxSysCounters[PsxCounter_VBLANK]++;
}
}
EM_BOOL emIntrCallback2(double time, void* userData)
{
emIntrCallback(userData);
return g_stopIntrThread ? EM_FALSE : EM_TRUE;
}
#endif
int PsyX_Sys_SetVMode(int mode)
{
int old = g_vmode;
g_vmode = mode;
#ifdef __EMSCRIPTEN__
if (old != g_vmode)
{
//if(g_emIntrInterval != -1)
// emscripten_clear_interval(g_emIntrInterval);
g_stopIntrThread = 1;
emscripten_sleep(100);
g_stopIntrThread = 0;
emscripten_set_timeout_loop(emIntrCallback2, 1.0, NULL);
}
#endif
return old;
}
int PsyX_Sys_GetVBlankCount()
{
if (g_skipSwapInterval)
{
// extra speedup.
// does not affect `vsync_callback` count
g_psxSysCounters[PsxCounter_VBLANK] += 1;
g_frameSkip++;
}
return g_psxSysCounters[PsxCounter_VBLANK];
}
int intrThreadMain(void* data)
{
Util_InitHPCTimer(&g_vblTimer);
while (!g_stopIntrThread)
{
// step counters
{
const double timestep = g_vmode == MODE_NTSC ? FIXED_TIME_STEP_NTSC : FIXED_TIME_STEP_PAL;
const double vblDelta = Util_GetHPCTime(&g_vblTimer, 0);
if (vblDelta > timestep)
{
SDL_LockMutex(g_intrMutex);
if (vsync_callback)
vsync_callback();
SDL_UnlockMutex(g_intrMutex);
// do vblank events
g_psxSysCounters[PsxCounter_VBLANK]++;
Util_GetHPCTime(&g_vblTimer, 1);
}
}
}
return 0;
}
static int PsyX_Sys_InitialiseCore()
{
#ifdef __EMSCRIPTEN__
Util_InitHPCTimer(&g_vblTimer);
#else
g_intrThread = SDL_CreateThread(intrThreadMain, "psyX_intr", NULL);
if (NULL == g_intrThread)
{
eprinterr("SDL_CreateThread failed: %s\n", SDL_GetError());
return 0;
}
g_intrMutex = SDL_CreateMutex();
if (NULL == g_intrMutex)
{
eprinterr("SDL_CreateMutex failed: %s\n", SDL_GetError());
return 0;
}
#endif
return 1;
}
static void PsyX_Sys_InitialiseInput()
{
g_cfg_keyboardMapping.kc_square = SDL_SCANCODE_X;
g_cfg_keyboardMapping.kc_circle = SDL_SCANCODE_V;
g_cfg_keyboardMapping.kc_triangle = SDL_SCANCODE_Z;
g_cfg_keyboardMapping.kc_cross = SDL_SCANCODE_C;
g_cfg_keyboardMapping.kc_l1 = SDL_SCANCODE_LSHIFT;
g_cfg_keyboardMapping.kc_l2 = SDL_SCANCODE_LCTRL;
g_cfg_keyboardMapping.kc_l3 = SDL_SCANCODE_LEFTBRACKET;
g_cfg_keyboardMapping.kc_r1 = SDL_SCANCODE_RSHIFT;
g_cfg_keyboardMapping.kc_r2 = SDL_SCANCODE_RCTRL;
g_cfg_keyboardMapping.kc_r3 = SDL_SCANCODE_RIGHTBRACKET;
g_cfg_keyboardMapping.kc_dpad_up = SDL_SCANCODE_UP;
g_cfg_keyboardMapping.kc_dpad_down = SDL_SCANCODE_DOWN;
g_cfg_keyboardMapping.kc_dpad_left = SDL_SCANCODE_LEFT;
g_cfg_keyboardMapping.kc_dpad_right = SDL_SCANCODE_RIGHT;
g_cfg_keyboardMapping.kc_select = SDL_SCANCODE_SPACE;
g_cfg_keyboardMapping.kc_start = SDL_SCANCODE_RETURN;
//----------------
g_cfg_controllerMapping.gc_square = SDL_CONTROLLER_BUTTON_X;
g_cfg_controllerMapping.gc_circle = SDL_CONTROLLER_BUTTON_B;
g_cfg_controllerMapping.gc_triangle = SDL_CONTROLLER_BUTTON_Y;
g_cfg_controllerMapping.gc_cross = SDL_CONTROLLER_BUTTON_A;
g_cfg_controllerMapping.gc_l1 = SDL_CONTROLLER_BUTTON_LEFTSHOULDER;
g_cfg_controllerMapping.gc_l2 = SDL_CONTROLLER_AXIS_TRIGGERLEFT | CONTROLLER_MAP_FLAG_AXIS;
g_cfg_controllerMapping.gc_l3 = SDL_CONTROLLER_BUTTON_LEFTSTICK;
g_cfg_controllerMapping.gc_r1 = SDL_CONTROLLER_BUTTON_RIGHTSHOULDER;
g_cfg_controllerMapping.gc_r2 = SDL_CONTROLLER_AXIS_TRIGGERRIGHT | CONTROLLER_MAP_FLAG_AXIS;
g_cfg_controllerMapping.gc_r3 = SDL_CONTROLLER_BUTTON_RIGHTSTICK;
g_cfg_controllerMapping.gc_dpad_up = SDL_CONTROLLER_BUTTON_DPAD_UP;
g_cfg_controllerMapping.gc_dpad_down = SDL_CONTROLLER_BUTTON_DPAD_DOWN;
g_cfg_controllerMapping.gc_dpad_left = SDL_CONTROLLER_BUTTON_DPAD_LEFT;
g_cfg_controllerMapping.gc_dpad_right = SDL_CONTROLLER_BUTTON_DPAD_RIGHT;
g_cfg_controllerMapping.gc_select = SDL_CONTROLLER_BUTTON_BACK;
g_cfg_controllerMapping.gc_start = SDL_CONTROLLER_BUTTON_START;
g_cfg_controllerMapping.gc_axis_left_x = SDL_CONTROLLER_AXIS_LEFTX | CONTROLLER_MAP_FLAG_AXIS;
g_cfg_controllerMapping.gc_axis_left_y = SDL_CONTROLLER_AXIS_LEFTY | CONTROLLER_MAP_FLAG_AXIS;
g_cfg_controllerMapping.gc_axis_right_x = SDL_CONTROLLER_AXIS_RIGHTX | CONTROLLER_MAP_FLAG_AXIS;
g_cfg_controllerMapping.gc_axis_right_y = SDL_CONTROLLER_AXIS_RIGHTY | CONTROLLER_MAP_FLAG_AXIS;
PsyX_Pad_InitSystem();
}
#ifdef __GNUC__
// should be strcasecmp, but this one never existed in C's std, and all the usage-cases don't seem to fail on Linux/Mingw.
#define _stricmp(s1, s2) strcmp(s1, s2)
#endif
// Keyboard mapping lookup
int PsyX_LookupKeyboardMapping(const char* str, int default_value)
{
const char* scancodeName;
int i;
if (str)
{
if (!_stricmp("NONE", str))
return SDL_SCANCODE_UNKNOWN;
for (i = 0; i < SDL_NUM_SCANCODES; i++)
{
scancodeName = SDL_GetScancodeName((SDL_Scancode)i);
if (strlen(scancodeName) && !_stricmp(scancodeName, str))
{
return i;
}
}
}
return default_value;
}
// Game controller mapping lookup
// Available controller binds(refer to SDL2 game controller)
//
// Axes:
// leftx lefty
// rightx righty
// lefttrigger righttrigger
//
// NOTE: adding `-` before axis names makes it inverse, so `-leftx` inverse left stick X axis
//
// Buttons:
// a, b, x, y
// back guide start
// leftstick rightstick
// leftshoulder rightshoulder
// dpup dpdown dpleft dpright
int PsyX_LookupGameControllerMapping(const char* str, int default_value)
{
const char* axisStr;
const char* buttonOrAxisName;
int i, axisFlags;
if (str)
{
axisFlags = CONTROLLER_MAP_FLAG_AXIS;
axisStr = str;
if (*axisStr == '-')
{
axisFlags |= CONTROLLER_MAP_FLAG_INVERSE;
axisStr++;
}
if (!_stricmp("NONE", str))
return SDL_CONTROLLER_BUTTON_INVALID;
// check buttons
for (i = 0; i < SDL_CONTROLLER_BUTTON_MAX; i++)
{
buttonOrAxisName = SDL_GameControllerGetStringForButton((SDL_GameControllerButton)i);
if (strlen(buttonOrAxisName) && !_stricmp(buttonOrAxisName, str))
{
return i;
}
}
// Check axes
for (i = 0; i < SDL_CONTROLLER_AXIS_MAX; i++)
{
buttonOrAxisName = SDL_GameControllerGetStringForAxis((SDL_GameControllerAxis)i);
if (strlen(buttonOrAxisName) && !_stricmp(buttonOrAxisName, axisStr))
{
return i | axisFlags;
}
}
}
return default_value;
}
char* g_appNameStr = NULL;
void PsyX_GetWindowName(char* buffer)
{
#ifdef _DEBUG
sprintf(buffer, "%s | Debug", g_appNameStr);
#else
sprintf(buffer, "%s", g_appNameStr);
#endif
}
FILE* g_logStream = NULL;
// intialise logging
void PsyX_Log_Initialise()
{
char appLogFilename[128];
sprintf(appLogFilename, "%s.log", g_appNameStr);
g_logStream = fopen(appLogFilename, "wb");
if (!g_logStream)
eprinterr("Error - cannot create log file '%s'\n", appLogFilename);
}
void PsyX_Log_Finalise()
{
PsyX_Log_Warning("---- LOG CLOSED ----\n");
if (g_logStream)
fclose(g_logStream);
g_logStream = NULL;
}
void PsyX_Log_Flush()
{
if (g_logStream)
fflush(g_logStream);
}
// spew types
typedef enum
{
SPEW_NORM,
SPEW_INFO,
SPEW_WARNING,
SPEW_ERROR,
SPEW_SUCCESS,
}SpewType_t;
#ifdef _WIN32
static unsigned short g_InitialColor = 0xFFFF;
static unsigned short g_LastColor = 0xFFFF;
static unsigned short g_BadColor = 0xFFFF;
static WORD g_BackgroundFlags = 0xFFFF;
CRITICAL_SECTION g_SpewCS;
char g_bSpewCSInitted = 0;
static void Spew_GetInitialColors()
{
// Get the old background attributes.
CONSOLE_SCREEN_BUFFER_INFO oldInfo;
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &oldInfo);
g_InitialColor = g_LastColor = oldInfo.wAttributes & (FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
g_BackgroundFlags = oldInfo.wAttributes & (BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY);
g_BadColor = 0;
if (g_BackgroundFlags & BACKGROUND_RED)
g_BadColor |= FOREGROUND_RED;
if (g_BackgroundFlags & BACKGROUND_GREEN)
g_BadColor |= FOREGROUND_GREEN;
if (g_BackgroundFlags & BACKGROUND_BLUE)
g_BadColor |= FOREGROUND_BLUE;
if (g_BackgroundFlags & BACKGROUND_INTENSITY)
g_BadColor |= FOREGROUND_INTENSITY;
}
static WORD Spew_SetConsoleTextColor(int red, int green, int blue, int intensity)
{
WORD ret = g_LastColor;
g_LastColor = 0;
if (red) g_LastColor |= FOREGROUND_RED;
if (green) g_LastColor |= FOREGROUND_GREEN;
if (blue) g_LastColor |= FOREGROUND_BLUE;
if (intensity) g_LastColor |= FOREGROUND_INTENSITY;
// Just use the initial color if there's a match...
if (g_LastColor == g_BadColor)
g_LastColor = g_InitialColor;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), g_LastColor | g_BackgroundFlags);
return ret;
}
static void Spew_RestoreConsoleTextColor(WORD color)
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color | g_BackgroundFlags);
g_LastColor = color;
}
void Spew_ConDebugSpew(SpewType_t type, char* text)
{
// Hopefully two threads won't call this simultaneously right at the start!
if (!g_bSpewCSInitted)
{
Spew_GetInitialColors();
InitializeCriticalSection(&g_SpewCS);
g_bSpewCSInitted = 1;
}
WORD old;
EnterCriticalSection(&g_SpewCS);
{
if (type == SPEW_NORM)
{
old = Spew_SetConsoleTextColor(1, 1, 1, 0);
}
else if (type == SPEW_WARNING)
{
old = Spew_SetConsoleTextColor(1, 1, 0, 1);
}
else if (type == SPEW_SUCCESS)
{
old = Spew_SetConsoleTextColor(0, 1, 0, 1);
}
else if (type == SPEW_ERROR)
{
old = Spew_SetConsoleTextColor(1, 0, 0, 1);
}
else if (type == SPEW_INFO)
{
old = Spew_SetConsoleTextColor(0, 1, 1, 1);
}
else
{
old = Spew_SetConsoleTextColor(1, 1, 1, 1);
}
OutputDebugStringA(text);
printf("%s", text);
Spew_RestoreConsoleTextColor(old);
}
LeaveCriticalSection(&g_SpewCS);
}
#endif
void PrintMessageToOutput(SpewType_t spewtype, char const* pMsgFormat, va_list args)
{
static char pTempBuffer[4096];
int len = 0;
vsprintf(&pTempBuffer[len], pMsgFormat, args);
#ifdef WIN32
Spew_ConDebugSpew(spewtype, pTempBuffer);
#elif defined(__EMSCRIPTEN__)
if (spewtype == SPEW_INFO)
{
EM_ASM({
console.info(UTF8ToString($0));
}, pTempBuffer);
}
else if (spewtype == SPEW_WARNING)
{
EM_ASM({
console.warn(UTF8ToString($0));
}, pTempBuffer);
}
else if (spewtype == SPEW_ERROR)
{
EM_ASM({
console.error(UTF8ToString($0));
}, pTempBuffer);
}
else
{
EM_ASM({
console.log(UTF8ToString($0));
}, pTempBuffer);
}
#else
printf(pTempBuffer);
#endif
if(g_logStream)
fprintf(g_logStream, pTempBuffer);
}
void PsyX_Log(const char* fmt, ...)
{
va_list argptr;
va_start(argptr, fmt);
PrintMessageToOutput(SPEW_NORM, fmt, argptr);
va_end(argptr);
}
void PsyX_Log_Info(const char* fmt, ...)
{
va_list argptr;
va_start(argptr, fmt);
PrintMessageToOutput(SPEW_INFO, fmt, argptr);
va_end(argptr);
}
void PsyX_Log_Warning(const char* fmt, ...)
{
va_list argptr;
va_start(argptr, fmt);
PrintMessageToOutput(SPEW_WARNING, fmt, argptr);
va_end(argptr);
}
void PsyX_Log_Error(const char* fmt, ...)
{
va_list argptr;
va_start(argptr, fmt);
PrintMessageToOutput(SPEW_ERROR, fmt, argptr);
va_end(argptr);
}
void PsyX_Log_Success(const char* fmt, ...)
{
va_list argptr;
va_start(argptr, fmt);
PrintMessageToOutput(SPEW_SUCCESS, fmt, argptr);
va_end(argptr);
}
void PsyX_Initialise(char* appName, int width, int height, int fullscreen)
{
char windowNameStr[128];
g_appNameStr = appName;
InstallExceptionHandler();
PsyX_Log_Initialise();
PsyX_GetWindowName(windowNameStr);
#if defined(_WIN32) && defined(_DEBUG)
if (AllocConsole())
{
freopen("CONOUT$", "w", stdout);
SetConsoleTitleA(windowNameStr);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED);
}
#endif
eprintinfo("Initialising Psy-X %d.%d\n", PSYX_MAJOR_VERSION, PSYX_MINOR_VERSION);
eprintinfo("Build date: %s:%s\n", PSYX_COMPILE_DATE, PSYX_COMPILE_TIME);
#if defined(__EMSCRIPTEN__)
SDL_SetHint(SDL_HINT_EMSCRIPTEN_ASYNCIFY, "0");
#endif
if (SDL_Init(SDL_INIT_VIDEO) != 0)
{
eprinterr("Failed to initialise SDL\n");
PsyX_Shutdown();
return;
}
if (!GR_InitialiseRender(windowNameStr, width, height, fullscreen))
{
eprinterr("Failed to Intialise Window\n");
PsyX_Shutdown();
return;
}
if (!PsyX_Sys_InitialiseCore())
{
eprinterr("Failed to Intialise Psy-X Core.\n");
PsyX_Shutdown();
return;
}
if (!GR_InitialisePSX())
{
eprinterr("Failed to Intialise PSX.\n");
PsyX_Shutdown();
return;
}
PsyX_Sys_InitialiseInput();
// set shutdown function (PSX apps usualy don't exit)
atexit(PsyX_Shutdown);
// disable cursor visibility
SDL_ShowCursor(0);
}
void PsyX_GetScreenSize(int* screenWidth, int* screenHeight)
{
SDL_GetWindowSize(g_window, screenWidth, screenHeight);
}
void PsyX_SetCursorPosition(int x, int y)
{
SDL_WarpMouseInWindow(g_window, x, y);
}
void PsyX_Sys_DoDebugKeys(int nKey, char down); // forward decl
void PsyX_Sys_DoDebugMouseMotion(int x, int y);
void PsyX_Exit();
int g_activeKeyboardControllers = 0x1;
int g_altKeyState = 0;
void PsyX_Sys_DoPollEvent()
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_CONTROLLERDEVICEADDED:
PsyX_Pad_Event_ControllerAdded(event.cdevice.which);
break;
case SDL_CONTROLLERDEVICEREMOVED:
PsyX_Pad_Event_ControllerRemoved(event.cdevice.which);
break;
case SDL_QUIT:
PsyX_Exit();
break;
case SDL_WINDOWEVENT:
switch (event.window.event)
{
case SDL_WINDOWEVENT_RESIZED:
g_windowWidth = event.window.data1;
g_windowHeight = event.window.data2;
GR_ResetDevice();
break;
case SDL_WINDOWEVENT_CLOSE:
PsyX_Exit();
break;
}
break;
case SDL_MOUSEMOTION:
PsyX_Sys_DoDebugMouseMotion(event.motion.x, event.motion.y);
break;
case SDL_KEYDOWN:
case SDL_KEYUP:
{
int nKey = event.key.keysym.scancode;
if (nKey == SDL_SCANCODE_RALT)
{
g_altKeyState = (event.type == SDL_KEYDOWN);
}
else if (nKey == SDL_SCANCODE_RETURN)
{
if (g_altKeyState && event.type == SDL_KEYDOWN)
{
int fullscreen = SDL_GetWindowFlags(g_window) & SDL_WINDOW_FULLSCREEN > 0;
SDL_SetWindowFullscreen(g_window, fullscreen ? 0 : SDL_WINDOW_FULLSCREEN_DESKTOP);
SDL_GetWindowSize(g_window, &g_windowWidth, &g_windowHeight);
GR_ResetDevice();
}
break;
}
// lshift/right shift
if (nKey == SDL_SCANCODE_RSHIFT)
nKey = SDL_SCANCODE_LSHIFT;
else if (nKey == SDL_SCANCODE_RCTRL)
nKey = SDL_SCANCODE_LCTRL;
else if (nKey == SDL_SCANCODE_RALT)
nKey = SDL_SCANCODE_LALT;
if (g_cfg_gameOnTextInput && nKey == SDL_SCANCODE_BACKSPACE && event.type == SDL_KEYDOWN)
{
(g_cfg_gameOnTextInput)(NULL);
}
PsyX_Sys_DoDebugKeys(nKey, (event.type == SDL_KEYUP) ? 0 : 1);
break;
}
case SDL_TEXTINPUT:
{
if(g_cfg_gameOnTextInput)
(g_cfg_gameOnTextInput)(event.text.text);
break;
}
}
}
}
char begin_scene_flag = 0;
char PsyX_BeginScene()
{
PsyX_Sys_DoPollEvent();
if (begin_scene_flag)
return 0;
assert(!begin_scene_flag);
{
int swapInterval = (g_cfg_swapInterval && g_enableSwapInterval && !g_skipSwapInterval) ? g_swapInterval : 0;
// Maximum is (ScreenRefreshRate / 2).
// If our screen refresh rate is lower than our PSX vmode refresh rate,
// we reducing swap interval to maintain the framerate.
// Example:
// target 60fps, 50hz screen = no interval (tearing)
// target 30fps, 50hz screen = 60hz interval (less tearing)
// target 30fps, 60hz screen = 30hz interval (no tearing)
SDL_DisplayMode curMode;
if (SDL_GetWindowDisplayMode(g_window, &curMode) == 0)
{
const int mode_frequency = g_vmode == MODE_NTSC ? VBLANK_FREQUENCY_NTSC : VBLANK_FREQUENCY_PAL;
if (curMode.refresh_rate < mode_frequency)
swapInterval--;
}
if (swapInterval < 0)
swapInterval = 0;
GR_UpdateSwapIntervalState(swapInterval);
}
GR_BeginScene();
if (activeDrawEnv.isbg)
{
const RECT16 clipenv = activeDrawEnv.clip;
const u_char r = activeDrawEnv.r0;
const u_char g = activeDrawEnv.g0;
const u_char b = activeDrawEnv.b0;
// TODO: clear all affected backbuffers
//GR_ClearVRAM(clipenv.x, clipenv.y, clipenv.w, clipenv.h, r, g, b);
GR_Clear(clipenv.x, clipenv.y, clipenv.w, clipenv.h, r, g, b);
}
begin_scene_flag = 1;
PsyX_Log_Flush();
return 1;
}
uint PsyX_CalcFPS();
void PsyX_EndScene()
{
if (!begin_scene_flag)
return;
assert(begin_scene_flag);
begin_scene_flag = 0;
#if USE_PGXP
PGXP_ClearCache();
#endif
GR_EndScene();
GR_StoreFrameBuffer(activeDispEnv.disp.x, activeDispEnv.disp.y, activeDispEnv.disp.w, activeDispEnv.disp.h);
GR_SwapWindow();
}
#if !defined(__EMSCRIPTEN__) && !defined(__ANDROID__)
void PsyX_TakeScreenshot()
{
u_char* pixels = (u_char*)malloc(g_windowWidth * g_windowHeight * 4);
#if defined(RENDERER_OGL)
glReadPixels(0, 0, g_windowWidth, g_windowHeight, GL_BGRA, GL_UNSIGNED_BYTE, pixels);
#elif defined(RENDERER_OGLES)
glReadPixels(0, 0, g_windowWidth, g_windowHeight, GL_RGBA, GL_UNSIGNED_BYTE, pixels); // FIXME: is that correct format?
#endif
SDL_Surface* surface = SDL_CreateRGBSurfaceFrom(pixels, g_windowWidth, g_windowHeight, 8 * 4, g_windowWidth * 4, 0, 0, 0, 0);
SDL_SaveBMP(surface, "SCREENSHOT.BMP");
SDL_FreeSurface(surface);
free(pixels);
}
#endif
void PsyX_Sys_DoDebugMouseMotion(int x, int y)
{
if (g_dbg_gameDebugMouse)
g_dbg_gameDebugMouse(x, y);
}
void PsyX_Sys_DoDebugKeys(int nKey, char down)
{
if (g_dbg_gameDebugKeys)
g_dbg_gameDebugKeys(nKey, down);
#if 1 //def _DEBUG
if (nKey == SDL_SCANCODE_BACKSPACE)
{
if (down)
g_skipSwapInterval = 1;
else
g_skipSwapInterval = 0;
}
#endif
if (!down)
{
switch (nKey)
{
#ifdef _DEBUG
case SDL_SCANCODE_F1:
g_dbg_wireframeMode ^= 1;
eprintwarn("wireframe mode: %d\n", g_dbg_wireframeMode);
break;
case SDL_SCANCODE_F2:
g_dbg_texturelessMode ^= 1;
eprintwarn("textureless mode: %d\n", g_dbg_texturelessMode);
break;
case SDL_SCANCODE_UP:
case SDL_SCANCODE_DOWN:
if (g_dbg_emulatorPaused)
{
g_dbg_polygonSelected += (nKey == SDL_SCANCODE_UP) ? 3 : -3;
}
break;
case SDL_SCANCODE_F10:
eprintwarn("saving VRAM.TGA\n");
GR_SaveVRAM("VRAM.TGA", 0, 0, VRAM_WIDTH, VRAM_HEIGHT, 1);
break;
#endif
#if !defined(__EMSCRIPTEN__) && !defined(__ANDROID__)
case SDL_SCANCODE_F12:
eprintwarn("Saving screenshot...\n");
PsyX_TakeScreenshot();
break;
#endif
case SDL_SCANCODE_F3:
g_cfg_bilinearFiltering ^= 1;
eprintwarn("filtering mode: %d\n", g_cfg_bilinearFiltering);
break;
case SDL_SCANCODE_F4:
g_activeKeyboardControllers++;
g_activeKeyboardControllers = g_activeKeyboardControllers % 4;
if (g_activeKeyboardControllers == 0)
g_activeKeyboardControllers++;
eprintwarn("Active keyboard controller: %d\n", g_activeKeyboardControllers);
break;
case SDL_SCANCODE_F5:
g_cfg_pgxpTextureCorrection ^= 1;
break;
case SDL_SCANCODE_F6:
g_cfg_pgxpZBuffer ^= 1;
break;
}
}
}
void PsyX_UpdateInput()
{
// also poll events here
PsyX_Sys_DoPollEvent();
if(!g_altKeyState)
PsyX_Pad_InternalPadUpdates();
}
uint PsyX_CalcFPS()
{
#define FPS_INTERVAL 1.0
static unsigned int lastTime = 0;
static unsigned int currentFps = 0;
static unsigned int passedFrames = 0;
lastTime = SDL_GetTicks();
passedFrames++;
if (lastTime < SDL_GetTicks() - FPS_INTERVAL * 1000)
{
lastTime = SDL_GetTicks();
currentFps = passedFrames;
passedFrames = 0;
}
return currentFps;
}
void PsyX_SetSwapInterval(int interval)
{
g_swapInterval = interval;
}
void PsyX_EnableSwapInterval(int enable)
{
g_enableSwapInterval = enable;
}
void PsyX_WaitForTimestep(int count)
{
#if 0 // defined(RENDERER_OGL) || defined(RENDERER_OGLES)
glFinish(); // best time to complete GPU drawing
#endif
// wait for vblank
if (!g_skipSwapInterval)
{
static int swapLastVbl = 0;
int vbl;
do
{
#ifdef __EMSCRIPTEN__
emscripten_sleep(0);
#endif
vbl = PsyX_Sys_GetVBlankCount();
}
while (vbl - swapLastVbl < count);
swapLastVbl = PsyX_Sys_GetVBlankCount();