From 828e808444ff38689d455d43920ad4f70e879bdf Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Fri, 21 Mar 2025 19:55:33 +0000 Subject: [PATCH] Codechange: Split NewGRF loader into separate Action handlers. --- src/newgrf.cpp | 8437 +------------------------ src/newgrf/CMakeLists.txt | 39 + src/newgrf/newgrf_act0.cpp | 281 + src/newgrf/newgrf_act0_aircraft.cpp | 201 + src/newgrf/newgrf_act0_airports.cpp | 270 + src/newgrf/newgrf_act0_badges.cpp | 59 + src/newgrf/newgrf_act0_bridges.cpp | 133 + src/newgrf/newgrf_act0_canals.cpp | 56 + src/newgrf/newgrf_act0_cargo.cpp | 177 + src/newgrf/newgrf_act0_globalvar.cpp | 552 ++ src/newgrf/newgrf_act0_houses.cpp | 358 ++ src/newgrf/newgrf_act0_industries.cpp | 708 +++ src/newgrf/newgrf_act0_objects.cpp | 203 + src/newgrf/newgrf_act0_railtypes.cpp | 246 + src/newgrf/newgrf_act0_roadstops.cpp | 156 + src/newgrf/newgrf_act0_roadtypes.cpp | 235 + src/newgrf/newgrf_act0_roadvehs.cpp | 238 + src/newgrf/newgrf_act0_ships.cpp | 225 + src/newgrf/newgrf_act0_sounds.cpp | 76 + src/newgrf/newgrf_act0_stations.cpp | 307 + src/newgrf/newgrf_act0_trains.cpp | 340 + src/newgrf/newgrf_act1.cpp | 89 + src/newgrf/newgrf_act10.cpp | 37 + src/newgrf/newgrf_act11.cpp | 180 + src/newgrf/newgrf_act12.cpp | 80 + src/newgrf/newgrf_act13.cpp | 79 + src/newgrf/newgrf_act14.cpp | 462 ++ src/newgrf/newgrf_act2.cpp | 704 +++ src/newgrf/newgrf_act3.cpp | 778 +++ src/newgrf/newgrf_act4.cpp | 167 + src/newgrf/newgrf_act5.cpp | 198 + src/newgrf/newgrf_act6.cpp | 119 + src/newgrf/newgrf_act7_9.cpp | 353 ++ src/newgrf/newgrf_act8.cpp | 84 + src/newgrf/newgrf_acta.cpp | 102 + src/newgrf/newgrf_actb.cpp | 132 + src/newgrf/newgrf_actc.cpp | 36 + src/newgrf/newgrf_actd.cpp | 491 ++ src/newgrf/newgrf_acte.cpp | 68 + src/newgrf/newgrf_actf.cpp | 103 + src/newgrf/newgrf_internal.h | 77 + src/newgrf/newgrf_internal_vehicle.h | 71 + 42 files changed, 9356 insertions(+), 8351 deletions(-) create mode 100644 src/newgrf/newgrf_act0.cpp create mode 100644 src/newgrf/newgrf_act0_aircraft.cpp create mode 100644 src/newgrf/newgrf_act0_airports.cpp create mode 100644 src/newgrf/newgrf_act0_badges.cpp create mode 100644 src/newgrf/newgrf_act0_bridges.cpp create mode 100644 src/newgrf/newgrf_act0_canals.cpp create mode 100644 src/newgrf/newgrf_act0_cargo.cpp create mode 100644 src/newgrf/newgrf_act0_globalvar.cpp create mode 100644 src/newgrf/newgrf_act0_houses.cpp create mode 100644 src/newgrf/newgrf_act0_industries.cpp create mode 100644 src/newgrf/newgrf_act0_objects.cpp create mode 100644 src/newgrf/newgrf_act0_railtypes.cpp create mode 100644 src/newgrf/newgrf_act0_roadstops.cpp create mode 100644 src/newgrf/newgrf_act0_roadtypes.cpp create mode 100644 src/newgrf/newgrf_act0_roadvehs.cpp create mode 100644 src/newgrf/newgrf_act0_ships.cpp create mode 100644 src/newgrf/newgrf_act0_sounds.cpp create mode 100644 src/newgrf/newgrf_act0_stations.cpp create mode 100644 src/newgrf/newgrf_act0_trains.cpp create mode 100644 src/newgrf/newgrf_act1.cpp create mode 100644 src/newgrf/newgrf_act10.cpp create mode 100644 src/newgrf/newgrf_act11.cpp create mode 100644 src/newgrf/newgrf_act12.cpp create mode 100644 src/newgrf/newgrf_act13.cpp create mode 100644 src/newgrf/newgrf_act14.cpp create mode 100644 src/newgrf/newgrf_act2.cpp create mode 100644 src/newgrf/newgrf_act3.cpp create mode 100644 src/newgrf/newgrf_act4.cpp create mode 100644 src/newgrf/newgrf_act5.cpp create mode 100644 src/newgrf/newgrf_act6.cpp create mode 100644 src/newgrf/newgrf_act7_9.cpp create mode 100644 src/newgrf/newgrf_act8.cpp create mode 100644 src/newgrf/newgrf_acta.cpp create mode 100644 src/newgrf/newgrf_actb.cpp create mode 100644 src/newgrf/newgrf_actc.cpp create mode 100644 src/newgrf/newgrf_actd.cpp create mode 100644 src/newgrf/newgrf_acte.cpp create mode 100644 src/newgrf/newgrf_actf.cpp create mode 100644 src/newgrf/newgrf_internal_vehicle.h diff --git a/src/newgrf.cpp b/src/newgrf.cpp index be82d67602..a0bb429834 100644 --- a/src/newgrf.cpp +++ b/src/newgrf.cpp @@ -8,8 +8,6 @@ /** @file newgrf.cpp Base of all NewGRF support. */ #include "stdafx.h" - -#include #include "core/backup_type.hpp" #include "core/container_func.hpp" #include "debug.h" @@ -20,46 +18,33 @@ #include "town.h" #include "newgrf_engine.h" #include "newgrf_text.h" -#include "fontcache.h" +#include "spritecache.h" #include "currency.h" #include "landscape.h" #include "newgrf_badge.h" -#include "newgrf_badge_type.h" #include "newgrf_cargo.h" -#include "newgrf_house.h" #include "newgrf_sound.h" #include "newgrf_station.h" #include "industrytype.h" -#include "industry_map.h" -#include "newgrf_act5.h" #include "newgrf_canal.h" #include "newgrf_townname.h" #include "newgrf_industries.h" #include "newgrf_airporttiles.h" #include "newgrf_airport.h" #include "newgrf_object.h" -#include "rev.h" -#include "fios.h" -#include "strings_func.h" -#include "timer/timer_game_tick.h" -#include "timer/timer_game_calendar.h" -#include "string_func.h" #include "network/core/config.h" #include "smallmap_gui.h" #include "genworld.h" -#include "error.h" #include "error_func.h" -#include "vehicle_func.h" -#include "language.h" #include "vehicle_base.h" #include "road.h" #include "newgrf_roadstop.h" #include "newgrf/newgrf_bytereader.h" +#include "newgrf/newgrf_internal_vehicle.h" #include "newgrf/newgrf_internal.h" #include "newgrf/newgrf_stringmapping.h" #include "table/strings.h" -#include "table/build_industry.h" #include "safeguards.h" @@ -83,96 +68,12 @@ const std::vector &GetAllGRFFiles() /** Miscellaneous GRF features, set by Action 0x0D, parameter 0x9E */ GrfMiscBits _misc_grf_features{}; -/** 32 * 8 = 256 flags. Apparently TTDPatch uses this many.. */ -static uint32_t _ttdpatch_flags[8]; - /** Indicates which are the newgrf features currently loaded ingame */ GRFLoadedFeatures _loaded_newgrf_features; GrfProcessingState _cur; -/** - * Helper to check whether an image index is valid for a particular NewGRF vehicle. - * @tparam T The type of vehicle. - * @param image_index The image index to check. - * @return True iff the image index is valid, or 0xFD (use new graphics). - */ -template -static inline bool IsValidNewGRFImageIndex(uint8_t image_index) -{ - return image_index == 0xFD || IsValidImageIndex(image_index); -} - -typedef void (*SpecialSpriteHandler)(ByteReader &buf); - -/** The maximum amount of stations a single GRF is allowed to add */ -static const uint NUM_STATIONS_PER_GRF = UINT16_MAX - 1; - -/** Temporary engine data used when loading only */ -struct GRFTempEngineData { - /** Summary state of refittability properties */ - enum Refittability : uint8_t { - UNSET = 0, ///< No properties assigned. Default refit masks shall be activated. - EMPTY, ///< GRF defined vehicle as not-refittable. The vehicle shall only carry the default cargo. - NONEMPTY, ///< GRF defined the vehicle as refittable. If the refitmask is empty after translation (cargotypes not available), disable the vehicle. - }; - - CargoClasses cargo_allowed; ///< Bitmask of cargo classes that are allowed as a refit. - CargoClasses cargo_allowed_required; ///< Bitmask of cargo classes that are required to be all present to allow a cargo as a refit. - CargoClasses cargo_disallowed; ///< Bitmask of cargo classes that are disallowed as a refit. - RailTypeLabel railtypelabel; - uint8_t roadtramtype; - const GRFFile *defaultcargo_grf; ///< GRF defining the cargo translation table to use if the default cargo is the 'first refittable'. - Refittability refittability; ///< Did the newgrf set any refittability property? If not, default refittability will be applied. - uint8_t rv_max_speed; ///< Temporary storage of RV prop 15, maximum speed in mph/0.8 - CargoTypes ctt_include_mask; ///< Cargo types always included in the refit mask. - CargoTypes ctt_exclude_mask; ///< Cargo types always excluded from the refit mask. - - /** - * Update the summary refittability on setting a refittability property. - * @param non_empty true if the GRF sets the vehicle to be refittable. - */ - void UpdateRefittability(bool non_empty) - { - if (non_empty) { - this->refittability = NONEMPTY; - } else if (this->refittability == UNSET) { - this->refittability = EMPTY; - } - } -}; - -static ReferenceThroughBaseContainer> _gted; ///< Temporary engine data used during NewGRF loading - -/** - * Contains the GRF ID of the owner of a vehicle if it has been reserved. - * GRM for vehicles is only used if dynamic engine allocation is disabled, - * so 256 is the number of original engines. */ -static std::array _grm_engines{}; - -/** Contains the GRF ID of the owner of a cargo if it has been reserved */ -static std::array _grm_cargoes{}; - -struct GRFLocation { - uint32_t grfid; - uint32_t nfoline; - - GRFLocation(uint32_t grfid, uint32_t nfoline) : grfid(grfid), nfoline(nfoline) { } - - bool operator<(const GRFLocation &other) const - { - return this->grfid < other.grfid || (this->grfid == other.grfid && this->nfoline < other.nfoline); - } - - bool operator == (const GRFLocation &other) const - { - return this->grfid == other.grfid && this->nfoline == other.nfoline; - } -}; - -static std::map> _grm_sprites; -typedef std::map> GRFLineToSpriteOverride; -static GRFLineToSpriteOverride _grf_line_to_action6_sprite_override; +ReferenceThroughBaseContainer> _gted; ///< Temporary engine data used during NewGRF loading /** * Debug() function dedicated to newGRF debugging messages @@ -194,7 +95,7 @@ void GrfMsgI(int severity, const std::string &msg) * @param grfid The grfID to obtain the file for * @return The file. */ -static GRFFile *GetFileByGRFID(uint32_t grfid) +GRFFile *GetFileByGRFID(uint32_t grfid) { for (GRFFile * const file : _grf_files) { if (file->grfid == grfid) return file; @@ -227,7 +128,7 @@ static void ClearTemporaryNewGRFData(GRFFile *gf) * @param config GRFConfig to disable, nullptr for current. * @return Error message of the GRF for further customisation. */ -static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = nullptr) +GRFError *DisableGrf(StringID message, GRFConfig *config) { GRFFile *file; if (config != nullptr) { @@ -248,6 +149,21 @@ static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = nul return &config->error.value(); } +/** + * Disable a static NewGRF when it is influencing another (non-static) + * NewGRF as this could cause desyncs. + * + * We could just tell the NewGRF querying that the file doesn't exist, + * but that might give unwanted results. Disabling the NewGRF gives the + * best result as no NewGRF author can complain about that. + * @param c The NewGRF to disable. + */ +void DisableStaticNewGRFInfluencingNonStaticNewGRFs(GRFConfig &c) +{ + GRFError *error = DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC, &c); + error->data = _cur.grfconfig->GetName(); +} + static std::map _grf_id_overrides; /** @@ -255,7 +171,7 @@ static std::map _grf_id_overrides; * @param source_grfid The grfID which wants to override another NewGRF. * @param target_grfid The grfID which is being overridden. */ -static void SetNewGRFOverride(uint32_t source_grfid, uint32_t target_grfid) +void SetNewGRFOverride(uint32_t source_grfid, uint32_t target_grfid) { if (target_grfid == 0) { _grf_id_overrides.erase(source_grfid); @@ -270,7 +186,7 @@ static void SetNewGRFOverride(uint32_t source_grfid, uint32_t target_grfid) * Get overridden GRF for current GRF if present. * @return Overridden GRFFile if present, or nullptr. */ -static GRFFile *GetCurrentGRFOverride() +GRFFile *GetCurrentGRFOverride() { auto found = _grf_id_overrides.find(_cur.grffile->grfid); if (found != std::end(_grf_id_overrides)) { @@ -288,7 +204,7 @@ static GRFFile *GetCurrentGRFOverride() * @param static_access If the engine is not present, return nullptr instead of allocating a new engine. (Used for static Action 0x04). * @return The requested engine. */ -static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16_t internal_id, bool static_access = false) +Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16_t internal_id, bool static_access) { /* Hack for add-on GRFs that need to modify another GRF's engines. This lets * them use the same engine slots. */ @@ -382,246 +298,13 @@ EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16_t internal return _engine_mngr.GetID(type, internal_id, scope_grfid); } -/** - * Map the colour modifiers of TTDPatch to those that Open is using. - * @param grf_sprite Pointer to the structure been modified. - */ -static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite) -{ - if (HasBit(grf_sprite->pal, 14)) { - ClrBit(grf_sprite->pal, 14); - SetBit(grf_sprite->sprite, SPRITE_MODIFIER_OPAQUE); - } - if (HasBit(grf_sprite->sprite, 14)) { - ClrBit(grf_sprite->sprite, 14); - SetBit(grf_sprite->sprite, PALETTE_MODIFIER_TRANSPARENT); - } - if (HasBit(grf_sprite->sprite, 15)) { - ClrBit(grf_sprite->sprite, 15); - SetBit(grf_sprite->sprite, PALETTE_MODIFIER_COLOUR); - } -} - -/** - * Read a sprite and a palette from the GRF and convert them into a format - * suitable to OpenTTD. - * @param buf Input stream. - * @param read_flags Whether to read TileLayoutFlags. - * @param invert_action1_flag Set to true, if palette bit 15 means 'not from action 1'. - * @param use_cur_spritesets Whether to use currently referenceable action 1 sets. - * @param feature GrfSpecFeature to use spritesets from. - * @param[out] grf_sprite Read sprite and palette. - * @param[out] max_sprite_offset Optionally returns the number of sprites in the spriteset of the sprite. (0 if no spritset) - * @param[out] max_palette_offset Optionally returns the number of sprites in the spriteset of the palette. (0 if no spritset) - * @return Read TileLayoutFlags. - */ -static TileLayoutFlags ReadSpriteLayoutSprite(ByteReader &buf, bool read_flags, bool invert_action1_flag, bool use_cur_spritesets, int feature, PalSpriteID *grf_sprite, uint16_t *max_sprite_offset = nullptr, uint16_t *max_palette_offset = nullptr) -{ - grf_sprite->sprite = buf.ReadWord(); - grf_sprite->pal = buf.ReadWord(); - TileLayoutFlags flags = read_flags ? (TileLayoutFlags)buf.ReadWord() : TLF_NOTHING; - - MapSpriteMappingRecolour(grf_sprite); - - bool custom_sprite = HasBit(grf_sprite->pal, 15) != invert_action1_flag; - ClrBit(grf_sprite->pal, 15); - if (custom_sprite) { - /* Use sprite from Action 1 */ - uint index = GB(grf_sprite->sprite, 0, 14); - if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) { - GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset {}", index); - grf_sprite->sprite = SPR_IMG_QUERY; - grf_sprite->pal = PAL_NONE; - } else { - SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index; - if (max_sprite_offset != nullptr) *max_sprite_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX; - SB(grf_sprite->sprite, 0, SPRITE_WIDTH, sprite); - SetBit(grf_sprite->sprite, SPRITE_MODIFIER_CUSTOM_SPRITE); - } - } else if ((flags & TLF_SPRITE_VAR10) && !(flags & TLF_SPRITE_REG_FLAGS)) { - GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout specifies var10 value for non-action-1 sprite"); - DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT); - return flags; - } - - if (flags & TLF_CUSTOM_PALETTE) { - /* Use palette from Action 1 */ - uint index = GB(grf_sprite->pal, 0, 14); - if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) { - GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset {} for 'palette'", index); - grf_sprite->pal = PAL_NONE; - } else { - SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index; - if (max_palette_offset != nullptr) *max_palette_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX; - SB(grf_sprite->pal, 0, SPRITE_WIDTH, sprite); - SetBit(grf_sprite->pal, SPRITE_MODIFIER_CUSTOM_SPRITE); - } - } else if ((flags & TLF_PALETTE_VAR10) && !(flags & TLF_PALETTE_REG_FLAGS)) { - GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 value for non-action-1 palette"); - DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT); - return flags; - } - - return flags; -} - -/** - * Preprocess the TileLayoutFlags and read register modifiers from the GRF. - * @param buf Input stream. - * @param flags TileLayoutFlags to process. - * @param is_parent Whether the sprite is a parentsprite with a bounding box. - * @param dts Sprite layout to insert data into. - * @param index Sprite index to process; 0 for ground sprite. - */ -static void ReadSpriteLayoutRegisters(ByteReader &buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index) -{ - if (!(flags & TLF_DRAWING_FLAGS)) return; - - if (dts->registers.empty()) dts->AllocateRegisters(); - TileLayoutRegisters ®s = const_cast(dts->registers[index]); - regs.flags = flags & TLF_DRAWING_FLAGS; - - if (flags & TLF_DODRAW) regs.dodraw = buf.ReadByte(); - if (flags & TLF_SPRITE) regs.sprite = buf.ReadByte(); - if (flags & TLF_PALETTE) regs.palette = buf.ReadByte(); - - if (is_parent) { - if (flags & TLF_BB_XY_OFFSET) { - regs.delta.parent[0] = buf.ReadByte(); - regs.delta.parent[1] = buf.ReadByte(); - } - if (flags & TLF_BB_Z_OFFSET) regs.delta.parent[2] = buf.ReadByte(); - } else { - if (flags & TLF_CHILD_X_OFFSET) regs.delta.child[0] = buf.ReadByte(); - if (flags & TLF_CHILD_Y_OFFSET) regs.delta.child[1] = buf.ReadByte(); - } - - if (flags & TLF_SPRITE_VAR10) { - regs.sprite_var10 = buf.ReadByte(); - if (regs.sprite_var10 > TLR_MAX_VAR10) { - GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 ({}) exceeding the maximal allowed value {}", regs.sprite_var10, TLR_MAX_VAR10); - DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT); - return; - } - } - - if (flags & TLF_PALETTE_VAR10) { - regs.palette_var10 = buf.ReadByte(); - if (regs.palette_var10 > TLR_MAX_VAR10) { - GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 ({}) exceeding the maximal allowed value {}", regs.palette_var10, TLR_MAX_VAR10); - DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT); - return; - } - } -} - -/** - * Read a spritelayout from the GRF. - * @param buf Input - * @param num_building_sprites Number of building sprites to read - * @param use_cur_spritesets Whether to use currently referenceable action 1 sets. - * @param feature GrfSpecFeature to use spritesets from. - * @param allow_var10 Whether the spritelayout may specify var10 values for resolving multiple action-1-2-3 chains - * @param no_z_position Whether bounding boxes have no Z offset - * @param dts Layout container to output into - * @return True on error (GRF was disabled). - */ -static bool ReadSpriteLayout(ByteReader &buf, uint num_building_sprites, bool use_cur_spritesets, uint8_t feature, bool allow_var10, bool no_z_position, NewGRFSpriteLayout *dts) -{ - bool has_flags = HasBit(num_building_sprites, 6); - ClrBit(num_building_sprites, 6); - TileLayoutFlags valid_flags = TLF_KNOWN_FLAGS; - if (!allow_var10) valid_flags &= ~TLF_VAR10_FLAGS; - dts->Allocate(num_building_sprites); // allocate before reading groundsprite flags - - std::vector max_sprite_offset(num_building_sprites + 1, 0); - std::vector max_palette_offset(num_building_sprites + 1, 0); - - /* Groundsprite */ - TileLayoutFlags flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &dts->ground, max_sprite_offset.data(), max_palette_offset.data()); - if (_cur.skip_sprites < 0) return true; - - if (flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS)) { - GrfMsg(1, "ReadSpriteLayout: Spritelayout uses invalid flag 0x{:X} for ground sprite", flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS)); - DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT); - return true; - } - - ReadSpriteLayoutRegisters(buf, flags, false, dts, 0); - if (_cur.skip_sprites < 0) return true; - - for (uint i = 0; i < num_building_sprites; i++) { - DrawTileSeqStruct *seq = const_cast(&dts->seq[i]); - - flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &seq->image, max_sprite_offset.data() + i + 1, max_palette_offset.data() + i + 1); - if (_cur.skip_sprites < 0) return true; - - if (flags & ~valid_flags) { - GrfMsg(1, "ReadSpriteLayout: Spritelayout uses unknown flag 0x{:X}", flags & ~valid_flags); - DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT); - return true; - } - - seq->delta_x = buf.ReadByte(); - seq->delta_y = buf.ReadByte(); - - if (!no_z_position) seq->delta_z = buf.ReadByte(); - - if (seq->IsParentSprite()) { - seq->size_x = buf.ReadByte(); - seq->size_y = buf.ReadByte(); - seq->size_z = buf.ReadByte(); - } - - ReadSpriteLayoutRegisters(buf, flags, seq->IsParentSprite(), dts, i + 1); - if (_cur.skip_sprites < 0) return true; - } - - /* Check if the number of sprites per spriteset is consistent */ - bool is_consistent = true; - dts->consistent_max_offset = 0; - for (uint i = 0; i < num_building_sprites + 1; i++) { - if (max_sprite_offset[i] > 0) { - if (dts->consistent_max_offset == 0) { - dts->consistent_max_offset = max_sprite_offset[i]; - } else if (dts->consistent_max_offset != max_sprite_offset[i]) { - is_consistent = false; - break; - } - } - if (max_palette_offset[i] > 0) { - if (dts->consistent_max_offset == 0) { - dts->consistent_max_offset = max_palette_offset[i]; - } else if (dts->consistent_max_offset != max_palette_offset[i]) { - is_consistent = false; - break; - } - } - } - - /* When the Action1 sets are unknown, everything should be 0 (no spriteset usage) or UINT16_MAX (some spriteset usage) */ - assert(use_cur_spritesets || (is_consistent && (dts->consistent_max_offset == 0 || dts->consistent_max_offset == UINT16_MAX))); - - if (!is_consistent || !dts->registers.empty()) { - dts->consistent_max_offset = 0; - if (dts->registers.empty()) dts->AllocateRegisters(); - - for (uint i = 0; i < num_building_sprites + 1; i++) { - TileLayoutRegisters ®s = const_cast(dts->registers[i]); - regs.max_sprite_offset = max_sprite_offset[i]; - regs.max_palette_offset = max_palette_offset[i]; - } - } - - return false; -} /** * Translate the refit mask. refit_mask is uint32_t as it has not been mapped to CargoTypes. */ -static CargoTypes TranslateRefitMask(uint32_t refit_mask) +CargoTypes TranslateRefitMask(uint32_t refit_mask) { CargoTypes result = 0; for (uint8_t bit : SetBitIterator(refit_mask)) { @@ -638,7 +321,7 @@ static CargoTypes TranslateRefitMask(uint32_t refit_mask) * @param error_location Function name for grf error messages * @param[out] index If \a base_pointer is valid, \a index is assigned to the matching price; else it is left unchanged */ -static void ConvertTTDBasePrice(uint32_t base_pointer, const char *error_location, Price *index) +void ConvertTTDBasePrice(uint32_t base_pointer, const char *error_location, Price *index) { /* Special value for 'none' */ if (base_pointer == 0) { @@ -657,1785 +340,6 @@ static void ConvertTTDBasePrice(uint32_t base_pointer, const char *error_locatio *index = (Price)((base_pointer - start) / size); } -/** Possible return values for the FeatureChangeInfo functions */ -enum ChangeInfoResult : uint8_t { - CIR_SUCCESS, ///< Variable was parsed and read - CIR_DISABLED, ///< GRF was disabled due to error - CIR_UNHANDLED, ///< Variable was parsed but unread - CIR_UNKNOWN, ///< Variable is unknown - CIR_INVALID_ID, ///< Attempt to modify an invalid ID -}; - -using ChangeInfoHandler = ChangeInfoResult(uint first, uint last, int prop, ByteReader &buf); - -/** - * Define properties common to all vehicles - * @param ei Engine info. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult CommonVehicleChangeInfo(EngineInfo *ei, int prop, ByteReader &buf) -{ - switch (prop) { - case 0x00: // Introduction date - ei->base_intro = CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR + buf.ReadWord(); - break; - - case 0x02: // Decay speed - ei->decay_speed = buf.ReadByte(); - break; - - case 0x03: // Vehicle life - ei->lifelength = TimerGameCalendar::Year{buf.ReadByte()}; - break; - - case 0x04: // Model life - ei->base_life = TimerGameCalendar::Year{buf.ReadByte()}; - break; - - case 0x06: // Climates available - ei->climates = LandscapeTypes{buf.ReadByte()}; - break; - - case PROP_VEHICLE_LOAD_AMOUNT: // 0x07 Loading speed - /* Amount of cargo loaded during a vehicle's "loading tick" */ - ei->load_amount = buf.ReadByte(); - break; - - default: - return CIR_UNKNOWN; - } - - return CIR_SUCCESS; -} - -/** - * Skip a list of badges. - * @param buf Buffer reader containing list of badges to skip. - */ -static void SkipBadgeList(ByteReader &buf) -{ - uint16_t count = buf.ReadWord(); - while (count-- > 0) { - buf.ReadWord(); - } -} - -/** - * Read a list of badges. - * @param buf Buffer reader containing list of badges to read. - * @param feature The feature of the badge list. - * @returns list of badges. - */ -static std::vector ReadBadgeList(ByteReader &buf, GrfSpecFeature feature) -{ - uint16_t count = buf.ReadWord(); - - std::vector badges; - badges.reserve(count); - - while (count-- > 0) { - uint16_t local_index = buf.ReadWord(); - if (local_index >= std::size(_cur.grffile->badge_list)) { - GrfMsg(1, "ReadBadgeList: Badge label {} out of range (max {}), skipping.", local_index, std::size(_cur.grffile->badge_list) - 1); - continue; - } - - BadgeID index = _cur.grffile->badge_list[local_index]; - - /* Is badge already present? */ - if (std::ranges::find(badges, index) != std::end(badges)) continue; - - badges.push_back(index); - MarkBadgeSeen(index, feature); - } - - return badges; -} - -/** - * Define properties for rail vehicles - * @param first Local ID of the first vehicle. - * @param last Local ID of the last vehicle. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult RailVehicleChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - for (uint id = first; id < last; ++id) { - Engine *e = GetNewEngine(_cur.grffile, VEH_TRAIN, id); - if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles - - EngineInfo *ei = &e->info; - RailVehicleInfo *rvi = &e->u.rail; - - switch (prop) { - case 0x05: { // Track type - uint8_t tracktype = buf.ReadByte(); - - if (tracktype < _cur.grffile->railtype_list.size()) { - _gted[e->index].railtypelabel = _cur.grffile->railtype_list[tracktype]; - break; - } - - switch (tracktype) { - case 0: _gted[e->index].railtypelabel = rvi->engclass >= 2 ? RAILTYPE_LABEL_ELECTRIC : RAILTYPE_LABEL_RAIL; break; - case 1: _gted[e->index].railtypelabel = RAILTYPE_LABEL_MONO; break; - case 2: _gted[e->index].railtypelabel = RAILTYPE_LABEL_MAGLEV; break; - default: - GrfMsg(1, "RailVehicleChangeInfo: Invalid track type {} specified, ignoring", tracktype); - break; - } - break; - } - - case 0x08: // AI passenger service - /* Tells the AI that this engine is designed for - * passenger services and shouldn't be used for freight. */ - rvi->ai_passenger_only = buf.ReadByte(); - break; - - case PROP_TRAIN_SPEED: { // 0x09 Speed (1 unit is 1 km-ish/h) - uint16_t speed = buf.ReadWord(); - if (speed == 0xFFFF) speed = 0; - - rvi->max_speed = speed; - break; - } - - case PROP_TRAIN_POWER: // 0x0B Power - rvi->power = buf.ReadWord(); - - /* Set engine / wagon state based on power */ - if (rvi->power != 0) { - if (rvi->railveh_type == RAILVEH_WAGON) { - rvi->railveh_type = RAILVEH_SINGLEHEAD; - } - } else { - rvi->railveh_type = RAILVEH_WAGON; - } - break; - - case PROP_TRAIN_RUNNING_COST_FACTOR: // 0x0D Running cost factor - rvi->running_cost = buf.ReadByte(); - break; - - case 0x0E: // Running cost base - ConvertTTDBasePrice(buf.ReadDWord(), "RailVehicleChangeInfo", &rvi->running_cost_class); - break; - - case 0x12: { // Sprite ID - uint8_t spriteid = buf.ReadByte(); - uint8_t orig_spriteid = spriteid; - - /* TTD sprite IDs point to a location in a 16bit array, but we use it - * as an array index, so we need it to be half the original value. */ - if (spriteid < 0xFD) spriteid >>= 1; - - if (IsValidNewGRFImageIndex(spriteid)) { - rvi->image_index = spriteid; - } else { - GrfMsg(1, "RailVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid); - rvi->image_index = 0; - } - break; - } - - case 0x13: { // Dual-headed - uint8_t dual = buf.ReadByte(); - - if (dual != 0) { - rvi->railveh_type = RAILVEH_MULTIHEAD; - } else { - rvi->railveh_type = rvi->power == 0 ? - RAILVEH_WAGON : RAILVEH_SINGLEHEAD; - } - break; - } - - case PROP_TRAIN_CARGO_CAPACITY: // 0x14 Cargo capacity - rvi->capacity = buf.ReadByte(); - break; - - case 0x15: { // Cargo type - _gted[e->index].defaultcargo_grf = _cur.grffile; - uint8_t ctype = buf.ReadByte(); - - if (ctype == 0xFF) { - /* 0xFF is specified as 'use first refittable' */ - ei->cargo_type = INVALID_CARGO; - } else { - /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */ - ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile); - if (ei->cargo_type == INVALID_CARGO) GrfMsg(2, "RailVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype); - } - ei->cargo_label = CT_INVALID; - break; - } - - case PROP_TRAIN_WEIGHT: // 0x16 Weight - SB(rvi->weight, 0, 8, buf.ReadByte()); - break; - - case PROP_TRAIN_COST_FACTOR: // 0x17 Cost factor - rvi->cost_factor = buf.ReadByte(); - break; - - case 0x18: // AI rank - GrfMsg(2, "RailVehicleChangeInfo: Property 0x18 'AI rank' not used by NoAI, ignored."); - buf.ReadByte(); - break; - - case 0x19: { // Engine traction type - /* What do the individual numbers mean? - * 0x00 .. 0x07: Steam - * 0x08 .. 0x27: Diesel - * 0x28 .. 0x31: Electric - * 0x32 .. 0x37: Monorail - * 0x38 .. 0x41: Maglev - */ - uint8_t traction = buf.ReadByte(); - EngineClass engclass; - - if (traction <= 0x07) { - engclass = EC_STEAM; - } else if (traction <= 0x27) { - engclass = EC_DIESEL; - } else if (traction <= 0x31) { - engclass = EC_ELECTRIC; - } else if (traction <= 0x37) { - engclass = EC_MONORAIL; - } else if (traction <= 0x41) { - engclass = EC_MAGLEV; - } else { - break; - } - - if (_cur.grffile->railtype_list.empty()) { - /* Use traction type to select between normal and electrified - * rail only when no translation list is in place. */ - if (_gted[e->index].railtypelabel == RAILTYPE_LABEL_RAIL && engclass >= EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_LABEL_ELECTRIC; - if (_gted[e->index].railtypelabel == RAILTYPE_LABEL_ELECTRIC && engclass < EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_LABEL_RAIL; - } - - rvi->engclass = engclass; - break; - } - - case 0x1A: // Alter purchase list sort order - AlterVehicleListOrder(e->index, buf.ReadExtendedByte()); - break; - - case 0x1B: // Powered wagons power bonus - rvi->pow_wag_power = buf.ReadWord(); - break; - - case 0x1C: // Refit cost - ei->refit_cost = buf.ReadByte(); - break; - - case 0x1D: { // Refit cargo - uint32_t mask = buf.ReadDWord(); - _gted[e->index].UpdateRefittability(mask != 0); - ei->refit_mask = TranslateRefitMask(mask); - _gted[e->index].defaultcargo_grf = _cur.grffile; - break; - } - - case 0x1E: { // Callback - auto mask = ei->callback_mask.base(); - SB(mask, 0, 8, buf.ReadByte()); - ei->callback_mask = VehicleCallbackMasks{mask}; - break; - } - - case PROP_TRAIN_TRACTIVE_EFFORT: // 0x1F Tractive effort coefficient - rvi->tractive_effort = buf.ReadByte(); - break; - - case 0x20: // Air drag - rvi->air_drag = buf.ReadByte(); - break; - - case PROP_TRAIN_SHORTEN_FACTOR: // 0x21 Shorter vehicle - rvi->shorten_factor = buf.ReadByte(); - break; - - case 0x22: // Visual effect - rvi->visual_effect = buf.ReadByte(); - /* Avoid accidentally setting visual_effect to the default value - * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */ - if (rvi->visual_effect == VE_DEFAULT) { - assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT)); - SB(rvi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0); - } - break; - - case 0x23: // Powered wagons weight bonus - rvi->pow_wag_weight = buf.ReadByte(); - break; - - case 0x24: { // High byte of vehicle weight - uint8_t weight = buf.ReadByte(); - - if (weight > 4) { - GrfMsg(2, "RailVehicleChangeInfo: Nonsensical weight of {} tons, ignoring", weight << 8); - } else { - SB(rvi->weight, 8, 8, weight); - } - break; - } - - case PROP_TRAIN_USER_DATA: // 0x25 User-defined bit mask to set when checking veh. var. 42 - rvi->user_def_data = buf.ReadByte(); - break; - - case 0x26: // Retire vehicle early - ei->retire_early = buf.ReadByte(); - break; - - case 0x27: // Miscellaneous flags - ei->misc_flags = static_cast(buf.ReadByte()); - _loaded_newgrf_features.has_2CC |= ei->misc_flags.Test(EngineMiscFlag::Uses2CC); - break; - - case 0x28: // Cargo classes allowed - _gted[e->index].cargo_allowed = CargoClasses{buf.ReadWord()}; - _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed.Any()); - _gted[e->index].defaultcargo_grf = _cur.grffile; - break; - - case 0x29: // Cargo classes disallowed - _gted[e->index].cargo_disallowed = CargoClasses{buf.ReadWord()}; - _gted[e->index].UpdateRefittability(false); - break; - - case 0x2A: // Long format introduction date (days since year 0) - ei->base_intro = TimerGameCalendar::Date(buf.ReadDWord()); - break; - - case PROP_TRAIN_CARGO_AGE_PERIOD: // 0x2B Cargo aging period - ei->cargo_age_period = buf.ReadWord(); - break; - - case 0x2C: // CTT refit include list - case 0x2D: { // CTT refit exclude list - uint8_t count = buf.ReadByte(); - _gted[e->index].UpdateRefittability(prop == 0x2C && count != 0); - if (prop == 0x2C) _gted[e->index].defaultcargo_grf = _cur.grffile; - CargoTypes &ctt = prop == 0x2C ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask; - ctt = 0; - while (count--) { - CargoType ctype = GetCargoTranslation(buf.ReadByte(), _cur.grffile); - if (IsValidCargoType(ctype)) SetBit(ctt, ctype); - } - break; - } - - case PROP_TRAIN_CURVE_SPEED_MOD: // 0x2E Curve speed modifier - rvi->curve_speed_mod = buf.ReadWord(); - break; - - case 0x2F: // Engine variant - ei->variant_id = static_cast(buf.ReadWord()); - break; - - case 0x30: // Extra miscellaneous flags - ei->extra_flags = static_cast(buf.ReadDWord()); - break; - - case 0x31: { // Callback additional mask - auto mask = ei->callback_mask.base(); - SB(mask, 8, 8, buf.ReadByte()); - ei->callback_mask = VehicleCallbackMasks{mask}; - break; - } - - case 0x32: // Cargo classes required for a refit. - _gted[e->index].cargo_allowed_required = CargoClasses{buf.ReadWord()}; - break; - - case 0x33: // Badge list - e->badges = ReadBadgeList(buf, GSF_TRAINS); - break; - - default: - ret = CommonVehicleChangeInfo(ei, prop, buf); - break; - } - } - - return ret; -} - -/** - * Define properties for road vehicles - * @param first Local ID of the first vehicle. - * @param last Local ID of the last vehicle. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult RoadVehicleChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - for (uint id = first; id < last; ++id) { - Engine *e = GetNewEngine(_cur.grffile, VEH_ROAD, id); - if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles - - EngineInfo *ei = &e->info; - RoadVehicleInfo *rvi = &e->u.road; - - switch (prop) { - case 0x05: // Road/tram type - /* RoadTypeLabel is looked up later after the engine's road/tram - * flag is set, however 0 means the value has not been set. */ - _gted[e->index].roadtramtype = buf.ReadByte() + 1; - break; - - case 0x08: // Speed (1 unit is 0.5 kmh) - rvi->max_speed = buf.ReadByte(); - break; - - case PROP_ROADVEH_RUNNING_COST_FACTOR: // 0x09 Running cost factor - rvi->running_cost = buf.ReadByte(); - break; - - case 0x0A: // Running cost base - ConvertTTDBasePrice(buf.ReadDWord(), "RoadVehicleChangeInfo", &rvi->running_cost_class); - break; - - case 0x0E: { // Sprite ID - uint8_t spriteid = buf.ReadByte(); - uint8_t orig_spriteid = spriteid; - - /* cars have different custom id in the GRF file */ - if (spriteid == 0xFF) spriteid = 0xFD; - - if (spriteid < 0xFD) spriteid >>= 1; - - if (IsValidNewGRFImageIndex(spriteid)) { - rvi->image_index = spriteid; - } else { - GrfMsg(1, "RoadVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid); - rvi->image_index = 0; - } - break; - } - - case PROP_ROADVEH_CARGO_CAPACITY: // 0x0F Cargo capacity - rvi->capacity = buf.ReadByte(); - break; - - case 0x10: { // Cargo type - _gted[e->index].defaultcargo_grf = _cur.grffile; - uint8_t ctype = buf.ReadByte(); - - if (ctype == 0xFF) { - /* 0xFF is specified as 'use first refittable' */ - ei->cargo_type = INVALID_CARGO; - } else { - /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */ - ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile); - if (ei->cargo_type == INVALID_CARGO) GrfMsg(2, "RoadVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype); - } - ei->cargo_label = CT_INVALID; - break; - } - - case PROP_ROADVEH_COST_FACTOR: // 0x11 Cost factor - rvi->cost_factor = buf.ReadByte(); - break; - - case 0x12: // SFX - rvi->sfx = GetNewGRFSoundID(_cur.grffile, buf.ReadByte()); - break; - - case PROP_ROADVEH_POWER: // Power in units of 10 HP. - rvi->power = buf.ReadByte(); - break; - - case PROP_ROADVEH_WEIGHT: // Weight in units of 1/4 tons. - rvi->weight = buf.ReadByte(); - break; - - case PROP_ROADVEH_SPEED: // Speed in mph/0.8 - _gted[e->index].rv_max_speed = buf.ReadByte(); - break; - - case 0x16: { // Cargoes available for refitting - uint32_t mask = buf.ReadDWord(); - _gted[e->index].UpdateRefittability(mask != 0); - ei->refit_mask = TranslateRefitMask(mask); - _gted[e->index].defaultcargo_grf = _cur.grffile; - break; - } - - case 0x17: { // Callback mask - auto mask = ei->callback_mask.base(); - SB(mask, 0, 8, buf.ReadByte()); - ei->callback_mask = VehicleCallbackMasks{mask}; - break; - } - - case PROP_ROADVEH_TRACTIVE_EFFORT: // Tractive effort coefficient in 1/256. - rvi->tractive_effort = buf.ReadByte(); - break; - - case 0x19: // Air drag - rvi->air_drag = buf.ReadByte(); - break; - - case 0x1A: // Refit cost - ei->refit_cost = buf.ReadByte(); - break; - - case 0x1B: // Retire vehicle early - ei->retire_early = buf.ReadByte(); - break; - - case 0x1C: // Miscellaneous flags - ei->misc_flags = static_cast(buf.ReadByte()); - _loaded_newgrf_features.has_2CC |= ei->misc_flags.Test(EngineMiscFlag::Uses2CC); - break; - - case 0x1D: // Cargo classes allowed - _gted[e->index].cargo_allowed = CargoClasses{buf.ReadWord()}; - _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed.Any()); - _gted[e->index].defaultcargo_grf = _cur.grffile; - break; - - case 0x1E: // Cargo classes disallowed - _gted[e->index].cargo_disallowed = CargoClasses{buf.ReadWord()}; - _gted[e->index].UpdateRefittability(false); - break; - - case 0x1F: // Long format introduction date (days since year 0) - ei->base_intro = TimerGameCalendar::Date(buf.ReadDWord()); - break; - - case 0x20: // Alter purchase list sort order - AlterVehicleListOrder(e->index, buf.ReadExtendedByte()); - break; - - case 0x21: // Visual effect - rvi->visual_effect = buf.ReadByte(); - /* Avoid accidentally setting visual_effect to the default value - * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */ - if (rvi->visual_effect == VE_DEFAULT) { - assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT)); - SB(rvi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0); - } - break; - - case PROP_ROADVEH_CARGO_AGE_PERIOD: // 0x22 Cargo aging period - ei->cargo_age_period = buf.ReadWord(); - break; - - case PROP_ROADVEH_SHORTEN_FACTOR: // 0x23 Shorter vehicle - rvi->shorten_factor = buf.ReadByte(); - break; - - case 0x24: // CTT refit include list - case 0x25: { // CTT refit exclude list - uint8_t count = buf.ReadByte(); - _gted[e->index].UpdateRefittability(prop == 0x24 && count != 0); - if (prop == 0x24) _gted[e->index].defaultcargo_grf = _cur.grffile; - CargoTypes &ctt = prop == 0x24 ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask; - ctt = 0; - while (count--) { - CargoType ctype = GetCargoTranslation(buf.ReadByte(), _cur.grffile); - if (IsValidCargoType(ctype)) SetBit(ctt, ctype); - } - break; - } - - case 0x26: // Engine variant - ei->variant_id = static_cast(buf.ReadWord()); - break; - - case 0x27: // Extra miscellaneous flags - ei->extra_flags = static_cast(buf.ReadDWord()); - break; - - case 0x28: { // Callback additional mask - auto mask = ei->callback_mask.base(); - SB(mask, 8, 8, buf.ReadByte()); - ei->callback_mask = VehicleCallbackMasks{mask}; - break; - } - - case 0x29: // Cargo classes required for a refit. - _gted[e->index].cargo_allowed_required = CargoClasses{buf.ReadWord()}; - break; - - case 0x2A: // Badge list - e->badges = ReadBadgeList(buf, GSF_ROADVEHICLES); - break; - - default: - ret = CommonVehicleChangeInfo(ei, prop, buf); - break; - } - } - - return ret; -} - -/** - * Define properties for ships - * @param first Local ID of the first vehicle. - * @param last Local ID of the last vehicle. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult ShipVehicleChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - for (uint id = first; id < last; ++id) { - Engine *e = GetNewEngine(_cur.grffile, VEH_SHIP, id); - if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles - - EngineInfo *ei = &e->info; - ShipVehicleInfo *svi = &e->u.ship; - - switch (prop) { - case 0x08: { // Sprite ID - uint8_t spriteid = buf.ReadByte(); - uint8_t orig_spriteid = spriteid; - - /* ships have different custom id in the GRF file */ - if (spriteid == 0xFF) spriteid = 0xFD; - - if (spriteid < 0xFD) spriteid >>= 1; - - if (IsValidNewGRFImageIndex(spriteid)) { - svi->image_index = spriteid; - } else { - GrfMsg(1, "ShipVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid); - svi->image_index = 0; - } - break; - } - - case 0x09: // Refittable - svi->old_refittable = (buf.ReadByte() != 0); - break; - - case PROP_SHIP_COST_FACTOR: // 0x0A Cost factor - svi->cost_factor = buf.ReadByte(); - break; - - case PROP_SHIP_SPEED: // 0x0B Speed (1 unit is 0.5 km-ish/h). Use 0x23 to achieve higher speeds. - svi->max_speed = buf.ReadByte(); - break; - - case 0x0C: { // Cargo type - _gted[e->index].defaultcargo_grf = _cur.grffile; - uint8_t ctype = buf.ReadByte(); - - if (ctype == 0xFF) { - /* 0xFF is specified as 'use first refittable' */ - ei->cargo_type = INVALID_CARGO; - } else { - /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */ - ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile); - if (ei->cargo_type == INVALID_CARGO) GrfMsg(2, "ShipVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype); - } - ei->cargo_label = CT_INVALID; - break; - } - - case PROP_SHIP_CARGO_CAPACITY: // 0x0D Cargo capacity - svi->capacity = buf.ReadWord(); - break; - - case PROP_SHIP_RUNNING_COST_FACTOR: // 0x0F Running cost factor - svi->running_cost = buf.ReadByte(); - break; - - case 0x10: // SFX - svi->sfx = GetNewGRFSoundID(_cur.grffile, buf.ReadByte()); - break; - - case 0x11: { // Cargoes available for refitting - uint32_t mask = buf.ReadDWord(); - _gted[e->index].UpdateRefittability(mask != 0); - ei->refit_mask = TranslateRefitMask(mask); - _gted[e->index].defaultcargo_grf = _cur.grffile; - break; - } - - case 0x12: { // Callback mask - auto mask = ei->callback_mask.base(); - SB(mask, 0, 8, buf.ReadByte()); - ei->callback_mask = VehicleCallbackMasks{mask}; - break; - } - - case 0x13: // Refit cost - ei->refit_cost = buf.ReadByte(); - break; - - case 0x14: // Ocean speed fraction - svi->ocean_speed_frac = buf.ReadByte(); - break; - - case 0x15: // Canal speed fraction - svi->canal_speed_frac = buf.ReadByte(); - break; - - case 0x16: // Retire vehicle early - ei->retire_early = buf.ReadByte(); - break; - - case 0x17: // Miscellaneous flags - ei->misc_flags = static_cast(buf.ReadByte()); - _loaded_newgrf_features.has_2CC |= ei->misc_flags.Test(EngineMiscFlag::Uses2CC); - break; - - case 0x18: // Cargo classes allowed - _gted[e->index].cargo_allowed = CargoClasses{buf.ReadWord()}; - _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed.Any()); - _gted[e->index].defaultcargo_grf = _cur.grffile; - break; - - case 0x19: // Cargo classes disallowed - _gted[e->index].cargo_disallowed = CargoClasses{buf.ReadWord()}; - _gted[e->index].UpdateRefittability(false); - break; - - case 0x1A: // Long format introduction date (days since year 0) - ei->base_intro = TimerGameCalendar::Date(buf.ReadDWord()); - break; - - case 0x1B: // Alter purchase list sort order - AlterVehicleListOrder(e->index, buf.ReadExtendedByte()); - break; - - case 0x1C: // Visual effect - svi->visual_effect = buf.ReadByte(); - /* Avoid accidentally setting visual_effect to the default value - * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */ - if (svi->visual_effect == VE_DEFAULT) { - assert(HasBit(svi->visual_effect, VE_DISABLE_EFFECT)); - SB(svi->visual_effect, VE_TYPE_START, VE_TYPE_COUNT, 0); - } - break; - - case PROP_SHIP_CARGO_AGE_PERIOD: // 0x1D Cargo aging period - ei->cargo_age_period = buf.ReadWord(); - break; - - case 0x1E: // CTT refit include list - case 0x1F: { // CTT refit exclude list - uint8_t count = buf.ReadByte(); - _gted[e->index].UpdateRefittability(prop == 0x1E && count != 0); - if (prop == 0x1E) _gted[e->index].defaultcargo_grf = _cur.grffile; - CargoTypes &ctt = prop == 0x1E ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask; - ctt = 0; - while (count--) { - CargoType ctype = GetCargoTranslation(buf.ReadByte(), _cur.grffile); - if (IsValidCargoType(ctype)) SetBit(ctt, ctype); - } - break; - } - - case 0x20: // Engine variant - ei->variant_id = static_cast(buf.ReadWord()); - break; - - case 0x21: // Extra miscellaneous flags - ei->extra_flags = static_cast(buf.ReadDWord()); - break; - - case 0x22: { // Callback additional mask - auto mask = ei->callback_mask.base(); - SB(mask, 8, 8, buf.ReadByte()); - ei->callback_mask = VehicleCallbackMasks{mask}; - break; - } - - case 0x23: // Speed (1 unit is 0.5 km-ish/h) - svi->max_speed = buf.ReadWord(); - break; - - case 0x24: // Acceleration (1 unit is 0.5 km-ish/h per tick) - svi->acceleration = std::max(1, buf.ReadByte()); - break; - - case 0x25: // Cargo classes required for a refit. - _gted[e->index].cargo_allowed_required = CargoClasses{buf.ReadWord()}; - break; - - case 0x26: // Badge list - e->badges = ReadBadgeList(buf, GSF_SHIPS); - break; - - default: - ret = CommonVehicleChangeInfo(ei, prop, buf); - break; - } - } - - return ret; -} - -/** - * Define properties for aircraft - * @param first Local ID of the first vehicle. - * @param last Local ID of the last vehicle. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult AircraftVehicleChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - for (uint id = first; id < last; ++id) { - Engine *e = GetNewEngine(_cur.grffile, VEH_AIRCRAFT, id); - if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles - - EngineInfo *ei = &e->info; - AircraftVehicleInfo *avi = &e->u.air; - - switch (prop) { - case 0x08: { // Sprite ID - uint8_t spriteid = buf.ReadByte(); - uint8_t orig_spriteid = spriteid; - - /* aircraft have different custom id in the GRF file */ - if (spriteid == 0xFF) spriteid = 0xFD; - - if (spriteid < 0xFD) spriteid >>= 1; - - if (IsValidNewGRFImageIndex(spriteid)) { - avi->image_index = spriteid; - } else { - GrfMsg(1, "AircraftVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid); - avi->image_index = 0; - } - break; - } - - case 0x09: // Helicopter - if (buf.ReadByte() == 0) { - avi->subtype = AIR_HELI; - } else { - SB(avi->subtype, 0, 1, 1); // AIR_CTOL - } - break; - - case 0x0A: // Large - AssignBit(avi->subtype, 1, buf.ReadByte() != 0); // AIR_FAST - break; - - case PROP_AIRCRAFT_COST_FACTOR: // 0x0B Cost factor - avi->cost_factor = buf.ReadByte(); - break; - - case PROP_AIRCRAFT_SPEED: // 0x0C Speed (1 unit is 8 mph, we translate to 1 unit is 1 km-ish/h) - avi->max_speed = (buf.ReadByte() * 128) / 10; - break; - - case 0x0D: // Acceleration - avi->acceleration = buf.ReadByte(); - break; - - case PROP_AIRCRAFT_RUNNING_COST_FACTOR: // 0x0E Running cost factor - avi->running_cost = buf.ReadByte(); - break; - - case PROP_AIRCRAFT_PASSENGER_CAPACITY: // 0x0F Passenger capacity - avi->passenger_capacity = buf.ReadWord(); - break; - - case PROP_AIRCRAFT_MAIL_CAPACITY: // 0x11 Mail capacity - avi->mail_capacity = buf.ReadByte(); - break; - - case 0x12: // SFX - avi->sfx = GetNewGRFSoundID(_cur.grffile, buf.ReadByte()); - break; - - case 0x13: { // Cargoes available for refitting - uint32_t mask = buf.ReadDWord(); - _gted[e->index].UpdateRefittability(mask != 0); - ei->refit_mask = TranslateRefitMask(mask); - _gted[e->index].defaultcargo_grf = _cur.grffile; - break; - } - - case 0x14: { // Callback mask - auto mask = ei->callback_mask.base(); - SB(mask, 0, 8, buf.ReadByte()); - ei->callback_mask = VehicleCallbackMasks{mask}; - break; - } - - case 0x15: // Refit cost - ei->refit_cost = buf.ReadByte(); - break; - - case 0x16: // Retire vehicle early - ei->retire_early = buf.ReadByte(); - break; - - case 0x17: // Miscellaneous flags - ei->misc_flags = static_cast(buf.ReadByte()); - _loaded_newgrf_features.has_2CC |= ei->misc_flags.Test(EngineMiscFlag::Uses2CC); - break; - - case 0x18: // Cargo classes allowed - _gted[e->index].cargo_allowed = CargoClasses{buf.ReadWord()}; - _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed.Any()); - _gted[e->index].defaultcargo_grf = _cur.grffile; - break; - - case 0x19: // Cargo classes disallowed - _gted[e->index].cargo_disallowed = CargoClasses{buf.ReadWord()}; - _gted[e->index].UpdateRefittability(false); - break; - - case 0x1A: // Long format introduction date (days since year 0) - ei->base_intro = TimerGameCalendar::Date(buf.ReadDWord()); - break; - - case 0x1B: // Alter purchase list sort order - AlterVehicleListOrder(e->index, buf.ReadExtendedByte()); - break; - - case PROP_AIRCRAFT_CARGO_AGE_PERIOD: // 0x1C Cargo aging period - ei->cargo_age_period = buf.ReadWord(); - break; - - case 0x1D: // CTT refit include list - case 0x1E: { // CTT refit exclude list - uint8_t count = buf.ReadByte(); - _gted[e->index].UpdateRefittability(prop == 0x1D && count != 0); - if (prop == 0x1D) _gted[e->index].defaultcargo_grf = _cur.grffile; - CargoTypes &ctt = prop == 0x1D ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask; - ctt = 0; - while (count--) { - CargoType ctype = GetCargoTranslation(buf.ReadByte(), _cur.grffile); - if (IsValidCargoType(ctype)) SetBit(ctt, ctype); - } - break; - } - - case PROP_AIRCRAFT_RANGE: // 0x1F Max aircraft range - avi->max_range = buf.ReadWord(); - break; - - case 0x20: // Engine variant - ei->variant_id = static_cast(buf.ReadWord()); - break; - - case 0x21: // Extra miscellaneous flags - ei->extra_flags = static_cast(buf.ReadDWord()); - break; - - case 0x22: { // Callback additional mask - auto mask = ei->callback_mask.base(); - SB(mask, 8, 8, buf.ReadByte()); - ei->callback_mask = VehicleCallbackMasks{mask}; - break; - } - - case 0x23: // Cargo classes required for a refit. - _gted[e->index].cargo_allowed_required = CargoClasses{buf.ReadWord()}; - break; - - case 0x24: // Badge list - e->badges = ReadBadgeList(buf, GSF_AIRCRAFT); - break; - - default: - ret = CommonVehicleChangeInfo(ei, prop, buf); - break; - } - } - - return ret; -} - -/** - * Define properties for stations - * @param first Local ID of the first station. - * @param last Local ID of the last station. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult StationChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - if (last > NUM_STATIONS_PER_GRF) { - GrfMsg(1, "StationChangeInfo: Station {} is invalid, max {}, ignoring", last, NUM_STATIONS_PER_GRF); - return CIR_INVALID_ID; - } - - /* Allocate station specs if necessary */ - if (_cur.grffile->stations.size() < last) _cur.grffile->stations.resize(last); - - for (uint id = first; id < last; ++id) { - auto &statspec = _cur.grffile->stations[id]; - - /* Check that the station we are modifying is defined. */ - if (statspec == nullptr && prop != 0x08) { - GrfMsg(2, "StationChangeInfo: Attempt to modify undefined station {}, ignoring", id); - return CIR_INVALID_ID; - } - - switch (prop) { - case 0x08: { // Class ID - /* Property 0x08 is special; it is where the station is allocated */ - if (statspec == nullptr) { - statspec = std::make_unique(); - } - - /* Swap classid because we read it in BE meaning WAYP or DFLT */ - uint32_t classid = buf.ReadDWord(); - statspec->class_index = StationClass::Allocate(std::byteswap(classid)); - break; - } - - case 0x09: { // Define sprite layout - uint16_t tiles = buf.ReadExtendedByte(); - statspec->renderdata.clear(); // delete earlier loaded stuff - statspec->renderdata.reserve(tiles); - - for (uint t = 0; t < tiles; t++) { - NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back(); - dts->consistent_max_offset = UINT16_MAX; // Spritesets are unknown, so no limit. - - if (buf.HasData(4) && buf.PeekDWord() == 0) { - buf.Skip(4); - extern const DrawTileSpriteSpan _station_display_datas_rail[8]; - const DrawTileSpriteSpan &dtss = _station_display_datas_rail[t % 8]; - dts->ground = dtss.ground; - dts->seq.insert(dts->seq.end(), dtss.GetSequence().begin(), dtss.GetSequence().end()); - continue; - } - - ReadSpriteLayoutSprite(buf, false, false, false, GSF_STATIONS, &dts->ground); - /* On error, bail out immediately. Temporary GRF data was already freed */ - if (_cur.skip_sprites < 0) return CIR_DISABLED; - - std::vector tmp_layout; - for (;;) { - uint8_t delta_x = buf.ReadByte(); - if (delta_x == 0x80) break; - - /* no relative bounding box support */ - DrawTileSeqStruct &dtss = tmp_layout.emplace_back(); - dtss.delta_x = delta_x; - dtss.delta_y = buf.ReadByte(); - dtss.delta_z = buf.ReadByte(); - dtss.size_x = buf.ReadByte(); - dtss.size_y = buf.ReadByte(); - dtss.size_z = buf.ReadByte(); - - ReadSpriteLayoutSprite(buf, false, true, false, GSF_STATIONS, &dtss.image); - /* On error, bail out immediately. Temporary GRF data was already freed */ - if (_cur.skip_sprites < 0) return CIR_DISABLED; - } - dts->seq = std::move(tmp_layout); - } - - /* Number of layouts must be even, alternating X and Y */ - if (statspec->renderdata.size() & 1) { - GrfMsg(1, "StationChangeInfo: Station {} defines an odd number of sprite layouts, dropping the last item", id); - statspec->renderdata.pop_back(); - } - break; - } - - case 0x0A: { // Copy sprite layout - uint16_t srcid = buf.ReadExtendedByte(); - const StationSpec *srcstatspec = srcid >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[srcid].get(); - - if (srcstatspec == nullptr) { - GrfMsg(1, "StationChangeInfo: Station {} is not defined, cannot copy sprite layout to {}.", srcid, id); - continue; - } - - statspec->renderdata.clear(); // delete earlier loaded stuff - statspec->renderdata.reserve(srcstatspec->renderdata.size()); - - for (const auto &it : srcstatspec->renderdata) { - statspec->renderdata.emplace_back(it); - } - break; - } - - case 0x0B: // Callback mask - statspec->callback_mask = static_cast(buf.ReadByte()); - break; - - case 0x0C: // Disallowed number of platforms - statspec->disallowed_platforms = buf.ReadByte(); - break; - - case 0x0D: // Disallowed platform lengths - statspec->disallowed_lengths = buf.ReadByte(); - break; - - case 0x0E: // Define custom layout - while (buf.HasData()) { - uint8_t length = buf.ReadByte(); - uint8_t number = buf.ReadByte(); - - if (length == 0 || number == 0) break; - - const uint8_t *buf_layout = buf.ReadBytes(length * number); - - /* Create entry in layouts and assign the layout to it. */ - auto &layout = statspec->layouts[GetStationLayoutKey(number, length)]; - layout.assign(buf_layout, buf_layout + length * number); - - /* Ensure the first bit, axis, is zero. The rest of the value is validated during rendering, as we don't know the range yet. */ - for (auto &tile : layout) { - if ((tile & ~1U) != tile) { - GrfMsg(1, "StationChangeInfo: Invalid tile {} in layout {}x{}", tile, length, number); - tile &= ~1U; - } - } - } - break; - - case 0x0F: { // Copy custom layout - uint16_t srcid = buf.ReadExtendedByte(); - const StationSpec *srcstatspec = srcid >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[srcid].get(); - - if (srcstatspec == nullptr) { - GrfMsg(1, "StationChangeInfo: Station {} is not defined, cannot copy tile layout to {}.", srcid, id); - continue; - } - - statspec->layouts = srcstatspec->layouts; - break; - } - - case 0x10: // Little/lots cargo threshold - statspec->cargo_threshold = buf.ReadWord(); - break; - - case 0x11: { // Pylon placement - uint8_t pylons = buf.ReadByte(); - if (statspec->tileflags.size() < 8) statspec->tileflags.resize(8); - for (int j = 0; j < 8; ++j) { - if (HasBit(pylons, j)) { - statspec->tileflags[j].Set(StationSpec::TileFlag::Pylons); - } else { - statspec->tileflags[j].Reset(StationSpec::TileFlag::Pylons); - } - } - break; - } - - case 0x12: // Cargo types for random triggers - if (_cur.grffile->grf_version >= 7) { - statspec->cargo_triggers = TranslateRefitMask(buf.ReadDWord()); - } else { - statspec->cargo_triggers = (CargoTypes)buf.ReadDWord(); - } - break; - - case 0x13: // General flags - statspec->flags = StationSpecFlags{buf.ReadByte()}; - break; - - case 0x14: { // Overhead wire placement - uint8_t wires = buf.ReadByte(); - if (statspec->tileflags.size() < 8) statspec->tileflags.resize(8); - for (int j = 0; j < 8; ++j) { - if (HasBit(wires, j)) { - statspec->tileflags[j].Set(StationSpec::TileFlag::NoWires); - } else { - statspec->tileflags[j].Reset(StationSpec::TileFlag::NoWires); - } - } - break; - } - - case 0x15: { // Blocked tiles - uint8_t blocked = buf.ReadByte(); - if (statspec->tileflags.size() < 8) statspec->tileflags.resize(8); - for (int j = 0; j < 8; ++j) { - if (HasBit(blocked, j)) { - statspec->tileflags[j].Set(StationSpec::TileFlag::Blocked); - } else { - statspec->tileflags[j].Reset(StationSpec::TileFlag::Blocked); - } - } - break; - } - - case 0x16: // Animation info - statspec->animation.frames = buf.ReadByte(); - statspec->animation.status = buf.ReadByte(); - break; - - case 0x17: // Animation speed - statspec->animation.speed = buf.ReadByte(); - break; - - case 0x18: // Animation triggers - statspec->animation.triggers = buf.ReadWord(); - break; - - /* 0x19 road routing (not implemented) */ - - case 0x1A: { // Advanced sprite layout - uint16_t tiles = buf.ReadExtendedByte(); - statspec->renderdata.clear(); // delete earlier loaded stuff - statspec->renderdata.reserve(tiles); - - for (uint t = 0; t < tiles; t++) { - NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back(); - uint num_building_sprites = buf.ReadByte(); - /* On error, bail out immediately. Temporary GRF data was already freed */ - if (ReadSpriteLayout(buf, num_building_sprites, false, GSF_STATIONS, true, false, dts)) return CIR_DISABLED; - } - - /* Number of layouts must be even, alternating X and Y */ - if (statspec->renderdata.size() & 1) { - GrfMsg(1, "StationChangeInfo: Station {} defines an odd number of sprite layouts, dropping the last item", id); - statspec->renderdata.pop_back(); - } - break; - } - - case 0x1B: // Minimum bridge height (not implemented) - buf.ReadWord(); - buf.ReadWord(); - buf.ReadWord(); - buf.ReadWord(); - break; - - case 0x1C: // Station Name - AddStringForMapping(GRFStringID{buf.ReadWord()}, &statspec->name); - break; - - case 0x1D: // Station Class name - AddStringForMapping(GRFStringID{buf.ReadWord()}, [statspec = statspec.get()](StringID str) { StationClass::Get(statspec->class_index)->name = str; }); - break; - - case 0x1E: { // Extended tile flags (replaces prop 11, 14 and 15) - uint16_t tiles = buf.ReadExtendedByte(); - auto flags = reinterpret_cast(buf.ReadBytes(tiles)); - statspec->tileflags.assign(flags, flags + tiles); - break; - } - - case 0x1F: // Badge list - statspec->badges = ReadBadgeList(buf, GSF_STATIONS); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -/** - * Define properties for water features - * @param first Local ID of the first water feature. - * @param last Local ID of the last water feature. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult CanalChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - if (last > CF_END) { - GrfMsg(1, "CanalChangeInfo: Canal feature 0x{:02X} is invalid, max {}, ignoring", last, CF_END); - return CIR_INVALID_ID; - } - - for (uint id = first; id < last; ++id) { - CanalProperties *cp = &_cur.grffile->canal_local_properties[id]; - - switch (prop) { - case 0x08: - cp->callback_mask = static_cast(buf.ReadByte()); - break; - - case 0x09: - cp->flags = buf.ReadByte(); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -/** - * Define properties for bridges - * @param first Local ID of the first bridge. - * @param last Local ID of the last bridge. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult BridgeChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - if (last > MAX_BRIDGES) { - GrfMsg(1, "BridgeChangeInfo: Bridge {} is invalid, max {}, ignoring", last, MAX_BRIDGES); - return CIR_INVALID_ID; - } - - for (uint id = first; id < last; ++id) { - BridgeSpec *bridge = &_bridge[id]; - - switch (prop) { - case 0x08: { // Year of availability - /* We treat '0' as always available */ - uint8_t year = buf.ReadByte(); - bridge->avail_year = (year > 0 ? CalendarTime::ORIGINAL_BASE_YEAR + year : TimerGameCalendar::Year{}); - break; - } - - case 0x09: // Minimum length - bridge->min_length = buf.ReadByte(); - break; - - case 0x0A: // Maximum length - bridge->max_length = buf.ReadByte(); - if (bridge->max_length > 16) bridge->max_length = UINT16_MAX; - break; - - case 0x0B: // Cost factor - bridge->price = buf.ReadByte(); - break; - - case 0x0C: // Maximum speed - bridge->speed = buf.ReadWord(); - if (bridge->speed == 0) bridge->speed = UINT16_MAX; - break; - - case 0x0D: { // Bridge sprite tables - uint8_t tableid = buf.ReadByte(); - uint8_t numtables = buf.ReadByte(); - size_t size = tableid + numtables; - - if (bridge->sprite_table.size() < size) { - /* Allocate memory for sprite table pointers and zero out */ - bridge->sprite_table.resize(std::min(size, NUM_BRIDGE_PIECES)); - } - - for (; numtables-- != 0; tableid++) { - if (tableid >= NUM_BRIDGE_PIECES) { // skip invalid data - GrfMsg(1, "BridgeChangeInfo: Table {} >= {}, skipping", tableid, NUM_BRIDGE_PIECES); - for (uint8_t sprite = 0; sprite < SPRITES_PER_BRIDGE_PIECE; sprite++) buf.ReadDWord(); - continue; - } - - if (bridge->sprite_table[tableid].empty()) { - bridge->sprite_table[tableid].resize(SPRITES_PER_BRIDGE_PIECE); - } - - for (uint8_t sprite = 0; sprite < SPRITES_PER_BRIDGE_PIECE; sprite++) { - SpriteID image = buf.ReadWord(); - PaletteID pal = buf.ReadWord(); - - bridge->sprite_table[tableid][sprite].sprite = image; - bridge->sprite_table[tableid][sprite].pal = pal; - - MapSpriteMappingRecolour(&bridge->sprite_table[tableid][sprite]); - } - } - break; - } - - case 0x0E: // Flags; bit 0 - disable far pillars - bridge->flags = buf.ReadByte(); - break; - - case 0x0F: // Long format year of availability (year since year 0) - bridge->avail_year = Clamp(TimerGameCalendar::Year(buf.ReadDWord()), CalendarTime::MIN_YEAR, CalendarTime::MAX_YEAR); - break; - - case 0x10: // purchase string - AddStringForMapping(GRFStringID{buf.ReadWord()}, &bridge->material); - break; - - case 0x11: // description of bridge with rails - AddStringForMapping(GRFStringID{buf.ReadWord()}, &bridge->transport_name[0]); - break; - - case 0x12: // description of bridge with roads - AddStringForMapping(GRFStringID{buf.ReadWord()}, &bridge->transport_name[1]); - break; - - case 0x13: // 16 bits cost multiplier - bridge->price = buf.ReadWord(); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -/** - * Ignore a house property - * @param prop Property to read. - * @param buf Property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult IgnoreTownHouseProperty(int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - switch (prop) { - case 0x09: - case 0x0B: - case 0x0C: - case 0x0D: - case 0x0E: - case 0x0F: - case 0x11: - case 0x14: - case 0x15: - case 0x16: - case 0x18: - case 0x19: - case 0x1A: - case 0x1B: - case 0x1C: - case 0x1D: - case 0x1F: - buf.ReadByte(); - break; - - case 0x0A: - case 0x10: - case 0x12: - case 0x13: - case 0x21: - case 0x22: - buf.ReadWord(); - break; - - case 0x1E: - buf.ReadDWord(); - break; - - case 0x17: - for (uint j = 0; j < 4; j++) buf.ReadByte(); - break; - - case 0x20: { - uint8_t count = buf.ReadByte(); - for (uint8_t j = 0; j < count; j++) buf.ReadByte(); - break; - } - - case 0x23: - buf.Skip(buf.ReadByte() * 2); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - return ret; -} - -/** - * Define properties for houses - * @param first Local ID of the first house. - * @param last Local ID of the last house. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult TownHouseChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - if (last > NUM_HOUSES_PER_GRF) { - GrfMsg(1, "TownHouseChangeInfo: Too many houses loaded ({}), max ({}). Ignoring.", last, NUM_HOUSES_PER_GRF); - return CIR_INVALID_ID; - } - - /* Allocate house specs if they haven't been allocated already. */ - if (_cur.grffile->housespec.size() < last) _cur.grffile->housespec.resize(last); - - for (uint id = first; id < last; ++id) { - auto &housespec = _cur.grffile->housespec[id]; - - if (prop != 0x08 && housespec == nullptr) { - /* If the house property 08 is not yet set, ignore this property */ - ChangeInfoResult cir = IgnoreTownHouseProperty(prop, buf); - if (cir > ret) ret = cir; - continue; - } - - switch (prop) { - case 0x08: { // Substitute building type, and definition of a new house - uint8_t subs_id = buf.ReadByte(); - if (subs_id == 0xFF) { - /* Instead of defining a new house, a substitute house id - * of 0xFF disables the old house with the current id. */ - if (id < NEW_HOUSE_OFFSET) HouseSpec::Get(id)->enabled = false; - continue; - } else if (subs_id >= NEW_HOUSE_OFFSET) { - /* The substitute id must be one of the original houses. */ - GrfMsg(2, "TownHouseChangeInfo: Attempt to use new house {} as substitute house for {}. Ignoring.", subs_id, id); - continue; - } - - /* Allocate space for this house. */ - if (housespec == nullptr) { - /* Only the first property 08 setting copies properties; if you later change it, properties will stay. */ - housespec = std::make_unique(*HouseSpec::Get(subs_id)); - - housespec->enabled = true; - housespec->grf_prop.local_id = id; - housespec->grf_prop.subst_id = subs_id; - housespec->grf_prop.SetGRFFile(_cur.grffile); - /* Set default colours for randomization, used if not overridden. */ - housespec->random_colour[0] = COLOUR_RED; - housespec->random_colour[1] = COLOUR_BLUE; - housespec->random_colour[2] = COLOUR_ORANGE; - housespec->random_colour[3] = COLOUR_GREEN; - - /* House flags 40 and 80 are exceptions; these flags are never set automatically. */ - housespec->building_flags.Reset(BuildingFlag::IsChurch).Reset(BuildingFlag::IsStadium); - - /* Make sure that the third cargo type is valid in this - * climate. This can cause problems when copying the properties - * of a house that accepts food, where the new house is valid - * in the temperate climate. */ - CargoType cargo_type = housespec->accepts_cargo[2]; - if (!IsValidCargoType(cargo_type)) cargo_type = GetCargoTypeByLabel(housespec->accepts_cargo_label[2]); - if (!IsValidCargoType(cargo_type)) { - housespec->cargo_acceptance[2] = 0; - } - } - break; - } - - case 0x09: // Building flags - housespec->building_flags = (BuildingFlags)buf.ReadByte(); - break; - - case 0x0A: { // Availability years - uint16_t years = buf.ReadWord(); - housespec->min_year = GB(years, 0, 8) > 150 ? CalendarTime::MAX_YEAR : CalendarTime::ORIGINAL_BASE_YEAR + GB(years, 0, 8); - housespec->max_year = GB(years, 8, 8) > 150 ? CalendarTime::MAX_YEAR : CalendarTime::ORIGINAL_BASE_YEAR + GB(years, 8, 8); - break; - } - - case 0x0B: // Population - housespec->population = buf.ReadByte(); - break; - - case 0x0C: // Mail generation multiplier - housespec->mail_generation = buf.ReadByte(); - break; - - case 0x0D: // Passenger acceptance - case 0x0E: // Mail acceptance - housespec->cargo_acceptance[prop - 0x0D] = buf.ReadByte(); - break; - - case 0x0F: { // Goods/candy, food/fizzy drinks acceptance - int8_t goods = buf.ReadByte(); - - /* If value of goods is negative, it means in fact food or, if in toyland, fizzy_drink acceptance. - * Else, we have "standard" 3rd cargo type, goods or candy, for toyland once more */ - CargoType cargo_type = (goods >= 0) ? ((_settings_game.game_creation.landscape == LandscapeType::Toyland) ? GetCargoTypeByLabel(CT_CANDY) : GetCargoTypeByLabel(CT_GOODS)) : - ((_settings_game.game_creation.landscape == LandscapeType::Toyland) ? GetCargoTypeByLabel(CT_FIZZY_DRINKS) : GetCargoTypeByLabel(CT_FOOD)); - - /* Make sure the cargo type is valid in this climate. */ - if (!IsValidCargoType(cargo_type)) goods = 0; - - housespec->accepts_cargo[2] = cargo_type; - housespec->accepts_cargo_label[2] = CT_INVALID; - housespec->cargo_acceptance[2] = abs(goods); // but we do need positive value here - break; - } - - case 0x10: // Local authority rating decrease on removal - housespec->remove_rating_decrease = buf.ReadWord(); - break; - - case 0x11: // Removal cost multiplier - housespec->removal_cost = buf.ReadByte(); - break; - - case 0x12: // Building name ID - AddStringForMapping(GRFStringID{buf.ReadWord()}, &housespec->building_name); - break; - - case 0x13: // Building availability mask - housespec->building_availability = (HouseZones)buf.ReadWord(); - break; - - case 0x14: { // House callback mask - auto mask = housespec->callback_mask.base(); - SB(mask, 0, 8, buf.ReadByte()); - housespec->callback_mask = HouseCallbackMasks{mask}; - break; - } - - case 0x15: { // House override byte - uint8_t override = buf.ReadByte(); - - /* The house being overridden must be an original house. */ - if (override >= NEW_HOUSE_OFFSET) { - GrfMsg(2, "TownHouseChangeInfo: Attempt to override new house {} with house id {}. Ignoring.", override, id); - continue; - } - - _house_mngr.Add(id, _cur.grffile->grfid, override); - break; - } - - case 0x16: // Periodic refresh multiplier - housespec->processing_time = std::min(buf.ReadByte(), 63u); - break; - - case 0x17: // Four random colours to use - for (uint j = 0; j < 4; j++) housespec->random_colour[j] = static_cast(GB(buf.ReadByte(), 0, 4)); - break; - - case 0x18: // Relative probability of appearing - housespec->probability = buf.ReadByte(); - break; - - case 0x19: // Extra flags - housespec->extra_flags = static_cast(buf.ReadByte()); - break; - - case 0x1A: // Animation frames - housespec->animation.frames = buf.ReadByte(); - housespec->animation.status = GB(housespec->animation.frames, 7, 1); - SB(housespec->animation.frames, 7, 1, 0); - break; - - case 0x1B: // Animation speed - housespec->animation.speed = Clamp(buf.ReadByte(), 2, 16); - break; - - case 0x1C: // Class of the building type - housespec->class_id = AllocateHouseClassID(buf.ReadByte(), _cur.grffile->grfid); - break; - - case 0x1D: { // Callback mask part 2 - auto mask = housespec->callback_mask.base(); - SB(mask, 8, 8, buf.ReadByte()); - housespec->callback_mask = HouseCallbackMasks{mask}; - break; - } - - case 0x1E: { // Accepted cargo types - uint32_t cargotypes = buf.ReadDWord(); - - /* Check if the cargo types should not be changed */ - if (cargotypes == 0xFFFFFFFF) break; - - for (uint j = 0; j < HOUSE_ORIGINAL_NUM_ACCEPTS; j++) { - /* Get the cargo number from the 'list' */ - uint8_t cargo_part = GB(cargotypes, 8 * j, 8); - CargoType cargo = GetCargoTranslation(cargo_part, _cur.grffile); - - if (!IsValidCargoType(cargo)) { - /* Disable acceptance of invalid cargo type */ - housespec->cargo_acceptance[j] = 0; - } else { - housespec->accepts_cargo[j] = cargo; - } - housespec->accepts_cargo_label[j] = CT_INVALID; - } - break; - } - - case 0x1F: // Minimum life span - housespec->minimum_life = buf.ReadByte(); - break; - - case 0x20: { // Cargo acceptance watch list - uint8_t count = buf.ReadByte(); - for (uint8_t j = 0; j < count; j++) { - CargoType cargo = GetCargoTranslation(buf.ReadByte(), _cur.grffile); - if (IsValidCargoType(cargo)) SetBit(housespec->watched_cargoes, cargo); - } - break; - } - - case 0x21: // long introduction year - housespec->min_year = TimerGameCalendar::Year{buf.ReadWord()}; - break; - - case 0x22: // long maximum year - housespec->max_year = TimerGameCalendar::Year{buf.ReadWord()}; - if (housespec->max_year == UINT16_MAX) housespec->max_year = CalendarTime::MAX_YEAR; - break; - - case 0x23: { // variable length cargo types accepted - uint count = buf.ReadByte(); - if (count > lengthof(housespec->accepts_cargo)) { - GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG); - error->param_value[1] = prop; - return CIR_DISABLED; - } - /* Always write the full accepts_cargo array, and check each index for being inside the - * provided data. This ensures all values are properly initialized, and also avoids - * any risks of array overrun. */ - for (uint i = 0; i < lengthof(housespec->accepts_cargo); i++) { - if (i < count) { - housespec->accepts_cargo[i] = GetCargoTranslation(buf.ReadByte(), _cur.grffile); - housespec->cargo_acceptance[i] = buf.ReadByte(); - } else { - housespec->accepts_cargo[i] = INVALID_CARGO; - housespec->cargo_acceptance[i] = 0; - } - if (i < std::size(housespec->accepts_cargo_label)) housespec->accepts_cargo_label[i] = CT_INVALID; - } - break; - } - - case 0x24: // Badge list - housespec->badges = ReadBadgeList(buf, GSF_HOUSES); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - /** * Get the language map associated with a given NewGRF and language. * @param grfid The NewGRF to get the map for. @@ -2454,6102 +358,11 @@ static ChangeInfoResult TownHouseChangeInfo(uint first, uint last, int prop, Byt return &it->second; } -/** - * Load a cargo- or railtype-translation table. - * @param first ID of the first translation table entry. - * @param last ID of the last translation table entry. - * @param buf The property value. - * @param gettable Function to get storage for the translation table. - * @param name Name of the table for debug output. - * @return ChangeInfoResult. - */ -template -static ChangeInfoResult LoadTranslationTable(uint first, uint last, ByteReader &buf, TGetTableFunc gettable, std::string_view name) -{ - if (first != 0) { - GrfMsg(1, "LoadTranslationTable: {} translation table must start at zero", name); - return CIR_INVALID_ID; - } - - std::vector &translation_table = gettable(*_cur.grffile); - translation_table.clear(); - translation_table.reserve(last); - for (uint id = first; id < last; ++id) { - translation_table.push_back(T(std::byteswap(buf.ReadDWord()))); - } - - GRFFile *grf_override = GetCurrentGRFOverride(); - if (grf_override != nullptr) { - /* GRF override is present, copy the translation table to the overridden GRF as well. */ - GrfMsg(1, "LoadTranslationTable: Copying {} translation table to override GRFID '{}'", name, std::byteswap(grf_override->grfid)); - std::vector &override_table = gettable(*grf_override); - override_table = translation_table; - } - - return CIR_SUCCESS; -} - -static ChangeInfoResult LoadBadgeTranslationTable(uint first, uint last, ByteReader &buf, std::vector &translation_table, const char *name) -{ - if (first != 0 && first != std::size(translation_table)) { - GrfMsg(1, "LoadBadgeTranslationTable: {} translation table must start at zero or {}", name, std::size(translation_table)); - return CIR_INVALID_ID; - } - - if (first == 0) translation_table.clear(); - translation_table.reserve(last); - for (uint id = first; id < last; ++id) { - std::string_view label = buf.ReadString(); - translation_table.push_back(GetOrCreateBadge(label).index); - } - - return CIR_SUCCESS; -} - -/** - * Helper to read a DWord worth of bytes from the reader - * and to return it as a valid string. - * @param reader The source of the DWord. - * @return The read DWord as string. - */ -static std::string ReadDWordAsString(ByteReader &reader) -{ - std::string output; - for (int i = 0; i < 4; i++) output.push_back(reader.ReadByte()); - return StrMakeValid(output); -} - -/** - * Define properties for global variables - * @param first ID of the first global var. - * @param last ID of the last global var. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult GlobalVarChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - /* Properties which are handled as a whole */ - switch (prop) { - case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos) - return LoadTranslationTable(first, last, buf, [](GRFFile &grf) -> std::vector & { return grf.cargo_list; }, "Cargo"); - - case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes) - return LoadTranslationTable(first, last, buf, [](GRFFile &grf) -> std::vector & { return grf.railtype_list; }, "Rail type"); - - case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined roadtypes) - return LoadTranslationTable(first, last, buf, [](GRFFile &grf) -> std::vector & { return grf.roadtype_list; }, "Road type"); - - case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined tramtypes) - return LoadTranslationTable(first, last, buf, [](GRFFile &grf) -> std::vector & { return grf.tramtype_list; }, "Tram type"); - - case 0x18: // Badge translation table - return LoadBadgeTranslationTable(first, last, buf, _cur.grffile->badge_list, "Badge"); - - default: - break; - } - - /* Properties which are handled per item */ - ChangeInfoResult ret = CIR_SUCCESS; - for (uint id = first; id < last; ++id) { - switch (prop) { - case 0x08: { // Cost base factor - int factor = buf.ReadByte(); - - if (id < PR_END) { - _cur.grffile->price_base_multipliers[id] = std::min(factor - 8, MAX_PRICE_MODIFIER); - } else { - GrfMsg(1, "GlobalVarChangeInfo: Price {} out of range, ignoring", id); - } - break; - } - - case 0x0A: { // Currency display names - uint curidx = GetNewgrfCurrencyIdConverted(id); - if (curidx < CURRENCY_END) { - AddStringForMapping(GRFStringID{buf.ReadWord()}, [curidx](StringID str) { - _currency_specs[curidx].name = str; - _currency_specs[curidx].code.clear(); - }); - } else { - buf.ReadWord(); - } - break; - } - - case 0x0B: { // Currency multipliers - uint curidx = GetNewgrfCurrencyIdConverted(id); - uint32_t rate = buf.ReadDWord(); - - if (curidx < CURRENCY_END) { - /* TTDPatch uses a multiple of 1000 for its conversion calculations, - * which OTTD does not. For this reason, divide grf value by 1000, - * to be compatible */ - _currency_specs[curidx].rate = rate / 1000; - } else { - GrfMsg(1, "GlobalVarChangeInfo: Currency multipliers {} out of range, ignoring", curidx); - } - break; - } - - case 0x0C: { // Currency options - uint curidx = GetNewgrfCurrencyIdConverted(id); - uint16_t options = buf.ReadWord(); - - if (curidx < CURRENCY_END) { - _currency_specs[curidx].separator.clear(); - _currency_specs[curidx].separator.push_back(GB(options, 0, 8)); - /* By specifying only one bit, we prevent errors, - * since newgrf specs said that only 0 and 1 can be set for symbol_pos */ - _currency_specs[curidx].symbol_pos = GB(options, 8, 1); - } else { - GrfMsg(1, "GlobalVarChangeInfo: Currency option {} out of range, ignoring", curidx); - } - break; - } - - case 0x0D: { // Currency prefix symbol - uint curidx = GetNewgrfCurrencyIdConverted(id); - std::string prefix = ReadDWordAsString(buf); - - if (curidx < CURRENCY_END) { - _currency_specs[curidx].prefix = std::move(prefix); - } else { - GrfMsg(1, "GlobalVarChangeInfo: Currency symbol {} out of range, ignoring", curidx); - } - break; - } - - case 0x0E: { // Currency suffix symbol - uint curidx = GetNewgrfCurrencyIdConverted(id); - std::string suffix = ReadDWordAsString(buf); - - if (curidx < CURRENCY_END) { - _currency_specs[curidx].suffix = std::move(suffix); - } else { - GrfMsg(1, "GlobalVarChangeInfo: Currency symbol {} out of range, ignoring", curidx); - } - break; - } - - case 0x0F: { // Euro introduction dates - uint curidx = GetNewgrfCurrencyIdConverted(id); - TimerGameCalendar::Year year_euro{buf.ReadWord()}; - - if (curidx < CURRENCY_END) { - _currency_specs[curidx].to_euro = year_euro; - } else { - GrfMsg(1, "GlobalVarChangeInfo: Euro intro date {} out of range, ignoring", curidx); - } - break; - } - - case 0x10: // Snow line height table - if (last > 1 || IsSnowLineSet()) { - GrfMsg(1, "GlobalVarChangeInfo: The snowline can only be set once ({})", last); - } else if (buf.Remaining() < SNOW_LINE_MONTHS * SNOW_LINE_DAYS) { - GrfMsg(1, "GlobalVarChangeInfo: Not enough entries set in the snowline table ({})", buf.Remaining()); - } else { - auto snow_line = std::make_unique(); - - for (uint i = 0; i < SNOW_LINE_MONTHS; i++) { - for (uint j = 0; j < SNOW_LINE_DAYS; j++) { - uint8_t &level = snow_line->table[i][j]; - level = buf.ReadByte(); - if (_cur.grffile->grf_version >= 8) { - if (level != 0xFF) level = level * (1 + _settings_game.construction.map_height_limit) / 256; - } else { - if (level >= 128) { - /* no snow */ - level = 0xFF; - } else { - level = level * (1 + _settings_game.construction.map_height_limit) / 128; - } - } - - snow_line->highest_value = std::max(snow_line->highest_value, level); - snow_line->lowest_value = std::min(snow_line->lowest_value, level); - } - } - SetSnowLine(std::move(snow_line)); - } - break; - - case 0x11: // GRF match for engine allocation - /* This is loaded during the reservation stage, so just skip it here. */ - /* Each entry is 8 bytes. */ - buf.Skip(8); - break; - - case 0x13: // Gender translation table - case 0x14: // Case translation table - case 0x15: { // Plural form translation - uint curidx = id; // The current index, i.e. language. - const LanguageMetadata *lang = curidx < MAX_LANG ? GetLanguage(curidx) : nullptr; - if (lang == nullptr) { - GrfMsg(1, "GlobalVarChangeInfo: Language {} is not known, ignoring", curidx); - /* Skip over the data. */ - if (prop == 0x15) { - buf.ReadByte(); - } else { - while (buf.ReadByte() != 0) { - buf.ReadString(); - } - } - break; - } - - if (prop == 0x15) { - uint plural_form = buf.ReadByte(); - if (plural_form >= LANGUAGE_MAX_PLURAL) { - GrfMsg(1, "GlobalVarChanceInfo: Plural form {} is out of range, ignoring", plural_form); - } else { - _cur.grffile->language_map[curidx].plural_form = plural_form; - } - break; - } - - uint8_t newgrf_id = buf.ReadByte(); // The NewGRF (custom) identifier. - while (newgrf_id != 0) { - std::string_view name = buf.ReadString(); // The name for the OpenTTD identifier. - - /* We'll just ignore the UTF8 identifier character. This is (fairly) - * safe as OpenTTD's strings gender/cases are usually in ASCII which - * is just a subset of UTF8, or they need the bigger UTF8 characters - * such as Cyrillic. Thus we will simply assume they're all UTF8. */ - char32_t c; - size_t len = Utf8Decode(&c, name.data()); - if (c == NFO_UTF8_IDENTIFIER) name = name.substr(len); - - LanguageMap::Mapping map; - map.newgrf_id = newgrf_id; - if (prop == 0x13) { - map.openttd_id = lang->GetGenderIndex(name.data()); - if (map.openttd_id >= MAX_NUM_GENDERS) { - GrfMsg(1, "GlobalVarChangeInfo: Gender name {} is not known, ignoring", StrMakeValid(name)); - } else { - _cur.grffile->language_map[curidx].gender_map.push_back(map); - } - } else { - map.openttd_id = lang->GetCaseIndex(name.data()); - if (map.openttd_id >= MAX_NUM_CASES) { - GrfMsg(1, "GlobalVarChangeInfo: Case name {} is not known, ignoring", StrMakeValid(name)); - } else { - _cur.grffile->language_map[curidx].case_map.push_back(map); - } - } - newgrf_id = buf.ReadByte(); - } - break; - } - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -static ChangeInfoResult GlobalVarReserveInfo(uint first, uint last, int prop, ByteReader &buf) -{ - /* Properties which are handled as a whole */ - switch (prop) { - case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos) - return LoadTranslationTable(first, last, buf, [](GRFFile &grf) -> std::vector & { return grf.cargo_list; }, "Cargo"); - - case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes) - return LoadTranslationTable(first, last, buf, [](GRFFile &grf) -> std::vector & { return grf.railtype_list; }, "Rail type"); - - case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined roadtypes) - return LoadTranslationTable(first, last, buf, [](GRFFile &grf) -> std::vector & { return grf.roadtype_list; }, "Road type"); - - case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined tramtypes) - return LoadTranslationTable(first, last, buf, [](GRFFile &grf) -> std::vector & { return grf.tramtype_list; }, "Tram type"); - - case 0x18: // Badge translation table - return LoadBadgeTranslationTable(first, last, buf, _cur.grffile->badge_list, "Badge"); - - default: - break; - } - - /* Properties which are handled per item */ - ChangeInfoResult ret = CIR_SUCCESS; - - for (uint id = first; id < last; ++id) { - switch (prop) { - case 0x08: // Cost base factor - case 0x15: // Plural form translation - buf.ReadByte(); - break; - - case 0x0A: // Currency display names - case 0x0C: // Currency options - case 0x0F: // Euro introduction dates - buf.ReadWord(); - break; - - case 0x0B: // Currency multipliers - case 0x0D: // Currency prefix symbol - case 0x0E: // Currency suffix symbol - buf.ReadDWord(); - break; - - case 0x10: // Snow line height table - buf.Skip(SNOW_LINE_MONTHS * SNOW_LINE_DAYS); - break; - - case 0x11: { // GRF match for engine allocation - uint32_t s = buf.ReadDWord(); - uint32_t t = buf.ReadDWord(); - SetNewGRFOverride(s, t); - break; - } - - case 0x13: // Gender translation table - case 0x14: // Case translation table - while (buf.ReadByte() != 0) { - buf.ReadString(); - } - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - - -/** - * Define properties for cargoes - * @param first ID of the first cargo. - * @param last ID of the last cargo. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult CargoChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - if (last > NUM_CARGO) { - GrfMsg(2, "CargoChangeInfo: Cargo type {} out of range (max {})", last, NUM_CARGO - 1); - return CIR_INVALID_ID; - } - - for (uint id = first; id < last; ++id) { - CargoSpec *cs = CargoSpec::Get(id); - - switch (prop) { - case 0x08: // Bit number of cargo - cs->bitnum = buf.ReadByte(); - if (cs->IsValid()) { - cs->grffile = _cur.grffile; - SetBit(_cargo_mask, id); - } else { - ClrBit(_cargo_mask, id); - } - BuildCargoLabelMap(); - break; - - case 0x09: // String ID for cargo type name - AddStringForMapping(GRFStringID{buf.ReadWord()}, &cs->name); - break; - - case 0x0A: // String for 1 unit of cargo - AddStringForMapping(GRFStringID{buf.ReadWord()}, &cs->name_single); - break; - - case 0x0B: // String for singular quantity of cargo (e.g. 1 tonne of coal) - case 0x1B: // String for cargo units - /* String for units of cargo. This is different in OpenTTD - * (e.g. tonnes) to TTDPatch (e.g. {COMMA} tonne of coal). - * Property 1B is used to set OpenTTD's behaviour. */ - AddStringForMapping(GRFStringID{buf.ReadWord()}, &cs->units_volume); - break; - - case 0x0C: // String for plural quantity of cargo (e.g. 10 tonnes of coal) - case 0x1C: // String for any amount of cargo - /* Strings for an amount of cargo. This is different in OpenTTD - * (e.g. {WEIGHT} of coal) to TTDPatch (e.g. {COMMA} tonnes of coal). - * Property 1C is used to set OpenTTD's behaviour. */ - AddStringForMapping(GRFStringID{buf.ReadWord()}, &cs->quantifier); - break; - - case 0x0D: // String for two letter cargo abbreviation - AddStringForMapping(GRFStringID{buf.ReadWord()}, &cs->abbrev); - break; - - case 0x0E: // Sprite ID for cargo icon - cs->sprite = buf.ReadWord(); - break; - - case 0x0F: // Weight of one unit of cargo - cs->weight = buf.ReadByte(); - break; - - case 0x10: // Used for payment calculation - cs->transit_periods[0] = buf.ReadByte(); - break; - - case 0x11: // Used for payment calculation - cs->transit_periods[1] = buf.ReadByte(); - break; - - case 0x12: // Base cargo price - cs->initial_payment = buf.ReadDWord(); - break; - - case 0x13: // Colour for station rating bars - cs->rating_colour = buf.ReadByte(); - break; - - case 0x14: // Colour for cargo graph - cs->legend_colour = buf.ReadByte(); - break; - - case 0x15: // Freight status - cs->is_freight = (buf.ReadByte() != 0); - break; - - case 0x16: // Cargo classes - cs->classes = CargoClasses{buf.ReadWord()}; - break; - - case 0x17: // Cargo label - cs->label = CargoLabel{std::byteswap(buf.ReadDWord())}; - BuildCargoLabelMap(); - break; - - case 0x18: { // Town growth substitute type - uint8_t substitute_type = buf.ReadByte(); - - switch (substitute_type) { - case 0x00: cs->town_acceptance_effect = TAE_PASSENGERS; break; - case 0x02: cs->town_acceptance_effect = TAE_MAIL; break; - case 0x05: cs->town_acceptance_effect = TAE_GOODS; break; - case 0x09: cs->town_acceptance_effect = TAE_WATER; break; - case 0x0B: cs->town_acceptance_effect = TAE_FOOD; break; - default: - GrfMsg(1, "CargoChangeInfo: Unknown town growth substitute value {}, setting to none.", substitute_type); - [[fallthrough]]; - case 0xFF: cs->town_acceptance_effect = TAE_NONE; break; - } - break; - } - - case 0x19: // Town growth coefficient - buf.ReadWord(); - break; - - case 0x1A: // Bitmask of callbacks to use - cs->callback_mask = static_cast(buf.ReadByte()); - break; - - case 0x1D: // Vehicle capacity muliplier - cs->multiplier = std::max(1u, buf.ReadWord()); - break; - - case 0x1E: { // Town production substitute type - uint8_t substitute_type = buf.ReadByte(); - - switch (substitute_type) { - case 0x00: cs->town_production_effect = TPE_PASSENGERS; break; - case 0x02: cs->town_production_effect = TPE_MAIL; break; - default: - GrfMsg(1, "CargoChangeInfo: Unknown town production substitute value {}, setting to none.", substitute_type); - [[fallthrough]]; - case 0xFF: cs->town_production_effect = TPE_NONE; break; - } - break; - } - - case 0x1F: // Town production multiplier - cs->town_production_multiplier = std::max(1U, buf.ReadWord()); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - - -/** - * Define properties for sound effects - * @param first Local ID of the first sound. - * @param last Local ID of the last sound. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult SoundEffectChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - if (_cur.grffile->sound_offset == 0) { - GrfMsg(1, "SoundEffectChangeInfo: No effects defined, skipping"); - return CIR_INVALID_ID; - } - - if (last - ORIGINAL_SAMPLE_COUNT > _cur.grffile->num_sounds) { - GrfMsg(1, "SoundEffectChangeInfo: Attempting to change undefined sound effect ({}), max ({}). Ignoring.", last, ORIGINAL_SAMPLE_COUNT + _cur.grffile->num_sounds); - return CIR_INVALID_ID; - } - - for (uint id = first; id < last; ++id) { - SoundEntry *sound = GetSound(first + _cur.grffile->sound_offset - ORIGINAL_SAMPLE_COUNT); - - switch (prop) { - case 0x08: // Relative volume - sound->volume = Clamp(buf.ReadByte(), 0, SOUND_EFFECT_MAX_VOLUME); - break; - - case 0x09: // Priority - sound->priority = buf.ReadByte(); - break; - - case 0x0A: { // Override old sound - SoundID orig_sound = buf.ReadByte(); - - if (orig_sound >= ORIGINAL_SAMPLE_COUNT) { - GrfMsg(1, "SoundEffectChangeInfo: Original sound {} not defined (max {})", orig_sound, ORIGINAL_SAMPLE_COUNT); - } else { - SoundEntry *old_sound = GetSound(orig_sound); - - /* Literally copy the data of the new sound over the original */ - *old_sound = *sound; - } - break; - } - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -/** - * Ignore an industry tile property - * @param prop The property to ignore. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult IgnoreIndustryTileProperty(int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - switch (prop) { - case 0x09: - case 0x0D: - case 0x0E: - case 0x10: - case 0x11: - case 0x12: - buf.ReadByte(); - break; - - case 0x0A: - case 0x0B: - case 0x0C: - case 0x0F: - buf.ReadWord(); - break; - - case 0x13: - buf.Skip(buf.ReadByte() * 2); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - return ret; -} - -/** - * Define properties for industry tiles - * @param first Local ID of the first industry tile. - * @param last Local ID of the last industry tile. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult IndustrytilesChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - if (last > NUM_INDUSTRYTILES_PER_GRF) { - GrfMsg(1, "IndustryTilesChangeInfo: Too many industry tiles loaded ({}), max ({}). Ignoring.", last, NUM_INDUSTRYTILES_PER_GRF); - return CIR_INVALID_ID; - } - - /* Allocate industry tile specs if they haven't been allocated already. */ - if (_cur.grffile->indtspec.size() < last) _cur.grffile->indtspec.resize(last); - - for (uint id = first; id < last; ++id) { - auto &tsp = _cur.grffile->indtspec[id]; - - if (prop != 0x08 && tsp == nullptr) { - ChangeInfoResult cir = IgnoreIndustryTileProperty(prop, buf); - if (cir > ret) ret = cir; - continue; - } - - switch (prop) { - case 0x08: { // Substitute industry tile type - uint8_t subs_id = buf.ReadByte(); - if (subs_id >= NEW_INDUSTRYTILEOFFSET) { - /* The substitute id must be one of the original industry tile. */ - GrfMsg(2, "IndustryTilesChangeInfo: Attempt to use new industry tile {} as substitute industry tile for {}. Ignoring.", subs_id, id); - continue; - } - - /* Allocate space for this industry. */ - if (tsp == nullptr) { - tsp = std::make_unique(_industry_tile_specs[subs_id]); - - tsp->enabled = true; - - /* A copied tile should not have the animation infos copied too. - * The anim_state should be left untouched, though - * It is up to the author to animate them */ - tsp->anim_production = INDUSTRYTILE_NOANIM; - tsp->anim_next = INDUSTRYTILE_NOANIM; - - tsp->grf_prop.local_id = id; - tsp->grf_prop.subst_id = subs_id; - tsp->grf_prop.SetGRFFile(_cur.grffile); - _industile_mngr.AddEntityID(id, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot - } - break; - } - - case 0x09: { // Industry tile override - uint8_t ovrid = buf.ReadByte(); - - /* The industry being overridden must be an original industry. */ - if (ovrid >= NEW_INDUSTRYTILEOFFSET) { - GrfMsg(2, "IndustryTilesChangeInfo: Attempt to override new industry tile {} with industry tile id {}. Ignoring.", ovrid, id); - continue; - } - - _industile_mngr.Add(id, _cur.grffile->grfid, ovrid); - break; - } - - case 0x0A: // Tile acceptance - case 0x0B: - case 0x0C: { - uint16_t acctp = buf.ReadWord(); - tsp->accepts_cargo[prop - 0x0A] = GetCargoTranslation(GB(acctp, 0, 8), _cur.grffile); - tsp->acceptance[prop - 0x0A] = Clamp(GB(acctp, 8, 8), 0, 16); - tsp->accepts_cargo_label[prop - 0x0A] = CT_INVALID; - break; - } - - case 0x0D: // Land shape flags - tsp->slopes_refused = (Slope)buf.ReadByte(); - break; - - case 0x0E: // Callback mask - tsp->callback_mask = static_cast(buf.ReadByte()); - break; - - case 0x0F: // Animation information - tsp->animation.frames = buf.ReadByte(); - tsp->animation.status = buf.ReadByte(); - break; - - case 0x10: // Animation speed - tsp->animation.speed = buf.ReadByte(); - break; - - case 0x11: // Triggers for callback 25 - tsp->animation.triggers = buf.ReadByte(); - break; - - case 0x12: // Special flags - tsp->special_flags = IndustryTileSpecialFlags{buf.ReadByte()}; - break; - - case 0x13: { // variable length cargo acceptance - uint8_t num_cargoes = buf.ReadByte(); - if (num_cargoes > std::size(tsp->acceptance)) { - GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG); - error->param_value[1] = prop; - return CIR_DISABLED; - } - for (uint i = 0; i < std::size(tsp->acceptance); i++) { - if (i < num_cargoes) { - tsp->accepts_cargo[i] = GetCargoTranslation(buf.ReadByte(), _cur.grffile); - /* Tile acceptance can be negative to counteract the IndustryTileSpecialFlag::AcceptsAllCargo flag */ - tsp->acceptance[i] = (int8_t)buf.ReadByte(); - } else { - tsp->accepts_cargo[i] = INVALID_CARGO; - tsp->acceptance[i] = 0; - } - if (i < std::size(tsp->accepts_cargo_label)) tsp->accepts_cargo_label[i] = CT_INVALID; - } - break; - } - - case 0x14: // Badge list - tsp->badges = ReadBadgeList(buf, GSF_INDUSTRYTILES); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -/** - * Ignore an industry property - * @param prop The property to ignore. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult IgnoreIndustryProperty(int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - switch (prop) { - case 0x09: - case 0x0B: - case 0x0F: - case 0x12: - case 0x13: - case 0x14: - case 0x17: - case 0x18: - case 0x19: - case 0x21: - case 0x22: - buf.ReadByte(); - break; - - case 0x0C: - case 0x0D: - case 0x0E: - case 0x10: // INDUSTRY_ORIGINAL_NUM_OUTPUTS bytes - case 0x1B: - case 0x1F: - case 0x24: - buf.ReadWord(); - break; - - case 0x11: // INDUSTRY_ORIGINAL_NUM_INPUTS bytes + 1 - case 0x1A: - case 0x1C: - case 0x1D: - case 0x1E: - case 0x20: - case 0x23: - buf.ReadDWord(); - break; - - case 0x0A: { - uint8_t num_table = buf.ReadByte(); - for (uint8_t j = 0; j < num_table; j++) { - for (uint k = 0;; k++) { - uint8_t x = buf.ReadByte(); - if (x == 0xFE && k == 0) { - buf.ReadByte(); - buf.ReadByte(); - break; - } - - uint8_t y = buf.ReadByte(); - if (x == 0 && y == 0x80) break; - - uint8_t gfx = buf.ReadByte(); - if (gfx == 0xFE) buf.ReadWord(); - } - } - break; - } - - case 0x16: - for (uint8_t j = 0; j < INDUSTRY_ORIGINAL_NUM_INPUTS; j++) buf.ReadByte(); - break; - - case 0x15: - case 0x25: - case 0x26: - case 0x27: - buf.Skip(buf.ReadByte()); - break; - - case 0x28: { - int num_inputs = buf.ReadByte(); - int num_outputs = buf.ReadByte(); - buf.Skip(num_inputs * num_outputs * 2); - break; - } - - case 0x29: // Badge list - SkipBadgeList(buf); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - return ret; -} - -/** - * Validate the industry layout; e.g. to prevent duplicate tiles. - * @param layout The layout to check. - * @return True if the layout is deemed valid. - */ -static bool ValidateIndustryLayout(const IndustryTileLayout &layout) -{ - const size_t size = layout.size(); - if (size == 0) return false; - - for (size_t i = 0; i < size - 1; i++) { - for (size_t j = i + 1; j < size; j++) { - if (layout[i].ti.x == layout[j].ti.x && - layout[i].ti.y == layout[j].ti.y) { - return false; - } - } - } - - bool have_regular_tile = false; - for (const auto &tilelayout : layout) { - if (tilelayout.gfx != GFX_WATERTILE_SPECIALCHECK) { - have_regular_tile = true; - break; - } - } - - return have_regular_tile; -} - -/** - * Define properties for industries - * @param first Local ID of the first industry. - * @param last Local ID of the last industry. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult IndustriesChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - if (last > NUM_INDUSTRYTYPES_PER_GRF) { - GrfMsg(1, "IndustriesChangeInfo: Too many industries loaded ({}), max ({}). Ignoring.", last, NUM_INDUSTRYTYPES_PER_GRF); - return CIR_INVALID_ID; - } - - /* Allocate industry specs if they haven't been allocated already. */ - if (_cur.grffile->industryspec.size() < last) _cur.grffile->industryspec.resize(last); - - for (uint id = first; id < last; ++id) { - auto &indsp = _cur.grffile->industryspec[id]; - - if (prop != 0x08 && indsp == nullptr) { - ChangeInfoResult cir = IgnoreIndustryProperty(prop, buf); - if (cir > ret) ret = cir; - continue; - } - - switch (prop) { - case 0x08: { // Substitute industry type - uint8_t subs_id = buf.ReadByte(); - if (subs_id == 0xFF) { - /* Instead of defining a new industry, a substitute industry id - * of 0xFF disables the old industry with the current id. */ - _industry_specs[id].enabled = false; - continue; - } else if (subs_id >= NEW_INDUSTRYOFFSET) { - /* The substitute id must be one of the original industry. */ - GrfMsg(2, "_industry_specs: Attempt to use new industry {} as substitute industry for {}. Ignoring.", subs_id, id); - continue; - } - - /* Allocate space for this industry. - * Only need to do it once. If ever it is called again, it should not - * do anything */ - if (indsp == nullptr) { - indsp = std::make_unique(_origin_industry_specs[subs_id]); - - indsp->enabled = true; - indsp->grf_prop.local_id = id; - indsp->grf_prop.subst_id = subs_id; - indsp->grf_prop.SetGRFFile(_cur.grffile); - /* If the grf industry needs to check its surrounding upon creation, it should - * rely on callbacks, not on the original placement functions */ - indsp->check_proc = CHECK_NOTHING; - } - break; - } - - case 0x09: { // Industry type override - uint8_t ovrid = buf.ReadByte(); - - /* The industry being overridden must be an original industry. */ - if (ovrid >= NEW_INDUSTRYOFFSET) { - GrfMsg(2, "IndustriesChangeInfo: Attempt to override new industry {} with industry id {}. Ignoring.", ovrid, id); - continue; - } - indsp->grf_prop.override = ovrid; - _industry_mngr.Add(id, _cur.grffile->grfid, ovrid); - break; - } - - case 0x0A: { // Set industry layout(s) - uint8_t new_num_layouts = buf.ReadByte(); - uint32_t definition_size = buf.ReadDWord(); - uint32_t bytes_read = 0; - std::vector new_layouts; - IndustryTileLayout layout; - - for (uint8_t j = 0; j < new_num_layouts; j++) { - layout.clear(); - - for (uint k = 0;; k++) { - if (bytes_read >= definition_size) { - GrfMsg(3, "IndustriesChangeInfo: Incorrect size for industry tile layout definition for industry {}.", id); - /* Avoid warning twice */ - definition_size = UINT32_MAX; - } - - IndustryTileLayoutTile &it = layout.emplace_back(); - - it.ti.x = buf.ReadByte(); // Offsets from northermost tile - ++bytes_read; - - if (it.ti.x == 0xFE && k == 0) { - /* This means we have to borrow the layout from an old industry */ - IndustryType type = buf.ReadByte(); - uint8_t laynbr = buf.ReadByte(); - bytes_read += 2; - - if (type >= lengthof(_origin_industry_specs)) { - GrfMsg(1, "IndustriesChangeInfo: Invalid original industry number for layout import, industry {}", id); - DisableGrf(STR_NEWGRF_ERROR_INVALID_ID); - return CIR_DISABLED; - } - if (laynbr >= _origin_industry_specs[type].layouts.size()) { - GrfMsg(1, "IndustriesChangeInfo: Invalid original industry layout index for layout import, industry {}", id); - DisableGrf(STR_NEWGRF_ERROR_INVALID_ID); - return CIR_DISABLED; - } - layout = _origin_industry_specs[type].layouts[laynbr]; - break; - } - - it.ti.y = buf.ReadByte(); // Or table definition finalisation - ++bytes_read; - - if (it.ti.x == 0 && it.ti.y == 0x80) { - /* Terminator, remove and finish up */ - layout.pop_back(); - break; - } - - it.gfx = buf.ReadByte(); - ++bytes_read; - - if (it.gfx == 0xFE) { - /* Use a new tile from this GRF */ - int local_tile_id = buf.ReadWord(); - bytes_read += 2; - - /* Read the ID from the _industile_mngr. */ - int tempid = _industile_mngr.GetID(local_tile_id, _cur.grffile->grfid); - - if (tempid == INVALID_INDUSTRYTILE) { - GrfMsg(2, "IndustriesChangeInfo: Attempt to use industry tile {} with industry id {}, not yet defined. Ignoring.", local_tile_id, id); - } else { - /* Declared as been valid, can be used */ - it.gfx = tempid; - } - } else if (it.gfx == GFX_WATERTILE_SPECIALCHECK) { - it.ti.x = (int8_t)GB(it.ti.x, 0, 8); - it.ti.y = (int8_t)GB(it.ti.y, 0, 8); - - /* When there were only 256x256 maps, TileIndex was a uint16_t and - * it.ti was just a TileIndexDiff that was added to it. - * As such negative "x" values were shifted into the "y" position. - * x = -1, y = 1 -> x = 255, y = 0 - * Since GRF version 8 the position is interpreted as pair of independent int8. - * For GRF version < 8 we need to emulate the old shifting behaviour. - */ - if (_cur.grffile->grf_version < 8 && it.ti.x < 0) it.ti.y += 1; - } - } - - if (!ValidateIndustryLayout(layout)) { - /* The industry layout was not valid, so skip this one. */ - GrfMsg(1, "IndustriesChangeInfo: Invalid industry layout for industry id {}. Ignoring", id); - } else { - new_layouts.push_back(layout); - } - } - - /* Install final layout construction in the industry spec */ - indsp->layouts = std::move(new_layouts); - break; - } - - case 0x0B: // Industry production flags - indsp->life_type = IndustryLifeTypes{buf.ReadByte()}; - break; - - case 0x0C: // Industry closure message - AddStringForMapping(GRFStringID{buf.ReadWord()}, &indsp->closure_text); - break; - - case 0x0D: // Production increase message - AddStringForMapping(GRFStringID{buf.ReadWord()}, &indsp->production_up_text); - break; - - case 0x0E: // Production decrease message - AddStringForMapping(GRFStringID{buf.ReadWord()}, &indsp->production_down_text); - break; - - case 0x0F: // Fund cost multiplier - indsp->cost_multiplier = buf.ReadByte(); - break; - - case 0x10: // Production cargo types - for (uint8_t j = 0; j < INDUSTRY_ORIGINAL_NUM_OUTPUTS; j++) { - indsp->produced_cargo[j] = GetCargoTranslation(buf.ReadByte(), _cur.grffile); - indsp->produced_cargo_label[j] = CT_INVALID; - } - break; - - case 0x11: // Acceptance cargo types - for (uint8_t j = 0; j < INDUSTRY_ORIGINAL_NUM_INPUTS; j++) { - indsp->accepts_cargo[j] = GetCargoTranslation(buf.ReadByte(), _cur.grffile); - indsp->accepts_cargo_label[j] = CT_INVALID; - } - buf.ReadByte(); // Unnused, eat it up - break; - - case 0x12: // Production multipliers - case 0x13: - indsp->production_rate[prop - 0x12] = buf.ReadByte(); - break; - - case 0x14: // Minimal amount of cargo distributed - indsp->minimal_cargo = buf.ReadByte(); - break; - - case 0x15: { // Random sound effects - uint8_t num_sounds = buf.ReadByte(); - - std::vector sounds; - sounds.reserve(num_sounds); - for (uint8_t j = 0; j < num_sounds; ++j) { - sounds.push_back(buf.ReadByte()); - } - - indsp->random_sounds = std::move(sounds); - break; - } - - case 0x16: // Conflicting industry types - for (uint8_t j = 0; j < 3; j++) indsp->conflicting[j] = buf.ReadByte(); - break; - - case 0x17: // Probability in random game - indsp->appear_creation[to_underlying(_settings_game.game_creation.landscape)] = buf.ReadByte(); - break; - - case 0x18: // Probability during gameplay - indsp->appear_ingame[to_underlying(_settings_game.game_creation.landscape)] = buf.ReadByte(); - break; - - case 0x19: // Map colour - indsp->map_colour = buf.ReadByte(); - break; - - case 0x1A: // Special industry flags to define special behavior - indsp->behaviour = IndustryBehaviours{buf.ReadDWord()}; - break; - - case 0x1B: // New industry text ID - AddStringForMapping(GRFStringID{buf.ReadWord()}, &indsp->new_industry_text); - break; - - case 0x1C: // Input cargo multipliers for the three input cargo types - case 0x1D: - case 0x1E: { - uint32_t multiples = buf.ReadDWord(); - indsp->input_cargo_multiplier[prop - 0x1C][0] = GB(multiples, 0, 16); - indsp->input_cargo_multiplier[prop - 0x1C][1] = GB(multiples, 16, 16); - break; - } - - case 0x1F: // Industry name - AddStringForMapping(GRFStringID{buf.ReadWord()}, &indsp->name); - break; - - case 0x20: // Prospecting success chance - indsp->prospecting_chance = buf.ReadDWord(); - break; - - case 0x21: // Callback mask - case 0x22: { // Callback additional mask - auto mask = indsp->callback_mask.base(); - SB(mask, (prop - 0x21) * 8, 8, buf.ReadByte()); - indsp->callback_mask = IndustryCallbackMasks{mask}; - break; - } - - case 0x23: // removal cost multiplier - indsp->removal_cost_multiplier = buf.ReadDWord(); - break; - - case 0x24: { // name for nearby station - GRFStringID str{buf.ReadWord()}; - if (str == 0) { - indsp->station_name = STR_NULL; - } else { - AddStringForMapping(str, &indsp->station_name); - } - break; - } - - case 0x25: { // variable length produced cargoes - uint8_t num_cargoes = buf.ReadByte(); - if (num_cargoes > std::size(indsp->produced_cargo)) { - GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG); - error->param_value[1] = prop; - return CIR_DISABLED; - } - for (size_t i = 0; i < std::size(indsp->produced_cargo); i++) { - if (i < num_cargoes) { - CargoType cargo = GetCargoTranslation(buf.ReadByte(), _cur.grffile); - indsp->produced_cargo[i] = cargo; - } else { - indsp->produced_cargo[i] = INVALID_CARGO; - } - if (i < std::size(indsp->produced_cargo_label)) indsp->produced_cargo_label[i] = CT_INVALID; - } - break; - } - - case 0x26: { // variable length accepted cargoes - uint8_t num_cargoes = buf.ReadByte(); - if (num_cargoes > std::size(indsp->accepts_cargo)) { - GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG); - error->param_value[1] = prop; - return CIR_DISABLED; - } - for (size_t i = 0; i < std::size(indsp->accepts_cargo); i++) { - if (i < num_cargoes) { - CargoType cargo = GetCargoTranslation(buf.ReadByte(), _cur.grffile); - indsp->accepts_cargo[i] = cargo; - } else { - indsp->accepts_cargo[i] = INVALID_CARGO; - } - if (i < std::size(indsp->accepts_cargo_label)) indsp->accepts_cargo_label[i] = CT_INVALID; - } - break; - } - - case 0x27: { // variable length production rates - uint8_t num_cargoes = buf.ReadByte(); - if (num_cargoes > lengthof(indsp->production_rate)) { - GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG); - error->param_value[1] = prop; - return CIR_DISABLED; - } - for (uint i = 0; i < lengthof(indsp->production_rate); i++) { - if (i < num_cargoes) { - indsp->production_rate[i] = buf.ReadByte(); - } else { - indsp->production_rate[i] = 0; - } - } - break; - } - - case 0x28: { // variable size input/output production multiplier table - uint8_t num_inputs = buf.ReadByte(); - uint8_t num_outputs = buf.ReadByte(); - if (num_inputs > std::size(indsp->accepts_cargo) || num_outputs > std::size(indsp->produced_cargo)) { - GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG); - error->param_value[1] = prop; - return CIR_DISABLED; - } - for (size_t i = 0; i < std::size(indsp->accepts_cargo); i++) { - for (size_t j = 0; j < std::size(indsp->produced_cargo); j++) { - uint16_t mult = 0; - if (i < num_inputs && j < num_outputs) mult = buf.ReadWord(); - indsp->input_cargo_multiplier[i][j] = mult; - } - } - break; - } - - case 0x29: // Badge list - indsp->badges = ReadBadgeList(buf, GSF_INDUSTRIES); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -/** - * Define properties for airports - * @param first Local ID of the first airport. - * @param last Local ID of the last airport. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult AirportChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - if (last > NUM_AIRPORTS_PER_GRF) { - GrfMsg(1, "AirportChangeInfo: Too many airports, trying id ({}), max ({}). Ignoring.", last, NUM_AIRPORTS_PER_GRF); - return CIR_INVALID_ID; - } - - /* Allocate industry specs if they haven't been allocated already. */ - if (_cur.grffile->airportspec.size() < last) _cur.grffile->airportspec.resize(last); - - for (uint id = first; id < last; ++id) { - auto &as = _cur.grffile->airportspec[id]; - - if (as == nullptr && prop != 0x08 && prop != 0x09) { - GrfMsg(2, "AirportChangeInfo: Attempt to modify undefined airport {}, ignoring", id); - return CIR_INVALID_ID; - } - - switch (prop) { - case 0x08: { // Modify original airport - uint8_t subs_id = buf.ReadByte(); - if (subs_id == 0xFF) { - /* Instead of defining a new airport, an airport id - * of 0xFF disables the old airport with the current id. */ - AirportSpec::GetWithoutOverride(id)->enabled = false; - continue; - } else if (subs_id >= NEW_AIRPORT_OFFSET) { - /* The substitute id must be one of the original airports. */ - GrfMsg(2, "AirportChangeInfo: Attempt to use new airport {} as substitute airport for {}. Ignoring.", subs_id, id); - continue; - } - - /* Allocate space for this airport. - * Only need to do it once. If ever it is called again, it should not - * do anything */ - if (as == nullptr) { - as = std::make_unique(*AirportSpec::GetWithoutOverride(subs_id)); - - as->enabled = true; - as->grf_prop.local_id = id; - as->grf_prop.subst_id = subs_id; - as->grf_prop.SetGRFFile(_cur.grffile); - /* override the default airport */ - _airport_mngr.Add(id, _cur.grffile->grfid, subs_id); - } - break; - } - - case 0x0A: { // Set airport layout - uint8_t num_layouts = buf.ReadByte(); - buf.ReadDWord(); // Total size of definition, unneeded. - uint8_t size_x = 0; - uint8_t size_y = 0; - - std::vector layouts; - layouts.reserve(num_layouts); - - for (uint8_t j = 0; j != num_layouts; ++j) { - auto &layout = layouts.emplace_back(); - layout.rotation = static_cast(buf.ReadByte() & 6); // Rotation can only be DIR_NORTH, DIR_EAST, DIR_SOUTH or DIR_WEST. - - for (;;) { - auto &tile = layout.tiles.emplace_back(); - tile.ti.x = buf.ReadByte(); - tile.ti.y = buf.ReadByte(); - if (tile.ti.x == 0 && tile.ti.y == 0x80) { - /* Convert terminator to our own. */ - tile.ti.x = -0x80; - tile.ti.y = 0; - tile.gfx = 0; - break; - } - - tile.gfx = buf.ReadByte(); - - if (tile.gfx == 0xFE) { - /* Use a new tile from this GRF */ - int local_tile_id = buf.ReadWord(); - - /* Read the ID from the _airporttile_mngr. */ - uint16_t tempid = _airporttile_mngr.GetID(local_tile_id, _cur.grffile->grfid); - - if (tempid == INVALID_AIRPORTTILE) { - GrfMsg(2, "AirportChangeInfo: Attempt to use airport tile {} with airport id {}, not yet defined. Ignoring.", local_tile_id, id); - } else { - /* Declared as been valid, can be used */ - tile.gfx = tempid; - } - } else if (tile.gfx == 0xFF) { - tile.ti.x = static_cast(GB(tile.ti.x, 0, 8)); - tile.ti.y = static_cast(GB(tile.ti.y, 0, 8)); - } - - /* Determine largest size. */ - if (layout.rotation == DIR_E || layout.rotation == DIR_W) { - size_x = std::max(size_x, tile.ti.y + 1); - size_y = std::max(size_y, tile.ti.x + 1); - } else { - size_x = std::max(size_x, tile.ti.x + 1); - size_y = std::max(size_y, tile.ti.y + 1); - } - } - } - as->layouts = std::move(layouts); - as->size_x = size_x; - as->size_y = size_y; - break; - } - - case 0x0C: - as->min_year = TimerGameCalendar::Year{buf.ReadWord()}; - as->max_year = TimerGameCalendar::Year{buf.ReadWord()}; - if (as->max_year == 0xFFFF) as->max_year = CalendarTime::MAX_YEAR; - break; - - case 0x0D: - as->ttd_airport_type = (TTDPAirportType)buf.ReadByte(); - break; - - case 0x0E: - as->catchment = Clamp(buf.ReadByte(), 1, MAX_CATCHMENT); - break; - - case 0x0F: - as->noise_level = buf.ReadByte(); - break; - - case 0x10: - AddStringForMapping(GRFStringID{buf.ReadWord()}, &as->name); - break; - - case 0x11: // Maintenance cost factor - as->maintenance_cost = buf.ReadWord(); - break; - - case 0x12: // Badge list - as->badges = ReadBadgeList(buf, GSF_AIRPORTS); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -/** - * Ignore properties for objects - * @param prop The property to ignore. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult IgnoreObjectProperty(uint prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - switch (prop) { - case 0x0B: - case 0x0C: - case 0x0D: - case 0x12: - case 0x14: - case 0x16: - case 0x17: - case 0x18: - buf.ReadByte(); - break; - - case 0x09: - case 0x0A: - case 0x10: - case 0x11: - case 0x13: - case 0x15: - buf.ReadWord(); - break; - - case 0x08: - case 0x0E: - case 0x0F: - buf.ReadDWord(); - break; - - case 0x19: // Badge list - SkipBadgeList(buf); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - - return ret; -} - -/** - * Define properties for objects - * @param first Local ID of the first object. - * @param last Local ID of the last object. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult ObjectChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - if (last > NUM_OBJECTS_PER_GRF) { - GrfMsg(1, "ObjectChangeInfo: Too many objects loaded ({}), max ({}). Ignoring.", last, NUM_OBJECTS_PER_GRF); - return CIR_INVALID_ID; - } - - /* Allocate object specs if they haven't been allocated already. */ - if (_cur.grffile->objectspec.size() < last) _cur.grffile->objectspec.resize(last); - - for (uint id = first; id < last; ++id) { - auto &spec = _cur.grffile->objectspec[id]; - - if (prop != 0x08 && spec == nullptr) { - /* If the object property 08 is not yet set, ignore this property */ - ChangeInfoResult cir = IgnoreObjectProperty(prop, buf); - if (cir > ret) ret = cir; - continue; - } - - switch (prop) { - case 0x08: { // Class ID - /* Allocate space for this object. */ - if (spec == nullptr) { - spec = std::make_unique(); - spec->views = 1; // Default for NewGRFs that don't set it. - spec->size = OBJECT_SIZE_1X1; // Default for NewGRFs that manage to not set it (1x1) - } - - /* Swap classid because we read it in BE. */ - uint32_t classid = buf.ReadDWord(); - spec->class_index = ObjectClass::Allocate(std::byteswap(classid)); - break; - } - - case 0x09: { // Class name - AddStringForMapping(GRFStringID{buf.ReadWord()}, [spec = spec.get()](StringID str) { ObjectClass::Get(spec->class_index)->name = str; }); - break; - } - - case 0x0A: // Object name - AddStringForMapping(GRFStringID{buf.ReadWord()}, &spec->name); - break; - - case 0x0B: // Climate mask - spec->climate = LandscapeTypes{buf.ReadByte()}; - break; - - case 0x0C: // Size - spec->size = buf.ReadByte(); - if (GB(spec->size, 0, 4) == 0 || GB(spec->size, 4, 4) == 0) { - GrfMsg(0, "ObjectChangeInfo: Invalid object size requested (0x{:X}) for object id {}. Ignoring.", spec->size, id); - spec->size = OBJECT_SIZE_1X1; - } - break; - - case 0x0D: // Build cost multiplier - spec->build_cost_multiplier = buf.ReadByte(); - spec->clear_cost_multiplier = spec->build_cost_multiplier; - break; - - case 0x0E: // Introduction date - spec->introduction_date = TimerGameCalendar::Date(buf.ReadDWord()); - break; - - case 0x0F: // End of life - spec->end_of_life_date = TimerGameCalendar::Date(buf.ReadDWord()); - break; - - case 0x10: // Flags - spec->flags = (ObjectFlags)buf.ReadWord(); - _loaded_newgrf_features.has_2CC |= spec->flags.Test(ObjectFlag::Uses2CC); - break; - - case 0x11: // Animation info - spec->animation.frames = buf.ReadByte(); - spec->animation.status = buf.ReadByte(); - break; - - case 0x12: // Animation speed - spec->animation.speed = buf.ReadByte(); - break; - - case 0x13: // Animation triggers - spec->animation.triggers = buf.ReadWord(); - break; - - case 0x14: // Removal cost multiplier - spec->clear_cost_multiplier = buf.ReadByte(); - break; - - case 0x15: // Callback mask - spec->callback_mask = static_cast(buf.ReadWord()); - break; - - case 0x16: // Building height - spec->height = buf.ReadByte(); - break; - - case 0x17: // Views - spec->views = buf.ReadByte(); - if (spec->views != 1 && spec->views != 2 && spec->views != 4) { - GrfMsg(2, "ObjectChangeInfo: Invalid number of views ({}) for object id {}. Ignoring.", spec->views, id); - spec->views = 1; - } - break; - - case 0x18: // Amount placed on 256^2 map on map creation - spec->generate_amount = buf.ReadByte(); - break; - - case 0x19: // Badge list - spec->badges = ReadBadgeList(buf, GSF_OBJECTS); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -/** - * Define properties for railtypes - * @param first Local ID of the first railtype. - * @param last Local ID of the last railtype. - * @param prop The property to change. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult RailTypeChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - extern RailTypeInfo _railtypes[RAILTYPE_END]; - - if (last > RAILTYPE_END) { - GrfMsg(1, "RailTypeChangeInfo: Rail type {} is invalid, max {}, ignoring", last, RAILTYPE_END); - return CIR_INVALID_ID; - } - - for (uint id = first; id < last; ++id) { - RailType rt = _cur.grffile->railtype_map[id]; - if (rt == INVALID_RAILTYPE) return CIR_INVALID_ID; - - RailTypeInfo *rti = &_railtypes[rt]; - - switch (prop) { - case 0x08: // Label of rail type - /* Skipped here as this is loaded during reservation stage. */ - buf.ReadDWord(); - break; - - case 0x09: { // Toolbar caption of railtype (sets name as well for backwards compatibility for grf ver < 8) - GRFStringID str{buf.ReadWord()}; - AddStringForMapping(str, &rti->strings.toolbar_caption); - if (_cur.grffile->grf_version < 8) { - AddStringForMapping(str, &rti->strings.name); - } - break; - } - - case 0x0A: // Menu text of railtype - AddStringForMapping(GRFStringID{buf.ReadWord()}, &rti->strings.menu_text); - break; - - case 0x0B: // Build window caption - AddStringForMapping(GRFStringID{buf.ReadWord()}, &rti->strings.build_caption); - break; - - case 0x0C: // Autoreplace text - AddStringForMapping(GRFStringID{buf.ReadWord()}, &rti->strings.replace_text); - break; - - case 0x0D: // New locomotive text - AddStringForMapping(GRFStringID{buf.ReadWord()}, &rti->strings.new_loco); - break; - - case 0x0E: // Compatible railtype list - case 0x0F: // Powered railtype list - case 0x18: // Railtype list required for date introduction - case 0x19: // Introduced railtype list - { - /* Rail type compatibility bits are added to the existing bits - * to allow multiple GRFs to modify compatibility with the - * default rail types. */ - int n = buf.ReadByte(); - for (int j = 0; j != n; j++) { - RailTypeLabel label = buf.ReadDWord(); - RailType resolved_rt = GetRailTypeByLabel(std::byteswap(label), false); - if (resolved_rt != INVALID_RAILTYPE) { - switch (prop) { - case 0x0F: SetBit(rti->powered_railtypes, resolved_rt); [[fallthrough]]; // Powered implies compatible. - case 0x0E: SetBit(rti->compatible_railtypes, resolved_rt); break; - case 0x18: SetBit(rti->introduction_required_railtypes, resolved_rt); break; - case 0x19: SetBit(rti->introduces_railtypes, resolved_rt); break; - } - } - } - break; - } - - case 0x10: // Rail Type flags - rti->flags = static_cast(buf.ReadByte()); - break; - - case 0x11: // Curve speed advantage - rti->curve_speed = buf.ReadByte(); - break; - - case 0x12: // Station graphic - rti->fallback_railtype = Clamp(buf.ReadByte(), 0, 2); - break; - - case 0x13: // Construction cost factor - rti->cost_multiplier = buf.ReadWord(); - break; - - case 0x14: // Speed limit - rti->max_speed = buf.ReadWord(); - break; - - case 0x15: // Acceleration model - rti->acceleration_type = Clamp(buf.ReadByte(), 0, 2); - break; - - case 0x16: // Map colour - rti->map_colour = buf.ReadByte(); - break; - - case 0x17: // Introduction date - rti->introduction_date = TimerGameCalendar::Date(buf.ReadDWord()); - break; - - case 0x1A: // Sort order - rti->sorting_order = buf.ReadByte(); - break; - - case 0x1B: // Name of railtype (overridden by prop 09 for grf ver < 8) - AddStringForMapping(GRFStringID{buf.ReadWord()}, &rti->strings.name); - break; - - case 0x1C: // Maintenance cost factor - rti->maintenance_multiplier = buf.ReadWord(); - break; - - case 0x1D: // Alternate rail type label list - /* Skipped here as this is loaded during reservation stage. */ - for (int j = buf.ReadByte(); j != 0; j--) buf.ReadDWord(); - break; - - case 0x1E: // Badge list - rti->badges = ReadBadgeList(buf, GSF_RAILTYPES); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -static ChangeInfoResult RailTypeReserveInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - extern RailTypeInfo _railtypes[RAILTYPE_END]; - - if (last > RAILTYPE_END) { - GrfMsg(1, "RailTypeReserveInfo: Rail type {} is invalid, max {}, ignoring", last, RAILTYPE_END); - return CIR_INVALID_ID; - } - - for (uint id = first; id < last; ++id) { - switch (prop) { - case 0x08: // Label of rail type - { - RailTypeLabel rtl = buf.ReadDWord(); - rtl = std::byteswap(rtl); - - RailType rt = GetRailTypeByLabel(rtl, false); - if (rt == INVALID_RAILTYPE) { - /* Set up new rail type */ - rt = AllocateRailType(rtl); - } - - _cur.grffile->railtype_map[id] = rt; - break; - } - - case 0x09: // Toolbar caption of railtype - case 0x0A: // Menu text - case 0x0B: // Build window caption - case 0x0C: // Autoreplace text - case 0x0D: // New loco - case 0x13: // Construction cost - case 0x14: // Speed limit - case 0x1B: // Name of railtype - case 0x1C: // Maintenance cost factor - buf.ReadWord(); - break; - - case 0x1D: // Alternate rail type label list - if (_cur.grffile->railtype_map[id] != INVALID_RAILTYPE) { - int n = buf.ReadByte(); - for (int j = 0; j != n; j++) { - _railtypes[_cur.grffile->railtype_map[id]].alternate_labels.push_back(std::byteswap(buf.ReadDWord())); - } - break; - } - GrfMsg(1, "RailTypeReserveInfo: Ignoring property 1D for rail type {} because no label was set", id); - [[fallthrough]]; - - case 0x0E: // Compatible railtype list - case 0x0F: // Powered railtype list - case 0x18: // Railtype list required for date introduction - case 0x19: // Introduced railtype list - for (int j = buf.ReadByte(); j != 0; j--) buf.ReadDWord(); - break; - - case 0x10: // Rail Type flags - case 0x11: // Curve speed advantage - case 0x12: // Station graphic - case 0x15: // Acceleration model - case 0x16: // Map colour - case 0x1A: // Sort order - buf.ReadByte(); - break; - - case 0x17: // Introduction date - buf.ReadDWord(); - break; - - case 0x1E: // Badge list - SkipBadgeList(buf); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -/** - * Define properties for roadtypes - * @param first Local ID of the first roadtype. - * @param last Local ID of the last roadtype. - * @param prop The property to change. - * @param buf The property value. - * @param rtt Road/tram type. - * @return ChangeInfoResult. - */ -static ChangeInfoResult RoadTypeChangeInfo(uint first, uint last, int prop, ByteReader &buf, RoadTramType rtt) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - extern RoadTypeInfo _roadtypes[ROADTYPE_END]; - std::array &type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map; - - if (last > ROADTYPE_END) { - GrfMsg(1, "RoadTypeChangeInfo: Road type {} is invalid, max {}, ignoring", last, ROADTYPE_END); - return CIR_INVALID_ID; - } - - for (uint id = first; id < last; ++id) { - RoadType rt = type_map[id]; - if (rt == INVALID_ROADTYPE) return CIR_INVALID_ID; - - RoadTypeInfo *rti = &_roadtypes[rt]; - - switch (prop) { - case 0x08: // Label of road type - /* Skipped here as this is loaded during reservation stage. */ - buf.ReadDWord(); - break; - - case 0x09: // Toolbar caption of roadtype - AddStringForMapping(GRFStringID{buf.ReadWord()}, &rti->strings.toolbar_caption); - break; - - case 0x0A: // Menu text of roadtype - AddStringForMapping(GRFStringID{buf.ReadWord()}, &rti->strings.menu_text); - break; - - case 0x0B: // Build window caption - AddStringForMapping(GRFStringID{buf.ReadWord()}, &rti->strings.build_caption); - break; - - case 0x0C: // Autoreplace text - AddStringForMapping(GRFStringID{buf.ReadWord()}, &rti->strings.replace_text); - break; - - case 0x0D: // New engine text - AddStringForMapping(GRFStringID{buf.ReadWord()}, &rti->strings.new_engine); - break; - - case 0x0F: // Powered roadtype list - case 0x18: // Roadtype list required for date introduction - case 0x19: { // Introduced roadtype list - /* Road type compatibility bits are added to the existing bits - * to allow multiple GRFs to modify compatibility with the - * default road types. */ - int n = buf.ReadByte(); - for (int j = 0; j != n; j++) { - RoadTypeLabel label = buf.ReadDWord(); - RoadType resolved_rt = GetRoadTypeByLabel(std::byteswap(label), false); - if (resolved_rt != INVALID_ROADTYPE) { - switch (prop) { - case 0x0F: - if (GetRoadTramType(resolved_rt) == rtt) { - SetBit(rti->powered_roadtypes, resolved_rt); - } else { - GrfMsg(1, "RoadTypeChangeInfo: Powered road type list: Road type {} road/tram type does not match road type {}, ignoring", resolved_rt, rt); - } - break; - case 0x18: SetBit(rti->introduction_required_roadtypes, resolved_rt); break; - case 0x19: SetBit(rti->introduces_roadtypes, resolved_rt); break; - } - } - } - break; - } - - case 0x10: // Road Type flags - rti->flags = static_cast(buf.ReadByte()); - break; - - case 0x13: // Construction cost factor - rti->cost_multiplier = buf.ReadWord(); - break; - - case 0x14: // Speed limit - rti->max_speed = buf.ReadWord(); - break; - - case 0x16: // Map colour - rti->map_colour = buf.ReadByte(); - break; - - case 0x17: // Introduction date - rti->introduction_date = TimerGameCalendar::Date(buf.ReadDWord()); - break; - - case 0x1A: // Sort order - rti->sorting_order = buf.ReadByte(); - break; - - case 0x1B: // Name of roadtype - AddStringForMapping(GRFStringID{buf.ReadWord()}, &rti->strings.name); - break; - - case 0x1C: // Maintenance cost factor - rti->maintenance_multiplier = buf.ReadWord(); - break; - - case 0x1D: // Alternate road type label list - /* Skipped here as this is loaded during reservation stage. */ - for (int j = buf.ReadByte(); j != 0; j--) buf.ReadDWord(); - break; - - case 0x1E: // Badge list - rti->badges = ReadBadgeList(buf, GSF_ROADTYPES); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -static ChangeInfoResult RoadTypeChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - return RoadTypeChangeInfo(first, last, prop, buf, RTT_ROAD); -} - -static ChangeInfoResult TramTypeChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - return RoadTypeChangeInfo(first, last, prop, buf, RTT_TRAM); -} - - -static ChangeInfoResult RoadTypeReserveInfo(uint first, uint last, int prop, ByteReader &buf, RoadTramType rtt) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - extern RoadTypeInfo _roadtypes[ROADTYPE_END]; - std::array &type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map; - - if (last > ROADTYPE_END) { - GrfMsg(1, "RoadTypeReserveInfo: Road type {} is invalid, max {}, ignoring", last, ROADTYPE_END); - return CIR_INVALID_ID; - } - - for (uint id = first; id < last; ++id) { - switch (prop) { - case 0x08: { // Label of road type - RoadTypeLabel rtl = buf.ReadDWord(); - rtl = std::byteswap(rtl); - - RoadType rt = GetRoadTypeByLabel(rtl, false); - if (rt == INVALID_ROADTYPE) { - /* Set up new road type */ - rt = AllocateRoadType(rtl, rtt); - } else if (GetRoadTramType(rt) != rtt) { - GrfMsg(1, "RoadTypeReserveInfo: Road type {} is invalid type (road/tram), ignoring", id); - return CIR_INVALID_ID; - } - - type_map[id] = rt; - break; - } - case 0x09: // Toolbar caption of roadtype - case 0x0A: // Menu text - case 0x0B: // Build window caption - case 0x0C: // Autoreplace text - case 0x0D: // New loco - case 0x13: // Construction cost - case 0x14: // Speed limit - case 0x1B: // Name of roadtype - case 0x1C: // Maintenance cost factor - buf.ReadWord(); - break; - - case 0x1D: // Alternate road type label list - if (type_map[id] != INVALID_ROADTYPE) { - int n = buf.ReadByte(); - for (int j = 0; j != n; j++) { - _roadtypes[type_map[id]].alternate_labels.push_back(std::byteswap(buf.ReadDWord())); - } - break; - } - GrfMsg(1, "RoadTypeReserveInfo: Ignoring property 1D for road type {} because no label was set", id); - /* FALL THROUGH */ - - case 0x0F: // Powered roadtype list - case 0x18: // Roadtype list required for date introduction - case 0x19: // Introduced roadtype list - for (int j = buf.ReadByte(); j != 0; j--) buf.ReadDWord(); - break; - - case 0x10: // Road Type flags - case 0x16: // Map colour - case 0x1A: // Sort order - buf.ReadByte(); - break; - - case 0x17: // Introduction date - buf.ReadDWord(); - break; - - case 0x1E: // Badge list - SkipBadgeList(buf); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -static ChangeInfoResult RoadTypeReserveInfo(uint first, uint last, int prop, ByteReader &buf) -{ - return RoadTypeReserveInfo(first, last, prop, buf, RTT_ROAD); -} - -static ChangeInfoResult TramTypeReserveInfo(uint first, uint last, int prop, ByteReader &buf) -{ - return RoadTypeReserveInfo(first, last, prop, buf, RTT_TRAM); -} - -static ChangeInfoResult AirportTilesChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - if (last > NUM_AIRPORTTILES_PER_GRF) { - GrfMsg(1, "AirportTileChangeInfo: Too many airport tiles loaded ({}), max ({}). Ignoring.", last, NUM_AIRPORTTILES_PER_GRF); - return CIR_INVALID_ID; - } - - /* Allocate airport tile specs if they haven't been allocated already. */ - if (_cur.grffile->airtspec.size() < last) _cur.grffile->airtspec.resize(last); - - for (uint id = first; id < last; ++id) { - auto &tsp = _cur.grffile->airtspec[id]; - - if (prop != 0x08 && tsp == nullptr) { - GrfMsg(2, "AirportTileChangeInfo: Attempt to modify undefined airport tile {}. Ignoring.", id); - return CIR_INVALID_ID; - } - - switch (prop) { - case 0x08: { // Substitute airport tile type - uint8_t subs_id = buf.ReadByte(); - if (subs_id >= NEW_AIRPORTTILE_OFFSET) { - /* The substitute id must be one of the original airport tiles. */ - GrfMsg(2, "AirportTileChangeInfo: Attempt to use new airport tile {} as substitute airport tile for {}. Ignoring.", subs_id, id); - continue; - } - - /* Allocate space for this airport tile. */ - if (tsp == nullptr) { - tsp = std::make_unique(*AirportTileSpec::Get(subs_id)); - - tsp->enabled = true; - - tsp->animation.status = ANIM_STATUS_NO_ANIMATION; - - tsp->grf_prop.local_id = id; - tsp->grf_prop.subst_id = subs_id; - tsp->grf_prop.SetGRFFile(_cur.grffile); - _airporttile_mngr.AddEntityID(id, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot - } - break; - } - - case 0x09: { // Airport tile override - uint8_t override = buf.ReadByte(); - - /* The airport tile being overridden must be an original airport tile. */ - if (override >= NEW_AIRPORTTILE_OFFSET) { - GrfMsg(2, "AirportTileChangeInfo: Attempt to override new airport tile {} with airport tile id {}. Ignoring.", override, id); - continue; - } - - _airporttile_mngr.Add(id, _cur.grffile->grfid, override); - break; - } - - case 0x0E: // Callback mask - tsp->callback_mask = static_cast(buf.ReadByte()); - break; - - case 0x0F: // Animation information - tsp->animation.frames = buf.ReadByte(); - tsp->animation.status = buf.ReadByte(); - break; - - case 0x10: // Animation speed - tsp->animation.speed = buf.ReadByte(); - break; - - case 0x11: // Animation triggers - tsp->animation.triggers = buf.ReadByte(); - break; - - case 0x12: // Badge list - tsp->badges = ReadBadgeList(buf, GSF_TRAMTYPES); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -/** - * Ignore properties for roadstops - * @param prop The property to ignore. - * @param buf The property value. - * @return ChangeInfoResult. - */ -static ChangeInfoResult IgnoreRoadStopProperty(uint prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - switch (prop) { - case 0x09: - case 0x0C: - case 0x0F: - case 0x11: - buf.ReadByte(); - break; - - case 0x0A: - case 0x0B: - case 0x0E: - case 0x10: - case 0x15: - buf.ReadWord(); - break; - - case 0x08: - case 0x0D: - case 0x12: - buf.ReadDWord(); - break; - - case 0x16: // Badge list - SkipBadgeList(buf); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - - return ret; -} - -static ChangeInfoResult BadgeChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - if (last >= UINT16_MAX) { - GrfMsg(1, "BadgeChangeInfo: Tag {} is invalid, max {}, ignoring", last, UINT16_MAX - 1); - return CIR_INVALID_ID; - } - - for (uint id = first; id < last; ++id) { - auto it = _cur.grffile->badge_map.find(id); - if (prop != 0x08 && it == std::end(_cur.grffile->badge_map)) { - GrfMsg(1, "BadgeChangeInfo: Attempt to modify undefined tag {}, ignoring", id); - return CIR_INVALID_ID; - } - - Badge *badge = nullptr; - if (prop != 0x08) badge = GetBadge(it->second); - - switch (prop) { - case 0x08: { // Label - std::string_view label = buf.ReadString(); - _cur.grffile->badge_map[id] = GetOrCreateBadge(label).index; - break; - } - - case 0x09: // Flags - badge->flags = static_cast(buf.ReadDWord()); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -static ChangeInfoResult RoadStopChangeInfo(uint first, uint last, int prop, ByteReader &buf) -{ - ChangeInfoResult ret = CIR_SUCCESS; - - if (last > NUM_ROADSTOPS_PER_GRF) { - GrfMsg(1, "RoadStopChangeInfo: RoadStop {} is invalid, max {}, ignoring", last, NUM_ROADSTOPS_PER_GRF); - return CIR_INVALID_ID; - } - - if (_cur.grffile->roadstops.size() < last) _cur.grffile->roadstops.resize(last); - - for (uint id = first; id < last; ++id) { - auto &rs = _cur.grffile->roadstops[id]; - - if (rs == nullptr && prop != 0x08) { - GrfMsg(1, "RoadStopChangeInfo: Attempt to modify undefined road stop {}, ignoring", id); - ChangeInfoResult cir = IgnoreRoadStopProperty(prop, buf); - if (cir > ret) ret = cir; - continue; - } - - switch (prop) { - case 0x08: { // Road Stop Class ID - if (rs == nullptr) { - rs = std::make_unique(); - } - - uint32_t classid = buf.ReadDWord(); - rs->class_index = RoadStopClass::Allocate(std::byteswap(classid)); - break; - } - - case 0x09: // Road stop type - rs->stop_type = (RoadStopAvailabilityType)buf.ReadByte(); - break; - - case 0x0A: // Road Stop Name - AddStringForMapping(GRFStringID{buf.ReadWord()}, &rs->name); - break; - - case 0x0B: // Road Stop Class name - AddStringForMapping(GRFStringID{buf.ReadWord()}, [rs = rs.get()](StringID str) { RoadStopClass::Get(rs->class_index)->name = str; }); - break; - - case 0x0C: // The draw mode - rs->draw_mode = static_cast(buf.ReadByte()); - break; - - case 0x0D: // Cargo types for random triggers - rs->cargo_triggers = TranslateRefitMask(buf.ReadDWord()); - break; - - case 0x0E: // Animation info - rs->animation.frames = buf.ReadByte(); - rs->animation.status = buf.ReadByte(); - break; - - case 0x0F: // Animation speed - rs->animation.speed = buf.ReadByte(); - break; - - case 0x10: // Animation triggers - rs->animation.triggers = buf.ReadWord(); - break; - - case 0x11: // Callback mask - rs->callback_mask = static_cast(buf.ReadByte()); - break; - - case 0x12: // General flags - rs->flags = static_cast(buf.ReadDWord()); // Future-proofing, size this as 4 bytes, but we only need two byte's worth of flags at present - break; - - case 0x15: // Cost multipliers - rs->build_cost_multiplier = buf.ReadByte(); - rs->clear_cost_multiplier = buf.ReadByte(); - break; - - case 0x16: // Badge list - rs->badges = ReadBadgeList(buf, GSF_ROADSTOPS); - break; - - default: - ret = CIR_UNKNOWN; - break; - } - } - - return ret; -} - -static bool HandleChangeInfoResult(const char *caller, ChangeInfoResult cir, uint8_t feature, uint8_t property) -{ - switch (cir) { - default: NOT_REACHED(); - - case CIR_DISABLED: - /* Error has already been printed; just stop parsing */ - return true; - - case CIR_SUCCESS: - return false; - - case CIR_UNHANDLED: - GrfMsg(1, "{}: Ignoring property 0x{:02X} of feature 0x{:02X} (not implemented)", caller, property, feature); - return false; - - case CIR_UNKNOWN: - GrfMsg(0, "{}: Unknown property 0x{:02X} of feature 0x{:02X}, disabling", caller, property, feature); - [[fallthrough]]; - - case CIR_INVALID_ID: { - /* No debug message for an invalid ID, as it has already been output */ - GRFError *error = DisableGrf(cir == CIR_INVALID_ID ? STR_NEWGRF_ERROR_INVALID_ID : STR_NEWGRF_ERROR_UNKNOWN_PROPERTY); - if (cir != CIR_INVALID_ID) error->param_value[1] = property; - return true; - } - } -} - -/* Action 0x00 */ -static void FeatureChangeInfo(ByteReader &buf) -{ - /* <00> ()... - * - * B feature - * B num-props how many properties to change per vehicle/station - * B num-info how many vehicles/stations to change - * E id ID of first vehicle/station to change, if num-info is - * greater than one, this one and the following - * vehicles/stations will be changed - * B property what property to change, depends on the feature - * V new-info new bytes of info (variable size; depends on properties) */ - - static ChangeInfoHandler * const handler[] = { - /* GSF_TRAINS */ RailVehicleChangeInfo, - /* GSF_ROADVEHICLES */ RoadVehicleChangeInfo, - /* GSF_SHIPS */ ShipVehicleChangeInfo, - /* GSF_AIRCRAFT */ AircraftVehicleChangeInfo, - /* GSF_STATIONS */ StationChangeInfo, - /* GSF_CANALS */ CanalChangeInfo, - /* GSF_BRIDGES */ BridgeChangeInfo, - /* GSF_HOUSES */ TownHouseChangeInfo, - /* GSF_GLOBALVAR */ GlobalVarChangeInfo, - /* GSF_INDUSTRYTILES */ IndustrytilesChangeInfo, - /* GSF_INDUSTRIES */ IndustriesChangeInfo, - /* GSF_CARGOES */ nullptr, // Cargo is handled during reservation - /* GSF_SOUNDFX */ SoundEffectChangeInfo, - /* GSF_AIRPORTS */ AirportChangeInfo, - /* GSF_SIGNALS */ nullptr, - /* GSF_OBJECTS */ ObjectChangeInfo, - /* GSF_RAILTYPES */ RailTypeChangeInfo, - /* GSF_AIRPORTTILES */ AirportTilesChangeInfo, - /* GSF_ROADTYPES */ RoadTypeChangeInfo, - /* GSF_TRAMTYPES */ TramTypeChangeInfo, - /* GSF_ROADSTOPS */ RoadStopChangeInfo, - /* GSF_BADGES */ BadgeChangeInfo, - }; - static_assert(GSF_END == std::size(handler)); - - uint8_t feature = buf.ReadByte(); - uint8_t numprops = buf.ReadByte(); - uint numinfo = buf.ReadByte(); - uint engine = buf.ReadExtendedByte(); - - if (feature >= GSF_END) { - GrfMsg(1, "FeatureChangeInfo: Unsupported feature 0x{:02X}, skipping", feature); - return; - } - - GrfMsg(6, "FeatureChangeInfo: Feature 0x{:02X}, {} properties, to apply to {}+{}", - feature, numprops, engine, numinfo); - - if (handler[feature] == nullptr) { - if (feature != GSF_CARGOES) GrfMsg(1, "FeatureChangeInfo: Unsupported feature 0x{:02X}, skipping", feature); - return; - } - - /* Mark the feature as used by the grf */ - SetBit(_cur.grffile->grf_features, feature); - - while (numprops-- && buf.HasData()) { - uint8_t prop = buf.ReadByte(); - - ChangeInfoResult cir = handler[feature](engine, engine + numinfo, prop, buf); - if (HandleChangeInfoResult("FeatureChangeInfo", cir, feature, prop)) return; - } -} - -/* Action 0x00 (GLS_SAFETYSCAN) */ -static void SafeChangeInfo(ByteReader &buf) -{ - uint8_t feature = buf.ReadByte(); - uint8_t numprops = buf.ReadByte(); - uint numinfo = buf.ReadByte(); - buf.ReadExtendedByte(); // id - - if (feature == GSF_BRIDGES && numprops == 1) { - uint8_t prop = buf.ReadByte(); - /* Bridge property 0x0D is redefinition of sprite layout tables, which - * is considered safe. */ - if (prop == 0x0D) return; - } else if (feature == GSF_GLOBALVAR && numprops == 1) { - uint8_t prop = buf.ReadByte(); - /* Engine ID Mappings are safe, if the source is static */ - if (prop == 0x11) { - bool is_safe = true; - for (uint i = 0; i < numinfo; i++) { - uint32_t s = buf.ReadDWord(); - buf.ReadDWord(); // dest - const GRFConfig *grfconfig = GetGRFConfig(s); - if (grfconfig != nullptr && !grfconfig->flags.Test(GRFConfigFlag::Static)) { - is_safe = false; - break; - } - } - if (is_safe) return; - } - } - - _cur.grfconfig->flags.Set(GRFConfigFlag::Unsafe); - - /* Skip remainder of GRF */ - _cur.skip_sprites = -1; -} - -/* Action 0x00 (GLS_RESERVE) */ -static void ReserveChangeInfo(ByteReader &buf) -{ - uint8_t feature = buf.ReadByte(); - - if (feature != GSF_CARGOES && feature != GSF_GLOBALVAR && feature != GSF_RAILTYPES && feature != GSF_ROADTYPES && feature != GSF_TRAMTYPES) return; - - uint8_t numprops = buf.ReadByte(); - uint8_t numinfo = buf.ReadByte(); - uint16_t index = buf.ReadExtendedByte(); - - while (numprops-- && buf.HasData()) { - uint8_t prop = buf.ReadByte(); - ChangeInfoResult cir = CIR_SUCCESS; - - switch (feature) { - default: NOT_REACHED(); - case GSF_CARGOES: - cir = CargoChangeInfo(index, index + numinfo, prop, buf); - break; - - case GSF_GLOBALVAR: - cir = GlobalVarReserveInfo(index, index + numinfo, prop, buf); - break; - - case GSF_RAILTYPES: - cir = RailTypeReserveInfo(index, index + numinfo, prop, buf); - break; - - case GSF_ROADTYPES: - cir = RoadTypeReserveInfo(index, index + numinfo, prop, buf); - break; - - case GSF_TRAMTYPES: - cir = TramTypeReserveInfo(index, index + numinfo, prop, buf); - break; - } - - if (HandleChangeInfoResult("ReserveChangeInfo", cir, feature, prop)) return; - } -} - -/* Action 0x01 */ -static void NewSpriteSet(ByteReader &buf) -{ - /* Basic format: <01> - * Extended format: <01> 00 - * - * B feature feature to define sprites for - * 0, 1, 2, 3: veh-type, 4: train stations - * E first-set first sprite set to define - * B num-sets number of sprite sets (extended byte in extended format) - * E num-ent how many entries per sprite set - * For vehicles, this is the number of different - * vehicle directions in each sprite set - * Set num-dirs=8, unless your sprites are symmetric. - * In that case, use num-dirs=4. - */ - - uint8_t feature = buf.ReadByte(); - uint16_t num_sets = buf.ReadByte(); - uint16_t first_set = 0; - - if (num_sets == 0 && buf.HasData(3)) { - /* Extended Action1 format. - * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */ - first_set = buf.ReadExtendedByte(); - num_sets = buf.ReadExtendedByte(); - } - uint16_t num_ents = buf.ReadExtendedByte(); - - if (feature >= GSF_END) { - _cur.skip_sprites = num_sets * num_ents; - GrfMsg(1, "NewSpriteSet: Unsupported feature 0x{:02X}, skipping {} sprites", feature, _cur.skip_sprites); - return; - } - - _cur.AddSpriteSets(feature, _cur.spriteid, first_set, num_sets, num_ents); - - GrfMsg(7, "New sprite set at {} of feature 0x{:02X}, consisting of {} sets with {} views each (total {})", - _cur.spriteid, feature, num_sets, num_ents, num_sets * num_ents - ); - - for (int i = 0; i < num_sets * num_ents; i++) { - _cur.nfo_line++; - LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line); - } -} - -/* Action 0x01 (SKIP) */ -static void SkipAct1(ByteReader &buf) -{ - buf.ReadByte(); - uint16_t num_sets = buf.ReadByte(); - - if (num_sets == 0 && buf.HasData(3)) { - /* Extended Action1 format. - * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */ - buf.ReadExtendedByte(); // first_set - num_sets = buf.ReadExtendedByte(); - } - uint16_t num_ents = buf.ReadExtendedByte(); - - _cur.skip_sprites = num_sets * num_ents; - - GrfMsg(3, "SkipAct1: Skipping {} sprites", _cur.skip_sprites); -} - -using CachedCallback = std::pair; -static std::vector _cached_callback_groups; ///< Sorted list of cached callback result spritegroups. - -static const SpriteGroup *GetCallbackResultGroup(uint16_t value) -{ - /* Old style callback results (only valid for version < 8) have the highest byte 0xFF to signify it is a callback result. - * New style ones only have the highest bit set (allows 15-bit results, instead of just 8) */ - if (_cur.grffile->grf_version < 8 && GB(value, 8, 8) == 0xFF) { - value &= ~0xFF00; - } else { - value &= ~0x8000; - } - - /* Find position for value within the cached callback list. */ - auto it = std::ranges::lower_bound(_cached_callback_groups, value, std::less{}, &CachedCallback::first); - if (it != std::end(_cached_callback_groups) && it->first == value) return SpriteGroup::Get(it->second); - - /* Result value is not present, so make it and add to cache. */ - assert(CallbackResultSpriteGroup::CanAllocateItem()); - const SpriteGroup *group = new CallbackResultSpriteGroup(value); - it = _cached_callback_groups.emplace(it, value, group->index); - return group; -} - -/* Helper function to either create a callback or link to a previously - * defined spritegroup. */ -static const SpriteGroup *GetGroupFromGroupID(uint8_t setid, uint8_t type, uint16_t groupid) -{ - if (HasBit(groupid, 15)) return GetCallbackResultGroup(groupid); - - if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) { - GrfMsg(1, "GetGroupFromGroupID(0x{:02X}:0x{:02X}): Groupid 0x{:04X} does not exist, leaving empty", setid, type, groupid); - return nullptr; - } - - return _cur.spritegroups[groupid]; -} - -/** - * Helper function to either create a callback or a result sprite group. - * @param feature GrfSpecFeature to define spritegroup for. - * @param setid SetID of the currently being parsed Action2. (only for debug output) - * @param type Type of the currently being parsed Action2. (only for debug output) - * @param spriteid Raw value from the GRF for the new spritegroup; describes either the return value or the referenced spritegroup. - * @return Created spritegroup. - */ -static const SpriteGroup *CreateGroupFromGroupID(uint8_t feature, uint8_t setid, uint8_t type, uint16_t spriteid) -{ - if (HasBit(spriteid, 15)) return GetCallbackResultGroup(spriteid); - - if (!_cur.IsValidSpriteSet(feature, spriteid)) { - GrfMsg(1, "CreateGroupFromGroupID(0x{:02X}:0x{:02X}): Sprite set {} invalid", setid, type, spriteid); - return nullptr; - } - - SpriteID spriteset_start = _cur.GetSprite(feature, spriteid); - uint num_sprites = _cur.GetNumEnts(feature, spriteid); - - /* Ensure that the sprites are loeded */ - assert(spriteset_start + num_sprites <= _cur.spriteid); - - assert(ResultSpriteGroup::CanAllocateItem()); - return new ResultSpriteGroup(spriteset_start, num_sprites); -} - -/* Action 0x02 */ -static void NewSpriteGroup(ByteReader &buf) -{ - /* <02> - * - * B feature see action 1 - * B set-id ID of this particular definition - * B type/num-entries - * if 80 or greater, this is a randomized or variational - * list definition, see below - * otherwise it specifies a number of entries, the exact - * meaning depends on the feature - * V feature-specific-data (huge mess, don't even look it up --pasky) */ - const SpriteGroup *act_group = nullptr; - - uint8_t feature = buf.ReadByte(); - if (feature >= GSF_END) { - GrfMsg(1, "NewSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature); - return; - } - - uint8_t setid = buf.ReadByte(); - uint8_t type = buf.ReadByte(); - - /* Sprite Groups are created here but they are allocated from a pool, so - * we do not need to delete anything if there is an exception from the - * ByteReader. */ - - switch (type) { - /* Deterministic Sprite Group */ - case 0x81: // Self scope, byte - case 0x82: // Parent scope, byte - case 0x85: // Self scope, word - case 0x86: // Parent scope, word - case 0x89: // Self scope, dword - case 0x8A: // Parent scope, dword - { - uint8_t varadjust; - uint8_t varsize; - - assert(DeterministicSpriteGroup::CanAllocateItem()); - DeterministicSpriteGroup *group = new DeterministicSpriteGroup(); - group->nfo_line = _cur.nfo_line; - act_group = group; - group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF; - - switch (GB(type, 2, 2)) { - default: NOT_REACHED(); - case 0: group->size = DSG_SIZE_BYTE; varsize = 1; break; - case 1: group->size = DSG_SIZE_WORD; varsize = 2; break; - case 2: group->size = DSG_SIZE_DWORD; varsize = 4; break; - } - - /* Loop through the var adjusts. Unfortunately we don't know how many we have - * from the outset, so we shall have to keep reallocing. */ - do { - DeterministicSpriteGroupAdjust &adjust = group->adjusts.emplace_back(); - - /* The first var adjust doesn't have an operation specified, so we set it to add. */ - adjust.operation = group->adjusts.size() == 1 ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)buf.ReadByte(); - adjust.variable = buf.ReadByte(); - if (adjust.variable == 0x7E) { - /* Link subroutine group */ - adjust.subroutine = GetGroupFromGroupID(setid, type, buf.ReadByte()); - } else { - adjust.parameter = IsInsideMM(adjust.variable, 0x60, 0x80) ? buf.ReadByte() : 0; - } - - varadjust = buf.ReadByte(); - adjust.shift_num = GB(varadjust, 0, 5); - adjust.type = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2); - adjust.and_mask = buf.ReadVarSize(varsize); - - if (adjust.type != DSGA_TYPE_NONE) { - adjust.add_val = buf.ReadVarSize(varsize); - adjust.divmod_val = buf.ReadVarSize(varsize); - if (adjust.divmod_val == 0) adjust.divmod_val = 1; // Ensure that divide by zero cannot occur - } else { - adjust.add_val = 0; - adjust.divmod_val = 0; - } - - /* Continue reading var adjusts while bit 5 is set. */ - } while (HasBit(varadjust, 5)); - - std::vector ranges; - ranges.resize(buf.ReadByte()); - for (auto &range : ranges) { - range.group = GetGroupFromGroupID(setid, type, buf.ReadWord()); - range.low = buf.ReadVarSize(varsize); - range.high = buf.ReadVarSize(varsize); - } - - group->default_group = GetGroupFromGroupID(setid, type, buf.ReadWord()); - group->error_group = ranges.empty() ? group->default_group : ranges[0].group; - /* nvar == 0 is a special case -- we turn our value into a callback result */ - group->calculated_result = ranges.empty(); - - /* Sort ranges ascending. When ranges overlap, this may required clamping or splitting them */ - std::vector bounds; - bounds.reserve(ranges.size()); - for (const auto &range : ranges) { - bounds.push_back(range.low); - if (range.high != UINT32_MAX) bounds.push_back(range.high + 1); - } - std::sort(bounds.begin(), bounds.end()); - bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end()); - - std::vector target; - target.reserve(bounds.size()); - for (const auto &bound : bounds) { - const SpriteGroup *t = group->default_group; - for (const auto &range : ranges) { - if (range.low <= bound && bound <= range.high) { - t = range.group; - break; - } - } - target.push_back(t); - } - assert(target.size() == bounds.size()); - - for (uint j = 0; j < bounds.size(); ) { - if (target[j] != group->default_group) { - DeterministicSpriteGroupRange &r = group->ranges.emplace_back(); - r.group = target[j]; - r.low = bounds[j]; - while (j < bounds.size() && target[j] == r.group) { - j++; - } - r.high = j < bounds.size() ? bounds[j] - 1 : UINT32_MAX; - } else { - j++; - } - } - - break; - } - - /* Randomized Sprite Group */ - case 0x80: // Self scope - case 0x83: // Parent scope - case 0x84: // Relative scope - { - assert(RandomizedSpriteGroup::CanAllocateItem()); - RandomizedSpriteGroup *group = new RandomizedSpriteGroup(); - group->nfo_line = _cur.nfo_line; - act_group = group; - group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF; - - if (HasBit(type, 2)) { - if (feature <= GSF_AIRCRAFT) group->var_scope = VSG_SCOPE_RELATIVE; - group->count = buf.ReadByte(); - } - - uint8_t triggers = buf.ReadByte(); - group->triggers = GB(triggers, 0, 7); - group->cmp_mode = HasBit(triggers, 7) ? RSG_CMP_ALL : RSG_CMP_ANY; - group->lowest_randbit = buf.ReadByte(); - - uint8_t num_groups = buf.ReadByte(); - if (!HasExactlyOneBit(num_groups)) { - GrfMsg(1, "NewSpriteGroup: Random Action 2 nrand should be power of 2"); - } - - group->groups.reserve(num_groups); - for (uint i = 0; i < num_groups; i++) { - group->groups.push_back(GetGroupFromGroupID(setid, type, buf.ReadWord())); - } - - break; - } - - /* Neither a variable or randomized sprite group... must be a real group */ - default: - { - switch (feature) { - case GSF_TRAINS: - case GSF_ROADVEHICLES: - case GSF_SHIPS: - case GSF_AIRCRAFT: - case GSF_STATIONS: - case GSF_CANALS: - case GSF_CARGOES: - case GSF_AIRPORTS: - case GSF_RAILTYPES: - case GSF_ROADTYPES: - case GSF_TRAMTYPES: - case GSF_BADGES: - { - uint8_t num_loaded = type; - uint8_t num_loading = buf.ReadByte(); - - if (!_cur.HasValidSpriteSets(feature)) { - GrfMsg(0, "NewSpriteGroup: No sprite set to work on! Skipping"); - return; - } - - GrfMsg(6, "NewSpriteGroup: New SpriteGroup 0x{:02X}, {} loaded, {} loading", - setid, num_loaded, num_loading); - - if (num_loaded + num_loading == 0) { - GrfMsg(1, "NewSpriteGroup: no result, skipping invalid RealSpriteGroup"); - break; - } - - if (num_loaded + num_loading == 1) { - /* Avoid creating 'Real' sprite group if only one option. */ - uint16_t spriteid = buf.ReadWord(); - act_group = CreateGroupFromGroupID(feature, setid, type, spriteid); - GrfMsg(8, "NewSpriteGroup: one result, skipping RealSpriteGroup = subset {}", spriteid); - break; - } - - std::vector loaded; - std::vector loading; - - loaded.reserve(num_loaded); - for (uint i = 0; i < num_loaded; i++) { - loaded.push_back(buf.ReadWord()); - GrfMsg(8, "NewSpriteGroup: + rg->loaded[{}] = subset {}", i, loaded[i]); - } - - loading.reserve(num_loading); - for (uint i = 0; i < num_loading; i++) { - loading.push_back(buf.ReadWord()); - GrfMsg(8, "NewSpriteGroup: + rg->loading[{}] = subset {}", i, loading[i]); - } - - bool loaded_same = !loaded.empty() && std::adjacent_find(loaded.begin(), loaded.end(), std::not_equal_to<>()) == loaded.end(); - bool loading_same = !loading.empty() && std::adjacent_find(loading.begin(), loading.end(), std::not_equal_to<>()) == loading.end(); - if (loaded_same && loading_same && loaded[0] == loading[0]) { - /* Both lists only contain the same value, so don't create 'Real' sprite group */ - act_group = CreateGroupFromGroupID(feature, setid, type, loaded[0]); - GrfMsg(8, "NewSpriteGroup: same result, skipping RealSpriteGroup = subset {}", loaded[0]); - break; - } - - assert(RealSpriteGroup::CanAllocateItem()); - RealSpriteGroup *group = new RealSpriteGroup(); - group->nfo_line = _cur.nfo_line; - act_group = group; - - if (loaded_same && loaded.size() > 1) loaded.resize(1); - group->loaded.reserve(loaded.size()); - for (uint16_t spriteid : loaded) { - const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid); - group->loaded.push_back(t); - } - - if (loading_same && loading.size() > 1) loading.resize(1); - group->loading.reserve(loading.size()); - for (uint16_t spriteid : loading) { - const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid); - group->loading.push_back(t); - } - - break; - } - - case GSF_HOUSES: - case GSF_AIRPORTTILES: - case GSF_OBJECTS: - case GSF_INDUSTRYTILES: - case GSF_ROADSTOPS: { - uint8_t num_building_sprites = std::max((uint8_t)1, type); - - assert(TileLayoutSpriteGroup::CanAllocateItem()); - TileLayoutSpriteGroup *group = new TileLayoutSpriteGroup(); - group->nfo_line = _cur.nfo_line; - act_group = group; - - /* On error, bail out immediately. Temporary GRF data was already freed */ - if (ReadSpriteLayout(buf, num_building_sprites, true, feature, false, type == 0, &group->dts)) return; - break; - } - - case GSF_INDUSTRIES: { - if (type > 2) { - GrfMsg(1, "NewSpriteGroup: Unsupported industry production version {}, skipping", type); - break; - } - - assert(IndustryProductionSpriteGroup::CanAllocateItem()); - IndustryProductionSpriteGroup *group = new IndustryProductionSpriteGroup(); - group->nfo_line = _cur.nfo_line; - act_group = group; - group->version = type; - if (type == 0) { - group->num_input = INDUSTRY_ORIGINAL_NUM_INPUTS; - for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_INPUTS; i++) { - group->subtract_input[i] = (int16_t)buf.ReadWord(); // signed - } - group->num_output = INDUSTRY_ORIGINAL_NUM_OUTPUTS; - for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_OUTPUTS; i++) { - group->add_output[i] = buf.ReadWord(); // unsigned - } - group->again = buf.ReadByte(); - } else if (type == 1) { - group->num_input = INDUSTRY_ORIGINAL_NUM_INPUTS; - for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_INPUTS; i++) { - group->subtract_input[i] = buf.ReadByte(); - } - group->num_output = INDUSTRY_ORIGINAL_NUM_OUTPUTS; - for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_OUTPUTS; i++) { - group->add_output[i] = buf.ReadByte(); - } - group->again = buf.ReadByte(); - } else if (type == 2) { - group->num_input = buf.ReadByte(); - if (group->num_input > std::size(group->subtract_input)) { - GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK); - error->data = "too many inputs (max 16)"; - return; - } - for (uint i = 0; i < group->num_input; i++) { - uint8_t rawcargo = buf.ReadByte(); - CargoType cargo = GetCargoTranslation(rawcargo, _cur.grffile); - if (!IsValidCargoType(cargo)) { - /* The mapped cargo is invalid. This is permitted at this point, - * as long as the result is not used. Mark it invalid so this - * can be tested later. */ - group->version = 0xFF; - } else if (auto v = group->cargo_input | std::views::take(i); std::ranges::find(v, cargo) != v.end()) { - GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK); - error->data = "duplicate input cargo"; - return; - } - group->cargo_input[i] = cargo; - group->subtract_input[i] = buf.ReadByte(); - } - group->num_output = buf.ReadByte(); - if (group->num_output > std::size(group->add_output)) { - GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK); - error->data = "too many outputs (max 16)"; - return; - } - for (uint i = 0; i < group->num_output; i++) { - uint8_t rawcargo = buf.ReadByte(); - CargoType cargo = GetCargoTranslation(rawcargo, _cur.grffile); - if (!IsValidCargoType(cargo)) { - /* Mark this result as invalid to use */ - group->version = 0xFF; - } else if (auto v = group->cargo_output | std::views::take(i); std::ranges::find(v, cargo) != v.end()) { - GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK); - error->data = "duplicate output cargo"; - return; - } - group->cargo_output[i] = cargo; - group->add_output[i] = buf.ReadByte(); - } - group->again = buf.ReadByte(); - } else { - NOT_REACHED(); - } - break; - } - - /* Loading of Tile Layout and Production Callback groups would happen here */ - default: GrfMsg(1, "NewSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature); - } - } - } - - _cur.spritegroups[setid] = act_group; -} - -/** - * Get the cargo translation table to use for the given GRF file. - * @param grffile GRF file. - * @returns Readonly cargo translation table to use. - */ -std::span GetCargoTranslationTable(const GRFFile &grffile) -{ - /* Always use the translation table if it's installed. */ - if (!grffile.cargo_list.empty()) return grffile.cargo_list; - - /* Pre-v7 use climate-dependent "slot" table. */ - if (grffile.grf_version < 7) return GetClimateDependentCargoTranslationTable(); - - /* Otherwise use climate-independent "bitnum" table. */ - return GetClimateIndependentCargoTranslationTable(); -} - -static CargoType TranslateCargo(uint8_t feature, uint8_t ctype) -{ - /* Special cargo types for purchase list and stations */ - if ((feature == GSF_STATIONS || feature == GSF_ROADSTOPS) && ctype == 0xFE) return SpriteGroupCargo::SG_DEFAULT_NA; - if (ctype == 0xFF) return SpriteGroupCargo::SG_PURCHASE; - - auto cargo_list = GetCargoTranslationTable(*_cur.grffile); - - /* Check if the cargo type is out of bounds of the cargo translation table */ - if (ctype >= cargo_list.size()) { - GrfMsg(1, "TranslateCargo: Cargo type {} out of range (max {}), skipping.", ctype, (unsigned int)_cur.grffile->cargo_list.size() - 1); - return INVALID_CARGO; - } - - /* Look up the cargo label from the translation table */ - CargoLabel cl = cargo_list[ctype]; - if (cl == CT_INVALID) { - GrfMsg(5, "TranslateCargo: Cargo type {} not available in this climate, skipping.", ctype); - return INVALID_CARGO; - } - - CargoType cargo_type = GetCargoTypeByLabel(cl); - if (!IsValidCargoType(cargo_type)) { - 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)); - return INVALID_CARGO; - } - - 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), cargo_type); - return cargo_type; -} - - -static bool IsValidGroupID(uint16_t groupid, const char *function) -{ - if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) { - GrfMsg(1, "{}: Spritegroup 0x{:04X} out of range or empty, skipping.", function, groupid); - return false; - } - - return true; -} - -static void VehicleMapSpriteGroup(ByteReader &buf, uint8_t feature, uint8_t idcount) -{ - static std::vector last_engines; // Engine IDs are remembered in case the next action is a wagon override. - bool wagover = false; - - /* Test for 'wagon override' flag */ - if (HasBit(idcount, 7)) { - wagover = true; - /* Strip off the flag */ - idcount = GB(idcount, 0, 7); - - if (last_engines.empty()) { - GrfMsg(0, "VehicleMapSpriteGroup: WagonOverride: No engine to do override with"); - return; - } - - GrfMsg(6, "VehicleMapSpriteGroup: WagonOverride: {} engines, {} wagons", last_engines.size(), idcount); - } else { - last_engines.resize(idcount); - } - - std::vector engines; - engines.reserve(idcount); - for (uint i = 0; i < idcount; i++) { - Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, buf.ReadExtendedByte()); - if (e == nullptr) { - /* No engine could be allocated?!? Deal with it. Okay, - * this might look bad. Also make sure this NewGRF - * gets disabled, as a half loaded one is bad. */ - HandleChangeInfoResult("VehicleMapSpriteGroup", CIR_INVALID_ID, 0, 0); - return; - } - - engines.push_back(e->index); - if (!wagover) last_engines[i] = engines[i]; - } - - uint8_t cidcount = buf.ReadByte(); - for (uint c = 0; c < cidcount; c++) { - uint8_t ctype = buf.ReadByte(); - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) continue; - - GrfMsg(8, "VehicleMapSpriteGroup: * [{}] Cargo type 0x{:X}, group id 0x{:02X}", c, ctype, groupid); - - CargoType cargo_type = TranslateCargo(feature, ctype); - if (!IsValidCargoType(cargo_type)) continue; - - for (uint i = 0; i < idcount; i++) { - EngineID engine = engines[i]; - - GrfMsg(7, "VehicleMapSpriteGroup: [{}] Engine {}...", i, engine); - - if (wagover) { - SetWagonOverrideSprites(engine, cargo_type, _cur.spritegroups[groupid], last_engines); - } else { - SetCustomEngineSprites(engine, cargo_type, _cur.spritegroups[groupid]); - } - } - } - - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) return; - - GrfMsg(8, "-- Default group id 0x{:04X}", groupid); - - for (uint i = 0; i < idcount; i++) { - EngineID engine = engines[i]; - - if (wagover) { - SetWagonOverrideSprites(engine, SpriteGroupCargo::SG_DEFAULT, _cur.spritegroups[groupid], last_engines); - } else { - SetCustomEngineSprites(engine, SpriteGroupCargo::SG_DEFAULT, _cur.spritegroups[groupid]); - SetEngineGRF(engine, _cur.grffile); - } - } -} - - -static void CanalMapSpriteGroup(ByteReader &buf, uint8_t idcount) -{ - std::vector cfs; - cfs.reserve(idcount); - for (uint i = 0; i < idcount; i++) { - cfs.push_back(buf.ReadExtendedByte()); - } - - uint8_t cidcount = buf.ReadByte(); - buf.Skip(cidcount * 3); - - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "CanalMapSpriteGroup")) return; - - for (auto &cf : cfs) { - if (cf >= CF_END) { - GrfMsg(1, "CanalMapSpriteGroup: Canal subset {} out of range, skipping", cf); - continue; - } - - _water_feature[cf].grffile = _cur.grffile; - _water_feature[cf].group = _cur.spritegroups[groupid]; - } -} - - -static void StationMapSpriteGroup(ByteReader &buf, uint8_t idcount) -{ - if (_cur.grffile->stations.empty()) { - GrfMsg(1, "StationMapSpriteGroup: No stations defined, skipping"); - return; - } - - std::vector stations; - stations.reserve(idcount); - for (uint i = 0; i < idcount; i++) { - stations.push_back(buf.ReadExtendedByte()); - } - - uint8_t cidcount = buf.ReadByte(); - for (uint c = 0; c < cidcount; c++) { - uint8_t ctype = buf.ReadByte(); - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) continue; - - ctype = TranslateCargo(GSF_STATIONS, ctype); - if (!IsValidCargoType(ctype)) continue; - - for (auto &station : stations) { - StationSpec *statspec = station >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[station].get(); - - if (statspec == nullptr) { - GrfMsg(1, "StationMapSpriteGroup: Station {} undefined, skipping", station); - continue; - } - - statspec->grf_prop.SetSpriteGroup(ctype, _cur.spritegroups[groupid]); - } - } - - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) return; - - for (auto &station : stations) { - StationSpec *statspec = station >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[station].get(); - - if (statspec == nullptr) { - GrfMsg(1, "StationMapSpriteGroup: Station {} undefined, skipping", station); - continue; - } - - if (statspec->grf_prop.HasGrfFile()) { - GrfMsg(1, "StationMapSpriteGroup: Station {} mapped multiple times, skipping", station); - continue; - } - - statspec->grf_prop.SetSpriteGroup(SpriteGroupCargo::SG_DEFAULT, _cur.spritegroups[groupid]); - statspec->grf_prop.SetGRFFile(_cur.grffile); - statspec->grf_prop.local_id = station; - StationClass::Assign(statspec); - } -} - - -static void TownHouseMapSpriteGroup(ByteReader &buf, uint8_t idcount) -{ - if (_cur.grffile->housespec.empty()) { - GrfMsg(1, "TownHouseMapSpriteGroup: No houses defined, skipping"); - return; - } - - std::vector houses; - houses.reserve(idcount); - for (uint i = 0; i < idcount; i++) { - houses.push_back(buf.ReadExtendedByte()); - } - - /* Skip the cargo type section, we only care about the default group */ - uint8_t cidcount = buf.ReadByte(); - buf.Skip(cidcount * 3); - - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "TownHouseMapSpriteGroup")) return; - - for (auto &house : houses) { - HouseSpec *hs = house >= _cur.grffile->housespec.size() ? nullptr : _cur.grffile->housespec[house].get(); - - if (hs == nullptr) { - GrfMsg(1, "TownHouseMapSpriteGroup: House {} undefined, skipping.", house); - continue; - } - - hs->grf_prop.SetSpriteGroup(0, _cur.spritegroups[groupid]); - } -} - -static void IndustryMapSpriteGroup(ByteReader &buf, uint8_t idcount) -{ - if (_cur.grffile->industryspec.empty()) { - GrfMsg(1, "IndustryMapSpriteGroup: No industries defined, skipping"); - return; - } - - std::vector industries; - industries.reserve(idcount); - for (uint i = 0; i < idcount; i++) { - industries.push_back(buf.ReadExtendedByte()); - } - - /* Skip the cargo type section, we only care about the default group */ - uint8_t cidcount = buf.ReadByte(); - buf.Skip(cidcount * 3); - - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "IndustryMapSpriteGroup")) return; - - for (auto &industry : industries) { - IndustrySpec *indsp = industry >= _cur.grffile->industryspec.size() ? nullptr : _cur.grffile->industryspec[industry].get(); - - if (indsp == nullptr) { - GrfMsg(1, "IndustryMapSpriteGroup: Industry {} undefined, skipping", industry); - continue; - } - - indsp->grf_prop.SetSpriteGroup(0, _cur.spritegroups[groupid]); - } -} - -static void IndustrytileMapSpriteGroup(ByteReader &buf, uint8_t idcount) -{ - if (_cur.grffile->indtspec.empty()) { - GrfMsg(1, "IndustrytileMapSpriteGroup: No industry tiles defined, skipping"); - return; - } - - std::vector indtiles; - indtiles.reserve(idcount); - for (uint i = 0; i < idcount; i++) { - indtiles.push_back(buf.ReadExtendedByte()); - } - - /* Skip the cargo type section, we only care about the default group */ - uint8_t cidcount = buf.ReadByte(); - buf.Skip(cidcount * 3); - - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "IndustrytileMapSpriteGroup")) return; - - for (auto &indtile : indtiles) { - IndustryTileSpec *indtsp = indtile >= _cur.grffile->indtspec.size() ? nullptr : _cur.grffile->indtspec[indtile].get(); - - if (indtsp == nullptr) { - GrfMsg(1, "IndustrytileMapSpriteGroup: Industry tile {} undefined, skipping", indtile); - continue; - } - - indtsp->grf_prop.SetSpriteGroup(0, _cur.spritegroups[groupid]); - } -} - -static void CargoMapSpriteGroup(ByteReader &buf, uint8_t idcount) -{ - std::vector cargoes; - cargoes.reserve(idcount); - for (uint i = 0; i < idcount; i++) { - cargoes.push_back(buf.ReadExtendedByte()); - } - - /* Skip the cargo type section, we only care about the default group */ - uint8_t cidcount = buf.ReadByte(); - buf.Skip(cidcount * 3); - - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "CargoMapSpriteGroup")) return; - - for (auto &cargo_type : cargoes) { - if (cargo_type >= NUM_CARGO) { - GrfMsg(1, "CargoMapSpriteGroup: Cargo type {} out of range, skipping", cargo_type); - continue; - } - - CargoSpec *cs = CargoSpec::Get(cargo_type); - cs->grffile = _cur.grffile; - cs->group = _cur.spritegroups[groupid]; - } -} - -static void ObjectMapSpriteGroup(ByteReader &buf, uint8_t idcount) -{ - if (_cur.grffile->objectspec.empty()) { - GrfMsg(1, "ObjectMapSpriteGroup: No object tiles defined, skipping"); - return; - } - - std::vector objects; - objects.reserve(idcount); - for (uint i = 0; i < idcount; i++) { - objects.push_back(buf.ReadExtendedByte()); - } - - uint8_t cidcount = buf.ReadByte(); - for (uint c = 0; c < cidcount; c++) { - uint8_t ctype = buf.ReadByte(); - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) continue; - - /* The only valid option here is purchase list sprite groups. */ - if (ctype != 0xFF) { - GrfMsg(1, "ObjectMapSpriteGroup: Invalid cargo bitnum {} for objects, skipping.", ctype); - continue; - } - - for (auto &object : objects) { - ObjectSpec *spec = object >= _cur.grffile->objectspec.size() ? nullptr : _cur.grffile->objectspec[object].get(); - - if (spec == nullptr) { - GrfMsg(1, "ObjectMapSpriteGroup: Object {} undefined, skipping", object); - continue; - } - - spec->grf_prop.SetSpriteGroup(OBJECT_SPRITE_GROUP_PURCHASE, _cur.spritegroups[groupid]); - } - } - - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) return; - - for (auto &object : objects) { - ObjectSpec *spec = object >= _cur.grffile->objectspec.size() ? nullptr : _cur.grffile->objectspec[object].get(); - - if (spec == nullptr) { - GrfMsg(1, "ObjectMapSpriteGroup: Object {} undefined, skipping", object); - continue; - } - - if (spec->grf_prop.HasGrfFile()) { - GrfMsg(1, "ObjectMapSpriteGroup: Object {} mapped multiple times, skipping", object); - continue; - } - - spec->grf_prop.SetSpriteGroup(OBJECT_SPRITE_GROUP_DEFAULT, _cur.spritegroups[groupid]); - spec->grf_prop.SetGRFFile(_cur.grffile); - spec->grf_prop.local_id = object; - } -} - -static void RailTypeMapSpriteGroup(ByteReader &buf, uint8_t idcount) -{ - std::vector railtypes; - railtypes.reserve(idcount); - for (uint i = 0; i < idcount; i++) { - uint16_t id = buf.ReadExtendedByte(); - railtypes.push_back(id < RAILTYPE_END ? _cur.grffile->railtype_map[id] : INVALID_RAILTYPE); - } - - uint8_t cidcount = buf.ReadByte(); - for (uint c = 0; c < cidcount; c++) { - uint8_t ctype = buf.ReadByte(); - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "RailTypeMapSpriteGroup")) continue; - - if (ctype >= RTSG_END) continue; - - extern RailTypeInfo _railtypes[RAILTYPE_END]; - for (auto &railtype : railtypes) { - if (railtype != INVALID_RAILTYPE) { - RailTypeInfo *rti = &_railtypes[railtype]; - - rti->grffile[ctype] = _cur.grffile; - rti->group[ctype] = _cur.spritegroups[groupid]; - } - } - } - - /* Railtypes do not use the default group. */ - buf.ReadWord(); -} - -static void RoadTypeMapSpriteGroup(ByteReader &buf, uint8_t idcount, RoadTramType rtt) -{ - std::array &type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map; - - std::vector roadtypes; - roadtypes.reserve(idcount); - for (uint i = 0; i < idcount; i++) { - uint16_t id = buf.ReadExtendedByte(); - roadtypes.push_back(id < ROADTYPE_END ? type_map[id] : INVALID_ROADTYPE); - } - - uint8_t cidcount = buf.ReadByte(); - for (uint c = 0; c < cidcount; c++) { - uint8_t ctype = buf.ReadByte(); - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "RoadTypeMapSpriteGroup")) continue; - - if (ctype >= ROTSG_END) continue; - - extern RoadTypeInfo _roadtypes[ROADTYPE_END]; - for (auto &roadtype : roadtypes) { - if (roadtype != INVALID_ROADTYPE) { - RoadTypeInfo *rti = &_roadtypes[roadtype]; - - rti->grffile[ctype] = _cur.grffile; - rti->group[ctype] = _cur.spritegroups[groupid]; - } - } - } - - /* Roadtypes do not use the default group. */ - buf.ReadWord(); -} - -static void AirportMapSpriteGroup(ByteReader &buf, uint8_t idcount) -{ - if (_cur.grffile->airportspec.empty()) { - GrfMsg(1, "AirportMapSpriteGroup: No airports defined, skipping"); - return; - } - - std::vector airports; - airports.reserve(idcount); - for (uint i = 0; i < idcount; i++) { - airports.push_back(buf.ReadExtendedByte()); - } - - /* Skip the cargo type section, we only care about the default group */ - uint8_t cidcount = buf.ReadByte(); - buf.Skip(cidcount * 3); - - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "AirportMapSpriteGroup")) return; - - for (auto &airport : airports) { - AirportSpec *as = airport >= _cur.grffile->airportspec.size() ? nullptr : _cur.grffile->airportspec[airport].get(); - - if (as == nullptr) { - GrfMsg(1, "AirportMapSpriteGroup: Airport {} undefined, skipping", airport); - continue; - } - - as->grf_prop.SetSpriteGroup(0, _cur.spritegroups[groupid]); - } -} - -static void AirportTileMapSpriteGroup(ByteReader &buf, uint8_t idcount) -{ - if (_cur.grffile->airtspec.empty()) { - GrfMsg(1, "AirportTileMapSpriteGroup: No airport tiles defined, skipping"); - return; - } - - std::vector airptiles; - airptiles.reserve(idcount); - for (uint i = 0; i < idcount; i++) { - airptiles.push_back(buf.ReadExtendedByte()); - } - - /* Skip the cargo type section, we only care about the default group */ - uint8_t cidcount = buf.ReadByte(); - buf.Skip(cidcount * 3); - - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "AirportTileMapSpriteGroup")) return; - - for (auto &airptile : airptiles) { - AirportTileSpec *airtsp = airptile >= _cur.grffile->airtspec.size() ? nullptr : _cur.grffile->airtspec[airptile].get(); - - if (airtsp == nullptr) { - GrfMsg(1, "AirportTileMapSpriteGroup: Airport tile {} undefined, skipping", airptile); - continue; - } - - airtsp->grf_prop.SetSpriteGroup(0, _cur.spritegroups[groupid]); - } -} - -static void RoadStopMapSpriteGroup(ByteReader &buf, uint8_t idcount) -{ - if (_cur.grffile->roadstops.empty()) { - GrfMsg(1, "RoadStopMapSpriteGroup: No roadstops defined, skipping"); - return; - } - - std::vector roadstops; - roadstops.reserve(idcount); - for (uint i = 0; i < idcount; i++) { - roadstops.push_back(buf.ReadExtendedByte()); - } - - uint8_t cidcount = buf.ReadByte(); - for (uint c = 0; c < cidcount; c++) { - uint8_t ctype = buf.ReadByte(); - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "RoadStopMapSpriteGroup")) continue; - - ctype = TranslateCargo(GSF_ROADSTOPS, ctype); - if (!IsValidCargoType(ctype)) continue; - - for (auto &roadstop : roadstops) { - RoadStopSpec *roadstopspec = roadstop >= _cur.grffile->roadstops.size() ? nullptr : _cur.grffile->roadstops[roadstop].get(); - - if (roadstopspec == nullptr) { - GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} undefined, skipping", roadstop); - continue; - } - - roadstopspec->grf_prop.SetSpriteGroup(ctype, _cur.spritegroups[groupid]); - } - } - - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "RoadStopMapSpriteGroup")) return; - - for (auto &roadstop : roadstops) { - RoadStopSpec *roadstopspec = roadstop >= _cur.grffile->roadstops.size() ? nullptr : _cur.grffile->roadstops[roadstop].get(); - - if (roadstopspec == nullptr) { - GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} undefined, skipping.", roadstop); - continue; - } - - if (roadstopspec->grf_prop.HasGrfFile()) { - GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} mapped multiple times, skipping", roadstop); - continue; - } - - roadstopspec->grf_prop.SetSpriteGroup(SpriteGroupCargo::SG_DEFAULT, _cur.spritegroups[groupid]); - roadstopspec->grf_prop.SetGRFFile(_cur.grffile); - roadstopspec->grf_prop.local_id = roadstop; - RoadStopClass::Assign(roadstopspec); - } -} - -static void BadgeMapSpriteGroup(ByteReader &buf, uint8_t idcount) -{ - if (_cur.grffile->badge_map.empty()) { - GrfMsg(1, "BadgeMapSpriteGroup: No badges defined, skipping"); - return; - } - - std::vector local_ids; - local_ids.reserve(idcount); - for (uint i = 0; i < idcount; i++) { - local_ids.push_back(buf.ReadExtendedByte()); - } - - uint8_t cidcount = buf.ReadByte(); - for (uint c = 0; c < cidcount; c++) { - uint8_t ctype = buf.ReadByte(); - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "BadgeMapSpriteGroup")) continue; - - if (ctype >= GSF_END) continue; - - for (const auto &local_id : local_ids) { - auto found = _cur.grffile->badge_map.find(local_id); - if (found == std::end(_cur.grffile->badge_map)) { - GrfMsg(1, "BadgeMapSpriteGroup: Badge {} undefined, skipping", local_id); - continue; - } - - auto &badge = *GetBadge(found->second); - badge.grf_prop.SetSpriteGroup(ctype, _cur.spritegroups[groupid]); - } - } - - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "BadgeMapSpriteGroup")) return; - - for (auto &local_id : local_ids) { - auto found = _cur.grffile->badge_map.find(local_id); - if (found == std::end(_cur.grffile->badge_map)) { - GrfMsg(1, "BadgeMapSpriteGroup: Badge {} undefined, skipping", local_id); - continue; - } - - auto &badge = *GetBadge(found->second); - badge.grf_prop.SetSpriteGroup(GSF_END, _cur.spritegroups[groupid]); - badge.grf_prop.SetGRFFile(_cur.grffile); - badge.grf_prop.local_id = local_id; - } -} - -/* Action 0x03 */ -static void FeatureMapSpriteGroup(ByteReader &buf) -{ - /* <03> ... [ ]... - * id-list := [] [id-list] - * cargo-list := [cargo-list] - * - * B feature see action 0 - * B n-id bits 0-6: how many IDs this definition applies to - * bit 7: if set, this is a wagon override definition (see below) - * E ids the IDs for which this definition applies - * B num-cid number of cargo IDs (sprite group IDs) in this definition - * can be zero, in that case the def-cid is used always - * B cargo-type type of this cargo type (e.g. mail=2, wood=7, see below) - * W cid cargo ID (sprite group ID) for this type of cargo - * W def-cid default cargo ID (sprite group ID) */ - - uint8_t feature = buf.ReadByte(); - uint8_t idcount = buf.ReadByte(); - - if (feature >= GSF_END) { - GrfMsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature); - return; - } - - /* If idcount is zero, this is a feature callback */ - if (idcount == 0) { - /* Skip number of cargo ids? */ - buf.ReadByte(); - uint16_t groupid = buf.ReadWord(); - if (!IsValidGroupID(groupid, "FeatureMapSpriteGroup")) return; - - GrfMsg(6, "FeatureMapSpriteGroup: Adding generic feature callback for feature 0x{:02X}", feature); - - AddGenericCallback(feature, _cur.grffile, _cur.spritegroups[groupid]); - return; - } - - /* Mark the feature as used by the grf (generic callbacks do not count) */ - SetBit(_cur.grffile->grf_features, feature); - - GrfMsg(6, "FeatureMapSpriteGroup: Feature 0x{:02X}, {} ids", feature, idcount); - - switch (feature) { - case GSF_TRAINS: - case GSF_ROADVEHICLES: - case GSF_SHIPS: - case GSF_AIRCRAFT: - VehicleMapSpriteGroup(buf, feature, idcount); - return; - - case GSF_CANALS: - CanalMapSpriteGroup(buf, idcount); - return; - - case GSF_STATIONS: - StationMapSpriteGroup(buf, idcount); - return; - - case GSF_HOUSES: - TownHouseMapSpriteGroup(buf, idcount); - return; - - case GSF_INDUSTRIES: - IndustryMapSpriteGroup(buf, idcount); - return; - - case GSF_INDUSTRYTILES: - IndustrytileMapSpriteGroup(buf, idcount); - return; - - case GSF_CARGOES: - CargoMapSpriteGroup(buf, idcount); - return; - - case GSF_AIRPORTS: - AirportMapSpriteGroup(buf, idcount); - return; - - case GSF_OBJECTS: - ObjectMapSpriteGroup(buf, idcount); - break; - - case GSF_RAILTYPES: - RailTypeMapSpriteGroup(buf, idcount); - break; - - case GSF_ROADTYPES: - RoadTypeMapSpriteGroup(buf, idcount, RTT_ROAD); - break; - - case GSF_TRAMTYPES: - RoadTypeMapSpriteGroup(buf, idcount, RTT_TRAM); - break; - - case GSF_AIRPORTTILES: - AirportTileMapSpriteGroup(buf, idcount); - return; - - case GSF_ROADSTOPS: - RoadStopMapSpriteGroup(buf, idcount); - return; - - case GSF_BADGES: - BadgeMapSpriteGroup(buf, idcount); - break; - - default: - GrfMsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature); - return; - } -} - -/* Action 0x04 */ -static void FeatureNewName(ByteReader &buf) -{ - /* <04> - * - * B veh-type see action 0 (as 00..07, + 0A - * But IF veh-type = 48, then generic text - * B language-id If bit 6 is set, This is the extended language scheme, - * with up to 64 language. - * Otherwise, it is a mapping where set bits have meaning - * 0 = american, 1 = english, 2 = german, 3 = french, 4 = spanish - * Bit 7 set means this is a generic text, not a vehicle one (or else) - * B num-veh number of vehicles which are getting a new name - * B/W offset number of the first vehicle that gets a new name - * Byte : ID of vehicle to change - * Word : ID of string to change/add - * S data new texts, each of them zero-terminated, after - * which the next name begins. */ - - bool new_scheme = _cur.grffile->grf_version >= 7; - - uint8_t feature = buf.ReadByte(); - if (feature >= GSF_END && feature != 0x48) { - GrfMsg(1, "FeatureNewName: Unsupported feature 0x{:02X}, skipping", feature); - return; - } - - uint8_t lang = buf.ReadByte(); - uint8_t num = buf.ReadByte(); - bool generic = HasBit(lang, 7); - uint16_t id; - if (generic) { - id = buf.ReadWord(); - } else if (feature <= GSF_AIRCRAFT || feature == GSF_BADGES) { - id = buf.ReadExtendedByte(); - } else { - id = buf.ReadByte(); - } - - ClrBit(lang, 7); - - uint16_t endid = id + num; - - GrfMsg(6, "FeatureNewName: About to rename engines {}..{} (feature 0x{:02X}) in language 0x{:02X}", - id, endid, feature, lang); - - /* Feature overlay to make non-generic strings unique in their feature. We use feature + 1 so that generic strings stay as they are. */ - uint32_t feature_overlay = generic ? 0 : ((feature + 1) << 16); - - for (; id < endid && buf.HasData(); id++) { - const std::string_view name = buf.ReadString(); - GrfMsg(8, "FeatureNewName: 0x{:04X} <- {}", id, StrMakeValid(name)); - - switch (feature) { - case GSF_TRAINS: - case GSF_ROADVEHICLES: - case GSF_SHIPS: - case GSF_AIRCRAFT: - if (!generic) { - Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, id, _cur.grfconfig->flags.Test(GRFConfigFlag::Static)); - if (e == nullptr) break; - StringID string = AddGRFString(_cur.grffile->grfid, GRFStringID{feature_overlay | e->index.base()}, lang, new_scheme, false, name, e->info.string_id); - e->info.string_id = string; - } else { - AddGRFString(_cur.grffile->grfid, GRFStringID{id}, lang, new_scheme, true, name, STR_UNDEFINED); - } - break; - - case GSF_BADGES: { - if (!generic) { - auto found = _cur.grffile->badge_map.find(id); - if (found == std::end(_cur.grffile->badge_map)) { - GrfMsg(1, "FeatureNewName: Attempt to name undefined badge 0x{:X}, ignoring", id); - } else { - Badge &badge = *GetBadge(found->second); - badge.name = AddGRFString(_cur.grffile->grfid, GRFStringID{feature_overlay | id}, lang, true, false, name, STR_UNDEFINED); - } - } else { - AddGRFString(_cur.grffile->grfid, GRFStringID{id}, lang, new_scheme, true, name, STR_UNDEFINED); - } - break; - } - - default: - if (IsInsideMM(id, 0xD000, 0xD400) || IsInsideMM(id, 0xD800, 0x10000)) { - AddGRFString(_cur.grffile->grfid, GRFStringID{id}, lang, new_scheme, true, name, STR_UNDEFINED); - break; - } - - switch (GB(id, 8, 8)) { - case 0xC4: // Station class name - if (GB(id, 0, 8) >= _cur.grffile->stations.size() || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) { - GrfMsg(1, "FeatureNewName: Attempt to name undefined station 0x{:X}, ignoring", GB(id, 0, 8)); - } else { - StationClassID class_index = _cur.grffile->stations[GB(id, 0, 8)]->class_index; - StationClass::Get(class_index)->name = AddGRFString(_cur.grffile->grfid, GRFStringID{id}, lang, new_scheme, false, name, STR_UNDEFINED); - } - break; - - case 0xC5: // Station name - if (GB(id, 0, 8) >= _cur.grffile->stations.size() || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) { - GrfMsg(1, "FeatureNewName: Attempt to name undefined station 0x{:X}, ignoring", GB(id, 0, 8)); - } else { - _cur.grffile->stations[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, GRFStringID{id}, lang, new_scheme, false, name, STR_UNDEFINED); - } - break; - - case 0xC7: // Airporttile name - if (GB(id, 0, 8) >= _cur.grffile->airtspec.size() || _cur.grffile->airtspec[GB(id, 0, 8)] == nullptr) { - GrfMsg(1, "FeatureNewName: Attempt to name undefined airport tile 0x{:X}, ignoring", GB(id, 0, 8)); - } else { - _cur.grffile->airtspec[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, GRFStringID{id}, lang, new_scheme, false, name, STR_UNDEFINED); - } - break; - - case 0xC9: // House name - if (GB(id, 0, 8) >= _cur.grffile->housespec.size() || _cur.grffile->housespec[GB(id, 0, 8)] == nullptr) { - GrfMsg(1, "FeatureNewName: Attempt to name undefined house 0x{:X}, ignoring.", GB(id, 0, 8)); - } else { - _cur.grffile->housespec[GB(id, 0, 8)]->building_name = AddGRFString(_cur.grffile->grfid, GRFStringID{id}, lang, new_scheme, false, name, STR_UNDEFINED); - } - break; - - default: - GrfMsg(7, "FeatureNewName: Unsupported ID (0x{:04X})", id); - break; - } - break; - } - } -} - -/** - * Sanitize incoming sprite offsets for Action 5 graphics replacements. - * @param num The number of sprites to load. - * @param offset Offset from the base. - * @param max_sprites The maximum number of sprites that can be loaded in this action 5. - * @param name Used for error warnings. - * @return The number of sprites that is going to be skipped. - */ -static uint16_t SanitizeSpriteOffset(uint16_t &num, uint16_t offset, int max_sprites, const std::string_view name) -{ - - if (offset >= max_sprites) { - GrfMsg(1, "GraphicsNew: {} sprite offset must be less than {}, skipping", name, max_sprites); - uint orig_num = num; - num = 0; - return orig_num; - } - - if (offset + num > max_sprites) { - GrfMsg(4, "GraphicsNew: {} sprite overflow, truncating...", name); - uint orig_num = num; - num = std::max(max_sprites - offset, 0); - return orig_num - num; - } - - return 0; -} - - -/** The information about action 5 types. */ -static constexpr auto _action5_types = std::to_array({ - /* Note: min_sprites should not be changed. Therefore these constants are directly here and not in sprites.h */ - /* 0x00 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x00" }, - /* 0x01 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x01" }, - /* 0x02 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x02" }, - /* 0x03 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x03" }, - /* 0x04 */ { A5BLOCK_ALLOW_OFFSET, SPR_SIGNALS_BASE, 1, PRESIGNAL_SEMAPHORE_AND_PBS_SPRITE_COUNT, "Signal graphics" }, - /* 0x05 */ { A5BLOCK_ALLOW_OFFSET, SPR_ELRAIL_BASE, 1, ELRAIL_SPRITE_COUNT, "Rail catenary graphics" }, - /* 0x06 */ { A5BLOCK_ALLOW_OFFSET, SPR_SLOPES_BASE, 1, NORMAL_AND_HALFTILE_FOUNDATION_SPRITE_COUNT, "Foundation graphics" }, - /* 0x07 */ { A5BLOCK_INVALID, 0, 75, 0, "TTDP GUI graphics" }, // Not used by OTTD. - /* 0x08 */ { A5BLOCK_ALLOW_OFFSET, SPR_CANALS_BASE, 1, CANALS_SPRITE_COUNT, "Canal graphics" }, - /* 0x09 */ { A5BLOCK_ALLOW_OFFSET, SPR_ONEWAY_BASE, 1, ONEWAY_SPRITE_COUNT, "One way road graphics" }, - /* 0x0A */ { A5BLOCK_ALLOW_OFFSET, SPR_2CCMAP_BASE, 1, TWOCCMAP_SPRITE_COUNT, "2CC colour maps" }, - /* 0x0B */ { A5BLOCK_ALLOW_OFFSET, SPR_TRAMWAY_BASE, 1, TRAMWAY_SPRITE_COUNT, "Tramway graphics" }, - /* 0x0C */ { A5BLOCK_INVALID, 0, 133, 0, "Snowy temperate tree" }, // Not yet used by OTTD. - /* 0x0D */ { A5BLOCK_FIXED, SPR_SHORE_BASE, 16, SHORE_SPRITE_COUNT, "Shore graphics" }, - /* 0x0E */ { A5BLOCK_INVALID, 0, 0, 0, "New Signals graphics" }, // Not yet used by OTTD. - /* 0x0F */ { A5BLOCK_ALLOW_OFFSET, SPR_TRACKS_FOR_SLOPES_BASE, 1, TRACKS_FOR_SLOPES_SPRITE_COUNT, "Sloped rail track" }, - /* 0x10 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORTX_BASE, 1, AIRPORTX_SPRITE_COUNT, "Airport graphics" }, - /* 0x11 */ { A5BLOCK_ALLOW_OFFSET, SPR_ROADSTOP_BASE, 1, ROADSTOP_SPRITE_COUNT, "Road stop graphics" }, - /* 0x12 */ { A5BLOCK_ALLOW_OFFSET, SPR_AQUEDUCT_BASE, 1, AQUEDUCT_SPRITE_COUNT, "Aqueduct graphics" }, - /* 0x13 */ { A5BLOCK_ALLOW_OFFSET, SPR_AUTORAIL_BASE, 1, AUTORAIL_SPRITE_COUNT, "Autorail graphics" }, - /* 0x14 */ { A5BLOCK_INVALID, 0, 1, 0, "Flag graphics" }, // deprecated, no longer used. - /* 0x15 */ { A5BLOCK_ALLOW_OFFSET, SPR_OPENTTD_BASE, 1, OPENTTD_SPRITE_COUNT, "OpenTTD GUI graphics" }, - /* 0x16 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORT_PREVIEW_BASE, 1, AIRPORT_PREVIEW_SPRITE_COUNT, "Airport preview graphics" }, - /* 0x17 */ { A5BLOCK_ALLOW_OFFSET, SPR_RAILTYPE_TUNNEL_BASE, 1, RAILTYPE_TUNNEL_BASE_COUNT, "Railtype tunnel base" }, - /* 0x18 */ { A5BLOCK_ALLOW_OFFSET, SPR_PALETTE_BASE, 1, PALETTE_SPRITE_COUNT, "Palette" }, - /* 0x19 */ { A5BLOCK_ALLOW_OFFSET, SPR_ROAD_WAYPOINTS_BASE, 1, ROAD_WAYPOINTS_SPRITE_COUNT, "Road waypoints" }, - /* 0x1A */ { A5BLOCK_ALLOW_OFFSET, SPR_OVERLAY_ROCKS_BASE, 1, OVERLAY_ROCKS_SPRITE_COUNT, "Overlay rocks" }, -}); - -/** - * Get list of all action 5 types - * @return Read-only span of action 5 type information. - */ -std::span GetAction5Types() -{ - return _action5_types; -} - -/* Action 0x05 */ -static void GraphicsNew(ByteReader &buf) -{ - /* <05> - * - * B graphics-type What set of graphics the sprites define. - * E num-sprites How many sprites are in this set? - * V other data Graphics type specific data. Currently unused. */ - - uint8_t type = buf.ReadByte(); - uint16_t num = buf.ReadExtendedByte(); - uint16_t offset = HasBit(type, 7) ? buf.ReadExtendedByte() : 0; - ClrBit(type, 7); // Clear the high bit as that only indicates whether there is an offset. - - if ((type == 0x0D) && (num == 10) && _cur.grfconfig->flags.Test(GRFConfigFlag::System)) { - /* Special not-TTDP-compatible case used in openttd.grf - * Missing shore sprites and initialisation of SPR_SHORE_BASE */ - GrfMsg(2, "GraphicsNew: Loading 10 missing shore sprites from extra grf."); - LoadNextSprite(SPR_SHORE_BASE + 0, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_S - LoadNextSprite(SPR_SHORE_BASE + 5, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_W - LoadNextSprite(SPR_SHORE_BASE + 7, *_cur.file, _cur.nfo_line++); // SLOPE_WSE - LoadNextSprite(SPR_SHORE_BASE + 10, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_N - LoadNextSprite(SPR_SHORE_BASE + 11, *_cur.file, _cur.nfo_line++); // SLOPE_NWS - LoadNextSprite(SPR_SHORE_BASE + 13, *_cur.file, _cur.nfo_line++); // SLOPE_ENW - LoadNextSprite(SPR_SHORE_BASE + 14, *_cur.file, _cur.nfo_line++); // SLOPE_SEN - LoadNextSprite(SPR_SHORE_BASE + 15, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_E - LoadNextSprite(SPR_SHORE_BASE + 16, *_cur.file, _cur.nfo_line++); // SLOPE_EW - LoadNextSprite(SPR_SHORE_BASE + 17, *_cur.file, _cur.nfo_line++); // SLOPE_NS - if (_loaded_newgrf_features.shore == SHORE_REPLACE_NONE) _loaded_newgrf_features.shore = SHORE_REPLACE_ONLY_NEW; - return; - } - - /* Supported type? */ - if ((type >= std::size(_action5_types)) || (_action5_types[type].block_type == A5BLOCK_INVALID)) { - GrfMsg(2, "GraphicsNew: Custom graphics (type 0x{:02X}) sprite block of length {} (unimplemented, ignoring)", type, num); - _cur.skip_sprites = num; - return; - } - - const Action5Type *action5_type = &_action5_types[type]; - - /* Contrary to TTDP we allow always to specify too few sprites as we allow always an offset, - * except for the long version of the shore type: - * Ignore offset if not allowed */ - if ((action5_type->block_type != A5BLOCK_ALLOW_OFFSET) && (offset != 0)) { - GrfMsg(1, "GraphicsNew: {} (type 0x{:02X}) do not allow an field. Ignoring offset.", action5_type->name, type); - offset = 0; - } - - /* Ignore action5 if too few sprites are specified. (for TTDP compatibility) - * This does not make sense, if is allowed */ - if ((action5_type->block_type == A5BLOCK_FIXED) && (num < action5_type->min_sprites)) { - GrfMsg(1, "GraphicsNew: {} (type 0x{:02X}) count must be at least {}. Only {} were specified. Skipping.", action5_type->name, type, action5_type->min_sprites, num); - _cur.skip_sprites = num; - return; - } - - /* Load at most max_sprites sprites. Skip remaining sprites. (for compatibility with TTDP and future extensions) */ - uint16_t skip_num = SanitizeSpriteOffset(num, offset, action5_type->max_sprites, action5_type->name); - SpriteID replace = action5_type->sprite_base + offset; - - /* Load sprites starting from , then skip sprites. */ - GrfMsg(2, "GraphicsNew: Replacing sprites {} to {} of {} (type 0x{:02X}) at SpriteID 0x{:04X}", offset, offset + num - 1, action5_type->name, type, replace); - - if (type == 0x0D) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_5; - - if (type == 0x0B) { - static const SpriteID depot_with_track_offset = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_TRAMWAY_BASE; - static const SpriteID depot_no_track_offset = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_TRAMWAY_BASE; - if (offset <= depot_with_track_offset && offset + num > depot_with_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_WITH_TRACK; - if (offset <= depot_no_track_offset && offset + num > depot_no_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_NO_TRACK; - } - - /* If the baseset or grf only provides sprites for flat tiles (pre #10282), duplicate those for use on slopes. */ - bool dup_oneway_sprites = ((type == 0x09) && (offset + num <= ONEWAY_SLOPE_N_OFFSET)); - - for (; num > 0; num--) { - _cur.nfo_line++; - SpriteID load_index = (replace == 0 ? _cur.spriteid++ : replace++); - LoadNextSprite(load_index, *_cur.file, _cur.nfo_line); - if (dup_oneway_sprites) { - DupSprite(load_index, load_index + ONEWAY_SLOPE_N_OFFSET); - DupSprite(load_index, load_index + ONEWAY_SLOPE_S_OFFSET); - } - } - - _cur.skip_sprites = skip_num; -} - -/* Action 0x05 (SKIP) */ -static void SkipAct5(ByteReader &buf) -{ - /* Ignore type byte */ - buf.ReadByte(); - - /* Skip the sprites of this action */ - _cur.skip_sprites = buf.ReadExtendedByte(); - - GrfMsg(3, "SkipAct5: Skipping {} sprites", _cur.skip_sprites); -} - -/** - * Reads a variable common to VarAction2 and Action7/9/D. - * - * Returns VarAction2 variable 'param' resp. Action7/9/D variable '0x80 + param'. - * If a variable is not accessible from all four actions, it is handled in the action specific functions. - * - * @param param variable number (as for VarAction2, for Action7/9/D you have to subtract 0x80 first). - * @param value returns the value of the variable. - * @param grffile NewGRF querying the variable - * @return true iff the variable is known and the value is returned in 'value'. - */ -bool GetGlobalVariable(uint8_t param, uint32_t *value, const GRFFile *grffile) -{ - switch (param) { - case 0x00: // current date - *value = std::max(TimerGameCalendar::date - CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR, TimerGameCalendar::Date(0)).base(); - return true; - - case 0x01: // current year - *value = (Clamp(TimerGameCalendar::year, CalendarTime::ORIGINAL_BASE_YEAR, CalendarTime::ORIGINAL_MAX_YEAR) - CalendarTime::ORIGINAL_BASE_YEAR).base(); - return true; - - 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) - TimerGameCalendar::YearMonthDay ymd = TimerGameCalendar::ConvertDateToYMD(TimerGameCalendar::date); - TimerGameCalendar::Date start_of_year = TimerGameCalendar::ConvertYMDToDate(ymd.year, 0, 1); - *value = ymd.month | (ymd.day - 1) << 8 | (TimerGameCalendar::IsLeapYear(ymd.year) ? 1 << 15 : 0) | (TimerGameCalendar::date - start_of_year).base() << 16; - return true; - } - - case 0x03: // current climate, 0=temp, 1=arctic, 2=trop, 3=toyland - *value = to_underlying(_settings_game.game_creation.landscape); - return true; - - case 0x06: // road traffic side, bit 4 clear=left, set=right - *value = _settings_game.vehicle.road_side << 4; - return true; - - case 0x09: // date fraction - *value = TimerGameCalendar::date_fract * 885; - return true; - - case 0x0A: // animation counter - *value = GB(TimerGameTick::counter, 0, 16); - return true; - - case 0x0B: { // TTDPatch version - uint major = 2; - uint minor = 6; - uint revision = 1; // special case: 2.0.1 is 2.0.10 - uint build = 1382; - *value = (major << 24) | (minor << 20) | (revision << 16) | build; - return true; - } - - case 0x0D: // TTD Version, 00=DOS, 01=Windows - *value = _cur.grfconfig->palette & GRFP_USE_MASK; - return true; - - case 0x0E: // Y-offset for train sprites - *value = _cur.grffile->traininfo_vehicle_pitch; - return true; - - case 0x0F: // Rail track type cost factors - *value = 0; - SB(*value, 0, 8, GetRailTypeInfo(RAILTYPE_RAIL)->cost_multiplier); // normal rail - if (_settings_game.vehicle.disable_elrails) { - /* skip elrail multiplier - disabled */ - SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_MONO)->cost_multiplier); // monorail - } else { - SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_ELECTRIC)->cost_multiplier); // electified railway - /* Skip monorail multiplier - no space in result */ - } - SB(*value, 16, 8, GetRailTypeInfo(RAILTYPE_MAGLEV)->cost_multiplier); // maglev - return true; - - case 0x11: // current rail tool type - *value = 0; // constant fake value to avoid desync - return true; - - case 0x12: // Game mode - *value = _game_mode; - return true; - - /* case 0x13: // Tile refresh offset to left not implemented */ - /* case 0x14: // Tile refresh offset to right not implemented */ - /* case 0x15: // Tile refresh offset upwards not implemented */ - /* case 0x16: // Tile refresh offset downwards not implemented */ - /* case 0x17: // temperate snow line not implemented */ - - case 0x1A: // Always -1 - *value = UINT_MAX; - return true; - - case 0x1B: // Display options - *value = 0x3F; // constant fake value to avoid desync - return true; - - case 0x1D: // TTD Platform, 00=TTDPatch, 01=OpenTTD - *value = 1; - return true; - - case 0x1E: { // Miscellaneous GRF features - GrfMiscBits bits = _misc_grf_features; - - /* Add the local flags */ - assert(!bits.Test(GrfMiscBit::TrainWidth32Pixels)); - if (_cur.grffile->traininfo_vehicle_width == VEHICLEINFO_FULL_VEHICLE_WIDTH) bits.Set(GrfMiscBit::TrainWidth32Pixels); - - *value = bits.base(); - return true; - } - - /* case 0x1F: // locale dependent settings not implemented to avoid desync */ - - case 0x20: { // snow line height - uint8_t snowline = GetSnowLine(); - if (_settings_game.game_creation.landscape == LandscapeType::Arctic && snowline <= _settings_game.construction.map_height_limit) { - *value = Clamp(snowline * (grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFE); - } else { - /* No snow */ - *value = 0xFF; - } - return true; - } - - case 0x21: // OpenTTD version - *value = _openttd_newgrf_version; - return true; - - case 0x22: // difficulty level - *value = SP_CUSTOM; - return true; - - case 0x23: // long format date - *value = TimerGameCalendar::date.base(); - return true; - - case 0x24: // long format year - *value = TimerGameCalendar::year.base(); - return true; - - default: return false; - } -} - -static uint32_t GetParamVal(uint8_t param, uint32_t *cond_val) -{ - /* First handle variable common with VarAction2 */ - uint32_t value; - if (GetGlobalVariable(param - 0x80, &value, _cur.grffile)) return value; - - - /* Non-common variable */ - switch (param) { - case 0x84: { // GRF loading stage - uint32_t res = 0; - - if (_cur.stage > GLS_INIT) SetBit(res, 0); - if (_cur.stage == GLS_RESERVE) SetBit(res, 8); - if (_cur.stage == GLS_ACTIVATION) SetBit(res, 9); - return res; - } - - case 0x85: // TTDPatch flags, only for bit tests - if (cond_val == nullptr) { - /* Supported in Action 0x07 and 0x09, not 0x0D */ - return 0; - } else { - uint32_t index = *cond_val / 0x20; - uint32_t param_val = index < lengthof(_ttdpatch_flags) ? _ttdpatch_flags[index] : 0; - *cond_val %= 0x20; - return param_val; - } - - case 0x88: // GRF ID check - return 0; - - /* case 0x99: Global ID offset not implemented */ - - default: - /* GRF Parameter */ - if (param < 0x80) return _cur.grffile->GetParam(param); - - /* In-game variable. */ - GrfMsg(1, "Unsupported in-game variable 0x{:02X}", param); - return UINT_MAX; - } -} - -/* Action 0x06 */ -static void CfgApply(ByteReader &buf) -{ - /* <06> ... - * - * B param-num Number of parameter to substitute (First = "zero") - * Ignored if that parameter was not specified in newgrf.cfg - * B param-size How many bytes to replace. If larger than 4, the - * bytes of the following parameter are used. In that - * case, nothing is applied unless *all* parameters - * were specified. - * B offset Offset into data from beginning of next sprite - * to place where parameter is to be stored. */ - - /* Preload the next sprite */ - SpriteFile &file = *_cur.file; - size_t pos = file.GetPos(); - uint32_t num = file.GetContainerVersion() >= 2 ? file.ReadDword() : file.ReadWord(); - uint8_t type = file.ReadByte(); - - /* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */ - if (type != 0xFF) { - GrfMsg(2, "CfgApply: Ignoring (next sprite is real, unsupported)"); - - /* Reset the file position to the start of the next sprite */ - file.SeekTo(pos, SEEK_SET); - return; - } - - /* Get (or create) the override for the next sprite. */ - GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line + 1); - std::vector &preload_sprite = _grf_line_to_action6_sprite_override[location]; - - /* Load new sprite data if it hasn't already been loaded. */ - if (preload_sprite.empty()) { - preload_sprite.resize(num); - file.ReadBlock(preload_sprite.data(), num); - } - - /* Reset the file position to the start of the next sprite */ - file.SeekTo(pos, SEEK_SET); - - /* Now perform the Action 0x06 on our data. */ - for (;;) { - uint i; - uint param_num; - uint param_size; - uint offset; - bool add_value; - - /* Read the parameter to apply. 0xFF indicates no more data to change. */ - param_num = buf.ReadByte(); - if (param_num == 0xFF) break; - - /* Get the size of the parameter to use. If the size covers multiple - * double words, sequential parameter values are used. */ - param_size = buf.ReadByte(); - - /* Bit 7 of param_size indicates we should add to the original value - * instead of replacing it. */ - add_value = HasBit(param_size, 7); - param_size = GB(param_size, 0, 7); - - /* Where to apply the data to within the pseudo sprite data. */ - offset = buf.ReadExtendedByte(); - - /* If the parameter is a GRF parameter (not an internal variable) check - * if it (and all further sequential parameters) has been defined. */ - if (param_num < 0x80 && (param_num + (param_size - 1) / 4) >= std::size(_cur.grffile->param)) { - GrfMsg(2, "CfgApply: Ignoring (param {} not set)", (param_num + (param_size - 1) / 4)); - break; - } - - GrfMsg(8, "CfgApply: Applying {} bytes from parameter 0x{:02X} at offset 0x{:04X}", param_size, param_num, offset); - - bool carry = false; - for (i = 0; i < param_size && offset + i < num; i++) { - uint32_t value = GetParamVal(param_num + i / 4, nullptr); - /* Reset carry flag for each iteration of the variable (only really - * matters if param_size is greater than 4) */ - if (i % 4 == 0) carry = false; - - if (add_value) { - uint new_value = preload_sprite[offset + i] + GB(value, (i % 4) * 8, 8) + (carry ? 1 : 0); - preload_sprite[offset + i] = GB(new_value, 0, 8); - /* Check if the addition overflowed */ - carry = new_value >= 256; - } else { - preload_sprite[offset + i] = GB(value, (i % 4) * 8, 8); - } - } - } -} - -/** - * Disable a static NewGRF when it is influencing another (non-static) - * NewGRF as this could cause desyncs. - * - * We could just tell the NewGRF querying that the file doesn't exist, - * but that might give unwanted results. Disabling the NewGRF gives the - * best result as no NewGRF author can complain about that. - * @param c The NewGRF to disable. - */ -static void DisableStaticNewGRFInfluencingNonStaticNewGRFs(GRFConfig &c) -{ - GRFError *error = DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC, &c); - error->data = _cur.grfconfig->GetName(); -} - -/* Action 0x07 - * Action 0x09 */ -static void SkipIf(ByteReader &buf) -{ - /* <07/09> - * - * B param-num - * B param-size - * B condition-type - * V value - * B num-sprites */ - uint32_t cond_val = 0; - uint32_t mask = 0; - bool result; - - uint8_t param = buf.ReadByte(); - uint8_t paramsize = buf.ReadByte(); - uint8_t condtype = buf.ReadByte(); - - if (condtype < 2) { - /* Always 1 for bit tests, the given value should be ignored. */ - paramsize = 1; - } - - switch (paramsize) { - case 8: cond_val = buf.ReadDWord(); mask = buf.ReadDWord(); break; - case 4: cond_val = buf.ReadDWord(); mask = 0xFFFFFFFF; break; - case 2: cond_val = buf.ReadWord(); mask = 0x0000FFFF; break; - case 1: cond_val = buf.ReadByte(); mask = 0x000000FF; break; - default: break; - } - - if (param < 0x80 && std::size(_cur.grffile->param) <= param) { - GrfMsg(7, "SkipIf: Param {} undefined, skipping test", param); - return; - } - - GrfMsg(7, "SkipIf: Test condtype {}, param 0x{:02X}, condval 0x{:08X}", condtype, param, cond_val); - - /* condtypes that do not use 'param' are always valid. - * condtypes that use 'param' are either not valid for param 0x88, or they are only valid for param 0x88. - */ - if (condtype >= 0x0B) { - /* Tests that ignore 'param' */ - switch (condtype) { - case 0x0B: result = !IsValidCargoType(GetCargoTypeByLabel(CargoLabel(std::byteswap(cond_val)))); - break; - case 0x0C: result = IsValidCargoType(GetCargoTypeByLabel(CargoLabel(std::byteswap(cond_val)))); - break; - case 0x0D: result = GetRailTypeByLabel(std::byteswap(cond_val)) == INVALID_RAILTYPE; - break; - case 0x0E: result = GetRailTypeByLabel(std::byteswap(cond_val)) != INVALID_RAILTYPE; - break; - case 0x0F: { - RoadType rt = GetRoadTypeByLabel(std::byteswap(cond_val)); - result = rt == INVALID_ROADTYPE || !RoadTypeIsRoad(rt); - break; - } - case 0x10: { - RoadType rt = GetRoadTypeByLabel(std::byteswap(cond_val)); - result = rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt); - break; - } - case 0x11: { - RoadType rt = GetRoadTypeByLabel(std::byteswap(cond_val)); - result = rt == INVALID_ROADTYPE || !RoadTypeIsTram(rt); - break; - } - case 0x12: { - RoadType rt = GetRoadTypeByLabel(std::byteswap(cond_val)); - result = rt != INVALID_ROADTYPE && RoadTypeIsTram(rt); - break; - } - default: GrfMsg(1, "SkipIf: Unsupported condition type {:02X}. Ignoring", condtype); return; - } - } else if (param == 0x88) { - /* GRF ID checks */ - - GRFConfig *c = GetGRFConfig(cond_val, mask); - - if (c != nullptr && c->flags.Test(GRFConfigFlag::Static) && !_cur.grfconfig->flags.Test(GRFConfigFlag::Static) && _networking) { - DisableStaticNewGRFInfluencingNonStaticNewGRFs(*c); - c = nullptr; - } - - if (condtype != 10 && c == nullptr) { - GrfMsg(7, "SkipIf: GRFID 0x{:08X} unknown, skipping test", std::byteswap(cond_val)); - return; - } - - switch (condtype) { - /* Tests 0x06 to 0x0A are only for param 0x88, GRFID checks */ - case 0x06: // Is GRFID active? - result = c->status == GCS_ACTIVATED; - break; - - case 0x07: // Is GRFID non-active? - result = c->status != GCS_ACTIVATED; - break; - - case 0x08: // GRFID is not but will be active? - result = c->status == GCS_INITIALISED; - break; - - case 0x09: // GRFID is or will be active? - result = c->status == GCS_ACTIVATED || c->status == GCS_INITIALISED; - break; - - case 0x0A: // GRFID is not nor will be active - /* This is the only condtype that doesn't get ignored if the GRFID is not found */ - result = c == nullptr || c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND; - break; - - default: GrfMsg(1, "SkipIf: Unsupported GRF condition type {:02X}. Ignoring", condtype); return; - } - } else { - /* Tests that use 'param' and are not GRF ID checks. */ - uint32_t param_val = GetParamVal(param, &cond_val); // cond_val is modified for param == 0x85 - switch (condtype) { - case 0x00: result = !!(param_val & (1 << cond_val)); - break; - case 0x01: result = !(param_val & (1 << cond_val)); - break; - case 0x02: result = (param_val & mask) == cond_val; - break; - case 0x03: result = (param_val & mask) != cond_val; - break; - case 0x04: result = (param_val & mask) < cond_val; - break; - case 0x05: result = (param_val & mask) > cond_val; - break; - default: GrfMsg(1, "SkipIf: Unsupported condition type {:02X}. Ignoring", condtype); return; - } - } - - if (!result) { - GrfMsg(2, "SkipIf: Not skipping sprites, test was false"); - return; - } - - uint8_t numsprites = buf.ReadByte(); - - /* numsprites can be a GOTO label if it has been defined in the GRF - * file. The jump will always be the first matching label that follows - * the current nfo_line. If no matching label is found, the first matching - * label in the file is used. */ - const GRFLabel *choice = nullptr; - for (const auto &label : _cur.grffile->labels) { - if (label.label != numsprites) continue; - - /* Remember a goto before the current line */ - if (choice == nullptr) choice = &label; - /* If we find a label here, this is definitely good */ - if (label.nfo_line > _cur.nfo_line) { - choice = &label; - break; - } - } - - if (choice != nullptr) { - GrfMsg(2, "SkipIf: Jumping to label 0x{:X} at line {}, test was true", choice->label, choice->nfo_line); - _cur.file->SeekTo(choice->pos, SEEK_SET); - _cur.nfo_line = choice->nfo_line; - return; - } - - GrfMsg(2, "SkipIf: Skipping {} sprites, test was true", numsprites); - _cur.skip_sprites = numsprites; - if (_cur.skip_sprites == 0) { - /* Zero means there are no sprites to skip, so - * we use -1 to indicate that all further - * sprites should be skipped. */ - _cur.skip_sprites = -1; - - /* If an action 8 hasn't been encountered yet, disable the grf. */ - if (_cur.grfconfig->status != (_cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED)) { - DisableGrf(); - } - } -} - - -/* Action 0x08 (GLS_FILESCAN) */ -static void ScanInfo(ByteReader &buf) -{ - uint8_t grf_version = buf.ReadByte(); - uint32_t grfid = buf.ReadDWord(); - std::string_view name = buf.ReadString(); - - _cur.grfconfig->ident.grfid = grfid; - - if (grf_version < 2 || grf_version > 8) { - _cur.grfconfig->flags.Set(GRFConfigFlag::Invalid); - Debug(grf, 0, "{}: NewGRF \"{}\" (GRFID {:08X}) uses GRF version {}, which is incompatible with this version of OpenTTD.", _cur.grfconfig->filename, StrMakeValid(name), std::byteswap(grfid), grf_version); - } - - /* GRF IDs starting with 0xFF are reserved for internal TTDPatch use */ - if (GB(grfid, 0, 8) == 0xFF) _cur.grfconfig->flags.Set(GRFConfigFlag::System); - - AddGRFTextToList(_cur.grfconfig->name, 0x7F, grfid, false, name); - - if (buf.HasData()) { - std::string_view info = buf.ReadString(); - AddGRFTextToList(_cur.grfconfig->info, 0x7F, grfid, true, info); - } - - /* GLS_INFOSCAN only looks for the action 8, so we can skip the rest of the file */ - _cur.skip_sprites = -1; -} - -/* Action 0x08 */ -static void GRFInfo(ByteReader &buf) -{ - /* <08> - * - * B version newgrf version, currently 06 - * 4*B grf-id globally unique ID of this .grf file - * S name name of this .grf set - * S info string describing the set, and e.g. author and copyright */ - - uint8_t version = buf.ReadByte(); - uint32_t grfid = buf.ReadDWord(); - std::string_view name = buf.ReadString(); - - if (_cur.stage < GLS_RESERVE && _cur.grfconfig->status != GCS_UNKNOWN) { - DisableGrf(STR_NEWGRF_ERROR_MULTIPLE_ACTION_8); - return; - } - - if (_cur.grffile->grfid != grfid) { - Debug(grf, 0, "GRFInfo: GRFID {:08X} in FILESCAN stage does not match GRFID {:08X} in INIT/RESERVE/ACTIVATION stage", std::byteswap(_cur.grffile->grfid), std::byteswap(grfid)); - _cur.grffile->grfid = grfid; - } - - _cur.grffile->grf_version = version; - _cur.grfconfig->status = _cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED; - - /* Do swap the GRFID for displaying purposes since people expect that */ - Debug(grf, 1, "GRFInfo: Loaded GRFv{} set {:08X} - {} (palette: {}, version: {})", version, std::byteswap(grfid), StrMakeValid(name), (_cur.grfconfig->palette & GRFP_USE_MASK) ? "Windows" : "DOS", _cur.grfconfig->version); -} - -/** - * Check if a sprite ID range is within the GRM reversed range for the currently loading NewGRF. - * @param first_sprite First sprite of range. - * @param num_sprites Number of sprites in the range. - * @return True iff the NewGRF has reserved a range equal to or greater than the provided range. - */ -static bool IsGRMReservedSprite(SpriteID first_sprite, uint16_t num_sprites) -{ - for (const auto &grm_sprite : _grm_sprites) { - if (grm_sprite.first.grfid != _cur.grffile->grfid) continue; - if (grm_sprite.second.first <= first_sprite && grm_sprite.second.first + grm_sprite.second.second >= first_sprite + num_sprites) return true; - } - return false; -} - -/* Action 0x0A */ -static void SpriteReplace(ByteReader &buf) -{ - /* <0A> [ ...] - * : - * - * B num-sets How many sets of sprites to replace. - * Each set: - * B num-sprites How many sprites are in this set - * W first-sprite First sprite number to replace */ - - uint8_t num_sets = buf.ReadByte(); - - for (uint i = 0; i < num_sets; i++) { - uint8_t num_sprites = buf.ReadByte(); - uint16_t first_sprite = buf.ReadWord(); - - GrfMsg(2, "SpriteReplace: [Set {}] Changing {} sprites, beginning with {}", - i, num_sprites, first_sprite - ); - - if (first_sprite + num_sprites >= SPR_OPENTTD_BASE) { - /* Outside allowed range, check for GRM sprite reservations. */ - if (!IsGRMReservedSprite(first_sprite, num_sprites)) { - GrfMsg(0, "SpriteReplace: [Set {}] Changing {} sprites, beginning with {}, above limit of {} and not within reserved range, ignoring.", - i, num_sprites, first_sprite, SPR_OPENTTD_BASE); - - /* Load the sprites at the current location so they will do nothing instead of appearing to work. */ - first_sprite = _cur.spriteid; - _cur.spriteid += num_sprites; - } - } - - for (uint j = 0; j < num_sprites; j++) { - SpriteID load_index = first_sprite + j; - _cur.nfo_line++; - LoadNextSprite(load_index, *_cur.file, _cur.nfo_line); // XXX - - /* Shore sprites now located at different addresses. - * So detect when the old ones get replaced. */ - if (IsInsideMM(load_index, SPR_ORIGINALSHORE_START, SPR_ORIGINALSHORE_END + 1)) { - if (_loaded_newgrf_features.shore != SHORE_REPLACE_ACTION_5) _loaded_newgrf_features.shore = SHORE_REPLACE_ACTION_A; - } - } - } -} - -/* Action 0x0A (SKIP) */ -static void SkipActA(ByteReader &buf) -{ - uint8_t num_sets = buf.ReadByte(); - - for (uint i = 0; i < num_sets; i++) { - /* Skip the sprites this replaces */ - _cur.skip_sprites += buf.ReadByte(); - /* But ignore where they go */ - buf.ReadWord(); - } - - GrfMsg(3, "SkipActA: Skipping {} sprites", _cur.skip_sprites); -} - -/* Action 0x0B */ -static void GRFLoadError(ByteReader &buf) -{ - /* <0B> [ 00] [] 00 [] - * - * B severity 00: notice, continue loading grf file - * 01: warning, continue loading grf file - * 02: error, but continue loading grf file, and attempt - * loading grf again when loading or starting next game - * 03: error, abort loading and prevent loading again in - * the future (only when restarting the patch) - * B language-id see action 4, use 1F for built-in error messages - * B message-id message to show, see below - * S message for custom messages (message-id FF), text of the message - * not present for built-in messages. - * V data additional data for built-in (or custom) messages - * B parnum parameter numbers to be shown in the message (maximum of 2) */ - - static const StringID msgstr[] = { - STR_NEWGRF_ERROR_VERSION_NUMBER, - STR_NEWGRF_ERROR_DOS_OR_WINDOWS, - STR_NEWGRF_ERROR_UNSET_SWITCH, - STR_NEWGRF_ERROR_INVALID_PARAMETER, - STR_NEWGRF_ERROR_LOAD_BEFORE, - STR_NEWGRF_ERROR_LOAD_AFTER, - STR_NEWGRF_ERROR_OTTD_VERSION_NUMBER, - }; - - static const StringID sevstr[] = { - STR_NEWGRF_ERROR_MSG_INFO, - STR_NEWGRF_ERROR_MSG_WARNING, - STR_NEWGRF_ERROR_MSG_ERROR, - STR_NEWGRF_ERROR_MSG_FATAL - }; - - uint8_t severity = buf.ReadByte(); - uint8_t lang = buf.ReadByte(); - uint8_t message_id = buf.ReadByte(); - - /* Skip the error if it isn't valid for the current language. */ - if (!CheckGrfLangID(lang, _cur.grffile->grf_version)) return; - - /* Skip the error until the activation stage unless bit 7 of the severity - * is set. */ - if (!HasBit(severity, 7) && _cur.stage == GLS_INIT) { - GrfMsg(7, "GRFLoadError: Skipping non-fatal GRFLoadError in stage {}", _cur.stage); - return; - } - ClrBit(severity, 7); - - if (severity >= lengthof(sevstr)) { - GrfMsg(7, "GRFLoadError: Invalid severity id {}. Setting to 2 (non-fatal error).", severity); - severity = 2; - } else if (severity == 3) { - /* This is a fatal error, so make sure the GRF is deactivated and no - * more of it gets loaded. */ - DisableGrf(); - - /* Make sure we show fatal errors, instead of silly infos from before */ - _cur.grfconfig->error.reset(); - } - - if (message_id >= lengthof(msgstr) && message_id != 0xFF) { - GrfMsg(7, "GRFLoadError: Invalid message id."); - return; - } - - if (buf.Remaining() <= 1) { - GrfMsg(7, "GRFLoadError: No message data supplied."); - return; - } - - /* For now we can only show one message per newgrf file. */ - if (_cur.grfconfig->error.has_value()) return; - - _cur.grfconfig->error = {sevstr[severity]}; - GRFError *error = &_cur.grfconfig->error.value(); - - if (message_id == 0xFF) { - /* This is a custom error message. */ - if (buf.HasData()) { - std::string_view message = buf.ReadString(); - - error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, SCC_RAW_STRING_POINTER); - } else { - GrfMsg(7, "GRFLoadError: No custom message supplied."); - error->custom_message.clear(); - } - } else { - error->message = msgstr[message_id]; - } - - if (buf.HasData()) { - std::string_view data = buf.ReadString(); - - error->data = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, data); - } else { - GrfMsg(7, "GRFLoadError: No message data supplied."); - error->data.clear(); - } - - /* Only two parameter numbers can be used in the string. */ - for (uint i = 0; i < error->param_value.size() && buf.HasData(); i++) { - uint param_number = buf.ReadByte(); - error->param_value[i] = _cur.grffile->GetParam(param_number); - } -} - -/* Action 0x0C */ -static void GRFComment(ByteReader &buf) -{ - /* <0C> [] - * - * V ignored Anything following the 0C is ignored */ - - if (!buf.HasData()) return; - - std::string_view text = buf.ReadString(); - GrfMsg(2, "GRFComment: {}", StrMakeValid(text)); -} - -/* Action 0x0D (GLS_SAFETYSCAN) */ -static void SafeParamSet(ByteReader &buf) -{ - uint8_t target = buf.ReadByte(); - - /* Writing GRF parameters and some bits of 'misc GRF features' are safe. */ - if (target < 0x80 || target == 0x9E) return; - - /* GRM could be unsafe, but as here it can only happen after other GRFs - * are loaded, it should be okay. If the GRF tried to use the slots it - * reserved, it would be marked unsafe anyway. GRM for (e.g. bridge) - * sprites is considered safe. */ - - _cur.grfconfig->flags.Set(GRFConfigFlag::Unsafe); - - /* Skip remainder of GRF */ - _cur.skip_sprites = -1; -} - - -static uint32_t GetPatchVariable(uint8_t param) -{ - switch (param) { - /* start year - 1920 */ - case 0x0B: return (std::max(_settings_game.game_creation.starting_year, CalendarTime::ORIGINAL_BASE_YEAR) - CalendarTime::ORIGINAL_BASE_YEAR).base(); - - /* freight trains weight factor */ - case 0x0E: return _settings_game.vehicle.freight_trains; - - /* empty wagon speed increase */ - case 0x0F: return 0; - - /* plane speed factor; our patch option is reversed from TTDPatch's, - * the following is good for 1x, 2x and 4x (most common?) and... - * well not really for 3x. */ - case 0x10: - switch (_settings_game.vehicle.plane_speed) { - default: - case 4: return 1; - case 3: return 2; - case 2: return 2; - case 1: return 4; - } - - - /* 2CC colourmap base sprite */ - case 0x11: return SPR_2CCMAP_BASE; - - /* map size: format = -MABXYSS - * M : the type of map - * bit 0 : set : squared map. Bit 1 is now not relevant - * clear : rectangle map. Bit 1 will indicate the bigger edge of the map - * bit 1 : set : Y is the bigger edge. Bit 0 is clear - * clear : X is the bigger edge. - * A : minimum edge(log2) of the map - * B : maximum edge(log2) of the map - * XY : edges(log2) of each side of the map. - * SS : combination of both X and Y, thus giving the size(log2) of the map - */ - case 0x13: { - uint8_t map_bits = 0; - uint8_t log_X = Map::LogX() - 6; // subtraction is required to make the minimal size (64) zero based - uint8_t log_Y = Map::LogY() - 6; - uint8_t max_edge = std::max(log_X, log_Y); - - if (log_X == log_Y) { // we have a squared map, since both edges are identical - SetBit(map_bits, 0); - } else { - if (max_edge == log_Y) SetBit(map_bits, 1); // edge Y been the biggest, mark it - } - - return (map_bits << 24) | (std::min(log_X, log_Y) << 20) | (max_edge << 16) | - (log_X << 12) | (log_Y << 8) | (log_X + log_Y); - } - - /* The maximum height of the map. */ - case 0x14: - return _settings_game.construction.map_height_limit; - - /* Extra foundations base sprite */ - case 0x15: - return SPR_SLOPES_BASE; - - /* Shore base sprite */ - case 0x16: - return SPR_SHORE_BASE; - - /* Game map seed */ - case 0x17: - return _settings_game.game_creation.generation_seed; - - default: - GrfMsg(2, "ParamSet: Unknown Patch variable 0x{:02X}.", param); - return 0; - } -} - - -static uint32_t PerformGRM(std::span grm, uint16_t count, uint8_t op, uint8_t target, const char *type) -{ - uint start = 0; - uint size = 0; - - if (op == 6) { - /* Return GRFID of set that reserved ID */ - return grm[_cur.grffile->GetParam(target)]; - } - - /* With an operation of 2 or 3, we want to reserve a specific block of IDs */ - if (op == 2 || op == 3) start = _cur.grffile->GetParam(target); - - for (uint i = start; i < std::size(grm); i++) { - if (grm[i] == 0) { - size++; - } else { - if (op == 2 || op == 3) break; - start = i + 1; - size = 0; - } - - if (size == count) break; - } - - if (size == count) { - /* Got the slot... */ - if (op == 0 || op == 3) { - GrfMsg(2, "ParamSet: GRM: Reserving {} {} at {}", count, type, start); - for (uint i = 0; i < count; i++) grm[start + i] = _cur.grffile->grfid; - } - return start; - } - - /* Unable to allocate */ - if (op != 4 && op != 5) { - /* Deactivate GRF */ - GrfMsg(0, "ParamSet: GRM: Unable to allocate {} {}, deactivating", count, type); - DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED); - return UINT_MAX; - } - - GrfMsg(1, "ParamSet: GRM: Unable to allocate {} {}", count, type); - return UINT_MAX; -} - - -/** Action 0x0D: Set parameter */ -static void ParamSet(ByteReader &buf) -{ - /* <0D> [] - * - * B target parameter number where result is stored - * B operation operation to perform, see below - * B source1 first source operand - * B source2 second source operand - * D data data to use in the calculation, not necessary - * if both source1 and source2 refer to actual parameters - * - * Operations - * 00 Set parameter equal to source1 - * 01 Addition, source1 + source2 - * 02 Subtraction, source1 - source2 - * 03 Unsigned multiplication, source1 * source2 (both unsigned) - * 04 Signed multiplication, source1 * source2 (both signed) - * 05 Unsigned bit shift, source1 by source2 (source2 taken to be a - * signed quantity; left shift if positive and right shift if - * negative, source1 is unsigned) - * 06 Signed bit shift, source1 by source2 - * (source2 like in 05, and source1 as well) - */ - - uint8_t target = buf.ReadByte(); - uint8_t oper = buf.ReadByte(); - uint32_t src1 = buf.ReadByte(); - uint32_t src2 = buf.ReadByte(); - - uint32_t data = 0; - if (buf.Remaining() >= 4) data = buf.ReadDWord(); - - /* You can add 80 to the operation to make it apply only if the target - * is not defined yet. In this respect, a parameter is taken to be - * defined if any of the following applies: - * - it has been set to any value in the newgrf(w).cfg parameter list - * - it OR A PARAMETER WITH HIGHER NUMBER has been set to any value by - * an earlier action D */ - if (HasBit(oper, 7)) { - if (target < 0x80 && target < std::size(_cur.grffile->param)) { - GrfMsg(7, "ParamSet: Param {} already defined, skipping", target); - return; - } - - oper = GB(oper, 0, 7); - } - - if (src2 == 0xFE) { - if (GB(data, 0, 8) == 0xFF) { - if (data == 0x0000FFFF) { - /* Patch variables */ - src1 = GetPatchVariable(src1); - } else { - /* GRF Resource Management */ - uint8_t op = src1; - uint8_t feature = GB(data, 8, 8); - uint16_t count = GB(data, 16, 16); - - if (_cur.stage == GLS_RESERVE) { - if (feature == 0x08) { - /* General sprites */ - if (op == 0) { - /* Check if the allocated sprites will fit below the original sprite limit */ - if (_cur.spriteid + count >= 16384) { - GrfMsg(0, "ParamSet: GRM: Unable to allocate {} sprites; try changing NewGRF order", count); - DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED); - return; - } - - /* Reserve space at the current sprite ID */ - GrfMsg(4, "ParamSet: GRM: Allocated {} sprites at {}", count, _cur.spriteid); - _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)] = std::make_pair(_cur.spriteid, count); - _cur.spriteid += count; - } - } - /* Ignore GRM result during reservation */ - src1 = 0; - } else if (_cur.stage == GLS_ACTIVATION) { - switch (feature) { - case 0x00: // Trains - case 0x01: // Road Vehicles - case 0x02: // Ships - case 0x03: // Aircraft - if (!_settings_game.vehicle.dynamic_engines) { - src1 = PerformGRM({std::begin(_grm_engines) + _engine_offsets[feature], _engine_counts[feature]}, count, op, target, "vehicles"); - if (_cur.skip_sprites == -1) return; - } else { - /* GRM does not apply for dynamic engine allocation. */ - switch (op) { - case 2: - case 3: - src1 = _cur.grffile->GetParam(target); - break; - - default: - src1 = 0; - break; - } - } - break; - - case 0x08: // General sprites - switch (op) { - case 0: - /* Return space reserved during reservation stage */ - src1 = _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)].first; - GrfMsg(4, "ParamSet: GRM: Using pre-allocated sprites at {}", src1); - break; - - case 1: - src1 = _cur.spriteid; - break; - - default: - GrfMsg(1, "ParamSet: GRM: Unsupported operation {} for general sprites", op); - return; - } - break; - - case 0x0B: // Cargo - /* There are two ranges: one for cargo IDs and one for cargo bitmasks */ - src1 = PerformGRM(_grm_cargoes, count, op, target, "cargoes"); - if (_cur.skip_sprites == -1) return; - break; - - default: GrfMsg(1, "ParamSet: GRM: Unsupported feature 0x{:X}", feature); return; - } - } else { - /* Ignore GRM during initialization */ - src1 = 0; - } - } - } else { - /* Read another GRF File's parameter */ - const GRFFile *file = GetFileByGRFID(data); - GRFConfig *c = GetGRFConfig(data); - if (c != nullptr && c->flags.Test(GRFConfigFlag::Static) && !_cur.grfconfig->flags.Test(GRFConfigFlag::Static) && _networking) { - /* Disable the read GRF if it is a static NewGRF. */ - DisableStaticNewGRFInfluencingNonStaticNewGRFs(*c); - src1 = 0; - } else if (file == nullptr || c == nullptr || c->status == GCS_DISABLED) { - src1 = 0; - } else if (src1 == 0xFE) { - src1 = c->version; - } else { - src1 = file->GetParam(src1); - } - } - } else { - /* The source1 and source2 operands refer to the grf parameter number - * like in action 6 and 7. In addition, they can refer to the special - * variables available in action 7, or they can be FF to use the value - * of . If referring to parameters that are undefined, a value - * of 0 is used instead. */ - src1 = (src1 == 0xFF) ? data : GetParamVal(src1, nullptr); - src2 = (src2 == 0xFF) ? data : GetParamVal(src2, nullptr); - } - - uint32_t res; - switch (oper) { - case 0x00: - res = src1; - break; - - case 0x01: - res = src1 + src2; - break; - - case 0x02: - res = src1 - src2; - break; - - case 0x03: - res = src1 * src2; - break; - - case 0x04: - res = (int32_t)src1 * (int32_t)src2; - break; - - case 0x05: - if ((int32_t)src2 < 0) { - res = src1 >> -(int32_t)src2; - } else { - res = src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures. - } - break; - - case 0x06: - if ((int32_t)src2 < 0) { - res = (int32_t)src1 >> -(int32_t)src2; - } else { - res = (int32_t)src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures. - } - break; - - case 0x07: // Bitwise AND - res = src1 & src2; - break; - - case 0x08: // Bitwise OR - res = src1 | src2; - break; - - case 0x09: // Unsigned division - if (src2 == 0) { - res = src1; - } else { - res = src1 / src2; - } - break; - - case 0x0A: // Signed division - if (src2 == 0) { - res = src1; - } else { - res = (int32_t)src1 / (int32_t)src2; - } - break; - - case 0x0B: // Unsigned modulo - if (src2 == 0) { - res = src1; - } else { - res = src1 % src2; - } - break; - - case 0x0C: // Signed modulo - if (src2 == 0) { - res = src1; - } else { - res = (int32_t)src1 % (int32_t)src2; - } - break; - - default: GrfMsg(0, "ParamSet: Unknown operation {}, skipping", oper); return; - } - - switch (target) { - case 0x8E: // Y-Offset for train sprites - _cur.grffile->traininfo_vehicle_pitch = res; - break; - - case 0x8F: { // Rail track type cost factors - extern RailTypeInfo _railtypes[RAILTYPE_END]; - _railtypes[RAILTYPE_RAIL].cost_multiplier = GB(res, 0, 8); - if (_settings_game.vehicle.disable_elrails) { - _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 0, 8); - _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 8, 8); - } else { - _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 8, 8); - _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 16, 8); - } - _railtypes[RAILTYPE_MAGLEV].cost_multiplier = GB(res, 16, 8); - break; - } - - /* not implemented */ - case 0x93: // Tile refresh offset to left -- Intended to allow support for larger sprites, not necessary for OTTD - case 0x94: // Tile refresh offset to right - case 0x95: // Tile refresh offset upwards - case 0x96: // Tile refresh offset downwards - 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 - case 0x99: // Global ID offset -- Not necessary since IDs are remapped automatically - GrfMsg(7, "ParamSet: Skipping unimplemented target 0x{:02X}", target); - break; - - case 0x9E: { // Miscellaneous GRF features - GrfMiscBits bits(res); - - /* Set train list engine width */ - _cur.grffile->traininfo_vehicle_width = bits.Test(GrfMiscBit::TrainWidth32Pixels) ? VEHICLEINFO_FULL_VEHICLE_WIDTH : TRAININFO_DEFAULT_VEHICLE_WIDTH; - /* Remove the local flags from the global flags */ - bits.Reset(GrfMiscBit::TrainWidth32Pixels); - - /* Only copy safe bits for static grfs */ - if (_cur.grfconfig->flags.Test(GRFConfigFlag::Static)) { - GrfMiscBits safe_bits = GrfMiscBit::SecondRockyTileSet; - - _misc_grf_features.Reset(safe_bits); - _misc_grf_features.Set(bits & safe_bits); - } else { - _misc_grf_features = bits; - } - break; - } - - case 0x9F: // locale-dependent settings - GrfMsg(7, "ParamSet: Skipping unimplemented target 0x{:02X}", target); - break; - - default: - if (target < 0x80) { - /* Resize (and fill with zeroes) if needed. */ - if (target >= std::size(_cur.grffile->param)) _cur.grffile->param.resize(target + 1); - _cur.grffile->param[target] = res; - } else { - GrfMsg(7, "ParamSet: Skipping unknown target 0x{:02X}", target); - } - break; - } -} - -/* Action 0x0E (GLS_SAFETYSCAN) */ -static void SafeGRFInhibit(ByteReader &buf) -{ - /* <0E> - * - * B num Number of GRFIDs that follow - * D grfids GRFIDs of the files to deactivate */ - - uint8_t num = buf.ReadByte(); - - for (uint i = 0; i < num; i++) { - uint32_t grfid = buf.ReadDWord(); - - /* GRF is unsafe it if tries to deactivate other GRFs */ - if (grfid != _cur.grfconfig->ident.grfid) { - _cur.grfconfig->flags.Set(GRFConfigFlag::Unsafe); - - /* Skip remainder of GRF */ - _cur.skip_sprites = -1; - - return; - } - } -} - -/* Action 0x0E */ -static void GRFInhibit(ByteReader &buf) -{ - /* <0E> - * - * B num Number of GRFIDs that follow - * D grfids GRFIDs of the files to deactivate */ - - uint8_t num = buf.ReadByte(); - - for (uint i = 0; i < num; i++) { - uint32_t grfid = buf.ReadDWord(); - GRFConfig *file = GetGRFConfig(grfid); - - /* Unset activation flag */ - if (file != nullptr && file != _cur.grfconfig) { - GrfMsg(2, "GRFInhibit: Deactivating file '{}'", file->filename); - GRFError *error = DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED, file); - error->data = _cur.grfconfig->GetName(); - } - } -} - -/** Action 0x0F - Define Town names */ -static void FeatureTownName(ByteReader &buf) -{ - /* <0F> - * - * B id ID of this definition in bottom 7 bits (final definition if bit 7 set) - * V style-name Name of the style (only for final definition) - * B num-parts Number of parts in this definition - * V parts The parts */ - - uint32_t grfid = _cur.grffile->grfid; - - GRFTownName *townname = AddGRFTownName(grfid); - - uint8_t id = buf.ReadByte(); - GrfMsg(6, "FeatureTownName: definition 0x{:02X}", id & 0x7F); - - if (HasBit(id, 7)) { - /* Final definition */ - ClrBit(id, 7); - bool new_scheme = _cur.grffile->grf_version >= 7; - - uint8_t lang = buf.ReadByte(); - StringID style = STR_UNDEFINED; - - do { - ClrBit(lang, 7); - - std::string_view name = buf.ReadString(); - - std::string lang_name = TranslateTTDPatchCodes(grfid, lang, false, name); - GrfMsg(6, "FeatureTownName: lang 0x{:X} -> '{}'", lang, lang_name); - - style = AddGRFString(grfid, GRFStringID{id}, lang, new_scheme, false, name, STR_UNDEFINED); - - lang = buf.ReadByte(); - } while (lang != 0); - townname->styles.emplace_back(style, id); - } - - uint8_t parts = buf.ReadByte(); - GrfMsg(6, "FeatureTownName: {} parts", parts); - - townname->partlists[id].reserve(parts); - for (uint partnum = 0; partnum < parts; partnum++) { - NamePartList &partlist = townname->partlists[id].emplace_back(); - uint8_t texts = buf.ReadByte(); - partlist.bitstart = buf.ReadByte(); - partlist.bitcount = buf.ReadByte(); - partlist.maxprob = 0; - GrfMsg(6, "FeatureTownName: part {} contains {} texts and will use GB(seed, {}, {})", partnum, texts, partlist.bitstart, partlist.bitcount); - - partlist.parts.reserve(texts); - for (uint textnum = 0; textnum < texts; textnum++) { - NamePart &part = partlist.parts.emplace_back(); - part.prob = buf.ReadByte(); - - if (HasBit(part.prob, 7)) { - uint8_t ref_id = buf.ReadByte(); - if (ref_id >= GRFTownName::MAX_LISTS || townname->partlists[ref_id].empty()) { - GrfMsg(0, "FeatureTownName: definition 0x{:02X} doesn't exist, deactivating", ref_id); - DelGRFTownName(grfid); - DisableGrf(STR_NEWGRF_ERROR_INVALID_ID); - return; - } - part.id = ref_id; - GrfMsg(6, "FeatureTownName: part {}, text {}, uses intermediate definition 0x{:02X} (with probability {})", partnum, textnum, ref_id, part.prob & 0x7F); - } else { - std::string_view text = buf.ReadString(); - part.text = TranslateTTDPatchCodes(grfid, 0, false, text); - GrfMsg(6, "FeatureTownName: part {}, text {}, '{}' (with probability {})", partnum, textnum, part.text, part.prob); - } - partlist.maxprob += GB(part.prob, 0, 7); - } - GrfMsg(6, "FeatureTownName: part {}, total probability {}", partnum, partlist.maxprob); - } -} - -/** Action 0x10 - Define goto label */ -static void DefineGotoLabel(ByteReader &buf) -{ - /* <10>