summaryrefslogtreecommitdiff
path: root/engine.c
blob: 0ed802637d1cdc681ec8e37e775535980ab16480 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
/* $Id$ */

#include "stdafx.h"
#include "openttd.h"
#include "debug.h"
#include "functions.h"
#include "string.h"
#include "strings.h"
#include "table/strings.h"
#include "engine.h"
#include "table/engines.h"
#include "gfx.h"
#include "player.h"
#include "command.h"
#include "vehicle.h"
#include "news.h"
#include "saveload.h"
#include "sprite.h"
#include "variables.h"
#include "train.h"

EngineInfo _engine_info[TOTAL_NUM_ENGINES];
RailVehicleInfo _rail_vehicle_info[NUM_TRAIN_ENGINES];
ShipVehicleInfo _ship_vehicle_info[NUM_SHIP_ENGINES];
AircraftVehicleInfo _aircraft_vehicle_info[NUM_AIRCRAFT_ENGINES];
RoadVehicleInfo _road_vehicle_info[NUM_ROAD_ENGINES];

enum {
	ENGINE_AVAILABLE = 1,
	ENGINE_INTRODUCING = 2,
	ENGINE_PREVIEWING = 4,
};

/** TRANSLATE FROM LOCAL CARGO TO GLOBAL CARGO ID'S.
 * This maps the per-landscape cargo ID's to globally unique cargo ID's usable ie. in
 * the custom GRF  files. It is basically just a transcribed table from TTDPatch's newgrf.txt.
 */
const CargoID _global_cargo_id[NUM_LANDSCAPE][NUM_CARGO] = {
	/* LT_NORMAL */ {GC_PASSENGERS, GC_COAL,  GC_MAIL, GC_OIL, GC_LIVESTOCK, GC_GOODS, GC_GRAIN, GC_WOOD, GC_IRON_ORE,    GC_STEEL,  GC_VALUABLES, GC_PAPER_TEMP},
	/* LT_HILLY */  {GC_PASSENGERS, GC_COAL,  GC_MAIL, GC_OIL, GC_LIVESTOCK, GC_GOODS, GC_GRAIN, GC_WOOD, GC_INVALID,     GC_PAPER,  GC_VALUABLES, GC_FOOD },
	/* LT_DESERT */ {GC_PASSENGERS, GC_RUBBER,GC_MAIL, GC_OIL, GC_FRUIT,     GC_GOODS, GC_GRAIN, GC_WOOD, GC_COPPER_ORE,  GC_WATER,  GC_VALUABLES, GC_FOOD },
	/* LT_CANDY */  {GC_PASSENGERS, GC_SUGAR, GC_MAIL, GC_TOYS,GC_BATTERIES, GC_CANDY, GC_TOFFEE,GC_COLA, GC_COTTON_CANDY,GC_BUBBLES,GC_PLASTIC,   GC_FIZZY_DRINKS },
	/**
	 * - GC_INVALID (255) means that  cargo is not available for that climate
	 * - GC_PAPER_TEMP (27) is paper in  temperate climate in TTDPatch
	 * Following can  be renumbered:
	 * - GC_DEFAULT (29) is the defa ult cargo for the purpose of spritesets
	 * - GC_PURCHASE (30) is the purchase list image (the equivalent of 0xff) for the purpose of spritesets
	 */
};

/** BEGIN --- TRANSLATE FROM GLOBAL CARGO TO LOCAL CARGO ID'S **/
/** Map global cargo ID's to local-cargo ID's */
const CargoID _local_cargo_id_ctype[NUM_GLOBAL_CID] = {
	CT_PASSENGERS,CT_COAL,   CT_MAIL,        CT_OIL,      CT_LIVESTOCK,CT_GOODS,  CT_GRAIN,      CT_WOOD,         /*  0- 7 */
	CT_IRON_ORE,  CT_STEEL,  CT_VALUABLES,   CT_PAPER,    CT_FOOD,     CT_FRUIT,  CT_COPPER_ORE, CT_WATER,        /*  8-15 */
	CT_RUBBER,    CT_SUGAR,  CT_TOYS,        CT_BATTERIES,CT_CANDY,    CT_TOFFEE, CT_COLA,       CT_COTTON_CANDY, /* 16-23 */
	CT_BUBBLES,   CT_PLASTIC,CT_FIZZY_DRINKS,CT_PAPER     /* unsup. */,CT_HILLY_UNUSED,                           /* 24-28 */
	CT_INVALID,   CT_INVALID                                                                                      /* 29-30 */
};

#define MC(cargo) (1 << cargo)
/** Bitmasked value where the global cargo ID is available in landscape
 * 0: LT_NORMAL, 1: LT_HILLY, 2: LT_DESERT, 3: LT_CANDY */
const uint32 _landscape_global_cargo_mask[NUM_LANDSCAPE] =
{ /* LT_NORMAL: temperate */
	MC(GC_PASSENGERS)|MC(GC_COAL)|MC(GC_MAIL)|MC(GC_OIL)|MC(GC_LIVESTOCK)|MC(GC_GOODS)|MC(GC_GRAIN)|MC(GC_WOOD)|
	MC(GC_IRON_ORE)|MC(GC_STEEL)|MC(GC_VALUABLES),
	/* LT_HILLY: arctic */
	MC(GC_PASSENGERS)|MC(GC_COAL)|MC(GC_MAIL)|MC(GC_OIL)|MC(GC_LIVESTOCK)|MC(GC_GOODS)|
	MC(GC_GRAIN)|MC(GC_WOOD)|MC(GC_VALUABLES)|MC(GC_PAPER)|MC(GC_FOOD),
	/* LT_DESERT: rainforest/desert */
	MC(GC_PASSENGERS)|MC(GC_MAIL)|MC(GC_OIL)|MC(GC_GOODS)|MC(GC_GRAIN)|MC(GC_WOOD)|
	MC(GC_VALUABLES)|MC(GC_FOOD)|MC(GC_FRUIT)|MC(GC_COPPER_ORE)|MC(GC_WATER)|MC(GC_RUBBER),
	/* LT_CANDY: toyland */
	MC(GC_PASSENGERS)|MC(GC_MAIL)|MC(GC_SUGAR)|MC(GC_TOYS)|MC(GC_BATTERIES)|MC(GC_CANDY)|
	MC(GC_TOFFEE)|MC(GC_COLA)|MC(GC_COTTON_CANDY)|MC(GC_BUBBLES)|MC(GC_PLASTIC)|MC(GC_FIZZY_DRINKS)
};
/** END   --- TRANSLATE FROM GLOBAL CARGO TO LOCAL CARGO ID'S **/

/** Bitmasked values of what type of cargo is refittable for the given vehicle-type.
 * This coupled with the landscape information (_landscape_global_cargo_mask) gives
 * us exactly what is refittable and what is not */
