forked from TheSuperHackers/GeneralsGameCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRecorder.cpp
More file actions
1808 lines (1614 loc) · 51.5 KB
/
Recorder.cpp
File metadata and controls
1808 lines (1614 loc) · 51.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
** Command & Conquer Generals Zero Hour(tm)
** Copyright 2025 Electronic Arts Inc.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** 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, see <http://www.gnu.org/licenses/>.
*/
////////////////////////////////////////////////////////////////////////////////
// //
// (c) 2001-2003 Electronic Arts Inc. //
// //
////////////////////////////////////////////////////////////////////////////////
#include "PreRTS.h" // This must go first in EVERY cpp file in the GameEngine
#include "Common/Recorder.h"
#include "Common/file.h"
#include "Common/FileSystem.h"
#include "Common/PlayerList.h"
#include "Common/Player.h"
#include "Common/GlobalData.h"
#include "Common/GameEngine.h"
#include "GameClient/ClientInstance.h"
#include "GameClient/GameWindow.h"
#include "GameClient/GameWindowManager.h"
#include "GameClient/InGameUI.h"
#include "GameClient/Shell.h"
#include "GameClient/GameText.h"
#include "GameNetwork/LANAPICallbacks.h"
#include "GameNetwork/GameMessageParser.h"
#include "GameNetwork/GameSpy/PeerDefs.h"
#include "GameNetwork/networkutil.h"
#include "GameLogic/GameLogic.h"
#include "Common/RandomValue.h"
#include "Common/CRCDebug.h"
#include "Common/OptionPreferences.h"
#include "Common/version.h"
constexpr const char s_genrep[] = "GENREP";
constexpr const UnsignedInt replayBufferBytes = 8192;
Int REPLAY_CRC_INTERVAL = 100;
const char *replayExtention = ".rep";
const char *lastReplayFileName = "00000000"; // a name the user is unlikely to ever type, but won't cause panic & confusion
// TheSuperHackers @tweak helmutbuhler 25/04/2025
// The replay header contains two time fields; startTime and endTime of type time_t.
// time_t is 32 bit wide on VC6, but on newer compilers it is 64 bit wide.
// In order to remain compatible we need to load and save time values with 32 bits.
// Note that this will overflow on January 18, 2038. @todo Upgrade to 64 bits when we break compatibility.
typedef int32_t replay_time_t;
static time_t startTime;
static const UnsignedInt startTimeOffset = 6;
static const UnsignedInt endTimeOffset = startTimeOffset + sizeof(replay_time_t);
static const UnsignedInt frameCountOffset = endTimeOffset + sizeof(replay_time_t);
static const UnsignedInt desyncOffset = frameCountOffset + sizeof(UnsignedInt);
static const UnsignedInt quitEarlyOffset = desyncOffset + sizeof(Bool);
static const UnsignedInt disconOffset = quitEarlyOffset + sizeof(Bool);
void RecorderClass::logGameStart(AsciiString options)
{
if (!m_file)
return;
time(&startTime);
UnsignedInt fileSize = m_file->size();
// move to appropriate offset
if ( m_file->seek(startTimeOffset, File::seekMode::START) == startTimeOffset )
{
// save off start time
replay_time_t tmp = (replay_time_t)startTime;
m_file->write(&tmp, sizeof(tmp));
}
// move back to end of stream
#ifdef DEBUG_CRASHING
Int res =
#endif
m_file->seek(fileSize, File::seekMode::START);
DEBUG_ASSERTCRASH(res == fileSize, ("Could not seek to end of file!"));
#if defined(RTS_DEBUG)
if (TheNetwork && TheGlobalData->m_saveStats)
{
//if (TheLAN)
{
unsigned long bufSize = MAX_COMPUTERNAME_LENGTH + 1;
char computerName[MAX_COMPUTERNAME_LENGTH + 1];
if (!GetComputerName(computerName, &bufSize))
{
strcpy(computerName, "unknown");
}
AsciiString statsFile = TheGlobalData->m_baseStatsDir;
TheFileSystem->createDirectory(statsFile);
statsFile.concat(computerName);
statsFile.concat(".txt");
FILE *logFP = fopen(statsFile.str(), "a+");
if (!logFP)
{
// try again locally
TheWritableGlobalData->m_baseStatsDir = TheGlobalData->getPath_UserData();
statsFile = TheGlobalData->m_baseStatsDir;
statsFile.concat(computerName);
statsFile.concat(".txt");
logFP = fopen(statsFile.str(), "a+");
}
if (logFP)
{
struct tm *t2 = localtime(&startTime);
fprintf(logFP, "\nGame start at %s\tOptions are %s\n", asctime(t2), options.str());
fclose(logFP);
}
}
}
#endif
}
void RecorderClass::logPlayerDisconnect(UnicodeString player, Int slot)
{
if (!m_file)
return;
DEBUG_ASSERTCRASH((slot >= 0) && (slot < MAX_SLOTS), ("Attempting to disconnect an invalid slot number"));
if ((slot < 0) || (slot >= (MAX_SLOTS)))
{
return;
}
UnsignedInt fileSize = m_file->size();
// move to appropriate offset
Int playerSlotDisconOffset = disconOffset + slot * sizeof(Bool);
if ( m_file->seek(playerSlotDisconOffset, File::seekMode::START) == playerSlotDisconOffset )
{
// save off discon status
Bool flag = TRUE;
m_file->write(&flag, sizeof(flag));
}
// move back to end of stream
#ifdef DEBUG_CRASHING
Int res =
#endif
m_file->seek(fileSize, File::seekMode::START);
DEBUG_ASSERTCRASH(res == fileSize, ("Could not seek to end of file!"));
#if defined(RTS_DEBUG)
if (TheGlobalData->m_saveStats)
{
unsigned long bufSize = MAX_COMPUTERNAME_LENGTH + 1;
char computerName[MAX_COMPUTERNAME_LENGTH + 1];
if (!GetComputerName(computerName, &bufSize))
{
strcpy(computerName, "unknown");
}
AsciiString statsFile = TheGlobalData->m_baseStatsDir;
statsFile.concat(computerName);
statsFile.concat(".txt");
FILE *logFP = fopen(statsFile.str(), "a+");
if (logFP)
{
time_t t;
time(&t);
struct tm *t2 = localtime(&t);
fprintf(logFP, "\tPlayer %ls dropped at %s", player.str(), asctime(t2));
fclose(logFP);
}
}
#endif
}
void RecorderClass::logCRCMismatch()
{
if (!m_file)
return;
UnsignedInt fileSize = m_file->size();
// move to appropriate offset
if ( m_file->seek(desyncOffset, File::seekMode::START) == desyncOffset )
{
// save off desync status
Bool flag = TRUE;
m_file->write(&flag, sizeof(flag));
}
// move back to end of stream
#ifdef DEBUG_CRASHING
Int res =
#endif
m_file->seek(fileSize, File::seekMode::START);
DEBUG_ASSERTCRASH(res == fileSize, ("Could not seek to end of file!"));
#if defined(RTS_DEBUG)
if (TheGlobalData->m_saveStats)
{
m_wasDesync = TRUE;
unsigned long bufSize = MAX_COMPUTERNAME_LENGTH + 1;
char computerName[MAX_COMPUTERNAME_LENGTH + 1];
if (!GetComputerName(computerName, &bufSize))
{
strcpy(computerName, "unknown");
}
AsciiString statsFile = TheGlobalData->m_baseStatsDir;
statsFile.concat(computerName);
statsFile.concat(".txt");
FILE *logFP = fopen(statsFile.str(), "a+");
if (logFP)
{
time_t t;
time(&t);
struct tm *t2 = localtime(&t);
fprintf(logFP, "\tCRC mismatch at %s", asctime(t2));
fclose(logFP);
}
}
#endif
}
void RecorderClass::logGameEnd()
{
if (!m_file)
return;
time_t t;
time(&t);
UnsignedInt frameCount = TheGameLogic->getFrame();
UnsignedInt fileSize = m_file->size();
// move to appropriate offset
if ( m_file->seek(endTimeOffset, File::seekMode::START) == endTimeOffset )
{
// save off end time
replay_time_t tmp = (replay_time_t)t;
m_file->write(&tmp, sizeof(tmp));
}
// move to appropriate offset
if ( m_file->seek(frameCountOffset, File::seekMode::START) == frameCountOffset )
{
// save off frameCount
m_file->write(&frameCount, sizeof(frameCount));
}
// move back to end of stream
#ifdef DEBUG_CRASHING
Int res =
#endif
m_file->seek(fileSize, File::seekMode::START);
DEBUG_ASSERTCRASH(res == fileSize, ("Could not seek to end of file!"));
#if defined(RTS_DEBUG)
if (TheNetwork && TheGlobalData->m_saveStats)
{
//if (TheLAN)
{
unsigned long bufSize = MAX_COMPUTERNAME_LENGTH + 1;
char computerName[MAX_COMPUTERNAME_LENGTH + 1];
if (!GetComputerName(computerName, &bufSize))
{
strcpy(computerName, "unknown");
}
AsciiString statsFile = TheGlobalData->m_baseStatsDir;
statsFile.concat(computerName);
statsFile.concat(".txt");
FILE *logFP = fopen(statsFile.str(), "a+");
if (logFP)
{
struct tm *t2 = localtime(&t);
time_t duration = t - startTime;
Int minutes = duration/60;
Int seconds = duration%60;
fprintf(logFP, "Game end at %s(%d:%2.2d elapsed time)\n", asctime(t2), minutes, seconds);
fclose(logFP);
}
}
}
#endif
}
void RecorderClass::cleanUpReplayFile()
{
#if defined(RTS_DEBUG)
if (TheGlobalData->m_saveStats)
{
char fname[_MAX_PATH+1];
strlcpy(fname, TheGlobalData->m_baseStatsDir.str(), ARRAY_SIZE(fname));
strlcat(fname, m_fileName.str(), ARRAY_SIZE(fname));
DEBUG_LOG(("Saving replay to %s", fname));
AsciiString oldFname;
oldFname.format("%s%s", getReplayDir().str(), m_fileName.str());
CopyFile(oldFname.str(), fname, TRUE);
#ifdef DEBUG_LOGGING
const char* logFileName = DebugGetLogFileName();
if (logFileName[0] == '\0')
return;
AsciiString debugFname = fname;
debugFname.truncateBy(3);
debugFname.concat("txt");
UnsignedInt fileSize = 0;
FILE *fp = fopen(logFileName, "rb");
if (fp)
{
fseek(fp, 0, SEEK_END);
fileSize = ftell(fp);
fclose(fp);
fp = nullptr;
DEBUG_LOG(("Log file size was %d", fileSize));
}
const int MAX_DEBUG_SIZE = 65536;
if (fileSize <= MAX_DEBUG_SIZE || TheGlobalData->m_saveAllStats)
{
DEBUG_LOG(("Using CopyFile to copy %s", logFileName));
CopyFile(logFileName, debugFname.str(), TRUE);
}
else
{
DEBUG_LOG(("manual copy of %s", logFileName));
FILE *ifp = fopen(logFileName, "rb");
FILE *ofp = fopen(debugFname.str(), "wb");
if (ifp && ofp)
{
fseek(ifp, fileSize-MAX_DEBUG_SIZE, SEEK_SET);
char buf[4096];
Int len;
while ( (len=fread(buf, 1, 4096, ifp)) > 0 )
{
fwrite(buf, 1, len, ofp);
}
fclose(ofp);
fclose(ifp);
ifp = nullptr;
ofp = nullptr;
}
else
{
if (ifp) fclose(ifp);
if (ofp) fclose(ofp);
ifp = nullptr;
ofp = nullptr;
}
}
#endif // DEBUG_LOGGING
}
#endif
}
/**
* The recorder object.
*/
RecorderClass *TheRecorder = nullptr;
/**
* Constructor
*/
RecorderClass::RecorderClass()
{
m_originalGameMode = GAME_NONE;
m_mode = RECORDERMODETYPE_RECORD;
m_file = nullptr;
m_fileName.clear();
m_currentFilePosition = 0;
m_doingAnalysis = FALSE;
m_archiveReplays = FALSE;
m_nextFrame = 0;
m_wasDesync = FALSE;
init(); // just for the heck of it.
}
/**
* Destructor
*/
RecorderClass::~RecorderClass() {
}
/**
* Initialization
* The recorder will record by default since every game will be recorded.
* Obviously a game that is being played back will not be recorded.
* Since the playback is done through a special interface, that interface
* will set the recorder mode to RECORDERMODETYPE_PLAYBACK.
*/
void RecorderClass::init() {
m_originalGameMode = GAME_NONE;
m_mode = RECORDERMODETYPE_NONE;
m_file = nullptr;
m_fileName.clear();
m_currentFilePosition = 0;
m_gameInfo.clearSlotList();
m_gameInfo.reset();
if (TheGlobalData->m_pendingFile.isEmpty())
m_gameInfo.setMap(TheGlobalData->m_mapName);
else
m_gameInfo.setMap(TheGlobalData->m_pendingFile);
m_gameInfo.setSeed(GetGameLogicRandomSeed());
m_wasDesync = FALSE;
m_doingAnalysis = FALSE;
m_playbackFrameCount = 0;
OptionPreferences optionPref;
m_archiveReplays = optionPref.getArchiveReplaysEnabled();
}
/**
* Reset the recorder to the "initialized state."
*/
void RecorderClass::reset() {
if (m_file != nullptr) {
m_file->close();
m_file = nullptr;
}
m_fileName.clear();
init();
}
/**
* update
* Do the update for this frame.
*/
void RecorderClass::update() {
if (m_mode == RECORDERMODETYPE_RECORD || m_mode == RECORDERMODETYPE_NONE) {
updateRecord();
} else if (isPlaybackMode()) {
updatePlayback();
}
}
/**
* Do the update for the next frame of this playback.
*/
void RecorderClass::updatePlayback() {
// Remove any bad commands that have been inserted by the local user that shouldn't be
// executed during playback.
CullBadCommandsResult result = cullBadCommands();
if (result.hasClearGameDataMessage) {
// TheSuperHackers @bugfix Stop appending more commands if the replay playback is about to end.
// Previously this would be able to append more commands, which could have unintended consequences,
// such as crashing the game when a MSG_PLACE_BEACON is appended after MSG_CLEAR_GAME_DATA.
// MSG_CLEAR_GAME_DATA is supposed to be processed later this frame, which will then stop this playback.
return;
}
if (m_nextFrame == -1) {
// This is reached if there are no more commands to be executed.
return;
}
UnsignedInt curFrame = TheGameLogic->getFrame();
if (m_doingAnalysis)
curFrame = m_nextFrame;
// While there are commands to be queued up for this frame, do it.
while (m_nextFrame == curFrame) {
appendNextCommand(); // append the next command to TheCommandQueue
readNextFrame(); // Read the next command's frame number for playback.
}
}
/**
* Stop the currently running playback. This is probably due either to the user exiting out of the playback or
* reaching the end of the playback file.
*/
void RecorderClass::stopPlayback() {
if (m_file != nullptr) {
m_file->close();
m_file = nullptr;
}
m_fileName.clear();
if (!m_doingAnalysis)
{
TheGameLogic->exitGame();
}
}
/**
* Update function for recording a game. Basically all the pertinent logic commands for this frame are written out
* to a file.
*/
void RecorderClass::updateRecord()
{
Bool needFlush = FALSE;
static Int lastFrame = -1;
GameMessage *msg = TheCommandList->getFirstMessage();
while (msg != nullptr) {
if (msg->getType() == GameMessage::MSG_NEW_GAME &&
msg->getArgument(0)->integer != GAME_SHELL &&
msg->getArgument(0)->integer != GAME_SINGLE_PLAYER && // Due to the massive amount of scripts that use <local player> in GC and single player, replays have been cut for them.
msg->getArgument(0)->integer != GAME_NONE)
{
m_originalGameMode = msg->getArgument(0)->integer;
DEBUG_LOG(("RecorderClass::updateRecord() - original game is mode %d", m_originalGameMode));
lastFrame = 0;
GameDifficulty diff = DIFFICULTY_NORMAL;
if (msg->getArgumentCount() >= 2)
diff = (GameDifficulty)msg->getArgument(1)->integer;
Int rankPoints = 0;
if (msg->getArgumentCount() >= 3)
rankPoints = msg->getArgument(2)->integer;
Int maxFPS = 0;
if (msg->getArgumentCount() >= 4)
maxFPS = msg->getArgument(3)->integer;
startRecording(diff, m_originalGameMode, rankPoints, maxFPS);
} else if (msg->getType() == GameMessage::MSG_CLEAR_GAME_DATA) {
if (m_file != nullptr) {
lastFrame = -1;
writeToFile(msg);
stopRecording();
needFlush = FALSE;
}
m_fileName.clear();
} else {
if (m_file != nullptr) {
if ((msg->getType() > GameMessage::MSG_BEGIN_NETWORK_MESSAGES) &&
(msg->getType() < GameMessage::MSG_END_NETWORK_MESSAGES)) {
// Only write the important messages to the file.
writeToFile(msg);
needFlush = TRUE;
}
}
}
msg = msg->next();
}
if (needFlush) {
DEBUG_ASSERTCRASH(m_file != nullptr, ("RecorderClass::updateRecord() - unexpected call to fflush(m_file)"));
m_file->flush();
}
}
/**
* Start a new file for recording. This will always overwrite the "LastReplay.rep" file with the new one.
* So don't call this unless you really mean it.
*/
void RecorderClass::startRecording(GameDifficulty diff, Int originalGameMode, Int rankPoints, Int maxFPS) {
DEBUG_ASSERTCRASH(m_file == nullptr, ("Starting to record game while game is in progress."));
reset();
m_mode = RECORDERMODETYPE_RECORD;
AsciiString filepath = getReplayDir();
// We have to make sure the replay dir exists.
TheFileSystem->createDirectory(filepath);
m_fileName = getLastReplayFileName();
m_fileName.concat(getReplayExtention());
filepath.concat(m_fileName);
m_file = TheFileSystem->openFile(filepath.str(), File::WRITE | File::BINARY);
if (m_file == nullptr) {
DEBUG_ASSERTCRASH(m_file != nullptr, ("Failed to create replay file"));
return;
}
// TheSuperHackers @info the null terminator needs to be ignored to maintain retail replay file layout
m_file->writeFormat("%s", s_genrep);
//
// save space for stats to be filled in.
//
// **** if this changes, change the LAN code above ****
//
replay_time_t time = 0;
m_file->write(&time, sizeof(time)); // reserve space for start time
m_file->write(&time, sizeof(time)); // reserve space for end time
UnsignedInt frames = 0;
m_file->write(&frames, sizeof(frames)); // reserve space for duration in frames
Bool flag = FALSE;
m_file->write(&flag, sizeof(flag)); // reserve space for flag (true if we desync)
m_file->write(&flag, sizeof(flag)); // reserve space for flag (true if we quit early)
for (Int i=0; i<MAX_SLOTS; ++i)
{
m_file->write(&flag, sizeof(flag)); // reserve space for flag (true if player i disconnects)
}
// Print out the name of the replay.
UnicodeString replayName;
replayName = TheGameText->fetch("GUI:LastReplay");
m_file->writeFormat(L"%s", replayName.str());
m_file->writeChar(L"\0");
// Date and Time
SYSTEMTIME systemTime;
GetLocalTime( &systemTime );
m_file->write(&systemTime, sizeof(systemTime));
// write out version info
UnicodeString versionString = TheVersion->getUnicodeVersion();
UnicodeString versionTimeString = TheVersion->getUnicodeBuildTime();
UnsignedInt versionNumber = TheVersion->getVersionNumber();
m_file->writeFormat(L"%s", versionString.str());
m_file->writeChar(L"\0");
m_file->writeFormat(L"%s", versionTimeString.str());
m_file->writeChar(L"\0");
m_file->write(&versionNumber, sizeof(versionNumber));
m_file->write(&(TheGlobalData->m_exeCRC), sizeof(TheGlobalData->m_exeCRC));
m_file->write(&(TheGlobalData->m_iniCRC), sizeof(TheGlobalData->m_iniCRC));
// Number of players
/*
Int numPlayers = ThePlayerList->getPlayerCount();
fwrite(&numPlayers, sizeof(numPlayers), 1, m_file);
*/
// Write the slot list.
AsciiString theSlotList;
Int localIndex = -1;
if (TheNetwork)
{
if (TheLAN)
{
GameInfo *game = TheLAN->GetMyGame();
DEBUG_ASSERTCRASH(game, ("Starting a LAN game with no LANGameInfo object!"));
theSlotList = GameInfoToAsciiString(game);
for (Int i=0; i<MAX_SLOTS; ++i)
{
if (game->getLocalIP() == game->getSlot(i)->getIP())
{
localIndex = i;
break;
}
}
}
else
{
theSlotList = GameInfoToAsciiString(TheGameSpyGame);
localIndex = TheGameSpyGame->getLocalSlotNum();
}
}
else
{
if(TheSkirmishGameInfo)
{
TheSkirmishGameInfo->setCRCInterval(REPLAY_CRC_INTERVAL);
theSlotList = GameInfoToAsciiString(TheSkirmishGameInfo);
DEBUG_LOG(("GameInfo String: %s",theSlotList.str()));
localIndex = 0;
}
else
{
// single player. format the generic (empty) slotlist
m_gameInfo.setCRCInterval(REPLAY_CRC_INTERVAL);
theSlotList = GameInfoToAsciiString(&m_gameInfo);
}
}
logGameStart(theSlotList);
DEBUG_LOG(("RecorderClass::startRecording - theSlotList = %s", theSlotList.str()));
// write slot list (starting spots, color, alliances, etc
m_file->writeFormat("%s", theSlotList.str());
m_file->writeChar("\0");
m_file->writeFormat("%d", localIndex);
m_file->writeChar("\0");
/*
/// @todo fix this to use starting spots and player alliances when those are put in the game.
for (Int i = 0; i < numPlayers; ++i) {
Player *player = ThePlayerList->getNthPlayer(i);
if (player == nullptr) {
continue;
}
UnicodeString name = player->getPlayerDisplayName();
fwprintf(m_file, L"%s", name.str());
fputwc(0, m_file);
UnicodeString faction = player->getFaction()->getFactionDisplayName();
fwprintf(m_file, L"%s", faction.str());
fputwc(0, m_file);
Int color = player->getColor()->getAsInt();
fwrite(&color, sizeof(color), 1, m_file);
Int team = 0;
Int startingSpot = 0;
fwrite(&startingSpot, sizeof(Int), 1, m_file);
fwrite(&team, sizeof(Int), 1, m_file);
}
*/
// Write the game difficulty.
m_file->write(&diff, sizeof(diff));
// Write original game mode
m_file->write(&originalGameMode, sizeof(originalGameMode));
// Write rank points to add at game start
m_file->write(&rankPoints, sizeof(rankPoints));
// Write maxFPS chosen
m_file->write(&maxFPS, sizeof(maxFPS));
DEBUG_LOG(("RecorderClass::startRecording() - diff=%d, mode=%d, FPS=%d", diff, originalGameMode, maxFPS));
/*
// Write the map name.
fprintf(m_file, "%s", (TheGlobalData->m_mapName).str());
fputc(0, m_file);
*/
/// @todo Need to write game options when there are some to be written.
}
/**
* This will stop the current recording session and close the file. This should always be called at the end of
* every game.
*/
void RecorderClass::stopRecording() {
logGameEnd();
if (TheNetwork)
{
//if (TheLAN)
{
if (m_wasDesync)
cleanUpReplayFile();
m_wasDesync = FALSE;
}
}
if (m_file != nullptr) {
m_file->close();
m_file = nullptr;
if (m_archiveReplays)
archiveReplay(m_fileName);
}
m_fileName.clear();
}
/**
* TheSuperHackers @feature Stubbjax 17/10/2025 Copy the replay file to the archive directory and rename it using the current timestamp.
*/
void RecorderClass::archiveReplay(AsciiString fileName)
{
SYSTEMTIME st;
GetLocalTime(&st);
AsciiString archiveFileName;
// Use a standard YYYYMMDD_HHMMSS format for simplicity and to avoid conflicts.
archiveFileName.format("%04d%02d%02d_%02d%02d%02d", st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
AsciiString extension = getReplayExtention();
AsciiString sourcePath = getReplayDir();
sourcePath.concat(fileName);
if (!sourcePath.endsWith(extension))
sourcePath.concat(extension);
AsciiString destPath = getReplayArchiveDir();
TheFileSystem->createDirectory(destPath.str());
destPath.concat(archiveFileName);
destPath.concat(extension);
if (!CopyFile(sourcePath.str(), destPath.str(), FALSE))
DEBUG_LOG(("RecorderClass::archiveReplay: Failed to copy %s to %s", sourcePath.str(), destPath.str()));
}
/**
* Write this game message to the record file. This also writes the game message's execution frame.
*/
void RecorderClass::writeToFile(GameMessage * msg) {
// Write the frame number for this command.
UnsignedInt frame = TheGameLogic->getFrame();
m_file->write(&frame, sizeof(frame));
// Write the command type
GameMessage::Type type = msg->getType();
m_file->write(&type, sizeof(type));
// Write the player index
Int playerIndex = msg->getPlayerIndex();
m_file->write(&playerIndex, sizeof(playerIndex));
#ifdef DEBUG_LOGGING
AsciiString commandName = msg->getCommandAsString();
if (type < GameMessage::MSG_BEGIN_NETWORK_MESSAGES || type > GameMessage::MSG_END_NETWORK_MESSAGES)
{
commandName.concat(" (Non-Network message!)");
}
else if (type == GameMessage::MSG_BEGIN_NETWORK_MESSAGES)
{
AsciiString tmp;
tmp.format(" (CRC 0x%8.8X)", msg->getArgument(0)->integer);
commandName.concat(tmp);
}
//DEBUG_LOG(("RecorderClass::writeToFile - Adding %s command from player %d to TheCommandList on frame %d",
//commandName.str(), msg->getPlayerIndex(), TheGameLogic->getFrame()));
#endif // DEBUG_LOGGING
GameMessageParser *parser = newInstance(GameMessageParser)(msg);
UnsignedByte numTypes = parser->getNumTypes();
m_file->write(&numTypes, sizeof(numTypes));
GameMessageParserArgumentType *argType = parser->getFirstArgumentType();
while (argType != nullptr) {
UnsignedByte type = (UnsignedByte)(argType->getType());
m_file->write(&type, sizeof(type));
UnsignedByte argTypeCount = (UnsignedByte)(argType->getArgCount());
m_file->write(&argTypeCount, sizeof(argTypeCount));
argType = argType->getNext();
}
// UnsignedByte lasttype = (UnsignedByte)ARGUMENTDATATYPE_UNKNOWN;
Int numArgs = msg->getArgumentCount();
for (Int i = 0; i < numArgs; ++i) {
// UnsignedByte type = (UnsignedByte)(msg->getArgumentDataType(i));
// if (lasttype != type) {
// fwrite(&type, sizeof(type), 1, m_file);
// lasttype = type;
// }
writeArgument(msg->getArgumentDataType(i), *(msg->getArgument(i)));
}
deleteInstance(parser);
parser = nullptr;
}
void RecorderClass::writeArgument(GameMessageArgumentDataType type, const GameMessageArgumentType arg) {
switch (type) {
case ARGUMENTDATATYPE_INTEGER:
m_file->write( &(arg.integer), sizeof(arg.integer) );
break;
case ARGUMENTDATATYPE_REAL:
m_file->write( &(arg.real), sizeof(arg.real) );
break;
case ARGUMENTDATATYPE_BOOLEAN:
m_file->write( &(arg.boolean), sizeof(arg.boolean) );
break;
case ARGUMENTDATATYPE_OBJECTID:
m_file->write( &(arg.objectID), sizeof(arg.objectID) );
break;
case ARGUMENTDATATYPE_DRAWABLEID:
m_file->write( &(arg.drawableID), sizeof(arg.drawableID) );
break;
case ARGUMENTDATATYPE_TEAMID:
m_file->write( &(arg.teamID), sizeof(arg.teamID) );
break;
case ARGUMENTDATATYPE_LOCATION:
m_file->write( &(arg.location), sizeof(arg.location) );
break;
case ARGUMENTDATATYPE_PIXEL:
m_file->write( &(arg.pixel), sizeof(arg.pixel) );
break;
case ARGUMENTDATATYPE_PIXELREGION:
m_file->write( &(arg.pixelRegion), sizeof(arg.pixelRegion) );
break;
case ARGUMENTDATATYPE_TIMESTAMP:
m_file->write( &(arg.timestamp), sizeof(arg.timestamp) );
break;
case ARGUMENTDATATYPE_WIDECHAR:
m_file->write( &(arg.wChar), sizeof(arg.wChar) );
break;
default:
DEBUG_LOG(("Unknown GameMessageArgumentDataType in RecorderClass::writeArgument"));
break;
}
}
/**
* Read in a replay header, for (1) populating a replay listbox or (2) starting playback. In
* case (2), set FILE *m_file.
*/
Bool RecorderClass::readReplayHeader(ReplayHeader& header)
{
AsciiString filepath = getReplayDir();
filepath.concat(header.filename.str());
// TheSuperHackers @performance More buffered data reduces disk overhead and will improve fast forward playback
const UnsignedInt buffersize = header.forPlayback ? replayBufferBytes : File::BUFFERSIZE;
m_file = TheFileSystem->openFile(filepath.str(), File::READ | File::BINARY, buffersize);
if (m_file == nullptr)
{
DEBUG_LOG(("Can't open %s (%s)", filepath.str(), header.filename.str()));
return FALSE;
}
// Read the GENREP header.
char genrep[sizeof(s_genrep) - 1] = {0};
m_file->read( &genrep, sizeof(s_genrep) - 1 );
if ( strncmp(genrep, s_genrep, sizeof(s_genrep) - 1 ) != 0 ) {
DEBUG_LOG(("RecorderClass::readReplayHeader - replay file did not have GENREP at the start."));
m_file->close();
m_file = nullptr;
return FALSE;
}
// read in some stats
replay_time_t tmp;
m_file->read(&tmp, sizeof(tmp));
header.startTime = tmp;
m_file->read(&tmp, sizeof(tmp));
header.endTime = tmp;
m_file->read(&header.frameCount, sizeof(header.frameCount));
m_file->read(&header.desyncGame, sizeof(header.desyncGame));
m_file->read(&header.quitEarly, sizeof(header.quitEarly));
for (Int i=0; i<MAX_SLOTS; ++i)
{
m_file->read(&(header.playerDiscons[i]), sizeof(Bool));
}
// Read the Replay Name. We don't actually do anything with it. Oh well.
header.replayName = readUnicodeString();
// Read the date and time. We don't really do anything with this either. Oh well.
m_file->read(&header.timeVal, sizeof(header.timeVal));
// Read in the Version info
header.versionString = readUnicodeString();
header.versionTimeString = readUnicodeString();
m_file->read(&header.versionNumber, sizeof(header.versionNumber));
m_file->read(&header.exeCRC, sizeof(header.exeCRC));
m_file->read(&header.iniCRC, sizeof(header.iniCRC));
// Read in the GameInfo
header.gameOptions = readAsciiString();
m_gameInfo.reset();
m_gameInfo.enterGame();
DEBUG_LOG(("RecorderClass::readReplayHeader - GameInfo = %s", header.gameOptions.str()));
if (!ParseAsciiStringToGameInfo(&m_gameInfo, header.gameOptions))
{
DEBUG_LOG(("RecorderClass::readReplayHeader - replay file did not have a valid GameInfo string."));
m_file->close();
m_file = nullptr;
return FALSE;
}
m_gameInfo.startGame(0);
AsciiString playerIndex = readAsciiString();
header.localPlayerIndex = atoi(playerIndex.str());
if (header.localPlayerIndex < -1 || header.localPlayerIndex >= MAX_SLOTS)
{
DEBUG_LOG(("RecorderClass::readReplayHeader - invalid local slot number."));
m_gameInfo.endGame();
m_gameInfo.reset();
m_file->close();
m_file = nullptr;
return FALSE;
}
if (header.localPlayerIndex >= 0)
{
Int localIP = m_gameInfo.getSlot(header.localPlayerIndex)->getIP();
m_gameInfo.setLocalIP(localIP);
}
if (!header.forPlayback)
{
m_gameInfo.endGame();
m_gameInfo.reset();
m_file->close();
m_file = nullptr;
}
return TRUE;
}
Bool RecorderClass::simulateReplay(AsciiString filename)
{
Bool success = playbackFile(filename);
if (success)
m_mode = RECORDERMODETYPE_SIMULATION_PLAYBACK;
return success;
}
#if defined(RTS_DEBUG)
Bool RecorderClass::analyzeReplay( AsciiString filename )
{
m_doingAnalysis = TRUE;
return playbackFile(filename);
}
#endif
Bool RecorderClass::isPlaybackInProgress() const
{
return isPlaybackMode() && m_nextFrame != -1;
}
AsciiString RecorderClass::getCurrentReplayFilename()
{