summaryrefslogtreecommitdiff
path: root/src/gamelog.cpp
blob: b57f7a47ac08e40bedc3751c1bf295f68b855064 (plain)
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
/* $Id$ */

/** @file gamelog.cpp Definition of functions used for logging of important changes in the game */

#include "stdafx.h"
#include "openttd.h"
#include "saveload.h"
#include "core/alloc_func.hpp"
#include "core/bitmath_func.hpp"
#include "core/math_func.hpp"
#include "network/core/config.h"
#include "variables.h"
#include "string_func.h"
#include "settings_type.h"
#include "newgrf_config.h"
#include <string.h>
#include <stdarg.h>
#include "gamelog.h"
#include "console_func.h"
#include "debug.h"
#include "rev.h"

extern const uint16 SAVEGAME_VERSION;  ///< current savegame version

extern SavegameType _savegame_type; ///< type of savegame we are loading

extern uint32 _ttdp_version;     ///< version of TTDP savegame (if applicable)
extern uint16 _sl_version;       ///< the major savegame version identifier
extern byte   _sl_minor_version; ///< the minor savegame version, DO NOT USE!

/** Type of logged change */
enum GamelogChangeType {
	GLCT_MODE,        ///< Scenario editor x Game, different landscape
	GLCT_REVISION,    ///< Changed game revision string
	GLCT_OLDVER,      ///< Loaded from savegame without logged data
	GLCT_PATCH,       ///< Non-networksafe patch value changed
	GLCT_GRFADD,      ///< Removed GRF
	GLCT_GRFREM,      ///< Added GRF
	GLCT_GRFCOMPAT,   ///< Loading compatible GRF
	GLCT_GRFPARAM,    ///< GRF parameter changed
	GLCT_GRFMOVE,     ///< GRF order changed
	GLCT_GRFBUG,      ///< GRF bug triggered
	GLCT_END,         ///< So we know how many GLCTs are there
	GLCT_NONE = 0xFF, ///< In savegames, end of list
};


/** Contains information about one logged change */
struct LoggedChange {
	GamelogChangeType ct; ///< Type of change logged in this struct
	union {
		struct {
			byte mode;       ///< new game mode - Editor x Game
			byte landscape;  ///< landscape (temperate, arctic, ...)
		} mode;
		struct {
			char text[NETWORK_REVISION_LENGTH]; ///< revision string, _openttd_revision
			uint32 newgrf;   ///< _openttd_newgrf_version
			uint16 slver;    ///< _sl_version
			byte modified;   ///< _openttd_revision_modified
		} revision;
		struct {
			uint32 type;     ///< type of savegame, @see SavegameType
			uint32 version;  ///< major and minor version OR ttdp version
		} oldver;
		GRFIdentifier grfadd;    ///< ID and md5sum of added GRF
		struct {
			uint32 grfid;    ///< ID of removed GRF
		} grfrem;
		GRFIdentifier grfcompat; ///< ID and new md5sum of changed GRF
		struct {
			uint32 grfid;    ///< ID of GRF with changed parameters
		} grfparam;
		struct {
			uint32 grfid;    ///< ID of moved GRF
			int32 offset;    ///< offset, positive = move down
		} grfmove;
		struct {
			char *name;      ///< name of the patch
			int32 oldval;    ///< old value
			int32 newval;    ///< new value
		} patch;
		struct {
			uint64 data;     ///< additional data
			uint32 grfid;    ///< ID of problematic GRF
			byte bug;        ///< type of bug, @see enum GRFBugs
		} grfbug;
	};
};


/** Contains information about one logged action that caused at least one logged change */
struct LoggedAction {
	LoggedChange *change; ///< First logged change in this action
	uint32 changes;       ///< Number of changes in this action
	GamelogActionType at; ///< Type of action
	uint16 tick;          ///< Tick when it happened
};

static GamelogActionType _gamelog_action_type = GLAT_NONE; ///< action to record if anything changes

static LoggedAction *_gamelog_action = NULL; ///< first logged action
static uint _gamelog_actions         = 0;    ///< number of actions
static LoggedAction *_current_action = NULL; ///< current action we are logging, NULL when there is no action active


/** Stores information about new action, but doesn't allocate it
 * Action is allocated only when there is at least one change
 * @param at type of action
 */
void GamelogStartAction(GamelogActionType at)
{
	assert(_gamelog_action_type == GLAT_NONE); // do not allow starting new action without stopping the previous first
	_gamelog_action_type = at;
}

