Fix 03cc0d6: Mark level crossings dirty when removing road from them, not from bridge...
[openttd-github.git] / src / newgrf.cpp
blob09e8c6fd4eddad47d8cfefad52667c42b747f844
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file newgrf.cpp Base of all NewGRF support. */
10 #include "stdafx.h"
12 #include <stdarg.h>
14 #include "debug.h"
15 #include "fileio_func.h"
16 #include "engine_func.h"
17 #include "engine_base.h"
18 #include "bridge.h"
19 #include "town.h"
20 #include "newgrf_engine.h"
21 #include "newgrf_text.h"
22 #include "fontcache.h"
23 #include "currency.h"
24 #include "landscape.h"
25 #include "newgrf_cargo.h"
26 #include "newgrf_house.h"
27 #include "newgrf_sound.h"
28 #include "newgrf_station.h"
29 #include "industrytype.h"
30 #include "industry_map.h"
31 #include "newgrf_canal.h"
32 #include "newgrf_townname.h"
33 #include "newgrf_industries.h"
34 #include "newgrf_airporttiles.h"
35 #include "newgrf_airport.h"
36 #include "newgrf_object.h"
37 #include "rev.h"
38 #include "fios.h"
39 #include "strings_func.h"
40 #include "date_func.h"
41 #include "string_func.h"
42 #include "network/core/config.h"
43 #include <map>
44 #include "smallmap_gui.h"
45 #include "genworld.h"
46 #include "error.h"
47 #include "vehicle_func.h"
48 #include "language.h"
49 #include "vehicle_base.h"
50 #include "road.h"
52 #include "table/strings.h"
53 #include "table/build_industry.h"
55 #include "safeguards.h"
57 /* TTDPatch extended GRF format codec
58 * (c) Petr Baudis 2004 (GPL'd)
59 * Changes by Florian octo Forster are (c) by the OpenTTD development team.
61 * Contains portions of documentation by TTDPatch team.
62 * Thanks especially to Josef Drexler for the documentation as well as a lot
63 * of help at #tycoon. Also thanks to Michael Blunck for his GRF files which
64 * served as subject to the initial testing of this codec. */
66 /** List of all loaded GRF files */
67 static std::vector<GRFFile *> _grf_files;
69 const std::vector<GRFFile *> &GetAllGRFFiles()
71 return _grf_files;
74 /** Miscellaneous GRF features, set by Action 0x0D, parameter 0x9E */
75 byte _misc_grf_features = 0;
77 /** 32 * 8 = 256 flags. Apparently TTDPatch uses this many.. */
78 static uint32 _ttdpatch_flags[8];
80 /** Indicates which are the newgrf features currently loaded ingame */
81 GRFLoadedFeatures _loaded_newgrf_features;
83 static const uint MAX_SPRITEGROUP = UINT8_MAX; ///< Maximum GRF-local ID for a spritegroup.
85 /** Temporary data during loading of GRFs */
86 struct GrfProcessingState {
87 private:
88 /** Definition of a single Action1 spriteset */
89 struct SpriteSet {
90 SpriteID sprite; ///< SpriteID of the first sprite of the set.
91 uint num_sprites; ///< Number of sprites in the set.
94 /** Currently referenceable spritesets */
95 std::map<uint, SpriteSet> spritesets[GSF_END];
97 public:
98 /* Global state */
99 GrfLoadingStage stage; ///< Current loading stage
100 SpriteID spriteid; ///< First available SpriteID for loading realsprites.
102 /* Local state in the file */
103 SpriteFile *file; ///< File of currently processed GRF file.
104 GRFFile *grffile; ///< Currently processed GRF file.
105 GRFConfig *grfconfig; ///< Config of the currently processed GRF file.
106 uint32 nfo_line; ///< Currently processed pseudo sprite number in the GRF.
108 /* Kind of return values when processing certain actions */
109 int skip_sprites; ///< Number of pseudo sprites to skip before processing the next one. (-1 to skip to end of file)
111 /* Currently referenceable spritegroups */
112 const SpriteGroup *spritegroups[MAX_SPRITEGROUP + 1];
114 /** Clear temporary data before processing the next file in the current loading stage */
115 void ClearDataForNextFile()
117 this->nfo_line = 0;
118 this->skip_sprites = 0;
120 for (uint i = 0; i < GSF_END; i++) {
121 this->spritesets[i].clear();
124 memset(this->spritegroups, 0, sizeof(this->spritegroups));
128 * Records new spritesets.
129 * @param feature GrfSpecFeature the set is defined for.
130 * @param first_sprite SpriteID of the first sprite in the set.
131 * @param first_set First spriteset to define.
132 * @param numsets Number of sets to define.
133 * @param numents Number of sprites per set to define.
135 void AddSpriteSets(byte feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
137 assert(feature < GSF_END);
138 for (uint i = 0; i < numsets; i++) {
139 SpriteSet &set = this->spritesets[feature][first_set + i];
140 set.sprite = first_sprite + i * numents;
141 set.num_sprites = numents;
146 * Check whether there are any valid spritesets for a feature.
147 * @param feature GrfSpecFeature to check.
148 * @return true if there are any valid sets.
149 * @note Spritesets with zero sprites are valid to allow callback-failures.
151 bool HasValidSpriteSets(byte feature) const
153 assert(feature < GSF_END);
154 return !this->spritesets[feature].empty();
158 * Check whether a specific set is defined.
159 * @param feature GrfSpecFeature to check.
160 * @param set Set to check.
161 * @return true if the set is valid.
162 * @note Spritesets with zero sprites are valid to allow callback-failures.
164 bool IsValidSpriteSet(byte feature, uint set) const
166 assert(feature < GSF_END);
167 return this->spritesets[feature].find(set) != this->spritesets[feature].end();
171 * Returns the first sprite of a spriteset.
172 * @param feature GrfSpecFeature to query.
173 * @param set Set to query.
174 * @return First sprite of the set.
176 SpriteID GetSprite(byte feature, uint set) const
178 assert(IsValidSpriteSet(feature, set));
179 return this->spritesets[feature].find(set)->second.sprite;
183 * Returns the number of sprites in a spriteset
184 * @param feature GrfSpecFeature to query.
185 * @param set Set to query.
186 * @return Number of sprites in the set.
188 uint GetNumEnts(byte feature, uint set) const
190 assert(IsValidSpriteSet(feature, set));
191 return this->spritesets[feature].find(set)->second.num_sprites;
195 static GrfProcessingState _cur;
199 * Helper to check whether an image index is valid for a particular NewGRF vehicle.
200 * @tparam T The type of vehicle.
201 * @param image_index The image index to check.
202 * @return True iff the image index is valid, or 0xFD (use new graphics).
204 template <VehicleType T>
205 static inline bool IsValidNewGRFImageIndex(uint8 image_index)
207 return image_index == 0xFD || IsValidImageIndex<T>(image_index);
210 class OTTDByteReaderSignal { };
212 /** Class to read from a NewGRF file */
213 class ByteReader {
214 protected:
215 byte *data;
216 byte *end;
218 public:
219 ByteReader(byte *data, byte *end) : data(data), end(end) { }
221 inline byte *ReadBytes(size_t size)
223 if (data + size >= end) {
224 /* Put data at the end, as would happen if every byte had been individually read. */
225 data = end;
226 throw OTTDByteReaderSignal();
229 byte *ret = data;
230 data += size;
231 return ret;
234 inline byte ReadByte()
236 if (data < end) return *(data)++;
237 throw OTTDByteReaderSignal();
240 uint16 ReadWord()
242 uint16 val = ReadByte();
243 return val | (ReadByte() << 8);
246 uint16 ReadExtendedByte()
248 uint16 val = ReadByte();
249 return val == 0xFF ? ReadWord() : val;
252 uint32 ReadDWord()
254 uint32 val = ReadWord();
255 return val | (ReadWord() << 16);
258 uint32 ReadVarSize(byte size)
260 switch (size) {
261 case 1: return ReadByte();
262 case 2: return ReadWord();
263 case 4: return ReadDWord();
264 default:
265 NOT_REACHED();
266 return 0;
270 const char *ReadString()
272 char *string = reinterpret_cast<char *>(data);
273 size_t string_length = ttd_strnlen(string, Remaining());
275 if (string_length == Remaining()) {
276 /* String was not NUL terminated, so make sure it is now. */
277 string[string_length - 1] = '\0';
278 grfmsg(7, "String was not terminated with a zero byte.");
279 } else {
280 /* Increase the string length to include the NUL byte. */
281 string_length++;
283 Skip(string_length);
285 return string;
288 inline size_t Remaining() const
290 return end - data;
293 inline bool HasData(size_t count = 1) const
295 return data + count <= end;
298 inline byte *Data()
300 return data;
303 inline void Skip(size_t len)
305 data += len;
306 /* It is valid to move the buffer to exactly the end of the data,
307 * as there may not be any more data read. */
308 if (data > end) throw OTTDByteReaderSignal();
312 typedef void (*SpecialSpriteHandler)(ByteReader *buf);
314 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.
316 /** Temporary engine data used when loading only */
317 struct GRFTempEngineData {
318 /** Summary state of refittability properties */
319 enum Refittability {
320 UNSET = 0, ///< No properties assigned. Default refit masks shall be activated.
321 EMPTY, ///< GRF defined vehicle as not-refittable. The vehicle shall only carry the default cargo.
322 NONEMPTY, ///< GRF defined the vehicle as refittable. If the refitmask is empty after translation (cargotypes not available), disable the vehicle.
325 uint16 cargo_allowed;
326 uint16 cargo_disallowed;
327 RailTypeLabel railtypelabel;
328 uint8 roadtramtype;
329 const GRFFile *defaultcargo_grf; ///< GRF defining the cargo translation table to use if the default cargo is the 'first refittable'.
330 Refittability refittability; ///< Did the newgrf set any refittability property? If not, default refittability will be applied.
331 bool prop27_set; ///< Did the NewGRF set property 27 (misc flags)?
332 uint8 rv_max_speed; ///< Temporary storage of RV prop 15, maximum speed in mph/0.8
333 CargoTypes ctt_include_mask; ///< Cargo types always included in the refit mask.
334 CargoTypes ctt_exclude_mask; ///< Cargo types always excluded from the refit mask.
337 * Update the summary refittability on setting a refittability property.
338 * @param non_empty true if the GRF sets the vehicle to be refittable.
340 void UpdateRefittability(bool non_empty)
342 if (non_empty) {
343 this->refittability = NONEMPTY;
344 } else if (this->refittability == UNSET) {
345 this->refittability = EMPTY;
350 static GRFTempEngineData *_gted; ///< Temporary engine data used during NewGRF loading
353 * Contains the GRF ID of the owner of a vehicle if it has been reserved.
354 * GRM for vehicles is only used if dynamic engine allocation is disabled,
355 * so 256 is the number of original engines. */
356 static uint32 _grm_engines[256];
358 /** Contains the GRF ID of the owner of a cargo if it has been reserved */
359 static uint32 _grm_cargoes[NUM_CARGO * 2];
361 struct GRFLocation {
362 uint32 grfid;
363 uint32 nfoline;
365 GRFLocation(uint32 grfid, uint32 nfoline) : grfid(grfid), nfoline(nfoline) { }
367 bool operator<(const GRFLocation &other) const
369 return this->grfid < other.grfid || (this->grfid == other.grfid && this->nfoline < other.nfoline);
372 bool operator == (const GRFLocation &other) const
374 return this->grfid == other.grfid && this->nfoline == other.nfoline;
378 static std::map<GRFLocation, SpriteID> _grm_sprites;
379 typedef std::map<GRFLocation, byte*> GRFLineToSpriteOverride;
380 static GRFLineToSpriteOverride _grf_line_to_action6_sprite_override;
383 * Debug() function dedicated to newGRF debugging messages
384 * Function is essentially the same as Debug(grf, severity, ...) with the
385 * addition of file:line information when parsing grf files.
386 * NOTE: for the above reason(s) grfmsg() should ONLY be used for
387 * loading/parsing grf files, not for runtime debug messages as there
388 * is no file information available during that time.
389 * @param severity debugging severity level, see debug.h
390 * @param str message in printf() format
392 void CDECL grfmsg(int severity, const char *str, ...)
394 char buf[1024];
395 va_list va;
397 va_start(va, str);
398 vseprintf(buf, lastof(buf), str, va);
399 va_end(va);
401 Debug(grf, severity, "[{}:{}] {}", _cur.grfconfig->filename, _cur.nfo_line, buf);
405 * Obtain a NewGRF file by its grfID
406 * @param grfid The grfID to obtain the file for
407 * @return The file.
409 static GRFFile *GetFileByGRFID(uint32 grfid)
411 for (GRFFile * const file : _grf_files) {
412 if (file->grfid == grfid) return file;
414 return nullptr;
418 * Obtain a NewGRF file by its filename
419 * @param filename The filename to obtain the file for.
420 * @return The file.
422 static GRFFile *GetFileByFilename(const char *filename)
424 for (GRFFile * const file : _grf_files) {
425 if (strcmp(file->filename, filename) == 0) return file;
427 return nullptr;
430 /** Reset all NewGRFData that was used only while processing data */
431 static void ClearTemporaryNewGRFData(GRFFile *gf)
433 /* Clear the GOTO labels used for GRF processing */
434 for (GRFLabel *l = gf->label; l != nullptr;) {
435 GRFLabel *l2 = l->next;
436 free(l);
437 l = l2;
439 gf->label = nullptr;
443 * Disable a GRF
444 * @param message Error message or STR_NULL.
445 * @param config GRFConfig to disable, nullptr for current.
446 * @return Error message of the GRF for further customisation.
448 static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = nullptr)
450 GRFFile *file;
451 if (config != nullptr) {
452 file = GetFileByGRFID(config->ident.grfid);
453 } else {
454 config = _cur.grfconfig;
455 file = _cur.grffile;
458 config->status = GCS_DISABLED;
459 if (file != nullptr) ClearTemporaryNewGRFData(file);
460 if (config == _cur.grfconfig) _cur.skip_sprites = -1;
462 if (message != STR_NULL) {
463 delete config->error;
464 config->error = new GRFError(STR_NEWGRF_ERROR_MSG_FATAL, message);
465 if (config == _cur.grfconfig) config->error->param_value[0] = _cur.nfo_line;
468 return config->error;
472 * Information for mapping static StringIDs.
474 struct StringIDMapping {
475 uint32 grfid; ///< Source NewGRF.
476 StringID source; ///< Source StringID (GRF local).
477 StringID *target; ///< Destination for mapping result.
479 typedef std::vector<StringIDMapping> StringIDMappingVector;
480 static StringIDMappingVector _string_to_grf_mapping;
483 * Record a static StringID for getting translated later.
484 * @param source Source StringID (GRF local).
485 * @param target Destination for the mapping result.
487 static void AddStringForMapping(StringID source, StringID *target)
489 *target = STR_UNDEFINED;
490 _string_to_grf_mapping.push_back({_cur.grffile->grfid, source, target});
494 * Perform a mapping from TTDPatch's string IDs to OpenTTD's
495 * string IDs, but only for the ones we are aware off; the rest
496 * like likely unused and will show a warning.
497 * @param str the string ID to convert
498 * @return the converted string ID
500 static StringID TTDPStringIDToOTTDStringIDMapping(StringID str)
502 /* StringID table for TextIDs 0x4E->0x6D */
503 static const StringID units_volume[] = {
504 STR_ITEMS, STR_PASSENGERS, STR_TONS, STR_BAGS,
505 STR_LITERS, STR_ITEMS, STR_CRATES, STR_TONS,
506 STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
507 STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
508 STR_TONS, STR_TONS, STR_BAGS, STR_LITERS,
509 STR_TONS, STR_LITERS, STR_TONS, STR_ITEMS,
510 STR_BAGS, STR_LITERS, STR_TONS, STR_ITEMS,
511 STR_TONS, STR_ITEMS, STR_LITERS, STR_ITEMS
514 /* A string straight from a NewGRF; this was already translated by MapGRFStringID(). */
515 assert(!IsInsideMM(str, 0xD000, 0xD7FF));
517 #define TEXTID_TO_STRINGID(begin, end, stringid, stringend) \
518 static_assert(stringend - stringid == end - begin); \
519 if (str >= begin && str <= end) return str + (stringid - begin)
521 /* We have some changes in our cargo strings, resulting in some missing. */
522 TEXTID_TO_STRINGID(0x000E, 0x002D, STR_CARGO_PLURAL_NOTHING, STR_CARGO_PLURAL_FIZZY_DRINKS);
523 TEXTID_TO_STRINGID(0x002E, 0x004D, STR_CARGO_SINGULAR_NOTHING, STR_CARGO_SINGULAR_FIZZY_DRINK);
524 if (str >= 0x004E && str <= 0x006D) return units_volume[str - 0x004E];
525 TEXTID_TO_STRINGID(0x006E, 0x008D, STR_QUANTITY_NOTHING, STR_QUANTITY_FIZZY_DRINKS);
526 TEXTID_TO_STRINGID(0x008E, 0x00AD, STR_ABBREV_NOTHING, STR_ABBREV_FIZZY_DRINKS);
527 TEXTID_TO_STRINGID(0x00D1, 0x00E0, STR_COLOUR_DARK_BLUE, STR_COLOUR_WHITE);
529 /* Map building names according to our lang file changes. There are several
530 * ranges of house ids, all of which need to be remapped to allow newgrfs
531 * to use original house names. */
532 TEXTID_TO_STRINGID(0x200F, 0x201F, STR_TOWN_BUILDING_NAME_TALL_OFFICE_BLOCK_1, STR_TOWN_BUILDING_NAME_OLD_HOUSES_1);
533 TEXTID_TO_STRINGID(0x2036, 0x2041, STR_TOWN_BUILDING_NAME_COTTAGES_1, STR_TOWN_BUILDING_NAME_SHOPPING_MALL_1);
534 TEXTID_TO_STRINGID(0x2059, 0x205C, STR_TOWN_BUILDING_NAME_IGLOO_1, STR_TOWN_BUILDING_NAME_PIGGY_BANK_1);
536 /* Same thing for industries */
537 TEXTID_TO_STRINGID(0x4802, 0x4826, STR_INDUSTRY_NAME_COAL_MINE, STR_INDUSTRY_NAME_SUGAR_MINE);
538 TEXTID_TO_STRINGID(0x482D, 0x482E, STR_NEWS_INDUSTRY_CONSTRUCTION, STR_NEWS_INDUSTRY_PLANTED);
539 TEXTID_TO_STRINGID(0x4832, 0x4834, STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_CLOSURE_LACK_OF_TREES);
540 TEXTID_TO_STRINGID(0x4835, 0x4838, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM);
541 TEXTID_TO_STRINGID(0x4839, 0x483A, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM);
543 switch (str) {
544 case 0x4830: return STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY;
545 case 0x4831: return STR_ERROR_FOREST_CAN_ONLY_BE_PLANTED;
546 case 0x483B: return STR_ERROR_CAN_ONLY_BE_POSITIONED;
548 #undef TEXTID_TO_STRINGID
550 if (str == STR_NULL) return STR_EMPTY;
552 Debug(grf, 0, "Unknown StringID 0x{:04X} remapped to STR_EMPTY. Please open a Feature Request if you need it", str);
554 return STR_EMPTY;
558 * Used when setting an object's property to map to the GRF's strings
559 * while taking in consideration the "drift" between TTDPatch string system and OpenTTD's one
560 * @param grfid Id of the grf file.
561 * @param str StringID that we want to have the equivalent in OoenTTD.
562 * @return The properly adjusted StringID.
564 StringID MapGRFStringID(uint32 grfid, StringID str)
566 if (IsInsideMM(str, 0xD800, 0xE000)) {
567 /* General text provided by NewGRF.
568 * In the specs this is called the 0xDCxx range (misc persistent texts),
569 * but we meanwhile extended the range to 0xD800-0xDFFF.
570 * Note: We are not involved in the "persistent" business, since we do not store
571 * any NewGRF strings in savegames. */
572 return GetGRFStringID(grfid, str);
573 } else if (IsInsideMM(str, 0xD000, 0xD800)) {
574 /* Callback text provided by NewGRF.
575 * In the specs this is called the 0xD0xx range (misc graphics texts).
576 * These texts can be returned by various callbacks.
578 * Due to how TTDP implements the GRF-local- to global-textid translation
579 * texts included via 0x80 or 0x81 control codes have to add 0x400 to the textid.
580 * We do not care about that difference and just mask out the 0x400 bit.
582 str &= ~0x400;
583 return GetGRFStringID(grfid, str);
584 } else {
585 /* The NewGRF wants to include/reference an original TTD string.
586 * Try our best to find an equivalent one. */
587 return TTDPStringIDToOTTDStringIDMapping(str);
591 static std::map<uint32, uint32> _grf_id_overrides;
594 * Set the override for a NewGRF
595 * @param source_grfid The grfID which wants to override another NewGRF.
596 * @param target_grfid The grfID which is being overridden.
598 static void SetNewGRFOverride(uint32 source_grfid, uint32 target_grfid)
600 _grf_id_overrides[source_grfid] = target_grfid;
601 grfmsg(5, "SetNewGRFOverride: Added override of 0x%X to 0x%X", BSWAP32(source_grfid), BSWAP32(target_grfid));
605 * Returns the engine associated to a certain internal_id, resp. allocates it.
606 * @param file NewGRF that wants to change the engine.
607 * @param type Vehicle type.
608 * @param internal_id Engine ID inside the NewGRF.
609 * @param static_access If the engine is not present, return nullptr instead of allocating a new engine. (Used for static Action 0x04).
610 * @return The requested engine.
612 static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16 internal_id, bool static_access = false)
614 /* Hack for add-on GRFs that need to modify another GRF's engines. This lets
615 * them use the same engine slots. */
616 uint32 scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
617 if (_settings_game.vehicle.dynamic_engines) {
618 /* If dynamic_engies is enabled, there can be multiple independent ID ranges. */
619 scope_grfid = file->grfid;
620 uint32 override = _grf_id_overrides[file->grfid];
621 if (override != 0) {
622 scope_grfid = override;
623 const GRFFile *grf_match = GetFileByGRFID(override);
624 if (grf_match == nullptr) {
625 grfmsg(5, "Tried mapping from GRFID %x to %x but target is not loaded", BSWAP32(file->grfid), BSWAP32(override));
626 } else {
627 grfmsg(5, "Mapping from GRFID %x to %x", BSWAP32(file->grfid), BSWAP32(override));
631 /* Check if the engine is registered in the override manager */
632 EngineID engine = _engine_mngr.GetID(type, internal_id, scope_grfid);
633 if (engine != INVALID_ENGINE) {
634 Engine *e = Engine::Get(engine);
635 if (e->grf_prop.grffile == nullptr) e->grf_prop.grffile = file;
636 return e;
640 /* Check if there is an unreserved slot */
641 EngineID engine = _engine_mngr.GetID(type, internal_id, INVALID_GRFID);
642 if (engine != INVALID_ENGINE) {
643 Engine *e = Engine::Get(engine);
645 if (e->grf_prop.grffile == nullptr) {
646 e->grf_prop.grffile = file;
647 grfmsg(5, "Replaced engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
650 /* Reserve the engine slot */
651 if (!static_access) {
652 EngineIDMapping *eid = _engine_mngr.data() + engine;
653 eid->grfid = scope_grfid; // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
656 return e;
659 if (static_access) return nullptr;
661 if (!Engine::CanAllocateItem()) {
662 grfmsg(0, "Can't allocate any more engines");
663 return nullptr;
666 size_t engine_pool_size = Engine::GetPoolSize();
668 /* ... it's not, so create a new one based off an existing engine */
669 Engine *e = new Engine(type, internal_id);
670 e->grf_prop.grffile = file;
672 /* Reserve the engine slot */
673 assert(_engine_mngr.size() == e->index);
674 _engine_mngr.push_back({
675 scope_grfid, // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
676 internal_id,
677 type,
678 std::min<uint8>(internal_id, _engine_counts[type]) // substitute_id == _engine_counts[subtype] means "no substitute"
681 if (engine_pool_size != Engine::GetPoolSize()) {
682 /* Resize temporary engine data ... */
683 _gted = ReallocT(_gted, Engine::GetPoolSize());
685 /* and blank the new block. */
686 size_t len = (Engine::GetPoolSize() - engine_pool_size) * sizeof(*_gted);
687 memset(_gted + engine_pool_size, 0, len);
689 if (type == VEH_TRAIN) {
690 _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
693 grfmsg(5, "Created new engine at index %d for GRFID %x, type %d, index %d", e->index, BSWAP32(file->grfid), type, internal_id);
695 return e;
699 * Return the ID of a new engine
700 * @param file The NewGRF file providing the engine.
701 * @param type The Vehicle type.
702 * @param internal_id NewGRF-internal ID of the engine.
703 * @return The new EngineID.
704 * @note depending on the dynamic_engine setting and a possible override
705 * property the grfID may be unique or overwriting or partially re-defining
706 * properties of an existing engine.
708 EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16 internal_id)
710 uint32 scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
711 if (_settings_game.vehicle.dynamic_engines) {
712 scope_grfid = file->grfid;
713 uint32 override = _grf_id_overrides[file->grfid];
714 if (override != 0) scope_grfid = override;
717 return _engine_mngr.GetID(type, internal_id, scope_grfid);
721 * Map the colour modifiers of TTDPatch to those that Open is using.
722 * @param grf_sprite Pointer to the structure been modified.
724 static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
726 if (HasBit(grf_sprite->pal, 14)) {
727 ClrBit(grf_sprite->pal, 14);
728 SetBit(grf_sprite->sprite, SPRITE_MODIFIER_OPAQUE);
731 if (HasBit(grf_sprite->sprite, 14)) {
732 ClrBit(grf_sprite->sprite, 14);
733 SetBit(grf_sprite->sprite, PALETTE_MODIFIER_TRANSPARENT);
736 if (HasBit(grf_sprite->sprite, 15)) {
737 ClrBit(grf_sprite->sprite, 15);
738 SetBit(grf_sprite->sprite, PALETTE_MODIFIER_COLOUR);
743 * Read a sprite and a palette from the GRF and convert them into a format
744 * suitable to OpenTTD.
745 * @param buf Input stream.
746 * @param read_flags Whether to read TileLayoutFlags.
747 * @param invert_action1_flag Set to true, if palette bit 15 means 'not from action 1'.
748 * @param use_cur_spritesets Whether to use currently referenceable action 1 sets.
749 * @param feature GrfSpecFeature to use spritesets from.
750 * @param[out] grf_sprite Read sprite and palette.
751 * @param[out] max_sprite_offset Optionally returns the number of sprites in the spriteset of the sprite. (0 if no spritset)
752 * @param[out] max_palette_offset Optionally returns the number of sprites in the spriteset of the palette. (0 if no spritset)
753 * @return Read TileLayoutFlags.
755 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)
757 grf_sprite->sprite = buf->ReadWord();
758 grf_sprite->pal = buf->ReadWord();
759 TileLayoutFlags flags = read_flags ? (TileLayoutFlags)buf->ReadWord() : TLF_NOTHING;
761 MapSpriteMappingRecolour(grf_sprite);
763 bool custom_sprite = HasBit(grf_sprite->pal, 15) != invert_action1_flag;
764 ClrBit(grf_sprite->pal, 15);
765 if (custom_sprite) {
766 /* Use sprite from Action 1 */
767 uint index = GB(grf_sprite->sprite, 0, 14);
768 if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
769 grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset %d", index);
770 grf_sprite->sprite = SPR_IMG_QUERY;
771 grf_sprite->pal = PAL_NONE;
772 } else {
773 SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
774 if (max_sprite_offset != nullptr) *max_sprite_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
775 SB(grf_sprite->sprite, 0, SPRITE_WIDTH, sprite);
776 SetBit(grf_sprite->sprite, SPRITE_MODIFIER_CUSTOM_SPRITE);
778 } else if ((flags & TLF_SPRITE_VAR10) && !(flags & TLF_SPRITE_REG_FLAGS)) {
779 grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout specifies var10 value for non-action-1 sprite");
780 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
781 return flags;
784 if (flags & TLF_CUSTOM_PALETTE) {
785 /* Use palette from Action 1 */
786 uint index = GB(grf_sprite->pal, 0, 14);
787 if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
788 grfmsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset %d for 'palette'", index);
789 grf_sprite->pal = PAL_NONE;
790 } else {
791 SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
792 if (max_palette_offset != nullptr) *max_palette_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
793 SB(grf_sprite->pal, 0, SPRITE_WIDTH, sprite);
794 SetBit(grf_sprite->pal, SPRITE_MODIFIER_CUSTOM_SPRITE);
796 } else if ((flags & TLF_PALETTE_VAR10) && !(flags & TLF_PALETTE_REG_FLAGS)) {
797 grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 value for non-action-1 palette");
798 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
799 return flags;
802 return flags;
806 * Preprocess the TileLayoutFlags and read register modifiers from the GRF.
807 * @param buf Input stream.
808 * @param flags TileLayoutFlags to process.
809 * @param is_parent Whether the sprite is a parentsprite with a bounding box.
810 * @param dts Sprite layout to insert data into.
811 * @param index Sprite index to process; 0 for ground sprite.
813 static void ReadSpriteLayoutRegisters(ByteReader *buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
815 if (!(flags & TLF_DRAWING_FLAGS)) return;
817 if (dts->registers == nullptr) dts->AllocateRegisters();
818 TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[index]);
819 regs.flags = flags & TLF_DRAWING_FLAGS;
821 if (flags & TLF_DODRAW) regs.dodraw = buf->ReadByte();
822 if (flags & TLF_SPRITE) regs.sprite = buf->ReadByte();
823 if (flags & TLF_PALETTE) regs.palette = buf->ReadByte();
825 if (is_parent) {
826 if (flags & TLF_BB_XY_OFFSET) {
827 regs.delta.parent[0] = buf->ReadByte();
828 regs.delta.parent[1] = buf->ReadByte();
830 if (flags & TLF_BB_Z_OFFSET) regs.delta.parent[2] = buf->ReadByte();
831 } else {
832 if (flags & TLF_CHILD_X_OFFSET) regs.delta.child[0] = buf->ReadByte();
833 if (flags & TLF_CHILD_Y_OFFSET) regs.delta.child[1] = buf->ReadByte();
836 if (flags & TLF_SPRITE_VAR10) {
837 regs.sprite_var10 = buf->ReadByte();
838 if (regs.sprite_var10 > TLR_MAX_VAR10) {
839 grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 (%d) exceeding the maximal allowed value %d", regs.sprite_var10, TLR_MAX_VAR10);
840 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
841 return;
845 if (flags & TLF_PALETTE_VAR10) {
846 regs.palette_var10 = buf->ReadByte();
847 if (regs.palette_var10 > TLR_MAX_VAR10) {
848 grfmsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 (%d) exceeding the maximal allowed value %d", regs.palette_var10, TLR_MAX_VAR10);
849 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
850 return;
856 * Read a spritelayout from the GRF.
857 * @param buf Input
858 * @param num_building_sprites Number of building sprites to read
859 * @param use_cur_spritesets Whether to use currently referenceable action 1 sets.
860 * @param feature GrfSpecFeature to use spritesets from.
861 * @param allow_var10 Whether the spritelayout may specify var10 values for resolving multiple action-1-2-3 chains
862 * @param no_z_position Whether bounding boxes have no Z offset
863 * @param dts Layout container to output into
864 * @return True on error (GRF was disabled).
866 static bool ReadSpriteLayout(ByteReader *buf, uint num_building_sprites, bool use_cur_spritesets, byte feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts)
868 bool has_flags = HasBit(num_building_sprites, 6);
869 ClrBit(num_building_sprites, 6);
870 TileLayoutFlags valid_flags = TLF_KNOWN_FLAGS;
871 if (!allow_var10) valid_flags &= ~TLF_VAR10_FLAGS;
872 dts->Allocate(num_building_sprites); // allocate before reading groundsprite flags
874 uint16 *max_sprite_offset = AllocaM(uint16, num_building_sprites + 1);
875 uint16 *max_palette_offset = AllocaM(uint16, num_building_sprites + 1);
876 MemSetT(max_sprite_offset, 0, num_building_sprites + 1);
877 MemSetT(max_palette_offset, 0, num_building_sprites + 1);
879 /* Groundsprite */
880 TileLayoutFlags flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &dts->ground, max_sprite_offset, max_palette_offset);
881 if (_cur.skip_sprites < 0) return true;
883 if (flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS)) {
884 grfmsg(1, "ReadSpriteLayout: Spritelayout uses invalid flag 0x%x for ground sprite", flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS));
885 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
886 return true;
889 ReadSpriteLayoutRegisters(buf, flags, false, dts, 0);
890 if (_cur.skip_sprites < 0) return true;
892 for (uint i = 0; i < num_building_sprites; i++) {
893 DrawTileSeqStruct *seq = const_cast<DrawTileSeqStruct*>(&dts->seq[i]);
895 flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &seq->image, max_sprite_offset + i + 1, max_palette_offset + i + 1);
896 if (_cur.skip_sprites < 0) return true;
898 if (flags & ~valid_flags) {
899 grfmsg(1, "ReadSpriteLayout: Spritelayout uses unknown flag 0x%x", flags & ~valid_flags);
900 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
901 return true;
904 seq->delta_x = buf->ReadByte();
905 seq->delta_y = buf->ReadByte();
907 if (!no_z_position) seq->delta_z = buf->ReadByte();
909 if (seq->IsParentSprite()) {
910 seq->size_x = buf->ReadByte();
911 seq->size_y = buf->ReadByte();
912 seq->size_z = buf->ReadByte();
915 ReadSpriteLayoutRegisters(buf, flags, seq->IsParentSprite(), dts, i + 1);
916 if (_cur.skip_sprites < 0) return true;
919 /* Check if the number of sprites per spriteset is consistent */
920 bool is_consistent = true;
921 dts->consistent_max_offset = 0;
922 for (uint i = 0; i < num_building_sprites + 1; i++) {
923 if (max_sprite_offset[i] > 0) {
924 if (dts->consistent_max_offset == 0) {
925 dts->consistent_max_offset = max_sprite_offset[i];
926 } else if (dts->consistent_max_offset != max_sprite_offset[i]) {
927 is_consistent = false;
928 break;
931 if (max_palette_offset[i] > 0) {
932 if (dts->consistent_max_offset == 0) {
933 dts->consistent_max_offset = max_palette_offset[i];
934 } else if (dts->consistent_max_offset != max_palette_offset[i]) {
935 is_consistent = false;
936 break;
941 /* When the Action1 sets are unknown, everything should be 0 (no spriteset usage) or UINT16_MAX (some spriteset usage) */
942 assert(use_cur_spritesets || (is_consistent && (dts->consistent_max_offset == 0 || dts->consistent_max_offset == UINT16_MAX)));
944 if (!is_consistent || dts->registers != nullptr) {
945 dts->consistent_max_offset = 0;
946 if (dts->registers == nullptr) dts->AllocateRegisters();
948 for (uint i = 0; i < num_building_sprites + 1; i++) {
949 TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[i]);
950 regs.max_sprite_offset = max_sprite_offset[i];
951 regs.max_palette_offset = max_palette_offset[i];
955 return false;
959 * Translate the refit mask. refit_mask is uint32 as it has not been mapped to CargoTypes.
961 static CargoTypes TranslateRefitMask(uint32 refit_mask)
963 CargoTypes result = 0;
964 for (uint8 bit : SetBitIterator(refit_mask)) {
965 CargoID cargo = GetCargoTranslation(bit, _cur.grffile, true);
966 if (cargo != CT_INVALID) SetBit(result, cargo);
968 return result;
972 * Converts TTD(P) Base Price pointers into the enum used by OTTD
973 * See http://wiki.ttdpatch.net/tiki-index.php?page=BaseCosts
974 * @param base_pointer TTD(P) Base Price Pointer
975 * @param error_location Function name for grf error messages
976 * @param[out] index If \a base_pointer is valid, \a index is assigned to the matching price; else it is left unchanged
978 static void ConvertTTDBasePrice(uint32 base_pointer, const char *error_location, Price *index)
980 /* Special value for 'none' */
981 if (base_pointer == 0) {
982 *index = INVALID_PRICE;
983 return;
986 static const uint32 start = 0x4B34; ///< Position of first base price
987 static const uint32 size = 6; ///< Size of each base price record
989 if (base_pointer < start || (base_pointer - start) % size != 0 || (base_pointer - start) / size >= PR_END) {
990 grfmsg(1, "%s: Unsupported running cost base 0x%04X, ignoring", error_location, base_pointer);
991 return;
994 *index = (Price)((base_pointer - start) / size);
997 /** Possible return values for the FeatureChangeInfo functions */
998 enum ChangeInfoResult {
999 CIR_SUCCESS, ///< Variable was parsed and read
1000 CIR_DISABLED, ///< GRF was disabled due to error
1001 CIR_UNHANDLED, ///< Variable was parsed but unread
1002 CIR_UNKNOWN, ///< Variable is unknown
1003 CIR_INVALID_ID, ///< Attempt to modify an invalid ID
1006 typedef ChangeInfoResult (*VCI_Handler)(uint engine, int numinfo, int prop, ByteReader *buf);
1009 * Define properties common to all vehicles
1010 * @param ei Engine info.
1011 * @param prop The property to change.
1012 * @param buf The property value.
1013 * @return ChangeInfoResult.
1015 static ChangeInfoResult CommonVehicleChangeInfo(EngineInfo *ei, int prop, ByteReader *buf)
1017 switch (prop) {
1018 case 0x00: // Introduction date
1019 ei->base_intro = buf->ReadWord() + DAYS_TILL_ORIGINAL_BASE_YEAR;
1020 break;
1022 case 0x02: // Decay speed
1023 ei->decay_speed = buf->ReadByte();
1024 break;
1026 case 0x03: // Vehicle life
1027 ei->lifelength = buf->ReadByte();
1028 break;
1030 case 0x04: // Model life
1031 ei->base_life = buf->ReadByte();
1032 break;
1034 case 0x06: // Climates available
1035 ei->climates = buf->ReadByte();
1036 break;
1038 case PROP_VEHICLE_LOAD_AMOUNT: // 0x07 Loading speed
1039 /* Amount of cargo loaded during a vehicle's "loading tick" */
1040 ei->load_amount = buf->ReadByte();
1041 break;
1043 default:
1044 return CIR_UNKNOWN;
1047 return CIR_SUCCESS;
1051 * Define properties for rail vehicles
1052 * @param engine :ocal ID of the first vehicle.
1053 * @param numinfo Number of subsequent IDs to change the property for.
1054 * @param prop The property to change.
1055 * @param buf The property value.
1056 * @return ChangeInfoResult.
1058 static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1060 ChangeInfoResult ret = CIR_SUCCESS;
1062 for (int i = 0; i < numinfo; i++) {
1063 Engine *e = GetNewEngine(_cur.grffile, VEH_TRAIN, engine + i);
1064 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1066 EngineInfo *ei = &e->info;
1067 RailVehicleInfo *rvi = &e->u.rail;
1069 switch (prop) {
1070 case 0x05: { // Track type
1071 uint8 tracktype = buf->ReadByte();
1073 if (tracktype < _cur.grffile->railtype_list.size()) {
1074 _gted[e->index].railtypelabel = _cur.grffile->railtype_list[tracktype];
1075 break;
1078 switch (tracktype) {
1079 case 0: _gted[e->index].railtypelabel = rvi->engclass >= 2 ? RAILTYPE_ELECTRIC_LABEL : RAILTYPE_RAIL_LABEL; break;
1080 case 1: _gted[e->index].railtypelabel = RAILTYPE_MONO_LABEL; break;
1081 case 2: _gted[e->index].railtypelabel = RAILTYPE_MAGLEV_LABEL; break;
1082 default:
1083 grfmsg(1, "RailVehicleChangeInfo: Invalid track type %d specified, ignoring", tracktype);
1084 break;
1086 break;
1089 case 0x08: // AI passenger service
1090 /* Tells the AI that this engine is designed for
1091 * passenger services and shouldn't be used for freight. */
1092 rvi->ai_passenger_only = buf->ReadByte();
1093 break;
1095 case PROP_TRAIN_SPEED: { // 0x09 Speed (1 unit is 1 km-ish/h)
1096 uint16 speed = buf->ReadWord();
1097 if (speed == 0xFFFF) speed = 0;
1099 rvi->max_speed = speed;
1100 break;
1103 case PROP_TRAIN_POWER: // 0x0B Power
1104 rvi->power = buf->ReadWord();
1106 /* Set engine / wagon state based on power */
1107 if (rvi->power != 0) {
1108 if (rvi->railveh_type == RAILVEH_WAGON) {
1109 rvi->railveh_type = RAILVEH_SINGLEHEAD;
1111 } else {
1112 rvi->railveh_type = RAILVEH_WAGON;
1114 break;
1116 case PROP_TRAIN_RUNNING_COST_FACTOR: // 0x0D Running cost factor
1117 rvi->running_cost = buf->ReadByte();
1118 break;
1120 case 0x0E: // Running cost base
1121 ConvertTTDBasePrice(buf->ReadDWord(), "RailVehicleChangeInfo", &rvi->running_cost_class);
1122 break;
1124 case 0x12: { // Sprite ID
1125 uint8 spriteid = buf->ReadByte();
1126 uint8 orig_spriteid = spriteid;
1128 /* TTD sprite IDs point to a location in a 16bit array, but we use it
1129 * as an array index, so we need it to be half the original value. */
1130 if (spriteid < 0xFD) spriteid >>= 1;
1132 if (IsValidNewGRFImageIndex<VEH_TRAIN>(spriteid)) {
1133 rvi->image_index = spriteid;
1134 } else {
1135 grfmsg(1, "RailVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1136 rvi->image_index = 0;
1138 break;
1141 case 0x13: { // Dual-headed
1142 uint8 dual = buf->ReadByte();
1144 if (dual != 0) {
1145 rvi->railveh_type = RAILVEH_MULTIHEAD;
1146 } else {
1147 rvi->railveh_type = rvi->power == 0 ?
1148 RAILVEH_WAGON : RAILVEH_SINGLEHEAD;
1150 break;
1153 case PROP_TRAIN_CARGO_CAPACITY: // 0x14 Cargo capacity
1154 rvi->capacity = buf->ReadByte();
1155 break;
1157 case 0x15: { // Cargo type
1158 _gted[e->index].defaultcargo_grf = _cur.grffile;
1159 uint8 ctype = buf->ReadByte();
1161 if (ctype == 0xFF) {
1162 /* 0xFF is specified as 'use first refittable' */
1163 ei->cargo_type = CT_INVALID;
1164 } else if (_cur.grffile->grf_version >= 8) {
1165 /* Use translated cargo. Might result in CT_INVALID (first refittable), if cargo is not defined. */
1166 ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1167 } else if (ctype < NUM_CARGO) {
1168 /* Use untranslated cargo. */
1169 ei->cargo_type = ctype;
1170 } else {
1171 ei->cargo_type = CT_INVALID;
1172 grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
1174 break;
1177 case PROP_TRAIN_WEIGHT: // 0x16 Weight
1178 SB(rvi->weight, 0, 8, buf->ReadByte());
1179 break;
1181 case PROP_TRAIN_COST_FACTOR: // 0x17 Cost factor
1182 rvi->cost_factor = buf->ReadByte();
1183 break;
1185 case 0x18: // AI rank
1186 grfmsg(2, "RailVehicleChangeInfo: Property 0x18 'AI rank' not used by NoAI, ignored.");
1187 buf->ReadByte();
1188 break;
1190 case 0x19: { // Engine traction type
1191 /* What do the individual numbers mean?
1192 * 0x00 .. 0x07: Steam
1193 * 0x08 .. 0x27: Diesel
1194 * 0x28 .. 0x31: Electric
1195 * 0x32 .. 0x37: Monorail
1196 * 0x38 .. 0x41: Maglev
1198 uint8 traction = buf->ReadByte();
1199 EngineClass engclass;
1201 if (traction <= 0x07) {
1202 engclass = EC_STEAM;
1203 } else if (traction <= 0x27) {
1204 engclass = EC_DIESEL;
1205 } else if (traction <= 0x31) {
1206 engclass = EC_ELECTRIC;
1207 } else if (traction <= 0x37) {
1208 engclass = EC_MONORAIL;
1209 } else if (traction <= 0x41) {
1210 engclass = EC_MAGLEV;
1211 } else {
1212 break;
1215 if (_cur.grffile->railtype_list.size() == 0) {
1216 /* Use traction type to select between normal and electrified
1217 * rail only when no translation list is in place. */
1218 if (_gted[e->index].railtypelabel == RAILTYPE_RAIL_LABEL && engclass >= EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_ELECTRIC_LABEL;
1219 if (_gted[e->index].railtypelabel == RAILTYPE_ELECTRIC_LABEL && engclass < EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_RAIL_LABEL;
1222 rvi->engclass = engclass;
1223 break;
1226 case 0x1A: // Alter purchase list sort order
1227 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1228 break;
1230 case 0x1B: // Powered wagons power bonus
1231 rvi->pow_wag_power = buf->ReadWord();
1232 break;
1234 case 0x1C: // Refit cost
1235 ei->refit_cost = buf->ReadByte();
1236 break;
1238 case 0x1D: { // Refit cargo
1239 uint32 mask = buf->ReadDWord();
1240 _gted[e->index].UpdateRefittability(mask != 0);
1241 ei->refit_mask = TranslateRefitMask(mask);
1242 _gted[e->index].defaultcargo_grf = _cur.grffile;
1243 break;
1246 case 0x1E: // Callback
1247 ei->callback_mask = buf->ReadByte();
1248 break;
1250 case PROP_TRAIN_TRACTIVE_EFFORT: // 0x1F Tractive effort coefficient
1251 rvi->tractive_effort = buf->ReadByte();
1252 break;
1254 case 0x20: // Air drag
1255 rvi->air_drag = buf->ReadByte();
1256 break;
1258 case PROP_TRAIN_SHORTEN_FACTOR: // 0x21 Shorter vehicle
1259 rvi->shorten_factor = buf->ReadByte();
1260 break;
1262 case 0x22: // Visual effect
1263 rvi->visual_effect = buf->ReadByte();
1264 /* Avoid accidentally setting visual_effect to the default value
1265 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1266 if (rvi->visual_effect == VE_DEFAULT) {
1267 assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1268 SB(rvi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
1270 break;
1272 case 0x23: // Powered wagons weight bonus
1273 rvi->pow_wag_weight = buf->ReadByte();
1274 break;
1276 case 0x24: { // High byte of vehicle weight
1277 byte weight = buf->ReadByte();
1279 if (weight > 4) {
1280 grfmsg(2, "RailVehicleChangeInfo: Nonsensical weight of %d tons, ignoring", weight << 8);
1281 } else {
1282 SB(rvi->weight, 8, 8, weight);
1284 break;
1287 case PROP_TRAIN_USER_DATA: // 0x25 User-defined bit mask to set when checking veh. var. 42
1288 rvi->user_def_data = buf->ReadByte();
1289 break;
1291 case 0x26: // Retire vehicle early
1292 ei->retire_early = buf->ReadByte();
1293 break;
1295 case 0x27: // Miscellaneous flags
1296 ei->misc_flags = buf->ReadByte();
1297 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1298 _gted[e->index].prop27_set = true;
1299 break;
1301 case 0x28: // Cargo classes allowed
1302 _gted[e->index].cargo_allowed = buf->ReadWord();
1303 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1304 _gted[e->index].defaultcargo_grf = _cur.grffile;
1305 break;
1307 case 0x29: // Cargo classes disallowed
1308 _gted[e->index].cargo_disallowed = buf->ReadWord();
1309 _gted[e->index].UpdateRefittability(false);
1310 break;
1312 case 0x2A: // Long format introduction date (days since year 0)
1313 ei->base_intro = buf->ReadDWord();
1314 break;
1316 case PROP_TRAIN_CARGO_AGE_PERIOD: // 0x2B Cargo aging period
1317 ei->cargo_age_period = buf->ReadWord();
1318 break;
1320 case 0x2C: // CTT refit include list
1321 case 0x2D: { // CTT refit exclude list
1322 uint8 count = buf->ReadByte();
1323 _gted[e->index].UpdateRefittability(prop == 0x2C && count != 0);
1324 if (prop == 0x2C) _gted[e->index].defaultcargo_grf = _cur.grffile;
1325 CargoTypes &ctt = prop == 0x2C ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1326 ctt = 0;
1327 while (count--) {
1328 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1329 if (ctype == CT_INVALID) continue;
1330 SetBit(ctt, ctype);
1332 break;
1335 case PROP_TRAIN_CURVE_SPEED_MOD: // 0x2E Curve speed modifier
1336 rvi->curve_speed_mod = buf->ReadWord();
1337 break;
1339 default:
1340 ret = CommonVehicleChangeInfo(ei, prop, buf);
1341 break;
1345 return ret;
1349 * Define properties for road vehicles
1350 * @param engine Local ID of the first vehicle.
1351 * @param numinfo Number of subsequent IDs to change the property for.
1352 * @param prop The property to change.
1353 * @param buf The property value.
1354 * @return ChangeInfoResult.
1356 static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1358 ChangeInfoResult ret = CIR_SUCCESS;
1360 for (int i = 0; i < numinfo; i++) {
1361 Engine *e = GetNewEngine(_cur.grffile, VEH_ROAD, engine + i);
1362 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1364 EngineInfo *ei = &e->info;
1365 RoadVehicleInfo *rvi = &e->u.road;
1367 switch (prop) {
1368 case 0x05: // Road/tram type
1369 /* RoadTypeLabel is looked up later after the engine's road/tram
1370 * flag is set, however 0 means the value has not been set. */
1371 _gted[e->index].roadtramtype = buf->ReadByte() + 1;
1372 break;
1374 case 0x08: // Speed (1 unit is 0.5 kmh)
1375 rvi->max_speed = buf->ReadByte();
1376 break;
1378 case PROP_ROADVEH_RUNNING_COST_FACTOR: // 0x09 Running cost factor
1379 rvi->running_cost = buf->ReadByte();
1380 break;
1382 case 0x0A: // Running cost base
1383 ConvertTTDBasePrice(buf->ReadDWord(), "RoadVehicleChangeInfo", &rvi->running_cost_class);
1384 break;
1386 case 0x0E: { // Sprite ID
1387 uint8 spriteid = buf->ReadByte();
1388 uint8 orig_spriteid = spriteid;
1390 /* cars have different custom id in the GRF file */
1391 if (spriteid == 0xFF) spriteid = 0xFD;
1393 if (spriteid < 0xFD) spriteid >>= 1;
1395 if (IsValidNewGRFImageIndex<VEH_ROAD>(spriteid)) {
1396 rvi->image_index = spriteid;
1397 } else {
1398 grfmsg(1, "RoadVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1399 rvi->image_index = 0;
1401 break;
1404 case PROP_ROADVEH_CARGO_CAPACITY: // 0x0F Cargo capacity
1405 rvi->capacity = buf->ReadByte();
1406 break;
1408 case 0x10: { // Cargo type
1409 _gted[e->index].defaultcargo_grf = _cur.grffile;
1410 uint8 ctype = buf->ReadByte();
1412 if (ctype == 0xFF) {
1413 /* 0xFF is specified as 'use first refittable' */
1414 ei->cargo_type = CT_INVALID;
1415 } else if (_cur.grffile->grf_version >= 8) {
1416 /* Use translated cargo. Might result in CT_INVALID (first refittable), if cargo is not defined. */
1417 ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1418 } else if (ctype < NUM_CARGO) {
1419 /* Use untranslated cargo. */
1420 ei->cargo_type = ctype;
1421 } else {
1422 ei->cargo_type = CT_INVALID;
1423 grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
1425 break;
1428 case PROP_ROADVEH_COST_FACTOR: // 0x11 Cost factor
1429 rvi->cost_factor = buf->ReadByte();
1430 break;
1432 case 0x12: // SFX
1433 rvi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1434 break;
1436 case PROP_ROADVEH_POWER: // Power in units of 10 HP.
1437 rvi->power = buf->ReadByte();
1438 break;
1440 case PROP_ROADVEH_WEIGHT: // Weight in units of 1/4 tons.
1441 rvi->weight = buf->ReadByte();
1442 break;
1444 case PROP_ROADVEH_SPEED: // Speed in mph/0.8
1445 _gted[e->index].rv_max_speed = buf->ReadByte();
1446 break;
1448 case 0x16: { // Cargoes available for refitting
1449 uint32 mask = buf->ReadDWord();
1450 _gted[e->index].UpdateRefittability(mask != 0);
1451 ei->refit_mask = TranslateRefitMask(mask);
1452 _gted[e->index].defaultcargo_grf = _cur.grffile;
1453 break;
1456 case 0x17: // Callback mask
1457 ei->callback_mask = buf->ReadByte();
1458 break;
1460 case PROP_ROADVEH_TRACTIVE_EFFORT: // Tractive effort coefficient in 1/256.
1461 rvi->tractive_effort = buf->ReadByte();
1462 break;
1464 case 0x19: // Air drag
1465 rvi->air_drag = buf->ReadByte();
1466 break;
1468 case 0x1A: // Refit cost
1469 ei->refit_cost = buf->ReadByte();
1470 break;
1472 case 0x1B: // Retire vehicle early
1473 ei->retire_early = buf->ReadByte();
1474 break;
1476 case 0x1C: // Miscellaneous flags
1477 ei->misc_flags = buf->ReadByte();
1478 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1479 break;
1481 case 0x1D: // Cargo classes allowed
1482 _gted[e->index].cargo_allowed = buf->ReadWord();
1483 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1484 _gted[e->index].defaultcargo_grf = _cur.grffile;
1485 break;
1487 case 0x1E: // Cargo classes disallowed
1488 _gted[e->index].cargo_disallowed = buf->ReadWord();
1489 _gted[e->index].UpdateRefittability(false);
1490 break;
1492 case 0x1F: // Long format introduction date (days since year 0)
1493 ei->base_intro = buf->ReadDWord();
1494 break;
1496 case 0x20: // Alter purchase list sort order
1497 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1498 break;
1500 case 0x21: // Visual effect
1501 rvi->visual_effect = buf->ReadByte();
1502 /* Avoid accidentally setting visual_effect to the default value
1503 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1504 if (rvi->visual_effect == VE_DEFAULT) {
1505 assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1506 SB(rvi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
1508 break;
1510 case PROP_ROADVEH_CARGO_AGE_PERIOD: // 0x22 Cargo aging period
1511 ei->cargo_age_period = buf->ReadWord();
1512 break;
1514 case PROP_ROADVEH_SHORTEN_FACTOR: // 0x23 Shorter vehicle
1515 rvi->shorten_factor = buf->ReadByte();
1516 break;
1518 case 0x24: // CTT refit include list
1519 case 0x25: { // CTT refit exclude list
1520 uint8 count = buf->ReadByte();
1521 _gted[e->index].UpdateRefittability(prop == 0x24 && count != 0);
1522 if (prop == 0x24) _gted[e->index].defaultcargo_grf = _cur.grffile;
1523 CargoTypes &ctt = prop == 0x24 ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1524 ctt = 0;
1525 while (count--) {
1526 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1527 if (ctype == CT_INVALID) continue;
1528 SetBit(ctt, ctype);
1530 break;
1533 default:
1534 ret = CommonVehicleChangeInfo(ei, prop, buf);
1535 break;
1539 return ret;
1543 * Define properties for ships
1544 * @param engine Local ID of the first vehicle.
1545 * @param numinfo Number of subsequent IDs to change the property for.
1546 * @param prop The property to change.
1547 * @param buf The property value.
1548 * @return ChangeInfoResult.
1550 static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1552 ChangeInfoResult ret = CIR_SUCCESS;
1554 for (int i = 0; i < numinfo; i++) {
1555 Engine *e = GetNewEngine(_cur.grffile, VEH_SHIP, engine + i);
1556 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1558 EngineInfo *ei = &e->info;
1559 ShipVehicleInfo *svi = &e->u.ship;
1561 switch (prop) {
1562 case 0x08: { // Sprite ID
1563 uint8 spriteid = buf->ReadByte();
1564 uint8 orig_spriteid = spriteid;
1566 /* ships have different custom id in the GRF file */
1567 if (spriteid == 0xFF) spriteid = 0xFD;
1569 if (spriteid < 0xFD) spriteid >>= 1;
1571 if (IsValidNewGRFImageIndex<VEH_SHIP>(spriteid)) {
1572 svi->image_index = spriteid;
1573 } else {
1574 grfmsg(1, "ShipVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1575 svi->image_index = 0;
1577 break;
1580 case 0x09: // Refittable
1581 svi->old_refittable = (buf->ReadByte() != 0);
1582 break;
1584 case PROP_SHIP_COST_FACTOR: // 0x0A Cost factor
1585 svi->cost_factor = buf->ReadByte();
1586 break;
1588 case PROP_SHIP_SPEED: // 0x0B Speed (1 unit is 0.5 km-ish/h)
1589 svi->max_speed = buf->ReadByte();
1590 break;
1592 case 0x0C: { // Cargo type
1593 _gted[e->index].defaultcargo_grf = _cur.grffile;
1594 uint8 ctype = buf->ReadByte();
1596 if (ctype == 0xFF) {
1597 /* 0xFF is specified as 'use first refittable' */
1598 ei->cargo_type = CT_INVALID;
1599 } else if (_cur.grffile->grf_version >= 8) {
1600 /* Use translated cargo. Might result in CT_INVALID (first refittable), if cargo is not defined. */
1601 ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1602 } else if (ctype < NUM_CARGO) {
1603 /* Use untranslated cargo. */
1604 ei->cargo_type = ctype;
1605 } else {
1606 ei->cargo_type = CT_INVALID;
1607 grfmsg(2, "RailVehicleChangeInfo: Invalid cargo type %d, using first refittable", ctype);
1609 break;
1612 case PROP_SHIP_CARGO_CAPACITY: // 0x0D Cargo capacity
1613 svi->capacity = buf->ReadWord();
1614 break;
1616 case PROP_SHIP_RUNNING_COST_FACTOR: // 0x0F Running cost factor
1617 svi->running_cost = buf->ReadByte();
1618 break;
1620 case 0x10: // SFX
1621 svi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1622 break;
1624 case 0x11: { // Cargoes available for refitting
1625 uint32 mask = buf->ReadDWord();
1626 _gted[e->index].UpdateRefittability(mask != 0);
1627 ei->refit_mask = TranslateRefitMask(mask);
1628 _gted[e->index].defaultcargo_grf = _cur.grffile;
1629 break;
1632 case 0x12: // Callback mask
1633 ei->callback_mask = buf->ReadByte();
1634 break;
1636 case 0x13: // Refit cost
1637 ei->refit_cost = buf->ReadByte();
1638 break;
1640 case 0x14: // Ocean speed fraction
1641 svi->ocean_speed_frac = buf->ReadByte();
1642 break;
1644 case 0x15: // Canal speed fraction
1645 svi->canal_speed_frac = buf->ReadByte();
1646 break;
1648 case 0x16: // Retire vehicle early
1649 ei->retire_early = buf->ReadByte();
1650 break;
1652 case 0x17: // Miscellaneous flags
1653 ei->misc_flags = buf->ReadByte();
1654 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1655 break;
1657 case 0x18: // Cargo classes allowed
1658 _gted[e->index].cargo_allowed = buf->ReadWord();
1659 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1660 _gted[e->index].defaultcargo_grf = _cur.grffile;
1661 break;
1663 case 0x19: // Cargo classes disallowed
1664 _gted[e->index].cargo_disallowed = buf->ReadWord();
1665 _gted[e->index].UpdateRefittability(false);
1666 break;
1668 case 0x1A: // Long format introduction date (days since year 0)
1669 ei->base_intro = buf->ReadDWord();
1670 break;
1672 case 0x1B: // Alter purchase list sort order
1673 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1674 break;
1676 case 0x1C: // Visual effect
1677 svi->visual_effect = buf->ReadByte();
1678 /* Avoid accidentally setting visual_effect to the default value
1679 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1680 if (svi->visual_effect == VE_DEFAULT) {
1681 assert(HasBit(svi->visual_effect, VE_DISABLE_EFFECT));
1682 SB(svi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0);
1684 break;
1686 case PROP_SHIP_CARGO_AGE_PERIOD: // 0x1D Cargo aging period
1687 ei->cargo_age_period = buf->ReadWord();
1688 break;
1690 case 0x1E: // CTT refit include list
1691 case 0x1F: { // CTT refit exclude list
1692 uint8 count = buf->ReadByte();
1693 _gted[e->index].UpdateRefittability(prop == 0x1E && count != 0);
1694 if (prop == 0x1E) _gted[e->index].defaultcargo_grf = _cur.grffile;
1695 CargoTypes &ctt = prop == 0x1E ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1696 ctt = 0;
1697 while (count--) {
1698 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1699 if (ctype == CT_INVALID) continue;
1700 SetBit(ctt, ctype);
1702 break;
1705 default:
1706 ret = CommonVehicleChangeInfo(ei, prop, buf);
1707 break;
1711 return ret;
1715 * Define properties for aircraft
1716 * @param engine Local ID of the aircraft.
1717 * @param numinfo Number of subsequent IDs to change the property for.
1718 * @param prop The property to change.
1719 * @param buf The property value.
1720 * @return ChangeInfoResult.
1722 static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader *buf)
1724 ChangeInfoResult ret = CIR_SUCCESS;
1726 for (int i = 0; i < numinfo; i++) {
1727 Engine *e = GetNewEngine(_cur.grffile, VEH_AIRCRAFT, engine + i);
1728 if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1730 EngineInfo *ei = &e->info;
1731 AircraftVehicleInfo *avi = &e->u.air;
1733 switch (prop) {
1734 case 0x08: { // Sprite ID
1735 uint8 spriteid = buf->ReadByte();
1736 uint8 orig_spriteid = spriteid;
1738 /* aircraft have different custom id in the GRF file */
1739 if (spriteid == 0xFF) spriteid = 0xFD;
1741 if (spriteid < 0xFD) spriteid >>= 1;
1743 if (IsValidNewGRFImageIndex<VEH_AIRCRAFT>(spriteid)) {
1744 avi->image_index = spriteid;
1745 } else {
1746 grfmsg(1, "AircraftVehicleChangeInfo: Invalid Sprite %d specified, ignoring", orig_spriteid);
1747 avi->image_index = 0;
1749 break;
1752 case 0x09: // Helicopter
1753 if (buf->ReadByte() == 0) {
1754 avi->subtype = AIR_HELI;
1755 } else {
1756 SB(avi->subtype, 0, 1, 1); // AIR_CTOL
1758 break;
1760 case 0x0A: // Large
1761 SB(avi->subtype, 1, 1, (buf->ReadByte() != 0 ? 1 : 0)); // AIR_FAST
1762 break;
1764 case PROP_AIRCRAFT_COST_FACTOR: // 0x0B Cost factor
1765 avi->cost_factor = buf->ReadByte();
1766 break;
1768 case PROP_AIRCRAFT_SPEED: // 0x0C Speed (1 unit is 8 mph, we translate to 1 unit is 1 km-ish/h)
1769 avi->max_speed = (buf->ReadByte() * 128) / 10;
1770 break;
1772 case 0x0D: // Acceleration
1773 avi->acceleration = buf->ReadByte();
1774 break;
1776 case PROP_AIRCRAFT_RUNNING_COST_FACTOR: // 0x0E Running cost factor
1777 avi->running_cost = buf->ReadByte();
1778 break;
1780 case PROP_AIRCRAFT_PASSENGER_CAPACITY: // 0x0F Passenger capacity
1781 avi->passenger_capacity = buf->ReadWord();
1782 break;
1784 case PROP_AIRCRAFT_MAIL_CAPACITY: // 0x11 Mail capacity
1785 avi->mail_capacity = buf->ReadByte();
1786 break;
1788 case 0x12: // SFX
1789 avi->sfx = GetNewGRFSoundID(_cur.grffile, buf->ReadByte());
1790 break;
1792 case 0x13: { // Cargoes available for refitting
1793 uint32 mask = buf->ReadDWord();
1794 _gted[e->index].UpdateRefittability(mask != 0);
1795 ei->refit_mask = TranslateRefitMask(mask);
1796 _gted[e->index].defaultcargo_grf = _cur.grffile;
1797 break;
1800 case 0x14: // Callback mask
1801 ei->callback_mask = buf->ReadByte();
1802 break;
1804 case 0x15: // Refit cost
1805 ei->refit_cost = buf->ReadByte();
1806 break;
1808 case 0x16: // Retire vehicle early
1809 ei->retire_early = buf->ReadByte();
1810 break;
1812 case 0x17: // Miscellaneous flags
1813 ei->misc_flags = buf->ReadByte();
1814 _loaded_newgrf_features.has_2CC |= HasBit(ei->misc_flags, EF_USES_2CC);
1815 break;
1817 case 0x18: // Cargo classes allowed
1818 _gted[e->index].cargo_allowed = buf->ReadWord();
1819 _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1820 _gted[e->index].defaultcargo_grf = _cur.grffile;
1821 break;
1823 case 0x19: // Cargo classes disallowed
1824 _gted[e->index].cargo_disallowed = buf->ReadWord();
1825 _gted[e->index].UpdateRefittability(false);
1826 break;
1828 case 0x1A: // Long format introduction date (days since year 0)
1829 ei->base_intro = buf->ReadDWord();
1830 break;
1832 case 0x1B: // Alter purchase list sort order
1833 AlterVehicleListOrder(e->index, buf->ReadExtendedByte());
1834 break;
1836 case PROP_AIRCRAFT_CARGO_AGE_PERIOD: // 0x1C Cargo aging period
1837 ei->cargo_age_period = buf->ReadWord();
1838 break;
1840 case 0x1D: // CTT refit include list
1841 case 0x1E: { // CTT refit exclude list
1842 uint8 count = buf->ReadByte();
1843 _gted[e->index].UpdateRefittability(prop == 0x1D && count != 0);
1844 if (prop == 0x1D) _gted[e->index].defaultcargo_grf = _cur.grffile;
1845 CargoTypes &ctt = prop == 0x1D ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1846 ctt = 0;
1847 while (count--) {
1848 CargoID ctype = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
1849 if (ctype == CT_INVALID) continue;
1850 SetBit(ctt, ctype);
1852 break;
1855 case PROP_AIRCRAFT_RANGE: // 0x1F Max aircraft range
1856 avi->max_range = buf->ReadWord();
1857 break;
1859 default:
1860 ret = CommonVehicleChangeInfo(ei, prop, buf);
1861 break;
1865 return ret;
1869 * Define properties for stations
1870 * @param stid StationID of the first station tile.
1871 * @param numinfo Number of subsequent station tiles to change the property for.
1872 * @param prop The property to change.
1873 * @param buf The property value.
1874 * @return ChangeInfoResult.
1876 static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader *buf)
1878 ChangeInfoResult ret = CIR_SUCCESS;
1880 if (stid + numinfo > NUM_STATIONS_PER_GRF) {
1881 grfmsg(1, "StationChangeInfo: Station %u is invalid, max %u, ignoring", stid + numinfo, NUM_STATIONS_PER_GRF);
1882 return CIR_INVALID_ID;
1885 /* Allocate station specs if necessary */
1886 if (_cur.grffile->stations == nullptr) _cur.grffile->stations = CallocT<StationSpec*>(NUM_STATIONS_PER_GRF);
1888 for (int i = 0; i < numinfo; i++) {
1889 StationSpec *statspec = _cur.grffile->stations[stid + i];
1891 /* Check that the station we are modifying is defined. */
1892 if (statspec == nullptr && prop != 0x08) {
1893 grfmsg(2, "StationChangeInfo: Attempt to modify undefined station %u, ignoring", stid + i);
1894 return CIR_INVALID_ID;
1897 switch (prop) {
1898 case 0x08: { // Class ID
1899 StationSpec **spec = &_cur.grffile->stations[stid + i];
1901 /* Property 0x08 is special; it is where the station is allocated */
1902 if (*spec == nullptr) *spec = new StationSpec();
1904 /* Swap classid because we read it in BE meaning WAYP or DFLT */
1905 uint32 classid = buf->ReadDWord();
1906 (*spec)->cls_id = StationClass::Allocate(BSWAP32(classid));
1907 break;
1910 case 0x09: { // Define sprite layout
1911 uint16 tiles = buf->ReadExtendedByte();
1912 statspec->renderdata.clear(); // delete earlier loaded stuff
1913 statspec->renderdata.reserve(tiles);
1915 for (uint t = 0; t < tiles; t++) {
1916 NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
1917 dts->consistent_max_offset = UINT16_MAX; // Spritesets are unknown, so no limit.
1919 if (buf->HasData(4) && *(uint32*)buf->Data() == 0) {
1920 buf->Skip(4);
1921 extern const DrawTileSprites _station_display_datas_rail[8];
1922 dts->Clone(&_station_display_datas_rail[t % 8]);
1923 continue;
1926 ReadSpriteLayoutSprite(buf, false, false, false, GSF_STATIONS, &dts->ground);
1927 /* On error, bail out immediately. Temporary GRF data was already freed */
1928 if (_cur.skip_sprites < 0) return CIR_DISABLED;
1930 static std::vector<DrawTileSeqStruct> tmp_layout;
1931 tmp_layout.clear();
1932 for (;;) {
1933 /* no relative bounding box support */
1934 DrawTileSeqStruct &dtss = tmp_layout.emplace_back();
1935 MemSetT(&dtss, 0);
1937 dtss.delta_x = buf->ReadByte();
1938 if (dtss.IsTerminator()) break;
1939 dtss.delta_y = buf->ReadByte();
1940 dtss.delta_z = buf->ReadByte();
1941 dtss.size_x = buf->ReadByte();
1942 dtss.size_y = buf->ReadByte();
1943 dtss.size_z = buf->ReadByte();
1945 ReadSpriteLayoutSprite(buf, false, true, false, GSF_STATIONS, &dtss.image);
1946 /* On error, bail out immediately. Temporary GRF data was already freed */
1947 if (_cur.skip_sprites < 0) return CIR_DISABLED;
1949 dts->Clone(tmp_layout.data());
1952 /* Number of layouts must be even, alternating X and Y */
1953 if (statspec->renderdata.size() & 1) {
1954 grfmsg(1, "StationChangeInfo: Station %u defines an odd number of sprite layouts, dropping the last item", stid + i);
1955 statspec->renderdata.pop_back();
1957 break;
1960 case 0x0A: { // Copy sprite layout
1961 byte srcid = buf->ReadByte();
1962 const StationSpec *srcstatspec = _cur.grffile->stations[srcid];
1964 if (srcstatspec == nullptr) {
1965 grfmsg(1, "StationChangeInfo: Station %u is not defined, cannot copy sprite layout to %u.", srcid, stid + i);
1966 continue;
1969 statspec->renderdata.clear(); // delete earlier loaded stuff
1970 statspec->renderdata.reserve(srcstatspec->renderdata.size());
1972 for (const auto &it : srcstatspec->renderdata) {
1973 NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
1974 dts->Clone(&it);
1976 break;
1979 case 0x0B: // Callback mask
1980 statspec->callback_mask = buf->ReadByte();
1981 break;
1983 case 0x0C: // Disallowed number of platforms
1984 statspec->disallowed_platforms = buf->ReadByte();
1985 break;
1987 case 0x0D: // Disallowed platform lengths
1988 statspec->disallowed_lengths = buf->ReadByte();
1989 break;
1991 case 0x0E: // Define custom layout
1992 while (buf->HasData()) {
1993 byte length = buf->ReadByte();
1994 byte number = buf->ReadByte();
1996 if (length == 0 || number == 0) break;
1998 if (statspec->layouts.size() < length) statspec->layouts.resize(length);
1999 if (statspec->layouts[length - 1].size() < number) statspec->layouts[length - 1].resize(number);
2001 const byte *layout = buf->ReadBytes(length * number);
2002 statspec->layouts[length - 1][number - 1].assign(layout, layout + length * number);
2004 /* Validate tile values are only the permitted 00, 02, 04 and 06. */
2005 for (auto &tile : statspec->layouts[length - 1][number - 1]) {
2006 if ((tile & 6) != tile) {
2007 grfmsg(1, "StationChangeInfo: Invalid tile %u in layout %ux%u", tile, length, number);
2008 tile &= 6;
2012 break;
2014 case 0x0F: { // Copy custom layout
2015 byte srcid = buf->ReadByte();
2016 const StationSpec *srcstatspec = _cur.grffile->stations[srcid];
2018 if (srcstatspec == nullptr) {
2019 grfmsg(1, "StationChangeInfo: Station %u is not defined, cannot copy tile layout to %u.", srcid, stid + i);
2020 continue;
2023 statspec->layouts = srcstatspec->layouts;
2024 break;
2027 case 0x10: // Little/lots cargo threshold
2028 statspec->cargo_threshold = buf->ReadWord();
2029 break;
2031 case 0x11: // Pylon placement
2032 statspec->pylons = buf->ReadByte();
2033 break;
2035 case 0x12: // Cargo types for random triggers
2036 if (_cur.grffile->grf_version >= 7) {
2037 statspec->cargo_triggers = TranslateRefitMask(buf->ReadDWord());
2038 } else {
2039 statspec->cargo_triggers = (CargoTypes)buf->ReadDWord();
2041 break;
2043 case 0x13: // General flags
2044 statspec->flags = buf->ReadByte();
2045 break;
2047 case 0x14: // Overhead wire placement
2048 statspec->wires = buf->ReadByte();
2049 break;
2051 case 0x15: // Blocked tiles
2052 statspec->blocked = buf->ReadByte();
2053 break;
2055 case 0x16: // Animation info
2056 statspec->animation.frames = buf->ReadByte();
2057 statspec->animation.status = buf->ReadByte();
2058 break;
2060 case 0x17: // Animation speed
2061 statspec->animation.speed = buf->ReadByte();
2062 break;
2064 case 0x18: // Animation triggers
2065 statspec->animation.triggers = buf->ReadWord();
2066 break;
2068 case 0x1A: { // Advanced sprite layout
2069 uint16 tiles = buf->ReadExtendedByte();
2070 statspec->renderdata.clear(); // delete earlier loaded stuff
2071 statspec->renderdata.reserve(tiles);
2073 for (uint t = 0; t < tiles; t++) {
2074 NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
2075 uint num_building_sprites = buf->ReadByte();
2076 /* On error, bail out immediately. Temporary GRF data was already freed */
2077 if (ReadSpriteLayout(buf, num_building_sprites, false, GSF_STATIONS, true, false, dts)) return CIR_DISABLED;
2080 /* Number of layouts must be even, alternating X and Y */
2081 if (statspec->renderdata.size() & 1) {
2082 grfmsg(1, "StationChangeInfo: Station %u defines an odd number of sprite layouts, dropping the last item", stid + i);
2083 statspec->renderdata.pop_back();
2085 break;
2088 default:
2089 ret = CIR_UNKNOWN;
2090 break;
2094 return ret;
2098 * Define properties for water features
2099 * @param id Type of the first water feature.
2100 * @param numinfo Number of subsequent water feature ids to change the property for.
2101 * @param prop The property to change.
2102 * @param buf The property value.
2103 * @return ChangeInfoResult.
2105 static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
2107 ChangeInfoResult ret = CIR_SUCCESS;
2109 if (id + numinfo > CF_END) {
2110 grfmsg(1, "CanalChangeInfo: Canal feature 0x%02X is invalid, max %u, ignoring", id + numinfo, CF_END);
2111 return CIR_INVALID_ID;
2114 for (int i = 0; i < numinfo; i++) {
2115 CanalProperties *cp = &_cur.grffile->canal_local_properties[id + i];
2117 switch (prop) {
2118 case 0x08:
2119 cp->callback_mask = buf->ReadByte();
2120 break;
2122 case 0x09:
2123 cp->flags = buf->ReadByte();
2124 break;
2126 default:
2127 ret = CIR_UNKNOWN;
2128 break;
2132 return ret;
2136 * Define properties for bridges
2137 * @param brid BridgeID of the bridge.
2138 * @param numinfo Number of subsequent bridgeIDs to change the property for.
2139 * @param prop The property to change.
2140 * @param buf The property value.
2141 * @return ChangeInfoResult.
2143 static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteReader *buf)
2145 ChangeInfoResult ret = CIR_SUCCESS;
2147 if (brid + numinfo > MAX_BRIDGES) {
2148 grfmsg(1, "BridgeChangeInfo: Bridge %u is invalid, max %u, ignoring", brid + numinfo, MAX_BRIDGES);
2149 return CIR_INVALID_ID;
2152 for (int i = 0; i < numinfo; i++) {
2153 BridgeSpec *bridge = &_bridge[brid + i];
2155 switch (prop) {
2156 case 0x08: { // Year of availability
2157 /* We treat '0' as always available */
2158 byte year = buf->ReadByte();
2159 bridge->avail_year = (year > 0 ? ORIGINAL_BASE_YEAR + year : 0);
2160 break;
2163 case 0x09: // Minimum length
2164 bridge->min_length = buf->ReadByte();
2165 break;
2167 case 0x0A: // Maximum length
2168 bridge->max_length = buf->ReadByte();
2169 if (bridge->max_length > 16) bridge->max_length = 0xFFFF;
2170 break;
2172 case 0x0B: // Cost factor
2173 bridge->price = buf->ReadByte();
2174 break;
2176 case 0x0C: // Maximum speed
2177 bridge->speed = buf->ReadWord();
2178 break;
2180 case 0x0D: { // Bridge sprite tables
2181 byte tableid = buf->ReadByte();
2182 byte numtables = buf->ReadByte();
2184 if (bridge->sprite_table == nullptr) {
2185 /* Allocate memory for sprite table pointers and zero out */
2186 bridge->sprite_table = CallocT<PalSpriteID*>(7);
2189 for (; numtables-- != 0; tableid++) {
2190 if (tableid >= 7) { // skip invalid data
2191 grfmsg(1, "BridgeChangeInfo: Table %d >= 7, skipping", tableid);
2192 for (byte sprite = 0; sprite < 32; sprite++) buf->ReadDWord();
2193 continue;
2196 if (bridge->sprite_table[tableid] == nullptr) {
2197 bridge->sprite_table[tableid] = MallocT<PalSpriteID>(32);
2200 for (byte sprite = 0; sprite < 32; sprite++) {
2201 SpriteID image = buf->ReadWord();
2202 PaletteID pal = buf->ReadWord();
2204 bridge->sprite_table[tableid][sprite].sprite = image;
2205 bridge->sprite_table[tableid][sprite].pal = pal;
2207 MapSpriteMappingRecolour(&bridge->sprite_table[tableid][sprite]);
2210 break;
2213 case 0x0E: // Flags; bit 0 - disable far pillars
2214 bridge->flags = buf->ReadByte();
2215 break;
2217 case 0x0F: // Long format year of availability (year since year 0)
2218 bridge->avail_year = Clamp(buf->ReadDWord(), MIN_YEAR, MAX_YEAR);
2219 break;
2221 case 0x10: { // purchase string
2222 StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2223 if (newone != STR_UNDEFINED) bridge->material = newone;
2224 break;
2227 case 0x11: // description of bridge with rails or roads
2228 case 0x12: {
2229 StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2230 if (newone != STR_UNDEFINED) bridge->transport_name[prop - 0x11] = newone;
2231 break;
2234 case 0x13: // 16 bits cost multiplier
2235 bridge->price = buf->ReadWord();
2236 break;
2238 default:
2239 ret = CIR_UNKNOWN;
2240 break;
2244 return ret;
2248 * Ignore a house property
2249 * @param prop Property to read.
2250 * @param buf Property value.
2251 * @return ChangeInfoResult.
2253 static ChangeInfoResult IgnoreTownHouseProperty(int prop, ByteReader *buf)
2255 ChangeInfoResult ret = CIR_SUCCESS;
2257 switch (prop) {
2258 case 0x09:
2259 case 0x0B:
2260 case 0x0C:
2261 case 0x0D:
2262 case 0x0E:
2263 case 0x0F:
2264 case 0x11:
2265 case 0x14:
2266 case 0x15:
2267 case 0x16:
2268 case 0x18:
2269 case 0x19:
2270 case 0x1A:
2271 case 0x1B:
2272 case 0x1C:
2273 case 0x1D:
2274 case 0x1F:
2275 buf->ReadByte();
2276 break;
2278 case 0x0A:
2279 case 0x10:
2280 case 0x12:
2281 case 0x13:
2282 case 0x21:
2283 case 0x22:
2284 buf->ReadWord();
2285 break;
2287 case 0x1E:
2288 buf->ReadDWord();
2289 break;
2291 case 0x17:
2292 for (uint j = 0; j < 4; j++) buf->ReadByte();
2293 break;
2295 case 0x20: {
2296 byte count = buf->ReadByte();
2297 for (byte j = 0; j < count; j++) buf->ReadByte();
2298 break;
2301 case 0x23:
2302 buf->Skip(buf->ReadByte() * 2);
2303 break;
2305 default:
2306 ret = CIR_UNKNOWN;
2307 break;
2309 return ret;
2313 * Define properties for houses
2314 * @param hid HouseID of the house.
2315 * @param numinfo Number of subsequent houseIDs to change the property for.
2316 * @param prop The property to change.
2317 * @param buf The property value.
2318 * @return ChangeInfoResult.
2320 static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, ByteReader *buf)
2322 ChangeInfoResult ret = CIR_SUCCESS;
2324 if (hid + numinfo > NUM_HOUSES_PER_GRF) {
2325 grfmsg(1, "TownHouseChangeInfo: Too many houses loaded (%u), max (%u). Ignoring.", hid + numinfo, NUM_HOUSES_PER_GRF);
2326 return CIR_INVALID_ID;
2329 /* Allocate house specs if they haven't been allocated already. */
2330 if (_cur.grffile->housespec == nullptr) {
2331 _cur.grffile->housespec = CallocT<HouseSpec*>(NUM_HOUSES_PER_GRF);
2334 for (int i = 0; i < numinfo; i++) {
2335 HouseSpec *housespec = _cur.grffile->housespec[hid + i];
2337 if (prop != 0x08 && housespec == nullptr) {
2338 /* If the house property 08 is not yet set, ignore this property */
2339 ChangeInfoResult cir = IgnoreTownHouseProperty(prop, buf);
2340 if (cir > ret) ret = cir;
2341 continue;
2344 switch (prop) {
2345 case 0x08: { // Substitute building type, and definition of a new house
2346 HouseSpec **house = &_cur.grffile->housespec[hid + i];
2347 byte subs_id = buf->ReadByte();
2349 if (subs_id == 0xFF) {
2350 /* Instead of defining a new house, a substitute house id
2351 * of 0xFF disables the old house with the current id. */
2352 HouseSpec::Get(hid + i)->enabled = false;
2353 continue;
2354 } else if (subs_id >= NEW_HOUSE_OFFSET) {
2355 /* The substitute id must be one of the original houses. */
2356 grfmsg(2, "TownHouseChangeInfo: Attempt to use new house %u as substitute house for %u. Ignoring.", subs_id, hid + i);
2357 continue;
2360 /* Allocate space for this house. */
2361 if (*house == nullptr) *house = CallocT<HouseSpec>(1);
2363 housespec = *house;
2365 MemCpyT(housespec, HouseSpec::Get(subs_id));
2367 housespec->enabled = true;
2368 housespec->grf_prop.local_id = hid + i;
2369 housespec->grf_prop.subst_id = subs_id;
2370 housespec->grf_prop.grffile = _cur.grffile;
2371 housespec->random_colour[0] = 0x04; // those 4 random colours are the base colour
2372 housespec->random_colour[1] = 0x08; // for all new houses
2373 housespec->random_colour[2] = 0x0C; // they stand for red, blue, orange and green
2374 housespec->random_colour[3] = 0x06;
2376 /* Make sure that the third cargo type is valid in this
2377 * climate. This can cause problems when copying the properties
2378 * of a house that accepts food, where the new house is valid
2379 * in the temperate climate. */
2380 if (!CargoSpec::Get(housespec->accepts_cargo[2])->IsValid()) {
2381 housespec->cargo_acceptance[2] = 0;
2383 break;
2386 case 0x09: // Building flags
2387 housespec->building_flags = (BuildingFlags)buf->ReadByte();
2388 break;
2390 case 0x0A: { // Availability years
2391 uint16 years = buf->ReadWord();
2392 housespec->min_year = GB(years, 0, 8) > 150 ? MAX_YEAR : ORIGINAL_BASE_YEAR + GB(years, 0, 8);
2393 housespec->max_year = GB(years, 8, 8) > 150 ? MAX_YEAR : ORIGINAL_BASE_YEAR + GB(years, 8, 8);
2394 break;
2397 case 0x0B: // Population
2398 housespec->population = buf->ReadByte();
2399 break;
2401 case 0x0C: // Mail generation multiplier
2402 housespec->mail_generation = buf->ReadByte();
2403 break;
2405 case 0x0D: // Passenger acceptance
2406 case 0x0E: // Mail acceptance
2407 housespec->cargo_acceptance[prop - 0x0D] = buf->ReadByte();
2408 break;
2410 case 0x0F: { // Goods/candy, food/fizzy drinks acceptance
2411 int8 goods = buf->ReadByte();
2413 /* If value of goods is negative, it means in fact food or, if in toyland, fizzy_drink acceptance.
2414 * Else, we have "standard" 3rd cargo type, goods or candy, for toyland once more */
2415 CargoID cid = (goods >= 0) ? ((_settings_game.game_creation.landscape == LT_TOYLAND) ? CT_CANDY : CT_GOODS) :
2416 ((_settings_game.game_creation.landscape == LT_TOYLAND) ? CT_FIZZY_DRINKS : CT_FOOD);
2418 /* Make sure the cargo type is valid in this climate. */
2419 if (!CargoSpec::Get(cid)->IsValid()) goods = 0;
2421 housespec->accepts_cargo[2] = cid;
2422 housespec->cargo_acceptance[2] = abs(goods); // but we do need positive value here
2423 break;
2426 case 0x10: // Local authority rating decrease on removal
2427 housespec->remove_rating_decrease = buf->ReadWord();
2428 break;
2430 case 0x11: // Removal cost multiplier
2431 housespec->removal_cost = buf->ReadByte();
2432 break;
2434 case 0x12: // Building name ID
2435 AddStringForMapping(buf->ReadWord(), &housespec->building_name);
2436 break;
2438 case 0x13: // Building availability mask
2439 housespec->building_availability = (HouseZones)buf->ReadWord();
2440 break;
2442 case 0x14: // House callback mask
2443 housespec->callback_mask |= buf->ReadByte();
2444 break;
2446 case 0x15: { // House override byte
2447 byte override = buf->ReadByte();
2449 /* The house being overridden must be an original house. */
2450 if (override >= NEW_HOUSE_OFFSET) {
2451 grfmsg(2, "TownHouseChangeInfo: Attempt to override new house %u with house id %u. Ignoring.", override, hid + i);
2452 continue;
2455 _house_mngr.Add(hid + i, _cur.grffile->grfid, override);
2456 break;
2459 case 0x16: // Periodic refresh multiplier
2460 housespec->processing_time = std::min<byte>(buf->ReadByte(), 63u);
2461 break;
2463 case 0x17: // Four random colours to use
2464 for (uint j = 0; j < 4; j++) housespec->random_colour[j] = buf->ReadByte();
2465 break;
2467 case 0x18: // Relative probability of appearing
2468 housespec->probability = buf->ReadByte();
2469 break;
2471 case 0x19: // Extra flags
2472 housespec->extra_flags = (HouseExtraFlags)buf->ReadByte();
2473 break;
2475 case 0x1A: // Animation frames
2476 housespec->animation.frames = buf->ReadByte();
2477 housespec->animation.status = GB(housespec->animation.frames, 7, 1);
2478 SB(housespec->animation.frames, 7, 1, 0);
2479 break;
2481 case 0x1B: // Animation speed
2482 housespec->animation.speed = Clamp(buf->ReadByte(), 2, 16);
2483 break;
2485 case 0x1C: // Class of the building type
2486 housespec->class_id = AllocateHouseClassID(buf->ReadByte(), _cur.grffile->grfid);
2487 break;
2489 case 0x1D: // Callback mask part 2
2490 housespec->callback_mask |= (buf->ReadByte() << 8);
2491 break;
2493 case 0x1E: { // Accepted cargo types
2494 uint32 cargotypes = buf->ReadDWord();
2496 /* Check if the cargo types should not be changed */
2497 if (cargotypes == 0xFFFFFFFF) break;
2499 for (uint j = 0; j < 3; j++) {
2500 /* Get the cargo number from the 'list' */
2501 uint8 cargo_part = GB(cargotypes, 8 * j, 8);
2502 CargoID cargo = GetCargoTranslation(cargo_part, _cur.grffile);
2504 if (cargo == CT_INVALID) {
2505 /* Disable acceptance of invalid cargo type */
2506 housespec->cargo_acceptance[j] = 0;
2507 } else {
2508 housespec->accepts_cargo[j] = cargo;
2511 break;
2514 case 0x1F: // Minimum life span
2515 housespec->minimum_life = buf->ReadByte();
2516 break;
2518 case 0x20: { // Cargo acceptance watch list
2519 byte count = buf->ReadByte();
2520 for (byte j = 0; j < count; j++) {
2521 CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
2522 if (cargo != CT_INVALID) SetBit(housespec->watched_cargoes, cargo);
2524 break;
2527 case 0x21: // long introduction year
2528 housespec->min_year = buf->ReadWord();
2529 break;
2531 case 0x22: // long maximum year
2532 housespec->max_year = buf->ReadWord();
2533 break;
2535 case 0x23: { // variable length cargo types accepted
2536 uint count = buf->ReadByte();
2537 if (count > lengthof(housespec->accepts_cargo)) {
2538 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
2539 error->param_value[1] = prop;
2540 return CIR_DISABLED;
2542 /* Always write the full accepts_cargo array, and check each index for being inside the
2543 * provided data. This ensures all values are properly initialized, and also avoids
2544 * any risks of array overrun. */
2545 for (uint i = 0; i < lengthof(housespec->accepts_cargo); i++) {
2546 if (i < count) {
2547 housespec->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
2548 housespec->cargo_acceptance[i] = buf->ReadByte();
2549 } else {
2550 housespec->accepts_cargo[i] = CT_INVALID;
2551 housespec->cargo_acceptance[i] = 0;
2554 break;
2557 default:
2558 ret = CIR_UNKNOWN;
2559 break;
2563 return ret;
2567 * Get the language map associated with a given NewGRF and language.
2568 * @param grfid The NewGRF to get the map for.
2569 * @param language_id The (NewGRF) language ID to get the map for.
2570 * @return The LanguageMap, or nullptr if it couldn't be found.
2572 /* static */ const LanguageMap *LanguageMap::GetLanguageMap(uint32 grfid, uint8 language_id)
2574 /* LanguageID "MAX_LANG", i.e. 7F is any. This language can't have a gender/case mapping, but has to be handled gracefully. */
2575 const GRFFile *grffile = GetFileByGRFID(grfid);
2576 return (grffile != nullptr && grffile->language_map != nullptr && language_id < MAX_LANG) ? &grffile->language_map[language_id] : nullptr;
2580 * Load a cargo- or railtype-translation table.
2581 * @param gvid ID of the global variable. This is basically only checked for zerones.
2582 * @param numinfo Number of subsequent IDs to change the property for.
2583 * @param buf The property value.
2584 * @param[in,out] translation_table Storage location for the translation table.
2585 * @param name Name of the table for debug output.
2586 * @return ChangeInfoResult.
2588 template <typename T>
2589 static ChangeInfoResult LoadTranslationTable(uint gvid, int numinfo, ByteReader *buf, T &translation_table, const char *name)
2591 if (gvid != 0) {
2592 grfmsg(1, "LoadTranslationTable: %s translation table must start at zero", name);
2593 return CIR_INVALID_ID;
2596 translation_table.clear();
2597 for (int i = 0; i < numinfo; i++) {
2598 uint32 item = buf->ReadDWord();
2599 translation_table.push_back(BSWAP32(item));
2602 return CIR_SUCCESS;
2606 * Helper to read a DWord worth of bytes from the reader
2607 * and to return it as a valid string.
2608 * @param reader The source of the DWord.
2609 * @return The read DWord as string.
2611 static std::string ReadDWordAsString(ByteReader *reader)
2613 char output[5];
2614 for (int i = 0; i < 4; i++) output[i] = reader->ReadByte();
2615 output[4] = '\0';
2616 StrMakeValidInPlace(output, lastof(output));
2618 return std::string(output);
2622 * Define properties for global variables
2623 * @param gvid ID of the global variable.
2624 * @param numinfo Number of subsequent IDs to change the property for.
2625 * @param prop The property to change.
2626 * @param buf The property value.
2627 * @return ChangeInfoResult.
2629 static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
2631 /* Properties which are handled as a whole */
2632 switch (prop) {
2633 case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2634 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2636 case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2637 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2639 case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2640 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2642 case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2643 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
2645 default:
2646 break;
2649 /* Properties which are handled per item */
2650 ChangeInfoResult ret = CIR_SUCCESS;
2651 for (int i = 0; i < numinfo; i++) {
2652 switch (prop) {
2653 case 0x08: { // Cost base factor
2654 int factor = buf->ReadByte();
2655 uint price = gvid + i;
2657 if (price < PR_END) {
2658 _cur.grffile->price_base_multipliers[price] = std::min<int>(factor - 8, MAX_PRICE_MODIFIER);
2659 } else {
2660 grfmsg(1, "GlobalVarChangeInfo: Price %d out of range, ignoring", price);
2662 break;
2665 case 0x0A: { // Currency display names
2666 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2667 StringID newone = GetGRFStringID(_cur.grffile->grfid, buf->ReadWord());
2669 if ((newone != STR_UNDEFINED) && (curidx < CURRENCY_END)) {
2670 _currency_specs[curidx].name = newone;
2672 break;
2675 case 0x0B: { // Currency multipliers
2676 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2677 uint32 rate = buf->ReadDWord();
2679 if (curidx < CURRENCY_END) {
2680 /* TTDPatch uses a multiple of 1000 for its conversion calculations,
2681 * which OTTD does not. For this reason, divide grf value by 1000,
2682 * to be compatible */
2683 _currency_specs[curidx].rate = rate / 1000;
2684 } else {
2685 grfmsg(1, "GlobalVarChangeInfo: Currency multipliers %d out of range, ignoring", curidx);
2687 break;
2690 case 0x0C: { // Currency options
2691 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2692 uint16 options = buf->ReadWord();
2694 if (curidx < CURRENCY_END) {
2695 _currency_specs[curidx].separator.clear();
2696 _currency_specs[curidx].separator.push_back(GB(options, 0, 8));
2697 /* By specifying only one bit, we prevent errors,
2698 * since newgrf specs said that only 0 and 1 can be set for symbol_pos */
2699 _currency_specs[curidx].symbol_pos = GB(options, 8, 1);
2700 } else {
2701 grfmsg(1, "GlobalVarChangeInfo: Currency option %d out of range, ignoring", curidx);
2703 break;
2706 case 0x0D: { // Currency prefix symbol
2707 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2708 std::string prefix = ReadDWordAsString(buf);
2710 if (curidx < CURRENCY_END) {
2711 _currency_specs[curidx].prefix = prefix;
2712 } else {
2713 grfmsg(1, "GlobalVarChangeInfo: Currency symbol %d out of range, ignoring", curidx);
2715 break;
2718 case 0x0E: { // Currency suffix symbol
2719 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2720 std::string suffix = ReadDWordAsString(buf);
2722 if (curidx < CURRENCY_END) {
2723 _currency_specs[curidx].suffix = suffix;
2724 } else {
2725 grfmsg(1, "GlobalVarChangeInfo: Currency symbol %d out of range, ignoring", curidx);
2727 break;
2730 case 0x0F: { // Euro introduction dates
2731 uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2732 Year year_euro = buf->ReadWord();
2734 if (curidx < CURRENCY_END) {
2735 _currency_specs[curidx].to_euro = year_euro;
2736 } else {
2737 grfmsg(1, "GlobalVarChangeInfo: Euro intro date %d out of range, ignoring", curidx);
2739 break;
2742 case 0x10: // Snow line height table
2743 if (numinfo > 1 || IsSnowLineSet()) {
2744 grfmsg(1, "GlobalVarChangeInfo: The snowline can only be set once (%d)", numinfo);
2745 } else if (buf->Remaining() < SNOW_LINE_MONTHS * SNOW_LINE_DAYS) {
2746 grfmsg(1, "GlobalVarChangeInfo: Not enough entries set in the snowline table (" PRINTF_SIZE ")", buf->Remaining());
2747 } else {
2748 byte table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS];
2750 for (uint i = 0; i < SNOW_LINE_MONTHS; i++) {
2751 for (uint j = 0; j < SNOW_LINE_DAYS; j++) {
2752 table[i][j] = buf->ReadByte();
2753 if (_cur.grffile->grf_version >= 8) {
2754 if (table[i][j] != 0xFF) table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 256;
2755 } else {
2756 if (table[i][j] >= 128) {
2757 /* no snow */
2758 table[i][j] = 0xFF;
2759 } else {
2760 table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 128;
2765 SetSnowLine(table);
2767 break;
2769 case 0x11: // GRF match for engine allocation
2770 /* This is loaded during the reservation stage, so just skip it here. */
2771 /* Each entry is 8 bytes. */
2772 buf->Skip(8);
2773 break;
2775 case 0x13: // Gender translation table
2776 case 0x14: // Case translation table
2777 case 0x15: { // Plural form translation
2778 uint curidx = gvid + i; // The current index, i.e. language.
2779 const LanguageMetadata *lang = curidx < MAX_LANG ? GetLanguage(curidx) : nullptr;
2780 if (lang == nullptr) {
2781 grfmsg(1, "GlobalVarChangeInfo: Language %d is not known, ignoring", curidx);
2782 /* Skip over the data. */
2783 if (prop == 0x15) {
2784 buf->ReadByte();
2785 } else {
2786 while (buf->ReadByte() != 0) {
2787 buf->ReadString();
2790 break;
2793 if (_cur.grffile->language_map == nullptr) _cur.grffile->language_map = new LanguageMap[MAX_LANG];
2795 if (prop == 0x15) {
2796 uint plural_form = buf->ReadByte();
2797 if (plural_form >= LANGUAGE_MAX_PLURAL) {
2798 grfmsg(1, "GlobalVarChanceInfo: Plural form %d is out of range, ignoring", plural_form);
2799 } else {
2800 _cur.grffile->language_map[curidx].plural_form = plural_form;
2802 break;
2805 byte newgrf_id = buf->ReadByte(); // The NewGRF (custom) identifier.
2806 while (newgrf_id != 0) {
2807 const char *name = buf->ReadString(); // The name for the OpenTTD identifier.
2809 /* We'll just ignore the UTF8 identifier character. This is (fairly)
2810 * safe as OpenTTD's strings gender/cases are usually in ASCII which
2811 * is just a subset of UTF8, or they need the bigger UTF8 characters
2812 * such as Cyrillic. Thus we will simply assume they're all UTF8. */
2813 WChar c;
2814 size_t len = Utf8Decode(&c, name);
2815 if (c == NFO_UTF8_IDENTIFIER) name += len;
2817 LanguageMap::Mapping map;
2818 map.newgrf_id = newgrf_id;
2819 if (prop == 0x13) {
2820 map.openttd_id = lang->GetGenderIndex(name);
2821 if (map.openttd_id >= MAX_NUM_GENDERS) {
2822 grfmsg(1, "GlobalVarChangeInfo: Gender name %s is not known, ignoring", name);
2823 } else {
2824 _cur.grffile->language_map[curidx].gender_map.push_back(map);
2826 } else {
2827 map.openttd_id = lang->GetCaseIndex(name);
2828 if (map.openttd_id >= MAX_NUM_CASES) {
2829 grfmsg(1, "GlobalVarChangeInfo: Case name %s is not known, ignoring", name);
2830 } else {
2831 _cur.grffile->language_map[curidx].case_map.push_back(map);
2834 newgrf_id = buf->ReadByte();
2836 break;
2839 default:
2840 ret = CIR_UNKNOWN;
2841 break;
2845 return ret;
2848 static ChangeInfoResult GlobalVarReserveInfo(uint gvid, int numinfo, int prop, ByteReader *buf)
2850 /* Properties which are handled as a whole */
2851 switch (prop) {
2852 case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2853 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2855 case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2856 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2858 case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined roadtypes)
2859 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2861 case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined tramtypes)
2862 return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
2864 default:
2865 break;
2868 /* Properties which are handled per item */
2869 ChangeInfoResult ret = CIR_SUCCESS;
2870 for (int i = 0; i < numinfo; i++) {
2871 switch (prop) {
2872 case 0x08: // Cost base factor
2873 case 0x15: // Plural form translation
2874 buf->ReadByte();
2875 break;
2877 case 0x0A: // Currency display names
2878 case 0x0C: // Currency options
2879 case 0x0F: // Euro introduction dates
2880 buf->ReadWord();
2881 break;
2883 case 0x0B: // Currency multipliers
2884 case 0x0D: // Currency prefix symbol
2885 case 0x0E: // Currency suffix symbol
2886 buf->ReadDWord();
2887 break;
2889 case 0x10: // Snow line height table
2890 buf->Skip(SNOW_LINE_MONTHS * SNOW_LINE_DAYS);
2891 break;
2893 case 0x11: { // GRF match for engine allocation
2894 uint32 s = buf->ReadDWord();
2895 uint32 t = buf->ReadDWord();
2896 SetNewGRFOverride(s, t);
2897 break;
2900 case 0x13: // Gender translation table
2901 case 0x14: // Case translation table
2902 while (buf->ReadByte() != 0) {
2903 buf->ReadString();
2905 break;
2907 default:
2908 ret = CIR_UNKNOWN;
2909 break;
2913 return ret;
2918 * Define properties for cargoes
2919 * @param cid Local ID of the cargo.
2920 * @param numinfo Number of subsequent IDs to change the property for.
2921 * @param prop The property to change.
2922 * @param buf The property value.
2923 * @return ChangeInfoResult.
2925 static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader *buf)
2927 ChangeInfoResult ret = CIR_SUCCESS;
2929 if (cid + numinfo > NUM_CARGO) {
2930 grfmsg(2, "CargoChangeInfo: Cargo type %d out of range (max %d)", cid + numinfo, NUM_CARGO - 1);
2931 return CIR_INVALID_ID;
2934 for (int i = 0; i < numinfo; i++) {
2935 CargoSpec *cs = CargoSpec::Get(cid + i);
2937 switch (prop) {
2938 case 0x08: // Bit number of cargo
2939 cs->bitnum = buf->ReadByte();
2940 if (cs->IsValid()) {
2941 cs->grffile = _cur.grffile;
2942 SetBit(_cargo_mask, cid + i);
2943 } else {
2944 ClrBit(_cargo_mask, cid + i);
2946 break;
2948 case 0x09: // String ID for cargo type name
2949 AddStringForMapping(buf->ReadWord(), &cs->name);
2950 break;
2952 case 0x0A: // String for 1 unit of cargo
2953 AddStringForMapping(buf->ReadWord(), &cs->name_single);
2954 break;
2956 case 0x0B: // String for singular quantity of cargo (e.g. 1 tonne of coal)
2957 case 0x1B: // String for cargo units
2958 /* String for units of cargo. This is different in OpenTTD
2959 * (e.g. tonnes) to TTDPatch (e.g. {COMMA} tonne of coal).
2960 * Property 1B is used to set OpenTTD's behaviour. */
2961 AddStringForMapping(buf->ReadWord(), &cs->units_volume);
2962 break;
2964 case 0x0C: // String for plural quantity of cargo (e.g. 10 tonnes of coal)
2965 case 0x1C: // String for any amount of cargo
2966 /* Strings for an amount of cargo. This is different in OpenTTD
2967 * (e.g. {WEIGHT} of coal) to TTDPatch (e.g. {COMMA} tonnes of coal).
2968 * Property 1C is used to set OpenTTD's behaviour. */
2969 AddStringForMapping(buf->ReadWord(), &cs->quantifier);
2970 break;
2972 case 0x0D: // String for two letter cargo abbreviation
2973 AddStringForMapping(buf->ReadWord(), &cs->abbrev);
2974 break;
2976 case 0x0E: // Sprite ID for cargo icon
2977 cs->sprite = buf->ReadWord();
2978 break;
2980 case 0x0F: // Weight of one unit of cargo
2981 cs->weight = buf->ReadByte();
2982 break;
2984 case 0x10: // Used for payment calculation
2985 cs->transit_days[0] = buf->ReadByte();
2986 break;
2988 case 0x11: // Used for payment calculation
2989 cs->transit_days[1] = buf->ReadByte();
2990 break;
2992 case 0x12: // Base cargo price
2993 cs->initial_payment = buf->ReadDWord();
2994 break;
2996 case 0x13: // Colour for station rating bars
2997 cs->rating_colour = buf->ReadByte();
2998 break;
3000 case 0x14: // Colour for cargo graph
3001 cs->legend_colour = buf->ReadByte();
3002 break;
3004 case 0x15: // Freight status
3005 cs->is_freight = (buf->ReadByte() != 0);
3006 break;
3008 case 0x16: // Cargo classes
3009 cs->classes = buf->ReadWord();
3010 break;
3012 case 0x17: // Cargo label
3013 cs->label = buf->ReadDWord();
3014 cs->label = BSWAP32(cs->label);
3015 break;
3017 case 0x18: { // Town growth substitute type
3018 uint8 substitute_type = buf->ReadByte();
3020 switch (substitute_type) {
3021 case 0x00: cs->town_effect = TE_PASSENGERS; break;
3022 case 0x02: cs->town_effect = TE_MAIL; break;
3023 case 0x05: cs->town_effect = TE_GOODS; break;
3024 case 0x09: cs->town_effect = TE_WATER; break;
3025 case 0x0B: cs->town_effect = TE_FOOD; break;
3026 default:
3027 grfmsg(1, "CargoChangeInfo: Unknown town growth substitute value %d, setting to none.", substitute_type);
3028 FALLTHROUGH;
3029 case 0xFF: cs->town_effect = TE_NONE; break;
3031 break;
3034 case 0x19: // Town growth coefficient
3035 buf->ReadWord();
3036 break;
3038 case 0x1A: // Bitmask of callbacks to use
3039 cs->callback_mask = buf->ReadByte();
3040 break;
3042 case 0x1D: // Vehicle capacity muliplier
3043 cs->multiplier = std::max<uint16>(1u, buf->ReadWord());
3044 break;
3046 default:
3047 ret = CIR_UNKNOWN;
3048 break;
3052 return ret;
3057 * Define properties for sound effects
3058 * @param sid Local ID of the sound.
3059 * @param numinfo Number of subsequent IDs to change the property for.
3060 * @param prop The property to change.
3061 * @param buf The property value.
3062 * @return ChangeInfoResult.
3064 static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, ByteReader *buf)
3066 ChangeInfoResult ret = CIR_SUCCESS;
3068 if (_cur.grffile->sound_offset == 0) {
3069 grfmsg(1, "SoundEffectChangeInfo: No effects defined, skipping");
3070 return CIR_INVALID_ID;
3073 if (sid + numinfo - ORIGINAL_SAMPLE_COUNT > _cur.grffile->num_sounds) {
3074 grfmsg(1, "SoundEffectChangeInfo: Attempting to change undefined sound effect (%u), max (%u). Ignoring.", sid + numinfo, ORIGINAL_SAMPLE_COUNT + _cur.grffile->num_sounds);
3075 return CIR_INVALID_ID;
3078 for (int i = 0; i < numinfo; i++) {
3079 SoundEntry *sound = GetSound(sid + i + _cur.grffile->sound_offset - ORIGINAL_SAMPLE_COUNT);
3081 switch (prop) {
3082 case 0x08: // Relative volume
3083 sound->volume = buf->ReadByte();
3084 break;
3086 case 0x09: // Priority
3087 sound->priority = buf->ReadByte();
3088 break;
3090 case 0x0A: { // Override old sound
3091 SoundID orig_sound = buf->ReadByte();
3093 if (orig_sound >= ORIGINAL_SAMPLE_COUNT) {
3094 grfmsg(1, "SoundEffectChangeInfo: Original sound %d not defined (max %d)", orig_sound, ORIGINAL_SAMPLE_COUNT);
3095 } else {
3096 SoundEntry *old_sound = GetSound(orig_sound);
3098 /* Literally copy the data of the new sound over the original */
3099 *old_sound = *sound;
3101 break;
3104 default:
3105 ret = CIR_UNKNOWN;
3106 break;
3110 return ret;
3114 * Ignore an industry tile property
3115 * @param prop The property to ignore.
3116 * @param buf The property value.
3117 * @return ChangeInfoResult.
3119 static ChangeInfoResult IgnoreIndustryTileProperty(int prop, ByteReader *buf)
3121 ChangeInfoResult ret = CIR_SUCCESS;
3123 switch (prop) {
3124 case 0x09:
3125 case 0x0D:
3126 case 0x0E:
3127 case 0x10:
3128 case 0x11:
3129 case 0x12:
3130 buf->ReadByte();
3131 break;
3133 case 0x0A:
3134 case 0x0B:
3135 case 0x0C:
3136 case 0x0F:
3137 buf->ReadWord();
3138 break;
3140 case 0x13:
3141 buf->Skip(buf->ReadByte() * 2);
3142 break;
3144 default:
3145 ret = CIR_UNKNOWN;
3146 break;
3148 return ret;
3152 * Define properties for industry tiles
3153 * @param indtid Local ID of the industry tile.
3154 * @param numinfo Number of subsequent industry tile IDs to change the property for.
3155 * @param prop The property to change.
3156 * @param buf The property value.
3157 * @return ChangeInfoResult.
3159 static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader *buf)
3161 ChangeInfoResult ret = CIR_SUCCESS;
3163 if (indtid + numinfo > NUM_INDUSTRYTILES_PER_GRF) {
3164 grfmsg(1, "IndustryTilesChangeInfo: Too many industry tiles loaded (%u), max (%u). Ignoring.", indtid + numinfo, NUM_INDUSTRYTILES_PER_GRF);
3165 return CIR_INVALID_ID;
3168 /* Allocate industry tile specs if they haven't been allocated already. */
3169 if (_cur.grffile->indtspec == nullptr) {
3170 _cur.grffile->indtspec = CallocT<IndustryTileSpec*>(NUM_INDUSTRYTILES_PER_GRF);
3173 for (int i = 0; i < numinfo; i++) {
3174 IndustryTileSpec *tsp = _cur.grffile->indtspec[indtid + i];
3176 if (prop != 0x08 && tsp == nullptr) {
3177 ChangeInfoResult cir = IgnoreIndustryTileProperty(prop, buf);
3178 if (cir > ret) ret = cir;
3179 continue;
3182 switch (prop) {
3183 case 0x08: { // Substitute industry tile type
3184 IndustryTileSpec **tilespec = &_cur.grffile->indtspec[indtid + i];
3185 byte subs_id = buf->ReadByte();
3187 if (subs_id >= NEW_INDUSTRYTILEOFFSET) {
3188 /* The substitute id must be one of the original industry tile. */
3189 grfmsg(2, "IndustryTilesChangeInfo: Attempt to use new industry tile %u as substitute industry tile for %u. Ignoring.", subs_id, indtid + i);
3190 continue;
3193 /* Allocate space for this industry. */
3194 if (*tilespec == nullptr) {
3195 *tilespec = CallocT<IndustryTileSpec>(1);
3196 tsp = *tilespec;
3198 memcpy(tsp, &_industry_tile_specs[subs_id], sizeof(_industry_tile_specs[subs_id]));
3199 tsp->enabled = true;
3201 /* A copied tile should not have the animation infos copied too.
3202 * The anim_state should be left untouched, though
3203 * It is up to the author to animate them */
3204 tsp->anim_production = INDUSTRYTILE_NOANIM;
3205 tsp->anim_next = INDUSTRYTILE_NOANIM;
3207 tsp->grf_prop.local_id = indtid + i;
3208 tsp->grf_prop.subst_id = subs_id;
3209 tsp->grf_prop.grffile = _cur.grffile;
3210 _industile_mngr.AddEntityID(indtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
3212 break;
3215 case 0x09: { // Industry tile override
3216 byte ovrid = buf->ReadByte();
3218 /* The industry being overridden must be an original industry. */
3219 if (ovrid >= NEW_INDUSTRYTILEOFFSET) {
3220 grfmsg(2, "IndustryTilesChangeInfo: Attempt to override new industry tile %u with industry tile id %u. Ignoring.", ovrid, indtid + i);
3221 continue;
3224 _industile_mngr.Add(indtid + i, _cur.grffile->grfid, ovrid);
3225 break;
3228 case 0x0A: // Tile acceptance
3229 case 0x0B:
3230 case 0x0C: {
3231 uint16 acctp = buf->ReadWord();
3232 tsp->accepts_cargo[prop - 0x0A] = GetCargoTranslation(GB(acctp, 0, 8), _cur.grffile);
3233 tsp->acceptance[prop - 0x0A] = Clamp(GB(acctp, 8, 8), 0, 16);
3234 break;
3237 case 0x0D: // Land shape flags
3238 tsp->slopes_refused = (Slope)buf->ReadByte();
3239 break;
3241 case 0x0E: // Callback mask
3242 tsp->callback_mask = buf->ReadByte();
3243 break;
3245 case 0x0F: // Animation information
3246 tsp->animation.frames = buf->ReadByte();
3247 tsp->animation.status = buf->ReadByte();
3248 break;
3250 case 0x10: // Animation speed
3251 tsp->animation.speed = buf->ReadByte();
3252 break;
3254 case 0x11: // Triggers for callback 25
3255 tsp->animation.triggers = buf->ReadByte();
3256 break;
3258 case 0x12: // Special flags
3259 tsp->special_flags = (IndustryTileSpecialFlags)buf->ReadByte();
3260 break;
3262 case 0x13: { // variable length cargo acceptance
3263 byte num_cargoes = buf->ReadByte();
3264 if (num_cargoes > lengthof(tsp->acceptance)) {
3265 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3266 error->param_value[1] = prop;
3267 return CIR_DISABLED;
3269 for (uint i = 0; i < lengthof(tsp->acceptance); i++) {
3270 if (i < num_cargoes) {
3271 tsp->accepts_cargo[i] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3272 /* Tile acceptance can be negative to counteract the INDTILE_SPECIAL_ACCEPTS_ALL_CARGO flag */
3273 tsp->acceptance[i] = (int8)buf->ReadByte();
3274 } else {
3275 tsp->accepts_cargo[i] = CT_INVALID;
3276 tsp->acceptance[i] = 0;
3279 break;
3282 default:
3283 ret = CIR_UNKNOWN;
3284 break;
3288 return ret;
3292 * Ignore an industry property
3293 * @param prop The property to ignore.
3294 * @param buf The property value.
3295 * @return ChangeInfoResult.
3297 static ChangeInfoResult IgnoreIndustryProperty(int prop, ByteReader *buf)
3299 ChangeInfoResult ret = CIR_SUCCESS;
3301 switch (prop) {
3302 case 0x09:
3303 case 0x0B:
3304 case 0x0F:
3305 case 0x12:
3306 case 0x13:
3307 case 0x14:
3308 case 0x17:
3309 case 0x18:
3310 case 0x19:
3311 case 0x21:
3312 case 0x22:
3313 buf->ReadByte();
3314 break;
3316 case 0x0C:
3317 case 0x0D:
3318 case 0x0E:
3319 case 0x10:
3320 case 0x1B:
3321 case 0x1F:
3322 case 0x24:
3323 buf->ReadWord();
3324 break;
3326 case 0x11:
3327 case 0x1A:
3328 case 0x1C:
3329 case 0x1D:
3330 case 0x1E:
3331 case 0x20:
3332 case 0x23:
3333 buf->ReadDWord();
3334 break;
3336 case 0x0A: {
3337 byte num_table = buf->ReadByte();
3338 for (byte j = 0; j < num_table; j++) {
3339 for (uint k = 0;; k++) {
3340 byte x = buf->ReadByte();
3341 if (x == 0xFE && k == 0) {
3342 buf->ReadByte();
3343 buf->ReadByte();
3344 break;
3347 byte y = buf->ReadByte();
3348 if (x == 0 && y == 0x80) break;
3350 byte gfx = buf->ReadByte();
3351 if (gfx == 0xFE) buf->ReadWord();
3354 break;
3357 case 0x16:
3358 for (byte j = 0; j < 3; j++) buf->ReadByte();
3359 break;
3361 case 0x15:
3362 case 0x25:
3363 case 0x26:
3364 case 0x27:
3365 buf->Skip(buf->ReadByte());
3366 break;
3368 case 0x28: {
3369 int num_inputs = buf->ReadByte();
3370 int num_outputs = buf->ReadByte();
3371 buf->Skip(num_inputs * num_outputs * 2);
3372 break;
3375 default:
3376 ret = CIR_UNKNOWN;
3377 break;
3379 return ret;
3383 * Validate the industry layout; e.g. to prevent duplicate tiles.
3384 * @param layout The layout to check.
3385 * @return True if the layout is deemed valid.
3387 static bool ValidateIndustryLayout(const IndustryTileLayout &layout)
3389 const size_t size = layout.size();
3390 if (size == 0) return false;
3392 for (size_t i = 0; i < size - 1; i++) {
3393 for (size_t j = i + 1; j < size; j++) {
3394 if (layout[i].ti.x == layout[j].ti.x &&
3395 layout[i].ti.y == layout[j].ti.y) {
3396 return false;
3401 bool have_regular_tile = false;
3402 for (size_t i = 0; i < size; i++) {
3403 if (layout[i].gfx != GFX_WATERTILE_SPECIALCHECK) {
3404 have_regular_tile = true;
3405 break;
3409 return have_regular_tile;
3413 * Define properties for industries
3414 * @param indid Local ID of the industry.
3415 * @param numinfo Number of subsequent industry IDs to change the property for.
3416 * @param prop The property to change.
3417 * @param buf The property value.
3418 * @return ChangeInfoResult.
3420 static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, ByteReader *buf)
3422 ChangeInfoResult ret = CIR_SUCCESS;
3424 if (indid + numinfo > NUM_INDUSTRYTYPES_PER_GRF) {
3425 grfmsg(1, "IndustriesChangeInfo: Too many industries loaded (%u), max (%u). Ignoring.", indid + numinfo, NUM_INDUSTRYTYPES_PER_GRF);
3426 return CIR_INVALID_ID;
3429 /* Allocate industry specs if they haven't been allocated already. */
3430 if (_cur.grffile->industryspec == nullptr) {
3431 _cur.grffile->industryspec = CallocT<IndustrySpec*>(NUM_INDUSTRYTYPES_PER_GRF);
3434 for (int i = 0; i < numinfo; i++) {
3435 IndustrySpec *indsp = _cur.grffile->industryspec[indid + i];
3437 if (prop != 0x08 && indsp == nullptr) {
3438 ChangeInfoResult cir = IgnoreIndustryProperty(prop, buf);
3439 if (cir > ret) ret = cir;
3440 continue;
3443 switch (prop) {
3444 case 0x08: { // Substitute industry type
3445 IndustrySpec **indspec = &_cur.grffile->industryspec[indid + i];
3446 byte subs_id = buf->ReadByte();
3448 if (subs_id == 0xFF) {
3449 /* Instead of defining a new industry, a substitute industry id
3450 * of 0xFF disables the old industry with the current id. */
3451 _industry_specs[indid + i].enabled = false;
3452 continue;
3453 } else if (subs_id >= NEW_INDUSTRYOFFSET) {
3454 /* The substitute id must be one of the original industry. */
3455 grfmsg(2, "_industry_specs: Attempt to use new industry %u as substitute industry for %u. Ignoring.", subs_id, indid + i);
3456 continue;
3459 /* Allocate space for this industry.
3460 * Only need to do it once. If ever it is called again, it should not
3461 * do anything */
3462 if (*indspec == nullptr) {
3463 *indspec = new IndustrySpec;
3464 indsp = *indspec;
3466 *indsp = _origin_industry_specs[subs_id];
3467 indsp->enabled = true;
3468 indsp->grf_prop.local_id = indid + i;
3469 indsp->grf_prop.subst_id = subs_id;
3470 indsp->grf_prop.grffile = _cur.grffile;
3471 /* If the grf industry needs to check its surrounding upon creation, it should
3472 * rely on callbacks, not on the original placement functions */
3473 indsp->check_proc = CHECK_NOTHING;
3475 break;
3478 case 0x09: { // Industry type override
3479 byte ovrid = buf->ReadByte();
3481 /* The industry being overridden must be an original industry. */
3482 if (ovrid >= NEW_INDUSTRYOFFSET) {
3483 grfmsg(2, "IndustriesChangeInfo: Attempt to override new industry %u with industry id %u. Ignoring.", ovrid, indid + i);
3484 continue;
3486 indsp->grf_prop.override = ovrid;
3487 _industry_mngr.Add(indid + i, _cur.grffile->grfid, ovrid);
3488 break;
3491 case 0x0A: { // Set industry layout(s)
3492 byte new_num_layouts = buf->ReadByte();
3493 uint32 definition_size = buf->ReadDWord();
3494 uint32 bytes_read = 0;
3495 std::vector<IndustryTileLayout> new_layouts;
3496 IndustryTileLayout layout;
3498 for (byte j = 0; j < new_num_layouts; j++) {
3499 layout.clear();
3501 for (uint k = 0;; k++) {
3502 if (bytes_read >= definition_size) {
3503 grfmsg(3, "IndustriesChangeInfo: Incorrect size for industry tile layout definition for industry %u.", indid);
3504 /* Avoid warning twice */
3505 definition_size = UINT32_MAX;
3508 layout.push_back(IndustryTileLayoutTile{});
3509 IndustryTileLayoutTile &it = layout.back();
3511 it.ti.x = buf->ReadByte(); // Offsets from northermost tile
3512 ++bytes_read;
3514 if (it.ti.x == 0xFE && k == 0) {
3515 /* This means we have to borrow the layout from an old industry */
3516 IndustryType type = buf->ReadByte();
3517 byte laynbr = buf->ReadByte();
3518 bytes_read += 2;
3520 if (type >= lengthof(_origin_industry_specs)) {
3521 grfmsg(1, "IndustriesChangeInfo: Invalid original industry number for layout import, industry %u", indid);
3522 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3523 return CIR_DISABLED;
3525 if (laynbr >= _origin_industry_specs[type].layouts.size()) {
3526 grfmsg(1, "IndustriesChangeInfo: Invalid original industry layout index for layout import, industry %u", indid);
3527 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3528 return CIR_DISABLED;
3530 layout = _origin_industry_specs[type].layouts[laynbr];
3531 break;
3534 it.ti.y = buf->ReadByte(); // Or table definition finalisation
3535 ++bytes_read;
3537 if (it.ti.x == 0 && it.ti.y == 0x80) {
3538 /* Terminator, remove and finish up */
3539 layout.pop_back();
3540 break;
3543 it.gfx = buf->ReadByte();
3544 ++bytes_read;
3546 if (it.gfx == 0xFE) {
3547 /* Use a new tile from this GRF */
3548 int local_tile_id = buf->ReadWord();
3549 bytes_read += 2;
3551 /* Read the ID from the _industile_mngr. */
3552 int tempid = _industile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3554 if (tempid == INVALID_INDUSTRYTILE) {
3555 grfmsg(2, "IndustriesChangeInfo: Attempt to use industry tile %u with industry id %u, not yet defined. Ignoring.", local_tile_id, indid);
3556 } else {
3557 /* Declared as been valid, can be used */
3558 it.gfx = tempid;
3560 } else if (it.gfx == GFX_WATERTILE_SPECIALCHECK) {
3561 it.ti.x = (int8)GB(it.ti.x, 0, 8);
3562 it.ti.y = (int8)GB(it.ti.y, 0, 8);
3564 /* When there were only 256x256 maps, TileIndex was a uint16 and
3565 * it.ti was just a TileIndexDiff that was added to it.
3566 * As such negative "x" values were shifted into the "y" position.
3567 * x = -1, y = 1 -> x = 255, y = 0
3568 * Since GRF version 8 the position is interpreted as pair of independent int8.
3569 * For GRF version < 8 we need to emulate the old shifting behaviour.
3571 if (_cur.grffile->grf_version < 8 && it.ti.x < 0) it.ti.y += 1;
3575 if (!ValidateIndustryLayout(layout)) {
3576 /* The industry layout was not valid, so skip this one. */
3577 grfmsg(1, "IndustriesChangeInfo: Invalid industry layout for industry id %u. Ignoring", indid);
3578 new_num_layouts--;
3579 j--;
3580 } else {
3581 new_layouts.push_back(layout);
3585 /* Install final layout construction in the industry spec */
3586 indsp->layouts = new_layouts;
3587 break;
3590 case 0x0B: // Industry production flags
3591 indsp->life_type = (IndustryLifeType)buf->ReadByte();
3592 break;
3594 case 0x0C: // Industry closure message
3595 AddStringForMapping(buf->ReadWord(), &indsp->closure_text);
3596 break;
3598 case 0x0D: // Production increase message
3599 AddStringForMapping(buf->ReadWord(), &indsp->production_up_text);
3600 break;
3602 case 0x0E: // Production decrease message
3603 AddStringForMapping(buf->ReadWord(), &indsp->production_down_text);
3604 break;
3606 case 0x0F: // Fund cost multiplier
3607 indsp->cost_multiplier = buf->ReadByte();
3608 break;
3610 case 0x10: // Production cargo types
3611 for (byte j = 0; j < 2; j++) {
3612 indsp->produced_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3614 break;
3616 case 0x11: // Acceptance cargo types
3617 for (byte j = 0; j < 3; j++) {
3618 indsp->accepts_cargo[j] = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3620 buf->ReadByte(); // Unnused, eat it up
3621 break;
3623 case 0x12: // Production multipliers
3624 case 0x13:
3625 indsp->production_rate[prop - 0x12] = buf->ReadByte();
3626 break;
3628 case 0x14: // Minimal amount of cargo distributed
3629 indsp->minimal_cargo = buf->ReadByte();
3630 break;
3632 case 0x15: { // Random sound effects
3633 indsp->number_of_sounds = buf->ReadByte();
3634 uint8 *sounds = MallocT<uint8>(indsp->number_of_sounds);
3636 try {
3637 for (uint8 j = 0; j < indsp->number_of_sounds; j++) {
3638 sounds[j] = buf->ReadByte();
3640 } catch (...) {
3641 free(sounds);
3642 throw;
3645 if (HasBit(indsp->cleanup_flag, CLEAN_RANDOMSOUNDS)) {
3646 free(indsp->random_sounds);
3648 indsp->random_sounds = sounds;
3649 SetBit(indsp->cleanup_flag, CLEAN_RANDOMSOUNDS);
3650 break;
3653 case 0x16: // Conflicting industry types
3654 for (byte j = 0; j < 3; j++) indsp->conflicting[j] = buf->ReadByte();
3655 break;
3657 case 0x17: // Probability in random game
3658 indsp->appear_creation[_settings_game.game_creation.landscape] = buf->ReadByte();
3659 break;
3661 case 0x18: // Probability during gameplay
3662 indsp->appear_ingame[_settings_game.game_creation.landscape] = buf->ReadByte();
3663 break;
3665 case 0x19: // Map colour
3666 indsp->map_colour = buf->ReadByte();
3667 break;
3669 case 0x1A: // Special industry flags to define special behavior
3670 indsp->behaviour = (IndustryBehaviour)buf->ReadDWord();
3671 break;
3673 case 0x1B: // New industry text ID
3674 AddStringForMapping(buf->ReadWord(), &indsp->new_industry_text);
3675 break;
3677 case 0x1C: // Input cargo multipliers for the three input cargo types
3678 case 0x1D:
3679 case 0x1E: {
3680 uint32 multiples = buf->ReadDWord();
3681 indsp->input_cargo_multiplier[prop - 0x1C][0] = GB(multiples, 0, 16);
3682 indsp->input_cargo_multiplier[prop - 0x1C][1] = GB(multiples, 16, 16);
3683 break;
3686 case 0x1F: // Industry name
3687 AddStringForMapping(buf->ReadWord(), &indsp->name);
3688 break;
3690 case 0x20: // Prospecting success chance
3691 indsp->prospecting_chance = buf->ReadDWord();
3692 break;
3694 case 0x21: // Callback mask
3695 case 0x22: { // Callback additional mask
3696 byte aflag = buf->ReadByte();
3697 SB(indsp->callback_mask, (prop - 0x21) * 8, 8, aflag);
3698 break;
3701 case 0x23: // removal cost multiplier
3702 indsp->removal_cost_multiplier = buf->ReadDWord();
3703 break;
3705 case 0x24: { // name for nearby station
3706 uint16 str = buf->ReadWord();
3707 if (str == 0) {
3708 indsp->station_name = STR_NULL;
3709 } else {
3710 AddStringForMapping(str, &indsp->station_name);
3712 break;
3715 case 0x25: { // variable length produced cargoes
3716 byte num_cargoes = buf->ReadByte();
3717 if (num_cargoes > lengthof(indsp->produced_cargo)) {
3718 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3719 error->param_value[1] = prop;
3720 return CIR_DISABLED;
3722 for (uint i = 0; i < lengthof(indsp->produced_cargo); i++) {
3723 if (i < num_cargoes) {
3724 CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3725 indsp->produced_cargo[i] = cargo;
3726 } else {
3727 indsp->produced_cargo[i] = CT_INVALID;
3730 break;
3733 case 0x26: { // variable length accepted cargoes
3734 byte num_cargoes = buf->ReadByte();
3735 if (num_cargoes > lengthof(indsp->accepts_cargo)) {
3736 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3737 error->param_value[1] = prop;
3738 return CIR_DISABLED;
3740 for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
3741 if (i < num_cargoes) {
3742 CargoID cargo = GetCargoTranslation(buf->ReadByte(), _cur.grffile);
3743 indsp->accepts_cargo[i] = cargo;
3744 } else {
3745 indsp->accepts_cargo[i] = CT_INVALID;
3748 break;
3751 case 0x27: { // variable length production rates
3752 byte num_cargoes = buf->ReadByte();
3753 if (num_cargoes > lengthof(indsp->production_rate)) {
3754 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3755 error->param_value[1] = prop;
3756 return CIR_DISABLED;
3758 for (uint i = 0; i < lengthof(indsp->production_rate); i++) {
3759 if (i < num_cargoes) {
3760 indsp->production_rate[i] = buf->ReadByte();
3761 } else {
3762 indsp->production_rate[i] = 0;
3765 break;
3768 case 0x28: { // variable size input/output production multiplier table
3769 byte num_inputs = buf->ReadByte();
3770 byte num_outputs = buf->ReadByte();
3771 if (num_inputs > lengthof(indsp->accepts_cargo) || num_outputs > lengthof(indsp->produced_cargo)) {
3772 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3773 error->param_value[1] = prop;
3774 return CIR_DISABLED;
3776 for (uint i = 0; i < lengthof(indsp->accepts_cargo); i++) {
3777 for (uint j = 0; j < lengthof(indsp->produced_cargo); j++) {
3778 uint16 mult = 0;
3779 if (i < num_inputs && j < num_outputs) mult = buf->ReadWord();
3780 indsp->input_cargo_multiplier[i][j] = mult;
3783 break;
3786 default:
3787 ret = CIR_UNKNOWN;
3788 break;
3792 return ret;
3796 * Create a copy of the tile table so it can be freed later
3797 * without problems.
3798 * @param as The AirportSpec to copy the arrays of.
3800 static void DuplicateTileTable(AirportSpec *as)
3802 AirportTileTable **table_list = MallocT<AirportTileTable*>(as->num_table);
3803 for (int i = 0; i < as->num_table; i++) {
3804 uint num_tiles = 1;
3805 const AirportTileTable *it = as->table[0];
3806 do {
3807 num_tiles++;
3808 } while ((++it)->ti.x != -0x80);
3809 table_list[i] = MallocT<AirportTileTable>(num_tiles);
3810 MemCpyT(table_list[i], as->table[i], num_tiles);
3812 as->table = table_list;
3813 HangarTileTable *depot_table = MallocT<HangarTileTable>(as->nof_depots);
3814 MemCpyT(depot_table, as->depot_table, as->nof_depots);
3815 as->depot_table = depot_table;
3816 Direction *rotation = MallocT<Direction>(as->num_table);
3817 MemCpyT(rotation, as->rotation, as->num_table);
3818 as->rotation = rotation;
3822 * Define properties for airports
3823 * @param airport Local ID of the airport.
3824 * @param numinfo Number of subsequent airport IDs to change the property for.
3825 * @param prop The property to change.
3826 * @param buf The property value.
3827 * @return ChangeInfoResult.
3829 static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader *buf)
3831 ChangeInfoResult ret = CIR_SUCCESS;
3833 if (airport + numinfo > NUM_AIRPORTS_PER_GRF) {
3834 grfmsg(1, "AirportChangeInfo: Too many airports, trying id (%u), max (%u). Ignoring.", airport + numinfo, NUM_AIRPORTS_PER_GRF);
3835 return CIR_INVALID_ID;
3838 /* Allocate industry specs if they haven't been allocated already. */
3839 if (_cur.grffile->airportspec == nullptr) {
3840 _cur.grffile->airportspec = CallocT<AirportSpec*>(NUM_AIRPORTS_PER_GRF);
3843 for (int i = 0; i < numinfo; i++) {
3844 AirportSpec *as = _cur.grffile->airportspec[airport + i];
3846 if (as == nullptr && prop != 0x08 && prop != 0x09) {
3847 grfmsg(2, "AirportChangeInfo: Attempt to modify undefined airport %u, ignoring", airport + i);
3848 return CIR_INVALID_ID;
3851 switch (prop) {
3852 case 0x08: { // Modify original airport
3853 byte subs_id = buf->ReadByte();
3855 if (subs_id == 0xFF) {
3856 /* Instead of defining a new airport, an airport id
3857 * of 0xFF disables the old airport with the current id. */
3858 AirportSpec::GetWithoutOverride(airport + i)->enabled = false;
3859 continue;
3860 } else if (subs_id >= NEW_AIRPORT_OFFSET) {
3861 /* The substitute id must be one of the original airports. */
3862 grfmsg(2, "AirportChangeInfo: Attempt to use new airport %u as substitute airport for %u. Ignoring.", subs_id, airport + i);
3863 continue;
3866 AirportSpec **spec = &_cur.grffile->airportspec[airport + i];
3867 /* Allocate space for this airport.
3868 * Only need to do it once. If ever it is called again, it should not
3869 * do anything */
3870 if (*spec == nullptr) {
3871 *spec = MallocT<AirportSpec>(1);
3872 as = *spec;
3874 memcpy(as, AirportSpec::GetWithoutOverride(subs_id), sizeof(*as));
3875 as->enabled = true;
3876 as->grf_prop.local_id = airport + i;
3877 as->grf_prop.subst_id = subs_id;
3878 as->grf_prop.grffile = _cur.grffile;
3879 /* override the default airport */
3880 _airport_mngr.Add(airport + i, _cur.grffile->grfid, subs_id);
3881 /* Create a copy of the original tiletable so it can be freed later. */
3882 DuplicateTileTable(as);
3884 break;
3887 case 0x0A: { // Set airport layout
3888 byte old_num_table = as->num_table;
3889 free(as->rotation);
3890 as->num_table = buf->ReadByte(); // Number of layaouts
3891 as->rotation = MallocT<Direction>(as->num_table);
3892 uint32 defsize = buf->ReadDWord(); // Total size of the definition
3893 AirportTileTable **tile_table = CallocT<AirportTileTable*>(as->num_table); // Table with tiles to compose the airport
3894 AirportTileTable *att = CallocT<AirportTileTable>(defsize); // Temporary array to read the tile layouts from the GRF
3895 int size;
3896 const AirportTileTable *copy_from;
3897 try {
3898 for (byte j = 0; j < as->num_table; j++) {
3899 const_cast<Direction&>(as->rotation[j]) = (Direction)buf->ReadByte();
3900 for (int k = 0;; k++) {
3901 att[k].ti.x = buf->ReadByte(); // Offsets from northermost tile
3902 att[k].ti.y = buf->ReadByte();
3904 if (att[k].ti.x == 0 && att[k].ti.y == 0x80) {
3905 /* Not the same terminator. The one we are using is rather
3906 * x = -80, y = 0 . So, adjust it. */
3907 att[k].ti.x = -0x80;
3908 att[k].ti.y = 0;
3909 att[k].gfx = 0;
3911 size = k + 1;
3912 copy_from = att;
3913 break;
3916 att[k].gfx = buf->ReadByte();
3918 if (att[k].gfx == 0xFE) {
3919 /* Use a new tile from this GRF */
3920 int local_tile_id = buf->ReadWord();
3922 /* Read the ID from the _airporttile_mngr. */
3923 uint16 tempid = _airporttile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3925 if (tempid == INVALID_AIRPORTTILE) {
3926 grfmsg(2, "AirportChangeInfo: Attempt to use airport tile %u with airport id %u, not yet defined. Ignoring.", local_tile_id, airport + i);
3927 } else {
3928 /* Declared as been valid, can be used */
3929 att[k].gfx = tempid;
3931 } else if (att[k].gfx == 0xFF) {
3932 att[k].ti.x = (int8)GB(att[k].ti.x, 0, 8);
3933 att[k].ti.y = (int8)GB(att[k].ti.y, 0, 8);
3936 if (as->rotation[j] == DIR_E || as->rotation[j] == DIR_W) {
3937 as->size_x = std::max<byte>(as->size_x, att[k].ti.y + 1);
3938 as->size_y = std::max<byte>(as->size_y, att[k].ti.x + 1);
3939 } else {
3940 as->size_x = std::max<byte>(as->size_x, att[k].ti.x + 1);
3941 as->size_y = std::max<byte>(as->size_y, att[k].ti.y + 1);
3944 tile_table[j] = CallocT<AirportTileTable>(size);
3945 memcpy(tile_table[j], copy_from, sizeof(*copy_from) * size);
3947 /* Free old layouts in the airport spec */
3948 for (int j = 0; j < old_num_table; j++) {
3949 /* remove the individual layouts */
3950 free(as->table[j]);
3952 free(as->table);
3953 /* Install final layout construction in the airport spec */
3954 as->table = tile_table;
3955 free(att);
3956 } catch (...) {
3957 for (int i = 0; i < as->num_table; i++) {
3958 free(tile_table[i]);
3960 free(tile_table);
3961 free(att);
3962 throw;
3964 break;
3967 case 0x0C:
3968 as->min_year = buf->ReadWord();
3969 as->max_year = buf->ReadWord();
3970 if (as->max_year == 0xFFFF) as->max_year = MAX_YEAR;
3971 break;
3973 case 0x0D:
3974 as->ttd_airport_type = (TTDPAirportType)buf->ReadByte();
3975 break;
3977 case 0x0E:
3978 as->catchment = Clamp(buf->ReadByte(), 1, MAX_CATCHMENT);
3979 break;
3981 case 0x0F:
3982 as->noise_level = buf->ReadByte();
3983 break;
3985 case 0x10:
3986 AddStringForMapping(buf->ReadWord(), &as->name);
3987 break;
3989 case 0x11: // Maintenance cost factor
3990 as->maintenance_cost = buf->ReadWord();
3991 break;
3993 default:
3994 ret = CIR_UNKNOWN;
3995 break;
3999 return ret;
4003 * Ignore properties for objects
4004 * @param prop The property to ignore.
4005 * @param buf The property value.
4006 * @return ChangeInfoResult.
4008 static ChangeInfoResult IgnoreObjectProperty(uint prop, ByteReader *buf)
4010 ChangeInfoResult ret = CIR_SUCCESS;
4012 switch (prop) {
4013 case 0x0B:
4014 case 0x0C:
4015 case 0x0D:
4016 case 0x12:
4017 case 0x14:
4018 case 0x16:
4019 case 0x17:
4020 buf->ReadByte();
4021 break;
4023 case 0x09:
4024 case 0x0A:
4025 case 0x10:
4026 case 0x11:
4027 case 0x13:
4028 case 0x15:
4029 buf->ReadWord();
4030 break;
4032 case 0x08:
4033 case 0x0E:
4034 case 0x0F:
4035 buf->ReadDWord();
4036 break;
4038 default:
4039 ret = CIR_UNKNOWN;
4040 break;
4043 return ret;
4047 * Define properties for objects
4048 * @param id Local ID of the object.
4049 * @param numinfo Number of subsequent objectIDs to change the property for.
4050 * @param prop The property to change.
4051 * @param buf The property value.
4052 * @return ChangeInfoResult.
4054 static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4056 ChangeInfoResult ret = CIR_SUCCESS;
4058 if (id + numinfo > NUM_OBJECTS_PER_GRF) {
4059 grfmsg(1, "ObjectChangeInfo: Too many objects loaded (%u), max (%u). Ignoring.", id + numinfo, NUM_OBJECTS_PER_GRF);
4060 return CIR_INVALID_ID;
4063 /* Allocate object specs if they haven't been allocated already. */
4064 if (_cur.grffile->objectspec == nullptr) {
4065 _cur.grffile->objectspec = CallocT<ObjectSpec*>(NUM_OBJECTS_PER_GRF);
4068 for (int i = 0; i < numinfo; i++) {
4069 ObjectSpec *spec = _cur.grffile->objectspec[id + i];
4071 if (prop != 0x08 && spec == nullptr) {
4072 /* If the object property 08 is not yet set, ignore this property */
4073 ChangeInfoResult cir = IgnoreObjectProperty(prop, buf);
4074 if (cir > ret) ret = cir;
4075 continue;
4078 switch (prop) {
4079 case 0x08: { // Class ID
4080 ObjectSpec **ospec = &_cur.grffile->objectspec[id + i];
4082 /* Allocate space for this object. */
4083 if (*ospec == nullptr) {
4084 *ospec = CallocT<ObjectSpec>(1);
4085 (*ospec)->views = 1; // Default for NewGRFs that don't set it.
4086 (*ospec)->size = OBJECT_SIZE_1X1; // Default for NewGRFs that manage to not set it (1x1)
4089 /* Swap classid because we read it in BE. */
4090 uint32 classid = buf->ReadDWord();
4091 (*ospec)->cls_id = ObjectClass::Allocate(BSWAP32(classid));
4092 (*ospec)->enabled = true;
4093 break;
4096 case 0x09: { // Class name
4097 ObjectClass *objclass = ObjectClass::Get(spec->cls_id);
4098 AddStringForMapping(buf->ReadWord(), &objclass->name);
4099 break;
4102 case 0x0A: // Object name
4103 AddStringForMapping(buf->ReadWord(), &spec->name);
4104 break;
4106 case 0x0B: // Climate mask
4107 spec->climate = buf->ReadByte();
4108 break;
4110 case 0x0C: // Size
4111 spec->size = buf->ReadByte();
4112 if (GB(spec->size, 0, 4) == 0 || GB(spec->size, 4, 4) == 0) {
4113 grfmsg(0, "ObjectChangeInfo: Invalid object size requested (0x%x) for object id %u. Ignoring.", spec->size, id + i);
4114 spec->size = OBJECT_SIZE_1X1;
4116 break;
4118 case 0x0D: // Build cost multipler
4119 spec->build_cost_multiplier = buf->ReadByte();
4120 spec->clear_cost_multiplier = spec->build_cost_multiplier;
4121 break;
4123 case 0x0E: // Introduction date
4124 spec->introduction_date = buf->ReadDWord();
4125 break;
4127 case 0x0F: // End of life
4128 spec->end_of_life_date = buf->ReadDWord();
4129 break;
4131 case 0x10: // Flags
4132 spec->flags = (ObjectFlags)buf->ReadWord();
4133 _loaded_newgrf_features.has_2CC |= (spec->flags & OBJECT_FLAG_2CC_COLOUR) != 0;
4134 break;
4136 case 0x11: // Animation info
4137 spec->animation.frames = buf->ReadByte();
4138 spec->animation.status = buf->ReadByte();
4139 break;
4141 case 0x12: // Animation speed
4142 spec->animation.speed = buf->ReadByte();
4143 break;
4145 case 0x13: // Animation triggers
4146 spec->animation.triggers = buf->ReadWord();
4147 break;
4149 case 0x14: // Removal cost multiplier
4150 spec->clear_cost_multiplier = buf->ReadByte();
4151 break;
4153 case 0x15: // Callback mask
4154 spec->callback_mask = buf->ReadWord();
4155 break;
4157 case 0x16: // Building height
4158 spec->height = buf->ReadByte();
4159 break;
4161 case 0x17: // Views
4162 spec->views = buf->ReadByte();
4163 if (spec->views != 1 && spec->views != 2 && spec->views != 4) {
4164 grfmsg(2, "ObjectChangeInfo: Invalid number of views (%u) for object id %u. Ignoring.", spec->views, id + i);
4165 spec->views = 1;
4167 break;
4169 case 0x18: // Amount placed on 256^2 map on map creation
4170 spec->generate_amount = buf->ReadByte();
4171 break;
4173 default:
4174 ret = CIR_UNKNOWN;
4175 break;
4179 return ret;
4183 * Define properties for railtypes
4184 * @param id ID of the railtype.
4185 * @param numinfo Number of subsequent IDs to change the property for.
4186 * @param prop The property to change.
4187 * @param buf The property value.
4188 * @return ChangeInfoResult.
4190 static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4192 ChangeInfoResult ret = CIR_SUCCESS;
4194 extern RailtypeInfo _railtypes[RAILTYPE_END];
4196 if (id + numinfo > RAILTYPE_END) {
4197 grfmsg(1, "RailTypeChangeInfo: Rail type %u is invalid, max %u, ignoring", id + numinfo, RAILTYPE_END);
4198 return CIR_INVALID_ID;
4201 for (int i = 0; i < numinfo; i++) {
4202 RailType rt = _cur.grffile->railtype_map[id + i];
4203 if (rt == INVALID_RAILTYPE) return CIR_INVALID_ID;
4205 RailtypeInfo *rti = &_railtypes[rt];
4207 switch (prop) {
4208 case 0x08: // Label of rail type
4209 /* Skipped here as this is loaded during reservation stage. */
4210 buf->ReadDWord();
4211 break;
4213 case 0x09: { // Toolbar caption of railtype (sets name as well for backwards compatibility for grf ver < 8)
4214 uint16 str = buf->ReadWord();
4215 AddStringForMapping(str, &rti->strings.toolbar_caption);
4216 if (_cur.grffile->grf_version < 8) {
4217 AddStringForMapping(str, &rti->strings.name);
4219 break;
4222 case 0x0A: // Menu text of railtype
4223 AddStringForMapping(buf->ReadWord(), &rti->strings.menu_text);
4224 break;
4226 case 0x0B: // Build window caption
4227 AddStringForMapping(buf->ReadWord(), &rti->strings.build_caption);
4228 break;
4230 case 0x0C: // Autoreplace text
4231 AddStringForMapping(buf->ReadWord(), &rti->strings.replace_text);
4232 break;
4234 case 0x0D: // New locomotive text
4235 AddStringForMapping(buf->ReadWord(), &rti->strings.new_loco);
4236 break;
4238 case 0x0E: // Compatible railtype list
4239 case 0x0F: // Powered railtype list
4240 case 0x18: // Railtype list required for date introduction
4241 case 0x19: // Introduced railtype list
4243 /* Rail type compatibility bits are added to the existing bits
4244 * to allow multiple GRFs to modify compatibility with the
4245 * default rail types. */
4246 int n = buf->ReadByte();
4247 for (int j = 0; j != n; j++) {
4248 RailTypeLabel label = buf->ReadDWord();
4249 RailType rt = GetRailTypeByLabel(BSWAP32(label), false);
4250 if (rt != INVALID_RAILTYPE) {
4251 switch (prop) {
4252 case 0x0F: SetBit(rti->powered_railtypes, rt); FALLTHROUGH; // Powered implies compatible.
4253 case 0x0E: SetBit(rti->compatible_railtypes, rt); break;
4254 case 0x18: SetBit(rti->introduction_required_railtypes, rt); break;
4255 case 0x19: SetBit(rti->introduces_railtypes, rt); break;
4259 break;
4262 case 0x10: // Rail Type flags
4263 rti->flags = (RailTypeFlags)buf->ReadByte();
4264 break;
4266 case 0x11: // Curve speed advantage
4267 rti->curve_speed = buf->ReadByte();
4268 break;
4270 case 0x12: // Station graphic
4271 rti->fallback_railtype = Clamp(buf->ReadByte(), 0, 2);
4272 break;
4274 case 0x13: // Construction cost factor
4275 rti->cost_multiplier = buf->ReadWord();
4276 break;
4278 case 0x14: // Speed limit
4279 rti->max_speed = buf->ReadWord();
4280 break;
4282 case 0x15: // Acceleration model
4283 rti->acceleration_type = Clamp(buf->ReadByte(), 0, 2);
4284 break;
4286 case 0x16: // Map colour
4287 rti->map_colour = buf->ReadByte();
4288 break;
4290 case 0x17: // Introduction date
4291 rti->introduction_date = buf->ReadDWord();
4292 break;
4294 case 0x1A: // Sort order
4295 rti->sorting_order = buf->ReadByte();
4296 break;
4298 case 0x1B: // Name of railtype (overridden by prop 09 for grf ver < 8)
4299 AddStringForMapping(buf->ReadWord(), &rti->strings.name);
4300 break;
4302 case 0x1C: // Maintenance cost factor
4303 rti->maintenance_multiplier = buf->ReadWord();
4304 break;
4306 case 0x1D: // Alternate rail type label list
4307 /* Skipped here as this is loaded during reservation stage. */
4308 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4309 break;
4311 default:
4312 ret = CIR_UNKNOWN;
4313 break;
4317 return ret;
4320 static ChangeInfoResult RailTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4322 ChangeInfoResult ret = CIR_SUCCESS;
4324 extern RailtypeInfo _railtypes[RAILTYPE_END];
4326 if (id + numinfo > RAILTYPE_END) {
4327 grfmsg(1, "RailTypeReserveInfo: Rail type %u is invalid, max %u, ignoring", id + numinfo, RAILTYPE_END);
4328 return CIR_INVALID_ID;
4331 for (int i = 0; i < numinfo; i++) {
4332 switch (prop) {
4333 case 0x08: // Label of rail type
4335 RailTypeLabel rtl = buf->ReadDWord();
4336 rtl = BSWAP32(rtl);
4338 RailType rt = GetRailTypeByLabel(rtl, false);
4339 if (rt == INVALID_RAILTYPE) {
4340 /* Set up new rail type */
4341 rt = AllocateRailType(rtl);
4344 _cur.grffile->railtype_map[id + i] = rt;
4345 break;
4348 case 0x09: // Toolbar caption of railtype
4349 case 0x0A: // Menu text
4350 case 0x0B: // Build window caption
4351 case 0x0C: // Autoreplace text
4352 case 0x0D: // New loco
4353 case 0x13: // Construction cost
4354 case 0x14: // Speed limit
4355 case 0x1B: // Name of railtype
4356 case 0x1C: // Maintenance cost factor
4357 buf->ReadWord();
4358 break;
4360 case 0x1D: // Alternate rail type label list
4361 if (_cur.grffile->railtype_map[id + i] != INVALID_RAILTYPE) {
4362 int n = buf->ReadByte();
4363 for (int j = 0; j != n; j++) {
4364 _railtypes[_cur.grffile->railtype_map[id + i]].alternate_labels.push_back(BSWAP32(buf->ReadDWord()));
4366 break;
4368 grfmsg(1, "RailTypeReserveInfo: Ignoring property 1D for rail type %u because no label was set", id + i);
4369 FALLTHROUGH;
4371 case 0x0E: // Compatible railtype list
4372 case 0x0F: // Powered railtype list
4373 case 0x18: // Railtype list required for date introduction
4374 case 0x19: // Introduced railtype list
4375 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4376 break;
4378 case 0x10: // Rail Type flags
4379 case 0x11: // Curve speed advantage
4380 case 0x12: // Station graphic
4381 case 0x15: // Acceleration model
4382 case 0x16: // Map colour
4383 case 0x1A: // Sort order
4384 buf->ReadByte();
4385 break;
4387 case 0x17: // Introduction date
4388 buf->ReadDWord();
4389 break;
4391 default:
4392 ret = CIR_UNKNOWN;
4393 break;
4397 return ret;
4401 * Define properties for roadtypes
4402 * @param id ID of the roadtype.
4403 * @param numinfo Number of subsequent IDs to change the property for.
4404 * @param prop The property to change.
4405 * @param buf The property value.
4406 * @return ChangeInfoResult.
4408 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
4410 ChangeInfoResult ret = CIR_SUCCESS;
4412 extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4413 RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4415 if (id + numinfo > ROADTYPE_END) {
4416 grfmsg(1, "RoadTypeChangeInfo: Road type %u is invalid, max %u, ignoring", id + numinfo, ROADTYPE_END);
4417 return CIR_INVALID_ID;
4420 for (int i = 0; i < numinfo; i++) {
4421 RoadType rt = type_map[id + i];
4422 if (rt == INVALID_ROADTYPE) return CIR_INVALID_ID;
4424 RoadTypeInfo *rti = &_roadtypes[rt];
4426 switch (prop) {
4427 case 0x08: // Label of road type
4428 /* Skipped here as this is loaded during reservation stage. */
4429 buf->ReadDWord();
4430 break;
4432 case 0x09: { // Toolbar caption of roadtype (sets name as well for backwards compatibility for grf ver < 8)
4433 uint16 str = buf->ReadWord();
4434 AddStringForMapping(str, &rti->strings.toolbar_caption);
4435 break;
4438 case 0x0A: // Menu text of roadtype
4439 AddStringForMapping(buf->ReadWord(), &rti->strings.menu_text);
4440 break;
4442 case 0x0B: // Build window caption
4443 AddStringForMapping(buf->ReadWord(), &rti->strings.build_caption);
4444 break;
4446 case 0x0C: // Autoreplace text
4447 AddStringForMapping(buf->ReadWord(), &rti->strings.replace_text);
4448 break;
4450 case 0x0D: // New engine text
4451 AddStringForMapping(buf->ReadWord(), &rti->strings.new_engine);
4452 break;
4454 case 0x0F: // Powered roadtype list
4455 case 0x18: // Roadtype list required for date introduction
4456 case 0x19: { // Introduced roadtype list
4457 /* Road type compatibility bits are added to the existing bits
4458 * to allow multiple GRFs to modify compatibility with the
4459 * default road types. */
4460 int n = buf->ReadByte();
4461 for (int j = 0; j != n; j++) {
4462 RoadTypeLabel label = buf->ReadDWord();
4463 RoadType rt = GetRoadTypeByLabel(BSWAP32(label), false);
4464 if (rt != INVALID_ROADTYPE) {
4465 switch (prop) {
4466 case 0x0F: SetBit(rti->powered_roadtypes, rt); break;
4467 case 0x18: SetBit(rti->introduction_required_roadtypes, rt); break;
4468 case 0x19: SetBit(rti->introduces_roadtypes, rt); break;
4472 break;
4475 case 0x10: // Road Type flags
4476 rti->flags = (RoadTypeFlags)buf->ReadByte();
4477 break;
4479 case 0x13: // Construction cost factor
4480 rti->cost_multiplier = buf->ReadWord();
4481 break;
4483 case 0x14: // Speed limit
4484 rti->max_speed = buf->ReadWord();
4485 break;
4487 case 0x16: // Map colour
4488 rti->map_colour = buf->ReadByte();
4489 break;
4491 case 0x17: // Introduction date
4492 rti->introduction_date = buf->ReadDWord();
4493 break;
4495 case 0x1A: // Sort order
4496 rti->sorting_order = buf->ReadByte();
4497 break;
4499 case 0x1B: // Name of roadtype
4500 AddStringForMapping(buf->ReadWord(), &rti->strings.name);
4501 break;
4503 case 0x1C: // Maintenance cost factor
4504 rti->maintenance_multiplier = buf->ReadWord();
4505 break;
4507 case 0x1D: // Alternate road type label list
4508 /* Skipped here as this is loaded during reservation stage. */
4509 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4510 break;
4512 default:
4513 ret = CIR_UNKNOWN;
4514 break;
4518 return ret;
4521 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4523 return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_ROAD);
4526 static ChangeInfoResult TramTypeChangeInfo(uint id, int numinfo, int prop, ByteReader *buf)
4528 return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_TRAM);
4532 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf, RoadTramType rtt)
4534 ChangeInfoResult ret = CIR_SUCCESS;
4536 extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4537 RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4539 if (id + numinfo > ROADTYPE_END) {
4540 grfmsg(1, "RoadTypeReserveInfo: Road type %u is invalid, max %u, ignoring", id + numinfo, ROADTYPE_END);
4541 return CIR_INVALID_ID;
4544 for (int i = 0; i < numinfo; i++) {
4545 switch (prop) {
4546 case 0x08: { // Label of road type
4547 RoadTypeLabel rtl = buf->ReadDWord();
4548 rtl = BSWAP32(rtl);
4550 RoadType rt = GetRoadTypeByLabel(rtl, false);
4551 if (rt == INVALID_ROADTYPE) {
4552 /* Set up new road type */
4553 rt = AllocateRoadType(rtl, rtt);
4554 } else if (GetRoadTramType(rt) != rtt) {
4555 grfmsg(1, "RoadTypeReserveInfo: Road type %u is invalid type (road/tram), ignoring", id + numinfo);
4556 return CIR_INVALID_ID;
4559 type_map[id + i] = rt;
4560 break;
4562 case 0x09: // Toolbar caption of roadtype
4563 case 0x0A: // Menu text
4564 case 0x0B: // Build window caption
4565 case 0x0C: // Autoreplace text
4566 case 0x0D: // New loco
4567 case 0x13: // Construction cost
4568 case 0x14: // Speed limit
4569 case 0x1B: // Name of roadtype
4570 case 0x1C: // Maintenance cost factor
4571 buf->ReadWord();
4572 break;
4574 case 0x1D: // Alternate road type label list
4575 if (type_map[id + i] != INVALID_ROADTYPE) {
4576 int n = buf->ReadByte();
4577 for (int j = 0; j != n; j++) {
4578 _roadtypes[type_map[id + i]].alternate_labels.push_back(BSWAP32(buf->ReadDWord()));
4580 break;
4582 grfmsg(1, "RoadTypeReserveInfo: Ignoring property 1D for road type %u because no label was set", id + i);
4583 /* FALL THROUGH */
4585 case 0x0F: // Powered roadtype list
4586 case 0x18: // Roadtype list required for date introduction
4587 case 0x19: // Introduced roadtype list
4588 for (int j = buf->ReadByte(); j != 0; j--) buf->ReadDWord();
4589 break;
4591 case 0x10: // Road Type flags
4592 case 0x16: // Map colour
4593 case 0x1A: // Sort order
4594 buf->ReadByte();
4595 break;
4597 case 0x17: // Introduction date
4598 buf->ReadDWord();
4599 break;
4601 default:
4602 ret = CIR_UNKNOWN;
4603 break;
4607 return ret;
4610 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4612 return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_ROAD);
4615 static ChangeInfoResult TramTypeReserveInfo(uint id, int numinfo, int prop, ByteReader *buf)
4617 return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_TRAM);
4620 static ChangeInfoResult AirportTilesChangeInfo(uint airtid, int numinfo, int prop, ByteReader *buf)
4622 ChangeInfoResult ret = CIR_SUCCESS;
4624 if (airtid + numinfo > NUM_AIRPORTTILES_PER_GRF) {
4625 grfmsg(1, "AirportTileChangeInfo: Too many airport tiles loaded (%u), max (%u). Ignoring.", airtid + numinfo, NUM_AIRPORTTILES_PER_GRF);
4626 return CIR_INVALID_ID;
4629 /* Allocate airport tile specs if they haven't been allocated already. */
4630 if (_cur.grffile->airtspec == nullptr) {
4631 _cur.grffile->airtspec = CallocT<AirportTileSpec*>(NUM_AIRPORTTILES_PER_GRF);
4634 for (int i = 0; i < numinfo; i++) {
4635 AirportTileSpec *tsp = _cur.grffile->airtspec[airtid + i];
4637 if (prop != 0x08 && tsp == nullptr) {
4638 grfmsg(2, "AirportTileChangeInfo: Attempt to modify undefined airport tile %u. Ignoring.", airtid + i);
4639 return CIR_INVALID_ID;
4642 switch (prop) {
4643 case 0x08: { // Substitute airport tile type
4644 AirportTileSpec **tilespec = &_cur.grffile->airtspec[airtid + i];
4645 byte subs_id = buf->ReadByte();
4647 if (subs_id >= NEW_AIRPORTTILE_OFFSET) {
4648 /* The substitute id must be one of the original airport tiles. */
4649 grfmsg(2, "AirportTileChangeInfo: Attempt to use new airport tile %u as substitute airport tile for %u. Ignoring.", subs_id, airtid + i);
4650 continue;
4653 /* Allocate space for this airport tile. */
4654 if (*tilespec == nullptr) {
4655 *tilespec = CallocT<AirportTileSpec>(1);
4656 tsp = *tilespec;
4658 memcpy(tsp, AirportTileSpec::Get(subs_id), sizeof(AirportTileSpec));
4659 tsp->enabled = true;
4661 tsp->animation.status = ANIM_STATUS_NO_ANIMATION;
4663 tsp->grf_prop.local_id = airtid + i;
4664 tsp->grf_prop.subst_id = subs_id;
4665 tsp->grf_prop.grffile = _cur.grffile;
4666 _airporttile_mngr.AddEntityID(airtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
4668 break;
4671 case 0x09: { // Airport tile override
4672 byte override = buf->ReadByte();
4674 /* The airport tile being overridden must be an original airport tile. */
4675 if (override >= NEW_AIRPORTTILE_OFFSET) {
4676 grfmsg(2, "AirportTileChangeInfo: Attempt to override new airport tile %u with airport tile id %u. Ignoring.", override, airtid + i);
4677 continue;
4680 _airporttile_mngr.Add(airtid + i, _cur.grffile->grfid, override);
4681 break;
4684 case 0x0E: // Callback mask
4685 tsp->callback_mask = buf->ReadByte();
4686 break;
4688 case 0x0F: // Animation information
4689 tsp->animation.frames = buf->ReadByte();
4690 tsp->animation.status = buf->ReadByte();
4691 break;
4693 case 0x10: // Animation speed
4694 tsp->animation.speed = buf->ReadByte();
4695 break;
4697 case 0x11: // Animation triggers
4698 tsp->animation.triggers = buf->ReadByte();
4699 break;
4701 default:
4702 ret = CIR_UNKNOWN;
4703 break;
4707 return ret;
4710 static bool HandleChangeInfoResult(const char *caller, ChangeInfoResult cir, uint8 feature, uint8 property)
4712 switch (cir) {
4713 default: NOT_REACHED();
4715 case CIR_DISABLED:
4716 /* Error has already been printed; just stop parsing */
4717 return true;
4719 case CIR_SUCCESS:
4720 return false;
4722 case CIR_UNHANDLED:
4723 grfmsg(1, "%s: Ignoring property 0x%02X of feature 0x%02X (not implemented)", caller, property, feature);
4724 return false;
4726 case CIR_UNKNOWN:
4727 grfmsg(0, "%s: Unknown property 0x%02X of feature 0x%02X, disabling", caller, property, feature);
4728 FALLTHROUGH;
4730 case CIR_INVALID_ID: {
4731 /* No debug message for an invalid ID, as it has already been output */
4732 GRFError *error = DisableGrf(cir == CIR_INVALID_ID ? STR_NEWGRF_ERROR_INVALID_ID : STR_NEWGRF_ERROR_UNKNOWN_PROPERTY);
4733 if (cir != CIR_INVALID_ID) error->param_value[1] = property;
4734 return true;
4739 /* Action 0x00 */
4740 static void FeatureChangeInfo(ByteReader *buf)
4742 /* <00> <feature> <num-props> <num-info> <id> (<property <new-info>)...
4744 * B feature
4745 * B num-props how many properties to change per vehicle/station
4746 * B num-info how many vehicles/stations to change
4747 * E id ID of first vehicle/station to change, if num-info is
4748 * greater than one, this one and the following
4749 * vehicles/stations will be changed
4750 * B property what property to change, depends on the feature
4751 * V new-info new bytes of info (variable size; depends on properties) */
4753 static const VCI_Handler handler[] = {
4754 /* GSF_TRAINS */ RailVehicleChangeInfo,
4755 /* GSF_ROADVEHICLES */ RoadVehicleChangeInfo,
4756 /* GSF_SHIPS */ ShipVehicleChangeInfo,
4757 /* GSF_AIRCRAFT */ AircraftVehicleChangeInfo,
4758 /* GSF_STATIONS */ StationChangeInfo,
4759 /* GSF_CANALS */ CanalChangeInfo,
4760 /* GSF_BRIDGES */ BridgeChangeInfo,
4761 /* GSF_HOUSES */ TownHouseChangeInfo,
4762 /* GSF_GLOBALVAR */ GlobalVarChangeInfo,
4763 /* GSF_INDUSTRYTILES */ IndustrytilesChangeInfo,
4764 /* GSF_INDUSTRIES */ IndustriesChangeInfo,
4765 /* GSF_CARGOES */ nullptr, // Cargo is handled during reservation
4766 /* GSF_SOUNDFX */ SoundEffectChangeInfo,
4767 /* GSF_AIRPORTS */ AirportChangeInfo,
4768 /* GSF_SIGNALS */ nullptr,
4769 /* GSF_OBJECTS */ ObjectChangeInfo,
4770 /* GSF_RAILTYPES */ RailTypeChangeInfo,
4771 /* GSF_AIRPORTTILES */ AirportTilesChangeInfo,
4772 /* GSF_ROADTYPES */ RoadTypeChangeInfo,
4773 /* GSF_TRAMTYPES */ TramTypeChangeInfo,
4775 static_assert(GSF_END == lengthof(handler));
4777 uint8 feature = buf->ReadByte();
4778 uint8 numprops = buf->ReadByte();
4779 uint numinfo = buf->ReadByte();
4780 uint engine = buf->ReadExtendedByte();
4782 if (feature >= GSF_END) {
4783 grfmsg(1, "FeatureChangeInfo: Unsupported feature 0x%02X, skipping", feature);
4784 return;
4787 grfmsg(6, "FeatureChangeInfo: Feature 0x%02X, %d properties, to apply to %d+%d",
4788 feature, numprops, engine, numinfo);
4790 if (handler[feature] == nullptr) {
4791 if (feature != GSF_CARGOES) grfmsg(1, "FeatureChangeInfo: Unsupported feature 0x%02X, skipping", feature);
4792 return;
4795 /* Mark the feature as used by the grf */
4796 SetBit(_cur.grffile->grf_features, feature);
4798 while (numprops-- && buf->HasData()) {
4799 uint8 prop = buf->ReadByte();
4801 ChangeInfoResult cir = handler[feature](engine, numinfo, prop, buf);
4802 if (HandleChangeInfoResult("FeatureChangeInfo", cir, feature, prop)) return;
4806 /* Action 0x00 (GLS_SAFETYSCAN) */
4807 static void SafeChangeInfo(ByteReader *buf)
4809 uint8 feature = buf->ReadByte();
4810 uint8 numprops = buf->ReadByte();
4811 uint numinfo = buf->ReadByte();
4812 buf->ReadExtendedByte(); // id
4814 if (feature == GSF_BRIDGES && numprops == 1) {
4815 uint8 prop = buf->ReadByte();
4816 /* Bridge property 0x0D is redefinition of sprite layout tables, which
4817 * is considered safe. */
4818 if (prop == 0x0D) return;
4819 } else if (feature == GSF_GLOBALVAR && numprops == 1) {
4820 uint8 prop = buf->ReadByte();
4821 /* Engine ID Mappings are safe, if the source is static */
4822 if (prop == 0x11) {
4823 bool is_safe = true;
4824 for (uint i = 0; i < numinfo; i++) {
4825 uint32 s = buf->ReadDWord();
4826 buf->ReadDWord(); // dest
4827 const GRFConfig *grfconfig = GetGRFConfig(s);
4828 if (grfconfig != nullptr && !HasBit(grfconfig->flags, GCF_STATIC)) {
4829 is_safe = false;
4830 break;
4833 if (is_safe) return;
4837 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
4839 /* Skip remainder of GRF */
4840 _cur.skip_sprites = -1;
4843 /* Action 0x00 (GLS_RESERVE) */
4844 static void ReserveChangeInfo(ByteReader *buf)
4846 uint8 feature = buf->ReadByte();
4848 if (feature != GSF_CARGOES && feature != GSF_GLOBALVAR && feature != GSF_RAILTYPES && feature != GSF_ROADTYPES && feature != GSF_TRAMTYPES) return;
4850 uint8 numprops = buf->ReadByte();
4851 uint8 numinfo = buf->ReadByte();
4852 uint8 index = buf->ReadExtendedByte();
4854 while (numprops-- && buf->HasData()) {
4855 uint8 prop = buf->ReadByte();
4856 ChangeInfoResult cir = CIR_SUCCESS;
4858 switch (feature) {
4859 default: NOT_REACHED();
4860 case GSF_CARGOES:
4861 cir = CargoChangeInfo(index, numinfo, prop, buf);
4862 break;
4864 case GSF_GLOBALVAR:
4865 cir = GlobalVarReserveInfo(index, numinfo, prop, buf);
4866 break;
4868 case GSF_RAILTYPES:
4869 cir = RailTypeReserveInfo(index, numinfo, prop, buf);
4870 break;
4872 case GSF_ROADTYPES:
4873 cir = RoadTypeReserveInfo(index, numinfo, prop, buf);
4874 break;
4876 case GSF_TRAMTYPES:
4877 cir = TramTypeReserveInfo(index, numinfo, prop, buf);
4878 break;
4881 if (HandleChangeInfoResult("ReserveChangeInfo", cir, feature, prop)) return;
4885 /* Action 0x01 */
4886 static void NewSpriteSet(ByteReader *buf)
4888 /* Basic format: <01> <feature> <num-sets> <num-ent>
4889 * Extended format: <01> <feature> 00 <first-set> <num-sets> <num-ent>
4891 * B feature feature to define sprites for
4892 * 0, 1, 2, 3: veh-type, 4: train stations
4893 * E first-set first sprite set to define
4894 * B num-sets number of sprite sets (extended byte in extended format)
4895 * E num-ent how many entries per sprite set
4896 * For vehicles, this is the number of different
4897 * vehicle directions in each sprite set
4898 * Set num-dirs=8, unless your sprites are symmetric.
4899 * In that case, use num-dirs=4.
4902 uint8 feature = buf->ReadByte();
4903 uint16 num_sets = buf->ReadByte();
4904 uint16 first_set = 0;
4906 if (num_sets == 0 && buf->HasData(3)) {
4907 /* Extended Action1 format.
4908 * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
4909 first_set = buf->ReadExtendedByte();
4910 num_sets = buf->ReadExtendedByte();
4912 uint16 num_ents = buf->ReadExtendedByte();
4914 if (feature >= GSF_END) {
4915 _cur.skip_sprites = num_sets * num_ents;
4916 grfmsg(1, "NewSpriteSet: Unsupported feature 0x%02X, skipping %d sprites", feature, _cur.skip_sprites);
4917 return;
4920 _cur.AddSpriteSets(feature, _cur.spriteid, first_set, num_sets, num_ents);
4922 grfmsg(7, "New sprite set at %d of feature 0x%02X, consisting of %d sets with %d views each (total %d)",
4923 _cur.spriteid, feature, num_sets, num_ents, num_sets * num_ents
4926 for (int i = 0; i < num_sets * num_ents; i++) {
4927 _cur.nfo_line++;
4928 LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
4932 /* Action 0x01 (SKIP) */
4933 static void SkipAct1(ByteReader *buf)
4935 buf->ReadByte();
4936 uint16 num_sets = buf->ReadByte();
4938 if (num_sets == 0 && buf->HasData(3)) {
4939 /* Extended Action1 format.
4940 * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
4941 buf->ReadExtendedByte(); // first_set
4942 num_sets = buf->ReadExtendedByte();
4944 uint16 num_ents = buf->ReadExtendedByte();
4946 _cur.skip_sprites = num_sets * num_ents;
4948 grfmsg(3, "SkipAct1: Skipping %d sprites", _cur.skip_sprites);
4951 /* Helper function to either create a callback or link to a previously
4952 * defined spritegroup. */
4953 static const SpriteGroup *GetGroupFromGroupID(byte setid, byte type, uint16 groupid)
4955 if (HasBit(groupid, 15)) {
4956 assert(CallbackResultSpriteGroup::CanAllocateItem());
4957 return new CallbackResultSpriteGroup(groupid, _cur.grffile->grf_version >= 8);
4960 if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
4961 grfmsg(1, "GetGroupFromGroupID(0x%02X:0x%02X): Groupid 0x%04X does not exist, leaving empty", setid, type, groupid);
4962 return nullptr;
4965 return _cur.spritegroups[groupid];
4969 * Helper function to either create a callback or a result sprite group.
4970 * @param feature GrfSpecFeature to define spritegroup for.
4971 * @param setid SetID of the currently being parsed Action2. (only for debug output)
4972 * @param type Type of the currently being parsed Action2. (only for debug output)
4973 * @param spriteid Raw value from the GRF for the new spritegroup; describes either the return value or the referenced spritegroup.
4974 * @return Created spritegroup.
4976 static const SpriteGroup *CreateGroupFromGroupID(byte feature, byte setid, byte type, uint16 spriteid)
4978 if (HasBit(spriteid, 15)) {
4979 assert(CallbackResultSpriteGroup::CanAllocateItem());
4980 return new CallbackResultSpriteGroup(spriteid, _cur.grffile->grf_version >= 8);
4983 if (!_cur.IsValidSpriteSet(feature, spriteid)) {
4984 grfmsg(1, "CreateGroupFromGroupID(0x%02X:0x%02X): Sprite set %u invalid", setid, type, spriteid);
4985 return nullptr;
4988 SpriteID spriteset_start = _cur.GetSprite(feature, spriteid);
4989 uint num_sprites = _cur.GetNumEnts(feature, spriteid);
4991 /* Ensure that the sprites are loeded */
4992 assert(spriteset_start + num_sprites <= _cur.spriteid);
4994 assert(ResultSpriteGroup::CanAllocateItem());
4995 return new ResultSpriteGroup(spriteset_start, num_sprites);
4998 /* Action 0x02 */
4999 static void NewSpriteGroup(ByteReader *buf)
5001 /* <02> <feature> <set-id> <type/num-entries> <feature-specific-data...>
5003 * B feature see action 1
5004 * B set-id ID of this particular definition
5005 * B type/num-entries
5006 * if 80 or greater, this is a randomized or variational
5007 * list definition, see below
5008 * otherwise it specifies a number of entries, the exact
5009 * meaning depends on the feature
5010 * V feature-specific-data (huge mess, don't even look it up --pasky) */
5011 const SpriteGroup *act_group = nullptr;
5013 uint8 feature = buf->ReadByte();
5014 if (feature >= GSF_END) {
5015 grfmsg(1, "NewSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5016 return;
5019 uint8 setid = buf->ReadByte();
5020 uint8 type = buf->ReadByte();
5022 /* Sprite Groups are created here but they are allocated from a pool, so
5023 * we do not need to delete anything if there is an exception from the
5024 * ByteReader. */
5026 switch (type) {
5027 /* Deterministic Sprite Group */
5028 case 0x81: // Self scope, byte
5029 case 0x82: // Parent scope, byte
5030 case 0x85: // Self scope, word
5031 case 0x86: // Parent scope, word
5032 case 0x89: // Self scope, dword
5033 case 0x8A: // Parent scope, dword
5035 byte varadjust;
5036 byte varsize;
5038 assert(DeterministicSpriteGroup::CanAllocateItem());
5039 DeterministicSpriteGroup *group = new DeterministicSpriteGroup();
5040 group->nfo_line = _cur.nfo_line;
5041 act_group = group;
5042 group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5044 switch (GB(type, 2, 2)) {
5045 default: NOT_REACHED();
5046 case 0: group->size = DSG_SIZE_BYTE; varsize = 1; break;
5047 case 1: group->size = DSG_SIZE_WORD; varsize = 2; break;
5048 case 2: group->size = DSG_SIZE_DWORD; varsize = 4; break;
5051 /* Loop through the var adjusts. Unfortunately we don't know how many we have
5052 * from the outset, so we shall have to keep reallocing. */
5053 do {
5054 DeterministicSpriteGroupAdjust &adjust = group->adjusts.emplace_back();
5056 /* The first var adjust doesn't have an operation specified, so we set it to add. */
5057 adjust.operation = group->adjusts.size() == 1 ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)buf->ReadByte();
5058 adjust.variable = buf->ReadByte();
5059 if (adjust.variable == 0x7E) {
5060 /* Link subroutine group */
5061 adjust.subroutine = GetGroupFromGroupID(setid, type, buf->ReadByte());
5062 } else {
5063 adjust.parameter = IsInsideMM(adjust.variable, 0x60, 0x80) ? buf->ReadByte() : 0;
5066 varadjust = buf->ReadByte();
5067 adjust.shift_num = GB(varadjust, 0, 5);
5068 adjust.type = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2);
5069 adjust.and_mask = buf->ReadVarSize(varsize);
5071 if (adjust.type != DSGA_TYPE_NONE) {
5072 adjust.add_val = buf->ReadVarSize(varsize);
5073 adjust.divmod_val = buf->ReadVarSize(varsize);
5074 } else {
5075 adjust.add_val = 0;
5076 adjust.divmod_val = 0;
5079 /* Continue reading var adjusts while bit 5 is set. */
5080 } while (HasBit(varadjust, 5));
5082 std::vector<DeterministicSpriteGroupRange> ranges;
5083 ranges.resize(buf->ReadByte());
5084 for (uint i = 0; i < ranges.size(); i++) {
5085 ranges[i].group = GetGroupFromGroupID(setid, type, buf->ReadWord());
5086 ranges[i].low = buf->ReadVarSize(varsize);
5087 ranges[i].high = buf->ReadVarSize(varsize);
5090 group->default_group = GetGroupFromGroupID(setid, type, buf->ReadWord());
5091 group->error_group = ranges.size() > 0 ? ranges[0].group : group->default_group;
5092 /* nvar == 0 is a special case -- we turn our value into a callback result */
5093 group->calculated_result = ranges.size() == 0;
5095 /* Sort ranges ascending. When ranges overlap, this may required clamping or splitting them */
5096 std::vector<uint32> bounds;
5097 for (uint i = 0; i < ranges.size(); i++) {
5098 bounds.push_back(ranges[i].low);
5099 if (ranges[i].high != UINT32_MAX) bounds.push_back(ranges[i].high + 1);
5101 std::sort(bounds.begin(), bounds.end());
5102 bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
5104 std::vector<const SpriteGroup *> target;
5105 for (uint j = 0; j < bounds.size(); ++j) {
5106 uint32 v = bounds[j];
5107 const SpriteGroup *t = group->default_group;
5108 for (uint i = 0; i < ranges.size(); i++) {
5109 if (ranges[i].low <= v && v <= ranges[i].high) {
5110 t = ranges[i].group;
5111 break;
5114 target.push_back(t);
5116 assert(target.size() == bounds.size());
5118 for (uint j = 0; j < bounds.size(); ) {
5119 if (target[j] != group->default_group) {
5120 DeterministicSpriteGroupRange &r = group->ranges.emplace_back();
5121 r.group = target[j];
5122 r.low = bounds[j];
5123 while (j < bounds.size() && target[j] == r.group) {
5124 j++;
5126 r.high = j < bounds.size() ? bounds[j] - 1 : UINT32_MAX;
5127 } else {
5128 j++;
5132 break;
5135 /* Randomized Sprite Group */
5136 case 0x80: // Self scope
5137 case 0x83: // Parent scope
5138 case 0x84: // Relative scope
5140 assert(RandomizedSpriteGroup::CanAllocateItem());
5141 RandomizedSpriteGroup *group = new RandomizedSpriteGroup();
5142 group->nfo_line = _cur.nfo_line;
5143 act_group = group;
5144 group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5146 if (HasBit(type, 2)) {
5147 if (feature <= GSF_AIRCRAFT) group->var_scope = VSG_SCOPE_RELATIVE;
5148 group->count = buf->ReadByte();
5151 uint8 triggers = buf->ReadByte();
5152 group->triggers = GB(triggers, 0, 7);
5153 group->cmp_mode = HasBit(triggers, 7) ? RSG_CMP_ALL : RSG_CMP_ANY;
5154 group->lowest_randbit = buf->ReadByte();
5156 byte num_groups = buf->ReadByte();
5157 if (!HasExactlyOneBit(num_groups)) {
5158 grfmsg(1, "NewSpriteGroup: Random Action 2 nrand should be power of 2");
5161 for (uint i = 0; i < num_groups; i++) {
5162 group->groups.push_back(GetGroupFromGroupID(setid, type, buf->ReadWord()));
5165 break;
5168 /* Neither a variable or randomized sprite group... must be a real group */
5169 default:
5171 switch (feature) {
5172 case GSF_TRAINS:
5173 case GSF_ROADVEHICLES:
5174 case GSF_SHIPS:
5175 case GSF_AIRCRAFT:
5176 case GSF_STATIONS:
5177 case GSF_CANALS:
5178 case GSF_CARGOES:
5179 case GSF_AIRPORTS:
5180 case GSF_RAILTYPES:
5181 case GSF_ROADTYPES:
5182 case GSF_TRAMTYPES:
5184 byte num_loaded = type;
5185 byte num_loading = buf->ReadByte();
5187 if (!_cur.HasValidSpriteSets(feature)) {
5188 grfmsg(0, "NewSpriteGroup: No sprite set to work on! Skipping");
5189 return;
5192 grfmsg(6, "NewSpriteGroup: New SpriteGroup 0x%02X, %u loaded, %u loading",
5193 setid, num_loaded, num_loading);
5195 if (num_loaded + num_loading == 0) {
5196 grfmsg(1, "NewSpriteGroup: no result, skipping invalid RealSpriteGroup");
5197 break;
5200 if (num_loaded + num_loading == 1) {
5201 /* Avoid creating 'Real' sprite group if only one option. */
5202 uint16 spriteid = buf->ReadWord();
5203 act_group = CreateGroupFromGroupID(feature, setid, type, spriteid);
5204 grfmsg(8, "NewSpriteGroup: one result, skipping RealSpriteGroup = subset %u", spriteid);
5205 break;
5208 std::vector<uint16> loaded;
5209 std::vector<uint16> loading;
5211 for (uint i = 0; i < num_loaded; i++) {
5212 loaded.push_back(buf->ReadWord());
5213 grfmsg(8, "NewSpriteGroup: + rg->loaded[%i] = subset %u", i, loaded[i]);
5216 for (uint i = 0; i < num_loading; i++) {
5217 loading.push_back(buf->ReadWord());
5218 grfmsg(8, "NewSpriteGroup: + rg->loading[%i] = subset %u", i, loading[i]);
5221 if (std::adjacent_find(loaded.begin(), loaded.end(), std::not_equal_to<>()) == loaded.end() &&
5222 std::adjacent_find(loading.begin(), loading.end(), std::not_equal_to<>()) == loading.end() &&
5223 loaded[0] == loading[0])
5225 /* Both lists only contain the same value, so don't create 'Real' sprite group */
5226 act_group = CreateGroupFromGroupID(feature, setid, type, loaded[0]);
5227 grfmsg(8, "NewSpriteGroup: same result, skipping RealSpriteGroup = subset %u", loaded[0]);
5228 break;
5231 assert(RealSpriteGroup::CanAllocateItem());
5232 RealSpriteGroup *group = new RealSpriteGroup();
5233 group->nfo_line = _cur.nfo_line;
5234 act_group = group;
5236 for (uint16 spriteid : loaded) {
5237 const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5238 group->loaded.push_back(t);
5241 for (uint16 spriteid : loading) {
5242 const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5243 group->loading.push_back(t);
5246 break;
5249 case GSF_HOUSES:
5250 case GSF_AIRPORTTILES:
5251 case GSF_OBJECTS:
5252 case GSF_INDUSTRYTILES: {
5253 byte num_building_sprites = std::max((uint8)1, type);
5255 assert(TileLayoutSpriteGroup::CanAllocateItem());
5256 TileLayoutSpriteGroup *group = new TileLayoutSpriteGroup();
5257 group->nfo_line = _cur.nfo_line;
5258 act_group = group;
5260 /* On error, bail out immediately. Temporary GRF data was already freed */
5261 if (ReadSpriteLayout(buf, num_building_sprites, true, feature, false, type == 0, &group->dts)) return;
5262 break;
5265 case GSF_INDUSTRIES: {
5266 if (type > 2) {
5267 grfmsg(1, "NewSpriteGroup: Unsupported industry production version %d, skipping", type);
5268 break;
5271 assert(IndustryProductionSpriteGroup::CanAllocateItem());
5272 IndustryProductionSpriteGroup *group = new IndustryProductionSpriteGroup();
5273 group->nfo_line = _cur.nfo_line;
5274 act_group = group;
5275 group->version = type;
5276 if (type == 0) {
5277 group->num_input = 3;
5278 for (uint i = 0; i < 3; i++) {
5279 group->subtract_input[i] = (int16)buf->ReadWord(); // signed
5281 group->num_output = 2;
5282 for (uint i = 0; i < 2; i++) {
5283 group->add_output[i] = buf->ReadWord(); // unsigned
5285 group->again = buf->ReadByte();
5286 } else if (type == 1) {
5287 group->num_input = 3;
5288 for (uint i = 0; i < 3; i++) {
5289 group->subtract_input[i] = buf->ReadByte();
5291 group->num_output = 2;
5292 for (uint i = 0; i < 2; i++) {
5293 group->add_output[i] = buf->ReadByte();
5295 group->again = buf->ReadByte();
5296 } else if (type == 2) {
5297 group->num_input = buf->ReadByte();
5298 if (group->num_input > lengthof(group->subtract_input)) {
5299 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5300 error->data = "too many inputs (max 16)";
5301 return;
5303 for (uint i = 0; i < group->num_input; i++) {
5304 byte rawcargo = buf->ReadByte();
5305 CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5306 if (cargo == CT_INVALID) {
5307 /* The mapped cargo is invalid. This is permitted at this point,
5308 * as long as the result is not used. Mark it invalid so this
5309 * can be tested later. */
5310 group->version = 0xFF;
5311 } else if (std::find(group->cargo_input, group->cargo_input + i, cargo) != group->cargo_input + i) {
5312 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5313 error->data = "duplicate input cargo";
5314 return;
5316 group->cargo_input[i] = cargo;
5317 group->subtract_input[i] = buf->ReadByte();
5319 group->num_output = buf->ReadByte();
5320 if (group->num_output > lengthof(group->add_output)) {
5321 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5322 error->data = "too many outputs (max 16)";
5323 return;
5325 for (uint i = 0; i < group->num_output; i++) {
5326 byte rawcargo = buf->ReadByte();
5327 CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5328 if (cargo == CT_INVALID) {
5329 /* Mark this result as invalid to use */
5330 group->version = 0xFF;
5331 } else if (std::find(group->cargo_output, group->cargo_output + i, cargo) != group->cargo_output + i) {
5332 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5333 error->data = "duplicate output cargo";
5334 return;
5336 group->cargo_output[i] = cargo;
5337 group->add_output[i] = buf->ReadByte();
5339 group->again = buf->ReadByte();
5340 } else {
5341 NOT_REACHED();
5343 break;
5346 /* Loading of Tile Layout and Production Callback groups would happen here */
5347 default: grfmsg(1, "NewSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5352 _cur.spritegroups[setid] = act_group;
5355 static CargoID TranslateCargo(uint8 feature, uint8 ctype)
5357 if (feature == GSF_OBJECTS) {
5358 switch (ctype) {
5359 case 0: return 0;
5360 case 0xFF: return CT_PURCHASE_OBJECT;
5361 default:
5362 grfmsg(1, "TranslateCargo: Invalid cargo bitnum %d for objects, skipping.", ctype);
5363 return CT_INVALID;
5366 /* Special cargo types for purchase list and stations */
5367 if (feature == GSF_STATIONS && ctype == 0xFE) return CT_DEFAULT_NA;
5368 if (ctype == 0xFF) return CT_PURCHASE;
5370 if (_cur.grffile->cargo_list.size() == 0) {
5371 /* No cargo table, so use bitnum values */
5372 if (ctype >= 32) {
5373 grfmsg(1, "TranslateCargo: Cargo bitnum %d out of range (max 31), skipping.", ctype);
5374 return CT_INVALID;
5377 for (const CargoSpec *cs : CargoSpec::Iterate()) {
5378 if (cs->bitnum == ctype) {
5379 grfmsg(6, "TranslateCargo: Cargo bitnum %d mapped to cargo type %d.", ctype, cs->Index());
5380 return cs->Index();
5384 grfmsg(5, "TranslateCargo: Cargo bitnum %d not available in this climate, skipping.", ctype);
5385 return CT_INVALID;
5388 /* Check if the cargo type is out of bounds of the cargo translation table */
5389 if (ctype >= _cur.grffile->cargo_list.size()) {
5390 grfmsg(1, "TranslateCargo: Cargo type %d out of range (max %d), skipping.", ctype, (unsigned int)_cur.grffile->cargo_list.size() - 1);
5391 return CT_INVALID;
5394 /* Look up the cargo label from the translation table */
5395 CargoLabel cl = _cur.grffile->cargo_list[ctype];
5396 if (cl == 0) {
5397 grfmsg(5, "TranslateCargo: Cargo type %d not available in this climate, skipping.", ctype);
5398 return CT_INVALID;
5401 ctype = GetCargoIDByLabel(cl);
5402 if (ctype == CT_INVALID) {
5403 grfmsg(5, "TranslateCargo: Cargo '%c%c%c%c' unsupported, skipping.", GB(cl, 24, 8), GB(cl, 16, 8), GB(cl, 8, 8), GB(cl, 0, 8));
5404 return CT_INVALID;
5407 grfmsg(6, "TranslateCargo: Cargo '%c%c%c%c' mapped to cargo type %d.", GB(cl, 24, 8), GB(cl, 16, 8), GB(cl, 8, 8), GB(cl, 0, 8), ctype);
5408 return ctype;
5412 static bool IsValidGroupID(uint16 groupid, const char *function)
5414 if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
5415 grfmsg(1, "%s: Spritegroup 0x%04X out of range or empty, skipping.", function, groupid);
5416 return false;
5419 return true;
5422 static void VehicleMapSpriteGroup(ByteReader *buf, byte feature, uint8 idcount)
5424 static EngineID *last_engines;
5425 static uint last_engines_count;
5426 bool wagover = false;
5428 /* Test for 'wagon override' flag */
5429 if (HasBit(idcount, 7)) {
5430 wagover = true;
5431 /* Strip off the flag */
5432 idcount = GB(idcount, 0, 7);
5434 if (last_engines_count == 0) {
5435 grfmsg(0, "VehicleMapSpriteGroup: WagonOverride: No engine to do override with");
5436 return;
5439 grfmsg(6, "VehicleMapSpriteGroup: WagonOverride: %u engines, %u wagons",
5440 last_engines_count, idcount);
5441 } else {
5442 if (last_engines_count != idcount) {
5443 last_engines = ReallocT(last_engines, idcount);
5444 last_engines_count = idcount;
5448 EngineID *engines = AllocaM(EngineID, idcount);
5449 for (uint i = 0; i < idcount; i++) {
5450 Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, buf->ReadExtendedByte());
5451 if (e == nullptr) {
5452 /* No engine could be allocated?!? Deal with it. Okay,
5453 * this might look bad. Also make sure this NewGRF
5454 * gets disabled, as a half loaded one is bad. */
5455 HandleChangeInfoResult("VehicleMapSpriteGroup", CIR_INVALID_ID, 0, 0);
5456 return;
5459 engines[i] = e->index;
5460 if (!wagover) last_engines[i] = engines[i];
5463 uint8 cidcount = buf->ReadByte();
5464 for (uint c = 0; c < cidcount; c++) {
5465 uint8 ctype = buf->ReadByte();
5466 uint16 groupid = buf->ReadWord();
5467 if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) continue;
5469 grfmsg(8, "VehicleMapSpriteGroup: * [%d] Cargo type 0x%X, group id 0x%02X", c, ctype, groupid);
5471 ctype = TranslateCargo(feature, ctype);
5472 if (ctype == CT_INVALID) continue;
5474 for (uint i = 0; i < idcount; i++) {
5475 EngineID engine = engines[i];
5477 grfmsg(7, "VehicleMapSpriteGroup: [%d] Engine %d...", i, engine);
5479 if (wagover) {
5480 SetWagonOverrideSprites(engine, ctype, _cur.spritegroups[groupid], last_engines, last_engines_count);
5481 } else {
5482 SetCustomEngineSprites(engine, ctype, _cur.spritegroups[groupid]);
5487 uint16 groupid = buf->ReadWord();
5488 if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) return;
5490 grfmsg(8, "-- Default group id 0x%04X", groupid);
5492 for (uint i = 0; i < idcount; i++) {
5493 EngineID engine = engines[i];
5495 if (wagover) {
5496 SetWagonOverrideSprites(engine, CT_DEFAULT, _cur.spritegroups[groupid], last_engines, last_engines_count);
5497 } else {
5498 SetCustomEngineSprites(engine, CT_DEFAULT, _cur.spritegroups[groupid]);
5499 SetEngineGRF(engine, _cur.grffile);
5505 static void CanalMapSpriteGroup(ByteReader *buf, uint8 idcount)
5507 CanalFeature *cfs = AllocaM(CanalFeature, idcount);
5508 for (uint i = 0; i < idcount; i++) {
5509 cfs[i] = (CanalFeature)buf->ReadByte();
5512 uint8 cidcount = buf->ReadByte();
5513 buf->Skip(cidcount * 3);
5515 uint16 groupid = buf->ReadWord();
5516 if (!IsValidGroupID(groupid, "CanalMapSpriteGroup")) return;
5518 for (uint i = 0; i < idcount; i++) {
5519 CanalFeature cf = cfs[i];
5521 if (cf >= CF_END) {
5522 grfmsg(1, "CanalMapSpriteGroup: Canal subset %d out of range, skipping", cf);
5523 continue;
5526 _water_feature[cf].grffile = _cur.grffile;
5527 _water_feature[cf].group = _cur.spritegroups[groupid];
5532 static void StationMapSpriteGroup(ByteReader *buf, uint8 idcount)
5534 uint8 *stations = AllocaM(uint8, idcount);
5535 for (uint i = 0; i < idcount; i++) {
5536 stations[i] = buf->ReadByte();
5539 uint8 cidcount = buf->ReadByte();
5540 for (uint c = 0; c < cidcount; c++) {
5541 uint8 ctype = buf->ReadByte();
5542 uint16 groupid = buf->ReadWord();
5543 if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) continue;
5545 ctype = TranslateCargo(GSF_STATIONS, ctype);
5546 if (ctype == CT_INVALID) continue;
5548 for (uint i = 0; i < idcount; i++) {
5549 StationSpec *statspec = _cur.grffile->stations == nullptr ? nullptr : _cur.grffile->stations[stations[i]];
5551 if (statspec == nullptr) {
5552 grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
5553 continue;
5556 statspec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5560 uint16 groupid = buf->ReadWord();
5561 if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) return;
5563 for (uint i = 0; i < idcount; i++) {
5564 StationSpec *statspec = _cur.grffile->stations == nullptr ? nullptr : _cur.grffile->stations[stations[i]];
5566 if (statspec == nullptr) {
5567 grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X does not exist, skipping", stations[i]);
5568 continue;
5571 if (statspec->grf_prop.grffile != nullptr) {
5572 grfmsg(1, "StationMapSpriteGroup: Station with ID 0x%02X mapped multiple times, skipping", stations[i]);
5573 continue;
5576 statspec->grf_prop.spritegroup[CT_DEFAULT] = _cur.spritegroups[groupid];
5577 statspec->grf_prop.grffile = _cur.grffile;
5578 statspec->grf_prop.local_id = stations[i];
5579 StationClass::Assign(statspec);
5584 static void TownHouseMapSpriteGroup(ByteReader *buf, uint8 idcount)
5586 uint8 *houses = AllocaM(uint8, idcount);
5587 for (uint i = 0; i < idcount; i++) {
5588 houses[i] = buf->ReadByte();
5591 /* Skip the cargo type section, we only care about the default group */
5592 uint8 cidcount = buf->ReadByte();
5593 buf->Skip(cidcount * 3);
5595 uint16 groupid = buf->ReadWord();
5596 if (!IsValidGroupID(groupid, "TownHouseMapSpriteGroup")) return;
5598 if (_cur.grffile->housespec == nullptr) {
5599 grfmsg(1, "TownHouseMapSpriteGroup: No houses defined, skipping");
5600 return;
5603 for (uint i = 0; i < idcount; i++) {
5604 HouseSpec *hs = _cur.grffile->housespec[houses[i]];
5606 if (hs == nullptr) {
5607 grfmsg(1, "TownHouseMapSpriteGroup: House %d undefined, skipping.", houses[i]);
5608 continue;
5611 hs->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5615 static void IndustryMapSpriteGroup(ByteReader *buf, uint8 idcount)
5617 uint8 *industries = AllocaM(uint8, idcount);
5618 for (uint i = 0; i < idcount; i++) {
5619 industries[i] = buf->ReadByte();
5622 /* Skip the cargo type section, we only care about the default group */
5623 uint8 cidcount = buf->ReadByte();
5624 buf->Skip(cidcount * 3);
5626 uint16 groupid = buf->ReadWord();
5627 if (!IsValidGroupID(groupid, "IndustryMapSpriteGroup")) return;
5629 if (_cur.grffile->industryspec == nullptr) {
5630 grfmsg(1, "IndustryMapSpriteGroup: No industries defined, skipping");
5631 return;
5634 for (uint i = 0; i < idcount; i++) {
5635 IndustrySpec *indsp = _cur.grffile->industryspec[industries[i]];
5637 if (indsp == nullptr) {
5638 grfmsg(1, "IndustryMapSpriteGroup: Industry %d undefined, skipping", industries[i]);
5639 continue;
5642 indsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5646 static void IndustrytileMapSpriteGroup(ByteReader *buf, uint8 idcount)
5648 uint8 *indtiles = AllocaM(uint8, idcount);
5649 for (uint i = 0; i < idcount; i++) {
5650 indtiles[i] = buf->ReadByte();
5653 /* Skip the cargo type section, we only care about the default group */
5654 uint8 cidcount = buf->ReadByte();
5655 buf->Skip(cidcount * 3);
5657 uint16 groupid = buf->ReadWord();
5658 if (!IsValidGroupID(groupid, "IndustrytileMapSpriteGroup")) return;
5660 if (_cur.grffile->indtspec == nullptr) {
5661 grfmsg(1, "IndustrytileMapSpriteGroup: No industry tiles defined, skipping");
5662 return;
5665 for (uint i = 0; i < idcount; i++) {
5666 IndustryTileSpec *indtsp = _cur.grffile->indtspec[indtiles[i]];
5668 if (indtsp == nullptr) {
5669 grfmsg(1, "IndustrytileMapSpriteGroup: Industry tile %d undefined, skipping", indtiles[i]);
5670 continue;
5673 indtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5677 static void CargoMapSpriteGroup(ByteReader *buf, uint8 idcount)
5679 CargoID *cargoes = AllocaM(CargoID, idcount);
5680 for (uint i = 0; i < idcount; i++) {
5681 cargoes[i] = buf->ReadByte();
5684 /* Skip the cargo type section, we only care about the default group */
5685 uint8 cidcount = buf->ReadByte();
5686 buf->Skip(cidcount * 3);
5688 uint16 groupid = buf->ReadWord();
5689 if (!IsValidGroupID(groupid, "CargoMapSpriteGroup")) return;
5691 for (uint i = 0; i < idcount; i++) {
5692 CargoID cid = cargoes[i];
5694 if (cid >= NUM_CARGO) {
5695 grfmsg(1, "CargoMapSpriteGroup: Cargo ID %d out of range, skipping", cid);
5696 continue;
5699 CargoSpec *cs = CargoSpec::Get(cid);
5700 cs->grffile = _cur.grffile;
5701 cs->group = _cur.spritegroups[groupid];
5705 static void ObjectMapSpriteGroup(ByteReader *buf, uint8 idcount)
5707 if (_cur.grffile->objectspec == nullptr) {
5708 grfmsg(1, "ObjectMapSpriteGroup: No object tiles defined, skipping");
5709 return;
5712 uint8 *objects = AllocaM(uint8, idcount);
5713 for (uint i = 0; i < idcount; i++) {
5714 objects[i] = buf->ReadByte();
5717 uint8 cidcount = buf->ReadByte();
5718 for (uint c = 0; c < cidcount; c++) {
5719 uint8 ctype = buf->ReadByte();
5720 uint16 groupid = buf->ReadWord();
5721 if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) continue;
5723 ctype = TranslateCargo(GSF_OBJECTS, ctype);
5724 if (ctype == CT_INVALID) continue;
5726 for (uint i = 0; i < idcount; i++) {
5727 ObjectSpec *spec = _cur.grffile->objectspec[objects[i]];
5729 if (spec == nullptr) {
5730 grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X undefined, skipping", objects[i]);
5731 continue;
5734 spec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5738 uint16 groupid = buf->ReadWord();
5739 if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) return;
5741 for (uint i = 0; i < idcount; i++) {
5742 ObjectSpec *spec = _cur.grffile->objectspec[objects[i]];
5744 if (spec == nullptr) {
5745 grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X undefined, skipping", objects[i]);
5746 continue;
5749 if (spec->grf_prop.grffile != nullptr) {
5750 grfmsg(1, "ObjectMapSpriteGroup: Object with ID 0x%02X mapped multiple times, skipping", objects[i]);
5751 continue;
5754 spec->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5755 spec->grf_prop.grffile = _cur.grffile;
5756 spec->grf_prop.local_id = objects[i];
5760 static void RailTypeMapSpriteGroup(ByteReader *buf, uint8 idcount)
5762 uint8 *railtypes = AllocaM(uint8, idcount);
5763 for (uint i = 0; i < idcount; i++) {
5764 uint8 id = buf->ReadByte();
5765 railtypes[i] = id < RAILTYPE_END ? _cur.grffile->railtype_map[id] : INVALID_RAILTYPE;
5768 uint8 cidcount = buf->ReadByte();
5769 for (uint c = 0; c < cidcount; c++) {
5770 uint8 ctype = buf->ReadByte();
5771 uint16 groupid = buf->ReadWord();
5772 if (!IsValidGroupID(groupid, "RailTypeMapSpriteGroup")) continue;
5774 if (ctype >= RTSG_END) continue;
5776 extern RailtypeInfo _railtypes[RAILTYPE_END];
5777 for (uint i = 0; i < idcount; i++) {
5778 if (railtypes[i] != INVALID_RAILTYPE) {
5779 RailtypeInfo *rti = &_railtypes[railtypes[i]];
5781 rti->grffile[ctype] = _cur.grffile;
5782 rti->group[ctype] = _cur.spritegroups[groupid];
5787 /* Railtypes do not use the default group. */
5788 buf->ReadWord();
5791 static void RoadTypeMapSpriteGroup(ByteReader *buf, uint8 idcount, RoadTramType rtt)
5793 RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
5795 uint8 *roadtypes = AllocaM(uint8, idcount);
5796 for (uint i = 0; i < idcount; i++) {
5797 uint8 id = buf->ReadByte();
5798 roadtypes[i] = id < ROADTYPE_END ? type_map[id] : INVALID_ROADTYPE;
5801 uint8 cidcount = buf->ReadByte();
5802 for (uint c = 0; c < cidcount; c++) {
5803 uint8 ctype = buf->ReadByte();
5804 uint16 groupid = buf->ReadWord();
5805 if (!IsValidGroupID(groupid, "RoadTypeMapSpriteGroup")) continue;
5807 if (ctype >= ROTSG_END) continue;
5809 extern RoadTypeInfo _roadtypes[ROADTYPE_END];
5810 for (uint i = 0; i < idcount; i++) {
5811 if (roadtypes[i] != INVALID_ROADTYPE) {
5812 RoadTypeInfo *rti = &_roadtypes[roadtypes[i]];
5814 rti->grffile[ctype] = _cur.grffile;
5815 rti->group[ctype] = _cur.spritegroups[groupid];
5820 /* Roadtypes do not use the default group. */
5821 buf->ReadWord();
5824 static void AirportMapSpriteGroup(ByteReader *buf, uint8 idcount)
5826 uint8 *airports = AllocaM(uint8, idcount);
5827 for (uint i = 0; i < idcount; i++) {
5828 airports[i] = buf->ReadByte();
5831 /* Skip the cargo type section, we only care about the default group */
5832 uint8 cidcount = buf->ReadByte();
5833 buf->Skip(cidcount * 3);
5835 uint16 groupid = buf->ReadWord();
5836 if (!IsValidGroupID(groupid, "AirportMapSpriteGroup")) return;
5838 if (_cur.grffile->airportspec == nullptr) {
5839 grfmsg(1, "AirportMapSpriteGroup: No airports defined, skipping");
5840 return;
5843 for (uint i = 0; i < idcount; i++) {
5844 AirportSpec *as = _cur.grffile->airportspec[airports[i]];
5846 if (as == nullptr) {
5847 grfmsg(1, "AirportMapSpriteGroup: Airport %d undefined, skipping", airports[i]);
5848 continue;
5851 as->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5855 static void AirportTileMapSpriteGroup(ByteReader *buf, uint8 idcount)
5857 uint8 *airptiles = AllocaM(uint8, idcount);
5858 for (uint i = 0; i < idcount; i++) {
5859 airptiles[i] = buf->ReadByte();
5862 /* Skip the cargo type section, we only care about the default group */
5863 uint8 cidcount = buf->ReadByte();
5864 buf->Skip(cidcount * 3);
5866 uint16 groupid = buf->ReadWord();
5867 if (!IsValidGroupID(groupid, "AirportTileMapSpriteGroup")) return;
5869 if (_cur.grffile->airtspec == nullptr) {
5870 grfmsg(1, "AirportTileMapSpriteGroup: No airport tiles defined, skipping");
5871 return;
5874 for (uint i = 0; i < idcount; i++) {
5875 AirportTileSpec *airtsp = _cur.grffile->airtspec[airptiles[i]];
5877 if (airtsp == nullptr) {
5878 grfmsg(1, "AirportTileMapSpriteGroup: Airport tile %d undefined, skipping", airptiles[i]);
5879 continue;
5882 airtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5887 /* Action 0x03 */
5888 static void FeatureMapSpriteGroup(ByteReader *buf)
5890 /* <03> <feature> <n-id> <ids>... <num-cid> [<cargo-type> <cid>]... <def-cid>
5891 * id-list := [<id>] [id-list]
5892 * cargo-list := <cargo-type> <cid> [cargo-list]
5894 * B feature see action 0
5895 * B n-id bits 0-6: how many IDs this definition applies to
5896 * bit 7: if set, this is a wagon override definition (see below)
5897 * B ids the IDs for which this definition applies
5898 * B num-cid number of cargo IDs (sprite group IDs) in this definition
5899 * can be zero, in that case the def-cid is used always
5900 * B cargo-type type of this cargo type (e.g. mail=2, wood=7, see below)
5901 * W cid cargo ID (sprite group ID) for this type of cargo
5902 * W def-cid default cargo ID (sprite group ID) */
5904 uint8 feature = buf->ReadByte();
5905 uint8 idcount = buf->ReadByte();
5907 if (feature >= GSF_END) {
5908 grfmsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5909 return;
5912 /* If idcount is zero, this is a feature callback */
5913 if (idcount == 0) {
5914 /* Skip number of cargo ids? */
5915 buf->ReadByte();
5916 uint16 groupid = buf->ReadWord();
5917 if (!IsValidGroupID(groupid, "FeatureMapSpriteGroup")) return;
5919 grfmsg(6, "FeatureMapSpriteGroup: Adding generic feature callback for feature 0x%02X", feature);
5921 AddGenericCallback(feature, _cur.grffile, _cur.spritegroups[groupid]);
5922 return;
5925 /* Mark the feature as used by the grf (generic callbacks do not count) */
5926 SetBit(_cur.grffile->grf_features, feature);
5928 grfmsg(6, "FeatureMapSpriteGroup: Feature 0x%02X, %d ids", feature, idcount);
5930 switch (feature) {
5931 case GSF_TRAINS:
5932 case GSF_ROADVEHICLES:
5933 case GSF_SHIPS:
5934 case GSF_AIRCRAFT:
5935 VehicleMapSpriteGroup(buf, feature, idcount);
5936 return;
5938 case GSF_CANALS:
5939 CanalMapSpriteGroup(buf, idcount);
5940 return;
5942 case GSF_STATIONS:
5943 StationMapSpriteGroup(buf, idcount);
5944 return;
5946 case GSF_HOUSES:
5947 TownHouseMapSpriteGroup(buf, idcount);
5948 return;
5950 case GSF_INDUSTRIES:
5951 IndustryMapSpriteGroup(buf, idcount);
5952 return;
5954 case GSF_INDUSTRYTILES:
5955 IndustrytileMapSpriteGroup(buf, idcount);
5956 return;
5958 case GSF_CARGOES:
5959 CargoMapSpriteGroup(buf, idcount);
5960 return;
5962 case GSF_AIRPORTS:
5963 AirportMapSpriteGroup(buf, idcount);
5964 return;
5966 case GSF_OBJECTS:
5967 ObjectMapSpriteGroup(buf, idcount);
5968 break;
5970 case GSF_RAILTYPES:
5971 RailTypeMapSpriteGroup(buf, idcount);
5972 break;
5974 case GSF_ROADTYPES:
5975 RoadTypeMapSpriteGroup(buf, idcount, RTT_ROAD);
5976 break;
5978 case GSF_TRAMTYPES:
5979 RoadTypeMapSpriteGroup(buf, idcount, RTT_TRAM);
5980 break;
5982 case GSF_AIRPORTTILES:
5983 AirportTileMapSpriteGroup(buf, idcount);
5984 return;
5986 default:
5987 grfmsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x%02X, skipping", feature);
5988 return;
5992 /* Action 0x04 */
5993 static void FeatureNewName(ByteReader *buf)
5995 /* <04> <veh-type> <language-id> <num-veh> <offset> <data...>
5997 * B veh-type see action 0 (as 00..07, + 0A
5998 * But IF veh-type = 48, then generic text
5999 * B language-id If bit 6 is set, This is the extended language scheme,
6000 * with up to 64 language.
6001 * Otherwise, it is a mapping where set bits have meaning
6002 * 0 = american, 1 = english, 2 = german, 3 = french, 4 = spanish
6003 * Bit 7 set means this is a generic text, not a vehicle one (or else)
6004 * B num-veh number of vehicles which are getting a new name
6005 * B/W offset number of the first vehicle that gets a new name
6006 * Byte : ID of vehicle to change
6007 * Word : ID of string to change/add
6008 * S data new texts, each of them zero-terminated, after
6009 * which the next name begins. */
6011 bool new_scheme = _cur.grffile->grf_version >= 7;
6013 uint8 feature = buf->ReadByte();
6014 if (feature >= GSF_END && feature != 0x48) {
6015 grfmsg(1, "FeatureNewName: Unsupported feature 0x%02X, skipping", feature);
6016 return;
6019 uint8 lang = buf->ReadByte();
6020 uint8 num = buf->ReadByte();
6021 bool generic = HasBit(lang, 7);
6022 uint16 id;
6023 if (generic) {
6024 id = buf->ReadWord();
6025 } else if (feature <= GSF_AIRCRAFT) {
6026 id = buf->ReadExtendedByte();
6027 } else {
6028 id = buf->ReadByte();
6031 ClrBit(lang, 7);
6033 uint16 endid = id + num;
6035 grfmsg(6, "FeatureNewName: About to rename engines %d..%d (feature 0x%02X) in language 0x%02X",
6036 id, endid, feature, lang);
6038 for (; id < endid && buf->HasData(); id++) {
6039 const char *name = buf->ReadString();
6040 grfmsg(8, "FeatureNewName: 0x%04X <- %s", id, name);
6042 switch (feature) {
6043 case GSF_TRAINS:
6044 case GSF_ROADVEHICLES:
6045 case GSF_SHIPS:
6046 case GSF_AIRCRAFT:
6047 if (!generic) {
6048 Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, id, HasBit(_cur.grfconfig->flags, GCF_STATIC));
6049 if (e == nullptr) break;
6050 StringID string = AddGRFString(_cur.grffile->grfid, e->index, lang, new_scheme, false, name, e->info.string_id);
6051 e->info.string_id = string;
6052 } else {
6053 AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6055 break;
6057 default:
6058 if (IsInsideMM(id, 0xD000, 0xD400) || IsInsideMM(id, 0xD800, 0xE000)) {
6059 AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6060 break;
6063 switch (GB(id, 8, 8)) {
6064 case 0xC4: // Station class name
6065 if (_cur.grffile->stations == nullptr || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6066 grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
6067 } else {
6068 StationClassID cls_id = _cur.grffile->stations[GB(id, 0, 8)]->cls_id;
6069 StationClass::Get(cls_id)->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6071 break;
6073 case 0xC5: // Station name
6074 if (_cur.grffile->stations == nullptr || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6075 grfmsg(1, "FeatureNewName: Attempt to name undefined station 0x%X, ignoring", GB(id, 0, 8));
6076 } else {
6077 _cur.grffile->stations[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6079 break;
6081 case 0xC7: // Airporttile name
6082 if (_cur.grffile->airtspec == nullptr || _cur.grffile->airtspec[GB(id, 0, 8)] == nullptr) {
6083 grfmsg(1, "FeatureNewName: Attempt to name undefined airport tile 0x%X, ignoring", GB(id, 0, 8));
6084 } else {
6085 _cur.grffile->airtspec[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6087 break;
6089 case 0xC9: // House name
6090 if (_cur.grffile->housespec == nullptr || _cur.grffile->housespec[GB(id, 0, 8)] == nullptr) {
6091 grfmsg(1, "FeatureNewName: Attempt to name undefined house 0x%X, ignoring.", GB(id, 0, 8));
6092 } else {
6093 _cur.grffile->housespec[GB(id, 0, 8)]->building_name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6095 break;
6097 default:
6098 grfmsg(7, "FeatureNewName: Unsupported ID (0x%04X)", id);
6099 break;
6101 break;
6107 * Sanitize incoming sprite offsets for Action 5 graphics replacements.
6108 * @param num The number of sprites to load.
6109 * @param offset Offset from the base.
6110 * @param max_sprites The maximum number of sprites that can be loaded in this action 5.
6111 * @param name Used for error warnings.
6112 * @return The number of sprites that is going to be skipped.
6114 static uint16 SanitizeSpriteOffset(uint16& num, uint16 offset, int max_sprites, const char *name)
6117 if (offset >= max_sprites) {
6118 grfmsg(1, "GraphicsNew: %s sprite offset must be less than %i, skipping", name, max_sprites);
6119 uint orig_num = num;
6120 num = 0;
6121 return orig_num;
6124 if (offset + num > max_sprites) {
6125 grfmsg(4, "GraphicsNew: %s sprite overflow, truncating...", name);
6126 uint orig_num = num;
6127 num = std::max(max_sprites - offset, 0);
6128 return orig_num - num;
6131 return 0;
6135 /** The type of action 5 type. */
6136 enum Action5BlockType {
6137 A5BLOCK_FIXED, ///< Only allow replacing a whole block of sprites. (TTDP compatible)
6138 A5BLOCK_ALLOW_OFFSET, ///< Allow replacing any subset by specifiing an offset.
6139 A5BLOCK_INVALID, ///< unknown/not-implemented type
6141 /** Information about a single action 5 type. */
6142 struct Action5Type {
6143 Action5BlockType block_type; ///< How is this Action5 type processed?
6144 SpriteID sprite_base; ///< Load the sprites starting from this sprite.
6145 uint16 min_sprites; ///< If the Action5 contains less sprites, the whole block will be ignored.
6146 uint16 max_sprites; ///< If the Action5 contains more sprites, only the first max_sprites sprites will be used.
6147 const char *name; ///< Name for error messages.
6150 /** The information about action 5 types. */
6151 static const Action5Type _action5_types[] = {
6152 /* Note: min_sprites should not be changed. Therefore these constants are directly here and not in sprites.h */
6153 /* 0x00 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x00" },
6154 /* 0x01 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x01" },
6155 /* 0x02 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x02" },
6156 /* 0x03 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x03" },
6157 /* 0x04 */ { A5BLOCK_ALLOW_OFFSET, SPR_SIGNALS_BASE, 1, PRESIGNAL_SEMAPHORE_AND_PBS_SPRITE_COUNT, "Signal graphics" },
6158 /* 0x05 */ { A5BLOCK_ALLOW_OFFSET, SPR_ELRAIL_BASE, 1, ELRAIL_SPRITE_COUNT, "Rail catenary graphics" },
6159 /* 0x06 */ { A5BLOCK_ALLOW_OFFSET, SPR_SLOPES_BASE, 1, NORMAL_AND_HALFTILE_FOUNDATION_SPRITE_COUNT, "Foundation graphics" },
6160 /* 0x07 */ { A5BLOCK_INVALID, 0, 75, 0, "TTDP GUI graphics" }, // Not used by OTTD.
6161 /* 0x08 */ { A5BLOCK_ALLOW_OFFSET, SPR_CANALS_BASE, 1, CANALS_SPRITE_COUNT, "Canal graphics" },
6162 /* 0x09 */ { A5BLOCK_ALLOW_OFFSET, SPR_ONEWAY_BASE, 1, ONEWAY_SPRITE_COUNT, "One way road graphics" },
6163 /* 0x0A */ { A5BLOCK_ALLOW_OFFSET, SPR_2CCMAP_BASE, 1, TWOCCMAP_SPRITE_COUNT, "2CC colour maps" },
6164 /* 0x0B */ { A5BLOCK_ALLOW_OFFSET, SPR_TRAMWAY_BASE, 1, TRAMWAY_SPRITE_COUNT, "Tramway graphics" },
6165 /* 0x0C */ { A5BLOCK_INVALID, 0, 133, 0, "Snowy temperate tree" }, // Not yet used by OTTD.
6166 /* 0x0D */ { A5BLOCK_FIXED, SPR_SHORE_BASE, 16, SPR_SHORE_SPRITE_COUNT, "Shore graphics" },
6167 /* 0x0E */ { A5BLOCK_INVALID, 0, 0, 0, "New Signals graphics" }, // Not yet used by OTTD.
6168 /* 0x0F */ { A5BLOCK_ALLOW_OFFSET, SPR_TRACKS_FOR_SLOPES_BASE, 1, TRACKS_FOR_SLOPES_SPRITE_COUNT, "Sloped rail track" },
6169 /* 0x10 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORTX_BASE, 1, AIRPORTX_SPRITE_COUNT, "Airport graphics" },
6170 /* 0x11 */ { A5BLOCK_ALLOW_OFFSET, SPR_ROADSTOP_BASE, 1, ROADSTOP_SPRITE_COUNT, "Road stop graphics" },
6171 /* 0x12 */ { A5BLOCK_ALLOW_OFFSET, SPR_AQUEDUCT_BASE, 1, AQUEDUCT_SPRITE_COUNT, "Aqueduct graphics" },
6172 /* 0x13 */ { A5BLOCK_ALLOW_OFFSET, SPR_AUTORAIL_BASE, 1, AUTORAIL_SPRITE_COUNT, "Autorail graphics" },
6173 /* 0x14 */ { A5BLOCK_INVALID, 0, 1, 0, "Flag graphics" }, // deprecated, no longer used.
6174 /* 0x15 */ { A5BLOCK_ALLOW_OFFSET, SPR_OPENTTD_BASE, 1, OPENTTD_SPRITE_COUNT, "OpenTTD GUI graphics" },
6175 /* 0x16 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORT_PREVIEW_BASE, 1, SPR_AIRPORT_PREVIEW_COUNT, "Airport preview graphics" },
6176 /* 0x17 */ { A5BLOCK_ALLOW_OFFSET, SPR_RAILTYPE_TUNNEL_BASE, 1, RAILTYPE_TUNNEL_BASE_COUNT, "Railtype tunnel base" },
6177 /* 0x18 */ { A5BLOCK_ALLOW_OFFSET, SPR_PALETTE_BASE, 1, PALETTE_SPRITE_COUNT, "Palette" },
6180 /* Action 0x05 */
6181 static void GraphicsNew(ByteReader *buf)
6183 /* <05> <graphics-type> <num-sprites> <other data...>
6185 * B graphics-type What set of graphics the sprites define.
6186 * E num-sprites How many sprites are in this set?
6187 * V other data Graphics type specific data. Currently unused. */
6189 uint8 type = buf->ReadByte();
6190 uint16 num = buf->ReadExtendedByte();
6191 uint16 offset = HasBit(type, 7) ? buf->ReadExtendedByte() : 0;
6192 ClrBit(type, 7); // Clear the high bit as that only indicates whether there is an offset.
6194 if ((type == 0x0D) && (num == 10) && HasBit(_cur.grfconfig->flags, GCF_SYSTEM)) {
6195 /* Special not-TTDP-compatible case used in openttd.grf
6196 * Missing shore sprites and initialisation of SPR_SHORE_BASE */
6197 grfmsg(2, "GraphicsNew: Loading 10 missing shore sprites from extra grf.");
6198 LoadNextSprite(SPR_SHORE_BASE + 0, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_S
6199 LoadNextSprite(SPR_SHORE_BASE + 5, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_W
6200 LoadNextSprite(SPR_SHORE_BASE + 7, *_cur.file, _cur.nfo_line++); // SLOPE_WSE
6201 LoadNextSprite(SPR_SHORE_BASE + 10, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_N
6202 LoadNextSprite(SPR_SHORE_BASE + 11, *_cur.file, _cur.nfo_line++); // SLOPE_NWS
6203 LoadNextSprite(SPR_SHORE_BASE + 13, *_cur.file, _cur.nfo_line++); // SLOPE_ENW
6204 LoadNextSprite(SPR_SHORE_BASE + 14, *_cur.file, _cur.nfo_line++); // SLOPE_SEN
6205 LoadNextSprite(SPR_SHORE_BASE + 15, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_E
6206 LoadNextSprite(SPR_SHORE_BASE + 16, *_cur.file, _cur.nfo_line++); // SLOPE_EW
6207 LoadNextSprite(SPR_SHORE_BASE + 17, *_cur.file, _cur.nfo_line++); // SLOPE_NS
6208 if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ONLY_NEW;
6209 return;
6212 /* Supported type? */
6213 if ((type >= lengthof(_action5_types)) || (_action5_types[type].block_type == A5BLOCK_INVALID)) {
6214 grfmsg(2, "GraphicsNew: Custom graphics (type 0x%02X) sprite block of length %u (unimplemented, ignoring)", type, num);
6215 _cur.skip_sprites = num;
6216 return;
6219 const Action5Type *action5_type = &_action5_types[type];
6221 /* Contrary to TTDP we allow always to specify too few sprites as we allow always an offset,
6222 * except for the long version of the shore type:
6223 * Ignore offset if not allowed */
6224 if ((action5_type->block_type != A5BLOCK_ALLOW_OFFSET) && (offset != 0)) {
6225 grfmsg(1, "GraphicsNew: %s (type 0x%02X) do not allow an <offset> field. Ignoring offset.", action5_type->name, type);
6226 offset = 0;
6229 /* Ignore action5 if too few sprites are specified. (for TTDP compatibility)
6230 * This does not make sense, if <offset> is allowed */
6231 if ((action5_type->block_type == A5BLOCK_FIXED) && (num < action5_type->min_sprites)) {
6232 grfmsg(1, "GraphicsNew: %s (type 0x%02X) count must be at least %d. Only %d were specified. Skipping.", action5_type->name, type, action5_type->min_sprites, num);
6233 _cur.skip_sprites = num;
6234 return;
6237 /* Load at most max_sprites sprites. Skip remaining sprites. (for compatibility with TTDP and future extensions) */
6238 uint16 skip_num = SanitizeSpriteOffset(num, offset, action5_type->max_sprites, action5_type->name);
6239 SpriteID replace = action5_type->sprite_base + offset;
6241 /* Load <num> sprites starting from <replace>, then skip <skip_num> sprites. */
6242 grfmsg(2, "GraphicsNew: Replacing sprites %d to %d of %s (type 0x%02X) at SpriteID 0x%04X", offset, offset + num - 1, action5_type->name, type, replace);
6244 if (type == 0x0D) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_5;
6246 if (type == 0x0B) {
6247 static const SpriteID depot_with_track_offset = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_TRAMWAY_BASE;
6248 static const SpriteID depot_no_track_offset = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_TRAMWAY_BASE;
6249 if (offset <= depot_with_track_offset && offset + num > depot_with_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_WITH_TRACK;
6250 if (offset <= depot_no_track_offset && offset + num > depot_no_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_NO_TRACK;
6253 for (; num > 0; num--) {
6254 _cur.nfo_line++;
6255 LoadNextSprite(replace == 0 ? _cur.spriteid++ : replace++, *_cur.file, _cur.nfo_line);
6258 _cur.skip_sprites = skip_num;
6261 /* Action 0x05 (SKIP) */
6262 static void SkipAct5(ByteReader *buf)
6264 /* Ignore type byte */
6265 buf->ReadByte();
6267 /* Skip the sprites of this action */
6268 _cur.skip_sprites = buf->ReadExtendedByte();
6270 grfmsg(3, "SkipAct5: Skipping %d sprites", _cur.skip_sprites);
6274 * Reads a variable common to VarAction2 and Action7/9/D.
6276 * Returns VarAction2 variable 'param' resp. Action7/9/D variable '0x80 + param'.
6277 * If a variable is not accessible from all four actions, it is handled in the action specific functions.
6279 * @param param variable number (as for VarAction2, for Action7/9/D you have to subtract 0x80 first).
6280 * @param value returns the value of the variable.
6281 * @param grffile NewGRF querying the variable
6282 * @return true iff the variable is known and the value is returned in 'value'.
6284 bool GetGlobalVariable(byte param, uint32 *value, const GRFFile *grffile)
6286 switch (param) {
6287 case 0x00: // current date
6288 *value = std::max(_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0);
6289 return true;
6291 case 0x01: // current year
6292 *value = Clamp(_cur_year, ORIGINAL_BASE_YEAR, ORIGINAL_MAX_YEAR) - ORIGINAL_BASE_YEAR;
6293 return true;
6295 case 0x02: { // detailed date information: month of year (bit 0-7), day of month (bit 8-12), leap year (bit 15), day of year (bit 16-24)
6296 YearMonthDay ymd;
6297 ConvertDateToYMD(_date, &ymd);
6298 Date start_of_year = ConvertYMDToDate(ymd.year, 0, 1);
6299 *value = ymd.month | (ymd.day - 1) << 8 | (IsLeapYear(ymd.year) ? 1 << 15 : 0) | (_date - start_of_year) << 16;
6300 return true;
6303 case 0x03: // current climate, 0=temp, 1=arctic, 2=trop, 3=toyland
6304 *value = _settings_game.game_creation.landscape;
6305 return true;
6307 case 0x06: // road traffic side, bit 4 clear=left, set=right
6308 *value = _settings_game.vehicle.road_side << 4;
6309 return true;
6311 case 0x09: // date fraction
6312 *value = _date_fract * 885;
6313 return true;
6315 case 0x0A: // animation counter
6316 *value = GB(_tick_counter, 0, 16);
6317 return true;
6319 case 0x0B: { // TTDPatch version
6320 uint major = 2;
6321 uint minor = 6;
6322 uint revision = 1; // special case: 2.0.1 is 2.0.10
6323 uint build = 1382;
6324 *value = (major << 24) | (minor << 20) | (revision << 16) | build;
6325 return true;
6328 case 0x0D: // TTD Version, 00=DOS, 01=Windows
6329 *value = _cur.grfconfig->palette & GRFP_USE_MASK;
6330 return true;
6332 case 0x0E: // Y-offset for train sprites
6333 *value = _cur.grffile->traininfo_vehicle_pitch;
6334 return true;
6336 case 0x0F: // Rail track type cost factors
6337 *value = 0;
6338 SB(*value, 0, 8, GetRailTypeInfo(RAILTYPE_RAIL)->cost_multiplier); // normal rail
6339 if (_settings_game.vehicle.disable_elrails) {
6340 /* skip elrail multiplier - disabled */
6341 SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_MONO)->cost_multiplier); // monorail
6342 } else {
6343 SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_ELECTRIC)->cost_multiplier); // electified railway
6344 /* Skip monorail multiplier - no space in result */
6346 SB(*value, 16, 8, GetRailTypeInfo(RAILTYPE_MAGLEV)->cost_multiplier); // maglev
6347 return true;
6349 case 0x11: // current rail tool type
6350 *value = 0; // constant fake value to avoid desync
6351 return true;
6353 case 0x12: // Game mode
6354 *value = _game_mode;
6355 return true;
6357 /* case 0x13: // Tile refresh offset to left not implemented */
6358 /* case 0x14: // Tile refresh offset to right not implemented */
6359 /* case 0x15: // Tile refresh offset upwards not implemented */
6360 /* case 0x16: // Tile refresh offset downwards not implemented */
6361 /* case 0x17: // temperate snow line not implemented */
6363 case 0x1A: // Always -1
6364 *value = UINT_MAX;
6365 return true;
6367 case 0x1B: // Display options
6368 *value = 0x3F; // constant fake value to avoid desync
6369 return true;
6371 case 0x1D: // TTD Platform, 00=TTDPatch, 01=OpenTTD
6372 *value = 1;
6373 return true;
6375 case 0x1E: // Miscellaneous GRF features
6376 *value = _misc_grf_features;
6378 /* Add the local flags */
6379 assert(!HasBit(*value, GMB_TRAIN_WIDTH_32_PIXELS));
6380 if (_cur.grffile->traininfo_vehicle_width == VEHICLEINFO_FULL_VEHICLE_WIDTH) SetBit(*value, GMB_TRAIN_WIDTH_32_PIXELS);
6381 return true;
6383 /* case 0x1F: // locale dependent settings not implemented to avoid desync */
6385 case 0x20: { // snow line height
6386 byte snowline = GetSnowLine();
6387 if (_settings_game.game_creation.landscape == LT_ARCTIC && snowline <= _settings_game.construction.map_height_limit) {
6388 *value = Clamp(snowline * (grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFE);
6389 } else {
6390 /* No snow */
6391 *value = 0xFF;
6393 return true;
6396 case 0x21: // OpenTTD version
6397 *value = _openttd_newgrf_version;
6398 return true;
6400 case 0x22: // difficulty level
6401 *value = SP_CUSTOM;
6402 return true;
6404 case 0x23: // long format date
6405 *value = _date;
6406 return true;
6408 case 0x24: // long format year
6409 *value = _cur_year;
6410 return true;
6412 default: return false;
6416 static uint32 GetParamVal(byte param, uint32 *cond_val)
6418 /* First handle variable common with VarAction2 */
6419 uint32 value;
6420 if (GetGlobalVariable(param - 0x80, &value, _cur.grffile)) return value;
6422 /* Non-common variable */
6423 switch (param) {
6424 case 0x84: { // GRF loading stage
6425 uint32 res = 0;
6427 if (_cur.stage > GLS_INIT) SetBit(res, 0);
6428 if (_cur.stage == GLS_RESERVE) SetBit(res, 8);
6429 if (_cur.stage == GLS_ACTIVATION) SetBit(res, 9);
6430 return res;
6433 case 0x85: // TTDPatch flags, only for bit tests
6434 if (cond_val == nullptr) {
6435 /* Supported in Action 0x07 and 0x09, not 0x0D */
6436 return 0;
6437 } else {
6438 uint32 index = *cond_val / 0x20;
6439 uint32 param_val = index < lengthof(_ttdpatch_flags) ? _ttdpatch_flags[index] : 0;
6440 *cond_val %= 0x20;
6441 return param_val;
6444 case 0x88: // GRF ID check
6445 return 0;
6447 /* case 0x99: Global ID offset not implemented */
6449 default:
6450 /* GRF Parameter */
6451 if (param < 0x80) return _cur.grffile->GetParam(param);
6453 /* In-game variable. */
6454 grfmsg(1, "Unsupported in-game variable 0x%02X", param);
6455 return UINT_MAX;
6459 /* Action 0x06 */
6460 static void CfgApply(ByteReader *buf)
6462 /* <06> <param-num> <param-size> <offset> ... <FF>
6464 * B param-num Number of parameter to substitute (First = "zero")
6465 * Ignored if that parameter was not specified in newgrf.cfg
6466 * B param-size How many bytes to replace. If larger than 4, the
6467 * bytes of the following parameter are used. In that
6468 * case, nothing is applied unless *all* parameters
6469 * were specified.
6470 * B offset Offset into data from beginning of next sprite
6471 * to place where parameter is to be stored. */
6473 /* Preload the next sprite */
6474 SpriteFile &file = *_cur.file;
6475 size_t pos = file.GetPos();
6476 uint32 num = file.GetContainerVersion() >= 2 ? file.ReadDword() : file.ReadWord();
6477 uint8 type = file.ReadByte();
6478 byte *preload_sprite = nullptr;
6480 /* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */
6481 if (type == 0xFF) {
6482 preload_sprite = MallocT<byte>(num);
6483 file.ReadBlock(preload_sprite, num);
6486 /* Reset the file position to the start of the next sprite */
6487 file.SeekTo(pos, SEEK_SET);
6489 if (type != 0xFF) {
6490 grfmsg(2, "CfgApply: Ignoring (next sprite is real, unsupported)");
6491 free(preload_sprite);
6492 return;
6495 GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line + 1);
6496 GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
6497 if (it != _grf_line_to_action6_sprite_override.end()) {
6498 free(preload_sprite);
6499 preload_sprite = _grf_line_to_action6_sprite_override[location];
6500 } else {
6501 _grf_line_to_action6_sprite_override[location] = preload_sprite;
6504 /* Now perform the Action 0x06 on our data. */
6506 for (;;) {
6507 uint i;
6508 uint param_num;
6509 uint param_size;
6510 uint offset;
6511 bool add_value;
6513 /* Read the parameter to apply. 0xFF indicates no more data to change. */
6514 param_num = buf->ReadByte();
6515 if (param_num == 0xFF) break;
6517 /* Get the size of the parameter to use. If the size covers multiple
6518 * double words, sequential parameter values are used. */
6519 param_size = buf->ReadByte();
6521 /* Bit 7 of param_size indicates we should add to the original value
6522 * instead of replacing it. */
6523 add_value = HasBit(param_size, 7);
6524 param_size = GB(param_size, 0, 7);
6526 /* Where to apply the data to within the pseudo sprite data. */
6527 offset = buf->ReadExtendedByte();
6529 /* If the parameter is a GRF parameter (not an internal variable) check
6530 * if it (and all further sequential parameters) has been defined. */
6531 if (param_num < 0x80 && (param_num + (param_size - 1) / 4) >= _cur.grffile->param_end) {
6532 grfmsg(2, "CfgApply: Ignoring (param %d not set)", (param_num + (param_size - 1) / 4));
6533 break;
6536 grfmsg(8, "CfgApply: Applying %u bytes from parameter 0x%02X at offset 0x%04X", param_size, param_num, offset);
6538 bool carry = false;
6539 for (i = 0; i < param_size && offset + i < num; i++) {
6540 uint32 value = GetParamVal(param_num + i / 4, nullptr);
6541 /* Reset carry flag for each iteration of the variable (only really
6542 * matters if param_size is greater than 4) */
6543 if (i % 4 == 0) carry = false;
6545 if (add_value) {
6546 uint new_value = preload_sprite[offset + i] + GB(value, (i % 4) * 8, 8) + (carry ? 1 : 0);
6547 preload_sprite[offset + i] = GB(new_value, 0, 8);
6548 /* Check if the addition overflowed */
6549 carry = new_value >= 256;
6550 } else {
6551 preload_sprite[offset + i] = GB(value, (i % 4) * 8, 8);
6558 * Disable a static NewGRF when it is influencing another (non-static)
6559 * NewGRF as this could cause desyncs.
6561 * We could just tell the NewGRF querying that the file doesn't exist,
6562 * but that might give unwanted results. Disabling the NewGRF gives the
6563 * best result as no NewGRF author can complain about that.
6564 * @param c The NewGRF to disable.
6566 static void DisableStaticNewGRFInfluencingNonStaticNewGRFs(GRFConfig *c)
6568 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC, c);
6569 error->data = _cur.grfconfig->GetName();
6572 /* Action 0x07
6573 * Action 0x09 */
6574 static void SkipIf(ByteReader *buf)
6576 /* <07/09> <param-num> <param-size> <condition-type> <value> <num-sprites>
6578 * B param-num
6579 * B param-size
6580 * B condition-type
6581 * V value
6582 * B num-sprites */
6583 uint32 cond_val = 0;
6584 uint32 mask = 0;
6585 bool result;
6587 uint8 param = buf->ReadByte();
6588 uint8 paramsize = buf->ReadByte();
6589 uint8 condtype = buf->ReadByte();
6591 if (condtype < 2) {
6592 /* Always 1 for bit tests, the given value should be ignored. */
6593 paramsize = 1;
6596 switch (paramsize) {
6597 case 8: cond_val = buf->ReadDWord(); mask = buf->ReadDWord(); break;
6598 case 4: cond_val = buf->ReadDWord(); mask = 0xFFFFFFFF; break;
6599 case 2: cond_val = buf->ReadWord(); mask = 0x0000FFFF; break;
6600 case 1: cond_val = buf->ReadByte(); mask = 0x000000FF; break;
6601 default: break;
6604 if (param < 0x80 && _cur.grffile->param_end <= param) {
6605 grfmsg(7, "SkipIf: Param %d undefined, skipping test", param);
6606 return;
6609 grfmsg(7, "SkipIf: Test condtype %d, param 0x%02X, condval 0x%08X", condtype, param, cond_val);
6611 /* condtypes that do not use 'param' are always valid.
6612 * condtypes that use 'param' are either not valid for param 0x88, or they are only valid for param 0x88.
6614 if (condtype >= 0x0B) {
6615 /* Tests that ignore 'param' */
6616 switch (condtype) {
6617 case 0x0B: result = GetCargoIDByLabel(BSWAP32(cond_val)) == CT_INVALID;
6618 break;
6619 case 0x0C: result = GetCargoIDByLabel(BSWAP32(cond_val)) != CT_INVALID;
6620 break;
6621 case 0x0D: result = GetRailTypeByLabel(BSWAP32(cond_val)) == INVALID_RAILTYPE;
6622 break;
6623 case 0x0E: result = GetRailTypeByLabel(BSWAP32(cond_val)) != INVALID_RAILTYPE;
6624 break;
6625 case 0x0F: {
6626 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6627 result = rt == INVALID_ROADTYPE || !RoadTypeIsRoad(rt);
6628 break;
6630 case 0x10: {
6631 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6632 result = rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt);
6633 break;
6635 case 0x11: {
6636 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6637 result = rt == INVALID_ROADTYPE || !RoadTypeIsTram(rt);
6638 break;
6640 case 0x12: {
6641 RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6642 result = rt != INVALID_ROADTYPE && RoadTypeIsTram(rt);
6643 break;
6645 default: grfmsg(1, "SkipIf: Unsupported condition type %02X. Ignoring", condtype); return;
6647 } else if (param == 0x88) {
6648 /* GRF ID checks */
6650 GRFConfig *c = GetGRFConfig(cond_val, mask);
6652 if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
6653 DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
6654 c = nullptr;
6657 if (condtype != 10 && c == nullptr) {
6658 grfmsg(7, "SkipIf: GRFID 0x%08X unknown, skipping test", BSWAP32(cond_val));
6659 return;
6662 switch (condtype) {
6663 /* Tests 0x06 to 0x0A are only for param 0x88, GRFID checks */
6664 case 0x06: // Is GRFID active?
6665 result = c->status == GCS_ACTIVATED;
6666 break;
6668 case 0x07: // Is GRFID non-active?
6669 result = c->status != GCS_ACTIVATED;
6670 break;
6672 case 0x08: // GRFID is not but will be active?
6673 result = c->status == GCS_INITIALISED;
6674 break;
6676 case 0x09: // GRFID is or will be active?
6677 result = c->status == GCS_ACTIVATED || c->status == GCS_INITIALISED;
6678 break;
6680 case 0x0A: // GRFID is not nor will be active
6681 /* This is the only condtype that doesn't get ignored if the GRFID is not found */
6682 result = c == nullptr || c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND;
6683 break;
6685 default: grfmsg(1, "SkipIf: Unsupported GRF condition type %02X. Ignoring", condtype); return;
6687 } else {
6688 /* Tests that use 'param' and are not GRF ID checks. */
6689 uint32 param_val = GetParamVal(param, &cond_val); // cond_val is modified for param == 0x85
6690 switch (condtype) {
6691 case 0x00: result = !!(param_val & (1 << cond_val));
6692 break;
6693 case 0x01: result = !(param_val & (1 << cond_val));
6694 break;
6695 case 0x02: result = (param_val & mask) == cond_val;
6696 break;
6697 case 0x03: result = (param_val & mask) != cond_val;
6698 break;
6699 case 0x04: result = (param_val & mask) < cond_val;
6700 break;
6701 case 0x05: result = (param_val & mask) > cond_val;
6702 break;
6703 default: grfmsg(1, "SkipIf: Unsupported condition type %02X. Ignoring", condtype); return;
6707 if (!result) {
6708 grfmsg(2, "SkipIf: Not skipping sprites, test was false");
6709 return;
6712 uint8 numsprites = buf->ReadByte();
6714 /* numsprites can be a GOTO label if it has been defined in the GRF
6715 * file. The jump will always be the first matching label that follows
6716 * the current nfo_line. If no matching label is found, the first matching
6717 * label in the file is used. */
6718 GRFLabel *choice = nullptr;
6719 for (GRFLabel *label = _cur.grffile->label; label != nullptr; label = label->next) {
6720 if (label->label != numsprites) continue;
6722 /* Remember a goto before the current line */
6723 if (choice == nullptr) choice = label;
6724 /* If we find a label here, this is definitely good */
6725 if (label->nfo_line > _cur.nfo_line) {
6726 choice = label;
6727 break;
6731 if (choice != nullptr) {
6732 grfmsg(2, "SkipIf: Jumping to label 0x%0X at line %d, test was true", choice->label, choice->nfo_line);
6733 _cur.file->SeekTo(choice->pos, SEEK_SET);
6734 _cur.nfo_line = choice->nfo_line;
6735 return;
6738 grfmsg(2, "SkipIf: Skipping %d sprites, test was true", numsprites);
6739 _cur.skip_sprites = numsprites;
6740 if (_cur.skip_sprites == 0) {
6741 /* Zero means there are no sprites to skip, so
6742 * we use -1 to indicate that all further
6743 * sprites should be skipped. */
6744 _cur.skip_sprites = -1;
6746 /* If an action 8 hasn't been encountered yet, disable the grf. */
6747 if (_cur.grfconfig->status != (_cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED)) {
6748 DisableGrf();
6754 /* Action 0x08 (GLS_FILESCAN) */
6755 static void ScanInfo(ByteReader *buf)
6757 uint8 grf_version = buf->ReadByte();
6758 uint32 grfid = buf->ReadDWord();
6759 const char *name = buf->ReadString();
6761 _cur.grfconfig->ident.grfid = grfid;
6763 if (grf_version < 2 || grf_version > 8) {
6764 SetBit(_cur.grfconfig->flags, GCF_INVALID);
6765 Debug(grf, 0, "{}: NewGRF \"{}\" (GRFID {:08X}) uses GRF version {}, which is incompatible with this version of OpenTTD.", _cur.grfconfig->filename, name, BSWAP32(grfid), grf_version);
6768 /* GRF IDs starting with 0xFF are reserved for internal TTDPatch use */
6769 if (GB(grfid, 0, 8) == 0xFF) SetBit(_cur.grfconfig->flags, GCF_SYSTEM);
6771 AddGRFTextToList(_cur.grfconfig->name, 0x7F, grfid, false, name);
6773 if (buf->HasData()) {
6774 const char *info = buf->ReadString();
6775 AddGRFTextToList(_cur.grfconfig->info, 0x7F, grfid, true, info);
6778 /* GLS_INFOSCAN only looks for the action 8, so we can skip the rest of the file */
6779 _cur.skip_sprites = -1;
6782 /* Action 0x08 */
6783 static void GRFInfo(ByteReader *buf)
6785 /* <08> <version> <grf-id> <name> <info>
6787 * B version newgrf version, currently 06
6788 * 4*B grf-id globally unique ID of this .grf file
6789 * S name name of this .grf set
6790 * S info string describing the set, and e.g. author and copyright */
6792 uint8 version = buf->ReadByte();
6793 uint32 grfid = buf->ReadDWord();
6794 const char *name = buf->ReadString();
6796 if (_cur.stage < GLS_RESERVE && _cur.grfconfig->status != GCS_UNKNOWN) {
6797 DisableGrf(STR_NEWGRF_ERROR_MULTIPLE_ACTION_8);
6798 return;
6801 if (_cur.grffile->grfid != grfid) {
6802 Debug(grf, 0, "GRFInfo: GRFID {:08X} in FILESCAN stage does not match GRFID {:08X} in INIT/RESERVE/ACTIVATION stage", BSWAP32(_cur.grffile->grfid), BSWAP32(grfid));
6803 _cur.grffile->grfid = grfid;
6806 _cur.grffile->grf_version = version;
6807 _cur.grfconfig->status = _cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED;
6809 /* Do swap the GRFID for displaying purposes since people expect that */
6810 Debug(grf, 1, "GRFInfo: Loaded GRFv{} set {:08X} - {} (palette: {}, version: {})", version, BSWAP32(grfid), name, (_cur.grfconfig->palette & GRFP_USE_MASK) ? "Windows" : "DOS", _cur.grfconfig->version);
6813 /* Action 0x0A */
6814 static void SpriteReplace(ByteReader *buf)
6816 /* <0A> <num-sets> <set1> [<set2> ...]
6817 * <set>: <num-sprites> <first-sprite>
6819 * B num-sets How many sets of sprites to replace.
6820 * Each set:
6821 * B num-sprites How many sprites are in this set
6822 * W first-sprite First sprite number to replace */
6824 uint8 num_sets = buf->ReadByte();
6826 for (uint i = 0; i < num_sets; i++) {
6827 uint8 num_sprites = buf->ReadByte();
6828 uint16 first_sprite = buf->ReadWord();
6830 grfmsg(2, "SpriteReplace: [Set %d] Changing %d sprites, beginning with %d",
6831 i, num_sprites, first_sprite
6834 for (uint j = 0; j < num_sprites; j++) {
6835 int load_index = first_sprite + j;
6836 _cur.nfo_line++;
6837 LoadNextSprite(load_index, *_cur.file, _cur.nfo_line); // XXX
6839 /* Shore sprites now located at different addresses.
6840 * So detect when the old ones get replaced. */
6841 if (IsInsideMM(load_index, SPR_ORIGINALSHORE_START, SPR_ORIGINALSHORE_END + 1)) {
6842 if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
6848 /* Action 0x0A (SKIP) */
6849 static void SkipActA(ByteReader *buf)
6851 uint8 num_sets = buf->ReadByte();
6853 for (uint i = 0; i < num_sets; i++) {
6854 /* Skip the sprites this replaces */
6855 _cur.skip_sprites += buf->ReadByte();
6856 /* But ignore where they go */
6857 buf->ReadWord();
6860 grfmsg(3, "SkipActA: Skipping %d sprites", _cur.skip_sprites);
6863 /* Action 0x0B */
6864 static void GRFLoadError(ByteReader *buf)
6866 /* <0B> <severity> <language-id> <message-id> [<message...> 00] [<data...>] 00 [<parnum>]
6868 * B severity 00: notice, continue loading grf file
6869 * 01: warning, continue loading grf file
6870 * 02: error, but continue loading grf file, and attempt
6871 * loading grf again when loading or starting next game
6872 * 03: error, abort loading and prevent loading again in
6873 * the future (only when restarting the patch)
6874 * B language-id see action 4, use 1F for built-in error messages
6875 * B message-id message to show, see below
6876 * S message for custom messages (message-id FF), text of the message
6877 * not present for built-in messages.
6878 * V data additional data for built-in (or custom) messages
6879 * B parnum parameter numbers to be shown in the message (maximum of 2) */
6881 static const StringID msgstr[] = {
6882 STR_NEWGRF_ERROR_VERSION_NUMBER,
6883 STR_NEWGRF_ERROR_DOS_OR_WINDOWS,
6884 STR_NEWGRF_ERROR_UNSET_SWITCH,
6885 STR_NEWGRF_ERROR_INVALID_PARAMETER,
6886 STR_NEWGRF_ERROR_LOAD_BEFORE,
6887 STR_NEWGRF_ERROR_LOAD_AFTER,
6888 STR_NEWGRF_ERROR_OTTD_VERSION_NUMBER,
6891 static const StringID sevstr[] = {
6892 STR_NEWGRF_ERROR_MSG_INFO,
6893 STR_NEWGRF_ERROR_MSG_WARNING,
6894 STR_NEWGRF_ERROR_MSG_ERROR,
6895 STR_NEWGRF_ERROR_MSG_FATAL
6898 byte severity = buf->ReadByte();
6899 byte lang = buf->ReadByte();
6900 byte message_id = buf->ReadByte();
6902 /* Skip the error if it isn't valid for the current language. */
6903 if (!CheckGrfLangID(lang, _cur.grffile->grf_version)) return;
6905 /* Skip the error until the activation stage unless bit 7 of the severity
6906 * is set. */
6907 if (!HasBit(severity, 7) && _cur.stage == GLS_INIT) {
6908 grfmsg(7, "GRFLoadError: Skipping non-fatal GRFLoadError in stage %d", _cur.stage);
6909 return;
6911 ClrBit(severity, 7);
6913 if (severity >= lengthof(sevstr)) {
6914 grfmsg(7, "GRFLoadError: Invalid severity id %d. Setting to 2 (non-fatal error).", severity);
6915 severity = 2;
6916 } else if (severity == 3) {
6917 /* This is a fatal error, so make sure the GRF is deactivated and no
6918 * more of it gets loaded. */
6919 DisableGrf();
6921 /* Make sure we show fatal errors, instead of silly infos from before */
6922 delete _cur.grfconfig->error;
6923 _cur.grfconfig->error = nullptr;
6926 if (message_id >= lengthof(msgstr) && message_id != 0xFF) {
6927 grfmsg(7, "GRFLoadError: Invalid message id.");
6928 return;
6931 if (buf->Remaining() <= 1) {
6932 grfmsg(7, "GRFLoadError: No message data supplied.");
6933 return;
6936 /* For now we can only show one message per newgrf file. */
6937 if (_cur.grfconfig->error != nullptr) return;
6939 GRFError *error = new GRFError(sevstr[severity]);
6941 if (message_id == 0xFF) {
6942 /* This is a custom error message. */
6943 if (buf->HasData()) {
6944 const char *message = buf->ReadString();
6946 error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, SCC_RAW_STRING_POINTER);
6947 } else {
6948 grfmsg(7, "GRFLoadError: No custom message supplied.");
6949 error->custom_message.clear();
6951 } else {
6952 error->message = msgstr[message_id];
6955 if (buf->HasData()) {
6956 const char *data = buf->ReadString();
6958 error->data = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, data);
6959 } else {
6960 grfmsg(7, "GRFLoadError: No message data supplied.");
6961 error->data.clear();
6964 /* Only two parameter numbers can be used in the string. */
6965 for (uint i = 0; i < lengthof(error->param_value) && buf->HasData(); i++) {
6966 uint param_number = buf->ReadByte();
6967 error->param_value[i] = _cur.grffile->GetParam(param_number);
6970 _cur.grfconfig->error = error;
6973 /* Action 0x0C */
6974 static void GRFComment(ByteReader *buf)
6976 /* <0C> [<ignored...>]
6978 * V ignored Anything following the 0C is ignored */
6980 if (!buf->HasData()) return;
6982 const char *text = buf->ReadString();
6983 grfmsg(2, "GRFComment: %s", text);
6986 /* Action 0x0D (GLS_SAFETYSCAN) */
6987 static void SafeParamSet(ByteReader *buf)
6989 uint8 target = buf->ReadByte();
6991 /* Writing GRF parameters and some bits of 'misc GRF features' are safe. */
6992 if (target < 0x80 || target == 0x9E) return;
6994 /* GRM could be unsafe, but as here it can only happen after other GRFs
6995 * are loaded, it should be okay. If the GRF tried to use the slots it
6996 * reserved, it would be marked unsafe anyway. GRM for (e.g. bridge)
6997 * sprites is considered safe. */
6999 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7001 /* Skip remainder of GRF */
7002 _cur.skip_sprites = -1;
7006 static uint32 GetPatchVariable(uint8 param)
7008 switch (param) {
7009 /* start year - 1920 */
7010 case 0x0B: return std::max(_settings_game.game_creation.starting_year, ORIGINAL_BASE_YEAR) - ORIGINAL_BASE_YEAR;
7012 /* freight trains weight factor */
7013 case 0x0E: return _settings_game.vehicle.freight_trains;
7015 /* empty wagon speed increase */
7016 case 0x0F: return 0;
7018 /* plane speed factor; our patch option is reversed from TTDPatch's,
7019 * the following is good for 1x, 2x and 4x (most common?) and...
7020 * well not really for 3x. */
7021 case 0x10:
7022 switch (_settings_game.vehicle.plane_speed) {
7023 default:
7024 case 4: return 1;
7025 case 3: return 2;
7026 case 2: return 2;
7027 case 1: return 4;
7031 /* 2CC colourmap base sprite */
7032 case 0x11: return SPR_2CCMAP_BASE;
7034 /* map size: format = -MABXYSS
7035 * M : the type of map
7036 * bit 0 : set : squared map. Bit 1 is now not relevant
7037 * clear : rectangle map. Bit 1 will indicate the bigger edge of the map
7038 * bit 1 : set : Y is the bigger edge. Bit 0 is clear
7039 * clear : X is the bigger edge.
7040 * A : minimum edge(log2) of the map
7041 * B : maximum edge(log2) of the map
7042 * XY : edges(log2) of each side of the map.
7043 * SS : combination of both X and Y, thus giving the size(log2) of the map
7045 case 0x13: {
7046 byte map_bits = 0;
7047 byte log_X = MapLogX() - 6; // subtraction is required to make the minimal size (64) zero based
7048 byte log_Y = MapLogY() - 6;
7049 byte max_edge = std::max(log_X, log_Y);
7051 if (log_X == log_Y) { // we have a squared map, since both edges are identical
7052 SetBit(map_bits, 0);
7053 } else {
7054 if (max_edge == log_Y) SetBit(map_bits, 1); // edge Y been the biggest, mark it
7057 return (map_bits << 24) | (std::min(log_X, log_Y) << 20) | (max_edge << 16) |
7058 (log_X << 12) | (log_Y << 8) | (log_X + log_Y);
7061 /* The maximum height of the map. */
7062 case 0x14:
7063 return _settings_game.construction.map_height_limit;
7065 /* Extra foundations base sprite */
7066 case 0x15:
7067 return SPR_SLOPES_BASE;
7069 /* Shore base sprite */
7070 case 0x16:
7071 return SPR_SHORE_BASE;
7073 /* Game map seed */
7074 case 0x17:
7075 return _settings_game.game_creation.generation_seed;
7077 default:
7078 grfmsg(2, "ParamSet: Unknown Patch variable 0x%02X.", param);
7079 return 0;
7084 static uint32 PerformGRM(uint32 *grm, uint16 num_ids, uint16 count, uint8 op, uint8 target, const char *type)
7086 uint start = 0;
7087 uint size = 0;
7089 if (op == 6) {
7090 /* Return GRFID of set that reserved ID */
7091 return grm[_cur.grffile->GetParam(target)];
7094 /* With an operation of 2 or 3, we want to reserve a specific block of IDs */
7095 if (op == 2 || op == 3) start = _cur.grffile->GetParam(target);
7097 for (uint i = start; i < num_ids; i++) {
7098 if (grm[i] == 0) {
7099 size++;
7100 } else {
7101 if (op == 2 || op == 3) break;
7102 start = i + 1;
7103 size = 0;
7106 if (size == count) break;
7109 if (size == count) {
7110 /* Got the slot... */
7111 if (op == 0 || op == 3) {
7112 grfmsg(2, "ParamSet: GRM: Reserving %d %s at %d", count, type, start);
7113 for (uint i = 0; i < count; i++) grm[start + i] = _cur.grffile->grfid;
7115 return start;
7118 /* Unable to allocate */
7119 if (op != 4 && op != 5) {
7120 /* Deactivate GRF */
7121 grfmsg(0, "ParamSet: GRM: Unable to allocate %d %s, deactivating", count, type);
7122 DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7123 return UINT_MAX;
7126 grfmsg(1, "ParamSet: GRM: Unable to allocate %d %s", count, type);
7127 return UINT_MAX;
7131 /** Action 0x0D: Set parameter */
7132 static void ParamSet(ByteReader *buf)
7134 /* <0D> <target> <operation> <source1> <source2> [<data>]
7136 * B target parameter number where result is stored
7137 * B operation operation to perform, see below
7138 * B source1 first source operand
7139 * B source2 second source operand
7140 * D data data to use in the calculation, not necessary
7141 * if both source1 and source2 refer to actual parameters
7143 * Operations
7144 * 00 Set parameter equal to source1
7145 * 01 Addition, source1 + source2
7146 * 02 Subtraction, source1 - source2
7147 * 03 Unsigned multiplication, source1 * source2 (both unsigned)
7148 * 04 Signed multiplication, source1 * source2 (both signed)
7149 * 05 Unsigned bit shift, source1 by source2 (source2 taken to be a
7150 * signed quantity; left shift if positive and right shift if
7151 * negative, source1 is unsigned)
7152 * 06 Signed bit shift, source1 by source2
7153 * (source2 like in 05, and source1 as well)
7156 uint8 target = buf->ReadByte();
7157 uint8 oper = buf->ReadByte();
7158 uint32 src1 = buf->ReadByte();
7159 uint32 src2 = buf->ReadByte();
7161 uint32 data = 0;
7162 if (buf->Remaining() >= 4) data = buf->ReadDWord();
7164 /* You can add 80 to the operation to make it apply only if the target
7165 * is not defined yet. In this respect, a parameter is taken to be
7166 * defined if any of the following applies:
7167 * - it has been set to any value in the newgrf(w).cfg parameter list
7168 * - it OR A PARAMETER WITH HIGHER NUMBER has been set to any value by
7169 * an earlier action D */
7170 if (HasBit(oper, 7)) {
7171 if (target < 0x80 && target < _cur.grffile->param_end) {
7172 grfmsg(7, "ParamSet: Param %u already defined, skipping", target);
7173 return;
7176 oper = GB(oper, 0, 7);
7179 if (src2 == 0xFE) {
7180 if (GB(data, 0, 8) == 0xFF) {
7181 if (data == 0x0000FFFF) {
7182 /* Patch variables */
7183 src1 = GetPatchVariable(src1);
7184 } else {
7185 /* GRF Resource Management */
7186 uint8 op = src1;
7187 uint8 feature = GB(data, 8, 8);
7188 uint16 count = GB(data, 16, 16);
7190 if (_cur.stage == GLS_RESERVE) {
7191 if (feature == 0x08) {
7192 /* General sprites */
7193 if (op == 0) {
7194 /* Check if the allocated sprites will fit below the original sprite limit */
7195 if (_cur.spriteid + count >= 16384) {
7196 grfmsg(0, "ParamSet: GRM: Unable to allocate %d sprites; try changing NewGRF order", count);
7197 DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7198 return;
7201 /* Reserve space at the current sprite ID */
7202 grfmsg(4, "ParamSet: GRM: Allocated %d sprites at %d", count, _cur.spriteid);
7203 _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)] = _cur.spriteid;
7204 _cur.spriteid += count;
7207 /* Ignore GRM result during reservation */
7208 src1 = 0;
7209 } else if (_cur.stage == GLS_ACTIVATION) {
7210 switch (feature) {
7211 case 0x00: // Trains
7212 case 0x01: // Road Vehicles
7213 case 0x02: // Ships
7214 case 0x03: // Aircraft
7215 if (!_settings_game.vehicle.dynamic_engines) {
7216 src1 = PerformGRM(&_grm_engines[_engine_offsets[feature]], _engine_counts[feature], count, op, target, "vehicles");
7217 if (_cur.skip_sprites == -1) return;
7218 } else {
7219 /* GRM does not apply for dynamic engine allocation. */
7220 switch (op) {
7221 case 2:
7222 case 3:
7223 src1 = _cur.grffile->GetParam(target);
7224 break;
7226 default:
7227 src1 = 0;
7228 break;
7231 break;
7233 case 0x08: // General sprites
7234 switch (op) {
7235 case 0:
7236 /* Return space reserved during reservation stage */
7237 src1 = _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)];
7238 grfmsg(4, "ParamSet: GRM: Using pre-allocated sprites at %d", src1);
7239 break;
7241 case 1:
7242 src1 = _cur.spriteid;
7243 break;
7245 default:
7246 grfmsg(1, "ParamSet: GRM: Unsupported operation %d for general sprites", op);
7247 return;
7249 break;
7251 case 0x0B: // Cargo
7252 /* There are two ranges: one for cargo IDs and one for cargo bitmasks */
7253 src1 = PerformGRM(_grm_cargoes, NUM_CARGO * 2, count, op, target, "cargoes");
7254 if (_cur.skip_sprites == -1) return;
7255 break;
7257 default: grfmsg(1, "ParamSet: GRM: Unsupported feature 0x%X", feature); return;
7259 } else {
7260 /* Ignore GRM during initialization */
7261 src1 = 0;
7264 } else {
7265 /* Read another GRF File's parameter */
7266 const GRFFile *file = GetFileByGRFID(data);
7267 GRFConfig *c = GetGRFConfig(data);
7268 if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
7269 /* Disable the read GRF if it is a static NewGRF. */
7270 DisableStaticNewGRFInfluencingNonStaticNewGRFs(c);
7271 src1 = 0;
7272 } else if (file == nullptr || c == nullptr || c->status == GCS_DISABLED) {
7273 src1 = 0;
7274 } else if (src1 == 0xFE) {
7275 src1 = c->version;
7276 } else {
7277 src1 = file->GetParam(src1);
7280 } else {
7281 /* The source1 and source2 operands refer to the grf parameter number
7282 * like in action 6 and 7. In addition, they can refer to the special
7283 * variables available in action 7, or they can be FF to use the value
7284 * of <data>. If referring to parameters that are undefined, a value
7285 * of 0 is used instead. */
7286 src1 = (src1 == 0xFF) ? data : GetParamVal(src1, nullptr);
7287 src2 = (src2 == 0xFF) ? data : GetParamVal(src2, nullptr);
7290 uint32 res;
7291 switch (oper) {
7292 case 0x00:
7293 res = src1;
7294 break;
7296 case 0x01:
7297 res = src1 + src2;
7298 break;
7300 case 0x02:
7301 res = src1 - src2;
7302 break;
7304 case 0x03:
7305 res = src1 * src2;
7306 break;
7308 case 0x04:
7309 res = (int32)src1 * (int32)src2;
7310 break;
7312 case 0x05:
7313 if ((int32)src2 < 0) {
7314 res = src1 >> -(int32)src2;
7315 } else {
7316 res = src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7318 break;
7320 case 0x06:
7321 if ((int32)src2 < 0) {
7322 res = (int32)src1 >> -(int32)src2;
7323 } else {
7324 res = (int32)src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7326 break;
7328 case 0x07: // Bitwise AND
7329 res = src1 & src2;
7330 break;
7332 case 0x08: // Bitwise OR
7333 res = src1 | src2;
7334 break;
7336 case 0x09: // Unsigned division
7337 if (src2 == 0) {
7338 res = src1;
7339 } else {
7340 res = src1 / src2;
7342 break;
7344 case 0x0A: // Signed division
7345 if (src2 == 0) {
7346 res = src1;
7347 } else {
7348 res = (int32)src1 / (int32)src2;
7350 break;
7352 case 0x0B: // Unsigned modulo
7353 if (src2 == 0) {
7354 res = src1;
7355 } else {
7356 res = src1 % src2;
7358 break;
7360 case 0x0C: // Signed modulo
7361 if (src2 == 0) {
7362 res = src1;
7363 } else {
7364 res = (int32)src1 % (int32)src2;
7366 break;
7368 default: grfmsg(0, "ParamSet: Unknown operation %d, skipping", oper); return;
7371 switch (target) {
7372 case 0x8E: // Y-Offset for train sprites
7373 _cur.grffile->traininfo_vehicle_pitch = res;
7374 break;
7376 case 0x8F: { // Rail track type cost factors
7377 extern RailtypeInfo _railtypes[RAILTYPE_END];
7378 _railtypes[RAILTYPE_RAIL].cost_multiplier = GB(res, 0, 8);
7379 if (_settings_game.vehicle.disable_elrails) {
7380 _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 0, 8);
7381 _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 8, 8);
7382 } else {
7383 _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 8, 8);
7384 _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 16, 8);
7386 _railtypes[RAILTYPE_MAGLEV].cost_multiplier = GB(res, 16, 8);
7387 break;
7390 /* not implemented */
7391 case 0x93: // Tile refresh offset to left -- Intended to allow support for larger sprites, not necessary for OTTD
7392 case 0x94: // Tile refresh offset to right
7393 case 0x95: // Tile refresh offset upwards
7394 case 0x96: // Tile refresh offset downwards
7395 case 0x97: // Snow line height -- Better supported by feature 8 property 10h (snow line table) TODO: implement by filling the entire snow line table with the given value
7396 case 0x99: // Global ID offset -- Not necessary since IDs are remapped automatically
7397 grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
7398 break;
7400 case 0x9E: // Miscellaneous GRF features
7401 /* Set train list engine width */
7402 _cur.grffile->traininfo_vehicle_width = HasBit(res, GMB_TRAIN_WIDTH_32_PIXELS) ? VEHICLEINFO_FULL_VEHICLE_WIDTH : TRAININFO_DEFAULT_VEHICLE_WIDTH;
7403 /* Remove the local flags from the global flags */
7404 ClrBit(res, GMB_TRAIN_WIDTH_32_PIXELS);
7406 /* Only copy safe bits for static grfs */
7407 if (HasBit(_cur.grfconfig->flags, GCF_STATIC)) {
7408 uint32 safe_bits = 0;
7409 SetBit(safe_bits, GMB_SECOND_ROCKY_TILE_SET);
7411 _misc_grf_features = (_misc_grf_features & ~safe_bits) | (res & safe_bits);
7412 } else {
7413 _misc_grf_features = res;
7415 break;
7417 case 0x9F: // locale-dependent settings
7418 grfmsg(7, "ParamSet: Skipping unimplemented target 0x%02X", target);
7419 break;
7421 default:
7422 if (target < 0x80) {
7423 _cur.grffile->param[target] = res;
7424 /* param is zeroed by default */
7425 if (target + 1U > _cur.grffile->param_end) _cur.grffile->param_end = target + 1;
7426 } else {
7427 grfmsg(7, "ParamSet: Skipping unknown target 0x%02X", target);
7429 break;
7433 /* Action 0x0E (GLS_SAFETYSCAN) */
7434 static void SafeGRFInhibit(ByteReader *buf)
7436 /* <0E> <num> <grfids...>
7438 * B num Number of GRFIDs that follow
7439 * D grfids GRFIDs of the files to deactivate */
7441 uint8 num = buf->ReadByte();
7443 for (uint i = 0; i < num; i++) {
7444 uint32 grfid = buf->ReadDWord();
7446 /* GRF is unsafe it if tries to deactivate other GRFs */
7447 if (grfid != _cur.grfconfig->ident.grfid) {
7448 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7450 /* Skip remainder of GRF */
7451 _cur.skip_sprites = -1;
7453 return;
7458 /* Action 0x0E */
7459 static void GRFInhibit(ByteReader *buf)
7461 /* <0E> <num> <grfids...>
7463 * B num Number of GRFIDs that follow
7464 * D grfids GRFIDs of the files to deactivate */
7466 uint8 num = buf->ReadByte();
7468 for (uint i = 0; i < num; i++) {
7469 uint32 grfid = buf->ReadDWord();
7470 GRFConfig *file = GetGRFConfig(grfid);
7472 /* Unset activation flag */
7473 if (file != nullptr && file != _cur.grfconfig) {
7474 grfmsg(2, "GRFInhibit: Deactivating file '%s'", file->filename);
7475 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED, file);
7476 error->data = _cur.grfconfig->GetName();
7481 /** Action 0x0F - Define Town names */
7482 static void FeatureTownName(ByteReader *buf)
7484 /* <0F> <id> <style-name> <num-parts> <parts>
7486 * B id ID of this definition in bottom 7 bits (final definition if bit 7 set)
7487 * V style-name Name of the style (only for final definition)
7488 * B num-parts Number of parts in this definition
7489 * V parts The parts */
7491 uint32 grfid = _cur.grffile->grfid;
7493 GRFTownName *townname = AddGRFTownName(grfid);
7495 byte id = buf->ReadByte();
7496 grfmsg(6, "FeatureTownName: definition 0x%02X", id & 0x7F);
7498 if (HasBit(id, 7)) {
7499 /* Final definition */
7500 ClrBit(id, 7);
7501 bool new_scheme = _cur.grffile->grf_version >= 7;
7503 byte lang = buf->ReadByte();
7505 byte nb_gen = townname->nb_gen;
7506 do {
7507 ClrBit(lang, 7);
7509 const char *name = buf->ReadString();
7511 std::string lang_name = TranslateTTDPatchCodes(grfid, lang, false, name);
7512 grfmsg(6, "FeatureTownName: lang 0x%X -> '%s'", lang, lang_name.c_str());
7514 townname->name[nb_gen] = AddGRFString(grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
7516 lang = buf->ReadByte();
7517 } while (lang != 0);
7518 townname->id[nb_gen] = id;
7519 townname->nb_gen++;
7522 byte nb = buf->ReadByte();
7523 grfmsg(6, "FeatureTownName: %u parts", nb);
7525 townname->nbparts[id] = nb;
7526 townname->partlist[id] = CallocT<NamePartList>(nb);
7528 for (int i = 0; i < nb; i++) {
7529 byte nbtext = buf->ReadByte();
7530 townname->partlist[id][i].bitstart = buf->ReadByte();
7531 townname->partlist[id][i].bitcount = buf->ReadByte();
7532 townname->partlist[id][i].maxprob = 0;
7533 townname->partlist[id][i].partcount = nbtext;
7534 townname->partlist[id][i].parts = CallocT<NamePart>(nbtext);
7535 grfmsg(6, "FeatureTownName: part %d contains %d texts and will use GB(seed, %d, %d)", i, nbtext, townname->partlist[id][i].bitstart, townname->partlist[id][i].bitcount);
7537 for (int j = 0; j < nbtext; j++) {
7538 byte prob = buf->ReadByte();
7540 if (HasBit(prob, 7)) {
7541 byte ref_id = buf->ReadByte();
7543 if (townname->nbparts[ref_id] == 0) {
7544 grfmsg(0, "FeatureTownName: definition 0x%02X doesn't exist, deactivating", ref_id);
7545 DelGRFTownName(grfid);
7546 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
7547 return;
7550 grfmsg(6, "FeatureTownName: part %d, text %d, uses intermediate definition 0x%02X (with probability %d)", i, j, ref_id, prob & 0x7F);
7551 townname->partlist[id][i].parts[j].data.id = ref_id;
7552 } else {
7553 const char *text = buf->ReadString();
7554 townname->partlist[id][i].parts[j].data.text = stredup(TranslateTTDPatchCodes(grfid, 0, false, text).c_str());
7555 grfmsg(6, "FeatureTownName: part %d, text %d, '%s' (with probability %d)", i, j, townname->partlist[id][i].parts[j].data.text, prob);
7557 townname->partlist[id][i].parts[j].prob = prob;
7558 townname->partlist[id][i].maxprob += GB(prob, 0, 7);
7560 grfmsg(6, "FeatureTownName: part %d, total probability %d", i, townname->partlist[id][i].maxprob);
7564 /** Action 0x10 - Define goto label */
7565 static void DefineGotoLabel(ByteReader *buf)
7567 /* <10> <label> [<comment>]
7569 * B label The label to define
7570 * V comment Optional comment - ignored */
7572 byte nfo_label = buf->ReadByte();
7574 GRFLabel *label = MallocT<GRFLabel>(1);
7575 label->label = nfo_label;
7576 label->nfo_line = _cur.nfo_line;
7577 label->pos = _cur.file->GetPos();
7578 label->next = nullptr;
7580 /* Set up a linked list of goto targets which we will search in an Action 0x7/0x9 */
7581 if (_cur.grffile->label == nullptr) {
7582 _cur.grffile->label = label;
7583 } else {
7584 /* Attach the label to the end of the list */
7585 GRFLabel *l;
7586 for (l = _cur.grffile->label; l->next != nullptr; l = l->next) {}
7587 l->next = label;
7590 grfmsg(2, "DefineGotoLabel: GOTO target with label 0x%02X", label->label);
7594 * Process a sound import from another GRF file.
7595 * @param sound Destination for sound.
7597 static void ImportGRFSound(SoundEntry *sound)
7599 const GRFFile *file;
7600 uint32 grfid = _cur.file->ReadDword();
7601 SoundID sound_id = _cur.file->ReadWord();
7603 file = GetFileByGRFID(grfid);
7604 if (file == nullptr || file->sound_offset == 0) {
7605 grfmsg(1, "ImportGRFSound: Source file not available");
7606 return;
7609 if (sound_id >= file->num_sounds) {
7610 grfmsg(1, "ImportGRFSound: Sound effect %d is invalid", sound_id);
7611 return;
7614 grfmsg(2, "ImportGRFSound: Copying sound %d (%d) from file %X", sound_id, file->sound_offset + sound_id, grfid);
7616 *sound = *GetSound(file->sound_offset + sound_id);
7618 /* Reset volume and priority, which TTDPatch doesn't copy */
7619 sound->volume = 128;
7620 sound->priority = 0;
7624 * Load a sound from a file.
7625 * @param offs File offset to read sound from.
7626 * @param sound Destination for sound.
7628 static void LoadGRFSound(size_t offs, SoundEntry *sound)
7630 /* Set default volume and priority */
7631 sound->volume = 0x80;
7632 sound->priority = 0;
7634 if (offs != SIZE_MAX) {
7635 /* Sound is present in the NewGRF. */
7636 sound->file = _cur.file;
7637 sound->file_offset = offs;
7638 sound->grf_container_ver = _cur.file->GetContainerVersion();
7642 /* Action 0x11 */
7643 static void GRFSound(ByteReader *buf)
7645 /* <11> <num>
7647 * W num Number of sound files that follow */
7649 uint16 num = buf->ReadWord();
7650 if (num == 0) return;
7652 SoundEntry *sound;
7653 if (_cur.grffile->sound_offset == 0) {
7654 _cur.grffile->sound_offset = GetNumSounds();
7655 _cur.grffile->num_sounds = num;
7656 sound = AllocateSound(num);
7657 } else {
7658 sound = GetSound(_cur.grffile->sound_offset);
7661 SpriteFile &file = *_cur.file;
7662 byte grf_container_version = file.GetContainerVersion();
7663 for (int i = 0; i < num; i++) {
7664 _cur.nfo_line++;
7666 /* Check whether the index is in range. This might happen if multiple action 11 are present.
7667 * While this is invalid, we do not check for this. But we should prevent it from causing bigger trouble */
7668 bool invalid = i >= _cur.grffile->num_sounds;
7670 size_t offs = file.GetPos();
7672 uint32 len = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
7673 byte type = file.ReadByte();
7675 if (grf_container_version >= 2 && type == 0xFD) {
7676 /* Reference to sprite section. */
7677 if (invalid) {
7678 grfmsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7679 file.SkipBytes(len);
7680 } else if (len != 4) {
7681 grfmsg(1, "GRFSound: Invalid sprite section import");
7682 file.SkipBytes(len);
7683 } else {
7684 uint32 id = file.ReadDword();
7685 if (_cur.stage == GLS_INIT) LoadGRFSound(GetGRFSpriteOffset(id), sound + i);
7687 continue;
7690 if (type != 0xFF) {
7691 grfmsg(1, "GRFSound: Unexpected RealSprite found, skipping");
7692 file.SkipBytes(7);
7693 SkipSpriteData(*_cur.file, type, len - 8);
7694 continue;
7697 if (invalid) {
7698 grfmsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7699 file.SkipBytes(len);
7702 byte action = file.ReadByte();
7703 switch (action) {
7704 case 0xFF:
7705 /* Allocate sound only in init stage. */
7706 if (_cur.stage == GLS_INIT) {
7707 if (grf_container_version >= 2) {
7708 grfmsg(1, "GRFSound: Inline sounds are not supported for container version >= 2");
7709 } else {
7710 LoadGRFSound(offs, sound + i);
7713 file.SkipBytes(len - 1); // already read <action>
7714 break;
7716 case 0xFE:
7717 if (_cur.stage == GLS_ACTIVATION) {
7718 /* XXX 'Action 0xFE' isn't really specified. It is only mentioned for
7719 * importing sounds, so this is probably all wrong... */
7720 if (file.ReadByte() != 0) grfmsg(1, "GRFSound: Import type mismatch");
7721 ImportGRFSound(sound + i);
7722 } else {
7723 file.SkipBytes(len - 1); // already read <action>
7725 break;
7727 default:
7728 grfmsg(1, "GRFSound: Unexpected Action %x found, skipping", action);
7729 file.SkipBytes(len - 1); // already read <action>
7730 break;
7735 /* Action 0x11 (SKIP) */
7736 static void SkipAct11(ByteReader *buf)
7738 /* <11> <num>
7740 * W num Number of sound files that follow */
7742 _cur.skip_sprites = buf->ReadWord();
7744 grfmsg(3, "SkipAct11: Skipping %d sprites", _cur.skip_sprites);
7747 /** Action 0x12 */
7748 static void LoadFontGlyph(ByteReader *buf)
7750 /* <12> <num_def> <font_size> <num_char> <base_char>
7752 * B num_def Number of definitions
7753 * B font_size Size of font (0 = normal, 1 = small, 2 = large, 3 = mono)
7754 * B num_char Number of consecutive glyphs
7755 * W base_char First character index */
7757 uint8 num_def = buf->ReadByte();
7759 for (uint i = 0; i < num_def; i++) {
7760 FontSize size = (FontSize)buf->ReadByte();
7761 uint8 num_char = buf->ReadByte();
7762 uint16 base_char = buf->ReadWord();
7764 if (size >= FS_END) {
7765 grfmsg(1, "LoadFontGlyph: Size %u is not supported, ignoring", size);
7768 grfmsg(7, "LoadFontGlyph: Loading %u glyph(s) at 0x%04X for size %u", num_char, base_char, size);
7770 for (uint c = 0; c < num_char; c++) {
7771 if (size < FS_END) SetUnicodeGlyph(size, base_char + c, _cur.spriteid);
7772 _cur.nfo_line++;
7773 LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
7778 /** Action 0x12 (SKIP) */
7779 static void SkipAct12(ByteReader *buf)
7781 /* <12> <num_def> <font_size> <num_char> <base_char>
7783 * B num_def Number of definitions
7784 * B font_size Size of font (0 = normal, 1 = small, 2 = large)
7785 * B num_char Number of consecutive glyphs
7786 * W base_char First character index */
7788 uint8 num_def = buf->ReadByte();
7790 for (uint i = 0; i < num_def; i++) {
7791 /* Ignore 'size' byte */
7792 buf->ReadByte();
7794 /* Sum up number of characters */
7795 _cur.skip_sprites += buf->ReadByte();
7797 /* Ignore 'base_char' word */
7798 buf->ReadWord();
7801 grfmsg(3, "SkipAct12: Skipping %d sprites", _cur.skip_sprites);
7804 /** Action 0x13 */
7805 static void TranslateGRFStrings(ByteReader *buf)
7807 /* <13> <grfid> <num-ent> <offset> <text...>
7809 * 4*B grfid The GRFID of the file whose texts are to be translated
7810 * B num-ent Number of strings
7811 * W offset First text ID
7812 * S text... Zero-terminated strings */
7814 uint32 grfid = buf->ReadDWord();
7815 const GRFConfig *c = GetGRFConfig(grfid);
7816 if (c == nullptr || (c->status != GCS_INITIALISED && c->status != GCS_ACTIVATED)) {
7817 grfmsg(7, "TranslateGRFStrings: GRFID 0x%08x unknown, skipping action 13", BSWAP32(grfid));
7818 return;
7821 if (c->status == GCS_INITIALISED) {
7822 /* If the file is not active but will be activated later, give an error
7823 * and disable this file. */
7824 GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LOAD_AFTER);
7826 error->data = GetString(STR_NEWGRF_ERROR_AFTER_TRANSLATED_FILE);
7828 return;
7831 /* Since no language id is supplied for with version 7 and lower NewGRFs, this string has
7832 * to be added as a generic string, thus the language id of 0x7F. For this to work
7833 * new_scheme has to be true as well, which will also be implicitly the case for version 8
7834 * and higher. A language id of 0x7F will be overridden by a non-generic id, so this will
7835 * not change anything if a string has been provided specifically for this language. */
7836 byte language = _cur.grffile->grf_version >= 8 ? buf->ReadByte() : 0x7F;
7837 byte num_strings = buf->ReadByte();
7838 uint16 first_id = buf->ReadWord();
7840 if (!((first_id >= 0xD000 && first_id + num_strings <= 0xD400) || (first_id >= 0xD800 && first_id + num_strings <= 0xE000))) {
7841 grfmsg(7, "TranslateGRFStrings: Attempting to set out-of-range string IDs in action 13 (first: 0x%4X, number: 0x%2X)", first_id, num_strings);
7842 return;
7845 for (uint i = 0; i < num_strings && buf->HasData(); i++) {
7846 const char *string = buf->ReadString();
7848 if (StrEmpty(string)) {
7849 grfmsg(7, "TranslateGRFString: Ignoring empty string.");
7850 continue;
7853 AddGRFString(grfid, first_id + i, language, true, true, string, STR_UNDEFINED);
7857 /** Callback function for 'INFO'->'NAME' to add a translation to the newgrf name. */
7858 static bool ChangeGRFName(byte langid, const char *str)
7860 AddGRFTextToList(_cur.grfconfig->name, langid, _cur.grfconfig->ident.grfid, false, str);
7861 return true;
7864 /** Callback function for 'INFO'->'DESC' to add a translation to the newgrf description. */
7865 static bool ChangeGRFDescription(byte langid, const char *str)
7867 AddGRFTextToList(_cur.grfconfig->info, langid, _cur.grfconfig->ident.grfid, true, str);
7868 return true;
7871 /** Callback function for 'INFO'->'URL_' to set the newgrf url. */
7872 static bool ChangeGRFURL(byte langid, const char *str)
7874 AddGRFTextToList(_cur.grfconfig->url, langid, _cur.grfconfig->ident.grfid, false, str);
7875 return true;
7878 /** Callback function for 'INFO'->'NPAR' to set the number of valid parameters. */
7879 static bool ChangeGRFNumUsedParams(size_t len, ByteReader *buf)
7881 if (len != 1) {
7882 grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'NPAR' but got " PRINTF_SIZE ", ignoring this field", len);
7883 buf->Skip(len);
7884 } else {
7885 _cur.grfconfig->num_valid_params = std::min<byte>(buf->ReadByte(), lengthof(_cur.grfconfig->param));
7887 return true;
7890 /** Callback function for 'INFO'->'PALS' to set the number of valid parameters. */
7891 static bool ChangeGRFPalette(size_t len, ByteReader *buf)
7893 if (len != 1) {
7894 grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'PALS' but got " PRINTF_SIZE ", ignoring this field", len);
7895 buf->Skip(len);
7896 } else {
7897 char data = buf->ReadByte();
7898 GRFPalette pal = GRFP_GRF_UNSET;
7899 switch (data) {
7900 case '*':
7901 case 'A': pal = GRFP_GRF_ANY; break;
7902 case 'W': pal = GRFP_GRF_WINDOWS; break;
7903 case 'D': pal = GRFP_GRF_DOS; break;
7904 default:
7905 grfmsg(2, "StaticGRFInfo: unexpected value '%02x' for 'INFO'->'PALS', ignoring this field", data);
7906 break;
7908 if (pal != GRFP_GRF_UNSET) {
7909 _cur.grfconfig->palette &= ~GRFP_GRF_MASK;
7910 _cur.grfconfig->palette |= pal;
7913 return true;
7916 /** Callback function for 'INFO'->'BLTR' to set the blitter info. */
7917 static bool ChangeGRFBlitter(size_t len, ByteReader *buf)
7919 if (len != 1) {
7920 grfmsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'BLTR' but got " PRINTF_SIZE ", ignoring this field", len);
7921 buf->Skip(len);
7922 } else {
7923 char data = buf->ReadByte();
7924 GRFPalette pal = GRFP_BLT_UNSET;
7925 switch (data) {
7926 case '8': pal = GRFP_BLT_UNSET; break;
7927 case '3': pal = GRFP_BLT_32BPP; break;
7928 default:
7929 grfmsg(2, "StaticGRFInfo: unexpected value '%02x' for 'INFO'->'BLTR', ignoring this field", data);
7930 return true;
7932 _cur.grfconfig->palette &= ~GRFP_BLT_MASK;
7933 _cur.grfconfig->palette |= pal;
7935 return true;
7938 /** Callback function for 'INFO'->'VRSN' to the version of the NewGRF. */
7939 static bool ChangeGRFVersion(size_t len, ByteReader *buf)
7941 if (len != 4) {
7942 grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'VRSN' but got " PRINTF_SIZE ", ignoring this field", len);
7943 buf->Skip(len);
7944 } else {
7945 /* Set min_loadable_version as well (default to minimal compatibility) */
7946 _cur.grfconfig->version = _cur.grfconfig->min_loadable_version = buf->ReadDWord();
7948 return true;
7951 /** Callback function for 'INFO'->'MINV' to the minimum compatible version of the NewGRF. */
7952 static bool ChangeGRFMinVersion(size_t len, ByteReader *buf)
7954 if (len != 4) {
7955 grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'MINV' but got " PRINTF_SIZE ", ignoring this field", len);
7956 buf->Skip(len);
7957 } else {
7958 _cur.grfconfig->min_loadable_version = buf->ReadDWord();
7959 if (_cur.grfconfig->version == 0) {
7960 grfmsg(2, "StaticGRFInfo: 'MINV' defined before 'VRSN' or 'VRSN' set to 0, ignoring this field");
7961 _cur.grfconfig->min_loadable_version = 0;
7963 if (_cur.grfconfig->version < _cur.grfconfig->min_loadable_version) {
7964 grfmsg(2, "StaticGRFInfo: 'MINV' defined as %d, limiting it to 'VRSN'", _cur.grfconfig->min_loadable_version);
7965 _cur.grfconfig->min_loadable_version = _cur.grfconfig->version;
7968 return true;
7971 static GRFParameterInfo *_cur_parameter; ///< The parameter which info is currently changed by the newgrf.
7973 /** Callback function for 'INFO'->'PARAM'->param_num->'NAME' to set the name of a parameter. */
7974 static bool ChangeGRFParamName(byte langid, const char *str)
7976 AddGRFTextToList(_cur_parameter->name, langid, _cur.grfconfig->ident.grfid, false, str);
7977 return true;
7980 /** Callback function for 'INFO'->'PARAM'->param_num->'DESC' to set the description of a parameter. */
7981 static bool ChangeGRFParamDescription(byte langid, const char *str)
7983 AddGRFTextToList(_cur_parameter->desc, langid, _cur.grfconfig->ident.grfid, true, str);
7984 return true;
7987 /** Callback function for 'INFO'->'PARAM'->param_num->'TYPE' to set the typeof a parameter. */
7988 static bool ChangeGRFParamType(size_t len, ByteReader *buf)
7990 if (len != 1) {
7991 grfmsg(2, "StaticGRFInfo: expected 1 byte for 'INFO'->'PARA'->'TYPE' but got " PRINTF_SIZE ", ignoring this field", len);
7992 buf->Skip(len);
7993 } else {
7994 GRFParameterType type = (GRFParameterType)buf->ReadByte();
7995 if (type < PTYPE_END) {
7996 _cur_parameter->type = type;
7997 } else {
7998 grfmsg(3, "StaticGRFInfo: unknown parameter type %d, ignoring this field", type);
8001 return true;
8004 /** Callback function for 'INFO'->'PARAM'->param_num->'LIMI' to set the min/max value of a parameter. */
8005 static bool ChangeGRFParamLimits(size_t len, ByteReader *buf)
8007 if (_cur_parameter->type != PTYPE_UINT_ENUM) {
8008 grfmsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' is only valid for parameters with type uint/enum, ignoring this field");
8009 buf->Skip(len);
8010 } else if (len != 8) {
8011 grfmsg(2, "StaticGRFInfo: expected 8 bytes for 'INFO'->'PARA'->'LIMI' but got " PRINTF_SIZE ", ignoring this field", len);
8012 buf->Skip(len);
8013 } else {
8014 uint32 min_value = buf->ReadDWord();
8015 uint32 max_value = buf->ReadDWord();
8016 if (min_value <= max_value) {
8017 _cur_parameter->min_value = min_value;
8018 _cur_parameter->max_value = max_value;
8019 } else {
8020 grfmsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' values are incoherent, ignoring this field");
8023 return true;
8026 /** Callback function for 'INFO'->'PARAM'->param_num->'MASK' to set the parameter and bits to use. */
8027 static bool ChangeGRFParamMask(size_t len, ByteReader *buf)
8029 if (len < 1 || len > 3) {
8030 grfmsg(2, "StaticGRFInfo: expected 1 to 3 bytes for 'INFO'->'PARA'->'MASK' but got " PRINTF_SIZE ", ignoring this field", len);
8031 buf->Skip(len);
8032 } else {
8033 byte param_nr = buf->ReadByte();
8034 if (param_nr >= lengthof(_cur.grfconfig->param)) {
8035 grfmsg(2, "StaticGRFInfo: invalid parameter number in 'INFO'->'PARA'->'MASK', param %d, ignoring this field", param_nr);
8036 buf->Skip(len - 1);
8037 } else {
8038 _cur_parameter->param_nr = param_nr;
8039 if (len >= 2) _cur_parameter->first_bit = std::min<byte>(buf->ReadByte(), 31);
8040 if (len >= 3) _cur_parameter->num_bit = std::min<byte>(buf->ReadByte(), 32 - _cur_parameter->first_bit);
8044 return true;
8047 /** Callback function for 'INFO'->'PARAM'->param_num->'DFLT' to set the default value. */
8048 static bool ChangeGRFParamDefault(size_t len, ByteReader *buf)
8050 if (len != 4) {
8051 grfmsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'PARA'->'DEFA' but got " PRINTF_SIZE ", ignoring this field", len);
8052 buf->Skip(len);
8053 } else {
8054 _cur_parameter->def_value = buf->ReadDWord();
8056 _cur.grfconfig->has_param_defaults = true;
8057 return true;
8060 typedef bool (*DataHandler)(size_t, ByteReader *); ///< Type of callback function for binary nodes
8061 typedef bool (*TextHandler)(byte, const char *str); ///< Type of callback function for text nodes
8062 typedef bool (*BranchHandler)(ByteReader *); ///< Type of callback function for branch nodes
8065 * Data structure to store the allowed id/type combinations for action 14. The
8066 * data can be represented as a tree with 3 types of nodes:
8067 * 1. Branch nodes (identified by 'C' for choice).
8068 * 2. Binary leaf nodes (identified by 'B').
8069 * 3. Text leaf nodes (identified by 'T').
8071 struct AllowedSubtags {
8072 /** Create empty subtags object used to identify the end of a list. */
8073 AllowedSubtags() :
8074 id(0),
8075 type(0)
8079 * Create a binary leaf node.
8080 * @param id The id for this node.
8081 * @param handler The callback function to call.
8083 AllowedSubtags(uint32 id, DataHandler handler) :
8084 id(id),
8085 type('B')
8087 this->handler.data = handler;
8091 * Create a text leaf node.
8092 * @param id The id for this node.
8093 * @param handler The callback function to call.
8095 AllowedSubtags(uint32 id, TextHandler handler) :
8096 id(id),
8097 type('T')
8099 this->handler.text = handler;
8103 * Create a branch node with a callback handler
8104 * @param id The id for this node.
8105 * @param handler The callback function to call.
8107 AllowedSubtags(uint32 id, BranchHandler handler) :
8108 id(id),
8109 type('C')
8111 this->handler.call_handler = true;
8112 this->handler.u.branch = handler;
8116 * Create a branch node with a list of sub-nodes.
8117 * @param id The id for this node.
8118 * @param subtags Array with all valid subtags.
8120 AllowedSubtags(uint32 id, AllowedSubtags *subtags) :
8121 id(id),
8122 type('C')
8124 this->handler.call_handler = false;
8125 this->handler.u.subtags = subtags;
8128 uint32 id; ///< The identifier for this node
8129 byte type; ///< The type of the node, must be one of 'C', 'B' or 'T'.
8130 union {
8131 DataHandler data; ///< Callback function for a binary node, only valid if type == 'B'.
8132 TextHandler text; ///< Callback function for a text node, only valid if type == 'T'.
8133 struct {
8134 union {
8135 BranchHandler branch; ///< Callback function for a branch node, only valid if type == 'C' && call_handler.
8136 AllowedSubtags *subtags; ///< Pointer to a list of subtags, only valid if type == 'C' && !call_handler.
8137 } u;
8138 bool call_handler; ///< True if there is a callback function for this node, false if there is a list of subnodes.
8140 } handler;
8143 static bool SkipUnknownInfo(ByteReader *buf, byte type);
8144 static bool HandleNodes(ByteReader *buf, AllowedSubtags *tags);
8147 * Callback function for 'INFO'->'PARA'->param_num->'VALU' to set the names
8148 * of some parameter values (type uint/enum) or the names of some bits
8149 * (type bitmask). In both cases the format is the same:
8150 * Each subnode should be a text node with the value/bit number as id.
8152 static bool ChangeGRFParamValueNames(ByteReader *buf)
8154 byte type = buf->ReadByte();
8155 while (type != 0) {
8156 uint32 id = buf->ReadDWord();
8157 if (type != 'T' || id > _cur_parameter->max_value) {
8158 grfmsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA'->param_num->'VALU' should have type 't' and the value/bit number as id");
8159 if (!SkipUnknownInfo(buf, type)) return false;
8160 type = buf->ReadByte();
8161 continue;
8164 byte langid = buf->ReadByte();
8165 const char *name_string = buf->ReadString();
8167 std::pair<uint32, GRFTextList> *val_name = _cur_parameter->value_names.Find(id);
8168 if (val_name != _cur_parameter->value_names.End()) {
8169 AddGRFTextToList(val_name->second, langid, _cur.grfconfig->ident.grfid, false, name_string);
8170 } else {
8171 GRFTextList list;
8172 AddGRFTextToList(list, langid, _cur.grfconfig->ident.grfid, false, name_string);
8173 _cur_parameter->value_names.Insert(id, list);
8176 type = buf->ReadByte();
8178 return true;
8181 /** Action14 parameter tags */
8182 AllowedSubtags _tags_parameters[] = {
8183 AllowedSubtags('NAME', ChangeGRFParamName),
8184 AllowedSubtags('DESC', ChangeGRFParamDescription),
8185 AllowedSubtags('TYPE', ChangeGRFParamType),
8186 AllowedSubtags('LIMI', ChangeGRFParamLimits),
8187 AllowedSubtags('MASK', ChangeGRFParamMask),
8188 AllowedSubtags('VALU', ChangeGRFParamValueNames),
8189 AllowedSubtags('DFLT', ChangeGRFParamDefault),
8190 AllowedSubtags()
8194 * Callback function for 'INFO'->'PARA' to set extra information about the
8195 * parameters. Each subnode of 'INFO'->'PARA' should be a branch node with
8196 * the parameter number as id. The first parameter has id 0. The maximum
8197 * parameter that can be changed is set by 'INFO'->'NPAR' which defaults to 80.
8199 static bool HandleParameterInfo(ByteReader *buf)
8201 byte type = buf->ReadByte();
8202 while (type != 0) {
8203 uint32 id = buf->ReadDWord();
8204 if (type != 'C' || id >= _cur.grfconfig->num_valid_params) {
8205 grfmsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA' should have type 'C' and their parameter number as id");
8206 if (!SkipUnknownInfo(buf, type)) return false;
8207 type = buf->ReadByte();
8208 continue;
8211 if (id >= _cur.grfconfig->param_info.size()) {
8212 _cur.grfconfig->param_info.resize(id + 1);
8214 if (_cur.grfconfig->param_info[id] == nullptr) {
8215 _cur.grfconfig->param_info[id] = new GRFParameterInfo(id);
8217 _cur_parameter = _cur.grfconfig->param_info[id];
8218 /* Read all parameter-data and process each node. */
8219 if (!HandleNodes(buf, _tags_parameters)) return false;
8220 type = buf->ReadByte();
8222 return true;
8225 /** Action14 tags for the INFO node */
8226 AllowedSubtags _tags_info[] = {
8227 AllowedSubtags('NAME', ChangeGRFName),
8228 AllowedSubtags('DESC', ChangeGRFDescription),
8229 AllowedSubtags('URL_', ChangeGRFURL),
8230 AllowedSubtags('NPAR', ChangeGRFNumUsedParams),
8231 AllowedSubtags('PALS', ChangeGRFPalette),
8232 AllowedSubtags('BLTR', ChangeGRFBlitter),
8233 AllowedSubtags('VRSN', ChangeGRFVersion),
8234 AllowedSubtags('MINV', ChangeGRFMinVersion),
8235 AllowedSubtags('PARA', HandleParameterInfo),
8236 AllowedSubtags()
8239 /** Action14 root tags */
8240 AllowedSubtags _tags_root[] = {
8241 AllowedSubtags('INFO', _tags_info),
8242 AllowedSubtags()
8247 * Try to skip the current node and all subnodes (if it's a branch node).
8248 * @param buf Buffer.
8249 * @param type The node type to skip.
8250 * @return True if we could skip the node, false if an error occurred.
8252 static bool SkipUnknownInfo(ByteReader *buf, byte type)
8254 /* type and id are already read */
8255 switch (type) {
8256 case 'C': {
8257 byte new_type = buf->ReadByte();
8258 while (new_type != 0) {
8259 buf->ReadDWord(); // skip the id
8260 if (!SkipUnknownInfo(buf, new_type)) return false;
8261 new_type = buf->ReadByte();
8263 break;
8266 case 'T':
8267 buf->ReadByte(); // lang
8268 buf->ReadString(); // actual text
8269 break;
8271 case 'B': {
8272 uint16 size = buf->ReadWord();
8273 buf->Skip(size);
8274 break;
8277 default:
8278 return false;
8281 return true;
8285 * Handle the nodes of an Action14
8286 * @param type Type of node.
8287 * @param id ID.
8288 * @param buf Buffer.
8289 * @param subtags Allowed subtags.
8290 * @return Whether all tags could be handled.
8292 static bool HandleNode(byte type, uint32 id, ByteReader *buf, AllowedSubtags subtags[])
8294 uint i = 0;
8295 AllowedSubtags *tag;
8296 while ((tag = &subtags[i++])->type != 0) {
8297 if (tag->id != BSWAP32(id) || tag->type != type) continue;
8298 switch (type) {
8299 default: NOT_REACHED();
8301 case 'T': {
8302 byte langid = buf->ReadByte();
8303 return tag->handler.text(langid, buf->ReadString());
8306 case 'B': {
8307 size_t len = buf->ReadWord();
8308 if (buf->Remaining() < len) return false;
8309 return tag->handler.data(len, buf);
8312 case 'C': {
8313 if (tag->handler.call_handler) {
8314 return tag->handler.u.branch(buf);
8316 return HandleNodes(buf, tag->handler.u.subtags);
8320 grfmsg(2, "StaticGRFInfo: unknown type/id combination found, type=%c, id=%x", type, id);
8321 return SkipUnknownInfo(buf, type);
8325 * Handle the contents of a 'C' choice of an Action14
8326 * @param buf Buffer.
8327 * @param subtags List of subtags.
8328 * @return Whether the nodes could all be handled.
8330 static bool HandleNodes(ByteReader *buf, AllowedSubtags subtags[])
8332 byte type = buf->ReadByte();
8333 while (type != 0) {
8334 uint32 id = buf->ReadDWord();
8335 if (!HandleNode(type, id, buf, subtags)) return false;
8336 type = buf->ReadByte();
8338 return true;
8342 * Handle Action 0x14
8343 * @param buf Buffer.
8345 static void StaticGRFInfo(ByteReader *buf)
8347 /* <14> <type> <id> <text/data...> */
8348 HandleNodes(buf, _tags_root);
8352 * Set the current NewGRF as unsafe for static use
8353 * @param buf Unused.
8354 * @note Used during safety scan on unsafe actions.
8356 static void GRFUnsafe(ByteReader *buf)
8358 SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
8360 /* Skip remainder of GRF */
8361 _cur.skip_sprites = -1;
8365 /** Initialize the TTDPatch flags */
8366 static void InitializeGRFSpecial()
8368 _ttdpatch_flags[0] = ((_settings_game.station.never_expire_airports ? 1U : 0U) << 0x0C) // keepsmallairport
8369 | (1U << 0x0D) // newairports
8370 | (1U << 0x0E) // largestations
8371 | ((_settings_game.construction.max_bridge_length > 16 ? 1U : 0U) << 0x0F) // longbridges
8372 | (0U << 0x10) // loadtime
8373 | (1U << 0x12) // presignals
8374 | (1U << 0x13) // extpresignals
8375 | ((_settings_game.vehicle.never_expire_vehicles ? 1U : 0U) << 0x16) // enginespersist
8376 | (1U << 0x1B) // multihead
8377 | (1U << 0x1D) // lowmemory
8378 | (1U << 0x1E); // generalfixes
8380 _ttdpatch_flags[1] = ((_settings_game.economy.station_noise_level ? 1U : 0U) << 0x07) // moreairports - based on units of noise
8381 | (1U << 0x08) // mammothtrains
8382 | (1U << 0x09) // trainrefit
8383 | (0U << 0x0B) // subsidiaries
8384 | ((_settings_game.order.gradual_loading ? 1U : 0U) << 0x0C) // gradualloading
8385 | (1U << 0x12) // unifiedmaglevmode - set bit 0 mode. Not revelant to OTTD
8386 | (1U << 0x13) // unifiedmaglevmode - set bit 1 mode
8387 | (1U << 0x14) // bridgespeedlimits
8388 | (1U << 0x16) // eternalgame
8389 | (1U << 0x17) // newtrains
8390 | (1U << 0x18) // newrvs
8391 | (1U << 0x19) // newships
8392 | (1U << 0x1A) // newplanes
8393 | ((_settings_game.construction.train_signal_side == 1 ? 1U : 0U) << 0x1B) // signalsontrafficside
8394 | ((_settings_game.vehicle.disable_elrails ? 0U : 1U) << 0x1C); // electrifiedrailway
8396 _ttdpatch_flags[2] = (1U << 0x01) // loadallgraphics - obsolote
8397 | (1U << 0x03) // semaphores
8398 | (1U << 0x0A) // newobjects
8399 | (0U << 0x0B) // enhancedgui
8400 | (0U << 0x0C) // newagerating
8401 | ((_settings_game.construction.build_on_slopes ? 1U : 0U) << 0x0D) // buildonslopes
8402 | (1U << 0x0E) // fullloadany
8403 | (1U << 0x0F) // planespeed
8404 | (0U << 0x10) // moreindustriesperclimate - obsolete
8405 | (0U << 0x11) // moretoylandfeatures
8406 | (1U << 0x12) // newstations
8407 | (1U << 0x13) // tracktypecostdiff
8408 | (1U << 0x14) // manualconvert
8409 | ((_settings_game.construction.build_on_slopes ? 1U : 0U) << 0x15) // buildoncoasts
8410 | (1U << 0x16) // canals
8411 | (1U << 0x17) // newstartyear
8412 | ((_settings_game.vehicle.freight_trains > 1 ? 1U : 0U) << 0x18) // freighttrains
8413 | (1U << 0x19) // newhouses
8414 | (1U << 0x1A) // newbridges
8415 | (1U << 0x1B) // newtownnames
8416 | (1U << 0x1C) // moreanimation
8417 | ((_settings_game.vehicle.wagon_speed_limits ? 1U : 0U) << 0x1D) // wagonspeedlimits
8418 | (1U << 0x1E) // newshistory
8419 | (0U << 0x1F); // custombridgeheads
8421 _ttdpatch_flags[3] = (0U << 0x00) // newcargodistribution
8422 | (1U << 0x01) // windowsnap
8423 | ((_settings_game.economy.allow_town_roads || _generating_world ? 0U : 1U) << 0x02) // townbuildnoroad
8424 | (1U << 0x03) // pathbasedsignalling
8425 | (0U << 0x04) // aichoosechance
8426 | (1U << 0x05) // resolutionwidth
8427 | (1U << 0x06) // resolutionheight
8428 | (1U << 0x07) // newindustries
8429 | ((_settings_game.order.improved_load ? 1U : 0U) << 0x08) // fifoloading
8430 | (0U << 0x09) // townroadbranchprob
8431 | (0U << 0x0A) // tempsnowline
8432 | (1U << 0x0B) // newcargo
8433 | (1U << 0x0C) // enhancemultiplayer
8434 | (1U << 0x0D) // onewayroads
8435 | (1U << 0x0E) // irregularstations
8436 | (1U << 0x0F) // statistics
8437 | (1U << 0x10) // newsounds
8438 | (1U << 0x11) // autoreplace
8439 | (1U << 0x12) // autoslope
8440 | (0U << 0x13) // followvehicle
8441 | (1U << 0x14) // trams
8442 | (0U << 0x15) // enhancetunnels
8443 | (1U << 0x16) // shortrvs
8444 | (1U << 0x17) // articulatedrvs
8445 | ((_settings_game.vehicle.dynamic_engines ? 1U : 0U) << 0x18) // dynamic engines
8446 | (1U << 0x1E) // variablerunningcosts
8447 | (1U << 0x1F); // any switch is on
8449 _ttdpatch_flags[4] = (1U << 0x00) // larger persistent storage
8450 | ((_settings_game.economy.inflation ? 1U : 0U) << 0x01); // inflation is on
8453 /** Reset and clear all NewGRF stations */
8454 static void ResetCustomStations()
8456 for (GRFFile * const file : _grf_files) {
8457 StationSpec **&stations = file->stations;
8458 if (stations == nullptr) continue;
8459 for (uint i = 0; i < NUM_STATIONS_PER_GRF; i++) {
8460 if (stations[i] == nullptr) continue;
8461 StationSpec *statspec = stations[i];
8463 /* Release this station */
8464 delete statspec;
8467 /* Free and reset the station data */
8468 free(stations);
8469 stations = nullptr;
8473 /** Reset and clear all NewGRF houses */
8474 static void ResetCustomHouses()
8476 for (GRFFile * const file : _grf_files) {
8477 HouseSpec **&housespec = file->housespec;
8478 if (housespec == nullptr) continue;
8479 for (uint i = 0; i < NUM_HOUSES_PER_GRF; i++) {
8480 free(housespec[i]);
8483 free(housespec);
8484 housespec = nullptr;
8488 /** Reset and clear all NewGRF airports */
8489 static void ResetCustomAirports()
8491 for (GRFFile * const file : _grf_files) {
8492 AirportSpec **aslist = file->airportspec;
8493 if (aslist != nullptr) {
8494 for (uint i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
8495 AirportSpec *as = aslist[i];
8497 if (as != nullptr) {
8498 /* We need to remove the tiles layouts */
8499 for (int j = 0; j < as->num_table; j++) {
8500 /* remove the individual layouts */
8501 free(as->table[j]);
8503 free(as->table);
8504 free(as->depot_table);
8505 free(as->rotation);
8507 free(as);
8510 free(aslist);
8511 file->airportspec = nullptr;
8514 AirportTileSpec **&airporttilespec = file->airtspec;
8515 if (airporttilespec != nullptr) {
8516 for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
8517 free(airporttilespec[i]);
8519 free(airporttilespec);
8520 airporttilespec = nullptr;
8525 /** Reset and clear all NewGRF industries */
8526 static void ResetCustomIndustries()
8528 for (GRFFile * const file : _grf_files) {
8529 IndustrySpec **&industryspec = file->industryspec;
8530 IndustryTileSpec **&indtspec = file->indtspec;
8532 /* We are verifiying both tiles and industries specs loaded from the grf file
8533 * First, let's deal with industryspec */
8534 if (industryspec != nullptr) {
8535 for (uint i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) {
8536 IndustrySpec *ind = industryspec[i];
8537 delete ind;
8540 free(industryspec);
8541 industryspec = nullptr;
8544 if (indtspec == nullptr) continue;
8545 for (uint i = 0; i < NUM_INDUSTRYTILES_PER_GRF; i++) {
8546 free(indtspec[i]);
8549 free(indtspec);
8550 indtspec = nullptr;
8554 /** Reset and clear all NewObjects */
8555 static void ResetCustomObjects()
8557 for (GRFFile * const file : _grf_files) {
8558 ObjectSpec **&objectspec = file->objectspec;
8559 if (objectspec == nullptr) continue;
8560 for (uint i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
8561 free(objectspec[i]);
8564 free(objectspec);
8565 objectspec = nullptr;
8569 /** Reset and clear all NewGRFs */
8570 static void ResetNewGRF()
8572 for (GRFFile * const file : _grf_files) {
8573 delete file;
8576 _grf_files.clear();
8577 _cur.grffile = nullptr;
8580 /** Clear all NewGRF errors */
8581 static void ResetNewGRFErrors()
8583 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
8584 if (!HasBit(c->flags, GCF_COPY) && c->error != nullptr) {
8585 delete c->error;
8586 c->error = nullptr;
8592 * Reset all NewGRF loaded data
8594 void ResetNewGRFData()
8596 CleanUpStrings();
8597 CleanUpGRFTownNames();
8599 /* Copy/reset original engine info data */
8600 SetupEngines();
8602 /* Copy/reset original bridge info data */
8603 ResetBridges();
8605 /* Reset rail type information */
8606 ResetRailTypes();
8608 /* Copy/reset original road type info data */
8609 ResetRoadTypes();
8611 /* Allocate temporary refit/cargo class data */
8612 _gted = CallocT<GRFTempEngineData>(Engine::GetPoolSize());
8614 /* Fill rail type label temporary data for default trains */
8615 for (const Engine *e : Engine::IterateType(VEH_TRAIN)) {
8616 _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
8619 /* Reset GRM reservations */
8620 memset(&_grm_engines, 0, sizeof(_grm_engines));
8621 memset(&_grm_cargoes, 0, sizeof(_grm_cargoes));
8623 /* Reset generic feature callback lists */
8624 ResetGenericCallbacks();
8626 /* Reset price base data */
8627 ResetPriceBaseMultipliers();
8629 /* Reset the curencies array */
8630 ResetCurrencies();
8632 /* Reset the house array */
8633 ResetCustomHouses();
8634 ResetHouses();
8636 /* Reset the industries structures*/
8637 ResetCustomIndustries();
8638 ResetIndustries();
8640 /* Reset the objects. */
8641 ObjectClass::Reset();
8642 ResetCustomObjects();
8643 ResetObjects();
8645 /* Reset station classes */
8646 StationClass::Reset();
8647 ResetCustomStations();
8649 /* Reset airport-related structures */
8650 AirportClass::Reset();
8651 ResetCustomAirports();
8652 AirportSpec::ResetAirports();
8653 AirportTileSpec::ResetAirportTiles();
8655 /* Reset canal sprite groups and flags */
8656 memset(_water_feature, 0, sizeof(_water_feature));
8658 /* Reset the snowline table. */
8659 ClearSnowLine();
8661 /* Reset NewGRF files */
8662 ResetNewGRF();
8664 /* Reset NewGRF errors. */
8665 ResetNewGRFErrors();
8667 /* Set up the default cargo types */
8668 SetupCargoForClimate(_settings_game.game_creation.landscape);
8670 /* Reset misc GRF features and train list display variables */
8671 _misc_grf_features = 0;
8673 _loaded_newgrf_features.has_2CC = false;
8674 _loaded_newgrf_features.used_liveries = 1 << LS_DEFAULT;
8675 _loaded_newgrf_features.shore = SHORE_REPLACE_NONE;
8676 _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_NONE;
8678 /* Clear all GRF overrides */
8679 _grf_id_overrides.clear();
8681 InitializeSoundPool();
8682 _spritegroup_pool.CleanPool();
8686 * Reset NewGRF data which is stored persistently in savegames.
8688 void ResetPersistentNewGRFData()
8690 /* Reset override managers */
8691 _engine_mngr.ResetToDefaultMapping();
8692 _house_mngr.ResetMapping();
8693 _industry_mngr.ResetMapping();
8694 _industile_mngr.ResetMapping();
8695 _airport_mngr.ResetMapping();
8696 _airporttile_mngr.ResetMapping();
8700 * Construct the Cargo Mapping
8701 * @note This is the reverse of a cargo translation table
8703 static void BuildCargoTranslationMap()
8705 memset(_cur.grffile->cargo_map, 0xFF, sizeof(_cur.grffile->cargo_map));
8707 for (CargoID c = 0; c < NUM_CARGO; c++) {
8708 const CargoSpec *cs = CargoSpec::Get(c);
8709 if (!cs->IsValid()) continue;
8711 if (_cur.grffile->cargo_list.size() == 0) {
8712 /* Default translation table, so just a straight mapping to bitnum */
8713 _cur.grffile->cargo_map[c] = cs->bitnum;
8714 } else {
8715 /* Check the translation table for this cargo's label */
8716 int idx = find_index(_cur.grffile->cargo_list, {cs->label});
8717 if (idx >= 0) _cur.grffile->cargo_map[c] = idx;
8723 * Prepare loading a NewGRF file with its config
8724 * @param config The NewGRF configuration struct with name, id, parameters and alike.
8726 static void InitNewGRFFile(const GRFConfig *config)
8728 GRFFile *newfile = GetFileByFilename(config->filename);
8729 if (newfile != nullptr) {
8730 /* We already loaded it once. */
8731 _cur.grffile = newfile;
8732 return;
8735 newfile = new GRFFile(config);
8736 _grf_files.push_back(_cur.grffile = newfile);
8740 * Constructor for GRFFile
8741 * @param config GRFConfig to copy name, grfid and parameters from.
8743 GRFFile::GRFFile(const GRFConfig *config)
8745 this->filename = stredup(config->filename);
8746 this->grfid = config->ident.grfid;
8748 /* Initialise local settings to defaults */
8749 this->traininfo_vehicle_pitch = 0;
8750 this->traininfo_vehicle_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
8752 /* Mark price_base_multipliers as 'not set' */
8753 for (Price i = PR_BEGIN; i < PR_END; i++) {
8754 this->price_base_multipliers[i] = INVALID_PRICE_MODIFIER;
8757 /* Initialise rail type map with default rail types */
8758 std::fill(std::begin(this->railtype_map), std::end(this->railtype_map), INVALID_RAILTYPE);
8759 this->railtype_map[0] = RAILTYPE_RAIL;
8760 this->railtype_map[1] = RAILTYPE_ELECTRIC;
8761 this->railtype_map[2] = RAILTYPE_MONO;
8762 this->railtype_map[3] = RAILTYPE_MAGLEV;
8764 /* Initialise road type map with default road types */
8765 std::fill(std::begin(this->roadtype_map), std::end(this->roadtype_map), INVALID_ROADTYPE);
8766 this->roadtype_map[0] = ROADTYPE_ROAD;
8768 /* Initialise tram type map with default tram types */
8769 std::fill(std::begin(this->tramtype_map), std::end(this->tramtype_map), INVALID_ROADTYPE);
8770 this->tramtype_map[0] = ROADTYPE_TRAM;
8772 /* Copy the initial parameter list
8773 * 'Uninitialised' parameters are zeroed as that is their default value when dynamically creating them. */
8774 static_assert(lengthof(this->param) == lengthof(config->param) && lengthof(this->param) == 0x80);
8776 assert(config->num_params <= lengthof(config->param));
8777 this->param_end = config->num_params;
8778 if (this->param_end > 0) {
8779 MemCpyT(this->param, config->param, this->param_end);
8783 GRFFile::~GRFFile()
8785 free(this->filename);
8786 delete[] this->language_map;
8791 * Precalculate refit masks from cargo classes for all vehicles.
8793 static void CalculateRefitMasks()
8795 CargoTypes original_known_cargoes = 0;
8796 for (int ct = 0; ct != NUM_ORIGINAL_CARGO; ++ct) {
8797 CargoID cid = GetDefaultCargoID(_settings_game.game_creation.landscape, static_cast<CargoType>(ct));
8798 if (cid != CT_INVALID) SetBit(original_known_cargoes, cid);
8801 for (Engine *e : Engine::Iterate()) {
8802 EngineID engine = e->index;
8803 EngineInfo *ei = &e->info;
8804 bool only_defaultcargo; ///< Set if the vehicle shall carry only the default cargo
8806 /* If the NewGRF did not set any cargo properties, we apply default values. */
8807 if (_gted[engine].defaultcargo_grf == nullptr) {
8808 /* If the vehicle has any capacity, apply the default refit masks */
8809 if (e->type != VEH_TRAIN || e->u.rail.capacity != 0) {
8810 static constexpr byte T = 1 << LT_TEMPERATE;
8811 static constexpr byte A = 1 << LT_ARCTIC;
8812 static constexpr byte S = 1 << LT_TROPIC;
8813 static constexpr byte Y = 1 << LT_TOYLAND;
8814 static const struct DefaultRefitMasks {
8815 byte climate;
8816 CargoType cargo_type;
8817 CargoTypes cargo_allowed;
8818 CargoTypes cargo_disallowed;
8819 } _default_refit_masks[] = {
8820 {T | A | S | Y, CT_PASSENGERS, CC_PASSENGERS, 0},
8821 {T | A | S , CT_MAIL, CC_MAIL, 0},
8822 {T | A | S , CT_VALUABLES, CC_ARMOURED, CC_LIQUID},
8823 { Y, CT_MAIL, CC_MAIL | CC_ARMOURED, CC_LIQUID},
8824 {T | A , CT_COAL, CC_BULK, 0},
8825 { S , CT_COPPER_ORE, CC_BULK, 0},
8826 { Y, CT_SUGAR, CC_BULK, 0},
8827 {T | A | S , CT_OIL, CC_LIQUID, 0},
8828 { Y, CT_COLA, CC_LIQUID, 0},
8829 {T , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
8830 { A | S , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS | CC_REFRIGERATED},
8831 { A | S , CT_FOOD, CC_REFRIGERATED, 0},
8832 { Y, CT_CANDY, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
8835 if (e->type == VEH_AIRCRAFT) {
8836 /* Aircraft default to "light" cargoes */
8837 _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS;
8838 _gted[engine].cargo_disallowed = CC_LIQUID;
8839 } else if (e->type == VEH_SHIP) {
8840 switch (ei->cargo_type) {
8841 case CT_PASSENGERS:
8842 /* Ferries */
8843 _gted[engine].cargo_allowed = CC_PASSENGERS;
8844 _gted[engine].cargo_disallowed = 0;
8845 break;
8846 case CT_OIL:
8847 /* Tankers */
8848 _gted[engine].cargo_allowed = CC_LIQUID;
8849 _gted[engine].cargo_disallowed = 0;
8850 break;
8851 default:
8852 /* Cargo ships */
8853 if (_settings_game.game_creation.landscape == LT_TOYLAND) {
8854 /* No tanker in toyland :( */
8855 _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
8856 _gted[engine].cargo_disallowed = CC_PASSENGERS;
8857 } else {
8858 _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS;
8859 _gted[engine].cargo_disallowed = CC_LIQUID | CC_PASSENGERS;
8861 break;
8863 e->u.ship.old_refittable = true;
8864 } else if (e->type == VEH_TRAIN && e->u.rail.railveh_type != RAILVEH_WAGON) {
8865 /* Train engines default to all cargoes, so you can build single-cargo consists with fast engines.
8866 * Trains loading multiple cargoes may start stations accepting unwanted cargoes. */
8867 _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
8868 _gted[engine].cargo_disallowed = 0;
8869 } else {
8870 /* Train wagons and road vehicles are classified by their default cargo type */
8871 for (const auto &drm : _default_refit_masks) {
8872 if (!HasBit(drm.climate, _settings_game.game_creation.landscape)) continue;
8873 if (drm.cargo_type != ei->cargo_type) continue;
8875 _gted[engine].cargo_allowed = drm.cargo_allowed;
8876 _gted[engine].cargo_disallowed = drm.cargo_disallowed;
8877 break;
8880 /* All original cargoes have specialised vehicles, so exclude them */
8881 _gted[engine].ctt_exclude_mask = original_known_cargoes;
8884 _gted[engine].UpdateRefittability(_gted[engine].cargo_allowed != 0);
8886 /* Translate cargo_type using the original climate-specific cargo table. */
8887 ei->cargo_type = GetDefaultCargoID(_settings_game.game_creation.landscape, static_cast<CargoType>(ei->cargo_type));
8888 if (ei->cargo_type != CT_INVALID) ClrBit(_gted[engine].ctt_exclude_mask, ei->cargo_type);
8891 /* Compute refittability */
8893 CargoTypes mask = 0;
8894 CargoTypes not_mask = 0;
8895 CargoTypes xor_mask = ei->refit_mask;
8897 /* If the original masks set by the grf are zero, the vehicle shall only carry the default cargo.
8898 * Note: After applying the translations, the vehicle may end up carrying no defined cargo. It becomes unavailable in that case. */
8899 only_defaultcargo = _gted[engine].refittability != GRFTempEngineData::NONEMPTY;
8901 if (_gted[engine].cargo_allowed != 0) {
8902 /* Build up the list of cargo types from the set cargo classes. */
8903 for (const CargoSpec *cs : CargoSpec::Iterate()) {
8904 if (_gted[engine].cargo_allowed & cs->classes) SetBit(mask, cs->Index());
8905 if (_gted[engine].cargo_disallowed & cs->classes) SetBit(not_mask, cs->Index());
8909 ei->refit_mask = ((mask & ~not_mask) ^ xor_mask) & _cargo_mask;
8911 /* Apply explicit refit includes/excludes. */
8912 ei->refit_mask |= _gted[engine].ctt_include_mask;
8913 ei->refit_mask &= ~_gted[engine].ctt_exclude_mask;
8916 /* Clear invalid cargoslots (from default vehicles or pre-NewCargo GRFs) */
8917 if (ei->cargo_type != CT_INVALID && !HasBit(_cargo_mask, ei->cargo_type)) ei->cargo_type = CT_INVALID;
8919 /* Ensure that the vehicle is either not refittable, or that the default cargo is one of the refittable cargoes.
8920 * Note: Vehicles refittable to no cargo are handle differently to vehicle refittable to a single cargo. The latter might have subtypes. */
8921 if (!only_defaultcargo && (e->type != VEH_SHIP || e->u.ship.old_refittable) && ei->cargo_type != CT_INVALID && !HasBit(ei->refit_mask, ei->cargo_type)) {
8922 ei->cargo_type = CT_INVALID;
8925 /* Check if this engine's cargo type is valid. If not, set to the first refittable
8926 * cargo type. Finally disable the vehicle, if there is still no cargo. */
8927 if (ei->cargo_type == CT_INVALID && ei->refit_mask != 0) {
8928 /* Figure out which CTT to use for the default cargo, if it is 'first refittable'. */
8929 const uint8 *cargo_map_for_first_refittable = nullptr;
8931 const GRFFile *file = _gted[engine].defaultcargo_grf;
8932 if (file == nullptr) file = e->GetGRF();
8933 if (file != nullptr && file->grf_version >= 8 && file->cargo_list.size() != 0) {
8934 cargo_map_for_first_refittable = file->cargo_map;
8938 if (cargo_map_for_first_refittable != nullptr) {
8939 /* Use first refittable cargo from cargo translation table */
8940 byte best_local_slot = 0xFF;
8941 for (CargoID cargo_type : SetCargoBitIterator(ei->refit_mask)) {
8942 byte local_slot = cargo_map_for_first_refittable[cargo_type];
8943 if (local_slot < best_local_slot) {
8944 best_local_slot = local_slot;
8945 ei->cargo_type = cargo_type;
8950 if (ei->cargo_type == CT_INVALID) {
8951 /* Use first refittable cargo slot */
8952 ei->cargo_type = (CargoID)FindFirstBit(ei->refit_mask);
8955 if (ei->cargo_type == CT_INVALID) ei->climates = 0;
8957 /* Clear refit_mask for not refittable ships */
8958 if (e->type == VEH_SHIP && !e->u.ship.old_refittable) {
8959 ei->refit_mask = 0;
8964 /** Set to use the correct action0 properties for each canal feature */
8965 static void FinaliseCanals()
8967 for (uint i = 0; i < CF_END; i++) {
8968 if (_water_feature[i].grffile != nullptr) {
8969 _water_feature[i].callback_mask = _water_feature[i].grffile->canal_local_properties[i].callback_mask;
8970 _water_feature[i].flags = _water_feature[i].grffile->canal_local_properties[i].flags;
8975 /** Check for invalid engines */
8976 static void FinaliseEngineArray()
8978 for (Engine *e : Engine::Iterate()) {
8979 if (e->GetGRF() == nullptr) {
8980 const EngineIDMapping &eid = _engine_mngr[e->index];
8981 if (eid.grfid != INVALID_GRFID || eid.internal_id != eid.substitute_id) {
8982 e->info.string_id = STR_NEWGRF_INVALID_ENGINE;
8986 if (!HasBit(e->info.climates, _settings_game.game_creation.landscape)) continue;
8988 /* When the train does not set property 27 (misc flags), but it
8989 * is overridden by a NewGRF graphically we want to disable the
8990 * flipping possibility. */
8991 if (e->type == VEH_TRAIN && !_gted[e->index].prop27_set && e->GetGRF() != nullptr && is_custom_sprite(e->u.rail.image_index)) {
8992 ClrBit(e->info.misc_flags, EF_RAIL_FLIPS);
8995 /* Skip wagons, there livery is defined via the engine */
8996 if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
8997 LiveryScheme ls = GetEngineLiveryScheme(e->index, INVALID_ENGINE, nullptr);
8998 SetBit(_loaded_newgrf_features.used_liveries, ls);
8999 /* Note: For ships and roadvehicles we assume that they cannot be refitted between passenger and freight */
9001 if (e->type == VEH_TRAIN) {
9002 SetBit(_loaded_newgrf_features.used_liveries, LS_FREIGHT_WAGON);
9003 switch (ls) {
9004 case LS_STEAM:
9005 case LS_DIESEL:
9006 case LS_ELECTRIC:
9007 case LS_MONORAIL:
9008 case LS_MAGLEV:
9009 SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_STEAM + ls - LS_STEAM);
9010 break;
9012 case LS_DMU:
9013 case LS_EMU:
9014 SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_DIESEL + ls - LS_DMU);
9015 break;
9017 default: NOT_REACHED();
9024 /** Check for invalid cargoes */
9025 static void FinaliseCargoArray()
9027 for (CargoID c = 0; c < NUM_CARGO; c++) {
9028 CargoSpec *cs = CargoSpec::Get(c);
9029 if (!cs->IsValid()) {
9030 cs->name = cs->name_single = cs->units_volume = STR_NEWGRF_INVALID_CARGO;
9031 cs->quantifier = STR_NEWGRF_INVALID_CARGO_QUANTITY;
9032 cs->abbrev = STR_NEWGRF_INVALID_CARGO_ABBREV;
9038 * Check if a given housespec is valid and disable it if it's not.
9039 * The housespecs that follow it are used to check the validity of
9040 * multitile houses.
9041 * @param hs The housespec to check.
9042 * @param next1 The housespec that follows \c hs.
9043 * @param next2 The housespec that follows \c next1.
9044 * @param next3 The housespec that follows \c next2.
9045 * @param filename The filename of the newgrf this house was defined in.
9046 * @return Whether the given housespec is valid.
9048 static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const char *filename)
9050 if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 &&
9051 (next1 == nullptr || !next1->enabled || (next1->building_flags & BUILDING_HAS_1_TILE) != 0)) ||
9052 ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 &&
9053 (next2 == nullptr || !next2->enabled || (next2->building_flags & BUILDING_HAS_1_TILE) != 0 ||
9054 next3 == nullptr || !next3->enabled || (next3->building_flags & BUILDING_HAS_1_TILE) != 0))) {
9055 hs->enabled = false;
9056 if (filename != nullptr) Debug(grf, 1, "FinaliseHouseArray: {} defines house {} as multitile, but no suitable tiles follow. Disabling house.", filename, hs->grf_prop.local_id);
9057 return false;
9060 /* Some places sum population by only counting north tiles. Other places use all tiles causing desyncs.
9061 * As the newgrf specs define population to be zero for non-north tiles, we just disable the offending house.
9062 * If you want to allow non-zero populations somewhen, make sure to sum the population of all tiles in all places. */
9063 if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 && next1->population != 0) ||
9064 ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 && (next2->population != 0 || next3->population != 0))) {
9065 hs->enabled = false;
9066 if (filename != nullptr) Debug(grf, 1, "FinaliseHouseArray: {} defines multitile house {} with non-zero population on additional tiles. Disabling house.", filename, hs->grf_prop.local_id);
9067 return false;
9070 /* Substitute type is also used for override, and having an override with a different size causes crashes.
9071 * This check should only be done for NewGRF houses because grf_prop.subst_id is not set for original houses.*/
9072 if (filename != nullptr && (hs->building_flags & BUILDING_HAS_1_TILE) != (HouseSpec::Get(hs->grf_prop.subst_id)->building_flags & BUILDING_HAS_1_TILE)) {
9073 hs->enabled = false;
9074 Debug(grf, 1, "FinaliseHouseArray: {} defines house {} with different house size then it's substitute type. Disabling house.", filename, hs->grf_prop.local_id);
9075 return false;
9078 /* Make sure that additional parts of multitile houses are not available. */
9079 if ((hs->building_flags & BUILDING_HAS_1_TILE) == 0 && (hs->building_availability & HZ_ZONALL) != 0 && (hs->building_availability & HZ_CLIMALL) != 0) {
9080 hs->enabled = false;
9081 if (filename != nullptr) Debug(grf, 1, "FinaliseHouseArray: {} defines house {} without a size but marked it as available. Disabling house.", filename, hs->grf_prop.local_id);
9082 return false;
9085 return true;
9089 * Make sure there is at least one house available in the year 0 for the given
9090 * climate / housezone combination.
9091 * @param bitmask The climate and housezone to check for. Exactly one climate
9092 * bit and one housezone bit should be set.
9094 static void EnsureEarlyHouse(HouseZones bitmask)
9096 Year min_year = MAX_YEAR;
9098 for (int i = 0; i < NUM_HOUSES; i++) {
9099 HouseSpec *hs = HouseSpec::Get(i);
9100 if (hs == nullptr || !hs->enabled) continue;
9101 if ((hs->building_availability & bitmask) != bitmask) continue;
9102 if (hs->min_year < min_year) min_year = hs->min_year;
9105 if (min_year == 0) return;
9107 for (int i = 0; i < NUM_HOUSES; i++) {
9108 HouseSpec *hs = HouseSpec::Get(i);
9109 if (hs == nullptr || !hs->enabled) continue;
9110 if ((hs->building_availability & bitmask) != bitmask) continue;
9111 if (hs->min_year == min_year) hs->min_year = 0;
9116 * Add all new houses to the house array. House properties can be set at any
9117 * time in the GRF file, so we can only add a house spec to the house array
9118 * after the file has finished loading. We also need to check the dates, due to
9119 * the TTDPatch behaviour described below that we need to emulate.
9121 static void FinaliseHouseArray()
9123 /* If there are no houses with start dates before 1930, then all houses
9124 * with start dates of 1930 have them reset to 0. This is in order to be
9125 * compatible with TTDPatch, where if no houses have start dates before
9126 * 1930 and the date is before 1930, the game pretends that this is 1930.
9127 * If there have been any houses defined with start dates before 1930 then
9128 * the dates are left alone.
9129 * On the other hand, why 1930? Just 'fix' the houses with the lowest
9130 * minimum introduction date to 0.
9132 for (GRFFile * const file : _grf_files) {
9133 HouseSpec **&housespec = file->housespec;
9134 if (housespec == nullptr) continue;
9136 for (int i = 0; i < NUM_HOUSES_PER_GRF; i++) {
9137 HouseSpec *hs = housespec[i];
9139 if (hs == nullptr) continue;
9141 const HouseSpec *next1 = (i + 1 < NUM_HOUSES_PER_GRF ? housespec[i + 1] : nullptr);
9142 const HouseSpec *next2 = (i + 2 < NUM_HOUSES_PER_GRF ? housespec[i + 2] : nullptr);
9143 const HouseSpec *next3 = (i + 3 < NUM_HOUSES_PER_GRF ? housespec[i + 3] : nullptr);
9145 if (!IsHouseSpecValid(hs, next1, next2, next3, file->filename)) continue;
9147 _house_mngr.SetEntitySpec(hs);
9151 for (int i = 0; i < NUM_HOUSES; i++) {
9152 HouseSpec *hs = HouseSpec::Get(i);
9153 const HouseSpec *next1 = (i + 1 < NUM_HOUSES ? HouseSpec::Get(i + 1) : nullptr);
9154 const HouseSpec *next2 = (i + 2 < NUM_HOUSES ? HouseSpec::Get(i + 2) : nullptr);
9155 const HouseSpec *next3 = (i + 3 < NUM_HOUSES ? HouseSpec::Get(i + 3) : nullptr);
9157 /* We need to check all houses again to we are sure that multitile houses
9158 * did get consecutive IDs and none of the parts are missing. */
9159 if (!IsHouseSpecValid(hs, next1, next2, next3, nullptr)) {
9160 /* GetHouseNorthPart checks 3 houses that are directly before
9161 * it in the house pool. If any of those houses have multi-tile
9162 * flags set it assumes it's part of a multitile house. Since
9163 * we can have invalid houses in the pool marked as disabled, we
9164 * don't want to have them influencing valid tiles. As such set
9165 * building_flags to zero here to make sure any house following
9166 * this one in the pool is properly handled as 1x1 house. */
9167 hs->building_flags = TILE_NO_FLAG;
9171 HouseZones climate_mask = (HouseZones)(1 << (_settings_game.game_creation.landscape + 12));
9172 EnsureEarlyHouse(HZ_ZON1 | climate_mask);
9173 EnsureEarlyHouse(HZ_ZON2 | climate_mask);
9174 EnsureEarlyHouse(HZ_ZON3 | climate_mask);
9175 EnsureEarlyHouse(HZ_ZON4 | climate_mask);
9176 EnsureEarlyHouse(HZ_ZON5 | climate_mask);
9178 if (_settings_game.game_creation.landscape == LT_ARCTIC) {
9179 EnsureEarlyHouse(HZ_ZON1 | HZ_SUBARTC_ABOVE);
9180 EnsureEarlyHouse(HZ_ZON2 | HZ_SUBARTC_ABOVE);
9181 EnsureEarlyHouse(HZ_ZON3 | HZ_SUBARTC_ABOVE);
9182 EnsureEarlyHouse(HZ_ZON4 | HZ_SUBARTC_ABOVE);
9183 EnsureEarlyHouse(HZ_ZON5 | HZ_SUBARTC_ABOVE);
9188 * Add all new industries to the industry array. Industry properties can be set at any
9189 * time in the GRF file, so we can only add a industry spec to the industry array
9190 * after the file has finished loading.
9192 static void FinaliseIndustriesArray()
9194 for (GRFFile * const file : _grf_files) {
9195 IndustrySpec **&industryspec = file->industryspec;
9196 IndustryTileSpec **&indtspec = file->indtspec;
9197 if (industryspec != nullptr) {
9198 for (int i = 0; i < NUM_INDUSTRYTYPES_PER_GRF; i++) {
9199 IndustrySpec *indsp = industryspec[i];
9201 if (indsp != nullptr && indsp->enabled) {
9202 StringID strid;
9203 /* process the conversion of text at the end, so to be sure everything will be fine
9204 * and available. Check if it does not return undefind marker, which is a very good sign of a
9205 * substitute industry who has not changed the string been examined, thus using it as such */
9206 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->name);
9207 if (strid != STR_UNDEFINED) indsp->name = strid;
9209 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->closure_text);
9210 if (strid != STR_UNDEFINED) indsp->closure_text = strid;
9212 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_up_text);
9213 if (strid != STR_UNDEFINED) indsp->production_up_text = strid;
9215 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_down_text);
9216 if (strid != STR_UNDEFINED) indsp->production_down_text = strid;
9218 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->new_industry_text);
9219 if (strid != STR_UNDEFINED) indsp->new_industry_text = strid;
9221 if (indsp->station_name != STR_NULL) {
9222 /* STR_NULL (0) can be set by grf. It has a meaning regarding assignation of the
9223 * station's name. Don't want to lose the value, therefore, do not process. */
9224 strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->station_name);
9225 if (strid != STR_UNDEFINED) indsp->station_name = strid;
9228 _industry_mngr.SetEntitySpec(indsp);
9233 if (indtspec != nullptr) {
9234 for (int i = 0; i < NUM_INDUSTRYTILES_PER_GRF; i++) {
9235 IndustryTileSpec *indtsp = indtspec[i];
9236 if (indtsp != nullptr) {
9237 _industile_mngr.SetEntitySpec(indtsp);
9243 for (uint j = 0; j < NUM_INDUSTRYTYPES; j++) {
9244 IndustrySpec *indsp = &_industry_specs[j];
9245 if (indsp->enabled && indsp->grf_prop.grffile != nullptr) {
9246 for (uint i = 0; i < 3; i++) {
9247 indsp->conflicting[i] = MapNewGRFIndustryType(indsp->conflicting[i], indsp->grf_prop.grffile->grfid);
9250 if (!indsp->enabled) {
9251 indsp->name = STR_NEWGRF_INVALID_INDUSTRYTYPE;
9257 * Add all new objects to the object array. Object properties can be set at any
9258 * time in the GRF file, so we can only add an object spec to the object array
9259 * after the file has finished loading.
9261 static void FinaliseObjectsArray()
9263 for (GRFFile * const file : _grf_files) {
9264 ObjectSpec **&objectspec = file->objectspec;
9265 if (objectspec != nullptr) {
9266 for (int i = 0; i < NUM_OBJECTS_PER_GRF; i++) {
9267 if (objectspec[i] != nullptr && objectspec[i]->grf_prop.grffile != nullptr && objectspec[i]->enabled) {
9268 _object_mngr.SetEntitySpec(objectspec[i]);
9276 * Add all new airports to the airport array. Airport properties can be set at any
9277 * time in the GRF file, so we can only add a airport spec to the airport array
9278 * after the file has finished loading.
9280 static void FinaliseAirportsArray()
9282 for (GRFFile * const file : _grf_files) {
9283 AirportSpec **&airportspec = file->airportspec;
9284 if (airportspec != nullptr) {
9285 for (int i = 0; i < NUM_AIRPORTS_PER_GRF; i++) {
9286 if (airportspec[i] != nullptr && airportspec[i]->enabled) {
9287 _airport_mngr.SetEntitySpec(airportspec[i]);
9292 AirportTileSpec **&airporttilespec = file->airtspec;
9293 if (airporttilespec != nullptr) {
9294 for (uint i = 0; i < NUM_AIRPORTTILES_PER_GRF; i++) {
9295 if (airporttilespec[i] != nullptr && airporttilespec[i]->enabled) {
9296 _airporttile_mngr.SetEntitySpec(airporttilespec[i]);
9303 /* Here we perform initial decoding of some special sprites (as are they
9304 * described at http://www.ttdpatch.net/src/newgrf.txt, but this is only a very
9305 * partial implementation yet).
9306 * XXX: We consider GRF files trusted. It would be trivial to exploit OTTD by
9307 * a crafted invalid GRF file. We should tell that to the user somehow, or
9308 * better make this more robust in the future. */
9309 static void DecodeSpecialSprite(byte *buf, uint num, GrfLoadingStage stage)
9311 /* XXX: There is a difference between staged loading in TTDPatch and
9312 * here. In TTDPatch, for some reason actions 1 and 2 are carried out
9313 * during stage 1, whilst action 3 is carried out during stage 2 (to
9314 * "resolve" cargo IDs... wtf). This is a little problem, because cargo
9315 * IDs are valid only within a given set (action 1) block, and may be
9316 * overwritten after action 3 associates them. But overwriting happens
9317 * in an earlier stage than associating, so... We just process actions
9318 * 1 and 2 in stage 2 now, let's hope that won't get us into problems.
9319 * --pasky
9320 * We need a pre-stage to set up GOTO labels of Action 0x10 because the grf
9321 * is not in memory and scanning the file every time would be too expensive.
9322 * In other stages we skip action 0x10 since it's already dealt with. */
9323 static const SpecialSpriteHandler handlers[][GLS_END] = {
9324 /* 0x00 */ { nullptr, SafeChangeInfo, nullptr, nullptr, ReserveChangeInfo, FeatureChangeInfo, },
9325 /* 0x01 */ { SkipAct1, SkipAct1, SkipAct1, SkipAct1, SkipAct1, NewSpriteSet, },
9326 /* 0x02 */ { nullptr, nullptr, nullptr, nullptr, nullptr, NewSpriteGroup, },
9327 /* 0x03 */ { nullptr, GRFUnsafe, nullptr, nullptr, nullptr, FeatureMapSpriteGroup, },
9328 /* 0x04 */ { nullptr, nullptr, nullptr, nullptr, nullptr, FeatureNewName, },
9329 /* 0x05 */ { SkipAct5, SkipAct5, SkipAct5, SkipAct5, SkipAct5, GraphicsNew, },
9330 /* 0x06 */ { nullptr, nullptr, nullptr, CfgApply, CfgApply, CfgApply, },
9331 /* 0x07 */ { nullptr, nullptr, nullptr, nullptr, SkipIf, SkipIf, },
9332 /* 0x08 */ { ScanInfo, nullptr, nullptr, GRFInfo, GRFInfo, GRFInfo, },
9333 /* 0x09 */ { nullptr, nullptr, nullptr, SkipIf, SkipIf, SkipIf, },
9334 /* 0x0A */ { SkipActA, SkipActA, SkipActA, SkipActA, SkipActA, SpriteReplace, },
9335 /* 0x0B */ { nullptr, nullptr, nullptr, GRFLoadError, GRFLoadError, GRFLoadError, },
9336 /* 0x0C */ { nullptr, nullptr, nullptr, GRFComment, nullptr, GRFComment, },
9337 /* 0x0D */ { nullptr, SafeParamSet, nullptr, ParamSet, ParamSet, ParamSet, },
9338 /* 0x0E */ { nullptr, SafeGRFInhibit, nullptr, GRFInhibit, GRFInhibit, GRFInhibit, },
9339 /* 0x0F */ { nullptr, GRFUnsafe, nullptr, FeatureTownName, nullptr, nullptr, },
9340 /* 0x10 */ { nullptr, nullptr, DefineGotoLabel, nullptr, nullptr, nullptr, },
9341 /* 0x11 */ { SkipAct11, GRFUnsafe, SkipAct11, GRFSound, SkipAct11, GRFSound, },
9342 /* 0x12 */ { SkipAct12, SkipAct12, SkipAct12, SkipAct12, SkipAct12, LoadFontGlyph, },
9343 /* 0x13 */ { nullptr, nullptr, nullptr, nullptr, nullptr, TranslateGRFStrings, },
9344 /* 0x14 */ { StaticGRFInfo, nullptr, nullptr, nullptr, nullptr, nullptr, },
9347 GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line);
9349 GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
9350 if (it == _grf_line_to_action6_sprite_override.end()) {
9351 /* No preloaded sprite to work with; read the
9352 * pseudo sprite content. */
9353 _cur.file->ReadBlock(buf, num);
9354 } else {
9355 /* Use the preloaded sprite data. */
9356 buf = _grf_line_to_action6_sprite_override[location];
9357 grfmsg(7, "DecodeSpecialSprite: Using preloaded pseudo sprite data");
9359 /* Skip the real (original) content of this action. */
9360 _cur.file->SeekTo(num, SEEK_CUR);
9363 ByteReader br(buf, buf + num);
9364 ByteReader *bufp = &br;
9366 try {
9367 byte action = bufp->ReadByte();
9369 if (action == 0xFF) {
9370 grfmsg(2, "DecodeSpecialSprite: Unexpected data block, skipping");
9371 } else if (action == 0xFE) {
9372 grfmsg(2, "DecodeSpecialSprite: Unexpected import block, skipping");
9373 } else if (action >= lengthof(handlers)) {
9374 grfmsg(7, "DecodeSpecialSprite: Skipping unknown action 0x%02X", action);
9375 } else if (handlers[action][stage] == nullptr) {
9376 grfmsg(7, "DecodeSpecialSprite: Skipping action 0x%02X in stage %d", action, stage);
9377 } else {
9378 grfmsg(7, "DecodeSpecialSprite: Handling action 0x%02X in stage %d", action, stage);
9379 handlers[action][stage](bufp);
9381 } catch (...) {
9382 grfmsg(1, "DecodeSpecialSprite: Tried to read past end of pseudo-sprite data");
9383 DisableGrf(STR_NEWGRF_ERROR_READ_BOUNDS);
9388 * Load a particular NewGRF from a SpriteFile.
9389 * @param config The configuration of the to be loaded NewGRF.
9390 * @param stage The loading stage of the NewGRF.
9391 * @param file The file to load the GRF data from.
9393 static void LoadNewGRFFileFromFile(GRFConfig *config, GrfLoadingStage stage, SpriteFile &file)
9395 _cur.file = &file;
9396 _cur.grfconfig = config;
9398 Debug(grf, 2, "LoadNewGRFFile: Reading NewGRF-file '{}'", config->filename);
9400 byte grf_container_version = file.GetContainerVersion();
9401 if (grf_container_version == 0) {
9402 Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9403 return;
9406 if (stage == GLS_INIT || stage == GLS_ACTIVATION) {
9407 /* We need the sprite offsets in the init stage for NewGRF sounds
9408 * and in the activation stage for real sprites. */
9409 ReadGRFSpriteOffsets(file);
9410 } else {
9411 /* Skip sprite section offset if present. */
9412 if (grf_container_version >= 2) file.ReadDword();
9415 if (grf_container_version >= 2) {
9416 /* Read compression value. */
9417 byte compression = file.ReadByte();
9418 if (compression != 0) {
9419 Debug(grf, 7, "LoadNewGRFFile: Unsupported compression format");
9420 return;
9424 /* Skip the first sprite; we don't care about how many sprites this
9425 * does contain; newest TTDPatches and George's longvehicles don't
9426 * neither, apparently. */
9427 uint32 num = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
9428 if (num == 4 && file.ReadByte() == 0xFF) {
9429 file.ReadDword();
9430 } else {
9431 Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9432 return;
9435 _cur.ClearDataForNextFile();
9437 ReusableBuffer<byte> buf;
9439 while ((num = (grf_container_version >= 2 ? file.ReadDword() : file.ReadWord())) != 0) {
9440 byte type = file.ReadByte();
9441 _cur.nfo_line++;
9443 if (type == 0xFF) {
9444 if (_cur.skip_sprites == 0) {
9445 DecodeSpecialSprite(buf.Allocate(num), num, stage);
9447 /* Stop all processing if we are to skip the remaining sprites */
9448 if (_cur.skip_sprites == -1) break;
9450 continue;
9451 } else {
9452 file.SkipBytes(num);
9454 } else {
9455 if (_cur.skip_sprites == 0) {
9456 grfmsg(0, "LoadNewGRFFile: Unexpected sprite, disabling");
9457 DisableGrf(STR_NEWGRF_ERROR_UNEXPECTED_SPRITE);
9458 break;
9461 if (grf_container_version >= 2 && type == 0xFD) {
9462 /* Reference to data section. Container version >= 2 only. */
9463 file.SkipBytes(num);
9464 } else {
9465 file.SkipBytes(7);
9466 SkipSpriteData(file, type, num - 8);
9470 if (_cur.skip_sprites > 0) _cur.skip_sprites--;
9475 * Load a particular NewGRF.
9476 * @param config The configuration of the to be loaded NewGRF.
9477 * @param stage The loading stage of the NewGRF.
9478 * @param subdir The sub directory to find the NewGRF in.
9479 * @param temporary The NewGRF/sprite file is to be loaded temporarily and should be closed immediately,
9480 * contrary to loading the SpriteFile and having it cached by the SpriteCache.
9482 void LoadNewGRFFile(GRFConfig *config, GrfLoadingStage stage, Subdirectory subdir, bool temporary)
9484 const char *filename = config->filename;
9486 /* A .grf file is activated only if it was active when the game was
9487 * started. If a game is loaded, only its active .grfs will be
9488 * reactivated, unless "loadallgraphics on" is used. A .grf file is
9489 * considered active if its action 8 has been processed, i.e. its
9490 * action 8 hasn't been skipped using an action 7.
9492 * During activation, only actions 0, 1, 2, 3, 4, 5, 7, 8, 9, 0A and 0B are
9493 * carried out. All others are ignored, because they only need to be
9494 * processed once at initialization. */
9495 if (stage != GLS_FILESCAN && stage != GLS_SAFETYSCAN && stage != GLS_LABELSCAN) {
9496 _cur.grffile = GetFileByFilename(filename);
9497 if (_cur.grffile == nullptr) usererror("File '%s' lost in cache.\n", filename);
9498 if (stage == GLS_RESERVE && config->status != GCS_INITIALISED) return;
9499 if (stage == GLS_ACTIVATION && !HasBit(config->flags, GCF_RESERVED)) return;
9502 bool needs_palette_remap = config->palette & GRFP_USE_MASK;
9503 if (temporary) {
9504 SpriteFile temporarySpriteFile(filename, subdir, needs_palette_remap);
9505 LoadNewGRFFileFromFile(config, stage, temporarySpriteFile);
9506 } else {
9507 LoadNewGRFFileFromFile(config, stage, OpenCachedSpriteFile(filename, subdir, needs_palette_remap));
9512 * Relocates the old shore sprites at new positions.
9514 * 1. If shore sprites are neither loaded by Action5 nor ActionA, the extra sprites from openttd(w/d).grf are used. (SHORE_REPLACE_ONLY_NEW)
9515 * 2. If a newgrf replaces some shore sprites by ActionA. The (maybe also replaced) grass tiles are used for corner shores. (SHORE_REPLACE_ACTION_A)
9516 * 3. If a newgrf replaces shore sprites by Action5 any shore replacement by ActionA has no effect. (SHORE_REPLACE_ACTION_5)
9518 static void ActivateOldShore()
9520 /* Use default graphics, if no shore sprites were loaded.
9521 * Should not happen, as the base set's extra grf should include some. */
9522 if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A;
9524 if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) {
9525 DupSprite(SPR_ORIGINALSHORE_START + 1, SPR_SHORE_BASE + 1); // SLOPE_W
9526 DupSprite(SPR_ORIGINALSHORE_START + 2, SPR_SHORE_BASE + 2); // SLOPE_S
9527 DupSprite(SPR_ORIGINALSHORE_START + 6, SPR_SHORE_BASE + 3); // SLOPE_SW
9528 DupSprite(SPR_ORIGINALSHORE_START + 0, SPR_SHORE_BASE + 4); // SLOPE_E
9529 DupSprite(SPR_ORIGINALSHORE_START + 4, SPR_SHORE_BASE + 6); // SLOPE_SE
9530 DupSprite(SPR_ORIGINALSHORE_START + 3, SPR_SHORE_BASE + 8); // SLOPE_N
9531 DupSprite(SPR_ORIGINALSHORE_START + 7, SPR_SHORE_BASE + 9); // SLOPE_NW
9532 DupSprite(SPR_ORIGINALSHORE_START + 5, SPR_SHORE_BASE + 12); // SLOPE_NE
9535 if (_loaded_newgrf_features.shore == SHORE_REPLACE_ACTION_A) {
9536 DupSprite(SPR_FLAT_GRASS_TILE + 16, SPR_SHORE_BASE + 0); // SLOPE_STEEP_S
9537 DupSprite(SPR_FLAT_GRASS_TILE + 17, SPR_SHORE_BASE + 5); // SLOPE_STEEP_W
9538 DupSprite(SPR_FLAT_GRASS_TILE + 7, SPR_SHORE_BASE + 7); // SLOPE_WSE
9539 DupSprite(SPR_FLAT_GRASS_TILE + 15, SPR_SHORE_BASE + 10); // SLOPE_STEEP_N
9540 DupSprite(SPR_FLAT_GRASS_TILE + 11, SPR_SHORE_BASE + 11); // SLOPE_NWS
9541 DupSprite(SPR_FLAT_GRASS_TILE + 13, SPR_SHORE_BASE + 13); // SLOPE_ENW
9542 DupSprite(SPR_FLAT_GRASS_TILE + 14, SPR_SHORE_BASE + 14); // SLOPE_SEN
9543 DupSprite(SPR_FLAT_GRASS_TILE + 18, SPR_SHORE_BASE + 15); // SLOPE_STEEP_E
9545 /* XXX - SLOPE_EW, SLOPE_NS are currently not used.
9546 * If they would be used somewhen, then these grass tiles will most like not look as needed */
9547 DupSprite(SPR_FLAT_GRASS_TILE + 5, SPR_SHORE_BASE + 16); // SLOPE_EW
9548 DupSprite(SPR_FLAT_GRASS_TILE + 10, SPR_SHORE_BASE + 17); // SLOPE_NS
9553 * Replocate the old tram depot sprites to the new position, if no new ones were loaded.
9555 static void ActivateOldTramDepot()
9557 if (_loaded_newgrf_features.tram == TRAMWAY_REPLACE_DEPOT_WITH_TRACK) {
9558 DupSprite(SPR_ROAD_DEPOT + 0, SPR_TRAMWAY_DEPOT_NO_TRACK + 0); // use road depot graphics for "no tracks"
9559 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 1, SPR_TRAMWAY_DEPOT_NO_TRACK + 1);
9560 DupSprite(SPR_ROAD_DEPOT + 2, SPR_TRAMWAY_DEPOT_NO_TRACK + 2); // use road depot graphics for "no tracks"
9561 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 3, SPR_TRAMWAY_DEPOT_NO_TRACK + 3);
9562 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 4, SPR_TRAMWAY_DEPOT_NO_TRACK + 4);
9563 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 5, SPR_TRAMWAY_DEPOT_NO_TRACK + 5);
9568 * Decide whether price base multipliers of grfs shall apply globally or only to the grf specifying them
9570 static void FinalisePriceBaseMultipliers()
9572 extern const PriceBaseSpec _price_base_specs[];
9573 /** Features, to which '_grf_id_overrides' applies. Currently vehicle features only. */
9574 static const uint32 override_features = (1 << GSF_TRAINS) | (1 << GSF_ROADVEHICLES) | (1 << GSF_SHIPS) | (1 << GSF_AIRCRAFT);
9576 /* Evaluate grf overrides */
9577 int num_grfs = (uint)_grf_files.size();
9578 int *grf_overrides = AllocaM(int, num_grfs);
9579 for (int i = 0; i < num_grfs; i++) {
9580 grf_overrides[i] = -1;
9582 GRFFile *source = _grf_files[i];
9583 uint32 override = _grf_id_overrides[source->grfid];
9584 if (override == 0) continue;
9586 GRFFile *dest = GetFileByGRFID(override);
9587 if (dest == nullptr) continue;
9589 grf_overrides[i] = find_index(_grf_files, dest);
9590 assert(grf_overrides[i] >= 0);
9593 /* Override features and price base multipliers of earlier loaded grfs */
9594 for (int i = 0; i < num_grfs; i++) {
9595 if (grf_overrides[i] < 0 || grf_overrides[i] >= i) continue;
9596 GRFFile *source = _grf_files[i];
9597 GRFFile *dest = _grf_files[grf_overrides[i]];
9599 uint32 features = (source->grf_features | dest->grf_features) & override_features;
9600 source->grf_features |= features;
9601 dest->grf_features |= features;
9603 for (Price p = PR_BEGIN; p < PR_END; p++) {
9604 /* No price defined -> nothing to do */
9605 if (!HasBit(features, _price_base_specs[p].grf_feature) || source->price_base_multipliers[p] == INVALID_PRICE_MODIFIER) continue;
9606 Debug(grf, 3, "'{}' overrides price base multiplier {} of '{}'", source->filename, p, dest->filename);
9607 dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9611 /* Propagate features and price base multipliers of afterwards loaded grfs, if none is present yet */
9612 for (int i = num_grfs - 1; i >= 0; i--) {
9613 if (grf_overrides[i] < 0 || grf_overrides[i] <= i) continue;
9614 GRFFile *source = _grf_files[i];
9615 GRFFile *dest = _grf_files[grf_overrides[i]];
9617 uint32 features = (source->grf_features | dest->grf_features) & override_features;
9618 source->grf_features |= features;
9619 dest->grf_features |= features;
9621 for (Price p = PR_BEGIN; p < PR_END; p++) {
9622 /* Already a price defined -> nothing to do */
9623 if (!HasBit(features, _price_base_specs[p].grf_feature) || dest->price_base_multipliers[p] != INVALID_PRICE_MODIFIER) continue;
9624 Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, source->filename, dest->filename);
9625 dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9629 /* The 'master grf' now have the correct multipliers. Assign them to the 'addon grfs' to make everything consistent. */
9630 for (int i = 0; i < num_grfs; i++) {
9631 if (grf_overrides[i] < 0) continue;
9632 GRFFile *source = _grf_files[i];
9633 GRFFile *dest = _grf_files[grf_overrides[i]];
9635 uint32 features = (source->grf_features | dest->grf_features) & override_features;
9636 source->grf_features |= features;
9637 dest->grf_features |= features;
9639 for (Price p = PR_BEGIN; p < PR_END; p++) {
9640 if (!HasBit(features, _price_base_specs[p].grf_feature)) continue;
9641 if (source->price_base_multipliers[p] != dest->price_base_multipliers[p]) {
9642 Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, dest->filename, source->filename);
9644 source->price_base_multipliers[p] = dest->price_base_multipliers[p];
9648 /* Apply fallback prices for grf version < 8 */
9649 for (GRFFile * const file : _grf_files) {
9650 if (file->grf_version >= 8) continue;
9651 PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9652 for (Price p = PR_BEGIN; p < PR_END; p++) {
9653 Price fallback_price = _price_base_specs[p].fallback_price;
9654 if (fallback_price != INVALID_PRICE && price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9655 /* No price multiplier has been set.
9656 * So copy the multiplier from the fallback price, maybe a multiplier was set there. */
9657 price_base_multipliers[p] = price_base_multipliers[fallback_price];
9662 /* Decide local/global scope of price base multipliers */
9663 for (GRFFile * const file : _grf_files) {
9664 PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9665 for (Price p = PR_BEGIN; p < PR_END; p++) {
9666 if (price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9667 /* No multiplier was set; set it to a neutral value */
9668 price_base_multipliers[p] = 0;
9669 } else {
9670 if (!HasBit(file->grf_features, _price_base_specs[p].grf_feature)) {
9671 /* The grf does not define any objects of the feature,
9672 * so it must be a difficulty setting. Apply it globally */
9673 Debug(grf, 3, "'{}' sets global price base multiplier {}", file->filename, p);
9674 SetPriceBaseMultiplier(p, price_base_multipliers[p]);
9675 price_base_multipliers[p] = 0;
9676 } else {
9677 Debug(grf, 3, "'{}' sets local price base multiplier {}", file->filename, p);
9684 extern void InitGRFTownGeneratorNames();
9686 /** Finish loading NewGRFs and execute needed post-processing */
9687 static void AfterLoadGRFs()
9689 for (StringIDMapping &it : _string_to_grf_mapping) {
9690 *it.target = MapGRFStringID(it.grfid, it.source);
9692 _string_to_grf_mapping.clear();
9694 /* Free the action 6 override sprites. */
9695 for (GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.begin(); it != _grf_line_to_action6_sprite_override.end(); it++) {
9696 free((*it).second);
9698 _grf_line_to_action6_sprite_override.clear();
9700 /* Polish cargoes */
9701 FinaliseCargoArray();
9703 /* Pre-calculate all refit masks after loading GRF files. */
9704 CalculateRefitMasks();
9706 /* Polish engines */
9707 FinaliseEngineArray();
9709 /* Set the actually used Canal properties */
9710 FinaliseCanals();
9712 /* Add all new houses to the house array. */
9713 FinaliseHouseArray();
9715 /* Add all new industries to the industry array. */
9716 FinaliseIndustriesArray();
9718 /* Add all new objects to the object array. */
9719 FinaliseObjectsArray();
9721 InitializeSortedCargoSpecs();
9723 /* Sort the list of industry types. */
9724 SortIndustryTypes();
9726 /* Create dynamic list of industry legends for smallmap_gui.cpp */
9727 BuildIndustriesLegend();
9729 /* Build the routemap legend, based on the available cargos */
9730 BuildLinkStatsLegend();
9732 /* Add all new airports to the airports array. */
9733 FinaliseAirportsArray();
9734 BindAirportSpecs();
9736 /* Update the townname generators list */
9737 InitGRFTownGeneratorNames();
9739 /* Run all queued vehicle list order changes */
9740 CommitVehicleListOrderChanges();
9742 /* Load old shore sprites in new position, if they were replaced by ActionA */
9743 ActivateOldShore();
9745 /* Load old tram depot sprites in new position, if no new ones are present */
9746 ActivateOldTramDepot();
9748 /* Set up custom rail types */
9749 InitRailTypes();
9750 InitRoadTypes();
9752 for (Engine *e : Engine::IterateType(VEH_ROAD)) {
9753 if (_gted[e->index].rv_max_speed != 0) {
9754 /* Set RV maximum speed from the mph/0.8 unit value */
9755 e->u.road.max_speed = _gted[e->index].rv_max_speed * 4;
9758 RoadTramType rtt = HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? RTT_TRAM : RTT_ROAD;
9760 const GRFFile *file = e->GetGRF();
9761 if (file == nullptr || _gted[e->index].roadtramtype == 0) {
9762 e->u.road.roadtype = (rtt == RTT_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
9763 continue;
9766 /* Remove +1 offset. */
9767 _gted[e->index].roadtramtype--;
9769 const std::vector<RoadTypeLabel> *list = (rtt == RTT_TRAM) ? &file->tramtype_list : &file->roadtype_list;
9770 if (_gted[e->index].roadtramtype < list->size())
9772 RoadTypeLabel rtl = (*list)[_gted[e->index].roadtramtype];
9773 RoadType rt = GetRoadTypeByLabel(rtl);
9774 if (rt != INVALID_ROADTYPE && GetRoadTramType(rt) == rtt) {
9775 e->u.road.roadtype = rt;
9776 continue;
9780 /* Road type is not available, so disable this engine */
9781 e->info.climates = 0;
9784 for (Engine *e : Engine::IterateType(VEH_TRAIN)) {
9785 RailType railtype = GetRailTypeByLabel(_gted[e->index].railtypelabel);
9786 if (railtype == INVALID_RAILTYPE) {
9787 /* Rail type is not available, so disable this engine */
9788 e->info.climates = 0;
9789 } else {
9790 e->u.rail.railtype = railtype;
9794 SetYearEngineAgingStops();
9796 FinalisePriceBaseMultipliers();
9798 /* Deallocate temporary loading data */
9799 free(_gted);
9800 _grm_sprites.clear();
9804 * Load all the NewGRFs.
9805 * @param load_index The offset for the first sprite to add.
9806 * @param num_baseset Number of NewGRFs at the front of the list to look up in the baseset dir instead of the newgrf dir.
9808 void LoadNewGRF(uint load_index, uint num_baseset)
9810 /* In case of networking we need to "sync" the start values
9811 * so all NewGRFs are loaded equally. For this we use the
9812 * start date of the game and we set the counters, etc. to
9813 * 0 so they're the same too. */
9814 Date date = _date;
9815 Year year = _cur_year;
9816 DateFract date_fract = _date_fract;
9817 uint64 tick_counter = _tick_counter;
9818 byte display_opt = _display_opt;
9820 if (_networking) {
9821 _cur_year = _settings_game.game_creation.starting_year;
9822 _date = ConvertYMDToDate(_cur_year, 0, 1);
9823 _date_fract = 0;
9824 _tick_counter = 0;
9825 _display_opt = 0;
9828 InitializeGRFSpecial();
9830 ResetNewGRFData();
9833 * Reset the status of all files, so we can 'retry' to load them.
9834 * This is needed when one for example rearranges the NewGRFs in-game
9835 * and a previously disabled NewGRF becomes usable. If it would not
9836 * be reset, the NewGRF would remain disabled even though it should
9837 * have been enabled.
9839 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
9840 if (c->status != GCS_NOT_FOUND) c->status = GCS_UNKNOWN;
9843 _cur.spriteid = load_index;
9845 /* Load newgrf sprites
9846 * in each loading stage, (try to) open each file specified in the config
9847 * and load information from it. */
9848 for (GrfLoadingStage stage = GLS_LABELSCAN; stage <= GLS_ACTIVATION; stage++) {
9849 /* Set activated grfs back to will-be-activated between reservation- and activation-stage.
9850 * This ensures that action7/9 conditions 0x06 - 0x0A work correctly. */
9851 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
9852 if (c->status == GCS_ACTIVATED) c->status = GCS_INITIALISED;
9855 if (stage == GLS_RESERVE) {
9856 static const uint32 overrides[][2] = {
9857 { 0x44442202, 0x44440111 }, // UKRS addons modifies UKRS
9858 { 0x6D620402, 0x6D620401 }, // DBSetXL ECS extension modifies DBSetXL
9859 { 0x4D656f20, 0x4D656F17 }, // LV4cut modifies LV4
9861 for (size_t i = 0; i < lengthof(overrides); i++) {
9862 SetNewGRFOverride(BSWAP32(overrides[i][0]), BSWAP32(overrides[i][1]));
9866 uint num_grfs = 0;
9867 uint num_non_static = 0;
9869 _cur.stage = stage;
9870 for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
9871 if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND) continue;
9872 if (stage > GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) continue;
9874 Subdirectory subdir = num_grfs < num_baseset ? BASESET_DIR : NEWGRF_DIR;
9875 if (!FioCheckFileExists(c->filename, subdir)) {
9876 Debug(grf, 0, "NewGRF file is missing '{}'; disabling", c->filename);
9877 c->status = GCS_NOT_FOUND;
9878 continue;
9881 if (stage == GLS_LABELSCAN) InitNewGRFFile(c);
9883 if (!HasBit(c->flags, GCF_STATIC) && !HasBit(c->flags, GCF_SYSTEM)) {
9884 if (num_non_static == NETWORK_MAX_GRF_COUNT) {
9885 Debug(grf, 0, "'{}' is not loaded as the maximum number of non-static GRFs has been reached", c->filename);
9886 c->status = GCS_DISABLED;
9887 c->error = new GRFError(STR_NEWGRF_ERROR_MSG_FATAL, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED);
9888 continue;
9890 num_non_static++;
9893 num_grfs++;
9895 LoadNewGRFFile(c, stage, subdir, false);
9896 if (stage == GLS_RESERVE) {
9897 SetBit(c->flags, GCF_RESERVED);
9898 } else if (stage == GLS_ACTIVATION) {
9899 ClrBit(c->flags, GCF_RESERVED);
9900 assert(GetFileByGRFID(c->ident.grfid) == _cur.grffile);
9901 ClearTemporaryNewGRFData(_cur.grffile);
9902 BuildCargoTranslationMap();
9903 Debug(sprite, 2, "LoadNewGRF: Currently {} sprites are loaded", _cur.spriteid);
9904 } else if (stage == GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) {
9905 /* We're not going to activate this, so free whatever data we allocated */
9906 ClearTemporaryNewGRFData(_cur.grffile);
9911 /* Pseudo sprite processing is finished; free temporary stuff */
9912 _cur.ClearDataForNextFile();
9914 /* Call any functions that should be run after GRFs have been loaded. */
9915 AfterLoadGRFs();
9917 /* Now revert back to the original situation */
9918 _cur_year = year;
9919 _date = date;
9920 _date_fract = date_fract;
9921 _tick_counter = tick_counter;
9922 _display_opt = display_opt;