-
Notifications
You must be signed in to change notification settings - Fork 105
/
Game.cpp
2230 lines (1762 loc) · 65.2 KB
/
Game.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
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
#include "Rendering/GL/myGL.h"
#include <Rml/Backends/RmlUi_Backend.h>
#include <RmlUi/Core.h>
#include "Game.h"
#include "Camera.h"
#include "CameraHandler.h"
#include "ChatMessage.h"
#include "CommandMessage.h"
#include "ConsoleHistory.h"
#include "GameHelper.h"
#include "GameSetup.h"
#include "GlobalUnsynced.h"
#include "LoadScreen.h"
#include "SelectedUnitsHandler.h"
#include "WaitCommandsAI.h"
#include "WordCompletion.h"
#include "IVideoCapturing.h"
#include "InMapDraw.h"
#include "InMapDrawModel.h"
#include "SyncedActionExecutor.h"
#include "SyncedGameCommands.h"
#include "UnsyncedActionExecutor.h"
#include "UnsyncedGameCommands.h"
#include "Game/Players/Player.h"
#include "Game/Players/PlayerHandler.h"
#include "Game/UI/PlayerRoster.h"
#include "Game/UI/PlayerRosterDrawer.h"
#include "Game/UI/UnitTracker.h"
#include "ExternalAI/AILibraryManager.h"
#include "ExternalAI/EngineOutHandler.h"
#include "ExternalAI/SkirmishAIHandler.h"
#include "Rendering/WorldDrawer.h"
#include "Rendering/Env/IWater.h"
#include "Rendering/Env/WaterRendering.h"
#include "Rendering/Env/MapRendering.h"
#include "Rendering/Fonts/CFontTexture.h"
#include "Rendering/Fonts/glFont.h"
#include "Rendering/CommandDrawer.h"
#include "Rendering/LineDrawer.h"
#include "Rendering/GlobalRendering.h"
#include "Rendering/DebugDrawerAI.h"
#include "Rendering/HUDDrawer.h"
#include "Rendering/IconHandler.h"
#include "Rendering/ModelsDataUploader.h"
#include "Rendering/ShadowHandler.h"
#include "Rendering/TeamHighlight.h"
#include "Rendering/Units/UnitDrawer.h"
#include "Rendering/UniformConstants.h"
#include "Rendering/Map/InfoTexture/IInfoTextureHandler.h"
#include "Rendering/Textures/NamedTextures.h"
#include "Lua/LuaGaia.h"
#include "Lua/LuaHandle.h"
#include "Lua/LuaInputReceiver.h"
#include "Lua/LuaMenu.h"
#include "Lua/LuaRules.h"
#include "Lua/LuaOpenGL.h"
#include "Lua/LuaParser.h"
#include "Lua/LuaSyncedRead.h"
#include "Lua/LuaUI.h"
#include "Map/MapDamage.h"
#include "Map/MapInfo.h"
#include "Map/ReadMap.h"
#include "Net/GameServer.h"
#include "Net/Protocol/NetProtocol.h"
#include "Sim/Ecs/Registry.h"
#include "Sim/Ecs/Helper.h"
#include "Sim/Features/FeatureDef.h"
#include "Sim/Features/FeatureDefHandler.h"
#include "Sim/Features/FeatureHandler.h"
#include "Sim/Misc/CategoryHandler.h"
#include "Sim/Misc/DamageArrayHandler.h"
#include "Sim/Misc/YardmapStatusEffectsMap.h"
#include "Sim/Misc/GeometricObjects.h"
#include "Sim/Misc/GroundBlockingObjectMap.h"
#include "Sim/Misc/BuildingMaskMap.h"
#include "Sim/Misc/LosHandler.h"
#include "Sim/Misc/ModInfo.h"
#include "Sim/Misc/InterceptHandler.h"
#include "Sim/Misc/QuadField.h"
#include "Sim/Misc/SideParser.h"
#include "Sim/Misc/SmoothHeightMesh.h"
#include "Sim/Misc/TeamHandler.h"
#include "Sim/Misc/Wind.h"
#include "Sim/Misc/ResourceHandler.h"
#include "Sim/MoveTypes/MoveDefHandler.h"
#include "Sim/MoveTypes/MoveTypeFactory.h"
#include "Sim/Path/IPathManager.h"
#include "Sim/Projectiles/ExplosionGenerator.h"
#include "Sim/Projectiles/Projectile.h"
#include "Sim/Projectiles/ProjectileHandler.h"
#include "Sim/Units/CommandAI/CommandAI.h"
#include "Sim/Units/Scripts/UnitScriptFactory.h"
#include "Sim/Units/Scripts/UnitScriptEngine.h"
#include "Sim/Units/UnitHandler.h"
#include "Sim/Units/UnitDefHandler.h"
#include "Sim/Weapons/WeaponDefHandler.h"
#include "Sim/Weapons/WeaponLoader.h"
#include "UI/CommandColors.h"
#include "UI/EndGameBox.h"
#include "UI/GameSetupDrawer.h"
#include "UI/GuiHandler.h"
#include "UI/InfoConsole.h"
#include "UI/KeyBindings.h"
#include "UI/MiniMap.h"
#include "UI/MouseHandler.h"
#include "UI/ResourceBar.h"
#include "UI/SelectionKeyHandler.h"
#include "UI/TooltipConsole.h"
#include "UI/ProfileDrawer.h"
#include "UI/Groups/GroupHandler.h"
#include "System/Config/ConfigHandler.h"
#include "System/creg/SerializeLuaState.h"
#include "System/EventHandler.h"
#include "System/Exceptions.h"
#include "System/Sync/FPUCheck.h"
#include "System/SafeUtil.h"
#include "System/SpringExitCode.h"
#include "System/SpringMath.h"
#include "System/FileSystem/FileSystem.h"
#include "System/LoadSave/LoadSaveHandler.h"
#include "System/LoadSave/DemoRecorder.h"
#include "System/Log/ILog.h"
#include "System/Platform/Misc.h"
#include "System/Platform/Watchdog.h"
#include "System/Sound/ISound.h"
#include "System/Sound/ISoundChannels.h"
#include "System/Sync/DumpState.h"
#include "System/TimeProfiler.h"
#include "System/LoadLock.h"
#include "System/Misc/TracyDefs.h"
#undef CreateDirectory
CONFIG(bool, GameEndOnConnectionLoss).defaultValue(true);
// CONFIG(bool, LuaCollectGarbageOnSimFrame).defaultValue(true);
CONFIG(bool, ShowFPS).defaultValue(false).description("Displays current framerate.");
CONFIG(bool, ShowClock).defaultValue(true).headlessValue(false).description("Displays a clock on the top-right corner of the screen showing the elapsed time of the current game.");
CONFIG(bool, ShowSpeed).defaultValue(false).description("Displays current game speed.");
CONFIG(int, ShowPlayerInfo).defaultValue(1).headlessValue(0);
CONFIG(float, GuiOpacity).defaultValue(0.8f).minimumValue(0.0f).maximumValue(1.0f).description("Sets the opacity of the built-in Spring UI. Generally has no effect on LuaUI widgets. Can be set in-game using shift+, to decrease and shift+. to increase.");
CONFIG(std::string, InputTextGeo).defaultValue("");
CONFIG(int, SmoothTimeOffset).defaultValue(0).headlessValue(0).description("Enables frametimeoffset smoothing, 0 = off (old version), -1 = forced 0.5, 1-20 smooth, recommended = 2-3");
CGame* game = nullptr;
CR_BIND(CGame, (std::string(""), std::string(""), nullptr))
CR_REG_METADATA(CGame, (
CR_MEMBER(lastSimFrame),
CR_IGNORED(lastNumQueuedSimFrames),
CR_IGNORED(numDrawFrames),
CR_IGNORED(frameStartTime),
CR_IGNORED(lastSimFrameTime),
CR_IGNORED(lastDrawFrameTime),
CR_IGNORED(lastFrameTime),
CR_IGNORED(lastReadNetTime),
CR_IGNORED(lastNetPacketProcessTime),
CR_IGNORED(lastReceivedNetPacketTime),
CR_IGNORED(lastSimFrameNetPacketTime),
CR_IGNORED(lastUnsyncedUpdateTime),
CR_IGNORED(skipLastDrawTime),
CR_IGNORED(lastActionList), //IGNORED?
CR_IGNORED(updateDeltaSeconds),
CR_MEMBER(totalGameTime),
CR_IGNORED(chatSound),
CR_MEMBER(hideInterface),
// FIXME: atomic type deduction
CR_IGNORED(loadDone),
CR_IGNORED(gameOver),
CR_IGNORED(gameDrawMode),
CR_MEMBER(showFPS),
CR_MEMBER(showClock),
CR_MEMBER(showSpeed),
CR_IGNORED(playerTraffic),
CR_MEMBER(noSpectatorChat),
CR_MEMBER(gameID),
CR_IGNORED(skipping),
CR_MEMBER(playing),
CR_IGNORED(paused),
CR_IGNORED(msgProcTimeLeft),
CR_IGNORED(consumeSpeedMult),
/*
CR_IGNORED(skipStartFrame),
CR_IGNORED(skipEndFrame),
CR_IGNORED(skipTotalFrames),
CR_IGNORED(skipSeconds),
CR_IGNORED(skipSoundmute),
CR_IGNORED(skipOldSpeed),
CR_IGNORED(skipOldUserSpeed),
*/
CR_MEMBER(speedControl),
CR_MEMBER(luaGCControl),
CR_IGNORED(jobDispatcher),
CR_IGNORED(curKeyCodeChain),
CR_IGNORED(curScanCodeChain),
CR_IGNORED(worldDrawer),
CR_IGNORED(saveFileHandler),
// Post Load
CR_POSTLOAD(PostLoad)
))
CGame::CGame(const std::string& mapFileName, const std::string& modFileName, ILoadSaveHandler* saveFile)
: frameStartTime(spring_gettime())
, lastSimFrameTime(spring_gettime())
, lastDrawFrameTime(spring_gettime())
, lastFrameTime(spring_gettime())
, lastReadNetTime(spring_gettime())
, lastNetPacketProcessTime(spring_gettime())
, lastReceivedNetPacketTime(spring_gettime())
, lastSimFrameNetPacketTime(spring_gettime())
, lastUnsyncedUpdateTime(spring_gettime())
, skipLastDrawTime(spring_gettime())
, saveFileHandler(saveFile)
{
game = this;
memset(gameID, 0, sizeof(gameID));
// set "Headless" in config overlay (not persisted)
configHandler->Set("Headless", (SpringVersion::IsHeadless()) ? 1 : 0, true);
showFPS = configHandler->GetBool("ShowFPS");
showClock = configHandler->GetBool("ShowClock");
showSpeed = configHandler->GetBool("ShowSpeed");
speedControl = configHandler->GetInt("SpeedControl");
playerRoster.SetSortTypeByCode((PlayerRoster::SortType)configHandler->GetInt("ShowPlayerInfo"));
CInputReceiver::guiAlpha = configHandler->GetFloat("GuiOpacity");
ParseInputTextGeometry("default");
ParseInputTextGeometry(configHandler->GetString("InputTextGeo"));
// clear left-over receivers in case we reloaded
gameCommandConsole.ResetState();
envResHandler.ResetState();
modInfo.Init(modFileName);
// needed for LuaIntro (pushes LuaConstGame)
assert(mapInfo == nullptr);
mapInfo = new CMapInfo(mapFileName, gameSetup->mapName);
if (!sideParser.Load())
throw content_error(sideParser.GetErrorLog());
// after this, other components are able to register chat action-executors
SyncedGameCommands::CreateInstance();
UnsyncedGameCommands::CreateInstance();
// note: makes no sense to create this unless we have AI's
// (events will just go into the void otherwise) but it is
// unconditionally deref'ed in too many places
CEngineOutHandler::Create();
CResourceHandler::CreateInstance();
CCategoryHandler::CreateInstance();
}
CGame::~CGame()
{
ENTER_SYNCED_CODE();
LOG("[Game::%s][1]", __func__);
RmlGui::Shutdown();
helper->Kill();
KillLua(true);
KillMisc();
KillRendering();
KillInterface();
KillSimulation();
LOG("[Game::%s][2]", __func__);
spring::SafeDelete(saveFileHandler); // ILoadSaveHandler, depends on vfsHandler via ~IArchive
LOG("[Game::%s][3]", __func__);
CCategoryHandler::RemoveInstance();
CResourceHandler::FreeInstance();
LEAVE_SYNCED_CODE();
}
void CGame::AddTimedJobs()
{
RECOIL_DETAILED_TRACY_ZONE;
{
JobDispatcher::Job j;
j.f = [this]() -> bool {
const float simFrameDeltaTime = (spring_gettime() - lastSimFrameNetPacketTime).toMilliSecsf();
const float gcForcedDeltaTime = (5.0f * 1000.0f) / (GAME_SPEED * gs->speedFactor);
// SimFrame handles gc when not paused, this all other cases
// do not check the global synced state, never true in demos
if (luaGCControl == 1 || simFrameDeltaTime > gcForcedDeltaTime)
eventHandler.CollectGarbage(false);
CInputReceiver::CollectGarbage();
return true;
};
j.freq = GAME_SPEED;
j.time = (1000.0f / j.freq) * (1 - j.startDirect);
j.name = "EventHandler::CollectGarbage";
jobDispatcher.AddTimedJob(j);
}
{
JobDispatcher::Job j;
j.f = []() -> bool {
CTimeProfiler::GetInstance().Update();
return true;
};
j.freq = 1.0f;
j.time = (1000.0f / j.freq) * (1 - j.startDirect);
j.name = "Profiler::Update";
jobDispatcher.AddTimedJob(j);
}
}
void CGame::Load(const std::string& mapFileName)
{
// NOTE:
// this is needed for LuaHandle::CallOut*UpdateCallIn
// the main-thread is NOT the same as the load-thread
// when LoadingMT=1 (!!!)
Threading::SetGameLoadThread();
Watchdog::RegisterThread(WDT_LOAD);
ZoneScoped;
auto& globalQuit = gu->globalQuit;
bool forcedQuit = false;
LuaParser baseDefsParser("gamedata/defs.lua", SPRING_VFS_MOD_BASE, SPRING_VFS_ZIP, {true}, {false});
LuaParser nullDefsParser("return {UnitDefs = {}, FeatureDefs = {}, WeaponDefs = {}, ArmorDefs = {}, MoveDefs = {}}", SPRING_VFS_ZIP, 0, {true}, {true});
LuaParser* defsParser = &baseDefsParser;
try {
LOG("[Game::%s][1] globalQuit=%d threaded=%d", __func__, globalQuit.load(), !Threading::IsMainThread());
LoadMap(mapFileName);
Watchdog::ClearTimer(WDT_LOAD);
LoadDefs(defsParser);
Watchdog::ClearTimer(WDT_LOAD);
} catch (const content_error& e) {
LOG_L(L_ERROR, "[Game::%s][1] forced quit with exception \"%s\"", __func__, e.what());
defsParser = &nullDefsParser;
defsParser->Execute();
// we can not (yet) do a clean early exit here because the dtor assumes
// all loading stages proceeded normally; just force automatic shutdown
forcedQuit = true;
}
try {
LOG("[Game::%s][2] globalQuit=%d forcedQuit=%d", __func__, globalQuit.load(), forcedQuit);
PreLoadSimulation(defsParser);
Watchdog::ClearTimer(WDT_LOAD);
PreLoadRendering();
Watchdog::ClearTimer(WDT_LOAD);
} catch (const content_error& e) {
LOG_L(L_ERROR, "[Game::%s][2] forced quit with exception \"%s\"", __func__, e.what());
forcedQuit = true;
}
try {
LOG("[Game::%s][3] globalQuit=%d forcedQuit=%d", __func__, globalQuit.load(), forcedQuit);
PostLoadSimulation(defsParser);
Watchdog::ClearTimer(WDT_LOAD);
PostLoadRendering();
Watchdog::ClearTimer(WDT_LOAD);
} catch (const content_error& e) {
LOG_L(L_ERROR, "[Game::%s][3] forced quit with exception \"%s\"", __func__, e.what());
forcedQuit = true;
}
if (!forcedQuit) {
try {
LOG("[Game::%s][4] globalQuit=%d forcedQuit=%d", __func__, globalQuit.load(), forcedQuit);
LoadInterface();
Watchdog::ClearTimer(WDT_LOAD);
} catch (const content_error& e) {
LOG_L(L_ERROR, "[Game::%s][4] forced quit with exception \"%s\"", __func__, e.what());
forcedQuit = true;
}
}
if (!forcedQuit) {
try {
LOG("[Game::%s][5] globalQuit=%d forcedQuit=%d", __func__, globalQuit.load(), forcedQuit);
LoadFinalize();
Watchdog::ClearTimer(WDT_LOAD);
} catch (const content_error& e) {
LOG_L(L_ERROR, "[Game::%s][5] forced quit with exception \"%s\"", __func__, e.what());
forcedQuit = true;
}
}
if (!forcedQuit) {
try {
LOG("[Game::%s][6] globalQuit=%d forcedQuit=%d", __func__, globalQuit.load(), forcedQuit);
LoadLua(saveFileHandler != nullptr, false);
Watchdog::ClearTimer(WDT_LOAD);
} catch (const content_error& e) {
LOG_L(L_ERROR, "[Game::%s][6] forced quit with exception \"%s\"", __func__, e.what());
forcedQuit = true;
}
}
try {
LOG("[Game::%s][7] globalQuit=%d forcedQuit=%d", __func__, globalQuit.load(), forcedQuit);
if (!globalQuit && saveFileHandler != nullptr) {
loadscreen->SetLoadMessage("Loading Saved Game");
{
auto lock = CLoadLock::GetUniqueLock();
saveFileHandler->LoadGame();
Watchdog::ClearTimer(WDT_LOAD);
}
LoadLua(false, true);
Watchdog::ClearTimer(WDT_LOAD);
} else {
ENTER_SYNCED_CODE();
{
auto lock = CLoadLock::GetUniqueLock();
eventHandler.GamePreload();
Watchdog::ClearTimer(WDT_LOAD);
eventHandler.CollectGarbage(true);
Watchdog::ClearTimer(WDT_LOAD);
}
LEAVE_SYNCED_CODE();
}
// Update height bounds and pathing after pregame or a saved game load.
{
ENTER_SYNCED_CODE();
//needed in case pre-game terraform changed the map
readMap->UpdateHeightBounds();
Watchdog::ClearTimer(WDT_LOAD);
pathManager->PostFinalizeRefresh();
Watchdog::ClearTimer(WDT_LOAD);
LEAVE_SYNCED_CODE();
}
{
char msgBuf[512];
SNPRINTF(msgBuf, sizeof(msgBuf), "[Game::%s][lua{Rules,Gaia}={%p,%p}][locale=\"%s\"]", __func__, luaRules, luaGaia, setlocale(LC_ALL, nullptr));
CLIENT_NETLOG(gu->myPlayerNum, LOG_LEVEL_INFO, msgBuf);
}
} catch (const content_error& e) {
LOG_L(L_ERROR, "[Game::%s][7] forced quit with exception \"%s\"", __func__, e.what());
forcedQuit = true;
}
if (!forcedQuit) {
try {
LOG("[Game::%s][8] globalQuit=%d forcedQuit=%d", __func__, globalQuit.load(), forcedQuit);
LoadSkirmishAIs();
Watchdog::ClearTimer(WDT_LOAD);
} catch (const content_error& e) {
LOG_L(L_ERROR, "[Game::%s][8] forced quit with exception \"%s\"", __func__, e.what());
forcedQuit = true;
}
}
Watchdog::DeregisterThread(WDT_LOAD);
AddTimedJobs();
if (forcedQuit)
spring::exitCode = spring::EXIT_CODE_NOLOAD;
loadDone = true;
globalQuit = globalQuit | forcedQuit;
}
void CGame::LoadMap(const std::string& mapFileName)
{
ENTER_SYNCED_CODE();
{
SCOPED_ONCE_TIMER("Game::LoadMap");
loadscreen->SetLoadMessage("Parsing Map Information");
waterRendering->Init();
mapRendering->Init();
// simulation components
helper->Init();
readMap = CReadMap::LoadMap(mapFileName);
// half size; building positions are snapped to multiples of BUILD_SQUARE_SIZE
buildingMaskMap.Init(mapDims.hmapx * mapDims.hmapy);
groundBlockingObjectMap.Init(mapDims.mapSquares);
yardmapStatusEffectsMap.InitNewYardmapStatusEffectsMap();
}
LEAVE_SYNCED_CODE();
}
void CGame::LoadDefs(LuaParser* defsParser)
{
ENTER_SYNCED_CODE();
{
SCOPED_ONCE_TIMER("Game::LoadDefs (GameData)");
loadscreen->SetLoadMessage("Loading GameData Definitions");
defsParser->SetupLua(true, true);
// customize the defs environment; LuaParser has no access to LuaSyncedRead
#define LSR_ADDFUNC(f) defsParser->AddFunc(#f, LuaSyncedRead::f)
defsParser->GetTable("Spring");
LSR_ADDFUNC(GetModOptions);
LSR_ADDFUNC(GetModOption);
LSR_ADDFUNC(GetMapOptions);
LSR_ADDFUNC(GetMapOption);
LSR_ADDFUNC(GetTeamLuaAI);
LSR_ADDFUNC(GetTeamList);
LSR_ADDFUNC(GetGaiaTeamID);
LSR_ADDFUNC(GetPlayerList);
LSR_ADDFUNC(GetAllyTeamList);
LSR_ADDFUNC(GetTeamInfo);
LSR_ADDFUNC(GetAllyTeamInfo);
LSR_ADDFUNC(GetAIInfo);
LSR_ADDFUNC(GetTeamAllyTeamID);
LSR_ADDFUNC(AreTeamsAllied);
LSR_ADDFUNC(ArePlayersAllied);
LSR_ADDFUNC(GetSideData);
defsParser->EndTable();
#undef LSR_ADDFUNC
// run the parser
if (!defsParser->Execute())
throw content_error("Defs-Parser: " + defsParser->GetErrorLog());
const LuaTable& root = defsParser->GetRoot();
if (!root.IsValid())
throw content_error("Error loading gamedata definitions");
// bail now if any of these tables are invalid
// makes searching for errors that much easier
if (!root.SubTable("UnitDefs").IsValid())
throw content_error("Error loading UnitDefs");
if (!root.SubTable("FeatureDefs").IsValid())
throw content_error("Error loading FeatureDefs");
if (!root.SubTable("WeaponDefs").IsValid())
throw content_error("Error loading WeaponDefs");
if (!root.SubTable("ArmorDefs").IsValid())
throw content_error("Error loading ArmorDefs");
if (!root.SubTable("MoveDefs").IsValid())
throw content_error("Error loading MoveDefs");
}
{
loadscreen->SetLoadMessage("Loading Radar Icons");
auto lock = CLoadLock::GetUniqueLock();
icon::iconHandler.Init();
}
{
SCOPED_ONCE_TIMER("Game::LoadDefs (Sound)");
loadscreen->SetLoadMessage("Loading Sound Definitions");
LuaParser soundDefsParser("gamedata/sounds.lua", SPRING_VFS_MOD_BASE, SPRING_VFS_MOD_BASE);
soundDefsParser.GetTable("Spring");
soundDefsParser.AddFunc("GetModOptions", LuaSyncedRead::GetModOptions);
soundDefsParser.AddFunc("GetMapOptions", LuaSyncedRead::GetMapOptions);
soundDefsParser.EndTable();
sound->LoadSoundDefs(&soundDefsParser);
chatSound = sound->GetDefSoundId("IncomingChat");
}
LEAVE_SYNCED_CODE();
}
void CGame::PreLoadSimulation(LuaParser* defsParser)
{
ZoneScoped;
ENTER_SYNCED_CODE();
loadscreen->SetLoadMessage("Creating Smooth Height Mesh");
smoothGround.Init(int2(mapDims.mapx, mapDims.mapy), modInfo.smoothMeshResDivider, modInfo.smoothMeshSmoothRadius);
loadscreen->SetLoadMessage("Creating QuadField & CEGs");
moveDefHandler.Init(defsParser);
quadField.Init(int2(mapDims.mapx, mapDims.mapy), modInfo.quadFieldQuadSizeInElmos);
damageArrayHandler.Init(defsParser);
explGenHandler.Init();
}
void CGame::PostLoadSimulation(LuaParser* defsParser)
{
ZoneScoped;
CommonDefHandler::InitStatic();
{
SCOPED_ONCE_TIMER("Game::PostLoadSim (WeaponDefs)");
loadscreen->SetLoadMessage("Loading Weapon Definitions");
weaponDefHandler->Init(defsParser);
}
{
SCOPED_ONCE_TIMER("Game::PostLoadSim (UnitDefs)");
loadscreen->SetLoadMessage("Loading Unit Definitions");
unitDefHandler->Init(defsParser);
}
{
SCOPED_ONCE_TIMER("Game::PostLoadSim (FeatureDefs)");
loadscreen->SetLoadMessage("Loading Feature Definitions");
featureDefHandler->Init(defsParser);
}
CUnit::InitStatic();
CCommandAI::InitCommandDescriptionCache();
CUnitScriptFactory::InitStatic();
CUnitScriptEngine::InitStatic();
MoveTypeFactory::InitStatic();
CWeaponLoader::InitStatic();
unitHandler.Init();
featureHandler.Init();
projectileHandler.Init();
CLosHandler::InitStatic();
readMap->InitHeightMapDigestVectors(losHandler->los.size);
// pre-load the PFS, gets finalized after Lua
//
// features loaded from the map (and any terrain changes
// made by Lua while loading) would otherwise generate a
// queue of pending PFS updates, which should be consumed
// to avoid blocking regular updates from being processed
// however, doing so was impossible without stalling the
// loading thread for *minutes* in the worst-case scenario
//
// the only disadvantage is that LuaPathFinder can not be
// used during Lua initialization anymore (not a concern)
//
// NOTE:
// the cache written to disk will reflect changes made by
// Lua which can vary each run with {mod,map}options, etc
// --> need a way to let Lua flush it or re-calculate map
// checksum (over heightmap + blockmap, not raw archive)
mapDamage = IMapDamage::InitMapDamage();
pathManager = IPathManager::GetInstance(modInfo.pathFinderSystem);
moveDefHandler.PostSimInit();
// load map-specific features
loadscreen->SetLoadMessage("Initializing Map Features");
featureDefHandler->LoadFeatureDefsFromMap();
if (saveFileHandler == nullptr)
featureHandler.LoadFeaturesFromMap();
// must be called after features are all loaded
unitDefHandler->SanitizeUnitDefs();
envResHandler.LoadTidal(mapInfo->map.tidalStrength);
envResHandler.LoadWind(mapInfo->atmosphere.minWind, mapInfo->atmosphere.maxWind);
inMapDrawerModel = new CInMapDrawModel();
inMapDrawer = new CInMapDraw();
LEAVE_SYNCED_CODE();
}
void CGame::PreLoadRendering()
{
ZoneScoped;
auto lock = CLoadLock::GetUniqueLock();
geometricObjects = new CGeometricObjects();
// load components that need to exist before PostLoadSimulation
matrixUploader.Init();
modelsUniformsUploader.Init();
worldDrawer.InitPre();
}
void CGame::PostLoadRendering() {
ZoneScoped;
worldDrawer.InitPost();
}
void CGame::LoadInterface()
{
ZoneScoped;
auto lock = CLoadLock::GetUniqueLock();
camHandler->Init();
mouse->ReloadCursors();
selectedUnitsHandler.Init(playerHandler.ActivePlayers());
// NB: these are also added to word-completion
syncedGameCommands->AddDefaultActionExecutors();
unsyncedGameCommands->AddDefaultActionExecutors();
// interface components
cmdColors.LoadConfigFromFile("cmdcolors.txt");
keyBindings.Init();
keyBindings.LoadDefaults();
keyBindings.Load();
{
SCOPED_ONCE_TIMER("Game::LoadInterface (Console)");
gameConsoleHistory.Init();
gameTextInput.ClearInput();
wordCompletion.Init();
for (int pp = 0; pp < playerHandler.ActivePlayers(); pp++) {
wordCompletion.AddWordRaw(playerHandler.Player(pp)->name, false, false, false);
}
// add the Skirmish AIs instance names to word completion (eg for chatting)
for (const auto& ai: skirmishAIHandler.GetAllSkirmishAIs()) {
wordCompletion.AddWordRaw(ai.second->name + " ", false, false, false);
}
// add the available Skirmish AI libraries to word completion, for /aicontrol
for (const auto& aiLib: aiLibManager->GetSkirmishAIKeys()) {
wordCompletion.AddWordRaw(aiLib.GetShortName() + " " + aiLib.GetVersion() + " ", false, false, false);
}
// add the available Lua AI implementations to word completion, for /aicontrol
for (const std::string& sn: skirmishAIHandler.GetLuaAIImplShortNames()) {
wordCompletion.AddWordRaw(sn + " ", false, false, false);
}
// register {Unit,Feature}Def names
for (const auto& pair: unitDefHandler->GetUnitDefIDs()) {
wordCompletion.AddWordRaw(pair.first + " ", false, true, false);
}
for (const auto& pair: featureDefHandler->GetFeatureDefIDs()) {
wordCompletion.AddWordRaw(pair.first + " ", false, true, false);
}
// register /command's
for (const auto& pair: syncedGameCommands->GetActionExecutors()) {
wordCompletion.AddWordRaw("/" + pair.first + " ", true, false, false);
}
for (const auto& pair: unsyncedGameCommands->GetActionExecutors()) {
wordCompletion.AddWordRaw("/" + pair.first + " ", true, false, false);
}
// legacy commands without executors
for (const auto& pair: gameCommandConsole.GetCommandMap()) {
wordCompletion.AddWordRaw("/" + pair.first + " ", true, false, false);
}
wordCompletion.Sort();
wordCompletion.Filter();
}
tooltip = new CTooltipConsole();
guihandler = new CGuiHandler();
minimap = new CMiniMap();
resourceBar = new CResourceBar();
selectionKeys.Init();
uiGroupHandlers.clear();
uiGroupHandlers.reserve(teamHandler.ActiveTeams());
for (int t = 0; t < teamHandler.ActiveTeams(); ++t) {
uiGroupHandlers.emplace_back(t);
}
if (saveFileHandler == nullptr) {
// note: disable is needed in case user reloads before StartPlaying
GameSetupDrawer::Disable();
GameSetupDrawer::Enable();
}
RmlGui::Initialize();
}
void CGame::LoadLua(bool dryRun, bool onlyUnsynced)
{
ZoneScoped;
assert(!(dryRun && onlyUnsynced));
// Lua components
ENTER_SYNCED_CODE();
CLuaHandle::SetDevMode(gameSetup->luaDevMode);
LOG("[Game::%s] Lua developer mode %sabled", __func__, (CLuaHandle::GetDevMode()? "en": "dis"));
const std::string prefix = (dryRun ? "Synced " : (onlyUnsynced ? "Unsynced " : ""));
const std::string names[] = {"LuaRules", "LuaGaia"};
CSplitLuaHandle* handles[] = {luaRules, luaGaia};
decltype(&CLuaRules::LoadFreeHandler) loaders[] = {CLuaRules::LoadFreeHandler, CLuaGaia::LoadFreeHandler};
for (int i = 0; i < 2; i++) {
loadscreen->SetLoadMessage("Loading " + prefix + names[i]);
if (onlyUnsynced && handles[i] != nullptr) {
handles[i]->InitUnsynced();
} else {
loaders[i](dryRun);
}
}
LEAVE_SYNCED_CODE();
if (!dryRun) {
loadscreen->SetLoadMessage("Loading LuaUI");
auto lock = CLoadLock::GetUniqueLock();
CLuaUI::LoadFreeHandler();
}
}
void CGame::LoadSkirmishAIs()
{
if (gameSetup->hostDemo)
return;
// happens if LoadInterface was skipped or interrupted on forcedQuit
// the AI callback code expects this to be non-empty on construction
if (uiGroupHandlers.empty())
return;
// create Skirmish AI's if required
const std::vector<uint8_t>& localAIs = skirmishAIHandler.GetSkirmishAIsByPlayer(gu->myPlayerNum);
if (localAIs.empty() && !IsSavedGame())
return;
SCOPED_ONCE_TIMER("Game::LoadSkirmishAIs");
loadscreen->SetLoadMessage("Loading Skirmish AIs");
for (uint8_t localAI: localAIs)
skirmishAIHandler.CreateLocalSkirmishAI(localAI, IsSavedGame());
if (IsSavedGame()) {
saveFileHandler->LoadAIData();
for (uint8_t localAI: localAIs)
skirmishAIHandler.PostLoadSkirmishAI(localAI);
}
}
void CGame::LoadFinalize()
{
ZoneScoped;
{
loadscreen->SetLoadMessage("[" + std::string(__func__) + "] finalizing PFS");
ENTER_SYNCED_CODE();
const std::uint64_t dt = pathManager->Finalize();
const std::uint32_t cs = pathManager->GetPathCheckSum();
LEAVE_SYNCED_CODE();
loadscreen->SetLoadMessage(
"[" + std::string(__func__) + "] finalized PFS " +
"(" + IntToString(dt, "%ld") + "ms, checksum " + IntToString(cs, "%08x") + ")"
);
}
lastReadNetTime = spring_gettime();
lastSimFrameTime = lastReadNetTime;
lastDrawFrameTime = lastReadNetTime;
updateDeltaSeconds = 0.0f;
}
void CGame::PostLoad()
{
RECOIL_DETAILED_TRACY_ZONE;
GameSetupDrawer::Disable();
Sim::systemUtils.NotifyPostLoad();
if (gameServer != nullptr) {
gameServer->PostLoad(gs->frameNum);
}
}
void CGame::KillLua(bool dtor)
{
RECOIL_DETAILED_TRACY_ZONE;
// belongs here; destructs LuaIntro (which might access sound, etc)
// if LoadingMT=1, a reload-request might be seen by SpringApp::Run
// while the loading thread is still alive so this must go first
assert((!dtor) || (loadscreen == nullptr));
LOG("[Game::%s][0] dtor=%d loadscreen=%p", __func__, dtor, loadscreen);
CLoadScreen::DeleteInstance();
// kill LuaUI here, various handler pointers are invalid in ~GuiHandler
LOG("[Game::%s][1] dtor=%d luaUI=%p", __func__, dtor, luaUI);
CLuaUI::FreeHandler();
ENTER_SYNCED_CODE();
LOG("[Game::%s][2] dtor=%d luaGaia=%p", __func__, dtor, luaGaia);
CLuaGaia::FreeHandler();
LOG("[Game::%s][3] dtor=%d luaRules=%p", __func__, dtor, luaRules);
CLuaRules::FreeHandler();
CSplitLuaHandle::ClearGameParams();
LEAVE_SYNCED_CODE();
LOG("[Game::%s][4] dtor=%d", __func__, dtor);
LuaOpenGL::Free();
LOG("[Game::%s][5] dtor=%d", __func__, dtor);
creg::UnregisterAllCFunctions();
}
void CGame::KillMisc()
{
RECOIL_DETAILED_TRACY_ZONE;
LOG("[Game::%s][1]", __func__);
CEndGameBox::Destroy();
IVideoCapturing::FreeInstance();
LOG("[Game::%s][2]", __func__);
// delete this first since AI's might call back into sim-components in their dtors
// this means the simulation *should not* assume the EOH still exists on game exit
CEngineOutHandler::Destroy();
LOG("[Game::%s][3]", __func__);
// TODO move these to the end of this dtor, once all action-executors are registered by their respective engine sub-parts
UnsyncedGameCommands::DestroyInstance(gu->globalReload);
SyncedGameCommands::DestroyInstance(gu->globalReload);
}
void CGame::KillRendering()
{
RECOIL_DETAILED_TRACY_ZONE;
LOG("[Game::%s][1]", __func__);
icon::iconHandler.Kill();
spring::SafeDelete(geometricObjects);
worldDrawer.Kill();
matrixUploader.Kill();
modelsUniformsUploader.Kill();
}
void CGame::KillInterface()
{
RECOIL_DETAILED_TRACY_ZONE;
LOG("[Game::%s][1]", __func__);
ProfileDrawer::SetEnabled(false);
camHandler->Kill();
spring::SafeDelete(guihandler);
spring::SafeDelete(minimap);
spring::SafeDelete(resourceBar);
spring::SafeDelete(tooltip); // CTooltipConsole*