/** Stops logging of any changes
 */
void GamelogStopAction()
{
	assert(_gamelog_action_type != GLAT_NONE); // nobody should try to stop if there is no action in progress

	bool print = _current_action != NULL;

	_current_action = NULL;
	_gamelog_action_type = GLAT_NONE;

	if (print) GamelogPrintDebug(5);
}

/** Resets and frees all memory allocated - used before loading or starting a new game
 */
void GamelogReset()
{
	assert(_gamelog_action_type == GLAT_NONE);

	for (uint i = 0; i < _gamelog_actions; i++) {
		const LoggedAction *la = &_gamelog_action[i];
		for (uint j = 0; j < la->changes; j++) {
			const LoggedChange *lc = &la->change[j];
			if (lc->ct == GLCT_PATCH) free(lc->patch.name);
		}
		free(la->change);
	}

	free(_gamelog_action);

	_gamelog_action  = NULL;
	_gamelog_actions = 0;
	_current_action  = NULL;
}

enum {
	GAMELOG_BUF_LEN = 1024 ///< length of buffer for one line of text
};

static int _dbgofs = 0; ///< offset in current output buffer

static void AddDebugText(char *buf, const char *s, ...)
{
	if (GAMELOG_BUF_LEN <= _dbgofs) return;

	va_list va;

	va_start(va, s);
	_dbgofs += vsnprintf(buf + _dbgofs, GAMELOG_BUF_LEN - _dbgofs, s, va);
	va_end(va);
}


/** Prints GRF filename if found
 * @param grfid GRF which filename to print
 */
static void PrintGrfFilename(char *buf, uint grfid)
{
	const GRFConfig *gc = FindGRFConfig(grfid);

	if (gc == NULL) return;

	AddDebugText(buf, ", filename: %s", gc->filename);
}

/** Prints GRF ID, checksum and filename if found
 * @param grfid GRF ID
 * @param md5sum array of md5sum to print
 */
static void PrintGrfInfo(char *buf, uint grfid, const uint8 *md5sum)
{
	char txt[40];

	md5sumToString(txt, lastof(txt), md5sum);

	AddDebugText(buf, "GRF ID %08X, checksum %s", BSWAP32(grfid), txt);

	PrintGrfFilename(buf, grfid);

	return;
}


/** Text messages for various logged actions */
static const char *la_text[] = {
	"new game started",
	"game loaded",
	"GRF config changed",
	"cheat was used",
	"patch settings changed",
	"GRF bug triggered",
};

assert_compile(lengthof(la_text) == GLAT_END);


