forked from OpenTTD/OpenTTD
/
saveload.cpp
2889 lines (2501 loc) · 83.6 KB
/
saveload.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
/* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD 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, version 2.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file saveload.cpp
* All actions handling saving and loading goes on in this file. The general actions
* are as follows for saving a game (loading is analogous):
* <ol>
* <li>initialize the writer by creating a temporary memory-buffer for it
* <li>go through all to-be saved elements, each 'chunk' (#ChunkHandler) prefixed by a label
* <li>use their description array (#SaveLoad) to know what elements to save and in what version
* of the game it was active (used when loading)
* <li>write all data byte-by-byte to the temporary buffer so it is endian-safe
* <li>when the buffer is full; flush it to the output (eg save to file) (_sl.buf, _sl.bufp, _sl.bufe)
* <li>repeat this until everything is done, and flush any remaining output to file
* </ol>
*/
#include <deque>
#include "../stdafx.h"
#include "../debug.h"
#include "../station_base.h"
#include "../thread.h"
#include "../town.h"
#include "../network/network.h"
#include "../window_func.h"
#include "../strings_func.h"
#include "../core/endian_func.hpp"
#include "../vehicle_base.h"
#include "../company_func.h"
#include "../date_func.h"
#include "../autoreplace_base.h"
#include "../roadstop_base.h"
#include "../linkgraph/linkgraph.h"
#include "../linkgraph/linkgraphjob.h"
#include "../statusbar_gui.h"
#include "../fileio_func.h"
#include "../gamelog.h"
#include "../string_func.h"
#include "../fios.h"
#include "../error.h"
#include <atomic>
#include "table/strings.h"
#include "saveload_internal.h"
#include "saveload_filter.h"
#include "../safeguards.h"
extern const SaveLoadVersion SAVEGAME_VERSION = (SaveLoadVersion)(SL_MAX_VERSION - 1); ///< Current savegame version of OpenTTD.
SavegameType _savegame_type; ///< type of savegame we are loading
FileToSaveLoad _file_to_saveload; ///< File to save or load in the openttd loop.
uint32 _ttdp_version; ///< version of TTDP savegame (if applicable)
SaveLoadVersion _sl_version; ///< the major savegame version identifier
byte _sl_minor_version; ///< the minor savegame version, DO NOT USE!
char _savegame_format[8]; ///< how to compress savegames
bool _do_autosave; ///< are we doing an autosave at the moment?
/** What are we currently doing? */
enum SaveLoadAction {
SLA_LOAD, ///< loading
SLA_SAVE, ///< saving
SLA_PTRS, ///< fixing pointers
SLA_NULL, ///< null all pointers (on loading error)
SLA_LOAD_CHECK, ///< partial loading into #_load_check_data
};
enum NeedLength {
NL_NONE = 0, ///< not working in NeedLength mode
NL_WANTLENGTH = 1, ///< writing length and data
NL_CALCLENGTH = 2, ///< need to calculate the length
};
/** Save in chunks of 128 KiB. */
static const size_t MEMORY_CHUNK_SIZE = 128 * 1024;
/** A buffer for reading (and buffering) savegame data. */
struct ReadBuffer {
byte buf[MEMORY_CHUNK_SIZE]; ///< Buffer we're going to read from.
byte *bufp; ///< Location we're at reading the buffer.
byte *bufe; ///< End of the buffer we can read from.
LoadFilter *reader; ///< The filter used to actually read.
size_t read; ///< The amount of read bytes so far from the filter.
/**
* Initialise our variables.
* @param reader The filter to actually read data.
*/
ReadBuffer(LoadFilter *reader) : bufp(nullptr), bufe(nullptr), reader(reader), read(0)
{
}
inline byte ReadByte()
{
if (this->bufp == this->bufe) {
size_t len = this->reader->Read(this->buf, lengthof(this->buf));
if (len == 0) SlErrorCorrupt("Unexpected end of chunk");
this->read += len;
this->bufp = this->buf;
this->bufe = this->buf + len;
}
return *this->bufp++;
}
/**
* Get the size of the memory dump made so far.
* @return The size.
*/
size_t GetSize() const
{
return this->read - (this->bufe - this->bufp);
}
};
/** Container for dumping the savegame (quickly) to memory. */
struct MemoryDumper {
std::vector<byte *> blocks; ///< Buffer with blocks of allocated memory.
byte *buf; ///< Buffer we're going to write to.
byte *bufe; ///< End of the buffer we write to.
/** Initialise our variables. */
MemoryDumper() : buf(nullptr), bufe(nullptr)
{
}
~MemoryDumper()
{
for (auto p : this->blocks) {
free(p);
}
}
/**
* Write a single byte into the dumper.
* @param b The byte to write.
*/
inline void WriteByte(byte b)
{
/* Are we at the end of this chunk? */
if (this->buf == this->bufe) {
this->buf = CallocT<byte>(MEMORY_CHUNK_SIZE);
this->blocks.push_back(this->buf);
this->bufe = this->buf + MEMORY_CHUNK_SIZE;
}
*this->buf++ = b;
}
/**
* Flush this dumper into a writer.
* @param writer The filter we want to use.
*/
void Flush(SaveFilter *writer)
{
uint i = 0;
size_t t = this->GetSize();
while (t > 0) {
size_t to_write = min(MEMORY_CHUNK_SIZE, t);
writer->Write(this->blocks[i++], to_write);
t -= to_write;
}
writer->Finish();
}
/**
* Get the size of the memory dump made so far.
* @return The size.
*/
size_t GetSize() const
{
return this->blocks.size() * MEMORY_CHUNK_SIZE - (this->bufe - this->buf);
}
};
/** The saveload struct, containing reader-writer functions, buffer, version, etc. */
struct SaveLoadParams {
SaveLoadAction action; ///< are we doing a save or a load atm.
NeedLength need_length; ///< working in NeedLength (Autolength) mode?
byte block_mode; ///< ???
bool error; ///< did an error occur or not
size_t obj_len; ///< the length of the current object we are busy with
int array_index, last_array_index; ///< in the case of an array, the current and last positions
MemoryDumper *dumper; ///< Memory dumper to write the savegame to.
SaveFilter *sf; ///< Filter to write the savegame to.
ReadBuffer *reader; ///< Savegame reading buffer.
LoadFilter *lf; ///< Filter to read the savegame from.
StringID error_str; ///< the translatable error message to show
char *extra_msg; ///< the error message
byte ff_state; ///< The state of fast-forward when saving started.
bool saveinprogress; ///< Whether there is currently a save in progress.
};
static SaveLoadParams _sl; ///< Parameters used for/at saveload.
/* these define the chunks */
extern const ChunkHandler _gamelog_chunk_handlers[];
extern const ChunkHandler _map_chunk_handlers[];
extern const ChunkHandler _misc_chunk_handlers[];
extern const ChunkHandler _name_chunk_handlers[];
extern const ChunkHandler _cheat_chunk_handlers[] ;
extern const ChunkHandler _setting_chunk_handlers[];
extern const ChunkHandler _company_chunk_handlers[];
extern const ChunkHandler _engine_chunk_handlers[];
extern const ChunkHandler _veh_chunk_handlers[];
extern const ChunkHandler _waypoint_chunk_handlers[];
extern const ChunkHandler _depot_chunk_handlers[];
extern const ChunkHandler _order_chunk_handlers[];
extern const ChunkHandler _town_chunk_handlers[];
extern const ChunkHandler _sign_chunk_handlers[];
extern const ChunkHandler _station_chunk_handlers[];
extern const ChunkHandler _industry_chunk_handlers[];
extern const ChunkHandler _economy_chunk_handlers[];
extern const ChunkHandler _subsidy_chunk_handlers[];
extern const ChunkHandler _cargomonitor_chunk_handlers[];
extern const ChunkHandler _goal_chunk_handlers[];
extern const ChunkHandler _story_page_chunk_handlers[];
extern const ChunkHandler _ai_chunk_handlers[];
extern const ChunkHandler _game_chunk_handlers[];
extern const ChunkHandler _animated_tile_chunk_handlers[];
extern const ChunkHandler _newgrf_chunk_handlers[];
extern const ChunkHandler _group_chunk_handlers[];
extern const ChunkHandler _cargopacket_chunk_handlers[];
extern const ChunkHandler _autoreplace_chunk_handlers[];
extern const ChunkHandler _labelmaps_chunk_handlers[];
extern const ChunkHandler _linkgraph_chunk_handlers[];
extern const ChunkHandler _airport_chunk_handlers[];
extern const ChunkHandler _object_chunk_handlers[];
extern const ChunkHandler _persistent_storage_chunk_handlers[];
/** Array of all chunks in a savegame, \c nullptr terminated. */
static const ChunkHandler * const _chunk_handlers[] = {
_gamelog_chunk_handlers,
_map_chunk_handlers,
_misc_chunk_handlers,
_name_chunk_handlers,
_cheat_chunk_handlers,
_setting_chunk_handlers,
_veh_chunk_handlers,
_waypoint_chunk_handlers,
_depot_chunk_handlers,
_order_chunk_handlers,
_industry_chunk_handlers,
_economy_chunk_handlers,
_subsidy_chunk_handlers,
_cargomonitor_chunk_handlers,
_goal_chunk_handlers,
_story_page_chunk_handlers,
_engine_chunk_handlers,
_town_chunk_handlers,
_sign_chunk_handlers,
_station_chunk_handlers,
_company_chunk_handlers,
_ai_chunk_handlers,
_game_chunk_handlers,
_animated_tile_chunk_handlers,
_newgrf_chunk_handlers,
_group_chunk_handlers,
_cargopacket_chunk_handlers,
_autoreplace_chunk_handlers,
_labelmaps_chunk_handlers,
_linkgraph_chunk_handlers,
_airport_chunk_handlers,
_object_chunk_handlers,
_persistent_storage_chunk_handlers,
nullptr,
};
/**
* Iterate over all chunk handlers.
* @param ch the chunk handler iterator
*/
#define FOR_ALL_CHUNK_HANDLERS(ch) \
for (const ChunkHandler * const *chsc = _chunk_handlers; *chsc != nullptr; chsc++) \
for (const ChunkHandler *ch = *chsc; ch != nullptr; ch = (ch->flags & CH_LAST) ? nullptr : ch + 1)
/** Null all pointers (convert index -> nullptr) */
static void SlNullPointers()
{
_sl.action = SLA_NULL;
/* We don't want any savegame conversion code to run
* during NULLing; especially those that try to get
* pointers from other pools. */
_sl_version = SAVEGAME_VERSION;
DEBUG(sl, 1, "Nulling pointers");
FOR_ALL_CHUNK_HANDLERS(ch) {
if (ch->ptrs_proc != nullptr) {
DEBUG(sl, 2, "Nulling pointers for %c%c%c%c", ch->id >> 24, ch->id >> 16, ch->id >> 8, ch->id);
ch->ptrs_proc();
}
}
DEBUG(sl, 1, "All pointers nulled");
assert(_sl.action == SLA_NULL);
}
/**
* Error handler. Sets everything up to show an error message and to clean
* up the mess of a partial savegame load.
* @param string The translatable error message to show.
* @param extra_msg An extra error message coming from one of the APIs.
* @note This function does never return as it throws an exception to
* break out of all the saveload code.
*/
void NORETURN SlError(StringID string, const char *extra_msg)
{
/* Distinguish between loading into _load_check_data vs. normal save/load. */
if (_sl.action == SLA_LOAD_CHECK) {
_load_check_data.error = string;
free(_load_check_data.error_data);
_load_check_data.error_data = (extra_msg == nullptr) ? nullptr : stredup(extra_msg);
} else {
_sl.error_str = string;
free(_sl.extra_msg);
_sl.extra_msg = (extra_msg == nullptr) ? nullptr : stredup(extra_msg);
}
/* We have to nullptr all pointers here; we might be in a state where
* the pointers are actually filled with indices, which means that
* when we access them during cleaning the pool dereferences of
* those indices will be made with segmentation faults as result. */
if (_sl.action == SLA_LOAD || _sl.action == SLA_PTRS) SlNullPointers();
throw std::exception();
}
/**
* Error handler for corrupt savegames. Sets everything up to show the
* error message and to clean up the mess of a partial savegame load.
* @param msg Location the corruption has been spotted.
* @note This function does never return as it throws an exception to
* break out of all the saveload code.
*/
void NORETURN SlErrorCorrupt(const char *msg)
{
SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, msg);
}
/**
* Issue an SlErrorCorrupt with a format string.
* @param format format string
* @param ... arguments to format string
* @note This function does never return as it throws an exception to
* break out of all the saveload code.
*/
void NORETURN SlErrorCorruptFmt(const char *format, ...)
{
va_list ap;
char msg[256];
va_start(ap, format);
vseprintf(msg, lastof(msg), format, ap);
va_end(ap);
SlErrorCorrupt(msg);
}
typedef void (*AsyncSaveFinishProc)(); ///< Callback for when the savegame loading is finished.
static std::atomic<AsyncSaveFinishProc> _async_save_finish; ///< Callback to call when the savegame loading is finished.
static std::thread _save_thread; ///< The thread we're using to compress and write a savegame
/**
* Called by save thread to tell we finished saving.
* @param proc The callback to call when saving is done.
*/
static void SetAsyncSaveFinish(AsyncSaveFinishProc proc)
{
if (_exit_game) return;
while (_async_save_finish.load(std::memory_order_acquire) != nullptr) CSleep(10);
_async_save_finish.store(proc, std::memory_order_release);
}
/**
* Handle async save finishes.
*/
void ProcessAsyncSaveFinish()
{
AsyncSaveFinishProc proc = _async_save_finish.exchange(nullptr, std::memory_order_acq_rel);
if (proc == nullptr) return;
proc();
if (_save_thread.joinable()) {
_save_thread.join();
}
}
/**
* Wrapper for reading a byte from the buffer.
* @return The read byte.
*/
byte SlReadByte()
{
return _sl.reader->ReadByte();
}
/**
* Wrapper for writing a byte to the dumper.
* @param b The byte to write.
*/
void SlWriteByte(byte b)
{
_sl.dumper->WriteByte(b);
}
static inline int SlReadUint16()
{
int x = SlReadByte() << 8;
return x | SlReadByte();
}
static inline uint32 SlReadUint32()
{
uint32 x = SlReadUint16() << 16;
return x | SlReadUint16();
}
static inline uint64 SlReadUint64()
{
uint32 x = SlReadUint32();
uint32 y = SlReadUint32();
return (uint64)x << 32 | y;
}
static inline void SlWriteUint16(uint16 v)
{
SlWriteByte(GB(v, 8, 8));
SlWriteByte(GB(v, 0, 8));
}
static inline void SlWriteUint32(uint32 v)
{
SlWriteUint16(GB(v, 16, 16));
SlWriteUint16(GB(v, 0, 16));
}
static inline void SlWriteUint64(uint64 x)
{
SlWriteUint32((uint32)(x >> 32));
SlWriteUint32((uint32)x);
}
/**
* Read in bytes from the file/data structure but don't do
* anything with them, discarding them in effect
* @param length The amount of bytes that is being treated this way
*/
static inline void SlSkipBytes(size_t length)
{
for (; length != 0; length--) SlReadByte();
}
/**
* Read in the header descriptor of an object or an array.
* If the highest bit is set (7), then the index is bigger than 127
* elements, so use the next byte to read in the real value.
* The actual value is then both bytes added with the first shifted
* 8 bits to the left, and dropping the highest bit (which only indicated a big index).
* x = ((x & 0x7F) << 8) + SlReadByte();
* @return Return the value of the index
*/
static uint SlReadSimpleGamma()
{
uint i = SlReadByte();
if (HasBit(i, 7)) {
i &= ~0x80;
if (HasBit(i, 6)) {
i &= ~0x40;
if (HasBit(i, 5)) {
i &= ~0x20;
if (HasBit(i, 4)) {
i &= ~0x10;
if (HasBit(i, 3)) {
SlErrorCorrupt("Unsupported gamma");
}
i = SlReadByte(); // 32 bits only.
}
i = (i << 8) | SlReadByte();
}
i = (i << 8) | SlReadByte();
}
i = (i << 8) | SlReadByte();
}
return i;
}
/**
* Write the header descriptor of an object or an array.
* If the element is bigger than 127, use 2 bytes for saving
* and use the highest byte of the first written one as a notice
* that the length consists of 2 bytes, etc.. like this:
* 0xxxxxxx
* 10xxxxxx xxxxxxxx
* 110xxxxx xxxxxxxx xxxxxxxx
* 1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx
* 11110--- xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
* We could extend the scheme ad infinum to support arbitrarily
* large chunks, but as sizeof(size_t) == 4 is still very common
* we don't support anything above 32 bits. That's why in the last
* case the 3 most significant bits are unused.
* @param i Index being written
*/
static void SlWriteSimpleGamma(size_t i)
{
if (i >= (1 << 7)) {
if (i >= (1 << 14)) {
if (i >= (1 << 21)) {
if (i >= (1 << 28)) {
assert(i <= UINT32_MAX); // We can only support 32 bits for now.
SlWriteByte((byte)(0xF0));
SlWriteByte((byte)(i >> 24));
} else {
SlWriteByte((byte)(0xE0 | (i >> 24)));
}
SlWriteByte((byte)(i >> 16));
} else {
SlWriteByte((byte)(0xC0 | (i >> 16)));
}
SlWriteByte((byte)(i >> 8));
} else {
SlWriteByte((byte)(0x80 | (i >> 8)));
}
}
SlWriteByte((byte)i);
}
/** Return how many bytes used to encode a gamma value */
static inline uint SlGetGammaLength(size_t i)
{
return 1 + (i >= (1 << 7)) + (i >= (1 << 14)) + (i >= (1 << 21)) + (i >= (1 << 28));
}
static inline uint SlReadSparseIndex()
{
return SlReadSimpleGamma();
}
static inline void SlWriteSparseIndex(uint index)
{
SlWriteSimpleGamma(index);
}
static inline uint SlReadArrayLength()
{
return SlReadSimpleGamma();
}
static inline void SlWriteArrayLength(size_t length)
{
SlWriteSimpleGamma(length);
}
static inline uint SlGetArrayLength(size_t length)
{
return SlGetGammaLength(length);
}
/**
* Return the size in bytes of a certain type of normal/atomic variable
* as it appears in memory. See VarTypes
* @param conv VarType type of variable that is used for calculating the size
* @return Return the size of this type in bytes
*/
static inline uint SlCalcConvMemLen(VarType conv)
{
static const byte conv_mem_size[] = {1, 1, 1, 2, 2, 4, 4, 8, 8, 0};
byte length = GB(conv, 4, 4);
switch (length << 4) {
case SLE_VAR_STRB:
case SLE_VAR_STRBQ:
case SLE_VAR_STR:
case SLE_VAR_STRQ:
return SlReadArrayLength();
default:
assert(length < lengthof(conv_mem_size));
return conv_mem_size[length];
}
}
/**
* Return the size in bytes of a certain type of normal/atomic variable
* as it appears in a saved game. See VarTypes
* @param conv VarType type of variable that is used for calculating the size
* @return Return the size of this type in bytes
*/
static inline byte SlCalcConvFileLen(VarType conv)
{
static const byte conv_file_size[] = {1, 1, 2, 2, 4, 4, 8, 8, 2};
byte length = GB(conv, 0, 4);
assert(length < lengthof(conv_file_size));
return conv_file_size[length];
}
/** Return the size in bytes of a reference (pointer) */
static inline size_t SlCalcRefLen()
{
return IsSavegameVersionBefore(SLV_69) ? 2 : 4;
}
void SlSetArrayIndex(uint index)
{
_sl.need_length = NL_WANTLENGTH;
_sl.array_index = index;
}
static size_t _next_offs;
/**
* Iterate through the elements of an array and read the whole thing
* @return The index of the object, or -1 if we have reached the end of current block
*/
int SlIterateArray()
{
int index;
/* After reading in the whole array inside the loop
* we must have read in all the data, so we must be at end of current block. */
if (_next_offs != 0 && _sl.reader->GetSize() != _next_offs) SlErrorCorrupt("Invalid chunk size");
for (;;) {
uint length = SlReadArrayLength();
if (length == 0) {
_next_offs = 0;
return -1;
}
_sl.obj_len = --length;
_next_offs = _sl.reader->GetSize() + length;
switch (_sl.block_mode) {
case CH_SPARSE_ARRAY: index = (int)SlReadSparseIndex(); break;
case CH_ARRAY: index = _sl.array_index++; break;
default:
DEBUG(sl, 0, "SlIterateArray error");
return -1; // error
}
if (length != 0) return index;
}
}
/**
* Skip an array or sparse array
*/
void SlSkipArray()
{
while (SlIterateArray() != -1) {
SlSkipBytes(_next_offs - _sl.reader->GetSize());
}
}
/**
* Sets the length of either a RIFF object or the number of items in an array.
* This lets us load an object or an array of arbitrary size
* @param length The length of the sought object/array
*/
void SlSetLength(size_t length)
{
assert(_sl.action == SLA_SAVE);
switch (_sl.need_length) {
case NL_WANTLENGTH:
_sl.need_length = NL_NONE;
switch (_sl.block_mode) {
case CH_RIFF:
/* Ugly encoding of >16M RIFF chunks
* The lower 24 bits are normal
* The uppermost 4 bits are bits 24:27 */
assert(length < (1 << 28));
SlWriteUint32((uint32)((length & 0xFFFFFF) | ((length >> 24) << 28)));
break;
case CH_ARRAY:
assert(_sl.last_array_index <= _sl.array_index);
while (++_sl.last_array_index <= _sl.array_index) {
SlWriteArrayLength(1);
}
SlWriteArrayLength(length + 1);
break;
case CH_SPARSE_ARRAY:
SlWriteArrayLength(length + 1 + SlGetArrayLength(_sl.array_index)); // Also include length of sparse index.
SlWriteSparseIndex(_sl.array_index);
break;
default: NOT_REACHED();
}
break;
case NL_CALCLENGTH:
_sl.obj_len += (int)length;
break;
default: NOT_REACHED();
}
}
/**
* Save/Load bytes. These do not need to be converted to Little/Big Endian
* so directly write them or read them to/from file
* @param ptr The source or destination of the object being manipulated
* @param length number of bytes this fast CopyBytes lasts
*/
static void SlCopyBytes(void *ptr, size_t length)
{
byte *p = (byte *)ptr;
switch (_sl.action) {
case SLA_LOAD_CHECK:
case SLA_LOAD:
for (; length != 0; length--) *p++ = SlReadByte();
break;
case SLA_SAVE:
for (; length != 0; length--) SlWriteByte(*p++);
break;
default: NOT_REACHED();
}
}
/** Get the length of the current object */
size_t SlGetFieldLength()
{
return _sl.obj_len;
}
/**
* Return a signed-long version of the value of a setting
* @param ptr pointer to the variable
* @param conv type of variable, can be a non-clean
* type, eg one with other flags because it is parsed
* @return returns the value of the pointer-setting
*/
int64 ReadValue(const void *ptr, VarType conv)
{
switch (GetVarMemType(conv)) {
case SLE_VAR_BL: return (*(const bool *)ptr != 0);
case SLE_VAR_I8: return *(const int8 *)ptr;
case SLE_VAR_U8: return *(const byte *)ptr;
case SLE_VAR_I16: return *(const int16 *)ptr;
case SLE_VAR_U16: return *(const uint16*)ptr;
case SLE_VAR_I32: return *(const int32 *)ptr;
case SLE_VAR_U32: return *(const uint32*)ptr;
case SLE_VAR_I64: return *(const int64 *)ptr;
case SLE_VAR_U64: return *(const uint64*)ptr;
case SLE_VAR_NULL:return 0;
default: NOT_REACHED();
}
}
/**
* Write the value of a setting
* @param ptr pointer to the variable
* @param conv type of variable, can be a non-clean type, eg
* with other flags. It is parsed upon read
* @param val the new value being given to the variable
*/
void WriteValue(void *ptr, VarType conv, int64 val)
{
switch (GetVarMemType(conv)) {
case SLE_VAR_BL: *(bool *)ptr = (val != 0); break;
case SLE_VAR_I8: *(int8 *)ptr = val; break;
case SLE_VAR_U8: *(byte *)ptr = val; break;
case SLE_VAR_I16: *(int16 *)ptr = val; break;
case SLE_VAR_U16: *(uint16*)ptr = val; break;
case SLE_VAR_I32: *(int32 *)ptr = val; break;
case SLE_VAR_U32: *(uint32*)ptr = val; break;
case SLE_VAR_I64: *(int64 *)ptr = val; break;
case SLE_VAR_U64: *(uint64*)ptr = val; break;
case SLE_VAR_NAME: *(char**)ptr = CopyFromOldName(val); break;
case SLE_VAR_NULL: break;
default: NOT_REACHED();
}
}
/**
* Handle all conversion and typechecking of variables here.
* In the case of saving, read in the actual value from the struct
* and then write them to file, endian safely. Loading a value
* goes exactly the opposite way
* @param ptr The object being filled/read
* @param conv VarType type of the current element of the struct
*/
static void SlSaveLoadConv(void *ptr, VarType conv)
{
switch (_sl.action) {
case SLA_SAVE: {
int64 x = ReadValue(ptr, conv);
/* Write the value to the file and check if its value is in the desired range */
switch (GetVarFileType(conv)) {
case SLE_FILE_I8: assert(x >= -128 && x <= 127); SlWriteByte(x);break;
case SLE_FILE_U8: assert(x >= 0 && x <= 255); SlWriteByte(x);break;
case SLE_FILE_I16:assert(x >= -32768 && x <= 32767); SlWriteUint16(x);break;
case SLE_FILE_STRINGID:
case SLE_FILE_U16:assert(x >= 0 && x <= 65535); SlWriteUint16(x);break;
case SLE_FILE_I32:
case SLE_FILE_U32: SlWriteUint32((uint32)x);break;
case SLE_FILE_I64:
case SLE_FILE_U64: SlWriteUint64(x);break;
default: NOT_REACHED();
}
break;
}
case SLA_LOAD_CHECK:
case SLA_LOAD: {
int64 x;
/* Read a value from the file */
switch (GetVarFileType(conv)) {
case SLE_FILE_I8: x = (int8 )SlReadByte(); break;
case SLE_FILE_U8: x = (byte )SlReadByte(); break;
case SLE_FILE_I16: x = (int16 )SlReadUint16(); break;
case SLE_FILE_U16: x = (uint16)SlReadUint16(); break;
case SLE_FILE_I32: x = (int32 )SlReadUint32(); break;
case SLE_FILE_U32: x = (uint32)SlReadUint32(); break;
case SLE_FILE_I64: x = (int64 )SlReadUint64(); break;
case SLE_FILE_U64: x = (uint64)SlReadUint64(); break;
case SLE_FILE_STRINGID: x = RemapOldStringID((uint16)SlReadUint16()); break;
default: NOT_REACHED();
}
/* Write The value to the struct. These ARE endian safe. */
WriteValue(ptr, conv, x);
break;
}
case SLA_PTRS: break;
case SLA_NULL: break;
default: NOT_REACHED();
}
}
/**
* Calculate the net length of a string. This is in almost all cases
* just strlen(), but if the string is not properly terminated, we'll
* resort to the maximum length of the buffer.
* @param ptr pointer to the stringbuffer
* @param length maximum length of the string (buffer). If -1 we don't care
* about a maximum length, but take string length as it is.
* @return return the net length of the string
*/
static inline size_t SlCalcNetStringLen(const char *ptr, size_t length)
{
if (ptr == nullptr) return 0;
return min(strlen(ptr), length - 1);
}
/**
* Calculate the gross length of the string that it
* will occupy in the savegame. This includes the real length, returned
* by SlCalcNetStringLen and the length that the index will occupy.
* @param ptr pointer to the stringbuffer
* @param length maximum length of the string (buffer size, etc.)
* @param conv type of data been used
* @return return the gross length of the string
*/
static inline size_t SlCalcStringLen(const void *ptr, size_t length, VarType conv)
{
size_t len;
const char *str;
switch (GetVarMemType(conv)) {
default: NOT_REACHED();
case SLE_VAR_STR:
case SLE_VAR_STRQ:
str = *(const char * const *)ptr;
len = SIZE_MAX;
break;
case SLE_VAR_STRB:
case SLE_VAR_STRBQ:
str = (const char *)ptr;
len = length;
break;
}
len = SlCalcNetStringLen(str, len);
return len + SlGetArrayLength(len); // also include the length of the index
}
/**
* Save/Load a string.
* @param ptr the string being manipulated
* @param length of the string (full length)
* @param conv must be SLE_FILE_STRING
*/
static void SlString(void *ptr, size_t length, VarType conv)
{
switch (_sl.action) {
case SLA_SAVE: {
size_t len;
switch (GetVarMemType(conv)) {
default: NOT_REACHED();
case SLE_VAR_STRB:
case SLE_VAR_STRBQ:
len = SlCalcNetStringLen((char *)ptr, length);
break;
case SLE_VAR_STR:
case SLE_VAR_STRQ:
ptr = *(char **)ptr;
len = SlCalcNetStringLen((char *)ptr, SIZE_MAX);
break;
}
SlWriteArrayLength(len);
SlCopyBytes(ptr, len);
break;
}
case SLA_LOAD_CHECK:
case SLA_LOAD: {
size_t len = SlReadArrayLength();
switch (GetVarMemType(conv)) {
default: NOT_REACHED();
case SLE_VAR_STRB:
case SLE_VAR_STRBQ:
if (len >= length) {
DEBUG(sl, 1, "String length in savegame is bigger than buffer, truncating");
SlCopyBytes(ptr, length);
SlSkipBytes(len - length);
len = length - 1;
} else {
SlCopyBytes(ptr, len);
}
break;
case SLE_VAR_STR:
case SLE_VAR_STRQ: // Malloc'd string, free previous incarnation, and allocate
free(*(char **)ptr);
if (len == 0) {
*(char **)ptr = nullptr;
return;
} else {
*(char **)ptr = MallocT<char>(len + 1); // terminating '\0'
ptr = *(char **)ptr;
SlCopyBytes(ptr, len);
}
break;
}
((char *)ptr)[len] = '\0'; // properly terminate the string
StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK;
if ((conv & SLF_ALLOW_CONTROL) != 0) {
settings = settings | SVS_ALLOW_CONTROL_CODE;
if (IsSavegameVersionBefore(SLV_169)) {
str_fix_scc_encoded((char *)ptr, (char *)ptr + len);
}
}
if ((conv & SLF_ALLOW_NEWLINE) != 0) {
settings = settings | SVS_ALLOW_NEWLINE;
}
str_validate((char *)ptr, (char *)ptr + len, settings);
break;
}
case SLA_PTRS: break;
case SLA_NULL: break;
default: NOT_REACHED();
}
}
/**
* Return the size in bytes of a certain type of atomic array
* @param length The length of the array counted in elements
* @param conv VarType type of the variable that is used in calculating the size
*/
static inline size_t SlCalcArrayLen(size_t length, VarType conv)
{
return SlCalcConvFileLen(conv) * length;
}
/**
* Save/Load an array.
* @param array The array being manipulated
* @param length The length of the array in elements
* @param conv VarType type of the atomic array (int, byte, uint64, etc.)
*/
void SlArray(void *array, size_t length, VarType conv)
{
if (_sl.action == SLA_PTRS || _sl.action == SLA_NULL) return;