OpenTTD Source  20240917-master-g9ab0a47812
newgrf.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #include "stdafx.h"
11 
12 #include "core/backup_type.hpp"
13 #include "core/container_func.hpp"
14 #include "debug.h"
15 #include "fileio_func.h"
16 #include "engine_func.h"
17 #include "engine_base.h"
18 #include "bridge.h"
19 #include "town.h"
20 #include "newgrf_engine.h"
21 #include "newgrf_text.h"
22 #include "fontcache.h"
23 #include "currency.h"
24 #include "landscape.h"
25 #include "newgrf_cargo.h"
26 #include "newgrf_house.h"
27 #include "newgrf_sound.h"
28 #include "newgrf_station.h"
29 #include "industrytype.h"
30 #include "industry_map.h"
31 #include "newgrf_act5.h"
32 #include "newgrf_canal.h"
33 #include "newgrf_townname.h"
34 #include "newgrf_industries.h"
35 #include "newgrf_airporttiles.h"
36 #include "newgrf_airport.h"
37 #include "newgrf_object.h"
38 #include "rev.h"
39 #include "fios.h"
40 #include "strings_func.h"
41 #include "timer/timer_game_tick.h"
43 #include "string_func.h"
44 #include "network/core/config.h"
45 #include "smallmap_gui.h"
46 #include "genworld.h"
47 #include "error.h"
48 #include "error_func.h"
49 #include "vehicle_func.h"
50 #include "language.h"
51 #include "vehicle_base.h"
52 #include "road.h"
53 #include "newgrf_roadstop.h"
54 
55 #include "table/strings.h"
56 #include "table/build_industry.h"
57 
58 #include "safeguards.h"
59 
60 /* TTDPatch extended GRF format codec
61  * (c) Petr Baudis 2004 (GPL'd)
62  * Changes by Florian octo Forster are (c) by the OpenTTD development team.
63  *
64  * Contains portions of documentation by TTDPatch team.
65  * Thanks especially to Josef Drexler for the documentation as well as a lot
66  * of help at #tycoon. Also thanks to Michael Blunck for his GRF files which
67  * served as subject to the initial testing of this codec. */
68 
70 static std::vector<GRFFile *> _grf_files;
71 
72 const std::vector<GRFFile *> &GetAllGRFFiles()
73 {
74  return _grf_files;
75 }
76 
78 uint8_t _misc_grf_features = 0;
79 
81 static uint32_t _ttdpatch_flags[8];
82 
85 
86 static const uint MAX_SPRITEGROUP = UINT8_MAX;
87 
90 private:
92  struct SpriteSet {
94  uint num_sprites;
95  };
96 
98  std::map<uint, SpriteSet> spritesets[GSF_END];
99 
100 public:
101  /* Global state */
102  GrfLoadingStage stage;
104 
105  /* Local state in the file */
109  uint32_t nfo_line;
110 
111  /* Kind of return values when processing certain actions */
113 
114  /* Currently referenceable spritegroups */
115  const SpriteGroup *spritegroups[MAX_SPRITEGROUP + 1];
116 
119  {
120  this->nfo_line = 0;
121  this->skip_sprites = 0;
122 
123  for (uint i = 0; i < GSF_END; i++) {
124  this->spritesets[i].clear();
125  }
126 
127  memset(this->spritegroups, 0, sizeof(this->spritegroups));
128  }
129 
138  void AddSpriteSets(uint8_t feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
139  {
140  assert(feature < GSF_END);
141  for (uint i = 0; i < numsets; i++) {
142  SpriteSet &set = this->spritesets[feature][first_set + i];
143  set.sprite = first_sprite + i * numents;
144  set.num_sprites = numents;
145  }
146  }
147 
154  bool HasValidSpriteSets(uint8_t feature) const
155  {
156  assert(feature < GSF_END);
157  return !this->spritesets[feature].empty();
158  }
159 
167  bool IsValidSpriteSet(uint8_t feature, uint set) const
168  {
169  assert(feature < GSF_END);
170  return this->spritesets[feature].find(set) != this->spritesets[feature].end();
171  }
172 
179  SpriteID GetSprite(uint8_t feature, uint set) const
180  {
181  assert(IsValidSpriteSet(feature, set));
182  return this->spritesets[feature].find(set)->second.sprite;
183  }
184 
191  uint GetNumEnts(uint8_t feature, uint set) const
192  {
193  assert(IsValidSpriteSet(feature, set));
194  return this->spritesets[feature].find(set)->second.num_sprites;
195  }
196 };
197 
198 static GrfProcessingState _cur;
199 
200 
207 template <VehicleType T>
208 static inline bool IsValidNewGRFImageIndex(uint8_t image_index)
209 {
210  return image_index == 0xFD || IsValidImageIndex<T>(image_index);
211 }
212 
214 
216 class ByteReader {
217 protected:
218  uint8_t *data;
219  uint8_t *end;
220 
221 public:
222  ByteReader(uint8_t *data, uint8_t *end) : data(data), end(end) { }
223 
224  inline uint8_t *ReadBytes(size_t size)
225  {
226  if (data + size >= end) {
227  /* Put data at the end, as would happen if every byte had been individually read. */
228  data = end;
229  throw OTTDByteReaderSignal();
230  }
231 
232  uint8_t *ret = data;
233  data += size;
234  return ret;
235  }
236 
237  inline uint8_t ReadByte()
238  {
239  if (data < end) return *(data)++;
240  throw OTTDByteReaderSignal();
241  }
242 
243  uint16_t ReadWord()
244  {
245  uint16_t val = ReadByte();
246  return val | (ReadByte() << 8);
247  }
248 
249  uint16_t ReadExtendedByte()
250  {
251  uint16_t val = ReadByte();
252  return val == 0xFF ? ReadWord() : val;
253  }
254 
255  uint32_t ReadDWord()
256  {
257  uint32_t val = ReadWord();
258  return val | (ReadWord() << 16);
259  }
260 
261  uint32_t PeekDWord()
262  {
263  AutoRestoreBackup backup(this->data, this->data);
264  return this->ReadDWord();
265  }
266 
267  uint32_t ReadVarSize(uint8_t size)
268  {
269  switch (size) {
270  case 1: return ReadByte();
271  case 2: return ReadWord();
272  case 4: return ReadDWord();
273  default:
274  NOT_REACHED();
275  return 0;
276  }
277  }
278 
279  std::string_view ReadString()
280  {
281  char *string = reinterpret_cast<char *>(data);
282  size_t string_length = ttd_strnlen(string, Remaining());
283 
284  /* Skip past the terminating NUL byte if it is present, but not more than remaining. */
285  Skip(std::min(string_length + 1, Remaining()));
286 
287  return std::string_view(string, string_length);
288  }
289 
290  inline size_t Remaining() const
291  {
292  return end - data;
293  }
294 
295  inline bool HasData(size_t count = 1) const
296  {
297  return data + count <= end;
298  }
299 
300  inline void Skip(size_t len)
301  {
302  data += len;
303  /* It is valid to move the buffer to exactly the end of the data,
304  * as there may not be any more data read. */
305  if (data > end) throw OTTDByteReaderSignal();
306  }
307 };
308 
309 typedef void (*SpecialSpriteHandler)(ByteReader &buf);
310 
312 static const uint NUM_STATIONS_PER_GRF = UINT16_MAX - 1;
313 
318  UNSET = 0,
321  };
322 
323  CargoClasses cargo_allowed;
324  CargoClasses cargo_disallowed;
325  RailTypeLabel railtypelabel;
326  uint8_t roadtramtype;
329  uint8_t rv_max_speed;
330  CargoTypes ctt_include_mask;
331  CargoTypes ctt_exclude_mask;
332 
337  void UpdateRefittability(bool non_empty)
338  {
339  if (non_empty) {
340  this->refittability = NONEMPTY;
341  } else if (this->refittability == UNSET) {
342  this->refittability = EMPTY;
343  }
344  }
345 };
346 
347 static std::vector<GRFTempEngineData> _gted;
348 
353 static uint32_t _grm_engines[256];
354 
356 static uint32_t _grm_cargoes[NUM_CARGO * 2];
357 
358 struct GRFLocation {
359  uint32_t grfid;
360  uint32_t nfoline;
361 
362  GRFLocation(uint32_t grfid, uint32_t nfoline) : grfid(grfid), nfoline(nfoline) { }
363 
364  bool operator<(const GRFLocation &other) const
365  {
366  return this->grfid < other.grfid || (this->grfid == other.grfid && this->nfoline < other.nfoline);
367  }
368 
369  bool operator == (const GRFLocation &other) const
370  {
371  return this->grfid == other.grfid && this->nfoline == other.nfoline;
372  }
373 };
374 
375 static std::map<GRFLocation, std::pair<SpriteID, uint16_t>> _grm_sprites;
376 typedef std::map<GRFLocation, std::vector<uint8_t>> GRFLineToSpriteOverride;
377 static GRFLineToSpriteOverride _grf_line_to_action6_sprite_override;
378 
389 void GrfMsgI(int severity, const std::string &msg)
390 {
391  Debug(grf, severity, "[{}:{}] {}", _cur.grfconfig->filename, _cur.nfo_line, msg);
392 }
393 
399 static GRFFile *GetFileByGRFID(uint32_t grfid)
400 {
401  for (GRFFile * const file : _grf_files) {
402  if (file->grfid == grfid) return file;
403  }
404  return nullptr;
405 }
406 
412 static GRFFile *GetFileByFilename(const std::string &filename)
413 {
414  for (GRFFile * const file : _grf_files) {
415  if (file->filename == filename) return file;
416  }
417  return nullptr;
418 }
419 
422 {
423  gf->labels.clear();
424 }
425 
432 static GRFError *DisableGrf(StringID message = STR_NULL, GRFConfig *config = nullptr)
433 {
434  GRFFile *file;
435  if (config != nullptr) {
436  file = GetFileByGRFID(config->ident.grfid);
437  } else {
438  config = _cur.grfconfig;
439  file = _cur.grffile;
440  }
441 
442  config->status = GCS_DISABLED;
443  if (file != nullptr) ClearTemporaryNewGRFData(file);
444  if (config == _cur.grfconfig) _cur.skip_sprites = -1;
445 
446  if (message == STR_NULL) return nullptr;
447 
448  config->error = {STR_NEWGRF_ERROR_MSG_FATAL, message};
449  if (config == _cur.grfconfig) config->error->param_value[0] = _cur.nfo_line;
450  return &config->error.value();
451 }
452 
457  uint32_t grfid;
459  std::function<void(StringID)> func;
460 
461  StringIDMapping(uint32_t grfid, StringID source, std::function<void(StringID)> &&func) : grfid(grfid), source(source), func(std::move(func)) { }
462 };
463 
465 static std::vector<StringIDMapping> _string_to_grf_mapping;
466 
472 static void AddStringForMapping(StringID source, std::function<void(StringID)> &&func)
473 {
474  func(STR_UNDEFINED);
475  _string_to_grf_mapping.emplace_back(_cur.grffile->grfid, source, std::move(func));
476 }
477 
483 static void AddStringForMapping(StringID source, StringID *target)
484 {
485  AddStringForMapping(source, [target](StringID str) { *target = str; });
486 }
487 
496 {
497  /* StringID table for TextIDs 0x4E->0x6D */
498  static const StringID units_volume[] = {
499  STR_ITEMS, STR_PASSENGERS, STR_TONS, STR_BAGS,
500  STR_LITERS, STR_ITEMS, STR_CRATES, STR_TONS,
501  STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
502  STR_TONS, STR_TONS, STR_TONS, STR_BAGS,
503  STR_TONS, STR_TONS, STR_BAGS, STR_LITERS,
504  STR_TONS, STR_LITERS, STR_TONS, STR_ITEMS,
505  STR_BAGS, STR_LITERS, STR_TONS, STR_ITEMS,
506  STR_TONS, STR_ITEMS, STR_LITERS, STR_ITEMS
507  };
508 
509  /* A string straight from a NewGRF; this was already translated by MapGRFStringID(). */
510  assert(!IsInsideMM(str, 0xD000, 0xD7FF));
511 
512 #define TEXTID_TO_STRINGID(begin, end, stringid, stringend) \
513  static_assert(stringend - stringid == end - begin); \
514  if (str >= begin && str <= end) return str + (stringid - begin)
515 
516  /* We have some changes in our cargo strings, resulting in some missing. */
517  TEXTID_TO_STRINGID(0x000E, 0x002D, STR_CARGO_PLURAL_NOTHING, STR_CARGO_PLURAL_FIZZY_DRINKS);
518  TEXTID_TO_STRINGID(0x002E, 0x004D, STR_CARGO_SINGULAR_NOTHING, STR_CARGO_SINGULAR_FIZZY_DRINK);
519  if (str >= 0x004E && str <= 0x006D) return units_volume[str - 0x004E];
520  TEXTID_TO_STRINGID(0x006E, 0x008D, STR_QUANTITY_NOTHING, STR_QUANTITY_FIZZY_DRINKS);
521  TEXTID_TO_STRINGID(0x008E, 0x00AD, STR_ABBREV_NOTHING, STR_ABBREV_FIZZY_DRINKS);
522  TEXTID_TO_STRINGID(0x00D1, 0x00E0, STR_COLOUR_DARK_BLUE, STR_COLOUR_WHITE);
523 
524  /* Map building names according to our lang file changes. There are several
525  * ranges of house ids, all of which need to be remapped to allow newgrfs
526  * to use original house names. */
527  TEXTID_TO_STRINGID(0x200F, 0x201F, STR_TOWN_BUILDING_NAME_TALL_OFFICE_BLOCK_1, STR_TOWN_BUILDING_NAME_OLD_HOUSES_1);
528  TEXTID_TO_STRINGID(0x2036, 0x2041, STR_TOWN_BUILDING_NAME_COTTAGES_1, STR_TOWN_BUILDING_NAME_SHOPPING_MALL_1);
529  TEXTID_TO_STRINGID(0x2059, 0x205C, STR_TOWN_BUILDING_NAME_IGLOO_1, STR_TOWN_BUILDING_NAME_PIGGY_BANK_1);
530 
531  /* Same thing for industries */
532  TEXTID_TO_STRINGID(0x4802, 0x4826, STR_INDUSTRY_NAME_COAL_MINE, STR_INDUSTRY_NAME_SUGAR_MINE);
533  TEXTID_TO_STRINGID(0x482D, 0x482E, STR_NEWS_INDUSTRY_CONSTRUCTION, STR_NEWS_INDUSTRY_PLANTED);
534  TEXTID_TO_STRINGID(0x4832, 0x4834, STR_NEWS_INDUSTRY_CLOSURE_GENERAL, STR_NEWS_INDUSTRY_CLOSURE_LACK_OF_TREES);
535  TEXTID_TO_STRINGID(0x4835, 0x4838, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_INCREASE_FARM);
536  TEXTID_TO_STRINGID(0x4839, 0x483A, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_GENERAL, STR_NEWS_INDUSTRY_PRODUCTION_DECREASE_FARM);
537 
538  switch (str) {
539  case 0x4830: return STR_ERROR_CAN_T_CONSTRUCT_THIS_INDUSTRY;
540  case 0x4831: return STR_ERROR_FOREST_CAN_ONLY_BE_PLANTED;
541  case 0x483B: return STR_ERROR_CAN_ONLY_BE_POSITIONED;
542  }
543 #undef TEXTID_TO_STRINGID
544 
545  if (str == STR_NULL) return STR_EMPTY;
546 
547  Debug(grf, 0, "Unknown StringID 0x{:04X} remapped to STR_EMPTY. Please open a Feature Request if you need it", str);
548 
549  return STR_EMPTY;
550 }
551 
559 StringID MapGRFStringID(uint32_t grfid, StringID str)
560 {
561  if (IsInsideMM(str, 0xD800, 0x10000)) {
562  /* General text provided by NewGRF.
563  * In the specs this is called the 0xDCxx range (misc persistent texts),
564  * but we meanwhile extended the range to 0xD800-0xFFFF.
565  * Note: We are not involved in the "persistent" business, since we do not store
566  * any NewGRF strings in savegames. */
567  return GetGRFStringID(grfid, str);
568  } else if (IsInsideMM(str, 0xD000, 0xD800)) {
569  /* Callback text provided by NewGRF.
570  * In the specs this is called the 0xD0xx range (misc graphics texts).
571  * These texts can be returned by various callbacks.
572  *
573  * Due to how TTDP implements the GRF-local- to global-textid translation
574  * texts included via 0x80 or 0x81 control codes have to add 0x400 to the textid.
575  * We do not care about that difference and just mask out the 0x400 bit.
576  */
577  str &= ~0x400;
578  return GetGRFStringID(grfid, str);
579  } else {
580  /* The NewGRF wants to include/reference an original TTD string.
581  * Try our best to find an equivalent one. */
583  }
584 }
585 
586 static std::map<uint32_t, uint32_t> _grf_id_overrides;
587 
593 static void SetNewGRFOverride(uint32_t source_grfid, uint32_t target_grfid)
594 {
595  if (target_grfid == 0) {
596  _grf_id_overrides.erase(source_grfid);
597  GrfMsg(5, "SetNewGRFOverride: Removed override of 0x{:X}", BSWAP32(source_grfid));
598  } else {
599  _grf_id_overrides[source_grfid] = target_grfid;
600  GrfMsg(5, "SetNewGRFOverride: Added override of 0x{:X} to 0x{:X}", BSWAP32(source_grfid), BSWAP32(target_grfid));
601  }
602 }
603 
612 static Engine *GetNewEngine(const GRFFile *file, VehicleType type, uint16_t internal_id, bool static_access = false)
613 {
614  /* Hack for add-on GRFs that need to modify another GRF's engines. This lets
615  * them use the same engine slots. */
616  uint32_t scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
618  /* If dynamic_engies is enabled, there can be multiple independent ID ranges. */
619  scope_grfid = file->grfid;
620  if (auto it = _grf_id_overrides.find(file->grfid); it != std::end(_grf_id_overrides)) {
621  scope_grfid = it->second;
622  const GRFFile *grf_match = GetFileByGRFID(scope_grfid);
623  if (grf_match == nullptr) {
624  GrfMsg(5, "Tried mapping from GRFID {:x} to {:x} but target is not loaded", BSWAP32(file->grfid), BSWAP32(scope_grfid));
625  } else {
626  GrfMsg(5, "Mapping from GRFID {:x} to {:x}", BSWAP32(file->grfid), BSWAP32(scope_grfid));
627  }
628  }
629 
630  /* Check if the engine is registered in the override manager */
631  EngineID engine = _engine_mngr.GetID(type, internal_id, scope_grfid);
632  if (engine != INVALID_ENGINE) {
633  Engine *e = Engine::Get(engine);
634  if (e->grf_prop.grffile == nullptr) e->grf_prop.grffile = file;
635  return e;
636  }
637  }
638 
639  /* Check if there is an unreserved slot */
640  EngineID engine = _engine_mngr.GetID(type, internal_id, INVALID_GRFID);
641  if (engine != INVALID_ENGINE) {
642  Engine *e = Engine::Get(engine);
643 
644  if (e->grf_prop.grffile == nullptr) {
645  e->grf_prop.grffile = file;
646  GrfMsg(5, "Replaced engine at index {} for GRFID {:x}, type {}, index {}", e->index, BSWAP32(file->grfid), type, internal_id);
647  }
648 
649  /* Reserve the engine slot */
650  if (!static_access) {
651  EngineIDMapping *eid = _engine_mngr.data() + engine;
652  eid->grfid = scope_grfid; // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
653  }
654 
655  return e;
656  }
657 
658  if (static_access) return nullptr;
659 
660  if (!Engine::CanAllocateItem()) {
661  GrfMsg(0, "Can't allocate any more engines");
662  return nullptr;
663  }
664 
665  size_t engine_pool_size = Engine::GetPoolSize();
666 
667  /* ... it's not, so create a new one based off an existing engine */
668  Engine *e = new Engine(type, internal_id);
669  e->grf_prop.grffile = file;
670 
671  /* Reserve the engine slot */
672  assert(_engine_mngr.size() == e->index);
673  _engine_mngr.push_back({
674  scope_grfid, // Note: this is INVALID_GRFID if dynamic_engines is disabled, so no reservation
675  internal_id,
676  type,
677  std::min<uint8_t>(internal_id, _engine_counts[type]) // substitute_id == _engine_counts[subtype] means "no substitute"
678  });
679 
680  if (engine_pool_size != Engine::GetPoolSize()) {
681  /* Resize temporary engine data ... */
682  _gted.resize(Engine::GetPoolSize());
683  }
684  if (type == VEH_TRAIN) {
685  _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
686  }
687 
688  GrfMsg(5, "Created new engine at index {} for GRFID {:x}, type {}, index {}", e->index, BSWAP32(file->grfid), type, internal_id);
689 
690  return e;
691 }
692 
703 EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16_t internal_id)
704 {
705  uint32_t scope_grfid = INVALID_GRFID; // If not using dynamic_engines, all newgrfs share their ID range
707  scope_grfid = file->grfid;
708  if (auto it = _grf_id_overrides.find(file->grfid); it != std::end(_grf_id_overrides)) {
709  scope_grfid = it->second;
710  }
711  }
712 
713  return _engine_mngr.GetID(type, internal_id, scope_grfid);
714 }
715 
720 static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
721 {
722  if (HasBit(grf_sprite->pal, 14)) {
723  ClrBit(grf_sprite->pal, 14);
724  SetBit(grf_sprite->sprite, SPRITE_MODIFIER_OPAQUE);
725  }
726 
727  if (HasBit(grf_sprite->sprite, 14)) {
728  ClrBit(grf_sprite->sprite, 14);
730  }
731 
732  if (HasBit(grf_sprite->sprite, 15)) {
733  ClrBit(grf_sprite->sprite, 15);
734  SetBit(grf_sprite->sprite, PALETTE_MODIFIER_COLOUR);
735  }
736 }
737 
751 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)
752 {
753  grf_sprite->sprite = buf.ReadWord();
754  grf_sprite->pal = buf.ReadWord();
755  TileLayoutFlags flags = read_flags ? (TileLayoutFlags)buf.ReadWord() : TLF_NOTHING;
756 
757  MapSpriteMappingRecolour(grf_sprite);
758 
759  bool custom_sprite = HasBit(grf_sprite->pal, 15) != invert_action1_flag;
760  ClrBit(grf_sprite->pal, 15);
761  if (custom_sprite) {
762  /* Use sprite from Action 1 */
763  uint index = GB(grf_sprite->sprite, 0, 14);
764  if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
765  GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset {}", index);
766  grf_sprite->sprite = SPR_IMG_QUERY;
767  grf_sprite->pal = PAL_NONE;
768  } else {
769  SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
770  if (max_sprite_offset != nullptr) *max_sprite_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
771  SB(grf_sprite->sprite, 0, SPRITE_WIDTH, sprite);
773  }
774  } else if ((flags & TLF_SPRITE_VAR10) && !(flags & TLF_SPRITE_REG_FLAGS)) {
775  GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout specifies var10 value for non-action-1 sprite");
776  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
777  return flags;
778  }
779 
780  if (flags & TLF_CUSTOM_PALETTE) {
781  /* Use palette from Action 1 */
782  uint index = GB(grf_sprite->pal, 0, 14);
783  if (use_cur_spritesets && (!_cur.IsValidSpriteSet(feature, index) || _cur.GetNumEnts(feature, index) == 0)) {
784  GrfMsg(1, "ReadSpriteLayoutSprite: Spritelayout uses undefined custom spriteset {} for 'palette'", index);
785  grf_sprite->pal = PAL_NONE;
786  } else {
787  SpriteID sprite = use_cur_spritesets ? _cur.GetSprite(feature, index) : index;
788  if (max_palette_offset != nullptr) *max_palette_offset = use_cur_spritesets ? _cur.GetNumEnts(feature, index) : UINT16_MAX;
789  SB(grf_sprite->pal, 0, SPRITE_WIDTH, sprite);
791  }
792  } else if ((flags & TLF_PALETTE_VAR10) && !(flags & TLF_PALETTE_REG_FLAGS)) {
793  GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 value for non-action-1 palette");
794  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
795  return flags;
796  }
797 
798  return flags;
799 }
800 
809 static void ReadSpriteLayoutRegisters(ByteReader &buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
810 {
811  if (!(flags & TLF_DRAWING_FLAGS)) return;
812 
813  if (dts->registers == nullptr) dts->AllocateRegisters();
814  TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[index]);
815  regs.flags = flags & TLF_DRAWING_FLAGS;
816 
817  if (flags & TLF_DODRAW) regs.dodraw = buf.ReadByte();
818  if (flags & TLF_SPRITE) regs.sprite = buf.ReadByte();
819  if (flags & TLF_PALETTE) regs.palette = buf.ReadByte();
820 
821  if (is_parent) {
822  if (flags & TLF_BB_XY_OFFSET) {
823  regs.delta.parent[0] = buf.ReadByte();
824  regs.delta.parent[1] = buf.ReadByte();
825  }
826  if (flags & TLF_BB_Z_OFFSET) regs.delta.parent[2] = buf.ReadByte();
827  } else {
828  if (flags & TLF_CHILD_X_OFFSET) regs.delta.child[0] = buf.ReadByte();
829  if (flags & TLF_CHILD_Y_OFFSET) regs.delta.child[1] = buf.ReadByte();
830  }
831 
832  if (flags & TLF_SPRITE_VAR10) {
833  regs.sprite_var10 = buf.ReadByte();
834  if (regs.sprite_var10 > TLR_MAX_VAR10) {
835  GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 ({}) exceeding the maximal allowed value {}", regs.sprite_var10, TLR_MAX_VAR10);
836  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
837  return;
838  }
839  }
840 
841  if (flags & TLF_PALETTE_VAR10) {
842  regs.palette_var10 = buf.ReadByte();
843  if (regs.palette_var10 > TLR_MAX_VAR10) {
844  GrfMsg(1, "ReadSpriteLayoutRegisters: Spritelayout specifies var10 ({}) exceeding the maximal allowed value {}", regs.palette_var10, TLR_MAX_VAR10);
845  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
846  return;
847  }
848  }
849 }
850 
862 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)
863 {
864  bool has_flags = HasBit(num_building_sprites, 6);
865  ClrBit(num_building_sprites, 6);
866  TileLayoutFlags valid_flags = TLF_KNOWN_FLAGS;
867  if (!allow_var10) valid_flags &= ~TLF_VAR10_FLAGS;
868  dts->Allocate(num_building_sprites); // allocate before reading groundsprite flags
869 
870  std::vector<uint16_t> max_sprite_offset(num_building_sprites + 1, 0);
871  std::vector<uint16_t> max_palette_offset(num_building_sprites + 1, 0);
872 
873  /* Groundsprite */
874  TileLayoutFlags flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &dts->ground, max_sprite_offset.data(), max_palette_offset.data());
875  if (_cur.skip_sprites < 0) return true;
876 
877  if (flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS)) {
878  GrfMsg(1, "ReadSpriteLayout: Spritelayout uses invalid flag 0x{:X} for ground sprite", flags & ~(valid_flags & ~TLF_NON_GROUND_FLAGS));
879  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
880  return true;
881  }
882 
883  ReadSpriteLayoutRegisters(buf, flags, false, dts, 0);
884  if (_cur.skip_sprites < 0) return true;
885 
886  for (uint i = 0; i < num_building_sprites; i++) {
887  DrawTileSeqStruct *seq = const_cast<DrawTileSeqStruct*>(&dts->seq[i]);
888 
889  flags = ReadSpriteLayoutSprite(buf, has_flags, false, use_cur_spritesets, feature, &seq->image, max_sprite_offset.data() + i + 1, max_palette_offset.data() + i + 1);
890  if (_cur.skip_sprites < 0) return true;
891 
892  if (flags & ~valid_flags) {
893  GrfMsg(1, "ReadSpriteLayout: Spritelayout uses unknown flag 0x{:X}", flags & ~valid_flags);
894  DisableGrf(STR_NEWGRF_ERROR_INVALID_SPRITE_LAYOUT);
895  return true;
896  }
897 
898  seq->delta_x = buf.ReadByte();
899  seq->delta_y = buf.ReadByte();
900 
901  if (!no_z_position) seq->delta_z = buf.ReadByte();
902 
903  if (seq->IsParentSprite()) {
904  seq->size_x = buf.ReadByte();
905  seq->size_y = buf.ReadByte();
906  seq->size_z = buf.ReadByte();
907  }
908 
909  ReadSpriteLayoutRegisters(buf, flags, seq->IsParentSprite(), dts, i + 1);
910  if (_cur.skip_sprites < 0) return true;
911  }
912 
913  /* Check if the number of sprites per spriteset is consistent */
914  bool is_consistent = true;
915  dts->consistent_max_offset = 0;
916  for (uint i = 0; i < num_building_sprites + 1; i++) {
917  if (max_sprite_offset[i] > 0) {
918  if (dts->consistent_max_offset == 0) {
919  dts->consistent_max_offset = max_sprite_offset[i];
920  } else if (dts->consistent_max_offset != max_sprite_offset[i]) {
921  is_consistent = false;
922  break;
923  }
924  }
925  if (max_palette_offset[i] > 0) {
926  if (dts->consistent_max_offset == 0) {
927  dts->consistent_max_offset = max_palette_offset[i];
928  } else if (dts->consistent_max_offset != max_palette_offset[i]) {
929  is_consistent = false;
930  break;
931  }
932  }
933  }
934 
935  /* When the Action1 sets are unknown, everything should be 0 (no spriteset usage) or UINT16_MAX (some spriteset usage) */
936  assert(use_cur_spritesets || (is_consistent && (dts->consistent_max_offset == 0 || dts->consistent_max_offset == UINT16_MAX)));
937 
938  if (!is_consistent || dts->registers != nullptr) {
939  dts->consistent_max_offset = 0;
940  if (dts->registers == nullptr) dts->AllocateRegisters();
941 
942  for (uint i = 0; i < num_building_sprites + 1; i++) {
943  TileLayoutRegisters &regs = const_cast<TileLayoutRegisters&>(dts->registers[i]);
944  regs.max_sprite_offset = max_sprite_offset[i];
945  regs.max_palette_offset = max_palette_offset[i];
946  }
947  }
948 
949  return false;
950 }
951 
955 static CargoTypes TranslateRefitMask(uint32_t refit_mask)
956 {
957  CargoTypes result = 0;
958  for (uint8_t bit : SetBitIterator(refit_mask)) {
959  CargoID cargo = GetCargoTranslation(bit, _cur.grffile, true);
960  if (IsValidCargoID(cargo)) SetBit(result, cargo);
961  }
962  return result;
963 }
964 
972 static void ConvertTTDBasePrice(uint32_t base_pointer, const char *error_location, Price *index)
973 {
974  /* Special value for 'none' */
975  if (base_pointer == 0) {
976  *index = INVALID_PRICE;
977  return;
978  }
979 
980  static const uint32_t start = 0x4B34;
981  static const uint32_t size = 6;
982 
983  if (base_pointer < start || (base_pointer - start) % size != 0 || (base_pointer - start) / size >= PR_END) {
984  GrfMsg(1, "{}: Unsupported running cost base 0x{:04X}, ignoring", error_location, base_pointer);
985  return;
986  }
987 
988  *index = (Price)((base_pointer - start) / size);
989 }
990 
998 };
999 
1000 typedef ChangeInfoResult (*VCI_Handler)(uint engine, int numinfo, int prop, ByteReader &buf);
1001 
1010 {
1011  switch (prop) {
1012  case 0x00: // Introduction date
1014  break;
1015 
1016  case 0x02: // Decay speed
1017  ei->decay_speed = buf.ReadByte();
1018  break;
1019 
1020  case 0x03: // Vehicle life
1021  ei->lifelength = buf.ReadByte();
1022  break;
1023 
1024  case 0x04: // Model life
1025  ei->base_life = buf.ReadByte();
1026  break;
1027 
1028  case 0x06: // Climates available
1029  ei->climates = buf.ReadByte();
1030  break;
1031 
1032  case PROP_VEHICLE_LOAD_AMOUNT: // 0x07 Loading speed
1033  /* Amount of cargo loaded during a vehicle's "loading tick" */
1034  ei->load_amount = buf.ReadByte();
1035  break;
1036 
1037  default:
1038  return CIR_UNKNOWN;
1039  }
1040 
1041  return CIR_SUCCESS;
1042 }
1043 
1052 static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader &buf)
1053 {
1055 
1056  for (int i = 0; i < numinfo; i++) {
1057  Engine *e = GetNewEngine(_cur.grffile, VEH_TRAIN, engine + i);
1058  if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1059 
1060  EngineInfo *ei = &e->info;
1061  RailVehicleInfo *rvi = &e->u.rail;
1062 
1063  switch (prop) {
1064  case 0x05: { // Track type
1065  uint8_t tracktype = buf.ReadByte();
1066 
1067  if (tracktype < _cur.grffile->railtype_list.size()) {
1068  _gted[e->index].railtypelabel = _cur.grffile->railtype_list[tracktype];
1069  break;
1070  }
1071 
1072  switch (tracktype) {
1073  case 0: _gted[e->index].railtypelabel = rvi->engclass >= 2 ? RAILTYPE_LABEL_ELECTRIC : RAILTYPE_LABEL_RAIL; break;
1074  case 1: _gted[e->index].railtypelabel = RAILTYPE_LABEL_MONO; break;
1075  case 2: _gted[e->index].railtypelabel = RAILTYPE_LABEL_MAGLEV; break;
1076  default:
1077  GrfMsg(1, "RailVehicleChangeInfo: Invalid track type {} specified, ignoring", tracktype);
1078  break;
1079  }
1080  break;
1081  }
1082 
1083  case 0x08: // AI passenger service
1084  /* Tells the AI that this engine is designed for
1085  * passenger services and shouldn't be used for freight. */
1086  rvi->ai_passenger_only = buf.ReadByte();
1087  break;
1088 
1089  case PROP_TRAIN_SPEED: { // 0x09 Speed (1 unit is 1 km-ish/h)
1090  uint16_t speed = buf.ReadWord();
1091  if (speed == 0xFFFF) speed = 0;
1092 
1093  rvi->max_speed = speed;
1094  break;
1095  }
1096 
1097  case PROP_TRAIN_POWER: // 0x0B Power
1098  rvi->power = buf.ReadWord();
1099 
1100  /* Set engine / wagon state based on power */
1101  if (rvi->power != 0) {
1102  if (rvi->railveh_type == RAILVEH_WAGON) {
1103  rvi->railveh_type = RAILVEH_SINGLEHEAD;
1104  }
1105  } else {
1106  rvi->railveh_type = RAILVEH_WAGON;
1107  }
1108  break;
1109 
1110  case PROP_TRAIN_RUNNING_COST_FACTOR: // 0x0D Running cost factor
1111  rvi->running_cost = buf.ReadByte();
1112  break;
1113 
1114  case 0x0E: // Running cost base
1115  ConvertTTDBasePrice(buf.ReadDWord(), "RailVehicleChangeInfo", &rvi->running_cost_class);
1116  break;
1117 
1118  case 0x12: { // Sprite ID
1119  uint8_t spriteid = buf.ReadByte();
1120  uint8_t orig_spriteid = spriteid;
1121 
1122  /* TTD sprite IDs point to a location in a 16bit array, but we use it
1123  * as an array index, so we need it to be half the original value. */
1124  if (spriteid < 0xFD) spriteid >>= 1;
1125 
1126  if (IsValidNewGRFImageIndex<VEH_TRAIN>(spriteid)) {
1127  rvi->image_index = spriteid;
1128  } else {
1129  GrfMsg(1, "RailVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1130  rvi->image_index = 0;
1131  }
1132  break;
1133  }
1134 
1135  case 0x13: { // Dual-headed
1136  uint8_t dual = buf.ReadByte();
1137 
1138  if (dual != 0) {
1139  rvi->railveh_type = RAILVEH_MULTIHEAD;
1140  } else {
1141  rvi->railveh_type = rvi->power == 0 ?
1143  }
1144  break;
1145  }
1146 
1147  case PROP_TRAIN_CARGO_CAPACITY: // 0x14 Cargo capacity
1148  rvi->capacity = buf.ReadByte();
1149  break;
1150 
1151  case 0x15: { // Cargo type
1152  _gted[e->index].defaultcargo_grf = _cur.grffile;
1153  uint8_t ctype = buf.ReadByte();
1154 
1155  if (ctype == 0xFF) {
1156  /* 0xFF is specified as 'use first refittable' */
1157  ei->cargo_type = INVALID_CARGO;
1158  } else if (_cur.grffile->grf_version >= 8) {
1159  /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
1160  ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1161  } else if (ctype < NUM_CARGO) {
1162  /* Use untranslated cargo. */
1163  ei->cargo_type = ctype;
1164  } else {
1165  ei->cargo_type = INVALID_CARGO;
1166  GrfMsg(2, "RailVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype);
1167  }
1168  ei->cargo_label = CT_INVALID;
1169  break;
1170  }
1171 
1172  case PROP_TRAIN_WEIGHT: // 0x16 Weight
1173  SB(rvi->weight, 0, 8, buf.ReadByte());
1174  break;
1175 
1176  case PROP_TRAIN_COST_FACTOR: // 0x17 Cost factor
1177  rvi->cost_factor = buf.ReadByte();
1178  break;
1179 
1180  case 0x18: // AI rank
1181  GrfMsg(2, "RailVehicleChangeInfo: Property 0x18 'AI rank' not used by NoAI, ignored.");
1182  buf.ReadByte();
1183  break;
1184 
1185  case 0x19: { // Engine traction type
1186  /* What do the individual numbers mean?
1187  * 0x00 .. 0x07: Steam
1188  * 0x08 .. 0x27: Diesel
1189  * 0x28 .. 0x31: Electric
1190  * 0x32 .. 0x37: Monorail
1191  * 0x38 .. 0x41: Maglev
1192  */
1193  uint8_t traction = buf.ReadByte();
1194  EngineClass engclass;
1195 
1196  if (traction <= 0x07) {
1197  engclass = EC_STEAM;
1198  } else if (traction <= 0x27) {
1199  engclass = EC_DIESEL;
1200  } else if (traction <= 0x31) {
1201  engclass = EC_ELECTRIC;
1202  } else if (traction <= 0x37) {
1203  engclass = EC_MONORAIL;
1204  } else if (traction <= 0x41) {
1205  engclass = EC_MAGLEV;
1206  } else {
1207  break;
1208  }
1209 
1210  if (_cur.grffile->railtype_list.empty()) {
1211  /* Use traction type to select between normal and electrified
1212  * rail only when no translation list is in place. */
1213  if (_gted[e->index].railtypelabel == RAILTYPE_LABEL_RAIL && engclass >= EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_LABEL_ELECTRIC;
1214  if (_gted[e->index].railtypelabel == RAILTYPE_LABEL_ELECTRIC && engclass < EC_ELECTRIC) _gted[e->index].railtypelabel = RAILTYPE_LABEL_RAIL;
1215  }
1216 
1217  rvi->engclass = engclass;
1218  break;
1219  }
1220 
1221  case 0x1A: // Alter purchase list sort order
1222  AlterVehicleListOrder(e->index, buf.ReadExtendedByte());
1223  break;
1224 
1225  case 0x1B: // Powered wagons power bonus
1226  rvi->pow_wag_power = buf.ReadWord();
1227  break;
1228 
1229  case 0x1C: // Refit cost
1230  ei->refit_cost = buf.ReadByte();
1231  break;
1232 
1233  case 0x1D: { // Refit cargo
1234  uint32_t mask = buf.ReadDWord();
1235  _gted[e->index].UpdateRefittability(mask != 0);
1236  ei->refit_mask = TranslateRefitMask(mask);
1237  _gted[e->index].defaultcargo_grf = _cur.grffile;
1238  break;
1239  }
1240 
1241  case 0x1E: // Callback
1242  SB(ei->callback_mask, 0, 8, buf.ReadByte());
1243  break;
1244 
1245  case PROP_TRAIN_TRACTIVE_EFFORT: // 0x1F Tractive effort coefficient
1246  rvi->tractive_effort = buf.ReadByte();
1247  break;
1248 
1249  case 0x20: // Air drag
1250  rvi->air_drag = buf.ReadByte();
1251  break;
1252 
1253  case PROP_TRAIN_SHORTEN_FACTOR: // 0x21 Shorter vehicle
1254  rvi->shorten_factor = buf.ReadByte();
1255  break;
1256 
1257  case 0x22: // Visual effect
1258  rvi->visual_effect = buf.ReadByte();
1259  /* Avoid accidentally setting visual_effect to the default value
1260  * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1261  if (rvi->visual_effect == VE_DEFAULT) {
1262  assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1264  }
1265  break;
1266 
1267  case 0x23: // Powered wagons weight bonus
1268  rvi->pow_wag_weight = buf.ReadByte();
1269  break;
1270 
1271  case 0x24: { // High byte of vehicle weight
1272  uint8_t weight = buf.ReadByte();
1273 
1274  if (weight > 4) {
1275  GrfMsg(2, "RailVehicleChangeInfo: Nonsensical weight of {} tons, ignoring", weight << 8);
1276  } else {
1277  SB(rvi->weight, 8, 8, weight);
1278  }
1279  break;
1280  }
1281 
1282  case PROP_TRAIN_USER_DATA: // 0x25 User-defined bit mask to set when checking veh. var. 42
1283  rvi->user_def_data = buf.ReadByte();
1284  break;
1285 
1286  case 0x26: // Retire vehicle early
1287  ei->retire_early = buf.ReadByte();
1288  break;
1289 
1290  case 0x27: // Miscellaneous flags
1291  ei->misc_flags = buf.ReadByte();
1293  break;
1294 
1295  case 0x28: // Cargo classes allowed
1296  _gted[e->index].cargo_allowed = buf.ReadWord();
1297  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1298  _gted[e->index].defaultcargo_grf = _cur.grffile;
1299  break;
1300 
1301  case 0x29: // Cargo classes disallowed
1302  _gted[e->index].cargo_disallowed = buf.ReadWord();
1303  _gted[e->index].UpdateRefittability(false);
1304  break;
1305 
1306  case 0x2A: // Long format introduction date (days since year 0)
1307  ei->base_intro = buf.ReadDWord();
1308  break;
1309 
1310  case PROP_TRAIN_CARGO_AGE_PERIOD: // 0x2B Cargo aging period
1311  ei->cargo_age_period = buf.ReadWord();
1312  break;
1313 
1314  case 0x2C: // CTT refit include list
1315  case 0x2D: { // CTT refit exclude list
1316  uint8_t count = buf.ReadByte();
1317  _gted[e->index].UpdateRefittability(prop == 0x2C && count != 0);
1318  if (prop == 0x2C) _gted[e->index].defaultcargo_grf = _cur.grffile;
1319  CargoTypes &ctt = prop == 0x2C ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1320  ctt = 0;
1321  while (count--) {
1322  CargoID ctype = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
1323  if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1324  }
1325  break;
1326  }
1327 
1328  case PROP_TRAIN_CURVE_SPEED_MOD: // 0x2E Curve speed modifier
1329  rvi->curve_speed_mod = buf.ReadWord();
1330  break;
1331 
1332  case 0x2F: // Engine variant
1333  ei->variant_id = buf.ReadWord();
1334  break;
1335 
1336  case 0x30: // Extra miscellaneous flags
1337  ei->extra_flags = static_cast<ExtraEngineFlags>(buf.ReadDWord());
1338  break;
1339 
1340  case 0x31: // Callback additional mask
1341  SB(ei->callback_mask, 8, 8, buf.ReadByte());
1342  break;
1343 
1344  default:
1345  ret = CommonVehicleChangeInfo(ei, prop, buf);
1346  break;
1347  }
1348  }
1349 
1350  return ret;
1351 }
1352 
1361 static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader &buf)
1362 {
1364 
1365  for (int i = 0; i < numinfo; i++) {
1366  Engine *e = GetNewEngine(_cur.grffile, VEH_ROAD, engine + i);
1367  if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1368 
1369  EngineInfo *ei = &e->info;
1370  RoadVehicleInfo *rvi = &e->u.road;
1371 
1372  switch (prop) {
1373  case 0x05: // Road/tram type
1374  /* RoadTypeLabel is looked up later after the engine's road/tram
1375  * flag is set, however 0 means the value has not been set. */
1376  _gted[e->index].roadtramtype = buf.ReadByte() + 1;
1377  break;
1378 
1379  case 0x08: // Speed (1 unit is 0.5 kmh)
1380  rvi->max_speed = buf.ReadByte();
1381  break;
1382 
1383  case PROP_ROADVEH_RUNNING_COST_FACTOR: // 0x09 Running cost factor
1384  rvi->running_cost = buf.ReadByte();
1385  break;
1386 
1387  case 0x0A: // Running cost base
1388  ConvertTTDBasePrice(buf.ReadDWord(), "RoadVehicleChangeInfo", &rvi->running_cost_class);
1389  break;
1390 
1391  case 0x0E: { // Sprite ID
1392  uint8_t spriteid = buf.ReadByte();
1393  uint8_t orig_spriteid = spriteid;
1394 
1395  /* cars have different custom id in the GRF file */
1396  if (spriteid == 0xFF) spriteid = 0xFD;
1397 
1398  if (spriteid < 0xFD) spriteid >>= 1;
1399 
1400  if (IsValidNewGRFImageIndex<VEH_ROAD>(spriteid)) {
1401  rvi->image_index = spriteid;
1402  } else {
1403  GrfMsg(1, "RoadVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1404  rvi->image_index = 0;
1405  }
1406  break;
1407  }
1408 
1409  case PROP_ROADVEH_CARGO_CAPACITY: // 0x0F Cargo capacity
1410  rvi->capacity = buf.ReadByte();
1411  break;
1412 
1413  case 0x10: { // Cargo type
1414  _gted[e->index].defaultcargo_grf = _cur.grffile;
1415  uint8_t ctype = buf.ReadByte();
1416 
1417  if (ctype == 0xFF) {
1418  /* 0xFF is specified as 'use first refittable' */
1419  ei->cargo_type = INVALID_CARGO;
1420  } else if (_cur.grffile->grf_version >= 8) {
1421  /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
1422  ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1423  } else if (ctype < NUM_CARGO) {
1424  /* Use untranslated cargo. */
1425  ei->cargo_type = ctype;
1426  } else {
1427  ei->cargo_type = INVALID_CARGO;
1428  GrfMsg(2, "RailVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype);
1429  }
1430  ei->cargo_label = CT_INVALID;
1431  break;
1432  }
1433 
1434  case PROP_ROADVEH_COST_FACTOR: // 0x11 Cost factor
1435  rvi->cost_factor = buf.ReadByte();
1436  break;
1437 
1438  case 0x12: // SFX
1439  rvi->sfx = GetNewGRFSoundID(_cur.grffile, buf.ReadByte());
1440  break;
1441 
1442  case PROP_ROADVEH_POWER: // Power in units of 10 HP.
1443  rvi->power = buf.ReadByte();
1444  break;
1445 
1446  case PROP_ROADVEH_WEIGHT: // Weight in units of 1/4 tons.
1447  rvi->weight = buf.ReadByte();
1448  break;
1449 
1450  case PROP_ROADVEH_SPEED: // Speed in mph/0.8
1451  _gted[e->index].rv_max_speed = buf.ReadByte();
1452  break;
1453 
1454  case 0x16: { // Cargoes available for refitting
1455  uint32_t mask = buf.ReadDWord();
1456  _gted[e->index].UpdateRefittability(mask != 0);
1457  ei->refit_mask = TranslateRefitMask(mask);
1458  _gted[e->index].defaultcargo_grf = _cur.grffile;
1459  break;
1460  }
1461 
1462  case 0x17: // Callback mask
1463  SB(ei->callback_mask, 0, 8, buf.ReadByte());
1464  break;
1465 
1466  case PROP_ROADVEH_TRACTIVE_EFFORT: // Tractive effort coefficient in 1/256.
1467  rvi->tractive_effort = buf.ReadByte();
1468  break;
1469 
1470  case 0x19: // Air drag
1471  rvi->air_drag = buf.ReadByte();
1472  break;
1473 
1474  case 0x1A: // Refit cost
1475  ei->refit_cost = buf.ReadByte();
1476  break;
1477 
1478  case 0x1B: // Retire vehicle early
1479  ei->retire_early = buf.ReadByte();
1480  break;
1481 
1482  case 0x1C: // Miscellaneous flags
1483  ei->misc_flags = buf.ReadByte();
1485  break;
1486 
1487  case 0x1D: // Cargo classes allowed
1488  _gted[e->index].cargo_allowed = buf.ReadWord();
1489  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1490  _gted[e->index].defaultcargo_grf = _cur.grffile;
1491  break;
1492 
1493  case 0x1E: // Cargo classes disallowed
1494  _gted[e->index].cargo_disallowed = buf.ReadWord();
1495  _gted[e->index].UpdateRefittability(false);
1496  break;
1497 
1498  case 0x1F: // Long format introduction date (days since year 0)
1499  ei->base_intro = buf.ReadDWord();
1500  break;
1501 
1502  case 0x20: // Alter purchase list sort order
1503  AlterVehicleListOrder(e->index, buf.ReadExtendedByte());
1504  break;
1505 
1506  case 0x21: // Visual effect
1507  rvi->visual_effect = buf.ReadByte();
1508  /* Avoid accidentally setting visual_effect to the default value
1509  * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1510  if (rvi->visual_effect == VE_DEFAULT) {
1511  assert(HasBit(rvi->visual_effect, VE_DISABLE_EFFECT));
1513  }
1514  break;
1515 
1516  case PROP_ROADVEH_CARGO_AGE_PERIOD: // 0x22 Cargo aging period
1517  ei->cargo_age_period = buf.ReadWord();
1518  break;
1519 
1520  case PROP_ROADVEH_SHORTEN_FACTOR: // 0x23 Shorter vehicle
1521  rvi->shorten_factor = buf.ReadByte();
1522  break;
1523 
1524  case 0x24: // CTT refit include list
1525  case 0x25: { // CTT refit exclude list
1526  uint8_t count = buf.ReadByte();
1527  _gted[e->index].UpdateRefittability(prop == 0x24 && count != 0);
1528  if (prop == 0x24) _gted[e->index].defaultcargo_grf = _cur.grffile;
1529  CargoTypes &ctt = prop == 0x24 ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1530  ctt = 0;
1531  while (count--) {
1532  CargoID ctype = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
1533  if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1534  }
1535  break;
1536  }
1537 
1538  case 0x26: // Engine variant
1539  ei->variant_id = buf.ReadWord();
1540  break;
1541 
1542  case 0x27: // Extra miscellaneous flags
1543  ei->extra_flags = static_cast<ExtraEngineFlags>(buf.ReadDWord());
1544  break;
1545 
1546  case 0x28: // Callback additional mask
1547  SB(ei->callback_mask, 8, 8, buf.ReadByte());
1548  break;
1549 
1550  default:
1551  ret = CommonVehicleChangeInfo(ei, prop, buf);
1552  break;
1553  }
1554  }
1555 
1556  return ret;
1557 }
1558 
1567 static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader &buf)
1568 {
1570 
1571  for (int i = 0; i < numinfo; i++) {
1572  Engine *e = GetNewEngine(_cur.grffile, VEH_SHIP, engine + i);
1573  if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1574 
1575  EngineInfo *ei = &e->info;
1576  ShipVehicleInfo *svi = &e->u.ship;
1577 
1578  switch (prop) {
1579  case 0x08: { // Sprite ID
1580  uint8_t spriteid = buf.ReadByte();
1581  uint8_t orig_spriteid = spriteid;
1582 
1583  /* ships have different custom id in the GRF file */
1584  if (spriteid == 0xFF) spriteid = 0xFD;
1585 
1586  if (spriteid < 0xFD) spriteid >>= 1;
1587 
1588  if (IsValidNewGRFImageIndex<VEH_SHIP>(spriteid)) {
1589  svi->image_index = spriteid;
1590  } else {
1591  GrfMsg(1, "ShipVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1592  svi->image_index = 0;
1593  }
1594  break;
1595  }
1596 
1597  case 0x09: // Refittable
1598  svi->old_refittable = (buf.ReadByte() != 0);
1599  break;
1600 
1601  case PROP_SHIP_COST_FACTOR: // 0x0A Cost factor
1602  svi->cost_factor = buf.ReadByte();
1603  break;
1604 
1605  case PROP_SHIP_SPEED: // 0x0B Speed (1 unit is 0.5 km-ish/h). Use 0x23 to achieve higher speeds.
1606  svi->max_speed = buf.ReadByte();
1607  break;
1608 
1609  case 0x0C: { // Cargo type
1610  _gted[e->index].defaultcargo_grf = _cur.grffile;
1611  uint8_t ctype = buf.ReadByte();
1612 
1613  if (ctype == 0xFF) {
1614  /* 0xFF is specified as 'use first refittable' */
1615  ei->cargo_type = INVALID_CARGO;
1616  } else if (_cur.grffile->grf_version >= 8) {
1617  /* Use translated cargo. Might result in INVALID_CARGO (first refittable), if cargo is not defined. */
1618  ei->cargo_type = GetCargoTranslation(ctype, _cur.grffile);
1619  } else if (ctype < NUM_CARGO) {
1620  /* Use untranslated cargo. */
1621  ei->cargo_type = ctype;
1622  } else {
1623  ei->cargo_type = INVALID_CARGO;
1624  GrfMsg(2, "ShipVehicleChangeInfo: Invalid cargo type {}, using first refittable", ctype);
1625  }
1626  ei->cargo_label = CT_INVALID;
1627  break;
1628  }
1629 
1630  case PROP_SHIP_CARGO_CAPACITY: // 0x0D Cargo capacity
1631  svi->capacity = buf.ReadWord();
1632  break;
1633 
1634  case PROP_SHIP_RUNNING_COST_FACTOR: // 0x0F Running cost factor
1635  svi->running_cost = buf.ReadByte();
1636  break;
1637 
1638  case 0x10: // SFX
1639  svi->sfx = GetNewGRFSoundID(_cur.grffile, buf.ReadByte());
1640  break;
1641 
1642  case 0x11: { // Cargoes available for refitting
1643  uint32_t mask = buf.ReadDWord();
1644  _gted[e->index].UpdateRefittability(mask != 0);
1645  ei->refit_mask = TranslateRefitMask(mask);
1646  _gted[e->index].defaultcargo_grf = _cur.grffile;
1647  break;
1648  }
1649 
1650  case 0x12: // Callback mask
1651  SB(ei->callback_mask, 0, 8, buf.ReadByte());
1652  break;
1653 
1654  case 0x13: // Refit cost
1655  ei->refit_cost = buf.ReadByte();
1656  break;
1657 
1658  case 0x14: // Ocean speed fraction
1659  svi->ocean_speed_frac = buf.ReadByte();
1660  break;
1661 
1662  case 0x15: // Canal speed fraction
1663  svi->canal_speed_frac = buf.ReadByte();
1664  break;
1665 
1666  case 0x16: // Retire vehicle early
1667  ei->retire_early = buf.ReadByte();
1668  break;
1669 
1670  case 0x17: // Miscellaneous flags
1671  ei->misc_flags = buf.ReadByte();
1673  break;
1674 
1675  case 0x18: // Cargo classes allowed
1676  _gted[e->index].cargo_allowed = buf.ReadWord();
1677  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1678  _gted[e->index].defaultcargo_grf = _cur.grffile;
1679  break;
1680 
1681  case 0x19: // Cargo classes disallowed
1682  _gted[e->index].cargo_disallowed = buf.ReadWord();
1683  _gted[e->index].UpdateRefittability(false);
1684  break;
1685 
1686  case 0x1A: // Long format introduction date (days since year 0)
1687  ei->base_intro = buf.ReadDWord();
1688  break;
1689 
1690  case 0x1B: // Alter purchase list sort order
1691  AlterVehicleListOrder(e->index, buf.ReadExtendedByte());
1692  break;
1693 
1694  case 0x1C: // Visual effect
1695  svi->visual_effect = buf.ReadByte();
1696  /* Avoid accidentally setting visual_effect to the default value
1697  * Since bit 6 (disable effects) is set anyways, we can safely erase some bits. */
1698  if (svi->visual_effect == VE_DEFAULT) {
1699  assert(HasBit(svi->visual_effect, VE_DISABLE_EFFECT));
1701  }
1702  break;
1703 
1704  case PROP_SHIP_CARGO_AGE_PERIOD: // 0x1D Cargo aging period
1705  ei->cargo_age_period = buf.ReadWord();
1706  break;
1707 
1708  case 0x1E: // CTT refit include list
1709  case 0x1F: { // CTT refit exclude list
1710  uint8_t count = buf.ReadByte();
1711  _gted[e->index].UpdateRefittability(prop == 0x1E && count != 0);
1712  if (prop == 0x1E) _gted[e->index].defaultcargo_grf = _cur.grffile;
1713  CargoTypes &ctt = prop == 0x1E ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1714  ctt = 0;
1715  while (count--) {
1716  CargoID ctype = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
1717  if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1718  }
1719  break;
1720  }
1721 
1722  case 0x20: // Engine variant
1723  ei->variant_id = buf.ReadWord();
1724  break;
1725 
1726  case 0x21: // Extra miscellaneous flags
1727  ei->extra_flags = static_cast<ExtraEngineFlags>(buf.ReadDWord());
1728  break;
1729 
1730  case 0x22: // Callback additional mask
1731  SB(ei->callback_mask, 8, 8, buf.ReadByte());
1732  break;
1733 
1734  case 0x23: // Speed (1 unit is 0.5 km-ish/h)
1735  svi->max_speed = buf.ReadWord();
1736  break;
1737 
1738  case 0x24: // Acceleration (1 unit is 0.5 km-ish/h per tick)
1739  svi->acceleration = std::max<uint8_t>(1, buf.ReadByte());
1740  break;
1741 
1742  default:
1743  ret = CommonVehicleChangeInfo(ei, prop, buf);
1744  break;
1745  }
1746  }
1747 
1748  return ret;
1749 }
1750 
1759 static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader &buf)
1760 {
1762 
1763  for (int i = 0; i < numinfo; i++) {
1764  Engine *e = GetNewEngine(_cur.grffile, VEH_AIRCRAFT, engine + i);
1765  if (e == nullptr) return CIR_INVALID_ID; // No engine could be allocated, so neither can any next vehicles
1766 
1767  EngineInfo *ei = &e->info;
1768  AircraftVehicleInfo *avi = &e->u.air;
1769 
1770  switch (prop) {
1771  case 0x08: { // Sprite ID
1772  uint8_t spriteid = buf.ReadByte();
1773  uint8_t orig_spriteid = spriteid;
1774 
1775  /* aircraft have different custom id in the GRF file */
1776  if (spriteid == 0xFF) spriteid = 0xFD;
1777 
1778  if (spriteid < 0xFD) spriteid >>= 1;
1779 
1780  if (IsValidNewGRFImageIndex<VEH_AIRCRAFT>(spriteid)) {
1781  avi->image_index = spriteid;
1782  } else {
1783  GrfMsg(1, "AircraftVehicleChangeInfo: Invalid Sprite {} specified, ignoring", orig_spriteid);
1784  avi->image_index = 0;
1785  }
1786  break;
1787  }
1788 
1789  case 0x09: // Helicopter
1790  if (buf.ReadByte() == 0) {
1791  avi->subtype = AIR_HELI;
1792  } else {
1793  SB(avi->subtype, 0, 1, 1); // AIR_CTOL
1794  }
1795  break;
1796 
1797  case 0x0A: // Large
1798  AssignBit(avi->subtype, 1, buf.ReadByte() != 0); // AIR_FAST
1799  break;
1800 
1801  case PROP_AIRCRAFT_COST_FACTOR: // 0x0B Cost factor
1802  avi->cost_factor = buf.ReadByte();
1803  break;
1804 
1805  case PROP_AIRCRAFT_SPEED: // 0x0C Speed (1 unit is 8 mph, we translate to 1 unit is 1 km-ish/h)
1806  avi->max_speed = (buf.ReadByte() * 128) / 10;
1807  break;
1808 
1809  case 0x0D: // Acceleration
1810  avi->acceleration = buf.ReadByte();
1811  break;
1812 
1813  case PROP_AIRCRAFT_RUNNING_COST_FACTOR: // 0x0E Running cost factor
1814  avi->running_cost = buf.ReadByte();
1815  break;
1816 
1817  case PROP_AIRCRAFT_PASSENGER_CAPACITY: // 0x0F Passenger capacity
1818  avi->passenger_capacity = buf.ReadWord();
1819  break;
1820 
1821  case PROP_AIRCRAFT_MAIL_CAPACITY: // 0x11 Mail capacity
1822  avi->mail_capacity = buf.ReadByte();
1823  break;
1824 
1825  case 0x12: // SFX
1826  avi->sfx = GetNewGRFSoundID(_cur.grffile, buf.ReadByte());
1827  break;
1828 
1829  case 0x13: { // Cargoes available for refitting
1830  uint32_t mask = buf.ReadDWord();
1831  _gted[e->index].UpdateRefittability(mask != 0);
1832  ei->refit_mask = TranslateRefitMask(mask);
1833  _gted[e->index].defaultcargo_grf = _cur.grffile;
1834  break;
1835  }
1836 
1837  case 0x14: // Callback mask
1838  SB(ei->callback_mask, 0, 8, buf.ReadByte());
1839  break;
1840 
1841  case 0x15: // Refit cost
1842  ei->refit_cost = buf.ReadByte();
1843  break;
1844 
1845  case 0x16: // Retire vehicle early
1846  ei->retire_early = buf.ReadByte();
1847  break;
1848 
1849  case 0x17: // Miscellaneous flags
1850  ei->misc_flags = buf.ReadByte();
1852  break;
1853 
1854  case 0x18: // Cargo classes allowed
1855  _gted[e->index].cargo_allowed = buf.ReadWord();
1856  _gted[e->index].UpdateRefittability(_gted[e->index].cargo_allowed != 0);
1857  _gted[e->index].defaultcargo_grf = _cur.grffile;
1858  break;
1859 
1860  case 0x19: // Cargo classes disallowed
1861  _gted[e->index].cargo_disallowed = buf.ReadWord();
1862  _gted[e->index].UpdateRefittability(false);
1863  break;
1864 
1865  case 0x1A: // Long format introduction date (days since year 0)
1866  ei->base_intro = buf.ReadDWord();
1867  break;
1868 
1869  case 0x1B: // Alter purchase list sort order
1870  AlterVehicleListOrder(e->index, buf.ReadExtendedByte());
1871  break;
1872 
1873  case PROP_AIRCRAFT_CARGO_AGE_PERIOD: // 0x1C Cargo aging period
1874  ei->cargo_age_period = buf.ReadWord();
1875  break;
1876 
1877  case 0x1D: // CTT refit include list
1878  case 0x1E: { // CTT refit exclude list
1879  uint8_t count = buf.ReadByte();
1880  _gted[e->index].UpdateRefittability(prop == 0x1D && count != 0);
1881  if (prop == 0x1D) _gted[e->index].defaultcargo_grf = _cur.grffile;
1882  CargoTypes &ctt = prop == 0x1D ? _gted[e->index].ctt_include_mask : _gted[e->index].ctt_exclude_mask;
1883  ctt = 0;
1884  while (count--) {
1885  CargoID ctype = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
1886  if (IsValidCargoID(ctype)) SetBit(ctt, ctype);
1887  }
1888  break;
1889  }
1890 
1891  case PROP_AIRCRAFT_RANGE: // 0x1F Max aircraft range
1892  avi->max_range = buf.ReadWord();
1893  break;
1894 
1895  case 0x20: // Engine variant
1896  ei->variant_id = buf.ReadWord();
1897  break;
1898 
1899  case 0x21: // Extra miscellaneous flags
1900  ei->extra_flags = static_cast<ExtraEngineFlags>(buf.ReadDWord());
1901  break;
1902 
1903  case 0x22: // Callback additional mask
1904  SB(ei->callback_mask, 8, 8, buf.ReadByte());
1905  break;
1906 
1907  default:
1908  ret = CommonVehicleChangeInfo(ei, prop, buf);
1909  break;
1910  }
1911  }
1912 
1913  return ret;
1914 }
1915 
1924 static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader &buf)
1925 {
1927 
1928  if (stid + numinfo > NUM_STATIONS_PER_GRF) {
1929  GrfMsg(1, "StationChangeInfo: Station {} is invalid, max {}, ignoring", stid + numinfo, NUM_STATIONS_PER_GRF);
1930  return CIR_INVALID_ID;
1931  }
1932 
1933  /* Allocate station specs if necessary */
1934  if (_cur.grffile->stations.size() < stid + numinfo) _cur.grffile->stations.resize(stid + numinfo);
1935 
1936  for (int i = 0; i < numinfo; i++) {
1937  auto &statspec = _cur.grffile->stations[stid + i];
1938 
1939  /* Check that the station we are modifying is defined. */
1940  if (statspec == nullptr && prop != 0x08) {
1941  GrfMsg(2, "StationChangeInfo: Attempt to modify undefined station {}, ignoring", stid + i);
1942  return CIR_INVALID_ID;
1943  }
1944 
1945  switch (prop) {
1946  case 0x08: { // Class ID
1947  /* Property 0x08 is special; it is where the station is allocated */
1948  if (statspec == nullptr) {
1949  statspec = std::make_unique<StationSpec>();
1950  }
1951 
1952  /* Swap classid because we read it in BE meaning WAYP or DFLT */
1953  uint32_t classid = buf.ReadDWord();
1954  statspec->class_index = StationClass::Allocate(BSWAP32(classid));
1955  break;
1956  }
1957 
1958  case 0x09: { // Define sprite layout
1959  uint16_t tiles = buf.ReadExtendedByte();
1960  statspec->renderdata.clear(); // delete earlier loaded stuff
1961  statspec->renderdata.reserve(tiles);
1962 
1963  for (uint t = 0; t < tiles; t++) {
1964  NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
1965  dts->consistent_max_offset = UINT16_MAX; // Spritesets are unknown, so no limit.
1966 
1967  if (buf.HasData(4) && buf.PeekDWord() == 0) {
1968  buf.Skip(4);
1969  extern const DrawTileSprites _station_display_datas_rail[8];
1970  dts->Clone(&_station_display_datas_rail[t % 8]);
1971  continue;
1972  }
1973 
1974  ReadSpriteLayoutSprite(buf, false, false, false, GSF_STATIONS, &dts->ground);
1975  /* On error, bail out immediately. Temporary GRF data was already freed */
1976  if (_cur.skip_sprites < 0) return CIR_DISABLED;
1977 
1978  static std::vector<DrawTileSeqStruct> tmp_layout;
1979  tmp_layout.clear();
1980  for (;;) {
1981  /* no relative bounding box support */
1982  DrawTileSeqStruct &dtss = tmp_layout.emplace_back();
1983  MemSetT(&dtss, 0);
1984 
1985  dtss.delta_x = buf.ReadByte();
1986  if (dtss.IsTerminator()) break;
1987  dtss.delta_y = buf.ReadByte();
1988  dtss.delta_z = buf.ReadByte();
1989  dtss.size_x = buf.ReadByte();
1990  dtss.size_y = buf.ReadByte();
1991  dtss.size_z = buf.ReadByte();
1992 
1993  ReadSpriteLayoutSprite(buf, false, true, false, GSF_STATIONS, &dtss.image);
1994  /* On error, bail out immediately. Temporary GRF data was already freed */
1995  if (_cur.skip_sprites < 0) return CIR_DISABLED;
1996  }
1997  dts->Clone(tmp_layout.data());
1998  }
1999 
2000  /* Number of layouts must be even, alternating X and Y */
2001  if (statspec->renderdata.size() & 1) {
2002  GrfMsg(1, "StationChangeInfo: Station {} defines an odd number of sprite layouts, dropping the last item", stid + i);
2003  statspec->renderdata.pop_back();
2004  }
2005  break;
2006  }
2007 
2008  case 0x0A: { // Copy sprite layout
2009  uint16_t srcid = buf.ReadExtendedByte();
2010  const StationSpec *srcstatspec = srcid >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[srcid].get();
2011 
2012  if (srcstatspec == nullptr) {
2013  GrfMsg(1, "StationChangeInfo: Station {} is not defined, cannot copy sprite layout to {}.", srcid, stid + i);
2014  continue;
2015  }
2016 
2017  statspec->renderdata.clear(); // delete earlier loaded stuff
2018  statspec->renderdata.reserve(srcstatspec->renderdata.size());
2019 
2020  for (const auto &it : srcstatspec->renderdata) {
2021  NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
2022  dts->Clone(&it);
2023  }
2024  break;
2025  }
2026 
2027  case 0x0B: // Callback mask
2028  statspec->callback_mask = buf.ReadByte();
2029  break;
2030 
2031  case 0x0C: // Disallowed number of platforms
2032  statspec->disallowed_platforms = buf.ReadByte();
2033  break;
2034 
2035  case 0x0D: // Disallowed platform lengths
2036  statspec->disallowed_lengths = buf.ReadByte();
2037  break;
2038 
2039  case 0x0E: // Define custom layout
2040  while (buf.HasData()) {
2041  uint8_t length = buf.ReadByte();
2042  uint8_t number = buf.ReadByte();
2043 
2044  if (length == 0 || number == 0) break;
2045 
2046  const uint8_t *buf_layout = buf.ReadBytes(length * number);
2047 
2048  /* Create entry in layouts and assign the layout to it. */
2049  auto &layout = statspec->layouts[GetStationLayoutKey(number, length)];
2050  layout.assign(buf_layout, buf_layout + length * number);
2051 
2052  /* Ensure the first bit, axis, is zero. The rest of the value is validated during rendering, as we don't know the range yet. */
2053  for (auto &tile : layout) {
2054  if ((tile & ~1U) != tile) {
2055  GrfMsg(1, "StationChangeInfo: Invalid tile {} in layout {}x{}", tile, length, number);
2056  tile &= ~1U;
2057  }
2058  }
2059  }
2060  break;
2061 
2062  case 0x0F: { // Copy custom layout
2063  uint16_t srcid = buf.ReadExtendedByte();
2064  const StationSpec *srcstatspec = srcid >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[srcid].get();
2065 
2066  if (srcstatspec == nullptr) {
2067  GrfMsg(1, "StationChangeInfo: Station {} is not defined, cannot copy tile layout to {}.", srcid, stid + i);
2068  continue;
2069  }
2070 
2071  statspec->layouts = srcstatspec->layouts;
2072  break;
2073  }
2074 
2075  case 0x10: // Little/lots cargo threshold
2076  statspec->cargo_threshold = buf.ReadWord();
2077  break;
2078 
2079  case 0x11: { // Pylon placement
2080  uint8_t pylons = buf.ReadByte();
2081  if (statspec->tileflags.size() < 8) statspec->tileflags.resize(8);
2082  for (int j = 0; j < 8; ++j) {
2083  if (HasBit(pylons, j)) {
2084  statspec->tileflags[j] |= StationSpec::TileFlags::Pylons;
2085  } else {
2086  statspec->tileflags[j] &= ~StationSpec::TileFlags::Pylons;
2087  }
2088  }
2089  break;
2090  }
2091 
2092  case 0x12: // Cargo types for random triggers
2093  if (_cur.grffile->grf_version >= 7) {
2094  statspec->cargo_triggers = TranslateRefitMask(buf.ReadDWord());
2095  } else {
2096  statspec->cargo_triggers = (CargoTypes)buf.ReadDWord();
2097  }
2098  break;
2099 
2100  case 0x13: // General flags
2101  statspec->flags = buf.ReadByte();
2102  break;
2103 
2104  case 0x14: { // Overhead wire placement
2105  uint8_t wires = buf.ReadByte();
2106  if (statspec->tileflags.size() < 8) statspec->tileflags.resize(8);
2107  for (int j = 0; j < 8; ++j) {
2108  if (HasBit(wires, j)) {
2109  statspec->tileflags[j] |= StationSpec::TileFlags::NoWires;
2110  } else {
2111  statspec->tileflags[j] &= ~StationSpec::TileFlags::NoWires;
2112  }
2113  }
2114  break;
2115  }
2116 
2117  case 0x15: { // Blocked tiles
2118  uint8_t blocked = buf.ReadByte();
2119  if (statspec->tileflags.size() < 8) statspec->tileflags.resize(8);
2120  for (int j = 0; j < 8; ++j) {
2121  if (HasBit(blocked, j)) {
2122  statspec->tileflags[j] |= StationSpec::TileFlags::Blocked;
2123  } else {
2124  statspec->tileflags[j] &= ~StationSpec::TileFlags::Blocked;
2125  }
2126  }
2127  break;
2128  }
2129 
2130  case 0x16: // Animation info
2131  statspec->animation.frames = buf.ReadByte();
2132  statspec->animation.status = buf.ReadByte();
2133  break;
2134 
2135  case 0x17: // Animation speed
2136  statspec->animation.speed = buf.ReadByte();
2137  break;
2138 
2139  case 0x18: // Animation triggers
2140  statspec->animation.triggers = buf.ReadWord();
2141  break;
2142 
2143  /* 0x19 road routing (not implemented) */
2144 
2145  case 0x1A: { // Advanced sprite layout
2146  uint16_t tiles = buf.ReadExtendedByte();
2147  statspec->renderdata.clear(); // delete earlier loaded stuff
2148  statspec->renderdata.reserve(tiles);
2149 
2150  for (uint t = 0; t < tiles; t++) {
2151  NewGRFSpriteLayout *dts = &statspec->renderdata.emplace_back();
2152  uint num_building_sprites = buf.ReadByte();
2153  /* On error, bail out immediately. Temporary GRF data was already freed */
2154  if (ReadSpriteLayout(buf, num_building_sprites, false, GSF_STATIONS, true, false, dts)) return CIR_DISABLED;
2155  }
2156 
2157  /* Number of layouts must be even, alternating X and Y */
2158  if (statspec->renderdata.size() & 1) {
2159  GrfMsg(1, "StationChangeInfo: Station {} defines an odd number of sprite layouts, dropping the last item", stid + i);
2160  statspec->renderdata.pop_back();
2161  }
2162  break;
2163  }
2164 
2165  case 0x1B: // Minimum bridge height (not implemented)
2166  buf.ReadWord();
2167  buf.ReadWord();
2168  buf.ReadWord();
2169  buf.ReadWord();
2170  break;
2171 
2172  case 0x1C: // Station Name
2173  AddStringForMapping(buf.ReadWord(), &statspec->name);
2174  break;
2175 
2176  case 0x1D: // Station Class name
2177  AddStringForMapping(buf.ReadWord(), [statspec = statspec.get()](StringID str) { StationClass::Get(statspec->class_index)->name = str; });
2178  break;
2179 
2180  case 0x1E: { // Extended tile flags (replaces prop 11, 14 and 15)
2181  uint16_t tiles = buf.ReadExtendedByte();
2182  auto flags = reinterpret_cast<const StationSpec::TileFlags *>(buf.ReadBytes(tiles));
2183  statspec->tileflags.assign(flags, flags + tiles);
2184  break;
2185  }
2186 
2187  default:
2188  ret = CIR_UNKNOWN;
2189  break;
2190  }
2191  }
2192 
2193  return ret;
2194 }
2195 
2204 static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, ByteReader &buf)
2205 {
2207 
2208  if (id + numinfo > CF_END) {
2209  GrfMsg(1, "CanalChangeInfo: Canal feature 0x{:02X} is invalid, max {}, ignoring", id + numinfo, CF_END);
2210  return CIR_INVALID_ID;
2211  }
2212 
2213  for (int i = 0; i < numinfo; i++) {
2214  CanalProperties *cp = &_cur.grffile->canal_local_properties[id + i];
2215 
2216  switch (prop) {
2217  case 0x08:
2218  cp->callback_mask = buf.ReadByte();
2219  break;
2220 
2221  case 0x09:
2222  cp->flags = buf.ReadByte();
2223  break;
2224 
2225  default:
2226  ret = CIR_UNKNOWN;
2227  break;
2228  }
2229  }
2230 
2231  return ret;
2232 }
2233 
2242 static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteReader &buf)
2243 {
2245 
2246  if (brid + numinfo > MAX_BRIDGES) {
2247  GrfMsg(1, "BridgeChangeInfo: Bridge {} is invalid, max {}, ignoring", brid + numinfo, MAX_BRIDGES);
2248  return CIR_INVALID_ID;
2249  }
2250 
2251  for (int i = 0; i < numinfo; i++) {
2252  BridgeSpec *bridge = &_bridge[brid + i];
2253 
2254  switch (prop) {
2255  case 0x08: { // Year of availability
2256  /* We treat '0' as always available */
2257  uint8_t year = buf.ReadByte();
2258  bridge->avail_year = (year > 0 ? CalendarTime::ORIGINAL_BASE_YEAR + year : 0);
2259  break;
2260  }
2261 
2262  case 0x09: // Minimum length
2263  bridge->min_length = buf.ReadByte();
2264  break;
2265 
2266  case 0x0A: // Maximum length
2267  bridge->max_length = buf.ReadByte();
2268  if (bridge->max_length > 16) bridge->max_length = UINT16_MAX;
2269  break;
2270 
2271  case 0x0B: // Cost factor
2272  bridge->price = buf.ReadByte();
2273  break;
2274 
2275  case 0x0C: // Maximum speed
2276  bridge->speed = buf.ReadWord();
2277  if (bridge->speed == 0) bridge->speed = UINT16_MAX;
2278  break;
2279 
2280  case 0x0D: { // Bridge sprite tables
2281  uint8_t tableid = buf.ReadByte();
2282  uint8_t numtables = buf.ReadByte();
2283 
2284  if (bridge->sprite_table == nullptr) {
2285  /* Allocate memory for sprite table pointers and zero out */
2286  bridge->sprite_table = CallocT<PalSpriteID*>(7);
2287  }
2288 
2289  for (; numtables-- != 0; tableid++) {
2290  if (tableid >= 7) { // skip invalid data
2291  GrfMsg(1, "BridgeChangeInfo: Table {} >= 7, skipping", tableid);
2292  for (uint8_t sprite = 0; sprite < 32; sprite++) buf.ReadDWord();
2293  continue;
2294  }
2295 
2296  if (bridge->sprite_table[tableid] == nullptr) {
2297  bridge->sprite_table[tableid] = MallocT<PalSpriteID>(32);
2298  }
2299 
2300  for (uint8_t sprite = 0; sprite < 32; sprite++) {
2301  SpriteID image = buf.ReadWord();
2302  PaletteID pal = buf.ReadWord();
2303 
2304  bridge->sprite_table[tableid][sprite].sprite = image;
2305  bridge->sprite_table[tableid][sprite].pal = pal;
2306 
2307  MapSpriteMappingRecolour(&bridge->sprite_table[tableid][sprite]);
2308  }
2309  }
2310  break;
2311  }
2312 
2313  case 0x0E: // Flags; bit 0 - disable far pillars
2314  bridge->flags = buf.ReadByte();
2315  break;
2316 
2317  case 0x0F: // Long format year of availability (year since year 0)
2319  break;
2320 
2321  case 0x10: { // purchase string
2322  StringID newone = GetGRFStringID(_cur.grffile->grfid, buf.ReadWord());
2323  if (newone != STR_UNDEFINED) bridge->material = newone;
2324  break;
2325  }
2326 
2327  case 0x11: // description of bridge with rails or roads
2328  case 0x12: {
2329  StringID newone = GetGRFStringID(_cur.grffile->grfid, buf.ReadWord());
2330  if (newone != STR_UNDEFINED) bridge->transport_name[prop - 0x11] = newone;
2331  break;
2332  }
2333 
2334  case 0x13: // 16 bits cost multiplier
2335  bridge->price = buf.ReadWord();
2336  break;
2337 
2338  default:
2339  ret = CIR_UNKNOWN;
2340  break;
2341  }
2342  }
2343 
2344  return ret;
2345 }
2346 
2354 {
2356 
2357  switch (prop) {
2358  case 0x09:
2359  case 0x0B:
2360  case 0x0C:
2361  case 0x0D:
2362  case 0x0E:
2363  case 0x0F:
2364  case 0x11:
2365  case 0x14:
2366  case 0x15:
2367  case 0x16:
2368  case 0x18:
2369  case 0x19:
2370  case 0x1A:
2371  case 0x1B:
2372  case 0x1C:
2373  case 0x1D:
2374  case 0x1F:
2375  buf.ReadByte();
2376  break;
2377 
2378  case 0x0A:
2379  case 0x10:
2380  case 0x12:
2381  case 0x13:
2382  case 0x21:
2383  case 0x22:
2384  buf.ReadWord();
2385  break;
2386 
2387  case 0x1E:
2388  buf.ReadDWord();
2389  break;
2390 
2391  case 0x17:
2392  for (uint j = 0; j < 4; j++) buf.ReadByte();
2393  break;
2394 
2395  case 0x20: {
2396  uint8_t count = buf.ReadByte();
2397  for (uint8_t j = 0; j < count; j++) buf.ReadByte();
2398  break;
2399  }
2400 
2401  case 0x23:
2402  buf.Skip(buf.ReadByte() * 2);
2403  break;
2404 
2405  default:
2406  ret = CIR_UNKNOWN;
2407  break;
2408  }
2409  return ret;
2410 }
2411 
2420 static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, ByteReader &buf)
2421 {
2423 
2424  if (hid + numinfo > NUM_HOUSES_PER_GRF) {
2425  GrfMsg(1, "TownHouseChangeInfo: Too many houses loaded ({}), max ({}). Ignoring.", hid + numinfo, NUM_HOUSES_PER_GRF);
2426  return CIR_INVALID_ID;
2427  }
2428 
2429  /* Allocate house specs if they haven't been allocated already. */
2430  if (_cur.grffile->housespec.size() < hid + numinfo) _cur.grffile->housespec.resize(hid + numinfo);
2431 
2432  for (int i = 0; i < numinfo; i++) {
2433  auto &housespec = _cur.grffile->housespec[hid + i];
2434 
2435  if (prop != 0x08 && housespec == nullptr) {
2436  /* If the house property 08 is not yet set, ignore this property */
2437  ChangeInfoResult cir = IgnoreTownHouseProperty(prop, buf);
2438  if (cir > ret) ret = cir;
2439  continue;
2440  }
2441 
2442  switch (prop) {
2443  case 0x08: { // Substitute building type, and definition of a new house
2444  uint8_t subs_id = buf.ReadByte();
2445  if (subs_id == 0xFF) {
2446  /* Instead of defining a new house, a substitute house id
2447  * of 0xFF disables the old house with the current id. */
2448  if (hid + i < NEW_HOUSE_OFFSET) HouseSpec::Get(hid + i)->enabled = false;
2449  continue;
2450  } else if (subs_id >= NEW_HOUSE_OFFSET) {
2451  /* The substitute id must be one of the original houses. */
2452  GrfMsg(2, "TownHouseChangeInfo: Attempt to use new house {} as substitute house for {}. Ignoring.", subs_id, hid + i);
2453  continue;
2454  }
2455 
2456  /* Allocate space for this house. */
2457  if (housespec == nullptr) {
2458  /* Only the first property 08 setting copies properties; if you later change it, properties will stay. */
2459  housespec = std::make_unique<HouseSpec>(*HouseSpec::Get(subs_id));
2460 
2461  housespec->enabled = true;
2462  housespec->grf_prop.local_id = hid + i;
2463  housespec->grf_prop.subst_id = subs_id;
2464  housespec->grf_prop.grffile = _cur.grffile;
2465  /* Set default colours for randomization, used if not overridden. */
2466  housespec->random_colour[0] = COLOUR_RED;
2467  housespec->random_colour[1] = COLOUR_BLUE;
2468  housespec->random_colour[2] = COLOUR_ORANGE;
2469  housespec->random_colour[3] = COLOUR_GREEN;
2470 
2471  /* House flags 40 and 80 are exceptions; these flags are never set automatically. */
2472  housespec->building_flags &= ~(BUILDING_IS_CHURCH | BUILDING_IS_STADIUM);
2473 
2474  /* Make sure that the third cargo type is valid in this
2475  * climate. This can cause problems when copying the properties
2476  * of a house that accepts food, where the new house is valid
2477  * in the temperate climate. */
2478  CargoID cid = housespec->accepts_cargo[2];
2479  if (!IsValidCargoID(cid)) cid = GetCargoIDByLabel(housespec->accepts_cargo_label[2]);
2480  if (!IsValidCargoID(cid)) {
2481  housespec->cargo_acceptance[2] = 0;
2482  }
2483  }
2484  break;
2485  }
2486 
2487  case 0x09: // Building flags
2488  housespec->building_flags = (BuildingFlags)buf.ReadByte();
2489  break;
2490 
2491  case 0x0A: { // Availability years
2492  uint16_t years = buf.ReadWord();
2493  housespec->min_year = GB(years, 0, 8) > 150 ? CalendarTime::MAX_YEAR : CalendarTime::ORIGINAL_BASE_YEAR + GB(years, 0, 8);
2494  housespec->max_year = GB(years, 8, 8) > 150 ? CalendarTime::MAX_YEAR : CalendarTime::ORIGINAL_BASE_YEAR + GB(years, 8, 8);
2495  break;
2496  }
2497 
2498  case 0x0B: // Population
2499  housespec->population = buf.ReadByte();
2500  break;
2501 
2502  case 0x0C: // Mail generation multiplier
2503  housespec->mail_generation = buf.ReadByte();
2504  break;
2505 
2506  case 0x0D: // Passenger acceptance
2507  case 0x0E: // Mail acceptance
2508  housespec->cargo_acceptance[prop - 0x0D] = buf.ReadByte();
2509  break;
2510 
2511  case 0x0F: { // Goods/candy, food/fizzy drinks acceptance
2512  int8_t goods = buf.ReadByte();
2513 
2514  /* If value of goods is negative, it means in fact food or, if in toyland, fizzy_drink acceptance.
2515  * Else, we have "standard" 3rd cargo type, goods or candy, for toyland once more */
2516  CargoID cid = (goods >= 0) ? ((_settings_game.game_creation.landscape == LT_TOYLAND) ? GetCargoIDByLabel(CT_CANDY) : GetCargoIDByLabel(CT_GOODS)) :
2517  ((_settings_game.game_creation.landscape == LT_TOYLAND) ? GetCargoIDByLabel(CT_FIZZY_DRINKS) : GetCargoIDByLabel(CT_FOOD));
2518 
2519  /* Make sure the cargo type is valid in this climate. */
2520  if (!IsValidCargoID(cid)) goods = 0;
2521 
2522  housespec->accepts_cargo[2] = cid;
2523  housespec->accepts_cargo_label[2] = CT_INVALID;
2524  housespec->cargo_acceptance[2] = abs(goods); // but we do need positive value here
2525  break;
2526  }
2527 
2528  case 0x10: // Local authority rating decrease on removal
2529  housespec->remove_rating_decrease = buf.ReadWord();
2530  break;
2531 
2532  case 0x11: // Removal cost multiplier
2533  housespec->removal_cost = buf.ReadByte();
2534  break;
2535 
2536  case 0x12: // Building name ID
2537  AddStringForMapping(buf.ReadWord(), &housespec->building_name);
2538  break;
2539 
2540  case 0x13: // Building availability mask
2541  housespec->building_availability = (HouseZones)buf.ReadWord();
2542  break;
2543 
2544  case 0x14: // House callback mask
2545  housespec->callback_mask |= buf.ReadByte();
2546  break;
2547 
2548  case 0x15: { // House override byte
2549  uint8_t override = buf.ReadByte();
2550 
2551  /* The house being overridden must be an original house. */
2552  if (override >= NEW_HOUSE_OFFSET) {
2553  GrfMsg(2, "TownHouseChangeInfo: Attempt to override new house {} with house id {}. Ignoring.", override, hid + i);
2554  continue;
2555  }
2556 
2557  _house_mngr.Add(hid + i, _cur.grffile->grfid, override);
2558  break;
2559  }
2560 
2561  case 0x16: // Periodic refresh multiplier
2562  housespec->processing_time = std::min<uint8_t>(buf.ReadByte(), 63u);
2563  break;
2564 
2565  case 0x17: // Four random colours to use
2566  for (uint j = 0; j < 4; j++) housespec->random_colour[j] = static_cast<Colours>(GB(buf.ReadByte(), 0, 4));
2567  break;
2568 
2569  case 0x18: // Relative probability of appearing
2570  housespec->probability = buf.ReadByte();
2571  break;
2572 
2573  case 0x19: // Extra flags
2574  housespec->extra_flags = (HouseExtraFlags)buf.ReadByte();
2575  break;
2576 
2577  case 0x1A: // Animation frames
2578  housespec->animation.frames = buf.ReadByte();
2579  housespec->animation.status = GB(housespec->animation.frames, 7, 1);
2580  SB(housespec->animation.frames, 7, 1, 0);
2581  break;
2582 
2583  case 0x1B: // Animation speed
2584  housespec->animation.speed = Clamp(buf.ReadByte(), 2, 16);
2585  break;
2586 
2587  case 0x1C: // Class of the building type
2588  housespec->class_id = AllocateHouseClassID(buf.ReadByte(), _cur.grffile->grfid);
2589  break;
2590 
2591  case 0x1D: // Callback mask part 2
2592  housespec->callback_mask |= (buf.ReadByte() << 8);
2593  break;
2594 
2595  case 0x1E: { // Accepted cargo types
2596  uint32_t cargotypes = buf.ReadDWord();
2597 
2598  /* Check if the cargo types should not be changed */
2599  if (cargotypes == 0xFFFFFFFF) break;
2600 
2601  for (uint j = 0; j < HOUSE_ORIGINAL_NUM_ACCEPTS; j++) {
2602  /* Get the cargo number from the 'list' */
2603  uint8_t cargo_part = GB(cargotypes, 8 * j, 8);
2604  CargoID cargo = GetCargoTranslation(cargo_part, _cur.grffile);
2605 
2606  if (!IsValidCargoID(cargo)) {
2607  /* Disable acceptance of invalid cargo type */
2608  housespec->cargo_acceptance[j] = 0;
2609  } else {
2610  housespec->accepts_cargo[j] = cargo;
2611  }
2612  housespec->accepts_cargo_label[j] = CT_INVALID;
2613  }
2614  break;
2615  }
2616 
2617  case 0x1F: // Minimum life span
2618  housespec->minimum_life = buf.ReadByte();
2619  break;
2620 
2621  case 0x20: { // Cargo acceptance watch list
2622  uint8_t count = buf.ReadByte();
2623  for (uint8_t j = 0; j < count; j++) {
2624  CargoID cargo = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
2625  if (IsValidCargoID(cargo)) SetBit(housespec->watched_cargoes, cargo);
2626  }
2627  break;
2628  }
2629 
2630  case 0x21: // long introduction year
2631  housespec->min_year = buf.ReadWord();
2632  break;
2633 
2634  case 0x22: // long maximum year
2635  housespec->max_year = buf.ReadWord();
2636  if (housespec->max_year == UINT16_MAX) housespec->max_year = CalendarTime::MAX_YEAR;
2637  break;
2638 
2639  case 0x23: { // variable length cargo types accepted
2640  uint count = buf.ReadByte();
2641  if (count > lengthof(housespec->accepts_cargo)) {
2642  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
2643  error->param_value[1] = prop;
2644  return CIR_DISABLED;
2645  }
2646  /* Always write the full accepts_cargo array, and check each index for being inside the
2647  * provided data. This ensures all values are properly initialized, and also avoids
2648  * any risks of array overrun. */
2649  for (uint i = 0; i < lengthof(housespec->accepts_cargo); i++) {
2650  if (i < count) {
2651  housespec->accepts_cargo[i] = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
2652  housespec->cargo_acceptance[i] = buf.ReadByte();
2653  } else {
2654  housespec->accepts_cargo[i] = INVALID_CARGO;
2655  housespec->cargo_acceptance[i] = 0;
2656  }
2657  housespec->accepts_cargo_label[i] = CT_INVALID;
2658  }
2659  break;
2660  }
2661 
2662  default:
2663  ret = CIR_UNKNOWN;
2664  break;
2665  }
2666  }
2667 
2668  return ret;
2669 }
2670 
2677 /* static */ const LanguageMap *LanguageMap::GetLanguageMap(uint32_t grfid, uint8_t language_id)
2678 {
2679  /* LanguageID "MAX_LANG", i.e. 7F is any. This language can't have a gender/case mapping, but has to be handled gracefully. */
2680  const GRFFile *grffile = GetFileByGRFID(grfid);
2681  if (grffile == nullptr) return nullptr;
2682 
2683  auto it = grffile->language_map.find(language_id);
2684  if (it == std::end(grffile->language_map)) return nullptr;
2685 
2686  return &it->second;
2687 }
2688 
2698 template <typename T>
2699 static ChangeInfoResult LoadTranslationTable(uint gvid, int numinfo, ByteReader &buf, std::vector<T> &translation_table, const char *name)
2700 {
2701  if (gvid != 0) {
2702  GrfMsg(1, "LoadTranslationTable: {} translation table must start at zero", name);
2703  return CIR_INVALID_ID;
2704  }
2705 
2706  translation_table.clear();
2707  translation_table.reserve(numinfo);
2708  for (int i = 0; i < numinfo; i++) {
2709  translation_table.push_back(T(BSWAP32(buf.ReadDWord())));
2710  }
2711 
2712  return CIR_SUCCESS;
2713 }
2714 
2721 static std::string ReadDWordAsString(ByteReader &reader)
2722 {
2723  std::string output;
2724  for (int i = 0; i < 4; i++) output.push_back(reader.ReadByte());
2725  return StrMakeValid(output);
2726 }
2727 
2736 static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader &buf)
2737 {
2738  /* Properties which are handled as a whole */
2739  switch (prop) {
2740  case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2741  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2742 
2743  case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2744  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2745 
2746  case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2747  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2748 
2749  case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2750  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
2751 
2752  default:
2753  break;
2754  }
2755 
2756  /* Properties which are handled per item */
2758  for (int i = 0; i < numinfo; i++) {
2759  switch (prop) {
2760  case 0x08: { // Cost base factor
2761  int factor = buf.ReadByte();
2762  uint price = gvid + i;
2763 
2764  if (price < PR_END) {
2765  _cur.grffile->price_base_multipliers[price] = std::min<int>(factor - 8, MAX_PRICE_MODIFIER);
2766  } else {
2767  GrfMsg(1, "GlobalVarChangeInfo: Price {} out of range, ignoring", price);
2768  }
2769  break;
2770  }
2771 
2772  case 0x0A: { // Currency display names
2773  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2774  StringID newone = GetGRFStringID(_cur.grffile->grfid, buf.ReadWord());
2775 
2776  if ((newone != STR_UNDEFINED) && (curidx < CURRENCY_END)) {
2777  _currency_specs[curidx].name = newone;
2778  _currency_specs[curidx].code.clear();
2779  }
2780  break;
2781  }
2782 
2783  case 0x0B: { // Currency multipliers
2784  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2785  uint32_t rate = buf.ReadDWord();
2786 
2787  if (curidx < CURRENCY_END) {
2788  /* TTDPatch uses a multiple of 1000 for its conversion calculations,
2789  * which OTTD does not. For this reason, divide grf value by 1000,
2790  * to be compatible */
2791  _currency_specs[curidx].rate = rate / 1000;
2792  } else {
2793  GrfMsg(1, "GlobalVarChangeInfo: Currency multipliers {} out of range, ignoring", curidx);
2794  }
2795  break;
2796  }
2797 
2798  case 0x0C: { // Currency options
2799  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2800  uint16_t options = buf.ReadWord();
2801 
2802  if (curidx < CURRENCY_END) {
2803  _currency_specs[curidx].separator.clear();
2804  _currency_specs[curidx].separator.push_back(GB(options, 0, 8));
2805  /* By specifying only one bit, we prevent errors,
2806  * since newgrf specs said that only 0 and 1 can be set for symbol_pos */
2807  _currency_specs[curidx].symbol_pos = GB(options, 8, 1);
2808  } else {
2809  GrfMsg(1, "GlobalVarChangeInfo: Currency option {} out of range, ignoring", curidx);
2810  }
2811  break;
2812  }
2813 
2814  case 0x0D: { // Currency prefix symbol
2815  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2816  std::string prefix = ReadDWordAsString(buf);
2817 
2818  if (curidx < CURRENCY_END) {
2819  _currency_specs[curidx].prefix = prefix;
2820  } else {
2821  GrfMsg(1, "GlobalVarChangeInfo: Currency symbol {} out of range, ignoring", curidx);
2822  }
2823  break;
2824  }
2825 
2826  case 0x0E: { // Currency suffix symbol
2827  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2828  std::string suffix = ReadDWordAsString(buf);
2829 
2830  if (curidx < CURRENCY_END) {
2831  _currency_specs[curidx].suffix = suffix;
2832  } else {
2833  GrfMsg(1, "GlobalVarChangeInfo: Currency symbol {} out of range, ignoring", curidx);
2834  }
2835  break;
2836  }
2837 
2838  case 0x0F: { // Euro introduction dates
2839  uint curidx = GetNewgrfCurrencyIdConverted(gvid + i);
2840  TimerGameCalendar::Year year_euro = buf.ReadWord();
2841 
2842  if (curidx < CURRENCY_END) {
2843  _currency_specs[curidx].to_euro = year_euro;
2844  } else {
2845  GrfMsg(1, "GlobalVarChangeInfo: Euro intro date {} out of range, ignoring", curidx);
2846  }
2847  break;
2848  }
2849 
2850  case 0x10: // Snow line height table
2851  if (numinfo > 1 || IsSnowLineSet()) {
2852  GrfMsg(1, "GlobalVarChangeInfo: The snowline can only be set once ({})", numinfo);
2853  } else if (buf.Remaining() < SNOW_LINE_MONTHS * SNOW_LINE_DAYS) {
2854  GrfMsg(1, "GlobalVarChangeInfo: Not enough entries set in the snowline table ({})", buf.Remaining());
2855  } else {
2856  uint8_t table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS];
2857 
2858  for (uint i = 0; i < SNOW_LINE_MONTHS; i++) {
2859  for (uint j = 0; j < SNOW_LINE_DAYS; j++) {
2860  table[i][j] = buf.ReadByte();
2861  if (_cur.grffile->grf_version >= 8) {
2862  if (table[i][j] != 0xFF) table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 256;
2863  } else {
2864  if (table[i][j] >= 128) {
2865  /* no snow */
2866  table[i][j] = 0xFF;
2867  } else {
2868  table[i][j] = table[i][j] * (1 + _settings_game.construction.map_height_limit) / 128;
2869  }
2870  }
2871  }
2872  }
2873  SetSnowLine(table);
2874  }
2875  break;
2876 
2877  case 0x11: // GRF match for engine allocation
2878  /* This is loaded during the reservation stage, so just skip it here. */
2879  /* Each entry is 8 bytes. */
2880  buf.Skip(8);
2881  break;
2882 
2883  case 0x13: // Gender translation table
2884  case 0x14: // Case translation table
2885  case 0x15: { // Plural form translation
2886  uint curidx = gvid + i; // The current index, i.e. language.
2887  const LanguageMetadata *lang = curidx < MAX_LANG ? GetLanguage(curidx) : nullptr;
2888  if (lang == nullptr) {
2889  GrfMsg(1, "GlobalVarChangeInfo: Language {} is not known, ignoring", curidx);
2890  /* Skip over the data. */
2891  if (prop == 0x15) {
2892  buf.ReadByte();
2893  } else {
2894  while (buf.ReadByte() != 0) {
2895  buf.ReadString();
2896  }
2897  }
2898  break;
2899  }
2900 
2901  if (prop == 0x15) {
2902  uint plural_form = buf.ReadByte();
2903  if (plural_form >= LANGUAGE_MAX_PLURAL) {
2904  GrfMsg(1, "GlobalVarChanceInfo: Plural form {} is out of range, ignoring", plural_form);
2905  } else {
2906  _cur.grffile->language_map[curidx].plural_form = plural_form;
2907  }
2908  break;
2909  }
2910 
2911  uint8_t newgrf_id = buf.ReadByte(); // The NewGRF (custom) identifier.
2912  while (newgrf_id != 0) {
2913  std::string_view name = buf.ReadString(); // The name for the OpenTTD identifier.
2914 
2915  /* We'll just ignore the UTF8 identifier character. This is (fairly)
2916  * safe as OpenTTD's strings gender/cases are usually in ASCII which
2917  * is just a subset of UTF8, or they need the bigger UTF8 characters
2918  * such as Cyrillic. Thus we will simply assume they're all UTF8. */
2919  char32_t c;
2920  size_t len = Utf8Decode(&c, name.data());
2921  if (c == NFO_UTF8_IDENTIFIER) name = name.substr(len);
2922 
2924  map.newgrf_id = newgrf_id;
2925  if (prop == 0x13) {
2926  map.openttd_id = lang->GetGenderIndex(name.data());
2927  if (map.openttd_id >= MAX_NUM_GENDERS) {
2928  GrfMsg(1, "GlobalVarChangeInfo: Gender name {} is not known, ignoring", StrMakeValid(name));
2929  } else {
2930  _cur.grffile->language_map[curidx].gender_map.push_back(map);
2931  }
2932  } else {
2933  map.openttd_id = lang->GetCaseIndex(name.data());
2934  if (map.openttd_id >= MAX_NUM_CASES) {
2935  GrfMsg(1, "GlobalVarChangeInfo: Case name {} is not known, ignoring", StrMakeValid(name));
2936  } else {
2937  _cur.grffile->language_map[curidx].case_map.push_back(map);
2938  }
2939  }
2940  newgrf_id = buf.ReadByte();
2941  }
2942  break;
2943  }
2944 
2945  default:
2946  ret = CIR_UNKNOWN;
2947  break;
2948  }
2949  }
2950 
2951  return ret;
2952 }
2953 
2954 static ChangeInfoResult GlobalVarReserveInfo(uint gvid, int numinfo, int prop, ByteReader &buf)
2955 {
2956  /* Properties which are handled as a whole */
2957  switch (prop) {
2958  case 0x09: // Cargo Translation Table; loading during both reservation and activation stage (in case it is selected depending on defined cargos)
2959  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->cargo_list, "Cargo");
2960 
2961  case 0x12: // Rail type translation table; loading during both reservation and activation stage (in case it is selected depending on defined railtypes)
2962  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->railtype_list, "Rail type");
2963 
2964  case 0x16: // Road type translation table; loading during both reservation and activation stage (in case it is selected depending on defined roadtypes)
2965  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->roadtype_list, "Road type");
2966 
2967  case 0x17: // Tram type translation table; loading during both reservation and activation stage (in case it is selected depending on defined tramtypes)
2968  return LoadTranslationTable(gvid, numinfo, buf, _cur.grffile->tramtype_list, "Tram type");
2969 
2970  default:
2971  break;
2972  }
2973 
2974  /* Properties which are handled per item */
2976  for (int i = 0; i < numinfo; i++) {
2977  switch (prop) {
2978  case 0x08: // Cost base factor
2979  case 0x15: // Plural form translation
2980  buf.ReadByte();
2981  break;
2982 
2983  case 0x0A: // Currency display names
2984  case 0x0C: // Currency options
2985  case 0x0F: // Euro introduction dates
2986  buf.ReadWord();
2987  break;
2988 
2989  case 0x0B: // Currency multipliers
2990  case 0x0D: // Currency prefix symbol
2991  case 0x0E: // Currency suffix symbol
2992  buf.ReadDWord();
2993  break;
2994 
2995  case 0x10: // Snow line height table
2996  buf.Skip(SNOW_LINE_MONTHS * SNOW_LINE_DAYS);
2997  break;
2998 
2999  case 0x11: { // GRF match for engine allocation
3000  uint32_t s = buf.ReadDWord();
3001  uint32_t t = buf.ReadDWord();
3002  SetNewGRFOverride(s, t);
3003  break;
3004  }
3005 
3006  case 0x13: // Gender translation table
3007  case 0x14: // Case translation table
3008  while (buf.ReadByte() != 0) {
3009  buf.ReadString();
3010  }
3011  break;
3012 
3013  default:
3014  ret = CIR_UNKNOWN;
3015  break;
3016  }
3017  }
3018 
3019  return ret;
3020 }
3021 
3022 
3031 static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader &buf)
3032 {
3034 
3035  if (cid + numinfo > NUM_CARGO) {
3036  GrfMsg(2, "CargoChangeInfo: Cargo type {} out of range (max {})", cid + numinfo, NUM_CARGO - 1);
3037  return CIR_INVALID_ID;
3038  }
3039 
3040  for (int i = 0; i < numinfo; i++) {
3041  CargoSpec *cs = CargoSpec::Get(cid + i);
3042 
3043  switch (prop) {
3044  case 0x08: // Bit number of cargo
3045  cs->bitnum = buf.ReadByte();
3046  if (cs->IsValid()) {
3047  cs->grffile = _cur.grffile;
3048  SetBit(_cargo_mask, cid + i);
3049  } else {
3050  ClrBit(_cargo_mask, cid + i);
3051  }
3053  break;
3054 
3055  case 0x09: // String ID for cargo type name
3056  AddStringForMapping(buf.ReadWord(), &cs->name);
3057  break;
3058 
3059  case 0x0A: // String for 1 unit of cargo
3060  AddStringForMapping(buf.ReadWord(), &cs->name_single);
3061  break;
3062 
3063  case 0x0B: // String for singular quantity of cargo (e.g. 1 tonne of coal)
3064  case 0x1B: // String for cargo units
3065  /* String for units of cargo. This is different in OpenTTD
3066  * (e.g. tonnes) to TTDPatch (e.g. {COMMA} tonne of coal).
3067  * Property 1B is used to set OpenTTD's behaviour. */
3068  AddStringForMapping(buf.ReadWord(), &cs->units_volume);
3069  break;
3070 
3071  case 0x0C: // String for plural quantity of cargo (e.g. 10 tonnes of coal)
3072  case 0x1C: // String for any amount of cargo
3073  /* Strings for an amount of cargo. This is different in OpenTTD
3074  * (e.g. {WEIGHT} of coal) to TTDPatch (e.g. {COMMA} tonnes of coal).
3075  * Property 1C is used to set OpenTTD's behaviour. */
3076  AddStringForMapping(buf.ReadWord(), &cs->quantifier);
3077  break;
3078 
3079  case 0x0D: // String for two letter cargo abbreviation
3080  AddStringForMapping(buf.ReadWord(), &cs->abbrev);
3081  break;
3082 
3083  case 0x0E: // Sprite ID for cargo icon
3084  cs->sprite = buf.ReadWord();
3085  break;
3086 
3087  case 0x0F: // Weight of one unit of cargo
3088  cs->weight = buf.ReadByte();
3089  break;
3090 
3091  case 0x10: // Used for payment calculation
3092  cs->transit_periods[0] = buf.ReadByte();
3093  break;
3094 
3095  case 0x11: // Used for payment calculation
3096  cs->transit_periods[1] = buf.ReadByte();
3097  break;
3098 
3099  case 0x12: // Base cargo price
3100  cs->initial_payment = buf.ReadDWord();
3101  break;
3102 
3103  case 0x13: // Colour for station rating bars
3104  cs->rating_colour = buf.ReadByte();
3105  break;
3106 
3107  case 0x14: // Colour for cargo graph
3108  cs->legend_colour = buf.ReadByte();
3109  break;
3110 
3111  case 0x15: // Freight status
3112  cs->is_freight = (buf.ReadByte() != 0);
3113  break;
3114 
3115  case 0x16: // Cargo classes
3116  cs->classes = buf.ReadWord();
3117  break;
3118 
3119  case 0x17: // Cargo label
3120  cs->label = CargoLabel{BSWAP32(buf.ReadDWord())};
3122  break;
3123 
3124  case 0x18: { // Town growth substitute type
3125  uint8_t substitute_type = buf.ReadByte();
3126 
3127  switch (substitute_type) {
3128  case 0x00: cs->town_acceptance_effect = TAE_PASSENGERS; break;
3129  case 0x02: cs->town_acceptance_effect = TAE_MAIL; break;
3130  case 0x05: cs->town_acceptance_effect = TAE_GOODS; break;
3131  case 0x09: cs->town_acceptance_effect = TAE_WATER; break;
3132  case 0x0B: cs->town_acceptance_effect = TAE_FOOD; break;
3133  default:
3134  GrfMsg(1, "CargoChangeInfo: Unknown town growth substitute value {}, setting to none.", substitute_type);
3135  [[fallthrough]];
3136  case 0xFF: cs->town_acceptance_effect = TAE_NONE; break;
3137  }
3138  break;
3139  }
3140 
3141  case 0x19: // Town growth coefficient
3142  buf.ReadWord();
3143  break;
3144 
3145  case 0x1A: // Bitmask of callbacks to use
3146  cs->callback_mask = buf.ReadByte();
3147  break;
3148 
3149  case 0x1D: // Vehicle capacity muliplier
3150  cs->multiplier = std::max<uint16_t>(1u, buf.ReadWord());
3151  break;
3152 
3153  case 0x1E: { // Town production substitute type
3154  uint8_t substitute_type = buf.ReadByte();
3155 
3156  switch (substitute_type) {
3157  case 0x00: cs->town_production_effect = TPE_PASSENGERS; break;
3158  case 0x02: cs->town_production_effect = TPE_MAIL; break;
3159  default:
3160  GrfMsg(1, "CargoChangeInfo: Unknown town production substitute value {}, setting to none.", substitute_type);
3161  [[fallthrough]];
3162  case 0xFF: cs->town_production_effect = TPE_NONE; break;
3163  }
3164  break;
3165  }
3166 
3167  case 0x1F: // Town production multiplier
3168  cs->town_production_multiplier = std::max<uint16_t>(1U, buf.ReadWord());
3169  break;
3170 
3171  default:
3172  ret = CIR_UNKNOWN;
3173  break;
3174  }
3175  }
3176 
3177  return ret;
3178 }
3179 
3180 
3189 static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, ByteReader &buf)
3190 {
3192 
3193  if (_cur.grffile->sound_offset == 0) {
3194  GrfMsg(1, "SoundEffectChangeInfo: No effects defined, skipping");
3195  return CIR_INVALID_ID;
3196  }
3197 
3198  if (sid + numinfo - ORIGINAL_SAMPLE_COUNT > _cur.grffile->num_sounds) {
3199  GrfMsg(1, "SoundEffectChangeInfo: Attempting to change undefined sound effect ({}), max ({}). Ignoring.", sid + numinfo, ORIGINAL_SAMPLE_COUNT + _cur.grffile->num_sounds);
3200  return CIR_INVALID_ID;
3201  }
3202 
3203  for (int i = 0; i < numinfo; i++) {
3204  SoundEntry *sound = GetSound(sid + i + _cur.grffile->sound_offset - ORIGINAL_SAMPLE_COUNT);
3205 
3206  switch (prop) {
3207  case 0x08: // Relative volume
3208  sound->volume = Clamp(buf.ReadByte(), 0, SOUND_EFFECT_MAX_VOLUME);
3209  break;
3210 
3211  case 0x09: // Priority
3212  sound->priority = buf.ReadByte();
3213  break;
3214 
3215  case 0x0A: { // Override old sound
3216  SoundID orig_sound = buf.ReadByte();
3217 
3218  if (orig_sound >= ORIGINAL_SAMPLE_COUNT) {
3219  GrfMsg(1, "SoundEffectChangeInfo: Original sound {} not defined (max {})", orig_sound, ORIGINAL_SAMPLE_COUNT);
3220  } else {
3221  SoundEntry *old_sound = GetSound(orig_sound);
3222 
3223  /* Literally copy the data of the new sound over the original */
3224  *old_sound = *sound;
3225  }
3226  break;
3227  }
3228 
3229  default:
3230  ret = CIR_UNKNOWN;
3231  break;
3232  }
3233  }
3234 
3235  return ret;
3236 }
3237 
3245 {
3247 
3248  switch (prop) {
3249  case 0x09:
3250  case 0x0D:
3251  case 0x0E:
3252  case 0x10:
3253  case 0x11:
3254  case 0x12:
3255  buf.ReadByte();
3256  break;
3257 
3258  case 0x0A:
3259  case 0x0B:
3260  case 0x0C:
3261  case 0x0F:
3262  buf.ReadWord();
3263  break;
3264 
3265  case 0x13:
3266  buf.Skip(buf.ReadByte() * 2);
3267  break;
3268 
3269  default:
3270  ret = CIR_UNKNOWN;
3271  break;
3272  }
3273  return ret;
3274 }
3275 
3284 static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader &buf)
3285 {
3287 
3288  if (indtid + numinfo > NUM_INDUSTRYTILES_PER_GRF) {
3289  GrfMsg(1, "IndustryTilesChangeInfo: Too many industry tiles loaded ({}), max ({}). Ignoring.", indtid + numinfo, NUM_INDUSTRYTILES_PER_GRF);
3290  return CIR_INVALID_ID;
3291  }
3292 
3293  /* Allocate industry tile specs if they haven't been allocated already. */
3294  if (_cur.grffile->indtspec.size() < indtid + numinfo) _cur.grffile->indtspec.resize(indtid + numinfo);
3295 
3296  for (int i = 0; i < numinfo; i++) {
3297  auto &tsp = _cur.grffile->indtspec[indtid + i];
3298 
3299  if (prop != 0x08 && tsp == nullptr) {
3301  if (cir > ret) ret = cir;
3302  continue;
3303  }
3304 
3305  switch (prop) {
3306  case 0x08: { // Substitute industry tile type
3307  uint8_t subs_id = buf.ReadByte();
3308  if (subs_id >= NEW_INDUSTRYTILEOFFSET) {
3309  /* The substitute id must be one of the original industry tile. */
3310  GrfMsg(2, "IndustryTilesChangeInfo: Attempt to use new industry tile {} as substitute industry tile for {}. Ignoring.", subs_id, indtid + i);
3311  continue;
3312  }
3313 
3314  /* Allocate space for this industry. */
3315  if (tsp == nullptr) {
3316  tsp = std::make_unique<IndustryTileSpec>(_industry_tile_specs[subs_id]);
3317 
3318  tsp->enabled = true;
3319 
3320  /* A copied tile should not have the animation infos copied too.
3321  * The anim_state should be left untouched, though
3322  * It is up to the author to animate them */
3323  tsp->anim_production = INDUSTRYTILE_NOANIM;
3324  tsp->anim_next = INDUSTRYTILE_NOANIM;
3325 
3326  tsp->grf_prop.local_id = indtid + i;
3327  tsp->grf_prop.subst_id = subs_id;
3328  tsp->grf_prop.grffile = _cur.grffile;
3329  _industile_mngr.AddEntityID(indtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
3330  }
3331  break;
3332  }
3333 
3334  case 0x09: { // Industry tile override
3335  uint8_t ovrid = buf.ReadByte();
3336 
3337  /* The industry being overridden must be an original industry. */
3338  if (ovrid >= NEW_INDUSTRYTILEOFFSET) {
3339  GrfMsg(2, "IndustryTilesChangeInfo: Attempt to override new industry tile {} with industry tile id {}. Ignoring.", ovrid, indtid + i);
3340  continue;
3341  }
3342 
3343  _industile_mngr.Add(indtid + i, _cur.grffile->grfid, ovrid);
3344  break;
3345  }
3346 
3347  case 0x0A: // Tile acceptance
3348  case 0x0B:
3349  case 0x0C: {
3350  uint16_t acctp = buf.ReadWord();
3351  tsp->accepts_cargo[prop - 0x0A] = GetCargoTranslation(GB(acctp, 0, 8), _cur.grffile);
3352  tsp->acceptance[prop - 0x0A] = Clamp(GB(acctp, 8, 8), 0, 16);
3353  tsp->accepts_cargo_label[prop - 0x0A] = CT_INVALID;
3354  break;
3355  }
3356 
3357  case 0x0D: // Land shape flags
3358  tsp->slopes_refused = (Slope)buf.ReadByte();
3359  break;
3360 
3361  case 0x0E: // Callback mask
3362  tsp->callback_mask = buf.ReadByte();
3363  break;
3364 
3365  case 0x0F: // Animation information
3366  tsp->animation.frames = buf.ReadByte();
3367  tsp->animation.status = buf.ReadByte();
3368  break;
3369 
3370  case 0x10: // Animation speed
3371  tsp->animation.speed = buf.ReadByte();
3372  break;
3373 
3374  case 0x11: // Triggers for callback 25
3375  tsp->animation.triggers = buf.ReadByte();
3376  break;
3377 
3378  case 0x12: // Special flags
3379  tsp->special_flags = (IndustryTileSpecialFlags)buf.ReadByte();
3380  break;
3381 
3382  case 0x13: { // variable length cargo acceptance
3383  uint8_t num_cargoes = buf.ReadByte();
3384  if (num_cargoes > std::size(tsp->acceptance)) {
3385  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3386  error->param_value[1] = prop;
3387  return CIR_DISABLED;
3388  }
3389  for (uint i = 0; i < std::size(tsp->acceptance); i++) {
3390  if (i < num_cargoes) {
3391  tsp->accepts_cargo[i] = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
3392  /* Tile acceptance can be negative to counteract the INDTILE_SPECIAL_ACCEPTS_ALL_CARGO flag */
3393  tsp->acceptance[i] = (int8_t)buf.ReadByte();
3394  } else {
3395  tsp->accepts_cargo[i] = INVALID_CARGO;
3396  tsp->acceptance[i] = 0;
3397  }
3398  tsp->accepts_cargo_label[i] = CT_INVALID;
3399  }
3400  break;
3401  }
3402 
3403  default:
3404  ret = CIR_UNKNOWN;
3405  break;
3406  }
3407  }
3408 
3409  return ret;
3410 }
3411 
3419 {
3421 
3422  switch (prop) {
3423  case 0x09:
3424  case 0x0B:
3425  case 0x0F:
3426  case 0x12:
3427  case 0x13:
3428  case 0x14:
3429  case 0x17:
3430  case 0x18:
3431  case 0x19:
3432  case 0x21:
3433  case 0x22:
3434  buf.ReadByte();
3435  break;
3436 
3437  case 0x0C:
3438  case 0x0D:
3439  case 0x0E:
3440  case 0x10: // INDUSTRY_ORIGINAL_NUM_OUTPUTS bytes
3441  case 0x1B:
3442  case 0x1F:
3443  case 0x24:
3444  buf.ReadWord();
3445  break;
3446 
3447  case 0x11: // INDUSTRY_ORIGINAL_NUM_INPUTS bytes + 1
3448  case 0x1A:
3449  case 0x1C:
3450  case 0x1D:
3451  case 0x1E:
3452  case 0x20:
3453  case 0x23:
3454  buf.ReadDWord();
3455  break;
3456 
3457  case 0x0A: {
3458  uint8_t num_table = buf.ReadByte();
3459  for (uint8_t j = 0; j < num_table; j++) {
3460  for (uint k = 0;; k++) {
3461  uint8_t x = buf.ReadByte();
3462  if (x == 0xFE && k == 0) {
3463  buf.ReadByte();
3464  buf.ReadByte();
3465  break;
3466  }
3467 
3468  uint8_t y = buf.ReadByte();
3469  if (x == 0 && y == 0x80) break;
3470 
3471  uint8_t gfx = buf.ReadByte();
3472  if (gfx == 0xFE) buf.ReadWord();
3473  }
3474  }
3475  break;
3476  }
3477 
3478  case 0x16:
3479  for (uint8_t j = 0; j < INDUSTRY_ORIGINAL_NUM_INPUTS; j++) buf.ReadByte();
3480  break;
3481 
3482  case 0x15:
3483  case 0x25:
3484  case 0x26:
3485  case 0x27:
3486  buf.Skip(buf.ReadByte());
3487  break;
3488 
3489  case 0x28: {
3490  int num_inputs = buf.ReadByte();
3491  int num_outputs = buf.ReadByte();
3492  buf.Skip(num_inputs * num_outputs * 2);
3493  break;
3494  }
3495 
3496  default:
3497  ret = CIR_UNKNOWN;
3498  break;
3499  }
3500  return ret;
3501 }
3502 
3508 static bool ValidateIndustryLayout(const IndustryTileLayout &layout)
3509 {
3510  const size_t size = layout.size();
3511  if (size == 0) return false;
3512 
3513  for (size_t i = 0; i < size - 1; i++) {
3514  for (size_t j = i + 1; j < size; j++) {
3515  if (layout[i].ti.x == layout[j].ti.x &&
3516  layout[i].ti.y == layout[j].ti.y) {
3517  return false;
3518  }
3519  }
3520  }
3521 
3522  bool have_regular_tile = false;
3523  for (const auto &tilelayout : layout) {
3524  if (tilelayout.gfx != GFX_WATERTILE_SPECIALCHECK) {
3525  have_regular_tile = true;
3526  break;
3527  }
3528  }
3529 
3530  return have_regular_tile;
3531 }
3532 
3541 static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, ByteReader &buf)
3542 {
3544 
3545  if (indid + numinfo > NUM_INDUSTRYTYPES_PER_GRF) {
3546  GrfMsg(1, "IndustriesChangeInfo: Too many industries loaded ({}), max ({}). Ignoring.", indid + numinfo, NUM_INDUSTRYTYPES_PER_GRF);
3547  return CIR_INVALID_ID;
3548  }
3549 
3550  /* Allocate industry specs if they haven't been allocated already. */
3551  if (_cur.grffile->industryspec.size() < indid + numinfo) _cur.grffile->industryspec.resize(indid + numinfo);
3552 
3553  for (int i = 0; i < numinfo; i++) {
3554  auto &indsp = _cur.grffile->industryspec[indid + i];
3555 
3556  if (prop != 0x08 && indsp == nullptr) {
3557  ChangeInfoResult cir = IgnoreIndustryProperty(prop, buf);
3558  if (cir > ret) ret = cir;
3559  continue;
3560  }
3561 
3562  switch (prop) {
3563  case 0x08: { // Substitute industry type
3564  uint8_t subs_id = buf.ReadByte();
3565  if (subs_id == 0xFF) {
3566  /* Instead of defining a new industry, a substitute industry id
3567  * of 0xFF disables the old industry with the current id. */
3568  _industry_specs[indid + i].enabled = false;
3569  continue;
3570  } else if (subs_id >= NEW_INDUSTRYOFFSET) {
3571  /* The substitute id must be one of the original industry. */
3572  GrfMsg(2, "_industry_specs: Attempt to use new industry {} as substitute industry for {}. Ignoring.", subs_id, indid + i);
3573  continue;
3574  }
3575 
3576  /* Allocate space for this industry.
3577  * Only need to do it once. If ever it is called again, it should not
3578  * do anything */
3579  if (indsp == nullptr) {
3580  indsp = std::make_unique<IndustrySpec>(_origin_industry_specs[subs_id]);
3581 
3582  indsp->enabled = true;
3583  indsp->grf_prop.local_id = indid + i;
3584  indsp->grf_prop.subst_id = subs_id;
3585  indsp->grf_prop.grffile = _cur.grffile;
3586  /* If the grf industry needs to check its surrounding upon creation, it should
3587  * rely on callbacks, not on the original placement functions */
3588  indsp->check_proc = CHECK_NOTHING;
3589  }
3590  break;
3591  }
3592 
3593  case 0x09: { // Industry type override
3594  uint8_t ovrid = buf.ReadByte();
3595 
3596  /* The industry being overridden must be an original industry. */
3597  if (ovrid >= NEW_INDUSTRYOFFSET) {
3598  GrfMsg(2, "IndustriesChangeInfo: Attempt to override new industry {} with industry id {}. Ignoring.", ovrid, indid + i);
3599  continue;
3600  }
3601  indsp->grf_prop.override = ovrid;
3602  _industry_mngr.Add(indid + i, _cur.grffile->grfid, ovrid);
3603  break;
3604  }
3605 
3606  case 0x0A: { // Set industry layout(s)
3607  uint8_t new_num_layouts = buf.ReadByte();
3608  uint32_t definition_size = buf.ReadDWord();
3609  uint32_t bytes_read = 0;
3610  std::vector<IndustryTileLayout> new_layouts;
3611  IndustryTileLayout layout;
3612 
3613  for (uint8_t j = 0; j < new_num_layouts; j++) {
3614  layout.clear();
3615  layout.reserve(new_num_layouts);
3616 
3617  for (uint k = 0;; k++) {
3618  if (bytes_read >= definition_size) {
3619  GrfMsg(3, "IndustriesChangeInfo: Incorrect size for industry tile layout definition for industry {}.", indid);
3620  /* Avoid warning twice */
3621  definition_size = UINT32_MAX;
3622  }
3623 
3624  layout.push_back(IndustryTileLayoutTile{});
3625  IndustryTileLayoutTile &it = layout.back();
3626 
3627  it.ti.x = buf.ReadByte(); // Offsets from northermost tile
3628  ++bytes_read;
3629 
3630  if (it.ti.x == 0xFE && k == 0) {
3631  /* This means we have to borrow the layout from an old industry */
3632  IndustryType type = buf.ReadByte();
3633  uint8_t laynbr = buf.ReadByte();
3634  bytes_read += 2;
3635 
3636  if (type >= lengthof(_origin_industry_specs)) {
3637  GrfMsg(1, "IndustriesChangeInfo: Invalid original industry number for layout import, industry {}", indid);
3638  DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3639  return CIR_DISABLED;
3640  }
3641  if (laynbr >= _origin_industry_specs[type].layouts.size()) {
3642  GrfMsg(1, "IndustriesChangeInfo: Invalid original industry layout index for layout import, industry {}", indid);
3643  DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
3644  return CIR_DISABLED;
3645  }
3646  layout = _origin_industry_specs[type].layouts[laynbr];
3647  break;
3648  }
3649 
3650  it.ti.y = buf.ReadByte(); // Or table definition finalisation
3651  ++bytes_read;
3652 
3653  if (it.ti.x == 0 && it.ti.y == 0x80) {
3654  /* Terminator, remove and finish up */
3655  layout.pop_back();
3656  break;
3657  }
3658 
3659  it.gfx = buf.ReadByte();
3660  ++bytes_read;
3661 
3662  if (it.gfx == 0xFE) {
3663  /* Use a new tile from this GRF */
3664  int local_tile_id = buf.ReadWord();
3665  bytes_read += 2;
3666 
3667  /* Read the ID from the _industile_mngr. */
3668  int tempid = _industile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3669 
3670  if (tempid == INVALID_INDUSTRYTILE) {
3671  GrfMsg(2, "IndustriesChangeInfo: Attempt to use industry tile {} with industry id {}, not yet defined. Ignoring.", local_tile_id, indid);
3672  } else {
3673  /* Declared as been valid, can be used */
3674  it.gfx = tempid;
3675  }
3676  } else if (it.gfx == GFX_WATERTILE_SPECIALCHECK) {
3677  it.ti.x = (int8_t)GB(it.ti.x, 0, 8);
3678  it.ti.y = (int8_t)GB(it.ti.y, 0, 8);
3679 
3680  /* When there were only 256x256 maps, TileIndex was a uint16_t and
3681  * it.ti was just a TileIndexDiff that was added to it.
3682  * As such negative "x" values were shifted into the "y" position.
3683  * x = -1, y = 1 -> x = 255, y = 0
3684  * Since GRF version 8 the position is interpreted as pair of independent int8.
3685  * For GRF version < 8 we need to emulate the old shifting behaviour.
3686  */
3687  if (_cur.grffile->grf_version < 8 && it.ti.x < 0) it.ti.y += 1;
3688  }
3689  }
3690 
3691  if (!ValidateIndustryLayout(layout)) {
3692  /* The industry layout was not valid, so skip this one. */
3693  GrfMsg(1, "IndustriesChangeInfo: Invalid industry layout for industry id {}. Ignoring", indid);
3694  new_num_layouts--;
3695  j--;
3696  } else {
3697  new_layouts.push_back(layout);
3698  }
3699  }
3700 
3701  /* Install final layout construction in the industry spec */
3702  indsp->layouts = new_layouts;
3703  break;
3704  }
3705 
3706  case 0x0B: // Industry production flags
3707  indsp->life_type = (IndustryLifeType)buf.ReadByte();
3708  break;
3709 
3710  case 0x0C: // Industry closure message
3711  AddStringForMapping(buf.ReadWord(), &indsp->closure_text);
3712  break;
3713 
3714  case 0x0D: // Production increase message
3715  AddStringForMapping(buf.ReadWord(), &indsp->production_up_text);
3716  break;
3717 
3718  case 0x0E: // Production decrease message
3719  AddStringForMapping(buf.ReadWord(), &indsp->production_down_text);
3720  break;
3721 
3722  case 0x0F: // Fund cost multiplier
3723  indsp->cost_multiplier = buf.ReadByte();
3724  break;
3725 
3726  case 0x10: // Production cargo types
3727  for (uint8_t j = 0; j < INDUSTRY_ORIGINAL_NUM_OUTPUTS; j++) {
3728  indsp->produced_cargo[j] = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
3729  indsp->produced_cargo_label[j] = CT_INVALID;
3730  }
3731  break;
3732 
3733  case 0x11: // Acceptance cargo types
3734  for (uint8_t j = 0; j < INDUSTRY_ORIGINAL_NUM_INPUTS; j++) {
3735  indsp->accepts_cargo[j] = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
3736  indsp->accepts_cargo_label[j] = CT_INVALID;
3737  }
3738  buf.ReadByte(); // Unnused, eat it up
3739  break;
3740 
3741  case 0x12: // Production multipliers
3742  case 0x13:
3743  indsp->production_rate[prop - 0x12] = buf.ReadByte();
3744  break;
3745 
3746  case 0x14: // Minimal amount of cargo distributed
3747  indsp->minimal_cargo = buf.ReadByte();
3748  break;
3749 
3750  case 0x15: { // Random sound effects
3751  uint8_t num_sounds = buf.ReadByte();
3752 
3753  std::vector<uint8_t> sounds;
3754  sounds.reserve(num_sounds);
3755  for (uint8_t j = 0; j < num_sounds; ++j) {
3756  sounds.push_back(buf.ReadByte());
3757  }
3758 
3759  indsp->random_sounds = std::move(sounds);
3760  break;
3761  }
3762 
3763  case 0x16: // Conflicting industry types
3764  for (uint8_t j = 0; j < 3; j++) indsp->conflicting[j] = buf.ReadByte();
3765  break;
3766 
3767  case 0x17: // Probability in random game
3768  indsp->appear_creation[_settings_game.game_creation.landscape] = buf.ReadByte();
3769  break;
3770 
3771  case 0x18: // Probability during gameplay
3772  indsp->appear_ingame[_settings_game.game_creation.landscape] = buf.ReadByte();
3773  break;
3774 
3775  case 0x19: // Map colour
3776  indsp->map_colour = buf.ReadByte();
3777  break;
3778 
3779  case 0x1A: // Special industry flags to define special behavior
3780  indsp->behaviour = (IndustryBehaviour)buf.ReadDWord();
3781  break;
3782 
3783  case 0x1B: // New industry text ID
3784  AddStringForMapping(buf.ReadWord(), &indsp->new_industry_text);
3785  break;
3786 
3787  case 0x1C: // Input cargo multipliers for the three input cargo types
3788  case 0x1D:
3789  case 0x1E: {
3790  uint32_t multiples = buf.ReadDWord();
3791  indsp->input_cargo_multiplier[prop - 0x1C][0] = GB(multiples, 0, 16);
3792  indsp->input_cargo_multiplier[prop - 0x1C][1] = GB(multiples, 16, 16);
3793  break;
3794  }
3795 
3796  case 0x1F: // Industry name
3797  AddStringForMapping(buf.ReadWord(), &indsp->name);
3798  break;
3799 
3800  case 0x20: // Prospecting success chance
3801  indsp->prospecting_chance = buf.ReadDWord();
3802  break;
3803 
3804  case 0x21: // Callback mask
3805  case 0x22: { // Callback additional mask
3806  uint8_t aflag = buf.ReadByte();
3807  SB(indsp->callback_mask, (prop - 0x21) * 8, 8, aflag);
3808  break;
3809  }
3810 
3811  case 0x23: // removal cost multiplier
3812  indsp->removal_cost_multiplier = buf.ReadDWord();
3813  break;
3814 
3815  case 0x24: { // name for nearby station
3816  uint16_t str = buf.ReadWord();
3817  if (str == 0) {
3818  indsp->station_name = STR_NULL;
3819  } else {
3820  AddStringForMapping(str, &indsp->station_name);
3821  }
3822  break;
3823  }
3824 
3825  case 0x25: { // variable length produced cargoes
3826  uint8_t num_cargoes = buf.ReadByte();
3827  if (num_cargoes > std::size(indsp->produced_cargo)) {
3828  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3829  error->param_value[1] = prop;
3830  return CIR_DISABLED;
3831  }
3832  for (size_t i = 0; i < std::size(indsp->produced_cargo); i++) {
3833  if (i < num_cargoes) {
3834  CargoID cargo = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
3835  indsp->produced_cargo[i] = cargo;
3836  } else {
3837  indsp->produced_cargo[i] = INVALID_CARGO;
3838  }
3839  indsp->produced_cargo_label[i] = CT_INVALID;
3840  }
3841  break;
3842  }
3843 
3844  case 0x26: { // variable length accepted cargoes
3845  uint8_t num_cargoes = buf.ReadByte();
3846  if (num_cargoes > std::size(indsp->accepts_cargo)) {
3847  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3848  error->param_value[1] = prop;
3849  return CIR_DISABLED;
3850  }
3851  for (size_t i = 0; i < std::size(indsp->accepts_cargo); i++) {
3852  if (i < num_cargoes) {
3853  CargoID cargo = GetCargoTranslation(buf.ReadByte(), _cur.grffile);
3854  indsp->accepts_cargo[i] = cargo;
3855  } else {
3856  indsp->accepts_cargo[i] = INVALID_CARGO;
3857  }
3858  indsp->accepts_cargo_label[i] = CT_INVALID;
3859  }
3860  break;
3861  }
3862 
3863  case 0x27: { // variable length production rates
3864  uint8_t num_cargoes = buf.ReadByte();
3865  if (num_cargoes > lengthof(indsp->production_rate)) {
3866  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3867  error->param_value[1] = prop;
3868  return CIR_DISABLED;
3869  }
3870  for (uint i = 0; i < lengthof(indsp->production_rate); i++) {
3871  if (i < num_cargoes) {
3872  indsp->production_rate[i] = buf.ReadByte();
3873  } else {
3874  indsp->production_rate[i] = 0;
3875  }
3876  }
3877  break;
3878  }
3879 
3880  case 0x28: { // variable size input/output production multiplier table
3881  uint8_t num_inputs = buf.ReadByte();
3882  uint8_t num_outputs = buf.ReadByte();
3883  if (num_inputs > std::size(indsp->accepts_cargo) || num_outputs > std::size(indsp->produced_cargo)) {
3884  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LIST_PROPERTY_TOO_LONG);
3885  error->param_value[1] = prop;
3886  return CIR_DISABLED;
3887  }
3888  for (size_t i = 0; i < std::size(indsp->accepts_cargo); i++) {
3889  for (size_t j = 0; j < std::size(indsp->produced_cargo); j++) {
3890  uint16_t mult = 0;
3891  if (i < num_inputs && j < num_outputs) mult = buf.ReadWord();
3892  indsp->input_cargo_multiplier[i][j] = mult;
3893  }
3894  }
3895  break;
3896  }
3897 
3898  default:
3899  ret = CIR_UNKNOWN;
3900  break;
3901  }
3902  }
3903 
3904  return ret;
3905 }
3906 
3915 static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader &buf)
3916 {
3918 
3919  if (airport + numinfo > NUM_AIRPORTS_PER_GRF) {
3920  GrfMsg(1, "AirportChangeInfo: Too many airports, trying id ({}), max ({}). Ignoring.", airport + numinfo, NUM_AIRPORTS_PER_GRF);
3921  return CIR_INVALID_ID;
3922  }
3923 
3924  /* Allocate industry specs if they haven't been allocated already. */
3925  if (_cur.grffile->airportspec.size() < airport + numinfo) _cur.grffile->airportspec.resize(airport + numinfo);
3926 
3927  for (int i = 0; i < numinfo; i++) {
3928  auto &as = _cur.grffile->airportspec[airport + i];
3929 
3930  if (as == nullptr && prop != 0x08 && prop != 0x09) {
3931  GrfMsg(2, "AirportChangeInfo: Attempt to modify undefined airport {}, ignoring", airport + i);
3932  return CIR_INVALID_ID;
3933  }
3934 
3935  switch (prop) {
3936  case 0x08: { // Modify original airport
3937  uint8_t subs_id = buf.ReadByte();
3938  if (subs_id == 0xFF) {
3939  /* Instead of defining a new airport, an airport id
3940  * of 0xFF disables the old airport with the current id. */
3941  AirportSpec::GetWithoutOverride(airport + i)->enabled = false;
3942  continue;
3943  } else if (subs_id >= NEW_AIRPORT_OFFSET) {
3944  /* The substitute id must be one of the original airports. */
3945  GrfMsg(2, "AirportChangeInfo: Attempt to use new airport {} as substitute airport for {}. Ignoring.", subs_id, airport + i);
3946  continue;
3947  }
3948 
3949  /* Allocate space for this airport.
3950  * Only need to do it once. If ever it is called again, it should not
3951  * do anything */
3952  if (as == nullptr) {
3953  as = std::make_unique<AirportSpec>(*AirportSpec::GetWithoutOverride(subs_id));
3954 
3955  as->enabled = true;
3956  as->grf_prop.local_id = airport + i;
3957  as->grf_prop.subst_id = subs_id;
3958  as->grf_prop.grffile = _cur.grffile;
3959  /* override the default airport */
3960  _airport_mngr.Add(airport + i, _cur.grffile->grfid, subs_id);
3961  }
3962  break;
3963  }
3964 
3965  case 0x0A: { // Set airport layout
3966  uint8_t num_layouts = buf.ReadByte();
3967  buf.ReadDWord(); // Total size of definition, unneeded.
3968  uint8_t size_x = 0;
3969  uint8_t size_y = 0;
3970 
3971  std::vector<AirportTileLayout> layouts;
3972  layouts.reserve(num_layouts);
3973 
3974  for (uint8_t j = 0; j != num_layouts; ++j) {
3975  auto &layout = layouts.emplace_back();
3976  layout.rotation = static_cast<Direction>(buf.ReadByte() & 6); // Rotation can only be DIR_NORTH, DIR_EAST, DIR_SOUTH or DIR_WEST.
3977 
3978  for (;;) {
3979  auto &tile = layout.tiles.emplace_back();
3980  tile.ti.x = buf.ReadByte();
3981  tile.ti.y = buf.ReadByte();
3982  if (tile.ti.x == 0 && tile.ti.y == 0x80) {
3983  /* Convert terminator to our own. */
3984  tile.ti.x = -0x80;
3985  tile.ti.y = 0;
3986  tile.gfx = 0;
3987  break;
3988  }
3989 
3990  tile.gfx = buf.ReadByte();
3991 
3992  if (tile.gfx == 0xFE) {
3993  /* Use a new tile from this GRF */
3994  int local_tile_id = buf.ReadWord();
3995 
3996  /* Read the ID from the _airporttile_mngr. */
3997  uint16_t tempid = _airporttile_mngr.GetID(local_tile_id, _cur.grffile->grfid);
3998 
3999  if (tempid == INVALID_AIRPORTTILE) {
4000  GrfMsg(2, "AirportChangeInfo: Attempt to use airport tile {} with airport id {}, not yet defined. Ignoring.", local_tile_id, airport + i);
4001  } else {
4002  /* Declared as been valid, can be used */
4003  tile.gfx = tempid;
4004  }
4005  } else if (tile.gfx == 0xFF) {
4006  tile.ti.x = static_cast<int8_t>(GB(tile.ti.x, 0, 8));
4007  tile.ti.y = static_cast<int8_t>(GB(tile.ti.y, 0, 8));
4008  }
4009 
4010  /* Determine largest size. */
4011  if (layout.rotation == DIR_E || layout.rotation == DIR_W) {
4012  size_x = std::max<uint8_t>(size_x, tile.ti.y + 1);
4013  size_y = std::max<uint8_t>(size_y, tile.ti.x + 1);
4014  } else {
4015  size_x = std::max<uint8_t>(size_x, tile.ti.x + 1);
4016  size_y = std::max<uint8_t>(size_y, tile.ti.y + 1);
4017  }
4018  }
4019  }
4020  as->layouts = std::move(layouts);
4021  as->size_x = size_x;
4022  as->size_y = size_y;
4023  break;
4024  }
4025 
4026  case 0x0C:
4027  as->min_year = buf.ReadWord();
4028  as->max_year = buf.ReadWord();
4029  if (as->max_year == 0xFFFF) as->max_year = CalendarTime::MAX_YEAR;
4030  break;
4031 
4032  case 0x0D:
4033  as->ttd_airport_type = (TTDPAirportType)buf.ReadByte();
4034  break;
4035 
4036  case 0x0E:
4037  as->catchment = Clamp(buf.ReadByte(), 1, MAX_CATCHMENT);
4038  break;
4039 
4040  case 0x0F:
4041  as->noise_level = buf.ReadByte();
4042  break;
4043 
4044  case 0x10:
4045  AddStringForMapping(buf.ReadWord(), &as->name);
4046  break;
4047 
4048  case 0x11: // Maintenance cost factor
4049  as->maintenance_cost = buf.ReadWord();
4050  break;
4051 
4052  default:
4053  ret = CIR_UNKNOWN;
4054  break;
4055  }
4056  }
4057 
4058  return ret;
4059 }
4060 
4068 {
4070 
4071  switch (prop) {
4072  case 0x0B:
4073  case 0x0C:
4074  case 0x0D:
4075  case 0x12:
4076  case 0x14:
4077  case 0x16:
4078  case 0x17:
4079  case 0x18:
4080  buf.ReadByte();
4081  break;
4082 
4083  case 0x09:
4084  case 0x0A:
4085  case 0x10:
4086  case 0x11:
4087  case 0x13:
4088  case 0x15:
4089  buf.ReadWord();
4090  break;
4091 
4092  case 0x08:
4093  case 0x0E:
4094  case 0x0F:
4095  buf.ReadDWord();
4096  break;
4097 
4098  default:
4099  ret = CIR_UNKNOWN;
4100  break;
4101  }
4102 
4103  return ret;
4104 }
4105 
4114 static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteReader &buf)
4115 {
4117 
4118  if (id + numinfo > NUM_OBJECTS_PER_GRF) {
4119  GrfMsg(1, "ObjectChangeInfo: Too many objects loaded ({}), max ({}). Ignoring.", id + numinfo, NUM_OBJECTS_PER_GRF);
4120  return CIR_INVALID_ID;
4121  }
4122 
4123  /* Allocate object specs if they haven't been allocated already. */
4124  if (_cur.grffile->objectspec.size() < id + numinfo) _cur.grffile->objectspec.resize(id + numinfo);
4125 
4126  for (int i = 0; i < numinfo; i++) {
4127  auto &spec = _cur.grffile->objectspec[id + i];
4128 
4129  if (prop != 0x08 && spec == nullptr) {
4130  /* If the object property 08 is not yet set, ignore this property */
4131  ChangeInfoResult cir = IgnoreObjectProperty(prop, buf);
4132  if (cir > ret) ret = cir;
4133  continue;
4134  }
4135 
4136  switch (prop) {
4137  case 0x08: { // Class ID
4138  /* Allocate space for this object. */
4139  if (spec == nullptr) {
4140  spec = std::make_unique<ObjectSpec>();
4141  spec->views = 1; // Default for NewGRFs that don't set it.
4142  spec->size = OBJECT_SIZE_1X1; // Default for NewGRFs that manage to not set it (1x1)
4143  }
4144 
4145  /* Swap classid because we read it in BE. */
4146  uint32_t classid = buf.ReadDWord();
4147  spec->class_index = ObjectClass::Allocate(BSWAP32(classid));
4148  break;
4149  }
4150 
4151  case 0x09: { // Class name
4152  AddStringForMapping(buf.ReadWord(), [spec = spec.get()](StringID str) { ObjectClass::Get(spec->class_index)->name = str; });
4153  break;
4154  }
4155 
4156  case 0x0A: // Object name
4157  AddStringForMapping(buf.ReadWord(), &spec->name);
4158  break;
4159 
4160  case 0x0B: // Climate mask
4161  spec->climate = buf.ReadByte();
4162  break;
4163 
4164  case 0x0C: // Size
4165  spec->size = buf.ReadByte();
4166  if (GB(spec->size, 0, 4) == 0 || GB(spec->size, 4, 4) == 0) {
4167  GrfMsg(0, "ObjectChangeInfo: Invalid object size requested (0x{:X}) for object id {}. Ignoring.", spec->size, id + i);
4168  spec->size = OBJECT_SIZE_1X1;
4169  }
4170  break;
4171 
4172  case 0x0D: // Build cost multipler
4173  spec->build_cost_multiplier = buf.ReadByte();
4174  spec->clear_cost_multiplier = spec->build_cost_multiplier;
4175  break;
4176 
4177  case 0x0E: // Introduction date
4178  spec->introduction_date = buf.ReadDWord();
4179  break;
4180 
4181  case 0x0F: // End of life
4182  spec->end_of_life_date = buf.ReadDWord();
4183  break;
4184 
4185  case 0x10: // Flags
4186  spec->flags = (ObjectFlags)buf.ReadWord();
4187  _loaded_newgrf_features.has_2CC |= (spec->flags & OBJECT_FLAG_2CC_COLOUR) != 0;
4188  break;
4189 
4190  case 0x11: // Animation info
4191  spec->animation.frames = buf.ReadByte();
4192  spec->animation.status = buf.ReadByte();
4193  break;
4194 
4195  case 0x12: // Animation speed
4196  spec->animation.speed = buf.ReadByte();
4197  break;
4198 
4199  case 0x13: // Animation triggers
4200  spec->animation.triggers = buf.ReadWord();
4201  break;
4202 
4203  case 0x14: // Removal cost multiplier
4204  spec->clear_cost_multiplier = buf.ReadByte();
4205  break;
4206 
4207  case 0x15: // Callback mask
4208  spec->callback_mask = buf.ReadWord();
4209  break;
4210 
4211  case 0x16: // Building height
4212  spec->height = buf.ReadByte();
4213  break;
4214 
4215  case 0x17: // Views
4216  spec->views = buf.ReadByte();
4217  if (spec->views != 1 && spec->views != 2 && spec->views != 4) {
4218  GrfMsg(2, "ObjectChangeInfo: Invalid number of views ({}) for object id {}. Ignoring.", spec->views, id + i);
4219  spec->views = 1;
4220  }
4221  break;
4222 
4223  case 0x18: // Amount placed on 256^2 map on map creation
4224  spec->generate_amount = buf.ReadByte();
4225  break;
4226 
4227  default:
4228  ret = CIR_UNKNOWN;
4229  break;
4230  }
4231  }
4232 
4233  return ret;
4234 }
4235 
4244 static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, ByteReader &buf)
4245 {
4247 
4248  extern RailTypeInfo _railtypes[RAILTYPE_END];
4249 
4250  if (id + numinfo > RAILTYPE_END) {
4251  GrfMsg(1, "RailTypeChangeInfo: Rail type {} is invalid, max {}, ignoring", id + numinfo, RAILTYPE_END);
4252  return CIR_INVALID_ID;
4253  }
4254 
4255  for (int i = 0; i < numinfo; i++) {
4256  RailType rt = _cur.grffile->railtype_map[id + i];
4257  if (rt == INVALID_RAILTYPE) return CIR_INVALID_ID;
4258 
4259  RailTypeInfo *rti = &_railtypes[rt];
4260 
4261  switch (prop) {
4262  case 0x08: // Label of rail type
4263  /* Skipped here as this is loaded during reservation stage. */
4264  buf.ReadDWord();
4265  break;
4266 
4267  case 0x09: { // Toolbar caption of railtype (sets name as well for backwards compatibility for grf ver < 8)
4268  uint16_t str = buf.ReadWord();
4270  if (_cur.grffile->grf_version < 8) {
4271  AddStringForMapping(str, &rti->strings.name);
4272  }
4273  break;
4274  }
4275 
4276  case 0x0A: // Menu text of railtype
4277  AddStringForMapping(buf.ReadWord(), &rti->strings.menu_text);
4278  break;
4279 
4280  case 0x0B: // Build window caption
4281  AddStringForMapping(buf.ReadWord(), &rti->strings.build_caption);
4282  break;
4283 
4284  case 0x0C: // Autoreplace text
4285  AddStringForMapping(buf.ReadWord(), &rti->strings.replace_text);
4286  break;
4287 
4288  case 0x0D: // New locomotive text
4289  AddStringForMapping(buf.ReadWord(), &rti->strings.new_loco);
4290  break;
4291 
4292  case 0x0E: // Compatible railtype list
4293  case 0x0F: // Powered railtype list
4294  case 0x18: // Railtype list required for date introduction
4295  case 0x19: // Introduced railtype list
4296  {
4297  /* Rail type compatibility bits are added to the existing bits
4298  * to allow multiple GRFs to modify compatibility with the
4299  * default rail types. */
4300  int n = buf.ReadByte();
4301  for (int j = 0; j != n; j++) {
4302  RailTypeLabel label = buf.ReadDWord();
4303  RailType resolved_rt = GetRailTypeByLabel(BSWAP32(label), false);
4304  if (resolved_rt != INVALID_RAILTYPE) {
4305  switch (prop) {
4306  case 0x0F: SetBit(rti->powered_railtypes, resolved_rt); [[fallthrough]]; // Powered implies compatible.
4307  case 0x0E: SetBit(rti->compatible_railtypes, resolved_rt); break;
4308  case 0x18: SetBit(rti->introduction_required_railtypes, resolved_rt); break;
4309  case 0x19: SetBit(rti->introduces_railtypes, resolved_rt); break;
4310  }
4311  }
4312  }
4313  break;
4314  }
4315 
4316  case 0x10: // Rail Type flags
4317  rti->flags = (RailTypeFlags)buf.ReadByte();
4318  break;
4319 
4320  case 0x11: // Curve speed advantage
4321  rti->curve_speed = buf.ReadByte();
4322  break;
4323 
4324  case 0x12: // Station graphic
4325  rti->fallback_railtype = Clamp(buf.ReadByte(), 0, 2);
4326  break;
4327 
4328  case 0x13: // Construction cost factor
4329  rti->cost_multiplier = buf.ReadWord();
4330  break;
4331 
4332  case 0x14: // Speed limit
4333  rti->max_speed = buf.ReadWord();
4334  break;
4335 
4336  case 0x15: // Acceleration model
4337  rti->acceleration_type = Clamp(buf.ReadByte(), 0, 2);
4338  break;
4339 
4340  case 0x16: // Map colour
4341  rti->map_colour = buf.ReadByte();
4342  break;
4343 
4344  case 0x17: // Introduction date
4345  rti->introduction_date = buf.ReadDWord();
4346  break;
4347 
4348  case 0x1A: // Sort order
4349  rti->sorting_order = buf.ReadByte();
4350  break;
4351 
4352  case 0x1B: // Name of railtype (overridden by prop 09 for grf ver < 8)
4353  AddStringForMapping(buf.ReadWord(), &rti->strings.name);
4354  break;
4355 
4356  case 0x1C: // Maintenance cost factor
4357  rti->maintenance_multiplier = buf.ReadWord();
4358  break;
4359 
4360  case 0x1D: // Alternate rail type label list
4361  /* Skipped here as this is loaded during reservation stage. */
4362  for (int j = buf.ReadByte(); j != 0; j--) buf.ReadDWord();
4363  break;
4364 
4365  default:
4366  ret = CIR_UNKNOWN;
4367  break;
4368  }
4369  }
4370 
4371  return ret;
4372 }
4373 
4374 static ChangeInfoResult RailTypeReserveInfo(uint id, int numinfo, int prop, ByteReader &buf)
4375 {
4377 
4378  extern RailTypeInfo _railtypes[RAILTYPE_END];
4379 
4380  if (id + numinfo > RAILTYPE_END) {
4381  GrfMsg(1, "RailTypeReserveInfo: Rail type {} is invalid, max {}, ignoring", id + numinfo, RAILTYPE_END);
4382  return CIR_INVALID_ID;
4383  }
4384 
4385  for (int i = 0; i < numinfo; i++) {
4386  switch (prop) {
4387  case 0x08: // Label of rail type
4388  {
4389  RailTypeLabel rtl = buf.ReadDWord();
4390  rtl = BSWAP32(rtl);
4391 
4392  RailType rt = GetRailTypeByLabel(rtl, false);
4393  if (rt == INVALID_RAILTYPE) {
4394  /* Set up new rail type */
4395  rt = AllocateRailType(rtl);
4396  }
4397 
4398  _cur.grffile->railtype_map[id + i] = rt;
4399  break;
4400  }
4401 
4402  case 0x09: // Toolbar caption of railtype
4403  case 0x0A: // Menu text
4404  case 0x0B: // Build window caption
4405  case 0x0C: // Autoreplace text
4406  case 0x0D: // New loco
4407  case 0x13: // Construction cost
4408  case 0x14: // Speed limit
4409  case 0x1B: // Name of railtype
4410  case 0x1C: // Maintenance cost factor
4411  buf.ReadWord();
4412  break;
4413 
4414  case 0x1D: // Alternate rail type label list
4415  if (_cur.grffile->railtype_map[id + i] != INVALID_RAILTYPE) {
4416  int n = buf.ReadByte();
4417  for (int j = 0; j != n; j++) {
4418  _railtypes[_cur.grffile->railtype_map[id + i]].alternate_labels.push_back(BSWAP32(buf.ReadDWord()));
4419  }
4420  break;
4421  }
4422  GrfMsg(1, "RailTypeReserveInfo: Ignoring property 1D for rail type {} because no label was set", id + i);
4423  [[fallthrough]];
4424 
4425  case 0x0E: // Compatible railtype list
4426  case 0x0F: // Powered railtype list
4427  case 0x18: // Railtype list required for date introduction
4428  case 0x19: // Introduced railtype list
4429  for (int j = buf.ReadByte(); j != 0; j--) buf.ReadDWord();
4430  break;
4431 
4432  case 0x10: // Rail Type flags
4433  case 0x11: // Curve speed advantage
4434  case 0x12: // Station graphic
4435  case 0x15: // Acceleration model
4436  case 0x16: // Map colour
4437  case 0x1A: // Sort order
4438  buf.ReadByte();
4439  break;
4440 
4441  case 0x17: // Introduction date
4442  buf.ReadDWord();
4443  break;
4444 
4445  default:
4446  ret = CIR_UNKNOWN;
4447  break;
4448  }
4449  }
4450 
4451  return ret;
4452 }
4453 
4462 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader &buf, RoadTramType rtt)
4463 {
4465 
4466  extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4467  RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4468 
4469  if (id + numinfo > ROADTYPE_END) {
4470  GrfMsg(1, "RoadTypeChangeInfo: Road type {} is invalid, max {}, ignoring", id + numinfo, ROADTYPE_END);
4471  return CIR_INVALID_ID;
4472  }
4473 
4474  for (int i = 0; i < numinfo; i++) {
4475  RoadType rt = type_map[id + i];
4476  if (rt == INVALID_ROADTYPE) return CIR_INVALID_ID;
4477 
4478  RoadTypeInfo *rti = &_roadtypes[rt];
4479 
4480  switch (prop) {
4481  case 0x08: // Label of road type
4482  /* Skipped here as this is loaded during reservation stage. */
4483  buf.ReadDWord();
4484  break;
4485 
4486  case 0x09: { // Toolbar caption of roadtype (sets name as well for backwards compatibility for grf ver < 8)
4487  uint16_t str = buf.ReadWord();
4489  break;
4490  }
4491 
4492  case 0x0A: // Menu text of roadtype
4493  AddStringForMapping(buf.ReadWord(), &rti->strings.menu_text);
4494  break;
4495 
4496  case 0x0B: // Build window caption
4497  AddStringForMapping(buf.ReadWord(), &rti->strings.build_caption);
4498  break;
4499 
4500  case 0x0C: // Autoreplace text
4501  AddStringForMapping(buf.ReadWord(), &rti->strings.replace_text);
4502  break;
4503 
4504  case 0x0D: // New engine text
4505  AddStringForMapping(buf.ReadWord(), &rti->strings.new_engine);
4506  break;
4507 
4508  case 0x0F: // Powered roadtype list
4509  case 0x18: // Roadtype list required for date introduction
4510  case 0x19: { // Introduced roadtype list
4511  /* Road type compatibility bits are added to the existing bits
4512  * to allow multiple GRFs to modify compatibility with the
4513  * default road types. */
4514  int n = buf.ReadByte();
4515  for (int j = 0; j != n; j++) {
4516  RoadTypeLabel label = buf.ReadDWord();
4517  RoadType resolved_rt = GetRoadTypeByLabel(BSWAP32(label), false);
4518  if (resolved_rt != INVALID_ROADTYPE) {
4519  switch (prop) {
4520  case 0x0F:
4521  if (GetRoadTramType(resolved_rt) == rtt) {
4522  SetBit(rti->powered_roadtypes, resolved_rt);
4523  } else {
4524  GrfMsg(1, "RoadTypeChangeInfo: Powered road type list: Road type {} road/tram type does not match road type {}, ignoring", resolved_rt, rt);
4525  }
4526  break;
4527  case 0x18: SetBit(rti->introduction_required_roadtypes, resolved_rt); break;
4528  case 0x19: SetBit(rti->introduces_roadtypes, resolved_rt); break;
4529  }
4530  }
4531  }
4532  break;
4533  }
4534 
4535  case 0x10: // Road Type flags
4536  rti->flags = (RoadTypeFlags)buf.ReadByte();
4537  break;
4538 
4539  case 0x13: // Construction cost factor
4540  rti->cost_multiplier = buf.ReadWord();
4541  break;
4542 
4543  case 0x14: // Speed limit
4544  rti->max_speed = buf.ReadWord();
4545  break;
4546 
4547  case 0x16: // Map colour
4548  rti->map_colour = buf.ReadByte();
4549  break;
4550 
4551  case 0x17: // Introduction date
4552  rti->introduction_date = buf.ReadDWord();
4553  break;
4554 
4555  case 0x1A: // Sort order
4556  rti->sorting_order = buf.ReadByte();
4557  break;
4558 
4559  case 0x1B: // Name of roadtype
4560  AddStringForMapping(buf.ReadWord(), &rti->strings.name);
4561  break;
4562 
4563  case 0x1C: // Maintenance cost factor
4564  rti->maintenance_multiplier = buf.ReadWord();
4565  break;
4566 
4567  case 0x1D: // Alternate road type label list
4568  /* Skipped here as this is loaded during reservation stage. */
4569  for (int j = buf.ReadByte(); j != 0; j--) buf.ReadDWord();
4570  break;
4571 
4572  default:
4573  ret = CIR_UNKNOWN;
4574  break;
4575  }
4576  }
4577 
4578  return ret;
4579 }
4580 
4581 static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader &buf)
4582 {
4583  return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_ROAD);
4584 }
4585 
4586 static ChangeInfoResult TramTypeChangeInfo(uint id, int numinfo, int prop, ByteReader &buf)
4587 {
4588  return RoadTypeChangeInfo(id, numinfo, prop, buf, RTT_TRAM);
4589 }
4590 
4591 
4592 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader &buf, RoadTramType rtt)
4593 {
4595 
4596  extern RoadTypeInfo _roadtypes[ROADTYPE_END];
4597  RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
4598 
4599  if (id + numinfo > ROADTYPE_END) {
4600  GrfMsg(1, "RoadTypeReserveInfo: Road type {} is invalid, max {}, ignoring", id + numinfo, ROADTYPE_END);
4601  return CIR_INVALID_ID;
4602  }
4603 
4604  for (int i = 0; i < numinfo; i++) {
4605  switch (prop) {
4606  case 0x08: { // Label of road type
4607  RoadTypeLabel rtl = buf.ReadDWord();
4608  rtl = BSWAP32(rtl);
4609 
4610  RoadType rt = GetRoadTypeByLabel(rtl, false);
4611  if (rt == INVALID_ROADTYPE) {
4612  /* Set up new road type */
4613  rt = AllocateRoadType(rtl, rtt);
4614  } else if (GetRoadTramType(rt) != rtt) {
4615  GrfMsg(1, "RoadTypeReserveInfo: Road type {} is invalid type (road/tram), ignoring", id + numinfo);
4616  return CIR_INVALID_ID;
4617  }
4618 
4619  type_map[id + i] = rt;
4620  break;
4621  }
4622  case 0x09: // Toolbar caption of roadtype
4623  case 0x0A: // Menu text
4624  case 0x0B: // Build window caption
4625  case 0x0C: // Autoreplace text
4626  case 0x0D: // New loco
4627  case 0x13: // Construction cost
4628  case 0x14: // Speed limit
4629  case 0x1B: // Name of roadtype
4630  case 0x1C: // Maintenance cost factor
4631  buf.ReadWord();
4632  break;
4633 
4634  case 0x1D: // Alternate road type label list
4635  if (type_map[id + i] != INVALID_ROADTYPE) {
4636  int n = buf.ReadByte();
4637  for (int j = 0; j != n; j++) {
4638  _roadtypes[type_map[id + i]].alternate_labels.push_back(BSWAP32(buf.ReadDWord()));
4639  }
4640  break;
4641  }
4642  GrfMsg(1, "RoadTypeReserveInfo: Ignoring property 1D for road type {} because no label was set", id + i);
4643  /* FALL THROUGH */
4644 
4645  case 0x0F: // Powered roadtype list
4646  case 0x18: // Roadtype list required for date introduction
4647  case 0x19: // Introduced roadtype list
4648  for (int j = buf.ReadByte(); j != 0; j--) buf.ReadDWord();
4649  break;
4650 
4651  case 0x10: // Road Type flags
4652  case 0x16: // Map colour
4653  case 0x1A: // Sort order
4654  buf.ReadByte();
4655  break;
4656 
4657  case 0x17: // Introduction date
4658  buf.ReadDWord();
4659  break;
4660 
4661  default:
4662  ret = CIR_UNKNOWN;
4663  break;
4664  }
4665  }
4666 
4667  return ret;
4668 }
4669 
4670 static ChangeInfoResult RoadTypeReserveInfo(uint id, int numinfo, int prop, ByteReader &buf)
4671 {
4672  return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_ROAD);
4673 }
4674 
4675 static ChangeInfoResult TramTypeReserveInfo(uint id, int numinfo, int prop, ByteReader &buf)
4676 {
4677  return RoadTypeReserveInfo(id, numinfo, prop, buf, RTT_TRAM);
4678 }
4679 
4680 static ChangeInfoResult AirportTilesChangeInfo(uint airtid, int numinfo, int prop, ByteReader &buf)
4681 {
4683 
4684  if (airtid + numinfo > NUM_AIRPORTTILES_PER_GRF) {
4685  GrfMsg(1, "AirportTileChangeInfo: Too many airport tiles loaded ({}), max ({}). Ignoring.", airtid + numinfo, NUM_AIRPORTTILES_PER_GRF);
4686  return CIR_INVALID_ID;
4687  }
4688 
4689  /* Allocate airport tile specs if they haven't been allocated already. */
4690  if (_cur.grffile->airtspec.size() < airtid + numinfo) _cur.grffile->airtspec.resize(airtid + numinfo);
4691 
4692  for (int i = 0; i < numinfo; i++) {
4693  auto &tsp = _cur.grffile->airtspec[airtid + i];
4694 
4695  if (prop != 0x08 && tsp == nullptr) {
4696  GrfMsg(2, "AirportTileChangeInfo: Attempt to modify undefined airport tile {}. Ignoring.", airtid + i);
4697  return CIR_INVALID_ID;
4698  }
4699 
4700  switch (prop) {
4701  case 0x08: { // Substitute airport tile type
4702  uint8_t subs_id = buf.ReadByte();
4703  if (subs_id >= NEW_AIRPORTTILE_OFFSET) {
4704  /* The substitute id must be one of the original airport tiles. */
4705  GrfMsg(2, "AirportTileChangeInfo: Attempt to use new airport tile {} as substitute airport tile for {}. Ignoring.", subs_id, airtid + i);
4706  continue;
4707  }
4708 
4709  /* Allocate space for this airport tile. */
4710  if (tsp == nullptr) {
4711  tsp = std::make_unique<AirportTileSpec>(*AirportTileSpec::Get(subs_id));
4712 
4713  tsp->enabled = true;
4714 
4715  tsp->animation.status = ANIM_STATUS_NO_ANIMATION;
4716 
4717  tsp->grf_prop.local_id = airtid + i;
4718  tsp->grf_prop.subst_id = subs_id;
4719  tsp->grf_prop.grffile = _cur.grffile;
4720  _airporttile_mngr.AddEntityID(airtid + i, _cur.grffile->grfid, subs_id); // pre-reserve the tile slot
4721  }
4722  break;
4723  }
4724 
4725  case 0x09: { // Airport tile override
4726  uint8_t override = buf.ReadByte();
4727 
4728  /* The airport tile being overridden must be an original airport tile. */
4729  if (override >= NEW_AIRPORTTILE_OFFSET) {
4730  GrfMsg(2, "AirportTileChangeInfo: Attempt to override new airport tile {} with airport tile id {}. Ignoring.", override, airtid + i);
4731  continue;
4732  }
4733 
4734  _airporttile_mngr.Add(airtid + i, _cur.grffile->grfid, override);
4735  break;
4736  }
4737 
4738  case 0x0E: // Callback mask
4739  tsp->callback_mask = buf.ReadByte();
4740  break;
4741 
4742  case 0x0F: // Animation information
4743  tsp->animation.frames = buf.ReadByte();
4744  tsp->animation.status = buf.ReadByte();
4745  break;
4746 
4747  case 0x10: // Animation speed
4748  tsp->animation.speed = buf.ReadByte();
4749  break;
4750 
4751  case 0x11: // Animation triggers
4752  tsp->animation.triggers = buf.ReadByte();
4753  break;
4754 
4755  default:
4756  ret = CIR_UNKNOWN;
4757  break;
4758  }
4759  }
4760 
4761  return ret;
4762 }
4763 
4771 {
4773 
4774  switch (prop) {
4775  case 0x09:
4776  case 0x0C:
4777  case 0x0F:
4778  case 0x11:
4779  buf.ReadByte();
4780  break;
4781 
4782  case 0x0A:
4783  case 0x0B:
4784  case 0x0E:
4785  case 0x10:
4786  case 0x15:
4787  buf.ReadWord();
4788  break;
4789 
4790  case 0x08:
4791  case 0x0D:
4792  case 0x12:
4793  buf.ReadDWord();
4794  break;
4795 
4796  default:
4797  ret = CIR_UNKNOWN;
4798  break;
4799  }
4800 
4801  return ret;
4802 }
4803 
4804 static ChangeInfoResult RoadStopChangeInfo(uint id, int numinfo, int prop, ByteReader &buf)
4805 {
4807 
4808  if (id + numinfo > NUM_ROADSTOPS_PER_GRF) {
4809  GrfMsg(1, "RoadStopChangeInfo: RoadStop {} is invalid, max {}, ignoring", id + numinfo, NUM_ROADSTOPS_PER_GRF);
4810  return CIR_INVALID_ID;
4811  }
4812 
4813  if (_cur.grffile->roadstops.size() < id + numinfo) _cur.grffile->roadstops.resize(id + numinfo);
4814 
4815  for (int i = 0; i < numinfo; i++) {
4816  auto &rs = _cur.grffile->roadstops[id + i];
4817 
4818  if (rs == nullptr && prop != 0x08) {
4819  GrfMsg(1, "RoadStopChangeInfo: Attempt to modify undefined road stop {}, ignoring", id + i);
4820  ChangeInfoResult cir = IgnoreRoadStopProperty(prop, buf);
4821  if (cir > ret) ret = cir;
4822  continue;
4823  }
4824 
4825  switch (prop) {
4826  case 0x08: { // Road Stop Class ID
4827  if (rs == nullptr) {
4828  rs = std::make_unique<RoadStopSpec>();
4829  }
4830 
4831  uint32_t classid = buf.ReadDWord();
4832  rs->class_index = RoadStopClass::Allocate(BSWAP32(classid));
4833  break;
4834  }
4835 
4836  case 0x09: // Road stop type
4837  rs->stop_type = (RoadStopAvailabilityType)buf.ReadByte();
4838  break;
4839 
4840  case 0x0A: // Road Stop Name
4841  AddStringForMapping(buf.ReadWord(), &rs->name);
4842  break;
4843 
4844  case 0x0B: // Road Stop Class name
4845  AddStringForMapping(buf.ReadWord(), [rs = rs.get()](StringID str) { RoadStopClass::Get(rs->class_index)->name = str; });
4846  break;
4847 
4848  case 0x0C: // The draw mode
4849  rs->draw_mode = static_cast<RoadStopDrawMode>(buf.ReadByte());
4850  break;
4851 
4852  case 0x0D: // Cargo types for random triggers
4853  rs->cargo_triggers = TranslateRefitMask(buf.ReadDWord());
4854  break;
4855 
4856  case 0x0E: // Animation info
4857  rs->animation.frames = buf.ReadByte();
4858  rs->animation.status = buf.ReadByte();
4859  break;
4860 
4861  case 0x0F: // Animation speed
4862  rs->animation.speed = buf.ReadByte();
4863  break;
4864 
4865  case 0x10: // Animation triggers
4866  rs->animation.triggers = buf.ReadWord();
4867  break;
4868 
4869  case 0x11: // Callback mask
4870  rs->callback_mask = buf.ReadByte();
4871  break;
4872 
4873  case 0x12: // General flags
4874  rs->flags = (uint16_t)buf.ReadDWord(); // Future-proofing, size this as 4 bytes, but we only need two byte's worth of flags at present
4875  break;
4876 
4877  case 0x15: // Cost multipliers
4878  rs->build_cost_multiplier = buf.ReadByte();
4879  rs->clear_cost_multiplier = buf.ReadByte();
4880  break;
4881 
4882  default:
4883  ret = CIR_UNKNOWN;
4884  break;
4885  }
4886  }
4887 
4888  return ret;
4889 }
4890 
4891 static bool HandleChangeInfoResult(const char *caller, ChangeInfoResult cir, uint8_t feature, uint8_t property)
4892 {
4893  switch (cir) {
4894  default: NOT_REACHED();
4895 
4896  case CIR_DISABLED:
4897  /* Error has already been printed; just stop parsing */
4898  return true;
4899 
4900  case CIR_SUCCESS:
4901  return false;
4902 
4903  case CIR_UNHANDLED:
4904  GrfMsg(1, "{}: Ignoring property 0x{:02X} of feature 0x{:02X} (not implemented)", caller, property, feature);
4905  return false;
4906 
4907  case CIR_UNKNOWN:
4908  GrfMsg(0, "{}: Unknown property 0x{:02X} of feature 0x{:02X}, disabling", caller, property, feature);
4909  [[fallthrough]];
4910 
4911  case CIR_INVALID_ID: {
4912  /* No debug message for an invalid ID, as it has already been output */
4913  GRFError *error = DisableGrf(cir == CIR_INVALID_ID ? STR_NEWGRF_ERROR_INVALID_ID : STR_NEWGRF_ERROR_UNKNOWN_PROPERTY);
4914  if (cir != CIR_INVALID_ID) error->param_value[1] = property;
4915  return true;
4916  }
4917  }
4918 }
4919 
4920 /* Action 0x00 */
4921 static void FeatureChangeInfo(ByteReader &buf)
4922 {
4923  /* <00> <feature> <num-props> <num-info> <id> (<property <new-info>)...
4924  *
4925  * B feature
4926  * B num-props how many properties to change per vehicle/station
4927  * B num-info how many vehicles/stations to change
4928  * E id ID of first vehicle/station to change, if num-info is
4929  * greater than one, this one and the following
4930  * vehicles/stations will be changed
4931  * B property what property to change, depends on the feature
4932  * V new-info new bytes of info (variable size; depends on properties) */
4933 
4934  static const VCI_Handler handler[] = {
4935  /* GSF_TRAINS */ RailVehicleChangeInfo,
4936  /* GSF_ROADVEHICLES */ RoadVehicleChangeInfo,
4937  /* GSF_SHIPS */ ShipVehicleChangeInfo,
4938  /* GSF_AIRCRAFT */ AircraftVehicleChangeInfo,
4939  /* GSF_STATIONS */ StationChangeInfo,
4940  /* GSF_CANALS */ CanalChangeInfo,
4941  /* GSF_BRIDGES */ BridgeChangeInfo,
4942  /* GSF_HOUSES */ TownHouseChangeInfo,
4943  /* GSF_GLOBALVAR */ GlobalVarChangeInfo,
4944  /* GSF_INDUSTRYTILES */ IndustrytilesChangeInfo,
4945  /* GSF_INDUSTRIES */ IndustriesChangeInfo,
4946  /* GSF_CARGOES */ nullptr, // Cargo is handled during reservation
4947  /* GSF_SOUNDFX */ SoundEffectChangeInfo,
4948  /* GSF_AIRPORTS */ AirportChangeInfo,
4949  /* GSF_SIGNALS */ nullptr,
4950  /* GSF_OBJECTS */ ObjectChangeInfo,
4951  /* GSF_RAILTYPES */ RailTypeChangeInfo,
4952  /* GSF_AIRPORTTILES */ AirportTilesChangeInfo,
4953  /* GSF_ROADTYPES */ RoadTypeChangeInfo,
4954  /* GSF_TRAMTYPES */ TramTypeChangeInfo,
4955  /* GSF_ROADSTOPS */ RoadStopChangeInfo,
4956  };
4957  static_assert(GSF_END == lengthof(handler));
4958 
4959  uint8_t feature = buf.ReadByte();
4960  uint8_t numprops = buf.ReadByte();
4961  uint numinfo = buf.ReadByte();
4962  uint engine = buf.ReadExtendedByte();
4963 
4964  if (feature >= GSF_END) {
4965  GrfMsg(1, "FeatureChangeInfo: Unsupported feature 0x{:02X}, skipping", feature);
4966  return;
4967  }
4968 
4969  GrfMsg(6, "FeatureChangeInfo: Feature 0x{:02X}, {} properties, to apply to {}+{}",
4970  feature, numprops, engine, numinfo);
4971 
4972  if (handler[feature] == nullptr) {
4973  if (feature != GSF_CARGOES) GrfMsg(1, "FeatureChangeInfo: Unsupported feature 0x{:02X}, skipping", feature);
4974  return;
4975  }
4976 
4977  /* Mark the feature as used by the grf */
4978  SetBit(_cur.grffile->grf_features, feature);
4979 
4980  while (numprops-- && buf.HasData()) {
4981  uint8_t prop = buf.ReadByte();
4982 
4983  ChangeInfoResult cir = handler[feature](engine, numinfo, prop, buf);
4984  if (HandleChangeInfoResult("FeatureChangeInfo", cir, feature, prop)) return;
4985  }
4986 }
4987 
4988 /* Action 0x00 (GLS_SAFETYSCAN) */
4989 static void SafeChangeInfo(ByteReader &buf)
4990 {
4991  uint8_t feature = buf.ReadByte();
4992  uint8_t numprops = buf.ReadByte();
4993  uint numinfo = buf.ReadByte();
4994  buf.ReadExtendedByte(); // id
4995 
4996  if (feature == GSF_BRIDGES && numprops == 1) {
4997  uint8_t prop = buf.ReadByte();
4998  /* Bridge property 0x0D is redefinition of sprite layout tables, which
4999  * is considered safe. */
5000  if (prop == 0x0D) return;
5001  } else if (feature == GSF_GLOBALVAR && numprops == 1) {
5002  uint8_t prop = buf.ReadByte();
5003  /* Engine ID Mappings are safe, if the source is static */
5004  if (prop == 0x11) {
5005  bool is_safe = true;
5006  for (uint i = 0; i < numinfo; i++) {
5007  uint32_t s = buf.ReadDWord();
5008  buf.ReadDWord(); // dest
5009  const GRFConfig *grfconfig = GetGRFConfig(s);
5010  if (grfconfig != nullptr && !HasBit(grfconfig->flags, GCF_STATIC)) {
5011  is_safe = false;
5012  break;
5013  }
5014  }
5015  if (is_safe) return;
5016  }
5017  }
5018 
5019  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
5020 
5021  /* Skip remainder of GRF */
5022  _cur.skip_sprites = -1;
5023 }
5024 
5025 /* Action 0x00 (GLS_RESERVE) */
5026 static void ReserveChangeInfo(ByteReader &buf)
5027 {
5028  uint8_t feature = buf.ReadByte();
5029 
5030  if (feature != GSF_CARGOES && feature != GSF_GLOBALVAR && feature != GSF_RAILTYPES && feature != GSF_ROADTYPES && feature != GSF_TRAMTYPES) return;
5031 
5032  uint8_t numprops = buf.ReadByte();
5033  uint8_t numinfo = buf.ReadByte();
5034  uint8_t index = buf.ReadExtendedByte();
5035 
5036  while (numprops-- && buf.HasData()) {
5037  uint8_t prop = buf.ReadByte();
5039 
5040  switch (feature) {
5041  default: NOT_REACHED();
5042  case GSF_CARGOES:
5043  cir = CargoChangeInfo(index, numinfo, prop, buf);
5044  break;
5045 
5046  case GSF_GLOBALVAR:
5047  cir = GlobalVarReserveInfo(index, numinfo, prop, buf);
5048  break;
5049 
5050  case GSF_RAILTYPES:
5051  cir = RailTypeReserveInfo(index, numinfo, prop, buf);
5052  break;
5053 
5054  case GSF_ROADTYPES:
5055  cir = RoadTypeReserveInfo(index, numinfo, prop, buf);
5056  break;
5057 
5058  case GSF_TRAMTYPES:
5059  cir = TramTypeReserveInfo(index, numinfo, prop, buf);
5060  break;
5061  }
5062 
5063  if (HandleChangeInfoResult("ReserveChangeInfo", cir, feature, prop)) return;
5064  }
5065 }
5066 
5067 /* Action 0x01 */
5068 static void NewSpriteSet(ByteReader &buf)
5069 {
5070  /* Basic format: <01> <feature> <num-sets> <num-ent>
5071  * Extended format: <01> <feature> 00 <first-set> <num-sets> <num-ent>
5072  *
5073  * B feature feature to define sprites for
5074  * 0, 1, 2, 3: veh-type, 4: train stations
5075  * E first-set first sprite set to define
5076  * B num-sets number of sprite sets (extended byte in extended format)
5077  * E num-ent how many entries per sprite set
5078  * For vehicles, this is the number of different
5079  * vehicle directions in each sprite set
5080  * Set num-dirs=8, unless your sprites are symmetric.
5081  * In that case, use num-dirs=4.
5082  */
5083 
5084  uint8_t feature = buf.ReadByte();
5085  uint16_t num_sets = buf.ReadByte();
5086  uint16_t first_set = 0;
5087 
5088  if (num_sets == 0 && buf.HasData(3)) {
5089  /* Extended Action1 format.
5090  * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
5091  first_set = buf.ReadExtendedByte();
5092  num_sets = buf.ReadExtendedByte();
5093  }
5094  uint16_t num_ents = buf.ReadExtendedByte();
5095 
5096  if (feature >= GSF_END) {
5097  _cur.skip_sprites = num_sets * num_ents;
5098  GrfMsg(1, "NewSpriteSet: Unsupported feature 0x{:02X}, skipping {} sprites", feature, _cur.skip_sprites);
5099  return;
5100  }
5101 
5102  _cur.AddSpriteSets(feature, _cur.spriteid, first_set, num_sets, num_ents);
5103 
5104  GrfMsg(7, "New sprite set at {} of feature 0x{:02X}, consisting of {} sets with {} views each (total {})",
5105  _cur.spriteid, feature, num_sets, num_ents, num_sets * num_ents
5106  );
5107 
5108  for (int i = 0; i < num_sets * num_ents; i++) {
5109  _cur.nfo_line++;
5110  LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
5111  }
5112 }
5113 
5114 /* Action 0x01 (SKIP) */
5115 static void SkipAct1(ByteReader &buf)
5116 {
5117  buf.ReadByte();
5118  uint16_t num_sets = buf.ReadByte();
5119 
5120  if (num_sets == 0 && buf.HasData(3)) {
5121  /* Extended Action1 format.
5122  * Some GRFs define zero sets of zero sprites, though there is actually no use in that. Ignore them. */
5123  buf.ReadExtendedByte(); // first_set
5124  num_sets = buf.ReadExtendedByte();
5125  }
5126  uint16_t num_ents = buf.ReadExtendedByte();
5127 
5128  _cur.skip_sprites = num_sets * num_ents;
5129 
5130  GrfMsg(3, "SkipAct1: Skipping {} sprites", _cur.skip_sprites);
5131 }
5132 
5133 /* Helper function to either create a callback or link to a previously
5134  * defined spritegroup. */
5135 static const SpriteGroup *GetGroupFromGroupID(uint8_t setid, uint8_t type, uint16_t groupid)
5136 {
5137  if (HasBit(groupid, 15)) {
5139  return new CallbackResultSpriteGroup(groupid, _cur.grffile->grf_version >= 8);
5140  }
5141 
5142  if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
5143  GrfMsg(1, "GetGroupFromGroupID(0x{:02X}:0x{:02X}): Groupid 0x{:04X} does not exist, leaving empty", setid, type, groupid);
5144  return nullptr;
5145  }
5146 
5147  return _cur.spritegroups[groupid];
5148 }
5149 
5158 static const SpriteGroup *CreateGroupFromGroupID(uint8_t feature, uint8_t setid, uint8_t type, uint16_t spriteid)
5159 {
5160  if (HasBit(spriteid, 15)) {
5162  return new CallbackResultSpriteGroup(spriteid, _cur.grffile->grf_version >= 8);
5163  }
5164 
5165  if (!_cur.IsValidSpriteSet(feature, spriteid)) {
5166  GrfMsg(1, "CreateGroupFromGroupID(0x{:02X}:0x{:02X}): Sprite set {} invalid", setid, type, spriteid);
5167  return nullptr;
5168  }
5169 
5170  SpriteID spriteset_start = _cur.GetSprite(feature, spriteid);
5171  uint num_sprites = _cur.GetNumEnts(feature, spriteid);
5172 
5173  /* Ensure that the sprites are loeded */
5174  assert(spriteset_start + num_sprites <= _cur.spriteid);
5175 
5177  return new ResultSpriteGroup(spriteset_start, num_sprites);
5178 }
5179 
5180 /* Action 0x02 */
5181 static void NewSpriteGroup(ByteReader &buf)
5182 {
5183  /* <02> <feature> <set-id> <type/num-entries> <feature-specific-data...>
5184  *
5185  * B feature see action 1
5186  * B set-id ID of this particular definition
5187  * B type/num-entries
5188  * if 80 or greater, this is a randomized or variational
5189  * list definition, see below
5190  * otherwise it specifies a number of entries, the exact
5191  * meaning depends on the feature
5192  * V feature-specific-data (huge mess, don't even look it up --pasky) */
5193  const SpriteGroup *act_group = nullptr;
5194 
5195  uint8_t feature = buf.ReadByte();
5196  if (feature >= GSF_END) {
5197  GrfMsg(1, "NewSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
5198  return;
5199  }
5200 
5201  uint8_t setid = buf.ReadByte();
5202  uint8_t type = buf.ReadByte();
5203 
5204  /* Sprite Groups are created here but they are allocated from a pool, so
5205  * we do not need to delete anything if there is an exception from the
5206  * ByteReader. */
5207 
5208  switch (type) {
5209  /* Deterministic Sprite Group */
5210  case 0x81: // Self scope, byte
5211  case 0x82: // Parent scope, byte
5212  case 0x85: // Self scope, word
5213  case 0x86: // Parent scope, word
5214  case 0x89: // Self scope, dword
5215  case 0x8A: // Parent scope, dword
5216  {
5217  uint8_t varadjust;
5218  uint8_t varsize;
5219 
5222  group->nfo_line = _cur.nfo_line;
5223  act_group = group;
5224  group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5225 
5226  switch (GB(type, 2, 2)) {
5227  default: NOT_REACHED();
5228  case 0: group->size = DSG_SIZE_BYTE; varsize = 1; break;
5229  case 1: group->size = DSG_SIZE_WORD; varsize = 2; break;
5230  case 2: group->size = DSG_SIZE_DWORD; varsize = 4; break;
5231  }
5232 
5233  /* Loop through the var adjusts. Unfortunately we don't know how many we have
5234  * from the outset, so we shall have to keep reallocing. */
5235  do {
5236  DeterministicSpriteGroupAdjust &adjust = group->adjusts.emplace_back();
5237 
5238  /* The first var adjust doesn't have an operation specified, so we set it to add. */
5239  adjust.operation = group->adjusts.size() == 1 ? DSGA_OP_ADD : (DeterministicSpriteGroupAdjustOperation)buf.ReadByte();
5240  adjust.variable = buf.ReadByte();
5241  if (adjust.variable == 0x7E) {
5242  /* Link subroutine group */
5243  adjust.subroutine = GetGroupFromGroupID(setid, type, buf.ReadByte());
5244  } else {
5245  adjust.parameter = IsInsideMM(adjust.variable, 0x60, 0x80) ? buf.ReadByte() : 0;
5246  }
5247 
5248  varadjust = buf.ReadByte();
5249  adjust.shift_num = GB(varadjust, 0, 5);
5250  adjust.type = (DeterministicSpriteGroupAdjustType)GB(varadjust, 6, 2);
5251  adjust.and_mask = buf.ReadVarSize(varsize);
5252 
5253  if (adjust.type != DSGA_TYPE_NONE) {
5254  adjust.add_val = buf.ReadVarSize(varsize);
5255  adjust.divmod_val = buf.ReadVarSize(varsize);
5256  } else {
5257  adjust.add_val = 0;
5258  adjust.divmod_val = 0;
5259  }
5260 
5261  /* Continue reading var adjusts while bit 5 is set. */
5262  } while (HasBit(varadjust, 5));
5263 
5264  std::vector<DeterministicSpriteGroupRange> ranges;
5265  ranges.resize(buf.ReadByte());
5266  for (auto &range : ranges) {
5267  range.group = GetGroupFromGroupID(setid, type, buf.ReadWord());
5268  range.low = buf.ReadVarSize(varsize);
5269  range.high = buf.ReadVarSize(varsize);
5270  }
5271 
5272  group->default_group = GetGroupFromGroupID(setid, type, buf.ReadWord());
5273  group->error_group = ranges.empty() ? group->default_group : ranges[0].group;
5274  /* nvar == 0 is a special case -- we turn our value into a callback result */
5275  group->calculated_result = ranges.empty();
5276 
5277  /* Sort ranges ascending. When ranges overlap, this may required clamping or splitting them */
5278  std::vector<uint32_t> bounds;
5279  bounds.reserve(ranges.size());
5280  for (const auto &range : ranges) {
5281  bounds.push_back(range.low);
5282  if (range.high != UINT32_MAX) bounds.push_back(range.high + 1);
5283  }
5284  std::sort(bounds.begin(), bounds.end());
5285  bounds.erase(std::unique(bounds.begin(), bounds.end()), bounds.end());
5286 
5287  std::vector<const SpriteGroup *> target;
5288  target.reserve(bounds.size());
5289  for (const auto &bound : bounds) {
5290  const SpriteGroup *t = group->default_group;
5291  for (const auto &range : ranges) {
5292  if (range.low <= bound && bound <= range.high) {
5293  t = range.group;
5294  break;
5295  }
5296  }
5297  target.push_back(t);
5298  }
5299  assert(target.size() == bounds.size());
5300 
5301  for (uint j = 0; j < bounds.size(); ) {
5302  if (target[j] != group->default_group) {
5303  DeterministicSpriteGroupRange &r = group->ranges.emplace_back();
5304  r.group = target[j];
5305  r.low = bounds[j];
5306  while (j < bounds.size() && target[j] == r.group) {
5307  j++;
5308  }
5309  r.high = j < bounds.size() ? bounds[j] - 1 : UINT32_MAX;
5310  } else {
5311  j++;
5312  }
5313  }
5314 
5315  break;
5316  }
5317 
5318  /* Randomized Sprite Group */
5319  case 0x80: // Self scope
5320  case 0x83: // Parent scope
5321  case 0x84: // Relative scope
5322  {
5325  group->nfo_line = _cur.nfo_line;
5326  act_group = group;
5327  group->var_scope = HasBit(type, 1) ? VSG_SCOPE_PARENT : VSG_SCOPE_SELF;
5328 
5329  if (HasBit(type, 2)) {
5330  if (feature <= GSF_AIRCRAFT) group->var_scope = VSG_SCOPE_RELATIVE;
5331  group->count = buf.ReadByte();
5332  }
5333 
5334  uint8_t triggers = buf.ReadByte();
5335  group->triggers = GB(triggers, 0, 7);
5336  group->cmp_mode = HasBit(triggers, 7) ? RSG_CMP_ALL : RSG_CMP_ANY;
5337  group->lowest_randbit = buf.ReadByte();
5338 
5339  uint8_t num_groups = buf.ReadByte();
5340  if (!HasExactlyOneBit(num_groups)) {
5341  GrfMsg(1, "NewSpriteGroup: Random Action 2 nrand should be power of 2");
5342  }
5343 
5344  group->groups.reserve(num_groups);
5345  for (uint i = 0; i < num_groups; i++) {
5346  group->groups.push_back(GetGroupFromGroupID(setid, type, buf.ReadWord()));
5347  }
5348 
5349  break;
5350  }
5351 
5352  /* Neither a variable or randomized sprite group... must be a real group */
5353  default:
5354  {
5355  switch (feature) {
5356  case GSF_TRAINS:
5357  case GSF_ROADVEHICLES:
5358  case GSF_SHIPS:
5359  case GSF_AIRCRAFT:
5360  case GSF_STATIONS:
5361  case GSF_CANALS:
5362  case GSF_CARGOES:
5363  case GSF_AIRPORTS:
5364  case GSF_RAILTYPES:
5365  case GSF_ROADTYPES:
5366  case GSF_TRAMTYPES:
5367  {
5368  uint8_t num_loaded = type;
5369  uint8_t num_loading = buf.ReadByte();
5370 
5371  if (!_cur.HasValidSpriteSets(feature)) {
5372  GrfMsg(0, "NewSpriteGroup: No sprite set to work on! Skipping");
5373  return;
5374  }
5375 
5376  GrfMsg(6, "NewSpriteGroup: New SpriteGroup 0x{:02X}, {} loaded, {} loading",
5377  setid, num_loaded, num_loading);
5378 
5379  if (num_loaded + num_loading == 0) {
5380  GrfMsg(1, "NewSpriteGroup: no result, skipping invalid RealSpriteGroup");
5381  break;
5382  }
5383 
5384  if (num_loaded + num_loading == 1) {
5385  /* Avoid creating 'Real' sprite group if only one option. */
5386  uint16_t spriteid = buf.ReadWord();
5387  act_group = CreateGroupFromGroupID(feature, setid, type, spriteid);
5388  GrfMsg(8, "NewSpriteGroup: one result, skipping RealSpriteGroup = subset {}", spriteid);
5389  break;
5390  }
5391 
5392  std::vector<uint16_t> loaded;
5393  std::vector<uint16_t> loading;
5394 
5395  loaded.reserve(num_loaded);
5396  for (uint i = 0; i < num_loaded; i++) {
5397  loaded.push_back(buf.ReadWord());
5398  GrfMsg(8, "NewSpriteGroup: + rg->loaded[{}] = subset {}", i, loaded[i]);
5399  }
5400 
5401  loading.reserve(num_loading);
5402  for (uint i = 0; i < num_loading; i++) {
5403  loading.push_back(buf.ReadWord());
5404  GrfMsg(8, "NewSpriteGroup: + rg->loading[{}] = subset {}", i, loading[i]);
5405  }
5406 
5407  bool loaded_same = !loaded.empty() && std::adjacent_find(loaded.begin(), loaded.end(), std::not_equal_to<>()) == loaded.end();
5408  bool loading_same = !loading.empty() && std::adjacent_find(loading.begin(), loading.end(), std::not_equal_to<>()) == loading.end();
5409  if (loaded_same && loading_same && loaded[0] == loading[0]) {
5410  /* Both lists only contain the same value, so don't create 'Real' sprite group */
5411  act_group = CreateGroupFromGroupID(feature, setid, type, loaded[0]);
5412  GrfMsg(8, "NewSpriteGroup: same result, skipping RealSpriteGroup = subset {}", loaded[0]);
5413  break;
5414  }
5415 
5417  RealSpriteGroup *group = new RealSpriteGroup();
5418  group->nfo_line = _cur.nfo_line;
5419  act_group = group;
5420 
5421  if (loaded_same && loaded.size() > 1) loaded.resize(1);
5422  group->loaded.reserve(loaded.size());
5423  for (uint16_t spriteid : loaded) {
5424  const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5425  group->loaded.push_back(t);
5426  }
5427 
5428  if (loading_same && loading.size() > 1) loading.resize(1);
5429  group->loading.reserve(loading.size());
5430  for (uint16_t spriteid : loading) {
5431  const SpriteGroup *t = CreateGroupFromGroupID(feature, setid, type, spriteid);
5432  group->loading.push_back(t);
5433  }
5434 
5435  break;
5436  }
5437 
5438  case GSF_HOUSES:
5439  case GSF_AIRPORTTILES:
5440  case GSF_OBJECTS:
5441  case GSF_INDUSTRYTILES:
5442  case GSF_ROADSTOPS: {
5443  uint8_t num_building_sprites = std::max((uint8_t)1, type);
5444 
5447  group->nfo_line = _cur.nfo_line;
5448  act_group = group;
5449 
5450  /* On error, bail out immediately. Temporary GRF data was already freed */
5451  if (ReadSpriteLayout(buf, num_building_sprites, true, feature, false, type == 0, &group->dts)) return;
5452  break;
5453  }
5454 
5455  case GSF_INDUSTRIES: {
5456  if (type > 2) {
5457  GrfMsg(1, "NewSpriteGroup: Unsupported industry production version {}, skipping", type);
5458  break;
5459  }
5460 
5463  group->nfo_line = _cur.nfo_line;
5464  act_group = group;
5465  group->version = type;
5466  if (type == 0) {
5468  for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_INPUTS; i++) {
5469  group->subtract_input[i] = (int16_t)buf.ReadWord(); // signed
5470  }
5472  for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_OUTPUTS; i++) {
5473  group->add_output[i] = buf.ReadWord(); // unsigned
5474  }
5475  group->again = buf.ReadByte();
5476  } else if (type == 1) {
5478  for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_INPUTS; i++) {
5479  group->subtract_input[i] = buf.ReadByte();
5480  }
5482  for (uint i = 0; i < INDUSTRY_ORIGINAL_NUM_OUTPUTS; i++) {
5483  group->add_output[i] = buf.ReadByte();
5484  }
5485  group->again = buf.ReadByte();
5486  } else if (type == 2) {
5487  group->num_input = buf.ReadByte();
5488  if (group->num_input > lengthof(group->subtract_input)) {
5489  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5490  error->data = "too many inputs (max 16)";
5491  return;
5492  }
5493  for (uint i = 0; i < group->num_input; i++) {
5494  uint8_t rawcargo = buf.ReadByte();
5495  CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5496  if (!IsValidCargoID(cargo)) {
5497  /* The mapped cargo is invalid. This is permitted at this point,
5498  * as long as the result is not used. Mark it invalid so this
5499  * can be tested later. */
5500  group->version = 0xFF;
5501  } else if (std::find(group->cargo_input, group->cargo_input + i, cargo) != group->cargo_input + i) {
5502  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5503  error->data = "duplicate input cargo";
5504  return;
5505  }
5506  group->cargo_input[i] = cargo;
5507  group->subtract_input[i] = buf.ReadByte();
5508  }
5509  group->num_output = buf.ReadByte();
5510  if (group->num_output > lengthof(group->add_output)) {
5511  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5512  error->data = "too many outputs (max 16)";
5513  return;
5514  }
5515  for (uint i = 0; i < group->num_output; i++) {
5516  uint8_t rawcargo = buf.ReadByte();
5517  CargoID cargo = GetCargoTranslation(rawcargo, _cur.grffile);
5518  if (!IsValidCargoID(cargo)) {
5519  /* Mark this result as invalid to use */
5520  group->version = 0xFF;
5521  } else if (std::find(group->cargo_output, group->cargo_output + i, cargo) != group->cargo_output + i) {
5522  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_INDPROD_CALLBACK);
5523  error->data = "duplicate output cargo";
5524  return;
5525  }
5526  group->cargo_output[i] = cargo;
5527  group->add_output[i] = buf.ReadByte();
5528  }
5529  group->again = buf.ReadByte();
5530  } else {
5531  NOT_REACHED();
5532  }
5533  break;
5534  }
5535 
5536  /* Loading of Tile Layout and Production Callback groups would happen here */
5537  default: GrfMsg(1, "NewSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
5538  }
5539  }
5540  }
5541 
5542  _cur.spritegroups[setid] = act_group;
5543 }
5544 
5545 static CargoID TranslateCargo(uint8_t feature, uint8_t ctype)
5546 {
5547  /* Special cargo types for purchase list and stations */
5548  if ((feature == GSF_STATIONS || feature == GSF_ROADSTOPS) && ctype == 0xFE) return SpriteGroupCargo::SG_DEFAULT_NA;
5549  if (ctype == 0xFF) return SpriteGroupCargo::SG_PURCHASE;
5550 
5551  if (_cur.grffile->cargo_list.empty()) {
5552  /* No cargo table, so use bitnum values */
5553  if (ctype >= 32) {
5554  GrfMsg(1, "TranslateCargo: Cargo bitnum {} out of range (max 31), skipping.", ctype);
5555  return INVALID_CARGO;
5556  }
5557 
5558  for (const CargoSpec *cs : CargoSpec::Iterate()) {
5559  if (cs->bitnum == ctype) {
5560  GrfMsg(6, "TranslateCargo: Cargo bitnum {} mapped to cargo type {}.", ctype, cs->Index());
5561  return cs->Index();
5562  }
5563  }
5564 
5565  GrfMsg(5, "TranslateCargo: Cargo bitnum {} not available in this climate, skipping.", ctype);
5566  return INVALID_CARGO;
5567  }
5568 
5569  /* Check if the cargo type is out of bounds of the cargo translation table */
5570  if (ctype >= _cur.grffile->cargo_list.size()) {
5571  GrfMsg(1, "TranslateCargo: Cargo type {} out of range (max {}), skipping.", ctype, (unsigned int)_cur.grffile->cargo_list.size() - 1);
5572  return INVALID_CARGO;
5573  }
5574 
5575  /* Look up the cargo label from the translation table */
5576  CargoLabel cl = _cur.grffile->cargo_list[ctype];
5577  if (cl == CT_INVALID) {
5578  GrfMsg(5, "TranslateCargo: Cargo type {} not available in this climate, skipping.", ctype);
5579  return INVALID_CARGO;
5580  }
5581 
5582  CargoID cid = GetCargoIDByLabel(cl);
5583  if (!IsValidCargoID(cid)) {
5584  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));
5585  return INVALID_CARGO;
5586  }
5587 
5588  GrfMsg(6, "TranslateCargo: Cargo '{:c}{:c}{:c}{:c}' mapped to cargo type {}.", GB(cl.base(), 24, 8), GB(cl.base(), 16, 8), GB(cl.base(), 8, 8), GB(cl.base(), 0, 8), cid);
5589  return cid;
5590 }
5591 
5592 
5593 static bool IsValidGroupID(uint16_t groupid, const char *function)
5594 {
5595  if (groupid > MAX_SPRITEGROUP || _cur.spritegroups[groupid] == nullptr) {
5596  GrfMsg(1, "{}: Spritegroup 0x{:04X} out of range or empty, skipping.", function, groupid);
5597  return false;
5598  }
5599 
5600  return true;
5601 }
5602 
5603 static void VehicleMapSpriteGroup(ByteReader &buf, uint8_t feature, uint8_t idcount)
5604 {
5605  static std::vector<EngineID> last_engines; // Engine IDs are remembered in case the next action is a wagon override.
5606  bool wagover = false;
5607 
5608  /* Test for 'wagon override' flag */
5609  if (HasBit(idcount, 7)) {
5610  wagover = true;
5611  /* Strip off the flag */
5612  idcount = GB(idcount, 0, 7);
5613 
5614  if (last_engines.empty()) {
5615  GrfMsg(0, "VehicleMapSpriteGroup: WagonOverride: No engine to do override with");
5616  return;
5617  }
5618 
5619  GrfMsg(6, "VehicleMapSpriteGroup: WagonOverride: {} engines, {} wagons", last_engines.size(), idcount);
5620  } else {
5621  last_engines.resize(idcount);
5622  }
5623 
5624  std::vector<EngineID> engines;
5625  engines.reserve(idcount);
5626  for (uint i = 0; i < idcount; i++) {
5627  Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, buf.ReadExtendedByte());
5628  if (e == nullptr) {
5629  /* No engine could be allocated?!? Deal with it. Okay,
5630  * this might look bad. Also make sure this NewGRF
5631  * gets disabled, as a half loaded one is bad. */
5632  HandleChangeInfoResult("VehicleMapSpriteGroup", CIR_INVALID_ID, 0, 0);
5633  return;
5634  }
5635 
5636  engines.push_back(e->index);
5637  if (!wagover) last_engines[i] = engines[i];
5638  }
5639 
5640  uint8_t cidcount = buf.ReadByte();
5641  for (uint c = 0; c < cidcount; c++) {
5642  uint8_t ctype = buf.ReadByte();
5643  uint16_t groupid = buf.ReadWord();
5644  if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) continue;
5645 
5646  GrfMsg(8, "VehicleMapSpriteGroup: * [{}] Cargo type 0x{:X}, group id 0x{:02X}", c, ctype, groupid);
5647 
5648  CargoID cid = TranslateCargo(feature, ctype);
5649  if (!IsValidCargoID(cid)) continue;
5650 
5651  for (uint i = 0; i < idcount; i++) {
5652  EngineID engine = engines[i];
5653 
5654  GrfMsg(7, "VehicleMapSpriteGroup: [{}] Engine {}...", i, engine);
5655 
5656  if (wagover) {
5657  SetWagonOverrideSprites(engine, cid, _cur.spritegroups[groupid], last_engines);
5658  } else {
5659  SetCustomEngineSprites(engine, cid, _cur.spritegroups[groupid]);
5660  }
5661  }
5662  }
5663 
5664  uint16_t groupid = buf.ReadWord();
5665  if (!IsValidGroupID(groupid, "VehicleMapSpriteGroup")) return;
5666 
5667  GrfMsg(8, "-- Default group id 0x{:04X}", groupid);
5668 
5669  for (uint i = 0; i < idcount; i++) {
5670  EngineID engine = engines[i];
5671 
5672  if (wagover) {
5673  SetWagonOverrideSprites(engine, SpriteGroupCargo::SG_DEFAULT, _cur.spritegroups[groupid], last_engines);
5674  } else {
5675  SetCustomEngineSprites(engine, SpriteGroupCargo::SG_DEFAULT, _cur.spritegroups[groupid]);
5676  SetEngineGRF(engine, _cur.grffile);
5677  }
5678  }
5679 }
5680 
5681 
5682 static void CanalMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5683 {
5684  std::vector<uint16_t> cfs;
5685  cfs.reserve(idcount);
5686  for (uint i = 0; i < idcount; i++) {
5687  cfs.push_back(buf.ReadExtendedByte());
5688  }
5689 
5690  uint8_t cidcount = buf.ReadByte();
5691  buf.Skip(cidcount * 3);
5692 
5693  uint16_t groupid = buf.ReadWord();
5694  if (!IsValidGroupID(groupid, "CanalMapSpriteGroup")) return;
5695 
5696  for (auto &cf : cfs) {
5697  if (cf >= CF_END) {
5698  GrfMsg(1, "CanalMapSpriteGroup: Canal subset {} out of range, skipping", cf);
5699  continue;
5700  }
5701 
5702  _water_feature[cf].grffile = _cur.grffile;
5703  _water_feature[cf].group = _cur.spritegroups[groupid];
5704  }
5705 }
5706 
5707 
5708 static void StationMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5709 {
5710  if (_cur.grffile->stations.empty()) {
5711  GrfMsg(1, "StationMapSpriteGroup: No stations defined, skipping");
5712  return;
5713  }
5714 
5715  std::vector<uint16_t> stations;
5716  stations.reserve(idcount);
5717  for (uint i = 0; i < idcount; i++) {
5718  stations.push_back(buf.ReadExtendedByte());
5719  }
5720 
5721  uint8_t cidcount = buf.ReadByte();
5722  for (uint c = 0; c < cidcount; c++) {
5723  uint8_t ctype = buf.ReadByte();
5724  uint16_t groupid = buf.ReadWord();
5725  if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) continue;
5726 
5727  ctype = TranslateCargo(GSF_STATIONS, ctype);
5728  if (!IsValidCargoID(ctype)) continue;
5729 
5730  for (auto &station : stations) {
5731  StationSpec *statspec = station >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[station].get();
5732 
5733  if (statspec == nullptr) {
5734  GrfMsg(1, "StationMapSpriteGroup: Station {} undefined, skipping", station);
5735  continue;
5736  }
5737 
5738  statspec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
5739  }
5740  }
5741 
5742  uint16_t groupid = buf.ReadWord();
5743  if (!IsValidGroupID(groupid, "StationMapSpriteGroup")) return;
5744 
5745  for (auto &station : stations) {
5746  StationSpec *statspec = station >= _cur.grffile->stations.size() ? nullptr : _cur.grffile->stations[station].get();
5747 
5748  if (statspec == nullptr) {
5749  GrfMsg(1, "StationMapSpriteGroup: Station {} undefined, skipping", station);
5750  continue;
5751  }
5752 
5753  if (statspec->grf_prop.grffile != nullptr) {
5754  GrfMsg(1, "StationMapSpriteGroup: Station {} mapped multiple times, skipping", station);
5755  continue;
5756  }
5757 
5758  statspec->grf_prop.spritegroup[SpriteGroupCargo::SG_DEFAULT] = _cur.spritegroups[groupid];
5759  statspec->grf_prop.grffile = _cur.grffile;
5760  statspec->grf_prop.local_id = station;
5761  StationClass::Assign(statspec);
5762  }
5763 }
5764 
5765 
5766 static void TownHouseMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5767 {
5768  if (_cur.grffile->housespec.empty()) {
5769  GrfMsg(1, "TownHouseMapSpriteGroup: No houses defined, skipping");
5770  return;
5771  }
5772 
5773  std::vector<uint16_t> houses;
5774  houses.reserve(idcount);
5775  for (uint i = 0; i < idcount; i++) {
5776  houses.push_back(buf.ReadExtendedByte());
5777  }
5778 
5779  /* Skip the cargo type section, we only care about the default group */
5780  uint8_t cidcount = buf.ReadByte();
5781  buf.Skip(cidcount * 3);
5782 
5783  uint16_t groupid = buf.ReadWord();
5784  if (!IsValidGroupID(groupid, "TownHouseMapSpriteGroup")) return;
5785 
5786  for (auto &house : houses) {
5787  HouseSpec *hs = house >= _cur.grffile->housespec.size() ? nullptr : _cur.grffile->housespec[house].get();
5788 
5789  if (hs == nullptr) {
5790  GrfMsg(1, "TownHouseMapSpriteGroup: House {} undefined, skipping.", house);
5791  continue;
5792  }
5793 
5794  hs->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5795  }
5796 }
5797 
5798 static void IndustryMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5799 {
5800  if (_cur.grffile->industryspec.empty()) {
5801  GrfMsg(1, "IndustryMapSpriteGroup: No industries defined, skipping");
5802  return;
5803  }
5804 
5805  std::vector<uint16_t> industries;
5806  industries.reserve(idcount);
5807  for (uint i = 0; i < idcount; i++) {
5808  industries.push_back(buf.ReadExtendedByte());
5809  }
5810 
5811  /* Skip the cargo type section, we only care about the default group */
5812  uint8_t cidcount = buf.ReadByte();
5813  buf.Skip(cidcount * 3);
5814 
5815  uint16_t groupid = buf.ReadWord();
5816  if (!IsValidGroupID(groupid, "IndustryMapSpriteGroup")) return;
5817 
5818  for (auto &industry : industries) {
5819  IndustrySpec *indsp = industry >= _cur.grffile->industryspec.size() ? nullptr : _cur.grffile->industryspec[industry].get();
5820 
5821  if (indsp == nullptr) {
5822  GrfMsg(1, "IndustryMapSpriteGroup: Industry {} undefined, skipping", industry);
5823  continue;
5824  }
5825 
5826  indsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5827  }
5828 }
5829 
5830 static void IndustrytileMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5831 {
5832  if (_cur.grffile->indtspec.empty()) {
5833  GrfMsg(1, "IndustrytileMapSpriteGroup: No industry tiles defined, skipping");
5834  return;
5835  }
5836 
5837  std::vector<uint16_t> indtiles;
5838  indtiles.reserve(idcount);
5839  for (uint i = 0; i < idcount; i++) {
5840  indtiles.push_back(buf.ReadExtendedByte());
5841  }
5842 
5843  /* Skip the cargo type section, we only care about the default group */
5844  uint8_t cidcount = buf.ReadByte();
5845  buf.Skip(cidcount * 3);
5846 
5847  uint16_t groupid = buf.ReadWord();
5848  if (!IsValidGroupID(groupid, "IndustrytileMapSpriteGroup")) return;
5849 
5850  for (auto &indtile : indtiles) {
5851  IndustryTileSpec *indtsp = indtile >= _cur.grffile->indtspec.size() ? nullptr : _cur.grffile->indtspec[indtile].get();
5852 
5853  if (indtsp == nullptr) {
5854  GrfMsg(1, "IndustrytileMapSpriteGroup: Industry tile {} undefined, skipping", indtile);
5855  continue;
5856  }
5857 
5858  indtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
5859  }
5860 }
5861 
5862 static void CargoMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5863 {
5864  std::vector<uint16_t> cargoes;
5865  cargoes.reserve(idcount);
5866  for (uint i = 0; i < idcount; i++) {
5867  cargoes.push_back(buf.ReadExtendedByte());
5868  }
5869 
5870  /* Skip the cargo type section, we only care about the default group */
5871  uint8_t cidcount = buf.ReadByte();
5872  buf.Skip(cidcount * 3);
5873 
5874  uint16_t groupid = buf.ReadWord();
5875  if (!IsValidGroupID(groupid, "CargoMapSpriteGroup")) return;
5876 
5877  for (auto &cid : cargoes) {
5878  if (cid >= NUM_CARGO) {
5879  GrfMsg(1, "CargoMapSpriteGroup: Cargo ID {} out of range, skipping", cid);
5880  continue;
5881  }
5882 
5883  CargoSpec *cs = CargoSpec::Get(cid);
5884  cs->grffile = _cur.grffile;
5885  cs->group = _cur.spritegroups[groupid];
5886  }
5887 }
5888 
5889 static void ObjectMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5890 {
5891  if (_cur.grffile->objectspec.empty()) {
5892  GrfMsg(1, "ObjectMapSpriteGroup: No object tiles defined, skipping");
5893  return;
5894  }
5895 
5896  std::vector<uint16_t> objects;
5897  objects.reserve(idcount);
5898  for (uint i = 0; i < idcount; i++) {
5899  objects.push_back(buf.ReadExtendedByte());
5900  }
5901 
5902  uint8_t cidcount = buf.ReadByte();
5903  for (uint c = 0; c < cidcount; c++) {
5904  uint8_t ctype = buf.ReadByte();
5905  uint16_t groupid = buf.ReadWord();
5906  if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) continue;
5907 
5908  /* The only valid option here is purchase list sprite groups. */
5909  if (ctype != 0xFF) {
5910  GrfMsg(1, "ObjectMapSpriteGroup: Invalid cargo bitnum {} for objects, skipping.", ctype);
5911  continue;
5912  }
5913 
5914  for (auto &object : objects) {
5915  ObjectSpec *spec = object >= _cur.grffile->objectspec.size() ? nullptr : _cur.grffile->objectspec[object].get();
5916 
5917  if (spec == nullptr) {
5918  GrfMsg(1, "ObjectMapSpriteGroup: Object {} undefined, skipping", object);
5919  continue;
5920  }
5921 
5922  spec->grf_prop.spritegroup[OBJECT_SPRITE_GROUP_PURCHASE] = _cur.spritegroups[groupid];
5923  }
5924  }
5925 
5926  uint16_t groupid = buf.ReadWord();
5927  if (!IsValidGroupID(groupid, "ObjectMapSpriteGroup")) return;
5928 
5929  for (auto &object : objects) {
5930  ObjectSpec *spec = object >= _cur.grffile->objectspec.size() ? nullptr : _cur.grffile->objectspec[object].get();
5931 
5932  if (spec == nullptr) {
5933  GrfMsg(1, "ObjectMapSpriteGroup: Object {} undefined, skipping", object);
5934  continue;
5935  }
5936 
5937  if (spec->grf_prop.grffile != nullptr) {
5938  GrfMsg(1, "ObjectMapSpriteGroup: Object {} mapped multiple times, skipping", object);
5939  continue;
5940  }
5941 
5942  spec->grf_prop.spritegroup[OBJECT_SPRITE_GROUP_DEFAULT] = _cur.spritegroups[groupid];
5943  spec->grf_prop.grffile = _cur.grffile;
5944  spec->grf_prop.local_id = object;
5945  }
5946 }
5947 
5948 static void RailTypeMapSpriteGroup(ByteReader &buf, uint8_t idcount)
5949 {
5950  std::vector<uint8_t> railtypes;
5951  railtypes.reserve(idcount);
5952  for (uint i = 0; i < idcount; i++) {
5953  uint16_t id = buf.ReadExtendedByte();
5954  railtypes.push_back(id < RAILTYPE_END ? _cur.grffile->railtype_map[id] : INVALID_RAILTYPE);
5955  }
5956 
5957  uint8_t cidcount = buf.ReadByte();
5958  for (uint c = 0; c < cidcount; c++) {
5959  uint8_t ctype = buf.ReadByte();
5960  uint16_t groupid = buf.ReadWord();
5961  if (!IsValidGroupID(groupid, "RailTypeMapSpriteGroup")) continue;
5962 
5963  if (ctype >= RTSG_END) continue;
5964 
5965  extern RailTypeInfo _railtypes[RAILTYPE_END];
5966  for (auto &railtype : railtypes) {
5967  if (railtype != INVALID_RAILTYPE) {
5968  RailTypeInfo *rti = &_railtypes[railtype];
5969 
5970  rti->grffile[ctype] = _cur.grffile;
5971  rti->group[ctype] = _cur.spritegroups[groupid];
5972  }
5973  }
5974  }
5975 
5976  /* Railtypes do not use the default group. */
5977  buf.ReadWord();
5978 }
5979 
5980 static void RoadTypeMapSpriteGroup(ByteReader &buf, uint8_t idcount, RoadTramType rtt)
5981 {
5982  RoadType *type_map = (rtt == RTT_TRAM) ? _cur.grffile->tramtype_map : _cur.grffile->roadtype_map;
5983 
5984  std::vector<uint8_t> roadtypes;
5985  roadtypes.reserve(idcount);
5986  for (uint i = 0; i < idcount; i++) {
5987  uint16_t id = buf.ReadExtendedByte();
5988  roadtypes.push_back(id < ROADTYPE_END ? type_map[id] : INVALID_ROADTYPE);
5989  }
5990 
5991  uint8_t cidcount = buf.ReadByte();
5992  for (uint c = 0; c < cidcount; c++) {
5993  uint8_t ctype = buf.ReadByte();
5994  uint16_t groupid = buf.ReadWord();
5995  if (!IsValidGroupID(groupid, "RoadTypeMapSpriteGroup")) continue;
5996 
5997  if (ctype >= ROTSG_END) continue;
5998 
5999  extern RoadTypeInfo _roadtypes[ROADTYPE_END];
6000  for (auto &roadtype : roadtypes) {
6001  if (roadtype != INVALID_ROADTYPE) {
6002  RoadTypeInfo *rti = &_roadtypes[roadtype];
6003 
6004  rti->grffile[ctype] = _cur.grffile;
6005  rti->group[ctype] = _cur.spritegroups[groupid];
6006  }
6007  }
6008  }
6009 
6010  /* Roadtypes do not use the default group. */
6011  buf.ReadWord();
6012 }
6013 
6014 static void AirportMapSpriteGroup(ByteReader &buf, uint8_t idcount)
6015 {
6016  if (_cur.grffile->airportspec.empty()) {
6017  GrfMsg(1, "AirportMapSpriteGroup: No airports defined, skipping");
6018  return;
6019  }
6020 
6021  std::vector<uint16_t> airports;
6022  airports.reserve(idcount);
6023  for (uint i = 0; i < idcount; i++) {
6024  airports.push_back(buf.ReadExtendedByte());
6025  }
6026 
6027  /* Skip the cargo type section, we only care about the default group */
6028  uint8_t cidcount = buf.ReadByte();
6029  buf.Skip(cidcount * 3);
6030 
6031  uint16_t groupid = buf.ReadWord();
6032  if (!IsValidGroupID(groupid, "AirportMapSpriteGroup")) return;
6033 
6034  for (auto &airport : airports) {
6035  AirportSpec *as = airport >= _cur.grffile->airportspec.size() ? nullptr : _cur.grffile->airportspec[airport].get();
6036 
6037  if (as == nullptr) {
6038  GrfMsg(1, "AirportMapSpriteGroup: Airport {} undefined, skipping", airport);
6039  continue;
6040  }
6041 
6042  as->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
6043  }
6044 }
6045 
6046 static void AirportTileMapSpriteGroup(ByteReader &buf, uint8_t idcount)
6047 {
6048  if (_cur.grffile->airtspec.empty()) {
6049  GrfMsg(1, "AirportTileMapSpriteGroup: No airport tiles defined, skipping");
6050  return;
6051  }
6052 
6053  std::vector<uint16_t> airptiles;
6054  airptiles.reserve(idcount);
6055  for (uint i = 0; i < idcount; i++) {
6056  airptiles.push_back(buf.ReadExtendedByte());
6057  }
6058 
6059  /* Skip the cargo type section, we only care about the default group */
6060  uint8_t cidcount = buf.ReadByte();
6061  buf.Skip(cidcount * 3);
6062 
6063  uint16_t groupid = buf.ReadWord();
6064  if (!IsValidGroupID(groupid, "AirportTileMapSpriteGroup")) return;
6065 
6066  for (auto &airptile : airptiles) {
6067  AirportTileSpec *airtsp = airptile >= _cur.grffile->airtspec.size() ? nullptr : _cur.grffile->airtspec[airptile].get();
6068 
6069  if (airtsp == nullptr) {
6070  GrfMsg(1, "AirportTileMapSpriteGroup: Airport tile {} undefined, skipping", airptile);
6071  continue;
6072  }
6073 
6074  airtsp->grf_prop.spritegroup[0] = _cur.spritegroups[groupid];
6075  }
6076 }
6077 
6078 static void RoadStopMapSpriteGroup(ByteReader &buf, uint8_t idcount)
6079 {
6080  if (_cur.grffile->roadstops.empty()) {
6081  GrfMsg(1, "RoadStopMapSpriteGroup: No roadstops defined, skipping");
6082  return;
6083  }
6084 
6085  std::vector<uint16_t> roadstops;
6086  roadstops.reserve(idcount);
6087  for (uint i = 0; i < idcount; i++) {
6088  roadstops.push_back(buf.ReadExtendedByte());
6089  }
6090 
6091  uint8_t cidcount = buf.ReadByte();
6092  for (uint c = 0; c < cidcount; c++) {
6093  uint8_t ctype = buf.ReadByte();
6094  uint16_t groupid = buf.ReadWord();
6095  if (!IsValidGroupID(groupid, "RoadStopMapSpriteGroup")) continue;
6096 
6097  ctype = TranslateCargo(GSF_ROADSTOPS, ctype);
6098  if (!IsValidCargoID(ctype)) continue;
6099 
6100  for (auto &roadstop : roadstops) {
6101  RoadStopSpec *roadstopspec = roadstop >= _cur.grffile->roadstops.size() ? nullptr : _cur.grffile->roadstops[roadstop].get();
6102 
6103  if (roadstopspec == nullptr) {
6104  GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} undefined, skipping", roadstop);
6105  continue;
6106  }
6107 
6108  roadstopspec->grf_prop.spritegroup[ctype] = _cur.spritegroups[groupid];
6109  }
6110  }
6111 
6112  uint16_t groupid = buf.ReadWord();
6113  if (!IsValidGroupID(groupid, "RoadStopMapSpriteGroup")) return;
6114 
6115  for (auto &roadstop : roadstops) {
6116  RoadStopSpec *roadstopspec = roadstop >= _cur.grffile->roadstops.size() ? nullptr : _cur.grffile->roadstops[roadstop].get();
6117 
6118  if (roadstopspec == nullptr) {
6119  GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} undefined, skipping.", roadstop);
6120  continue;
6121  }
6122 
6123  if (roadstopspec->grf_prop.grffile != nullptr) {
6124  GrfMsg(1, "RoadStopMapSpriteGroup: Road stop {} mapped multiple times, skipping", roadstop);
6125  continue;
6126  }
6127 
6128  roadstopspec->grf_prop.spritegroup[SpriteGroupCargo::SG_DEFAULT] = _cur.spritegroups[groupid];
6129  roadstopspec->grf_prop.grffile = _cur.grffile;
6130  roadstopspec->grf_prop.local_id = roadstop;
6131  RoadStopClass::Assign(roadstopspec);
6132  }
6133 }
6134 
6135 /* Action 0x03 */
6136 static void FeatureMapSpriteGroup(ByteReader &buf)
6137 {
6138  /* <03> <feature> <n-id> <ids>... <num-cid> [<cargo-type> <cid>]... <def-cid>
6139  * id-list := [<id>] [id-list]
6140  * cargo-list := <cargo-type> <cid> [cargo-list]
6141  *
6142  * B feature see action 0
6143  * B n-id bits 0-6: how many IDs this definition applies to
6144  * bit 7: if set, this is a wagon override definition (see below)
6145  * E ids the IDs for which this definition applies
6146  * B num-cid number of cargo IDs (sprite group IDs) in this definition
6147  * can be zero, in that case the def-cid is used always
6148  * B cargo-type type of this cargo type (e.g. mail=2, wood=7, see below)
6149  * W cid cargo ID (sprite group ID) for this type of cargo
6150  * W def-cid default cargo ID (sprite group ID) */
6151 
6152  uint8_t feature = buf.ReadByte();
6153  uint8_t idcount = buf.ReadByte();
6154 
6155  if (feature >= GSF_END) {
6156  GrfMsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
6157  return;
6158  }
6159 
6160  /* If idcount is zero, this is a feature callback */
6161  if (idcount == 0) {
6162  /* Skip number of cargo ids? */
6163  buf.ReadByte();
6164  uint16_t groupid = buf.ReadWord();
6165  if (!IsValidGroupID(groupid, "FeatureMapSpriteGroup")) return;
6166 
6167  GrfMsg(6, "FeatureMapSpriteGroup: Adding generic feature callback for feature 0x{:02X}", feature);
6168 
6169  AddGenericCallback(feature, _cur.grffile, _cur.spritegroups[groupid]);
6170  return;
6171  }
6172 
6173  /* Mark the feature as used by the grf (generic callbacks do not count) */
6174  SetBit(_cur.grffile->grf_features, feature);
6175 
6176  GrfMsg(6, "FeatureMapSpriteGroup: Feature 0x{:02X}, {} ids", feature, idcount);
6177 
6178  switch (feature) {
6179  case GSF_TRAINS:
6180  case GSF_ROADVEHICLES:
6181  case GSF_SHIPS:
6182  case GSF_AIRCRAFT:
6183  VehicleMapSpriteGroup(buf, feature, idcount);
6184  return;
6185 
6186  case GSF_CANALS:
6187  CanalMapSpriteGroup(buf, idcount);
6188  return;
6189 
6190  case GSF_STATIONS:
6191  StationMapSpriteGroup(buf, idcount);
6192  return;
6193 
6194  case GSF_HOUSES:
6195  TownHouseMapSpriteGroup(buf, idcount);
6196  return;
6197 
6198  case GSF_INDUSTRIES:
6199  IndustryMapSpriteGroup(buf, idcount);
6200  return;
6201 
6202  case GSF_INDUSTRYTILES:
6203  IndustrytileMapSpriteGroup(buf, idcount);
6204  return;
6205 
6206  case GSF_CARGOES:
6207  CargoMapSpriteGroup(buf, idcount);
6208  return;
6209 
6210  case GSF_AIRPORTS:
6211  AirportMapSpriteGroup(buf, idcount);
6212  return;
6213 
6214  case GSF_OBJECTS:
6215  ObjectMapSpriteGroup(buf, idcount);
6216  break;
6217 
6218  case GSF_RAILTYPES:
6219  RailTypeMapSpriteGroup(buf, idcount);
6220  break;
6221 
6222  case GSF_ROADTYPES:
6223  RoadTypeMapSpriteGroup(buf, idcount, RTT_ROAD);
6224  break;
6225 
6226  case GSF_TRAMTYPES:
6227  RoadTypeMapSpriteGroup(buf, idcount, RTT_TRAM);
6228  break;
6229 
6230  case GSF_AIRPORTTILES:
6231  AirportTileMapSpriteGroup(buf, idcount);
6232  return;
6233 
6234  case GSF_ROADSTOPS:
6235  RoadStopMapSpriteGroup(buf, idcount);
6236  return;
6237 
6238  default:
6239  GrfMsg(1, "FeatureMapSpriteGroup: Unsupported feature 0x{:02X}, skipping", feature);
6240  return;
6241  }
6242 }
6243 
6244 /* Action 0x04 */
6245 static void FeatureNewName(ByteReader &buf)
6246 {
6247  /* <04> <veh-type> <language-id> <num-veh> <offset> <data...>
6248  *
6249  * B veh-type see action 0 (as 00..07, + 0A
6250  * But IF veh-type = 48, then generic text
6251  * B language-id If bit 6 is set, This is the extended language scheme,
6252  * with up to 64 language.
6253  * Otherwise, it is a mapping where set bits have meaning
6254  * 0 = american, 1 = english, 2 = german, 3 = french, 4 = spanish
6255  * Bit 7 set means this is a generic text, not a vehicle one (or else)
6256  * B num-veh number of vehicles which are getting a new name
6257  * B/W offset number of the first vehicle that gets a new name
6258  * Byte : ID of vehicle to change
6259  * Word : ID of string to change/add
6260  * S data new texts, each of them zero-terminated, after
6261  * which the next name begins. */
6262 
6263  bool new_scheme = _cur.grffile->grf_version >= 7;
6264 
6265  uint8_t feature = buf.ReadByte();
6266  if (feature >= GSF_END && feature != 0x48) {
6267  GrfMsg(1, "FeatureNewName: Unsupported feature 0x{:02X}, skipping", feature);
6268  return;
6269  }
6270 
6271  uint8_t lang = buf.ReadByte();
6272  uint8_t num = buf.ReadByte();
6273  bool generic = HasBit(lang, 7);
6274  uint16_t id;
6275  if (generic) {
6276  id = buf.ReadWord();
6277  } else if (feature <= GSF_AIRCRAFT) {
6278  id = buf.ReadExtendedByte();
6279  } else {
6280  id = buf.ReadByte();
6281  }
6282 
6283  ClrBit(lang, 7);
6284 
6285  uint16_t endid = id + num;
6286 
6287  GrfMsg(6, "FeatureNewName: About to rename engines {}..{} (feature 0x{:02X}) in language 0x{:02X}",
6288  id, endid, feature, lang);
6289 
6290  for (; id < endid && buf.HasData(); id++) {
6291  const std::string_view name = buf.ReadString();
6292  GrfMsg(8, "FeatureNewName: 0x{:04X} <- {}", id, StrMakeValid(name));
6293 
6294  switch (feature) {
6295  case GSF_TRAINS:
6296  case GSF_ROADVEHICLES:
6297  case GSF_SHIPS:
6298  case GSF_AIRCRAFT:
6299  if (!generic) {
6300  Engine *e = GetNewEngine(_cur.grffile, (VehicleType)feature, id, HasBit(_cur.grfconfig->flags, GCF_STATIC));
6301  if (e == nullptr) break;
6302  StringID string = AddGRFString(_cur.grffile->grfid, e->index, lang, new_scheme, false, name, e->info.string_id);
6303  e->info.string_id = string;
6304  } else {
6305  AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6306  }
6307  break;
6308 
6309  default:
6310  if (IsInsideMM(id, 0xD000, 0xD400) || IsInsideMM(id, 0xD800, 0x10000)) {
6311  AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, true, name, STR_UNDEFINED);
6312  break;
6313  }
6314 
6315  switch (GB(id, 8, 8)) {
6316  case 0xC4: // Station class name
6317  if (GB(id, 0, 8) >= _cur.grffile->stations.size() || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6318  GrfMsg(1, "FeatureNewName: Attempt to name undefined station 0x{:X}, ignoring", GB(id, 0, 8));
6319  } else {
6320  StationClassID class_index = _cur.grffile->stations[GB(id, 0, 8)]->class_index;
6321  StationClass::Get(class_index)->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6322  }
6323  break;
6324 
6325  case 0xC5: // Station name
6326  if (GB(id, 0, 8) >= _cur.grffile->stations.size() || _cur.grffile->stations[GB(id, 0, 8)] == nullptr) {
6327  GrfMsg(1, "FeatureNewName: Attempt to name undefined station 0x{:X}, ignoring", GB(id, 0, 8));
6328  } else {
6329  _cur.grffile->stations[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6330  }
6331  break;
6332 
6333  case 0xC7: // Airporttile name
6334  if (GB(id, 0, 8) >= _cur.grffile->airtspec.size() || _cur.grffile->airtspec[GB(id, 0, 8)] == nullptr) {
6335  GrfMsg(1, "FeatureNewName: Attempt to name undefined airport tile 0x{:X}, ignoring", GB(id, 0, 8));
6336  } else {
6337  _cur.grffile->airtspec[GB(id, 0, 8)]->name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6338  }
6339  break;
6340 
6341  case 0xC9: // House name
6342  if (GB(id, 0, 8) >= _cur.grffile->housespec.size() || _cur.grffile->housespec[GB(id, 0, 8)] == nullptr) {
6343  GrfMsg(1, "FeatureNewName: Attempt to name undefined house 0x{:X}, ignoring.", GB(id, 0, 8));
6344  } else {
6345  _cur.grffile->housespec[GB(id, 0, 8)]->building_name = AddGRFString(_cur.grffile->grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
6346  }
6347  break;
6348 
6349  default:
6350  GrfMsg(7, "FeatureNewName: Unsupported ID (0x{:04X})", id);
6351  break;
6352  }
6353  break;
6354  }
6355  }
6356 }
6357 
6366 static uint16_t SanitizeSpriteOffset(uint16_t &num, uint16_t offset, int max_sprites, const std::string_view name)
6367 {
6368 
6369  if (offset >= max_sprites) {
6370  GrfMsg(1, "GraphicsNew: {} sprite offset must be less than {}, skipping", name, max_sprites);
6371  uint orig_num = num;
6372  num = 0;
6373  return orig_num;
6374  }
6375 
6376  if (offset + num > max_sprites) {
6377  GrfMsg(4, "GraphicsNew: {} sprite overflow, truncating...", name);
6378  uint orig_num = num;
6379  num = std::max(max_sprites - offset, 0);
6380  return orig_num - num;
6381  }
6382 
6383  return 0;
6384 }
6385 
6386 
6388 static constexpr auto _action5_types = std::to_array<Action5Type>({
6389  /* Note: min_sprites should not be changed. Therefore these constants are directly here and not in sprites.h */
6390  /* 0x00 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x00" },
6391  /* 0x01 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x01" },
6392  /* 0x02 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x02" },
6393  /* 0x03 */ { A5BLOCK_INVALID, 0, 0, 0, "Type 0x03" },
6394  /* 0x04 */ { A5BLOCK_ALLOW_OFFSET, SPR_SIGNALS_BASE, 1, PRESIGNAL_SEMAPHORE_AND_PBS_SPRITE_COUNT, "Signal graphics" },
6395  /* 0x05 */ { A5BLOCK_ALLOW_OFFSET, SPR_ELRAIL_BASE, 1, ELRAIL_SPRITE_COUNT, "Rail catenary graphics" },
6396  /* 0x06 */ { A5BLOCK_ALLOW_OFFSET, SPR_SLOPES_BASE, 1, NORMAL_AND_HALFTILE_FOUNDATION_SPRITE_COUNT, "Foundation graphics" },
6397  /* 0x07 */ { A5BLOCK_INVALID, 0, 75, 0, "TTDP GUI graphics" }, // Not used by OTTD.
6398  /* 0x08 */ { A5BLOCK_ALLOW_OFFSET, SPR_CANALS_BASE, 1, CANALS_SPRITE_COUNT, "Canal graphics" },
6399  /* 0x09 */ { A5BLOCK_ALLOW_OFFSET, SPR_ONEWAY_BASE, 1, ONEWAY_SPRITE_COUNT, "One way road graphics" },
6400  /* 0x0A */ { A5BLOCK_ALLOW_OFFSET, SPR_2CCMAP_BASE, 1, TWOCCMAP_SPRITE_COUNT, "2CC colour maps" },
6401  /* 0x0B */ { A5BLOCK_ALLOW_OFFSET, SPR_TRAMWAY_BASE, 1, TRAMWAY_SPRITE_COUNT, "Tramway graphics" },
6402  /* 0x0C */ { A5BLOCK_INVALID, 0, 133, 0, "Snowy temperate tree" }, // Not yet used by OTTD.
6403  /* 0x0D */ { A5BLOCK_FIXED, SPR_SHORE_BASE, 16, SPR_SHORE_SPRITE_COUNT, "Shore graphics" },
6404  /* 0x0E */ { A5BLOCK_INVALID, 0, 0, 0, "New Signals graphics" }, // Not yet used by OTTD.
6405  /* 0x0F */ { A5BLOCK_ALLOW_OFFSET, SPR_TRACKS_FOR_SLOPES_BASE, 1, TRACKS_FOR_SLOPES_SPRITE_COUNT, "Sloped rail track" },
6406  /* 0x10 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORTX_BASE, 1, AIRPORTX_SPRITE_COUNT, "Airport graphics" },
6407  /* 0x11 */ { A5BLOCK_ALLOW_OFFSET, SPR_ROADSTOP_BASE, 1, ROADSTOP_SPRITE_COUNT, "Road stop graphics" },
6408  /* 0x12 */ { A5BLOCK_ALLOW_OFFSET, SPR_AQUEDUCT_BASE, 1, AQUEDUCT_SPRITE_COUNT, "Aqueduct graphics" },
6409  /* 0x13 */ { A5BLOCK_ALLOW_OFFSET, SPR_AUTORAIL_BASE, 1, AUTORAIL_SPRITE_COUNT, "Autorail graphics" },
6410  /* 0x14 */ { A5BLOCK_INVALID, 0, 1, 0, "Flag graphics" }, // deprecated, no longer used.
6411  /* 0x15 */ { A5BLOCK_ALLOW_OFFSET, SPR_OPENTTD_BASE, 1, OPENTTD_SPRITE_COUNT, "OpenTTD GUI graphics" },
6412  /* 0x16 */ { A5BLOCK_ALLOW_OFFSET, SPR_AIRPORT_PREVIEW_BASE, 1, SPR_AIRPORT_PREVIEW_COUNT, "Airport preview graphics" },
6413  /* 0x17 */ { A5BLOCK_ALLOW_OFFSET, SPR_RAILTYPE_TUNNEL_BASE, 1, RAILTYPE_TUNNEL_BASE_COUNT, "Railtype tunnel base" },
6414  /* 0x18 */ { A5BLOCK_ALLOW_OFFSET, SPR_PALETTE_BASE, 1, PALETTE_SPRITE_COUNT, "Palette" },
6415  /* 0x19 */ { A5BLOCK_ALLOW_OFFSET, SPR_ROAD_WAYPOINTS_BASE, 1, ROAD_WAYPOINTS_SPRITE_COUNT, "Road waypoints" },
6416 });
6417 
6422 std::span<const Action5Type> GetAction5Types()
6423 {
6424  return _action5_types;
6425 }
6426 
6427 /* Action 0x05 */
6428 static void GraphicsNew(ByteReader &buf)
6429 {
6430  /* <05> <graphics-type> <num-sprites> <other data...>
6431  *
6432  * B graphics-type What set of graphics the sprites define.
6433  * E num-sprites How many sprites are in this set?
6434  * V other data Graphics type specific data. Currently unused. */
6435 
6436  uint8_t type = buf.ReadByte();
6437  uint16_t num = buf.ReadExtendedByte();
6438  uint16_t offset = HasBit(type, 7) ? buf.ReadExtendedByte() : 0;
6439  ClrBit(type, 7); // Clear the high bit as that only indicates whether there is an offset.
6440 
6441  if ((type == 0x0D) && (num == 10) && HasBit(_cur.grfconfig->flags, GCF_SYSTEM)) {
6442  /* Special not-TTDP-compatible case used in openttd.grf
6443  * Missing shore sprites and initialisation of SPR_SHORE_BASE */
6444  GrfMsg(2, "GraphicsNew: Loading 10 missing shore sprites from extra grf.");
6445  LoadNextSprite(SPR_SHORE_BASE + 0, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_S
6446  LoadNextSprite(SPR_SHORE_BASE + 5, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_W
6447  LoadNextSprite(SPR_SHORE_BASE + 7, *_cur.file, _cur.nfo_line++); // SLOPE_WSE
6448  LoadNextSprite(SPR_SHORE_BASE + 10, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_N
6449  LoadNextSprite(SPR_SHORE_BASE + 11, *_cur.file, _cur.nfo_line++); // SLOPE_NWS
6450  LoadNextSprite(SPR_SHORE_BASE + 13, *_cur.file, _cur.nfo_line++); // SLOPE_ENW
6451  LoadNextSprite(SPR_SHORE_BASE + 14, *_cur.file, _cur.nfo_line++); // SLOPE_SEN
6452  LoadNextSprite(SPR_SHORE_BASE + 15, *_cur.file, _cur.nfo_line++); // SLOPE_STEEP_E
6453  LoadNextSprite(SPR_SHORE_BASE + 16, *_cur.file, _cur.nfo_line++); // SLOPE_EW
6454  LoadNextSprite(SPR_SHORE_BASE + 17, *_cur.file, _cur.nfo_line++); // SLOPE_NS
6456  return;
6457  }
6458 
6459  /* Supported type? */
6460  if ((type >= std::size(_action5_types)) || (_action5_types[type].block_type == A5BLOCK_INVALID)) {
6461  GrfMsg(2, "GraphicsNew: Custom graphics (type 0x{:02X}) sprite block of length {} (unimplemented, ignoring)", type, num);
6462  _cur.skip_sprites = num;
6463  return;
6464  }
6465 
6466  const Action5Type *action5_type = &_action5_types[type];
6467 
6468  /* Contrary to TTDP we allow always to specify too few sprites as we allow always an offset,
6469  * except for the long version of the shore type:
6470  * Ignore offset if not allowed */
6471  if ((action5_type->block_type != A5BLOCK_ALLOW_OFFSET) && (offset != 0)) {
6472  GrfMsg(1, "GraphicsNew: {} (type 0x{:02X}) do not allow an <offset> field. Ignoring offset.", action5_type->name, type);
6473  offset = 0;
6474  }
6475 
6476  /* Ignore action5 if too few sprites are specified. (for TTDP compatibility)
6477  * This does not make sense, if <offset> is allowed */
6478  if ((action5_type->block_type == A5BLOCK_FIXED) && (num < action5_type->min_sprites)) {
6479  GrfMsg(1, "GraphicsNew: {} (type 0x{:02X}) count must be at least {}. Only {} were specified. Skipping.", action5_type->name, type, action5_type->min_sprites, num);
6480  _cur.skip_sprites = num;
6481  return;
6482  }
6483 
6484  /* Load at most max_sprites sprites. Skip remaining sprites. (for compatibility with TTDP and future extensions) */
6485  uint16_t skip_num = SanitizeSpriteOffset(num, offset, action5_type->max_sprites, action5_type->name);
6486  SpriteID replace = action5_type->sprite_base + offset;
6487 
6488  /* Load <num> sprites starting from <replace>, then skip <skip_num> sprites. */
6489  GrfMsg(2, "GraphicsNew: Replacing sprites {} to {} of {} (type 0x{:02X}) at SpriteID 0x{:04X}", offset, offset + num - 1, action5_type->name, type, replace);
6490 
6492 
6493  if (type == 0x0B) {
6494  static const SpriteID depot_with_track_offset = SPR_TRAMWAY_DEPOT_WITH_TRACK - SPR_TRAMWAY_BASE;
6495  static const SpriteID depot_no_track_offset = SPR_TRAMWAY_DEPOT_NO_TRACK - SPR_TRAMWAY_BASE;
6496  if (offset <= depot_with_track_offset && offset + num > depot_with_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_WITH_TRACK;
6497  if (offset <= depot_no_track_offset && offset + num > depot_no_track_offset) _loaded_newgrf_features.tram = TRAMWAY_REPLACE_DEPOT_NO_TRACK;
6498  }
6499 
6500  /* If the baseset or grf only provides sprites for flat tiles (pre #10282), duplicate those for use on slopes. */
6501  bool dup_oneway_sprites = ((type == 0x09) && (offset + num <= SPR_ONEWAY_SLOPE_N_OFFSET));
6502 
6503  for (; num > 0; num--) {
6504  _cur.nfo_line++;
6505  int load_index = (replace == 0 ? _cur.spriteid++ : replace++);
6506  LoadNextSprite(load_index, *_cur.file, _cur.nfo_line);
6507  if (dup_oneway_sprites) {
6508  DupSprite(load_index, load_index + SPR_ONEWAY_SLOPE_N_OFFSET);
6509  DupSprite(load_index, load_index + SPR_ONEWAY_SLOPE_S_OFFSET);
6510  }
6511  }
6512 
6513  _cur.skip_sprites = skip_num;
6514 }
6515 
6516 /* Action 0x05 (SKIP) */
6517 static void SkipAct5(ByteReader &buf)
6518 {
6519  /* Ignore type byte */
6520  buf.ReadByte();
6521 
6522  /* Skip the sprites of this action */
6523  _cur.skip_sprites = buf.ReadExtendedByte();
6524 
6525  GrfMsg(3, "SkipAct5: Skipping {} sprites", _cur.skip_sprites);
6526 }
6527 
6539 bool GetGlobalVariable(uint8_t param, uint32_t *value, const GRFFile *grffile)
6540 {
6541  switch (param) {
6542  case 0x00: // current date
6543  *value = std::max(TimerGameCalendar::date - CalendarTime::DAYS_TILL_ORIGINAL_BASE_YEAR, TimerGameCalendar::Date(0)).base();
6544  return true;
6545 
6546  case 0x01: // current year
6548  return true;
6549 
6550  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)
6551  TimerGameCalendar::YearMonthDay ymd = TimerGameCalendar::ConvertDateToYMD(TimerGameCalendar::date);
6552  TimerGameCalendar::Date start_of_year = TimerGameCalendar::ConvertYMDToDate(ymd.year, 0, 1);
6553  *value = ymd.month | (ymd.day - 1) << 8 | (TimerGameCalendar::IsLeapYear(ymd.year) ? 1 << 15 : 0) | (TimerGameCalendar::date - start_of_year).base() << 16;
6554  return true;
6555  }
6556 
6557  case 0x03: // current climate, 0=temp, 1=arctic, 2=trop, 3=toyland
6559  return true;
6560 
6561  case 0x06: // road traffic side, bit 4 clear=left, set=right
6562  *value = _settings_game.vehicle.road_side << 4;
6563  return true;
6564 
6565  case 0x09: // date fraction
6566  *value = TimerGameCalendar::date_fract * 885;
6567  return true;
6568 
6569  case 0x0A: // animation counter
6570  *value = GB(TimerGameTick::counter, 0, 16);
6571  return true;
6572 
6573  case 0x0B: { // TTDPatch version
6574  uint major = 2;
6575  uint minor = 6;
6576  uint revision = 1; // special case: 2.0.1 is 2.0.10
6577  uint build = 1382;
6578  *value = (major << 24) | (minor << 20) | (revision << 16) | build;
6579  return true;
6580  }
6581 
6582  case 0x0D: // TTD Version, 00=DOS, 01=Windows
6583  *value = _cur.grfconfig->palette & GRFP_USE_MASK;
6584  return true;
6585 
6586  case 0x0E: // Y-offset for train sprites
6587  *value = _cur.grffile->traininfo_vehicle_pitch;
6588  return true;
6589 
6590  case 0x0F: // Rail track type cost factors
6591  *value = 0;
6592  SB(*value, 0, 8, GetRailTypeInfo(RAILTYPE_RAIL)->cost_multiplier); // normal rail
6594  /* skip elrail multiplier - disabled */
6595  SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_MONO)->cost_multiplier); // monorail
6596  } else {
6597  SB(*value, 8, 8, GetRailTypeInfo(RAILTYPE_ELECTRIC)->cost_multiplier); // electified railway
6598  /* Skip monorail multiplier - no space in result */
6599  }
6600  SB(*value, 16, 8, GetRailTypeInfo(RAILTYPE_MAGLEV)->cost_multiplier); // maglev
6601  return true;
6602 
6603  case 0x11: // current rail tool type
6604  *value = 0; // constant fake value to avoid desync
6605  return true;
6606 
6607  case 0x12: // Game mode
6608  *value = _game_mode;
6609  return true;
6610 
6611  /* case 0x13: // Tile refresh offset to left not implemented */
6612  /* case 0x14: // Tile refresh offset to right not implemented */
6613  /* case 0x15: // Tile refresh offset upwards not implemented */
6614  /* case 0x16: // Tile refresh offset downwards not implemented */
6615  /* case 0x17: // temperate snow line not implemented */
6616 
6617  case 0x1A: // Always -1
6618  *value = UINT_MAX;
6619  return true;
6620 
6621  case 0x1B: // Display options
6622  *value = 0x3F; // constant fake value to avoid desync
6623  return true;
6624 
6625  case 0x1D: // TTD Platform, 00=TTDPatch, 01=OpenTTD
6626  *value = 1;
6627  return true;
6628 
6629  case 0x1E: // Miscellaneous GRF features
6630  *value = _misc_grf_features;
6631 
6632  /* Add the local flags */
6633  assert(!HasBit(*value, GMB_TRAIN_WIDTH_32_PIXELS));
6634  if (_cur.grffile->traininfo_vehicle_width == VEHICLEINFO_FULL_VEHICLE_WIDTH) SetBit(*value, GMB_TRAIN_WIDTH_32_PIXELS);
6635  return true;
6636 
6637  /* case 0x1F: // locale dependent settings not implemented to avoid desync */
6638 
6639  case 0x20: { // snow line height
6640  uint8_t snowline = GetSnowLine();
6642  *value = Clamp(snowline * (grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFE);
6643  } else {
6644  /* No snow */
6645  *value = 0xFF;
6646  }
6647  return true;
6648  }
6649 
6650  case 0x21: // OpenTTD version
6651  *value = _openttd_newgrf_version;
6652  return true;
6653 
6654  case 0x22: // difficulty level
6655  *value = SP_CUSTOM;
6656  return true;
6657 
6658  case 0x23: // long format date
6659  *value = TimerGameCalendar::date.base();
6660  return true;
6661 
6662  case 0x24: // long format year
6663  *value = TimerGameCalendar::year.base();
6664  return true;
6665 
6666  default: return false;
6667  }
6668 }
6669 
6670 static uint32_t GetParamVal(uint8_t param, uint32_t *cond_val)
6671 {
6672  /* First handle variable common with VarAction2 */
6673  uint32_t value;
6674  if (GetGlobalVariable(param - 0x80, &value, _cur.grffile)) return value;
6675 
6676 
6677  /* Non-common variable */
6678  switch (param) {
6679  case 0x84: { // GRF loading stage
6680  uint32_t res = 0;
6681 
6682  if (_cur.stage > GLS_INIT) SetBit(res, 0);
6683  if (_cur.stage == GLS_RESERVE) SetBit(res, 8);
6684  if (_cur.stage == GLS_ACTIVATION) SetBit(res, 9);
6685  return res;
6686  }
6687 
6688  case 0x85: // TTDPatch flags, only for bit tests
6689  if (cond_val == nullptr) {
6690  /* Supported in Action 0x07 and 0x09, not 0x0D */
6691  return 0;
6692  } else {
6693  uint32_t index = *cond_val / 0x20;
6694  uint32_t param_val = index < lengthof(_ttdpatch_flags) ? _ttdpatch_flags[index] : 0;
6695  *cond_val %= 0x20;
6696  return param_val;
6697  }
6698 
6699  case 0x88: // GRF ID check
6700  return 0;
6701 
6702  /* case 0x99: Global ID offset not implemented */
6703 
6704  default:
6705  /* GRF Parameter */
6706  if (param < 0x80) return _cur.grffile->GetParam(param);
6707 
6708  /* In-game variable. */
6709  GrfMsg(1, "Unsupported in-game variable 0x{:02X}", param);
6710  return UINT_MAX;
6711  }
6712 }
6713 
6714 /* Action 0x06 */
6715 static void CfgApply(ByteReader &buf)
6716 {
6717  /* <06> <param-num> <param-size> <offset> ... <FF>
6718  *
6719  * B param-num Number of parameter to substitute (First = "zero")
6720  * Ignored if that parameter was not specified in newgrf.cfg
6721  * B param-size How many bytes to replace. If larger than 4, the
6722  * bytes of the following parameter are used. In that
6723  * case, nothing is applied unless *all* parameters
6724  * were specified.
6725  * B offset Offset into data from beginning of next sprite
6726  * to place where parameter is to be stored. */
6727 
6728  /* Preload the next sprite */
6729  SpriteFile &file = *_cur.file;
6730  size_t pos = file.GetPos();
6731  uint32_t num = file.GetContainerVersion() >= 2 ? file.ReadDword() : file.ReadWord();
6732  uint8_t type = file.ReadByte();
6733 
6734  /* Check if the sprite is a pseudo sprite. We can't operate on real sprites. */
6735  if (type != 0xFF) {
6736  GrfMsg(2, "CfgApply: Ignoring (next sprite is real, unsupported)");
6737 
6738  /* Reset the file position to the start of the next sprite */
6739  file.SeekTo(pos, SEEK_SET);
6740  return;
6741  }
6742 
6743  /* Get (or create) the override for the next sprite. */
6744  GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line + 1);
6745  std::vector<uint8_t> &preload_sprite = _grf_line_to_action6_sprite_override[location];
6746 
6747  /* Load new sprite data if it hasn't already been loaded. */
6748  if (preload_sprite.empty()) {
6749  preload_sprite.resize(num);
6750  file.ReadBlock(preload_sprite.data(), num);
6751  }
6752 
6753  /* Reset the file position to the start of the next sprite */
6754  file.SeekTo(pos, SEEK_SET);
6755 
6756  /* Now perform the Action 0x06 on our data. */
6757  for (;;) {
6758  uint i;
6759  uint param_num;
6760  uint param_size;
6761  uint offset;
6762  bool add_value;
6763 
6764  /* Read the parameter to apply. 0xFF indicates no more data to change. */
6765  param_num = buf.ReadByte();
6766  if (param_num == 0xFF) break;
6767 
6768  /* Get the size of the parameter to use. If the size covers multiple
6769  * double words, sequential parameter values are used. */
6770  param_size = buf.ReadByte();
6771 
6772  /* Bit 7 of param_size indicates we should add to the original value
6773  * instead of replacing it. */
6774  add_value = HasBit(param_size, 7);
6775  param_size = GB(param_size, 0, 7);
6776 
6777  /* Where to apply the data to within the pseudo sprite data. */
6778  offset = buf.ReadExtendedByte();
6779 
6780  /* If the parameter is a GRF parameter (not an internal variable) check
6781  * if it (and all further sequential parameters) has been defined. */
6782  if (param_num < 0x80 && (param_num + (param_size - 1) / 4) >= _cur.grffile->param_end) {
6783  GrfMsg(2, "CfgApply: Ignoring (param {} not set)", (param_num + (param_size - 1) / 4));
6784  break;
6785  }
6786 
6787  GrfMsg(8, "CfgApply: Applying {} bytes from parameter 0x{:02X} at offset 0x{:04X}", param_size, param_num, offset);
6788 
6789  bool carry = false;
6790  for (i = 0; i < param_size && offset + i < num; i++) {
6791  uint32_t value = GetParamVal(param_num + i / 4, nullptr);
6792  /* Reset carry flag for each iteration of the variable (only really
6793  * matters if param_size is greater than 4) */
6794  if (i % 4 == 0) carry = false;
6795 
6796  if (add_value) {
6797  uint new_value = preload_sprite[offset + i] + GB(value, (i % 4) * 8, 8) + (carry ? 1 : 0);
6798  preload_sprite[offset + i] = GB(new_value, 0, 8);
6799  /* Check if the addition overflowed */
6800  carry = new_value >= 256;
6801  } else {
6802  preload_sprite[offset + i] = GB(value, (i % 4) * 8, 8);
6803  }
6804  }
6805  }
6806 }
6807 
6818 {
6819  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_STATIC_GRF_CAUSES_DESYNC, c);
6820  error->data = _cur.grfconfig->GetName();
6821 }
6822 
6823 /* Action 0x07
6824  * Action 0x09 */
6825 static void SkipIf(ByteReader &buf)
6826 {
6827  /* <07/09> <param-num> <param-size> <condition-type> <value> <num-sprites>
6828  *
6829  * B param-num
6830  * B param-size
6831  * B condition-type
6832  * V value
6833  * B num-sprites */
6834  uint32_t cond_val = 0;
6835  uint32_t mask = 0;
6836  bool result;
6837 
6838  uint8_t param = buf.ReadByte();
6839  uint8_t paramsize = buf.ReadByte();
6840  uint8_t condtype = buf.ReadByte();
6841 
6842  if (condtype < 2) {
6843  /* Always 1 for bit tests, the given value should be ignored. */
6844  paramsize = 1;
6845  }
6846 
6847  switch (paramsize) {
6848  case 8: cond_val = buf.ReadDWord(); mask = buf.ReadDWord(); break;
6849  case 4: cond_val = buf.ReadDWord(); mask = 0xFFFFFFFF; break;
6850  case 2: cond_val = buf.ReadWord(); mask = 0x0000FFFF; break;
6851  case 1: cond_val = buf.ReadByte(); mask = 0x000000FF; break;
6852  default: break;
6853  }
6854 
6855  if (param < 0x80 && _cur.grffile->param_end <= param) {
6856  GrfMsg(7, "SkipIf: Param {} undefined, skipping test", param);
6857  return;
6858  }
6859 
6860  GrfMsg(7, "SkipIf: Test condtype {}, param 0x{:02X}, condval 0x{:08X}", condtype, param, cond_val);
6861 
6862  /* condtypes that do not use 'param' are always valid.
6863  * condtypes that use 'param' are either not valid for param 0x88, or they are only valid for param 0x88.
6864  */
6865  if (condtype >= 0x0B) {
6866  /* Tests that ignore 'param' */
6867  switch (condtype) {
6868  case 0x0B: result = !IsValidCargoID(GetCargoIDByLabel(CargoLabel(BSWAP32(cond_val))));
6869  break;
6870  case 0x0C: result = IsValidCargoID(GetCargoIDByLabel(CargoLabel(BSWAP32(cond_val))));
6871  break;
6872  case 0x0D: result = GetRailTypeByLabel(BSWAP32(cond_val)) == INVALID_RAILTYPE;
6873  break;
6874  case 0x0E: result = GetRailTypeByLabel(BSWAP32(cond_val)) != INVALID_RAILTYPE;
6875  break;
6876  case 0x0F: {
6877  RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6878  result = rt == INVALID_ROADTYPE || !RoadTypeIsRoad(rt);
6879  break;
6880  }
6881  case 0x10: {
6882  RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6883  result = rt != INVALID_ROADTYPE && RoadTypeIsRoad(rt);
6884  break;
6885  }
6886  case 0x11: {
6887  RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6888  result = rt == INVALID_ROADTYPE || !RoadTypeIsTram(rt);
6889  break;
6890  }
6891  case 0x12: {
6892  RoadType rt = GetRoadTypeByLabel(BSWAP32(cond_val));
6893  result = rt != INVALID_ROADTYPE && RoadTypeIsTram(rt);
6894  break;
6895  }
6896  default: GrfMsg(1, "SkipIf: Unsupported condition type {:02X}. Ignoring", condtype); return;
6897  }
6898  } else if (param == 0x88) {
6899  /* GRF ID checks */
6900 
6901  GRFConfig *c = GetGRFConfig(cond_val, mask);
6902 
6903  if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
6905  c = nullptr;
6906  }
6907 
6908  if (condtype != 10 && c == nullptr) {
6909  GrfMsg(7, "SkipIf: GRFID 0x{:08X} unknown, skipping test", BSWAP32(cond_val));
6910  return;
6911  }
6912 
6913  switch (condtype) {
6914  /* Tests 0x06 to 0x0A are only for param 0x88, GRFID checks */
6915  case 0x06: // Is GRFID active?
6916  result = c->status == GCS_ACTIVATED;
6917  break;
6918 
6919  case 0x07: // Is GRFID non-active?
6920  result = c->status != GCS_ACTIVATED;
6921  break;
6922 
6923  case 0x08: // GRFID is not but will be active?
6924  result = c->status == GCS_INITIALISED;
6925  break;
6926 
6927  case 0x09: // GRFID is or will be active?
6928  result = c->status == GCS_ACTIVATED || c->status == GCS_INITIALISED;
6929  break;
6930 
6931  case 0x0A: // GRFID is not nor will be active
6932  /* This is the only condtype that doesn't get ignored if the GRFID is not found */
6933  result = c == nullptr || c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND;
6934  break;
6935 
6936  default: GrfMsg(1, "SkipIf: Unsupported GRF condition type {:02X}. Ignoring", condtype); return;
6937  }
6938  } else {
6939  /* Tests that use 'param' and are not GRF ID checks. */
6940  uint32_t param_val = GetParamVal(param, &cond_val); // cond_val is modified for param == 0x85
6941  switch (condtype) {
6942  case 0x00: result = !!(param_val & (1 << cond_val));
6943  break;
6944  case 0x01: result = !(param_val & (1 << cond_val));
6945  break;
6946  case 0x02: result = (param_val & mask) == cond_val;
6947  break;
6948  case 0x03: result = (param_val & mask) != cond_val;
6949  break;
6950  case 0x04: result = (param_val & mask) < cond_val;
6951  break;
6952  case 0x05: result = (param_val & mask) > cond_val;
6953  break;
6954  default: GrfMsg(1, "SkipIf: Unsupported condition type {:02X}. Ignoring", condtype); return;
6955  }
6956  }
6957 
6958  if (!result) {
6959  GrfMsg(2, "SkipIf: Not skipping sprites, test was false");
6960  return;
6961  }
6962 
6963  uint8_t numsprites = buf.ReadByte();
6964 
6965  /* numsprites can be a GOTO label if it has been defined in the GRF
6966  * file. The jump will always be the first matching label that follows
6967  * the current nfo_line. If no matching label is found, the first matching
6968  * label in the file is used. */
6969  const GRFLabel *choice = nullptr;
6970  for (const auto &label : _cur.grffile->labels) {
6971  if (label.label != numsprites) continue;
6972 
6973  /* Remember a goto before the current line */
6974  if (choice == nullptr) choice = &label;
6975  /* If we find a label here, this is definitely good */
6976  if (label.nfo_line > _cur.nfo_line) {
6977  choice = &label;
6978  break;
6979  }
6980  }
6981 
6982  if (choice != nullptr) {
6983  GrfMsg(2, "SkipIf: Jumping to label 0x{:X} at line {}, test was true", choice->label, choice->nfo_line);
6984  _cur.file->SeekTo(choice->pos, SEEK_SET);
6985  _cur.nfo_line = choice->nfo_line;
6986  return;
6987  }
6988 
6989  GrfMsg(2, "SkipIf: Skipping {} sprites, test was true", numsprites);
6990  _cur.skip_sprites = numsprites;
6991  if (_cur.skip_sprites == 0) {
6992  /* Zero means there are no sprites to skip, so
6993  * we use -1 to indicate that all further
6994  * sprites should be skipped. */
6995  _cur.skip_sprites = -1;
6996 
6997  /* If an action 8 hasn't been encountered yet, disable the grf. */
6998  if (_cur.grfconfig->status != (_cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED)) {
6999  DisableGrf();
7000  }
7001  }
7002 }
7003 
7004 
7005 /* Action 0x08 (GLS_FILESCAN) */
7006 static void ScanInfo(ByteReader &buf)
7007 {
7008  uint8_t grf_version = buf.ReadByte();
7009  uint32_t grfid = buf.ReadDWord();
7010  std::string_view name = buf.ReadString();
7011 
7012  _cur.grfconfig->ident.grfid = grfid;
7013 
7014  if (grf_version < 2 || grf_version > 8) {
7016  Debug(grf, 0, "{}: NewGRF \"{}\" (GRFID {:08X}) uses GRF version {}, which is incompatible with this version of OpenTTD.", _cur.grfconfig->filename, StrMakeValid(name), BSWAP32(grfid), grf_version);
7017  }
7018 
7019  /* GRF IDs starting with 0xFF are reserved for internal TTDPatch use */
7020  if (GB(grfid, 0, 8) == 0xFF) SetBit(_cur.grfconfig->flags, GCF_SYSTEM);
7021 
7022  AddGRFTextToList(_cur.grfconfig->name, 0x7F, grfid, false, name);
7023 
7024  if (buf.HasData()) {
7025  std::string_view info = buf.ReadString();
7026  AddGRFTextToList(_cur.grfconfig->info, 0x7F, grfid, true, info);
7027  }
7028 
7029  /* GLS_INFOSCAN only looks for the action 8, so we can skip the rest of the file */
7030  _cur.skip_sprites = -1;
7031 }
7032 
7033 /* Action 0x08 */
7034 static void GRFInfo(ByteReader &buf)
7035 {
7036  /* <08> <version> <grf-id> <name> <info>
7037  *
7038  * B version newgrf version, currently 06
7039  * 4*B grf-id globally unique ID of this .grf file
7040  * S name name of this .grf set
7041  * S info string describing the set, and e.g. author and copyright */
7042 
7043  uint8_t version = buf.ReadByte();
7044  uint32_t grfid = buf.ReadDWord();
7045  std::string_view name = buf.ReadString();
7046 
7047  if (_cur.stage < GLS_RESERVE && _cur.grfconfig->status != GCS_UNKNOWN) {
7048  DisableGrf(STR_NEWGRF_ERROR_MULTIPLE_ACTION_8);
7049  return;
7050  }
7051 
7052  if (_cur.grffile->grfid != grfid) {
7053  Debug(grf, 0, "GRFInfo: GRFID {:08X} in FILESCAN stage does not match GRFID {:08X} in INIT/RESERVE/ACTIVATION stage", BSWAP32(_cur.grffile->grfid), BSWAP32(grfid));
7054  _cur.grffile->grfid = grfid;
7055  }
7056 
7057  _cur.grffile->grf_version = version;
7058  _cur.grfconfig->status = _cur.stage < GLS_RESERVE ? GCS_INITIALISED : GCS_ACTIVATED;
7059 
7060  /* Do swap the GRFID for displaying purposes since people expect that */
7061  Debug(grf, 1, "GRFInfo: Loaded GRFv{} set {:08X} - {} (palette: {}, version: {})", version, BSWAP32(grfid), StrMakeValid(name), (_cur.grfconfig->palette & GRFP_USE_MASK) ? "Windows" : "DOS", _cur.grfconfig->version);
7062 }
7063 
7070 static bool IsGRMReservedSprite(SpriteID first_sprite, uint16_t num_sprites)
7071 {
7072  for (const auto &grm_sprite : _grm_sprites) {
7073  if (grm_sprite.first.grfid != _cur.grffile->grfid) continue;
7074  if (grm_sprite.second.first <= first_sprite && grm_sprite.second.first + grm_sprite.second.second >= first_sprite + num_sprites) return true;
7075  }
7076  return false;
7077 }
7078 
7079 /* Action 0x0A */
7080 static void SpriteReplace(ByteReader &buf)
7081 {
7082  /* <0A> <num-sets> <set1> [<set2> ...]
7083  * <set>: <num-sprites> <first-sprite>
7084  *
7085  * B num-sets How many sets of sprites to replace.
7086  * Each set:
7087  * B num-sprites How many sprites are in this set
7088  * W first-sprite First sprite number to replace */
7089 
7090  uint8_t num_sets = buf.ReadByte();
7091 
7092  for (uint i = 0; i < num_sets; i++) {
7093  uint8_t num_sprites = buf.ReadByte();
7094  uint16_t first_sprite = buf.ReadWord();
7095 
7096  GrfMsg(2, "SpriteReplace: [Set {}] Changing {} sprites, beginning with {}",
7097  i, num_sprites, first_sprite
7098  );
7099 
7100  if (first_sprite + num_sprites >= SPR_OPENTTD_BASE) {
7101  /* Outside allowed range, check for GRM sprite reservations. */
7102  if (!IsGRMReservedSprite(first_sprite, num_sprites)) {
7103  GrfMsg(0, "SpriteReplace: [Set {}] Changing {} sprites, beginning with {}, above limit of {} and not within reserved range, ignoring.",
7104  i, num_sprites, first_sprite, SPR_OPENTTD_BASE);
7105 
7106  /* Load the sprites at the current location so they will do nothing instead of appearing to work. */
7107  first_sprite = _cur.spriteid;
7108  _cur.spriteid += num_sprites;
7109  }
7110  }
7111 
7112  for (uint j = 0; j < num_sprites; j++) {
7113  int load_index = first_sprite + j;
7114  _cur.nfo_line++;
7115  LoadNextSprite(load_index, *_cur.file, _cur.nfo_line); // XXX
7116 
7117  /* Shore sprites now located at different addresses.
7118  * So detect when the old ones get replaced. */
7119  if (IsInsideMM(load_index, SPR_ORIGINALSHORE_START, SPR_ORIGINALSHORE_END + 1)) {
7121  }
7122  }
7123  }
7124 }
7125 
7126 /* Action 0x0A (SKIP) */
7127 static void SkipActA(ByteReader &buf)
7128 {
7129  uint8_t num_sets = buf.ReadByte();
7130 
7131  for (uint i = 0; i < num_sets; i++) {
7132  /* Skip the sprites this replaces */
7133  _cur.skip_sprites += buf.ReadByte();
7134  /* But ignore where they go */
7135  buf.ReadWord();
7136  }
7137 
7138  GrfMsg(3, "SkipActA: Skipping {} sprites", _cur.skip_sprites);
7139 }
7140 
7141 /* Action 0x0B */
7142 static void GRFLoadError(ByteReader &buf)
7143 {
7144  /* <0B> <severity> <language-id> <message-id> [<message...> 00] [<data...>] 00 [<parnum>]
7145  *
7146  * B severity 00: notice, continue loading grf file
7147  * 01: warning, continue loading grf file
7148  * 02: error, but continue loading grf file, and attempt
7149  * loading grf again when loading or starting next game
7150  * 03: error, abort loading and prevent loading again in
7151  * the future (only when restarting the patch)
7152  * B language-id see action 4, use 1F for built-in error messages
7153  * B message-id message to show, see below
7154  * S message for custom messages (message-id FF), text of the message
7155  * not present for built-in messages.
7156  * V data additional data for built-in (or custom) messages
7157  * B parnum parameter numbers to be shown in the message (maximum of 2) */
7158 
7159  static const StringID msgstr[] = {
7160  STR_NEWGRF_ERROR_VERSION_NUMBER,
7161  STR_NEWGRF_ERROR_DOS_OR_WINDOWS,
7162  STR_NEWGRF_ERROR_UNSET_SWITCH,
7163  STR_NEWGRF_ERROR_INVALID_PARAMETER,
7164  STR_NEWGRF_ERROR_LOAD_BEFORE,
7165  STR_NEWGRF_ERROR_LOAD_AFTER,
7166  STR_NEWGRF_ERROR_OTTD_VERSION_NUMBER,
7167  };
7168 
7169  static const StringID sevstr[] = {
7170  STR_NEWGRF_ERROR_MSG_INFO,
7171  STR_NEWGRF_ERROR_MSG_WARNING,
7172  STR_NEWGRF_ERROR_MSG_ERROR,
7173  STR_NEWGRF_ERROR_MSG_FATAL
7174  };
7175 
7176  uint8_t severity = buf.ReadByte();
7177  uint8_t lang = buf.ReadByte();
7178  uint8_t message_id = buf.ReadByte();
7179 
7180  /* Skip the error if it isn't valid for the current language. */
7181  if (!CheckGrfLangID(lang, _cur.grffile->grf_version)) return;
7182 
7183  /* Skip the error until the activation stage unless bit 7 of the severity
7184  * is set. */
7185  if (!HasBit(severity, 7) && _cur.stage == GLS_INIT) {
7186  GrfMsg(7, "GRFLoadError: Skipping non-fatal GRFLoadError in stage {}", _cur.stage);
7187  return;
7188  }
7189  ClrBit(severity, 7);
7190 
7191  if (severity >= lengthof(sevstr)) {
7192  GrfMsg(7, "GRFLoadError: Invalid severity id {}. Setting to 2 (non-fatal error).", severity);
7193  severity = 2;
7194  } else if (severity == 3) {
7195  /* This is a fatal error, so make sure the GRF is deactivated and no
7196  * more of it gets loaded. */
7197  DisableGrf();
7198 
7199  /* Make sure we show fatal errors, instead of silly infos from before */
7200  _cur.grfconfig->error.reset();
7201  }
7202 
7203  if (message_id >= lengthof(msgstr) && message_id != 0xFF) {
7204  GrfMsg(7, "GRFLoadError: Invalid message id.");
7205  return;
7206  }
7207 
7208  if (buf.Remaining() <= 1) {
7209  GrfMsg(7, "GRFLoadError: No message data supplied.");
7210  return;
7211  }
7212 
7213  /* For now we can only show one message per newgrf file. */
7214  if (_cur.grfconfig->error.has_value()) return;
7215 
7216  _cur.grfconfig->error = {sevstr[severity]};
7217  GRFError *error = &_cur.grfconfig->error.value();
7218 
7219  if (message_id == 0xFF) {
7220  /* This is a custom error message. */
7221  if (buf.HasData()) {
7222  std::string_view message = buf.ReadString();
7223 
7224  error->custom_message = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, message, SCC_RAW_STRING_POINTER);
7225  } else {
7226  GrfMsg(7, "GRFLoadError: No custom message supplied.");
7227  error->custom_message.clear();
7228  }
7229  } else {
7230  error->message = msgstr[message_id];
7231  }
7232 
7233  if (buf.HasData()) {
7234  std::string_view data = buf.ReadString();
7235 
7236  error->data = TranslateTTDPatchCodes(_cur.grffile->grfid, lang, true, data);
7237  } else {
7238  GrfMsg(7, "GRFLoadError: No message data supplied.");
7239  error->data.clear();
7240  }
7241 
7242  /* Only two parameter numbers can be used in the string. */
7243  for (uint i = 0; i < error->param_value.size() && buf.HasData(); i++) {
7244  uint param_number = buf.ReadByte();
7245  error->param_value[i] = _cur.grffile->GetParam(param_number);
7246  }
7247 }
7248 
7249 /* Action 0x0C */
7250 static void GRFComment(ByteReader &buf)
7251 {
7252  /* <0C> [<ignored...>]
7253  *
7254  * V ignored Anything following the 0C is ignored */
7255 
7256  if (!buf.HasData()) return;
7257 
7258  std::string_view text = buf.ReadString();
7259  GrfMsg(2, "GRFComment: {}", StrMakeValid(text));
7260 }
7261 
7262 /* Action 0x0D (GLS_SAFETYSCAN) */
7263 static void SafeParamSet(ByteReader &buf)
7264 {
7265  uint8_t target = buf.ReadByte();
7266 
7267  /* Writing GRF parameters and some bits of 'misc GRF features' are safe. */
7268  if (target < 0x80 || target == 0x9E) return;
7269 
7270  /* GRM could be unsafe, but as here it can only happen after other GRFs
7271  * are loaded, it should be okay. If the GRF tried to use the slots it
7272  * reserved, it would be marked unsafe anyway. GRM for (e.g. bridge)
7273  * sprites is considered safe. */
7274 
7275  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7276 
7277  /* Skip remainder of GRF */
7278  _cur.skip_sprites = -1;
7279 }
7280 
7281 
7282 static uint32_t GetPatchVariable(uint8_t param)
7283 {
7284  switch (param) {
7285  /* start year - 1920 */
7287 
7288  /* freight trains weight factor */
7289  case 0x0E: return _settings_game.vehicle.freight_trains;
7290 
7291  /* empty wagon speed increase */
7292  case 0x0F: return 0;
7293 
7294  /* plane speed factor; our patch option is reversed from TTDPatch's,
7295  * the following is good for 1x, 2x and 4x (most common?) and...
7296  * well not really for 3x. */
7297  case 0x10:
7299  default:
7300  case 4: return 1;
7301  case 3: return 2;
7302  case 2: return 2;
7303  case 1: return 4;
7304  }
7305 
7306 
7307  /* 2CC colourmap base sprite */
7308  case 0x11: return SPR_2CCMAP_BASE;
7309 
7310  /* map size: format = -MABXYSS
7311  * M : the type of map
7312  * bit 0 : set : squared map. Bit 1 is now not relevant
7313  * clear : rectangle map. Bit 1 will indicate the bigger edge of the map
7314  * bit 1 : set : Y is the bigger edge. Bit 0 is clear
7315  * clear : X is the bigger edge.
7316  * A : minimum edge(log2) of the map
7317  * B : maximum edge(log2) of the map
7318  * XY : edges(log2) of each side of the map.
7319  * SS : combination of both X and Y, thus giving the size(log2) of the map
7320  */
7321  case 0x13: {
7322  uint8_t map_bits = 0;
7323  uint8_t log_X = Map::LogX() - 6; // subtraction is required to make the minimal size (64) zero based
7324  uint8_t log_Y = Map::LogY() - 6;
7325  uint8_t max_edge = std::max(log_X, log_Y);
7326 
7327  if (log_X == log_Y) { // we have a squared map, since both edges are identical
7328  SetBit(map_bits, 0);
7329  } else {
7330  if (max_edge == log_Y) SetBit(map_bits, 1); // edge Y been the biggest, mark it
7331  }
7332 
7333  return (map_bits << 24) | (std::min(log_X, log_Y) << 20) | (max_edge << 16) |
7334  (log_X << 12) | (log_Y << 8) | (log_X + log_Y);
7335  }
7336 
7337  /* The maximum height of the map. */
7338  case 0x14:
7340 
7341  /* Extra foundations base sprite */
7342  case 0x15:
7343  return SPR_SLOPES_BASE;
7344 
7345  /* Shore base sprite */
7346  case 0x16:
7347  return SPR_SHORE_BASE;
7348 
7349  /* Game map seed */
7350  case 0x17:
7352 
7353  default:
7354  GrfMsg(2, "ParamSet: Unknown Patch variable 0x{:02X}.", param);
7355  return 0;
7356  }
7357 }
7358 
7359 
7360 static uint32_t PerformGRM(uint32_t *grm, uint16_t num_ids, uint16_t count, uint8_t op, uint8_t target, const char *type)
7361 {
7362  uint start = 0;
7363  uint size = 0;
7364 
7365  if (op == 6) {
7366  /* Return GRFID of set that reserved ID */
7367  return grm[_cur.grffile->GetParam(target)];
7368  }
7369 
7370  /* With an operation of 2 or 3, we want to reserve a specific block of IDs */
7371  if (op == 2 || op == 3) start = _cur.grffile->GetParam(target);
7372 
7373  for (uint i = start; i < num_ids; i++) {
7374  if (grm[i] == 0) {
7375  size++;
7376  } else {
7377  if (op == 2 || op == 3) break;
7378  start = i + 1;
7379  size = 0;
7380  }
7381 
7382  if (size == count) break;
7383  }
7384 
7385  if (size == count) {
7386  /* Got the slot... */
7387  if (op == 0 || op == 3) {
7388  GrfMsg(2, "ParamSet: GRM: Reserving {} {} at {}", count, type, start);
7389  for (uint i = 0; i < count; i++) grm[start + i] = _cur.grffile->grfid;
7390  }
7391  return start;
7392  }
7393 
7394  /* Unable to allocate */
7395  if (op != 4 && op != 5) {
7396  /* Deactivate GRF */
7397  GrfMsg(0, "ParamSet: GRM: Unable to allocate {} {}, deactivating", count, type);
7398  DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7399  return UINT_MAX;
7400  }
7401 
7402  GrfMsg(1, "ParamSet: GRM: Unable to allocate {} {}", count, type);
7403  return UINT_MAX;
7404 }
7405 
7406 
7408 static void ParamSet(ByteReader &buf)
7409 {
7410  /* <0D> <target> <operation> <source1> <source2> [<data>]
7411  *
7412  * B target parameter number where result is stored
7413  * B operation operation to perform, see below
7414  * B source1 first source operand
7415  * B source2 second source operand
7416  * D data data to use in the calculation, not necessary
7417  * if both source1 and source2 refer to actual parameters
7418  *
7419  * Operations
7420  * 00 Set parameter equal to source1
7421  * 01 Addition, source1 + source2
7422  * 02 Subtraction, source1 - source2
7423  * 03 Unsigned multiplication, source1 * source2 (both unsigned)
7424  * 04 Signed multiplication, source1 * source2 (both signed)
7425  * 05 Unsigned bit shift, source1 by source2 (source2 taken to be a
7426  * signed quantity; left shift if positive and right shift if
7427  * negative, source1 is unsigned)
7428  * 06 Signed bit shift, source1 by source2
7429  * (source2 like in 05, and source1 as well)
7430  */
7431 
7432  uint8_t target = buf.ReadByte();
7433  uint8_t oper = buf.ReadByte();
7434  uint32_t src1 = buf.ReadByte();
7435  uint32_t src2 = buf.ReadByte();
7436 
7437  uint32_t data = 0;
7438  if (buf.Remaining() >= 4) data = buf.ReadDWord();
7439 
7440  /* You can add 80 to the operation to make it apply only if the target
7441  * is not defined yet. In this respect, a parameter is taken to be
7442  * defined if any of the following applies:
7443  * - it has been set to any value in the newgrf(w).cfg parameter list
7444  * - it OR A PARAMETER WITH HIGHER NUMBER has been set to any value by
7445  * an earlier action D */
7446  if (HasBit(oper, 7)) {
7447  if (target < 0x80 && target < _cur.grffile->param_end) {
7448  GrfMsg(7, "ParamSet: Param {} already defined, skipping", target);
7449  return;
7450  }
7451 
7452  oper = GB(oper, 0, 7);
7453  }
7454 
7455  if (src2 == 0xFE) {
7456  if (GB(data, 0, 8) == 0xFF) {
7457  if (data == 0x0000FFFF) {
7458  /* Patch variables */
7459  src1 = GetPatchVariable(src1);
7460  } else {
7461  /* GRF Resource Management */
7462  uint8_t op = src1;
7463  uint8_t feature = GB(data, 8, 8);
7464  uint16_t count = GB(data, 16, 16);
7465 
7466  if (_cur.stage == GLS_RESERVE) {
7467  if (feature == 0x08) {
7468  /* General sprites */
7469  if (op == 0) {
7470  /* Check if the allocated sprites will fit below the original sprite limit */
7471  if (_cur.spriteid + count >= 16384) {
7472  GrfMsg(0, "ParamSet: GRM: Unable to allocate {} sprites; try changing NewGRF order", count);
7473  DisableGrf(STR_NEWGRF_ERROR_GRM_FAILED);
7474  return;
7475  }
7476 
7477  /* Reserve space at the current sprite ID */
7478  GrfMsg(4, "ParamSet: GRM: Allocated {} sprites at {}", count, _cur.spriteid);
7479  _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)] = std::make_pair(_cur.spriteid, count);
7480  _cur.spriteid += count;
7481  }
7482  }
7483  /* Ignore GRM result during reservation */
7484  src1 = 0;
7485  } else if (_cur.stage == GLS_ACTIVATION) {
7486  switch (feature) {
7487  case 0x00: // Trains
7488  case 0x01: // Road Vehicles
7489  case 0x02: // Ships
7490  case 0x03: // Aircraft
7492  src1 = PerformGRM(&_grm_engines[_engine_offsets[feature]], _engine_counts[feature], count, op, target, "vehicles");
7493  if (_cur.skip_sprites == -1) return;
7494  } else {
7495  /* GRM does not apply for dynamic engine allocation. */
7496  switch (op) {
7497  case 2:
7498  case 3:
7499  src1 = _cur.grffile->GetParam(target);
7500  break;
7501 
7502  default:
7503  src1 = 0;
7504  break;
7505  }
7506  }
7507  break;
7508 
7509  case 0x08: // General sprites
7510  switch (op) {
7511  case 0:
7512  /* Return space reserved during reservation stage */
7513  src1 = _grm_sprites[GRFLocation(_cur.grffile->grfid, _cur.nfo_line)].first;
7514  GrfMsg(4, "ParamSet: GRM: Using pre-allocated sprites at {}", src1);
7515  break;
7516 
7517  case 1:
7518  src1 = _cur.spriteid;
7519  break;
7520 
7521  default:
7522  GrfMsg(1, "ParamSet: GRM: Unsupported operation {} for general sprites", op);
7523  return;
7524  }
7525  break;
7526 
7527  case 0x0B: // Cargo
7528  /* There are two ranges: one for cargo IDs and one for cargo bitmasks */
7529  src1 = PerformGRM(_grm_cargoes, NUM_CARGO * 2, count, op, target, "cargoes");
7530  if (_cur.skip_sprites == -1) return;
7531  break;
7532 
7533  default: GrfMsg(1, "ParamSet: GRM: Unsupported feature 0x{:X}", feature); return;
7534  }
7535  } else {
7536  /* Ignore GRM during initialization */
7537  src1 = 0;
7538  }
7539  }
7540  } else {
7541  /* Read another GRF File's parameter */
7542  const GRFFile *file = GetFileByGRFID(data);
7543  GRFConfig *c = GetGRFConfig(data);
7544  if (c != nullptr && HasBit(c->flags, GCF_STATIC) && !HasBit(_cur.grfconfig->flags, GCF_STATIC) && _networking) {
7545  /* Disable the read GRF if it is a static NewGRF. */
7547  src1 = 0;
7548  } else if (file == nullptr || c == nullptr || c->status == GCS_DISABLED) {
7549  src1 = 0;
7550  } else if (src1 == 0xFE) {
7551  src1 = c->version;
7552  } else {
7553  src1 = file->GetParam(src1);
7554  }
7555  }
7556  } else {
7557  /* The source1 and source2 operands refer to the grf parameter number
7558  * like in action 6 and 7. In addition, they can refer to the special
7559  * variables available in action 7, or they can be FF to use the value
7560  * of <data>. If referring to parameters that are undefined, a value
7561  * of 0 is used instead. */
7562  src1 = (src1 == 0xFF) ? data : GetParamVal(src1, nullptr);
7563  src2 = (src2 == 0xFF) ? data : GetParamVal(src2, nullptr);
7564  }
7565 
7566  uint32_t res;
7567  switch (oper) {
7568  case 0x00:
7569  res = src1;
7570  break;
7571 
7572  case 0x01:
7573  res = src1 + src2;
7574  break;
7575 
7576  case 0x02:
7577  res = src1 - src2;
7578  break;
7579 
7580  case 0x03:
7581  res = src1 * src2;
7582  break;
7583 
7584  case 0x04:
7585  res = (int32_t)src1 * (int32_t)src2;
7586  break;
7587 
7588  case 0x05:
7589  if ((int32_t)src2 < 0) {
7590  res = src1 >> -(int32_t)src2;
7591  } else {
7592  res = src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7593  }
7594  break;
7595 
7596  case 0x06:
7597  if ((int32_t)src2 < 0) {
7598  res = (int32_t)src1 >> -(int32_t)src2;
7599  } else {
7600  res = (int32_t)src1 << (src2 & 0x1F); // Same behaviour as in EvalAdjustT, mask 'value' to 5 bits, which should behave the same on all architectures.
7601  }
7602  break;
7603 
7604  case 0x07: // Bitwise AND
7605  res = src1 & src2;
7606  break;
7607 
7608  case 0x08: // Bitwise OR
7609  res = src1 | src2;
7610  break;
7611 
7612  case 0x09: // Unsigned division
7613  if (src2 == 0) {
7614  res = src1;
7615  } else {
7616  res = src1 / src2;
7617  }
7618  break;
7619 
7620  case 0x0A: // Signed division
7621  if (src2 == 0) {
7622  res = src1;
7623  } else {
7624  res = (int32_t)src1 / (int32_t)src2;
7625  }
7626  break;
7627 
7628  case 0x0B: // Unsigned modulo
7629  if (src2 == 0) {
7630  res = src1;
7631  } else {
7632  res = src1 % src2;
7633  }
7634  break;
7635 
7636  case 0x0C: // Signed modulo
7637  if (src2 == 0) {
7638  res = src1;
7639  } else {
7640  res = (int32_t)src1 % (int32_t)src2;
7641  }
7642  break;
7643 
7644  default: GrfMsg(0, "ParamSet: Unknown operation {}, skipping", oper); return;
7645  }
7646 
7647  switch (target) {
7648  case 0x8E: // Y-Offset for train sprites
7649  _cur.grffile->traininfo_vehicle_pitch = res;
7650  break;
7651 
7652  case 0x8F: { // Rail track type cost factors
7653  extern RailTypeInfo _railtypes[RAILTYPE_END];
7654  _railtypes[RAILTYPE_RAIL].cost_multiplier = GB(res, 0, 8);
7656  _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 0, 8);
7657  _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 8, 8);
7658  } else {
7659  _railtypes[RAILTYPE_ELECTRIC].cost_multiplier = GB(res, 8, 8);
7660  _railtypes[RAILTYPE_MONO].cost_multiplier = GB(res, 16, 8);
7661  }
7662  _railtypes[RAILTYPE_MAGLEV].cost_multiplier = GB(res, 16, 8);
7663  break;
7664  }
7665 
7666  /* not implemented */
7667  case 0x93: // Tile refresh offset to left -- Intended to allow support for larger sprites, not necessary for OTTD
7668  case 0x94: // Tile refresh offset to right
7669  case 0x95: // Tile refresh offset upwards
7670  case 0x96: // Tile refresh offset downwards
7671  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
7672  case 0x99: // Global ID offset -- Not necessary since IDs are remapped automatically
7673  GrfMsg(7, "ParamSet: Skipping unimplemented target 0x{:02X}", target);
7674  break;
7675 
7676  case 0x9E: // Miscellaneous GRF features
7677  /* Set train list engine width */
7678  _cur.grffile->traininfo_vehicle_width = HasBit(res, GMB_TRAIN_WIDTH_32_PIXELS) ? VEHICLEINFO_FULL_VEHICLE_WIDTH : TRAININFO_DEFAULT_VEHICLE_WIDTH;
7679  /* Remove the local flags from the global flags */
7681 
7682  /* Only copy safe bits for static grfs */
7683  if (HasBit(_cur.grfconfig->flags, GCF_STATIC)) {
7684  uint32_t safe_bits = 0;
7685  SetBit(safe_bits, GMB_SECOND_ROCKY_TILE_SET);
7686 
7687  _misc_grf_features = (_misc_grf_features & ~safe_bits) | (res & safe_bits);
7688  } else {
7689  _misc_grf_features = res;
7690  }
7691  break;
7692 
7693  case 0x9F: // locale-dependent settings
7694  GrfMsg(7, "ParamSet: Skipping unimplemented target 0x{:02X}", target);
7695  break;
7696 
7697  default:
7698  if (target < 0x80) {
7699  _cur.grffile->param[target] = res;
7700  /* param is zeroed by default */
7701  if (target + 1U > _cur.grffile->param_end) _cur.grffile->param_end = target + 1;
7702  } else {
7703  GrfMsg(7, "ParamSet: Skipping unknown target 0x{:02X}", target);
7704  }
7705  break;
7706  }
7707 }
7708 
7709 /* Action 0x0E (GLS_SAFETYSCAN) */
7710 static void SafeGRFInhibit(ByteReader &buf)
7711 {
7712  /* <0E> <num> <grfids...>
7713  *
7714  * B num Number of GRFIDs that follow
7715  * D grfids GRFIDs of the files to deactivate */
7716 
7717  uint8_t num = buf.ReadByte();
7718 
7719  for (uint i = 0; i < num; i++) {
7720  uint32_t grfid = buf.ReadDWord();
7721 
7722  /* GRF is unsafe it if tries to deactivate other GRFs */
7723  if (grfid != _cur.grfconfig->ident.grfid) {
7724  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
7725 
7726  /* Skip remainder of GRF */
7727  _cur.skip_sprites = -1;
7728 
7729  return;
7730  }
7731  }
7732 }
7733 
7734 /* Action 0x0E */
7735 static void GRFInhibit(ByteReader &buf)
7736 {
7737  /* <0E> <num> <grfids...>
7738  *
7739  * B num Number of GRFIDs that follow
7740  * D grfids GRFIDs of the files to deactivate */
7741 
7742  uint8_t num = buf.ReadByte();
7743 
7744  for (uint i = 0; i < num; i++) {
7745  uint32_t grfid = buf.ReadDWord();
7746  GRFConfig *file = GetGRFConfig(grfid);
7747 
7748  /* Unset activation flag */
7749  if (file != nullptr && file != _cur.grfconfig) {
7750  GrfMsg(2, "GRFInhibit: Deactivating file '{}'", file->filename);
7751  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_FORCEFULLY_DISABLED, file);
7752  error->data = _cur.grfconfig->GetName();
7753  }
7754  }
7755 }
7756 
7758 static void FeatureTownName(ByteReader &buf)
7759 {
7760  /* <0F> <id> <style-name> <num-parts> <parts>
7761  *
7762  * B id ID of this definition in bottom 7 bits (final definition if bit 7 set)
7763  * V style-name Name of the style (only for final definition)
7764  * B num-parts Number of parts in this definition
7765  * V parts The parts */
7766 
7767  uint32_t grfid = _cur.grffile->grfid;
7768 
7769  GRFTownName *townname = AddGRFTownName(grfid);
7770 
7771  uint8_t id = buf.ReadByte();
7772  GrfMsg(6, "FeatureTownName: definition 0x{:02X}", id & 0x7F);
7773 
7774  if (HasBit(id, 7)) {
7775  /* Final definition */
7776  ClrBit(id, 7);
7777  bool new_scheme = _cur.grffile->grf_version >= 7;
7778 
7779  uint8_t lang = buf.ReadByte();
7780  StringID style = STR_UNDEFINED;
7781 
7782  do {
7783  ClrBit(lang, 7);
7784 
7785  std::string_view name = buf.ReadString();
7786 
7787  std::string lang_name = TranslateTTDPatchCodes(grfid, lang, false, name);
7788  GrfMsg(6, "FeatureTownName: lang 0x{:X} -> '{}'", lang, lang_name);
7789 
7790  style = AddGRFString(grfid, id, lang, new_scheme, false, name, STR_UNDEFINED);
7791 
7792  lang = buf.ReadByte();
7793  } while (lang != 0);
7794  townname->styles.emplace_back(style, id);
7795  }
7796 
7797  uint8_t parts = buf.ReadByte();
7798  GrfMsg(6, "FeatureTownName: {} parts", parts);
7799 
7800  townname->partlists[id].reserve(parts);
7801  for (uint partnum = 0; partnum < parts; partnum++) {
7802  NamePartList &partlist = townname->partlists[id].emplace_back();
7803  uint8_t texts = buf.ReadByte();
7804  partlist.bitstart = buf.ReadByte();
7805  partlist.bitcount = buf.ReadByte();
7806  partlist.maxprob = 0;
7807  GrfMsg(6, "FeatureTownName: part {} contains {} texts and will use GB(seed, {}, {})", partnum, texts, partlist.bitstart, partlist.bitcount);
7808 
7809  partlist.parts.reserve(texts);
7810  for (uint textnum = 0; textnum < texts; textnum++) {
7811  NamePart &part = partlist.parts.emplace_back();
7812  part.prob = buf.ReadByte();
7813 
7814  if (HasBit(part.prob, 7)) {
7815  uint8_t ref_id = buf.ReadByte();
7816  if (ref_id >= GRFTownName::MAX_LISTS || townname->partlists[ref_id].empty()) {
7817  GrfMsg(0, "FeatureTownName: definition 0x{:02X} doesn't exist, deactivating", ref_id);
7818  DelGRFTownName(grfid);
7819  DisableGrf(STR_NEWGRF_ERROR_INVALID_ID);
7820  return;
7821  }
7822  part.id = ref_id;
7823  GrfMsg(6, "FeatureTownName: part {}, text {}, uses intermediate definition 0x{:02X} (with probability {})", partnum, textnum, ref_id, part.prob & 0x7F);
7824  } else {
7825  std::string_view text = buf.ReadString();
7826  part.text = TranslateTTDPatchCodes(grfid, 0, false, text);
7827  GrfMsg(6, "FeatureTownName: part {}, text {}, '{}' (with probability {})", partnum, textnum, part.text, part.prob);
7828  }
7829  partlist.maxprob += GB(part.prob, 0, 7);
7830  }
7831  GrfMsg(6, "FeatureTownName: part {}, total probability {}", partnum, partlist.maxprob);
7832  }
7833 }
7834 
7836 static void DefineGotoLabel(ByteReader &buf)
7837 {
7838  /* <10> <label> [<comment>]
7839  *
7840  * B label The label to define
7841  * V comment Optional comment - ignored */
7842 
7843  uint8_t nfo_label = buf.ReadByte();
7844 
7845  _cur.grffile->labels.emplace_back(nfo_label, _cur.nfo_line, _cur.file->GetPos());
7846 
7847  GrfMsg(2, "DefineGotoLabel: GOTO target with label 0x{:02X}", nfo_label);
7848 }
7849 
7854 static void ImportGRFSound(SoundEntry *sound)
7855 {
7856  const GRFFile *file;
7857  uint32_t grfid = _cur.file->ReadDword();
7858  SoundID sound_id = _cur.file->ReadWord();
7859 
7860  file = GetFileByGRFID(grfid);
7861  if (file == nullptr || file->sound_offset == 0) {
7862  GrfMsg(1, "ImportGRFSound: Source file not available");
7863  return;
7864  }
7865 
7866  if (sound_id >= file->num_sounds) {
7867  GrfMsg(1, "ImportGRFSound: Sound effect {} is invalid", sound_id);
7868  return;
7869  }
7870 
7871  GrfMsg(2, "ImportGRFSound: Copying sound {} ({}) from file {:x}", sound_id, file->sound_offset + sound_id, grfid);
7872 
7873  *sound = *GetSound(file->sound_offset + sound_id);
7874 
7875  /* Reset volume and priority, which TTDPatch doesn't copy */
7876  sound->volume = SOUND_EFFECT_MAX_VOLUME;
7877  sound->priority = 0;
7878 }
7879 
7885 static void LoadGRFSound(size_t offs, SoundEntry *sound)
7886 {
7887  /* Set default volume and priority */
7888  sound->volume = SOUND_EFFECT_MAX_VOLUME;
7889  sound->priority = 0;
7890 
7891  if (offs != SIZE_MAX) {
7892  /* Sound is present in the NewGRF. */
7893  sound->file = _cur.file;
7894  sound->file_offset = offs;
7895  sound->grf_container_ver = _cur.file->GetContainerVersion();
7896  }
7897 }
7898 
7899 /* Action 0x11 */
7900 static void GRFSound(ByteReader &buf)
7901 {
7902  /* <11> <num>
7903  *
7904  * W num Number of sound files that follow */
7905 
7906  uint16_t num = buf.ReadWord();
7907  if (num == 0) return;
7908 
7909  SoundEntry *sound;
7910  if (_cur.grffile->sound_offset == 0) {
7911  _cur.grffile->sound_offset = GetNumSounds();
7912  _cur.grffile->num_sounds = num;
7913  sound = AllocateSound(num);
7914  } else {
7915  sound = GetSound(_cur.grffile->sound_offset);
7916  }
7917 
7918  SpriteFile &file = *_cur.file;
7919  uint8_t grf_container_version = file.GetContainerVersion();
7920  for (int i = 0; i < num; i++) {
7921  _cur.nfo_line++;
7922 
7923  /* Check whether the index is in range. This might happen if multiple action 11 are present.
7924  * While this is invalid, we do not check for this. But we should prevent it from causing bigger trouble */
7925  bool invalid = i >= _cur.grffile->num_sounds;
7926 
7927  size_t offs = file.GetPos();
7928 
7929  uint32_t len = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
7930  uint8_t type = file.ReadByte();
7931 
7932  if (grf_container_version >= 2 && type == 0xFD) {
7933  /* Reference to sprite section. */
7934  if (invalid) {
7935  GrfMsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7936  file.SkipBytes(len);
7937  } else if (len != 4) {
7938  GrfMsg(1, "GRFSound: Invalid sprite section import");
7939  file.SkipBytes(len);
7940  } else {
7941  uint32_t id = file.ReadDword();
7942  if (_cur.stage == GLS_INIT) LoadGRFSound(GetGRFSpriteOffset(id), sound + i);
7943  }
7944  continue;
7945  }
7946 
7947  if (type != 0xFF) {
7948  GrfMsg(1, "GRFSound: Unexpected RealSprite found, skipping");
7949  file.SkipBytes(7);
7950  SkipSpriteData(*_cur.file, type, len - 8);
7951  continue;
7952  }
7953 
7954  if (invalid) {
7955  GrfMsg(1, "GRFSound: Sound index out of range (multiple Action 11?)");
7956  file.SkipBytes(len);
7957  }
7958 
7959  uint8_t action = file.ReadByte();
7960  switch (action) {
7961  case 0xFF:
7962  /* Allocate sound only in init stage. */
7963  if (_cur.stage == GLS_INIT) {
7964  if (grf_container_version >= 2) {
7965  GrfMsg(1, "GRFSound: Inline sounds are not supported for container version >= 2");
7966  } else {
7967  LoadGRFSound(offs, sound + i);
7968  }
7969  }
7970  file.SkipBytes(len - 1); // already read <action>
7971  break;
7972 
7973  case 0xFE:
7974  if (_cur.stage == GLS_ACTIVATION) {
7975  /* XXX 'Action 0xFE' isn't really specified. It is only mentioned for
7976  * importing sounds, so this is probably all wrong... */
7977  if (file.ReadByte() != 0) GrfMsg(1, "GRFSound: Import type mismatch");
7978  ImportGRFSound(sound + i);
7979  } else {
7980  file.SkipBytes(len - 1); // already read <action>
7981  }
7982  break;
7983 
7984  default:
7985  GrfMsg(1, "GRFSound: Unexpected Action {:x} found, skipping", action);
7986  file.SkipBytes(len - 1); // already read <action>
7987  break;
7988  }
7989  }
7990 }
7991 
7992 /* Action 0x11 (SKIP) */
7993 static void SkipAct11(ByteReader &buf)
7994 {
7995  /* <11> <num>
7996  *
7997  * W num Number of sound files that follow */
7998 
7999  _cur.skip_sprites = buf.ReadWord();
8000 
8001  GrfMsg(3, "SkipAct11: Skipping {} sprites", _cur.skip_sprites);
8002 }
8003 
8005 static void LoadFontGlyph(ByteReader &buf)
8006 {
8007  /* <12> <num_def> <font_size> <num_char> <base_char>
8008  *
8009  * B num_def Number of definitions
8010  * B font_size Size of font (0 = normal, 1 = small, 2 = large, 3 = mono)
8011  * B num_char Number of consecutive glyphs
8012  * W base_char First character index */
8013 
8014  uint8_t num_def = buf.ReadByte();
8015 
8016  for (uint i = 0; i < num_def; i++) {
8017  FontSize size = (FontSize)buf.ReadByte();
8018  uint8_t num_char = buf.ReadByte();
8019  uint16_t base_char = buf.ReadWord();
8020 
8021  if (size >= FS_END) {
8022  GrfMsg(1, "LoadFontGlyph: Size {} is not supported, ignoring", size);
8023  }
8024 
8025  GrfMsg(7, "LoadFontGlyph: Loading {} glyph(s) at 0x{:04X} for size {}", num_char, base_char, size);
8026 
8027  for (uint c = 0; c < num_char; c++) {
8028  if (size < FS_END) SetUnicodeGlyph(size, base_char + c, _cur.spriteid);
8029  _cur.nfo_line++;
8030  LoadNextSprite(_cur.spriteid++, *_cur.file, _cur.nfo_line);
8031  }
8032  }
8033 }
8034 
8036 static void SkipAct12(ByteReader &buf)
8037 {
8038  /* <12> <num_def> <font_size> <num_char> <base_char>
8039  *
8040  * B num_def Number of definitions
8041  * B font_size Size of font (0 = normal, 1 = small, 2 = large)
8042  * B num_char Number of consecutive glyphs
8043  * W base_char First character index */
8044 
8045  uint8_t num_def = buf.ReadByte();
8046 
8047  for (uint i = 0; i < num_def; i++) {
8048  /* Ignore 'size' byte */
8049  buf.ReadByte();
8050 
8051  /* Sum up number of characters */
8052  _cur.skip_sprites += buf.ReadByte();
8053 
8054  /* Ignore 'base_char' word */
8055  buf.ReadWord();
8056  }
8057 
8058  GrfMsg(3, "SkipAct12: Skipping {} sprites", _cur.skip_sprites);
8059 }
8060 
8063 {
8064  /* <13> <grfid> <num-ent> <offset> <text...>
8065  *
8066  * 4*B grfid The GRFID of the file whose texts are to be translated
8067  * B num-ent Number of strings
8068  * W offset First text ID
8069  * S text... Zero-terminated strings */
8070 
8071  uint32_t grfid = buf.ReadDWord();
8072  const GRFConfig *c = GetGRFConfig(grfid);
8073  if (c == nullptr || (c->status != GCS_INITIALISED && c->status != GCS_ACTIVATED)) {
8074  GrfMsg(7, "TranslateGRFStrings: GRFID 0x{:08X} unknown, skipping action 13", BSWAP32(grfid));
8075  return;
8076  }
8077 
8078  if (c->status == GCS_INITIALISED) {
8079  /* If the file is not active but will be activated later, give an error
8080  * and disable this file. */
8081  GRFError *error = DisableGrf(STR_NEWGRF_ERROR_LOAD_AFTER);
8082 
8083  error->data = GetString(STR_NEWGRF_ERROR_AFTER_TRANSLATED_FILE);
8084 
8085  return;
8086  }
8087 
8088  /* Since no language id is supplied for with version 7 and lower NewGRFs, this string has
8089  * to be added as a generic string, thus the language id of 0x7F. For this to work
8090  * new_scheme has to be true as well, which will also be implicitly the case for version 8
8091  * and higher. A language id of 0x7F will be overridden by a non-generic id, so this will
8092  * not change anything if a string has been provided specifically for this language. */
8093  uint8_t language = _cur.grffile->grf_version >= 8 ? buf.ReadByte() : 0x7F;
8094  uint8_t num_strings = buf.ReadByte();
8095  uint16_t first_id = buf.ReadWord();
8096 
8097  if (!((first_id >= 0xD000 && first_id + num_strings <= 0xD400) || (first_id >= 0xD800 && first_id + num_strings <= 0xE000))) {
8098  GrfMsg(7, "TranslateGRFStrings: Attempting to set out-of-range string IDs in action 13 (first: 0x{:04X}, number: 0x{:02X})", first_id, num_strings);
8099  return;
8100  }
8101 
8102  for (uint i = 0; i < num_strings && buf.HasData(); i++) {
8103  std::string_view string = buf.ReadString();
8104 
8105  if (string.empty()) {
8106  GrfMsg(7, "TranslateGRFString: Ignoring empty string.");
8107  continue;
8108  }
8109 
8110  AddGRFString(grfid, first_id + i, language, true, true, string, STR_UNDEFINED);
8111  }
8112 }
8113 
8115 static bool ChangeGRFName(uint8_t langid, std::string_view str)
8116 {
8117  AddGRFTextToList(_cur.grfconfig->name, langid, _cur.grfconfig->ident.grfid, false, str);
8118  return true;
8119 }
8120 
8122 static bool ChangeGRFDescription(uint8_t langid, std::string_view str)
8123 {
8124  AddGRFTextToList(_cur.grfconfig->info, langid, _cur.grfconfig->ident.grfid, true, str);
8125  return true;
8126 }
8127 
8129 static bool ChangeGRFURL(uint8_t langid, std::string_view str)
8130 {
8131  AddGRFTextToList(_cur.grfconfig->url, langid, _cur.grfconfig->ident.grfid, false, str);
8132  return true;
8133 }
8134 
8136 static bool ChangeGRFNumUsedParams(size_t len, ByteReader &buf)
8137 {
8138  if (len != 1) {
8139  GrfMsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'NPAR' but got {}, ignoring this field", len);
8140  buf.Skip(len);
8141  } else {
8142  _cur.grfconfig->num_valid_params = std::min(buf.ReadByte(), ClampTo<uint8_t>(_cur.grfconfig->param.size()));
8143  }
8144  return true;
8145 }
8146 
8148 static bool ChangeGRFPalette(size_t len, ByteReader &buf)
8149 {
8150  if (len != 1) {
8151  GrfMsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'PALS' but got {}, ignoring this field", len);
8152  buf.Skip(len);
8153  } else {
8154  char data = buf.ReadByte();
8155  GRFPalette pal = GRFP_GRF_UNSET;
8156  switch (data) {
8157  case '*':
8158  case 'A': pal = GRFP_GRF_ANY; break;
8159  case 'W': pal = GRFP_GRF_WINDOWS; break;
8160  case 'D': pal = GRFP_GRF_DOS; break;
8161  default:
8162  GrfMsg(2, "StaticGRFInfo: unexpected value '{:02X}' for 'INFO'->'PALS', ignoring this field", data);
8163  break;
8164  }
8165  if (pal != GRFP_GRF_UNSET) {
8166  _cur.grfconfig->palette &= ~GRFP_GRF_MASK;
8167  _cur.grfconfig->palette |= pal;
8168  }
8169  }
8170  return true;
8171 }
8172 
8174 static bool ChangeGRFBlitter(size_t len, ByteReader &buf)
8175 {
8176  if (len != 1) {
8177  GrfMsg(2, "StaticGRFInfo: expected only 1 byte for 'INFO'->'BLTR' but got {}, ignoring this field", len);
8178  buf.Skip(len);
8179  } else {
8180  char data = buf.ReadByte();
8181  GRFPalette pal = GRFP_BLT_UNSET;
8182  switch (data) {
8183  case '8': pal = GRFP_BLT_UNSET; break;
8184  case '3': pal = GRFP_BLT_32BPP; break;
8185  default:
8186  GrfMsg(2, "StaticGRFInfo: unexpected value '{:02X}' for 'INFO'->'BLTR', ignoring this field", data);
8187  return true;
8188  }
8189  _cur.grfconfig->palette &= ~GRFP_BLT_MASK;
8190  _cur.grfconfig->palette |= pal;
8191  }
8192  return true;
8193 }
8194 
8196 static bool ChangeGRFVersion(size_t len, ByteReader &buf)
8197 {
8198  if (len != 4) {
8199  GrfMsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'VRSN' but got {}, ignoring this field", len);
8200  buf.Skip(len);
8201  } else {
8202  /* Set min_loadable_version as well (default to minimal compatibility) */
8203  _cur.grfconfig->version = _cur.grfconfig->min_loadable_version = buf.ReadDWord();
8204  }
8205  return true;
8206 }
8207 
8209 static bool ChangeGRFMinVersion(size_t len, ByteReader &buf)
8210 {
8211  if (len != 4) {
8212  GrfMsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'MINV' but got {}, ignoring this field", len);
8213  buf.Skip(len);
8214  } else {
8215  _cur.grfconfig->min_loadable_version = buf.ReadDWord();
8216  if (_cur.grfconfig->version == 0) {
8217  GrfMsg(2, "StaticGRFInfo: 'MINV' defined before 'VRSN' or 'VRSN' set to 0, ignoring this field");
8218  _cur.grfconfig->min_loadable_version = 0;
8219  }
8220  if (_cur.grfconfig->version < _cur.grfconfig->min_loadable_version) {
8221  GrfMsg(2, "StaticGRFInfo: 'MINV' defined as {}, limiting it to 'VRSN'", _cur.grfconfig->min_loadable_version);
8223  }
8224  }
8225  return true;
8226 }
8227 
8229 
8231 static bool ChangeGRFParamName(uint8_t langid, std::string_view str)
8232 {
8233  AddGRFTextToList(_cur_parameter->name, langid, _cur.grfconfig->ident.grfid, false, str);
8234  return true;
8235 }
8236 
8238 static bool ChangeGRFParamDescription(uint8_t langid, std::string_view str)
8239 {
8240  AddGRFTextToList(_cur_parameter->desc, langid, _cur.grfconfig->ident.grfid, true, str);
8241  return true;
8242 }
8243 
8245 static bool ChangeGRFParamType(size_t len, ByteReader &buf)
8246 {
8247  if (len != 1) {
8248  GrfMsg(2, "StaticGRFInfo: expected 1 byte for 'INFO'->'PARA'->'TYPE' but got {}, ignoring this field", len);
8249  buf.Skip(len);
8250  } else {
8251  GRFParameterType type = (GRFParameterType)buf.ReadByte();
8252  if (type < PTYPE_END) {
8253  _cur_parameter->type = type;
8254  } else {
8255  GrfMsg(3, "StaticGRFInfo: unknown parameter type {}, ignoring this field", type);
8256  }
8257  }
8258  return true;
8259 }
8260 
8262 static bool ChangeGRFParamLimits(size_t len, ByteReader &buf)
8263 {
8265  GrfMsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' is only valid for parameters with type uint/enum, ignoring this field");
8266  buf.Skip(len);
8267  } else if (len != 8) {
8268  GrfMsg(2, "StaticGRFInfo: expected 8 bytes for 'INFO'->'PARA'->'LIMI' but got {}, ignoring this field", len);
8269  buf.Skip(len);
8270  } else {
8271  uint32_t min_value = buf.ReadDWord();
8272  uint32_t max_value = buf.ReadDWord();
8273  if (min_value <= max_value) {
8274  _cur_parameter->min_value = min_value;
8275  _cur_parameter->max_value = max_value;
8276  } else {
8277  GrfMsg(2, "StaticGRFInfo: 'INFO'->'PARA'->'LIMI' values are incoherent, ignoring this field");
8278  }
8279  }
8280  return true;
8281 }
8282 
8284 static bool ChangeGRFParamMask(size_t len, ByteReader &buf)
8285 {
8286  if (len < 1 || len > 3) {
8287  GrfMsg(2, "StaticGRFInfo: expected 1 to 3 bytes for 'INFO'->'PARA'->'MASK' but got {}, ignoring this field", len);
8288  buf.Skip(len);
8289  } else {
8290  uint8_t param_nr = buf.ReadByte();
8291  if (param_nr >= _cur.grfconfig->param.size()) {
8292  GrfMsg(2, "StaticGRFInfo: invalid parameter number in 'INFO'->'PARA'->'MASK', param {}, ignoring this field", param_nr);
8293  buf.Skip(len - 1);
8294  } else {
8295  _cur_parameter->param_nr = param_nr;
8296  if (len >= 2) _cur_parameter->first_bit = std::min<uint8_t>(buf.ReadByte(), 31);
8297  if (len >= 3) _cur_parameter->num_bit = std::min<uint8_t>(buf.ReadByte(), 32 - _cur_parameter->first_bit);
8298  }
8299  }
8300 
8301  return true;
8302 }
8303 
8305 static bool ChangeGRFParamDefault(size_t len, ByteReader &buf)
8306 {
8307  if (len != 4) {
8308  GrfMsg(2, "StaticGRFInfo: expected 4 bytes for 'INFO'->'PARA'->'DEFA' but got {}, ignoring this field", len);
8309  buf.Skip(len);
8310  } else {
8311  _cur_parameter->def_value = buf.ReadDWord();
8312  }
8313  _cur.grfconfig->has_param_defaults = true;
8314  return true;
8315 }
8316 
8317 typedef bool (*DataHandler)(size_t, ByteReader &);
8318 typedef bool (*TextHandler)(uint8_t, std::string_view str);
8319 typedef bool (*BranchHandler)(ByteReader &);
8320 
8331  id(0),
8332  type(0)
8333  {}
8334 
8340  AllowedSubtags(uint32_t id, DataHandler handler) :
8341  id(id),
8342  type('B')
8343  {
8344  this->handler.data = handler;
8345  }
8346 
8352  AllowedSubtags(uint32_t id, TextHandler handler) :
8353  id(id),
8354  type('T')
8355  {
8356  this->handler.text = handler;
8357  }
8358 
8364  AllowedSubtags(uint32_t id, BranchHandler handler) :
8365  id(id),
8366  type('C')
8367  {
8368  this->handler.call_handler = true;
8369  this->handler.u.branch = handler;
8370  }
8371 
8378  id(id),
8379  type('C')
8380  {
8381  this->handler.call_handler = false;
8382  this->handler.u.subtags = subtags;
8383  }
8384 
8385  uint32_t id;
8386  uint8_t type;
8387  union {
8390  struct {
8391  union {
8394  } u;
8396  };
8397  } handler;
8398 };
8399 
8400 static bool SkipUnknownInfo(ByteReader &buf, uint8_t type);
8401 static bool HandleNodes(ByteReader &buf, AllowedSubtags *tags);
8402 
8410 {
8411  uint8_t type = buf.ReadByte();
8412  while (type != 0) {
8413  uint32_t id = buf.ReadDWord();
8414  if (type != 'T' || id > _cur_parameter->max_value) {
8415  GrfMsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA'->param_num->'VALU' should have type 't' and the value/bit number as id");
8416  if (!SkipUnknownInfo(buf, type)) return false;
8417  type = buf.ReadByte();
8418  continue;
8419  }
8420 
8421  uint8_t langid = buf.ReadByte();
8422  std::string_view name_string = buf.ReadString();
8423 
8424  auto val_name = _cur_parameter->value_names.find(id);
8425  if (val_name != _cur_parameter->value_names.end()) {
8426  AddGRFTextToList(val_name->second, langid, _cur.grfconfig->ident.grfid, false, name_string);
8427  } else {
8428  GRFTextList list;
8429  AddGRFTextToList(list, langid, _cur.grfconfig->ident.grfid, false, name_string);
8430  _cur_parameter->value_names[id] = list;
8431  }
8432 
8433  type = buf.ReadByte();
8434  }
8435  return true;
8436 }
8437 
8447  AllowedSubtags()
8448 };
8449 
8457 {
8458  uint8_t type = buf.ReadByte();
8459  while (type != 0) {
8460  uint32_t id = buf.ReadDWord();
8461  if (type != 'C' || id >= _cur.grfconfig->num_valid_params) {
8462  GrfMsg(2, "StaticGRFInfo: all child nodes of 'INFO'->'PARA' should have type 'C' and their parameter number as id");
8463  if (!SkipUnknownInfo(buf, type)) return false;
8464  type = buf.ReadByte();
8465  continue;
8466  }
8467 
8468  if (id >= _cur.grfconfig->param_info.size()) {
8469  _cur.grfconfig->param_info.resize(id + 1);
8470  }
8471  if (!_cur.grfconfig->param_info[id].has_value()) {
8472  _cur.grfconfig->param_info[id] = GRFParameterInfo(id);
8473  }
8474  _cur_parameter = &_cur.grfconfig->param_info[id].value();
8475  /* Read all parameter-data and process each node. */
8476  if (!HandleNodes(buf, _tags_parameters)) return false;
8477  type = buf.ReadByte();
8478  }
8479  return true;
8480 }
8481 
8484  AllowedSubtags('NAME', ChangeGRFName),
8486  AllowedSubtags('URL_', ChangeGRFURL),
8493  AllowedSubtags()
8494 };
8495 
8498  AllowedSubtags('INFO', _tags_info),
8499  AllowedSubtags()
8500 };
8501 
8502 
8509 static bool SkipUnknownInfo(ByteReader &buf, uint8_t type)
8510 {
8511  /* type and id are already read */
8512  switch (type) {
8513  case 'C': {
8514  uint8_t new_type = buf.ReadByte();
8515  while (new_type != 0) {
8516  buf.ReadDWord(); // skip the id
8517  if (!SkipUnknownInfo(buf, new_type)) return false;
8518  new_type = buf.ReadByte();
8519  }
8520  break;
8521  }
8522 
8523  case 'T':
8524  buf.ReadByte(); // lang
8525  buf.ReadString(); // actual text
8526  break;
8527 
8528  case 'B': {
8529  uint16_t size = buf.ReadWord();
8530  buf.Skip(size);
8531  break;
8532  }
8533 
8534  default:
8535  return false;
8536  }
8537 
8538  return true;
8539 }
8540 
8549 static bool HandleNode(uint8_t type, uint32_t id, ByteReader &buf, AllowedSubtags subtags[])
8550 {
8551  uint i = 0;
8552  AllowedSubtags *tag;
8553  while ((tag = &subtags[i++])->type != 0) {
8554  if (tag->id != BSWAP32(id) || tag->type != type) continue;
8555  switch (type) {
8556  default: NOT_REACHED();
8557 
8558  case 'T': {
8559  uint8_t langid = buf.ReadByte();
8560  return tag->handler.text(langid, buf.ReadString());
8561  }
8562 
8563  case 'B': {
8564  size_t len = buf.ReadWord();
8565  if (buf.Remaining() < len) return false;
8566  return tag->handler.data(len, buf);
8567  }
8568 
8569  case 'C': {
8570  if (tag->handler.call_handler) {
8571  return tag->handler.u.branch(buf);
8572  }
8573  return HandleNodes(buf, tag->handler.u.subtags);
8574  }
8575  }
8576  }
8577  GrfMsg(2, "StaticGRFInfo: unknown type/id combination found, type={:c}, id={:x}", type, id);
8578  return SkipUnknownInfo(buf, type);
8579 }
8580 
8587 static bool HandleNodes(ByteReader &buf, AllowedSubtags subtags[])
8588 {
8589  uint8_t type = buf.ReadByte();
8590  while (type != 0) {
8591  uint32_t id = buf.ReadDWord();
8592  if (!HandleNode(type, id, buf, subtags)) return false;
8593  type = buf.ReadByte();
8594  }
8595  return true;
8596 }
8597 
8602 static void StaticGRFInfo(ByteReader &buf)
8603 {
8604  /* <14> <type> <id> <text/data...> */
8605  HandleNodes(buf, _tags_root);
8606 }
8607 
8612 static void GRFUnsafe(ByteReader &)
8613 {
8614  SetBit(_cur.grfconfig->flags, GCF_UNSAFE);
8615 
8616  /* Skip remainder of GRF */
8617  _cur.skip_sprites = -1;
8618 }
8619 
8620 
8623 {
8624  _ttdpatch_flags[0] = ((_settings_game.station.never_expire_airports ? 1U : 0U) << 0x0C) // keepsmallairport
8625  | (1U << 0x0D) // newairports
8626  | (1U << 0x0E) // largestations
8627  | ((_settings_game.construction.max_bridge_length > 16 ? 1U : 0U) << 0x0F) // longbridges
8628  | (0U << 0x10) // loadtime
8629  | (1U << 0x12) // presignals
8630  | (1U << 0x13) // extpresignals
8631  | ((_settings_game.vehicle.never_expire_vehicles ? 1U : 0U) << 0x16) // enginespersist
8632  | (1U << 0x1B) // multihead
8633  | (1U << 0x1D) // lowmemory
8634  | (1U << 0x1E); // generalfixes
8635 
8636  _ttdpatch_flags[1] = ((_settings_game.economy.station_noise_level ? 1U : 0U) << 0x07) // moreairports - based on units of noise
8637  | (1U << 0x08) // mammothtrains
8638  | (1U << 0x09) // trainrefit
8639  | (0U << 0x0B) // subsidiaries
8640  | ((_settings_game.order.gradual_loading ? 1U : 0U) << 0x0C) // gradualloading
8641  | (1U << 0x12) // unifiedmaglevmode - set bit 0 mode. Not revelant to OTTD
8642  | (1U << 0x13) // unifiedmaglevmode - set bit 1 mode
8643  | (1U << 0x14) // bridgespeedlimits
8644  | (1U << 0x16) // eternalgame
8645  | (1U << 0x17) // newtrains
8646  | (1U << 0x18) // newrvs
8647  | (1U << 0x19) // newships
8648  | (1U << 0x1A) // newplanes
8649  | ((_settings_game.construction.train_signal_side == 1 ? 1U : 0U) << 0x1B) // signalsontrafficside
8650  | ((_settings_game.vehicle.disable_elrails ? 0U : 1U) << 0x1C); // electrifiedrailway
8651 
8652  _ttdpatch_flags[2] = (1U << 0x01) // loadallgraphics - obsolote
8653  | (1U << 0x03) // semaphores
8654  | (1U << 0x0A) // newobjects
8655  | (0U << 0x0B) // enhancedgui
8656  | (0U << 0x0C) // newagerating
8657  | ((_settings_game.construction.build_on_slopes ? 1U : 0U) << 0x0D) // buildonslopes
8658  | (1U << 0x0E) // fullloadany
8659  | (1U << 0x0F) // planespeed
8660  | (0U << 0x10) // moreindustriesperclimate - obsolete
8661  | (0U << 0x11) // moretoylandfeatures
8662  | (1U << 0x12) // newstations
8663  | (1U << 0x13) // tracktypecostdiff
8664  | (1U << 0x14) // manualconvert
8665  | ((_settings_game.construction.build_on_slopes ? 1U : 0U) << 0x15) // buildoncoasts
8666  | (1U << 0x16) // canals
8667  | (1U << 0x17) // newstartyear
8668  | ((_settings_game.vehicle.freight_trains > 1 ? 1U : 0U) << 0x18) // freighttrains
8669  | (1U << 0x19) // newhouses
8670  | (1U << 0x1A) // newbridges
8671  | (1U << 0x1B) // newtownnames
8672  | (1U << 0x1C) // moreanimation
8673  | ((_settings_game.vehicle.wagon_speed_limits ? 1U : 0U) << 0x1D) // wagonspeedlimits
8674  | (1U << 0x1E) // newshistory
8675  | (0U << 0x1F); // custombridgeheads
8676 
8677  _ttdpatch_flags[3] = (0U << 0x00) // newcargodistribution
8678  | (1U << 0x01) // windowsnap
8679  | ((_settings_game.economy.allow_town_roads || _generating_world ? 0U : 1U) << 0x02) // townbuildnoroad
8680  | (1U << 0x03) // pathbasedsignalling
8681  | (0U << 0x04) // aichoosechance
8682  | (1U << 0x05) // resolutionwidth
8683  | (1U << 0x06) // resolutionheight
8684  | (1U << 0x07) // newindustries
8685  | ((_settings_game.order.improved_load ? 1U : 0U) << 0x08) // fifoloading
8686  | (0U << 0x09) // townroadbranchprob
8687  | (0U << 0x0A) // tempsnowline
8688  | (1U << 0x0B) // newcargo
8689  | (1U << 0x0C) // enhancemultiplayer
8690  | (1U << 0x0D) // onewayroads
8691  | (1U << 0x0E) // irregularstations
8692  | (1U << 0x0F) // statistics
8693  | (1U << 0x10) // newsounds
8694  | (1U << 0x11) // autoreplace
8695  | (1U << 0x12) // autoslope
8696  | (0U << 0x13) // followvehicle
8697  | (1U << 0x14) // trams
8698  | (0U << 0x15) // enhancetunnels
8699  | (1U << 0x16) // shortrvs
8700  | (1U << 0x17) // articulatedrvs
8701  | ((_settings_game.vehicle.dynamic_engines ? 1U : 0U) << 0x18) // dynamic engines
8702  | (1U << 0x1E) // variablerunningcosts
8703  | (1U << 0x1F); // any switch is on
8704 
8705  _ttdpatch_flags[4] = (1U << 0x00) // larger persistent storage
8706  | ((_settings_game.economy.inflation ? 1U : 0U) << 0x01) // inflation is on
8707  | (1U << 0x02); // extended string range
8708 }
8709 
8711 static void ResetCustomStations()
8712 {
8713  for (GRFFile * const file : _grf_files) {
8714  file->stations.clear();
8715  }
8716 }
8717 
8719 static void ResetCustomHouses()
8720 {
8721  for (GRFFile * const file : _grf_files) {
8722  file->housespec.clear();
8723  }
8724 }
8725 
8727 static void ResetCustomAirports()
8728 {
8729  for (GRFFile * const file : _grf_files) {
8730  file->airportspec.clear();
8731  file->airtspec.clear();
8732  }
8733 }
8734 
8737 {
8738  for (GRFFile * const file : _grf_files) {
8739  file->industryspec.clear();
8740  file->indtspec.clear();
8741  }
8742 }
8743 
8745 static void ResetCustomObjects()
8746 {
8747  for (GRFFile * const file : _grf_files) {
8748  file->objectspec.clear();
8749  }
8750 }
8751 
8752 static void ResetCustomRoadStops()
8753 {
8754  for (auto file : _grf_files) {
8755  file->roadstops.clear();
8756  }
8757 }
8758 
8760 static void ResetNewGRF()
8761 {
8762  for (GRFFile * const file : _grf_files) {
8763  delete file;
8764  }
8765 
8766  _grf_files.clear();
8767  _cur.grffile = nullptr;
8768 }
8769 
8771 static void ResetNewGRFErrors()
8772 {
8773  for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
8774  c->error.reset();
8775  }
8776 }
8777 
8782 {
8783  CleanUpStrings();
8784  CleanUpGRFTownNames();
8785 
8786  /* Copy/reset original engine info data */
8787  SetupEngines();
8788 
8789  /* Copy/reset original bridge info data */
8790  ResetBridges();
8791 
8792  /* Reset rail type information */
8793  ResetRailTypes();
8794 
8795  /* Copy/reset original road type info data */
8796  ResetRoadTypes();
8797 
8798  /* Allocate temporary refit/cargo class data */
8799  _gted.resize(Engine::GetPoolSize());
8800 
8801  /* Fill rail type label temporary data for default trains */
8802  for (const Engine *e : Engine::IterateType(VEH_TRAIN)) {
8803  _gted[e->index].railtypelabel = GetRailTypeInfo(e->u.rail.railtype)->label;
8804  }
8805 
8806  /* Reset GRM reservations */
8807  memset(&_grm_engines, 0, sizeof(_grm_engines));
8808  memset(&_grm_cargoes, 0, sizeof(_grm_cargoes));
8809 
8810  /* Reset generic feature callback lists */
8812 
8813  /* Reset price base data */
8815 
8816  /* Reset the curencies array */
8817  ResetCurrencies();
8818 
8819  /* Reset the house array */
8821  ResetHouses();
8822 
8823  /* Reset the industries structures*/
8825  ResetIndustries();
8826 
8827  /* Reset the objects. */
8830  ResetObjects();
8831 
8832  /* Reset station classes */
8835 
8836  /* Reset airport-related structures */
8841 
8842  /* Reset road stop classes */
8844  ResetCustomRoadStops();
8845 
8846  /* Reset canal sprite groups and flags */
8847  memset(_water_feature, 0, sizeof(_water_feature));
8848 
8849  /* Reset the snowline table. */
8850  ClearSnowLine();
8851 
8852  /* Reset NewGRF files */
8853  ResetNewGRF();
8854 
8855  /* Reset NewGRF errors. */
8857 
8858  /* Set up the default cargo types */
8860 
8861  /* Reset misc GRF features and train list display variables */
8862  _misc_grf_features = 0;
8863 
8865  _loaded_newgrf_features.used_liveries = 1 << LS_DEFAULT;
8868 
8869  /* Clear all GRF overrides */
8870  _grf_id_overrides.clear();
8871 
8872  InitializeSoundPool();
8873  _spritegroup_pool.CleanPool();
8874 }
8875 
8880 {
8881  /* Reset override managers */
8882  _engine_mngr.ResetToDefaultMapping();
8883  _house_mngr.ResetMapping();
8884  _industry_mngr.ResetMapping();
8885  _industile_mngr.ResetMapping();
8886  _airport_mngr.ResetMapping();
8887  _airporttile_mngr.ResetMapping();
8888 }
8889 
8895 {
8896  _cur.grffile->cargo_map.fill(UINT8_MAX);
8897 
8898  for (const CargoSpec *cs : CargoSpec::Iterate()) {
8899  if (!cs->IsValid()) continue;
8900 
8901  if (_cur.grffile->cargo_list.empty()) {
8902  /* Default translation table, so just a straight mapping to bitnum */
8903  _cur.grffile->cargo_map[cs->Index()] = cs->bitnum;
8904  } else {
8905  /* Check the translation table for this cargo's label */
8906  int idx = find_index(_cur.grffile->cargo_list, {cs->label});
8907  if (idx >= 0) _cur.grffile->cargo_map[cs->Index()] = idx;
8908  }
8909  }
8910 }
8911 
8916 static void InitNewGRFFile(const GRFConfig *config)
8917 {
8918  GRFFile *newfile = GetFileByFilename(config->filename);
8919  if (newfile != nullptr) {
8920  /* We already loaded it once. */
8921  _cur.grffile = newfile;
8922  return;
8923  }
8924 
8925  newfile = new GRFFile(config);
8926  _grf_files.push_back(_cur.grffile = newfile);
8927 }
8928 
8934 {
8935  this->filename = config->filename;
8936  this->grfid = config->ident.grfid;
8937 
8938  /* Initialise local settings to defaults */
8939  this->traininfo_vehicle_pitch = 0;
8940  this->traininfo_vehicle_width = TRAININFO_DEFAULT_VEHICLE_WIDTH;
8941 
8942  /* Mark price_base_multipliers as 'not set' */
8943  for (Price i = PR_BEGIN; i < PR_END; i++) {
8944  this->price_base_multipliers[i] = INVALID_PRICE_MODIFIER;
8945  }
8946 
8947  /* Initialise rail type map with default rail types */
8948  std::fill(std::begin(this->railtype_map), std::end(this->railtype_map), INVALID_RAILTYPE);
8949  this->railtype_map[0] = RAILTYPE_RAIL;
8950  this->railtype_map[1] = RAILTYPE_ELECTRIC;
8951  this->railtype_map[2] = RAILTYPE_MONO;
8952  this->railtype_map[3] = RAILTYPE_MAGLEV;
8953 
8954  /* Initialise road type map with default road types */
8955  std::fill(std::begin(this->roadtype_map), std::end(this->roadtype_map), INVALID_ROADTYPE);
8956  this->roadtype_map[0] = ROADTYPE_ROAD;
8957 
8958  /* Initialise tram type map with default tram types */
8959  std::fill(std::begin(this->tramtype_map), std::end(this->tramtype_map), INVALID_ROADTYPE);
8960  this->tramtype_map[0] = ROADTYPE_TRAM;
8961 
8962  /* Copy the initial parameter list
8963  * 'Uninitialised' parameters are zeroed as that is their default value when dynamically creating them. */
8964  this->param = config->param;
8965  this->param_end = config->num_params;
8966 }
8967 
8973 static CargoLabel GetActiveCargoLabel(const std::initializer_list<CargoLabel> &labels)
8974 {
8975  for (const CargoLabel &label : labels) {
8976  CargoID cid = GetCargoIDByLabel(label);
8977  if (cid != INVALID_CARGO) return label;
8978  }
8979  return CT_INVALID;
8980 }
8981 
8987 static CargoLabel GetActiveCargoLabel(const std::variant<CargoLabel, MixedCargoType> &label)
8988 {
8989  if (std::holds_alternative<CargoLabel>(label)) return std::get<CargoLabel>(label);
8990  if (std::holds_alternative<MixedCargoType>(label)) {
8991  switch (std::get<MixedCargoType>(label)) {
8992  case MCT_LIVESTOCK_FRUIT: return GetActiveCargoLabel({CT_LIVESTOCK, CT_FRUIT});
8993  case MCT_GRAIN_WHEAT_MAIZE: return GetActiveCargoLabel({CT_GRAIN, CT_WHEAT, CT_MAIZE});
8994  case MCT_VALUABLES_GOLD_DIAMONDS: return GetActiveCargoLabel({CT_VALUABLES, CT_GOLD, CT_DIAMONDS});
8995  default: NOT_REACHED();
8996  }
8997  }
8998  NOT_REACHED();
8999 }
9000 
9004 static void CalculateRefitMasks()
9005 {
9006  CargoTypes original_known_cargoes = 0;
9007  for (CargoID cid = 0; cid != NUM_CARGO; ++cid) {
9008  if (IsDefaultCargo(cid)) SetBit(original_known_cargoes, cid);
9009  }
9010 
9011  for (Engine *e : Engine::Iterate()) {
9012  EngineID engine = e->index;
9013  EngineInfo *ei = &e->info;
9014  bool only_defaultcargo;
9015 
9016  /* Apply default cargo translation map if cargo type hasn't been set, either explicitly or by aircraft cargo handling. */
9017  if (!IsValidCargoID(e->info.cargo_type)) {
9018  e->info.cargo_type = GetCargoIDByLabel(GetActiveCargoLabel(e->info.cargo_label));
9019  }
9020 
9021  /* If the NewGRF did not set any cargo properties, we apply default values. */
9022  if (_gted[engine].defaultcargo_grf == nullptr) {
9023  /* If the vehicle has any capacity, apply the default refit masks */
9024  if (e->type != VEH_TRAIN || e->u.rail.capacity != 0) {
9025  static constexpr uint8_t T = 1 << LT_TEMPERATE;
9026  static constexpr uint8_t A = 1 << LT_ARCTIC;
9027  static constexpr uint8_t S = 1 << LT_TROPIC;
9028  static constexpr uint8_t Y = 1 << LT_TOYLAND;
9029  static const struct DefaultRefitMasks {
9030  uint8_t climate;
9031  CargoLabel cargo_label;
9032  CargoClasses cargo_allowed;
9033  CargoClasses cargo_disallowed;
9034  } _default_refit_masks[] = {
9035  {T | A | S | Y, CT_PASSENGERS, CC_PASSENGERS, 0},
9036  {T | A | S , CT_MAIL, CC_MAIL, 0},
9037  {T | A | S , CT_VALUABLES, CC_ARMOURED, CC_LIQUID},
9038  { Y, CT_MAIL, CC_MAIL | CC_ARMOURED, CC_LIQUID},
9039  {T | A , CT_COAL, CC_BULK, 0},
9040  { S , CT_COPPER_ORE, CC_BULK, 0},
9041  { Y, CT_SUGAR, CC_BULK, 0},
9042  {T | A | S , CT_OIL, CC_LIQUID, 0},
9043  { Y, CT_COLA, CC_LIQUID, 0},
9044  {T , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
9045  { A | S , CT_GOODS, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS | CC_REFRIGERATED},
9046  { A | S , CT_FOOD, CC_REFRIGERATED, 0},
9047  { Y, CT_CANDY, CC_PIECE_GOODS | CC_EXPRESS, CC_LIQUID | CC_PASSENGERS},
9048  };
9049 
9050  if (e->type == VEH_AIRCRAFT) {
9051  /* Aircraft default to "light" cargoes */
9052  _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS;
9053  _gted[engine].cargo_disallowed = CC_LIQUID;
9054  } else if (e->type == VEH_SHIP) {
9055  CargoLabel label = GetActiveCargoLabel(ei->cargo_label);
9056  switch (label.base()) {
9057  case CT_PASSENGERS.base():
9058  /* Ferries */
9059  _gted[engine].cargo_allowed = CC_PASSENGERS;
9060  _gted[engine].cargo_disallowed = 0;
9061  break;
9062  case CT_OIL.base():
9063  /* Tankers */
9064  _gted[engine].cargo_allowed = CC_LIQUID;
9065  _gted[engine].cargo_disallowed = 0;
9066  break;
9067  default:
9068  /* Cargo ships */
9069  if (_settings_game.game_creation.landscape == LT_TOYLAND) {
9070  /* No tanker in toyland :( */
9071  _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
9072  _gted[engine].cargo_disallowed = CC_PASSENGERS;
9073  } else {
9074  _gted[engine].cargo_allowed = CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS;
9075  _gted[engine].cargo_disallowed = CC_LIQUID | CC_PASSENGERS;
9076  }
9077  break;
9078  }
9079  e->u.ship.old_refittable = true;
9080  } else if (e->type == VEH_TRAIN && e->u.rail.railveh_type != RAILVEH_WAGON) {
9081  /* Train engines default to all cargoes, so you can build single-cargo consists with fast engines.
9082  * Trains loading multiple cargoes may start stations accepting unwanted cargoes. */
9083  _gted[engine].cargo_allowed = CC_PASSENGERS | CC_MAIL | CC_ARMOURED | CC_EXPRESS | CC_BULK | CC_PIECE_GOODS | CC_LIQUID;
9084  _gted[engine].cargo_disallowed = 0;
9085  } else {
9086  /* Train wagons and road vehicles are classified by their default cargo type */
9087  CargoLabel label = GetActiveCargoLabel(ei->cargo_label);
9088  for (const auto &drm : _default_refit_masks) {
9089  if (!HasBit(drm.climate, _settings_game.game_creation.landscape)) continue;
9090  if (drm.cargo_label != label) continue;
9091 
9092  _gted[engine].cargo_allowed = drm.cargo_allowed;
9093  _gted[engine].cargo_disallowed = drm.cargo_disallowed;
9094  break;
9095  }
9096 
9097  /* All original cargoes have specialised vehicles, so exclude them */
9098  _gted[engine].ctt_exclude_mask = original_known_cargoes;
9099  }
9100  }
9101  _gted[engine].UpdateRefittability(_gted[engine].cargo_allowed != 0);
9102 
9103  if (IsValidCargoID(ei->cargo_type)) ClrBit(_gted[engine].ctt_exclude_mask, ei->cargo_type);
9104  }
9105 
9106  /* Compute refittability */
9107  {
9108  CargoTypes mask = 0;
9109  CargoTypes not_mask = 0;
9110  CargoTypes xor_mask = ei->refit_mask;
9111 
9112  /* If the original masks set by the grf are zero, the vehicle shall only carry the default cargo.
9113  * Note: After applying the translations, the vehicle may end up carrying no defined cargo. It becomes unavailable in that case. */
9114  only_defaultcargo = _gted[engine].refittability != GRFTempEngineData::NONEMPTY;
9115 
9116  if (_gted[engine].cargo_allowed != 0) {
9117  /* Build up the list of cargo types from the set cargo classes. */
9118  for (const CargoSpec *cs : CargoSpec::Iterate()) {
9119  if (_gted[engine].cargo_allowed & cs->classes) SetBit(mask, cs->Index());
9120  if (_gted[engine].cargo_disallowed & cs->classes) SetBit(not_mask, cs->Index());
9121  }
9122  }
9123 
9124  ei->refit_mask = ((mask & ~not_mask) ^ xor_mask) & _cargo_mask;
9125 
9126  /* Apply explicit refit includes/excludes. */
9127  ei->refit_mask |= _gted[engine].ctt_include_mask;
9128  ei->refit_mask &= ~_gted[engine].ctt_exclude_mask;
9129  }
9130 
9131  /* Clear invalid cargoslots (from default vehicles or pre-NewCargo GRFs) */
9132  if (IsValidCargoID(ei->cargo_type) && !HasBit(_cargo_mask, ei->cargo_type)) ei->cargo_type = INVALID_CARGO;
9133 
9134  /* Ensure that the vehicle is either not refittable, or that the default cargo is one of the refittable cargoes.
9135  * Note: Vehicles refittable to no cargo are handle differently to vehicle refittable to a single cargo. The latter might have subtypes. */
9136  if (!only_defaultcargo && (e->type != VEH_SHIP || e->u.ship.old_refittable) && IsValidCargoID(ei->cargo_type) && !HasBit(ei->refit_mask, ei->cargo_type)) {
9137  ei->cargo_type = INVALID_CARGO;
9138  }
9139 
9140  /* Check if this engine's cargo type is valid. If not, set to the first refittable
9141  * cargo type. Finally disable the vehicle, if there is still no cargo. */
9142  if (!IsValidCargoID(ei->cargo_type) && ei->refit_mask != 0) {
9143  /* Figure out which CTT to use for the default cargo, if it is 'first refittable'. */
9144  const GRFFile *file = _gted[engine].defaultcargo_grf;
9145  if (file == nullptr) file = e->GetGRF();
9146  if (file != nullptr && file->grf_version >= 8 && !file->cargo_list.empty()) {
9147  /* Use first refittable cargo from cargo translation table */
9148  uint8_t best_local_slot = UINT8_MAX;
9149  for (CargoID cargo_type : SetCargoBitIterator(ei->refit_mask)) {
9150  uint8_t local_slot = file->cargo_map[cargo_type];
9151  if (local_slot < best_local_slot) {
9152  best_local_slot = local_slot;
9153  ei->cargo_type = cargo_type;
9154  }
9155  }
9156  }
9157 
9158  if (!IsValidCargoID(ei->cargo_type)) {
9159  /* Use first refittable cargo slot */
9160  ei->cargo_type = (CargoID)FindFirstBit(ei->refit_mask);
9161  }
9162  }
9163  if (!IsValidCargoID(ei->cargo_type) && e->type == VEH_TRAIN && e->u.rail.railveh_type != RAILVEH_WAGON && e->u.rail.capacity == 0) {
9164  /* For train engines which do not carry cargo it does not matter if their cargo type is invalid.
9165  * Fallback to the first available instead, if the cargo type has not been changed (as indicated by
9166  * cargo_label not being CT_INVALID). */
9167  if (GetActiveCargoLabel(ei->cargo_label) != CT_INVALID) {
9168  ei->cargo_type = static_cast<CargoID>(FindFirstBit(_standard_cargo_mask));
9169  }
9170  }
9171  if (!IsValidCargoID(ei->cargo_type)) ei->climates = 0;
9172 
9173  /* Clear refit_mask for not refittable ships */
9174  if (e->type == VEH_SHIP && !e->u.ship.old_refittable) {
9175  ei->refit_mask = 0;
9176  }
9177  }
9178 }
9179 
9181 static void FinaliseCanals()
9182 {
9183  for (uint i = 0; i < CF_END; i++) {
9184  if (_water_feature[i].grffile != nullptr) {
9187  }
9188  }
9189 }
9190 
9192 static void FinaliseEngineArray()
9193 {
9194  for (Engine *e : Engine::Iterate()) {
9195  if (e->GetGRF() == nullptr) {
9196  const EngineIDMapping &eid = _engine_mngr[e->index];
9197  if (eid.grfid != INVALID_GRFID || eid.internal_id != eid.substitute_id) {
9198  e->info.string_id = STR_NEWGRF_INVALID_ENGINE;
9199  }
9200  }
9201 
9202  /* Do final mapping on variant engine ID. */
9203  if (e->info.variant_id != INVALID_ENGINE) {
9204  e->info.variant_id = GetNewEngineID(e->grf_prop.grffile, e->type, e->info.variant_id);
9205  }
9206 
9207  if (!HasBit(e->info.climates, _settings_game.game_creation.landscape)) continue;
9208 
9209  /* Skip wagons, there livery is defined via the engine */
9210  if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
9213  /* Note: For ships and roadvehicles we assume that they cannot be refitted between passenger and freight */
9214 
9215  if (e->type == VEH_TRAIN) {
9216  SetBit(_loaded_newgrf_features.used_liveries, LS_FREIGHT_WAGON);
9217  switch (ls) {
9218  case LS_STEAM:
9219  case LS_DIESEL:
9220  case LS_ELECTRIC:
9221  case LS_MONORAIL:
9222  case LS_MAGLEV:
9223  SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_STEAM + ls - LS_STEAM);
9224  break;
9225 
9226  case LS_DMU:
9227  case LS_EMU:
9228  SetBit(_loaded_newgrf_features.used_liveries, LS_PASSENGER_WAGON_DIESEL + ls - LS_DMU);
9229  break;
9230 
9231  default: NOT_REACHED();
9232  }
9233  }
9234  }
9235  }
9236 
9237  /* Check engine variants don't point back on themselves (either directly or via a loop) then set appropriate flags
9238  * on variant engine. This is performed separately as all variant engines need to have been resolved. */
9239  for (Engine *e : Engine::Iterate()) {
9240  EngineID parent = e->info.variant_id;
9241  while (parent != INVALID_ENGINE) {
9242  parent = Engine::Get(parent)->info.variant_id;
9243  if (parent != e->index) continue;
9244 
9245  /* Engine looped back on itself, so clear the variant. */
9246  e->info.variant_id = INVALID_ENGINE;
9247 
9248  GrfMsg(1, "FinaliseEngineArray: Variant of engine {:x} in '{}' loops back on itself", _engine_mngr[e->index].internal_id, e->GetGRF()->filename);
9249  break;
9250  }
9251 
9252  if (e->info.variant_id != INVALID_ENGINE) {
9254  }
9255  }
9256 }
9257 
9260 {
9261  for (CargoSpec &cs : CargoSpec::array) {
9262  if (cs.town_production_effect == INVALID_TPE) {
9263  /* Set default town production effect by cargo label. */
9264  switch (cs.label.base()) {
9265  case CT_PASSENGERS.base(): cs.town_production_effect = TPE_PASSENGERS; break;
9266  case CT_MAIL.base(): cs.town_production_effect = TPE_MAIL; break;
9267  default: cs.town_production_effect = TPE_NONE; break;
9268  }
9269  }
9270  if (!cs.IsValid()) {
9271  cs.name = cs.name_single = cs.units_volume = STR_NEWGRF_INVALID_CARGO;
9272  cs.quantifier = STR_NEWGRF_INVALID_CARGO_QUANTITY;
9273  cs.abbrev = STR_NEWGRF_INVALID_CARGO_ABBREV;
9274  }
9275  }
9276 }
9277 
9289 static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const std::string &filename)
9290 {
9291  if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 &&
9292  (next1 == nullptr || !next1->enabled || (next1->building_flags & BUILDING_HAS_1_TILE) != 0)) ||
9293  ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 &&
9294  (next2 == nullptr || !next2->enabled || (next2->building_flags & BUILDING_HAS_1_TILE) != 0 ||
9295  next3 == nullptr || !next3->enabled || (next3->building_flags & BUILDING_HAS_1_TILE) != 0))) {
9296  hs->enabled = false;
9297  if (!filename.empty()) Debug(grf, 1, "FinaliseHouseArray: {} defines house {} as multitile, but no suitable tiles follow. Disabling house.", filename, hs->grf_prop.local_id);
9298  return false;
9299  }
9300 
9301  /* Some places sum population by only counting north tiles. Other places use all tiles causing desyncs.
9302  * As the newgrf specs define population to be zero for non-north tiles, we just disable the offending house.
9303  * If you want to allow non-zero populations somewhen, make sure to sum the population of all tiles in all places. */
9304  if (((hs->building_flags & BUILDING_HAS_2_TILES) != 0 && next1->population != 0) ||
9305  ((hs->building_flags & BUILDING_HAS_4_TILES) != 0 && (next2->population != 0 || next3->population != 0))) {
9306  hs->enabled = false;
9307  if (!filename.empty()) Debug(grf, 1, "FinaliseHouseArray: {} defines multitile house {} with non-zero population on additional tiles. Disabling house.", filename, hs->grf_prop.local_id);
9308  return false;
9309  }
9310 
9311  /* Substitute type is also used for override, and having an override with a different size causes crashes.
9312  * This check should only be done for NewGRF houses because grf_prop.subst_id is not set for original houses.*/
9313  if (!filename.empty() && (hs->building_flags & BUILDING_HAS_1_TILE) != (HouseSpec::Get(hs->grf_prop.subst_id)->building_flags & BUILDING_HAS_1_TILE)) {
9314  hs->enabled = false;
9315  Debug(grf, 1, "FinaliseHouseArray: {} defines house {} with different house size then it's substitute type. Disabling house.", filename, hs->grf_prop.local_id);
9316  return false;
9317  }
9318 
9319  /* Make sure that additional parts of multitile houses are not available. */
9320  if ((hs->building_flags & BUILDING_HAS_1_TILE) == 0 && (hs->building_availability & HZ_ZONALL) != 0 && (hs->building_availability & HZ_CLIMALL) != 0) {
9321  hs->enabled = false;
9322  if (!filename.empty()) Debug(grf, 1, "FinaliseHouseArray: {} defines house {} without a size but marked it as available. Disabling house.", filename, hs->grf_prop.local_id);
9323  return false;
9324  }
9325 
9326  return true;
9327 }
9328 
9335 static void EnsureEarlyHouse(HouseZones bitmask)
9336 {
9338 
9339  for (const auto &hs : HouseSpec::Specs()) {
9340  if (!hs.enabled) continue;
9341  if ((hs.building_availability & bitmask) != bitmask) continue;
9342  if (hs.min_year < min_year) min_year = hs.min_year;
9343  }
9344 
9345  if (min_year == 0) return;
9346 
9347  for (auto &hs : HouseSpec::Specs()) {
9348  if (!hs.enabled) continue;
9349  if ((hs.building_availability & bitmask) != bitmask) continue;
9350  if (hs.min_year == min_year) hs.min_year = 0;
9351  }
9352 }
9353 
9360 static void FinaliseHouseArray()
9361 {
9362  /* If there are no houses with start dates before 1930, then all houses
9363  * with start dates of 1930 have them reset to 0. This is in order to be
9364  * compatible with TTDPatch, where if no houses have start dates before
9365  * 1930 and the date is before 1930, the game pretends that this is 1930.
9366  * If there have been any houses defined with start dates before 1930 then
9367  * the dates are left alone.
9368  * On the other hand, why 1930? Just 'fix' the houses with the lowest
9369  * minimum introduction date to 0.
9370  */
9371  for (GRFFile * const file : _grf_files) {
9372  if (file->housespec.empty()) continue;
9373 
9374  size_t num_houses = file->housespec.size();
9375  for (size_t i = 0; i < num_houses; i++) {
9376  HouseSpec *hs = file->housespec[i].get();
9377 
9378  if (hs == nullptr) continue;
9379 
9380  const HouseSpec *next1 = (i + 1 < num_houses ? file->housespec[i + 1].get() : nullptr);
9381  const HouseSpec *next2 = (i + 2 < num_houses ? file->housespec[i + 2].get() : nullptr);
9382  const HouseSpec *next3 = (i + 3 < num_houses ? file->housespec[i + 3].get() : nullptr);
9383 
9384  if (!IsHouseSpecValid(hs, next1, next2, next3, file->filename)) continue;
9385 
9386  _house_mngr.SetEntitySpec(hs);
9387  }
9388  }
9389 
9390  for (size_t i = 0; i < HouseSpec::Specs().size(); i++) {
9391  HouseSpec *hs = HouseSpec::Get(i);
9392  const HouseSpec *next1 = (i + 1 < NUM_HOUSES ? HouseSpec::Get(i + 1) : nullptr);
9393  const HouseSpec *next2 = (i + 2 < NUM_HOUSES ? HouseSpec::Get(i + 2) : nullptr);
9394  const HouseSpec *next3 = (i + 3 < NUM_HOUSES ? HouseSpec::Get(i + 3) : nullptr);
9395 
9396  /* We need to check all houses again to we are sure that multitile houses
9397  * did get consecutive IDs and none of the parts are missing. */
9398  if (!IsHouseSpecValid(hs, next1, next2, next3, std::string{})) {
9399  /* GetHouseNorthPart checks 3 houses that are directly before
9400  * it in the house pool. If any of those houses have multi-tile
9401  * flags set it assumes it's part of a multitile house. Since
9402  * we can have invalid houses in the pool marked as disabled, we
9403  * don't want to have them influencing valid tiles. As such set
9404  * building_flags to zero here to make sure any house following
9405  * this one in the pool is properly handled as 1x1 house. */
9406  hs->building_flags = TILE_NO_FLAG;
9407  }
9408 
9409  /* Apply default cargo translation map for unset cargo slots */
9410  for (uint i = 0; i < lengthof(hs->accepts_cargo); ++i) {
9411  if (!IsValidCargoID(hs->accepts_cargo[i])) hs->accepts_cargo[i] = GetCargoIDByLabel(hs->accepts_cargo_label[i]);
9412  /* Disable acceptance if cargo type is invalid. */
9413  if (!IsValidCargoID(hs->accepts_cargo[i])) hs->cargo_acceptance[i] = 0;
9414  }
9415  }
9416 
9417  HouseZones climate_mask = (HouseZones)(1 << (_settings_game.game_creation.landscape + 12));
9418  EnsureEarlyHouse(HZ_ZON1 | climate_mask);
9419  EnsureEarlyHouse(HZ_ZON2 | climate_mask);
9420  EnsureEarlyHouse(HZ_ZON3 | climate_mask);
9421  EnsureEarlyHouse(HZ_ZON4 | climate_mask);
9422  EnsureEarlyHouse(HZ_ZON5 | climate_mask);
9423 
9424  if (_settings_game.game_creation.landscape == LT_ARCTIC) {
9430  }
9431 }
9432 
9439 {
9440  for (GRFFile * const file : _grf_files) {
9441  for (const auto &indsp : file->industryspec) {
9442  if (indsp == nullptr || !indsp->enabled) continue;
9443 
9444  StringID strid;
9445  /* process the conversion of text at the end, so to be sure everything will be fine
9446  * and available. Check if it does not return undefind marker, which is a very good sign of a
9447  * substitute industry who has not changed the string been examined, thus using it as such */
9448  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->name);
9449  if (strid != STR_UNDEFINED) indsp->name = strid;
9450 
9451  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->closure_text);
9452  if (strid != STR_UNDEFINED) indsp->closure_text = strid;
9453 
9454  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_up_text);
9455  if (strid != STR_UNDEFINED) indsp->production_up_text = strid;
9456 
9457  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->production_down_text);
9458  if (strid != STR_UNDEFINED) indsp->production_down_text = strid;
9459 
9460  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->new_industry_text);
9461  if (strid != STR_UNDEFINED) indsp->new_industry_text = strid;
9462 
9463  if (indsp->station_name != STR_NULL) {
9464  /* STR_NULL (0) can be set by grf. It has a meaning regarding assignation of the
9465  * station's name. Don't want to lose the value, therefore, do not process. */
9466  strid = GetGRFStringID(indsp->grf_prop.grffile->grfid, indsp->station_name);
9467  if (strid != STR_UNDEFINED) indsp->station_name = strid;
9468  }
9469 
9470  _industry_mngr.SetEntitySpec(indsp.get());
9471  }
9472 
9473  for (const auto &indtsp : file->indtspec) {
9474  if (indtsp != nullptr) {
9475  _industile_mngr.SetEntitySpec(indtsp.get());
9476  }
9477  }
9478  }
9479 
9480  for (auto &indsp : _industry_specs) {
9481  if (indsp.enabled && indsp.grf_prop.grffile != nullptr) {
9482  for (auto &conflicting : indsp.conflicting) {
9483  conflicting = MapNewGRFIndustryType(conflicting, indsp.grf_prop.grffile->grfid);
9484  }
9485  }
9486  if (!indsp.enabled) {
9487  indsp.name = STR_NEWGRF_INVALID_INDUSTRYTYPE;
9488  }
9489 
9490  /* Apply default cargo translation map for unset cargo slots */
9491  for (size_t i = 0; i < std::size(indsp.produced_cargo); ++i) {
9492  if (!IsValidCargoID(indsp.produced_cargo[i])) indsp.produced_cargo[i] = GetCargoIDByLabel(GetActiveCargoLabel(indsp.produced_cargo_label[i]));
9493  }
9494  for (size_t i = 0; i < std::size(indsp.accepts_cargo); ++i) {
9495  if (!IsValidCargoID(indsp.accepts_cargo[i])) indsp.accepts_cargo[i] = GetCargoIDByLabel(GetActiveCargoLabel(indsp.accepts_cargo_label[i]));
9496  }
9497  }
9498 
9499  for (auto &indtsp : _industry_tile_specs) {
9500  /* Apply default cargo translation map for unset cargo slots */
9501  for (size_t i = 0; i < indtsp.accepts_cargo.size(); ++i) {
9502  if (!IsValidCargoID(indtsp.accepts_cargo[i])) indtsp.accepts_cargo[i] = GetCargoIDByLabel(GetActiveCargoLabel(indtsp.accepts_cargo_label[i]));
9503  }
9504  }
9505 }
9506 
9513 {
9514  for (GRFFile * const file : _grf_files) {
9515  for (auto &objectspec : file->objectspec) {
9516  if (objectspec != nullptr && objectspec->grf_prop.grffile != nullptr && objectspec->IsEnabled()) {
9517  _object_mngr.SetEntitySpec(objectspec.get());
9518  }
9519  }
9520  }
9521 
9523 }
9524 
9531 {
9532  for (GRFFile * const file : _grf_files) {
9533  for (auto &as : file->airportspec) {
9534  if (as != nullptr && as->enabled) {
9535  _airport_mngr.SetEntitySpec(as.get());
9536  }
9537  }
9538 
9539  for (auto &ats : file->airtspec) {
9540  if (ats != nullptr && ats->enabled) {
9541  _airporttile_mngr.SetEntitySpec(ats.get());
9542  }
9543  }
9544  }
9545 }
9546 
9547 /* Here we perform initial decoding of some special sprites (as are they
9548  * described at http://www.ttdpatch.net/src/newgrf.txt, but this is only a very
9549  * partial implementation yet).
9550  * XXX: We consider GRF files trusted. It would be trivial to exploit OTTD by
9551  * a crafted invalid GRF file. We should tell that to the user somehow, or
9552  * better make this more robust in the future. */
9553 static void DecodeSpecialSprite(uint8_t *buf, uint num, GrfLoadingStage stage)
9554 {
9555  /* XXX: There is a difference between staged loading in TTDPatch and
9556  * here. In TTDPatch, for some reason actions 1 and 2 are carried out
9557  * during stage 1, whilst action 3 is carried out during stage 2 (to
9558  * "resolve" cargo IDs... wtf). This is a little problem, because cargo
9559  * IDs are valid only within a given set (action 1) block, and may be
9560  * overwritten after action 3 associates them. But overwriting happens
9561  * in an earlier stage than associating, so... We just process actions
9562  * 1 and 2 in stage 2 now, let's hope that won't get us into problems.
9563  * --pasky
9564  * We need a pre-stage to set up GOTO labels of Action 0x10 because the grf
9565  * is not in memory and scanning the file every time would be too expensive.
9566  * In other stages we skip action 0x10 since it's already dealt with. */
9567  static const SpecialSpriteHandler handlers[][GLS_END] = {
9568  /* 0x00 */ { nullptr, SafeChangeInfo, nullptr, nullptr, ReserveChangeInfo, FeatureChangeInfo, },
9569  /* 0x01 */ { SkipAct1, SkipAct1, SkipAct1, SkipAct1, SkipAct1, NewSpriteSet, },
9570  /* 0x02 */ { nullptr, nullptr, nullptr, nullptr, nullptr, NewSpriteGroup, },
9571  /* 0x03 */ { nullptr, GRFUnsafe, nullptr, nullptr, nullptr, FeatureMapSpriteGroup, },
9572  /* 0x04 */ { nullptr, nullptr, nullptr, nullptr, nullptr, FeatureNewName, },
9573  /* 0x05 */ { SkipAct5, SkipAct5, SkipAct5, SkipAct5, SkipAct5, GraphicsNew, },
9574  /* 0x06 */ { nullptr, nullptr, nullptr, CfgApply, CfgApply, CfgApply, },
9575  /* 0x07 */ { nullptr, nullptr, nullptr, nullptr, SkipIf, SkipIf, },
9576  /* 0x08 */ { ScanInfo, nullptr, nullptr, GRFInfo, GRFInfo, GRFInfo, },
9577  /* 0x09 */ { nullptr, nullptr, nullptr, SkipIf, SkipIf, SkipIf, },
9578  /* 0x0A */ { SkipActA, SkipActA, SkipActA, SkipActA, SkipActA, SpriteReplace, },
9579  /* 0x0B */ { nullptr, nullptr, nullptr, GRFLoadError, GRFLoadError, GRFLoadError, },
9580  /* 0x0C */ { nullptr, nullptr, nullptr, GRFComment, nullptr, GRFComment, },
9581  /* 0x0D */ { nullptr, SafeParamSet, nullptr, ParamSet, ParamSet, ParamSet, },
9582  /* 0x0E */ { nullptr, SafeGRFInhibit, nullptr, GRFInhibit, GRFInhibit, GRFInhibit, },
9583  /* 0x0F */ { nullptr, GRFUnsafe, nullptr, FeatureTownName, nullptr, nullptr, },
9584  /* 0x10 */ { nullptr, nullptr, DefineGotoLabel, nullptr, nullptr, nullptr, },
9585  /* 0x11 */ { SkipAct11, GRFUnsafe, SkipAct11, GRFSound, SkipAct11, GRFSound, },
9587  /* 0x13 */ { nullptr, nullptr, nullptr, nullptr, nullptr, TranslateGRFStrings, },
9588  /* 0x14 */ { StaticGRFInfo, nullptr, nullptr, nullptr, nullptr, nullptr, },
9589  };
9590 
9591  GRFLocation location(_cur.grfconfig->ident.grfid, _cur.nfo_line);
9592 
9593  GRFLineToSpriteOverride::iterator it = _grf_line_to_action6_sprite_override.find(location);
9594  if (it == _grf_line_to_action6_sprite_override.end()) {
9595  /* No preloaded sprite to work with; read the
9596  * pseudo sprite content. */
9597  _cur.file->ReadBlock(buf, num);
9598  } else {
9599  /* Use the preloaded sprite data. */
9600  buf = _grf_line_to_action6_sprite_override[location].data();
9601  GrfMsg(7, "DecodeSpecialSprite: Using preloaded pseudo sprite data");
9602 
9603  /* Skip the real (original) content of this action. */
9604  _cur.file->SeekTo(num, SEEK_CUR);
9605  }
9606 
9607  ByteReader br(buf, buf + num);
9608 
9609  try {
9610  uint8_t action = br.ReadByte();
9611 
9612  if (action == 0xFF) {
9613  GrfMsg(2, "DecodeSpecialSprite: Unexpected data block, skipping");
9614  } else if (action == 0xFE) {
9615  GrfMsg(2, "DecodeSpecialSprite: Unexpected import block, skipping");
9616  } else if (action >= lengthof(handlers)) {
9617  GrfMsg(7, "DecodeSpecialSprite: Skipping unknown action 0x{:02X}", action);
9618  } else if (handlers[action][stage] == nullptr) {
9619  GrfMsg(7, "DecodeSpecialSprite: Skipping action 0x{:02X} in stage {}", action, stage);
9620  } else {
9621  GrfMsg(7, "DecodeSpecialSprite: Handling action 0x{:02X} in stage {}", action, stage);
9622  handlers[action][stage](br);
9623  }
9624  } catch (...) {
9625  GrfMsg(1, "DecodeSpecialSprite: Tried to read past end of pseudo-sprite data");
9626  DisableGrf(STR_NEWGRF_ERROR_READ_BOUNDS);
9627  }
9628 }
9629 
9636 static void LoadNewGRFFileFromFile(GRFConfig *config, GrfLoadingStage stage, SpriteFile &file)
9637 {
9638  _cur.file = &file;
9639  _cur.grfconfig = config;
9640 
9641  Debug(grf, 2, "LoadNewGRFFile: Reading NewGRF-file '{}'", config->filename);
9642 
9643  uint8_t grf_container_version = file.GetContainerVersion();
9644  if (grf_container_version == 0) {
9645  Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9646  return;
9647  }
9648 
9649  if (stage == GLS_INIT || stage == GLS_ACTIVATION) {
9650  /* We need the sprite offsets in the init stage for NewGRF sounds
9651  * and in the activation stage for real sprites. */
9652  ReadGRFSpriteOffsets(file);
9653  } else {
9654  /* Skip sprite section offset if present. */
9655  if (grf_container_version >= 2) file.ReadDword();
9656  }
9657 
9658  if (grf_container_version >= 2) {
9659  /* Read compression value. */
9660  uint8_t compression = file.ReadByte();
9661  if (compression != 0) {
9662  Debug(grf, 7, "LoadNewGRFFile: Unsupported compression format");
9663  return;
9664  }
9665  }
9666 
9667  /* Skip the first sprite; we don't care about how many sprites this
9668  * does contain; newest TTDPatches and George's longvehicles don't
9669  * neither, apparently. */
9670  uint32_t num = grf_container_version >= 2 ? file.ReadDword() : file.ReadWord();
9671  if (num == 4 && file.ReadByte() == 0xFF) {
9672  file.ReadDword();
9673  } else {
9674  Debug(grf, 7, "LoadNewGRFFile: Custom .grf has invalid format");
9675  return;
9676  }
9677 
9678  _cur.ClearDataForNextFile();
9679 
9681 
9682  while ((num = (grf_container_version >= 2 ? file.ReadDword() : file.ReadWord())) != 0) {
9683  uint8_t type = file.ReadByte();
9684  _cur.nfo_line++;
9685 
9686  if (type == 0xFF) {
9687  if (_cur.skip_sprites == 0) {
9688  DecodeSpecialSprite(buf.Allocate(num), num, stage);
9689 
9690  /* Stop all processing if we are to skip the remaining sprites */
9691  if (_cur.skip_sprites == -1) break;
9692 
9693  continue;
9694  } else {
9695  file.SkipBytes(num);
9696  }
9697  } else {
9698  if (_cur.skip_sprites == 0) {
9699  GrfMsg(0, "LoadNewGRFFile: Unexpected sprite, disabling");
9700  DisableGrf(STR_NEWGRF_ERROR_UNEXPECTED_SPRITE);
9701  break;
9702  }
9703 
9704  if (grf_container_version >= 2 && type == 0xFD) {
9705  /* Reference to data section. Container version >= 2 only. */
9706  file.SkipBytes(num);
9707  } else {
9708  file.SkipBytes(7);
9709  SkipSpriteData(file, type, num - 8);
9710  }
9711  }
9712 
9713  if (_cur.skip_sprites > 0) _cur.skip_sprites--;
9714  }
9715 }
9716 
9725 void LoadNewGRFFile(GRFConfig *config, GrfLoadingStage stage, Subdirectory subdir, bool temporary)
9726 {
9727  const std::string &filename = config->filename;
9728 
9729  /* A .grf file is activated only if it was active when the game was
9730  * started. If a game is loaded, only its active .grfs will be
9731  * reactivated, unless "loadallgraphics on" is used. A .grf file is
9732  * considered active if its action 8 has been processed, i.e. its
9733  * action 8 hasn't been skipped using an action 7.
9734  *
9735  * During activation, only actions 0, 1, 2, 3, 4, 5, 7, 8, 9, 0A and 0B are
9736  * carried out. All others are ignored, because they only need to be
9737  * processed once at initialization. */
9738  if (stage != GLS_FILESCAN && stage != GLS_SAFETYSCAN && stage != GLS_LABELSCAN) {
9739  _cur.grffile = GetFileByFilename(filename);
9740  if (_cur.grffile == nullptr) UserError("File '{}' lost in cache.\n", filename);
9741  if (stage == GLS_RESERVE && config->status != GCS_INITIALISED) return;
9742  if (stage == GLS_ACTIVATION && !HasBit(config->flags, GCF_RESERVED)) return;
9743  }
9744 
9745  bool needs_palette_remap = config->palette & GRFP_USE_MASK;
9746  if (temporary) {
9747  SpriteFile temporarySpriteFile(filename, subdir, needs_palette_remap);
9748  LoadNewGRFFileFromFile(config, stage, temporarySpriteFile);
9749  } else {
9750  LoadNewGRFFileFromFile(config, stage, OpenCachedSpriteFile(filename, subdir, needs_palette_remap));
9751  }
9752 }
9753 
9761 static void ActivateOldShore()
9762 {
9763  /* Use default graphics, if no shore sprites were loaded.
9764  * Should not happen, as the base set's extra grf should include some. */
9766 
9768  DupSprite(SPR_ORIGINALSHORE_START + 1, SPR_SHORE_BASE + 1); // SLOPE_W
9769  DupSprite(SPR_ORIGINALSHORE_START + 2, SPR_SHORE_BASE + 2); // SLOPE_S
9770  DupSprite(SPR_ORIGINALSHORE_START + 6, SPR_SHORE_BASE + 3); // SLOPE_SW
9771  DupSprite(SPR_ORIGINALSHORE_START + 0, SPR_SHORE_BASE + 4); // SLOPE_E
9772  DupSprite(SPR_ORIGINALSHORE_START + 4, SPR_SHORE_BASE + 6); // SLOPE_SE
9773  DupSprite(SPR_ORIGINALSHORE_START + 3, SPR_SHORE_BASE + 8); // SLOPE_N
9774  DupSprite(SPR_ORIGINALSHORE_START + 7, SPR_SHORE_BASE + 9); // SLOPE_NW
9775  DupSprite(SPR_ORIGINALSHORE_START + 5, SPR_SHORE_BASE + 12); // SLOPE_NE
9776  }
9777 
9779  DupSprite(SPR_FLAT_GRASS_TILE + 16, SPR_SHORE_BASE + 0); // SLOPE_STEEP_S
9780  DupSprite(SPR_FLAT_GRASS_TILE + 17, SPR_SHORE_BASE + 5); // SLOPE_STEEP_W
9781  DupSprite(SPR_FLAT_GRASS_TILE + 7, SPR_SHORE_BASE + 7); // SLOPE_WSE
9782  DupSprite(SPR_FLAT_GRASS_TILE + 15, SPR_SHORE_BASE + 10); // SLOPE_STEEP_N
9783  DupSprite(SPR_FLAT_GRASS_TILE + 11, SPR_SHORE_BASE + 11); // SLOPE_NWS
9784  DupSprite(SPR_FLAT_GRASS_TILE + 13, SPR_SHORE_BASE + 13); // SLOPE_ENW
9785  DupSprite(SPR_FLAT_GRASS_TILE + 14, SPR_SHORE_BASE + 14); // SLOPE_SEN
9786  DupSprite(SPR_FLAT_GRASS_TILE + 18, SPR_SHORE_BASE + 15); // SLOPE_STEEP_E
9787 
9788  /* XXX - SLOPE_EW, SLOPE_NS are currently not used.
9789  * If they would be used somewhen, then these grass tiles will most like not look as needed */
9790  DupSprite(SPR_FLAT_GRASS_TILE + 5, SPR_SHORE_BASE + 16); // SLOPE_EW
9791  DupSprite(SPR_FLAT_GRASS_TILE + 10, SPR_SHORE_BASE + 17); // SLOPE_NS
9792  }
9793 }
9794 
9799 {
9801  DupSprite(SPR_ROAD_DEPOT + 0, SPR_TRAMWAY_DEPOT_NO_TRACK + 0); // use road depot graphics for "no tracks"
9802  DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 1, SPR_TRAMWAY_DEPOT_NO_TRACK + 1);
9803  DupSprite(SPR_ROAD_DEPOT + 2, SPR_TRAMWAY_DEPOT_NO_TRACK + 2); // use road depot graphics for "no tracks"
9804  DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 3, SPR_TRAMWAY_DEPOT_NO_TRACK + 3);
9805  DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 4, SPR_TRAMWAY_DEPOT_NO_TRACK + 4);
9806  DupSprite(SPR_TRAMWAY_DEPOT_WITH_TRACK + 5, SPR_TRAMWAY_DEPOT_NO_TRACK + 5);
9807  }
9808 }
9809 
9814 {
9815  extern const PriceBaseSpec _price_base_specs[];
9817  static const uint32_t override_features = (1 << GSF_TRAINS) | (1 << GSF_ROADVEHICLES) | (1 << GSF_SHIPS) | (1 << GSF_AIRCRAFT);
9818 
9819  /* Evaluate grf overrides */
9820  int num_grfs = (uint)_grf_files.size();
9821  std::vector<int> grf_overrides(num_grfs, -1);
9822  for (int i = 0; i < num_grfs; i++) {
9823  GRFFile *source = _grf_files[i];
9824  auto it = _grf_id_overrides.find(source->grfid);
9825  if (it == std::end(_grf_id_overrides)) continue;
9826  uint32_t override = it->second;
9827 
9828  GRFFile *dest = GetFileByGRFID(override);
9829  if (dest == nullptr) continue;
9830 
9831  grf_overrides[i] = find_index(_grf_files, dest);
9832  assert(grf_overrides[i] >= 0);
9833  }
9834 
9835  /* Override features and price base multipliers of earlier loaded grfs */
9836  for (int i = 0; i < num_grfs; i++) {
9837  if (grf_overrides[i] < 0 || grf_overrides[i] >= i) continue;
9838  GRFFile *source = _grf_files[i];
9839  GRFFile *dest = _grf_files[grf_overrides[i]];
9840 
9841  uint32_t features = (source->grf_features | dest->grf_features) & override_features;
9842  source->grf_features |= features;
9843  dest->grf_features |= features;
9844 
9845  for (Price p = PR_BEGIN; p < PR_END; p++) {
9846  /* No price defined -> nothing to do */
9847  if (!HasBit(features, _price_base_specs[p].grf_feature) || source->price_base_multipliers[p] == INVALID_PRICE_MODIFIER) continue;
9848  Debug(grf, 3, "'{}' overrides price base multiplier {} of '{}'", source->filename, p, dest->filename);
9849  dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9850  }
9851  }
9852 
9853  /* Propagate features and price base multipliers of afterwards loaded grfs, if none is present yet */
9854  for (int i = num_grfs - 1; i >= 0; i--) {
9855  if (grf_overrides[i] < 0 || grf_overrides[i] <= i) continue;
9856  GRFFile *source = _grf_files[i];
9857  GRFFile *dest = _grf_files[grf_overrides[i]];
9858 
9859  uint32_t features = (source->grf_features | dest->grf_features) & override_features;
9860  source->grf_features |= features;
9861  dest->grf_features |= features;
9862 
9863  for (Price p = PR_BEGIN; p < PR_END; p++) {
9864  /* Already a price defined -> nothing to do */
9865  if (!HasBit(features, _price_base_specs[p].grf_feature) || dest->price_base_multipliers[p] != INVALID_PRICE_MODIFIER) continue;
9866  Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, source->filename, dest->filename);
9867  dest->price_base_multipliers[p] = source->price_base_multipliers[p];
9868  }
9869  }
9870 
9871  /* The 'master grf' now have the correct multipliers. Assign them to the 'addon grfs' to make everything consistent. */
9872  for (int i = 0; i < num_grfs; i++) {
9873  if (grf_overrides[i] < 0) continue;
9874  GRFFile *source = _grf_files[i];
9875  GRFFile *dest = _grf_files[grf_overrides[i]];
9876 
9877  uint32_t features = (source->grf_features | dest->grf_features) & override_features;
9878  source->grf_features |= features;
9879  dest->grf_features |= features;
9880 
9881  for (Price p = PR_BEGIN; p < PR_END; p++) {
9882  if (!HasBit(features, _price_base_specs[p].grf_feature)) continue;
9883  if (source->price_base_multipliers[p] != dest->price_base_multipliers[p]) {
9884  Debug(grf, 3, "Price base multiplier {} from '{}' propagated to '{}'", p, dest->filename, source->filename);
9885  }
9886  source->price_base_multipliers[p] = dest->price_base_multipliers[p];
9887  }
9888  }
9889 
9890  /* Apply fallback prices for grf version < 8 */
9891  for (GRFFile * const file : _grf_files) {
9892  if (file->grf_version >= 8) continue;
9893  PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9894  for (Price p = PR_BEGIN; p < PR_END; p++) {
9895  Price fallback_price = _price_base_specs[p].fallback_price;
9896  if (fallback_price != INVALID_PRICE && price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9897  /* No price multiplier has been set.
9898  * So copy the multiplier from the fallback price, maybe a multiplier was set there. */
9899  price_base_multipliers[p] = price_base_multipliers[fallback_price];
9900  }
9901  }
9902  }
9903 
9904  /* Decide local/global scope of price base multipliers */
9905  for (GRFFile * const file : _grf_files) {
9906  PriceMultipliers &price_base_multipliers = file->price_base_multipliers;
9907  for (Price p = PR_BEGIN; p < PR_END; p++) {
9908  if (price_base_multipliers[p] == INVALID_PRICE_MODIFIER) {
9909  /* No multiplier was set; set it to a neutral value */
9910  price_base_multipliers[p] = 0;
9911  } else {
9912  if (!HasBit(file->grf_features, _price_base_specs[p].grf_feature)) {
9913  /* The grf does not define any objects of the feature,
9914  * so it must be a difficulty setting. Apply it globally */
9915  Debug(grf, 3, "'{}' sets global price base multiplier {}", file->filename, p);
9916  SetPriceBaseMultiplier(p, price_base_multipliers[p]);
9917  price_base_multipliers[p] = 0;
9918  } else {
9919  Debug(grf, 3, "'{}' sets local price base multiplier {}", file->filename, p);
9920  }
9921  }
9922  }
9923  }
9924 }
9925 
9926 extern void InitGRFTownGeneratorNames();
9927 
9929 static void AfterLoadGRFs()
9930 {
9932  it.func(MapGRFStringID(it.grfid, it.source));
9933  }
9934  _string_to_grf_mapping.clear();
9935 
9936  /* Clear the action 6 override sprites. */
9937  _grf_line_to_action6_sprite_override.clear();
9938 
9939  /* Polish cargoes */
9941 
9942  /* Pre-calculate all refit masks after loading GRF files. */
9944 
9945  /* Polish engines */
9947 
9948  /* Set the actually used Canal properties */
9949  FinaliseCanals();
9950 
9951  /* Add all new houses to the house array. */
9953 
9954  /* Add all new industries to the industry array. */
9956 
9957  /* Add all new objects to the object array. */
9959 
9961 
9962  /* Sort the list of industry types. */
9964 
9965  /* Create dynamic list of industry legends for smallmap_gui.cpp */
9967 
9968  /* Build the routemap legend, based on the available cargos */
9970 
9971  /* Add all new airports to the airports array. */
9973  BindAirportSpecs();
9974 
9975  /* Update the townname generators list */
9977 
9978  /* Run all queued vehicle list order changes */
9980 
9981  /* Load old shore sprites in new position, if they were replaced by ActionA */
9982  ActivateOldShore();
9983 
9984  /* Load old tram depot sprites in new position, if no new ones are present */
9986 
9987  /* Set up custom rail types */
9988  InitRailTypes();
9989  InitRoadTypes();
9990 
9991  for (Engine *e : Engine::IterateType(VEH_ROAD)) {
9992  if (_gted[e->index].rv_max_speed != 0) {
9993  /* Set RV maximum speed from the mph/0.8 unit value */
9994  e->u.road.max_speed = _gted[e->index].rv_max_speed * 4;
9995  }
9996 
9997  RoadTramType rtt = HasBit(e->info.misc_flags, EF_ROAD_TRAM) ? RTT_TRAM : RTT_ROAD;
9998 
9999  const GRFFile *file = e->GetGRF();
10000  if (file == nullptr || _gted[e->index].roadtramtype == 0) {
10001  e->u.road.roadtype = (rtt == RTT_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
10002  continue;
10003  }
10004 
10005  /* Remove +1 offset. */
10006  _gted[e->index].roadtramtype--;
10007 
10008  const std::vector<RoadTypeLabel> *list = (rtt == RTT_TRAM) ? &file->tramtype_list : &file->roadtype_list;
10009  if (_gted[e->index].roadtramtype < list->size())
10010  {
10011  RoadTypeLabel rtl = (*list)[_gted[e->index].roadtramtype];
10012  RoadType rt = GetRoadTypeByLabel(rtl);
10013  if (rt != INVALID_ROADTYPE && GetRoadTramType(rt) == rtt) {
10014  e->u.road.roadtype = rt;
10015  continue;
10016  }
10017  }
10018 
10019  /* Road type is not available, so disable this engine */
10020  e->info.climates = 0;
10021  }
10022 
10023  for (Engine *e : Engine::IterateType(VEH_TRAIN)) {
10024  RailType railtype = GetRailTypeByLabel(_gted[e->index].railtypelabel);
10025  if (railtype == INVALID_RAILTYPE) {
10026  /* Rail type is not available, so disable this engine */
10027  e->info.climates = 0;
10028  } else {
10029  e->u.rail.railtype = railtype;
10030  e->u.rail.intended_railtype = railtype;
10031  }
10032  }
10033 
10035 
10037 
10038  /* Deallocate temporary loading data */
10039  _gted.clear();
10040  _grm_sprites.clear();
10041 }
10042 
10048 void LoadNewGRF(uint load_index, uint num_baseset)
10049 {
10050  /* In case of networking we need to "sync" the start values
10051  * so all NewGRFs are loaded equally. For this we use the
10052  * start date of the game and we set the counters, etc. to
10053  * 0 so they're the same too. */
10054  TimerGameCalendar::Date date = TimerGameCalendar::date;
10057 
10058  TimerGameEconomy::Date economy_date = TimerGameEconomy::date;
10059  TimerGameEconomy::Year economy_year = TimerGameEconomy::year;
10061 
10062  uint64_t tick_counter = TimerGameTick::counter;
10063  uint8_t display_opt = _display_opt;
10064 
10065  if (_networking) {
10069 
10073 
10075  _display_opt = 0;
10076  }
10077 
10079 
10080  ResetNewGRFData();
10081 
10082  /*
10083  * Reset the status of all files, so we can 'retry' to load them.
10084  * This is needed when one for example rearranges the NewGRFs in-game
10085  * and a previously disabled NewGRF becomes usable. If it would not
10086  * be reset, the NewGRF would remain disabled even though it should
10087  * have been enabled.
10088  */
10089  for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
10090  if (c->status != GCS_NOT_FOUND) c->status = GCS_UNKNOWN;
10091  }
10092 
10093  _cur.spriteid = load_index;
10094 
10095  /* Load newgrf sprites
10096  * in each loading stage, (try to) open each file specified in the config
10097  * and load information from it. */
10098  for (GrfLoadingStage stage = GLS_LABELSCAN; stage <= GLS_ACTIVATION; stage++) {
10099  /* Set activated grfs back to will-be-activated between reservation- and activation-stage.
10100  * This ensures that action7/9 conditions 0x06 - 0x0A work correctly. */
10101  for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
10102  if (c->status == GCS_ACTIVATED) c->status = GCS_INITIALISED;
10103  }
10104 
10105  if (stage == GLS_RESERVE) {
10106  static const std::pair<uint32_t, uint32_t> default_grf_overrides[] = {
10107  { BSWAP32(0x44442202), BSWAP32(0x44440111) }, // UKRS addons modifies UKRS
10108  { BSWAP32(0x6D620402), BSWAP32(0x6D620401) }, // DBSetXL ECS extension modifies DBSetXL
10109  { BSWAP32(0x4D656f20), BSWAP32(0x4D656F17) }, // LV4cut modifies LV4
10110  };
10111  for (const auto &grf_override : default_grf_overrides) {
10112  SetNewGRFOverride(grf_override.first, grf_override.second);
10113  }
10114  }
10115 
10116  uint num_grfs = 0;
10117  uint num_non_static = 0;
10118 
10119  _cur.stage = stage;
10120  for (GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
10121  if (c->status == GCS_DISABLED || c->status == GCS_NOT_FOUND) continue;
10122  if (stage > GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) continue;
10123 
10124  Subdirectory subdir = num_grfs < num_baseset ? BASESET_DIR : NEWGRF_DIR;
10125  if (!FioCheckFileExists(c->filename, subdir)) {
10126  Debug(grf, 0, "NewGRF file is missing '{}'; disabling", c->filename);
10127  c->status = GCS_NOT_FOUND;
10128  continue;
10129  }
10130 
10131  if (stage == GLS_LABELSCAN) InitNewGRFFile(c);
10132 
10133  if (!HasBit(c->flags, GCF_STATIC) && !HasBit(c->flags, GCF_SYSTEM)) {
10134  if (num_non_static == NETWORK_MAX_GRF_COUNT) {
10135  Debug(grf, 0, "'{}' is not loaded as the maximum number of non-static GRFs has been reached", c->filename);
10136  c->status = GCS_DISABLED;
10137  c->error = {STR_NEWGRF_ERROR_MSG_FATAL, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED};
10138  continue;
10139  }
10140  num_non_static++;
10141  }
10142 
10143  num_grfs++;
10144 
10145  LoadNewGRFFile(c, stage, subdir, false);
10146  if (stage == GLS_RESERVE) {
10147  SetBit(c->flags, GCF_RESERVED);
10148  } else if (stage == GLS_ACTIVATION) {
10149  ClrBit(c->flags, GCF_RESERVED);
10150  assert(GetFileByGRFID(c->ident.grfid) == _cur.grffile);
10153  Debug(sprite, 2, "LoadNewGRF: Currently {} sprites are loaded", _cur.spriteid);
10154  } else if (stage == GLS_INIT && HasBit(c->flags, GCF_INIT_ONLY)) {
10155  /* We're not going to activate this, so free whatever data we allocated */
10157  }
10158  }
10159  }
10160 
10161  /* Pseudo sprite processing is finished; free temporary stuff */
10162  _cur.ClearDataForNextFile();
10163 
10164  /* Call any functions that should be run after GRFs have been loaded. */
10165  AfterLoadGRFs();
10166 
10167  /* Now revert back to the original situation */
10168  TimerGameCalendar::year = year;
10169  TimerGameCalendar::date = date;
10170  TimerGameCalendar::date_fract = date_fract;
10171 
10172  TimerGameEconomy::year = economy_year;
10173  TimerGameEconomy::date = economy_date;
10174  TimerGameEconomy::date_fract = economy_date_fract;
10175 
10176  TimerGameTick::counter = tick_counter;
10177  _display_opt = display_opt;
10178 }
ResetCustomHouses
static void ResetCustomHouses()
Reset and clear all NewGRF houses.
Definition: newgrf.cpp:8719
INVALID_RAILTYPE
@ INVALID_RAILTYPE
Flag for invalid railtype.
Definition: rail_type.h:34
RoadTypeInfo::flags
RoadTypeFlags flags
Bit mask of road type flags.
Definition: road.h:127
AllowedSubtags::call_handler
bool call_handler
True if there is a callback function for this node, false if there is a list of subnodes.
Definition: newgrf.cpp:8395
RandomAccessFile::ReadByte
uint8_t ReadByte()
Read a byte from the file.
Definition: random_access_file.cpp:107
RoadTypeInfo::new_engine
StringID new_engine
Name of an engine for this type of road in the engine preview GUI.
Definition: road.h:108
CC_MAIL
@ CC_MAIL
Mail.
Definition: cargotype.h:51
GRFLocation
Definition: newgrf.cpp:358
CalculateRefitMasks
static void CalculateRefitMasks()
Precalculate refit masks from cargo classes for all vehicles.
Definition: newgrf.cpp:9004
OBJECT_SIZE_1X1
static const uint8_t OBJECT_SIZE_1X1
The value of a NewGRF's size property when the object is 1x1 tiles: low nibble for X,...
Definition: newgrf_object.h:43
GRFP_USE_MASK
@ GRFP_USE_MASK
Bitmask to get only the use palette use states.
Definition: newgrf_config.h:68
_display_opt
uint8_t _display_opt
What do we want to draw/do?
Definition: transparency_gui.cpp:26
RoadTypeInfo::toolbar_caption
StringID toolbar_caption
Caption in the construction toolbar GUI for this rail type.
Definition: road.h:104
_standard_cargo_mask
CargoTypes _standard_cargo_mask
Bitmask of real cargo types available.
Definition: cargotype.cpp:36
AllocateSound
SoundEntry * AllocateSound(uint num)
Allocate sound slots.
Definition: newgrf_sound.cpp:31
RailVehicleInfo::pow_wag_power
uint16_t pow_wag_power
Extra power applied to consist if wagon should be powered.
Definition: engine_type.h:56
GRFTempEngineData::UpdateRefittability
void UpdateRefittability(bool non_empty)
Update the summary refittability on setting a refittability property.
Definition: newgrf.cpp:337
RailVehicleInfo::curve_speed_mod
int16_t curve_speed_mod
Modifier to maximum speed in curves (fixed-point binary with 8 fractional bits)
Definition: engine_type.h:63
INVALID_ENGINE
static const EngineID INVALID_ENGINE
Constant denoting an invalid engine.
Definition: engine_type.h:206
EngineInfo::misc_flags
uint8_t misc_flags
Miscellaneous flags.
Definition: engine_type.h:155
RailVehicleInfo::pow_wag_weight
uint8_t pow_wag_weight
Extra weight applied to consist if wagon should be powered.
Definition: engine_type.h:57
RailTypeInfo::curve_speed
uint8_t curve_speed
Multiplier for curve maximum speed advantage.
Definition: rail.h:206
Action5Type::sprite_base
SpriteID sprite_base
Load the sprites starting from this sprite.
Definition: newgrf_act5.h:23
DSGA_OP_ADD
@ DSGA_OP_ADD
a + b
Definition: newgrf_spritegroup.h:121
OrderSettings::improved_load
bool improved_load
improved loading algorithm
Definition: settings_type.h:481
GrfProcessingState::IsValidSpriteSet
bool IsValidSpriteSet(uint8_t feature, uint set) const
Check whether a specific set is defined.
Definition: newgrf.cpp:167
HZ_ZON1
@ HZ_ZON1
0..4 1,2,4,8,10 which town zones the building can be built in, Zone1 been the further suburb
Definition: house.h:68
GRFTownName::styles
std::vector< TownNameStyle > styles
Style names defined by the Town Name NewGRF.
Definition: newgrf_townname.h:42
INVALID_AIRPORTTILE
static const uint INVALID_AIRPORTTILE
id for an invalid airport tile
Definition: airport.h:25
RoadTypeInfo
Definition: road.h:78
RailVehicleInfo::air_drag
uint8_t air_drag
Coefficient of air drag.
Definition: engine_type.h:61
NUM_STATIONS_PER_GRF
static const uint NUM_STATIONS_PER_GRF
The maximum amount of stations a single GRF is allowed to add.
Definition: newgrf.cpp:312
PROP_TRAIN_SPEED
@ PROP_TRAIN_SPEED
Max. speed: 1 unit = 1/1.6 mph = 1 km-ish/h.
Definition: newgrf_properties.h:21
GRFConfig::info
GRFTextWrapper info
NOSAVE: GRF info (author, copyright, ...) (Action 0x08)
Definition: newgrf_config.h:158
AllowedSubtags::AllowedSubtags
AllowedSubtags()
Create empty subtags object used to identify the end of a list.
Definition: newgrf.cpp:8330
RailTypeInfo::introduction_date
TimerGameCalendar::Date introduction_date
Introduction date.
Definition: rail.h:255
ResetCustomObjects
static void ResetCustomObjects()
Reset and clear all NewObjects.
Definition: newgrf.cpp:8745
VehicleSettings::road_side
uint8_t road_side
the side of the road vehicles drive on
Definition: settings_type.h:508
Engine::IterateType
static Pool::IterateWrapperFiltered< Engine, EngineTypeFilter > IterateType(VehicleType vt, size_t from=0)
Returns an iterable ensemble of all valid engines of the given type.
Definition: engine_base.h:186
IndustriesChangeInfo
static ChangeInfoResult IndustriesChangeInfo(uint indid, int numinfo, int prop, ByteReader &buf)
Define properties for industries.
Definition: newgrf.cpp:3541
SetBit
constexpr T SetBit(T &x, const uint8_t y)
Set a bit in a variable.
Definition: bitmath_func.hpp:121
_action5_types
static constexpr auto _action5_types
The information about action 5 types.
Definition: newgrf.cpp:6388
LanguageMetadata
Make sure the size is right.
Definition: language.h:93
VE_DISABLE_EFFECT
@ VE_DISABLE_EFFECT
Flag to disable visual effect.
Definition: vehicle_base.h:93
MCT_GRAIN_WHEAT_MAIZE
@ MCT_GRAIN_WHEAT_MAIZE
Cargo can be grain, wheat or maize.
Definition: cargo_type.h:85
ReadSpriteLayoutSprite
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)
Read a sprite and a palette from the GRF and convert them into a format suitable to OpenTTD.
Definition: newgrf.cpp:751
newgrf_station.h
SetUnicodeGlyph
void SetUnicodeGlyph(FontSize size, char32_t key, SpriteID sprite)
Map a SpriteID to the font size and key.
Definition: fontcache.h:152
newgrf_house.h
GRFFile::roadtype_list
std::vector< RoadTypeLabel > roadtype_list
Roadtype translation table (road)
Definition: newgrf.h:136
Pool::PoolItem<&_engine_pool >::Get
static Titem * Get(size_t index)
Returns Titem with given index.
Definition: pool_type.hpp:339
EngineOverrideManager::ResetToDefaultMapping
void ResetToDefaultMapping()
Initializes the EngineOverrideManager with the default engines.
Definition: engine.cpp:509
CargoSpec::label
CargoLabel label
Unique label of the cargo type.
Definition: cargotype.h:72
AircraftVehicleInfo::max_range
uint16_t max_range
Maximum range of this aircraft.
Definition: engine_type.h:110
ReadDWordAsString
static std::string ReadDWordAsString(ByteReader &reader)
Helper to read a DWord worth of bytes from the reader and to return it as a valid string.
Definition: newgrf.cpp:2721
TimerGameTick::counter
static TickCounter counter
Monotonic counter, in ticks, since start of game.
Definition: timer_game_tick.h:60
HouseZones
HouseZones
Definition: house.h:66
OBJECT_FLAG_2CC_COLOUR
@ OBJECT_FLAG_2CC_COLOUR
Object wants 2CC colour mapping.
Definition: newgrf_object.h:34
RailTypeChangeInfo
static ChangeInfoResult RailTypeChangeInfo(uint id, int numinfo, int prop, ByteReader &buf)
Define properties for railtypes.
Definition: newgrf.cpp:4244
PROP_TRAIN_CARGO_CAPACITY
@ PROP_TRAIN_CARGO_CAPACITY
Capacity (if dualheaded: for each single vehicle)
Definition: newgrf_properties.h:24
CC_LIQUID
@ CC_LIQUID
Liquids (Oil, Water, Rubber)
Definition: cargotype.h:56
ChangeGRFDescription
static bool ChangeGRFDescription(uint8_t langid, std::string_view str)
Callback function for 'INFO'->'DESC' to add a translation to the newgrf description.
Definition: newgrf.cpp:8122
CC_PASSENGERS
@ CC_PASSENGERS
Passengers.
Definition: cargotype.h:50
GameSettings::station
StationSettings station
settings related to station management
Definition: settings_type.h:605
ResetCustomAirports
static void ResetCustomAirports()
Reset and clear all NewGRF airports.
Definition: newgrf.cpp:8727
AircraftVehicleInfo::max_speed
uint16_t max_speed
Maximum speed (1 unit = 8 mph = 12.8 km-ish/h)
Definition: engine_type.h:107
DIR_E
@ DIR_E
East.
Definition: direction_type.h:28
PROP_ROADVEH_TRACTIVE_EFFORT
@ PROP_ROADVEH_TRACTIVE_EFFORT
Tractive effort coefficient in 1/256.
Definition: newgrf_properties.h:39
SNOW_LINE_DAYS
static const uint SNOW_LINE_DAYS
Number of days in each month in the snow line table.
Definition: landscape.h:17
RoadTypeInfo::map_colour
uint8_t map_colour
Colour on mini-map.
Definition: road.h:157
RoadTypeInfo::menu_text
StringID menu_text
Name of this rail type in the main toolbar dropdown.
Definition: road.h:105
TimerGameConst< struct Calendar >::DAYS_TILL_ORIGINAL_BASE_YEAR
static constexpr TimerGame< struct Calendar >::Date DAYS_TILL_ORIGINAL_BASE_YEAR
The date of the first day of the original base year.
Definition: timer_game_common.h:184
GetFileByGRFID
static GRFFile * GetFileByGRFID(uint32_t grfid)
Obtain a NewGRF file by its grfID.
Definition: newgrf.cpp:399
DeterministicSpriteGroupRange
Definition: newgrf_spritegroup.h:160
GRFConfig::num_valid_params
uint8_t num_valid_params
NOSAVE: Number of valid parameters (action 0x14)
Definition: newgrf_config.h:169
StationSpec::renderdata
std::vector< NewGRFSpriteLayout > renderdata
Number of tile layouts.
Definition: newgrf_station.h:149
NUM_INDUSTRYTYPES_PER_GRF
static const IndustryType NUM_INDUSTRYTYPES_PER_GRF
maximum number of industry types per NewGRF; limited to 128 because bit 7 has a special meaning in so...
Definition: industry_type.h:23
SPR_SHORE_BASE
static const SpriteID SPR_SHORE_BASE
shore tiles - action 05-0D
Definition: sprites.h:224
IndustryProductionSpriteGroup::num_output
uint8_t num_output
How many add_output values are valid.
Definition: newgrf_spritegroup.h:276
TLF_DODRAW
@ TLF_DODRAW
Only draw sprite if value of register TileLayoutRegisters::dodraw is non-zero.
Definition: newgrf_commons.h:35
ReusableBuffer< uint8_t >
GetRoadTypeByLabel
RoadType GetRoadTypeByLabel(RoadTypeLabel label, bool allow_alternate_labels)
Get the road type for a given label.
Definition: road.cpp:254
HouseExtraFlags
HouseExtraFlags
Definition: house.h:83
GRFError::custom_message
std::string custom_message
Custom message (if present)
Definition: newgrf_config.h:112
PROP_ROADVEH_COST_FACTOR
@ PROP_ROADVEH_COST_FACTOR
Purchase cost.
Definition: newgrf_properties.h:35
IsInsideMM
constexpr bool IsInsideMM(const T x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
Definition: math_func.hpp:268
GCS_ACTIVATED
@ GCS_ACTIVATED
GRF file has been activated.
Definition: newgrf_config.h:39
ObjectSpec
Allow incrementing of ObjectClassID variables.
Definition: newgrf_object.h:60
RoadStopSpec
Road stop specification.
Definition: newgrf_roadstop.h:135
ROADTYPE_ROAD
@ ROADTYPE_ROAD
Basic road type.
Definition: road_type.h:27
TileLayoutRegisters::dodraw
uint8_t dodraw
Register deciding whether the sprite shall be drawn at all. Non-zero means drawing.
Definition: newgrf_commons.h:92
ObjectSpec::grf_prop
GRFFilePropsBase< 2 > grf_prop
Properties related the the grf file.
Definition: newgrf_object.h:62
GrfProcessingState::grffile
GRFFile * grffile
Currently processed GRF file.
Definition: newgrf.cpp:107
DrawTileSeqStruct::IsParentSprite
bool IsParentSprite() const
Check whether this is a parent sprite with a boundingbox.
Definition: sprite.h:47
HouseSpec::Specs
static std::vector< HouseSpec > & Specs()
Get a reference to all HouseSpecs.
Definition: newgrf_house.cpp:50
RoadTypeInfo::introduction_date
TimerGameCalendar::Date introduction_date
Introduction date.
Definition: road.h:166
NamePartList::maxprob
uint16_t maxprob
Total probability of all parts.
Definition: newgrf_townname.h:27
_engine_offsets
const uint8_t _engine_offsets[4]
Offset of the first engine of each vehicle type in original engine data.
Definition: engine.cpp:61
GetRailTypeInfo
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition: rail.h:307
_string_to_grf_mapping
static std::vector< StringIDMapping > _string_to_grf_mapping
Strings to be mapped during load.
Definition: newgrf.cpp:465
IsValidNewGRFImageIndex
static bool IsValidNewGRFImageIndex(uint8_t image_index)
Helper to check whether an image index is valid for a particular NewGRF vehicle.
Definition: newgrf.cpp:208
ResetCustomIndustries
static void ResetCustomIndustries()
Reset and clear all NewGRF industries.
Definition: newgrf.cpp:8736
PROP_TRAIN_RUNNING_COST_FACTOR
@ PROP_TRAIN_RUNNING_COST_FACTOR
Yearly runningcost (if dualheaded: sum of both vehicles)
Definition: newgrf_properties.h:23
GRFUnsafe
static void GRFUnsafe(ByteReader &)
Set the current NewGRF as unsafe for static use.
Definition: newgrf.cpp:8612
TimerGameCalendar::date_fract
static DateFract date_fract
Fractional part of the day.
Definition: timer_game_calendar.h:35
smallmap_gui.h
_grf_files
static std::vector< GRFFile * > _grf_files
List of all loaded GRF files.
Definition: newgrf.cpp:70
SPRITE_WIDTH
@ SPRITE_WIDTH
number of bits for the sprite number
Definition: sprites.h:1535
HZ_CLIMALL
@ HZ_CLIMALL
Bitmask of all climate bits.
Definition: house.h:79
FeatureTownName
static void FeatureTownName(ByteReader &buf)
Action 0x0F - Define Town names.
Definition: newgrf.cpp:7758
AddStringForMapping
static void AddStringForMapping(StringID source, std::function< void(StringID)> &&func)
Record a static StringID for getting translated later.
Definition: newgrf.cpp:472
TLF_CHILD_X_OFFSET
@ TLF_CHILD_X_OFFSET
Add signed offset to child sprite X positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:43
RAILTYPE_RAIL
@ RAILTYPE_RAIL
Standard non-electric rails.
Definition: rail_type.h:29
RoadTypeInfo::introduces_roadtypes
RoadTypes introduces_roadtypes
Bitmask of which other roadtypes are introduced when this roadtype is introduced.
Definition: road.h:177
GRFFile::price_base_multipliers
PriceMultipliers price_base_multipliers
Price base multipliers as set by the grf.
Definition: newgrf.h:150
Map::LogX
static debug_inline uint LogX()
Logarithm of the map size along the X side.
Definition: map_func.h:251
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32_t id, BranchHandler handler)
Create a branch node with a callback handler.
Definition: newgrf.cpp:8364
RAILTYPE_ELECTRIC
@ RAILTYPE_ELECTRIC
Electric rails.
Definition: rail_type.h:30
DeterministicSpriteGroup
Definition: newgrf_spritegroup.h:167
PROP_TRAIN_TRACTIVE_EFFORT
@ PROP_TRAIN_TRACTIVE_EFFORT
Tractive effort coefficient in 1/256.
Definition: newgrf_properties.h:27
AllowedSubtags::branch
BranchHandler branch
Callback function for a branch node, only valid if type == 'C' && call_handler.
Definition: newgrf.cpp:8392
TimerGameEconomy::ConvertYMDToDate
static Date ConvertYMDToDate(Year year, Month month, Day day)
Converts a tuple of Year, Month and Day to a Date.
Definition: timer_game_economy.cpp:66
timer_game_calendar.h
HouseSpec::accepts_cargo
CargoID accepts_cargo[HOUSE_NUM_ACCEPTS]
input cargo slots
Definition: house.h:103
BuildCargoLabelMap
void BuildCargoLabelMap()
Build cargo label map.
Definition: cargotype.cpp:93
RailVehicleInfo::tractive_effort
uint8_t tractive_effort
Tractive effort coefficient.
Definition: engine_type.h:60
NewGRFSpriteLayout::AllocateRegisters
void AllocateRegisters()
Allocate memory for register modifiers.
Definition: newgrf_commons.cpp:621
CC_PIECE_GOODS
@ CC_PIECE_GOODS
Piece goods (Livestock, Wood, Steel, Paper)
Definition: cargotype.h:55
PALETTE_MODIFIER_COLOUR
@ PALETTE_MODIFIER_COLOUR
this bit is set when a recolouring process is in action
Definition: sprites.h:1550
BASESET_DIR
@ BASESET_DIR
Subdirectory for all base data (base sets, intro game)
Definition: fileio_type.h:123
currency.h
LoadFontGlyph
static void LoadFontGlyph(ByteReader &buf)
Action 0x12.
Definition: newgrf.cpp:8005
ChangeGRFParamName
static bool ChangeGRFParamName(uint8_t langid, std::string_view str)
Callback function for 'INFO'->'PARAM'->param_num->'NAME' to set the name of a parameter.
Definition: newgrf.cpp:8231
StringID
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
Definition: strings_type.h:16
Price
Price
Enumeration of all base prices for use with Prices.
Definition: economy_type.h:89
PROP_AIRCRAFT_MAIL_CAPACITY
@ PROP_AIRCRAFT_MAIL_CAPACITY
Mail Capacity.
Definition: newgrf_properties.h:53
RailTypeInfo::new_loco
StringID new_loco
Name of an engine for this type of rail in the engine preview GUI.
Definition: rail.h:181
AllowedSubtags::type
uint8_t type
The type of the node, must be one of 'C', 'B' or 'T'.
Definition: newgrf.cpp:8386
StationClassID
StationClassID
Definition: newgrf_station.h:86
FinaliseCanals
static void FinaliseCanals()
Set to use the correct action0 properties for each canal feature.
Definition: newgrf.cpp:9181
CanalProperties::callback_mask
uint8_t callback_mask
Bitmask of canal callbacks that have to be called.
Definition: newgrf.h:41
CanalProperties::flags
uint8_t flags
Flags controlling display.
Definition: newgrf.h:42
CargoLabel
StrongType::Typedef< uint32_t, struct CargoLabelTag, StrongType::Compare > CargoLabel
Globally unique label of a cargo type.
Definition: cargo_type.h:17
EC_STEAM
@ EC_STEAM
Steam rail engine.
Definition: engine_type.h:34
PriceBaseSpec::grf_feature
uint grf_feature
GRF Feature that decides whether price multipliers apply locally or globally, #GSF_END if none.
Definition: economy_type.h:210
GB
constexpr static debug_inline uint GB(const T x, const uint8_t s, const uint8_t n)
Fetch n bits from x, started at bit s.
Definition: bitmath_func.hpp:32
RandomizedSpriteGroup::cmp_mode
RandomizedSpriteGroupCompareMode cmp_mode
Check for these triggers:
Definition: newgrf_spritegroup.h:195
VE_DEFAULT
@ VE_DEFAULT
Default value to indicate that visual effect should be based on engine class.
Definition: vehicle_base.h:97
RailType
RailType
Enumeration for all possible railtypes.
Definition: rail_type.h:27
Pool::PoolItem::index
Tindex index
Index of this pool item.
Definition: pool_type.hpp:238
RoadStopDrawMode
RoadStopDrawMode
Different draw modes to disallow rendering of some parts of the stop or road.
Definition: newgrf_roadstop.h:61
PROP_ROADVEH_SHORTEN_FACTOR
@ PROP_ROADVEH_SHORTEN_FACTOR
Shorter vehicles.
Definition: newgrf_properties.h:41
BridgeSpec::sprite_table
PalSpriteID ** sprite_table
table of sprites for drawing the bridge
Definition: bridge.h:52
DeterministicSpriteGroupAdjustOperation
DeterministicSpriteGroupAdjustOperation
Definition: newgrf_spritegroup.h:120
CargoSpec::Get
static CargoSpec * Get(size_t index)
Retrieve cargo details for the given cargo ID.
Definition: cargotype.h:134
ResetPersistentNewGRFData
void ResetPersistentNewGRFData()
Reset NewGRF data which is stored persistently in savegames.
Definition: newgrf.cpp:8879
VEH_TRAIN
@ VEH_TRAIN
Train vehicle type.
Definition: vehicle_type.h:24
PROP_SHIP_CARGO_CAPACITY
@ PROP_SHIP_CARGO_CAPACITY
Capacity.
Definition: newgrf_properties.h:45
_bridge
BridgeSpec _bridge[MAX_BRIDGES]
The specification of all bridges.
Definition: tunnelbridge_cmd.cpp:52
PalSpriteID::sprite
SpriteID sprite
The 'real' sprite.
Definition: gfx_type.h:24
HouseSpec::cargo_acceptance
uint8_t cargo_acceptance[HOUSE_NUM_ACCEPTS]
acceptance level for the cargo slots
Definition: house.h:102
GrfProcessingState::ClearDataForNextFile
void ClearDataForNextFile()
Clear temporary data before processing the next file in the current loading stage.
Definition: newgrf.cpp:118
PROP_AIRCRAFT_RUNNING_COST_FACTOR
@ PROP_AIRCRAFT_RUNNING_COST_FACTOR
Yearly runningcost.
Definition: newgrf_properties.h:51
NewGRFClass::Assign
static void Assign(Tspec *spec)
Assign a spec to one of the classes.
Definition: newgrf_class_func.h:70
HouseSpec::enabled
bool enabled
the house is available to build (true by default, but can be disabled by newgrf)
Definition: house.h:107
RailVehicleInfo::shorten_factor
uint8_t shorten_factor
length on main map for this type is 8 - shorten_factor
Definition: engine_type.h:59
IndustryProductionSpriteGroup::add_output
uint16_t add_output[INDUSTRY_NUM_OUTPUTS]
Add this much output cargo when successful (unsigned, is indirect in cb version 1+)
Definition: newgrf_spritegroup.h:277
SortIndustryTypes
void SortIndustryTypes()
Initialize the list of sorted industry types.
Definition: industry_gui.cpp:237
ResetPriceBaseMultipliers
void ResetPriceBaseMultipliers()
Reset changes to the price base multipliers.
Definition: economy.cpp:890
RoadVehicleInfo::shorten_factor
uint8_t shorten_factor
length on main map for this type is 8 - shorten_factor
Definition: engine_type.h:127
ResetRailTypes
void ResetRailTypes()
Reset all rail type information to its default values.
Definition: rail_cmd.cpp:65
GrfProcessingState::spritesets
std::map< uint, SpriteSet > spritesets[GSF_END]
Currently referenceable spritesets.
Definition: newgrf.cpp:98
StrMakeValid
static void StrMakeValid(T &dst, const char *str, const char *last, StringValidationSettings settings)
Copies the valid (UTF-8) characters from str up to last to the dst.
Definition: string.cpp:107
GrfProcessingState::spriteid
SpriteID spriteid
First available SpriteID for loading realsprites.
Definition: newgrf.cpp:103
StationChangeInfo
static ChangeInfoResult StationChangeInfo(uint stid, int numinfo, int prop, ByteReader &buf)
Define properties for stations.
Definition: newgrf.cpp:1924
GRFConfig::filename
std::string filename
Filename - either with or without full path.
Definition: newgrf_config.h:156
RailTypeInfo
This struct contains all the info that is needed to draw and construct tracks.
Definition: rail.h:127
VehicleSettings::wagon_speed_limits
bool wagon_speed_limits
enable wagon speed limits
Definition: settings_type.h:497
CIR_INVALID_ID
@ CIR_INVALID_ID
Attempt to modify an invalid ID.
Definition: newgrf.cpp:997
TLF_CUSTOM_PALETTE
@ TLF_CUSTOM_PALETTE
Palette is from Action 1 (moved to SPRITE_MODIFIER_CUSTOM_SPRITE in palette during loading).
Definition: newgrf_commons.h:38
A5BLOCK_FIXED
@ A5BLOCK_FIXED
Only allow replacing a whole block of sprites. (TTDP compatible)
Definition: newgrf_act5.h:15
RailTypeInfo::alternate_labels
RailTypeLabelList alternate_labels
Rail type labels this type provides in addition to the main label.
Definition: rail.h:241
_currency_specs
std::array< CurrencySpec, CURRENCY_END > _currency_specs
Array of currencies used by the system.
Definition: currency.cpp:77
RailVehicleInfo::running_cost
uint8_t running_cost
Running cost of engine; For multiheaded engines the sum of both running costs.
Definition: engine_type.h:51
_tags_info
AllowedSubtags _tags_info[]
Action14 tags for the INFO node.
Definition: newgrf.cpp:8483
AnimationInfo::frames
uint8_t frames
The number of frames.
Definition: newgrf_animation_type.h:19
vehicle_base.h
ConvertTTDBasePrice
static void ConvertTTDBasePrice(uint32_t base_pointer, const char *error_location, Price *index)
Converts TTD(P) Base Price pointers into the enum used by OTTD See http://wiki.ttdpatch....
Definition: newgrf.cpp:972
VEH_ROAD
@ VEH_ROAD
Road vehicle type.
Definition: vehicle_type.h:25
fileio_func.h
GCS_NOT_FOUND
@ GCS_NOT_FOUND
GRF file was not found in the local cache.
Definition: newgrf_config.h:37
GetNewgrfCurrencyIdConverted
uint8_t GetNewgrfCurrencyIdConverted(uint8_t grfcurr_id)
Will return the ottd's index correspondence to the ttdpatch's id.
Definition: currency.cpp:116
RailVehicleInfo::capacity
uint8_t capacity
Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
Definition: engine_type.h:54
IsDefaultCargo
bool IsDefaultCargo(CargoID cid)
Test if a cargo is a default cargo type.
Definition: cargotype.cpp:111
newgrf_airport.h
SetupCargoForClimate
void SetupCargoForClimate(LandscapeID l)
Set up the default cargo types for the given landscape type.
Definition: cargotype.cpp:48
build_industry.h
GRFTempEngineData::ctt_include_mask
CargoTypes ctt_include_mask
Cargo types always included in the refit mask.
Definition: newgrf.cpp:330
TimerGameEconomy::date_fract
static DateFract date_fract
Fractional part of the day.
Definition: timer_game_economy.h:38
CargoSpec::Iterate
static IterateWrapper Iterate(size_t from=0)
Returns an iterable ensemble of all valid CargoSpec.
Definition: cargotype.h:190
SetSnowLine
void SetSnowLine(uint8_t table[SNOW_LINE_MONTHS][SNOW_LINE_DAYS])
Set a variable snow line, as loaded from a newgrf file.
Definition: landscape.cpp:589
SetupEngines
void SetupEngines()
Initialise the engine pool with the data from the original vehicles.
Definition: engine.cpp:565
GRFConfig::ident
GRFIdentifier ident
grfid and md5sum to uniquely identify newgrfs
Definition: newgrf_config.h:154
newgrf_townname.h
RailTypeInfo::introduction_required_railtypes
RailTypes introduction_required_railtypes
Bitmask of railtypes that are required for this railtype to be introduced at a given introduction_dat...
Definition: rail.h:261
RAILTYPE_END
@ RAILTYPE_END
Used for iterations.
Definition: rail_type.h:33
ttd_strnlen
size_t ttd_strnlen(const char *str, size_t maxlen)
Get the length of a string, within a limited buffer.
Definition: string_func.h:69
AirportSpec::ResetAirports
static void ResetAirports()
This function initializes the airportspec array.
Definition: newgrf_airport.cpp:111
CargoSpec
Specification of a cargo type.
Definition: cargotype.h:71
GetNewEngine
static Engine * GetNewEngine(const GRFFile *file, VehicleType type, uint16_t internal_id, bool static_access=false)
Returns the engine associated to a certain internal_id, resp.
Definition: newgrf.cpp:612
_misc_grf_features
uint8_t _misc_grf_features
Miscellaneous GRF features, set by Action 0x0D, parameter 0x9E.
Definition: newgrf.cpp:78
ReusableBuffer::Allocate
T * Allocate(size_t count)
Get buffer of at least count times T.
Definition: alloc_type.hpp:42
GRFConfig::status
GRFStatus status
NOSAVE: GRFStatus, enum.
Definition: newgrf_config.h:165
GetNewGRFSoundID
SoundID GetNewGRFSoundID(const GRFFile *file, SoundID sound_id)
Resolve NewGRF sound ID.
Definition: newgrf_sound.cpp:169
TranslateGRFStrings
static void TranslateGRFStrings(ByteReader &buf)
Action 0x13.
Definition: newgrf.cpp:8062
VE_TYPE_COUNT
@ VE_TYPE_COUNT
Number of bits used for the effect type.
Definition: vehicle_base.h:87
town.h
ChangeGRFName
static bool ChangeGRFName(uint8_t langid, std::string_view str)
Callback function for 'INFO'->'NAME' to add a translation to the newgrf name.
Definition: newgrf.cpp:8115
GetGRFConfig
GRFConfig * GetGRFConfig(uint32_t grfid, uint32_t mask)
Retrieve a NewGRF from the current config by its grfid.
Definition: newgrf_config.cpp:712
NUM_OBJECTS_PER_GRF
static const ObjectType NUM_OBJECTS_PER_GRF
Number of supported objects per NewGRF.
Definition: object_type.h:24
BridgeSpec::speed
uint16_t speed
maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: bridge.h:47
GRFP_GRF_UNSET
@ GRFP_GRF_UNSET
The NewGRF provided no information.
Definition: newgrf_config.h:70
StrongType::Typedef
Templated helper to make a type-safe 'typedef' representing a single POD value.
Definition: strong_typedef_type.hpp:150
ObjectFlags
ObjectFlags
Various object behaviours.
Definition: newgrf_object.h:24
EngineInfo
Information about a vehicle.
Definition: engine_type.h:144
GrfProcessingState::file
SpriteFile * file
File of currently processed GRF file.
Definition: newgrf.cpp:106
GRFLoadedFeatures::used_liveries
uint64_t used_liveries
Bitmask of LiveryScheme used by the defined engines.
Definition: newgrf.h:179
GMB_TRAIN_WIDTH_32_PIXELS
@ GMB_TRAIN_WIDTH_32_PIXELS
Use 32 pixels per train vehicle in depot gui and vehicle details. Never set in the global variable;.
Definition: newgrf.h:61
IndustrySpec::station_name
StringID station_name
Default name for nearby station.
Definition: industrytype.h:128
NamePart::id
uint8_t id
If probability bit 7 is set.
Definition: newgrf_townname.h:20
CIR_SUCCESS
@ CIR_SUCCESS
Variable was parsed and read.
Definition: newgrf.cpp:993
GRFConfig::min_loadable_version
uint32_t min_loadable_version
NOSAVE: Minimum compatible version a NewGRF can define.
Definition: newgrf_config.h:163
MAX_SPRITEGROUP
static const uint MAX_SPRITEGROUP
Maximum GRF-local ID for a spritegroup.
Definition: newgrf.cpp:86
ChangeGRFParamLimits
static bool ChangeGRFParamLimits(size_t len, ByteReader &buf)
Callback function for 'INFO'->'PARAM'->param_num->'LIMI' to set the min/max value of a parameter.
Definition: newgrf.cpp:8262
RoadTypeInfo::replace_text
StringID replace_text
Text used in the autoreplace GUI.
Definition: road.h:107
AllowedSubtags::text
TextHandler text
Callback function for a text node, only valid if type == 'T'.
Definition: newgrf.cpp:8389
RailTypeInfo::group
const SpriteGroup * group[RTSG_END]
Sprite groups for resolving sprites.
Definition: rail.h:281
Engine
Definition: engine_base.h:37
Action5Type::max_sprites
uint16_t max_sprites
If the Action5 contains more sprites, only the first max_sprites sprites will be used.
Definition: newgrf_act5.h:25
HandleNodes
static bool HandleNodes(ByteReader &buf, AllowedSubtags subtags[])
Handle the contents of a 'C' choice of an Action14.
Definition: newgrf.cpp:8587
IndustryTileSpec::accepts_cargo
std::array< CargoID, INDUSTRY_NUM_INPUTS > accepts_cargo
Cargo accepted by this tile.
Definition: industrytype.h:149
GRFParameterInfo::type
GRFParameterType type
The type of this parameter.
Definition: newgrf_config.h:131
ShipVehicleInfo::canal_speed_frac
uint8_t canal_speed_frac
Fraction of maximum speed for canal/river tiles.
Definition: engine_type.h:78
RailTypeInfo::strings
struct RailTypeInfo::@26 strings
Strings associated with the rail type.
_tags_parameters
AllowedSubtags _tags_parameters[]
Action14 parameter tags.
Definition: newgrf.cpp:8439
RoadVehicleInfo::roadtype
RoadType roadtype
Road type.
Definition: engine_type.h:128
fios.h
BridgeSpec::price
uint16_t price
the price multiplier
Definition: bridge.h:46
ConstructionSettings::max_bridge_length
uint16_t max_bridge_length
maximum length of bridges
Definition: settings_type.h:385
ObjectChangeInfo
static ChangeInfoResult ObjectChangeInfo(uint id, int numinfo, int prop, ByteReader &buf)
Define properties for objects.
Definition: newgrf.cpp:4114
FinalisePriceBaseMultipliers
static void FinalisePriceBaseMultipliers()
Decide whether price base multipliers of grfs shall apply globally or only to the grf specifying them...
Definition: newgrf.cpp:9813
RandomAccessFile::ReadBlock
void ReadBlock(void *ptr, size_t size)
Read a block.
Definition: random_access_file.cpp:145
_engine_counts
const uint8_t _engine_counts[4]
Number of engines of each vehicle type in original engine data.
Definition: engine.cpp:53
TLF_BB_Z_OFFSET
@ TLF_BB_Z_OFFSET
Add signed offset to bounding box Z positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:41
PaletteID
uint32_t PaletteID
The number of the palette.
Definition: gfx_type.h:19
ChangeGRFParamDescription
static bool ChangeGRFParamDescription(uint8_t langid, std::string_view str)
Callback function for 'INFO'->'PARAM'->param_num->'DESC' to set the description of a parameter.
Definition: newgrf.cpp:8238
GFX_WATERTILE_SPECIALCHECK
@ GFX_WATERTILE_SPECIALCHECK
not really a tile, but rather a very special check
Definition: industry_map.h:54
TPE_MAIL
@ TPE_MAIL
Cargo behaves mail-like for production.
Definition: cargotype.h:37
GameCreationSettings::landscape
uint8_t landscape
the landscape we're currently in
Definition: settings_type.h:368
newgrf_act5.h
ReadSpriteLayout
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)
Read a spritelayout from the GRF.
Definition: newgrf.cpp:862
AirportSpec
Defines the data structure for an airport.
Definition: newgrf_airport.h:105
NewGRFClass::name
StringID name
Name of this class.
Definition: newgrf_class.h:49
HasExactlyOneBit
constexpr bool HasExactlyOneBit(T value)
Test whether value has exactly 1 bit set.
Definition: bitmath_func.hpp:278
GRFParameterInfo::min_value
uint32_t min_value
The minimal value this parameter can have.
Definition: newgrf_config.h:132
NUM_HOUSES_PER_GRF
static const HouseID NUM_HOUSES_PER_GRF
Number of supported houses per NewGRF; limited to 255 to allow extending Action3 with an extended byt...
Definition: house.h:25
genworld.h
TileLayoutRegisters
Additional modifiers for items in sprite layouts.
Definition: newgrf_commons.h:90
CargoSpec::initial_payment
int32_t initial_payment
Initial payment rate before inflation is applied.
Definition: cargotype.h:79
IndustrytilesChangeInfo
static ChangeInfoResult IndustrytilesChangeInfo(uint indtid, int numinfo, int prop, ByteReader &buf)
Define properties for industry tiles.
Definition: newgrf.cpp:3284
LanguageMap::Mapping::openttd_id
uint8_t openttd_id
OpenTTD's internal ID for a case/gender.
Definition: newgrf_text_type.h:32
TAE_MAIL
@ TAE_MAIL
Cargo behaves mail-like.
Definition: cargotype.h:25
GRFP_BLT_UNSET
@ GRFP_BLT_UNSET
The NewGRF provided no information or doesn't care about a 32 bpp blitter.
Definition: newgrf_config.h:76
CIR_UNHANDLED
@ CIR_UNHANDLED
Variable was parsed but unread.
Definition: newgrf.cpp:995
Debug
#define Debug(category, level, format_string,...)
Ouptut a line of debugging information.
Definition: debug.h:37
SPR_AQUEDUCT_BASE
static const SpriteID SPR_AQUEDUCT_BASE
Sprites for the Aqueduct.
Definition: sprites.h:186
GrfProcessingState::nfo_line
uint32_t nfo_line
Currently processed pseudo sprite number in the GRF.
Definition: newgrf.cpp:109
industry_map.h
CargoSpec::array
static CargoSpec array[NUM_CARGO]
Array holding all CargoSpecs.
Definition: cargotype.h:196
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32_t id, DataHandler handler)
Create a binary leaf node.
Definition: newgrf.cpp:8340
ChangeGRFParamValueNames
static bool ChangeGRFParamValueNames(ByteReader &buf)
Callback function for 'INFO'->'PARA'->param_num->'VALU' to set the names of some parameter values (ty...
Definition: newgrf.cpp:8409
GameSettings::game_creation
GameCreationSettings game_creation
settings used during the creation of a game (map)
Definition: settings_type.h:594
CC_EXPRESS
@ CC_EXPRESS
Express cargo (Goods, Food, Candy, but also possible for passengers)
Definition: cargotype.h:52
RandomizedSpriteGroup::var_scope
VarSpriteGroupScope var_scope
Take this object:
Definition: newgrf_spritegroup.h:193
SPR_ROAD_WAYPOINTS_BASE
static const SpriteID SPR_ROAD_WAYPOINTS_BASE
Road waypoint sprites.
Definition: sprites.h:311
GCF_INVALID
@ GCF_INVALID
GRF is unusable with this version of OpenTTD.
Definition: newgrf_config.h:30
NFO_UTF8_IDENTIFIER
static const char32_t NFO_UTF8_IDENTIFIER
This character (thorn) indicates a unicode string to NFO.
Definition: newgrf_text_type.h:14
AllocateRoadType
RoadType AllocateRoadType(RoadTypeLabel label, RoadTramType rtt)
Allocate a new road type label.
Definition: road_cmd.cpp:134
IndustryTileLayout
std::vector< IndustryTileLayoutTile > IndustryTileLayout
A complete tile layout for an industry is a list of tiles.
Definition: industrytype.h:96
GCF_INIT_ONLY
@ GCF_INIT_ONLY
GRF file is processed up to GLS_INIT.
Definition: newgrf_config.h:28
EC_ELECTRIC
@ EC_ELECTRIC
Electric rail engine.
Definition: engine_type.h:36
find_index
int find_index(Container const &container, typename Container::const_reference item)
Helper function to get the index of an item Consider using std::set, std::unordered_set or std::flat_...
Definition: container_func.hpp:41
A5BLOCK_INVALID
@ A5BLOCK_INVALID
unknown/not-implemented type
Definition: newgrf_act5.h:17
RailVehicleInfo::cost_factor
uint8_t cost_factor
Purchase cost factor; For multiheaded engines the sum of both engine prices.
Definition: engine_type.h:45
ReadSpriteLayoutRegisters
static void ReadSpriteLayoutRegisters(ByteReader &buf, TileLayoutFlags flags, bool is_parent, NewGRFSpriteLayout *dts, uint index)
Preprocess the TileLayoutFlags and read register modifiers from the GRF.
Definition: newgrf.cpp:809
DeterministicSpriteGroupAdjust::parameter
uint8_t parameter
Used for variables between 0x60 and 0x7F inclusive.
Definition: newgrf_spritegroup.h:151
FinaliseCargoArray
void FinaliseCargoArray()
Check for invalid cargoes.
Definition: newgrf.cpp:9259
BridgeSpec
Struct containing information about a single bridge type.
Definition: bridge.h:42
HandleNode
static bool HandleNode(uint8_t type, uint32_t id, ByteReader &buf, AllowedSubtags subtags[])
Handle the nodes of an Action14.
Definition: newgrf.cpp:8549
IndustrySpec::closure_text
StringID closure_text
Message appearing when the industry closes.
Definition: industrytype.h:125
RailTypeInfo::compatible_railtypes
RailTypes compatible_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype can physically travel
Definition: rail.h:191
Engine::GetGRF
const GRFFile * GetGRF() const
Retrieve the NewGRF the engine is tied to.
Definition: engine_base.h:167
GrfProcessingState::SpriteSet::sprite
SpriteID sprite
SpriteID of the first sprite of the set.
Definition: newgrf.cpp:93
GRFFile::traininfo_vehicle_pitch
int traininfo_vehicle_pitch
Vertical offset for drawing train images in depot GUI and vehicle details.
Definition: newgrf.h:146
AirportTileSpec::ResetAirportTiles
static void ResetAirportTiles()
This function initializes the tile array of AirportTileSpec.
Definition: newgrf_airporttiles.cpp:58
TLF_KNOWN_FLAGS
@ TLF_KNOWN_FLAGS
Known flags. Any unknown set flag will disable the GRF.
Definition: newgrf_commons.h:49
DrawTileSprites::ground
PalSpriteID ground
Palette and sprite for the ground.
Definition: sprite.h:59
TileLayoutRegisters::sprite_var10
uint8_t sprite_var10
Value for variable 10 when resolving the sprite.
Definition: newgrf_commons.h:101
AirportTileSpec
Defines the data structure of each individual tile of an airport.
Definition: newgrf_airporttiles.h:68
GrfProcessingState::GetNumEnts
uint GetNumEnts(uint8_t feature, uint set) const
Returns the number of sprites in a spriteset.
Definition: newgrf.cpp:191
NETWORK_MAX_GRF_COUNT
static const uint NETWORK_MAX_GRF_COUNT
Maximum number of GRFs that can be sent.
Definition: config.h:91
SoundEntry::grf_container_ver
uint8_t grf_container_ver
NewGRF container version if the sound is from a NewGRF.
Definition: sound_type.h:22
RailTypeInfo::name
StringID name
Name of this rail type.
Definition: rail.h:176
EC_MAGLEV
@ EC_MAGLEV
Maglev engine.
Definition: engine_type.h:38
GRFTempEngineData::Refittability
Refittability
Summary state of refittability properties.
Definition: newgrf.cpp:317
NamePartList::bitstart
uint8_t bitstart
Start of random seed bits to use.
Definition: newgrf_townname.h:25
newgrf_airporttiles.h
GameSettings::order
OrderSettings order
settings related to orders
Definition: settings_type.h:601
RealSpriteGroup::loading
std::vector< const SpriteGroup * > loading
List of loading groups (can be SpriteIDs or Callback results)
Definition: newgrf_spritegroup.h:90
Pool::PoolItem<&_engine_pool >::GetPoolSize
static size_t GetPoolSize()
Returns first unused index.
Definition: pool_type.hpp:360
ObjectSpec::BindToClasses
static void BindToClasses()
Tie all ObjectSpecs to their class.
Definition: newgrf_object.cpp:111
InitGRFTownGeneratorNames
void InitGRFTownGeneratorNames()
Allocate memory for the NewGRF town names.
Definition: newgrf_townname.cpp:81
GRFP_GRF_DOS
@ GRFP_GRF_DOS
The NewGRF says the DOS palette can be used.
Definition: newgrf_config.h:71
TextHandler
bool(* TextHandler)(uint8_t, std::string_view str)
Type of callback function for text nodes.
Definition: newgrf.cpp:8318
MAX_CATCHMENT
@ MAX_CATCHMENT
Maximum catchment for airports with "modified catchment" enabled.
Definition: station_type.h:86
TileLayoutRegisters::palette
uint8_t palette
Register specifying a signed offset for the palette.
Definition: newgrf_commons.h:94
MAX_NUM_CASES
static const uint8_t MAX_NUM_CASES
Maximum number of supported cases.
Definition: language.h:21
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32_t id, TextHandler handler)
Create a text leaf node.
Definition: newgrf.cpp:8352
GRFLoadedFeatures::has_2CC
bool has_2CC
Set if any vehicle is loaded which uses 2cc (two company colours).
Definition: newgrf.h:178
StringIDMapping::func
std::function< void(StringID)> func
Function for mapping result.
Definition: newgrf.cpp:459
DIR_W
@ DIR_W
West.
Definition: direction_type.h:32
VSG_SCOPE_SELF
@ VSG_SCOPE_SELF
Resolved object itself.
Definition: newgrf_spritegroup.h:100
PROP_ROADVEH_SPEED
@ PROP_ROADVEH_SPEED
Max. speed: 1 unit = 1/0.8 mph = 2 km-ish/h.
Definition: newgrf_properties.h:38
DisableStaticNewGRFInfluencingNonStaticNewGRFs
static void DisableStaticNewGRFInfluencingNonStaticNewGRFs(GRFConfig *c)
Disable a static NewGRF when it is influencing another (non-static) NewGRF as this could cause desync...
Definition: newgrf.cpp:6817
LoadNewGRF
void LoadNewGRF(uint load_index, uint num_baseset)
Load all the NewGRFs.
Definition: newgrf.cpp:10048
ConstructionSettings::train_signal_side
uint8_t train_signal_side
show signals on left / driving / right side
Definition: settings_type.h:388
LoadNewGRFFile
void LoadNewGRFFile(GRFConfig *config, GrfLoadingStage stage, Subdirectory subdir, bool temporary)
Load a particular NewGRF.
Definition: newgrf.cpp:9725
ChangeGRFNumUsedParams
static bool ChangeGRFNumUsedParams(size_t len, ByteReader &buf)
Callback function for 'INFO'->'NPAR' to set the number of valid parameters.
Definition: newgrf.cpp:8136
SHORE_REPLACE_NONE
@ SHORE_REPLACE_NONE
No shore sprites were replaced.
Definition: newgrf.h:165
GRFConfig::version
uint32_t version
NOSAVE: Version a NewGRF can set so only the newest NewGRF is shown.
Definition: newgrf_config.h:162
EconomySettings::station_noise_level
bool station_noise_level
build new airports when the town noise level is still within accepted limits
Definition: settings_type.h:532
RailVehicleInfo
Information about a rail vehicle.
Definition: engine_type.h:42
GRFLoadedFeatures::shore
ShoreReplacement shore
In which way shore sprites were replaced.
Definition: newgrf.h:180
RailTypeInfo::maintenance_multiplier
uint16_t maintenance_multiplier
Cost multiplier for maintenance of this rail type.
Definition: rail.h:221
error_func.h
RoadTypeInfo::powered_roadtypes
RoadTypes powered_roadtypes
bitmask to the OTHER roadtypes on which a vehicle of THIS roadtype generates power
Definition: road.h:122
NUM_AIRPORTTILES_PER_GRF
static const uint NUM_AIRPORTTILES_PER_GRF
Number of airport tiles per NewGRF; limited to 255 to allow extending Action3 with an extended byte l...
Definition: airport.h:21
RailVehicleInfo::engclass
EngineClass engclass
Class of engine for this vehicle.
Definition: engine_type.h:53
GRFParameterInfo::value_names
std::map< uint32_t, GRFTextList > value_names
Names for each value.
Definition: newgrf_config.h:138
BindAirportSpecs
void BindAirportSpecs()
Tie all airportspecs to their class.
Definition: newgrf_airport.cpp:124
CargoSpec::classes
CargoClasses classes
Classes of this cargo type.
Definition: cargotype.h:78
EngineInfo::callback_mask
uint16_t callback_mask
Bitmask of vehicle callbacks that have to be called.
Definition: engine_type.h:156
StaticGRFInfo
static void StaticGRFInfo(ByteReader &buf)
Handle Action 0x14.
Definition: newgrf.cpp:8602
DefineGotoLabel
static void DefineGotoLabel(ByteReader &buf)
Action 0x10 - Define goto label.
Definition: newgrf.cpp:7836
LoadNextSprite
bool LoadNextSprite(int load_index, SpriteFile &file, uint file_sprite_id)
Load a real or recolour sprite.
Definition: spritecache.cpp:618
AircraftVehicleInfo::subtype
uint8_t subtype
Type of aircraft.
Definition: engine_type.h:104
A5BLOCK_ALLOW_OFFSET
@ A5BLOCK_ALLOW_OFFSET
Allow replacing any subset by specifiing an offset.
Definition: newgrf_act5.h:16
VE_TYPE_START
@ VE_TYPE_START
First bit used for the type of effect.
Definition: vehicle_base.h:86
GRFParameterInfo::param_nr
uint8_t param_nr
GRF parameter to store content in.
Definition: newgrf_config.h:135
VehicleSettings::freight_trains
uint8_t freight_trains
value to multiply the weight of cargo by
Definition: settings_type.h:504
GRFFile::tramtype_list
std::vector< RoadTypeLabel > tramtype_list
Roadtype translation table (tram)
Definition: newgrf.h:139
BSWAP32
static uint32_t BSWAP32(uint32_t x)
Perform a 32 bits endianness bitswap on x.
Definition: bitmath_func.hpp:364
CommonVehicleChangeInfo
static ChangeInfoResult CommonVehicleChangeInfo(EngineInfo *ei, int prop, ByteReader &buf)
Define properties common to all vehicles.
Definition: newgrf.cpp:1009
SetBitIterator
Iterable ensemble of each set bit in a value.
Definition: bitmath_func.hpp:301
PROP_AIRCRAFT_CARGO_AGE_PERIOD
@ PROP_AIRCRAFT_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:54
NEW_INDUSTRYOFFSET
static const IndustryType NEW_INDUSTRYOFFSET
original number of industry types
Definition: industry_type.h:25
GCF_UNSAFE
@ GCF_UNSAFE
GRF file is unsafe for static usage.
Definition: newgrf_config.h:24
GCS_INITIALISED
@ GCS_INITIALISED
GRF file has been initialised.
Definition: newgrf_config.h:38
GRFConfig
Information about GRF, used in the game and (part of it) in savegames.
Definition: newgrf_config.h:147
NUM_HOUSES
static const HouseID NUM_HOUSES
Total number of houses.
Definition: house.h:29
CargoSpec::weight
uint8_t weight
Weight of a single unit of this cargo type in 1/16 ton (62.5 kg).
Definition: cargotype.h:76
newgrf_engine.h
PROP_ROADVEH_CARGO_AGE_PERIOD
@ PROP_ROADVEH_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:40
MAX_BRIDGES
static const uint MAX_BRIDGES
Maximal number of available bridge specs.
Definition: bridge.h:35
StringIDMapping::source
StringID source
Source StringID (GRF local).
Definition: newgrf.cpp:458
Action5Type::name
const std::string_view name
Name for error messages.
Definition: newgrf_act5.h:26
ShipVehicleInfo::visual_effect
uint8_t visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:76
SetPriceBaseMultiplier
void SetPriceBaseMultiplier(Price price, int factor)
Change a price base by the given factor.
Definition: economy.cpp:902
IndustrySpec::conflicting
IndustryType conflicting[3]
Industries this industry cannot be close to.
Definition: industrytype.h:106
MapNewGRFIndustryType
IndustryType MapNewGRFIndustryType(IndustryType grf_type, uint32_t grf_id)
Map the GRF local type to an industry type.
Definition: newgrf_industries.cpp:40
TLF_BB_XY_OFFSET
@ TLF_BB_XY_OFFSET
Add signed offset to bounding box X and Y positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:40
GetGRFSpriteOffset
size_t GetGRFSpriteOffset(uint32_t id)
Get the file offset for a specific sprite in the sprite section of a GRF.
Definition: spritecache.cpp:553
OverrideManagerBase::ResetMapping
void ResetMapping()
Resets the mapping, which is used while initializing game.
Definition: newgrf_commons.cpp:72
FinaliseIndustriesArray
static void FinaliseIndustriesArray()
Add all new industries to the industry array.
Definition: newgrf.cpp:9438
TLF_CHILD_Y_OFFSET
@ TLF_CHILD_Y_OFFSET
Add signed offset to child sprite Y positions from register TileLayoutRegisters::delta....
Definition: newgrf_commons.h:44
GRFP_GRF_ANY
@ GRFP_GRF_ANY
The NewGRF says any palette can be used.
Definition: newgrf_config.h:73
GCF_SYSTEM
@ GCF_SYSTEM
GRF file is an openttd-internal system grf.
Definition: newgrf_config.h:23
NEW_HOUSE_OFFSET
static const HouseID NEW_HOUSE_OFFSET
Offset for new houses.
Definition: house.h:28
IgnoreObjectProperty
static ChangeInfoResult IgnoreObjectProperty(uint prop, ByteReader &buf)
Ignore properties for objects.
Definition: newgrf.cpp:4067
CallbackResultSpriteGroup
Definition: newgrf_spritegroup.h:210
ChangeGRFURL
static bool ChangeGRFURL(uint8_t langid, std::string_view str)
Callback function for 'INFO'->'URL_' to set the newgrf url.
Definition: newgrf.cpp:8129
CargoSpec::units_volume
StringID units_volume
Name of a single unit of cargo of this type.
Definition: cargotype.h:90
CargoSpec::IsValid
bool IsValid() const
Tests for validity of this cargospec.
Definition: cargotype.h:115
ChangeGRFPalette
static bool ChangeGRFPalette(size_t len, ByteReader &buf)
Callback function for 'INFO'->'PALS' to set the number of valid parameters.
Definition: newgrf.cpp:8148
RoadTypeInfo::maintenance_multiplier
uint16_t maintenance_multiplier
Cost multiplier for maintenance of this road type.
Definition: road.h:137
IndustryProductionSpriteGroup::version
uint8_t version
Production callback version used, or 0xFF if marked invalid.
Definition: newgrf_spritegroup.h:272
HouseSpec::building_flags
BuildingFlags building_flags
some flags that describe the house (size, stadium etc...)
Definition: house.h:105
GetFileByFilename
static GRFFile * GetFileByFilename(const std::string &filename)
Obtain a NewGRF file by its filename.
Definition: newgrf.cpp:412
ConstructionSettings::map_height_limit
uint8_t map_height_limit
the maximum allowed heightlevel
Definition: settings_type.h:382
RoadVehicleInfo
Information about a road vehicle.
Definition: engine_type.h:114
DrawTileSeqStruct::delta_z
int8_t delta_z
0x80 identifies child sprites
Definition: sprite.h:28
EngineIDMapping::grfid
uint32_t grfid
The GRF ID of the file the entity belongs to.
Definition: engine_base.h:193
IndustryProductionSpriteGroup
Definition: newgrf_spritegroup.h:269
TimerGameCalendar::ConvertYMDToDate
static Date ConvertYMDToDate(Year year, Month month, Day day)
Converts a tuple of Year, Month and Day to a Date.
Definition: timer_game_calendar.cpp:55
SPRITE_MODIFIER_OPAQUE
@ SPRITE_MODIFIER_OPAQUE
Set when a sprite must not ever be displayed transparently.
Definition: sprites.h:1548
INDUSTRYTILE_NOANIM
static const IndustryGfx INDUSTRYTILE_NOANIM
flag to mark industry tiles as having no animation
Definition: industry_type.h:31
INVALID_INDUSTRYTILE
static const IndustryGfx INVALID_INDUSTRYTILE
one above amount is considered invalid
Definition: industry_type.h:34
RailTypeInfo::fallback_railtype
uint8_t fallback_railtype
Original railtype number to use when drawing non-newgrf railtypes, or when drawing stations.
Definition: rail.h:201
EF_USES_2CC
@ EF_USES_2CC
Vehicle uses two company colours.
Definition: engine_type.h:170
SHORE_REPLACE_ONLY_NEW
@ SHORE_REPLACE_ONLY_NEW
Only corner-shores were loaded by Action5 (openttd(w/d).grf only).
Definition: newgrf.h:168
BridgeSpec::transport_name
StringID transport_name[2]
description of the bridge, when built for road or rail
Definition: bridge.h:51
TPE_PASSENGERS
@ TPE_PASSENGERS
Cargo behaves passenger-like for production.
Definition: cargotype.h:36
_cargo_mask
CargoTypes _cargo_mask
Bitmask of cargo types available.
Definition: cargotype.cpp:31
LiveryScheme
LiveryScheme
List of different livery schemes.
Definition: livery.h:21
SP_CUSTOM
@ SP_CUSTOM
No profile, special "custom" highscore.
Definition: settings_type.h:46
IndustrySpec::production_up_text
StringID production_up_text
Message appearing when the industry's production is increasing.
Definition: industrytype.h:126
NUM_AIRPORTS_PER_GRF
@ NUM_AIRPORTS_PER_GRF
Maximal number of airports per NewGRF.
Definition: airport.h:40
VEH_SHIP
@ VEH_SHIP
Ship vehicle type.
Definition: vehicle_type.h:26
CleanUpStrings
void CleanUpStrings()
House cleaning.
Definition: newgrf_text.cpp:682
RailTypeInfo::toolbar_caption
StringID toolbar_caption
Caption in the construction toolbar GUI for this rail type.
Definition: rail.h:177
EnsureEarlyHouse
static void EnsureEarlyHouse(HouseZones bitmask)
Make sure there is at least one house available in the year 0 for the given climate / housezone combi...
Definition: newgrf.cpp:9335
CC_REFRIGERATED
@ CC_REFRIGERATED
Refrigerated cargo (Food, Fruit)
Definition: cargotype.h:57
GrfProcessingState::SpriteSet
Definition of a single Action1 spriteset.
Definition: newgrf.cpp:92
LoadNewGRFFileFromFile
static void LoadNewGRFFileFromFile(GRFConfig *config, GrfLoadingStage stage, SpriteFile &file)
Load a particular NewGRF from a SpriteFile.
Definition: newgrf.cpp:9636
CargoSpec::grffile
const struct GRFFile * grffile
NewGRF where #group belongs to.
Definition: cargotype.h:96
SanitizeSpriteOffset
static uint16_t SanitizeSpriteOffset(uint16_t &num, uint16_t offset, int max_sprites, const std::string_view name)
Sanitize incoming sprite offsets for Action 5 graphics replacements.
Definition: newgrf.cpp:6366
EC_DIESEL
@ EC_DIESEL
Diesel rail engine.
Definition: engine_type.h:35
SpriteGroupCargo::SG_DEFAULT
static constexpr CargoID SG_DEFAULT
Default type used when no more-specific cargo matches.
Definition: newgrf_cargo.h:23
StationSettings::never_expire_airports
bool never_expire_airports
never expire airports
Definition: settings_type.h:569
AfterLoadGRFs
static void AfterLoadGRFs()
Finish loading NewGRFs and execute needed post-processing.
Definition: newgrf.cpp:9929
_cur_parameter
static GRFParameterInfo * _cur_parameter
The parameter which info is currently changed by the newgrf.
Definition: newgrf.cpp:8228
TileLayoutRegisters::max_palette_offset
uint16_t max_palette_offset
Maximum offset to add to the palette. (limited by size of the spriteset)
Definition: newgrf_commons.h:96
RoadTypeInfo::group
const SpriteGroup * group[ROTSG_END]
Sprite groups for resolving sprites.
Definition: road.h:192
SHORE_REPLACE_ACTION_5
@ SHORE_REPLACE_ACTION_5
Shore sprites were replaced by Action5.
Definition: newgrf.h:166
StringIDMapping
Information for mapping static StringIDs.
Definition: newgrf.cpp:456
MAX_NUM_GENDERS
static const uint8_t MAX_NUM_GENDERS
Maximum number of supported genders.
Definition: language.h:20
StationSpec::TileFlags::Blocked
@ Blocked
Tile is blocked to vehicles.
RoadVehicleInfo::air_drag
uint8_t air_drag
Coefficient of air drag.
Definition: engine_type.h:125
_settings_game
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:57
ChangeGRFParamMask
static bool ChangeGRFParamMask(size_t len, ByteReader &buf)
Callback function for 'INFO'->'PARAM'->param_num->'MASK' to set the parameter and bits to use.
Definition: newgrf.cpp:8284
NUM_INDUSTRYTILES_PER_GRF
static const IndustryGfx NUM_INDUSTRYTILES_PER_GRF
Maximum number of industry tiles per NewGRF; limited to 255 to allow extending Action3 with an extend...
Definition: industry_type.h:29
ValidateIndustryLayout
static bool ValidateIndustryLayout(const IndustryTileLayout &layout)
Validate the industry layout; e.g.
Definition: newgrf.cpp:3508
RailTypeInfo::label
RailTypeLabel label
Unique 32 bit rail type identifier.
Definition: rail.h:236
timer_game_tick.h
TimerGameConst< struct Calendar >::ORIGINAL_MAX_YEAR
static constexpr TimerGame< struct Calendar >::Year ORIGINAL_MAX_YEAR
The maximum year of the original TTD.
Definition: timer_game_common.h:167
RoadTypeInfo::alternate_labels
RoadTypeLabelList alternate_labels
Road type labels this type provides in addition to the main label.
Definition: road.h:152
RoadTypeChangeInfo
static ChangeInfoResult RoadTypeChangeInfo(uint id, int numinfo, int prop, ByteReader &buf, RoadTramType rtt)
Define properties for roadtypes.
Definition: newgrf.cpp:4462
_water_feature
WaterFeature _water_feature[CF_END]
Table of canal 'feature' sprite groups.
Definition: newgrf_canal.cpp:21
PriceBaseSpec::fallback_price
Price fallback_price
Fallback price multiplier for new prices but old grfs.
Definition: economy_type.h:211
GRFParameterInfo
Information about one grf parameter.
Definition: newgrf_config.h:127
CargoSpec::sprite
SpriteID sprite
Icon to display this cargo type, may be 0xFFF (which means to resolve an action123 chain).
Definition: cargotype.h:94
RoadType
RoadType
The different roadtypes we support.
Definition: road_type.h:25
GRFConfig::error
std::optional< GRFError > error
NOSAVE: Error/Warning during GRF loading (Action 0x0B)
Definition: newgrf_config.h:160
ANIM_STATUS_NO_ANIMATION
static const uint8_t ANIM_STATUS_NO_ANIMATION
There is no animation.
Definition: newgrf_animation_type.h:15
GameSettings::economy
EconomySettings economy
settings to change the economy
Definition: settings_type.h:603
DrawTileSeqStruct::IsTerminator
bool IsTerminator() const
Check whether this is a sequence terminator.
Definition: sprite.h:41
EngineInfo::climates
uint8_t climates
Climates supported by the engine.
Definition: engine_type.h:150
PROP_SHIP_CARGO_AGE_PERIOD
@ PROP_SHIP_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:47
GRFFile::language_map
std::unordered_map< uint8_t, LanguageMap > language_map
Mappings related to the languages.
Definition: newgrf.h:144
GRFParameterInfo::first_bit
uint8_t first_bit
First bit to use in the GRF parameter.
Definition: newgrf_config.h:136
NewGRFSpriteLayout
NewGRF supplied spritelayout.
Definition: newgrf_commons.h:112
StationSpec::TileFlags::NoWires
@ NoWires
Tile should NOT contain catenary wires.
MAX_LANG
static const uint MAX_LANG
Maximum number of languages supported by the game, and the NewGRF specs.
Definition: strings_type.h:19
CargoChangeInfo
static ChangeInfoResult CargoChangeInfo(uint cid, int numinfo, int prop, ByteReader &buf)
Define properties for cargoes.
Definition: newgrf.cpp:3031
TimerGameCalendar::ConvertDateToYMD
static YearMonthDay ConvertDateToYMD(Date date)
Converts a Date to a Year, Month & Day.
Definition: timer_game_calendar.cpp:42
safeguards.h
RoadVehicleInfo::power
uint8_t power
Power in 10hp units.
Definition: engine_type.h:123
EngineIDMapping::substitute_id
uint8_t substitute_id
The (original) entity ID to use if this GRF is not available (currently not used)
Definition: engine_base.h:196
AircraftVehicleInfo::mail_capacity
uint8_t mail_capacity
Mail capacity (bags).
Definition: engine_type.h:108
ObjectOverrideManager::SetEntitySpec
void SetEntitySpec(ObjectSpec *spec)
Method to install the new object data in its proper slot The slot assignment is internal of this meth...
Definition: newgrf_commons.cpp:302
GameCreationSettings::starting_year
TimerGameCalendar::Year starting_year
starting date
Definition: settings_type.h:353
lengthof
#define lengthof(array)
Return the length of an fixed size array.
Definition: stdafx.h:280
GRFP_BLT_32BPP
@ GRFP_BLT_32BPP
The NewGRF prefers a 32 bpp blitter.
Definition: newgrf_config.h:77
ImportGRFSound
static void ImportGRFSound(SoundEntry *sound)
Process a sound import from another GRF file.
Definition: newgrf.cpp:7854
CreateGroupFromGroupID
static const SpriteGroup * CreateGroupFromGroupID(uint8_t feature, uint8_t setid, uint8_t type, uint16_t spriteid)
Helper function to either create a callback or a result sprite group.
Definition: newgrf.cpp:5158
GRFConfig::has_param_defaults
bool has_param_defaults
NOSAVE: did this newgrf specify any defaults for it's parameters.
Definition: newgrf_config.h:172
GRFFile::param_end
uint param_end
one more than the highest set parameter
Definition: newgrf.h:126
TLR_MAX_VAR10
static const uint TLR_MAX_VAR10
Maximum value for var 10.
Definition: newgrf_commons.h:105
EngineDisplayFlags::IsFolded
@ IsFolded
Set if display of variants should be folded (hidden).
GrfProcessingState
Temporary data during loading of GRFs.
Definition: newgrf.cpp:89
IndustryProductionSpriteGroup::subtract_input
int16_t subtract_input[INDUSTRY_NUM_INPUTS]
Take this much of the input cargo (can be negative, is indirect in cb version 1+)
Definition: newgrf_spritegroup.h:274
SPRITE_MODIFIER_CUSTOM_SPRITE
@ SPRITE_MODIFIER_CUSTOM_SPRITE
Set when a sprite originates from an Action 1.
Definition: sprites.h:1547
_tags_root
AllowedSubtags _tags_root[]
Action14 root tags.
Definition: newgrf.cpp:8497
RailVehicleInfo::ai_passenger_only
uint8_t ai_passenger_only
Bit value to tell AI that this engine is for passenger use only.
Definition: engine_type.h:55
FinaliseObjectsArray
static void FinaliseObjectsArray()
Add all new objects to the object array.
Definition: newgrf.cpp:9512
GRFTempEngineData::EMPTY
@ EMPTY
GRF defined vehicle as not-refittable. The vehicle shall only carry the default cargo.
Definition: newgrf.cpp:319
GRFTownName::partlists
std::vector< NamePartList > partlists[MAX_LISTS]
Lists of town name parts.
Definition: newgrf_townname.h:43
NamePart::text
std::string text
If probability bit 7 is clear.
Definition: newgrf_townname.h:19
DrawTileSprites
Ground palette sprite of a tile, together with its sprite layout.
Definition: sprite.h:58
RoadStopSpec::grf_prop
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
Definition: newgrf_roadstop.h:142
_networking
bool _networking
are we in networking mode?
Definition: network.cpp:65
TPE_NONE
@ TPE_NONE
Town will not produce this cargo type.
Definition: cargotype.h:35
TTDPAirportType
TTDPAirportType
Allow incrementing of AirportClassID variables.
Definition: newgrf_airport.h:83
HouseSpec::population
uint8_t population
population (Zero on other tiles in multi tile house.)
Definition: house.h:97
WaterFeature::callback_mask
uint8_t callback_mask
Bitmask of canal callbacks that have to be called.
Definition: newgrf_canal.h:25
CargoSpec::callback_mask
uint8_t callback_mask
Bitmask of cargo callbacks that have to be called.
Definition: cargotype.h:86
NewGRFClass::Reset
static void Reset()
Reset the classes, i.e.
Definition: newgrf_class_func.h:16
GRFTextList
std::vector< GRFText > GRFTextList
A GRF text with a list of translations.
Definition: newgrf_text_type.h:23
newgrf_text.h
road.h
INVALID_ROADTYPE
@ INVALID_ROADTYPE
flag for invalid roadtype
Definition: road_type.h:30
RoadVehicleInfo::tractive_effort
uint8_t tractive_effort
Coefficient of tractive effort.
Definition: engine_type.h:124
RoadTypeInfo::name
StringID name
Name of this rail type.
Definition: road.h:103
error.h
INVALID_TPE
@ INVALID_TPE
Invalid town production effect.
Definition: cargotype.h:44
OverrideManagerBase::AddEntityID
virtual uint16_t AddEntityID(uint16_t grf_local_id, uint32_t grfid, uint16_t substitute_id)
Reserves a place in the mapping array for an entity to be installed.
Definition: newgrf_commons.cpp:109
CargoSpec::is_freight
bool is_freight
Cargo type is considered to be freight (affects train freight multiplier).
Definition: cargotype.h:82
RailTypeInfo::cost_multiplier
uint16_t cost_multiplier
Cost multiplier for building this rail type.
Definition: rail.h:216
ChangeGRFVersion
static bool ChangeGRFVersion(size_t len, ByteReader &buf)
Callback function for 'INFO'->'VRSN' to the version of the NewGRF.
Definition: newgrf.cpp:8196
TimerGameConst< struct Calendar >::MAX_YEAR
static constexpr TimerGame< struct Calendar >::Year MAX_YEAR
MAX_YEAR, nicely rounded value of the number of years that can be encoded in a single 32 bits date,...
Definition: timer_game_common.h:173
GRFTempEngineData::ctt_exclude_mask
CargoTypes ctt_exclude_mask
Cargo types always excluded from the refit mask.
Definition: newgrf.cpp:331
GRFTempEngineData::defaultcargo_grf
const GRFFile * defaultcargo_grf
GRF defining the cargo translation table to use if the default cargo is the 'first refittable'.
Definition: newgrf.cpp:327
ResetCurrencies
void ResetCurrencies(bool preserve_custom)
Will fill _currency_specs array with default values from origin_currency_specs Called only from newgr...
Definition: currency.cpp:160
EngineIDMapping
Definition: engine_base.h:192
TAE_PASSENGERS
@ TAE_PASSENGERS
Cargo behaves passenger-like.
Definition: cargotype.h:24
GRFP_GRF_MASK
@ GRFP_GRF_MASK
Bitmask to get only the NewGRF supplied information.
Definition: newgrf_config.h:74
_loaded_newgrf_features
GRFLoadedFeatures _loaded_newgrf_features
Indicates which are the newgrf features currently loaded ingame.
Definition: newgrf.cpp:84
Pool::CleanPool
void CleanPool() override
Virtual method that deletes all items in the pool.
RoadTypeInfo::sorting_order
uint8_t sorting_order
The sorting order of this roadtype for the toolbar dropdown.
Definition: road.h:182
language.h
GrfProcessingState::AddSpriteSets
void AddSpriteSets(uint8_t feature, SpriteID first_sprite, uint first_set, uint numsets, uint numents)
Records new spritesets.
Definition: newgrf.cpp:138
RoadTypeInfo::cost_multiplier
uint16_t cost_multiplier
Cost multiplier for building this road type.
Definition: road.h:132
newgrf_roadstop.h
RandomAccessFile::filename
std::string filename
Full name of the file; relative path to subdir plus the extension of the file.
Definition: random_access_file_type.h:26
CargoSpec::bitnum
uint8_t bitnum
Cargo bit number, is INVALID_CARGO_BITNUM for a non-used spec.
Definition: cargotype.h:73
GetActiveCargoLabel
static CargoLabel GetActiveCargoLabel(const std::initializer_list< CargoLabel > &labels)
Find first cargo label that exists and is active from a list of cargo labels.
Definition: newgrf.cpp:8973
GRFFile::traininfo_vehicle_width
uint traininfo_vehicle_width
Width (in pixels) of a 8/8 train vehicle in depot GUI and vehicle details.
Definition: newgrf.h:147
GetGRFStringID
StringID GetGRFStringID(uint32_t grfid, StringID stringid)
Returns the index for this stringid associated with its grfID.
Definition: newgrf_text.cpp:587
SoundEntry
Definition: sound_type.h:13
RailVehicleInfo::user_def_data
uint8_t user_def_data
Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles.
Definition: engine_type.h:62
stdafx.h
GrfProcessingState::grfconfig
GRFConfig * grfconfig
Config of the currently processed GRF file.
Definition: newgrf.cpp:108
TLF_NON_GROUND_FLAGS
@ TLF_NON_GROUND_FLAGS
Flags which do not work for the (first) ground sprite.
Definition: newgrf_commons.h:55
ShipVehicleInfo::ocean_speed_frac
uint8_t ocean_speed_frac
Fraction of maximum speed for ocean tiles.
Definition: engine_type.h:77
RailTypeInfo::grffile
const GRFFile * grffile[RTSG_END]
NewGRF providing the Action3 for the railtype.
Definition: rail.h:276
landscape.h
OTTDByteReaderSignal
Definition: newgrf.cpp:213
PROP_AIRCRAFT_COST_FACTOR
@ PROP_AIRCRAFT_COST_FACTOR
Purchase cost.
Definition: newgrf_properties.h:49
SpriteFile::GetContainerVersion
uint8_t GetContainerVersion() const
Get the version number of container type used by the file.
Definition: sprite_file_type.hpp:38
IndustrySpec
Defines the data structure for constructing industry.
Definition: industrytype.h:101
SpriteID
uint32_t SpriteID
The number of a sprite, without mapping bits and colourtables.
Definition: gfx_type.h:18
PROP_TRAIN_CURVE_SPEED_MOD
@ PROP_TRAIN_CURVE_SPEED_MOD
Modifier to maximum speed in curves.
Definition: newgrf_properties.h:31
IndustryTileSpec::grf_prop
GRFFileProps grf_prop
properties related to the grf file
Definition: industrytype.h:165
SPR_RAILTYPE_TUNNEL_BASE
static const SpriteID SPR_RAILTYPE_TUNNEL_BASE
Tunnel sprites with grass only for custom railtype tunnel.
Definition: sprites.h:299
EngineClass
EngineClass
Type of rail engine.
Definition: engine_type.h:33
PALETTE_MODIFIER_TRANSPARENT
@ PALETTE_MODIFIER_TRANSPARENT
when a sprite is to be displayed transparently, this bit needs to be set.
Definition: sprites.h:1549
NEWGRF_DIR
@ NEWGRF_DIR
Subdirectory for all NewGRFs.
Definition: fileio_type.h:124
GRFTempEngineData::refittability
Refittability refittability
Did the newgrf set any refittability property? If not, default refittability will be applied.
Definition: newgrf.cpp:328
GRFTownName
Definition: newgrf_townname.h:38
GRFConfig::palette
uint8_t palette
GRFPalette, bitset.
Definition: newgrf_config.h:170
ChangeGRFBlitter
static bool ChangeGRFBlitter(size_t len, ByteReader &buf)
Callback function for 'INFO'->'BLTR' to set the blitter info.
Definition: newgrf.cpp:8174
PROP_SHIP_RUNNING_COST_FACTOR
@ PROP_SHIP_RUNNING_COST_FACTOR
Yearly runningcost.
Definition: newgrf_properties.h:46
IndustryProductionSpriteGroup::num_input
uint8_t num_input
How many subtract_input values are valid.
Definition: newgrf_spritegroup.h:273
GRFConfig::param_info
std::vector< std::optional< GRFParameterInfo > > param_info
NOSAVE: extra information about the parameters.
Definition: newgrf_config.h:171
RAILVEH_WAGON
@ RAILVEH_WAGON
simple wagon, not motorized
Definition: engine_type.h:29
RealSpriteGroup::loaded
std::vector< const SpriteGroup * > loaded
List of loaded groups (can be SpriteIDs or Callback results)
Definition: newgrf_spritegroup.h:89
LanguageMap::Mapping
Mapping between NewGRF and OpenTTD IDs.
Definition: newgrf_text_type.h:30
VehicleSettings::plane_speed
uint8_t plane_speed
divisor for speed of aircraft
Definition: settings_type.h:503
GetAction5Types
std::span< const Action5Type > GetAction5Types()
Get list of all action 5 types.
Definition: newgrf.cpp:6422
BuildCargoTranslationMap
static void BuildCargoTranslationMap()
Construct the Cargo Mapping.
Definition: newgrf.cpp:8894
WaterFeature::grffile
const GRFFile * grffile
NewGRF where 'group' belongs to.
Definition: newgrf_canal.h:24
GRFFilePropsBase::local_id
uint16_t local_id
id defined by the grf file for this entity
Definition: newgrf_commons.h:311
ShipVehicleInfo::old_refittable
bool old_refittable
Is ship refittable; only used during initialisation. Later use EngineInfo::refit_mask.
Definition: engine_type.h:75
GrfProcessingState::GetSprite
SpriteID GetSprite(uint8_t feature, uint set) const
Returns the first sprite of a spriteset.
Definition: newgrf.cpp:179
BuildIndustriesLegend
void BuildIndustriesLegend()
Fills an array for the industries legends.
Definition: smallmap_gui.cpp:189
newgrf_object.h
RailTypeInfo::max_speed
uint16_t max_speed
Maximum speed for vehicles travelling on this rail type.
Definition: rail.h:231
RailTypeInfo::powered_railtypes
RailTypes powered_railtypes
bitmask to the OTHER railtypes on which an engine of THIS railtype generates power
Definition: rail.h:188
GRFTempEngineData::rv_max_speed
uint8_t rv_max_speed
Temporary storage of RV prop 15, maximum speed in mph/0.8.
Definition: newgrf.cpp:329
RandomAccessFile::GetPos
size_t GetPos() const
Get position in the file.
Definition: random_access_file.cpp:71
FinaliseEngineArray
static void FinaliseEngineArray()
Check for invalid engines.
Definition: newgrf.cpp:9192
GRFParameterType
GRFParameterType
The possible types of a newgrf parameter.
Definition: newgrf_config.h:120
GRFTempEngineData::UNSET
@ UNSET
No properties assigned. Default refit masks shall be activated.
Definition: newgrf.cpp:318
TranslateRefitMask
static CargoTypes TranslateRefitMask(uint32_t refit_mask)
Translate the refit mask.
Definition: newgrf.cpp:955
HZ_ZON5
@ HZ_ZON5
center of town
Definition: house.h:72
_generating_world
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:67
AssignBit
constexpr T AssignBit(T &x, const uint8_t y, bool value)
Assigns a bit in a variable.
Definition: bitmath_func.hpp:200
GCS_UNKNOWN
@ GCS_UNKNOWN
The status of this grf file is unknown.
Definition: newgrf_config.h:35
RailTypeInfo::menu_text
StringID menu_text
Name of this rail type in the main toolbar dropdown.
Definition: rail.h:178
SpriteFile
RandomAccessFile with some extra information specific for sprite files.
Definition: sprite_file_type.hpp:19
ROADTYPE_END
@ ROADTYPE_END
Used for iterations.
Definition: road_type.h:29
DeterministicSpriteGroupAdjust
Definition: newgrf_spritegroup.h:147
HOUSE_ORIGINAL_NUM_ACCEPTS
static const uint HOUSE_ORIGINAL_NUM_ACCEPTS
Original number of accepted cargo types.
Definition: house.h:33
PriceBaseSpec
Describes properties of price bases.
Definition: economy_type.h:207
GRFError::param_value
std::array< uint32_t, 2 > param_value
Values of GRF parameters to show for message and custom_message.
Definition: newgrf_config.h:116
string_func.h
IndustrySpec::enabled
bool enabled
entity still available (by default true).newgrf can disable it, though
Definition: industrytype.h:133
GRFFile::canal_local_properties
CanalProperties canal_local_properties[CF_END]
Canal properties as set by this NewGRF.
Definition: newgrf.h:142
GRFError
Information about why GRF had problems during initialisation.
Definition: newgrf_config.h:109
RoadTypeInfo::grffile
const GRFFile * grffile[ROTSG_END]
NewGRF providing the Action3 for the roadtype.
Definition: road.h:187
NUM_ROADSTOPS_PER_GRF
static const int NUM_ROADSTOPS_PER_GRF
The maximum amount of roadstops a single GRF is allowed to add.
Definition: newgrf_roadstop.h:23
GCS_DISABLED
@ GCS_DISABLED
GRF file is disabled.
Definition: newgrf_config.h:36
CIR_DISABLED
@ CIR_DISABLED
GRF was disabled due to error.
Definition: newgrf.cpp:994
RandomAccessFile::ReadWord
uint16_t ReadWord()
Read a word (16 bits) from the file (in low endian format).
Definition: random_access_file.cpp:124
CT_INVALID
static constexpr CargoLabel CT_INVALID
Invalid cargo type.
Definition: cargo_type.h:71
GRFError::message
StringID message
Default message.
Definition: newgrf_config.h:114
AllocateRailType
RailType AllocateRailType(RailTypeLabel label)
Allocate a new rail type label.
Definition: rail_cmd.cpp:150
GRFParameterInfo::max_value
uint32_t max_value
The maximal value of this parameter.
Definition: newgrf_config.h:133
vehicle_func.h
rev.h
CURRENCY_END
@ CURRENCY_END
always the last item
Definition: currency.h:71
PROP_TRAIN_WEIGHT
@ PROP_TRAIN_WEIGHT
Weight in t (if dualheaded: for each single vehicle)
Definition: newgrf_properties.h:25
PROP_VEHICLE_LOAD_AMOUNT
@ PROP_VEHICLE_LOAD_AMOUNT
Loading speed.
Definition: newgrf_properties.h:19
GRFFile::GRFFile
GRFFile(const struct GRFConfig *config)
Constructor for GRFFile.
Definition: newgrf.cpp:8933
TAE_NONE
@ TAE_NONE
Cargo has no effect.
Definition: cargotype.h:23
CT_PASSENGERS
static constexpr CargoLabel CT_PASSENGERS
Available types of cargo Labels may be re-used between different climates.
Definition: cargo_type.h:30
CargoSpec::town_production_effect
TownProductionEffect town_production_effect
The effect on town cargo production.
Definition: cargotype.h:84
VehicleSettings::dynamic_engines
bool dynamic_engines
enable dynamic allocation of engine data
Definition: settings_type.h:505
newgrf_sound.h
Pool::PoolItem<&_engine_pool >::Iterate
static Pool::IterateWrapper< Titem > Iterate(size_t from=0)
Returns an iterable ensemble of all valid Titem.
Definition: pool_type.hpp:388
ROADTYPE_TRAM
@ ROADTYPE_TRAM
Trams.
Definition: road_type.h:28
GRFConfig::flags
uint8_t flags
NOSAVE: GCF_Flags, bitset.
Definition: newgrf_config.h:164
GRFP_GRF_WINDOWS
@ GRFP_GRF_WINDOWS
The NewGRF says the Windows palette can be used.
Definition: newgrf_config.h:72
strings_func.h
TLF_VAR10_FLAGS
@ TLF_VAR10_FLAGS
Flags which refer to using multiple action-1-2-3 chains.
Definition: newgrf_commons.h:58
TimerGameEconomy::year
static Year year
Current year, starting at 0.
Definition: timer_game_economy.h:35
StationSpec
Station specification.
Definition: newgrf_station.h:115
ParamSet
static void ParamSet(ByteReader &buf)
Action 0x0D: Set parameter.
Definition: newgrf.cpp:7408
AirportSpec::enabled
bool enabled
Entity still available (by default true). Newgrf can disable it, though.
Definition: newgrf_airport.h:120
SetNewGRFOverride
static void SetNewGRFOverride(uint32_t source_grfid, uint32_t target_grfid)
Set the override for a NewGRF.
Definition: newgrf.cpp:593
LanguageMap
Mapping of language data between a NewGRF and OpenTTD.
Definition: newgrf_text_type.h:28
PROP_TRAIN_SHORTEN_FACTOR
@ PROP_TRAIN_SHORTEN_FACTOR
Shorter vehicles.
Definition: newgrf_properties.h:28
FioCheckFileExists
bool FioCheckFileExists(const std::string &filename, Subdirectory subdir)
Check whether the given file exists.
Definition: fileio.cpp:121
bridge.h
EngineIDMapping::internal_id
uint16_t internal_id
The internal ID within the GRF file.
Definition: engine_base.h:194
NEW_AIRPORT_OFFSET
@ NEW_AIRPORT_OFFSET
Number of the first newgrf airport.
Definition: airport.h:39
RandomAccessFile::SkipBytes
void SkipBytes(size_t n)
Skip n bytes ahead in the file.
Definition: random_access_file.cpp:155
EngineInfo::base_life
TimerGameCalendar::Year base_life
Basic duration of engine availability (without random parts). 0xFF means infinite life.
Definition: engine_type.h:147
GameCreationSettings::generation_seed
uint32_t generation_seed
noise seed for world generation
Definition: settings_type.h:352
CargoClasses
uint16_t CargoClasses
Bitmask of cargo classes.
Definition: cargotype.h:64
GRFTempEngineData
Temporary engine data used when loading only.
Definition: newgrf.cpp:315
StationSpec::layouts
std::unordered_map< uint16_t, std::vector< uint8_t > > layouts
Custom platform layouts, keyed by platform and length combined.
Definition: newgrf_station.h:174
ResetNewGRFErrors
static void ResetNewGRFErrors()
Clear all NewGRF errors.
Definition: newgrf.cpp:8771
IsHouseSpecValid
static bool IsHouseSpecValid(HouseSpec *hs, const HouseSpec *next1, const HouseSpec *next2, const HouseSpec *next3, const std::string &filename)
Check if a given housespec is valid and disable it if it's not.
Definition: newgrf.cpp:9289
RoadStopAvailabilityType
RoadStopAvailabilityType
Various different options for availability, restricting the roadstop to be only for busses or for tru...
Definition: newgrf_roadstop.h:49
GRFConfig::name
GRFTextWrapper name
NOSAVE: GRF name (Action 0x08)
Definition: newgrf_config.h:157
ResetNewGRF
static void ResetNewGRF()
Reset and clear all NewGRFs.
Definition: newgrf.cpp:8760
GRFLoadedFeatures::tram
TramReplacement tram
In which way tram depots were replaced.
Definition: newgrf.h:181
AircraftVehicleChangeInfo
static ChangeInfoResult AircraftVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader &buf)
Define properties for aircraft.
Definition: newgrf.cpp:1759
GRFConfig::param
std::array< uint32_t, 0x80 > param
GRF parameters.
Definition: newgrf_config.h:167
GRFParameterInfo::desc
GRFTextList desc
The description of this parameter.
Definition: newgrf_config.h:130
AllowedSubtags
Data structure to store the allowed id/type combinations for action 14.
Definition: newgrf.cpp:8328
RoadVehicleInfo::visual_effect
uint8_t visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:126
FinaliseAirportsArray
static void FinaliseAirportsArray()
Add all new airports to the airport array.
Definition: newgrf.cpp:9530
TileLayoutRegisters::parent
uint8_t parent[3]
Registers for signed offsets for the bounding box position of parent sprites.
Definition: newgrf_commons.h:98
DataHandler
bool(* DataHandler)(size_t, ByteReader &)
Type of callback function for binary nodes.
Definition: newgrf.cpp:8317
SHORE_REPLACE_ACTION_A
@ SHORE_REPLACE_ACTION_A
Shore sprites were replaced by ActionA (using grass tiles for the corner-shores).
Definition: newgrf.h:167
GCF_RESERVED
@ GCF_RESERVED
GRF file passed GLS_RESERVE stage.
Definition: newgrf_config.h:29
NamePartList
Definition: newgrf_townname.h:24
Slope
Slope
Enumeration for the slope-type.
Definition: slope_type.h:48
HZ_SUBARTC_ABOVE
@ HZ_SUBARTC_ABOVE
11 800 can appear in sub-arctic climate above the snow line
Definition: house.h:74
RailTypeInfo::map_colour
uint8_t map_colour
Colour on mini-map.
Definition: rail.h:246
TRAMWAY_REPLACE_DEPOT_WITH_TRACK
@ TRAMWAY_REPLACE_DEPOT_WITH_TRACK
Electrified depot graphics with tram track were loaded.
Definition: newgrf.h:173
abs
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition: math_func.hpp:23
GrfProcessingState::HasValidSpriteSets
bool HasValidSpriteSets(uint8_t feature) const
Check whether there are any valid spritesets for a feature.
Definition: newgrf.cpp:154
MapSpriteMappingRecolour
static void MapSpriteMappingRecolour(PalSpriteID *grf_sprite)
Map the colour modifiers of TTDPatch to those that Open is using.
Definition: newgrf.cpp:720
INDUSTRY_ORIGINAL_NUM_OUTPUTS
static const int INDUSTRY_ORIGINAL_NUM_OUTPUTS
Original number of produced cargo types.
Definition: industry_type.h:41
GetStationLayoutKey
uint16_t GetStationLayoutKey(uint8_t platforms, uint8_t length)
Get the station layout key for a given station layout size.
Definition: newgrf_station.h:189
ConstructionSettings::build_on_slopes
bool build_on_slopes
allow building on slopes
Definition: settings_type.h:383
RealSpriteGroup
Definition: newgrf_spritegroup.h:79
AllowedSubtags::subtags
AllowedSubtags * subtags
Pointer to a list of subtags, only valid if type == 'C' && !call_handler.
Definition: newgrf.cpp:8393
MCT_LIVESTOCK_FRUIT
@ MCT_LIVESTOCK_FRUIT
Cargo can be livestock or fruit.
Definition: cargo_type.h:84
HouseSpec::Get
static HouseSpec * Get(size_t house_id)
Get the spec for a house ID.
Definition: newgrf_house.cpp:69
NewGRFClass::Allocate
static Tindex Allocate(uint32_t global_id)
Allocate a class with a given global class ID.
Definition: newgrf_class_func.h:32
Action5Type::block_type
Action5BlockType block_type
How is this Action5 type processed?
Definition: newgrf_act5.h:22
RandomizedSpriteGroup::lowest_randbit
uint8_t lowest_randbit
Look for this in the per-object randomized bitmask:
Definition: newgrf_spritegroup.h:199
AirportSpec::grf_prop
struct GRFFileProps grf_prop
Properties related to the grf file.
Definition: newgrf_airport.h:121
CargoSpec::quantifier
StringID quantifier
Text for multiple units of cargo of this type.
Definition: cargotype.h:91
SPR_AIRPORT_PREVIEW_BASE
static const SpriteID SPR_AIRPORT_PREVIEW_BASE
Airport preview sprites.
Definition: sprites.h:248
HandleParameterInfo
static bool HandleParameterInfo(ByteReader &buf)
Callback function for 'INFO'->'PARA' to set extra information about the parameters.
Definition: newgrf.cpp:8456
VSG_SCOPE_PARENT
@ VSG_SCOPE_PARENT
Related object of the resolved one.
Definition: newgrf_spritegroup.h:101
GRFConfig::next
struct GRFConfig * next
NOSAVE: Next item in the linked list.
Definition: newgrf_config.h:174
industrytype.h
RAILVEH_MULTIHEAD
@ RAILVEH_MULTIHEAD
indicates a combination of two locomotives
Definition: engine_type.h:28
TimerGame< struct Calendar >::IsLeapYear
static constexpr bool IsLeapYear(Year year)
Checks whether the given year is a leap year or not.
Definition: timer_game_common.h:63
GetEngineLiveryScheme
LiveryScheme GetEngineLiveryScheme(EngineID engine_type, EngineID parent_engine_type, const Vehicle *v)
Determines the LiveryScheme for a vehicle.
Definition: vehicle.cpp:1970
ShipVehicleInfo::acceleration
uint8_t acceleration
Acceleration (1 unit = 1/3.2 mph per tick = 0.5 km-ish/h per tick)
Definition: engine_type.h:70
LanguagePackHeader::GetGenderIndex
uint8_t GetGenderIndex(const char *gender_str) const
Get the index for the given gender.
Definition: language.h:68
InitializeSortedCargoSpecs
void InitializeSortedCargoSpecs()
Initialize the list of sorted cargo specifications.
Definition: cargotype.cpp:201
EngineInfo::variant_id
EngineID variant_id
Engine variant ID. If set, will be treated specially in purchase lists.
Definition: engine_type.h:160
EngineOverrideManager::GetID
EngineID GetID(VehicleType type, uint16_t grf_local_id, uint32_t grfid)
Looks up an EngineID in the EngineOverrideManager.
Definition: engine.cpp:532
SPR_OPENTTD_BASE
static const SpriteID SPR_OPENTTD_BASE
Extra graphic spritenumbers.
Definition: sprites.h:56
SpriteGroupCargo::SG_PURCHASE
static constexpr CargoID SG_PURCHASE
Used in purchase lists before an item exists.
Definition: newgrf_cargo.h:24
SoundEffectChangeInfo
static ChangeInfoResult SoundEffectChangeInfo(uint sid, int numinfo, int prop, ByteReader &buf)
Define properties for sound effects.
Definition: newgrf.cpp:3189
IndustrySpec::production_down_text
StringID production_down_text
Message appearing when the industry's production is decreasing.
Definition: industrytype.h:127
ChangeGRFParamDefault
static bool ChangeGRFParamDefault(size_t len, ByteReader &buf)
Callback function for 'INFO'->'PARAM'->param_num->'DFLT' to set the default value.
Definition: newgrf.cpp:8305
AutoRestoreBackup
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
Definition: backup_type.hpp:150
TRAMWAY_REPLACE_DEPOT_NONE
@ TRAMWAY_REPLACE_DEPOT_NONE
No tram depot graphics were loaded.
Definition: newgrf.h:172
AlterVehicleListOrder
void AlterVehicleListOrder(EngineID engine, uint target)
Record a vehicle ListOrderChange.
Definition: newgrf_engine.cpp:1299
GetNewEngineID
EngineID GetNewEngineID(const GRFFile *file, VehicleType type, uint16_t internal_id)
Return the ID of a new engine.
Definition: newgrf.cpp:703
LanguageMap::GetLanguageMap
static const LanguageMap * GetLanguageMap(uint32_t grfid, uint8_t language_id)
Get the language map associated with a given NewGRF and language.
Definition: newgrf.cpp:2677
TownHouseChangeInfo
static ChangeInfoResult TownHouseChangeInfo(uint hid, int numinfo, int prop, ByteReader &buf)
Define properties for houses.
Definition: newgrf.cpp:2420
GetString
std::string GetString(StringID string)
Resolve the given StringID into a std::string with all the associated DParam lookups and formatting.
Definition: strings.cpp:319
IndustrySpec::grf_prop
GRFFileProps grf_prop
properties related to the grf file
Definition: industrytype.h:134
_ttdpatch_flags
static uint32_t _ttdpatch_flags[8]
32 * 8 = 256 flags.
Definition: newgrf.cpp:81
TRAMWAY_REPLACE_DEPOT_NO_TRACK
@ TRAMWAY_REPLACE_DEPOT_NO_TRACK
Electrified depot graphics without tram track were loaded.
Definition: newgrf.h:174
NewGRFSpriteLayout::consistent_max_offset
uint consistent_max_offset
Number of sprites in all referenced spritesets.
Definition: newgrf_commons.h:119
IsSnowLineSet
bool IsSnowLineSet()
Has a snow line table already been loaded.
Definition: landscape.cpp:579
StationSpec::TileFlags
TileFlags
Definition: newgrf_station.h:163
GRFParameterInfo::name
GRFTextList name
The name of this parameter.
Definition: newgrf_config.h:129
GRFParameterInfo::def_value
uint32_t def_value
Default value of this parameter.
Definition: newgrf_config.h:134
RailVehicleInfo::weight
uint16_t weight
Weight of vehicle (tons); For multiheaded engines the weight of each single engine.
Definition: engine_type.h:50
Pool::PoolItem<&_engine_pool >::CanAllocateItem
static bool CanAllocateItem(size_t n=1)
Helper functions so we can use PoolItem::Function() instead of _poolitem_pool.Function()
Definition: pool_type.hpp:309
INDUSTRY_ORIGINAL_NUM_INPUTS
static const int INDUSTRY_ORIGINAL_NUM_INPUTS
Original number of accepted cargo types.
Definition: industry_type.h:40
IndustryTileLayoutTile
Definition of one tile in an industry tile layout.
Definition: industrytype.h:90
EngineInfo::cargo_age_period
uint16_t cargo_age_period
Number of ticks before carried cargo is aged.
Definition: engine_type.h:159
VehicleSettings::disable_elrails
bool disable_elrails
when true, the elrails are disabled
Definition: settings_type.h:498
TimerGameConst< struct Calendar >::MIN_YEAR
static constexpr TimerGame< struct Calendar >::Year MIN_YEAR
The absolute minimum year in OTTD.
Definition: timer_game_common.h:176
InitNewGRFFile
static void InitNewGRFFile(const GRFConfig *config)
Prepare loading a NewGRF file with its config.
Definition: newgrf.cpp:8916
CommitVehicleListOrderChanges
void CommitVehicleListOrderChanges()
Deternine default engine sorting and execute recorded ListOrderChanges from AlterVehicleListOrder.
Definition: newgrf_engine.cpp:1329
ShipVehicleInfo
Information about a ship vehicle.
Definition: engine_type.h:67
HouseSpec::building_availability
HouseZones building_availability
where can it be built (climates, zones)
Definition: house.h:106
CanalChangeInfo
static ChangeInfoResult CanalChangeInfo(uint id, int numinfo, int prop, ByteReader &buf)
Define properties for water features.
Definition: newgrf.cpp:2204
CargoID
uint8_t CargoID
Cargo slots to indicate a cargo type within a game.
Definition: cargo_type.h:22
MapGRFStringID
StringID MapGRFStringID(uint32_t grfid, StringID str)
Used when setting an object's property to map to the GRF's strings while taking in consideration the ...
Definition: newgrf.cpp:559
RoadTypeFlags
RoadTypeFlags
Roadtype flags.
Definition: road.h:46
Direction
Direction
Defines the 8 directions on the map.
Definition: direction_type.h:24
Subdirectory
Subdirectory
The different kinds of subdirectories OpenTTD uses.
Definition: fileio_type.h:115
TileLayoutFlags
TileLayoutFlags
Flags to enable register usage in sprite layouts.
Definition: newgrf_commons.h:32
CargoSpec::name
StringID name
Name of this type of cargo.
Definition: cargotype.h:88
PROP_ROADVEH_CARGO_CAPACITY
@ PROP_ROADVEH_CARGO_CAPACITY
Capacity.
Definition: newgrf_properties.h:34
RailVehicleInfo::railtype
RailType railtype
Railtype, mangled if elrail is disabled.
Definition: engine_type.h:46
ResetNewGRFData
void ResetNewGRFData()
Reset all NewGRF loaded data.
Definition: newgrf.cpp:8781
GRFFile::cargo_list
std::vector< CargoLabel > cargo_list
Cargo translation table (local ID -> label)
Definition: newgrf.h:130
GrfMsgI
void GrfMsgI(int severity, const std::string &msg)
Debug() function dedicated to newGRF debugging messages Function is essentially the same as Debug(grf...
Definition: newgrf.cpp:389
PalSpriteID
Combination of a palette sprite and a 'real' sprite.
Definition: gfx_type.h:23
GRFConfig::url
GRFTextWrapper url
NOSAVE: URL belonging to this GRF.
Definition: newgrf_config.h:159
GRFFile::labels
std::vector< GRFLabel > labels
List of labels.
Definition: newgrf.h:128
ActivateOldTramDepot
static void ActivateOldTramDepot()
Replocate the old tram depot sprites to the new position, if no new ones were loaded.
Definition: newgrf.cpp:9798
AllowedSubtags::AllowedSubtags
AllowedSubtags(uint32_t id, AllowedSubtags *subtags)
Create a branch node with a list of sub-nodes.
Definition: newgrf.cpp:8377
container_func.hpp
GetLanguage
const LanguageMetadata * GetLanguage(uint8_t newgrflangid)
Get the language with the given NewGRF language ID.
Definition: strings.cpp:2029
ExtraEngineFlags
ExtraEngineFlags
Definition: engine_type.h:131
RoadTypeInfo::strings
struct RoadTypeInfo::@29 strings
Strings associated with the rail type.
GrfProcessingState::stage
GrfLoadingStage stage
Current loading stage.
Definition: newgrf.cpp:102
ORIGINAL_SAMPLE_COUNT
static const uint ORIGINAL_SAMPLE_COUNT
The number of sounds in the original sample.cat.
Definition: sound_type.h:116
_gted
static std::vector< GRFTempEngineData > _gted
Temporary engine data used during NewGRF loading.
Definition: newgrf.cpp:347
CHECK_NOTHING
@ CHECK_NOTHING
Always succeeds.
Definition: industrytype.h:34
RoadVehicleChangeInfo
static ChangeInfoResult RoadVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader &buf)
Define properties for road vehicles.
Definition: newgrf.cpp:1361
NamePart
Definition: newgrf_townname.h:18
IgnoreIndustryTileProperty
static ChangeInfoResult IgnoreIndustryTileProperty(int prop, ByteReader &buf)
Ignore an industry tile property.
Definition: newgrf.cpp:3244
RailVehicleInfo::visual_effect
uint8_t visual_effect
Bitstuffed NewGRF visual effect data.
Definition: engine_type.h:58
CargoSpec::name_single
StringID name_single
Name of a single entity of this type of cargo.
Definition: cargotype.h:89
GRFTownName::MAX_LISTS
static const uint MAX_LISTS
Maximum number of town name lists that can be defined per GRF.
Definition: newgrf_townname.h:39
PTYPE_END
@ PTYPE_END
Invalid parameter type.
Definition: newgrf_config.h:123
AllowedSubtags::id
uint32_t id
The identifier for this node.
Definition: newgrf.cpp:8385
CC_BULK
@ CC_BULK
Bulk cargo (Coal, Grain etc., Ores, Fruit)
Definition: cargotype.h:54
CargoSpec::abbrev
StringID abbrev
Two letter abbreviation for this cargo type.
Definition: cargotype.h:92
NamePartList::bitcount
uint8_t bitcount
Number of bits of random seed to use.
Definition: newgrf_townname.h:26
WaterFeature::flags
uint8_t flags
Flags controlling display.
Definition: newgrf_canal.h:26
RailVehicleInfo::power
uint16_t power
Power of engine (hp); For multiheaded engines the sum of both engine powers.
Definition: engine_type.h:49
FinaliseHouseArray
static void FinaliseHouseArray()
Add all new houses to the house array.
Definition: newgrf.cpp:9360
RailVehicleInfo::intended_railtype
RailType intended_railtype
Intended railtype, regardless of elrail being enabled or disabled.
Definition: engine_type.h:47
BridgeSpec::flags
uint8_t flags
bit 0 set: disable drawing of far pillars.
Definition: bridge.h:53
NamePartList::parts
std::vector< NamePart > parts
List of parts to choose from.
Definition: newgrf_townname.h:28
NewGRFSpriteLayout::Clone
void Clone(const DrawTileSeqStruct *source)
Clone the building sprites of a spritelayout.
Definition: newgrf_commons.cpp:571
TileIndexDiffC::y
int16_t y
The y value of the coordinate.
Definition: map_type.h:33
RandomAccessFile::SeekTo
void SeekTo(size_t pos, int mode)
Seek in the current file.
Definition: random_access_file.cpp:90
RailTypeInfo::introduces_railtypes
RailTypes introduces_railtypes
Bitmask of which other railtypes are introduced when this railtype is introduced.
Definition: rail.h:266
_grfconfig
GRFConfig * _grfconfig
First item in list of current GRF set up.
Definition: newgrf_config.cpp:164
IgnoreRoadStopProperty
static ChangeInfoResult IgnoreRoadStopProperty(uint prop, ByteReader &buf)
Ignore properties for roadstops.
Definition: newgrf.cpp:4770
DrawTileSprites::seq
const DrawTileSeqStruct * seq
Array of child sprites. Terminated with a terminator entry.
Definition: sprite.h:60
CIR_UNKNOWN
@ CIR_UNKNOWN
Variable is unknown.
Definition: newgrf.cpp:996
GRFTempEngineData::NONEMPTY
@ NONEMPTY
GRF defined the vehicle as refittable. If the refitmask is empty after translation (cargotypes not av...
Definition: newgrf.cpp:320
TimerGame< struct Calendar >::DateFract
uint16_t DateFract
The fraction of a date we're in, i.e.
Definition: timer_game_common.h:38
IgnoreTownHouseProperty
static ChangeInfoResult IgnoreTownHouseProperty(int prop, ByteReader &buf)
Ignore a house property.
Definition: newgrf.cpp:2353
BridgeSpec::min_length
uint8_t min_length
the minimum length (not counting start and end tile)
Definition: bridge.h:44
ResetObjects
void ResetObjects()
This function initialize the spec arrays of objects.
Definition: newgrf_object.cpp:121
EngineInfo::retire_early
int8_t retire_early
Number of years early to retire vehicle.
Definition: engine_type.h:157
RAILTYPE_MAGLEV
@ RAILTYPE_MAGLEV
Maglev.
Definition: rail_type.h:32
TileLayoutRegisters::sprite
uint8_t sprite
Register specifying a signed offset for the sprite.
Definition: newgrf_commons.h:93
RoadTypeInfo::max_speed
uint16_t max_speed
Maximum speed for vehicles travelling on this road type.
Definition: road.h:142
GlobalVarChangeInfo
static ChangeInfoResult GlobalVarChangeInfo(uint gvid, int numinfo, int prop, ByteReader &buf)
Define properties for global variables.
Definition: newgrf.cpp:2736
RAILTYPE_MONO
@ RAILTYPE_MONO
Monorail.
Definition: rail_type.h:31
StationSpec::grf_prop
GRFFilePropsBase< NUM_CARGO+3 > grf_prop
Properties related the the grf file.
Definition: newgrf_station.h:127
RailVehicleInfo::max_speed
uint16_t max_speed
Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h)
Definition: engine_type.h:48
Map::LogY
static uint LogY()
Logarithm of the map size along the y side.
Definition: map_func.h:261
InitializeGRFSpecial
static void InitializeGRFSpecial()
Initialize the TTDPatch flags.
Definition: newgrf.cpp:8622
BridgeSpec::avail_year
TimerGameCalendar::Year avail_year
the year where it becomes available
Definition: bridge.h:43
HouseSpec::accepts_cargo_label
CargoLabel accepts_cargo_label[HOUSE_NUM_ACCEPTS]
input landscape cargo slots
Definition: house.h:104
GRFIdentifier::grfid
uint32_t grfid
GRF ID (defined by Action 0x08)
Definition: newgrf_config.h:84
ActivateOldShore
static void ActivateOldShore()
Relocates the old shore sprites at new positions.
Definition: newgrf.cpp:9761
AircraftVehicleInfo::passenger_capacity
uint16_t passenger_capacity
Passenger capacity (persons).
Definition: engine_type.h:109
BridgeSpec::material
StringID material
the string that contains the bridge description
Definition: bridge.h:50
LanguageMap::Mapping::newgrf_id
uint8_t newgrf_id
NewGRF's internal ID for a case/gender.
Definition: newgrf_text_type.h:31
TileLayoutRegisters::flags
TileLayoutFlags flags
Flags defining which members are valid and to be used.
Definition: newgrf_commons.h:91
GRFConfig::num_params
uint8_t num_params
Number of used parameters.
Definition: newgrf_config.h:168
LanguagePackHeader::GetCaseIndex
uint8_t GetCaseIndex(const char *case_str) const
Get the index for the given case.
Definition: language.h:81
newgrf_canal.h
TimerGameConst< struct Calendar >::ORIGINAL_BASE_YEAR
static constexpr TimerGame< struct Calendar >::Year ORIGINAL_BASE_YEAR
The minimum starting year/base year of the original TTD.
Definition: timer_game_common.h:163
TILE_HEIGHT
static const uint TILE_HEIGHT
Height of a height level in world coordinate AND in pixels in #ZOOM_BASE.
Definition: tile_type.h:18
ShipVehicleChangeInfo
static ChangeInfoResult ShipVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader &buf)
Define properties for ships.
Definition: newgrf.cpp:1567
TAE_WATER
@ TAE_WATER
Cargo behaves water-like.
Definition: cargotype.h:27
TileLayoutRegisters::child
uint8_t child[2]
Registers for signed offsets for the position of child sprites.
Definition: newgrf_commons.h:99
AirportSpec::GetWithoutOverride
static AirportSpec * GetWithoutOverride(uint8_t type)
Retrieve airport spec for the given airport.
Definition: newgrf_airport.cpp:75
VehicleSettings::never_expire_vehicles
bool never_expire_vehicles
never expire vehicles
Definition: settings_type.h:506
OverrideManagerBase::Add
void Add(uint16_t local_id, uint32_t grfid, uint entity_type)
Since the entity IDs defined by the GRF file does not necessarily correlate to those used by the game...
Definition: newgrf_commons.cpp:62
HouseSpec
Definition: house.h:93
VehicleType
VehicleType
Available vehicle types.
Definition: vehicle_type.h:21
config.h
GrfProcessingState::SpriteSet::num_sprites
uint num_sprites
Number of sprites in the set.
Definition: newgrf.cpp:94
NEW_AIRPORTTILE_OFFSET
static const uint NEW_AIRPORTTILE_OFFSET
offset of first newgrf airport tile
Definition: airport.h:24
RoadVehicleInfo::weight
uint8_t weight
Weight in 1/4t units.
Definition: engine_type.h:122
VEH_AIRCRAFT
@ VEH_AIRCRAFT
Aircraft vehicle type.
Definition: vehicle_type.h:27
PROP_SHIP_COST_FACTOR
@ PROP_SHIP_COST_FACTOR
Purchase cost.
Definition: newgrf_properties.h:43
ChangeInfoResult
ChangeInfoResult
Possible return values for the FeatureChangeInfo functions.
Definition: newgrf.cpp:992
engine_base.h
IndustryProductionSpriteGroup::cargo_output
CargoID cargo_output[INDUSTRY_NUM_OUTPUTS]
Which output cargoes to add to (only cb version 2)
Definition: newgrf_spritegroup.h:278
SpriteGroupCargo::SG_DEFAULT_NA
static constexpr CargoID SG_DEFAULT_NA
Used only by stations and roads when no more-specific cargo matches.
Definition: newgrf_cargo.h:25
RailTypeInfo::flags
RailTypeFlags flags
Bit mask of rail type flags.
Definition: rail.h:211
fontcache.h
_object_mngr
ObjectOverrideManager _object_mngr
The override manager for our objects.
RandomAccessFile::ReadDword
uint32_t ReadDword()
Read a double word (32 bits) from the file (in low endian format).
Definition: random_access_file.cpp:134
ShipVehicleInfo::max_speed
uint16_t max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
Definition: engine_type.h:71
IsValidCargoID
bool IsValidCargoID(CargoID t)
Test whether cargo type is not INVALID_CARGO.
Definition: cargo_type.h:107
Engine::grf_prop
GRFFilePropsBase< NUM_CARGO+2 > grf_prop
Properties related the the grf file.
Definition: engine_base.h:77
RAILVEH_SINGLEHEAD
@ RAILVEH_SINGLEHEAD
indicates a "standalone" locomotive
Definition: engine_type.h:27
MCT_VALUABLES_GOLD_DIAMONDS
@ MCT_VALUABLES_GOLD_DIAMONDS
Cargo can be valuables, gold or diamonds.
Definition: cargo_type.h:86
GRFFile::GetParam
uint32_t GetParam(uint number) const
Get GRF Parameter with range checking.
Definition: newgrf.h:155
IndustryTileSpecialFlags
IndustryTileSpecialFlags
Flags for miscellaneous industry tile specialities.
Definition: industrytype.h:82
IndustrySpec::accepts_cargo
std::array< CargoID, INDUSTRY_NUM_INPUTS > accepts_cargo
16 accepted cargoes.
Definition: industrytype.h:116
ReadGRFSpriteOffsets
void ReadGRFSpriteOffsets(SpriteFile &file)
Parse the sprite section of GRFs.
Definition: spritecache.cpp:562
GRFParameterInfo::num_bit
uint8_t num_bit
Number of bits to use for this parameter.
Definition: newgrf_config.h:137
SB
constexpr T SB(T &x, const uint8_t s, const uint8_t n, const U d)
Set n bits in x starting at bit s to d.
Definition: bitmath_func.hpp:58
EF_ROAD_TRAM
@ EF_ROAD_TRAM
Road vehicle is a tram/light rail vehicle.
Definition: engine_type.h:169
GetRailTypeByLabel
RailType GetRailTypeByLabel(RailTypeLabel label, bool allow_alternate_labels)
Get the rail type for a given label.
Definition: rail.cpp:311
NEW_INDUSTRYTILEOFFSET
static const IndustryGfx NEW_INDUSTRYTILEOFFSET
original number of tiles
Definition: industry_type.h:32
newgrf_industries.h
PalSpriteID::pal
PaletteID pal
The palette (use PAL_NONE) if not needed)
Definition: gfx_type.h:25
EconomySettings::inflation
bool inflation
disable inflation
Definition: settings_type.h:514
TimerGameCalendar::date
static Date date
Current date in days (day counter).
Definition: timer_game_calendar.h:34
IgnoreIndustryProperty
static ChangeInfoResult IgnoreIndustryProperty(int prop, ByteReader &buf)
Ignore an industry property.
Definition: newgrf.cpp:3418
GameSettings::construction
ConstructionSettings construction
construction of things in-game
Definition: settings_type.h:595
StationSpec::TileFlags::Pylons
@ Pylons
Tile should contain catenary pylons.
GameSettings::vehicle
VehicleSettings vehicle
options for vehicles
Definition: settings_type.h:602
FontSize
FontSize
Available font sizes.
Definition: gfx_type.h:208
EngineID
uint16_t EngineID
Unique identification number of an engine.
Definition: engine_type.h:21
TLF_PALETTE_REG_FLAGS
@ TLF_PALETTE_REG_FLAGS
Flags which require resolving the action-1-2-3 chain for the palette, even if it is no action-1 palet...
Definition: newgrf_commons.h:64
TLF_SPRITE
@ TLF_SPRITE
Add signed offset to sprite from register TileLayoutRegisters::sprite.
Definition: newgrf_commons.h:36
BranchHandler
bool(* BranchHandler)(ByteReader &)
Type of callback function for branch nodes.
Definition: newgrf.cpp:8319
ClearTemporaryNewGRFData
static void ClearTemporaryNewGRFData(GRFFile *gf)
Reset all NewGRFData that was used only while processing data.
Definition: newgrf.cpp:421
TLF_PALETTE
@ TLF_PALETTE
Add signed offset to palette from register TileLayoutRegisters::palette.
Definition: newgrf_commons.h:37
PTYPE_UINT_ENUM
@ PTYPE_UINT_ENUM
The parameter allows a range of numbers, each of which can have a special name.
Definition: newgrf_config.h:121
_grm_cargoes
static uint32_t _grm_cargoes[NUM_CARGO *2]
Contains the GRF ID of the owner of a cargo if it has been reserved.
Definition: newgrf.cpp:356
PROP_AIRCRAFT_PASSENGER_CAPACITY
@ PROP_AIRCRAFT_PASSENGER_CAPACITY
Passenger Capacity.
Definition: newgrf_properties.h:52
PROP_SHIP_SPEED
@ PROP_SHIP_SPEED
Max. speed: 1 unit = 1/3.2 mph = 0.5 km-ish/h.
Definition: newgrf_properties.h:44
ClearSnowLine
void ClearSnowLine()
Clear the variable snow line table and free the memory.
Definition: landscape.cpp:640
ResetRoadTypes
void ResetRoadTypes()
Reset all road type information to its default values.
Definition: road_cmd.cpp:67
GRFPalette
GRFPalette
Information that can/has to be stored about a GRF's palette.
Definition: newgrf_config.h:59
PROP_ROADVEH_POWER
@ PROP_ROADVEH_POWER
Power in 10 HP.
Definition: newgrf_properties.h:36
GetSnowLine
uint8_t GetSnowLine()
Get the current snow line, either variable or static.
Definition: landscape.cpp:608
RandomizedSpriteGroup
Definition: newgrf_spritegroup.h:190
SkipSpriteData
bool SkipSpriteData(SpriteFile &file, uint8_t type, uint16_t num)
Skip the given amount of sprite graphics data.
Definition: spritecache.cpp:122
IndustrySpec::name
StringID name
Displayed name of the industry.
Definition: industrytype.h:123
IndustryBehaviour
IndustryBehaviour
Various industry behaviours mostly to represent original TTD specialities.
Definition: industrytype.h:55
PROP_TRAIN_COST_FACTOR
@ PROP_TRAIN_COST_FACTOR
Purchase cost (if dualheaded: sum of both vehicles)
Definition: newgrf_properties.h:26
IndustrySpec::new_industry_text
StringID new_industry_text
Message appearing when the industry is built.
Definition: industrytype.h:124
IndustryProductionSpriteGroup::cargo_input
CargoID cargo_input[INDUSTRY_NUM_INPUTS]
Which input cargoes to take from (only cb version 2)
Definition: newgrf_spritegroup.h:275
ByteReader
Class to read from a NewGRF file.
Definition: newgrf.cpp:216
LoadGRFSound
static void LoadGRFSound(size_t offs, SoundEntry *sound)
Load a sound from a file.
Definition: newgrf.cpp:7885
Clamp
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition: math_func.hpp:79
TTDPStringIDToOTTDStringIDMapping
static StringID TTDPStringIDToOTTDStringIDMapping(StringID str)
Perform a mapping from TTDPatch's string IDs to OpenTTD's string IDs, but only for the ones we are aw...
Definition: newgrf.cpp:495
GRFFilePropsBase::grffile
const struct GRFFile * grffile
grf file that introduced this entity
Definition: newgrf_commons.h:312
TranslateTTDPatchCodes
std::string TranslateTTDPatchCodes(uint32_t grfid, uint8_t language_id, bool allow_newlines, std::string_view str, StringControlCode byte80)
Translate TTDPatch string codes into something OpenTTD can handle (better).
Definition: newgrf_text.cpp:236
PROP_AIRCRAFT_SPEED
@ PROP_AIRCRAFT_SPEED
Max. speed: 1 unit = 8 mph = 12.8 km-ish/h.
Definition: newgrf_properties.h:50
CanalProperties
Canal properties local to the NewGRF.
Definition: newgrf.h:40
CargoSpec::town_production_multiplier
uint16_t town_production_multiplier
Town production multipler, if commanded by TownProductionEffect.
Definition: cargotype.h:85
ResetBridges
void ResetBridges()
Reset the data been eventually changed by the grf loaded.
Definition: tunnelbridge_cmd.cpp:86
Utf8Decode
size_t Utf8Decode(char32_t *c, const char *s)
Decode and consume the next UTF-8 encoded character.
Definition: string.cpp:419
AllowedSubtags::data
DataHandler data
Callback function for a binary node, only valid if type == 'B'.
Definition: newgrf.cpp:8388
NUM_CARGO
static const CargoID NUM_CARGO
Maximum number of cargo types in a game.
Definition: cargo_type.h:74
EngineInfo::string_id
StringID string_id
Default name of engine.
Definition: engine_type.h:158
AircraftVehicleInfo
Information about a aircraft vehicle.
Definition: engine_type.h:100
RailTypeFlags
RailTypeFlags
Railtype flags.
Definition: rail.h:35
TileLayoutRegisters::max_sprite_offset
uint16_t max_sprite_offset
Maximum offset to add to the sprite. (limited by size of the spriteset)
Definition: newgrf_commons.h:95
DrawTileSeqStruct::delta_x
int8_t delta_x
0x80 is sequence terminator
Definition: sprite.h:26
NewGRFClass::Get
static NewGRFClass * Get(Tindex class_index)
Get a particular class.
Definition: newgrf_class_func.h:82
PROP_TRAIN_POWER
@ PROP_TRAIN_POWER
Power in hp (if dualheaded: sum of both vehicles)
Definition: newgrf_properties.h:22
AirportTileSpec::Get
static const AirportTileSpec * Get(StationGfx gfx)
Retrieve airport tile spec for the given airport tile.
Definition: newgrf_airporttiles.cpp:37
HouseSpec::min_year
TimerGameCalendar::Year min_year
introduction year of the house
Definition: house.h:95
MemSetT
void MemSetT(T *ptr, uint8_t value, size_t num=1)
Type-safe version of memset().
Definition: mem_func.hpp:49
IndustryOverrideManager::SetEntitySpec
void SetEntitySpec(IndustrySpec *inds)
Method to install the new industry data in its proper slot The slot assignment is internal of this me...
Definition: newgrf_commons.cpp:247
PROP_TRAIN_CARGO_AGE_PERIOD
@ PROP_TRAIN_CARGO_AGE_PERIOD
Number of ticks before carried cargo is aged.
Definition: newgrf_properties.h:30
ResetIndustries
void ResetIndustries()
This function initialize the spec arrays of both industry and industry tiles.
Definition: industry_cmd.cpp:80
PROP_ROADVEH_RUNNING_COST_FACTOR
@ PROP_ROADVEH_RUNNING_COST_FACTOR
Yearly runningcost.
Definition: newgrf_properties.h:33
SPR_TRACKS_FOR_SLOPES_BASE
static const SpriteID SPR_TRACKS_FOR_SLOPES_BASE
Sprites for 'highlighting' tracks on sloped land.
Definition: sprites.h:198
ResultSpriteGroup
Definition: newgrf_spritegroup.h:236
GetCargoTranslation
CargoID GetCargoTranslation(uint8_t cargo, const GRFFile *grffile, bool usebit)
Translate a GRF-local cargo slot/bitnum into a CargoID.
Definition: newgrf_cargo.cpp:79
IndustryTileSpec
Defines the data structure of each individual tile of an industry.
Definition: industrytype.h:148
GRFLoadedFeatures
Definition: newgrf.h:177
TLF_DRAWING_FLAGS
@ TLF_DRAWING_FLAGS
Flags which are still required after loading the GRF.
Definition: newgrf_commons.h:52
TLF_PALETTE_VAR10
@ TLF_PALETTE_VAR10
Resolve palette with a specific value in variable 10.
Definition: newgrf_commons.h:47
InitRailTypes
void InitRailTypes()
Resolve sprites of custom rail types.
Definition: rail_cmd.cpp:130
RailTypeInfo::build_caption
StringID build_caption
Caption of the build vehicle GUI for this rail type.
Definition: rail.h:179
RoadVehicleInfo::max_speed
uint16_t max_speed
Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
Definition: engine_type.h:120
ClrBit
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
Definition: bitmath_func.hpp:151
DisableGrf
static GRFError * DisableGrf(StringID message=STR_NULL, GRFConfig *config=nullptr)
Disable a GRF.
Definition: newgrf.cpp:432
AirportTileSpec::grf_prop
GRFFileProps grf_prop
properties related the the grf file
Definition: newgrf_airporttiles.h:74
TLF_SPRITE_REG_FLAGS
@ TLF_SPRITE_REG_FLAGS
Flags which require resolving the action-1-2-3 chain for the sprite, even if it is no action-1 sprite...
Definition: newgrf_commons.h:61
AirportChangeInfo
static ChangeInfoResult AirportChangeInfo(uint airport, int numinfo, int prop, ByteReader &buf)
Define properties for airports.
Definition: newgrf.cpp:3915
InitRoadTypes
void InitRoadTypes()
Resolve sprites of custom road types.
Definition: road_cmd.cpp:114
RailTypeInfo::acceleration_type
uint8_t acceleration_type
Acceleration type of this rail type.
Definition: rail.h:226
RoadTypeInfo::build_caption
StringID build_caption
Caption of the build vehicle GUI for this rail type.
Definition: road.h:106
GrfProcessingState::skip_sprites
int skip_sprites
Number of pseudo sprites to skip before processing the next one. (-1 to skip to end of file)
Definition: newgrf.cpp:112
RailTypeInfo::replace_text
StringID replace_text
Text used in the autoreplace GUI.
Definition: rail.h:180
OpenCachedSpriteFile
SpriteFile & OpenCachedSpriteFile(const std::string &filename, Subdirectory subdir, bool palette_remap)
Open/get the SpriteFile that is cached for use in the sprite cache.
Definition: spritecache.cpp:93
ResetCustomStations
static void ResetCustomStations()
Reset and clear all NewGRF stations.
Definition: newgrf.cpp:8711
TLF_SPRITE_VAR10
@ TLF_SPRITE_VAR10
Resolve sprite with a specific value in variable 10.
Definition: newgrf_commons.h:46
PROP_AIRCRAFT_RANGE
@ PROP_AIRCRAFT_RANGE
Aircraft range.
Definition: newgrf_properties.h:55
RailTypeInfo::sorting_order
uint8_t sorting_order
The sorting order of this railtype for the toolbar dropdown.
Definition: rail.h:271
EconomySettings::allow_town_roads
bool allow_town_roads
towns are allowed to build roads (always allowed when generating world / in SE)
Definition: settings_type.h:530
GRFFile::cargo_map
std::array< uint8_t, NUM_CARGO > cargo_map
Inverse cargo translation table (CargoID -> local ID)
Definition: newgrf.h:131
BuildLinkStatsLegend
void BuildLinkStatsLegend()
Populate legend table for the link stat view.
Definition: smallmap_gui.cpp:219
EngineDisplayFlags::HasVariants
@ HasVariants
Set if engine has variants.
RoadTypeInfo::introduction_required_roadtypes
RoadTypes introduction_required_roadtypes
Bitmask of roadtypes that are required for this roadtype to be introduced at a given introduction_dat...
Definition: road.h:172
TileIndexDiffC::x
int16_t x
The x value of the coordinate.
Definition: map_type.h:32
newgrf_cargo.h
SetYearEngineAgingStops
void SetYearEngineAgingStops()
Compute the value for _year_engine_aging_stops.
Definition: engine.cpp:657
GRFFile::railtype_list
std::vector< RailTypeLabel > railtype_list
Railtype translation table.
Definition: newgrf.h:133
RandomizedSpriteGroup::groups
std::vector< const SpriteGroup * > groups
Take the group with appropriate index:
Definition: newgrf_spritegroup.h:201
TAE_GOODS
@ TAE_GOODS
Cargo behaves goods/candy-like.
Definition: cargotype.h:26
RailVehicleChangeInfo
static ChangeInfoResult RailVehicleChangeInfo(uint engine, int numinfo, int prop, ByteReader &buf)
Define properties for rail vehicles.
Definition: newgrf.cpp:1052
CC_ARMOURED
@ CC_ARMOURED
Armoured cargo (Valuables, Gold, Diamonds)
Definition: cargotype.h:53
StationSpec::cargo_triggers
CargoTypes cargo_triggers
Bitmask of cargo types which cause trigger re-randomizing.
Definition: newgrf_station.h:157
SpriteGroup
Definition: newgrf_spritegroup.h:57
GRFLabel
Definition: newgrf.h:99
SPR_ONEWAY_BASE
static const SpriteID SPR_ONEWAY_BASE
One way road sprites.
Definition: sprites.h:293
HouseSpec::grf_prop
GRFFileProps grf_prop
Properties related the the grf file.
Definition: house.h:110
CargoSpec::multiplier
uint16_t multiplier
Capacity multiplier for vehicles. (8 fractional bits)
Definition: cargotype.h:77
GRFFilePropsBase::spritegroup
std::array< const struct SpriteGroup *, Tcnt > spritegroup
pointers to the different sprites of the entity
Definition: newgrf_commons.h:313
ResetGenericCallbacks
void ResetGenericCallbacks()
Reset all generic feature callback sprite groups.
Definition: newgrf_generic.cpp:94
Action5Type
Information about a single action 5 type.
Definition: newgrf_act5.h:21
EngineInfo::base_intro
TimerGameCalendar::Date base_intro
Basic date of engine introduction (without random parts).
Definition: engine_type.h:145
SkipUnknownInfo
static bool SkipUnknownInfo(ByteReader &buf, uint8_t type)
Try to skip the current node and all subnodes (if it's a branch node).
Definition: newgrf.cpp:8509
EngineInfo::lifelength
TimerGameCalendar::Year lifelength
Lifetime of a single vehicle.
Definition: engine_type.h:146
BridgeChangeInfo
static ChangeInfoResult BridgeChangeInfo(uint brid, int numinfo, int prop, ByteReader &buf)
Define properties for bridges.
Definition: newgrf.cpp:2242
SetEngineGRF
void SetEngineGRF(EngineID engine, const GRFFile *file)
Tie a GRFFile entry to an engine, to allow us to retrieve GRF parameters etc during a game.
Definition: newgrf_engine.cpp:71
IsGRMReservedSprite
static bool IsGRMReservedSprite(SpriteID first_sprite, uint16_t num_sprites)
Check if a sprite ID range is within the GRM reversed range for the currently loading NewGRF.
Definition: newgrf.cpp:7070
OrderSettings::gradual_loading
bool gradual_loading
load vehicles gradually
Definition: settings_type.h:482
AddGRFTextToList
static void AddGRFTextToList(GRFTextList &list, uint8_t langid, std::string_view text_to_add)
Add a new text to a GRFText list.
Definition: newgrf_text.cpp:485
Action5Type::min_sprites
uint16_t min_sprites
If the Action5 contains less sprites, the whole block will be ignored.
Definition: newgrf_act5.h:24
ChangeGRFMinVersion
static bool ChangeGRFMinVersion(size_t len, ByteReader &buf)
Callback function for 'INFO'->'MINV' to the minimum compatible version of the NewGRF.
Definition: newgrf.cpp:8209
AddGRFString
StringID AddGRFString(uint32_t grfid, uint16_t stringid, uint8_t langid_to_add, bool new_scheme, bool allow_newlines, std::string_view text_to_add, StringID def_string)
Add the new read string into our structure.
Definition: newgrf_text.cpp:543
GCF_STATIC
@ GCF_STATIC
GRF file is used statically (can be used in any MP game)
Definition: newgrf_config.h:25
NewGRFSpriteLayout::Allocate
void Allocate(uint num_sprites)
Allocate a spritelayout for num_sprites building sprites.
Definition: newgrf_commons.cpp:609
IndustryLifeType
IndustryLifeType
Available types of industry lifetimes.
Definition: industrytype.h:22
GRFFile
Dynamic data of a loaded NewGRF.
Definition: newgrf.h:108
PROP_TRAIN_USER_DATA
@ PROP_TRAIN_USER_DATA
User defined data for vehicle variable 0x42.
Definition: newgrf_properties.h:29
Engine::type
VehicleType type
Vehicle type, ie VEH_ROAD, VEH_TRAIN, etc.
Definition: engine_base.h:56
LoadTranslationTable
static ChangeInfoResult LoadTranslationTable(uint gvid, int numinfo, ByteReader &buf, std::vector< T > &translation_table, const char *name)
Load a cargo- or railtype-translation table.
Definition: newgrf.cpp:2699
debug.h
OverrideManagerBase::GetID
virtual uint16_t GetID(uint16_t grf_local_id, uint32_t grfid) const
Return the ID (if ever available) of a previously inserted entity.
Definition: newgrf_commons.cpp:90
_grm_engines
static uint32_t _grm_engines[256]
Contains the GRF ID of the owner of a vehicle if it has been reserved.
Definition: newgrf.cpp:353
TileLayoutSpriteGroup
Action 2 sprite layout for houses, industry tiles, objects and airport tiles.
Definition: newgrf_spritegroup.h:260
SkipAct12
static void SkipAct12(ByteReader &buf)
Action 0x12 (SKIP)
Definition: newgrf.cpp:8036
TAE_FOOD
@ TAE_FOOD
Cargo behaves food/fizzy-drinks-like.
Definition: cargotype.h:28
GetGlobalVariable
bool GetGlobalVariable(uint8_t param, uint32_t *value, const GRFFile *grffile)
Reads a variable common to VarAction2 and Action7/9/D.
Definition: newgrf.cpp:6539
VSG_SCOPE_RELATIVE
@ VSG_SCOPE_RELATIVE
Relative position (vehicles only)
Definition: newgrf_spritegroup.h:102
GRFConfig::GetName
const char * GetName() const
Get the name of this grf.
Definition: newgrf_config.cpp:98
NamePart::prob
uint8_t prob
The relative probability of the following name to appear in the bottom 7 bits.
Definition: newgrf_townname.h:21
BridgeSpec::max_length
uint16_t max_length
the maximum length (not counting start and end tile)
Definition: bridge.h:45
PROP_ROADVEH_WEIGHT
@ PROP_ROADVEH_WEIGHT
Weight in 1/4 t.
Definition: newgrf_properties.h:37
SPR_TRAMWAY_BASE
static const SpriteID SPR_TRAMWAY_BASE
Tramway sprites.
Definition: sprites.h:272
engine_func.h
AddGenericCallback
void AddGenericCallback(uint8_t feature, const GRFFile *file, const SpriteGroup *group)
Add a generic feature callback sprite group to the appropriate feature list.
Definition: newgrf_generic.cpp:108
EC_MONORAIL
@ EC_MONORAIL
Mono rail engine.
Definition: engine_type.h:37
GRFError::data
std::string data
Additional data for message and custom_message.
Definition: newgrf_config.h:113
WaterFeature::group
const SpriteGroup * group
Sprite group to start resolving.
Definition: newgrf_canal.h:23
TimerGameCalendar::year
static Year year
Current year, starting at 0.
Definition: timer_game_calendar.h:32
DrawTileSeqStruct
A tile child sprite and palette to draw for stations etc, with 3D bounding box.
Definition: sprite.h:25
TileLayoutRegisters::palette_var10
uint8_t palette_var10
Value for variable 10 when resolving the palette.
Definition: newgrf_commons.h:102
HouseOverrideManager::SetEntitySpec
void SetEntitySpec(const HouseSpec *hs)
Install the specs into the HouseSpecs array It will find itself the proper slot on which it will go.
Definition: newgrf_commons.cpp:159
ChangeGRFParamType
static bool ChangeGRFParamType(size_t len, ByteReader &buf)
Callback function for 'INFO'->'PARAM'->param_num->'TYPE' to set the typeof a parameter.
Definition: newgrf.cpp:8245
backup_type.hpp
StringIDMapping::grfid
uint32_t grfid
Source NewGRF.
Definition: newgrf.cpp:457
HZ_ZONALL
@ HZ_ZONALL
1F This is just to englobe all above types at once
Definition: house.h:73
GRFFile::grf_features
uint32_t grf_features
Bitset of GrfSpecFeature the grf uses.
Definition: newgrf.h:149
TimerGameEconomy::date
static Date date
Current date in days (day counter).
Definition: timer_game_economy.h:37
SNOW_LINE_MONTHS
static const uint SNOW_LINE_MONTHS
Number of months in the snow line table.
Definition: landscape.h:16
CargoSpec::town_acceptance_effect
TownAcceptanceEffect town_acceptance_effect
The effect that delivering this cargo type has on towns. Also affects destination of subsidies.
Definition: cargotype.h:83
GRFP_BLT_MASK
@ GRFP_BLT_MASK
Bitmask to only get the blitter information.
Definition: newgrf_config.h:78
FindFirstBit
constexpr uint8_t FindFirstBit(T x)
Search the first set bit in a value.
Definition: bitmath_func.hpp:213
HasBit
constexpr debug_inline bool HasBit(const T x, const uint8_t y)
Checks if a bit in a value is set.
Definition: bitmath_func.hpp:103