/** Prints active gamelog */
void GamelogPrint(GamelogPrintProc *proc)
{
	char buf[GAMELOG_BUF_LEN];

	proc("---- gamelog start ----");

	const LoggedAction *laend = &_gamelog_action[_gamelog_actions];

	for (const LoggedAction *la = _gamelog_action; la != laend; la++) {
		assert((uint)la->at < GLAT_END);

		snprintf(buf, GAMELOG_BUF_LEN, "Tick %u: %s", (uint)la->tick, la_text[(uint)la->at]);
		proc(buf);

		const LoggedChange *lcend = &la->change[la->changes];

		for (const LoggedChange *lc = la->change; lc != lcend; lc++) {
			_dbgofs = 0;
			AddDebugText(buf, "     ");

			switch (lc->ct) {
				default: NOT_REACHED();
				case GLCT_MODE:
					AddDebugText(buf, "New game mode: %u landscape: %u",
						(uint)lc->mode.mode, (uint)lc->mode.landscape);
					break;

				case GLCT_REVISION:
					AddDebugText(buf, "Revision text changed to %s, savegame version %u, ",
						lc->revision.text, lc->revision.slver);

					switch (lc->revision.modified) {
						case 0: AddDebugText(buf, "not "); break;
						case 1: AddDebugText(buf, "maybe "); break;
						default: break;
					}

					AddDebugText(buf, "modified, _openttd_newgrf_version = 0x%08x", lc->revision.newgrf);
					break;

				case GLCT_OLDVER:
					AddDebugText(buf, "Conversion from ");
					switch (lc->oldver.type) {
						default: NOT_REACHED();
						case SGT_OTTD:
							AddDebugText(buf, "OTTD savegame without gamelog: version %u, %u",
								GB(lc->oldver.version, 8, 16), GB(lc->oldver.version, 0, 8));
							break;

						case SGT_TTD:
							AddDebugText(buf, "TTD savegame");
							break;

						case SGT_TTDP1:
						case SGT_TTDP2:
							AddDebugText(buf, "TTDP savegame, %s format",
								lc->oldver.type == SGT_TTDP1 ? "old" : "new");
							if (lc->oldver.version != 0) {
								AddDebugText(buf, ", TTDP version %u.%u.%u.%u",
									GB(lc->oldver.version, 24, 8), GB(lc->oldver.version, 20, 4),
									GB(lc->oldver.version, 16, 4), GB(lc->oldver.version, 0, 16));
							}
							break;
					}
					break;

				case GLCT_PATCH:
					AddDebugText(buf, "Patch setting changed: %s : %d -> %d", lc->patch.name, lc->patch.oldval, lc->patch.newval);
					break;

				case GLCT_GRFADD:
					AddDebugText(buf, "Added NewGRF: ");
					PrintGrfInfo(buf, lc->grfadd.grfid, lc->grfadd.md5sum);
					break;

				case GLCT_GRFREM:
					AddDebugText(buf, "Removed NewGRF: %08X", BSWAP32(lc->grfrem.grfid));
					PrintGrfFilename(buf, lc->grfrem.grfid);
					break;

				case GLCT_GRFCOMPAT:
					AddDebugText(buf, "Compatible NewGRF loaded: ");
					PrintGrfInfo(buf, lc->grfcompat.grfid, lc->grfcompat.md5sum);
					break;

				case GLCT_GRFPARAM:
					AddDebugText(buf, "GRF parameter changed: %08X", BSWAP32(lc->grfparam.grfid));
					PrintGrfFilename(buf, lc->grfparam.grfid);
					break;

				case GLCT_GRFMOVE:
					AddDebugText(buf, "GRF order changed: %08X moved %d places %s",
						BSWAP32(lc->grfmove.grfid), abs(lc->grfmove.offset), lc->grfmove.offset >= 0 ? "down" : "up" );
					PrintGrfFilename(buf, lc->grfmove.grfid);
					break;

				case GLCT_GRFBUG:
					switch (lc->grfbug.bug) {
						default: NOT_REACHED();
						case GBUG_VEH_LENGTH:
							AddDebugText(buf, "Rail vehicle changes length outside a depot: GRF ID %08X, internal ID 0x%X", BSWAP32(lc->grfbug.grfid), (uint)lc->grfbug.data);
							PrintGrfFilename(buf, lc->grfbug.grfid);
							break;
					}
			}

			proc(buf);
		}
	}

	proc("---- gamelog end ----");
}


static void GamelogPrintConsoleProc(const char *s)
{
	IConsolePrint(CC_WARNING, s);
}

void GamelogPrintConsole()
{
	GamelogPrint(&GamelogPrintConsoleProc);
}

static int _gamelog_print_level = 0; ///< gamelog debug level we need to print stuff

static void GamelogPrintDebugProc(const char *s)
{
	DEBUG(gamelog, _gamelog_print_level, s);
}


/** Prints gamelog to debug output. Code is executed even when
 * there will be no output. It is called very seldom, so it
 * doesn't matter that much. At least it gives more uniform code...
 * @param level debug level we need to print stuff
 */
void GamelogPrintDebug(int level)
{
	_gamelog_print_level = level;
	GamelogPrint(&GamelogPrintDebugProc);
}


/** Allocates new LoggedChange and new LoggedAction if needed.
 * If there is no action active, NULL is returned.
 * @param ct type of change
 * @return new LoggedChange, or NULL if there is no action active
 */
static LoggedChange *GamelogChange(GamelogChangeType ct)
{
	if (_current_action == NULL) {
		if (_gamelog_action_type == GLAT_NONE) return NULL;

		_gamelog_action  = ReallocT(_gamelog_action, _gamelog_actions + 1);
		_current_action  = &_gamelog_action[_gamelog_actions++];

		_current_action->at      = _gamelog_action_type;
		_current_action->tick    = _tick_counter;
		_current_action->change  = NULL;
		_current_action->changes = 0;
	}

	_current_action->change = ReallocT(_current_action->change, _current_action->changes + 1);

	LoggedChange *lc = &_current_action->change[_current_action->changes++];
	lc->ct = ct;

	return lc;
}


/** Logs a change in game revision
 * @param revision new revision string
 */
