-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
newgrf.cpp
10452 lines (8833 loc) · 342 KB
/
newgrf.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of 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 newgrf.cpp Base of all NewGRF support. */
#include "stdafx.h"
#include <stdarg.h>
#include <algorithm>
#include "debug.h"
#include "fileio_func.h"
#include "engine_func.h"
#include "engine_base.h"
#include "bridge.h"
#include "town.h"
#include "newgrf_engine.h"
#include "newgrf_text.h"
#include "fontcache.h"
#include "currency.h"
#include "landscape.h"
#include "newgrf_cargo.h"
#include "newgrf_house.h"
#include "newgrf_sound.h"
#include "newgrf_station.h"
#include "industrytype.h"
#include "newgrf_canal.h"
#include "newgrf_townname.h"
#include "newgrf_industries.h"
#include "newgrf_airporttiles.h"
#include "newgrf_airport.h"
#include "newgrf_object.h"
#include "rev.h"
#include "fios.h"
#include "strings_func.h"
#include "date_func.h"
#include "string_func.h"
#include "network/network.h"
#include "smallmap_gui.h"
#include "genworld.h"
#include "error.h"
#include "vehicle_func.h"
#include "language.h"
#include "vehicle_base.h"
#include "road.h"
#include "table/strings.h"
#include "table/build_industry.h"
#include "3rdparty/cpp-btree/btree_map.h"
#include "safeguards.h"
/* TTDPatch extended GRF format codec
* (c) Petr Baudis 2004 (GPL'd)
* Changes by Florian octo Forster are (c) by the OpenTTD development team.
*
* Contains portions of documentation by TTDPatch team.
* Thanks especially to Josef Drexler for the documentation as well as a lot
* of help at #tycoon. Also thanks to Michael Blunck for his GRF files which
* served as subject to the initial testing of this codec. */
/** List of all loaded GRF files */
static std::vector<GRFFile *> _grf_files;
const std::vector<GRFFile *> &GetAllGRFFiles()
{
return _grf_files;
}
/** Miscellaneous GRF features, set by Action 0x0D, parameter 0x9E */
byte _misc_grf_features = 0;
/** 32 * 8 = 256 flags. Apparently TTDPatch uses this many.. */
static uint32 _ttdpatch_flags[8];
/** Indicates which are the newgrf features currently loaded ingame */
GRFLoadedFeatures _loaded_newgrf_features;
static const uint MAX_SPRITEGROUP = UINT8_MAX; ///< Maximum GRF-local ID for a spritegroup.
/** Base GRF ID for OpenTTD's base graphics GRFs. */
static const uint32 OPENTTD_GRAPHICS_BASE_GRF_ID = BSWAP32(0xFF4F5400);
/** Temporary data during loading of GRFs */
struct GrfProcessingState {
private:
/** Definition of a single Action1 spriteset */
struct SpriteSet {
SpriteID sprite; ///< SpriteID of the first sprite of the set.
uint num_sprites; ///< Number of sprites in the set.
};
/** Currently referenceable spritesets */
btree::btree_map<uint, SpriteSet> spritesets[GSF_END];
public:
/* Global state */
GrfLoadingStage stage; ///< Current loading stage
SpriteID spriteid; ///< First available SpriteID for loading realsprites.
/* Local state in the file */
uint file_index; ///< File index of currently processed GRF file.
GRFFile *grffile; ///< Currently processed GRF file.
GRFConfig *grfconfig; ///< Config of the currently processed GRF file.
uint32 nfo_line; ///< Currently processed pseudo sprite number in the GRF.
byte grf_container_ver; ///< Container format of the current GRF file.
/* Kind of return values when processing certain actions */
int skip_sprites; ///< Number of pseudo sprites to skip before processing the next one. (-1 to skip to end of file)
/* Currently referenceable spritegroups */
SpriteGroup *spritegroups[MAX_SPRITEGROUP + 1];
/** Clear temporary data before processing the next file in the current loading stage */
void ClearDataForNextFile()
{
this->nfo_line = 0;
this->skip_sprites = 0;
for (uint i = 0; i < GSF_END; i++) {
this->spritesets[i].clear();
}
memset(this->spritegroups, 0, sizeof(this->spritegroups));
}
/**
* Records new spritesets.
* @param feature GrfSpecFeature the set is defined for.
* @param first_sprite SpriteID of the first sprite in the set.
* @param first_set First spriteset to define.
* @param numsets Number of sets to define.
* @param numents Number of sprites per set to define.
*/
void AddSpriteSets(byte feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
{
assert(feature < GSF_END);
for (uint i = 0; i < numsets; i++) {
SpriteSet &set = this->spritesets[feature][first_set + i];
set.sprite = first_sprite + i * numents;
set.num_sprites = numents;
}
}
/**
* Check whether there are any valid spritesets for a feature.
* @param feature GrfSpecFeature to check.
* @return true if there are any valid sets.
* @note Spritesets with zero sprites are valid to allow callback-failures.
*/
bool HasValidSpriteSets(byte feature) const
{
assert(feature < GSF_END);
return !this->spritesets[feature].empty();
}
/**
* Check whether a specific set is defined.
* @param feature GrfSpecFeature to check.
* @param set Set to check.
* @return true if the set is valid.
* @note Spritesets with zero sprites are valid to allow callback-failures.
*/
bool IsValidSpriteSet(byte feature, uint set) const
{
assert(feature < GSF_END);
return this->spritesets[feature].find(set) != this->spritesets[feature].end();
}
/**
* Returns the first sprite of a spriteset.
* @param feature GrfSpecFeature to query.
* @param set Set to query.
* @return First sprite of the set.
*/
SpriteID GetSprite(byte feature, uint set) const
{
assert(IsValidSpriteSet(feature, set));
return this->spritesets[feature].find(set)->second.sprite;
}
/**
* Returns the number of sprites in a spriteset
* @param feature GrfSpecFeature to query.
* @param set Set to query.
* @return Number of sprites in the set.
*/
uint GetNumEnts(byte feature, uint set) const
{
assert(IsValidSpriteSet(feature, set));
return this->spritesets[feature].find(set)->second.num_sprites;
}
};
static GrfProcessingState _cur;
/**
* Helper to check whether an image index is valid for a particular NewGRF vehicle.
* @tparam T The type of vehicle.
* @param image_index The image index to check.
* @return True iff the image index is valid, or 0xFD (use new graphics).
*/
template <VehicleType T>
static inline bool IsValidNewGRFImageIndex(uint8 image_index)
{
return image_index == 0xFD || IsValidImageIndex<T>(image_index);
}
class OTTDByteReaderSignal { };
/** Class to read from a NewGRF file */
class ByteReader {
protected:
byte *data;
byte *end;
public:
ByteReader(byte *data, byte *end) : data(data), end(end) { }
inline byte ReadByte()
{
if (data < end) return *(data)++;
throw OTTDByteReaderSignal();
}
uint16 ReadWord()
{
uint16 val = ReadByte();
return val | (ReadByte() << 8);
}
uint16 ReadExtendedByte()
{
uint16 val = ReadByte();
return val == 0xFF ? ReadWord() : val;
}
uint32 ReadDWord()
{
uint32 val = ReadWord();
return val | (ReadWord() << 16);
}
uint32 ReadVarSize(byte size)
{
switch (size) {
case 1: return ReadByte();
case 2: return ReadWord();
case 4: return ReadDWord();
default:
NOT_REACHED();
return 0;
}
}
const char *ReadString()
{
char *string = reinterpret_cast<char *>(data);
size_t string_length = ttd_strnlen(string, Remaining());
if (string_length == Remaining()) {
/* String was not NUL terminated, so make sure it is now. */
string[string_length - 1] = '\0';
grfmsg(7, "String was not terminated with a zero byte.");
} else {
/* Increase the string length to include the NUL byte. */
string_length++;
}
Skip(string_length);
return string;
}
inline size_t Remaining() const
{
return end - data;
}
inline bool HasData(size_t count = 1) const
{
return data + count <= end;
}
inline byte *Data()
{
return data;
}
inline void Skip(size_t len)
{
data += len;
/* It is valid to move the buffer to exactly the end of the data,
* as there may not be any more data read. */
if (data > end) throw OTTDByteReaderSignal();
}
};
typedef void (*SpecialSpriteHandler)(ByteReader *buf);
static const uint NUM_STATIONS_PER_GRF = 255; ///< Number of StationSpecs per NewGRF; limited to 255 to allow extending Action3 with an extended byte later on.
/** Temporary engine data used when loading only */
struct GRFTempEngineData {
/** Summary state of refittability properties */
enum Refittability {
UNSET = 0, ///< No properties assigned. Default refit masks shall be activated.
EMPTY, ///< GRF defined vehicle as not-refittable. The vehicle shall only carry the default cargo.
NONEMPTY, ///< GRF defined the vehicle as refittable. If the refitmask is empty after translation (cargotypes not available), disable the vehicle.
};
uint16 cargo_allowed;
uint16 cargo_disallowed;
RailTypeLabel railtypelabel;
uint8 roadtramtype;
const GRFFile *defaultcargo_grf; ///< GRF defining the cargo translation table to use if the default cargo is the 'first refittable'.
Refittability refittability; ///< Did the newgrf set any refittability property? If not, default refittability will be applied.
bool prop27_set; ///< Did the NewGRF set property 27 (misc flags)?
uint8 rv_max_speed; ///< Temporary storage of RV prop 15, maximum speed in mph/0.8
CargoTypes ctt_include_mask; ///< Cargo types always included in the refit mask.
CargoTypes ctt_exclude_mask; ///< Cargo types always excluded from the refit mask.
/**
* Update the summary refittability on setting a refittability property.
* @param non_empty true if the GRF sets the vehicle to be refittable.
*/
void UpdateRefittability(bool non_empty)
{
if (non_empty) {
this->refittability = NONEMPTY;
} else if (this->refittability == UNSET) {
this->refittability = EMPTY;
}
}
};
static GRFTempEngineData *_gted; ///< Temporary engine data used during NewGRF loading
/**
* Contains the GRF ID of the owner of a vehicle if it has been reserved.
* GRM for vehicles is only used if dynamic engine allocation is disabled,
* so 256 is the number of original engines. */
static uint32 _grm_engines[256];
/** Contains the GRF ID of the owner of a cargo if it has been reserved */
static uint32 _grm_cargoes[NUM_CARGO * 2];
struct GRFLocation {
uint32 grfid;
uint32 nfoline;
GRFLocation() { }
GRFLocation(uint32 grfid, uint32 nfoline) : grfid(grfid), nfoline(nfoline) { }
bool operator<(const GRFLocation &other) const
{
return this->grfid < other.grfid || (this->grfid == other.grfid && this->nfoline < other.nfoline);
}
bool operator == (const GRFLocation &other) const
{
return this->grfid == other.grfid && this->nfoline == other.nfoline;
}
};
static btree::btree_map<GRFLocation, SpriteID> _grm_sprites;
typedef btree::btree_map<GRFLocation, byte*> GRFLineToSpriteOverride;
static GRFLineToSpriteOverride _grf_line_to_action6_sprite_override;
/**
* DEBUG() function dedicated to newGRF debugging messages
* Function is essentially the same as DEBUG(grf, severity, ...) with the
* addition of file:line information when parsing grf files.
* NOTE: for the above reason(s) grfmsg() should ONLY be used for
* loading/parsing grf files, not for runtime debug messages as there
* is no file information available during that time.
* @param severity debugging severity level, see debug.h
* @param str message in printf() format
*/
void CDECL _intl_grfmsg(int severity, const char *str, ...)
{
char buf[1024];
va_list va;
va_start(va, str);
vseprintf(buf, lastof(buf), str, va);
va_end(va);
DEBUG(grf, severity, "[%s:%d] %s", _cur.grfconfig->GetDisplayPath(), _cur.nfo_line, buf);
}
/**
* Obtain a NewGRF file by its grfID
* @param grfid The grfID to obtain the file for
* @return The file.
*/
GRFFile *GetFileByGRFID(uint32 grfid)
{
for (GRFFile * const file : _grf_files) {
if (file->grfid == grfid) return file;
}
return nullptr;
}
/**
* Obtain a NewGRF file by its filename
* @param filename The filename to obtain the file for.
* @return The file.
*/
static GRFFile *GetFileByFilename(const char *filename)
{
for (GRFFile * const file : _grf_files) {
if (strcmp(file->filename, filename) == 0) return file;
}
return nullptr;
}
/** Reset all NewGRFData that was used only while processing data */
static void ClearTemporaryNewGRFData(GRFFile *gf)
{
/* Clear the GOTO labels used for GRF processing */
for (GRFLabel *l = gf->label; l != nullptr;) {
GRFLabel *l2 = l->next;
free(l);
l = l2;
}
gf->label = nullptr;
}
/**
* Disable a GRF
* @param message Error message or STR_NULL.
* @param config GRFConfig to disable, nullptr for current.
* @return Error message of the GRF for further customisation.
*/
static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = nullptr)
{
GRFFile *file;
if (config != nullptr) {
file = GetFileByGRFID(config->ident.grfid);
} else {
config = _cur.grfconfig;
file = _cur.grffile;
}
config->status = GCS_DISABLED;
if (file != nullptr) ClearTemporaryNewGRFData(file);
if (config == _cur.grfconfig) _cur.skip_sprites = -1;
if (message != STR_NULL) {
delete config->error;
config->error = new GRFError(STR_NEWGRF_ERROR_MSG_FATAL, message);
if (config == _cur.grfconfig) config->error->param_value[0] = _cur.nfo_line;
}
return config->error;
}
/**
* Information for mapping static StringIDs.
*/
struct StringIDMapping {
uint32 grfid; ///< Source NewGRF.
StringID source; ///< Source StringID (GRF local).
StringID *target; ///< Destination for mapping result.
};
typedef std::vector<StringIDMapping> StringIDMappingVector;
static StringIDMappingVector _string_to_grf_mapping;
/**
* Record a static StringID for getting translated later.
* @param source Source StringID (GRF local).
* @param target Destination for the mapping result.
*/
static void AddStringForMapping(StringID source, StringID *target)
{
*target = STR_UNDEFINED;
_string_to_grf_mapping.push_back({_cur.grffile->grfid, source, target});
}
/**
* Perform a mapping from TTDPatch's string IDs to OpenTTD's
* string IDs, but only for the ones we are aware off; the rest
* like likely unused and will show a warning.
* @param str the string ID to convert
* @return the converted string ID
*/
static StringID TTDPStringIDToOTTDStringIDMapping(StringID str)
{
/* StringID table for TextIDs 0x4E->0x6D */
static const StringID units_volume[] = {
STR_ITEMS, STR_PASSENGERS, STR_TONS, STR_BAGS,
STR_LITERS, STR_ITEMS, STR_CRATES, STR_TONS,
STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
STR_TONS, STR_TONS, STR_BAGS, STR_LITERS,
STR_TONS, STR_LITERS, STR_TONS, STR_ITEMS,
STR_BAGS, STR_LITERS, STR_TONS, STR_ITEMS,
STR_TONS, STR_ITEMS, STR_LITERS, STR_ITEMS
};
/* A string straight from a NewGRF; this was already translated by MapGRFStringID(). */
assert(!IsInsideMM(str, 0xD000, 0xD7FF));
#define TEXTID_TO_STRINGID(begin, end, stringid, stringend) \
assert_compile(stringend - stringid == end - begin); \
if (str >= begin && str <= end) return str + (stringid - begin)
/* We have some changes in our cargo strings, resulting in some missing. */
TEXTID_TO_STRINGID(0x000E, 0x002D, STR_CARGO_PLURAL_NOTHING, STR_CARGO_PLURAL_FIZZY_DRINKS);
TEXTID_TO_STRINGID(0x002E, 0x004D, STR_CARGO_SINGULAR_NOTHING, STR_CARGO_SINGULAR_FIZZY_DRINK);
if (str >= 0x004E && str <= 0x006D) return units_volume[str - 0x004E];
TEXTID_TO_STRINGID(0x006E, 0x008D, STR_QUANTITY_NOTHING, STR_QUANTITY_FIZZY_DRINKS);
TEXTID_TO_STRINGID(0x008E, 0x00AD, STR_ABBREV_NOTHING, STR_ABBREV_FIZZY_DRINKS);
TEXTID_TO_STRINGID(0x00D1, 0x00E0, STR_COLOUR_DARK_BLUE, STR_COLOUR_WHITE);
/* Map building names according to our lang file changes. There are several
* ranges of house ids, all of which need to be remapped to allow newgrfs
* to use original house names. */
TEXTID_TO_STRINGID(0x200F, 0x201F, STR_TOWN_BUILDING_NAME_TALL_OFFICE_BLOCK_1, STR_TOWN_BUILDING_NAME_OLD_HOUSES_1);
TEXTID_TO_STRINGID(0x2036, 0x2041, STR_TOWN_BUILDING_NAME_COTTAGES_1, STR_TOWN_BUILDING_NAME_SHOPPING_MALL_1);
TEXTID_TO_STRINGID(0x2059, 0x205C, STR_TOWN_BUILDING_NAME_IGLOO_1, STR_TOWN_BUILDING_NAME_PIGGY_BANK_1);
/* Same thing for industries */
TEXTID_TO_STRINGID(0x4802, 0x4826, STR_INDUSTRY_NAME_COAL_MINE, STR_INDUSTRY_NAME_SUGAR_MINE);
TEXTID_TO_STRINGID(0x482D, 0x482E, STR_NEWS_INDUSTRY_CONSTRUCTION, STR_NEWS_INDUSTRY_PLANTED);
TEXTID_TO_STRINGID(0x4832, 0x4834, STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_CLOSURE_LACK_OF_TREES);
TEXTID_TO_STRINGID(0x4835, 0x4838, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM);
TEXTID_TO_STRINGID(0x4839, 0x483A, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM);
switch (str) {
case 0x4830: return STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY;
case 0x4831: return STR_ERROR_FOREST_CAN_ONLY_BE_PLANTED;
case 0x483B: return STR_ERROR_CAN_ONLY_BE_POSITIONED;
}
#undef TEXTID_TO_STRINGID
if (str == STR_NULL) return STR_EMPTY;
DEBUG(grf, 0, "Unknown StringID 0x%04X remapped to STR_EMPTY. Please open a Feature Request if you need it", str);
return STR_EMPTY;
}
/**
* Used when setting an object's property to map to the GRF's strings
* while taking in consideration the "drift" between TTDPatch string system and OpenTTD's one
* @param grfid Id of the grf file.
* @param str StringID that we want to have the equivalent in OoenTTD.
* @return The properly adjusted StringID.
*/
StringID MapGRFStringID(uint32 grfid, StringID str)
{
if (IsInsideMM(str, 0xD800, 0xE000)) {
/* General text provided by NewGRF.
* In the specs this is called the 0xDCxx range (misc persistent texts),
* but we meanwhile extended the range to 0xD800-0xDFFF.
* Note: We are not involved in the "persistent" business, since we do not store
* any NewGRF strings in savegames. */
return GetGRFStringID(grfid, str);
} else if (IsInsideMM(str, 0xD000, 0xD800)) {
/* Callback text provided by NewGRF.
* In the specs this is called the 0xD0xx range (misc graphics texts).
* These texts can be returned by various callbacks.
*
* Due to how TTDP implements the GRF-local- to global-textid translation
* texts included via 0x80 or 0x81 control codes have to add 0x400 to the textid.
* We do not care about that difference and just mask out the 0x400 bit.
*/
str &= ~0x400;
return GetGRFStringID(grfid, str);
} else {
/* The NewGRF wants to include/reference an original TTD string.
* Try our best to find an equivalent one. */
return TTDPStringIDToOTTDStringIDMapping(str);
}
}
static std::map<uint32, uint32> _grf_id_overrides;
/**
* Set the override for a NewGRF
* @param source_grfid The grfID which wants to override another NewGRF.
* @param target_grfid The grfID which is being overridden.
*/
static void SetNewGRFOverride(uint32 source_grfid, uint32 target_grfid)
{
_grf_id_overrides[source_grfid] = target_grfid;
grfmsg(5, "SetNewGRFOverride: Added override of 0x%X to 0x%X", BSWAP32(source_grfid), BSWAP32(target_grfid));
}
/**
* Returns the engine associated to a certain internal_id, resp. allocates it.
* @param file NewGRF that wants to change the engine.
* @param type Vehicle type.
* @param internal_id Engine ID inside the NewGRF.
* @param static_access If the engine is not present, return nullptr instead of allocating a new engine. (Used for static Action 0x04).
* @return The requested engine.
*/
static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16 internal_id, bool static_access = false)
{
/* Hack for add-on GRFs that need to modify another GRF's engines. This lets
* them use the same engine slots. */
uint32 scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
if (_settings_game.vehicle.dynamic_engines) {
/* If dynamic_engies is enabled, there can be multiple independent ID ranges. */
scope_grfid = file->grfid;
uint32 override = _grf_id_overrides[file->grfid];
if (override != 0) {
scope_grfid = override;
const GRFFile *grf_match = GetFileByGRFID(override);
if (grf_match == nullptr) {
grfmsg(5, "Tried mapping from GRFID %x to %x but target is not loaded", BSWAP32(file->grfid), BSWAP32(override));
} else {
grfmsg(5, "Mapping from GRFID %x to %x", BSWAP32(file->grfid), BSWAP32(override));
}
}
/* Check if the engine is registered in the override manager */
EngineID engine = _engine_mngr.GetID(type, internal_id, scope_grfid);
if (engine != INVALID_ENGINE) {
Engine *e = Engine::Get(engine);
if (e->grf_prop.grffile == nullptr) e->grf_prop.grffile = file;
return e;
}
}
/* Check if there is an unreserved slot */
EngineID engine = _engine_mngr.GetID(type, internal_id, INVALID_GRFID);
if (engine != INVALID_ENGINE) {
Engine *e = Engine::Get(engine);
if (e->grf_prop.grffile == nullptr) {
e->grf_prop.grffile = file;
grfmsg(5, "Replaced engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
}
/* Reserve the engine slot */
if (!static_access) {
EngineIDMapping *eid = _engine_mngr.data() + engine;
eid->grfid = scope_grfid; // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
}
return e;
}
if (static_access) return nullptr;
if (!Engine::CanAllocateItem()) {
grfmsg(0, "Can't allocate any more engines");
return nullptr;
}
size_t engine_pool_size = Engine::GetPoolSize();
/* ... it's not, so create a new one based off an existing engine */
Engine *e = new Engine(type, internal_id);
e->grf_prop.grffile = file;
/* Reserve the engine slot */
assert(_engine_mngr.size() == e->index);
_engine_mngr.push_back({
scope_grfid, // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
internal_id,
type,
static_cast<uint8>(min(internal_id, _engine_counts[type])) // substitute_id == _engine_counts[subtype] means "no substitute"
});
if (engine_pool_size != Engine::GetPoolSize()) {
/* Resize temporary engine data ... */
_gted = ReallocT(_gted, Engine::GetPoolSize());
/* and blank the new block. */
size_t len = (Engine::GetPoolSize() - engine_pool_size) * sizeof(*_gted);
memset(_gted + engine_pool_size, 0, len);
}
if (type == VEH_TRAIN) {
_gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
}
grfmsg(5, "Created new engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
return e;
}
/**
* Return the ID of a new engine
* @param file The NewGRF file providing the engine.
* @param type The Vehicle type.
* @param internal_id NewGRF-internal ID of the engine.
* @return The new EngineID.
* @note depending on the dynamic_engine setting and a possible override
* property the grfID may be unique or overwriting or partially re-defining
* properties of an existing engine.
*/
EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16 internal_id)
{
uint32 scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
if (_settings_game.vehicle.dynamic_engines) {
scope_grfid = file->grfid;
uint32 override = _grf_id_overrides[file->grfid];
if (override != 0) scope_grfid = override;
}
return _engine_mngr.GetID(type, internal_id, scope_grfid);
}
/**
* Map the colour modifiers of TTDPatch to those that Open is using.
* @param grf_sprite Pointer to the structure been modified.
*/
static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
{
if (HasBit(grf_sprite->pal, 14)) {
ClrBit(grf_sprite->pal, 14);
SetBit(grf_sprite->sprite, SPRITE_MODIFIER_OPAQUE);
}
if (HasBit(grf_sprite->sprite, 14)) {
ClrBit(grf_sprite->sprite, 14);
SetBit(grf_sprite->sprite, PALETTE_MODIFIER_TRANSPARENT);
}
if (HasBit(grf_sprite->sprite, 15)) {
ClrBit(grf_sprite->sprite, 15);
SetBit(grf_sprite->sprite, PALETTE_MODIFIER_COLOUR);
}
}
/**
* Read a sprite and a palette from the GRF and convert them into a format
* suitable to OpenTTD.
* @param buf Input stream.
* @param read_flags Whether to read TileLayoutFlags.
* @param invert_action1_flag Set to true, if palette bit 15 means 'not from action 1'.
* @param use_cur_spritesets Whether to use currently referenceable action 1 sets.
* @param feature GrfSpecFeature to use spritesets from.
* @param[out] grf_sprite Read sprite and palette.
* @param[out] max_sprite_offset Optionally returns the number of sprites in the spriteset of the sprite. (0 if no spritset)
* @param[out] max_palette_offset Optionally returns the number of sprites in the spriteset of the palette. (0 if no spritset)
* @return Read TileLayoutFlags.
*/
static TileLayoutFlags ReadSpriteLayoutSprite(ByteReader *buf, bool read_flags, bool invert_action1_flag, bool use_cur_spritesets, int feature, PalSpriteID *grf_sprite, uint16 *max_sprite_offset = nullptr, uint16 *max_palette_offset = nullptr)
{
grf_sprite->sprite = buf->ReadWord();
grf_sprite->pal = buf->ReadWord();
TileLayoutFlags flags = read_flags ? (TileLayoutFlags)buf->ReadWord() : TLF_NOTHING;
MapSpriteMappingRecolour(grf_sprite);
bool custom_sprite = HasBit(grf_sprite->pal, 15) != invert_action1_flag;
ClrBit(grf_sprite->pal, 15);
if (custom_sprite) {
/* Use sprite from Action 1 */
uint index = GB(grf_sprite->sprite, 0, 14);
if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset %d", index);
grf_sprite->sprite = SPR_IMG_QUERY;
grf_sprite->pal = PAL_NONE;
} else {
SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
if (max_sprite_offset != nullptr) *max_sprite_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
SB(grf_sprite->sprite, 0, SPRITE_WIDTH, sprite);
SetBit(grf_sprite->sprite, SPRITE_MODIFIER_CUSTOM_SPRITE);
}
} else if ((flags & TLF_SPRITE_VAR10) && !(flags & TLF_SPRITE_REG_FLAGS)) {
grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout specifies var10 value for non-action-1 sprite");
DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
return flags;
}
if (flags & TLF_CUSTOM_PALETTE) {
/* Use palette from Action 1 */
uint index = GB(grf_sprite->pal, 0, 14);
if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset %d for 'palette'", index);
grf_sprite->pal = PAL_NONE;
} else {
SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
if (max_palette_offset != nullptr) *max_palette_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
SB(grf_sprite->pal, 0, SPRITE_WIDTH, sprite);
SetBit(grf_sprite->pal, SPRITE_MODIFIER_CUSTOM_SPRITE);
}
} else if ((flags & TLF_PALETTE_VAR10) && !(flags & TLF_PALETTE_REG_FLAGS)) {
grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 value for non-action-1 palette");
DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
return flags;
}
return flags;
}
/**
* Preprocess the TileLayoutFlags and read register modifiers from the GRF.
* @param buf Input stream.
* @param flags TileLayoutFlags to process.
* @param is_parent Whether the sprite is a parentsprite with a bounding box.
* @param dts Sprite layout to insert data into.
* @param index Sprite index to process; 0 for ground sprite.
*/
static void ReadSpriteLayoutRegisters(ByteReader *buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
{
if (!(flags & TLF_DRAWING_FLAGS)) return;
if (dts->registers == nullptr) dts->AllocateRegisters();
TileLayoutRegisters ®s = const_cast<TileLayoutRegisters&>(dts->registers[index]);
regs.flags = flags & TLF_DRAWING_FLAGS;
if (flags & TLF_DODRAW) regs.dodraw = buf->ReadByte();
if (flags & TLF_SPRITE) regs.sprite = buf->ReadByte();
if (flags & TLF_PALETTE) regs.palette = buf->ReadByte();
if (is_parent) {
if (flags & TLF_BB_XY_OFFSET) {
regs.delta.parent[0] = buf->ReadByte();
regs.delta.parent[1] = buf->ReadByte();
}
if (flags & TLF_BB_Z_OFFSET) regs.delta.parent[2] = buf->ReadByte();
} else {
if (flags & TLF_CHILD_X_OFFSET) regs.delta.child[0] = buf->ReadByte();
if (flags & TLF_CHILD_Y_OFFSET) regs.delta.child[1] = buf->ReadByte();
}
if (flags & TLF_SPRITE_VAR10) {
regs.sprite_var10 = buf->ReadByte();
if (regs.sprite_var10 > TLR_MAX_VAR10) {
grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 (%d) exceeding the maximal allowed value %d", regs.sprite_var10, TLR_MAX_VAR10);
DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
return;
}
}
if (flags & TLF_PALETTE_VAR10) {
regs.palette_var10 = buf->ReadByte();
if (regs.palette_var10 > TLR_MAX_VAR10) {
grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 (%d) exceeding the maximal allowed value %d", regs.palette_var10, TLR_MAX_VAR10);
DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
return;
}
}
}
/**
* Read a spritelayout from the GRF.
* @param buf Input
* @param num_building_sprites Number of building sprites to read
* @param use_cur_spritesets Whether to use currently referenceable action 1 sets.
* @param feature GrfSpecFeature to use spritesets from.
* @param allow_var10 Whether the spritelayout may specify var10 values for resolving multiple action-1-2-3 chains
* @param no_z_position Whether bounding boxes have no Z offset
* @param dts Layout container to output into
* @return True on error (GRF was disabled).
*/
static bool ReadSpriteLayout(ByteReader *buf, uint num_building_sprites, bool use_cur_spritesets, byte feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts)
{
bool has_flags = HasBit(num_building_sprites, 6);
ClrBit(num_building_sprites, 6);
TileLayoutFlags valid_flags = TLF_KNOWN_FLAGS;
if (!allow_var10) valid_flags &= ~TLF_VAR10_FLAGS;
dts->Allocate(num_building_sprites); // allocate before reading groundsprite flags
uint16 *max_sprite_offset = AllocaM(uint16, num_building_sprites + 1);
uint16 *max_palette_offset = AllocaM(uint16, num_building_sprites + 1);
MemSetT(max_sprite_offset, 0, num_building_sprites + 1);
MemSetT(max_palette_offset, 0, num_building_sprites + 1);
/* Groundsprite */
TileLayoutFlags flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &dts->ground, max_sprite_offset, max_palette_offset);
if (_cur.skip_sprites < 0) return true;
if (flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS)) {
grfmsg(1, "ReadSpriteLayout: Spritelayout uses invalid flag 0x%x for ground sprite", flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS));
DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
return true;
}
ReadSpriteLayoutRegisters(buf, flags, false, dts, 0);
if (_cur.skip_sprites < 0) return true;
for (uint i = 0; i < num_building_sprites; i++) {
DrawTileSeqStruct *seq = const_cast<DrawTileSeqStruct*>(&dts->seq[i]);
flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &seq->image, max_sprite_offset + i + 1, max_palette_offset + i + 1);
if (_cur.skip_sprites < 0) return true;
if (flags & ~valid_flags) {
grfmsg(1, "ReadSpriteLayout: Spritelayout uses unknown flag 0x%x", flags & ~valid_flags);
DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
return true;
}
seq->delta_x = buf->ReadByte();
seq->delta_y = buf->ReadByte();
if (!no_z_position) seq->delta_z = buf->ReadByte();
if (seq->IsParentSprite()) {
seq->size_x = buf->ReadByte();
seq->size_y = buf->ReadByte();
seq->size_z = buf->ReadByte();
}
ReadSpriteLayoutRegisters(buf, flags, seq->IsParentSprite(), dts, i + 1);
if (_cur.skip_sprites < 0) return true;
}
/* Check if the number of sprites per spriteset is consistent */
bool is_consistent = true;
dts->consistent_max_offset = 0;
for (uint i = 0; i < num_building_sprites + 1; i++) {
if (max_sprite_offset[i] > 0) {
if (dts->consistent_max_offset == 0) {
dts->consistent_max_offset = max_sprite_offset[i];
} else if (dts->consistent_max_offset != max_sprite_offset[i]) {
is_consistent = false;
break;
}
}
if (max_palette_offset[i] > 0) {
if (dts->consistent_max_offset == 0) {
dts->consistent_max_offset = max_palette_offset[i];
} else if (dts->consistent_max_offset != max_palette_offset[i]) {
is_consistent = false;
break;
}
}
}
/* When the Action1 sets are unknown, everything should be 0 (no spriteset usage) or UINT16_MAX (some spriteset usage) */
assert(use_cur_spritesets || (is_consistent && (dts->consistent_max_offset == 0 || dts->consistent_max_offset == UINT16_MAX)));
if (!is_consistent || dts->registers != nullptr) {
dts->consistent_max_offset = 0;
if (dts->registers == nullptr) dts->AllocateRegisters();
for (uint i = 0; i < num_building_sprites + 1; i++) {
TileLayoutRegisters ®s = const_cast<TileLayoutRegisters&>(dts->registers[i]);
regs.max_sprite_offset = max_sprite_offset[i];
regs.max_palette_offset = max_palette_offset[i];
}
}
return false;
}
/**
* Translate the refit mask. refit_mask is uint32 as it has not been mapped to CargoTypes.
*/
static CargoTypes TranslateRefitMask(uint32 refit_mask)
{
CargoTypes result = 0;
uint8 bit;
FOR_EACH_SET_BIT(bit, refit_mask) {
CargoID cargo = GetCargoTranslation(bit, _cur.grffile, true);
if (cargo != CT_INVALID) SetBit(result, cargo);
}
return result;
}
/**
* Converts TTD(P) Base Price pointers into the enum used by OTTD
* See http://wiki.ttdpatch.net/tiki-index.php?page=BaseCosts
* @param base_pointer TTD(P) Base Price Pointer
* @param error_location Function name for grf error messages
* @param[out] index If \a base_pointer is valid, \a index is assigned to the matching price; else it is left unchanged
*/
static void ConvertTTDBasePrice(uint32 base_pointer, const char *error_location, Price *index)
{
/* Special value for 'none' */
if (base_pointer == 0) {
*index = INVALID_PRICE;
return;
}
static const uint32 start = 0x4B34; ///< Position of first base price
static const uint32 size = 6; ///< Size of each base price record
if (base_pointer < start || (base_pointer - start) % size != 0 || (base_pointer - start) / size >= PR_END) {
grfmsg(1, "%s: Unsupported running cost base 0x%04X, ignoring", error_location, base_pointer);
return;
}
*index = (Price)((base_pointer - start) / size);
}
/** Possible return values for the FeatureChangeInfo functions */
enum ChangeInfoResult {
CIR_SUCCESS, ///< Variable was parsed and read
CIR_DISABLED, ///< GRF was disabled due to error
CIR_UNHANDLED, ///< Variable was parsed but unread
CIR_UNKNOWN, ///< Variable is unknown
CIR_INVALID_ID, ///< Attempt to modify an invalid ID
};
typedef ChangeInfoResult (*VCI_Handler)(uint engine, int numinfo, int prop, const GRFFilePropertyRemapEntry *mapping_entry, ByteReader *buf);