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/>.
8 /** @file newgrf.cpp Base of all NewGRF support. */
12 #include "core/container_func.hpp"
14 #include "fileio_func.h"
15 #include "engine_func.h"
16 #include "engine_base.h"
19 #include "newgrf_engine.h"
20 #include "newgrf_text.h"
21 #include "fontcache.h"
23 #include "landscape.h"
24 #include "newgrf_cargo.h"
25 #include "newgrf_house.h"
26 #include "newgrf_sound.h"
27 #include "newgrf_station.h"
28 #include "industrytype.h"
29 #include "industry_map.h"
30 #include "newgrf_canal.h"
31 #include "newgrf_townname.h"
32 #include "newgrf_industries.h"
33 #include "newgrf_airporttiles.h"
34 #include "newgrf_airport.h"
35 #include "newgrf_object.h"
38 #include "strings_func.h"
39 #include "timer/timer_game_tick.h"
40 #include "timer/timer_game_calendar.h"
41 #include "string_func.h"
42 #include "network/core/config.h"
43 #include "smallmap_gui.h"
46 #include "error_func.h"
47 #include "vehicle_func.h"
49 #include "vehicle_base.h"
51 #include "newgrf_roadstop.h"
53 #include "table/strings.h"
54 #include "table/build_industry.h"
56 #include "safeguards.h"
58 /* TTDPatch extended GRF format codec
59 * (c) Petr Baudis 2004 (GPL'd)
60 * Changes by Florian octo Forster are (c) by the OpenTTD development team.
62 * Contains portions of documentation by TTDPatch team.
63 * Thanks especially to Josef Drexler for the documentation as well as a lot
64 * of help at #tycoon. Also thanks to Michael Blunck for his GRF files which
65 * served as subject to the initial testing of this codec. */
67 /** List of all loaded GRF files */
68 static std::vector
<GRFFile
*> _grf_files
;
70 const std::vector
<GRFFile
*> &GetAllGRFFiles()
75 /** Miscellaneous GRF features, set by Action 0x0D, parameter 0x9E */
76 byte _misc_grf_features
= 0;
78 /** 32 * 8 = 256 flags. Apparently TTDPatch uses this many.. */
79 static uint32_t _ttdpatch_flags
[8];
81 /** Indicates which are the newgrf features currently loaded ingame */
82 GRFLoadedFeatures _loaded_newgrf_features
;
84 static const uint MAX_SPRITEGROUP
= UINT8_MAX
; ///< Maximum GRF-local ID for a spritegroup.
86 /** Temporary data during loading of GRFs */
87 struct GrfProcessingState
{
89 /** Definition of a single Action1 spriteset */
91 SpriteID sprite
; ///< SpriteID of the first sprite of the set.
92 uint num_sprites
; ///< Number of sprites in the set.
95 /** Currently referenceable spritesets */
96 std::map
<uint
, SpriteSet
> spritesets
[GSF_END
];
100 GrfLoadingStage stage
; ///< Current loading stage
101 SpriteID spriteid
; ///< First available SpriteID for loading realsprites.
103 /* Local state in the file */
104 SpriteFile
*file
; ///< File of currently processed GRF file.
105 GRFFile
*grffile
; ///< Currently processed GRF file.
106 GRFConfig
*grfconfig
; ///< Config of the currently processed GRF file.
107 uint32_t nfo_line
; ///< Currently processed pseudo sprite number in the GRF.
109 /* Kind of return values when processing certain actions */
110 int skip_sprites
; ///< Number of pseudo sprites to skip before processing the next one. (-1 to skip to end of file)
112 /* Currently referenceable spritegroups */
113 const SpriteGroup
*spritegroups
[MAX_SPRITEGROUP
+ 1];
115 /** Clear temporary data before processing the next file in the current loading stage */
116 void ClearDataForNextFile()
119 this->skip_sprites
= 0;
121 for (uint i
= 0; i
< GSF_END
; i
++) {
122 this->spritesets
[i
].clear();
125 memset(this->spritegroups
, 0, sizeof(this->spritegroups
));
129 * Records new spritesets.
130 * @param feature GrfSpecFeature the set is defined for.
131 * @param first_sprite SpriteID of the first sprite in the set.
132 * @param first_set First spriteset to define.
133 * @param numsets Number of sets to define.
134 * @param numents Number of sprites per set to define.
136 void AddSpriteSets(byte feature
, SpriteID first_sprite
, uint first_set
, uint numsets
, uint numents
)
138 assert(feature
< GSF_END
);
139 for (uint i
= 0; i
< numsets
; i
++) {
140 SpriteSet
&set
= this->spritesets
[feature
][first_set
+ i
];
141 set
.sprite
= first_sprite
+ i
* numents
;
142 set
.num_sprites
= numents
;
147 * Check whether there are any valid spritesets for a feature.
148 * @param feature GrfSpecFeature to check.
149 * @return true if there are any valid sets.
150 * @note Spritesets with zero sprites are valid to allow callback-failures.
152 bool HasValidSpriteSets(byte feature
) const
154 assert(feature
< GSF_END
);
155 return !this->spritesets
[feature
].empty();
159 * Check whether a specific set is defined.
160 * @param feature GrfSpecFeature to check.
161 * @param set Set to check.
162 * @return true if the set is valid.
163 * @note Spritesets with zero sprites are valid to allow callback-failures.
165 bool IsValidSpriteSet(byte feature
, uint set
) const
167 assert(feature
< GSF_END
);
168 return this->spritesets
[feature
].find(set
) != this->spritesets
[feature
].end();
172 * Returns the first sprite of a spriteset.
173 * @param feature GrfSpecFeature to query.
174 * @param set Set to query.
175 * @return First sprite of the set.
177 SpriteID
GetSprite(byte feature
, uint set
) const
179 assert(IsValidSpriteSet(feature
, set
));
180 return this->spritesets
[feature
].find(set
)->second
.sprite
;
184 * Returns the number of sprites in a spriteset
185 * @param feature GrfSpecFeature to query.
186 * @param set Set to query.
187 * @return Number of sprites in the set.
189 uint
GetNumEnts(byte feature
, uint set
) const
191 assert(IsValidSpriteSet(feature
, set
));
192 return this->spritesets
[feature
].find(set
)->second
.num_sprites
;
196 static GrfProcessingState _cur
;
200 * Helper to check whether an image index is valid for a particular NewGRF vehicle.
201 * @tparam T The type of vehicle.
202 * @param image_index The image index to check.
203 * @return True iff the image index is valid, or 0xFD (use new graphics).
205 template <VehicleType T
>
206 static inline bool IsValidNewGRFImageIndex(uint8_t image_index
)
208 return image_index
== 0xFD || IsValidImageIndex
<T
>(image_index
);
211 class OTTDByteReaderSignal
{ };
213 /** Class to read from a NewGRF file */
220 ByteReader(byte
*data
, byte
*end
) : data(data
), end(end
) { }
222 inline byte
*ReadBytes(size_t size
)
224 if (data
+ size
>= end
) {
225 /* Put data at the end, as would happen if every byte had been individually read. */
227 throw OTTDByteReaderSignal();
235 inline byte
ReadByte()
237 if (data
< end
) return *(data
)++;
238 throw OTTDByteReaderSignal();
243 uint16_t val
= ReadByte();
244 return val
| (ReadByte() << 8);
247 uint16_t ReadExtendedByte()
249 uint16_t val
= ReadByte();
250 return val
== 0xFF ? ReadWord() : val
;
255 uint32_t val
= ReadWord();
256 return val
| (ReadWord() << 16);
259 uint32_t ReadVarSize(byte size
)
262 case 1: return ReadByte();
263 case 2: return ReadWord();
264 case 4: return ReadDWord();
271 const char *ReadString()
273 char *string
= reinterpret_cast<char *>(data
);
274 size_t string_length
= ttd_strnlen(string
, Remaining());
276 if (string_length
== Remaining()) {
277 /* String was not NUL terminated, so make sure it is now. */
278 string
[string_length
- 1] = '\0';
279 GrfMsg(7, "String was not terminated with a zero byte.");
281 /* Increase the string length to include the NUL byte. */
289 inline size_t Remaining() const
294 inline bool HasData(size_t count
= 1) const
296 return data
+ count
<= end
;
304 inline void Skip(size_t len
)
307 /* It is valid to move the buffer to exactly the end of the data,
308 * as there may not be any more data read. */
309 if (data
> end
) throw OTTDByteReaderSignal();
313 typedef void (*SpecialSpriteHandler
)(ByteReader
*buf
);
315 /** The maximum amount of stations a single GRF is allowed to add */
316 static const uint NUM_STATIONS_PER_GRF
= UINT16_MAX
- 1;
318 /** Temporary engine data used when loading only */
319 struct GRFTempEngineData
{
320 /** Summary state of refittability properties */
322 UNSET
= 0, ///< No properties assigned. Default refit masks shall be activated.
323 EMPTY
, ///< GRF defined vehicle as not-refittable. The vehicle shall only carry the default cargo.
324 NONEMPTY
, ///< GRF defined the vehicle as refittable. If the refitmask is empty after translation (cargotypes not available), disable the vehicle.
327 uint16_t cargo_allowed
;
328 uint16_t cargo_disallowed
;
329 RailTypeLabel railtypelabel
;
330 uint8_t roadtramtype
;
331 const GRFFile
*defaultcargo_grf
; ///< GRF defining the cargo translation table to use if the default cargo is the 'first refittable'.
332 Refittability refittability
; ///< Did the newgrf set any refittability property? If not, default refittability will be applied.
333 uint8_t rv_max_speed
; ///< Temporary storage of RV prop 15, maximum speed in mph/0.8
334 CargoTypes ctt_include_mask
; ///< Cargo types always included in the refit mask.
335 CargoTypes ctt_exclude_mask
; ///< Cargo types always excluded from the refit mask.
338 * Update the summary refittability on setting a refittability property.
339 * @param non_empty true if the GRF sets the vehicle to be refittable.
341 void UpdateRefittability(bool non_empty
)
344 this->refittability
= NONEMPTY
;
345 } else if (this->refittability
== UNSET
) {
346 this->refittability
= EMPTY
;
351 static std::vector
<GRFTempEngineData
> _gted
; ///< Temporary engine data used during NewGRF loading
354 * Contains the GRF ID of the owner of a vehicle if it has been reserved.
355 * GRM for vehicles is only used if dynamic engine allocation is disabled,
356 * so 256 is the number of original engines. */
357 static uint32_t _grm_engines
[256];
359 /** Contains the GRF ID of the owner of a cargo if it has been reserved */
360 static uint32_t _grm_cargoes
[NUM_CARGO
* 2];
366 GRFLocation(uint32_t grfid
, uint32_t nfoline
) : grfid(grfid
), nfoline(nfoline
) { }
368 bool operator<(const GRFLocation
&other
) const
370 return this->grfid
< other
.grfid
|| (this->grfid
== other
.grfid
&& this->nfoline
< other
.nfoline
);
373 bool operator == (const GRFLocation
&other
) const
375 return this->grfid
== other
.grfid
&& this->nfoline
== other
.nfoline
;
379 static std::map
<GRFLocation
, SpriteID
> _grm_sprites
;
380 typedef std::map
<GRFLocation
, std::vector
<byte
>> GRFLineToSpriteOverride
;
381 static GRFLineToSpriteOverride _grf_line_to_action6_sprite_override
;
384 * Debug() function dedicated to newGRF debugging messages
385 * Function is essentially the same as Debug(grf, severity, ...) with the
386 * addition of file:line information when parsing grf files.
387 * NOTE: for the above reason(s) GrfMsg() should ONLY be used for
388 * loading/parsing grf files, not for runtime debug messages as there
389 * is no file information available during that time.
390 * @param severity debugging severity level, see debug.h
391 * @param msg the message
393 void GrfMsgI(int severity
, const std::string
&msg
)
395 Debug(grf
, severity
, "[{}:{}] {}", _cur
.grfconfig
->filename
, _cur
.nfo_line
, msg
);
399 * Obtain a NewGRF file by its grfID
400 * @param grfid The grfID to obtain the file for
403 static GRFFile
*GetFileByGRFID(uint32_t grfid
)
405 for (GRFFile
* const file
: _grf_files
) {
406 if (file
->grfid
== grfid
) return file
;
412 * Obtain a NewGRF file by its filename
413 * @param filename The filename to obtain the file for.
416 static GRFFile
*GetFileByFilename(const std::string
&filename
)
418 for (GRFFile
* const file
: _grf_files
) {
419 if (file
->filename
== filename
) return file
;
424 /** Reset all NewGRFData that was used only while processing data */
425 static void ClearTemporaryNewGRFData(GRFFile
*gf
)
432 * @param message Error message or STR_NULL.
433 * @param config GRFConfig to disable, nullptr for current.
434 * @return Error message of the GRF for further customisation.
436 static GRFError
*DisableGrf(StringID message
= STR_NULL
, GRFConfig
*config
= nullptr)
439 if (config
!= nullptr) {
440 file
= GetFileByGRFID(config
->ident
.grfid
);
442 config
= _cur
.grfconfig
;
446 config
->status
= GCS_DISABLED
;
447 if (file
!= nullptr) ClearTemporaryNewGRFData(file
);
448 if (config
== _cur
.grfconfig
) _cur
.skip_sprites
= -1;
450 if (message
== STR_NULL
) return nullptr;
452 config
->error
= {STR_NEWGRF_ERROR_MSG_FATAL
, message
};
453 if (config
== _cur
.grfconfig
) config
->error
->param_value
[0] = _cur
.nfo_line
;
454 return &config
->error
.value();
458 * Information for mapping static StringIDs.
460 struct StringIDMapping
{
461 uint32_t grfid
; ///< Source NewGRF.
462 StringID source
; ///< Source StringID (GRF local).
463 StringID
*target
; ///< Destination for mapping result.
465 typedef std::vector
<StringIDMapping
> StringIDMappingVector
;
466 static StringIDMappingVector _string_to_grf_mapping
;
469 * Record a static StringID for getting translated later.
470 * @param source Source StringID (GRF local).
471 * @param target Destination for the mapping result.
473 static void AddStringForMapping(StringID source
, StringID
*target
)
475 *target
= STR_UNDEFINED
;
476 _string_to_grf_mapping
.push_back({_cur
.grffile
->grfid
, source
, target
});
480 * Perform a mapping from TTDPatch's string IDs to OpenTTD's
481 * string IDs, but only for the ones we are aware off; the rest
482 * like likely unused and will show a warning.
483 * @param str the string ID to convert
484 * @return the converted string ID
486 static StringID
TTDPStringIDToOTTDStringIDMapping(StringID str
)
488 /* StringID table for TextIDs 0x4E->0x6D */
489 static const StringID units_volume
[] = {
490 STR_ITEMS
, STR_PASSENGERS
, STR_TONS
, STR_BAGS
,
491 STR_LITERS
, STR_ITEMS
, STR_CRATES
, STR_TONS
,
492 STR_TONS
, STR_TONS
, STR_TONS
, STR_BAGS
,
493 STR_TONS
, STR_TONS
, STR_TONS
, STR_BAGS
,
494 STR_TONS
, STR_TONS
, STR_BAGS
, STR_LITERS
,
495 STR_TONS
, STR_LITERS
, STR_TONS
, STR_ITEMS
,
496 STR_BAGS
, STR_LITERS
, STR_TONS
, STR_ITEMS
,
497 STR_TONS
, STR_ITEMS
, STR_LITERS
, STR_ITEMS
500 /* A string straight from a NewGRF; this was already translated by MapGRFStringID(). */
501 assert(!IsInsideMM(str
, 0xD000, 0xD7FF));
503 #define TEXTID_TO_STRINGID(begin, end, stringid, stringend) \
504 static_assert(stringend - stringid == end - begin); \
505 if (str >= begin && str <= end) return str + (stringid - begin)
507 /* We have some changes in our cargo strings, resulting in some missing. */
508 TEXTID_TO_STRINGID(0x000E, 0x002D, STR_CARGO_PLURAL_NOTHING
, STR_CARGO_PLURAL_FIZZY_DRINKS
);
509 TEXTID_TO_STRINGID(0x002E, 0x004D, STR_CARGO_SINGULAR_NOTHING
, STR_CARGO_SINGULAR_FIZZY_DRINK
);
510 if (str
>= 0x004E && str
<= 0x006D) return units_volume
[str
- 0x004E];
511 TEXTID_TO_STRINGID(0x006E, 0x008D, STR_QUANTITY_NOTHING
, STR_QUANTITY_FIZZY_DRINKS
);
512 TEXTID_TO_STRINGID(0x008E, 0x00AD, STR_ABBREV_NOTHING
, STR_ABBREV_FIZZY_DRINKS
);
513 TEXTID_TO_STRINGID(0x00D1, 0x00E0, STR_COLOUR_DARK_BLUE
, STR_COLOUR_WHITE
);
515 /* Map building names according to our lang file changes. There are several
516 * ranges of house ids, all of which need to be remapped to allow newgrfs
517 * to use original house names. */
518 TEXTID_TO_STRINGID(0x200F, 0x201F, STR_TOWN_BUILDING_NAME_TALL_OFFICE_BLOCK_1
, STR_TOWN_BUILDING_NAME_OLD_HOUSES_1
);
519 TEXTID_TO_STRINGID(0x2036, 0x2041, STR_TOWN_BUILDING_NAME_COTTAGES_1
, STR_TOWN_BUILDING_NAME_SHOPPING_MALL_1
);
520 TEXTID_TO_STRINGID(0x2059, 0x205C, STR_TOWN_BUILDING_NAME_IGLOO_1
, STR_TOWN_BUILDING_NAME_PIGGY_BANK_1
);
522 /* Same thing for industries */
523 TEXTID_TO_STRINGID(0x4802, 0x4826, STR_INDUSTRY_NAME_COAL_MINE
, STR_INDUSTRY_NAME_SUGAR_MINE
);
524 TEXTID_TO_STRINGID(0x482D, 0x482E, STR_NEWS_INDUSTRY_CONSTRUCTION
, STR_NEWS_INDUSTRY_PLANTED
);
525 TEXTID_TO_STRINGID(0x4832, 0x4834, STR_NEWS_INDUSTRY_CLOSURE_GENERAL
, STR_NEWS_INDUSTRY_CLOSURE_LACK_OF_TREES
);
526 TEXTID_TO_STRINGID(0x4835, 0x4838, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL
, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM
);
527 TEXTID_TO_STRINGID(0x4839, 0x483A, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL
, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM
);
530 case 0x4830: return STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY
;
531 case 0x4831: return STR_ERROR_FOREST_CAN_ONLY_BE_PLANTED
;
532 case 0x483B: return STR_ERROR_CAN_ONLY_BE_POSITIONED
;
534 #undef TEXTID_TO_STRINGID
536 if (str
== STR_NULL
) return STR_EMPTY
;
538 Debug(grf
, 0, "Unknown StringID 0x{:04X} remapped to STR_EMPTY. Please open a Feature Request if you need it", str
);
544 * Used when setting an object's property to map to the GRF's strings
545 * while taking in consideration the "drift" between TTDPatch string system and OpenTTD's one
546 * @param grfid Id of the grf file.
547 * @param str StringID that we want to have the equivalent in OoenTTD.
548 * @return The properly adjusted StringID.
550 StringID
MapGRFStringID(uint32_t grfid
, StringID str
)
552 if (IsInsideMM(str
, 0xD800, 0x10000)) {
553 /* General text provided by NewGRF.
554 * In the specs this is called the 0xDCxx range (misc persistent texts),
555 * but we meanwhile extended the range to 0xD800-0xFFFF.
556 * Note: We are not involved in the "persistent" business, since we do not store
557 * any NewGRF strings in savegames. */
558 return GetGRFStringID(grfid
, str
);
559 } else if (IsInsideMM(str
, 0xD000, 0xD800)) {
560 /* Callback text provided by NewGRF.
561 * In the specs this is called the 0xD0xx range (misc graphics texts).
562 * These texts can be returned by various callbacks.
564 * Due to how TTDP implements the GRF-local- to global-textid translation
565 * texts included via 0x80 or 0x81 control codes have to add 0x400 to the textid.
566 * We do not care about that difference and just mask out the 0x400 bit.
569 return GetGRFStringID(grfid
, str
);
571 /* The NewGRF wants to include/reference an original TTD string.
572 * Try our best to find an equivalent one. */
573 return TTDPStringIDToOTTDStringIDMapping(str
);
577 static std::map
<uint32_t, uint32_t> _grf_id_overrides
;
580 * Set the override for a NewGRF
581 * @param source_grfid The grfID which wants to override another NewGRF.
582 * @param target_grfid The grfID which is being overridden.
584 static void SetNewGRFOverride(uint32_t source_grfid
, uint32_t target_grfid
)
586 _grf_id_overrides
[source_grfid
] = target_grfid
;
587 GrfMsg(5, "SetNewGRFOverride: Added override of 0x{:X} to 0x{:X}", BSWAP32(source_grfid
), BSWAP32(target_grfid
));
591 * Returns the engine associated to a certain internal_id, resp. allocates it.
592 * @param file NewGRF that wants to change the engine.
593 * @param type Vehicle type.
594 * @param internal_id Engine ID inside the NewGRF.
595 * @param static_access If the engine is not present, return nullptr instead of allocating a new engine. (Used for static Action 0x04).
596 * @return The requested engine.
598 static Engine
*GetNewEngine(const GRFFile
*file
, VehicleType type
, uint16_t internal_id
, bool static_access
= false)
600 /* Hack for add-on GRFs that need to modify another GRF's engines. This lets
601 * them use the same engine slots. */
602 uint32_t scope_grfid
= INVALID_GRFID
; // If not using dynamic_engines, all newgrfs share their ID range
603 if (_settings_game
.vehicle
.dynamic_engines
) {
604 /* If dynamic_engies is enabled, there can be multiple independent ID ranges. */
605 scope_grfid
= file
->grfid
;
606 uint32_t override
= _grf_id_overrides
[file
->grfid
];
608 scope_grfid
= override
;
609 const GRFFile
*grf_match
= GetFileByGRFID(override
);
610 if (grf_match
== nullptr) {
611 GrfMsg(5, "Tried mapping from GRFID {:x} to {:x} but target is not loaded", BSWAP32(file
->grfid
), BSWAP32(override
));
613 GrfMsg(5, "Mapping from GRFID {:x} to {:x}", BSWAP32(file
->grfid
), BSWAP32(override
));
617 /* Check if the engine is registered in the override manager */
618 EngineID engine
= _engine_mngr
.GetID(type
, internal_id
, scope_grfid
);
619 if (engine
!= INVALID_ENGINE
) {
620 Engine
*e
= Engine::Get(engine
);
621 if (e
->grf_prop
.grffile
== nullptr) e
->grf_prop
.grffile
= file
;
626 /* Check if there is an unreserved slot */
627 EngineID engine
= _engine_mngr
.GetID(type
, internal_id
, INVALID_GRFID
);
628 if (engine
!= INVALID_ENGINE
) {
629 Engine
*e
= Engine::Get(engine
);
631 if (e
->grf_prop
.grffile
== nullptr) {
632 e
->grf_prop
.grffile
= file
;
633 GrfMsg(5, "Replaced engine at index {} for GRFID {:x}, type {}, index {}", e
->index
, BSWAP32(file
->grfid
), type
, internal_id
);
636 /* Reserve the engine slot */
637 if (!static_access
) {
638 EngineIDMapping
*eid
= _engine_mngr
.data() + engine
;
639 eid
->grfid
= scope_grfid
; // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
645 if (static_access
) return nullptr;
647 if (!Engine::CanAllocateItem()) {
648 GrfMsg(0, "Can't allocate any more engines");
652 size_t engine_pool_size
= Engine::GetPoolSize();
654 /* ... it's not, so create a new one based off an existing engine */
655 Engine
*e
= new Engine(type
, internal_id
);
656 e
->grf_prop
.grffile
= file
;
658 /* Reserve the engine slot */
659 assert(_engine_mngr
.size() == e
->index
);
660 _engine_mngr
.push_back({
661 scope_grfid
, // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
664 std::min
<uint8_t>(internal_id
, _engine_counts
[type
]) // substitute_id == _engine_counts[subtype] means "no substitute"
667 if (engine_pool_size
!= Engine::GetPoolSize()) {
668 /* Resize temporary engine data ... */
669 _gted
.resize(Engine::GetPoolSize());
671 if (type
== VEH_TRAIN
) {
672 _gted
[e
->index
].railtypelabel
= GetRailTypeInfo(e
->u
.rail
.railtype
)->label
;
675 GrfMsg(5, "Created new engine at index {} for GRFID {:x}, type {}, index {}", e
->index
, BSWAP32(file
->grfid
), type
, internal_id
);
681 * Return the ID of a new engine
682 * @param file The NewGRF file providing the engine.
683 * @param type The Vehicle type.
684 * @param internal_id NewGRF-internal ID of the engine.
685 * @return The new EngineID.
686 * @note depending on the dynamic_engine setting and a possible override
687 * property the grfID may be unique or overwriting or partially re-defining
688 * properties of an existing engine.
690 EngineID
GetNewEngineID(const GRFFile
*file
, VehicleType type
, uint16_t internal_id
)
692 uint32_t scope_grfid
= INVALID_GRFID
; // If not using dynamic_engines, all newgrfs share their ID range
693 if (_settings_game
.vehicle
.dynamic_engines
) {
694 scope_grfid
= file
->grfid
;
695 uint32_t override
= _grf_id_overrides
[file
->grfid
];
696 if (override
!= 0) scope_grfid
= override
;
699 return _engine_mngr
.GetID(type
, internal_id
, scope_grfid
);
703 * Map the colour modifiers of TTDPatch to those that Open is using.
704 * @param grf_sprite Pointer to the structure been modified.
706 static void MapSpriteMappingRecolour(PalSpriteID
*grf_sprite
)
708 if (HasBit(grf_sprite
->pal
, 14)) {
709 ClrBit(grf_sprite
->pal
, 14);
710 SetBit(grf_sprite
->sprite
, SPRITE_MODIFIER_OPAQUE
);
713 if (HasBit(grf_sprite
->sprite
, 14)) {
714 ClrBit(grf_sprite
->sprite
, 14);
715 SetBit(grf_sprite
->sprite
, PALETTE_MODIFIER_TRANSPARENT
);
718 if (HasBit(grf_sprite
->sprite
, 15)) {
719 ClrBit(grf_sprite
->sprite
, 15);
720 SetBit(grf_sprite
->sprite
, PALETTE_MODIFIER_COLOUR
);
725 * Read a sprite and a palette from the GRF and convert them into a format
726 * suitable to OpenTTD.
727 * @param buf Input stream.
728 * @param read_flags Whether to read TileLayoutFlags.
729 * @param invert_action1_flag Set to true, if palette bit 15 means 'not from action 1'.
730 * @param use_cur_spritesets Whether to use currently referenceable action 1 sets.
731 * @param feature GrfSpecFeature to use spritesets from.
732 * @param[out] grf_sprite Read sprite and palette.
733 * @param[out] max_sprite_offset Optionally returns the number of sprites in the spriteset of the sprite. (0 if no spritset)
734 * @param[out] max_palette_offset Optionally returns the number of sprites in the spriteset of the palette. (0 if no spritset)
735 * @return Read TileLayoutFlags.
737 static TileLayoutFlags
ReadSpriteLayoutSprite(ByteReader
*buf
, bool read_flags
, bool invert_action1_flag
, bool use_cur_spritesets
, int feature
, PalSpriteID
*grf_sprite
, uint16_t *max_sprite_offset
= nullptr, uint16_t *max_palette_offset
= nullptr)
739 grf_sprite
->sprite
= buf
->ReadWord();
740 grf_sprite
->pal
= buf
->ReadWord();
741 TileLayoutFlags flags
= read_flags
? (TileLayoutFlags
)buf
->ReadWord() : TLF_NOTHING
;
743 MapSpriteMappingRecolour(grf_sprite
);
745 bool custom_sprite
= HasBit(grf_sprite
->pal
, 15) != invert_action1_flag
;
746 ClrBit(grf_sprite
->pal
, 15);
748 /* Use sprite from Action 1 */
749 uint index
= GB(grf_sprite
->sprite
, 0, 14);
750 if (use_cur_spritesets
&& (!_cur
.IsValidSpriteSet(feature
, index
) || _cur
.GetNumEnts(feature
, index
) == 0)) {
751 GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset {}", index
);
752 grf_sprite
->sprite
= SPR_IMG_QUERY
;
753 grf_sprite
->pal
= PAL_NONE
;
755 SpriteID sprite
= use_cur_spritesets
? _cur
.GetSprite(feature
, index
) : index
;
756 if (max_sprite_offset
!= nullptr) *max_sprite_offset
= use_cur_spritesets
? _cur
.GetNumEnts(feature
, index
) : UINT16_MAX
;
757 SB(grf_sprite
->sprite
, 0, SPRITE_WIDTH
, sprite
);
758 SetBit(grf_sprite
->sprite
, SPRITE_MODIFIER_CUSTOM_SPRITE
);
760 } else if ((flags
& TLF_SPRITE_VAR10
) && !(flags
& TLF_SPRITE_REG_FLAGS
)) {
761 GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout specifies var10 value for non-action-1 sprite");
762 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT
);
766 if (flags
& TLF_CUSTOM_PALETTE
) {
767 /* Use palette from Action 1 */
768 uint index
= GB(grf_sprite
->pal
, 0, 14);
769 if (use_cur_spritesets
&& (!_cur
.IsValidSpriteSet(feature
, index
) || _cur
.GetNumEnts(feature
, index
) == 0)) {
770 GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset {} for 'palette'", index
);
771 grf_sprite
->pal
= PAL_NONE
;
773 SpriteID sprite
= use_cur_spritesets
? _cur
.GetSprite(feature
, index
) : index
;
774 if (max_palette_offset
!= nullptr) *max_palette_offset
= use_cur_spritesets
? _cur
.GetNumEnts(feature
, index
) : UINT16_MAX
;
775 SB(grf_sprite
->pal
, 0, SPRITE_WIDTH
, sprite
);
776 SetBit(grf_sprite
->pal
, SPRITE_MODIFIER_CUSTOM_SPRITE
);
778 } else if ((flags
& TLF_PALETTE_VAR10
) && !(flags
& TLF_PALETTE_REG_FLAGS
)) {
779 GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 value for non-action-1 palette");
780 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT
);
788 * Preprocess the TileLayoutFlags and read register modifiers from the GRF.
789 * @param buf Input stream.
790 * @param flags TileLayoutFlags to process.
791 * @param is_parent Whether the sprite is a parentsprite with a bounding box.
792 * @param dts Sprite layout to insert data into.
793 * @param index Sprite index to process; 0 for ground sprite.
795 static void ReadSpriteLayoutRegisters(ByteReader
*buf
, TileLayoutFlags flags
, bool is_parent
, NewGRFSpriteLayout
*dts
, uint index
)
797 if (!(flags
& TLF_DRAWING_FLAGS
)) return;
799 if (dts
->registers
== nullptr) dts
->AllocateRegisters();
800 TileLayoutRegisters
®s
= const_cast<TileLayoutRegisters
&>(dts
->registers
[index
]);
801 regs
.flags
= flags
& TLF_DRAWING_FLAGS
;
803 if (flags
& TLF_DODRAW
) regs
.dodraw
= buf
->ReadByte();
804 if (flags
& TLF_SPRITE
) regs
.sprite
= buf
->ReadByte();
805 if (flags
& TLF_PALETTE
) regs
.palette
= buf
->ReadByte();
808 if (flags
& TLF_BB_XY_OFFSET
) {
809 regs
.delta
.parent
[0] = buf
->ReadByte();
810 regs
.delta
.parent
[1] = buf
->ReadByte();
812 if (flags
& TLF_BB_Z_OFFSET
) regs
.delta
.parent
[2] = buf
->ReadByte();
814 if (flags
& TLF_CHILD_X_OFFSET
) regs
.delta
.child
[0] = buf
->ReadByte();
815 if (flags
& TLF_CHILD_Y_OFFSET
) regs
.delta
.child
[1] = buf
->ReadByte();
818 if (flags
& TLF_SPRITE_VAR10
) {
819 regs
.sprite_var10
= buf
->ReadByte();
820 if (regs
.sprite_var10
> TLR_MAX_VAR10
) {
821 GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 ({}) exceeding the maximal allowed value {}", regs
.sprite_var10
, TLR_MAX_VAR10
);
822 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT
);
827 if (flags
& TLF_PALETTE_VAR10
) {
828 regs
.palette_var10
= buf
->ReadByte();
829 if (regs
.palette_var10
> TLR_MAX_VAR10
) {
830 GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 ({}) exceeding the maximal allowed value {}", regs
.palette_var10
, TLR_MAX_VAR10
);
831 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT
);
838 * Read a spritelayout from the GRF.
840 * @param num_building_sprites Number of building sprites to read
841 * @param use_cur_spritesets Whether to use currently referenceable action 1 sets.
842 * @param feature GrfSpecFeature to use spritesets from.
843 * @param allow_var10 Whether the spritelayout may specify var10 values for resolving multiple action-1-2-3 chains
844 * @param no_z_position Whether bounding boxes have no Z offset
845 * @param dts Layout container to output into
846 * @return True on error (GRF was disabled).
848 static bool ReadSpriteLayout(ByteReader
*buf
, uint num_building_sprites
, bool use_cur_spritesets
, byte feature
, bool allow_var10
, bool no_z_position
, NewGRFSpriteLayout
*dts
)
850 bool has_flags
= HasBit(num_building_sprites
, 6);
851 ClrBit(num_building_sprites
, 6);
852 TileLayoutFlags valid_flags
= TLF_KNOWN_FLAGS
;
853 if (!allow_var10
) valid_flags
&= ~TLF_VAR10_FLAGS
;
854 dts
->Allocate(num_building_sprites
); // allocate before reading groundsprite flags
856 std::vector
<uint16_t> max_sprite_offset(num_building_sprites
+ 1, 0);
857 std::vector
<uint16_t> max_palette_offset(num_building_sprites
+ 1, 0);
860 TileLayoutFlags flags
= ReadSpriteLayoutSprite(buf
, has_flags
, false, use_cur_spritesets
, feature
, &dts
->ground
, max_sprite_offset
.data(), max_palette_offset
.data());
861 if (_cur
.skip_sprites
< 0) return true;
863 if (flags
& ~(valid_flags
& ~TLF_NON_GROUND_FLAGS
)) {
864 GrfMsg(1, "ReadSpriteLayout: Spritelayout uses invalid flag 0x{:X} for ground sprite", flags
& ~(valid_flags
& ~TLF_NON_GROUND_FLAGS
));
865 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT
);
869 ReadSpriteLayoutRegisters(buf
, flags
, false, dts
, 0);
870 if (_cur
.skip_sprites
< 0) return true;
872 for (uint i
= 0; i
< num_building_sprites
; i
++) {
873 DrawTileSeqStruct
*seq
= const_cast<DrawTileSeqStruct
*>(&dts
->seq
[i
]);
875 flags
= ReadSpriteLayoutSprite(buf
, has_flags
, false, use_cur_spritesets
, feature
, &seq
->image
, max_sprite_offset
.data() + i
+ 1, max_palette_offset
.data() + i
+ 1);
876 if (_cur
.skip_sprites
< 0) return true;
878 if (flags
& ~valid_flags
) {
879 GrfMsg(1, "ReadSpriteLayout: Spritelayout uses unknown flag 0x{:X}", flags
& ~valid_flags
);
880 DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT
);
884 seq
->delta_x
= buf
->ReadByte();
885 seq
->delta_y
= buf
->ReadByte();
887 if (!no_z_position
) seq
->delta_z
= buf
->ReadByte();
889 if (seq
->IsParentSprite()) {
890 seq
->size_x
= buf
->ReadByte();
891 seq
->size_y
= buf
->ReadByte();
892 seq
->size_z
= buf
->ReadByte();
895 ReadSpriteLayoutRegisters(buf
, flags
, seq
->IsParentSprite(), dts
, i
+ 1);
896 if (_cur
.skip_sprites
< 0) return true;
899 /* Check if the number of sprites per spriteset is consistent */
900 bool is_consistent
= true;
901 dts
->consistent_max_offset
= 0;
902 for (uint i
= 0; i
< num_building_sprites
+ 1; i
++) {
903 if (max_sprite_offset
[i
] > 0) {
904 if (dts
->consistent_max_offset
== 0) {
905 dts
->consistent_max_offset
= max_sprite_offset
[i
];
906 } else if (dts
->consistent_max_offset
!= max_sprite_offset
[i
]) {
907 is_consistent
= false;
911 if (max_palette_offset
[i
] > 0) {
912 if (dts
->consistent_max_offset
== 0) {
913 dts
->consistent_max_offset
= max_palette_offset
[i
];
914 } else if (dts
->consistent_max_offset
!= max_palette_offset
[i
]) {
915 is_consistent
= false;
921 /* When the Action1 sets are unknown, everything should be 0 (no spriteset usage) or UINT16_MAX (some spriteset usage) */
922 assert(use_cur_spritesets
|| (is_consistent
&& (dts
->consistent_max_offset
== 0 || dts
->consistent_max_offset
== UINT16_MAX
)));
924 if (!is_consistent
|| dts
->registers
!= nullptr) {
925 dts
->consistent_max_offset
= 0;
926 if (dts
->registers
== nullptr) dts
->AllocateRegisters();
928 for (uint i
= 0; i
< num_building_sprites
+ 1; i
++) {
929 TileLayoutRegisters
®s
= const_cast<TileLayoutRegisters
&>(dts
->registers
[i
]);
930 regs
.max_sprite_offset
= max_sprite_offset
[i
];
931 regs
.max_palette_offset
= max_palette_offset
[i
];
939 * Translate the refit mask. refit_mask is uint32_t as it has not been mapped to CargoTypes.
941 static CargoTypes
TranslateRefitMask(uint32_t refit_mask
)
943 CargoTypes result
= 0;
944 for (uint8_t bit
: SetBitIterator(refit_mask
)) {
945 CargoID cargo
= GetCargoTranslation(bit
, _cur
.grffile
, true);
946 if (IsValidCargoID(cargo
)) SetBit(result
, cargo
);
952 * Converts TTD(P) Base Price pointers into the enum used by OTTD
953 * See http://wiki.ttdpatch.net/tiki-index.php?page=BaseCosts
954 * @param base_pointer TTD(P) Base Price Pointer
955 * @param error_location Function name for grf error messages
956 * @param[out] index If \a base_pointer is valid, \a index is assigned to the matching price; else it is left unchanged
958 static void ConvertTTDBasePrice(uint32_t base_pointer
, const char *error_location
, Price
*index
)
960 /* Special value for 'none' */
961 if (base_pointer
== 0) {
962 *index
= INVALID_PRICE
;
966 static const uint32_t start
= 0x4B34; ///< Position of first base price
967 static const uint32_t size
= 6; ///< Size of each base price record
969 if (base_pointer
< start
|| (base_pointer
- start
) % size
!= 0 || (base_pointer
- start
) / size
>= PR_END
) {
970 GrfMsg(1, "{}: Unsupported running cost base 0x{:04X}, ignoring", error_location
, base_pointer
);
974 *index
= (Price
)((base_pointer
- start
) / size
);
977 /** Possible return values for the FeatureChangeInfo functions */
978 enum ChangeInfoResult
{
979 CIR_SUCCESS
, ///< Variable was parsed and read
980 CIR_DISABLED
, ///< GRF was disabled due to error
981 CIR_UNHANDLED
, ///< Variable was parsed but unread
982 CIR_UNKNOWN
, ///< Variable is unknown
983 CIR_INVALID_ID
, ///< Attempt to modify an invalid ID
986 typedef ChangeInfoResult (*VCI_Handler
)(uint engine
, int numinfo
, int prop
, ByteReader
*buf
);
989 * Define properties common to all vehicles
990 * @param ei Engine info.
991 * @param prop The property to change.
992 * @param buf The property value.
993 * @return ChangeInfoResult.
995 static ChangeInfoResult
CommonVehicleChangeInfo(EngineInfo
*ei
, int prop
, ByteReader
*buf
)
998 case 0x00: // Introduction date
999 ei
->base_intro
= buf
->ReadWord() + CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR
;
1002 case 0x02: // Decay speed
1003 ei
->decay_speed
= buf
->ReadByte();
1006 case 0x03: // Vehicle life
1007 ei
->lifelength
= buf
->ReadByte();
1010 case 0x04: // Model life
1011 ei
->base_life
= buf
->ReadByte();
1014 case 0x06: // Climates available
1015 ei
->climates
= buf
->ReadByte();
1018 case PROP_VEHICLE_LOAD_AMOUNT
: // 0x07 Loading speed
1019 /* Amount of cargo loaded during a vehicle's "loading tick" */
1020 ei
->load_amount
= buf
->ReadByte();
1031 * Define properties for rail vehicles
1032 * @param engine :ocal ID of the first vehicle.
1033 * @param numinfo Number of subsequent IDs to change the property for.
1034 * @param prop The property to change.
1035 * @param buf The property value.
1036 * @return ChangeInfoResult.
1038 static ChangeInfoResult
RailVehicleChangeInfo(uint engine
, int numinfo
, int prop
, ByteReader
*buf
)
1040 ChangeInfoResult ret
= CIR_SUCCESS
;
1042 for (int i
= 0; i
< numinfo
; i
++) {
1043 Engine
*e
= GetNewEngine(_cur
.grffile
, VEH_TRAIN
, engine
+ i
);
1044 if (e
== nullptr) return CIR_INVALID_ID
; // No engine could be allocated, so neither can any next vehicles
1046 EngineInfo
*ei
= &e
->info
;
1047 RailVehicleInfo
*rvi
= &e
->u
.rail
;
1050 case 0x05: { // Track type
1051 uint8_t tracktype
= buf
->ReadByte();
1053 if (tracktype
< _cur
.grffile
->railtype_list
.size()) {
1054 _gted
[e
->index
].railtypelabel
= _cur
.grffile
->railtype_list
[tracktype
];
1058 switch (tracktype
) {
1059 case 0: _gted
[e
->index
].railtypelabel
= rvi
->engclass
>= 2 ? RAILTYPE_LABEL_ELECTRIC
: RAILTYPE_LABEL_RAIL
; break;
1060 case 1: _gted
[e
->index
].railtypelabel
= RAILTYPE_LABEL_MONO
; break;
1061 case 2: _gted
[e
->index
].railtypelabel
= RAILTYPE_LABEL_MAGLEV
; break;
1063 GrfMsg(1, "RailVehicleChangeInfo: Invalid track type {} specified, ignoring", tracktype
);
1069 case 0x08: // AI passenger service
1070 /* Tells the AI that this engine is designed for
1071 * passenger services and shouldn't be used for freight. */
1072 rvi
->ai_passenger_only
= buf
->ReadByte();
1075 case PROP_TRAIN_SPEED
: { // 0x09 Speed (1 unit is 1 km-ish/h)
1076 uint16_t speed
= buf
->ReadWord();
1077 if (speed
== 0xFFFF) speed
= 0;
1079 rvi
->max_speed
= speed
;
1083 case PROP_TRAIN_POWER
: // 0x0B Power
1084 rvi
->power
= buf
->ReadWord();
1086 /* Set engine / wagon state based on power */
1087 if (rvi
->power
!= 0) {
1088 if (rvi
->railveh_type
== RAILVEH_WAGON
) {
1089 rvi
->railveh_type
= RAILVEH_SINGLEHEAD
;
1092 rvi
->railveh_type
= RAILVEH_WAGON
;
1096 case PROP_TRAIN_RUNNING_COST_FACTOR
: // 0x0D Running cost factor
1097 rvi
->running_cost
= buf
->ReadByte();
1100 case 0x0E: // Running cost base
1101 ConvertTTDBasePrice(buf
->ReadDWord(), "RailVehicleChangeInfo", &rvi
->running_cost_class
);
1104 case 0x12: { // Sprite ID
1105 uint8_t spriteid
= buf
->ReadByte();
1106 uint8_t orig_spriteid
= spriteid
;
1108 /* TTD sprite IDs point to a location in a 16bit array, but we use it
1109 * as an array index, so we need it to be half the original value. */
1110 if (spriteid
< 0xFD) spriteid
>>= 1;
1112 if (IsValidNewGRFImageIndex
<VEH_TRAIN
>(spriteid
)) {
1113 rvi
->image_index
= spriteid
;
1115 GrfMsg(1, "RailVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid
);
1116 rvi
->image_index
= 0;
1121 case 0x13: { // Dual-headed
1122 uint8_t dual
= buf
->ReadByte();
1125 rvi
->railveh_type
= RAILVEH_MULTIHEAD
;
1127 rvi
->railveh_type
= rvi
->power
== 0 ?
1128 RAILVEH_WAGON
: RAILVEH_SINGLEHEAD
;
1133 case PROP_TRAIN_CARGO_CAPACITY
: // 0x14 Cargo capacity
1134 rvi
->capacity
= buf
->ReadByte();
1137 case 0x15: { // Cargo type
1138 _gted
[e
->index
].defaultcargo_grf
= _cur
.grffile
;
1139 uint8_t ctype
= buf
->ReadByte();
1141 if (ctype
== 0xFF) {
1142 /* 0xFF is specified as 'use first refittable' */
1143 ei
->cargo_type
= INVALID_CARGO
;
1144 } else if (_cur
.grffile
->grf_version
>= 8) {
1145 /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
1146 ei
->cargo_type
= GetCargoTranslation(ctype
, _cur
.grffile
);
1147 } else if (ctype
< NUM_CARGO
) {
1148 /* Use untranslated cargo. */
1149 ei
->cargo_type
= ctype
;
1151 ei
->cargo_type
= INVALID_CARGO
;
1152 GrfMsg(2, "RailVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype
);
1154 ei
->cargo_label
= CT_INVALID
;
1158 case PROP_TRAIN_WEIGHT
: // 0x16 Weight
1159 SB(rvi
->weight
, 0, 8, buf
->ReadByte());
1162 case PROP_TRAIN_COST_FACTOR
: // 0x17 Cost factor
1163 rvi
->cost_factor
= buf
->ReadByte();
1166 case 0x18: // AI rank
1167 GrfMsg(2, "RailVehicleChangeInfo: Property 0x18 'AI rank' not used by NoAI, ignored.");
1171 case 0x19: { // Engine traction type
1172 /* What do the individual numbers mean?
1173 * 0x00 .. 0x07: Steam
1174 * 0x08 .. 0x27: Diesel
1175 * 0x28 .. 0x31: Electric
1176 * 0x32 .. 0x37: Monorail
1177 * 0x38 .. 0x41: Maglev
1179 uint8_t traction
= buf
->ReadByte();
1180 EngineClass engclass
;
1182 if (traction
<= 0x07) {
1183 engclass
= EC_STEAM
;
1184 } else if (traction
<= 0x27) {
1185 engclass
= EC_DIESEL
;
1186 } else if (traction
<= 0x31) {
1187 engclass
= EC_ELECTRIC
;
1188 } else if (traction
<= 0x37) {
1189 engclass
= EC_MONORAIL
;
1190 } else if (traction
<= 0x41) {
1191 engclass
= EC_MAGLEV
;
1196 if (_cur
.grffile
->railtype_list
.empty()) {
1197 /* Use traction type to select between normal and electrified
1198 * rail only when no translation list is in place. */
1199 if (_gted
[e
->index
].railtypelabel
== RAILTYPE_LABEL_RAIL
&& engclass
>= EC_ELECTRIC
) _gted
[e
->index
].railtypelabel
= RAILTYPE_LABEL_ELECTRIC
;
1200 if (_gted
[e
->index
].railtypelabel
== RAILTYPE_LABEL_ELECTRIC
&& engclass
< EC_ELECTRIC
) _gted
[e
->index
].railtypelabel
= RAILTYPE_LABEL_RAIL
;
1203 rvi
->engclass
= engclass
;
1207 case 0x1A: // Alter purchase list sort order
1208 AlterVehicleListOrder(e
->index
, buf
->ReadExtendedByte());
1211 case 0x1B: // Powered wagons power bonus
1212 rvi
->pow_wag_power
= buf
->ReadWord();
1215 case 0x1C: // Refit cost
1216 ei
->refit_cost
= buf
->ReadByte();
1219 case 0x1D: { // Refit cargo
1220 uint32_t mask
= buf
->ReadDWord();
1221 _gted
[e
->index
].UpdateRefittability(mask
!= 0);
1222 ei
->refit_mask
= TranslateRefitMask(mask
);
1223 _gted
[e
->index
].defaultcargo_grf
= _cur
.grffile
;
1227 case 0x1E: // Callback
1228 SB(ei
->callback_mask
, 0, 8, buf
->ReadByte());
1231 case PROP_TRAIN_TRACTIVE_EFFORT
: // 0x1F Tractive effort coefficient
1232 rvi
->tractive_effort
= buf
->ReadByte();
1235 case 0x20: // Air drag
1236 rvi
->air_drag
= buf
->ReadByte();
1239 case PROP_TRAIN_SHORTEN_FACTOR
: // 0x21 Shorter vehicle
1240 rvi
->shorten_factor
= buf
->ReadByte();
1243 case 0x22: // Visual effect
1244 rvi
->visual_effect
= buf
->ReadByte();
1245 /* Avoid accidentally setting visual_effect to the default value
1246 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1247 if (rvi
->visual_effect
== VE_DEFAULT
) {
1248 assert(HasBit(rvi
->visual_effect
, VE_DISABLE_EFFECT
));
1249 SB(rvi
->visual_effect
, VE_TYPE_START
, VE_TYPE_COUNT
, 0);
1253 case 0x23: // Powered wagons weight bonus
1254 rvi
->pow_wag_weight
= buf
->ReadByte();
1257 case 0x24: { // High byte of vehicle weight
1258 byte weight
= buf
->ReadByte();
1261 GrfMsg(2, "RailVehicleChangeInfo: Nonsensical weight of {} tons, ignoring", weight
<< 8);
1263 SB(rvi
->weight
, 8, 8, weight
);
1268 case PROP_TRAIN_USER_DATA
: // 0x25 User-defined bit mask to set when checking veh. var. 42
1269 rvi
->user_def_data
= buf
->ReadByte();
1272 case 0x26: // Retire vehicle early
1273 ei
->retire_early
= buf
->ReadByte();
1276 case 0x27: // Miscellaneous flags
1277 ei
->misc_flags
= buf
->ReadByte();
1278 _loaded_newgrf_features
.has_2CC
|= HasBit(ei
->misc_flags
, EF_USES_2CC
);
1281 case 0x28: // Cargo classes allowed
1282 _gted
[e
->index
].cargo_allowed
= buf
->ReadWord();
1283 _gted
[e
->index
].UpdateRefittability(_gted
[e
->index
].cargo_allowed
!= 0);
1284 _gted
[e
->index
].defaultcargo_grf
= _cur
.grffile
;
1287 case 0x29: // Cargo classes disallowed
1288 _gted
[e
->index
].cargo_disallowed
= buf
->ReadWord();
1289 _gted
[e
->index
].UpdateRefittability(false);
1292 case 0x2A: // Long format introduction date (days since year 0)
1293 ei
->base_intro
= buf
->ReadDWord();
1296 case PROP_TRAIN_CARGO_AGE_PERIOD
: // 0x2B Cargo aging period
1297 ei
->cargo_age_period
= buf
->ReadWord();
1300 case 0x2C: // CTT refit include list
1301 case 0x2D: { // CTT refit exclude list
1302 uint8_t count
= buf
->ReadByte();
1303 _gted
[e
->index
].UpdateRefittability(prop
== 0x2C && count
!= 0);
1304 if (prop
== 0x2C) _gted
[e
->index
].defaultcargo_grf
= _cur
.grffile
;
1305 CargoTypes
&ctt
= prop
== 0x2C ? _gted
[e
->index
].ctt_include_mask
: _gted
[e
->index
].ctt_exclude_mask
;
1308 CargoID ctype
= GetCargoTranslation(buf
->ReadByte(), _cur
.grffile
);
1309 if (IsValidCargoID(ctype
)) SetBit(ctt
, ctype
);
1314 case PROP_TRAIN_CURVE_SPEED_MOD
: // 0x2E Curve speed modifier
1315 rvi
->curve_speed_mod
= buf
->ReadWord();
1318 case 0x2F: // Engine variant
1319 ei
->variant_id
= buf
->ReadWord();
1322 case 0x30: // Extra miscellaneous flags
1323 ei
->extra_flags
= static_cast<ExtraEngineFlags
>(buf
->ReadDWord());
1326 case 0x31: // Callback additional mask
1327 SB(ei
->callback_mask
, 8, 8, buf
->ReadByte());
1331 ret
= CommonVehicleChangeInfo(ei
, prop
, buf
);
1340 * Define properties for road vehicles
1341 * @param engine Local ID of the first vehicle.
1342 * @param numinfo Number of subsequent IDs to change the property for.
1343 * @param prop The property to change.
1344 * @param buf The property value.
1345 * @return ChangeInfoResult.
1347 static ChangeInfoResult
RoadVehicleChangeInfo(uint engine
, int numinfo
, int prop
, ByteReader
*buf
)
1349 ChangeInfoResult ret
= CIR_SUCCESS
;
1351 for (int i
= 0; i
< numinfo
; i
++) {
1352 Engine
*e
= GetNewEngine(_cur
.grffile
, VEH_ROAD
, engine
+ i
);
1353 if (e
== nullptr) return CIR_INVALID_ID
; // No engine could be allocated, so neither can any next vehicles
1355 EngineInfo
*ei
= &e
->info
;
1356 RoadVehicleInfo
*rvi
= &e
->u
.road
;
1359 case 0x05: // Road/tram type
1360 /* RoadTypeLabel is looked up later after the engine's road/tram
1361 * flag is set, however 0 means the value has not been set. */
1362 _gted
[e
->index
].roadtramtype
= buf
->ReadByte() + 1;
1365 case 0x08: // Speed (1 unit is 0.5 kmh)
1366 rvi
->max_speed
= buf
->ReadByte();
1369 case PROP_ROADVEH_RUNNING_COST_FACTOR
: // 0x09 Running cost factor
1370 rvi
->running_cost
= buf
->ReadByte();
1373 case 0x0A: // Running cost base
1374 ConvertTTDBasePrice(buf
->ReadDWord(), "RoadVehicleChangeInfo", &rvi
->running_cost_class
);
1377 case 0x0E: { // Sprite ID
1378 uint8_t spriteid
= buf
->ReadByte();
1379 uint8_t orig_spriteid
= spriteid
;
1381 /* cars have different custom id in the GRF file */
1382 if (spriteid
== 0xFF) spriteid
= 0xFD;
1384 if (spriteid
< 0xFD) spriteid
>>= 1;
1386 if (IsValidNewGRFImageIndex
<VEH_ROAD
>(spriteid
)) {
1387 rvi
->image_index
= spriteid
;
1389 GrfMsg(1, "RoadVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid
);
1390 rvi
->image_index
= 0;
1395 case PROP_ROADVEH_CARGO_CAPACITY
: // 0x0F Cargo capacity
1396 rvi
->capacity
= buf
->ReadByte();
1399 case 0x10: { // Cargo type
1400 _gted
[e
->index
].defaultcargo_grf
= _cur
.grffile
;
1401 uint8_t ctype
= buf
->ReadByte();
1403 if (ctype
== 0xFF) {
1404 /* 0xFF is specified as 'use first refittable' */
1405 ei
->cargo_type
= INVALID_CARGO
;
1406 } else if (_cur
.grffile
->grf_version
>= 8) {
1407 /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
1408 ei
->cargo_type
= GetCargoTranslation(ctype
, _cur
.grffile
);
1409 } else if (ctype
< NUM_CARGO
) {
1410 /* Use untranslated cargo. */
1411 ei
->cargo_type
= ctype
;
1413 ei
->cargo_type
= INVALID_CARGO
;
1414 GrfMsg(2, "RailVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype
);
1416 ei
->cargo_label
= CT_INVALID
;
1420 case PROP_ROADVEH_COST_FACTOR
: // 0x11 Cost factor
1421 rvi
->cost_factor
= buf
->ReadByte();
1425 rvi
->sfx
= GetNewGRFSoundID(_cur
.grffile
, buf
->ReadByte());
1428 case PROP_ROADVEH_POWER
: // Power in units of 10 HP.
1429 rvi
->power
= buf
->ReadByte();
1432 case PROP_ROADVEH_WEIGHT
: // Weight in units of 1/4 tons.
1433 rvi
->weight
= buf
->ReadByte();
1436 case PROP_ROADVEH_SPEED
: // Speed in mph/0.8
1437 _gted
[e
->index
].rv_max_speed
= buf
->ReadByte();
1440 case 0x16: { // Cargoes available for refitting
1441 uint32_t mask
= buf
->ReadDWord();
1442 _gted
[e
->index
].UpdateRefittability(mask
!= 0);
1443 ei
->refit_mask
= TranslateRefitMask(mask
);
1444 _gted
[e
->index
].defaultcargo_grf
= _cur
.grffile
;
1448 case 0x17: // Callback mask
1449 SB(ei
->callback_mask
, 0, 8, buf
->ReadByte());
1452 case PROP_ROADVEH_TRACTIVE_EFFORT
: // Tractive effort coefficient in 1/256.
1453 rvi
->tractive_effort
= buf
->ReadByte();
1456 case 0x19: // Air drag
1457 rvi
->air_drag
= buf
->ReadByte();
1460 case 0x1A: // Refit cost
1461 ei
->refit_cost
= buf
->ReadByte();
1464 case 0x1B: // Retire vehicle early
1465 ei
->retire_early
= buf
->ReadByte();
1468 case 0x1C: // Miscellaneous flags
1469 ei
->misc_flags
= buf
->ReadByte();
1470 _loaded_newgrf_features
.has_2CC
|= HasBit(ei
->misc_flags
, EF_USES_2CC
);
1473 case 0x1D: // Cargo classes allowed
1474 _gted
[e
->index
].cargo_allowed
= buf
->ReadWord();
1475 _gted
[e
->index
].UpdateRefittability(_gted
[e
->index
].cargo_allowed
!= 0);
1476 _gted
[e
->index
].defaultcargo_grf
= _cur
.grffile
;
1479 case 0x1E: // Cargo classes disallowed
1480 _gted
[e
->index
].cargo_disallowed
= buf
->ReadWord();
1481 _gted
[e
->index
].UpdateRefittability(false);
1484 case 0x1F: // Long format introduction date (days since year 0)
1485 ei
->base_intro
= buf
->ReadDWord();
1488 case 0x20: // Alter purchase list sort order
1489 AlterVehicleListOrder(e
->index
, buf
->ReadExtendedByte());
1492 case 0x21: // Visual effect
1493 rvi
->visual_effect
= buf
->ReadByte();
1494 /* Avoid accidentally setting visual_effect to the default value
1495 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1496 if (rvi
->visual_effect
== VE_DEFAULT
) {
1497 assert(HasBit(rvi
->visual_effect
, VE_DISABLE_EFFECT
));
1498 SB(rvi
->visual_effect
, VE_TYPE_START
, VE_TYPE_COUNT
, 0);
1502 case PROP_ROADVEH_CARGO_AGE_PERIOD
: // 0x22 Cargo aging period
1503 ei
->cargo_age_period
= buf
->ReadWord();
1506 case PROP_ROADVEH_SHORTEN_FACTOR
: // 0x23 Shorter vehicle
1507 rvi
->shorten_factor
= buf
->ReadByte();
1510 case 0x24: // CTT refit include list
1511 case 0x25: { // CTT refit exclude list
1512 uint8_t count
= buf
->ReadByte();
1513 _gted
[e
->index
].UpdateRefittability(prop
== 0x24 && count
!= 0);
1514 if (prop
== 0x24) _gted
[e
->index
].defaultcargo_grf
= _cur
.grffile
;
1515 CargoTypes
&ctt
= prop
== 0x24 ? _gted
[e
->index
].ctt_include_mask
: _gted
[e
->index
].ctt_exclude_mask
;
1518 CargoID ctype
= GetCargoTranslation(buf
->ReadByte(), _cur
.grffile
);
1519 if (IsValidCargoID(ctype
)) SetBit(ctt
, ctype
);
1524 case 0x26: // Engine variant
1525 ei
->variant_id
= buf
->ReadWord();
1528 case 0x27: // Extra miscellaneous flags
1529 ei
->extra_flags
= static_cast<ExtraEngineFlags
>(buf
->ReadDWord());
1532 case 0x28: // Callback additional mask
1533 SB(ei
->callback_mask
, 8, 8, buf
->ReadByte());
1537 ret
= CommonVehicleChangeInfo(ei
, prop
, buf
);
1546 * Define properties for ships
1547 * @param engine Local ID of the first vehicle.
1548 * @param numinfo Number of subsequent IDs to change the property for.
1549 * @param prop The property to change.
1550 * @param buf The property value.
1551 * @return ChangeInfoResult.
1553 static ChangeInfoResult
ShipVehicleChangeInfo(uint engine
, int numinfo
, int prop
, ByteReader
*buf
)
1555 ChangeInfoResult ret
= CIR_SUCCESS
;
1557 for (int i
= 0; i
< numinfo
; i
++) {
1558 Engine
*e
= GetNewEngine(_cur
.grffile
, VEH_SHIP
, engine
+ i
);
1559 if (e
== nullptr) return CIR_INVALID_ID
; // No engine could be allocated, so neither can any next vehicles
1561 EngineInfo
*ei
= &e
->info
;
1562 ShipVehicleInfo
*svi
= &e
->u
.ship
;
1565 case 0x08: { // Sprite ID
1566 uint8_t spriteid
= buf
->ReadByte();
1567 uint8_t orig_spriteid
= spriteid
;
1569 /* ships have different custom id in the GRF file */
1570 if (spriteid
== 0xFF) spriteid
= 0xFD;
1572 if (spriteid
< 0xFD) spriteid
>>= 1;
1574 if (IsValidNewGRFImageIndex
<VEH_SHIP
>(spriteid
)) {
1575 svi
->image_index
= spriteid
;
1577 GrfMsg(1, "ShipVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid
);
1578 svi
->image_index
= 0;
1583 case 0x09: // Refittable
1584 svi
->old_refittable
= (buf
->ReadByte() != 0);
1587 case PROP_SHIP_COST_FACTOR
: // 0x0A Cost factor
1588 svi
->cost_factor
= buf
->ReadByte();
1591 case PROP_SHIP_SPEED
: // 0x0B Speed (1 unit is 0.5 km-ish/h). Use 0x23 to achieve higher speeds.
1592 svi
->max_speed
= buf
->ReadByte();
1595 case 0x0C: { // Cargo type
1596 _gted
[e
->index
].defaultcargo_grf
= _cur
.grffile
;
1597 uint8_t ctype
= buf
->ReadByte();
1599 if (ctype
== 0xFF) {
1600 /* 0xFF is specified as 'use first refittable' */
1601 ei
->cargo_type
= INVALID_CARGO
;
1602 } else if (_cur
.grffile
->grf_version
>= 8) {
1603 /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
1604 ei
->cargo_type
= GetCargoTranslation(ctype
, _cur
.grffile
);
1605 } else if (ctype
< NUM_CARGO
) {
1606 /* Use untranslated cargo. */
1607 ei
->cargo_type
= ctype
;
1609 ei
->cargo_type
= INVALID_CARGO
;
1610 GrfMsg(2, "ShipVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype
);
1612 ei
->cargo_label
= CT_INVALID
;
1616 case PROP_SHIP_CARGO_CAPACITY
: // 0x0D Cargo capacity
1617 svi
->capacity
= buf
->ReadWord();
1620 case PROP_SHIP_RUNNING_COST_FACTOR
: // 0x0F Running cost factor
1621 svi
->running_cost
= buf
->ReadByte();
1625 svi
->sfx
= GetNewGRFSoundID(_cur
.grffile
, buf
->ReadByte());
1628 case 0x11: { // Cargoes available for refitting
1629 uint32_t mask
= buf
->ReadDWord();
1630 _gted
[e
->index
].UpdateRefittability(mask
!= 0);
1631 ei
->refit_mask
= TranslateRefitMask(mask
);
1632 _gted
[e
->index
].defaultcargo_grf
= _cur
.grffile
;
1636 case 0x12: // Callback mask
1637 SB(ei
->callback_mask
, 0, 8, buf
->ReadByte());
1640 case 0x13: // Refit cost
1641 ei
->refit_cost
= buf
->ReadByte();
1644 case 0x14: // Ocean speed fraction
1645 svi
->ocean_speed_frac
= buf
->ReadByte();
1648 case 0x15: // Canal speed fraction
1649 svi
->canal_speed_frac
= buf
->ReadByte();
1652 case 0x16: // Retire vehicle early
1653 ei
->retire_early
= buf
->ReadByte();
1656 case 0x17: // Miscellaneous flags
1657 ei
->misc_flags
= buf
->ReadByte();
1658 _loaded_newgrf_features
.has_2CC
|= HasBit(ei
->misc_flags
, EF_USES_2CC
);
1661 case 0x18: // Cargo classes allowed
1662 _gted
[e
->index
].cargo_allowed
= buf
->ReadWord();
1663 _gted
[e
->index
].UpdateRefittability(_gted
[e
->index
].cargo_allowed
!= 0);
1664 _gted
[e
->index
].defaultcargo_grf
= _cur
.grffile
;
1667 case 0x19: // Cargo classes disallowed
1668 _gted
[e
->index
].cargo_disallowed
= buf
->ReadWord();
1669 _gted
[e
->index
].UpdateRefittability(false);
1672 case 0x1A: // Long format introduction date (days since year 0)
1673 ei
->base_intro
= buf
->ReadDWord();
1676 case 0x1B: // Alter purchase list sort order
1677 AlterVehicleListOrder(e
->index
, buf
->ReadExtendedByte());
1680 case 0x1C: // Visual effect
1681 svi
->visual_effect
= buf
->ReadByte();
1682 /* Avoid accidentally setting visual_effect to the default value
1683 * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1684 if (svi
->visual_effect
== VE_DEFAULT
) {
1685 assert(HasBit(svi
->visual_effect
, VE_DISABLE_EFFECT
));
1686 SB(svi
->visual_effect
, VE_TYPE_START
, VE_TYPE_COUNT
, 0);
1690 case PROP_SHIP_CARGO_AGE_PERIOD
: // 0x1D Cargo aging period
1691 ei
->cargo_age_period
= buf
->ReadWord();
1694 case 0x1E: // CTT refit include list
1695 case 0x1F: { // CTT refit exclude list
1696 uint8_t count
= buf
->ReadByte();
1697 _gted
[e
->index
].UpdateRefittability(prop
== 0x1E && count
!= 0);
1698 if (prop
== 0x1E) _gted
[e
->index
].defaultcargo_grf
= _cur
.grffile
;
1699 CargoTypes
&ctt
= prop
== 0x1E ? _gted
[e
->index
].ctt_include_mask
: _gted
[e
->index
].ctt_exclude_mask
;
1702 CargoID ctype
= GetCargoTranslation(buf
->ReadByte(), _cur
.grffile
);
1703 if (IsValidCargoID(ctype
)) SetBit(ctt
, ctype
);
1708 case 0x20: // Engine variant
1709 ei
->variant_id
= buf
->ReadWord();
1712 case 0x21: // Extra miscellaneous flags
1713 ei
->extra_flags
= static_cast<ExtraEngineFlags
>(buf
->ReadDWord());
1716 case 0x22: // Callback additional mask
1717 SB(ei
->callback_mask
, 8, 8, buf
->ReadByte());
1720 case 0x23: // Speed (1 unit is 0.5 km-ish/h)
1721 svi
->max_speed
= buf
->ReadWord();
1724 case 0x24: // Acceleration (1 unit is 0.5 km-ish/h per tick)
1725 svi
->acceleration
= std::max
<uint8_t>(1, buf
->ReadByte());
1729 ret
= CommonVehicleChangeInfo(ei
, prop
, buf
);
1738 * Define properties for aircraft
1739 * @param engine Local ID of the aircraft.
1740 * @param numinfo Number of subsequent IDs to change the property for.
1741 * @param prop The property to change.
1742 * @param buf The property value.
1743 * @return ChangeInfoResult.
1745 static ChangeInfoResult
AircraftVehicleChangeInfo(uint engine
, int numinfo
, int prop
, ByteReader
*buf
)
1747 ChangeInfoResult ret
= CIR_SUCCESS
;
1749 for (int i
= 0; i
< numinfo
; i
++) {
1750 Engine
*e
= GetNewEngine(_cur
.grffile
, VEH_AIRCRAFT
, engine
+ i
);
1751 if (e
== nullptr) return CIR_INVALID_ID
; // No engine could be allocated, so neither can any next vehicles
1753 EngineInfo
*ei
= &e
->info
;
1754 AircraftVehicleInfo
*avi
= &e
->u
.air
;
1757 case 0x08: { // Sprite ID
1758 uint8_t spriteid
= buf
->ReadByte();
1759 uint8_t orig_spriteid
= spriteid
;
1761 /* aircraft have different custom id in the GRF file */
1762 if (spriteid
== 0xFF) spriteid
= 0xFD;
1764 if (spriteid
< 0xFD) spriteid
>>= 1;
1766 if (IsValidNewGRFImageIndex
<VEH_AIRCRAFT
>(spriteid
)) {
1767 avi
->image_index
= spriteid
;
1769 GrfMsg(1, "AircraftVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid
);
1770 avi
->image_index
= 0;
1775 case 0x09: // Helicopter
1776 if (buf
->ReadByte() == 0) {
1777 avi
->subtype
= AIR_HELI
;
1779 SB(avi
->subtype
, 0, 1, 1); // AIR_CTOL
1784 SB(avi
->subtype
, 1, 1, (buf
->ReadByte() != 0 ? 1 : 0)); // AIR_FAST
1787 case PROP_AIRCRAFT_COST_FACTOR
: // 0x0B Cost factor
1788 avi
->cost_factor
= buf
->ReadByte();
1791 case PROP_AIRCRAFT_SPEED
: // 0x0C Speed (1 unit is 8 mph, we translate to 1 unit is 1 km-ish/h)
1792 avi
->max_speed
= (buf
->ReadByte() * 128) / 10;
1795 case 0x0D: // Acceleration
1796 avi
->acceleration
= buf
->ReadByte();
1799 case PROP_AIRCRAFT_RUNNING_COST_FACTOR
: // 0x0E Running cost factor
1800 avi
->running_cost
= buf
->ReadByte();
1803 case PROP_AIRCRAFT_PASSENGER_CAPACITY
: // 0x0F Passenger capacity
1804 avi
->passenger_capacity
= buf
->ReadWord();
1807 case PROP_AIRCRAFT_MAIL_CAPACITY
: // 0x11 Mail capacity
1808 avi
->mail_capacity
= buf
->ReadByte();
1812 avi
->sfx
= GetNewGRFSoundID(_cur
.grffile
, buf
->ReadByte());
1815 case 0x13: { // Cargoes available for refitting
1816 uint32_t mask
= buf
->ReadDWord();
1817 _gted
[e
->index
].UpdateRefittability(mask
!= 0);
1818 ei
->refit_mask
= TranslateRefitMask(mask
);
1819 _gted
[e
->index
].defaultcargo_grf
= _cur
.grffile
;
1823 case 0x14: // Callback mask
1824 SB(ei
->callback_mask
, 0, 8, buf
->ReadByte());
1827 case 0x15: // Refit cost
1828 ei
->refit_cost
= buf
->ReadByte();
1831 case 0x16: // Retire vehicle early
1832 ei
->retire_early
= buf
->ReadByte();
1835 case 0x17: // Miscellaneous flags
1836 ei
->misc_flags
= buf
->ReadByte();
1837 _loaded_newgrf_features
.has_2CC
|= HasBit(ei
->misc_flags
, EF_USES_2CC
);
1840 case 0x18: // Cargo classes allowed
1841 _gted
[e
->index
].cargo_allowed
= buf
->ReadWord();
1842 _gted
[e
->index
].UpdateRefittability(_gted
[e
->index
].cargo_allowed
!= 0);
1843 _gted
[e
->index
].defaultcargo_grf
= _cur
.grffile
;
1846 case 0x19: // Cargo classes disallowed
1847 _gted
[e
->index
].cargo_disallowed
= buf
->ReadWord();
1848 _gted
[e
->index
].UpdateRefittability(false);
1851 case 0x1A: // Long format introduction date (days since year 0)
1852 ei
->base_intro
= buf
->ReadDWord();
1855 case 0x1B: // Alter purchase list sort order
1856 AlterVehicleListOrder(e
->index
, buf
->ReadExtendedByte());
1859 case PROP_AIRCRAFT_CARGO_AGE_PERIOD
: // 0x1C Cargo aging period
1860 ei
->cargo_age_period
= buf
->ReadWord();
1863 case 0x1D: // CTT refit include list
1864 case 0x1E: { // CTT refit exclude list
1865 uint8_t count
= buf
->ReadByte();
1866 _gted
[e
->index
].UpdateRefittability(prop
== 0x1D && count
!= 0);
1867 if (prop
== 0x1D) _gted
[e
->index
].defaultcargo_grf
= _cur
.grffile
;
1868 CargoTypes
&ctt
= prop
== 0x1D ? _gted
[e
->index
].ctt_include_mask
: _gted
[e
->index
].ctt_exclude_mask
;
1871 CargoID ctype
= GetCargoTranslation(buf
->ReadByte(), _cur
.grffile
);
1872 if (IsValidCargoID(ctype
)) SetBit(ctt
, ctype
);
1877 case PROP_AIRCRAFT_RANGE
: // 0x1F Max aircraft range
1878 avi
->max_range
= buf
->ReadWord();
1881 case 0x20: // Engine variant
1882 ei
->variant_id
= buf
->ReadWord();
1885 case 0x21: // Extra miscellaneous flags
1886 ei
->extra_flags
= static_cast<ExtraEngineFlags
>(buf
->ReadDWord());
1889 case 0x22: // Callback additional mask
1890 SB(ei
->callback_mask
, 8, 8, buf
->ReadByte());
1894 ret
= CommonVehicleChangeInfo(ei
, prop
, buf
);
1903 * Define properties for stations
1904 * @param stid StationID of the first station tile.
1905 * @param numinfo Number of subsequent station tiles to change the property for.
1906 * @param prop The property to change.
1907 * @param buf The property value.
1908 * @return ChangeInfoResult.
1910 static ChangeInfoResult
StationChangeInfo(uint stid
, int numinfo
, int prop
, ByteReader
*buf
)
1912 ChangeInfoResult ret
= CIR_SUCCESS
;
1914 if (stid
+ numinfo
> NUM_STATIONS_PER_GRF
) {
1915 GrfMsg(1, "StationChangeInfo: Station {} is invalid, max {}, ignoring", stid
+ numinfo
, NUM_STATIONS_PER_GRF
);
1916 return CIR_INVALID_ID
;
1919 /* Allocate station specs if necessary */
1920 if (_cur
.grffile
->stations
.size() < stid
+ numinfo
) _cur
.grffile
->stations
.resize(stid
+ numinfo
);
1922 for (int i
= 0; i
< numinfo
; i
++) {
1923 StationSpec
*statspec
= _cur
.grffile
->stations
[stid
+ i
].get();
1925 /* Check that the station we are modifying is defined. */
1926 if (statspec
== nullptr && prop
!= 0x08) {
1927 GrfMsg(2, "StationChangeInfo: Attempt to modify undefined station {}, ignoring", stid
+ i
);
1928 return CIR_INVALID_ID
;
1932 case 0x08: { // Class ID
1933 /* Property 0x08 is special; it is where the station is allocated */
1934 if (statspec
== nullptr) {
1935 _cur
.grffile
->stations
[stid
+ i
] = std::make_unique
<StationSpec
>();
1936 statspec
= _cur
.grffile
->stations
[stid
+ i
].get();
1939 /* Swap classid because we read it in BE meaning WAYP or DFLT */
1940 uint32_t classid
= buf
->ReadDWord();
1941 statspec
->cls_id
= StationClass::Allocate(BSWAP32(classid
));
1945 case 0x09: { // Define sprite layout
1946 uint16_t tiles
= buf
->ReadExtendedByte();
1947 statspec
->renderdata
.clear(); // delete earlier loaded stuff
1948 statspec
->renderdata
.reserve(tiles
);
1950 for (uint t
= 0; t
< tiles
; t
++) {
1951 NewGRFSpriteLayout
*dts
= &statspec
->renderdata
.emplace_back();
1952 dts
->consistent_max_offset
= UINT16_MAX
; // Spritesets are unknown, so no limit.
1954 if (buf
->HasData(4) && *(uint32_t*)buf
->Data() == 0) {
1956 extern const DrawTileSprites _station_display_datas_rail
[8];
1957 dts
->Clone(&_station_display_datas_rail
[t
% 8]);
1961 ReadSpriteLayoutSprite(buf
, false, false, false, GSF_STATIONS
, &dts
->ground
);
1962 /* On error, bail out immediately. Temporary GRF data was already freed */
1963 if (_cur
.skip_sprites
< 0) return CIR_DISABLED
;
1965 static std::vector
<DrawTileSeqStruct
> tmp_layout
;
1968 /* no relative bounding box support */
1969 DrawTileSeqStruct
&dtss
= tmp_layout
.emplace_back();
1972 dtss
.delta_x
= buf
->ReadByte();
1973 if (dtss
.IsTerminator()) break;
1974 dtss
.delta_y
= buf
->ReadByte();
1975 dtss
.delta_z
= buf
->ReadByte();
1976 dtss
.size_x
= buf
->ReadByte();
1977 dtss
.size_y
= buf
->ReadByte();
1978 dtss
.size_z
= buf
->ReadByte();
1980 ReadSpriteLayoutSprite(buf
, false, true, false, GSF_STATIONS
, &dtss
.image
);
1981 /* On error, bail out immediately. Temporary GRF data was already freed */
1982 if (_cur
.skip_sprites
< 0) return CIR_DISABLED
;
1984 dts
->Clone(tmp_layout
.data());
1987 /* Number of layouts must be even, alternating X and Y */
1988 if (statspec
->renderdata
.size() & 1) {
1989 GrfMsg(1, "StationChangeInfo: Station {} defines an odd number of sprite layouts, dropping the last item", stid
+ i
);
1990 statspec
->renderdata
.pop_back();
1995 case 0x0A: { // Copy sprite layout
1996 uint16_t srcid
= buf
->ReadExtendedByte();
1997 const StationSpec
*srcstatspec
= srcid
>= _cur
.grffile
->stations
.size() ? nullptr : _cur
.grffile
->stations
[srcid
].get();
1999 if (srcstatspec
== nullptr) {
2000 GrfMsg(1, "StationChangeInfo: Station {} is not defined, cannot copy sprite layout to {}.", srcid
, stid
+ i
);
2004 statspec
->renderdata
.clear(); // delete earlier loaded stuff
2005 statspec
->renderdata
.reserve(srcstatspec
->renderdata
.size());
2007 for (const auto &it
: srcstatspec
->renderdata
) {
2008 NewGRFSpriteLayout
*dts
= &statspec
->renderdata
.emplace_back();
2014 case 0x0B: // Callback mask
2015 statspec
->callback_mask
= buf
->ReadByte();
2018 case 0x0C: // Disallowed number of platforms
2019 statspec
->disallowed_platforms
= buf
->ReadByte();
2022 case 0x0D: // Disallowed platform lengths
2023 statspec
->disallowed_lengths
= buf
->ReadByte();
2026 case 0x0E: // Define custom layout
2027 while (buf
->HasData()) {
2028 byte length
= buf
->ReadByte();
2029 byte number
= buf
->ReadByte();
2031 if (length
== 0 || number
== 0) break;
2033 if (statspec
->layouts
.size() < length
) statspec
->layouts
.resize(length
);
2034 if (statspec
->layouts
[length
- 1].size() < number
) statspec
->layouts
[length
- 1].resize(number
);
2036 const byte
*layout
= buf
->ReadBytes(length
* number
);
2037 statspec
->layouts
[length
- 1][number
- 1].assign(layout
, layout
+ length
* number
);
2039 /* Validate tile values are only the permitted 00, 02, 04 and 06. */
2040 for (auto &tile
: statspec
->layouts
[length
- 1][number
- 1]) {
2041 if ((tile
& 6) != tile
) {
2042 GrfMsg(1, "StationChangeInfo: Invalid tile {} in layout {}x{}", tile
, length
, number
);
2049 case 0x0F: { // Copy custom layout
2050 uint16_t srcid
= buf
->ReadExtendedByte();
2051 const StationSpec
*srcstatspec
= srcid
>= _cur
.grffile
->stations
.size() ? nullptr : _cur
.grffile
->stations
[srcid
].get();
2053 if (srcstatspec
== nullptr) {
2054 GrfMsg(1, "StationChangeInfo: Station {} is not defined, cannot copy tile layout to {}.", srcid
, stid
+ i
);
2058 statspec
->layouts
= srcstatspec
->layouts
;
2062 case 0x10: // Little/lots cargo threshold
2063 statspec
->cargo_threshold
= buf
->ReadWord();
2066 case 0x11: // Pylon placement
2067 statspec
->pylons
= buf
->ReadByte();
2070 case 0x12: // Cargo types for random triggers
2071 if (_cur
.grffile
->grf_version
>= 7) {
2072 statspec
->cargo_triggers
= TranslateRefitMask(buf
->ReadDWord());
2074 statspec
->cargo_triggers
= (CargoTypes
)buf
->ReadDWord();
2078 case 0x13: // General flags
2079 statspec
->flags
= buf
->ReadByte();
2082 case 0x14: // Overhead wire placement
2083 statspec
->wires
= buf
->ReadByte();
2086 case 0x15: // Blocked tiles
2087 statspec
->blocked
= buf
->ReadByte();
2090 case 0x16: // Animation info
2091 statspec
->animation
.frames
= buf
->ReadByte();
2092 statspec
->animation
.status
= buf
->ReadByte();
2095 case 0x17: // Animation speed
2096 statspec
->animation
.speed
= buf
->ReadByte();
2099 case 0x18: // Animation triggers
2100 statspec
->animation
.triggers
= buf
->ReadWord();
2103 /* 0x19 road routing (not implemented) */
2105 case 0x1A: { // Advanced sprite layout
2106 uint16_t tiles
= buf
->ReadExtendedByte();
2107 statspec
->renderdata
.clear(); // delete earlier loaded stuff
2108 statspec
->renderdata
.reserve(tiles
);
2110 for (uint t
= 0; t
< tiles
; t
++) {
2111 NewGRFSpriteLayout
*dts
= &statspec
->renderdata
.emplace_back();
2112 uint num_building_sprites
= buf
->ReadByte();
2113 /* On error, bail out immediately. Temporary GRF data was already freed */
2114 if (ReadSpriteLayout(buf
, num_building_sprites
, false, GSF_STATIONS
, true, false, dts
)) return CIR_DISABLED
;
2117 /* Number of layouts must be even, alternating X and Y */
2118 if (statspec
->renderdata
.size() & 1) {
2119 GrfMsg(1, "StationChangeInfo: Station {} defines an odd number of sprite layouts, dropping the last item", stid
+ i
);
2120 statspec
->renderdata
.pop_back();
2125 case 0x1B: // Minimum bridge height (not implemented)
2132 case 0x1C: // Station Name
2133 AddStringForMapping(buf
->ReadWord(), &statspec
->name
);
2136 case 0x1D: // Station Class name
2137 AddStringForMapping(buf
->ReadWord(), &StationClass::Get(statspec
->cls_id
)->name
);
2150 * Define properties for water features
2151 * @param id Type of the first water feature.
2152 * @param numinfo Number of subsequent water feature ids to change the property for.
2153 * @param prop The property to change.
2154 * @param buf The property value.
2155 * @return ChangeInfoResult.
2157 static ChangeInfoResult
CanalChangeInfo(uint id
, int numinfo
, int prop
, ByteReader
*buf
)
2159 ChangeInfoResult ret
= CIR_SUCCESS
;
2161 if (id
+ numinfo
> CF_END
) {
2162 GrfMsg(1, "CanalChangeInfo: Canal feature 0x{:02X} is invalid, max {}, ignoring", id
+ numinfo
, CF_END
);
2163 return CIR_INVALID_ID
;
2166 for (int i
= 0; i
< numinfo
; i
++) {
2167 CanalProperties
*cp
= &_cur
.grffile
->canal_local_properties
[id
+ i
];
2171 cp
->callback_mask
= buf
->ReadByte();
2175 cp
->flags
= buf
->ReadByte();
2188 * Define properties for bridges
2189 * @param brid BridgeID of the bridge.
2190 * @param numinfo Number of subsequent bridgeIDs to change the property for.
2191 * @param prop The property to change.
2192 * @param buf The property value.
2193 * @return ChangeInfoResult.
2195 static ChangeInfoResult
BridgeChangeInfo(uint brid
, int numinfo
, int prop
, ByteReader
*buf
)
2197 ChangeInfoResult ret
= CIR_SUCCESS
;
2199 if (brid
+ numinfo
> MAX_BRIDGES
) {
2200 GrfMsg(1, "BridgeChangeInfo: Bridge {} is invalid, max {}, ignoring", brid
+ numinfo
, MAX_BRIDGES
);
2201 return CIR_INVALID_ID
;
2204 for (int i
= 0; i
< numinfo
; i
++) {
2205 BridgeSpec
*bridge
= &_bridge
[brid
+ i
];
2208 case 0x08: { // Year of availability
2209 /* We treat '0' as always available */
2210 byte year
= buf
->ReadByte();
2211 bridge
->avail_year
= (year
> 0 ? CalendarTime::ORIGINAL_BASE_YEAR
+ year
: 0);
2215 case 0x09: // Minimum length
2216 bridge
->min_length
= buf
->ReadByte();
2219 case 0x0A: // Maximum length
2220 bridge
->max_length
= buf
->ReadByte();
2221 if (bridge
->max_length
> 16) bridge
->max_length
= UINT16_MAX
;
2224 case 0x0B: // Cost factor
2225 bridge
->price
= buf
->ReadByte();
2228 case 0x0C: // Maximum speed
2229 bridge
->speed
= buf
->ReadWord();
2230 if (bridge
->speed
== 0) bridge
->speed
= UINT16_MAX
;
2233 case 0x0D: { // Bridge sprite tables
2234 byte tableid
= buf
->ReadByte();
2235 byte numtables
= buf
->ReadByte();
2237 if (bridge
->sprite_table
== nullptr) {
2238 /* Allocate memory for sprite table pointers and zero out */
2239 bridge
->sprite_table
= CallocT
<PalSpriteID
*>(7);
2242 for (; numtables
-- != 0; tableid
++) {
2243 if (tableid
>= 7) { // skip invalid data
2244 GrfMsg(1, "BridgeChangeInfo: Table {} >= 7, skipping", tableid
);
2245 for (byte sprite
= 0; sprite
< 32; sprite
++) buf
->ReadDWord();
2249 if (bridge
->sprite_table
[tableid
] == nullptr) {
2250 bridge
->sprite_table
[tableid
] = MallocT
<PalSpriteID
>(32);
2253 for (byte sprite
= 0; sprite
< 32; sprite
++) {
2254 SpriteID image
= buf
->ReadWord();
2255 PaletteID pal
= buf
->ReadWord();
2257 bridge
->sprite_table
[tableid
][sprite
].sprite
= image
;
2258 bridge
->sprite_table
[tableid
][sprite
].pal
= pal
;
2260 MapSpriteMappingRecolour(&bridge
->sprite_table
[tableid
][sprite
]);
2266 case 0x0E: // Flags; bit 0 - disable far pillars
2267 bridge
->flags
= buf
->ReadByte();
2270 case 0x0F: // Long format year of availability (year since year 0)
2271 bridge
->avail_year
= Clamp(TimerGameCalendar::Year(buf
->ReadDWord()), CalendarTime::MIN_YEAR
, CalendarTime::MAX_YEAR
);
2274 case 0x10: { // purchase string
2275 StringID newone
= GetGRFStringID(_cur
.grffile
->grfid
, buf
->ReadWord());
2276 if (newone
!= STR_UNDEFINED
) bridge
->material
= newone
;
2280 case 0x11: // description of bridge with rails or roads
2282 StringID newone
= GetGRFStringID(_cur
.grffile
->grfid
, buf
->ReadWord());
2283 if (newone
!= STR_UNDEFINED
) bridge
->transport_name
[prop
- 0x11] = newone
;
2287 case 0x13: // 16 bits cost multiplier
2288 bridge
->price
= buf
->ReadWord();
2301 * Ignore a house property
2302 * @param prop Property to read.
2303 * @param buf Property value.
2304 * @return ChangeInfoResult.
2306 static ChangeInfoResult
IgnoreTownHouseProperty(int prop
, ByteReader
*buf
)
2308 ChangeInfoResult ret
= CIR_SUCCESS
;
2345 for (uint j
= 0; j
< 4; j
++) buf
->ReadByte();
2349 byte count
= buf
->ReadByte();
2350 for (byte j
= 0; j
< count
; j
++) buf
->ReadByte();
2355 buf
->Skip(buf
->ReadByte() * 2);
2366 * Define properties for houses
2367 * @param hid HouseID of the house.
2368 * @param numinfo Number of subsequent houseIDs to change the property for.
2369 * @param prop The property to change.
2370 * @param buf The property value.
2371 * @return ChangeInfoResult.
2373 static ChangeInfoResult
TownHouseChangeInfo(uint hid
, int numinfo
, int prop
, ByteReader
*buf
)
2375 ChangeInfoResult ret
= CIR_SUCCESS
;
2377 if (hid
+ numinfo
> NUM_HOUSES_PER_GRF
) {
2378 GrfMsg(1, "TownHouseChangeInfo: Too many houses loaded ({}), max ({}). Ignoring.", hid
+ numinfo
, NUM_HOUSES_PER_GRF
);
2379 return CIR_INVALID_ID
;
2382 /* Allocate house specs if they haven't been allocated already. */
2383 if (_cur
.grffile
->housespec
.size() < hid
+ numinfo
) _cur
.grffile
->housespec
.resize(hid
+ numinfo
);
2385 for (int i
= 0; i
< numinfo
; i
++) {
2386 HouseSpec
*housespec
= _cur
.grffile
->housespec
[hid
+ i
].get();
2388 if (prop
!= 0x08 && housespec
== nullptr) {
2389 /* If the house property 08 is not yet set, ignore this property */
2390 ChangeInfoResult cir
= IgnoreTownHouseProperty(prop
, buf
);
2391 if (cir
> ret
) ret
= cir
;
2396 case 0x08: { // Substitute building type, and definition of a new house
2397 byte subs_id
= buf
->ReadByte();
2398 if (subs_id
== 0xFF) {
2399 /* Instead of defining a new house, a substitute house id
2400 * of 0xFF disables the old house with the current id. */
2401 if (hid
+ i
< NEW_HOUSE_OFFSET
) HouseSpec::Get(hid
+ i
)->enabled
= false;
2403 } else if (subs_id
>= NEW_HOUSE_OFFSET
) {
2404 /* The substitute id must be one of the original houses. */
2405 GrfMsg(2, "TownHouseChangeInfo: Attempt to use new house {} as substitute house for {}. Ignoring.", subs_id
, hid
+ i
);
2409 /* Allocate space for this house. */
2410 if (housespec
== nullptr) {
2411 /* Only the first property 08 setting copies properties; if you later change it, properties will stay. */
2412 _cur
.grffile
->housespec
[hid
+ i
] = std::make_unique
<HouseSpec
>(*HouseSpec::Get(subs_id
));
2413 housespec
= _cur
.grffile
->housespec
[hid
+ i
].get();
2415 housespec
->enabled
= true;
2416 housespec
->grf_prop
.local_id
= hid
+ i
;
2417 housespec
->grf_prop
.subst_id
= subs_id
;
2418 housespec
->grf_prop
.grffile
= _cur
.grffile
;
2419 /* Set default colours for randomization, used if not overridden. */
2420 housespec
->random_colour
[0] = COLOUR_RED
;
2421 housespec
->random_colour
[1] = COLOUR_BLUE
;
2422 housespec
->random_colour
[2] = COLOUR_ORANGE
;
2423 housespec
->random_colour
[3] = COLOUR_GREEN
;
2425 /* House flags 40 and 80 are exceptions; these flags are never set automatically. */
2426 housespec
->building_flags
&= ~(BUILDING_IS_CHURCH
| BUILDING_IS_STADIUM
);
2428 /* Make sure that the third cargo type is valid in this
2429 * climate. This can cause problems when copying the properties
2430 * of a house that accepts food, where the new house is valid
2431 * in the temperate climate. */
2432 CargoID cid
= housespec
->accepts_cargo
[2];
2433 if (!IsValidCargoID(cid
)) cid
= GetCargoIDByLabel(housespec
->accepts_cargo_label
[2]);
2434 if (!IsValidCargoID(cid
)) {
2435 housespec
->cargo_acceptance
[2] = 0;
2441 case 0x09: // Building flags
2442 housespec
->building_flags
= (BuildingFlags
)buf
->ReadByte();
2445 case 0x0A: { // Availability years
2446 uint16_t years
= buf
->ReadWord();
2447 housespec
->min_year
= GB(years
, 0, 8) > 150 ? CalendarTime::MAX_YEAR
: CalendarTime::ORIGINAL_BASE_YEAR
+ GB(years
, 0, 8);
2448 housespec
->max_year
= GB(years
, 8, 8) > 150 ? CalendarTime::MAX_YEAR
: CalendarTime::ORIGINAL_BASE_YEAR
+ GB(years
, 8, 8);
2452 case 0x0B: // Population
2453 housespec
->population
= buf
->ReadByte();
2456 case 0x0C: // Mail generation multiplier
2457 housespec
->mail_generation
= buf
->ReadByte();
2460 case 0x0D: // Passenger acceptance
2461 case 0x0E: // Mail acceptance
2462 housespec
->cargo_acceptance
[prop
- 0x0D] = buf
->ReadByte();
2465 case 0x0F: { // Goods/candy, food/fizzy drinks acceptance
2466 int8_t goods
= buf
->ReadByte();
2468 /* If value of goods is negative, it means in fact food or, if in toyland, fizzy_drink acceptance.
2469 * Else, we have "standard" 3rd cargo type, goods or candy, for toyland once more */
2470 CargoID cid
= (goods
>= 0) ? ((_settings_game
.game_creation
.landscape
== LT_TOYLAND
) ? GetCargoIDByLabel(CT_CANDY
) : GetCargoIDByLabel(CT_GOODS
)) :
2471 ((_settings_game
.game_creation
.landscape
== LT_TOYLAND
) ? GetCargoIDByLabel(CT_FIZZY_DRINKS
) : GetCargoIDByLabel(CT_FOOD
));
2473 /* Make sure the cargo type is valid in this climate. */
2474 if (!IsValidCargoID(cid
)) goods
= 0;
2476 housespec
->accepts_cargo
[2] = cid
;
2477 housespec
->accepts_cargo_label
[2] = CT_INVALID
;
2478 housespec
->cargo_acceptance
[2] = abs(goods
); // but we do need positive value here
2482 case 0x10: // Local authority rating decrease on removal
2483 housespec
->remove_rating_decrease
= buf
->ReadWord();
2486 case 0x11: // Removal cost multiplier
2487 housespec
->removal_cost
= buf
->ReadByte();
2490 case 0x12: // Building name ID
2491 AddStringForMapping(buf
->ReadWord(), &housespec
->building_name
);
2494 case 0x13: // Building availability mask
2495 housespec
->building_availability
= (HouseZones
)buf
->ReadWord();
2498 case 0x14: // House callback mask
2499 housespec
->callback_mask
|= buf
->ReadByte();
2502 case 0x15: { // House override byte
2503 byte override
= buf
->ReadByte();
2505 /* The house being overridden must be an original house. */
2506 if (override
>= NEW_HOUSE_OFFSET
) {
2507 GrfMsg(2, "TownHouseChangeInfo: Attempt to override new house {} with house id {}. Ignoring.", override
, hid
+ i
);
2511 _house_mngr
.Add(hid
+ i
, _cur
.grffile
->grfid
, override
);
2515 case 0x16: // Periodic refresh multiplier
2516 housespec
->processing_time
= std::min
<byte
>(buf
->ReadByte(), 63u);
2519 case 0x17: // Four random colours to use
2520 for (uint j
= 0; j
< 4; j
++) housespec
->random_colour
[j
] = static_cast<Colours
>(GB(buf
->ReadByte(), 0, 4));
2523 case 0x18: // Relative probability of appearing
2524 housespec
->probability
= buf
->ReadByte();
2527 case 0x19: // Extra flags
2528 housespec
->extra_flags
= (HouseExtraFlags
)buf
->ReadByte();
2531 case 0x1A: // Animation frames
2532 housespec
->animation
.frames
= buf
->ReadByte();
2533 housespec
->animation
.status
= GB(housespec
->animation
.frames
, 7, 1);
2534 SB(housespec
->animation
.frames
, 7, 1, 0);
2537 case 0x1B: // Animation speed
2538 housespec
->animation
.speed
= Clamp(buf
->ReadByte(), 2, 16);
2541 case 0x1C: // Class of the building type
2542 housespec
->class_id
= AllocateHouseClassID(buf
->ReadByte(), _cur
.grffile
->grfid
);
2545 case 0x1D: // Callback mask part 2
2546 housespec
->callback_mask
|= (buf
->ReadByte() << 8);
2549 case 0x1E: { // Accepted cargo types
2550 uint32_t cargotypes
= buf
->ReadDWord();
2552 /* Check if the cargo types should not be changed */
2553 if (cargotypes
== 0xFFFFFFFF) break;
2555 for (uint j
= 0; j
< 3; j
++) {
2556 /* Get the cargo number from the 'list' */
2557 uint8_t cargo_part
= GB(cargotypes
, 8 * j
, 8);
2558 CargoID cargo
= GetCargoTranslation(cargo_part
, _cur
.grffile
);
2560 if (!IsValidCargoID(cargo
)) {
2561 /* Disable acceptance of invalid cargo type */
2562 housespec
->cargo_acceptance
[j
] = 0;
2564 housespec
->accepts_cargo
[j
] = cargo
;
2570 case 0x1F: // Minimum life span
2571 housespec
->minimum_life
= buf
->ReadByte();
2574 case 0x20: { // Cargo acceptance watch list
2575 byte count
= buf
->ReadByte();
2576 for (byte j
= 0; j
< count
; j
++) {
2577 CargoID cargo
= GetCargoTranslation(buf
->ReadByte(), _cur
.grffile
);
2578 if (IsValidCargoID(cargo
)) SetBit(housespec
->watched_cargoes
, cargo
);
2583 case 0x21: // long introduction year
2584 housespec
->min_year
= buf
->ReadWord();
2587 case 0x22: // long maximum year
2588 housespec
->max_year
= buf
->ReadWord();
2591 case 0x23: { // variable length cargo types accepted
2592 uint count
= buf
->ReadByte();
2593 if (count
> lengthof(housespec
->accepts_cargo
)) {
2594 GRFError
*error
= DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG
);
2595 error
->param_value
[1] = prop
;
2596 return CIR_DISABLED
;
2598 /* Always write the full accepts_cargo array, and check each index for being inside the
2599 * provided data. This ensures all values are properly initialized, and also avoids
2600 * any risks of array overrun. */
2601 for (uint i
= 0; i
< lengthof(housespec
->accepts_cargo
); i
++) {
2603 housespec
->accepts_cargo
[i
] = GetCargoTranslation(buf
->ReadByte(), _cur
.grffile
);
2604 housespec
->cargo_acceptance
[i
] = buf
->ReadByte();
2606 housespec
->accepts_cargo
[i
] = INVALID_CARGO
;
2607 housespec
->cargo_acceptance
[i
] = 0;
2609 housespec
->accepts_cargo_label
[i
] = CT_INVALID
;
2624 * Get the language map associated with a given NewGRF and language.
2625 * @param grfid The NewGRF to get the map for.
2626 * @param language_id The (NewGRF) language ID to get the map for.
2627 * @return The LanguageMap, or nullptr if it couldn't be found.
2629 /* static */ const LanguageMap
*LanguageMap::GetLanguageMap(uint32_t grfid
, uint8_t language_id
)
2631 /* LanguageID "MAX_LANG", i.e. 7F is any. This language can't have a gender/case mapping, but has to be handled gracefully. */
2632 const GRFFile
*grffile
= GetFileByGRFID(grfid
);
2633 return (grffile
!= nullptr && grffile
->language_map
!= nullptr && language_id
< MAX_LANG
) ? &grffile
->language_map
[language_id
] : nullptr;
2637 * Load a cargo- or railtype-translation table.
2638 * @param gvid ID of the global variable. This is basically only checked for zerones.
2639 * @param numinfo Number of subsequent IDs to change the property for.
2640 * @param buf The property value.
2641 * @param[in,out] translation_table Storage location for the translation table.
2642 * @param name Name of the table for debug output.
2643 * @return ChangeInfoResult.
2645 template <typename T
>
2646 static ChangeInfoResult
LoadTranslationTable(uint gvid
, int numinfo
, ByteReader
*buf
, std::vector
<T
> &translation_table
, const char *name
)
2649 GrfMsg(1, "LoadTranslationTable: {} translation table must start at zero", name
);
2650 return CIR_INVALID_ID
;
2653 translation_table
.clear();
2654 for (int i
= 0; i
< numinfo
; i
++) {
2655 translation_table
.push_back(T(BSWAP32(buf
->ReadDWord())));
2662 * Helper to read a DWord worth of bytes from the reader
2663 * and to return it as a valid string.
2664 * @param reader The source of the DWord.
2665 * @return The read DWord as string.
2667 static std::string
ReadDWordAsString(ByteReader
*reader
)
2670 for (int i
= 0; i
< 4; i
++) output
.push_back(reader
->ReadByte());
2671 return StrMakeValid(output
);
2675 * Define properties for global variables
2676 * @param gvid ID of the global variable.
2677 * @param numinfo Number of subsequent IDs to change the property for.
2678 * @param prop The property to change.
2679 * @param buf The property value.
2680 * @return ChangeInfoResult.
2682 static ChangeInfoResult
GlobalVarChangeInfo(uint gvid
, int numinfo
, int prop
, ByteReader
*buf
)
2684 /* Properties which are handled as a whole */
2686 case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2687 return LoadTranslationTable(gvid
, numinfo
, buf
, _cur
.grffile
->cargo_list
, "Cargo");
2689 case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2690 return LoadTranslationTable(gvid
, numinfo
, buf
, _cur
.grffile
->railtype_list
, "Rail type");
2692 case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2693 return LoadTranslationTable(gvid
, numinfo
, buf
, _cur
.grffile
->roadtype_list
, "Road type");
2695 case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2696 return LoadTranslationTable(gvid
, numinfo
, buf
, _cur
.grffile
->tramtype_list
, "Tram type");
2702 /* Properties which are handled per item */
2703 ChangeInfoResult ret
= CIR_SUCCESS
;
2704 for (int i
= 0; i
< numinfo
; i
++) {
2706 case 0x08: { // Cost base factor
2707 int factor
= buf
->ReadByte();
2708 uint price
= gvid
+ i
;
2710 if (price
< PR_END
) {
2711 _cur
.grffile
->price_base_multipliers
[price
] = std::min
<int>(factor
- 8, MAX_PRICE_MODIFIER
);
2713 GrfMsg(1, "GlobalVarChangeInfo: Price {} out of range, ignoring", price
);
2718 case 0x0A: { // Currency display names
2719 uint curidx
= GetNewgrfCurrencyIdConverted(gvid
+ i
);
2720 StringID newone
= GetGRFStringID(_cur
.grffile
->grfid
, buf
->ReadWord());
2722 if ((newone
!= STR_UNDEFINED
) && (curidx
< CURRENCY_END
)) {
2723 _currency_specs
[curidx
].name
= newone
;
2724 _currency_specs
[curidx
].code
.clear();
2729 case 0x0B: { // Currency multipliers
2730 uint curidx
= GetNewgrfCurrencyIdConverted(gvid
+ i
);
2731 uint32_t rate
= buf
->ReadDWord();
2733 if (curidx
< CURRENCY_END
) {
2734 /* TTDPatch uses a multiple of 1000 for its conversion calculations,
2735 * which OTTD does not. For this reason, divide grf value by 1000,
2736 * to be compatible */
2737 _currency_specs
[curidx
].rate
= rate
/ 1000;
2739 GrfMsg(1, "GlobalVarChangeInfo: Currency multipliers {} out of range, ignoring", curidx
);
2744 case 0x0C: { // Currency options
2745 uint curidx
= GetNewgrfCurrencyIdConverted(gvid
+ i
);
2746 uint16_t options
= buf
->ReadWord();
2748 if (curidx
< CURRENCY_END
) {
2749 _currency_specs
[curidx
].separator
.clear();
2750 _currency_specs
[curidx
].separator
.push_back(GB(options
, 0, 8));
2751 /* By specifying only one bit, we prevent errors,
2752 * since newgrf specs said that only 0 and 1 can be set for symbol_pos */
2753 _currency_specs
[curidx
].symbol_pos
= GB(options
, 8, 1);
2755 GrfMsg(1, "GlobalVarChangeInfo: Currency option {} out of range, ignoring", curidx
);
2760 case 0x0D: { // Currency prefix symbol
2761 uint curidx
= GetNewgrfCurrencyIdConverted(gvid
+ i
);
2762 std::string prefix
= ReadDWordAsString(buf
);
2764 if (curidx
< CURRENCY_END
) {
2765 _currency_specs
[curidx
].prefix
= prefix
;
2767 GrfMsg(1, "GlobalVarChangeInfo: Currency symbol {} out of range, ignoring", curidx
);
2772 case 0x0E: { // Currency suffix symbol
2773 uint curidx
= GetNewgrfCurrencyIdConverted(gvid
+ i
);
2774 std::string suffix
= ReadDWordAsString(buf
);
2776 if (curidx
< CURRENCY_END
) {
2777 _currency_specs
[curidx
].suffix
= suffix
;
2779 GrfMsg(1, "GlobalVarChangeInfo: Currency symbol {} out of range, ignoring", curidx
);
2784 case 0x0F: { // Euro introduction dates
2785 uint curidx
= GetNewgrfCurrencyIdConverted(gvid
+ i
);
2786 TimerGameCalendar::Year year_euro
= buf
->ReadWord();
2788 if (curidx
< CURRENCY_END
) {
2789 _currency_specs
[curidx
].to_euro
= year_euro
;
2791 GrfMsg(1, "GlobalVarChangeInfo: Euro intro date {} out of range, ignoring", curidx
);
2796 case 0x10: // Snow line height table
2797 if (numinfo
> 1 || IsSnowLineSet()) {
2798 GrfMsg(1, "GlobalVarChangeInfo: The snowline can only be set once ({})", numinfo
);
2799 } else if (buf
->Remaining() < SNOW_LINE_MONTHS
* SNOW_LINE_DAYS
) {
2800 GrfMsg(1, "GlobalVarChangeInfo: Not enough entries set in the snowline table ({})", buf
->Remaining());
2802 byte table
[SNOW_LINE_MONTHS
][SNOW_LINE_DAYS
];
2804 for (uint i
= 0; i
< SNOW_LINE_MONTHS
; i
++) {
2805 for (uint j
= 0; j
< SNOW_LINE_DAYS
; j
++) {
2806 table
[i
][j
] = buf
->ReadByte();
2807 if (_cur
.grffile
->grf_version
>= 8) {
2808 if (table
[i
][j
] != 0xFF) table
[i
][j
] = table
[i
][j
] * (1 + _settings_game
.construction
.map_height_limit
) / 256;
2810 if (table
[i
][j
] >= 128) {
2814 table
[i
][j
] = table
[i
][j
] * (1 + _settings_game
.construction
.map_height_limit
) / 128;
2823 case 0x11: // GRF match for engine allocation
2824 /* This is loaded during the reservation stage, so just skip it here. */
2825 /* Each entry is 8 bytes. */
2829 case 0x13: // Gender translation table
2830 case 0x14: // Case translation table
2831 case 0x15: { // Plural form translation
2832 uint curidx
= gvid
+ i
; // The current index, i.e. language.
2833 const LanguageMetadata
*lang
= curidx
< MAX_LANG
? GetLanguage(curidx
) : nullptr;
2834 if (lang
== nullptr) {
2835 GrfMsg(1, "GlobalVarChangeInfo: Language {} is not known, ignoring", curidx
);
2836 /* Skip over the data. */
2840 while (buf
->ReadByte() != 0) {
2847 if (_cur
.grffile
->language_map
== nullptr) _cur
.grffile
->language_map
= new LanguageMap
[MAX_LANG
];
2850 uint plural_form
= buf
->ReadByte();
2851 if (plural_form
>= LANGUAGE_MAX_PLURAL
) {
2852 GrfMsg(1, "GlobalVarChanceInfo: Plural form {} is out of range, ignoring", plural_form
);
2854 _cur
.grffile
->language_map
[curidx
].plural_form
= plural_form
;
2859 byte newgrf_id
= buf
->ReadByte(); // The NewGRF (custom) identifier.
2860 while (newgrf_id
!= 0) {
2861 const char *name
= buf
->ReadString(); // The name for the OpenTTD identifier.
2863 /* We'll just ignore the UTF8 identifier character. This is (fairly)
2864 * safe as OpenTTD's strings gender/cases are usually in ASCII which
2865 * is just a subset of UTF8, or they need the bigger UTF8 characters
2866 * such as Cyrillic. Thus we will simply assume they're all UTF8. */
2868 size_t len
= Utf8Decode(&c
, name
);
2869 if (c
== NFO_UTF8_IDENTIFIER
) name
+= len
;
2871 LanguageMap::Mapping map
;
2872 map
.newgrf_id
= newgrf_id
;
2874 map
.openttd_id
= lang
->GetGenderIndex(name
);
2875 if (map
.openttd_id
>= MAX_NUM_GENDERS
) {
2876 GrfMsg(1, "GlobalVarChangeInfo: Gender name {} is not known, ignoring", name
);
2878 _cur
.grffile
->language_map
[curidx
].gender_map
.push_back(map
);
2881 map
.openttd_id
= lang
->GetCaseIndex(name
);
2882 if (map
.openttd_id
>= MAX_NUM_CASES
) {
2883 GrfMsg(1, "GlobalVarChangeInfo: Case name {} is not known, ignoring", name
);
2885 _cur
.grffile
->language_map
[curidx
].case_map
.push_back(map
);
2888 newgrf_id
= buf
->ReadByte();
2902 static ChangeInfoResult
GlobalVarReserveInfo(uint gvid
, int numinfo
, int prop
, ByteReader
*buf
)
2904 /* Properties which are handled as a whole */
2906 case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2907 return LoadTranslationTable(gvid
, numinfo
, buf
, _cur
.grffile
->cargo_list
, "Cargo");
2909 case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2910 return LoadTranslationTable(gvid
, numinfo
, buf
, _cur
.grffile
->railtype_list
, "Rail type");
2912 case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined roadtypes)
2913 return LoadTranslationTable(gvid
, numinfo
, buf
, _cur
.grffile
->roadtype_list
, "Road type");
2915 case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined tramtypes)
2916 return LoadTranslationTable(gvid
, numinfo
, buf
, _cur
.grffile
->tramtype_list
, "Tram type");
2922 /* Properties which are handled per item */
2923 ChangeInfoResult ret
= CIR_SUCCESS
;
2924 for (int i
= 0; i
< numinfo
; i
++) {
2926 case 0x08: // Cost base factor
2927 case 0x15: // Plural form translation
2931 case 0x0A: // Currency display names
2932 case 0x0C: // Currency options
2933 case 0x0F: // Euro introduction dates
2937 case 0x0B: // Currency multipliers
2938 case 0x0D: // Currency prefix symbol
2939 case 0x0E: // Currency suffix symbol
2943 case 0x10: // Snow line height table
2944 buf
->Skip(SNOW_LINE_MONTHS
* SNOW_LINE_DAYS
);
2947 case 0x11: { // GRF match for engine allocation
2948 uint32_t s
= buf
->ReadDWord();
2949 uint32_t t
= buf
->ReadDWord();
2950 SetNewGRFOverride(s
, t
);
2954 case 0x13: // Gender translation table
2955 case 0x14: // Case translation table
2956 while (buf
->ReadByte() != 0) {
2972 * Define properties for cargoes
2973 * @param cid Local ID of the cargo.
2974 * @param numinfo Number of subsequent IDs to change the property for.
2975 * @param prop The property to change.
2976 * @param buf The property value.
2977 * @return ChangeInfoResult.
2979 static ChangeInfoResult
CargoChangeInfo(uint cid
, int numinfo
, int prop
, ByteReader
*buf
)
2981 ChangeInfoResult ret
= CIR_SUCCESS
;
2983 if (cid
+ numinfo
> NUM_CARGO
) {
2984 GrfMsg(2, "CargoChangeInfo: Cargo type {} out of range (max {})", cid
+ numinfo
, NUM_CARGO
- 1);
2985 return CIR_INVALID_ID
;
2988 for (int i
= 0; i
< numinfo
; i
++) {
2989 CargoSpec
*cs
= CargoSpec::Get(cid
+ i
);
2992 case 0x08: // Bit number of cargo
2993 cs
->bitnum
= buf
->ReadByte();
2994 if (cs
->IsValid()) {
2995 cs
->grffile
= _cur
.grffile
;
2996 SetBit(_cargo_mask
, cid
+ i
);
2998 ClrBit(_cargo_mask
, cid
+ i
);
3000 BuildCargoLabelMap();
3003 case 0x09: // String ID for cargo type name
3004 AddStringForMapping(buf
->ReadWord(), &cs
->name
);
3007 case 0x0A: // String for 1 unit of cargo
3008 AddStringForMapping(buf
->ReadWord(), &cs
->name_single
);
3011 case 0x0B: // String for singular quantity of cargo (e.g. 1 tonne of coal)
3012 case 0x1B: // String for cargo units
3013 /* String for units of cargo. This is different in OpenTTD
3014 * (e.g. tonnes) to TTDPatch (e.g. {COMMA} tonne of coal).
3015 * Property 1B is used to set OpenTTD's behaviour. */
3016 AddStringForMapping(buf
->ReadWord(), &cs
->units_volume
);
3019 case 0x0C: // String for plural quantity of cargo (e.g. 10 tonnes of coal)
3020 case 0x1C: // String for any amount of cargo
3021 /* Strings for an amount of cargo. This is different in OpenTTD
3022 * (e.g. {WEIGHT} of coal) to TTDPatch (e.g. {COMMA} tonnes of coal).
3023 * Property 1C is used to set OpenTTD's behaviour. */
3024 AddStringForMapping(buf
->ReadWord(), &cs
->quantifier
);
3027 case 0x0D: // String for two letter cargo abbreviation
3028 AddStringForMapping(buf
->ReadWord(), &cs
->abbrev
);
3031 case 0x0E: // Sprite ID for cargo icon
3032 cs
->sprite
= buf
->ReadWord();
3035 case 0x0F: // Weight of one unit of cargo
3036 cs
->weight
= buf
->ReadByte();
3039 case 0x10: // Used for payment calculation
3040 cs
->transit_periods
[0] = buf
->ReadByte();
3043 case 0x11: // Used for payment calculation
3044 cs
->transit_periods
[1] = buf
->ReadByte();
3047 case 0x12: // Base cargo price
3048 cs
->initial_payment
= buf
->ReadDWord();
3051 case 0x13: // Colour for station rating bars
3052 cs
->rating_colour
= buf
->ReadByte();
3055 case 0x14: // Colour for cargo graph
3056 cs
->legend_colour
= buf
->ReadByte();
3059 case 0x15: // Freight status
3060 cs
->is_freight
= (buf
->ReadByte() != 0);
3063 case 0x16: // Cargo classes
3064 cs
->classes
= buf
->ReadWord();
3067 case 0x17: // Cargo label
3068 cs
->label
= CargoLabel
{BSWAP32(buf
->ReadDWord())};
3069 BuildCargoLabelMap();
3072 case 0x18: { // Town growth substitute type
3073 uint8_t substitute_type
= buf
->ReadByte();
3075 switch (substitute_type
) {
3076 case 0x00: cs
->town_acceptance_effect
= TAE_PASSENGERS
; break;
3077 case 0x02: cs
->town_acceptance_effect
= TAE_MAIL
; break;
3078 case 0x05: cs
->town_acceptance_effect
= TAE_GOODS
; break;
3079 case 0x09: cs
->town_acceptance_effect
= TAE_WATER
; break;
3080 case 0x0B: cs
->town_acceptance_effect
= TAE_FOOD
; break;
3082 GrfMsg(1, "CargoChangeInfo: Unknown town growth substitute value {}, setting to none.", substitute_type
);
3084 case 0xFF: cs
->town_acceptance_effect
= TAE_NONE
; break;
3089 case 0x19: // Town growth coefficient
3093 case 0x1A: // Bitmask of callbacks to use
3094 cs
->callback_mask
= buf
->ReadByte();
3097 case 0x1D: // Vehicle capacity muliplier
3098 cs
->multiplier
= std::max
<uint16_t>(1u, buf
->ReadWord());
3101 case 0x1E: { // Town production substitute type
3102 uint8_t substitute_type
= buf
->ReadByte();
3104 switch (substitute_type
) {
3105 case 0x00: cs
->town_production_effect
= TPE_PASSENGERS
; break;
3106 case 0x02: cs
->town_production_effect
= TPE_MAIL
; break;
3108 GrfMsg(1, "CargoChangeInfo: Unknown town production substitute value {}, setting to none.", substitute_type
);
3110 case 0xFF: cs
->town_production_effect
= TPE_NONE
; break;
3115 case 0x1F: // Town production multiplier
3116 cs
->town_production_multiplier
= std::max
<uint16_t>(1U, buf
->ReadWord());
3130 * Define properties for sound effects
3131 * @param sid Local ID of the sound.
3132 * @param numinfo Number of subsequent IDs to change the property for.
3133 * @param prop The property to change.
3134 * @param buf The property value.
3135 * @return ChangeInfoResult.
3137 static ChangeInfoResult
SoundEffectChangeInfo(uint sid
, int numinfo
, int prop
, ByteReader
*buf
)
3139 ChangeInfoResult ret
= CIR_SUCCESS
;
3141 if (_cur
.grffile
->sound_offset
== 0) {
3142 GrfMsg(1, "SoundEffectChangeInfo: No effects defined, skipping");
3143 return CIR_INVALID_ID
;
3146 if (sid
+ numinfo
- ORIGINAL_SAMPLE_COUNT
> _cur
.grffile
->num_sounds
) {
3147 GrfMsg(1, "SoundEffectChangeInfo: Attempting to change undefined sound effect ({}), max ({}). Ignoring.", sid
+ numinfo
, ORIGINAL_SAMPLE_COUNT
+ _cur
.grffile
->num_sounds
);
3148 return CIR_INVALID_ID
;
3151 for (int i
= 0; i
< numinfo
; i
++) {
3152 SoundEntry
*sound
= GetSound(sid
+ i
+ _cur
.grffile
->sound_offset
- ORIGINAL_SAMPLE_COUNT
);
3155 case 0x08: // Relative volume
3156 sound
->volume
= buf
->ReadByte();
3159 case 0x09: // Priority
3160 sound
->priority
= buf
->ReadByte();
3163 case 0x0A: { // Override old sound
3164 SoundID orig_sound
= buf
->ReadByte();
3166 if (orig_sound
>= ORIGINAL_SAMPLE_COUNT
) {
3167 GrfMsg(1, "SoundEffectChangeInfo: Original sound {} not defined (max {})", orig_sound
, ORIGINAL_SAMPLE_COUNT
);
3169 SoundEntry
*old_sound
= GetSound(orig_sound
);
3171 /* Literally copy the data of the new sound over the original */
3172 *old_sound
= *sound
;
3187 * Ignore an industry tile property
3188 * @param prop The property to ignore.
3189 * @param buf The property value.
3190 * @return ChangeInfoResult.
3192 static ChangeInfoResult
IgnoreIndustryTileProperty(int prop
, ByteReader
*buf
)
3194 ChangeInfoResult ret
= CIR_SUCCESS
;
3214 buf
->Skip(buf
->ReadByte() * 2);
3225 * Define properties for industry tiles
3226 * @param indtid Local ID of the industry tile.
3227 * @param numinfo Number of subsequent industry tile IDs to change the property for.
3228 * @param prop The property to change.
3229 * @param buf The property value.
3230 * @return ChangeInfoResult.
3232 static ChangeInfoResult
IndustrytilesChangeInfo(uint indtid
, int numinfo
, int prop
, ByteReader
*buf
)
3234 ChangeInfoResult ret
= CIR_SUCCESS
;
3236 if (indtid
+ numinfo
> NUM_INDUSTRYTILES_PER_GRF
) {
3237 GrfMsg(1, "IndustryTilesChangeInfo: Too many industry tiles loaded ({}), max ({}). Ignoring.", indtid
+ numinfo
, NUM_INDUSTRYTILES_PER_GRF
);
3238 return CIR_INVALID_ID
;
3241 /* Allocate industry tile specs if they haven't been allocated already. */
3242 if (_cur
.grffile
->indtspec
.size() < indtid
+ numinfo
) _cur
.grffile
->indtspec
.resize(indtid
+ numinfo
);
3244 for (int i
= 0; i
< numinfo
; i
++) {
3245 IndustryTileSpec
*tsp
= _cur
.grffile
->indtspec
[indtid
+ i
].get();
3247 if (prop
!= 0x08 && tsp
== nullptr) {
3248 ChangeInfoResult cir
= IgnoreIndustryTileProperty(prop
, buf
);
3249 if (cir
> ret
) ret
= cir
;
3254 case 0x08: { // Substitute industry tile type
3255 byte subs_id
= buf
->ReadByte();
3256 if (subs_id
>= NEW_INDUSTRYTILEOFFSET
) {
3257 /* The substitute id must be one of the original industry tile. */
3258 GrfMsg(2, "IndustryTilesChangeInfo: Attempt to use new industry tile {} as substitute industry tile for {}. Ignoring.", subs_id
, indtid
+ i
);
3262 /* Allocate space for this industry. */
3263 if (tsp
== nullptr) {
3264 _cur
.grffile
->indtspec
[indtid
+ i
] = std::make_unique
<IndustryTileSpec
>(_industry_tile_specs
[subs_id
]);
3265 tsp
= _cur
.grffile
->indtspec
[indtid
+ i
].get();
3267 tsp
->enabled
= true;
3269 /* A copied tile should not have the animation infos copied too.
3270 * The anim_state should be left untouched, though
3271 * It is up to the author to animate them */
3272 tsp
->anim_production
= INDUSTRYTILE_NOANIM
;
3273 tsp
->anim_next
= INDUSTRYTILE_NOANIM
;
3275 tsp
->grf_prop
.local_id
= indtid
+ i
;
3276 tsp
->grf_prop
.subst_id
= subs_id
;
3277 tsp
->grf_prop
.grffile
= _cur
.grffile
;
3278 _industile_mngr
.AddEntityID(indtid
+ i
, _cur
.grffile
->grfid
, subs_id
); // pre-reserve the tile slot
3283 case 0x09: { // Industry tile override
3284 byte ovrid
= buf
->ReadByte();
3286 /* The industry being overridden must be an original industry. */
3287 if (ovrid
>= NEW_INDUSTRYTILEOFFSET
) {
3288 GrfMsg(2, "IndustryTilesChangeInfo: Attempt to override new industry tile {} with industry tile id {}. Ignoring.", ovrid
, indtid
+ i
);
3292 _industile_mngr
.Add(indtid
+ i
, _cur
.grffile
->grfid
, ovrid
);
3296 case 0x0A: // Tile acceptance
3299 uint16_t acctp
= buf
->ReadWord();
3300 tsp
->accepts_cargo
[prop
- 0x0A] = GetCargoTranslation(GB(acctp
, 0, 8), _cur
.grffile
);
3301 tsp
->acceptance
[prop
- 0x0A] = Clamp(GB(acctp
, 8, 8), 0, 16);
3305 case 0x0D: // Land shape flags
3306 tsp
->slopes_refused
= (Slope
)buf
->ReadByte();
3309 case 0x0E: // Callback mask
3310 tsp
->callback_mask
= buf
->ReadByte();
3313 case 0x0F: // Animation information
3314 tsp
->animation
.frames
= buf
->ReadByte();
3315 tsp
->animation
.status
= buf
->ReadByte();
3318 case 0x10: // Animation speed
3319 tsp
->animation
.speed
= buf
->ReadByte();
3322 case 0x11: // Triggers for callback 25
3323 tsp
->animation
.triggers
= buf
->ReadByte();
3326 case 0x12: // Special flags
3327 tsp
->special_flags
= (IndustryTileSpecialFlags
)buf
->ReadByte();
3330 case 0x13: { // variable length cargo acceptance
3331 byte num_cargoes
= buf
->ReadByte();
3332 if (num_cargoes
> std::size(tsp
->acceptance
)) {
3333 GRFError
*error
= DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG
);
3334 error
->param_value
[1] = prop
;
3335 return CIR_DISABLED
;
3337 for (uint i
= 0; i
< std::size(tsp
->acceptance
); i
++) {
3338 if (i
< num_cargoes
) {
3339 tsp
->accepts_cargo
[i
] = GetCargoTranslation(buf
->ReadByte(), _cur
.grffile
);
3340 /* Tile acceptance can be negative to counteract the INDTILE_SPECIAL_ACCEPTS_ALL_CARGO flag */
3341 tsp
->acceptance
[i
] = (int8_t)buf
->ReadByte();
3343 tsp
->accepts_cargo
[i
] = INVALID_CARGO
;
3344 tsp
->acceptance
[i
] = 0;
3346 tsp
->accepts_cargo_label
[i
] = CT_INVALID
;
3361 * Ignore an industry property
3362 * @param prop The property to ignore.
3363 * @param buf The property value.
3364 * @return ChangeInfoResult.
3366 static ChangeInfoResult
IgnoreIndustryProperty(int prop
, ByteReader
*buf
)
3368 ChangeInfoResult ret
= CIR_SUCCESS
;
3406 byte num_table
= buf
->ReadByte();
3407 for (byte j
= 0; j
< num_table
; j
++) {
3408 for (uint k
= 0;; k
++) {
3409 byte x
= buf
->ReadByte();
3410 if (x
== 0xFE && k
== 0) {
3416 byte y
= buf
->ReadByte();
3417 if (x
== 0 && y
== 0x80) break;
3419 byte gfx
= buf
->ReadByte();
3420 if (gfx
== 0xFE) buf
->ReadWord();
3427 for (byte j
= 0; j
< 3; j
++) buf
->ReadByte();
3434 buf
->Skip(buf
->ReadByte());
3438 int num_inputs
= buf
->ReadByte();
3439 int num_outputs
= buf
->ReadByte();
3440 buf
->Skip(num_inputs
* num_outputs
* 2);
3452 * Validate the industry layout; e.g. to prevent duplicate tiles.
3453 * @param layout The layout to check.
3454 * @return True if the layout is deemed valid.
3456 static bool ValidateIndustryLayout(const IndustryTileLayout
&layout
)
3458 const size_t size
= layout
.size();
3459 if (size
== 0) return false;
3461 for (size_t i
= 0; i
< size
- 1; i
++) {
3462 for (size_t j
= i
+ 1; j
< size
; j
++) {
3463 if (layout
[i
].ti
.x
== layout
[j
].ti
.x
&&
3464 layout
[i
].ti
.y
== layout
[j
].ti
.y
) {
3470 bool have_regular_tile
= false;
3471 for (const auto &tilelayout
: layout
) {
3472 if (tilelayout
.gfx
!= GFX_WATERTILE_SPECIALCHECK
) {
3473 have_regular_tile
= true;
3478 return have_regular_tile
;
3482 * Define properties for industries
3483 * @param indid Local ID of the industry.
3484 * @param numinfo Number of subsequent industry IDs to change the property for.
3485 * @param prop The property to change.
3486 * @param buf The property value.
3487 * @return ChangeInfoResult.
3489 static ChangeInfoResult
IndustriesChangeInfo(uint indid
, int numinfo
, int prop
, ByteReader
*buf
)
3491 ChangeInfoResult ret
= CIR_SUCCESS
;
3493 if (indid
+ numinfo
> NUM_INDUSTRYTYPES_PER_GRF
) {
3494 GrfMsg(1, "IndustriesChangeInfo: Too many industries loaded ({}), max ({}). Ignoring.", indid
+ numinfo
, NUM_INDUSTRYTYPES_PER_GRF
);
3495 return CIR_INVALID_ID
;
3498 /* Allocate industry specs if they haven't been allocated already. */
3499 if (_cur
.grffile
->industryspec
.size() < indid
+ numinfo
) _cur
.grffile
->industryspec
.resize(indid
+ numinfo
);
3501 for (int i
= 0; i
< numinfo
; i
++) {
3502 IndustrySpec
*indsp
= _cur
.grffile
->industryspec
[indid
+ i
].get();
3504 if (prop
!= 0x08 && indsp
== nullptr) {
3505 ChangeInfoResult cir
= IgnoreIndustryProperty(prop
, buf
);
3506 if (cir
> ret
) ret
= cir
;
3511 case 0x08: { // Substitute industry type
3512 byte subs_id
= buf
->ReadByte();
3513 if (subs_id
== 0xFF) {
3514 /* Instead of defining a new industry, a substitute industry id
3515 * of 0xFF disables the old industry with the current id. */
3516 _industry_specs
[indid
+ i
].enabled
= false;
3518 } else if (subs_id
>= NEW_INDUSTRYOFFSET
) {
3519 /* The substitute id must be one of the original industry. */
3520 GrfMsg(2, "_industry_specs: Attempt to use new industry {} as substitute industry for {}. Ignoring.", subs_id
, indid
+ i
);
3524 /* Allocate space for this industry.
3525 * Only need to do it once. If ever it is called again, it should not
3527 if (indsp
== nullptr) {
3528 _cur
.grffile
->industryspec
[indid
+ i
] = std::make_unique
<IndustrySpec
>(_origin_industry_specs
[subs_id
]);
3529 indsp
= _cur
.grffile
->industryspec
[indid
+ i
].get();
3531 indsp
->enabled
= true;
3532 indsp
->grf_prop
.local_id
= indid
+ i
;
3533 indsp
->grf_prop
.subst_id
= subs_id
;
3534 indsp
->grf_prop
.grffile
= _cur
.grffile
;
3535 /* If the grf industry needs to check its surrounding upon creation, it should
3536 * rely on callbacks, not on the original placement functions */
3537 indsp
->check_proc
= CHECK_NOTHING
;
3542 case 0x09: { // Industry type override
3543 byte ovrid
= buf
->ReadByte();
3545 /* The industry being overridden must be an original industry. */
3546 if (ovrid
>= NEW_INDUSTRYOFFSET
) {
3547 GrfMsg(2, "IndustriesChangeInfo: Attempt to override new industry {} with industry id {}. Ignoring.", ovrid
, indid
+ i
);
3550 indsp
->grf_prop
.override
= ovrid
;
3551 _industry_mngr
.Add(indid
+ i
, _cur
.grffile
->grfid
, ovrid
);
3555 case 0x0A: { // Set industry layout(s)
3556 byte new_num_layouts
= buf
->ReadByte();
3557 uint32_t definition_size
= buf
->ReadDWord();
3558 uint32_t bytes_read
= 0;
3559 std::vector
<IndustryTileLayout
> new_layouts
;
3560 IndustryTileLayout layout
;
3562 for (byte j
= 0; j
< new_num_layouts
; j
++) {
3565 for (uint k
= 0;; k
++) {
3566 if (bytes_read
>= definition_size
) {
3567 GrfMsg(3, "IndustriesChangeInfo: Incorrect size for industry tile layout definition for industry {}.", indid
);
3568 /* Avoid warning twice */
3569 definition_size
= UINT32_MAX
;
3572 layout
.push_back(IndustryTileLayoutTile
{});
3573 IndustryTileLayoutTile
&it
= layout
.back();
3575 it
.ti
.x
= buf
->ReadByte(); // Offsets from northermost tile
3578 if (it
.ti
.x
== 0xFE && k
== 0) {
3579 /* This means we have to borrow the layout from an old industry */
3580 IndustryType type
= buf
->ReadByte();
3581 byte laynbr
= buf
->ReadByte();
3584 if (type
>= lengthof(_origin_industry_specs
)) {
3585 GrfMsg(1, "IndustriesChangeInfo: Invalid original industry number for layout import, industry {}", indid
);
3586 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID
);
3587 return CIR_DISABLED
;
3589 if (laynbr
>= _origin_industry_specs
[type
].layouts
.size()) {
3590 GrfMsg(1, "IndustriesChangeInfo: Invalid original industry layout index for layout import, industry {}", indid
);
3591 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID
);
3592 return CIR_DISABLED
;
3594 layout
= _origin_industry_specs
[type
].layouts
[laynbr
];
3598 it
.ti
.y
= buf
->ReadByte(); // Or table definition finalisation
3601 if (it
.ti
.x
== 0 && it
.ti
.y
== 0x80) {
3602 /* Terminator, remove and finish up */
3607 it
.gfx
= buf
->ReadByte();
3610 if (it
.gfx
== 0xFE) {
3611 /* Use a new tile from this GRF */
3612 int local_tile_id
= buf
->ReadWord();
3615 /* Read the ID from the _industile_mngr. */
3616 int tempid
= _industile_mngr
.GetID(local_tile_id
, _cur
.grffile
->grfid
);
3618 if (tempid
== INVALID_INDUSTRYTILE
) {
3619 GrfMsg(2, "IndustriesChangeInfo: Attempt to use industry tile {} with industry id {}, not yet defined. Ignoring.", local_tile_id
, indid
);
3621 /* Declared as been valid, can be used */
3624 } else if (it
.gfx
== GFX_WATERTILE_SPECIALCHECK
) {
3625 it
.ti
.x
= (int8_t)GB(it
.ti
.x
, 0, 8);
3626 it
.ti
.y
= (int8_t)GB(it
.ti
.y
, 0, 8);
3628 /* When there were only 256x256 maps, TileIndex was a uint16_t and
3629 * it.ti was just a TileIndexDiff that was added to it.
3630 * As such negative "x" values were shifted into the "y" position.
3631 * x = -1, y = 1 -> x = 255, y = 0
3632 * Since GRF version 8 the position is interpreted as pair of independent int8.
3633 * For GRF version < 8 we need to emulate the old shifting behaviour.
3635 if (_cur
.grffile
->grf_version
< 8 && it
.ti
.x
< 0) it
.ti
.y
+= 1;
3639 if (!ValidateIndustryLayout(layout
)) {
3640 /* The industry layout was not valid, so skip this one. */
3641 GrfMsg(1, "IndustriesChangeInfo: Invalid industry layout for industry id {}. Ignoring", indid
);
3645 new_layouts
.push_back(layout
);
3649 /* Install final layout construction in the industry spec */
3650 indsp
->layouts
= new_layouts
;
3654 case 0x0B: // Industry production flags
3655 indsp
->life_type
= (IndustryLifeType
)buf
->ReadByte();
3658 case 0x0C: // Industry closure message
3659 AddStringForMapping(buf
->ReadWord(), &indsp
->closure_text
);
3662 case 0x0D: // Production increase message
3663 AddStringForMapping(buf
->ReadWord(), &indsp
->production_up_text
);
3666 case 0x0E: // Production decrease message
3667 AddStringForMapping(buf
->ReadWord(), &indsp
->production_down_text
);
3670 case 0x0F: // Fund cost multiplier
3671 indsp
->cost_multiplier
= buf
->ReadByte();
3674 case 0x10: // Production cargo types
3675 for (byte j
= 0; j
< 2; j
++) {
3676 indsp
->produced_cargo
[j
] = GetCargoTranslation(buf
->ReadByte(), _cur
.grffile
);
3677 indsp
->produced_cargo_label
[j
] = CT_INVALID
;
3681 case 0x11: // Acceptance cargo types
3682 for (byte j
= 0; j
< 3; j
++) {
3683 indsp
->accepts_cargo
[j
] = GetCargoTranslation(buf
->ReadByte(), _cur
.grffile
);
3684 indsp
->accepts_cargo_label
[j
] = CT_INVALID
;
3686 buf
->ReadByte(); // Unnused, eat it up
3689 case 0x12: // Production multipliers
3691 indsp
->production_rate
[prop
- 0x12] = buf
->ReadByte();
3694 case 0x14: // Minimal amount of cargo distributed
3695 indsp
->minimal_cargo
= buf
->ReadByte();
3698 case 0x15: { // Random sound effects
3699 indsp
->number_of_sounds
= buf
->ReadByte();
3700 uint8_t *sounds
= MallocT
<uint8_t>(indsp
->number_of_sounds
);
3703 for (uint8_t j
= 0; j
< indsp
->number_of_sounds
; j
++) {
3704 sounds
[j
] = buf
->ReadByte();
3711 if (HasBit(indsp
->cleanup_flag
, CLEAN_RANDOMSOUNDS
)) {
3712 free(indsp
->random_sounds
);
3714 indsp
->random_sounds
= sounds
;
3715 SetBit(indsp
->cleanup_flag
, CLEAN_RANDOMSOUNDS
);
3719 case 0x16: // Conflicting industry types
3720 for (byte j
= 0; j
< 3; j
++) indsp
->conflicting
[j
] = buf
->ReadByte();
3723 case 0x17: // Probability in random game
3724 indsp
->appear_creation
[_settings_game
.game_creation
.landscape
] = buf
->ReadByte();
3727 case 0x18: // Probability during gameplay
3728 indsp
->appear_ingame
[_settings_game
.game_creation
.landscape
] = buf
->ReadByte();
3731 case 0x19: // Map colour
3732 indsp
->map_colour
= buf
->ReadByte();
3735 case 0x1A: // Special industry flags to define special behavior
3736 indsp
->behaviour
= (IndustryBehaviour
)buf
->ReadDWord();
3739 case 0x1B: // New industry text ID
3740 AddStringForMapping(buf
->ReadWord(), &indsp
->new_industry_text
);
3743 case 0x1C: // Input cargo multipliers for the three input cargo types
3746 uint32_t multiples
= buf
->ReadDWord();
3747 indsp
->input_cargo_multiplier
[prop
- 0x1C][0] = GB(multiples
, 0, 16);
3748 indsp
->input_cargo_multiplier
[prop
- 0x1C][1] = GB(multiples
, 16, 16);
3752 case 0x1F: // Industry name
3753 AddStringForMapping(buf
->ReadWord(), &indsp
->name
);
3756 case 0x20: // Prospecting success chance
3757 indsp
->prospecting_chance
= buf
->ReadDWord();
3760 case 0x21: // Callback mask
3761 case 0x22: { // Callback additional mask
3762 byte aflag
= buf
->ReadByte();
3763 SB(indsp
->callback_mask
, (prop
- 0x21) * 8, 8, aflag
);
3767 case 0x23: // removal cost multiplier
3768 indsp
->removal_cost_multiplier
= buf
->ReadDWord();
3771 case 0x24: { // name for nearby station
3772 uint16_t str
= buf
->ReadWord();
3774 indsp
->station_name
= STR_NULL
;
3776 AddStringForMapping(str
, &indsp
->station_name
);
3781 case 0x25: { // variable length produced cargoes
3782 byte num_cargoes
= buf
->ReadByte();
3783 if (num_cargoes
> lengthof(indsp
->produced_cargo
)) {
3784 GRFError
*error
= DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG
);
3785 error
->param_value
[1] = prop
;
3786 return CIR_DISABLED
;
3788 for (uint i
= 0; i
< lengthof(indsp
->produced_cargo
); i
++) {
3789 if (i
< num_cargoes
) {
3790 CargoID cargo
= GetCargoTranslation(buf
->ReadByte(), _cur
.grffile
);
3791 indsp
->produced_cargo
[i
] = cargo
;
3793 indsp
->produced_cargo
[i
] = INVALID_CARGO
;
3795 indsp
->produced_cargo_label
[i
] = CT_INVALID
;
3800 case 0x26: { // variable length accepted cargoes
3801 byte num_cargoes
= buf
->ReadByte();
3802 if (num_cargoes
> lengthof(indsp
->accepts_cargo
)) {
3803 GRFError
*error
= DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG
);
3804 error
->param_value
[1] = prop
;
3805 return CIR_DISABLED
;
3807 for (uint i
= 0; i
< lengthof(indsp
->accepts_cargo
); i
++) {
3808 if (i
< num_cargoes
) {
3809 CargoID cargo
= GetCargoTranslation(buf
->ReadByte(), _cur
.grffile
);
3810 indsp
->accepts_cargo
[i
] = cargo
;
3812 indsp
->accepts_cargo
[i
] = INVALID_CARGO
;
3814 indsp
->accepts_cargo_label
[i
] = CT_INVALID
;
3819 case 0x27: { // variable length production rates
3820 byte num_cargoes
= buf
->ReadByte();
3821 if (num_cargoes
> lengthof(indsp
->production_rate
)) {
3822 GRFError
*error
= DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG
);
3823 error
->param_value
[1] = prop
;
3824 return CIR_DISABLED
;
3826 for (uint i
= 0; i
< lengthof(indsp
->production_rate
); i
++) {
3827 if (i
< num_cargoes
) {
3828 indsp
->production_rate
[i
] = buf
->ReadByte();
3830 indsp
->production_rate
[i
] = 0;
3836 case 0x28: { // variable size input/output production multiplier table
3837 byte num_inputs
= buf
->ReadByte();
3838 byte num_outputs
= buf
->ReadByte();
3839 if (num_inputs
> lengthof(indsp
->accepts_cargo
) || num_outputs
> lengthof(indsp
->produced_cargo
)) {
3840 GRFError
*error
= DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG
);
3841 error
->param_value
[1] = prop
;
3842 return CIR_DISABLED
;
3844 for (uint i
= 0; i
< lengthof(indsp
->accepts_cargo
); i
++) {
3845 for (uint j
= 0; j
< lengthof(indsp
->produced_cargo
); j
++) {
3847 if (i
< num_inputs
&& j
< num_outputs
) mult
= buf
->ReadWord();
3848 indsp
->input_cargo_multiplier
[i
][j
] = mult
;
3864 * Create a copy of the tile table so it can be freed later
3866 * @param as The AirportSpec to copy the arrays of.
3868 static void DuplicateTileTable(AirportSpec
*as
)
3870 AirportTileTable
**table_list
= MallocT
<AirportTileTable
*>(as
->num_table
);
3871 for (int i
= 0; i
< as
->num_table
; i
++) {
3873 const AirportTileTable
*it
= as
->table
[0];
3876 } while ((++it
)->ti
.x
!= -0x80);
3877 table_list
[i
] = MallocT
<AirportTileTable
>(num_tiles
);
3878 MemCpyT(table_list
[i
], as
->table
[i
], num_tiles
);
3880 as
->table
= table_list
;
3881 HangarTileTable
*depot_table
= MallocT
<HangarTileTable
>(as
->nof_depots
);
3882 MemCpyT(depot_table
, as
->depot_table
, as
->nof_depots
);
3883 as
->depot_table
= depot_table
;
3884 Direction
*rotation
= MallocT
<Direction
>(as
->num_table
);
3885 MemCpyT(rotation
, as
->rotation
, as
->num_table
);
3886 as
->rotation
= rotation
;
3890 * Define properties for airports
3891 * @param airport Local ID of the airport.
3892 * @param numinfo Number of subsequent airport IDs to change the property for.
3893 * @param prop The property to change.
3894 * @param buf The property value.
3895 * @return ChangeInfoResult.
3897 static ChangeInfoResult
AirportChangeInfo(uint airport
, int numinfo
, int prop
, ByteReader
*buf
)
3899 ChangeInfoResult ret
= CIR_SUCCESS
;
3901 if (airport
+ numinfo
> NUM_AIRPORTS_PER_GRF
) {
3902 GrfMsg(1, "AirportChangeInfo: Too many airports, trying id ({}), max ({}). Ignoring.", airport
+ numinfo
, NUM_AIRPORTS_PER_GRF
);
3903 return CIR_INVALID_ID
;
3906 /* Allocate industry specs if they haven't been allocated already. */
3907 if (_cur
.grffile
->airportspec
.size() < airport
+ numinfo
) _cur
.grffile
->airportspec
.resize(airport
+ numinfo
);
3909 for (int i
= 0; i
< numinfo
; i
++) {
3910 AirportSpec
*as
= _cur
.grffile
->airportspec
[airport
+ i
].get();
3912 if (as
== nullptr && prop
!= 0x08 && prop
!= 0x09) {
3913 GrfMsg(2, "AirportChangeInfo: Attempt to modify undefined airport {}, ignoring", airport
+ i
);
3914 return CIR_INVALID_ID
;
3918 case 0x08: { // Modify original airport
3919 byte subs_id
= buf
->ReadByte();
3920 if (subs_id
== 0xFF) {
3921 /* Instead of defining a new airport, an airport id
3922 * of 0xFF disables the old airport with the current id. */
3923 AirportSpec::GetWithoutOverride(airport
+ i
)->enabled
= false;
3925 } else if (subs_id
>= NEW_AIRPORT_OFFSET
) {
3926 /* The substitute id must be one of the original airports. */
3927 GrfMsg(2, "AirportChangeInfo: Attempt to use new airport {} as substitute airport for {}. Ignoring.", subs_id
, airport
+ i
);
3931 /* Allocate space for this airport.
3932 * Only need to do it once. If ever it is called again, it should not
3934 if (as
== nullptr) {
3935 _cur
.grffile
->airportspec
[airport
+ i
] = std::make_unique
<AirportSpec
>(*AirportSpec::GetWithoutOverride(subs_id
));
3936 as
= _cur
.grffile
->airportspec
[airport
+ i
].get();
3939 as
->grf_prop
.local_id
= airport
+ i
;
3940 as
->grf_prop
.subst_id
= subs_id
;
3941 as
->grf_prop
.grffile
= _cur
.grffile
;
3942 /* override the default airport */
3943 _airport_mngr
.Add(airport
+ i
, _cur
.grffile
->grfid
, subs_id
);
3944 /* Create a copy of the original tiletable so it can be freed later. */
3945 DuplicateTileTable(as
);
3950 case 0x0A: { // Set airport layout
3951 byte old_num_table
= as
->num_table
;
3953 as
->num_table
= buf
->ReadByte(); // Number of layaouts
3954 as
->rotation
= MallocT
<Direction
>(as
->num_table
);
3955 uint32_t defsize
= buf
->ReadDWord(); // Total size of the definition
3956 AirportTileTable
**tile_table
= CallocT
<AirportTileTable
*>(as
->num_table
); // Table with tiles to compose the airport
3957 AirportTileTable
*att
= CallocT
<AirportTileTable
>(defsize
); // Temporary array to read the tile layouts from the GRF
3959 const AirportTileTable
*copy_from
;
3961 for (byte j
= 0; j
< as
->num_table
; j
++) {
3962 const_cast<Direction
&>(as
->rotation
[j
]) = (Direction
)buf
->ReadByte();
3963 for (int k
= 0;; k
++) {
3964 att
[k
].ti
.x
= buf
->ReadByte(); // Offsets from northermost tile
3965 att
[k
].ti
.y
= buf
->ReadByte();
3967 if (att
[k
].ti
.x
== 0 && att
[k
].ti
.y
== 0x80) {
3968 /* Not the same terminator. The one we are using is rather
3969 * x = -80, y = 0 . So, adjust it. */
3970 att
[k
].ti
.x
= -0x80;
3979 att
[k
].gfx
= buf
->ReadByte();
3981 if (att
[k
].gfx
== 0xFE) {
3982 /* Use a new tile from this GRF */
3983 int local_tile_id
= buf
->ReadWord();
3985 /* Read the ID from the _airporttile_mngr. */
3986 uint16_t tempid
= _airporttile_mngr
.GetID(local_tile_id
, _cur
.grffile
->grfid
);
3988 if (tempid
== INVALID_AIRPORTTILE
) {
3989 GrfMsg(2, "AirportChangeInfo: Attempt to use airport tile {} with airport id {}, not yet defined. Ignoring.", local_tile_id
, airport
+ i
);
3991 /* Declared as been valid, can be used */
3992 att
[k
].gfx
= tempid
;
3994 } else if (att
[k
].gfx
== 0xFF) {
3995 att
[k
].ti
.x
= (int8_t)GB(att
[k
].ti
.x
, 0, 8);
3996 att
[k
].ti
.y
= (int8_t)GB(att
[k
].ti
.y
, 0, 8);
3999 if (as
->rotation
[j
] == DIR_E
|| as
->rotation
[j
] == DIR_W
) {
4000 as
->size_x
= std::max
<byte
>(as
->size_x
, att
[k
].ti
.y
+ 1);
4001 as
->size_y
= std::max
<byte
>(as
->size_y
, att
[k
].ti
.x
+ 1);
4003 as
->size_x
= std::max
<byte
>(as
->size_x
, att
[k
].ti
.x
+ 1);
4004 as
->size_y
= std::max
<byte
>(as
->size_y
, att
[k
].ti
.y
+ 1);
4007 tile_table
[j
] = CallocT
<AirportTileTable
>(size
);
4008 memcpy(tile_table
[j
], copy_from
, sizeof(*copy_from
) * size
);
4010 /* Free old layouts in the airport spec */
4011 for (int j
= 0; j
< old_num_table
; j
++) {
4012 /* remove the individual layouts */
4016 /* Install final layout construction in the airport spec */
4017 as
->table
= tile_table
;
4020 for (int i
= 0; i
< as
->num_table
; i
++) {
4021 free(tile_table
[i
]);
4031 as
->min_year
= buf
->ReadWord();
4032 as
->max_year
= buf
->ReadWord();
4033 if (as
->max_year
== 0xFFFF) as
->max_year
= CalendarTime::MAX_YEAR
;
4037 as
->ttd_airport_type
= (TTDPAirportType
)buf
->ReadByte();
4041 as
->catchment
= Clamp(buf
->ReadByte(), 1, MAX_CATCHMENT
);
4045 as
->noise_level
= buf
->ReadByte();
4049 AddStringForMapping(buf
->ReadWord(), &as
->name
);
4052 case 0x11: // Maintenance cost factor
4053 as
->maintenance_cost
= buf
->ReadWord();
4066 * Ignore properties for objects
4067 * @param prop The property to ignore.
4068 * @param buf The property value.
4069 * @return ChangeInfoResult.
4071 static ChangeInfoResult
IgnoreObjectProperty(uint prop
, ByteReader
*buf
)
4073 ChangeInfoResult ret
= CIR_SUCCESS
;
4111 * Define properties for objects
4112 * @param id Local ID of the object.
4113 * @param numinfo Number of subsequent objectIDs to change the property for.
4114 * @param prop The property to change.
4115 * @param buf The property value.
4116 * @return ChangeInfoResult.
4118 static ChangeInfoResult
ObjectChangeInfo(uint id
, int numinfo
, int prop
, ByteReader
*buf
)
4120 ChangeInfoResult ret
= CIR_SUCCESS
;
4122 if (id
+ numinfo
> NUM_OBJECTS_PER_GRF
) {
4123 GrfMsg(1, "ObjectChangeInfo: Too many objects loaded ({}), max ({}). Ignoring.", id
+ numinfo
, NUM_OBJECTS_PER_GRF
);
4124 return CIR_INVALID_ID
;
4127 /* Allocate object specs if they haven't been allocated already. */
4128 if (_cur
.grffile
->objectspec
.size() < id
+ numinfo
) _cur
.grffile
->objectspec
.resize(id
+ numinfo
);
4130 for (int i
= 0; i
< numinfo
; i
++) {
4131 ObjectSpec
*spec
= _cur
.grffile
->objectspec
[id
+ i
].get();
4133 if (prop
!= 0x08 && spec
== nullptr) {
4134 /* If the object property 08 is not yet set, ignore this property */
4135 ChangeInfoResult cir
= IgnoreObjectProperty(prop
, buf
);
4136 if (cir
> ret
) ret
= cir
;
4141 case 0x08: { // Class ID
4142 /* Allocate space for this object. */
4143 if (spec
== nullptr) {
4144 _cur
.grffile
->objectspec
[id
+ i
] = std::make_unique
<ObjectSpec
>();
4145 spec
= _cur
.grffile
->objectspec
[id
+ i
].get();
4146 spec
->views
= 1; // Default for NewGRFs that don't set it.
4147 spec
->size
= OBJECT_SIZE_1X1
; // Default for NewGRFs that manage to not set it (1x1)
4150 /* Swap classid because we read it in BE. */
4151 uint32_t classid
= buf
->ReadDWord();
4152 spec
->cls_id
= ObjectClass::Allocate(BSWAP32(classid
));
4156 case 0x09: { // Class name
4157 ObjectClass
*objclass
= ObjectClass::Get(spec
->cls_id
);
4158 AddStringForMapping(buf
->ReadWord(), &objclass
->name
);
4162 case 0x0A: // Object name
4163 AddStringForMapping(buf
->ReadWord(), &spec
->name
);
4166 case 0x0B: // Climate mask
4167 spec
->climate
= buf
->ReadByte();
4171 spec
->size
= buf
->ReadByte();
4172 if (GB(spec
->size
, 0, 4) == 0 || GB(spec
->size
, 4, 4) == 0) {
4173 GrfMsg(0, "ObjectChangeInfo: Invalid object size requested (0x{:X}) for object id {}. Ignoring.", spec
->size
, id
+ i
);
4174 spec
->size
= OBJECT_SIZE_1X1
;
4178 case 0x0D: // Build cost multipler
4179 spec
->build_cost_multiplier
= buf
->ReadByte();
4180 spec
->clear_cost_multiplier
= spec
->build_cost_multiplier
;
4183 case 0x0E: // Introduction date
4184 spec
->introduction_date
= buf
->ReadDWord();
4187 case 0x0F: // End of life
4188 spec
->end_of_life_date
= buf
->ReadDWord();
4192 spec
->flags
= (ObjectFlags
)buf
->ReadWord();
4193 _loaded_newgrf_features
.has_2CC
|= (spec
->flags
& OBJECT_FLAG_2CC_COLOUR
) != 0;
4196 case 0x11: // Animation info
4197 spec
->animation
.frames
= buf
->ReadByte();
4198 spec
->animation
.status
= buf
->ReadByte();
4201 case 0x12: // Animation speed
4202 spec
->animation
.speed
= buf
->ReadByte();
4205 case 0x13: // Animation triggers
4206 spec
->animation
.triggers
= buf
->ReadWord();
4209 case 0x14: // Removal cost multiplier
4210 spec
->clear_cost_multiplier
= buf
->ReadByte();
4213 case 0x15: // Callback mask
4214 spec
->callback_mask
= buf
->ReadWord();
4217 case 0x16: // Building height
4218 spec
->height
= buf
->ReadByte();
4222 spec
->views
= buf
->ReadByte();
4223 if (spec
->views
!= 1 && spec
->views
!= 2 && spec
->views
!= 4) {
4224 GrfMsg(2, "ObjectChangeInfo: Invalid number of views ({}) for object id {}. Ignoring.", spec
->views
, id
+ i
);
4229 case 0x18: // Amount placed on 256^2 map on map creation
4230 spec
->generate_amount
= buf
->ReadByte();
4243 * Define properties for railtypes
4244 * @param id ID of the railtype.
4245 * @param numinfo Number of subsequent IDs to change the property for.
4246 * @param prop The property to change.
4247 * @param buf The property value.
4248 * @return ChangeInfoResult.
4250 static ChangeInfoResult
RailTypeChangeInfo(uint id
, int numinfo
, int prop
, ByteReader
*buf
)
4252 ChangeInfoResult ret
= CIR_SUCCESS
;
4254 extern RailTypeInfo _railtypes
[RAILTYPE_END
];
4256 if (id
+ numinfo
> RAILTYPE_END
) {
4257 GrfMsg(1, "RailTypeChangeInfo: Rail type {} is invalid, max {}, ignoring", id
+ numinfo
, RAILTYPE_END
);
4258 return CIR_INVALID_ID
;
4261 for (int i
= 0; i
< numinfo
; i
++) {
4262 RailType rt
= _cur
.grffile
->railtype_map
[id
+ i
];
4263 if (rt
== INVALID_RAILTYPE
) return CIR_INVALID_ID
;
4265 RailTypeInfo
*rti
= &_railtypes
[rt
];
4268 case 0x08: // Label of rail type
4269 /* Skipped here as this is loaded during reservation stage. */
4273 case 0x09: { // Toolbar caption of railtype (sets name as well for backwards compatibility for grf ver < 8)
4274 uint16_t str
= buf
->ReadWord();
4275 AddStringForMapping(str
, &rti
->strings
.toolbar_caption
);
4276 if (_cur
.grffile
->grf_version
< 8) {
4277 AddStringForMapping(str
, &rti
->strings
.name
);
4282 case 0x0A: // Menu text of railtype
4283 AddStringForMapping(buf
->ReadWord(), &rti
->strings
.menu_text
);
4286 case 0x0B: // Build window caption
4287 AddStringForMapping(buf
->ReadWord(), &rti
->strings
.build_caption
);
4290 case 0x0C: // Autoreplace text
4291 AddStringForMapping(buf
->ReadWord(), &rti
->strings
.replace_text
);
4294 case 0x0D: // New locomotive text
4295 AddStringForMapping(buf
->ReadWord(), &rti
->strings
.new_loco
);
4298 case 0x0E: // Compatible railtype list
4299 case 0x0F: // Powered railtype list
4300 case 0x18: // Railtype list required for date introduction
4301 case 0x19: // Introduced railtype list
4303 /* Rail type compatibility bits are added to the existing bits
4304 * to allow multiple GRFs to modify compatibility with the
4305 * default rail types. */
4306 int n
= buf
->ReadByte();
4307 for (int j
= 0; j
!= n
; j
++) {
4308 RailTypeLabel label
= buf
->ReadDWord();
4309 RailType resolved_rt
= GetRailTypeByLabel(BSWAP32(label
), false);
4310 if (resolved_rt
!= INVALID_RAILTYPE
) {
4312 case 0x0F: SetBit(rti
->powered_railtypes
, resolved_rt
); [[fallthrough
]]; // Powered implies compatible.
4313 case 0x0E: SetBit(rti
->compatible_railtypes
, resolved_rt
); break;
4314 case 0x18: SetBit(rti
->introduction_required_railtypes
, resolved_rt
); break;
4315 case 0x19: SetBit(rti
->introduces_railtypes
, resolved_rt
); break;
4322 case 0x10: // Rail Type flags
4323 rti
->flags
= (RailTypeFlags
)buf
->ReadByte();
4326 case 0x11: // Curve speed advantage
4327 rti
->curve_speed
= buf
->ReadByte();
4330 case 0x12: // Station graphic
4331 rti
->fallback_railtype
= Clamp(buf
->ReadByte(), 0, 2);
4334 case 0x13: // Construction cost factor
4335 rti
->cost_multiplier
= buf
->ReadWord();
4338 case 0x14: // Speed limit
4339 rti
->max_speed
= buf
->ReadWord();
4342 case 0x15: // Acceleration model
4343 rti
->acceleration_type
= Clamp(buf
->ReadByte(), 0, 2);
4346 case 0x16: // Map colour
4347 rti
->map_colour
= buf
->ReadByte();
4350 case 0x17: // Introduction date
4351 rti
->introduction_date
= buf
->ReadDWord();
4354 case 0x1A: // Sort order
4355 rti
->sorting_order
= buf
->ReadByte();
4358 case 0x1B: // Name of railtype (overridden by prop 09 for grf ver < 8)
4359 AddStringForMapping(buf
->ReadWord(), &rti
->strings
.name
);
4362 case 0x1C: // Maintenance cost factor
4363 rti
->maintenance_multiplier
= buf
->ReadWord();
4366 case 0x1D: // Alternate rail type label list
4367 /* Skipped here as this is loaded during reservation stage. */
4368 for (int j
= buf
->ReadByte(); j
!= 0; j
--) buf
->ReadDWord();
4380 static ChangeInfoResult
RailTypeReserveInfo(uint id
, int numinfo
, int prop
, ByteReader
*buf
)
4382 ChangeInfoResult ret
= CIR_SUCCESS
;
4384 extern RailTypeInfo _railtypes
[RAILTYPE_END
];
4386 if (id
+ numinfo
> RAILTYPE_END
) {
4387 GrfMsg(1, "RailTypeReserveInfo: Rail type {} is invalid, max {}, ignoring", id
+ numinfo
, RAILTYPE_END
);
4388 return CIR_INVALID_ID
;
4391 for (int i
= 0; i
< numinfo
; i
++) {
4393 case 0x08: // Label of rail type
4395 RailTypeLabel rtl
= buf
->ReadDWord();
4398 RailType rt
= GetRailTypeByLabel(rtl
, false);
4399 if (rt
== INVALID_RAILTYPE
) {
4400 /* Set up new rail type */
4401 rt
= AllocateRailType(rtl
);
4404 _cur
.grffile
->railtype_map
[id
+ i
] = rt
;
4408 case 0x09: // Toolbar caption of railtype
4409 case 0x0A: // Menu text
4410 case 0x0B: // Build window caption
4411 case 0x0C: // Autoreplace text
4412 case 0x0D: // New loco
4413 case 0x13: // Construction cost
4414 case 0x14: // Speed limit
4415 case 0x1B: // Name of railtype
4416 case 0x1C: // Maintenance cost factor
4420 case 0x1D: // Alternate rail type label list
4421 if (_cur
.grffile
->railtype_map
[id
+ i
] != INVALID_RAILTYPE
) {
4422 int n
= buf
->ReadByte();
4423 for (int j
= 0; j
!= n
; j
++) {
4424 _railtypes
[_cur
.grffile
->railtype_map
[id
+ i
]].alternate_labels
.push_back(BSWAP32(buf
->ReadDWord()));
4428 GrfMsg(1, "RailTypeReserveInfo: Ignoring property 1D for rail type {} because no label was set", id
+ i
);
4431 case 0x0E: // Compatible railtype list
4432 case 0x0F: // Powered railtype list
4433 case 0x18: // Railtype list required for date introduction
4434 case 0x19: // Introduced railtype list
4435 for (int j
= buf
->ReadByte(); j
!= 0; j
--) buf
->ReadDWord();
4438 case 0x10: // Rail Type flags
4439 case 0x11: // Curve speed advantage
4440 case 0x12: // Station graphic
4441 case 0x15: // Acceleration model
4442 case 0x16: // Map colour
4443 case 0x1A: // Sort order
4447 case 0x17: // Introduction date
4461 * Define properties for roadtypes
4462 * @param id ID of the roadtype.
4463 * @param numinfo Number of subsequent IDs to change the property for.
4464 * @param prop The property to change.
4465 * @param buf The property value.
4466 * @return ChangeInfoResult.
4468 static ChangeInfoResult
RoadTypeChangeInfo(uint id
, int numinfo
, int prop
, ByteReader
*buf
, RoadTramType rtt
)
4470 ChangeInfoResult ret
= CIR_SUCCESS
;
4472 extern RoadTypeInfo _roadtypes
[ROADTYPE_END
];
4473 RoadType
*type_map
= (rtt
== RTT_TRAM
) ? _cur
.grffile
->tramtype_map
: _cur
.grffile
->roadtype_map
;
4475 if (id
+ numinfo
> ROADTYPE_END
) {
4476 GrfMsg(1, "RoadTypeChangeInfo: Road type {} is invalid, max {}, ignoring", id
+ numinfo
, ROADTYPE_END
);
4477 return CIR_INVALID_ID
;
4480 for (int i
= 0; i
< numinfo
; i
++) {
4481 RoadType rt
= type_map
[id
+ i
];
4482 if (rt
== INVALID_ROADTYPE
) return CIR_INVALID_ID
;
4484 RoadTypeInfo
*rti
= &_roadtypes
[rt
];
4487 case 0x08: // Label of road type
4488 /* Skipped here as this is loaded during reservation stage. */
4492 case 0x09: { // Toolbar caption of roadtype (sets name as well for backwards compatibility for grf ver < 8)
4493 uint16_t str
= buf
->ReadWord();
4494 AddStringForMapping(str
, &rti
->strings
.toolbar_caption
);
4498 case 0x0A: // Menu text of roadtype
4499 AddStringForMapping(buf
->ReadWord(), &rti
->strings
.menu_text
);
4502 case 0x0B: // Build window caption
4503 AddStringForMapping(buf
->ReadWord(), &rti
->strings
.build_caption
);
4506 case 0x0C: // Autoreplace text
4507 AddStringForMapping(buf
->ReadWord(), &rti
->strings
.replace_text
);
4510 case 0x0D: // New engine text
4511 AddStringForMapping(buf
->ReadWord(), &rti
->strings
.new_engine
);
4514 case 0x0F: // Powered roadtype list
4515 case 0x18: // Roadtype list required for date introduction
4516 case 0x19: { // Introduced roadtype list
4517 /* Road type compatibility bits are added to the existing bits
4518 * to allow multiple GRFs to modify compatibility with the
4519 * default road types. */
4520 int n
= buf
->ReadByte();
4521 for (int j
= 0; j
!= n
; j
++) {
4522 RoadTypeLabel label
= buf
->ReadDWord();
4523 RoadType resolved_rt
= GetRoadTypeByLabel(BSWAP32(label
), false);
4524 if (resolved_rt
!= INVALID_ROADTYPE
) {
4527 if (GetRoadTramType(resolved_rt
) == rtt
) {
4528 SetBit(rti
->powered_roadtypes
, resolved_rt
);
4530 GrfMsg(1, "RoadTypeChangeInfo: Powered road type list: Road type {} road/tram type does not match road type {}, ignoring", resolved_rt
, rt
);
4533 case 0x18: SetBit(rti
->introduction_required_roadtypes
, resolved_rt
); break;
4534 case 0x19: SetBit(rti
->introduces_roadtypes
, resolved_rt
); break;
4541 case 0x10: // Road Type flags
4542 rti
->flags
= (RoadTypeFlags
)buf
->ReadByte();
4545 case 0x13: // Construction cost factor
4546 rti
->cost_multiplier
= buf
->ReadWord();
4549 case 0x14: // Speed limit
4550 rti
->max_speed
= buf
->ReadWord();
4553 case 0x16: // Map colour
4554 rti
->map_colour
= buf
->ReadByte();
4557 case 0x17: // Introduction date
4558 rti
->introduction_date
= buf
->ReadDWord();
4561 case 0x1A: // Sort order
4562 rti
->sorting_order
= buf
->ReadByte();
4565 case 0x1B: // Name of roadtype
4566 AddStringForMapping(buf
->ReadWord(), &rti
->strings
.name
);
4569 case 0x1C: // Maintenance cost factor
4570 rti
->maintenance_multiplier
= buf
->ReadWord();
4573 case 0x1D: // Alternate road type label list
4574 /* Skipped here as this is loaded during reservation stage. */
4575 for (int j
= buf
->ReadByte(); j
!= 0; j
--) buf
->ReadDWord();
4587 static ChangeInfoResult
RoadTypeChangeInfo(uint id
, int numinfo
, int prop
, ByteReader
*buf
)
4589 return RoadTypeChangeInfo(id
, numinfo
, prop
, buf
, RTT_ROAD
);
4592 static ChangeInfoResult
TramTypeChangeInfo(uint id
, int numinfo
, int prop
, ByteReader
*buf
)
4594 return RoadTypeChangeInfo(id
, numinfo
, prop
, buf
, RTT_TRAM
);
4598 static ChangeInfoResult
RoadTypeReserveInfo(uint id
, int numinfo
, int prop
, ByteReader
*buf
, RoadTramType rtt
)
4600 ChangeInfoResult ret
= CIR_SUCCESS
;
4602 extern RoadTypeInfo _roadtypes
[ROADTYPE_END
];
4603 RoadType
*type_map
= (rtt
== RTT_TRAM
) ? _cur
.grffile
->tramtype_map
: _cur
.grffile
->roadtype_map
;
4605 if (id
+ numinfo
> ROADTYPE_END
) {
4606 GrfMsg(1, "RoadTypeReserveInfo: Road type {} is invalid, max {}, ignoring", id
+ numinfo
, ROADTYPE_END
);
4607 return CIR_INVALID_ID
;
4610 for (int i
= 0; i
< numinfo
; i
++) {
4612 case 0x08: { // Label of road type
4613 RoadTypeLabel rtl
= buf
->ReadDWord();
4616 RoadType rt
= GetRoadTypeByLabel(rtl
, false);
4617 if (rt
== INVALID_ROADTYPE
) {
4618 /* Set up new road type */
4619 rt
= AllocateRoadType(rtl
, rtt
);
4620 } else if (GetRoadTramType(rt
) != rtt
) {
4621 GrfMsg(1, "RoadTypeReserveInfo: Road type {} is invalid type (road/tram), ignoring", id
+ numinfo
);
4622 return CIR_INVALID_ID
;
4625 type_map
[id
+ i
] = rt
;
4628 case 0x09: // Toolbar caption of roadtype
4629 case 0x0A: // Menu text
4630 case 0x0B: // Build window caption
4631 case 0x0C: // Autoreplace text
4632 case 0x0D: // New loco
4633 case 0x13: // Construction cost
4634 case 0x14: // Speed limit
4635 case 0x1B: // Name of roadtype
4636 case 0x1C: // Maintenance cost factor
4640 case 0x1D: // Alternate road type label list
4641 if (type_map
[id
+ i
] != INVALID_ROADTYPE
) {
4642 int n
= buf
->ReadByte();
4643 for (int j
= 0; j
!= n
; j
++) {
4644 _roadtypes
[type_map
[id
+ i
]].alternate_labels
.push_back(BSWAP32(buf
->ReadDWord()));
4648 GrfMsg(1, "RoadTypeReserveInfo: Ignoring property 1D for road type {} because no label was set", id
+ i
);
4651 case 0x0F: // Powered roadtype list
4652 case 0x18: // Roadtype list required for date introduction
4653 case 0x19: // Introduced roadtype list
4654 for (int j
= buf
->ReadByte(); j
!= 0; j
--) buf
->ReadDWord();
4657 case 0x10: // Road Type flags
4658 case 0x16: // Map colour
4659 case 0x1A: // Sort order
4663 case 0x17: // Introduction date
4676 static ChangeInfoResult
RoadTypeReserveInfo(uint id
, int numinfo
, int prop
, ByteReader
*buf
)
4678 return RoadTypeReserveInfo(id
, numinfo
, prop
, buf
, RTT_ROAD
);
4681 static ChangeInfoResult
TramTypeReserveInfo(uint id
, int numinfo
, int prop
, ByteReader
*buf
)
4683 return RoadTypeReserveInfo(id
, numinfo
, prop
, buf
, RTT_TRAM
);
4686 static ChangeInfoResult
AirportTilesChangeInfo(uint airtid
, int numinfo
, int prop
, ByteReader
*buf
)
4688 ChangeInfoResult ret
= CIR_SUCCESS
;
4690 if (airtid
+ numinfo
> NUM_AIRPORTTILES_PER_GRF
) {
4691 GrfMsg(1, "AirportTileChangeInfo: Too many airport tiles loaded ({}), max ({}). Ignoring.", airtid
+ numinfo
, NUM_AIRPORTTILES_PER_GRF
);
4692 return CIR_INVALID_ID
;
4695 /* Allocate airport tile specs if they haven't been allocated already. */
4696 if (_cur
.grffile
->airtspec
.size() < airtid
+ numinfo
) _cur
.grffile
->airtspec
.resize(airtid
+ numinfo
);
4698 for (int i
= 0; i
< numinfo
; i
++) {
4699 AirportTileSpec
*tsp
= _cur
.grffile
->airtspec
[airtid
+ i
].get();
4701 if (prop
!= 0x08 && tsp
== nullptr) {
4702 GrfMsg(2, "AirportTileChangeInfo: Attempt to modify undefined airport tile {}. Ignoring.", airtid
+ i
);
4703 return CIR_INVALID_ID
;
4707 case 0x08: { // Substitute airport tile type
4708 byte subs_id
= buf
->ReadByte();
4709 if (subs_id
>= NEW_AIRPORTTILE_OFFSET
) {
4710 /* The substitute id must be one of the original airport tiles. */
4711 GrfMsg(2, "AirportTileChangeInfo: Attempt to use new airport tile {} as substitute airport tile for {}. Ignoring.", subs_id
, airtid
+ i
);
4715 /* Allocate space for this airport tile. */
4716 if (tsp
== nullptr) {
4717 _cur
.grffile
->airtspec
[airtid
+ i
] = std::make_unique
<AirportTileSpec
>(*AirportTileSpec::Get(subs_id
));
4718 tsp
= _cur
.grffile
->airtspec
[airtid
+ i
].get();
4720 tsp
->enabled
= true;
4722 tsp
->animation
.status
= ANIM_STATUS_NO_ANIMATION
;
4724 tsp
->grf_prop
.local_id
= airtid
+ i
;
4725 tsp
->grf_prop
.subst_id
= subs_id
;
4726 tsp
->grf_prop
.grffile
= _cur
.grffile
;
4727 _airporttile_mngr
.AddEntityID(airtid
+ i
, _cur
.grffile
->grfid
, subs_id
); // pre-reserve the tile slot
4732 case 0x09: { // Airport tile override
4733 byte override
= buf
->ReadByte();
4735 /* The airport tile being overridden must be an original airport tile. */
4736 if (override
>= NEW_AIRPORTTILE_OFFSET
) {
4737 GrfMsg(2, "AirportTileChangeInfo: Attempt to override new airport tile {} with airport tile id {}. Ignoring.", override
, airtid
+ i
);
4741 _airporttile_mngr
.Add(airtid
+ i
, _cur
.grffile
->grfid
, override
);
4745 case 0x0E: // Callback mask
4746 tsp
->callback_mask
= buf
->ReadByte();
4749 case 0x0F: // Animation information
4750 tsp
->animation
.frames
= buf
->ReadByte();
4751 tsp
->animation
.status
= buf
->ReadByte();
4754 case 0x10: // Animation speed
4755 tsp
->animation
.speed
= buf
->ReadByte();
4758 case 0x11: // Animation triggers
4759 tsp
->animation
.triggers
= buf
->ReadByte();
4772 * Ignore properties for roadstops
4773 * @param prop The property to ignore.
4774 * @param buf The property value.
4775 * @return ChangeInfoResult.
4777 static ChangeInfoResult
IgnoreRoadStopProperty(uint prop
, ByteReader
*buf
)
4779 ChangeInfoResult ret
= CIR_SUCCESS
;
4811 static ChangeInfoResult
RoadStopChangeInfo(uint id
, int numinfo
, int prop
, ByteReader
*buf
)
4813 ChangeInfoResult ret
= CIR_SUCCESS
;
4815 if (id
+ numinfo
> NUM_ROADSTOPS_PER_GRF
) {
4816 GrfMsg(1, "RoadStopChangeInfo: RoadStop {} is invalid, max {}, ignoring", id
+ numinfo
, NUM_ROADSTOPS_PER_GRF
);
4817 return CIR_INVALID_ID
;
4820 if (_cur
.grffile
->roadstops
.size() < id
+ numinfo
) _cur
.grffile
->roadstops
.resize(id
+ numinfo
);
4822 for (int i
= 0; i
< numinfo
; i
++) {
4823 RoadStopSpec
*rs
= _cur
.grffile
->roadstops
[id
+ i
].get();
4825 if (rs
== nullptr && prop
!= 0x08) {
4826 GrfMsg(1, "RoadStopChangeInfo: Attempt to modify undefined road stop {}, ignoring", id
+ i
);
4827 ChangeInfoResult cir
= IgnoreRoadStopProperty(prop
, buf
);
4828 if (cir
> ret
) ret
= cir
;
4833 case 0x08: { // Road Stop Class ID
4834 if (rs
== nullptr) {
4835 _cur
.grffile
->roadstops
[id
+ i
] = std::make_unique
<RoadStopSpec
>();
4836 rs
= _cur
.grffile
->roadstops
[id
+ i
].get();
4839 uint32_t classid
= buf
->ReadDWord();
4840 rs
->cls_id
= RoadStopClass::Allocate(BSWAP32(classid
));
4841 rs
->spec_id
= id
+ i
;
4845 case 0x09: // Road stop type
4846 rs
->stop_type
= (RoadStopAvailabilityType
)buf
->ReadByte();
4849 case 0x0A: // Road Stop Name
4850 AddStringForMapping(buf
->ReadWord(), &rs
->name
);
4853 case 0x0B: // Road Stop Class name
4854 AddStringForMapping(buf
->ReadWord(), &RoadStopClass::Get(rs
->cls_id
)->name
);
4857 case 0x0C: // The draw mode
4858 rs
->draw_mode
= (RoadStopDrawMode
)buf
->ReadByte();
4861 case 0x0D: // Cargo types for random triggers
4862 rs
->cargo_triggers
= TranslateRefitMask(buf
->ReadDWord());
4865 case 0x0E: // Animation info
4866 rs
->animation
.frames
= buf
->ReadByte();
4867 rs
->animation
.status
= buf
->ReadByte();
4870 case 0x0F: // Animation speed
4871 rs
->animation
.speed
= buf
->ReadByte();
4874 case 0x10: // Animation triggers
4875 rs
->animation
.triggers
= buf
->ReadWord();
4878 case 0x11: // Callback mask
4879 rs
->callback_mask
= buf
->ReadByte();
4882 case 0x12: // General flags
4883 rs
->flags
= (uint8_t)buf
->ReadDWord(); // Future-proofing, size this as 4 bytes, but we only need one byte's worth of flags at present
4886 case 0x15: // Cost multipliers
4887 rs
->build_cost_multiplier
= buf
->ReadByte();
4888 rs
->clear_cost_multiplier
= buf
->ReadByte();
4900 static bool HandleChangeInfoResult(const char *caller
, ChangeInfoResult cir
, uint8_t feature
, uint8_t property
)
4903 default: NOT_REACHED();
4906 /* Error has already been printed; just stop parsing */
4913 GrfMsg(1, "{}: Ignoring property 0x{:02X} of feature 0x{:02X} (not implemented)", caller
, property
, feature
);
4917 GrfMsg(0, "{}: Unknown property 0x{:02X} of feature 0x{:02X}, disabling", caller
, property
, feature
);
4920 case CIR_INVALID_ID
: {
4921 /* No debug message for an invalid ID, as it has already been output */
4922 GRFError
*error
= DisableGrf(cir
== CIR_INVALID_ID
? STR_NEWGRF_ERROR_INVALID_ID
: STR_NEWGRF_ERROR_UNKNOWN_PROPERTY
);
4923 if (cir
!= CIR_INVALID_ID
) error
->param_value
[1] = property
;
4930 static void FeatureChangeInfo(ByteReader
*buf
)
4932 /* <00> <feature> <num-props> <num-info> <id> (<property <new-info>)...
4935 * B num-props how many properties to change per vehicle/station
4936 * B num-info how many vehicles/stations to change
4937 * E id ID of first vehicle/station to change, if num-info is
4938 * greater than one, this one and the following
4939 * vehicles/stations will be changed
4940 * B property what property to change, depends on the feature
4941 * V new-info new bytes of info (variable size; depends on properties) */
4943 static const VCI_Handler handler
[] = {
4944 /* GSF_TRAINS */ RailVehicleChangeInfo
,
4945 /* GSF_ROADVEHICLES */ RoadVehicleChangeInfo
,
4946 /* GSF_SHIPS */ ShipVehicleChangeInfo
,
4947 /* GSF_AIRCRAFT */ AircraftVehicleChangeInfo
,
4948 /* GSF_STATIONS */ StationChangeInfo
,
4949 /* GSF_CANALS */ CanalChangeInfo
,
4950 /* GSF_BRIDGES */ BridgeChangeInfo
,
4951 /* GSF_HOUSES */ TownHouseChangeInfo
,
4952 /* GSF_GLOBALVAR */ GlobalVarChangeInfo
,
4953 /* GSF_INDUSTRYTILES */ IndustrytilesChangeInfo
,
4954 /* GSF_INDUSTRIES */ IndustriesChangeInfo
,
4955 /* GSF_CARGOES */ nullptr, // Cargo is handled during reservation
4956 /* GSF_SOUNDFX */ SoundEffectChangeInfo
,
4957 /* GSF_AIRPORTS */ AirportChangeInfo
,
4958 /* GSF_SIGNALS */ nullptr,
4959 /* GSF_OBJECTS */ ObjectChangeInfo
,
4960 /* GSF_RAILTYPES */ RailTypeChangeInfo
,
4961 /* GSF_AIRPORTTILES */ AirportTilesChangeInfo
,
4962 /* GSF_ROADTYPES */ RoadTypeChangeInfo
,
4963 /* GSF_TRAMTYPES */ TramTypeChangeInfo
,
4964 /* GSF_ROADSTOPS */ RoadStopChangeInfo
,
4966 static_assert(GSF_END
== lengthof(handler
));
4968 uint8_t feature
= buf
->ReadByte();
4969 uint8_t numprops
= buf
->ReadByte();
4970 uint numinfo
= buf
->ReadByte();
4971 uint engine
= buf
->ReadExtendedByte();
4973 if (feature
>= GSF_END
) {
4974 GrfMsg(1, "FeatureChangeInfo: Unsupported feature 0x{:02X}, skipping", feature
);
4978 GrfMsg(6, "FeatureChangeInfo: Feature 0x{:02X}, {} properties, to apply to {}+{}",
4979 feature
, numprops
, engine
, numinfo
);
4981 if (handler
[feature
] == nullptr) {
4982 if (feature
!= GSF_CARGOES
) GrfMsg(1, "FeatureChangeInfo: Unsupported feature 0x{:02X}, skipping", feature
);
4986 /* Mark the feature as used by the grf */
4987 SetBit(_cur
.grffile
->grf_features
, feature
);
4989 while (numprops
-- && buf
->HasData()) {
4990 uint8_t prop
= buf
->ReadByte();
4992 ChangeInfoResult cir
= handler
[feature
](engine
, numinfo
, prop
, buf
);
4993 if (HandleChangeInfoResult("FeatureChangeInfo", cir
, feature
, prop
)) return;
4997 /* Action 0x00 (GLS_SAFETYSCAN) */
4998 static void SafeChangeInfo(ByteReader
*buf
)
5000 uint8_t feature
= buf
->ReadByte();
5001 uint8_t numprops
= buf
->ReadByte();
5002 uint numinfo
= buf
->ReadByte();
5003 buf
->ReadExtendedByte(); // id
5005 if (feature
== GSF_BRIDGES
&& numprops
== 1) {
5006 uint8_t prop
= buf
->ReadByte();
5007 /* Bridge property 0x0D is redefinition of sprite layout tables, which
5008 * is considered safe. */
5009 if (prop
== 0x0D) return;
5010 } else if (feature
== GSF_GLOBALVAR
&& numprops
== 1) {
5011 uint8_t prop
= buf
->ReadByte();
5012 /* Engine ID Mappings are safe, if the source is static */
5014 bool is_safe
= true;
5015 for (uint i
= 0; i
< numinfo
; i
++) {
5016 uint32_t s
= buf
->ReadDWord();
5017 buf
->ReadDWord(); // dest
5018 const GRFConfig
*grfconfig
= GetGRFConfig(s
);
5019 if (grfconfig
!= nullptr && !HasBit(grfconfig
->flags
, GCF_STATIC
)) {
5024 if (is_safe
) return;
5028 SetBit(_cur
.grfconfig
->flags
, GCF_UNSAFE
);
5030 /* Skip remainder of GRF */
5031 _cur
.skip_sprites
= -1;
5034 /* Action 0x00 (GLS_RESERVE) */
5035 static void ReserveChangeInfo(ByteReader
*buf
)
5037 uint8_t feature
= buf
->ReadByte();
5039 if (feature
!= GSF_CARGOES
&& feature
!= GSF_GLOBALVAR
&& feature
!= GSF_RAILTYPES
&& feature
!= GSF_ROADTYPES
&& feature
!= GSF_TRAMTYPES
) return;
5041 uint8_t numprops
= buf
->ReadByte();
5042 uint8_t numinfo
= buf
->ReadByte();
5043 uint8_t index
= buf
->ReadExtendedByte();
5045 while (numprops
-- && buf
->HasData()) {
5046 uint8_t prop
= buf
->ReadByte();
5047 ChangeInfoResult cir
= CIR_SUCCESS
;
5050 default: NOT_REACHED();
5052 cir
= CargoChangeInfo(index
, numinfo
, prop
, buf
);
5056 cir
= GlobalVarReserveInfo(index
, numinfo
, prop
, buf
);
5060 cir
= RailTypeReserveInfo(index
, numinfo
, prop
, buf
);
5064 cir
= RoadTypeReserveInfo(index
, numinfo
, prop
, buf
);
5068 cir
= TramTypeReserveInfo(index
, numinfo
, prop
, buf
);
5072 if (HandleChangeInfoResult("ReserveChangeInfo", cir
, feature
, prop
)) return;
5077 static void NewSpriteSet(ByteReader
*buf
)
5079 /* Basic format: <01> <feature> <num-sets> <num-ent>
5080 * Extended format: <01> <feature> 00 <first-set> <num-sets> <num-ent>
5082 * B feature feature to define sprites for
5083 * 0, 1, 2, 3: veh-type, 4: train stations
5084 * E first-set first sprite set to define
5085 * B num-sets number of sprite sets (extended byte in extended format)
5086 * E num-ent how many entries per sprite set
5087 * For vehicles, this is the number of different
5088 * vehicle directions in each sprite set
5089 * Set num-dirs=8, unless your sprites are symmetric.
5090 * In that case, use num-dirs=4.
5093 uint8_t feature
= buf
->ReadByte();
5094 uint16_t num_sets
= buf
->ReadByte();
5095 uint16_t first_set
= 0;
5097 if (num_sets
== 0 && buf
->HasData(3)) {
5098 /* Extended Action1 format.
5099 * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
5100 first_set
= buf
->ReadExtendedByte();
5101 num_sets
= buf
->ReadExtendedByte();
5103 uint16_t num_ents
= buf
->ReadExtendedByte();
5105 if (feature
>= GSF_END
) {
5106 _cur
.skip_sprites
= num_sets
* num_ents
;
5107 GrfMsg(1, "NewSpriteSet: Unsupported feature 0x{:02X}, skipping {} sprites", feature
, _cur
.skip_sprites
);
5111 _cur
.AddSpriteSets(feature
, _cur
.spriteid
, first_set
, num_sets
, num_ents
);
5113 GrfMsg(7, "New sprite set at {} of feature 0x{:02X}, consisting of {} sets with {} views each (total {})",
5114 _cur
.spriteid
, feature
, num_sets
, num_ents
, num_sets
* num_ents
5117 for (int i
= 0; i
< num_sets
* num_ents
; i
++) {
5119 LoadNextSprite(_cur
.spriteid
++, *_cur
.file
, _cur
.nfo_line
);
5123 /* Action 0x01 (SKIP) */
5124 static void SkipAct1(ByteReader
*buf
)
5127 uint16_t num_sets
= buf
->ReadByte();
5129 if (num_sets
== 0 && buf
->HasData(3)) {
5130 /* Extended Action1 format.
5131 * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
5132 buf
->ReadExtendedByte(); // first_set
5133 num_sets
= buf
->ReadExtendedByte();
5135 uint16_t num_ents
= buf
->ReadExtendedByte();
5137 _cur
.skip_sprites
= num_sets
* num_ents
;
5139 GrfMsg(3, "SkipAct1: Skipping {} sprites", _cur
.skip_sprites
);
5142 /* Helper function to either create a callback or link to a previously
5143 * defined spritegroup. */
5144 static const SpriteGroup
*GetGroupFromGroupID(byte setid
, byte type
, uint16_t groupid
)
5146 if (HasBit(groupid
, 15)) {
5147 assert(CallbackResultSpriteGroup::CanAllocateItem());
5148 return new CallbackResultSpriteGroup(groupid
, _cur
.grffile
->grf_version
>= 8);
5151 if (groupid
> MAX_SPRITEGROUP
|| _cur
.spritegroups
[groupid
] == nullptr) {
5152 GrfMsg(1, "GetGroupFromGroupID(0x{:02X}:0x{:02X}): Groupid 0x{:04X} does not exist, leaving empty", setid
, type
, groupid
);
5156 return _cur
.spritegroups
[groupid
];
5160 * Helper function to either create a callback or a result sprite group.
5161 * @param feature GrfSpecFeature to define spritegroup for.
5162 * @param setid SetID of the currently being parsed Action2. (only for debug output)
5163 * @param type Type of the currently being parsed Action2. (only for debug output)
5164 * @param spriteid Raw value from the GRF for the new spritegroup; describes either the return value or the referenced spritegroup.
5165 * @return Created spritegroup.
5167 static const SpriteGroup
*CreateGroupFromGroupID(byte feature
, byte setid
, byte type
, uint16_t spriteid
)
5169 if (HasBit(spriteid
, 15)) {
5170 assert(CallbackResultSpriteGroup::CanAllocateItem());
5171 return new CallbackResultSpriteGroup(spriteid
, _cur
.grffile
->grf_version
>= 8);
5174 if (!_cur
.IsValidSpriteSet(feature
, spriteid
)) {
5175 GrfMsg(1, "CreateGroupFromGroupID(0x{:02X}:0x{:02X}): Sprite set {} invalid", setid
, type
, spriteid
);
5179 SpriteID spriteset_start
= _cur
.GetSprite(feature
, spriteid
);
5180 uint num_sprites
= _cur
.GetNumEnts(feature
, spriteid
);
5182 /* Ensure that the sprites are loeded */
5183 assert(spriteset_start
+ num_sprites
<= _cur
.spriteid
);
5185 assert(ResultSpriteGroup::CanAllocateItem());
5186 return new ResultSpriteGroup(spriteset_start
, num_sprites
);
5190 static void NewSpriteGroup(ByteReader
*buf
)
5192 /* <02> <feature> <set-id> <type/num-entries> <feature-specific-data...>
5194 * B feature see action 1
5195 * B set-id ID of this particular definition
5196 * B type/num-entries
5197 * if 80 or greater, this is a randomized or variational
5198 * list definition, see below
5199 * otherwise it specifies a number of entries, the exact
5200 * meaning depends on the feature
5201 * V feature-specific-data (huge mess, don't even look it up --pasky) */
5202 const SpriteGroup
*act_group
= nullptr;
5204 uint8_t feature
= buf
->ReadByte();
5205 if (feature
>= GSF_END
) {
5206 GrfMsg(1, "NewSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature
);
5210 uint8_t setid
= buf
->ReadByte();
5211 uint8_t type
= buf
->ReadByte();
5213 /* Sprite Groups are created here but they are allocated from a pool, so
5214 * we do not need to delete anything if there is an exception from the
5218 /* Deterministic Sprite Group */
5219 case 0x81: // Self scope, byte
5220 case 0x82: // Parent scope, byte
5221 case 0x85: // Self scope, word
5222 case 0x86: // Parent scope, word
5223 case 0x89: // Self scope, dword
5224 case 0x8A: // Parent scope, dword
5229 assert(DeterministicSpriteGroup::CanAllocateItem());
5230 DeterministicSpriteGroup
*group
= new DeterministicSpriteGroup();
5231 group
->nfo_line
= _cur
.nfo_line
;
5233 group
->var_scope
= HasBit(type
, 1) ? VSG_SCOPE_PARENT
: VSG_SCOPE_SELF
;
5235 switch (GB(type
, 2, 2)) {
5236 default: NOT_REACHED();
5237 case 0: group
->size
= DSG_SIZE_BYTE
; varsize
= 1; break;
5238 case 1: group
->size
= DSG_SIZE_WORD
; varsize
= 2; break;
5239 case 2: group
->size
= DSG_SIZE_DWORD
; varsize
= 4; break;
5242 /* Loop through the var adjusts. Unfortunately we don't know how many we have
5243 * from the outset, so we shall have to keep reallocing. */
5245 DeterministicSpriteGroupAdjust
&adjust
= group
->adjusts
.emplace_back();
5247 /* The first var adjust doesn't have an operation specified, so we set it to add. */
5248 adjust
.operation
= group
->adjusts
.size() == 1 ? DSGA_OP_ADD
: (DeterministicSpriteGroupAdjustOperation
)buf
->ReadByte();
5249 adjust
.variable
= buf
->ReadByte();
5250 if (adjust
.variable
== 0x7E) {
5251 /* Link subroutine group */
5252 adjust
.subroutine
= GetGroupFromGroupID(setid
, type
, buf
->ReadByte());
5254 adjust
.parameter
= IsInsideMM(adjust
.variable
, 0x60, 0x80) ? buf
->ReadByte() : 0;
5257 varadjust
= buf
->ReadByte();
5258 adjust
.shift_num
= GB(varadjust
, 0, 5);
5259 adjust
.type
= (DeterministicSpriteGroupAdjustType
)GB(varadjust
, 6, 2);
5260 adjust
.and_mask
= buf
->ReadVarSize(varsize
);
5262 if (adjust
.type
!= DSGA_TYPE_NONE
) {
5263 adjust
.add_val
= buf
->ReadVarSize(varsize
);
5264 adjust
.divmod_val
= buf
->ReadVarSize(varsize
);
5267 adjust
.divmod_val
= 0;
5270 /* Continue reading var adjusts while bit 5 is set. */
5271 } while (HasBit(varadjust
, 5));
5273 std::vector
<DeterministicSpriteGroupRange
> ranges
;
5274 ranges
.resize(buf
->ReadByte());
5275 for (uint i
= 0; i
< ranges
.size(); i
++) {
5276 ranges
[i
].group
= GetGroupFromGroupID(setid
, type
, buf
->ReadWord());
5277 ranges
[i
].low
= buf
->ReadVarSize(varsize
);
5278 ranges
[i
].high
= buf
->ReadVarSize(varsize
);
5281 group
->default_group
= GetGroupFromGroupID(setid
, type
, buf
->ReadWord());
5282 group
->error_group
= ranges
.empty() ? group
->default_group
: ranges
[0].group
;
5283 /* nvar == 0 is a special case -- we turn our value into a callback result */
5284 group
->calculated_result
= ranges
.empty();
5286 /* Sort ranges ascending. When ranges overlap, this may required clamping or splitting them */
5287 std::vector
<uint32_t> bounds
;
5288 for (uint i
= 0; i
< ranges
.size(); i
++) {
5289 bounds
.push_back(ranges
[i
].low
);
5290 if (ranges
[i
].high
!= UINT32_MAX
) bounds
.push_back(ranges
[i
].high
+ 1);
5292 std::sort(bounds
.begin(), bounds
.end());
5293 bounds
.erase(std::unique(bounds
.begin(), bounds
.end()), bounds
.end());
5295 std::vector
<const SpriteGroup
*> target
;
5296 for (uint j
= 0; j
< bounds
.size(); ++j
) {
5297 uint32_t v
= bounds
[j
];
5298 const SpriteGroup
*t
= group
->default_group
;
5299 for (uint i
= 0; i
< ranges
.size(); i
++) {
5300 if (ranges
[i
].low
<= v
&& v
<= ranges
[i
].high
) {
5301 t
= ranges
[i
].group
;
5305 target
.push_back(t
);
5307 assert(target
.size() == bounds
.size());
5309 for (uint j
= 0; j
< bounds
.size(); ) {
5310 if (target
[j
] != group
->default_group
) {
5311 DeterministicSpriteGroupRange
&r
= group
->ranges
.emplace_back();
5312 r
.group
= target
[j
];
5314 while (j
< bounds
.size() && target
[j
] == r
.group
) {
5317 r
.high
= j
< bounds
.size() ? bounds
[j
] - 1 : UINT32_MAX
;
5326 /* Randomized Sprite Group */
5327 case 0x80: // Self scope
5328 case 0x83: // Parent scope
5329 case 0x84: // Relative scope
5331 assert(RandomizedSpriteGroup::CanAllocateItem());
5332 RandomizedSpriteGroup
*group
= new RandomizedSpriteGroup();
5333 group
->nfo_line
= _cur
.nfo_line
;
5335 group
->var_scope
= HasBit(type
, 1) ? VSG_SCOPE_PARENT
: VSG_SCOPE_SELF
;
5337 if (HasBit(type
, 2)) {
5338 if (feature
<= GSF_AIRCRAFT
) group
->var_scope
= VSG_SCOPE_RELATIVE
;
5339 group
->count
= buf
->ReadByte();
5342 uint8_t triggers
= buf
->ReadByte();
5343 group
->triggers
= GB(triggers
, 0, 7);
5344 group
->cmp_mode
= HasBit(triggers
, 7) ? RSG_CMP_ALL
: RSG_CMP_ANY
;
5345 group
->lowest_randbit
= buf
->ReadByte();
5347 byte num_groups
= buf
->ReadByte();
5348 if (!HasExactlyOneBit(num_groups
)) {
5349 GrfMsg(1, "NewSpriteGroup: Random Action 2 nrand should be power of 2");
5352 for (uint i
= 0; i
< num_groups
; i
++) {
5353 group
->groups
.push_back(GetGroupFromGroupID(setid
, type
, buf
->ReadWord()));
5359 /* Neither a variable or randomized sprite group... must be a real group */
5364 case GSF_ROADVEHICLES
:
5375 byte num_loaded
= type
;
5376 byte num_loading
= buf
->ReadByte();
5378 if (!_cur
.HasValidSpriteSets(feature
)) {
5379 GrfMsg(0, "NewSpriteGroup: No sprite set to work on! Skipping");
5383 GrfMsg(6, "NewSpriteGroup: New SpriteGroup 0x{:02X}, {} loaded, {} loading",
5384 setid
, num_loaded
, num_loading
);
5386 if (num_loaded
+ num_loading
== 0) {
5387 GrfMsg(1, "NewSpriteGroup: no result, skipping invalid RealSpriteGroup");
5391 if (num_loaded
+ num_loading
== 1) {
5392 /* Avoid creating 'Real' sprite group if only one option. */
5393 uint16_t spriteid
= buf
->ReadWord();
5394 act_group
= CreateGroupFromGroupID(feature
, setid
, type
, spriteid
);
5395 GrfMsg(8, "NewSpriteGroup: one result, skipping RealSpriteGroup = subset {}", spriteid
);
5399 std::vector
<uint16_t> loaded
;
5400 std::vector
<uint16_t> loading
;
5402 for (uint i
= 0; i
< num_loaded
; i
++) {
5403 loaded
.push_back(buf
->ReadWord());
5404 GrfMsg(8, "NewSpriteGroup: + rg->loaded[{}] = subset {}", i
, loaded
[i
]);
5407 for (uint i
= 0; i
< num_loading
; i
++) {
5408 loading
.push_back(buf
->ReadWord());
5409 GrfMsg(8, "NewSpriteGroup: + rg->loading[{}] = subset {}", i
, loading
[i
]);
5412 if (std::adjacent_find(loaded
.begin(), loaded
.end(), std::not_equal_to
<>()) == loaded
.end() &&
5413 std::adjacent_find(loading
.begin(), loading
.end(), std::not_equal_to
<>()) == loading
.end() &&
5414 loaded
[0] == loading
[0])
5416 /* Both lists only contain the same value, so don't create 'Real' sprite group */
5417 act_group
= CreateGroupFromGroupID(feature
, setid
, type
, loaded
[0]);
5418 GrfMsg(8, "NewSpriteGroup: same result, skipping RealSpriteGroup = subset {}", loaded
[0]);
5422 assert(RealSpriteGroup::CanAllocateItem());
5423 RealSpriteGroup
*group
= new RealSpriteGroup();
5424 group
->nfo_line
= _cur
.nfo_line
;
5427 for (uint16_t spriteid
: loaded
) {
5428 const SpriteGroup
*t
= CreateGroupFromGroupID(feature
, setid
, type
, spriteid
);
5429 group
->loaded
.push_back(t
);
5432 for (uint16_t spriteid
: loading
) {
5433 const SpriteGroup
*t
= CreateGroupFromGroupID(feature
, setid
, type
, spriteid
);
5434 group
->loading
.push_back(t
);
5441 case GSF_AIRPORTTILES
:
5443 case GSF_INDUSTRYTILES
:
5444 case GSF_ROADSTOPS
: {
5445 byte num_building_sprites
= std::max((uint8_t)1, type
);
5447 assert(TileLayoutSpriteGroup::CanAllocateItem());
5448 TileLayoutSpriteGroup
*group
= new TileLayoutSpriteGroup();
5449 group
->nfo_line
= _cur
.nfo_line
;
5452 /* On error, bail out immediately. Temporary GRF data was already freed */
5453 if (ReadSpriteLayout(buf
, num_building_sprites
, true, feature
, false, type
== 0, &group
->dts
)) return;
5457 case GSF_INDUSTRIES
: {
5459 GrfMsg(1, "NewSpriteGroup: Unsupported industry production version {}, skipping", type
);
5463 assert(IndustryProductionSpriteGroup::CanAllocateItem());
5464 IndustryProductionSpriteGroup
*group
= new IndustryProductionSpriteGroup();
5465 group
->nfo_line
= _cur
.nfo_line
;
5467 group
->version
= type
;
5469 group
->num_input
= 3;
5470 for (uint i
= 0; i
< 3; i
++) {
5471 group
->subtract_input
[i
] = (int16_t)buf
->ReadWord(); // signed
5473 group
->num_output
= 2;
5474 for (uint i
= 0; i
< 2; i
++) {
5475 group
->add_output
[i
] = buf
->ReadWord(); // unsigned
5477 group
->again
= buf
->ReadByte();
5478 } else if (type
== 1) {
5479 group
->num_input
= 3;
5480 for (uint i
= 0; i
< 3; i
++) {
5481 group
->subtract_input
[i
] = buf
->ReadByte();
5483 group
->num_output
= 2;
5484 for (uint i
= 0; i
< 2; i
++) {
5485 group
->add_output
[i
] = buf
->ReadByte();
5487 group
->again
= buf
->ReadByte();
5488 } else if (type
== 2) {
5489 group
->num_input
= buf
->ReadByte();
5490 if (group
->num_input
> lengthof(group
->subtract_input
)) {
5491 GRFError
*error
= DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK
);
5492 error
->data
= "too many inputs (max 16)";
5495 for (uint i
= 0; i
< group
->num_input
; i
++) {
5496 byte rawcargo
= buf
->ReadByte();
5497 CargoID cargo
= GetCargoTranslation(rawcargo
, _cur
.grffile
);
5498 if (!IsValidCargoID(cargo
)) {
5499 /* The mapped cargo is invalid. This is permitted at this point,
5500 * as long as the result is not used. Mark it invalid so this
5501 * can be tested later. */
5502 group
->version
= 0xFF;
5503 } else if (std::find(group
->cargo_input
, group
->cargo_input
+ i
, cargo
) != group
->cargo_input
+ i
) {
5504 GRFError
*error
= DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK
);
5505 error
->data
= "duplicate input cargo";
5508 group
->cargo_input
[i
] = cargo
;
5509 group
->subtract_input
[i
] = buf
->ReadByte();
5511 group
->num_output
= buf
->ReadByte();
5512 if (group
->num_output
> lengthof(group
->add_output
)) {
5513 GRFError
*error
= DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK
);
5514 error
->data
= "too many outputs (max 16)";
5517 for (uint i
= 0; i
< group
->num_output
; i
++) {
5518 byte rawcargo
= buf
->ReadByte();
5519 CargoID cargo
= GetCargoTranslation(rawcargo
, _cur
.grffile
);
5520 if (!IsValidCargoID(cargo
)) {
5521 /* Mark this result as invalid to use */
5522 group
->version
= 0xFF;
5523 } else if (std::find(group
->cargo_output
, group
->cargo_output
+ i
, cargo
) != group
->cargo_output
+ i
) {
5524 GRFError
*error
= DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK
);
5525 error
->data
= "duplicate output cargo";
5528 group
->cargo_output
[i
] = cargo
;
5529 group
->add_output
[i
] = buf
->ReadByte();
5531 group
->again
= buf
->ReadByte();
5538 /* Loading of Tile Layout and Production Callback groups would happen here */
5539 default: GrfMsg(1, "NewSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature
);
5544 _cur
.spritegroups
[setid
] = act_group
;
5547 static CargoID
TranslateCargo(uint8_t feature
, uint8_t ctype
)
5549 /* Special cargo types for purchase list and stations */
5550 if ((feature
== GSF_STATIONS
|| feature
== GSF_ROADSTOPS
) && ctype
== 0xFE) return SpriteGroupCargo::SG_DEFAULT_NA
;
5551 if (ctype
== 0xFF) return SpriteGroupCargo::SG_PURCHASE
;
5553 if (_cur
.grffile
->cargo_list
.empty()) {
5554 /* No cargo table, so use bitnum values */
5556 GrfMsg(1, "TranslateCargo: Cargo bitnum {} out of range (max 31), skipping.", ctype
);
5557 return INVALID_CARGO
;
5560 for (const CargoSpec
*cs
: CargoSpec::Iterate()) {
5561 if (cs
->bitnum
== ctype
) {
5562 GrfMsg(6, "TranslateCargo: Cargo bitnum {} mapped to cargo type {}.", ctype
, cs
->Index());
5567 GrfMsg(5, "TranslateCargo: Cargo bitnum {} not available in this climate, skipping.", ctype
);
5568 return INVALID_CARGO
;
5571 /* Check if the cargo type is out of bounds of the cargo translation table */
5572 if (ctype
>= _cur
.grffile
->cargo_list
.size()) {
5573 GrfMsg(1, "TranslateCargo: Cargo type {} out of range (max {}), skipping.", ctype
, (unsigned int)_cur
.grffile
->cargo_list
.size() - 1);
5574 return INVALID_CARGO
;
5577 /* Look up the cargo label from the translation table */
5578 CargoLabel cl
= _cur
.grffile
->cargo_list
[ctype
];
5579 if (cl
== CT_INVALID
) {
5580 GrfMsg(5, "TranslateCargo: Cargo type {} not available in this climate, skipping.", ctype
);
5581 return INVALID_CARGO
;
5584 CargoID cid
= GetCargoIDByLabel(cl
);
5585 if (!IsValidCargoID(cid
)) {
5586 GrfMsg(5, "TranslateCargo: Cargo '{:c}{:c}{:c}{:c}' unsupported, skipping.", GB(cl
.base(), 24, 8), GB(cl
.base(), 16, 8), GB(cl
.base(), 8, 8), GB(cl
.base(), 0, 8));
5587 return INVALID_CARGO
;
5590 GrfMsg(6, "TranslateCargo: Cargo '{:c}{:c}{:c}{:c}' mapped to cargo type {}.", GB(cl
.base(), 24, 8), GB(cl
.base(), 16, 8), GB(cl
.base(), 8, 8), GB(cl
.base(), 0, 8), cid
);
5595 static bool IsValidGroupID(uint16_t groupid
, const char *function
)
5597 if (groupid
> MAX_SPRITEGROUP
|| _cur
.spritegroups
[groupid
] == nullptr) {
5598 GrfMsg(1, "{}: Spritegroup 0x{:04X} out of range or empty, skipping.", function
, groupid
);
5605 static void VehicleMapSpriteGroup(ByteReader
*buf
, byte feature
, uint8_t idcount
)
5607 static EngineID
*last_engines
;
5608 static uint last_engines_count
;
5609 bool wagover
= false;
5611 /* Test for 'wagon override' flag */
5612 if (HasBit(idcount
, 7)) {
5614 /* Strip off the flag */
5615 idcount
= GB(idcount
, 0, 7);
5617 if (last_engines_count
== 0) {
5618 GrfMsg(0, "VehicleMapSpriteGroup: WagonOverride: No engine to do override with");
5622 GrfMsg(6, "VehicleMapSpriteGroup: WagonOverride: {} engines, {} wagons",
5623 last_engines_count
, idcount
);
5625 if (last_engines_count
!= idcount
) {
5626 last_engines
= ReallocT(last_engines
, idcount
);
5627 last_engines_count
= idcount
;
5631 std::vector
<EngineID
> engines
;
5632 for (uint i
= 0; i
< idcount
; i
++) {
5633 Engine
*e
= GetNewEngine(_cur
.grffile
, (VehicleType
)feature
, buf
->ReadExtendedByte());
5635 /* No engine could be allocated?!? Deal with it. Okay,
5636 * this might look bad. Also make sure this NewGRF
5637 * gets disabled, as a half loaded one is bad. */
5638 HandleChangeInfoResult("VehicleMapSpriteGroup", CIR_INVALID_ID
, 0, 0);
5642 engines
.push_back(e
->index
);
5643 if (!wagover
) last_engines
[i
] = engines
[i
];
5646 uint8_t cidcount
= buf
->ReadByte();
5647 for (uint c
= 0; c
< cidcount
; c
++) {
5648 uint8_t ctype
= buf
->ReadByte();
5649 uint16_t groupid
= buf
->ReadWord();
5650 if (!IsValidGroupID(groupid
, "VehicleMapSpriteGroup")) continue;
5652 GrfMsg(8, "VehicleMapSpriteGroup: * [{}] Cargo type 0x{:X}, group id 0x{:02X}", c
, ctype
, groupid
);
5654 CargoID cid
= TranslateCargo(feature
, ctype
);
5655 if (!IsValidCargoID(cid
)) continue;
5657 for (uint i
= 0; i
< idcount
; i
++) {
5658 EngineID engine
= engines
[i
];
5660 GrfMsg(7, "VehicleMapSpriteGroup: [{}] Engine {}...", i
, engine
);
5663 SetWagonOverrideSprites(engine
, cid
, _cur
.spritegroups
[groupid
], last_engines
, last_engines_count
);
5665 SetCustomEngineSprites(engine
, cid
, _cur
.spritegroups
[groupid
]);
5670 uint16_t groupid
= buf
->ReadWord();
5671 if (!IsValidGroupID(groupid
, "VehicleMapSpriteGroup")) return;
5673 GrfMsg(8, "-- Default group id 0x{:04X}", groupid
);
5675 for (uint i
= 0; i
< idcount
; i
++) {
5676 EngineID engine
= engines
[i
];
5679 SetWagonOverrideSprites(engine
, SpriteGroupCargo::SG_DEFAULT
, _cur
.spritegroups
[groupid
], last_engines
, last_engines_count
);
5681 SetCustomEngineSprites(engine
, SpriteGroupCargo::SG_DEFAULT
, _cur
.spritegroups
[groupid
]);
5682 SetEngineGRF(engine
, _cur
.grffile
);
5688 static void CanalMapSpriteGroup(ByteReader
*buf
, uint8_t idcount
)
5690 std::vector
<uint16_t> cfs
;
5691 cfs
.reserve(idcount
);
5692 for (uint i
= 0; i
< idcount
; i
++) {
5693 cfs
.push_back(buf
->ReadExtendedByte());
5696 uint8_t cidcount
= buf
->ReadByte();
5697 buf
->Skip(cidcount
* 3);
5699 uint16_t groupid
= buf
->ReadWord();
5700 if (!IsValidGroupID(groupid
, "CanalMapSpriteGroup")) return;
5702 for (auto &cf
: cfs
) {
5704 GrfMsg(1, "CanalMapSpriteGroup: Canal subset {} out of range, skipping", cf
);
5708 _water_feature
[cf
].grffile
= _cur
.grffile
;
5709 _water_feature
[cf
].group
= _cur
.spritegroups
[groupid
];
5714 static void StationMapSpriteGroup(ByteReader
*buf
, uint8_t idcount
)
5716 if (_cur
.grffile
->stations
.empty()) {
5717 GrfMsg(1, "StationMapSpriteGroup: No stations defined, skipping");
5721 std::vector
<uint16_t> stations
;
5722 stations
.reserve(idcount
);
5723 for (uint i
= 0; i
< idcount
; i
++) {
5724 stations
.push_back(buf
->ReadExtendedByte());
5727 uint8_t cidcount
= buf
->ReadByte();
5728 for (uint c
= 0; c
< cidcount
; c
++) {
5729 uint8_t ctype
= buf
->ReadByte();
5730 uint16_t groupid
= buf
->ReadWord();
5731 if (!IsValidGroupID(groupid
, "StationMapSpriteGroup")) continue;
5733 ctype
= TranslateCargo(GSF_STATIONS
, ctype
);
5734 if (!IsValidCargoID(ctype
)) continue;
5736 for (auto &station
: stations
) {
5737 StationSpec
*statspec
= station
>= _cur
.grffile
->stations
.size() ? nullptr : _cur
.grffile
->stations
[station
].get();
5739 if (statspec
== nullptr) {
5740 GrfMsg(1, "StationMapSpriteGroup: Station {} undefined, skipping", station
);
5744 statspec
->grf_prop
.spritegroup
[ctype
] = _cur
.spritegroups
[groupid
];
5748 uint16_t groupid
= buf
->ReadWord();
5749 if (!IsValidGroupID(groupid
, "StationMapSpriteGroup")) return;
5751 for (auto &station
: stations
) {
5752 StationSpec
*statspec
= station
>= _cur
.grffile
->stations
.size() ? nullptr : _cur
.grffile
->stations
[station
].get();
5754 if (statspec
== nullptr) {
5755 GrfMsg(1, "StationMapSpriteGroup: Station {} undefined, skipping", station
);
5759 if (statspec
->grf_prop
.grffile
!= nullptr) {
5760 GrfMsg(1, "StationMapSpriteGroup: Station {} mapped multiple times, skipping", station
);
5764 statspec
->grf_prop
.spritegroup
[SpriteGroupCargo::SG_DEFAULT
] = _cur
.spritegroups
[groupid
];
5765 statspec
->grf_prop
.grffile
= _cur
.grffile
;
5766 statspec
->grf_prop
.local_id
= station
;
5767 StationClass::Assign(statspec
);
5772 static void TownHouseMapSpriteGroup(ByteReader
*buf
, uint8_t idcount
)
5774 if (_cur
.grffile
->housespec
.empty()) {
5775 GrfMsg(1, "TownHouseMapSpriteGroup: No houses defined, skipping");
5779 std::vector
<uint16_t> houses
;
5780 houses
.reserve(idcount
);
5781 for (uint i
= 0; i
< idcount
; i
++) {
5782 houses
.push_back(buf
->ReadExtendedByte());
5785 /* Skip the cargo type section, we only care about the default group */
5786 uint8_t cidcount
= buf
->ReadByte();
5787 buf
->Skip(cidcount
* 3);
5789 uint16_t groupid
= buf
->ReadWord();
5790 if (!IsValidGroupID(groupid
, "TownHouseMapSpriteGroup")) return;
5792 for (auto &house
: houses
) {
5793 HouseSpec
*hs
= house
>= _cur
.grffile
->housespec
.size() ? nullptr : _cur
.grffile
->housespec
[house
].get();
5795 if (hs
== nullptr) {
5796 GrfMsg(1, "TownHouseMapSpriteGroup: House {} undefined, skipping.", house
);
5800 hs
->grf_prop
.spritegroup
[0] = _cur
.spritegroups
[groupid
];
5804 static void IndustryMapSpriteGroup(ByteReader
*buf
, uint8_t idcount
)
5806 if (_cur
.grffile
->industryspec
.empty()) {
5807 GrfMsg(1, "IndustryMapSpriteGroup: No industries defined, skipping");
5811 std::vector
<uint16_t> industries
;
5812 industries
.reserve(idcount
);
5813 for (uint i
= 0; i
< idcount
; i
++) {
5814 industries
.push_back(buf
->ReadExtendedByte());
5817 /* Skip the cargo type section, we only care about the default group */
5818 uint8_t cidcount
= buf
->ReadByte();
5819 buf
->Skip(cidcount
* 3);
5821 uint16_t groupid
= buf
->ReadWord();
5822 if (!IsValidGroupID(groupid
, "IndustryMapSpriteGroup")) return;
5824 for (auto &industry
: industries
) {
5825 IndustrySpec
*indsp
= industry
>= _cur
.grffile
->industryspec
.size() ? nullptr : _cur
.grffile
->industryspec
[industry
].get();
5827 if (indsp
== nullptr) {
5828 GrfMsg(1, "IndustryMapSpriteGroup: Industry {} undefined, skipping", industry
);
5832 indsp
->grf_prop
.spritegroup
[0] = _cur
.spritegroups
[groupid
];
5836 static void IndustrytileMapSpriteGroup(ByteReader
*buf
, uint8_t idcount
)
5838 if (_cur
.grffile
->indtspec
.empty()) {
5839 GrfMsg(1, "IndustrytileMapSpriteGroup: No industry tiles defined, skipping");
5843 std::vector
<uint16_t> indtiles
;
5844 indtiles
.reserve(idcount
);
5845 for (uint i
= 0; i
< idcount
; i
++) {
5846 indtiles
.push_back(buf
->ReadExtendedByte());
5849 /* Skip the cargo type section, we only care about the default group */
5850 uint8_t cidcount
= buf
->ReadByte();
5851 buf
->Skip(cidcount
* 3);
5853 uint16_t groupid
= buf
->ReadWord();
5854 if (!IsValidGroupID(groupid
, "IndustrytileMapSpriteGroup")) return;
5856 for (auto &indtile
: indtiles
) {
5857 IndustryTileSpec
*indtsp
= indtile
>= _cur
.grffile
->indtspec
.size() ? nullptr : _cur
.grffile
->indtspec
[indtile
].get();
5859 if (indtsp
== nullptr) {
5860 GrfMsg(1, "IndustrytileMapSpriteGroup: Industry tile {} undefined, skipping", indtile
);
5864 indtsp
->grf_prop
.spritegroup
[0] = _cur
.spritegroups
[groupid
];
5868 static void CargoMapSpriteGroup(ByteReader
*buf
, uint8_t idcount
)
5870 std::vector
<uint16_t> cargoes
;
5871 cargoes
.reserve(idcount
);
5872 for (uint i
= 0; i
< idcount
; i
++) {
5873 cargoes
.push_back(buf
->ReadExtendedByte());
5876 /* Skip the cargo type section, we only care about the default group */
5877 uint8_t cidcount
= buf
->ReadByte();
5878 buf
->Skip(cidcount
* 3);
5880 uint16_t groupid
= buf
->ReadWord();
5881 if (!IsValidGroupID(groupid
, "CargoMapSpriteGroup")) return;
5883 for (auto &cid
: cargoes
) {
5884 if (cid
>= NUM_CARGO
) {
5885 GrfMsg(1, "CargoMapSpriteGroup: Cargo ID {} out of range, skipping", cid
);
5889 CargoSpec
*cs
= CargoSpec::Get(cid
);
5890 cs
->grffile
= _cur
.grffile
;
5891 cs
->group
= _cur
.spritegroups
[groupid
];
5895 static void ObjectMapSpriteGroup(ByteReader
*buf
, uint8_t idcount
)
5897 if (_cur
.grffile
->objectspec
.empty()) {
5898 GrfMsg(1, "ObjectMapSpriteGroup: No object tiles defined, skipping");
5902 std::vector
<uint16_t> objects
;
5903 objects
.reserve(idcount
);
5904 for (uint i
= 0; i
< idcount
; i
++) {
5905 objects
.push_back(buf
->ReadExtendedByte());
5908 uint8_t cidcount
= buf
->ReadByte();
5909 for (uint c
= 0; c
< cidcount
; c
++) {
5910 uint8_t ctype
= buf
->ReadByte();
5911 uint16_t groupid
= buf
->ReadWord();
5912 if (!IsValidGroupID(groupid
, "ObjectMapSpriteGroup")) continue;
5914 /* The only valid option here is purchase list sprite groups. */
5915 if (ctype
!= 0xFF) {
5916 GrfMsg(1, "ObjectMapSpriteGroup: Invalid cargo bitnum {} for objects, skipping.", ctype
);
5920 for (auto &object
: objects
) {
5921 ObjectSpec
*spec
= object
>= _cur
.grffile
->objectspec
.size() ? nullptr : _cur
.grffile
->objectspec
[object
].get();
5923 if (spec
== nullptr) {
5924 GrfMsg(1, "ObjectMapSpriteGroup: Object {} undefined, skipping", object
);
5928 spec
->grf_prop
.spritegroup
[OBJECT_SPRITE_GROUP_PURCHASE
] = _cur
.spritegroups
[groupid
];
5932 uint16_t groupid
= buf
->ReadWord();
5933 if (!IsValidGroupID(groupid
, "ObjectMapSpriteGroup")) return;
5935 for (auto &object
: objects
) {
5936 ObjectSpec
*spec
= object
>= _cur
.grffile
->objectspec
.size() ? nullptr : _cur
.grffile
->objectspec
[object
].get();
5938 if (spec
== nullptr) {
5939 GrfMsg(1, "ObjectMapSpriteGroup: Object {} undefined, skipping", object
);
5943 if (spec
->grf_prop
.grffile
!= nullptr) {
5944 GrfMsg(1, "ObjectMapSpriteGroup: Object {} mapped multiple times, skipping", object
);
5948 spec
->grf_prop
.spritegroup
[OBJECT_SPRITE_GROUP_DEFAULT
] = _cur
.spritegroups
[groupid
];
5949 spec
->grf_prop
.grffile
= _cur
.grffile
;
5950 spec
->grf_prop
.local_id
= object
;
5954 static void RailTypeMapSpriteGroup(ByteReader
*buf
, uint8_t idcount
)
5956 std::vector
<uint8_t> railtypes
;
5957 railtypes
.reserve(idcount
);
5958 for (uint i
= 0; i
< idcount
; i
++) {
5959 uint16_t id
= buf
->ReadExtendedByte();
5960 railtypes
.push_back(id
< RAILTYPE_END
? _cur
.grffile
->railtype_map
[id
] : INVALID_RAILTYPE
);
5963 uint8_t cidcount
= buf
->ReadByte();
5964 for (uint c
= 0; c
< cidcount
; c
++) {
5965 uint8_t ctype
= buf
->ReadByte();
5966 uint16_t groupid
= buf
->ReadWord();
5967 if (!IsValidGroupID(groupid
, "RailTypeMapSpriteGroup")) continue;
5969 if (ctype
>= RTSG_END
) continue;
5971 extern RailTypeInfo _railtypes
[RAILTYPE_END
];
5972 for (auto &railtype
: railtypes
) {
5973 if (railtype
!= INVALID_RAILTYPE
) {
5974 RailTypeInfo
*rti
= &_railtypes
[railtype
];
5976 rti
->grffile
[ctype
] = _cur
.grffile
;
5977 rti
->group
[ctype
] = _cur
.spritegroups
[groupid
];
5982 /* Railtypes do not use the default group. */
5986 static void RoadTypeMapSpriteGroup(ByteReader
*buf
, uint8_t idcount
, RoadTramType rtt
)
5988 RoadType
*type_map
= (rtt
== RTT_TRAM
) ? _cur
.grffile
->tramtype_map
: _cur
.grffile
->roadtype_map
;
5990 std::vector
<uint8_t> roadtypes
;
5991 roadtypes
.reserve(idcount
);
5992 for (uint i
= 0; i
< idcount
; i
++) {
5993 uint16_t id
= buf
->ReadExtendedByte();
5994 roadtypes
.push_back(id
< ROADTYPE_END
? type_map
[id
] : INVALID_ROADTYPE
);
5997 uint8_t cidcount
= buf
->ReadByte();
5998 for (uint c
= 0; c
< cidcount
; c
++) {
5999 uint8_t ctype
= buf
->ReadByte();
6000 uint16_t groupid
= buf
->ReadWord();
6001 if (!IsValidGroupID(groupid
, "RoadTypeMapSpriteGroup")) continue;
6003 if (ctype
>= ROTSG_END
) continue;
6005 extern RoadTypeInfo _roadtypes
[ROADTYPE_END
];
6006 for (auto &roadtype
: roadtypes
) {
6007 if (roadtype
!= INVALID_ROADTYPE
) {
6008 RoadTypeInfo
*rti
= &_roadtypes
[roadtype
];
6010 rti
->grffile
[ctype
] = _cur
.grffile
;
6011 rti
->group
[ctype
] = _cur
.spritegroups
[groupid
];
6016 /* Roadtypes do not use the default group. */
6020 static void AirportMapSpriteGroup(ByteReader
*buf
, uint8_t idcount
)
6022 if (_cur
.grffile
->airportspec
.empty()) {
6023 GrfMsg(1, "AirportMapSpriteGroup: No airports defined, skipping");
6027 std::vector
<uint16_t> airports
;
6028 airports
.reserve(idcount
);
6029 for (uint i
= 0; i
< idcount
; i
++) {
6030 airports
.push_back(buf
->ReadExtendedByte());
6033 /* Skip the cargo type section, we only care about the default group */
6034 uint8_t cidcount
= buf
->ReadByte();
6035 buf
->Skip(cidcount
* 3);
6037 uint16_t groupid
= buf
->ReadWord();
6038 if (!IsValidGroupID(groupid
, "AirportMapSpriteGroup")) return;
6040 for (auto &airport
: airports
) {
6041 AirportSpec
*as
= airport
>= _cur
.grffile
->airportspec
.size() ? nullptr : _cur
.grffile
->airportspec
[airport
].get();
6043 if (as
== nullptr) {
6044 GrfMsg(1, "AirportMapSpriteGroup: Airport {} undefined, skipping", airport
);
6048 as
->grf_prop
.spritegroup
[0] = _cur
.spritegroups
[groupid
];
6052 static void AirportTileMapSpriteGroup(ByteReader
*buf
, uint8_t idcount
)
6054 if (_cur
.grffile
->airtspec
.empty()) {
6055 GrfMsg(1, "AirportTileMapSpriteGroup: No airport tiles defined, skipping");
6059 std::vector
<uint16_t> airptiles
;
6060 airptiles
.reserve(idcount
);
6061 for (uint i
= 0; i
< idcount
; i
++) {
6062 airptiles
.push_back(buf
->ReadExtendedByte());
6065 /* Skip the cargo type section, we only care about the default group */
6066 uint8_t cidcount
= buf
->ReadByte();
6067 buf
->Skip(cidcount
* 3);
6069 uint16_t groupid
= buf
->ReadWord();
6070 if (!IsValidGroupID(groupid
, "AirportTileMapSpriteGroup")) return;
6072 for (auto &airptile
: airptiles
) {
6073 AirportTileSpec
*airtsp
= airptile
>= _cur
.grffile
->airtspec
.size() ? nullptr : _cur
.grffile
->airtspec
[airptile
].get();
6075 if (airtsp
== nullptr) {
6076 GrfMsg(1, "AirportTileMapSpriteGroup: Airport tile {} undefined, skipping", airptile
);
6080 airtsp
->grf_prop
.spritegroup
[0] = _cur
.spritegroups
[groupid
];
6084 static void RoadStopMapSpriteGroup(ByteReader
*buf
, uint8_t idcount
)
6086 if (_cur
.grffile
->roadstops
.empty()) {
6087 GrfMsg(1, "RoadStopMapSpriteGroup: No roadstops defined, skipping");
6091 std::vector
<uint16_t> roadstops
;
6092 roadstops
.reserve(idcount
);
6093 for (uint i
= 0; i
< idcount
; i
++) {
6094 roadstops
.push_back(buf
->ReadExtendedByte());
6097 uint8_t cidcount
= buf
->ReadByte();
6098 for (uint c
= 0; c
< cidcount
; c
++) {
6099 uint8_t ctype
= buf
->ReadByte();
6100 uint16_t groupid
= buf
->ReadWord();
6101 if (!IsValidGroupID(groupid
, "RoadStopMapSpriteGroup")) continue;
6103 ctype
= TranslateCargo(GSF_ROADSTOPS
, ctype
);
6104 if (!IsValidCargoID(ctype
)) continue;
6106 for (auto &roadstop
: roadstops
) {
6107 RoadStopSpec
*roadstopspec
= roadstop
>= _cur
.grffile
->roadstops
.size() ? nullptr : _cur
.grffile
->roadstops
[roadstop
].get();
6109 if (roadstopspec
== nullptr) {
6110 GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} undefined, skipping", roadstop
);
6114 roadstopspec
->grf_prop
.spritegroup
[ctype
] = _cur
.spritegroups
[groupid
];
6118 uint16_t groupid
= buf
->ReadWord();
6119 if (!IsValidGroupID(groupid
, "RoadStopMapSpriteGroup")) return;
6121 for (auto &roadstop
: roadstops
) {
6122 RoadStopSpec
*roadstopspec
= roadstop
>= _cur
.grffile
->roadstops
.size() ? nullptr : _cur
.grffile
->roadstops
[roadstop
].get();
6124 if (roadstopspec
== nullptr) {
6125 GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} undefined, skipping.", roadstop
);
6129 if (roadstopspec
->grf_prop
.grffile
!= nullptr) {
6130 GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} mapped multiple times, skipping", roadstop
);
6134 roadstopspec
->grf_prop
.spritegroup
[SpriteGroupCargo::SG_DEFAULT
] = _cur
.spritegroups
[groupid
];
6135 roadstopspec
->grf_prop
.grffile
= _cur
.grffile
;
6136 roadstopspec
->grf_prop
.local_id
= roadstop
;
6137 RoadStopClass::Assign(roadstopspec
);
6142 static void FeatureMapSpriteGroup(ByteReader
*buf
)
6144 /* <03> <feature> <n-id> <ids>... <num-cid> [<cargo-type> <cid>]... <def-cid>
6145 * id-list := [<id>] [id-list]
6146 * cargo-list := <cargo-type> <cid> [cargo-list]
6148 * B feature see action 0
6149 * B n-id bits 0-6: how many IDs this definition applies to
6150 * bit 7: if set, this is a wagon override definition (see below)
6151 * E ids the IDs for which this definition applies
6152 * B num-cid number of cargo IDs (sprite group IDs) in this definition
6153 * can be zero, in that case the def-cid is used always
6154 * B cargo-type type of this cargo type (e.g. mail=2, wood=7, see below)
6155 * W cid cargo ID (sprite group ID) for this type of cargo
6156 * W def-cid default cargo ID (sprite group ID) */
6158 uint8_t feature
= buf
->ReadByte();
6159 uint8_t idcount
= buf
->ReadByte();
6161 if (feature
>= GSF_END
) {
6162 GrfMsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature
);
6166 /* If idcount is zero, this is a feature callback */
6168 /* Skip number of cargo ids? */
6170 uint16_t groupid
= buf
->ReadWord();
6171 if (!IsValidGroupID(groupid
, "FeatureMapSpriteGroup")) return;
6173 GrfMsg(6, "FeatureMapSpriteGroup: Adding generic feature callback for feature 0x{:02X}", feature
);
6175 AddGenericCallback(feature
, _cur
.grffile
, _cur
.spritegroups
[groupid
]);
6179 /* Mark the feature as used by the grf (generic callbacks do not count) */
6180 SetBit(_cur
.grffile
->grf_features
, feature
);
6182 GrfMsg(6, "FeatureMapSpriteGroup: Feature 0x{:02X}, {} ids", feature
, idcount
);
6186 case GSF_ROADVEHICLES
:
6189 VehicleMapSpriteGroup(buf
, feature
, idcount
);
6193 CanalMapSpriteGroup(buf
, idcount
);
6197 StationMapSpriteGroup(buf
, idcount
);
6201 TownHouseMapSpriteGroup(buf
, idcount
);
6204 case GSF_INDUSTRIES
:
6205 IndustryMapSpriteGroup(buf
, idcount
);
6208 case GSF_INDUSTRYTILES
:
6209 IndustrytileMapSpriteGroup(buf
, idcount
);
6213 CargoMapSpriteGroup(buf
, idcount
);
6217 AirportMapSpriteGroup(buf
, idcount
);
6221 ObjectMapSpriteGroup(buf
, idcount
);
6225 RailTypeMapSpriteGroup(buf
, idcount
);
6229 RoadTypeMapSpriteGroup(buf
, idcount
, RTT_ROAD
);
6233 RoadTypeMapSpriteGroup(buf
, idcount
, RTT_TRAM
);
6236 case GSF_AIRPORTTILES
:
6237 AirportTileMapSpriteGroup(buf
, idcount
);
6241 RoadStopMapSpriteGroup(buf
, idcount
);
6245 GrfMsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature
);
6251 static void FeatureNewName(ByteReader
*buf
)
6253 /* <04> <veh-type> <language-id> <num-veh> <offset> <data...>
6255 * B veh-type see action 0 (as 00..07, + 0A
6256 * But IF veh-type = 48, then generic text
6257 * B language-id If bit 6 is set, This is the extended language scheme,
6258 * with up to 64 language.
6259 * Otherwise, it is a mapping where set bits have meaning
6260 * 0 = american, 1 = english, 2 = german, 3 = french, 4 = spanish
6261 * Bit 7 set means this is a generic text, not a vehicle one (or else)
6262 * B num-veh number of vehicles which are getting a new name
6263 * B/W offset number of the first vehicle that gets a new name
6264 * Byte : ID of vehicle to change
6265 * Word : ID of string to change/add
6266 * S data new texts, each of them zero-terminated, after
6267 * which the next name begins. */
6269 bool new_scheme
= _cur
.grffile
->grf_version
>= 7;
6271 uint8_t feature
= buf
->ReadByte();
6272 if (feature
>= GSF_END
&& feature
!= 0x48) {
6273 GrfMsg(1, "FeatureNewName: Unsupported feature 0x{:02X}, skipping", feature
);
6277 uint8_t lang
= buf
->ReadByte();
6278 uint8_t num
= buf
->ReadByte();
6279 bool generic
= HasBit(lang
, 7);
6282 id
= buf
->ReadWord();
6283 } else if (feature
<= GSF_AIRCRAFT
) {
6284 id
= buf
->ReadExtendedByte();
6286 id
= buf
->ReadByte();
6291 uint16_t endid
= id
+ num
;
6293 GrfMsg(6, "FeatureNewName: About to rename engines {}..{} (feature 0x{:02X}) in language 0x{:02X}",
6294 id
, endid
, feature
, lang
);
6296 for (; id
< endid
&& buf
->HasData(); id
++) {
6297 const char *name
= buf
->ReadString();
6298 GrfMsg(8, "FeatureNewName: 0x{:04X} <- {}", id
, name
);
6302 case GSF_ROADVEHICLES
:
6306 Engine
*e
= GetNewEngine(_cur
.grffile
, (VehicleType
)feature
, id
, HasBit(_cur
.grfconfig
->flags
, GCF_STATIC
));
6307 if (e
== nullptr) break;
6308 StringID string
= AddGRFString(_cur
.grffile
->grfid
, e
->index
, lang
, new_scheme
, false, name
, e
->info
.string_id
);
6309 e
->info
.string_id
= string
;
6311 AddGRFString(_cur
.grffile
->grfid
, id
, lang
, new_scheme
, true, name
, STR_UNDEFINED
);
6316 if (IsInsideMM(id
, 0xD000, 0xD400) || IsInsideMM(id
, 0xD800, 0x10000)) {
6317 AddGRFString(_cur
.grffile
->grfid
, id
, lang
, new_scheme
, true, name
, STR_UNDEFINED
);
6321 switch (GB(id
, 8, 8)) {
6322 case 0xC4: // Station class name
6323 if (GB(id
, 0, 8) >= _cur
.grffile
->stations
.size() || _cur
.grffile
->stations
[GB(id
, 0, 8)] == nullptr) {
6324 GrfMsg(1, "FeatureNewName: Attempt to name undefined station 0x{:X}, ignoring", GB(id
, 0, 8));
6326 StationClassID cls_id
= _cur
.grffile
->stations
[GB(id
, 0, 8)]->cls_id
;
6327 StationClass::Get(cls_id
)->name
= AddGRFString(_cur
.grffile
->grfid
, id
, lang
, new_scheme
, false, name
, STR_UNDEFINED
);
6331 case 0xC5: // Station name
6332 if (GB(id
, 0, 8) >= _cur
.grffile
->stations
.size() || _cur
.grffile
->stations
[GB(id
, 0, 8)] == nullptr) {
6333 GrfMsg(1, "FeatureNewName: Attempt to name undefined station 0x{:X}, ignoring", GB(id
, 0, 8));
6335 _cur
.grffile
->stations
[GB(id
, 0, 8)]->name
= AddGRFString(_cur
.grffile
->grfid
, id
, lang
, new_scheme
, false, name
, STR_UNDEFINED
);
6339 case 0xC7: // Airporttile name
6340 if (GB(id
, 0, 8) >= _cur
.grffile
->airtspec
.size() || _cur
.grffile
->airtspec
[GB(id
, 0, 8)] == nullptr) {
6341 GrfMsg(1, "FeatureNewName: Attempt to name undefined airport tile 0x{:X}, ignoring", GB(id
, 0, 8));
6343 _cur
.grffile
->airtspec
[GB(id
, 0, 8)]->name
= AddGRFString(_cur
.grffile
->grfid
, id
, lang
, new_scheme
, false, name
, STR_UNDEFINED
);
6347 case 0xC9: // House name
6348 if (GB(id
, 0, 8) >= _cur
.grffile
->housespec
.size() || _cur
.grffile
->housespec
[GB(id
, 0, 8)] == nullptr) {
6349 GrfMsg(1, "FeatureNewName: Attempt to name undefined house 0x{:X}, ignoring.", GB(id
, 0, 8));
6351 _cur
.grffile
->housespec
[GB(id
, 0, 8)]->building_name
= AddGRFString(_cur
.grffile
->grfid
, id
, lang
, new_scheme
, false, name
, STR_UNDEFINED
);
6356 GrfMsg(7, "FeatureNewName: Unsupported ID (0x{:04X})", id
);
6365 * Sanitize incoming sprite offsets for Action 5 graphics replacements.
6366 * @param num The number of sprites to load.
6367 * @param offset Offset from the base.
6368 * @param max_sprites The maximum number of sprites that can be loaded in this action 5.
6369 * @param name Used for error warnings.
6370 * @return The number of sprites that is going to be skipped.
6372 static uint16_t SanitizeSpriteOffset(uint16_t &num
, uint16_t offset
, int max_sprites
, const char *name
)
6375 if (offset
>= max_sprites
) {
6376 GrfMsg(1, "GraphicsNew: {} sprite offset must be less than {}, skipping", name
, max_sprites
);
6377 uint orig_num
= num
;
6382 if (offset
+ num
> max_sprites
) {
6383 GrfMsg(4, "GraphicsNew: {} sprite overflow, truncating...", name
);
6384 uint orig_num
= num
;
6385 num
= std::max(max_sprites
- offset
, 0);
6386 return orig_num
- num
;
6393 /** The type of action 5 type. */
6394 enum Action5BlockType
{
6395 A5BLOCK_FIXED
, ///< Only allow replacing a whole block of sprites. (TTDP compatible)
6396 A5BLOCK_ALLOW_OFFSET
, ///< Allow replacing any subset by specifiing an offset.
6397 A5BLOCK_INVALID
, ///< unknown/not-implemented type
6399 /** Information about a single action 5 type. */
6400 struct Action5Type
{
6401 Action5BlockType block_type
; ///< How is this Action5 type processed?
6402 SpriteID sprite_base
; ///< Load the sprites starting from this sprite.
6403 uint16_t min_sprites
; ///< If the Action5 contains less sprites, the whole block will be ignored.
6404 uint16_t max_sprites
; ///< If the Action5 contains more sprites, only the first max_sprites sprites will be used.
6405 const char *name
; ///< Name for error messages.
6408 /** The information about action 5 types. */
6409 static const Action5Type _action5_types
[] = {
6410 /* Note: min_sprites should not be changed. Therefore these constants are directly here and not in sprites.h */
6411 /* 0x00 */ { A5BLOCK_INVALID
, 0, 0, 0, "Type 0x00" },
6412 /* 0x01 */ { A5BLOCK_INVALID
, 0, 0, 0, "Type 0x01" },
6413 /* 0x02 */ { A5BLOCK_INVALID
, 0, 0, 0, "Type 0x02" },
6414 /* 0x03 */ { A5BLOCK_INVALID
, 0, 0, 0, "Type 0x03" },
6415 /* 0x04 */ { A5BLOCK_ALLOW_OFFSET
, SPR_SIGNALS_BASE
, 1, PRESIGNAL_SEMAPHORE_AND_PBS_SPRITE_COUNT
, "Signal graphics" },
6416 /* 0x05 */ { A5BLOCK_ALLOW_OFFSET
, SPR_ELRAIL_BASE
, 1, ELRAIL_SPRITE_COUNT
, "Rail catenary graphics" },
6417 /* 0x06 */ { A5BLOCK_ALLOW_OFFSET
, SPR_SLOPES_BASE
, 1, NORMAL_AND_HALFTILE_FOUNDATION_SPRITE_COUNT
, "Foundation graphics" },
6418 /* 0x07 */ { A5BLOCK_INVALID
, 0, 75, 0, "TTDP GUI graphics" }, // Not used by OTTD.
6419 /* 0x08 */ { A5BLOCK_ALLOW_OFFSET
, SPR_CANALS_BASE
, 1, CANALS_SPRITE_COUNT
, "Canal graphics" },
6420 /* 0x09 */ { A5BLOCK_ALLOW_OFFSET
, SPR_ONEWAY_BASE
, 1, ONEWAY_SPRITE_COUNT
, "One way road graphics" },
6421 /* 0x0A */ { A5BLOCK_ALLOW_OFFSET
, SPR_2CCMAP_BASE
, 1, TWOCCMAP_SPRITE_COUNT
, "2CC colour maps" },
6422 /* 0x0B */ { A5BLOCK_ALLOW_OFFSET
, SPR_TRAMWAY_BASE
, 1, TRAMWAY_SPRITE_COUNT
, "Tramway graphics" },
6423 /* 0x0C */ { A5BLOCK_INVALID
, 0, 133, 0, "Snowy temperate tree" }, // Not yet used by OTTD.
6424 /* 0x0D */ { A5BLOCK_FIXED
, SPR_SHORE_BASE
, 16, SPR_SHORE_SPRITE_COUNT
, "Shore graphics" },
6425 /* 0x0E */ { A5BLOCK_INVALID
, 0, 0, 0, "New Signals graphics" }, // Not yet used by OTTD.
6426 /* 0x0F */ { A5BLOCK_ALLOW_OFFSET
, SPR_TRACKS_FOR_SLOPES_BASE
, 1, TRACKS_FOR_SLOPES_SPRITE_COUNT
, "Sloped rail track" },
6427 /* 0x10 */ { A5BLOCK_ALLOW_OFFSET
, SPR_AIRPORTX_BASE
, 1, AIRPORTX_SPRITE_COUNT
, "Airport graphics" },
6428 /* 0x11 */ { A5BLOCK_ALLOW_OFFSET
, SPR_ROADSTOP_BASE
, 1, ROADSTOP_SPRITE_COUNT
, "Road stop graphics" },
6429 /* 0x12 */ { A5BLOCK_ALLOW_OFFSET
, SPR_AQUEDUCT_BASE
, 1, AQUEDUCT_SPRITE_COUNT
, "Aqueduct graphics" },
6430 /* 0x13 */ { A5BLOCK_ALLOW_OFFSET
, SPR_AUTORAIL_BASE
, 1, AUTORAIL_SPRITE_COUNT
, "Autorail graphics" },
6431 /* 0x14 */ { A5BLOCK_INVALID
, 0, 1, 0, "Flag graphics" }, // deprecated, no longer used.
6432 /* 0x15 */ { A5BLOCK_ALLOW_OFFSET
, SPR_OPENTTD_BASE
, 1, OPENTTD_SPRITE_COUNT
, "OpenTTD GUI graphics" },
6433 /* 0x16 */ { A5BLOCK_ALLOW_OFFSET
, SPR_AIRPORT_PREVIEW_BASE
, 1, SPR_AIRPORT_PREVIEW_COUNT
, "Airport preview graphics" },
6434 /* 0x17 */ { A5BLOCK_ALLOW_OFFSET
, SPR_RAILTYPE_TUNNEL_BASE
, 1, RAILTYPE_TUNNEL_BASE_COUNT
, "Railtype tunnel base" },
6435 /* 0x18 */ { A5BLOCK_ALLOW_OFFSET
, SPR_PALETTE_BASE
, 1, PALETTE_SPRITE_COUNT
, "Palette" },
6439 static void GraphicsNew(ByteReader
*buf
)
6441 /* <05> <graphics-type> <num-sprites> <other data...>
6443 * B graphics-type What set of graphics the sprites define.
6444 * E num-sprites How many sprites are in this set?
6445 * V other data Graphics type specific data. Currently unused. */
6447 uint8_t type
= buf
->ReadByte();
6448 uint16_t num
= buf
->ReadExtendedByte();
6449 uint16_t offset
= HasBit(type
, 7) ? buf
->ReadExtendedByte() : 0;
6450 ClrBit(type
, 7); // Clear the high bit as that only indicates whether there is an offset.
6452 if ((type
== 0x0D) && (num
== 10) && HasBit(_cur
.grfconfig
->flags
, GCF_SYSTEM
)) {
6453 /* Special not-TTDP-compatible case used in openttd.grf
6454 * Missing shore sprites and initialisation of SPR_SHORE_BASE */
6455 GrfMsg(2, "GraphicsNew: Loading 10 missing shore sprites from extra grf.");
6456 LoadNextSprite(SPR_SHORE_BASE
+ 0, *_cur
.file
, _cur
.nfo_line
++); // SLOPE_STEEP_S
6457 LoadNextSprite(SPR_SHORE_BASE
+ 5, *_cur
.file
, _cur
.nfo_line
++); // SLOPE_STEEP_W
6458 LoadNextSprite(SPR_SHORE_BASE
+ 7, *_cur
.file
, _cur
.nfo_line
++); // SLOPE_WSE
6459 LoadNextSprite(SPR_SHORE_BASE
+ 10, *_cur
.file
, _cur
.nfo_line
++); // SLOPE_STEEP_N
6460 LoadNextSprite(SPR_SHORE_BASE
+ 11, *_cur
.file
, _cur
.nfo_line
++); // SLOPE_NWS
6461 LoadNextSprite(SPR_SHORE_BASE
+ 13, *_cur
.file
, _cur
.nfo_line
++); // SLOPE_ENW
6462 LoadNextSprite(SPR_SHORE_BASE
+ 14, *_cur
.file
, _cur
.nfo_line
++); // SLOPE_SEN
6463 LoadNextSprite(SPR_SHORE_BASE
+ 15, *_cur
.file
, _cur
.nfo_line
++); // SLOPE_STEEP_E
6464 LoadNextSprite(SPR_SHORE_BASE
+ 16, *_cur
.file
, _cur
.nfo_line
++); // SLOPE_EW
6465 LoadNextSprite(SPR_SHORE_BASE
+ 17, *_cur
.file
, _cur
.nfo_line
++); // SLOPE_NS
6466 if (_loaded_newgrf_features
.shore
== SHORE_REPLACE_NONE
) _loaded_newgrf_features
.shore
= SHORE_REPLACE_ONLY_NEW
;
6470 /* Supported type? */
6471 if ((type
>= lengthof(_action5_types
)) || (_action5_types
[type
].block_type
== A5BLOCK_INVALID
)) {
6472 GrfMsg(2, "GraphicsNew: Custom graphics (type 0x{:02X}) sprite block of length {} (unimplemented, ignoring)", type
, num
);
6473 _cur
.skip_sprites
= num
;
6477 const Action5Type
*action5_type
= &_action5_types
[type
];
6479 /* Contrary to TTDP we allow always to specify too few sprites as we allow always an offset,
6480 * except for the long version of the shore type:
6481 * Ignore offset if not allowed */
6482 if ((action5_type
->block_type
!= A5BLOCK_ALLOW_OFFSET
) && (offset
!= 0)) {
6483 GrfMsg(1, "GraphicsNew: {} (type 0x{:02X}) do not allow an <offset> field. Ignoring offset.", action5_type
->name
, type
);
6487 /* Ignore action5 if too few sprites are specified. (for TTDP compatibility)
6488 * This does not make sense, if <offset> is allowed */
6489 if ((action5_type
->block_type
== A5BLOCK_FIXED
) && (num
< action5_type
->min_sprites
)) {
6490 GrfMsg(1, "GraphicsNew: {} (type 0x{:02X}) count must be at least {}. Only {} were specified. Skipping.", action5_type
->name
, type
, action5_type
->min_sprites
, num
);
6491 _cur
.skip_sprites
= num
;
6495 /* Load at most max_sprites sprites. Skip remaining sprites. (for compatibility with TTDP and future extensions) */
6496 uint16_t skip_num
= SanitizeSpriteOffset(num
, offset
, action5_type
->max_sprites
, action5_type
->name
);
6497 SpriteID replace
= action5_type
->sprite_base
+ offset
;
6499 /* Load <num> sprites starting from <replace>, then skip <skip_num> sprites. */
6500 GrfMsg(2, "GraphicsNew: Replacing sprites {} to {} of {} (type 0x{:02X}) at SpriteID 0x{:04X}", offset
, offset
+ num
- 1, action5_type
->name
, type
, replace
);
6502 if (type
== 0x0D) _loaded_newgrf_features
.shore
= SHORE_REPLACE_ACTION_5
;
6505 static const SpriteID depot_with_track_offset
= SPR_TRAMWAY_DEPOT_WITH_TRACK
- SPR_TRAMWAY_BASE
;
6506 static const SpriteID depot_no_track_offset
= SPR_TRAMWAY_DEPOT_NO_TRACK
- SPR_TRAMWAY_BASE
;
6507 if (offset
<= depot_with_track_offset
&& offset
+ num
> depot_with_track_offset
) _loaded_newgrf_features
.tram
= TRAMWAY_REPLACE_DEPOT_WITH_TRACK
;
6508 if (offset
<= depot_no_track_offset
&& offset
+ num
> depot_no_track_offset
) _loaded_newgrf_features
.tram
= TRAMWAY_REPLACE_DEPOT_NO_TRACK
;
6511 /* If the baseset or grf only provides sprites for flat tiles (pre #10282), duplicate those for use on slopes. */
6512 bool dup_oneway_sprites
= ((type
== 0x09) && (offset
+ num
<= SPR_ONEWAY_SLOPE_N_OFFSET
));
6514 for (; num
> 0; num
--) {
6516 int load_index
= (replace
== 0 ? _cur
.spriteid
++ : replace
++);
6517 LoadNextSprite(load_index
, *_cur
.file
, _cur
.nfo_line
);
6518 if (dup_oneway_sprites
) {
6519 DupSprite(load_index
, load_index
+ SPR_ONEWAY_SLOPE_N_OFFSET
);
6520 DupSprite(load_index
, load_index
+ SPR_ONEWAY_SLOPE_S_OFFSET
);
6524 _cur
.skip_sprites
= skip_num
;
6527 /* Action 0x05 (SKIP) */
6528 static void SkipAct5(ByteReader
*buf
)
6530 /* Ignore type byte */
6533 /* Skip the sprites of this action */
6534 _cur
.skip_sprites
= buf
->ReadExtendedByte();
6536 GrfMsg(3, "SkipAct5: Skipping {} sprites", _cur
.skip_sprites
);
6540 * Reads a variable common to VarAction2 and Action7/9/D.
6542 * Returns VarAction2 variable 'param' resp. Action7/9/D variable '0x80 + param'.
6543 * If a variable is not accessible from all four actions, it is handled in the action specific functions.
6545 * @param param variable number (as for VarAction2, for Action7/9/D you have to subtract 0x80 first).
6546 * @param value returns the value of the variable.
6547 * @param grffile NewGRF querying the variable
6548 * @return true iff the variable is known and the value is returned in 'value'.
6550 bool GetGlobalVariable(byte param
, uint32_t *value
, const GRFFile
*grffile
)
6553 case 0x00: // current date
6554 *value
= std::max(TimerGameCalendar::date
- CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR
, TimerGameCalendar::Date(0)).base();
6557 case 0x01: // current year
6558 *value
= (Clamp(TimerGameCalendar::year
, CalendarTime::ORIGINAL_BASE_YEAR
, CalendarTime::ORIGINAL_MAX_YEAR
) - CalendarTime::ORIGINAL_BASE_YEAR
).base();
6561 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)
6562 TimerGameCalendar::YearMonthDay ymd
= TimerGameCalendar::ConvertDateToYMD(TimerGameCalendar::date
);
6563 TimerGameCalendar::Date start_of_year
= TimerGameCalendar::ConvertYMDToDate(ymd
.year
, 0, 1);
6564 *value
= ymd
.month
| (ymd
.day
- 1) << 8 | (TimerGameCalendar::IsLeapYear(ymd
.year
) ? 1 << 15 : 0) | (TimerGameCalendar::date
- start_of_year
).base() << 16;
6568 case 0x03: // current climate, 0=temp, 1=arctic, 2=trop, 3=toyland
6569 *value
= _settings_game
.game_creation
.landscape
;
6572 case 0x06: // road traffic side, bit 4 clear=left, set=right
6573 *value
= _settings_game
.vehicle
.road_side
<< 4;
6576 case 0x09: // date fraction
6577 *value
= TimerGameCalendar::date_fract
* 885;
6580 case 0x0A: // animation counter
6581 *value
= GB(TimerGameTick::counter
, 0, 16);
6584 case 0x0B: { // TTDPatch version
6587 uint revision
= 1; // special case: 2.0.1 is 2.0.10
6589 *value
= (major
<< 24) | (minor
<< 20) | (revision
<< 16) | build
;
6593 case 0x0D: // TTD Version, 00=DOS, 01=Windows
6594 *value
= _cur
.grfconfig
->palette
& GRFP_USE_MASK
;
6597 case 0x0E: // Y-offset for train sprites
6598 *value
= _cur
.grffile
->traininfo_vehicle_pitch
;
6601 case 0x0F: // Rail track type cost factors
6603 SB(*value
, 0, 8, GetRailTypeInfo(RAILTYPE_RAIL
)->cost_multiplier
); // normal rail
6604 if (_settings_game
.vehicle
.disable_elrails
) {
6605 /* skip elrail multiplier - disabled */
6606 SB(*value
, 8, 8, GetRailTypeInfo(RAILTYPE_MONO
)->cost_multiplier
); // monorail
6608 SB(*value
, 8, 8, GetRailTypeInfo(RAILTYPE_ELECTRIC
)->cost_multiplier
); // electified railway
6609 /* Skip monorail multiplier - no space in result */
6611 SB(*value
, 16, 8, GetRailTypeInfo(RAILTYPE_MAGLEV
)->cost_multiplier
); // maglev
6614 case 0x11: // current rail tool type
6615 *value
= 0; // constant fake value to avoid desync
6618 case 0x12: // Game mode
6619 *value
= _game_mode
;
6622 /* case 0x13: // Tile refresh offset to left not implemented */
6623 /* case 0x14: // Tile refresh offset to right not implemented */
6624 /* case 0x15: // Tile refresh offset upwards not implemented */
6625 /* case 0x16: // Tile refresh offset downwards not implemented */
6626 /* case 0x17: // temperate snow line not implemented */
6628 case 0x1A: // Always -1
6632 case 0x1B: // Display options
6633 *value
= 0x3F; // constant fake value to avoid desync
6636 case 0x1D: // TTD Platform, 00=TTDPatch, 01=OpenTTD
6640 case 0x1E: // Miscellaneous GRF features
6641 *value
= _misc_grf_features
;
6643 /* Add the local flags */
6644 assert(!HasBit(*value
, GMB_TRAIN_WIDTH_32_PIXELS
));
6645 if (_cur
.grffile
->traininfo_vehicle_width
== VEHICLEINFO_FULL_VEHICLE_WIDTH
) SetBit(*value
, GMB_TRAIN_WIDTH_32_PIXELS
);
6648 /* case 0x1F: // locale dependent settings not implemented to avoid desync */
6650 case 0x20: { // snow line height
6651 byte snowline
= GetSnowLine();
6652 if (_settings_game
.game_creation
.landscape
== LT_ARCTIC
&& snowline
<= _settings_game
.construction
.map_height_limit
) {
6653 *value
= Clamp(snowline
* (grffile
->grf_version
>= 8 ? 1 : TILE_HEIGHT
), 0, 0xFE);
6661 case 0x21: // OpenTTD version
6662 *value
= _openttd_newgrf_version
;
6665 case 0x22: // difficulty level
6669 case 0x23: // long format date
6670 *value
= TimerGameCalendar::date
.base();
6673 case 0x24: // long format year
6674 *value
= TimerGameCalendar::year
.base();
6677 default: return false;
6681 static uint32_t GetParamVal(byte param
, uint32_t *cond_val
)
6683 /* First handle variable common with VarAction2 */
6685 if (GetGlobalVariable(param
- 0x80, &value
, _cur
.grffile
)) return value
;
6688 /* Non-common variable */
6690 case 0x84: { // GRF loading stage
6693 if (_cur
.stage
> GLS_INIT
) SetBit(res
, 0);
6694 if (_cur
.stage
== GLS_RESERVE
) SetBit(res
, 8);
6695 if (_cur
.stage
== GLS_ACTIVATION
) SetBit(res
, 9);
6699 case 0x85: // TTDPatch flags, only for bit tests
6700 if (cond_val
== nullptr) {
6701 /* Supported in Action 0x07 and 0x09, not 0x0D */
6704 uint32_t index
= *cond_val
/ 0x20;
6705 uint32_t param_val
= index
< lengthof(_ttdpatch_flags
) ? _ttdpatch_flags
[index
] : 0;
6710 case 0x88: // GRF ID check
6713 /* case 0x99: Global ID offset not implemented */
6717 if (param
< 0x80) return _cur
.grffile
->GetParam(param
);
6719 /* In-game variable. */
6720 GrfMsg(1, "Unsupported in-game variable 0x{:02X}", param
);
6726 static void CfgApply(ByteReader
*buf
)
6728 /* <06> <param-num> <param-size> <offset> ... <FF>
6730 * B param-num Number of parameter to substitute (First = "zero")
6731 * Ignored if that parameter was not specified in newgrf.cfg
6732 * B param-size How many bytes to replace. If larger than 4, the
6733 * bytes of the following parameter are used. In that
6734 * case, nothing is applied unless *all* parameters
6736 * B offset Offset into data from beginning of next sprite
6737 * to place where parameter is to be stored. */
6739 /* Preload the next sprite */
6740 SpriteFile
&file
= *_cur
.file
;
6741 size_t pos
= file
.GetPos();
6742 uint32_t num
= file
.GetContainerVersion() >= 2 ? file
.ReadDword() : file
.ReadWord();
6743 uint8_t type
= file
.ReadByte();
6745 /* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */
6747 GrfMsg(2, "CfgApply: Ignoring (next sprite is real, unsupported)");
6749 /* Reset the file position to the start of the next sprite */
6750 file
.SeekTo(pos
, SEEK_SET
);
6754 /* Get (or create) the override for the next sprite. */
6755 GRFLocation
location(_cur
.grfconfig
->ident
.grfid
, _cur
.nfo_line
+ 1);
6756 std::vector
<byte
> &preload_sprite
= _grf_line_to_action6_sprite_override
[location
];
6758 /* Load new sprite data if it hasn't already been loaded. */
6759 if (preload_sprite
.empty()) {
6760 preload_sprite
.resize(num
);
6761 file
.ReadBlock(preload_sprite
.data(), num
);
6764 /* Reset the file position to the start of the next sprite */
6765 file
.SeekTo(pos
, SEEK_SET
);
6767 /* Now perform the Action 0x06 on our data. */
6775 /* Read the parameter to apply. 0xFF indicates no more data to change. */
6776 param_num
= buf
->ReadByte();
6777 if (param_num
== 0xFF) break;
6779 /* Get the size of the parameter to use. If the size covers multiple
6780 * double words, sequential parameter values are used. */
6781 param_size
= buf
->ReadByte();
6783 /* Bit 7 of param_size indicates we should add to the original value
6784 * instead of replacing it. */
6785 add_value
= HasBit(param_size
, 7);
6786 param_size
= GB(param_size
, 0, 7);
6788 /* Where to apply the data to within the pseudo sprite data. */
6789 offset
= buf
->ReadExtendedByte();
6791 /* If the parameter is a GRF parameter (not an internal variable) check
6792 * if it (and all further sequential parameters) has been defined. */
6793 if (param_num
< 0x80 && (param_num
+ (param_size
- 1) / 4) >= _cur
.grffile
->param_end
) {
6794 GrfMsg(2, "CfgApply: Ignoring (param {} not set)", (param_num
+ (param_size
- 1) / 4));
6798 GrfMsg(8, "CfgApply: Applying {} bytes from parameter 0x{:02X} at offset 0x{:04X}", param_size
, param_num
, offset
);
6801 for (i
= 0; i
< param_size
&& offset
+ i
< num
; i
++) {
6802 uint32_t value
= GetParamVal(param_num
+ i
/ 4, nullptr);
6803 /* Reset carry flag for each iteration of the variable (only really
6804 * matters if param_size is greater than 4) */
6805 if (i
% 4 == 0) carry
= false;
6808 uint new_value
= preload_sprite
[offset
+ i
] + GB(value
, (i
% 4) * 8, 8) + (carry
? 1 : 0);
6809 preload_sprite
[offset
+ i
] = GB(new_value
, 0, 8);
6810 /* Check if the addition overflowed */
6811 carry
= new_value
>= 256;
6813 preload_sprite
[offset
+ i
] = GB(value
, (i
% 4) * 8, 8);
6820 * Disable a static NewGRF when it is influencing another (non-static)
6821 * NewGRF as this could cause desyncs.
6823 * We could just tell the NewGRF querying that the file doesn't exist,
6824 * but that might give unwanted results. Disabling the NewGRF gives the
6825 * best result as no NewGRF author can complain about that.
6826 * @param c The NewGRF to disable.
6828 static void DisableStaticNewGRFInfluencingNonStaticNewGRFs(GRFConfig
*c
)
6830 GRFError
*error
= DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC
, c
);
6831 error
->data
= _cur
.grfconfig
->GetName();
6836 static void SkipIf(ByteReader
*buf
)
6838 /* <07/09> <param-num> <param-size> <condition-type> <value> <num-sprites>
6845 uint32_t cond_val
= 0;
6849 uint8_t param
= buf
->ReadByte();
6850 uint8_t paramsize
= buf
->ReadByte();
6851 uint8_t condtype
= buf
->ReadByte();
6854 /* Always 1 for bit tests, the given value should be ignored. */
6858 switch (paramsize
) {
6859 case 8: cond_val
= buf
->ReadDWord(); mask
= buf
->ReadDWord(); break;
6860 case 4: cond_val
= buf
->ReadDWord(); mask
= 0xFFFFFFFF; break;
6861 case 2: cond_val
= buf
->ReadWord(); mask
= 0x0000FFFF; break;
6862 case 1: cond_val
= buf
->ReadByte(); mask
= 0x000000FF; break;
6866 if (param
< 0x80 && _cur
.grffile
->param_end
<= param
) {
6867 GrfMsg(7, "SkipIf: Param {} undefined, skipping test", param
);
6871 GrfMsg(7, "SkipIf: Test condtype {}, param 0x{:02X}, condval 0x{:08X}", condtype
, param
, cond_val
);
6873 /* condtypes that do not use 'param' are always valid.
6874 * condtypes that use 'param' are either not valid for param 0x88, or they are only valid for param 0x88.
6876 if (condtype
>= 0x0B) {
6877 /* Tests that ignore 'param' */
6879 case 0x0B: result
= !IsValidCargoID(GetCargoIDByLabel(CargoLabel(BSWAP32(cond_val
))));
6881 case 0x0C: result
= IsValidCargoID(GetCargoIDByLabel(CargoLabel(BSWAP32(cond_val
))));
6883 case 0x0D: result
= GetRailTypeByLabel(BSWAP32(cond_val
)) == INVALID_RAILTYPE
;
6885 case 0x0E: result
= GetRailTypeByLabel(BSWAP32(cond_val
)) != INVALID_RAILTYPE
;
6888 RoadType rt
= GetRoadTypeByLabel(BSWAP32(cond_val
));
6889 result
= rt
== INVALID_ROADTYPE
|| !RoadTypeIsRoad(rt
);
6893 RoadType rt
= GetRoadTypeByLabel(BSWAP32(cond_val
));
6894 result
= rt
!= INVALID_ROADTYPE
&& RoadTypeIsRoad(rt
);
6898 RoadType rt
= GetRoadTypeByLabel(BSWAP32(cond_val
));
6899 result
= rt
== INVALID_ROADTYPE
|| !RoadTypeIsTram(rt
);
6903 RoadType rt
= GetRoadTypeByLabel(BSWAP32(cond_val
));
6904 result
= rt
!= INVALID_ROADTYPE
&& RoadTypeIsTram(rt
);
6907 default: GrfMsg(1, "SkipIf: Unsupported condition type {:02X}. Ignoring", condtype
); return;
6909 } else if (param
== 0x88) {
6912 GRFConfig
*c
= GetGRFConfig(cond_val
, mask
);
6914 if (c
!= nullptr && HasBit(c
->flags
, GCF_STATIC
) && !HasBit(_cur
.grfconfig
->flags
, GCF_STATIC
) && _networking
) {
6915 DisableStaticNewGRFInfluencingNonStaticNewGRFs(c
);
6919 if (condtype
!= 10 && c
== nullptr) {
6920 GrfMsg(7, "SkipIf: GRFID 0x{:08X} unknown, skipping test", BSWAP32(cond_val
));
6925 /* Tests 0x06 to 0x0A are only for param 0x88, GRFID checks */
6926 case 0x06: // Is GRFID active?
6927 result
= c
->status
== GCS_ACTIVATED
;
6930 case 0x07: // Is GRFID non-active?
6931 result
= c
->status
!= GCS_ACTIVATED
;
6934 case 0x08: // GRFID is not but will be active?
6935 result
= c
->status
== GCS_INITIALISED
;
6938 case 0x09: // GRFID is or will be active?
6939 result
= c
->status
== GCS_ACTIVATED
|| c
->status
== GCS_INITIALISED
;
6942 case 0x0A: // GRFID is not nor will be active
6943 /* This is the only condtype that doesn't get ignored if the GRFID is not found */
6944 result
= c
== nullptr || c
->status
== GCS_DISABLED
|| c
->status
== GCS_NOT_FOUND
;
6947 default: GrfMsg(1, "SkipIf: Unsupported GRF condition type {:02X}. Ignoring", condtype
); return;
6950 /* Tests that use 'param' and are not GRF ID checks. */
6951 uint32_t param_val
= GetParamVal(param
, &cond_val
); // cond_val is modified for param == 0x85
6953 case 0x00: result
= !!(param_val
& (1 << cond_val
));
6955 case 0x01: result
= !(param_val
& (1 << cond_val
));
6957 case 0x02: result
= (param_val
& mask
) == cond_val
;
6959 case 0x03: result
= (param_val
& mask
) != cond_val
;
6961 case 0x04: result
= (param_val
& mask
) < cond_val
;
6963 case 0x05: result
= (param_val
& mask
) > cond_val
;
6965 default: GrfMsg(1, "SkipIf: Unsupported condition type {:02X}. Ignoring", condtype
); return;
6970 GrfMsg(2, "SkipIf: Not skipping sprites, test was false");
6974 uint8_t numsprites
= buf
->ReadByte();
6976 /* numsprites can be a GOTO label if it has been defined in the GRF
6977 * file. The jump will always be the first matching label that follows
6978 * the current nfo_line. If no matching label is found, the first matching
6979 * label in the file is used. */
6980 const GRFLabel
*choice
= nullptr;
6981 for (const auto &label
: _cur
.grffile
->labels
) {
6982 if (label
.label
!= numsprites
) continue;
6984 /* Remember a goto before the current line */
6985 if (choice
== nullptr) choice
= &label
;
6986 /* If we find a label here, this is definitely good */
6987 if (label
.nfo_line
> _cur
.nfo_line
) {
6993 if (choice
!= nullptr) {
6994 GrfMsg(2, "SkipIf: Jumping to label 0x{:X} at line {}, test was true", choice
->label
, choice
->nfo_line
);
6995 _cur
.file
->SeekTo(choice
->pos
, SEEK_SET
);
6996 _cur
.nfo_line
= choice
->nfo_line
;
7000 GrfMsg(2, "SkipIf: Skipping {} sprites, test was true", numsprites
);
7001 _cur
.skip_sprites
= numsprites
;
7002 if (_cur
.skip_sprites
== 0) {
7003 /* Zero means there are no sprites to skip, so
7004 * we use -1 to indicate that all further
7005 * sprites should be skipped. */
7006 _cur
.skip_sprites
= -1;
7008 /* If an action 8 hasn't been encountered yet, disable the grf. */
7009 if (_cur
.grfconfig
->status
!= (_cur
.stage
< GLS_RESERVE
? GCS_INITIALISED
: GCS_ACTIVATED
)) {
7016 /* Action 0x08 (GLS_FILESCAN) */
7017 static void ScanInfo(ByteReader
*buf
)
7019 uint8_t grf_version
= buf
->ReadByte();
7020 uint32_t grfid
= buf
->ReadDWord();
7021 const char *name
= buf
->ReadString();
7023 _cur
.grfconfig
->ident
.grfid
= grfid
;
7025 if (grf_version
< 2 || grf_version
> 8) {
7026 SetBit(_cur
.grfconfig
->flags
, GCF_INVALID
);
7027 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
);
7030 /* GRF IDs starting with 0xFF are reserved for internal TTDPatch use */
7031 if (GB(grfid
, 0, 8) == 0xFF) SetBit(_cur
.grfconfig
->flags
, GCF_SYSTEM
);
7033 AddGRFTextToList(_cur
.grfconfig
->name
, 0x7F, grfid
, false, name
);
7035 if (buf
->HasData()) {
7036 const char *info
= buf
->ReadString();
7037 AddGRFTextToList(_cur
.grfconfig
->info
, 0x7F, grfid
, true, info
);
7040 /* GLS_INFOSCAN only looks for the action 8, so we can skip the rest of the file */
7041 _cur
.skip_sprites
= -1;
7045 static void GRFInfo(ByteReader
*buf
)
7047 /* <08> <version> <grf-id> <name> <info>
7049 * B version newgrf version, currently 06
7050 * 4*B grf-id globally unique ID of this .grf file
7051 * S name name of this .grf set
7052 * S info string describing the set, and e.g. author and copyright */
7054 uint8_t version
= buf
->ReadByte();
7055 uint32_t grfid
= buf
->ReadDWord();
7056 const char *name
= buf
->ReadString();
7058 if (_cur
.stage
< GLS_RESERVE
&& _cur
.grfconfig
->status
!= GCS_UNKNOWN
) {
7059 DisableGrf(STR_NEWGRF_ERROR_MULTIPLE_ACTION_8
);
7063 if (_cur
.grffile
->grfid
!= grfid
) {
7064 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
));
7065 _cur
.grffile
->grfid
= grfid
;
7068 _cur
.grffile
->grf_version
= version
;
7069 _cur
.grfconfig
->status
= _cur
.stage
< GLS_RESERVE
? GCS_INITIALISED
: GCS_ACTIVATED
;
7071 /* Do swap the GRFID for displaying purposes since people expect that */
7072 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
);
7076 static void SpriteReplace(ByteReader
*buf
)
7078 /* <0A> <num-sets> <set1> [<set2> ...]
7079 * <set>: <num-sprites> <first-sprite>
7081 * B num-sets How many sets of sprites to replace.
7083 * B num-sprites How many sprites are in this set
7084 * W first-sprite First sprite number to replace */
7086 uint8_t num_sets
= buf
->ReadByte();
7088 for (uint i
= 0; i
< num_sets
; i
++) {
7089 uint8_t num_sprites
= buf
->ReadByte();
7090 uint16_t first_sprite
= buf
->ReadWord();
7092 GrfMsg(2, "SpriteReplace: [Set {}] Changing {} sprites, beginning with {}",
7093 i
, num_sprites
, first_sprite
7096 for (uint j
= 0; j
< num_sprites
; j
++) {
7097 int load_index
= first_sprite
+ j
;
7099 LoadNextSprite(load_index
, *_cur
.file
, _cur
.nfo_line
); // XXX
7101 /* Shore sprites now located at different addresses.
7102 * So detect when the old ones get replaced. */
7103 if (IsInsideMM(load_index
, SPR_ORIGINALSHORE_START
, SPR_ORIGINALSHORE_END
+ 1)) {
7104 if (_loaded_newgrf_features
.shore
!= SHORE_REPLACE_ACTION_5
) _loaded_newgrf_features
.shore
= SHORE_REPLACE_ACTION_A
;
7110 /* Action 0x0A (SKIP) */
7111 static void SkipActA(ByteReader
*buf
)
7113 uint8_t num_sets
= buf
->ReadByte();
7115 for (uint i
= 0; i
< num_sets
; i
++) {
7116 /* Skip the sprites this replaces */
7117 _cur
.skip_sprites
+= buf
->ReadByte();
7118 /* But ignore where they go */
7122 GrfMsg(3, "SkipActA: Skipping {} sprites", _cur
.skip_sprites
);
7126 static void GRFLoadError(ByteReader
*buf
)
7128 /* <0B> <severity> <language-id> <message-id> [<message...> 00] [<data...>] 00 [<parnum>]
7130 * B severity 00: notice, continue loading grf file
7131 * 01: warning, continue loading grf file
7132 * 02: error, but continue loading grf file, and attempt
7133 * loading grf again when loading or starting next game
7134 * 03: error, abort loading and prevent loading again in
7135 * the future (only when restarting the patch)
7136 * B language-id see action 4, use 1F for built-in error messages
7137 * B message-id message to show, see below
7138 * S message for custom messages (message-id FF), text of the message
7139 * not present for built-in messages.
7140 * V data additional data for built-in (or custom) messages
7141 * B parnum parameter numbers to be shown in the message (maximum of 2) */
7143 static const StringID msgstr
[] = {
7144 STR_NEWGRF_ERROR_VERSION_NUMBER
,
7145 STR_NEWGRF_ERROR_DOS_OR_WINDOWS
,
7146 STR_NEWGRF_ERROR_UNSET_SWITCH
,
7147 STR_NEWGRF_ERROR_INVALID_PARAMETER
,
7148 STR_NEWGRF_ERROR_LOAD_BEFORE
,
7149 STR_NEWGRF_ERROR_LOAD_AFTER
,
7150 STR_NEWGRF_ERROR_OTTD_VERSION_NUMBER
,
7153 static const StringID sevstr
[] = {
7154 STR_NEWGRF_ERROR_MSG_INFO
,
7155 STR_NEWGRF_ERROR_MSG_WARNING
,
7156 STR_NEWGRF_ERROR_MSG_ERROR
,
7157 STR_NEWGRF_ERROR_MSG_FATAL
7160 byte severity
= buf
->ReadByte();
7161 byte lang
= buf
->ReadByte();
7162 byte message_id
= buf
->ReadByte();
7164 /* Skip the error if it isn't valid for the current language. */
7165 if (!CheckGrfLangID(lang
, _cur
.grffile
->grf_version
)) return;
7167 /* Skip the error until the activation stage unless bit 7 of the severity
7169 if (!HasBit(severity
, 7) && _cur
.stage
== GLS_INIT
) {
7170 GrfMsg(7, "GRFLoadError: Skipping non-fatal GRFLoadError in stage {}", _cur
.stage
);
7173 ClrBit(severity
, 7);
7175 if (severity
>= lengthof(sevstr
)) {
7176 GrfMsg(7, "GRFLoadError: Invalid severity id {}. Setting to 2 (non-fatal error).", severity
);
7178 } else if (severity
== 3) {
7179 /* This is a fatal error, so make sure the GRF is deactivated and no
7180 * more of it gets loaded. */
7183 /* Make sure we show fatal errors, instead of silly infos from before */
7184 _cur
.grfconfig
->error
.reset();
7187 if (message_id
>= lengthof(msgstr
) && message_id
!= 0xFF) {
7188 GrfMsg(7, "GRFLoadError: Invalid message id.");
7192 if (buf
->Remaining() <= 1) {
7193 GrfMsg(7, "GRFLoadError: No message data supplied.");
7197 /* For now we can only show one message per newgrf file. */
7198 if (_cur
.grfconfig
->error
.has_value()) return;
7200 _cur
.grfconfig
->error
= {sevstr
[severity
]};
7201 GRFError
*error
= &_cur
.grfconfig
->error
.value();
7203 if (message_id
== 0xFF) {
7204 /* This is a custom error message. */
7205 if (buf
->HasData()) {
7206 const char *message
= buf
->ReadString();
7208 error
->custom_message
= TranslateTTDPatchCodes(_cur
.grffile
->grfid
, lang
, true, message
, SCC_RAW_STRING_POINTER
);
7210 GrfMsg(7, "GRFLoadError: No custom message supplied.");
7211 error
->custom_message
.clear();
7214 error
->message
= msgstr
[message_id
];
7217 if (buf
->HasData()) {
7218 const char *data
= buf
->ReadString();
7220 error
->data
= TranslateTTDPatchCodes(_cur
.grffile
->grfid
, lang
, true, data
);
7222 GrfMsg(7, "GRFLoadError: No message data supplied.");
7223 error
->data
.clear();
7226 /* Only two parameter numbers can be used in the string. */
7227 for (uint i
= 0; i
< error
->param_value
.size() && buf
->HasData(); i
++) {
7228 uint param_number
= buf
->ReadByte();
7229 error
->param_value
[i
] = _cur
.grffile
->GetParam(param_number
);
7234 static void GRFComment(ByteReader
*buf
)
7236 /* <0C> [<ignored...>]
7238 * V ignored Anything following the 0C is ignored */
7240 if (!buf
->HasData()) return;
7242 const char *text
= buf
->ReadString();
7243 GrfMsg(2, "GRFComment: {}", text
);
7246 /* Action 0x0D (GLS_SAFETYSCAN) */
7247 static void SafeParamSet(ByteReader
*buf
)
7249 uint8_t target
= buf
->ReadByte();
7251 /* Writing GRF parameters and some bits of 'misc GRF features' are safe. */
7252 if (target
< 0x80 || target
== 0x9E) return;
7254 /* GRM could be unsafe, but as here it can only happen after other GRFs
7255 * are loaded, it should be okay. If the GRF tried to use the slots it
7256 * reserved, it would be marked unsafe anyway. GRM for (e.g. bridge)
7257 * sprites is considered safe. */
7259 SetBit(_cur
.grfconfig
->flags
, GCF_UNSAFE
);
7261 /* Skip remainder of GRF */
7262 _cur
.skip_sprites
= -1;
7266 static uint32_t GetPatchVariable(uint8_t param
)
7269 /* start year - 1920 */
7270 case 0x0B: return (std::max(_settings_game
.game_creation
.starting_year
, CalendarTime::ORIGINAL_BASE_YEAR
) - CalendarTime::ORIGINAL_BASE_YEAR
).base();
7272 /* freight trains weight factor */
7273 case 0x0E: return _settings_game
.vehicle
.freight_trains
;
7275 /* empty wagon speed increase */
7276 case 0x0F: return 0;
7278 /* plane speed factor; our patch option is reversed from TTDPatch's,
7279 * the following is good for 1x, 2x and 4x (most common?) and...
7280 * well not really for 3x. */
7282 switch (_settings_game
.vehicle
.plane_speed
) {
7291 /* 2CC colourmap base sprite */
7292 case 0x11: return SPR_2CCMAP_BASE
;
7294 /* map size: format = -MABXYSS
7295 * M : the type of map
7296 * bit 0 : set : squared map. Bit 1 is now not relevant
7297 * clear : rectangle map. Bit 1 will indicate the bigger edge of the map
7298 * bit 1 : set : Y is the bigger edge. Bit 0 is clear
7299 * clear : X is the bigger edge.
7300 * A : minimum edge(log2) of the map
7301 * B : maximum edge(log2) of the map
7302 * XY : edges(log2) of each side of the map.
7303 * SS : combination of both X and Y, thus giving the size(log2) of the map
7307 byte log_X
= Map::LogX() - 6; // subtraction is required to make the minimal size (64) zero based
7308 byte log_Y
= Map::LogY() - 6;
7309 byte max_edge
= std::max(log_X
, log_Y
);
7311 if (log_X
== log_Y
) { // we have a squared map, since both edges are identical
7312 SetBit(map_bits
, 0);
7314 if (max_edge
== log_Y
) SetBit(map_bits
, 1); // edge Y been the biggest, mark it
7317 return (map_bits
<< 24) | (std::min(log_X
, log_Y
) << 20) | (max_edge
<< 16) |
7318 (log_X
<< 12) | (log_Y
<< 8) | (log_X
+ log_Y
);
7321 /* The maximum height of the map. */
7323 return _settings_game
.construction
.map_height_limit
;
7325 /* Extra foundations base sprite */
7327 return SPR_SLOPES_BASE
;
7329 /* Shore base sprite */
7331 return SPR_SHORE_BASE
;
7335 return _settings_game
.game_creation
.generation_seed
;
7338 GrfMsg(2, "ParamSet: Unknown Patch variable 0x{:02X}.", param
);
7344 static uint32_t PerformGRM(uint32_t *grm
, uint16_t num_ids
, uint16_t count
, uint8_t op
, uint8_t target
, const char *type
)
7350 /* Return GRFID of set that reserved ID */
7351 return grm
[_cur
.grffile
->GetParam(target
)];
7354 /* With an operation of 2 or 3, we want to reserve a specific block of IDs */
7355 if (op
== 2 || op
== 3) start
= _cur
.grffile
->GetParam(target
);
7357 for (uint i
= start
; i
< num_ids
; i
++) {
7361 if (op
== 2 || op
== 3) break;
7366 if (size
== count
) break;
7369 if (size
== count
) {
7370 /* Got the slot... */
7371 if (op
== 0 || op
== 3) {
7372 GrfMsg(2, "ParamSet: GRM: Reserving {} {} at {}", count
, type
, start
);
7373 for (uint i
= 0; i
< count
; i
++) grm
[start
+ i
] = _cur
.grffile
->grfid
;
7378 /* Unable to allocate */
7379 if (op
!= 4 && op
!= 5) {
7380 /* Deactivate GRF */
7381 GrfMsg(0, "ParamSet: GRM: Unable to allocate {} {}, deactivating", count
, type
);
7382 DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED
);
7386 GrfMsg(1, "ParamSet: GRM: Unable to allocate {} {}", count
, type
);
7391 /** Action 0x0D: Set parameter */
7392 static void ParamSet(ByteReader
*buf
)
7394 /* <0D> <target> <operation> <source1> <source2> [<data>]
7396 * B target parameter number where result is stored
7397 * B operation operation to perform, see below
7398 * B source1 first source operand
7399 * B source2 second source operand
7400 * D data data to use in the calculation, not necessary
7401 * if both source1 and source2 refer to actual parameters
7404 * 00 Set parameter equal to source1
7405 * 01 Addition, source1 + source2
7406 * 02 Subtraction, source1 - source2
7407 * 03 Unsigned multiplication, source1 * source2 (both unsigned)
7408 * 04 Signed multiplication, source1 * source2 (both signed)
7409 * 05 Unsigned bit shift, source1 by source2 (source2 taken to be a
7410 * signed quantity; left shift if positive and right shift if
7411 * negative, source1 is unsigned)
7412 * 06 Signed bit shift, source1 by source2
7413 * (source2 like in 05, and source1 as well)
7416 uint8_t target
= buf
->ReadByte();
7417 uint8_t oper
= buf
->ReadByte();
7418 uint32_t src1
= buf
->ReadByte();
7419 uint32_t src2
= buf
->ReadByte();
7422 if (buf
->Remaining() >= 4) data
= buf
->ReadDWord();
7424 /* You can add 80 to the operation to make it apply only if the target
7425 * is not defined yet. In this respect, a parameter is taken to be
7426 * defined if any of the following applies:
7427 * - it has been set to any value in the newgrf(w).cfg parameter list
7428 * - it OR A PARAMETER WITH HIGHER NUMBER has been set to any value by
7429 * an earlier action D */
7430 if (HasBit(oper
, 7)) {
7431 if (target
< 0x80 && target
< _cur
.grffile
->param_end
) {
7432 GrfMsg(7, "ParamSet: Param {} already defined, skipping", target
);
7436 oper
= GB(oper
, 0, 7);
7440 if (GB(data
, 0, 8) == 0xFF) {
7441 if (data
== 0x0000FFFF) {
7442 /* Patch variables */
7443 src1
= GetPatchVariable(src1
);
7445 /* GRF Resource Management */
7447 uint8_t feature
= GB(data
, 8, 8);
7448 uint16_t count
= GB(data
, 16, 16);
7450 if (_cur
.stage
== GLS_RESERVE
) {
7451 if (feature
== 0x08) {
7452 /* General sprites */
7454 /* Check if the allocated sprites will fit below the original sprite limit */
7455 if (_cur
.spriteid
+ count
>= 16384) {
7456 GrfMsg(0, "ParamSet: GRM: Unable to allocate {} sprites; try changing NewGRF order", count
);
7457 DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED
);
7461 /* Reserve space at the current sprite ID */
7462 GrfMsg(4, "ParamSet: GRM: Allocated {} sprites at {}", count
, _cur
.spriteid
);
7463 _grm_sprites
[GRFLocation(_cur
.grffile
->grfid
, _cur
.nfo_line
)] = _cur
.spriteid
;
7464 _cur
.spriteid
+= count
;
7467 /* Ignore GRM result during reservation */
7469 } else if (_cur
.stage
== GLS_ACTIVATION
) {
7471 case 0x00: // Trains
7472 case 0x01: // Road Vehicles
7474 case 0x03: // Aircraft
7475 if (!_settings_game
.vehicle
.dynamic_engines
) {
7476 src1
= PerformGRM(&_grm_engines
[_engine_offsets
[feature
]], _engine_counts
[feature
], count
, op
, target
, "vehicles");
7477 if (_cur
.skip_sprites
== -1) return;
7479 /* GRM does not apply for dynamic engine allocation. */
7483 src1
= _cur
.grffile
->GetParam(target
);
7493 case 0x08: // General sprites
7496 /* Return space reserved during reservation stage */
7497 src1
= _grm_sprites
[GRFLocation(_cur
.grffile
->grfid
, _cur
.nfo_line
)];
7498 GrfMsg(4, "ParamSet: GRM: Using pre-allocated sprites at {}", src1
);
7502 src1
= _cur
.spriteid
;
7506 GrfMsg(1, "ParamSet: GRM: Unsupported operation {} for general sprites", op
);
7512 /* There are two ranges: one for cargo IDs and one for cargo bitmasks */
7513 src1
= PerformGRM(_grm_cargoes
, NUM_CARGO
* 2, count
, op
, target
, "cargoes");
7514 if (_cur
.skip_sprites
== -1) return;
7517 default: GrfMsg(1, "ParamSet: GRM: Unsupported feature 0x{:X}", feature
); return;
7520 /* Ignore GRM during initialization */
7525 /* Read another GRF File's parameter */
7526 const GRFFile
*file
= GetFileByGRFID(data
);
7527 GRFConfig
*c
= GetGRFConfig(data
);
7528 if (c
!= nullptr && HasBit(c
->flags
, GCF_STATIC
) && !HasBit(_cur
.grfconfig
->flags
, GCF_STATIC
) && _networking
) {
7529 /* Disable the read GRF if it is a static NewGRF. */
7530 DisableStaticNewGRFInfluencingNonStaticNewGRFs(c
);
7532 } else if (file
== nullptr || c
== nullptr || c
->status
== GCS_DISABLED
) {
7534 } else if (src1
== 0xFE) {
7537 src1
= file
->GetParam(src1
);
7541 /* The source1 and source2 operands refer to the grf parameter number
7542 * like in action 6 and 7. In addition, they can refer to the special
7543 * variables available in action 7, or they can be FF to use the value
7544 * of <data>. If referring to parameters that are undefined, a value
7545 * of 0 is used instead. */
7546 src1
= (src1
== 0xFF) ? data
: GetParamVal(src1
, nullptr);
7547 src2
= (src2
== 0xFF) ? data
: GetParamVal(src2
, nullptr);
7569 res
= (int32_t)src1
* (int32_t)src2
;
7573 if ((int32_t)src2
< 0) {
7574 res
= src1
>> -(int32_t)src2
;
7576 res
= src1
<< (src2
& 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7581 if ((int32_t)src2
< 0) {
7582 res
= (int32_t)src1
>> -(int32_t)src2
;
7584 res
= (int32_t)src1
<< (src2
& 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7588 case 0x07: // Bitwise AND
7592 case 0x08: // Bitwise OR
7596 case 0x09: // Unsigned division
7604 case 0x0A: // Signed division
7608 res
= (int32_t)src1
/ (int32_t)src2
;
7612 case 0x0B: // Unsigned modulo
7620 case 0x0C: // Signed modulo
7624 res
= (int32_t)src1
% (int32_t)src2
;
7628 default: GrfMsg(0, "ParamSet: Unknown operation {}, skipping", oper
); return;
7632 case 0x8E: // Y-Offset for train sprites
7633 _cur
.grffile
->traininfo_vehicle_pitch
= res
;
7636 case 0x8F: { // Rail track type cost factors
7637 extern RailTypeInfo _railtypes
[RAILTYPE_END
];
7638 _railtypes
[RAILTYPE_RAIL
].cost_multiplier
= GB(res
, 0, 8);
7639 if (_settings_game
.vehicle
.disable_elrails
) {
7640 _railtypes
[RAILTYPE_ELECTRIC
].cost_multiplier
= GB(res
, 0, 8);
7641 _railtypes
[RAILTYPE_MONO
].cost_multiplier
= GB(res
, 8, 8);
7643 _railtypes
[RAILTYPE_ELECTRIC
].cost_multiplier
= GB(res
, 8, 8);
7644 _railtypes
[RAILTYPE_MONO
].cost_multiplier
= GB(res
, 16, 8);
7646 _railtypes
[RAILTYPE_MAGLEV
].cost_multiplier
= GB(res
, 16, 8);
7650 /* not implemented */
7651 case 0x93: // Tile refresh offset to left -- Intended to allow support for larger sprites, not necessary for OTTD
7652 case 0x94: // Tile refresh offset to right
7653 case 0x95: // Tile refresh offset upwards
7654 case 0x96: // Tile refresh offset downwards
7655 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
7656 case 0x99: // Global ID offset -- Not necessary since IDs are remapped automatically
7657 GrfMsg(7, "ParamSet: Skipping unimplemented target 0x{:02X}", target
);
7660 case 0x9E: // Miscellaneous GRF features
7661 /* Set train list engine width */
7662 _cur
.grffile
->traininfo_vehicle_width
= HasBit(res
, GMB_TRAIN_WIDTH_32_PIXELS
) ? VEHICLEINFO_FULL_VEHICLE_WIDTH
: TRAININFO_DEFAULT_VEHICLE_WIDTH
;
7663 /* Remove the local flags from the global flags */
7664 ClrBit(res
, GMB_TRAIN_WIDTH_32_PIXELS
);
7666 /* Only copy safe bits for static grfs */
7667 if (HasBit(_cur
.grfconfig
->flags
, GCF_STATIC
)) {
7668 uint32_t safe_bits
= 0;
7669 SetBit(safe_bits
, GMB_SECOND_ROCKY_TILE_SET
);
7671 _misc_grf_features
= (_misc_grf_features
& ~safe_bits
) | (res
& safe_bits
);
7673 _misc_grf_features
= res
;
7677 case 0x9F: // locale-dependent settings
7678 GrfMsg(7, "ParamSet: Skipping unimplemented target 0x{:02X}", target
);
7682 if (target
< 0x80) {
7683 _cur
.grffile
->param
[target
] = res
;
7684 /* param is zeroed by default */
7685 if (target
+ 1U > _cur
.grffile
->param_end
) _cur
.grffile
->param_end
= target
+ 1;
7687 GrfMsg(7, "ParamSet: Skipping unknown target 0x{:02X}", target
);
7693 /* Action 0x0E (GLS_SAFETYSCAN) */
7694 static void SafeGRFInhibit(ByteReader
*buf
)
7696 /* <0E> <num> <grfids...>
7698 * B num Number of GRFIDs that follow
7699 * D grfids GRFIDs of the files to deactivate */
7701 uint8_t num
= buf
->ReadByte();
7703 for (uint i
= 0; i
< num
; i
++) {
7704 uint32_t grfid
= buf
->ReadDWord();
7706 /* GRF is unsafe it if tries to deactivate other GRFs */
7707 if (grfid
!= _cur
.grfconfig
->ident
.grfid
) {
7708 SetBit(_cur
.grfconfig
->flags
, GCF_UNSAFE
);
7710 /* Skip remainder of GRF */
7711 _cur
.skip_sprites
= -1;
7719 static void GRFInhibit(ByteReader
*buf
)
7721 /* <0E> <num> <grfids...>
7723 * B num Number of GRFIDs that follow
7724 * D grfids GRFIDs of the files to deactivate */
7726 uint8_t num
= buf
->ReadByte();
7728 for (uint i
= 0; i
< num
; i
++) {
7729 uint32_t grfid
= buf
->ReadDWord();
7730 GRFConfig
*file
= GetGRFConfig(grfid
);
7732 /* Unset activation flag */
7733 if (file
!= nullptr && file
!= _cur
.grfconfig
) {
7734 GrfMsg(2, "GRFInhibit: Deactivating file '{}'", file
->filename
);
7735 GRFError
*error
= DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED
, file
);
7736 error
->data
= _cur
.grfconfig
->GetName();
7741 /** Action 0x0F - Define Town names */
7742 static void FeatureTownName(ByteReader
*buf
)
7744 /* <0F> <id> <style-name> <num-parts> <parts>
7746 * B id ID of this definition in bottom 7 bits (final definition if bit 7 set)
7747 * V style-name Name of the style (only for final definition)
7748 * B num-parts Number of parts in this definition
7749 * V parts The parts */
7751 uint32_t grfid
= _cur
.grffile
->grfid
;
7753 GRFTownName
*townname
= AddGRFTownName(grfid
);
7755 byte id
= buf
->ReadByte();
7756 GrfMsg(6, "FeatureTownName: definition 0x{:02X}", id
& 0x7F);
7758 if (HasBit(id
, 7)) {
7759 /* Final definition */
7761 bool new_scheme
= _cur
.grffile
->grf_version
>= 7;
7763 byte lang
= buf
->ReadByte();
7764 StringID style
= STR_UNDEFINED
;
7769 const char *name
= buf
->ReadString();
7771 std::string lang_name
= TranslateTTDPatchCodes(grfid
, lang
, false, name
);
7772 GrfMsg(6, "FeatureTownName: lang 0x{:X} -> '{}'", lang
, lang_name
);
7774 style
= AddGRFString(grfid
, id
, lang
, new_scheme
, false, name
, STR_UNDEFINED
);
7776 lang
= buf
->ReadByte();
7777 } while (lang
!= 0);
7778 townname
->styles
.emplace_back(style
, id
);
7781 uint8_t parts
= buf
->ReadByte();
7782 GrfMsg(6, "FeatureTownName: {} parts", parts
);
7784 townname
->partlists
[id
].reserve(parts
);
7785 for (uint partnum
= 0; partnum
< parts
; partnum
++) {
7786 NamePartList
&partlist
= townname
->partlists
[id
].emplace_back();
7787 uint8_t texts
= buf
->ReadByte();
7788 partlist
.bitstart
= buf
->ReadByte();
7789 partlist
.bitcount
= buf
->ReadByte();
7790 partlist
.maxprob
= 0;
7791 GrfMsg(6, "FeatureTownName: part {} contains {} texts and will use GB(seed, {}, {})", partnum
, texts
, partlist
.bitstart
, partlist
.bitcount
);
7793 partlist
.parts
.reserve(texts
);
7794 for (uint textnum
= 0; textnum
< texts
; textnum
++) {
7795 NamePart
&part
= partlist
.parts
.emplace_back();
7796 part
.prob
= buf
->ReadByte();
7798 if (HasBit(part
.prob
, 7)) {
7799 byte ref_id
= buf
->ReadByte();
7800 if (ref_id
>= GRFTownName::MAX_LISTS
|| townname
->partlists
[ref_id
].empty()) {
7801 GrfMsg(0, "FeatureTownName: definition 0x{:02X} doesn't exist, deactivating", ref_id
);
7802 DelGRFTownName(grfid
);
7803 DisableGrf(STR_NEWGRF_ERROR_INVALID_ID
);
7807 GrfMsg(6, "FeatureTownName: part {}, text {}, uses intermediate definition 0x{:02X} (with probability {})", partnum
, textnum
, ref_id
, part
.prob
& 0x7F);
7809 const char *text
= buf
->ReadString();
7810 part
.text
= TranslateTTDPatchCodes(grfid
, 0, false, text
);
7811 GrfMsg(6, "FeatureTownName: part {}, text {}, '{}' (with probability {})", partnum
, textnum
, part
.text
, part
.prob
);
7813 partlist
.maxprob
+= GB(part
.prob
, 0, 7);
7815 GrfMsg(6, "FeatureTownName: part {}, total probability {}", partnum
, partlist
.maxprob
);
7819 /** Action 0x10 - Define goto label */
7820 static void DefineGotoLabel(ByteReader
*buf
)
7822 /* <10> <label> [<comment>]
7824 * B label The label to define
7825 * V comment Optional comment - ignored */
7827 byte nfo_label
= buf
->ReadByte();
7829 _cur
.grffile
->labels
.emplace_back(nfo_label
, _cur
.nfo_line
, _cur
.file
->GetPos());
7831 GrfMsg(2, "DefineGotoLabel: GOTO target with label 0x{:02X}", nfo_label
);
7835 * Process a sound import from another GRF file.
7836 * @param sound Destination for sound.
7838 static void ImportGRFSound(SoundEntry
*sound
)
7840 const GRFFile
*file
;
7841 uint32_t grfid
= _cur
.file
->ReadDword();
7842 SoundID sound_id
= _cur
.file
->ReadWord();
7844 file
= GetFileByGRFID(grfid
);
7845 if (file
== nullptr || file
->sound_offset
== 0) {
7846 GrfMsg(1, "ImportGRFSound: Source file not available");
7850 if (sound_id
>= file
->num_sounds
) {
7851 GrfMsg(1, "ImportGRFSound: Sound effect {} is invalid", sound_id
);
7855 GrfMsg(2, "ImportGRFSound: Copying sound {} ({}) from file {:x}", sound_id
, file
->sound_offset
+ sound_id
, grfid
);
7857 *sound
= *GetSound(file
->sound_offset
+ sound_id
);
7859 /* Reset volume and priority, which TTDPatch doesn't copy */
7860 sound
->volume
= 128;
7861 sound
->priority
= 0;
7865 * Load a sound from a file.
7866 * @param offs File offset to read sound from.
7867 * @param sound Destination for sound.
7869 static void LoadGRFSound(size_t offs
, SoundEntry
*sound
)
7871 /* Set default volume and priority */
7872 sound
->volume
= 0x80;
7873 sound
->priority
= 0;
7875 if (offs
!= SIZE_MAX
) {
7876 /* Sound is present in the NewGRF. */
7877 sound
->file
= _cur
.file
;
7878 sound
->file_offset
= offs
;
7879 sound
->grf_container_ver
= _cur
.file
->GetContainerVersion();
7884 static void GRFSound(ByteReader
*buf
)
7888 * W num Number of sound files that follow */
7890 uint16_t num
= buf
->ReadWord();
7891 if (num
== 0) return;
7894 if (_cur
.grffile
->sound_offset
== 0) {
7895 _cur
.grffile
->sound_offset
= GetNumSounds();
7896 _cur
.grffile
->num_sounds
= num
;
7897 sound
= AllocateSound(num
);
7899 sound
= GetSound(_cur
.grffile
->sound_offset
);
7902 SpriteFile
&file
= *_cur
.file
;
7903 byte grf_container_version
= file
.GetContainerVersion();
7904 for (int i
= 0; i
< num
; i
++) {
7907 /* Check whether the index is in range. This might happen if multiple action 11 are present.
7908 * While this is invalid, we do not check for this. But we should prevent it from causing bigger trouble */
7909 bool invalid
= i
>= _cur
.grffile
->num_sounds
;
7911 size_t offs
= file
.GetPos();
7913 uint32_t len
= grf_container_version
>= 2 ? file
.ReadDword() : file
.ReadWord();
7914 byte type
= file
.ReadByte();
7916 if (grf_container_version
>= 2 && type
== 0xFD) {
7917 /* Reference to sprite section. */
7919 GrfMsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7920 file
.SkipBytes(len
);
7921 } else if (len
!= 4) {
7922 GrfMsg(1, "GRFSound: Invalid sprite section import");
7923 file
.SkipBytes(len
);
7925 uint32_t id
= file
.ReadDword();
7926 if (_cur
.stage
== GLS_INIT
) LoadGRFSound(GetGRFSpriteOffset(id
), sound
+ i
);
7932 GrfMsg(1, "GRFSound: Unexpected RealSprite found, skipping");
7934 SkipSpriteData(*_cur
.file
, type
, len
- 8);
7939 GrfMsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7940 file
.SkipBytes(len
);
7943 byte action
= file
.ReadByte();
7946 /* Allocate sound only in init stage. */
7947 if (_cur
.stage
== GLS_INIT
) {
7948 if (grf_container_version
>= 2) {
7949 GrfMsg(1, "GRFSound: Inline sounds are not supported for container version >= 2");
7951 LoadGRFSound(offs
, sound
+ i
);
7954 file
.SkipBytes(len
- 1); // already read <action>
7958 if (_cur
.stage
== GLS_ACTIVATION
) {
7959 /* XXX 'Action 0xFE' isn't really specified. It is only mentioned for
7960 * importing sounds, so this is probably all wrong... */
7961 if (file
.ReadByte() != 0) GrfMsg(1, "GRFSound: Import type mismatch");
7962 ImportGRFSound(sound
+ i
);
7964 file
.SkipBytes(len
- 1); // already read <action>
7969 GrfMsg(1, "GRFSound: Unexpected Action {:x} found, skipping", action
);
7970 file
.SkipBytes(len
- 1); // already read <action>
7976 /* Action 0x11 (SKIP) */
7977 static void SkipAct11(ByteReader
*buf
)
7981 * W num Number of sound files that follow */
7983 _cur
.skip_sprites
= buf
->ReadWord();
7985 GrfMsg(3, "SkipAct11: Skipping {} sprites", _cur
.skip_sprites
);
7989 static void LoadFontGlyph(ByteReader
*buf
)
7991 /* <12> <num_def> <font_size> <num_char> <base_char>
7993 * B num_def Number of definitions
7994 * B font_size Size of font (0 = normal, 1 = small, 2 = large, 3 = mono)
7995 * B num_char Number of consecutive glyphs
7996 * W base_char First character index */
7998 uint8_t num_def
= buf
->ReadByte();
8000 for (uint i
= 0; i
< num_def
; i
++) {
8001 FontSize size
= (FontSize
)buf
->ReadByte();
8002 uint8_t num_char
= buf
->ReadByte();
8003 uint16_t base_char
= buf
->ReadWord();
8005 if (size
>= FS_END
) {
8006 GrfMsg(1, "LoadFontGlyph: Size {} is not supported, ignoring", size
);
8009 GrfMsg(7, "LoadFontGlyph: Loading {} glyph(s) at 0x{:04X} for size {}", num_char
, base_char
, size
);
8011 for (uint c
= 0; c
< num_char
; c
++) {
8012 if (size
< FS_END
) SetUnicodeGlyph(size
, base_char
+ c
, _cur
.spriteid
);
8014 LoadNextSprite(_cur
.spriteid
++, *_cur
.file
, _cur
.nfo_line
);
8019 /** Action 0x12 (SKIP) */
8020 static void SkipAct12(ByteReader
*buf
)
8022 /* <12> <num_def> <font_size> <num_char> <base_char>
8024 * B num_def Number of definitions
8025 * B font_size Size of font (0 = normal, 1 = small, 2 = large)
8026 * B num_char Number of consecutive glyphs
8027 * W base_char First character index */
8029 uint8_t num_def
= buf
->ReadByte();
8031 for (uint i
= 0; i
< num_def
; i
++) {
8032 /* Ignore 'size' byte */
8035 /* Sum up number of characters */
8036 _cur
.skip_sprites
+= buf
->ReadByte();
8038 /* Ignore 'base_char' word */
8042 GrfMsg(3, "SkipAct12: Skipping {} sprites", _cur
.skip_sprites
);
8046 static void TranslateGRFStrings(ByteReader
*buf
)
8048 /* <13> <grfid> <num-ent> <offset> <text...>
8050 * 4*B grfid The GRFID of the file whose texts are to be translated
8051 * B num-ent Number of strings
8052 * W offset First text ID
8053 * S text... Zero-terminated strings */
8055 uint32_t grfid
= buf
->ReadDWord();
8056 const GRFConfig
*c
= GetGRFConfig(grfid
);
8057 if (c
== nullptr || (c
->status
!= GCS_INITIALISED
&& c
->status
!= GCS_ACTIVATED
)) {
8058 GrfMsg(7, "TranslateGRFStrings: GRFID 0x{:08X} unknown, skipping action 13", BSWAP32(grfid
));
8062 if (c
->status
== GCS_INITIALISED
) {
8063 /* If the file is not active but will be activated later, give an error
8064 * and disable this file. */
8065 GRFError
*error
= DisableGrf(STR_NEWGRF_ERROR_LOAD_AFTER
);
8067 error
->data
= GetString(STR_NEWGRF_ERROR_AFTER_TRANSLATED_FILE
);
8072 /* Since no language id is supplied for with version 7 and lower NewGRFs, this string has
8073 * to be added as a generic string, thus the language id of 0x7F. For this to work
8074 * new_scheme has to be true as well, which will also be implicitly the case for version 8
8075 * and higher. A language id of 0x7F will be overridden by a non-generic id, so this will
8076 * not change anything if a string has been provided specifically for this language. */
8077 byte language
= _cur
.grffile
->grf_version
>= 8 ? buf
->ReadByte() : 0x7F;
8078 byte num_strings
= buf
->ReadByte();
8079 uint16_t first_id
= buf
->ReadWord();
8081 if (!((first_id
>= 0xD000 && first_id
+ num_strings
<= 0xD400) || (first_id
>= 0xD800 && first_id
+ num_strings
<= 0xE000))) {
8082 GrfMsg(7, "TranslateGRFStrings: Attempting to set out-of-range string IDs in action 13 (first: 0x{:04X}, number: 0x{:02X})", first_id
, num_strings
);
8086 for (uint i
= 0; i
< num_strings
&& buf
->HasData(); i
++) {
8087 const char *string
= buf
->ReadString();
8089 if (StrEmpty(string
)) {
8090 GrfMsg(7, "TranslateGRFString: Ignoring empty string.");
8094 AddGRFString(grfid
, first_id
+ i
, language
, true, true, string
, STR_UNDEFINED
);
8098 /** Callback function for 'INFO'->'NAME' to add a translation to the newgrf name. */
8099 static bool ChangeGRFName(byte langid
, const char *str
)
8101 AddGRFTextToList(_cur
.grfconfig
->name
, langid
, _cur
.grfconfig
->ident
.grfid
, false, str
);
8105 /** Callback function for 'INFO'->'DESC' to add a translation to the newgrf description. */
8106 static bool ChangeGRFDescription(byte langid
, const char *str
)
8108 AddGRFTextToList(_cur
.grfconfig
->info
, langid
, _cur
.grfconfig
->ident
.grfid
, true, str
);
8112 /** Callback function for 'INFO'->'URL_' to set the newgrf url. */
8113 static bool ChangeGRFURL(byte langid
, const char *str
)
8115 AddGRFTextToList(_cur
.grfconfig
->url
, langid
, _cur
.grfconfig
->ident
.grfid
, false, str
);
8119 /** Callback function for 'INFO'->'NPAR' to set the number of valid parameters. */
8120 static bool ChangeGRFNumUsedParams(size_t len
, ByteReader
*buf
)
8123 GrfMsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'NPAR' but got {}, ignoring this field", len
);
8126 _cur
.grfconfig
->num_valid_params
= std::min(buf
->ReadByte(), ClampTo
<uint8_t>(_cur
.grfconfig
->param
.size()));
8131 /** Callback function for 'INFO'->'PALS' to set the number of valid parameters. */
8132 static bool ChangeGRFPalette(size_t len
, ByteReader
*buf
)
8135 GrfMsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'PALS' but got {}, ignoring this field", len
);
8138 char data
= buf
->ReadByte();
8139 GRFPalette pal
= GRFP_GRF_UNSET
;
8142 case 'A': pal
= GRFP_GRF_ANY
; break;
8143 case 'W': pal
= GRFP_GRF_WINDOWS
; break;
8144 case 'D': pal
= GRFP_GRF_DOS
; break;
8146 GrfMsg(2, "StaticGRFInfo: unexpected value '{:02X}' for 'INFO'->'PALS', ignoring this field", data
);
8149 if (pal
!= GRFP_GRF_UNSET
) {
8150 _cur
.grfconfig
->palette
&= ~GRFP_GRF_MASK
;
8151 _cur
.grfconfig
->palette
|= pal
;
8157 /** Callback function for 'INFO'->'BLTR' to set the blitter info. */
8158 static bool ChangeGRFBlitter(size_t len
, ByteReader
*buf
)
8161 GrfMsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'BLTR' but got {}, ignoring this field", len
);
8164 char data
= buf
->ReadByte();
8165 GRFPalette pal
= GRFP_BLT_UNSET
;
8167 case '8': pal
= GRFP_BLT_UNSET
; break;
8168 case '3': pal
= GRFP_BLT_32BPP
; break;
8170 GrfMsg(2, "StaticGRFInfo: unexpected value '{:02X}' for 'INFO'->'BLTR', ignoring this field", data
);
8173 _cur
.grfconfig
->palette
&= ~GRFP_BLT_MASK
;
8174 _cur
.grfconfig
->palette
|= pal
;
8179 /** Callback function for 'INFO'->'VRSN' to the version of the NewGRF. */
8180 static bool ChangeGRFVersion(size_t len
, ByteReader
*buf
)
8183 GrfMsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'VRSN' but got {}, ignoring this field", len
);
8186 /* Set min_loadable_version as well (default to minimal compatibility) */
8187 _cur
.grfconfig
->version
= _cur
.grfconfig
->min_loadable_version
= buf
->ReadDWord();
8192 /** Callback function for 'INFO'->'MINV' to the minimum compatible version of the NewGRF. */
8193 static bool ChangeGRFMinVersion(size_t len
, ByteReader
*buf
)
8196 GrfMsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'MINV' but got {}, ignoring this field", len
);
8199 _cur
.grfconfig
->min_loadable_version
= buf
->ReadDWord();
8200 if (_cur
.grfconfig
->version
== 0) {
8201 GrfMsg(2, "StaticGRFInfo: 'MINV' defined before 'VRSN' or 'VRSN' set to 0, ignoring this field");
8202 _cur
.grfconfig
->min_loadable_version
= 0;
8204 if (_cur
.grfconfig
->version
< _cur
.grfconfig
->min_loadable_version
) {
8205 GrfMsg(2, "StaticGRFInfo: 'MINV' defined as {}, limiting it to 'VRSN'", _cur
.grfconfig
->min_loadable_version
);
8206 _cur
.grfconfig
->min_loadable_version
= _cur
.grfconfig
->version
;
8212 static GRFParameterInfo
*_cur_parameter
; ///< The parameter which info is currently changed by the newgrf.
8214 /** Callback function for 'INFO'->'PARAM'->param_num->'NAME' to set the name of a parameter. */
8215 static bool ChangeGRFParamName(byte langid
, const char *str
)
8217 AddGRFTextToList(_cur_parameter
->name
, langid
, _cur
.grfconfig
->ident
.grfid
, false, str
);
8221 /** Callback function for 'INFO'->'PARAM'->param_num->'DESC' to set the description of a parameter. */
8222 static bool ChangeGRFParamDescription(byte langid
, const char *str
)
8224 AddGRFTextToList(_cur_parameter
->desc
, langid
, _cur
.grfconfig
->ident
.grfid
, true, str
);
8228 /** Callback function for 'INFO'->'PARAM'->param_num->'TYPE' to set the typeof a parameter. */
8229 static bool ChangeGRFParamType(size_t len
, ByteReader
*buf
)
8232 GrfMsg(2, "StaticGRFInfo: expected 1 byte for 'INFO'->'PARA'->'TYPE' but got {}, ignoring this field", len
);
8235 GRFParameterType type
= (GRFParameterType
)buf
->ReadByte();
8236 if (type
< PTYPE_END
) {
8237 _cur_parameter
->type
= type
;
8239 GrfMsg(3, "StaticGRFInfo: unknown parameter type {}, ignoring this field", type
);
8245 /** Callback function for 'INFO'->'PARAM'->param_num->'LIMI' to set the min/max value of a parameter. */
8246 static bool ChangeGRFParamLimits(size_t len
, ByteReader
*buf
)
8248 if (_cur_parameter
->type
!= PTYPE_UINT_ENUM
) {
8249 GrfMsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' is only valid for parameters with type uint/enum, ignoring this field");
8251 } else if (len
!= 8) {
8252 GrfMsg(2, "StaticGRFInfo: expected 8 bytes for 'INFO'->'PARA'->'LIMI' but got {}, ignoring this field", len
);
8255 uint32_t min_value
= buf
->ReadDWord();
8256 uint32_t max_value
= buf
->ReadDWord();
8257 if (min_value
<= max_value
) {
8258 _cur_parameter
->min_value
= min_value
;
8259 _cur_parameter
->max_value
= max_value
;
8261 GrfMsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' values are incoherent, ignoring this field");
8267 /** Callback function for 'INFO'->'PARAM'->param_num->'MASK' to set the parameter and bits to use. */
8268 static bool ChangeGRFParamMask(size_t len
, ByteReader
*buf
)
8270 if (len
< 1 || len
> 3) {
8271 GrfMsg(2, "StaticGRFInfo: expected 1 to 3 bytes for 'INFO'->'PARA'->'MASK' but got {}, ignoring this field", len
);
8274 byte param_nr
= buf
->ReadByte();
8275 if (param_nr
>= _cur
.grfconfig
->param
.size()) {
8276 GrfMsg(2, "StaticGRFInfo: invalid parameter number in 'INFO'->'PARA'->'MASK', param {}, ignoring this field", param_nr
);
8279 _cur_parameter
->param_nr
= param_nr
;
8280 if (len
>= 2) _cur_parameter
->first_bit
= std::min
<byte
>(buf
->ReadByte(), 31);
8281 if (len
>= 3) _cur_parameter
->num_bit
= std::min
<byte
>(buf
->ReadByte(), 32 - _cur_parameter
->first_bit
);
8288 /** Callback function for 'INFO'->'PARAM'->param_num->'DFLT' to set the default value. */
8289 static bool ChangeGRFParamDefault(size_t len
, ByteReader
*buf
)
8292 GrfMsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'PARA'->'DEFA' but got {}, ignoring this field", len
);
8295 _cur_parameter
->def_value
= buf
->ReadDWord();
8297 _cur
.grfconfig
->has_param_defaults
= true;
8301 typedef bool (*DataHandler
)(size_t, ByteReader
*); ///< Type of callback function for binary nodes
8302 typedef bool (*TextHandler
)(byte
, const char *str
); ///< Type of callback function for text nodes
8303 typedef bool (*BranchHandler
)(ByteReader
*); ///< Type of callback function for branch nodes
8306 * Data structure to store the allowed id/type combinations for action 14. The
8307 * data can be represented as a tree with 3 types of nodes:
8308 * 1. Branch nodes (identified by 'C' for choice).
8309 * 2. Binary leaf nodes (identified by 'B').
8310 * 3. Text leaf nodes (identified by 'T').
8312 struct AllowedSubtags
{
8313 /** Create empty subtags object used to identify the end of a list. */
8320 * Create a binary leaf node.
8321 * @param id The id for this node.
8322 * @param handler The callback function to call.
8324 AllowedSubtags(uint32_t id
, DataHandler handler
) :
8328 this->handler
.data
= handler
;
8332 * Create a text leaf node.
8333 * @param id The id for this node.
8334 * @param handler The callback function to call.
8336 AllowedSubtags(uint32_t id
, TextHandler handler
) :
8340 this->handler
.text
= handler
;
8344 * Create a branch node with a callback handler
8345 * @param id The id for this node.
8346 * @param handler The callback function to call.
8348 AllowedSubtags(uint32_t id
, BranchHandler handler
) :
8352 this->handler
.call_handler
= true;
8353 this->handler
.u
.branch
= handler
;
8357 * Create a branch node with a list of sub-nodes.
8358 * @param id The id for this node.
8359 * @param subtags Array with all valid subtags.
8361 AllowedSubtags(uint32_t id
, AllowedSubtags
*subtags
) :
8365 this->handler
.call_handler
= false;
8366 this->handler
.u
.subtags
= subtags
;
8369 uint32_t id
; ///< The identifier for this node
8370 byte type
; ///< The type of the node, must be one of 'C', 'B' or 'T'.
8372 DataHandler data
; ///< Callback function for a binary node, only valid if type == 'B'.
8373 TextHandler text
; ///< Callback function for a text node, only valid if type == 'T'.
8376 BranchHandler branch
; ///< Callback function for a branch node, only valid if type == 'C' && call_handler.
8377 AllowedSubtags
*subtags
; ///< Pointer to a list of subtags, only valid if type == 'C' && !call_handler.
8379 bool call_handler
; ///< True if there is a callback function for this node, false if there is a list of subnodes.
8384 static bool SkipUnknownInfo(ByteReader
*buf
, byte type
);
8385 static bool HandleNodes(ByteReader
*buf
, AllowedSubtags
*tags
);
8388 * Callback function for 'INFO'->'PARA'->param_num->'VALU' to set the names
8389 * of some parameter values (type uint/enum) or the names of some bits
8390 * (type bitmask). In both cases the format is the same:
8391 * Each subnode should be a text node with the value/bit number as id.
8393 static bool ChangeGRFParamValueNames(ByteReader
*buf
)
8395 byte type
= buf
->ReadByte();
8397 uint32_t id
= buf
->ReadDWord();
8398 if (type
!= 'T' || id
> _cur_parameter
->max_value
) {
8399 GrfMsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA'->param_num->'VALU' should have type 't' and the value/bit number as id");
8400 if (!SkipUnknownInfo(buf
, type
)) return false;
8401 type
= buf
->ReadByte();
8405 byte langid
= buf
->ReadByte();
8406 const char *name_string
= buf
->ReadString();
8408 auto val_name
= _cur_parameter
->value_names
.find(id
);
8409 if (val_name
!= _cur_parameter
->value_names
.end()) {
8410 AddGRFTextToList(val_name
->second
, langid
, _cur
.grfconfig
->ident
.grfid
, false, name_string
);
8413 AddGRFTextToList(list
, langid
, _cur
.grfconfig
->ident
.grfid
, false, name_string
);
8414 _cur_parameter
->value_names
[id
] = list
;
8417 type
= buf
->ReadByte();
8422 /** Action14 parameter tags */
8423 AllowedSubtags _tags_parameters
[] = {
8424 AllowedSubtags('NAME', ChangeGRFParamName
),
8425 AllowedSubtags('DESC', ChangeGRFParamDescription
),
8426 AllowedSubtags('TYPE', ChangeGRFParamType
),
8427 AllowedSubtags('LIMI', ChangeGRFParamLimits
),
8428 AllowedSubtags('MASK', ChangeGRFParamMask
),
8429 AllowedSubtags('VALU', ChangeGRFParamValueNames
),
8430 AllowedSubtags('DFLT', ChangeGRFParamDefault
),
8435 * Callback function for 'INFO'->'PARA' to set extra information about the
8436 * parameters. Each subnode of 'INFO'->'PARA' should be a branch node with
8437 * the parameter number as id. The first parameter has id 0. The maximum
8438 * parameter that can be changed is set by 'INFO'->'NPAR' which defaults to 80.
8440 static bool HandleParameterInfo(ByteReader
*buf
)
8442 byte type
= buf
->ReadByte();
8444 uint32_t id
= buf
->ReadDWord();
8445 if (type
!= 'C' || id
>= _cur
.grfconfig
->num_valid_params
) {
8446 GrfMsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA' should have type 'C' and their parameter number as id");
8447 if (!SkipUnknownInfo(buf
, type
)) return false;
8448 type
= buf
->ReadByte();
8452 if (id
>= _cur
.grfconfig
->param_info
.size()) {
8453 _cur
.grfconfig
->param_info
.resize(id
+ 1);
8455 if (!_cur
.grfconfig
->param_info
[id
].has_value()) {
8456 _cur
.grfconfig
->param_info
[id
] = GRFParameterInfo(id
);
8458 _cur_parameter
= &_cur
.grfconfig
->param_info
[id
].value();
8459 /* Read all parameter-data and process each node. */
8460 if (!HandleNodes(buf
, _tags_parameters
)) return false;
8461 type
= buf
->ReadByte();
8466 /** Action14 tags for the INFO node */
8467 AllowedSubtags _tags_info
[] = {
8468 AllowedSubtags('NAME', ChangeGRFName
),
8469 AllowedSubtags('DESC', ChangeGRFDescription
),
8470 AllowedSubtags('URL_', ChangeGRFURL
),
8471 AllowedSubtags('NPAR', ChangeGRFNumUsedParams
),
8472 AllowedSubtags('PALS', ChangeGRFPalette
),
8473 AllowedSubtags('BLTR', ChangeGRFBlitter
),
8474 AllowedSubtags('VRSN', ChangeGRFVersion
),
8475 AllowedSubtags('MINV', ChangeGRFMinVersion
),
8476 AllowedSubtags('PARA', HandleParameterInfo
),
8480 /** Action14 root tags */
8481 AllowedSubtags _tags_root
[] = {
8482 AllowedSubtags('INFO', _tags_info
),
8488 * Try to skip the current node and all subnodes (if it's a branch node).
8489 * @param buf Buffer.
8490 * @param type The node type to skip.
8491 * @return True if we could skip the node, false if an error occurred.
8493 static bool SkipUnknownInfo(ByteReader
*buf
, byte type
)
8495 /* type and id are already read */
8498 byte new_type
= buf
->ReadByte();
8499 while (new_type
!= 0) {
8500 buf
->ReadDWord(); // skip the id
8501 if (!SkipUnknownInfo(buf
, new_type
)) return false;
8502 new_type
= buf
->ReadByte();
8508 buf
->ReadByte(); // lang
8509 buf
->ReadString(); // actual text
8513 uint16_t size
= buf
->ReadWord();
8526 * Handle the nodes of an Action14
8527 * @param type Type of node.
8529 * @param buf Buffer.
8530 * @param subtags Allowed subtags.
8531 * @return Whether all tags could be handled.
8533 static bool HandleNode(byte type
, uint32_t id
, ByteReader
*buf
, AllowedSubtags subtags
[])
8536 AllowedSubtags
*tag
;
8537 while ((tag
= &subtags
[i
++])->type
!= 0) {
8538 if (tag
->id
!= BSWAP32(id
) || tag
->type
!= type
) continue;
8540 default: NOT_REACHED();
8543 byte langid
= buf
->ReadByte();
8544 return tag
->handler
.text(langid
, buf
->ReadString());
8548 size_t len
= buf
->ReadWord();
8549 if (buf
->Remaining() < len
) return false;
8550 return tag
->handler
.data(len
, buf
);
8554 if (tag
->handler
.call_handler
) {
8555 return tag
->handler
.u
.branch(buf
);
8557 return HandleNodes(buf
, tag
->handler
.u
.subtags
);
8561 GrfMsg(2, "StaticGRFInfo: unknown type/id combination found, type={:c}, id={:x}", type
, id
);
8562 return SkipUnknownInfo(buf
, type
);
8566 * Handle the contents of a 'C' choice of an Action14
8567 * @param buf Buffer.
8568 * @param subtags List of subtags.
8569 * @return Whether the nodes could all be handled.
8571 static bool HandleNodes(ByteReader
*buf
, AllowedSubtags subtags
[])
8573 byte type
= buf
->ReadByte();
8575 uint32_t id
= buf
->ReadDWord();
8576 if (!HandleNode(type
, id
, buf
, subtags
)) return false;
8577 type
= buf
->ReadByte();
8583 * Handle Action 0x14
8584 * @param buf Buffer.
8586 static void StaticGRFInfo(ByteReader
*buf
)
8588 /* <14> <type> <id> <text/data...> */
8589 HandleNodes(buf
, _tags_root
);
8593 * Set the current NewGRF as unsafe for static use
8594 * @note Used during safety scan on unsafe actions.
8596 static void GRFUnsafe(ByteReader
*)
8598 SetBit(_cur
.grfconfig
->flags
, GCF_UNSAFE
);
8600 /* Skip remainder of GRF */
8601 _cur
.skip_sprites
= -1;
8605 /** Initialize the TTDPatch flags */
8606 static void InitializeGRFSpecial()
8608 _ttdpatch_flags
[0] = ((_settings_game
.station
.never_expire_airports
? 1U : 0U) << 0x0C) // keepsmallairport
8609 | (1U << 0x0D) // newairports
8610 | (1U << 0x0E) // largestations
8611 | ((_settings_game
.construction
.max_bridge_length
> 16 ? 1U : 0U) << 0x0F) // longbridges
8612 | (0U << 0x10) // loadtime
8613 | (1U << 0x12) // presignals
8614 | (1U << 0x13) // extpresignals
8615 | ((_settings_game
.vehicle
.never_expire_vehicles
? 1U : 0U) << 0x16) // enginespersist
8616 | (1U << 0x1B) // multihead
8617 | (1U << 0x1D) // lowmemory
8618 | (1U << 0x1E); // generalfixes
8620 _ttdpatch_flags
[1] = ((_settings_game
.economy
.station_noise_level
? 1U : 0U) << 0x07) // moreairports - based on units of noise
8621 | (1U << 0x08) // mammothtrains
8622 | (1U << 0x09) // trainrefit
8623 | (0U << 0x0B) // subsidiaries
8624 | ((_settings_game
.order
.gradual_loading
? 1U : 0U) << 0x0C) // gradualloading
8625 | (1U << 0x12) // unifiedmaglevmode - set bit 0 mode. Not revelant to OTTD
8626 | (1U << 0x13) // unifiedmaglevmode - set bit 1 mode
8627 | (1U << 0x14) // bridgespeedlimits
8628 | (1U << 0x16) // eternalgame
8629 | (1U << 0x17) // newtrains
8630 | (1U << 0x18) // newrvs
8631 | (1U << 0x19) // newships
8632 | (1U << 0x1A) // newplanes
8633 | ((_settings_game
.construction
.train_signal_side
== 1 ? 1U : 0U) << 0x1B) // signalsontrafficside
8634 | ((_settings_game
.vehicle
.disable_elrails
? 0U : 1U) << 0x1C); // electrifiedrailway
8636 _ttdpatch_flags
[2] = (1U << 0x01) // loadallgraphics - obsolote
8637 | (1U << 0x03) // semaphores
8638 | (1U << 0x0A) // newobjects
8639 | (0U << 0x0B) // enhancedgui
8640 | (0U << 0x0C) // newagerating
8641 | ((_settings_game
.construction
.build_on_slopes
? 1U : 0U) << 0x0D) // buildonslopes
8642 | (1U << 0x0E) // fullloadany
8643 | (1U << 0x0F) // planespeed
8644 | (0U << 0x10) // moreindustriesperclimate - obsolete
8645 | (0U << 0x11) // moretoylandfeatures
8646 | (1U << 0x12) // newstations
8647 | (1U << 0x13) // tracktypecostdiff
8648 | (1U << 0x14) // manualconvert
8649 | ((_settings_game
.construction
.build_on_slopes
? 1U : 0U) << 0x15) // buildoncoasts
8650 | (1U << 0x16) // canals
8651 | (1U << 0x17) // newstartyear
8652 | ((_settings_game
.vehicle
.freight_trains
> 1 ? 1U : 0U) << 0x18) // freighttrains
8653 | (1U << 0x19) // newhouses
8654 | (1U << 0x1A) // newbridges
8655 | (1U << 0x1B) // newtownnames
8656 | (1U << 0x1C) // moreanimation
8657 | ((_settings_game
.vehicle
.wagon_speed_limits
? 1U : 0U) << 0x1D) // wagonspeedlimits
8658 | (1U << 0x1E) // newshistory
8659 | (0U << 0x1F); // custombridgeheads
8661 _ttdpatch_flags
[3] = (0U << 0x00) // newcargodistribution
8662 | (1U << 0x01) // windowsnap
8663 | ((_settings_game
.economy
.allow_town_roads
|| _generating_world
? 0U : 1U) << 0x02) // townbuildnoroad
8664 | (1U << 0x03) // pathbasedsignalling
8665 | (0U << 0x04) // aichoosechance
8666 | (1U << 0x05) // resolutionwidth
8667 | (1U << 0x06) // resolutionheight
8668 | (1U << 0x07) // newindustries
8669 | ((_settings_game
.order
.improved_load
? 1U : 0U) << 0x08) // fifoloading
8670 | (0U << 0x09) // townroadbranchprob
8671 | (0U << 0x0A) // tempsnowline
8672 | (1U << 0x0B) // newcargo
8673 | (1U << 0x0C) // enhancemultiplayer
8674 | (1U << 0x0D) // onewayroads
8675 | (1U << 0x0E) // irregularstations
8676 | (1U << 0x0F) // statistics
8677 | (1U << 0x10) // newsounds
8678 | (1U << 0x11) // autoreplace
8679 | (1U << 0x12) // autoslope
8680 | (0U << 0x13) // followvehicle
8681 | (1U << 0x14) // trams
8682 | (0U << 0x15) // enhancetunnels
8683 | (1U << 0x16) // shortrvs
8684 | (1U << 0x17) // articulatedrvs
8685 | ((_settings_game
.vehicle
.dynamic_engines
? 1U : 0U) << 0x18) // dynamic engines
8686 | (1U << 0x1E) // variablerunningcosts
8687 | (1U << 0x1F); // any switch is on
8689 _ttdpatch_flags
[4] = (1U << 0x00) // larger persistent storage
8690 | ((_settings_game
.economy
.inflation
? 1U : 0U) << 0x01) // inflation is on
8691 | (1U << 0x02); // extended string range
8694 /** Reset and clear all NewGRF stations */
8695 static void ResetCustomStations()
8697 for (GRFFile
* const file
: _grf_files
) {
8698 file
->stations
.clear();
8702 /** Reset and clear all NewGRF houses */
8703 static void ResetCustomHouses()
8705 for (GRFFile
* const file
: _grf_files
) {
8706 file
->housespec
.clear();
8710 /** Reset and clear all NewGRF airports */
8711 static void ResetCustomAirports()
8713 for (GRFFile
* const file
: _grf_files
) {
8714 for (auto &as
: file
->airportspec
) {
8715 if (as
!= nullptr) {
8716 /* We need to remove the tiles layouts */
8717 for (int j
= 0; j
< as
->num_table
; j
++) {
8718 /* remove the individual layouts */
8722 free(as
->depot_table
);
8726 file
->airportspec
.clear();
8727 file
->airtspec
.clear();
8731 /** Reset and clear all NewGRF industries */
8732 static void ResetCustomIndustries()
8734 for (GRFFile
* const file
: _grf_files
) {
8735 file
->industryspec
.clear();
8736 file
->indtspec
.clear();
8740 /** Reset and clear all NewObjects */
8741 static void ResetCustomObjects()
8743 for (GRFFile
* const file
: _grf_files
) {
8744 file
->objectspec
.clear();
8748 static void ResetCustomRoadStops()
8750 for (auto file
: _grf_files
) {
8751 file
->roadstops
.clear();
8755 /** Reset and clear all NewGRFs */
8756 static void ResetNewGRF()
8758 for (GRFFile
* const file
: _grf_files
) {
8763 _cur
.grffile
= nullptr;
8766 /** Clear all NewGRF errors */
8767 static void ResetNewGRFErrors()
8769 for (GRFConfig
*c
= _grfconfig
; c
!= nullptr; c
= c
->next
) {
8775 * Reset all NewGRF loaded data
8777 void ResetNewGRFData()
8780 CleanUpGRFTownNames();
8782 /* Copy/reset original engine info data */
8785 /* Copy/reset original bridge info data */
8788 /* Reset rail type information */
8791 /* Copy/reset original road type info data */
8794 /* Allocate temporary refit/cargo class data */
8795 _gted
.resize(Engine::GetPoolSize());
8797 /* Fill rail type label temporary data for default trains */
8798 for (const Engine
*e
: Engine::IterateType(VEH_TRAIN
)) {
8799 _gted
[e
->index
].railtypelabel
= GetRailTypeInfo(e
->u
.rail
.railtype
)->label
;
8802 /* Reset GRM reservations */
8803 memset(&_grm_engines
, 0, sizeof(_grm_engines
));
8804 memset(&_grm_cargoes
, 0, sizeof(_grm_cargoes
));
8806 /* Reset generic feature callback lists */
8807 ResetGenericCallbacks();
8809 /* Reset price base data */
8810 ResetPriceBaseMultipliers();
8812 /* Reset the curencies array */
8815 /* Reset the house array */
8816 ResetCustomHouses();
8819 /* Reset the industries structures*/
8820 ResetCustomIndustries();
8823 /* Reset the objects. */
8824 ObjectClass::Reset();
8825 ResetCustomObjects();
8828 /* Reset station classes */
8829 StationClass::Reset();
8830 ResetCustomStations();
8832 /* Reset airport-related structures */
8833 AirportClass::Reset();
8834 ResetCustomAirports();
8835 AirportSpec::ResetAirports();
8836 AirportTileSpec::ResetAirportTiles();
8838 /* Reset road stop classes */
8839 RoadStopClass::Reset();
8840 ResetCustomRoadStops();
8842 /* Reset canal sprite groups and flags */
8843 memset(_water_feature
, 0, sizeof(_water_feature
));
8845 /* Reset the snowline table. */
8848 /* Reset NewGRF files */
8851 /* Reset NewGRF errors. */
8852 ResetNewGRFErrors();
8854 /* Set up the default cargo types */
8855 SetupCargoForClimate(_settings_game
.game_creation
.landscape
);
8857 /* Reset misc GRF features and train list display variables */
8858 _misc_grf_features
= 0;
8860 _loaded_newgrf_features
.has_2CC
= false;
8861 _loaded_newgrf_features
.used_liveries
= 1 << LS_DEFAULT
;
8862 _loaded_newgrf_features
.shore
= SHORE_REPLACE_NONE
;
8863 _loaded_newgrf_features
.tram
= TRAMWAY_REPLACE_DEPOT_NONE
;
8865 /* Clear all GRF overrides */
8866 _grf_id_overrides
.clear();
8868 InitializeSoundPool();
8869 _spritegroup_pool
.CleanPool();
8873 * Reset NewGRF data which is stored persistently in savegames.
8875 void ResetPersistentNewGRFData()
8877 /* Reset override managers */
8878 _engine_mngr
.ResetToDefaultMapping();
8879 _house_mngr
.ResetMapping();
8880 _industry_mngr
.ResetMapping();
8881 _industile_mngr
.ResetMapping();
8882 _airport_mngr
.ResetMapping();
8883 _airporttile_mngr
.ResetMapping();
8887 * Construct the Cargo Mapping
8888 * @note This is the reverse of a cargo translation table
8890 static void BuildCargoTranslationMap()
8892 _cur
.grffile
->cargo_map
.fill(UINT8_MAX
);
8894 for (const CargoSpec
*cs
: CargoSpec::Iterate()) {
8895 if (!cs
->IsValid()) continue;
8897 if (_cur
.grffile
->cargo_list
.empty()) {
8898 /* Default translation table, so just a straight mapping to bitnum */
8899 _cur
.grffile
->cargo_map
[cs
->Index()] = cs
->bitnum
;
8901 /* Check the translation table for this cargo's label */
8902 int idx
= find_index(_cur
.grffile
->cargo_list
, {cs
->label
});
8903 if (idx
>= 0) _cur
.grffile
->cargo_map
[cs
->Index()] = idx
;
8909 * Prepare loading a NewGRF file with its config
8910 * @param config The NewGRF configuration struct with name, id, parameters and alike.
8912 static void InitNewGRFFile(const GRFConfig
*config
)
8914 GRFFile
*newfile
= GetFileByFilename(config
->filename
);
8915 if (newfile
!= nullptr) {
8916 /* We already loaded it once. */
8917 _cur
.grffile
= newfile
;
8921 newfile
= new GRFFile(config
);
8922 _grf_files
.push_back(_cur
.grffile
= newfile
);
8926 * Constructor for GRFFile
8927 * @param config GRFConfig to copy name, grfid and parameters from.
8929 GRFFile::GRFFile(const GRFConfig
*config
)
8931 this->filename
= config
->filename
;
8932 this->grfid
= config
->ident
.grfid
;
8934 /* Initialise local settings to defaults */
8935 this->traininfo_vehicle_pitch
= 0;
8936 this->traininfo_vehicle_width
= TRAININFO_DEFAULT_VEHICLE_WIDTH
;
8938 /* Mark price_base_multipliers as 'not set' */
8939 for (Price i
= PR_BEGIN
; i
< PR_END
; i
++) {
8940 this->price_base_multipliers
[i
] = INVALID_PRICE_MODIFIER
;
8943 /* Initialise rail type map with default rail types */
8944 std::fill(std::begin(this->railtype_map
), std::end(this->railtype_map
), INVALID_RAILTYPE
);
8945 this->railtype_map
[0] = RAILTYPE_RAIL
;
8946 this->railtype_map
[1] = RAILTYPE_ELECTRIC
;
8947 this->railtype_map
[2] = RAILTYPE_MONO
;
8948 this->railtype_map
[3] = RAILTYPE_MAGLEV
;
8950 /* Initialise road type map with default road types */
8951 std::fill(std::begin(this->roadtype_map
), std::end(this->roadtype_map
), INVALID_ROADTYPE
);
8952 this->roadtype_map
[0] = ROADTYPE_ROAD
;
8954 /* Initialise tram type map with default tram types */
8955 std::fill(std::begin(this->tramtype_map
), std::end(this->tramtype_map
), INVALID_ROADTYPE
);
8956 this->tramtype_map
[0] = ROADTYPE_TRAM
;
8958 /* Copy the initial parameter list
8959 * 'Uninitialised' parameters are zeroed as that is their default value when dynamically creating them. */
8960 this->param
= config
->param
;
8961 this->param_end
= config
->num_params
;
8966 delete[] this->language_map
;
8970 * Find first cargo label that exists and is active from a list of cargo labels.
8971 * @param labels List of cargo labels.
8972 * @returns First cargo label in list that exists, or CT_INVALID if none exist.
8974 static CargoLabel
GetActiveCargoLabel(const std::initializer_list
<CargoLabel
> &labels
)
8976 for (const CargoLabel
&label
: labels
) {
8977 CargoID cid
= GetCargoIDByLabel(label
);
8978 if (cid
!= INVALID_CARGO
) return label
;
8984 * Get active cargo label from either a cargo label or climate-dependent mixed cargo type.
8985 * @param label Cargo label or climate-dependent mixed cargo type.
8986 * @returns Active cargo label, or CT_INVALID if cargo label is not active.
8988 static CargoLabel
GetActiveCargoLabel(const std::variant
<CargoLabel
, MixedCargoType
> &label
)
8990 if (std::holds_alternative
<CargoLabel
>(label
)) return std::get
<CargoLabel
>(label
);
8991 if (std::holds_alternative
<MixedCargoType
>(label
)) {
8992 switch (std::get
<MixedCargoType
>(label
)) {
8993 case MCT_LIVESTOCK_FRUIT
: return GetActiveCargoLabel({CT_LIVESTOCK
, CT_FRUIT
});
8994 case MCT_GRAIN_WHEAT_MAIZE
: return GetActiveCargoLabel({CT_GRAIN
, CT_WHEAT
, CT_MAIZE
});
8995 case MCT_VALUABLES_GOLD_DIAMONDS
: return GetActiveCargoLabel({CT_VALUABLES
, CT_GOLD
, CT_DIAMONDS
});
8996 default: NOT_REACHED();
9003 * Precalculate refit masks from cargo classes for all vehicles.
9005 static void CalculateRefitMasks()
9007 CargoTypes original_known_cargoes
= 0;
9008 for (CargoID cid
= 0; cid
!= NUM_CARGO
; ++cid
) {
9009 if (IsDefaultCargo(cid
)) SetBit(original_known_cargoes
, cid
);
9012 for (Engine
*e
: Engine::Iterate()) {
9013 EngineID engine
= e
->index
;
9014 EngineInfo
*ei
= &e
->info
;
9015 bool only_defaultcargo
; ///< Set if the vehicle shall carry only the default cargo
9017 /* Apply default cargo translation map if cargo type hasn't been set, either explicitly or by aircraft cargo handling. */
9018 if (!IsValidCargoID(e
->info
.cargo_type
)) {
9019 e
->info
.cargo_type
= GetCargoIDByLabel(GetActiveCargoLabel(e
->info
.cargo_label
));
9022 /* If the NewGRF did not set any cargo properties, we apply default values. */
9023 if (_gted
[engine
].defaultcargo_grf
== nullptr) {
9024 /* If the vehicle has any capacity, apply the default refit masks */
9025 if (e
->type
!= VEH_TRAIN
|| e
->u
.rail
.capacity
!= 0) {
9026 static constexpr byte T
= 1 << LT_TEMPERATE
;
9027 static constexpr byte A
= 1 << LT_ARCTIC
;
9028 static constexpr byte S
= 1 << LT_TROPIC
;
9029 static constexpr byte Y
= 1 << LT_TOYLAND
;
9030 static const struct DefaultRefitMasks
{
9032 CargoLabel cargo_label
;
9033 CargoTypes cargo_allowed
;
9034 CargoTypes cargo_disallowed
;
9035 } _default_refit_masks
[] = {
9036 {T
| A
| S
| Y
, CT_PASSENGERS
, CC_PASSENGERS
, 0},
9037 {T
| A
| S
, CT_MAIL
, CC_MAIL
, 0},
9038 {T
| A
| S
, CT_VALUABLES
, CC_ARMOURED
, CC_LIQUID
},
9039 { Y
, CT_MAIL
, CC_MAIL
| CC_ARMOURED
, CC_LIQUID
},
9040 {T
| A
, CT_COAL
, CC_BULK
, 0},
9041 { S
, CT_COPPER_ORE
, CC_BULK
, 0},
9042 { Y
, CT_SUGAR
, CC_BULK
, 0},
9043 {T
| A
| S
, CT_OIL
, CC_LIQUID
, 0},
9044 { Y
, CT_COLA
, CC_LIQUID
, 0},
9045 {T
, CT_GOODS
, CC_PIECE_GOODS
| CC_EXPRESS
, CC_LIQUID
| CC_PASSENGERS
},
9046 { A
| S
, CT_GOODS
, CC_PIECE_GOODS
| CC_EXPRESS
, CC_LIQUID
| CC_PASSENGERS
| CC_REFRIGERATED
},
9047 { A
| S
, CT_FOOD
, CC_REFRIGERATED
, 0},
9048 { Y
, CT_CANDY
, CC_PIECE_GOODS
| CC_EXPRESS
, CC_LIQUID
| CC_PASSENGERS
},
9051 if (e
->type
== VEH_AIRCRAFT
) {
9052 /* Aircraft default to "light" cargoes */
9053 _gted
[engine
].cargo_allowed
= CC_PASSENGERS
| CC_MAIL
| CC_ARMOURED
| CC_EXPRESS
;
9054 _gted
[engine
].cargo_disallowed
= CC_LIQUID
;
9055 } else if (e
->type
== VEH_SHIP
) {
9056 CargoLabel label
= GetActiveCargoLabel(ei
->cargo_label
);
9057 switch (label
.base()) {
9058 case CT_PASSENGERS
.base():
9060 _gted
[engine
].cargo_allowed
= CC_PASSENGERS
;
9061 _gted
[engine
].cargo_disallowed
= 0;
9065 _gted
[engine
].cargo_allowed
= CC_LIQUID
;
9066 _gted
[engine
].cargo_disallowed
= 0;
9070 if (_settings_game
.game_creation
.landscape
== LT_TOYLAND
) {
9071 /* No tanker in toyland :( */
9072 _gted
[engine
].cargo_allowed
= CC_MAIL
| CC_ARMOURED
| CC_EXPRESS
| CC_BULK
| CC_PIECE_GOODS
| CC_LIQUID
;
9073 _gted
[engine
].cargo_disallowed
= CC_PASSENGERS
;
9075 _gted
[engine
].cargo_allowed
= CC_MAIL
| CC_ARMOURED
| CC_EXPRESS
| CC_BULK
| CC_PIECE_GOODS
;
9076 _gted
[engine
].cargo_disallowed
= CC_LIQUID
| CC_PASSENGERS
;
9080 e
->u
.ship
.old_refittable
= true;
9081 } else if (e
->type
== VEH_TRAIN
&& e
->u
.rail
.railveh_type
!= RAILVEH_WAGON
) {
9082 /* Train engines default to all cargoes, so you can build single-cargo consists with fast engines.
9083 * Trains loading multiple cargoes may start stations accepting unwanted cargoes. */
9084 _gted
[engine
].cargo_allowed
= CC_PASSENGERS
| CC_MAIL
| CC_ARMOURED
| CC_EXPRESS
| CC_BULK
| CC_PIECE_GOODS
| CC_LIQUID
;
9085 _gted
[engine
].cargo_disallowed
= 0;
9087 /* Train wagons and road vehicles are classified by their default cargo type */
9088 CargoLabel label
= GetActiveCargoLabel(ei
->cargo_label
);
9089 for (const auto &drm
: _default_refit_masks
) {
9090 if (!HasBit(drm
.climate
, _settings_game
.game_creation
.landscape
)) continue;
9091 if (drm
.cargo_label
!= label
) continue;
9093 _gted
[engine
].cargo_allowed
= drm
.cargo_allowed
;
9094 _gted
[engine
].cargo_disallowed
= drm
.cargo_disallowed
;
9098 /* All original cargoes have specialised vehicles, so exclude them */
9099 _gted
[engine
].ctt_exclude_mask
= original_known_cargoes
;
9102 _gted
[engine
].UpdateRefittability(_gted
[engine
].cargo_allowed
!= 0);
9104 if (IsValidCargoID(ei
->cargo_type
)) ClrBit(_gted
[engine
].ctt_exclude_mask
, ei
->cargo_type
);
9107 /* Compute refittability */
9109 CargoTypes mask
= 0;
9110 CargoTypes not_mask
= 0;
9111 CargoTypes xor_mask
= ei
->refit_mask
;
9113 /* If the original masks set by the grf are zero, the vehicle shall only carry the default cargo.
9114 * Note: After applying the translations, the vehicle may end up carrying no defined cargo. It becomes unavailable in that case. */
9115 only_defaultcargo
= _gted
[engine
].refittability
!= GRFTempEngineData::NONEMPTY
;
9117 if (_gted
[engine
].cargo_allowed
!= 0) {
9118 /* Build up the list of cargo types from the set cargo classes. */
9119 for (const CargoSpec
*cs
: CargoSpec::Iterate()) {
9120 if (_gted
[engine
].cargo_allowed
& cs
->classes
) SetBit(mask
, cs
->Index());
9121 if (_gted
[engine
].cargo_disallowed
& cs
->classes
) SetBit(not_mask
, cs
->Index());
9125 ei
->refit_mask
= ((mask
& ~not_mask
) ^ xor_mask
) & _cargo_mask
;
9127 /* Apply explicit refit includes/excludes. */
9128 ei
->refit_mask
|= _gted
[engine
].ctt_include_mask
;
9129 ei
->refit_mask
&= ~_gted
[engine
].ctt_exclude_mask
;
9132 /* Clear invalid cargoslots (from default vehicles or pre-NewCargo GRFs) */
9133 if (IsValidCargoID(ei
->cargo_type
) && !HasBit(_cargo_mask
, ei
->cargo_type
)) ei
->cargo_type
= INVALID_CARGO
;
9135 /* Ensure that the vehicle is either not refittable, or that the default cargo is one of the refittable cargoes.
9136 * Note: Vehicles refittable to no cargo are handle differently to vehicle refittable to a single cargo. The latter might have subtypes. */
9137 if (!only_defaultcargo
&& (e
->type
!= VEH_SHIP
|| e
->u
.ship
.old_refittable
) && IsValidCargoID(ei
->cargo_type
) && !HasBit(ei
->refit_mask
, ei
->cargo_type
)) {
9138 ei
->cargo_type
= INVALID_CARGO
;
9141 /* Check if this engine's cargo type is valid. If not, set to the first refittable
9142 * cargo type. Finally disable the vehicle, if there is still no cargo. */
9143 if (!IsValidCargoID(ei
->cargo_type
) && ei
->refit_mask
!= 0) {
9144 /* Figure out which CTT to use for the default cargo, if it is 'first refittable'. */
9145 const GRFFile
*file
= _gted
[engine
].defaultcargo_grf
;
9146 if (file
== nullptr) file
= e
->GetGRF();
9147 if (file
!= nullptr && file
->grf_version
>= 8 && !file
->cargo_list
.empty()) {
9148 /* Use first refittable cargo from cargo translation table */
9149 byte best_local_slot
= UINT8_MAX
;
9150 for (CargoID cargo_type
: SetCargoBitIterator(ei
->refit_mask
)) {
9151 byte local_slot
= file
->cargo_map
[cargo_type
];
9152 if (local_slot
< best_local_slot
) {
9153 best_local_slot
= local_slot
;
9154 ei
->cargo_type
= cargo_type
;
9159 if (!IsValidCargoID(ei
->cargo_type
)) {
9160 /* Use first refittable cargo slot */
9161 ei
->cargo_type
= (CargoID
)FindFirstBit(ei
->refit_mask
);
9164 if (!IsValidCargoID(ei
->cargo_type
)) ei
->climates
= 0;
9166 /* Clear refit_mask for not refittable ships */
9167 if (e
->type
== VEH_SHIP
&& !e
->u
.ship
.old_refittable
) {
9173 /** Set to use the correct action0 properties for each canal feature */
9174 static void FinaliseCanals()
9176 for (uint i
= 0; i
< CF_END
; i
++) {
9177 if (_water_feature
[i
].grffile
!= nullptr) {
9178 _water_feature
[i
].callback_mask
= _water_feature
[i
].grffile
->canal_local_properties
[i
].callback_mask
;
9179 _water_feature
[i
].flags
= _water_feature
[i
].grffile
->canal_local_properties
[i
].flags
;
9184 /** Check for invalid engines */
9185 static void FinaliseEngineArray()
9187 for (Engine
*e
: Engine::Iterate()) {
9188 if (e
->GetGRF() == nullptr) {
9189 const EngineIDMapping
&eid
= _engine_mngr
[e
->index
];
9190 if (eid
.grfid
!= INVALID_GRFID
|| eid
.internal_id
!= eid
.substitute_id
) {
9191 e
->info
.string_id
= STR_NEWGRF_INVALID_ENGINE
;
9195 /* Do final mapping on variant engine ID. */
9196 if (e
->info
.variant_id
!= INVALID_ENGINE
) {
9197 e
->info
.variant_id
= GetNewEngineID(e
->grf_prop
.grffile
, e
->type
, e
->info
.variant_id
);
9200 if (!HasBit(e
->info
.climates
, _settings_game
.game_creation
.landscape
)) continue;
9202 /* Skip wagons, there livery is defined via the engine */
9203 if (e
->type
!= VEH_TRAIN
|| e
->u
.rail
.railveh_type
!= RAILVEH_WAGON
) {
9204 LiveryScheme ls
= GetEngineLiveryScheme(e
->index
, INVALID_ENGINE
, nullptr);
9205 SetBit(_loaded_newgrf_features
.used_liveries
, ls
);
9206 /* Note: For ships and roadvehicles we assume that they cannot be refitted between passenger and freight */
9208 if (e
->type
== VEH_TRAIN
) {
9209 SetBit(_loaded_newgrf_features
.used_liveries
, LS_FREIGHT_WAGON
);
9216 SetBit(_loaded_newgrf_features
.used_liveries
, LS_PASSENGER_WAGON_STEAM
+ ls
- LS_STEAM
);
9221 SetBit(_loaded_newgrf_features
.used_liveries
, LS_PASSENGER_WAGON_DIESEL
+ ls
- LS_DMU
);
9224 default: NOT_REACHED();
9230 /* Check engine variants don't point back on themselves (either directly or via a loop) then set appropriate flags
9231 * on variant engine. This is performed separately as all variant engines need to have been resolved. */
9232 for (Engine
*e
: Engine::Iterate()) {
9233 EngineID parent
= e
->info
.variant_id
;
9234 while (parent
!= INVALID_ENGINE
) {
9235 parent
= Engine::Get(parent
)->info
.variant_id
;
9236 if (parent
!= e
->index
) continue;
9238 /* Engine looped back on itself, so clear the variant. */
9239 e
->info
.variant_id
= INVALID_ENGINE
;
9241 GrfMsg(1, "FinaliseEngineArray: Variant of engine {:x} in '{}' loops back on itself", _engine_mngr
[e
->index
].internal_id
, e
->GetGRF()->filename
);
9245 if (e
->info
.variant_id
!= INVALID_ENGINE
) {
9246 Engine::Get(e
->info
.variant_id
)->display_flags
|= EngineDisplayFlags::HasVariants
| EngineDisplayFlags::IsFolded
;
9251 /** Check for invalid cargoes */
9252 void FinaliseCargoArray()
9254 for (CargoSpec
&cs
: CargoSpec::array
) {
9255 if (cs
.town_production_effect
== INVALID_TPE
) {
9256 /* Set default town production effect by cargo label. */
9257 switch (cs
.label
.base()) {
9258 case CT_PASSENGERS
.base(): cs
.town_production_effect
= TPE_PASSENGERS
; break;
9259 case CT_MAIL
.base(): cs
.town_production_effect
= TPE_MAIL
; break;
9260 default: cs
.town_production_effect
= TPE_NONE
; break;
9263 if (!cs
.IsValid()) {
9264 cs
.name
= cs
.name_single
= cs
.units_volume
= STR_NEWGRF_INVALID_CARGO
;
9265 cs
.quantifier
= STR_NEWGRF_INVALID_CARGO_QUANTITY
;
9266 cs
.abbrev
= STR_NEWGRF_INVALID_CARGO_ABBREV
;
9272 * Check if a given housespec is valid and disable it if it's not.
9273 * The housespecs that follow it are used to check the validity of
9275 * @param hs The housespec to check.
9276 * @param next1 The housespec that follows \c hs.
9277 * @param next2 The housespec that follows \c next1.
9278 * @param next3 The housespec that follows \c next2.
9279 * @param filename The filename of the newgrf this house was defined in.
9280 * @return Whether the given housespec is valid.
9282 static bool IsHouseSpecValid(HouseSpec
*hs
, const HouseSpec
*next1
, const HouseSpec
*next2
, const HouseSpec
*next3
, const std::string
&filename
)
9284 if (((hs
->building_flags
& BUILDING_HAS_2_TILES
) != 0 &&
9285 (next1
== nullptr || !next1
->enabled
|| (next1
->building_flags
& BUILDING_HAS_1_TILE
) != 0)) ||
9286 ((hs
->building_flags
& BUILDING_HAS_4_TILES
) != 0 &&
9287 (next2
== nullptr || !next2
->enabled
|| (next2
->building_flags
& BUILDING_HAS_1_TILE
) != 0 ||
9288 next3
== nullptr || !next3
->enabled
|| (next3
->building_flags
& BUILDING_HAS_1_TILE
) != 0))) {
9289 hs
->enabled
= false;
9290 if (!filename
.empty()) Debug(grf
, 1, "FinaliseHouseArray: {} defines house {} as multitile, but no suitable tiles follow. Disabling house.", filename
, hs
->grf_prop
.local_id
);
9294 /* Some places sum population by only counting north tiles. Other places use all tiles causing desyncs.
9295 * As the newgrf specs define population to be zero for non-north tiles, we just disable the offending house.
9296 * If you want to allow non-zero populations somewhen, make sure to sum the population of all tiles in all places. */
9297 if (((hs
->building_flags
& BUILDING_HAS_2_TILES
) != 0 && next1
->population
!= 0) ||
9298 ((hs
->building_flags
& BUILDING_HAS_4_TILES
) != 0 && (next2
->population
!= 0 || next3
->population
!= 0))) {
9299 hs
->enabled
= false;
9300 if (!filename
.empty()) Debug(grf
, 1, "FinaliseHouseArray: {} defines multitile house {} with non-zero population on additional tiles. Disabling house.", filename
, hs
->grf_prop
.local_id
);
9304 /* Substitute type is also used for override, and having an override with a different size causes crashes.
9305 * This check should only be done for NewGRF houses because grf_prop.subst_id is not set for original houses.*/
9306 if (!filename
.empty() && (hs
->building_flags
& BUILDING_HAS_1_TILE
) != (HouseSpec::Get(hs
->grf_prop
.subst_id
)->building_flags
& BUILDING_HAS_1_TILE
)) {
9307 hs
->enabled
= false;
9308 Debug(grf
, 1, "FinaliseHouseArray: {} defines house {} with different house size then it's substitute type. Disabling house.", filename
, hs
->grf_prop
.local_id
);
9312 /* Make sure that additional parts of multitile houses are not available. */
9313 if ((hs
->building_flags
& BUILDING_HAS_1_TILE
) == 0 && (hs
->building_availability
& HZ_ZONALL
) != 0 && (hs
->building_availability
& HZ_CLIMALL
) != 0) {
9314 hs
->enabled
= false;
9315 if (!filename
.empty()) Debug(grf
, 1, "FinaliseHouseArray: {} defines house {} without a size but marked it as available. Disabling house.", filename
, hs
->grf_prop
.local_id
);
9323 * Make sure there is at least one house available in the year 0 for the given
9324 * climate / housezone combination.
9325 * @param bitmask The climate and housezone to check for. Exactly one climate
9326 * bit and one housezone bit should be set.
9328 static void EnsureEarlyHouse(HouseZones bitmask
)
9330 TimerGameCalendar::Year min_year
= CalendarTime::MAX_YEAR
;
9332 for (int i
= 0; i
< NUM_HOUSES
; i
++) {
9333 HouseSpec
*hs
= HouseSpec::Get(i
);
9334 if (hs
== nullptr || !hs
->enabled
) continue;
9335 if ((hs
->building_availability
& bitmask
) != bitmask
) continue;
9336 if (hs
->min_year
< min_year
) min_year
= hs
->min_year
;
9339 if (min_year
== 0) return;
9341 for (int i
= 0; i
< NUM_HOUSES
; i
++) {
9342 HouseSpec
*hs
= HouseSpec::Get(i
);
9343 if (hs
== nullptr || !hs
->enabled
) continue;
9344 if ((hs
->building_availability
& bitmask
) != bitmask
) continue;
9345 if (hs
->min_year
== min_year
) hs
->min_year
= 0;
9350 * Add all new houses to the house array. House properties can be set at any
9351 * time in the GRF file, so we can only add a house spec to the house array
9352 * after the file has finished loading. We also need to check the dates, due to
9353 * the TTDPatch behaviour described below that we need to emulate.
9355 static void FinaliseHouseArray()
9357 /* If there are no houses with start dates before 1930, then all houses
9358 * with start dates of 1930 have them reset to 0. This is in order to be
9359 * compatible with TTDPatch, where if no houses have start dates before
9360 * 1930 and the date is before 1930, the game pretends that this is 1930.
9361 * If there have been any houses defined with start dates before 1930 then
9362 * the dates are left alone.
9363 * On the other hand, why 1930? Just 'fix' the houses with the lowest
9364 * minimum introduction date to 0.
9366 for (GRFFile
* const file
: _grf_files
) {
9367 if (file
->housespec
.empty()) continue;
9369 size_t num_houses
= file
->housespec
.size();
9370 for (size_t i
= 0; i
< num_houses
; i
++) {
9371 HouseSpec
*hs
= file
->housespec
[i
].get();
9373 if (hs
== nullptr) continue;
9375 const HouseSpec
*next1
= (i
+ 1 < num_houses
? file
->housespec
[i
+ 1].get() : nullptr);
9376 const HouseSpec
*next2
= (i
+ 2 < num_houses
? file
->housespec
[i
+ 2].get() : nullptr);
9377 const HouseSpec
*next3
= (i
+ 3 < num_houses
? file
->housespec
[i
+ 3].get() : nullptr);
9379 if (!IsHouseSpecValid(hs
, next1
, next2
, next3
, file
->filename
)) continue;
9381 _house_mngr
.SetEntitySpec(hs
);
9385 for (size_t i
= 0; i
< NUM_HOUSES
; i
++) {
9386 HouseSpec
*hs
= HouseSpec::Get(i
);
9387 const HouseSpec
*next1
= (i
+ 1 < NUM_HOUSES
? HouseSpec::Get(i
+ 1) : nullptr);
9388 const HouseSpec
*next2
= (i
+ 2 < NUM_HOUSES
? HouseSpec::Get(i
+ 2) : nullptr);
9389 const HouseSpec
*next3
= (i
+ 3 < NUM_HOUSES
? HouseSpec::Get(i
+ 3) : nullptr);
9391 /* We need to check all houses again to we are sure that multitile houses
9392 * did get consecutive IDs and none of the parts are missing. */
9393 if (!IsHouseSpecValid(hs
, next1
, next2
, next3
, std::string
{})) {
9394 /* GetHouseNorthPart checks 3 houses that are directly before
9395 * it in the house pool. If any of those houses have multi-tile
9396 * flags set it assumes it's part of a multitile house. Since
9397 * we can have invalid houses in the pool marked as disabled, we
9398 * don't want to have them influencing valid tiles. As such set
9399 * building_flags to zero here to make sure any house following
9400 * this one in the pool is properly handled as 1x1 house. */
9401 hs
->building_flags
= TILE_NO_FLAG
;
9404 /* Apply default cargo translation map for unset cargo slots */
9405 for (uint i
= 0; i
< lengthof(hs
->accepts_cargo
); ++i
) {
9406 if (!IsValidCargoID(hs
->accepts_cargo
[i
])) hs
->accepts_cargo
[i
] = GetCargoIDByLabel(hs
->accepts_cargo_label
[i
]);
9407 /* Disable acceptance if cargo type is invalid. */
9408 if (!IsValidCargoID(hs
->accepts_cargo
[i
])) hs
->cargo_acceptance
[i
] = 0;
9412 HouseZones climate_mask
= (HouseZones
)(1 << (_settings_game
.game_creation
.landscape
+ 12));
9413 EnsureEarlyHouse(HZ_ZON1
| climate_mask
);
9414 EnsureEarlyHouse(HZ_ZON2
| climate_mask
);
9415 EnsureEarlyHouse(HZ_ZON3
| climate_mask
);
9416 EnsureEarlyHouse(HZ_ZON4
| climate_mask
);
9417 EnsureEarlyHouse(HZ_ZON5
| climate_mask
);
9419 if (_settings_game
.game_creation
.landscape
== LT_ARCTIC
) {
9420 EnsureEarlyHouse(HZ_ZON1
| HZ_SUBARTC_ABOVE
);
9421 EnsureEarlyHouse(HZ_ZON2
| HZ_SUBARTC_ABOVE
);
9422 EnsureEarlyHouse(HZ_ZON3
| HZ_SUBARTC_ABOVE
);
9423 EnsureEarlyHouse(HZ_ZON4
| HZ_SUBARTC_ABOVE
);
9424 EnsureEarlyHouse(HZ_ZON5
| HZ_SUBARTC_ABOVE
);
9429 * Add all new industries to the industry array. Industry properties can be set at any
9430 * time in the GRF file, so we can only add a industry spec to the industry array
9431 * after the file has finished loading.
9433 static void FinaliseIndustriesArray()
9435 for (GRFFile
* const file
: _grf_files
) {
9436 for (const auto &indsp
: file
->industryspec
) {
9437 if (indsp
== nullptr || !indsp
->enabled
) continue;
9440 /* process the conversion of text at the end, so to be sure everything will be fine
9441 * and available. Check if it does not return undefind marker, which is a very good sign of a
9442 * substitute industry who has not changed the string been examined, thus using it as such */
9443 strid
= GetGRFStringID(indsp
->grf_prop
.grffile
->grfid
, indsp
->name
);
9444 if (strid
!= STR_UNDEFINED
) indsp
->name
= strid
;
9446 strid
= GetGRFStringID(indsp
->grf_prop
.grffile
->grfid
, indsp
->closure_text
);
9447 if (strid
!= STR_UNDEFINED
) indsp
->closure_text
= strid
;
9449 strid
= GetGRFStringID(indsp
->grf_prop
.grffile
->grfid
, indsp
->production_up_text
);
9450 if (strid
!= STR_UNDEFINED
) indsp
->production_up_text
= strid
;
9452 strid
= GetGRFStringID(indsp
->grf_prop
.grffile
->grfid
, indsp
->production_down_text
);
9453 if (strid
!= STR_UNDEFINED
) indsp
->production_down_text
= strid
;
9455 strid
= GetGRFStringID(indsp
->grf_prop
.grffile
->grfid
, indsp
->new_industry_text
);
9456 if (strid
!= STR_UNDEFINED
) indsp
->new_industry_text
= strid
;
9458 if (indsp
->station_name
!= STR_NULL
) {
9459 /* STR_NULL (0) can be set by grf. It has a meaning regarding assignation of the
9460 * station's name. Don't want to lose the value, therefore, do not process. */
9461 strid
= GetGRFStringID(indsp
->grf_prop
.grffile
->grfid
, indsp
->station_name
);
9462 if (strid
!= STR_UNDEFINED
) indsp
->station_name
= strid
;
9465 _industry_mngr
.SetEntitySpec(indsp
.get());
9468 for (const auto &indtsp
: file
->indtspec
) {
9469 if (indtsp
!= nullptr) {
9470 _industile_mngr
.SetEntitySpec(indtsp
.get());
9475 for (auto &indsp
: _industry_specs
) {
9476 if (indsp
.enabled
&& indsp
.grf_prop
.grffile
!= nullptr) {
9477 for (auto &conflicting
: indsp
.conflicting
) {
9478 conflicting
= MapNewGRFIndustryType(conflicting
, indsp
.grf_prop
.grffile
->grfid
);
9481 if (!indsp
.enabled
) {
9482 indsp
.name
= STR_NEWGRF_INVALID_INDUSTRYTYPE
;
9485 /* Apply default cargo translation map for unset cargo slots */
9486 for (uint i
= 0; i
< lengthof(indsp
.produced_cargo
); ++i
) {
9487 if (!IsValidCargoID(indsp
.produced_cargo
[i
])) indsp
.produced_cargo
[i
] = GetCargoIDByLabel(GetActiveCargoLabel(indsp
.produced_cargo_label
[i
]));
9489 for (uint i
= 0; i
< lengthof(indsp
.accepts_cargo
); ++i
) {
9490 if (!IsValidCargoID(indsp
.accepts_cargo
[i
])) indsp
.accepts_cargo
[i
] = GetCargoIDByLabel(GetActiveCargoLabel(indsp
.accepts_cargo_label
[i
]));
9494 for (auto &indtsp
: _industry_tile_specs
) {
9495 /* Apply default cargo translation map for unset cargo slots */
9496 for (uint i
= 0; i
< lengthof(indtsp
.accepts_cargo
); ++i
) {
9497 if (!IsValidCargoID(indtsp
.accepts_cargo
[i
])) indtsp
.accepts_cargo
[i
] = GetCargoIDByLabel(GetActiveCargoLabel(indtsp
.accepts_cargo_label
[i
]));
9503 * Add all new objects to the object array. Object properties can be set at any
9504 * time in the GRF file, so we can only add an object spec to the object array
9505 * after the file has finished loading.
9507 static void FinaliseObjectsArray()
9509 for (GRFFile
* const file
: _grf_files
) {
9510 for (auto &objectspec
: file
->objectspec
) {
9511 if (objectspec
!= nullptr && objectspec
->grf_prop
.grffile
!= nullptr && objectspec
->IsEnabled()) {
9512 _object_mngr
.SetEntitySpec(objectspec
.get());
9517 ObjectSpec::BindToClasses();
9521 * Add all new airports to the airport array. Airport properties can be set at any
9522 * time in the GRF file, so we can only add a airport spec to the airport array
9523 * after the file has finished loading.
9525 static void FinaliseAirportsArray()
9527 for (GRFFile
* const file
: _grf_files
) {
9528 for (auto &as
: file
->airportspec
) {
9529 if (as
!= nullptr && as
->enabled
) {
9530 _airport_mngr
.SetEntitySpec(as
.get());
9534 for (auto &ats
: file
->airtspec
) {
9535 if (ats
!= nullptr && ats
->enabled
) {
9536 _airporttile_mngr
.SetEntitySpec(ats
.get());
9542 /* Here we perform initial decoding of some special sprites (as are they
9543 * described at http://www.ttdpatch.net/src/newgrf.txt, but this is only a very
9544 * partial implementation yet).
9545 * XXX: We consider GRF files trusted. It would be trivial to exploit OTTD by
9546 * a crafted invalid GRF file. We should tell that to the user somehow, or
9547 * better make this more robust in the future. */
9548 static void DecodeSpecialSprite(byte
*buf
, uint num
, GrfLoadingStage stage
)
9550 /* XXX: There is a difference between staged loading in TTDPatch and
9551 * here. In TTDPatch, for some reason actions 1 and 2 are carried out
9552 * during stage 1, whilst action 3 is carried out during stage 2 (to
9553 * "resolve" cargo IDs... wtf). This is a little problem, because cargo
9554 * IDs are valid only within a given set (action 1) block, and may be
9555 * overwritten after action 3 associates them. But overwriting happens
9556 * in an earlier stage than associating, so... We just process actions
9557 * 1 and 2 in stage 2 now, let's hope that won't get us into problems.
9559 * We need a pre-stage to set up GOTO labels of Action 0x10 because the grf
9560 * is not in memory and scanning the file every time would be too expensive.
9561 * In other stages we skip action 0x10 since it's already dealt with. */
9562 static const SpecialSpriteHandler handlers
[][GLS_END
] = {
9563 /* 0x00 */ { nullptr, SafeChangeInfo
, nullptr, nullptr, ReserveChangeInfo
, FeatureChangeInfo
, },
9564 /* 0x01 */ { SkipAct1
, SkipAct1
, SkipAct1
, SkipAct1
, SkipAct1
, NewSpriteSet
, },
9565 /* 0x02 */ { nullptr, nullptr, nullptr, nullptr, nullptr, NewSpriteGroup
, },
9566 /* 0x03 */ { nullptr, GRFUnsafe
, nullptr, nullptr, nullptr, FeatureMapSpriteGroup
, },
9567 /* 0x04 */ { nullptr, nullptr, nullptr, nullptr, nullptr, FeatureNewName
, },
9568 /* 0x05 */ { SkipAct5
, SkipAct5
, SkipAct5
, SkipAct5
, SkipAct5
, GraphicsNew
, },
9569 /* 0x06 */ { nullptr, nullptr, nullptr, CfgApply
, CfgApply
, CfgApply
, },
9570 /* 0x07 */ { nullptr, nullptr, nullptr, nullptr, SkipIf
, SkipIf
, },
9571 /* 0x08 */ { ScanInfo
, nullptr, nullptr, GRFInfo
, GRFInfo
, GRFInfo
, },
9572 /* 0x09 */ { nullptr, nullptr, nullptr, SkipIf
, SkipIf
, SkipIf
, },
9573 /* 0x0A */ { SkipActA
, SkipActA
, SkipActA
, SkipActA
, SkipActA
, SpriteReplace
, },
9574 /* 0x0B */ { nullptr, nullptr, nullptr, GRFLoadError
, GRFLoadError
, GRFLoadError
, },
9575 /* 0x0C */ { nullptr, nullptr, nullptr, GRFComment
, nullptr, GRFComment
, },
9576 /* 0x0D */ { nullptr, SafeParamSet
, nullptr, ParamSet
, ParamSet
, ParamSet
, },
9577 /* 0x0E */ { nullptr, SafeGRFInhibit
, nullptr, GRFInhibit
, GRFInhibit
, GRFInhibit
, },
9578 /* 0x0F */ { nullptr, GRFUnsafe
, nullptr, FeatureTownName
, nullptr, nullptr, },
9579 /* 0x10 */ { nullptr, nullptr, DefineGotoLabel
, nullptr, nullptr, nullptr, },
9580 /* 0x11 */ { SkipAct11
, GRFUnsafe
, SkipAct11
, GRFSound
, SkipAct11
, GRFSound
, },
9581 /* 0x12 */ { SkipAct12
, SkipAct12
, SkipAct12
, SkipAct12
, SkipAct12
, LoadFontGlyph
, },
9582 /* 0x13 */ { nullptr, nullptr, nullptr, nullptr, nullptr, TranslateGRFStrings
, },
9583 /* 0x14 */ { StaticGRFInfo
, nullptr, nullptr, nullptr, nullptr, nullptr, },
9586 GRFLocation
location(_cur
.grfconfig
->ident
.grfid
, _cur
.nfo_line
);
9588 GRFLineToSpriteOverride::iterator it
= _grf_line_to_action6_sprite_override
.find(location
);
9589 if (it
== _grf_line_to_action6_sprite_override
.end()) {
9590 /* No preloaded sprite to work with; read the
9591 * pseudo sprite content. */
9592 _cur
.file
->ReadBlock(buf
, num
);
9594 /* Use the preloaded sprite data. */
9595 buf
= _grf_line_to_action6_sprite_override
[location
].data();
9596 GrfMsg(7, "DecodeSpecialSprite: Using preloaded pseudo sprite data");
9598 /* Skip the real (original) content of this action. */
9599 _cur
.file
->SeekTo(num
, SEEK_CUR
);
9602 ByteReader
br(buf
, buf
+ num
);
9603 ByteReader
*bufp
= &br
;
9606 byte action
= bufp
->ReadByte();
9608 if (action
== 0xFF) {
9609 GrfMsg(2, "DecodeSpecialSprite: Unexpected data block, skipping");
9610 } else if (action
== 0xFE) {
9611 GrfMsg(2, "DecodeSpecialSprite: Unexpected import block, skipping");
9612 } else if (action
>= lengthof(handlers
)) {
9613 GrfMsg(7, "DecodeSpecialSprite: Skipping unknown action 0x{:02X}", action
);
9614 } else if (handlers
[action
][stage
] == nullptr) {
9615 GrfMsg(7, "DecodeSpecialSprite: Skipping action 0x{:02X} in stage {}", action
, stage
);
9617 GrfMsg(7, "DecodeSpecialSprite: Handling action 0x{:02X} in stage {}", action
, stage
);
9618 handlers
[action
][stage
](bufp
);
9621 GrfMsg(1, "DecodeSpecialSprite: Tried to read past end of pseudo-sprite data");
9622 DisableGrf(STR_NEWGRF_ERROR_READ_BOUNDS
);
9627 * Load a particular NewGRF from a SpriteFile.
9628 * @param config The configuration of the to be loaded NewGRF.
9629 * @param stage The loading stage of the NewGRF.
9630 * @param file The file to load the GRF data from.
9632 static void LoadNewGRFFileFromFile(GRFConfig
*config
, GrfLoadingStage stage
, SpriteFile
&file
)
9635 _cur
.grfconfig
= config
;
9637 Debug(grf
, 2, "LoadNewGRFFile: Reading NewGRF-file '{}'", config
->filename
);
9639 byte grf_container_version
= file
.GetContainerVersion();
9640 if (grf_container_version
== 0) {
9641 Debug(grf
, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9645 if (stage
== GLS_INIT
|| stage
== GLS_ACTIVATION
) {
9646 /* We need the sprite offsets in the init stage for NewGRF sounds
9647 * and in the activation stage for real sprites. */
9648 ReadGRFSpriteOffsets(file
);
9650 /* Skip sprite section offset if present. */
9651 if (grf_container_version
>= 2) file
.ReadDword();
9654 if (grf_container_version
>= 2) {
9655 /* Read compression value. */
9656 byte compression
= file
.ReadByte();
9657 if (compression
!= 0) {
9658 Debug(grf
, 7, "LoadNewGRFFile: Unsupported compression format");
9663 /* Skip the first sprite; we don't care about how many sprites this
9664 * does contain; newest TTDPatches and George's longvehicles don't
9665 * neither, apparently. */
9666 uint32_t num
= grf_container_version
>= 2 ? file
.ReadDword() : file
.ReadWord();
9667 if (num
== 4 && file
.ReadByte() == 0xFF) {
9670 Debug(grf
, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9674 _cur
.ClearDataForNextFile();
9676 ReusableBuffer
<byte
> buf
;
9678 while ((num
= (grf_container_version
>= 2 ? file
.ReadDword() : file
.ReadWord())) != 0) {
9679 byte type
= file
.ReadByte();
9683 if (_cur
.skip_sprites
== 0) {
9684 DecodeSpecialSprite(buf
.Allocate(num
), num
, stage
);
9686 /* Stop all processing if we are to skip the remaining sprites */
9687 if (_cur
.skip_sprites
== -1) break;
9691 file
.SkipBytes(num
);
9694 if (_cur
.skip_sprites
== 0) {
9695 GrfMsg(0, "LoadNewGRFFile: Unexpected sprite, disabling");
9696 DisableGrf(STR_NEWGRF_ERROR_UNEXPECTED_SPRITE
);
9700 if (grf_container_version
>= 2 && type
== 0xFD) {
9701 /* Reference to data section. Container version >= 2 only. */
9702 file
.SkipBytes(num
);
9705 SkipSpriteData(file
, type
, num
- 8);
9709 if (_cur
.skip_sprites
> 0) _cur
.skip_sprites
--;
9714 * Load a particular NewGRF.
9715 * @param config The configuration of the to be loaded NewGRF.
9716 * @param stage The loading stage of the NewGRF.
9717 * @param subdir The sub directory to find the NewGRF in.
9718 * @param temporary The NewGRF/sprite file is to be loaded temporarily and should be closed immediately,
9719 * contrary to loading the SpriteFile and having it cached by the SpriteCache.
9721 void LoadNewGRFFile(GRFConfig
*config
, GrfLoadingStage stage
, Subdirectory subdir
, bool temporary
)
9723 const std::string
&filename
= config
->filename
;
9725 /* A .grf file is activated only if it was active when the game was
9726 * started. If a game is loaded, only its active .grfs will be
9727 * reactivated, unless "loadallgraphics on" is used. A .grf file is
9728 * considered active if its action 8 has been processed, i.e. its
9729 * action 8 hasn't been skipped using an action 7.
9731 * During activation, only actions 0, 1, 2, 3, 4, 5, 7, 8, 9, 0A and 0B are
9732 * carried out. All others are ignored, because they only need to be
9733 * processed once at initialization. */
9734 if (stage
!= GLS_FILESCAN
&& stage
!= GLS_SAFETYSCAN
&& stage
!= GLS_LABELSCAN
) {
9735 _cur
.grffile
= GetFileByFilename(filename
);
9736 if (_cur
.grffile
== nullptr) UserError("File '{}' lost in cache.\n", filename
);
9737 if (stage
== GLS_RESERVE
&& config
->status
!= GCS_INITIALISED
) return;
9738 if (stage
== GLS_ACTIVATION
&& !HasBit(config
->flags
, GCF_RESERVED
)) return;
9741 bool needs_palette_remap
= config
->palette
& GRFP_USE_MASK
;
9743 SpriteFile
temporarySpriteFile(filename
, subdir
, needs_palette_remap
);
9744 LoadNewGRFFileFromFile(config
, stage
, temporarySpriteFile
);
9746 LoadNewGRFFileFromFile(config
, stage
, OpenCachedSpriteFile(filename
, subdir
, needs_palette_remap
));
9751 * Relocates the old shore sprites at new positions.
9753 * 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)
9754 * 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)
9755 * 3. If a newgrf replaces shore sprites by Action5 any shore replacement by ActionA has no effect. (SHORE_REPLACE_ACTION_5)
9757 static void ActivateOldShore()
9759 /* Use default graphics, if no shore sprites were loaded.
9760 * Should not happen, as the base set's extra grf should include some. */
9761 if (_loaded_newgrf_features
.shore
== SHORE_REPLACE_NONE
) _loaded_newgrf_features
.shore
= SHORE_REPLACE_ACTION_A
;
9763 if (_loaded_newgrf_features
.shore
!= SHORE_REPLACE_ACTION_5
) {
9764 DupSprite(SPR_ORIGINALSHORE_START
+ 1, SPR_SHORE_BASE
+ 1); // SLOPE_W
9765 DupSprite(SPR_ORIGINALSHORE_START
+ 2, SPR_SHORE_BASE
+ 2); // SLOPE_S
9766 DupSprite(SPR_ORIGINALSHORE_START
+ 6, SPR_SHORE_BASE
+ 3); // SLOPE_SW
9767 DupSprite(SPR_ORIGINALSHORE_START
+ 0, SPR_SHORE_BASE
+ 4); // SLOPE_E
9768 DupSprite(SPR_ORIGINALSHORE_START
+ 4, SPR_SHORE_BASE
+ 6); // SLOPE_SE
9769 DupSprite(SPR_ORIGINALSHORE_START
+ 3, SPR_SHORE_BASE
+ 8); // SLOPE_N
9770 DupSprite(SPR_ORIGINALSHORE_START
+ 7, SPR_SHORE_BASE
+ 9); // SLOPE_NW
9771 DupSprite(SPR_ORIGINALSHORE_START
+ 5, SPR_SHORE_BASE
+ 12); // SLOPE_NE
9774 if (_loaded_newgrf_features
.shore
== SHORE_REPLACE_ACTION_A
) {
9775 DupSprite(SPR_FLAT_GRASS_TILE
+ 16, SPR_SHORE_BASE
+ 0); // SLOPE_STEEP_S
9776 DupSprite(SPR_FLAT_GRASS_TILE
+ 17, SPR_SHORE_BASE
+ 5); // SLOPE_STEEP_W
9777 DupSprite(SPR_FLAT_GRASS_TILE
+ 7, SPR_SHORE_BASE
+ 7); // SLOPE_WSE
9778 DupSprite(SPR_FLAT_GRASS_TILE
+ 15, SPR_SHORE_BASE
+ 10); // SLOPE_STEEP_N
9779 DupSprite(SPR_FLAT_GRASS_TILE
+ 11, SPR_SHORE_BASE
+ 11); // SLOPE_NWS
9780 DupSprite(SPR_FLAT_GRASS_TILE
+ 13, SPR_SHORE_BASE
+ 13); // SLOPE_ENW
9781 DupSprite(SPR_FLAT_GRASS_TILE
+ 14, SPR_SHORE_BASE
+ 14); // SLOPE_SEN
9782 DupSprite(SPR_FLAT_GRASS_TILE
+ 18, SPR_SHORE_BASE
+ 15); // SLOPE_STEEP_E
9784 /* XXX - SLOPE_EW, SLOPE_NS are currently not used.
9785 * If they would be used somewhen, then these grass tiles will most like not look as needed */
9786 DupSprite(SPR_FLAT_GRASS_TILE
+ 5, SPR_SHORE_BASE
+ 16); // SLOPE_EW
9787 DupSprite(SPR_FLAT_GRASS_TILE
+ 10, SPR_SHORE_BASE
+ 17); // SLOPE_NS
9792 * Replocate the old tram depot sprites to the new position, if no new ones were loaded.
9794 static void ActivateOldTramDepot()
9796 if (_loaded_newgrf_features
.tram
== TRAMWAY_REPLACE_DEPOT_WITH_TRACK
) {
9797 DupSprite(SPR_ROAD_DEPOT
+ 0, SPR_TRAMWAY_DEPOT_NO_TRACK
+ 0); // use road depot graphics for "no tracks"
9798 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK
+ 1, SPR_TRAMWAY_DEPOT_NO_TRACK
+ 1);
9799 DupSprite(SPR_ROAD_DEPOT
+ 2, SPR_TRAMWAY_DEPOT_NO_TRACK
+ 2); // use road depot graphics for "no tracks"
9800 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK
+ 3, SPR_TRAMWAY_DEPOT_NO_TRACK
+ 3);
9801 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK
+ 4, SPR_TRAMWAY_DEPOT_NO_TRACK
+ 4);
9802 DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK
+ 5, SPR_TRAMWAY_DEPOT_NO_TRACK
+ 5);
9807 * Decide whether price base multipliers of grfs shall apply globally or only to the grf specifying them
9809 static void FinalisePriceBaseMultipliers()
9811 extern const PriceBaseSpec _price_base_specs
[];
9812 /** Features, to which '_grf_id_overrides' applies. Currently vehicle features only. */
9813 static const uint32_t override_features
= (1 << GSF_TRAINS
) | (1 << GSF_ROADVEHICLES
) | (1 << GSF_SHIPS
) | (1 << GSF_AIRCRAFT
);
9815 /* Evaluate grf overrides */
9816 int num_grfs
= (uint
)_grf_files
.size();
9817 std::vector
<int> grf_overrides(num_grfs
, -1);
9818 for (int i
= 0; i
< num_grfs
; i
++) {
9819 GRFFile
*source
= _grf_files
[i
];
9820 uint32_t override
= _grf_id_overrides
[source
->grfid
];
9821 if (override
== 0) continue;
9823 GRFFile
*dest
= GetFileByGRFID(override
);
9824 if (dest
== nullptr) continue;
9826 grf_overrides
[i
] = find_index(_grf_files
, dest
);
9827 assert(grf_overrides
[i
] >= 0);
9830 /* Override features and price base multipliers of earlier loaded grfs */
9831 for (int i
= 0; i
< num_grfs
; i
++) {
9832 if (grf_overrides
[i
] < 0 || grf_overrides
[i
] >= i
) continue;
9833 GRFFile
*source
= _grf_files
[i
];
9834 GRFFile
*dest
= _grf_files
[grf_overrides
[i
]];
9836 uint32_t features
= (source
->grf_features
| dest
->grf_features
) & override_features
;
9837 source
->grf_features
|= features
;
9838 dest
->grf_features
|= features
;
9840 for (Price p
= PR_BEGIN
; p
< PR_END
; p
++) {
9841 /* No price defined -> nothing to do */
9842 if (!HasBit(features
, _price_base_specs
[p
].grf_feature
) || source
->price_base_multipliers
[p
] == INVALID_PRICE_MODIFIER
) continue;
9843 Debug(grf
, 3, "'{}' overrides price base multiplier {} of '{}'", source
->filename
, p
, dest
->filename
);
9844 dest
->price_base_multipliers
[p
] = source
->price_base_multipliers
[p
];
9848 /* Propagate features and price base multipliers of afterwards loaded grfs, if none is present yet */
9849 for (int i
= num_grfs
- 1; i
>= 0; i
--) {
9850 if (grf_overrides
[i
] < 0 || grf_overrides
[i
] <= i
) continue;
9851 GRFFile
*source
= _grf_files
[i
];
9852 GRFFile
*dest
= _grf_files
[grf_overrides
[i
]];
9854 uint32_t features
= (source
->grf_features
| dest
->grf_features
) & override_features
;
9855 source
->grf_features
|= features
;
9856 dest
->grf_features
|= features
;
9858 for (Price p
= PR_BEGIN
; p
< PR_END
; p
++) {
9859 /* Already a price defined -> nothing to do */
9860 if (!HasBit(features
, _price_base_specs
[p
].grf_feature
) || dest
->price_base_multipliers
[p
] != INVALID_PRICE_MODIFIER
) continue;
9861 Debug(grf
, 3, "Price base multiplier {} from '{}' propagated to '{}'", p
, source
->filename
, dest
->filename
);
9862 dest
->price_base_multipliers
[p
] = source
->price_base_multipliers
[p
];
9866 /* The 'master grf' now have the correct multipliers. Assign them to the 'addon grfs' to make everything consistent. */
9867 for (int i
= 0; i
< num_grfs
; i
++) {
9868 if (grf_overrides
[i
] < 0) continue;
9869 GRFFile
*source
= _grf_files
[i
];
9870 GRFFile
*dest
= _grf_files
[grf_overrides
[i
]];
9872 uint32_t features
= (source
->grf_features
| dest
->grf_features
) & override_features
;
9873 source
->grf_features
|= features
;
9874 dest
->grf_features
|= features
;
9876 for (Price p
= PR_BEGIN
; p
< PR_END
; p
++) {
9877 if (!HasBit(features
, _price_base_specs
[p
].grf_feature
)) continue;
9878 if (source
->price_base_multipliers
[p
] != dest
->price_base_multipliers
[p
]) {
9879 Debug(grf
, 3, "Price base multiplier {} from '{}' propagated to '{}'", p
, dest
->filename
, source
->filename
);
9881 source
->price_base_multipliers
[p
] = dest
->price_base_multipliers
[p
];
9885 /* Apply fallback prices for grf version < 8 */
9886 for (GRFFile
* const file
: _grf_files
) {
9887 if (file
->grf_version
>= 8) continue;
9888 PriceMultipliers
&price_base_multipliers
= file
->price_base_multipliers
;
9889 for (Price p
= PR_BEGIN
; p
< PR_END
; p
++) {
9890 Price fallback_price
= _price_base_specs
[p
].fallback_price
;
9891 if (fallback_price
!= INVALID_PRICE
&& price_base_multipliers
[p
] == INVALID_PRICE_MODIFIER
) {
9892 /* No price multiplier has been set.
9893 * So copy the multiplier from the fallback price, maybe a multiplier was set there. */
9894 price_base_multipliers
[p
] = price_base_multipliers
[fallback_price
];
9899 /* Decide local/global scope of price base multipliers */
9900 for (GRFFile
* const file
: _grf_files
) {
9901 PriceMultipliers
&price_base_multipliers
= file
->price_base_multipliers
;
9902 for (Price p
= PR_BEGIN
; p
< PR_END
; p
++) {
9903 if (price_base_multipliers
[p
] == INVALID_PRICE_MODIFIER
) {
9904 /* No multiplier was set; set it to a neutral value */
9905 price_base_multipliers
[p
] = 0;
9907 if (!HasBit(file
->grf_features
, _price_base_specs
[p
].grf_feature
)) {
9908 /* The grf does not define any objects of the feature,
9909 * so it must be a difficulty setting. Apply it globally */
9910 Debug(grf
, 3, "'{}' sets global price base multiplier {}", file
->filename
, p
);
9911 SetPriceBaseMultiplier(p
, price_base_multipliers
[p
]);
9912 price_base_multipliers
[p
] = 0;
9914 Debug(grf
, 3, "'{}' sets local price base multiplier {}", file
->filename
, p
);
9921 extern void InitGRFTownGeneratorNames();
9923 /** Finish loading NewGRFs and execute needed post-processing */
9924 static void AfterLoadGRFs()
9926 for (StringIDMapping
&it
: _string_to_grf_mapping
) {
9927 *it
.target
= MapGRFStringID(it
.grfid
, it
.source
);
9929 _string_to_grf_mapping
.clear();
9931 /* Clear the action 6 override sprites. */
9932 _grf_line_to_action6_sprite_override
.clear();
9934 /* Polish cargoes */
9935 FinaliseCargoArray();
9937 /* Pre-calculate all refit masks after loading GRF files. */
9938 CalculateRefitMasks();
9940 /* Polish engines */
9941 FinaliseEngineArray();
9943 /* Set the actually used Canal properties */
9946 /* Add all new houses to the house array. */
9947 FinaliseHouseArray();
9949 /* Add all new industries to the industry array. */
9950 FinaliseIndustriesArray();
9952 /* Add all new objects to the object array. */
9953 FinaliseObjectsArray();
9955 InitializeSortedCargoSpecs();
9957 /* Sort the list of industry types. */
9958 SortIndustryTypes();
9960 /* Create dynamic list of industry legends for smallmap_gui.cpp */
9961 BuildIndustriesLegend();
9963 /* Build the routemap legend, based on the available cargos */
9964 BuildLinkStatsLegend();
9966 /* Add all new airports to the airports array. */
9967 FinaliseAirportsArray();
9970 /* Update the townname generators list */
9971 InitGRFTownGeneratorNames();
9973 /* Run all queued vehicle list order changes */
9974 CommitVehicleListOrderChanges();
9976 /* Load old shore sprites in new position, if they were replaced by ActionA */
9979 /* Load old tram depot sprites in new position, if no new ones are present */
9980 ActivateOldTramDepot();
9982 /* Set up custom rail types */
9986 for (Engine
*e
: Engine::IterateType(VEH_ROAD
)) {
9987 if (_gted
[e
->index
].rv_max_speed
!= 0) {
9988 /* Set RV maximum speed from the mph/0.8 unit value */
9989 e
->u
.road
.max_speed
= _gted
[e
->index
].rv_max_speed
* 4;
9992 RoadTramType rtt
= HasBit(e
->info
.misc_flags
, EF_ROAD_TRAM
) ? RTT_TRAM
: RTT_ROAD
;
9994 const GRFFile
*file
= e
->GetGRF();
9995 if (file
== nullptr || _gted
[e
->index
].roadtramtype
== 0) {
9996 e
->u
.road
.roadtype
= (rtt
== RTT_TRAM
) ? ROADTYPE_TRAM
: ROADTYPE_ROAD
;
10000 /* Remove +1 offset. */
10001 _gted
[e
->index
].roadtramtype
--;
10003 const std::vector
<RoadTypeLabel
> *list
= (rtt
== RTT_TRAM
) ? &file
->tramtype_list
: &file
->roadtype_list
;
10004 if (_gted
[e
->index
].roadtramtype
< list
->size())
10006 RoadTypeLabel rtl
= (*list
)[_gted
[e
->index
].roadtramtype
];
10007 RoadType rt
= GetRoadTypeByLabel(rtl
);
10008 if (rt
!= INVALID_ROADTYPE
&& GetRoadTramType(rt
) == rtt
) {
10009 e
->u
.road
.roadtype
= rt
;
10014 /* Road type is not available, so disable this engine */
10015 e
->info
.climates
= 0;
10018 for (Engine
*e
: Engine::IterateType(VEH_TRAIN
)) {
10019 RailType railtype
= GetRailTypeByLabel(_gted
[e
->index
].railtypelabel
);
10020 if (railtype
== INVALID_RAILTYPE
) {
10021 /* Rail type is not available, so disable this engine */
10022 e
->info
.climates
= 0;
10024 e
->u
.rail
.railtype
= railtype
;
10025 e
->u
.rail
.intended_railtype
= railtype
;
10029 SetYearEngineAgingStops();
10031 FinalisePriceBaseMultipliers();
10033 /* Deallocate temporary loading data */
10035 _grm_sprites
.clear();
10039 * Load all the NewGRFs.
10040 * @param load_index The offset for the first sprite to add.
10041 * @param num_baseset Number of NewGRFs at the front of the list to look up in the baseset dir instead of the newgrf dir.
10043 void LoadNewGRF(uint load_index
, uint num_baseset
)
10045 /* In case of networking we need to "sync" the start values
10046 * so all NewGRFs are loaded equally. For this we use the
10047 * start date of the game and we set the counters, etc. to
10048 * 0 so they're the same too. */
10049 TimerGameCalendar::Date date
= TimerGameCalendar::date
;
10050 TimerGameCalendar::Year year
= TimerGameCalendar::year
;
10051 TimerGameCalendar::DateFract date_fract
= TimerGameCalendar::date_fract
;
10053 TimerGameEconomy::Date economy_date
= TimerGameEconomy::date
;
10054 TimerGameEconomy::Year economy_year
= TimerGameEconomy::year
;
10055 TimerGameEconomy::DateFract economy_date_fract
= TimerGameEconomy::date_fract
;
10057 uint64_t tick_counter
= TimerGameTick::counter
;
10058 byte display_opt
= _display_opt
;
10061 TimerGameCalendar::year
= _settings_game
.game_creation
.starting_year
;
10062 TimerGameCalendar::date
= TimerGameCalendar::ConvertYMDToDate(TimerGameCalendar::year
, 0, 1);
10063 TimerGameCalendar::date_fract
= 0;
10065 TimerGameEconomy::year
= _settings_game
.game_creation
.starting_year
.base();
10066 TimerGameEconomy::date
= TimerGameEconomy::ConvertYMDToDate(TimerGameEconomy::year
, 0, 1);
10067 TimerGameEconomy::date_fract
= 0;
10069 TimerGameTick::counter
= 0;
10073 InitializeGRFSpecial();
10078 * Reset the status of all files, so we can 'retry' to load them.
10079 * This is needed when one for example rearranges the NewGRFs in-game
10080 * and a previously disabled NewGRF becomes usable. If it would not
10081 * be reset, the NewGRF would remain disabled even though it should
10082 * have been enabled.
10084 for (GRFConfig
*c
= _grfconfig
; c
!= nullptr; c
= c
->next
) {
10085 if (c
->status
!= GCS_NOT_FOUND
) c
->status
= GCS_UNKNOWN
;
10088 _cur
.spriteid
= load_index
;
10090 /* Load newgrf sprites
10091 * in each loading stage, (try to) open each file specified in the config
10092 * and load information from it. */
10093 for (GrfLoadingStage stage
= GLS_LABELSCAN
; stage
<= GLS_ACTIVATION
; stage
++) {
10094 /* Set activated grfs back to will-be-activated between reservation- and activation-stage.
10095 * This ensures that action7/9 conditions 0x06 - 0x0A work correctly. */
10096 for (GRFConfig
*c
= _grfconfig
; c
!= nullptr; c
= c
->next
) {
10097 if (c
->status
== GCS_ACTIVATED
) c
->status
= GCS_INITIALISED
;
10100 if (stage
== GLS_RESERVE
) {
10101 static const uint32_t overrides
[][2] = {
10102 { 0x44442202, 0x44440111 }, // UKRS addons modifies UKRS
10103 { 0x6D620402, 0x6D620401 }, // DBSetXL ECS extension modifies DBSetXL
10104 { 0x4D656f20, 0x4D656F17 }, // LV4cut modifies LV4
10106 for (size_t i
= 0; i
< lengthof(overrides
); i
++) {
10107 SetNewGRFOverride(BSWAP32(overrides
[i
][0]), BSWAP32(overrides
[i
][1]));
10112 uint num_non_static
= 0;
10114 _cur
.stage
= stage
;
10115 for (GRFConfig
*c
= _grfconfig
; c
!= nullptr; c
= c
->next
) {
10116 if (c
->status
== GCS_DISABLED
|| c
->status
== GCS_NOT_FOUND
) continue;
10117 if (stage
> GLS_INIT
&& HasBit(c
->flags
, GCF_INIT_ONLY
)) continue;
10119 Subdirectory subdir
= num_grfs
< num_baseset
? BASESET_DIR
: NEWGRF_DIR
;
10120 if (!FioCheckFileExists(c
->filename
, subdir
)) {
10121 Debug(grf
, 0, "NewGRF file is missing '{}'; disabling", c
->filename
);
10122 c
->status
= GCS_NOT_FOUND
;
10126 if (stage
== GLS_LABELSCAN
) InitNewGRFFile(c
);
10128 if (!HasBit(c
->flags
, GCF_STATIC
) && !HasBit(c
->flags
, GCF_SYSTEM
)) {
10129 if (num_non_static
== NETWORK_MAX_GRF_COUNT
) {
10130 Debug(grf
, 0, "'{}' is not loaded as the maximum number of non-static GRFs has been reached", c
->filename
);
10131 c
->status
= GCS_DISABLED
;
10132 c
->error
= {STR_NEWGRF_ERROR_MSG_FATAL
, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED
};
10140 LoadNewGRFFile(c
, stage
, subdir
, false);
10141 if (stage
== GLS_RESERVE
) {
10142 SetBit(c
->flags
, GCF_RESERVED
);
10143 } else if (stage
== GLS_ACTIVATION
) {
10144 ClrBit(c
->flags
, GCF_RESERVED
);
10145 assert(GetFileByGRFID(c
->ident
.grfid
) == _cur
.grffile
);
10146 ClearTemporaryNewGRFData(_cur
.grffile
);
10147 BuildCargoTranslationMap();
10148 Debug(sprite
, 2, "LoadNewGRF: Currently {} sprites are loaded", _cur
.spriteid
);
10149 } else if (stage
== GLS_INIT
&& HasBit(c
->flags
, GCF_INIT_ONLY
)) {
10150 /* We're not going to activate this, so free whatever data we allocated */
10151 ClearTemporaryNewGRFData(_cur
.grffile
);
10156 /* Pseudo sprite processing is finished; free temporary stuff */
10157 _cur
.ClearDataForNextFile();
10159 /* Call any functions that should be run after GRFs have been loaded. */
10162 /* Now revert back to the original situation */
10163 TimerGameCalendar::year
= year
;
10164 TimerGameCalendar::date
= date
;
10165 TimerGameCalendar::date_fract
= date_fract
;
10167 TimerGameEconomy::year
= economy_year
;
10168 TimerGameEconomy::date
= economy_date
;
10169 TimerGameEconomy::date_fract
= economy_date_fract
;
10171 TimerGameTick::counter
= tick_counter
;
10172 _display_opt
= display_opt
;