const uint32 _default_refitmasks[NUM_VEHICLE_TYPES] = {
	/* Trains */
	MC(GC_PASSENGERS)|MC(GC_COAL)|MC(GC_MAIL)|MC(GC_LIVESTOCK)|MC(GC_GOODS)|MC(GC_GRAIN)|MC(GC_WOOD)|MC(GC_IRON_ORE)|
	MC(GC_STEEL)|MC(GC_VALUABLES)|MC(GC_PAPER)|MC(GC_FOOD)|MC(GC_FRUIT)|MC(GC_COPPER_ORE)|MC(GC_WATER)|MC(GC_SUGAR)|
	MC(GC_TOYS)|MC(GC_CANDY)|MC(GC_TOFFEE)|MC(GC_COLA)|MC(GC_COTTON_CANDY)|MC(GC_BUBBLES)|MC(GC_PLASTIC)|MC(GC_FIZZY_DRINKS),
	/* Road vehicles (not refittable by default) */
	0,
	/* Ships */
	MC(GC_COAL)|MC(GC_MAIL)|MC(GC_LIVESTOCK)|MC(GC_GOODS)|MC(GC_GRAIN)|MC(GC_WOOD)|MC(GC_IRON_ORE)|MC(GC_STEEL)|MC(GC_VALUABLES)|
	MC(GC_PAPER)|MC(GC_FOOD)|MC(GC_FRUIT)|MC(GC_COPPER_ORE)|MC(GC_WATER)|MC(GC_RUBBER)|MC(GC_SUGAR)|MC(GC_TOYS)|MC(GC_BATTERIES)|
	MC(GC_CANDY)|MC(GC_TOFFEE)|MC(GC_COLA)|MC(GC_COTTON_CANDY)|MC(GC_BUBBLES)|MC(GC_PLASTIC)|MC(GC_FIZZY_DRINKS),
	/* Aircraft */
	MC(GC_PASSENGERS)|MC(GC_MAIL)|MC(GC_GOODS)|MC(GC_VALUABLES)|MC(GC_FOOD)|MC(GC_FRUIT)|MC(GC_SUGAR)|MC(GC_TOYS)|
	MC(GC_BATTERIES)|MC(GC_CANDY)|MC(GC_TOFFEE)|MC(GC_COLA)|MC(GC_COTTON_CANDY)|MC(GC_BUBBLES)|MC(GC_PLASTIC)|MC(GC_FIZZY_DRINKS),
	/* Special/Disaster */
	0,0
};

/**
 * Bitmask of classes for cargo types.
 */
const uint32 cargo_classes[16] = {
	/* Passengers */ MC(GC_PASSENGERS),
	/* Mail       */ MC(GC_MAIL),
	/* Express    */ MC(GC_GOODS)|MC(GC_FOOD)|MC(GC_CANDY),
	/* Armoured   */ MC(GC_VALUABLES),
	/* Bulk       */ MC(GC_COAL)|MC(GC_GRAIN)|MC(GC_IRON_ORE)|MC(GC_COPPER_ORE)|MC(GC_FRUIT)|MC(GC_SUGAR)|MC(GC_TOFFEE)|MC(GC_COTTON_CANDY),
	/* Piece      */ MC(GC_LIVESTOCK)|MC(GC_WOOD)|MC(GC_STEEL)|MC(GC_PAPER)|MC(GC_TOYS)|MC(GC_BATTERIES)|MC(GC_BUBBLES)|MC(GC_FIZZY_DRINKS),
	/* Liquids    */ MC(GC_OIL)|MC(GC_WATER)|MC(GC_RUBBER)|MC(GC_COLA)|MC(GC_PLASTIC),
	/* Chilled    */ MC(GC_FOOD)|MC(GC_FRUIT),
	/* Undefined  */ 0, 0, 0, 0, 0, 0, 0, 0
};
#undef MC

void ShowEnginePreviewWindow(EngineID engine);

void DeleteCustomEngineNames(void)
{
	uint i;
	StringID old;

	for (i = 0; i != TOTAL_NUM_ENGINES; i++) {
		old = _engine_name_strings[i];
		_engine_name_strings[i] = i + STR_8000_KIRBY_PAUL_TANK_STEAM;
		DeleteName(old);
	}

	_vehicle_design_names &= ~1;
}

void LoadCustomEngineNames(void)
{
	// XXX: not done */
	DEBUG(misc, 1) ("LoadCustomEngineNames: not done");
}

static void SetupEngineNames(void)
{
	StringID *name;

	for (name = _engine_name_strings; name != endof(_engine_name_strings); name++)
		*name = STR_SV_EMPTY;

	DeleteCustomEngineNames();
	LoadCustomEngineNames();
}

static void AdjustAvailAircraft(void)
{
	uint16 date = _date;
	byte avail = 0;
	if (date >= 12784) avail |= 2; // big airport
	if (date < 14610 || _patches.always_small_airport) avail |= 1;  // small airport
	if (date >= 15706) avail |= 4; // enable heliport

	if (avail != _avail_aircraft) {
		_avail_aircraft = avail;
		InvalidateWindow(WC_BUILD_STATION, 0);
	}
}

static void CalcEngineReliability(Engine *e)
{
	uint age = e->age;

	if (age < e->duration_phase_1) {
		uint start = e->reliability_start;
		e->reliability = age * (e->reliability_max - start) / e->duration_phase_1 + start;
	} else if ((age -= e->duration_phase_1) < e->duration_phase_2) {
		e->reliability = e->reliability_max;
	} else if ((age -= e->duration_phase_2) < e->duration_phase_3) {
		uint max = e->reliability_max;
		e->reliability = (int)age * (int)(e->reliability_final - max) / e->duration_phase_3 + max;
	} else {
		// time's up for this engine
		// make it either available to all players (if never_expire_vehicles is enabled and if it was available earlier)
		// or disable this engine completely
		e->player_avail = (_patches.never_expire_vehicles && e->player_avail)? -1 : 0;
		e->reliability = e->reliability_final;
	}
}

void AddTypeToEngines(void)
{
	Engine* e = _engines;

	do e->type = VEH_Train;    while (++e < &_engines[ROAD_ENGINES_INDEX]);
	do e->type = VEH_Road;     while (++e < &_engines[SHIP_ENGINES_INDEX]);
	do e->type = VEH_Ship;     while (++e < &_engines[AIRCRAFT_ENGINES_INDEX]);
	do e->type = VEH_Aircraft; while (++e < &_engines[TOTAL_NUM_ENGINES]);
	do e->type = VEH_Special;  while (++e < endof(_engines));
}

