forked from vpinball/vpinball
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
1006 lines (877 loc) · 32.7 KB
/
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
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
// VPinball.cpp : Implementation of WinMain
#include "stdafx.h"
#include "vpversion.h"
#ifdef CRASH_HANDLER
#include "StackTrace.h"
#include "CrashHandler.h"
#include "BlackBox.h"
#endif
#include "resource.h"
#include <initguid.h>
#define SET_CRT_DEBUG_FIELD(a) _CrtSetDbgFlag((a) | _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG))
#include "vpinball_i.c"
#include <locale>
#include <codecvt>
#include "plog/Initializers/RollingFileInitializer.h"
#ifdef CRASH_HANDLER
extern "C" int __cdecl _purecall()
{
ShowError("Pure Virtual Function Call");
CONTEXT Context = {};
#ifdef _WIN64
RtlCaptureContext(&Context);
#else
Context.ContextFlags = CONTEXT_CONTROL;
__asm
{
Label:
mov[Context.Ebp], ebp;
mov[Context.Esp], esp;
mov eax, [Label];
mov[Context.Eip], eax;
}
#endif
char callStack[2048] = {};
rde::StackTrace::GetCallStack(&Context, true, callStack, sizeof(callStack) - 1);
ShowError(callStack);
return 0;
}
#endif
#ifndef DISABLE_FORCE_NVIDIA_OPTIMUS
extern "C" {
__declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
}
#else
extern "C" {
__declspec(dllexport) DWORD NvOptimusEnablement = 0x00000000;
}
#endif
#ifndef DISABLE_FORCE_AMD_HIGHPERF
extern "C" { _declspec(dllexport) DWORD AmdPowerXpressRequestHighPerformance = 0x00000001; }
#endif
#if (WINVER <= 0x0601 /* _WIN32_WINNT_WIN7 */ )
typedef enum ORIENTATION_PREFERENCE {
ORIENTATION_PREFERENCE_NONE = 0x0,
ORIENTATION_PREFERENCE_LANDSCAPE = 0x1,
ORIENTATION_PREFERENCE_PORTRAIT = 0x2,
ORIENTATION_PREFERENCE_LANDSCAPE_FLIPPED = 0x4,
ORIENTATION_PREFERENCE_PORTRAIT_FLIPPED = 0x8
} ORIENTATION_PREFERENCE;
typedef BOOL(WINAPI *pSDARP)(ORIENTATION_PREFERENCE orientation);
static pSDARP SetDisplayAutoRotationPreferences = nullptr;
#endif
#if !defined(DEBUG_XXX) && !defined(_CRTDBG_MAP_ALLOC) //&& (!defined(__STDCPP_DEFAULT_NEW_ALIGNMENT__) || (__STDCPP_DEFAULT_NEW_ALIGNMENT__ < 16))
//!! somewhat custom new/delete still needed, otherwise VPX crashes when exiting the player
// is this due to win32xx's whacky Shared_Ptr implementation?
void *operator new(const size_t size_req)
{
void* const ptr = _aligned_malloc(size_req, 16);
if (!ptr)
throw std::bad_alloc{};
return ptr;
}
void operator delete(void *address)
{
_aligned_free(address);
}
/*void *operator new[](const size_t size_req)
{
void* const ptr = _aligned_malloc(size_req, 16);
if (!ptr)
throw std::bad_alloc{};
return ptr;
}
void operator delete[](void *address)
{
_aligned_free(address);
}*/
#endif
CComModule _Module;
BEGIN_OBJECT_MAP(ObjectMap)
END_OBJECT_MAP()
PCHAR* CommandLineToArgvA(PCHAR CmdLine, int* _argc)
{
PCHAR* argv;
PCHAR _argv;
int len;
ULONG argc;
CHAR a;
size_t i, j;
BOOLEAN in_QM;
BOOLEAN in_TEXT;
BOOLEAN in_SPACE;
len = lstrlen(CmdLine);
i = ((len + 2) / 2) * sizeof(PVOID) + sizeof(PVOID);
argv = (PCHAR*)malloc(i + (len + 2) * sizeof(CHAR));
_argv = (PCHAR)(((PUCHAR)argv) + i);
argc = 0;
argv[argc] = _argv;
in_QM = FALSE;
in_TEXT = FALSE;
in_SPACE = TRUE;
i = 0;
j = 0;
while ((a = CmdLine[i])) {
if (in_QM) {
if (a == '\"') {
in_QM = FALSE;
}
else {
_argv[j] = a;
j++;
}
}
else {
switch (a) {
case '\"':
in_QM = TRUE;
in_TEXT = TRUE;
if (in_SPACE) {
argv[argc] = _argv + j;
argc++;
}
in_SPACE = FALSE;
break;
case ' ':
case '\t':
case '\n':
case '\r':
if (in_TEXT) {
_argv[j] = '\0';
j++;
}
in_TEXT = FALSE;
in_SPACE = TRUE;
break;
default:
in_TEXT = TRUE;
if (in_SPACE) {
argv[argc] = _argv + j;
argc++;
}
_argv[j] = a;
j++;
in_SPACE = FALSE;
break;
}
}
i++;
}
_argv[j] = '\0';
argv[argc] = nullptr;
(*_argc) = argc;
return argv;
}
void SetupLogger(const bool enable);
robin_hood::unordered_map<ItemTypeEnum, EditableInfo> EditableRegistry::m_map;
static const string options[] = { // keep in sync with option_names & option_descs!
"h"s,
"Help"s,
"?"s,
"UnregServer"s,
"RegServer"s,
"DisableTrueFullscreen"s,
"EnableTrueFullscreen"s,
"Minimized"s,
"ExtMinimized"s,
"Primary"s,
"GLES"s,
"LessCPUthreads"s,
"Edit"s,
"Play"s,
"PovEdit"s,
"Pov"s,
"ExtractVBS"s,
"Ini"s,
"TableIni"s,
"TournamentFile"s,
"exit"s // (ab)used by frontend, not handled by us
}; // + c1..c9
static const string option_descs[] =
{
string(),
string(),
string(),
"Unregister VP functions"s,
"Register VP functions"s,
"Force-disable True Fullscreen setting"s,
"Force-enable True Fullscreen setting"s,
"Start VP in the 'invisible' minimized window mode"s,
"Start VP in the 'invisible' minimized window mode, but with enabled Pause Menu"s,
"Force VP to render on the Primary/Pixel(0,0) Monitor"s,
"[value] Overrides the global emission scale (day/night setting, value range: 0.115..0.925)"s,
"Limit the amount of parallel execution"s,
"[filename] Load file into VP"s,
"[filename] Load and play file"s,
"[filename] Load and run file in live editing mode, then export new pov on exit"s,
"[filename] Load, export pov and close"s,
"[filename] Load, export table script and close"s,
"[filename] Use a custom settings file instead of loading it from the default location"s,
"[filename] Use a custom table settings file. This option is only available in conjunction with a command which specifies a table filename like Play, Edit,..."s,
"[table filename] [tournament filename] Load a table and tournament file and convert to .png"s,
string()
};
enum option_names
{
OPTION_H,
OPTION_HELP,
OPTION_QMARK,
OPTION_UNREGSERVER,
OPTION_REGSERVER,
OPTION_DISABLETRUEFULLSCREEN,
OPTION_ENABLETRUEFULLSCREEN,
OPTION_MINIMIZED,
OPTION_EXTMINIMIZED,
OPTION_PRIMARY,
OPTION_GLES,
OPTION_LESSCPUTHREADS,
OPTION_EDIT,
OPTION_PLAY,
OPTION_POVEDIT,
OPTION_POV,
OPTION_EXTRACTVBS,
OPTION_INI,
OPTION_TABLE_INI,
OPTION_TOURNAMENT,
OPTION_FRONTEND_EXIT
};
static bool compare_option(const char *const arg, const option_names option)
{
return ((lstrcmpi(arg, ('-'+options[option]).c_str()) == 0) ||
(lstrcmpi(arg, ('/'+options[option]).c_str()) == 0));
}
class VPApp : public CWinApp
{
private:
bool m_run;
bool m_play;
bool m_extractPov;
bool m_file;
bool m_loadFileResult;
bool m_extractScript;
bool m_tournament;
bool m_bgles;
float m_fgles;
string m_szTableFileName;
string m_szTableIniFileName;
string m_szIniFileName;
string m_szTournamentName;
VPinball m_vpinball;
public:
VPApp(HINSTANCE hInstance)
{
m_vpinball.theInstance = GetInstanceHandle();
SetResourceHandle(m_vpinball.theInstance);
g_pvp = &m_vpinball;
}
virtual ~VPApp()
{
_Module.Term();
CoUninitialize();
g_pvp = nullptr;
#ifdef _CRTDBG_MAP_ALLOC
#ifdef DEBUG_XXX //disable this in perference to DevPartner
_CrtSetDumpClient(MemLeakAlert);
#endif
_CrtDumpMemoryLeaks();
#endif
}
string GetPathFromArg(const string& arg, bool setCurrentPath)
{
string path = arg;
if ((arg[0] == '-') || (arg[0] == '/')) // Remove leading - or /
path = path.substr(1, path.size() - 1);
if (path[0] == '"') // Remove " "
path = path.substr(1, path.size() - 1);
if (path[1] != ':') // Add current path
{
char szLoadDir[MAXSTRING];
GetCurrentDirectory(MAXSTRING, szLoadDir);
path = string(szLoadDir) + PATH_SEPARATOR_CHAR + path;
}
else if (setCurrentPath) // Or set the current path from the arg
{
const string dir = PathFromFilename(path);
SetCurrentDirectory(dir.c_str());
}
return path;
}
BOOL InitInstance() override
{
#ifdef CRASH_HANDLER
rde::CrashHandler::Init();
#endif
#ifdef _MSC_VER
// disable auto-rotate on tablets
#if (WINVER <= 0x0601)
SetDisplayAutoRotationPreferences = (pSDARP)GetProcAddress(GetModuleHandle(TEXT("user32.dll")),
"SetDisplayAutoRotationPreferences");
if (SetDisplayAutoRotationPreferences)
SetDisplayAutoRotationPreferences(ORIENTATION_PREFERENCE_LANDSCAPE);
#else
SetDisplayAutoRotationPreferences(ORIENTATION_PREFERENCE_LANDSCAPE);
#endif
//!! max(2u, std::thread::hardware_concurrency()) ??
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
m_vpinball.m_logicalNumberOfProcessors = sysinfo.dwNumberOfProcessors; //!! this ignores processor groups, so if at some point we need extreme multi threading, implement this in addition!
#else
m_vpinball.m_logicalNumberOfProcessors = SDL_GetCPUCount();
#endif
IsOnWine(); // init static variable in there
#ifdef _MSC_VER
#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)
const HRESULT hRes = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
#else
const HRESULT hRes = CoInitialize(nullptr);
#endif
_ASSERTE(SUCCEEDED(hRes));
_Module.Init(ObjectMap, m_vpinball.theInstance, &LIBID_VPinballLib);
#endif
m_file = false;
m_play = false;
bool allowLoadOnStart = true;
m_extractPov = false;
m_run = true;
m_loadFileResult = true;
m_extractScript = false;
m_tournament = false;
m_fgles = 0.f;
m_bgles = false;
m_szTableFileName.clear();
// Default ini path (can be overriden from command line)
m_szIniFileName = m_vpinball.m_szMyPrefPath + "VPinballX.ini"s;
int nArgs;
LPSTR *szArglist = CommandLineToArgvA(GetCommandLine(), &nArgs);
for (int i = 1; i < nArgs; ++i) // skip szArglist[0], contains executable name
{
bool valid_param = false;
if ((szArglist[i][0] != '-') && (szArglist[i][0] != '/')) // ignore stuff (directories) that is passed in via frontends
valid_param = true;
if (!valid_param) for (size_t i2 = 0; i2 < std::size(options); ++i2)
{
if (compare_option(szArglist[i], (option_names)i2))
{
valid_param = true;
break;
}
}
if (!valid_param) for (char t = '1'; t <= '9'; ++t)
{
if ((lstrcmpi(szArglist[i], ("-c"s+t).c_str()) == 0) || (lstrcmpi(szArglist[i], ("/c"s+t).c_str()) == 0))
{
valid_param = true;
break;
}
}
//
if (!valid_param
|| compare_option(szArglist[i], OPTION_H)
|| compare_option(szArglist[i], OPTION_HELP)
|| compare_option(szArglist[i], OPTION_QMARK))
{
string output = '-' +options[OPTION_UNREGSERVER]+ " "+option_descs[OPTION_UNREGSERVER]+
"\n-" +options[OPTION_REGSERVER]+ " "+option_descs[OPTION_REGSERVER]+
"\n\n-"+options[OPTION_DISABLETRUEFULLSCREEN]+" "+option_descs[OPTION_DISABLETRUEFULLSCREEN]+
"\n-" +options[OPTION_ENABLETRUEFULLSCREEN]+ " "+option_descs[OPTION_ENABLETRUEFULLSCREEN]+
"\n-" +options[OPTION_MINIMIZED]+ " "+option_descs[OPTION_MINIMIZED]+
"\n-" +options[OPTION_EXTMINIMIZED]+ " "+option_descs[OPTION_EXTMINIMIZED]+
"\n-" +options[OPTION_PRIMARY]+ " "+option_descs[OPTION_PRIMARY]+
"\n\n-"+options[OPTION_GLES]+ " "+option_descs[OPTION_GLES]+
"\n\n-"+options[OPTION_LESSCPUTHREADS]+ " "+option_descs[OPTION_LESSCPUTHREADS]+
"\n\n-"+options[OPTION_EDIT]+ " "+option_descs[OPTION_EDIT]+
"\n-" +options[OPTION_PLAY]+ " "+option_descs[OPTION_PLAY]+
"\n-" +options[OPTION_POVEDIT]+ " "+option_descs[OPTION_POVEDIT]+
"\n-" +options[OPTION_POV]+ " "+option_descs[OPTION_POV]+
"\n-" +options[OPTION_EXTRACTVBS]+ " "+option_descs[OPTION_EXTRACTVBS]+
"\n-" +options[OPTION_INI]+ " "+option_descs[OPTION_INI]+
"\n-" +options[OPTION_TABLE_INI]+ " "+option_descs[OPTION_TABLE_INI]+
"\n\n-"+options[OPTION_TOURNAMENT]+ " "+option_descs[OPTION_TOURNAMENT]+
"\n\n-c1 [customparam] .. -c9 [customparam] Custom user parameters that can be accessed in the script via GetCustomParam(X)";
if (!valid_param)
output = "Invalid Parameter "s + szArglist[i] + "\n\nValid Parameters are:\n\n" + output;
::MessageBox(NULL, output.c_str(), "Visual Pinball Usage", valid_param ? MB_OK : MB_ICONERROR);
exit(valid_param ? 0 : 1);
}
//
if (compare_option(szArglist[i], OPTION_LESSCPUTHREADS))
m_vpinball.m_logicalNumberOfProcessors = max(min(m_vpinball.m_logicalNumberOfProcessors, 2), m_vpinball.m_logicalNumberOfProcessors/4); // only use 1/4th the threads, but at least 2 (if there are 2)
//
if (compare_option(szArglist[i], OPTION_UNREGSERVER))
{
_Module.UpdateRegistryFromResource(IDR_VPINBALL, FALSE);
const HRESULT ret = _Module.UnregisterServer(TRUE);
if (ret != S_OK)
ShowError("Unregister VP functions failed");
m_run = false;
break;
}
if (compare_option(szArglist[i], OPTION_REGSERVER))
{
_Module.UpdateRegistryFromResource(IDR_VPINBALL, TRUE);
const HRESULT ret = _Module.RegisterServer(TRUE);
if (ret != S_OK)
ShowError("Register VP functions failed");
m_run = false;
break;
}
//
if (compare_option(szArglist[i], OPTION_DISABLETRUEFULLSCREEN))
{
m_vpinball.m_disEnableTrueFullscreen = 0;
continue;
}
if (compare_option(szArglist[i], OPTION_ENABLETRUEFULLSCREEN))
{
m_vpinball.m_disEnableTrueFullscreen = 1;
continue;
}
//
bool useCustomParams = false;
int customIdx = 1;
for (char t = '1'; t <= '9'; ++t)
{
if (lstrcmpi(szArglist[i], ("-c"s+t).c_str()) == 0 || lstrcmpi(szArglist[i], ("/c"s+t).c_str()) == 0)
{
useCustomParams = true;
break;
}
customIdx++;
}
if (useCustomParams && (i+1<nArgs))
{
const size_t len = strlen(szArglist[i + 1]);
m_vpinball.m_customParameters[customIdx - 1] = new WCHAR[len + 1];
MultiByteToWideCharNull(CP_ACP, 0, szArglist[i + 1], -1, m_vpinball.m_customParameters[customIdx - 1], (int)len + 1);
++i; // two params processed
continue;
}
//
const bool minimized = compare_option(szArglist[i], OPTION_MINIMIZED);
if (minimized)
{
m_vpinball.m_open_minimized = true;
m_vpinball.m_disable_pause_menu = true;
}
const bool ext_minimized = compare_option(szArglist[i], OPTION_EXTMINIMIZED);
if (ext_minimized)
m_vpinball.m_open_minimized = true;
const bool gles = compare_option(szArglist[i], OPTION_GLES);
const bool primaryDisplay = compare_option(szArglist[i], OPTION_PRIMARY);
if (primaryDisplay)
m_vpinball.m_primaryDisplay = true;
// global emission scale parameter handling
if (gles && (i + 1 < nArgs))
{
char *lpszStr;
if ((szArglist[i + 1][0] == '-') || (szArglist[i + 1][0] == '/'))
lpszStr = szArglist[i + 1] + 1;
else
lpszStr = szArglist[i + 1];
m_fgles = clamp((float)atof(lpszStr), 0.115f, 0.925f);
m_bgles = true;
}
const bool editfile = compare_option(szArglist[i], OPTION_EDIT);
const bool playfile = compare_option(szArglist[i], OPTION_PLAY);
const bool povEdit = compare_option(szArglist[i], OPTION_POVEDIT);
const bool extractpov = compare_option(szArglist[i], OPTION_POV);
const bool extractscript = compare_option(szArglist[i], OPTION_EXTRACTVBS);
const bool ini = compare_option(szArglist[i], OPTION_INI);
const bool tableIni = compare_option(szArglist[i], OPTION_TABLE_INI);
const bool tournament = compare_option(szArglist[i], OPTION_TOURNAMENT);
if (/*playfile ||*/ extractpov || extractscript || tournament)
m_vpinball.m_open_minimized = true;
if (ini || tableIni || editfile || playfile || povEdit || extractpov || extractscript || tournament)
{
if (i + 1 >= nArgs)
{
::MessageBox(NULL, ("Option '"s + szArglist[i] + "' must be followed by a valid file path"s).c_str(), "Command Line Error", MB_ICONERROR);
exit(1);
}
const string path = GetPathFromArg(szArglist[i + 1], false);
if (!FileExists(path) && !ini && !tableIni)
{
::MessageBox(NULL, ("File '"s + path + "' was not found"s).c_str(), "Command Line Error", MB_ICONERROR);
exit(1);
}
if (tournament && (i + 2 >= nArgs))
{
::MessageBox(NULL, ("Option '"s + szArglist[i] + "' must be followed by two valid file paths"s).c_str(), "Command Line Error", MB_ICONERROR);
exit(1);
}
if (tournament)
{
m_szTournamentName = GetPathFromArg(szArglist[i + 2], false);
i++; // three params processed
if (!FileExists(m_szTournamentName))
{
::MessageBox(NULL, ("File '"s + m_szTournamentName + "' was not found"s).c_str(), "Command Line Error", MB_ICONERROR);
exit(1);
}
}
i++; // two params processed
if (ini)
m_szIniFileName = path;
else if (tableIni)
m_szTableIniFileName = path;
else // editfile || playfile || povEdit || extractpov || extractscript || tournament
{
allowLoadOnStart = false; // Don't face the user with a load dialog since the file is provided on the command line
m_file = true;
if (m_play || m_extractPov || m_extractScript || m_vpinball.m_povEdit || m_tournament)
{
::MessageBox(NULL, ("Only one of " + options[OPTION_EDIT] + ", " + options[OPTION_PLAY] + ", " + options[OPTION_POVEDIT] + ", " + options[OPTION_POV] + ", " + options[OPTION_EXTRACTVBS] + ", " + options[OPTION_TOURNAMENT] + " can be used.").c_str(),
"Command Line Error", MB_ICONERROR);
exit(1);
}
m_play = playfile || povEdit;
m_extractPov = extractpov;
m_extractScript = extractscript;
m_vpinball.m_povEdit = povEdit;
m_tournament = tournament;
m_szTableFileName = path;
}
}
}
free(szArglist);
// Default ini path (can be overriden from command line via m_szIniFileName)
if (m_szIniFileName.empty())
{
FILE *f;
// first check if there is a .ini next to the .exe, otherwise use the default location
if ((fopen_s(&f, (m_vpinball.m_szMyPath + "VPinballX.ini").c_str(), "r") == 0) && f)
{
m_vpinball.m_szMyPrefPath = m_vpinball.m_szMyPath;
fclose(f);
}
m_szIniFileName = m_vpinball.m_szMyPrefPath + "VPinballX.ini";
}
m_vpinball.m_settings.LoadFromFile(m_szIniFileName, true);
m_vpinball.m_settings.SaveValue(Settings::Version, "VPinball"s, VP_VERSION_STRING_DIGITS);
SetupLogger(m_vpinball.m_settings.LoadValueWithDefault(Settings::Editor, "EnableLog"s, false));
PLOGI << "Starting VPX - " << VP_VERSION_STRING_FULL_LITERAL;
// Start VP with file dialog open and then also playing that one?
const bool stos = allowLoadOnStart && m_vpinball.m_settings.LoadValueWithDefault(Settings::Editor, "SelectTableOnStart"s, true);
if (stos)
{
m_file = true;
m_play = true;
}
// load and register VP type library for COM integration
char szFileName[MAXSTRING];
if (GetModuleFileName(m_vpinball.theInstance, szFileName, MAXSTRING))
{
ITypeLib *ptl = nullptr;
MAKE_WIDEPTR_FROMANSI(wszFileName, szFileName);
if (SUCCEEDED(LoadTypeLib(wszFileName, &ptl)))
{
// first try to register system-wide (if running as admin)
HRESULT hr = RegisterTypeLib(ptl, wszFileName, nullptr);
if (!SUCCEEDED(hr))
{
// if failed, register only for current user
hr = RegisterTypeLibForUser(ptl, wszFileName, nullptr);
if (!SUCCEEDED(hr))
m_vpinball.MessageBox("Could not register type library. Try running Visual Pinball as administrator.", "Error", MB_ICONERROR);
}
ptl->Release();
}
else
m_vpinball.MessageBox("Could not load type library.", "Error", MB_ICONERROR);
}
#if _WIN32_WINNT >= 0x0400 & defined(_ATL_FREE_THREADED)
const HRESULT hRes2 = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE | REGCLS_SUSPENDED);
_ASSERTE(SUCCEEDED(hRes));
hRes2 = CoResumeClassObjects();
#else
const HRESULT hRes2 = _Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE);
#endif
_ASSERTE(SUCCEEDED(hRes2));
INITCOMMONCONTROLSEX iccex;
iccex.dwSize = sizeof(INITCOMMONCONTROLSEX);
iccex.dwICC = ICC_COOL_CLASSES;
InitCommonControlsEx(&iccex);
EditableRegistry::RegisterEditable<Bumper>();
EditableRegistry::RegisterEditable<Decal>();
EditableRegistry::RegisterEditable<DispReel>();
EditableRegistry::RegisterEditable<Flasher>();
EditableRegistry::RegisterEditable<Flipper>();
EditableRegistry::RegisterEditable<Gate>();
EditableRegistry::RegisterEditable<Kicker>();
EditableRegistry::RegisterEditable<Light>();
EditableRegistry::RegisterEditable<LightSeq>();
EditableRegistry::RegisterEditable<Plunger>();
EditableRegistry::RegisterEditable<Primitive>();
EditableRegistry::RegisterEditable<Ramp>();
EditableRegistry::RegisterEditable<Rubber>();
EditableRegistry::RegisterEditable<Spinner>();
EditableRegistry::RegisterEditable<Surface>();
EditableRegistry::RegisterEditable<Textbox>();
EditableRegistry::RegisterEditable<Timer>();
EditableRegistry::RegisterEditable<Trigger>();
EditableRegistry::RegisterEditable<HitTarget>();
m_vpinball.AddRef();
m_vpinball.Create(nullptr);
m_vpinball.m_bgles = m_bgles;
m_vpinball.m_fgles = m_fgles;
g_haccel = LoadAccelerators(m_vpinball.theInstance, MAKEINTRESOURCE(IDR_VPACCEL));
if (m_file)
{
if (!m_szTableFileName.empty())
{
PLOGI << "Loading table from command line option: " << m_szTableFileName;
m_vpinball.LoadFileName(m_szTableFileName, !m_play);
m_vpinball.m_table_played_via_command_line = m_play;
m_loadFileResult = m_vpinball.m_ptableActive != nullptr;
if (m_vpinball.m_ptableActive && !m_szTableIniFileName.empty())
m_vpinball.m_ptableActive->SetSettingsFileName(m_szTableIniFileName);
if (!m_loadFileResult && m_vpinball.m_open_minimized)
m_vpinball.QuitPlayer(Player::CloseState::CS_CLOSE_APP);
}
else
{
m_loadFileResult = m_vpinball.LoadFile(!m_play);
m_vpinball.m_table_played_via_SelectTableOnStart = m_vpinball.m_settings.LoadValueWithDefault(Settings::Editor, "SelectTableOnPlayerClose"s, true) ? m_loadFileResult : false;
}
if (m_extractScript && m_loadFileResult)
{
string szScriptFilename = m_szTableFileName;
if(ReplaceExtensionFromFilename(szScriptFilename, "vbs"s))
m_vpinball.m_ptableActive->m_pcv->SaveToFile(szScriptFilename);
m_vpinball.QuitPlayer(Player::CloseState::CS_CLOSE_APP);
}
if (m_extractPov && m_loadFileResult)
{
for (int i = 0; i < 3; i++)
m_vpinball.m_ptableActive->mViewSetups[i].SaveToTableOverrideSettings(m_vpinball.m_ptableActive->m_settings, (ViewSetupID) i);
m_vpinball.m_ptableActive->m_settings.Save();
m_vpinball.QuitPlayer(Player::CloseState::CS_CLOSE_APP);
}
if (m_tournament && m_loadFileResult)
{
m_vpinball.GenerateImageFromTournamentFile(m_szTableFileName, m_szTournamentName);
m_vpinball.QuitPlayer(Player::CloseState::CS_CLOSE_APP);
}
}
//SET_CRT_DEBUG_FIELD( _CRTDBG_LEAK_CHECK_DF );
return TRUE;
}
int Run() override
{
if (m_run)
{
if (m_play && m_loadFileResult)
m_vpinball.DoPlay(m_vpinball.m_povEdit);
// VBA APC handles message loop (bastards)
m_vpinball.MainMsgLoop();
m_vpinball.m_settings.Save();
m_vpinball.Release();
DestroyAcceleratorTable(g_haccel);
_Module.RevokeClassObjects();
Sleep(THREADS_PAUSE); //wait for any threads to finish
}
return 0;
}
};
#if defined(ENABLE_SDL)
// The OpenGL implementation will fail on NVIDIA drivers when Threaded Optimization is enabled so we disable it for this app
// Note: There are quite a lot of applications doing this, but I think this may hide an incorrect OpenGL call somewhere
// that the threaded optimization of NVIDIA drivers ends up to crash. This would be good to find the root cause, if any.
#include "nvapi/nvapi.h"
#include "nvapi/NvApiDriverSettings.h"
#pragma warning(push)
#pragma warning(disable : 4838)
#include "nvapi/NvApiDriverSettings.c"
#pragma warning(pop)
enum NvThreadOptimization
{
NV_THREAD_OPTIMIZATION_AUTO = 0,
NV_THREAD_OPTIMIZATION_ENABLE = 1,
NV_THREAD_OPTIMIZATION_DISABLE = 2,
NV_THREAD_OPTIMIZATION_NO_SUPPORT = 3
};
static bool NvAPI_OK_Verify(NvAPI_Status status)
{
if (status == NVAPI_OK)
return true;
NvAPI_ShortString szDesc = { 0 };
NvAPI_GetErrorMessage(status, szDesc);
PLOGI << "NVAPI error: " << szDesc;
return false;
}
static NvThreadOptimization GetNVIDIAThreadOptimization()
{
NvThreadOptimization threadOptimization = NV_THREAD_OPTIMIZATION_NO_SUPPORT;
NvAPI_Status status;
status = NvAPI_Initialize();
if (!NvAPI_OK_Verify(status))
return threadOptimization;
NvDRSSessionHandle hSession;
status = NvAPI_DRS_CreateSession(&hSession);
if (!NvAPI_OK_Verify(status))
return threadOptimization;
status = NvAPI_DRS_LoadSettings(hSession);
if (!NvAPI_OK_Verify(status))
{
NvAPI_DRS_DestroySession(hSession);
return threadOptimization;
}
NvDRSProfileHandle hProfile;
status = NvAPI_DRS_GetBaseProfile(hSession, &hProfile);
if (!NvAPI_OK_Verify(status))
{
NvAPI_DRS_DestroySession(hSession);
return threadOptimization;
}
NVDRS_SETTING originalSetting = {};
originalSetting.version = NVDRS_SETTING_VER;
status = NvAPI_DRS_GetSetting(hSession, hProfile, OGL_THREAD_CONTROL_ID, &originalSetting);
if (NvAPI_OK_Verify(status))
{
threadOptimization = (NvThreadOptimization)originalSetting.u32CurrentValue;
}
NvAPI_DRS_DestroySession(hSession);
return threadOptimization;
}
static void SetNVIDIAThreadOptimization(NvThreadOptimization threadedOptimization)
{
if (threadedOptimization == NV_THREAD_OPTIMIZATION_NO_SUPPORT)
return;
NvAPI_Status status;
status = NvAPI_Initialize();
if (!NvAPI_OK_Verify(status))
return;
NvDRSSessionHandle hSession;
status = NvAPI_DRS_CreateSession(&hSession);
if (!NvAPI_OK_Verify(status))
return;
status = NvAPI_DRS_LoadSettings(hSession);
if (!NvAPI_OK_Verify(status))
{
NvAPI_DRS_DestroySession(hSession);
return;
}
NvDRSProfileHandle hProfile;
status = NvAPI_DRS_GetBaseProfile(hSession, &hProfile);
if (!NvAPI_OK_Verify(status))
{
NvAPI_DRS_DestroySession(hSession);
return;
}
NVDRS_SETTING setting = {};
setting.version = NVDRS_SETTING_VER;
setting.settingId = OGL_THREAD_CONTROL_ID;
setting.settingType = NVDRS_DWORD_TYPE;
setting.u32CurrentValue = (EValues_OGL_THREAD_CONTROL)threadedOptimization;
status = NvAPI_DRS_SetSetting(hSession, hProfile, &setting);
if (!NvAPI_OK_Verify(status))
{
NvAPI_DRS_DestroySession(hSession);
return;
}
status = NvAPI_DRS_SaveSettings(hSession);
NvAPI_OK_Verify(status);
NvAPI_DRS_DestroySession(hSession);
}
#endif
class DebugAppender : public plog::IAppender
{
public:
virtual void write(const plog::Record &record) PLOG_OVERRIDE
{
if (g_pvp == nullptr || g_pplayer == nullptr)
return;
auto table = g_pvp->GetActiveTable();
if (table == nullptr)
return;
#ifdef _WIN32
// Convert from wchar* to char* on Win32
auto msg = record.getMessage();
const int len = (int)lstrlenW(msg);
char *const szT = new char[len + 1];
WideCharToMultiByteNull(CP_ACP, 0, msg, -1, szT, len + 1, nullptr, nullptr);
table->m_pcv->AddToDebugOutput(szT);
delete [] szT;
#else
table->m_pcv->AddToDebugOutput(record.getMessage());
#endif
}
};
void SetupLogger(const bool enable)
{
plog::Severity maxLogSeverity = plog::none;
if (enable)
{
static bool initialized = false;
if (!initialized)
{
initialized = true;
static plog::RollingFileAppender<plog::TxtFormatter> fileAppender("vpinball.log", 1024 * 1024 * 5, 1);
static DebugAppender debugAppender;
plog::Logger<PLOG_DEFAULT_INSTANCE_ID>::getInstance()->addAppender(&debugAppender);
plog::Logger<PLOG_DEFAULT_INSTANCE_ID>::getInstance()->addAppender(&fileAppender);
plog::Logger<PLOG_NO_DBG_OUT_INSTANCE_ID>::getInstance()->addAppender(&fileAppender);
}
#ifdef _DEBUG
maxLogSeverity = plog::debug;
#else
maxLogSeverity = plog::info;
#endif
}
plog::Logger<PLOG_DEFAULT_INSTANCE_ID>::getInstance()->setMaxSeverity(maxLogSeverity);
plog::Logger<PLOG_NO_DBG_OUT_INSTANCE_ID>::getInstance()->setMaxSeverity(maxLogSeverity);
}
extern "C" int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR /*lpCmdLine*/, int /*nShowCmd*/)
{
#if defined(ENABLE_SDL)
static NvThreadOptimization s_OriginalNVidiaThreadOptimization = NV_THREAD_OPTIMIZATION_NO_SUPPORT;
#endif
int retval;
try
{
#if defined(ENABLE_SDL)
s_OriginalNVidiaThreadOptimization = GetNVIDIAThreadOptimization();
if (s_OriginalNVidiaThreadOptimization != NV_THREAD_OPTIMIZATION_NO_SUPPORT && s_OriginalNVidiaThreadOptimization != NV_THREAD_OPTIMIZATION_DISABLE)
{
PLOGI << "Disabling NVIDIA Threaded Optimization";
SetNVIDIAThreadOptimization(NV_THREAD_OPTIMIZATION_DISABLE);
}
#endif
#if defined(ENABLE_SDL) || defined(ENABLE_SDL_INPUT)
SDL_Init(0
#ifdef ENABLE_SDL
| SDL_INIT_VIDEO
#endif
#ifdef ENABLE_SDL_INPUT
| SDL_INIT_JOYSTICK
#endif
);
#endif
plog::init<PLOG_DEFAULT_INSTANCE_ID>();
plog::init<PLOG_NO_DBG_OUT_INSTANCE_ID>(); // Logger that do not show in the debug window to avoid duplicated messages
// Start Win32++
VPApp theApp(hInstance);
theApp.InitInstance();
// Run the application
retval = theApp.Run();
}
// catch all CException types
catch (const CException &e)
{
// Display the exception and quit
MessageBox(nullptr, e.GetText(), AtoT(e.what()), MB_ICONERROR);
retval = -1;
}
#if defined(ENABLE_SDL) || defined(ENABLE_SDL_INPUT)
SDL_Quit();
#endif
#if defined(ENABLE_SDL)
if (s_OriginalNVidiaThreadOptimization != NV_THREAD_OPTIMIZATION_NO_SUPPORT && s_OriginalNVidiaThreadOptimization != NV_THREAD_OPTIMIZATION_DISABLE)
{
PLOGI << "Restoring NVIDIA Threaded Optimization";
SetNVIDIAThreadOptimization(s_OriginalNVidiaThreadOptimization);