void GamelogRevision()
{
	assert(_gamelog_action_type == GLAT_START || _gamelog_action_type == GLAT_LOAD);

	LoggedChange *lc = GamelogChange(GLCT_REVISION);
	if (lc == NULL) return;

	strecpy(lc->revision.text, _openttd_revision, lastof(lc->revision.text));
	lc->revision.slver = SAVEGAME_VERSION;
	lc->revision.modified = _openttd_revision_modified;
	lc->revision.newgrf = _openttd_newgrf_version;
}

/** Logs a change in game mode (scenario editor or game)
 */
void GamelogMode()
{
	assert(_gamelog_action_type == GLAT_START || _gamelog_action_type == GLAT_LOAD || _gamelog_action_type == GLAT_CHEAT);

	LoggedChange *lc = GamelogChange(GLCT_MODE);
	if (lc == NULL) return;

	lc->mode.mode      = _game_mode;
	lc->mode.landscape = _settings_game.game_creation.landscape;
}

/** Logs loading from savegame without gamelog
 */
void GamelogOldver()
{
	assert(_gamelog_action_type == GLAT_LOAD);

	LoggedChange *lc = GamelogChange(GLCT_OLDVER);
	if (lc == NULL) return;

	lc->oldver.type = _savegame_type;
	lc->oldver.version = (_savegame_type == SGT_OTTD ? ((uint32)_sl_version << 8 | _sl_minor_version) : _ttdp_version);
}

/** Logs change in game patches. Only non-networksafe patches are logged
 * @param name patch name
 * @param oldval old patch value
 * @param newval new patch value
 */
void GamelogPatch(const char *name, int32 oldval, int32 newval)
{
	assert(_gamelog_action_type == GLAT_PATCH);

	LoggedChange *lc = GamelogChange(GLCT_PATCH);
	if (lc == NULL) return;

	lc->patch.name = strdup(name);
	lc->patch.oldval = oldval;
	lc->patch.newval = newval;
}


/** Finds out if current revision is different than last revision stored in the savegame.
 * Appends GLCT_REVISION when the revision string changed
 */
void GamelogTestRevision()
{
	const LoggedChange *rev = NULL;

	const LoggedAction *laend = &_gamelog_action[_gamelog_actions];
	for (const LoggedAction *la = _gamelog_action; la != laend; la++) {
		const LoggedChange *lcend = &la->change[la->changes];
		for (const LoggedChange *lc = la->change; lc != lcend; lc++) {
			if (lc->ct == GLCT_REVISION) rev = lc;
		}
	}

	if (rev == NULL || strcmp(rev->revision.text, _openttd_revision) != 0 ||
			rev->revision.modified != _openttd_revision_modified ||
			rev->revision.newgrf != _openttd_newgrf_version) {
		GamelogRevision();
	}
}

/** Finds last stored game mode or landscape.
 * Any change is logged
 */
void GamelogTestMode()
{
	const LoggedChange *mode = NULL;

	const LoggedAction *laend = &_gamelog_action[_gamelog_actions];
	for (const LoggedAction *la = _gamelog_action; la != laend; la++) {
		const LoggedChange *lcend = &la->change[la->changes];
		for (const LoggedChange *lc = la->change; lc != lcend; lc++) {
			if (lc->ct == GLCT_MODE) mode = lc;
		}
	}

	if (mode == NULL || mode->mode.mode != _game_mode || mode->mode.landscape != _settings_game.game_creation.landscape) GamelogMode();
}


/** Logs triggered GRF bug.
 * @param grfid ID of problematic GRF
 * @param bug type of bug, @see enum GRFBugs
 * @param data additional data
 */
static void GamelogGRFBug(uint32 grfid, byte bug, uint64 data)
{
	assert(_gamelog_action_type == GLAT_GRFBUG);

	LoggedChange *lc = GamelogChange(GLCT_GRFBUG);
	if (lc == NULL) return;

	lc->grfbug.data  = data;
	lc->grfbug.grfid = grfid;
	lc->grfbug.bug   = bug;
}

/** Logs GRF bug - rail vehicle has different length after reversing.
 * Ensures this is logged only once for each GRF and engine type
 * This check takes some time, but it is called pretty seldom, so it
 * doesn't matter that much (ideally it shouldn't be called at all).
 * @param engine engine to log
 * @return true iff a unique record was done
 */