void StartupEngines(void)
{
	Engine *e;
	const EngineInfo *ei;

	SetupEngineNames();

	for (e = _engines, ei = _engine_info; e != endof(_engines); e++, ei++) {
		uint32 r;

		e->age = 0;
		e->railtype = ei->railtype;
		e->flags = 0;
		e->player_avail = 0;

		// The magic value of 729 days below comes from the NewGRF spec. If the
		// base intro date is before 1922 then the random number of days is not
		// added.
		r = Random();
		e->intro_date = ei->base_intro <= 729 ? ei->base_intro : GB(r, 0, 9) + ei->base_intro;
		if (e->intro_date <= _date) {
			e->age = (_date - e->intro_date) >> 5;
			e->player_avail = (byte)-1;
			e->flags |= ENGINE_AVAILABLE;
		}

		e->reliability_start = GB(r, 16, 14) + 0x7AE0;
		r = Random();
		e->reliability_max   = GB(r,  0, 14) + 0xBFFF;
		e->reliability_final = GB(r, 16, 14) + 0x3FFF;

		r = Random();
		e->duration_phase_1 = GB(r, 0, 5) + 7;
		e->duration_phase_2 = GB(r, 5, 4) + ei->base_life * 12 - 96;
		e->duration_phase_3 = GB(r, 9, 7) + 120;

		e->reliability_spd_dec = (ei->unk2&0x7F) << 2;

		/* my invented flag for something that is a wagon */
		if (ei->unk2 & 0x80) {
			e->age = 0xFFFF;
		} else {
			CalcEngineReliability(e);
		}

		e->lifelength = ei->lifelength + _patches.extend_vehicle_life;

		// prevent certain engines from ever appearing.
		if (!HASBIT(ei->climates, _opt.landscape)) {
			e->flags |= ENGINE_AVAILABLE;
			e->player_avail = 0;
		}

		/* This sets up type for the engine
		   It is needed if you want to ask the engine what type it is
		   It should hopefully be the same as when you ask a vehicle what it is
		   but using this, you can ask what type an engine number is
		   even if it is not a vehicle (yet)*/
	}

	AdjustAvailAircraft();
}

// TODO: We don't support cargo-specific wagon overrides. Pretty exotic... ;-) --pasky

typedef struct WagonOverride {
	byte *train_id;
	int trains;
	SpriteGroup *group;
} WagonOverride;

typedef struct WagonOverrides {
	int overrides_count;
	WagonOverride *overrides;
} WagonOverrides;

static WagonOverrides _engine_wagon_overrides[TOTAL_NUM_ENGINES];

void SetWagonOverrideSprites(EngineID engine, SpriteGroup *group, byte *train_id,
	int trains)
{
	WagonOverrides *wos;
	WagonOverride *wo;

	wos = &_engine_wagon_overrides[engine];
	wos->overrides_count++;
	wos->overrides = realloc(wos->overrides,
		wos->overrides_count * sizeof(*wos->overrides));

	wo = &wos->overrides[wos->overrides_count - 1];
	/* FIXME: If we are replacing an override, release original SpriteGroup
	 * to prevent leaks. But first we need to refcount the SpriteGroup.
	 * --pasky */
	wo->group = group;
	group->ref_count++;
	wo->trains = trains;
	wo->train_id = malloc(trains);
	memcpy(wo->train_id, train_id, trains);
}

static const SpriteGroup *GetWagonOverrideSpriteSet(EngineID engine, byte overriding_engine)
{
	const WagonOverrides *wos = &_engine_wagon_overrides[engine];
	int i;

	// XXX: This could turn out to be a timesink on profiles. We could
	// always just dedicate 65535 bytes for an [engine][train] trampoline
	// for O(1). Or O(logMlogN) and searching binary tree or smt. like
	// that. --pasky

	for (i = 0; i < wos->overrides_count; i++) {
		const WagonOverride *wo = &wos->overrides[i];
		int j;

		for (j = 0; j < wo->trains; j++) {
			if (wo->train_id[j] == overriding_engine)
				return wo->group;
		}
	}
	return NULL;
}

/**
 * Unload all wagon override sprite groups.
 */
void UnloadWagonOverrides(void)
{
	WagonOverrides *wos;
	WagonOverride *wo;
	EngineID engine;
	int i;

	for (engine = 0; engine < TOTAL_NUM_ENGINES; engine++) {
		wos = &_engine_wagon_overrides[engine];
		for (i = 0; i < wos->overrides_count; i++) {
			wo = &wos->overrides[i];
			UnloadSpriteGroup(&wo->group);
			free(wo->train_id);
		}
		free(wos->overrides);
		wos->overrides_count = 0;
		wos->overrides = NULL;
	}
}

// 0 - 28 are cargos, 29 is default, 30 is the advert (purchase list)
// (It isn't and shouldn't be like this in the GRF files since new cargo types
// may appear in future - however it's more convenient to store it like this in
// memory. --pasky)
static SpriteGroup *engine_custom_sprites[TOTAL_NUM_ENGINES][NUM_GLOBAL_CID];

void SetCustomEngineSprites(EngineID engine, byte cargo, SpriteGroup *group)
{
	if (engine_custom_sprites[engine][cargo] != NULL) {
		DEBUG(grf, 6)("SetCustomEngineSprites: engine `%d' cargo `%d' already has group -- removing.", engine, cargo);
		UnloadSpriteGroup(&engine_custom_sprites[engine][cargo]);
	}
	engine_custom_sprites[engine][cargo] = group;
	group->ref_count++;
}

/**
 * Unload all engine sprite groups.
 */
void UnloadCustomEngineSprites(void)
{
	EngineID engine;
	CargoID cargo;

	for (engine = 0; engine < TOTAL_NUM_ENGINES; engine++) {
		for (cargo = 0; cargo < NUM_GLOBAL_CID; cargo++) {
			if (engine_custom_sprites[engine][cargo] != NULL) {
				DEBUG(grf, 6)("UnloadCustomEngineSprites: Unloading group for engine `%d' cargo `%d'.", engine, cargo);
				UnloadSpriteGroup(&engine_custom_sprites[engine][cargo]);
			}
		}
	}
}

static int MapOldSubType(const Vehicle *v)
{
	if (v->type != VEH_Train) return v->subtype;
	if (IsTrainEngine(v)) return 0;
	if (IsFreeWagon(v)) return 4;
	return 2;
}

typedef SpriteGroup *(*resolve_callback)(const SpriteGroup *spritegroup,
	const Vehicle *veh, uint16 callback_info, void *resolve_func); /* XXX data pointer used as function pointer */

