-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSeriousSam.cpp
2016 lines (1585 loc) · 60.5 KB
/
SeriousSam.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
/* Copyright (c) 2002-2012 Croteam Ltd.
This program is free software; you can redistribute it and/or modify
it under the terms of version 2 of the GNU General Public License as published by
the Free Software Foundation
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */
#include "StdH.h"
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <process.h>
#include "resource.h"
#include "SplashScreen.h"
#include "MainWindow.h"
#include "GlSettings.h"
#include "LevelInfo.h"
#include "CmdLine.h"
#include "Credits.h"
#include "GUI/Menus/MenuStuff.h"
// [Cecil] Classics patch
#include <CoreLib/Query/QueryManager.h>
#include <CoreLib/Networking/Modules/VotingSystem.h>
#include <Engine/Sound/SoundData.h>
#include "Cecil/UpdateCheck.h"
#include "Cecil/WindowModes.h"
#include <locale.h>
// Application state variables
extern BOOL _bRunning = TRUE;
extern BOOL _bQuitScreen = TRUE;
extern BOOL bMenuActive = FALSE;
extern BOOL bMenuRendering = FALSE;
static BOOL _bReconsiderInput = FALSE;
// [Cecil] Computer screen resolution
extern PIX2D _vpixScreenRes = PIX2D(0, 0);
static INDEX sam_iMaxFPSActive = 500;
static INDEX sam_iMaxFPSInactive = 10;
static INDEX sam_bPauseOnMinimize = TRUE; // auto-pause when window has been minimized
static INDEX sam_bWideScreen = FALSE; // [Cecil] Dummy; replaced with 'sam_bAdjustForAspectRatio'
extern FLOAT sam_fPlayerOffset = 0.0f;
// Display mode settings
static INDEX sam_iWindowMode = 0; // [Cecil] Different window modes
static INDEX sam_iScreenSizeI = 1024; // current size of the window
static INDEX sam_iScreenSizeJ = 768; // current size of the window
static INDEX sam_iDisplayDepth = 0; // 0 = default, 1 = 16bit, 2 = 32bit
static INDEX sam_iDisplayAdapter = 0;
// [Cecil] Variables for setup via config
static INDEX sam_iConfigWindowMode = 0;
static CTString sam_strConfigResolution = "1024x768";
static INDEX sam_iConfigDisplayDepth = 0;
static INDEX sam_iConfigDisplayAdapter = 0;
static INDEX sam_iConfigGfxAPI = 0;
extern INDEX sam_iGfxAPI = 0; // 0 = OpenGL
extern INDEX sam_bFirstStarted = FALSE;
extern FLOAT sam_tmDisplayModeReport = 5.0f;
extern INDEX sam_bShowAllLevels = FALSE;
static INDEX sam_bMentalActivated = FALSE;
// Network settings
extern CTString sam_strNetworkSettings = "";
// Command line
extern CTString sam_strCommandLine = "";
// 0...app started for the first time
// 1...all ok
// 2...automatic fallback
static INDEX _iDisplayModeChangeFlag = 0;
static TIME _tmDisplayModeChanged = 100.0f; // when display mode was last changed
// Rendering preferences for automatic settings
extern INDEX sam_iVideoSetup = 1;
// Automatic adjustment of audio quality
extern BOOL sam_bAutoAdjustAudio = TRUE;
extern INDEX sam_bAutoPlayDemos = TRUE;
static INDEX _bInAutoPlayLoop = TRUE;
// Menu calling
extern INDEX sam_bMenuSave = FALSE;
extern INDEX sam_bMenuLoad = FALSE;
extern INDEX sam_bMenuControls = FALSE;
extern INDEX sam_bMenuHiScore = FALSE;
extern INDEX sam_bToggleConsole = FALSE;
extern INDEX sam_iStartCredits = FALSE;
// For mod re-loading
extern CTFileName _fnmModToLoad = CTString("");
extern CTString _strModServerJoin = CTString("");
extern CTString _strURLToVisit = CTString("");
// State variables fo addon execution
// 0 - nothing
// 1 - start (invoke console)
// 2 - console invoked, waiting for one redraw
extern INDEX _iAddonExecState = 0;
extern CTFileName _fnmAddonToExec = CTString("");
// Logo textures
static CTextureObject _toLogoCT;
static CTextureObject _toLogoODI;
static CTextureObject _toLogoEAX;
extern CTextureObject *_ptoLogoCT = NULL;
extern CTextureObject *_ptoLogoODI = NULL;
extern CTextureObject *_ptoLogoEAX = NULL;
// [Cecil] The First Encounter
#if SE1_GAME == SS_TFE
CTString sam_strModName = "- T H E F I R S T E N C O U N T E R -";
CTString sam_strTechTestLevel = "Levels\\TechTest.wld";
CTString sam_strTrainingLevel = "Levels\\KarnakDemo.wld";
#else
CTString sam_strModName = "- T H E S E C O N D E N C O U N T E R -";
CTString sam_strTechTestLevel = "Levels\\LevelsMP\\TechTest.wld";
CTString sam_strTrainingLevel = "Levels\\KarnakDemo.wld";
#endif
ENGINE_API extern INDEX snd_iFormat;
// [Cecil] Set new LCD drawport for Game
void SetDrawportForGame(CDrawPort *pdpSet) {
_pGame->LCDSetDrawport(pdpSet);
// Adjust aspect ratio for the menu
if (IConfig::mod[k_EModDataProps_ProperTextScaling]) {
pdpSet->dp_fWideAdjustment = ((FLOAT)pdpSet->GetHeight() / (FLOAT)pdpSet->GetWidth()) * (4.0f / 3.0f);
}
};
// Main window canvas
CDrawPort *_pdpMenu = NULL;
CDrawPort *_pdpNormal = NULL;
CViewPort *_pvpViewPort = NULL;
HINSTANCE _hInstance;
static void PlayDemo(SHELL_FUNC_ARGS) {
BEGIN_SHELL_FUNC;
const CTString &strDemoFilename = *NEXT_ARG(CTString *);
_gmMenuGameMode = GM_DEMO;
CTFileName fnDemo = "demos\\" + strDemoFilename + ".dem";
extern BOOL LSLoadDemo(const CTFileName &fnm);
LSLoadDemo(fnDemo);
}
static void ApplyRenderingPreferences(void) {
ApplyGLSettings(TRUE);
}
static void ApplyVideoMode(void) {
StartNewMode((GfxAPIType)sam_iGfxAPI, sam_iDisplayAdapter, sam_iScreenSizeI, sam_iScreenSizeJ, (DisplayDepth)sam_iDisplayDepth, sam_iWindowMode);
}
static INDEX sam_old_iWindowMode; // [Cecil] Different window modes
static INDEX sam_old_iScreenSizeI;
static INDEX sam_old_iScreenSizeJ;
static INDEX sam_old_iDisplayDepth;
static INDEX sam_old_iDisplayAdapter;
static INDEX sam_old_iGfxAPI;
static INDEX sam_old_iVideoSetup;
// [Cecil] Methods for applying new video and audio options
static void RevertVideoSettings(void) {
// restore previous variables
sam_iWindowMode = sam_old_iWindowMode;
sam_iScreenSizeI = sam_old_iScreenSizeI;
sam_iScreenSizeJ = sam_old_iScreenSizeJ;
sam_iDisplayDepth = sam_old_iDisplayDepth;
sam_iDisplayAdapter = sam_old_iDisplayAdapter;
sam_iGfxAPI = sam_old_iGfxAPI;
sam_iVideoSetup = sam_old_iVideoSetup;
// update the video mode
ApplyVideoMode();
};
static void ApplyVideoOptions(void) {
// Remember old video settings
sam_old_iWindowMode = sam_iWindowMode;
sam_old_iScreenSizeI = sam_iScreenSizeI;
sam_old_iScreenSizeJ = sam_iScreenSizeJ;
sam_old_iDisplayDepth = sam_iDisplayDepth;
sam_old_iDisplayAdapter = sam_iDisplayAdapter;
sam_old_iGfxAPI = sam_iGfxAPI;
sam_old_iVideoSetup = sam_iVideoSetup;
// [Cecil] Use config values
const GfxAPIType eAPI = NormalizeGfxAPI(sam_iConfigGfxAPI);
const INDEX iAdapter = sam_iConfigDisplayAdapter;
DisplayDepth eDisplayDepth = NormalizeDepth(sam_iConfigDisplayDepth);
INDEX iWindowMode = Clamp(sam_iConfigWindowMode, (INDEX)E_WM_WINDOWED, (INDEX)E_WM_FULLSCREEN);
// [Cecil] Keep custom preferences
extern INDEX _iLastPreferences;
if (sam_iVideoSetup < 0 || sam_iVideoSetup >= _iDisplayPrefsLastOpt) {
_iLastPreferences = sam_iVideoSetup;
}
// force fullscreen mode if needed
CDisplayAdapter &da = _pGfx->gl_gaAPI[eAPI].ga_adaAdapter[iAdapter];
if (da.da_ulFlags & DAF_FULLSCREENONLY) {
iWindowMode = E_WM_FULLSCREEN;
}
if (da.da_ulFlags & DAF_16BITONLY) {
eDisplayDepth = DD_16BIT;
}
// force window to always be in default colors
if (iWindowMode != E_WM_FULLSCREEN) {
eDisplayDepth = DD_DEFAULT;
}
// [Cecil] Get resolution from the custom string
PIX iW, iH;
if (sam_strConfigResolution.ScanF("%dx%d", &iW, &iH) != 2) {
iW = 1024;
iH = 768;
}
StartNewMode(eAPI, iAdapter, iW, iH, eDisplayDepth, iWindowMode);
// FIXUP: keyboard focus lost when going from full screen to window mode
// due to WM_MOUSEMOVE being sent
extern BOOL _bMouseUsedLast;
extern CMenuGadget *_pmgUnderCursor;
_bMouseUsedLast = FALSE;
_pmgUnderCursor = _pGUIM->gmConfirmMenu.gm_pmgSelectedByDefault;
CConfirmMenu::ChangeTo(LOCALIZE("KEEP THIS SETTING?"), NULL, &RevertVideoSettings, TRUE);
};
static void ApplyAudioOptions(void) {
if (sam_bAutoAdjustAudio) {
_pShell->Execute("include \"" SCRIPTS_ADDONS_DIR "SFX-AutoAdjust.ini\"");
} else {
switch (snd_iFormat) {
case 1: _pSound->SetFormat(CSoundLibrary::SF_11025_16); break;
case 2: _pSound->SetFormat(CSoundLibrary::SF_22050_16); break;
case 3: _pSound->SetFormat(CSoundLibrary::SF_44100_16); break;
default: _pSound->SetFormat(CSoundLibrary::SF_NONE);
}
}
snd_iFormat = _pSound->GetFormat();
};
static void BenchMark(void) {
_pGfx->Benchmark(_pvpViewPort, _pdpMenu);
}
static void QuitGame(void) {
_bRunning = FALSE;
_bQuitScreen = FALSE;
}
// Check if another app is already running
static HANDLE _hLock = NULL;
static CTFileName _fnmLock;
static void DirectoryLockOn(void) {
// create lock filename
_fnmLock = IDir::AppPath() + "SeriousSam.loc";
// try to open lock file
_hLock = CreateFileA(
_fnmLock,
GENERIC_WRITE,
0, // no sharing
NULL, // pointer to security attributes
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE, // file attributes
NULL);
// if failed
if (_hLock == NULL || GetLastError() != 0) {
// report warning
CPutString(LOCALIZE("WARNING: SeriousSam didn't shut down properly last time!\n"));
}
}
static void DirectoryLockOff(void) {
// if lock is open
if (_hLock != NULL) {
// close it
CloseHandle(_hLock);
}
}
void End(void);
// Automaticaly manage input enable/disable toggling
static BOOL _bInputEnabled = FALSE;
void UpdateInputEnabledState(void) {
// do nothing if window is invalid
if (_hwndMain == NULL) {
return;
}
// input should be enabled if application is active
// and no menu is active and no console is active
BOOL bShouldBeEnabled = (!IsIconic(_hwndMain) && !bMenuActive && GetGameAPI()->GetConState() == CS_OFF
&& (GetGameAPI()->GetCompState() == CS_OFF || GetGameAPI()->GetCompState() == CS_ONINBACKGROUND))
|| _bDefiningKey;
// if should be turned off
if ((!bShouldBeEnabled && _bInputEnabled) || _bReconsiderInput) {
// disable it and remember new state
_pInput->DisableInput();
_bInputEnabled = FALSE;
}
// if should be turned on
if (bShouldBeEnabled && !_bInputEnabled) {
// enable it and remember new state
_pInput->EnableInput(_hwndMain);
_bInputEnabled = TRUE;
}
_bReconsiderInput = FALSE;
}
// Automaticaly manage pause toggling
void UpdatePauseState(void) {
// [Cecil] Get states
const INDEX iConState = GetGameAPI()->GetConState();
const INDEX iCompState = GetGameAPI()->GetCompState();
// [Cecil] Check Steam overlay
BOOL bShouldPause = (bMenuActive || GetSteamAPI()->IsOverlayOn() ||
iConState == CS_ON || iConState == CS_TURNINGON || iConState == CS_TURNINGOFF ||
iCompState == CS_ON || iCompState == CS_TURNINGON || iCompState == CS_TURNINGOFF);
_pNetwork->SetLocalPause(_gmRunningGameMode == GM_SINGLE_PLAYER && bShouldPause);
}
// Limit current frame rate if neeeded
void LimitFrameRate(void) {
// measure passed time for each loop
static CTimerValue tvLast(-1.0f);
CTimerValue tvNow = _pTimer->GetHighPrecisionTimer();
TIME tmCurrentDelta = (tvNow - tvLast).GetSeconds();
// limit maximum frame rate
sam_iMaxFPSActive = ClampDn((INDEX)sam_iMaxFPSActive, 1L);
sam_iMaxFPSInactive = ClampDn((INDEX)sam_iMaxFPSInactive, 1L);
INDEX iMaxFPS = sam_iMaxFPSActive;
if (IsIconic(_hwndMain)) {
iMaxFPS = sam_iMaxFPSInactive;
}
if (GetGameAPI()->GetCurrentSplitCfg() == CGame::SSC_DEDICATED) {
iMaxFPS = ClampDn(iMaxFPS, 60L); // never go very slow if dedicated server
}
TIME tmWantedDelta = 1.0f / iMaxFPS;
if (tmCurrentDelta < tmWantedDelta) {
Sleep((tmWantedDelta - tmCurrentDelta) * 1000.0f);
}
// remember new time
tvLast = _pTimer->GetHighPrecisionTimer();
}
// Load first demo
void StartNextDemo(void) {
if (!sam_bAutoPlayDemos || !_bInAutoPlayLoop) {
_bInAutoPlayLoop = FALSE;
return;
}
// skip if no demos
if (_lhAutoDemos.IsEmpty()) {
_bInAutoPlayLoop = FALSE;
return;
}
// get first demo level and cycle the list
CLevelInfo *pli = LIST_HEAD(_lhAutoDemos, CLevelInfo, li_lnNode);
pli->li_lnNode.Remove();
_lhAutoDemos.AddTail(pli->li_lnNode);
// if intro
if (pli->li_fnLevel == sam_strIntroLevel) {
// start intro
_gmRunningGameMode = GM_NONE;
// [Cecil] Reset start player indices
GetGameAPI()->ResetStartProfiles();
GetGameAPI()->SetProfileForStart(0, 0);
GetGameAPI()->SetNetworkProvider(CGameAPI::NP_LOCAL);
GetGameAPI()->SetStartSplitCfg(CGame::SSC_PLAY1);
// [Cecil] Use difficulties and game modes from the API
_pShell->SetINDEX("gam_iStartDifficulty", ClassicsModData_GetDiff(2)->m_iLevel); // Normal
_pShell->SetINDEX("gam_iStartMode", GetGameAPI()->GetGameMode(0)); // Flyover
// [Cecil] Pass byte container
CSesPropsContainer sp;
_pGame->SetSinglePlayerSession((CSessionProperties &)sp);
GetGameAPI()->SetFirstLoading(TRUE);
// [Cecil] Start game through the API
if (GetGameAPI()->NewGame(sam_strIntroLevel, sam_strIntroLevel, (CSessionProperties &)sp)) {
_gmRunningGameMode = GM_INTRO;
}
// if not intro
} else {
// start the demo
GetGameAPI()->SetStartSplitCfg(CGame::SSC_OBSERVER);
// [Cecil] Reset start player indices
GetGameAPI()->ResetStartProfiles();
// play the demo
GetGameAPI()->SetNetworkProvider(CGameAPI::NP_LOCAL);
_gmRunningGameMode = GM_NONE;
if (_pGame->StartDemoPlay(pli->li_fnLevel)) {
_gmRunningGameMode = GM_DEMO;
CON_DiscardLastLineTimes();
}
}
if (_gmRunningGameMode == GM_NONE) {
_bInAutoPlayLoop = FALSE;
}
}
// Run web browser and view an url
void RunBrowser(const char *strUrl, BOOL bUseSteamOverlay) {
// [Cecil] Try web browser in Steam overlay
if (bUseSteamOverlay) {
if (GetSteamAPI()->OpenWebPage(strUrl)) return;
}
int iResult = (int)ShellExecuteA(_hwndMain, "OPEN", strUrl, NULL, NULL, SW_SHOWMAXIMIZED);
if (iResult < 32) {
// should report error?
NOTHING;
}
}
void LoadAndForceTexture(CTextureObject &to, CTextureObject *&pto, const CTFileName &fnm) {
try {
to.SetData_t(fnm);
CTextureData *ptd = (CTextureData *)to.GetData();
ptd->Force(TEX_CONSTANT);
ptd = ptd->td_ptdBaseTexture;
if (ptd != NULL) {
ptd->Force(TEX_CONSTANT);
}
pto = &to;
} catch (char *pchrError) {
(void *)pchrError;
pto = NULL;
}
}
BOOL Init(HINSTANCE hInstance, int nCmdShow, CTString strCmdLine) {
_hInstance = hInstance;
// [Cecil] Mark as a game
ClassicsPatch_Setup(k_EClassicsPatchAppType_Game);
// [Cecil] Set DPI awareness
SetDPIAwareness();
ShowSplashScreen(hInstance);
#if _PATCHCONFIG_ENGINEPATCHES
// [Cecil] Function patches
_EnginePatches.FileSystem();
#endif
// [Cecil] Get screen resolution
_vpixScreenRes = PIX2D(::GetSystemMetrics(SM_CXSCREEN),
::GetSystemMetrics(SM_CYSCREEN));
// prepare main window
MainWindow_Init();
OpenMainWindowInvisible();
// [Cecil] Remember command line arguments
_strRestartCommandLine = strCmdLine;
// parse command line before initializing engine
ParseCommandLine(strCmdLine, TRUE);
#if SE1_GAME == SS_REV
// [Cecil] Rev: Use Steam the same way as in Revolution's EXE
if (strCmdLine.FindSubstr("-nosteam") == -1) {
if (_pSteam->IsSteamRunning()) {
_pSteam->Initialize(FALSE, 227780, "Serious Sam: Revolution");
} else {
// [Cecil] NOTE: Restarts the client but doesn't initialize?
_pSteam->RestartSteamIfNecessary();
}
}
#endif
// initialize engine
SE_InitEngine(sam_strGameName);
// [Cecil] Custom initialization
ClassicsPatch_InitExt();
SE_LoadDefaultFonts();
// now print the output of command line parsing
CPrintF("%s", cmd_strOutput);
// lock the directory
DirectoryLockOn();
// load all translation tables
InitTranslation();
try {
AddTranslationTablesDir_t(CTString("Data\\Translations\\"), CTString("*.txt"));
FinishTranslationTable();
} catch (char *strError) {
FatalError("Cannot load translation tables:\n%s", strError);
}
// [Cecil] Translate the mod name
sam_strModName = TRANSV(sam_strModName);
// always disable all warnings when in serious sam
_pShell->Execute("con_bNoWarnings=1;");
// declare shell symbols
_pShell->DeclareSymbol("user void PlayDemo(CTString);", &PlayDemo);
_pShell->DeclareSymbol("persistent INDEX sam_iWindowMode;", &sam_iWindowMode); // [Cecil] Window modes
_pShell->DeclareSymbol("persistent INDEX sam_iScreenSizeI;", &sam_iScreenSizeI);
_pShell->DeclareSymbol("persistent INDEX sam_iScreenSizeJ;", &sam_iScreenSizeJ);
_pShell->DeclareSymbol("persistent INDEX sam_iDisplayDepth;", &sam_iDisplayDepth);
_pShell->DeclareSymbol("persistent INDEX sam_iDisplayAdapter;", &sam_iDisplayAdapter);
// [Cecil] Variables for setup via config
_pShell->DeclareSymbol("INDEX sam_iConfigWindowMode;", &sam_iConfigWindowMode);
_pShell->DeclareSymbol("CTString sam_strConfigResolution;", &sam_strConfigResolution);
_pShell->DeclareSymbol("INDEX sam_iConfigDisplayDepth;", &sam_iConfigDisplayDepth);
_pShell->DeclareSymbol("INDEX sam_iConfigDisplayAdapter;", &sam_iConfigDisplayAdapter);
_pShell->DeclareSymbol("INDEX sam_iConfigGfxAPI;", &sam_iConfigGfxAPI);
_pShell->DeclareSymbol("persistent INDEX sam_iGfxAPI;", &sam_iGfxAPI);
_pShell->DeclareSymbol("persistent INDEX sam_bFirstStarted;", &sam_bFirstStarted);
_pShell->DeclareSymbol("persistent INDEX sam_bAutoAdjustAudio;", &sam_bAutoAdjustAudio);
_pShell->DeclareSymbol("persistent user INDEX sam_bWideScreen;", &sam_bWideScreen);
_pShell->DeclareSymbol("persistent user FLOAT sam_fPlayerOffset;", &sam_fPlayerOffset);
_pShell->DeclareSymbol("persistent user INDEX sam_bAutoPlayDemos;", &sam_bAutoPlayDemos);
_pShell->DeclareSymbol("persistent user INDEX sam_iMaxFPSActive;", &sam_iMaxFPSActive);
_pShell->DeclareSymbol("persistent user INDEX sam_iMaxFPSInactive;", &sam_iMaxFPSInactive);
_pShell->DeclareSymbol("persistent user INDEX sam_bPauseOnMinimize;", &sam_bPauseOnMinimize);
_pShell->DeclareSymbol("persistent user FLOAT sam_tmDisplayModeReport;", &sam_tmDisplayModeReport);
_pShell->DeclareSymbol("persistent user CTString sam_strNetworkSettings;", &sam_strNetworkSettings);
_pShell->DeclareSymbol("user CTString sam_strModName;", &sam_strModName);
_pShell->DeclareSymbol("persistent INDEX sam_bShowAllLevels;", &sam_bShowAllLevels);
_pShell->DeclareSymbol("persistent INDEX sam_bMentalActivated;", &sam_bMentalActivated);
_pShell->DeclareSymbol("user CTString sam_strTechTestLevel;", &sam_strTechTestLevel);
_pShell->DeclareSymbol("user CTString sam_strTrainingLevel;", &sam_strTrainingLevel);
_pShell->DeclareSymbol("user void Quit(void);", &QuitGame);
_pShell->DeclareSymbol("persistent user INDEX sam_iVideoSetup;", &sam_iVideoSetup);
_pShell->DeclareSymbol("user void ApplyRenderingPreferences(void);", &ApplyRenderingPreferences);
_pShell->DeclareSymbol("user void ApplyVideoMode(void);", &ApplyVideoMode);
_pShell->DeclareSymbol("user void Benchmark(void);", &BenchMark);
_pShell->DeclareSymbol("user INDEX sam_bMenuSave;", &sam_bMenuSave);
_pShell->DeclareSymbol("user INDEX sam_bMenuLoad;", &sam_bMenuLoad);
_pShell->DeclareSymbol("user INDEX sam_bMenuControls;", &sam_bMenuControls);
_pShell->DeclareSymbol("user INDEX sam_bMenuHiScore;", &sam_bMenuHiScore);
_pShell->DeclareSymbol("user INDEX sam_bToggleConsole;",&sam_bToggleConsole);
_pShell->DeclareSymbol("INDEX sam_iStartCredits;", &sam_iStartCredits);
// [Cecil] Custom commands for option menus
_pShell->DeclareSymbol("void ApplyVideoOptions(void);", &ApplyVideoOptions);
_pShell->DeclareSymbol("void ApplyAudioOptions(void);", &ApplyAudioOptions);
// [Cecil] Load Game library as a module
GetPluginAPI()->LoadGameLib("Data\\SeriousSam.gms");
_pNetwork->md_strGameID = sam_strGameName;
_pGame->LCDInit();
if (sam_bFirstStarted) {
InfoMessage(LOCALIZE(
"SeriousSam is starting for the first time.\n"
"If you experience any problems, please consult\n"
"ReadMe file for troubleshooting information."));
}
// initialize sound library
snd_iFormat = Clamp(snd_iFormat, (INDEX)CSoundLibrary::SF_NONE, (INDEX)CSoundLibrary::SF_44100_16);
_pSound->SetFormat((enum CSoundLibrary::SoundFormat)snd_iFormat);
if (sam_bAutoAdjustAudio) {
_pShell->Execute("include \"" SCRIPTS_ADDONS_DIR "SFX-AutoAdjust.ini\"");
}
// execute script given on command line
if (cmd_strScript != "") {
CPrintF("Command line script: '%s'\n", cmd_strScript);
CTString strCmd;
strCmd.PrintF("include \"%s\"", cmd_strScript);
_pShell->Execute(strCmd);
}
// load logo textures
LoadAndForceTexture(_toLogoCT, _ptoLogoCT, CTFILENAME("Textures\\Logo\\LogoCT.tex"));
LoadAndForceTexture(_toLogoODI, _ptoLogoODI, CTFILENAME("Textures\\Logo\\GodGamesLogo.tex"));
LoadAndForceTexture(_toLogoEAX, _ptoLogoEAX, CTFILENAME("Textures\\Logo\\LogoEAX.tex"));
// !! NOTE !! Re-enable these to allow mod support.
LoadStringVar(CTString("Data\\Var\\Sam_Version.var"), sam_strVersion);
LoadStringVar(CTString("Data\\Var\\ModName.var"), sam_strModName);
CPrintF(LOCALIZE("Serious Sam version: %s\n"), sam_strVersion);
CPrintF(LOCALIZE("Active mod: %s\n"), sam_strModName);
InitializeMenus();
// if there is a mod
if (_fnmMod != "") {
// execute the mod startup script
_pShell->Execute(CTString("include \"Scripts\\Mod_startup.ini\";"));
}
// init gl settings module
InitGLSettings();
// init level-info subsystem
LoadLevelsList();
LoadDemosList();
// [Cecil] Load in-game plugins
GetPluginAPI()->LoadPlugins(k_EPluginFlagGame);
// apply application mode
ApplyVideoMode();
// set default mode reporting
if (sam_bFirstStarted) {
_iDisplayModeChangeFlag = 0;
sam_bFirstStarted = FALSE;
}
HideSplashScreen();
// [Cecil] If nothing has been started by the command line
if (!ExecuteCommandLine()) {
// Start playing demos
StartNextDemo();
}
return TRUE;
}
void End(void) {
_pGame->DisableLoadingHook();
// cleanup level-info subsystem
ClearLevelsList();
ClearDemosList();
// destroy the main window and its canvas
if (_pvpViewPort != NULL) {
_pGfx->DestroyWindowCanvas(_pvpViewPort);
_pvpViewPort = NULL;
_pdpNormal = NULL;
}
CloseMainWindow();
MainWindow_End();
DestroyMenus();
_pGame->End();
_pGame->LCDEnd();
// [Cecil] Clean up the core
ClassicsPatch_Shutdown();
// unlock the directory
DirectoryLockOff();
SE_EndEngine();
}
// Print display mode info if needed
void PrintDisplayModeInfo(void) {
// skip if timed out
if (_pTimer->GetRealTimeTick() > (_tmDisplayModeChanged + sam_tmDisplayModeReport)) {
return;
}
// cache some general vars
SLONG slDPWidth = _pdpMenu->GetWidth();
SLONG slDPHeight = _pdpMenu->GetHeight();
if (_pdpMenu->IsDualHead()) {
slDPWidth /= 2;
}
CDisplayMode dm;
dm.dm_pixSizeI = slDPWidth;
dm.dm_pixSizeJ = slDPHeight;
// determine proper text scale for statistics display
FLOAT fTextScale = (FLOAT)slDPHeight / 480.0f; // [Cecil] Use height instead of width
// get resolution
CTString strRes;
extern CTString _strPreferencesDescription;
strRes.PrintF("%dx%dx%s", slDPWidth, slDPHeight, _pGfx->gl_dmCurrentDisplayMode.DepthString());
if (dm.IsDualHead()) {
strRes += LOCALIZE(" DualMonitor");
}
if (dm.IsWideScreen()) {
strRes += LOCALIZE(" WideScreen");
}
if (_pGfx->gl_eCurrentAPI == GAT_OGL) {
strRes += " (OpenGL)";
}
#ifdef SE1_D3D
else if (_pGfx->gl_eCurrentAPI == GAT_D3D) {
strRes += " (Direct3D)";
}
#endif // SE1_D3D
CTString strDescr;
strDescr.PrintF("\n%s (%s)\n", _strPreferencesDescription, RenderingPreferencesDescription(sam_iVideoSetup));
strRes += strDescr;
// tell if application is started for the first time, or failed to set mode
if (_iDisplayModeChangeFlag == 0) {
strRes += LOCALIZE("Display mode set by default!");
} else if (_iDisplayModeChangeFlag == 2) {
strRes += LOCALIZE("Last mode set failed!");
}
// print it all
_pdpMenu->SetFont(_pfdDisplayFont);
_pdpMenu->SetTextScaling(fTextScale);
_pdpMenu->SetTextAspect(1.0f);
_pdpMenu->PutText(strRes, slDPWidth * 0.05f, slDPHeight * 0.85f, _pGame->LCDGetColor(C_GREEN | 255, "display mode"));
}
// Do the main game loop and render screen
void DoGame(void) {
// set flag if not in game
if (!GetGameAPI()->IsGameOn()) {
_gmRunningGameMode = GM_NONE;
}
if ((_gmRunningGameMode == GM_DEMO && _pNetwork->IsDemoPlayFinished())
|| (_gmRunningGameMode == GM_INTRO && _pNetwork->IsGameFinished())) {
_pGame->StopGame();
_gmRunningGameMode = GM_NONE;
// load next demo
StartNextDemo();
if (!_bInAutoPlayLoop) {
// start menu
StartMenus();
}
}
// do the main game loop
if (_gmRunningGameMode != GM_NONE) {
_pGame->GameMainLoop();
// if game is not started
} else {
// [Cecil] Update master server
IMasterServer::EnumUpdate();
// just handle broadcast messages
_pNetwork->GameInactive();
}
// [Cecil] Update current vote
IVotingSystem::UpdateVote();
if (sam_iStartCredits > 0) {
Credits_On(sam_iStartCredits);
sam_iStartCredits = 0;
}
if (sam_iStartCredits < 0) {
Credits_Off();
sam_iStartCredits = 0;
}
if (_gmRunningGameMode == GM_NONE) {
Credits_Off();
sam_iStartCredits = 0;
}
// redraw the view
if (!IsIconic(_hwndMain) && _pdpMenu != NULL && _pdpMenu->Lock()) {
// [Cecil] Set drawport that will be used for custom Steam screenshots
GetSteamAPI()->SetScreenshotHook(_pdpMenu);
// [Cecil] Keep rendering the game in the background while in menu
BOOL bRenderGame = (!bMenuActive || sam_bBackgroundGameRender);
if (_gmRunningGameMode != GM_NONE && bRenderGame) {
// [Cecil] Call API before redrawing the game
IHooks::OnPreDraw(_pdpMenu);
// [Cecil] Don't wait for server while playing demos (removes "Waiting for server to continue" message)
if (_pNetwork->IsPlayingDemo()) {
_pNetwork->ga_sesSessionState.ses_bWaitingForServer = FALSE;
}
#if _PATCHCONFIG_ENGINEPATCHES
// [Cecil] Don't listen to in-game sounds if rendering the game in the menu
_EnginePatches._bNoListening = bMenuActive;
#endif
// handle pretouching of textures and shadowmaps
_pdpMenu->Unlock();
_pGame->GameRedrawView(_pdpMenu, (GetGameAPI()->GetConState() != CS_OFF) ? 0 : GRV_SHOWEXTRAS);
_pdpMenu->Lock();
_pGame->ComputerRender(_pdpMenu);
// [Cecil] Call API after redrawing the game
IHooks::OnPostDraw(_pdpMenu);
_pdpMenu->Unlock();
CDrawPort dpScroller(_pdpMenu, TRUE);
dpScroller.Lock();
if (Credits_Render(&dpScroller) == 0) {
Credits_Off();
}
dpScroller.Unlock();
_pdpMenu->Lock();
} else {
_pdpMenu->Fill(_pGame->LCDGetColor(C_dGREEN | CT_OPAQUE, "bcg fill"));
}
// do menu
if (bMenuRendering) {
// clear z-buffer
_pdpMenu->FillZBuffer(ZBUF_BACK);
// remember if we should render menus next tick
bMenuRendering = DoMenu(_pdpMenu);
}
// print display mode info if needed
PrintDisplayModeInfo();
#if SE1_GAME == SS_REV
// [Cecil] Rev: Render Steam overlay
_pSteam->RenderCustomOverlay(_pdpMenu);
#endif
// render console
_pGame->ConsoleRender(_pdpMenu);
// [Cecil] Call API every render frame
IHooks::OnFrame(_pdpMenu);
// done with all
_pdpMenu->Unlock();
// show
_pvpViewPort->SwapBuffers();
// [Cecil] Reset drawport for screenshots
} else {
GetSteamAPI()->SetScreenshotHook(NULL);
}
}
void TeleportPlayer(int iPosition) {
CTString strCommand;
strCommand.PrintF("cht_iGoToMarker = %d;", iPosition);
_pShell->Execute(strCommand);
}
// [Cecil] Poll input & window events
static BOOL PollEvent(MSG &msg) {
#if _PATCHCONFIG_ENGINEPATCHES && _PATCHCONFIG_EXTEND_INPUT
if (CInputPatch::IsInitialized()) {
// Manual joystick update
CInputPatch::UpdateJoysticks();
// Process event for the first controller that sends it
const INDEX ctControllers = inp_aControllers.Count();
for (INDEX iCtrl = 0; iCtrl < ctControllers; iCtrl++) {
if (CInputPatch::SetupControllerEvent(iCtrl, msg)) {
return TRUE;
}
}
}
#endif // _PATCHCONFIG_EXTEND_INPUT
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
// If it's not a mouse message
if (msg.message < WM_MOUSEFIRST || msg.message > WM_MOUSELAST) {
// And not system key messages
if (!((msg.message == WM_KEYDOWN && msg.wParam == VK_F10) || msg.message == WM_SYSKEYDOWN)) {
// Dispatch it
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return TRUE;
}
return FALSE;
};
// [Cecil] Check any significant controller button
static BOOL AnyControllerButton(MSG &msg) {
#if _PATCHCONFIG_ENGINEPATCHES && _PATCHCONFIG_EXTEND_INPUT
if (CInputPatch::IsInitialized() && msg.message == WM_CTRLBUTTONDOWN) {
switch (msg.wParam) {
case SDL_CONTROLLER_BUTTON_A: case SDL_CONTROLLER_BUTTON_B:
case SDL_CONTROLLER_BUTTON_X: case SDL_CONTROLLER_BUTTON_Y:
case SDL_CONTROLLER_BUTTON_BACK: case SDL_CONTROLLER_BUTTON_GUIDE: case SDL_CONTROLLER_BUTTON_START:
return TRUE;
}
}
#endif // _PATCHCONFIG_EXTEND_INPUT
return FALSE;
};
// [Cecil] Check if the "Back" button is pressed
static BOOL IsBackPressed(MSG &msg) {
return (msg.message == WM_KEYDOWN && msg.wParam == VK_ESCAPE)
|| (msg.message == WM_CTRLBUTTONDOWN && msg.wParam == SDL_CONTROLLER_BUTTON_START);
};
CTextureObject _toStarField;
static FLOAT _fLastVolume = 1.0f;
void RenderStarfield(CDrawPort *pdp, FLOAT fStrength) {
CTextureData *ptd = (CTextureData *)_toStarField.GetData();
// skip if no texture