bool GamelogGRFBugReverse(uint32 grfid, uint16 internal_id)
{
	const LoggedAction *laend = &_gamelog_action[_gamelog_actions];
	for (const LoggedAction *la = _gamelog_action; la != laend; la++) {
		const LoggedChange *lcend = &la->change[la->changes];
		for (const LoggedChange *lc = la->change; lc != lcend; lc++) {
			if (lc->ct == GLCT_GRFBUG && lc->grfbug.grfid == grfid &&
					lc->grfbug.bug == GBUG_VEH_LENGTH && lc->grfbug.data == internal_id) {
				return false;
			}
		}
	}

	GamelogStartAction(GLAT_GRFBUG);
	GamelogGRFBug(grfid, GBUG_VEH_LENGTH, internal_id);
	GamelogStopAction();

	return true;
}


/** Decides if GRF should be logged
 * @param g grf to determine
 * @return true iff GRF is not static and is loaded
 */
static inline bool IsLoggableGrfConfig(const GRFConfig *g)
{
	return !HasBit(g->flags, GCF_STATIC) && g->status != GCS_NOT_FOUND;
}

/** Logs removal of a GRF
 * @param grfid ID of removed GRF
 */
void GamelogGRFRemove(uint32 grfid)
{
	assert(_gamelog_action_type == GLAT_LOAD || _gamelog_action_type == GLAT_GRF);

	LoggedChange *lc = GamelogChange(GLCT_GRFREM);
	if (lc == NULL) return;

	lc->grfrem.grfid = grfid;
}

/** Logs adding of a GRF
 * @param newg added GRF
 */
void GamelogGRFAdd(const GRFConfig *newg)
{
	assert(_gamelog_action_type == GLAT_LOAD || _gamelog_action_type == GLAT_START || _gamelog_action_type == GLAT_GRF);

	if (!IsLoggableGrfConfig(newg)) return;

	LoggedChange *lc = GamelogChange(GLCT_GRFADD);
	if (lc == NULL) return;

	memcpy(&lc->grfadd, newg, sizeof(GRFIdentifier));
}

/** Logs loading compatible GRF
 * (the same ID, but different MD5 hash)
 * @param newg new (updated) GRF
 */
void GamelogGRFCompatible(const GRFIdentifier *newg)
{
	assert(_gamelog_action_type == GLAT_LOAD || _gamelog_action_type == GLAT_GRF);

	LoggedChange *lc = GamelogChange(GLCT_GRFCOMPAT);
	if (lc == NULL) return;

	memcpy(&lc->grfcompat, newg, sizeof(GRFIdentifier));
}

/** Logs changing GRF order
 * @param grfid GRF that is moved
 * @param offset how far it is moved, positive = moved down
 */
static void GamelogGRFMove(uint32 grfid, int32 offset)
{
	assert(_gamelog_action_type == GLAT_GRF);

	LoggedChange *lc = GamelogChange(GLCT_GRFMOVE);
	if (lc == NULL) return;

	lc->grfmove.grfid  = grfid;
	lc->grfmove.offset = offset;
}

/** Logs change in GRF parameters.
 * Details about parameters changed are not stored
 * @param grfid ID of GRF to store
 */
static void GamelogGRFParameters(uint32 grfid)
{
	assert(_gamelog_action_type == GLAT_GRF);

	LoggedChange *lc = GamelogChange(GLCT_GRFPARAM);
	if (lc == NULL) return;

	lc->grfparam.grfid = grfid;
}

/** Logs adding of list of GRFs.
 * Useful when old savegame is loaded or when new game is started
 * @param newg head of GRF linked list
 */
void GamelogGRFAddList(const GRFConfig *newg)
{
	assert(_gamelog_action_type == GLAT_START || _gamelog_action_type == GLAT_LOAD);

	for (; newg != NULL; newg = newg->next) {
		GamelogGRFAdd(newg);
	}
}

/** List of GRFs using array of pointers instead of linked list */
struct GRFList {
	uint n;
	const GRFConfig *grf[VARARRAY_SIZE];
};

/** Generates GRFList
 * @param grfc head of GRF linked list
 */
static GRFList *GenerateGRFList(const GRFConfig *grfc)
{
	uint n = 0;
	for (const GRFConfig *g = grfc; g != NULL; g = g->next) {
		if (IsLoggableGrfConfig(g)) n++;
	}

	GRFList *list = (GRFList*)MallocT<byte>(sizeof(GRFList) + n * sizeof(GRFConfig*));

	list->n = 0;
	for (const GRFConfig *g = grfc; g != NULL; g = g->next) {
		if (IsLoggableGrfConfig(g)) list->grf[list->n++] = g;
	}

	return list;
}