static const SpriteGroup* ResolveVehicleSpriteGroup(const SpriteGroup *spritegroup,
	const Vehicle *veh, uint16 callback_info, resolve_callback resolve_func)
{
	if (spritegroup == NULL)
		return NULL;

	//debug("spgt %d", spritegroup->type);
	switch (spritegroup->type) {
		case SGT_REAL:
		case SGT_CALLBACK:
			return spritegroup;

		case SGT_DETERMINISTIC: {
			const DeterministicSpriteGroup *dsg = &spritegroup->g.determ;
			const SpriteGroup *target;
			int value = -1;

			//debug("[%p] Having fun resolving variable %x", veh, dsg->variable);
			if (dsg->variable == 0x0C) {
				/* Callback ID */
				value = callback_info & 0xFF;
			} else if (dsg->variable == 0x10) {
				value = (callback_info >> 8) & 0xFF;
			} else if ((dsg->variable >> 6) == 0) {
				/* General property */
				value = GetDeterministicSpriteValue(dsg->variable);
			} else {
				/* Vehicle-specific property. */

				if (veh == NULL) {
					/* We are in a purchase list of something,
					 * and we are checking for something undefined.
					 * That means we should get the first target
					 * (NOT the default one). */
					if (dsg->num_ranges > 0) {
						target = dsg->ranges[0].group;
					} else {
						target = dsg->default_group;
					}
					return resolve_func(target, NULL, callback_info, resolve_func);
				}

				if (dsg->var_scope == VSG_SCOPE_PARENT) {
					/* First engine in the vehicle chain */
					if (veh->type == VEH_Train)
						veh = GetFirstVehicleInChain(veh);
				}

				if (dsg->variable == 0x40 || dsg->variable == 0x41) {
					if (veh->type == VEH_Train) {
						const Vehicle *u = GetFirstVehicleInChain(veh);
						byte chain_before = 0, chain_after = 0;

						while (u != veh) {
							chain_before++;
							if (dsg->variable == 0x41 && u->engine_type != veh->engine_type)
								chain_before = 0;
							u = u->next;
						}
						while (u->next != NULL && (dsg->variable == 0x40 || u->next->engine_type == veh->engine_type)) {
							chain_after++;
							u = u->next;
						};

						value = chain_before | chain_after << 8
						        | (chain_before + chain_after) << 16;
					} else {
						value = 1; /* 1 vehicle in the chain */
					}

				} else {
					// TTDPatch runs on little-endian arch;
					// Variable is 0x80 + offset in TTD's vehicle structure
					switch (dsg->variable - 0x80) {
#define veh_prop(id_, value_) case (id_): value = (value_); break
						veh_prop(0x00, veh->type);
						veh_prop(0x01, MapOldSubType(veh));
						veh_prop(0x04, veh->index);
						veh_prop(0x05, veh->index & 0xFF);
						/* XXX? Is THIS right? */
						veh_prop(0x0A, PackOrder(&veh->current_order));
						veh_prop(0x0B, PackOrder(&veh->current_order) & 0xff);
						veh_prop(0x0C, veh->num_orders);
						veh_prop(0x0D, veh->cur_order_index);
						veh_prop(0x10, veh->load_unload_time_rem);
						veh_prop(0x11, veh->load_unload_time_rem & 0xFF);
						veh_prop(0x12, veh->date_of_last_service);
						veh_prop(0x13, veh->date_of_last_service & 0xFF);
						veh_prop(0x14, veh->service_interval);
						veh_prop(0x15, veh->service_interval & 0xFF);
						veh_prop(0x16, veh->last_station_visited);
						veh_prop(0x17, veh->tick_counter);
						veh_prop(0x18, veh->max_speed);
						veh_prop(0x19, veh->max_speed & 0xFF);
						veh_prop(0x1F, veh->direction);
						veh_prop(0x28, veh->cur_image);
						veh_prop(0x29, veh->cur_image & 0xFF);
						veh_prop(0x32, veh->vehstatus);
						veh_prop(0x33, veh->vehstatus);
						veh_prop(0x34, veh->cur_speed);
						veh_prop(0x35, veh->cur_speed & 0xFF);
						veh_prop(0x36, veh->subspeed);
						veh_prop(0x37, veh->acceleration);
						veh_prop(0x39, veh->cargo_type);
						veh_prop(0x3A, veh->cargo_cap);
						veh_prop(0x3B, veh->cargo_cap & 0xFF);
						veh_prop(0x3C, veh->cargo_count);
						veh_prop(0x3D, veh->cargo_count & 0xFF);
						veh_prop(0x3E, veh->cargo_source); // Probably useless; so what
						veh_prop(0x3F, veh->cargo_days);
						veh_prop(0x40, veh->age);
						veh_prop(0x41, veh->age & 0xFF);
						veh_prop(0x42, veh->max_age);
						veh_prop(0x43, veh->max_age & 0xFF);
						veh_prop(0x44, veh->build_year);
						veh_prop(0x45, veh->unitnumber);
						veh_prop(0x46, veh->engine_type);
						veh_prop(0x47, veh->engine_type & 0xFF);
						veh_prop(0x48, veh->spritenum);
						veh_prop(0x49, veh->day_counter);
						veh_prop(0x4A, veh->breakdowns_since_last_service);
						veh_prop(0x4B, veh->breakdown_ctr);
						veh_prop(0x4C, veh->breakdown_delay);
						veh_prop(0x4D, veh->breakdown_chance);
						veh_prop(0x4E, veh->reliability);
						veh_prop(0x4F, veh->reliability & 0xFF);
						veh_prop(0x50, veh->reliability_spd_dec);
						veh_prop(0x51, veh->reliability_spd_dec & 0xFF);
						veh_prop(0x52, veh->profit_this_year);
						veh_prop(0x53, veh->profit_this_year & 0xFFFFFF);
						veh_prop(0x54, veh->profit_this_year & 0xFFFF);
						veh_prop(0x55, veh->profit_this_year & 0xFF);
						veh_prop(0x56, veh->profit_last_year);
						veh_prop(0x57, veh->profit_last_year & 0xFF);
						veh_prop(0x58, veh->profit_last_year);
						veh_prop(0x59, veh->profit_last_year & 0xFF);
						veh_prop(0x5A, veh->next == NULL ? INVALID_VEHICLE : veh->next->index);
						veh_prop(0x5C, veh->value);
						veh_prop(0x5D, veh->value & 0xFFFFFF);
						veh_prop(0x5E, veh->value & 0xFFFF);
						veh_prop(0x5F, veh->value & 0xFF);
						veh_prop(0x60, veh->string_id);
						veh_prop(0x61, veh->string_id & 0xFF);
						/* 00h..07h=sub image? 40h=in tunnel; actually some kind of status
						 * aircraft: >=13h when in flight
						 * train, ship: 80h=in depot
						 * rv: 0feh=in depot */
						/* TODO veh_prop(0x62, veh->???); */

						/* TODO: The rest is per-vehicle, I hope no GRF file looks so far.
						 * But they won't let us have an easy ride so surely *some* GRF
						 * file does. So someone needs to do this too. --pasky */

#undef veh_prop
					}
				}
			}

			target = value != -1 ? EvalDeterministicSpriteGroup(dsg, value) : dsg->default_group;
			//debug("Resolved variable %x: %d, %p", dsg->variable, value, callback);
			return resolve_func(target, veh, callback_info, resolve_func);
		}

		case SGT_RANDOMIZED: {
			const RandomizedSpriteGroup *rsg = &spritegroup->g.random;

			if (veh == NULL) {
				/* Purchase list of something. Show the first one. */
				assert(rsg->num_groups > 0);
				//debug("going for %p: %d", rsg->groups[0], rsg->groups[0].type);
				return resolve_func(rsg->groups[0], NULL, callback_info, resolve_func);
			}

			if (rsg->var_scope == VSG_SCOPE_PARENT) {
				/* First engine in the vehicle chain */
				if (veh->type == VEH_Train)
					veh = GetFirstVehicleInChain(veh);
			}

			return resolve_func(EvalRandomizedSpriteGroup(rsg, veh->random_bits), veh, callback_info, resolve_func);
		}

		default:
			error("I don't know how to handle such a spritegroup %d!", spritegroup->type);
			return NULL;
	}
}

static const SpriteGroup *GetVehicleSpriteGroup(EngineID engine, const Vehicle *v)
{
	const SpriteGroup *group;
	byte cargo = GC_PURCHASE;

	if (v != NULL) {
		cargo = _global_cargo_id[_opt.landscape][v->cargo_type];
		assert(cargo != GC_INVALID);
	}

	group = engine_custom_sprites[engine][cargo];

	if (v != NULL && v->type == VEH_Train) {
		const SpriteGroup *overset = GetWagonOverrideSpriteSet(engine, v->u.rail.first_engine);

		if (overset != NULL) group = overset;
	}

	return group;
}

int GetCustomEngineSprite(EngineID engine, const Vehicle *v, byte direction)
{
	const SpriteGroup *group;
	const RealSpriteGroup *rsg;
	byte cargo = GC_PURCHASE;
	byte loaded = 0;
	bool in_motion = 0;
	int totalsets, spriteset;
	int r;

	if (v != NULL) {
		int capacity = v->cargo_cap;

		cargo = _global_cargo_id[_opt.landscape][v->cargo_type];
		assert(cargo != GC_INVALID);

		if (capacity == 0) capacity = 1;
		loaded = (v->cargo_count * 100) / capacity;

		if (v->type == VEH_Train) {
			in_motion = GetFirstVehicleInChain(v)->current_order.type != OT_LOADING;
		} else {
			in_motion = v->current_order.type != OT_LOADING;
		}
	}

	group = GetVehicleSpriteGroup(engine, v);
	group = ResolveVehicleSpriteGroup(group, v, 0, (resolve_callback) ResolveVehicleSpriteGroup);

	if (group == NULL && cargo != GC_DEFAULT) {
		// This group is empty but perhaps there'll be a default one.
		group = ResolveVehicleSpriteGroup(engine_custom_sprites[engine][GC_DEFAULT], v, 0,
		                                (resolve_callback) ResolveVehicleSpriteGroup);
	}

	if (group == NULL)
		return 0;

	assert(group->type == SGT_REAL);
	rsg = &group->g.real;

	if (!rsg->sprites_per_set) {
		// This group is empty. This function users should therefore
		// look up the sprite number in _engine_original_sprites.
		return 0;
	}

	assert(rsg->sprites_per_set <= 8);
	direction %= rsg->sprites_per_set;

	totalsets = in_motion ? rsg->loaded_count : rsg->loading_count;

	// My aim here is to make it possible to visually determine absolutely
	// empty and totally full vehicles. --pasky
	if (loaded == 100 || totalsets == 1) { // full
		spriteset = totalsets - 1;
	} else if (loaded == 0 || totalsets == 2) { // empty
		spriteset = 0;
	} else { // something inbetween
		spriteset = loaded * (totalsets - 2) / 100 + 1;
		// correct possible rounding errors
		if (!spriteset)
			spriteset = 1;
		else if (spriteset == totalsets - 1)
			spriteset--;
	}

	r = (in_motion ? rsg->loaded[spriteset]->g.result.result : rsg->loading[spriteset]->g.result.result) + direction;
	return r;
}

/**
 * Check if a wagon is currently using a wagon override
 * @param v The wagon to check
 * @return true if it is using an override, false otherwise
 */
bool UsesWagonOverride(const Vehicle* v)
{
	assert(v->type == VEH_Train);
	return GetWagonOverrideSpriteSet(v->engine_type, v->u.rail.first_engine) != NULL;
}

/**
 * Evaluates a newgrf callback
 * @param callback_info info about which callback to evaluate
 *  (bit 0-7)  = CallBack id of the callback to use, see CallBackId enum
 *  (bit 8-15) = Other info some callbacks need to have, callback specific, see CallBackId enum, not used yet
 * @param engine Engine type of the vehicle to evaluate the callback for
 * @param vehicle The vehicle to evaluate the callback for, NULL if it doesnt exist (yet)
 * @return The value the callback returned, or CALLBACK_FAILED if it failed
 */
uint16 GetCallBackResult(uint16 callback_info, EngineID engine, const Vehicle *v)
{
	const SpriteGroup *group;
	byte cargo = GC_DEFAULT;

	if (v != NULL)
		cargo = _global_cargo_id[_opt.landscape][v->cargo_type];

	group = engine_custom_sprites[engine][cargo];

	if (v != NULL && v->type == VEH_Train) {
		const SpriteGroup *overset = GetWagonOverrideSpriteSet(engine, v->u.rail.first_engine);

		if (overset != NULL) group = overset;
	}

	group = ResolveVehicleSpriteGroup(group, v, callback_info, (resolve_callback) ResolveVehicleSpriteGroup);

	if (group == NULL && cargo != GC_DEFAULT) {
		// This group is empty but perhaps there'll be a default one.
		group = ResolveVehicleSpriteGroup(engine_custom_sprites[engine][GC_DEFAULT], v, callback_info,
		                                (resolve_callback) ResolveVehicleSpriteGroup);
	}

	if (group == NULL || group->type != SGT_CALLBACK)
		return CALLBACK_FAILED;

	return group->g.callback.result;
}



// Global variables are evil, yes, but we would end up with horribly overblown
// calling convention otherwise and this should be 100% reentrant.
static byte _vsg_random_triggers;
static byte _vsg_bits_to_reseed;