/** Compares two NewGRF lists and logs any change
 * @param oldc original GRF list
 * @param newc new GRF list
 */
void GamelogGRFUpdate(const GRFConfig *oldc, const GRFConfig *newc)
{
	GRFList *ol = GenerateGRFList(oldc);
	GRFList *nl = GenerateGRFList(newc);

	uint o = 0, n = 0;

	while (o < ol->n && n < nl->n) {
		const GRFConfig *og = ol->grf[o];
		const GRFConfig *ng = nl->grf[n];

		if (og->grfid != ng->grfid) {
			uint oi, ni;
			for (oi = 0; oi < ol->n; oi++) {
				if (ol->grf[oi]->grfid == nl->grf[n]->grfid) break;
			}
			if (oi < o) {
				/* GRF was moved, this change has been logged already */
				n++;
				continue;
			}
			if (oi == ol->n) {
				/* GRF couldn't be found in the OLD list, GRF was ADDED */
				GamelogGRFAdd(nl->grf[n++]);
				continue;
			}
			for (ni = 0; ni < nl->n; ni++) {
				if (nl->grf[ni]->grfid == ol->grf[o]->grfid) break;
			}
			if (ni < n) {
				/* GRF was moved, this change has been logged already */
				o++;
				continue;
			}
			if (ni == nl->n) {
				/* GRF couldn't be found in the NEW list, GRF was REMOVED */
				GamelogGRFRemove(ol->grf[o++]->grfid);
				continue;
			}

			/* o < oi < ol->n
			 * n < ni < nl->n */
			assert(ni > n && ni < nl->n);
			assert(oi > o && oi < ol->n);

			ni -= n; // number of GRFs it was moved downwards
			oi -= o; // number of GRFs it was moved upwards

			if (ni >= oi) { // prefer the one that is moved further
				/* GRF was moved down */
				GamelogGRFMove(ol->grf[o++]->grfid, ni);
			} else {
				GamelogGRFMove(nl->grf[n++]->grfid, -(int)oi);
			}
		} else {
			if (memcmp(og->md5sum, ng->md5sum, sizeof(og->md5sum)) != 0) {
				/* md5sum changed, probably loading 'compatible' GRF */
				GamelogGRFCompatible(nl->grf[n]);
			}

			if (og->num_params != ng->num_params || memcmp(og->param, ng->param, og->num_params * sizeof(og->param[0])) != 0) {
				GamelogGRFParameters(ol->grf[o]->grfid);
			}

			o++;
			n++;
		}
	}

	while (o < ol->n) GamelogGRFRemove(ol->grf[o++]->grfid); // remaining GRFs were removed ...
	while (n < nl->n) GamelogGRFAdd   (nl->grf[n++]);    // ... or added

	free(ol);
	free(nl);
}


static const SaveLoad _glog_action_desc[] = {
	SLE_VAR(LoggedAction, tick,              SLE_UINT16),
	SLE_END()
};

static const SaveLoad _glog_mode_desc[] = {
	SLE_VAR(LoggedChange, mode.mode,         SLE_UINT8),
	SLE_VAR(LoggedChange, mode.landscape,    SLE_UINT8),
	SLE_END()
};

static const SaveLoad _glog_revision_desc[] = {
	SLE_ARR(LoggedChange, revision.text,     SLE_UINT8,  NETWORK_REVISION_LENGTH),
	SLE_VAR(LoggedChange, revision.newgrf,   SLE_UINT32),
	SLE_VAR(LoggedChange, revision.slver,    SLE_UINT16),
	SLE_VAR(LoggedChange, revision.modified, SLE_UINT8),
	SLE_END()
};

static const SaveLoad _glog_oldver_desc[] = {
	SLE_VAR(LoggedChange, oldver.type,       SLE_UINT32),
	SLE_VAR(LoggedChange, oldver.version,    SLE_UINT32),
	SLE_END()
};

static const SaveLoad _glog_patch_desc[] = {
	SLE_STR(LoggedChange, patch.name,        SLE_STR,    128),
	SLE_VAR(LoggedChange, patch.oldval,      SLE_INT32),
	SLE_VAR(LoggedChange, patch.newval,      SLE_INT32),
	SLE_END()
};