static const SpriteGroup *TriggerVehicleSpriteGroup(const SpriteGroup *spritegroup,
	Vehicle *veh, uint16 callback_info, resolve_callback resolve_func)
{
	if (spritegroup == NULL)
		return NULL;

	if (spritegroup->type == SGT_RANDOMIZED) {
		_vsg_bits_to_reseed |= RandomizedSpriteGroupTriggeredBits(
			&spritegroup->g.random,
			_vsg_random_triggers,
			&veh->waiting_triggers
		);
	}

	return ResolveVehicleSpriteGroup(spritegroup, veh, callback_info, resolve_func);
}

static void DoTriggerVehicle(Vehicle *veh, VehicleTrigger trigger, byte base_random_bits, bool first)
{
	const SpriteGroup *group;
	const RealSpriteGroup *rsg;
	byte new_random_bits;

	_vsg_random_triggers = trigger;
	_vsg_bits_to_reseed = 0;
	group = TriggerVehicleSpriteGroup(GetVehicleSpriteGroup(veh->engine_type, veh), veh, 0,
	                                  (resolve_callback) TriggerVehicleSpriteGroup);

	if (group == NULL && veh->cargo_type != GC_DEFAULT) {
		// This group turned out to be empty but perhaps there'll be a default one.
		group = TriggerVehicleSpriteGroup(engine_custom_sprites[veh->engine_type][GC_DEFAULT], veh, 0,
		                                  (resolve_callback) TriggerVehicleSpriteGroup);
	}

	if (group == NULL)
		return;

	assert(group->type == SGT_REAL);
	rsg = &group->g.real;

	new_random_bits = Random();
	veh->random_bits &= ~_vsg_bits_to_reseed;
	veh->random_bits |= (first ? new_random_bits : base_random_bits) & _vsg_bits_to_reseed;

	switch (trigger) {
		case VEHICLE_TRIGGER_NEW_CARGO:
			/* All vehicles in chain get ANY_NEW_CARGO trigger now.
			 * So we call it for the first one and they will recurse. */
			/* Indexing part of vehicle random bits needs to be
			 * same for all triggered vehicles in the chain (to get
			 * all the random-cargo wagons carry the same cargo,
			 * i.e.), so we give them all the NEW_CARGO triggered
			 * vehicle's portion of random bits. */
			assert(first);
			DoTriggerVehicle(GetFirstVehicleInChain(veh), VEHICLE_TRIGGER_ANY_NEW_CARGO, new_random_bits, false);
			break;
		case VEHICLE_TRIGGER_DEPOT:
			/* We now trigger the next vehicle in chain recursively.
			 * The random bits portions may be different for each
			 * vehicle in chain. */
			if (veh->next != NULL)
				DoTriggerVehicle(veh->next, trigger, 0, true);
			break;
		case VEHICLE_TRIGGER_EMPTY:
			/* We now trigger the next vehicle in chain
			 * recursively.  The random bits portions must be same
			 * for each vehicle in chain, so we give them all
			 * first chained vehicle's portion of random bits. */
			if (veh->next != NULL)
				DoTriggerVehicle(veh->next, trigger, first ? new_random_bits : base_random_bits, false);
			break;
		case VEHICLE_TRIGGER_ANY_NEW_CARGO:
			/* Now pass the trigger recursively to the next vehicle
			 * in chain. */
			assert(!first);
			if (veh->next != NULL)
				DoTriggerVehicle(veh->next, VEHICLE_TRIGGER_ANY_NEW_CARGO, base_random_bits, false);
			break;
	}
}

void TriggerVehicle(Vehicle *veh, VehicleTrigger trigger)
{
	if (trigger == VEHICLE_TRIGGER_DEPOT) {
		// store that the vehicle entered a depot this tick
		VehicleEnteredDepotThisTick(veh);
	}

	DoTriggerVehicle(veh, trigger, 0, true);
}

static char *_engine_custom_names[TOTAL_NUM_ENGINES];

void SetCustomEngineName(EngineID engine, const char *name)
{
	_engine_custom_names[engine] = strdup(name);
}

void UnloadCustomEngineNames(void)
{
	char **i;
	for (i = _engine_custom_names; i != endof(_engine_custom_names); i++) {
		free(*i);
		*i = NULL;
	}
}

StringID GetCustomEngineName(EngineID engine)
{
	if (!_engine_custom_names[engine])
		return _engine_name_strings[engine];
	ttd_strlcpy(_userstring, _engine_custom_names[engine], lengthof(_userstring));
	return STR_SPEC_USERSTRING;
}


static void AcceptEnginePreview(Engine *e, PlayerID player)
{
	Player *p = GetPlayer(player);

	assert(e->railtype < RAILTYPE_END);
	SETBIT(e->player_avail, player);
	SETBIT(p->avail_railtypes, e->railtype);

	e->preview_player = 0xFF;
	InvalidateWindowClasses(WC_BUILD_VEHICLE);
	InvalidateWindowClasses(WC_REPLACE_VEHICLE);
}

static PlayerID GetBestPlayer(PlayerID pp)
{
	const Player *p;
	int32 best_hist;
	PlayerID best_player;
	uint mask = 0;

	do {
		best_hist = -1;
		best_player = OWNER_SPECTATOR;
		FOR_ALL_PLAYERS(p) {
			if (p->is_active && p->block_preview == 0 && !HASBIT(mask, p->index) &&
					p->old_economy[0].performance_history > best_hist) {
				best_hist = p->old_economy[0].performance_history;
				best_player = p->index;
			}
		}

		if (best_player == OWNER_SPECTATOR) return OWNER_SPECTATOR;

		SETBIT(mask, best_player);
	} while (--pp != 0);

	return best_player;
}

void EnginesDailyLoop(void)
{
	EngineID i;

	if (_cur_year >= 130) return;

	for (i = 0; i != lengthof(_engines); i++) {
		Engine* e = &_engines[i];

		if (e->flags & ENGINE_INTRODUCING) {
			if (e->flags & ENGINE_PREVIEWING) {
				if (e->preview_player != 0xFF && !--e->preview_wait) {
					e->flags &= ~ENGINE_PREVIEWING;
					DeleteWindowById(WC_ENGINE_PREVIEW, i);
					e->preview_player++;
				}
 			} else if (e->preview_player != 0xFF) {
				PlayerID best_player = GetBestPlayer(e->preview_player);

				if (best_player == OWNER_SPECTATOR) {
					e->preview_player = 0xFF;
					continue;
				}

				if (!IS_HUMAN_PLAYER(best_player)) {
					/* XXX - TTDBUG: TTD has a bug here ???? */
					AcceptEnginePreview(e, best_player);
				} else {
					e->flags |= ENGINE_PREVIEWING;
					e->preview_wait = 20;
					if (IS_INTERACTIVE_PLAYER(best_player)) ShowEnginePreviewWindow(i);
				}
			}
		}
	}
}