static const SaveLoad _glog_grfadd_desc[] = {
	SLE_VAR(LoggedChange, grfadd.grfid,      SLE_UINT32    ),
	SLE_ARR(LoggedChange, grfadd.md5sum,     SLE_UINT8,  16),
	SLE_END()
};

static const SaveLoad _glog_grfrem_desc[] = {
	SLE_VAR(LoggedChange, grfrem.grfid,      SLE_UINT32),
	SLE_END()
};

static const SaveLoad _glog_grfcompat_desc[] = {
	SLE_VAR(LoggedChange, grfcompat.grfid,   SLE_UINT32    ),
	SLE_ARR(LoggedChange, grfcompat.md5sum,  SLE_UINT8,  16),
	SLE_END()
};

static const SaveLoad _glog_grfparam_desc[] = {
	SLE_VAR(LoggedChange, grfparam.grfid,    SLE_UINT32),
	SLE_END()
};

static const SaveLoad _glog_grfmove_desc[] = {
	SLE_VAR(LoggedChange, grfmove.grfid,     SLE_UINT32),
	SLE_VAR(LoggedChange, grfmove.offset,    SLE_INT32),
	SLE_END()
};

static const SaveLoad _glog_grfbug_desc[] = {
	SLE_VAR(LoggedChange, grfbug.data,       SLE_UINT64),
	SLE_VAR(LoggedChange, grfbug.grfid,      SLE_UINT32),
	SLE_VAR(LoggedChange, grfbug.bug,        SLE_UINT8),
	SLE_END()
};

static const SaveLoad *_glog_desc[] = {
	_glog_mode_desc,
	_glog_revision_desc,
	_glog_oldver_desc,
	_glog_patch_desc,
	_glog_grfadd_desc,
	_glog_grfrem_desc,
	_glog_grfcompat_desc,
	_glog_grfparam_desc,
	_glog_grfmove_desc,
	_glog_grfbug_desc,
};

assert_compile(lengthof(_glog_desc) == GLCT_END);

static void Load_GLOG()
{
	assert(_gamelog_action == NULL);
	assert(_gamelog_actions == 0);

	GamelogActionType at;
	while ((at = (GamelogActionType)SlReadByte()) != GLAT_NONE) {
		_gamelog_action = ReallocT(_gamelog_action, _gamelog_actions + 1);
		LoggedAction *la = &_gamelog_action[_gamelog_actions++];

		la->at = at;

		SlObject(la, _glog_action_desc); // has to be saved after 'DATE'!
		la->change = NULL;
		la->changes = 0;

		GamelogChangeType ct;
		while ((ct = (GamelogChangeType)SlReadByte()) != GLCT_NONE) {
			la->change = ReallocT(la->change, la->changes + 1);

			LoggedChange *lc = &la->change[la->changes++];
			/* for SLE_STR, pointer has to be valid! so make it NULL */
			memset(lc, 0, sizeof(*lc));
			lc->ct = ct;

			assert((uint)ct < GLCT_END);

			SlObject(lc, _glog_desc[ct]);
		}
	}
}

static void Save_GLOG()
{
	const LoggedAction *laend = &_gamelog_action[_gamelog_actions];
	size_t length = 0;

	for (const LoggedAction *la = _gamelog_action; la != laend; la++) {
		const LoggedChange *lcend = &la->change[la->changes];
		for (LoggedChange *lc = la->change; lc != lcend; lc++) {
			assert((uint)lc->ct < lengthof(_glog_desc));
			length += SlCalcObjLength(lc, _glog_desc[lc->ct]) + 1;
		}
		length += 4;
	}
	length++;

	SlSetLength(length);

	for (LoggedAction *la = _gamelog_action; la != laend; la++) {
		SlWriteByte(la->at);
		SlObject(la, _glog_action_desc);

		const LoggedChange *lcend = &la->change[la->changes];
		for (LoggedChange *lc = la->change; lc != lcend; lc++) {
			SlWriteByte(lc->ct);
			assert((uint)lc->ct < GLCT_END);
			SlObject(lc, _glog_desc[lc->ct]);
		}
		SlWriteByte(GLCT_NONE);
	}
	SlWriteByte(GLAT_NONE);
}


extern const ChunkHandler _gamelog_chunk_handlers[] = {
	{ 'GLOG', Save_GLOG, Load_GLOG, CH_RIFF | CH_LAST }
};