/** Accept an engine prototype. XXX - it is possible that the top-player
 * changes while you are waiting to accept the offer? Then it becomes invalid
 * @param x,y unused
 * @param p1 engine-prototype offered
 * @param p2 unused
 */
int32 CmdWantEnginePreview(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	Engine *e;

	if (!IsEngineIndex(p1)) return CMD_ERROR;
	e = GetEngine(p1);
	if (GetBestPlayer(e->preview_player) != _current_player) return CMD_ERROR;

	if (flags & DC_EXEC) AcceptEnginePreview(e, _current_player);

	return 0;
}

// Determine if an engine type is a wagon (and not a loco)
static bool IsWagon(EngineID index)
{
	return index < NUM_TRAIN_ENGINES && RailVehInfo(index)->flags & RVI_WAGON;
}

static void NewVehicleAvailable(Engine *e)
{
	Vehicle *v;
	Player *p;
	EngineID index = e - _engines;

	// In case the player didn't build the vehicle during the intro period,
	// prevent that player from getting future intro periods for a while.
	if (e->flags & ENGINE_INTRODUCING) {
		FOR_ALL_PLAYERS(p) {
			uint block_preview = p->block_preview;

			if (!HASBIT(e->player_avail, p->index)) continue;

			/* We assume the user did NOT build it.. prove me wrong ;) */
			p->block_preview = 20;

			FOR_ALL_VEHICLES(v) {
				if (v->type == VEH_Train || v->type == VEH_Road || v->type == VEH_Ship ||
						(v->type == VEH_Aircraft && v->subtype <= 2)) {
					if (v->owner == p->index && v->engine_type == index) {
						/* The user did prove me wrong, so restore old value */
						p->block_preview = block_preview;
						break;
					}
				}
			}
		}
	}

	e->flags = (e->flags & ~ENGINE_INTRODUCING) | ENGINE_AVAILABLE;
	InvalidateWindowClasses(WC_BUILD_VEHICLE);
	InvalidateWindowClasses(WC_REPLACE_VEHICLE);

	// Now available for all players
	e->player_avail = (byte)-1;

	// Do not introduce new rail wagons
	if (IsWagon(index)) return;

	// make maglev / monorail available
	FOR_ALL_PLAYERS(p) {
		if (p->is_active) {
			assert(e->railtype < RAILTYPE_END);
			SETBIT(p->avail_railtypes, e->railtype);
		}
	}

	if (index < NUM_TRAIN_ENGINES) {
		AddNewsItem(index, NEWS_FLAGS(NM_CALLBACK, 0, NT_NEW_VEHICLES, DNC_TRAINAVAIL), 0, 0);
	} else if (index < NUM_TRAIN_ENGINES + NUM_ROAD_ENGINES) {
		AddNewsItem(index, NEWS_FLAGS(NM_CALLBACK, 0, NT_NEW_VEHICLES, DNC_ROADAVAIL), 0, 0);
	} else if (index < NUM_TRAIN_ENGINES + NUM_ROAD_ENGINES + NUM_SHIP_ENGINES) {
		AddNewsItem(index, NEWS_FLAGS(NM_CALLBACK, 0, NT_NEW_VEHICLES, DNC_SHIPAVAIL), 0, 0);
	} else {
		AddNewsItem(index, NEWS_FLAGS(NM_CALLBACK, 0, NT_NEW_VEHICLES, DNC_AIRCRAFTAVAIL), 0, 0);
	}
}

void EnginesMonthlyLoop(void)
{
	Engine *e;

	if (_cur_year < 130) {
		for (e = _engines; e != endof(_engines); e++) {
			// Age the vehicle
			if (e->flags & ENGINE_AVAILABLE && e->age != 0xFFFF) {
				e->age++;
				CalcEngineReliability(e);
			}

			if (!(e->flags & ENGINE_AVAILABLE) && (uint16)(_date - min(_date, 365)) >= e->intro_date) {
				// Introduce it to all players
				NewVehicleAvailable(e);
			} else if (!(e->flags & (ENGINE_AVAILABLE|ENGINE_INTRODUCING)) && _date >= e->intro_date) {
				// Introduction date has passed.. show introducing dialog to one player.
				e->flags |= ENGINE_INTRODUCING;

				// Do not introduce new rail wagons
				if (!IsWagon(e - _engines))
					e->preview_player = 1; // Give to the player with the highest rating.
			}
		}
	}
	AdjustAvailAircraft();
}

/** Rename an engine.
 * @param x,y unused
 * @param p1 engine ID to rename
 * @param p2 unused
 */
int32 CmdRenameEngine(int x, int y, uint32 flags, uint32 p1, uint32 p2)
{
	StringID str;

	if (!IsEngineIndex(p1) || _cmd_text[0] == '\0') return CMD_ERROR;

	str = AllocateNameUnique(_cmd_text, 0);
	if (str == 0) return CMD_ERROR;

	if (flags & DC_EXEC) {
		StringID old_str = _engine_name_strings[p1];
		_engine_name_strings[p1] = str;
		DeleteName(old_str);
		_vehicle_design_names |= 3;
		MarkWholeScreenDirty();
	} else {
		DeleteName(str);
	}

	return 0;
}


/*
 * returns true if an engine is valid, of the specified type, and buildable by
 * the current player, false otherwise
 *
 * engine = index of the engine to check
 * type   = the type the engine should be of (VEH_xxx)
 */
bool IsEngineBuildable(uint engine, byte type)
{
	const Engine *e;

	// check if it's an engine that is in the engine array
	if (!IsEngineIndex(engine)) return false;

	e = GetEngine(engine);

	// check if it's an engine of specified type
	if (e->type != type) return false;

	// check if it's available
	if (!HASBIT(e->player_avail, _current_player)) return false;

	return true;
}

/************************************************************************
 * Engine Replacement stuff
 ************************************************************************/

static void EngineRenewPoolNewBlock(uint start_item); /* Forward declare for initializer of _engine_renew_pool */
enum {
	ENGINE_RENEW_POOL_BLOCK_SIZE_BITS = 3,
	ENGINE_RENEW_POOL_MAX_BLOCKS      = 8000,
};

MemoryPool _engine_renew_pool = { "EngineRe", ENGINE_RENEW_POOL_MAX_BLOCKS, ENGINE_RENEW_POOL_BLOCK_SIZE_BITS, sizeof(EngineRenew), &EngineRenewPoolNewBlock, 0, 0, NULL };

static inline uint16 GetEngineRenewPoolSize(void)
{
	return _engine_renew_pool.total_items;
}

#define FOR_ALL_ENGINE_RENEWS_FROM(er, start) for (er = GetEngineRenew(start); er != NULL; er = (er->index + 1 < GetEngineRenewPoolSize()) ? GetEngineRenew(er->index + 1) : NULL)
#define FOR_ALL_ENGINE_RENEWS(er) FOR_ALL_ENGINE_RENEWS_FROM(er, 0)

static void EngineRenewPoolNewBlock(uint start_item)
{
	EngineRenew *er;

	FOR_ALL_ENGINE_RENEWS_FROM(er, start_item) {
		er->index = start_item++;
		er->from = INVALID_ENGINE;
	}
}


static EngineRenew *AllocateEngineRenew(void)
{
	EngineRenew *er;

	FOR_ALL_ENGINE_RENEWS(er) {
		if (er->from == INVALID_ENGINE) {
			er->to = INVALID_ENGINE;
			er->next = NULL;
			return er;
		}
	}

	/* Check if we can add a block to the pool */
	if (AddBlockToPool(&_engine_renew_pool)) return AllocateEngineRenew();

	return NULL;
}

/**
 * Retrieves the EngineRenew that specifies the replacement of the given
 * engine type from the given renewlist */
static EngineRenew *GetEngineReplacement(EngineRenewList erl, EngineID engine)
{
	EngineRenew* er = (EngineRenew*)erl; /* Fetch first element */
	while (er) {
		if (er->from == engine) return er;
		er = er->next;
	}
	return NULL;
}

void RemoveAllEngineReplacement(EngineRenewList* erl)
{
	EngineRenew* er = (EngineRenew*)(*erl); /* Fetch first element */
	while (er) {
		er->from = INVALID_ENGINE; /* "Deallocate" all elements */
		er = er->next;
	}
	*erl = NULL; /* Empty list */
}

EngineID EngineReplacement(EngineRenewList erl, EngineID engine)
{
	const EngineRenew *er = GetEngineReplacement(erl, engine);
	return er == NULL ? INVALID_ENGINE : er->to;
}

int32 AddEngineReplacement(EngineRenewList* erl, EngineID old_engine, EngineID new_engine, uint32 flags)
{
	EngineRenew *er;

	// Check if the old vehicle is already in the list
	er = GetEngineReplacement(*erl, old_engine);
	if (er != NULL) {
		if (flags & DC_EXEC) er->to = new_engine;
		return 0;
	}

	er = AllocateEngineRenew();
	if (er == NULL) return CMD_ERROR;

	if (flags & DC_EXEC) {
		er->from = old_engine;
		er->to = new_engine;
		er->next = (EngineRenew*)(*erl); /* Resolve the first element in the list */

		*erl = (EngineRenewList)er; /* Insert before the first element */
	}

	return 0;
}

int32 RemoveEngineReplacement(EngineRenewList* erl, EngineID engine, uint32 flags)
{
	EngineRenew* er = (EngineRenew*)(*erl); /* Start at the first element */
	EngineRenew* prev = NULL;

	while (er)
	{
		if (er->from == engine) {
			if (flags & DC_EXEC) {
				if (prev == NULL) { /* First element */
					(*erl) = (EngineRenewList)er->next; /* The second becomes the new first element */
				} else {
					prev->next = er->next; /* Cut this element out */
				}
				er->from = INVALID_ENGINE; /* Deallocate */
			}
			return 0;
		}
		prev = er;
		er = er->next; /* Look at next element */
	}

	return CMD_ERROR; /* Not found? */
}

static const SaveLoad _engine_renew_desc[] = {
	SLE_VAR(EngineRenew, from, SLE_UINT16),
	SLE_VAR(EngineRenew, to,   SLE_UINT16),

	SLE_REF(EngineRenew, next, REF_ENGINE_RENEWS),

	SLE_END()
};

static void Save_ERNW(void)
{
	EngineRenew *er;

	FOR_ALL_ENGINE_RENEWS(er) {
		if (er->from != INVALID_ENGINE) {
			SlSetArrayIndex(er->index);
			SlObject(er, _engine_renew_desc);
		}
	}
}

static void Load_ERNW(void)
{
	int index;

	while ((index = SlIterateArray()) != -1) {
		EngineRenew *er;

		if (!AddBlockIfNeeded(&_engine_renew_pool, index))
			error("EngineRenews: failed loading savegame: too many EngineRenews");

		er = GetEngineRenew(index);
		SlObject(er, _engine_renew_desc);
	}
}

static const SaveLoad _engine_desc[] = {
	SLE_VAR(Engine,intro_date,						SLE_UINT16),
	SLE_VAR(Engine,age,										SLE_UINT16),
	SLE_VAR(Engine,reliability,						SLE_UINT16),
	SLE_VAR(Engine,reliability_spd_dec,		SLE_UINT16),
	SLE_VAR(Engine,reliability_start,			SLE_UINT16),
	SLE_VAR(Engine,reliability_max,				SLE_UINT16),
	SLE_VAR(Engine,reliability_final,			SLE_UINT16),
	SLE_VAR(Engine,duration_phase_1,			SLE_UINT16),
	SLE_VAR(Engine,duration_phase_2,			SLE_UINT16),
	SLE_VAR(Engine,duration_phase_3,			SLE_UINT16),

	SLE_VAR(Engine,lifelength,						SLE_UINT8),
	SLE_VAR(Engine,flags,									SLE_UINT8),
	SLE_VAR(Engine,preview_player,				SLE_UINT8),
	SLE_VAR(Engine,preview_wait,					SLE_UINT8),
	SLE_VAR(Engine,railtype,							SLE_UINT8),
	SLE_VAR(Engine,player_avail,					SLE_UINT8),

	// reserve extra space in savegame here. (currently 16 bytes)
	SLE_CONDARR(NullStruct,null,SLE_FILE_U64 | SLE_VAR_NULL, 2, 2, 255),

	SLE_END()
};

static void Save_ENGN(void)
{
	uint i;

	for (i = 0; i != lengthof(_engines); i++) {
		SlSetArrayIndex(i);
		SlObject(&_engines[i], _engine_desc);
	}
}

static void Load_ENGN(void)
{
	int index;
	while ((index = SlIterateArray()) != -1) {
		SlObject(GetEngine(index), _engine_desc);
	}
}

static void LoadSave_ENGS(void)
{
	SlArray(_engine_name_strings, lengthof(_engine_name_strings), SLE_STRINGID);
}

const ChunkHandler _engine_chunk_handlers[] = {
	{ 'ENGN', Save_ENGN,     Load_ENGN,     CH_ARRAY          },
	{ 'ENGS', LoadSave_ENGS, LoadSave_ENGS, CH_RIFF           },
	{ 'ERNW', Save_ERNW,     Load_ERNW,     CH_ARRAY | CH_LAST},
};

void InitializeEngines(void)
{
	/* Clean the engine renew pool and create 1 block in it */
	CleanPool(&_engine_renew_pool);
	AddBlockToPool(&_engine_renew_pool);
}